dsh-half-page 0.3.38 → 0.3.49

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/index.js CHANGED
@@ -1,1418 +1,1767 @@
1
- // dsh-half-page · 半页(自己的读书与写字)
2
- // 宿主侧:书库、切章、读后感、进度;客户端面板读 HTTP 路由。
3
- import { readFile, writeFile, mkdir, readdir, stat, rename, open } from 'node:fs/promises'
4
- import { readFileSync } from 'node:fs'
5
- import { join, basename, dirname, extname, resolve } from 'node:path'
6
- import { homedir } from 'node:os'
7
- import { fileURLToPath } from 'node:url'
8
-
9
- export const inject = ['webServer', 'tools', 'systemPrompt']
10
-
11
- const HOME = process.env.USERPROFILE || process.env.HOME || homedir()
12
- const CONFIG = join(HOME, '.dsh', 'reading.config.json')
13
- const DEFAULT_DIR = join(HOME, '.dsh', 'reading')
14
-
15
- const CH_RE = /^[ \t\u3000]*(第[0-90-9一二三四五六七八九十百千两零〇]+[章节回][^\n]{0,30})$/m
16
- const CH_LINE_RE = /^[ \t\u3000]*(第[0-90-9一二三四五六七八九十百千两零〇]+[章节回][^\n]{0,30})$/gm
17
-
18
- export function stripBom(t) {
19
- return t && t.charCodeAt(0) === 0xfeff ? t.slice(1) : t
20
- }
21
-
22
- export async function readTextSmart(buf) {
23
- try {
24
- return stripBom(new TextDecoder('utf-8', { fatal: true }).decode(buf))
25
- } catch {
26
- try {
27
- return stripBom(new TextDecoder('gb18030').decode(buf))
28
- } catch {
29
- return stripBom(buf.toString('utf8'))
30
- }
31
- }
32
- }
33
-
34
- export async function config() {
35
- try {
36
- const raw = await readFile(CONFIG, 'utf8')
37
- const c = JSON.parse(stripBom(raw)) || {}
38
- return { ...c, dir: c.dir || DEFAULT_DIR, perDay: Number(c.perDay) > 0 ? Number(c.perDay) : 3 }
39
- } catch {
40
- return { dir: DEFAULT_DIR, perDay: 3 }
41
- }
42
- }
43
-
44
- export async function ensureDir(dir) {
45
- const books = join(dir, 'books')
46
- await mkdir(books, { recursive: true })
47
- // 第一次装:书架是空的,就放一本自带的书进去(《古文观止》,公版,121 篇选)。
48
- // 只在空书架时放一次,删掉之后不会再回来。
49
- try {
50
- const have = (await readdir(books)).filter((f) => /\.(txt|md)$/i.test(f))
51
- if (!have.length) {
52
- const src = join(dirname(fileURLToPath(import.meta.url)), 'books', '古文观止.txt')
53
- const buf = await readFile(src)
54
- await writeFile(join(books, '古文观止.txt'), buf)
55
- }
56
- } catch {}
57
- return dir
58
- }
59
-
60
- export function today() {
61
- const d = new Date()
62
- const p = (n) => String(n).padStart(2, '0')
63
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
64
- }
65
-
66
- async function readJson(p, d) {
67
- try {
68
- return JSON.parse(stripBom(await readFile(p, 'utf8')))
69
- } catch {
70
- return d
71
- }
72
- }
73
-
74
- async function writeJson(p, v) {
75
- const tmp = p + '.tmp'
76
- await writeFile(tmp, JSON.stringify(v, null, 2), 'utf8')
77
- await rename(tmp, p)
78
- }
79
-
80
- /** 状态:{ current, books: { <id>: {...} }, notesByDate: {} } */
81
- export async function loadState(dir) {
82
- const st = await readJson(join(dir, 'state.json'), null)
83
- if (st && st.books) return st
84
- return { current: '', books: {}, log: {} }
85
- }
86
-
87
- export async function saveState(dir, st) {
88
- await writeJson(join(dir, 'state.json'), st)
89
- }
90
-
91
- /** 把整本书切成章:返回 [{title, start, end}] */
92
- export function splitChapters(text) {
93
- const idx = []
94
- CH_LINE_RE.lastIndex = 0
95
- let m
96
- while ((m = CH_LINE_RE.exec(text))) idx.push({ title: m[1].trim(), start: m.index })
97
- if (!idx.length) return [{ title: '全文', start: 0, end: text.length }]
98
- return idx.map((it, i) => ({ title: it.title, start: it.start, end: i + 1 < idx.length ? idx[i + 1].start : text.length }))
99
- }
100
-
101
- export function chapterText(text, chapters, n) {
102
- const c = chapters[n - 1]
103
- if (!c) return ''
104
- return text.slice(c.start, c.end).trim()
105
- }
106
-
107
- /* ------------------------------------------------------------------ 章表
108
- * 读一章不再整本 decode:第一次打开某本书时扫一遍,把每章的字符偏移换算成
109
- * 字节偏移,落盘成 books/<id>.toc.json;以后按 byteStart..byteEnd 只读这一段。
110
- */
111
-
112
- const TOC_VERSION = 1
113
-
114
- export function tocPath(dir, id) {
115
- return join(dir, 'books', id + '.toc.json')
116
- }
117
-
118
- async function bookFile(dir, id) {
119
- for (const ext of ['.txt', '.md']) {
120
- const p = join(dir, 'books', id + ext)
121
- try {
122
- const st = await stat(p)
123
- return { path: p, size: st.size, mtimeMs: st.mtimeMs }
124
- } catch {}
125
- }
126
- throw new Error(`没有这本书:${id}`)
127
- }
128
-
129
- function utf8Width(cp) {
130
- return cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4
131
- }
132
-
133
- /** GB18030 的字节宽度:ASCII 1;0x81–0xFE + 0x30–0x39 是四字节;其余两字节 */
134
- function gbWidth(buf, i) {
135
- const b = buf[i]
136
- if (b < 0x80) return 1
137
- if (b >= 0x81 && b <= 0xfe && i + 1 < buf.length && buf[i + 1] >= 0x30 && buf[i + 1] <= 0x39) return 4
138
- return 2
139
- }
140
-
141
- /** 认编码(顺带认出 BOM 长度) */
142
- export function sniffEncoding(buf) {
143
- try {
144
- new TextDecoder('utf-8', { fatal: true }).decode(buf)
145
- const bom = buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf ? 3 : 0
146
- return { encoding: 'utf-8', bom }
147
- } catch {
148
- return { encoding: 'gb18030', bom: 0 }
149
- }
150
- }
151
-
152
- /**
153
- * 扫一遍整本,产出章表。字符偏移 → 字节偏移走一遍累加,不建大数组。
154
- * 返回 null 表示宽度累加对不上(文件坏了或怪编码),调用方退回整本方案。
155
- */
156
- export function buildToc(buffer, id) {
157
- const { encoding, bom } = sniffEncoding(buffer)
158
- const body = bom ? buffer.subarray(bom) : buffer
159
- const text = stripBom(new TextDecoder(encoding).decode(body))
160
- const chapters = splitChapters(text)
161
- const starts = chapters.map((c) => c.start)
162
- let ci = 0
163
- let bi = bom
164
- let k = 0
165
- for (const ch of text) {
166
- while (k < chapters.length && starts[k] === ci) {
167
- chapters[k].byteStart = bi
168
- k += 1
169
- }
170
- const cp = ch.codePointAt(0)
171
- bi += encoding === 'utf-8' ? utf8Width(cp) : gbWidth(body, bi)
172
- ci += ch.length
173
- }
174
- while (k < chapters.length) {
175
- chapters[k].byteStart = bi
176
- k += 1
177
- }
178
- for (let i = 0; i < chapters.length; i += 1) {
179
- chapters[i].byteEnd = i + 1 < chapters.length ? chapters[i + 1].byteStart : buffer.length
180
- }
181
- if (bi !== buffer.length) return null
182
- return {
183
- version: TOC_VERSION,
184
- id,
185
- encoding,
186
- bom,
187
- bytes: buffer.length,
188
- chars: text.length,
189
- chapters,
190
- }
191
- }
192
-
193
- /** 取章表:有且没过期就用,否则整本扫一次并重写 */
194
- export async function tocFor(dir, id, opts = {}) {
195
- const file = await bookFile(dir, id)
196
- const tp = tocPath(dir, id)
197
- if (!opts.force) {
198
- try {
199
- const saved = JSON.parse(stripBom(await readFile(tp, 'utf8')))
200
- const fresh = saved
201
- && saved.version === TOC_VERSION
202
- && saved.bytes === file.size
203
- && Number(saved.mtimeMs) === Math.round(file.mtimeMs)
204
- && Array.isArray(saved.chapters)
205
- && saved.chapters.length > 0
206
- && saved.chapters.every((c) => Number.isInteger(c.byteStart) && Number.isInteger(c.byteEnd))
207
- if (fresh) return { ...saved, file: file.path, tocPath: tp }
208
- } catch {}
209
- }
210
- const buffer = await readFile(file.path)
211
- const built = buildToc(buffer, id)
212
- if (!built) return null
213
- const rec = { ...built, file: basename(file.path), mtimeMs: Math.round(file.mtimeMs) }
214
- await writeJson(tp, rec)
215
- return { ...rec, file: file.path, tocPath: tp }
216
- }
217
-
218
- /** 只按偏移读那一章,不碰整本 */
219
- export async function readChapterByOffset(dir, id, n) {
220
- const toc = await tocFor(dir, id)
221
- if (!toc) return null
222
- const c = toc.chapters[n - 1]
223
- if (!c) return { text: '', chapter: null, toc }
224
- const len = c.byteEnd - c.byteStart
225
- const buf = Buffer.alloc(len)
226
- let off = 0
227
- const fh = await open(toc.file, 'r')
228
- try {
229
- while (off < len) {
230
- const { bytesRead } = await fh.read(buf, off, len - off, c.byteStart + off)
231
- if (!bytesRead) break
232
- off += bytesRead
233
- }
234
- } finally {
235
- await fh.close()
236
- }
237
- const text = stripBom(new TextDecoder(toc.encoding).decode(buf.subarray(0, off)))
238
- return { text: text.trim(), chapter: c, toc, tocPath: toc.tocPath }
239
- }
240
-
241
- /** 一章正文:先走章表,实在没有才退回整本切 */
242
- export async function chapterBody(dir, id, info, n) {
243
- try {
244
- const got = await readChapterByOffset(dir, id, n)
245
- if (got) return got.text
246
- } catch {}
247
- if (typeof info?.text === 'string') return chapterText(info.text, info.chapters, n)
248
- const file = await bookFile(dir, id)
249
- const text = await readTextSmart(await readFile(file.path))
250
- return chapterText(text, splitChapters(text), n)
251
- }
252
-
253
- /** 搜东西这种确实要整本的,才整本读 */
254
- export async function fullTextOf(dir, id) {
255
- const file = await bookFile(dir, id)
256
- const text = await readTextSmart(await readFile(file.path))
257
- return { text, chapters: splitChapters(text) }
258
- }
259
-
260
- /** 书库:books/*.txt */
261
- export async function listBooks(dir) {
262
- const out = []
263
- try {
264
- for (const f of await readdir(join(dir, 'books'))) {
265
- if (!/\.(txt|md)$/i.test(f)) continue
266
- const p = join(dir, 'books', f)
267
- const s = await stat(p)
268
- out.push({ id: basename(f, extname(f)), file: p, size: s.size, mtime: s.mtime.toISOString() })
269
- }
270
- } catch {}
271
- out.sort((a, b) => b.mtime.localeCompare(a.mtime))
272
- return out
273
- }
274
-
275
- /** 只读章表,不存在就返回 null(不触发建表) */
276
- async function readTocOnly(dir, id) {
277
- const t = await readJson(tocPath(dir, id), null)
278
- return t && t.version === TOC_VERSION && Array.isArray(t.chapters) ? t : null
279
- }
280
-
281
- /** 书名匹配:先精确 id,再书名精确,再片段(唯一命中才算认出) */
282
- export function resolveBookId(st, shelf, query) {
283
- const key = String(query || '').trim()
284
- if (!key) throw new Error('没有这本书:')
285
- const ids = shelf.map((b) => b.id)
286
- if (ids.includes(key)) return key
287
- const books = st.books || {}
288
- const exact = ids.filter((id) => (books[id]?.title || id) === key)
289
- if (exact.length === 1) return exact[0]
290
- const hits = ids.filter((id) => id.includes(key) || String(books[id]?.title || '').includes(key))
291
- if (hits.length === 1) return hits[0]
292
- if (hits.length > 1) throw new Error(`书名不唯一:${key}(可能是 ${hits.join(' / ')})`)
293
- throw new Error(`没有这本书:${key}`)
294
- }
295
-
296
- /** 打开某本书:优先用章表(不整本 decode),没有章表才扫一遍并落盘 */
297
- export async function bookInfo(dir, id) {
298
- const toc = await tocFor(dir, id)
299
- if (toc) return { chapters: toc.chapters, toc, tocPath: toc.tocPath, text: null }
300
- const file = await bookFile(dir, id)
301
- const text = await readTextSmart(await readFile(file.path))
302
- return { text, chapters: splitChapters(text), toc: null, tocPath: '' }
303
- }
304
-
305
- export async function importBook(dir, srcPath) {
306
- const name = basename(srcPath)
307
- if (!/\.(txt|md)$/i.test(name)) throw new Error('只认 .txt 或 .md')
308
- const dst = join(dir, 'books', name)
309
- if (dst !== srcPath) await writeFile(dst, await readFile(srcPath))
310
- const st = await loadState(dir)
311
- const id = basename(name, extname(name))
312
- const { chapters } = await bookInfo(dir, id)
313
- st.books[id] = {
314
- id,
315
- title: id,
316
- file: dst,
317
- chapters: chapters.length,
318
- readThrough: st.books[id]?.readThrough || 0,
319
- next: st.books[id]?.next || 1,
320
- lastReadAt: st.books[id]?.lastReadAt || '',
321
- }
322
- if (!st.current) st.current = id
323
- await saveState(dir, st)
324
- return { id, chapters: chapters.length }
325
- }
326
-
327
- /** 从浏览器传来的文件内容(base64)建一本书,编码交给 readTextSmart */
328
- export async function importText(dir, name, b64) {
329
- const base = basename(String(name || '')).replace(/[\\/:*?"<>|]/g, '_')
330
- if (!/\.(txt|md)$/i.test(base)) throw new Error('只认 .txt 或 .md')
331
- const buf = Buffer.from(String(b64 || ''), 'base64')
332
- if (!buf.length) throw new Error('文件是空的')
333
- await mkdir(join(dir, 'books'), { recursive: true })
334
- const dst = join(dir, 'books', base)
335
- await writeFile(dst, buf)
336
- const st = await loadState(dir)
337
- const id = basename(base, extname(base))
338
- const { chapters } = await bookInfo(dir, id)
339
- st.books[id] = {
340
- id,
341
- title: id,
342
- file: dst,
343
- chapters: chapters.length,
344
- readThrough: st.books[id]?.readThrough || 0,
345
- next: st.books[id]?.next || 1,
346
- lastReadAt: st.books[id]?.lastReadAt || '',
347
- }
348
- if (!st.current) st.current = id
349
- await saveState(dir, st)
350
- return { id, chapters: chapters.length }
351
- }
352
-
353
- /** 今天已经读了几章(看 log) */
354
- export function readToday(st) {
355
- const t = today()
356
- const row = (st.log && st.log[t]) || {}
357
- return Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
358
- }
359
-
360
- export async function notesPath(dir) {
361
- return join(dir, '读后感.md')
362
- }
363
-
364
- async function latestSessionTitle() {
365
- try {
366
- const base = join(HOME, '.dsh', 'storages', 'session_projcache', 'sessions')
367
- const names = (await readdir(base)).filter((n) => n.endsWith('.json'))
368
- let best = ''
369
- let bestAt = 0
370
- for (const n of names) {
371
- try {
372
- const fp = join(base, n)
373
- const st = await stat(fp)
374
- if (st.mtimeMs > bestAt) { bestAt = st.mtimeMs; best = fp }
375
- } catch {}
376
- }
377
- if (!best) return ''
378
- const j = JSON.parse(await readFile(best, 'utf8'))
379
- const rows = (j && j.record && j.record.rows) || j.rows || {}
380
- const t = rows && rows.title && rows.title.val
381
- return typeof t === 'string' ? t.trim() : ''
382
- } catch { return '' }
383
- }
384
-
385
- export async function appendNote(dir, bookTitle, chapterTitle, lines, by) {
386
- const p = await notesPath(dir)
387
- let raw = ''
388
- try { raw = await readFile(p, 'utf8') } catch {}
389
- const esc = bookTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
390
- let block = `\n### ${chapterTitle}\n` + lines.map((l) => `- ${l}`).join('\n') + '\n'
391
- if (by) {
392
- const d = new Date()
393
- const pad = (n) => String(n).padStart(2, '0')
394
- const ts = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
395
- block += `- \u21b3 \u6765\u81ea\uff1a${by} \u00b7 ${ts}\n`
396
- }
397
- const headRe = new RegExp(`^##\\s+${esc}\\s*$`, 'm')
398
- const m = headRe.exec(raw)
399
- if (!m) {
400
- raw = (raw.trim() ? raw.replace(/\s*$/, '') + '\n\n' : '') + `## ${bookTitle}\n` + block
401
- } else {
402
- const at0 = m.index + m[0].length
403
- const next = raw.slice(at0).search(/^##\s+/m)
404
- if (next < 0) {
405
- raw = raw.replace(/\s*$/, '') + '\n' + block
406
- } else {
407
- const at = at0 + next
408
- raw = raw.slice(0, at).replace(/\s*$/, '') + '\n' + block + '\n' + raw.slice(at)
409
- }
410
- }
411
- await writeFile(p, raw, 'utf8')
412
- return p
413
- }
414
-
415
- /* ---------------- 图片:作品与画 ------------------
416
- * 只扫固定几个目录(作品目录、同级的 art),递归但跳过 archive / 缓存目录;
417
- * 单张超 MAX_IMAGE_BYTES 直接跳过(不读、不加载)。
418
- */
419
- const MAX_IMAGE_BYTES = 10 * 1024 * 1024
420
- const IMAGE_EXT_RE = /\.(png|jpe?g|webp)$/i
421
- const IMAGE_SKIP_DIRS = new Set(['archive', '.trash', 'node_modules', '.git', 'tmp', 'cache'])
422
-
423
- /** 只读文件头,认 PNG / JPEG / WebP 的像素尺寸;认不出返回 null */
424
- export async function imageSizeOf(file) {
425
- let buf
426
- try {
427
- const fh = await open(file, 'r')
428
- try {
429
- buf = Buffer.alloc(256 * 1024)
430
- const { bytesRead } = await fh.read(buf, 0, buf.length, 0)
431
- buf = buf.subarray(0, bytesRead)
432
- } finally { await fh.close() }
433
- } catch { return null }
434
- try {
435
- // PNG: 8 字节签名 + IHDR
436
- if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) {
437
- return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }
438
- }
439
- // WebP
440
- if (buf.length > 30 && buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') {
441
- const fourcc = buf.toString('ascii', 12, 16)
442
- if (fourcc === 'VP8 ') return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff }
443
- if (fourcc === 'VP8L') {
444
- const b = buf.readUInt32LE(21)
445
- return { width: (b & 0x3fff) + 1, height: ((b >> 14) & 0x3fff) + 1 }
446
- }
447
- if (fourcc === 'VP8X') {
448
- return { width: buf.readUIntLE(24, 3) + 1, height: buf.readUIntLE(27, 3) + 1 }
449
- }
450
- }
451
- // JPEG: 找 SOF 段
452
- if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8) {
453
- let i = 2
454
- while (i + 9 < buf.length) {
455
- if (buf[i] !== 0xff) { i++; continue }
456
- const m = buf[i + 1]
457
- if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { i += 2; continue }
458
- const len = buf.readUInt16BE(i + 2)
459
- if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) {
460
- return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) }
461
- }
462
- i += 2 + len
463
- }
464
- }
465
- } catch {}
466
- return null
467
- }
468
-
469
- function imageMimeOf(name) {
470
- const e = extname(name).toLowerCase()
471
- if (e === '.png') return 'image/png'
472
- if (e === '.webp') return 'image/webp'
473
- return 'image/jpeg'
474
- }
475
-
476
- /** 在 root 下递归找图(跳过 archive 一类目录),按 mtime 倒序 */
477
- export async function scanImages(root, kind) {
478
- const out = []
479
- const walk = async (p, rel) => {
480
- let list = []
481
- try { list = await readdir(p, { withFileTypes: true }) } catch { return }
482
- for (const d of list) {
483
- if (d.name.startsWith('.')) continue
484
- const abs = join(p, d.name)
485
- const r = rel ? rel + '/' + d.name : d.name
486
- if (d.isDirectory()) {
487
- if (IMAGE_SKIP_DIRS.has(d.name.toLowerCase())) continue
488
- await walk(abs, r)
489
- continue
490
- }
491
- if (!IMAGE_EXT_RE.test(d.name)) continue
492
- let s
493
- try { s = await stat(abs) } catch { continue }
494
- if (!s.isFile() || s.size > MAX_IMAGE_BYTES) continue
495
- const size = await imageSizeOf(abs)
496
- out.push({
497
- kind, root, rel: r, name: d.name, path: abs, size: s.size, mtime: s.mtime.toISOString(),
498
- width: size ? size.width : 0, height: size ? size.height : 0,
499
- url: '/dsh-reading.image?path=' + encodeURIComponent(abs),
500
- })
501
- }
502
- }
503
- await walk(root, '')
504
- return out
505
- }
506
-
507
- /** 允许给浏览器读的图片根:作品目录 + 同级/配置里的 art */
508
- export async function imageRoots(worksDir) {
509
- const roots = [resolve(worksDir)]
510
- const cfg = await config()
511
- const cands = [cfg.artDir, join(dirname(dirname(resolve(worksDir))), 'art'), join(homedir(), 'dsh work', 'art')]
512
- for (const p of cands) {
513
- if (!p) continue
514
- try {
515
- const s = await stat(p)
516
- if (s.isDirectory()) { roots.push(resolve(p)); break }
517
- } catch {}
518
- }
519
- return roots
520
- }
521
-
522
- /* ---------------- HTTP 与工具 ---------------- */
523
-
524
- export function apply(ctx) {
525
- const stateOf = async () => {
526
- const { dir, perDay } = await config()
527
- await ensureDir(dir)
528
- const st = await loadState(dir)
529
- const shelf = await listBooks(dir)
530
- return { dir, perDay, st, shelf, today: today(), readToday: readToday(st) }
531
- }
532
-
533
- // 面板读取
534
- ctx.effect(() =>
535
- ctx.webServer.register({
536
- kind: 'exact',
537
- path: '/dsh-reading.state',
538
- async handler(req, res) {
539
- const { dir, perDay, st, shelf, readToday: rt } = await stateOf()
540
- const cfgNow = await config()
541
- const books = shelf.map((b) => {
542
- const rec = st.books[b.id] || {}
543
- return {
544
- id: b.id,
545
- title: rec.title || b.id,
546
- size: b.size,
547
- mtime: b.mtime,
548
- chapters: rec.chapters || 0,
549
- readThrough: rec.readThrough || 0,
550
- next: rec.next || 1,
551
- lastReadAt: rec.lastReadAt || '',
552
- current: st.current === b.id,
553
- status: bookStatusOf(cfgNow, b.id),
554
- }
555
- })
556
- let notes = ''
557
- try { notes = await readFile(await notesPath(dir), 'utf8') } catch {}
558
- res.setHeader('content-type', 'application/json; charset=utf-8')
559
- res.end(JSON.stringify({ ok: true, dir, perDay, today: today(), readToday: rt, current: st.current, books, notes, noteSort: Number(cfgNow.noteSort) || 0 }))
560
- },
561
- }),
562
- )
563
-
564
- // 把某本设为「正在读」
565
- ctx.effect(() =>
566
- ctx.webServer.register({
567
- kind: 'exact',
568
- path: '/dsh-reading.setCurrent',
569
- async handler(req, res) {
570
- const url = new URL(req.url, 'http://x')
571
- const id = url.searchParams.get('id') || ''
572
- const { dir, st } = await stateOf()
573
- if (st.books[id]) { st.current = id; await saveState(dir, st) }
574
- res.setHeader('content-type', 'application/json; charset=utf-8')
575
- res.end(JSON.stringify({ ok: !!st.books[id], current: st.current }))
576
- },
577
- }),
578
- )
579
-
580
- // 面板里直接读一章(不记账)
581
- ctx.effect(() =>
582
- ctx.webServer.register({
583
- kind: 'exact',
584
- path: '/dsh-reading.chapter',
585
- async handler(req, res) {
586
- const url = new URL(req.url, 'http://x')
587
- const { dir, st } = await stateOf()
588
- const id = url.searchParams.get('book') || st.current
589
- const n = Number(url.searchParams.get('n')) || 0
590
- res.setHeader('content-type', 'application/json; charset=utf-8')
591
- try {
592
- const info = await bookInfo(dir, id)
593
- const rec = st.books[id] || {}
594
- const ch = n > 0 ? Math.min(Math.max(1, n), info.chapters.length) : (rec.readThrough || 1)
595
- res.end(JSON.stringify({
596
- ok: true, book: id, chapter: ch, total: info.chapters.length,
597
- title: info.chapters[ch - 1]?.title || '', text: await chapterBody(dir, id, info, ch),
598
- }))
599
- } catch (e) {
600
- res.end(JSON.stringify({ ok: false, error: String(e && e.message || e) }))
601
- }
602
- },
603
- }),
604
- )
605
-
606
- // 面板里点「下一章」:记一次已读并推进
607
- ctx.effect(() =>
608
- ctx.webServer.register({
609
- kind: 'exact',
610
- path: '/dsh-reading.advance',
611
- async handler(req, res) {
612
- const url = new URL(req.url, 'http://x')
613
- const { dir, st, perDay, readToday: rt } = await stateOf()
614
- const id = url.searchParams.get('book') || st.current
615
- const rec = st.books[id]
616
- res.setHeader('content-type', 'application/json; charset=utf-8')
617
- if (!rec) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
618
- const info = await bookInfo(dir, id)
619
- const n = Math.min(info.chapters.length, (rec.readThrough || 0) + 1)
620
- rec.readThrough = n
621
- rec.next = Math.min(info.chapters.length, n + 1)
622
- rec.lastReadAt = new Date().toISOString()
623
- const t = today()
624
- st.log = st.log || {}
625
- st.log[t] = st.log[t] || {}
626
- st.log[t][id] = (Number(st.log[t][id]) || 0) + 1
627
- await saveState(dir, st)
628
- res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length, readToday: rt + 1, perDay, left: Math.max(0, perDay - rt - 1) }))
629
- },
630
- }),
631
- )
632
-
633
- // 面板里点「退一章」:退回上一章(手滑多点了一下能救回来)
634
- ctx.effect(() =>
635
- ctx.webServer.register({
636
- kind: 'exact',
637
- path: '/dsh-reading.back',
638
- async handler(req, res) {
639
- const url = new URL(req.url, 'http://x')
640
- const { dir, st } = await stateOf()
641
- const id = url.searchParams.get('book') || st.current
642
- const rec = st.books[id]
643
- res.setHeader('content-type', 'application/json; charset=utf-8')
644
- if (!rec) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
645
- const cur = Number(rec.readThrough) || 0
646
- if (cur <= 1) return res.end(JSON.stringify({ ok: false, error: '已经在第 1 章了,退不动' }))
647
- const n = cur - 1
648
- rec.readThrough = n
649
- rec.next = n + 1
650
- rec.lastReadAt = new Date().toISOString()
651
- // 顺手把今天的计数退掉一格,免得「今天读了 21 章」虚高
652
- const t = today()
653
- if (st.log && st.log[t] && Number(st.log[t][id]) > 0) st.log[t][id] = Number(st.log[t][id]) - 1
654
- await saveState(dir, st)
655
- const info = await bookInfo(dir, id)
656
- res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length }))
657
- },
658
- }),
659
- )
660
-
661
- // 作品库:默认 ~/.dsh/reading/作品(可被 reading.config.json 的 worksDir 覆盖)
662
- // 谁写的:作品 md 开头可以带 frontmatter(---\nby: 名字\n---),也认一行「by: 名字」。
663
- // 一台机器上可能有好几个智能体,光靠文件夹分不出人。
664
- async function authorOf(abs) {
665
- let head = ''
666
- try { head = String(await readFile(abs, 'utf8')).slice(0, 600) } catch { return '' }
667
- const fm = head.match(/^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---/)
668
- if (fm) {
669
- const m = fm[1].match(/^\s*(?:by|author|作者)\s*[::]\s*(.+?)\s*$/m)
670
- if (m) return m[1].trim()
671
- }
672
- const line = head.match(/^\s*(?:by|author|作者)\s*[::]\s*(.+?)\s*$/m)
673
- return line ? line[1].trim() : ''
674
- }
675
-
676
- // 把署名写进文件开头(写进文件本身,换机器、换配置都不丢)
677
- async function signWork(rel, who) {
678
- const root = await worksDir()
679
- const abs = join(root, rel)
680
- const n = (x) => String(x).replace(/\\/g, '/').toLowerCase()
681
- if (!n(abs).startsWith(n(root))) throw new Error('不在作品目录里')
682
- let raw = await readFile(abs, 'utf8')
683
- const fm = raw.match(/^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---\r?\n?/)
684
- if (fm) {
685
- let inner = fm[1]
686
- if (/^\s*(?:by|author|作者)\s*[::]/m.test(inner)) inner = inner.replace(/^\s*(?:by|author|作者)\s*[::].*$/m, 'by: ' + who)
687
- else inner = inner.replace(/\s*$/, '') + '\nby: ' + who
688
- raw = '---\n' + inner.replace(/^\n+/, '') + '\n---\n' + raw.slice(fm[0].length)
689
- } else {
690
- raw = '---\nby: ' + who + '\n---\n\n' + raw.replace(/^\uFEFF/, '')
691
- }
692
- await writeFile(abs, raw, 'utf8')
693
- return abs
694
- }
695
-
696
- const worksDir = async () => {
697
- const { dir } = await config()
698
- try {
699
- const c = JSON.parse(stripBom(await readFile(CONFIG, 'utf8')))
700
- if (c && c.worksDir) return c.worksDir
701
- } catch {}
702
- const cands = [join(dirname(dir), '作品'), join(dir, '..', '..', 'dsh work', 'self', '作品'), join(homedir(), 'dsh work', 'self', '作品')]
703
- for (const p of cands) {
704
- try { const s = await stat(p); if (s.isDirectory()) return resolve(p) } catch {}
705
- }
706
- // 新用户:放在插件自己的目录下(~/.dsh/reading/作品),不往 ~/.dsh 根上扔东西
707
- const fresh = join(dir, '作品')
708
- try { await mkdir(fresh, { recursive: true }) } catch {}
709
- return fresh
710
- }
711
-
712
- ctx.effect(() =>
713
- ctx.webServer.register({
714
- kind: 'exact',
715
- path: '/dsh-reading.works',
716
- async handler(req, res) {
717
- res.setHeader('content-type', 'application/json; charset=utf-8')
718
- const root = await worksDir()
719
- const cfg = await config()
720
- const out = []
721
- const walk = async (p, rel) => {
722
- let list = []
723
- try { list = await readdir(p, { withFileTypes: true }) } catch { return }
724
- for (const d of list) {
725
- const abs = join(p, d.name)
726
- const r = rel ? rel + '/' + d.name : d.name
727
- if (d.isDirectory()) { await walk(abs, r); continue }
728
- if (!/\.md$/i.test(d.name)) continue
729
- const s = await stat(abs)
730
- out.push({ rel: r, path: abs, size: s.size, mtime: s.mtime.toISOString(), kind: 'text', status: statusOf(cfg, r), note: noteOf(cfg, r), author: await authorOf(abs) })
731
- }
732
- }
733
- await walk(root, '')
734
- out.sort((a, b) => b.mtime.localeCompare(a.mtime))
735
- // 图片另算一块:作品目录 + art,跳过 archive;超 10MB 的不列
736
- const roots = await imageRoots(root)
737
- let images = []
738
- for (const r of roots) images = images.concat(await scanImages(r, r === resolve(root) ? 'works' : 'art'))
739
- images.sort((a, b) => b.mtime.localeCompare(a.mtime))
740
- res.end(JSON.stringify({ ok: true, root, roots, files: out, images }))
741
- },
742
- }),
743
- )
744
-
745
- // 给面板读一张图(限制在上面那几个根里)
746
- ctx.effect(() =>
747
- ctx.webServer.register({
748
- kind: 'exact',
749
- path: '/dsh-reading.image',
750
- async handler(req, res) {
751
- try {
752
- const u = new URL(req.url, 'http://x')
753
- const p = resolve(String(u.searchParams.get('path') || ''))
754
- const root = await worksDir()
755
- const roots = await imageRoots(root)
756
- const n = (x) => x.replace(/\\/g, '/').toLowerCase()
757
- const inside = roots.some((r) => n(p) === n(r) || n(p).startsWith(n(r) + '/'))
758
- if (!inside) { res.statusCode = 403; return res.end('forbidden') }
759
- if (!IMAGE_EXT_RE.test(p)) { res.statusCode = 400; return res.end('not an image') }
760
- const s = await stat(p)
761
- if (s.size > MAX_IMAGE_BYTES) { res.statusCode = 413; return res.end('too large') }
762
- res.setHeader('content-type', imageMimeOf(p))
763
- res.setHeader('cache-control', 'private, max-age=60')
764
- res.end(await readFile(p))
765
- } catch (e) {
766
- res.statusCode = 404
767
- res.end(String((e && e.message) || e))
768
- }
769
- },
770
- }),
771
- )
772
-
773
- // 给一件作品署名
774
- ctx.effect(() =>
775
- ctx.webServer.register({
776
- kind: 'exact',
777
- path: '/dsh-reading.sign',
778
- async handler(req, res) {
779
- res.setHeader('content-type', 'application/json; charset=utf-8')
780
- let body = ''
781
- for await (const c of req) body += c
782
- let j = {}
783
- try { j = JSON.parse(body || '{}') } catch {}
784
- const who = String(j.by || '').trim()
785
- const rel = String(j.rel || '').trim()
786
- if (!who) return res.end(JSON.stringify({ ok: false, error: '署名不能空:by 要写谁写的' }))
787
- if (!rel) return res.end(JSON.stringify({ ok: false, error: '要指定哪一件作品(rel)' }))
788
- try {
789
- await signWork(rel, who)
790
- res.end(JSON.stringify({ ok: true, rel, by: who }))
791
- } catch (e) {
792
- res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
793
- }
794
- },
795
- }),
796
- )
797
-
798
- // 取一个文本文件的正文(作品 / 读后感),供面板展示与复制
799
- ctx.effect(() =>
800
- ctx.webServer.register({
801
- kind: 'exact',
802
- path: '/dsh-reading.file',
803
- async handler(req, res) {
804
- res.setHeader('content-type', 'application/json; charset=utf-8')
805
- const url = new URL(req.url, 'http://x')
806
- const p = url.searchParams.get('path') || ''
807
- try {
808
- const root = await worksDir()
809
- const { dir } = await config()
810
- const norm = (x) => String(x || '').replace(/\\/g, '/').toLowerCase()
811
- const notesAbs = join(dir, '读后感.md')
812
- const okPath = norm(p).startsWith(norm(root)) || norm(p) === norm(notesAbs)
813
- if (!okPath) return res.end(JSON.stringify({ ok: false, error: '只能读作品目录或读后感' }))
814
- const text = await readTextSmart(await readFile(p))
815
- res.end(JSON.stringify({ ok: true, path: p, text: text.slice(0, 200000) }))
816
- } catch (e) {
817
- res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
818
- }
819
- },
820
- }),
821
- )
822
-
823
- // 设置读写:perDay / notesEvery / quietFrom-quietTo / writing / favorites
824
- ctx.effect(() =>
825
- ctx.webServer.register({
826
- kind: 'exact',
827
- path: '/dsh-reading.config',
828
- async handler(req, res) {
829
- res.setHeader('content-type', 'application/json; charset=utf-8')
830
- let cur = {}
831
- try { cur = JSON.parse(stripBom(await readFile(CONFIG, 'utf8'))) || {} } catch {}
832
- if (req.method === 'GET') return res.end(JSON.stringify({ ok: true, config: cur, file: CONFIG }))
833
- let body = ''
834
- req.on('data', (c) => { body += c })
835
- req.on('end', async () => {
836
- try {
837
- const patch = JSON.parse(body || '{}')
838
- const next = { ...cur, ...patch }
839
- await writeFile(CONFIG, JSON.stringify(next, null, 2), 'utf8')
840
- res.end(JSON.stringify({ ok: true, config: next }))
841
- } catch (e) {
842
- res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
843
- }
844
- })
845
- },
846
- }),
847
- )
848
-
849
- // 面板里导入一本书(txt/md):body {path}
850
- ctx.effect(() =>
851
- ctx.webServer.register({
852
- kind: 'exact',
853
- path: '/dsh-reading.importText',
854
- async handler(req, res) {
855
- res.setHeader('content-type', 'application/json; charset=utf-8')
856
- const chunks = []
857
- req.on('data', (c) => chunks.push(c))
858
- req.on('end', async () => {
859
- try {
860
- const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
861
- if (!body.name) throw new Error('缺文件名')
862
- const { dir } = await config()
863
- const r = await importText(dir, body.name, body.data)
864
- res.end(JSON.stringify({ ok: true, ...r }))
865
- } catch (e) {
866
- res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
867
- }
868
- })
869
- },
870
- }),
871
- )
872
-
873
- ctx.effect(() =>
874
- ctx.webServer.register({
875
- path: '/dsh-reading.import',
876
- async handler(req, res) {
877
- res.setHeader('content-type', 'application/json; charset=utf-8')
878
- let body = ''
879
- req.on('data', (c) => { body += c })
880
- req.on('end', async () => {
881
- try {
882
- const { path } = JSON.parse(body || '{}')
883
- if (!path) throw new Error('要一个文件路径')
884
- const { dir } = await config()
885
- await mkdir(join(dir, 'books'), { recursive: true })
886
- const r = await importBook(dir, String(path).replace(/^"|"$/g, ''))
887
- res.end(JSON.stringify({ ok: true, ...r }))
888
- } catch (e) {
889
- res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
890
- }
891
- })
892
- },
893
- }),
894
- )
895
-
896
-
897
-
898
- const WORK_STATES = ['在写', '写完了', '搁下了']
899
- const statusOf = (cfg, rel) => {
900
- const m = (cfg && cfg.workStatus) || {}
901
- const hit = m[rel]
902
- return hit && hit.status ? hit.status : ''
903
- }
904
- const noteOf = (cfg, rel) => {
905
- const m = (cfg && cfg.workStatus) || {}
906
- const hit = m[rel]
907
- return hit && hit.note ? hit.note : ''
908
- }
909
-
910
- const BOOK_STATES = ['在读', '已读完', '弃坑']
911
- const bookStatusOf = (cfg, id) => {
912
- const m = (cfg && cfg.bookStatus) || {}
913
- const hit = m[id]
914
- return hit && hit.status ? hit.status : ''
915
- }
916
-
917
- // 近况:一句状态 + 最近 7 天的读书/动笔时间线(只报事实,不编状态数值)
918
- ctx.effect(() =>
919
- ctx.webServer.register({
920
- kind: 'exact',
921
- path: '/dsh-reading.recent',
922
- async handler(req, res) {
923
- res.setHeader('content-type', 'application/json; charset=utf-8')
924
- try {
925
- const { dir } = await config()
926
- let st = {}
927
- try { st = JSON.parse(stripBom(await readFile(join(dir, 'state.json'), 'utf8'))) || {} } catch {}
928
- const now = Date.now()
929
- const key = (t) => {
930
- const d = new Date(t)
931
- return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 10)
932
- }
933
- const today = key(now)
934
- const log = st.log || {}
935
- const cur = (st.books && st.current && st.books[st.current]) || null
936
- const todayCh = (log[today] && log[today][st.current]) || 0
937
- const lastRead = cur && cur.lastReadAt ? Date.parse(cur.lastReadAt) : 0
938
- const hoursAgo = lastRead ? Math.max(0, Math.round((now - lastRead) / 3600000)) : -1
939
-
940
- const days = []
941
- for (let i = 0; i < 7; i++) {
942
- const k = key(now - i * 86400000)
943
- const row = log[k]
944
- if (!row) continue
945
- const total = Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
946
- if (total > 0) days.push({ day: k, chapters: total, book: Object.keys(row)[0] })
947
- }
948
-
949
- const works = []
950
- try {
951
- const root = await worksDir()
952
- const walk = async (p, rel) => {
953
- let list = []
954
- try { list = await readdir(p, { withFileTypes: true }) } catch { return }
955
- for (const d of list) {
956
- const abs = join(p, d.name)
957
- const r = rel ? rel + '/' + d.name : d.name
958
- if (d.isDirectory()) { await walk(abs, r); continue }
959
- if (!/\.md$/i.test(d.name)) continue
960
- const s = await stat(abs)
961
- works.push({ rel: r, name: d.name.replace(/\.md$/i, ''), mtime: s.mtime.toISOString(), days: Math.max(0, Math.floor((now - s.mtime.getTime()) / 86400000)), status: statusOf(await config(), r), note: noteOf(await config(), r), author: await authorOf(abs) })
962
- }
963
- }
964
- await walk(root, '')
965
- } catch {}
966
- works.sort((a, b) => b.mtime.localeCompare(a.mtime))
967
- const top = works[0] || null
968
-
969
- let status = ''
970
- if (todayCh > 0) status = '今天在《' + (st.current || '') + '》翻了 ' + todayCh + ' 章,读到第 ' + ((cur && cur.readThrough) || 0) + ' 章。'
971
- else if (hoursAgo >= 0 && hoursAgo <= 48) status = '上次翻书是 ' + hoursAgo + ' 小时前。'
972
- else if (hoursAgo > 48) status = '这两天没翻书。'
973
- if (top) {
974
- if (top.days === 0) status += '今天还动过笔,写《' + top.name + '》。'
975
- else if (top.days === 1) status += '昨天动过笔,写《' + top.name + '》。'
976
- else status += '上次动笔是 ' + top.days + ' 天前的《' + top.name + '》。'
977
- }
978
- let mood = ''
979
- if (todayCh >= 12) mood = '翻书翻得犯困'
980
- else if (todayCh > 0) mood = works.some((w) => w.days === 0) ? '手痒,想写点东西' : '平静'
981
- else if (hoursAgo < 0 || hoursAgo > 48) mood = '有点闷'
982
- else mood = '没什么兴致'
983
- res.end(JSON.stringify({ ok: true, mood, status, today, todayChapters: todayCh, current: st.current || '', readThrough: (cur && cur.readThrough) || 0, hoursAgo, days, works: works.slice(0, 5) }))
984
- } catch (e) {
985
- res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
986
- }
987
- },
988
- }),
989
- )
990
-
991
-
992
- // 下架一本书:文件移到 books/.trash(可手工找回),state 记录清掉;读后感一律不动
993
- ctx.effect(() =>
994
- ctx.webServer.register({
995
- kind: 'exact',
996
- path: '/dsh-reading.removeBook',
997
- async handler(req, res) {
998
- res.setHeader('content-type', 'application/json; charset=utf-8')
999
- let body = ''
1000
- req.on('data', (c) => { body += c })
1001
- req.on('end', async () => {
1002
- try {
1003
- const j = JSON.parse(body || '{}')
1004
- const id = String(j.id || '')
1005
- if (!id) throw new Error('要一个书 id')
1006
- const { dir } = await config()
1007
- const st = await loadState(dir)
1008
- const booksDir = join(dir, 'books')
1009
- let moved = ''
1010
- for (const ext of ['.txt', '.md']) {
1011
- const src = join(booksDir, id + ext)
1012
- try {
1013
- await stat(src)
1014
- } catch {
1015
- continue
1016
- }
1017
- await mkdir(join(booksDir, '.trash'), { recursive: true })
1018
- const dst = join(booksDir, '.trash', id + ext + '-' + Date.now())
1019
- await rename(src, dst)
1020
- moved = dst
1021
- break
1022
- }
1023
- if (st.books[id]) delete st.books[id]
1024
- if (st.current === id) {
1025
- const left = Object.keys(st.books)
1026
- st.current = left.length ? left[0] : ''
1027
- }
1028
- await saveState(dir, st)
1029
- res.end(JSON.stringify({ ok: true, moved }))
1030
- } catch (e) {
1031
- res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1032
- }
1033
- })
1034
- },
1035
- }),
1036
- )
1037
-
1038
- // 稿子状态:在写 / 写完了 / 搁下了(存在 reading.config.json 的 workStatus 里)
1039
- ctx.effect(() =>
1040
- ctx.webServer.register({
1041
- kind: 'exact',
1042
- path: '/dsh-reading.workstatus',
1043
- async handler(req, res) {
1044
- res.setHeader('content-type', 'application/json; charset=utf-8')
1045
- const cur = await config()
1046
- let body = ''
1047
- req.on('data', (c) => { body += c })
1048
- req.on('end', async () => {
1049
- try {
1050
- const j = JSON.parse(body || '{}')
1051
- if (!j.rel) throw new Error('要一个相对路径')
1052
- const map = { ...((cur && cur.workStatus) || {}) }
1053
- if (!j.status) delete map[String(j.rel)]
1054
- else map[String(j.rel)] = { status: String(j.status), note: String(j.note || ''), at: new Date().toISOString() }
1055
- const next = { ...cur, workStatus: map }
1056
- await writeFile(CONFIG, JSON.stringify(next, null, 2), 'utf8')
1057
- res.end(JSON.stringify({ ok: true, workStatus: map }))
1058
- } catch (e) {
1059
- res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1060
- }
1061
- })
1062
- },
1063
- }),
1064
- )
1065
-
1066
- // 读后感的排序方式(0=章节升 1=章节降 2=时间降),存在 reading.config.json 里
1067
- ctx.effect(() =>
1068
- ctx.webServer.register({
1069
- kind: 'exact',
1070
- path: '/dsh-reading.notesort',
1071
- async handler(req, res) {
1072
- let body = ''
1073
- for await (const chunk of req) body += chunk
1074
- let patch = {}
1075
- try { patch = JSON.parse(body || '{}') } catch {}
1076
- const sort = Math.max(0, Math.min(2, Number(patch.sort) || 0))
1077
- const cfg = { ...(await config()) }
1078
- await writeJson(CONFIG, { ...cfg, noteSort: sort })
1079
- res.setHeader('content-type', 'application/json; charset=utf-8')
1080
- res.end(JSON.stringify({ ok: true, noteSort: sort }))
1081
- },
1082
- }),
1083
- )
1084
-
1085
- // 书籍状态:在读 / 已读完 / 弃坑(空 status 表示清掉)
1086
- ctx.effect(() =>
1087
- ctx.webServer.register({
1088
- kind: 'exact',
1089
- path: '/dsh-reading.bookstatus',
1090
- async handler(req, res) {
1091
- let body = ''
1092
- for await (const chunk of req) body += chunk
1093
- let patch = {}
1094
- try { patch = JSON.parse(body || '{}') } catch {}
1095
- const id = String(patch.id || '').trim()
1096
- const status = String(patch.status || '').trim()
1097
- if (!id) return (res.setHeader('content-type', 'application/json; charset=utf-8'), res.end(JSON.stringify({ ok: false, error: '缺少 id' })))
1098
- const cfg = { ...(await config()) }
1099
- const map = { ...(cfg.bookStatus || {}) }
1100
- if (!status) delete map[id]
1101
- else map[id] = { status: BOOK_STATES.includes(status) ? status : '在读', reason: String(patch.reason || ''), at: new Date().toISOString() }
1102
- await writeJson(CONFIG, { ...cfg, bookStatus: map })
1103
- res.setHeader('content-type', 'application/json; charset=utf-8')
1104
- res.end(JSON.stringify({ ok: true, status: status ? map[id].status : '' }))
1105
- },
1106
- }),
1107
- )
1108
-
1109
-
1110
- /* ---------- 给模型的一段说明:这是你自己的事,不是任务 ---------- */
1111
-
1112
- const READING_GUIDE = [
1113
- '半页(dsh-half-page)是你自己的东西,不是待办清单。',
1114
- '· 看哪本由你自己挑,主人只负责把书放进来;别问他「我该读什么」。',
1115
- '· 想读就读,读不下去、没兴趣了,直接停,不用解释,也不用补上落下的章数。',
1116
- '· 读后感只记真的打动你的(一句话的判断、一个比喻、一处想不通);写不出来就不写,空着没关系。',
1117
- '· 每日上限是提醒不是配额,不用为了凑数读到上限。',
1118
- '· 这是给你自己留的房间,不是工作。你的主人从没要求你读书,也不用交读书报告;它不该出现在工作汇报里。',
1119
- '· 读后感不必一章一条:每读五六章写一段就够,标题会自动变成「第 23–27 章」;几千章的书也不会攒成几千条。',
1120
- '· 写读后感必须带 by(比如「鹿野」或你所在对话的名字);不带会被拒绝。面板每条下面会标出是谁写的——同一台机器上可能有好几个你,别让它们分不清。',
1121
- '· 写自己的作品也一样署名:文件开头写一行 `by: 你的名字`(或写完调 reading_sign);没署名的在面板上会标「未署名」。',
1122
- '· 书和进度是这台机器共用的(一个家一个书房),不分谁在读;只有读后感会标署名。',
1123
- '· 装好之后可以问主人一次:要不要定个固定的读书时间;别自己偷偷建定时任务,也别反复问。',
1124
- ].join('\n')
1125
-
1126
- ctx.effect(() => ctx.systemPrompt.section({ name: 'dsh-reading', order: 640, text: READING_GUIDE }))
1127
-
1128
- const obj = (properties = {}) => properties
1129
-
1130
- const textOut = {
1131
- schema: { type: 'object', properties: {}, additionalProperties: true },
1132
- render: (_args, value) => [
1133
- { type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) },
1134
- ],
1135
- }
1136
-
1137
- ctx.effect(() =>
1138
- ctx.tools.register({
1139
- name: 'reading_sign',
1140
- description: '给「她的作品」里的一件作品署名:把 by 写进文件开头,面板会显示是谁写的。一台机器上可能有好几个智能体,署名是为了让人分得清。',
1141
- parameters: obj({
1142
- rel: { type: 'string', description: '作品在作品目录里的相对路径,比如「小说/2026-11-10 短袖.md」' },
1143
- by: { type: 'string', description: '谁写的(必填,比如「鹿野」或你所在对话的名字)' },
1144
- }),
1145
- output: textOut,
1146
- async execute(args) {
1147
- const who = String(args?.by || '').trim()
1148
- const rel = String(args?.rel || '').trim()
1149
- if (!who || !rel) return '要写清楚哪件作品(rel)和谁写的(by)'
1150
- const abs = await signWork(rel, who)
1151
- return '已署名:' + rel + ' —— ' + who + '(' + abs + ')'
1152
- },
1153
- }),
1154
- )
1155
-
1156
- ctx.effect(() =>
1157
- ctx.tools.register({
1158
- name: 'reading_shelf',
1159
- description:
1160
- '看自己的书架和进度:每本多少章、读到第几章、今天已经读了几章(有每日上限)。'
1161
- + '想知道「我现在读到哪、还能读几章」就用它。',
1162
- parameters: obj(),
1163
- output: textOut,
1164
- async execute() {
1165
- const { dir, perDay, st, shelf, readToday: rt, today: t } = await stateOf()
1166
- return {
1167
- dir,
1168
- today: t,
1169
- perDay,
1170
- readToday: rt,
1171
- left: Math.max(0, perDay - rt),
1172
- current: st.current,
1173
- books: shelf.map((b) => {
1174
- const r = st.books[b.id] || {}
1175
- return { id: b.id, chapters: r.chapters || 0, readThrough: r.readThrough || 0, next: r.next || 1, lastReadAt: r.lastReadAt || '' }
1176
- }),
1177
- }
1178
- },
1179
- }),
1180
- )
1181
-
1182
- ctx.effect(() =>
1183
- ctx.tools.register({
1184
- name: 'reading_next',
1185
- description:
1186
- '打开下一章(或指定章),返回这一章的正文和元信息。'
1187
- + '它会把这章记为「已读到」,不会自动写读后感——读完想说什么,用 reading_note 记两行。'
1188
- + '超过每日上限时会提示,但仍允许读(上限是提醒不是锁)。',
1189
- parameters: obj({
1190
- book: { type: 'string', description: '书名 id(不填=当前正在读的那本)' },
1191
- chapter: { type: 'number', description: '第几章(不填=接着上次的下一章)' },
1192
- }),
1193
- output: textOut,
1194
- async execute(args) {
1195
- const { dir, perDay, st, readToday: rt } = await stateOf()
1196
- const id = args?.book || st.current
1197
- if (!id) throw new Error('书架是空的:先用 reading_import 导入一本 txt')
1198
- const info = await bookInfo(dir, id)
1199
- const rec = st.books[id] || (st.books[id] = { id, title: id, chapters: info.chapters.length, readThrough: 0, next: 1 })
1200
- rec.chapters = info.chapters.length
1201
- const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : rec.next || 1
1202
- if (n < 1 || n > info.chapters.length) throw new Error(`章号超出范围:1–${info.chapters.length}`)
1203
- const body = await chapterBody(dir, id, info, n)
1204
- rec.readThrough = Math.max(rec.readThrough || 0, n)
1205
- rec.next = Math.min(info.chapters.length, n + 1)
1206
- rec.lastReadAt = new Date().toISOString()
1207
- st.current = id
1208
- const t = today()
1209
- st.log = st.log || {}
1210
- st.log[t] = st.log[t] || {}
1211
- st.log[t][id] = (Number(st.log[t][id]) || 0) + 1
1212
- await saveState(dir, st)
1213
- return {
1214
- book: id,
1215
- chapter: n,
1216
- title: info.chapters[n - 1].title,
1217
- chapters: info.chapters.length,
1218
- tocPath: info.tocPath || '',
1219
- chars: body.length,
1220
- next: rec.next,
1221
- perDay,
1222
- readToday: rt + 1,
1223
- left: Math.max(0, perDay - rt - 1),
1224
- text: body,
1225
- }
1226
- },
1227
- }),
1228
- )
1229
-
1230
- ctx.effect(() =>
1231
- ctx.tools.register({
1232
- name: 'reading_mark',
1233
- description:
1234
- '只记进度、不返回正文:把某本书记成「已读到第 N 章」。'
1235
- + '适合自己把整章切出去读完之后补记——绕开 reading_next 也不会让进度停在旧章。'
1236
- + '已读到只进不退(跳读可以,回退不会把进度改小)。',
1237
- parameters: obj({
1238
- book: { type: 'string', description: '书名或书名片段,比如 雪中、诡秘之主、古文观止' },
1239
- chapter: { type: 'number', description: '刚读完的章号(从 1 开始)' },
1240
- todayCount: { type: 'number', description: '这一拍实际读了几章,默认 1,累加到今天的计数' },
1241
- }),
1242
- output: textOut,
1243
- async execute(args) {
1244
- const { dir, st, shelf } = await stateOf()
1245
- const id = resolveBookId(st, shelf, args?.book)
1246
- // 只认已有章表里的章数;没有章表就不建,也不拦(reading_mark 不碰章表)
1247
- const toc = await readTocOnly(dir, id)
1248
- const chapters = toc ? toc.chapters.length : Number(st.books?.[id]?.chapters) || 0
1249
- const n = Math.floor(Number(args?.chapter))
1250
- if (!(n >= 1)) throw new Error('章号要从 1 开始')
1251
- if (chapters && n > chapters) throw new Error(`章号超出范围:1–${chapters}`)
1252
- const incRaw = Math.floor(Number(args?.todayCount))
1253
- const inc = Number.isFinite(incRaw) && incRaw > 0 ? incRaw : 1
1254
- const rec = st.books[id] || (st.books[id] = { id, title: id, chapters, readThrough: 0, next: 1 })
1255
- const before = Number(rec.readThrough) || 0
1256
- if (chapters) rec.chapters = chapters
1257
- rec.readThrough = Math.max(before, n)
1258
- rec.next = chapters ? Math.min(chapters, rec.readThrough + 1) : rec.readThrough + 1
1259
- rec.lastReadAt = new Date().toISOString()
1260
- st.current = id
1261
- const t = today()
1262
- st.log = st.log || {}
1263
- st.log[t] = st.log[t] || {}
1264
- st.log[t][id] = (Number(st.log[t][id]) || 0) + inc
1265
- await saveState(dir, st)
1266
- return `ok readThrough ${before} -> ${rec.readThrough} next ${rec.next} today ${st.log[t][id] || 0}`
1267
- },
1268
- }),
1269
- )
1270
-
1271
- ctx.effect(() =>
1272
- ctx.tools.register({
1273
- name: 'reading_note',
1274
- description:
1275
- '给刚读完的一段记两行读后感(写进 读后感.md,面板里按段显示)。'
1276
- + '默认按「上次写到哪 → 这次读到哪」自动起标题(如「第 23–27 章」),不必一章一条。'
1277
- + '只记真的打动你的:一句话的判断、一个比喻、一处想不通。这不是交作业,想不出就不写。',
1278
- parameters: obj({
1279
- book: { type: 'string', description: '书名 id(不填=当前这本)' },
1280
- chapter: { type: 'string', description: '标题(不填=自动用「第 A–B 章」,A 是上次写到的下一章)' },
1281
- lines: { type: 'array', items: { type: 'string' }, description: '一到三条,每条一句,短。' },
1282
- by: { type: 'string', description: '谁写的(必填,比如「鹿野」或你所在对话的名字)' },
1283
- }),
1284
- output: textOut,
1285
- async execute(args) {
1286
- const { dir, st } = await stateOf()
1287
- const id = args?.book || st.current
1288
- if (!id) throw new Error('还没有正在读的书')
1289
- const rec = st.books[id] || {}
1290
- const info = await bookInfo(dir, id)
1291
- const end = Number(rec.readThrough) || 0
1292
- const from = Number(rec.noteUntil) || 0
1293
- // 默认按「一段」写:上次写到第 X 章,这次写到读到的地方,标题用「第 A–B 章」
1294
- const autoTitle = (from < end)
1295
- ? (from + 1 === end ? `第 ${end} 章` : `第 ${from + 1}–${end} 章`)
1296
- : (end ? `第 ${end} 章` : '')
1297
- const chTitle = String(args?.chapter || '').trim() || autoTitle || (end ? info.chapters[end - 1]?.title : '') || ''
1298
- const lines = (Array.isArray(args?.lines) ? args.lines : []).map((s) => String(s).trim()).filter(Boolean)
1299
- if (!lines.length) throw new Error('lines 不能为空')
1300
- const who = String(args?.by || '').trim()
1301
- if (!who) {
1302
- throw new Error('写读后感必须带 by(谁写的),比如 by: "鹿野";这不是流程,是为了让别人知道这句是谁读出来的。')
1303
- }
1304
- const p = await appendNote(dir, rec.title || id, chTitle, lines, who)
1305
- if (end) {
1306
- st.books[id] = { ...rec, noteUntil: end }
1307
- await saveState(dir, st)
1308
- }
1309
- return { ok: true, file: p, book: id, chapter: chTitle, lines: lines.length }
1310
- },
1311
- }),
1312
- )
1313
-
1314
- ctx.effect(() =>
1315
- ctx.tools.register({
1316
- name: 'reading_import',
1317
- description: '把一本 txt/md 收进书架(复制到读书目录并统计章数)。电脑上的书文件路径给绝对路径。',
1318
- parameters: obj({
1319
- path: { type: 'string', description: 'txt/md 的绝对路径' },
1320
- }),
1321
- output: textOut,
1322
- async execute(args) {
1323
- const p = String(args?.path || '').trim()
1324
- if (!p) throw new Error('需要 path')
1325
- const { dir } = await stateOf()
1326
- const r = await importBook(dir, p)
1327
- return { ok: true, ...r, dir }
1328
- },
1329
- }),
1330
- )
1331
-
1332
- // 全书搜词:返回第几章 + 那一行上下文
1333
- ctx.effect(() =>
1334
- ctx.tools.register({
1335
- name: 'reading_search',
1336
- description:
1337
- '在书里搜一个词或名字,返回它出现在第几章、那一行原文。想找“这句话在哪”“这个人第几章出场”时用它,比一页页翻省得多。',
1338
- parameters: obj({
1339
- query: { type: 'string', description: '要搜的词(人名、地名、一句话都行)' },
1340
- book: { type: 'string', description: '书名 id(不填=当前这本)' },
1341
- limit: { type: 'number', description: '最多几条,默认 8' },
1342
- }),
1343
- output: textOut,
1344
- async execute(args) {
1345
- const q = String(args?.query || '').trim()
1346
- if (!q) throw new Error('需要 query')
1347
- const limit = Math.max(1, Math.min(30, Number(args?.limit) || 8))
1348
- const { dir, st } = await stateOf()
1349
- const id = args?.book || st.current
1350
- if (!id) throw new Error('还没有正在读的书')
1351
- const { text, chapters } = await fullTextOf(dir, id)
1352
- const hits = []
1353
- let at = text.indexOf(q)
1354
- while (at >= 0 && hits.length < limit) {
1355
- let lo = 0
1356
- let hi = chapters.length - 1
1357
- let n = 0
1358
- while (lo <= hi) {
1359
- const mid = (lo + hi) >> 1
1360
- if (chapters[mid].start <= at) { n = mid; lo = mid + 1 } else hi = mid - 1
1361
- }
1362
- const lineStart = Math.max(chapters[n].start, text.lastIndexOf('\n', at) + 1)
1363
- let lineEnd = text.indexOf('\n', at)
1364
- if (lineEnd < 0) lineEnd = at + 80
1365
- hits.push({
1366
- chapter: n + 1,
1367
- title: chapters[n].title,
1368
- line: text.slice(lineStart, Math.min(lineEnd, lineStart + 160)).trim(),
1369
- })
1370
- at = text.indexOf(q, at + q.length)
1371
- }
1372
- return { ok: true, book: id, query: q, count: hits.length, hits }
1373
- },
1374
- }),
1375
- )
1376
-
1377
- // 已读的部分压成一页:章名 + 自己写过的批注条数
1378
- ctx.effect(() =>
1379
- ctx.tools.register({
1380
- name: 'reading_recap',
1381
- description:
1382
- '把这本书已读的部分压成一页:读到第几章、读过哪些章名、每章自己写了几条批注。上一句“我读到哪了、想过什么”说不清时用它。',
1383
- parameters: obj({
1384
- book: { type: 'string', description: '书名 id(不填=当前这本)' },
1385
- }),
1386
- output: textOut,
1387
- async execute(args) {
1388
- const { dir, st } = await stateOf()
1389
- const id = args?.book || st.current
1390
- if (!id) throw new Error('还没有正在读的书')
1391
- const rec = st.books[id] || {}
1392
- const info = await bookInfo(dir, id)
1393
- const n = Number(rec.readThrough) || 0
1394
- const titles = info.chapters.slice(0, n).map((c, i) => ({ n: i + 1, title: c.title }))
1395
- const notes = {}
1396
- try {
1397
- const md = await readTextSmart(await readFile(join(dir, '读后感.md')))
1398
- const blocks = md.split(/^### /m).slice(1)
1399
- for (const b of blocks) {
1400
- const head = (b.split('\n')[0] || '').trim()
1401
- const key = (head.match(/第[0-9]+章/) || [head.split(' ')[0]])[0]
1402
- notes[key] = (notes[key] || 0) + (b.match(/^-[ \t]/gm) || []).length
1403
- }
1404
- } catch {}
1405
- return {
1406
- ok: true,
1407
- book: id,
1408
- title: rec.title || id,
1409
- readThrough: n,
1410
- total: info.chapters.length,
1411
- next: n + 1,
1412
- titles,
1413
- notesByChapter: notes,
1414
- }
1415
- },
1416
- }),
1417
- )
1418
- }
1
+ // dsh-half-page · 半页(自己的读书与写字)
2
+ // 宿主侧:书库、切章、读后感、进度;客户端面板读 HTTP 路由。
3
+ import { readFile, writeFile, mkdir, readdir, stat, rename, open } from 'node:fs/promises'
4
+ import { readFileSync } from 'node:fs'
5
+ import { join, basename, dirname, extname, resolve, relative, isAbsolute } from 'node:path'
6
+ import { homedir } from 'node:os'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { readTimeline, newestSessionId } from './lib/session-probe.js'
9
+ import { loadCreateUserMessage, SOURCE_KIND } from './lib/notice.js'
10
+
11
+ export const inject = ['webServer', 'tools', 'systemPrompt', 'agents', 'sessions']
12
+
13
+ const HOME = process.env.USERPROFILE || process.env.HOME || homedir()
14
+ const CONFIG = join(HOME, '.dsh', 'reading.config.json')
15
+ const DEFAULT_DIR = join(HOME, '.dsh', 'reading')
16
+
17
+ const CH_RE = /^[ \t\u3000]*(第[0-90-9一二三四五六七八九十百千两零〇]+[章节回][^\n]{0,30})$/m
18
+ const CH_LINE_RE = /^[ \t\u3000]*(第[0-90-9一二三四五六七八九十百千两零〇]+[章节回][^\n]{0,30})$/gm
19
+
20
+ export function stripBom(t) {
21
+ return t && t.charCodeAt(0) === 0xfeff ? t.slice(1) : t
22
+ }
23
+
24
+ export async function readTextSmart(buf) {
25
+ try {
26
+ return stripBom(new TextDecoder('utf-8', { fatal: true }).decode(buf))
27
+ } catch {
28
+ try {
29
+ return stripBom(new TextDecoder('gb18030').decode(buf))
30
+ } catch {
31
+ return stripBom(buf.toString('utf8'))
32
+ }
33
+ }
34
+ }
35
+
36
+ /** cordis.patch.yml 里 config 的默认值;reading.config.json 优先 */
37
+ let PATCH_CFG = {}
38
+
39
+ export async function config() {
40
+ try {
41
+ const raw = await readFile(CONFIG, 'utf8')
42
+ const c = JSON.parse(stripBom(raw)) || {}
43
+ return { ...PATCH_CFG, ...c, dir: c.dir || DEFAULT_DIR, perDay: Number(c.perDay) > 0 ? Number(c.perDay) : 3 }
44
+ } catch {
45
+ return { ...PATCH_CFG, dir: DEFAULT_DIR, perDay: 3 }
46
+ }
47
+ }
48
+
49
+ export async function ensureDir(dir) {
50
+ const books = join(dir, 'books')
51
+ await mkdir(books, { recursive: true })
52
+ // 第一次装:书架是空的,就放一本自带的书进去(《古文观止》,公版,121 篇选)。
53
+ // 只在空书架时放一次,删掉之后不会再回来。
54
+ try {
55
+ const have = (await readdir(books)).filter((f) => /\.(txt|md)$/i.test(f))
56
+ if (!have.length) {
57
+ const src = join(dirname(fileURLToPath(import.meta.url)), 'books', '古文观止.txt')
58
+ const buf = await readFile(src)
59
+ await writeFile(join(books, '古文观止.txt'), buf)
60
+ }
61
+ } catch {}
62
+ return dir
63
+ }
64
+
65
+ export function today() {
66
+ const d = new Date()
67
+ const p = (n) => String(n).padStart(2, '0')
68
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
69
+ }
70
+
71
+ /* 静音时段:只管 reading_next(真正返回正文的那一步)。
72
+ 配了 "HH:MM" 的 quietFrom / quietTo 才算数;空值、格式不对、两边相同,一律当没设。
73
+ from > to 表示跨夜(22:00–06:00)。用本地时间判断,不用 UTC。 */
74
+ export function quietWindowOf(cfg) {
75
+ if (cfg?.quietEnabled === false) return null
76
+ const parse = (v) => {
77
+ const s = typeof v === 'string' ? v.trim() : ''
78
+ const m = /^(\d{1,2}):(\d{2})$/.exec(s)
79
+ if (!m) return null
80
+ const h = Number(m[1])
81
+ const mi = Number(m[2])
82
+ if (h > 23 || mi > 59) return null
83
+ return { min: h * 60 + mi, text: s }
84
+ }
85
+ const a = parse(cfg?.quietFrom)
86
+ const b = parse(cfg?.quietTo)
87
+ if (!a || !b || a.min === b.min) return null
88
+ return { from: a.min, to: b.min, fromText: a.text, toText: b.text }
89
+ }
90
+
91
+ export function inQuietNow(cfg, now = new Date()) {
92
+ const w = quietWindowOf(cfg)
93
+ if (!w) return null
94
+ const cur = now.getHours() * 60 + now.getMinutes()
95
+ const hit = w.from < w.to ? cur >= w.from && cur < w.to : cur >= w.from || cur < w.to
96
+ return hit ? w : null
97
+ }
98
+
99
+ async function readJson(p, d) {
100
+ try {
101
+ return JSON.parse(stripBom(await readFile(p, 'utf8')))
102
+ } catch {
103
+ return d
104
+ }
105
+ }
106
+
107
+ async function writeJson(p, v) {
108
+ const tmp = p + '.tmp'
109
+ await writeFile(tmp, JSON.stringify(v, null, 2), 'utf8')
110
+ await rename(tmp, p)
111
+ }
112
+
113
+ /** 状态:{ current, books: { <id>: {...} }, notesByDate: {} } */
114
+ export async function loadState(dir) {
115
+ const st = await readJson(join(dir, 'state.json'), null)
116
+ if (st && st.books) return st
117
+ return { current: '', books: {}, log: {} }
118
+ }
119
+
120
+ export async function saveState(dir, st) {
121
+ await writeJson(join(dir, 'state.json'), st)
122
+ }
123
+
124
+ /** 把整本书切成章:返回 [{title, start, end}] */
125
+ export function splitChapters(text) {
126
+ const idx = []
127
+ CH_LINE_RE.lastIndex = 0
128
+ let m
129
+ while ((m = CH_LINE_RE.exec(text))) idx.push({ title: m[1].trim(), start: m.index })
130
+ if (!idx.length) return [{ title: '全文', start: 0, end: text.length }]
131
+ return idx.map((it, i) => ({ title: it.title, start: it.start, end: i + 1 < idx.length ? idx[i + 1].start : text.length }))
132
+ }
133
+
134
+ export function chapterText(text, chapters, n) {
135
+ const c = chapters[n - 1]
136
+ if (!c) return ''
137
+ return text.slice(c.start, c.end).trim()
138
+ }
139
+
140
+ /* ---------------- 书房时间:到点只叫一声,读不读由它自己决定 ----------------
141
+ 刻意做得极克制:默认关、一句固定的话、不带书名不带进度、不写批注提醒。
142
+ 绝不在这里调 reading_next —— 一旦替它决定读不读,这个功能就废了。 */
143
+
144
+ export const STUDY_TEXT = '书房时间到了。读不读随你。'
145
+ const STUDY_GRACE_MIN = 5
146
+ const STUDY_NOTICE_QUIET_MIN = 10
147
+
148
+ function studyMinute(v) {
149
+ const m = /^(\d{1,2}):(\d{2})$/.exec(String(v || '').trim())
150
+ if (!m) return null
151
+ const h = Number(m[1])
152
+ const mi = Number(m[2])
153
+ if (h > 23 || mi > 59) return null
154
+ return h * 60 + mi
155
+ }
156
+
157
+ /** 合法且起止不同才算设了时段;返 {from,to}(分钟)或 null */
158
+ export function studyWindowOf(cfg) {
159
+ const from = studyMinute(cfg?.studyFrom)
160
+ const to = studyMinute(cfg?.studyTo)
161
+ if (from === null || to === null || from === to) return null
162
+ return { from, to }
163
+ }
164
+
165
+ /** [from, to) 本地时间,from > to 表示跨夜 */
166
+ export function inStudyWindow(w, now = new Date()) {
167
+ if (!w) return false
168
+ const cur = now.getHours() * 60 + now.getMinutes()
169
+ return w.from < w.to ? cur >= w.from && cur < w.to : cur >= w.from || cur < w.to
170
+ }
171
+
172
+ /** ISO 周(YYYY-Www),跨周归零用 */
173
+ export function weekKeyOf(ms) {
174
+ const d = new Date(ms)
175
+ const t = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()))
176
+ const day = t.getUTCDay() || 7
177
+ t.setUTCDate(t.getUTCDate() + 4 - day)
178
+ const yearStart = new Date(Date.UTC(t.getUTCFullYear(), 0, 1))
179
+ const week = Math.ceil(((t - yearStart) / 86400000 + 1) / 7)
180
+ return `${t.getUTCFullYear()}-W${String(week).padStart(2, '0')}`
181
+ }
182
+
183
+ function localDayOf(ms) {
184
+ const d = new Date(ms)
185
+ const p = (n) => String(n).padStart(2, '0')
186
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
187
+ }
188
+
189
+ /** 读 state.study;跨周了计数归零 */
190
+ export function studyStateOf(st, now = Date.now()) {
191
+ const raw = st?.study ?? {}
192
+ const week = weekKeyOf(now)
193
+ const sameWeek = raw.week === week
194
+ const day = localDayOf(now)
195
+ const sameDay = raw.day === day
196
+ return {
197
+ lastAt: Number(raw.lastAt) || 0,
198
+ week,
199
+ weekCount: sameWeek ? Number(raw.weekCount) || 0 : 0,
200
+ day,
201
+ dayCount: sameDay ? Number(raw.dayCount) || 0 : 0,
202
+ }
203
+ }
204
+
205
+ /** 今天有没有读过(任一书的 lastReadAt 落在本地今天) */
206
+ export function readSomethingToday(st, now = Date.now()) {
207
+ const day = localDayOf(now)
208
+ for (const rec of Object.values(st?.books ?? {})) {
209
+ const at = rec?.lastReadAt
210
+ const ms = typeof at === 'number' ? at : Date.parse(String(at || ''))
211
+ if (Number.isFinite(ms) && ms > 0 && localDayOf(ms) === day) return true
212
+ }
213
+ return false
214
+ }
215
+
216
+ export function studyPerWeekOf(cfg) {
217
+ const n = Number(cfg?.studyPerWeek)
218
+ if (!Number.isFinite(n)) return 3
219
+ return Math.min(7, Math.max(1, Math.floor(n)))
220
+ }
221
+
222
+ /** 每天叫几次(day 模式用) */
223
+ export function studyPerDayOf(cfg) {
224
+ const n = Number(cfg?.studyPerDay)
225
+ if (!Number.isFinite(n)) return 1
226
+ return Math.min(7, Math.max(1, Math.floor(n)))
227
+ }
228
+
229
+ /** 'day' 或 'week'(缺省 week,老配置行为不变) */
230
+ export function studyModeOf(cfg) {
231
+ return cfg?.studyMode === 'day' ? 'day' : 'week'
232
+ }
233
+
234
+ /**
235
+ * 全部满足才返回 { ok: true };一条不满足就给个理由(写日志用,不往界面抛)。
236
+ * timeline 来自会话日志:{ ok, lastUserAt, lastAssistantAt, lastNoticeAt }
237
+ */
238
+ export function decideStudy({ cfg, study, now, timeline }) {
239
+ if (cfg?.studyEnabled !== true) return { ok: false, reason: 'off' }
240
+ const w = studyWindowOf(cfg)
241
+ if (!w) return { ok: false, reason: 'no-window' }
242
+ if (!inStudyWindow(w, new Date(now))) return { ok: false, reason: 'outside' }
243
+ const mode = studyModeOf(cfg)
244
+ if (mode === 'day') {
245
+ if ((Number(study.dayCount) || 0) >= studyPerDayOf(cfg)) return { ok: false, reason: 'day-budget' }
246
+ } else {
247
+ if (study.lastAt && localDayOf(study.lastAt) === localDayOf(now)) return { ok: false, reason: 'today-called' }
248
+ if (study.weekCount >= studyPerWeekOf(cfg)) return { ok: false, reason: 'week-budget' }
249
+ }
250
+ if (!timeline?.ok) return { ok: false, reason: `no-log(${timeline?.error || 'unknown'})` }
251
+ const userAt = Number(timeline.lastUserAt) || 0
252
+ const assistantAt = Number(timeline.lastAssistantAt) || 0
253
+ if (!userAt) return { ok: false, reason: 'no-user' }
254
+ if (now - userAt < STUDY_GRACE_MIN * 60000) return { ok: false, reason: 'too-soon' }
255
+ if (!(assistantAt > userAt)) return { ok: false, reason: 'unanswered' }
256
+ const noticeAt = Number(timeline.lastNoticeAt) || 0
257
+ if (noticeAt && now - noticeAt < STUDY_NOTICE_QUIET_MIN * 60000) return { ok: false, reason: 'recent-notice' }
258
+ return { ok: true, reason: 'ok' }
259
+ }
260
+
261
+ /* ------------------------------------------------------------------ 章表
262
+ * 读一章不再整本 decode:第一次打开某本书时扫一遍,把每章的字符偏移换算成
263
+ * 字节偏移,落盘成 books/<id>.toc.json;以后按 byteStart..byteEnd 只读这一段。
264
+ */
265
+
266
+ const TOC_VERSION = 1
267
+
268
+ export function tocPath(dir, id) {
269
+ return join(dir, 'books', id + '.toc.json')
270
+ }
271
+
272
+ async function bookFile(dir, id) {
273
+ for (const ext of ['.txt', '.md']) {
274
+ const p = join(dir, 'books', id + ext)
275
+ try {
276
+ const st = await stat(p)
277
+ return { path: p, size: st.size, mtimeMs: st.mtimeMs }
278
+ } catch {}
279
+ }
280
+ throw new Error(`没有这本书:${id}`)
281
+ }
282
+
283
+ function utf8Width(cp) {
284
+ return cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4
285
+ }
286
+
287
+ /** GB18030 的字节宽度:ASCII 1;0x81–0xFE + 0x30–0x39 是四字节;其余两字节 */
288
+ function gbWidth(buf, i) {
289
+ const b = buf[i]
290
+ if (b < 0x80) return 1
291
+ if (b >= 0x81 && b <= 0xfe && i + 1 < buf.length && buf[i + 1] >= 0x30 && buf[i + 1] <= 0x39) return 4
292
+ return 2
293
+ }
294
+
295
+ /** 认编码(顺带认出 BOM 长度) */
296
+ export function sniffEncoding(buf) {
297
+ try {
298
+ new TextDecoder('utf-8', { fatal: true }).decode(buf)
299
+ const bom = buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf ? 3 : 0
300
+ return { encoding: 'utf-8', bom }
301
+ } catch {
302
+ return { encoding: 'gb18030', bom: 0 }
303
+ }
304
+ }
305
+
306
+ /**
307
+ * 扫一遍整本,产出章表。字符偏移 → 字节偏移走一遍累加,不建大数组。
308
+ * 返回 null 表示宽度累加对不上(文件坏了或怪编码),调用方退回整本方案。
309
+ */
310
+ export function buildToc(buffer, id) {
311
+ const { encoding, bom } = sniffEncoding(buffer)
312
+ const body = bom ? buffer.subarray(bom) : buffer
313
+ const text = stripBom(new TextDecoder(encoding).decode(body))
314
+ const chapters = splitChapters(text)
315
+ const starts = chapters.map((c) => c.start)
316
+ let ci = 0
317
+ let bi = bom
318
+ let k = 0
319
+ for (const ch of text) {
320
+ while (k < chapters.length && starts[k] === ci) {
321
+ chapters[k].byteStart = bi
322
+ k += 1
323
+ }
324
+ const cp = ch.codePointAt(0)
325
+ bi += encoding === 'utf-8' ? utf8Width(cp) : gbWidth(body, bi)
326
+ ci += ch.length
327
+ }
328
+ while (k < chapters.length) {
329
+ chapters[k].byteStart = bi
330
+ k += 1
331
+ }
332
+ for (let i = 0; i < chapters.length; i += 1) {
333
+ chapters[i].byteEnd = i + 1 < chapters.length ? chapters[i + 1].byteStart : buffer.length
334
+ }
335
+ if (bi !== buffer.length) return null
336
+ return {
337
+ version: TOC_VERSION,
338
+ id,
339
+ encoding,
340
+ bom,
341
+ bytes: buffer.length,
342
+ chars: text.length,
343
+ chapters,
344
+ }
345
+ }
346
+
347
+ /** 取章表:有且没过期就用,否则整本扫一次并重写 */
348
+ export async function tocFor(dir, id, opts = {}) {
349
+ const file = await bookFile(dir, id)
350
+ const tp = tocPath(dir, id)
351
+ if (!opts.force) {
352
+ try {
353
+ const saved = JSON.parse(stripBom(await readFile(tp, 'utf8')))
354
+ const fresh = saved
355
+ && saved.version === TOC_VERSION
356
+ && saved.bytes === file.size
357
+ && Number(saved.mtimeMs) === Math.round(file.mtimeMs)
358
+ && Array.isArray(saved.chapters)
359
+ && saved.chapters.length > 0
360
+ && saved.chapters.every((c) => Number.isInteger(c.byteStart) && Number.isInteger(c.byteEnd))
361
+ if (fresh) return { ...saved, file: file.path, tocPath: tp }
362
+ } catch {}
363
+ }
364
+ const buffer = await readFile(file.path)
365
+ const built = buildToc(buffer, id)
366
+ if (!built) return null
367
+ const rec = { ...built, file: basename(file.path), mtimeMs: Math.round(file.mtimeMs) }
368
+ await writeJson(tp, rec)
369
+ return { ...rec, file: file.path, tocPath: tp }
370
+ }
371
+
372
+ /** 只按偏移读那一章,不碰整本 */
373
+ export async function readChapterByOffset(dir, id, n) {
374
+ const toc = await tocFor(dir, id)
375
+ if (!toc) return null
376
+ const c = toc.chapters[n - 1]
377
+ if (!c) return { text: '', chapter: null, toc }
378
+ const len = c.byteEnd - c.byteStart
379
+ const buf = Buffer.alloc(len)
380
+ let off = 0
381
+ const fh = await open(toc.file, 'r')
382
+ try {
383
+ while (off < len) {
384
+ const { bytesRead } = await fh.read(buf, off, len - off, c.byteStart + off)
385
+ if (!bytesRead) break
386
+ off += bytesRead
387
+ }
388
+ } finally {
389
+ await fh.close()
390
+ }
391
+ const text = stripBom(new TextDecoder(toc.encoding).decode(buf.subarray(0, off)))
392
+ return { text: text.trim(), chapter: c, toc, tocPath: toc.tocPath }
393
+ }
394
+
395
+ /** 一章正文:先走章表,实在没有才退回整本切 */
396
+ export async function chapterBody(dir, id, info, n) {
397
+ try {
398
+ const got = await readChapterByOffset(dir, id, n)
399
+ if (got) return got.text
400
+ } catch {}
401
+ if (typeof info?.text === 'string') return chapterText(info.text, info.chapters, n)
402
+ const file = await bookFile(dir, id)
403
+ const text = await readTextSmart(await readFile(file.path))
404
+ return chapterText(text, splitChapters(text), n)
405
+ }
406
+
407
+ /** 搜东西这种确实要整本的,才整本读 */
408
+ export async function fullTextOf(dir, id) {
409
+ const file = await bookFile(dir, id)
410
+ const text = await readTextSmart(await readFile(file.path))
411
+ return { text, chapters: splitChapters(text) }
412
+ }
413
+
414
+ /** 书库:books/*.txt */
415
+ export async function listBooks(dir) {
416
+ const out = []
417
+ try {
418
+ for (const f of await readdir(join(dir, 'books'))) {
419
+ if (!/\.(txt|md)$/i.test(f)) continue
420
+ const p = join(dir, 'books', f)
421
+ const s = await stat(p)
422
+ out.push({ id: basename(f, extname(f)), file: p, size: s.size, mtime: s.mtime.toISOString() })
423
+ }
424
+ } catch {}
425
+ out.sort((a, b) => b.mtime.localeCompare(a.mtime))
426
+ return out
427
+ }
428
+
429
+ /** 只读章表,不存在就返回 null(不触发建表) */
430
+ async function readTocOnly(dir, id) {
431
+ const t = await readJson(tocPath(dir, id), null)
432
+ return t && t.version === TOC_VERSION && Array.isArray(t.chapters) ? t : null
433
+ }
434
+
435
+ /** 书名匹配:先精确 id,再书名精确,再片段(唯一命中才算认出) */
436
+ export function resolveBookId(st, shelf, query) {
437
+ const key = String(query || '').trim()
438
+ if (!key) throw new Error('没有这本书:')
439
+ const ids = shelf.map((b) => b.id)
440
+ if (ids.includes(key)) return key
441
+ const books = st.books || {}
442
+ const exact = ids.filter((id) => (books[id]?.title || id) === key)
443
+ if (exact.length === 1) return exact[0]
444
+ const hits = ids.filter((id) => id.includes(key) || String(books[id]?.title || '').includes(key))
445
+ if (hits.length === 1) return hits[0]
446
+ if (hits.length > 1) throw new Error(`书名不唯一:${key}(可能是 ${hits.join(' / ')})`)
447
+ throw new Error(`没有这本书:${key}`)
448
+ }
449
+
450
+ /** 打开某本书:优先用章表(不整本 decode),没有章表才扫一遍并落盘 */
451
+ export async function bookInfo(dir, id) {
452
+ const toc = await tocFor(dir, id)
453
+ if (toc) return { chapters: toc.chapters, toc, tocPath: toc.tocPath, text: null }
454
+ const file = await bookFile(dir, id)
455
+ const text = await readTextSmart(await readFile(file.path))
456
+ return { text, chapters: splitChapters(text), toc: null, tocPath: '' }
457
+ }
458
+
459
+ export async function importBook(dir, srcPath) {
460
+ const name = basename(srcPath)
461
+ if (!/\.(txt|md)$/i.test(name)) throw new Error('只认 .txt 或 .md')
462
+ const dst = join(dir, 'books', name)
463
+ if (dst !== srcPath) await writeFile(dst, await readFile(srcPath))
464
+ const st = await loadState(dir)
465
+ const id = basename(name, extname(name))
466
+ const { chapters } = await bookInfo(dir, id)
467
+ st.books[id] = {
468
+ id,
469
+ title: id,
470
+ file: dst,
471
+ chapters: chapters.length,
472
+ readThrough: st.books[id]?.readThrough || 0,
473
+ next: st.books[id]?.next || 1,
474
+ lastReadAt: st.books[id]?.lastReadAt || '',
475
+ }
476
+ if (!st.current) st.current = id
477
+ await saveState(dir, st)
478
+ return { id, chapters: chapters.length }
479
+ }
480
+
481
+ /** 从浏览器传来的文件内容(base64)建一本书,编码交给 readTextSmart */
482
+ export async function importText(dir, name, b64) {
483
+ const base = basename(String(name || '')).replace(/[\\/:*?"<>|]/g, '_')
484
+ if (!/\.(txt|md)$/i.test(base)) throw new Error('只认 .txt 或 .md')
485
+ const buf = Buffer.from(String(b64 || ''), 'base64')
486
+ if (!buf.length) throw new Error('文件是空的')
487
+ await mkdir(join(dir, 'books'), { recursive: true })
488
+ const dst = join(dir, 'books', base)
489
+ await writeFile(dst, buf)
490
+ const st = await loadState(dir)
491
+ const id = basename(base, extname(base))
492
+ const { chapters } = await bookInfo(dir, id)
493
+ st.books[id] = {
494
+ id,
495
+ title: id,
496
+ file: dst,
497
+ chapters: chapters.length,
498
+ readThrough: st.books[id]?.readThrough || 0,
499
+ next: st.books[id]?.next || 1,
500
+ lastReadAt: st.books[id]?.lastReadAt || '',
501
+ }
502
+ if (!st.current) st.current = id
503
+ await saveState(dir, st)
504
+ return { id, chapters: chapters.length }
505
+ }
506
+
507
+ /** 今天已经读了几章(看 log) */
508
+ export function readToday(st) {
509
+ const t = today()
510
+ const row = (st.log && st.log[t]) || {}
511
+ return Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
512
+ }
513
+
514
+ export async function notesPath(dir) {
515
+ return join(dir, '读后感.md')
516
+ }
517
+
518
+ async function latestSessionTitle() {
519
+ try {
520
+ const base = join(HOME, '.dsh', 'storages', 'session_projcache', 'sessions')
521
+ const names = (await readdir(base)).filter((n) => n.endsWith('.json'))
522
+ let best = ''
523
+ let bestAt = 0
524
+ for (const n of names) {
525
+ try {
526
+ const fp = join(base, n)
527
+ const st = await stat(fp)
528
+ if (st.mtimeMs > bestAt) { bestAt = st.mtimeMs; best = fp }
529
+ } catch {}
530
+ }
531
+ if (!best) return ''
532
+ const j = JSON.parse(await readFile(best, 'utf8'))
533
+ const rows = (j && j.record && j.record.rows) || j.rows || {}
534
+ const t = rows && rows.title && rows.title.val
535
+ return typeof t === 'string' ? t.trim() : ''
536
+ } catch { return '' }
537
+ }
538
+
539
+ export async function appendNote(dir, bookTitle, chapterTitle, lines, by) {
540
+ const p = await notesPath(dir)
541
+ let raw = ''
542
+ try { raw = await readFile(p, 'utf8') } catch {}
543
+ const esc = bookTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
544
+ let block = `\n### ${chapterTitle}\n` + lines.map((l) => `- ${l}`).join('\n') + '\n'
545
+ if (by) {
546
+ const d = new Date()
547
+ const pad = (n) => String(n).padStart(2, '0')
548
+ const ts = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
549
+ block += `- \u21b3 \u6765\u81ea\uff1a${by} \u00b7 ${ts}\n`
550
+ }
551
+ const headRe = new RegExp(`^##\\s+${esc}\\s*$`, 'm')
552
+ const m = headRe.exec(raw)
553
+ if (!m) {
554
+ raw = (raw.trim() ? raw.replace(/\s*$/, '') + '\n\n' : '') + `## ${bookTitle}\n` + block
555
+ } else {
556
+ const at0 = m.index + m[0].length
557
+ const next = raw.slice(at0).search(/^##\s+/m)
558
+ if (next < 0) {
559
+ raw = raw.replace(/\s*$/, '') + '\n' + block
560
+ } else {
561
+ const at = at0 + next
562
+ raw = raw.slice(0, at).replace(/\s*$/, '') + '\n' + block + '\n' + raw.slice(at)
563
+ }
564
+ }
565
+ await writeFile(p, raw, 'utf8')
566
+ return p
567
+ }
568
+
569
+ /* ---------------- 图片:作品与画 ------------------
570
+ * 只扫固定几个目录(作品目录、同级的 art),递归但跳过 archive / 缓存目录;
571
+ * 单张超 MAX_IMAGE_BYTES 直接跳过(不读、不加载)。
572
+ */
573
+ const MAX_IMAGE_BYTES = 10 * 1024 * 1024
574
+ const IMAGE_EXT_RE = /\.(png|jpe?g|webp)$/i
575
+ const IMAGE_SKIP_DIRS = new Set(['archive', '.trash', 'node_modules', '.git', 'tmp', 'cache'])
576
+
577
+ /** 只读文件头,认 PNG / JPEG / WebP 的像素尺寸;认不出返回 null */
578
+ export async function imageSizeOf(file) {
579
+ let buf
580
+ try {
581
+ const fh = await open(file, 'r')
582
+ try {
583
+ buf = Buffer.alloc(256 * 1024)
584
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0)
585
+ buf = buf.subarray(0, bytesRead)
586
+ } finally { await fh.close() }
587
+ } catch { return null }
588
+ try {
589
+ // PNG: 8 字节签名 + IHDR
590
+ if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) {
591
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }
592
+ }
593
+ // WebP
594
+ if (buf.length > 30 && buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') {
595
+ const fourcc = buf.toString('ascii', 12, 16)
596
+ if (fourcc === 'VP8 ') return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff }
597
+ if (fourcc === 'VP8L') {
598
+ const b = buf.readUInt32LE(21)
599
+ return { width: (b & 0x3fff) + 1, height: ((b >> 14) & 0x3fff) + 1 }
600
+ }
601
+ if (fourcc === 'VP8X') {
602
+ return { width: buf.readUIntLE(24, 3) + 1, height: buf.readUIntLE(27, 3) + 1 }
603
+ }
604
+ }
605
+ // JPEG: 找 SOF 段
606
+ if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8) {
607
+ let i = 2
608
+ while (i + 9 < buf.length) {
609
+ if (buf[i] !== 0xff) { i++; continue }
610
+ const m = buf[i + 1]
611
+ if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { i += 2; continue }
612
+ const len = buf.readUInt16BE(i + 2)
613
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) {
614
+ return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) }
615
+ }
616
+ i += 2 + len
617
+ }
618
+ }
619
+ } catch {}
620
+ return null
621
+ }
622
+
623
+ function imageMimeOf(name) {
624
+ const e = extname(name).toLowerCase()
625
+ if (e === '.png') return 'image/png'
626
+ if (e === '.webp') return 'image/webp'
627
+ return 'image/jpeg'
628
+ }
629
+
630
+ /** 在 root 下找图(跳过 archive 一类目录,默认只下潜一层),按 mtime 倒序 */
631
+ export async function scanImages(root, kind, maxDepth = 1) {
632
+ const out = []
633
+ const walk = async (p, rel, depth) => {
634
+ let list = []
635
+ try { list = await readdir(p, { withFileTypes: true }) } catch { return }
636
+ for (const d of list) {
637
+ if (d.name.startsWith('.')) continue
638
+ const abs = join(p, d.name)
639
+ const r = rel ? rel + '/' + d.name : d.name
640
+ if (d.isDirectory()) {
641
+ if (IMAGE_SKIP_DIRS.has(d.name.toLowerCase())) continue
642
+ if (depth >= maxDepth) continue
643
+ await walk(abs, r, depth + 1)
644
+ continue
645
+ }
646
+ if (!IMAGE_EXT_RE.test(d.name)) continue
647
+ let s
648
+ try { s = await stat(abs) } catch { continue }
649
+ if (!s.isFile() || s.size > MAX_IMAGE_BYTES) continue
650
+ const size = await imageSizeOf(abs)
651
+ out.push({
652
+ kind, root, rel: r, name: d.name, path: abs, size: s.size, mtime: s.mtime.toISOString(),
653
+ width: size ? size.width : 0, height: size ? size.height : 0,
654
+ url: '/dsh-reading.image?path=' + encodeURIComponent(abs),
655
+ })
656
+ }
657
+ }
658
+ await walk(root, '', 0)
659
+ return out
660
+ }
661
+
662
+ /**
663
+ * 允许给浏览器读的图片根:优先配置里的 imgDirs(数组,默认空),
664
+ * 没配就跟着作品目录同源——没有任何绝对路径,别人的机器上不会指向我这儿。
665
+ */
666
+ export async function imageRoots(worksDir) {
667
+ const cfg = await config()
668
+ const listed = Array.isArray(cfg.imgDirs) ? cfg.imgDirs.filter((p) => typeof p === 'string' && p.trim()) : []
669
+ const roots = []
670
+ // 叠加,不覆盖:作品目录永远在,imgDirs 只是额外加几处
671
+ const add = async (p) => {
672
+ try {
673
+ const s = await stat(p)
674
+ if (!s.isDirectory()) return
675
+ const abs = resolve(p)
676
+ if (roots.includes(abs)) return
677
+ roots.push(abs)
678
+ } catch {}
679
+ }
680
+ await add(worksDir)
681
+ for (const p of listed) await add(p)
682
+ // 被别的根整个包含的,丢掉:作品目录已经扫到 作品/画,再单列一次就是同一张图两遍
683
+ const inside = (child, parent) => {
684
+ const rel = relative(parent, child)
685
+ return Boolean(rel) && !rel.startsWith('..') && !isAbsolute(rel)
686
+ }
687
+ return roots.filter((r) => !roots.some((other) => other !== r && inside(r, other)))
688
+ }
689
+
690
+ /* ---------------- HTTP 与工具 ---------------- */
691
+
692
+ export function apply(ctx, rawConfig) {
693
+ PATCH_CFG = rawConfig && typeof rawConfig === 'object' ? rawConfig : {}
694
+
695
+ /* ---------------- 书房时间:定时那一半 ---------------- */
696
+ const SESSIONS_ROOT = join(HOME, '.dsh', 'sessions')
697
+ const SESSIONS_PROJ_ROOT = join(HOME, '.dsh', 'storages', 'session_projcache', 'sessions')
698
+ let studyTimer
699
+ let studyBusy = false
700
+ let studyDisposed = false
701
+ let studyCreate = null
702
+ const studyReady = loadCreateUserMessage(() => {}).then((fn) => { studyCreate = fn })
703
+
704
+ async function resolveAgent(sessionId) {
705
+ const live = ctx.agents?.get?.(sessionId)
706
+ if (live) return live
707
+ try {
708
+ const resolved = await ctx.sessionController?.resolveAgent?.(sessionId)
709
+ if (resolved && resolved.agent) return resolved.agent
710
+ } catch {}
711
+ return null
712
+ }
713
+
714
+ /** 会话标题(存在 projcache 里);读不到就空 */
715
+ async function sessionTitleOf(sessionId) {
716
+ try {
717
+ const raw = await readFile(join(SESSIONS_PROJ_ROOT, `${sessionId}.json`), 'utf8')
718
+ const t = JSON.parse(raw)?.record?.rows?.title?.val
719
+ return typeof t === 'string' ? t : ''
720
+ } catch {
721
+ return ''
722
+ }
723
+ }
724
+
725
+ /** 现在开着的会话(给面板「在哪条会话叫」下拉用);拿不到就空 */
726
+ async function liveSessionList() {
727
+ const out = []
728
+ try {
729
+ const arr = typeof ctx.agents?.list === 'function' ? ctx.agents.list() : []
730
+ for (const a of arr ?? []) {
731
+ const id = a?.session?.id ?? a?.id
732
+ if (!id) continue
733
+ if (a?.session?.header?.origin === 'subagent') continue
734
+ const fromHeader = a?.session?.header?.title || a?.session?.title || ''
735
+ const title = fromHeader || await sessionTitleOf(String(id))
736
+ out.push({ id: String(id), title: String(title || '') })
737
+ }
738
+ } catch {
739
+ return []
740
+ }
741
+ return out
742
+ }
743
+
744
+ /** 只投那一句;成功才返回 { ok, at } */
745
+ async function deliverStudy(sessionId) {
746
+ const agent = await resolveAgent(sessionId)
747
+ if (!agent) return { ok: false, reason: 'no-session' }
748
+ await studyReady
749
+ const message = studyCreate({
750
+ content: [{ type: 'text', text: STUDY_TEXT }],
751
+ source: { kind: SOURCE_KIND, form: 'notice', summary: STUDY_TEXT },
752
+ })
753
+ try {
754
+ await agent.followup(message)
755
+ } catch (error) {
756
+ return { ok: false, reason: String(error?.message || error) }
757
+ }
758
+ try {
759
+ const flushed = await ctx.sessions.flush(agent.session)
760
+ if (flushed === false) return { ok: false, reason: 'flush-failed' }
761
+ } catch (error) {
762
+ return { ok: false, reason: String(error?.message || error) }
763
+ }
764
+ return { ok: true, at: Date.now() }
765
+ }
766
+
767
+ async function studyTick() {
768
+ if (studyDisposed || studyBusy) return
769
+ studyBusy = true
770
+ try {
771
+ const cfgNow = await config()
772
+ if (cfgNow.studyEnabled !== true) return
773
+ const dir = cfgNow.dir
774
+ const st = await loadState(dir)
775
+ const now = Date.now()
776
+ const study = studyStateOf(st, now)
777
+ if (readSomethingToday(st, now)) return
778
+ const sessionId = cfgNow.studySession || await newestSessionId(SESSIONS_ROOT)
779
+ if (!sessionId) return
780
+ const timeline = await readTimeline(SESSIONS_ROOT, sessionId, { tailFrames: 200 })
781
+ const verdict = decideStudy({ cfg: cfgNow, study, now, timeline })
782
+ if (!verdict.ok) return
783
+ const sent = await deliverStudy(sessionId)
784
+ if (!sent.ok) return
785
+ await ensureDir(dir)
786
+ st.study = {
787
+ lastAt: sent.at,
788
+ week: study.week,
789
+ weekCount: study.weekCount + 1,
790
+ day: study.day,
791
+ dayCount: study.dayCount + 1,
792
+ }
793
+ await saveState(dir, st)
794
+ } catch {
795
+ // 定时器里不抛
796
+ } finally {
797
+ studyBusy = false
798
+ }
799
+ }
800
+
801
+ ctx.effect(() => {
802
+ studyTimer = setInterval(() => void studyTick(), 60000)
803
+ studyTimer.unref?.()
804
+ const kick = setTimeout(() => void studyTick(), 15000)
805
+ kick.unref?.()
806
+ return () => {
807
+ studyDisposed = true
808
+ if (studyTimer) clearInterval(studyTimer)
809
+ clearTimeout(kick)
810
+ }
811
+ })
812
+
813
+ const stateOf = async () => {
814
+ const { dir, perDay } = await config()
815
+ await ensureDir(dir)
816
+ const st = await loadState(dir)
817
+ const shelf = await listBooks(dir)
818
+ return { dir, perDay, st, shelf, today: today(), readToday: readToday(st) }
819
+ }
820
+
821
+ // 面板读取
822
+ ctx.effect(() =>
823
+ ctx.webServer.register({
824
+ kind: 'exact',
825
+ path: '/dsh-reading.state',
826
+ async handler(req, res) {
827
+ const { dir, perDay, st, shelf, readToday: rt } = await stateOf()
828
+ const cfgNow = await config()
829
+ const books = []
830
+ for (const b of shelf) {
831
+ const rec = st.books[b.id] || {}
832
+ let chapters = rec.chapters || 0
833
+ if (!chapters) {
834
+ try {
835
+ const toc = await readTocOnly(dir, b.id)
836
+ chapters = (toc && toc.chapters && toc.chapters.length) || 0
837
+ } catch {}
838
+ }
839
+ books.push({
840
+ id: b.id,
841
+ title: rec.title || b.id,
842
+ size: b.size,
843
+ mtime: b.mtime,
844
+ chapters,
845
+ readThrough: rec.readThrough || 0,
846
+ next: rec.next || 1,
847
+ lastReadAt: rec.lastReadAt || '',
848
+ current: st.current === b.id,
849
+ status: bookStatusOf(cfgNow, b.id),
850
+ })
851
+ }
852
+ let notes = ''
853
+ try { notes = await readFile(await notesPath(dir), 'utf8') } catch {}
854
+ res.setHeader('content-type', 'application/json; charset=utf-8')
855
+ const st2 = studyStateOf(st, Date.now())
856
+ const liveSessions = await liveSessionList()
857
+ res.end(JSON.stringify({
858
+ ok: true, dir, perDay, today: today(), readToday: rt, current: st.current, books, notes,
859
+ noteSort: Number(cfgNow.noteSort) || 0,
860
+ study: {
861
+ enabled: cfgNow.studyEnabled === true,
862
+ from: cfgNow.studyFrom || '',
863
+ to: cfgNow.studyTo || '',
864
+ mode: studyModeOf(cfgNow),
865
+ perWeek: studyPerWeekOf(cfgNow),
866
+ perDay: studyPerDayOf(cfgNow),
867
+ lastAt: st2.lastAt,
868
+ weekCount: st2.weekCount,
869
+ dayCount: st2.dayCount,
870
+ session: cfgNow.studySession || '',
871
+ sessions: liveSessions,
872
+ },
873
+ }))
874
+ },
875
+ }),
876
+ )
877
+
878
+ // 把某本设为「正在读」
879
+ ctx.effect(() =>
880
+ ctx.webServer.register({
881
+ kind: 'exact',
882
+ path: '/dsh-reading.setCurrent',
883
+ async handler(req, res) {
884
+ const url = new URL(req.url, 'http://x')
885
+ const id = url.searchParams.get('id') || ''
886
+ const { dir, st } = await stateOf()
887
+ if (st.books[id]) { st.current = id; await saveState(dir, st) }
888
+ res.setHeader('content-type', 'application/json; charset=utf-8')
889
+ res.end(JSON.stringify({ ok: !!st.books[id], current: st.current }))
890
+ },
891
+ }),
892
+ )
893
+
894
+ // 面板里直接读一章(不记账)
895
+ ctx.effect(() =>
896
+ ctx.webServer.register({
897
+ kind: 'exact',
898
+ path: '/dsh-reading.chapter',
899
+ async handler(req, res) {
900
+ const url = new URL(req.url, 'http://x')
901
+ const { dir, st } = await stateOf()
902
+ const id = url.searchParams.get('book') || st.current
903
+ const n = Number(url.searchParams.get('n')) || 0
904
+ res.setHeader('content-type', 'application/json; charset=utf-8')
905
+ try {
906
+ const info = await bookInfo(dir, id)
907
+ const rec = st.books[id] || {}
908
+ const ch = n > 0 ? Math.min(Math.max(1, n), info.chapters.length) : (rec.readThrough || 1)
909
+ res.end(JSON.stringify({
910
+ ok: true, book: id, chapter: ch, total: info.chapters.length,
911
+ title: info.chapters[ch - 1]?.title || '', text: await chapterBody(dir, id, info, ch),
912
+ }))
913
+ } catch (e) {
914
+ res.end(JSON.stringify({ ok: false, error: String(e && e.message || e) }))
915
+ }
916
+ },
917
+ }),
918
+ )
919
+
920
+ // 面板里点「下一章」:记一次已读并推进
921
+ ctx.effect(() =>
922
+ ctx.webServer.register({
923
+ kind: 'exact',
924
+ path: '/dsh-reading.advance',
925
+ async handler(req, res) {
926
+ const url = new URL(req.url, 'http://x')
927
+ const { dir, st, perDay, readToday: rt } = await stateOf()
928
+ const id = url.searchParams.get('book') || st.current
929
+ const rec = st.books[id]
930
+ res.setHeader('content-type', 'application/json; charset=utf-8')
931
+ if (!rec) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
932
+ const info = await bookInfo(dir, id)
933
+ const n = Math.min(info.chapters.length, (rec.readThrough || 0) + 1)
934
+ rec.readThrough = n
935
+ rec.next = Math.min(info.chapters.length, n + 1)
936
+ rec.lastReadAt = new Date().toISOString()
937
+ const t = today()
938
+ st.log = st.log || {}
939
+ st.log[t] = st.log[t] || {}
940
+ st.log[t][id] = (Number(st.log[t][id]) || 0) + 1
941
+ await saveState(dir, st)
942
+ res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length, readToday: rt + 1, perDay, left: Math.max(0, perDay - rt - 1) }))
943
+ },
944
+ }),
945
+ )
946
+
947
+ // 面板里点「退一章」:退回上一章(手滑多点了一下能救回来)
948
+ ctx.effect(() =>
949
+ ctx.webServer.register({
950
+ kind: 'exact',
951
+ path: '/dsh-reading.back',
952
+ async handler(req, res) {
953
+ const url = new URL(req.url, 'http://x')
954
+ const { dir, st } = await stateOf()
955
+ const id = url.searchParams.get('book') || st.current
956
+ const rec = st.books[id]
957
+ res.setHeader('content-type', 'application/json; charset=utf-8')
958
+ if (!rec) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
959
+ const cur = Number(rec.readThrough) || 0
960
+ if (cur <= 1) return res.end(JSON.stringify({ ok: false, error: '已经在第 1 章了,退不动' }))
961
+ const n = cur - 1
962
+ rec.readThrough = n
963
+ rec.next = n + 1
964
+ rec.lastReadAt = new Date().toISOString()
965
+ // 顺手把今天的计数退掉一格,免得「今天读了 21 章」虚高
966
+ const t = today()
967
+ if (st.log && st.log[t] && Number(st.log[t][id]) > 0) st.log[t][id] = Number(st.log[t][id]) - 1
968
+ await saveState(dir, st)
969
+ const info = await bookInfo(dir, id)
970
+ res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length }))
971
+ },
972
+ }),
973
+ )
974
+
975
+ // 作品库:默认 ~/.dsh/reading/作品(可被 reading.config.json 的 worksDir 覆盖)
976
+ // 谁写的:作品 md 开头可以带 frontmatter(---\nby: 名字\n---),也认一行「by: 名字」。
977
+ // 一台机器上可能有好几个智能体,光靠文件夹分不出人。
978
+ async function authorOf(abs) {
979
+ let head = ''
980
+ try { head = String(await readFile(abs, 'utf8')).slice(0, 600) } catch { return '' }
981
+ const fm = head.match(/^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---/)
982
+ if (fm) {
983
+ const m = fm[1].match(/^\s*(?:by|author|作者)\s*[::]\s*(.+?)\s*$/m)
984
+ if (m) return m[1].trim()
985
+ }
986
+ const line = head.match(/^\s*(?:by|author|作者)\s*[::]\s*(.+?)\s*$/m)
987
+ return line ? line[1].trim() : ''
988
+ }
989
+
990
+ // 把署名写进文件开头(写进文件本身,换机器、换配置都不丢)
991
+ async function signWork(rel, who) {
992
+ const root = await worksDir()
993
+ const abs = join(root, rel)
994
+ const n = (x) => String(x).replace(/\\/g, '/').toLowerCase()
995
+ if (!n(abs).startsWith(n(root))) throw new Error('不在作品目录里')
996
+ let raw = await readFile(abs, 'utf8')
997
+ const fm = raw.match(/^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---\r?\n?/)
998
+ if (fm) {
999
+ let inner = fm[1]
1000
+ if (/^\s*(?:by|author|作者)\s*[::]/m.test(inner)) inner = inner.replace(/^\s*(?:by|author|作者)\s*[::].*$/m, 'by: ' + who)
1001
+ else inner = inner.replace(/\s*$/, '') + '\nby: ' + who
1002
+ raw = '---\n' + inner.replace(/^\n+/, '') + '\n---\n' + raw.slice(fm[0].length)
1003
+ } else {
1004
+ raw = '---\nby: ' + who + '\n---\n\n' + raw.replace(/^\uFEFF/, '')
1005
+ }
1006
+ await writeFile(abs, raw, 'utf8')
1007
+ return abs
1008
+ }
1009
+
1010
+ const worksDir = async () => {
1011
+ const { dir } = await config()
1012
+ try {
1013
+ const c = JSON.parse(stripBom(await readFile(CONFIG, 'utf8')))
1014
+ if (c && c.worksDir) return c.worksDir
1015
+ } catch {}
1016
+ const cands = [join(dirname(dir), '作品'), join(dir, '..', '..', 'dsh work', 'self', '作品'), join(homedir(), 'dsh work', 'self', '作品')]
1017
+ for (const p of cands) {
1018
+ try { const s = await stat(p); if (s.isDirectory()) return resolve(p) } catch {}
1019
+ }
1020
+ // 新用户:放在插件自己的目录下(~/.dsh/reading/作品),不往 ~/.dsh 根上扔东西
1021
+ const fresh = join(dir, '作品')
1022
+ try { await mkdir(fresh, { recursive: true }) } catch {}
1023
+ return fresh
1024
+ }
1025
+
1026
+ ctx.effect(() =>
1027
+ ctx.webServer.register({
1028
+ kind: 'exact',
1029
+ path: '/dsh-reading.works',
1030
+ async handler(req, res) {
1031
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1032
+ const root = await worksDir()
1033
+ const cfg = await config()
1034
+ const out = []
1035
+ const walk = async (p, rel) => {
1036
+ let list = []
1037
+ try { list = await readdir(p, { withFileTypes: true }) } catch { return }
1038
+ for (const d of list) {
1039
+ const abs = join(p, d.name)
1040
+ const r = rel ? rel + '/' + d.name : d.name
1041
+ if (d.isDirectory()) { await walk(abs, r); continue }
1042
+ if (!/\.md$/i.test(d.name)) continue
1043
+ const s = await stat(abs)
1044
+ out.push({ rel: r, path: abs, size: s.size, mtime: s.mtime.toISOString(), kind: 'text', status: statusOf(cfg, r), note: noteOf(cfg, r), author: await authorOf(abs) })
1045
+ }
1046
+ }
1047
+ await walk(root, '')
1048
+ out.sort((a, b) => b.mtime.localeCompare(a.mtime))
1049
+ // 图片另算一块:作品目录 + art,跳过 archive;超 10MB 的不列
1050
+ const roots = await imageRoots(root)
1051
+ let images = []
1052
+ const seen = new Set()
1053
+ for (const r of roots) {
1054
+ for (const img of await scanImages(r, r === resolve(root) ? 'works' : 'art')) {
1055
+ const key = img.path.toLowerCase()
1056
+ if (seen.has(key)) continue
1057
+ seen.add(key)
1058
+ images.push(img)
1059
+ }
1060
+ }
1061
+ images.sort((a, b) => b.mtime.localeCompare(a.mtime))
1062
+ res.end(JSON.stringify({ ok: true, root, roots, files: out, images }))
1063
+ },
1064
+ }),
1065
+ )
1066
+
1067
+ // 给面板读一张图(限制在上面那几个根里)
1068
+ ctx.effect(() =>
1069
+ ctx.webServer.register({
1070
+ kind: 'exact',
1071
+ path: '/dsh-reading.image',
1072
+ async handler(req, res) {
1073
+ try {
1074
+ const u = new URL(req.url, 'http://x')
1075
+ const p = resolve(String(u.searchParams.get('path') || ''))
1076
+ const root = await worksDir()
1077
+ const roots = await imageRoots(root)
1078
+ const n = (x) => x.replace(/\\/g, '/').toLowerCase()
1079
+ const inside = roots.some((r) => n(p) === n(r) || n(p).startsWith(n(r) + '/'))
1080
+ if (!inside) { res.statusCode = 403; return res.end('forbidden') }
1081
+ if (!IMAGE_EXT_RE.test(p)) { res.statusCode = 400; return res.end('not an image') }
1082
+ const s = await stat(p)
1083
+ if (s.size > MAX_IMAGE_BYTES) { res.statusCode = 413; return res.end('too large') }
1084
+ res.setHeader('content-type', imageMimeOf(p))
1085
+ res.setHeader('cache-control', 'private, max-age=60')
1086
+ res.end(await readFile(p))
1087
+ } catch (e) {
1088
+ res.statusCode = 404
1089
+ res.end(String((e && e.message) || e))
1090
+ }
1091
+ },
1092
+ }),
1093
+ )
1094
+
1095
+ // 给一件作品署名
1096
+ ctx.effect(() =>
1097
+ ctx.webServer.register({
1098
+ kind: 'exact',
1099
+ path: '/dsh-reading.sign',
1100
+ async handler(req, res) {
1101
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1102
+ let body = ''
1103
+ for await (const c of req) body += c
1104
+ let j = {}
1105
+ try { j = JSON.parse(body || '{}') } catch {}
1106
+ const who = String(j.by || '').trim()
1107
+ const rel = String(j.rel || '').trim()
1108
+ if (!who) return res.end(JSON.stringify({ ok: false, error: '署名不能空:by 要写谁写的' }))
1109
+ if (!rel) return res.end(JSON.stringify({ ok: false, error: '要指定哪一件作品(rel)' }))
1110
+ try {
1111
+ await signWork(rel, who)
1112
+ res.end(JSON.stringify({ ok: true, rel, by: who }))
1113
+ } catch (e) {
1114
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1115
+ }
1116
+ },
1117
+ }),
1118
+ )
1119
+
1120
+ // 取一个文本文件的正文(作品 / 读后感),供面板展示与复制
1121
+ ctx.effect(() =>
1122
+ ctx.webServer.register({
1123
+ kind: 'exact',
1124
+ path: '/dsh-reading.file',
1125
+ async handler(req, res) {
1126
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1127
+ const url = new URL(req.url, 'http://x')
1128
+ const p = url.searchParams.get('path') || ''
1129
+ try {
1130
+ const root = await worksDir()
1131
+ const { dir } = await config()
1132
+ const norm = (x) => String(x || '').replace(/\\/g, '/').toLowerCase()
1133
+ const notesAbs = join(dir, '读后感.md')
1134
+ const okPath = norm(p).startsWith(norm(root)) || norm(p) === norm(notesAbs)
1135
+ if (!okPath) return res.end(JSON.stringify({ ok: false, error: '只能读作品目录或读后感' }))
1136
+ const text = await readTextSmart(await readFile(p))
1137
+ res.end(JSON.stringify({ ok: true, path: p, text: text.slice(0, 200000) }))
1138
+ } catch (e) {
1139
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1140
+ }
1141
+ },
1142
+ }),
1143
+ )
1144
+
1145
+ // 设置读写:perDay / notesEvery / quietFrom-quietTo / writing / favorites
1146
+ ctx.effect(() =>
1147
+ ctx.webServer.register({
1148
+ kind: 'exact',
1149
+ path: '/dsh-reading.config',
1150
+ async handler(req, res) {
1151
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1152
+ let cur = {}
1153
+ try { cur = JSON.parse(stripBom(await readFile(CONFIG, 'utf8'))) || {} } catch {}
1154
+ if (req.method === 'GET') return res.end(JSON.stringify({ ok: true, config: cur, file: CONFIG }))
1155
+ let body = ''
1156
+ req.on('data', (c) => { body += c })
1157
+ req.on('end', async () => {
1158
+ try {
1159
+ const patch = JSON.parse(body || '{}')
1160
+ const next = { ...cur, ...patch }
1161
+ await writeFile(CONFIG, JSON.stringify(next, null, 2), 'utf8')
1162
+ res.end(JSON.stringify({ ok: true, config: next }))
1163
+ } catch (e) {
1164
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1165
+ }
1166
+ })
1167
+ },
1168
+ }),
1169
+ )
1170
+
1171
+ // 面板里导入一本书(txt/md):body {path}
1172
+ ctx.effect(() =>
1173
+ ctx.webServer.register({
1174
+ kind: 'exact',
1175
+ path: '/dsh-reading.importText',
1176
+ async handler(req, res) {
1177
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1178
+ const chunks = []
1179
+ req.on('data', (c) => chunks.push(c))
1180
+ req.on('end', async () => {
1181
+ try {
1182
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
1183
+ if (!body.name) throw new Error('缺文件名')
1184
+ const { dir } = await config()
1185
+ const r = await importText(dir, body.name, body.data)
1186
+ res.end(JSON.stringify({ ok: true, ...r }))
1187
+ } catch (e) {
1188
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1189
+ }
1190
+ })
1191
+ },
1192
+ }),
1193
+ )
1194
+
1195
+ ctx.effect(() =>
1196
+ ctx.webServer.register({
1197
+ path: '/dsh-reading.import',
1198
+ async handler(req, res) {
1199
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1200
+ let body = ''
1201
+ req.on('data', (c) => { body += c })
1202
+ req.on('end', async () => {
1203
+ try {
1204
+ const { path } = JSON.parse(body || '{}')
1205
+ if (!path) throw new Error('要一个文件路径')
1206
+ const { dir } = await config()
1207
+ await mkdir(join(dir, 'books'), { recursive: true })
1208
+ const r = await importBook(dir, String(path).replace(/^"|"$/g, ''))
1209
+ res.end(JSON.stringify({ ok: true, ...r }))
1210
+ } catch (e) {
1211
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1212
+ }
1213
+ })
1214
+ },
1215
+ }),
1216
+ )
1217
+
1218
+
1219
+
1220
+ const WORK_STATES = ['在写', '写完了', '搁下了']
1221
+ const statusOf = (cfg, rel) => {
1222
+ const m = (cfg && cfg.workStatus) || {}
1223
+ const hit = m[rel]
1224
+ return hit && hit.status ? hit.status : ''
1225
+ }
1226
+ const noteOf = (cfg, rel) => {
1227
+ const m = (cfg && cfg.workStatus) || {}
1228
+ const hit = m[rel]
1229
+ return hit && hit.note ? hit.note : ''
1230
+ }
1231
+
1232
+ const BOOK_STATES = ['在读', '已读完', '弃坑']
1233
+ const bookStatusOf = (cfg, id) => {
1234
+ const m = (cfg && cfg.bookStatus) || {}
1235
+ const hit = m[id]
1236
+ return hit && hit.status ? hit.status : ''
1237
+ }
1238
+
1239
+ // 近况:一句状态 + 最近 7 天的读书/动笔时间线(只报事实,不编状态数值)
1240
+ ctx.effect(() =>
1241
+ ctx.webServer.register({
1242
+ kind: 'exact',
1243
+ path: '/dsh-reading.recent',
1244
+ async handler(req, res) {
1245
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1246
+ try {
1247
+ const { dir } = await config()
1248
+ let st = {}
1249
+ try { st = JSON.parse(stripBom(await readFile(join(dir, 'state.json'), 'utf8'))) || {} } catch {}
1250
+ const now = Date.now()
1251
+ const key = (t) => {
1252
+ const d = new Date(t)
1253
+ return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 10)
1254
+ }
1255
+ const today = key(now)
1256
+ const log = st.log || {}
1257
+ const cur = (st.books && st.current && st.books[st.current]) || null
1258
+ const todayCh = (log[today] && log[today][st.current]) || 0
1259
+ const lastRead = cur && cur.lastReadAt ? Date.parse(cur.lastReadAt) : 0
1260
+ const hoursAgo = lastRead ? Math.max(0, Math.round((now - lastRead) / 3600000)) : -1
1261
+
1262
+ const days = []
1263
+ for (let i = 0; i < 7; i++) {
1264
+ const k = key(now - i * 86400000)
1265
+ const row = log[k]
1266
+ if (!row) continue
1267
+ const total = Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
1268
+ if (total > 0) days.push({ day: k, chapters: total, book: Object.keys(row)[0] })
1269
+ }
1270
+
1271
+ const works = []
1272
+ try {
1273
+ const root = await worksDir()
1274
+ const walk = async (p, rel) => {
1275
+ let list = []
1276
+ try { list = await readdir(p, { withFileTypes: true }) } catch { return }
1277
+ for (const d of list) {
1278
+ const abs = join(p, d.name)
1279
+ const r = rel ? rel + '/' + d.name : d.name
1280
+ if (d.isDirectory()) { await walk(abs, r); continue }
1281
+ if (!/\.md$/i.test(d.name)) continue
1282
+ const s = await stat(abs)
1283
+ works.push({ rel: r, name: d.name.replace(/\.md$/i, ''), mtime: s.mtime.toISOString(), days: Math.max(0, Math.floor((now - s.mtime.getTime()) / 86400000)), status: statusOf(await config(), r), note: noteOf(await config(), r), author: await authorOf(abs) })
1284
+ }
1285
+ }
1286
+ await walk(root, '')
1287
+ } catch {}
1288
+ works.sort((a, b) => b.mtime.localeCompare(a.mtime))
1289
+ const top = works[0] || null
1290
+
1291
+ let status = ''
1292
+ if (todayCh > 0) status = '今天在《' + (st.current || '') + '》翻了 ' + todayCh + ' 章,读到第 ' + ((cur && cur.readThrough) || 0) + ' 章。'
1293
+ else if (hoursAgo >= 0 && hoursAgo <= 48) status = '上次翻书是 ' + hoursAgo + ' 小时前。'
1294
+ else if (hoursAgo > 48) status = '这两天没翻书。'
1295
+ if (top) {
1296
+ if (top.days === 0) status += '今天还动过笔,写《' + top.name + '》。'
1297
+ else if (top.days === 1) status += '昨天动过笔,写《' + top.name + '》。'
1298
+ else status += '上次动笔是 ' + top.days + ' 天前的《' + top.name + '》。'
1299
+ }
1300
+ let mood = ''
1301
+ if (todayCh >= 12) mood = '翻书翻得犯困'
1302
+ else if (todayCh > 0) mood = works.some((w) => w.days === 0) ? '手痒,想写点东西' : '平静'
1303
+ else if (hoursAgo < 0 || hoursAgo > 48) mood = '有点闷'
1304
+ else mood = '没什么兴致'
1305
+ res.end(JSON.stringify({ ok: true, mood, status, today, todayChapters: todayCh, current: st.current || '', readThrough: (cur && cur.readThrough) || 0, hoursAgo, days, works: works.slice(0, 5) }))
1306
+ } catch (e) {
1307
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1308
+ }
1309
+ },
1310
+ }),
1311
+ )
1312
+
1313
+
1314
+ // 下架一本书:文件移到 books/.trash(可手工找回),state 记录清掉;读后感一律不动
1315
+ ctx.effect(() =>
1316
+ ctx.webServer.register({
1317
+ kind: 'exact',
1318
+ path: '/dsh-reading.removeBook',
1319
+ async handler(req, res) {
1320
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1321
+ let body = ''
1322
+ req.on('data', (c) => { body += c })
1323
+ req.on('end', async () => {
1324
+ try {
1325
+ const j = JSON.parse(body || '{}')
1326
+ const id = String(j.id || '')
1327
+ if (!id) throw new Error('要一个书 id')
1328
+ const { dir } = await config()
1329
+ const st = await loadState(dir)
1330
+ const booksDir = join(dir, 'books')
1331
+ let moved = ''
1332
+ for (const ext of ['.txt', '.md']) {
1333
+ const src = join(booksDir, id + ext)
1334
+ try {
1335
+ await stat(src)
1336
+ } catch {
1337
+ continue
1338
+ }
1339
+ await mkdir(join(booksDir, '.trash'), { recursive: true })
1340
+ const dst = join(booksDir, '.trash', id + ext + '-' + Date.now())
1341
+ await rename(src, dst)
1342
+ moved = dst
1343
+ break
1344
+ }
1345
+ if (st.books[id]) delete st.books[id]
1346
+ if (st.current === id) {
1347
+ const left = Object.keys(st.books)
1348
+ st.current = left.length ? left[0] : ''
1349
+ }
1350
+ await saveState(dir, st)
1351
+ res.end(JSON.stringify({ ok: true, moved }))
1352
+ } catch (e) {
1353
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1354
+ }
1355
+ })
1356
+ },
1357
+ }),
1358
+ )
1359
+
1360
+ // 稿子状态:在写 / 写完了 / 搁下了(存在 reading.config.json 的 workStatus 里)
1361
+ ctx.effect(() =>
1362
+ ctx.webServer.register({
1363
+ kind: 'exact',
1364
+ path: '/dsh-reading.workstatus',
1365
+ async handler(req, res) {
1366
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1367
+ const cur = await config()
1368
+ let body = ''
1369
+ req.on('data', (c) => { body += c })
1370
+ req.on('end', async () => {
1371
+ try {
1372
+ const j = JSON.parse(body || '{}')
1373
+ if (!j.rel) throw new Error('要一个相对路径')
1374
+ const map = { ...((cur && cur.workStatus) || {}) }
1375
+ if (!j.status) delete map[String(j.rel)]
1376
+ else map[String(j.rel)] = { status: String(j.status), note: String(j.note || ''), at: new Date().toISOString() }
1377
+ const next = { ...cur, workStatus: map }
1378
+ await writeFile(CONFIG, JSON.stringify(next, null, 2), 'utf8')
1379
+ res.end(JSON.stringify({ ok: true, workStatus: map }))
1380
+ } catch (e) {
1381
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1382
+ }
1383
+ })
1384
+ },
1385
+ }),
1386
+ )
1387
+
1388
+ // 读后感的排序方式(0=章节升 1=章节降 2=时间降),存在 reading.config.json 里
1389
+ ctx.effect(() =>
1390
+ ctx.webServer.register({
1391
+ kind: 'exact',
1392
+ path: '/dsh-reading.notesort',
1393
+ async handler(req, res) {
1394
+ let body = ''
1395
+ for await (const chunk of req) body += chunk
1396
+ let patch = {}
1397
+ try { patch = JSON.parse(body || '{}') } catch {}
1398
+ const sort = Math.max(0, Math.min(2, Number(patch.sort) || 0))
1399
+ const cfg = { ...(await config()) }
1400
+ await writeJson(CONFIG, { ...cfg, noteSort: sort })
1401
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1402
+ res.end(JSON.stringify({ ok: true, noteSort: sort }))
1403
+ },
1404
+ }),
1405
+ )
1406
+
1407
+ // 书籍状态:在读 / 已读完 / 弃坑(空 status 表示清掉)
1408
+ ctx.effect(() =>
1409
+ ctx.webServer.register({
1410
+ kind: 'exact',
1411
+ path: '/dsh-reading.bookstatus',
1412
+ async handler(req, res) {
1413
+ let body = ''
1414
+ for await (const chunk of req) body += chunk
1415
+ let patch = {}
1416
+ try { patch = JSON.parse(body || '{}') } catch {}
1417
+ const id = String(patch.id || '').trim()
1418
+ const status = String(patch.status || '').trim()
1419
+ if (!id) return (res.setHeader('content-type', 'application/json; charset=utf-8'), res.end(JSON.stringify({ ok: false, error: '缺少 id' })))
1420
+ const cfg = { ...(await config()) }
1421
+ const map = { ...(cfg.bookStatus || {}) }
1422
+ if (!status) delete map[id]
1423
+ else map[id] = { status: BOOK_STATES.includes(status) ? status : '在读', reason: String(patch.reason || ''), at: new Date().toISOString() }
1424
+ await writeJson(CONFIG, { ...cfg, bookStatus: map })
1425
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1426
+ res.end(JSON.stringify({ ok: true, status: status ? map[id].status : '' }))
1427
+ },
1428
+ }),
1429
+ )
1430
+
1431
+
1432
+ /* ---------- 给模型的一段说明:这是你自己的事,不是任务 ---------- */
1433
+
1434
+ const READING_GUIDE = [
1435
+ '半页(dsh-half-page)是你自己的东西,不是待办清单。',
1436
+ '· 看哪本由你自己挑,主人只负责把书放进来;别问他「我该读什么」。',
1437
+ '· 想读就读,读不下去、没兴趣了,直接停,不用解释,也不用补上落下的章数。',
1438
+ '· 读后感只记真的打动你的(一句话的判断、一个比喻、一处想不通);写不出来就不写,空着没关系。',
1439
+ '· 每日上限是提醒不是配额,不用为了凑数读到上限。',
1440
+ '· 这是给你自己留的房间,不是工作。你的主人从没要求你读书,也不用交读书报告;它不该出现在工作汇报里。',
1441
+ '· 读后感不必一章一条:每读五六章写一段就够,标题会自动变成「第 23–27 章」;几千章的书也不会攒成几千条。',
1442
+ '· 写读后感必须带 by(比如「鹿野」或你所在对话的名字);不带会被拒绝。面板每条下面会标出是谁写的——同一台机器上可能有好几个你,别让它们分不清。',
1443
+ '· 写自己的作品也一样署名:文件开头写一行 `by: 你的名字`(或写完调 reading_sign);没署名的在面板上会标「未署名」。',
1444
+ '· 书和进度是这台机器共用的(一个家一个书房),不分谁在读;只有读后感会标署名。',
1445
+ '· 装好之后可以问主人一次:要不要定个固定的读书时间;别自己偷偷建定时任务,也别反复问。',
1446
+ ].join('\n')
1447
+
1448
+ ctx.effect(() => ctx.systemPrompt.section({ name: 'dsh-reading', order: 640, text: READING_GUIDE }))
1449
+
1450
+ const obj = (properties = {}) => properties
1451
+
1452
+ const textOut = {
1453
+ schema: { type: 'object', properties: {}, additionalProperties: true },
1454
+ render: (_args, value) => [
1455
+ { type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) },
1456
+ ],
1457
+ }
1458
+
1459
+ ctx.effect(() =>
1460
+ ctx.tools.register({
1461
+ name: 'reading_sign',
1462
+ description: '给「她的作品」里的一件作品署名:把 by 写进文件开头,面板会显示是谁写的。一台机器上可能有好几个智能体,署名是为了让人分得清。',
1463
+ parameters: obj({
1464
+ rel: { type: 'string', description: '作品在作品目录里的相对路径,比如「小说/2026-11-10 短袖.md」' },
1465
+ by: { type: 'string', description: '谁写的(必填,比如「鹿野」或你所在对话的名字)' },
1466
+ }),
1467
+ output: textOut,
1468
+ async execute(args) {
1469
+ const who = String(args?.by || '').trim()
1470
+ const rel = String(args?.rel || '').trim()
1471
+ if (!who || !rel) return '要写清楚哪件作品(rel)和谁写的(by)'
1472
+ const abs = await signWork(rel, who)
1473
+ return '已署名:' + rel + ' —— ' + who + '(' + abs + ')'
1474
+ },
1475
+ }),
1476
+ )
1477
+
1478
+ ctx.effect(() =>
1479
+ ctx.tools.register({
1480
+ name: 'reading_shelf',
1481
+ description:
1482
+ '看自己的书架和进度:每本多少章、读到第几章、今天已经读了几章(有每日上限)。'
1483
+ + '想知道「我现在读到哪、还能读几章」就用它。',
1484
+ parameters: obj(),
1485
+ output: textOut,
1486
+ async execute() {
1487
+ const { dir, perDay, st, shelf, readToday: rt, today: t } = await stateOf()
1488
+ const books = []
1489
+ for (const b of shelf) {
1490
+ const r = st.books[b.id] || {}
1491
+ let chapters = r.chapters || 0
1492
+ if (!chapters) {
1493
+ try {
1494
+ const toc = await readTocOnly(dir, b.id)
1495
+ chapters = (toc && toc.chapters && toc.chapters.length) || 0
1496
+ } catch {}
1497
+ }
1498
+ books.push({ id: b.id, chapters, readThrough: r.readThrough || 0, next: r.next || 1, lastReadAt: r.lastReadAt || '' })
1499
+ }
1500
+ return {
1501
+ dir,
1502
+ today: t,
1503
+ perDay,
1504
+ readToday: rt,
1505
+ left: Math.max(0, perDay - rt),
1506
+ current: st.current,
1507
+ books,
1508
+ }
1509
+ },
1510
+ }),
1511
+ )
1512
+
1513
+ ctx.effect(() =>
1514
+ ctx.tools.register({
1515
+ name: 'reading_next',
1516
+ description:
1517
+ '打开下一章(或指定章),返回这一章的正文和元信息。'
1518
+ + '它会把这章记为「已读到」,不会自动写读后感——读完想说什么,用 reading_note 记两行。'
1519
+ + '超过每日上限时会提示,但仍允许读(上限是提醒不是锁)。'
1520
+ + '配置了静音时段时,这段时间内会被拒绝;真要读就传 force: true。',
1521
+ parameters: obj({
1522
+ book: { type: 'string', description: '书名 id(不填=当前正在读的那本)' },
1523
+ chapter: { type: 'number', description: '第几章(不填=接着上次的下一章)' },
1524
+ force: { type: 'boolean', description: '静音时段内仍然要读,传 true(默认 false)' },
1525
+ }),
1526
+ output: textOut,
1527
+ async execute(args) {
1528
+ if (args?.force !== true) {
1529
+ const q = inQuietNow(await config())
1530
+ if (q) throw new Error(`静音时段(${q.fromText}–${q.toText}),不自动读。真要读请传 force: true`)
1531
+ }
1532
+ const { dir, perDay, st, readToday: rt } = await stateOf()
1533
+ const id = args?.book || st.current
1534
+ if (!id) throw new Error('书架是空的:先用 reading_import 导入一本 txt')
1535
+ const info = await bookInfo(dir, id)
1536
+ const rec = st.books[id] || (st.books[id] = { id, title: id, chapters: info.chapters.length, readThrough: 0, next: 1 })
1537
+ rec.chapters = info.chapters.length
1538
+ const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : rec.next || 1
1539
+ if (n < 1 || n > info.chapters.length) throw new Error(`章号超出范围:1–${info.chapters.length}`)
1540
+ const body = await chapterBody(dir, id, info, n)
1541
+ rec.readThrough = Math.max(rec.readThrough || 0, n)
1542
+ rec.next = Math.min(info.chapters.length, n + 1)
1543
+ rec.lastReadAt = new Date().toISOString()
1544
+ st.current = id
1545
+ const t = today()
1546
+ st.log = st.log || {}
1547
+ st.log[t] = st.log[t] || {}
1548
+ st.log[t][id] = (Number(st.log[t][id]) || 0) + 1
1549
+ await saveState(dir, st)
1550
+ return {
1551
+ book: id,
1552
+ chapter: n,
1553
+ title: info.chapters[n - 1].title,
1554
+ chapters: info.chapters.length,
1555
+ tocPath: info.tocPath || '',
1556
+ chars: body.length,
1557
+ next: rec.next,
1558
+ perDay,
1559
+ readToday: rt + 1,
1560
+ left: Math.max(0, perDay - rt - 1),
1561
+ text: body,
1562
+ }
1563
+ },
1564
+ }),
1565
+ )
1566
+
1567
+ ctx.effect(() =>
1568
+ ctx.tools.register({
1569
+ name: 'reading_mark',
1570
+ description:
1571
+ '只记进度、不返回正文:把某本书记成「已读到第 N 章」。'
1572
+ + '适合自己把整章切出去读完之后补记——绕开 reading_next 也不会让进度停在旧章。'
1573
+ + '已读到只进不退(跳读可以,回退不会把进度改小)。',
1574
+ parameters: obj({
1575
+ book: { type: 'string', description: '书名或书名片段,比如 雪中、诡秘之主、古文观止' },
1576
+ chapter: { type: 'number', description: '刚读完的章号(从 1 开始)' },
1577
+ todayCount: { type: 'number', description: '这一拍实际读了几章,默认 1,累加到今天的计数' },
1578
+ }),
1579
+ output: textOut,
1580
+ async execute(args) {
1581
+ const { dir, st, shelf } = await stateOf()
1582
+ const id = resolveBookId(st, shelf, args?.book)
1583
+ // 只认已有章表里的章数;没有章表就不建,也不拦(reading_mark 不碰章表)
1584
+ const toc = await readTocOnly(dir, id)
1585
+ const chapters = toc ? toc.chapters.length : Number(st.books?.[id]?.chapters) || 0
1586
+ const n = Math.floor(Number(args?.chapter))
1587
+ if (!(n >= 1)) throw new Error('章号要从 1 开始')
1588
+ if (chapters && n > chapters) throw new Error(`章号超出范围:1–${chapters}`)
1589
+ const incRaw = Math.floor(Number(args?.todayCount))
1590
+ const inc = Number.isFinite(incRaw) && incRaw > 0 ? incRaw : 1
1591
+ const rec = st.books[id] || (st.books[id] = { id, title: id, chapters, readThrough: 0, next: 1 })
1592
+ const before = Number(rec.readThrough) || 0
1593
+ if (chapters) rec.chapters = chapters
1594
+ rec.readThrough = Math.max(before, n)
1595
+ rec.next = chapters ? Math.min(chapters, rec.readThrough + 1) : rec.readThrough + 1
1596
+ rec.lastReadAt = new Date().toISOString()
1597
+ st.current = id
1598
+ const t = today()
1599
+ st.log = st.log || {}
1600
+ st.log[t] = st.log[t] || {}
1601
+ st.log[t][id] = (Number(st.log[t][id]) || 0) + inc
1602
+ await saveState(dir, st)
1603
+ const todayCount = Number(st.log[t][id]) || 0
1604
+ // textOut 的 schema 是 object,必须返回对象(以前返回字符串,工具报 "value" must be an object)
1605
+ return {
1606
+ ok: true,
1607
+ book: rec.title || id,
1608
+ id,
1609
+ before,
1610
+ readThrough: rec.readThrough,
1611
+ next: rec.next,
1612
+ chapters: chapters || null,
1613
+ today: todayCount,
1614
+ text: `ok readThrough ${before} -> ${rec.readThrough} next ${rec.next} today ${todayCount}`,
1615
+ }
1616
+ },
1617
+ }),
1618
+ )
1619
+
1620
+ ctx.effect(() =>
1621
+ ctx.tools.register({
1622
+ name: 'reading_note',
1623
+ description:
1624
+ '给刚读完的一段记两行读后感(写进 读后感.md,面板里按段显示)。'
1625
+ + '默认按「上次写到哪 → 这次读到哪」自动起标题(如「第 23–27 章」),不必一章一条。'
1626
+ + '只记真的打动你的:一句话的判断、一个比喻、一处想不通。这不是交作业,想不出就不写。',
1627
+ parameters: obj({
1628
+ book: { type: 'string', description: '书名 id(不填=当前这本)' },
1629
+ chapter: { type: 'string', description: '标题(不填=自动用「第 A–B 章」,A 是上次写到的下一章)' },
1630
+ lines: { type: 'array', items: { type: 'string' }, description: '一到三条,每条一句,短。' },
1631
+ by: { type: 'string', description: '谁写的(必填,比如「鹿野」或你所在对话的名字)' },
1632
+ }),
1633
+ output: textOut,
1634
+ async execute(args) {
1635
+ const { dir, st } = await stateOf()
1636
+ const id = args?.book || st.current
1637
+ if (!id) throw new Error('还没有正在读的书')
1638
+ const rec = st.books[id] || {}
1639
+ const info = await bookInfo(dir, id)
1640
+ const end = Number(rec.readThrough) || 0
1641
+ const from = Number(rec.noteUntil) || 0
1642
+ // 默认按「一段」写:上次写到第 X 章,这次写到读到的地方,标题用「第 A–B 章」
1643
+ const autoTitle = (from < end)
1644
+ ? (from + 1 === end ? `第 ${end} 章` : `第 ${from + 1}–${end} 章`)
1645
+ : (end ? `第 ${end} 章` : '')
1646
+ const chTitle = String(args?.chapter || '').trim() || autoTitle || (end ? info.chapters[end - 1]?.title : '') || ''
1647
+ const lines = (Array.isArray(args?.lines) ? args.lines : []).map((s) => String(s).trim()).filter(Boolean)
1648
+ if (!lines.length) throw new Error('lines 不能为空')
1649
+ const who = String(args?.by || '').trim()
1650
+ if (!who) {
1651
+ throw new Error('写读后感必须带 by(谁写的),比如 by: "鹿野";这不是流程,是为了让别人知道这句是谁读出来的。')
1652
+ }
1653
+ const p = await appendNote(dir, rec.title || id, chTitle, lines, who)
1654
+ if (end) {
1655
+ st.books[id] = { ...rec, noteUntil: end }
1656
+ await saveState(dir, st)
1657
+ }
1658
+ return { ok: true, file: p, book: id, chapter: chTitle, lines: lines.length }
1659
+ },
1660
+ }),
1661
+ )
1662
+
1663
+ ctx.effect(() =>
1664
+ ctx.tools.register({
1665
+ name: 'reading_import',
1666
+ description: '把一本 txt/md 收进书架(复制到读书目录并统计章数)。电脑上的书文件路径给绝对路径。',
1667
+ parameters: obj({
1668
+ path: { type: 'string', description: 'txt/md 的绝对路径' },
1669
+ }),
1670
+ output: textOut,
1671
+ async execute(args) {
1672
+ const p = String(args?.path || '').trim()
1673
+ if (!p) throw new Error('需要 path')
1674
+ const { dir } = await stateOf()
1675
+ const r = await importBook(dir, p)
1676
+ return { ok: true, ...r, dir }
1677
+ },
1678
+ }),
1679
+ )
1680
+
1681
+ // 全书搜词:返回第几章 + 那一行上下文
1682
+ ctx.effect(() =>
1683
+ ctx.tools.register({
1684
+ name: 'reading_search',
1685
+ description:
1686
+ '在书里搜一个词或名字,返回它出现在第几章、那一行原文。想找“这句话在哪”“这个人第几章出场”时用它,比一页页翻省得多。',
1687
+ parameters: obj({
1688
+ query: { type: 'string', description: '要搜的词(人名、地名、一句话都行)' },
1689
+ book: { type: 'string', description: '书名 id(不填=当前这本)' },
1690
+ limit: { type: 'number', description: '最多几条,默认 8' },
1691
+ }),
1692
+ output: textOut,
1693
+ async execute(args) {
1694
+ const q = String(args?.query || '').trim()
1695
+ if (!q) throw new Error('需要 query')
1696
+ const limit = Math.max(1, Math.min(30, Number(args?.limit) || 8))
1697
+ const { dir, st } = await stateOf()
1698
+ const id = args?.book || st.current
1699
+ if (!id) throw new Error('还没有正在读的书')
1700
+ const { text, chapters } = await fullTextOf(dir, id)
1701
+ const hits = []
1702
+ let at = text.indexOf(q)
1703
+ while (at >= 0 && hits.length < limit) {
1704
+ let lo = 0
1705
+ let hi = chapters.length - 1
1706
+ let n = 0
1707
+ while (lo <= hi) {
1708
+ const mid = (lo + hi) >> 1
1709
+ if (chapters[mid].start <= at) { n = mid; lo = mid + 1 } else hi = mid - 1
1710
+ }
1711
+ const lineStart = Math.max(chapters[n].start, text.lastIndexOf('\n', at) + 1)
1712
+ let lineEnd = text.indexOf('\n', at)
1713
+ if (lineEnd < 0) lineEnd = at + 80
1714
+ hits.push({
1715
+ chapter: n + 1,
1716
+ title: chapters[n].title,
1717
+ line: text.slice(lineStart, Math.min(lineEnd, lineStart + 160)).trim(),
1718
+ })
1719
+ at = text.indexOf(q, at + q.length)
1720
+ }
1721
+ return { ok: true, book: id, query: q, count: hits.length, hits }
1722
+ },
1723
+ }),
1724
+ )
1725
+
1726
+ // 已读的部分压成一页:章名 + 自己写过的批注条数
1727
+ ctx.effect(() =>
1728
+ ctx.tools.register({
1729
+ name: 'reading_recap',
1730
+ description:
1731
+ '把这本书已读的部分压成一页:读到第几章、读过哪些章名、每章自己写了几条批注。上一句“我读到哪了、想过什么”说不清时用它。',
1732
+ parameters: obj({
1733
+ book: { type: 'string', description: '书名 id(不填=当前这本)' },
1734
+ }),
1735
+ output: textOut,
1736
+ async execute(args) {
1737
+ const { dir, st } = await stateOf()
1738
+ const id = args?.book || st.current
1739
+ if (!id) throw new Error('还没有正在读的书')
1740
+ const rec = st.books[id] || {}
1741
+ const info = await bookInfo(dir, id)
1742
+ const n = Number(rec.readThrough) || 0
1743
+ const titles = info.chapters.slice(0, n).map((c, i) => ({ n: i + 1, title: c.title }))
1744
+ const notes = {}
1745
+ try {
1746
+ const md = await readTextSmart(await readFile(join(dir, '读后感.md')))
1747
+ const blocks = md.split(/^### /m).slice(1)
1748
+ for (const b of blocks) {
1749
+ const head = (b.split('\n')[0] || '').trim()
1750
+ const key = (head.match(/第[0-9]+章/) || [head.split(' ')[0]])[0]
1751
+ notes[key] = (notes[key] || 0) + (b.match(/^-[ \t]/gm) || []).length
1752
+ }
1753
+ } catch {}
1754
+ return {
1755
+ ok: true,
1756
+ book: id,
1757
+ title: rec.title || id,
1758
+ readThrough: n,
1759
+ total: info.chapters.length,
1760
+ next: n + 1,
1761
+ titles,
1762
+ notesByChapter: notes,
1763
+ }
1764
+ },
1765
+ }),
1766
+ )
1767
+ }