@nelsonlongxiang/dsh-prompt-templates 0.4.4 → 0.13.2

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 (50) hide show
  1. package/README.md +113 -62
  2. package/README_zh.md +112 -62
  3. package/cordis.patch.yml +4 -0
  4. package/lib/cli/app.js +169 -0
  5. package/lib/cli/database.js +162 -0
  6. package/lib/cli/main.js +6 -0
  7. package/lib/cli/model.js +247 -0
  8. package/lib/client/Library.js +290 -0
  9. package/lib/client/Panel.js +37 -201
  10. package/lib/client/PanelButton.js +27 -3
  11. package/lib/client/PromptTab.js +11 -0
  12. package/lib/client/api.js +16 -0
  13. package/lib/client/filter.js +27 -0
  14. package/lib/client/index.js +53 -36
  15. package/lib/client/locales.js +34 -2
  16. package/lib/client/meta.js +10 -0
  17. package/lib/client/service.js +57 -37
  18. package/lib/client/slots.js +5 -3
  19. package/lib/client/store.js +12 -1
  20. package/lib/client/tab.js +32 -0
  21. package/lib/client.js +798 -286
  22. package/lib/client.js.map +1 -1
  23. package/lib/index.js +35 -16
  24. package/lib/inject.js +236 -0
  25. package/lib/invariant.js +1 -1
  26. package/lib/store.js +108 -32
  27. package/lib/types/cli/app.d.ts +1 -0
  28. package/lib/types/cli/database.d.ts +69 -0
  29. package/lib/types/cli/main.d.ts +2 -0
  30. package/lib/types/cli/model.d.ts +62 -0
  31. package/lib/types/client/Library.d.ts +34 -0
  32. package/lib/types/client/Panel.d.ts +1 -1
  33. package/lib/types/client/PanelButton.d.ts +10 -9
  34. package/lib/types/client/PromptTab.d.ts +17 -0
  35. package/lib/types/client/api.d.ts +11 -1
  36. package/lib/types/client/filter.d.ts +10 -0
  37. package/lib/types/client/index.d.ts +6 -2
  38. package/lib/types/client/locales.d.ts +34 -2
  39. package/lib/types/client/meta.d.ts +6 -0
  40. package/lib/types/client/service.d.ts +50 -6
  41. package/lib/types/client/slots.d.ts +57 -5
  42. package/lib/types/client/store.d.ts +14 -1
  43. package/lib/types/client/tab.d.ts +31 -0
  44. package/lib/types/index.d.ts +8 -1
  45. package/lib/types/inject.d.ts +150 -0
  46. package/lib/types/store.d.ts +27 -4
  47. package/lib/types/types.d.ts +49 -0
  48. package/lib/types/variables.d.ts +24 -0
  49. package/lib/variables.js +36 -0
  50. package/package.json +98 -105
