@njuptlzf/agent-chat-server 0.1.1 → 0.2.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.
Files changed (65) hide show
  1. package/dist/audit.d.ts +54 -0
  2. package/dist/audit.js +133 -0
  3. package/dist/authz.d.ts +134 -0
  4. package/dist/authz.js +238 -0
  5. package/dist/events.d.ts +33 -0
  6. package/dist/events.js +169 -0
  7. package/dist/index.d.ts +16 -0
  8. package/dist/index.js +4 -0
  9. package/dist/main.d.ts +1 -0
  10. package/dist/main.js +126 -0
  11. package/dist/manifest.d.ts +147 -0
  12. package/dist/manifest.js +491 -0
  13. package/dist/mcp-config.d.ts +87 -0
  14. package/dist/mcp-config.js +353 -0
  15. package/dist/model-config.d.ts +123 -0
  16. package/dist/model-config.js +371 -0
  17. package/dist/model-failover.d.ts +42 -0
  18. package/dist/model-failover.js +82 -0
  19. package/dist/models-api.d.ts +98 -0
  20. package/dist/models-api.js +326 -0
  21. package/dist/persona-config.d.ts +112 -0
  22. package/dist/persona-config.js +368 -0
  23. package/dist/persona-trial.d.ts +50 -0
  24. package/dist/persona-trial.js +77 -0
  25. package/dist/product-routes.d.ts +35 -0
  26. package/dist/product-routes.js +92 -0
  27. package/dist/server.d.ts +162 -0
  28. package/dist/server.js +2572 -0
  29. package/dist/session.d.ts +218 -0
  30. package/dist/session.js +545 -0
  31. package/dist/sqlite-stores.d.ts +173 -0
  32. package/dist/sqlite-stores.js +921 -0
  33. package/dist/stores.d.ts +506 -0
  34. package/dist/stores.js +614 -0
  35. package/dist/testing.d.ts +42 -0
  36. package/dist/testing.js +47 -0
  37. package/dist/trial-grant.d.ts +40 -0
  38. package/dist/trial-grant.js +24 -0
  39. package/dist/usage-report.d.ts +23 -0
  40. package/dist/usage-report.js +68 -0
  41. package/dist/util.d.ts +3 -0
  42. package/dist/util.js +5 -0
  43. package/package.json +64 -58
  44. package/scripts/agentchat-integrate.mjs +607 -601
  45. package/src/audit.ts +169 -169
  46. package/src/authz.ts +307 -307
  47. package/src/events.ts +206 -206
  48. package/src/index.ts +26 -26
  49. package/src/main.ts +142 -142
  50. package/src/manifest.ts +562 -562
  51. package/src/mcp-config.ts +385 -385
  52. package/src/model-config.ts +424 -424
  53. package/src/model-failover.ts +95 -95
  54. package/src/models-api.ts +360 -360
  55. package/src/persona-config.ts +436 -436
  56. package/src/persona-trial.ts +121 -121
  57. package/src/product-routes.ts +102 -102
  58. package/src/server.ts +2647 -2647
  59. package/src/session.ts +688 -688
  60. package/src/sqlite-stores.ts +1040 -1040
  61. package/src/stores.ts +899 -899
  62. package/src/testing.ts +80 -80
  63. package/src/trial-grant.ts +62 -62
  64. package/src/usage-report.ts +86 -86
  65. package/src/util.ts +6 -6
