@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/lib/inject.js ADDED
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Scheduled template auto-injection (host half): re-surfaces inject-enabled
3
+ * templates into the model context on turn boundaries. The single sanctioned
4
+ * mutation point is the `agent/pre-step` waterfall — its enter decision can
5
+ * append user-role messages, which the loop then logs as durable
6
+ * `user/message` events, keeping the model-visible input replayable. The
7
+ * `<system-reminder>` frame and typed source mirror the tool-skill catalog
8
+ * precedent.
9
+ *
10
+ * Trigger semantics: a template injects at the FIRST admitted step of every
11
+ * boundary turn (`turn % inject_every === 0`, turns are 1-based and durable).
12
+ * Idempotence is anchored on the durable log — a boundary turn that already
13
+ * carries a `prompt-template-schedule` message is never injected twice —
14
+ * while a per-session in-memory memo keeps the common step free of scans.
15
+ *
16
+ * @module dsh-prompt-templates/inject
17
+ */
18
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
19
+ import { expandTemplateVariables } from "./variables.js";
20
+ /** How many recent injections per session the history surface keeps. */
21
+ export const INJECTION_HISTORY_LIMIT = 20;
22
+ /**
23
+ * Per-session injection bookkeeping. Memory-only surface for the UI badge
24
+ * and its history dropdown; correctness of injection itself never depends
25
+ * on it (the durable log remains the idempotence anchor).
26
+ */
27
+ export class InjectionTracker {
28
+ #history = new Map();
29
+ /** Record that `sessionId` just received the injection described by `entry`. */
30
+ note(sessionId, entry) {
31
+ const entries = this.#history.get(sessionId) ?? [];
32
+ entries.unshift(entry);
33
+ if (entries.length > INJECTION_HISTORY_LIMIT)
34
+ entries.length = INJECTION_HISTORY_LIMIT;
35
+ this.#history.set(sessionId, entries);
36
+ }
37
+ /** The latest injection recorded for `sessionId`, or null if none since boot. */
38
+ status(sessionId) {
39
+ const latest = this.#history.get(sessionId)?.[0];
40
+ if (latest === undefined)
41
+ return null;
42
+ return { turn: latest.turn, at: latest.at, templates: latest.templates };
43
+ }
44
+ /** The session recent injections, newest first (bounded by INJECTION_HISTORY_LIMIT). */
45
+ history(sessionId) {
46
+ return [...this.#history.get(sessionId) ?? []];
47
+ }
48
+ }
49
+ /** Whether `turn` is a boundary turn for the interval `every` (both 1-based positive). */
50
+ export function isBoundaryTurn(turn, every) {
51
+ return Number.isInteger(turn) && turn >= 1 && Number.isInteger(every) && every >= 1 && turn % every === 0;
52
+ }
53
+ /** Narrow one page of templates to those enabled and due at this boundary turn, preserving store order. */
54
+ export function dueTemplates(templates, turn) {
55
+ const due = [];
56
+ for (const template of templates) {
57
+ if (template.inject_enabled && template.inject_every !== null && isBoundaryTurn(turn, template.inject_every)) {
58
+ due.push({ id: template.id, name: template.name, content: template.content, every: template.inject_every, mode: template.mode });
59
+ }
60
+ }
61
+ return due;
62
+ }
63
+ /**
64
+ * Whether the event window `[scannedFrom, events.length)` already carries a
65
+ * scheduled injection for `turn`. Backward scan over durable events only —
66
+ * the same posture as the skill-catalog probe, so compaction visibility and
67
+ * restart resume never resurrect a duplicate. Matches BOTH delivery shapes:
68
+ * the silent `prompt-template-schedule` source and the visible user-channel
69
+ * source (`kind:'user'` + `scheduled:'prompt-template'`).
70
+ */
71
+ export function alreadyInjectedAtTurn(events, scannedFrom, turn) {
72
+ for (let index = events.length - 1; index >= scannedFrom; index -= 1) {
73
+ const event = events[index];
74
+ if (event === undefined || event.type !== 'user/message')
75
+ continue;
76
+ const source = event.data.source;
77
+ if (source === undefined || source.turn !== turn)
78
+ continue;
79
+ const scheduled = source.kind === 'prompt-template-schedule'
80
+ || (source.kind === 'user' && source.scheduled === 'prompt-template');
81
+ if (!scheduled)
82
+ continue;
83
+ return true;
84
+ }
85
+ return false;
86
+ }
87
+ /** XML-escape a template name for the `<template name="…">` attribute. */
88
+ function escapeTemplateName(name) {
89
+ return name
90
+ .replaceAll('&', '&amp;')
91
+ .replaceAll('<', '&lt;')
92
+ .replaceAll('>', '&gt;')
93
+ .replaceAll('"', '&quot;');
94
+ }
95
+ /**
96
+ * Render ONE combined `<system-reminder>` user message for the due
97
+ * templates. The frame is written for the model (English, like every
98
+ * first-party reminder); template content is embedded verbatim and the
99
+ * durable source records what went out.
100
+ */
101
+ export function renderInjectionMessage(turn, templates) {
102
+ return createUserMessage({
103
+ content: [{
104
+ type: 'text',
105
+ text: [
106
+ '<system-reminder>',
107
+ `Scheduled prompt-template injection from dsh-prompt-templates (turn ${turn}). The following templates repeat every N rounds in this session; follow their guidance for the work in this round.`,
108
+ '',
109
+ ...templates.flatMap(template => [
110
+ `<template name="${escapeTemplateName(template.name)}" every="${template.every}">`,
111
+ template.content,
112
+ '</template>',
113
+ ]),
114
+ '</system-reminder>',
115
+ ].join('\n'),
116
+ }],
117
+ source: {
118
+ kind: 'prompt-template-schedule',
119
+ turn,
120
+ templates: templates.map(template => ({ id: template.id, name: template.name, every: template.every })),
121
+ },
122
+ });
123
+ }
124
+ /**
125
+ * Render ONE visible scheduled injection as an ordinary user message. The
126
+ * header names the origin (so a reader never mistakes it for human typing)
127
+ * and the durable source keeps the dedup-scan marker.
128
+ */
129
+ export function renderVisibleInjectionMessage(turn, templates) {
130
+ return createUserMessage({
131
+ content: [{
132
+ type: 'text',
133
+ text: [
134
+ `⚙️ 定时注入 · 第 ${turn} 轮 · ${templates.map(template => template.name).join('、')}`,
135
+ '',
136
+ ...templates.flatMap(template => [template.content, '']),
137
+ ].join('\n').trimEnd(),
138
+ }],
139
+ source: {
140
+ kind: 'user',
141
+ scheduled: 'prompt-template',
142
+ turn,
143
+ templates: templates.map(template => ({ id: template.id, name: template.name, every: template.every })),
144
+ },
145
+ });
146
+ }
147
+ /**
148
+ * Register the `agent/pre-step` listener that performs scheduled injection
149
+ * for every agent in this composition. Registration order is irrelevant:
150
+ * the listener calls `next()` first and only appends to the downstream
151
+ * decision, so other pre-step listeners keep their own semantics.
152
+ *
153
+ * Failure posture mirrors the skill catalog: a fault inside this listener
154
+ * must never fail the session's steps, so the first fault is reported and
155
+ * later ones stay silent while injection degrades to pass-through.
156
+ *
157
+ * @param ctx - host context to attach the listener to.
158
+ * @param config - deployment switch.
159
+ * @param store - lazy template store accessor (shared with the routes).
160
+ * @returns handle exposing the per-session last-injection status for the UI.
161
+ */
162
+ export function registerAutoInject(ctx, config, store) {
163
+ const tracker = new InjectionTracker();
164
+ // Per-session performance memo ONLY — correctness is anchored on the
165
+ // durable log scan. Entries are cheap and bounded by session count.
166
+ const sessions = new Map();
167
+ let faultReported = false;
168
+ ctx.on('agent/pre-step', async ({ agent, messages, turn, signal }, next) => {
169
+ const decision = await next();
170
+ if (decision.kind === 'reject')
171
+ return decision;
172
+ if (!config.enabled)
173
+ return decision;
174
+ // Never fabricate a step: injection rides an admitted batch only.
175
+ if (messages.length === 0)
176
+ return decision;
177
+ try {
178
+ const sessionId = String(agent.session.header.id);
179
+ const state = sessions.get(sessionId) ?? { scanned: 0, injectedTurns: new Set() };
180
+ sessions.set(sessionId, state);
181
+ if (state.injectedTurns.has(turn))
182
+ return decision;
183
+ // alpha.4 removed the session.events getter: prefer the snapshotEvents()
184
+ // frozen full-log snapshot, fall back to the legacy array, then empty.
185
+ const sessionLike = agent.session;
186
+ const events = (typeof sessionLike.snapshotEvents === 'function' ? sessionLike.snapshotEvents() : sessionLike.events) ?? [];
187
+ // Compaction or a log rewrite can shrink the array: memo indexes would
188
+ // go stale, so fall back to a full rescan.
189
+ if (events.length < state.scanned)
190
+ state.scanned = 0;
191
+ const due = dueTemplates(store().listInjectable(sessionId), turn);
192
+ if (due.length === 0)
193
+ return decision;
194
+ // Expand variable placeholders with this delivery context;
195
+ // unresolved ones stay literal. The history surface records the
196
+ // expanded bodies — what actually went out.
197
+ const expanded = due.map(candidate => ({
198
+ ...candidate,
199
+ content: expandTemplateVariables(candidate.content, { sessionId, turn }),
200
+ }));
201
+ if (alreadyInjectedAtTurn(events, state.scanned, turn)) {
202
+ state.injectedTurns.add(turn);
203
+ return decision;
204
+ }
205
+ signal.throwIfAborted();
206
+ state.scanned = events.length;
207
+ state.injectedTurns.add(turn);
208
+ tracker.note(sessionId, {
209
+ turn,
210
+ at: Date.now(),
211
+ templates: due.map(template => template.name),
212
+ content: expanded.map(template => template.content).join('\n\n'),
213
+ });
214
+ // Split by delivery mode: silent templates ride the invisible reminder
215
+ // frame; visible ones stamp the user channel so the chat transcript
216
+ // renders them. Both share one boundary (dedup covers the turn as a
217
+ // whole — either source shape satisfies alreadyInjectedAtTurn).
218
+ const injected = [];
219
+ const silent = expanded.filter(template => template.mode !== 'visible');
220
+ const visible = expanded.filter(template => template.mode === 'visible');
221
+ if (silent.length > 0)
222
+ injected.push(renderInjectionMessage(turn, silent));
223
+ if (visible.length > 0)
224
+ injected.push(renderVisibleInjectionMessage(turn, visible));
225
+ return { ...decision, messages: [...decision.messages, ...injected] };
226
+ }
227
+ catch (error) {
228
+ if (!faultReported) {
229
+ faultReported = true;
230
+ console.error('[dsh-prompt-templates] auto-inject skipped this step; further faults stay silent:', error);
231
+ }
232
+ return decision;
233
+ }
234
+ });
235
+ return { status: tracker.status.bind(tracker), history: tracker.history.bind(tracker) };
236
+ }
package/lib/invariant.js CHANGED
@@ -4,7 +4,7 @@ const PACKAGE_NAME = 'dsh-prompt-templates';
4
4
  export const name = 'prompt-templates-invariant';
5
5
  /** Service required before the companion can reserve package ownership. */
6
6
  export const inject = ['invariants'];
7
- /** No runtime invariant: the durable truth lives in the Python SQLite backend. */
7
+ /** No runtime invariant: the store owns its data integrity in SQLite directly. */
8
8
  const install = () => { };
9
9
  /** Register this package's invariant companion. */
10
10
  export const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
package/lib/store.js CHANGED
@@ -1,13 +1,18 @@
1
1
  /**
2
2
  * Pure-TS template store over `node:sqlite`, replacing the former Python
3
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.
4
+ * (`templates` + `categories` tables, `user_version` 4), so an existing
5
+ * `$DSH_HOME/ext/prompt-templates/db.sqlite3` keeps working and migrates
6
+ * in place.
6
7
  *
7
8
  * Business rules ported verbatim from the Python store:
8
9
  * - a template name is unique within its scope partition `(scope, session_id)`
9
10
  * - `scope='session'` requires `session_id`; `scope='global'` must not carry one
10
11
  * - make-global rejects already-global rows and global name collisions
12
+ * and extended in v3 with the auto-inject facts:
13
+ * - `inject_enabled` toggles per-round scheduled injection
14
+ * - `inject_every` is the interval in rounds (1..injectMaxEvery); it is
15
+ * required whenever `inject_enabled` is on and may persist while off
11
16
  *
12
17
  * @module dsh-prompt-templates/store
13
18
  */
@@ -15,8 +20,10 @@ import { randomUUID } from 'node:crypto';
15
20
  import { mkdirSync, chmodSync } from 'node:fs';
16
21
  import { dirname } from 'node:path';
17
22
  import { DatabaseSync } from 'node:sqlite';
18
- /** Schema version gate; v2 adds `templates.category` and the `categories` table. */
19
- const SCHEMA_VERSION = 2;
23
+ /** Schema version gate; v4 adds `templates.mode` (inject|visible). */
24
+ const SCHEMA_VERSION = 4;
25
+ /** Upper bound of the inject interval when the deployment config omits one. */
26
+ export const DEFAULT_INJECT_MAX_EVERY = 1000;
20
27
  const NAME_MAX = 128;
21
28
  const DESCRIPTION_MAX = 512;
22
29
  const SESSION_ID_MAX = 128;
@@ -27,29 +34,34 @@ export class TemplateRuleError extends Error {
27
34
  this.name = 'TemplateRuleError';
28
35
  }
29
36
  }
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)
37
+ /** v4 schema: v3 columns plus the injection delivery mode. */
38
+ const SCHEMA_V4_SQL = `CREATE TABLE templates (
39
+ id TEXT PRIMARY KEY,
40
+ name TEXT NOT NULL,
41
+ content TEXT NOT NULL,
42
+ scope TEXT NOT NULL,
43
+ session_id TEXT,
44
+ description TEXT,
45
+ position INTEGER NOT NULL DEFAULT 0,
46
+ category TEXT,
47
+ inject_enabled INTEGER NOT NULL DEFAULT 0,
48
+ inject_every INTEGER,
49
+ mode TEXT NOT NULL DEFAULT 'inject',
50
+ created_at TEXT NOT NULL,
51
+ updated_at TEXT NOT NULL
52
+ );
53
+ CREATE TABLE categories (
54
+ name TEXT NOT NULL,
55
+ scope TEXT NOT NULL,
56
+ session_id TEXT,
57
+ PRIMARY KEY (scope, session_id, name)
48
58
  )`;
