@nelsonlongxiang/dsh-prompt-templates 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/evolution-default.md +1 -1
- package/docs/spec-event-inject.md +21 -0
- package/lib/cli/database.js +3 -3
- package/lib/client.js +1 -1
- package/lib/event-inject.js +38 -8
- package/lib/event-store.js +58 -0
- package/lib/index.js +47 -4
- package/lib/lessons.js +453 -0
- package/lib/store.js +23 -4
- package/lib/types/event-inject.d.ts +7 -0
- package/lib/types/event-store.d.ts +32 -0
- package/lib/types/index.d.ts +6 -1
- package/lib/types/lessons.d.ts +192 -0
- package/lib/types/store.d.ts +7 -3
- package/package.json +1 -1
|
@@ -140,6 +140,7 @@ src/
|
|
|
140
140
|
- 提醒之后,下一次相关调用的稳定指纹变了 → `signal: changed`
|
|
141
141
|
- 提醒之后同一模式又出现 → `signal: repeated`,修订号加 1
|
|
142
142
|
- 0.16(schema v8):同时 `repeated_after_reminder` 加 1,即「提醒后仍在重复」的次数。`signal` 在下一次提醒时清空,这个计数不清空,留给以后的观察者读;在 `GET …/event-episodes` 和面板的问题台账里都能看到。
|
|
143
|
+
- 交接(未发布,见 9.4):每问题的提醒次数用完、上次提醒后同一模式又出现、而且仍停在 `notified`(没人处置)时,插件不再沉默,而是发**一次**交接通知,说明已提醒几次、提醒后又重复几次,请把试过的做法和结果交给属主或评审。交接通知不算又一次提醒,不改问题的状态和计数。
|
|
143
144
|
- `applied` / `verified` / `ineffective` / `reverted` / `rejected` / `deferred` / `awaiting_authorization` 只通过审计接口设置,并且必须附证据引用(call id 或会话事件序号)。Agent 的口头自述不是证据。
|
|
144
145
|
- 宿主不能证明模型“读到”了提醒,所以不设 `consumed`;需要时在报告里写 UNKNOWN。
|
|
145
146
|
|
|
@@ -315,3 +316,23 @@ eventInject:
|
|
|
315
316
|
- `src/event-inject.ts`:`tools/result` 观察器与 pre-step 消费者
|
|
316
317
|
- `src/store.ts`:v4 → v5 迁移;`src/index.ts`:配置与审计路由
|
|
317
318
|
- 测试:`tests/event-features.test.ts`、`tests/event-store.test.ts`、`tests/event-host.test.ts`,以及 `tests/dsh-contract.test.ts` 的两条护栏
|
|
319
|
+
|
|
320
|
+
### 9.4 交接通知(未发布,分支 `feat/event-handoff`)
|
|
321
|
+
|
|
322
|
+
**为什么。** 原来每问题最多提醒 `max_per_episode` 次(默认 2)。提醒用完后同一模式再出现,插件只把 `repeated_after_reminder` 加一,然后不再出声:Agent 被告知过「查过仍解不开就交出去」,但属主那边没有任何信号,问题就悬着。依据是 agent-atelier 的设计草案(`docs/design/rsi-transformation-policy.md` 的 T2:自修两次仍复发就停止,交给属主或评审;该草案在分支 `docs/experience-theory-design` 上,尚未合并,不是现行规则)。
|
|
323
|
+
|
|
324
|
+
**什么时候发。** 同时满足:规则启用;问题仍是 `notified`(没被人工处置);`notify_count` 已达 `max_per_episode`;上次提醒之后又有新证据(`evidence_revision > notified_revision`);冷却已过;这个问题从没排过交接。
|
|
325
|
+
|
|
326
|
+
**发什么。** 一条「【工坊·交接|规则 …|证据修订 …】」:已提醒几次、提醒后仍重复几次、示例与证据引用,「插件不再就此提醒」,「请停止就此自行反复修正,把试过的做法和结果交给属主或评审」,以及不授权声明。与提醒同一套措辞约束:不出现 a2a 工具名,赋值不进提示词。按规则配置的模式投递(默认可见,属主在对话里看得到)。
|
|
327
|
+
|
|
328
|
+
**怎么记。**
|
|
329
|
+
|
|
330
|
+
- 走同一个待发记录与对账机制,计入每轮条数和字符预算。去重键是 `<会话>|<问题>|<规则@版本>|handoff`,不带证据修订号:同一问题、同一规则版本只发一次。
|
|
331
|
+
- 未送达时用同一个键重试,达到 `maxAttempts` 标 `failed`;**新证据不会把它标成 `superseded`**,因为后来的重复正是它要报告的事。
|
|
332
|
+
- 交接不调用 `prepare`:问题的 `notify_count`、`notified_revision`、`signal`、冷却和状态都不变。
|
|
333
|
+
- 审计路由 `GET …/event-episodes` 的每个问题多一个 `handoff` 字段:`none` / `due` / `pending` / `sent` / `failed`。`due` 只描述条件已满足;规则关着时不会发。
|
|
334
|
+
- 介入记录里交接单独记成 `event:<规则>:handoff`,和这条规则的普通提醒分开,便于区分「提醒过」和「交接过」。
|
|
335
|
+
|
|
336
|
+
**不做什么。** 不改问题终态(仍只由审计接口加证据设置),不自动起决策卡,不调用其他插件,不改模板;跟随事件提醒总开关和规则开关,默认关。面板问题台账暂不显示这个字段,留给后续。
|
|
337
|
+
|
|
338
|
+
测试:`tests/event-store.test.ts` 的 M04(最后一步从「什么都不发」改为「只发交接,不是第三次提醒」)与两个 T2 用例;`tests/event-host.test.ts` 断言路由带 `handoff`。
|
package/lib/cli/database.js
CHANGED
|
@@ -9,7 +9,7 @@ import { createSnapshot, diffSnapshots } from "./model.js";
|
|
|
9
9
|
* v5 event tables, v6 the stored master switch / evolution enrollment, and
|
|
10
10
|
* v7 the combined migration all hold runtime state that is never exported.
|
|
11
11
|
*/
|
|
12
|
-
const SUPPORTED_DB_VERSIONS = [4, 5, 6, 7, 8, 9, 10];
|
|
12
|
+
const SUPPORTED_DB_VERSIONS = [4, 5, 6, 7, 8, 9, 10, 11];
|
|
13
13
|
/** A valid operation blocked by a safety/business gate (CLI exit 1). */
|
|
14
14
|
export class ImportBlockedError extends Error {
|
|
15
15
|
constructor(message) { super(message); this.name = 'ImportBlockedError'; }
|
|
@@ -21,7 +21,7 @@ export function exportDatabase(dbPath, filters = {}) {
|
|
|
21
21
|
db.exec('PRAGMA query_only=ON');
|
|
22
22
|
const version = Number(db.prepare('PRAGMA user_version').get().user_version);
|
|
23
23
|
if (!SUPPORTED_DB_VERSIONS.includes(version))
|
|
24
|
-
throw new Error(`${path} has schema version ${version}, expected 4 to
|
|
24
|
+
throw new Error(`${path} has schema version ${version}, expected 4 to 11`);
|
|
25
25
|
const clauses = [];
|
|
26
26
|
const args = [];
|
|
27
27
|
if (filters.scope !== undefined) {
|
|
@@ -116,7 +116,7 @@ export async function importDatabase(dbPath, incoming, options) {
|
|
|
116
116
|
db.exec(`PRAGMA busy_timeout=${options.busyTimeoutMs ?? 5000}`);
|
|
117
117
|
const version = Number(db.prepare('PRAGMA user_version').get().user_version);
|
|
118
118
|
if (!SUPPORTED_DB_VERSIONS.includes(version))
|
|
119
|
-
throw new Error(`${path} has schema version ${version}, expected 4 to
|
|
119
|
+
throw new Error(`${path} has schema version ${version}, expected 4 to 11`);
|
|
120
120
|
backupPath = resolve(options.backupOut ?? `${path}.${timestampName()}.bak`);
|
|
121
121
|
mkdirSync(dirname(backupPath), { recursive: true });
|
|
122
122
|
await backup(db, backupPath);
|
package/lib/client.js
CHANGED
|
@@ -346,7 +346,7 @@ window.__ModuleLoader__.load({
|
|
|
346
346
|
/** Canonical public source repository for the panel's metadata link. */
|
|
347
347
|
const GITHUB_REPOSITORY_URL = "https://github.com/NelsonLongXiang/dsh-prompt-templates";
|
|
348
348
|
/** Build-injected package version; `dev` only exists in unbundled unit tests. */
|
|
349
|
-
const PLUGIN_VERSION = "0.
|
|
349
|
+
const PLUGIN_VERSION = "0.18.0";
|
|
350
350
|
/** Header count: current-tab size when idle, matched/searchable when searching. */
|
|
351
351
|
function templateCountLabel(matched, searchable, searching) {
|
|
352
352
|
return searching ? `${matched}/${searchable}` : String(matched);
|
package/lib/event-inject.js
CHANGED
|
@@ -24,7 +24,7 @@ import { contentDigest } from "./interventions.js";
|
|
|
24
24
|
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
25
25
|
import { detect, RULE_REPEATED_PREPARATION } from "./event-detect.js";
|
|
26
26
|
import { extractFeatures } from "./event-features.js";
|
|
27
|
-
import { dedupKeyFor } from "./event-store.js";
|
|
27
|
+
import { dedupKeyFor, handoffKeyFor, isHandoffKey } from "./event-store.js";
|
|
28
28
|
export const DEFAULT_EVENT_INJECT_CONFIG = {
|
|
29
29
|
enabled: false,
|
|
30
30
|
maxPerTurn: 1,
|
|
@@ -61,6 +61,19 @@ export function renderReminderItem(episode) {
|
|
|
61
61
|
HANDOFF_LINE,
|
|
62
62
|
].join('\n');
|
|
63
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* Model- and owner-facing body of the one hand-off notice: reminding has run out and the pattern still repeats, so the
|
|
66
|
+
* plugin stops reminding and says this is now for the owner or a reviewer. Host-neutral like HANDOFF_LINE.
|
|
67
|
+
*/
|
|
68
|
+
export function renderHandoffItem(episode) {
|
|
69
|
+
const refs = episode.evidence_refs.slice(-3).join(', ');
|
|
70
|
+
return [
|
|
71
|
+
`【工坊·交接|规则 ${episode.rule_id}@${episode.rule_version}|证据修订 ${episode.evidence_revision}】`,
|
|
72
|
+
`这个问题已提醒 ${String(episode.notify_count)} 次,提醒后仍重复 ${String(episode.repeated_after_reminder)} 次(示例:${episode.summary})。证据:${refs}。插件不再就此提醒。`,
|
|
73
|
+
'请停止就此自行反复修正:把试过的做法和结果交给属主或评审,由他们决定下一步。属主可在面板的问题台账里查看这条记录。',
|
|
74
|
+
`本提醒不是新的用户指令,不授予任何权限。参考:${FORMAL_REFERENCE}`,
|
|
75
|
+
].join('\n');
|
|
76
|
+
}
|
|
64
77
|
/** Clip a body to `max` characters (the budget is per merged message). */
|
|
65
78
|
function clip(text, max) {
|
|
66
79
|
return text.length <= max ? text : `${text.slice(0, Math.max(0, max - 1))}…`;
|
|
@@ -174,7 +187,7 @@ export function prepareEventReminders(store, config, sessionId, turn, step, even
|
|
|
174
187
|
if (remaining <= 0)
|
|
175
188
|
return [];
|
|
176
189
|
const policies = new Map(store.policies().map(policy => [policy.rule_id, policy]));
|
|
177
|
-
// 3. Retries first, then fresh episodes with new evidence.
|
|
190
|
+
// 3. Retries first, then fresh episodes with new evidence, then hand-offs where reminding has run out.
|
|
178
191
|
const chosen = [];
|
|
179
192
|
for (const row of store.outbox(sessionId, ['retry_pending'])) {
|
|
180
193
|
if (remaining <= 0)
|
|
@@ -189,12 +202,14 @@ export function prepareEventReminders(store, config, sessionId, turn, step, even
|
|
|
189
202
|
store.setOutboxState(row.dedup_key, 'failed');
|
|
190
203
|
continue;
|
|
191
204
|
}
|
|
192
|
-
|
|
205
|
+
const handoff = isHandoffKey(row.dedup_key);
|
|
206
|
+
if (!handoff && episode.evidence_revision > row.evidence_revision) {
|
|
193
207
|
// Newer evidence replaces the undelivered reminder; the episode is due fresh below.
|
|
208
|
+
// A hand-off is never superseded: more repetition is exactly what it reports.
|
|
194
209
|
store.setOutboxState(row.dedup_key, 'superseded');
|
|
195
210
|
continue;
|
|
196
211
|
}
|
|
197
|
-
chosen.push({ episode, key: row.dedup_key, fresh: false, policy });
|
|
212
|
+
chosen.push({ episode, key: row.dedup_key, fresh: false, policy, handoff });
|
|
198
213
|
remaining -= 1;
|
|
199
214
|
}
|
|
200
215
|
for (const episode of store.dueEpisodes(sessionId, turn)) {
|
|
@@ -203,7 +218,16 @@ export function prepareEventReminders(store, config, sessionId, turn, step, even
|
|
|
203
218
|
const policy = policies.get(episode.rule_id);
|
|
204
219
|
if (policy === undefined)
|
|
205
220
|
continue;
|
|
206
|
-
chosen.push({ episode, key: dedupKeyFor(sessionId, episode, episode.evidence_revision), fresh: true, policy });
|
|
221
|
+
chosen.push({ episode, key: dedupKeyFor(sessionId, episode, episode.evidence_revision), fresh: true, policy, handoff: false });
|
|
222
|
+
remaining -= 1;
|
|
223
|
+
}
|
|
224
|
+
for (const episode of store.handoffDue(sessionId, turn)) {
|
|
225
|
+
if (remaining <= 0)
|
|
226
|
+
break;
|
|
227
|
+
const policy = policies.get(episode.rule_id);
|
|
228
|
+
if (policy === undefined)
|
|
229
|
+
continue;
|
|
230
|
+
chosen.push({ episode, key: handoffKeyFor(sessionId, episode), fresh: true, policy, handoff: true });
|
|
207
231
|
remaining -= 1;
|
|
208
232
|
}
|
|
209
233
|
if (chosen.length === 0)
|
|
@@ -212,11 +236,14 @@ export function prepareEventReminders(store, config, sessionId, turn, step, even
|
|
|
212
236
|
const byMode = new Map();
|
|
213
237
|
let used = 0;
|
|
214
238
|
for (const entry of chosen) {
|
|
215
|
-
const body = clip(renderReminderItem(entry.episode), Math.max(0, config.maxChars - used));
|
|
239
|
+
const body = clip(entry.handoff ? renderHandoffItem(entry.episode) : renderReminderItem(entry.episode), Math.max(0, config.maxChars - used));
|
|
216
240
|
if (body.length === 0)
|
|
217
241
|
break;
|
|
218
242
|
used += body.length;
|
|
219
|
-
|
|
243
|
+
if (entry.handoff)
|
|
244
|
+
store.prepareHandoff(sessionId, entry.episode, turn, step, entry.key);
|
|
245
|
+
else
|
|
246
|
+
store.prepare(sessionId, entry.episode, turn, step, entry.fresh, entry.key, entry.policy.cooldown_turns);
|
|
220
247
|
const bucket = byMode.get(entry.policy.mode) ?? { bodies: [], items: [] };
|
|
221
248
|
bucket.bodies.push(body);
|
|
222
249
|
bucket.items.push({
|
|
@@ -224,6 +251,7 @@ export function prepareEventReminders(store, config, sessionId, turn, step, even
|
|
|
224
251
|
episode_id: entry.episode.episode_id,
|
|
225
252
|
rule: `${entry.episode.rule_id}@${entry.episode.rule_version}`,
|
|
226
253
|
evidence_revision: entry.episode.evidence_revision,
|
|
254
|
+
...(entry.handoff ? { phase: 'handoff' } : {}),
|
|
227
255
|
});
|
|
228
256
|
byMode.set(entry.policy.mode, bucket);
|
|
229
257
|
}
|
|
@@ -296,7 +324,9 @@ export function recordEventInterventions(log, sessionId, turn, step, reminders)
|
|
|
296
324
|
const digest = contentDigest(text);
|
|
297
325
|
for (const item of probe.source?.items ?? []) {
|
|
298
326
|
const [ruleId, ruleVersion] = item.rule.split('@');
|
|
299
|
-
|
|
327
|
+
// A hand-off is logged apart from the rule's reminders, so a reader can tell "reminded" from "handed off".
|
|
328
|
+
const suffix = item.phase === 'handoff' ? ':handoff' : '';
|
|
329
|
+
log().record({ session_id: sessionId, source: 'event', method: null, caller: null, template_id: `event:${ruleId ?? item.rule}${suffix}`, template_name: `${ruleId ?? item.rule}${suffix}`,
|
|
300
330
|
template_version: ruleVersion ?? null, content_sha256: digest, turn, step, at });
|
|
301
331
|
}
|
|
302
332
|
}
|
package/lib/event-store.js
CHANGED
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
* prepared again, failed after too many attempts, superseded when newer
|
|
12
12
|
* evidence replaces an undelivered reminder.
|
|
13
13
|
*
|
|
14
|
+
* Once an episode's reminder budget is spent and the pattern still repeats,
|
|
15
|
+
* it gets one hand-off notice (its own outbox row, never superseded) instead
|
|
16
|
+
* of silence; the episode's own state and counts are left as they were.
|
|
17
|
+
*
|
|
14
18
|
* @module dsh-prompt-templates/event-store
|
|
15
19
|
*/
|
|
16
20
|
import { EVENT_RULES, EVIDENCE_REFS_MAX, RULE_REPEATED_FAILURE, RULE_REPEATED_PREPARATION, looksChanged } from "./event-detect.js";
|
|
@@ -142,6 +146,17 @@ export function episodeIdFor(sessionId, ruleId, key) {
|
|
|
142
146
|
export function dedupKeyFor(sessionId, episode, revision) {
|
|
143
147
|
return `${sessionId}|${episode.episode_id}|${revision}|${episode.rule_id}@${episode.rule_version}|notify`;
|
|
144
148
|
}
|
|
149
|
+
/**
|
|
150
|
+
* Idempotence key of the one hand-off notice an episode may get. It carries no evidence revision on purpose: newer
|
|
151
|
+
* evidence neither re-sends nor supersedes it, so an episode gets at most one per rule version.
|
|
152
|
+
*/
|
|
153
|
+
export function handoffKeyFor(sessionId, episode) {
|
|
154
|
+
return `${sessionId}|${episode.episode_id}|${episode.rule_id}@${episode.rule_version}|handoff`;
|
|
155
|
+
}
|
|
156
|
+
/** Whether an outbox row is a hand-off notice rather than a reminder. */
|
|
157
|
+
export function isHandoffKey(dedupKey) {
|
|
158
|
+
return dedupKey.endsWith('|handoff');
|
|
159
|
+
}
|
|
145
160
|
function positiveInt(name, value, max) {
|
|
146
161
|
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > max) {
|
|
147
162
|
throw new EventRuleError(`${name} must be an integer between 1 and ${max}`);
|
|
@@ -288,6 +303,36 @@ export class EventStore {
|
|
|
288
303
|
return policy !== undefined && episode.notify_count < policy.max_per_episode && !pending.has(episode.episode_id);
|
|
289
304
|
});
|
|
290
305
|
}
|
|
306
|
+
/**
|
|
307
|
+
* Episodes due their one hand-off notice at `turn`. Reminding has run out: the policy's per-episode budget is spent,
|
|
308
|
+
* the pattern came back after the last reminder, and the episode is still only `notified` (nobody resolved it). Instead
|
|
309
|
+
* of falling silent, the plugin says once that this is now for the owner or a reviewer. Cooldown applies as for
|
|
310
|
+
* reminders; an episode that ever had a hand-off queued is never due again.
|
|
311
|
+
*/
|
|
312
|
+
handoffDue(sessionId, turn) {
|
|
313
|
+
const enabled = new Map(this.policies().filter(policy => policy.enabled).map(policy => [policy.rule_id, policy]));
|
|
314
|
+
if (enabled.size === 0)
|
|
315
|
+
return [];
|
|
316
|
+
const rows = this.db.prepare(`SELECT * FROM event_episodes WHERE session_id = ? AND state = 'notified'
|
|
317
|
+
AND evidence_revision > notified_revision AND cooldown_until_turn <= ? ORDER BY created_at, episode_id`)
|
|
318
|
+
.all(sessionId, turn);
|
|
319
|
+
return rows.map(episodeView).filter(episode => {
|
|
320
|
+
const policy = enabled.get(episode.rule_id);
|
|
321
|
+
return policy !== undefined && episode.notify_count >= policy.max_per_episode && this.handoffRow(episode) === undefined;
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
/** An episode's hand-off state, for the audit route and its readers. */
|
|
325
|
+
handoffState(episode) {
|
|
326
|
+
const row = this.handoffRow(episode);
|
|
327
|
+
if (row !== undefined)
|
|
328
|
+
return row.state === 'persisted' ? 'sent' : row.state === 'failed' ? 'failed' : 'pending';
|
|
329
|
+
const policy = this.policy(episode.rule_id);
|
|
330
|
+
const exhausted = policy !== undefined && episode.notify_count >= policy.max_per_episode;
|
|
331
|
+
return episode.state === 'notified' && exhausted && episode.evidence_revision > episode.notified_revision ? 'due' : 'none';
|
|
332
|
+
}
|
|
333
|
+
handoffRow(episode) {
|
|
334
|
+
return this.db.prepare('SELECT * FROM event_outbox WHERE dedup_key = ?').get(handoffKeyFor(episode.session_id, episode));
|
|
335
|
+
}
|
|
291
336
|
/** Record a reminder as handed to the step (delivery `prepared`, episode `notified`). */
|
|
292
337
|
prepare(sessionId, episode, turn, step, fresh, dedupKey, cooldownTurns) {
|
|
293
338
|
const at = now();
|
|
@@ -311,6 +356,19 @@ export class EventStore {
|
|
|
311
356
|
throw error;
|
|
312
357
|
}
|
|
313
358
|
}
|
|
359
|
+
/**
|
|
360
|
+
* Record a hand-off notice as handed to the step (delivery `prepared`). The episode is left untouched: a hand-off is
|
|
361
|
+
* not another reminder, so its count, revision, signal and cooldown stay as they were.
|
|
362
|
+
*/
|
|
363
|
+
prepareHandoff(sessionId, episode, turn, step, dedupKey) {
|
|
364
|
+
const at = now();
|
|
365
|
+
this.db.prepare(`INSERT INTO event_outbox
|
|
366
|
+
(dedup_key, session_id, episode_id, evidence_revision, state, attempts, turn, step, created_at, updated_at)
|
|
367
|
+
VALUES (?, ?, ?, ?, 'prepared', 1, ?, ?, ?, ?)
|
|
368
|
+
ON CONFLICT(dedup_key) DO UPDATE SET state = 'prepared', attempts = attempts + 1, turn = excluded.turn,
|
|
369
|
+
step = excluded.step, updated_at = excluded.updated_at`)
|
|
370
|
+
.run(dedupKey, sessionId, episode.episode_id, episode.evidence_revision, turn, step, at, at);
|
|
371
|
+
}
|
|
314
372
|
/** Outbox rows of a session in the given states, oldest first. */
|
|
315
373
|
outbox(sessionId, states) {
|
|
316
374
|
if (states === undefined) {
|
package/lib/index.js
CHANGED
|
@@ -18,12 +18,14 @@
|
|
|
18
18
|
* GET /plugins/dsh-prompt-templates/event-policies → { items }
|
|
19
19
|
* PATCH /plugins/dsh-prompt-templates/event-policies/master → { config }
|
|
20
20
|
* PATCH /plugins/dsh-prompt-templates/event-policies/:rule_id → { policy } | 404
|
|
21
|
-
* GET /plugins/dsh-prompt-templates/event-episodes?session_id=… → { items, outbox }
|
|
21
|
+
* GET /plugins/dsh-prompt-templates/event-episodes?session_id=… → { items, outbox } (each item carries `handoff`)
|
|
22
22
|
* PATCH /plugins/dsh-prompt-templates/event-episodes/:id → { episode } | 404 (evidence_refs required)
|
|
23
23
|
* GET /plugins/dsh-prompt-templates/library[?session_id=] → { items, schema } (read-only card library, v9; with session_id: that session's own templates)
|
|
24
24
|
* POST /plugins/dsh-prompt-templates/library/import → { plan } (versioned pack; dry run unless apply: true)
|
|
25
25
|
* GET /plugins/dsh-prompt-templates/interventions?session_id=&since=&source=&limit= → { items, schema } (read-only, v9)
|
|
26
26
|
* POST /plugins/dsh-prompt-templates/interventions/manual → { intervention } (the panel's insert/send/interject)
|
|
27
|
+
* GET /plugins/dsh-prompt-templates/lessons?session_id= → { items, log, schema } (read-only, v11; no lesson text)
|
|
28
|
+
* PATCH /plugins/dsh-prompt-templates/lessons/:template_id { pinned } → { id, pinned } (the owner pins; phase 2)
|
|
27
29
|
*
|
|
28
30
|
* @module dsh-prompt-templates
|
|
29
31
|
*/
|
|
@@ -35,6 +37,7 @@ import { DEFAULT_INJECT_MAX_EVERY, SCHEMA_VERSION, TemplateRuleError, TemplateSt
|
|
|
35
37
|
import { INTERVENTION_SOURCES, MANUAL_METHODS, contentDigest } from "./interventions.js";
|
|
36
38
|
import { registerCast } from "./cast.js";
|
|
37
39
|
import { registerSelfCheck } from "./self-check.js";
|
|
40
|
+
import { DEFAULT_LESSONS_CONFIG, lessonsOf, pinLesson, registerLessons } from "./lessons.js";
|
|
38
41
|
export const name = 'prompt-templates';
|
|
39
42
|
export const Config = s.object({
|
|
40
43
|
dbPath: s.string(),
|
|
@@ -51,6 +54,15 @@ export const Config = s.object({
|
|
|
51
54
|
}).default({}),
|
|
52
55
|
cast: s.object({ enabled: s.boolean().default(false) }).default({}),
|
|
53
56
|
selfCheck: s.object({ enabled: s.boolean().default(false) }).default({}),
|
|
57
|
+
lessons: s.object({
|
|
58
|
+
enabled: s.boolean().default(DEFAULT_LESSONS_CONFIG.enabled),
|
|
59
|
+
mode: s.union(['inject', 'visible']).default(DEFAULT_LESSONS_CONFIG.mode),
|
|
60
|
+
maxPerSession: s.natural().min(1).max(100).default(DEFAULT_LESSONS_CONFIG.maxPerSession),
|
|
61
|
+
digestCooldownTurns: s.natural().min(1).default(DEFAULT_LESSONS_CONFIG.digestCooldownTurns),
|
|
62
|
+
recallCooldownTurns: s.natural().min(1).default(DEFAULT_LESSONS_CONFIG.recallCooldownTurns),
|
|
63
|
+
maxRecallChars: s.natural().min(40).max(600).default(DEFAULT_LESSONS_CONFIG.maxRecallChars),
|
|
64
|
+
maxPinned: s.natural().min(1).max(10).default(DEFAULT_LESSONS_CONFIG.maxPinned),
|
|
65
|
+
}).default({}),
|
|
54
66
|
});
|
|
55
67
|
/** Web-server service key candidates, newest first. */
|
|
56
68
|
const WEB_SERVER_KEYS = ['webServer', 'httpServer'];
|
|
@@ -87,6 +99,9 @@ export function apply(ctx, config) {
|
|
|
87
99
|
registerCast(ctx, client, () => config.cast?.enabled === true, () => config.selfCheck?.enabled === true);
|
|
88
100
|
// Observer phase 2 (PT-4): the wrap-up self-check, off unless selfCheck.enabled.
|
|
89
101
|
registerSelfCheck(ctx, client, () => config.selfCheck?.enabled === true);
|
|
102
|
+
// 体会 (docs/spec-lesson-inject.md, phase 1): off unless lessons.enabled.
|
|
103
|
+
const lessonsConfig = { ...DEFAULT_LESSONS_CONFIG, ...config.lessons };
|
|
104
|
+
registerLessons(ctx, client, () => lessonsConfig);
|
|
90
105
|
registerEventInject(ctx, eventInjectConfig, () => client().events, () => client().interventions);
|
|
91
106
|
let routesRegistered = false;
|
|
92
107
|
const registerRoutes = () => {
|
|
@@ -99,7 +114,7 @@ export function apply(ctx, config) {
|
|
|
99
114
|
ctx.effect(() => webServer.register({
|
|
100
115
|
kind: 'prefix',
|
|
101
116
|
path: '/plugins/dsh-prompt-templates',
|
|
102
|
-
handler: (req, res) => { void handle(req, res, client, inject.status, inject.history, () => client().events.masterEnabled(eventInjectConfig.enabled)); },
|
|
117
|
+
handler: (req, res) => { void handle(req, res, client, inject.status, inject.history, () => client().events.masterEnabled(eventInjectConfig.enabled), () => lessonsConfig); },
|
|
103
118
|
}), 'prompt-templates: api routes');
|
|
104
119
|
};
|
|
105
120
|
registerRoutes();
|
|
@@ -110,7 +125,7 @@ export function apply(ctx, config) {
|
|
|
110
125
|
});
|
|
111
126
|
}
|
|
112
127
|
/** Dispatch one API request against the template store. */
|
|
113
|
-
async function handle(req, res, client, injectStatus, injectHistory, eventInjectEnabled) {
|
|
128
|
+
async function handle(req, res, client, injectStatus, injectHistory, eventInjectEnabled, lessonsConfig = () => DEFAULT_LESSONS_CONFIG) {
|
|
114
129
|
const url = new URL(req.url ?? '/', 'http://x');
|
|
115
130
|
const segments = url.pathname.split('/').filter(part => part !== '');
|
|
116
131
|
// Route namespace: `/plugins/dsh-prompt-templates/<resource>/...`.
|
|
@@ -172,6 +187,33 @@ async function handle(req, res, client, injectStatus, injectHistory, eventInject
|
|
|
172
187
|
}
|
|
173
188
|
return json(res, 405, errorBody('method-not-allowed', `${method} ${url.pathname}`));
|
|
174
189
|
}
|
|
190
|
+
// 体会 (v11): one session's lessons and what the plugin did, read-only. No lesson text: the panel shows it as templates.
|
|
191
|
+
if (resource === 'lessons') {
|
|
192
|
+
if (rest.length === 0 && method === 'GET') {
|
|
193
|
+
const sessionId = url.searchParams.get('session_id');
|
|
194
|
+
if (sessionId === null || sessionId === '')
|
|
195
|
+
return json(res, 400, errorBody('bad-request', 'missing session_id'));
|
|
196
|
+
const store = client();
|
|
197
|
+
const items = lessonsOf(store, sessionId).map(lesson => {
|
|
198
|
+
const cue = store.lessons.cue(lesson.id);
|
|
199
|
+
return { id: lesson.id, index: lesson.index, version: lesson.version, content_sha256: contentDigest(lesson.content),
|
|
200
|
+
origin: cue?.origin ?? null, pinned: cue?.pinned === 1, recall_count: cue?.recall_count ?? 0, last_recalled_turn: cue?.last_recalled_turn ?? null };
|
|
201
|
+
});
|
|
202
|
+
return json(res, 200, { schema: SCHEMA_VERSION, items, log: store.lessons.log(sessionId, Number(url.searchParams.get('limit') ?? 100)) });
|
|
203
|
+
}
|
|
204
|
+
// Phase 2: the owner pins a lesson; it is loaded at the session's next start, resume or compaction.
|
|
205
|
+
const lessonId = rest[0];
|
|
206
|
+
if (lessonId !== undefined && rest.length === 1 && method === 'PATCH') {
|
|
207
|
+
const body = await readJson(req);
|
|
208
|
+
if (typeof body['pinned'] !== 'boolean')
|
|
209
|
+
return json(res, 400, errorBody('bad-request', 'pinned must be true or false'));
|
|
210
|
+
const result = pinLesson(client(), decodeURIComponent(lessonId), body['pinned'], lessonsConfig().maxPinned);
|
|
211
|
+
if (!result.ok)
|
|
212
|
+
return json(res, result.code === 'not-found' ? 404 : 409, errorBody(result.code, result.error));
|
|
213
|
+
return json(res, 200, { id: result.id, pinned: result.pinned });
|
|
214
|
+
}
|
|
215
|
+
return json(res, 405, errorBody('method-not-allowed', `${method} ${url.pathname}`));
|
|
216
|
+
}
|
|
175
217
|
if (resource === 'interventions') {
|
|
176
218
|
if (rest.length === 0 && method === 'GET') {
|
|
177
219
|
const sessionId = url.searchParams.get('session_id') ?? undefined;
|
|
@@ -243,7 +285,8 @@ async function handle(req, res, client, injectStatus, injectHistory, eventInject
|
|
|
243
285
|
if (sessionId === null || sessionId === '')
|
|
244
286
|
return json(res, 400, errorBody('bad-request', 'missing session_id'));
|
|
245
287
|
const events = client().events;
|
|
246
|
-
|
|
288
|
+
// `handoff`: where the episode stands once reminding has run out (none / due / pending / sent / failed).
|
|
289
|
+
return json(res, 200, { items: events.episodes(sessionId).map(episode => ({ ...episode, handoff: events.handoffState(episode) })), outbox: events.outbox(sessionId) });
|
|
247
290
|
}
|
|
248
291
|
const episodeId = rest[0];
|
|
249
292
|
if (episodeId !== undefined && rest.length === 1 && method === 'PATCH') {
|
package/lib/lessons.js
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 体会 (lessons), phase 1 of docs/spec-lesson-inject.md. After an experience a session writes down one or two sentences
|
|
3
|
+
* (what hurt, what to do first next time); when the session later meets the same situation, the sentence comes back.
|
|
4
|
+
*
|
|
5
|
+
* - Write. When an experience settles — an event episode signalled `changed`, a target that failed later succeeded, or
|
|
6
|
+
* the wrap-up self-check concluded `done` — the next step carries one short digest prompt. `lesson_write` stores the
|
|
7
|
+
* sentence as one of the session's own session templates (category 体会, name 体会·N, never scheduled). The cue it is
|
|
8
|
+
* recalled by is bound by the plugin from the real experience, never taken from the session's arguments.
|
|
9
|
+
* - Read. A later tool result matching a lesson's cue queues it; the next step, before the next model decision,
|
|
10
|
+
* carries it back.
|
|
11
|
+
*
|
|
12
|
+
* Phase 2 adds pinned lessons: the owner pins a few (never the session), and they are loaded once at the first step after
|
|
13
|
+
* the session starts, resumes or is compacted (not after `clear`).
|
|
14
|
+
*
|
|
15
|
+
* Off unless `lessons.enabled`. A lesson is the session's own reference, not an instruction, and grants nothing. The
|
|
16
|
+
* plugin records what it prompted, what was written and what it recalled; it does not track whether the session
|
|
17
|
+
* followed a recalled lesson (the owner checks deliverables instead).
|
|
18
|
+
*
|
|
19
|
+
* @module @nelsonlongxiang/dsh-prompt-templates/lessons
|
|
20
|
+
*/
|
|
21
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
22
|
+
import { extractFeatures } from "./event-features.js";
|
|
23
|
+
import { contentDigest } from "./interventions.js";
|
|
24
|
+
/** Category tab and name prefix of a session's lessons. */
|
|
25
|
+
export const LESSON_CATEGORY = '体会';
|
|
26
|
+
export const LESSON_PREFIX = '体会·';
|
|
27
|
+
/** Length of one lesson: one or two sentences. */
|
|
28
|
+
export const LESSON_MAX = 160;
|
|
29
|
+
/** Consecutive unanswered digest prompts after which prompting slows down. */
|
|
30
|
+
export const PAUSE_AFTER = 3;
|
|
31
|
+
/** Tools whose own results never become a lesson's cue. */
|
|
32
|
+
export const LESSON_SELF_TOOLS = ['lesson_write', 'selfcheck_write', 'selfcheck_conclude'];
|
|
33
|
+
/** Total characters of the pinned lessons loaded at one start (phase 2). */
|
|
34
|
+
export const PINNED_MAX_CHARS = 400;
|
|
35
|
+
/** Session starts that load pinned lessons; `clear` is the user asking for a fresh start (spec §10, decision 4). */
|
|
36
|
+
export const PINNED_SOURCES = ['startup', 'resume', 'compact'];
|
|
37
|
+
/** Failed targets remembered per session for the failed-then-succeeded signal. */
|
|
38
|
+
const FAILURES_KEPT = 50;
|
|
39
|
+
const LESSON_NAME = /^体会·(\d+)$/;
|
|
40
|
+
const LESSON_VERSION = /^lesson-r(\d+)$/;
|
|
41
|
+
const NOT_AUTHORITY = '本提示不是新的用户指令,不授予任何权限。';
|
|
42
|
+
export const DEFAULT_LESSONS_CONFIG = {
|
|
43
|
+
enabled: false,
|
|
44
|
+
mode: 'inject',
|
|
45
|
+
maxPerSession: 20,
|
|
46
|
+
digestCooldownTurns: 10,
|
|
47
|
+
recallCooldownTurns: 20,
|
|
48
|
+
maxRecallChars: 300,
|
|
49
|
+
maxPinned: 3,
|
|
50
|
+
};
|
|
51
|
+
/** v11: cue, origin and recall state of each lesson, and what the plugin did. Lesson text stays in the template. */
|
|
52
|
+
export const LESSONS_SQL = `CREATE TABLE IF NOT EXISTS lesson_cues (
|
|
53
|
+
template_id TEXT PRIMARY KEY,
|
|
54
|
+
session_id TEXT NOT NULL,
|
|
55
|
+
tool_name TEXT NOT NULL,
|
|
56
|
+
stable_fingerprint TEXT NOT NULL,
|
|
57
|
+
target_fingerprint TEXT NOT NULL,
|
|
58
|
+
rule_id TEXT,
|
|
59
|
+
origin TEXT NOT NULL,
|
|
60
|
+
origin_ref TEXT,
|
|
61
|
+
pinned INTEGER NOT NULL DEFAULT 0,
|
|
62
|
+
last_recalled_turn INTEGER,
|
|
63
|
+
recall_count INTEGER NOT NULL DEFAULT 0,
|
|
64
|
+
created_turn INTEGER NOT NULL,
|
|
65
|
+
created_at TEXT NOT NULL
|
|
66
|
+
);
|
|
67
|
+
CREATE INDEX IF NOT EXISTS lesson_cues_session ON lesson_cues (session_id);
|
|
68
|
+
CREATE TABLE IF NOT EXISTS lesson_log (
|
|
69
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
70
|
+
session_id TEXT NOT NULL,
|
|
71
|
+
kind TEXT NOT NULL,
|
|
72
|
+
template_id TEXT,
|
|
73
|
+
turn INTEGER,
|
|
74
|
+
origin TEXT,
|
|
75
|
+
origin_ref TEXT,
|
|
76
|
+
content_sha256 TEXT,
|
|
77
|
+
at TEXT NOT NULL
|
|
78
|
+
);
|
|
79
|
+
CREATE INDEX IF NOT EXISTS lesson_log_session ON lesson_log (session_id, seq)`;
|
|
80
|
+
export function newLessonState() {
|
|
81
|
+
return { failures: new Map(), recall: new Set(), loaded: new Set() };
|
|
82
|
+
}
|
|
83
|
+
/** Durable lesson state over the plugin's SQLite handle. */
|
|
84
|
+
export class LessonStore {
|
|
85
|
+
#db;
|
|
86
|
+
constructor(db) {
|
|
87
|
+
this.#db = db;
|
|
88
|
+
}
|
|
89
|
+
cue(templateId) {
|
|
90
|
+
return this.#db.prepare('SELECT * FROM lesson_cues WHERE template_id = ?').get(templateId);
|
|
91
|
+
}
|
|
92
|
+
/** Cues of the lessons that are still this session's own session templates (a promoted one is not recalled here). */
|
|
93
|
+
cues(sessionId) {
|
|
94
|
+
return this.#db.prepare(`SELECT c.* FROM lesson_cues c JOIN templates t ON t.id = c.template_id
|
|
95
|
+
WHERE c.session_id = ? AND t.scope = 'session' AND t.session_id = c.session_id ORDER BY c.created_at, c.template_id`)
|
|
96
|
+
.all(sessionId);
|
|
97
|
+
}
|
|
98
|
+
addCue(templateId, sessionId, cue, origin, originRef, turn) {
|
|
99
|
+
this.#db.prepare(`INSERT INTO lesson_cues (template_id, session_id, tool_name, stable_fingerprint, target_fingerprint, rule_id,
|
|
100
|
+
origin, origin_ref, created_turn, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
101
|
+
.run(templateId, sessionId, cue.tool_name, cue.stable_fingerprint, cue.target_fingerprint, cue.rule_id, origin, originRef, turn, new Date().toISOString());
|
|
102
|
+
}
|
|
103
|
+
/** Pin or unpin a lesson (the owner's route). Returns false when it has no cue row. */
|
|
104
|
+
setPinned(templateId, pinned) {
|
|
105
|
+
return Number(this.#db.prepare('UPDATE lesson_cues SET pinned = ? WHERE template_id = ?').run(pinned ? 1 : 0, templateId).changes) > 0;
|
|
106
|
+
}
|
|
107
|
+
markRecalled(templateId, turn) {
|
|
108
|
+
this.#db.prepare('UPDATE lesson_cues SET last_recalled_turn = ?, recall_count = recall_count + 1 WHERE template_id = ?').run(turn, templateId);
|
|
109
|
+
}
|
|
110
|
+
record(row) {
|
|
111
|
+
this.#db.prepare(`INSERT INTO lesson_log (session_id, kind, template_id, turn, origin, origin_ref, content_sha256, at)
|
|
112
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
113
|
+
.run(row.session_id, row.kind, row.template_id, row.turn, row.origin, row.origin_ref, row.content_sha256, new Date().toISOString());
|
|
114
|
+
}
|
|
115
|
+
log(sessionId, limit = 100) {
|
|
116
|
+
return this.#db.prepare('SELECT * FROM (SELECT * FROM lesson_log WHERE session_id = ? ORDER BY seq DESC LIMIT ?) ORDER BY seq')
|
|
117
|
+
.all(sessionId, Math.max(1, Math.min(500, Math.trunc(limit))));
|
|
118
|
+
}
|
|
119
|
+
lastPromptTurn(sessionId) {
|
|
120
|
+
const row = this.#db.prepare("SELECT MAX(turn) AS turn FROM lesson_log WHERE session_id = ? AND kind = 'prompted'").get(sessionId);
|
|
121
|
+
return row.turn ?? undefined;
|
|
122
|
+
}
|
|
123
|
+
/** Digest prompts since the session last wrote a lesson. */
|
|
124
|
+
promptsSinceWrite(sessionId) {
|
|
125
|
+
const written = this.#db.prepare("SELECT MAX(seq) AS seq FROM lesson_log WHERE session_id = ? AND kind = 'written'").get(sessionId);
|
|
126
|
+
const row = this.#db.prepare("SELECT COUNT(*) AS n FROM lesson_log WHERE session_id = ? AND kind = 'prompted' AND seq > ?")
|
|
127
|
+
.get(sessionId, written.seq ?? 0);
|
|
128
|
+
return Number(row.n);
|
|
129
|
+
}
|
|
130
|
+
prompted(sessionId, originRef) {
|
|
131
|
+
return this.#db.prepare("SELECT 1 FROM lesson_log WHERE session_id = ? AND kind = 'prompted' AND origin_ref = ? LIMIT 1").get(sessionId, originRef) !== undefined;
|
|
132
|
+
}
|
|
133
|
+
countAt(sessionId, kind, turn) {
|
|
134
|
+
const row = this.#db.prepare('SELECT COUNT(*) AS n FROM lesson_log WHERE session_id = ? AND kind = ? AND turn = ?').get(sessionId, kind, turn);
|
|
135
|
+
return Number(row.n);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** A session's lessons: its own session templates named 体会·N, oldest first. */
|
|
139
|
+
export function lessonsOf(store, sessionId) {
|
|
140
|
+
return store.list('session', sessionId).flatMap(t => {
|
|
141
|
+
const m = LESSON_NAME.exec(t.name);
|
|
142
|
+
return m === null ? [] : [{ id: t.id, index: Number(m[1]), content: t.content, version: t.version ?? null }];
|
|
143
|
+
}).sort((a, b) => a.index - b.index);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Write (or, with `replace`, rewrite) one of the calling session's lessons. A new lesson's cue comes from the experience
|
|
147
|
+
* the last digest prompt followed, else from the session's last observed call; the session cannot name a cue. A lesson
|
|
148
|
+
* the owner edited on the panel is the owner's: the session cannot rewrite it.
|
|
149
|
+
*/
|
|
150
|
+
export function writeLesson(store, state, sessionId, text, replace, config) {
|
|
151
|
+
const body = text.trim();
|
|
152
|
+
if (body === '' || [...body].length > LESSON_MAX) {
|
|
153
|
+
return { ok: false, code: 'length', error: `a lesson is 1..${String(LESSON_MAX)} characters: one or two sentences, what hurt and what to do first next time` };
|
|
154
|
+
}
|
|
155
|
+
const lessons = lessonsOf(store, sessionId);
|
|
156
|
+
if (replace !== undefined && replace !== null) {
|
|
157
|
+
const index = Number(replace);
|
|
158
|
+
const current = Number.isInteger(index) ? lessons.find(lesson => lesson.index === index) : undefined;
|
|
159
|
+
if (current === undefined)
|
|
160
|
+
return { ok: false, code: 'not-found', error: `no lesson ${String(replace)} in this session` };
|
|
161
|
+
const m = current.version === null ? null : LESSON_VERSION.exec(current.version);
|
|
162
|
+
if (m === null || current.version === null)
|
|
163
|
+
return { ok: false, code: 'owner-edited', error: 'the owner edited this lesson on the panel; it is theirs now' };
|
|
164
|
+
const next = `lesson-r${String(Number(m[1]) + 1)}`;
|
|
165
|
+
store.keepVersion(current.id, current.version, `${LESSON_PREFIX}${String(index)}`, current.content, 'lesson');
|
|
166
|
+
store.update(current.id, { content: body, version: next });
|
|
167
|
+
store.lessons.record({ session_id: sessionId, kind: 'written', template_id: current.id, turn: state.turn ?? null, origin: null, origin_ref: null, content_sha256: contentDigest(body) });
|
|
168
|
+
return { ok: true, id: current.id, index, version: next };
|
|
169
|
+
}
|
|
170
|
+
if (lessons.length >= config.maxPerSession) {
|
|
171
|
+
return { ok: false, code: 'full', error: `this session already has ${String(lessons.length)} lessons; rewrite one (replace) or ask the owner to remove some` };
|
|
172
|
+
}
|
|
173
|
+
if (!store.listCategories(sessionId).some(c => c.scope === 'session' && c.session_id === sessionId && c.name === LESSON_CATEGORY)) {
|
|
174
|
+
store.createCategory({ name: LESSON_CATEGORY, scope: 'session', session_id: sessionId });
|
|
175
|
+
}
|
|
176
|
+
const index = lessons.reduce((max, lesson) => Math.max(max, lesson.index), 0) + 1;
|
|
177
|
+
const made = store.create({
|
|
178
|
+
name: `${LESSON_PREFIX}${String(index)}`, content: body, scope: 'session', session_id: sessionId, category: LESSON_CATEGORY,
|
|
179
|
+
description: '会话自己写下的体会:经历之后的一两句话,同类情境下会被唤起',
|
|
180
|
+
});
|
|
181
|
+
store.update(made.id, { content: body, version: 'lesson-r1' });
|
|
182
|
+
const context = state.context;
|
|
183
|
+
const fromLast = state.last === undefined ? undefined : cueOf(state.last.features);
|
|
184
|
+
const cue = context ?? fromLast ?? { tool_name: '', stable_fingerprint: '', target_fingerprint: '', rule_id: null };
|
|
185
|
+
const origin = context?.origin ?? (fromLast === undefined ? 'none' : 'last-call');
|
|
186
|
+
const originRef = context?.origin_ref ?? (fromLast === undefined ? null : state.last?.callId ?? null);
|
|
187
|
+
store.lessons.addCue(made.id, sessionId, cue, origin, originRef, state.turn ?? 0);
|
|
188
|
+
store.lessons.record({ session_id: sessionId, kind: 'written', template_id: made.id, turn: state.turn ?? null, origin, origin_ref: originRef, content_sha256: contentDigest(body) });
|
|
189
|
+
state.context = undefined;
|
|
190
|
+
return { ok: true, id: made.id, index, version: 'lesson-r1' };
|
|
191
|
+
}
|
|
192
|
+
function cueOf(features, ruleId = null) {
|
|
193
|
+
return { tool_name: features.toolName, stable_fingerprint: features.stableFingerprint, target_fingerprint: features.targetFingerprint, rule_id: ruleId };
|
|
194
|
+
}
|
|
195
|
+
/** Whether a call's features fall in a lesson's situation: same tool, and the same preparation or the same target. */
|
|
196
|
+
export function cueMatches(cue, features) {
|
|
197
|
+
if (cue.tool_name === '' || cue.tool_name !== features.toolName)
|
|
198
|
+
return false;
|
|
199
|
+
return (cue.stable_fingerprint !== '' && cue.stable_fingerprint === features.stableFingerprint)
|
|
200
|
+
|| (cue.target_fingerprint !== '' && cue.target_fingerprint === features.targetFingerprint);
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Note one tool result: remember it as the last call, notice a target that failed and now succeeded (a digest
|
|
204
|
+
* signal), and queue every lesson whose cue it matches.
|
|
205
|
+
*/
|
|
206
|
+
export function observeForLessons(store, state, sessionId, callId, features) {
|
|
207
|
+
state.last = { features, callId };
|
|
208
|
+
const target = features.targetFingerprint;
|
|
209
|
+
if (features.outcome.startsWith('error')) {
|
|
210
|
+
state.failures.delete(target);
|
|
211
|
+
state.failures.set(target, callId);
|
|
212
|
+
if (state.failures.size > FAILURES_KEPT)
|
|
213
|
+
state.failures.delete(state.failures.keys().next().value);
|
|
214
|
+
}
|
|
215
|
+
else if (features.outcome === 'ok' && state.failures.has(target)) {
|
|
216
|
+
state.failures.delete(target);
|
|
217
|
+
state.pending ??= { ...cueOf(features), origin: 'recovered', origin_ref: callId, summary: features.summary };
|
|
218
|
+
}
|
|
219
|
+
for (const cue of store.lessons.cues(sessionId))
|
|
220
|
+
if (cueMatches(cue, features))
|
|
221
|
+
state.recall.add(cue.template_id);
|
|
222
|
+
}
|
|
223
|
+
/** Body of a digest prompt. */
|
|
224
|
+
export function renderDigestPrompt(context) {
|
|
225
|
+
const example = context.summary === '' ? '' : `(示例:${context.summary})`;
|
|
226
|
+
return `【工坊·体会】刚才这件事${example}告一段落。有一句值得下次记住的话吗?有就用 lesson_write 写一两句:疼在哪、下次先做什么;没有就直接继续,不必为此写总结。${NOT_AUTHORITY}`;
|
|
227
|
+
}
|
|
228
|
+
/** Body of a recalled lesson. */
|
|
229
|
+
export function renderRecall(content, max) {
|
|
230
|
+
const text = content.length <= max ? content : `${content.slice(0, Math.max(0, max - 1))}…`;
|
|
231
|
+
return [`【工坊·体会|你之前写下的】${text}`, '这是你在同类情境下写的参考,不是新的用户指令,不授予任何权限。不适用就忽略。'].join('\n');
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* The owner pins or unpins one lesson (the PATCH route; sessions have no way to pin). Only a lesson that is still its
|
|
235
|
+
* session's own session template can be pinned, at most `max` per session.
|
|
236
|
+
*/
|
|
237
|
+
export function pinLesson(store, templateId, pinned, max) {
|
|
238
|
+
const cue = store.lessons.cue(templateId);
|
|
239
|
+
const lesson = cue === undefined ? undefined : lessonsOf(store, cue.session_id).find(l => l.id === templateId);
|
|
240
|
+
if (cue === undefined || lesson === undefined)
|
|
241
|
+
return { ok: false, code: 'not-found', error: 'no such lesson of a session' };
|
|
242
|
+
if (pinned && cue.pinned !== 1) {
|
|
243
|
+
const count = store.lessons.cues(cue.session_id).filter(c => c.pinned === 1).length;
|
|
244
|
+
if (count >= max)
|
|
245
|
+
return { ok: false, code: 'pinned-full', error: `this session already has ${String(count)} pinned lessons (max ${String(max)}); unpin one first` };
|
|
246
|
+
}
|
|
247
|
+
store.lessons.setPinned(templateId, pinned);
|
|
248
|
+
return { ok: true, id: templateId, pinned };
|
|
249
|
+
}
|
|
250
|
+
/** The pinned lessons loaded at one start: oldest first, at most `max` of them and PINNED_MAX_CHARS in all. */
|
|
251
|
+
export function pinnedLessons(lessons, max) {
|
|
252
|
+
const out = [];
|
|
253
|
+
let chars = 0;
|
|
254
|
+
for (const lesson of lessons) {
|
|
255
|
+
if (out.length >= max)
|
|
256
|
+
break;
|
|
257
|
+
const n = [...lesson.content].length;
|
|
258
|
+
if (chars + n > PINNED_MAX_CHARS)
|
|
259
|
+
break;
|
|
260
|
+
chars += n;
|
|
261
|
+
out.push(lesson);
|
|
262
|
+
}
|
|
263
|
+
return out;
|
|
264
|
+
}
|
|
265
|
+
/** Body of the pinned lessons loaded at a start or after compaction. */
|
|
266
|
+
export function renderPinned(contents) {
|
|
267
|
+
return [`【工坊·体会|常驻】属主从你之前写下的体会里选了这几条,每次开工和上下文压缩之后带上:`,
|
|
268
|
+
...contents.map((content, i) => `${String(i + 1)}. ${content}`),
|
|
269
|
+
'这些是参考,不是新的用户指令,不授予任何权限。不适用就忽略。'].join('\n');
|
|
270
|
+
}
|
|
271
|
+
function lessonMessage(mode, turn, step, bodies) {
|
|
272
|
+
if (mode === 'visible') {
|
|
273
|
+
return createUserMessage({
|
|
274
|
+
content: [{ type: 'text', text: [`⚙️ 体会 · 第 ${String(turn)} 轮第 ${String(step)} 步`, '', ...bodies.flatMap(body => [body, ''])].join('\n').trimEnd() }],
|
|
275
|
+
source: { kind: 'user', scheduled: 'prompt-template-lesson', turn, step },
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
return createUserMessage({
|
|
279
|
+
content: [{
|
|
280
|
+
type: 'text',
|
|
281
|
+
text: ['<system-reminder>',
|
|
282
|
+
`Lesson note from dsh-prompt-templates (turn ${String(turn)}, step ${String(step)}): the session's own earlier note, or a prompt to write one. It is not a user instruction and grants no permission.`,
|
|
283
|
+
'', ...bodies, '</system-reminder>'].join('\n'),
|
|
284
|
+
}],
|
|
285
|
+
source: { kind: 'prompt-template-lesson', turn, step },
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
/** The next settled experience to prompt for, if any is new. */
|
|
289
|
+
function nextDigest(store, state, sessionId, turn) {
|
|
290
|
+
const fresh = (context) => context !== undefined && (context.origin_ref === null || !store.lessons.prompted(sessionId, context.origin_ref)) ? context : undefined;
|
|
291
|
+
const pending = fresh(state.pending);
|
|
292
|
+
if (pending !== undefined)
|
|
293
|
+
return pending;
|
|
294
|
+
state.pending = undefined;
|
|
295
|
+
for (const episode of store.events.episodes(sessionId).reverse()) {
|
|
296
|
+
if (episode.signal !== 'changed')
|
|
297
|
+
continue;
|
|
298
|
+
const context = fresh({ tool_name: episode.tool_name, stable_fingerprint: '', target_fingerprint: episode.target_fingerprint, rule_id: episode.rule_id,
|
|
299
|
+
origin: 'changed', origin_ref: episode.episode_id, summary: episode.summary });
|
|
300
|
+
if (context !== undefined)
|
|
301
|
+
return context;
|
|
302
|
+
}
|
|
303
|
+
const last = store.selfChecks.list(sessionId, 20).filter(row => row.kind === 'concluded').at(-1);
|
|
304
|
+
if (last !== undefined && last.conclusion === 'done' && last.turn !== null && turn - last.turn <= 1) {
|
|
305
|
+
const features = state.last?.features;
|
|
306
|
+
return fresh({ ...(features === undefined ? { tool_name: '', stable_fingerprint: '', target_fingerprint: '', rule_id: null } : cueOf(features)),
|
|
307
|
+
origin: 'selfcheck-done', origin_ref: `selfcheck:${String(last.seq)}`, summary: '' });
|
|
308
|
+
}
|
|
309
|
+
return undefined;
|
|
310
|
+
}
|
|
311
|
+
function digestAllowed(store, config, sessionId, turn) {
|
|
312
|
+
if (store.lessons.countAt(sessionId, 'prompted', turn) > 0)
|
|
313
|
+
return false;
|
|
314
|
+
const last = store.lessons.lastPromptTurn(sessionId);
|
|
315
|
+
if (last === undefined)
|
|
316
|
+
return true;
|
|
317
|
+
const quiet = store.lessons.promptsSinceWrite(sessionId) >= PAUSE_AFTER ? config.digestCooldownTurns * 3 : config.digestCooldownTurns;
|
|
318
|
+
return turn >= last + quiet;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* This step's lesson messages: at most one digest prompt and one recalled lesson per turn, each with its cooldown.
|
|
322
|
+
* Exported for tests; the host path is the `agent/pre-step` listener below. Delivery is best effort (a rejected step
|
|
323
|
+
* loses it); what was handed over is logged.
|
|
324
|
+
*/
|
|
325
|
+
export function prepareLessonMessages(store, state, config, sessionId, turn, step) {
|
|
326
|
+
state.turn = turn;
|
|
327
|
+
const bodies = [];
|
|
328
|
+
const pinned = new Set(store.lessons.cues(sessionId).filter(cue => cue.pinned === 1).map(cue => cue.template_id));
|
|
329
|
+
if (state.pinnedDue !== undefined) {
|
|
330
|
+
const source = state.pinnedDue;
|
|
331
|
+
state.pinnedDue = undefined;
|
|
332
|
+
const loaded = pinnedLessons(lessonsOf(store, sessionId).filter(lesson => pinned.has(lesson.id)), config.maxPinned);
|
|
333
|
+
state.loaded.clear();
|
|
334
|
+
for (const lesson of loaded)
|
|
335
|
+
state.loaded.add(lesson.id);
|
|
336
|
+
if (loaded.length > 0) {
|
|
337
|
+
const body = renderPinned(loaded.map(lesson => lesson.content));
|
|
338
|
+
bodies.push(body);
|
|
339
|
+
for (const lesson of loaded) {
|
|
340
|
+
store.lessons.record({ session_id: sessionId, kind: 'pinned-loaded', template_id: lesson.id, turn, origin: source, origin_ref: null, content_sha256: contentDigest(lesson.content) });
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
if (digestAllowed(store, config, sessionId, turn)) {
|
|
345
|
+
const context = nextDigest(store, state, sessionId, turn);
|
|
346
|
+
if (context !== undefined) {
|
|
347
|
+
const body = renderDigestPrompt(context);
|
|
348
|
+
bodies.push(body);
|
|
349
|
+
state.context = context;
|
|
350
|
+
if (state.pending === context)
|
|
351
|
+
state.pending = undefined;
|
|
352
|
+
store.lessons.record({ session_id: sessionId, kind: 'prompted', template_id: null, turn, origin: context.origin, origin_ref: context.origin_ref, content_sha256: contentDigest(body) });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (state.recall.size > 0 && store.lessons.countAt(sessionId, 'recalled', turn) === 0) {
|
|
356
|
+
const lessons = new Map(lessonsOf(store, sessionId).map(lesson => [lesson.id, lesson]));
|
|
357
|
+
for (const id of state.recall) {
|
|
358
|
+
const cue = store.lessons.cue(id);
|
|
359
|
+
const lesson = lessons.get(id);
|
|
360
|
+
// A pinned lesson loaded at the last start or compaction is already in the context.
|
|
361
|
+
if (cue === undefined || lesson === undefined || (pinned.has(id) && state.loaded.has(id)))
|
|
362
|
+
continue;
|
|
363
|
+
if (turn < (cue.last_recalled_turn ?? cue.created_turn) + config.recallCooldownTurns)
|
|
364
|
+
continue;
|
|
365
|
+
const body = renderRecall(lesson.content, config.maxRecallChars);
|
|
366
|
+
bodies.push(body);
|
|
367
|
+
store.lessons.markRecalled(id, turn);
|
|
368
|
+
store.lessons.record({ session_id: sessionId, kind: 'recalled', template_id: id, turn, origin: cue.origin, origin_ref: cue.origin_ref, content_sha256: contentDigest(body) });
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
state.recall.clear();
|
|
372
|
+
}
|
|
373
|
+
return bodies.length === 0 ? [] : [lessonMessage(config.mode, turn, step, bodies)];
|
|
374
|
+
}
|
|
375
|
+
/** Register the observer, the step consumer and `lesson_write`. All of it is inert unless `config().enabled`. */
|
|
376
|
+
export function registerLessons(ctx, store, config) {
|
|
377
|
+
const sessions = new Map();
|
|
378
|
+
const stateOf = (id) => { let s = sessions.get(id); if (s === undefined) {
|
|
379
|
+
s = newLessonState();
|
|
380
|
+
sessions.set(id, s);
|
|
381
|
+
} return s; };
|
|
382
|
+
let faultReported = false;
|
|
383
|
+
const fault = (label, error) => {
|
|
384
|
+
if (!faultReported) {
|
|
385
|
+
faultReported = true;
|
|
386
|
+
console.error(`[dsh-prompt-templates] lessons ${label}; further faults stay silent:`, error);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
ctx.on('tools/result', (exec, result) => {
|
|
390
|
+
try {
|
|
391
|
+
if (!config().enabled)
|
|
392
|
+
return;
|
|
393
|
+
const e = exec;
|
|
394
|
+
const name = String(e.name ?? '');
|
|
395
|
+
if (LESSON_SELF_TOOLS.includes(name))
|
|
396
|
+
return;
|
|
397
|
+
const sessionId = e.agent?.session.header.id;
|
|
398
|
+
if (sessionId === undefined || sessionId === null)
|
|
399
|
+
return;
|
|
400
|
+
observeForLessons(store(), stateOf(String(sessionId)), String(sessionId), String(e.callId ?? ''), extractFeatures(name, e.arguments, result));
|
|
401
|
+
}
|
|
402
|
+
catch (error) {
|
|
403
|
+
fault('skipped a tool result', error);
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
// Phase 2: a start, resume or compaction makes the next step load the pinned lessons; `clear` does not.
|
|
407
|
+
ctx.on('agent/created', ({ agent, source }) => {
|
|
408
|
+
try {
|
|
409
|
+
if (!config().enabled || !PINNED_SOURCES.includes(source))
|
|
410
|
+
return undefined;
|
|
411
|
+
stateOf(String(agent.session.header.id)).pinnedDue = source;
|
|
412
|
+
}
|
|
413
|
+
catch (error) {
|
|
414
|
+
fault('skipped a session start', error);
|
|
415
|
+
}
|
|
416
|
+
return undefined;
|
|
417
|
+
});
|
|
418
|
+
ctx.on('agent/pre-step', async ({ agent, turn, step, signal }, next) => {
|
|
419
|
+
const decision = await next();
|
|
420
|
+
if (decision.kind === 'reject' || signal.aborted)
|
|
421
|
+
return decision;
|
|
422
|
+
try {
|
|
423
|
+
if (!config().enabled)
|
|
424
|
+
return decision;
|
|
425
|
+
const sessionId = String(agent.session.header.id);
|
|
426
|
+
const messages = prepareLessonMessages(store(), stateOf(sessionId), config(), sessionId, turn, step);
|
|
427
|
+
return messages.length === 0 ? decision : { ...decision, messages: [...decision.messages, ...messages] };
|
|
428
|
+
}
|
|
429
|
+
catch (error) {
|
|
430
|
+
fault('skipped this step', error);
|
|
431
|
+
return decision;
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
const tools = ctx.get('tools');
|
|
435
|
+
if (typeof tools?.register === 'function') {
|
|
436
|
+
tools.register({
|
|
437
|
+
name: 'lesson_write',
|
|
438
|
+
description: 'Write down a lesson for your own session: one or two sentences (at most 160 characters) about an experience that just settled — what hurt or surprised you, and what to do first next time. The plugin links it to the situation it came from and brings it back when you meet that situation again. To rewrite one of your lessons, pass its number as replace. Write judgement, not authority; no secrets, tokens, internal addresses or local paths. No owner confirmation is needed; a lesson the owner edited is theirs. Acts only on the calling session.',
|
|
439
|
+
parameters: {
|
|
440
|
+
text: { type: 'string', required: true, description: 'The lesson, 1..160 characters.' },
|
|
441
|
+
replace: { type: 'number', description: 'Optional: the number N of your lesson 体会·N to rewrite.' },
|
|
442
|
+
},
|
|
443
|
+
execute: async (args, exec) => {
|
|
444
|
+
if (!config().enabled)
|
|
445
|
+
return { ok: false, code: 'disabled', error: 'lessons are off on this host' };
|
|
446
|
+
const sessionId = exec.agent?.session.header.id;
|
|
447
|
+
if (sessionId === undefined || sessionId === null)
|
|
448
|
+
return { ok: false, code: 'session', error: 'no calling session' };
|
|
449
|
+
return writeLesson(store(), stateOf(String(sessionId)), String(sessionId), String(args.text ?? ''), args.replace, config());
|
|
450
|
+
},
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
}
|
package/lib/store.js
CHANGED
|
@@ -24,6 +24,7 @@ import { DatabaseSync } from 'node:sqlite';
|
|
|
24
24
|
import { EVENT_MASTER_SQL, EVENT_REPEAT_AFTER_SQL, EVENT_SCHEMA_SQL, EventStore, seedDefaultPolicies } from "./event-store.js";
|
|
25
25
|
import { INTERVENTIONS_SQL, InterventionLog, contentDigest } from "./interventions.js";
|
|
26
26
|
import { SELF_CHECK_SQL, SelfCheckLog } from "./self-check.js";
|
|
27
|
+
import { LESSONS_SQL, LessonStore } from "./lessons.js";
|
|
27
28
|
/** v9: the version label of a template's text. */
|
|
28
29
|
const TEMPLATE_VERSION_SQL = 'ALTER TABLE templates ADD COLUMN version TEXT';
|
|
29
30
|
/** v9: versions stored beside a card's active text (library packs); the active pointer is `templates.version`. */
|
|
@@ -44,9 +45,10 @@ const TEMPLATE_VERSIONS_SQL = `CREATE TABLE IF NOT EXISTS template_versions (
|
|
|
44
45
|
* v7 combines both migrations into one schema version,
|
|
45
46
|
* v8 adds `event_episodes.repeated_after_reminder` (提醒后仍在重复, 0.16),
|
|
46
47
|
* v9 adds `templates.version` and the durable `interventions` log (observer phase 1, 0.16),
|
|
47
|
-
* v10 adds the wrap-up `self_check_log` (observer phase 2, PT-4)
|
|
48
|
+
* v10 adds the wrap-up `self_check_log` (observer phase 2, PT-4),
|
|
49
|
+
* v11 adds `lesson_cues` and `lesson_log` (体会, docs/spec-lesson-inject.md).
|
|
48
50
|
*/
|
|
49
|
-
export const SCHEMA_VERSION =
|
|
51
|
+
export const SCHEMA_VERSION = 11;
|
|
50
52
|
/** Upper bound of the inject interval when the deployment config omits one. */
|
|
51
53
|
export const DEFAULT_INJECT_MAX_EVERY = 1000;
|
|
52
54
|
const NAME_MAX = 128;
|
|
@@ -91,6 +93,8 @@ export class TemplateStore {
|
|
|
91
93
|
interventions;
|
|
92
94
|
/** The wrap-up self-check log (v10). */
|
|
93
95
|
selfChecks;
|
|
96
|
+
/** Lesson cues and log (v11). */
|
|
97
|
+
lessons;
|
|
94
98
|
constructor(dbPath, options = {}) {
|
|
95
99
|
this.#injectMaxEvery = options.injectMaxEvery ?? DEFAULT_INJECT_MAX_EVERY;
|
|
96
100
|
if (dbPath !== ':memory:') {
|
|
@@ -118,6 +122,7 @@ export class TemplateStore {
|
|
|
118
122
|
this.db.exec(TEMPLATE_VERSIONS_SQL);
|
|
119
123
|
this.db.exec(INTERVENTIONS_SQL);
|
|
120
124
|
this.db.exec(SELF_CHECK_SQL);
|
|
125
|
+
this.db.exec(LESSONS_SQL);
|
|
121
126
|
seedDefaultPolicies(this.db);
|
|
122
127
|
this.db.exec(`PRAGMA user_version=${SCHEMA_VERSION}`);
|
|
123
128
|
}
|
|
@@ -152,6 +157,8 @@ export class TemplateStore {
|
|
|
152
157
|
}
|
|
153
158
|
if (onDisk <= 9)
|
|
154
159
|
this.db.exec(SELF_CHECK_SQL);
|
|
160
|
+
if (onDisk <= 10)
|
|
161
|
+
this.db.exec(LESSONS_SQL);
|
|
155
162
|
this.db.exec(`PRAGMA user_version=${SCHEMA_VERSION}`);
|
|
156
163
|
}
|
|
157
164
|
else if (onDisk !== SCHEMA_VERSION) {
|
|
@@ -167,6 +174,7 @@ export class TemplateStore {
|
|
|
167
174
|
this.events = new EventStore(this.db);
|
|
168
175
|
this.interventions = new InterventionLog(this.db);
|
|
169
176
|
this.selfChecks = new SelfCheckLog(this.db);
|
|
177
|
+
this.lessons = new LessonStore(this.db);
|
|
170
178
|
}
|
|
171
179
|
catch (error) {
|
|
172
180
|
// A failed constructor has no owner to close it later. Preserve the
|
|
@@ -441,9 +449,20 @@ export class TemplateStore {
|
|
|
441
449
|
this.db.prepare("UPDATE templates SET scope = 'global', session_id = NULL, updated_at = ? WHERE id = ?").run(updated, id);
|
|
442
450
|
return rowToView({ ...row, scope: 'global', session_id: null, updated_at: updated });
|
|
443
451
|
}
|
|
444
|
-
/** Delete one template; `false` when absent. */
|
|
452
|
+
/** Delete one template; `false` when absent. A lesson's cue row goes with it (v11). */
|
|
445
453
|
delete(id) {
|
|
446
|
-
|
|
454
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
455
|
+
try {
|
|
456
|
+
const deleted = this.db.prepare('DELETE FROM templates WHERE id = ?').run(id).changes > 0;
|
|
457
|
+
if (deleted)
|
|
458
|
+
this.db.prepare('DELETE FROM lesson_cues WHERE template_id = ?').run(id);
|
|
459
|
+
this.db.exec('COMMIT');
|
|
460
|
+
return deleted;
|
|
461
|
+
}
|
|
462
|
+
catch (error) {
|
|
463
|
+
this.db.exec('ROLLBACK');
|
|
464
|
+
throw error;
|
|
465
|
+
}
|
|
447
466
|
}
|
|
448
467
|
/** List user categories: global ones plus one session's, ordered by name. */
|
|
449
468
|
listCategories(sessionId) {
|
|
@@ -33,6 +33,8 @@ export interface EventReminderItem {
|
|
|
33
33
|
readonly episode_id: string;
|
|
34
34
|
readonly rule: string;
|
|
35
35
|
readonly evidence_revision: number;
|
|
36
|
+
/** Present only on the one hand-off notice an episode may get (reminding has run out). */
|
|
37
|
+
readonly phase?: 'handoff';
|
|
36
38
|
}
|
|
37
39
|
/** Durable provenance of a silent event reminder. */
|
|
38
40
|
export interface TemplateEventSource {
|
|
@@ -77,6 +79,11 @@ export declare const DEFAULT_EVENT_INJECT_CONFIG: EventInjectConfig;
|
|
|
77
79
|
export declare const HANDOFF_LINE = "\u6309\u63D0\u9192\u67E5\u8FC7\u4ECD\u89E3\u4E0D\u5F00\u7684\uFF0C\u6309\u6240\u5728\u73AF\u5883\u7684\u4E0A\u62A5\u65B9\u5F0F\u4EA4\u51FA\u53BB\uFF0C\u5199\u6E05\u5DF2\u67E5\u5904\u3001\u7F3A\u7684\u90A3\u4E00\u53E5\u80CC\u666F\u3002";
|
|
78
80
|
/** Model-facing body of one reminder item. */
|
|
79
81
|
export declare function renderReminderItem(episode: Pick<EpisodeView, 'rule_id' | 'rule_version' | 'summary' | 'outcome' | 'evidence_refs' | 'evidence_revision'>): string;
|
|
82
|
+
/**
|
|
83
|
+
* Model- and owner-facing body of the one hand-off notice: reminding has run out and the pattern still repeats, so the
|
|
84
|
+
* plugin stops reminding and says this is now for the owner or a reviewer. Host-neutral like HANDOFF_LINE.
|
|
85
|
+
*/
|
|
86
|
+
export declare function renderHandoffItem(episode: Pick<EpisodeView, 'rule_id' | 'rule_version' | 'summary' | 'evidence_refs' | 'evidence_revision' | 'notify_count' | 'repeated_after_reminder'>): string;
|
|
80
87
|
/** Render one merged reminder message for the items of one delivery mode. */
|
|
81
88
|
export declare function renderEventReminder(turn: number, step: number, mode: TemplateInjectMode, bodies: readonly string[], items: readonly EventReminderItem[]): UserMessage;
|
|
82
89
|
/**
|
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
* prepared again, failed after too many attempts, superseded when newer
|
|
12
12
|
* evidence replaces an undelivered reminder.
|
|
13
13
|
*
|
|
14
|
+
* Once an episode's reminder budget is spent and the pattern still repeats,
|
|
15
|
+
* it gets one hand-off notice (its own outbox row, never superseded) instead
|
|
16
|
+
* of silence; the episode's own state and counts are left as they were.
|
|
17
|
+
*
|
|
14
18
|
* @module dsh-prompt-templates/event-store
|
|
15
19
|
*/
|
|
16
20
|
import type { DatabaseSync } from 'node:sqlite';
|
|
@@ -105,6 +109,19 @@ export declare class EventRuleError extends Error {
|
|
|
105
109
|
export declare function episodeIdFor(sessionId: string, ruleId: EventRuleId, key: string): string;
|
|
106
110
|
/** Idempotence key of one reminder delivery. */
|
|
107
111
|
export declare function dedupKeyFor(sessionId: string, episode: Pick<EpisodeView, 'episode_id' | 'rule_id' | 'rule_version'>, revision: number): string;
|
|
112
|
+
/**
|
|
113
|
+
* Idempotence key of the one hand-off notice an episode may get. It carries no evidence revision on purpose: newer
|
|
114
|
+
* evidence neither re-sends nor supersedes it, so an episode gets at most one per rule version.
|
|
115
|
+
*/
|
|
116
|
+
export declare function handoffKeyFor(sessionId: string, episode: Pick<EpisodeView, 'episode_id' | 'rule_id' | 'rule_version'>): string;
|
|
117
|
+
/** Whether an outbox row is a hand-off notice rather than a reminder. */
|
|
118
|
+
export declare function isHandoffKey(dedupKey: string): boolean;
|
|
119
|
+
/**
|
|
120
|
+
* Where an episode stands on hand-off: `due` once the per-episode reminder budget is spent and the pattern came back
|
|
121
|
+
* after the last reminder while nobody resolved it; `pending` while the notice awaits reconciliation; `sent` once it is
|
|
122
|
+
* in the durable log; `failed` after too many attempts.
|
|
123
|
+
*/
|
|
124
|
+
export type HandoffState = 'none' | 'due' | 'pending' | 'sent' | 'failed';
|
|
108
125
|
/** Event-reminder persistence over the plugin's SQLite handle. */
|
|
109
126
|
export declare class EventStore {
|
|
110
127
|
private readonly db;
|
|
@@ -145,8 +162,23 @@ export declare class EventStore {
|
|
|
145
162
|
* budget left, and no undelivered reminder already pending.
|
|
146
163
|
*/
|
|
147
164
|
dueEpisodes(sessionId: string, turn: number): EpisodeView[];
|
|
165
|
+
/**
|
|
166
|
+
* Episodes due their one hand-off notice at `turn`. Reminding has run out: the policy's per-episode budget is spent,
|
|
167
|
+
* the pattern came back after the last reminder, and the episode is still only `notified` (nobody resolved it). Instead
|
|
168
|
+
* of falling silent, the plugin says once that this is now for the owner or a reviewer. Cooldown applies as for
|
|
169
|
+
* reminders; an episode that ever had a hand-off queued is never due again.
|
|
170
|
+
*/
|
|
171
|
+
handoffDue(sessionId: string, turn: number): EpisodeView[];
|
|
172
|
+
/** An episode's hand-off state, for the audit route and its readers. */
|
|
173
|
+
handoffState(episode: EpisodeView): HandoffState;
|
|
174
|
+
private handoffRow;
|
|
148
175
|
/** Record a reminder as handed to the step (delivery `prepared`, episode `notified`). */
|
|
149
176
|
prepare(sessionId: string, episode: EpisodeView, turn: number, step: number, fresh: boolean, dedupKey: string, cooldownTurns: number): void;
|
|
177
|
+
/**
|
|
178
|
+
* Record a hand-off notice as handed to the step (delivery `prepared`). The episode is left untouched: a hand-off is
|
|
179
|
+
* not another reminder, so its count, revision, signal and cooldown stay as they were.
|
|
180
|
+
*/
|
|
181
|
+
prepareHandoff(sessionId: string, episode: EpisodeView, turn: number, step: number, dedupKey: string): void;
|
|
150
182
|
/** Outbox rows of a session in the given states, oldest first. */
|
|
151
183
|
outbox(sessionId: string, states?: readonly OutboxState[]): OutboxView[];
|
|
152
184
|
/** Whether a session has any reminder awaiting reconciliation. */
|
package/lib/types/index.d.ts
CHANGED
|
@@ -18,18 +18,21 @@
|
|
|
18
18
|
* GET /plugins/dsh-prompt-templates/event-policies → { items }
|
|
19
19
|
* PATCH /plugins/dsh-prompt-templates/event-policies/master → { config }
|
|
20
20
|
* PATCH /plugins/dsh-prompt-templates/event-policies/:rule_id → { policy } | 404
|
|
21
|
-
* GET /plugins/dsh-prompt-templates/event-episodes?session_id=… → { items, outbox }
|
|
21
|
+
* GET /plugins/dsh-prompt-templates/event-episodes?session_id=… → { items, outbox } (each item carries `handoff`)
|
|
22
22
|
* PATCH /plugins/dsh-prompt-templates/event-episodes/:id → { episode } | 404 (evidence_refs required)
|
|
23
23
|
* GET /plugins/dsh-prompt-templates/library[?session_id=] → { items, schema } (read-only card library, v9; with session_id: that session's own templates)
|
|
24
24
|
* POST /plugins/dsh-prompt-templates/library/import → { plan } (versioned pack; dry run unless apply: true)
|
|
25
25
|
* GET /plugins/dsh-prompt-templates/interventions?session_id=&since=&source=&limit= → { items, schema } (read-only, v9)
|
|
26
26
|
* POST /plugins/dsh-prompt-templates/interventions/manual → { intervention } (the panel's insert/send/interject)
|
|
27
|
+
* GET /plugins/dsh-prompt-templates/lessons?session_id= → { items, log, schema } (read-only, v11; no lesson text)
|
|
28
|
+
* PATCH /plugins/dsh-prompt-templates/lessons/:template_id { pinned } → { id, pinned } (the owner pins; phase 2)
|
|
27
29
|
*
|
|
28
30
|
* @module dsh-prompt-templates
|
|
29
31
|
*/
|
|
30
32
|
import type { Context } from '@deepseek-ai/cordis';
|
|
31
33
|
import s from '@deepseek-ai/schemastery';
|
|
32
34
|
import { type PromptTemplatesService } from './cast.ts';
|
|
35
|
+
import { type LessonsConfig } from './lessons.ts';
|
|
33
36
|
declare module '@deepseek-ai/cordis' {
|
|
34
37
|
interface Context {
|
|
35
38
|
/** dsh-prompt-templates' service for other plugins (observer phase 2). */
|
|
@@ -65,6 +68,8 @@ export interface Config {
|
|
|
65
68
|
readonly selfCheck?: {
|
|
66
69
|
readonly enabled?: boolean;
|
|
67
70
|
};
|
|
71
|
+
/** 体会 (docs/spec-lesson-inject.md): digest prompts, lesson_write and situational recall; off by default. */
|
|
72
|
+
readonly lessons?: Partial<LessonsConfig>;
|
|
68
73
|
}
|
|
69
74
|
export declare const Config: s<Config>;
|
|
70
75
|
/** Business error envelope shared with the browser face. */
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 体会 (lessons), phase 1 of docs/spec-lesson-inject.md. After an experience a session writes down one or two sentences
|
|
3
|
+
* (what hurt, what to do first next time); when the session later meets the same situation, the sentence comes back.
|
|
4
|
+
*
|
|
5
|
+
* - Write. When an experience settles — an event episode signalled `changed`, a target that failed later succeeded, or
|
|
6
|
+
* the wrap-up self-check concluded `done` — the next step carries one short digest prompt. `lesson_write` stores the
|
|
7
|
+
* sentence as one of the session's own session templates (category 体会, name 体会·N, never scheduled). The cue it is
|
|
8
|
+
* recalled by is bound by the plugin from the real experience, never taken from the session's arguments.
|
|
9
|
+
* - Read. A later tool result matching a lesson's cue queues it; the next step, before the next model decision,
|
|
10
|
+
* carries it back.
|
|
11
|
+
*
|
|
12
|
+
* Phase 2 adds pinned lessons: the owner pins a few (never the session), and they are loaded once at the first step after
|
|
13
|
+
* the session starts, resumes or is compacted (not after `clear`).
|
|
14
|
+
*
|
|
15
|
+
* Off unless `lessons.enabled`. A lesson is the session's own reference, not an instruction, and grants nothing. The
|
|
16
|
+
* plugin records what it prompted, what was written and what it recalled; it does not track whether the session
|
|
17
|
+
* followed a recalled lesson (the owner checks deliverables instead).
|
|
18
|
+
*
|
|
19
|
+
* @module @nelsonlongxiang/dsh-prompt-templates/lessons
|
|
20
|
+
*/
|
|
21
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
22
|
+
import type { UserMessage } from '@deepseek-ai/dsh-session';
|
|
23
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
24
|
+
import type { ObservationFeatures } from './event-features.ts';
|
|
25
|
+
import type { TemplateStore } from './store.ts';
|
|
26
|
+
/** Category tab and name prefix of a session's lessons. */
|
|
27
|
+
export declare const LESSON_CATEGORY = "\u4F53\u4F1A";
|
|
28
|
+
export declare const LESSON_PREFIX = "\u4F53\u4F1A\u00B7";
|
|
29
|
+
/** Length of one lesson: one or two sentences. */
|
|
30
|
+
export declare const LESSON_MAX = 160;
|
|
31
|
+
/** Consecutive unanswered digest prompts after which prompting slows down. */
|
|
32
|
+
export declare const PAUSE_AFTER = 3;
|
|
33
|
+
/** Tools whose own results never become a lesson's cue. */
|
|
34
|
+
export declare const LESSON_SELF_TOOLS: readonly string[];
|
|
35
|
+
/** Total characters of the pinned lessons loaded at one start (phase 2). */
|
|
36
|
+
export declare const PINNED_MAX_CHARS = 400;
|
|
37
|
+
/** Session starts that load pinned lessons; `clear` is the user asking for a fresh start (spec §10, decision 4). */
|
|
38
|
+
export declare const PINNED_SOURCES: readonly string[];
|
|
39
|
+
/** Deployment switches and budgets (`lessons` in the plugin config). */
|
|
40
|
+
export interface LessonsConfig {
|
|
41
|
+
readonly enabled: boolean;
|
|
42
|
+
readonly mode: 'inject' | 'visible';
|
|
43
|
+
readonly maxPerSession: number;
|
|
44
|
+
readonly digestCooldownTurns: number;
|
|
45
|
+
readonly recallCooldownTurns: number;
|
|
46
|
+
readonly maxRecallChars: number;
|
|
47
|
+
/** Pinned lessons per session (phase 2); only the owner pins. */
|
|
48
|
+
readonly maxPinned: number;
|
|
49
|
+
}
|
|
50
|
+
export declare const DEFAULT_LESSONS_CONFIG: LessonsConfig;
|
|
51
|
+
/** v11: cue, origin and recall state of each lesson, and what the plugin did. Lesson text stays in the template. */
|
|
52
|
+
export declare const LESSONS_SQL = "CREATE TABLE IF NOT EXISTS lesson_cues (\n template_id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n tool_name TEXT NOT NULL,\n stable_fingerprint TEXT NOT NULL,\n target_fingerprint TEXT NOT NULL,\n rule_id TEXT,\n origin TEXT NOT NULL,\n origin_ref TEXT,\n pinned INTEGER NOT NULL DEFAULT 0,\n last_recalled_turn INTEGER,\n recall_count INTEGER NOT NULL DEFAULT 0,\n created_turn INTEGER NOT NULL,\n created_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS lesson_cues_session ON lesson_cues (session_id);\nCREATE TABLE IF NOT EXISTS lesson_log (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n kind TEXT NOT NULL,\n template_id TEXT,\n turn INTEGER,\n origin TEXT,\n origin_ref TEXT,\n content_sha256 TEXT,\n at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS lesson_log_session ON lesson_log (session_id, seq)";
|
|
53
|
+
/** Where a lesson came from: the experience the digest prompt followed, or the last call when there was none. */
|
|
54
|
+
export type LessonOrigin = 'changed' | 'recovered' | 'selfcheck-done' | 'last-call' | 'none';
|
|
55
|
+
/** The situation a lesson is recalled in. */
|
|
56
|
+
export interface CueFeatures {
|
|
57
|
+
readonly tool_name: string;
|
|
58
|
+
readonly stable_fingerprint: string;
|
|
59
|
+
readonly target_fingerprint: string;
|
|
60
|
+
readonly rule_id: string | null;
|
|
61
|
+
}
|
|
62
|
+
/** One settled experience a digest prompt follows; bound to the lesson written in answer. */
|
|
63
|
+
export interface DigestContext extends CueFeatures {
|
|
64
|
+
readonly origin: Exclude<LessonOrigin, 'none'>;
|
|
65
|
+
readonly origin_ref: string | null;
|
|
66
|
+
/** Redacted example shown in the prompt; empty when there is none. */
|
|
67
|
+
readonly summary: string;
|
|
68
|
+
}
|
|
69
|
+
export interface CueRow extends CueFeatures {
|
|
70
|
+
readonly template_id: string;
|
|
71
|
+
readonly session_id: string;
|
|
72
|
+
readonly origin: LessonOrigin;
|
|
73
|
+
readonly origin_ref: string | null;
|
|
74
|
+
readonly pinned: number;
|
|
75
|
+
readonly last_recalled_turn: number | null;
|
|
76
|
+
readonly recall_count: number;
|
|
77
|
+
readonly created_turn: number;
|
|
78
|
+
readonly created_at: string;
|
|
79
|
+
}
|
|
80
|
+
export type LessonLogKind = 'prompted' | 'written' | 'recalled' | 'pinned-loaded';
|
|
81
|
+
export interface LessonLogRow {
|
|
82
|
+
readonly seq: number;
|
|
83
|
+
readonly session_id: string;
|
|
84
|
+
readonly kind: LessonLogKind;
|
|
85
|
+
readonly template_id: string | null;
|
|
86
|
+
readonly turn: number | null;
|
|
87
|
+
readonly origin: string | null;
|
|
88
|
+
readonly origin_ref: string | null;
|
|
89
|
+
readonly content_sha256: string | null;
|
|
90
|
+
readonly at: string;
|
|
91
|
+
}
|
|
92
|
+
/** Per-session runtime state; losing it on restart only drops a pending prompt or recall. */
|
|
93
|
+
export interface LessonState {
|
|
94
|
+
turn?: number;
|
|
95
|
+
last?: {
|
|
96
|
+
readonly features: ObservationFeatures;
|
|
97
|
+
readonly callId: string;
|
|
98
|
+
};
|
|
99
|
+
readonly failures: Map<string, string>;
|
|
100
|
+
/** A failed-then-succeeded target not yet prompted for. */
|
|
101
|
+
pending?: DigestContext;
|
|
102
|
+
/** The experience the last digest prompt followed; bound to the next lesson written. */
|
|
103
|
+
context?: DigestContext;
|
|
104
|
+
readonly recall: Set<string>;
|
|
105
|
+
/** Set by `agent/created` (startup, resume, compact): the next step loads the pinned lessons. */
|
|
106
|
+
pinnedDue?: string;
|
|
107
|
+
/** Pinned lessons loaded into this context; recall skips them. */
|
|
108
|
+
readonly loaded: Set<string>;
|
|
109
|
+
}
|
|
110
|
+
export declare function newLessonState(): LessonState;
|
|
111
|
+
/** Durable lesson state over the plugin's SQLite handle. */
|
|
112
|
+
export declare class LessonStore {
|
|
113
|
+
#private;
|
|
114
|
+
constructor(db: DatabaseSync);
|
|
115
|
+
cue(templateId: string): CueRow | undefined;
|
|
116
|
+
/** Cues of the lessons that are still this session's own session templates (a promoted one is not recalled here). */
|
|
117
|
+
cues(sessionId: string): CueRow[];
|
|
118
|
+
addCue(templateId: string, sessionId: string, cue: CueFeatures, origin: LessonOrigin, originRef: string | null, turn: number): void;
|
|
119
|
+
/** Pin or unpin a lesson (the owner's route). Returns false when it has no cue row. */
|
|
120
|
+
setPinned(templateId: string, pinned: boolean): boolean;
|
|
121
|
+
markRecalled(templateId: string, turn: number): void;
|
|
122
|
+
record(row: Omit<LessonLogRow, 'seq' | 'at'>): void;
|
|
123
|
+
log(sessionId: string, limit?: number): LessonLogRow[];
|
|
124
|
+
lastPromptTurn(sessionId: string): number | undefined;
|
|
125
|
+
/** Digest prompts since the session last wrote a lesson. */
|
|
126
|
+
promptsSinceWrite(sessionId: string): number;
|
|
127
|
+
prompted(sessionId: string, originRef: string): boolean;
|
|
128
|
+
countAt(sessionId: string, kind: LessonLogKind, turn: number): number;
|
|
129
|
+
}
|
|
130
|
+
/** One lesson as the read route and the recall see it. */
|
|
131
|
+
export interface LessonView {
|
|
132
|
+
readonly id: string;
|
|
133
|
+
readonly index: number;
|
|
134
|
+
readonly content: string;
|
|
135
|
+
readonly version: string | null;
|
|
136
|
+
}
|
|
137
|
+
/** A session's lessons: its own session templates named 体会·N, oldest first. */
|
|
138
|
+
export declare function lessonsOf(store: TemplateStore, sessionId: string): LessonView[];
|
|
139
|
+
type WriteResult = {
|
|
140
|
+
ok: true;
|
|
141
|
+
id: string;
|
|
142
|
+
index: number;
|
|
143
|
+
version: string;
|
|
144
|
+
} | {
|
|
145
|
+
ok: false;
|
|
146
|
+
code: string;
|
|
147
|
+
error: string;
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Write (or, with `replace`, rewrite) one of the calling session's lessons. A new lesson's cue comes from the experience
|
|
151
|
+
* the last digest prompt followed, else from the session's last observed call; the session cannot name a cue. A lesson
|
|
152
|
+
* the owner edited on the panel is the owner's: the session cannot rewrite it.
|
|
153
|
+
*/
|
|
154
|
+
export declare function writeLesson(store: TemplateStore, state: LessonState, sessionId: string, text: string, replace: unknown, config: LessonsConfig): WriteResult;
|
|
155
|
+
/** Whether a call's features fall in a lesson's situation: same tool, and the same preparation or the same target. */
|
|
156
|
+
export declare function cueMatches(cue: CueFeatures, features: ObservationFeatures): boolean;
|
|
157
|
+
/**
|
|
158
|
+
* Note one tool result: remember it as the last call, notice a target that failed and now succeeded (a digest
|
|
159
|
+
* signal), and queue every lesson whose cue it matches.
|
|
160
|
+
*/
|
|
161
|
+
export declare function observeForLessons(store: TemplateStore, state: LessonState, sessionId: string, callId: string, features: ObservationFeatures): void;
|
|
162
|
+
/** Body of a digest prompt. */
|
|
163
|
+
export declare function renderDigestPrompt(context: DigestContext): string;
|
|
164
|
+
/** Body of a recalled lesson. */
|
|
165
|
+
export declare function renderRecall(content: string, max: number): string;
|
|
166
|
+
type PinResult = {
|
|
167
|
+
ok: true;
|
|
168
|
+
id: string;
|
|
169
|
+
pinned: boolean;
|
|
170
|
+
} | {
|
|
171
|
+
ok: false;
|
|
172
|
+
code: 'not-found' | 'pinned-full';
|
|
173
|
+
error: string;
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* The owner pins or unpins one lesson (the PATCH route; sessions have no way to pin). Only a lesson that is still its
|
|
177
|
+
* session's own session template can be pinned, at most `max` per session.
|
|
178
|
+
*/
|
|
179
|
+
export declare function pinLesson(store: TemplateStore, templateId: string, pinned: boolean, max: number): PinResult;
|
|
180
|
+
/** The pinned lessons loaded at one start: oldest first, at most `max` of them and PINNED_MAX_CHARS in all. */
|
|
181
|
+
export declare function pinnedLessons(lessons: readonly LessonView[], max: number): LessonView[];
|
|
182
|
+
/** Body of the pinned lessons loaded at a start or after compaction. */
|
|
183
|
+
export declare function renderPinned(contents: readonly string[]): string;
|
|
184
|
+
/**
|
|
185
|
+
* This step's lesson messages: at most one digest prompt and one recalled lesson per turn, each with its cooldown.
|
|
186
|
+
* Exported for tests; the host path is the `agent/pre-step` listener below. Delivery is best effort (a rejected step
|
|
187
|
+
* loses it); what was handed over is logged.
|
|
188
|
+
*/
|
|
189
|
+
export declare function prepareLessonMessages(store: TemplateStore, state: LessonState, config: LessonsConfig, sessionId: string, turn: number, step: number): UserMessage[];
|
|
190
|
+
/** Register the observer, the step consumer and `lesson_write`. All of it is inert unless `config().enabled`. */
|
|
191
|
+
export declare function registerLessons(ctx: Context, store: () => TemplateStore, config: () => LessonsConfig): void;
|
|
192
|
+
export {};
|
package/lib/types/store.d.ts
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
import { EventStore } from './event-store.ts';
|
|
20
20
|
import { InterventionLog } from './interventions.ts';
|
|
21
21
|
import { SelfCheckLog } from './self-check.ts';
|
|
22
|
+
import { LessonStore } from './lessons.ts';
|
|
22
23
|
import type { CategoryCreateRequest, CategoryView, PromptScope, TemplateCreateRequest, TemplateInjectMode, TemplateUpdateRequest, TemplateView } from './types.ts';
|
|
23
24
|
/**
|
|
24
25
|
* Schema version gate; v4 adds `templates.mode` (inject|visible), v5 adds
|
|
@@ -27,9 +28,10 @@ import type { CategoryCreateRequest, CategoryView, PromptScope, TemplateCreateRe
|
|
|
27
28
|
* v7 combines both migrations into one schema version,
|
|
28
29
|
* v8 adds `event_episodes.repeated_after_reminder` (提醒后仍在重复, 0.16),
|
|
29
30
|
* v9 adds `templates.version` and the durable `interventions` log (observer phase 1, 0.16),
|
|
30
|
-
* v10 adds the wrap-up `self_check_log` (observer phase 2, PT-4)
|
|
31
|
+
* v10 adds the wrap-up `self_check_log` (observer phase 2, PT-4),
|
|
32
|
+
* v11 adds `lesson_cues` and `lesson_log` (体会, docs/spec-lesson-inject.md).
|
|
31
33
|
*/
|
|
32
|
-
export declare const SCHEMA_VERSION =
|
|
34
|
+
export declare const SCHEMA_VERSION = 11;
|
|
33
35
|
/** Upper bound of the inject interval when the deployment config omits one. */
|
|
34
36
|
export declare const DEFAULT_INJECT_MAX_EVERY = 1000;
|
|
35
37
|
/** Business-rule violation surfaced to routes as HTTP 400. */
|
|
@@ -72,6 +74,8 @@ export declare class TemplateStore {
|
|
|
72
74
|
readonly interventions: InterventionLog;
|
|
73
75
|
/** The wrap-up self-check log (v10). */
|
|
74
76
|
readonly selfChecks: SelfCheckLog;
|
|
77
|
+
/** Lesson cues and log (v11). */
|
|
78
|
+
readonly lessons: LessonStore;
|
|
75
79
|
constructor(dbPath: string, options?: TemplateStoreOptions);
|
|
76
80
|
/** Close the underlying database handle. */
|
|
77
81
|
close(): void;
|
|
@@ -107,7 +111,7 @@ export declare class TemplateStore {
|
|
|
107
111
|
keepVersion(templateId: string, version: string, name: string, content: string, source: string): void;
|
|
108
112
|
/** Promote one session template to the global partition; `undefined` when absent. */
|
|
109
113
|
makeGlobal(id: string): TemplateView | undefined;
|
|
110
|
-
/** Delete one template; `false` when absent. */
|
|
114
|
+
/** Delete one template; `false` when absent. A lesson's cue row goes with it (v11). */
|
|
111
115
|
delete(id: string): boolean;
|
|
112
116
|
/** List user categories: global ones plus one session's, ordered by name. */
|
|
113
117
|
listCategories(sessionId?: string): CategoryView[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nelsonlongxiang/dsh-prompt-templates",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "Quick prompt templates for DeepSeek Harness: global and per-session templates, a browser panel, and a pure-TS node:sqlite persistence backend",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|