dsh-progress-union 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +150 -3
- package/client.js +2330 -0
- package/cordis.patch.yml +4 -0
- package/docs/slot-models-comparison.md +23 -0
- package/docs/slot-trail-fanout.md +31 -0
- package/docs/spirit-reference.md +38 -0
- package/dsh.plugin.json +16 -0
- package/icon.svg +7 -0
- package/index.js +2148 -0
- package/package.json +58 -6
package/index.js
ADDED
|
@@ -0,0 +1,2148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-progress-union — host half.
|
|
3
|
+
*
|
|
4
|
+
* 结合原型:
|
|
5
|
+
* - 槽位真相源 fork 自 l3j3y3/dsh-progress-board (MIT):per-session 扁平任务板、
|
|
6
|
+
* revision 补丁 API、`progress_update` 增量工具、policy/user-edits/kickoff 三块
|
|
7
|
+
* 每请求重建的投影注入。
|
|
8
|
+
* - 时间/ETA 引擎 fork 自 uuhihj/task-progress-bar dsh-progress-widget (MIT):
|
|
9
|
+
* 事件驱动 (turn/step/todo/subagent) 的步数与耗时统计、ETA 先验 + 本机学习、
|
|
10
|
+
* `$DSH_HOME/dsh-progress-stats.json` 样本沿用不迁移。
|
|
11
|
+
* - 新增 progressAnchor 只读锚点平面:board(语义) / time(时间) / userEdits(未确认
|
|
12
|
+
* 用户改动) 三层,service + HTTP 双平面同一 builder,供压缩插件在压缩前取用。
|
|
13
|
+
* 契约见 README「给压缩插件的锚点契约」。
|
|
14
|
+
*
|
|
15
|
+
* 单协议收敛:board 启用的会话不再注入鲸程的文件上报协议(progress_update 是唯一
|
|
16
|
+
* 写通道);板关闭时文件上报层与 /dsh-progress/status 兼容原样保留。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs'
|
|
20
|
+
import os from 'node:os'
|
|
21
|
+
import path from 'node:path'
|
|
22
|
+
|
|
23
|
+
// —— 路由与存储标识 ——
|
|
24
|
+
const ROUTE_BASE = '/progress-union'
|
|
25
|
+
const LEGACY_BASE = '/progress-board' // 别名保留一版,与 board 原面板/脚本兼容
|
|
26
|
+
const WIDGET_STATUS_ROUTE = '/dsh-progress/status'
|
|
27
|
+
const UNIT_NAME = 'progress_union'
|
|
28
|
+
const ANCHOR_VERSION = 1
|
|
29
|
+
|
|
30
|
+
// —— board 侧限额(fork 原值,不放宽)——
|
|
31
|
+
const MAX_BODY_BYTES = 256 * 1024
|
|
32
|
+
const MAX_ITEMS = 200
|
|
33
|
+
const MAX_CHANGES = 50
|
|
34
|
+
const MAX_USER_CHANGES = 80
|
|
35
|
+
const MAX_TITLE = 180
|
|
36
|
+
const MAX_TEXT = 600
|
|
37
|
+
const MAX_APPROACH = 2000
|
|
38
|
+
const MAX_NOTE = 1600
|
|
39
|
+
const MAX_GROUP = 80
|
|
40
|
+
const STALE_MS = 10 * 60 * 1000
|
|
41
|
+
const KICKOFF_COOLDOWN_MS = 60 * 1000
|
|
42
|
+
const STATUSES = new Set(['todo', 'doing', 'done', 'blocked'])
|
|
43
|
+
|
|
44
|
+
// —— widget 侧时间与统计(DSH_HOME 与鲸程共文件,样本不迁移)——
|
|
45
|
+
const DSH_HOME = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
46
|
+
const PROGRESS_FILE = path.join(DSH_HOME, 'dsh-progress.json')
|
|
47
|
+
const PROGRESS_DIR = path.join(DSH_HOME, 'dsh-progress')
|
|
48
|
+
const PROGRESS_DIR_KEEP_MS = 24 * 60 * 60 * 1000
|
|
49
|
+
const STATS_FILE = path.join(DSH_HOME, 'dsh-progress-stats.json')
|
|
50
|
+
const STATS_MAX = 400
|
|
51
|
+
const IDLE_END_MS = 10 * 60 * 1000 // 兜底:turn 打开但 10 分钟无活动视为卡死结束
|
|
52
|
+
const FILE_STALE_MS = 2 * 60 * 1000 // 上报/板数据 2 分钟未更新视为陈旧
|
|
53
|
+
const SWEEP_MS = 4000
|
|
54
|
+
const BAD_READ_GRACE_MS = 2000
|
|
55
|
+
|
|
56
|
+
export const name = 'dsh-progress-union'
|
|
57
|
+
export const inject = ['tools', 'systemPrompt', 'webServer', 'agents']
|
|
58
|
+
|
|
59
|
+
const PROGRESS_POLICY = `## 进度板
|
|
60
|
+
progress_update 维护用户可见的实时进度板。每项含 title/status/percent/current/next/approach/note。
|
|
61
|
+
- 每个用户回合开始时先检查进度板:如果板是空的,你的第一个工具调用必须是 progress_update,先建立扁平任务,再执行任何其他工具。不要等做完才补计划。
|
|
62
|
+
- 每个用户回合至少调用一次 progress_update:这条消息是新任务就先增补任务(第一项设为 doing),不是新任务就传 changes=[] 确认。上一轮的任务已全部完成时同样要这样做,不要整回合都不碰进度板。
|
|
63
|
+
- 准备开始一项任务时先把该项设为 doing,current 写正在准备/做什么;完成时立即设为 done;若还有下一步,把下一条设为 doing。除每回合的确认调用外,只在完成任务、状态/百分比实质变化、思路转向或应用用户改动时更新;只发变化项,不重发整份计划。
|
|
64
|
+
- 用户每发来一段新的需求或反馈,先判断是否新任务;若是,在该回合开头新增/调整任务,再动手。
|
|
65
|
+
- 用户改动会以“进度板用户改动”注入,只含变化字段;以它为准,处理完传 ackUserRevision。
|
|
66
|
+
- 聊天只说明推进、下一步和待决策点,不复述整份计划。
|
|
67
|
+
|
|
68
|
+
## 提问
|
|
69
|
+
禁止猜。只有三类立即停:不可逆/高后果;目标根本歧义且在前 10%;需要价值判断或策略取舍。
|
|
70
|
+
其余采用可逆默认并标注假设;只有答案会显著改变路径、且至少两个维度各有三种合理解读时才问。
|
|
71
|
+
输入/约束澄清最晚约 50%,任何澄清不拖到中后段。每任务最多 2 轮、每轮最多 3 问;选项化、给推荐默认、先复述理解。问前把相关任务标 blocked 并写清等什么。`
|
|
72
|
+
|
|
73
|
+
// 辅助 LLM(审查/监视)的 system prompt:只允许"描述现状 + 校准百分比",禁止增删/改状态。
|
|
74
|
+
const ASSISTANT_SYSTEM = 'You are a progress auditor for a task board. Given the board checklist and the recent assistant output / tool activity / file changes, ' +
|
|
75
|
+
'update ONLY per-item current/next/percent so the board matches reality. ' +
|
|
76
|
+
'Never add, remove, retitle, or change the status of an item. ' +
|
|
77
|
+
'Output strictly one JSON object: {"changes":[{"id":"<existing id>","current"?:"...","next"?:"...","percent"?:0-100}],"note":"<one line audit verdict>"}. ' +
|
|
78
|
+
'If nothing needs updating, output {"changes":[],"note":"<why>"}.'
|
|
79
|
+
|
|
80
|
+
// ============================================================================
|
|
81
|
+
// 通用工具(board fork)
|
|
82
|
+
// ============================================================================
|
|
83
|
+
|
|
84
|
+
function isObject(value) {
|
|
85
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function clone(value) {
|
|
89
|
+
return JSON.parse(JSON.stringify(value))
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function text(value, max) {
|
|
93
|
+
if (typeof value !== 'string') return undefined
|
|
94
|
+
return value.trim().slice(0, max)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function finiteNumber(value) {
|
|
98
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function sessionKey(sessionId) {
|
|
102
|
+
return Buffer.from(sessionId, 'utf8').toString('base64url')
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function emptyState(sessionId) {
|
|
106
|
+
const now = Date.now()
|
|
107
|
+
return {
|
|
108
|
+
version: 1,
|
|
109
|
+
sessionId,
|
|
110
|
+
revision: 0,
|
|
111
|
+
userRevision: 0,
|
|
112
|
+
agentSeenRevision: 0,
|
|
113
|
+
enabled: false,
|
|
114
|
+
createdAt: now,
|
|
115
|
+
updatedAt: now,
|
|
116
|
+
items: [],
|
|
117
|
+
userChanges: [],
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function newItemId() {
|
|
122
|
+
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function summarize(items) {
|
|
126
|
+
const total = items.length
|
|
127
|
+
const counts = { done: 0, doing: 0, todo: 0, blocked: 0 }
|
|
128
|
+
let sum = 0
|
|
129
|
+
for (const item of items) {
|
|
130
|
+
counts[item.status] += 1
|
|
131
|
+
sum += item.percent
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
total,
|
|
135
|
+
done: counts.done,
|
|
136
|
+
doing: counts.doing,
|
|
137
|
+
todo: counts.todo,
|
|
138
|
+
blocked: counts.blocked,
|
|
139
|
+
percent: total === 0 ? 0 : Math.round(sum / total),
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function normalizeItems(items) {
|
|
144
|
+
items.sort((a, b) => a.order - b.order || a.updatedAt - b.updatedAt || a.id.localeCompare(b.id))
|
|
145
|
+
items.forEach((item, index) => {
|
|
146
|
+
item.order = index
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function itemView(item) {
|
|
151
|
+
return {
|
|
152
|
+
id: item.id,
|
|
153
|
+
title: item.title,
|
|
154
|
+
status: item.status,
|
|
155
|
+
percent: item.percent,
|
|
156
|
+
current: item.current,
|
|
157
|
+
next: item.next,
|
|
158
|
+
approach: item.approach || '',
|
|
159
|
+
note: item.note,
|
|
160
|
+
group: item.group,
|
|
161
|
+
order: item.order,
|
|
162
|
+
updatedAt: item.updatedAt,
|
|
163
|
+
updatedBy: item.updatedBy,
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function compactValue(value) {
|
|
168
|
+
if (value === undefined) return null
|
|
169
|
+
if (typeof value === 'string' && value.length > 240) return `${value.slice(0, 240)}…`
|
|
170
|
+
return value
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function fieldLabel(field) {
|
|
174
|
+
return (
|
|
175
|
+
{
|
|
176
|
+
title: '标题',
|
|
177
|
+
status: '状态',
|
|
178
|
+
percent: '百分比',
|
|
179
|
+
current: '当前动作',
|
|
180
|
+
next: '下一步',
|
|
181
|
+
approach: '思路与实现',
|
|
182
|
+
note: '备注',
|
|
183
|
+
group: '分组',
|
|
184
|
+
order: '顺序',
|
|
185
|
+
}[field] || field
|
|
186
|
+
)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function describeChange(change) {
|
|
190
|
+
if (change.kind === 'add') {
|
|
191
|
+
const details = (change.fields || [])
|
|
192
|
+
.filter((field) => field.field !== 'order')
|
|
193
|
+
.map((field) => `${fieldLabel(field.field)}=${JSON.stringify(compactValue(field.to))}`)
|
|
194
|
+
.join(',')
|
|
195
|
+
return `- [${change.itemId}] 新增任务「${change.title}」${details ? `(${details})` : ''}`
|
|
196
|
+
}
|
|
197
|
+
if (change.kind === 'remove') {
|
|
198
|
+
return `- [${change.itemId}] 删除任务「${change.title}」`
|
|
199
|
+
}
|
|
200
|
+
const fields = (change.fields || [])
|
|
201
|
+
.filter((field) => field.field !== 'order')
|
|
202
|
+
.map(
|
|
203
|
+
(field) =>
|
|
204
|
+
`${fieldLabel(field.field)}:${JSON.stringify(compactValue(field.from))} → ${JSON.stringify(compactValue(field.to))}`,
|
|
205
|
+
)
|
|
206
|
+
.join(';')
|
|
207
|
+
return `- [${change.itemId}] 「${change.title}」${fields ? `:${fields}` : ''}`
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ============================================================================
|
|
211
|
+
// 时间引擎工具(widget fork;仅 board 关闭的回落路径才用关键词猜测)
|
|
212
|
+
// ============================================================================
|
|
213
|
+
|
|
214
|
+
function readJsonText(file) {
|
|
215
|
+
// 去 BOM:PowerShell 5.1 写出的 efbbbf 会让 JSON.parse 直接抛——表现为"文件明明在读不到"。
|
|
216
|
+
return fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const lastGoodByKey = new Map()
|
|
220
|
+
let lastGoodAt = 0
|
|
221
|
+
|
|
222
|
+
function parseProgressFile(file, key) {
|
|
223
|
+
try {
|
|
224
|
+
const parsed = JSON.parse(readJsonText(file))
|
|
225
|
+
if (parsed && typeof parsed === 'object' && typeof parsed.task === 'string' && Array.isArray(parsed.stages)) {
|
|
226
|
+
lastGoodByKey.set(key, parsed)
|
|
227
|
+
lastGoodAt = Date.now()
|
|
228
|
+
return parsed
|
|
229
|
+
}
|
|
230
|
+
} catch (err) {
|
|
231
|
+
// 只在"文件存在但读坏了"时兜底;文件被删要立刻消失(与鲸程行为一致)
|
|
232
|
+
if (err && err.code !== 'ENOENT') {
|
|
233
|
+
const prev = lastGoodByKey.get(key)
|
|
234
|
+
if (prev && Date.now() - lastGoodAt < BAD_READ_GRACE_MS) return prev
|
|
235
|
+
}
|
|
236
|
+
lastGoodByKey.delete(key)
|
|
237
|
+
}
|
|
238
|
+
return null
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// 鲸程兼容层:读 $DSH_HOME/dsh-progress/<sid>.json 上报(板关闭时的增强层)。
|
|
242
|
+
function readFileTasks() {
|
|
243
|
+
const out = []
|
|
244
|
+
let names = []
|
|
245
|
+
try {
|
|
246
|
+
names = fs.readdirSync(PROGRESS_DIR).filter((n) => n.endsWith('.json'))
|
|
247
|
+
} catch (_err) {
|
|
248
|
+
names = []
|
|
249
|
+
}
|
|
250
|
+
for (const name of names) {
|
|
251
|
+
const full = path.join(PROGRESS_DIR, name)
|
|
252
|
+
const parsed = parseProgressFile(full, full)
|
|
253
|
+
if (parsed) out.push({ ...parsed, reportId: parsed.session ? String(parsed.session) : name.replace(/\.json$/, ''), source: 'dir' })
|
|
254
|
+
}
|
|
255
|
+
// 24 小时未更新的分文件顺手清理(活跃会话个位数,逐次 stat 可忽略)
|
|
256
|
+
for (const name of names) {
|
|
257
|
+
const full = path.join(PROGRESS_DIR, name)
|
|
258
|
+
try {
|
|
259
|
+
const st = fs.statSync(full)
|
|
260
|
+
if (Date.now() - st.mtimeMs > PROGRESS_DIR_KEEP_MS) {
|
|
261
|
+
fs.unlinkSync(full)
|
|
262
|
+
lastGoodByKey.delete(full)
|
|
263
|
+
}
|
|
264
|
+
} catch (_err) {}
|
|
265
|
+
}
|
|
266
|
+
const legacy = parseProgressFile(PROGRESS_FILE, PROGRESS_FILE)
|
|
267
|
+
if (legacy) out.push({ ...legacy, reportId: legacy.session ? String(legacy.session) : 'legacy', source: 'legacy' })
|
|
268
|
+
return out
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function textOf(msg) {
|
|
272
|
+
try {
|
|
273
|
+
if (!msg) return ''
|
|
274
|
+
if (Array.isArray(msg.content)) {
|
|
275
|
+
return msg.content
|
|
276
|
+
.filter((b) => b && b.type === 'text' && typeof b.text === 'string')
|
|
277
|
+
.map((b) => b.text)
|
|
278
|
+
.join(' ')
|
|
279
|
+
.trim()
|
|
280
|
+
}
|
|
281
|
+
if (typeof msg.content === 'string') return msg.content.trim()
|
|
282
|
+
return ''
|
|
283
|
+
} catch (_err) {
|
|
284
|
+
return ''
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const TITLE_MAP = [
|
|
289
|
+
[/修|bug|报错|错误|不行|失败|坏了|出问题|异常|打不开/, '问题修复'],
|
|
290
|
+
[/开发|实现|做|写|加一个|新增|功能|插件|脚本|搭|改|修改|优化|完善/, '功能开发'],
|
|
291
|
+
[/为什么|原因|分析|查|排查|看看|看一下/, '问题分析'],
|
|
292
|
+
[/整理|分类|移动|清理|重命名|归档|归纳/, '文件整理'],
|
|
293
|
+
[/安装|部署|配置|接入/, '安装部署'],
|
|
294
|
+
[/测试|验证|检查|试用/, '测试验证'],
|
|
295
|
+
[/总结|回顾|复盘/, '总结'],
|
|
296
|
+
[/方案|建议|怎么办|怎么弄|如何|怎么处理|给点/, '方案咨询'],
|
|
297
|
+
[/\b(fix|bug|error|broken|crash|fail(ed|ure)?)\b/i, '问题修复'],
|
|
298
|
+
[/\b(implement|add|build|create|feature|write|refactor)\b/i, '功能开发'],
|
|
299
|
+
[/\b(why|analy[sz]e|investigate|check|debug|look into|figure out)\b/i, '问题分析'],
|
|
300
|
+
[/\b(clean|organi[sz]e|sort|move|rename|archive)\b/i, '文件整理'],
|
|
301
|
+
[/\b(install|deploy|setup|configure|migrate)\b/i, '安装部署'],
|
|
302
|
+
[/\b(test|verify|validate|smoke)\b/i, '测试验证'],
|
|
303
|
+
[/\b(summary|summari[sz]e|retro|retrospective|review)\b/i, '总结'],
|
|
304
|
+
[/\b(plan|proposal|approach|options|how (do|to))\b/i, '方案咨询'],
|
|
305
|
+
]
|
|
306
|
+
|
|
307
|
+
function summarizeTitle(text) {
|
|
308
|
+
const raw = String(text || '').trim()
|
|
309
|
+
if (!raw) return '新任务'
|
|
310
|
+
for (const [re, label] of TITLE_MAP) {
|
|
311
|
+
if (re.test(raw)) return label
|
|
312
|
+
}
|
|
313
|
+
let t = raw
|
|
314
|
+
t = t.replace(/^(请你帮我|请你|帮我|麻烦你|麻烦|请|帮我一下|帮忙|能不能|可不可以|你给我|你帮我|你来|给我|你觉得|你怎么|你告诉我|那你|那你觉得|我想|我要)/, '')
|
|
315
|
+
t = t.replace(/[。!!??\s,,]+$/, '')
|
|
316
|
+
t = t.trim()
|
|
317
|
+
if (!t) return '新任务'
|
|
318
|
+
const stop = t.search(/[。!!??]/)
|
|
319
|
+
if (stop > 0) t = t.slice(0, stop)
|
|
320
|
+
if (t.length > 20) {
|
|
321
|
+
if (/^[\x20-\x7E]*$/.test(t)) {
|
|
322
|
+
const cut = t.slice(0, 20)
|
|
323
|
+
const sp = cut.lastIndexOf(' ')
|
|
324
|
+
t = (sp > 8 ? cut.slice(0, sp) : cut).trim() + '…'
|
|
325
|
+
} else {
|
|
326
|
+
t = t.slice(0, 20) + '…'
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return t
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// 子智能体任务名不走 TITLE_MAP 归类(否则全叫"问题修复"分不清谁是谁),优先派发 label。
|
|
333
|
+
function summarizeSubTitle(text) {
|
|
334
|
+
const raw = String(text || '').replace(/\s+/g, ' ').trim()
|
|
335
|
+
if (!raw) return '子任务'
|
|
336
|
+
let t = raw.replace(/^(请你帮我|请你|帮我|麻烦你|麻烦|请|帮我一下|帮忙|能不能|可不可以|你给我|你帮我|你来|给我)/, '').trim()
|
|
337
|
+
const stop = t.search(/[。!!??\n]/)
|
|
338
|
+
if (stop > 0) t = t.slice(0, stop)
|
|
339
|
+
if (t.length > 24) t = t.slice(0, 24) + '…'
|
|
340
|
+
return t || '子任务'
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// 自动阶段模板:仅 board 关闭时兜底显示(标注"自动估计"),锚点不吃这条。
|
|
344
|
+
function guessStages(text) {
|
|
345
|
+
const t = String(text || '')
|
|
346
|
+
if (/修|bug|报错|错误|不行|失败|异常|打不开/.test(t)) return ['定位问题', '实施修复', '验证结果']
|
|
347
|
+
if (/开发|实现|功能|插件|脚本|新增|搭建/.test(t)) return ['实现', '验证', '收尾']
|
|
348
|
+
if (/为什么|原因|分析|排查|查|看看/.test(t)) return ['收集信息', '分析原因', '给出结论']
|
|
349
|
+
if (/整理|分类|清理|移动|归档|归纳/.test(t)) return ['盘点现状', '分类处理', '校验交付']
|
|
350
|
+
if (/方案|建议|怎么办|怎么弄|如何/.test(t)) return ['分析需求', '拟定方案', '交付方案']
|
|
351
|
+
if (/安装|部署|配置|接入/.test(t)) return ['准备', '执行安装', '验证生效']
|
|
352
|
+
return ['处理中', '收尾']
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// 内置先验:1481 个真实 turn 实测,"跑到第 N 步时之后通常还要多久(秒)"。
|
|
356
|
+
const ETA_PRIOR = [
|
|
357
|
+
[1, 2, 66, 234],
|
|
358
|
+
[2, 3, 55, 240],
|
|
359
|
+
[3, 5, 60, 300],
|
|
360
|
+
[5, 10, 72, 294],
|
|
361
|
+
[10, 16, 66, 306],
|
|
362
|
+
[16, 26, 138, 618],
|
|
363
|
+
[26, Infinity, 186, 618],
|
|
364
|
+
]
|
|
365
|
+
|
|
366
|
+
function priorFor(step) {
|
|
367
|
+
const s = Math.max(1, Math.floor(Number(step) || 1))
|
|
368
|
+
for (const r of ETA_PRIOR) if (s >= r[0] && s < r[1]) return { p50: r[2], p75: r[3] }
|
|
369
|
+
return { p50: 180, p75: 900 }
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
let statsCache = null
|
|
373
|
+
let statsDirty = false
|
|
374
|
+
let statsLastWrite = 0
|
|
375
|
+
|
|
376
|
+
function loadStats() {
|
|
377
|
+
if (statsCache) return statsCache
|
|
378
|
+
try {
|
|
379
|
+
const p = JSON.parse(fs.readFileSync(STATS_FILE, 'utf8'))
|
|
380
|
+
statsCache = p && Array.isArray(p.samples)
|
|
381
|
+
? p.samples.filter((x) => x && isFinite(x.s) && isFinite(x.r)).slice(-STATS_MAX)
|
|
382
|
+
: []
|
|
383
|
+
} catch (_err) {
|
|
384
|
+
statsCache = []
|
|
385
|
+
}
|
|
386
|
+
return statsCache
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// 本机样本够 20 条/桶就用本机分位数,否则退回内置先验。
|
|
390
|
+
function learnedFor(step) {
|
|
391
|
+
try {
|
|
392
|
+
const s = Math.max(1, Math.floor(Number(step) || 1))
|
|
393
|
+
const bucket = ETA_PRIOR.find((r) => s >= r[0] && s < r[1])
|
|
394
|
+
if (!bucket) return null
|
|
395
|
+
const arr = loadStats()
|
|
396
|
+
.filter((x) => x.s >= bucket[0] && x.s < bucket[1])
|
|
397
|
+
.map((x) => x.r)
|
|
398
|
+
.sort((a, b) => a - b)
|
|
399
|
+
if (arr.length < 20) return null
|
|
400
|
+
return { p50: arr[Math.floor(arr.length * 0.5)], p75: arr[Math.floor(arr.length * 0.75)], n: arr.length }
|
|
401
|
+
} catch (_err) {
|
|
402
|
+
return null
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function recordSamples(rows) {
|
|
407
|
+
if (!Array.isArray(rows) || !rows.length) return
|
|
408
|
+
const all = loadStats()
|
|
409
|
+
for (const r of rows) all.push(r)
|
|
410
|
+
while (all.length > STATS_MAX) all.shift()
|
|
411
|
+
statsCache = all
|
|
412
|
+
statsDirty = true
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function flushStats() {
|
|
416
|
+
if (!statsDirty) return
|
|
417
|
+
const now = Date.now()
|
|
418
|
+
if (now - statsLastWrite < 15000) return
|
|
419
|
+
statsLastWrite = now
|
|
420
|
+
statsDirty = false
|
|
421
|
+
try {
|
|
422
|
+
const tmp = STATS_FILE + '.tmp'
|
|
423
|
+
fs.writeFileSync(tmp, JSON.stringify({ version: 1, updatedAt: now, samples: statsCache }))
|
|
424
|
+
fs.renameSync(tmp, STATS_FILE)
|
|
425
|
+
} catch (_err) {}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// ============================================================================
|
|
429
|
+
// apply
|
|
430
|
+
// ============================================================================
|
|
431
|
+
|
|
432
|
+
const DEFAULT_CONFIG = {
|
|
433
|
+
protocolHint: true, // 板关闭会话的文件上报协议注入开关
|
|
434
|
+
pollMs: 1000,
|
|
435
|
+
doneHoldMs: 30000,
|
|
436
|
+
doneKeepMs: 120000,
|
|
437
|
+
maxTasks: 64,
|
|
438
|
+
// 观察者(给主工作模型看"最近输出+清单",板滞后就及时补/催)
|
|
439
|
+
observer: {
|
|
440
|
+
enabled: true,
|
|
441
|
+
maxIdleSteps: 6, // 模型超过 N 步未写板 → 观察块升级为催办
|
|
442
|
+
maxIdleMs: 3 * 60 * 1000, // 或超过 N 毫秒未写板
|
|
443
|
+
autoSyncCurrent: true, // 观察者本人用事实性最近动作自动刷 doing 项的 current
|
|
444
|
+
autoSyncThrottleMs: 60 * 1000,
|
|
445
|
+
maxOutputs: 2,
|
|
446
|
+
maxTools: 3,
|
|
447
|
+
maxItems: 12,
|
|
448
|
+
},
|
|
449
|
+
// 辅助 LLM(审查/监视进度):直连 OpenAI 兼容端点,默认关。只允许改
|
|
450
|
+
// current/next/percent(命题→校验→落地),不增删任务、不改 title/status。
|
|
451
|
+
// 宿主通道暂无纯 chat 调用面,故只支持 direct;建议指向本地/局域网自建端点。
|
|
452
|
+
assistant: {
|
|
453
|
+
mode: '', // '' 关 | 'direct'
|
|
454
|
+
baseUrl: '',
|
|
455
|
+
apiKey: '',
|
|
456
|
+
model: '',
|
|
457
|
+
timeoutMs: 20_000,
|
|
458
|
+
minIntervalMs: 90_000,
|
|
459
|
+
maxCallsPerTurn: 1,
|
|
460
|
+
autoApply: true,
|
|
461
|
+
},
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
export async function apply(ctx, config) {
|
|
465
|
+
const cfg = Object.assign({}, DEFAULT_CONFIG, config && typeof config === 'object' ? config : {})
|
|
466
|
+
cfg.observer = Object.assign({}, DEFAULT_CONFIG.observer, cfg.observer && typeof cfg.observer === 'object' ? cfg.observer : {})
|
|
467
|
+
cfg.assistant = Object.assign({}, DEFAULT_CONFIG.assistant, cfg.assistant && typeof cfg.assistant === 'object' ? cfg.assistant : {})
|
|
468
|
+
const now = () => Date.now()
|
|
469
|
+
|
|
470
|
+
// —— 状态容器 ——
|
|
471
|
+
const states = new Map() // sessionId -> board state(槽位真相源)
|
|
472
|
+
const lastKickoffAt = new Map()
|
|
473
|
+
const taskMap = new Map() // sessionId -> 时间引擎派生态
|
|
474
|
+
const userTextMap = new Map()
|
|
475
|
+
let doneList = []
|
|
476
|
+
const live = { status: 'idle', steps: 0, startAt: 0, lastActivityAt: 0 }
|
|
477
|
+
let unit
|
|
478
|
+
let storageError = ''
|
|
479
|
+
let writeChain = Promise.resolve()
|
|
480
|
+
|
|
481
|
+
const storage = ctx.get('storage')
|
|
482
|
+
const webServer = ctx.get('webServer')
|
|
483
|
+
const systemPrompt = ctx.get('systemPrompt')
|
|
484
|
+
const tools = ctx.get('tools')
|
|
485
|
+
const agents = ctx.get('agents')
|
|
486
|
+
const commands = ctx.get('commands')
|
|
487
|
+
if (!systemPrompt || !tools) throw new Error('dsh-progress-union 需要 systemPrompt 与 tools 服务')
|
|
488
|
+
|
|
489
|
+
// ==========================================================================
|
|
490
|
+
// A. board 核心(fork 语义原样:revision / 409 / 全成全败 / ack / userChanges)
|
|
491
|
+
// ==========================================================================
|
|
492
|
+
|
|
493
|
+
function isEnabled(sessionId) {
|
|
494
|
+
return states.get(sessionId)?.enabled === true
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function setEnabled(sessionId, enabled) {
|
|
498
|
+
const state = ensureState(sessionId)
|
|
499
|
+
if (state.enabled === enabled) return
|
|
500
|
+
state.enabled = enabled
|
|
501
|
+
void persist(sessionId)
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
if (storage) {
|
|
505
|
+
try {
|
|
506
|
+
const backendName = storage.backend.names().find((name) => {
|
|
507
|
+
try {
|
|
508
|
+
return Boolean(storage.backend.get(name).kv)
|
|
509
|
+
} catch (_error) {
|
|
510
|
+
return false
|
|
511
|
+
}
|
|
512
|
+
})
|
|
513
|
+
if (backendName) {
|
|
514
|
+
unit = await storage.backend.get(backendName).kv.open({
|
|
515
|
+
name: UNIT_NAME,
|
|
516
|
+
version: 1,
|
|
517
|
+
tables: ['sessions'],
|
|
518
|
+
hasGlobal: false,
|
|
519
|
+
layout: 'per-record',
|
|
520
|
+
})
|
|
521
|
+
const all = await unit.loadAll()
|
|
522
|
+
for (const stored of Object.values(all.tables.sessions || {})) {
|
|
523
|
+
const record = isObject(stored) && isObject(stored.record) ? stored.record : stored
|
|
524
|
+
if (!isObject(record) || typeof record.sessionId !== 'string' || !Array.isArray(record.items)) continue
|
|
525
|
+
states.set(record.sessionId, record)
|
|
526
|
+
}
|
|
527
|
+
} else {
|
|
528
|
+
storageError = '没有可用的 KV 存储后端,进度只保存在内存中。'
|
|
529
|
+
}
|
|
530
|
+
} catch (error) {
|
|
531
|
+
storageError = `进度存储初始化失败,进度只保存在内存中:${error instanceof Error ? error.message : String(error)}`
|
|
532
|
+
}
|
|
533
|
+
} else {
|
|
534
|
+
storageError = 'storage 服务不可用,进度只保存在内存中。'
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function ensureState(sessionId) {
|
|
538
|
+
let state = states.get(sessionId)
|
|
539
|
+
if (!state) {
|
|
540
|
+
state = emptyState(sessionId)
|
|
541
|
+
states.set(sessionId, state)
|
|
542
|
+
}
|
|
543
|
+
for (const item of state.items) {
|
|
544
|
+
if (typeof item.approach !== 'string') item.approach = ''
|
|
545
|
+
}
|
|
546
|
+
if (typeof state.enabled !== 'boolean') state.enabled = false
|
|
547
|
+
return state
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function persist(sessionId) {
|
|
551
|
+
if (!unit) return writeChain
|
|
552
|
+
const snapshot = clone(states.get(sessionId))
|
|
553
|
+
writeChain = writeChain
|
|
554
|
+
.then(async () => {
|
|
555
|
+
await unit.putRecord('sessions', sessionKey(sessionId), snapshot)
|
|
556
|
+
if (storageError.startsWith('进度保存失败')) storageError = ''
|
|
557
|
+
})
|
|
558
|
+
.catch((error) => {
|
|
559
|
+
storageError = `进度保存失败,改动可能只在内存中:${error instanceof Error ? error.message : String(error)}`
|
|
560
|
+
})
|
|
561
|
+
return writeChain
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function publicSnapshot(state) {
|
|
565
|
+
const items = state.items.slice().sort((a, b) => a.order - b.order).map(itemView)
|
|
566
|
+
return {
|
|
567
|
+
ok: true,
|
|
568
|
+
sessionId: state.sessionId,
|
|
569
|
+
revision: state.revision,
|
|
570
|
+
userRevision: state.userRevision,
|
|
571
|
+
agentSeenRevision: state.agentSeenRevision,
|
|
572
|
+
enabled: state.enabled === true,
|
|
573
|
+
pendingUserChanges: state.userChanges.filter((change) => change.revision > state.agentSeenRevision).length,
|
|
574
|
+
updatedAt: state.updatedAt,
|
|
575
|
+
persistent: Boolean(unit) && !storageError.includes('失败'),
|
|
576
|
+
storageError: storageError || null,
|
|
577
|
+
items,
|
|
578
|
+
summary: summarize(items),
|
|
579
|
+
// 辅助 LLM(审查/监视)的配置回声:只回非机密字段,apiKey 只回布尔
|
|
580
|
+
assistant: {
|
|
581
|
+
enabled: assistantReady(),
|
|
582
|
+
mode: cfg.assistant.mode || '',
|
|
583
|
+
baseUrl: String(cfg.assistant.baseUrl || ''),
|
|
584
|
+
model: String(cfg.assistant.model || ''),
|
|
585
|
+
hasApiKey: String(cfg.assistant.apiKey || '') !== '',
|
|
586
|
+
minIntervalMs: Number(cfg.assistant.minIntervalMs) || 0,
|
|
587
|
+
autoApply: cfg.assistant.autoApply !== false,
|
|
588
|
+
},
|
|
589
|
+
serverTime: now(),
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function findItem(state, change) {
|
|
594
|
+
if (typeof change.id === 'string' && change.id.trim()) {
|
|
595
|
+
const id = change.id.trim()
|
|
596
|
+
return state.items.find((item) => item.id === id)
|
|
597
|
+
}
|
|
598
|
+
if (typeof change.title === 'string' && change.title.trim()) {
|
|
599
|
+
const title = change.title.trim()
|
|
600
|
+
const matches = state.items.filter((item) => item.title === title)
|
|
601
|
+
if (matches.length > 1) {
|
|
602
|
+
throw new Error(`标题「${title}」对应多个任务,请用 id 指定`)
|
|
603
|
+
}
|
|
604
|
+
return matches[0]
|
|
605
|
+
}
|
|
606
|
+
return undefined
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function applyOneChange(state, change, origin, at, records) {
|
|
610
|
+
if (!isObject(change)) throw new Error('changes 的每一项必须是对象')
|
|
611
|
+
const remove = change.remove === true
|
|
612
|
+
const existing = findItem(state, change)
|
|
613
|
+
|
|
614
|
+
if (remove) {
|
|
615
|
+
if (!existing) throw new Error(`找不到要删除的任务:${change.id || change.title || '(未提供 id/title)'}`)
|
|
616
|
+
state.items = state.items.filter((item) => item.id !== existing.id)
|
|
617
|
+
records.push({ kind: 'remove', itemId: existing.id, title: existing.title, fields: [] })
|
|
618
|
+
return
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
const hasTitle = typeof change.title === 'string' && change.title.trim()
|
|
622
|
+
if (!existing && !hasTitle) {
|
|
623
|
+
throw new Error('新增任务必须提供 title;更新任务必须提供 id 或精确 title')
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
if (!existing) {
|
|
627
|
+
if (state.items.length >= MAX_ITEMS) throw new Error(`任务数量已达到上限 ${MAX_ITEMS}`)
|
|
628
|
+
const title = text(change.title, MAX_TITLE)
|
|
629
|
+
if (!title) throw new Error('任务标题不能为空')
|
|
630
|
+
const status = STATUSES.has(change.status) ? change.status : 'todo'
|
|
631
|
+
const percent = status === 'done' ? 100 : Math.max(0, Math.min(100, Math.round(finiteNumber(change.percent) ?? 0)))
|
|
632
|
+
const item = {
|
|
633
|
+
id: newItemId(),
|
|
634
|
+
title,
|
|
635
|
+
status,
|
|
636
|
+
percent,
|
|
637
|
+
current: text(change.current, MAX_TEXT) || '',
|
|
638
|
+
next: text(change.next, MAX_TEXT) || '',
|
|
639
|
+
approach: text(change.approach, MAX_APPROACH) || '',
|
|
640
|
+
note: text(change.note, MAX_NOTE) || '',
|
|
641
|
+
group: text(change.group, MAX_GROUP) || '',
|
|
642
|
+
order: state.items.length,
|
|
643
|
+
updatedAt: at,
|
|
644
|
+
updatedBy: origin,
|
|
645
|
+
}
|
|
646
|
+
state.items.push(item)
|
|
647
|
+
records.push({
|
|
648
|
+
kind: 'add',
|
|
649
|
+
itemId: item.id,
|
|
650
|
+
title: item.title,
|
|
651
|
+
fields: [
|
|
652
|
+
{ field: 'status', from: null, to: item.status },
|
|
653
|
+
{ field: 'percent', from: null, to: item.percent },
|
|
654
|
+
],
|
|
655
|
+
})
|
|
656
|
+
return
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
const fields = []
|
|
660
|
+
function record(field, from, to) {
|
|
661
|
+
if (Object.is(from, to)) return
|
|
662
|
+
fields.push({ field, from, to })
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
if (typeof change.title === 'string') {
|
|
666
|
+
const nextTitle = text(change.title, MAX_TITLE)
|
|
667
|
+
if (!nextTitle) throw new Error('任务标题不能为空')
|
|
668
|
+
record('title', existing.title, nextTitle)
|
|
669
|
+
existing.title = nextTitle
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
if (typeof change.status === 'string') {
|
|
673
|
+
if (!STATUSES.has(change.status)) throw new Error(`未知状态:${change.status}`)
|
|
674
|
+
record('status', existing.status, change.status)
|
|
675
|
+
existing.status = change.status
|
|
676
|
+
if (change.status === 'done') {
|
|
677
|
+
record('percent', existing.percent, 100)
|
|
678
|
+
existing.percent = 100
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
if (change.percent !== undefined) {
|
|
683
|
+
const value = finiteNumber(change.percent)
|
|
684
|
+
if (value === undefined) throw new Error('percent 必须是 0–100 的数字')
|
|
685
|
+
const nextPercent = Math.max(0, Math.min(100, Math.round(value)))
|
|
686
|
+
record('percent', existing.percent, nextPercent)
|
|
687
|
+
existing.percent = nextPercent
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
if (existing.status === 'done' && existing.percent !== 100) {
|
|
691
|
+
record('percent', existing.percent, 100)
|
|
692
|
+
existing.percent = 100
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
for (const [field, max] of [
|
|
696
|
+
['current', MAX_TEXT],
|
|
697
|
+
['next', MAX_TEXT],
|
|
698
|
+
['approach', MAX_APPROACH],
|
|
699
|
+
['note', MAX_NOTE],
|
|
700
|
+
['group', MAX_GROUP],
|
|
701
|
+
]) {
|
|
702
|
+
if (typeof change[field] === 'string') {
|
|
703
|
+
const nextValue = text(change[field], max) || ''
|
|
704
|
+
record(field, existing[field], nextValue)
|
|
705
|
+
existing[field] = nextValue
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
if (change.order !== undefined) {
|
|
710
|
+
const nextOrder = finiteNumber(change.order)
|
|
711
|
+
if (nextOrder === undefined) throw new Error('order 必须是数字')
|
|
712
|
+
record('order', existing.order, nextOrder)
|
|
713
|
+
existing.order = nextOrder
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
if (fields.length > 0) {
|
|
717
|
+
existing.updatedAt = at
|
|
718
|
+
existing.updatedBy = origin
|
|
719
|
+
records.push({ kind: 'edit', itemId: existing.id, title: existing.title, fields })
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
async function applyChanges({ sessionId, changes, origin, expectedRevision, ackUserRevision }) {
|
|
724
|
+
if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 240) {
|
|
725
|
+
throw new Error('无效的 sessionId')
|
|
726
|
+
}
|
|
727
|
+
if (!Array.isArray(changes)) throw new Error('changes 必须是数组')
|
|
728
|
+
if (changes.length > MAX_CHANGES) throw new Error(`一次最多提交 ${MAX_CHANGES} 项改动`)
|
|
729
|
+
if (expectedRevision !== undefined && finiteNumber(expectedRevision) === undefined) {
|
|
730
|
+
throw new Error('expectedRevision 必须是数字')
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const state = ensureState(sessionId)
|
|
734
|
+
if (expectedRevision !== undefined && expectedRevision !== state.revision) {
|
|
735
|
+
const error = new Error('进度板已被更新,请先刷新再提交')
|
|
736
|
+
error.statusCode = 409
|
|
737
|
+
error.snapshot = publicSnapshot(state)
|
|
738
|
+
throw error
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// 批量改动在一次性克隆上验证并应用:半途失败会经由 HTTP 重试与 409 重放
|
|
742
|
+
// 变成重复或半应用任务(board 原教训,原样保留)。
|
|
743
|
+
const working = clone(state)
|
|
744
|
+
const records = []
|
|
745
|
+
const at = now()
|
|
746
|
+
for (const change of changes) applyOneChange(working, change, origin, at, records)
|
|
747
|
+
|
|
748
|
+
let revisionChanged = false
|
|
749
|
+
if (records.length > 0) {
|
|
750
|
+
working.revision += 1
|
|
751
|
+
working.updatedAt = at
|
|
752
|
+
normalizeItems(working.items)
|
|
753
|
+
for (const record of records) {
|
|
754
|
+
if (record.kind !== 'edit') continue
|
|
755
|
+
const orderField = record.fields.find((field) => field.field === 'order')
|
|
756
|
+
if (orderField) {
|
|
757
|
+
const after = working.items.find((item) => item.id === record.itemId)
|
|
758
|
+
if (after) orderField.to = after.order
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
if (origin === 'user') {
|
|
762
|
+
working.userRevision = working.revision
|
|
763
|
+
for (const record of records) working.userChanges.push({ revision: working.revision, at, ...record })
|
|
764
|
+
if (working.userChanges.length > MAX_USER_CHANGES) {
|
|
765
|
+
working.userChanges.splice(0, working.userChanges.length - MAX_USER_CHANGES)
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
revisionChanged = true
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
if (origin === 'agent' && ackUserRevision !== undefined) {
|
|
772
|
+
const ack = finiteNumber(ackUserRevision)
|
|
773
|
+
if (ack !== undefined) {
|
|
774
|
+
working.agentSeenRevision = Math.max(working.agentSeenRevision, Math.min(working.userRevision, Math.round(ack)))
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
if (revisionChanged || (origin === 'agent' && ackUserRevision !== undefined)) {
|
|
779
|
+
states.set(sessionId, working)
|
|
780
|
+
await persist(sessionId)
|
|
781
|
+
}
|
|
782
|
+
// 任何 agent 调用(含 changes=[] 确认)都算一次"模型已看板":重置催办计时;
|
|
783
|
+
// 观察者自己的 autoSync(origin='observer')只刷新板新鲜度,不抵消模型催办。
|
|
784
|
+
if (origin === 'agent' || revisionChanged) noteBoardWrite(sessionId, origin, at)
|
|
785
|
+
|
|
786
|
+
const changed = records.map((record) => {
|
|
787
|
+
if (record.kind === 'remove') return { id: record.itemId, title: record.title, removed: true }
|
|
788
|
+
return {
|
|
789
|
+
id: record.itemId,
|
|
790
|
+
title: record.title,
|
|
791
|
+
change: record.kind,
|
|
792
|
+
fields: record.fields.map((field) => field.field),
|
|
793
|
+
}
|
|
794
|
+
})
|
|
795
|
+
return { snapshot: publicSnapshot(working), changed: changed.filter(Boolean) }
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// ==========================================================================
|
|
799
|
+
// B. 注入面(board 三块照板 + 鲸程文件上报协议收敛)
|
|
800
|
+
// ==========================================================================
|
|
801
|
+
|
|
802
|
+
function pendingContext(sessionId) {
|
|
803
|
+
if (!isEnabled(sessionId)) return ''
|
|
804
|
+
const state = states.get(sessionId)
|
|
805
|
+
if (!state || state.userRevision <= state.agentSeenRevision) return ''
|
|
806
|
+
const changes = state.userChanges.filter((change) => change.revision > state.agentSeenRevision).slice(-20)
|
|
807
|
+
if (changes.length === 0) return ''
|
|
808
|
+
const lines = changes.map(describeChange)
|
|
809
|
+
return `<progress-board-user-edits revision="${state.userRevision}">
|
|
810
|
+
用户在进度板上做了以下改动。只依据这些改动调整方向,不要重读整份计划;用户改动优先于你原来的计划。
|
|
811
|
+
${lines.join('\n')}
|
|
812
|
+
处理完后调用 progress_update,传 ackUserRevision=${state.userRevision}。如果这些改动不要求修改任务,也可以传 changes=[] 仅确认收到。
|
|
813
|
+
</progress-board-user-edits>`
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
function kickoffContext(sessionId) {
|
|
817
|
+
if (!isEnabled(sessionId)) return ''
|
|
818
|
+
const state = states.get(sessionId)
|
|
819
|
+
if (!state || state.items.length === 0) {
|
|
820
|
+
return `<progress-board-kickoff>
|
|
821
|
+
进度板已启用但当前为空。本回合的第一个工具调用必须是 progress_update:先建立 2–5 个扁平任务(第一项设为 doing,current 写正在做什么),然后再调用其他工具或开始实现。
|
|
822
|
+
</progress-board-kickoff>`
|
|
823
|
+
}
|
|
824
|
+
// 板走完计划是更新静默停下的地方:空板之外,全完成或超 10 分钟没更新都再推一次。
|
|
825
|
+
const allDone = state.items.every((item) => item.status === 'done')
|
|
826
|
+
const idleMs = now() - (finiteNumber(state.updatedAt) ?? 0)
|
|
827
|
+
if (!allDone && idleMs < STALE_MS) return ''
|
|
828
|
+
// 投影每次 model request 重建而非每回合一次:一回合至多推一次,避免每步都邀请 changes=[]。
|
|
829
|
+
const at = now()
|
|
830
|
+
const lastNudge = lastKickoffAt.get(sessionId) ?? 0
|
|
831
|
+
if (at - lastNudge < KICKOFF_COOLDOWN_MS) return ''
|
|
832
|
+
lastKickoffAt.set(sessionId, at)
|
|
833
|
+
const reason = allDone
|
|
834
|
+
? '进度板上的任务已全部完成'
|
|
835
|
+
: `进度板已有 ${Math.round(idleMs / 60000)} 分钟没有更新`
|
|
836
|
+
return `<progress-board-kickoff>
|
|
837
|
+
${reason}。本回合开始前先用 progress_update 处理进度板:用户这条消息是新任务就先增补任务(第一项设为 doing,current 写正在做什么)再动手;不是新任务就传 changes=[] 确认。不要重发整份旧计划。
|
|
838
|
+
</progress-board-kickoff>`
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// ==========================================================================
|
|
842
|
+
// B2. 观察者(辅助主模型观察最近输出/清单;板滞后先自动补事实性 current,再催办)
|
|
843
|
+
// 依据:assistant/message(最近输出)、tool/call(最近动作)、
|
|
844
|
+
// step/start(距上一次写板的步数)——都是会话事件里的事实,不做语义猜测。
|
|
845
|
+
// ==========================================================================
|
|
846
|
+
|
|
847
|
+
const observers = new Map()
|
|
848
|
+
|
|
849
|
+
function obsOf(sid) {
|
|
850
|
+
let o = observers.get(sid)
|
|
851
|
+
if (!o) {
|
|
852
|
+
const at = now()
|
|
853
|
+
o = { outputs: [], tools: [], lastBoardAt: at, lastModelAt: at, stepsSinceBoard: 0, stepsSinceModel: 0, lastAutoSyncAt: 0,
|
|
854
|
+
assistantCalls: 0, lastAssistantAt: 0, assistantNote: '', assistantError: '' }
|
|
855
|
+
observers.set(sid, o)
|
|
856
|
+
}
|
|
857
|
+
return o
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// board 写后重置计数器:origin='observer'/'assistant' 只刷新"板新鲜度",不抵消"模型未同步"。
|
|
861
|
+
function noteBoardWrite(sid, origin, at) {
|
|
862
|
+
const o = obsOf(sid)
|
|
863
|
+
o.lastBoardAt = at
|
|
864
|
+
o.stepsSinceBoard = 0
|
|
865
|
+
if (origin !== 'observer' && origin !== 'assistant') {
|
|
866
|
+
o.lastModelAt = at
|
|
867
|
+
o.stepsSinceModel = 0
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function briefArgs(raw) {
|
|
872
|
+
try {
|
|
873
|
+
const v = JSON.parse(String(raw || ''))
|
|
874
|
+
if (isObject(v)) {
|
|
875
|
+
for (const key of ['command', 'path', 'file_path', 'pattern', 'query', 'url', 'name', 'title']) {
|
|
876
|
+
if (typeof v[key] === 'string' && v[key].trim()) return `${key}=${v[key].trim().slice(0, 70)}`
|
|
877
|
+
}
|
|
878
|
+
const lines = JSON.stringify(v)
|
|
879
|
+
return lines.length > 90 ? lines.slice(0, 90) + '…' : lines
|
|
880
|
+
}
|
|
881
|
+
} catch (_err) {}
|
|
882
|
+
const s = String(raw || '').trim()
|
|
883
|
+
return s.length > 90 ? s.slice(0, 90) + '…' : s
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
function recordTool(sid, data) {
|
|
887
|
+
const d = data || {}
|
|
888
|
+
if (typeof d.name !== 'string' || !d.name) return
|
|
889
|
+
const o = obsOf(sid)
|
|
890
|
+
const at = now()
|
|
891
|
+
o.tools.push({ at, name: d.name, brief: briefArgs(d.arguments) })
|
|
892
|
+
if (o.tools.length > 8) o.tools.splice(0, o.tools.length - 8)
|
|
893
|
+
// 文件改动(事实级):任何带路径类参数的工具调用都记一笔,同路径去重留最新
|
|
894
|
+
const file = filePathOf(d.arguments)
|
|
895
|
+
if (file) {
|
|
896
|
+
o.files = (o.files || []).filter((x) => x.path !== file)
|
|
897
|
+
o.files.push({ path: file, tool: d.name, at })
|
|
898
|
+
if (o.files.length > 6) o.files.splice(0, o.files.length - 6)
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
// 只认路径类参数(覆盖主流 fs 工具命名),拿不到就不记——不猜。
|
|
903
|
+
function filePathOf(raw) {
|
|
904
|
+
try {
|
|
905
|
+
const v = JSON.parse(String(raw || ''))
|
|
906
|
+
if (isObject(v)) {
|
|
907
|
+
for (const key of ['file_path', 'path', 'abs_path', 'target_file', 'filePath']) {
|
|
908
|
+
if (typeof v[key] === 'string' && v[key].trim()) return v[key].trim()
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
} catch (_err) {}
|
|
912
|
+
return ''
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function shortPath(p) {
|
|
916
|
+
const s = String(p || '')
|
|
917
|
+
return s.length > 64 ? '…' + s.slice(-64) : s
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function recordOutput(sid, data) {
|
|
921
|
+
const msg = data && data.message ? data.message : data
|
|
922
|
+
const t = textOf(msg).replace(/\s+/g, ' ').trim()
|
|
923
|
+
if (!t) return
|
|
924
|
+
const o = obsOf(sid)
|
|
925
|
+
o.outputs.push({ at: now(), text: t.length > 160 ? t.slice(0, 160) + '…' : t })
|
|
926
|
+
if (o.outputs.length > 4) o.outputs.splice(0, o.outputs.length - 4)
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// 板上还有活干才算"需要催":全完成/空板不打扰。
|
|
930
|
+
function boardHasWork(sid) {
|
|
931
|
+
const s = states.get(sid)
|
|
932
|
+
return Boolean(s && s.enabled && s.items.some((item) => item.status !== 'done'))
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
function modelIsLate(sid, at) {
|
|
936
|
+
const o = obsOf(sid)
|
|
937
|
+
return o.stepsSinceModel >= cfg.observer.maxIdleSteps || at - o.lastModelAt >= cfg.observer.maxIdleMs
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// 观察者自动补 current:只用事实(最近一次工具调用),不动 status/percent。
|
|
941
|
+
function maybeAutoSync(sid, at) {
|
|
942
|
+
if (!cfg.observer.autoSyncCurrent) return
|
|
943
|
+
if (!cfg.observer.enabled || !boardHasWork(sid)) return
|
|
944
|
+
const o = obsOf(sid)
|
|
945
|
+
if (o.stepsSinceBoard < cfg.observer.maxIdleSteps && at - o.lastBoardAt < cfg.observer.maxIdleMs) return
|
|
946
|
+
if (at - o.lastAutoSyncAt < cfg.observer.autoSyncThrottleMs) return
|
|
947
|
+
const lastTool = o.tools[o.tools.length - 1]
|
|
948
|
+
if (!lastTool || at - lastTool.at > cfg.observer.maxIdleMs) return
|
|
949
|
+
const state = states.get(sid)
|
|
950
|
+
const doing = state.items.find((item) => item.status === 'doing')
|
|
951
|
+
if (!doing) return
|
|
952
|
+
const line = `自动同步:${lastTool.name}${lastTool.brief ? ' · ' + lastTool.brief : ''}`.slice(0, MAX_TEXT)
|
|
953
|
+
if (doing.current === line) return
|
|
954
|
+
o.lastAutoSyncAt = at
|
|
955
|
+
void applyChanges({ sessionId: sid, changes: [{ id: doing.id, current: line }], origin: 'observer' }).catch(() => {})
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
// —— 辅助 LLM(审查/监视):命题 → 校验 → 落地(只动 current/next/percent)——
|
|
959
|
+
function assistantReady() {
|
|
960
|
+
return cfg.assistant.mode === 'direct'
|
|
961
|
+
&& String(cfg.assistant.baseUrl || '').trim() !== ''
|
|
962
|
+
&& String(cfg.assistant.model || '').trim() !== ''
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
// 从模型回复里抠出唯一 JSON 对象(容忍 ```json 围栏与前后废话)。
|
|
966
|
+
function parseProposal(raw) {
|
|
967
|
+
const text = String(raw || '').trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim()
|
|
968
|
+
const start = text.indexOf('{')
|
|
969
|
+
const end = text.lastIndexOf('}')
|
|
970
|
+
if (start < 0 || end <= start) return null
|
|
971
|
+
try {
|
|
972
|
+
const value = JSON.parse(text.slice(start, end + 1))
|
|
973
|
+
return isObject(value) ? value : null
|
|
974
|
+
} catch (_err) {
|
|
975
|
+
return null
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/**
|
|
980
|
+
* 板滞后(或模型久未同步)时问一次辅助模型。失败静默(记 assistantError),
|
|
981
|
+
* 绝不阻断主流程;每回合至多 maxCallsPerTurn 次、两次至少间隔 minIntervalMs。
|
|
982
|
+
*/
|
|
983
|
+
async function maybeAskAssistant(sid, at) {
|
|
984
|
+
if (!assistantReady() || !boardHasWork(sid)) return
|
|
985
|
+
const o = obsOf(sid)
|
|
986
|
+
if (!modelIsLate(sid, at) && o.stepsSinceBoard < cfg.observer.maxIdleSteps) return
|
|
987
|
+
if (at - o.lastAssistantAt < cfg.assistant.minIntervalMs) return
|
|
988
|
+
if (o.assistantCalls >= cfg.assistant.maxCallsPerTurn) return
|
|
989
|
+
const state = states.get(sid)
|
|
990
|
+
if (!state) return
|
|
991
|
+
o.assistantCalls += 1
|
|
992
|
+
o.lastAssistantAt = at
|
|
993
|
+
const lastOutput = o.outputs[o.outputs.length - 1]
|
|
994
|
+
const files = Array.isArray(o.files) ? o.files.slice(-4).map((f) => f.path) : []
|
|
995
|
+
const lines = [
|
|
996
|
+
...renderChecklist(state, cfg.observer.maxItems),
|
|
997
|
+
lastOutput ? `最近输出:${lastOutput.text}` : '最近输出:—',
|
|
998
|
+
o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
|
|
999
|
+
files.length ? `最近改动:${files.join(' · ')}` : '最近改动:—',
|
|
1000
|
+
]
|
|
1001
|
+
const controller = new AbortController()
|
|
1002
|
+
const timer = setTimeout(() => controller.abort(), Math.max(2000, Number(cfg.assistant.timeoutMs) || 20000))
|
|
1003
|
+
try {
|
|
1004
|
+
const base = String(cfg.assistant.baseUrl || '').replace(/\/+$/, '')
|
|
1005
|
+
const response = await fetch(`${base}/chat/completions`, {
|
|
1006
|
+
method: 'POST',
|
|
1007
|
+
headers: {
|
|
1008
|
+
'content-type': 'application/json',
|
|
1009
|
+
...(String(cfg.assistant.apiKey || '') !== '' ? { authorization: `Bearer ${cfg.assistant.apiKey}` } : {}),
|
|
1010
|
+
},
|
|
1011
|
+
body: JSON.stringify({
|
|
1012
|
+
model: cfg.assistant.model,
|
|
1013
|
+
temperature: 0,
|
|
1014
|
+
max_tokens: 300,
|
|
1015
|
+
messages: [
|
|
1016
|
+
{ role: 'system', content: ASSISTANT_SYSTEM },
|
|
1017
|
+
{ role: 'user', content: lines.join('\n') },
|
|
1018
|
+
],
|
|
1019
|
+
}),
|
|
1020
|
+
signal: controller.signal,
|
|
1021
|
+
})
|
|
1022
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
1023
|
+
const body = await response.json()
|
|
1024
|
+
const proposal = parseProposal(body?.choices?.[0]?.message?.content ?? '')
|
|
1025
|
+
if (!proposal) throw new Error('proposal-unparsable')
|
|
1026
|
+
o.assistantError = ''
|
|
1027
|
+
o.assistantNote = String(proposal.note || '').slice(0, 200)
|
|
1028
|
+
if (cfg.assistant.autoApply !== false && Array.isArray(proposal.changes) && proposal.changes.length > 0) {
|
|
1029
|
+
const byId = new Map(state.items.map((item) => [item.id, item]))
|
|
1030
|
+
const changes = []
|
|
1031
|
+
for (const candidate of proposal.changes.slice(0, 10)) {
|
|
1032
|
+
if (!isObject(candidate)) continue
|
|
1033
|
+
const target = byId.get(String(candidate.id || ''))
|
|
1034
|
+
if (!target) continue
|
|
1035
|
+
const patch = { id: target.id }
|
|
1036
|
+
if (typeof candidate.current === 'string') patch.current = candidate.current
|
|
1037
|
+
if (typeof candidate.next === 'string') patch.next = candidate.next
|
|
1038
|
+
if (typeof candidate.percent === 'number' && Number.isFinite(candidate.percent)) {
|
|
1039
|
+
patch.percent = Math.max(0, Math.min(100, Math.round(candidate.percent)))
|
|
1040
|
+
}
|
|
1041
|
+
if (Object.keys(patch).length > 1) changes.push(patch)
|
|
1042
|
+
}
|
|
1043
|
+
if (changes.length > 0) {
|
|
1044
|
+
await applyChanges({ sessionId: sid, changes, origin: 'assistant' })
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
} catch (err) {
|
|
1048
|
+
o.assistantError = err instanceof Error ? err.message : String(err)
|
|
1049
|
+
} finally {
|
|
1050
|
+
clearTimeout(timer)
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
function renderChecklist(state, maxItems) {
|
|
1055
|
+
const items = state.items.slice().sort((a, b) => a.order - b.order)
|
|
1056
|
+
const marks = { done: '[x]', doing: '[~]', blocked: '[!]', todo: '[ ]' }
|
|
1057
|
+
const lines = items.slice(0, maxItems).map((item) => {
|
|
1058
|
+
const bits = [`${marks[item.status] || '[ ]'} ${item.title}(${item.percent}%)`]
|
|
1059
|
+
if (item.status === 'doing' && item.current) {
|
|
1060
|
+
// 观察者自补的 current 标注待确认:模型不能把事实刷新闻当状态已同步
|
|
1061
|
+
const mark = item.current.startsWith('自动同步:') ? '(观察者补,待确认)' : ''
|
|
1062
|
+
bits.push(`当前:${item.current}${mark}`)
|
|
1063
|
+
}
|
|
1064
|
+
if (item.status === 'doing' && item.next) bits.push(`下一步:${item.next}`)
|
|
1065
|
+
if (item.status === 'blocked') bits.push(`阻塞:${item.note || '等待中'}`)
|
|
1066
|
+
return '- ' + bits.join(' · ')
|
|
1067
|
+
})
|
|
1068
|
+
if (items.length > maxItems) lines.push(`- …另有 ${items.length - maxItems} 项`)
|
|
1069
|
+
return lines
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/**
|
|
1073
|
+
* 观察块:每请求重建(systemPrompt.context),不进历史累积。
|
|
1074
|
+
* = 清单(checklist)+ 官方 todo 进度 + 最近输出 + 最近动作 +(滞后时)催办。
|
|
1075
|
+
* 门控:板启用且还有活干;关板/全完成时不占一行 token。
|
|
1076
|
+
*/
|
|
1077
|
+
function observerContext(sid) {
|
|
1078
|
+
if (!cfg.observer.enabled || !isEnabled(sid) || !boardHasWork(sid)) return ''
|
|
1079
|
+
const state = states.get(sid)
|
|
1080
|
+
const o = obsOf(sid)
|
|
1081
|
+
const at = now()
|
|
1082
|
+
const lines = []
|
|
1083
|
+
lines.push(...renderChecklist(state, cfg.observer.maxItems))
|
|
1084
|
+
const t = taskMap.get(sid)
|
|
1085
|
+
if (t && t.todoTotal >= 2) {
|
|
1086
|
+
const titles = Array.isArray(t.todoItems) ? t.todoItems.slice(0, 4).join('、') : ''
|
|
1087
|
+
lines.push(`[官方todo] 完成 ${t.todoDone}/${t.todoTotal}${titles ? ',未完:' + titles : ''}`)
|
|
1088
|
+
// 机械对比(算术,非语义):两套清单完成数漂移 → 让模型自己核对
|
|
1089
|
+
const boardDone = state.items.filter((item) => item.status === 'done').length
|
|
1090
|
+
if (t.todoDone !== boardDone) {
|
|
1091
|
+
lines.push(`对比:官方 todo 完成 ${t.todoDone}/${t.todoTotal} · 板完成 ${boardDone}/${state.items.length}(进度不一致,核对后修正一处)`)
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
const files = Array.isArray(o.files) ? o.files.slice(-4) : []
|
|
1095
|
+
if (files.length) lines.push(`最近改动:${files.map((f) => `${shortPath(f.path)}(${f.tool})`).join(' · ')}`)
|
|
1096
|
+
const lastOutput = o.outputs[o.outputs.length - 1]
|
|
1097
|
+
if (lastOutput) lines.push(`最近输出:「${lastOutput.text}」`)
|
|
1098
|
+
const tools = o.tools.slice(-cfg.observer.maxTools)
|
|
1099
|
+
if (tools.length) lines.push(`最近动作:${tools.map((x) => x.name).join(' → ')}`)
|
|
1100
|
+
const synced = o.stepsSinceModel > 0 ? `${o.stepsSinceModel} 步前` : '本回合'
|
|
1101
|
+
const late = modelIsLate(sid, at)
|
|
1102
|
+
if (late) {
|
|
1103
|
+
const idleMin = Math.max(0, Math.round((at - o.lastModelAt) / 60000))
|
|
1104
|
+
lines.push(`⚠ 进度已滞后(${synced}${idleMin >= 1 ? ',' + idleMin + ' 分钟' : ''}):先调用 progress_update 同步再继续;无变化就传 changes=[]。观察者已用最近动作自动刷新 current(updatedBy=observer),但状态/百分比仍需你确认。`)
|
|
1105
|
+
}
|
|
1106
|
+
if (o.assistantNote) lines.push(`助手审查:${o.assistantNote}`)
|
|
1107
|
+
if (o.assistantError) lines.push(`助手审查失败:${o.assistantError}(仅影响审查建议,不阻断主流程)`)
|
|
1108
|
+
return `<progress-observer revision="${state.revision}" synced="${synced}">\n${lines.join('\n')}\n</progress-observer>`
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
// 鲸程文件上报协议:仅 board 关闭的会话注入(开板会话 progress_update 是唯一写通道)。
|
|
1112
|
+
function protocolText(sid) {
|
|
1113
|
+
const who = String(sid || '')
|
|
1114
|
+
return '执行任务时维护**你自己的**进度文件 $DSH_HOME/dsh-progress/<你的会话id>.json(目录不存在就建;文件名就用会话 id,例如 $DSH_HOME/dsh-progress/' + (who || 'session-xxx') + '.json)。⚠️**千万不要写 $DSH_HOME/dsh-progress.json 那个单文件**——那里是所有会话共用的旧位置,谁写谁覆盖,会把别人的任务条顶掉。开工第一步写 {"task":"总结性任务名","session":"' + who + '","stages":["阶段1",...],"current":0,"pct":10,"action":"正在…","etaMin":N,"status":"running","startedAt":毫秒,"updatedAt":毫秒};session 必须原样填当前会话 id(插件据此把你这条上报合并到本会话的任务上,避免同一任务显示两条)。' +
|
|
1115
|
+
'⚠️**每完成一个可交付的小步就更新** current/pct/action/etaMin/updatedAt,不要只在阶段边界更新;**任何单步预计超过 60 秒的,先在 action 里写清"正在做什么(第 N/M 个)"再去做**,做完立刻更新一次。action 要写具体动作(如"渲染第 7/24 张"),不要写"处理中/排队中"这类空话。' +
|
|
1116
|
+
'⚠️遇到报错、等待用户确认、卡住不动时,立刻写 {"status":"blocked","issue":"一句话说清卡在哪","updatedAt":毫秒},恢复后改回 status:"running";插件会把 blocked 显示成橙色并展示 issue,用户就不会以为还在跑。' +
|
|
1117
|
+
'任务真正结束才标 {"status":"done","pct":100,"endedAt":毫秒}。ETA 按阶段数×复杂度推算并在回复中说明依据,简单任务≤3分钟。'
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
const hookedAgents = new WeakSet()
|
|
1121
|
+
function installAgentHook(agent) {
|
|
1122
|
+
if (!agent || !agent.id || !agent.ctx) return
|
|
1123
|
+
if (hookedAgents.has(agent)) return
|
|
1124
|
+
hookedAgents.add(agent)
|
|
1125
|
+
try {
|
|
1126
|
+
agent.ctx.on('agent/pre-step', async (payload, next) => {
|
|
1127
|
+
const decision = await next()
|
|
1128
|
+
try {
|
|
1129
|
+
if (!cfg.protocolHint) return decision
|
|
1130
|
+
// 单协议收敛:本会话板已启用 → 不再注入文件上报协议。
|
|
1131
|
+
const sid = String(agent.session?.id ?? agent.id)
|
|
1132
|
+
if (isEnabled(sid)) return decision
|
|
1133
|
+
if (!decision || decision.kind !== 'enter' || !Array.isArray(decision.messages)) return decision
|
|
1134
|
+
const freshUser = ((payload && payload.messages) || []).find((m) => m && m.source && m.source.kind === 'user')
|
|
1135
|
+
if (!freshUser) return decision
|
|
1136
|
+
decision.messages.push({
|
|
1137
|
+
id: 'dpg-' + now().toString(36) + '-' + Math.random().toString(36).slice(2, 8),
|
|
1138
|
+
role: 'user',
|
|
1139
|
+
content: [{ type: 'text', text: protocolText(agent.id) }],
|
|
1140
|
+
// session format v4 拒收旧 {kind:'plugin'} 包装:第三方必须用 producer-owned kind。
|
|
1141
|
+
source: { kind: 'plugin:dsh-progress-union', form: 'notice', summary: '任务进度上报协议' },
|
|
1142
|
+
})
|
|
1143
|
+
return decision
|
|
1144
|
+
} catch (_err) {
|
|
1145
|
+
return decision
|
|
1146
|
+
}
|
|
1147
|
+
})
|
|
1148
|
+
} catch (_err) {}
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// ==========================================================================
|
|
1152
|
+
// C. 时间引擎(widget fork;派生态与 board states 按 sessionId 并联)
|
|
1153
|
+
// ==========================================================================
|
|
1154
|
+
|
|
1155
|
+
function sessionOfAgent(agent) {
|
|
1156
|
+
return String(agent.session?.id ?? agent.id ?? 'default')
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
// 子智能体识别:delegationDepth>0 即子会话;parentSession 存在才采用,拿不到不硬猜。
|
|
1160
|
+
function markLineage(task, session) {
|
|
1161
|
+
try {
|
|
1162
|
+
const hd = session && session.header
|
|
1163
|
+
if (!hd || !task) return
|
|
1164
|
+
if (typeof hd.delegationDepth === 'number' && hd.delegationDepth > 0) task.isSub = true
|
|
1165
|
+
if (task.isSub && hd.parentSession) task.parentId = String(hd.parentSession)
|
|
1166
|
+
} catch (_err) {}
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
function subTitleOf(task, text) {
|
|
1170
|
+
if (task && task.subLabel) return task.subLabel
|
|
1171
|
+
return summarizeSubTitle(text)
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
function taskOf(sid) {
|
|
1175
|
+
let t = taskMap.get(sid)
|
|
1176
|
+
if (!t) {
|
|
1177
|
+
t = {
|
|
1178
|
+
active: false, open: false, title: '', project: '', startedAt: 0, steps: 0,
|
|
1179
|
+
lastActivityAt: 0, sid, isSub: false, parentId: '', subLabel: '', subTitled: false,
|
|
1180
|
+
_stepTimes: [], todoDone: 0, todoTotal: 0, etaSmooth: 0,
|
|
1181
|
+
}
|
|
1182
|
+
taskMap.set(sid, t)
|
|
1183
|
+
enforceCapacity(sid)
|
|
1184
|
+
}
|
|
1185
|
+
return t
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
function endTask(sid) {
|
|
1189
|
+
const t = taskMap.get(sid)
|
|
1190
|
+
if (!t || !t.active) return
|
|
1191
|
+
t.active = false
|
|
1192
|
+
const ended = now()
|
|
1193
|
+
// 学一条真实样本:某 step 发生时刻离任务结束还有多久(本机自校正 ETA 的原料)。
|
|
1194
|
+
try {
|
|
1195
|
+
if (Array.isArray(t._stepTimes) && t._stepTimes.length) {
|
|
1196
|
+
const rows = []
|
|
1197
|
+
t._stepTimes.forEach((at, i) => {
|
|
1198
|
+
const remainSec = (ended - at) / 1000
|
|
1199
|
+
if (remainSec > 0 && remainSec < 7200) rows.push({ s: i + 1, r: Math.round(remainSec) })
|
|
1200
|
+
})
|
|
1201
|
+
recordSamples(rows)
|
|
1202
|
+
flushStats()
|
|
1203
|
+
}
|
|
1204
|
+
} catch (_err) {}
|
|
1205
|
+
t._stepTimes = []
|
|
1206
|
+
doneList.push({ title: t.title, project: t.project, startedAt: t.startedAt, endedAt: ended, at: ended })
|
|
1207
|
+
doneList = doneList.filter((d) => ended - d.at < cfg.doneKeepMs)
|
|
1208
|
+
enforceCapacity(sid)
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
// 淘汰"最久没有活动"的会话(不能删最早插入的,长会话会被误删)。
|
|
1212
|
+
function enforceCapacity(skipSid) {
|
|
1213
|
+
if (taskMap.size <= cfg.maxTasks) return
|
|
1214
|
+
let victim = null
|
|
1215
|
+
let oldestAt = Infinity
|
|
1216
|
+
for (const [otherSid, other] of taskMap) {
|
|
1217
|
+
if (otherSid === skipSid) continue
|
|
1218
|
+
const at = Number(other.lastActivityAt) || 0
|
|
1219
|
+
if (at < oldestAt) {
|
|
1220
|
+
oldestAt = at
|
|
1221
|
+
victim = otherSid
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
if (victim) taskMap.delete(victim)
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
/**
|
|
1228
|
+
* ETA 计算(board 档优先)。纯函数按 (task, items, now) 求值;
|
|
1229
|
+
* `smoothing=true` 只走展示通道(会原地推进 etaSmooth),锚点读接口用
|
|
1230
|
+
* `smoothing=false`——保证同 (revision, steps, now) 同字节。
|
|
1231
|
+
*/
|
|
1232
|
+
function computeEta(t, boardItems, atMs, smoothing) {
|
|
1233
|
+
const startedAt = t && Number(t.startedAt) ? Number(t.startedAt) : 0
|
|
1234
|
+
const elapsedSec = startedAt > 0 ? Math.max(0, (atMs - startedAt) / 1000) : 0
|
|
1235
|
+
let prior = null
|
|
1236
|
+
let etaSrc = 'prior'
|
|
1237
|
+
|
|
1238
|
+
const boardActive = Array.isArray(boardItems) && boardItems.length >= 2
|
|
1239
|
+
let boardDone = 0
|
|
1240
|
+
let boardLeft = 0
|
|
1241
|
+
if (boardActive) {
|
|
1242
|
+
for (const item of boardItems) {
|
|
1243
|
+
if (item.status === 'done') boardDone += 1
|
|
1244
|
+
else if (item.status !== 'blocked') boardLeft += 1 // blocked 不计剩余:它在等人,不是等时间
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
const todoTotal = t ? Number(t.todoTotal) || 0 : 0
|
|
1248
|
+
const todoDone = t ? Number(t.todoDone) || 0 : 0
|
|
1249
|
+
|
|
1250
|
+
if (boardActive && boardDone >= 1 && elapsedSec > 0) {
|
|
1251
|
+
const perItemSec = elapsedSec / boardDone
|
|
1252
|
+
prior = { p50: Math.max(10, perItemSec * boardLeft), p75: Math.max(30, perItemSec * boardLeft * 2.2) }
|
|
1253
|
+
etaSrc = 'board'
|
|
1254
|
+
} else if (todoTotal >= 2 && todoDone >= 1 && elapsedSec > 0) {
|
|
1255
|
+
const perItemSec = elapsedSec / todoDone
|
|
1256
|
+
prior = { p50: Math.max(10, perItemSec * (todoTotal - todoDone)), p75: Math.max(30, perItemSec * (todoTotal - todoDone) * 2.2) }
|
|
1257
|
+
etaSrc = 'todo'
|
|
1258
|
+
} else {
|
|
1259
|
+
const steps = t ? Number(t.steps) || 0 : 0
|
|
1260
|
+
const learned = learnedFor(steps)
|
|
1261
|
+
prior = learned || priorFor(steps)
|
|
1262
|
+
etaSrc = learned ? 'local' : 'prior'
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
const overLimit = Math.min(prior.p75, Math.max(prior.p50 * 1.8, prior.p50 + 60))
|
|
1266
|
+
const overSec = elapsedSec - overLimit
|
|
1267
|
+
let remainMin
|
|
1268
|
+
if (overSec > 30) {
|
|
1269
|
+
// 超过这类任务 P75 → 报负数"已超预估",不假装还剩几秒。
|
|
1270
|
+
remainMin = -Math.max(1, Math.round(overSec / 60))
|
|
1271
|
+
} else {
|
|
1272
|
+
remainMin = Math.max(5, prior.p50 - elapsedSec * 0.6) / 60
|
|
1273
|
+
}
|
|
1274
|
+
if (smoothing && t) {
|
|
1275
|
+
const prev = Number(t.etaSmooth)
|
|
1276
|
+
t.etaSmooth = isFinite(prev) && prev !== 0 ? prev + (remainMin - prev) * 0.35 : remainMin
|
|
1277
|
+
if (Math.abs(t.etaSmooth - remainMin) < 0.03) t.etaSmooth = remainMin
|
|
1278
|
+
remainMin = t.etaSmooth
|
|
1279
|
+
}
|
|
1280
|
+
return {
|
|
1281
|
+
elapsedSec: Math.round(elapsedSec),
|
|
1282
|
+
etaMin: Math.max(0, Math.round(remainMin)),
|
|
1283
|
+
etaBasis: etaSrc,
|
|
1284
|
+
etaP75Min: Math.round(prior.p75 / 60),
|
|
1285
|
+
overMin: overSec > 30 ? Math.max(1, Math.round(overSec / 60)) : 0,
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
function staleOf(sessionId, atMs) {
|
|
1290
|
+
// stale 判定:板在场以 board.updatedAt 为主,否则以自动层 lastActivityAt 为备。
|
|
1291
|
+
const state = states.get(sessionId)
|
|
1292
|
+
const t = taskMap.get(sessionId)
|
|
1293
|
+
let ref = 0
|
|
1294
|
+
if (state && state.enabled && state.items.length > 0) ref = Number(state.updatedAt) || 0
|
|
1295
|
+
else if (t && t.active) ref = Number(t.lastActivityAt) || 0
|
|
1296
|
+
if (!ref) return 0
|
|
1297
|
+
const gap = atMs - ref
|
|
1298
|
+
return gap > FILE_STALE_MS ? Math.max(1, Math.round(gap / 60000)) : 0
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
// 自动层单任务展示载荷:board 开且有 items 时阶段/百分比取板事实,关板退回鲸程旧行为。
|
|
1302
|
+
function autoTaskPayload(t, atMs) {
|
|
1303
|
+
const state = states.get(t.sid)
|
|
1304
|
+
const boardItems = state && state.enabled && state.items.length > 0
|
|
1305
|
+
? state.items.slice().sort((a, b) => a.order - b.order)
|
|
1306
|
+
: null
|
|
1307
|
+
const eta = computeEta(t, boardItems, atMs, true)
|
|
1308
|
+
let stages
|
|
1309
|
+
let current = 0
|
|
1310
|
+
let pct = 0
|
|
1311
|
+
let action = ''
|
|
1312
|
+
let autoStage = true
|
|
1313
|
+
if (boardItems) {
|
|
1314
|
+
stages = boardItems.map((item) => item.title)
|
|
1315
|
+
const doingIndex = boardItems.findIndex((item) => item.status === 'doing')
|
|
1316
|
+
const firstOpen = boardItems.findIndex((item) => item.status !== 'done')
|
|
1317
|
+
current = doingIndex >= 0 ? doingIndex : firstOpen >= 0 ? firstOpen : Math.max(0, stages.length - 1)
|
|
1318
|
+
pct = summarize(boardItems).percent
|
|
1319
|
+
const doingItem = doingIndex >= 0 ? boardItems[doingIndex] : null
|
|
1320
|
+
action = doingItem ? doingItem.current || '' : ''
|
|
1321
|
+
autoStage = false
|
|
1322
|
+
} else {
|
|
1323
|
+
stages = guessStages(t.title)
|
|
1324
|
+
const total = Math.max(1, stages.length)
|
|
1325
|
+
current = Math.min(total - 1, Math.floor(t.steps / 3))
|
|
1326
|
+
pct = Math.min(100, Math.round(((t.steps % 3) / 3) * 100))
|
|
1327
|
+
}
|
|
1328
|
+
return {
|
|
1329
|
+
id: t.sid || '',
|
|
1330
|
+
isSub: !!t.isSub,
|
|
1331
|
+
parentId: t.parentId || '',
|
|
1332
|
+
task: t.title,
|
|
1333
|
+
project: t.project,
|
|
1334
|
+
stages,
|
|
1335
|
+
current,
|
|
1336
|
+
pct,
|
|
1337
|
+
action,
|
|
1338
|
+
etaMin: eta.etaMin,
|
|
1339
|
+
status: 'running',
|
|
1340
|
+
steps: t.steps,
|
|
1341
|
+
auto: true,
|
|
1342
|
+
autoStage,
|
|
1343
|
+
boardDriven: !autoStage,
|
|
1344
|
+
startedAt: t.startedAt,
|
|
1345
|
+
updatedAt: t.lastActivityAt,
|
|
1346
|
+
etaBasis: eta.etaBasis,
|
|
1347
|
+
etaP75Min: eta.etaP75Min,
|
|
1348
|
+
overMin: eta.overMin,
|
|
1349
|
+
todoDone: t.todoDone || 0,
|
|
1350
|
+
todoTotal: t.todoTotal || 0,
|
|
1351
|
+
staleMin: staleOf(t.sid, atMs),
|
|
1352
|
+
elapsedSec: eta.elapsedSec,
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
function latestActiveTask() {
|
|
1357
|
+
let latest = null
|
|
1358
|
+
for (const [, t] of taskMap) {
|
|
1359
|
+
if (!t.active) continue
|
|
1360
|
+
if (!latest || t.lastActivityAt >= latest.lastActivityAt) latest = t
|
|
1361
|
+
}
|
|
1362
|
+
return latest
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
function activeCount() {
|
|
1366
|
+
let n = 0
|
|
1367
|
+
for (const [, t] of taskMap) if (t.active) n += 1
|
|
1368
|
+
return n
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
function listActiveTasks() {
|
|
1372
|
+
const atMs = now()
|
|
1373
|
+
const out = []
|
|
1374
|
+
for (const [, t] of taskMap) {
|
|
1375
|
+
if (!t.active) continue
|
|
1376
|
+
const p = autoTaskPayload(t, atMs)
|
|
1377
|
+
p.id = p.id || String(t.sid)
|
|
1378
|
+
p.activeCount = activeCount()
|
|
1379
|
+
out.push(p)
|
|
1380
|
+
}
|
|
1381
|
+
// 鲸程兼容层:board 关闭的会话若有文件上报任务,合并/独立成条(blocked 也要显示)。
|
|
1382
|
+
const reportsByKey = new Map()
|
|
1383
|
+
for (const rep of readFileTasks()) {
|
|
1384
|
+
const key = String(rep.reportId || 'legacy')
|
|
1385
|
+
const prev = reportsByKey.get(key)
|
|
1386
|
+
if (!prev || (Number(rep.updatedAt) || 0) >= (Number(prev.updatedAt) || 0)) reportsByKey.set(key, rep)
|
|
1387
|
+
}
|
|
1388
|
+
for (const fileTask of reportsByKey.values()) {
|
|
1389
|
+
const fileStatus = String(fileTask.status || '')
|
|
1390
|
+
if (fileStatus !== 'running' && fileStatus !== 'blocked') continue
|
|
1391
|
+
const owner = out.find((x) => x.id === String(fileTask.session || ''))
|
|
1392
|
+
if (owner && !isEnabled(owner.id)) {
|
|
1393
|
+
out[out.indexOf(owner)] = {
|
|
1394
|
+
...owner,
|
|
1395
|
+
task: fileTask.task || owner.task,
|
|
1396
|
+
stages: Array.isArray(fileTask.stages) && fileTask.stages.length ? fileTask.stages : owner.stages,
|
|
1397
|
+
current: Number(fileTask.current) || 0,
|
|
1398
|
+
pct: Number(fileTask.pct) || 0,
|
|
1399
|
+
action: fileTask.action || '',
|
|
1400
|
+
etaMin: Math.max(0, Number(fileTask.etaMin) || 0),
|
|
1401
|
+
status: fileStatus,
|
|
1402
|
+
issue: fileStatus === 'blocked' ? String(fileTask.issue || '') : '',
|
|
1403
|
+
auto: false,
|
|
1404
|
+
autoStage: false,
|
|
1405
|
+
updatedAt: Math.max(Number(owner.updatedAt) || 0, Number(fileTask.updatedAt) || 0),
|
|
1406
|
+
}
|
|
1407
|
+
} else if (!owner) {
|
|
1408
|
+
out.push({
|
|
1409
|
+
...fileTask,
|
|
1410
|
+
id: 'file:' + String(fileTask.reportId || 'legacy'),
|
|
1411
|
+
fileSource: fileTask.source || 'legacy',
|
|
1412
|
+
auto: false,
|
|
1413
|
+
steps: 0,
|
|
1414
|
+
activeCount: activeCount(),
|
|
1415
|
+
status: fileStatus,
|
|
1416
|
+
issue: fileStatus === 'blocked' ? String(fileTask.issue || '') : '',
|
|
1417
|
+
startedAt: Number(fileTask.startedAt) || atMs,
|
|
1418
|
+
})
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
out.sort((a, b) => (Number(b.updatedAt) || 0) - (Number(a.updatedAt) || 0))
|
|
1422
|
+
return out
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
function buildTask() {
|
|
1426
|
+
const list = listActiveTasks()
|
|
1427
|
+
const reported = list.find((t) => t.auto === false && t.isSub !== true) || list.find((t) => t.auto === false)
|
|
1428
|
+
if (reported) return { ...reported, activeCount: activeCount() }
|
|
1429
|
+
const mainTask = list.find((t) => t.isSub !== true)
|
|
1430
|
+
if (mainTask) return { ...mainTask, activeCount: activeCount() }
|
|
1431
|
+
if (list.length) return { ...list[0], activeCount: activeCount() }
|
|
1432
|
+
if (doneList.length) {
|
|
1433
|
+
const d = doneList[doneList.length - 1]
|
|
1434
|
+
if (now() - d.at < cfg.doneKeepMs) {
|
|
1435
|
+
return {
|
|
1436
|
+
task: d.title, project: d.project, stages: [], current: 0, pct: 100,
|
|
1437
|
+
action: '', etaMin: 0, status: 'done', steps: 0, auto: true,
|
|
1438
|
+
startedAt: d.startedAt, endedAt: d.endedAt, updatedAt: d.endedAt, activeCount: 0,
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
return null
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
const disposers = []
|
|
1446
|
+
try {
|
|
1447
|
+
disposers.push(ctx.on('agent/created', ({ agent }) => installAgentHook(agent)))
|
|
1448
|
+
} catch (_err) {}
|
|
1449
|
+
for (const agent of agents?.list?.() ?? []) installAgentHook(agent)
|
|
1450
|
+
|
|
1451
|
+
disposers.push(ctx.on('session/event', (session, event) => {
|
|
1452
|
+
try {
|
|
1453
|
+
if (!event) return
|
|
1454
|
+
const sid = session && session.id ? String(session.id) : 'default'
|
|
1455
|
+
const type = event.type
|
|
1456
|
+
// 观察者原料:最近输出(assistant/message)与最近动作(tool/call)都是会话事实
|
|
1457
|
+
if (type === 'tool/call') {
|
|
1458
|
+
recordTool(sid, event.data)
|
|
1459
|
+
return
|
|
1460
|
+
}
|
|
1461
|
+
if (type === 'assistant/message') {
|
|
1462
|
+
recordOutput(sid, event.data)
|
|
1463
|
+
return
|
|
1464
|
+
}
|
|
1465
|
+
if (type === 'subagent/descriptor') {
|
|
1466
|
+
const dd = event.data || {}
|
|
1467
|
+
const label = dd && typeof dd.label === 'string' ? dd.label.trim() : ''
|
|
1468
|
+
if (label) {
|
|
1469
|
+
const sub = taskOf(sid)
|
|
1470
|
+
sub.subLabel = label
|
|
1471
|
+
sub.isSub = true
|
|
1472
|
+
markLineage(sub, session)
|
|
1473
|
+
if (sub.active) {
|
|
1474
|
+
sub.title = label
|
|
1475
|
+
sub.lastActivityAt = now()
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
return
|
|
1479
|
+
}
|
|
1480
|
+
if (type === 'todo/write' || type === 'todo/update') {
|
|
1481
|
+
const td = event.data || {}
|
|
1482
|
+
const todos = Array.isArray(td.todos) ? td.todos : []
|
|
1483
|
+
if (todos.length) {
|
|
1484
|
+
const tk = taskOf(sid)
|
|
1485
|
+
let done = 0
|
|
1486
|
+
for (const it of todos) {
|
|
1487
|
+
const st = it && it.status ? String(it.status) : ''
|
|
1488
|
+
if (st === 'completed') done += 1
|
|
1489
|
+
}
|
|
1490
|
+
tk.todoDone = done
|
|
1491
|
+
tk.todoTotal = todos.length
|
|
1492
|
+
tk.todoItems = todos
|
|
1493
|
+
.filter((it) => it && String(it.status || '') !== 'completed')
|
|
1494
|
+
.map((it) => String(it.content || ''))
|
|
1495
|
+
.filter(Boolean)
|
|
1496
|
+
.slice(0, 8)
|
|
1497
|
+
tk.lastActivityAt = now()
|
|
1498
|
+
}
|
|
1499
|
+
return
|
|
1500
|
+
}
|
|
1501
|
+
if (type === 'user/message') {
|
|
1502
|
+
const d = event.data
|
|
1503
|
+
const src = d && d.source
|
|
1504
|
+
if (src && src.kind === 'user') {
|
|
1505
|
+
const t = textOf(d)
|
|
1506
|
+
if (t) {
|
|
1507
|
+
userTextMap.set(sid, t)
|
|
1508
|
+
const task = taskMap.get(sid)
|
|
1509
|
+
if (task && task.active) {
|
|
1510
|
+
markLineage(task, session)
|
|
1511
|
+
if (task.isSub) {
|
|
1512
|
+
// 子任务只在第一条任务描述时命名,后续追问不改名。
|
|
1513
|
+
if (!task.subTitled) {
|
|
1514
|
+
task.title = subTitleOf(task, t)
|
|
1515
|
+
task.subTitled = true
|
|
1516
|
+
}
|
|
1517
|
+
} else {
|
|
1518
|
+
task.title = summarizeTitle(t)
|
|
1519
|
+
}
|
|
1520
|
+
task.lastActivityAt = now()
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return
|
|
1525
|
+
}
|
|
1526
|
+
if (type === 'turn/start') {
|
|
1527
|
+
const task = taskOf(sid)
|
|
1528
|
+
markLineage(task, session)
|
|
1529
|
+
const pendingText = userTextMap.get(sid) || ''
|
|
1530
|
+
task.open = true
|
|
1531
|
+
// 辅助 LLM 的每回合配额:开新回合重置
|
|
1532
|
+
obsOf(sid).assistantCalls = 0
|
|
1533
|
+
if (!task.active) {
|
|
1534
|
+
task.active = true
|
|
1535
|
+
task.startedAt = now()
|
|
1536
|
+
task.steps = 0
|
|
1537
|
+
task._stepTimes = []
|
|
1538
|
+
task.todoDone = 0
|
|
1539
|
+
task.todoTotal = 0
|
|
1540
|
+
task.etaSmooth = 0
|
|
1541
|
+
task.lastActivityAt = now()
|
|
1542
|
+
task.title = pendingText ? (task.isSub ? subTitleOf(task, pendingText) : summarizeTitle(pendingText)) : '处理中'
|
|
1543
|
+
if (task.isSub && pendingText) task.subTitled = true
|
|
1544
|
+
task.project = ''
|
|
1545
|
+
try {
|
|
1546
|
+
const cwd = session && session.header && session.header.cwd ? String(session.header.cwd) : ''
|
|
1547
|
+
if (cwd) task.project = path.basename(cwd)
|
|
1548
|
+
} catch (_err) {}
|
|
1549
|
+
} else {
|
|
1550
|
+
task.lastActivityAt = now()
|
|
1551
|
+
}
|
|
1552
|
+
if (pendingText) userTextMap.delete(sid)
|
|
1553
|
+
if (live.status === 'idle') live.status = 'running'
|
|
1554
|
+
if (!live.startAt) live.startAt = now()
|
|
1555
|
+
live.lastActivityAt = now()
|
|
1556
|
+
return
|
|
1557
|
+
}
|
|
1558
|
+
if (type === 'step/start') {
|
|
1559
|
+
// 观察者:距上次写板的步数与周期自动补(无板/全完成时内部直接返回)
|
|
1560
|
+
const o = obsOf(sid)
|
|
1561
|
+
o.stepsSinceBoard += 1
|
|
1562
|
+
o.stepsSinceModel += 1
|
|
1563
|
+
maybeAutoSync(sid, now())
|
|
1564
|
+
void maybeAskAssistant(sid, now())
|
|
1565
|
+
const task = taskMap.get(sid)
|
|
1566
|
+
if (task && task.active) {
|
|
1567
|
+
task.steps += 1
|
|
1568
|
+
if (!Array.isArray(task._stepTimes)) task._stepTimes = []
|
|
1569
|
+
task._stepTimes.push(now())
|
|
1570
|
+
task.lastActivityAt = now()
|
|
1571
|
+
}
|
|
1572
|
+
live.steps += 1
|
|
1573
|
+
live.lastActivityAt = now()
|
|
1574
|
+
if (!live.startAt) live.startAt = now()
|
|
1575
|
+
if (live.status === 'idle') live.status = 'running'
|
|
1576
|
+
return
|
|
1577
|
+
}
|
|
1578
|
+
if (type === 'turn/end') {
|
|
1579
|
+
const task = taskOf(sid)
|
|
1580
|
+
if (task.active) {
|
|
1581
|
+
task.open = false
|
|
1582
|
+
task.lastActivityAt = now()
|
|
1583
|
+
endTask(sid)
|
|
1584
|
+
}
|
|
1585
|
+
return
|
|
1586
|
+
}
|
|
1587
|
+
} catch (_err) {}
|
|
1588
|
+
}))
|
|
1589
|
+
|
|
1590
|
+
try {
|
|
1591
|
+
disposers.push(ctx.on('agent/status', ({ agent, status }) => {
|
|
1592
|
+
const st = String(status || 'idle')
|
|
1593
|
+
live.status = st
|
|
1594
|
+
live.lastActivityAt = now()
|
|
1595
|
+
if (st === 'running' && !live.startAt) live.startAt = now()
|
|
1596
|
+
if (agent && agent.id && st === 'running') {
|
|
1597
|
+
const task = taskMap.get(String(agent.id))
|
|
1598
|
+
if (task && task.active) task.lastActivityAt = now()
|
|
1599
|
+
}
|
|
1600
|
+
// idle 不直接结束任务:maintenance 阶段也报 idle,会误杀进行中任务;结束统一走 sweep。
|
|
1601
|
+
}))
|
|
1602
|
+
} catch (_err) {}
|
|
1603
|
+
|
|
1604
|
+
// 周期兜底:turn 打开但 10 分钟无活动 → 视为卡死结束。
|
|
1605
|
+
const sweepTimer = setInterval(() => {
|
|
1606
|
+
try {
|
|
1607
|
+
const atMs = now()
|
|
1608
|
+
for (const [sid, t] of taskMap) {
|
|
1609
|
+
if (t.active && t.open === true && atMs - t.lastActivityAt > IDLE_END_MS) endTask(sid)
|
|
1610
|
+
}
|
|
1611
|
+
} catch (_err) {}
|
|
1612
|
+
}, SWEEP_MS)
|
|
1613
|
+
if (typeof sweepTimer?.unref === 'function') sweepTimer.unref()
|
|
1614
|
+
|
|
1615
|
+
// ==========================================================================
|
|
1616
|
+
// D. progressAnchor 只读锚点面(service + HTTP 双平面,同一 builder)
|
|
1617
|
+
// 消费契约(保护区必嵌 / userEdits 硬约束 / rev 对账 / staleMin 标注)见 README。
|
|
1618
|
+
// ==========================================================================
|
|
1619
|
+
|
|
1620
|
+
function buildAnchor(sessionId, atMs = now()) {
|
|
1621
|
+
const state = states.get(sessionId)
|
|
1622
|
+
const t = taskMap.get(sessionId)
|
|
1623
|
+
const items = state ? state.items.slice().sort((a, b) => a.order - b.order) : []
|
|
1624
|
+
const summary = summarize(items)
|
|
1625
|
+
const inFlight = items
|
|
1626
|
+
.filter((item) => item.status === 'doing' || item.status === 'blocked')
|
|
1627
|
+
.map((item) => ({
|
|
1628
|
+
id: item.id,
|
|
1629
|
+
title: item.title,
|
|
1630
|
+
status: item.status,
|
|
1631
|
+
percent: item.percent,
|
|
1632
|
+
current: item.current || '',
|
|
1633
|
+
next: item.next || '',
|
|
1634
|
+
}))
|
|
1635
|
+
const pendingChanges = state ? state.userChanges.filter((c) => c.revision > state.agentSeenRevision) : []
|
|
1636
|
+
const userEdits = pendingChanges.slice(-20).map((c) => ({
|
|
1637
|
+
revision: c.revision,
|
|
1638
|
+
at: c.at,
|
|
1639
|
+
kind: c.kind,
|
|
1640
|
+
itemId: c.itemId,
|
|
1641
|
+
title: c.title,
|
|
1642
|
+
fields: (c.fields || [])
|
|
1643
|
+
.filter((f) => f.field !== 'order')
|
|
1644
|
+
.map((f) => ({ field: f.field, from: compactValue(f.from), to: compactValue(f.to) })),
|
|
1645
|
+
}))
|
|
1646
|
+
// 无在场任务(含 turn/end 后)时时间层给零值 + etaBasis='none'(不给伪 ETA,
|
|
1647
|
+
// steps 保留供"上一回合跑了多久"参考);在场时走纯函数 computeEta
|
|
1648
|
+
// (smoothing=false)——同 (revision, steps, now) 必同字节。
|
|
1649
|
+
const onAir = Boolean(t && t.startedAt && t.active)
|
|
1650
|
+
let time
|
|
1651
|
+
if (!onAir) {
|
|
1652
|
+
time = {
|
|
1653
|
+
startedAt: 0, elapsedSec: 0, steps: t ? Number(t.steps) || 0 : 0, etaMin: 0,
|
|
1654
|
+
etaBasis: 'none', etaP75Min: 0, overMin: 0, staleMin: staleOf(sessionId, atMs),
|
|
1655
|
+
todoDone: t ? Number(t.todoDone) || 0 : 0, todoTotal: t ? Number(t.todoTotal) || 0 : 0,
|
|
1656
|
+
}
|
|
1657
|
+
} else {
|
|
1658
|
+
const eta = computeEta(t, state && state.enabled && items.length ? items : null, atMs, false)
|
|
1659
|
+
time = {
|
|
1660
|
+
startedAt: Number(t.startedAt) || 0,
|
|
1661
|
+
elapsedSec: eta.elapsedSec,
|
|
1662
|
+
steps: Number(t.steps) || 0,
|
|
1663
|
+
etaMin: eta.etaMin,
|
|
1664
|
+
etaBasis: eta.etaBasis,
|
|
1665
|
+
etaP75Min: eta.etaP75Min,
|
|
1666
|
+
overMin: eta.overMin,
|
|
1667
|
+
staleMin: staleOf(sessionId, atMs),
|
|
1668
|
+
todoDone: Number(t.todoDone) || 0,
|
|
1669
|
+
todoTotal: Number(t.todoTotal) || 0,
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
return {
|
|
1673
|
+
version: ANCHOR_VERSION,
|
|
1674
|
+
sessionId: String(sessionId || ''),
|
|
1675
|
+
revision: state ? state.revision : 0,
|
|
1676
|
+
updatedAt: state ? Number(state.updatedAt) || 0 : 0,
|
|
1677
|
+
board: {
|
|
1678
|
+
enabled: Boolean(state && state.enabled),
|
|
1679
|
+
summary,
|
|
1680
|
+
inFlight,
|
|
1681
|
+
pendingUserChanges: pendingChanges.length,
|
|
1682
|
+
},
|
|
1683
|
+
time,
|
|
1684
|
+
userEdits,
|
|
1685
|
+
persistent: Boolean(unit) && !storageError.includes('失败'),
|
|
1686
|
+
// 预留位:prime-memory 关闭槽位尾迹扇出(定性方案见 docs/,本轮恒 null)。
|
|
1687
|
+
slotTrail: null,
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
// —— service 平面(同进程零 I/O;宿主无 provide 面时静默只留 HTTP)——
|
|
1692
|
+
const anchorApi = {
|
|
1693
|
+
version: ANCHOR_VERSION,
|
|
1694
|
+
get(sessionId, atMs) {
|
|
1695
|
+
return buildAnchor(String(sessionId || ''), finiteNumber(atMs) ?? now())
|
|
1696
|
+
},
|
|
1697
|
+
list(atMs) {
|
|
1698
|
+
const ids = new Set([...states.keys(), ...taskMap.keys()])
|
|
1699
|
+
return [...ids].map((sid) => buildAnchor(sid, finiteNumber(atMs) ?? now()))
|
|
1700
|
+
},
|
|
1701
|
+
}
|
|
1702
|
+
if (typeof ctx.provide === 'function') {
|
|
1703
|
+
try {
|
|
1704
|
+
const off = ctx.provide('progressAnchor', () => anchorApi)
|
|
1705
|
+
if (typeof off === 'function') disposers.push(off)
|
|
1706
|
+
} catch (_err) {
|
|
1707
|
+
// 宿主 provide 面形状不符:service 平面缺席,HTTP 平面照旧(锚点主出口)。
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
// —— sessionProjection 平面:全局多会话聚合(rev 稳定字段;时间字段走 HTTP/service)——
|
|
1712
|
+
function aggregateVersion() {
|
|
1713
|
+
let v = 0
|
|
1714
|
+
for (const s of states.values()) v += s.revision * 2 + (s.enabled === true ? 1 : 0)
|
|
1715
|
+
for (const t of taskMap.values()) v += (Number(t.steps) || 0) + (t.active ? 1 : 0)
|
|
1716
|
+
return v
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
function buildProjectionState() {
|
|
1720
|
+
const sessions = []
|
|
1721
|
+
for (const [sid, s] of states) {
|
|
1722
|
+
const t = taskMap.get(sid)
|
|
1723
|
+
const items = s.items.slice().sort((a, b) => a.order - b.order)
|
|
1724
|
+
sessions.push({
|
|
1725
|
+
sessionId: sid,
|
|
1726
|
+
enabled: s.enabled === true,
|
|
1727
|
+
revision: s.revision,
|
|
1728
|
+
summary: summarize(items),
|
|
1729
|
+
pendingUserChanges: s.userChanges.filter((c) => c.revision > s.agentSeenRevision).length,
|
|
1730
|
+
steps: t ? Number(t.steps) || 0 : 0,
|
|
1731
|
+
startedAt: t ? Number(t.startedAt) || 0 : 0,
|
|
1732
|
+
boardUpdatedAt: Number(s.updatedAt) || 0,
|
|
1733
|
+
})
|
|
1734
|
+
}
|
|
1735
|
+
sessions.sort((a, b) => a.sessionId.localeCompare(b.sessionId))
|
|
1736
|
+
return { version: ANCHOR_VERSION, agg: aggregateVersion(), sessions }
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
const projectionParse = (value, what) => {
|
|
1740
|
+
if (!isObject(value)) throw new Error(`${what}: 期望普通对象`)
|
|
1741
|
+
if (typeof value.version !== 'number' || typeof value.agg !== 'number' || !Array.isArray(value.sessions)) {
|
|
1742
|
+
throw new Error(`${what}: version/agg/sessions 形状不符`)
|
|
1743
|
+
}
|
|
1744
|
+
return value
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
ctx.inject(['sessionProjections'], (injected) => {
|
|
1748
|
+
const registry = injected && injected.sessionProjections
|
|
1749
|
+
if (!registry || typeof registry.register !== 'function') return
|
|
1750
|
+
try {
|
|
1751
|
+
const definition = {
|
|
1752
|
+
key: 'progressAnchor',
|
|
1753
|
+
stateSchema: { parse: (v) => projectionParse(v, 'progressAnchor.state') },
|
|
1754
|
+
init: () => buildProjectionState(),
|
|
1755
|
+
apply: (state) => (aggregateVersion() === state.agg ? state : buildProjectionState()),
|
|
1756
|
+
wire: {
|
|
1757
|
+
viewSchema: { parse: (v) => projectionParse(v, 'progressAnchor.view') },
|
|
1758
|
+
view: (state) => state,
|
|
1759
|
+
},
|
|
1760
|
+
schema: { parse: (v) => projectionParse(v, 'progressAnchor.view') },
|
|
1761
|
+
view: (state) => state,
|
|
1762
|
+
stateVersion: 0,
|
|
1763
|
+
}
|
|
1764
|
+
const off = registry.register(definition)
|
|
1765
|
+
if (typeof off === 'function') disposers.push(off)
|
|
1766
|
+
} catch (_err) {
|
|
1767
|
+
// 投影平面缺席/形状不符:消费方按 capability absence 降级,不影响板与锚点主出口。
|
|
1768
|
+
}
|
|
1769
|
+
})
|
|
1770
|
+
|
|
1771
|
+
// ==========================================================================
|
|
1772
|
+
// E. HTTP 路由(union 主前缀 + board 旧前缀别名一版)
|
|
1773
|
+
// ==========================================================================
|
|
1774
|
+
|
|
1775
|
+
const routeDisposers = []
|
|
1776
|
+
|
|
1777
|
+
function sendJson(res, status, body) {
|
|
1778
|
+
const textBody = JSON.stringify(body)
|
|
1779
|
+
res.writeHead(status, {
|
|
1780
|
+
'content-type': 'application/json; charset=utf-8',
|
|
1781
|
+
'cache-control': 'no-store',
|
|
1782
|
+
'content-length': Buffer.byteLength(textBody),
|
|
1783
|
+
})
|
|
1784
|
+
res.end(textBody)
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
async function readJson(req) {
|
|
1788
|
+
let size = 0
|
|
1789
|
+
const chunks = []
|
|
1790
|
+
for await (const chunk of req) {
|
|
1791
|
+
size += chunk.length
|
|
1792
|
+
if (size > MAX_BODY_BYTES) {
|
|
1793
|
+
const error = new Error('请求体过大')
|
|
1794
|
+
error.statusCode = 413
|
|
1795
|
+
throw error
|
|
1796
|
+
}
|
|
1797
|
+
chunks.push(chunk)
|
|
1798
|
+
}
|
|
1799
|
+
try {
|
|
1800
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
|
|
1801
|
+
} catch (_error) {
|
|
1802
|
+
const error = new Error('请求体不是有效 JSON')
|
|
1803
|
+
error.statusCode = 400
|
|
1804
|
+
throw error
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
function readSessionId(req) {
|
|
1809
|
+
const url = new URL(req.url || '/', 'http://localhost')
|
|
1810
|
+
const sessionId = url.searchParams.get('sessionId') || ''
|
|
1811
|
+
return sessionId && sessionId.length <= 240 ? sessionId : ''
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
if (webServer) {
|
|
1815
|
+
// 锚点读接口(压缩插件主用;GET 纯只读,零副作用)
|
|
1816
|
+
routeDisposers.push(
|
|
1817
|
+
webServer.register({
|
|
1818
|
+
kind: 'exact',
|
|
1819
|
+
path: `${ROUTE_BASE}/anchor`,
|
|
1820
|
+
handler: (req, res) => {
|
|
1821
|
+
if (req.method !== 'GET') {
|
|
1822
|
+
res.writeHead(405, { allow: 'GET' })
|
|
1823
|
+
res.end()
|
|
1824
|
+
return
|
|
1825
|
+
}
|
|
1826
|
+
const sessionId = readSessionId(req)
|
|
1827
|
+
if (!sessionId) {
|
|
1828
|
+
sendJson(res, 400, { ok: false, error: '缺少有效的 sessionId' })
|
|
1829
|
+
return
|
|
1830
|
+
}
|
|
1831
|
+
const url = new URL(req.url || '/', 'http://localhost')
|
|
1832
|
+
const atMs = finiteNumber(Number(url.searchParams.get('now'))) ?? now()
|
|
1833
|
+
sendJson(res, 200, { ok: true, anchor: buildAnchor(sessionId, atMs) })
|
|
1834
|
+
},
|
|
1835
|
+
}),
|
|
1836
|
+
)
|
|
1837
|
+
|
|
1838
|
+
// 鲸程兼容状态面(悬浮条轮询)
|
|
1839
|
+
routeDisposers.push(
|
|
1840
|
+
webServer.register({
|
|
1841
|
+
kind: 'exact',
|
|
1842
|
+
path: WIDGET_STATUS_ROUTE,
|
|
1843
|
+
handler: (req, res) => {
|
|
1844
|
+
try {
|
|
1845
|
+
sendJson(res, 200, {
|
|
1846
|
+
ok: true,
|
|
1847
|
+
task: buildTask(),
|
|
1848
|
+
tasks: listActiveTasks(),
|
|
1849
|
+
live,
|
|
1850
|
+
activeCount: activeCount(),
|
|
1851
|
+
config: { pollMs: cfg.pollMs, doneHoldMs: cfg.doneHoldMs },
|
|
1852
|
+
})
|
|
1853
|
+
} catch (_err) {
|
|
1854
|
+
sendJson(res, 200, { ok: false, task: null, live, activeCount: 0 })
|
|
1855
|
+
}
|
|
1856
|
+
},
|
|
1857
|
+
}),
|
|
1858
|
+
)
|
|
1859
|
+
|
|
1860
|
+
// 板路由:union 主前缀 + /progress-board 旧前缀别名(同 handler,保留一版)
|
|
1861
|
+
for (const base of [ROUTE_BASE, LEGACY_BASE]) {
|
|
1862
|
+
routeDisposers.push(
|
|
1863
|
+
webServer.register({
|
|
1864
|
+
kind: 'exact',
|
|
1865
|
+
path: `${base}/snapshot`,
|
|
1866
|
+
handler: (req, res) => {
|
|
1867
|
+
if (req.method !== 'GET') {
|
|
1868
|
+
res.writeHead(405, { allow: 'GET' })
|
|
1869
|
+
res.end()
|
|
1870
|
+
return
|
|
1871
|
+
}
|
|
1872
|
+
const sessionId = readSessionId(req)
|
|
1873
|
+
if (!sessionId) {
|
|
1874
|
+
sendJson(res, 400, { ok: false, error: '缺少有效的 sessionId' })
|
|
1875
|
+
return
|
|
1876
|
+
}
|
|
1877
|
+
sendJson(res, 200, publicSnapshot(ensureState(sessionId)))
|
|
1878
|
+
},
|
|
1879
|
+
}),
|
|
1880
|
+
)
|
|
1881
|
+
routeDisposers.push(
|
|
1882
|
+
webServer.register({
|
|
1883
|
+
kind: 'exact',
|
|
1884
|
+
path: `${base}/action`,
|
|
1885
|
+
handler: async (req, res) => {
|
|
1886
|
+
if (req.method !== 'POST') {
|
|
1887
|
+
res.writeHead(405, { allow: 'POST' })
|
|
1888
|
+
res.end()
|
|
1889
|
+
return
|
|
1890
|
+
}
|
|
1891
|
+
if (!String(req.headers['content-type'] || '').toLowerCase().startsWith('application/json')) {
|
|
1892
|
+
sendJson(res, 415, { ok: false, error: 'content-type 必须是 application/json' })
|
|
1893
|
+
return
|
|
1894
|
+
}
|
|
1895
|
+
try {
|
|
1896
|
+
const body = await readJson(req)
|
|
1897
|
+
const result = await applyChanges({
|
|
1898
|
+
sessionId: body.sessionId,
|
|
1899
|
+
changes: body.changes,
|
|
1900
|
+
origin: 'user',
|
|
1901
|
+
expectedRevision: body.expectedRevision,
|
|
1902
|
+
ackUserRevision: undefined,
|
|
1903
|
+
})
|
|
1904
|
+
sendJson(res, 200, { ok: true, ...result.snapshot, changed: result.changed })
|
|
1905
|
+
} catch (error) {
|
|
1906
|
+
const status = error && error.statusCode ? error.statusCode : 400
|
|
1907
|
+
sendJson(res, status, {
|
|
1908
|
+
ok: false,
|
|
1909
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1910
|
+
...(error && error.snapshot ? { snapshot: error.snapshot } : {}),
|
|
1911
|
+
})
|
|
1912
|
+
}
|
|
1913
|
+
},
|
|
1914
|
+
}),
|
|
1915
|
+
)
|
|
1916
|
+
routeDisposers.push(
|
|
1917
|
+
webServer.register({
|
|
1918
|
+
kind: 'exact',
|
|
1919
|
+
path: `${base}/active`,
|
|
1920
|
+
handler: async (req, res) => {
|
|
1921
|
+
if (req.method !== 'POST') {
|
|
1922
|
+
res.writeHead(405, { allow: 'POST' })
|
|
1923
|
+
res.end()
|
|
1924
|
+
return
|
|
1925
|
+
}
|
|
1926
|
+
if (!String(req.headers['content-type'] || '').toLowerCase().startsWith('application/json')) {
|
|
1927
|
+
sendJson(res, 415, { ok: false, error: 'content-type 必须是 application/json' })
|
|
1928
|
+
return
|
|
1929
|
+
}
|
|
1930
|
+
try {
|
|
1931
|
+
const body = await readJson(req)
|
|
1932
|
+
const sessionId = body.sessionId
|
|
1933
|
+
if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 240) {
|
|
1934
|
+
sendJson(res, 400, { ok: false, error: '缺少有效的 sessionId' })
|
|
1935
|
+
return
|
|
1936
|
+
}
|
|
1937
|
+
if (typeof body.active !== 'boolean') {
|
|
1938
|
+
sendJson(res, 400, { ok: false, error: 'active 必须是布尔值' })
|
|
1939
|
+
return
|
|
1940
|
+
}
|
|
1941
|
+
const source = body.source === 'command' || body.source === 'user' ? body.source : 'panel'
|
|
1942
|
+
if (body.active) {
|
|
1943
|
+
setEnabled(sessionId, true)
|
|
1944
|
+
} else if (source !== 'panel') {
|
|
1945
|
+
// 面板卸载不是用户决定:收起侧栏/切换视图不得静默关掉 agent 工具。
|
|
1946
|
+
setEnabled(sessionId, false)
|
|
1947
|
+
}
|
|
1948
|
+
sendJson(res, 200, { ok: true, enabled: isEnabled(sessionId), source })
|
|
1949
|
+
} catch (error) {
|
|
1950
|
+
const status = error && error.statusCode ? error.statusCode : 400
|
|
1951
|
+
sendJson(res, status, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
1952
|
+
}
|
|
1953
|
+
},
|
|
1954
|
+
}),
|
|
1955
|
+
)
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
ctx.effect(() => () => {
|
|
1960
|
+
for (const dispose of routeDisposers.splice(0)) dispose()
|
|
1961
|
+
if (unit) unit.close().catch(() => {})
|
|
1962
|
+
}, 'progress-union: http routes and storage')
|
|
1963
|
+
|
|
1964
|
+
// ==========================================================================
|
|
1965
|
+
// F. 工具 / 命令 / 注入绑定(board 照板,命名空间改 union)
|
|
1966
|
+
// ==========================================================================
|
|
1967
|
+
|
|
1968
|
+
ctx.effect(
|
|
1969
|
+
() =>
|
|
1970
|
+
tools.register({
|
|
1971
|
+
name: 'progress_update',
|
|
1972
|
+
description:
|
|
1973
|
+
'维护用户可见进度板。每个用户回合开始时若板为空,先调用本工具建立任务,再执行其他操作。只在子目标完成、状态/百分比实质变化、用户新任务或用户改动时增量更新;只发变化项,不重发整份计划。用户改动处理后传 ackUserRevision;仅确认传 changes=[]。',
|
|
1974
|
+
parameters: {
|
|
1975
|
+
type: 'object',
|
|
1976
|
+
additionalProperties: false,
|
|
1977
|
+
properties: {
|
|
1978
|
+
changes: {
|
|
1979
|
+
type: 'array',
|
|
1980
|
+
maxItems: MAX_CHANGES,
|
|
1981
|
+
description: '增量补丁;新增不传 id,更新传 id 或精确 title。',
|
|
1982
|
+
items: {
|
|
1983
|
+
type: 'object',
|
|
1984
|
+
additionalProperties: false,
|
|
1985
|
+
properties: {
|
|
1986
|
+
id: { type: 'string' },
|
|
1987
|
+
title: { type: 'string' },
|
|
1988
|
+
status: { type: 'string', enum: ['todo', 'doing', 'done', 'blocked'] },
|
|
1989
|
+
percent: { type: 'number', minimum: 0, maximum: 100 },
|
|
1990
|
+
current: { type: 'string' },
|
|
1991
|
+
next: { type: 'string' },
|
|
1992
|
+
approach: { type: 'string' },
|
|
1993
|
+
note: { type: 'string' },
|
|
1994
|
+
remove: { type: 'boolean' },
|
|
1995
|
+
},
|
|
1996
|
+
},
|
|
1997
|
+
},
|
|
1998
|
+
ackUserRevision: { type: 'integer', minimum: 0 },
|
|
1999
|
+
},
|
|
2000
|
+
required: ['changes'],
|
|
2001
|
+
},
|
|
2002
|
+
output: {
|
|
2003
|
+
schema: {
|
|
2004
|
+
type: 'object',
|
|
2005
|
+
additionalProperties: true,
|
|
2006
|
+
properties: {
|
|
2007
|
+
ok: { type: 'boolean' },
|
|
2008
|
+
revision: { type: 'number' },
|
|
2009
|
+
summary: { type: 'object', additionalProperties: true },
|
|
2010
|
+
changed: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
2011
|
+
},
|
|
2012
|
+
},
|
|
2013
|
+
render(_args, value) {
|
|
2014
|
+
return [{ type: 'text', text: JSON.stringify(value, null, 2) }]
|
|
2015
|
+
},
|
|
2016
|
+
},
|
|
2017
|
+
async execute(args, exec) {
|
|
2018
|
+
const agent = exec.agent
|
|
2019
|
+
if (!agent) throw new Error('progress_update 只能在 Agent 会话中调用')
|
|
2020
|
+
if (!isObject(args)) throw new Error('参数必须是对象')
|
|
2021
|
+
if (!Array.isArray(args.changes)) throw new Error('changes 必须是数组')
|
|
2022
|
+
const result = await applyChanges({
|
|
2023
|
+
sessionId: agent.session.id,
|
|
2024
|
+
changes: args.changes,
|
|
2025
|
+
origin: 'agent',
|
|
2026
|
+
expectedRevision: args.expectedRevision,
|
|
2027
|
+
ackUserRevision: args.ackUserRevision,
|
|
2028
|
+
})
|
|
2029
|
+
// 拉通道:把"观察"塞进模型本来就必调的那一次调用——inFlight 明细 + 时间面
|
|
2030
|
+
const anchor = buildAnchor(agent.session.id, now())
|
|
2031
|
+
return {
|
|
2032
|
+
ok: true,
|
|
2033
|
+
revision: result.snapshot.revision,
|
|
2034
|
+
userRevision: result.snapshot.userRevision,
|
|
2035
|
+
agentSeenRevision: result.snapshot.agentSeenRevision,
|
|
2036
|
+
summary: result.snapshot.summary,
|
|
2037
|
+
changed: result.changed,
|
|
2038
|
+
inFlight: anchor.board.inFlight.slice(0, 6),
|
|
2039
|
+
time: {
|
|
2040
|
+
steps: anchor.time.steps,
|
|
2041
|
+
elapsedSec: anchor.time.elapsedSec,
|
|
2042
|
+
etaMin: anchor.time.etaMin,
|
|
2043
|
+
etaBasis: anchor.time.etaBasis,
|
|
2044
|
+
staleMin: anchor.time.staleMin,
|
|
2045
|
+
},
|
|
2046
|
+
}
|
|
2047
|
+
},
|
|
2048
|
+
}, { when: ({ agent }) => isEnabled(sessionOfAgent(agent)) }),
|
|
2049
|
+
'progress-union: agent tool',
|
|
2050
|
+
)
|
|
2051
|
+
|
|
2052
|
+
if (commands) {
|
|
2053
|
+
ctx.effect(
|
|
2054
|
+
() =>
|
|
2055
|
+
commands.register({
|
|
2056
|
+
name: 'progress',
|
|
2057
|
+
description: '启用/关闭进度板工具(默认不加载,避免 token 开销)',
|
|
2058
|
+
input: { hint: '[on|off]' },
|
|
2059
|
+
handler: ({ agent, rawInput }) => {
|
|
2060
|
+
const sessionId = sessionOfAgent(agent)
|
|
2061
|
+
const mode = String(rawInput || '').trim().toLowerCase()
|
|
2062
|
+
if (mode === 'off') {
|
|
2063
|
+
setEnabled(sessionId, false)
|
|
2064
|
+
return { kind: 'success', text: '进度板已关闭;Agent 不再加载进度工具,文件上报协议恢复,手动编辑仍会保存。' }
|
|
2065
|
+
}
|
|
2066
|
+
setEnabled(sessionId, true)
|
|
2067
|
+
return {
|
|
2068
|
+
kind: 'success',
|
|
2069
|
+
text: '进度板已启用;之后在主界面发消息时 Agent 会自动更新,收起侧栏也不会关闭。输入 /progress off 可关闭。',
|
|
2070
|
+
}
|
|
2071
|
+
},
|
|
2072
|
+
}),
|
|
2073
|
+
'progress-union: /progress command',
|
|
2074
|
+
)
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
const agentDisposers = new Map()
|
|
2078
|
+
function bindAgentContext(agent) {
|
|
2079
|
+
const sessionId = sessionOfAgent(agent)
|
|
2080
|
+
if (agentDisposers.has(sessionId)) return
|
|
2081
|
+
const dispose = agent.ctx.effect(
|
|
2082
|
+
() => {
|
|
2083
|
+
const offPolicy = agent.ctx.systemPrompt.section({
|
|
2084
|
+
name: 'progress-union-policy',
|
|
2085
|
+
order: 520,
|
|
2086
|
+
text: () => (isEnabled(sessionId) ? PROGRESS_POLICY : ''),
|
|
2087
|
+
})
|
|
2088
|
+
const offContext = agent.ctx.systemPrompt.context({
|
|
2089
|
+
name: 'progress-union-user-edits',
|
|
2090
|
+
order: 60,
|
|
2091
|
+
text: () => pendingContext(sessionId),
|
|
2092
|
+
})
|
|
2093
|
+
const offKickoff = agent.ctx.systemPrompt.context({
|
|
2094
|
+
name: 'progress-union-kickoff',
|
|
2095
|
+
order: 61,
|
|
2096
|
+
text: () => kickoffContext(sessionId),
|
|
2097
|
+
})
|
|
2098
|
+
// 观察块:清单 + 最近输出/动作 + 滞后催办(每请求重建,不累积)
|
|
2099
|
+
const offObserver = agent.ctx.systemPrompt.context({
|
|
2100
|
+
name: 'progress-union-observer',
|
|
2101
|
+
order: 62,
|
|
2102
|
+
text: () => observerContext(sessionId),
|
|
2103
|
+
})
|
|
2104
|
+
return () => {
|
|
2105
|
+
offPolicy()
|
|
2106
|
+
offContext()
|
|
2107
|
+
offKickoff()
|
|
2108
|
+
offObserver()
|
|
2109
|
+
}
|
|
2110
|
+
},
|
|
2111
|
+
'progress-union: prompt policy, user edits and empty-board kickoff',
|
|
2112
|
+
)
|
|
2113
|
+
agentDisposers.set(sessionId, dispose)
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
ctx.effect(() => {
|
|
2117
|
+
// 存量 agent 不回放 agent/created:显式绑定,让中途启用的插件也能收到用户改动 diff。
|
|
2118
|
+
for (const agent of agents?.list?.() ?? []) bindAgentContext(agent)
|
|
2119
|
+
const offCreated = ctx.on('agent/created', ({ agent }) => bindAgentContext(agent))
|
|
2120
|
+
const offDisposed = ctx.on('agent/disposed', ({ agent }) => {
|
|
2121
|
+
const dispose = agentDisposers.get(sessionOfAgent(agent))
|
|
2122
|
+
if (dispose) {
|
|
2123
|
+
dispose()
|
|
2124
|
+
agentDisposers.delete(sessionOfAgent(agent))
|
|
2125
|
+
}
|
|
2126
|
+
})
|
|
2127
|
+
return () => {
|
|
2128
|
+
offCreated()
|
|
2129
|
+
offDisposed()
|
|
2130
|
+
for (const dispose of agentDisposers.values()) dispose()
|
|
2131
|
+
agentDisposers.clear()
|
|
2132
|
+
}
|
|
2133
|
+
}, 'progress-union: agent contexts')
|
|
2134
|
+
|
|
2135
|
+
ctx.effect(() => () => {
|
|
2136
|
+
clearInterval(sweepTimer)
|
|
2137
|
+
for (const dispose of disposers.splice(0)) {
|
|
2138
|
+
try {
|
|
2139
|
+
dispose()
|
|
2140
|
+
} catch (_err) {}
|
|
2141
|
+
}
|
|
2142
|
+
}, 'progress-union: timers and listeners')
|
|
2143
|
+
|
|
2144
|
+
// 注意:apply 不要 return 任何内省面。cordis 会把 apply 的 resolved value 当 effect
|
|
2145
|
+
// 收集,非函数非空即抛 TypeError("Invalid effect"),整条 entry 不激活(宿主只打一行
|
|
2146
|
+
// "warning: 1 entry did not activate",插件页显示异常)。对外面由 progressAnchor
|
|
2147
|
+
// service 与 /progress-union/* 路由承担。
|
|
2148
|
+
}
|