@2019wakeup/dsh-reader 0.0.0-stage → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +113 -2
  3. package/assets/cmaps/78-EUC-H.bcmap +0 -0
  4. package/assets/cmaps/78-EUC-V.bcmap +0 -0
  5. package/assets/cmaps/78-H.bcmap +0 -0
  6. package/assets/cmaps/78-RKSJ-H.bcmap +0 -0
  7. package/assets/cmaps/78-RKSJ-V.bcmap +0 -0
  8. package/assets/cmaps/78-V.bcmap +0 -0
  9. package/assets/cmaps/78ms-RKSJ-H.bcmap +0 -0
  10. package/assets/cmaps/78ms-RKSJ-V.bcmap +0 -0
  11. package/assets/cmaps/83pv-RKSJ-H.bcmap +0 -0
  12. package/assets/cmaps/90ms-RKSJ-H.bcmap +0 -0
  13. package/assets/cmaps/90ms-RKSJ-V.bcmap +0 -0
  14. package/assets/cmaps/90msp-RKSJ-H.bcmap +0 -0
  15. package/assets/cmaps/90msp-RKSJ-V.bcmap +0 -0
  16. package/assets/cmaps/90pv-RKSJ-H.bcmap +0 -0
  17. package/assets/cmaps/90pv-RKSJ-V.bcmap +0 -0
  18. package/assets/cmaps/Add-H.bcmap +0 -0
  19. package/assets/cmaps/Add-RKSJ-H.bcmap +0 -0
  20. package/assets/cmaps/Add-RKSJ-V.bcmap +0 -0
  21. package/assets/cmaps/Add-V.bcmap +0 -0
  22. package/assets/cmaps/Adobe-CNS1-0.bcmap +0 -0
  23. package/assets/cmaps/Adobe-CNS1-1.bcmap +0 -0
  24. package/assets/cmaps/Adobe-CNS1-2.bcmap +0 -0
  25. package/assets/cmaps/Adobe-CNS1-3.bcmap +0 -0
  26. package/assets/cmaps/Adobe-CNS1-4.bcmap +0 -0
  27. package/assets/cmaps/Adobe-CNS1-5.bcmap +0 -0
  28. package/assets/cmaps/Adobe-CNS1-6.bcmap +0 -0
  29. package/assets/cmaps/Adobe-CNS1-UCS2.bcmap +0 -0
  30. package/assets/cmaps/Adobe-GB1-0.bcmap +0 -0
  31. package/assets/cmaps/Adobe-GB1-1.bcmap +0 -0
  32. package/assets/cmaps/Adobe-GB1-2.bcmap +0 -0
  33. package/assets/cmaps/Adobe-GB1-3.bcmap +0 -0
  34. package/assets/cmaps/Adobe-GB1-4.bcmap +0 -0
  35. package/assets/cmaps/Adobe-GB1-5.bcmap +0 -0
  36. package/assets/cmaps/Adobe-GB1-UCS2.bcmap +0 -0
  37. package/assets/cmaps/Adobe-Japan1-0.bcmap +0 -0
  38. package/assets/cmaps/Adobe-Japan1-1.bcmap +0 -0
  39. package/assets/cmaps/Adobe-Japan1-2.bcmap +0 -0
  40. package/assets/cmaps/Adobe-Japan1-3.bcmap +0 -0
  41. package/assets/cmaps/Adobe-Japan1-4.bcmap +0 -0
  42. package/assets/cmaps/Adobe-Japan1-5.bcmap +0 -0
  43. package/assets/cmaps/Adobe-Japan1-6.bcmap +0 -0
  44. package/assets/cmaps/Adobe-Japan1-UCS2.bcmap +0 -0
  45. package/assets/cmaps/Adobe-Korea1-0.bcmap +0 -0
  46. package/assets/cmaps/Adobe-Korea1-1.bcmap +0 -0
  47. package/assets/cmaps/Adobe-Korea1-2.bcmap +0 -0
  48. package/assets/cmaps/Adobe-Korea1-UCS2.bcmap +0 -0
  49. package/assets/cmaps/B5-H.bcmap +0 -0
  50. package/assets/cmaps/B5-V.bcmap +0 -0
  51. package/assets/cmaps/B5pc-H.bcmap +0 -0
  52. package/assets/cmaps/B5pc-V.bcmap +0 -0
  53. package/assets/cmaps/CNS-EUC-H.bcmap +0 -0
  54. package/assets/cmaps/CNS-EUC-V.bcmap +0 -0
  55. package/assets/cmaps/CNS1-H.bcmap +0 -0
  56. package/assets/cmaps/CNS1-V.bcmap +0 -0
  57. package/assets/cmaps/CNS2-H.bcmap +0 -0
  58. package/assets/cmaps/CNS2-V.bcmap +3 -0
  59. package/assets/cmaps/ETHK-B5-H.bcmap +0 -0
  60. package/assets/cmaps/ETHK-B5-V.bcmap +0 -0
  61. package/assets/cmaps/ETen-B5-H.bcmap +0 -0
  62. package/assets/cmaps/ETen-B5-V.bcmap +0 -0
  63. package/assets/cmaps/ETenms-B5-H.bcmap +3 -0
  64. package/assets/cmaps/ETenms-B5-V.bcmap +0 -0
  65. package/assets/cmaps/EUC-H.bcmap +0 -0
  66. package/assets/cmaps/EUC-V.bcmap +0 -0
  67. package/assets/cmaps/Ext-H.bcmap +0 -0
  68. package/assets/cmaps/Ext-RKSJ-H.bcmap +0 -0
  69. package/assets/cmaps/Ext-RKSJ-V.bcmap +0 -0
  70. package/assets/cmaps/Ext-V.bcmap +0 -0
  71. package/assets/cmaps/GB-EUC-H.bcmap +0 -0
  72. package/assets/cmaps/GB-EUC-V.bcmap +0 -0
  73. package/assets/cmaps/GB-H.bcmap +4 -0
  74. package/assets/cmaps/GB-V.bcmap +0 -0
  75. package/assets/cmaps/GBK-EUC-H.bcmap +0 -0
  76. package/assets/cmaps/GBK-EUC-V.bcmap +0 -0
  77. package/assets/cmaps/GBK2K-H.bcmap +0 -0
  78. package/assets/cmaps/GBK2K-V.bcmap +0 -0
  79. package/assets/cmaps/GBKp-EUC-H.bcmap +0 -0
  80. package/assets/cmaps/GBKp-EUC-V.bcmap +0 -0
  81. package/assets/cmaps/GBT-EUC-H.bcmap +0 -0
  82. package/assets/cmaps/GBT-EUC-V.bcmap +0 -0
  83. package/assets/cmaps/GBT-H.bcmap +0 -0
  84. package/assets/cmaps/GBT-V.bcmap +0 -0
  85. package/assets/cmaps/GBTpc-EUC-H.bcmap +0 -0
  86. package/assets/cmaps/GBTpc-EUC-V.bcmap +0 -0
  87. package/assets/cmaps/GBpc-EUC-H.bcmap +0 -0
  88. package/assets/cmaps/GBpc-EUC-V.bcmap +0 -0
  89. package/assets/cmaps/H.bcmap +0 -0
  90. package/assets/cmaps/HKdla-B5-H.bcmap +0 -0
  91. package/assets/cmaps/HKdla-B5-V.bcmap +0 -0
  92. package/assets/cmaps/HKdlb-B5-H.bcmap +0 -0
  93. package/assets/cmaps/HKdlb-B5-V.bcmap +0 -0
  94. package/assets/cmaps/HKgccs-B5-H.bcmap +0 -0
  95. package/assets/cmaps/HKgccs-B5-V.bcmap +0 -0
  96. package/assets/cmaps/HKm314-B5-H.bcmap +0 -0
  97. package/assets/cmaps/HKm314-B5-V.bcmap +0 -0
  98. package/assets/cmaps/HKm471-B5-H.bcmap +0 -0
  99. package/assets/cmaps/HKm471-B5-V.bcmap +0 -0
  100. package/assets/cmaps/HKscs-B5-H.bcmap +0 -0
  101. package/assets/cmaps/HKscs-B5-V.bcmap +0 -0
  102. package/assets/cmaps/Hankaku.bcmap +0 -0
  103. package/assets/cmaps/Hiragana.bcmap +0 -0
  104. package/assets/cmaps/KSC-EUC-H.bcmap +0 -0
  105. package/assets/cmaps/KSC-EUC-V.bcmap +0 -0
  106. package/assets/cmaps/KSC-H.bcmap +0 -0
  107. package/assets/cmaps/KSC-Johab-H.bcmap +0 -0
  108. package/assets/cmaps/KSC-Johab-V.bcmap +0 -0
  109. package/assets/cmaps/KSC-V.bcmap +0 -0
  110. package/assets/cmaps/KSCms-UHC-H.bcmap +0 -0
  111. package/assets/cmaps/KSCms-UHC-HW-H.bcmap +0 -0
  112. package/assets/cmaps/KSCms-UHC-HW-V.bcmap +0 -0
  113. package/assets/cmaps/KSCms-UHC-V.bcmap +0 -0
  114. package/assets/cmaps/KSCpc-EUC-H.bcmap +0 -0
  115. package/assets/cmaps/KSCpc-EUC-V.bcmap +0 -0
  116. package/assets/cmaps/Katakana.bcmap +0 -0
  117. package/assets/cmaps/LICENSE +36 -0
  118. package/assets/cmaps/NWP-H.bcmap +0 -0
  119. package/assets/cmaps/NWP-V.bcmap +0 -0
  120. package/assets/cmaps/RKSJ-H.bcmap +0 -0
  121. package/assets/cmaps/RKSJ-V.bcmap +0 -0
  122. package/assets/cmaps/Roman.bcmap +0 -0
  123. package/assets/cmaps/UniCNS-UCS2-H.bcmap +0 -0
  124. package/assets/cmaps/UniCNS-UCS2-V.bcmap +0 -0
  125. package/assets/cmaps/UniCNS-UTF16-H.bcmap +0 -0
  126. package/assets/cmaps/UniCNS-UTF16-V.bcmap +0 -0
  127. package/assets/cmaps/UniCNS-UTF32-H.bcmap +0 -0
  128. package/assets/cmaps/UniCNS-UTF32-V.bcmap +0 -0
  129. package/assets/cmaps/UniCNS-UTF8-H.bcmap +0 -0
  130. package/assets/cmaps/UniCNS-UTF8-V.bcmap +0 -0
  131. package/assets/cmaps/UniGB-UCS2-H.bcmap +0 -0
  132. package/assets/cmaps/UniGB-UCS2-V.bcmap +0 -0
  133. package/assets/cmaps/UniGB-UTF16-H.bcmap +0 -0
  134. package/assets/cmaps/UniGB-UTF16-V.bcmap +0 -0
  135. package/assets/cmaps/UniGB-UTF32-H.bcmap +0 -0
  136. package/assets/cmaps/UniGB-UTF32-V.bcmap +0 -0
  137. package/assets/cmaps/UniGB-UTF8-H.bcmap +0 -0
  138. package/assets/cmaps/UniGB-UTF8-V.bcmap +0 -0
  139. package/assets/cmaps/UniJIS-UCS2-H.bcmap +0 -0
  140. package/assets/cmaps/UniJIS-UCS2-HW-H.bcmap +0 -0
  141. package/assets/cmaps/UniJIS-UCS2-HW-V.bcmap +0 -0
  142. package/assets/cmaps/UniJIS-UCS2-V.bcmap +0 -0
  143. package/assets/cmaps/UniJIS-UTF16-H.bcmap +0 -0
  144. package/assets/cmaps/UniJIS-UTF16-V.bcmap +0 -0
  145. package/assets/cmaps/UniJIS-UTF32-H.bcmap +0 -0
  146. package/assets/cmaps/UniJIS-UTF32-V.bcmap +0 -0
  147. package/assets/cmaps/UniJIS-UTF8-H.bcmap +0 -0
  148. package/assets/cmaps/UniJIS-UTF8-V.bcmap +0 -0
  149. package/assets/cmaps/UniJIS2004-UTF16-H.bcmap +0 -0
  150. package/assets/cmaps/UniJIS2004-UTF16-V.bcmap +0 -0
  151. package/assets/cmaps/UniJIS2004-UTF32-H.bcmap +0 -0
  152. package/assets/cmaps/UniJIS2004-UTF32-V.bcmap +0 -0
  153. package/assets/cmaps/UniJIS2004-UTF8-H.bcmap +0 -0
  154. package/assets/cmaps/UniJIS2004-UTF8-V.bcmap +0 -0
  155. package/assets/cmaps/UniJISPro-UCS2-HW-V.bcmap +0 -0
  156. package/assets/cmaps/UniJISPro-UCS2-V.bcmap +0 -0
  157. package/assets/cmaps/UniJISPro-UTF8-V.bcmap +0 -0
  158. package/assets/cmaps/UniJISX0213-UTF32-H.bcmap +0 -0
  159. package/assets/cmaps/UniJISX0213-UTF32-V.bcmap +0 -0
  160. package/assets/cmaps/UniJISX02132004-UTF32-H.bcmap +0 -0
  161. package/assets/cmaps/UniJISX02132004-UTF32-V.bcmap +0 -0
  162. package/assets/cmaps/UniKS-UCS2-H.bcmap +0 -0
  163. package/assets/cmaps/UniKS-UCS2-V.bcmap +0 -0
  164. package/assets/cmaps/UniKS-UTF16-H.bcmap +0 -0
  165. package/assets/cmaps/UniKS-UTF16-V.bcmap +0 -0
  166. package/assets/cmaps/UniKS-UTF32-H.bcmap +0 -0
  167. package/assets/cmaps/UniKS-UTF32-V.bcmap +0 -0
  168. package/assets/cmaps/UniKS-UTF8-H.bcmap +0 -0
  169. package/assets/cmaps/UniKS-UTF8-V.bcmap +0 -0
  170. package/assets/cmaps/V.bcmap +0 -0
  171. package/assets/cmaps/WP-Symbol.bcmap +0 -0
  172. package/assets/pdf.min.mjs +28 -0
  173. package/assets/pdf.worker.min.mjs +28 -0
  174. package/assets/standard_fonts/FoxitDingbats.pfb +0 -0
  175. package/assets/standard_fonts/FoxitFixed.pfb +0 -0
  176. package/assets/standard_fonts/FoxitFixedBold.pfb +0 -0
  177. package/assets/standard_fonts/FoxitFixedBoldItalic.pfb +0 -0
  178. package/assets/standard_fonts/FoxitFixedItalic.pfb +0 -0
  179. package/assets/standard_fonts/FoxitSerif.pfb +0 -0
  180. package/assets/standard_fonts/FoxitSerifBold.pfb +0 -0
  181. package/assets/standard_fonts/FoxitSerifBoldItalic.pfb +0 -0
  182. package/assets/standard_fonts/FoxitSerifItalic.pfb +0 -0
  183. package/assets/standard_fonts/FoxitSymbol.pfb +0 -0
  184. package/assets/standard_fonts/LICENSE_FOXIT +27 -0
  185. package/assets/standard_fonts/LICENSE_LIBERATION +363 -0
  186. package/assets/standard_fonts/LiberationSans-Bold.ttf +0 -0
  187. package/assets/standard_fonts/LiberationSans-BoldItalic.ttf +0 -0
  188. package/assets/standard_fonts/LiberationSans-Italic.ttf +0 -0
  189. package/assets/standard_fonts/LiberationSans-Regular.ttf +0 -0
  190. package/assets/wasm/LICENSE_JBIG2 +196 -0
  191. package/assets/wasm/LICENSE_OPENJPEG +39 -0
  192. package/assets/wasm/LICENSE_PDFJS_JBIG2 +13 -0
  193. package/assets/wasm/LICENSE_PDFJS_OPENJPEG +22 -0
  194. package/assets/wasm/LICENSE_PDFJS_QCMS +19 -0
  195. package/assets/wasm/LICENSE_PDFJS_QUICKJS +21 -0
  196. package/assets/wasm/LICENSE_QCMS +21 -0
  197. package/assets/wasm/LICENSE_QUICKJS +22 -0
  198. package/assets/wasm/jbig2.wasm +0 -0
  199. package/assets/wasm/jbig2_nowasm_fallback.js +2 -0
  200. package/assets/wasm/openjpeg.wasm +0 -0
  201. package/assets/wasm/openjpeg_nowasm_fallback.js +2 -0
  202. package/assets/wasm/qcms_bg.wasm +0 -0
  203. package/assets/wasm/quickjs-eval.js +16 -0
  204. package/assets/wasm/quickjs-eval.wasm +0 -0
  205. package/client.js +9137 -0
  206. package/cordis.patch.yml +4 -0
  207. package/docs/DETAIL.md +37 -0
  208. package/icon.svg +7 -0
  209. package/index.js +1575 -0
  210. package/lib/deadline.js +49 -0
  211. package/lib/explain.js +168 -0
  212. package/lib/fingerprint.js +15 -0
  213. package/lib/guide.js +92 -0
  214. package/lib/migrate.js +59 -0
  215. package/lib/paths.js +15 -0
  216. package/lib/prefs.js +18 -0
  217. package/lib/reader-context.js +382 -0
  218. package/lib/sent.js +17 -0
  219. package/lib/store.js +319 -0
  220. package/lib/translate.js +48 -0
  221. package/locale/en.json +7 -0
  222. package/locale/zh.json +7 -0
  223. package/package.json +87 -4
