dsh-reading-inbox 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -26,11 +26,13 @@ This plugin is the small implementation of those three things. Everything stays
26
26
  ## Features
27
27
 
28
28
  - **One-step clipping** — paste a URL; Readability extracts the article; Markdown + original HTML + title/author/date/source/excerpt are saved.
29
+ - **Text/selection capture** — when there is no fetchable URL, paste text, Markdown or HTML into the same inbox.
30
+ - **Import/export** — download all clips as JSON (optionally with original HTML) or one Markdown file; import JSON to restore clips, annotations and saved views.
29
31
  - **Inbox UI** — unread / reading / read / archived, search, tag filters, reading view, copy link, export Markdown.
30
32
  - **Highlights and notes** — select text to highlight it (yellow / green / blue / red) and add a note. Anchors use quote + surrounding context, so a re-clip re-locates them automatically; missing text becomes stale instead of landing on the wrong sentence. Markdown export includes active annotations.
31
33
  - **Local full-text search** — CJK is indexed as unigrams + bigrams, Latin as words; title and tags are boosted. No model call.
32
34
  - **Search grammar and saved views** — `tag:security`, `is:unread`, `site:example.com`, `after:2026-01-01`, `before:2026-12-31`, `has:highlight`; results include a matched snippet; save frequent queries as views.
33
- - **Agent tools** — `reading_clip`, `reading_search`, `reading_list`, `reading_read`, `reading_update`, `reading_highlight`.
35
+ - **Agent tools** — `reading_clip`, `reading_save_text`, `reading_search`, `reading_list`, `reading_read`, `reading_update`, `reading_highlight`.
34
36
  - **Slash command** — `/inbox <url> [tag1,tag2]` without leaving the conversation.
35
37
  - **Chinese-web friendly** — detects GBK / GB2312 / UTF-8 / Big5 so pages do not turn into mojibake.
36
38
  - **Safe defaults** — http/https only; every redirect hop is re-validated; DNS answers are checked again at connect time (DNS rebinding defense); loopback, private networks, CGNAT, link-local and cloud metadata addresses are rejected; hard caps of 5 MB, 20 seconds and 5 redirects.
@@ -47,7 +49,7 @@ From npm:
47
49
  dsh plugin --profile web add dsh-reading-inbox
48
50
  ```
49
51
 
50
- > pnpm's supply-chain policy waits before adopting a freshly published version. If an install right after a release picks the previous version, pin it: `dsh plugin --profile web add dsh-reading-inbox@0.3.0`.
52
+ > pnpm's supply-chain policy waits before adopting a freshly published version. If an install right after a release picks the previous version, pin it: `dsh plugin --profile web add dsh-reading-inbox@0.4.0`.
51
53
 
52
54
  From GitHub:
53
55
 
@@ -69,8 +71,8 @@ Restart `dsh web`. A **Reading inbox** row appears in the sidebar, and `/inbox`
69
71
 
70
72
  ### In the inbox
71
73
 
72
- 1. Paste a URL into the top bar and press Enter.
73
- 2. Click an item to read it. Mark read, archive, copy the link, export Markdown, or edit tags on the right.
74
+ 1. Paste a URL into the top bar and press Enter; use “Paste text” for content without a URL.
75
+ 2. “Export” downloads all clips as JSON; “Import” restores a previous JSON export. Click an item to read it; mark read, archive, copy the link, export Markdown, or edit tags on the right.
74
76
  3. Select text in the article: a highlight toolbar appears. Pick a color, add an optional note, and save.
75
77
  4. The search box searches title, body, tags and source as you type. Combine `tag:`, `is:`, `site:`, `after:` and `has:highlight` filters when needed.
76
78
  5. Save the current query as a view below the search box; one click restores the same filters.
@@ -110,6 +112,7 @@ Command output is shown in the UI only; the full article is not pushed into mode
110
112
  | `reading_read` | Read a Markdown slice by id; use `offset` / `nextOffset` for long articles and `hasMore` to know whether it is complete. |
111
113
  | `reading_update` | Change status or tags. Status: `unread` / `reading` / `read` / `archived`. |
112
114
  | `reading_highlight` | Create/list/update/delete highlights and notes. `action` is `create` / `list` / `update` / `delete`; `create` takes a `quote` from the article (plain text or Markdown; formatting is stripped, or pass `startOffset`/`endOffset`), plus optional `note` and `color`. |
115
+ | `reading_save_text` | Save pasted text / Markdown / HTML as a clip; use it for login walls, paywalled snippets, selections, or notes with no fetchable URL. Provide at least one of `text` / `markdown` / `html`. |
113
116
 
114
117
  ## Configuration
115
118
 
@@ -180,7 +183,7 @@ See [VERIFY.md](VERIFY.md) for the end-to-end check inside a real DSH.
180
183
 
181
184
  ```sh
182
185
  npm run build:client # rebuild client/client.js with esbuild
183
- npm test # 36 tests: extraction, rendering, SSRF, DNS checks, annotation anchoring, store races, search, routes, client bundle
186
+ npm test # 38 tests: extraction, rendering, SSRF, DNS checks, annotation anchoring, store races, search, routes, client bundle
184
187
  npm run verify # end-to-end self-check
