@nelsonlongxiang/dsh-prompt-templates 0.2.10 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +102 -65
  2. package/README_zh.md +101 -65
  3. package/cordis.patch.yml +28 -37
  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 +273 -0
  9. package/lib/client/Panel.js +70 -103
  10. package/lib/client/PanelButton.js +27 -3
  11. package/lib/client/PromptTab.js +11 -0
  12. package/lib/client/api.js +27 -0
  13. package/lib/client/filter.js +27 -0
  14. package/lib/client/index.js +61 -35
  15. package/lib/client/locales.js +40 -2
  16. package/lib/client/meta.js +10 -0
  17. package/lib/client/service.js +69 -2
  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 +949 -199
  22. package/lib/client.js.map +1 -1
  23. package/lib/index.js +82 -60
  24. package/lib/inject.js +210 -0
  25. package/lib/invariant.js +1 -1
  26. package/lib/store.js +351 -0
  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 +22 -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 +40 -2
  39. package/lib/types/client/meta.d.ts +6 -0
  40. package/lib/types/client/service.d.ts +64 -4
  41. package/lib/types/client/slots.d.ts +68 -7
  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 +21 -20
  45. package/lib/types/inject.d.ts +145 -0
  46. package/lib/types/store.d.ts +80 -0
  47. package/lib/types/types.d.ts +54 -3
  48. package/lib/types.js +2 -2
  49. package/package.json +96 -111
  50. package/python/README.md +0 -26
  51. package/python/pyproject.toml +0 -33
  52. package/python/src/dsh_prompt_templates/__init__.py +0 -22
  53. package/python/src/dsh_prompt_templates/cli.py +0 -216
  54. package/python/src/dsh_prompt_templates/db.py +0 -125
  55. package/python/src/dsh_prompt_templates/models.py +0 -59
  56. package/python/src/dsh_prompt_templates/server.py +0 -170
  57. package/python/src/dsh_prompt_templates/store.py +0 -156
  58. package/python/uv.lock +0 -520
  59. package/scripts/bootstrap.mjs +0 -38
