@njuptlzf/agent-chat-server 0.0.0-stage → 0.1.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/package.json +52 -4
- package/src/audit.ts +169 -0
- package/src/authz.ts +307 -0
- package/src/events.ts +206 -0
- package/src/index.ts +26 -0
- package/src/main.ts +142 -0
- package/src/manifest.ts +562 -0
- package/src/mcp-config.ts +385 -0
- package/src/model-config.ts +424 -0
- package/src/model-failover.ts +95 -0
- package/src/models-api.ts +360 -0
- package/src/persona-config.ts +436 -0
- package/src/persona-trial.ts +121 -0
- package/src/product-routes.ts +102 -0
- package/src/server.ts +2647 -0
- package/src/session.ts +688 -0
- package/src/sqlite-stores.ts +1040 -0
- package/src/stores.ts +899 -0
- package/src/testing.ts +81 -0
- package/src/trial-grant.ts +62 -0
- package/src/usage-report.ts +86 -0
- package/src/util.ts +6 -0
- package/README.md +0 -3
|
@@ -0,0 +1,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 { 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
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 人格「试跑」:用**还没保存的草稿**真调一次模型。
|
|
3
|
+
*
|
|
4
|
+
* 与「编译预览」的分界:预览回答"拼出来是什么"(免费、不建会话),试跑回答
|
|
5
|
+
* "它真的会怎么答"(花钱、真模型)。两者都要有——预览能看 prompt,看不出语气。
|
|
6
|
+
*
|
|
7
|
+
* 旁路(设计稿):**不写历史、不扣钱、不记 runLog、不占配额**。
|
|
8
|
+
* 只留一条 `admin.persona.trial` 审计(在 server.ts 的路由里写)。
|
|
9
|
+
* 理由是试跑是管理动作,不是用户消费:让它进用户账本会污染统计与限额。
|
|
10
|
+
*/
|
|
11
|
+
import type { TokenUsage } from "@njuptlzf/agent-chat-protocol";
|
|
12
|
+
import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
import { createEventMapper, emptyUsage } from "./events.ts";
|
|
14
|
+
import type { LoadedProduct, ToolContext } from "./manifest.ts";
|
|
15
|
+
import type { McpConfigStore } from "./mcp-config.ts";
|
|
16
|
+
import type { PersonaOverride } from "./persona-config.ts";
|
|
17
|
+
import { createProductSession, disposeProductSession } from "./session.ts";
|
|
18
|
+
|
|
19
|
+
/** 试跑最多等这么久:管理页不能因为模型卡住就永远转圈。 */
|
|
20
|
+
export const TRIAL_TIMEOUT_MS = 90_000;
|
|
21
|
+
/** 试跑输入上限:这是"试一句话",不是聊天窗口。 */
|
|
22
|
+
export const TRIAL_MAX_INPUT_CHARS = 2_000;
|
|
23
|
+
|
|
24
|
+
export interface TrialInput {
|
|
25
|
+
userId: string;
|
|
26
|
+
persona: string;
|
|
27
|
+
message: string;
|
|
28
|
+
/** 编辑器里的草稿;不传 = 用已保存的配置(与真实会话一致)。 */
|
|
29
|
+
override?: PersonaOverride;
|
|
30
|
+
qual?: string;
|
|
31
|
+
timeoutMs?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface TrialResult {
|
|
35
|
+
reply: string;
|
|
36
|
+
/** 声明给模型的工具名(与真实会话同一道白名单/停用过滤)。 */
|
|
37
|
+
tools: string[];
|
|
38
|
+
/** 这次运行里真的被调用过的工具。 */
|
|
39
|
+
usedTools: string[];
|
|
40
|
+
usage: TokenUsage;
|
|
41
|
+
ms: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 试跑需要的装配件(与 createChatServer 的 deps 同源,单独列出来便于测试)。 */
|
|
45
|
+
export interface TrialEnv {
|
|
46
|
+
product: LoadedProduct;
|
|
47
|
+
modelRuntime: ModelRuntime;
|
|
48
|
+
toolFactory: (ctx: ToolContext) => unknown[];
|
|
49
|
+
mcpConfig?: McpConfigStore;
|
|
50
|
+
dataDir: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 真跑一次。**复用 `createProductSession`**,所以 prompt、技能、工具白名单、
|
|
55
|
+
* MCP 可见性都与真实会话走同一条编译链——试跑看到的不是"另一套实现"。
|
|
56
|
+
*/
|
|
57
|
+
export async function runPersonaTrial(env: TrialEnv, input: TrialInput): Promise<TrialResult> {
|
|
58
|
+
const started = Date.now();
|
|
59
|
+
const tools = env.toolFactory({
|
|
60
|
+
productId: env.product.manifest.id,
|
|
61
|
+
productDir: env.product.dir,
|
|
62
|
+
userId: input.userId,
|
|
63
|
+
dataDir: env.dataDir,
|
|
64
|
+
qual: input.qual ?? "",
|
|
65
|
+
persona: input.persona,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
const session = await createProductSession({
|
|
69
|
+
product: env.product,
|
|
70
|
+
modelRuntime: env.modelRuntime,
|
|
71
|
+
tools,
|
|
72
|
+
userId: input.userId,
|
|
73
|
+
dataDir: env.dataDir,
|
|
74
|
+
qual: input.qual,
|
|
75
|
+
persona: input.persona,
|
|
76
|
+
personaOverride: input.override,
|
|
77
|
+
mcpConfig: env.mcpConfig,
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
const mapper = createEventMapper();
|
|
81
|
+
const texts: string[] = [];
|
|
82
|
+
const usedTools: string[] = [];
|
|
83
|
+
let modelError: string | undefined;
|
|
84
|
+
const unsubscribe = session.subscribe((event) => {
|
|
85
|
+
for (const out of mapper.map(event)) {
|
|
86
|
+
if (out.type === "message_end" && out.text) texts.push(out.text);
|
|
87
|
+
if (out.type === "tool_start") usedTools.push(out.name);
|
|
88
|
+
if (out.type === "error" && out.code === "model_error") modelError = out.message;
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
const timeoutMs = input.timeoutMs ?? TRIAL_TIMEOUT_MS;
|
|
93
|
+
let timedOut = false;
|
|
94
|
+
const timer = setTimeout(() => {
|
|
95
|
+
timedOut = true;
|
|
96
|
+
void session.abort();
|
|
97
|
+
}, timeoutMs);
|
|
98
|
+
let usage = emptyUsage();
|
|
99
|
+
let declared: string[] = [];
|
|
100
|
+
try {
|
|
101
|
+
await session.prompt(input.message);
|
|
102
|
+
await session.waitForIdle();
|
|
103
|
+
usage = mapper.totalUsage();
|
|
104
|
+
// 必须在 dispose 之前读:声明给模型的工具以会话实际装配为准。
|
|
105
|
+
declared = session.getActiveToolNames();
|
|
106
|
+
} finally {
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
unsubscribe();
|
|
109
|
+
await disposeProductSession(session);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (timedOut) throw new Error(`试跑超时(${Math.round(timeoutMs / 1000)} 秒),已中止`);
|
|
113
|
+
if (modelError) throw new Error(modelError);
|
|
114
|
+
return {
|
|
115
|
+
reply: texts.join("\n\n").trim(),
|
|
116
|
+
tools: declared,
|
|
117
|
+
usedTools,
|
|
118
|
+
usage,
|
|
119
|
+
ms: Date.now() - started,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 按 manifest 的 `server.routes` 声明**装配**产品业务路由。
|
|
3
|
+
*
|
|
4
|
+
* 装配逻辑放在 core 而非入口脚本中,是为了让形状校验可测:
|
|
5
|
+
* `createRoutes?.()` 在形状不对时若返回 undefined,会静默不挂任何产品路由、
|
|
6
|
+
* 服务照常起来而产品页面全线 404(fail-open)。
|
|
7
|
+
*
|
|
8
|
+
* 抽成 core 的两个函数后,三件事变得可测(进程内,不用 spawn 真进程):
|
|
9
|
+
* ① 形状校验:声明了 routes 就必须导出合法的 createRoutes(),
|
|
10
|
+
* 否则**抛错**(fail-closed:启动失败,不是静默空路由);
|
|
11
|
+
* ② init() 的错误必须往外传(不吞、不降级);
|
|
12
|
+
* ③ core 不 import 任何产品——路径是运行时从 manifest 读的,
|
|
13
|
+
* 动态 import 的 URL 是算出来的(静态 import 才会被边界守卫抓到)。
|
|
14
|
+
*/
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import { pathToFileURL } from "node:url";
|
|
17
|
+
import type { LoadedProduct } from "./manifest.ts";
|
|
18
|
+
import type { ProductAdminRoute, ProductRoute, ServerDeps } from "./server.ts";
|
|
19
|
+
|
|
20
|
+
/** 产品路由模块必须导出的形状(createRoutes() 的返回值)。 */
|
|
21
|
+
export interface ProductRouteModule {
|
|
22
|
+
/** 用户面路由。 */
|
|
23
|
+
routes: ProductRoute[];
|
|
24
|
+
/** 管理面路由(闸名与 core 内建组同一命名空间)。 */
|
|
25
|
+
admin: ProductAdminRoute[];
|
|
26
|
+
/** 启动期装配钩子(业务数据/索引之类)。可省略。 */
|
|
27
|
+
init?(deps: ServerDeps): void | Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 加载产品路由模块并校验形状。
|
|
32
|
+
*
|
|
33
|
+
* - manifest 没声明 `server.routes` ⇒ 返回 undefined(纯 core 部署,没有产品路由);
|
|
34
|
+
* - 声明了但文件不在/形状不对 ⇒ **抛错**(调用方据此启动失败)。
|
|
35
|
+
*
|
|
36
|
+
* 校验是逐项的,因为每个字段错了都会静默丢功能:
|
|
37
|
+
* routes 缺 createRoutes / 不是数组 ⇒ 产品业务路由全丢(页面 404);
|
|
38
|
+
* admin 写成别的键名 ⇒ 管理页 404;
|
|
39
|
+
* admin 条目少 match/group/handle ⇒ 闸判定错(可能放行或全拒)。
|
|
40
|
+
*/
|
|
41
|
+
export async function loadProductRoutes(product: LoadedProduct): Promise<ProductRouteModule | undefined> {
|
|
42
|
+
const rel = product.manifest.server?.routes;
|
|
43
|
+
if (!rel) return undefined;
|
|
44
|
+
const mod = (await import(pathToFileURL(path.resolve(product.dir, rel)).href)) as {
|
|
45
|
+
createRoutes?: unknown;
|
|
46
|
+
};
|
|
47
|
+
const create = mod?.createRoutes;
|
|
48
|
+
if (typeof create !== "function") {
|
|
49
|
+
throw new Error(`产品路由模块 ${rel} 必须导出 createRoutes()`);
|
|
50
|
+
}
|
|
51
|
+
const made = (create as () => unknown)();
|
|
52
|
+
if (!made || typeof made !== "object") {
|
|
53
|
+
throw new Error(`产品路由模块 ${rel} 的 createRoutes() 必须返回对象`);
|
|
54
|
+
}
|
|
55
|
+
const m = made as Partial<ProductRouteModule>;
|
|
56
|
+
if (!Array.isArray(m.routes)) {
|
|
57
|
+
throw new Error(`产品路由模块 ${rel} 的 createRoutes() 必须返回 { routes: [...] }`);
|
|
58
|
+
}
|
|
59
|
+
if (!Array.isArray(m.admin)) {
|
|
60
|
+
throw new Error(`产品路由模块 ${rel} 的 createRoutes() 必须返回 { admin: [...] }`);
|
|
61
|
+
}
|
|
62
|
+
for (const [i, r] of m.routes.entries()) {
|
|
63
|
+
if (typeof r !== "function") {
|
|
64
|
+
throw new Error(`产品路由模块 ${rel} 的 routes[${i}] 必须是函数`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
for (const [i, a] of m.admin.entries()) {
|
|
68
|
+
const bad = !a || typeof a.match !== "function" || typeof a.group !== "string" || typeof a.handle !== "function";
|
|
69
|
+
if (bad) {
|
|
70
|
+
throw new Error(`产品路由模块 ${rel} 的 admin[${i}] 必须是 { match(), group, handle() }`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (m.init !== undefined && typeof m.init !== "function") {
|
|
74
|
+
throw new Error(`产品路由模块 ${rel} 的 init 必须是函数(可省略)`);
|
|
75
|
+
}
|
|
76
|
+
return { routes: m.routes, admin: m.admin, init: m.init };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 调产品的 init() 钩子。**错误必须往外传**——产品装配失败就是启动失败,
|
|
81
|
+
* 不能吞掉降级成「起来了但业务数据是空的」(业务数据坏了该启动红,不是首请求 500)。
|
|
82
|
+
*/
|
|
83
|
+
export async function initProductRoutes(mod: ProductRouteModule | undefined, deps: ServerDeps): Promise<void> {
|
|
84
|
+
await mod?.init?.(deps);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 产品装配模块必须导出的形状:createProductStores(db) 返回要并入 ServerDeps 的产品 Store。 */
|
|
88
|
+
export type ProductAssembly = (db: unknown) => Record<string, unknown>;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 按 manifest 加载产品装配根(S4)。
|
|
92
|
+
* 未声明 ⇒ undefined(纯 core 部署);声明了但形状不对 ⇒ 抛错,启动失败而不是静默缺 Store。
|
|
93
|
+
*/
|
|
94
|
+
export async function loadProductAssembly(product: LoadedProduct): Promise<ProductAssembly | undefined> {
|
|
95
|
+
const rel = product.manifest.server?.assembly;
|
|
96
|
+
if (!rel) return undefined;
|
|
97
|
+
const mod = (await import(pathToFileURL(path.resolve(product.dir, rel)).href)) as { createProductStores?: unknown };
|
|
98
|
+
if (typeof mod.createProductStores !== "function") {
|
|
99
|
+
throw new Error(`产品装配模块 ${rel} 必须导出 createProductStores()`);
|
|
100
|
+
}
|
|
101
|
+
return mod.createProductStores as ProductAssembly;
|
|
102
|
+
}
|