185
188
  ```
186
189
 
@@ -197,12 +200,12 @@ Layout:
197
200
 
198
201
  ## Limits and roadmap
199
202
 
200
- 0.3.0 is deliberately small:
203
+ 0.4.0 is deliberately small:
201
204
 
202
205
  - [ ] SPA / login / anti-bot pages may yield no article; add a Playwright fallback.
203
206
  - [ ] Images still point at remote URLs; download them into `clips/<id>/assets/` for a full offline archive.
204
207
  - [ ] No PDF support; use `dsh-pdf-mineru` or a document reader for PDFs.
205
- - [ ] No browser extension or RSS import yet.
208
+ - [ ] No browser extension or RSS import yet; URL, paste-text, JSON import/export and agent tools are covered.
206
209
  - [ ] No sync/backup yet; the directory is portable.
207
210
  - [ ] Search is local BM25-style ranking; add chunking and result highlighting next.
208
211
 
package/README.md CHANGED
@@ -26,11 +26,13 @@ DSH 已经有 `web_fetch`、`read_url` 这类“读一次”的工具,但它
26
26
  ## 功能
27
27
 
28
28
  - **一键剪藏**:粘贴 URL → Readability 提取正文 → Markdown + 原文 HTML + 标题/作者/日期/来源/摘要。
29
+ - **文本/选区采集**:没有可抓取 URL 时,可以直接粘贴正文、Markdown 或 HTML,保存成同一收件箱条目。
30
+ - **导入/导出**:一键导出全部 JSON(可选原始 HTML)或全部 Markdown;导入 JSON 恢复文章、批注和保存视图。
29
31
  - **收件箱界面**:未读 / 在读 / 已读 / 归档,搜索、标签筛选、详情阅读、复制链接、导出 Markdown。
30
32
  - **划线与批注**:选中正文文字即可高亮(黄 / 绿 / 蓝 / 红),写笔记;批注按“引文 + 前后文”锚定,文章重新抓取后自动重定位,失败会标为失效而不是错贴。导出 Markdown 时带上有效批注。
31
33
  - **全文检索**:中文按单字 + 二元组切分,英文按词切分;标题和标签权重更高。纯本地,不调用模型。
32
34
  - **检索语法与保存视图**:支持 `tag:security`、`is:unread`、`site:example.com`、`after:2026-01-01`、`before:2026-12-31`、`has:highlight`;结果带命中 snippet;常用查询可存成视图。
33
- - **Agent 工具**:`reading_clip`、`reading_search`、`reading_list`、`reading_read`、`reading_update`、`reading_highlight`。
35
+ - **Agent 工具**:`reading_clip`、`reading_save_text`、`reading_search`、`reading_list`、`reading_read`、`reading_update`、`reading_highlight`。
34
36
  - **斜杠命令**:`/inbox <url> [tag1,tag2]`,不离开对话就能收藏。
35
37
  - **中文网页友好**:自动识别 GBK / GB2312 / UTF-8 / Big5 编码,避免乱码。
36
38
  - **安全默认**:只允许 http/https;逐跳校验重定向;DNS 解析结果在连接时再校验一次(防 DNS rebinding);拒绝本机/内网/云元数据地址;5 MB、20 秒、5 次重定向的硬上限。
@@ -47,7 +49,7 @@ DSH 已经有 `web_fetch`、`read_url` 这类“读一次”的工具,但它
47
49
  dsh plugin --profile web add dsh-reading-inbox
48
50
  ```
49
51
 
50
- > pnpm 的 supply-chain 策略会等新版本发布一段时间才默认采用它。刚发布后如果装到上一版,可显式指定版本:`dsh plugin --profile web add dsh-reading-inbox@0.3.0`。
52
+ > pnpm 的 supply-chain 策略会等新版本发布一段时间才默认采用它。刚发布后如果装到上一版,可显式指定版本:`dsh plugin --profile web add dsh-reading-inbox@0.4.0`。
51
53
 
52
54
  直接从 GitHub 安装:
53
55
 
@@ -69,8 +71,8 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
69
71
 
70
72
  ### 在收件箱里
71
73
 
72
- 1. 把网页链接粘贴到顶部的输入框,回车。
73
- 2. 左侧点击文章开始阅读;右侧可以标记已读、归档、复制链接、导出 Markdown、编辑标签。
74
+ 1. 把网页链接粘贴到顶部的输入框,回车;没有链接的内容用“粘贴文本”保存。
75
+ 2. 顶部“导出”下载全部 JSON;“导入”可以恢复之前导出的 JSON。左侧点击文章开始阅读;右侧可以标记已读、归档、复制链接、导出 Markdown、编辑标签。
74
76
  3. 选中正文文字,会浮出高亮工具栏:选颜色、写批注(可选),点“保存高亮”。
75
77
  4. 搜索框支持标题、正文、标签、来源;输入即搜。也可以用 `tag:`、`is:`、`site:`、`after:`、`has:highlight` 组合查询。
76
78
  5. 搜索框下方可以把当前查询存成“视图”,下次点一下就能回到同一组筛选。
@@ -110,6 +112,7 @@ dsh plugin --profile web add file:C:/path/to/dsh-reading-inbox
110
112
  | `reading_read` | 按 id 读取 Markdown 切片;用 `offset` / `nextOffset` 翻长文,`hasMore` 判断是否读完。 |
111
113
  | `reading_update` | 修改阅读状态或标签。状态:`unread` / `reading` / `read` / `archived`。 |
112
114
  | `reading_highlight` | 对文章做划线/批注:`action` 为 `create` / `list` / `update` / `delete`;`create` 传原文里的 `quote`(纯文本或 Markdown,服务端会去掉格式;也可传 `startOffset`/`endOffset`),可选 `note` 和 `color`。 |
115
+ | `reading_save_text` | 把粘贴的正文 / Markdown / HTML 保存成 clip;没有可抓取 URL 的登录页、付费墙、选中文字用它。`text` / `markdown` / `html` 至少一个。 |
113
116
 
114
117
  ## 配置
115
118
 
@@ -180,7 +183,7 @@ npm run dev # http://127.0.0.1:4173/dsh-reading-inbox/
180
183
 
