dsh-verbatim 0.0.0-stage → 0.1.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/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.en.md +166 -0
- package/README.md +165 -2
- package/bin/cli.mjs +58 -0
- package/bin/mcp-memory.mjs +235 -0
- package/client.js +9650 -0
- package/cordis.patch.yml +11 -0
- package/docs/ARCHITECTURE.md +35 -0
- package/docs/TOOLS.md +36 -0
- package/docs/banner.png +0 -0
- package/icon.svg +14 -0
- package/index.js +2558 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +95 -4
- package/sessions/qqb-p-0000000000-00000000000000000000000000000000.json +12 -0
- package/src/config/_test-entry.js +11 -0
- package/src/config/exclude-range.js +481 -0
- package/src/config/exclude-range.test.js +412 -0
- package/src/config/global-config.js +255 -0
- package/src/config/package.json +8 -0
- package/src/config/session-config.js +413 -0
- package/src/config/session-config.test.js +375 -0
- package/src/derive/_test-entry.js +18 -0
- package/src/derive/beat.js +194 -0
- package/src/derive/beat.test.js +323 -0
- package/src/derive/fact.js +277 -0
- package/src/derive/fact.test.js +389 -0
- package/src/derive/gist.js +649 -0
- package/src/derive/gist.test.js +294 -0
- package/src/derive/package.json +8 -0
- package/src/derive/prompts.js +299 -0
- package/src/host/config-views.js +182 -0
- package/src/host/db-admin.js +703 -0
- package/src/host/dsh-llm.js +90 -0
- package/src/host/probe.js +262 -0
- package/src/host/rebuild.js +593 -0
- package/src/host/scene-ops.js +542 -0
- package/src/host/session-lock.js +37 -0
- package/src/index.js +101 -0
- package/src/ingest/cli.js +501 -0
- package/src/ingest/export.js +957 -0
- package/src/ingest/export.test.js +1162 -0
- package/src/ingest/package.json +4 -0
- package/src/ingest/reader.js +243 -0
- package/src/model/embedding.js +336 -0
- package/src/model/llm.js +273 -0
- package/src/model/mock.js +193 -0
- package/src/model/model.test.js +420 -0
- package/src/model/package.json +8 -0
- package/src/model/rerank.js +161 -0
- package/src/package.json +4 -0
- package/src/pipeline.js +1472 -0
- package/src/scene/link.js +200 -0
- package/src/scene/package.json +4 -0
- package/src/scene/split.js +675 -0
- package/src/scene/split.test.js +575 -0
- package/src/scene/verify.js +214 -0
- package/src/search/_fixtures.js +106 -0
- package/src/search/_test-entry.js +19 -0
- package/src/search/bench.js +267 -0
- package/src/search/cache-concurrent.test.js +84 -0
- package/src/search/cache-contract.test.js +102 -0
- package/src/search/chunk.js +226 -0
- package/src/search/chunk.test.js +128 -0
- package/src/search/dedupe.js +271 -0
- package/src/search/indexer.js +879 -0
- package/src/search/indexer.test.js +481 -0
- package/src/search/note-rank.js +192 -0
- package/src/search/package.json +9 -0
- package/src/search/regression.test.js +386 -0
- package/src/search/rrf.js +365 -0
- package/src/search/rrf.test.js +374 -0
- package/src/search/scene-fallback.js +12 -0
- package/src/search/session-shape.js +86 -0
- package/src/search/session-shape.test.js +144 -0
- package/src/search/thread.js +300 -0
- package/src/search/thread.test.js +116 -0
- package/src/search/vector-store.js +1598 -0
- package/src/search/vector-store.test.js +345 -0
- package/src/search/window.js +310 -0
- package/src/search/window.test.js +308 -0
- package/src/store/db.js +715 -0
- package/src/store/note-session-migration.test.js +157 -0
- package/src/store/package.json +5 -0
- package/src/store/repo.js +2133 -0
- package/src/store/repo.test.js +1043 -0
- package/src/store/schema.sql +334 -0
- package/src/tools/format.js +503 -0
- package/src/tools/index.js +349 -0
- package/src/tools/isolation.test.js +405 -0
- package/src/tools/memory-forget.js +490 -0
- package/src/tools/memory-remember.js +349 -0
- package/src/tools/memory-search.js +2206 -0
- package/src/tools/merge-search.test.js +444 -0
- package/src/tools/package.json +5 -0
- package/src/tools/refusal-hint.test.js +51 -0
- package/src/tools/remember-forget.test.js +442 -0
- package/src/tools/scope.js +106 -0
- package/src/tools/time-route.js +747 -0
- package/src/tools/tools.test.js +968 -0
- package/src/tools/vector-gate.test.js +460 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `dsh-verbatim` are documented here.
|
|
4
|
+
|
|
5
|
+
## [0.1.0] - 2026-11-23
|
|
6
|
+
|
|
7
|
+
### Companion-First Memory & Retrieval
|
|
8
|
+
- **Verbatim SQLite Storage**: Persists complete conversation history (including compacted turns) in local SQLite (`node:sqlite`, `FTS5`, optional `sqlite-vec` with cosine fallback) with strict per-session isolation and physical deletion on rewind.
|
|
9
|
+
- **Companion Dual-Granularity Pipeline**: Defaults new and rebuilt sessions to `exchange` → `thread` segmentation with 30-minute settle windows, scene merge/split locking, and timeline cluster folding.
|
|
10
|
+
- **Hybrid Search + Optional Rerank**: Parallel keyword (`FTS5` trigram + 2-char CJK `LIKE`) and multi-granularity vector KNN fused via RRF (`k = 60`), with candidate pool expansion (`perRoute >= 24`) when `/rerank` is enabled.
|
|
11
|
+
- **Media Attachments & Captions**: Extracts attachment metadata (`sha256:` / local path / URL), resolves host attachment paths and user captions directly inside `memory_search` results, and supports inline preview & caption editing in the Library view.
|
|
12
|
+
|
|
13
|
+
### Agent Tools & Privacy Hardening
|
|
14
|
+
- **3-Tool Minimalist Surface**: Exposes `memory_search`, `memory_remember`, and `memory_forget` returning clean, compact plain-text dialogue blocks (`Speaker: text`).
|
|
15
|
+
- **Strict Exclusion Boundary**: Removed `includeExcluded` from the Agent tool schema and hints; excluded ranges and muted messages are only accessible to the user in the host UI.
|
|
16
|
+
- **Trash Discoverability**: `memory_search(scope='note')` surfaces recoverable trash note IDs so `memory_forget(restore: true)` is reachable.
|
|
17
|
+
- **Live Tool Hot-Reload**: Toggling `tools` in the panel immediately re-registers tools on active host agents without restarting.
|
|
18
|
+
|
|
19
|
+
### Material 3 Companion UI
|
|
20
|
+
- **6 Sidebar Tabs**: Overview (Hero sanctuary card, tonal KPI tiles, 38px circular Recall Readiness gauge, collapsible diagnostics), Search, Timeline (chat-bubble styling with hover-reveal actions), Notes (color-coded by ownership, duplicate merge, 30-day trash), Verify, and Library (session overview with 2-step delete, data browser with media caption editor, read-only SQL).
|
|
21
|
+
- **5 Global Settings Tabs**: General & Retrieval (with 3-step interactive Setup Guide), Sessions, Embedding (local service auto-probe + dimension detection), Rerank, and optional Summary LLM.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-verbatim contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.en.md
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="docs/banner.png" alt="dsh-verbatim — Companion-first verbatim long-term memory plugin for DeepSeek Harness" width="100%">
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">dsh-verbatim</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">Every word kept intact · Companion-first verbatim long-term memory plugin for DeepSeek Harness.</p>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
<img src="https://img.shields.io/badge/version-0.1.0-0F172A" alt="Version 0.1.0">
|
|
11
|
+
<img src="https://img.shields.io/badge/node-%3E%3D24-339933?logo=node.js&logoColor=white" alt="Node >=24">
|
|
12
|
+
<img src="https://img.shields.io/badge/storage-node%3Asqlite%20%2B%20FTS5-003B57?logo=sqlite&logoColor=white" alt="node:sqlite + FTS5">
|
|
13
|
+
<a href=".github/workflows/ci.yml"><img src="https://img.shields.io/badge/CI-GitHub%20Actions-2088FF?logo=github-actions&logoColor=white" alt="CI"></a>
|
|
14
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-2563EB" alt="MIT License"></a>
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+
<p align="center">
|
|
18
|
+
<a href="#what-it-does">What It Does</a> ·
|
|
19
|
+
<a href="#retrieval-example">Example</a> ·
|
|
20
|
+
<a href="#quick-start">Quick Start</a> ·
|
|
21
|
+
<a href="#how-it-works">How It Works</a> ·
|
|
22
|
+
<a href="#privacy--security">Privacy & Security</a> ·
|
|
23
|
+
<a href="#compatibility">Compatibility</a> ·
|
|
24
|
+
<a href="#uninstall">Uninstall</a> ·
|
|
25
|
+
<a href="#documentation">Docs</a> ·
|
|
26
|
+
<a href="#development">Development</a> ·
|
|
27
|
+
<a href="README.md">简体中文</a>
|
|
28
|
+
</p>
|
|
29
|
+
|
|
30
|
+
> `dsh-verbatim` is a community plugin for DeepSeek Harness (also providing a CLI and stdio MCP Server) built for AI companion conversations, without modifying DeepSeek Harness source files.
|
|
31
|
+
>
|
|
32
|
+
> **Current version: 0.1.0**. Powered by Node.js `>=24` built-in `node:sqlite` and FTS5. All verbatim messages, derived indexes, and settings stay local in `$DSH_HOME/verbatim/`.
|
|
33
|
+
|
|
34
|
+
`dsh-verbatim` keeps every conversation message word for word in a local SQLite database, automatically organizes exchanges and micro-topics, and brings back full original context through hybrid keyword + vector retrieval and optional reranking even after context compaction.
|
|
35
|
+
|
|
36
|
+
## What It Does
|
|
37
|
+
|
|
38
|
+
- **Verbatim source of truth, rebuildable derived layers**: The `msg` table is append-only (rewinds/deletes physically remove the message and its vectors); past conversations remain intact after context compaction.
|
|
39
|
+
- **Companion-first dual granularity (`exchange` → `thread`)**: Automatically segments natural chats into single exchanges and micro-topics, with 30-minute idle scene boundaries, scene merge/split locking, and timeline cluster folding.
|
|
40
|
+
- **Always-hybrid retrieval + optional reranking**: Runs FTS5 trigram / 2-character CJK `LIKE` in parallel with multi-granularity vector search (`vec_msg`, `vec_chunk`, `vec_scene`, `vec_note`), fused via RRF with optional `/rerank` rescoring (and automatic fallback).
|
|
41
|
+
- **Image attachments & captions**: Records image attachments and resolved local paths, supports inline preview and caption editing in the sidebar panel, and returns both paths and captions to the model.
|
|
42
|
+
- **Strict session isolation & privacy boundaries**: Settings and data are isolated per `session_id`; user-configured private exclude time ranges and per-message "do not recall" flags are completely invisible to Agent tools and cannot be bypassed via parameters.
|
|
43
|
+
- **Material 3 companion UI**: Includes **6 sidebar views** (Overview, Search, Timeline, Notes, Audit, Library) and **5 global settings tabs** (3-step setup guide, local model probing, session data management, and read-only SQL diagnostics).
|
|
44
|
+
|
|
45
|
+
## Retrieval Example
|
|
46
|
+
|
|
47
|
+
When the model calls `memory_search`, it receives plain-text results with exact time spans, compact dialogue lines, and hit markers (synthetic example below):
|
|
48
|
+
|
|
49
|
+
```text
|
|
50
|
+
「周末去公园」— 3 处
|
|
51
|
+
|
|
52
|
+
11-16 14:10–14:25 · 6轮 · 92字 · 命中 2 处
|
|
53
|
+
我:周六天气不错,去公园散步吗?
|
|
54
|
+
他:好呀,顺便去湖边坐坐 kw+vec ←
|
|
55
|
+
我:记得带上相机和防晒。 kw+vec ←
|
|
56
|
+
他:"/path/to/dsh_home/attachments/v1/objects/00/0000...png" [图片]
|
|
57
|
+
[图片备注:公园湖边的长椅]
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Quick Start
|
|
61
|
+
|
|
62
|
+
Make sure **Node.js `>=24`** is installed (uses built-in `node:sqlite`, no native C++ build toolchain required), then mount the plugin in DeepSeek Harness.
|
|
63
|
+
|
|
64
|
+
### 1. Install & Mount
|
|
65
|
+
|
|
66
|
+
```powershell
|
|
67
|
+
git clone https://github.com/saya-ch/dsh-verbatim.git
|
|
68
|
+
cd dsh-verbatim
|
|
69
|
+
npm install --no-audit --no-fund
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
#### Official DSH Desktop
|
|
73
|
+
|
|
74
|
+
Point to and enable the local `dsh-verbatim` directory from the **Plugins** page in DSH Desktop (the repository includes [cordis.patch.yml](cordis.patch.yml) and [package.json](package.json) manifests). Desktop profiles are managed by the app and do not use `--profile web` commands.
|
|
75
|
+
|
|
76
|
+
#### DSH Web
|
|
77
|
+
|
|
78
|
+
Mount this repository in your Web profile plugin configuration and start DSH:
|
|
79
|
+
|
|
80
|
+
```powershell
|
|
81
|
+
dsh --profile web
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
<details>
|
|
85
|
+
<summary>Using DeepSeek Harness from source or standalone CLI / MCP Server</summary>
|
|
86
|
+
|
|
87
|
+
In a DeepSeek Harness source checkout, run `pnpm dsh --profile web` with this plugin directory mounted.
|
|
88
|
+
|
|
89
|
+
You can also use the CLI or run a standard stdio MCP Server standalone:
|
|
90
|
+
|
|
91
|
+
```powershell
|
|
92
|
+
# CLI tool (ingest, search, stats, verify)
|
|
93
|
+
node bin/cli.mjs --help
|
|
94
|
+
|
|
95
|
+
# Start stdio MCP Server
|
|
96
|
+
node bin/mcp-memory.mjs
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
</details>
|
|
100
|
+
|
|
101
|
+
The database, global config, and per-session switches are stored under `$DSH_HOME/verbatim/` (defaults to `~/.dsh/verbatim/` if `DSH_HOME` is unset):
|
|
102
|
+
|
|
103
|
+
- `memory.db`: SQLite verbatim store and derived indexes
|
|
104
|
+
- `config.json`: Global embedding, rerank, and LLM settings
|
|
105
|
+
- `sessions/<session-id>.json`: Per-session toggles and private exclude ranges
|
|
106
|
+
|
|
107
|
+
### 2. Three Steps to Enable
|
|
108
|
+
|
|
109
|
+
1. Open **Settings → Verbatim Memory → Embedding**, choose a local service (Ollama / LM Studio auto-detection supported) or enter an OpenAI-compatible `/v1/embeddings` endpoint and test connectivity.
|
|
110
|
+
2. *(Optional)* Enable `/rerank` under **Rerank** to improve ranking accuracy on long histories.
|
|
111
|
+
3. Open the **Verbatim Memory** sidebar panel in any conversation and turn on **Remember new messages** and **Allow recall** (takes effect immediately without restarting).
|
|
112
|
+
|
|
113
|
+
## How It Works
|
|
114
|
+
|
|
115
|
+
```mermaid
|
|
116
|
+
flowchart LR
|
|
117
|
+
Chat["DSH Messages & Attachments"] -->|"Verbatim ingest"| Msg["msg table"]
|
|
118
|
+
Msg -->|"Companion split"| Gran["exchange / thread"]
|
|
119
|
+
Gran -->|"Hybrid index"| Index["FTS5 + Multi-granularity Vectors"]
|
|
120
|
+
Index -->|"RRF + Optional Rerank"| Tools["Agent Tools (search / around / timeline)"]
|
|
121
|
+
Tools -->|"Privacy-filtered"| Model["Active Chat Model"]
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
The plugin registers the ingest pipeline, search service, and 3 read-only Agent tools (`memory_search`, `memory_around`, `memory_timeline`) on the Host side, and injects the 6-view sidebar panel and 5-tab settings page on the Client side—without modifying DeepSeek Harness core files. See [Architecture](docs/ARCHITECTURE.md) for schema and lock details.
|
|
125
|
+
|
|
126
|
+
## Privacy & Security
|
|
127
|
+
|
|
128
|
+
- **Local-first storage**: Except for the embedding (`/v1/embeddings`), rerank (`/rerank`), or optional summary LLM endpoints you configure, all memories, captions, and settings stay local in `$DSH_HOME/verbatim/`.
|
|
129
|
+
- **Hard privacy boundaries**: Excluded time ranges and per-message exclusions are filtered directly at the storage/retrieval layer and cannot be bypassed by Agent tool parameters.
|
|
130
|
+
- **Physical rewind/delete**: Rewinding or deleting messages in DSH physically removes the corresponding rows and vectors from `memory.db`.
|
|
131
|
+
- **Read-only SQL diagnostics**: The SQL diagnostic tab in Settings only allows read-only queries.
|
|
132
|
+
|
|
133
|
+
## Compatibility
|
|
134
|
+
|
|
135
|
+
- **Node.js**: Requires `>=24` (relies on built-in `node:sqlite`).
|
|
136
|
+
- **`sqlite-vec`**: Listed in `optionalDependencies`. If unavailable on the host platform, vector search automatically falls back to pure-SQLite cosine similarity with equivalent recall results.
|
|
137
|
+
|
|
138
|
+
## Uninstall
|
|
139
|
+
|
|
140
|
+
Removing `dsh-verbatim` from your DeepSeek Harness plugin configuration **does not delete** `$DSH_HOME/verbatim/`. Re-mounting the plugin restores access to your existing memories.
|
|
141
|
+
|
|
142
|
+
To remove all local data permanently, back up `memory.db` or `sessions/*.json` if needed, remove the plugin, and then delete `$DSH_HOME/verbatim/`.
|
|
143
|
+
|
|
144
|
+
## Documentation
|
|
145
|
+
|
|
146
|
+
- [Architecture](docs/ARCHITECTURE.md): Storage schema, companion dual-granularity splitting, hybrid retrieval, and write locks
|
|
147
|
+
- [Agent Tools & Privacy](docs/TOOLS.md): Complete schemas, output formats, and privacy isolation guarantees
|
|
148
|
+
- [Changelog](CHANGELOG.md): Release notes
|
|
149
|
+
- [Contributing](CONTRIBUTING.md): Development workflow, verification commands, and synthetic test data policy
|
|
150
|
+
|
|
151
|
+
## Development
|
|
152
|
+
|
|
153
|
+
```powershell
|
|
154
|
+
# Rebuild client.js from src/client/*.js
|
|
155
|
+
npm run build:client
|
|
156
|
+
|
|
157
|
+
# Bundle consistency, TypeScript check, and syntax checks
|
|
158
|
+
npm run check
|
|
159
|
+
|
|
160
|
+
# Run full unit and frontend rendering test suite
|
|
161
|
+
npm test
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## License
|
|
165
|
+
|
|
166
|
+
[MIT](LICENSE)
|
package/README.md
CHANGED
|
@@ -1,3 +1,166 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="docs/banner.png" alt="dsh-verbatim — 为 DeepSeek Harness 打造的陪伴向长期逐字记忆插件" width="100%">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<h1 align="center">dsh-verbatim</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">Every word kept intact · 为 DeepSeek Harness 打造的陪伴向长期逐字记忆插件。</p>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
<img src="https://img.shields.io/badge/version-0.1.0-0F172A" alt="版本 0.1.0">
|
|
11
|
+
<img src="https://img.shields.io/badge/node-%3E%3D24-339933?logo=node.js&logoColor=white" alt="Node >=24">
|
|
12
|
+
<img src="https://img.shields.io/badge/storage-node%3Asqlite%20%2B%20FTS5-003B57?logo=sqlite&logoColor=white" alt="node:sqlite + FTS5">
|
|
13
|
+
<a href=".github/workflows/ci.yml"><img src="https://img.shields.io/badge/CI-GitHub%20Actions-2088FF?logo=github-actions&logoColor=white" alt="CI"></a>
|
|
14
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-2563EB" alt="MIT License"></a>
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+
<p align="center">
|
|
18
|
+
<a href="#能做什么">能做什么</a> ·
|
|
19
|
+
<a href="#检索返回示例">检索示例</a> ·
|
|
20
|
+
<a href="#快速开始">快速开始</a> ·
|
|
21
|
+
<a href="#工作原理">工作原理</a> ·
|
|
22
|
+
<a href="#隐私与安全">隐私与安全</a> ·
|
|
23
|
+
<a href="#兼容性">兼容性</a> ·
|
|
24
|
+
<a href="#卸载">卸载</a> ·
|
|
25
|
+
<a href="#文档导航">文档</a> ·
|
|
26
|
+
<a href="#开发与验证">开发</a> ·
|
|
27
|
+
<a href="README.en.md">English</a>
|
|
28
|
+
</p>
|
|
29
|
+
|
|
30
|
+
> `dsh-verbatim` 是面向 AI 陪伴场景的 DeepSeek Harness 社区插件(同时提供 CLI 与 MCP Server),不修改 DeepSeek Harness 源码。
|
|
31
|
+
>
|
|
32
|
+
> **当前版本:0.1.0**。基于 Node.js `>=24` 内置 `node:sqlite` 与 FTS5,所有对话原文、索引与设置均保存在本机 `$DSH_HOME/verbatim/`,无外部记忆托管服务。
|
|
33
|
+
|
|
34
|
+
`dsh-verbatim` 把每一次对话的原话一字不改地留存在本地 SQLite 中,按问答与微话题自动组织结构;当上下文被压缩或时间跨度拉长后,模型仍可通过关键词、向量语义与可选精排找回完整原话与当时语境。
|
|
35
|
+
|
|
36
|
+
## 能做什么
|
|
37
|
+
|
|
38
|
+
- **原文一字不改,派生层随时可重建**:`msg` 表作为单一事实来源只增不改(撤回消息会物理删除原文与对应向量);即使经历多次上下文压缩,过往对话依然完整留存。
|
|
39
|
+
- **陪伴优先的双粒度组织(`exchange` → `thread`)**:面向日常闲聊自动切分单轮问答与微话题,配合 30 分钟静默成场、场景合并/拆分锁定与时间线聚簇折叠,召回连贯而不碎片。
|
|
40
|
+
- **始终混合检索 + 可选精排**:并行执行 FTS5 trigram / 2 字中文 `LIKE` 与多粒度向量检索(`vec_msg` / `vec_chunk` / `vec_scene` / `vec_note`),经 RRF 融合排序,并支持 `/rerank` 二次精排(异常自动回退)。
|
|
41
|
+
- **图片附件与备注回想**:入库记录对话中的图片附件与本地解析路径,支持在侧栏内联预览与编辑图片备注(`caption`),检索结果会一并把图片路径与备注交还给模型。
|
|
42
|
+
- **严格会话隔离与隐私边界**:开关与数据按 `session_id` 独立隔离;用户设置的「私密排除时段」与单句「暂不回想」对 Agent 工具完全不可见,杜绝任何参数绕过。
|
|
43
|
+
- **Material 3 陪伴向前端**:提供 **6 个侧栏视图**(概览、搜索、时间轴、笔记、核对、库)与 **5 个全局设置页**(含 3 步快速上手引导、本地模型服务探测、会话数据管理与只读 SQL 诊断)。
|
|
44
|
+
|
|
45
|
+
## 检索返回示例
|
|
46
|
+
|
|
47
|
+
模型调用 `memory_search` 时,会收到带精确时间区间、紧凑对话行与命中标记的纯文本结果(以下为虚构示例):
|
|
48
|
+
|
|
49
|
+
```text
|
|
50
|
+
「周末去公园」— 3 处
|
|
51
|
+
|
|
52
|
+
11-16 14:10–14:25 · 6轮 · 92字 · 命中 2 处
|
|
53
|
+
我:周六天气不错,去公园散步吗?
|
|
54
|
+
他:好呀,顺便去湖边坐坐 kw+vec ←
|
|
55
|
+
我:记得带上相机和防晒。 kw+vec ←
|
|
56
|
+
他:"/path/to/dsh_home/attachments/v1/objects/00/0000...png" [图片]
|
|
57
|
+
[图片备注:公园湖边的长椅]
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## 快速开始
|
|
61
|
+
|
|
62
|
+
先确认本机已安装 **Node.js `>=24`**(使用内置 `node:sqlite`,无需额外原生编译工具),再将插件挂载到 DeepSeek Harness。
|
|
63
|
+
|
|
64
|
+
### 1. 安装与挂载
|
|
65
|
+
|
|
66
|
+
```powershell
|
|
67
|
+
git clone https://github.com/saya-ch/dsh-verbatim.git
|
|
68
|
+
cd dsh-verbatim
|
|
69
|
+
npm install --no-audit --no-fund
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
#### 官方 DSH Desktop
|
|
73
|
+
|
|
74
|
+
在应用的 **插件** 页面中指向并启用本地 `dsh-verbatim` 目录(仓库已包含 [cordis.patch.yml](cordis.patch.yml) 与 [package.json](package.json) 声明)。Desktop 的 profile 由应用管理,不适用下面的 `--profile web` 命令。
|
|
75
|
+
|
|
76
|
+
#### DSH Web
|
|
77
|
+
|
|
78
|
+
将本仓库挂载到 Web profile 的插件配置后启动:
|
|
79
|
+
|
|
80
|
+
```powershell
|
|
81
|
+
dsh --profile web
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
<details>
|
|
85
|
+
<summary>使用 DeepSeek Harness 源码模式或独立 CLI / MCP Server</summary>
|
|
86
|
+
|
|
87
|
+
在 DeepSeek Harness 源码目录中使用 `pnpm dsh --profile web` 启动并加载本插件目录。
|
|
88
|
+
|
|
89
|
+
如果你希望脱离插件界面单独导入、检索或作为标准 MCP Server(stdio)挂载到其他客户端:
|
|
90
|
+
|
|
91
|
+
```powershell
|
|
92
|
+
# CLI 工具(导入、检索、统计、校验)
|
|
93
|
+
node bin/cli.mjs --help
|
|
94
|
+
|
|
95
|
+
# 启动标准 MCP Server(stdio)
|
|
96
|
+
node bin/mcp-memory.mjs
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
</details>
|
|
100
|
+
|
|
101
|
+
记忆库、全局配置与按会话隔离的开关均保存在 `$DSH_HOME/verbatim/`(未设置 `DSH_HOME` 时默认为 `~/.dsh/verbatim/`):
|
|
102
|
+
|
|
103
|
+
- `memory.db`:SQLite 逐字记忆库与派生索引
|
|
104
|
+
- `config.json`:全局模型与服务配置
|
|
105
|
+
- `sessions/<session-id>.json`:每个会话独立的开关与私密排除规则
|
|
106
|
+
|
|
107
|
+
### 2. 三步启用陪伴记忆
|
|
108
|
+
|
|
109
|
+
1. 打开 **设置 → 逐字记忆 → 向量模型**,选择本地服务(支持 Ollama / LM Studio 自动扫描)或填写兼容 OpenAI `/v1/embeddings` 的远程接口并测试连通性。
|
|
110
|
+
2. (可选)在 **精排模型** 中开启 `/rerank` 精排,提升长记忆场景下的排序准确度。
|
|
111
|
+
3. 打开任意对话右侧栏的 **逐字记忆** 面板,开启 **记住新对话** 与 **让 TA 随时回想**(热更新立即生效,无需重启)。
|
|
112
|
+
|
|
113
|
+
## 工作原理
|
|
114
|
+
|
|
115
|
+
```mermaid
|
|
116
|
+
flowchart LR
|
|
117
|
+
Chat["DSH 对话与附件"] -->|"逐字留存"| Msg["msg 原文表"]
|
|
118
|
+
Msg -->|"陪伴切分"| Gran["exchange / thread"]
|
|
119
|
+
Gran -->|"混合索引"| Index["FTS5 + 多粒度向量"]
|
|
120
|
+
Index -->|"RRF + 可选 Rerank"| Tools["Agent 工具 (search / around / timeline)"]
|
|
121
|
+
Tools -->|"隐私过滤后回传"| Model["当前对话模型"]
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
插件通过 Host 服务挂载入库管线、检索服务与 3 个 Agent 只读工具(`memory_search`、`memory_around`、`memory_timeline`),并通过 Client 入口注入侧栏 6 视图与设置页 5 个标签页;不改写 DeepSeek Harness 安装目录中的源码。详细表结构与写入锁设计见 [系统架构说明](docs/ARCHITECTURE.md)。
|
|
125
|
+
|
|
126
|
+
## 隐私与安全
|
|
127
|
+
|
|
128
|
+
- **数据不出本机**:除你主动配置的向量 `/v1/embeddings` 与精排 `/rerank` 模型接口外,记忆库、附件备注与配置全部留在本地 `$DSH_HOME/verbatim/`。
|
|
129
|
+
- **硬隐私边界**:用户在面板中设置的「私密排除时段」与单句「暂不回想」在检索与工具查询层直接过滤,对 Agent 完全不可见,无法通过工具参数绕过。
|
|
130
|
+
- **物理撤回**:用户在 DSH 中撤回或删除消息时,对应原文与向量索引会从本地库中物理移除。
|
|
131
|
+
- **只读诊断**:设置页提供的 SQL 诊断入口仅允许执行只读查询,不会修改记忆原文。
|
|
132
|
+
|
|
133
|
+
## 兼容性
|
|
134
|
+
|
|
135
|
+
- **Node.js**:要求 `>=24`(依赖内置 `node:sqlite`)。
|
|
136
|
+
- **`sqlite-vec`**:作为 `optionalDependencies` 安装;若当前平台未加载成功,系统会自动降级为纯 SQLite 余弦检索,功能与召回结果等价,仅在大库全量扫描时略慢。
|
|
137
|
+
|
|
138
|
+
## 卸载
|
|
139
|
+
|
|
140
|
+
仅从 DeepSeek Harness 插件配置中移除 `dsh-verbatim` **不会删除** `$DSH_HOME/verbatim/` 中的记忆库与配置,重新挂载即可继续使用。
|
|
141
|
+
|
|
142
|
+
如需彻底清理本机数据,请先备份需要的 `memory.db` 或 `sessions/*.json`,移除插件后再手动删除 `$DSH_HOME/verbatim/` 目录。
|
|
143
|
+
|
|
144
|
+
## 文档导航
|
|
145
|
+
|
|
146
|
+
- [系统架构说明](docs/ARCHITECTURE.md):存储表结构、陪伴双粒度切分、混合检索与写入锁设计
|
|
147
|
+
- [Agent 工具与隐私边界](docs/TOOLS.md):3 个工具的完整 Schema、返回格式与隐私隔离机制
|
|
148
|
+
- [更新日志](CHANGELOG.md):版本变更记录
|
|
149
|
+
- [贡献指南](CONTRIBUTING.md):本地开发、校验流程与脱敏测试规范
|
|
150
|
+
|
|
151
|
+
## 开发与验证
|
|
152
|
+
|
|
153
|
+
```powershell
|
|
154
|
+
# 从 src/client/*.js 重新打包前端产物 client.js
|
|
155
|
+
npm run build:client
|
|
156
|
+
|
|
157
|
+
# 一致性检查、TypeScript 类型检查与语法校验
|
|
158
|
+
npm run check
|
|
159
|
+
|
|
160
|
+
# 运行完整单元测试与前端渲染测试
|
|
161
|
+
npm test
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## License
|
|
165
|
+
|
|
166
|
+
[MIT](LICENSE)
|
package/bin/cli.mjs
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 命令行入口。日常只做三件事:导入、重建、查库概况。
|
|
4
|
+
*
|
|
5
|
+
* dsh-verbatim import <session.v4.jsonl.zstd> 导入一个会话
|
|
6
|
+
* dsh-verbatim rebuild 从原文重建派生层
|
|
7
|
+
* dsh-verbatim stat 看一眼库里有什么
|
|
8
|
+
*/
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import { importSession, rebuildDerived, openPipelineDb } from '../src/pipeline.js';
|
|
12
|
+
import { createRepo, createExtras } from '../src/store/repo.js';
|
|
13
|
+
import { defaultDbPath } from '../src/store/db.js';
|
|
14
|
+
|
|
15
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
16
|
+
const dbPath = process.env.VERBATIM_DB || defaultDbPath();
|
|
17
|
+
|
|
18
|
+
function usage() {
|
|
19
|
+
console.log(`dsh-verbatim 0.1.0 —— 一字不改的长期记忆
|
|
20
|
+
|
|
21
|
+
用法:
|
|
22
|
+
dsh-verbatim import <会话日志> 导入一个会话(幂等,可重复跑)
|
|
23
|
+
dsh-verbatim rebuild 从原文重建场景/索引
|
|
24
|
+
dsh-verbatim stat 看一眼库里有什么
|
|
25
|
+
|
|
26
|
+
环境变量:
|
|
27
|
+
DSH_HOME 记忆库根目录(默认 ~/.dsh)
|
|
28
|
+
VERBATIM_DB 直接指定库文件路径
|
|
29
|
+
`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (!cmd || cmd === '-h' || cmd === '--help') {
|
|
33
|
+
usage();
|
|
34
|
+
process.exit(0);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (cmd === 'import') {
|
|
38
|
+
const file = rest[0];
|
|
39
|
+
if (!file || !fs.existsSync(file)) {
|
|
40
|
+
console.error(`找不到会话日志:${file ?? '(未提供)'}`);
|
|
41
|
+
process.exit(1);
|
|
42
|
+
}
|
|
43
|
+
await importSession(path.resolve(file), { dbPath });
|
|
44
|
+
} else if (cmd === 'rebuild') {
|
|
45
|
+
await rebuildDerived({ dbPath });
|
|
46
|
+
} else if (cmd === 'stat') {
|
|
47
|
+
const handle = openPipelineDb({ dbPath, logger: { warn() {} } });
|
|
48
|
+
const extras = createExtras(handle);
|
|
49
|
+
const s = extras.stats.get();
|
|
50
|
+
console.log(`库:${dbPath}`);
|
|
51
|
+
console.log(`消息 ${s.msgs} 条 / ${s.chars} 字 / 场景 ${s.scenes} 场`);
|
|
52
|
+
if (s.excludedMsgs) console.log(`按日期排除 ${s.excludedMsgs} 条 / ${s.excludedChars} 字(入库但检索不到)`);
|
|
53
|
+
handle.close();
|
|
54
|
+
} else {
|
|
55
|
+
console.error(`未知命令:${cmd}`);
|
|
56
|
+
usage();
|
|
57
|
+
process.exit(1);
|
|
58
|
+
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* MCP server —— 三个记忆工具的唯一对外出口。
|
|
4
|
+
*
|
|
5
|
+
* 为什么需要这个文件:工具实现得再好,没有 MCP 入口,宿主就调不到。
|
|
6
|
+
*
|
|
7
|
+
* 用法(stdio JSON-RPC,MCP 标准):
|
|
8
|
+
* node bin/mcp-memory.mjs
|
|
9
|
+
*
|
|
10
|
+
* 环境变量:
|
|
11
|
+
* DSH_HOME 会话日志与记忆库的根(默认 ~/.dsh)
|
|
12
|
+
* VERBATIM_DB 直接指定库文件(默认 $DSH_HOME/verbatim/memory.db)
|
|
13
|
+
* VERBATIM_SESSION 指定要同步哪个会话的日志文件
|
|
14
|
+
* (不指定则自动找最近修改的那个 —— 通常就是"当前会话")
|
|
15
|
+
* VERBATIM_AUTOSYNC 设为 0 关掉"调用前自动增量同步"
|
|
16
|
+
*
|
|
17
|
+
* 设计要点:MCP server 是被动进程,不知道 DSH 当前在哪个会话。
|
|
18
|
+
* 所以每次工具调用前,检查会话日志的 mtime,变了就增量同步一次
|
|
19
|
+
* (`importSession` 是幂等 upsert,重复跑不会出问题)。
|
|
20
|
+
* 这样才能"边聊边查得到"。
|
|
21
|
+
*
|
|
22
|
+
* 注意:stdout 是 JSON-RPC 流,**任何调试输出都必须走 stderr**。
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { createInterface } from 'node:readline';
|
|
26
|
+
import fs from 'node:fs';
|
|
27
|
+
import path from 'node:path';
|
|
28
|
+
import os from 'node:os';
|
|
29
|
+
|
|
30
|
+
import { openDb, defaultDbPath } from '../src/store/db.js';
|
|
31
|
+
import { createRepo, createExtras } from '../src/store/repo.js';
|
|
32
|
+
import { createToolSet } from '../src/tools/index.js';
|
|
33
|
+
import { loadSessionConfig } from '../src/config/session-config.js';
|
|
34
|
+
import { importSession } from '../src/pipeline.js';
|
|
35
|
+
|
|
36
|
+
const VERSION = '0.1.0';
|
|
37
|
+
const log = (...args) => console.error('[verbatim-mcp]', ...args);
|
|
38
|
+
|
|
39
|
+
/* ───────────────────────── 找会话日志 ───────────────────────── */
|
|
40
|
+
|
|
41
|
+
/** 在 $DSH_HOME/sessions 下找最近修改的 session.v4.jsonl.zstd */
|
|
42
|
+
function findLatestSession() {
|
|
43
|
+
const root = path.join(process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh'), 'sessions');
|
|
44
|
+
if (!fs.existsSync(root)) return null;
|
|
45
|
+
|
|
46
|
+
let best = null;
|
|
47
|
+
let bestAt = 0;
|
|
48
|
+
const walk = (dir, depth) => {
|
|
49
|
+
if (depth > 3) return;
|
|
50
|
+
let entries;
|
|
51
|
+
try {
|
|
52
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
53
|
+
} catch {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
for (const e of entries) {
|
|
57
|
+
const p = path.join(dir, e.name);
|
|
58
|
+
if (e.isDirectory()) walk(p, depth + 1);
|
|
59
|
+
else if (e.name === 'session.v4.jsonl.zstd') {
|
|
60
|
+
try {
|
|
61
|
+
const at = fs.statSync(p).mtimeMs;
|
|
62
|
+
if (at > bestAt) { bestAt = at; best = p; }
|
|
63
|
+
} catch { /* 读不到就跳过 */ }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
try { walk(root, 0); } catch { /* 权限问题当没找到 */ }
|
|
68
|
+
return best;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const sessionFile = process.env.VERBATIM_SESSION || findLatestSession();
|
|
72
|
+
const autoSync = process.env.VERBATIM_AUTOSYNC !== '0';
|
|
73
|
+
const dbPath = process.env.VERBATIM_DB || defaultDbPath();
|
|
74
|
+
|
|
75
|
+
/* ───────────────────────── 启动 ───────────────────────── */
|
|
76
|
+
|
|
77
|
+
let ctx = null;
|
|
78
|
+
try {
|
|
79
|
+
const handle = openDb({ dbPath, logger: { warn: (m) => log(m) } });
|
|
80
|
+
ctx = {
|
|
81
|
+
handle,
|
|
82
|
+
repo: createRepo(handle),
|
|
83
|
+
extras: createExtras(handle),
|
|
84
|
+
dbPath,
|
|
85
|
+
sessionFile,
|
|
86
|
+
};
|
|
87
|
+
log(`库已打开:${dbPath}${handle.hasVec ? '(向量索引可用)' : '(降级为暴力余弦,功能等价)'}`);
|
|
88
|
+
if (sessionFile) log(`同步会话:${sessionFile}`);
|
|
89
|
+
else log('没找到任何会话日志。设置 VERBATIM_SESSION 指向一个 session.v4.jsonl.zstd。');
|
|
90
|
+
} catch (e) {
|
|
91
|
+
log(`打开记忆库失败:${e.message}`);
|
|
92
|
+
ctx = null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/* ───────────────────────── 增量同步 ───────────────────────── */
|
|
96
|
+
|
|
97
|
+
let lastMtime = 0;
|
|
98
|
+
let syncing = null;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 保证库和会话日志一致。
|
|
102
|
+
* 按 mtime 判断,避免每次调用都重读整个日志(大文件要一两秒)。
|
|
103
|
+
* 并发调用共用同一个 promise,不会重复导入。
|
|
104
|
+
*/
|
|
105
|
+
async function ensureFresh() {
|
|
106
|
+
if (!autoSync || !ctx?.sessionFile) return;
|
|
107
|
+
let stat;
|
|
108
|
+
try {
|
|
109
|
+
stat = fs.statSync(ctx.sessionFile);
|
|
110
|
+
} catch {
|
|
111
|
+
return; // 日志没了就跑现状,不要因为同步失败让工具挂掉
|
|
112
|
+
}
|
|
113
|
+
if (stat.mtimeMs === lastMtime) return;
|
|
114
|
+
if (syncing) return syncing;
|
|
115
|
+
|
|
116
|
+
syncing = (async () => {
|
|
117
|
+
const t0 = Date.now();
|
|
118
|
+
try {
|
|
119
|
+
const r = await importSession(ctx.sessionFile, {
|
|
120
|
+
handle: ctx.handle,
|
|
121
|
+
dshHome: process.env.DSH_HOME ?? undefined,
|
|
122
|
+
quiet: true,
|
|
123
|
+
});
|
|
124
|
+
lastMtime = stat.mtimeMs;
|
|
125
|
+
log(`同步完成 ${Date.now() - t0}ms:入库 ${r?.ingest?.inserted ?? '?'} 条`);
|
|
126
|
+
} catch (e) {
|
|
127
|
+
// 同步失败不阻塞查询:查到的可能是稍旧的数据,但比报错好
|
|
128
|
+
log(`同步失败(继续用现有数据):${e.message}`);
|
|
129
|
+
lastMtime = stat.mtimeMs; // 别在同一个坏状态上反复重试
|
|
130
|
+
} finally {
|
|
131
|
+
syncing = null;
|
|
132
|
+
}
|
|
133
|
+
})();
|
|
134
|
+
return syncing;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/* ───────────────────────── 工具集 ───────────────────────── */
|
|
138
|
+
|
|
139
|
+
function buildTools() {
|
|
140
|
+
if (!ctx) return { tools: [], close: () => {} };
|
|
141
|
+
try {
|
|
142
|
+
const sid = ctx.sessionFile ? path.basename(path.dirname(ctx.sessionFile)) : '';
|
|
143
|
+
const cfg = loadSessionConfig(sid, { dshHome: process.env.DSH_HOME ?? undefined });
|
|
144
|
+
return createToolSet({ ...ctx, config: cfg, sessionId: sid });
|
|
145
|
+
} catch (e) {
|
|
146
|
+
log(`读取会话配置失败,按默认开关注册工具:${e.message}`);
|
|
147
|
+
const sid = ctx.sessionFile ? path.basename(path.dirname(ctx.sessionFile)) : '';
|
|
148
|
+
return createToolSet({ ...ctx, sessionId: sid });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const TOOL_SET = buildTools();
|
|
153
|
+
const TOOLS = TOOL_SET.tools ?? [];
|
|
154
|
+
|
|
155
|
+
/* ───────────────────────── JSON-RPC ───────────────────────── */
|
|
156
|
+
|
|
157
|
+
function send(payload) {
|
|
158
|
+
process.stdout.write(`${JSON.stringify(payload)}\n`);
|
|
159
|
+
}
|
|
160
|
+
const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
|
|
161
|
+
const replyError = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
|
|
162
|
+
|
|
163
|
+
async function handleRequest(msg) {
|
|
164
|
+
const { id, method, params } = msg;
|
|
165
|
+
|
|
166
|
+
switch (method) {
|
|
167
|
+
case 'initialize':
|
|
168
|
+
return reply(id, {
|
|
169
|
+
protocolVersion: '2024-11-05',
|
|
170
|
+
capabilities: { tools: {} },
|
|
171
|
+
serverInfo: { name: 'dsh-verbatim', version: VERSION },
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
case 'notifications/initialized':
|
|
175
|
+
return undefined;
|
|
176
|
+
|
|
177
|
+
case 'tools/list':
|
|
178
|
+
return reply(id, {
|
|
179
|
+
tools: TOOLS.map((t) => ({
|
|
180
|
+
name: t.name,
|
|
181
|
+
description: t.description,
|
|
182
|
+
inputSchema: t.parameters,
|
|
183
|
+
})),
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
case 'tools/call': {
|
|
187
|
+
const name = params?.name;
|
|
188
|
+
const tool = TOOLS.find((t) => t.name === name);
|
|
189
|
+
if (!tool) return replyError(id, -32602, `未知工具:${name}`);
|
|
190
|
+
|
|
191
|
+
// 每次调用前同步,保证"边聊边查得到"
|
|
192
|
+
await ensureFresh();
|
|
193
|
+
|
|
194
|
+
try {
|
|
195
|
+
const text = await tool.handler(params?.arguments ?? {}, ctx ?? {});
|
|
196
|
+
return reply(id, { content: [{ type: 'text', text: String(text) }] });
|
|
197
|
+
} catch (e) {
|
|
198
|
+
// 工具内部错误当"内容"返回:让TA知道发生了什么,
|
|
199
|
+
// 而不是让整个 JSON-RPC 调用失败(那会中断宿主的会话)。
|
|
200
|
+
return reply(id, {
|
|
201
|
+
content: [{ type: 'text', text: `工具执行出错:${e.message}` }],
|
|
202
|
+
isError: true,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
default:
|
|
208
|
+
return replyError(id, -32601, `不支持的方法:${method}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/* ───────────────────────── 主循环 ───────────────────────── */
|
|
213
|
+
|
|
214
|
+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
215
|
+
|
|
216
|
+
rl.on('line', (line) => {
|
|
217
|
+
const trimmed = line.trim();
|
|
218
|
+
if (!trimmed) return;
|
|
219
|
+
let msg;
|
|
220
|
+
try {
|
|
221
|
+
msg = JSON.parse(trimmed);
|
|
222
|
+
} catch {
|
|
223
|
+
log(`收到无法解析的行(已忽略,前 80 字符):${trimmed.slice(0, 80)}`);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
handleRequest(msg).catch((e) => {
|
|
227
|
+
log(`处理请求异常:${e.message}`);
|
|
228
|
+
if (msg?.id !== undefined) replyError(msg.id, -32603, e.message);
|
|
229
|
+
});
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
rl.on('close', () => {
|
|
233
|
+
try { ctx?.handle?.close?.(); } catch { /* 关不上也没关系,进程要退了 */ }
|
|
234
|
+
process.exit(0);
|
|
235
|
+
});
|