@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,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 业务接入配置面。
|
|
3
|
+
* `data/mcp-config.json` 为准,manifest 的 `mcp:` 段只是出厂种子(model-config 同款模式)。
|
|
4
|
+
*
|
|
5
|
+
* 纯函数层(parse / serialize / specUrlAllowed / toProxySpawn / mergedToolLabels)
|
|
6
|
+
* 全部**永不抛**:坏配置回落 manifest 种子 + 记 problems,助手不能因为一个错 JSON 说不了话。
|
|
7
|
+
* 语义问题只标不删的例外:整条 entry 形状不合法(翻译不出来、也连不上)时丢弃并记名——
|
|
8
|
+
* entry 是独立单元,不像 model-config 的字段那样有"救回一半"的意义。
|
|
9
|
+
*/
|
|
10
|
+
import { readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
export const MCP_CONFIG_FILENAME = "mcp-config.json";
|
|
14
|
+
/** 代理可执行文件的部署级覆盖(PyPI 装在用户 Scripts 目录,Windows 服务账号 PATH 未必有)。 */
|
|
15
|
+
export const MCP_PROXY_BIN_ENV = "MCP_PROXY_BIN";
|
|
16
|
+
/** spec/baseUrl 的 host 白名单(逗号分隔,`*.d` 通配域及其子域);不设 = 全放(4)。 */
|
|
17
|
+
export const MCP_SPEC_ALLOWLIST_ENV = "MCP_SPEC_ALLOWLIST";
|
|
18
|
+
const DEFAULT_PROXY_BIN = "mcp-openapi-proxy";
|
|
19
|
+
const CACHE_TTL_MS = 1000;
|
|
20
|
+
const NAME_RE = /^[a-z0-9][a-z0-9_-]*$/i;
|
|
21
|
+
const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
22
|
+
export function isHttpUrl(v) {
|
|
23
|
+
if (typeof v !== "string")
|
|
24
|
+
return false;
|
|
25
|
+
try {
|
|
26
|
+
const u = new URL(v);
|
|
27
|
+
return u.protocol === "http:" || u.protocol === "https:";
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** 一条 entry 的形状检查。返回 null = 合法;字符串 = 问题描述(调用方决定 fail 还是丢+记名)。 */
|
|
34
|
+
export function checkMcpDecl(name, raw) {
|
|
35
|
+
if (!NAME_RE.test(name))
|
|
36
|
+
return `name "${name}" must be letters, digits, dashes or underscores`;
|
|
37
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
38
|
+
return `mcp.${name} must be a mapping`;
|
|
39
|
+
const d = raw;
|
|
40
|
+
if (d.type !== undefined && d.type !== "stdio" && d.type !== "http" && d.type !== "openapi")
|
|
41
|
+
return `mcp.${name}.type must be stdio|http|openapi`;
|
|
42
|
+
if (d.exposure === "codemode" || d.exposure === "deferred")
|
|
43
|
+
return `mcp.${name}: exposure "${String(d.exposure)}" is not supported here; use "direct" or "hidden"`;
|
|
44
|
+
const hasStdio = typeof d.command === "string" && d.command.length > 0;
|
|
45
|
+
const hasHttp = typeof d.url === "string" && d.url.length > 0;
|
|
46
|
+
const isOpenapi = d.type === "openapi" || (d.type === undefined && !!d.openapi && !hasStdio && !hasHttp);
|
|
47
|
+
const kinds = (hasStdio ? 1 : 0) + (hasHttp ? 1 : 0) + (isOpenapi ? 1 : 0);
|
|
48
|
+
if (kinds === 0)
|
|
49
|
+
return `mcp.${name} needs a "command" (stdio), a "url" (http) or an "openapi" block`;
|
|
50
|
+
if (kinds > 1)
|
|
51
|
+
return `mcp.${name} has more than one of command/url/openapi`;
|
|
52
|
+
if (isOpenapi) {
|
|
53
|
+
const o = d.openapi;
|
|
54
|
+
if (!isHttpUrl(o.specUrl))
|
|
55
|
+
return `mcp.${name}.openapi.specUrl must be an absolute http(s) URL`;
|
|
56
|
+
if (o.baseUrl !== undefined && !isHttpUrl(o.baseUrl))
|
|
57
|
+
return `mcp.${name}.openapi.baseUrl must be an absolute http(s) URL`;
|
|
58
|
+
if (o.authEnv !== undefined) {
|
|
59
|
+
const a = o.authEnv;
|
|
60
|
+
if (!a || typeof a !== "object" || typeof a.header !== "string" || !a.header || typeof a.valueEnv !== "string" || !ENV_NAME_RE.test(a.valueEnv))
|
|
61
|
+
return `mcp.${name}.openapi.authEnv needs { header: string, valueEnv: ENV_NAME }`;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (d.toolExposure !== undefined) {
|
|
65
|
+
if (typeof d.toolExposure !== "object" || d.toolExposure === null)
|
|
66
|
+
return `mcp.${name}.toolExposure must be a mapping`;
|
|
67
|
+
for (const [tool, ex] of Object.entries(d.toolExposure)) {
|
|
68
|
+
if (ex !== "direct" && ex !== "hidden")
|
|
69
|
+
return `mcp.${name}.toolExposure["${tool}"] must be "direct" or "hidden"`;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (d.labels !== undefined) {
|
|
73
|
+
if (typeof d.labels !== "object" || d.labels === null)
|
|
74
|
+
return `mcp.${name}.labels must be a mapping`;
|
|
75
|
+
for (const [tool, label] of Object.entries(d.labels)) {
|
|
76
|
+
if (typeof label !== "string")
|
|
77
|
+
return `mcp.${name}.labels["${tool}"] must be a string`;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
/** 文件形状 → 内存形状。root 不是对象 ⇒ null(store 回落 manifest)。坏 entry 丢弃并记 problems。 */
|
|
83
|
+
export function parseMcpConfig(raw) {
|
|
84
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
85
|
+
return { servers: null, problems: ["root is not a JSON object"] };
|
|
86
|
+
const obj = raw;
|
|
87
|
+
if (obj.version !== undefined && obj.version !== 1) {
|
|
88
|
+
// 前向兼容:版本号不认识也照解析已知字段(同 model-config 口径)。
|
|
89
|
+
}
|
|
90
|
+
if (obj.servers === undefined)
|
|
91
|
+
return { servers: null, problems: ["`servers` is missing"] };
|
|
92
|
+
if (typeof obj.servers !== "object" || obj.servers === null || Array.isArray(obj.servers))
|
|
93
|
+
return { servers: null, problems: ["`servers` must be a mapping of name -> declaration"] };
|
|
94
|
+
const problems = [];
|
|
95
|
+
const servers = {};
|
|
96
|
+
for (const [name, decl] of Object.entries(obj.servers)) {
|
|
97
|
+
const problem = checkMcpDecl(name, decl);
|
|
98
|
+
if (problem) {
|
|
99
|
+
problems.push(problem);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
servers[name] = decl;
|
|
103
|
+
}
|
|
104
|
+
return { servers, problems };
|
|
105
|
+
}
|
|
106
|
+
/** manifest 的 `mcp:` 段 → 同款形状(source:"manifest")。 */
|
|
107
|
+
export function manifestMcpConfig(product, problems = []) {
|
|
108
|
+
return { version: 1, servers: product.manifest.mcp ?? {}, source: "manifest", problems };
|
|
109
|
+
}
|
|
110
|
+
/** 内存 → 文件(只写已知字段;source/problems 是运行时态,不落盘)。 */
|
|
111
|
+
export function serializeMcpConfig(cfg) {
|
|
112
|
+
return { version: 1, servers: cfg.servers };
|
|
113
|
+
}
|
|
114
|
+
export function createMcpConfigStore(dataDir, product, opts = {}) {
|
|
115
|
+
const file = path.join(dataDir, MCP_CONFIG_FILENAME);
|
|
116
|
+
const now = opts.now ?? Date.now;
|
|
117
|
+
const warn = opts.warn ?? ((m) => console.warn(m));
|
|
118
|
+
let cached;
|
|
119
|
+
let stamp = "";
|
|
120
|
+
let checkedAt = Number.NEGATIVE_INFINITY;
|
|
121
|
+
const readFile = () => {
|
|
122
|
+
let text;
|
|
123
|
+
try {
|
|
124
|
+
text = readFileSync(file, "utf8");
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
warn(`[mcp-config] cannot read ${file}: ${String(err)}; falling back to the manifest`);
|
|
128
|
+
return manifestMcpConfig(product, [`cannot read ${MCP_CONFIG_FILENAME}: ${String(err)}`]);
|
|
129
|
+
}
|
|
130
|
+
let raw;
|
|
131
|
+
try {
|
|
132
|
+
raw = JSON.parse(text);
|
|
133
|
+
}
|
|
134
|
+
catch (err) {
|
|
135
|
+
warn(`[mcp-config] ${file} is not valid JSON (${String(err)}); falling back to the manifest`);
|
|
136
|
+
return manifestMcpConfig(product, [`${MCP_CONFIG_FILENAME} is not valid JSON (${String(err)})`]);
|
|
137
|
+
}
|
|
138
|
+
const { servers, problems } = parseMcpConfig(raw);
|
|
139
|
+
if (!servers) {
|
|
140
|
+
warn(`[mcp-config] ${file} is unusable (${problems.join("; ")}); falling back to the manifest`);
|
|
141
|
+
return manifestMcpConfig(product, problems);
|
|
142
|
+
}
|
|
143
|
+
if (problems.length > 0)
|
|
144
|
+
warn(`[mcp-config] ${file}: ${problems.join("; ")}`);
|
|
145
|
+
return { version: 1, servers, source: "file", problems };
|
|
146
|
+
};
|
|
147
|
+
return {
|
|
148
|
+
path: file,
|
|
149
|
+
get() {
|
|
150
|
+
const t = now();
|
|
151
|
+
if (cached && t - checkedAt < CACHE_TTL_MS)
|
|
152
|
+
return cached;
|
|
153
|
+
checkedAt = t;
|
|
154
|
+
let stat;
|
|
155
|
+
try {
|
|
156
|
+
stat = statSync(file);
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
stat = undefined;
|
|
160
|
+
}
|
|
161
|
+
const next = stat ? `${stat.mtimeMs}:${stat.size}` : "";
|
|
162
|
+
if (cached && next === stamp)
|
|
163
|
+
return cached;
|
|
164
|
+
stamp = next;
|
|
165
|
+
cached = stat ? readFile() : manifestMcpConfig(product);
|
|
166
|
+
return cached;
|
|
167
|
+
},
|
|
168
|
+
invalidate() {
|
|
169
|
+
cached = undefined;
|
|
170
|
+
stamp = "";
|
|
171
|
+
checkedAt = Number.NEGATIVE_INFINITY;
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
/** 原子写(同款:tmp + rename,崩了不留半个 JSON),写完作废缓存。 */
|
|
176
|
+
export function saveMcpConfig(store, cfg) {
|
|
177
|
+
const body = JSON.stringify(serializeMcpConfig(cfg), null, 2) + "\n";
|
|
178
|
+
const tmp = `${store.path}.${process.pid}.${Date.now()}.tmp`;
|
|
179
|
+
writeFileSync(tmp, body, "utf8");
|
|
180
|
+
try {
|
|
181
|
+
renameSync(tmp, store.path);
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
try {
|
|
185
|
+
unlinkSync(tmp);
|
|
186
|
+
}
|
|
187
|
+
catch { /* 已经没了就算了 */ }
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
190
|
+
store.invalidate();
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* 4:`MCP_SPEC_ALLOWLIST` 不设 = 全放(含内网——私有化接内网 API 是主场景);
|
|
194
|
+
* 设了 = specUrl/baseUrl 的 host 必须命中。项逗号分隔;`*.d` 匹配 d 本身及其子域;
|
|
195
|
+
* 非 http(s) scheme 一律拒。纯函数,probe/保存两条路共用。
|
|
196
|
+
*/
|
|
197
|
+
export function specUrlAllowed(url, allowlist) {
|
|
198
|
+
if (allowlist === undefined || allowlist === null || !allowlist.trim())
|
|
199
|
+
return true;
|
|
200
|
+
let host;
|
|
201
|
+
try {
|
|
202
|
+
const u = new URL(url);
|
|
203
|
+
if (u.protocol !== "http:" && u.protocol !== "https:")
|
|
204
|
+
return false;
|
|
205
|
+
host = u.hostname.toLowerCase();
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
return allowlist
|
|
211
|
+
.split(",")
|
|
212
|
+
.map((s) => s.trim().toLowerCase())
|
|
213
|
+
.filter(Boolean)
|
|
214
|
+
.some((entry) => entry.startsWith("*.")
|
|
215
|
+
? host === entry.slice(2) || host.endsWith(`.${entry.slice(2)}`)
|
|
216
|
+
: host === entry);
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* openapi entry → mcp-openapi-proxy 的 stdio spawn 形状(翻译层)。
|
|
220
|
+
* 密钥只在 spawn 时从宿主 env 取(valueEnv 存的是**变量名**,配置里永远没有密钥本体)。
|
|
221
|
+
* MCP_PROXY_BIN 允许带参数(`node C:/fake/proxy.mjs`——测试与 python -m 场景都用得上;
|
|
222
|
+
* ponytail: 按空白切分,路径含空格的解释器请放短路径或用 PATH 查找)。
|
|
223
|
+
*/
|
|
224
|
+
export function toProxySpawn(decl, id, env = process.env) {
|
|
225
|
+
const o = decl.openapi;
|
|
226
|
+
const proxyEnv = {
|
|
227
|
+
OPENAPI_SPEC_URL: o.specUrl,
|
|
228
|
+
MCP_TRANSPORT: "stdio",
|
|
229
|
+
MCP_SERVER_NAME: id,
|
|
230
|
+
};
|
|
231
|
+
if (o.baseUrl)
|
|
232
|
+
proxyEnv.SERVER_URL_OVERRIDE = o.baseUrl;
|
|
233
|
+
if (o.authEnv) {
|
|
234
|
+
const key = env[o.authEnv.valueEnv];
|
|
235
|
+
if (key) {
|
|
236
|
+
proxyEnv.API_AUTH_HEADER = o.authEnv.header;
|
|
237
|
+
proxyEnv.API_KEY = key;
|
|
238
|
+
}
|
|
239
|
+
// 变量没配 ⇒ 不注入鉴权,试连时由代理报 401/403——probe 会把失败原样带回,不静默。
|
|
240
|
+
}
|
|
241
|
+
const [command = DEFAULT_PROXY_BIN, ...args] = (env[MCP_PROXY_BIN_ENV]?.trim() || DEFAULT_PROXY_BIN).split(/\s+/);
|
|
242
|
+
return { command, args, env: proxyEnv };
|
|
243
|
+
}
|
|
244
|
+
const HTTP_VERBS = new Set(["get", "post", "put", "patch", "delete", "del", "head", "options"]);
|
|
245
|
+
/** `<method>_<path>` → method。推不出来给 "?"(页面据此保守处理,不假装知道)。 */
|
|
246
|
+
export function methodOfToolName(name) {
|
|
247
|
+
const head = name.split(/[_-]/)[0]?.toLowerCase() ?? "";
|
|
248
|
+
return HTTP_VERBS.has(head) ? head : "?";
|
|
249
|
+
}
|
|
250
|
+
/** tools/list 的一条 → 页面要的形状。inputSchema 缺/坏都给空参数表(永不抛)。 */
|
|
251
|
+
export function toProbeTool(raw) {
|
|
252
|
+
const t = (raw ?? {});
|
|
253
|
+
const name = typeof t.name === "string" ? t.name : "";
|
|
254
|
+
const props = t.inputSchema?.properties;
|
|
255
|
+
return {
|
|
256
|
+
name,
|
|
257
|
+
description: typeof t.description === "string" ? t.description : "",
|
|
258
|
+
method: methodOfToolName(name),
|
|
259
|
+
params: props && typeof props === "object" ? Object.keys(props) : [],
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* 试连:spawn 代理 → initialize → tools/list → 立刻杀掉进程。
|
|
264
|
+
* 预算 10s(口径;spike 里首连要拉 spec,>3s 是常态,留 3 倍余量)。纯 stdio
|
|
265
|
+
* JSON-RPC,无网络依赖——网络在代理进程内部发生,这里只看它回不回话。
|
|
266
|
+
*/
|
|
267
|
+
export function probeMcpProxy(decl, id, opts = {}) {
|
|
268
|
+
const spawnShape = toProxySpawn(decl, id, opts.env ?? process.env);
|
|
269
|
+
// 默认 10 秒:本地代理本该毫秒级回话,10 秒已经等于"起不来"。
|
|
270
|
+
// `MCP_PROBE_TIMEOUT_MS` 是给测试用的:CI 上并发跑用例时 CPU 一挤,本地假代理
|
|
271
|
+
// 也可能摸到 10 秒边(实测偶发 502「试连超时」,单跑就绿)——把测试的预算放宽,
|
|
272
|
+
// 而不是把生产的等待时间拉长。
|
|
273
|
+
const envTimeout = Number(process.env.MCP_PROBE_TIMEOUT_MS);
|
|
274
|
+
const timeoutMs = opts.timeoutMs ?? (Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 10_000);
|
|
275
|
+
const t0 = Date.now();
|
|
276
|
+
return new Promise((resolve) => {
|
|
277
|
+
let child;
|
|
278
|
+
try {
|
|
279
|
+
child = spawn(spawnShape.command, spawnShape.args, {
|
|
280
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
281
|
+
env: { ...process.env, ...spawnShape.env },
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
catch (err) {
|
|
285
|
+
resolve({ ok: false, error: `代理无法启动:检查 ${MCP_PROXY_BIN_ENV} 或 PATH(${String(err)})` });
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
let settled = false;
|
|
289
|
+
let buf = "";
|
|
290
|
+
const send = (msg) => {
|
|
291
|
+
try {
|
|
292
|
+
child.stdin?.write(JSON.stringify(msg) + "\n");
|
|
293
|
+
}
|
|
294
|
+
catch { /* close 之后写失败由 finish 兜住 */ }
|
|
295
|
+
};
|
|
296
|
+
const finish = (r) => {
|
|
297
|
+
if (settled)
|
|
298
|
+
return;
|
|
299
|
+
settled = true;
|
|
300
|
+
clearTimeout(timer);
|
|
301
|
+
try {
|
|
302
|
+
child.kill();
|
|
303
|
+
}
|
|
304
|
+
catch { /* 已退出 */ }
|
|
305
|
+
resolve({ ...r, tookMs: Date.now() - t0 });
|
|
306
|
+
};
|
|
307
|
+
const timer = setTimeout(() => finish({ ok: false, error: `试连超时(${Math.round(timeoutMs / 1000)}s):spec 拉取太慢或地址不可达——重试一次通常就好(代理每次都重拉 spec,无缓存)` }), timeoutMs);
|
|
308
|
+
child.on("error", () => finish({ ok: false, error: `代理无法启动:检查 ${MCP_PROXY_BIN_ENV} 或 PATH(命令 "${spawnShape.command}" 不存在?)` }));
|
|
309
|
+
child.on("close", (code) => finish({ ok: false, error: `代理退出(code ${code ?? "?"}):检查 spec 地址可达性与 ${MCP_PROXY_BIN_ENV}` }));
|
|
310
|
+
child.stdout?.on("data", (chunk) => {
|
|
311
|
+
buf += chunk.toString("utf8");
|
|
312
|
+
let nl;
|
|
313
|
+
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
314
|
+
const line = buf.slice(0, nl).trim();
|
|
315
|
+
buf = buf.slice(nl + 1);
|
|
316
|
+
if (!line)
|
|
317
|
+
continue;
|
|
318
|
+
let msg;
|
|
319
|
+
try {
|
|
320
|
+
msg = JSON.parse(line);
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
continue; // 代理可能往 stdout 混非 JSON 日志行,忽略即可
|
|
324
|
+
}
|
|
325
|
+
if (msg.id === 1) {
|
|
326
|
+
send({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
327
|
+
send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} });
|
|
328
|
+
}
|
|
329
|
+
else if (msg.id === 2) {
|
|
330
|
+
const tools = (msg.result?.tools ?? []).map(toProbeTool);
|
|
331
|
+
finish({ ok: true, tools });
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
child.stderr?.on("data", () => { });
|
|
336
|
+
send({
|
|
337
|
+
jsonrpc: "2.0",
|
|
338
|
+
id: 1,
|
|
339
|
+
method: "initialize",
|
|
340
|
+
params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "agent-chat-probe", version: "1" } },
|
|
341
|
+
});
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
/** entry.labels → tools_meta 的全名键(mcp__<id>__<tool>),盖在 manifest.toolLabels 之上。 */
|
|
345
|
+
export function mergedToolLabels(cfg, manifestLabels) {
|
|
346
|
+
const out = { ...(manifestLabels ?? {}) };
|
|
347
|
+
for (const [id, decl] of Object.entries(cfg?.servers ?? {})) {
|
|
348
|
+
for (const [tool, label] of Object.entries(decl.labels ?? {})) {
|
|
349
|
+
out[`mcp__${id}__${tool}`] = label;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return out;
|
|
353
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { type LoadedProduct, type ResolvedTier } from "./manifest.ts";
|
|
2
|
+
/**
|
|
3
|
+
* 运行时模型配置。
|
|
4
|
+
*
|
|
5
|
+
* 三层落点:凭证/端点在 data 目录的 `models.json`(pi 自己的格式),运营
|
|
6
|
+
* 配置在 data 目录的 `model-config.json`(本文件,管理页写),仓库里的 manifest
|
|
7
|
+
* 只当**兜底默认值**。所以这里的每一条路径都要能回答同一个问题:
|
|
8
|
+
* **配置没了/坏了,助手还能不能说话?** 答:回落 manifest,打一行日志,不 500。
|
|
9
|
+
*
|
|
10
|
+
* 本层只有「读 + 校验 + 解析」,没有写盘也没有 HTTP(才加端点)。写盘端点的
|
|
11
|
+
* 校验规则要和这里同源,避免「页面放行、运行时丢掉」的两套口径。
|
|
12
|
+
*/
|
|
13
|
+
export declare const MODEL_CONFIG_FILENAME = "model-config.json";
|
|
14
|
+
/** 候选上限缺省 3,可配 1–5(业务参数一律可配,规范)。 */
|
|
15
|
+
export declare const DEFAULT_MAX_CANDIDATES = 3;
|
|
16
|
+
export declare const MAX_CANDIDATES_CEILING = 5;
|
|
17
|
+
/** 失败的候选在此期间不被选为主选;进程内存态,不进库。 */
|
|
18
|
+
export declare const DEFAULT_COOLDOWN_SECONDS = 120;
|
|
19
|
+
export interface ModelCandidate {
|
|
20
|
+
provider: string;
|
|
21
|
+
model: string;
|
|
22
|
+
}
|
|
23
|
+
export interface ModelProviderEntry {
|
|
24
|
+
enabled: boolean;
|
|
25
|
+
api?: string;
|
|
26
|
+
baseUrl?: string;
|
|
27
|
+
/** 只存 `env:NAME` 引用;实际密钥在 env 或 models.json 里。 */
|
|
28
|
+
keyRef?: string;
|
|
29
|
+
/** 「允许用于本产品」的白名单子集(从 `/models` 拉回来后管理员勾)。 */
|
|
30
|
+
models: string[];
|
|
31
|
+
/**
|
|
32
|
+
* 最近一次 `GET {baseUrl}/models` 拉回的全集(新增, 之外加的一个字段)。
|
|
33
|
+
* 不持久化它,管理页首屏就只能看到白名单、看不到「还有哪些没勾」;`fetchedAt`
|
|
34
|
+
* 也就失去意义。白名单 ⊆ 目录,但手工写的配置允许暂时越界(会被标出来)。
|
|
35
|
+
*/
|
|
36
|
+
catalog: string[];
|
|
37
|
+
fetchedAt?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface ModelTierBinding {
|
|
40
|
+
/** 有序:第 0 个是主模型,其余是备份。 */
|
|
41
|
+
candidates: ModelCandidate[];
|
|
42
|
+
}
|
|
43
|
+
export interface ModelRouting {
|
|
44
|
+
failover: boolean;
|
|
45
|
+
cooldownSeconds: number;
|
|
46
|
+
stickyWithinRun: boolean;
|
|
47
|
+
}
|
|
48
|
+
export interface ModelConfig {
|
|
49
|
+
version: 1;
|
|
50
|
+
maxCandidates: number;
|
|
51
|
+
providers: Record<string, ModelProviderEntry>;
|
|
52
|
+
tiers: Record<string, ModelTierBinding>;
|
|
53
|
+
routing: ModelRouting;
|
|
54
|
+
/** `file`=model-config.json 生效;`manifest`=回落(缺文件/坏 JSON/无可用候选)。 */
|
|
55
|
+
source: "file" | "manifest";
|
|
56
|
+
/** 校验中被丢弃或纠正的项,已同步打日志;管理页可原样透出。 */
|
|
57
|
+
problems: string[];
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* 校验一份 `model-config.json`。**永不抛**:能救的项就地纠正(clamp/去重/丢候选),
|
|
61
|
+
* 救不回来的记进 `problems`。`config === null` 只在根不是对象时出现——那种情况调用方
|
|
62
|
+
* 应当整体回落 manifest。
|
|
63
|
+
*/
|
|
64
|
+
export declare function parseModelConfig(raw: unknown): {
|
|
65
|
+
config: ModelConfig | null;
|
|
66
|
+
problems: string[];
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* 回落配置:把 manifest 的 `agent.model` + `agent.tiers` 投影成同一形状。
|
|
70
|
+
* 这样上层只有一条解析路径,不用到处判「有没有配置文件」(的第 2 步)。
|
|
71
|
+
* `problems` 用来把「为什么回落」带到管理页(读文件失败/坏 JSON 时由 store 传入)。
|
|
72
|
+
*/
|
|
73
|
+
export declare function manifestModelConfig(product: LoadedProduct, problems?: string[]): ModelConfig;
|
|
74
|
+
/**
|
|
75
|
+
* 内存形状 → 文件形状(只写已知字段:`source`/`problems` 是运行时态,不落盘)。
|
|
76
|
+
* 键序固定,diff 干净。
|
|
77
|
+
*/
|
|
78
|
+
export declare function serializeModelConfig(cfg: ModelConfig): Record<string, unknown>;
|
|
79
|
+
/**
|
|
80
|
+
* 原子写(写临时文件 + rename,进程崩溃不会留下半个 JSON),写完作废缓存
|
|
81
|
+
* ——下一个 run 立刻用新配置,不用等那 1 秒。
|
|
82
|
+
*/
|
|
83
|
+
export declare function saveModelConfig(store: ModelConfigStore, cfg: ModelConfig): void;
|
|
84
|
+
export interface ModelConfigStore {
|
|
85
|
+
/** 配置文件的绝对路径(管理页要显示「去改哪个文件」)。 */
|
|
86
|
+
readonly path: string;
|
|
87
|
+
/** 读当前生效配置(1 秒级缓存,mtime/size 变了才重解析)。 */
|
|
88
|
+
get(): ModelConfig;
|
|
89
|
+
/** 主动作废缓存——写完配置后立刻生效,不用等那 1 秒。 */
|
|
90
|
+
invalidate(): void;
|
|
91
|
+
}
|
|
92
|
+
export interface ModelConfigStoreOptions {
|
|
93
|
+
/** 注入时钟(测试用;生产用 Date.now)。 */
|
|
94
|
+
now?: () => number;
|
|
95
|
+
/** 日志出口(默认 console.warn);测试里可收集断言。 */
|
|
96
|
+
warn?: (message: string) => void;
|
|
97
|
+
}
|
|
98
|
+
export declare function createModelConfigStore(dataDir: string, product: LoadedProduct, opts?: ModelConfigStoreOptions): ModelConfigStore;
|
|
99
|
+
/** 候选能不能真的拿来跑:provider 存在、已启用、模型在白名单里。 */
|
|
100
|
+
export declare function candidateUsable(cfg: ModelConfig, c: ModelCandidate): boolean;
|
|
101
|
+
/**
|
|
102
|
+
* 某档**实际可用**的有序候选。`tierId` 省略时读 `tiers.default`——配置文件可以给
|
|
103
|
+
* 「没选档位」的请求单独绑一条链;没写就返回空数组,调用方据此回落 manifest。
|
|
104
|
+
*
|
|
105
|
+
* 过滤与截断都在这里(不在 parseModelConfig):解析层保留文件里的全部候选,
|
|
106
|
+
* 这样「停用 provider → 再启用」不会丢掉绑定,写盘也不会把超上限的候选截掉。
|
|
107
|
+
*/
|
|
108
|
+
export declare function candidatesFor(cfg: ModelConfig, tierId?: string): ModelCandidate[];
|
|
109
|
+
/**
|
|
110
|
+
* 把候选链的第 0 个套回 `ResolvedTier`:thinking / multiplier / label 仍由 manifest
|
|
111
|
+
* 决定(档位语义不跟着模型跑),只有 provider+model 被配置覆盖。
|
|
112
|
+
*/
|
|
113
|
+
export declare function applyCandidates(tier: ResolvedTier, candidates: ModelCandidate[]): ResolvedTier;
|
|
114
|
+
/**
|
|
115
|
+
* run 入口的唯一解析点:manifest 先定档位语义(未知 tier id → undefined → 400),
|
|
116
|
+
* 再由 model-config 覆盖物理 provider/model。的失败切换会在此基础上取整条链。
|
|
117
|
+
*/
|
|
118
|
+
export declare function resolveRunTier(product: LoadedProduct, tierId: string | undefined, cfg?: ModelConfig): ResolvedTier | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* run 入口的**有序候选链**。链为空 ⇒ 用 manifest 的单模型,保证老部署行为不变;
|
|
121
|
+
* 只有一条时链长 1,失败切换自然退化成「不切」。
|
|
122
|
+
*/
|
|
123
|
+
export declare function resolveChain(product: LoadedProduct, tierId: string | undefined, cfg?: ModelConfig): ModelCandidate[];
|