@@ -0,0 +1,491 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { existsSync, readFileSync, statSync } from "node:fs";
10
+ import path from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { parse } from "yaml";
13
+ import { DEFAULT_PERSONA_ID, PERSONA_UI_FIELDS } from "@njuptlzf/agent-chat-protocol";
14
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
15
+ const TIER_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
16
+ const QUAL_LEVELS = ["junior", "middle", "senior"];
17
+ const QUAL_SUBJECTS = ["mcq", "case", "essay", "code"];
18
+ function fail(file, msg) {
19
+ throw new Error(`Invalid manifest ${file}: ${msg}`);
20
+ }
21
+ /**
22
+ * 校验人格的展示文案。空字符串一律拒——`label: ""` 会让侧栏出现一个
23
+ * 看不见的按钮,比缺字段难查得多;缺字段才走前端回落。
24
+ */
25
+ function loadPersonaUi(file, at, raw) {
26
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
27
+ fail(file, `\`${at}\` must be a mapping`);
28
+ const src = raw;
29
+ const allowed = [...PERSONA_UI_FIELDS];
30
+ for (const key of Object.keys(src)) {
31
+ if (!allowed.includes(key))
32
+ fail(file, `\`${at}.${key}\` is not a display field (allowed: ${allowed.join(", ")})`);
33
+ }
34
+ const out = {};
35
+ for (const key of ["label", "icon", "tag", "hint", "welcome", "policyNote"]) {
36
+ const v = src[key];
37
+ if (v === undefined)
38
+ continue;
39
+ if (typeof v !== "string" || v.trim() === "")
40
+ fail(file, `\`${at}.${key}\` must be a non-empty string`);
41
+ out[key] = v;
42
+ }
43
+ if (src.suggestions !== undefined) {
44
+ if (!Array.isArray(src.suggestions) || src.suggestions.some((s) => typeof s !== "string" || !s.trim())) {
45
+ fail(file, `\`${at}.suggestions\` must be a list of non-empty strings`);
46
+ }
47
+ out.suggestions = src.suggestions;
48
+ }
49
+ return out;
50
+ }
51
+ /**
52
+ * Validate `agent.tiers` in place. Tiers are the only thing the UI may choose
53
+ * between, so a malformed list is a startup error, not a runtime surprise.
54
+ */
55
+ function loadTiers(file, manifest) {
56
+ const tiers = manifest.agent.tiers;
57
+ if (tiers === undefined)
58
+ return;
59
+ if (!Array.isArray(tiers) || tiers.length === 0)
60
+ fail(file, "`agent.tiers` must be a non-empty list");
61
+ const seen = new Set();
62
+ for (const [i, t] of tiers.entries()) {
63
+ const at = `agent.tiers[${i}]`;
64
+ if (!t || typeof t !== "object")
65
+ fail(file, `${at} must be a mapping`);
66
+ if (typeof t.id !== "string" || !TIER_ID.test(t.id))
67
+ fail(file, `${at}.id must be lowercase letters, digits and dashes`);
68
+ if (seen.has(t.id))
69
+ fail(file, `${at}.id "${t.id}" is duplicated`);
70
+ seen.add(t.id);
71
+ if (typeof t.label !== "string" || t.label.trim() === "")
72
+ fail(file, `${at}.label must be a non-empty string`);
73
+ if (t.description !== undefined && typeof t.description !== "string")
74
+ fail(file, `${at}.description must be a string`);
75
+ if (t.model !== undefined && (typeof t.model !== "string" || t.model.trim() === ""))
76
+ fail(file, `${at}.model must be a non-empty string`);
77
+ if (t.thinking !== undefined && !THINKING_LEVELS.includes(t.thinking)) {
78
+ fail(file, `${at}.thinking must be one of ${THINKING_LEVELS.join(", ")}`);
79
+ }
80
+ if (typeof t.multiplier !== "number" || !Number.isFinite(t.multiplier) || t.multiplier <= 0) {
81
+ fail(file, `${at}.multiplier must be a positive number`);
82
+ }
83
+ }
84
+ }
85
+ /**
86
+ * Validate `quals` in place (V0). The list drives navigation and the question
87
+ * bank layout, so a malformed entry is a startup error: an unknown subject would
88
+ * silently render no page, and a duplicate id would silently shadow a bank.
89
+ */
90
+ function loadQuals(file, manifest) {
91
+ const quals = manifest.quals;
92
+ if (quals === undefined)
93
+ return;
94
+ if (!Array.isArray(quals) || quals.length === 0)
95
+ fail(file, "`quals` must be a non-empty list");
96
+ const seen = new Set();
97
+ for (const [i, q] of quals.entries()) {
98
+ const at = `quals[${i}]`;
99
+ if (!q || typeof q !== "object")
100
+ fail(file, `${at} must be a mapping`);
101
+ if (typeof q.id !== "string" || !TIER_ID.test(q.id))
102
+ fail(file, `${at}.id must be lowercase letters, digits and dashes`);
103
+ if (seen.has(q.id))
104
+ fail(file, `${at}.id "${q.id}" is duplicated`);
105
+ seen.add(q.id);
106
+ if (typeof q.level !== "string" || !QUAL_LEVELS.includes(q.level))
107
+ fail(file, `${at}.level must be one of ${QUAL_LEVELS.join(", ")}`);
108
+ if (typeof q.label !== "string" || q.label.trim() === "")
109
+ fail(file, `${at}.label must be a non-empty string`);
110
+ if (q.direction !== undefined && typeof q.direction !== "string")
111
+ fail(file, `${at}.direction must be a string`);
112
+ if (!Array.isArray(q.subjects) || q.subjects.length === 0)
113
+ fail(file, `${at}.subjects must be a non-empty list`);
114
+ for (const s of q.subjects) {
115
+ if (!QUAL_SUBJECTS.includes(s))
116
+ fail(file, `${at}.subjects entries must be one of ${QUAL_SUBJECTS.join(", ")}`);
117
+ }
118
+ if (new Set(q.subjects).size !== q.subjects.length)
119
+ fail(file, `${at}.subjects has duplicates`);
120
+ if (q.enabled !== undefined && typeof q.enabled !== "boolean")
121
+ fail(file, `${at}.enabled must be a boolean`);
122
+ // Per-qualification agent overrides (S1). A typo here would silently keep the
123
+ // product-wide default persona where the operator meant a specialist, so the shape is
124
+ // checked at startup like every other manifest promise.
125
+ if (q.agent !== undefined) {
126
+ if (!q.agent || typeof q.agent !== "object" || Array.isArray(q.agent))
127
+ fail(file, `${at}.agent must be a mapping`);
128
+ // Only the two fields the decision allows. An unrecognised key (a mistyped
129
+ // `system_prompt:`) must not silently keep the product-wide default persona.
130
+ for (const k of Object.keys(q.agent)) {
131
+ if (k !== "systemPrompt" && k !== "skills")
132
+ fail(file, `${at}.agent allows only systemPrompt and skills (got "${k}")`);
133
+ }
134
+ if (q.agent.systemPrompt !== undefined && (typeof q.agent.systemPrompt !== "string" || q.agent.systemPrompt.trim() === "")) {
135
+ fail(file, `${at}.agent.systemPrompt must be a non-empty path`);
136
+ }
137
+ if (q.agent.skills !== undefined && (!Array.isArray(q.agent.skills) || !q.agent.skills.every((p) => typeof p === "string" && p.trim() !== ""))) {
138
+ fail(file, `${at}.agent.skills must be a list of non-empty paths`);
139
+ }
140
+ }
141
+ }
142
+ }
143
+ /**
144
+ * Resolve a `ChatRequest.tier` against the manifest.
145
+ *
146
+ * Returns undefined when the id is unknown, which the caller turns into a 400.
147
+ * Omitting the id is always valid and means the manifest's `agent.model`.
148
+ */
149
+ export function resolveTier(product, tierId) {
150
+ const base = product.manifest.agent.model;
151
+ const fallback = {
152
+ provider: base.provider,
153
+ model: base.id,
154
+ thinking: base.thinking ?? "off",
155
+ multiplier: 1,
156
+ };
157
+ if (tierId === undefined)
158
+ return fallback;
159
+ const tier = product.manifest.agent.tiers?.find((t) => t.id === tierId);
160
+ if (!tier)
161
+ return undefined;
162
+ return {
163
+ id: tier.id,
164
+ label: tier.label,
165
+ provider: base.provider,
166
+ model: tier.model ?? base.id,
167
+ thinking: tier.thinking ?? base.thinking ?? "off",
168
+ multiplier: tier.multiplier,
169
+ };
170
+ }
171
+ /**
172
+ * The effective default persona for one qualification (S1): its declared override when it
173
+ * has one (already resolved against the product defaults at load time), the
174
+ * product level otherwise. This is the only place that knows the fallback rule.
175
+ */
176
+ /**
177
+ * Which prompt/skills a run uses. Precedence: **persona > qual > product**.
178
+ *
179
+ * Persona wins because a secondary assistant is not per-exam — it answers
180
+ * account questions, and giving it an exam-specific prompt would be wrong.
181
+ * Unknown persona falls back to the product default; validating the id is the
182
+ * endpoint's job (400), not this lookup's.
183
+ *
184
+ * The product's default assistant is addressed by `product.defaultPersona`
185
+ * (): that id is **not** a persona override, so it resolves to the
186
+ * product/qual default like "no persona at all" would.
187
+ */
188
+ export function agentFor(product, qual, persona) {
189
+ if (persona !== undefined && persona !== "") {
190
+ const byPersona = product.personaAgents.get(persona);
191
+ if (byPersona)
192
+ return byPersona;
193
+ }
194
+ return (qual !== undefined && product.qualAgents.get(qual)) || product;
195
+ }
196
+ /**
197
+ * The ids a client may send as `persona` (通用化): the product's default
198
+ * assistant plus every declared persona. The endpoint validates against this
199
+ * set — core knows no persona id of its own.
200
+ */
201
+ export function personaIdsOf(product) {
202
+ return new Set([product.defaultPersona, ...product.personaAgents.keys()]);
203
+ }
204
+ /** Resolve a manifest-declared path against the product directory; leave bare commands alone. */
205
+ function resolveMaybePath(absDir, p) {
206
+ return /[/\\]/.test(p) ? path.resolve(absDir, p) : p;
207
+ }
208
+ /**
209
+ * Validate `mcp` declarations and resolve product-relative paths. pi's own
210
+ * config validation runs later (validateMcpServerConfig); this only guards the
211
+ * shape we promise in the manifest type.
212
+ */
213
+ function loadMcpDecls(file, absDir, decls) {
214
+ if (!decls)
215
+ return undefined;
216
+ const out = {};
217
+ for (const [name, raw] of Object.entries(decls)) {
218
+ if (!/^[a-z0-9][a-z0-9_-]*$/i.test(name))
219
+ fail(file, `mcp server name "${name}" must be letters, digits, dashes or underscores`);
220
+ if (!raw || typeof raw !== "object")
221
+ fail(file, `mcp.${name} must be a mapping`);
222
+ const d = raw;
223
+ const hasStdio = typeof d.command === "string" && d.command.length > 0;
224
+ const hasHttp = typeof d.url === "string" && d.url.length > 0;
225
+ const hasOpenapi = d.type === "openapi" || (d.type === undefined && !!d.openapi && !hasStdio && !hasHttp);
226
+ if (!hasStdio && !hasHttp && !hasOpenapi)
227
+ fail(file, `mcp.${name} needs a "command" (stdio), a "url" (http) or an "openapi" block`);
228
+ if ((hasStdio ? 1 : 0) + (hasHttp ? 1 : 0) + (hasOpenapi ? 1 : 0) > 1)
229
+ fail(file, `mcp.${name} has more than one of command/url/openapi`);
230
+ if (hasOpenapi && !/^https?:\/\//.test(d.openapi?.specUrl ?? ""))
231
+ fail(file, `mcp.${name}.openapi.specUrl must be an absolute http(s) URL`);
232
+ // "codemode"/"deferred" would silently disable the tools: this session loads only the mcp
233
+ // built-in extension, never codemode or tool-search (upstream activates a reaching tool only if
234
+ // it is already loaded — otherwise the tools stay undeclared with nothing but a log warning).
235
+ if (d.exposure === "codemode" || d.exposure === "deferred")
236
+ fail(file, `mcp.${name}: exposure "${d.exposure}" is not supported here; use "direct" or "hidden"`);
237
+ out[name] = {
238
+ ...d,
239
+ command: hasStdio ? resolveMaybePath(absDir, d.command) : undefined,
240
+ args: hasStdio ? d.args?.map((a) => resolveMaybePath(absDir, a)) : undefined,
241
+ cwd: hasStdio && d.cwd ? path.resolve(absDir, d.cwd) : undefined,
242
+ url: hasHttp ? d.url : undefined,
243
+ };
244
+ }
245
+ return out;
246
+ }
247
+ export function loadProduct(dir) {
248
+ const absDir = path.resolve(dir);
249
+ const file = path.join(absDir, "manifest.yaml");
250
+ const raw = parse(readFileSync(file, "utf8"));
251
+ if (!raw || typeof raw !== "object")
252
+ fail(file, "file is empty or not a YAML mapping");
253
+ if (!raw.id || !/^[a-z0-9][a-z0-9-]*$/.test(raw.id))
254
+ fail(file, "`id` must be lowercase letters, digits and dashes");
255
+ if (!raw.branding?.title)
256
+ fail(file, "`branding.title` is required");
257
+ if (!raw.agent?.systemPrompt)
258
+ fail(file, "`agent.systemPrompt` is required");
259
+ if (!raw.agent.model?.provider || !raw.agent.model?.id)
260
+ fail(file, "`agent.model.provider` and `agent.model.id` are required");
261
+ const manifest = raw;
262
+ // 业务路由声明。与 tools.inline / extensions 同级信任(仓库内代码),但
263
+ // 路径必须留在产品目录内——写 `../` 逃出去等于让 manifest 加载任意文件。
264
+ if (manifest.server?.routes !== undefined) {
265
+ const rel = manifest.server.routes;
266
+ if (typeof rel !== "string" || !rel.startsWith("./") || !rel.endsWith(".ts")) {
267
+ fail(file, "`server.routes` must be a string like \"./server/routes.ts\"");
268
+ }
269
+ const resolved = path.resolve(absDir, rel);
270
+ if (!resolved.startsWith(path.resolve(absDir) + path.sep) || !existsSync(resolved)) {
271
+ fail(file, `server.routes "${rel}" must be an existing .ts file inside the product directory`);
272
+ }
273
+ }
274
+ // S4:产品装配根声明,与 routes 同款校验(写 ../ 逃出产品目录 = 加载任意文件)。
275
+ if (manifest.server?.assembly !== undefined) {
276
+ const rel = manifest.server.assembly;
277
+ if (typeof rel !== "string" || !rel.startsWith("./") || !rel.endsWith(".ts")) {
278
+ fail(file, "`server.assembly` must be a string like \"./server/assembly.ts\"");
279
+ }
280
+ const resolved = path.resolve(absDir, rel);
281
+ if (!resolved.startsWith(path.resolve(absDir) + path.sep) || !existsSync(resolved)) {
282
+ fail(file, `server.assembly "${rel}" must be an existing .ts file inside the product directory`);
283
+ }
284
+ }
285
+ // pi 包通道:`agent.extensionPackages` **未开**。
286
+ // 以前写这个字段会被 YAML 静默保留、代码不认识也不报错——运维会以为生效了。
287
+ // 启动期直接拒绝,比"看起来支持"安全:想开通道,先过审核清单 + 改这一行。
288
+ if (manifest.agent.extensionPackages !== undefined) {
289
+ fail(file, "`agent.extensionPackages` is not enabled: this build only loads repo-reviewed files via `agent.extensions`");
290
+ }
291
+ manifest.mcp = loadMcpDecls(file, absDir, raw.mcp);
292
+ if (manifest.confirmTools !== undefined) {
293
+ if (!Array.isArray(manifest.confirmTools) || !manifest.confirmTools.every((t) => typeof t === "string" && t.trim() !== "")) {
294
+ fail(file, "`confirmTools` must be a list of non-empty tool names");
295
+ }
296
+ }
297
+ const maxRounds = manifest.agent.limits?.maxToolRounds;
298
+ if (maxRounds !== undefined && (!Number.isInteger(maxRounds) || maxRounds < 1)) {
299
+ fail(file, "`agent.limits.maxToolRounds` must be a positive integer");
300
+ }
301
+ // Extensions execute in-process with full privileges, so a malformed entry is a
302
+ // startup error: the operator must see a typo, not a silently skipped module.
303
+ // Entries must be files: pi resolves an additional path that is a directory by
304
+ // looking for package.json's `pi.extensions` or its own resource subdirectories,
305
+ // so a directory of loose .ts files would fail deep inside jiti with a bare
306
+ // "Cannot find module". Rejecting it here keeps the error where the operator is.
307
+ if (manifest.agent.extensions !== undefined) {
308
+ if (!Array.isArray(manifest.agent.extensions) || !manifest.agent.extensions.every((p) => typeof p === "string" && p.trim() !== "")) {
309
+ fail(file, "`agent.extensions` must be a list of non-empty paths");
310
+ }
311
+ for (const p of manifest.agent.extensions) {
312
+ const abs = path.resolve(absDir, p);
313
+ if (!existsSync(abs) || !statSync(abs).isFile()) {
314
+ fail(file, `\`agent.extensions\` entry "${p}" must be an existing file (resolved: ${abs})`);
315
+ }
316
+ }
317
+ }
318
+ if (manifest.agent.memory !== undefined && typeof manifest.agent.memory !== "boolean") {
319
+ fail(file, "`agent.memory` must be a boolean");
320
+ }
321
+ loadTiers(file, manifest);
322
+ loadQuals(file, manifest);
323
+ if (manifest.billing !== undefined) {
324
+ const b = manifest.billing;
325
+ const prices = [];
326
+ if (b.pricePerThousandTokensCents !== undefined)
327
+ prices.push(b.pricePerThousandTokensCents);
328
+ if (b.toolPricesCents !== undefined) {
329
+ if (typeof b.toolPricesCents !== "object" || b.toolPricesCents === null || Array.isArray(b.toolPricesCents)) {
330
+ fail(file, "`billing.toolPricesCents` must be a mapping of tool name to cents");
331
+ }
332
+ for (const [name, v] of Object.entries(b.toolPricesCents)) {
333
+ if (!name.trim())
334
+ fail(file, "`billing.toolPricesCents` keys must be non-empty tool names");
335
+ prices.push(v);
336
+ }
337
+ }
338
+ // 只卖会员套餐、不按 token 计价的产品也是合法的(prices 为空但有 plans)。
339
+ const planIds = Object.keys(b.plans ?? {});
340
+ if (prices.length === 0 && planIds.length === 0) {
341
+ fail(file, "`billing` needs `pricePerThousandTokensCents`, `toolPricesCents` and/or `plans`");
342
+ }
343
+ if (prices.some((v) => !Number.isInteger(v) || v <= 0))
344
+ fail(file, "`billing` prices must be positive integer cents");
345
+ if (b.mockAutoFulfill !== undefined && typeof b.mockAutoFulfill !== "boolean") {
346
+ fail(file, "`billing.mockAutoFulfill` must be a boolean");
347
+ }
348
+ if (b.plans !== undefined) {
349
+ if (typeof b.plans !== "object" || b.plans === null || Array.isArray(b.plans)) {
350
+ fail(file, "`billing.plans` must be a mapping of persona id to { days, priceCents }");
351
+ }
352
+ for (const [id, plan] of Object.entries(b.plans)) {
353
+ if (!/^[a-z][a-z0-9_-]*$/.test(id))
354
+ fail(file, `billing.plans key "${id}" must be lower-case letters, digits, dashes or underscores`);
355
+ if (typeof plan !== "object" || plan === null || Array.isArray(plan)) {
356
+ fail(file, `billing.plans.${id} must be an object`);
357
+ }
358
+ if (!Number.isInteger(plan.days) || plan.days < 1 || plan.days > 3650) {
359
+ fail(file, `billing.plans.${id}.days must be an integer between 1 and 3650`);
360
+ }
361
+ if (!Number.isInteger(plan.priceCents) || plan.priceCents < 1) {
362
+ fail(file, `billing.plans.${id}.priceCents must be a positive integer (cents)`);
363
+ }
364
+ }
365
+ }
366
+ }
367
+ const resolve = (p) => path.resolve(absDir, p);
368
+ const systemPromptText = readFileSync(resolve(manifest.agent.systemPrompt), "utf8");
369
+ const skillDirs = (manifest.agent.skills ?? []).map(resolve);
370
+ // Per-qualification overrides (S1) resolve eagerly: a missing prompt file must
371
+ // fail at startup, not on the first chat of that qualification. Omitted fields
372
+ // bake in the product default, so lookups never branch afterwards.
373
+ const qualAgents = new Map();
374
+ for (const q of manifest.quals ?? []) {
375
+ if (!q.agent)
376
+ continue;
377
+ qualAgents.set(q.id, {
378
+ systemPromptText: q.agent.systemPrompt ? readFileSync(resolve(q.agent.systemPrompt), "utf8") : systemPromptText,
379
+ skillDirs: q.agent.skills ? q.agent.skills.map(resolve) : skillDirs,
380
+ });
381
+ }
382
+ // Per-persona overrides (). `skills` omitted ⇒ 空数组,**不继承产品技能**:
383
+ // 声明人格继承默认助手的技能就会开始答业务题,那正是拆分要挡的事。
384
+ const personaAgents = new Map();
385
+ // 展示文案单独一张表:UI 层只读它,能力面进不了 /api/branding。
386
+ const personaUi = new Map();
387
+ for (const [id, p] of Object.entries(manifest.agent.personas ?? {})) {
388
+ if (!/^[a-z][a-z0-9_-]*$/.test(id))
389
+ fail(file, `agent.personas key "${id}" must be lower-case letters, digits, dashes or underscores`);
390
+ if (p.allowTools !== undefined) {
391
+ if (!Array.isArray(p.allowTools) || p.allowTools.some((t) => typeof t !== "string" || !t.trim())) {
392
+ fail(file, `agent.personas.${id}.allowTools must be a list of tool names`);
393
+ }
394
+ }
395
+ personaAgents.set(id, {
396
+ systemPromptText: readFileSync(resolve(p.systemPrompt), "utf8"),
397
+ skillDirs: (p.skills ?? []).map(resolve),
398
+ // 空数组是合法且有意义的值(「一个工具都不给」),所以只在声明时带出来。
399
+ ...(p.allowTools !== undefined ? { allowTools: p.allowTools } : {}),
400
+ });
401
+ if (p.ui !== undefined)
402
+ personaUi.set(id, loadPersonaUi(file, `agent.personas.${id}.ui`, p.ui));
403
+ }
404
+ // 默认助手的人格 id(通用化):**产品事实**,不是 core 事实。
405
+ // core 以前把两个具体 id 写死在 `Persona` 联合类型与路由校验里,换产品就得改 core;
406
+ // 现在由 manifest 声明,core 只校验「声明得像不像 id」「会不会撞车」。
407
+ const defaultPersona = manifest.agent.defaultPersona ?? DEFAULT_PERSONA_ID;
408
+ if (!/^[a-z][a-z0-9_-]*$/.test(defaultPersona)) {
409
+ fail(file, `agent.defaultPersona "${defaultPersona}" must be lower-case letters, digits, dashes or underscores`);
410
+ }
411
+ if (personaAgents.has(defaultPersona)) {
412
+ // 同一个 id 既是「默认助手」又是「某个人格的覆盖」,语义二义 ⇒ 启动期拒绝。
413
+ fail(file, `agent.defaultPersona "${defaultPersona}" must not also be declared in agent.personas`);
414
+ }
415
+ // 套餐键必须是本产品声明过的人格:写错一个字母就是"永远买不了",启动期就该红。
416
+ const declaredPersonas = new Set([defaultPersona, ...personaAgents.keys()]);
417
+ for (const id of Object.keys(manifest.billing?.plans ?? {})) {
418
+ if (!declaredPersonas.has(id)) {
419
+ fail(file, `billing.plans.${id} is not a declared persona (agent.defaultPersona / agent.personas)`);
420
+ }
421
+ }
422
+ // 必备段落:默认助手用产品级,各人格可用自己的覆盖,未声明则继承产品级。
423
+ const sectionList = (raw, at) => {
424
+ if (raw === undefined)
425
+ return [];
426
+ if (!Array.isArray(raw) || raw.some((s) => typeof s !== "string" || s.trim() === "")) {
427
+ fail(file, `${at} must be a list of non-empty strings`);
428
+ }
429
+ return raw;
430
+ };
431
+ const productSections = sectionList(manifest.agent.requiredSections, "agent.requiredSections");
432
+ const personaRequiredSections = new Map();
433
+ personaRequiredSections.set(defaultPersona, productSections);
434
+ for (const [id, p] of Object.entries(manifest.agent.personas ?? {})) {
435
+ personaRequiredSections.set(id, p.requiredSections === undefined ? productSections : sectionList(p.requiredSections, `agent.personas.${id}.requiredSections`));
436
+ }
437
+ // With `quals` the bank is one dir per qualification; without it the single
438
+ // conventional dir serves the product's only track (empty key).
439
+ const questionDirs = new Map((manifest.quals ?? []).map((q) => [q.id, path.join(absDir, "questions", q.id)]));
440
+ if (questionDirs.size === 0)
441
+ questionDirs.set("", path.join(absDir, "questions"));
442
+ const caseDirs = new Map((manifest.quals ?? []).map((q) => [q.id, path.join(absDir, "cases", q.id)]));
443
+ if (caseDirs.size === 0)
444
+ caseDirs.set("", path.join(absDir, "cases"));
445
+ const essayDirs = new Map((manifest.quals ?? []).map((q) => [q.id, path.join(absDir, "essays", q.id)]));
446
+ if (essayDirs.size === 0)
447
+ essayDirs.set("", path.join(absDir, "essays"));
448
+ const paperDirs = new Map((manifest.quals ?? []).map((q) => [q.id, path.join(absDir, "papers", q.id)]));
449
+ if (paperDirs.size === 0)
450
+ paperDirs.set("", path.join(absDir, "papers"));
451
+ // 插图(2026-11-05):与 questions/ 平级、按 qual 分目录——重名图(各场次都有
452
+ // 「img2.png」)天然隔离,删一个选项不会碰到另一个。
453
+ const figureDirs = new Map((manifest.quals ?? []).map((q) => [q.id, path.join(absDir, "figures", q.id)]));
454
+ if (figureDirs.size === 0)
455
+ figureDirs.set("", path.join(absDir, "figures"));
456
+ return {
457
+ manifest,
458
+ dir: absDir,
459
+ manifestFile: file,
460
+ systemPromptText,
461
+ skillDirs,
462
+ extensionPaths: (manifest.agent.extensions ?? []).map(resolve),
463
+ memoryEnabled: manifest.agent.memory !== false,
464
+ questionDirs,
465
+ caseDirs,
466
+ essayDirs,
467
+ paperDirs,
468
+ figureDirs,
469
+ qualAgents,
470
+ personaAgents,
471
+ personaUi,
472
+ defaultPersona,
473
+ personaRequiredSections,
474
+ defaultQual: manifest.quals?.[0]?.id ?? "",
475
+ toolsModulePath: manifest.tools?.inline ? resolve(manifest.tools.inline) : undefined,
476
+ };
477
+ }
478
+ /**
479
+ * Load the product's inline tools. The module's default export is
480
+ * `(ctx: ToolContext) => ToolDefinition[]`, called once per session so tools
481
+ * can close over the current user.
482
+ */
483
+ export async function loadToolFactory(product) {
484
+ if (!product.toolsModulePath)
485
+ return () => [];
486
+ const mod = await import(__rewriteRelativeImportExtension(pathToFileURL(product.toolsModulePath).href));
487
+ if (typeof mod.default !== "function") {
488
+ throw new Error(`${product.toolsModulePath} must default-export a function (ctx) => ToolDefinition[]`);
489
+ }
490
+ return mod.default;
491
+ }
@@ -0,0 +1,87 @@
1
+ import type { McpServerDecl } from "@njuptlzf/agent-chat-protocol";
2
+ import type { LoadedProduct } from "./manifest.ts";
3
+ export declare const MCP_CONFIG_FILENAME = "mcp-config.json";
4
+ /** 代理可执行文件的部署级覆盖(PyPI 装在用户 Scripts 目录,Windows 服务账号 PATH 未必有)。 */
5
+ export declare const MCP_PROXY_BIN_ENV = "MCP_PROXY_BIN";
6
+ /** spec/baseUrl 的 host 白名单(逗号分隔,`*.d` 通配域及其子域);不设 = 全放(4)。 */
7
+ export declare const MCP_SPEC_ALLOWLIST_ENV = "MCP_SPEC_ALLOWLIST";
8
+ export interface McpConfig {
9
+ version: 1;
10
+ servers: Record<string, McpServerDecl>;
11
+ source: "file" | "manifest";
12
+ problems: string[];
13
+ }
14
+ export declare function isHttpUrl(v: unknown): v is string;
15
+ /** 一条 entry 的形状检查。返回 null = 合法;字符串 = 问题描述(调用方决定 fail 还是丢+记名)。 */
16
+ export declare function checkMcpDecl(name: string, raw: unknown): string | null;
17
+ /** 文件形状 → 内存形状。root 不是对象 ⇒ null(store 回落 manifest)。坏 entry 丢弃并记 problems。 */
18
+ export declare function parseMcpConfig(raw: unknown): {
19
+ servers: Record<string, McpServerDecl> | null;
20
+ problems: string[];
21
+ };
22
+ /** manifest 的 `mcp:` 段 → 同款形状(source:"manifest")。 */
23
+ export declare function manifestMcpConfig(product: LoadedProduct, problems?: string[]): McpConfig;
24
+ /** 内存 → 文件(只写已知字段;source/problems 是运行时态,不落盘)。 */
25
+ export declare function serializeMcpConfig(cfg: McpConfig): Record<string, unknown>;
26
+ export interface McpConfigStore {
27
+ /** 配置文件的绝对路径(管理页显示「去改哪个文件」)。 */
28
+ readonly path: string;
29
+ /** 读当前生效配置(1 秒级缓存,mtime/size 变了才重解析)。 */
30
+ get(): McpConfig;
31
+ /** 主动作废缓存——端点写完立刻生效。 */
32
+ invalidate(): void;
33
+ }
34
+ export interface McpConfigStoreOptions {
35
+ now?: () => number;
36
+ warn?: (message: string) => void;
37
+ }
38
+ export declare function createMcpConfigStore(dataDir: string, product: LoadedProduct, opts?: McpConfigStoreOptions): McpConfigStore;
39
+ /** 原子写(同款:tmp + rename,崩了不留半个 JSON),写完作废缓存。 */
40
+ export declare function saveMcpConfig(store: McpConfigStore, cfg: McpConfig): void;
41
+ /**
42
+ * 4:`MCP_SPEC_ALLOWLIST` 不设 = 全放(含内网——私有化接内网 API 是主场景);
43
+ * 设了 = specUrl/baseUrl 的 host 必须命中。项逗号分隔;`*.d` 匹配 d 本身及其子域;
44
+ * 非 http(s) scheme 一律拒。纯函数,probe/保存两条路共用。
45
+ */
46
+ export declare function specUrlAllowed(url: string, allowlist: string | undefined | null): boolean;
47
+ /**
48
+ * openapi entry → mcp-openapi-proxy 的 stdio spawn 形状(翻译层)。
49
+ * 密钥只在 spawn 时从宿主 env 取(valueEnv 存的是**变量名**,配置里永远没有密钥本体)。
50
+ * MCP_PROXY_BIN 允许带参数(`node C:/fake/proxy.mjs`——测试与 python -m 场景都用得上;
51
+ * ponytail: 按空白切分,路径含空格的解释器请放短路径或用 PATH 查找)。
52
+ */
53
+ export declare function toProxySpawn(decl: McpServerDecl, id: string, env?: Record<string, string | undefined>): {
54
+ command: string;
55
+ args: string[];
56
+ env: Record<string, string>;
57
+ };
58
+ export interface McpProbeTool {
59
+ name: string;
60
+ description: string;
61
+ /** 工具名首段推的 HTTP 方法(代理命名 = `<method>_<path>`,spike);推不出来给 "?"。 */
62
+ method: string;
63
+ /** inputSchema.properties 的键。写操作灰标判定用(非 GET 且空 = $ref 请求体被吞)。 */
64
+ params: string[];
65
+ }
66
+ export interface McpProbeResult {
67
+ ok: boolean;
68
+ tools?: McpProbeTool[];
69
+ tookMs?: number;
70
+ /** 人话错误(502 回显用);**不含 stderr 原文**(可能带路径/内部信息)。 */
71
+ error?: string;
72
+ }
73
+ /** `<method>_<path>` → method。推不出来给 "?"(页面据此保守处理,不假装知道)。 */
74
+ export declare function methodOfToolName(name: string): string;
75
+ /** tools/list 的一条 → 页面要的形状。inputSchema 缺/坏都给空参数表(永不抛)。 */
76
+ export declare function toProbeTool(raw: unknown): McpProbeTool;
77
+ /**
78
+ * 试连:spawn 代理 → initialize → tools/list → 立刻杀掉进程。
79
+ * 预算 10s(口径;spike 里首连要拉 spec,>3s 是常态,留 3 倍余量)。纯 stdio
80
+ * JSON-RPC,无网络依赖——网络在代理进程内部发生,这里只看它回不回话。
81
+ */
82
+ export declare function probeMcpProxy(decl: McpServerDecl, id: string, opts?: {
83
+ env?: Record<string, string | undefined>;
84
+ timeoutMs?: number;
85
+ }): Promise<McpProbeResult>;
86
+ /** entry.labels → tools_meta 的全名键(mcp__<id>__<tool>),盖在 manifest.toolLabels 之上。 */
87
+ export declare function mergedToolLabels(cfg: McpConfig | undefined, manifestLabels: Record<string, string> | undefined): Record<string, string>;