49
59
  /** Pure-TS prompt-template store owning one SQLite database file. */
50
60
  export class TemplateStore {
61
+ #injectMaxEvery;
51
62
  db;
52
- constructor(dbPath) {
63
+ constructor(dbPath, options = {}) {
64
+ this.#injectMaxEvery = options.injectMaxEvery ?? DEFAULT_INJECT_MAX_EVERY;
53
65
  if (dbPath !== ':memory:') {
54
66
  mkdirSync(dirname(dbPath), { recursive: true });
55
67
  try {
@@ -62,14 +74,33 @@ export class TemplateStore {
62
74
  this.db.exec('PRAGMA busy_timeout=5000');
63
75
  const onDisk = Number(this.db.prepare('PRAGMA user_version').get().user_version);
64
76
  if (onDisk === 0) {
65
- this.db.exec(SCHEMA_V2_SQL);
77
+ this.db.exec(SCHEMA_V4_SQL);
66
78
  this.db.exec(`PRAGMA user_version=${SCHEMA_VERSION}`);
67
79
  }
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}`);
80
+ else if (onDisk >= 1 && onDisk < SCHEMA_VERSION) {
81
+ // Migration DDL runs in ONE transaction: a crash mid-way rolls back to
82
+ // the intact previous schema instead of stranding a half-altered table
83
+ // (same BEGIN/COMMIT posture as the category delete below).
84
+ this.db.exec('BEGIN');
85
+ try {
86
+ if (onDisk === 1) {
87
+ this.db.exec('ALTER TABLE templates ADD COLUMN category TEXT');
88
+ this.db.exec('CREATE TABLE categories (name TEXT NOT NULL, scope TEXT NOT NULL, session_id TEXT, PRIMARY KEY (scope, session_id, name))');
89
+ }
90
+ if (onDisk <= 2) {
91
+ this.db.exec('ALTER TABLE templates ADD COLUMN inject_enabled INTEGER NOT NULL DEFAULT 0');
92
+ this.db.exec('ALTER TABLE templates ADD COLUMN inject_every INTEGER');
93
+ }
94
+ if (onDisk <= 3) {
95
+ this.db.exec("ALTER TABLE templates ADD COLUMN mode TEXT NOT NULL DEFAULT 'inject'");
96
+ }
97
+ this.db.exec(`PRAGMA user_version=${SCHEMA_VERSION}`);
98
+ this.db.exec('COMMIT');
99
+ }
100
+ catch (error) {
101
+ this.db.exec('ROLLBACK');
102
+ throw error;
103
+ }
73
104
  }
74
105
  else if (onDisk !== SCHEMA_VERSION) {
75
106
  this.db.close();
@@ -104,6 +135,13 @@ export class TemplateStore {
104
135
  sql += ' ORDER BY position, created_at';
105
136
  return this.db.prepare(sql).all(...args).map(rowToView);
106
137
  }
138
+ /**
139
+ * List injection-enabled templates that apply to one session: global ones
140
+ * plus the session's own, ordered by position then creation time.
141
+ */
142
+ listInjectable(sessionId) {
143
+ return this.db.prepare("SELECT * FROM templates WHERE inject_enabled = 1 AND (scope = 'global' OR (scope = 'session' AND session_id = ?)) ORDER BY position, created_at").all(sessionId).map(rowToView);
144
+ }
107
145
  /** Fetch one template; `undefined` when absent. */
108
146
  get(id) {
109
147
  const row = this.db.prepare('SELECT * FROM templates WHERE id = ?').get(id);
@@ -137,6 +175,8 @@ export class TemplateStore {
137
175
  throw new TemplateRuleError('position must be a non-negative integer');
138
176
  }
139
177
  const category = this.#validatedCategory(data.category, scope, sessionId);
178
+ const inject = this.#validatedInject(data.inject_enabled, data.inject_every);
179
+ const mode = validatedMode(data.mode);
140
180
  const clash = this.db.prepare('SELECT id FROM templates WHERE scope = ? AND session_id IS ? AND name = ?').get(scope, sessionId, data.name);
141
181
  if (clash !== undefined) {
142
182
  throw new TemplateRuleError(`template name '${data.name}' already exists in scope ${scope}`);
@@ -151,10 +191,13 @@ export class TemplateStore {
151
191
  description,
152
192
  position,
153
193
  category,
194
+ inject_enabled: inject.enabled ? 1 : 0,
195
+ inject_every: inject.every,
196
+ mode,
154
197
  created_at: now,
155
198
  updated_at: now,
156
199
  };
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);
200
+ this.db.prepare('INSERT INTO templates (id, name, content, scope, session_id, description, position, category, inject_enabled, inject_every, mode, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(row.id, row.name, row.content, row.scope, row.session_id, row.description, row.position, row.category, row.inject_enabled, row.inject_every, row.mode, row.created_at, row.updated_at);
158
201
  return rowToView(row);
159
202
  }
160
203
  /** Apply a patch; `undefined` when absent. Renames keep the partition uniqueness rule. */
@@ -185,9 +228,16 @@ export class TemplateStore {
185
228
  if (fields['category'] !== undefined) {
186
229
  fields['category'] = this.#validatedCategory(fields['category'], row.scope, row.session_id);
187
230
  }
231
+ // Auto-inject facts resolve against the CURRENT row: an omitted field
232
+ // keeps its stored value, and the pair is validated as a whole.
233
+ const inject = this.#validatedInject(fields['inject_enabled'], fields['inject_every'], row.inject_enabled === 1, row.inject_every);
234
+ if (fields['mode'] !== undefined)
235
+ fields['mode'] = validatedMode(fields['mode']);
188
236
  const merged = { ...row, ...fields };
237
+ merged.inject_enabled = inject.enabled ? 1 : 0;
238
+ merged.inject_every = inject.every;
189
239
  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);
240
+ this.db.prepare('UPDATE templates SET name = ?, content = ?, description = ?, position = ?, category = ?, inject_enabled = ?, inject_every = ?, mode = ?, updated_at = ? WHERE id = ?').run(merged.name, merged.content, merged.description, merged.position, merged.category, merged.inject_enabled, merged.inject_every, merged.mode, merged.updated_at, id);
191
241
  return rowToView(merged);
192
242
  }
193
243
  /** Promote one session template to the global partition; `undefined` when absent. */
@@ -268,8 +318,34 @@ export class TemplateStore {
268
318
  }
269
319
  return category;
270
320
  }
321
+ /**
322
+ * Validate the auto-inject pair as a whole. Omitted fields fall back to
323
+ * the current row's values (create has none); enabling requires a whole
324
+ * interval within 1..injectMaxEvery, while disabling may keep the old
325
+ * interval so re-enabling needs no retyping.
326
+ */
327
+ #validatedInject(enabled, every, currentEnabled = false, currentEvery = null) {
328
+ const resolvedEnabled = enabled ?? currentEnabled;
329
+ const resolvedEvery = every === undefined ? currentEvery : every;
330
+ if (resolvedEvery !== null && (!Number.isInteger(resolvedEvery) || resolvedEvery < 1 || resolvedEvery > this.#injectMaxEvery)) {
331
+ throw new TemplateRuleError(`inject_every must be an integer between 1 and ${this.#injectMaxEvery}`);
332
+ }
333
+ if (resolvedEnabled && resolvedEvery === null) {
334
+ throw new TemplateRuleError('inject_every is required when inject is enabled');
335
+ }
336
+ return { enabled: resolvedEnabled, every: resolvedEvery };
337
+ }
271
338
  }
272
339
  /** Map one database row to the wire view (field names are already snake_case). */
273
340
  function rowToView(row) {
274
- return { ...row };
341
+ return { ...row, inject_enabled: row.inject_enabled === 1 };
342
+ }
343
+ /** Validate the injection delivery mode; omitted or null keeps the default. */
344
+ function validatedMode(mode) {
345
+ if (mode === undefined || mode === null)
346
+ return 'inject';
347
+ if (mode !== 'inject' && mode !== 'visible') {
348
+ throw new TemplateRuleError(`mode must be 'inject' or 'visible' (got ${String(mode)})`);
349
+ }
350
+ return mode;
275
351
  }
@@ -0,0 +1 @@
1
+ export declare function run(argv: readonly string[]): Promise<number>;
@@ -0,0 +1,69 @@
1
+ import { type DataSnapshot } from './model.ts';
2
+ export interface ImportPlan {
3
+ readonly changes: number;
4
+ readonly template_inserts: number;
5
+ readonly template_updates: number;
6
+ readonly category_inserts: number;
7
+ readonly name_conflicts: readonly unknown[];
8
+ readonly summary_sha256: string;
9
+ }
10
+ export interface ImportOptions {
11
+ readonly apply: boolean;
12
+ readonly expectedDbSha256?: string;
13
+ readonly confirmedSummarySha256?: string;
14
+ readonly backupOut?: string;
15
+ readonly maxChanges: number;
16
+ readonly busyTimeoutMs?: number;
17
+ }
18
+ export interface ImportResult {
19
+ readonly applied: boolean;
20
+ readonly backup?: string;
21
+ readonly plan: ImportPlan;
22
+ }
23
+ /** A valid operation blocked by a safety/business gate (CLI exit 1). */
24
+ export declare class ImportBlockedError extends Error {
25
+ constructor(message: string);
26
+ }
27
+ export declare function exportDatabase(dbPath: string, filters?: {
28
+ scope?: 'global' | 'session';
29
+ sessionId?: string;
30
+ }): DataSnapshot;
31
+ /** One search hit row projected for agent consumption. */
32
+ export interface SearchHit {
33
+ readonly id: string;
34
+ readonly name: string;
35
+ readonly content: string;
36
+ readonly scope: 'global' | 'session';
37
+ readonly category: string | null;
38
+ readonly updated_at: string;
39
+ }
40
+ export interface SearchOptions {
41
+ /** Case-insensitive substring over name + content; empty matches everything. */
42
+ readonly query?: string;
43
+ /** Narrow to one category name (any scope partition the category rules allow). */
44
+ readonly category?: string;
45
+ /** Include this session's private templates in addition to all globals. */
46
+ readonly sessionId?: string;
47
+ readonly limit: number;
48
+ }
49
+ export interface SearchResult {
50
+ readonly items: readonly SearchHit[];
51
+ readonly total: number;
52
+ readonly limit: number;
53
+ readonly matched_scopes: readonly ('global' | 'session')[];
54
+ }
55
+ /**
56
+ * Read-only template search for agents. Privacy boundary mirrors the panel:
57
+ * every global template is searchable; session-private rows only when the
58
+ * caller names that session via sessionId. Never searches other sessions.
59
+ */
60
+ export declare function searchTemplates(dbPath: string, options: SearchOptions): SearchResult;
61
+ /**
62
+ * Logical database hash: the canonical schema/categories/templates snapshot,
63
+ * not raw file bytes. This works against a live WAL database on Windows
64
+ * (where the main file may be locked and WAL pages are not in its byte hash)
65
+ * and binds exactly the business data an import may replace.
66
+ */
67
+ export declare function databaseSha256(dbPath: string): string;
68
+ export declare function planImport(dbPath: string, incoming: DataSnapshot): ImportPlan;
69
+ export declare function importDatabase(dbPath: string, incoming: DataSnapshot, options: ImportOptions): Promise<ImportResult>;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,62 @@
1
+ import type { CategoryView, TemplateView } from '../types.ts';
2
+ export declare const SNAPSHOT_SCHEMA_VERSION = 4;
3
+ export interface DataSnapshot {
4
+ readonly schema_version: 4;
5
+ readonly categories: readonly CategoryView[];
6
+ readonly templates: readonly TemplateView[];
7
+ readonly data_sha256: string;
8
+ readonly exported_at?: string;
9
+ readonly source?: string;
10
+ }
11
+ export interface DiffResult {
12
+ readonly identical: boolean;
13
+ readonly templates: {
14
+ readonly left: number;
15
+ readonly right: number;
16
+ readonly only_left: readonly TemplateView[];
17
+ readonly only_right: readonly TemplateView[];
18
+ readonly changed: readonly {
19
+ id: string;
20
+ name: string;
21
+ fields: readonly string[];
22
+ left: TemplateView;
23
+ right: TemplateView;
24
+ }[];
25
+ readonly name_conflicts: readonly {
26
+ name: string;
27
+ left_ids: readonly string[];
28
+ right_ids: readonly string[];
29
+ }[];
30
+ };
31
+ readonly categories: {
32
+ readonly left: number;
33
+ readonly right: number;
34
+ readonly only_left: readonly CategoryView[];
35
+ readonly only_right: readonly CategoryView[];
36
+ };
37
+ }
38
+ export type MergeStrategy = 'newer' | 'keep-base' | 'keep-incoming';
39
+ export interface MergeResult {
40
+ readonly snapshot?: DataSnapshot;
41
+ readonly conflicts: readonly MergeConflict[];
42
+ readonly summary: {
43
+ readonly templates: number;
44
+ readonly categories: number;
45
+ readonly inserted: number;
46
+ readonly incoming_selected: number;
47
+ readonly base_selected: number;
48
+ };
49
+ }
50
+ export interface MergeConflict {
51
+ readonly kind: 'same-time-different-content' | 'invalid-timestamp' | 'same-name-different-id';
52
+ readonly message: string;
53
+ readonly ids: readonly string[];
54
+ }
55
+ export declare function parseSnapshot(value: unknown): DataSnapshot;
56
+ export declare function createSnapshot(categories: readonly CategoryView[], templates: readonly TemplateView[], metadata?: {
57
+ exported_at?: string;
58
+ source?: string;
59
+ }): DataSnapshot;
60
+ export declare function canonicalJson(snapshot: DataSnapshot): string;
61
+ export declare function diffSnapshots(left: DataSnapshot, right: DataSnapshot): DiffResult;
62
+ export declare function mergeSnapshots(base: DataSnapshot, incoming: DataSnapshot, strategy: MergeStrategy, allowNameConflicts?: boolean): MergeResult;
@@ -0,0 +1,34 @@
1
+ import type { TemplateLibraryFace } from './slots.ts';
2
+ import type { PromptTemplateKey } from './locales.ts';
3
+ /** Optional title-row takeover by the host surface: the floating panel
4
+ * turns the row into its drag handle (pointer capture + move + release +
5
+ * double-click-to-reset) and appends its close button. */
6
+ export interface LibraryHeaderProps {
7
+ onPointerDown?: (event: React.PointerEvent<HTMLElement>) => void;
8
+ onPointerMove?: (event: React.PointerEvent<HTMLElement>) => void;
9
+ onPointerUp?: (event: React.PointerEvent<HTMLElement>) => void;
10
+ onDoubleClick?: () => void;
11
+ /** Tooltip for the drag handle (the floating panel's hint copy). */
12
+ hint?: string;
13
+ }
14
+ /** Props of the shared library body. */
15
+ export interface TemplateLibraryProps {
16
+ /** Delivery target for insert/send/interject and the session partition. */
17
+ sessionId: string | null;
18
+ /** The CRUD + delivery verbs (a subset of the panel face). */
19
+ face: TemplateLibraryFace;
20
+ t: (key: PromptTemplateKey) => string;
21
+ /** Title-row drag-handle wiring for the floating panel host. */
22
+ header?: LibraryHeaderProps;
23
+ /** Optional trailing controls in the title row (the floating panel's close button). */
24
+ headerExtra?: React.ReactNode;
25
+ }
26
+ /**
27
+ * The shared template library: toolbar (title + row count), live search,
28
+ * category tabs, the row list with inline edit/create forms, and the
29
+ * footer. Loads everything on mount; the parent decides placement and
30
+ * lifetime (the overlay mounts it only while open, the sidebar tab mounts
31
+ * it for the tab's lifetime).
32
+ * @param props - target session, shared verbs, locale, optional title-row takeover.
33
+ */
34
+ export declare function TemplateLibrary({ sessionId, face, t, header, headerExtra }: TemplateLibraryProps): import("react").JSX.Element;
@@ -4,7 +4,7 @@ import { createPromptPanelStore } from './store.ts';
4
4
  /** Full props of the shell.overlay panel entry. */
5
5
  export type PromptPanelProps = PropsRuntime<'shell.overlay'> & PromptPanelFace & PropsStore<ReturnType<typeof createPromptPanelStore>> & PropsLocale<'promptTemplates'>;
6
6
  /**
7
- * The prompt-templates panel body.
7
+ * The prompt-templates floating panel shell.
8
8
  * @param props - runtime kit, injected face members, store handle, and locale.
9
9
  */
10
10
  export declare function PromptPanel(props: PromptPanelProps): import("react").JSX.Element | null;