package/index.js ADDED
@@ -0,0 +1,1575 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { resolveInWorkspace } from './lib/paths.js'
6
+ import { createDeadline } from './lib/deadline.js'
7
+ import { readStore, writeStore, mutateStore, upsertDoc, listBackups, restoreLatestBackup } from './lib/store.js'
8
+ import { recordSent } from './lib/sent.js'
9
+ import { blockHash } from './src/client/translate.js'
10
+ import { buildTranslatePrompt, parseTranslationReply, TRANSLATE_LANGUAGES, TRANSLATE_SOURCES } from './lib/translate.js'
11
+ import { docFingerprint } from './lib/fingerprint.js'
12
+ import { buildExplainPrompt, buildQuickExplainPrompt, parseExplanation, buildContextPrompt, parseContextNote, buildAskPrompt } from './lib/explain.js'
13
+ import { sectionHash, buildSectionPrompt, buildOverviewPrompt, buildPartPrompt, parseSectionReply, parseOverviewReply, parsePartReply } from './lib/guide.js'
14
+ import {
15
+ buildReaderContextPayload,
16
+ buildReaderReadPayload,
17
+ buildReadingReport,
18
+ MAX_SESSION_ID_CHARS,
19
+ pickReaderTarget,
20
+ readReadingContext,
21
+ sameReaderPosition,
22
+ writeReadingSession,
23
+ } from './lib/reader-context.js'
24
+
25
+ export const inject = ['webServer', 'sessionPersistence', 'llm', 'agentDefaultModel', 'workingDirectory', 'tools']
26
+
27
+ const ROOT = '/dsh-reader-live'
28
+ const inflightExplains = new Map()
29
+ const isRecordObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
30
+ const ASSET_DIR = fileURLToPath(new URL('./assets/', import.meta.url))
31
+ const MAX_FILE_BYTES = 200 * 1024 * 1024
32
+ const MAX_BODY_BYTES = 20 * 1024 * 1024
33
+
34
+ const MIME = {
35
+ '.pdf': 'application/pdf',
36
+ '.epub': 'application/epub+zip',
37
+ '.md': 'text/markdown; charset=utf-8',
38
+ '.markdown': 'text/markdown; charset=utf-8',
39
+ '.txt': 'text/plain; charset=utf-8',
40
+ '.png': 'image/png',
41
+ '.jpg': 'image/jpeg',
42
+ '.jpeg': 'image/jpeg',
43
+ '.gif': 'image/gif',
44
+ '.webp': 'image/webp',
45
+ '.avif': 'image/avif',
46
+ }
47
+
48
+ function json(value, status = 200) {
49
+ return new Response(JSON.stringify(value), {
50
+ status,
51
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
52
+ })
53
+ }
54
+
55
+ function httpError(status, message) {
56
+ const error = new Error(message)
57
+ error.status = status
58
+ return error
59
+ }
60
+
61
+ function normalizeTerm(term) {
62
+ return String(term || '').trim().toLowerCase()
63
+ }
64
+
65
+ function normalizeOccurrence(store, input) {
66
+ if (!input || typeof input !== 'object') throw httpError(400, 'invalid occurrence')
67
+ const docKey = typeof input.docKey === 'string' ? input.docKey : ''
68
+ if (!docKey) throw httpError(400, 'invalid docKey')
69
+ if (!store.docs || !store.docs[docKey]) throw httpError(400, 'unknown docKey')
70
+ return {
71
+ docKey,
72
+ chapter: Number.isFinite(input.chapter) ? input.chapter : 0,
73
+ page: Number.isFinite(input.page) ? input.page : undefined,
74
+ quote: typeof input.quote === 'string' ? input.quote : '',
75
+ occurrence: Number.isFinite(input.occurrence) ? input.occurrence : 0,
76
+ }
77
+ }
78
+
79
+ function sameOccurrence(left, right) {
80
+ return (
81
+ left.docKey === right.docKey &&
82
+ left.quote === right.quote &&
83
+ left.chapter === right.chapter &&
84
+ (left.page || 0) === (right.page || 0) &&
85
+ (left.occurrence || 0) === (right.occurrence || 0)
86
+ )
87
+ }
88
+
89
+ function addOccurrence(store, conceptId, input) {
90
+ const concept = store.concepts[conceptId]
91
+ if (!concept) throw httpError(400, 'unknown concept')
92
+ const occurrence = normalizeOccurrence(store, input)
93
+ if (!Array.isArray(concept.occurrences)) concept.occurrences = []
94
+ if (!concept.occurrences.some((item) => sameOccurrence(item, occurrence))) {
95
+ concept.occurrences.push(occurrence)
96
+ }
97
+ return concept
98
+ }
99
+
100
+ async function workspaceFor(ctx, sessionId) {
101
+ if (sessionId) {
102
+ // The slot may hand over a bare UUID or the stored `session-<uuid>` id.
103
+ const candidates = [sessionId]
104
+ candidates.push(sessionId.startsWith('session-') ? sessionId.slice(8) : `session-${sessionId}`)
105
+ for (const candidate of candidates) {
106
+ const snapshot = await ctx.sessionPersistence.stat(candidate).catch(() => undefined)
107
+ const cwd = snapshot?.header?.cwd
108
+ if (cwd) return cwd
109
+ }
110
+ throw httpError(400, 'session workspace unavailable')
111
+ }
112
+ throw httpError(400, 'sessionId required')
113
+ }
114
+
115
+ async function listDir(cwd, dir) {
116
+ const target = resolveInWorkspace(cwd, dir || '.')
117
+ if (!target.ok) return json({ error: target.code }, 403)
118
+ let entries
119
+ try {
120
+ entries = await fs.readdir(target.abs, { withFileTypes: true })
121
+ } catch {
122
+ return json({ error: 'directory unavailable' }, 404)
123
+ }
124
+ const rows = entries
125
+ .filter((entry) => !entry.name.startsWith('.'))
126
+ .map((entry) => ({
127
+ name: entry.name,
128
+ type: entry.isDirectory() ? 'dir' : 'file',
129
+ path: path.relative(cwd, path.join(target.abs, entry.name)),
130
+ }))
131
+ .sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'dir' ? -1 : 1))
132
+ return json({ cwd, dir: path.relative(cwd, target.abs) || '.', entries: rows })
133
+ }
134
+
135
+ async function readFile(cwd, rel) {
136
+ const target = resolveInWorkspace(cwd, rel)
137
+ if (!target.ok) return json({ error: target.code }, 403)
138
+ let stat
139
+ try {
140
+ stat = await fs.stat(target.abs)
141
+ } catch {
142
+ return json({ error: 'file not found' }, 404)
143
+ }
144
+ if (!stat.isFile()) return json({ error: 'not a file' }, 400)
145
+ if (stat.size > MAX_FILE_BYTES) return json({ error: 'file too large' }, 413)
146
+ let root
147
+ try {
148
+ root = await fs.realpath(cwd)
149
+ } catch {
150
+ root = path.resolve(cwd)
151
+ }
152
+ const real = await fs.realpath(target.abs).catch(() => null)
153
+ if (real && real !== root && !real.startsWith(root + path.sep)) return json({ error: 'ESCAPE' }, 403)
154
+ const bytes = await fs.readFile(target.abs)
155
+ const type = MIME[path.extname(target.abs).toLowerCase()] || 'application/octet-stream'
156
+ return new Response(bytes, {
157
+ headers: {
158
+ 'content-type': type,
159
+ 'cache-control': 'no-store',
160
+ 'x-content-type-options': 'nosniff',
161
+ 'x-doc-fingerprint': docFingerprint(bytes),
162
+ },
163
+ })
164
+ }
165
+
166
+ const ASSET_MIME = {
167
+ '.mjs': 'text/javascript; charset=utf-8',
168
+ '.wasm': 'application/wasm',
169
+ '.bcmap': 'application/octet-stream',
170
+ '.ttf': 'font/ttf',
171
+ '.otf': 'font/otf',
172
+ }
173
+
174
+ async function serveAsset(name) {
175
+ if (!/^[A-Za-z0-9._/-]+$/.test(name) || name.includes('..')) return json({ error: 'bad asset' }, 400)
176
+ const root = path.resolve(ASSET_DIR)
177
+ const abs = path.resolve(root, name)
178
+ if (!abs.startsWith(root + path.sep)) return json({ error: 'bad asset' }, 400)
179
+ try {
180
+ const bytes = await fs.readFile(abs)
181
+ return new Response(bytes, {
182
+ headers: {
183
+ 'content-type': ASSET_MIME[path.extname(abs).toLowerCase()] || 'application/octet-stream',
184
+ 'cache-control': 'public, max-age=3600',
185
+ },
186
+ })
187
+ } catch {
188
+ return json({ error: 'asset not found' }, 404)
189
+ }
190
+ }
191
+
192
+ function pluginModel(store, ctx) {
193
+ const pref = store?.prefs?.model
194
+ if (pref && pref.provider && pref.model) {
195
+ const current = ctx.agentDefaultModel?.currentSelection?.()
196
+ return { provider: pref.provider, model: pref.model, reasoningEffort: current?.reasoningEffort }
197
+ }
198
+ return ctx.agentDefaultModel?.currentSelection?.() || {}
199
+ }
200
+
201
+ const effortCache = new Map()
202
+
203
+ /**
204
+ * How long one reader-initiated explanation may run before it is aborted.
205
+ *
206
+ * Nothing else bounds this call: it runs outside the agent loop, so a provider
207
+ * stream that stalls without finishing or erroring would keep the request — and
208
+ * the reader's pending card — alive indefinitely. Override for slow providers.
209
+ */
210
+ const EXPLAIN_TIMEOUT_ENV = 'DSH_READER_EXPLAIN_TIMEOUT_MS'
211
+ const DEFAULT_EXPLAIN_TIMEOUT_MS = 90_000
212
+
213
+ function explainTimeoutMs() {
214
+ const configured = Number(process.env[EXPLAIN_TIMEOUT_ENV])
215
+ return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_EXPLAIN_TIMEOUT_MS
216
+ }
217
+
218
+ async function effortsFor(ctx, provider, model) {
219
+ const key = `${provider}|${model}`
220
+ if (effortCache.has(key)) return effortCache.get(key)
221
+ let efforts = []
222
+ try {
223
+ const info = await ctx.llm?.resolveModelInfo?.(provider, model)
224
+ efforts = (info?.reasoning?.efforts || []).map((effort) => effort.id)
225
+ } catch {
226
+ efforts = []
227
+ }
228
+ effortCache.set(key, efforts)
229
+ return efforts
230
+ }
231
+
232
+ async function pickEffort(ctx, provider, model, preferred) {
233
+ const efforts = await effortsFor(ctx, provider, model)
234
+ const order = [...new Set([preferred, 'low', 'minimal', 'medium', 'high', 'max'].filter(Boolean))]
235
+ return order.find((id) => efforts.includes(id)) || null
236
+ }
237
+
238
+ async function complete(
239
+ ctx,
240
+ { system, user, maxTokens = 700, signal: callerSignal, timeoutMs = 0, provider: providerOverride, model: modelOverride, reasoningEffort },
241
+ ) {
242
+ const selection = ctx.agentDefaultModel?.currentSelection?.()
243
+ const provider = providerOverride || selection?.provider
244
+ const model = modelOverride || selection?.model
245
+ if (!provider || !model) throw httpError(503, 'no model configured')
246
+ const deadline = createDeadline({ timeoutMs, signal: callerSignal })
247
+ const timeoutError = () => httpError(504, `model did not answer within ${timeoutMs}ms`)
248
+ let reply = ''
249
+ try {
250
+ const stream = ctx.llm.stream({
251
+ provider,
252
+ model,
253
+ ...(reasoningEffort ? { reasoningEffort } : {}),
254
+ system,
255
+ messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
256
+ maxTokens,
257
+ temperature: 0.2,
258
+ signal: deadline.signal,
259
+ })
260
+ for await (const chunk of stream) {
261
+ if (chunk.type === 'text-delta') reply += chunk.text
262
+ if (chunk.type === 'finish' && chunk.reason?.kind === 'error') {
263
+ throw httpError(502, chunk.reason.failure?.message || 'model error')
264
+ }
265
+ }
266
+ } catch (error) {
267
+ // The aborted stream usually surfaces as its own error; report our deadline
268
+ // instead, because "the provider never answered" is the useful diagnosis.
269
+ if (deadline.timedOut) throw timeoutError()
270
+ throw error
271
+ } finally {
272
+ deadline.dispose()
273
+ }
274
+ if (deadline.timedOut) throw timeoutError()
275
+ return reply
276
+ }
277
+
278
+ const MAX_ANCESTOR_DEPTH = 4
279
+
280
+ /**
281
+ * The cards the reader came through, farthest ancestor first. Parents are only
282
+ * ever set to an already-stored concept, but the walk keeps a visited set so a
283
+ * hand-edited or migrated store can never spin here.
284
+ */
285
+ function ancestorChain(concepts, startId) {
286
+ const chain = []
287
+ const seen = new Set()
288
+ let current = typeof startId === 'string' && startId ? concepts?.[startId] : null
289
+ while (current && chain.length < MAX_ANCESTOR_DEPTH) {
290
+ const id = typeof current.id === 'string' && current.id ? current.id : null
291
+ if (!id || seen.has(id)) break
292
+ seen.add(id)
293
+ chain.push(current)
294
+ current = current.parentId ? concepts?.[current.parentId] : null
295
+ }
296
+ return chain.reverse()
297
+ }
298
+
299
+ async function explainConcept(ctx, cwd, body) {
300
+ const term = String(body?.term || '').trim()
301
+ if (!term) throw httpError(400, 'term required')
302
+ const sentence = String(body?.sentence || '')
303
+ const paragraph = String(body?.paragraph || '')
304
+ const store = await readStore(cwd)
305
+ const key = normalizeTerm(term)
306
+ const existing = Object.values(store.concepts).find((concept) => {
307
+ if (!concept || typeof concept !== 'object') return false
308
+ if (normalizeTerm(concept.term) === key) return true
309
+ return Array.isArray(concept.aliases) && concept.aliases.some((alias) => normalizeTerm(alias) === key)
310
+ })
311
+ const model = pluginModel(store, ctx)
312
+ const ancestors = ancestorChain(store.concepts, body?.parentId)
313
+ const depth = body?.depth === 'full' ? 'full' : 'quick'
314
+ if (existing) {
315
+ // Asking about a concept that is already on the path the reader came down
316
+ // would hand back the very card that raised the question. Reuse it as a
317
+ // step back up instead of re-explaining it against itself.
318
+ if (ancestors.some((item) => item.id === existing.id)) {
319
+ return {
320
+ concept: existing,
321
+ reused: true,
322
+ ancestor: true,
323
+ route: 'ancestor',
324
+ chain: ancestors.map((item) => ({ id: item.id, term: item.term })),
325
+ }
326
+ }
327
+ if (depth === 'full' && existing.depth !== 'full' && existing.source !== 'user') {
328
+ const { system, user } = buildExplainPrompt({
329
+ term: existing.term,
330
+ sentence,
331
+ paragraph,
332
+ docTitle: body?.docTitle,
333
+ ancestors,
334
+ })
335
+ const parsed = parseExplanation(
336
+ await complete(ctx, {
337
+ system,
338
+ user,
339
+ maxTokens: 1600,
340
+ timeoutMs: explainTimeoutMs(),
341
+ provider: model.provider,
342
+ model: model.model,
343
+ }),
344
+ )
345
+ const stored = await mutateStore(cwd, (current) => {
346
+ const target = current.concepts[existing.id]
347
+ if (target && target.source !== 'user') {
348
+ target.definition = parsed.definition || target.definition
349
+ target.intuition = parsed.intuition || target.intuition
350
+ target.context = parsed.context || target.context
351
+ target.examples = parsed.examples && parsed.examples.length ? parsed.examples : target.examples
352
+ target.depth = 'full'
353
+ target.updatedAt = Date.now()
354
+ }
355
+ recordSent(current, {
356
+ kind: 'explain',
357
+ preview: term,
358
+ chars: String(body?.sentence || '').length + String(body?.paragraph || '').length,
359
+ })
360
+ if (body?.docKey) addOccurrence(current, existing.id, body)
361
+ return current
362
+ })
363
+ return { concept: stored.concepts[existing.id], reused: false, upgraded: true, route: 'full', store: stored }
364
+ }
365
+ if (body?.docKey) {
366
+ const contexts = Array.isArray(existing.contexts) ? existing.contexts : []
367
+ const needsContext =
368
+ depth === 'full' &&
369
+ Boolean(body.sentence) &&
370
+ Boolean(existing.evidence?.docKey) &&
371
+ existing.evidence.docKey !== body.docKey &&
372
+ !contexts.some((entry) => entry.docKey === body.docKey)
373
+ let note = ''
374
+ if (needsContext) {
375
+ const prompt = buildContextPrompt({
376
+ term: existing.term,
377
+ sentence: body.sentence,
378
+ docTitle: body.docTitle,
379
+ })
380
+ note = parseContextNote(
381
+ await complete(ctx, {
382
+ ...prompt,
383
+ maxTokens: 400,
384
+ timeoutMs: explainTimeoutMs(),
385
+ provider: model.provider,
386
+ model: model.model,
387
+ }),
388
+ ).note
389
+ }
390
+ const stored = await mutateStore(cwd, (current) => {
391
+ recordSent(current, {
392
+ kind: 'explain',
393
+ preview: term,
394
+ chars: String(body.sentence || '').length + String(body.paragraph || '').length,
395
+ })
396
+ const concept = addOccurrence(current, existing.id, body)
397
+ if (needsContext && note) {
398
+ if (!Array.isArray(concept.contexts)) concept.contexts = []
399
+ if (!concept.contexts.some((entry) => entry.docKey === body.docKey)) {
400
+ concept.contexts.push({
401
+ docKey: body.docKey,
402
+ note,
403
+ quote: String(body.quote || '').slice(0, 200),
404
+ at: Date.now(),
405
+ })
406
+ if (concept.contexts.length > 5) concept.contexts = concept.contexts.slice(-5)
407
+ }
408
+ }
409
+ return current
410
+ })
411
+ return { concept: stored.concepts[existing.id], reused: true, route: 'cached', store: stored }
412
+ }
413
+ return { concept: existing, reused: true, route: 'cached' }
414
+ }
415
+
416
+ const quick = depth === 'quick'
417
+ const { system, user } = quick
418
+ ? buildQuickExplainPrompt({ term, sentence, docTitle: body?.docTitle, ancestors })
419
+ : buildExplainPrompt({ term, sentence, paragraph, docTitle: body?.docTitle, ancestors })
420
+ const quickEffort = quick ? await pickEffort(ctx, model.provider, model.model, 'low') : null
421
+ // Single-flight: two readers explaining the same term share one model call.
422
+ const inflightKey = `${cwd}|${key}|${depth}`
423
+ let pending = inflightExplains.get(inflightKey)
424
+ if (!pending) {
425
+ pending = complete(ctx, {
426
+ system,
427
+ user,
428
+ // The whole budget, not just the JSON: a reasoning model spends tokens
429
+ // before it emits anything. 260 truncated the quick explanation and hid
430
+ // the real failure behind an unusable reply; the guide path uses 900 for
431
+ // a comparable single call.
432
+ maxTokens: quick ? 900 : 1600,
433
+ timeoutMs: explainTimeoutMs(),
434
+ provider: model.provider,
435
+ model: model.model,
436
+ ...(quickEffort ? { reasoningEffort: quickEffort } : {}),
437
+ }).then((reply) => parseExplanation(reply))
438
+ inflightExplains.set(inflightKey, pending)
439
+ pending.finally(() => inflightExplains.delete(inflightKey)).catch(() => {})
440
+ }
441
+ const parsed = await pending
442
+ const concept = {
443
+ id: randomUUID(),
444
+ term,
445
+ aliases: [],
446
+ ...parsed,
447
+ parentId: typeof body?.parentId === 'string' && body.parentId ? body.parentId : null,
448
+ evidence: {
449
+ docKey: typeof body?.docKey === 'string' ? body.docKey : null,
450
+ quote: String(body?.quote || '').slice(0, 300),
451
+ sentence: String(body?.sentence || '').slice(0, 500),
452
+ },
453
+ depth,
454
+ qa: [],
455
+ status: 'ready',
456
+ source: 'agent',
457
+ createdAt: Date.now(),
458
+ updatedAt: Date.now(),
459
+ }
460
+ // Merge against the latest store under the per-workspace write queue: two
461
+ // explanations finishing together must not overwrite each other.
462
+ const stored = await mutateStore(cwd, (current) => {
463
+ recordSent(current, {
464
+ kind: 'explain',
465
+ preview: term,
466
+ chars: String(body?.sentence || '').length + String(body?.paragraph || '').length,
467
+ })
468
+ const found = Object.values(current.concepts).find((item) => normalizeTerm(item.term) === key)
469
+ if (found) {
470
+ if (body?.docKey) addOccurrence(current, found.id, body)
471
+ return current
472
+ }
473
+ current.concepts[concept.id] = { ...concept, occurrences: [] }
474
+ if (body?.docKey) addOccurrence(current, concept.id, body)
475
+ return current
476
+ })
477
+ const finalConcept =
478
+ stored.concepts[concept.id] ||
479
+ Object.values(stored.concepts).find((item) => normalizeTerm(item.term) === key) ||
480
+ concept
481
+ return { concept: finalConcept, route: depth, store: stored }
482
+ }
483
+
484
+ function send(res, status, value) {
485
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
486
+ res.end(JSON.stringify(value))
487
+ }
488
+
489
+ function handleRouteError(res, error) {
490
+ const status = typeof error?.status === 'number' ? error.status : 400
491
+ send(res, status, { error: String(error?.message || error) })
492
+ }
493
+
494
+ async function readBody(req) {
495
+ const chunks = []
496
+ let size = 0
497
+ for await (const chunk of req) {
498
+ size += chunk.length
499
+ if (size > MAX_BODY_BYTES) throw httpError(413, 'body too large')
500
+ chunks.push(chunk)
501
+ }
502
+ return size > 0 ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}
503
+ }
504
+
505
+ async function storeRoute(ctx, req, res) {
506
+ try {
507
+ const url = new URL(req.url, 'http://local')
508
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
509
+ if (req.method !== 'GET') {
510
+ send(res, 405, { error: 'method not allowed' })
511
+ return
512
+ }
513
+ send(res, 200, { store: await readStore(cwd) })
514
+ } catch (error) {
515
+ handleRouteError(res, error)
516
+ }
517
+ }
518
+
519
+ function docOf(store, docKey) {
520
+ if (!store.docs || typeof store.docs !== 'object') store.docs = {}
521
+ if (!store.docs[docKey]) {
522
+ store.docs[docKey] = { path: '', size: 0, mtime: 0, annotations: [], positions: {} }
523
+ }
524
+ const doc = store.docs[docKey]
525
+ if (!Array.isArray(doc.annotations)) doc.annotations = []
526
+ if (!doc.positions || typeof doc.positions !== 'object') doc.positions = {}
527
+ return doc
528
+ }
529
+
530
+ function applyPrefs(store, patch) {
531
+ if (!patch || typeof patch !== 'object') throw httpError(400, 'invalid prefs')
532
+ const next = { ...(store.prefs || {}) }
533
+ if ('fontSize' in patch) {
534
+ const value = Number(patch.fontSize)
535
+ if (!Number.isFinite(value) || value < 14 || value > 26) throw httpError(400, 'invalid fontSize')
536
+ next.fontSize = value
537
+ }
538
+ if ('lineHeight' in patch) {
539
+ const value = Number(patch.lineHeight)
540
+ if (!Number.isFinite(value) || value < 1.2 || value > 2.4) throw httpError(400, 'invalid lineHeight')
541
+ next.lineHeight = value
542
+ }
543
+ if ('hoverDelay' in patch) {
544
+ const value = Number(patch.hoverDelay)
545
+ if (!Number.isFinite(value) || value < 80 || value > 600) throw httpError(400, 'invalid hoverDelay')
546
+ next.hoverDelay = value
547
+ }
548
+ if ('chatWidth' in patch) {
549
+ const value = Number(patch.chatWidth)
550
+ if (!Number.isFinite(value) || value < 320 || value > 720) throw httpError(400, 'invalid chatWidth')
551
+ next.chatWidth = value
552
+ }
553
+ if ('cardTrigger' in patch) {
554
+ if (!['hover', 'click', 'off'].includes(patch.cardTrigger)) throw httpError(400, 'invalid cardTrigger')
555
+ next.cardTrigger = patch.cardTrigger
556
+ }
557
+ if ('model' in patch) {
558
+ if (patch.model === null || patch.model === undefined) {
559
+ next.model = null
560
+ } else if (
561
+ typeof patch.model === 'object' &&
562
+ typeof patch.model.provider === 'string' &&
563
+ patch.model.provider &&
564
+ typeof patch.model.model === 'string' &&
565
+ patch.model.model
566
+ ) {
567
+ next.model = { provider: patch.model.provider.slice(0, 120), model: patch.model.model.slice(0, 120) }
568
+ } else {
569
+ throw httpError(400, 'invalid model')
570
+ }
571
+ }
572
+ if ('guideDepth' in patch) {
573
+ if (!['quick', 'standard'].includes(patch.guideDepth)) throw httpError(400, 'invalid guideDepth')
574
+ next.guideDepth = patch.guideDepth
575
+ }
576
+ if ('translateTo' in patch) {
577
+ if (!['zh', 'en', 'ja'].includes(patch.translateTo)) throw httpError(400, 'invalid translateTo')
578
+ next.translateTo = patch.translateTo
579
+ }
580
+ if ('pageKeys' in patch) {
581
+ if (!['arrows', 'jk'].includes(patch.pageKeys)) throw httpError(400, 'invalid pageKeys')
582
+ next.pageKeys = patch.pageKeys
583
+ }
584
+ if ('pdfSpread' in patch) {
585
+ next.pdfSpread = Boolean(patch.pdfSpread)
586
+ }
587
+ if ('theme' in patch) {
588
+ if (!['system', 'light', 'dark', 'sepia'].includes(patch.theme)) throw httpError(400, 'invalid theme')
589
+ next.theme = patch.theme
590
+ }
591
+ store.prefs = next
592
+ return store
593
+ }
594
+
595
+ function applyMutation(store, body) {
596
+ const op = body?.op
597
+ if (op === 'concept/upsert') {
598
+ const concept = body.concept
599
+ if (!concept || typeof concept !== 'object' || typeof concept.id !== 'string' || typeof concept.term !== 'string') {
600
+ throw httpError(400, 'invalid concept')
601
+ }
602
+ store.concepts[concept.id] = { ...(store.concepts[concept.id] || {}), ...concept }
603
+ return store
604
+ }
605
+ if (op === 'concept/delete') {
606
+ if (typeof body.id !== 'string') throw httpError(400, 'invalid id')
607
+ const removed = store.concepts[body.id]
608
+ delete store.concepts[body.id]
609
+ if (removed) {
610
+ // Cards explained inside this one were drawn from its context. Promoting
611
+ // them keeps a single chain instead of leaving a parentId that resolves
612
+ // to nothing.
613
+ const parentId =
614
+ typeof removed.parentId === 'string' && store.concepts[removed.parentId] ? removed.parentId : null
615
+ for (const concept of Object.values(store.concepts)) {
616
+ if (concept && concept.parentId === body.id) concept.parentId = parentId
617
+ }
618
+ }
619
+ return store
620
+ }
621
+ if (op === 'prefs/set') {
622
+ return applyPrefs(store, body.prefs)
623
+ }
624
+ if (op === 'concept/merge') {
625
+ const { fromId, toId } = body
626
+ if (typeof fromId !== 'string' || typeof toId !== 'string' || fromId === toId) {
627
+ throw httpError(400, 'invalid merge')
628
+ }
629
+ const source = store.concepts[fromId]
630
+ const target = store.concepts[toId]
631
+ if (!source || !target) throw httpError(400, 'unknown concept')
632
+ const unique = (list) => [...new Set(list.filter(Boolean))]
633
+ target.aliases = unique([...(target.aliases || []), source.term, ...(source.aliases || [])]).filter(
634
+ (alias) => alias !== target.term,
635
+ )
636
+ target.related = unique([...(target.related || []), ...(source.related || [])])
637
+ const occKey = (item) => `${item.docKey}|${item.quote}|${item.chapter || 0}|${item.page || 0}|${item.occurrence || 0}`
638
+ const occurrences = new Map()
639
+ for (const item of [...(target.occurrences || []), ...(source.occurrences || [])]) occurrences.set(occKey(item), item)
640
+ target.occurrences = [...occurrences.values()]
641
+ const contexts = new Map()
642
+ for (const item of [...(target.contexts || []), ...(source.contexts || [])]) contexts.set(item.docKey, item)
643
+ target.contexts = [...contexts.values()].slice(-5)
644
+ target.qa = [...(target.qa || []), ...(source.qa || [])].slice(-20)
645
+ target.updatedAt = Date.now()
646
+ delete store.concepts[fromId]
647
+ return store
648
+ }
649
+ if (op === 'doc/relink') {
650
+ const { fromKey, toKey } = body
651
+ if (typeof fromKey !== 'string' || typeof toKey !== 'string' || fromKey === toKey) {
652
+ throw httpError(400, 'invalid relink')
653
+ }
654
+ const source = store.docs && store.docs[fromKey]
655
+ if (!source) throw httpError(400, 'unknown doc')
656
+ const target = docOf(store, toKey)
657
+ if (!target.path && source.path) target.path = source.path
658
+ const seen = new Set(target.annotations.map((item) => item && item.id))
659
+ for (const annotation of source.annotations || []) {
660
+ if (annotation && annotation.id && !seen.has(annotation.id)) target.annotations.push(annotation)
661
+ }
662
+ if (!target.guide && source.guide) target.guide = source.guide
663
+ if (!target.positions || Object.keys(target.positions).length === 0) target.positions = source.positions || {}
664
+ delete store.docs[fromKey]
665
+ return store
666
+ }
667
+ if (op === 'occurrence/add') {
668
+ if (typeof body.conceptId !== 'string') throw httpError(400, 'invalid concept')
669
+ addOccurrence(store, body.conceptId, body.occurrence)
670
+ return store
671
+ }
672
+ if (op === 'doc/upsert') {
673
+ const { docKey, path, size, mtime } = body
674
+ if (typeof docKey !== 'string' || !docKey) throw httpError(400, 'invalid docKey')
675
+ upsertDoc(store, { docKey, path, size, mtime })
676
+ return store
677
+ }
678
+ if (op === 'annotation/add' || op === 'annotation/update') {
679
+ const { docKey, annotation } = body
680
+ if (typeof docKey !== 'string' || !annotation || typeof annotation.id !== 'string') {
681
+ throw httpError(400, 'invalid annotation')
682
+ }
683
+ const doc = docOf(store, docKey)
684
+ const index = doc.annotations.findIndex((item) => item && item.id === annotation.id)
685
+ if (index >= 0) doc.annotations[index] = { ...doc.annotations[index], ...annotation }
686
+ else doc.annotations.push(annotation)
687
+ return store
688
+ }
689
+ if (op === 'annotation/remove') {
690
+ const { docKey } = body
691
+ if (typeof docKey !== 'string' || typeof body.id !== 'string') throw httpError(400, 'invalid annotation')
692
+ const doc = docOf(store, docKey)
693
+ doc.annotations = doc.annotations.filter((item) => item && item.id !== body.id)
694
+ return store
695
+ }
696
+ if (op === 'position/set') {
697
+ const { docKey, position } = body
698
+ if (typeof docKey !== 'string' || !position || typeof position !== 'object') throw httpError(400, 'invalid position')
699
+ docOf(store, docKey).positions = position
700
+ return store
701
+ }
702
+ throw httpError(400, 'unknown op')
703
+ }
704
+
705
+ async function mutateRoute(ctx, req, res) {
706
+ try {
707
+ const url = new URL(req.url, 'http://local')
708
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
709
+ const body = await readBody(req)
710
+ const store = await mutateStore(cwd, (current) => applyMutation(current, body))
711
+ send(res, 200, { store })
712
+ } catch (error) {
713
+ handleRouteError(res, error)
714
+ }
715
+ }
716
+
717
+ /**
718
+ * Leave a breadcrumb when an explanation fails.
719
+ *
720
+ * A failed explain used to leave no trace at all — no store write, no log — so
721
+ * the only symptom was a card that never stopped spinning. Recording the last
722
+ * few failures makes the next report diagnosable.
723
+ */
724
+ async function recordExplainFailure(cwd, body, error) {
725
+ if (!cwd) return
726
+ const entry = {
727
+ at: Date.now(),
728
+ route: 'explain',
729
+ term: String(body?.term || '').slice(0, 80),
730
+ depth: body?.depth === 'full' ? 'full' : 'quick',
731
+ status: typeof error?.status === 'number' ? error.status : 0,
732
+ message: String(error?.message || error).slice(0, 300),
733
+ }
734
+ try {
735
+ await mutateStore(cwd, (current) => {
736
+ current.debug.lastError = entry
737
+ const failures = Array.isArray(current.debug.errors) ? current.debug.errors : []
738
+ current.debug.errors = [...failures, entry].slice(-5)
739
+ return current
740
+ })
741
+ } catch {
742
+ // Diagnostics must never mask the failure the caller asked about.
743
+ }
744
+ }
745
+
746
+ async function explainRoute(ctx, req, res) {
747
+ let cwd = ''
748
+ let body = null
749
+ try {
750
+ const url = new URL(req.url, 'http://local')
751
+ cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
752
+ body = await readBody(req)
753
+ send(res, 200, await explainConcept(ctx, cwd, body))
754
+ } catch (error) {
755
+ await recordExplainFailure(cwd, body, error)
756
+ handleRouteError(res, error)
757
+ }
758
+ }
759
+
760
+ async function guideRoute(ctx, req, res) {
761
+ const url = new URL(req.url, 'http://local')
762
+ const streaming = url.searchParams.get('stream') === '1'
763
+ let finished = false
764
+ const controller = new AbortController()
765
+ const writeEvent = (event) => {
766
+ if (!streaming) return
767
+ try {
768
+ res.write(`${JSON.stringify(event)}\n`)
769
+ } catch {
770
+ /* client went away */
771
+ }
772
+ }
773
+ try {
774
+ if (typeof res.on === 'function') {
775
+ res.on('close', () => {
776
+ if (!finished) controller.abort()
777
+ })
778
+ }
779
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
780
+ const body = await readBody(req)
781
+ const docKey = String(body?.docKey || '')
782
+ const inputSections = Array.isArray(body?.sections) ? body.sections : []
783
+ const inputParts = Array.isArray(body?.parts) && body.parts.length > 0 ? body.parts : null
784
+ if (!docKey || inputSections.length === 0) throw httpError(400, 'docKey and sections required')
785
+ if (inputSections.length > 96) throw httpError(400, 'too many sections')
786
+ if (inputParts) {
787
+ if (inputParts.length > 32) throw httpError(400, 'too many parts')
788
+ const sectionIds = new Set(inputSections.map((section) => String(section?.id || '')))
789
+ for (const part of inputParts) {
790
+ if (!part || typeof part.id !== 'string' || !part.id) throw httpError(400, 'part id required')
791
+ if (!Array.isArray(part.sectionIds) || part.sectionIds.length === 0) throw httpError(400, 'part sections required')
792
+ for (const id of part.sectionIds) {
793
+ if (!sectionIds.has(String(id))) throw httpError(400, 'part references an unknown section')
794
+ }
795
+ }
796
+ }
797
+ let totalChars = 0
798
+ for (const input of inputSections) {
799
+ const length = String(input?.text || '').length
800
+ if (length > 8000) throw httpError(400, 'section too large')
801
+ totalChars += length
802
+ }
803
+ if (totalChars > 400000) throw httpError(400, 'document too large')
804
+
805
+ const store = await readStore(cwd)
806
+ if (!store.docs || !store.docs[docKey]) throw httpError(400, 'unknown docKey')
807
+ const previous = store.docs[docKey].guide
808
+ const previousById = new Map(((previous && previous.sections) || []).map((section) => [section.id, section]))
809
+ const previousParts = new Map(((previous && previous.parts) || []).map((part) => [part.id, part]))
810
+
811
+ if (streaming) {
812
+ res.writeHead(200, {
813
+ 'content-type': 'application/x-ndjson; charset=utf-8',
814
+ 'cache-control': 'no-store',
815
+ })
816
+ }
817
+
818
+ const model = pluginModel(store, ctx)
819
+ const sectionEffort = await pickEffort(ctx, model.provider, model.model, 'low')
820
+ const overviewEffort = await pickEffort(ctx, model.provider, model.model, 'medium')
821
+ const summaries = []
822
+ let generated = 0
823
+ let reused = 0
824
+ for (const input of inputSections) {
825
+ const id = String(input?.id || '')
826
+ if (!id) throw httpError(400, 'section id required')
827
+ const text = String(input.text || '')
828
+ const hash = sectionHash(text)
829
+ const cached = previousById.get(id)
830
+ if (cached && cached.hash === hash && cached.summary) {
831
+ summaries.push({
832
+ id,
833
+ title: String(input.title || cached.title || ''),
834
+ level: Number.isFinite(input.level) ? input.level : cached.level || 1,
835
+ ...(Number.isFinite(input.page) ? { page: input.page } : Number.isFinite(cached.page) ? { page: cached.page } : {}),
836
+ ...(Number.isFinite(input.chapter) ? { chapter: input.chapter } : Number.isFinite(cached.chapter) ? { chapter: cached.chapter } : {}),
837
+ hash,
838
+ summary: cached.summary,
839
+ keyPoints: cached.keyPoints || [],
840
+ })
841
+ reused += 1
842
+ } else {
843
+ const prompt = buildSectionPrompt({ title: input.title, text })
844
+ let parsed = parseSectionReply(
845
+ await complete(ctx, {
846
+ ...prompt,
847
+ maxTokens: 900,
848
+ signal: controller.signal,
849
+ provider: model.provider,
850
+ model: model.model,
851
+ reasoningEffort: sectionEffort,
852
+ }),
853
+ )
854
+ if (!parsed.summary) {
855
+ parsed = parseSectionReply(
856
+ await complete(ctx, {
857
+ ...prompt,
858
+ maxTokens: 900,
859
+ signal: controller.signal,
860
+ provider: model.provider,
861
+ model: model.model,
862
+ reasoningEffort: sectionEffort,
863
+ }),
864
+ )
865
+ }
866
+ if (!parsed.summary) throw httpError(502, 'empty guide section')
867
+ summaries.push({
868
+ id,
869
+ title: String(input.title || ''),
870
+ level: Number.isFinite(input.level) ? input.level : 1,
871
+ ...(Number.isFinite(input.page) ? { page: input.page } : {}),
872
+ ...(Number.isFinite(input.chapter) ? { chapter: input.chapter } : {}),
873
+ hash,
874
+ ...parsed,
875
+ })
876
+ generated += 1
877
+ }
878
+ writeEvent({
879
+ type: 'progress',
880
+ phase: 'section',
881
+ done: summaries.length,
882
+ total: inputSections.length,
883
+ title: String(input.title || ''),
884
+ })
885
+ }
886
+
887
+ const summaryById = new Map(summaries.map((section) => [section.id, section]))
888
+ let partSummaries = []
889
+ let partsGenerated = 0
890
+ if (inputParts) {
891
+ for (const [index, part] of inputParts.entries()) {
892
+ const members = part.sectionIds.map((id) => summaryById.get(String(id))).filter(Boolean)
893
+ if (members.length === 0) continue
894
+ const hash = sectionHash(members.map((member) => `${member.title}:${member.hash}`).join('|'))
895
+ if (members.length === 1) {
896
+ const member = members[0]
897
+ partSummaries.push({
898
+ id: part.id,
899
+ title: String(part.title || member.title || ''),
900
+ sectionIds: part.sectionIds.map(String),
901
+ hash,
902
+ summary: member.summary,
903
+ keyPoints: member.keyPoints || [],
904
+ reuseSection: true,
905
+ })
906
+ writeEvent({ type: 'progress', phase: 'part', done: index + 1, total: inputParts.length, title: String(part.title || '') })
907
+ continue
908
+ }
909
+ const cached = previousParts.get(part.id)
910
+ if (cached && cached.hash === hash && cached.summary) {
911
+ partSummaries.push({
912
+ id: part.id,
913
+ title: String(part.title || cached.title || ''),
914
+ sectionIds: part.sectionIds.map(String),
915
+ hash,
916
+ summary: cached.summary,
917
+ keyPoints: cached.keyPoints || [],
918
+ })
919
+ } else {
920
+ const prompt = buildPartPrompt({ title: part.title, sections: members })
921
+ let parsed = parsePartReply(
922
+ await complete(ctx, {
923
+ ...prompt,
924
+ maxTokens: 800,
925
+ signal: controller.signal,
926
+ provider: model.provider,
927
+ model: model.model,
928
+ reasoningEffort: sectionEffort,
929
+ }),
930
+ )
931
+ if (!parsed.summary) {
932
+ parsed = parsePartReply(
933
+ await complete(ctx, {
934
+ ...prompt,
935
+ maxTokens: 800,
936
+ signal: controller.signal,
937
+ provider: model.provider,
938
+ model: model.model,
939
+ reasoningEffort: sectionEffort,
940
+ }),
941
+ )
942
+ }
943
+ if (!parsed.summary) throw httpError(502, 'empty guide part')
944
+ partSummaries.push({
945
+ id: part.id,
946
+ title: String(part.title || ''),
947
+ sectionIds: part.sectionIds.map(String),
948
+ hash,
949
+ ...parsed,
950
+ })
951
+ partsGenerated += 1
952
+ }
953
+ writeEvent({
954
+ type: 'progress',
955
+ phase: 'part',
956
+ done: index + 1,
957
+ total: inputParts.length,
958
+ title: String(part.title || ''),
959
+ })
960
+ }
961
+ }
962
+
963
+ let synopsis = (previous && previous.synopsis) || ''
964
+ let questions = (previous && previous.questions) || []
965
+ const overviewInput = partSummaries.length > 0 ? partSummaries : summaries
966
+ if (generated > 0 || partsGenerated > 0 || !synopsis) {
967
+ const reply = await complete(ctx, {
968
+ ...buildOverviewPrompt(overviewInput),
969
+ maxTokens: 900,
970
+ signal: controller.signal,
971
+ provider: model.provider,
972
+ model: model.model,
973
+ reasoningEffort: overviewEffort,
974
+ })
975
+ const parsed = parseOverviewReply(reply)
976
+ synopsis = parsed.synopsis
977
+ questions = parsed.questions
978
+ }
979
+
980
+ const guide = {
981
+ generatedAt: Date.now(),
982
+ synopsis,
983
+ questions,
984
+ ...(partSummaries.length > 0 ? { parts: partSummaries } : {}),
985
+ sections: summaries,
986
+ }
987
+ const stored = await mutateStore(cwd, (current) => {
988
+ docOf(current, docKey).guide = guide
989
+ recordSent(current, { kind: 'guide', preview: String(body?.title || docKey), chars: totalChars })
990
+ return current
991
+ })
992
+ if (streaming) {
993
+ res.write(`${JSON.stringify({ type: 'done', guide, reused, generated, partsGenerated, store: stored })}\n`)
994
+ finished = true
995
+ res.end()
996
+ } else {
997
+ finished = true
998
+ send(res, 200, { guide, reused, generated, partsGenerated, store: stored })
999
+ }
1000
+ } catch (error) {
1001
+ if (streaming) {
1002
+ try {
1003
+ res.write(`${JSON.stringify({ type: 'error', error: String(error?.message || error) })}\n`)
1004
+ res.end()
1005
+ } catch {
1006
+ /* socket already closed */
1007
+ }
1008
+ return
1009
+ }
1010
+ handleRouteError(res, error)
1011
+ }
1012
+ }
1013
+
1014
+ async function searchForAsk(ctx, query, provider) {
1015
+ const web = typeof ctx.get === 'function' ? ctx.get('web') : null
1016
+ if (!web || typeof web.search !== 'function') return { used: false, error: 'web search unavailable' }
1017
+ try {
1018
+ if (typeof web.searchReady === 'function') {
1019
+ const ready = await web.searchReady(provider)
1020
+ if (!ready) return { used: false, error: 'web search not configured' }
1021
+ }
1022
+ const result = await web.search({ query: String(query).slice(0, 200), maxResults: 5, llmProvider: provider })
1023
+ const sources = (result.sources || []).slice(0, 5).map((source) => ({
1024
+ title: source.title || source.url,
1025
+ url: source.url,
1026
+ snippet: String(source.snippet || source.summary || '').slice(0, 200),
1027
+ }))
1028
+ return { used: true, content: String(result.content || '').slice(0, 1500), sources }
1029
+ } catch (error) {
1030
+ return { used: false, error: String(error?.message || error) }
1031
+ }
1032
+ }
1033
+
1034
+ async function askRoute(ctx, req, res) {
1035
+ try {
1036
+ const url = new URL(req.url, 'http://local')
1037
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
1038
+ const body = await readBody(req)
1039
+ const conceptId = String(body?.conceptId || '')
1040
+ const question = String(body?.question || '').trim()
1041
+ if (!conceptId) throw httpError(400, 'conceptId required')
1042
+ if (!question) throw httpError(400, 'question required')
1043
+ if (question.length > 500) throw httpError(400, 'question too long')
1044
+ const store = await readStore(cwd)
1045
+ const concept = store.concepts[conceptId]
1046
+ if (!concept) throw httpError(400, 'unknown concept')
1047
+
1048
+ const related = (Array.isArray(concept.related) ? concept.related : [])
1049
+ .map((term) => Object.values(store.concepts).find((item) => item.term === term))
1050
+ .filter(Boolean)
1051
+ .slice(0, 3)
1052
+ const model = pluginModel(store, ctx)
1053
+ const wantsWeb = body?.web === true
1054
+ const web = wantsWeb ? await searchForAsk(ctx, `${concept.term || ''} ${question}`, model.provider) : null
1055
+ const prompt = buildAskPrompt({ concept, question, related, web })
1056
+ const answer = (await complete(ctx, { ...prompt, maxTokens: 420, provider: model.provider, model: model.model })).trim().slice(0, 800)
1057
+ const webInfo = web
1058
+ ? { used: Boolean(web.used), error: web.error || null, sources: web.used ? web.sources || [] : [] }
1059
+ : null
1060
+
1061
+ const stored = await mutateStore(cwd, (current) => {
1062
+ recordSent(current, { kind: 'ask', preview: question, chars: question.length })
1063
+ const target = current.concepts[conceptId]
1064
+ if (!target) throw httpError(400, 'unknown concept')
1065
+ if (!Array.isArray(target.qa)) target.qa = []
1066
+ target.qa.push({ q: question, a: answer, at: Date.now(), ...(webInfo ? { web: webInfo } : {}) })
1067
+ if (target.qa.length > 20) target.qa = target.qa.slice(-20)
1068
+ return current
1069
+ })
1070
+ send(res, 200, { answer, web: webInfo, store: stored })
1071
+ } catch (error) {
1072
+ handleRouteError(res, error)
1073
+ }
1074
+ }
1075
+
1076
+ async function exportRoute(ctx, req, res) {
1077
+ try {
1078
+ const url = new URL(req.url, 'http://local')
1079
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
1080
+ const store = await readStore(cwd)
1081
+ const payload = JSON.stringify({ version: 2, exportedAt: Date.now(), store }, null, 2)
1082
+ res.writeHead(200, {
1083
+ 'content-type': 'application/json; charset=utf-8',
1084
+ 'content-disposition': 'attachment; filename="dsh-reader-export.json"',
1085
+ 'cache-control': 'no-store',
1086
+ })
1087
+ res.end(payload)
1088
+ } catch (error) {
1089
+ handleRouteError(res, error)
1090
+ }
1091
+ }
1092
+
1093
+ async function importRoute(ctx, req, res) {
1094
+ try {
1095
+ const url = new URL(req.url, 'http://local')
1096
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
1097
+ const body = await readBody(req)
1098
+ const incoming = body?.store || body
1099
+ if (
1100
+ !incoming ||
1101
+ typeof incoming !== 'object' ||
1102
+ incoming.version !== 2 ||
1103
+ typeof incoming.concepts !== 'object' ||
1104
+ typeof incoming.docs !== 'object'
1105
+ ) {
1106
+ throw httpError(400, 'invalid store')
1107
+ }
1108
+ const stored = await mutateStore(cwd, () => incoming)
1109
+ send(res, 200, { store: stored })
1110
+ } catch (error) {
1111
+ handleRouteError(res, error)
1112
+ }
1113
+ }
1114
+
1115
+ async function translateRoute(ctx, req, res) {
1116
+ try {
1117
+ const url = new URL(req.url, 'http://local')
1118
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
1119
+ const body = await readBody(req)
1120
+ const target = String(body?.target || 'zh')
1121
+ const from = String(body?.from || 'auto')
1122
+ if (!TRANSLATE_LANGUAGES.includes(target)) throw httpError(400, 'invalid target language')
1123
+ if (!TRANSLATE_SOURCES.includes(from)) throw httpError(400, 'invalid source language')
1124
+ const docKey = typeof body?.docKey === 'string' ? body.docKey : ''
1125
+ const segments = Array.isArray(body?.segments) ? body.segments : []
1126
+ if (segments.length === 0) throw httpError(400, 'segments required')
1127
+ if (segments.length > 40) throw httpError(400, 'too many segments')
1128
+ let total = 0
1129
+ for (const segment of segments) {
1130
+ if (!segment || typeof segment.id !== 'string' || !segment.id) throw httpError(400, 'segment id required')
1131
+ const text = String(segment.text || '')
1132
+ if (text.length > 4000) throw httpError(400, 'segment too large')
1133
+ total += text.length
1134
+ }
1135
+ if (total > 20000) throw httpError(400, 'translation request too large')
1136
+
1137
+ const store = await readStore(cwd)
1138
+ const existing = docKey && store.docs?.[docKey]?.translations?.[target]
1139
+ ? store.docs[docKey].translations[target]
1140
+ : {}
1141
+ const model = pluginModel(store, ctx)
1142
+ const result = {}
1143
+ const pending = []
1144
+ let cached = 0
1145
+ for (const segment of segments) {
1146
+ const hash = blockHash(segment.text)
1147
+ if (existing[hash]) {
1148
+ result[segment.id] = existing[hash]
1149
+ cached += 1
1150
+ } else {
1151
+ pending.push({ id: segment.id, hash, text: String(segment.text) })
1152
+ }
1153
+ }
1154
+
1155
+ let generated = 0
1156
+ const persisted = {}
1157
+ const batches = []
1158
+ let batch = []
1159
+ let batchChars = 0
1160
+ for (const segment of pending) {
1161
+ if (batch.length >= 8 || batchChars + segment.text.length > 3500) {
1162
+ if (batch.length > 0) batches.push(batch)
1163
+ batch = []
1164
+ batchChars = 0
1165
+ }
1166
+ batch.push(segment)
1167
+ batchChars += segment.text.length
1168
+ }
1169
+ if (batch.length > 0) batches.push(batch)
1170
+
1171
+ const effort = pending.length > 0 ? await pickEffort(ctx, model.provider, model.model, 'low') : null
1172
+ for (const group of batches) {
1173
+ const prompt = buildTranslatePrompt({
1174
+ target,
1175
+ from,
1176
+ segments: group.map((segment) => ({ id: segment.id, text: segment.text })),
1177
+ })
1178
+ const chars = group.reduce((sum, segment) => sum + segment.text.length, 0)
1179
+ const reply = await complete(ctx, {
1180
+ ...prompt,
1181
+ maxTokens: Math.min(2400, Math.max(400, chars * 2)),
1182
+ provider: model.provider,
1183
+ model: model.model,
1184
+ ...(effort ? { reasoningEffort: effort } : {}),
1185
+ })
1186
+ const parsed = parseTranslationReply(reply, group.map((segment) => segment.id))
1187
+ for (const segment of group) {
1188
+ if (!parsed[segment.id]) continue
1189
+ result[segment.id] = parsed[segment.id]
1190
+ persisted[segment.hash] = parsed[segment.id]
1191
+ generated += 1
1192
+ }
1193
+ }
1194
+
1195
+ let stored = null
1196
+ if (docKey && Object.keys(persisted).length > 0) {
1197
+ stored = await mutateStore(cwd, (current) => {
1198
+ const doc = docOf(current, docKey)
1199
+ if (!isRecordObject(doc.translations)) doc.translations = {}
1200
+ if (!isRecordObject(doc.translations[target])) doc.translations[target] = {}
1201
+ Object.assign(doc.translations[target], persisted)
1202
+ const keys = Object.keys(doc.translations[target])
1203
+ if (keys.length > 2000) {
1204
+ for (const key of keys.slice(0, keys.length - 2000)) delete doc.translations[target][key]
1205
+ }
1206
+ recordSent(current, {
1207
+ kind: 'translate',
1208
+ preview: `${target} ${String(segments[0].text || '').slice(0, 60)}`,
1209
+ chars: total,
1210
+ })
1211
+ return current
1212
+ })
1213
+ }
1214
+
1215
+ send(res, 200, { translations: result, cached, generated, target, ...(stored ? { store: stored } : {}) })
1216
+ } catch (error) {
1217
+ handleRouteError(res, error)
1218
+ }
1219
+ }
1220
+
1221
+ async function modelsRoute(ctx, req, res) {
1222
+ try {
1223
+ const listProviders = ctx.llm?.listProviders
1224
+ const providers = typeof listProviders === 'function' ? await listProviders.call(ctx.llm) : []
1225
+ const catalog = []
1226
+ for (const provider of providers.slice(0, 12)) {
1227
+ let models = []
1228
+ try {
1229
+ models = await ctx.llm.listModels(provider.id)
1230
+ } catch {
1231
+ models = []
1232
+ }
1233
+ catalog.push({
1234
+ id: provider.id,
1235
+ name: provider.name || provider.id,
1236
+ models: models
1237
+ .filter((model) => model && model.id)
1238
+ .map((model) => ({ id: model.id, name: model.name || model.id })),
1239
+ })
1240
+ }
1241
+ send(res, 200, { current: ctx.agentDefaultModel?.currentSelection?.() || null, providers: catalog })
1242
+ } catch (error) {
1243
+ handleRouteError(res, error)
1244
+ }
1245
+ }
1246
+
1247
+ async function backupsRoute(ctx, req, res) {
1248
+ try {
1249
+ const url = new URL(req.url, 'http://local')
1250
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
1251
+ if (req.method !== 'GET') {
1252
+ send(res, 405, { error: 'method not allowed' })
1253
+ return
1254
+ }
1255
+ send(res, 200, { backups: await listBackups(cwd) })
1256
+ } catch (error) {
1257
+ handleRouteError(res, error)
1258
+ }
1259
+ }
1260
+
1261
+ async function restoreRoute(ctx, req, res) {
1262
+ try {
1263
+ const url = new URL(req.url, 'http://local')
1264
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
1265
+ const restored = await restoreLatestBackup(cwd)
1266
+ if (!restored) throw httpError(404, 'no readable backup')
1267
+ send(res, 200, restored)
1268
+ } catch (error) {
1269
+ handleRouteError(res, error)
1270
+ }
1271
+ }
1272
+
1273
+ function storedReadingEntry(store, sessionId) {
1274
+ if (!isRecordObject(store.reading)) return undefined
1275
+ const entry = store.reading[sessionId]
1276
+ return isRecordObject(entry) ? entry : undefined
1277
+ }
1278
+
1279
+ async function persistReadingPosition(cwd, sessionId, storeEntry) {
1280
+ const current = storedReadingEntry(await readStore(cwd), sessionId)
1281
+ // The reader reports the same spot repeatedly while only the window slides;
1282
+ // skipping the unchanged case keeps the store backup rotation quiet.
1283
+ if (current && sameReaderPosition(current, storeEntry)) return
1284
+ await mutateStore(cwd, (store) => {
1285
+ if (!isRecordObject(store.reading)) store.reading = {}
1286
+ store.reading[sessionId] = storeEntry
1287
+ return store
1288
+ })
1289
+ }
1290
+
1291
+ async function contextRoute(ctx, req, res) {
1292
+ try {
1293
+ if (req.method !== 'POST') {
1294
+ send(res, 405, { error: 'method not allowed' })
1295
+ return
1296
+ }
1297
+ const body = await readBody(req)
1298
+ if (!isRecordObject(body) || typeof body.sessionId !== 'string' || !body.sessionId.trim()) {
1299
+ throw httpError(400, 'sessionId required')
1300
+ }
1301
+ const sessionId = body.sessionId.trim().slice(0, MAX_SESSION_ID_CHARS)
1302
+ const cwd = await workspaceFor(ctx, sessionId)
1303
+ const report = buildReadingReport({ sessionId, position: body.position, window: body.window })
1304
+ if (!report) throw httpError(400, 'sessionId required')
1305
+ // context.json carries the window that reader_read projects; store.reading
1306
+ // carries the book position only, so older consumers see a small record.
1307
+ await writeReadingSession(cwd, sessionId, report.entry)
1308
+ await persistReadingPosition(cwd, sessionId, report.storeEntry)
1309
+ send(res, 200, { ok: true })
1310
+ } catch (error) {
1311
+ handleRouteError(res, error)
1312
+ }
1313
+ }
1314
+
1315
+ function readerToolScope(ctx, toolName, exec) {
1316
+ const agent = exec && exec.agent
1317
+ if (!agent) throw new Error(`${toolName} 需要在一个会话中调用:当前工具调用没有关联会话。`)
1318
+ try {
1319
+ return { agent, cwd: ctx.workingDirectory.get(agent.session) }
1320
+ } catch (error) {
1321
+ throw new Error(`无法确定阅读位置所在工作区:${String(error?.message || error)}`)
1322
+ }
1323
+ }
1324
+
1325
+ function readerFailurePayload(error) {
1326
+ return `读取阅读位置失败:${String(error?.message || error)}`
1327
+ }
1328
+
1329
+ /**
1330
+ * Reader tools are authored once in the `defineTool` dialect and prefer the
1331
+ * runtime-provided `@deepseek-ai/dsh-tools` implementation. A bundle linked from
1332
+ * outside the profile cannot resolve that shipped peer unless its package.json
1333
+ * declares the peer (the profile runtime routes linked importers through their
1334
+ * own peer declarations), so a plain registry definition compiled from the same
1335
+ * author spec is used as a fallback instead of silently dropping the tools.
1336
+ */
1337
+ function compileValueSchema(node) {
1338
+ if (!isRecordObject(node)) return { type: 'json' }
1339
+ if (node.type === 'object') {
1340
+ const properties = {}
1341
+ const required = []
1342
+ for (const [key, child] of Object.entries(isRecordObject(node.properties) ? node.properties : {})) {
1343
+ properties[key] = compileValueSchema(child)
1344
+ if (isRecordObject(child) && child.required === true) required.push(key)
1345
+ }
1346
+ return {
1347
+ type: 'object',
1348
+ additionalProperties: node.additionalProperties === true,
1349
+ properties,
1350
+ ...(required.length ? { required } : {}),
1351
+ }
1352
+ }
1353
+ if (node.type === 'array') {
1354
+ return { type: 'array', ...(isRecordObject(node.items) ? { items: compileValueSchema(node.items) } : {}) }
1355
+ }
1356
+ const out = { type: node.type }
1357
+ if (typeof node.description === 'string') out.description = node.description
1358
+ if (Array.isArray(node.enum)) out.enum = [...node.enum]
1359
+ return out
1360
+ }
1361
+
1362
+ function compileParameterSchema(parameters) {
1363
+ return compileValueSchema({ type: 'object', properties: parameters, additionalProperties: false })
1364
+ }
1365
+
1366
+ function fallbackToolDefinition(spec) {
1367
+ return {
1368
+ name: spec.name,
1369
+ description: spec.description,
1370
+ parameters: compileParameterSchema(spec.parameters),
1371
+ output: {
1372
+ schema: compileValueSchema(spec.output.schema),
1373
+ render: spec.output.render,
1374
+ ...(typeof spec.output.presentationMeta === 'function' ? { presentationMeta: spec.output.presentationMeta } : {}),
1375
+ },
1376
+ execute: spec.execute,
1377
+ ...(typeof spec.presentCall === 'function' ? { presentCall: spec.presentCall } : {}),
1378
+ ...(typeof spec.presentResult === 'function' ? { presentResult: spec.presentResult } : {}),
1379
+ ...(typeof spec.isConcurrencySafe === 'function' ? { isConcurrencySafe: spec.isConcurrencySafe } : {}),
1380
+ }
1381
+ }
1382
+
1383
+ function readerToolSpecs(ctx) {
1384
+ return [
1385
+ {
1386
+ name: 'reader_context',
1387
+ description:
1388
+ '读取用户当前正在阅读的电子书、章节与阅读位置。当前会话的阅读位置由 dsh-reader 插件从阅读器客户端上报;用户说“这段”“上文”“接着往下”时先调用它。',
1389
+ parameters: {},
1390
+ presentCall: () => ({ card: 'generic', title: '读取阅读位置', kind: 'read' }),
1391
+ output: {
1392
+ schema: {
1393
+ type: 'object',
1394
+ additionalProperties: false,
1395
+ properties: {
1396
+ found: { type: 'boolean', required: true, description: '是否已收到当前会话的阅读位置。' },
1397
+ summary: { type: 'string', required: true, description: '可直接展示给模型的阅读位置摘要。' },
1398
+ book: { type: 'string', required: true },
1399
+ path: { type: 'string', required: true, description: '相对工作区的书籍路径。' },
1400
+ chapterTitle: { type: 'string', required: true },
1401
+ page: { type: 'integer', required: true },
1402
+ total: { type: 'integer', required: true },
1403
+ percent: { type: 'integer', required: true },
1404
+ hasWindow: { type: 'boolean', required: true, description: '是否已收到当前阅读窗口文本。' },
1405
+ windowTitle: { type: 'string', required: true },
1406
+ },
1407
+ },
1408
+ render: (_args, value) => [{ type: 'text', text: value.summary }],
1409
+ },
1410
+ async execute(_args, exec) {
1411
+ const { agent, cwd } = readerToolScope(ctx, 'reader_context', exec)
1412
+ try {
1413
+ const context = await readReadingContext(cwd)
1414
+ return buildReaderContextPayload(pickReaderTarget(context, agent.id))
1415
+ } catch (error) {
1416
+ return { ...buildReaderContextPayload(undefined), summary: readerFailurePayload(error) }
1417
+ }
1418
+ },
1419
+ },
1420
+ {
1421
+ name: 'reader_read',
1422
+ description:
1423
+ '读取用户最近一次上报的阅读窗口正文。窗口由阅读器客户端上报:PDF 是当前页前后几页,文本类书是当前滚动位置附近的片段,单次最多返回 8000 字;宿主不解析 PDF/EPUB 源文件,无法跨章或检索全书。',
1424
+ parameters: {
1425
+ mode: {
1426
+ type: 'string',
1427
+ enum: ['around', 'chapter', 'toc', 'search'],
1428
+ description: '读取方式:around=窗口正文(默认);chapter=窗口正文并在前面标出当前章节标题;toc=只返回当前章节标题(不是全书目录);search=只在窗口内查找关键词。窗口不包含用户要看的内容时,请让用户翻页或滚动后再读。',
1429
+ },
1430
+ query: { type: 'string', description: 'search 模式下在窗口内查找的关键词。' },
1431
+ limit: { type: 'integer', description: '返回文本的最大字数,默认 8000,上限 8000。' },
1432
+ },
1433
+ presentCall: (args) => ({
1434
+ card: 'generic',
1435
+ title: `读取阅读窗口(${args?.mode || 'around'})`,
1436
+ kind: 'read',
1437
+ ...(args?.query ? { rawInput: { query: args.query } } : {}),
1438
+ }),
1439
+ output: {
1440
+ schema: {
1441
+ type: 'object',
1442
+ additionalProperties: false,
1443
+ properties: {
1444
+ found: { type: 'boolean', required: true },
1445
+ mode: { type: 'string', required: true },
1446
+ title: { type: 'string', required: true, description: '书名或窗口标题。' },
1447
+ text: { type: 'string', required: true },
1448
+ truncated: { type: 'boolean', required: true },
1449
+ chapters: { type: 'array', required: true, items: { type: 'string' } },
1450
+ matches: { type: 'array', required: true, items: { type: 'string' } },
1451
+ },
1452
+ },
1453
+ render: (_args, value) => [{ type: 'text', text: value.title ? `《${value.title}》\n\n${value.text}` : value.text }],
1454
+ },
1455
+ isConcurrencySafe: () => true,
1456
+ async execute(args, exec) {
1457
+ const { agent, cwd } = readerToolScope(ctx, 'reader_read', exec)
1458
+ try {
1459
+ const context = await readReadingContext(cwd)
1460
+ return buildReaderReadPayload(pickReaderTarget(context, agent.id), args || {})
1461
+ } catch (error) {
1462
+ return { ...buildReaderReadPayload(undefined, args || {}), text: readerFailurePayload(error) }
1463
+ }
1464
+ },
1465
+ },
1466
+ ]
1467
+ }
1468
+
1469
+ async function registerReaderTools(ctx, disposers, isReleased) {
1470
+ let defineTool = null
1471
+ try {
1472
+ const tools = await import('@deepseek-ai/dsh-tools')
1473
+ if (typeof tools.defineTool === 'function') defineTool = tools.defineTool
1474
+ } catch {
1475
+ // The linked-bundle fallback below registers the same tools without the peer.
1476
+ }
1477
+ const specs = readerToolSpecs(ctx)
1478
+ const registerAll = (build) => {
1479
+ const registered = []
1480
+ try {
1481
+ for (const spec of specs) {
1482
+ const dispose = ctx.tools.register(build(spec))
1483
+ if (isReleased()) dispose()
1484
+ else registered.push(dispose)
1485
+ }
1486
+ return registered
1487
+ } catch (error) {
1488
+ for (const dispose of registered) {
1489
+ try {
1490
+ dispose()
1491
+ } catch {
1492
+ /* half-registered set is already gone */
1493
+ }
1494
+ }
1495
+ throw error
1496
+ }
1497
+ }
1498
+ try {
1499
+ const registered = registerAll(defineTool ? (spec) => defineTool(spec) : fallbackToolDefinition)
1500
+ for (const dispose of registered) disposers.push(dispose)
1501
+ return
1502
+ } catch (error) {
1503
+ if (!defineTool) throw error
1504
+ // A shipped implementation rejected the spec; keep the capability through
1505
+ // the plain definitions instead of leaving the tools missing.
1506
+ }
1507
+ const registered = registerAll(fallbackToolDefinition)
1508
+ for (const dispose of registered) disposers.push(dispose)
1509
+ }
1510
+
1511
+ async function handleGet(ctx, request) {
1512
+ const url = new URL(request.url, 'http://local')
1513
+ const pathname = url.pathname
1514
+ try {
1515
+ const cwd = await workspaceFor(ctx, url.searchParams.get('sessionId'))
1516
+ if (pathname === `${ROOT}/api/session`) return json({ cwd })
1517
+ if (pathname === `${ROOT}/api/list`) return await listDir(cwd, url.searchParams.get('dir'))
1518
+ if (pathname === `${ROOT}/api/file`) return await readFile(cwd, url.searchParams.get('path'))
1519
+ return json({ error: 'not found' }, 404)
1520
+ } catch (error) {
1521
+ const status = typeof error?.status === 'number' ? error.status : 500
1522
+ return json({ error: String(error?.message || error) }, status)
1523
+ }
1524
+ }
1525
+
1526
+ function assetRoute(request) {
1527
+ const pathname = new URL(request.url, 'http://local').pathname
1528
+ return serveAsset(pathname.slice(`${ROOT}/assets/`.length))
1529
+ }
1530
+
1531
+ export function apply(ctx) {
1532
+ const disposers = []
1533
+ const add = (route) => disposers.push(ctx.webServer.register(route))
1534
+ add({ kind: 'prefix', path: `${ROOT}/assets`, resource: (request) => assetRoute(request) })
1535
+ for (const name of ['session', 'list', 'file']) {
1536
+ add({ kind: 'exact', path: `${ROOT}/api/${name}`, resource: (request) => handleGet(ctx, request) })
1537
+ }
1538
+ add({ kind: 'exact', path: `${ROOT}/api/store`, handler: (req, res) => storeRoute(ctx, req, res) })
1539
+ add({ kind: 'exact', path: `${ROOT}/api/mutate`, handler: (req, res) => mutateRoute(ctx, req, res) })
1540
+ add({ kind: 'exact', path: `${ROOT}/api/explain`, handler: (req, res) => explainRoute(ctx, req, res) })
1541
+ add({ kind: 'exact', path: `${ROOT}/api/guide`, handler: (req, res) => guideRoute(ctx, req, res) })
1542
+ add({ kind: 'exact', path: `${ROOT}/api/concept/ask`, handler: (req, res) => askRoute(ctx, req, res) })
1543
+ add({ kind: 'exact', path: `${ROOT}/api/export`, handler: (req, res) => exportRoute(ctx, req, res) })
1544
+ add({ kind: 'exact', path: `${ROOT}/api/import`, handler: (req, res) => importRoute(ctx, req, res) })
1545
+ add({ kind: 'exact', path: `${ROOT}/api/models`, handler: (req, res) => modelsRoute(ctx, req, res) })
1546
+ add({ kind: 'exact', path: `${ROOT}/api/translate`, handler: (req, res) => translateRoute(ctx, req, res) })
1547
+ add({ kind: 'exact', path: `${ROOT}/api/backups`, handler: (req, res) => backupsRoute(ctx, req, res) })
1548
+ add({ kind: 'exact', path: `${ROOT}/api/restore`, handler: (req, res) => restoreRoute(ctx, req, res) })
1549
+ add({ kind: 'exact', path: `${ROOT}/api/context`, handler: (req, res) => contextRoute(ctx, req, res) })
1550
+ let released = false
1551
+ const release = () => {
1552
+ if (released) return
1553
+ released = true
1554
+ for (const dispose of disposers) {
1555
+ try {
1556
+ dispose()
1557
+ } catch {
1558
+ /* already released */
1559
+ }
1560
+ }
1561
+ }
1562
+ if (ctx.tools && typeof ctx.tools.register === 'function') {
1563
+ // Importing the shipped tool package and registering are both best-effort:
1564
+ // a failure must keep every reader route above alive, and the linked-bundle
1565
+ // fallback inside registerReaderTools still registers both tools.
1566
+ registerReaderTools(ctx, disposers, () => released).catch((error) => {
1567
+ if (typeof ctx.logger?.warn === 'function') {
1568
+ ctx.logger.warn(`dsh-reader: reader_context/reader_read 注册失败:${String(error?.message || error)}`)
1569
+ }
1570
+ })
1571
+ }
1572
+ // Own the registrations on this plugin's fiber as well as on unload.
1573
+ ctx.effect(() => release)
1574
+ return release
1575
+ }