@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.
Files changed (44) 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 +16 -10
  44. package/scripts/agentchat-integrate.mjs +852 -607
@@ -0,0 +1,371 @@
1
+ import { readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { resolveTier } from "./manifest.js";
4
+ /**
5
+ * 运行时模型配置。
6
+ *
7
+ * 三层落点:凭证/端点在 data 目录的 `models.json`(pi 自己的格式),运营
8
+ * 配置在 data 目录的 `model-config.json`(本文件,管理页写),仓库里的 manifest
9
+ * 只当**兜底默认值**。所以这里的每一条路径都要能回答同一个问题:
10
+ * **配置没了/坏了,助手还能不能说话?** 答:回落 manifest,打一行日志,不 500。
11
+ *
12
+ * 本层只有「读 + 校验 + 解析」,没有写盘也没有 HTTP(才加端点)。写盘端点的
13
+ * 校验规则要和这里同源,避免「页面放行、运行时丢掉」的两套口径。
14
+ */
15
+ export const MODEL_CONFIG_FILENAME = "model-config.json";
16
+ /** 候选上限缺省 3,可配 1–5(业务参数一律可配,规范)。 */
17
+ export const DEFAULT_MAX_CANDIDATES = 3;
18
+ export const MAX_CANDIDATES_CEILING = 5;
19
+ /** 失败的候选在此期间不被选为主选;进程内存态,不进库。 */
20
+ export const DEFAULT_COOLDOWN_SECONDS = 120;
21
+ /** `keyRef` 只允许 `env:NAME`——明文密钥不落这个文件,也不回显浏览器。 */
22
+ const KEY_REF = /^env:[A-Za-z_][A-Za-z0-9_]*$/;
23
+ /** 「1 秒级缓存」(热加载):1 秒内的重复读取不 stat 文件。 */
24
+ const CACHE_TTL_MS = 1000;
25
+ function isRecord(v) {
26
+ return v !== null && typeof v === "object" && !Array.isArray(v);
27
+ }
28
+ /**
29
+ * 校验一份 `model-config.json`。**永不抛**:能救的项就地纠正(clamp/去重/丢候选),
30
+ * 救不回来的记进 `problems`。`config === null` 只在根不是对象时出现——那种情况调用方
31
+ * 应当整体回落 manifest。
32
+ */
33
+ export function parseModelConfig(raw) {
34
+ const problems = [];
35
+ if (!isRecord(raw))
36
+ return { config: null, problems: ["root must be a JSON object"] };
37
+ // ---- maxCandidates:越界 clamp 到 1–5,不报错——配置写歪不能把服务打死。
38
+ let maxCandidates = DEFAULT_MAX_CANDIDATES;
39
+ if (raw.maxCandidates !== undefined) {
40
+ const n = raw.maxCandidates;
41
+ if (typeof n !== "number" || !Number.isInteger(n)) {
42
+ problems.push(`maxCandidates must be an integer 1–${MAX_CANDIDATES_CEILING}; using ${DEFAULT_MAX_CANDIDATES}`);
43
+ }
44
+ else if (n < 1 || n > MAX_CANDIDATES_CEILING) {
45
+ maxCandidates = Math.min(MAX_CANDIDATES_CEILING, Math.max(1, n));
46
+ problems.push(`maxCandidates ${n} is out of range 1–${MAX_CANDIDATES_CEILING}; clamped to ${maxCandidates}`);
47
+ }
48
+ else {
49
+ maxCandidates = n;
50
+ }
51
+ }
52
+ // ---- providers
53
+ const providers = {};
54
+ if (raw.providers !== undefined) {
55
+ if (!isRecord(raw.providers)) {
56
+ problems.push("providers must be an object");
57
+ }
58
+ else {
59
+ for (const [id, v] of Object.entries(raw.providers)) {
60
+ if (!isRecord(v)) {
61
+ problems.push(`providers.${id} must be an object`);
62
+ continue;
63
+ }
64
+ let models = [];
65
+ if (v.models !== undefined) {
66
+ if (!Array.isArray(v.models))
67
+ problems.push(`providers.${id}.models must be a list of strings`);
68
+ else {
69
+ models = [...new Set(v.models.filter((m) => typeof m === "string" && m.trim() !== "").map((m) => m.trim()))];
70
+ if (models.length !== v.models.length)
71
+ problems.push(`providers.${id}.models had empty or duplicate entries (dropped)`);
72
+ }
73
+ }
74
+ let catalog = [];
75
+ if (v.catalog !== undefined) {
76
+ if (!Array.isArray(v.catalog))
77
+ problems.push(`providers.${id}.catalog must be a list of strings`);
78
+ else
79
+ catalog = [...new Set(v.catalog.filter((m) => typeof m === "string" && m.trim() !== "").map((m) => m.trim()))];
80
+ }
81
+ // 白名单里手工写进来的模型也要能在目录里看到,否则管理页永远显示「不在目录」。
82
+ for (const m of models)
83
+ if (!catalog.includes(m))
84
+ catalog.push(m);
85
+ // keyRef 写歪只丢 keyRef,**不丢 provider**:真正取密钥的是 models.json 里的
86
+ // `$ENV`,keyRef 只是管理页「key 配好了吗」的元数据。
87
+ let keyRef;
88
+ if (v.keyRef !== undefined) {
89
+ if (typeof v.keyRef === "string" && KEY_REF.test(v.keyRef))
90
+ keyRef = v.keyRef;
91
+ else
92
+ problems.push(`providers.${id}.keyRef must look like env:NAME (got ${JSON.stringify(v.keyRef)})`);
93
+ }
94
+ providers[id] = {
95
+ enabled: v.enabled === undefined ? true : v.enabled === true,
96
+ ...(typeof v.api === "string" ? { api: v.api } : {}),
97
+ ...(typeof v.baseUrl === "string" ? { baseUrl: v.baseUrl } : {}),
98
+ ...(keyRef ? { keyRef } : {}),
99
+ models,
100
+ catalog,
101
+ ...(typeof v.fetchedAt === "string" ? { fetchedAt: v.fetchedAt } : {}),
102
+ };
103
+ }
104
+ }
105
+ }
106
+ // ---- tiers:候选必须落在「已启用 provider 的白名单」内,且不超上限。
107
+ const tiers = {};
108
+ if (raw.tiers !== undefined) {
109
+ if (!isRecord(raw.tiers)) {
110
+ problems.push("tiers must be an object");
111
+ }
112
+ else {
113
+ for (const [tierId, v] of Object.entries(raw.tiers)) {
114
+ if (!isRecord(v) || !Array.isArray(v.candidates)) {
115
+ problems.push(`tiers.${tierId}.candidates must be a list`);
116
+ continue;
117
+ }
118
+ const kept = [];
119
+ for (const [i, c] of v.candidates.entries()) {
120
+ const at = `tiers.${tierId}.candidates[${i}]`;
121
+ if (!isRecord(c) || typeof c.provider !== "string" || typeof c.model !== "string" || c.provider === "" || c.model === "") {
122
+ problems.push(`${at} must be {provider, model}`);
123
+ continue;
124
+ }
125
+ if (kept.some((k) => k.provider === c.provider && k.model === c.model)) {
126
+ problems.push(`${at} duplicates an earlier candidate`);
127
+ continue;
128
+ }
129
+ kept.push({ provider: c.provider, model: c.model });
130
+ }
131
+ // 语义问题(provider 不存在/停用/不在白名单)**只标不删**:删了等于替运维改配置,
132
+ // 而 的写盘是「读回来 → 改一处 → 写回去」,被删的候选就此永久消失
133
+ // (停用 provider → 引用它的绑定全没 → 再启用也回不来)。真正的过滤在
134
+ // candidatesFor():运行时跳过,文件保持运维意图。
135
+ let usable = 0;
136
+ for (const c of kept) {
137
+ const p = providers[c.provider];
138
+ if (!p)
139
+ problems.push(`tiers.${tierId}: unknown provider "${c.provider}"(候选保留,运行时跳过)`);
140
+ else if (!p.enabled)
141
+ problems.push(`tiers.${tierId}: provider "${c.provider}" is disabled(候选保留,运行时跳过)`);
142
+ else if (!p.models.includes(c.model))
143
+ problems.push(`tiers.${tierId}: model "${c.model}" is not in the whitelist of "${c.provider}"(候选保留,运行时跳过)`);
144
+ else
145
+ usable++;
146
+ }
147
+ if (kept.length === 0) {
148
+ problems.push(`tiers.${tierId}: no candidates; this tier falls back to the manifest`);
149
+ continue;
150
+ }
151
+ if (usable === 0)
152
+ problems.push(`tiers.${tierId}: no usable candidate; this tier falls back to the manifest`);
153
+ // 超上限同样只标不删(PUT 端点才拦新增),否则写回会把第 4、5 个候选截掉。
154
+ if (kept.length > maxCandidates) {
155
+ problems.push(`tiers.${tierId}: ${kept.length} candidates exceed maxCandidates ${maxCandidates}; only the first ${maxCandidates} are used`);
156
+ }
157
+ tiers[tierId] = { candidates: kept };
158
+ }
159
+ }
160
+ }
161
+ // ---- routing
162
+ const r = isRecord(raw.routing) ? raw.routing : {};
163
+ let cooldownSeconds = DEFAULT_COOLDOWN_SECONDS;
164
+ if (r.cooldownSeconds !== undefined) {
165
+ const n = r.cooldownSeconds;
166
+ if (typeof n !== "number" || !Number.isFinite(n) || n < 0)
167
+ problems.push("routing.cooldownSeconds must be a non-negative number");
168
+ else
169
+ cooldownSeconds = Math.min(3600, Math.round(n));
170
+ }
171
+ if (raw.routing !== undefined && !isRecord(raw.routing))
172
+ problems.push("routing must be an object");
173
+ if (raw.version !== undefined && raw.version !== 1) {
174
+ // 不当作错误:只解析我们认识的字段,多出来的留给以后的版本(前向兼容)。
175
+ problems.push(`version ${JSON.stringify(raw.version)} is not 1; parsing known fields only`);
176
+ }
177
+ return {
178
+ config: {
179
+ version: 1,
180
+ maxCandidates,
181
+ providers,
182
+ tiers,
183
+ routing: {
184
+ failover: r.failover === undefined ? true : r.failover === true,
185
+ cooldownSeconds,
186
+ stickyWithinRun: r.stickyWithinRun === undefined ? true : r.stickyWithinRun === true,
187
+ },
188
+ source: "file",
189
+ problems,
190
+ },
191
+ problems,
192
+ };
193
+ }
194
+ /**
195
+ * 回落配置:把 manifest 的 `agent.model` + `agent.tiers` 投影成同一形状。
196
+ * 这样上层只有一条解析路径,不用到处判「有没有配置文件」(的第 2 步)。
197
+ * `problems` 用来把「为什么回落」带到管理页(读文件失败/坏 JSON 时由 store 传入)。
198
+ */
199
+ export function manifestModelConfig(product, problems = []) {
200
+ const base = product.manifest.agent.model;
201
+ // 端点与密钥都在 models.json / env 里,manifest 只知道 provider 名。按 createModelRuntime
202
+ // 自己的约定推一个 `<PROVIDER>_API_KEY`(同一份猜测,两边不会说两套话),否则全新部署
203
+ // 没有 model-config.json 时管理页会把「key 配好了」误报成未配置。管理员可用 PUT keyEnv 覆盖。
204
+ const envName = `${base.provider.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_API_KEY`;
205
+ const tiers = {};
206
+ for (const t of product.manifest.agent.tiers ?? []) {
207
+ tiers[t.id] = { candidates: [{ provider: base.provider, model: t.model ?? base.id }] };
208
+ }
209
+ return {
210
+ version: 1,
211
+ maxCandidates: DEFAULT_MAX_CANDIDATES,
212
+ providers: { [base.provider]: { enabled: true, keyRef: `env:${envName}`, models: [base.id], catalog: [base.id] } },
213
+ tiers,
214
+ routing: { failover: true, cooldownSeconds: DEFAULT_COOLDOWN_SECONDS, stickyWithinRun: true },
215
+ source: "manifest",
216
+ problems,
217
+ };
218
+ }
219
+ /**
220
+ * 内存形状 → 文件形状(只写已知字段:`source`/`problems` 是运行时态,不落盘)。
221
+ * 键序固定,diff 干净。
222
+ */
223
+ export function serializeModelConfig(cfg) {
224
+ const providers = {};
225
+ for (const [id, p] of Object.entries(cfg.providers)) {
226
+ providers[id] = {
227
+ enabled: p.enabled,
228
+ ...(p.api ? { api: p.api } : {}),
229
+ ...(p.baseUrl ? { baseUrl: p.baseUrl } : {}),
230
+ ...(p.keyRef ? { keyRef: p.keyRef } : {}),
231
+ models: [...p.models],
232
+ catalog: [...p.catalog],
233
+ ...(p.fetchedAt ? { fetchedAt: p.fetchedAt } : {}),
234
+ };
235
+ }
236
+ const tiers = {};
237
+ for (const [id, t] of Object.entries(cfg.tiers)) {
238
+ tiers[id] = { candidates: t.candidates.map((c) => ({ provider: c.provider, model: c.model })) };
239
+ }
240
+ return { version: 1, maxCandidates: cfg.maxCandidates, providers, tiers, routing: { ...cfg.routing } };
241
+ }
242
+ /**
243
+ * 原子写(写临时文件 + rename,进程崩溃不会留下半个 JSON),写完作废缓存
244
+ * ——下一个 run 立刻用新配置,不用等那 1 秒。
245
+ */
246
+ export function saveModelConfig(store, cfg) {
247
+ const body = JSON.stringify(serializeModelConfig(cfg), null, 2) + "\n";
248
+ const tmp = `${store.path}.${process.pid}.${Date.now()}.tmp`;
249
+ writeFileSync(tmp, body, "utf8");
250
+ try {
251
+ renameSync(tmp, store.path);
252
+ }
253
+ catch (err) {
254
+ // rename 失败别把临时文件留在 data 目录里。
255
+ try {
256
+ unlinkSync(tmp);
257
+ }
258
+ catch { /* 已经没了就算了 */ }
259
+ throw err;
260
+ }
261
+ store.invalidate();
262
+ }
263
+ export function createModelConfigStore(dataDir, product, opts = {}) {
264
+ const file = path.join(dataDir, MODEL_CONFIG_FILENAME);
265
+ const now = opts.now ?? Date.now;
266
+ const warn = opts.warn ?? ((m) => console.warn(m));
267
+ let cached;
268
+ let stamp = "";
269
+ let checkedAt = Number.NEGATIVE_INFINITY;
270
+ const readFile = () => {
271
+ let text;
272
+ try {
273
+ text = readFileSync(file, "utf8");
274
+ }
275
+ catch (err) {
276
+ warn(`[model-config] cannot read ${file}: ${String(err)}; falling back to the manifest`);
277
+ return manifestModelConfig(product, [`cannot read ${MODEL_CONFIG_FILENAME}: ${String(err)}`]);
278
+ }
279
+ let raw;
280
+ try {
281
+ raw = JSON.parse(text);
282
+ }
283
+ catch (err) {
284
+ // 坏 JSON 不能让助手说不了话:回落 + 一行日志,不抛、不 500。
285
+ warn(`[model-config] ${file} is not valid JSON (${String(err)}); falling back to the manifest`);
286
+ return manifestModelConfig(product, [`${MODEL_CONFIG_FILENAME} is not valid JSON (${String(err)})`]);
287
+ }
288
+ const { config, problems } = parseModelConfig(raw);
289
+ if (!config) {
290
+ warn(`[model-config] ${file} is unusable (${problems.join("; ")}); falling back to the manifest`);
291
+ return manifestModelConfig(product, problems);
292
+ }
293
+ if (problems.length > 0)
294
+ warn(`[model-config] ${file}: ${problems.join("; ")}`);
295
+ return config;
296
+ };
297
+ return {
298
+ path: file,
299
+ get() {
300
+ const t = now();
301
+ if (cached && t - checkedAt < CACHE_TTL_MS)
302
+ return cached;
303
+ checkedAt = t;
304
+ let stat;
305
+ try {
306
+ stat = statSync(file);
307
+ }
308
+ catch {
309
+ stat = undefined;
310
+ }
311
+ const next = stat ? `${stat.mtimeMs}:${stat.size}` : "";
312
+ if (cached && next === stamp)
313
+ return cached;
314
+ stamp = next;
315
+ cached = stat ? readFile() : manifestModelConfig(product);
316
+ return cached;
317
+ },
318
+ invalidate() {
319
+ cached = undefined;
320
+ stamp = "";
321
+ checkedAt = Number.NEGATIVE_INFINITY;
322
+ },
323
+ };
324
+ }
325
+ /** 候选能不能真的拿来跑:provider 存在、已启用、模型在白名单里。 */
326
+ export function candidateUsable(cfg, c) {
327
+ const p = cfg.providers[c.provider];
328
+ return p !== undefined && p.enabled && p.models.includes(c.model);
329
+ }
330
+ /**
331
+ * 某档**实际可用**的有序候选。`tierId` 省略时读 `tiers.default`——配置文件可以给
332
+ * 「没选档位」的请求单独绑一条链;没写就返回空数组,调用方据此回落 manifest。
333
+ *
334
+ * 过滤与截断都在这里(不在 parseModelConfig):解析层保留文件里的全部候选,
335
+ * 这样「停用 provider → 再启用」不会丢掉绑定,写盘也不会把超上限的候选截掉。
336
+ */
337
+ export function candidatesFor(cfg, tierId) {
338
+ const list = cfg.tiers[tierId ?? "default"]?.candidates ?? [];
339
+ return list.filter((c) => candidateUsable(cfg, c)).slice(0, cfg.maxCandidates);
340
+ }
341
+ /**
342
+ * 把候选链的第 0 个套回 `ResolvedTier`:thinking / multiplier / label 仍由 manifest
343
+ * 决定(档位语义不跟着模型跑),只有 provider+model 被配置覆盖。
344
+ */
345
+ export function applyCandidates(tier, candidates) {
346
+ const first = candidates[0];
347
+ return first ? { ...tier, provider: first.provider, model: first.model } : tier;
348
+ }
349
+ /**
350
+ * run 入口的唯一解析点:manifest 先定档位语义(未知 tier id → undefined → 400),
351
+ * 再由 model-config 覆盖物理 provider/model。的失败切换会在此基础上取整条链。
352
+ */
353
+ export function resolveRunTier(product, tierId, cfg) {
354
+ const tier = resolveTier(product, tierId);
355
+ if (!tier)
356
+ return undefined;
357
+ if (!cfg)
358
+ return tier;
359
+ return applyCandidates(tier, candidatesFor(cfg, tierId));
360
+ }
361
+ /**
362
+ * run 入口的**有序候选链**。链为空 ⇒ 用 manifest 的单模型,保证老部署行为不变;
363
+ * 只有一条时链长 1,失败切换自然退化成「不切」。
364
+ */
365
+ export function resolveChain(product, tierId, cfg) {
366
+ const tier = resolveTier(product, tierId);
367
+ if (!tier)
368
+ return [];
369
+ const list = cfg ? candidatesFor(cfg, tierId) : [];
370
+ return list.length > 0 ? list : [{ provider: tier.provider, model: tier.model }];
371
+ }
@@ -0,0 +1,42 @@
1
+ import type { ModelCandidate } from "./model-config.ts";
2
+ /**
3
+ * 运行时候选链的失败切换。
4
+ *
5
+ * 这一层只放**纯判定**:错误分类、冷却、链序。真正的「重建会话 + 重发 prompt」在
6
+ * server.ts 的 run 循环里(它才知道流到哪一步了)。pi 自己的同 provider 重试
7
+ * (408/409/429/5xx backoff,2–3 次)在更下面,先让它重试完,我们再切候选。
8
+ */
9
+ /** 文案:用户侧只看到这一句,永远不出现 provider / 模型名。 */
10
+ export declare const FAILOVER_NOTICE = "\u670D\u52A1\u7E41\u5FD9\uFF0C\u5DF2\u81EA\u52A8\u5207\u6362\u53E6\u4E00\u6761\u7EBF\u8DEF";
11
+ export declare const candidateKey: (c: ModelCandidate) => string;
12
+ export interface CooldownRegistry {
13
+ /** 给刚失败的候选打冷却;seconds<=0 等于不冷却。 */
14
+ mark(c: ModelCandidate, seconds: number): void;
15
+ isCooling(c: ModelCandidate): boolean;
16
+ clear(): void;
17
+ }
18
+ /**
19
+ * 进程内存态(不进 DB,重启清空)。冷却不是「拉黑」——见 orderChain。
20
+ */
21
+ export declare function createCooldownRegistry(now?: () => number): CooldownRegistry;
22
+ /** 进程级默认冷却表(main.ts 不装配也能用;测试注入自己的实例以隔离)。 */
23
+ export declare const processCooldown: CooldownRegistry;
24
+ /**
25
+ * 冷却中的候选**排到链尾**,不是删掉: 说的是「不再被选为主选」,不是「不能当备选」。
26
+ * 只有一条候选时它仍然会被用——总比整个产品答不出话强。
27
+ */
28
+ export declare function orderChain(chain: readonly ModelCandidate[], cooldown: CooldownRegistry): ModelCandidate[];
29
+ /**
30
+ * 这次失败值不值得换候选。判不出来的一律**不切**(保守):宁可把原文冒给用户,
31
+ * 也不要为一条看不懂的错误悄悄换家、让「谁在答」变成谎话。
32
+ */
33
+ export declare function isRetryableModelError(message: string): boolean;
34
+ /**
35
+ * 从 pi 原始事件取模型报错原文(2026-11-04):failover 的正则**只吃原文**——
36
+ * 用户看到的那条 error 消息已经由 events.ts 折叠成人话,不能拿它当判定输入。
37
+ * 与 events.ts 的 error 事件同源同条件(message_end + stopReason==="error")。
38
+ */
39
+ export declare function rawModelError(event: {
40
+ type: string;
41
+ message?: unknown;
42
+ }): string;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * 运行时候选链的失败切换。
3
+ *
4
+ * 这一层只放**纯判定**:错误分类、冷却、链序。真正的「重建会话 + 重发 prompt」在
5
+ * server.ts 的 run 循环里(它才知道流到哪一步了)。pi 自己的同 provider 重试
6
+ * (408/409/429/5xx backoff,2–3 次)在更下面,先让它重试完,我们再切候选。
7
+ */
8
+ /** 文案:用户侧只看到这一句,永远不出现 provider / 模型名。 */
9
+ export const FAILOVER_NOTICE = "服务繁忙,已自动切换另一条线路";
10
+ export const candidateKey = (c) => `${c.provider}/${c.model}`;
11
+ /**
12
+ * 进程内存态(不进 DB,重启清空)。冷却不是「拉黑」——见 orderChain。
13
+ */
14
+ export function createCooldownRegistry(now = Date.now) {
15
+ const until = new Map();
16
+ return {
17
+ mark(c, seconds) {
18
+ if (!Number.isFinite(seconds) || seconds <= 0)
19
+ return;
20
+ until.set(candidateKey(c), now() + seconds * 1000);
21
+ },
22
+ isCooling(c) {
23
+ const key = candidateKey(c);
24
+ const at = until.get(key);
25
+ if (at === undefined)
26
+ return false;
27
+ if (at <= now()) {
28
+ until.delete(key);
29
+ return false;
30
+ }
31
+ return true;
32
+ },
33
+ clear() {
34
+ until.clear();
35
+ },
36
+ };
37
+ }
38
+ /** 进程级默认冷却表(main.ts 不装配也能用;测试注入自己的实例以隔离)。 */
39
+ export const processCooldown = createCooldownRegistry();
40
+ /**
41
+ * 冷却中的候选**排到链尾**,不是删掉: 说的是「不再被选为主选」,不是「不能当备选」。
42
+ * 只有一条候选时它仍然会被用——总比整个产品答不出话强。
43
+ */
44
+ export function orderChain(chain, cooldown) {
45
+ const ready = [];
46
+ const cooling = [];
47
+ for (const c of chain)
48
+ (cooldown.isCooling(c) ? cooling : ready).push(c);
49
+ return [...ready, ...cooling];
50
+ }
51
+ /**
52
+ * 换家也没用的错误:**请求本身**坏了(参数非法、超长、不支持的取值)。这类在哪个
53
+ * provider 都会失败,切过去只是把备用线路也烧一次。
54
+ *
55
+ * 注意 401/403 不在这一档:那是**钥匙**坏了,不是请求坏了。跨 provider 的候选各拿
56
+ * 各的 key,备用线路完全可能好使——这正是「备一条线路」的意义(验收原话:
57
+ * 「主线路 401 自动切备用出答案」)。同 provider 内 401 会连切到链尾再冒泡,代价有界。
58
+ */
59
+ const FATAL = /\b(400|422)\b|invalid[ _]request|bad[ _]request|context[ _]length|too many tokens|request too large|unsupported[ _](parameter|value)/i;
60
+ /** 可重试:鉴权/找不到端点(换钥匙、换端点可能就好了)、限流、服务端故障、网络抖动。 */
61
+ const RETRYABLE = /\b(401|403|404|405|408|409|429|5\d\d)\b|invalid[ _-]?api[ _-]?key|unauthorized|forbidden|not found|does not exist|rate[ _-]?limit|timeout|timed out|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ECONNABORTED|EAI_AGAIN|ENOTFOUND|socket hang up|fetch failed|network|overloaded|unavailable|bad gateway|gateway timeout/i;
62
+ /**
63
+ * 这次失败值不值得换候选。判不出来的一律**不切**(保守):宁可把原文冒给用户,
64
+ * 也不要为一条看不懂的错误悄悄换家、让「谁在答」变成谎话。
65
+ */
66
+ export function isRetryableModelError(message) {
67
+ if (FATAL.test(message))
68
+ return false;
69
+ return RETRYABLE.test(message);
70
+ }
71
+ /**
72
+ * 从 pi 原始事件取模型报错原文(2026-11-04):failover 的正则**只吃原文**——
73
+ * 用户看到的那条 error 消息已经由 events.ts 折叠成人话,不能拿它当判定输入。
74
+ * 与 events.ts 的 error 事件同源同条件(message_end + stopReason==="error")。
75
+ */
76
+ export function rawModelError(event) {
77
+ if (event.type !== "message_end")
78
+ return "";
79
+ // pi 的 message 是多态联合(System/User/Assistant…),这里只关心 stopReason/errorMessage。
80
+ const msg = event.message;
81
+ return msg?.stopReason === "error" ? (msg.errorMessage ?? "") : "";
82
+ }
@@ -0,0 +1,98 @@
1
+ import type { ModelsResponse, ModelTestResponse } from "@njuptlzf/agent-chat-protocol";
2
+ import type { ModelConfig, ModelProviderEntry } from "./model-config.ts";
3
+ /**
4
+ * 模型配置面的纯逻辑。
5
+ *
6
+ * 这里只有「校验 + 变形 + 两个出网探测」,没有 HTTP 也没有落盘——路由与审计写点
7
+ * 留在 server.ts(与 handleAdminAudit 同款分层),落盘走 model-config.ts 的
8
+ * saveModelConfig(原子替换 + 作废缓存)。
9
+ *
10
+ * 校验口径必须与 的 parseModelConfig 同源:**页面放行、运行时丢掉**是最坏的组合
11
+ * (管理员以为配好了,实际每次 run 都在回落 manifest)。
12
+ */
13
+ export interface ApiError {
14
+ code: "bad_request" | "not_found" | "provider_in_use" | "model_in_use" | "model_not_in_whitelist" | "provider_unreachable";
15
+ message: string;
16
+ status: number;
17
+ }
18
+ export declare function apiError(code: ApiError["code"], message: string): ApiError;
19
+ /** `env:NAME` → 实际密钥。没配/空串都算没配(keyConfigured=false)。 */
20
+ export declare function keyOf(entry: ModelProviderEntry): string | undefined;
21
+ /** `env:SENSENOVA_API_KEY` → `SENSENOVA_API_KEY`(展示用,不是密钥)。 */
22
+ export declare function keyEnvOf(entry: ModelProviderEntry): string | undefined;
23
+ /** 档位的展示元信息(label/multiplier)来自 manifest,配置只重绑不新增档位。 */
24
+ export interface TierMeta {
25
+ label?: string;
26
+ multiplier?: number;
27
+ }
28
+ export declare function toModelsResponse(cfg: ModelConfig, configPath: string, tierMeta?: Record<string, TierMeta>): ModelsResponse;
29
+ /**
30
+ * `PUT /api/admin/models/providers/:id`:只允许改白名单字段。
31
+ * 不做 upsert——新增 provider 必须在 `models.json` 里也有端点,浏览器填 key 是 的延后项。
32
+ */
33
+ export declare function patchProvider(cfg: ModelConfig, id: string, body: unknown): {
34
+ cfg: ModelConfig;
35
+ } | {
36
+ error: ApiError;
37
+ };
38
+ /** `DELETE /api/admin/models/providers/:id`:被档位引用 → 409。 */
39
+ export declare function deleteProvider(cfg: ModelConfig, id: string): {
40
+ cfg: ModelConfig;
41
+ } | {
42
+ error: ApiError;
43
+ };
44
+ /**
45
+ * `PUT /api/admin/models/tiers`:整档替换(只动请求里出现的档位)。
46
+ * 档位集合来自 manifest——配置只能重绑,不能新增档位(否则 `/api/chat` 仍然 400,
47
+ * 页面却显示配好了)。
48
+ */
49
+ export declare function patchTiers(cfg: ModelConfig, body: unknown, allowedTierIds: readonly string[]): {
50
+ cfg: ModelConfig;
51
+ } | {
52
+ error: ApiError;
53
+ };
54
+ /** `PUT /api/admin/models/routing`。 */
55
+ export declare function patchRouting(cfg: ModelConfig, body: unknown): {
56
+ cfg: ModelConfig;
57
+ } | {
58
+ error: ApiError;
59
+ };
60
+ export interface ProbeOptions {
61
+ /** 注入 fetch(测试用;生产用全局 fetch)。 */
62
+ fetchImpl?: typeof fetch;
63
+ timeoutMs?: number;
64
+ now?: () => number;
65
+ }
66
+ /**
67
+ * `POST .../refresh`:`GET {baseUrl}/models`(OpenAI 标准,带 Bearer)。
68
+ *
69
+ * 提到「pi 有原生 refreshModels 的 provider 优先走 runtime.refresh」。不走:
70
+ * `runtime.getModels()` 返回的是 models.json 里的静态目录,`refresh` 对没有原生
71
+ * 实现的 provider 是 no-op——那样会「看起来刷新成功、其实拿到旧列表」。等真的接了
72
+ * 一个有原生实现的 provider(OpenRouter 按 不接)再开这条分支。
73
+ */
74
+ export declare function refreshProvider(entry: ModelProviderEntry, opts?: ProbeOptions): Promise<{
75
+ models: Array<{
76
+ id: string;
77
+ name?: string;
78
+ contextWindow?: number;
79
+ }>;
80
+ fetchedAt: string;
81
+ source: "openai-models";
82
+ } | {
83
+ error: ApiError;
84
+ }>;
85
+ /**
86
+ * `POST .../test`:发一次 `max_tokens:1` 的最小请求——`checkAuth` 只看凭证形状,
87
+ * 验不了 baseUrl 通不通、key 有没有效。
88
+ */
89
+ export declare function testProvider(entry: ModelProviderEntry, model: string, opts?: ProbeOptions): Promise<ModelTestResponse>;
90
+ /** 探测用哪个模型:白名单第一个,退而求其次目录第一个。 */
91
+ export declare function modelToProbe(entry: ModelProviderEntry): string | undefined;
92
+ /**
93
+ * 从 `models.json`(pi 真正读的那份)里取端点。`model-config.json` 的 baseUrl 是
94
+ * 给管理页看的副本;配置里还没写的时候(首次进页面、或文件缺失回落 manifest),
95
+ * refresh/test 必须能借 models.json 的端点跑起来——否则「先去 models.json 写端点,
96
+ * 回来点刷新」这个流程第一步就死。
97
+ */
98
+ export declare function baseUrlFromModelsJson(dataDir: string, providerId: string): string | undefined;