@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
@@ -0,0 +1,382 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+
4
+ export const READING_DIR = '.dsh-reader'
5
+ export const CONTEXT_FILE = 'context.json'
6
+ export const MAX_WINDOW_CHARS = 24_000
7
+ export const MAX_READING_SESSIONS = 10
8
+ export const MAX_READ_CHARS = 8_000
9
+ export const MAX_SESSION_ID_CHARS = 200
10
+
11
+ const POSITION_MAX_CHARS = { path: 1000, name: 300, chapterTitle: 300 }
12
+ const WINDOW_TITLE_MAX_CHARS = 300
13
+ const STORE_FIELDS = ['path', 'name', 'ext', 'chapter', 'chapterTitle', 'page', 'total', 'percent']
14
+
15
+ export const NO_POSITION_HINT = '尚未上报阅读位置:当前会话还没有来自 dsh-reader 阅读器的位置上报。请用户先打开一本书。'
16
+ export const NO_WINDOW_HINT = '客户端尚未上报当前阅读窗口(可能仍在加载,或 PDF 文本抽取失败)。'
17
+
18
+ function isRecord(value) {
19
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
20
+ }
21
+
22
+ function text(value, max) {
23
+ return typeof value === 'string' ? value.slice(0, max) : ''
24
+ }
25
+
26
+ function integer(value, min, max) {
27
+ if (typeof value !== 'number' || !Number.isFinite(value)) return 0
28
+ const rounded = Math.trunc(value)
29
+ if (rounded < min) return min
30
+ if (rounded > max) return max
31
+ return rounded
32
+ }
33
+
34
+ function percent(value) {
35
+ if (typeof value !== 'number' || !Number.isFinite(value)) return 0
36
+ return Math.min(100, Math.max(0, Math.round(value)))
37
+ }
38
+
39
+ function extension(value) {
40
+ const raw = text(value, 16).trim().toLowerCase()
41
+ if (!raw) return ''
42
+ return raw.startsWith('.') ? raw : `.${raw}`
43
+ }
44
+
45
+ /**
46
+ * Canonical reader position. Unknown fields are dropped; wrong value types fall
47
+ * back to their neutral value so a malformed client report never reaches the
48
+ * store or the tools.
49
+ * @param {unknown} raw reported position
50
+ */
51
+ export function normalizeReaderPosition(raw) {
52
+ const source = isRecord(raw) ? raw : {}
53
+ return {
54
+ path: text(source.path, POSITION_MAX_CHARS.path).trim(),
55
+ name: text(source.name, POSITION_MAX_CHARS.name).trim(),
56
+ ext: extension(source.ext),
57
+ chapter: integer(source.chapter, 0, Number.MAX_SAFE_INTEGER),
58
+ chapterTitle: text(source.chapterTitle, POSITION_MAX_CHARS.chapterTitle).trim(),
59
+ page: integer(source.page, 0, Number.MAX_SAFE_INTEGER),
60
+ total: integer(source.total, 0, Number.MAX_SAFE_INTEGER),
61
+ percent: percent(source.percent),
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Canonical context window. A window without any text is treated as absent so
67
+ * reader_read can say exactly what is missing.
68
+ * @param {unknown} raw reported window
69
+ */
70
+ export function normalizeReaderWindow(raw) {
71
+ if (!isRecord(raw)) return null
72
+ const title = text(raw.title, WINDOW_TITLE_MAX_CHARS).trim()
73
+ const body = typeof raw.text === 'string' ? raw.text.slice(0, MAX_WINDOW_CHARS) : ''
74
+ if (!body.trim()) return null
75
+ return { title, text: body }
76
+ }
77
+
78
+ function normalizeUpdatedAt(raw, fallback) {
79
+ return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0 ? raw : fallback
80
+ }
81
+
82
+ function normalizeReadingEntry(raw, fallbackUpdatedAt = 0) {
83
+ if (!isRecord(raw)) return null
84
+ return {
85
+ ...normalizeReaderPosition(raw),
86
+ window: normalizeReaderWindow(raw.window),
87
+ updatedAt: normalizeUpdatedAt(raw.updatedAt, fallbackUpdatedAt),
88
+ }
89
+ }
90
+
91
+ function sortEntriesNewestFirst(sessions, protectedSessionId) {
92
+ return Object.keys(sessions).sort((left, right) => {
93
+ if (left === protectedSessionId) return -1
94
+ if (right === protectedSessionId) return 1
95
+ return (sessions[right].updatedAt || 0) - (sessions[left].updatedAt || 0)
96
+ })
97
+ }
98
+
99
+ function capSessions(sessions, protectedSessionId) {
100
+ const keys = sortEntriesNewestFirst(sessions, protectedSessionId)
101
+ const out = {}
102
+ for (const key of keys.slice(0, MAX_READING_SESSIONS)) out[key] = sessions[key]
103
+ return out
104
+ }
105
+
106
+ /** One private file no other reader version touches; a missing or corrupt file is empty. */
107
+ export function readingContextPath(cwd) {
108
+ return path.join(cwd, READING_DIR, CONTEXT_FILE)
109
+ }
110
+
111
+ /**
112
+ * @param {string} cwd workspace directory
113
+ * @returns {Promise<{ version: 1, sessions: Record<string, object> }>}
114
+ */
115
+ export async function readReadingContext(cwd) {
116
+ const empty = { version: 1, sessions: {} }
117
+ let raw
118
+ try {
119
+ raw = JSON.parse(await fs.readFile(readingContextPath(cwd), 'utf8'))
120
+ } catch {
121
+ // Missing, unreadable, or corrupt: the next report rewrites the file.
122
+ return empty
123
+ }
124
+ if (!isRecord(raw) || !isRecord(raw.sessions)) return empty
125
+ const sessions = {}
126
+ for (const [sessionId, value] of Object.entries(raw.sessions)) {
127
+ if (typeof sessionId !== 'string' || !sessionId || sessionId.length > MAX_SESSION_ID_CHARS) continue
128
+ const entry = normalizeReadingEntry(value)
129
+ if (entry) sessions[sessionId] = entry
130
+ }
131
+ return { version: 1, sessions: capSessions(sessions) }
132
+ }
133
+
134
+ let contextWriteQueue = Promise.resolve()
135
+
136
+ function enqueueContextWrite(cwd, task) {
137
+ const run = contextWriteQueue.then(task, task)
138
+ contextWriteQueue = run.then(
139
+ () => undefined,
140
+ () => undefined,
141
+ )
142
+ return run
143
+ }
144
+
145
+ async function writeContextFile(cwd, context) {
146
+ const dir = path.join(cwd, READING_DIR)
147
+ await fs.mkdir(dir, { recursive: true })
148
+ const file = readingContextPath(cwd)
149
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
150
+ try {
151
+ await fs.writeFile(tmp, JSON.stringify(context, null, 2), 'utf8')
152
+ await fs.rename(tmp, file)
153
+ } finally {
154
+ await fs.rm(tmp, { force: true }).catch(() => {})
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Persist one session's position and window. The newest MAX_READING_SESSIONS
160
+ * sessions survive; stale or malformed entries are dropped on the next read.
161
+ * @param {string} cwd workspace directory
162
+ * @param {string} sessionId owning session
163
+ * @param {object} entry position fields, optional window, optional updatedAt
164
+ * @returns {Promise<object>} canonical entry written to disk
165
+ */
166
+ export async function writeReadingSession(cwd, sessionId, entry) {
167
+ const id = typeof sessionId === 'string' ? sessionId.trim().slice(0, MAX_SESSION_ID_CHARS) : ''
168
+ if (!id) throw new TypeError('reader-context: sessionId required')
169
+ const canonical = normalizeReadingEntry(entry, Date.now())
170
+ if (!canonical) throw new TypeError('reader-context: invalid reading entry')
171
+ return enqueueContextWrite(cwd, async () => {
172
+ const context = await readReadingContext(cwd)
173
+ context.sessions[id] = canonical
174
+ context.sessions = capSessions(context.sessions, id)
175
+ await writeContextFile(cwd, context)
176
+ return canonical
177
+ })
178
+ }
179
+
180
+ /**
181
+ * Resolve the reported reading entry for one session. The session slot and the
182
+ * persisted session id disagree about the `session-` prefix across DSH
183
+ * versions, so both spellings are tried.
184
+ * @param {unknown} context result of readReadingContext
185
+ * @param {string} sessionId session or bare uuid
186
+ */
187
+ export function pickReaderTarget(context, sessionId) {
188
+ if (!isRecord(context) || !isRecord(context.sessions) || typeof sessionId !== 'string' || !sessionId) return undefined
189
+ const candidates = [sessionId]
190
+ candidates.push(sessionId.startsWith('session-') ? sessionId.slice(8) : `session-${sessionId}`)
191
+ for (const candidate of candidates) {
192
+ const entry = context.sessions[candidate]
193
+ if (isRecord(entry)) return entry
194
+ }
195
+ return undefined
196
+ }
197
+
198
+ function hasPosition(entry) {
199
+ return isRecord(entry) && Boolean(entry.path || (isRecord(entry.window) && (entry.window.title || entry.window.text)))
200
+ }
201
+
202
+ function bookTitle(entry) {
203
+ if (!isRecord(entry)) return ''
204
+ if (typeof entry.name === 'string' && entry.name) return entry.name
205
+ if (typeof entry.path !== 'string' || !entry.path) return ''
206
+ return path.basename(entry.path)
207
+ }
208
+
209
+ /** Human-readable one-line position for the model and for reader_context. */
210
+ export function describeReaderContext(entry) {
211
+ if (!hasPosition(entry)) return NO_POSITION_HINT
212
+ const parts = [`《${bookTitle(entry) || '未命名书籍'}》`]
213
+ if (entry.chapterTitle) parts.push(`第 ${entry.chapter + 1} 章「${entry.chapterTitle}」`)
214
+ else if (entry.chapter > 0) parts.push(`第 ${entry.chapter + 1} 章`)
215
+ if (entry.page > 0) {
216
+ parts.push(`第 ${entry.page}${entry.total > 0 ? `/${entry.total}` : ''} 页`)
217
+ }
218
+ if (entry.percent > 0) parts.push(`${entry.percent}%`)
219
+ return parts.join(' · ')
220
+ }
221
+
222
+ /** Canonical value of the reader_context tool. */
223
+ export function buildReaderContextPayload(entry) {
224
+ if (!hasPosition(entry)) {
225
+ return {
226
+ found: false,
227
+ summary: NO_POSITION_HINT,
228
+ book: '',
229
+ path: '',
230
+ chapterTitle: '',
231
+ page: 0,
232
+ total: 0,
233
+ percent: 0,
234
+ hasWindow: false,
235
+ windowTitle: '',
236
+ }
237
+ }
238
+ const window = isRecord(entry.window) ? entry.window : null
239
+ return {
240
+ found: true,
241
+ summary: describeReaderContext(entry),
242
+ book: bookTitle(entry),
243
+ path: typeof entry.path === 'string' ? entry.path : '',
244
+ chapterTitle: typeof entry.chapterTitle === 'string' ? entry.chapterTitle : '',
245
+ page: typeof entry.page === 'number' ? entry.page : 0,
246
+ total: typeof entry.total === 'number' ? entry.total : 0,
247
+ percent: typeof entry.percent === 'number' ? entry.percent : 0,
248
+ hasWindow: Boolean(window),
249
+ windowTitle: window && typeof window.title === 'string' ? window.title : '',
250
+ }
251
+ }
252
+
253
+ function readMode(value) {
254
+ return ['around', 'chapter', 'toc', 'search'].includes(value) ? value : 'around'
255
+ }
256
+
257
+ function readLimit(value) {
258
+ if (typeof value !== 'number' || !Number.isFinite(value)) return MAX_READ_CHARS
259
+ return Math.min(MAX_READ_CHARS, Math.max(1, Math.floor(value)))
260
+ }
261
+
262
+ function tocText(entry, title) {
263
+ const chapters = entry.chapterTitle ? [`第 ${entry.chapter + 1} 章 ${entry.chapterTitle}`] : []
264
+ return {
265
+ title,
266
+ mode: 'toc',
267
+ text: chapters.length > 0 ? `当前章节:\n${chapters.map((chapter) => `- ${chapter}`).join('\n')}` : '客户端尚未上报章节目录信息。',
268
+ truncated: false,
269
+ chapters,
270
+ matches: [],
271
+ }
272
+ }
273
+
274
+ function searchText(entry, window, query, title, limit) {
275
+ if (!query) {
276
+ return { title, mode: 'search', text: 'search 模式需要提供要查找的关键词(query)。', truncated: false, chapters: [], matches: [] }
277
+ }
278
+ const haystack = window.text
279
+ const needle = query.toLowerCase()
280
+ const lower = haystack.toLowerCase()
281
+ const matches = []
282
+ let index = lower.indexOf(needle)
283
+ while (index >= 0 && matches.length < 20) {
284
+ const start = Math.max(0, index - 80)
285
+ const end = Math.min(haystack.length, index + query.length + 120)
286
+ matches.push(haystack.slice(start, end).replace(/\s+/g, ' ').trim())
287
+ index = lower.indexOf(needle, index + Math.max(1, query.length))
288
+ }
289
+ if (matches.length === 0) {
290
+ return { title, mode: 'search', text: `当前阅读窗口中没有找到“${query}”。`, truncated: false, chapters: [], matches: [] }
291
+ }
292
+ const full = `在当前阅读窗口中命中 ${matches.length} 处:\n\n${matches.map((match, at) => `${at + 1}. ${match}`).join('\n')}`
293
+ return {
294
+ title,
295
+ mode: 'search',
296
+ text: full.slice(0, limit),
297
+ truncated: full.length > limit,
298
+ chapters: [],
299
+ matches,
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Read one reported window. The Host cannot parse book files (PDF/EPUB parsing
305
+ * lives in the reader client), so every mode is projected from the window the
306
+ * client last uploaded.
307
+ * @param {object|undefined} entry reading entry with a canonical position and window
308
+ * @param {{ mode?: string, query?: string, limit?: number }} [args]
309
+ */
310
+ export function readReaderWindow(entry, args) {
311
+ const options = isRecord(args) ? args : {}
312
+ const mode = readMode(options.mode)
313
+ const limit = readLimit(options.limit)
314
+ const window = isRecord(entry) && isRecord(entry.window) ? normalizeReaderWindow(entry.window) : null
315
+ const title = bookTitle(entry) || (window ? window.title : '')
316
+ if (mode === 'toc') return tocText(isRecord(entry) ? entry : {}, title)
317
+ if (!window) {
318
+ return { title, mode, text: NO_WINDOW_HINT, truncated: false, chapters: [], matches: [] }
319
+ }
320
+ if (mode === 'search') {
321
+ const query = typeof options.query === 'string' ? options.query.trim() : ''
322
+ return searchText(entry, window, query, title, limit)
323
+ }
324
+ const heading = mode === 'chapter' && entry.chapterTitle ? `第 ${entry.chapter + 1} 章 ${entry.chapterTitle}\n\n` : ''
325
+ const full = `${heading}${window.text}`
326
+ return {
327
+ title,
328
+ mode,
329
+ text: full.slice(0, limit),
330
+ truncated: full.length > limit,
331
+ chapters: [],
332
+ matches: [],
333
+ }
334
+ }
335
+
336
+ /** Canonical value of the reader_read tool. */
337
+ export function buildReaderReadPayload(entry, args) {
338
+ if (!hasPosition(entry)) {
339
+ return {
340
+ found: false,
341
+ mode: readMode(isRecord(args) ? args.mode : undefined),
342
+ title: '',
343
+ text: NO_POSITION_HINT,
344
+ truncated: false,
345
+ chapters: [],
346
+ matches: [],
347
+ }
348
+ }
349
+ const window = readReaderWindow(entry, args)
350
+ return {
351
+ found: true,
352
+ mode: window.mode,
353
+ title: window.title,
354
+ text: window.text,
355
+ truncated: window.truncated,
356
+ chapters: window.chapters,
357
+ matches: window.matches,
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Normalize one `POST /api/context` report for both persistence layers.
363
+ * @param {{ sessionId?: string, position?: unknown, window?: unknown, now?: number }} report
364
+ * @returns {{ entry: object, storeEntry: object } | null} null for a missing session id
365
+ */
366
+ export function buildReadingReport(report) {
367
+ const source = isRecord(report) ? report : {}
368
+ const sessionId = typeof source.sessionId === 'string' ? source.sessionId.trim() : ''
369
+ if (!sessionId) return null
370
+ const updatedAt = typeof source.now === 'number' && Number.isFinite(source.now) ? source.now : Date.now()
371
+ const position = normalizeReaderPosition(source.position)
372
+ return {
373
+ entry: { ...position, window: normalizeReaderWindow(source.window), updatedAt },
374
+ storeEntry: { ...position, updatedAt },
375
+ }
376
+ }
377
+
378
+ /** True when two canonical positions describe the same reading spot. */
379
+ export function sameReaderPosition(left, right) {
380
+ if (!isRecord(left) || !isRecord(right)) return false
381
+ return STORE_FIELDS.every((field) => left[field] === right[field])
382
+ }
package/lib/sent.js ADDED
@@ -0,0 +1,17 @@
1
+ /** Record one outbound model request for the "recently sent" view. */
2
+ export function recordSent(store, entry) {
3
+ if (!store.debug || typeof store.debug !== 'object') store.debug = {}
4
+ const list = Array.isArray(store.debug.lastSent) ? store.debug.lastSent : []
5
+ list.push({
6
+ at: Date.now(),
7
+ kind: String(entry.kind || 'explain'),
8
+ preview: String(entry.preview || '').slice(0, 120),
9
+ chars: Number.isFinite(entry.chars) ? entry.chars : 0,
10
+ })
11
+ store.debug.lastSent = list.slice(-10)
12
+ return store
13
+ }
14
+
15
+ export function recentSent(store) {
16
+ return (store && store.debug && Array.isArray(store.debug.lastSent) ? store.debug.lastSent : []).slice(-10).reverse()
17
+ }