@nelsonlongxiang/dsh-prompt-templates 0.2.9 → 0.4.4

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/lib/store.js ADDED
@@ -0,0 +1,275 @@
1
+ /**
2
+ * Pure-TS template store over `node:sqlite`, replacing the former Python
3
+ * backend child. Owns the same SQLite database file and schema
4
+ * (`templates` table, `user_version` 1), so an existing
5
+ * `$DSH_HOME/ext/prompt-templates/db.sqlite3` keeps working unchanged.
6
+ *
7
+ * Business rules ported verbatim from the Python store:
8
+ * - a template name is unique within its scope partition `(scope, session_id)`
9
+ * - `scope='session'` requires `session_id`; `scope='global'` must not carry one
10
+ * - make-global rejects already-global rows and global name collisions
11
+ *
12
+ * @module dsh-prompt-templates/store
13
+ */
14
+ import { randomUUID } from 'node:crypto';
15
+ import { mkdirSync, chmodSync } from 'node:fs';
16
+ import { dirname } from 'node:path';
17
+ import { DatabaseSync } from 'node:sqlite';
18
+ /** Schema version gate; v2 adds `templates.category` and the `categories` table. */
19
+ const SCHEMA_VERSION = 2;
20
+ const NAME_MAX = 128;
21
+ const DESCRIPTION_MAX = 512;
22
+ const SESSION_ID_MAX = 128;
23
+ /** Business-rule violation surfaced to routes as HTTP 400. */
24
+ export class TemplateRuleError extends Error {
25
+ constructor(message) {
26
+ super(message);
27
+ this.name = 'TemplateRuleError';
28
+ }
29
+ }
30
+ /** v2 schema: templates gain `category`; category tabs live in their own table. */
31
+ const SCHEMA_V2_SQL = `CREATE TABLE templates (
32
+ id TEXT PRIMARY KEY,
33
+ name TEXT NOT NULL,
34
+ content TEXT NOT NULL,
35
+ scope TEXT NOT NULL,
36
+ session_id TEXT,
37
+ description TEXT,
38
+ position INTEGER NOT NULL DEFAULT 0,
39
+ category TEXT,
40
+ created_at TEXT NOT NULL,
41
+ updated_at TEXT NOT NULL
42
+ );
43
+ CREATE TABLE categories (
44
+ name TEXT NOT NULL,
45
+ scope TEXT NOT NULL,
46
+ session_id TEXT,
47
+ PRIMARY KEY (scope, session_id, name)
48
+ )`;
49
+ /** Pure-TS prompt-template store owning one SQLite database file. */
50
+ export class TemplateStore {
51
+ db;
52
+ constructor(dbPath) {
53
+ if (dbPath !== ':memory:') {
54
+ mkdirSync(dirname(dbPath), { recursive: true });
55
+ try {
56
+ chmodSync(dirname(dbPath), 0o700);
57
+ }
58
+ catch { /* best-effort on non-POSIX */ }
59
+ }
60
+ this.db = new DatabaseSync(dbPath);
61
+ this.db.exec('PRAGMA journal_mode=WAL');
62
+ this.db.exec('PRAGMA busy_timeout=5000');
63
+ const onDisk = Number(this.db.prepare('PRAGMA user_version').get().user_version);
64
+ if (onDisk === 0) {
65
+ this.db.exec(SCHEMA_V2_SQL);
66
+ this.db.exec(`PRAGMA user_version=${SCHEMA_VERSION}`);
67
+ }
68
+ else if (onDisk === 1) {
69
+ // v1 → v2: category column (NULL = default tab) + the category tabs table.
70
+ this.db.exec('ALTER TABLE templates ADD COLUMN category TEXT');
71
+ this.db.exec('CREATE TABLE categories (name TEXT NOT NULL, scope TEXT NOT NULL, session_id TEXT, PRIMARY KEY (scope, session_id, name))');
72
+ this.db.exec(`PRAGMA user_version=${SCHEMA_VERSION}`);
73
+ }
74
+ else if (onDisk !== SCHEMA_VERSION) {
75
+ this.db.close();
76
+ throw new Error(`${dbPath} has schema version ${onDisk}, incompatible with this build (expected ${SCHEMA_VERSION})`);
77
+ }
78
+ if (dbPath !== ':memory:') {
79
+ try {
80
+ chmodSync(dbPath, 0o600);
81
+ }
82
+ catch { /* best-effort */ }
83
+ }
84
+ }
85
+ /** Close the underlying database handle. */
86
+ close() {
87
+ this.db.close();
88
+ }
89
+ /** List templates ordered by position then creation time, with optional scope/session filters. */
90
+ list(scope, sessionId) {
91
+ let sql = 'SELECT * FROM templates';
92
+ const conditions = [];
93
+ const args = [];
94
+ if (scope !== undefined) {
95
+ conditions.push('scope = ?');
96
+ args.push(scope);
97
+ }
98
+ if (sessionId !== undefined) {
99
+ conditions.push('session_id = ?');
100
+ args.push(sessionId);
101
+ }
102
+ if (conditions.length > 0)
103
+ sql += ` WHERE ${conditions.join(' AND ')}`;
104
+ sql += ' ORDER BY position, created_at';
105
+ return this.db.prepare(sql).all(...args).map(rowToView);
106
+ }
107
+ /** Fetch one template; `undefined` when absent. */
108
+ get(id) {
109
+ const row = this.db.prepare('SELECT * FROM templates WHERE id = ?').get(id);
110
+ return row === undefined ? undefined : rowToView(row);
111
+ }
112
+ /** Insert a template, rejecting a duplicate name in its scope partition. */
113
+ create(data) {
114
+ const scope = data.scope ?? 'global';
115
+ const sessionId = data.session_id ?? null;
116
+ if (typeof data.name !== 'string' || data.name.length < 1 || data.name.length > NAME_MAX) {
117
+ throw new TemplateRuleError(`name must be a string of 1..${NAME_MAX} characters`);
118
+ }
119
+ if (typeof data.content !== 'string' || data.content.length < 1) {
120
+ throw new TemplateRuleError('content must be a non-empty string');
121
+ }
122
+ if (scope === 'session' && (sessionId === null || sessionId === '')) {
123
+ throw new TemplateRuleError("scope='session' requires session_id");
124
+ }
125
+ if (scope === 'global' && sessionId !== null) {
126
+ throw new TemplateRuleError("scope='global' must not carry session_id");
127
+ }
128
+ if (sessionId !== null && sessionId.length > SESSION_ID_MAX) {
129
+ throw new TemplateRuleError(`session_id must be at most ${SESSION_ID_MAX} characters`);
130
+ }
131
+ const description = data.description ?? null;
132
+ if (description !== null && description.length > DESCRIPTION_MAX) {
133
+ throw new TemplateRuleError(`description must be at most ${DESCRIPTION_MAX} characters`);
134
+ }
135
+ const position = data.position ?? 0;
136
+ if (!Number.isInteger(position) || position < 0) {
137
+ throw new TemplateRuleError('position must be a non-negative integer');
138
+ }
139
+ const category = this.#validatedCategory(data.category, scope, sessionId);
140
+ const clash = this.db.prepare('SELECT id FROM templates WHERE scope = ? AND session_id IS ? AND name = ?').get(scope, sessionId, data.name);
141
+ if (clash !== undefined) {
142
+ throw new TemplateRuleError(`template name '${data.name}' already exists in scope ${scope}`);
143
+ }
144
+ const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
145
+ const row = {
146
+ id: randomUUID().replaceAll('-', ''),
147
+ name: data.name,
148
+ content: data.content,
149
+ scope,
150
+ session_id: sessionId,
151
+ description,
152
+ position,
153
+ category,
154
+ created_at: now,
155
+ updated_at: now,
156
+ };
157
+ this.db.prepare('INSERT INTO templates (id, name, content, scope, session_id, description, position, category, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(row.id, row.name, row.content, row.scope, row.session_id, row.description, row.position, row.category, row.created_at, row.updated_at);
158
+ return rowToView(row);
159
+ }
160
+ /** Apply a patch; `undefined` when absent. Renames keep the partition uniqueness rule. */
161
+ update(id, patch) {
162
+ const row = this.db.prepare('SELECT * FROM templates WHERE id = ?').get(id);
163
+ if (row === undefined)
164
+ return undefined;
165
+ const fields = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== undefined));
166
+ const newName = fields['name'];
167
+ if (newName !== undefined) {
168
+ if (typeof newName !== 'string' || newName.length < 1 || newName.length > NAME_MAX) {
169
+ throw new TemplateRuleError(`name must be a string of 1..${NAME_MAX} characters`);
170
+ }
171
+ if (newName !== row.name) {
172
+ const clash = this.db.prepare('SELECT id FROM templates WHERE id != ? AND scope = ? AND session_id IS ? AND name = ?').get(id, row.scope, row.session_id, newName);
173
+ if (clash !== undefined) {
174
+ throw new TemplateRuleError(`template name '${newName}' already exists in scope ${row.scope}`);
175
+ }
176
+ }
177
+ }
178
+ if (fields['description'] !== undefined && fields['description'] !== null
179
+ && String(fields['description']).length > DESCRIPTION_MAX) {
180
+ throw new TemplateRuleError(`description must be at most ${DESCRIPTION_MAX} characters`);
181
+ }
182
+ if (fields['position'] !== undefined && (!Number.isInteger(Number(fields['position'])) || Number(fields['position']) < 0)) {
183
+ throw new TemplateRuleError('position must be a non-negative integer');
184
+ }
185
+ if (fields['category'] !== undefined) {
186
+ fields['category'] = this.#validatedCategory(fields['category'], row.scope, row.session_id);
187
+ }
188
+ const merged = { ...row, ...fields };
189
+ merged.updated_at = new Date().toISOString().replace('T', ' ').slice(0, 19);
190
+ this.db.prepare('UPDATE templates SET name = ?, content = ?, description = ?, position = ?, category = ?, updated_at = ? WHERE id = ?').run(merged.name, merged.content, merged.description, merged.position, merged.category, merged.updated_at, id);
191
+ return rowToView(merged);
192
+ }
193
+ /** Promote one session template to the global partition; `undefined` when absent. */
194
+ makeGlobal(id) {
195
+ const row = this.db.prepare('SELECT * FROM templates WHERE id = ?').get(id);
196
+ if (row === undefined)
197
+ return undefined;
198
+ if (row.scope === 'global')
199
+ throw new TemplateRuleError(`template '${id}' is already global`);
200
+ const clash = this.db.prepare("SELECT id FROM templates WHERE scope = 'global' AND session_id IS NULL AND name = ?").get(row.name);
201
+ if (clash !== undefined) {
202
+ throw new TemplateRuleError(`template name '${row.name}' already exists in scope global`);
203
+ }
204
+ const updated = new Date().toISOString().replace('T', ' ').slice(0, 19);
205
+ this.db.prepare("UPDATE templates SET scope = 'global', session_id = NULL, updated_at = ? WHERE id = ?").run(updated, id);
206
+ return rowToView({ ...row, scope: 'global', session_id: null, updated_at: updated });
207
+ }
208
+ /** Delete one template; `false` when absent. */
209
+ delete(id) {
210
+ return this.db.prepare('DELETE FROM templates WHERE id = ?').run(id).changes > 0;
211
+ }
212
+ /** List user categories: global ones plus one session's, ordered by name. */
213
+ listCategories(sessionId) {
214
+ return this.db.prepare("SELECT name, scope, session_id FROM categories WHERE session_id IS NULL OR session_id IS ? ORDER BY name").all(sessionId ?? null)
215
+ .map(row => ({ ...row }));
216
+ }
217
+ /** Create one category tab; name unique within its (scope, session) partition. */
218
+ createCategory(data) {
219
+ const scope = data.scope ?? 'global';
220
+ const sessionId = data.session_id ?? null;
221
+ if (typeof data.name !== 'string' || data.name.trim().length < 1 || data.name.length > NAME_MAX) {
222
+ throw new TemplateRuleError(`category name must be a string of 1..${NAME_MAX} characters`);
223
+ }
224
+ if (scope === 'session' && (sessionId === null || sessionId === '')) {
225
+ throw new TemplateRuleError("scope='session' requires session_id");
226
+ }
227
+ if (scope === 'global' && sessionId !== null) {
228
+ throw new TemplateRuleError("scope='global' must not carry session_id");
229
+ }
230
+ const clash = this.db.prepare('SELECT name FROM categories WHERE scope = ? AND session_id IS ? AND name = ?').get(scope, sessionId, data.name);
231
+ if (clash !== undefined) {
232
+ throw new TemplateRuleError(`category '${data.name}' already exists in scope ${scope}`);
233
+ }
234
+ this.db.prepare('INSERT INTO categories (name, scope, session_id) VALUES (?, ?, ?)')
235
+ .run(data.name, scope, sessionId);
236
+ return { name: data.name, scope, session_id: sessionId };
237
+ }
238
+ /** Delete one category tab; its templates fall back to the default tab (category = NULL). */
239
+ deleteCategory(name, scope, sessionId) {
240
+ const existing = this.db.prepare('SELECT name FROM categories WHERE scope = ? AND session_id IS ? AND name = ?').get(scope, sessionId ?? null, name);
241
+ if (existing === undefined)
242
+ return false;
243
+ this.db.exec('BEGIN');
244
+ try {
245
+ this.db.prepare("UPDATE templates SET category = NULL WHERE category = ? AND scope = ? AND session_id IS ?")
246
+ .run(name, scope, sessionId ?? null);
247
+ this.db.prepare('DELETE FROM categories WHERE scope = ? AND session_id IS ? AND name = ?')
248
+ .run(scope, sessionId ?? null, name);
249
+ this.db.exec('COMMIT');
250
+ }
251
+ catch (error) {
252
+ this.db.exec('ROLLBACK');
253
+ throw error;
254
+ }
255
+ return true;
256
+ }
257
+ /**
258
+ * Validate a template's category against its scope partition: null is
259
+ * always fine (the default tab); a name must exist as a category of the
260
+ * same scope partition. Returns the normalized value.
261
+ */
262
+ #validatedCategory(category, scope, sessionId) {
263
+ if (category === undefined || category === null || category === '')
264
+ return null;
265
+ const existing = this.db.prepare('SELECT name FROM categories WHERE scope = ? AND session_id IS ? AND name = ?').get(scope, sessionId, category);
266
+ if (existing === undefined) {
267
+ throw new TemplateRuleError(`category '${category}' does not exist in scope ${scope}`);
268
+ }
269
+ return category;
270
+ }
271
+ }
272
+ /** Map one database row to the wire view (field names are already snake_case). */
273
+ function rowToView(row) {
274
+ return { ...row };
275
+ }
@@ -4,7 +4,7 @@
4
4
  * `{ ok: true; value } | { ok: false; error }` envelope the panel face
