@xiangyixie/dsh-superagent 0.14.1 → 0.14.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/board.js ADDED
@@ -0,0 +1,891 @@
1
+ /**
2
+ * dsh-superagent — the task board.
3
+ *
4
+ * One loopback page that answers three questions a person actually has:
5
+ * what is each subtask doing right now, what needs me, and how do I start the
6
+ * common kinds of work without writing a prompt.
7
+ *
8
+ * The board is an observer and a remote control, not a second orchestrator:
9
+ * every action goes through the host adapter, which owns the live agents.
10
+ * A broken connection costs nothing because each new stream opens with a full
11
+ * snapshot, and the snapshot is rebuilt from durable run records.
12
+ *
13
+ * @module dsh-superagent/board
14
+ */
15
+ import { randomBytes } from 'node:crypto'
16
+ import fsp from 'node:fs/promises'
17
+ import { createServer } from 'node:http'
18
+ import path from 'node:path'
19
+ import { ACTIVE_STATUSES } from './store.js'
20
+ import { formatMoney } from './cost.js'
21
+ import {
22
+ errorPayload,
23
+ readJson,
24
+ sameToken,
25
+ send,
26
+ sendText,
27
+ statusFor,
28
+ WorkbenchError,
29
+ } from './workbench.js'
30
+ import {
31
+ explainFailure,
32
+ explainRun,
33
+ parameterCopy,
34
+ runStatusLabel,
35
+ skipReason,
36
+ subtaskStatusLabel,
37
+ templateCopy,
38
+ } from './board-messages.js'
39
+
40
+ const DISCOVERY_FILE = 'board.json'
41
+ const MAX_CLIENTS = 16
42
+ const MAX_RUNS = 30
43
+ const MAX_RESULT_CHARS = 24_000
44
+ const MAX_AUDIT_ROWS = 120
45
+ const POLL_MS = 1_000
46
+ const HEARTBEAT_MS = 15_000
47
+ const REQUEST_TIMEOUT_MS = 30_000
48
+ const MAX_BUFFERED_BYTES = 4 * 1024 * 1024
49
+ const ROUTE_HINT = 'GET / serves the board; the JSON API is under /api/board.'
50
+
51
+ const ACTIVE_SUBTASK = new Set(['pending', 'waiting', 'running'])
52
+
53
+ /** @param {unknown} value @returns {string} */
54
+ function messageOf(value) {
55
+ return value instanceof Error ? value.message : String(value)
56
+ }
57
+
58
+ function trimText(value, limit) {
59
+ if (typeof value !== 'string') return null
60
+ const text = value.trim()
61
+ if (!text) return null
62
+ return text.length > limit ? `${text.slice(0, limit)}…` : text
63
+ }
64
+
65
+ function durationMs(from, to) {
66
+ const start = Date.parse(from ?? '')
67
+ if (!Number.isFinite(start)) return null
68
+ const end = to ? Date.parse(to) : Date.now()
69
+ return Number.isFinite(end) ? Math.max(0, end - start) : null
70
+ }
71
+
72
+ /**
73
+ * Shape one subtask for a card: enough to decide whether to stop it, rerun it,
74
+ * or ask why it never started, and no full output (that is a detail request).
75
+ */
76
+ function subtaskCard(run, subtask, { now = Date.now() } = {}) {
77
+ const failure = explainFailure(run, subtask)
78
+ const active = ACTIVE_STATUSES.has(run.status)
79
+ const usage = subtask.usage && typeof subtask.usage === 'object' ? subtask.usage : null
80
+ const cost = subtask.cost ?? null
81
+ const finishedAt = subtask.finishedAt ?? null
82
+ const elapsed = durationMs(subtask.startedAt, finishedAt ?? new Date(now).toISOString())
83
+ return {
84
+ key: subtask.key ?? `w${subtask.index}`,
85
+ index: subtask.index ?? null,
86
+ title: subtask.title ?? '(未命名子任务)',
87
+ status: subtask.status ?? 'pending',
88
+ statusLabel: subtaskStatusLabel(subtask.status),
89
+ attempts: subtask.attempts ?? 0,
90
+ startedAt: subtask.startedAt ?? null,
91
+ finishedAt,
92
+ elapsedMs: elapsed,
93
+ childId: subtask.childId ?? null,
94
+ dependsOn: Array.isArray(subtask.dependsOn) ? subtask.dependsOn : [],
95
+ waitingOn: Array.isArray(subtask.waitingOn) ? subtask.waitingOn : [],
96
+ requires: Array.isArray(subtask.requires) ? subtask.requires : [],
97
+ missingCapabilities: Array.isArray(subtask.missingCapabilities) ? subtask.missingCapabilities : [],
98
+ skipReason: skipReason(subtask, run),
99
+ blockedReason: subtask.blockedReason ?? null,
100
+ unverifiedReason: subtask.unverifiedReason ?? null,
101
+ tokens: usage?.totalTokens ?? null,
102
+ cost: cost ? { text: formatMoney(cost), currency: cost.currency ?? null, unpriced: cost.unpriced ?? [] } : null,
103
+ explanation: failure && (subtask.status === 'failed' || subtask.status === 'blocked'
104
+ || subtask.status === 'unverified' || subtask.status === 'cancelled') ? failure : null,
105
+ hasResult: typeof subtask.result === 'string' && subtask.result.length > 0,
106
+ canCancel: active && ACTIVE_SUBTASK.has(subtask.status),
107
+ canRerun: !active && subtask.status !== 'pending' && subtask.status !== 'waiting',
108
+ }
109
+ }
110
+
111
+ /** Shape one run for the board's left column and its detail cards. */
112
+ function runCard(run, { now = Date.now() } = {}) {
113
+ const subtasks = Array.isArray(run.subtasks) ? run.subtasks : []
114
+ const counts = { total: subtasks.length }
115
+ for (const subtask of subtasks) {
116
+ const key = subtask.status ?? 'pending'
117
+ counts[key] = (counts[key] ?? 0) + 1
118
+ }
119
+ const usage = run.usage && typeof run.usage === 'object' ? run.usage : null
120
+ const cost = run.cost ?? null
121
+ const openAttention = Array.isArray(run.attention?.items)
122
+ ? run.attention.items.filter(item => item && !item.answer)
123
+ : []
124
+ const failure = explainRun(run)
125
+ return {
126
+ id: run.id,
127
+ goal: trimText(run.goal, 300) ?? '(没有目标文本)',
128
+ status: run.status ?? 'unknown',
129
+ statusLabel: runStatusLabel(run.status),
130
+ mode: run.mode ?? 'planned',
131
+ createdAt: run.createdAt ?? null,
132
+ finishedAt: run.finishedAt ?? null,
133
+ elapsedMs: durationMs(run.createdAt, run.finishedAt ?? new Date(now).toISOString()),
134
+ active: ACTIVE_STATUSES.has(run.status),
135
+ cancelPending: run.cancelPending === true,
136
+ tokens: usage?.totalTokens ?? null,
137
+ cost: cost ? { text: formatMoney(cost), currency: cost.currency ?? null, unpriced: cost.unpriced ?? [] } : null,
138
+ counts,
139
+ attentionCount: openAttention.length,
140
+ error: run.error ? trimText(String(run.error), 500) : null,
141
+ explanation: failure,
142
+ preflight: run.preflight ?? null,
143
+ planNeedsInput: Array.isArray(run.plan?.needsInput) ? run.plan.needsInput.length : 0,
144
+ subtasks: subtasks.map(subtask => subtaskCard(run, subtask, { now })),
145
+ }
146
+ }
147
+
148
+ function optionList(item) {
149
+ return Array.isArray(item?.options) ? item.options.filter(option => typeof option === 'string' && option.trim()) : []
150
+ }
151
+
152
+ /**
153
+ * Collect everything that actually waits for a person.
154
+ *
155
+ * The id is the routing key for the answer endpoint, so it names the kind and
156
+ * the exact object; nothing is answered by array position.
157
+ */
158
+ function buildInbox(runs, extras = []) {
159
+ const items = []
160
+ for (const run of runs) {
161
+ const goal = trimText(run.goal, 160) ?? run.id
162
+ const open = Array.isArray(run.attention?.items)
163
+ ? run.attention.items.filter(item => item && !item.answer)
164
+ : []
165
+ // A question left open by a run that can no longer move is history, not a
166
+ // task: answering it changes nothing. Keep only the runs an answer can
167
+ // still advance — live ones, and a planner that stopped before planning.
168
+ const answerable = ACTIVE_STATUSES.has(run.status)
169
+ || (run.status === 'failed' && (run.subtasks ?? []).length === 0)
170
+ for (const [position, item] of answerable ? open.entries() : []) {
171
+ const id = item.id ?? `q${position + 1}`
172
+ items.push({
173
+ id: `question:${run.id}:${id}`,
174
+ kind: 'question',
175
+ kindLabel: '需要你回答',
176
+ runId: run.id,
177
+ runGoal: goal,
178
+ title: trimText(item.question, 300) ?? '运行需要你的一个决定',
179
+ what: `运行「${goal}」停在这里,等你回答:${trimText(item.question, 200) ?? '一个执行者无法自行决定的问题'}`,
180
+ why: trimText(item.reason, 300)
181
+ ?? (item.source === 'planner'
182
+ ? '规划器无法从目标里推断出这一点,凭猜测开工会把整次运行带偏。'
183
+ : '执行者遇到了只有你能做的判断,停下比自行假设更安全。'),
184
+ options: optionList(item),
185
+ impact: '回答会作为一条明确指令交给这次运行,未完成的部分会继续;不会新开一次运行。',
186
+ input: 'choice-or-text',
187
+ canAnswer: true,
188
+ })
189
+ }
190
+ for (const subtask of run.subtasks ?? []) {
191
+ if (subtask.status === 'unverified') {
192
+ items.push({
193
+ id: `review:${run.id}:${subtask.key}`,
194
+ kind: 'review',
195
+ kindLabel: '需要你验收',
196
+ runId: run.id,
197
+ runGoal: goal,
198
+ subtaskKey: subtask.key,
199
+ title: `验收「${subtask.title || subtask.key}」的交付物`,
200
+ what: `${subtask.unverifiedReason || '当前会话没有能力判断这个交付物是否正确。'}`,
201
+ why: '模型自己说完成不算数;这一票需要人看一眼。通过后它会进入最终报告,重做则会重新执行这一条。',
202
+ options: ['确认通过', '要求重做'],
203
+ impact: '「确认通过」把这条件任务计为完成并重新汇总报告;「要求重做」只重跑这一条。',
204
+ input: 'choice-or-text',
205
+ canAnswer: true,
206
+ })
207
+ }
208
+ if (subtask.status === 'blocked') {
209
+ const missing = Array.isArray(subtask.missingCapabilities) ? subtask.missingCapabilities : []
210
+ items.push({
211
+ id: `blocked:${run.id}:${subtask.key}`,
212
+ kind: 'capability',
213
+ kindLabel: '缺少能力',
214
+ runId: run.id,
215
+ runGoal: goal,
216
+ subtaskKey: subtask.key,
217
+ title: `「${subtask.title || subtask.key}」缺少 ${missing.join('、') || '所需工具'},没有启动`,
218
+ what: `规划里这条子任务声明需要 ${missing.join('、') || '一个当前会话没有的工具'},预检时被拦下,零 token 消耗。`,
219
+ why: '没有对应工具就开工,模型只会编造结果;所以这里选择不启动。',
220
+ options: ['我已补上能力,重跑这条'],
221
+ impact: '会先检查当前会话是否真的有这个工具,然后只重跑这一条子任务。',
222
+ input: 'choice',
223
+ canAnswer: true,
224
+ })
225
+ }
226
+ }
227
+ if (run.status === 'interrupted') {
228
+ items.push({
229
+ id: `resume:${run.id}`,
230
+ kind: 'resume',
231
+ kindLabel: '需要你继续',
232
+ runId: run.id,
233
+ runGoal: goal,
234
+ title: `运行「${goal}」被中断`,
235
+ what: '宿主或会话在运行途中退出,未完成的工作还留在状态目录里。',
236
+ why: '中断不是失败,已完成的部分不需要重做。',
237
+ options: ['继续未完成的工作'],
238
+ impact: '只重新执行未完成的子任务,已完成的会保留。',
239
+ input: 'choice',
240
+ canAnswer: true,
241
+ })
242
+ }
243
+ }
244
+ for (const extra of extras) {
245
+ if (!extra || !extra.id) continue
246
+ items.push({
247
+ kindLabel: '需要你处理',
248
+ input: 'choice-or-text',
249
+ canAnswer: true,
250
+ ...extra,
251
+ })
252
+ }
253
+ items.sort((left, right) => String(left.kind).localeCompare(String(right.kind)))
254
+ return items
255
+ }
256
+
257
+ function templateCard(template) {
258
+ const copy = templateCopy(template.id)
259
+ return {
260
+ id: template.id,
261
+ title: copy.title ?? template.title,
262
+ purpose: copy.purpose,
263
+ bestFor: copy.bestFor,
264
+ estimate: copy.estimate,
265
+ whenToUse: template.whenToUse,
266
+ whenNotToUse: Array.isArray(template.whenNotToUse) ? template.whenNotToUse : [],
267
+ params: (template.variables ?? []).map(variable => {
268
+ const param = parameterCopy(variable.name, template.id)
269
+ return {
270
+ name: variable.name,
271
+ label: param.label,
272
+ hint: param.hint,
273
+ description: copy.translated ? null : (variable.description ?? null),
274
+ }
275
+ }),
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Create one loopback board.
281
+ *
282
+ * @param {object} options - dependencies.
283
+ * @param {number} options.port - port, or 0 for an ephemeral one.
284
+ * @param {string} options.stateRoot - where `board.json` is written.
285
+ * @param {string} options.version - plugin version.
286
+ * @param {object} options.host - host adapter (see README "Board").
287
+ * @param {object} [options.pricing] - price table for live cost estimates.
288
+ * @param {(message: string) => void} [options.log] - diagnostics sink.
289
+ */
290
+ export function createBoard({ port, stateRoot, version, host, pricing, log = () => {} }) {
291
+ if (!host || typeof host !== 'object') throw new Error('createBoard needs a host adapter')
292
+ const token = randomBytes(32).toString('base64url')
293
+ const instanceId = randomBytes(6).toString('hex')
294
+ const discoveryPath = path.join(stateRoot, DISCOVERY_FILE)
295
+ const startedAt = new Date().toISOString()
296
+ const clients = new Set()
297
+ let boundPort = null
298
+ let server = null
299
+ let page = null
300
+ let starting = null
301
+ let closing = null
302
+ let stopRequested = false
303
+ let poller = null
304
+ let lastSnapshotJson = ''
305
+ let seq = 0
306
+
307
+ const url = () => `http://127.0.0.1:${boundPort}`
308
+ const allowedHosts = () => new Set([
309
+ `127.0.0.1:${boundPort}`,
310
+ `localhost:${boundPort}`,
311
+ `[::1]:${boundPort}`,
312
+ ])
313
+
314
+ function capabilities() {
315
+ try {
316
+ const value = host.capabilities()
317
+ if (!value || typeof value !== 'object') {
318
+ return { start: false, answer: false, reason: '宿主没有提供看板能力信息' }
319
+ }
320
+ return {
321
+ start: value.start === true,
322
+ answer: value.answer === true,
323
+ reason: typeof value.reason === 'string' && value.reason.trim() ? value.reason.trim() : null,
324
+ }
325
+ } catch (error) {
326
+ return { start: false, answer: false, reason: `读取宿主能力失败:${messageOf(error)}` }
327
+ }
328
+ }
329
+
330
+ function authorize(req, { allowQuery = false } = {}) {
331
+ if (!boundPort) {
332
+ throw new WorkbenchError(503, '看板还没有开始监听', { id: 'not-ready' })
333
+ }
334
+ const hostHeader = String(req.headers.host ?? '').toLowerCase()
335
+ if (!allowedHosts().has(hostHeader)) {
336
+ throw new WorkbenchError(403, `只接受本机访问,收到 Host "${hostHeader}"`, {
337
+ id: 'forbidden-host',
338
+ hint: `请直接打开 ${url()}`,
339
+ })
340
+ }
341
+ const header = String(req.headers.authorization ?? '')
342
+ const match = /^Bearer\s+(\S+)$/i.exec(header)
343
+ let given = match?.[1] ?? ''
344
+ if (!given && allowQuery) {
345
+ const query = new URL(req.url ?? '/', 'http://127.0.0.1').searchParams.get('token')
346
+ if (query) given = query
347
+ }
348
+ if (!given || !sameToken(given, token)) {
349
+ throw new WorkbenchError(401, '缺少访问口令或口令不正确', {
350
+ id: 'unauthorized',
351
+ hint: `打开 ${discoveryPath},把其中的 token 填进来;口令每次随宿主启动重新生成。`,
352
+ })
353
+ }
354
+ }
355
+
356
+ function nextSeq() {
357
+ seq += 1
358
+ return seq
359
+ }
360
+
361
+ function writeFrame(res, frame) {
362
+ if (res.destroyed || res.writableEnded) return false
363
+ res.write(`event: board\ndata: ${JSON.stringify(frame)}\n\n`)
364
+ if (res.writableLength > MAX_BUFFERED_BYTES) {
365
+ log(`board: dropping a stream that stopped reading (${res.writableLength} bytes buffered)`)
366
+ res.destroy()
367
+ clients.delete(res)
368
+ return false
369
+ }
370
+ return true
371
+ }
372
+
373
+ function broadcast(frame) {
374
+ const withSeq = { ...frame, seq: nextSeq(), at: new Date().toISOString() }
375
+ for (const res of clients) {
376
+ try {
377
+ writeFrame(res, withSeq)
378
+ } catch {
379
+ clients.delete(res)
380
+ }
381
+ }
382
+ return withSeq
383
+ }
384
+
385
+ async function listRuns() {
386
+ const value = await host.listRuns()
387
+ if (!Array.isArray(value)) return []
388
+ return value
389
+ .filter(run => run && typeof run === 'object' && run.id)
390
+ .sort((left, right) => String(right.createdAt ?? '').localeCompare(String(left.createdAt ?? '')))
391
+ .slice(0, MAX_RUNS)
392
+ }
393
+
394
+ async function extras() {
395
+ if (typeof host.extraInbox !== 'function') return []
396
+ try {
397
+ const value = await host.extraInbox()
398
+ return Array.isArray(value) ? value : []
399
+ } catch (error) {
400
+ log(`board: cannot read extra inbox items: ${messageOf(error)}`)
401
+ return []
402
+ }
403
+ }
404
+
405
+ async function snapshot() {
406
+ const runs = await listRuns()
407
+ const cards = runs.map(run => runCard(run))
408
+ const inbox = buildInbox(runs, await extras())
409
+ const templateList = typeof host.templates === 'function' ? await host.templates() : []
410
+ return {
411
+ service: 'dsh-superagent-board',
412
+ version,
413
+ at: new Date().toISOString(),
414
+ capabilities: capabilities(),
415
+ runs: cards,
416
+ inbox,
417
+ templates: (Array.isArray(templateList) ? templateList : []).map(templateCard),
418
+ summary: {
419
+ runs: cards.length,
420
+ active: cards.filter(card => card.active).length,
421
+ inbox: inbox.length,
422
+ },
423
+ }
424
+ }
425
+
426
+ async function runDetail(runId) {
427
+ const run = await host.readRun(runId)
428
+ if (!run) throw new WorkbenchError(404, `找不到运行 ${runId}`, { id: 'unknown-run' })
429
+ const card = runCard(run)
430
+ const subtasks = (run.subtasks ?? []).map(subtask => {
431
+ const item = subtaskCard(run, subtask)
432
+ return {
433
+ ...item,
434
+ prompt: trimText(subtask.prompt, 4_000),
435
+ result: trimText(subtask.result, MAX_RESULT_CHARS),
436
+ error: trimText(subtask.error, 4_000),
437
+ stopReason: subtask.stopReason ?? null,
438
+ deliverables: Array.isArray(subtask.deliverables) ? subtask.deliverables : [],
439
+ deliverableCheck: subtask.deliverableCheck ?? null,
440
+ audit: [],
441
+ }
442
+ })
443
+ const runAudit = []
444
+ if (typeof host.auditFor === 'function') {
445
+ try {
446
+ const rows = await host.auditFor({ runId, limit: 400 })
447
+ for (const row of rows) {
448
+ const entry = {
449
+ id: row.id ?? null,
450
+ at: row.at ?? null,
451
+ kind: row.kind ?? null,
452
+ action: row.action ?? null,
453
+ subtaskId: row.subtaskId ?? null,
454
+ actor: row.actor ?? null,
455
+ decision: row.decision ?? null,
456
+ result: row.result ?? null,
457
+ target: trimText(row.target, 300),
458
+ rule: row.rule ?? null,
459
+ reason: trimText(row.meta?.reason, 300),
460
+ }
461
+ runAudit.push(entry)
462
+ if (entry.subtaskId) {
463
+ const target = subtasks.find(subtask => entry.subtaskId === `subtask-${subtask.index}`)
464
+ if (target) target.audit.push(entry)
465
+ }
466
+ }
467
+ } catch (error) {
468
+ log(`board: cannot read audit for ${runId}: ${messageOf(error)}`)
469
+ }
470
+ }
471
+ return {
472
+ run: card,
473
+ goal: run.goal,
474
+ report: trimText(run.report, 60_000),
475
+ recovery: run.recovery ?? null,
476
+ limits: run.limits ?? null,
477
+ usage: run.usage ?? null,
478
+ audit: runAudit.slice(-MAX_AUDIT_ROWS),
479
+ subtasks,
480
+ }
481
+ }
482
+
483
+ function openStream(req, res) {
484
+ if (clients.size >= MAX_CLIENTS) {
485
+ throw new WorkbenchError(503, '同时打开的看板标签页太多,请关掉几个再试', { id: 'too-many-streams' })
486
+ }
487
+ res.writeHead(200, {
488
+ 'content-type': 'text/event-stream; charset=utf-8',
489
+ 'cache-control': 'no-cache, no-transform',
490
+ connection: 'keep-alive',
491
+ 'x-accel-buffering': 'no',
492
+ 'x-content-type-options': 'nosniff',
493
+ 'content-security-policy': "default-src 'none'",
494
+ })
495
+ res.flushHeaders?.()
496
+ clients.add(res)
497
+ snapshot()
498
+ .then(data => {
499
+ writeFrame(res, { type: 'snapshot', data, seq: nextSeq(), at: new Date().toISOString() })
500
+ })
501
+ .catch(error => {
502
+ writeFrame(res, {
503
+ type: 'error',
504
+ code: 'snapshot-failed',
505
+ message: messageOf(error),
506
+ seq: nextSeq(),
507
+ at: new Date().toISOString(),
508
+ })
509
+ })
510
+ const heartbeat = setInterval(() => {
511
+ if (res.destroyed || res.writableEnded) return
512
+ try {
513
+ res.write(': ping\n\n')
514
+ } catch {
515
+ // The close handler removes the client.
516
+ }
517
+ }, HEARTBEAT_MS)
518
+ heartbeat.unref?.()
519
+ const cleanup = () => {
520
+ clearInterval(heartbeat)
521
+ clients.delete(res)
522
+ }
523
+ req.on('close', cleanup)
524
+ res.on('close', cleanup)
525
+ res.on('error', cleanup)
526
+ }
527
+
528
+ async function pollOnce() {
529
+ const data = await snapshot()
530
+ const text = JSON.stringify(data)
531
+ if (text === lastSnapshotJson) return
532
+ lastSnapshotJson = text
533
+ if (clients.size > 0) broadcast({ type: 'snapshot', data })
534
+ }
535
+
536
+ function startPolling() {
537
+ if (poller || clients.size === 0) return
538
+ poller = setInterval(() => {
539
+ if (clients.size === 0) {
540
+ clearInterval(poller)
541
+ poller = null
542
+ return
543
+ }
544
+ pollOnce().catch(error => log(`board poll failed: ${messageOf(error)}`))
545
+ }, POLL_MS)
546
+ poller.unref?.()
547
+ }
548
+
549
+ /**
550
+ * Run one action, turning the two "wrong moment" refusals into 409s instead
551
+ * of 500s: a person who clicked rerun on a run that is still working should
552
+ * see why, not "服务器内部错误".
553
+ */
554
+ async function runAction(call, hint) {
555
+ try {
556
+ return await call()
557
+ } catch (error) {
558
+ const text = messageOf(error)
559
+ if (/is still active|still running|is running/i.test(text)) {
560
+ throw new WorkbenchError(409, '这次运行还在进行:等它停下再重跑,或者先取消那条子任务。', {
561
+ id: 'run-active',
562
+ hint,
563
+ })
564
+ }
565
+ if (/is not active|not running|nothing to cancel/i.test(text)) {
566
+ throw new WorkbenchError(409, '这次运行已经结束,看板不能在中途取消或继续它。', {
567
+ id: 'run-inactive',
568
+ hint,
569
+ })
570
+ }
571
+ throw error
572
+ }
573
+ }
574
+
575
+ /** Map an inbox id to the host call that answers it. */
576
+ async function answerInbox(itemId, answer) {
577
+ const [kind, runId, extra] = String(itemId).split(':')
578
+ if (!kind || !runId) {
579
+ throw new WorkbenchError(400, '这条待办缺少可执行的标识,请刷新页面后重试', { id: 'bad-inbox-id' })
580
+ }
581
+ if (kind === 'question') {
582
+ if (typeof host.answer !== 'function') {
583
+ throw new WorkbenchError(503, '当前宿主不能回答运行中的问题', { id: 'answer-unavailable' })
584
+ }
585
+ return host.answer({ runId, attentionId: extra || null, answer })
586
+ }
587
+ if (kind === 'review') {
588
+ if (typeof host.reviewSubtask !== 'function') {
589
+ throw new WorkbenchError(503, '当前宿主不能验收子任务', { id: 'review-unavailable' })
590
+ }
591
+ const verdict = /重做|reject|不通过/i.test(answer) ? 'reject' : 'accept'
592
+ return host.reviewSubtask({ runId, subtask: extra, verdict, note: answer })
593
+ }
594
+ if (kind === 'blocked') {
595
+ if (typeof host.rerunSubtask !== 'function') {
596
+ throw new WorkbenchError(503, '当前宿主不能重跑子任务', { id: 'rerun-unavailable' })
597
+ }
598
+ return host.rerunSubtask({ runId, subtask: extra })
599
+ }
600
+ if (kind === 'resume') {
601
+ if (typeof host.resumeRun !== 'function') {
602
+ throw new WorkbenchError(503, '当前宿主不能继续运行', { id: 'resume-unavailable' })
603
+ }
604
+ return host.resumeRun({ runId })
605
+ }
606
+ if (typeof host.answerInbox !== 'function') {
607
+ throw new WorkbenchError(404, '这条待办已经失效,请刷新页面', { id: 'unknown-inbox-item' })
608
+ }
609
+ return host.answerInbox({ id: itemId, answer })
610
+ }
611
+
612
+ async function handle(req, res) {
613
+ try {
614
+ const parsed = new URL(req.url ?? '/', 'http://127.0.0.1')
615
+ const method = req.method ?? 'GET'
616
+ const pathname = parsed.pathname
617
+
618
+ if (pathname === '/' || pathname === '/board' || pathname === '/index.html') {
619
+ if (method !== 'GET') throw new WorkbenchError(405, '这里只接受 GET', { id: 'method-not-allowed' })
620
+ authorize(req, { allowQuery: true })
621
+ sendText(res, 200, page, 'text/html; charset=utf-8', {
622
+ 'content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
623
+ + "connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
624
+ })
625
+ return
626
+ }
627
+
628
+ // EventSource cannot set headers, so the stream is the one route that also
629
+ // accepts the token in the query string.
630
+ authorize(req, { allowQuery: pathname === '/api/board/events' })
631
+ const parts = pathname.split('/').filter(Boolean)
632
+ if (parts[0] !== 'api' || parts[1] !== 'board') {
633
+ throw new WorkbenchError(404, `没有这个地址:${method} ${pathname}`, { id: 'not-found', hint: ROUTE_HINT })
634
+ }
635
+ const leaf = parts[2] ?? ''
636
+
637
+ if (leaf === 'health' && parts.length === 3) {
638
+ if (method !== 'GET') throw new WorkbenchError(405, '这里只接受 GET', { id: 'method-not-allowed' })
639
+ send(res, 200, {
640
+ ok: true,
641
+ data: {
642
+ service: 'dsh-superagent-board',
643
+ version,
644
+ pid: process.pid,
645
+ startedAt,
646
+ capabilities: capabilities(),
647
+ },
648
+ })
649
+ return
650
+ }
651
+
652
+ if (leaf === 'state' && parts.length === 3) {
653
+ if (method !== 'GET') throw new WorkbenchError(405, '这里只接受 GET', { id: 'method-not-allowed' })
654
+ send(res, 200, { ok: true, data: await snapshot() })
655
+ return
656
+ }
657
+
658
+ if (leaf === 'events' && parts.length === 3) {
659
+ if (method !== 'GET') throw new WorkbenchError(405, '这里只接受 GET', { id: 'method-not-allowed' })
660
+ openStream(req, res)
661
+ startPolling()
662
+ return
663
+ }
664
+
665
+ if (leaf === 'inbox' && parts.length === 5 && parts[4] === 'answer') {
666
+ if (method !== 'POST') throw new WorkbenchError(405, '这里只接受 POST', { id: 'method-not-allowed' })
667
+ const itemId = decodeURIComponent(parts[3])
668
+ const body = await readJson(req)
669
+ const answer = typeof body.answer === 'string' ? body.answer.trim() : ''
670
+ if (!answer) throw new WorkbenchError(400, '请先填写或选择一个答案', { id: 'missing-answer' })
671
+ const result = await answerInbox(itemId, answer)
672
+ lastSnapshotJson = ''
673
+ await pollOnce().catch(() => {})
674
+ send(res, 200, {
675
+ ok: true,
676
+ data: {
677
+ itemId,
678
+ answer,
679
+ runId: result?.id ?? result?.runId ?? null,
680
+ status: result?.status ?? null,
681
+ resumed: result?.resumed === true,
682
+ message: result?.message ?? '已记录你的回答,运行会从这里继续。',
683
+ },
684
+ })
685
+ return
686
+ }
687
+
688
+ if (leaf === 'templates' && parts.length === 5 && parts[4] === 'start') {
689
+ if (method !== 'POST') throw new WorkbenchError(405, '这里只接受 POST', { id: 'method-not-allowed' })
690
+ if (typeof host.startTemplate !== 'function') {
691
+ throw new WorkbenchError(503, '当前宿主不能发起运行', { id: 'start-unavailable' })
692
+ }
693
+ const templateId = decodeURIComponent(parts[3])
694
+ const body = await readJson(req)
695
+ const values = body.values && typeof body.values === 'object' && !Array.isArray(body.values)
696
+ ? body.values
697
+ : {}
698
+ const run = await host.startTemplate({ templateId, values })
699
+ lastSnapshotJson = ''
700
+ await pollOnce().catch(() => {})
701
+ send(res, 200, { ok: true, data: { runId: run?.id ?? null, status: run?.status ?? null } })
702
+ return
703
+ }
704
+
705
+ if (leaf === 'runs' && parts.length >= 4) {
706
+ const runId = decodeURIComponent(parts[3])
707
+ if (parts.length === 4) {
708
+ if (method !== 'GET') throw new WorkbenchError(405, '这里只接受 GET', { id: 'method-not-allowed' })
709
+ send(res, 200, { ok: true, data: await runDetail(runId) })
710
+ return
711
+ }
712
+ if (parts[4] === 'resume' && parts.length === 5) {
713
+ if (method !== 'POST') throw new WorkbenchError(405, '这里只接受 POST', { id: 'method-not-allowed' })
714
+ if (typeof host.resumeRun !== 'function') {
715
+ throw new WorkbenchError(503, '当前宿主不能继续运行', { id: 'resume-unavailable' })
716
+ }
717
+ const run = await runAction(() => host.resumeRun({ runId }), '等到运行停下后它会自己显示完成')
718
+ lastSnapshotJson = ''
719
+ await pollOnce().catch(() => {})
720
+ send(res, 200, { ok: true, data: { runId: run?.id ?? runId, status: run?.status ?? null } })
721
+ return
722
+ }
723
+ if (parts[4] === 'subtasks' && parts.length >= 7) {
724
+ const subtask = decodeURIComponent(parts[5])
725
+ const action = parts[6]
726
+ if (method !== 'POST') throw new WorkbenchError(405, '这里只接受 POST', { id: 'method-not-allowed' })
727
+ if (action === 'cancel') {
728
+ if (typeof host.cancelSubtask !== 'function') {
729
+ throw new WorkbenchError(503, '当前宿主不能取消子任务', { id: 'cancel-unavailable' })
730
+ }
731
+ const run = await runAction(
732
+ () => host.cancelSubtask({ runId, subtask }),
733
+ '只有正在排队或运行的子任务可以取消',
734
+ )
735
+ lastSnapshotJson = ''
736
+ await pollOnce().catch(() => {})
737
+ send(res, 200, { ok: true, data: { runId, subtask, status: 'cancelled', runStatus: run?.status ?? null } })
738
+ return
739
+ }
740
+ if (action === 'rerun') {
741
+ if (typeof host.rerunSubtask !== 'function') {
742
+ throw new WorkbenchError(503, '当前宿主不能重跑子任务', { id: 'rerun-unavailable' })
743
+ }
744
+ const run = await runAction(
745
+ () => host.rerunSubtask({ runId, subtask }),
746
+ '重跑只对已经结束的运行生效',
747
+ )
748
+ lastSnapshotJson = ''
749
+ await pollOnce().catch(() => {})
750
+ send(res, 200, { ok: true, data: { runId, subtask, status: run?.status ?? 'queued' } })
751
+ return
752
+ }
753
+ }
754
+ }
755
+
756
+ throw new WorkbenchError(404, `没有这个地址:${method} ${pathname}`, { id: 'not-found', hint: ROUTE_HINT })
757
+ } catch (error) {
758
+ if (statusFor(error) >= 500) log(`board request failed: ${messageOf(error)}`)
759
+ send(res, statusFor(error), errorPayload(error))
760
+ }
761
+ }
762
+
763
+ async function writeDiscovery() {
764
+ const caps = capabilities()
765
+ const doc = {
766
+ service: 'dsh-superagent-board',
767
+ version,
768
+ url: url(),
769
+ token,
770
+ pid: process.pid,
771
+ instanceId,
772
+ startedAt,
773
+ mode: caps.start ? 'ready' : 'observe-only',
774
+ }
775
+ const tmp = `${discoveryPath}.${process.pid}.${instanceId}.tmp`
776
+ const handle = await fsp.open(tmp, 'wx', 0o600)
777
+ try {
778
+ await handle.writeFile(`${JSON.stringify(doc, null, 2)}\n`, 'utf8')
779
+ } finally {
780
+ await handle.close()
781
+ }
782
+ await fsp.rename(tmp, discoveryPath)
783
+ try {
784
+ await fsp.chmod(discoveryPath, 0o600)
785
+ } catch {
786
+ // Windows ignores most mode bits; the file's ACL still applies.
787
+ }
788
+ }
789
+
790
+ async function removeDiscovery() {
791
+ try {
792
+ const current = JSON.parse(await fsp.readFile(discoveryPath, 'utf8'))
793
+ if (current?.instanceId !== instanceId) return
794
+ await fsp.unlink(discoveryPath)
795
+ } catch {
796
+ // Already gone, or replaced by another instance.
797
+ }
798
+ await fsp.unlink(`${discoveryPath}.${process.pid}.${instanceId}.tmp`).catch(() => {})
799
+ }
800
+
801
+ async function closeServer() {
802
+ if (!server) return
803
+ const instance = server
804
+ server = null
805
+ boundPort = null
806
+ await new Promise(resolve => {
807
+ instance.close(() => resolve())
808
+ instance.closeAllConnections?.()
809
+ })
810
+ }
811
+
812
+ return {
813
+ discoveryPath,
814
+ get token() {
815
+ return token
816
+ },
817
+ get port() {
818
+ return boundPort
819
+ },
820
+ get url() {
821
+ return boundPort ? url() : null
822
+ },
823
+
824
+ /** Bind loopback, load the page, and publish the discovery file. */
825
+ async start() {
826
+ if (server) return { port: boundPort, url: url() }
827
+ if (starting) return starting
828
+ if (stopRequested) throw new Error('看板已经停止,需要重新创建一个实例')
829
+ const run = (async () => {
830
+ page = await fsp.readFile(new URL('../public/board.html', import.meta.url), 'utf8')
831
+ const instance = createServer((req, res) => {
832
+ handle(req, res).catch(error => {
833
+ log(`board handler crashed: ${messageOf(error)}`)
834
+ send(res, 500, errorPayload(error))
835
+ })
836
+ })
837
+ instance.requestTimeout = REQUEST_TIMEOUT_MS
838
+ instance.headersTimeout = 10_000
839
+ instance.keepAliveTimeout = 5_000
840
+ instance.maxConnections = 64
841
+ await new Promise((resolve, reject) => {
842
+ instance.once('error', reject)
843
+ instance.listen(port, '127.0.0.1', () => {
844
+ instance.off('error', reject)
845
+ resolve()
846
+ })
847
+ })
848
+ const address = instance.address()
849
+ if (!address || typeof address === 'string') throw new Error('看板监听没有拿到 TCP 地址')
850
+ boundPort = address.port
851
+ server = instance
852
+ await writeDiscovery()
853
+ return { port: boundPort, url: url() }
854
+ })()
855
+ starting = run
856
+ try {
857
+ return await run
858
+ } finally {
859
+ starting = null
860
+ }
861
+ },
862
+
863
+ /** Close the socket, stop polling, and remove the discovery file. */
864
+ async stop() {
865
+ if (closing) return closing
866
+ stopRequested = true
867
+ closing = (async () => {
868
+ if (poller) {
869
+ clearInterval(poller)
870
+ poller = null
871
+ }
872
+ for (const res of clients) {
873
+ try {
874
+ writeFrame(res, { type: 'closed', seq: nextSeq(), at: new Date().toISOString() })
875
+ res.end()
876
+ } catch {
877
+ // The socket is already gone.
878
+ }
879
+ }
880
+ clients.clear()
881
+ await closeServer()
882
+ await removeDiscovery()
883
+ })()
884
+ try {
885
+ await closing
886
+ } finally {
887
+ closing = null
888
+ }
889
+ },
890
+ }
891
+ }