package/README.md CHANGED
@@ -1,65 +1,102 @@
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 a Python-backed SQLite persistence — 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
- **Requires `uv` on PATH** — install bootstraps a package-local Python venv with `uv sync`; a machine without it fails loud with a one-line fix instead of a broken install. The plugin composes beside the stock webserver row and spawns its Python child from that venv.
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 Python backend the Host bridges in as a managed subprocess (newline-delimited JSON-RPC); the child is lazily spawned and torn down with the plugin
28
-
29
- ## How it works
30
-
31
- ```text
32
- src/ TypeScript plugin (host half + browser half)
33
- index.ts Host: spawns the Python child, exposes the HTTP routes
34
- client/ Browser: panel UI registered into shell.overlay and
35
- conversation.input.right
36
- python/ Python backend package (template domain only)
37
- src/dsh_prompt_templates/
38
- pyproject.toml models, store, JSON-RPC server, CLI
39
- cordis.patch.yml Bundle patch: mounts the plugin row
40
- ```
41
-
42
- The Python package carries only the prompt-template domain, extracted from the shared extension backend so the plugin stays minimal and self-contained.
43
-
44
- ## Security
45
-
46
- - Template content reaches a model request only as ordinary user text the user chose to insert — no automatic injection into any prompt
47
- - The panel talks to the Python backend over the Host's plugin routes only; no extra listener, no outbound network
48
-
49
- ## Development
50
-
51
- ```sh
52
- pnpm install
53
- pnpm verify # typecheck + Python backend tests (uv --group test)
54
- pnpm build # tsc host + tsc client + tsdown browser bundle
55
- node scripts/bootstrap.mjs # uv sync the package-local venv
56
- ```
57
-
58
- ## Known limitations
59
-
60
- - **Insert appends to the draft** — caret-position insert is deferred
61
- - **Session templates need a current session** — with no session open, only global templates are reachable
62
-
63
- ## License
64
-
65
- 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 # typecheck
91
+ pnpm build # tsc host + tsc client + tsdown browser bundle
92
+ ```
93
+
94
+ ## Known limitations
95
+
96
+ - **Session templates need a current session** — with no session open, only global templates are reachable
97
+ - **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
98
+ - **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
99
+
100
+ ## License
101
+
102
+ MIT
package/README_zh.md CHANGED
@@ -1,65 +1,101 @@
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) 快捷提示词模板:全局与会话级模板、右侧浏览器面板、Python 后端的 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
- **需要 PATH 上有 `uv`**——安装时用 `uv sync` 建包内 Python venv;缺失的机器会大声报错并给出一行修复指引,而不是装出坏插件。插件组合在标准 webserver 行旁,Python 子进程从该 venv 拉起。
20
-
21
- ## 你能得到什么
22
-
23
- - **全局 + 会话模板**——全局处处生效;会话模板只属于当前对话,一键提升为全局
24
- - **插入或直发**——一键追加进草稿;send-now 立即发送;编辑、删除、转全局都在行内
25
- - **搜索与滚动**——边输入边过滤,长列表滚动可靠
26
- - **拖拽定位、双击复位**——面板记住你放的位置
27
- - **设计即持久**——模板经 Python 后端存 SQLite,Host 以受管子进程接入(换行分隔 JSON-RPC);子进程惰性拉起、随插件卸载回收
28
-
29
- ## 工作原理
30
-
31
- ```text
32
- src/ TypeScript 插件(host 面 + 浏览器面)
33
- index.ts Host:拉起 Python 子进程,暴露 HTTP 路由
34
- client/ 浏览器:面板 UI 注册进 shell.overlay 与
35
- conversation.input.right
36
- python/ Python 后端包(仅模板领域)
37
- src/dsh_prompt_templates/
38
- pyproject.toml models、store、JSON-RPC server、CLI
39
- cordis.patch.yml Bundle patch:挂插件行
40
- ```
41
-
42
- Python 包只承载模板领域,从共享扩展后端剥离而来,保持插件最小自包含。
43
-
44
- ## 安全
45
-
46
- - 模板内容只有经用户主动插入才作为普通用户文本进入模型请求——绝不自动注入任何提示词
47
- - 面板仅经 Host 的插件路由访问 Python 后端;无额外监听、无外联网络
48
-
49
- ## 开发
50
-
51
- ```sh
52
- pnpm install
53
- pnpm verify # typecheck + Python 后端测试(uv --group test)
54
- pnpm build # tsc host + tsc client + tsdown 浏览器 bundle
55
- node scripts/bootstrap.mjs # uv sync 包内 venv
56
- ```
57
-
58
- ## 已知限制
59
-
60
- - **插入是追加到草稿**——光标位置插入暂缓
61
- - **会话模板需要当前会话**——无会话打开时只能用全局模板
62
-
63
- ## 许可证
64
-
65
- 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 # typecheck
90
+ pnpm build # tsc host + tsc client + tsdown 浏览器 bundle
91
+ ```
92
+
93
+ ## 已知限制
94
+
95
+ - **会话模板需要当前会话**——无会话打开时只能用全局模板
96
+ - **注入不在对话流中渲染**——DSH 对话视图按设计省略注入的 context 行(消息 source 非 `user`);可在轨迹 tab 查看。交付模式为"对话流可见"的模板是例外:以普通用户消息渲染
97
+ - **请从 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`
98
+
99
+ ## 许可证
100
+
101
+ MIT
package/cordis.patch.yml CHANGED
@@ -1,37 +1,28 @@
1
- # dsh-prompt-templates bundle patch: mounts the prompt-templates plugin into
2
- # the host composition of a dsh profile. The plugin registers its
3
- # /plugins/dsh-prompt-templates routes into the shared web server and its
4
- # settings namespace into the shared settings document, so it needs no realm.
5
- #
6
- # Install: `dsh plugin --profile <name> add <this package>` (npm, a local
7
- # path, or Git). The `dsh plugin` command pnpm-installs the package into the
8
- # profile and reconciles it into the profile's `dsh.profile.bundles` layer
9
- # list.
10
- #
11
- # The Python backend child runs through `uv run --project <pkg>/python`:
12
- # `uv` lazily creates and syncs the package-local venv on first spawn, so no
13
- # separate bootstrap step has to have run inside the installed copy (a
14
- # `file:` install never executes `prepare`). The patch JS sandbox exposes
15
- # `process` and `baseUrl` (the profile directory, whose node_modules holds
16
- # the installed package) — `require`/`__dirname` are not available there.
17
- - insert:
18
- # Python backend child. The shared `python-bridge` service is provided by
19
- # the host profile (typically via @nelsonlongxiang/dsh-native-teams or by
20
- # explicitly bundling @nelsonlongxiang/dsh-python-bridge); this patch no
21
- # longer declares it to avoid duplicate loader entry ids when multiple
22
- # Python-backed plugins are composed.
23
- - id: prompt-templates
24
- # Node-resolvable package name — must stay in sync with package.json
25
- # `name`. Quoted because `@` is a reserved YAML indicator.
26
- name: '@nelsonlongxiang/dsh-prompt-templates'
27
- config:
28
- # The Python backend child: uv-managed package venv running the
29
- # extracted template backend's serve command.
30
- command: !!js >
31
- process.platform === 'win32'
32
- ? ['uv', 'run', '--project', process.getBuiltinModule('node:url').fileURLToPath(new URL('node_modules/@nelsonlongxiang/dsh-prompt-templates/python', baseUrl)), 'python', '-m', 'dsh_prompt_templates.cli', 'serve']
33
- : ['uv', 'run', '--project', process.getBuiltinModule('node:url').fileURLToPath(new URL('node_modules/@nelsonlongxiang/dsh-prompt-templates/python', baseUrl)), 'python', '-m', 'dsh_prompt_templates.cli', 'serve']
34
- # Explicit SQLite database path so persistence lands under
35
- # $DSH_HOME/ext/prompt-templates/ regardless of cwd or environment drift.
36
- dbPath: !!js >
37
- `${(process.env.DSH_HOME ?? `${process.getBuiltinModule('node:os').homedir()}/.dsh`).replace(/\\/g, '/')}/ext/prompt-templates/db.sqlite3`
1
+ # dsh-prompt-templates bundle patch: mounts the prompt-templates plugin into
2
+ # the host composition of a dsh profile. The plugin registers its
3
+ # /plugins/dsh-prompt-templates routes into the shared web server and its
4
+ # settings namespace into the shared settings document, so it needs no realm.
5
+ #
6
+ # Install: `dsh plugin --profile <name> add <this package>` (npm, a local
7
+ # path, or Git). The `dsh plugin` command pnpm-installs the package into the
8
+ # profile and reconciles it into the profile's `dsh.profile.bundles` layer
9
+ # list.
10
+ #
11
+ # The host half is pure TS: templates persist through `node:sqlite`
12
+ # directly inside the host process (no Python child, no pythonBridge
13
+ # service dependency). The patch JS sandbox exposes `process`; the default
14
+ # database path already resolves under $DSH_HOME, so only overrides need it.
15
+ - insert:
16
+ - id: prompt-templates
17
+ # Node-resolvable package name — must stay in sync with package.json
18
+ # `name`. Quoted because `@` is a reserved YAML indicator.
19
+ name: '@nelsonlongxiang/dsh-prompt-templates'
20
+ config:
21
+ # Explicit SQLite database path so persistence lands under
22
+ # $DSH_HOME/ext/prompt-templates/ regardless of cwd or environment drift.
23
+ dbPath: !!js >
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
+ }