@njuptlzf/agent-chat-server 0.2.0 → 0.3.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.
@@ -1,436 +1,447 @@
1
- /**
2
- * 人格配置面:`data/<product>/persona-config.json`。
3
- *
4
- * 与 `model-config.ts` / `mcp-config.ts` 同一套形状(这是项目里第三个配置面,
5
- * 共用的是**机制**不是 schema):
6
- * - manifest 是**出厂种子**,文件是运营改过的值;
7
- * - 读:1 秒级 mtime+size 缓存,变了才重解析;`invalidate()` 写完立刻生效;
8
- * - 写:原子写(tmp + rename),崩了不留半个 JSON;
9
- * - 坏文件:**永不抛**,回落 manifest 并记 `problems`(服务不能因为一个错 JSON 就起不来)。
10
- *
11
- * 边界(设计稿):**能力面永不进这个文件的可写面**。配置里只有
12
- * `disabledTools`(只能从 manifest 的白名单里减),没有「加工具」的字段。
13
- */
14
- import { readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
15
- import path from "node:path";
16
- import { PERSONA_UI_FIELDS, type PersonaUi } from "@njuptlzf/agent-chat-protocol";
17
- import { personaIdsOf, type LoadedProduct } from "./manifest.ts";
18
-
19
- export const PERSONA_CONFIG_FILENAME = "persona-config.json";
20
- const CACHE_TTL_MS = 1000;
21
- /** prompt 长度上下限:太短必然丢规则,太长会挤掉技能广告与工具说明。 */
22
- export const PROMPT_MIN_CHARS = 200;
23
- export const PROMPT_MAX_CHARS = 20_000;
24
-
25
- /** 单个人格的覆盖值。字段全部可选——缺字段回落 manifest(逐字段,不是整块替换)。 */
26
- export interface PersonaOverride {
27
- /** 人格正文全文(不是 patch:patch 难审、难回滚)。 */
28
- prompt?: string;
29
- /** 展示文案覆盖(只影响界面,不进模型)。 */
30
- ui?: PersonaUi;
31
- /** 从 manifest 白名单里**再收窄**:只能减,不能加。 */
32
- disabledTools?: string[];
33
- updatedBy?: string;
34
- updatedAt?: string;
35
- }
36
-
37
- /** 每改一次留一版;每个人格只留最近 N 版(配置是给人看的,不是数据库)。 */
38
- export const VERSIONS_PER_PERSONA = 20;
39
-
40
- export type PersonaVersionAction = "save" | "reset" | "rollback";
41
-
42
- /**
43
- * 一版快照。**回滚不是删历史**:它是把旧快照再写一次,生成新版本——
44
- * 这样"谁在什么时候退回了哪一版"本身也可追溯。
45
- */
46
- export interface PersonaVersionEntry {
47
- /** 写入后的配置版本号(全局单调递增,和 `PersonaConfig.version` 同一把尺)。 */
48
- version: number;
49
- persona: string;
50
- action: PersonaVersionAction;
51
- at: string;
52
- by: string;
53
- /** 这一版之后该人格的覆盖;`reset` 没有这个字段 = 回到 manifest。 */
54
- override?: PersonaOverride;
55
- /** 回滚时记「从哪一版恢复」。 */
56
- restoredFrom?: number;
57
- }
58
-
59
- export interface PersonaConfig {
60
- /** 单调递增;写接口用 `If-Match` 做乐观锁。 */
61
- version: number;
62
- personas: Record<string, PersonaOverride>;
63
- /** 版本快照:按写入顺序升序;同一个人格最多 `VERSIONS_PER_PERSONA` 条。 */
64
- versions: PersonaVersionEntry[];
65
- /** 运行时态:当前生效值来自文件还是 manifest(不落盘)。 */
66
- source: "manifest" | "file";
67
- /** 解析期发现的问题(坏字段、未知人格…),页面显示,不阻塞启动。 */
68
- problems: string[];
69
- }
70
-
71
- export interface PersonaConfigStore {
72
- /** 配置文件的绝对路径(管理页显示「去改哪个文件」)。 */
73
- readonly path: string;
74
- /** 读当前生效配置(1 秒级缓存,mtime/size 变了才重解析)。 */
75
- get(): PersonaConfig;
76
- /** 主动作废缓存——写接口保存后立刻生效。 */
77
- invalidate(): void;
78
- }
79
-
80
- export interface PersonaConfigStoreOptions {
81
- now?: () => number;
82
- warn?: (message: string) => void;
83
- }
84
-
85
- /** 文件不存在时的出厂值:一切走 manifest。 */
86
- export function manifestPersonaConfig(problems: string[] = []): PersonaConfig {
87
- return { version: 0, personas: {}, versions: [], source: "manifest", problems };
88
- }
89
-
90
- function isRecord(v: unknown): v is Record<string, unknown> {
91
- return typeof v === "object" && v !== null && !Array.isArray(v);
92
- }
93
-
94
- /**
95
- * 解析配置文件。**永不抛**:结构不对就返回 null(调用方回落 manifest),
96
- * 单个人格写坏就丢掉那一条并记 problem,其余照用。
97
- */
98
- export function parsePersonaConfig(raw: unknown, known: Set<string>): { config: PersonaConfig | null; problems: string[] } {
99
- const problems: string[] = [];
100
- if (!isRecord(raw)) return { config: null, problems: [`${PERSONA_CONFIG_FILENAME} must be a JSON object`] };
101
-
102
- const version = raw.version;
103
- if (version !== undefined && (typeof version !== "number" || !Number.isInteger(version) || version < 0)) {
104
- problems.push("`version` must be a non-negative integer");
105
- }
106
- const personasRaw = raw.personas;
107
- if (personasRaw !== undefined && !isRecord(personasRaw)) {
108
- return { config: null, problems: [...problems, "`personas` must be an object keyed by persona id"] };
109
- }
110
-
111
- const personas: Record<string, PersonaOverride> = {};
112
- for (const [id, value] of Object.entries(personasRaw ?? {})) {
113
- if (!known.has(id)) {
114
- // 人格删了但配置文件里还留着:忽略这一条,但要说出来(否则页面会显示一个不存在的条目)。
115
- problems.push(`persona "${id}" is not declared by the manifest; its override is ignored`);
116
- continue;
117
- }
118
- const out = parseOverride(value, `personas.${id}`, problems);
119
- if (out) personas[id] = out;
120
- }
121
-
122
- // 版本快照:坏条目丢掉并记 problem,**不回滚整个配置**——
123
- // 版本历史是审计辅助,不该因为它坏了就让现任配置失效。
124
- const versionsRaw = raw.versions;
125
- const versions: PersonaVersionEntry[] = [];
126
- if (versionsRaw !== undefined) {
127
- if (!Array.isArray(versionsRaw)) {
128
- problems.push("`versions` must be an array");
129
- } else {
130
- for (const [i, item] of versionsRaw.entries()) {
131
- const entry = parseVersionEntry(item, i, known, problems);
132
- if (entry) versions.push(entry);
133
- }
134
- versions.sort((a, b) => a.version - b.version);
135
- }
136
- }
137
-
138
- return {
139
- config: {
140
- version: typeof version === "number" && version >= 0 ? version : 1,
141
- personas,
142
- versions,
143
- source: "file",
144
- problems,
145
- },
146
- problems,
147
- };
148
- }
149
-
150
- /** 单个人格的覆盖值解析(配置里的 `personas[x]` 与版本快照里的 `override` 共用)。 */
151
- function parseOverride(raw: unknown, at: string, problems: string[]): PersonaOverride | undefined {
152
- if (!isRecord(raw)) {
153
- problems.push(`${at} must be an object`);
154
- return undefined;
155
- }
156
- const out: PersonaOverride = {};
157
- if (raw.prompt !== undefined) {
158
- if (typeof raw.prompt !== "string" || raw.prompt.trim() === "") problems.push(`${at}.prompt must be a non-empty string`);
159
- else out.prompt = raw.prompt;
160
- }
161
- if (raw.ui !== undefined) {
162
- const ui = parseUi(raw.ui, `${at}.ui`, problems);
163
- if (ui) out.ui = ui;
164
- }
165
- if (raw.disabledTools !== undefined) {
166
- if (!Array.isArray(raw.disabledTools) || raw.disabledTools.some((t) => typeof t !== "string" || !t.trim())) {
167
- problems.push(`${at}.disabledTools must be a list of tool names`);
168
- } else {
169
- out.disabledTools = raw.disabledTools as string[];
170
- }
171
- }
172
- for (const key of ["updatedBy", "updatedAt"] as const) {
173
- const v = raw[key];
174
- if (v === undefined) continue;
175
- if (typeof v !== "string") problems.push(`${at}.${key} must be a string`);
176
- else out[key] = v;
177
- }
178
- return out;
179
- }
180
-
181
- function parseVersionEntry(raw: unknown, index: number, known: Set<string>, problems: string[]): PersonaVersionEntry | undefined {
182
- const at = `versions[${index}]`;
183
- if (!isRecord(raw)) {
184
- problems.push(`${at} must be an object`);
185
- return undefined;
186
- }
187
- const { version, persona, action } = raw;
188
- if (typeof version !== "number" || !Number.isInteger(version) || version < 0) {
189
- problems.push(`${at}.version must be a non-negative integer`);
190
- return undefined;
191
- }
192
- if (typeof persona !== "string" || !known.has(persona)) {
193
- problems.push(`${at}.persona is not declared by the manifest; the snapshot is ignored`);
194
- return undefined;
195
- }
196
- if (action !== "save" && action !== "reset" && action !== "rollback") {
197
- problems.push(`${at}.action must be save/reset/rollback`);
198
- return undefined;
199
- }
200
- const atTime = typeof raw.at === "string" ? raw.at : "";
201
- const by = typeof raw.by === "string" ? raw.by : "";
202
- if (!atTime) problems.push(`${at}.at must be a string`);
203
- if (!by) problems.push(`${at}.by must be a string`);
204
- const out: PersonaVersionEntry = { version, persona, action, at: atTime, by };
205
- if (raw.override !== undefined) {
206
- const override = parseOverride(raw.override, `${at}.override`, problems);
207
- if (override) out.override = override;
208
- }
209
- if (typeof raw.restoredFrom === "number" && Number.isInteger(raw.restoredFrom)) out.restoredFrom = raw.restoredFrom;
210
- return out;
211
- }
212
-
213
- /** 展示文案的宽松解析(与 manifest 同一条规矩:拒空字符串、拒未知键)。 */
214
- function parseUi(raw: unknown, at: string, problems: string[]): PersonaUi | undefined {
215
- if (!isRecord(raw)) {
216
- problems.push(`${at} must be an object`);
217
- return undefined;
218
- }
219
- const out: PersonaUi = {};
220
- for (const [key, value] of Object.entries(raw)) {
221
- if (!(PERSONA_UI_FIELDS as readonly string[]).includes(key)) {
222
- problems.push(`${at}.${key} is not a display field`);
223
- continue;
224
- }
225
- if (key === "suggestions") {
226
- if (!Array.isArray(value) || value.some((s) => typeof s !== "string" || !s.trim())) {
227
- problems.push(`${at}.suggestions must be a list of non-empty strings`);
228
- } else {
229
- out.suggestions = value as string[];
230
- }
231
- continue;
232
- }
233
- if (typeof value !== "string" || value.trim() === "") {
234
- problems.push(`${at}.${key} must be a non-empty string`);
235
- continue;
236
- }
237
- out[key as Exclude<keyof PersonaUi, "suggestions">] = value;
238
- }
239
- return out;
240
- }
241
-
242
- export function createPersonaConfigStore(
243
- dataDir: string,
244
- product: LoadedProduct,
245
- opts: PersonaConfigStoreOptions = {},
246
- ): PersonaConfigStore {
247
- const file = path.join(dataDir, PERSONA_CONFIG_FILENAME);
248
- const now = opts.now ?? Date.now;
249
- const warn = opts.warn ?? ((m: string) => console.warn(m));
250
- const known = personaIdsOf(product);
251
-
252
- let cached: PersonaConfig | undefined;
253
- let stamp = "";
254
- let checkedAt = Number.NEGATIVE_INFINITY;
255
-
256
- const read = (): PersonaConfig => {
257
- let text: string;
258
- try {
259
- text = readFileSync(file, "utf8");
260
- } catch (err) {
261
- // 文件不存在是**正常状态**(从没配过),不打 warn 刷屏。
262
- return manifestPersonaConfig();
263
- }
264
- let raw: unknown;
265
- try {
266
- raw = JSON.parse(text);
267
- } catch (err) {
268
- warn(`[persona-config] ${file} is not valid JSON (${String(err)}); falling back to the manifest`);
269
- return manifestPersonaConfig([`${PERSONA_CONFIG_FILENAME} is not valid JSON (${String(err)})`]);
270
- }
271
- const { config, problems } = parsePersonaConfig(raw, known);
272
- if (!config) {
273
- warn(`[persona-config] ${file} is unusable (${problems.join("; ")}); falling back to the manifest`);
274
- return manifestPersonaConfig(problems);
275
- }
276
- if (problems.length > 0) warn(`[persona-config] ${file}: ${problems.join("; ")}`);
277
- return config;
278
- };
279
-
280
- return {
281
- path: file,
282
- get() {
283
- const t = now();
284
- if (cached && t - checkedAt < CACHE_TTL_MS) return cached;
285
- checkedAt = t;
286
- let stat: ReturnType<typeof statSync> | undefined;
287
- try {
288
- stat = statSync(file);
289
- } catch {
290
- stat = undefined;
291
- }
292
- const next = stat ? `${stat.mtimeMs}:${stat.size}` : "";
293
- if (cached && next === stamp) return cached;
294
- stamp = next;
295
- cached = stat ? read() : manifestPersonaConfig();
296
- return cached;
297
- },
298
- invalidate() {
299
- cached = undefined;
300
- stamp = "";
301
- checkedAt = Number.NEGATIVE_INFINITY;
302
- },
303
- };
304
- }
305
-
306
- /** 原子写(同 model/mcp-config:tmp + rename),写完作废缓存 ⇒ 下一次建会话生效。 */
307
- export function savePersonaConfig(store: PersonaConfigStore, cfg: PersonaConfig): void {
308
- const body =
309
- JSON.stringify({ version: cfg.version, personas: cfg.personas, versions: cfg.versions }, null, 2) + "\n";
310
- const tmp = `${store.path}.${process.pid}.${Date.now()}.tmp`;
311
- writeFileSync(tmp, body, "utf8");
312
- try {
313
- renameSync(tmp, store.path);
314
- } catch (err) {
315
- try {
316
- unlinkSync(tmp);
317
- } catch {
318
- /* 清理失败不影响主错误 */
319
- }
320
- throw err;
321
- }
322
- store.invalidate();
323
- }
324
-
325
- /**
326
- * 追加一版快照,并按人格裁到最近 `VERSIONS_PER_PERSONA` 条。
327
- * **裁的是最老的快照**,不是当前的生效值——两者是分开存的(`personas` 永远在)。
328
- */
329
- export function appendVersion(
330
- versions: PersonaVersionEntry[],
331
- entry: PersonaVersionEntry,
332
- perPersona = VERSIONS_PER_PERSONA,
333
- ): PersonaVersionEntry[] {
334
- const all = [...versions, entry];
335
- const kept: PersonaVersionEntry[] = [];
336
- const seen = new Map<string, number>();
337
- // 从新到旧保留,保证"只裁最老的那几条",且别的人格的历史不受牵连。
338
- for (let i = all.length - 1; i >= 0; i--) {
339
- const v = all[i]!;
340
- const n = seen.get(v.persona) ?? 0;
341
- if (n >= perPersona) continue;
342
- kept.push(v);
343
- seen.set(v.persona, n + 1);
344
- }
345
- return kept.reverse();
346
- }
347
-
348
- /** 某人格的版本快照,**新到旧**(页面按这个顺序列)。 */
349
- export function versionsOf(cfg: PersonaConfig, persona: string): PersonaVersionEntry[] {
350
- return cfg.versions.filter((v) => v.persona === persona).sort((a, b) => b.version - a.version);
351
- }
352
-
353
- export function versionEntry(cfg: PersonaConfig, persona: string, version: number): PersonaVersionEntry | undefined {
354
- return cfg.versions.find((v) => v.persona === persona && v.version === version);
355
- }
356
-
357
- /**
358
- * 该人格**当刻生效的版本号**(写进 `history.persona_version`):
359
- * - 有快照 ⇒ 最新那一版;
360
- * - 有覆盖但没快照(手工写入的配置)⇒ 当前配置版本;
361
- * - 没有覆盖 ⇒ 0(= 直接采用 manifest 出厂值,不代表已有版本记录)。
362
- */
363
- export function effectivePersonaVersion(cfg: PersonaConfig, persona: string): number {
364
- const list = versionsOf(cfg, persona);
365
- if (list.length > 0) return list[0]!.version;
366
- return cfg.personas[persona] !== undefined ? cfg.version : 0;
367
- }
368
-
369
- /**
370
- * 生效值 = manifest 编译结果 + 配置覆盖(**逐字段**)。
371
- *
372
- * 只做两件事:prompt 换掉;`disabledTools` 从白名单里减掉。
373
- * `allowTools === undefined`(manifest 未设白名单 = 不限)时原样返回 `undefined`,
374
- * 由 `filterToolsForPersona` / `narrowMcpExposure` 按 deny 名单处理——
375
- * 否则「不给白名单的人格」连一个工具都停不掉。
376
- */
377
- export function applyPersonaOverride(
378
- base: { systemPromptText: string; allowTools?: string[] },
379
- override: PersonaOverride | undefined,
380
- ): { prompt: string; allowTools: string[] | undefined; disabledTools: string[] } {
381
- const disabledTools = override?.disabledTools ?? [];
382
- const allowTools =
383
- base.allowTools === undefined || disabledTools.length === 0
384
- ? base.allowTools
385
- : base.allowTools.filter((t) => !disabledTools.includes(t));
386
- return { prompt: override?.prompt ?? base.systemPromptText, allowTools, disabledTools };
387
- }
388
-
389
- /**
390
- * 保存前校验(的写接口用它,先把它写出来并测)。
391
- * 一次返回**全部**错误,不挤牙膏——页面要能一次改完。
392
- */
393
- export function validatePersona(
394
- product: LoadedProduct,
395
- personaId: string,
396
- input: { prompt?: unknown; ui?: unknown; disabledTools?: unknown },
397
- ): string[] {
398
- const errors: string[] = [];
399
- const known = personaIdsOf(product);
400
- if (!known.has(personaId)) return [`unknown persona "${personaId}"`];
401
-
402
- if (input.prompt !== undefined) {
403
- if (typeof input.prompt !== "string") {
404
- errors.push("prompt must be a string");
405
- } else {
406
- const len = input.prompt.trim().length;
407
- if (len < PROMPT_MIN_CHARS) errors.push(`prompt is too short (${len} chars; minimum ${PROMPT_MIN_CHARS})`);
408
- if (len > PROMPT_MAX_CHARS) errors.push(`prompt is too long (${len} chars; maximum ${PROMPT_MAX_CHARS})`);
409
- // 必备段落:产品声明红线,core 只检查「在不在」。
410
- const lines = input.prompt.split("\n").map((l) => l.trimStart());
411
- for (const section of product.personaRequiredSections.get(personaId) ?? []) {
412
- if (!lines.some((l) => l.startsWith(section))) errors.push(`prompt is missing required section: ${section}`);
413
- }
414
- }
415
- }
416
-
417
- if (input.ui !== undefined) {
418
- const problems: string[] = [];
419
- parseUi(input.ui, "ui", problems);
420
- errors.push(...problems);
421
- }
422
-
423
- if (input.disabledTools !== undefined) {
424
- if (!Array.isArray(input.disabledTools) || input.disabledTools.some((t) => typeof t !== "string" || !t.trim())) {
425
- errors.push("disabledTools must be a list of tool names");
426
- } else if (product.personaAgents.get(personaId)?.allowTools !== undefined) {
427
- // 有白名单时,停用项必须是白名单的子集——结构上保证「只能减」。
428
- const allow = new Set(product.personaAgents.get(personaId)!.allowTools);
429
- for (const t of input.disabledTools as string[]) {
430
- if (!allow.has(t)) errors.push(`disabledTools: "${t}" is not in this persona's allowTools`);
431
- }
432
- }
433
- }
434
-
435
- return errors;
436
- }
1
+ /**
2
+ * 人格配置面:`data/<product>/persona-config.json`。
3
+ *
4
+ * 与 `model-config.ts` / `mcp-config.ts` 同一套形状(这是项目里第三个配置面,
5
+ * 共用的是**机制**不是 schema):
6
+ * - manifest 是**出厂种子**,文件是运营改过的值;
7
+ * - 读:1 秒级 mtime+size 缓存,变了才重解析;`invalidate()` 写完立刻生效;
8
+ * - 写:原子写(tmp + rename),崩了不留半个 JSON;
9
+ * - 坏文件:**永不抛**,回落 manifest 并记 `problems`(服务不能因为一个错 JSON 就起不来)。
10
+ *
11
+ * 边界(设计稿):**能力面永不进这个文件的可写面**。配置里只有
12
+ * `disabledTools`(只能从 manifest 的白名单里减),没有「加工具」的字段。
13
+ */
14
+ import { readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
15
+ import path from "node:path";
16
+ import { PERSONA_UI_FIELDS, type PersonaUi } from "@njuptlzf/agent-chat-protocol";
17
+ import { FOLLOW_UP_MODES, type FollowUpMode } from "./branding-ui.ts";
18
+ import { personaIdsOf, type LoadedProduct } from "./manifest.ts";
19
+
20
+ export const PERSONA_CONFIG_FILENAME = "persona-config.json";
21
+ const CACHE_TTL_MS = 1000;
22
+ /** prompt 长度上下限:太短必然丢规则,太长会挤掉技能广告与工具说明。 */
23
+ export const PROMPT_MIN_CHARS = 200;
24
+ export const PROMPT_MAX_CHARS = 20_000;
25
+
26
+ /** 单个人格的覆盖值。字段全部可选——缺字段回落 manifest(逐字段,不是整块替换)。 */
27
+ export interface PersonaOverride {
28
+ /** 人格正文全文(不是 patch:patch 难审、难回滚)。 */
29
+ prompt?: string;
30
+ /** 展示文案覆盖(只影响界面,不进模型)。 */
31
+ ui?: PersonaUi;
32
+ /** 从 manifest 白名单里**再收窄**:只能减,不能加。 */
33
+ disabledTools?: string[];
34
+ updatedBy?: string;
35
+ updatedAt?: string;
36
+ }
37
+
38
+ /** 每改一次留一版;每个人格只留最近 N 版(配置是给人看的,不是数据库)。 */
39
+ export const VERSIONS_PER_PERSONA = 20;
40
+
41
+ export type PersonaVersionAction = "save" | "reset" | "rollback";
42
+
43
+ /**
44
+ * 一版快照。**回滚不是删历史**:它是把旧快照再写一次,生成新版本——
45
+ * 这样"谁在什么时候退回了哪一版"本身也可追溯。
46
+ */
47
+ export interface PersonaVersionEntry {
48
+ /** 写入后的配置版本号(全局单调递增,和 `PersonaConfig.version` 同一把尺)。 */
49
+ version: number;
50
+ persona: string;
51
+ action: PersonaVersionAction;
52
+ at: string;
53
+ by: string;
54
+ /** 这一版之后该人格的覆盖;`reset` 没有这个字段 = 回到 manifest。 */
55
+ override?: PersonaOverride;
56
+ /** 回滚时记「从哪一版恢复」。 */
57
+ restoredFrom?: number;
58
+ }
59
+
60
+ export interface PersonaConfig {
61
+ /** 单调递增;写接口用 `If-Match` 做乐观锁。 */
62
+ version: number;
63
+ personas: Record<string, PersonaOverride>;
64
+ /** 版本快照:按写入顺序升序;同一个人格最多 `VERSIONS_PER_PERSONA` 条。 */
65
+ versions: PersonaVersionEntry[];
66
+ /** 运行时态:当前生效值来自文件还是 manifest(不落盘)。 */
67
+ source: "manifest" | "file";
68
+ /** 解析期发现的问题(坏字段、未知人格…),页面显示,不阻塞启动。 */
69
+ problems: string[];
70
+ }
71
+
72
+ export interface PersonaConfigStore {
73
+ /** 配置文件的绝对路径(管理页显示「去改哪个文件」)。 */
74
+ readonly path: string;
75
+ /** 读当前生效配置(1 秒级缓存,mtime/size 变了才重解析)。 */
76
+ get(): PersonaConfig;
77
+ /** 主动作废缓存——写接口保存后立刻生效。 */
78
+ invalidate(): void;
79
+ }
80
+
81
+ export interface PersonaConfigStoreOptions {
82
+ now?: () => number;
83
+ warn?: (message: string) => void;
84
+ }
85
+
86
+ /** 文件不存在时的出厂值:一切走 manifest。 */
87
+ export function manifestPersonaConfig(problems: string[] = []): PersonaConfig {
88
+ return { version: 0, personas: {}, versions: [], source: "manifest", problems };
89
+ }
90
+
91
+ function isRecord(v: unknown): v is Record<string, unknown> {
92
+ return typeof v === "object" && v !== null && !Array.isArray(v);
93
+ }
94
+
95
+ /**
96
+ * 解析配置文件。**永不抛**:结构不对就返回 null(调用方回落 manifest),
97
+ * 单个人格写坏就丢掉那一条并记 problem,其余照用。
98
+ */
99
+ export function parsePersonaConfig(raw: unknown, known: Set<string>): { config: PersonaConfig | null; problems: string[] } {
100
+ const problems: string[] = [];
101
+ if (!isRecord(raw)) return { config: null, problems: [`${PERSONA_CONFIG_FILENAME} must be a JSON object`] };
102
+
103
+ const version = raw.version;
104
+ if (version !== undefined && (typeof version !== "number" || !Number.isInteger(version) || version < 0)) {
105
+ problems.push("`version` must be a non-negative integer");
106
+ }
107
+ const personasRaw = raw.personas;
108
+ if (personasRaw !== undefined && !isRecord(personasRaw)) {
109
+ return { config: null, problems: [...problems, "`personas` must be an object keyed by persona id"] };
110
+ }
111
+
112
+ const personas: Record<string, PersonaOverride> = {};
113
+ for (const [id, value] of Object.entries(personasRaw ?? {})) {
114
+ if (!known.has(id)) {
115
+ // 人格删了但配置文件里还留着:忽略这一条,但要说出来(否则页面会显示一个不存在的条目)。
116
+ problems.push(`persona "${id}" is not declared by the manifest; its override is ignored`);
117
+ continue;
118
+ }
119
+ const out = parseOverride(value, `personas.${id}`, problems);
120
+ if (out) personas[id] = out;
121
+ }
122
+
123
+ // 版本快照:坏条目丢掉并记 problem,**不回滚整个配置**——
124
+ // 版本历史是审计辅助,不该因为它坏了就让现任配置失效。
125
+ const versionsRaw = raw.versions;
126
+ const versions: PersonaVersionEntry[] = [];
127
+ if (versionsRaw !== undefined) {
128
+ if (!Array.isArray(versionsRaw)) {
129
+ problems.push("`versions` must be an array");
130
+ } else {
131
+ for (const [i, item] of versionsRaw.entries()) {
132
+ const entry = parseVersionEntry(item, i, known, problems);
133
+ if (entry) versions.push(entry);
134
+ }
135
+ versions.sort((a, b) => a.version - b.version);
136
+ }
137
+ }
138
+
139
+ return {
140
+ config: {
141
+ version: typeof version === "number" && version >= 0 ? version : 1,
142
+ personas,
143
+ versions,
144
+ source: "file",
145
+ problems,
146
+ },
147
+ problems,
148
+ };
149
+ }
150
+
151
+ /** 单个人格的覆盖值解析(配置里的 `personas[x]` 与版本快照里的 `override` 共用)。 */
152
+ function parseOverride(raw: unknown, at: string, problems: string[]): PersonaOverride | undefined {
153
+ if (!isRecord(raw)) {
154
+ problems.push(`${at} must be an object`);
155
+ return undefined;
156
+ }
157
+ const out: PersonaOverride = {};
158
+ if (raw.prompt !== undefined) {
159
+ if (typeof raw.prompt !== "string" || raw.prompt.trim() === "") problems.push(`${at}.prompt must be a non-empty string`);
160
+ else out.prompt = raw.prompt;
161
+ }
162
+ if (raw.ui !== undefined) {
163
+ const ui = parseUi(raw.ui, `${at}.ui`, problems);
164
+ if (ui) out.ui = ui;
165
+ }
166
+ if (raw.disabledTools !== undefined) {
167
+ if (!Array.isArray(raw.disabledTools) || raw.disabledTools.some((t) => typeof t !== "string" || !t.trim())) {
168
+ problems.push(`${at}.disabledTools must be a list of tool names`);
169
+ } else {
170
+ out.disabledTools = raw.disabledTools as string[];
171
+ }
172
+ }
173
+ for (const key of ["updatedBy", "updatedAt"] as const) {
174
+ const v = raw[key];
175
+ if (v === undefined) continue;
176
+ if (typeof v !== "string") problems.push(`${at}.${key} must be a string`);
177
+ else out[key] = v;
178
+ }
179
+ return out;
180
+ }
181
+
182
+ function parseVersionEntry(raw: unknown, index: number, known: Set<string>, problems: string[]): PersonaVersionEntry | undefined {
183
+ const at = `versions[${index}]`;
184
+ if (!isRecord(raw)) {
185
+ problems.push(`${at} must be an object`);
186
+ return undefined;
187
+ }
188
+ const { version, persona, action } = raw;
189
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 0) {
190
+ problems.push(`${at}.version must be a non-negative integer`);
191
+ return undefined;
192
+ }
193
+ if (typeof persona !== "string" || !known.has(persona)) {
194
+ problems.push(`${at}.persona is not declared by the manifest; the snapshot is ignored`);
195
+ return undefined;
196
+ }
197
+ if (action !== "save" && action !== "reset" && action !== "rollback") {
198
+ problems.push(`${at}.action must be save/reset/rollback`);
199
+ return undefined;
200
+ }
201
+ const atTime = typeof raw.at === "string" ? raw.at : "";
202
+ const by = typeof raw.by === "string" ? raw.by : "";
203
+ if (!atTime) problems.push(`${at}.at must be a string`);
204
+ if (!by) problems.push(`${at}.by must be a string`);
205
+ const out: PersonaVersionEntry = { version, persona, action, at: atTime, by };
206
+ if (raw.override !== undefined) {
207
+ const override = parseOverride(raw.override, `${at}.override`, problems);
208
+ if (override) out.override = override;
209
+ }
210
+ if (typeof raw.restoredFrom === "number" && Number.isInteger(raw.restoredFrom)) out.restoredFrom = raw.restoredFrom;
211
+ return out;
212
+ }
213
+
214
+ /** 展示文案的宽松解析(与 manifest 同一条规矩:拒空字符串、拒未知键)。 */
215
+ function parseUi(raw: unknown, at: string, problems: string[]): PersonaUi | undefined {
216
+ if (!isRecord(raw)) {
217
+ problems.push(`${at} must be an object`);
218
+ return undefined;
219
+ }
220
+ const out: PersonaUi = {};
221
+ for (const [key, value] of Object.entries(raw)) {
222
+ if (!(PERSONA_UI_FIELDS as readonly string[]).includes(key)) {
223
+ problems.push(`${at}.${key} is not a display field`);
224
+ continue;
225
+ }
226
+ if (key === "suggestions") {
227
+ if (!Array.isArray(value) || value.some((s) => typeof s !== "string" || !s.trim())) {
228
+ problems.push(`${at}.suggestions must be a list of non-empty strings`);
229
+ } else {
230
+ out.suggestions = value as string[];
231
+ }
232
+ continue;
233
+ }
234
+ // 循环外专用块(与 manifest 的 loadPersonaUi 同款):字面量联合字段不能落进下面
235
+ // 的泛型字符串写,否则 `out[key] = value` 触发 TS「联合键写入取交集」编译错。
236
+ if (key === "followUpMode") {
237
+ if (typeof value !== "string" || !(FOLLOW_UP_MODES as readonly string[]).includes(value)) {
238
+ problems.push(`${at}.followUpMode must be one of ${FOLLOW_UP_MODES.join(" | ")}`);
239
+ } else {
240
+ out.followUpMode = value as FollowUpMode;
241
+ }
242
+ continue;
243
+ }
244
+ if (typeof value !== "string" || value.trim() === "") {
245
+ problems.push(`${at}.${key} must be a non-empty string`);
246
+ continue;
247
+ }
248
+ out[key as Exclude<keyof PersonaUi, "suggestions" | "followUpMode">] = value;
249
+ }
250
+ return out;
251
+ }
252
+
253
+ export function createPersonaConfigStore(
254
+ dataDir: string,
255
+ product: LoadedProduct,
256
+ opts: PersonaConfigStoreOptions = {},
257
+ ): PersonaConfigStore {
258
+ const file = path.join(dataDir, PERSONA_CONFIG_FILENAME);
259
+ const now = opts.now ?? Date.now;
260
+ const warn = opts.warn ?? ((m: string) => console.warn(m));
261
+ const known = personaIdsOf(product);
262
+
263
+ let cached: PersonaConfig | undefined;
264
+ let stamp = "";
265
+ let checkedAt = Number.NEGATIVE_INFINITY;
266
+
267
+ const read = (): PersonaConfig => {
268
+ let text: string;
269
+ try {
270
+ text = readFileSync(file, "utf8");
271
+ } catch (err) {
272
+ // 文件不存在是**正常状态**(从没配过),不打 warn 刷屏。
273
+ return manifestPersonaConfig();
274
+ }
275
+ let raw: unknown;
276
+ try {
277
+ raw = JSON.parse(text);
278
+ } catch (err) {
279
+ warn(`[persona-config] ${file} is not valid JSON (${String(err)}); falling back to the manifest`);
280
+ return manifestPersonaConfig([`${PERSONA_CONFIG_FILENAME} is not valid JSON (${String(err)})`]);
281
+ }
282
+ const { config, problems } = parsePersonaConfig(raw, known);
283
+ if (!config) {
284
+ warn(`[persona-config] ${file} is unusable (${problems.join("; ")}); falling back to the manifest`);
285
+ return manifestPersonaConfig(problems);
286
+ }
287
+ if (problems.length > 0) warn(`[persona-config] ${file}: ${problems.join("; ")}`);
288
+ return config;
289
+ };
290
+
291
+ return {
292
+ path: file,
293
+ get() {
294
+ const t = now();
295
+ if (cached && t - checkedAt < CACHE_TTL_MS) return cached;
296
+ checkedAt = t;
297
+ let stat: ReturnType<typeof statSync> | undefined;
298
+ try {
299
+ stat = statSync(file);
300
+ } catch {
301
+ stat = undefined;
302
+ }
303
+ const next = stat ? `${stat.mtimeMs}:${stat.size}` : "";
304
+ if (cached && next === stamp) return cached;
305
+ stamp = next;
306
+ cached = stat ? read() : manifestPersonaConfig();
307
+ return cached;
308
+ },
309
+ invalidate() {
310
+ cached = undefined;
311
+ stamp = "";
312
+ checkedAt = Number.NEGATIVE_INFINITY;
313
+ },
314
+ };
315
+ }
316
+
317
+ /** 原子写(同 model/mcp-config:tmp + rename),写完作废缓存 ⇒ 下一次建会话生效。 */
318
+ export function savePersonaConfig(store: PersonaConfigStore, cfg: PersonaConfig): void {
319
+ const body =
320
+ JSON.stringify({ version: cfg.version, personas: cfg.personas, versions: cfg.versions }, null, 2) + "\n";
321
+ const tmp = `${store.path}.${process.pid}.${Date.now()}.tmp`;
322
+ writeFileSync(tmp, body, "utf8");
323
+ try {
324
+ renameSync(tmp, store.path);
325
+ } catch (err) {
326
+ try {
327
+ unlinkSync(tmp);
328
+ } catch {
329
+ /* 清理失败不影响主错误 */
330
+ }
331
+ throw err;
332
+ }
333
+ store.invalidate();
334
+ }
335
+
336
+ /**
337
+ * 追加一版快照,并按人格裁到最近 `VERSIONS_PER_PERSONA` 条。
338
+ * **裁的是最老的快照**,不是当前的生效值——两者是分开存的(`personas` 永远在)。
339
+ */
340
+ export function appendVersion(
341
+ versions: PersonaVersionEntry[],
342
+ entry: PersonaVersionEntry,
343
+ perPersona = VERSIONS_PER_PERSONA,
344
+ ): PersonaVersionEntry[] {
345
+ const all = [...versions, entry];
346
+ const kept: PersonaVersionEntry[] = [];
347
+ const seen = new Map<string, number>();
348
+ // 从新到旧保留,保证"只裁最老的那几条",且别的人格的历史不受牵连。
349
+ for (let i = all.length - 1; i >= 0; i--) {
350
+ const v = all[i]!;
351
+ const n = seen.get(v.persona) ?? 0;
352
+ if (n >= perPersona) continue;
353
+ kept.push(v);
354
+ seen.set(v.persona, n + 1);
355
+ }
356
+ return kept.reverse();
357
+ }
358
+
359
+ /** 某人格的版本快照,**新到旧**(页面按这个顺序列)。 */
360
+ export function versionsOf(cfg: PersonaConfig, persona: string): PersonaVersionEntry[] {
361
+ return cfg.versions.filter((v) => v.persona === persona).sort((a, b) => b.version - a.version);
362
+ }
363
+
364
+ export function versionEntry(cfg: PersonaConfig, persona: string, version: number): PersonaVersionEntry | undefined {
365
+ return cfg.versions.find((v) => v.persona === persona && v.version === version);
366
+ }
367
+
368
+ /**
369
+ * 该人格**当刻生效的版本号**(写进 `history.persona_version`):
370
+ * - 有快照 ⇒ 最新那一版;
371
+ * - 有覆盖但没快照(手工写入的配置)⇒ 当前配置版本;
372
+ * - 没有覆盖 ⇒ 0(= 直接采用 manifest 出厂值,不代表已有版本记录)。
373
+ */
374
+ export function effectivePersonaVersion(cfg: PersonaConfig, persona: string): number {
375
+ const list = versionsOf(cfg, persona);
376
+ if (list.length > 0) return list[0]!.version;
377
+ return cfg.personas[persona] !== undefined ? cfg.version : 0;
378
+ }
379
+
380
+ /**
381
+ * 生效值 = manifest 编译结果 + 配置覆盖(**逐字段**)。
382
+ *
383
+ * 只做两件事:prompt 换掉;`disabledTools` 从白名单里减掉。
384
+ * `allowTools === undefined`(manifest 未设白名单 = 不限)时原样返回 `undefined`,
385
+ * 由 `filterToolsForPersona` / `narrowMcpExposure` 按 deny 名单处理——
386
+ * 否则「不给白名单的人格」连一个工具都停不掉。
387
+ */
388
+ export function applyPersonaOverride(
389
+ base: { systemPromptText: string; allowTools?: string[] },
390
+ override: PersonaOverride | undefined,
391
+ ): { prompt: string; allowTools: string[] | undefined; disabledTools: string[] } {
392
+ const disabledTools = override?.disabledTools ?? [];
393
+ const allowTools =
394
+ base.allowTools === undefined || disabledTools.length === 0
395
+ ? base.allowTools
396
+ : base.allowTools.filter((t) => !disabledTools.includes(t));
397
+ return { prompt: override?.prompt ?? base.systemPromptText, allowTools, disabledTools };
398
+ }
399
+
400
+ /**
401
+ * 保存前校验(的写接口用它,先把它写出来并测)。
402
+ * 一次返回**全部**错误,不挤牙膏——页面要能一次改完。
403
+ */
404
+ export function validatePersona(
405
+ product: LoadedProduct,
406
+ personaId: string,
407
+ input: { prompt?: unknown; ui?: unknown; disabledTools?: unknown },
408
+ ): string[] {
409
+ const errors: string[] = [];
410
+ const known = personaIdsOf(product);
411
+ if (!known.has(personaId)) return [`unknown persona "${personaId}"`];
412
+
413
+ if (input.prompt !== undefined) {
414
+ if (typeof input.prompt !== "string") {
415
+ errors.push("prompt must be a string");
416
+ } else {
417
+ const len = input.prompt.trim().length;
418
+ if (len < PROMPT_MIN_CHARS) errors.push(`prompt is too short (${len} chars; minimum ${PROMPT_MIN_CHARS})`);
419
+ if (len > PROMPT_MAX_CHARS) errors.push(`prompt is too long (${len} chars; maximum ${PROMPT_MAX_CHARS})`);
420
+ // 必备段落:产品声明红线,core 只检查「在不在」。
421
+ const lines = input.prompt.split("\n").map((l) => l.trimStart());
422
+ for (const section of product.personaRequiredSections.get(personaId) ?? []) {
423
+ if (!lines.some((l) => l.startsWith(section))) errors.push(`prompt is missing required section: ${section}`);
424
+ }
425
+ }
426
+ }
427
+
428
+ if (input.ui !== undefined) {
429
+ const problems: string[] = [];
430
+ parseUi(input.ui, "ui", problems);
431
+ errors.push(...problems);
432
+ }
433
+
434
+ if (input.disabledTools !== undefined) {
435
+ if (!Array.isArray(input.disabledTools) || input.disabledTools.some((t) => typeof t !== "string" || !t.trim())) {
436
+ errors.push("disabledTools must be a list of tool names");
437
+ } else if (product.personaAgents.get(personaId)?.allowTools !== undefined) {
438
+ // 有白名单时,停用项必须是白名单的子集——结构上保证「只能减」。
439
+ const allow = new Set(product.personaAgents.get(personaId)!.allowTools);
440
+ for (const t of input.disabledTools as string[]) {
441
+ if (!allow.has(t)) errors.push(`disabledTools: "${t}" is not in this persona's allowTools`);
442
+ }
443
+ }
444
+ }
445
+
446
+ return errors;
447
+ }