@njuptlzf/agent-chat-server 0.1.2 → 0.2.1
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/dist/audit.d.ts +54 -0
- package/dist/audit.js +133 -0
- package/dist/authz.d.ts +134 -0
- package/dist/authz.js +238 -0
- package/dist/events.d.ts +33 -0
- package/dist/events.js +169 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +4 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +126 -0
- package/dist/manifest.d.ts +147 -0
- package/dist/manifest.js +491 -0
- package/dist/mcp-config.d.ts +87 -0
- package/dist/mcp-config.js +353 -0
- package/dist/model-config.d.ts +123 -0
- package/dist/model-config.js +371 -0
- package/dist/model-failover.d.ts +42 -0
- package/dist/model-failover.js +82 -0
- package/dist/models-api.d.ts +98 -0
- package/dist/models-api.js +326 -0
- package/dist/persona-config.d.ts +112 -0
- package/dist/persona-config.js +368 -0
- package/dist/persona-trial.d.ts +50 -0
- package/dist/persona-trial.js +77 -0
- package/dist/product-routes.d.ts +35 -0
- package/dist/product-routes.js +92 -0
- package/dist/server.d.ts +162 -0
- package/dist/server.js +2572 -0
- package/dist/session.d.ts +218 -0
- package/dist/session.js +545 -0
- package/dist/sqlite-stores.d.ts +173 -0
- package/dist/sqlite-stores.js +921 -0
- package/dist/stores.d.ts +506 -0
- package/dist/stores.js +614 -0
- package/dist/testing.d.ts +42 -0
- package/dist/testing.js +47 -0
- package/dist/trial-grant.d.ts +40 -0
- package/dist/trial-grant.js +24 -0
- package/dist/usage-report.d.ts +23 -0
- package/dist/usage-report.js +68 -0
- package/dist/util.d.ts +3 -0
- package/dist/util.js +5 -0
- package/package.json +16 -10
- package/scripts/agentchat-integrate.mjs +852 -607
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
const STATUS = {
|
|
4
|
+
bad_request: 400,
|
|
5
|
+
not_found: 404,
|
|
6
|
+
provider_in_use: 409,
|
|
7
|
+
model_in_use: 400,
|
|
8
|
+
model_not_in_whitelist: 400,
|
|
9
|
+
provider_unreachable: 502,
|
|
10
|
+
};
|
|
11
|
+
export function apiError(code, message) {
|
|
12
|
+
return { code, message, status: STATUS[code] };
|
|
13
|
+
}
|
|
14
|
+
/** `env:NAME` → 实际密钥。没配/空串都算没配(keyConfigured=false)。 */
|
|
15
|
+
export function keyOf(entry) {
|
|
16
|
+
const ref = entry.keyRef;
|
|
17
|
+
if (!ref || !ref.startsWith("env:"))
|
|
18
|
+
return undefined;
|
|
19
|
+
const value = process.env[ref.slice(4)];
|
|
20
|
+
return value && value.trim() !== "" ? value : undefined;
|
|
21
|
+
}
|
|
22
|
+
/** `env:SENSENOVA_API_KEY` → `SENSENOVA_API_KEY`(展示用,不是密钥)。 */
|
|
23
|
+
export function keyEnvOf(entry) {
|
|
24
|
+
const ref = entry.keyRef;
|
|
25
|
+
return ref && ref.startsWith("env:") ? ref.slice(4) : undefined;
|
|
26
|
+
}
|
|
27
|
+
export function toModelsResponse(cfg, configPath, tierMeta = {}) {
|
|
28
|
+
const providers = Object.entries(cfg.providers).map(([id, p]) => {
|
|
29
|
+
const keyEnv = keyEnvOf(p);
|
|
30
|
+
return {
|
|
31
|
+
id,
|
|
32
|
+
enabled: p.enabled,
|
|
33
|
+
...(p.api ? { api: p.api } : {}),
|
|
34
|
+
...(p.baseUrl ? { baseUrl: p.baseUrl } : {}),
|
|
35
|
+
keyConfigured: keyOf(p) !== undefined,
|
|
36
|
+
...(keyEnv ? { keyEnv } : {}),
|
|
37
|
+
models: [...p.models],
|
|
38
|
+
catalog: [...p.catalog],
|
|
39
|
+
...(p.fetchedAt ? { fetchedAt: p.fetchedAt } : {}),
|
|
40
|
+
};
|
|
41
|
+
});
|
|
42
|
+
const tiers = {};
|
|
43
|
+
for (const [id, t] of Object.entries(cfg.tiers)) {
|
|
44
|
+
const meta = tierMeta[id];
|
|
45
|
+
tiers[id] = {
|
|
46
|
+
...(meta?.label ? { label: meta.label } : {}),
|
|
47
|
+
...(meta?.multiplier !== undefined ? { multiplier: meta.multiplier } : {}),
|
|
48
|
+
candidates: t.candidates.map((c) => ({ ...c })),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
source: cfg.source,
|
|
53
|
+
maxCandidates: cfg.maxCandidates,
|
|
54
|
+
providers,
|
|
55
|
+
tiers,
|
|
56
|
+
routing: { ...cfg.routing },
|
|
57
|
+
problems: [...cfg.problems],
|
|
58
|
+
configPath,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function isRecord(v) {
|
|
62
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
63
|
+
}
|
|
64
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
65
|
+
/**
|
|
66
|
+
* `PUT /api/admin/models/providers/:id`:只允许改白名单字段。
|
|
67
|
+
* 不做 upsert——新增 provider 必须在 `models.json` 里也有端点,浏览器填 key 是 的延后项。
|
|
68
|
+
*/
|
|
69
|
+
export function patchProvider(cfg, id, body) {
|
|
70
|
+
const current = cfg.providers[id];
|
|
71
|
+
if (!current)
|
|
72
|
+
return { error: apiError("not_found", `unknown provider "${id}"`) };
|
|
73
|
+
if (!isRecord(body))
|
|
74
|
+
return { error: apiError("bad_request", "body must be a JSON object") };
|
|
75
|
+
const next = { ...current, models: [...current.models], catalog: [...current.catalog] };
|
|
76
|
+
if (body.enabled !== undefined) {
|
|
77
|
+
if (typeof body.enabled !== "boolean")
|
|
78
|
+
return { error: apiError("bad_request", "`enabled` must be a boolean") };
|
|
79
|
+
next.enabled = body.enabled;
|
|
80
|
+
}
|
|
81
|
+
if (body.api !== undefined) {
|
|
82
|
+
if (typeof body.api !== "string" || body.api.trim() === "")
|
|
83
|
+
return { error: apiError("bad_request", "`api` must be a non-empty string") };
|
|
84
|
+
next.api = body.api.trim();
|
|
85
|
+
}
|
|
86
|
+
if (body.baseUrl !== undefined) {
|
|
87
|
+
if (typeof body.baseUrl !== "string")
|
|
88
|
+
return { error: apiError("bad_request", "`baseUrl` must be a string") };
|
|
89
|
+
let url;
|
|
90
|
+
try {
|
|
91
|
+
url = new URL(body.baseUrl.trim());
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return { error: apiError("bad_request", "`baseUrl` must be an absolute URL") };
|
|
95
|
+
}
|
|
96
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
97
|
+
return { error: apiError("bad_request", "`baseUrl` must be http(s)") };
|
|
98
|
+
next.baseUrl = body.baseUrl.trim().replace(/\/+$/, "");
|
|
99
|
+
}
|
|
100
|
+
if (body.keyEnv !== undefined) {
|
|
101
|
+
// 只接受环境变量名:密钥永远不经过浏览器。
|
|
102
|
+
if (body.keyEnv === null || body.keyEnv === "")
|
|
103
|
+
delete next.keyRef;
|
|
104
|
+
else if (typeof body.keyEnv === "string" && ENV_NAME.test(body.keyEnv.trim()))
|
|
105
|
+
next.keyRef = `env:${body.keyEnv.trim()}`;
|
|
106
|
+
else
|
|
107
|
+
return { error: apiError("bad_request", "`keyEnv` must be an env var name like SENSENOVA_API_KEY") };
|
|
108
|
+
}
|
|
109
|
+
if (body.models !== undefined) {
|
|
110
|
+
if (!Array.isArray(body.models) || body.models.some((m) => typeof m !== "string" || m.trim() === "")) {
|
|
111
|
+
return { error: apiError("bad_request", "`models` must be a list of non-empty strings") };
|
|
112
|
+
}
|
|
113
|
+
const whitelist = [...new Set(body.models.map((m) => m.trim()))];
|
|
114
|
+
// 撤白名单前先看有没有档位还引用它——否则运行时会静默丢掉这个候选(的反面)。
|
|
115
|
+
for (const [tierId, tier] of Object.entries(cfg.tiers)) {
|
|
116
|
+
for (const c of tier.candidates) {
|
|
117
|
+
if (c.provider === id && !whitelist.includes(c.model)) {
|
|
118
|
+
return { error: apiError("model_in_use", `model "${c.model}" is still bound to tier "${tierId}"; unbind it first`) };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
next.models = whitelist;
|
|
123
|
+
// 手工写进白名单的模型也要在目录里可见,否则页面永远显示「不在目录」。
|
|
124
|
+
for (const m of whitelist)
|
|
125
|
+
if (!next.catalog.includes(m))
|
|
126
|
+
next.catalog.push(m);
|
|
127
|
+
}
|
|
128
|
+
return { cfg: { ...cfg, providers: { ...cfg.providers, [id]: next } } };
|
|
129
|
+
}
|
|
130
|
+
/** `DELETE /api/admin/models/providers/:id`:被档位引用 → 409。 */
|
|
131
|
+
export function deleteProvider(cfg, id) {
|
|
132
|
+
if (!cfg.providers[id])
|
|
133
|
+
return { error: apiError("not_found", `unknown provider "${id}"`) };
|
|
134
|
+
const usedBy = Object.entries(cfg.tiers).filter(([, t]) => t.candidates.some((c) => c.provider === id)).map(([tierId]) => tierId);
|
|
135
|
+
if (usedBy.length > 0)
|
|
136
|
+
return { error: apiError("provider_in_use", `provider "${id}" is still bound to tier(s) ${usedBy.join(", ")}`) };
|
|
137
|
+
const providers = { ...cfg.providers };
|
|
138
|
+
delete providers[id];
|
|
139
|
+
return { cfg: { ...cfg, providers } };
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* `PUT /api/admin/models/tiers`:整档替换(只动请求里出现的档位)。
|
|
143
|
+
* 档位集合来自 manifest——配置只能重绑,不能新增档位(否则 `/api/chat` 仍然 400,
|
|
144
|
+
* 页面却显示配好了)。
|
|
145
|
+
*/
|
|
146
|
+
export function patchTiers(cfg, body, allowedTierIds) {
|
|
147
|
+
if (!isRecord(body) || !isRecord(body.tiers)) {
|
|
148
|
+
return { error: apiError("bad_request", "expected {tiers:{<id>:{candidates:[{provider,model}]}}}") };
|
|
149
|
+
}
|
|
150
|
+
const tiers = { ...cfg.tiers };
|
|
151
|
+
for (const [tierId, raw] of Object.entries(body.tiers)) {
|
|
152
|
+
if (!allowedTierIds.includes(tierId)) {
|
|
153
|
+
return { error: apiError("bad_request", `unknown tier "${tierId}"(档位集合来自 manifest,配置只能重绑不能新增)`) };
|
|
154
|
+
}
|
|
155
|
+
if (!isRecord(raw) || !Array.isArray(raw.candidates)) {
|
|
156
|
+
return { error: apiError("bad_request", `tiers.${tierId}.candidates must be a list`) };
|
|
157
|
+
}
|
|
158
|
+
const list = raw.candidates;
|
|
159
|
+
if (list.length === 0)
|
|
160
|
+
return { error: apiError("bad_request", `tiers.${tierId}: at least one candidate is required`) };
|
|
161
|
+
if (list.length > cfg.maxCandidates) {
|
|
162
|
+
return { error: apiError("bad_request", `tiers.${tierId}: ${list.length} candidates exceed maxCandidates ${cfg.maxCandidates}`) };
|
|
163
|
+
}
|
|
164
|
+
const out = [];
|
|
165
|
+
for (const [i, c] of list.entries()) {
|
|
166
|
+
const at = `tiers.${tierId}.candidates[${i}]`;
|
|
167
|
+
if (!isRecord(c) || typeof c.provider !== "string" || typeof c.model !== "string") {
|
|
168
|
+
return { error: apiError("bad_request", `${at} must be {provider, model}`) };
|
|
169
|
+
}
|
|
170
|
+
const provider = cfg.providers[c.provider];
|
|
171
|
+
if (!provider)
|
|
172
|
+
return { error: apiError("bad_request", `${at}: unknown provider "${c.provider}"`) };
|
|
173
|
+
if (!provider.enabled)
|
|
174
|
+
return { error: apiError("bad_request", `${at}: provider "${c.provider}" is disabled`) };
|
|
175
|
+
if (!provider.models.includes(c.model)) {
|
|
176
|
+
return { error: apiError("model_not_in_whitelist", `${at}: model "${c.model}" is not in the whitelist of "${c.provider}"`) };
|
|
177
|
+
}
|
|
178
|
+
if (out.some((o) => o.provider === c.provider && o.model === c.model)) {
|
|
179
|
+
return { error: apiError("bad_request", `${at} duplicates an earlier candidate`) };
|
|
180
|
+
}
|
|
181
|
+
out.push({ provider: c.provider, model: c.model });
|
|
182
|
+
}
|
|
183
|
+
tiers[tierId] = { candidates: out };
|
|
184
|
+
}
|
|
185
|
+
return { cfg: { ...cfg, tiers } };
|
|
186
|
+
}
|
|
187
|
+
/** `PUT /api/admin/models/routing`。 */
|
|
188
|
+
export function patchRouting(cfg, body) {
|
|
189
|
+
if (!isRecord(body))
|
|
190
|
+
return { error: apiError("bad_request", "body must be a JSON object") };
|
|
191
|
+
const routing = { ...cfg.routing };
|
|
192
|
+
if (body.failover !== undefined) {
|
|
193
|
+
if (typeof body.failover !== "boolean")
|
|
194
|
+
return { error: apiError("bad_request", "`failover` must be a boolean") };
|
|
195
|
+
routing.failover = body.failover;
|
|
196
|
+
}
|
|
197
|
+
if (body.stickyWithinRun !== undefined) {
|
|
198
|
+
if (typeof body.stickyWithinRun !== "boolean")
|
|
199
|
+
return { error: apiError("bad_request", "`stickyWithinRun` must be a boolean") };
|
|
200
|
+
routing.stickyWithinRun = body.stickyWithinRun;
|
|
201
|
+
}
|
|
202
|
+
if (body.cooldownSeconds !== undefined) {
|
|
203
|
+
const n = body.cooldownSeconds;
|
|
204
|
+
if (typeof n !== "number" || !Number.isFinite(n) || n < 0 || n > 3600) {
|
|
205
|
+
return { error: apiError("bad_request", "`cooldownSeconds` must be a number 0..3600") };
|
|
206
|
+
}
|
|
207
|
+
routing.cooldownSeconds = Math.round(n);
|
|
208
|
+
}
|
|
209
|
+
return { cfg: { ...cfg, routing } };
|
|
210
|
+
}
|
|
211
|
+
// ---------------------------------------------------------------- 出网探测
|
|
212
|
+
const PROBE_TIMEOUT_MS = 8000;
|
|
213
|
+
function errText(err) {
|
|
214
|
+
return err instanceof Error ? err.message : String(err);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* `POST .../refresh`:`GET {baseUrl}/models`(OpenAI 标准,带 Bearer)。
|
|
218
|
+
*
|
|
219
|
+
* 提到「pi 有原生 refreshModels 的 provider 优先走 runtime.refresh」。不走:
|
|
220
|
+
* `runtime.getModels()` 返回的是 models.json 里的静态目录,`refresh` 对没有原生
|
|
221
|
+
* 实现的 provider 是 no-op——那样会「看起来刷新成功、其实拿到旧列表」。等真的接了
|
|
222
|
+
* 一个有原生实现的 provider(OpenRouter 按 不接)再开这条分支。
|
|
223
|
+
*/
|
|
224
|
+
export async function refreshProvider(entry, opts = {}) {
|
|
225
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
226
|
+
const now = opts.now ?? Date.now;
|
|
227
|
+
if (!entry.baseUrl)
|
|
228
|
+
return { error: apiError("bad_request", "provider has no baseUrl") };
|
|
229
|
+
const key = keyOf(entry);
|
|
230
|
+
if (!key) {
|
|
231
|
+
return { error: apiError("provider_unreachable", `key is not configured (${entry.keyRef ?? "no keyRef"}); set the env var on the server`) };
|
|
232
|
+
}
|
|
233
|
+
const url = `${entry.baseUrl.replace(/\/+$/, "")}/models`;
|
|
234
|
+
let res;
|
|
235
|
+
try {
|
|
236
|
+
res = await fetchImpl(url, {
|
|
237
|
+
headers: { authorization: `Bearer ${key}` },
|
|
238
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? PROBE_TIMEOUT_MS),
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
return { error: apiError("provider_unreachable", `GET ${url} failed: ${errText(err)}`) };
|
|
243
|
+
}
|
|
244
|
+
if (!res.ok)
|
|
245
|
+
return { error: apiError("provider_unreachable", `GET ${url} → ${res.status} ${res.statusText}`) };
|
|
246
|
+
let body;
|
|
247
|
+
try {
|
|
248
|
+
body = await res.json();
|
|
249
|
+
}
|
|
250
|
+
catch (err) {
|
|
251
|
+
return { error: apiError("provider_unreachable", `GET ${url} returned non-JSON: ${errText(err)}`) };
|
|
252
|
+
}
|
|
253
|
+
// OpenAI: {data:[{id,…}]};部分网关: {models:[…]} 或裸数组。
|
|
254
|
+
const list = isRecord(body) && Array.isArray(body.data) ? body.data : isRecord(body) && Array.isArray(body.models) ? body.models : Array.isArray(body) ? body : null;
|
|
255
|
+
if (!list)
|
|
256
|
+
return { error: apiError("provider_unreachable", `GET ${url} did not return a model list`) };
|
|
257
|
+
const models = [];
|
|
258
|
+
for (const raw of list) {
|
|
259
|
+
const id = typeof raw === "string" ? raw : typeof raw?.id === "string" ? raw.id : undefined;
|
|
260
|
+
if (!id)
|
|
261
|
+
continue;
|
|
262
|
+
const cw = raw?.contextWindow ?? raw?.context_length ?? raw?.context_window;
|
|
263
|
+
models.push({
|
|
264
|
+
id,
|
|
265
|
+
...(typeof raw?.name === "string" ? { name: raw.name } : {}),
|
|
266
|
+
...(typeof cw === "number" && Number.isFinite(cw) ? { contextWindow: cw } : {}),
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
return { models, fetchedAt: new Date(now()).toISOString(), source: "openai-models" };
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* `POST .../test`:发一次 `max_tokens:1` 的最小请求——`checkAuth` 只看凭证形状,
|
|
273
|
+
* 验不了 baseUrl 通不通、key 有没有效。
|
|
274
|
+
*/
|
|
275
|
+
export async function testProvider(entry, model, opts = {}) {
|
|
276
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
277
|
+
const now = opts.now ?? Date.now;
|
|
278
|
+
const started = now();
|
|
279
|
+
const fail = (error) => ({ ok: false, latencyMs: now() - started, model, error });
|
|
280
|
+
if (!entry.baseUrl)
|
|
281
|
+
return fail("provider has no baseUrl");
|
|
282
|
+
const key = keyOf(entry);
|
|
283
|
+
if (!key)
|
|
284
|
+
return fail(`key is not configured (${entry.keyRef ?? "no keyRef"})`);
|
|
285
|
+
const url = `${entry.baseUrl.replace(/\/+$/, "")}/chat/completions`;
|
|
286
|
+
try {
|
|
287
|
+
const res = await fetchImpl(url, {
|
|
288
|
+
method: "POST",
|
|
289
|
+
headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
|
|
290
|
+
body: JSON.stringify({ model, messages: [{ role: "user", content: "ping" }], max_tokens: 1 }),
|
|
291
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? PROBE_TIMEOUT_MS),
|
|
292
|
+
});
|
|
293
|
+
if (!res.ok) {
|
|
294
|
+
const text = await res.text().catch(() => "");
|
|
295
|
+
return fail(`${res.status} ${res.statusText}${text ? `: ${text.slice(0, 200)}` : ""}`);
|
|
296
|
+
}
|
|
297
|
+
return { ok: true, latencyMs: now() - started, model };
|
|
298
|
+
}
|
|
299
|
+
catch (err) {
|
|
300
|
+
return fail(errText(err));
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/** 探测用哪个模型:白名单第一个,退而求其次目录第一个。 */
|
|
304
|
+
export function modelToProbe(entry) {
|
|
305
|
+
return entry.models[0] ?? entry.catalog[0];
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* 从 `models.json`(pi 真正读的那份)里取端点。`model-config.json` 的 baseUrl 是
|
|
309
|
+
* 给管理页看的副本;配置里还没写的时候(首次进页面、或文件缺失回落 manifest),
|
|
310
|
+
* refresh/test 必须能借 models.json 的端点跑起来——否则「先去 models.json 写端点,
|
|
311
|
+
* 回来点刷新」这个流程第一步就死。
|
|
312
|
+
*/
|
|
313
|
+
export function baseUrlFromModelsJson(dataDir, providerId) {
|
|
314
|
+
try {
|
|
315
|
+
const raw = JSON.parse(readFileSync(path.join(dataDir, "models.json"), "utf8"));
|
|
316
|
+
if (!isRecord(raw) || !isRecord(raw.providers))
|
|
317
|
+
return undefined;
|
|
318
|
+
const entry = raw.providers[providerId];
|
|
319
|
+
if (!isRecord(entry))
|
|
320
|
+
return undefined;
|
|
321
|
+
return typeof entry.baseUrl === "string" && entry.baseUrl.trim() !== "" ? entry.baseUrl.trim().replace(/\/+$/, "") : undefined;
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
return undefined;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { type PersonaUi } from "@njuptlzf/agent-chat-protocol";
|
|
2
|
+
import { type LoadedProduct } from "./manifest.ts";
|
|
3
|
+
export declare const PERSONA_CONFIG_FILENAME = "persona-config.json";
|
|
4
|
+
/** prompt 长度上下限:太短必然丢规则,太长会挤掉技能广告与工具说明。 */
|
|
5
|
+
export declare const PROMPT_MIN_CHARS = 200;
|
|
6
|
+
export declare const PROMPT_MAX_CHARS = 20000;
|
|
7
|
+
/** 单个人格的覆盖值。字段全部可选——缺字段回落 manifest(逐字段,不是整块替换)。 */
|
|
8
|
+
export interface PersonaOverride {
|
|
9
|
+
/** 人格正文全文(不是 patch:patch 难审、难回滚)。 */
|
|
10
|
+
prompt?: string;
|
|
11
|
+
/** 展示文案覆盖(只影响界面,不进模型)。 */
|
|
12
|
+
ui?: PersonaUi;
|
|
13
|
+
/** 从 manifest 白名单里**再收窄**:只能减,不能加。 */
|
|
14
|
+
disabledTools?: string[];
|
|
15
|
+
updatedBy?: string;
|
|
16
|
+
updatedAt?: string;
|
|
17
|
+
}
|
|
18
|
+
/** 每改一次留一版;每个人格只留最近 N 版(配置是给人看的,不是数据库)。 */
|
|
19
|
+
export declare const VERSIONS_PER_PERSONA = 20;
|
|
20
|
+
export type PersonaVersionAction = "save" | "reset" | "rollback";
|
|
21
|
+
/**
|
|
22
|
+
* 一版快照。**回滚不是删历史**:它是把旧快照再写一次,生成新版本——
|
|
23
|
+
* 这样"谁在什么时候退回了哪一版"本身也可追溯。
|
|
24
|
+
*/
|
|
25
|
+
export interface PersonaVersionEntry {
|
|
26
|
+
/** 写入后的配置版本号(全局单调递增,和 `PersonaConfig.version` 同一把尺)。 */
|
|
27
|
+
version: number;
|
|
28
|
+
persona: string;
|
|
29
|
+
action: PersonaVersionAction;
|
|
30
|
+
at: string;
|
|
31
|
+
by: string;
|
|
32
|
+
/** 这一版之后该人格的覆盖;`reset` 没有这个字段 = 回到 manifest。 */
|
|
33
|
+
override?: PersonaOverride;
|
|
34
|
+
/** 回滚时记「从哪一版恢复」。 */
|
|
35
|
+
restoredFrom?: number;
|
|
36
|
+
}
|
|
37
|
+
export interface PersonaConfig {
|
|
38
|
+
/** 单调递增;写接口用 `If-Match` 做乐观锁。 */
|
|
39
|
+
version: number;
|
|
40
|
+
personas: Record<string, PersonaOverride>;
|
|
41
|
+
/** 版本快照:按写入顺序升序;同一个人格最多 `VERSIONS_PER_PERSONA` 条。 */
|
|
42
|
+
versions: PersonaVersionEntry[];
|
|
43
|
+
/** 运行时态:当前生效值来自文件还是 manifest(不落盘)。 */
|
|
44
|
+
source: "manifest" | "file";
|
|
45
|
+
/** 解析期发现的问题(坏字段、未知人格…),页面显示,不阻塞启动。 */
|
|
46
|
+
problems: string[];
|
|
47
|
+
}
|
|
48
|
+
export interface PersonaConfigStore {
|
|
49
|
+
/** 配置文件的绝对路径(管理页显示「去改哪个文件」)。 */
|
|
50
|
+
readonly path: string;
|
|
51
|
+
/** 读当前生效配置(1 秒级缓存,mtime/size 变了才重解析)。 */
|
|
52
|
+
get(): PersonaConfig;
|
|
53
|
+
/** 主动作废缓存——写接口保存后立刻生效。 */
|
|
54
|
+
invalidate(): void;
|
|
55
|
+
}
|
|
56
|
+
export interface PersonaConfigStoreOptions {
|
|
57
|
+
now?: () => number;
|
|
58
|
+
warn?: (message: string) => void;
|
|
59
|
+
}
|
|
60
|
+
/** 文件不存在时的出厂值:一切走 manifest。 */
|
|
61
|
+
export declare function manifestPersonaConfig(problems?: string[]): PersonaConfig;
|
|
62
|
+
/**
|
|
63
|
+
* 解析配置文件。**永不抛**:结构不对就返回 null(调用方回落 manifest),
|
|
64
|
+
* 单个人格写坏就丢掉那一条并记 problem,其余照用。
|
|
65
|
+
*/
|
|
66
|
+
export declare function parsePersonaConfig(raw: unknown, known: Set<string>): {
|
|
67
|
+
config: PersonaConfig | null;
|
|
68
|
+
problems: string[];
|
|
69
|
+
};
|
|
70
|
+
export declare function createPersonaConfigStore(dataDir: string, product: LoadedProduct, opts?: PersonaConfigStoreOptions): PersonaConfigStore;
|
|
71
|
+
/** 原子写(同 model/mcp-config:tmp + rename),写完作废缓存 ⇒ 下一次建会话生效。 */
|
|
72
|
+
export declare function savePersonaConfig(store: PersonaConfigStore, cfg: PersonaConfig): void;
|
|
73
|
+
/**
|
|
74
|
+
* 追加一版快照,并按人格裁到最近 `VERSIONS_PER_PERSONA` 条。
|
|
75
|
+
* **裁的是最老的快照**,不是当前的生效值——两者是分开存的(`personas` 永远在)。
|
|
76
|
+
*/
|
|
77
|
+
export declare function appendVersion(versions: PersonaVersionEntry[], entry: PersonaVersionEntry, perPersona?: number): PersonaVersionEntry[];
|
|
78
|
+
/** 某人格的版本快照,**新到旧**(页面按这个顺序列)。 */
|
|
79
|
+
export declare function versionsOf(cfg: PersonaConfig, persona: string): PersonaVersionEntry[];
|
|
80
|
+
export declare function versionEntry(cfg: PersonaConfig, persona: string, version: number): PersonaVersionEntry | undefined;
|
|
81
|
+
/**
|
|
82
|
+
* 该人格**当刻生效的版本号**(写进 `history.persona_version`):
|
|
83
|
+
* - 有快照 ⇒ 最新那一版;
|
|
84
|
+
* - 有覆盖但没快照(手工写入的配置)⇒ 当前配置版本;
|
|
85
|
+
* - 没有覆盖 ⇒ 0(= 直接采用 manifest 出厂值,不代表已有版本记录)。
|
|
86
|
+
*/
|
|
87
|
+
export declare function effectivePersonaVersion(cfg: PersonaConfig, persona: string): number;
|
|
88
|
+
/**
|
|
89
|
+
* 生效值 = manifest 编译结果 + 配置覆盖(**逐字段**)。
|
|
90
|
+
*
|
|
91
|
+
* 只做两件事:prompt 换掉;`disabledTools` 从白名单里减掉。
|
|
92
|
+
* `allowTools === undefined`(manifest 未设白名单 = 不限)时原样返回 `undefined`,
|
|
93
|
+
* 由 `filterToolsForPersona` / `narrowMcpExposure` 按 deny 名单处理——
|
|
94
|
+
* 否则「不给白名单的人格」连一个工具都停不掉。
|
|
95
|
+
*/
|
|
96
|
+
export declare function applyPersonaOverride(base: {
|
|
97
|
+
systemPromptText: string;
|
|
98
|
+
allowTools?: string[];
|
|
99
|
+
}, override: PersonaOverride | undefined): {
|
|
100
|
+
prompt: string;
|
|
101
|
+
allowTools: string[] | undefined;
|
|
102
|
+
disabledTools: string[];
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* 保存前校验(的写接口用它,先把它写出来并测)。
|
|
106
|
+
* 一次返回**全部**错误,不挤牙膏——页面要能一次改完。
|
|
107
|
+
*/
|
|
108
|
+
export declare function validatePersona(product: LoadedProduct, personaId: string, input: {
|
|
109
|
+
prompt?: unknown;
|
|
110
|
+
ui?: unknown;
|
|
111
|
+
disabledTools?: unknown;
|
|
112
|
+
}): string[];
|