dsh-dispatch-board 0.0.0-stage → 0.1.2
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 +164 -2
- package/cordis.patch.yml +10 -0
- package/icon.svg +7 -0
- package/lib/client.js +2882 -0
- package/lib/index.js +1618 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +67 -4
- package/presets/taskboard.patch.yml +257 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1618 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-taskboard —— Host 半(Cordis 插件,ESM,无构建)。
|
|
3
|
+
*
|
|
4
|
+
* 单一 Loader 行(见 cordis.patch.yml)挂载本模块,职责:
|
|
5
|
+
* 1. 在 webServer 上注册 /taskboard 前缀路由,用 Connection RPC 信封
|
|
6
|
+
* ({type:'client-request', rpcId, method, payload} → {type:'server-response', rpcId, result})
|
|
7
|
+
* 给浏览器端提供 snapshot / add-task / update-task / delete-task / dispatch-now /
|
|
8
|
+
* set-config / archive-done / install-preset 八个端点;
|
|
9
|
+
* 2. 持久化任务看板到 $DSH_HOME/storages/dsh-taskboard/board.json(原子写);
|
|
10
|
+
* 3. 轮询「待开始」列:命中且目标主 Agent 空闲时,用 agent.followup() 推一条【任务看板】消息,
|
|
11
|
+
* 主 Agent 据此派发子 Agent(本插件不直接起子 Agent——派单是主 Agent 的职责);
|
|
12
|
+
* 4. 注册三个面向模型的工具:taskboard_list / taskboard_add / taskboard_update;
|
|
13
|
+
* 5. 插件 bundle 自带两个模式声明(presets/taskboard.patch.yml 里的
|
|
14
|
+
* @deepseek-ai/dsh-agent-preset 行:taskboard-dispatch 主 + taskboard-worker 执行者),
|
|
15
|
+
* 随 Loader 组合加载;本文件只从 agentPresets 注册表读回实时状态给 UI。
|
|
16
|
+
*
|
|
17
|
+
* 本文件顶层只 import node: 内建模块,不 import 任何 @deepseek-ai/*。
|
|
18
|
+
* 原因:外部插件包的 profile node_modules 里没有 dsh-tools / dsh-llm,
|
|
19
|
+
* 需要的数据结构(UserMessage / 工具定义)在本文件内手工构造(见 createBoardUserMessage)。
|
|
20
|
+
* 这样也保证 node --test 能在没有 DSH 进程时直接 import 本文件做纯函数单测。
|
|
21
|
+
*
|
|
22
|
+
* 契约(字段/端点/状态机)以 docs/architecture.md 为唯一事实来源。
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { randomUUID } from 'node:crypto'
|
|
26
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
27
|
+
import { homedir } from 'node:os'
|
|
28
|
+
import { dirname, join } from 'node:path'
|
|
29
|
+
import { fileURLToPath } from 'node:url'
|
|
30
|
+
|
|
31
|
+
export const name = 'taskboard'
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 只有 timer 是硬依赖(轮询定时器)。
|
|
35
|
+
* webServer 用 ctx.inject(['webServer'], cb) 等它就绪——这样插件在非 Web profile 里也照常
|
|
36
|
+
* 加载(看板工具与轮询可用,只是没有浏览器路由),而不是整包静默 PENDING 不加载。
|
|
37
|
+
*/
|
|
38
|
+
export const inject = ['timer']
|
|
39
|
+
|
|
40
|
+
/* ------------------------------------------------------------------ *
|
|
41
|
+
* 常量
|
|
42
|
+
* ------------------------------------------------------------------ */
|
|
43
|
+
|
|
44
|
+
const PACKAGE_NAME = 'dsh-taskboard'
|
|
45
|
+
const RPC_CHANNEL = '/taskboard'
|
|
46
|
+
const BOARD_VERSION = 1
|
|
47
|
+
const STORAGE_DIRNAME = 'dsh-taskboard'
|
|
48
|
+
const BOARD_FILENAME = 'board.json'
|
|
49
|
+
const MAX_BODY_BYTES = 512 * 1024
|
|
50
|
+
const MIN_POLL_INTERVAL_MS = 5000
|
|
51
|
+
const MAX_POLL_INTERVAL_MS = 300000
|
|
52
|
+
const DEFAULT_POLL_INTERVAL_MS = 15000
|
|
53
|
+
const DEFAULT_MAX_NOTIFICATIONS = 5
|
|
54
|
+
const MAX_NOTE_CHARS = 4000
|
|
55
|
+
const MAX_TITLE_CHARS = 200
|
|
56
|
+
|
|
57
|
+
/** 看板四列。顺序即 UI 列顺序。 */
|
|
58
|
+
export const STATUSES = ['todo', 'doing', 'done', 'archived']
|
|
59
|
+
|
|
60
|
+
/** 合法状态迁移(含原地更新)。轮询只扫 todo。 */
|
|
61
|
+
const TRANSITIONS = {
|
|
62
|
+
todo: ['todo', 'doing', 'archived'],
|
|
63
|
+
doing: ['doing', 'done', 'todo', 'archived'],
|
|
64
|
+
done: ['done', 'archived', 'doing', 'todo'],
|
|
65
|
+
archived: ['archived', 'todo'],
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 预设状态缓存时长:registry.list() 会重新审计挂载树,别在每个 2s 快照里都跑。 */
|
|
69
|
+
const PRESET_CACHE_MS = 15000
|
|
70
|
+
|
|
71
|
+
/* ------------------------------------------------------------------ *
|
|
72
|
+
* 通用小工具
|
|
73
|
+
* ------------------------------------------------------------------ */
|
|
74
|
+
|
|
75
|
+
/** 统一错误:带稳定 code,HTTP 层转成 RPC error 信封。 */
|
|
76
|
+
export class BoardError extends Error {
|
|
77
|
+
constructor(code, message, details = {}) {
|
|
78
|
+
super(message)
|
|
79
|
+
this.name = 'BoardError'
|
|
80
|
+
this.code = code
|
|
81
|
+
this.details = details
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function describeError(error) {
|
|
86
|
+
if (error instanceof Error) return error.message
|
|
87
|
+
return String(error)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function iso(ms) {
|
|
91
|
+
return new Date(ms).toISOString()
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function asString(value) {
|
|
95
|
+
return typeof value === 'string' ? value : ''
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function trimmed(value, max) {
|
|
99
|
+
const text = typeof value === 'string' ? value.trim() : ''
|
|
100
|
+
return text.length > max ? text.slice(0, max) : text
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isPlainObject(value) {
|
|
104
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** $DSH_HOME:优先环境变量,缺省 ~/.dsh(与 dsh-ollama-statistical 的做法一致)。 */
|
|
108
|
+
export function resolveDshHome() {
|
|
109
|
+
const fromEnv = typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : ''
|
|
110
|
+
if (fromEnv !== '') return fromEnv
|
|
111
|
+
return join(homedir(), '.dsh')
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function boardPath() {
|
|
115
|
+
// 测试/多实例隔离:显式指定 board.json 路径时优先用它,避免两个进程抢同一个文件。
|
|
116
|
+
const override = typeof process.env.DSH_TASKBOARD_PATH === 'string' ? process.env.DSH_TASKBOARD_PATH.trim() : ''
|
|
117
|
+
if (override !== '') return override
|
|
118
|
+
return join(resolveDshHome(), 'storages', STORAGE_DIRNAME, BOARD_FILENAME)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 原子写 JSON:tmp + rename。失败抛给调用方,由调用方决定降级。 */
|
|
122
|
+
export function writeJsonAtomic(filePath, value) {
|
|
123
|
+
const dir = dirname(filePath)
|
|
124
|
+
mkdirSync(dir, { recursive: true })
|
|
125
|
+
const tmp = filePath + '.tmp-' + process.pid
|
|
126
|
+
writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', 'utf8')
|
|
127
|
+
renameSync(tmp, filePath)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function readJsonFile(filePath) {
|
|
131
|
+
try {
|
|
132
|
+
const text = readFileSync(filePath, 'utf8')
|
|
133
|
+
const parsed = JSON.parse(text)
|
|
134
|
+
return isPlainObject(parsed) ? parsed : null
|
|
135
|
+
} catch {
|
|
136
|
+
return null
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/* ------------------------------------------------------------------ *
|
|
141
|
+
* 看板状态:构造 / 规范化 / 落盘
|
|
142
|
+
* ------------------------------------------------------------------ */
|
|
143
|
+
|
|
144
|
+
export function createEmptyBoard() {
|
|
145
|
+
return {
|
|
146
|
+
version: BOARD_VERSION,
|
|
147
|
+
nextId: 1,
|
|
148
|
+
revision: 0,
|
|
149
|
+
updatedAt: iso(Date.now()),
|
|
150
|
+
config: {
|
|
151
|
+
pollEnabled: true,
|
|
152
|
+
pollIntervalMs: DEFAULT_POLL_INTERVAL_MS,
|
|
153
|
+
maxNotifications: DEFAULT_MAX_NOTIFICATIONS,
|
|
154
|
+
dispatchMode: DEFAULT_DISPATCH_MODE,
|
|
155
|
+
},
|
|
156
|
+
tasks: [],
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 派发去处:新对话(默认)/ 回发起它的对话 / 自动挑空闲会话。 */
|
|
161
|
+
export const DISPATCH_MODES = ['new', 'creator', 'auto']
|
|
162
|
+
export const DEFAULT_DISPATCH_MODE = 'new'
|
|
163
|
+
|
|
164
|
+
export function normalizeConfig(raw) {
|
|
165
|
+
const config = isPlainObject(raw) ? raw : {}
|
|
166
|
+
const interval = Number(config.pollIntervalMs)
|
|
167
|
+
const maxNotifications = Number(config.maxNotifications)
|
|
168
|
+
return {
|
|
169
|
+
pollEnabled: config.pollEnabled !== false,
|
|
170
|
+
dispatchMode: DISPATCH_MODES.includes(config.dispatchMode) ? config.dispatchMode : DEFAULT_DISPATCH_MODE,
|
|
171
|
+
pollIntervalMs:
|
|
172
|
+
Number.isFinite(interval) && interval >= MIN_POLL_INTERVAL_MS && interval <= MAX_POLL_INTERVAL_MS
|
|
173
|
+
? Math.round(interval)
|
|
174
|
+
: DEFAULT_POLL_INTERVAL_MS,
|
|
175
|
+
maxNotifications:
|
|
176
|
+
Number.isFinite(maxNotifications) && maxNotifications >= 1 && maxNotifications <= 50
|
|
177
|
+
? Math.round(maxNotifications)
|
|
178
|
+
: DEFAULT_MAX_NOTIFICATIONS,
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function normalizeTask(raw, index) {
|
|
183
|
+
if (!isPlainObject(raw)) return null
|
|
184
|
+
const status = STATUSES.includes(raw.status) ? raw.status : 'todo'
|
|
185
|
+
const title = trimmed(raw.title, MAX_TITLE_CHARS)
|
|
186
|
+
if (title === '') return null
|
|
187
|
+
const id = trimmed(raw.id, 40) || 't-' + String(index + 1)
|
|
188
|
+
return {
|
|
189
|
+
id,
|
|
190
|
+
title,
|
|
191
|
+
note: trimmed(raw.note, MAX_NOTE_CHARS),
|
|
192
|
+
status,
|
|
193
|
+
source: raw.source === 'agent' ? 'agent' : 'user',
|
|
194
|
+
sessionId: typeof raw.sessionId === 'string' && raw.sessionId !== '' ? raw.sessionId : null,
|
|
195
|
+
// 最近一次投递给哪个会话(看板详情里「打开执行对话」用)。
|
|
196
|
+
dispatchedSessionId: typeof raw.dispatchedSessionId === 'string' && raw.dispatchedSessionId !== '' ? raw.dispatchedSessionId : null,
|
|
197
|
+
dispatchedSessionTitle: trimmed(raw.dispatchedSessionTitle, 200),
|
|
198
|
+
cwd: typeof raw.cwd === 'string' && raw.cwd !== '' ? raw.cwd : null,
|
|
199
|
+
assignee: trimmed(raw.assignee, 200),
|
|
200
|
+
result: trimmed(raw.result, MAX_NOTE_CHARS),
|
|
201
|
+
createdAt: asString(raw.createdAt) || iso(Date.now()),
|
|
202
|
+
updatedAt: asString(raw.updatedAt) || asString(raw.createdAt) || iso(Date.now()),
|
|
203
|
+
startedAt: asString(raw.startedAt) || null,
|
|
204
|
+
finishedAt: asString(raw.finishedAt) || null,
|
|
205
|
+
archivedAt: asString(raw.archivedAt) || null,
|
|
206
|
+
notifiedAt: asString(raw.notifiedAt) || null,
|
|
207
|
+
notificationCount: Number.isFinite(Number(raw.notificationCount)) ? Math.max(0, Math.round(Number(raw.notificationCount))) : 0,
|
|
208
|
+
lastError: trimmed(raw.lastError, 500),
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** 把磁盘上的原始值规范化成可信状态;坏任务被丢弃并计入 dropped。 */
|
|
213
|
+
export function normalizeBoard(raw) {
|
|
214
|
+
if (!isPlainObject(raw)) return { state: createEmptyBoard(), dropped: 0 }
|
|
215
|
+
const state = createEmptyBoard()
|
|
216
|
+
state.config = normalizeConfig(raw.config)
|
|
217
|
+
const rawTasks = Array.isArray(raw.tasks) ? raw.tasks : []
|
|
218
|
+
const tasks = []
|
|
219
|
+
const seen = new Set()
|
|
220
|
+
for (let i = 0; i < rawTasks.length; i++) {
|
|
221
|
+
const task = normalizeTask(rawTasks[i], i)
|
|
222
|
+
if (!task || seen.has(task.id)) continue
|
|
223
|
+
seen.add(task.id)
|
|
224
|
+
tasks.push(task)
|
|
225
|
+
}
|
|
226
|
+
state.tasks = tasks
|
|
227
|
+
let maxId = 0
|
|
228
|
+
for (const task of tasks) {
|
|
229
|
+
const match = /^t-(\d+)$/.exec(task.id)
|
|
230
|
+
if (match) maxId = Math.max(maxId, Number(match[1]))
|
|
231
|
+
}
|
|
232
|
+
const rawNext = Number(raw.nextId)
|
|
233
|
+
state.nextId = Math.max(Number.isFinite(rawNext) ? Math.round(rawNext) : 1, maxId + 1, 1)
|
|
234
|
+
const rawRev = Number(raw.revision)
|
|
235
|
+
state.revision = Number.isFinite(rawRev) ? Math.max(0, Math.round(rawRev)) : 0
|
|
236
|
+
state.updatedAt = asString(raw.updatedAt) || iso(Date.now())
|
|
237
|
+
return { state, dropped: rawTasks.length - tasks.length }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** 读板;坏文件改名保留现场后从空板开始。 */
|
|
241
|
+
export function loadBoardFromDisk(filePath = boardPath()) {
|
|
242
|
+
if (!existsSync(filePath)) return { state: createEmptyBoard(), warnings: [] }
|
|
243
|
+
const parsed = readJsonFile(filePath)
|
|
244
|
+
if (!parsed) {
|
|
245
|
+
const backup = filePath + '.corrupt-' + Date.now()
|
|
246
|
+
try {
|
|
247
|
+
renameSync(filePath, backup)
|
|
248
|
+
} catch {
|
|
249
|
+
/* 留不住现场也不阻塞启动 */
|
|
250
|
+
}
|
|
251
|
+
return { state: createEmptyBoard(), warnings: ['board.json 解析失败,已备份到 ' + backup] }
|
|
252
|
+
}
|
|
253
|
+
const { state, dropped } = normalizeBoard(parsed)
|
|
254
|
+
const warnings = dropped > 0 ? [String(dropped) + ' 个任务记录不合法已丢弃'] : []
|
|
255
|
+
return { state, warnings }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 写前重读:如果盘上的 revision 比内存新,说明别的进程写过(例如同时开了测试实例),
|
|
260
|
+
* 就整体采用盘上的状态再改,避免「整份内存状态覆盖掉别人的修改」(丢更新)。
|
|
261
|
+
* @returns {boolean} 是否发生了重载
|
|
262
|
+
*/
|
|
263
|
+
export function reloadBoardIfStale(rt) {
|
|
264
|
+
try {
|
|
265
|
+
if (!rt || !rt.filePath || !existsSync(rt.filePath)) return false
|
|
266
|
+
const loaded = loadBoardFromDisk(rt.filePath)
|
|
267
|
+
const disk = loaded && loaded.state
|
|
268
|
+
if (!disk) return false
|
|
269
|
+
if (Number(disk.revision) > Number(rt.state && rt.state.revision)) {
|
|
270
|
+
rt.state = disk
|
|
271
|
+
return true
|
|
272
|
+
}
|
|
273
|
+
} catch (error) {
|
|
274
|
+
console.warn('[taskboard] 重读看板失败:' + describeError(error))
|
|
275
|
+
}
|
|
276
|
+
return false
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** 提交变更:revision+1、updatedAt、落盘。写盘失败不抛(内存仍是真源)。 */
|
|
280
|
+
export function commitBoard(state, filePath = boardPath()) {
|
|
281
|
+
state.revision = (Number(state.revision) || 0) + 1
|
|
282
|
+
state.updatedAt = iso(Date.now())
|
|
283
|
+
try {
|
|
284
|
+
writeJsonAtomic(filePath, state)
|
|
285
|
+
return { saved: true }
|
|
286
|
+
} catch (error) {
|
|
287
|
+
console.warn('[taskboard] 看板写盘失败:' + describeError(error))
|
|
288
|
+
return { saved: false, error: describeError(error) }
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/* ------------------------------------------------------------------ *
|
|
293
|
+
* 任务操作(纯函数,便于单测)
|
|
294
|
+
* ------------------------------------------------------------------ */
|
|
295
|
+
|
|
296
|
+
export function findTask(state, id) {
|
|
297
|
+
const target = trimmed(id, 40)
|
|
298
|
+
if (target === '') throw new BoardError('bad-request', '缺少任务 id')
|
|
299
|
+
const task = state.tasks.find((item) => item.id === target)
|
|
300
|
+
if (!task) throw new BoardError('not-found', '任务不存在:' + target, { id: target })
|
|
301
|
+
return task
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function nextTaskId(state) {
|
|
305
|
+
const id = 't-' + state.nextId
|
|
306
|
+
state.nextId += 1
|
|
307
|
+
return id
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export function addTask(state, input, now = Date.now()) {
|
|
311
|
+
if (!isPlainObject(input)) throw new BoardError('bad-request', '参数必须是对象')
|
|
312
|
+
const title = trimmed(input.title, MAX_TITLE_CHARS)
|
|
313
|
+
if (title === '') throw new BoardError('bad-request', '标题不能为空')
|
|
314
|
+
const stamp = iso(now)
|
|
315
|
+
const task = {
|
|
316
|
+
id: nextTaskId(state),
|
|
317
|
+
title,
|
|
318
|
+
note: trimmed(input.note, MAX_NOTE_CHARS),
|
|
319
|
+
status: 'todo',
|
|
320
|
+
source: input.source === 'agent' ? 'agent' : 'user',
|
|
321
|
+
// 仅记录「哪个会话创建的」,不参与派发路由(派发永远是主 Agent 全自动)。
|
|
322
|
+
sessionId: typeof input.sessionId === 'string' && input.sessionId !== '' ? input.sessionId : null,
|
|
323
|
+
dispatchedSessionId: null,
|
|
324
|
+
dispatchedSessionTitle: '',
|
|
325
|
+
cwd: typeof input.cwd === 'string' && input.cwd !== '' ? input.cwd : null,
|
|
326
|
+
assignee: '',
|
|
327
|
+
result: '',
|
|
328
|
+
createdAt: stamp,
|
|
329
|
+
updatedAt: stamp,
|
|
330
|
+
startedAt: null,
|
|
331
|
+
finishedAt: null,
|
|
332
|
+
archivedAt: null,
|
|
333
|
+
notifiedAt: null,
|
|
334
|
+
notificationCount: 0,
|
|
335
|
+
lastError: '',
|
|
336
|
+
}
|
|
337
|
+
state.tasks.push(task)
|
|
338
|
+
return task
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export function canTransition(from, to) {
|
|
342
|
+
const allowed = TRANSITIONS[from]
|
|
343
|
+
return Array.isArray(allowed) && allowed.includes(to)
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function applyTaskUpdate(state, id, patch, now = Date.now()) {
|
|
347
|
+
const task = findTask(state, id)
|
|
348
|
+
if (!isPlainObject(patch)) throw new BoardError('bad-request', 'patch 必须是对象')
|
|
349
|
+
if (patch.status !== undefined) {
|
|
350
|
+
if (!STATUSES.includes(patch.status)) {
|
|
351
|
+
throw new BoardError('bad-request', '非法状态:' + String(patch.status), { allowed: STATUSES })
|
|
352
|
+
}
|
|
353
|
+
if (!canTransition(task.status, patch.status)) {
|
|
354
|
+
throw new BoardError('conflict', '不允许的状态迁移:' + task.status + ' → ' + patch.status, {
|
|
355
|
+
from: task.status,
|
|
356
|
+
to: patch.status,
|
|
357
|
+
allowed: TRANSITIONS[task.status] || [],
|
|
358
|
+
})
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
const stamp = iso(now)
|
|
362
|
+
const previousStatus = task.status
|
|
363
|
+
if (patch.status !== undefined && patch.status !== previousStatus) {
|
|
364
|
+
task.status = patch.status
|
|
365
|
+
// 状态变了,上一轮「派发跳过」的原因就过期了,别让它挂在卡片上误导人。
|
|
366
|
+
if (patch.clearError !== true) task.lastError = ''
|
|
367
|
+
if (patch.status === 'doing') {
|
|
368
|
+
task.startedAt = stamp
|
|
369
|
+
task.finishedAt = null
|
|
370
|
+
task.archivedAt = null
|
|
371
|
+
} else if (patch.status === 'done') {
|
|
372
|
+
task.finishedAt = stamp
|
|
373
|
+
} else if (patch.status === 'archived') {
|
|
374
|
+
task.archivedAt = stamp
|
|
375
|
+
} else if (patch.status === 'todo') {
|
|
376
|
+
// 回到待开始:重新排队派发,清掉上一轮的派发记账。
|
|
377
|
+
task.startedAt = null
|
|
378
|
+
task.finishedAt = null
|
|
379
|
+
task.archivedAt = null
|
|
380
|
+
task.notifiedAt = null
|
|
381
|
+
task.notificationCount = 0
|
|
382
|
+
task.assignee = ''
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
if (patch.title !== undefined) {
|
|
386
|
+
const title = trimmed(patch.title, MAX_TITLE_CHARS)
|
|
387
|
+
if (title === '') throw new BoardError('bad-request', '标题不能为空')
|
|
388
|
+
task.title = title
|
|
389
|
+
}
|
|
390
|
+
if (patch.note !== undefined) task.note = trimmed(patch.note, MAX_NOTE_CHARS)
|
|
391
|
+
if (patch.result !== undefined) task.result = trimmed(patch.result, MAX_NOTE_CHARS)
|
|
392
|
+
if (patch.assignee !== undefined) task.assignee = trimmed(patch.assignee, 200)
|
|
393
|
+
if (patch.lastError !== undefined) task.lastError = trimmed(patch.lastError, 500)
|
|
394
|
+
if (patch.clearError === true) task.lastError = ''
|
|
395
|
+
if (patch.sessionId !== undefined) {
|
|
396
|
+
task.sessionId = typeof patch.sessionId === 'string' && patch.sessionId !== '' ? patch.sessionId : null
|
|
397
|
+
}
|
|
398
|
+
task.updatedAt = stamp
|
|
399
|
+
return task
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export function archiveDoneTasks(state, now = Date.now()) {
|
|
403
|
+
let archived = 0
|
|
404
|
+
for (const task of state.tasks) {
|
|
405
|
+
if (task.status !== 'done') continue
|
|
406
|
+
task.status = 'archived'
|
|
407
|
+
task.archivedAt = iso(now)
|
|
408
|
+
task.updatedAt = iso(now)
|
|
409
|
+
archived += 1
|
|
410
|
+
}
|
|
411
|
+
return archived
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export function deleteTask(state, id) {
|
|
415
|
+
const task = findTask(state, id)
|
|
416
|
+
const index = state.tasks.indexOf(task)
|
|
417
|
+
if (index >= 0) state.tasks.splice(index, 1)
|
|
418
|
+
return task
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/* ------------------------------------------------------------------ *
|
|
422
|
+
* 派单:候选选择 / 目标 Agent / 消息构造
|
|
423
|
+
* ------------------------------------------------------------------ */
|
|
424
|
+
|
|
425
|
+
/** 通知冷却:两倍轮询间隔,最长 120s。 */
|
|
426
|
+
export function notifyCooldownMs(config) {
|
|
427
|
+
const interval = normalizeConfig(config).pollIntervalMs
|
|
428
|
+
return Math.min(Math.max(interval * 2, 10000), 120000)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* 选所有可派发的任务(纯函数,按优先级排序):
|
|
433
|
+
* - 只看 todo;
|
|
434
|
+
* - 通知次数达上限的不再投递;
|
|
435
|
+
* - 冷却期内不重复投递;
|
|
436
|
+
* - 按 createdAt、再按 id 数字序。
|
|
437
|
+
* 返回数组而不是单条:tick 会逐条试目标(某个任务的目标会话正忙时,不能挡住其它任务)。
|
|
438
|
+
*/
|
|
439
|
+
export function selectDispatchCandidates(state, now = Date.now()) {
|
|
440
|
+
const config = normalizeConfig(state.config)
|
|
441
|
+
const cooldown = notifyCooldownMs(config)
|
|
442
|
+
return state.tasks
|
|
443
|
+
.filter((task) => task.status === 'todo')
|
|
444
|
+
.filter((task) => task.notificationCount < config.maxNotifications)
|
|
445
|
+
.filter((task) => {
|
|
446
|
+
if (!task.notifiedAt) return true
|
|
447
|
+
const at = Date.parse(task.notifiedAt)
|
|
448
|
+
if (!Number.isFinite(at)) return true
|
|
449
|
+
return now - at >= cooldown
|
|
450
|
+
})
|
|
451
|
+
.sort((a, b) => {
|
|
452
|
+
const byTime = Date.parse(a.createdAt) - Date.parse(b.createdAt)
|
|
453
|
+
if (byTime !== 0 && Number.isFinite(byTime)) return byTime
|
|
454
|
+
return idNumber(a.id) - idNumber(b.id)
|
|
455
|
+
})
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** 选下一条要派发的任务(= 候选列表的第一条)。 */
|
|
459
|
+
export function selectDispatchCandidate(state, now = Date.now()) {
|
|
460
|
+
return selectDispatchCandidates(state, now)[0] || null
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function idNumber(id) {
|
|
464
|
+
const match = /^t-(\d+)$/.exec(String(id))
|
|
465
|
+
return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* 解析派发目标(全自动,用户不需要选会话):
|
|
470
|
+
* 1. 任务来自某个对话(task.sessionId 有值)且该会话在线 → 优先回那个对话(工作区绑定):
|
|
471
|
+
* 空闲就派;正在跑就等下一轮(creator-busy),不改派别的会话;
|
|
472
|
+
* 历史/冷会话唤醒不了就等(creator-cold);
|
|
473
|
+
* 2. 任务指定了工作区(task.cwd,平台看板创建的)→ 优先找**同一工作区**的空闲会话;
|
|
474
|
+
* 找不到就等(workspace-offline / workspace-busy),不改派到别的工作区(除非 force);
|
|
475
|
+
* 3. 都没有 → 优先「派单看板模式」的空闲 root Agent;再退化到任意空闲 root Agent;
|
|
476
|
+
* 4. 完全没有会话 → agent-busy / no-live-agent。
|
|
477
|
+
* @returns {{agent: object|null, reason: string}}
|
|
478
|
+
*/
|
|
479
|
+
export function resolveTargetAgent(agentsService, task = null, presetOf = headerPresetOf, options = {}) {
|
|
480
|
+
if (!agentsService || typeof agentsService.get !== 'function') {
|
|
481
|
+
return { agent: null, reason: 'no-agents-service' }
|
|
482
|
+
}
|
|
483
|
+
if (options.ignoreCreator !== true && task && typeof task.sessionId === 'string' && task.sessionId !== '') {
|
|
484
|
+
const creator = agentsService.get(task.sessionId)
|
|
485
|
+
if (creator) {
|
|
486
|
+
// force = 用户手动点「立即派发」:即使创建它的对话正忙,也把消息排进它的下一轮。
|
|
487
|
+
if (creator.status === 'idle' || options.force === true) return { agent: creator, reason: 'creator-session' }
|
|
488
|
+
return { agent: null, reason: 'creator-busy' }
|
|
489
|
+
}
|
|
490
|
+
// 创建它的对话不在线、又唤醒不了(历史会话被 UI 持有 writer 等):
|
|
491
|
+
// 默认**不**改派到别的工作区,等用户在那边发一条消息把它变成 live;只有手动「立即派发」才退化。
|
|
492
|
+
if (options.force !== true) return { agent: null, reason: 'creator-cold' }
|
|
493
|
+
}
|
|
494
|
+
let roots = []
|
|
495
|
+
try {
|
|
496
|
+
roots = typeof agentsService.roots === 'function' ? agentsService.roots() : []
|
|
497
|
+
} catch {
|
|
498
|
+
roots = []
|
|
499
|
+
}
|
|
500
|
+
const idle = roots.filter((agent) => agent && agent.status === 'idle')
|
|
501
|
+
const wantPath = task && typeof task.cwd === 'string' ? normalizePathForCompare(task.cwd) : ''
|
|
502
|
+
if (wantPath !== '') {
|
|
503
|
+
const inWorkspace = idle.filter((agent) => normalizePathForCompare(sessionCwd(agent)) === wantPath)
|
|
504
|
+
if (inWorkspace.length > 0) return { agent: inWorkspace[inWorkspace.length - 1], reason: 'workspace-session' }
|
|
505
|
+
if (options.force !== true) {
|
|
506
|
+
const anyInWorkspace = roots.some((agent) => normalizePathForCompare(sessionCwd(agent)) === wantPath)
|
|
507
|
+
return { agent: null, reason: anyInWorkspace ? 'workspace-busy' : 'workspace-offline' }
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
const dispatchers = idle.filter((agent) => {
|
|
511
|
+
try {
|
|
512
|
+
return presetOf(agent) === DISPATCH_PRESET_ID
|
|
513
|
+
} catch {
|
|
514
|
+
return false
|
|
515
|
+
}
|
|
516
|
+
})
|
|
517
|
+
if (dispatchers.length > 0) return { agent: dispatchers[dispatchers.length - 1], reason: 'dispatcher-root' }
|
|
518
|
+
if (idle.length > 0) return { agent: idle[idle.length - 1], reason: 'recent-root' }
|
|
519
|
+
if (roots.length > 0) return { agent: null, reason: 'agent-busy' }
|
|
520
|
+
return { agent: null, reason: 'no-live-agent' }
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** 从一个会话 id 解析它的工作区(cwd):先查 live Agent,再查 live Session。 */
|
|
524
|
+
export function resolveSessionCwd(ctx, sessionId) {
|
|
525
|
+
if (!sessionId || typeof sessionId !== 'string') return null
|
|
526
|
+
const readers = [
|
|
527
|
+
() => {
|
|
528
|
+
const agents = ctx && typeof ctx.get === 'function' ? ctx.get('agents') : undefined
|
|
529
|
+
const agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : undefined
|
|
530
|
+
const header = agent && agent.session ? agent.session.header : undefined
|
|
531
|
+
return header && typeof header.cwd === 'string' && header.cwd !== '' ? header.cwd : null
|
|
532
|
+
},
|
|
533
|
+
() => {
|
|
534
|
+
const sessions = ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : undefined
|
|
535
|
+
const session = sessions && typeof sessions.get === 'function' ? sessions.get(sessionId) : undefined
|
|
536
|
+
const header = session ? session.header : undefined
|
|
537
|
+
return header && typeof header.cwd === 'string' && header.cwd !== '' ? header.cwd : null
|
|
538
|
+
},
|
|
539
|
+
]
|
|
540
|
+
for (const read of readers) {
|
|
541
|
+
try {
|
|
542
|
+
const cwd = read()
|
|
543
|
+
if (cwd) return cwd
|
|
544
|
+
} catch {
|
|
545
|
+
/* 下一个读法 */
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return null
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* 冷会话(历史会话被打开但还没产生 live agent)的 cwd 兜底:查 sessionQuery 的会话列表。
|
|
553
|
+
* 只在 sync 读法拿不到时用,代价是一次 listSessions()。
|
|
554
|
+
*/
|
|
555
|
+
export async function resolveSessionCwdViaQuery(ctx, sessionId) {
|
|
556
|
+
if (!sessionId || typeof sessionId !== 'string') return null
|
|
557
|
+
try {
|
|
558
|
+
const query = ctx && typeof ctx.get === 'function' ? ctx.get('sessionQuery') : undefined
|
|
559
|
+
if (!query || typeof query.listSessions !== 'function') return null
|
|
560
|
+
const records = await query.listSessions()
|
|
561
|
+
const hit = (Array.isArray(records) ? records : []).find(
|
|
562
|
+
(record) => record && record.header && record.header.id === sessionId,
|
|
563
|
+
)
|
|
564
|
+
const cwd = hit && hit.header && typeof hit.header.cwd === 'string' ? hit.header.cwd : ''
|
|
565
|
+
return cwd !== '' ? cwd : null
|
|
566
|
+
} catch {
|
|
567
|
+
return null
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** 兜底:只读 session.header.agentPreset(创建时的预设,之后可能被切换过)。 */
|
|
572
|
+
function headerPresetOf(agent) {
|
|
573
|
+
try {
|
|
574
|
+
const header = agent && agent.session && agent.session.header
|
|
575
|
+
return header && typeof header.agentPreset === 'string' ? header.agentPreset : ''
|
|
576
|
+
} catch {
|
|
577
|
+
return ''
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* 权威读法:agentPresets.presetForSession(session) 读的是 Session 的 agentPreset 投影
|
|
583
|
+
* (header 初始化 + agent-preset/selected 事件推进),能反映创建后切换过的模式。
|
|
584
|
+
*/
|
|
585
|
+
function sessionPresetOfContext(ctx, agent) {
|
|
586
|
+
try {
|
|
587
|
+
const registry = ctx && typeof ctx.get === 'function' ? ctx.get('agentPresets') : undefined
|
|
588
|
+
if (registry && typeof registry.presetForSession === 'function' && agent && agent.session) {
|
|
589
|
+
const id = registry.presetForSession(agent.session)
|
|
590
|
+
if (typeof id === 'string' && id !== '') return id
|
|
591
|
+
}
|
|
592
|
+
} catch {
|
|
593
|
+
/* 退回头部字段 */
|
|
594
|
+
}
|
|
595
|
+
return headerPresetOf(agent)
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** 派发消息正文(模型看到的用户消息)。 */
|
|
599
|
+
export function buildDispatchText(task, now = Date.now()) {
|
|
600
|
+
const lines = ['【任务看板 · 待开始】' + task.id + ' ' + task.title]
|
|
601
|
+
if (task.note) lines.push('备注:' + task.note)
|
|
602
|
+
if (task.cwd) lines.push('工作目录:' + task.cwd)
|
|
603
|
+
lines.push('')
|
|
604
|
+
lines.push(
|
|
605
|
+
'请按派单规则处理这条看板任务:先用 taskboard_update 把它置为 doing,' +
|
|
606
|
+
'再派发子 Agent 执行(背景执行,不要自己在对话里等),然后结束本轮。' +
|
|
607
|
+
'子 Agent 回报后审核:通过就 taskboard_update 置为 done 并把结论写进 result;' +
|
|
608
|
+
'不通过就 send_message 打回同一个子 Agent 重做,任务保持 doing。' +
|
|
609
|
+
'写 result 时用 Markdown(小标题、- 列表、| 表格 |、`代码`),看板详情浮层会按 Markdown 渲染,' +
|
|
610
|
+
'一段大白话在详情里很难读。子 Agent 的汇报也要求同样的 Markdown 结构。',
|
|
611
|
+
)
|
|
612
|
+
if (task.notificationCount > 0) {
|
|
613
|
+
lines.push('(这是第 ' + (task.notificationCount + 1) + ' 次提醒;任务仍未派发。)')
|
|
614
|
+
}
|
|
615
|
+
lines.push('看板时间:' + iso(now))
|
|
616
|
+
return lines.join('\n')
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* 手工构造一条 UserMessage(等价于 @deepseek-ai/dsh-llm 的 createUserMessage,
|
|
621
|
+
* 但本包不 import 它)。source 用内置的 {kind:'user'},保证会话日志解码器一定认识。
|
|
622
|
+
*/
|
|
623
|
+
export function createBoardUserMessage(text) {
|
|
624
|
+
return {
|
|
625
|
+
id: randomUUID(),
|
|
626
|
+
role: 'user',
|
|
627
|
+
content: [{ type: 'text', text }],
|
|
628
|
+
source: { kind: 'user' },
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/* ------------------------------------------------------------------ *
|
|
633
|
+
* 预设(模式)状态
|
|
634
|
+
* ------------------------------------------------------------------ */
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* 0.2.2 起 preset 不再是 $DSH_HOME/.agent-presets 目录,而是 bundle patch 里的
|
|
638
|
+
* 一条 @deepseek-ai/dsh-agent-preset 声明行(见 presets/taskboard.patch.yml):
|
|
639
|
+
* 插件装进 profile 就声明了两个模式,随 Loader 组合加载,不需要写盘、也不需要额外重启。
|
|
640
|
+
* 这里只负责把 registry 的实时名单读出来给 UI 用。
|
|
641
|
+
*/
|
|
642
|
+
export const DISPATCH_PRESET_ID = 'taskboard-dispatch'
|
|
643
|
+
export const WORKER_PRESET_ID = 'taskboard-worker'
|
|
644
|
+
export const PRESET_PATCH_PATH = 'presets/taskboard.patch.yml'
|
|
645
|
+
|
|
646
|
+
function readPluginVersion() {
|
|
647
|
+
try {
|
|
648
|
+
const pkg = readJsonFile(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'))
|
|
649
|
+
const version = pkg && typeof pkg.version === 'string' ? pkg.version : ''
|
|
650
|
+
return version || '0.0.0'
|
|
651
|
+
} catch {
|
|
652
|
+
return '0.0.0'
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
export const PLUGIN_VERSION = readPluginVersion()
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* 读 agentPresets 注册表,返回两个模式的实时状态。
|
|
660
|
+
* @returns {Promise<{installed:boolean, version:string, path:string, restartRequired:boolean, broken:string, presets:object[]}>}
|
|
661
|
+
*/
|
|
662
|
+
export async function inspectPresets(ctx, version = PLUGIN_VERSION) {
|
|
663
|
+
const base = {
|
|
664
|
+
installed: false,
|
|
665
|
+
version,
|
|
666
|
+
path: 'bundle:' + PRESET_PATCH_PATH,
|
|
667
|
+
restartRequired: false,
|
|
668
|
+
broken: '',
|
|
669
|
+
presets: [],
|
|
670
|
+
}
|
|
671
|
+
const registry = ctx && typeof ctx.get === 'function' ? ctx.get('agentPresets') : undefined
|
|
672
|
+
if (!registry || typeof registry.list !== 'function') {
|
|
673
|
+
return { ...base, reason: '当前部署没有 agentPresets 服务(需要 dsh-web-app profile)' }
|
|
674
|
+
}
|
|
675
|
+
let roster = []
|
|
676
|
+
try {
|
|
677
|
+
roster = await registry.list()
|
|
678
|
+
} catch (error) {
|
|
679
|
+
return { ...base, reason: '读取模式名单失败:' + describeError(error) }
|
|
680
|
+
}
|
|
681
|
+
const ours = (Array.isArray(roster) ? roster : []).filter(
|
|
682
|
+
(item) => item && (item.id === DISPATCH_PRESET_ID || item.id === WORKER_PRESET_ID),
|
|
683
|
+
)
|
|
684
|
+
const dispatch = ours.find((item) => item.id === DISPATCH_PRESET_ID)
|
|
685
|
+
return {
|
|
686
|
+
...base,
|
|
687
|
+
installed: !!dispatch && !dispatch.broken,
|
|
688
|
+
broken: dispatch && dispatch.broken ? dispatch.broken : '',
|
|
689
|
+
presets: ours.map((item) => ({
|
|
690
|
+
id: item.id,
|
|
691
|
+
name: typeof item.name === 'string' ? item.name : item.id,
|
|
692
|
+
description: typeof item.description === 'string' ? item.description : '',
|
|
693
|
+
broken: typeof item.broken === 'string' ? item.broken : '',
|
|
694
|
+
})),
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/* ------------------------------------------------------------------ *
|
|
699
|
+
* RPC 信封与 HTTP 处理
|
|
700
|
+
* ------------------------------------------------------------------ */
|
|
701
|
+
|
|
702
|
+
const LOOPBACK_ADDRESSES = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
|
|
703
|
+
|
|
704
|
+
/** 从 Host 头里取精确 hostname(IPv6 保留方括号,去掉端口)。 */
|
|
705
|
+
export function hostnameOfHostHeader(value) {
|
|
706
|
+
const raw = typeof value === 'string' ? value.trim() : ''
|
|
707
|
+
if (raw === '') return ''
|
|
708
|
+
if (raw.startsWith('[')) {
|
|
709
|
+
const end = raw.indexOf(']')
|
|
710
|
+
return end === -1 ? raw.toLowerCase() : raw.slice(0, end + 1).toLowerCase()
|
|
711
|
+
}
|
|
712
|
+
const colon = raw.lastIndexOf(':')
|
|
713
|
+
return (colon === -1 ? raw : raw.slice(0, colon)).toLowerCase()
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* 只服务 loopback。判据是 TCP 对端地址(请求头伪造不了它),**不看 Host 头**——
|
|
718
|
+
* Host 头只用来给出可读的 403 提示,绝不作为放行依据(否则 Host: 127.0.0.1.evil.com 可绕过)。
|
|
719
|
+
* 本机反向代理转发时对端仍是 127.0.0.1,照常放行。
|
|
720
|
+
*/
|
|
721
|
+
export function isLoopbackRequest(req) {
|
|
722
|
+
const address = req && req.socket && req.socket.remoteAddress ? req.socket.remoteAddress : ''
|
|
723
|
+
return LOOPBACK_ADDRESSES.has(address)
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
function sendPlain(res, status, text) {
|
|
727
|
+
try {
|
|
728
|
+
res.statusCode = status
|
|
729
|
+
res.setHeader('content-type', 'text/plain; charset=utf-8')
|
|
730
|
+
res.setHeader('cache-control', 'no-store')
|
|
731
|
+
res.end(text)
|
|
732
|
+
} catch {
|
|
733
|
+
/* 响应可能已写出 */
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
function sendJson(res, status, value) {
|
|
738
|
+
try {
|
|
739
|
+
res.statusCode = status
|
|
740
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
741
|
+
res.setHeader('cache-control', 'no-store')
|
|
742
|
+
res.end(JSON.stringify(value))
|
|
743
|
+
} catch {
|
|
744
|
+
/* 响应可能已写出 */
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
function readRequestBody(req, limit = MAX_BODY_BYTES) {
|
|
749
|
+
return new Promise((resolve, reject) => {
|
|
750
|
+
const chunks = []
|
|
751
|
+
let size = 0
|
|
752
|
+
req.on('data', (chunk) => {
|
|
753
|
+
size += chunk.length
|
|
754
|
+
if (size > limit) {
|
|
755
|
+
reject(new BoardError('bad-request', '请求体超过 ' + limit + ' 字节'))
|
|
756
|
+
try {
|
|
757
|
+
req.destroy()
|
|
758
|
+
} catch {
|
|
759
|
+
/* ignore */
|
|
760
|
+
}
|
|
761
|
+
return
|
|
762
|
+
}
|
|
763
|
+
chunks.push(chunk)
|
|
764
|
+
})
|
|
765
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
|
766
|
+
req.on('error', (error) => reject(error))
|
|
767
|
+
})
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** 解析 RPC 信封(纯函数)。 */
|
|
771
|
+
export function parseRpcEnvelope(body) {
|
|
772
|
+
let parsed
|
|
773
|
+
try {
|
|
774
|
+
parsed = JSON.parse(body)
|
|
775
|
+
} catch {
|
|
776
|
+
throw new BoardError('bad-request', '请求体不是合法 JSON')
|
|
777
|
+
}
|
|
778
|
+
if (!isPlainObject(parsed)) throw new BoardError('bad-request', '信封必须是 JSON 对象')
|
|
779
|
+
if (parsed.type !== 'client-request') throw new BoardError('bad-request', '信封 type 必须是 client-request')
|
|
780
|
+
const rpcId = typeof parsed.rpcId === 'string' && parsed.rpcId !== '' ? parsed.rpcId : null
|
|
781
|
+
const method = typeof parsed.method === 'string' ? parsed.method.trim() : ''
|
|
782
|
+
if (method === '') throw new BoardError('bad-request', '信封缺少 method')
|
|
783
|
+
const payload = isPlainObject(parsed.payload) ? parsed.payload : {}
|
|
784
|
+
return { rpcId, method, payload }
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** 从 /taskboard/<endpoint> 提取 endpoint(纯函数)。 */
|
|
788
|
+
export function endpointFromUrl(rawUrl) {
|
|
789
|
+
const text = typeof rawUrl === 'string' && rawUrl !== '' ? rawUrl : '/'
|
|
790
|
+
const path = text.split('?')[0].split('#')[0]
|
|
791
|
+
if (!path.startsWith(RPC_CHANNEL)) return ''
|
|
792
|
+
const rest = path.slice(RPC_CHANNEL.length).replace(/^\/+/, '')
|
|
793
|
+
if (rest === '') return ''
|
|
794
|
+
const first = rest.split('/')[0]
|
|
795
|
+
return decodeURIComponent(first)
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
function errorPayload(error) {
|
|
799
|
+
if (error instanceof BoardError) {
|
|
800
|
+
return { ok: false, error: { code: error.code, message: error.message, details: error.details || {} } }
|
|
801
|
+
}
|
|
802
|
+
return { ok: false, error: { code: 'internal', message: describeError(error), details: {} } }
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
async function handleHttp(rt, req, res) {
|
|
806
|
+
if (!req || !res) return
|
|
807
|
+
if (req.method !== 'POST') return sendPlain(res, 405, 'method not allowed')
|
|
808
|
+
if (!isLoopbackRequest(req)) return sendPlain(res, 403, 'forbidden: loopback only')
|
|
809
|
+
const contentType = String((req.headers && req.headers['content-type']) || '')
|
|
810
|
+
if (!contentType.toLowerCase().includes('application/json')) {
|
|
811
|
+
return sendPlain(res, 415, 'expected application/json')
|
|
812
|
+
}
|
|
813
|
+
const endpoint = endpointFromUrl(typeof req.url === 'string' ? req.url : '/')
|
|
814
|
+
let rpcId = null
|
|
815
|
+
try {
|
|
816
|
+
const body = await readRequestBody(req)
|
|
817
|
+
const envelope = parseRpcEnvelope(body)
|
|
818
|
+
rpcId = envelope.rpcId
|
|
819
|
+
if (endpoint !== '' && envelope.method !== endpoint) {
|
|
820
|
+
throw new BoardError('bad-request', '路径端点 ' + endpoint + ' 与信封 method ' + envelope.method + ' 不一致')
|
|
821
|
+
}
|
|
822
|
+
const value = await dispatchRpc(rt, envelope.method, envelope.payload)
|
|
823
|
+
return sendJson(res, 200, { type: 'server-response', rpcId, result: { ok: true, value } })
|
|
824
|
+
} catch (error) {
|
|
825
|
+
if (!(error instanceof BoardError)) console.error('[taskboard] RPC 处理失败:' + describeError(error))
|
|
826
|
+
return sendJson(res, 200, { type: 'server-response', rpcId, result: errorPayload(error) })
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/* ------------------------------------------------------------------ *
|
|
831
|
+
* 快照与 RPC 端点
|
|
832
|
+
* ------------------------------------------------------------------ */
|
|
833
|
+
|
|
834
|
+
function sessionTitle(agent) {
|
|
835
|
+
try {
|
|
836
|
+
const header = agent && agent.session && agent.session.header
|
|
837
|
+
const title = header && typeof header.title === 'string' ? header.title.trim() : ''
|
|
838
|
+
if (title !== '') return title.length > SESSION_TITLE_MAX ? title.slice(0, SESSION_TITLE_MAX) : title
|
|
839
|
+
} catch {
|
|
840
|
+
/* ignore */
|
|
841
|
+
}
|
|
842
|
+
return ''
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
function sessionCwd(agent) {
|
|
846
|
+
try {
|
|
847
|
+
const header = agent && agent.session && agent.session.header
|
|
848
|
+
return header && typeof header.cwd === 'string' && header.cwd !== '' ? header.cwd : null
|
|
849
|
+
} catch {
|
|
850
|
+
return null
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function agentSessionId(agent) {
|
|
855
|
+
if (!agent) return null
|
|
856
|
+
if (typeof agent.id === 'string' && agent.id !== '') return agent.id
|
|
857
|
+
return sessionCwd(agent) === null && agent.session && typeof agent.session.id === 'string' ? agent.session.id : null
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/** 读缓存(过期才重新问 registry)。 */
|
|
861
|
+
async function refreshPresetInfo(rt, force = false) {
|
|
862
|
+
const now = Date.now()
|
|
863
|
+
if (!force && rt.presetInfo && now - (rt.presetInfoAt || 0) < PRESET_CACHE_MS) return rt.presetInfo
|
|
864
|
+
const info = await inspectPresets(rt.ctx)
|
|
865
|
+
rt.presetInfo = info
|
|
866
|
+
rt.presetInfoAt = now
|
|
867
|
+
return info
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
function listAgents(rt) {
|
|
871
|
+
const agents = typeof rt.ctx.get === 'function' ? rt.ctx.get('agents') : undefined
|
|
872
|
+
if (!agents) return []
|
|
873
|
+
let roots = []
|
|
874
|
+
try {
|
|
875
|
+
roots = typeof agents.roots === 'function' ? agents.roots() : []
|
|
876
|
+
} catch {
|
|
877
|
+
roots = []
|
|
878
|
+
}
|
|
879
|
+
const rows = []
|
|
880
|
+
for (const agent of roots) {
|
|
881
|
+
const sessionId = agentSessionId(agent)
|
|
882
|
+
if (!sessionId) continue
|
|
883
|
+
rows.push({
|
|
884
|
+
sessionId,
|
|
885
|
+
status: agent.status === 'running' ? 'running' : 'idle',
|
|
886
|
+
cwd: sessionCwd(agent),
|
|
887
|
+
title: sessionTitle(agent),
|
|
888
|
+
preset: sessionPresetOfContext(rt.ctx, agent) || null,
|
|
889
|
+
root: true,
|
|
890
|
+
})
|
|
891
|
+
}
|
|
892
|
+
return rows
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/** 路径取尾段作为展示名(Windows 反斜杠 / POSIX 都吃)。 */
|
|
896
|
+
export function baseName(path) {
|
|
897
|
+
if (typeof path !== 'string' || path === '') return ''
|
|
898
|
+
const parts = path.replace(/[\\/]+$/, '').split(/[\\/]/)
|
|
899
|
+
return parts.length > 0 ? parts[parts.length - 1] : path
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/** 是否 Windows 风格路径(盘符或反斜杠):只有它们才按大小写不敏感比较。 */
|
|
903
|
+
export function isWindowsStylePath(path) {
|
|
904
|
+
return typeof path === 'string' && (/^[A-Za-z]:[\\/]/.test(path) || path.includes('\\'))
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* 路径比较用归一化:统一反斜杠、去尾斜杠。
|
|
909
|
+
* Windows 风格路径一律小写(看盘符/反斜杠,而不是宿主平台)——
|
|
910
|
+
* Linux 上的 Web 端也可能管理 C:\ 路径,按平台判断会让同一目录被判成不同。
|
|
911
|
+
*/
|
|
912
|
+
export function normalizePathForCompare(path) {
|
|
913
|
+
if (typeof path !== 'string' || path === '') return ''
|
|
914
|
+
let value = path.replace(/\//g, '\\').replace(/\\+$/, '')
|
|
915
|
+
if (isWindowsStylePath(path)) value = value.toLowerCase()
|
|
916
|
+
return value
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/** 读工作区注册表(Web 端 ctx.workspaceRegistry.list()):平台看板用它列工作区。 */
|
|
920
|
+
export function listWorkspaces(rt) {
|
|
921
|
+
const rows = []
|
|
922
|
+
try {
|
|
923
|
+
const registry = rt && rt.ctx && typeof rt.ctx.get === 'function' ? rt.ctx.get('workspaceRegistry') : undefined
|
|
924
|
+
if (!registry || typeof registry.list !== 'function') return rows
|
|
925
|
+
for (const workspace of registry.list()) {
|
|
926
|
+
if (!workspace || typeof workspace.path !== 'string' || workspace.path === '') continue
|
|
927
|
+
rows.push({
|
|
928
|
+
id: typeof workspace.id === 'string' ? workspace.id : String(workspace.id),
|
|
929
|
+
path: workspace.path,
|
|
930
|
+
title:
|
|
931
|
+
typeof workspace.title === 'string' && workspace.title !== '' ? workspace.title : baseName(workspace.path),
|
|
932
|
+
status: typeof workspace.status === 'string' ? workspace.status : 'ok',
|
|
933
|
+
})
|
|
934
|
+
}
|
|
935
|
+
} catch (error) {
|
|
936
|
+
console.warn('[taskboard] 读工作区列表失败:' + describeError(error))
|
|
937
|
+
}
|
|
938
|
+
return rows
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
export function buildSnapshot(rt, now = Date.now(), preset = rt.presetInfo || null) {
|
|
942
|
+
const config = normalizeConfig(rt.state.config)
|
|
943
|
+
return {
|
|
944
|
+
version: BOARD_VERSION,
|
|
945
|
+
revision: Number(rt.state.revision) || 0,
|
|
946
|
+
updatedAt: rt.state.updatedAt,
|
|
947
|
+
config,
|
|
948
|
+
tasks: rt.state.tasks.map((task) => ({ ...task })),
|
|
949
|
+
poll: {
|
|
950
|
+
running: rt.poll.running === true,
|
|
951
|
+
lastRunAt: rt.poll.lastRunAt || null,
|
|
952
|
+
lastDispatchAt: rt.poll.lastDispatchAt || null,
|
|
953
|
+
lastDispatchTaskId: rt.poll.lastDispatchTaskId || null,
|
|
954
|
+
lastDispatchSessionId: rt.poll.lastDispatchSessionId || null,
|
|
955
|
+
lastDispatchSessionTitle: rt.poll.lastDispatchSessionTitle || null,
|
|
956
|
+
lastSkipReason: rt.poll.lastSkipReason || null,
|
|
957
|
+
},
|
|
958
|
+
agents: listAgents(rt),
|
|
959
|
+
workspaces: listWorkspaces(rt),
|
|
960
|
+
preset,
|
|
961
|
+
boardPath: rt.filePath,
|
|
962
|
+
pluginVersion: PLUGIN_VERSION,
|
|
963
|
+
now: iso(now),
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
async function dispatchRpc(rt, method, payload) {
|
|
968
|
+
// 每次请求前都对齐盘上状态:另一个进程(例如同时开着的测试实例)可能刚改过,
|
|
969
|
+
// 读也要对齐,否则界面会一直显示旧内存状态(表现为「点了归档还是已完成」)。
|
|
970
|
+
if (method !== 'session-info' && method !== 'install-preset') reloadBoardIfStale(rt)
|
|
971
|
+
switch (method) {
|
|
972
|
+
case 'snapshot':
|
|
973
|
+
return buildSnapshot(rt, Date.now(), await refreshPresetInfo(rt))
|
|
974
|
+
case 'add-task': {
|
|
975
|
+
// 从哪个对话加的,就记下那个会话与工作区:派发时优先回这个对话执行。
|
|
976
|
+
let cwd = typeof payload.cwd === 'string' && payload.cwd !== '' ? payload.cwd : resolveSessionCwd(rt.ctx, payload.sessionId)
|
|
977
|
+
if (!cwd) cwd = await resolveSessionCwdViaQuery(rt.ctx, payload.sessionId)
|
|
978
|
+
const task = addTask(rt.state, { ...payload, cwd })
|
|
979
|
+
commitBoard(rt.state, rt.filePath)
|
|
980
|
+
return { task }
|
|
981
|
+
}
|
|
982
|
+
case 'update-task': {
|
|
983
|
+
const id = payload.id
|
|
984
|
+
const rest = {}
|
|
985
|
+
for (const key of Object.keys(payload)) if (key !== 'id' && key !== 'patch') rest[key] = payload[key]
|
|
986
|
+
const patch = isPlainObject(payload.patch) ? payload.patch : rest
|
|
987
|
+
const task = applyTaskUpdate(rt.state, id, patch)
|
|
988
|
+
commitBoard(rt.state, rt.filePath)
|
|
989
|
+
return { task }
|
|
990
|
+
}
|
|
991
|
+
case 'delete-task': {
|
|
992
|
+
const task = deleteTask(rt.state, payload.id)
|
|
993
|
+
commitBoard(rt.state, rt.filePath)
|
|
994
|
+
return { deleted: true, id: task.id }
|
|
995
|
+
}
|
|
996
|
+
case 'dispatch-now': {
|
|
997
|
+
const result = await tick(rt, { taskId: payload.id, force: true })
|
|
998
|
+
return result
|
|
999
|
+
}
|
|
1000
|
+
case 'set-config': {
|
|
1001
|
+
const next = normalizeConfig({ ...normalizeConfig(rt.state.config), ...payload })
|
|
1002
|
+
const intervalChanged = next.pollIntervalMs !== normalizeConfig(rt.state.config).pollIntervalMs
|
|
1003
|
+
rt.state.config = next
|
|
1004
|
+
commitBoard(rt.state, rt.filePath)
|
|
1005
|
+
if (intervalChanged) startPolling(rt)
|
|
1006
|
+
return { config: next }
|
|
1007
|
+
}
|
|
1008
|
+
case 'archive-done': {
|
|
1009
|
+
const archived = archiveDoneTasks(rt.state)
|
|
1010
|
+
if (archived > 0) commitBoard(rt.state, rt.filePath)
|
|
1011
|
+
return { archived }
|
|
1012
|
+
}
|
|
1013
|
+
case 'session-info': {
|
|
1014
|
+
// 给 client 用:冷会话(历史会话)不在 snapshot.agents 里,也能拿到它的工作区做提示。
|
|
1015
|
+
const cwd = resolveSessionCwd(rt.ctx, payload.sessionId) || (await resolveSessionCwdViaQuery(rt.ctx, payload.sessionId))
|
|
1016
|
+
return { sessionId: typeof payload.sessionId === 'string' ? payload.sessionId : null, cwd }
|
|
1017
|
+
}
|
|
1018
|
+
case 'install-preset': {
|
|
1019
|
+
// 兼容旧客户端:0.2.2 起预设随 bundle 安装,这个端点只刷新状态、不再写盘。
|
|
1020
|
+
const preset = await refreshPresetInfo(rt, true)
|
|
1021
|
+
return { ...preset, action: 'none', reason: '预设随插件包声明,无需写盘或额外重启' }
|
|
1022
|
+
}
|
|
1023
|
+
default:
|
|
1024
|
+
throw new BoardError('bad-request', '未知端点:' + method)
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
/* ------------------------------------------------------------------ *
|
|
1029
|
+
* 轮询派单
|
|
1030
|
+
* ------------------------------------------------------------------ */
|
|
1031
|
+
|
|
1032
|
+
const SKIP_TEXT = {
|
|
1033
|
+
'poll-disabled': '轮询已暂停',
|
|
1034
|
+
'agent-busy': '目标会话正在运行,稍后再派',
|
|
1035
|
+
'creator-busy': '创建这条任务的对话正在运行,等它空下来再派',
|
|
1036
|
+
'creator-cold': '创建这条任务的对话还没激活(历史会话):在那边发一条消息,任务就会回到该对话执行;急的话点「立即派发」',
|
|
1037
|
+
'workspace-busy': '这条任务所属工作区的对话正在忙,等它空下来再派',
|
|
1038
|
+
'workspace-offline': '这条任务所属工作区没有打开的对话:先在那个工作区开一个对话,或点「立即派发」改派',
|
|
1039
|
+
'agent-offline': '任务指定的会话不在线',
|
|
1040
|
+
'no-live-agent': '没有在线的会话',
|
|
1041
|
+
'no-agents-service': 'agents 服务不可用',
|
|
1042
|
+
'followup-failed': '投递消息失败',
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
function skipText(reason) {
|
|
1046
|
+
return SKIP_TEXT[reason] || ''
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/**
|
|
1050
|
+
* 「派发到新对话」:在任务所属工作区新建一个派单模式的会话,把任务投给它。
|
|
1051
|
+
* 失败返回 null(调用方退回自动挑会话),不抛。
|
|
1052
|
+
*/
|
|
1053
|
+
export function workspaceIdForCwd(ctx, cwd) {
|
|
1054
|
+
if (typeof cwd !== 'string' || cwd === '') return ''
|
|
1055
|
+
const want = normalizePathForCompare(cwd)
|
|
1056
|
+
if (want === '') return ''
|
|
1057
|
+
try {
|
|
1058
|
+
const registry = ctx && typeof ctx.get === 'function' ? ctx.get('workspaceRegistry') : undefined
|
|
1059
|
+
if (!registry || typeof registry.list !== 'function') return ''
|
|
1060
|
+
const hit = registry.list().find((workspace) => workspace && typeof workspace.path === 'string' && normalizePathForCompare(workspace.path) === want)
|
|
1061
|
+
return hit && typeof hit.id === 'string' ? hit.id : ''
|
|
1062
|
+
} catch {
|
|
1063
|
+
return ''
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
async function createDispatchSession(rt, task) {
|
|
1068
|
+
try {
|
|
1069
|
+
const controller = typeof rt.ctx.get === 'function' ? rt.ctx.get('sessionController') : undefined
|
|
1070
|
+
if (!controller || typeof controller.create !== 'function') return null
|
|
1071
|
+
let cwd = task && typeof task.cwd === 'string' && task.cwd !== '' ? task.cwd : resolveSessionCwd(rt.ctx, task && task.sessionId)
|
|
1072
|
+
if (!cwd) cwd = await resolveSessionCwdViaQuery(rt.ctx, task && task.sessionId)
|
|
1073
|
+
if (!cwd) return null
|
|
1074
|
+
// 优先按工作区创建:这样新对话会落在任务所属工作区分组里,而不是「未分组」。
|
|
1075
|
+
const workspaceId = workspaceIdForCwd(rt.ctx, cwd)
|
|
1076
|
+
let created = null
|
|
1077
|
+
if (workspaceId !== '') {
|
|
1078
|
+
try {
|
|
1079
|
+
created = await controller.create({ workspaceId, agentPreset: DISPATCH_PRESET_ID })
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
console.warn('[taskboard] 按工作区新建对话失败,退回按 cwd 新建:' + describeError(error))
|
|
1082
|
+
created = null
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
if (!created) created = await controller.create({ cwd, agentPreset: DISPATCH_PRESET_ID })
|
|
1086
|
+
const sessionId = created && typeof created.sessionId === 'string' ? created.sessionId : ''
|
|
1087
|
+
if (sessionId === '') return null
|
|
1088
|
+
const agents = typeof rt.ctx.get === 'function' ? rt.ctx.get('agents') : undefined
|
|
1089
|
+
let agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : undefined
|
|
1090
|
+
if (!agent && typeof controller.resolveAgent === 'function') {
|
|
1091
|
+
const resolved = await controller.resolveAgent(sessionId)
|
|
1092
|
+
if (resolved && resolved.agent) agent = resolved.agent
|
|
1093
|
+
}
|
|
1094
|
+
if (!agent) return null
|
|
1095
|
+
console.log('[taskboard] 任务 ' + (task && task.id) + ' 新建对话:' + sessionId + '(' + cwd + ')')
|
|
1096
|
+
return agent
|
|
1097
|
+
} catch (error) {
|
|
1098
|
+
console.warn('[taskboard] 新建派发对话失败:' + describeError(error))
|
|
1099
|
+
return null
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
export async function tick(rt, options = {}) {
|
|
1104
|
+
reloadBoardIfStale(rt)
|
|
1105
|
+
const now = Date.now()
|
|
1106
|
+
rt.poll.lastRunAt = iso(now)
|
|
1107
|
+
const config = normalizeConfig(rt.state.config)
|
|
1108
|
+
if (!config.pollEnabled && !options.taskId) {
|
|
1109
|
+
rt.poll.lastSkipReason = 'poll-disabled'
|
|
1110
|
+
return { dispatched: false, reason: 'poll-disabled' }
|
|
1111
|
+
}
|
|
1112
|
+
let candidates = []
|
|
1113
|
+
if (options.taskId) {
|
|
1114
|
+
const single = findTask(rt.state, options.taskId)
|
|
1115
|
+
if (single.status !== 'todo') throw new BoardError('conflict', '只有待开始的任务可以立即派发(当前状态:' + single.status + ')')
|
|
1116
|
+
candidates = [single]
|
|
1117
|
+
} else {
|
|
1118
|
+
candidates = selectDispatchCandidates(rt.state, now)
|
|
1119
|
+
if (candidates.length === 0) {
|
|
1120
|
+
rt.poll.lastSkipReason = null
|
|
1121
|
+
return { dispatched: false, reason: 'no-candidate' }
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
const agents = typeof rt.ctx.get === 'function' ? rt.ctx.get('agents') : undefined
|
|
1125
|
+
const presetOf = (agent) => sessionPresetOfContext(rt.ctx, agent)
|
|
1126
|
+
|
|
1127
|
+
// 逐条试:某个任务的目标会话正忙时跳过它,继续看下一条,避免「一个忙会话挡住整列任务」。
|
|
1128
|
+
let task = null
|
|
1129
|
+
let resolved = { agent: null, reason: null }
|
|
1130
|
+
const mode = config.dispatchMode || 'new'
|
|
1131
|
+
for (const candidate of candidates) {
|
|
1132
|
+
// 默认「派发到新对话」:在任务工作区新建一个派单模式会话,任务不会被塞进别人的对话里。
|
|
1133
|
+
if (mode === 'new') {
|
|
1134
|
+
const freshAgent = await createDispatchSession(rt, candidate)
|
|
1135
|
+
if (freshAgent) {
|
|
1136
|
+
task = candidate
|
|
1137
|
+
resolved = { agent: freshAgent, reason: 'new-session' }
|
|
1138
|
+
break
|
|
1139
|
+
}
|
|
1140
|
+
// 新建失败(没有 sessionController / 解析不到工作区 / 预设不可用)→ 退回自动挑会话
|
|
1141
|
+
}
|
|
1142
|
+
// 创建它的对话没 live agent(历史会话)→ 先试着唤醒它,任务回到用户当时的那个对话。
|
|
1143
|
+
if (mode !== 'auto' && candidate.sessionId) {
|
|
1144
|
+
const liveCreator = agents && typeof agents.get === 'function' ? agents.get(candidate.sessionId) : undefined
|
|
1145
|
+
if (!liveCreator) await reviveSessionAgent(rt, candidate.sessionId)
|
|
1146
|
+
}
|
|
1147
|
+
const attempt = resolveTargetAgent(agents, candidate, presetOf, {
|
|
1148
|
+
force: options.force === true,
|
|
1149
|
+
ignoreCreator: mode === 'auto',
|
|
1150
|
+
})
|
|
1151
|
+
if (!attempt.agent) {
|
|
1152
|
+
rt.poll.lastSkipReason = attempt.reason
|
|
1153
|
+
const text = skipText(attempt.reason)
|
|
1154
|
+
if (text !== '' && candidate.lastError !== text) {
|
|
1155
|
+
candidate.lastError = text
|
|
1156
|
+
candidate.updatedAt = iso(now)
|
|
1157
|
+
commitBoard(rt.state, rt.filePath)
|
|
1158
|
+
}
|
|
1159
|
+
continue
|
|
1160
|
+
}
|
|
1161
|
+
if (!options.force && attempt.agent.status !== 'idle') {
|
|
1162
|
+
rt.poll.lastSkipReason = 'agent-busy'
|
|
1163
|
+
continue
|
|
1164
|
+
}
|
|
1165
|
+
task = candidate
|
|
1166
|
+
resolved = attempt
|
|
1167
|
+
break
|
|
1168
|
+
}
|
|
1169
|
+
if (!task) return { dispatched: false, reason: rt.poll.lastSkipReason || 'no-live-agent' }
|
|
1170
|
+
const sessionId = agentSessionId(resolved.agent)
|
|
1171
|
+
// 创建时没能解析出工作区(会话还没 live)→ 投递前从目标会话补一次,派发文本就能带上工作目录。
|
|
1172
|
+
if (!task.cwd) {
|
|
1173
|
+
const cwd = sessionCwd(resolved.agent)
|
|
1174
|
+
if (cwd) task.cwd = cwd
|
|
1175
|
+
}
|
|
1176
|
+
const message = createBoardUserMessage(buildDispatchText(task, now))
|
|
1177
|
+
try {
|
|
1178
|
+
resolved.agent.followup(message)
|
|
1179
|
+
// 关键:等 inbox splice 落盘再记账,否则重启会丢消息但 notificationCount 已 +1。
|
|
1180
|
+
// 官方 dsh-schedule 的投递路径同样在 followup 之后 await sessions.flush。
|
|
1181
|
+
try {
|
|
1182
|
+
const sessions = typeof rt.ctx.get === 'function' ? rt.ctx.get('sessions') : undefined
|
|
1183
|
+
if (sessions && typeof sessions.flush === 'function') await sessions.flush(resolved.agent.session)
|
|
1184
|
+
} catch (flushError) {
|
|
1185
|
+
console.warn('[taskboard] 会话 flush 失败(消息已入队):' + describeError(flushError))
|
|
1186
|
+
}
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
rt.poll.lastSkipReason = 'followup-failed'
|
|
1189
|
+
task.lastError = skipText('followup-failed') + ':' + describeError(error)
|
|
1190
|
+
task.updatedAt = iso(now)
|
|
1191
|
+
commitBoard(rt.state, rt.filePath)
|
|
1192
|
+
console.warn('[taskboard] 派发失败:' + describeError(error))
|
|
1193
|
+
return { dispatched: false, reason: 'followup-failed', error: describeError(error) }
|
|
1194
|
+
}
|
|
1195
|
+
task.notifiedAt = iso(now)
|
|
1196
|
+
task.notificationCount = (Number(task.notificationCount) || 0) + 1
|
|
1197
|
+
task.updatedAt = iso(now)
|
|
1198
|
+
task.lastError = ''
|
|
1199
|
+
// 投递成功即视为「进行中」:看板立刻反映已派发,不再依赖主 Agent 记得调 taskboard_update
|
|
1200
|
+
// (它照样可以再调一次 doing,迁移 doing→doing 合法)。
|
|
1201
|
+
if (task.status === 'todo') {
|
|
1202
|
+
task.status = 'doing'
|
|
1203
|
+
if (!task.startedAt) task.startedAt = iso(now)
|
|
1204
|
+
}
|
|
1205
|
+
rt.poll.lastDispatchAt = iso(now)
|
|
1206
|
+
rt.poll.lastDispatchSessionId = sessionId
|
|
1207
|
+
rt.poll.lastDispatchSessionTitle = sessionTitle(resolved.agent)
|
|
1208
|
+
task.dispatchedSessionId = sessionId
|
|
1209
|
+
task.dispatchedSessionTitle = sessionTitle(resolved.agent) || ''
|
|
1210
|
+
rt.poll.lastDispatchTaskId = task.id
|
|
1211
|
+
rt.poll.lastSkipReason = null
|
|
1212
|
+
commitBoard(rt.state, rt.filePath)
|
|
1213
|
+
return { dispatched: true, sessionId, task: { ...task } }
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
/** 唤醒失败缓存:同一会话 5 分钟内不重复尝试 resume。 */
|
|
1217
|
+
const REVIVE_RETRY_MS = 5 * 60 * 1000
|
|
1218
|
+
|
|
1219
|
+
/**
|
|
1220
|
+
* 把「创建任务的对话」从冷会话唤醒成 live agent(Web 端官方路径 sessionController.resolveAgent,
|
|
1221
|
+
* 与 UI 打开会话时的物化一致,带并发去重)。这样从历史会话右栏加的任务也能回到那个对话执行。
|
|
1222
|
+
* @returns {Promise<boolean>} 是否成功拿到 live agent
|
|
1223
|
+
*/
|
|
1224
|
+
async function reviveSessionAgent(rt, sessionId) {
|
|
1225
|
+
if (!sessionId) return false
|
|
1226
|
+
if (!rt.reviveFailures) rt.reviveFailures = new Map()
|
|
1227
|
+
const failedAt = rt.reviveFailures.get(sessionId)
|
|
1228
|
+
if (failedAt !== undefined && Date.now() - failedAt < REVIVE_RETRY_MS) return false
|
|
1229
|
+
const controller = typeof rt.ctx.get === 'function' ? rt.ctx.get('sessionController') : undefined
|
|
1230
|
+
if (!controller || typeof controller.resolveAgent !== 'function') return false
|
|
1231
|
+
try {
|
|
1232
|
+
const result = await controller.resolveAgent(sessionId)
|
|
1233
|
+
if (result && result.agent) {
|
|
1234
|
+
rt.reviveFailures.delete(sessionId)
|
|
1235
|
+
return true
|
|
1236
|
+
}
|
|
1237
|
+
const code = result && result.error && result.error.code ? result.error.code : 'unknown'
|
|
1238
|
+
rt.reviveFailures.set(sessionId, Date.now())
|
|
1239
|
+
console.warn('[taskboard] 唤醒会话 ' + sessionId + ' 失败:' + code)
|
|
1240
|
+
return false
|
|
1241
|
+
} catch (error) {
|
|
1242
|
+
rt.reviveFailures.set(sessionId, Date.now())
|
|
1243
|
+
console.warn('[taskboard] 唤醒会话 ' + sessionId + ' 异常:' + describeError(error))
|
|
1244
|
+
return false
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
function stopPolling(rt) {
|
|
1249
|
+
if (rt.timer) {
|
|
1250
|
+
try {
|
|
1251
|
+
rt.timer()
|
|
1252
|
+
} catch {
|
|
1253
|
+
/* disposer 已失效 */
|
|
1254
|
+
}
|
|
1255
|
+
rt.timer = null
|
|
1256
|
+
}
|
|
1257
|
+
rt.poll.running = false
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
/** 定时器的执行函数:防重入 + 用 withoutInitiator 避免把看板工作记到某个 Agent 的因果链上。 */
|
|
1261
|
+
function pollTick(rt) {
|
|
1262
|
+
if (rt.polling) return
|
|
1263
|
+
rt.polling = true
|
|
1264
|
+
const run = () => {
|
|
1265
|
+
tick(rt)
|
|
1266
|
+
.catch((error) => console.warn('[taskboard] 轮询异常:' + describeError(error)))
|
|
1267
|
+
.finally(() => {
|
|
1268
|
+
rt.polling = false
|
|
1269
|
+
})
|
|
1270
|
+
}
|
|
1271
|
+
try {
|
|
1272
|
+
const agents = typeof rt.ctx.get === 'function' ? rt.ctx.get('agents') : undefined
|
|
1273
|
+
if (agents && typeof agents.withoutInitiator === 'function') {
|
|
1274
|
+
agents.withoutInitiator(run)
|
|
1275
|
+
return
|
|
1276
|
+
}
|
|
1277
|
+
} catch {
|
|
1278
|
+
/* withoutInitiator 不可用时退化为普通调用 */
|
|
1279
|
+
}
|
|
1280
|
+
run()
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
/**
|
|
1284
|
+
* 启动/重建轮询定时器。优先 ctx.interval(插件卸载自动清理),退化 setInterval。
|
|
1285
|
+
* 改间隔时先 stopPolling 再 startPolling。
|
|
1286
|
+
*/
|
|
1287
|
+
function startPolling(rt) {
|
|
1288
|
+
stopPolling(rt)
|
|
1289
|
+
const interval = normalizeConfig(rt.state.config).pollIntervalMs
|
|
1290
|
+
rt.poll.running = true
|
|
1291
|
+
rt.polling = false
|
|
1292
|
+
try {
|
|
1293
|
+
if (rt.ctx && typeof rt.ctx.interval === 'function') {
|
|
1294
|
+
rt.timer = rt.ctx.interval(() => pollTick(rt), interval)
|
|
1295
|
+
return
|
|
1296
|
+
}
|
|
1297
|
+
} catch (error) {
|
|
1298
|
+
console.warn('[taskboard] ctx.interval 不可用,退化为 setInterval:' + describeError(error))
|
|
1299
|
+
}
|
|
1300
|
+
const handle = setInterval(() => pollTick(rt), interval)
|
|
1301
|
+
if (typeof handle.unref === 'function') handle.unref()
|
|
1302
|
+
rt.timer = () => clearInterval(handle)
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
/* ------------------------------------------------------------------ *
|
|
1306
|
+
* 模型工具
|
|
1307
|
+
* ------------------------------------------------------------------ */
|
|
1308
|
+
|
|
1309
|
+
const TASK_LIST_OUTPUT_SCHEMA = {
|
|
1310
|
+
type: 'object',
|
|
1311
|
+
additionalProperties: false,
|
|
1312
|
+
required: ['count', 'tasks'],
|
|
1313
|
+
properties: {
|
|
1314
|
+
count: { type: 'integer' },
|
|
1315
|
+
tasks: {
|
|
1316
|
+
type: 'array',
|
|
1317
|
+
items: {
|
|
1318
|
+
type: 'object',
|
|
1319
|
+
additionalProperties: false,
|
|
1320
|
+
required: ['id', 'title', 'status'],
|
|
1321
|
+
properties: {
|
|
1322
|
+
id: { type: 'string' },
|
|
1323
|
+
title: { type: 'string' },
|
|
1324
|
+
status: { type: 'string', enum: [...STATUSES] },
|
|
1325
|
+
note: { type: 'string' },
|
|
1326
|
+
assignee: { type: 'string' },
|
|
1327
|
+
result: { type: 'string' },
|
|
1328
|
+
updatedAt: { type: 'string' },
|
|
1329
|
+
},
|
|
1330
|
+
},
|
|
1331
|
+
},
|
|
1332
|
+
},
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
function taskBrief(task) {
|
|
1336
|
+
return {
|
|
1337
|
+
id: task.id,
|
|
1338
|
+
title: task.title,
|
|
1339
|
+
status: task.status,
|
|
1340
|
+
note: task.note || '',
|
|
1341
|
+
assignee: task.assignee || '',
|
|
1342
|
+
dispatchedSessionId: task.dispatchedSessionId || null,
|
|
1343
|
+
result: task.result || '',
|
|
1344
|
+
updatedAt: task.updatedAt,
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
function renderTaskList(value) {
|
|
1349
|
+
if (value.count === 0) return [{ type: 'text', text: '看板没有匹配的任务。' }]
|
|
1350
|
+
const lines = ['看板任务(' + value.count + ' 条):']
|
|
1351
|
+
for (const task of value.tasks) {
|
|
1352
|
+
const bits = ['[' + task.status + ']', task.id, task.title]
|
|
1353
|
+
if (task.assignee) bits.push('@' + task.assignee)
|
|
1354
|
+
lines.push('- ' + bits.join(' '))
|
|
1355
|
+
if (task.note) lines.push(' 备注:' + task.note)
|
|
1356
|
+
if (task.result) lines.push(' 结论:' + task.result)
|
|
1357
|
+
}
|
|
1358
|
+
return [{ type: 'text', text: lines.join('\n') }]
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
function renderTaskOne(prefix, task) {
|
|
1362
|
+
const lines = [prefix + task.id + ' [' + task.status + '] ' + task.title]
|
|
1363
|
+
if (task.note) lines.push('备注:' + task.note)
|
|
1364
|
+
if (task.result) lines.push('结论:' + task.result)
|
|
1365
|
+
lines.push('更新时间:' + task.updatedAt)
|
|
1366
|
+
return [{ type: 'text', text: lines.join('\n') }]
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
const TASK_ONE_OUTPUT_SCHEMA = {
|
|
1370
|
+
type: 'object',
|
|
1371
|
+
additionalProperties: false,
|
|
1372
|
+
required: ['task'],
|
|
1373
|
+
properties: {
|
|
1374
|
+
task: {
|
|
1375
|
+
type: 'object',
|
|
1376
|
+
additionalProperties: false,
|
|
1377
|
+
required: ['id', 'title', 'status'],
|
|
1378
|
+
properties: {
|
|
1379
|
+
id: { type: 'string' },
|
|
1380
|
+
title: { type: 'string' },
|
|
1381
|
+
status: { type: 'string', enum: [...STATUSES] },
|
|
1382
|
+
note: { type: 'string' },
|
|
1383
|
+
assignee: { type: 'string' },
|
|
1384
|
+
result: { type: 'string' },
|
|
1385
|
+
updatedAt: { type: 'string' },
|
|
1386
|
+
},
|
|
1387
|
+
},
|
|
1388
|
+
},
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
/**
|
|
1392
|
+
* 注册三个模型工具。宿主级注册 = 全局可见(所有预设的 Agent 都能用),
|
|
1393
|
+
* 这也是「非派单模式也能往看板里塞任务」的实现方式。
|
|
1394
|
+
*/
|
|
1395
|
+
function registerTools(toolCtx, rt) {
|
|
1396
|
+
const tools = toolCtx.tools
|
|
1397
|
+
if (!tools || typeof tools.register !== 'function') {
|
|
1398
|
+
console.warn('[taskboard] tools 服务不可用,跳过模型工具注册')
|
|
1399
|
+
return
|
|
1400
|
+
}
|
|
1401
|
+
tools.register({
|
|
1402
|
+
name: 'taskboard_list',
|
|
1403
|
+
description:
|
|
1404
|
+
'列出任务看板上的任务(默认全部状态:todo=待开始 / doing=进行中 / done=已完成 / archived=已归档)。' +
|
|
1405
|
+
'派单前用它确认要处理哪条任务,审核后用 taskboard_update 更新状态。',
|
|
1406
|
+
parameters: {
|
|
1407
|
+
type: 'object',
|
|
1408
|
+
additionalProperties: false,
|
|
1409
|
+
properties: {
|
|
1410
|
+
status: {
|
|
1411
|
+
type: 'string',
|
|
1412
|
+
enum: [...STATUSES],
|
|
1413
|
+
description: '只看某一列;省略则返回全部状态。',
|
|
1414
|
+
},
|
|
1415
|
+
},
|
|
1416
|
+
},
|
|
1417
|
+
output: {
|
|
1418
|
+
schema: TASK_LIST_OUTPUT_SCHEMA,
|
|
1419
|
+
render: (_args, value) => renderTaskList(value),
|
|
1420
|
+
},
|
|
1421
|
+
execute(args) {
|
|
1422
|
+
const want = args && args.status !== undefined ? args.status : ''
|
|
1423
|
+
if (want !== '' && !STATUSES.includes(want)) throw new Error('非法状态:' + String(want))
|
|
1424
|
+
const tasks = rt.state.tasks
|
|
1425
|
+
.filter((task) => (want === '' ? true : task.status === want))
|
|
1426
|
+
.map(taskBrief)
|
|
1427
|
+
return Promise.resolve({ count: tasks.length, tasks })
|
|
1428
|
+
},
|
|
1429
|
+
})
|
|
1430
|
+
tools.register({
|
|
1431
|
+
name: 'taskboard_add',
|
|
1432
|
+
description:
|
|
1433
|
+
'往任务看板添加一条待开始任务。用户口述的需求、你自己拆出来的后续任务都可以加进看板,' +
|
|
1434
|
+
'轮询器会把它派给主 Agent。title 必填,note 写验收标准或补充信息。',
|
|
1435
|
+
parameters: {
|
|
1436
|
+
type: 'object',
|
|
1437
|
+
additionalProperties: false,
|
|
1438
|
+
required: ['title'],
|
|
1439
|
+
properties: {
|
|
1440
|
+
title: { type: 'string', description: '任务标题(一句话,必填)' },
|
|
1441
|
+
note: { type: 'string', description: '备注:背景、范围、验收标准' },
|
|
1442
|
+
},
|
|
1443
|
+
},
|
|
1444
|
+
output: {
|
|
1445
|
+
schema: TASK_ONE_OUTPUT_SCHEMA,
|
|
1446
|
+
render: (_args, value) => renderTaskOne('已添加任务 ', value.task),
|
|
1447
|
+
},
|
|
1448
|
+
execute(args, exec) {
|
|
1449
|
+
const title = trimmed(args && args.title, MAX_TITLE_CHARS)
|
|
1450
|
+
if (title === '') throw new Error('title 不能为空')
|
|
1451
|
+
let sessionId = null
|
|
1452
|
+
let cwd = null
|
|
1453
|
+
try {
|
|
1454
|
+
const agent = exec && exec.agent
|
|
1455
|
+
if (agent && agent.session) {
|
|
1456
|
+
sessionId = typeof agent.session.id === 'string' ? agent.session.id : null
|
|
1457
|
+
const header = agent.session.header
|
|
1458
|
+
cwd = header && typeof header.cwd === 'string' ? header.cwd : null
|
|
1459
|
+
}
|
|
1460
|
+
} catch {
|
|
1461
|
+
/* 非 agent 调用时忽略 */
|
|
1462
|
+
}
|
|
1463
|
+
const task = addTask(rt.state, { title, note: args && args.note, source: 'agent', sessionId, cwd })
|
|
1464
|
+
commitBoard(rt.state, rt.filePath)
|
|
1465
|
+
return Promise.resolve({ task: taskBrief(task) })
|
|
1466
|
+
},
|
|
1467
|
+
})
|
|
1468
|
+
tools.register({
|
|
1469
|
+
name: 'taskboard_update',
|
|
1470
|
+
description:
|
|
1471
|
+
'更新看板任务:置为 doing(已派发)、done(审核通过)、todo(打回重做)、archived(归档);' +
|
|
1472
|
+
'也可以用 result 写审核结论、assignee 写子 Agent 标识。状态迁移非法时会返回错误。',
|
|
1473
|
+
parameters: {
|
|
1474
|
+
type: 'object',
|
|
1475
|
+
additionalProperties: false,
|
|
1476
|
+
required: ['id'],
|
|
1477
|
+
properties: {
|
|
1478
|
+
id: { type: 'string', description: '任务 id,例如 t-3' },
|
|
1479
|
+
status: { type: 'string', enum: [...STATUSES], description: '目标状态' },
|
|
1480
|
+
result: { type: 'string', description: '审核结论 / 子 Agent 汇报摘要' },
|
|
1481
|
+
assignee: { type: 'string', description: '子 Agent 的 label 或会话 id' },
|
|
1482
|
+
note: { type: 'string', description: '备注(覆盖原备注)' },
|
|
1483
|
+
},
|
|
1484
|
+
},
|
|
1485
|
+
output: {
|
|
1486
|
+
schema: TASK_ONE_OUTPUT_SCHEMA,
|
|
1487
|
+
render: (_args, value) => renderTaskOne('已更新任务 ', value.task),
|
|
1488
|
+
},
|
|
1489
|
+
execute(args) {
|
|
1490
|
+
if (!args || !args.id) throw new Error('缺少任务 id')
|
|
1491
|
+
const patch = {}
|
|
1492
|
+
for (const key of ['status', 'result', 'assignee', 'note']) {
|
|
1493
|
+
if (args[key] !== undefined) patch[key] = args[key]
|
|
1494
|
+
}
|
|
1495
|
+
const task = applyTaskUpdate(rt.state, args.id, patch)
|
|
1496
|
+
commitBoard(rt.state, rt.filePath)
|
|
1497
|
+
return Promise.resolve({ task: taskBrief(task) })
|
|
1498
|
+
},
|
|
1499
|
+
})
|
|
1500
|
+
console.log('[taskboard] 模型工具已注册:taskboard_list / taskboard_add / taskboard_update')
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
/* ------------------------------------------------------------------ *
|
|
1504
|
+
* 插件入口
|
|
1505
|
+
* ------------------------------------------------------------------ */
|
|
1506
|
+
|
|
1507
|
+
export function apply(ctx) {
|
|
1508
|
+
const runtime = {
|
|
1509
|
+
ctx,
|
|
1510
|
+
filePath: boardPath(),
|
|
1511
|
+
state: createEmptyBoard(),
|
|
1512
|
+
warnings: [],
|
|
1513
|
+
timer: null,
|
|
1514
|
+
polling: false,
|
|
1515
|
+
presetInfo: null,
|
|
1516
|
+
presetInfoAt: 0,
|
|
1517
|
+
reviveFailures: new Map(),
|
|
1518
|
+
poll: {
|
|
1519
|
+
running: false,
|
|
1520
|
+
lastRunAt: null,
|
|
1521
|
+
lastDispatchAt: null,
|
|
1522
|
+
lastDispatchSessionId: null,
|
|
1523
|
+
lastSkipReason: null,
|
|
1524
|
+
},
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
try {
|
|
1528
|
+
const loaded = loadBoardFromDisk(runtime.filePath)
|
|
1529
|
+
runtime.state = loaded.state
|
|
1530
|
+
runtime.warnings = loaded.warnings
|
|
1531
|
+
for (const warning of loaded.warnings) console.warn('[taskboard] ' + warning)
|
|
1532
|
+
} catch (error) {
|
|
1533
|
+
console.warn('[taskboard] 读取看板失败,从空板开始:' + describeError(error))
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
// 模式状态:agentPresets 服务就绪后读名单(预设本身由 bundle patch 声明,不在这里安装)。
|
|
1537
|
+
// 预设行的激活是异步的,所以前几次读不到不算失败——最多重试 3 次再告警。
|
|
1538
|
+
try {
|
|
1539
|
+
ctx.inject(['agentPresets'], () => {
|
|
1540
|
+
const report = (attempt) => {
|
|
1541
|
+
refreshPresetInfo(runtime, true)
|
|
1542
|
+
.then((preset) => {
|
|
1543
|
+
if (preset.installed) {
|
|
1544
|
+
console.log('[taskboard] 派单模式已就绪:' + preset.presets.map((item) => item.name + '(' + item.id + ')').join(' / '))
|
|
1545
|
+
return
|
|
1546
|
+
}
|
|
1547
|
+
if (attempt < 3) {
|
|
1548
|
+
try {
|
|
1549
|
+
ctx.timeout(() => report(attempt + 1), 2500)
|
|
1550
|
+
return
|
|
1551
|
+
} catch {
|
|
1552
|
+
/* 没有 timer 就退化为直接告警 */
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
console.warn('[taskboard] 派单模式未加载:' + (preset.broken || preset.reason || '未知原因'))
|
|
1556
|
+
})
|
|
1557
|
+
.catch((error) => console.warn('[taskboard] 读取模式状态失败:' + describeError(error)))
|
|
1558
|
+
}
|
|
1559
|
+
report(0)
|
|
1560
|
+
})
|
|
1561
|
+
} catch (error) {
|
|
1562
|
+
console.warn('[taskboard] agentPresets 注入失败:' + describeError(error))
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
// RPC 路由:webServer 是 Web profile 才有的服务,用 ctx.inject 等它就绪(缺失时插件照常运行)。
|
|
1566
|
+
try {
|
|
1567
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
1568
|
+
try {
|
|
1569
|
+
webCtx.effect(
|
|
1570
|
+
() =>
|
|
1571
|
+
webCtx.webServer.register({
|
|
1572
|
+
kind: 'prefix',
|
|
1573
|
+
path: RPC_CHANNEL,
|
|
1574
|
+
handler: (req, res) => {
|
|
1575
|
+
handleHttp(runtime, req, res).catch((error) => {
|
|
1576
|
+
console.error('[taskboard] 处理 RPC 请求失败:' + describeError(error))
|
|
1577
|
+
sendPlain(res, 500, 'internal error')
|
|
1578
|
+
})
|
|
1579
|
+
},
|
|
1580
|
+
}),
|
|
1581
|
+
'taskboard: rpc bridge',
|
|
1582
|
+
)
|
|
1583
|
+
console.log('[taskboard] RPC 路由已注册:' + RPC_CHANNEL)
|
|
1584
|
+
} catch (error) {
|
|
1585
|
+
console.error('[taskboard] RPC 路由注册失败:' + describeError(error))
|
|
1586
|
+
}
|
|
1587
|
+
})
|
|
1588
|
+
} catch (error) {
|
|
1589
|
+
console.error('[taskboard] webServer 注入失败:' + describeError(error))
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
// 轮询派单:定时器自己管理,config 改间隔时重建。
|
|
1593
|
+
try {
|
|
1594
|
+
startPolling(runtime)
|
|
1595
|
+
ctx.effect(
|
|
1596
|
+
() => () => {
|
|
1597
|
+
stopPolling(runtime)
|
|
1598
|
+
},
|
|
1599
|
+
'taskboard: poll cleanup',
|
|
1600
|
+
)
|
|
1601
|
+
console.log('[taskboard] 轮询已启动:' + normalizeConfig(runtime.state.config).pollIntervalMs + 'ms')
|
|
1602
|
+
} catch (error) {
|
|
1603
|
+
console.error('[taskboard] 轮询启动失败:' + describeError(error))
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
// 模型工具:tools 服务是可选的(headless/minimal profile 可能没有)。
|
|
1607
|
+
try {
|
|
1608
|
+
ctx.inject(['tools'], (toolCtx) => {
|
|
1609
|
+
try {
|
|
1610
|
+
registerTools(toolCtx, runtime)
|
|
1611
|
+
} catch (error) {
|
|
1612
|
+
console.error('[taskboard] 工具注册失败:' + describeError(error))
|
|
1613
|
+
}
|
|
1614
|
+
})
|
|
1615
|
+
} catch (error) {
|
|
1616
|
+
console.warn('[taskboard] tools 服务注入失败:' + describeError(error))
|
|
1617
|
+
}
|
|
1618
|
+
}
|