181
184
  ```sh
182
185
  npm run build:client # 重新构建 client/client.js(esbuild)
183
- npm test # 36 个测试:提取、渲染、SSRF、DNS 校验、批注锚定、存储竞态、检索、路由、客户端 bundle
186
+ npm test # 38 个测试:提取、渲染、SSRF、DNS 校验、批注锚定、存储竞态、检索、路由、客户端 bundle
184
187
  npm run verify # 端到端自检
185
188
  ```
186
189
 
@@ -197,12 +200,12 @@ npm run verify # 端到端自检
197
200
 
198
201
  ## 限制与 Roadmap
199
202
 
200
- 当前版本是 0.3.0,刻意不做大而全:
203
+ 当前版本是 0.4.0,刻意不做大而全:
201
204
 
202
205
  - [ ] SPA / 登录页 / 反爬页可能提取不到正文;下一步加 Playwright fallback。
203
206
  - [ ] 图片仍引用远程地址;下一步下载到 `clips/<id>/assets/` 做完整离线存档。
204
207
  - [ ] 暂不支持 PDF;PDF 请用 `dsh-pdf-mineru` 或文档阅读插件。
205
- - [ ] 暂无浏览器扩展 / RSS 导入;先做 URL 输入和 Agent 工具。
208
+ - [ ] 暂无浏览器扩展 / RSS 导入;已有 URL、粘贴文本、JSON 导入/导出和 Agent 工具。
206
209
  - [ ] 暂无同步/备份;先保证本地目录可复制。
207
210
  - [ ] 检索是本地 BM25 风格排序;下一步加标题/正文分块与搜索结果高亮。
208
211
 
package/VERIFY.md CHANGED
@@ -62,6 +62,12 @@ dsh --profile inbox-web --no-open --port 4191
62
62
  3. 点搜索框下方的“+ 视图”,输入名称并保存;应出现视图 chip。
63
63
  4. 清空搜索后点该 chip,搜索框应恢复保存的查询,列表回到同一组结果;点 chip 上的 × 可删除视图。
64
64
 
65
+ ### 3.3 粘贴文本、导入与导出
66
+
67
+ 1. 点顶部“粘贴文本”,填标题和正文(不填 URL)后保存;左侧应出现来源为“手动保存”的条目,详情里不显示“打开原文”。
68
+ 2. 点顶部“导出”,应下载 `dsh-reading-inbox.json`;换一个空数据目录后点“导入”选择该文件,文章、批注和视图应恢复。
69
+ 3. 直接访问 `http://127.0.0.1:4191/dsh-reading-inbox/api/export?format=markdown`,应下载包含所有文章和批注的 Markdown。
70
+
65
71
  ## 4. Agent 工具
66
72
 
67
73
  在对话里说:
package/index.js CHANGED
@@ -11,8 +11,8 @@ const webDir = fileURLToPath(new URL('./web/', import.meta.url))
11
11
 
12
12
  /**
13
13
  * Mount the reading inbox: storage under ~/.dsh-reading-inbox, a web panel on
14
- * the host webserver, six reading_* tools, a /inbox command, and one system
15
- * prompt section so the model knows when to clip, search, and annotate.
14
+ * the host webserver, seven reading_* tools, a /inbox command, and one system
15
+ * prompt section so the model knows when to clip, save text, search, and annotate.
16
16
  */