package/README.md CHANGED
@@ -1,62 +1,113 @@
1
- # @nelsonlongxiang/dsh-prompt-templates
2
-
3
- English | [中文](README_zh.md)
4
-
5
- [![npm](https://img.shields.io/npm/v/@nelsonlongxiang/dsh-prompt-templates?label=npm)](https://www.npmjs.com/package/@nelsonlongxiang/dsh-prompt-templates)
6
-
7
- Quick prompt templates for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness): global and per-session templates, a right-side browser panel, and pure-TS SQLite persistence via `node:sqlite` — one self-contained plugin, installable with `dsh plugin`.
8
-
9
- ![The templates panel](images/image-01.png)
10
-
11
- ## Install
12
-
13
- ```sh
14
- dsh plugin --profile web add @nelsonlongxiang/dsh-prompt-templates
15
- ```
16
-
17
- Restart `dsh web`, then look for the templates button in the composer tool row.
18
-
19
- No Python toolchain required — since 0.3.0 the host half persists templates through `node:sqlite` (Node ≥ 24) directly inside the host process, reading and writing the same `$DSH_HOME/ext/prompt-templates/db.sqlite3` the former Python child owned (zero data migration).
20
-
21
- ## What you get
22
-
23
- - **Global + per-session templates** — globals apply everywhere; session templates stay private to one conversation and can be promoted to global in one click
24
- - **Insert or send** — one click appends the template into the draft; send-now dispatches immediately; edit, delete, and make-global all live in the row
25
- - **Search & scroll** — filter the list as you type, reliable scrolling for long collections
26
- - **Drag to reposition, double-click to reset** — the panel remembers where you put it
27
- - **Durable by design** — templates persist in SQLite through a pure-TS store (`node:sqlite`) owned by the host plugin and closed with its lifecycle
28
-
29
- ## How it works
30
-
31
- ```text
32
- src/ TypeScript plugin (host half + browser half)
33
- index.ts Host: owns the TS store, exposes the HTTP routes
34
- store.ts Pure-TS template store over node:sqlite
35
- client/ Browser: panel UI registered into shell.overlay and
36
- conversation.input.right
37
- cordis.patch.yml Bundle patch: mounts the plugin row
38
- ```
39
-
40
- The store is pure TS inside the host half; no child process is spawned.
41
-
42
- ## Security
43
-
44
- - Template content reaches a model request only as ordinary user text the user chose to insert — no automatic injection into any prompt
45
- - The panel talks to the host store over the Host's plugin routes only; no extra listener, no outbound network
46
-
47
- ## Development
48
-
49
- ```sh
50
- pnpm install
51
- pnpm verify # typecheck
52
- pnpm build # tsc host + tsc client + tsdown browser bundle
53
- ```
54
-
55
- ## Known limitations
56
-
57
- - **Insert appends to the draft** — caret-position insert is deferred
58
- - **Session templates need a current session** — with no session open, only global templates are reachable
59
-
60
- ## License
61
-
62
- MIT
1
+ # @nelsonlongxiang/dsh-prompt-templates
2
+
3
+ English | [中文](README_zh.md)
4
+
5
+ [![npm](https://img.shields.io/npm/v/@nelsonlongxiang/dsh-prompt-templates?label=npm)](https://www.npmjs.com/package/@nelsonlongxiang/dsh-prompt-templates)
6
+
7
+ Quick prompt templates for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness): global and per-session templates, a right-side browser panel, and pure-TS SQLite persistence via `node:sqlite` — one self-contained plugin, installable with `dsh plugin`.
8
+
9
+ ![The templates panel](images/image-01.png)
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ dsh plugin --profile web add @nelsonlongxiang/dsh-prompt-templates
15
+ ```
16
+
17
+ Restart `dsh web`, then look for the templates button in the composer tool row. Since 0.12.0 the same library is also a **right-sidebar tab**: open it from the sidebar's `+` guide page (entry “Prompt templates”) — it lives beside the conversation, keeps the composer visible, and always targets the session the sidebar is viewing. On hosts without the sidebar services the tab stays dormant and the floating panel keeps working.
18
+
19
+ No Python toolchain required — since 0.3.0 the host half persists templates through `node:sqlite` (Node ≥ 24) directly inside the host process, reading and writing the same `$DSH_HOME/ext/prompt-templates/db.sqlite3` the former Python child owned (zero data migration).
20
+
21
+ ## What you get
22
+
23
+ - **Global + per-session templates** — globals apply everywhere; session templates stay private to one conversation and can be promoted to global in one click
24
+ - **Scheduled auto-injection** — per-template switch and interval: the host re-surfaces an enabled template into the model context at the first request of every Nth round, persisted in SQLite and logged as a durable session event; the library toolbar shows a `⟳N` badge with the session's latest injection (turn, time, template names)
25
+ - **Insert or send** — one click inserts the template at the composer caret (or replaces the current selection); send-now dispatches immediately; edit, delete, and make-global all live in the row
26
+ - **Right-sidebar tab** — the full library also docks as a sidebar tab (DSH ≥ 0.2.x): open it from the `+` guide and it follows the session you are viewing; the floating panel remains for quick one-shot use
27
+ - **Search & scroll** — filter the list as you type, reliable scrolling for long collections
28
+ - **Drag to reposition, double-click to reset** — the panel remembers where you put it
29
+ - **Durable by design** — templates persist in SQLite through a pure-TS store (`node:sqlite`) owned by the host plugin and closed with its lifecycle
30
+
31
+ ## Auto-inject
32
+
33
+ Each template (global or session-scoped) carries its own **switch + interval N**. When on, the host injects the template at the first request of every Nth round of the conversation — N=5 means rounds 5, 10, 15, …; rounds count user→assistant exchanges and keep their numbering across restarts.
34
+
35
+ - The injected content arrives as one durable `<system-reminder>` user message recorded in the session log (source kind `prompt-template-schedule`), so replays and audits reconstruct exactly what the model saw
36
+ - A boundary round is never injected twice, even across restarts or step retries
37
+ - Config persists in the plugin's SQLite database (schema v3); the deployment can silence everything with `injectEnabled: false` in the patch config
38
+
39
+ ## How it works
40
+
41
+ ```text
42
+ src/ TypeScript plugin (host half + browser half)
43
+ index.ts Host: owns the TS store, exposes the HTTP routes
44
+ store.ts Pure-TS template store over node:sqlite (schema v3)
45
+ inject.ts Host: scheduled auto-injection on the pre-step waterfall
46
+ invariant.ts Host: registers the package's invariant companion
47
+ cli/ The sync CLI (export/diff/merge/import) shipped as bin
48
+ client/ Browser: shared template library mounted as both the
49
+ shell.overlay floating panel and the right-sidebar
50
+ tab body (sidebar.right.pane.tab), plus the
51
+ conversation.input.right toggle button
52
+ cordis.patch.yml Bundle patch: mounts the plugin row
53
+ ```
54
+
55
+ The store is pure TS inside the host half; no child process is spawned.
56
+
57
+ ## Security
58
+
59
+ - Template content reaches a model request in exactly two ways: as ordinary user text the user chose to insert, or as scheduled auto-injection of templates where the switch was explicitly enabled — every injection is a durable session event
60
+ - The panel talks to the host store over the Host's plugin routes only; no extra listener, no outbound network
61
+
62
+ ## Database sync CLI
63
+
64
+ The package ships a deterministic, local-only CLI for comparing and merging prompt-template databases across DSH homes. It never writes a remote database directly.
65
+
66
+ ```sh
67
+ # Export a schema-v3 snapshot (canonical order + data_sha256)
68
+ dsh-prompt-templates export --db /path/to/db.sqlite3 --out snapshot.json --output=json
69
+
70
+ # Compare two snapshots (exit 1 with --fail-on-diff)
71
+ dsh-prompt-templates diff left.json right.json --output=json --fail-on-diff
72
+
73
+ # Merge into a JSON artifact only; equal-time or name conflicts block by default
74
+ dsh-prompt-templates merge base.json incoming.json --strategy newer --out merged.json --output=json
75
+
76
+ # Dry-run import (the default): review summary_sha256 and database hash
77
+ dsh-prompt-templates import --db /path/to/db.sqlite3 --in merged.json --output=json
78
+
79
+ # Apply only after binding both reviewed values; creates a backup, then one transaction
80
+ dsh-prompt-templates import --db /path/to/db.sqlite3 --in merged.json --apply \
81
+ --expect-db-sha256 <db-sha256> --confirm-summary-hash <dry-run-summary-sha256> --output=json
82
+ ```
83
+
84
+ `import` inserts/updates by template id and never prunes rows. It rejects unknown snapshot fields, unsupported schemas, mismatched hashes, same-name/different-id conflicts, and changes above `--max-changes` (default 100). Schema-v2 snapshots (pre-auto-inject) still import — the inject facts default to off; exports are always v3.
85
+
86
+ ## Development
87
+
88
+ ```sh
89
+ pnpm install
90
+ pnpm verify # everyday gate (local and CI)
91
+ pnpm verify:release # alias of pnpm verify
92
+ ```
93
+
94
+ `pnpm verify` is the gate to run before pushing. It does not boot a DeepSeek Harness process. In order:
95
+
96
+ 1. **typecheck** — `tsc --noEmit` for the host project and the client project
97
+ 2. **test:cli** — `node:test` over `tests/*.test.ts`: CLI sync, store rules, schema migration, inject helpers, client filters, and an in-process host check. That check mounts `apply()` on Cordis with a stand-in web server, drives the `/plugins/dsh-prompt-templates` routes (including inject-status), and runs the `agent/pre-step` listener against a fake session log
98
+ 3. **build** — host `tsc`, client `tsc`, and the tsdown browser bundle
99
+ 4. **test:package** — every CSS module class is present in `lib/client.js`, then `npm pack` and the packed `dsh-prompt-templates --help` shim
100
+
101
+ GitHub Actions (`.github/workflows/verify.yml`) runs the same command on pushes and pull requests to `master`, and on `v*` tags, with Node 24. The `@deepseek-ai/*` devDependencies are public npm packages, so CI needs no registry token and no harness checkout.
102
+
103
+ Still manual, because they need a live harness profile: booting `dsh web`, the browser panel against the real web server, and resume or compaction against a real session log.
104
+
105
+ ## Known limitations
106
+
107
+ - **Session templates need a current session** — with no session open, only global templates are reachable
108
+ - **Injections don't render in the chat transcript** — the DSH chat view omits injected context rows by design (they carry a non-`user` message source); see them in the trajectory tab. Templates with delivery mode **visible** are the exception: they render as ordinary user messages
109
+ - **Install from the npm registry, not from a Git URL** — the plugin compiles against the DSH harness checkout; `pnpm add github:<user>/<repo>` fails at the prepare build step because the published `@deepseek-ai/*` npm snapshots lag the harness source. Use `dsh plugin --profile <name> add @nelsonlongxiang/dsh-prompt-templates` instead
110
+
111
+ ## License
112
+
113
+ MIT
package/README_zh.md CHANGED
@@ -1,62 +1,112 @@
1
- # @nelsonlongxiang/dsh-prompt-templates
2
-
3
- [English](README.md) | 中文
4
-
5
- [![npm](https://img.shields.io/npm/v/@nelsonlongxiang/dsh-prompt-templates?label=npm)](https://www.npmjs.com/package/@nelsonlongxiang/dsh-prompt-templates)
6
-
7
- [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 快捷提示词模板:全局与会话级模板、右侧浏览器面板、纯 TS 的 `node:sqlite` 持久化——一个自包含插件,`dsh plugin` 即装。
8
-
9
- ![模板面板](images/image-01.png)
10
-
11
- ## 安装
12
-
13
- ```sh
14
- dsh plugin --profile web add @nelsonlongxiang/dsh-prompt-templates
15
- ```
16
-
17
- 重启 `dsh web`,在输入框工具行找到模板按钮。
18
-
19
- 无需 Python 工具链——0.3.0 起 host 面直接通过 `node:sqlite`(Node ≥ 24)在宿主进程内持久化,读写原来 Python 子进程持有的同一个 `$DSH_HOME/ext/prompt-templates/db.sqlite3`(数据零迁移)。
20
-
21
- ## 你能得到什么
22
-
23
- - **全局 + 会话模板**——全局处处生效;会话模板只属于当前对话,一键提升为全局
24
- - **插入或直发**——一键追加进草稿;send-now 立即发送;编辑、删除、转全局都在行内
25
- - **搜索与滚动**——边输入边过滤,长列表滚动可靠
26
- - **拖拽定位、双击复位**——面板记住你放的位置
27
- - **设计即持久**——模板经纯 TS 存储(`node:sqlite`)落 SQLite,由 host 插件持有并随其生命周期关闭
28
-
29
- ## 工作原理
30
-
31
- ```text
32
- src/ TypeScript 插件(host 面 + 浏览器面)
33
- index.ts Host:持有 TS 存储,暴露 HTTP 路由
34
- store.ts 纯 TS 模板存储(node:sqlite)
35
- client/ 浏览器:面板 UI 注册进 shell.overlay 与
36
- conversation.input.right
37
- cordis.patch.yml Bundle patch:挂插件行
38
- ```
39
-
40
- 存储是 host 面内的纯 TS 实现;不拉起任何子进程。
41
-
42
- ## 安全
43
-
44
- - 模板内容只有经用户主动插入才作为普通用户文本进入模型请求——绝不自动注入任何提示词
45
- - 面板仅经 Host 的插件路由访问 host 存储;无额外监听、无外联网络
46
-
47
- ## 开发
48
-
49
- ```sh
50
- pnpm install
51
- pnpm verify # typecheck
52
- pnpm build # tsc host + tsc client + tsdown 浏览器 bundle
53
- ```
54
-
55
- ## 已知限制
56
-
57
- - **插入是追加到草稿**——光标位置插入暂缓
58
- - **会话模板需要当前会话**——无会话打开时只能用全局模板
59
-
60
- ## 许可证
61
-
62
- MIT
1
+ # @nelsonlongxiang/dsh-prompt-templates
2
+
3
+ [English](README.md) | 中文
4
+
5
+ [![npm](https://img.shields.io/npm/v/@nelsonlongxiang/dsh-prompt-templates?label=npm)](https://www.npmjs.com/package/@nelsonlongxiang/dsh-prompt-templates)
6
+
7
+ [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 快捷提示词模板:全局与会话级模板、右侧浏览器面板、纯 TS 的 `node:sqlite` 持久化——一个自包含插件,`dsh plugin` 即装。
8
+
9
+ ![模板面板](images/image-01.png)
10
+
11
+ ## 安装
12
+
13
+ ```sh
14
+ dsh plugin --profile web add @nelsonlongxiang/dsh-prompt-templates
15
+ ```
16
+
17
+ 重启 `dsh web`,在输入框工具行找到模板按钮。0.12.0 起同一模板库还入驻**右侧栏 tab**:从侧栏 `+` 引导页(“提示词模板”入口)打开——它与对话同屏共存、不遮 composer,且始终作用于侧栏正在查看的会话。宿主没有侧栏服务时 tab 静默不激活,悬浮面板照常可用。
18
+
19
+ 无需 Python 工具链——0.3.0 起 host 面直接通过 `node:sqlite`(Node ≥ 24)在宿主进程内持久化,读写原来 Python 子进程持有的同一个 `$DSH_HOME/ext/prompt-templates/db.sqlite3`(数据零迁移)。
20
+
21
+ ## 你能得到什么
22
+
23
+ - **全局 + 会话模板**——全局处处生效;会话模板只属于当前对话,一键提升为全局
24
+ - **定时自动注入**——每条模板独立开关 + 间隔 N:开启后 host 在对话每第 N 轮的首个请求自动注入该模板,配置持久化于 SQLite,注入本身落为持久会话事件;模板库工具栏以 `⟳N` 徽标显示该会话最近一次注入(轮次、时间、模板名)
25
+ - **插入或直发**——一键插入到 composer 光标处(或替换当前选区);send-now 立即发送;编辑、删除、转全局都在行内
26
+ - **右侧栏 tab**——完整模板库可停靠为侧栏 tab(DSH ≥ 0.2.x):从 `+` 引导页打开,跟随当前查看的会话;悬浮面板保留作快捷一次性使用
27
+ - **搜索与滚动**——边输入边过滤,长列表滚动可靠
28
+ - **拖拽定位、双击复位**——面板记住你放的位置
29
+ - **设计即持久**——模板经纯 TS 存储(`node:sqlite`)落 SQLite,由 host 插件持有并随其生命周期关闭
30
+
31
+ ## 定时自动注入
32
+
33
+ 每条模板(全局或会话级)都带独立的**开关 + 间隔 N**。开启后,host 在对话每第 N 轮的第一个请求注入该模板——N=5 即第 5、10、15…轮;轮次按"用户输入→助手回复"计数,重启后序号延续。
34
+
35
+ - 注入内容是一条持久的 `<system-reminder>` 用户消息,记入会话日志(source kind `prompt-template-schedule`),重放与审计可精确还原模型所见
36
+ - 同一边界轮绝不重复注入——跨重启、跨步骤重试都不例外
37
+ - 配置持久化在插件 SQLite 库(schema v3);部署侧可在 patch 配置里 `injectEnabled: false` 一键全关
38
+
39
+ ## 工作原理
40
+
41
+ ```text
42
+ src/ TypeScript 插件(host 面 + 浏览器面)
43
+ index.ts Host:持有 TS 存储,暴露 HTTP 路由
44
+ store.ts 纯 TS 模板存储(node:sqlite,schema v3)
45
+ inject.ts Host:挂在 pre-step waterfall 上的定时注入
46
+ invariant.ts Host:注册本包的 invariant 伴生插件
47
+ cli/ 随 bin 发布的同步 CLI(export/diff/merge/import)
48
+ client/ 浏览器:共享模板库,同时挂载为 shell.overlay
49
+ 悬浮面板与右侧栏 tab body(sidebar.right.pane.tab),
50
+ 外加 conversation.input.right 开关按钮
51
+ cordis.patch.yml Bundle patch:挂插件行
52
+ ```
53
+
54
+ 存储是 host 面内的纯 TS 实现;不拉起任何子进程。
55
+
56
+ ## 安全
57
+
58
+ - 模板内容进入模型请求只有两条路:用户主动插入的普通用户文本,或开关被显式打开的定时注入模板——每次注入都是一条持久会话事件
59
+ - 面板仅经 Host 的插件路由访问 host 存储;无额外监听、无外联网络
60
+
61
+ ## 数据同步 CLI
62
+
63
+ 包内提供确定性的本地 CLI,用于跨 DSH home 对比、合并提示词模板数据库;禁止直接远程写库。
64
+
65
+ ```sh
66
+ # 导出 schema-v3 快照(确定性排序 + data_sha256)
67
+ dsh-prompt-templates export --db /path/to/db.sqlite3 --out snapshot.json --output=json
68
+
69
+ # 对比快照(加 --fail-on-diff 时发现差异返回 exit 1)
70
+ dsh-prompt-templates diff left.json right.json --output=json --fail-on-diff
71
+
72
+ # 只生成合并 JSON;同时间异内容或同名异 ID 默认阻断
73
+ dsh-prompt-templates merge base.json incoming.json --strategy newer --out merged.json --output=json
74
+
75
+ # 导入默认只 dry-run:先审核 summary_sha256 与数据库 hash
76
+ dsh-prompt-templates import --db /path/to/db.sqlite3 --in merged.json --output=json
77
+
78
+ # 显式 apply 才写;绑定两个已审核值,先备份,再执行单事务
79
+ dsh-prompt-templates import --db /path/to/db.sqlite3 --in merged.json --apply \
80
+ --expect-db-sha256 <db-sha256> --confirm-summary-hash <dry-run-summary-sha256> --output=json
81
+ ```
82
+
83
+ `import` 仅按模板 ID 插入/更新,绝不自动删除;未知字段、错误 schema、hash 漂移、同名异 ID,以及超过 `--max-changes`(默认 100)的变更均阻断。schema-v2 快照(无注入字段)仍可导入——注入项默认关闭;导出恒为 v3。
84
+
85
+ ## 开发
86
+
87
+ ```sh
88
+ pnpm install
89
+ pnpm verify # 日常门禁(本地与 CI)
90
+ pnpm verify:release # pnpm verify 的别名
91
+ ```
92
+
93
+ 推送前跑 `pnpm verify`。它不启动 DeepSeek Harness 进程,顺序为:
94
+
95
+ 1. **typecheck** — host 与 client 两个工程的 `tsc --noEmit`
96
+ 2. **test:cli** — `node:test` 跑 `tests/*.test.ts`:CLI 同步、store 规则、schema 迁移、注入纯函数、client 过滤,以及进程内 host 检查。该检查把 `apply()` 挂到 Cordis 上,用替身 web server 驱动 `/plugins/dsh-prompt-templates` 路由(含 inject-status),并对一份假会话日志跑 `agent/pre-step` 监听器
97
+ 3. **build** — host `tsc`、client `tsc`、tsdown 浏览器 bundle
98
+ 4. **test:package** — `lib/client.js` 含全部 CSS module class,再 `npm pack` 并跑打包后的 `dsh-prompt-templates --help`
99
+
100
+ GitHub Actions(`.github/workflows/verify.yml`)在指向 `master` 的 push / pull request 以及 `v*` tag 上用 Node 24 跑同一命令。`@deepseek-ai/*` devDependencies 来自公网 npm,CI 不需要 registry token,也不需要 harness 检出。
101
+
102
+ 仍需人工、因为它们依赖真实 harness profile:启动 `dsh web`、浏览器面板对接真实 web server,以及用真实会话日志验证 resume / compaction。
103
+
104
+ ## 已知限制
105
+
106
+ - **会话模板需要当前会话**——无会话打开时只能用全局模板
107
+ - **注入不在对话流中渲染**——DSH 对话视图按设计省略注入的 context 行(消息 source 非 `user`);可在轨迹 tab 查看。交付模式为"对话流可见"的模板是例外:以普通用户消息渲染
108
+ - **请从 npm registry 安装,不要装 Git URL**——插件编译对照 DSH harness 源码,公网 `@deepseek-ai/*` npm 快照落后于 harness 本体,`pnpm add github:<user>/<repo>` 会在 prepare 构建步失败。请用 `dsh plugin --profile <name> add @nelsonlongxiang/dsh-prompt-templates`
109
+
110
+ ## 许可证
111
+
112
+ MIT
package/cordis.patch.yml CHANGED
@@ -22,3 +22,7 @@
22
22
  # $DSH_HOME/ext/prompt-templates/ regardless of cwd or environment drift.
23
23
  dbPath: !!js >
24
24
  `${(process.env.DSH_HOME ?? `${process.getBuiltinModule('node:os').homedir()}/.dsh`).replace(/\\/g, '/')}/ext/prompt-templates/db.sqlite3`
25
+ # Scheduled auto-injection (defaults shown; the schema fills them when
26
+ # omitted, so these lines are optional):
27
+ # injectEnabled: true — master switch; false keeps the listener pass-through
28
+ # injectMaxEvery: 1000 — upper bound accepted for a template's interval
package/lib/cli/app.js ADDED
@@ -0,0 +1,169 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { databaseSha256, exportDatabase, ImportBlockedError, importDatabase, searchTemplates } from "./database.js";
5
+ import { canonicalJson, diffSnapshots, mergeSnapshots, parseSnapshot } from "./model.js";
6
+ const HELP = `dsh-prompt-templates — deterministic prompt-template database sync
7
+
8
+ Usage:
9
+ dsh-prompt-templates export --db <path> --out <json> [--scope all|global|session] [--session-id <id>] [--output human|json]
10
+ dsh-prompt-templates diff <left.json> <right.json> [--output human|json] [--json] [--fail-on-diff]
11
+ dsh-prompt-templates merge <base.json> <incoming.json> --strategy newer|keep-base|keep-incoming --out <json> [--allow-name-conflicts] [--output human|json]
12
+ dsh-prompt-templates import --db <path> --in <json> [--apply --expect-db-sha256 <sha> --confirm-summary-hash <sha>] [--backup-out <path>] [--max-changes <n>] [--output human|json]
13
+ dsh-prompt-templates db-sha256 --db <path> [--output human|json]
14
+ dsh-prompt-templates search --db <path> [--query <text>] [--category <name>] [--session-id <id>] [--limit <n>] [--output human|json]
15
+
16
+ Import is dry-run by default. --apply requires --expect-db-sha256 and creates a SQLite backup before one atomic transaction.
17
+ Search is read-only: globals always searchable; session-private rows only with --session-id (never other sessions).
18
+ `;
19
+ export async function run(argv) {
20
+ const started = performance.now();
21
+ const requestId = randomUUID();
22
+ let jsonOutput = argv.includes('--json') || valueAfter(argv, '--output') === 'json';
23
+ try {
24
+ const command = argv[0];
25
+ if (command === undefined || command === '--help' || command === '-h' || argv.includes('--help') || argv.includes('-h')) {
26
+ process.stdout.write(HELP);
27
+ return 0;
28
+ }
29
+ let data;
30
+ let exit = 0;
31
+ switch (command) {
32
+ case 'export': {
33
+ const db = required(argv, '--db');
34
+ const out = required(argv, '--out');
35
+ const scopeValue = valueAfter(argv, '--scope') ?? 'all';
36
+ if (!['all', 'global', 'session'].includes(scopeValue))
37
+ throw new UsageError('--scope must be all, global, or session');
38
+ const snapshot = exportDatabase(db, {
39
+ ...(scopeValue !== 'all' ? { scope: scopeValue } : {}),
40
+ ...(valueAfter(argv, '--session-id') !== undefined ? { sessionId: valueAfter(argv, '--session-id') } : {}),
41
+ });
42
+ writeFileSync(resolve(out), canonicalJson(snapshot), 'utf8');
43
+ data = { out: resolve(out), templates: snapshot.templates.length, categories: snapshot.categories.length, data_sha256: snapshot.data_sha256 };
44
+ break;
45
+ }
46
+ case 'diff': {
47
+ const leftPath = positional(argv, 1, 'left snapshot');
48
+ const rightPath = positional(argv, 2, 'right snapshot');
49
+ const result = diffSnapshots(readSnapshot(leftPath), readSnapshot(rightPath));
50
+ data = result;
51
+ if (!result.identical && argv.includes('--fail-on-diff'))
52
+ exit = 1;
53
+ break;
54
+ }
55
+ case 'merge': {
56
+ const basePath = positional(argv, 1, 'base snapshot');
57
+ const incomingPath = positional(argv, 2, 'incoming snapshot');
58
+ const strategy = required(argv, '--strategy');
59
+ if (!['newer', 'keep-base', 'keep-incoming'].includes(strategy))
60
+ throw new UsageError('--strategy must be newer, keep-base, or keep-incoming');
61
+ const out = required(argv, '--out');
62
+ const result = mergeSnapshots(readSnapshot(basePath), readSnapshot(incomingPath), strategy, argv.includes('--allow-name-conflicts'));
63
+ if (result.snapshot === undefined) {
64
+ data = result;
65
+ exit = 1;
66
+ }
67
+ else {
68
+ writeFileSync(resolve(out), canonicalJson(result.snapshot), 'utf8');
69
+ data = { out: resolve(out), data_sha256: result.snapshot.data_sha256, ...result.summary };
70
+ }
71
+ break;
72
+ }
73
+ case 'import': {
74
+ const db = required(argv, '--db');
75
+ const input = readSnapshot(required(argv, '--in'));
76
+ const maxRaw = valueAfter(argv, '--max-changes') ?? '100';
77
+ const maxChanges = Number(maxRaw);
78
+ if (!Number.isSafeInteger(maxChanges) || maxChanges < 0)
79
+ throw new UsageError('--max-changes must be a non-negative integer');
80
+ const result = await importDatabase(db, input, {
81
+ apply: argv.includes('--apply'),
82
+ maxChanges,
83
+ ...(valueAfter(argv, '--expect-db-sha256') !== undefined ? { expectedDbSha256: valueAfter(argv, '--expect-db-sha256') } : {}),
84
+ ...(valueAfter(argv, '--confirm-summary-hash') !== undefined ? { confirmedSummarySha256: valueAfter(argv, '--confirm-summary-hash') } : {}),
85
+ ...(valueAfter(argv, '--backup-out') !== undefined ? { backupOut: valueAfter(argv, '--backup-out') } : {}),
86
+ });
87
+ data = result;
88
+ break;
89
+ }
90
+ case 'db-sha256':
91
+ data = { sha256: databaseSha256(required(argv, '--db')) };
92
+ break;
93
+ case 'search': {
94
+ const db = required(argv, '--db');
95
+ const limitRaw = valueAfter(argv, '--limit') ?? '20';
96
+ const limit = Number(limitRaw);
97
+ if (!Number.isSafeInteger(limit) || limit < 1)
98
+ throw new UsageError('--limit must be a positive integer');
99
+ const sessionId = valueAfter(argv, '--session-id');
100
+ if (sessionId === '')
101
+ throw new UsageError('--session-id must be non-empty');
102
+ data = searchTemplates(db, {
103
+ limit,
104
+ ...(valueAfter(argv, '--query') !== undefined ? { query: valueAfter(argv, '--query') } : {}),
105
+ ...(valueAfter(argv, '--category') !== undefined ? { category: valueAfter(argv, '--category') } : {}),
106
+ ...(sessionId !== undefined ? { sessionId } : {}),
107
+ });
108
+ break;
109
+ }
110
+ default: throw new UsageError(`unknown command: ${command}`);
111
+ }
112
+ output(jsonOutput, { success: exit === 0, data, request_id: requestId, meta: { duration_ms: Math.round(performance.now() - started) } }, data);
113
+ return exit;
114
+ }
115
+ catch (error) {
116
+ const usage = error instanceof UsageError;
117
+ const blocked = error instanceof ImportBlockedError;
118
+ const message = error instanceof Error ? error.message : String(error);
119
+ const envelope = { success: false, error: { code: usage ? 'INVALID_ARGUMENT' : blocked ? 'BLOCKED' : 'OPERATION_FAILED', message, resolution: usage ? 'Run with --help for usage.' : 'Review the input paths, schema, hashes, and database state.', retry: false }, request_id: requestId, meta: { duration_ms: Math.round(performance.now() - started) } };
120
+ if (jsonOutput)
121
+ process.stdout.write(`${JSON.stringify(envelope)}\n`);
122
+ else
123
+ process.stderr.write(`error: ${message}\n`);
124
+ return blocked ? 1 : 2;
125
+ }
126
+ }
127
+ function output(json, envelope, human) {
128
+ process.stdout.write(json ? `${JSON.stringify(envelope)}\n` : `${humanText(human)}\n`);
129
+ }
130
+ function humanText(value) {
131
+ if (typeof value === 'object' && value !== null && 'identical' in value) {
132
+ const diff = value;
133
+ return diff.identical
134
+ ? 'No differences.'
135
+ : `Differences: templates only-left=${diff.templates.only_left.length}, only-right=${diff.templates.only_right.length}, changed=${diff.templates.changed.length}, name-conflicts=${diff.templates.name_conflicts.length}; categories only-left=${diff.categories.only_left.length}, only-right=${diff.categories.only_right.length}`;
136
+ }
137
+ return JSON.stringify(value, null, 2);
138
+ }
139
+ function readSnapshot(path) { return parseSnapshot(JSON.parse(readFileSync(resolve(path), 'utf8'))); }
140
+ function required(argv, name) {
141
+ const value = valueAfter(argv, name);
142
+ if (value === undefined)
143
+ throw new UsageError(`missing ${name}`);
144
+ return value;
145
+ }
146
+ function positional(argv, index, label) {
147
+ const value = argv[index];
148
+ if (value === undefined || value.startsWith('-'))
149
+ throw new UsageError(`missing ${label}`);
150
+ return value;
151
+ }
152
+ function valueAfter(argv, name) {
153
+ const inline = argv.find(arg => arg.startsWith(`${name}=`));
154
+ if (inline !== undefined) {
155
+ const value = inline.slice(name.length + 1);
156
+ if (value === '')
157
+ throw new UsageError(`missing value for ${name}`);
158
+ return value;
159
+ }
160
+ const index = argv.indexOf(name);
161
+ if (index === -1)
162
+ return undefined;
163
+ const value = argv[index + 1];
164
+ if (value === undefined || value.startsWith('--'))
165
+ throw new UsageError(`missing value for ${name}`);
166
+ return value;
167
+ }
168
+ class UsageError extends Error {
169
+ }