5
5
  * consumes, so callers never see transport details.
6
6
  */
7
- import type { TemplateView } from '../types.ts';
7
+ import type { CategoryView, TemplateView } from '../types.ts';
8
8
  /** Business error carried by a failed call. */
9
9
  export interface TemplateError {
10
10
  readonly code: string;
@@ -20,18 +20,31 @@ export type TemplateActionResult = {
20
20
  };
21
21
  /** Load the full template set (global + every session's). */
22
22
  export declare function listTemplates(): Promise<TemplateView[]>;
23
+ /** Load every user category tab (global + all sessions'; the panel filters). */
24
+ export declare function listCategories(): Promise<CategoryView[]>;
25
+ /** Create one category tab. */
26
+ export declare function createCategory(request: {
27
+ name: string;
28
+ scope: 'global' | 'session';
29
+ session_id: string | null;
30
+ }): Promise<TemplateActionResult>;
31
+ /** Delete one category tab (its templates fall back to the default tab). */
32
+ export declare function deleteCategory(name: string, scope: 'global' | 'session', sessionId: string | null): Promise<TemplateActionResult>;
23
33
  /** Create one template. */
24
34
  export declare function createTemplate(request: {
25
35
  name: string;
26
36
  content: string;
27
37
  scope: 'global' | 'session';
28
38
  session_id: string | null;
39
+ category?: string | null;
29
40
  }): Promise<TemplateActionResult>;
30
41
  /** Patch one template by id. */
31
42
  export declare function updateTemplate(id: string, request: {
32
43
  name?: string;
33
44
  content?: string;
34
45
  description?: string | null;
46
+ position?: number;
47
+ category?: string | null;
35
48
  }): Promise<TemplateActionResult>;
36
49
  /** Promote one session template to the global partition. */
37
50
  export declare function makeTemplateGlobal(id: string): Promise<TemplateActionResult>;
@@ -17,6 +17,12 @@ export declare const zh: {
17
17
  readonly 'panel.addSave': "保存";
18
18
  readonly 'panel.addCancel': "取消";
19
19
  readonly 'panel.insert': "插入";
20
+ readonly 'panel.interject': "插话打断";
21
+ readonly 'panel.newCategory': "新增分类";
22
+ readonly 'panel.categoryName': "分类名称";
23
+ readonly 'panel.categoryNone': "不设分类";
24
+ readonly 'panel.category': "分类";
25
+ readonly 'panel.deleteCategory': "删除分类";
20
26
  readonly 'panel.delete': "删除";
21
27
  readonly 'panel.edit': "编辑";
22
28
  readonly 'panel.makeGlobal': "设为全局";
@@ -42,6 +48,12 @@ export declare const en: {
42
48
  readonly 'panel.addSave': "Save";
43
49
  readonly 'panel.addCancel': "Cancel";
44
50
  readonly 'panel.insert': "Insert";
51
+ readonly 'panel.interject': "Interject (steer)";
52
+ readonly 'panel.newCategory': "New category";
53
+ readonly 'panel.categoryName': "Category name";
54
+ readonly 'panel.categoryNone': "No category";
55
+ readonly 'panel.category': "Category";
56
+ readonly 'panel.deleteCategory': "Delete category";
45
57
  readonly 'panel.delete': "Delete";
46
58
  readonly 'panel.edit': "Edit";
47
59
  readonly 'panel.makeGlobal': "Make global";
@@ -16,8 +16,10 @@ export type PromptPanelActions = BoundActions<ReturnType<typeof createPromptPane
16
16
  export interface IPromptPanel {
17
17
  /** Flip the panel open/closed. */
18
18
  toggle(): void;
19
- /** Insert one template's content into a session's composer draft. */
19
+ /** Insert one template's content into a session's composer draft at the caret. */
20
20
  insert(sessionId: SessionId, content: string): void;
21
+ /** Submit one template's content immediately, preserving the user's draft. */
22
+ interject(sessionId: SessionId, content: string): void;
21
23
  /** Fill the draft with one template's content and submit it immediately. */
22
24
  send(sessionId: SessionId, content: string): void;
23
25
  /**
@@ -56,12 +58,26 @@ export declare class PromptPanelController implements IPromptPanel {
56
58
  */
57
59
  openOnce(): void;
58
60
  /**
59
- * Append one template's content to a session's composer draft. An empty
60
- * draft takes the content verbatim; a non-empty draft joins with a newline.
61
+ * Insert one template's content into a session's composer draft at the
62
+ * live caret position (selection, when a range is selected, is replaced).
63
+ * The caret lives only in the DOM textarea — the input machine publishes
64
+ * no caret — so the composer textarea is located by matching its value
65
+ * against the draft snapshot; when no textarea is found the content falls
66
+ * back to an end-append (empty draft takes it verbatim, non-empty joins
67
+ * with a newline).
61
68
  * @param sessionId - target session.
62
69
  * @param content - template content.
63
70
  */
64
71
  insert(sessionId: SessionId, content: string): void;
72
+ /**
73
+ * Interject one template: steer it into the running agent turn. With
74
+ * steer mode the content interrupts the current turn at its next step
75
+ * (the same delivery as Cmd/Ctrl+Enter插话发送), rather than queuing
76
+ * after it. The user's own draft is left untouched.
77
+ * @param sessionId - target session.
78
+ * @param content - template content.
79
+ */
80
+ interject(sessionId: SessionId, content: string): void;
65
81
  /**
66
82
  * Fill the draft with one template's content and submit it immediately —
67
83
  * the same transaction as typing the text and pressing send.
@@ -6,10 +6,10 @@
6
6
  * carries the panel toggle.
7
7
  */
8
8
  import type { TemplateActionResult } from './api.ts';
9
- import type { TemplateView } from '../types.ts';
9
+ import type { CategoryView, TemplateView } from '../types.ts';
10
10
  /** One template row the panel renders (the backend record). */
11
11
  export type { TemplateView };
12
- export type { TemplateActionResult };
12
+ export type { TemplateActionResult, CategoryView };
13
13
  /** Persisted panel placement in viewport pixels. */
14
14
  export interface PanelPosition {
15
15
  readonly x: number;
@@ -19,18 +19,31 @@ export interface PanelPosition {
19
19
  export interface PromptPanelFace {
20
20
  /** Load the full template set (global + every session's); the component groups rows. */
21
21
  refresh: () => Promise<TemplateView[]>;
22
+ /** Load every user category tab (global + all sessions'). */
23
+ refreshCategories: () => Promise<CategoryView[]>;
24
+ /** Create one category tab (global, or owned by the given session). */
25
+ createCategory: (request: {
26
+ name: string;
27
+ scope: 'global' | 'session';
28
+ session_id: string | null;
29
+ }) => Promise<TemplateActionResult>;
30
+ /** Delete one category tab; its templates fall back to the default tab. */
31
+ removeCategory: (name: string, scope: 'global' | 'session', sessionId: string | null) => Promise<TemplateActionResult>;
22
32
  /** Create one template. */
23
33
  create: (request: {
24
34
  name: string;
25
35
  content: string;
26
36
  scope: 'global' | 'session';
27
37
  session_id: string | null;
38
+ category?: string | null;
28
39
  }) => Promise<TemplateActionResult>;
29
- /** Patch one template by id (name/content/description). */
40
+ /** Patch one template by id (name/content/description/position/category). */
30
41
  update: (id: string, request: {
31
42
  name?: string;
32
43
  content?: string;
33
44
  description?: string | null;
45
+ position?: number;
46
+ category?: string | null;
34
47
  }) => Promise<TemplateActionResult>;
35
48
  /** Delete one template by id. */
36
49
  remove: (id: string) => Promise<TemplateActionResult>;
@@ -42,10 +55,12 @@ export interface PromptPanelFace {
42
55
  savePanelPosition: (position: PanelPosition) => void;
43
56
  /** Forget the placement and return to the right-anchored default. */
44
57
  resetPanelPosition: () => void;
45
- /** Append the content to the session's composer draft. */
58
+ /** Insert the content at the session composer's caret position. */
46
59
  insert: (sessionId: string, content: string) => void;
47
60
  /** Fill the draft and submit it immediately (same as pressing send). */
48
61
  send: (sessionId: string, content: string) => void;
62
+ /** Submit the content immediately while preserving the user's draft (interject). */
63
+ interject: (sessionId: string, content: string) => void;
49
64
  }
50
65
  /** The composer entry's injected face: toggle the panel. */
51
66
  export interface PromptPanelToggleFace {
@@ -1,8 +1,8 @@
1
1
  /**
2
- * dsh-prompt-templates host half: spawns the Python backend child through
3
- * the subprocess seam and exposes template CRUD over web-server routes the
4
- * browser panel fetches (`/plugins/dsh-prompt-templates/*`). The Python
5
- * child owns all durable state; this plugin owns the child process, the
2
+ * dsh-prompt-templates host half: a pure-TS template store over
3
+ * `node:sqlite` (same schema and database file as the former Python
4
+ * backend child) exposed over web-server routes the browser panel fetches
5
+ * (`/plugins/dsh-prompt-templates/*`). The plugin owns the store, the
6
6
  * routes, and the settings namespace (panel default-open + placement).
7
7
  *
8
8
  * Route map (JSON bodies, `Cache-Control: no-store`):
@@ -19,17 +19,9 @@ import type { Context } from '@deepseek-ai/cordis';
19
19
  import s from '@deepseek-ai/schemastery';
20
20
  export type * from './types.ts';
21
21
  export declare const name = "prompt-templates";
22
- /** Spawns the Python child through the pythonBridge service; the web-server route registration waits for it lazily. */
23
- export declare const inject: string[];
24
- /** Deployment-varying spawn facts for the Python backend child. */
22
+ /** Deployment-varying persistence facts. */
25
23
  export interface Config {
26
- /** Complete argv; `argv[0]` is the executable running the backend `serve`. */
27
- readonly command: string[];
28
- /** Absolute working directory for the child. */
29
- readonly cwd?: string | null;
30
- /** Grace (ms) for the stdin-EOF quiesce before terminate escalation. */
31
- readonly eofGraceMs?: number | null;
32
- /** Optional explicit database path forwarded as `--db`. */
24
+ /** Optional explicit SQLite database path; defaults to `$DSH_HOME/ext/prompt-templates/db.sqlite3`. */
33
25
  readonly dbPath?: string | null;
34
26
  }
35
27
  export declare const Config: s<Config>;
@@ -39,10 +31,12 @@ export interface TemplateError {
39
31
  readonly message: string;
40
32
  }
41
33
  /**
42
- * Host plugin body: lazily register the web routes once the web server and
43
- * this plugin's pythonBridge service are both live; headless profiles without a
44
- * web server never block boot.
45
- * @param ctx - Host context carrying the pythonBridge service.
46
- * @param config - validated spawn facts for the Python backend.
34
+ * Host plugin body: own the template store, register the settings
35
+ * namespace, and lazily register the web routes once a web server is live;
36
+ * headless profiles without a web server never block boot.
37
+ * @param ctx - Host context.
38
+ * @param config - persistence facts.
47
39
  */
48
40
  export declare function apply(ctx: Context, config: Config): void;
41
+ export { TemplateStore, TemplateRuleError } from './store.ts';
42
+ export type { TemplateRow } from './store.ts';
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Pure-TS template store over `node:sqlite`, replacing the former Python
3
+ * backend child. Owns the same SQLite database file and schema
4
+ * (`templates` table, `user_version` 1), so an existing
5
+ * `$DSH_HOME/ext/prompt-templates/db.sqlite3` keeps working unchanged.
6
+ *
7
+ * Business rules ported verbatim from the Python store:
8
+ * - a template name is unique within its scope partition `(scope, session_id)`
9
+ * - `scope='session'` requires `session_id`; `scope='global'` must not carry one
10
+ * - make-global rejects already-global rows and global name collisions
11
+ *
12
+ * @module dsh-prompt-templates/store
13
+ */
14
+ import type { CategoryCreateRequest, CategoryView, PromptScope, TemplateCreateRequest, TemplateUpdateRequest, TemplateView } from './types.ts';
15
+ /** Business-rule violation surfaced to routes as HTTP 400. */
16
+ export declare class TemplateRuleError extends Error {
17
+ constructor(message: string);
18
+ }
19
+ /** One row as read from the database. */
20
+ export interface TemplateRow {
21
+ id: string;
22
+ name: string;
23
+ content: string;
24
+ scope: PromptScope;
25
+ session_id: string | null;
26
+ description: string | null;
27
+ position: number;
28
+ category: string | null;
29
+ created_at: string;
30
+ updated_at: string;
31
+ }
32
+ /** Pure-TS prompt-template store owning one SQLite database file. */
33
+ export declare class TemplateStore {
34
+ #private;
35
+ private readonly db;
36
+ constructor(dbPath: string);
37
+ /** Close the underlying database handle. */
38
+ close(): void;
39
+ /** List templates ordered by position then creation time, with optional scope/session filters. */
40
+ list(scope?: string, sessionId?: string): TemplateView[];
41
+ /** Fetch one template; `undefined` when absent. */
42
+ get(id: string): TemplateView | undefined;
43
+ /** Insert a template, rejecting a duplicate name in its scope partition. */
44
+ create(data: TemplateCreateRequest): TemplateView;
45
+ /** Apply a patch; `undefined` when absent. Renames keep the partition uniqueness rule. */
46
+ update(id: string, patch: TemplateUpdateRequest): TemplateView | undefined;
47
+ /** Promote one session template to the global partition; `undefined` when absent. */
48
+ makeGlobal(id: string): TemplateView | undefined;
49
+ /** Delete one template; `false` when absent. */
50
+ delete(id: string): boolean;
51
+ /** List user categories: global ones plus one session's, ordered by name. */
52
+ listCategories(sessionId?: string): CategoryView[];
53
+ /** Create one category tab; name unique within its (scope, session) partition. */
54
+ createCategory(data: CategoryCreateRequest): CategoryView;
55
+ /** Delete one category tab; its templates fall back to the default tab (category = NULL). */
56
+ deleteCategory(name: string, scope: string, sessionId?: string | null): boolean;
57
+ }
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * Wire payload types shared by the host routes and the browser API. Field
3
- * names match the Python side's Pydantic models verbatim (snake_case): the
4
- * type is the protocol and no field mapping can drift.
3
+ * names are snake_case end to end: the type is the protocol and no field
4
+ * mapping can drift.
5
5
  * @module dsh-prompt-templates/types
6
6
  */
7
7
  /** Scope partition of one template: global or private to one session. */
8
8
  export type PromptScope = 'global' | 'session';
9
- /** Canonical template record as stored by the Python backend. */
9
+ /** Canonical template record as stored by the backend. */
10
10
  export interface TemplateView {
11
11
  readonly id: string;
12
12
  readonly name: string;
@@ -16,10 +16,19 @@ export interface TemplateView {
16
16
  readonly session_id: string | null;
17
17
  readonly description: string | null;
18
18
  readonly position: number;
19
+ /** Category name; `null` = one of the default tabs (全局/会话模板). */
20
+ readonly category: string | null;
19
21
  /** ISO timestamp without timezone, as emitted by the backend. */
20
22
  readonly created_at: string;
21
23
  readonly updated_at: string;
22
24
  }
25
+ /** A user-created category tab. Default tabs (全局/会话模板) are implicit. */
26
+ export interface CategoryView {
27
+ readonly name: string;
28
+ readonly scope: PromptScope;
29
+ /** Owning session id; `null` for a global category. */
30
+ readonly session_id: string | null;
31
+ }
23
32
  /** Create payload; the backend validates scope/session consistency. */
24
33
  export interface TemplateCreateRequest {
25
34
  readonly name: string;
@@ -28,6 +37,7 @@ export interface TemplateCreateRequest {
28
37
  readonly session_id?: string | null;
29
38
  readonly description?: string | null;
30
39
  readonly position?: number;
40
+ readonly category?: string | null;
31
41
  }
32
42
  /** Update payload; every field optional. */
33
43
  export interface TemplateUpdateRequest {
@@ -35,4 +45,11 @@ export interface TemplateUpdateRequest {
35
45
  readonly content?: string;
36
46
  readonly description?: string | null;
37
47
  readonly position?: number;
48
+ readonly category?: string | null;
49
+ }
50
+ /** Category create payload. */
51
+ export interface CategoryCreateRequest {
52
+ readonly name: string;
53
+ readonly scope?: PromptScope;
54
+ readonly session_id?: string | null;
38
55
  }
package/lib/types.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Wire payload types shared by the host routes and the browser API. Field
3
- * names match the Python side's Pydantic models verbatim (snake_case): the
4
- * type is the protocol and no field mapping can drift.
3
+ * names are snake_case end to end: the type is the protocol and no field
4
+ * mapping can drift.
5
5
  * @module dsh-prompt-templates/types
6
6
  */
7
7
  export {};