17
17
  export function apply(ctx) {
18
18
  const config = loadConfig()
@@ -69,6 +69,7 @@ export function apply(ctx) {
69
69
  text: [
70
70
  '本机已安装阅读收件箱(dsh-reading-inbox)。',
71
71
  '当用户说“收藏 / 剪藏 / 稍后读 / 保存这个链接”时,调用 reading_clip。',
72
+ '当用户粘贴正文、选中文字,或内容没有可抓取的 URL 时,调用 reading_save_text(text/markdown/html 至少一个)。',
72
73
  '回答关于已保存文章的问题前,先用 reading_search 找到 clip id,再用 reading_read 读原文。',
73
74
  '当用户要求划线、高亮、批注、标记重点时,调用 reading_highlight:create 传 clip id 和原文中的 quote,可选 note/color;list 查看已有批注;update/delete 需要 annotationId。',
74
75
  '不要编造收件箱里没有的内容;如果搜索没有结果,明确说没有保存过。',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-reading-inbox",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "DeepSeek Harness 的阅读收件箱:网页剪藏、Markdown 存档、划线批注、标签、全文检索与 Agent 工具。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
package/src/markdown.js CHANGED
@@ -87,7 +87,7 @@ function makeTurndown(baseUrl) {
87
87
  return turndown
88
88
  }
89
89
 
90
- function countWords(text) {
90
+ export function countWords(text) {
91
91
  const cjk = (text.match(/[぀-ヿ㐀-䶿一-鿿가-힯]/g) || []).length
92
92
  const latin = (text.replace(/[぀-ヿ㐀-䶿一-鿿가-힯]/g, ' ').match(/[A-Za-z0-9_]+/g) || []).length
93
93
  return { wordCount: cjk + latin, charCount: text.length, cjk }
@@ -112,6 +112,13 @@ function clampText(value, maxLength) {
112
112
  return text.length > maxLength ? text.slice(0, maxLength) : text
113
113
  }
114
114
 
115
+ export function htmlToMarkdown(html, baseUrl = '') {
116
+ const document = parseHTML(`<!doctype html><html><body><div id="manual-root">${String(html ?? '')}</div></body></html>`).document
117
+ const root = document.getElementById('manual-root')
118
+ if (root === null) return ''
119
+ return cleanMarkdown(makeTurndown(baseUrl).turndown(root.innerHTML))
120
+ }
121
+
115
122
  /**
116
123
  * Turn raw HTML into a clean article: metadata, a Turndown Markdown body, and
117
124
  * a safe rendered HTML fragment. Readability runs on a fresh document so meta
package/src/routes.js CHANGED
@@ -130,6 +130,44 @@ async function handleApi(req, res, url, inbox) {
130
130
  return writeJson(res, 200, { ok: true, ...(await inbox.stats()) })
131
131
  }
132
132
 
133
+ if (segments[0] === 'export' && segments.length === 1) {
134
+ if (method !== 'GET') return writeError(res, 405, 'method not allowed')
135
+ const format = url.searchParams.get('format') || 'json'
136
+ if (format === 'markdown') {
137
+ const markdown = await inbox.exportAllMarkdown()
138
+ res.writeHead(200, {
139
+ ...commonHeaders('text/markdown; charset=utf-8'),
140
+ 'content-disposition': 'attachment; filename="dsh-reading-inbox.md"',
141
+ })
142
+ res.end(markdown)
143
+ return
144
+ }
145
+ if (format !== 'json') return writeError(res, 400, 'format 只支持 json 或 markdown')
146
+ const bundle = await inbox.exportBundle({
147
+ includeOriginal: url.searchParams.get('originals') === '1',
148
+ })
149
+ res.writeHead(200, {
150
+ ...commonHeaders('application/json; charset=utf-8'),
151
+ 'content-disposition': 'attachment; filename="dsh-reading-inbox.json"',
152
+ })
153
+ res.end(JSON.stringify(bundle, null, 2))
154
+ return
155
+ }
156
+
157
+ if (segments[0] === 'import' && segments.length === 1) {
158
+ if (method !== 'POST') return writeError(res, 405, 'method not allowed')
159
+ const body = await readJsonBody(req, 20 * 1024 * 1024)
160
+ const result = await inbox.importBundle(body)
161
+ return writeJson(res, 200, { ok: true, ...result })
162
+ }
163
+
164
+ if (segments[0] === 'save-text' && segments.length === 1) {
165
+ if (method !== 'POST') return writeError(res, 405, 'method not allowed')
166
+ const body = await readJsonBody(req, 2 * 1024 * 1024)
167
+ const result = await inbox.saveText(body)
168
+ return writeJson(res, 200, { ok: true, clip: result })
169
+ }
170
+
133
171
  if (segments[0] === 'views') {
134
172
  if (segments.length === 1) {
135
173
  if (method === 'GET') {
package/src/store.js CHANGED
@@ -6,10 +6,11 @@ import {
6
6
  buildAnnotationAnchor,
7
7
  normalizeColor,
8
8
  normalizeNote,
9
+ normalizeQuote,
9
10
  resolveAnnotations,
10
11
  } from './annotations.js'
11
12
  import { fetchHtml } from './fetch.js'
12
- import { exportMarkdown, parseArticle, renderMarkdown, renderedText } from './markdown.js'
13
+ import { countWords, exportMarkdown, htmlToMarkdown, parseArticle, renderMarkdown, renderedText } from './markdown.js'
13
14
  import { makeSnippet, parseQuery, queryTerms } from './search.js'
14
15
 
15
16
  const INDEX_VERSION = 1
@@ -26,6 +27,14 @@ function digest(value, length = 12) {
26
27
  return createHash('sha256').update(String(value)).digest('hex').slice(0, length)
27
28
  }
28
29
 
30
+ function safeClipId(value) {
31
+ return typeof value === 'string'
32
+ && /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(value)
33
+ && !value.includes('..')
34
+ ? value
35
+ : null
36
+ }
37
+
29
38
  function slugify(value) {
30
39
  const ascii = String(value ?? '')
31
40
  .normalize('NFKD')
@@ -427,6 +436,98 @@ export class ReadingInbox {
427
436
  return run
428
437
  }
429
438
 
439
+ async saveText(input = {}) {
440
+ await this.ready()
441
+ const rawMarkdown = String(input.markdown ?? '').trim()
442
+ const rawHtml = String(input.html ?? '').trim()
443
+ const rawText = String(input.text ?? '').trim()
444
+ if (rawMarkdown === '' && rawHtml === '' && rawText === '') {
445
+ throw new Error('需要 text、markdown 或 html')
446
+ }
447
+ const url = typeof input.url === 'string' && input.url.trim() !== ''
448
+ ? normalizeUrl(input.url)
449
+ : ''
450
+ const existing = url === '' ? undefined : this._byUrl.get(url)
451
+ if (existing !== undefined) {
452
+ const body = await this.readBody(existing.id).catch(() => '')
453
+ return { ...publicMeta(existing), duplicate: true, preview: body.slice(0, 500) }
454
+ }
455
+
456
+ return this._withMutation(async () => {
457
+ const current = url === '' ? undefined : this._byUrl.get(url)
458
+ if (current !== undefined) {
459
+ const body = await this.readBody(current.id).catch(() => '')
460
+ return { ...publicMeta(current), duplicate: true, preview: body.slice(0, 500) }
461
+ }
462
+
463
+ let markdown = rawMarkdown || (rawHtml !== '' ? htmlToMarkdown(rawHtml, url) : rawText)
464
+ markdown = markdown.trim()
465
+ if (markdown === '') throw new Error('内容为空')
466
+ let truncated = false
467
+ if (markdown.length > this.config.maxMarkdownChars) {
468
+ markdown = `${markdown.slice(0, this.config.maxMarkdownChars)}\n\n> 内容过长,已截断。`
469
+ truncated = true
470
+ }
471
+
472
+ const plain = renderedText(markdown)
473
+ const counts = countWords(plain)
474
+ const firstLine = plain.split(/\r?\n/).map(line => line.trim()).find(line => line !== '')
475
+ const titleSource = String(input.title ?? '').trim()
476
+ || firstLine
477
+ || (url === '' ? '未命名笔记' : (() => { try { return new URL(url).hostname } catch { return '未命名笔记' } })())
478
+ const title = titleSource.replace(/\s+/g, ' ').slice(0, 300)
479
+ const id = this.uniqueId(title, url || `text:${digest(markdown, 12)}`)
480
+ const explicitTags = normalizeTags([
481
+ ...(Array.isArray(input.tags) ? input.tags : []),
482
+ ...(this.config.defaultTags ?? []),
483
+ ])
484
+ const tags = explicitTags.length > 0
485
+ ? explicitTags
486
+ : normalizeTags((plain.match(/#[^\s#]+/g) ?? []).slice(0, 3).map(tag => tag.slice(1)))
487
+ const site = url === ''
488
+ ? '手动保存'
489
+ : (() => { try { return new URL(url).hostname } catch { return '手动保存' } })()
490
+ const meta = {
491
+ id,
492
+ url,
493
+ canonicalUrl: url,
494
+ title,
495
+ site,
496
+ author: '',
497
+ published: '',
498
+ clippedAt: nowIso(),
499
+ tags,
500
+ status: 'unread',
501
+ excerpt: plain.replace(/\s+/g, ' ').trim().slice(0, 240),
502
+ wordCount: counts.wordCount,
503
+ charCount: counts.charCount,
504
+ lang: counts.cjk > 0 ? 'zh' : 'en',
505
+ images: (markdown.match(/!\[[^\]]*\]\([^)]*\)/g) ?? []).length,
506
+ truncated,
507
+ annotationCount: 0,
508
+ contentHash: digest(markdown, 16),
509
+ manual: true,
510
+ articlePath: `clips/${id}/article.md`,
511
+ htmlPath: `clips/${id}/original.html`,
512
+ metaPath: `clips/${id}/meta.json`,
513
+ }
514
+
515
+ const clipDir = join(this.clipsDir, id)
516
+ await mkdir(clipDir, { recursive: true })
517
+ await writeFile(join(this.dir, meta.articlePath), `${markdown}\n`, 'utf8')
518
+ await writeFile(join(this.dir, meta.htmlPath), rawHtml || renderMarkdown(markdown), 'utf8')
519
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
520
+
521
+ this._clips.push(meta)
522
+ this._byId.set(meta.id, meta)
523
+ if (url !== '') this._byUrl.set(url, meta)
524
+ this._search.add(toSearchDoc(meta, markdown))
525
+ await this.persist()
526
+
527
+ return { ...publicMeta(meta), duplicate: false, preview: markdown.slice(0, 1_500) }
528
+ })
529
+ }
530
+
430
531
  async _clipOnce(url, options = {}) {
431
532
  const existing = this._byUrl.get(url)
432
533
  if (existing !== undefined && options.force !== true) {
@@ -731,6 +832,164 @@ export class ReadingInbox {
731
832
  return { meta: publicMeta(meta), markdown: exportMarkdown(meta, body, annotations) }
732
833
  }
733
834
 
835
+ async exportBundle(options = {}) {
836
+ await this.ready()
837
+ const clips = []
838
+ for (const meta of this._clips) {
839
+ const article = await this.readBody(meta.id).catch(() => '')
840
+ if (article === '') continue
841
+ const annotations = await this.readAnnotations(meta)
842
+ const item = { meta: publicMeta(meta), article, annotations }
843
+ if (options.includeOriginal === true) {
844
+ item.originalHtml = await readFile(join(this.dir, meta.htmlPath), 'utf8').catch(() => '')
845
+ }
846
+ clips.push(item)
847
+ }
848
+ return { version: 1, exportedAt: nowIso(), clips, views: await this.readViews() }
849
+ }
850
+
851
+ async exportAllMarkdown() {
852
+ await this.ready()
853
+ const parts = []
854
+ for (const meta of this._clips) {
855
+ const body = await this.readBody(meta.id).catch(() => '')
856
+ if (body === '') continue
857
+ const annotations = await this.listAnnotations(meta.id, body)
858
+ parts.push(exportMarkdown(meta, body, annotations))
859
+ }
860
+ return parts.join('\n\n---\n\n')
861
+ }
862
+
863
+ async importBundle(bundle) {
864
+ await this.ready()
865
+ if (bundle === null || typeof bundle !== 'object' || !Array.isArray(bundle.clips)) {
866
+ throw new Error('导入文件需要包含 clips 数组')
867
+ }
868
+ return this._withMutation(async () => {
869
+ let imported = 0
870
+ let skipped = 0
871
+ const errors = []
872
+ for (let index = 0; index < bundle.clips.length; index += 1) {
873
+ const raw = bundle.clips[index]
874
+ try {
875
+ if (raw === null || typeof raw !== 'object' || typeof raw.article !== 'string' || raw.article.trim() === '') {
876
+ skipped += 1
877
+ continue
878
+ }
879
+ const article = raw.article.trim()
880
+ if (article.length > 5_000_000) throw new Error('单篇正文超过 5 MB')
881
+ const metaIn = raw.meta !== null && typeof raw.meta === 'object' ? raw.meta : {}
882
+ let url = ''
883
+ if (typeof metaIn.url === 'string' && metaIn.url.trim() !== '') {
884
+ try { url = normalizeUrl(metaIn.url) } catch { url = '' }
885
+ }
886
+ if (url !== '' && this._byUrl.has(url)) {
887
+ skipped += 1
888
+ continue
889
+ }
890
+ const plain = renderedText(article)
891
+ const firstLine = plain.split(/\r?\n/).map(line => line.trim()).find(line => line !== '')
892
+ const title = (String(metaIn.title ?? '').trim() || firstLine || '导入文章')
893
+ .replace(/\s+/g, ' ')
894
+ .slice(0, 300)
895
+ const candidate = safeClipId(metaIn.id)
896
+ if (candidate !== null && this._byId.has(candidate)) {
897
+ skipped += 1
898
+ continue
899
+ }
900
+ const id = candidate === null
901
+ ? this.uniqueId(title, url || `import:${digest(article, 12)}`)
902
+ : candidate
903
+ const counts = countWords(plain)
904
+ const annotations = (Array.isArray(raw.annotations) ? raw.annotations : [])
905
+ .filter(annotation => annotation !== null && typeof annotation === 'object' && typeof annotation.id === 'string')
906
+ .map(annotation => ({
907
+ ...annotation,
908
+ quote: normalizeQuote(annotation.quote),
909
+ note: normalizeNote(annotation.note),
910
+ color: normalizeColor(annotation.color),
911
+ status: annotation.status === 'stale' ? 'stale' : 'active',
912
+ }))
913
+ const meta = {
914
+ id,
915
+ url,
916
+ canonicalUrl: typeof metaIn.canonicalUrl === 'string' ? metaIn.canonicalUrl : url,
917
+ title,
918
+ site: String(metaIn.site ?? (url === '' ? '导入' : '')).slice(0, 200),
919
+ author: String(metaIn.author ?? '').slice(0, 200),
920
+ published: String(metaIn.published ?? '').slice(0, 64),
921
+ clippedAt: typeof metaIn.clippedAt === 'string' && !Number.isNaN(Date.parse(metaIn.clippedAt))
922
+ ? metaIn.clippedAt
923
+ : nowIso(),
924
+ tags: normalizeTags(metaIn.tags),
925
+ status: STATUSES.has(metaIn.status) ? metaIn.status : 'unread',
926
+ excerpt: String(metaIn.excerpt ?? plain.replace(/\s+/g, ' ').trim().slice(0, 240)).slice(0, 240),
927
+ wordCount: counts.wordCount,
928
+ charCount: counts.charCount,
929
+ lang: counts.cjk > 0 ? 'zh' : 'en',
930
+ images: (article.match(/!\[[^\]]*\]\([^)]*\)/g) ?? []).length,
931
+ truncated: metaIn.truncated === true,
932
+ annotationCount: annotations.length,
933
+ contentHash: digest(article, 16),
934
+ manual: metaIn.manual === true,
935
+ articlePath: `clips/${id}/article.md`,
936
+ htmlPath: `clips/${id}/original.html`,
937
+ metaPath: `clips/${id}/meta.json`,
938
+ }
939
+ const originalHtml = typeof raw.originalHtml === 'string' && raw.originalHtml !== ''
940
+ ? raw.originalHtml
941
+ : renderMarkdown(article)
942
+ const clipDir = join(this.clipsDir, id)
943
+ await mkdir(clipDir, { recursive: true })
944
+ await writeFile(join(this.dir, meta.articlePath), `${article}\n`, 'utf8')
945
+ await writeFile(join(this.dir, meta.htmlPath), originalHtml, 'utf8')
946
+ await writeFile(join(this.dir, meta.metaPath), `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
947
+ if (annotations.length > 0) {
948
+ await writeJsonAtomic(this.annotationPath(meta), {
949
+ version: 1,
950
+ contentVersion: meta.contentHash,
951
+ annotations,
952
+ })
953
+ }
954
+ this._clips.push(meta)
955
+ this._byId.set(meta.id, meta)
956
+ if (url !== '') this._byUrl.set(url, meta)
957
+ if (meta.canonicalUrl !== '') this._byUrl.set(meta.canonicalUrl, meta)
958
+ this._search.add(toSearchDoc(meta, article))
959
+ imported += 1
960
+ } catch (error) {
961
+ errors.push({ index, message: error instanceof Error ? error.message : String(error) })
962
+ }
963
+ }
964
+
965
+ let viewsImported = 0
966
+ if (Array.isArray(bundle.views) && bundle.views.length > 0) {
967
+ const views = await this.readViews()
968
+ const existing = new Set(views.map(view => view.query))
969
+ for (const raw of bundle.views) {
970
+ if (raw === null || typeof raw !== 'object') continue
971
+ const name = String(raw.name ?? '').trim().slice(0, 60)
972
+ const query = String(raw.query ?? '').trim().slice(0, 500)
973
+ if (name === '' || query === '' || existing.has(query)) continue
974
+ const now = nowIso()
975
+ views.push({
976
+ id: `view-${digest(`${query}\n${now}`, 10)}`,
977
+ name,
978
+ query,
979
+ createdAt: now,
980
+ updatedAt: now,
981
+ })
982
+ existing.add(query)
983
+ viewsImported += 1
984
+ }
985
+ if (viewsImported > 0) await writeJsonAtomic(this.viewsPath, { version: 1, views })
986
+ }
987
+
988
+ if (imported > 0) await this.persist()
989
+ return { imported, skipped, viewsImported, errors }
990
+ })
991
+ }
992
+
734
993
  async persist() {
735
994
  const snapshot = { version: INDEX_VERSION, clips: this._clips }
736
995
  this._writeChain = this._writeChain
package/src/tools.js CHANGED
@@ -164,6 +164,53 @@ export function registerTools(ctx, { inbox }) {
164
164
  },
165
165
  })
166
166
 
167
+ ctx.tools.register({
168
+ name: 'reading_save_text',
169
+ description:
170
+ 'Save pasted text, Markdown, or HTML as a local reading-inbox clip when there is no fetchable URL. ' +
171
+ 'Use this for login-walled pages, paywalled snippets, selections, or notes the user wants to keep. ' +
172
+ 'Provide at least one of text, markdown, or html; title, url and tags are optional.',
173
+ parameters: {
174
+ type: 'object',
175
+ additionalProperties: false,
176
+ properties: {
177
+ title: { type: 'string', description: 'Optional title; first non-empty line is used otherwise.' },
178
+ text: { type: 'string', description: 'Plain text content.' },
179
+ markdown: { type: 'string', description: 'Markdown content; takes precedence over text.' },
180
+ html: { type: 'string', description: 'HTML content; converted to Markdown and archived as original.html.' },
181
+ url: { type: 'string', description: 'Optional source URL for attribution and duplicate detection.' },
182
+ tags: { type: 'array', items: { type: 'string' } },
183
+ },
184
+ required: [],
185
+ },
186
+ output: {
187
+ schema: {
188
+ type: 'object',
189
+ additionalProperties: false,
190
+ properties: clipProperties,
191
+ required: clipRequired,
192
+ },
193
+ render: (_args, value) => {
194
+ const lines = renderMeta(value, [])
195
+ if (value.duplicate) lines.push('note: this URL is already in the inbox; returning the existing clip.')
196
+ lines.push('', 'preview:', value.preview)
197
+ return text(lines.join('\n'))
198
+ },
199
+ },
200
+ timeoutMs: 15_000,
201
+ isConcurrencySafe: () => false,
202
+ async execute(args) {
203
+ return inbox.saveText({
204
+ title: args?.title,
205
+ text: args?.text,
206
+ markdown: args?.markdown,
207
+ html: args?.html,
208
+ url: args?.url,
209
+ tags: Array.isArray(args?.tags) ? args.tags : [],
210
+ })
211
+ },
212
+ })
213
+
167
214
  ctx.tools.register({
168
215
  name: 'reading_search',
169
216
  description:
package/web/app.js CHANGED
@@ -27,6 +27,17 @@ const els = {
27
27
  clipUrl: $('#clip-url'),
28
28
  clipTags: $('#clip-tags'),
29
29
  clipSubmit: $('#clip-submit'),
30
+ saveTextToggle: $('#save-text-toggle'),
31
+ textPanel: $('#text-panel'),
32
+ textForm: $('#text-form'),
33
+ textTitle: $('#text-title'),
34
+ textUrl: $('#text-url'),
35
+ textTags: $('#text-tags'),
36
+ textBody: $('#text-body'),
37
+ textCancel: $('#text-cancel'),
38
+ exportAll: $('#export-all'),
39
+ importToggle: $('#import-toggle'),
40
+ importFile: $('#import-file'),
30
41
  tagFilter: $('#tag-filter'),
31
42
  tagFilterName: $('#tag-filter-name'),
32
43
  tagClear: $('#tag-clear'),
@@ -101,7 +112,6 @@ function toast(message, isError = false) {
101
112
 
102
113
  async function api(path, options = {}) {
103
114
  const response = await fetch(`./api${path}`, {
104
- credentials: 'same-origin',
105
115
  ...options,
106
116
  headers: {
107
117
  ...(options.body === undefined ? {} : { 'content-type': 'application/json' }),
@@ -558,6 +568,7 @@ function renderDetail() {
558
568
  const author = item.author ? `<span>${escapeHtml(item.author)}</span><span>·</span>` : ''
559
569
  const published = item.published ? `<span>${escapeHtml(item.published.slice(0, 10))}</span><span>·</span>` : ''
560
570
  const truncated = item.truncated ? '<p class="article-note">原文较长,保存时已截断。</p>' : ''
571
+ const sourceLink = item.url ? `<a href="${escapeAttr(item.url)}" target="_blank" rel="noopener noreferrer">打开原文</a>` : ''
561
572
  const annotations = Array.isArray(item.annotations) ? item.annotations : []
562
573
  const annotationMeta = annotations.length > 0
563
574
  ? `<span>·</span><span>${annotations.length} 批注</span>`
@@ -573,8 +584,7 @@ function renderDetail() {
573
584
  </div>
574
585
  <h2>${escapeHtml(item.title)}</h2>
575
586
  <div class="detail-sub">
576
- ${author}${published}
577
- <a href="${escapeAttr(item.url)}" target="_blank" rel="noopener noreferrer">打开原文</a>
587
+ ${author}${published}${sourceLink}
578
588
  </div>
579
589
  <div class="actions">
580
590
  <button type="button" class="button ghost mobile-back" data-action="back">返回</button>
@@ -683,6 +693,98 @@ els.clipForm.addEventListener('submit', async event => {
683
693
  })
684
694
 
685
695
  let searchTimer
696
+ function showTextPanel() {
697
+ if (!els.textPanel) return
698
+ els.textPanel.hidden = false
699
+ els.textTitle.value = ''
700
+ els.textUrl.value = ''
701
+ els.textTags.value = ''
702
+ els.textBody.value = ''
703
+ els.textBody.focus()
704
+ }
705
+
706
+ function hideTextPanel() {
707
+ if (!els.textPanel) return
708
+ els.textPanel.hidden = true
709
+ }
710
+
711
+ if (els.saveTextToggle) els.saveTextToggle.addEventListener('click', showTextPanel)
712
+ if (els.textCancel) els.textCancel.addEventListener('click', hideTextPanel)
713
+ if (els.textForm) {
714
+ els.textForm.addEventListener('submit', async event => {
715
+ event.preventDefault()
716
+ const text = els.textBody.value.trim()
717
+ if (text === '') {
718
+ els.textBody.focus()
719
+ return
720
+ }
721
+ const submit = els.textForm.querySelector('button[type="submit"]')
722
+ if (submit) submit.disabled = true
723
+ try {
724
+ const data = await api('/save-text', {
725
+ method: 'POST',
726
+ body: JSON.stringify({
727
+ title: els.textTitle.value.trim(),
728
+ url: els.textUrl.value.trim(),
729
+ tags: els.textTags.value.split(/[,,]/).map(value => value.trim()).filter(Boolean),
730
+ text,
731
+ }),
732
+ })
733
+ const clip = data.clip
734
+ hideTextPanel()
735
+ toast(clip.duplicate ? '这个链接已经在收件箱里了' : '已保存到阅读收件箱')
736
+ await loadStats()
737
+ await loadList()
738
+ await select(clip.id)
739
+ } catch (error) {
740
+ toast(error.message, true)
741
+ } finally {
742
+ if (submit) submit.disabled = false
743
+ }
744
+ })
745
+ }
746
+
747
+ async function exportAll() {
748
+ try {
749
+ const response = await fetch('./api/export?format=json')
750
+ if (!response.ok) throw new Error(`导出失败:HTTP ${response.status}`)
751
+ const blob = await response.blob()
752
+ const link = document.createElement('a')
753
+ const url = URL.createObjectURL(blob)
754
+ link.href = url
755
+ link.download = 'dsh-reading-inbox.json'
756
+ document.body.append(link)
757
+ link.click()
758
+ link.remove()
759
+ setTimeout(() => URL.revokeObjectURL(url), 1_000)
760
+ toast('已导出全部')
761
+ } catch (error) {
762
+ toast(error.message, true)
763
+ }
764
+ }
765
+
766
+ if (els.exportAll) els.exportAll.addEventListener('click', exportAll)
767
+ if (els.importToggle && els.importFile) {
768
+ els.importToggle.addEventListener('click', () => els.importFile.click())
769
+ els.importFile.addEventListener('change', async () => {
770
+ const file = els.importFile.files?.[0]
771
+ if (!file) return
772
+ try {
773
+ const bundle = JSON.parse(await file.text())
774
+ const data = await api('/import', { method: 'POST', body: JSON.stringify(bundle) })
775
+ const errors = Array.isArray(data.errors) && data.errors.length > 0 ? `,${data.errors.length} 条错误` : ''
776
+ toast(`导入 ${data.imported} 篇,跳过 ${data.skipped} 篇${errors}`)
777
+ await loadStats()
778
+ await loadList()
779
+ await loadViews()
780
+ } catch (error) {
781
+ toast(error.message, true)
782
+ } finally {
783
+ els.importFile.value = ''
784
+ }
785
+ })
786
+ }
787
+
686
788
  els.search.addEventListener('input', () => {
687
789
  clearTimeout(searchTimer)
688
790
  searchTimer = setTimeout(() => {
package/web/index.html CHANGED
@@ -25,8 +25,27 @@
25
25
  </div>
26
26
  <button type="submit" class="primary" id="clip-submit">保存</button>
27
27
  </form>
28
+ <button type="button" id="save-text-toggle" class="button">粘贴文本</button>
29
+ <button type="button" id="export-all" class="button">导出</button>
30
+ <button type="button" id="import-toggle" class="button">导入</button>
31
+ <input id="import-file" type="file" accept="application/json,.json" hidden>
28
32
  </header>
29
33
 
34
+ <section id="text-panel" class="text-panel" hidden>
35
+ <form id="text-form" class="text-form">
36
+ <div class="text-form-row">
37
+ <input id="text-title" type="text" placeholder="标题(可选)">
38
+ <input id="text-url" type="text" placeholder="来源链接(可选)">
39
+ <input id="text-tags" type="text" placeholder="标签,逗号分隔(可选)">
40
+ </div>
41
+ <textarea id="text-body" rows="8" placeholder="粘贴正文、Markdown 或 HTML…" required></textarea>
42
+ <div class="text-form-actions">
43
+ <button type="submit" class="button primary">保存到收件箱</button>
44
+ <button type="button" id="text-cancel" class="button ghost">取消</button>
45
+ </div>
46
+ </form>
47
+ </section>
48
+
30
49
  <main class="layout" id="layout">
31
50
  <aside class="list-pane">
32
51
  <div class="list-head">
package/web/style.css CHANGED
@@ -812,3 +812,54 @@ mark.hl.pulse {
812
812
  border-radius: 8px;
813
813
  background: var(--panel-2);
814
814
  }
815
+
816
+ .text-panel {
817
+ padding: 12px 18px;
818
+ background: var(--panel);
819
+ border-bottom: 1px solid var(--border);
820
+ }
821
+
822
+ .text-panel[hidden] { display: none; }
823
+
824
+ .text-form {
825
+ display: flex;
826
+ flex-direction: column;
827
+ gap: 8px;
828
+ max-width: 980px;
829
+ }
830
+
831
+ .text-form-row {
832
+ display: flex;
833
+ gap: 8px;
834
+ flex-wrap: wrap;
835
+ }
836
+
837
+ .text-form-row input {
838
+ flex: 1 1 220px;
839
+ min-width: 0;
840
+ height: 30px;
841
+ padding: 0 8px;
842
+ border: 1px solid var(--border);
843
+ border-radius: 8px;
844
+ background: var(--panel-2);
845
+ }
846
+
847
+ .text-form textarea {
848
+ width: 100%;
849
+ min-height: 140px;
850
+ resize: vertical;
851
+ padding: 9px;
852
+ border: 1px solid var(--border);
853
+ border-radius: 8px;
854
+ background: var(--panel-2);
855
+ color: var(--text);
856
+ font: inherit;
857
+ line-height: 1.5;
858
+ }
859
+
860
+ .text-form-actions { display: flex; gap: 6px; }
861
+
862
+ @media (max-width: 820px) {
863
+ .text-panel { padding: 10px 12px; }
864
+ .text-form-row input { flex-basis: 100%; }
865
+ }