dsh-todo-board 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,1253 @@
1
+ /**
2
+ * dsh-todo-board — Host half.
3
+ *
4
+ * Owns one durable board file, the `todo_board` model tool, the turn-end
5
+ * auto-continue hook, one system-prompt section, and the
6
+ * `/dsh-todo-board/api` route the browser half talks to.
7
+ *
8
+ * Deliberately imports nothing from `@deepseek-ai/*`: a profile-installed
9
+ * plugin resolves modules from its own directory, and the harness packages are
10
+ * not reachable from there. Everything goes through `ctx`.
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
14
+ import { dirname, extname, join } from 'node:path'
15
+ import { homedir } from 'node:os'
16
+ import { randomUUID } from 'node:crypto'
17
+
18
+ export const name = 'dsh-todo-board'
19
+
20
+ const MODES = ['remind', 'resume', 'newSession']
21
+ const ROUTE = '/dsh-todo-board/api'
22
+ const IMAGE_ROUTE = '/dsh-todo-board/image'
23
+ const TOOL_NAME = 'todo_board'
24
+
25
+ /** Scheduled todos fire at minute precision, in the host machine's local time. */
26
+ const SCHEDULE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/
27
+ /** Safety net beside the exact timer: a suspended machine never delivers a timeout. */
28
+ const SCHEDULE_TICK_MS = 30000
29
+ /** Attachments one todo may carry; keeps a prompt from becoming an image dump. */
30
+ const MAX_IMAGES_PER_TODO = 4
31
+ const MEDIA_TYPE_BY_EXTENSION = {
32
+ '.png': 'image/png',
33
+ '.jpg': 'image/jpeg',
34
+ '.jpeg': 'image/jpeg',
35
+ '.webp': 'image/webp',
36
+ '.gif': 'image/gif',
37
+ }
38
+ const MEDIA_TYPES = Object.values(MEDIA_TYPE_BY_EXTENSION)
39
+
40
+ // --------------------------------------------------------------- small utils
41
+
42
+ function dshHome() {
43
+ const configured = process.env.DSH_HOME
44
+ if (typeof configured === 'string' && configured.trim() !== '') return configured
45
+ return join(homedir(), '.dsh')
46
+ }
47
+
48
+ function boardFile() {
49
+ return join(dshHome(), 'todo-board', 'board.json')
50
+ }
51
+
52
+ /** Case-insensitive, backslash-normalized directory key. */
53
+ function normalizeDir(dir) {
54
+ if (typeof dir !== 'string' || dir === '') return ''
55
+ let s = dir.replace(/\//g, '\\')
56
+ while (s.length > 1 && s.endsWith('\\')) s = s.slice(0, -1)
57
+ return s.toLowerCase()
58
+ }
59
+
60
+ /**
61
+ * Keep only durable-shaped image references, so a corrupt or hand-edited board
62
+ * can never smuggle an arbitrary object into a user message.
63
+ */
64
+ function normalizeImages(raw) {
65
+ if (!Array.isArray(raw)) return []
66
+ const out = []
67
+ for (const entry of raw) {
68
+ if (entry === null || typeof entry !== 'object') continue
69
+ if (typeof entry.attachmentId !== 'string' || entry.attachmentId === '') continue
70
+ if (MEDIA_TYPES.indexOf(entry.mediaType) < 0) continue
71
+ const ref = {
72
+ attachmentId: entry.attachmentId,
73
+ mediaType: entry.mediaType,
74
+ bytes: typeof entry.bytes === 'number' ? entry.bytes : 0,
75
+ width: typeof entry.width === 'number' ? entry.width : 0,
76
+ height: typeof entry.height === 'number' ? entry.height : 0,
77
+ }
78
+ if (typeof entry.name === 'string' && entry.name !== '') ref.name = entry.name
79
+ out.push(ref)
80
+ if (out.length >= MAX_IMAGES_PER_TODO) break
81
+ }
82
+ return out
83
+ }
84
+
85
+ function dirLabel(dir) {
86
+ if (typeof dir !== 'string' || dir === '') return '(未指定目录)'
87
+ const parts = dir.split(/[\\/]/).filter(Boolean)
88
+ return parts.length > 0 ? parts[parts.length - 1] : dir
89
+ }
90
+
91
+ /** Local `YYYY-MM-DDTHH:mm` for one epoch value — the board's schedule format. */
92
+ function formatLocal(ms) {
93
+ const date = new Date(ms)
94
+ const pad = (n) => String(n).padStart(2, '0')
95
+ return (
96
+ date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) +
97
+ 'T' + pad(date.getHours()) + ':' + pad(date.getMinutes())
98
+ )
99
+ }
100
+
101
+ /**
102
+ * Accept only a strict local `YYYY-MM-DDTHH:mm`, or an ISO string that carries
103
+ * an explicit offset (`Z` / `±HH:MM`) which is folded into host local time.
104
+ * Returns `''` for anything else, so a bad value clears the schedule instead of
105
+ * silently arming a wrong instant.
106
+ */
107
+ function normalizeSchedule(value) {
108
+ if (typeof value !== 'string') return ''
109
+ const text = value.trim()
110
+ if (text === '') return ''
111
+ const local = SCHEDULE_PATTERN.exec(text)
112
+ if (local !== null) {
113
+ const ms = new Date(
114
+ Number(local[1]), Number(local[2]) - 1, Number(local[3]), Number(local[4]), Number(local[5]), 0, 0,
115
+ ).getTime()
116
+ return Number.isFinite(ms) && formatLocal(ms) === text ? text : ''
117
+ }
118
+ if (!/(?:Z|[+-]\d{2}:\d{2})$/.test(text)) return ''
119
+ const ms = Date.parse(text)
120
+ return Number.isFinite(ms) ? formatLocal(ms) : ''
121
+ }
122
+
123
+ /** Epoch ms of a stored schedule, or 0 when it is absent/unparseable. */
124
+ function scheduleMs(schedule) {
125
+ const normalized = normalizeSchedule(schedule)
126
+ return normalized === '' ? 0 : new Date(normalized).getTime()
127
+ }
128
+
129
+ /** Human-facing clock, e.g. `09:30` (today/tomorrow) or `09-12 09:30`. */
130
+ function scheduleLabel(schedule) {
131
+ const ms = scheduleMs(schedule)
132
+ if (ms === 0) return ''
133
+ const pad = (n) => String(n).padStart(2, '0')
134
+ const date = new Date(ms)
135
+ const clock = pad(date.getHours()) + ':' + pad(date.getMinutes())
136
+ const today = formatLocal(Date.now()).slice(0, 10)
137
+ const day = formatLocal(ms).slice(0, 10)
138
+ if (day === today) return clock
139
+ if (day === formatLocal(Date.now() + 86400000).slice(0, 10)) return '明天 ' + clock
140
+ return day.slice(5) + ' ' + clock
141
+ }
142
+
143
+ function errText(err) {
144
+ if (err === undefined || err === null) return 'unknown error'
145
+ if (typeof err === 'string') return err
146
+ if (typeof err.message === 'string') return err.message
147
+ return String(err)
148
+ }
149
+
150
+ function sendJson(response, status, payload) {
151
+ try {
152
+ response.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
153
+ response.end(JSON.stringify(payload))
154
+ } catch (err) {
155
+ /* the browser navigated away mid-request */
156
+ }
157
+ }
158
+
159
+ async function readJsonBody(request) {
160
+ const chunks = []
161
+ for await (const chunk of request) chunks.push(chunk)
162
+ const text = Buffer.concat(chunks).toString('utf8')
163
+ if (text.trim() === '') return {}
164
+ const parsed = JSON.parse(text)
165
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
166
+ }
167
+
168
+ // ------------------------------------------------------------- tool schemas
169
+ // Raw JSON Schema (not the author-facing `defineTool` spec), because a
170
+ // profile-installed plugin cannot import `@deepseek-ai/dsh-tools`.
171
+
172
+ const TOOL_PARAMETERS = {
173
+ type: 'object',
174
+ properties: {
175
+ action: {
176
+ type: 'string',
177
+ enum: ['list', 'add', 'done', 'reopen', 'note', 'schedule'],
178
+ description: '要执行的操作。',
179
+ },
180
+ title: { type: 'string', description: 'add 时的待办内容(一句话)。' },
181
+ id: { type: 'string', description: 'done / reopen / note 时的待办 id。' },
182
+ dir: {
183
+ type: 'string',
184
+ description: 'list / add 时的目标目录;省略则使用当前会话的工作目录。',
185
+ },
186
+ mode: {
187
+ type: 'string',
188
+ enum: MODES,
189
+ description:
190
+ 'add 时的执行模式:remind=只提醒,resume=AI 停下后自动在同一会话续跑,newSession=自动新开会话执行。默认 remind。',
191
+ },
192
+ note: { type: 'string', description: 'add / note 时的备注文本。' },
193
+ schedule: {
194
+ type: 'string',
195
+ description:
196
+ 'add / schedule 时的定时执行时间,本地时间格式 YYYY-MM-DDTHH:mm(也接受带偏移量的 ISO 8601)。到点后该待办才可被派发;空字符串表示取消定时。',
197
+ },
198
+ all: { type: 'boolean', description: 'list 时是否列出所有目录的待办,默认 false。' },
199
+ images: {
200
+ type: 'array',
201
+ items: { type: 'string' },
202
+ description:
203
+ 'add 时的图片:每项是主机上的图片文件绝对路径(png / jpg / webp / gif)。最多 ' +
204
+ MAX_IMAGES_PER_TODO + ' 张;文件会被存进附件库,派发时作为真正的图片一起发给模型。',
205
+ },
206
+ },
207
+ required: ['action'],
208
+ }
209
+
210
+ const TOOL_OUTPUT_SCHEMA = {
211
+ type: 'object',
212
+ additionalProperties: false,
213
+ properties: {
214
+ message: { type: 'string' },
215
+ todos: {
216
+ type: 'array',
217
+ items: {
218
+ type: 'object',
219
+ additionalProperties: false,
220
+ properties: {
221
+ id: { type: 'string' },
222
+ title: { type: 'string' },
223
+ dirLabel: { type: 'string' },
224
+ mode: { type: 'string', enum: MODES },
225
+ schedule: { type: 'string' },
226
+ imageCount: { type: 'number' },
227
+ aiDone: { type: 'boolean' },
228
+ verified: { type: 'boolean' },
229
+ },
230
+ required: ['id', 'title', 'dirLabel', 'mode', 'schedule', 'imageCount', 'aiDone', 'verified'],
231
+ },
232
+ },
233
+ },
234
+ required: ['message', 'todos'],
235
+ }
236
+
237
+ // -------------------------------------------------------------------- plugin
238
+
239
+ export function apply(ctx) {
240
+ const board = { version: 1, seq: 0, todos: [] }
241
+ let storageError = ''
242
+
243
+ // ---------------------------------------------------------------- records
244
+
245
+ function touch(todo) {
246
+ todo.updatedAt = Date.now()
247
+ }
248
+
249
+ function normalize(raw) {
250
+ if (raw === null || typeof raw !== 'object') return null
251
+ const title = typeof raw.title === 'string' ? raw.title : ''
252
+ if (title === '') return null
253
+ const dirPath =
254
+ typeof raw.dirPath === 'string' ? raw.dirPath : typeof raw.dir === 'string' ? raw.dir : ''
255
+ return {
256
+ id: typeof raw.id === 'string' && raw.id !== '' ? raw.id : randomUUID(),
257
+ title,
258
+ dir: normalizeDir(dirPath),
259
+ dirPath,
260
+ mode: MODES.indexOf(raw.mode) >= 0 ? raw.mode : 'remind',
261
+ aiDone: raw.aiDone === true,
262
+ verified: raw.verified === true,
263
+ note: typeof raw.note === 'string' ? raw.note : '',
264
+ images: normalizeImages(raw.images),
265
+ schedule: normalizeSchedule(raw.schedule),
266
+ remindedAt: typeof raw.remindedAt === 'number' ? raw.remindedAt : 0,
267
+ order: typeof raw.order === 'number' && Number.isFinite(raw.order) ? raw.order : -1,
268
+ sourceSessionId: typeof raw.sourceSessionId === 'string' ? raw.sourceSessionId : '',
269
+ sourceSessionTitle: typeof raw.sourceSessionTitle === 'string' ? raw.sourceSessionTitle : '',
270
+ dispatchedAt: typeof raw.dispatchedAt === 'number' ? raw.dispatchedAt : 0,
271
+ runSessionId: typeof raw.runSessionId === 'string' ? raw.runSessionId : '',
272
+ createdAt: typeof raw.createdAt === 'number' ? raw.createdAt : Date.now(),
273
+ updatedAt: typeof raw.updatedAt === 'number' ? raw.updatedAt : Date.now(),
274
+ }
275
+ }
276
+
277
+ function renumber() {
278
+ for (let i = 0; i < board.todos.length; i++) board.todos[i].order = i
279
+ }
280
+
281
+ function nextOrder() {
282
+ let max = -1
283
+ for (const todo of board.todos) if (todo.order > max) max = todo.order
284
+ return max + 1
285
+ }
286
+
287
+ function find(id) {
288
+ for (const todo of board.todos) if (todo.id === id) return todo
289
+ return undefined
290
+ }
291
+
292
+ /** Panel record: full detail. Never used as a Tool return value. */
293
+ function plain(todo) {
294
+ return {
295
+ id: todo.id,
296
+ title: todo.title,
297
+ dir: todo.dir,
298
+ dirPath: todo.dirPath,
299
+ dirLabel: dirLabel(todo.dirPath || todo.dir),
300
+ mode: todo.mode,
301
+ aiDone: todo.aiDone === true,
302
+ verified: todo.verified === true,
303
+ note: todo.note,
304
+ images: todo.images.map((image) => ({ ...image })),
305
+ schedule: todo.schedule,
306
+ dueAt: scheduleMs(todo.schedule),
307
+ remindedAt: todo.remindedAt,
308
+ order: todo.order,
309
+ sourceSessionId: todo.sourceSessionId,
310
+ sourceSessionTitle: todo.sourceSessionTitle,
311
+ dispatchedAt: todo.dispatchedAt,
312
+ runSessionId: todo.runSessionId,
313
+ createdAt: todo.createdAt,
314
+ updatedAt: todo.updatedAt,
315
+ }
316
+ }
317
+
318
+ /** Exactly TOOL_OUTPUT_SCHEMA's item shape. */
319
+ function toolTodo(todo) {
320
+ return {
321
+ id: todo.id,
322
+ title: todo.title,
323
+ dirLabel: dirLabel(todo.dirPath || todo.dir),
324
+ mode: todo.mode,
325
+ schedule: todo.schedule,
326
+ imageCount: todo.images.length,
327
+ aiDone: todo.aiDone === true,
328
+ verified: todo.verified === true,
329
+ }
330
+ }
331
+
332
+ // ------------------------------------------------------------ persistence
333
+
334
+ function load() {
335
+ try {
336
+ const file = boardFile()
337
+ if (!existsSync(file)) {
338
+ save()
339
+ return
340
+ }
341
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
342
+ if (parsed === null || typeof parsed !== 'object' || !Array.isArray(parsed.todos)) return
343
+ const kept = []
344
+ for (const raw of parsed.todos) {
345
+ const todo = normalize(raw)
346
+ if (todo !== null) kept.push(todo)
347
+ }
348
+ // Legacy rows carry order -1: fall back to creation order, then densify.
349
+ kept.sort((a, b) => a.order - b.order || a.createdAt - b.createdAt)
350
+ board.todos = kept
351
+ renumber()
352
+ board.seq = typeof parsed.seq === 'number' ? parsed.seq : kept.length
353
+ storageError = ''
354
+ } catch (err) {
355
+ storageError = '读取待办文件失败:' + errText(err)
356
+ }
357
+ }
358
+
359
+ function save() {
360
+ try {
361
+ const file = boardFile()
362
+ mkdirSync(dirname(file), { recursive: true })
363
+ const tmp = file + '.tmp'
364
+ writeFileSync(tmp, JSON.stringify(board, null, 2), 'utf8')
365
+ renameSync(tmp, file)
366
+ storageError = ''
367
+ } catch (err) {
368
+ storageError = '写入待办文件失败:' + errText(err)
369
+ }
370
+ }
371
+
372
+ load()
373
+
374
+ // ------------------------------------------------------------- scheduling
375
+ //
376
+ // A scheduled todo becomes eligible only at its local wall-clock minute. One
377
+ // self-rearming timer tracks the nearest target; a coarse tick beside it
378
+ // catches timers a suspended machine never delivered. Both paths are
379
+ // idempotent through `dispatchedAt` / `remindedAt`.
380
+
381
+ let scheduleTimer
382
+ let scheduleTick
383
+ /** Ids whose dispatch is in flight — a second tick must not send them twice. */
384
+ const firing = new Set()
385
+
386
+ /** Pending todo whose scheduled minute has arrived, earliest first. */
387
+ function nextDue(now) {
388
+ let best
389
+ let bestMs = 0
390
+ for (const todo of board.todos) {
391
+ if (todo.verified || todo.aiDone) continue
392
+ // A dispatch already on its way is not due again: its state stamp lands
393
+ // only when it completes, so without this the timer would re-enter it.
394
+ if (firing.has(todo.id)) continue
395
+ const ms = scheduleMs(todo.schedule)
396
+ if (ms === 0 || ms > now) continue
397
+ if (todo.dispatchedAt > 0 || todo.remindedAt > 0) continue
398
+ if (best === undefined || ms < bestMs) {
399
+ best = todo
400
+ bestMs = ms
401
+ }
402
+ }
403
+ return best
404
+ }
405
+
406
+ /** Earliest pending schedule strictly in the future; 0 when none is set. */
407
+ function nextFuture(now) {
408
+ let soonest = 0
409
+ for (const todo of board.todos) {
410
+ if (todo.verified || todo.aiDone) continue
411
+ const ms = scheduleMs(todo.schedule)
412
+ if (ms <= now) continue
413
+ if (soonest === 0 || ms < soonest) soonest = ms
414
+ }
415
+ return soonest
416
+ }
417
+
418
+ /** Point the exact timer at the nearest target, or at the next check when none is set. */
419
+ function armTimer() {
420
+ if (scheduleTimer !== undefined) {
421
+ clearTimeout(scheduleTimer)
422
+ scheduleTimer = undefined
423
+ }
424
+ const now = Date.now()
425
+ if (nextDue(now) !== undefined) {
426
+ fireDue()
427
+ return
428
+ }
429
+ const soonest = nextFuture(now)
430
+ scheduleTimer = setTimeout(
431
+ () => {
432
+ scheduleTimer = undefined
433
+ fireDue()
434
+ },
435
+ soonest === 0 ? SCHEDULE_TICK_MS : Math.max(250, soonest - now),
436
+ )
437
+ // Never hold the host process open on this timer alone.
438
+ if (typeof scheduleTimer.unref === 'function') scheduleTimer.unref()
439
+ }
440
+
441
+ /**
442
+ * Dispatch every todo whose time has come.
443
+ *
444
+ * `remind` never wakes the model: it only stamps the reminder so the panel can
445
+ * surface it. The other two modes reuse the manual dispatch path, so a
446
+ * scheduled task lands exactly where the ▶ button would send it.
447
+ */
448
+ function fireDue() {
449
+ for (let todo = nextDue(Date.now()); todo !== undefined; todo = nextDue(Date.now())) {
450
+ if (firing.has(todo.id)) break
451
+ if (todo.mode === 'remind') {
452
+ todo.remindedAt = Date.now()
453
+ touch(todo)
454
+ save()
455
+ continue
456
+ }
457
+ firing.add(todo.id)
458
+ void dispatch(todo, todo.runSessionId)
459
+ .catch((err) => {
460
+ ctx.logger?.error?.('todo-board scheduled dispatch failed: ' + errText(err))
461
+ })
462
+ .finally(() => {
463
+ firing.delete(todo.id)
464
+ armTimer()
465
+ })
466
+ }
467
+ armTimer()
468
+ }
469
+
470
+ /** Any board mutation may have moved a target, so every write re-arms. */
471
+ function afterChange() {
472
+ save()
473
+ armTimer()
474
+ }
475
+
476
+ // ----------------------------------------------------------- board actions
477
+
478
+ function snapshotPayload() {
479
+ const dirs = {}
480
+ const agents = ctx.get('agents')
481
+ if (agents !== undefined) {
482
+ for (const agent of agents.list()) {
483
+ const header = agent.session === undefined ? undefined : agent.session.header
484
+ const cwd = header === undefined ? undefined : header.cwd
485
+ if (typeof cwd === 'string' && cwd !== '') dirs[normalizeDir(cwd)] = cwd
486
+ }
487
+ }
488
+ return {
489
+ ok: true,
490
+ storagePath: boardFile(),
491
+ storageError,
492
+ dirs,
493
+ todos: board.todos.map(plain),
494
+ }
495
+ }
496
+
497
+ async function createTodo(input) {
498
+ const title = typeof input.title === 'string' ? input.title.trim() : ''
499
+ if (title === '') return { ok: false, error: '待办内容不能为空' }
500
+ const schedule = normalizeSchedule(input.schedule)
501
+ if (typeof input.schedule === 'string' && input.schedule.trim() !== '' && schedule === '') {
502
+ return { ok: false, error: '定时时间格式无效,请用 YYYY-MM-DDTHH:mm(本地时间)' }
503
+ }
504
+ const todo = normalize({
505
+ title,
506
+ dirPath: typeof input.dir === 'string' ? input.dir.trim() : '',
507
+ mode: typeof input.mode === 'string' ? input.mode : 'remind',
508
+ schedule,
509
+ sourceSessionId: typeof input.sessionId === 'string' ? input.sessionId : '',
510
+ sourceSessionTitle: typeof input.sessionTitle === 'string' ? input.sessionTitle : '',
511
+ })
512
+ if (todo === null) return { ok: false, error: '无法创建待办' }
513
+ const admitted = await admitImages(input.images)
514
+ if (admitted.ok === false) return admitted
515
+ todo.images = admitted.images
516
+ todo.order = nextOrder()
517
+ board.todos.push(todo)
518
+ board.seq += 1
519
+ afterChange()
520
+ return { ok: true, todo: plain(todo), storageError }
521
+ }
522
+
523
+ /**
524
+ * Validate and store the images one todo carries.
525
+ *
526
+ * Bytes arrive base64-encoded from the panel (or are read from disk for the
527
+ * model tool) and are committed through the deployment's attachment store —
528
+ * the same admission path the chat upload uses, so limits, media types and
529
+ * normalization are the harness's, not ours. Returns `{ ok: false, error }`
530
+ * instead of throwing so a refused batch is a panel error, not a 500.
531
+ */
532
+ async function admitImages(entries) {
533
+ if (!Array.isArray(entries) || entries.length === 0) return { ok: true, images: [] }
534
+ if (entries.length > MAX_IMAGES_PER_TODO) {
535
+ return { ok: false, error: '一条待办最多带 ' + MAX_IMAGES_PER_TODO + ' 张图片' }
536
+ }
537
+ const store = ctx.get('attachments')
538
+ if (store === undefined) {
539
+ return { ok: false, error: '本部署没有 attachments 服务,无法保存图片' }
540
+ }
541
+ const refs = []
542
+ const inputs = []
543
+ for (const entry of entries) {
544
+ if (entry === null || typeof entry !== 'object') continue
545
+ const mediaType = typeof entry.mediaType === 'string' ? entry.mediaType : ''
546
+ if (MEDIA_TYPES.indexOf(mediaType) < 0) {
547
+ return { ok: false, error: '不支持的图片格式:' + (mediaType || '(未声明)') }
548
+ }
549
+ if (typeof entry.data === 'string' && entry.data !== '') {
550
+ inputs.push({
551
+ data: Buffer.from(entry.data, 'base64'),
552
+ mediaType,
553
+ name: typeof entry.name === 'string' ? entry.name : undefined,
554
+ })
555
+ continue
556
+ }
557
+ if (typeof entry.path === 'string' && entry.path !== '') {
558
+ let bytes
559
+ try {
560
+ bytes = new Uint8Array(readFileSync(entry.path))
561
+ } catch (err) {
562
+ return { ok: false, error: '读不到图片 ' + entry.path + ':' + errText(err) }
563
+ }
564
+ inputs.push({ data: bytes, mediaType, name: entry.path })
565
+ continue
566
+ }
567
+ return { ok: false, error: '图片需要 data(base64)或 path' }
568
+ }
569
+ if (inputs.length === 0) return { ok: true, images: [] }
570
+ try {
571
+ for (const input of inputs) refs.push(await store.saveImage(input))
572
+ } catch (err) {
573
+ return { ok: false, error: '图片被拒绝:' + errText(err) }
574
+ }
575
+ return { ok: true, images: refs }
576
+ }
577
+
578
+ async function patchTodo(input) {
579
+ const todo = find(typeof input.id === 'string' ? input.id : '')
580
+ if (todo === undefined) return { ok: false, error: '待办不存在' }
581
+ const patch = input.patch !== null && typeof input.patch === 'object' ? input.patch : {}
582
+ if (typeof patch.title === 'string' && patch.title.trim() !== '') todo.title = patch.title.trim()
583
+ if (typeof patch.note === 'string') todo.note = patch.note
584
+ if (typeof patch.mode === 'string' && MODES.indexOf(patch.mode) >= 0) todo.mode = patch.mode
585
+ if (typeof patch.schedule === 'string') {
586
+ const next = normalizeSchedule(patch.schedule)
587
+ if (next !== todo.schedule) {
588
+ todo.schedule = next
589
+ todo.remindedAt = 0
590
+ todo.dispatchedAt = 0
591
+ }
592
+ }
593
+ if (typeof patch.dir === 'string' && patch.dir.trim() !== '') {
594
+ todo.dirPath = patch.dir.trim()
595
+ todo.dir = normalizeDir(todo.dirPath)
596
+ }
597
+ if (patch.aiDone === true) {
598
+ todo.aiDone = true
599
+ todo.dispatchedAt = 0
600
+ }
601
+ if (patch.aiDone === false) todo.aiDone = false
602
+ if (patch.verified === true) todo.verified = true
603
+ if (patch.verified === false) {
604
+ todo.verified = false
605
+ todo.aiDone = false
606
+ }
607
+ if (patch.redispatch === true) todo.dispatchedAt = 0
608
+ if (Array.isArray(patch.images) && patch.images.length > 0) {
609
+ const admitted = await admitImages(patch.images)
610
+ if (admitted.ok === false) return admitted
611
+ todo.images = admitted.images
612
+ }
613
+ if (patch.clearImages === true) todo.images = []
614
+ // Unbinding (or rebinding) the run session is how a row is told to open a
615
+ // fresh session again: an empty value drops the binding.
616
+ if (typeof patch.runSessionId === 'string') {
617
+ todo.runSessionId = patch.runSessionId.trim()
618
+ todo.dispatchedAt = 0
619
+ }
620
+ touch(todo)
621
+ afterChange()
622
+ return { ok: true, todo: plain(todo), storageError }
623
+ }
624
+
625
+ /** The browser sends the new top-to-bottom id list; unmentioned rows follow. */
626
+ function reorderTodos(input) {
627
+ const ids = Array.isArray(input.ids) ? input.ids : []
628
+ if (ids.length === 0) return { ok: false, error: 'reorder 需要 ids' }
629
+ const byId = new Map()
630
+ for (const todo of board.todos) byId.set(todo.id, todo)
631
+ const ordered = []
632
+ const seen = new Set()
633
+ for (const id of ids) {
634
+ if (typeof id !== 'string') continue
635
+ const todo = byId.get(id)
636
+ if (todo === undefined || seen.has(id)) continue
637
+ seen.add(id)
638
+ ordered.push(todo)
639
+ }
640
+ for (const todo of board.todos) if (!seen.has(todo.id)) ordered.push(todo)
641
+ board.todos = ordered
642
+ renumber()
643
+ afterChange()
644
+ return { ok: true, count: ordered.length, storageError }
645
+ }
646
+
647
+ function removeTodo(input) {
648
+ const id = typeof input.id === 'string' ? input.id : ''
649
+ board.todos = board.todos.filter((todo) => todo.id !== id)
650
+ renumber()
651
+ afterChange()
652
+ return { ok: true, storageError }
653
+ }
654
+
655
+ function clearVerified() {
656
+ board.todos = board.todos.filter((todo) => !todo.verified)
657
+ renumber()
658
+ afterChange()
659
+ return { ok: true, storageError }
660
+ }
661
+
662
+ // ----------------------------------------------------------- dispatching
663
+
664
+ function noticeMessage(content, summary) {
665
+ return {
666
+ id: randomUUID(),
667
+ role: 'user',
668
+ content,
669
+ source: { kind: 'plugin', plugin: 'dsh-todo-board', form: 'notice', summary },
670
+ }
671
+ }
672
+
673
+ function todoPrompt(todo) {
674
+ const lines = ['【TODO 板 · 自动接续】', '待办:' + todo.title]
675
+ if (todo.dirPath) lines.push('工作目录:' + todo.dirPath)
676
+ if (todo.note) lines.push('备注:' + todo.note)
677
+ if (todo.images.length > 0) {
678
+ lines.push('附带的 ' + todo.images.length + ' 张图片在下面,先看图再动手。')
679
+ }
680
+ lines.push('')
681
+ lines.push('请现在直接开始执行这一条待办,不要再向用户确认。')
682
+ lines.push('完成之后:')
683
+ lines.push('1. 调用 ' + TOOL_NAME + ' 工具 action="done" id="' + todo.id + '" 把它标记为「AI 已完成」。')
684
+ lines.push('2. 调用 ' + TOOL_NAME + ' 工具 action="list" 查看同一目录下是否还有未完成待办(列表从上到下就是执行顺序)。')
685
+ lines.push('3. 如果还有,继续执行列表最上面那一条,不要停下来等待用户;如果没有了,简要汇报本轮完成情况。')
686
+ lines.push('不要替用户勾选「已验收」——那是用户验收后才勾的。')
687
+ return lines.join('\n')
688
+ }
689
+
690
+ /**
691
+ * Whether the route a todo is about to be sent to accepts images.
692
+ *
693
+ * The adapter's own model listing is the only truthful source, and it is
694
+ * async — so this runs at dispatch, not on every panel poll. An unknown
695
+ * provider, an adapter without discovery, or a probe failure all answer
696
+ * `true`: the adapter then reports its own refusal, which is still a clear
697
+ * error, and a broken probe must never block a text-only todo.
698
+ */
699
+ async function modelAcceptsImages(selection) {
700
+ if (selection === undefined || selection === null) return true
701
+ const provider = selection.provider
702
+ const model = selection.model
703
+ if (typeof provider !== 'string' || typeof model !== 'string') return true
704
+ const llm = ctx.get('llm')
705
+ if (llm === undefined || typeof llm.listModels !== 'function') return true
706
+ try {
707
+ const models = await llm.listModels(provider)
708
+ if (!Array.isArray(models)) return true
709
+ const wanted = models.find((entry) => entry !== null && entry !== undefined && entry.id === model)
710
+ if (wanted === undefined || wanted === null) return true
711
+ const modalities = wanted.inputModalities
712
+ if (!Array.isArray(modalities)) return true
713
+ return modalities.indexOf('image') >= 0
714
+ } catch (err) {
715
+ return true
716
+ }
717
+ }
718
+
719
+ /**
720
+ * The message a todo becomes: the instruction text plus the durable image
721
+ * references it carries, exactly like a human turn with attachments.
722
+ */
723
+ function todoContent(todo) {
724
+ const content = [{ type: 'text', text: todoPrompt(todo) }]
725
+ for (const image of todo.images) content.push({ type: 'image', attachment: image })
726
+ return content
727
+ }
728
+
729
+ function modelSelection(sourceAgent) {
730
+ if (sourceAgent !== undefined && sourceAgent.options !== undefined) {
731
+ const provider = sourceAgent.options.provider
732
+ const model = sourceAgent.options.model
733
+ if (typeof provider === 'string' || typeof model === 'string') return { provider, model }
734
+ }
735
+ const defaults = ctx.get('agentDefaultModel')
736
+ if (defaults !== undefined) {
737
+ try {
738
+ const selection = defaults.currentSelection()
739
+ if (selection !== null && typeof selection === 'object') {
740
+ return { provider: selection.provider, model: selection.model }
741
+ }
742
+ } catch (err) {
743
+ /* fall through to harness defaults */
744
+ }
745
+ }
746
+ return undefined
747
+ }
748
+
749
+ /**
750
+ * Register a freshly created session with the workspace that owns its
751
+ * directory, so the sidebar groups it instead of listing it as 未分组.
752
+ *
753
+ * Grouping is durable state on the workspace record (`sessionIds`), not a
754
+ * session header field: the web app attaches every session it opens, and a
755
+ * session created through `agents.create` skips that step. `attachSession`
756
+ * validates the session's live/persisted header cwd against the workspace
757
+ * path, which is exactly the directory we created the session in.
758
+ */
759
+ async function attachToWorkspace(sessionId, dirPath) {
760
+ if (dirPath === '') return 'no-dir'
761
+ const rootCtx = ctx.root === undefined ? ctx : ctx.root
762
+ const registry = rootCtx.get('workspaceRegistry')
763
+ if (registry === undefined) return 'no-service'
764
+ try {
765
+ let workspace = await registry.resolveByPath(dirPath)
766
+ if (workspace === undefined) workspace = await registry.create(dirPath)
767
+ await workspace.attachSession(sessionId)
768
+ return 'attached'
769
+ } catch (err) {
770
+ ctx.logger?.warn?.('todo-board: could not group the new session: ' + errText(err))
771
+ return 'failed'
772
+ }
773
+ }
774
+
775
+ /**
776
+ * Create a fully composed session in `todo.dirPath` and hand it the todo.
777
+ *
778
+ * Created through `ctx.root`, not through this plugin's own fiber: the agent
779
+ * is then owned by the application root, so stopping, updating or removing
780
+ * this plugin row leaves the session running. `setup` mounts the agent preset
781
+ * exactly the way the api-proxy does — without it the new agent would have no
782
+ * tools and no prompt.
783
+ */
784
+ async function spawnSession(todo) {
785
+ const rootCtx = ctx.root === undefined ? ctx : ctx.root
786
+ const agents = rootCtx.get('agents')
787
+ if (agents === undefined) return { ok: false, error: 'agents 服务不可用' }
788
+ const source = todo.sourceSessionId === '' ? undefined : agents.get(todo.sourceSessionId)
789
+ const meta = {}
790
+ if (todo.dirPath !== '') meta.cwd = todo.dirPath
791
+ let setup
792
+ const presets = ctx.get('agentPresets')
793
+ if (presets !== undefined) {
794
+ try {
795
+ const sourcePreset =
796
+ source === undefined || source.session === undefined
797
+ ? undefined
798
+ : source.session.header.agentPreset
799
+ const resolved = await presets.resolve(sourcePreset)
800
+ meta.agentPreset = resolved.id
801
+ const presetId = resolved.id
802
+ setup = async (agentCtx) => {
803
+ await presets.mount(agentCtx, presetId)
804
+ }
805
+ } catch (err) {
806
+ return { ok: false, error: '解析 agent preset 失败:' + errText(err) }
807
+ }
808
+ }
809
+ const sessionId = 'session-' + randomUUID()
810
+ const agentOptions = modelSelection(source)
811
+ if (!(await modelAcceptsImages(agentOptions))) return imageRefusal(todo)
812
+ try {
813
+ const handle = await agents.create({
814
+ sessionId,
815
+ meta,
816
+ agentOptions,
817
+ setup,
818
+ })
819
+ // Grouping is cosmetic: a failure here must not cost the session.
820
+ const grouped = await attachToWorkspace(sessionId, todo.dirPath)
821
+ todo.dispatchedAt = Date.now()
822
+ todo.runSessionId = sessionId
823
+ touch(todo)
824
+ afterChange()
825
+ handle.agent.followup(noticeMessage(todoPrompt(todo), 'TODO 接续(新会话):' + todo.title))
826
+ return { ok: true, target: 'new-session', sessionId, grouped }
827
+ } catch (err) {
828
+ return { ok: false, error: '新建会话失败:' + errText(err) }
829
+ }
830
+ }
831
+
832
+ /**
833
+ * Hand the todo to one live agent and remember it as this row's target.
834
+ *
835
+ * The dispatch stamp is written **before** the message call, so a re-entrant
836
+ * `fireDue` (or a second tick) can never pick the same row again while this
837
+ * one is still in flight.
838
+ */
839
+ function sendTo(todo, target, note) {
840
+ todo.dispatchedAt = Date.now()
841
+ todo.runSessionId = target.id
842
+ touch(todo)
843
+ afterChange()
844
+ const message = noticeMessage(todoContent(todo), note + todo.title)
845
+ if (target.status === 'running') {
846
+ target.steer(message)
847
+ } else {
848
+ target.followup(message)
849
+ }
850
+ return { ok: true, target: 'session', sessionId: target.id }
851
+ }
852
+
853
+ async function dispatch(todo, sessionId) {
854
+ const agents = ctx.get('agents')
855
+ // A `newSession` row owns the session it created: reuse that binding while
856
+ // the session is live, and only open another one once it is gone.
857
+ if (todo.mode === 'newSession') {
858
+ const bound =
859
+ todo.runSessionId === '' || agents === undefined ? undefined : agents.get(todo.runSessionId)
860
+ if (bound !== undefined) {
861
+ if (!(await imageRouteOk(todo, bound))) return imageRefusal(todo)
862
+ return sendTo(todo, bound, 'TODO 接续:')
863
+ }
864
+ return spawnSession(todo)
865
+ }
866
+ // A row created from the panel carries its origin session, not a run
867
+ // session: that origin is where a scheduled task should land.
868
+ const wanted = sessionId !== '' ? sessionId : todo.sourceSessionId
869
+ const target = agents !== undefined && wanted !== '' ? agents.get(wanted) : undefined
870
+ if (target !== undefined) {
871
+ if (!(await imageRouteOk(todo, target))) return imageRefusal(todo)
872
+ return sendTo(todo, target, 'TODO 接续:')
873
+ }
874
+ todo.dispatchedAt = Date.now()
875
+ touch(todo)
876
+ afterChange()
877
+ return {
878
+ ok: false,
879
+ error: '当前没有可接续的活动会话;请切到目标会话后重试,或把该待办改成「自动新会话」',
880
+ }
881
+ }
882
+
883
+ /** A todo without images never needs the capability probe. */
884
+ async function imageRouteOk(todo, target) {
885
+ if (todo.images.length === 0) return true
886
+ const options = target === undefined || target === null ? undefined : target.options
887
+ return modelAcceptsImages(options === undefined ? undefined : {
888
+ provider: options.provider,
889
+ model: options.model,
890
+ })
891
+ }
892
+
893
+ function imageRefusal(todo) {
894
+ return {
895
+ ok: false,
896
+ error:
897
+ '这条待办带了 ' + todo.images.length + ' 张图片,但目标会话的模型不接受图片输入' +
898
+ '(模型目录里没有声明 image)。换一个支持图片的模型,或先把图片从待办上移除。',
899
+ }
900
+ }
901
+
902
+ function pendingInDir(dir) {
903
+ const out = []
904
+ for (const todo of board.todos) {
905
+ if (todo.dir !== dir) continue
906
+ if (todo.aiDone || todo.verified) continue
907
+ out.push(todo)
908
+ }
909
+ return out
910
+ }
911
+
912
+ /** Topmost still-undispatched auto-mode todo in this directory. */
913
+ function nextUndispatched(dir) {
914
+ for (const todo of pendingInDir(dir)) {
915
+ if (todo.mode === 'remind') continue
916
+ if (todo.dispatchedAt > 0) continue
917
+ // A todo with a future time waits for the scheduler, not for this turn end.
918
+ const ms = scheduleMs(todo.schedule)
919
+ if (ms > 0 && ms > Date.now()) continue
920
+ return todo
921
+ }
922
+ return undefined
923
+ }
924
+
925
+ function runTodo(input) {
926
+ const todo = find(typeof input.id === 'string' ? input.id : '')
927
+ if (todo === undefined) return { ok: false, error: '待办不存在' }
928
+ return dispatch(todo, typeof input.sessionId === 'string' ? input.sessionId : '')
929
+ }
930
+
931
+ // ----------------------------------------------- turn end: auto-continue
932
+
933
+ ctx.on('agent/turn-stopping', (payload) => {
934
+ try {
935
+ const agent = payload === undefined || payload === null ? undefined : payload.agent
936
+ if (agent === undefined || agent === null) return
937
+ const header = agent.session === undefined || agent.session === null ? undefined : agent.session.header
938
+ const dir = normalizeDir(header === undefined ? undefined : header.cwd)
939
+ if (dir === '') return
940
+ const next = nextUndispatched(dir)
941
+ if (next === undefined) return
942
+ if (next.mode === 'resume') {
943
+ void dispatch(next, agent.id)
944
+ } else if (next.mode === 'newSession') {
945
+ next.dispatchedAt = Date.now()
946
+ touch(next)
947
+ afterChange()
948
+ void spawnSession(next)
949
+ }
950
+ } catch (err) {
951
+ ctx.logger?.error?.('todo-board turn-stopping failed: ' + errText(err))
952
+ }
953
+ })
954
+
955
+ // -------------------------------------------------------- prompt section
956
+
957
+ const prompt = ctx.get('systemPrompt')
958
+ if (prompt !== undefined) {
959
+ ctx.effect(
960
+ () =>
961
+ prompt.section({
962
+ name: 'todo-board',
963
+ order: 150,
964
+ text: [
965
+ '## TODO 板(跨会话待办)',
966
+ '用户维护着一个按工作目录分组的待办板,你可以用 `' + TOOL_NAME + '` 工具读写它。',
967
+ '- 列表**从上到下就是执行顺序**(用户可拖动调整);你应按这个顺序取任务。',
968
+ '- 每完成一项工作,立刻用 `' + TOOL_NAME + '` action="done" 把对应待办标记为「AI 已完成」(左勾)。',
969
+ '- 完成一项后,用 `' + TOOL_NAME + '` action="list" 查看**当前工作目录**下是否还有未完成待办;如果有,继续执行**列表最上面**那一条,不要停下来等待用户。',
970
+ '- 你只能勾左勾(AI 已完成);右勾(已验收)由用户自己勾,永远不要代勾。',
971
+ '- 待办可以带**定时时间**(本地 `YYYY-MM-DDTHH:mm`):带定时且还没到点的待办**先别做**,到点后 DSH 会自动派发它;你可以用 action="schedule" 给某条待办设置或取消时间。',
972
+ '- 待办也可以带**图片**:面板上可直接附图;你用 action="add" 时传 `images`(主机上图片文件的绝对路径)即可,派发时这些图会作为真正的图片发给你。列表里会标注图片张数。',
973
+ '- 如果用户给的任务不在待办板上,也可以先 action="add" 记一条再动手(新条目会被追加到最底下)。',
974
+ ].join('\n'),
975
+ }),
976
+ 'dsh-todo-board: prompt section',
977
+ )
978
+ }
979
+
980
+ // ------------------------------------------------------------ model tool
981
+
982
+ const tools = ctx.get('tools')
983
+ if (tools !== undefined) {
984
+ const definition = {
985
+ name: TOOL_NAME,
986
+ description:
987
+ '读写跨会话 TODO 板。列表从上到下就是执行顺序(用户可拖动调整)。action=list 查看待办(默认当前工作目录),action=add 新增(追加到底部,可用 images 附主机上的图片文件),action=done 标记 AI 已完成(左勾),action=reopen 撤销左勾,action=note 追加备注,action=schedule 设置/取消定时执行时间。带 schedule 的待办到点后才会被派发。',
988
+ parameters: TOOL_PARAMETERS,
989
+ output: {
990
+ schema: TOOL_OUTPUT_SCHEMA,
991
+ render: (_args, value) => [{ type: 'text', text: value.message }],
992
+ },
993
+ async execute(args, exec) {
994
+ const input = args !== null && typeof args === 'object' ? args : {}
995
+ const action = typeof input.action === 'string' ? input.action : 'list'
996
+ const agent = exec === undefined || exec === null ? undefined : exec.agent
997
+ const header = agent === undefined || agent === null ? undefined : agent.session.header
998
+ const cwd = header !== undefined && typeof header.cwd === 'string' ? header.cwd : ''
999
+
1000
+ if (action === 'add') {
1001
+ const title = typeof input.title === 'string' ? input.title.trim() : ''
1002
+ if (title === '') return { message: 'add 需要提供 title。', todos: [] }
1003
+ const schedule = normalizeSchedule(input.schedule)
1004
+ if (typeof input.schedule === 'string' && input.schedule.trim() !== '' && schedule === '') {
1005
+ return { message: 'schedule 格式无效,请用 YYYY-MM-DDTHH:mm(本地时间)。', todos: [] }
1006
+ }
1007
+ const dirPath = typeof input.dir === 'string' && input.dir !== '' ? input.dir : cwd
1008
+ // Paths are read here, at the board boundary, and stored durably so a
1009
+ // later dispatch needs no filesystem access of its own.
1010
+ let imageEntries = []
1011
+ if (Array.isArray(input.images) && input.images.length > 0) {
1012
+ imageEntries = []
1013
+ for (const entry of input.images) {
1014
+ if (typeof entry !== 'string' || entry.trim() === '') {
1015
+ return { message: 'images 需要是图片文件的绝对路径数组。', todos: [] }
1016
+ }
1017
+ const path = entry.trim()
1018
+ const mediaType = MEDIA_TYPE_BY_EXTENSION[extname(path).toLowerCase()]
1019
+ if (mediaType === undefined) {
1020
+ return {
1021
+ message: '不支持的图片扩展名:' + path + '(支持 png / jpg / jpeg / webp / gif)',
1022
+ todos: [],
1023
+ }
1024
+ }
1025
+ imageEntries.push({ path, mediaType })
1026
+ }
1027
+ }
1028
+ const admitted = await admitImages(imageEntries)
1029
+ if (admitted.ok === false) return { message: admitted.error, todos: [] }
1030
+ const todo = normalize({
1031
+ title,
1032
+ dirPath,
1033
+ mode: typeof input.mode === 'string' ? input.mode : 'remind',
1034
+ note: typeof input.note === 'string' ? input.note : '',
1035
+ schedule,
1036
+ sourceSessionId: agent === undefined || agent === null ? '' : agent.id,
1037
+ })
1038
+ if (todo === null) return { message: '无法创建这条待办。', todos: [] }
1039
+ todo.images = admitted.images
1040
+ todo.order = nextOrder()
1041
+ board.todos.push(todo)
1042
+ board.seq += 1
1043
+ afterChange()
1044
+ return {
1045
+ message:
1046
+ '已新增待办「' + title + '」(目录:' + (dirPath || '(未指定)') + ',模式:' +
1047
+ todo.mode +
1048
+ (todo.schedule === '' ? '' : ',定时:' + todo.schedule + '(' + scheduleLabel(todo.schedule) + ')') +
1049
+ (todo.images.length === 0 ? '' : ',图片:' + todo.images.length + ' 张') +
1050
+ ',追加到列表底部,id:' + todo.id + ')。',
1051
+ todos: [toolTodo(todo)],
1052
+ }
1053
+ }
1054
+
1055
+ if (action === 'done' || action === 'reopen' || action === 'note' || action === 'schedule') {
1056
+ const id = typeof input.id === 'string' ? input.id : ''
1057
+ const todo = find(id)
1058
+ if (todo === undefined) return { message: '找不到 id 为 ' + (id || '(空)') + ' 的待办。', todos: [] }
1059
+ if (action === 'done') {
1060
+ todo.aiDone = true
1061
+ todo.dispatchedAt = 0
1062
+ } else if (action === 'reopen') {
1063
+ todo.aiDone = false
1064
+ } else if (action === 'schedule') {
1065
+ const next = normalizeSchedule(input.schedule)
1066
+ if (typeof input.schedule === 'string' && input.schedule.trim() !== '' && next === '') {
1067
+ return { message: 'schedule 格式无效,请用 YYYY-MM-DDTHH:mm(本地时间)。', todos: [] }
1068
+ }
1069
+ todo.schedule = next
1070
+ todo.remindedAt = 0
1071
+ todo.dispatchedAt = 0
1072
+ } else {
1073
+ todo.note = typeof input.note === 'string' ? input.note : ''
1074
+ }
1075
+ touch(todo)
1076
+ afterChange()
1077
+ const label =
1078
+ action === 'done'
1079
+ ? '已标记 AI 完成'
1080
+ : action === 'reopen'
1081
+ ? '已撤销 AI 完成'
1082
+ : action === 'schedule'
1083
+ ? todo.schedule === ''
1084
+ ? '已取消定时'
1085
+ : '已设置定时 ' + todo.schedule + '(' + scheduleLabel(todo.schedule) + ')'
1086
+ : '已更新备注'
1087
+ return { message: label + ':「' + todo.title + '」。', todos: [toolTodo(todo)] }
1088
+ }
1089
+
1090
+ const all = input.all === true
1091
+ const wanted =
1092
+ typeof input.dir === 'string' && input.dir !== '' ? normalizeDir(input.dir) : normalizeDir(cwd)
1093
+ const list = []
1094
+ for (const todo of board.todos) {
1095
+ if (todo.verified) continue
1096
+ if (!all && wanted !== '' && todo.dir !== wanted) continue
1097
+ list.push(todo)
1098
+ }
1099
+ const shown = list.slice(0, 40)
1100
+ if (shown.length === 0) {
1101
+ return {
1102
+ message: all
1103
+ ? '待办板为空(没有未验收的条目)。'
1104
+ : '目录 ' + (cwd || '(未知)') + ' 下没有未完成的待办。',
1105
+ todos: [],
1106
+ }
1107
+ }
1108
+ const lines = [
1109
+ '未验收的待办共 ' + list.length + ' 条' +
1110
+ (all ? '' : '(目录 ' + (cwd || '(未知)') + ')') +
1111
+ ',从上到下就是执行顺序:',
1112
+ ]
1113
+ for (let i = 0; i < shown.length; i++) {
1114
+ const todo = shown[i]
1115
+ const ms = scheduleMs(todo.schedule)
1116
+ lines.push(
1117
+ i + 1 + '. [' + (todo.aiDone ? 'x' : ' ') + '] ' + todo.title +
1118
+ ' | id=' + todo.id +
1119
+ ' | 目录=' + dirLabel(todo.dirPath || todo.dir) +
1120
+ ' | 模式=' + todo.mode +
1121
+ (todo.images.length === 0 ? '' : ' | 图片=' + todo.images.length + ' 张') +
1122
+ (ms === 0
1123
+ ? ''
1124
+ : ' | 定时=' + todo.schedule + (ms > Date.now() ? '(未到点,先别做)' : '(已到点)')),
1125
+ )
1126
+ }
1127
+ return { message: lines.join('\n'), todos: shown.map(toolTodo) }
1128
+ },
1129
+ }
1130
+ ctx.effect(() => tools.register(definition), 'dsh-todo-board: todo_board tool')
1131
+ }
1132
+
1133
+ // ---------------------------------------------- scheduled execution timer
1134
+ //
1135
+ // Armed here rather than inline above so the timer is torn down with the
1136
+ // plugin row instead of leaking a timeout across a reload.
1137
+
1138
+ ctx.effect(() => {
1139
+ armTimer()
1140
+ scheduleTick = setInterval(() => fireDue(), SCHEDULE_TICK_MS)
1141
+ if (typeof scheduleTick.unref === 'function') scheduleTick.unref()
1142
+ return () => {
1143
+ if (scheduleTimer !== undefined) clearTimeout(scheduleTimer)
1144
+ if (scheduleTick !== undefined) clearInterval(scheduleTick)
1145
+ scheduleTimer = undefined
1146
+ scheduleTick = undefined
1147
+ }
1148
+ }, 'dsh-todo-board: scheduled execution timer')
1149
+
1150
+ // ------------------------------------------------------------ HTTP route
1151
+
1152
+ /**
1153
+ * Serve one attachment's bytes for the panel's thumbnails.
1154
+ *
1155
+ * The harness' own image route is session-scoped and refuses an attachment no
1156
+ * session log references — ours live on the board, so the board is the
1157
+ * authority here: an id that no todo references is a 404, never a read.
1158
+ */
1159
+ async function sendBoardImage(response, attachmentId) {
1160
+ let ref
1161
+ for (const todo of board.todos) {
1162
+ for (const image of todo.images) {
1163
+ if (image.attachmentId === attachmentId) {
1164
+ ref = image
1165
+ break
1166
+ }
1167
+ }
1168
+ if (ref !== undefined) break
1169
+ }
1170
+ if (ref === undefined) {
1171
+ response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
1172
+ response.end('unknown attachment')
1173
+ return
1174
+ }
1175
+ const store = ctx.get('attachments')
1176
+ if (store === undefined) {
1177
+ response.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' })
1178
+ response.end('attachments service unavailable')
1179
+ return
1180
+ }
1181
+ const stored = await store.readImage(ref)
1182
+ const body = Buffer.from(stored.data)
1183
+ response.writeHead(200, {
1184
+ 'content-type': stored.ref.mediaType,
1185
+ 'content-length': String(body.length),
1186
+ 'cache-control': 'private, max-age=3600',
1187
+ })
1188
+ response.end(body)
1189
+ }
1190
+
1191
+ ctx.inject(['webServer'], (hostCtx) => {
1192
+ hostCtx.effect(
1193
+ () =>
1194
+ hostCtx.webServer.register({
1195
+ kind: 'prefix',
1196
+ path: IMAGE_ROUTE,
1197
+ handler: async (request, response) => {
1198
+ try {
1199
+ if (request.method !== 'GET') {
1200
+ response.writeHead(405, { allow: 'GET' })
1201
+ response.end()
1202
+ return
1203
+ }
1204
+ const url = new URL(request.url === undefined ? '/' : request.url, 'http://localhost')
1205
+ const id = url.searchParams.get('id')
1206
+ await sendBoardImage(response, id === null ? '' : id)
1207
+ } catch (err) {
1208
+ response.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
1209
+ response.end(errText(err))
1210
+ }
1211
+ },
1212
+ }),
1213
+ 'dsh-todo-board: image route',
1214
+ )
1215
+ })
1216
+
1217
+ ctx.inject(['webServer'], (hostCtx) => {
1218
+ hostCtx.effect(
1219
+ () =>
1220
+ hostCtx.webServer.register({
1221
+ kind: 'exact',
1222
+ path: ROUTE,
1223
+ handler: async (request, response) => {
1224
+ try {
1225
+ if (request.method === 'GET') {
1226
+ sendJson(response, 200, snapshotPayload())
1227
+ return
1228
+ }
1229
+ if (request.method !== 'POST') {
1230
+ response.writeHead(405, { allow: 'GET, POST' })
1231
+ response.end()
1232
+ return
1233
+ }
1234
+ const body = await readJsonBody(request)
1235
+ const action = typeof body.action === 'string' ? body.action : ''
1236
+ let result
1237
+ if (action === 'create') result = await createTodo(body)
1238
+ else if (action === 'patch') result = await patchTodo(body)
1239
+ else if (action === 'reorder') result = reorderTodos(body)
1240
+ else if (action === 'remove') result = removeTodo(body)
1241
+ else if (action === 'clearVerified') result = clearVerified()
1242
+ else if (action === 'run') result = await runTodo(body)
1243
+ else result = { ok: false, error: 'unknown action: ' + (action || '(empty)') }
1244
+ sendJson(response, 200, result)
1245
+ } catch (err) {
1246
+ sendJson(response, 500, { ok: false, error: errText(err) })
1247
+ }
1248
+ },
1249
+ }),
1250
+ 'dsh-todo-board: api route',
1251
+ )
1252
+ })
1253
+ }