dsh-aperture 0.3.1 → 0.3.3
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/README.en.md +11 -10
- package/README.md +11 -10
- package/lib/client.js +1463 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +2084 -131
- package/lib/{aperture.d.ts → types/aperture.d.ts} +12 -10
- package/lib/types/catalog.d.ts +25 -0
- package/lib/types/config.d.ts +204 -0
- package/lib/types/index.d.ts +37 -0
- package/lib/{metadata → types/metadata}/extract.d.ts +15 -24
- package/lib/types/metadata/modelsdev.d.ts +40 -0
- package/lib/{metadata → types/metadata}/utils.d.ts +2 -0
- package/lib/types/panel.d.ts +71 -0
- package/lib/types/profile.d.ts +55 -0
- package/lib/types/registry.d.ts +31 -0
- package/lib/{relay.d.ts → types/relay.d.ts} +2 -0
- package/lib/types/remote.d.ts +54 -0
- package/lib/types/report.d.ts +115 -0
- package/lib/types/runtime.d.ts +87 -0
- package/lib/{sync.d.ts → types/sync.d.ts} +12 -23
- package/lib/types/types.d.ts +118 -0
- package/lib/{url.d.ts → types/url.d.ts} +5 -3
- package/package.json +44 -22
- package/client/aperture.js +0 -1566
- package/lib/aperture.js +0 -107
- package/lib/catalog.d.ts +0 -35
- package/lib/catalog.js +0 -74
- package/lib/config.d.ts +0 -214
- package/lib/config.js +0 -168
- package/lib/index.d.ts +0 -70
- package/lib/metadata/extract.js +0 -217
- package/lib/metadata/modelsdev.d.ts +0 -53
- package/lib/metadata/modelsdev.js +0 -302
- package/lib/metadata/utils.js +0 -86
- package/lib/panel.d.ts +0 -86
- package/lib/panel.js +0 -263
- package/lib/profile.d.ts +0 -62
- package/lib/profile.js +0 -158
- package/lib/registry.d.ts +0 -48
- package/lib/registry.js +0 -234
- package/lib/relay.js +0 -63
- package/lib/remote.d.ts +0 -64
- package/lib/remote.js +0 -96
- package/lib/report.d.ts +0 -123
- package/lib/report.js +0 -109
- package/lib/runtime.d.ts +0 -97
- package/lib/runtime.js +0 -194
- package/lib/sync.js +0 -176
- package/lib/types.d.ts +0 -116
- package/lib/types.js +0 -10
- package/lib/url.js +0 -67
package/lib/index.js
CHANGED
|
@@ -1,134 +1,2087 @@
|
|
|
1
|
+
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
3
|
+
//#region src/metadata/utils.ts
|
|
1
4
|
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
5
|
+
* Aperture 与 models.dev 返回的松散类型 JSON 的防御式读取器。每一个都接受
|
|
6
|
+
* `unknown`,并以 `undefined` 作答而不是抛错:一条格式错误的条目不能让整个清单
|
|
7
|
+
* 刷新失败。
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-aperture/metadata/utils
|
|
10
|
+
*/
|
|
11
|
+
/** 读取普通 JSON 对象,拒绝数组与原始值。 */
|
|
12
|
+
function asRecord$1(value) {
|
|
13
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
14
|
+
}
|
|
15
|
+
/** 读取非空且已去除首尾空白的字符串。 */
|
|
16
|
+
function stringValue(value) {
|
|
17
|
+
return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
|
|
18
|
+
}
|
|
19
|
+
/** 读取严格布尔值。 */
|
|
20
|
+
function booleanValue(value) {
|
|
21
|
+
return typeof value === "boolean" ? value : void 0;
|
|
22
|
+
}
|
|
23
|
+
/** 读取正整数,接受某些清单使用的 `128k` / `1.5M` 写法。 */
|
|
24
|
+
function positiveInteger(value) {
|
|
25
|
+
if (typeof value === "number") return Number.isSafeInteger(value) && value > 0 ? value : void 0;
|
|
26
|
+
if (typeof value !== "string") return;
|
|
27
|
+
const match = value.trim().replace(/[, _]/gu, "").match(/^(\d+(?:\.\d+)?)([kKmM])?$/u);
|
|
28
|
+
if (!match) return;
|
|
29
|
+
const amount = Number(match[1]);
|
|
30
|
+
const suffix = match[2]?.toLowerCase();
|
|
31
|
+
const normalized = amount * (suffix === "m" ? 1e6 : suffix === "k" ? 1e3 : 1);
|
|
32
|
+
return Number.isSafeInteger(normalized) && normalized > 0 ? normalized : void 0;
|
|
33
|
+
}
|
|
34
|
+
/** 候选中第一个已定义且去空白后非空的字符串。 */
|
|
35
|
+
function firstString(values) {
|
|
36
|
+
for (const value of values) {
|
|
37
|
+
const normalized = stringValue(value);
|
|
38
|
+
if (normalized !== void 0) return normalized;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** 候选中第一个正整数。 */
|
|
42
|
+
function firstPositiveInteger(values) {
|
|
43
|
+
for (const value of values) {
|
|
44
|
+
const normalized = positiveInteger(value);
|
|
45
|
+
if (normalized !== void 0) return normalized;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** 候选中第一个严格布尔值。 */
|
|
49
|
+
function firstBoolean(values) {
|
|
50
|
+
for (const value of values) {
|
|
51
|
+
const normalized = booleanValue(value);
|
|
52
|
+
if (normalized !== void 0) return normalized;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** 用于精确匹配的、转小写并去除空白的键。 */
|
|
56
|
+
function normalizeKey(value) {
|
|
57
|
+
return value?.trim().toLowerCase() ?? "";
|
|
58
|
+
}
|
|
59
|
+
/** 用于宽容匹配的、转小写并折叠标点的键。 */
|
|
60
|
+
function slugKey(value) {
|
|
61
|
+
return value?.trim().toLowerCase().replace(/['"]/gu, "").replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "") ?? "";
|
|
62
|
+
}
|
|
63
|
+
/** 最后一个 `/` 之后的全部内容;没有 `/` 时即整个值。 */
|
|
64
|
+
function suffixAfterSlash(value) {
|
|
65
|
+
return value.includes("/") ? value.split("/").pop() ?? value : value;
|
|
66
|
+
}
|
|
67
|
+
//#endregion
|
|
68
|
+
//#region src/url.ts
|
|
69
|
+
/**
|
|
70
|
+
* 单个 Aperture 实例的 URL 归一化。
|
|
71
|
+
*
|
|
72
|
+
* 配置里给的是实例根地址——`https://ai.example.ts.net`——本插件与 pi-ai 适配器
|
|
73
|
+
* 访问的每个端点都由它推导出来。结尾的 `/v1` 会被容忍并剥掉,而不是报错:VS Code
|
|
74
|
+
* 那个参考实现用的是相反的习惯,带着这种习惯过来的用户不该撞上 `/v1/v1`。
|
|
75
|
+
*
|
|
76
|
+
* @module dsh-aperture/url
|
|
77
|
+
*/
|
|
78
|
+
/** 去掉 URL 字符串结尾的所有正斜杠。 */
|
|
79
|
+
function stripTrailingSlashes(value) {
|
|
80
|
+
return value.replace(/\/+$/u, "");
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* 归一化配置里的实例根地址;若没有一个可用,则报告这一点。
|
|
84
|
+
*
|
|
85
|
+
* 只给主机名时按 HTTPS 假定,查询串与片段被丢弃,结尾的 `/v1`(连同任意多个
|
|
86
|
+
* 结尾斜杠)被去掉,这样调用方永远从实例根地址开始拼路径。
|
|
87
|
+
*
|
|
88
|
+
* @param raw - 原样保留的配置值。
|
|
89
|
+
* @returns 去掉结尾斜杠的归一化根地址;当值为空、或不是绝对的 HTTP(S) URL 时
|
|
90
|
+
* 返回 `undefined`。
|
|
91
|
+
*/
|
|
92
|
+
function normalizeBaseUrl(raw) {
|
|
93
|
+
const trimmed = raw?.trim();
|
|
94
|
+
if (!trimmed) return;
|
|
95
|
+
const withScheme = /^[a-z][a-z\d+\-.]*:\/\//iu.test(trimmed) ? trimmed : `https://${trimmed}`;
|
|
96
|
+
let url;
|
|
97
|
+
try {
|
|
98
|
+
url = new URL(withScheme);
|
|
99
|
+
} catch {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return;
|
|
103
|
+
url.hash = "";
|
|
104
|
+
url.search = "";
|
|
105
|
+
const path = stripTrailingSlashes(url.pathname).replace(/\/v1$/u, "");
|
|
106
|
+
url.pathname = path || "/";
|
|
107
|
+
return stripTrailingSlashes(url.toString());
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* 列出某个实例所服务模型的端点。
|
|
111
|
+
* @param instanceRoot - 归一化后的实例根地址。
|
|
112
|
+
* @returns 绝对地址的模型清单 URL。
|
|
113
|
+
*/
|
|
114
|
+
function buildModelsEndpoint(instanceRoot) {
|
|
115
|
+
return `${stripTrailingSlashes(instanceRoot)}/v1/models`;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* 某种协议下,一条 pi-ai 路由必须携带的 `baseURL`。
|
|
119
|
+
*
|
|
120
|
+
* 两种 OpenAI 协议会在路由的 `baseURL` 后面追加各自端点,所以它们拿到的是带 `/v1`
|
|
121
|
+
* 的根地址;`anthropic-messages` 走 provider SDK,SDK 自己会追加
|
|
122
|
+
* `/v1/messages`,所以它拿到的是裸的实例根地址。
|
|
123
|
+
* @param instanceRoot - 归一化后的实例根地址。
|
|
124
|
+
* @param protocol - 该路由的协议格式。
|
|
125
|
+
* @returns 该路由的 `baseURL`。
|
|
126
|
+
*/
|
|
127
|
+
function buildRouteBaseUrl(instanceRoot, protocol) {
|
|
128
|
+
const root = stripTrailingSlashes(instanceRoot);
|
|
129
|
+
return protocol === "anthropic-messages" ? root : `${root}/v1`;
|
|
130
|
+
}
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region src/aperture.ts
|
|
133
|
+
/**
|
|
134
|
+
* 端点问询:`GET {instance}/v1/models`。
|
|
135
|
+
*
|
|
136
|
+
* 这是插件为发现过程发出的唯一网络调用。它与 `dsh-llm-pi-ai` 自己的 "fetch available
|
|
137
|
+
* models" 动作读的是同一个端点——区别在于那个动作一次只采纳一份草稿,而本插件才是让
|
|
138
|
+
* 清单自行刷新的东西。
|
|
139
|
+
*
|
|
140
|
+
* @module dsh-aperture/aperture
|
|
141
|
+
*/
|
|
142
|
+
/** 有界读取:远超此值的模型清单不是模型清单。 */
|
|
143
|
+
const MAX_RESPONSE_BYTES = 4194304;
|
|
144
|
+
/**
|
|
145
|
+
* 问询一个 Aperture 实例,获取它服务的模型。
|
|
146
|
+
*
|
|
147
|
+
* @param instanceRoot - 一个已归一化的实例根。
|
|
148
|
+
* @param options - 请求头、超时与调用方取消信号。
|
|
149
|
+
* @returns 按端点顺序排列的原始条目。
|
|
150
|
+
* @throws 当请求失败、端点拒绝、应答过大,或响应体不是模型清单时,抛出带端点名的 Error。
|
|
151
|
+
*/
|
|
152
|
+
async function fetchModelsListing(instanceRoot, options = {}) {
|
|
153
|
+
const endpoint = buildModelsEndpoint(instanceRoot);
|
|
154
|
+
const timeoutMs = options.timeoutMs ?? 2e4;
|
|
155
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
156
|
+
const signal = options.signal === void 0 ? timeout : AbortSignal.any([options.signal, timeout]);
|
|
157
|
+
let response;
|
|
158
|
+
try {
|
|
159
|
+
response = await fetch(endpoint, {
|
|
160
|
+
method: "GET",
|
|
161
|
+
headers: {
|
|
162
|
+
accept: "application/json",
|
|
163
|
+
...options.headers
|
|
164
|
+
},
|
|
165
|
+
signal
|
|
166
|
+
});
|
|
167
|
+
} catch (error) {
|
|
168
|
+
throw new Error(`${endpoint} 无法访问:${describeError(error)}`, { cause: error });
|
|
169
|
+
}
|
|
170
|
+
if (!response.ok) {
|
|
171
|
+
const detail = await readErrorDetail(response);
|
|
172
|
+
throw new Error(`${endpoint} 应答 HTTP ${response.status}${detail === void 0 ? "" : `: ${detail}`}`);
|
|
173
|
+
}
|
|
174
|
+
const declaredLength = Number(response.headers.get("content-length") ?? "");
|
|
175
|
+
if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) throw new Error(`${endpoint} 应答了 ${declaredLength} 字节,超出 ${MAX_RESPONSE_BYTES} 字节的清单上限`);
|
|
176
|
+
const text = await response.text();
|
|
177
|
+
if (text.length > MAX_RESPONSE_BYTES) throw new Error(`${endpoint} 应答了 ${text.length} 字节,超出 ${MAX_RESPONSE_BYTES} 字节的清单上限`);
|
|
178
|
+
let body;
|
|
179
|
+
try {
|
|
180
|
+
body = JSON.parse(text);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
throw new Error(`${endpoint} 没有应答 JSON:${describeError(error)}`, { cause: error });
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
entries: readEntries$1(body, endpoint),
|
|
186
|
+
endpoint
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* 从清单响应体中读取出模型行。
|
|
191
|
+
*
|
|
192
|
+
* 存在 `data` 数组时以它为准;否则读取 `models` 对象,且只有值为对象的属性才算模型。
|
|
193
|
+
* 其他形状一律拒绝而不是当作空清单——空清单会覆盖掉一份可用的清单。
|
|
194
|
+
*
|
|
195
|
+
* @param body - 已解析的响应。
|
|
196
|
+
* @param endpoint - 应答的 URL,用于诊断。
|
|
197
|
+
* @returns 按端点顺序排列的原始模型行。
|
|
198
|
+
* @throws 当响应体不是可识别的清单时抛出 Error。
|
|
199
|
+
*/
|
|
200
|
+
function readEntries$1(body, endpoint) {
|
|
201
|
+
const record = asRecord$1(body);
|
|
202
|
+
if (!record) throw new Error(`${endpoint} 没有应答 JSON 对象`);
|
|
203
|
+
if (Array.isArray(record.data)) return record.data;
|
|
204
|
+
const models = asRecord$1(record.models);
|
|
205
|
+
if (models) return Object.values(models).filter((value) => asRecord$1(value) !== void 0);
|
|
206
|
+
throw new Error(`${endpoint} 既没有应答 "data" 数组,也没有应答 "models" 对象`);
|
|
207
|
+
}
|
|
208
|
+
/** 读取错误响应体的一小段,用于诊断。 */
|
|
209
|
+
async function readErrorDetail(response) {
|
|
210
|
+
try {
|
|
211
|
+
const trimmed = (await response.text()).trim();
|
|
212
|
+
return trimmed.length === 0 ? void 0 : trimmed.slice(0, 500);
|
|
213
|
+
} catch {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
/** 把一个未知的可抛出对象渲染成单行原因。 */
|
|
218
|
+
function describeError(error) {
|
|
219
|
+
if (error instanceof Error) {
|
|
220
|
+
const cause = error.cause;
|
|
221
|
+
return cause instanceof Error && cause.message !== error.message ? `${error.message} (${cause.message})` : error.message;
|
|
222
|
+
}
|
|
223
|
+
return String(error);
|
|
224
|
+
}
|
|
225
|
+
//#endregion
|
|
226
|
+
//#region src/metadata/modelsdev.ts
|
|
227
|
+
/** provider 别名匹配优先于任何键匹配。 */
|
|
228
|
+
const PROVIDER_ALIAS_BONUS = 200;
|
|
229
|
+
/** 已索引的 models.dev 清单,按单个模型的 id 与 provider 提示查询。 */
|
|
230
|
+
var ModelCatalogIndex = class {
|
|
231
|
+
byKey = /* @__PURE__ */ new Map();
|
|
232
|
+
entries;
|
|
233
|
+
/**
|
|
234
|
+
* @param entries - 每一个可用的清单条目。
|
|
235
|
+
*/
|
|
236
|
+
constructor(entries) {
|
|
237
|
+
this.entries = entries;
|
|
238
|
+
for (const entry of entries) for (const { key, score } of entryKeys(entry)) {
|
|
239
|
+
const bucket = this.byKey.get(key);
|
|
240
|
+
if (bucket === void 0) this.byKey.set(key, [{
|
|
241
|
+
entry,
|
|
242
|
+
keyScore: score
|
|
243
|
+
}]);
|
|
244
|
+
else bucket.push({
|
|
245
|
+
entry,
|
|
246
|
+
keyScore: score
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/** 该索引持有的可用条目数量。 */
|
|
251
|
+
get size() {
|
|
252
|
+
return this.entries.length;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* 为一个网关模型解析出最佳清单条目。
|
|
256
|
+
* @param modelId - 网关公布的 id。
|
|
257
|
+
* @param providerHints - 网关上报的上游 provider id 与名称。
|
|
258
|
+
* @returns 胜出条目的元数据;无任何匹配时为 `undefined`。
|
|
259
|
+
*/
|
|
260
|
+
lookup(modelId, providerHints = []) {
|
|
261
|
+
const candidates = /* @__PURE__ */ new Map();
|
|
262
|
+
for (const { key, score } of lookupKeys(modelId)) for (const scored of this.byKey.get(key) ?? []) {
|
|
263
|
+
const current = candidates.get(scored.entry) ?? 0;
|
|
264
|
+
candidates.set(scored.entry, Math.max(current, score + scored.keyScore));
|
|
265
|
+
}
|
|
266
|
+
const hintAliases = providerHints.flatMap((hint) => providerAliases(hint));
|
|
267
|
+
const modelProviderAliases = providerAliases(modelId.split("/")[0] ?? "");
|
|
268
|
+
let best;
|
|
269
|
+
for (const [entry, baseScore] of candidates) {
|
|
270
|
+
const score = baseScore + (matchingAliasScore(entry.providerAliases, hintAliases) || matchingAliasScore(entry.providerAliases, modelProviderAliases));
|
|
271
|
+
if (best === void 0 || score > best.score) best = {
|
|
272
|
+
entry,
|
|
273
|
+
score
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
return best === void 0 ? void 0 : { ...best.entry.metadata };
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
/**
|
|
280
|
+
* 在一份已解析的 models.dev 文档之上构建查找。
|
|
281
|
+
*
|
|
282
|
+
* 接受该文档发布过的所有形态:当前扁平的 `{ "<provider>/<model>": { … } }` 映射、值携带
|
|
283
|
+
* `models` 的旧式 provider 键映射,以及在 `providers` 或 `models` 之下包装上述任一形态的对象。
|
|
284
|
+
*
|
|
285
|
+
* @param document - 已解析的 JSON,或任何其他值。
|
|
286
|
+
* @returns 该查找;文档不含可用条目时为 `undefined`。
|
|
287
|
+
*/
|
|
288
|
+
function buildCatalogLookup(document) {
|
|
289
|
+
const index = buildCatalogIndex(document);
|
|
290
|
+
if (index === void 0) return;
|
|
291
|
+
return (model) => index.lookup(model.id, providerHintsOf(model));
|
|
292
|
+
}
|
|
293
|
+
/** 仅构建索引,并暴露其大小以用于诊断。 */
|
|
294
|
+
function buildCatalogIndex(document) {
|
|
295
|
+
const entries = readEntries(document);
|
|
296
|
+
return entries.length === 0 ? void 0 : new ModelCatalogIndex(entries);
|
|
297
|
+
}
|
|
298
|
+
/** 一次查找可用于评分的 provider 提示。 */
|
|
299
|
+
function providerHintsOf(model) {
|
|
300
|
+
const hints = [
|
|
301
|
+
model.provider,
|
|
302
|
+
model.providerName,
|
|
303
|
+
model.id.includes("/") ? model.id.split("/")[0] : void 0
|
|
304
|
+
];
|
|
305
|
+
return [...new Set(hints.filter((hint) => typeof hint === "string" && hint.trim().length > 0))];
|
|
306
|
+
}
|
|
307
|
+
/** 从一份清单文档中读取每一个可用条目。 */
|
|
308
|
+
function readEntries(document) {
|
|
309
|
+
const root = asRecord$1(document);
|
|
310
|
+
if (!root) return [];
|
|
311
|
+
return readContainer(asRecord$1(root.providers) ?? asRecord$1(root.models) ?? root);
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* 读取一层容器。
|
|
315
|
+
*
|
|
316
|
+
* 通过观察各值是否携带 `models` 容器来区分「provider → { models }」与「模型键 → 模型」:
|
|
317
|
+
* models.dev 实际发布的扁平文档是第二种形态,而旧式文档把第一种直接铺在根上。
|
|
318
|
+
*/
|
|
319
|
+
function readContainer(map) {
|
|
320
|
+
return Object.values(map).some((value) => asRecord$1(asRecord$1(value)?.models) !== void 0) ? readProviderMap(map) : readModelMap(map);
|
|
321
|
+
}
|
|
322
|
+
/** 读取以 provider 为键的映射,并从其 provider 推导每个模型的别名。 */
|
|
323
|
+
function readProviderMap(providers) {
|
|
324
|
+
const entries = [];
|
|
325
|
+
for (const [providerKey, providerValue] of Object.entries(providers)) {
|
|
326
|
+
const provider = asRecord$1(providerValue);
|
|
327
|
+
const models = asRecord$1(provider?.models);
|
|
328
|
+
if (!provider || !models) continue;
|
|
329
|
+
const aliases = providerAliases(providerKey, stringValue(provider.id), stringValue(provider.name));
|
|
330
|
+
for (const [modelKey, modelValue] of Object.entries(models)) {
|
|
331
|
+
const entry = readModelEntry(modelKey, modelValue, aliases);
|
|
332
|
+
if (entry) entries.push(entry);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return entries;
|
|
336
|
+
}
|
|
337
|
+
/** 读取模型键 → 模型条目的映射,并从该键推导 provider 别名。 */
|
|
338
|
+
function readModelMap(models) {
|
|
339
|
+
const entries = [];
|
|
340
|
+
for (const [modelKey, modelValue] of Object.entries(models)) {
|
|
341
|
+
const model = asRecord$1(modelValue);
|
|
342
|
+
if (!model) continue;
|
|
343
|
+
const modelId = firstString([model.id, modelKey]) ?? modelKey;
|
|
344
|
+
const entry = readModelEntry(modelKey, model, providerAliases(modelId.includes("/") ? modelId.split("/")[0] ?? "" : ""));
|
|
345
|
+
if (entry) entries.push(entry);
|
|
346
|
+
}
|
|
347
|
+
return entries;
|
|
348
|
+
}
|
|
349
|
+
/** 读取一个清单条目;未给出任何可用信息时为 `undefined`。 */
|
|
350
|
+
function readModelEntry(modelKey, value, aliases) {
|
|
351
|
+
const model = asRecord$1(value);
|
|
352
|
+
if (!model) return;
|
|
353
|
+
const metadata = readModelMetadata(model);
|
|
354
|
+
if (metadata === void 0) return;
|
|
355
|
+
const modelId = firstString([model.id, modelKey]) ?? modelKey;
|
|
356
|
+
const modelName = firstString([model.name, model.display_name]);
|
|
357
|
+
return {
|
|
358
|
+
modelId,
|
|
359
|
+
...modelName === void 0 ? {} : { modelName },
|
|
360
|
+
providerAliases: aliases,
|
|
361
|
+
metadata
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
/** 读取一个 models.dev 条目所贡献的元数据。 */
|
|
365
|
+
function readModelMetadata(model) {
|
|
366
|
+
const limit = asRecord$1(model.limit);
|
|
367
|
+
const topProvider = asRecord$1(model.top_provider);
|
|
368
|
+
const modalities = asRecord$1(model.modalities);
|
|
369
|
+
const contextWindow = firstPositiveInteger([
|
|
370
|
+
model.contextWindow,
|
|
371
|
+
model.context_window,
|
|
372
|
+
model.context_length,
|
|
373
|
+
model.max_input_tokens,
|
|
374
|
+
limit?.context,
|
|
375
|
+
limit?.input
|
|
376
|
+
]);
|
|
377
|
+
const maxTokens = firstPositiveInteger([
|
|
378
|
+
model.maxOutputTokens,
|
|
379
|
+
model.max_output_tokens,
|
|
380
|
+
model.maxTokens,
|
|
381
|
+
model.max_tokens,
|
|
382
|
+
limit?.output,
|
|
383
|
+
topProvider?.max_completion_tokens
|
|
384
|
+
]);
|
|
385
|
+
const reasoning = typeof model.reasoning === "boolean" ? model.reasoning : void 0;
|
|
386
|
+
const input = readInputModalities(model, modalities);
|
|
387
|
+
const name = firstString([model.name, model.display_name]);
|
|
388
|
+
if (contextWindow === void 0 && maxTokens === void 0 && reasoning === void 0 && input === void 0 && name === void 0) return;
|
|
389
|
+
return {
|
|
390
|
+
...contextWindow === void 0 ? {} : { contextWindow },
|
|
391
|
+
...maxTokens === void 0 ? {} : { maxTokens },
|
|
392
|
+
...reasoning === void 0 ? {} : { reasoning },
|
|
393
|
+
...input === void 0 ? {} : { input },
|
|
394
|
+
...name === void 0 ? {} : { name }
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
/** 读取清单条目声明的输入模态。 */
|
|
398
|
+
function readInputModalities(model, modalities) {
|
|
399
|
+
const list = modalities?.input ?? model.input;
|
|
400
|
+
if (!Array.isArray(list)) return;
|
|
401
|
+
const declared = /* @__PURE__ */ new Set();
|
|
402
|
+
for (const entry of list) {
|
|
403
|
+
const label = stringValue(entry)?.toLowerCase();
|
|
404
|
+
if (label === "text") declared.add("text");
|
|
405
|
+
else if (label === "image" || label === "vision") declared.add("image");
|
|
406
|
+
}
|
|
407
|
+
return declared.size === 0 ? void 0 : [...declared];
|
|
408
|
+
}
|
|
409
|
+
/** 一个清单条目贡献的每一个索引键及其得分。 */
|
|
410
|
+
function entryKeys(entry) {
|
|
411
|
+
const values = [
|
|
412
|
+
entry.modelId,
|
|
413
|
+
suffixAfterSlash(entry.modelId),
|
|
414
|
+
entry.modelName
|
|
415
|
+
];
|
|
416
|
+
return [...new Set(values.filter((value) => typeof value === "string" && value.trim().length > 0))].flatMap((value) => [{
|
|
417
|
+
key: normalizeKey(value),
|
|
418
|
+
score: 40
|
|
419
|
+
}, {
|
|
420
|
+
key: slugKey(value),
|
|
421
|
+
score: 30
|
|
422
|
+
}]).filter((item) => item.key.length > 0);
|
|
423
|
+
}
|
|
424
|
+
/** 一个网关模型 id 被查询时使用的每一个查找键及其权重。 */
|
|
425
|
+
function lookupKeys(modelId) {
|
|
426
|
+
const suffix = suffixAfterSlash(modelId);
|
|
427
|
+
return [{
|
|
428
|
+
value: modelId,
|
|
429
|
+
score: 70
|
|
430
|
+
}, {
|
|
431
|
+
value: suffix,
|
|
432
|
+
score: 80
|
|
433
|
+
}].flatMap(({ value, score }) => [{
|
|
434
|
+
key: normalizeKey(value),
|
|
435
|
+
score
|
|
436
|
+
}, {
|
|
437
|
+
key: slugKey(value),
|
|
438
|
+
score: score - 10
|
|
439
|
+
}]).filter((item) => item.key.length > 0);
|
|
440
|
+
}
|
|
441
|
+
/** 一个 provider id 或名称响应的每一个别名写法。 */
|
|
442
|
+
function providerAliases(...values) {
|
|
443
|
+
const aliases = /* @__PURE__ */ new Set();
|
|
444
|
+
for (const value of values) {
|
|
445
|
+
const slug = slugKey(value);
|
|
446
|
+
if (!slug) continue;
|
|
447
|
+
aliases.add(slug);
|
|
448
|
+
aliases.add(slug.replace(/-?ai$/u, ""));
|
|
449
|
+
aliases.add(slug.replace(/-?api$/u, ""));
|
|
450
|
+
aliases.add(slug.replace(/-?cloud$/u, ""));
|
|
451
|
+
}
|
|
452
|
+
const normalized = /* @__PURE__ */ new Set();
|
|
453
|
+
for (const alias of aliases) {
|
|
454
|
+
if (!alias) continue;
|
|
455
|
+
normalized.add(alias);
|
|
456
|
+
switch (alias) {
|
|
457
|
+
case "google-ai-studio":
|
|
458
|
+
case "google-generative-ai":
|
|
459
|
+
normalized.add("google");
|
|
460
|
+
break;
|
|
461
|
+
case "deepseek-ai":
|
|
462
|
+
normalized.add("deepseek");
|
|
463
|
+
break;
|
|
464
|
+
case "x-ai":
|
|
465
|
+
normalized.add("xai");
|
|
466
|
+
break;
|
|
467
|
+
case "moonshot":
|
|
468
|
+
case "moonshot-ai":
|
|
469
|
+
normalized.add("moonshotai");
|
|
470
|
+
break;
|
|
471
|
+
case "xiaomi":
|
|
472
|
+
case "xiaomi-mimo": normalized.add("xiaomimimo");
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return [...normalized];
|
|
476
|
+
}
|
|
477
|
+
/** 对两个别名集评分:任何交集都算一次 provider 匹配。 */
|
|
478
|
+
function matchingAliasScore(left, right) {
|
|
479
|
+
if (left.length === 0 || right.length === 0) return 0;
|
|
480
|
+
const rightSet = new Set(right);
|
|
481
|
+
return left.some((alias) => rightSet.has(alias)) ? PROVIDER_ALIAS_BONUS : 0;
|
|
482
|
+
}
|
|
483
|
+
//#endregion
|
|
484
|
+
//#region src/catalog.ts
|
|
485
|
+
/**
|
|
486
|
+
* 可选的第二来源:models.dev。
|
|
487
|
+
*
|
|
488
|
+
* Aperture 会设定模型的容量,但很少说明某个模型是否会推理,对输入模态则完全不
|
|
489
|
+
* 提。models.dev 会为同一批模型回答这两个问题,只是 id 有时才对得上,因此该文档
|
|
490
|
+
* 只索引一次,之后按评分查询(见 `metadata/modelsdev.ts`)。
|
|
491
|
+
*
|
|
492
|
+
* 这次抓取在任何意义上都是可选的:把 `modelMetadataUrl` 留空的部署,或者清单不
|
|
493
|
+
* 可达的部署,得到的是仅来自网关的清单,而不是一次失败的刷新。
|
|
494
|
+
*
|
|
495
|
+
* @module dsh-aperture/catalog
|
|
496
|
+
*/
|
|
497
|
+
/** 有界读取:清单远小于此值,而重定向到巨大的东西则不是清单。 */
|
|
498
|
+
const MAX_CATALOG_BYTES = 16777216;
|
|
499
|
+
/** 一个清单 URL 的进程生命周期缓存。 */
|
|
500
|
+
var ModelCatalog = class {
|
|
501
|
+
loaded;
|
|
502
|
+
/**
|
|
503
|
+
* 加载(或复用)某个 URL 上的清单。
|
|
504
|
+
* @param url - 清单 URL;为空则禁用查找。
|
|
505
|
+
* @param timeoutMs - 每次请求的超时时间。
|
|
506
|
+
* @returns 加载结果;从不抛出。
|
|
507
|
+
*/
|
|
508
|
+
async load(url, timeoutMs) {
|
|
509
|
+
if (url.length === 0) return {
|
|
510
|
+
entries: 0,
|
|
511
|
+
reason: "未配置清单 URL"
|
|
512
|
+
};
|
|
513
|
+
if (this.loaded?.url === url) return this.loaded.value;
|
|
514
|
+
const value = await this.fetchCatalog(url, timeoutMs);
|
|
515
|
+
this.loaded = {
|
|
516
|
+
url,
|
|
517
|
+
value
|
|
518
|
+
};
|
|
519
|
+
return value;
|
|
520
|
+
}
|
|
521
|
+
/** 抓取、解析并索引一份清单文档。 */
|
|
522
|
+
async fetchCatalog(url, timeoutMs) {
|
|
523
|
+
let body;
|
|
524
|
+
try {
|
|
525
|
+
const response = await fetch(url, {
|
|
526
|
+
headers: { accept: "application/json" },
|
|
527
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
528
|
+
});
|
|
529
|
+
if (!response.ok) return {
|
|
530
|
+
entries: 0,
|
|
531
|
+
reason: `${url} 应答 HTTP ${response.status}`
|
|
532
|
+
};
|
|
533
|
+
const text = await response.text();
|
|
534
|
+
if (text.length > MAX_CATALOG_BYTES) return {
|
|
535
|
+
entries: 0,
|
|
536
|
+
reason: `${url} 应答了 ${text.length} 字节,超出清单上限`
|
|
537
|
+
};
|
|
538
|
+
body = JSON.parse(text);
|
|
539
|
+
} catch (error) {
|
|
540
|
+
return {
|
|
541
|
+
entries: 0,
|
|
542
|
+
reason: `${url} 无法读取:${error instanceof Error ? error.message : String(error)}`
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
const lookup = buildCatalogLookup(body);
|
|
546
|
+
if (lookup === void 0) return {
|
|
547
|
+
entries: 0,
|
|
548
|
+
reason: `${url} 中没有可用的模型元数据`
|
|
549
|
+
};
|
|
550
|
+
return {
|
|
551
|
+
lookup,
|
|
552
|
+
entries: countEntries(body)
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
/** 统计一份清单文档包含的模型条目数,仅用于报告。 */
|
|
557
|
+
function countEntries(document) {
|
|
558
|
+
if (document === null || typeof document !== "object") return 0;
|
|
559
|
+
const root = document;
|
|
560
|
+
const wrapped = root.providers ?? root.models;
|
|
561
|
+
if (wrapped !== null && typeof wrapped === "object") return Object.keys(wrapped).length;
|
|
562
|
+
return Object.keys(root).length;
|
|
563
|
+
}
|
|
564
|
+
//#endregion
|
|
565
|
+
//#region src/config.ts
|
|
566
|
+
/**
|
|
567
|
+
* 配置 schema 与解析。
|
|
568
|
+
*
|
|
569
|
+
* 本插件拥有自己的 entry(`aperture`,用户层就是 profile patch 里那一行的 `config`),
|
|
570
|
+
* 但发布出去的一切都写进**另一个** entry `llm-pi-ai`:本插件决定有哪些模型,那个适配器
|
|
571
|
+
* 决定怎么跟它们说话。
|
|
572
|
+
*
|
|
573
|
+
* 整份 schema 都是 volatile 的:设置接缝**只**暴露 volatile 字段(没有 volatile 节点的
|
|
574
|
+
* entry 不出现在 `describe()` 里,界面就无从编辑),而这里每个字段都只影响下一轮发现、
|
|
575
|
+
* 没有一项需要重启——于是配置改动被 Loader 当作就地换引用的活更新,插件不重新挂载,
|
|
576
|
+
* 正在跑的那轮刷新也不会被掐断。
|
|
577
|
+
*
|
|
578
|
+
* @module dsh-aperture/config
|
|
579
|
+
*/
|
|
580
|
+
/** 本插件拥有、并可通过它配置的设置命名空间。 */
|
|
581
|
+
const APERTURE_NAMESPACE = "aperture";
|
|
582
|
+
/** 默认清单地址;参考实现用的是同一份文档。 */
|
|
583
|
+
const DEFAULT_MODEL_METADATA_URL = "https://models.dev/models.json";
|
|
584
|
+
/** 当 Aperture 与清单都没给出容量时,为模型假定的上下文容量。 */
|
|
585
|
+
const DEFAULT_CONTEXT_WINDOW = 128e3;
|
|
586
|
+
/** 访问网关与清单的单次请求超时。没有哪个部署需要为此改一次配置。 */
|
|
587
|
+
const DEFAULT_TIMEOUT_MS = 2e4;
|
|
588
|
+
/** provider 路由键的文法,与 Models 页面自身的规则一致。 */
|
|
589
|
+
const ROUTE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
590
|
+
/** 一个配置好的模型:对已发现模型的覆盖,或者一个额外的模型。 */
|
|
591
|
+
const modelConfig = z.object({
|
|
592
|
+
/** 模型 id;与已发现的 id 对应,或者新增一个网关没有列出的模型。 */
|
|
593
|
+
id: z.string().required(),
|
|
594
|
+
/** 选择器里显示的名字。 */
|
|
595
|
+
name: z.string(),
|
|
596
|
+
/** 协议覆盖:OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages。 */
|
|
597
|
+
api: z.string(),
|
|
598
|
+
/** 上下文容量(token 数)。 */
|
|
599
|
+
contextWindow: z.number().step(1).min(1),
|
|
600
|
+
/** 输出能力(token 数)。 */
|
|
601
|
+
maxTokens: z.number().step(1).min(1),
|
|
602
|
+
/** 请求模态。 */
|
|
603
|
+
input: z.array(z.union([z.const("text"), z.const("image")])),
|
|
604
|
+
/** 强制打开或关闭推理能力。 */
|
|
605
|
+
thinking: z.boolean(),
|
|
606
|
+
/** 提供的推理档位:键 = 档位,值 = 协议里的写法。 */
|
|
607
|
+
reasoningEfforts: z.dict(z.union([z.string(), z.const(null)]))
|
|
608
|
+
});
|
|
609
|
+
/**
|
|
610
|
+
* {@link Config} 的运行时 schema。
|
|
611
|
+
*
|
|
612
|
+
* 根节点上的 `.volatile()` 让整份配置成为活引用:`apply` 拿到的是 `Ref`,读值走
|
|
613
|
+
* `.get()`,每次变更都是对同一引用的 `updateVolatile`。校验与默认值照旧——volatile
|
|
614
|
+
* 只改变结果如何被持有。
|
|
615
|
+
*/
|
|
616
|
+
const Config = z.object({
|
|
617
|
+
baseUrl: z.string().default(""),
|
|
618
|
+
route: z.string().default("aperture"),
|
|
619
|
+
apiKeyEnv: z.string().default(""),
|
|
620
|
+
headers: z.dict(z.string()).default({}),
|
|
621
|
+
enabledModelIds: z.array(z.string()).default([]),
|
|
622
|
+
modelAliases: z.dict(z.string()).default({}),
|
|
623
|
+
models: z.array(modelConfig).default([]),
|
|
624
|
+
modelMetadataUrl: z.string().default(DEFAULT_MODEL_METADATA_URL),
|
|
625
|
+
images: z.union([z.const("ignore"), z.const("metadata")]).default("ignore"),
|
|
626
|
+
reasoning: z.union([z.const("auto"), z.const("off")]).default("auto"),
|
|
627
|
+
sync: z.boolean().default(true),
|
|
628
|
+
refreshIntervalMinutes: z.number().min(0).max(1440).default(0)
|
|
629
|
+
}).volatile();
|
|
630
|
+
/**
|
|
631
|
+
* 取活引用里的那份普通配置值。
|
|
632
|
+
*
|
|
633
|
+
* 根级 volatile 只改变配置**怎么被持有**,解析与校验照旧(非法值仍在 `Config(raw)` 当场
|
|
634
|
+
* 抛出,默认值也已补齐),所以这里只把活引用读成一份快照,交给不关心「活」的那几层。
|
|
635
|
+
*
|
|
636
|
+
* @param ref - Loader 交到 `apply` 手里的配置活引用。
|
|
637
|
+
* @returns 当前那份深冻结的普通配置值。
|
|
638
|
+
*/
|
|
639
|
+
function configValue(ref) {
|
|
640
|
+
return ref.get() ?? {};
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* 从一个路由键推出这一对路由的名字与显示名。
|
|
644
|
+
*
|
|
645
|
+
* 这三条事实曾经是三个可写字段,但一个部署要换的从来只是前缀:Anthropic 那条加
|
|
646
|
+
* `-anthropic` 后缀,显示名是路由键的标题写法(`aperture` → `Aperture`)。让它们互相
|
|
647
|
+
* 矛盾因此变成不可能,而不是要校验出来的错误。
|
|
648
|
+
*
|
|
649
|
+
* @param route - 已经过文法校验的 OpenAI 兼容路由键。
|
|
650
|
+
* @returns 五个推导出来的路由与显示名。
|
|
651
|
+
*/
|
|
652
|
+
function derivedNames(route) {
|
|
653
|
+
const displayName = route.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
|
|
654
|
+
return {
|
|
655
|
+
responsesRoute: `${route}-responses`,
|
|
656
|
+
anthropicRoute: `${route}-anthropic`,
|
|
657
|
+
displayName,
|
|
658
|
+
responsesDisplayName: `${displayName} (Responses)`,
|
|
659
|
+
anthropicDisplayName: `${displayName} (Anthropic)`
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* 解析一段配置,只拒绝那些自身就矛盾的错误。
|
|
664
|
+
*
|
|
665
|
+
* `baseUrl` 缺失或不可用**不**算错误:插件照常挂载但处于休眠,这样 profile 可以在还没人
|
|
666
|
+
* 填地址时就先带着这一行。路由键则必须拒绝——写错的路由键无法靠后续写入补救,插件会静默地
|
|
667
|
+
* 什么都不发布。
|
|
668
|
+
*
|
|
669
|
+
* @param config - 已补齐默认值的 `aperture` 段(`configValue` 的返回值,不是活引用)。
|
|
670
|
+
* @returns 校验过的配置。
|
|
671
|
+
* @throws Error 当路由键不合文法、或模型覆盖自身重复/无法服务时抛出,并在消息里点名字段。
|
|
672
|
+
*/
|
|
673
|
+
function resolveConfig(config) {
|
|
674
|
+
const rawBaseUrl = (config.baseUrl ?? "").trim();
|
|
675
|
+
const instanceRoot = normalizeBaseUrl(rawBaseUrl);
|
|
676
|
+
const route = (config.route ?? "").trim();
|
|
677
|
+
if (!ROUTE_PATTERN.test(route)) throw new Error(`route "${route}" 必须是小写连字符形式的 provider 路由名(需匹配 ${String(ROUTE_PATTERN)})`);
|
|
678
|
+
const models = config.models ?? [];
|
|
679
|
+
const seen = /* @__PURE__ */ new Set();
|
|
680
|
+
for (const model of models) {
|
|
681
|
+
const id = model.id.trim();
|
|
682
|
+
if (id.length === 0) throw new Error("models[].id 不能为空");
|
|
683
|
+
if (seen.has(id)) throw new Error(`models 里重复列出了 "${id}"`);
|
|
684
|
+
seen.add(id);
|
|
685
|
+
if (model.api !== void 0 && model.api !== "openai-completions" && model.api !== "openai-responses" && model.api !== "anthropic-messages") throw new Error(`models["${id}"].api "${model.api}" 无法服务;请使用 openai-completions、openai-responses 或 anthropic-messages`);
|
|
686
|
+
}
|
|
687
|
+
const apiKeyEnv = (config.apiKeyEnv ?? "").trim();
|
|
688
|
+
return {
|
|
689
|
+
instanceRoot,
|
|
690
|
+
rawBaseUrl,
|
|
691
|
+
route,
|
|
692
|
+
...derivedNames(route),
|
|
693
|
+
apiKeyEnv: apiKeyEnv.length === 0 ? void 0 : apiKeyEnv,
|
|
694
|
+
headers: config.headers ?? {},
|
|
695
|
+
enabledModelIds: config.enabledModelIds ?? [],
|
|
696
|
+
modelAliases: config.modelAliases ?? {},
|
|
697
|
+
models,
|
|
698
|
+
modelMetadataUrl: (config.modelMetadataUrl ?? "").trim(),
|
|
699
|
+
images: config.images ?? "ignore",
|
|
700
|
+
reasoning: config.reasoning ?? "auto",
|
|
701
|
+
sync: config.sync ?? true,
|
|
702
|
+
refreshIntervalMinutes: config.refreshIntervalMinutes ?? 0
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* 把「解析当前的配置段」包成一个按源缓存的 thunk。
|
|
707
|
+
*
|
|
708
|
+
* 配置活引用的 `.get()` 只在值真的变了之后才换快照,没变就还是同一个对象,因此返回值可以
|
|
709
|
+
* 直接当**配置版本**用。不缓存的话每次调用都是新对象,运行时的版本判断永远不成立,于是每次
|
|
710
|
+
* 刷新都会多排一轮。
|
|
711
|
+
*
|
|
712
|
+
* @param source - 生效配置段的活引用(每次编辑都就地换掉它的内容)。
|
|
713
|
+
* @returns 解析后的配置;源没换时返回同一个对象。
|
|
714
|
+
*/
|
|
715
|
+
function memoizedConfig(source) {
|
|
716
|
+
let from;
|
|
717
|
+
let resolved;
|
|
718
|
+
return () => {
|
|
719
|
+
const current = source();
|
|
720
|
+
if (resolved === void 0 || from !== current) {
|
|
721
|
+
from = current;
|
|
722
|
+
resolved = resolveConfig(current);
|
|
723
|
+
}
|
|
724
|
+
return resolved;
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
//#endregion
|
|
728
|
+
//#region src/report.ts
|
|
729
|
+
/**
|
|
730
|
+
* 组装报告。
|
|
731
|
+
*
|
|
732
|
+
* @param outcome - 最近一次刷新;一次都没完成过时传 `undefined`。
|
|
733
|
+
* @param config - 当前生效配置。
|
|
734
|
+
* @param declared - 用户层里写下的覆盖;缺省即「什么都没写过」。
|
|
735
|
+
* @returns 报告。
|
|
736
|
+
*/
|
|
737
|
+
function buildReport(outcome, config, declared = {}) {
|
|
738
|
+
const keys = /* @__PURE__ */ new Map();
|
|
739
|
+
for (const entry of declared.models ?? []) {
|
|
740
|
+
const id = typeof entry.id === "string" ? entry.id.trim() : "";
|
|
741
|
+
if (id.length === 0) continue;
|
|
742
|
+
keys.set(id, Object.keys(entry).filter((key) => key !== "id"));
|
|
743
|
+
}
|
|
744
|
+
for (const id of declared.aliasIds ?? []) keys.set(id, [...keys.get(id) ?? [], "alias"]);
|
|
745
|
+
const routes = (outcome?.routes ?? []).map((route) => ({
|
|
746
|
+
provider: route.provider,
|
|
747
|
+
...route.profile.api === void 0 ? {} : { api: route.profile.api },
|
|
748
|
+
...route.profile.baseURL === void 0 ? {} : { baseURL: route.profile.baseURL },
|
|
749
|
+
models: route.models.length
|
|
750
|
+
}));
|
|
751
|
+
const models = [];
|
|
752
|
+
const routed = /* @__PURE__ */ new Set();
|
|
753
|
+
const describe = (model, route) => {
|
|
754
|
+
routed.add(model.id);
|
|
755
|
+
const declaredKeys = keys.get(model.id) ?? [];
|
|
756
|
+
const alias = config.modelAliases[model.id];
|
|
757
|
+
return {
|
|
758
|
+
id: model.id,
|
|
759
|
+
name: model.name,
|
|
760
|
+
...route === void 0 ? {} : { route },
|
|
761
|
+
...model.protocol === void 0 ? {} : { protocol: model.protocol },
|
|
762
|
+
endpoints: model.endpoints,
|
|
763
|
+
...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
|
|
764
|
+
...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens },
|
|
765
|
+
input: model.input,
|
|
766
|
+
reasoning: model.reasoning,
|
|
767
|
+
provenance: model.provenance,
|
|
768
|
+
...declaredKeys.length === 0 ? {} : { overrideKeys: declaredKeys },
|
|
769
|
+
...alias === void 0 ? {} : { alias }
|
|
770
|
+
};
|
|
771
|
+
};
|
|
772
|
+
for (const route of outcome?.routes ?? []) for (const model of route.models) models.push(describe(model, route.provider));
|
|
773
|
+
for (const model of outcome?.models ?? []) if (!routed.has(model.id)) models.push(describe(model));
|
|
774
|
+
return {
|
|
775
|
+
place: config.instanceRoot ?? config.rawBaseUrl,
|
|
776
|
+
...outcome === void 0 ? {} : { refresh: refresh(outcome) },
|
|
777
|
+
routes,
|
|
778
|
+
models
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* 把一次刷新收成报告要显示的字段。
|
|
783
|
+
*
|
|
784
|
+
* @param outcome - 已完成的刷新。
|
|
785
|
+
* @returns 状态段的数据。
|
|
786
|
+
*/
|
|
787
|
+
function refresh(outcome) {
|
|
788
|
+
const catalog = outcome.catalog;
|
|
789
|
+
const sync = outcome.sync;
|
|
790
|
+
return {
|
|
791
|
+
trigger: outcome.trigger,
|
|
792
|
+
at: outcome.at.toISOString(),
|
|
793
|
+
durationMs: outcome.durationMs,
|
|
794
|
+
ok: outcome.ok,
|
|
795
|
+
...outcome.error === void 0 ? {} : { error: outcome.error },
|
|
796
|
+
catalog: {
|
|
797
|
+
available: catalog.lookup !== void 0,
|
|
798
|
+
entries: catalog.entries,
|
|
799
|
+
...catalog.reason === void 0 ? {} : { reason: catalog.reason }
|
|
800
|
+
},
|
|
801
|
+
...outcome.endpoint === void 0 ? {} : { endpoint: {
|
|
802
|
+
url: outcome.endpoint,
|
|
803
|
+
listed: outcome.listed
|
|
804
|
+
} },
|
|
805
|
+
...sync === void 0 ? {} : { sync: {
|
|
806
|
+
applied: sync.applied,
|
|
807
|
+
ops: sync.ops,
|
|
808
|
+
routes: sync.routes,
|
|
809
|
+
...sync.reason === void 0 ? {} : { reason: sync.reason }
|
|
810
|
+
} }
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
//#endregion
|
|
814
|
+
//#region src/metadata/extract.ts
|
|
815
|
+
/** 每个 Aperture 条目可能用来藏匿其事实的嵌套容器。 */
|
|
816
|
+
function containers(record) {
|
|
817
|
+
const metadata = asRecord$1(record.metadata);
|
|
818
|
+
return {
|
|
819
|
+
metadata,
|
|
820
|
+
capabilities: asRecord$1(record.capabilities),
|
|
821
|
+
metadataCapabilities: asRecord$1(metadata?.capabilities),
|
|
822
|
+
limit: asRecord$1(record.limit),
|
|
823
|
+
limits: asRecord$1(record.limits),
|
|
824
|
+
modalities: asRecord$1(record.modalities)
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* 读取一个条目所述的容量,可位于顶层,或嵌套在 `metadata`、`limit`、`limits` 之下。
|
|
829
|
+
*
|
|
830
|
+
* @param value - 一条原始模型条目。
|
|
831
|
+
* @returns 所述的容量;两者都未给出时为 `undefined`。
|
|
832
|
+
*/
|
|
833
|
+
function extractLimits(value) {
|
|
834
|
+
const record = asRecord$1(value);
|
|
835
|
+
if (!record) return;
|
|
836
|
+
const { metadata, limit, limits } = containers(record);
|
|
837
|
+
const metadataLimit = asRecord$1(metadata?.limit);
|
|
838
|
+
const metadataLimits = asRecord$1(metadata?.limits);
|
|
839
|
+
const contextWindow = firstPositiveInteger([
|
|
840
|
+
record.context_window_tokens,
|
|
841
|
+
record.max_context_tokens,
|
|
842
|
+
record.maxInputTokens,
|
|
843
|
+
record.max_input_tokens,
|
|
844
|
+
record.input_token_limit,
|
|
845
|
+
limit?.input,
|
|
846
|
+
limits?.input,
|
|
847
|
+
metadata?.maxInputTokens,
|
|
848
|
+
metadata?.max_input_tokens,
|
|
849
|
+
metadata?.input_token_limit,
|
|
850
|
+
metadataLimit?.input,
|
|
851
|
+
metadataLimits?.input,
|
|
852
|
+
record.context_length,
|
|
853
|
+
record.max_context_length,
|
|
854
|
+
record.context_window,
|
|
855
|
+
limit?.context,
|
|
856
|
+
limits?.context,
|
|
857
|
+
metadata?.context_length,
|
|
858
|
+
metadata?.max_context_length,
|
|
859
|
+
metadata?.context_window,
|
|
860
|
+
metadata?.max_context_tokens,
|
|
861
|
+
metadata?.context_window_tokens,
|
|
862
|
+
metadataLimit?.context,
|
|
863
|
+
metadataLimits?.context
|
|
864
|
+
]);
|
|
865
|
+
const maxTokens = firstPositiveInteger([
|
|
866
|
+
record.max_output_tokens,
|
|
867
|
+
record.maxOutputTokens,
|
|
868
|
+
record.output_token_limit,
|
|
869
|
+
record.max_completion_tokens,
|
|
870
|
+
limit?.output,
|
|
871
|
+
limits?.output,
|
|
872
|
+
metadata?.max_output_tokens,
|
|
873
|
+
metadata?.maxOutputTokens,
|
|
874
|
+
metadata?.output_token_limit,
|
|
875
|
+
metadata?.max_completion_tokens,
|
|
876
|
+
metadataLimit?.output,
|
|
877
|
+
metadataLimits?.output
|
|
878
|
+
]);
|
|
879
|
+
if (contextWindow === void 0 && maxTokens === void 0) return;
|
|
880
|
+
return {
|
|
881
|
+
...contextWindow === void 0 ? {} : { contextWindow },
|
|
882
|
+
...maxTokens === void 0 ? {} : { maxTokens }
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
/** 读取条目所述的显示名(`display_name` 是 Aperture 的写法)。 */
|
|
886
|
+
function extractDisplayName(value) {
|
|
887
|
+
const record = asRecord$1(value);
|
|
888
|
+
if (!record) return;
|
|
889
|
+
const metadata = asRecord$1(record.metadata);
|
|
890
|
+
return firstString([
|
|
891
|
+
record.display_name,
|
|
892
|
+
record.displayName,
|
|
893
|
+
record.name,
|
|
894
|
+
metadata?.display_name,
|
|
895
|
+
metadata?.name
|
|
896
|
+
]);
|
|
897
|
+
}
|
|
898
|
+
/** 读取条目公布的端点路径。 */
|
|
899
|
+
function extractEndpoints(value) {
|
|
900
|
+
const raw = asRecord$1(value)?.supported_endpoints;
|
|
901
|
+
if (!Array.isArray(raw)) return [];
|
|
902
|
+
return raw.flatMap((entry) => {
|
|
903
|
+
const path = stringValue(entry);
|
|
904
|
+
return path === void 0 ? [] : [path];
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
/** 读取条目上报的上游 provider 身份。 */
|
|
908
|
+
function extractProvider(value) {
|
|
909
|
+
const record = asRecord$1(value);
|
|
910
|
+
if (!record) return;
|
|
911
|
+
const metadata = asRecord$1(record.metadata);
|
|
912
|
+
const provider = asRecord$1(metadata?.provider);
|
|
913
|
+
const id = firstString([
|
|
914
|
+
provider?.id,
|
|
915
|
+
record.owned_by,
|
|
916
|
+
metadata?.provider_id
|
|
917
|
+
]);
|
|
918
|
+
const name = firstString([provider?.name, metadata?.provider_name]);
|
|
919
|
+
if (id === void 0 && name === void 0) return;
|
|
920
|
+
return {
|
|
921
|
+
...id === void 0 ? {} : { id },
|
|
922
|
+
...name === void 0 ? {} : { name }
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* 读取一个条目所述的能力事实。
|
|
927
|
+
*
|
|
928
|
+
* `reasoning: true` 是参考扩展与 models.dev 的信号;`thinking` 标志和嵌套的 `capabilities`
|
|
929
|
+
* 块是网关自己的词汇。视觉能力从 `modalities.input` 以及 `vision` / `supports_vision` 读取。
|
|
930
|
+
*
|
|
931
|
+
* @param value - 一条原始模型条目。
|
|
932
|
+
* @returns 所述的能力;未给出任何能力时为 `undefined`。
|
|
933
|
+
*/
|
|
934
|
+
function extractCapabilities(value) {
|
|
935
|
+
const record = asRecord$1(value);
|
|
936
|
+
if (!record) return;
|
|
937
|
+
const { metadata, capabilities, metadataCapabilities, modalities } = containers(record);
|
|
938
|
+
const reasoning = firstBoolean([
|
|
939
|
+
record.reasoning,
|
|
940
|
+
record.thinking,
|
|
941
|
+
capabilities?.reasoning,
|
|
942
|
+
capabilities?.thinking,
|
|
943
|
+
metadata?.reasoning,
|
|
944
|
+
metadata?.thinking,
|
|
945
|
+
metadataCapabilities?.reasoning,
|
|
946
|
+
metadataCapabilities?.thinking
|
|
947
|
+
]) ?? void 0;
|
|
948
|
+
const toolCalling = firstBoolean([
|
|
949
|
+
record.tool_call,
|
|
950
|
+
record.toolCalling,
|
|
951
|
+
capabilities?.tool_call,
|
|
952
|
+
capabilities?.toolCalling,
|
|
953
|
+
metadata?.tool_call,
|
|
954
|
+
metadata?.toolCalling,
|
|
955
|
+
metadataCapabilities?.tool_call,
|
|
956
|
+
metadataCapabilities?.toolCalling
|
|
957
|
+
]) ?? void 0;
|
|
958
|
+
const input = extractInput(record, metadata, capabilities, metadataCapabilities, modalities);
|
|
959
|
+
if (reasoning === void 0 && toolCalling === void 0 && input === void 0) return;
|
|
960
|
+
return {
|
|
961
|
+
...reasoning === void 0 ? {} : { reasoning },
|
|
962
|
+
...toolCalling === void 0 ? {} : { toolCalling },
|
|
963
|
+
...input === void 0 ? {} : { input }
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
/** 从两个清单使用的所有写法中读取声明的请求模态。 */
|
|
967
|
+
function extractInput(record, metadata, capabilities, metadataCapabilities, modalities) {
|
|
968
|
+
const lists = [
|
|
969
|
+
record.input,
|
|
970
|
+
record.input_modalities,
|
|
971
|
+
modalities?.input,
|
|
972
|
+
asRecord$1(metadata?.modalities)?.input,
|
|
973
|
+
metadata?.input,
|
|
974
|
+
metadata?.input_modalities
|
|
975
|
+
];
|
|
976
|
+
for (const list of lists) {
|
|
977
|
+
if (!Array.isArray(list)) continue;
|
|
978
|
+
const declared = [];
|
|
979
|
+
for (const entry of list) {
|
|
980
|
+
const label = stringValue(entry)?.toLowerCase();
|
|
981
|
+
if (label === "text" || label === "image" || label === "vision") declared.push(label === "text" ? "text" : "image");
|
|
982
|
+
}
|
|
983
|
+
if (declared.length > 0) return [...new Set(declared)];
|
|
984
|
+
}
|
|
985
|
+
const vision = firstBoolean([
|
|
986
|
+
record.vision,
|
|
987
|
+
record.supports_vision,
|
|
988
|
+
capabilities?.vision,
|
|
989
|
+
capabilities?.image,
|
|
990
|
+
metadata?.vision,
|
|
991
|
+
metadata?.supports_vision,
|
|
992
|
+
metadataCapabilities?.vision,
|
|
993
|
+
metadataCapabilities?.image
|
|
994
|
+
]);
|
|
995
|
+
if (vision === true) return ["text", "image"];
|
|
996
|
+
if (vision === false) return ["text"];
|
|
997
|
+
}
|
|
998
|
+
/** 一个条目究竟是不是可用的模型行。 */
|
|
999
|
+
function extractModelId(value) {
|
|
1000
|
+
const record = asRecord$1(value);
|
|
1001
|
+
return record === void 0 ? void 0 : stringValue(record.id);
|
|
1002
|
+
}
|
|
1003
|
+
//#endregion
|
|
1004
|
+
//#region src/registry.ts
|
|
1005
|
+
/**
|
|
1006
|
+
* 归一化阶段:一条原始网关条目,加上清单元数据,再加上配置,变成一个
|
|
1007
|
+
* `DiscoveredModel`。
|
|
1008
|
+
*
|
|
1009
|
+
* 三个决策只在这里做出,别处没有。
|
|
1010
|
+
*
|
|
1011
|
+
* **模型从哪个端点应答。** 端点由网关的 `supported_endpoints` 决定:只通过原生
|
|
1012
|
+
* `generateContent` 服务的 Gemini 模型 `dsh-llm-pi-ai` 根本够不到,发布到 OpenAI 兼容
|
|
1013
|
+
* 路由上只会得到一个每个请求都失败的模型。没有路由可服务的模型留在报告里,但不发布。
|
|
1014
|
+
*
|
|
1015
|
+
* **谁来决定模型的容量。** Aperture 优先(网关知道每个上游前面的代理接受什么),
|
|
1016
|
+
* models.dev 补它没说明的,配置兜底最后。兜底值只设定 `contextWindow`——没人声明过的
|
|
1017
|
+
* 输出上限保持缺失,免得把每个请求都限制在一个凭空捏造的数字上。
|
|
1018
|
+
*
|
|
1019
|
+
* **谁来决定模型是否会推理。** 依次是 Aperture、models.dev、插件的 `reasoning` 开关。
|
|
1020
|
+
* 错误的「是」会让用户选推理档位时付出一个 400 的代价,因此不从模型名猜测。
|
|
1021
|
+
*
|
|
1022
|
+
* @module dsh-aperture/registry
|
|
1023
|
+
*/
|
|
1024
|
+
/** 每个 OpenAI 兼容模型都必须通告的端点。 */
|
|
1025
|
+
const OPENAI_ENDPOINT = "/v1/chat/completions";
|
|
1026
|
+
/** OpenAI Responses 模型通告的端点。 */
|
|
1027
|
+
const OPENAI_RESPONSES_ENDPOINT = "/v1/responses";
|
|
1028
|
+
/** 每个 Anthropic Messages 模型都必须通告的端点。 */
|
|
1029
|
+
const ANTHROPIC_ENDPOINT = "/v1/messages";
|
|
1030
|
+
/**
|
|
1031
|
+
* 归一化、补全并合并一份网关清单。
|
|
1032
|
+
*
|
|
1033
|
+
* @param entries - 按端点顺序排列的原始模型行。
|
|
1034
|
+
* @param options - 配置开关。
|
|
1035
|
+
* @param lookup - 清单元数据查找器,在已加载时提供。
|
|
1036
|
+
* @returns 每个模型及其来源,以及没有路由能服务的那些模型。
|
|
1037
|
+
*/
|
|
1038
|
+
function buildRegistry(entries, options, lookup) {
|
|
1039
|
+
const enabled = new Set(options.enabledModelIds.map((id) => id.trim()).filter((id) => id.length > 0));
|
|
1040
|
+
const configuredById = /* @__PURE__ */ new Map();
|
|
1041
|
+
for (const configured of options.models) {
|
|
1042
|
+
const id = configured.id.trim();
|
|
1043
|
+
if (id.length > 0 && !configuredById.has(id)) configuredById.set(id, configured);
|
|
1044
|
+
}
|
|
1045
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1046
|
+
const models = [];
|
|
1047
|
+
for (const entry of entries) {
|
|
1048
|
+
const id = extractModelId(entry);
|
|
1049
|
+
if (id === void 0 || seen.has(id)) continue;
|
|
1050
|
+
if (enabled.size > 0 && !enabled.has(id)) continue;
|
|
1051
|
+
seen.add(id);
|
|
1052
|
+
models.push(fromEndpoint(entry, id, options, lookup));
|
|
1053
|
+
}
|
|
1054
|
+
for (const [id] of configuredById) {
|
|
1055
|
+
if (seen.has(id)) continue;
|
|
1056
|
+
seen.add(id);
|
|
1057
|
+
models.push(fromConfiguration(id, options, lookup));
|
|
1058
|
+
}
|
|
1059
|
+
const merged = models.map((model) => {
|
|
1060
|
+
const configured = configuredById.get(model.id);
|
|
1061
|
+
return configured === void 0 ? model : applyConfigured(model, configured, options);
|
|
1062
|
+
});
|
|
1063
|
+
return {
|
|
1064
|
+
models: merged,
|
|
1065
|
+
unserved: merged.filter((model) => model.protocol === void 0)
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
/** 归一化网关通告的一行。 */
|
|
1069
|
+
function fromEndpoint(entry, id, options, lookup) {
|
|
1070
|
+
const apertureLimits = extractLimits(entry);
|
|
1071
|
+
const capabilities = extractCapabilities(entry);
|
|
1072
|
+
const provider = extractProvider(entry);
|
|
1073
|
+
const endpoints = extractEndpoints(entry);
|
|
1074
|
+
const apertureName = extractDisplayName(entry);
|
|
1075
|
+
const catalog = lookupModel(lookup, id, provider, options.modelAliases);
|
|
1076
|
+
const protocol = classifyProtocol(endpoints);
|
|
1077
|
+
return {
|
|
1078
|
+
id,
|
|
1079
|
+
name: apertureName ?? catalog?.name ?? id,
|
|
1080
|
+
...protocol === void 0 ? {} : { protocol },
|
|
1081
|
+
endpoints,
|
|
1082
|
+
contextWindow: apertureLimits?.contextWindow ?? catalog?.contextWindow ?? 128e3,
|
|
1083
|
+
...resolveOutputCap(apertureLimits?.maxTokens ?? catalog?.maxTokens),
|
|
1084
|
+
input: options.images === "metadata" ? capabilities?.input ?? catalog?.input ?? ["text"] : ["text"],
|
|
1085
|
+
reasoning: options.reasoning === "auto" && (capabilities?.reasoning ?? catalog?.reasoning ?? false),
|
|
1086
|
+
...provider?.id === void 0 ? {} : { provider: provider.id },
|
|
1087
|
+
provenance: {
|
|
1088
|
+
limits: limitsSource(apertureLimits, catalog),
|
|
1089
|
+
reasoning: factsSource(capabilities?.reasoning, catalog?.reasoning),
|
|
1090
|
+
input: factsSource(capabilities?.input, catalog?.input),
|
|
1091
|
+
name: apertureName !== void 0 ? "aperture" : catalog?.name !== void 0 ? "models.dev" : "default"
|
|
1092
|
+
}
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
/** 归一化一个只因配置点名而存在的模型。 */
|
|
1096
|
+
function fromConfiguration(id, options, lookup) {
|
|
1097
|
+
const catalog = lookupModel(lookup, id, void 0, options.modelAliases);
|
|
1098
|
+
return {
|
|
1099
|
+
id,
|
|
1100
|
+
name: catalog?.name ?? id,
|
|
1101
|
+
endpoints: [],
|
|
1102
|
+
contextWindow: catalog?.contextWindow ?? 128e3,
|
|
1103
|
+
...resolveOutputCap(catalog?.maxTokens),
|
|
1104
|
+
input: options.images === "metadata" ? catalog?.input ?? ["text"] : ["text"],
|
|
1105
|
+
reasoning: options.reasoning === "auto" && (catalog?.reasoning ?? false),
|
|
1106
|
+
provenance: {
|
|
1107
|
+
limits: limitsSource(void 0, catalog),
|
|
1108
|
+
reasoning: factsSource(void 0, catalog?.reasoning),
|
|
1109
|
+
input: factsSource(void 0, catalog?.input),
|
|
1110
|
+
name: catalog?.name !== void 0 ? "models.dev" : "default"
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
/** 把一条配置条目声明的字段应用到一个已发现的模型上。 */
|
|
1115
|
+
function applyConfigured(model, configured, options) {
|
|
1116
|
+
const protocol = protocolFromConfigured(configured) ?? model.protocol;
|
|
1117
|
+
const contextWindow = configured.contextWindow ?? model.contextWindow;
|
|
1118
|
+
const maxTokens = configured.maxTokens ?? model.maxTokens;
|
|
1119
|
+
const name = configured.name?.trim() || model.name;
|
|
1120
|
+
const declaredInput = configured.input !== void 0 && configured.input.length > 0 ? configured.input : void 0;
|
|
1121
|
+
const input = declaredInput ?? model.input;
|
|
1122
|
+
return {
|
|
1123
|
+
id: model.id,
|
|
1124
|
+
name,
|
|
1125
|
+
...protocol === void 0 ? {} : { protocol },
|
|
1126
|
+
endpoints: model.endpoints,
|
|
1127
|
+
contextWindow: contextWindow ?? 128e3,
|
|
1128
|
+
...resolveOutputCap(maxTokens),
|
|
1129
|
+
input: declaredInput !== void 0 || options.images === "metadata" ? input : ["text"],
|
|
1130
|
+
reasoning: configured.thinking ?? model.reasoning,
|
|
1131
|
+
...model.provider === void 0 ? {} : { provider: model.provider },
|
|
1132
|
+
provenance: {
|
|
1133
|
+
limits: configured.contextWindow !== void 0 || configured.maxTokens !== void 0 ? "config" : model.provenance.limits,
|
|
1134
|
+
reasoning: configured.thinking !== void 0 ? "config" : model.provenance.reasoning,
|
|
1135
|
+
input: declaredInput !== void 0 ? "config" : model.provenance.input,
|
|
1136
|
+
name: configured.name?.trim() ? "config" : model.provenance.name
|
|
1137
|
+
}
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
/** 仅当确实有来源声明了输出上限时才带上它。 */
|
|
1141
|
+
function resolveOutputCap(maxTokens) {
|
|
1142
|
+
return maxTokens === void 0 ? {} : { maxTokens };
|
|
1143
|
+
}
|
|
1144
|
+
/** 防御式地查询清单查找器:查找器绝不能导致刷新失败。 */
|
|
1145
|
+
function lookupModel(lookup, id, provider, aliases) {
|
|
1146
|
+
if (lookup === void 0) return;
|
|
1147
|
+
const candidates = [aliases[id], id].filter((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
|
|
1148
|
+
for (const candidate of candidates) try {
|
|
1149
|
+
const found = lookup({
|
|
1150
|
+
id: candidate,
|
|
1151
|
+
...provider?.id === void 0 ? {} : { provider: provider.id },
|
|
1152
|
+
...provider?.name === void 0 ? {} : { providerName: provider.name }
|
|
1153
|
+
});
|
|
1154
|
+
if (found !== void 0) return found;
|
|
1155
|
+
} catch {}
|
|
1156
|
+
}
|
|
1157
|
+
/** 容量类事实的来源。 */
|
|
1158
|
+
function limitsSource(apertureLimits, catalog) {
|
|
1159
|
+
if (apertureLimits !== void 0) return "aperture";
|
|
1160
|
+
return catalog?.contextWindow !== void 0 || catalog?.maxTokens !== void 0 ? "models.dev" : "default";
|
|
1161
|
+
}
|
|
1162
|
+
/** 一项 Aperture 与清单都会回答的能力事实的来源。 */
|
|
1163
|
+
function factsSource(apertureFact, catalogFact) {
|
|
1164
|
+
if (apertureFact !== void 0) return "aperture";
|
|
1165
|
+
return catalogFact !== void 0 ? "models.dev" : "default";
|
|
1166
|
+
}
|
|
1167
|
+
/** 把配置里的一种 `api` 写法映射到可服务的协议。 */
|
|
1168
|
+
function protocolFromConfigured(configured) {
|
|
1169
|
+
switch (configured.api?.trim()) {
|
|
1170
|
+
case "openai-completions": return "openai-completions";
|
|
1171
|
+
case "openai-responses": return "openai-responses";
|
|
1172
|
+
case "anthropic-messages": return "anthropic-messages";
|
|
1173
|
+
default: return;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* 决定一个模型通告的端点适配哪条路由。
|
|
1178
|
+
*
|
|
1179
|
+
* 完全没有通告端点的清单按 OpenAI 兼容处理:不上报传输方式的网关绝大多数就是普通
|
|
1180
|
+
* Chat Completions 代理,而没有路由的模型无论如何都不可用。
|
|
1181
|
+
*
|
|
1182
|
+
* @param endpoints - 通告的端点路径。
|
|
1183
|
+
* @returns 可服务的协议;没有适配的协议时为 `undefined`。
|
|
1184
|
+
*/
|
|
1185
|
+
function classifyProtocol(endpoints) {
|
|
1186
|
+
if (endpoints.length === 0) return "openai-completions";
|
|
1187
|
+
if (endpoints.some((endpoint) => matchesEndpoint(endpoint, OPENAI_ENDPOINT))) return "openai-completions";
|
|
1188
|
+
if (endpoints.some((endpoint) => matchesEndpoint(endpoint, OPENAI_RESPONSES_ENDPOINT))) return "openai-responses";
|
|
1189
|
+
if (endpoints.some((endpoint) => matchesEndpoint(endpoint, ANTHROPIC_ENDPOINT))) return "anthropic-messages";
|
|
1190
|
+
}
|
|
1191
|
+
/** 判断一个通告的端点是否就是(或以之结尾)某个已知路径。 */
|
|
1192
|
+
function matchesEndpoint(advertised, known) {
|
|
1193
|
+
const path = advertised.split("?")[0]?.replace(/\/+$/u, "") ?? "";
|
|
1194
|
+
return path === known || path.endsWith(known);
|
|
1195
|
+
}
|
|
1196
|
+
/** 判断一个模型是否属于 DeepSeek 推理方言。 */
|
|
1197
|
+
function isDeepSeekFamily(model) {
|
|
1198
|
+
return `${model.id} ${model.name} ${model.provider ?? ""}`.toLowerCase().includes("deepseek");
|
|
1199
|
+
}
|
|
1200
|
+
//#endregion
|
|
1201
|
+
//#region src/profile.ts
|
|
1202
|
+
/** 无凭据路由发送的占位凭据的默认值。 */
|
|
1203
|
+
const DEFAULT_PLACEHOLDER_CREDENTIAL = "dsh-aperture";
|
|
1204
|
+
/** 为 DeepSeek 方言模型提供的推理档位。 */
|
|
1205
|
+
const DEEPSEEK_EFFORTS = {
|
|
1206
|
+
off: "disabled",
|
|
1207
|
+
high: "high",
|
|
1208
|
+
max: "max"
|
|
1209
|
+
};
|
|
1210
|
+
/**
|
|
1211
|
+
* 为其他所有推理模型提供的推理档位。
|
|
1212
|
+
*
|
|
1213
|
+
* `off` 无值——适配器把它映射为「什么都不发」,对 OpenAI 兼容端点而言这就是把思考交给
|
|
1214
|
+
* 模型自行决定。它之上的那一档是 Aperture 在它所代理的全部模型上都能接受的最宽写法;
|
|
1215
|
+
* `minimal`、`xhigh`、`max` 都至少被某个上游以 400 拒绝过,因此发现的模型绝不提供,
|
|
1216
|
+
* 更了解的部署可以在 `models` 里逐模型声明。
|
|
1217
|
+
*/
|
|
1218
|
+
const GENERIC_EFFORTS = {
|
|
1219
|
+
off: null,
|
|
1220
|
+
high: "high"
|
|
1221
|
+
};
|
|
1222
|
+
/**
|
|
1223
|
+
* 把归一化后的注册表变成 provider profile。
|
|
1224
|
+
*
|
|
1225
|
+
* @param models - 所有已发现的模型。
|
|
1226
|
+
* @param options - 路由与凭据配置。
|
|
1227
|
+
* @returns 要发布的路由,以及未能被服务的模型。
|
|
1228
|
+
*/
|
|
1229
|
+
function buildProfilePlan(models, options) {
|
|
1230
|
+
const completions = models.filter((model) => model.protocol === "openai-completions");
|
|
1231
|
+
const responses = models.filter((model) => model.protocol === "openai-responses");
|
|
1232
|
+
const anthropic = models.filter((model) => model.protocol === "anthropic-messages");
|
|
1233
|
+
const routes = [];
|
|
1234
|
+
if (completions.length > 0) routes.push({
|
|
1235
|
+
provider: options.route,
|
|
1236
|
+
profile: buildProfile("openai-completions", completions, options),
|
|
1237
|
+
models: completions
|
|
1238
|
+
});
|
|
1239
|
+
if (responses.length > 0) routes.push({
|
|
1240
|
+
provider: options.responsesRoute,
|
|
1241
|
+
profile: buildProfile("openai-responses", responses, options),
|
|
1242
|
+
models: responses
|
|
1243
|
+
});
|
|
1244
|
+
if (anthropic.length > 0) routes.push({
|
|
1245
|
+
provider: options.anthropicRoute,
|
|
1246
|
+
profile: buildProfile("anthropic-messages", anthropic, options),
|
|
1247
|
+
models: anthropic
|
|
1248
|
+
});
|
|
1249
|
+
return {
|
|
1250
|
+
routes,
|
|
1251
|
+
unserved: models.filter((model) => model.protocol === void 0),
|
|
1252
|
+
ownedRoutes: [
|
|
1253
|
+
options.route,
|
|
1254
|
+
options.responsesRoute,
|
|
1255
|
+
options.anthropicRoute
|
|
1256
|
+
]
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
/** 构建一种协议的路由 profile。 */
|
|
1260
|
+
function buildProfile(protocol, models, options) {
|
|
1261
|
+
const headers = routeHeaders(protocol, options);
|
|
1262
|
+
return {
|
|
1263
|
+
displayName: protocol === "openai-completions" ? options.displayName : protocol === "openai-responses" ? options.responsesDisplayName : options.anthropicDisplayName,
|
|
1264
|
+
api: protocol,
|
|
1265
|
+
baseURL: buildRouteBaseUrl(options.instanceRoot, protocol),
|
|
1266
|
+
...options.apiKeyEnv === void 0 ? {} : { apiKeyEnv: options.apiKeyEnv },
|
|
1267
|
+
...headers === void 0 ? {} : { headers },
|
|
1268
|
+
models: models.map((model) => buildModelEntry(model, protocol, options))
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
/**
|
|
1272
|
+
* 一条路由发送的头。
|
|
1273
|
+
*
|
|
1274
|
+
* 已配置的 `apiKeyEnv` 完全取代占位头——此后由凭据接缝提供。插件自身配置里的部署头在两种
|
|
1275
|
+
* 情况下都优先于占位头,需要真实静态令牌的网关正是借此拿到它。
|
|
1276
|
+
*
|
|
1277
|
+
* @param protocol - 该路由的协议。
|
|
1278
|
+
* @param options - 配置。
|
|
1279
|
+
* @returns 头字典;该路由不需要任何头时为 `undefined`。
|
|
1280
|
+
*/
|
|
1281
|
+
function routeHeaders(protocol, options) {
|
|
1282
|
+
const headers = {};
|
|
1283
|
+
if (!(options.apiKeyEnv !== void 0 || Object.keys(options.headers).some((name) => {
|
|
1284
|
+
const lower = name.toLowerCase();
|
|
1285
|
+
return lower === "authorization" || lower === "x-api-key" || lower === "cf-aig-authorization";
|
|
1286
|
+
}))) {
|
|
1287
|
+
if (protocol === "anthropic-messages") headers["x-api-key"] = DEFAULT_PLACEHOLDER_CREDENTIAL;
|
|
1288
|
+
else headers.authorization = `Bearer ${DEFAULT_PLACEHOLDER_CREDENTIAL}`;
|
|
1289
|
+
}
|
|
1290
|
+
Object.assign(headers, options.headers);
|
|
1291
|
+
return Object.keys(headers).length === 0 ? void 0 : headers;
|
|
1292
|
+
}
|
|
1293
|
+
/** 构建一条已配置的模型条目。 */
|
|
1294
|
+
function buildModelEntry(model, protocol, options) {
|
|
1295
|
+
const reasoning = resolveReasoning(model, protocol, options.configured.find((candidate) => candidate.id.trim() === model.id));
|
|
1296
|
+
return {
|
|
1297
|
+
id: model.id,
|
|
1298
|
+
name: model.name,
|
|
1299
|
+
...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
|
|
1300
|
+
...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens },
|
|
1301
|
+
input: [...model.input],
|
|
1302
|
+
...reasoning
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1305
|
+
/** 解析一条模型条目携带的推理字段。 */
|
|
1306
|
+
function resolveReasoning(model, protocol, configured) {
|
|
1307
|
+
const declared = configured?.reasoningEfforts;
|
|
1308
|
+
if (declared !== void 0 && Object.keys(declared).length > 0) return {
|
|
1309
|
+
reasoningEfforts: { ...declared },
|
|
1310
|
+
...compatFor(model, protocol)
|
|
1311
|
+
};
|
|
1312
|
+
if (!model.reasoning) return {};
|
|
1313
|
+
if (protocol === "anthropic-messages" && configured?.thinking !== true) return {};
|
|
1314
|
+
if (isDeepSeekFamily(model)) return {
|
|
1315
|
+
reasoningEfforts: { ...DEEPSEEK_EFFORTS },
|
|
1316
|
+
...compatFor(model, protocol)
|
|
1317
|
+
};
|
|
1318
|
+
return {
|
|
1319
|
+
reasoningEfforts: { ...GENERIC_EFFORTS },
|
|
1320
|
+
...compatFor(model, protocol)
|
|
1321
|
+
};
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* 推理模型所需的 compat 块。
|
|
1325
|
+
*
|
|
1326
|
+
* pi-ai 从 provider id 与 base URL 推断协议格式兼容性,而 Aperture 的 URL 对它说明不了
|
|
1327
|
+
* 什么,因此 DeepSeek 方言必须直接声明。`supportsReasoningEffort` 也要声明:URL 无法被
|
|
1328
|
+
* pi-ai 归位的网关目前默认为 true,但真正让 `reasoning_effort` 传输出去的是这个开关。
|
|
1329
|
+
*
|
|
1330
|
+
* @param model - 被描述的模型。
|
|
1331
|
+
* @param protocol - 该路由的协议。
|
|
1332
|
+
* @returns compat 块,或空对象。
|
|
1333
|
+
*/
|
|
1334
|
+
function compatFor(model, protocol) {
|
|
1335
|
+
if (protocol !== "openai-completions") return {};
|
|
1336
|
+
const compat = { supportsReasoningEffort: true };
|
|
1337
|
+
if (isDeepSeekFamily(model)) compat.thinkingFormat = "deepseek";
|
|
1338
|
+
return { compat };
|
|
1339
|
+
}
|
|
1340
|
+
//#endregion
|
|
1341
|
+
//#region src/sync.ts
|
|
1342
|
+
/** pi-ai 适配器注册的设置命名空间,也是本插件写入的那一个。 */
|
|
1343
|
+
const PI_AI_NAMESPACE = "llm-pi-ai";
|
|
1344
|
+
/**
|
|
1345
|
+
* 找一个 entry 的 descriptor。
|
|
1346
|
+
*
|
|
1347
|
+
* 设置接缝没有「按命名空间取值」这种读法:`describe()` 是唯一入口,它按 Loader 里的 entry
|
|
1348
|
+
* 逐个报告(`ns` 就是 entry id)。目标 entry 不存在时(比如 pi-ai 适配器没挂载)读不到。
|
|
1349
|
+
*
|
|
1350
|
+
* @param settings - 设置服务。
|
|
1351
|
+
* @param ns - 目标 entry id。
|
|
1352
|
+
* @returns 该 entry 的 descriptor;没有这个 entry 时为 `undefined`。
|
|
1353
|
+
*/
|
|
1354
|
+
function sectionDescriptor(settings, ns) {
|
|
1355
|
+
try {
|
|
1356
|
+
return settings.describe().find((descriptor) => descriptor.ns === ns);
|
|
1357
|
+
} catch {
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* 读一个 entry 的生效值。
|
|
1363
|
+
*
|
|
1364
|
+
* @param settings - 设置服务。
|
|
1365
|
+
* @param ns - 目标 entry id。
|
|
1366
|
+
* @returns 该 entry 的生效值(深冻结快照);没有这个 entry 时为 `undefined`。
|
|
1367
|
+
*/
|
|
1368
|
+
function sectionValue(settings, ns) {
|
|
1369
|
+
return sectionDescriptor(settings, ns)?.value;
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* 计算使某个配置段与方案一致的路径 op。
|
|
1373
|
+
*
|
|
1374
|
+
* @param current - 已解析的 `llm-pi-ai` 值;命名空间未注册时为 `undefined`。
|
|
1375
|
+
* @param routes - 方案希望存在的路由。
|
|
1376
|
+
* @param ownedRoutes - 本插件拥有的每个路由键,因此不再有模型的路由会被移除,而不是
|
|
1377
|
+
* 继续服务一份陈旧的清单。
|
|
1378
|
+
* @returns 要应用的 op;配置段已经匹配时为空数组。
|
|
1379
|
+
*/
|
|
1380
|
+
function planSync(current, routes, ownedRoutes) {
|
|
1381
|
+
const providers = readProviders(current);
|
|
1382
|
+
if (providers === void 0) return [];
|
|
1383
|
+
const ops = [];
|
|
1384
|
+
const desired = new Map(routes.map((route) => [route.provider, route.profile]));
|
|
1385
|
+
for (const provider of ownedRoutes) {
|
|
1386
|
+
const profile = desired.get(provider);
|
|
1387
|
+
if (profile === void 0) {
|
|
1388
|
+
if (provider in providers) ops.push({
|
|
1389
|
+
op: "unset",
|
|
1390
|
+
path: ["providers", provider]
|
|
1391
|
+
});
|
|
1392
|
+
continue;
|
|
1393
|
+
}
|
|
1394
|
+
if (deepEqualJson(providers[provider], profile)) continue;
|
|
1395
|
+
ops.push({
|
|
1396
|
+
op: "set",
|
|
1397
|
+
path: ["providers", provider],
|
|
1398
|
+
value: profile
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
return ops;
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* 把一个方案发布到 `llm-pi-ai` 配置段。
|
|
1405
|
+
*
|
|
1406
|
+
* @param settings - 设置服务。
|
|
1407
|
+
* @param routes - 要发布的路由。
|
|
1408
|
+
* @param ownedRoutes - 本插件拥有的每个路由键。
|
|
1409
|
+
* @returns 发生了什么;未写入任何内容时包含原因。
|
|
1410
|
+
*/
|
|
1411
|
+
async function applySync(settings, routes, ownedRoutes) {
|
|
1412
|
+
const current = sectionValue(settings, PI_AI_NAMESPACE);
|
|
1413
|
+
if (current === void 0) return {
|
|
1414
|
+
applied: false,
|
|
1415
|
+
ops: 0,
|
|
1416
|
+
routes: [],
|
|
1417
|
+
reason: `设置命名空间 "${PI_AI_NAMESPACE}" 未注册;@deepseek-ai/dsh-llm-pi-ai 是否已挂载?`
|
|
1418
|
+
};
|
|
1419
|
+
if (readProviders(current) === void 0) return {
|
|
1420
|
+
applied: false,
|
|
1421
|
+
ops: 0,
|
|
1422
|
+
routes: [],
|
|
1423
|
+
reason: `"${PI_AI_NAMESPACE}" 配置段不是 provider 字典`
|
|
1424
|
+
};
|
|
1425
|
+
const ops = planSync(current, routes, ownedRoutes);
|
|
1426
|
+
if (ops.length === 0) return {
|
|
1427
|
+
applied: false,
|
|
1428
|
+
ops: 0,
|
|
1429
|
+
routes: routes.map((route) => route.provider),
|
|
1430
|
+
reason: "已处于同步状态"
|
|
1431
|
+
};
|
|
1432
|
+
try {
|
|
1433
|
+
await settings.mutate(PI_AI_NAMESPACE, ops, currentRevision(settings));
|
|
1434
|
+
} catch (error) {
|
|
1435
|
+
if (!isConflict(error)) throw error;
|
|
1436
|
+
const retryOps = planSync(sectionValue(settings, PI_AI_NAMESPACE), routes, ownedRoutes);
|
|
1437
|
+
if (retryOps.length === 0) return {
|
|
1438
|
+
applied: false,
|
|
1439
|
+
ops: 0,
|
|
1440
|
+
routes: routes.map((route) => route.provider),
|
|
1441
|
+
reason: "已处于同步状态"
|
|
1442
|
+
};
|
|
1443
|
+
await settings.mutate(PI_AI_NAMESPACE, retryOps, currentRevision(settings));
|
|
1444
|
+
}
|
|
1445
|
+
return {
|
|
1446
|
+
applied: true,
|
|
1447
|
+
ops: ops.length,
|
|
1448
|
+
routes: routes.map((route) => route.provider)
|
|
1449
|
+
};
|
|
1450
|
+
}
|
|
1451
|
+
/** 从已解析的配置段值中读出 provider 字典。 */
|
|
1452
|
+
function readProviders(current) {
|
|
1453
|
+
if (current === null || typeof current !== "object") return;
|
|
1454
|
+
const providers = current.providers;
|
|
1455
|
+
if (providers === void 0) return {};
|
|
1456
|
+
return providers !== null && typeof providers === "object" && !Array.isArray(providers) ? providers : void 0;
|
|
1457
|
+
}
|
|
1458
|
+
/** pi-ai 配置段的当前版本号;provider 未暴露时为空。 */
|
|
1459
|
+
function currentRevision(settings) {
|
|
1460
|
+
return sectionDescriptor(settings, PI_AI_NAMESPACE)?.revision;
|
|
1461
|
+
}
|
|
1462
|
+
/** 判断某个可抛出对象是否为设置接缝的陈旧版本号冲突。 */
|
|
1463
|
+
function isConflict(error) {
|
|
1464
|
+
return error instanceof Error && error.code === "SETTINGS_CONFLICT";
|
|
1465
|
+
}
|
|
1466
|
+
/**
|
|
1467
|
+
* 结构化 JSON 相等性。
|
|
1468
|
+
*
|
|
1469
|
+
* 之所以自己写而不导入,是因为这里比较的值恰好都是 JSON:本插件生成的 profile,以及设置
|
|
1470
|
+
* 接缝从文档里解析回来的 profile。键顺序不属于这种同一性,因此被归一化掉。
|
|
1471
|
+
*
|
|
1472
|
+
* @param left - 一个 JSON 值。
|
|
1473
|
+
* @param right - 另一个。
|
|
1474
|
+
* @returns 两者是否结构相等。
|
|
1475
|
+
*/
|
|
1476
|
+
function deepEqualJson(left, right) {
|
|
1477
|
+
if (left === right) return true;
|
|
1478
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
1479
|
+
if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
|
|
1480
|
+
return left.every((value, index) => deepEqualJson(value, right[index]));
|
|
1481
|
+
}
|
|
1482
|
+
if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;
|
|
1483
|
+
const leftRecord = left;
|
|
1484
|
+
const rightRecord = right;
|
|
1485
|
+
const leftKeys = Object.keys(leftRecord).filter((key) => leftRecord[key] !== void 0);
|
|
1486
|
+
const rightKeys = Object.keys(rightRecord).filter((key) => rightRecord[key] !== void 0);
|
|
1487
|
+
if (leftKeys.length !== rightKeys.length) return false;
|
|
1488
|
+
return leftKeys.every((key) => key in rightRecord && deepEqualJson(leftRecord[key], rightRecord[key]));
|
|
1489
|
+
}
|
|
1490
|
+
//#endregion
|
|
1491
|
+
//#region src/runtime.ts
|
|
1492
|
+
/** 单飞(single-flight)的发现与发布。 */
|
|
1493
|
+
var ApertureRuntime = class {
|
|
1494
|
+
deps;
|
|
1495
|
+
running;
|
|
1496
|
+
/** 正在跑的那一轮读的是哪一份配置;用来判断排队者该并进它还是排到它后面。 */
|
|
1497
|
+
runningConfig;
|
|
1498
|
+
latest;
|
|
1499
|
+
/**
|
|
1500
|
+
* @param deps - 宿主服务与配置活引用(thunk)。
|
|
1501
|
+
*/
|
|
1502
|
+
constructor(deps) {
|
|
1503
|
+
this.deps = deps;
|
|
1504
|
+
}
|
|
1505
|
+
/** 最近一次已完成的刷新(如果完成过)。 */
|
|
1506
|
+
last() {
|
|
1507
|
+
return this.latest;
|
|
1508
|
+
}
|
|
1509
|
+
/**
|
|
1510
|
+
* 刷新;已有刷新在运行时,等它收尾之后再决定是并进新的一轮,还是自己起一轮。
|
|
1511
|
+
*
|
|
1512
|
+
* 承诺是「返回的那一轮读的是**此刻**的配置」:正在跑的那一轮若读的就是此刻这份配置,
|
|
1513
|
+
* 调用方并进它;否则等它收尾再重问一次。设置界面刚写完配置就来重读报告时,等的必须是
|
|
1514
|
+
* 读过新配置的那一轮——等正在跑的那一轮回来等于拿回过期报告,界面于是「保存了却没变」。
|
|
1515
|
+
* 配置身份可以直接比:设置服务每次提交都换一份深冻结的解析结果,没变就还是同一个对象。
|
|
1516
|
+
*
|
|
1517
|
+
* @param trigger - 触发来源;出现在配置页的状态段里。
|
|
1518
|
+
* @returns 本次调用所参与的那一轮刷新的结果。
|
|
1519
|
+
*/
|
|
1520
|
+
async refresh(trigger) {
|
|
1521
|
+
if (this.running !== void 0) {
|
|
1522
|
+
if (this.runningConfig === this.deps.config()) return this.running;
|
|
1523
|
+
await this.running;
|
|
1524
|
+
return this.refresh(trigger);
|
|
1525
|
+
}
|
|
1526
|
+
const config = this.deps.config();
|
|
1527
|
+
const run = this.run(trigger, config);
|
|
1528
|
+
this.running = run;
|
|
1529
|
+
this.runningConfig = config;
|
|
1530
|
+
try {
|
|
1531
|
+
return await run;
|
|
1532
|
+
} finally {
|
|
1533
|
+
this.running = void 0;
|
|
1534
|
+
this.runningConfig = void 0;
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
/** 执行一次刷新,绝不抛出异常。 */
|
|
1538
|
+
async run(trigger, config) {
|
|
1539
|
+
const started = Date.now();
|
|
1540
|
+
const at = /* @__PURE__ */ new Date();
|
|
1541
|
+
try {
|
|
1542
|
+
return await this.execute(trigger, config, started, at);
|
|
1543
|
+
} catch (error) {
|
|
1544
|
+
const outcome = {
|
|
1545
|
+
trigger,
|
|
1546
|
+
ok: false,
|
|
1547
|
+
at,
|
|
1548
|
+
durationMs: Date.now() - started,
|
|
1549
|
+
listed: 0,
|
|
1550
|
+
models: [],
|
|
1551
|
+
routes: [],
|
|
1552
|
+
unserved: [],
|
|
1553
|
+
catalog: {
|
|
1554
|
+
entries: 0,
|
|
1555
|
+
reason: "未执行"
|
|
1556
|
+
},
|
|
1557
|
+
error: message(error)
|
|
1558
|
+
};
|
|
1559
|
+
this.latest = outcome;
|
|
1560
|
+
this.deps.logger.warn("刷新失败:%s", outcome.error ?? "");
|
|
1561
|
+
return outcome;
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
/** 一次刷新的主体。 */
|
|
1565
|
+
async execute(trigger, config, started, at) {
|
|
1566
|
+
if (config.instanceRoot === void 0) {
|
|
1567
|
+
const outcome = {
|
|
1568
|
+
trigger,
|
|
1569
|
+
ok: false,
|
|
1570
|
+
at,
|
|
1571
|
+
durationMs: Date.now() - started,
|
|
1572
|
+
listed: 0,
|
|
1573
|
+
models: [],
|
|
1574
|
+
routes: [],
|
|
1575
|
+
unserved: [],
|
|
1576
|
+
catalog: {
|
|
1577
|
+
entries: 0,
|
|
1578
|
+
reason: "未尝试"
|
|
1579
|
+
},
|
|
1580
|
+
error: config.rawBaseUrl.length === 0 ? "未配置 baseUrl" : `baseUrl "${config.rawBaseUrl}" 不是可用的 URL`
|
|
1581
|
+
};
|
|
1582
|
+
this.latest = outcome;
|
|
1583
|
+
return outcome;
|
|
1584
|
+
}
|
|
1585
|
+
const catalog = await this.deps.catalog.load(config.modelMetadataUrl, DEFAULT_TIMEOUT_MS);
|
|
1586
|
+
let listed;
|
|
1587
|
+
let endpoint;
|
|
1588
|
+
try {
|
|
1589
|
+
const listing = await fetchModelsListing(config.instanceRoot, { timeoutMs: DEFAULT_TIMEOUT_MS });
|
|
1590
|
+
listed = listing.entries;
|
|
1591
|
+
endpoint = listing.endpoint;
|
|
1592
|
+
} catch (error) {
|
|
1593
|
+
const outcome = {
|
|
1594
|
+
trigger,
|
|
1595
|
+
ok: false,
|
|
1596
|
+
at,
|
|
1597
|
+
durationMs: Date.now() - started,
|
|
1598
|
+
listed: 0,
|
|
1599
|
+
models: [],
|
|
1600
|
+
routes: [],
|
|
1601
|
+
unserved: [],
|
|
1602
|
+
catalog,
|
|
1603
|
+
error: message(error)
|
|
1604
|
+
};
|
|
1605
|
+
this.latest = outcome;
|
|
1606
|
+
this.deps.logger.warn("发现失败;保留已发布的清单:%s", outcome.error ?? "");
|
|
1607
|
+
return outcome;
|
|
1608
|
+
}
|
|
1609
|
+
const registry = buildRegistry(listed, {
|
|
1610
|
+
models: config.models,
|
|
1611
|
+
enabledModelIds: config.enabledModelIds,
|
|
1612
|
+
modelAliases: config.modelAliases,
|
|
1613
|
+
images: config.images,
|
|
1614
|
+
reasoning: config.reasoning
|
|
1615
|
+
}, catalog.lookup);
|
|
1616
|
+
const plan = buildProfilePlan(registry.models, {
|
|
1617
|
+
instanceRoot: config.instanceRoot,
|
|
1618
|
+
route: config.route,
|
|
1619
|
+
responsesRoute: config.responsesRoute,
|
|
1620
|
+
anthropicRoute: config.anthropicRoute,
|
|
1621
|
+
displayName: config.displayName,
|
|
1622
|
+
responsesDisplayName: config.responsesDisplayName,
|
|
1623
|
+
anthropicDisplayName: config.anthropicDisplayName,
|
|
1624
|
+
...config.apiKeyEnv === void 0 ? {} : { apiKeyEnv: config.apiKeyEnv },
|
|
1625
|
+
headers: config.headers,
|
|
1626
|
+
configured: config.models
|
|
1627
|
+
});
|
|
1628
|
+
const sync = await this.publish(config, plan);
|
|
1629
|
+
const outcome = {
|
|
1630
|
+
trigger,
|
|
1631
|
+
ok: true,
|
|
1632
|
+
at,
|
|
1633
|
+
durationMs: Date.now() - started,
|
|
1634
|
+
endpoint,
|
|
1635
|
+
listed: listed.length,
|
|
1636
|
+
models: registry.models,
|
|
1637
|
+
routes: plan.routes,
|
|
1638
|
+
unserved: plan.unserved,
|
|
1639
|
+
catalog,
|
|
1640
|
+
sync
|
|
1641
|
+
};
|
|
1642
|
+
this.latest = outcome;
|
|
1643
|
+
this.deps.logger.info("发现 %d 个模型(来自 %s);已发布 %d 条路由%s", registry.models.length, endpoint, plan.routes.length, sync.applied ? "" : ` (${sync.reason ?? "未写入"})`);
|
|
1644
|
+
return outcome;
|
|
1645
|
+
}
|
|
1646
|
+
/** 写入方案,或说明为什么没有写入任何内容。 */
|
|
1647
|
+
async publish(config, plan) {
|
|
1648
|
+
const routes = config.sync ? plan.routes : [];
|
|
1649
|
+
try {
|
|
1650
|
+
const outcome = await applySync(this.deps.settings, routes, plan.ownedRoutes);
|
|
1651
|
+
return config.sync || outcome.applied ? outcome : {
|
|
1652
|
+
...outcome,
|
|
1653
|
+
reason: "同步已关闭,本插件没有发布过路由"
|
|
1654
|
+
};
|
|
1655
|
+
} catch (error) {
|
|
1656
|
+
this.deps.logger.warn("发布发现的清单失败:%s", message(error));
|
|
1657
|
+
return {
|
|
1658
|
+
applied: false,
|
|
1659
|
+
ops: 0,
|
|
1660
|
+
routes: [],
|
|
1661
|
+
reason: message(error)
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
};
|
|
1666
|
+
/** 把未知的可抛出对象渲染为单行原因。 */
|
|
1667
|
+
function message(error) {
|
|
1668
|
+
return error instanceof Error ? error.message : String(error);
|
|
1669
|
+
}
|
|
1670
|
+
//#endregion
|
|
1671
|
+
//#region src/panel.ts
|
|
1672
|
+
/** 把未知值当成一个普通对象;数组与 `null` 都不算。 */
|
|
1673
|
+
function asRecord(input) {
|
|
1674
|
+
return typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
|
|
1675
|
+
}
|
|
1676
|
+
/** 一个值是不是「没写」:空串、空数组、空字典都算。 */
|
|
1677
|
+
function isEmpty(value) {
|
|
1678
|
+
if (value === void 0 || value === null) return true;
|
|
1679
|
+
if (typeof value === "string") return value.trim().length === 0;
|
|
1680
|
+
if (Array.isArray(value)) return value.length === 0;
|
|
1681
|
+
if (typeof value === "object") return Object.keys(value).length === 0;
|
|
1682
|
+
return false;
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* 剔掉一条覆盖里的空值,只留 `id` 与真正写下的内容。
|
|
1686
|
+
*
|
|
1687
|
+
* 生效值里混着 schema 补出来的默认值(没写的数组字段会变成 `[]`)。原样写回用户层就成了用户
|
|
1688
|
+
* 从没写过的覆盖,界面上那颗「已覆盖」会一直挂着,按「恢复默认」又撤不掉。
|
|
1689
|
+
*
|
|
1690
|
+
* @param entry - 生效值里的一条。
|
|
1691
|
+
* @returns 可以写进用户层的那几条键。
|
|
1692
|
+
*/
|
|
1693
|
+
function prune(entry) {
|
|
1694
|
+
return Object.fromEntries(Object.entries(entry).filter(([key, value]) => key === "id" || !isEmpty(value)));
|
|
1695
|
+
}
|
|
1696
|
+
/**
|
|
1697
|
+
* 用户层里写下的覆盖。
|
|
1698
|
+
*
|
|
1699
|
+
* 「有没有覆盖」只能从用户层读:生效值里分不出用户写下的值与 schema 补出来的默认值。
|
|
1700
|
+
*
|
|
1701
|
+
* @param settings - 设置服务。
|
|
1702
|
+
* @returns `aperture.models` 的原样条目,以及写过别名的模型 id。
|
|
1703
|
+
*/
|
|
1704
|
+
function declaredOverrides(settings) {
|
|
1705
|
+
const user = readSection(settings).user;
|
|
1706
|
+
return {
|
|
1707
|
+
models: (Array.isArray(user.models) ? user.models : []).map(asRecord),
|
|
1708
|
+
aliasIds: Object.keys(asRecord(user.modelAliases))
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
/**
|
|
1712
|
+
* 读 `aperture` 段。
|
|
1713
|
+
*
|
|
1714
|
+
* `value` 是叠加默认值、组合层与用户层后的生效值,`user` 是用户层的原始片段——字段在不在
|
|
1715
|
+
* `user` 里才是「有没有被覆盖」的判据,拿生效值去和组合层比会得出错误答案。
|
|
1716
|
+
*
|
|
1717
|
+
* @param settings - 设置服务。
|
|
1718
|
+
* @returns 解析视图;命名空间尚未注册或描述符读不到时给出空值。
|
|
1719
|
+
*/
|
|
1720
|
+
function readSection(settings) {
|
|
1721
|
+
let descriptor;
|
|
1722
|
+
try {
|
|
1723
|
+
descriptor = settings.describe({ redactSecrets: true }).find((entry) => entry.ns === APERTURE_NAMESPACE);
|
|
1724
|
+
} catch {
|
|
1725
|
+
descriptor = void 0;
|
|
1726
|
+
}
|
|
1727
|
+
return {
|
|
1728
|
+
value: asRecord(descriptor?.value),
|
|
1729
|
+
user: asRecord(descriptor?.user),
|
|
1730
|
+
revision: descriptor?.revision
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
/**
|
|
1734
|
+
* 把补丁合并进 `models` 里的一条覆盖。
|
|
1735
|
+
*
|
|
1736
|
+
* 只做**校验与合并**,不做任何写入:非法值在这里挡下来,因为写进设置文档的坏值会让下一轮刷新的
|
|
1737
|
+
* `resolveConfig` 直接抛异常,而界面只能给用户一份再也刷新不出来的报告。
|
|
1738
|
+
*
|
|
1739
|
+
* @param base - 现有条目;没有时只带 `id`。
|
|
1740
|
+
* @param patch - 界面发来的稀疏补丁。
|
|
1741
|
+
* @returns 合并后的条目(已经没有任何字段时为 `undefined`),或一个错误。
|
|
1742
|
+
*/
|
|
1743
|
+
function mergeEntry(base, patch) {
|
|
1744
|
+
const entry = { ...base };
|
|
1745
|
+
if (patch.name !== void 0) {
|
|
1746
|
+
const name = patch.name === null ? "" : patch.name.trim();
|
|
1747
|
+
if (name.length === 0) delete entry.name;
|
|
1748
|
+
else entry.name = name;
|
|
1749
|
+
}
|
|
1750
|
+
if (patch.api !== void 0) {
|
|
1751
|
+
const api = patch.api === null ? "" : patch.api.trim();
|
|
1752
|
+
if (api.length === 0) delete entry.api;
|
|
1753
|
+
else if (api !== "openai-completions" && api !== "openai-responses" && api !== "anthropic-messages") return { error: `api "${api}" 无法服务;只能是 openai-completions、openai-responses 或 anthropic-messages` };
|
|
1754
|
+
else entry.api = api;
|
|
1755
|
+
}
|
|
1756
|
+
for (const field of ["contextWindow", "maxTokens"]) {
|
|
1757
|
+
const value = patch[field];
|
|
1758
|
+
if (value === void 0) continue;
|
|
1759
|
+
if (value === null) {
|
|
1760
|
+
delete entry[field];
|
|
1761
|
+
continue;
|
|
1762
|
+
}
|
|
1763
|
+
if (!Number.isInteger(value) || value < 1) return { error: `${field} 必须是不小于 1 的整数` };
|
|
1764
|
+
entry[field] = value;
|
|
1765
|
+
}
|
|
1766
|
+
if (patch.input !== void 0) {
|
|
1767
|
+
const input = patch.input === null ? [] : [...new Set(patch.input)];
|
|
1768
|
+
if (input.some((item) => item !== "text" && item !== "image")) return { error: "input 只能包含 text 或 image" };
|
|
1769
|
+
if (input.length === 0) delete entry.input;
|
|
1770
|
+
else entry.input = input;
|
|
1771
|
+
}
|
|
1772
|
+
if (patch.thinking !== void 0) {
|
|
1773
|
+
if (patch.thinking === null) delete entry.thinking;
|
|
1774
|
+
else entry.thinking = patch.thinking;
|
|
1775
|
+
}
|
|
1776
|
+
return Object.keys(entry).some((key) => key !== "id") ? { entry } : {};
|
|
1777
|
+
}
|
|
1778
|
+
/**
|
|
1779
|
+
* 组装端点。
|
|
1780
|
+
*
|
|
1781
|
+
* @param deps - 运行时、配置活引用与设置服务。
|
|
1782
|
+
* @returns 三个端点;`status` 是同步的,读一份已经算好的结果不该等待。
|
|
1783
|
+
*/
|
|
1784
|
+
function createPanelOps(deps) {
|
|
1785
|
+
const report = () => buildReport(deps.runtime.last(), deps.config(), declaredOverrides(deps.settings));
|
|
1786
|
+
return {
|
|
1787
|
+
status: report,
|
|
1788
|
+
async refresh() {
|
|
1789
|
+
const outcome = await deps.runtime.refresh("设置界面");
|
|
1790
|
+
return outcome.ok ? {
|
|
1791
|
+
ok: true,
|
|
1792
|
+
summary: "已重新发现并发布。"
|
|
1793
|
+
} : {
|
|
1794
|
+
ok: false,
|
|
1795
|
+
summary: `刷新没有成功:${outcome.error ?? "原因未知"}`
|
|
1796
|
+
};
|
|
1797
|
+
},
|
|
1798
|
+
async edit(id, patch) {
|
|
1799
|
+
const modelId = typeof id === "string" ? id.trim() : "";
|
|
1800
|
+
if (modelId.length === 0) return {
|
|
1801
|
+
ok: false,
|
|
1802
|
+
summary: "缺少模型 id。"
|
|
1803
|
+
};
|
|
1804
|
+
if (patch === void 0 || patch !== null && typeof patch !== "object") return {
|
|
1805
|
+
ok: false,
|
|
1806
|
+
summary: "缺少要写入的参数。"
|
|
1807
|
+
};
|
|
1808
|
+
const section = readSection(deps.settings);
|
|
1809
|
+
const before = (Array.isArray(section.value.models) ? section.value.models : []).map((entry) => prune(asRecord(entry)));
|
|
1810
|
+
const aliases = asRecord(section.value.modelAliases);
|
|
1811
|
+
const owned = asRecord(section.user.modelAliases);
|
|
1812
|
+
const index = before.findIndex((entry) => entry.id === modelId);
|
|
1813
|
+
const currentAlias = typeof aliases[modelId] === "string" ? aliases[modelId] : "";
|
|
1814
|
+
let models = before;
|
|
1815
|
+
const nextAliases = { ...aliases };
|
|
1816
|
+
let revoked = false;
|
|
1817
|
+
if (patch === null) {
|
|
1818
|
+
models = before.filter((_, at) => at !== index);
|
|
1819
|
+
if (currentAlias.length > 0) delete nextAliases[modelId];
|
|
1820
|
+
revoked = true;
|
|
1821
|
+
} else {
|
|
1822
|
+
const merged = mergeEntry(index === -1 ? { id: modelId } : before[index], patch);
|
|
1823
|
+
if (merged.error !== void 0) return {
|
|
1824
|
+
ok: false,
|
|
1825
|
+
summary: `"${modelId}":${merged.error}`
|
|
1826
|
+
};
|
|
1827
|
+
if (index === -1) {
|
|
1828
|
+
if (merged.entry !== void 0) models = [...before, merged.entry];
|
|
1829
|
+
} else if (merged.entry === void 0) models = before.filter((_, at) => at !== index);
|
|
1830
|
+
else models = before.map((entry, at) => at === index ? merged.entry : entry);
|
|
1831
|
+
const alias = patch.alias === void 0 ? currentAlias : (patch.alias ?? "").trim();
|
|
1832
|
+
if (alias.length === 0) delete nextAliases[modelId];
|
|
1833
|
+
else nextAliases[modelId] = alias;
|
|
1834
|
+
}
|
|
1835
|
+
const ops = [];
|
|
1836
|
+
if (JSON.stringify(models) !== JSON.stringify(before)) ops.push({
|
|
1837
|
+
op: "set",
|
|
1838
|
+
path: ["models"],
|
|
1839
|
+
value: models
|
|
1840
|
+
});
|
|
1841
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(aliases), ...Object.keys(nextAliases)])) {
|
|
1842
|
+
if (nextAliases[key] === aliases[key]) continue;
|
|
1843
|
+
if (nextAliases[key] !== void 0) {
|
|
1844
|
+
ops.push({
|
|
1845
|
+
op: "set",
|
|
1846
|
+
path: ["modelAliases", key],
|
|
1847
|
+
value: nextAliases[key]
|
|
1848
|
+
});
|
|
1849
|
+
continue;
|
|
1850
|
+
}
|
|
1851
|
+
if (Object.prototype.hasOwnProperty.call(owned, key)) ops.push({
|
|
1852
|
+
op: "unset",
|
|
1853
|
+
path: ["modelAliases", key]
|
|
1854
|
+
});
|
|
1855
|
+
}
|
|
1856
|
+
if (ops.length === 0) return {
|
|
1857
|
+
ok: true,
|
|
1858
|
+
summary: "没有要保存的改动。"
|
|
1859
|
+
};
|
|
1860
|
+
try {
|
|
1861
|
+
await deps.settings.mutate(APERTURE_NAMESPACE, ops, section.revision);
|
|
1862
|
+
const outcome = await deps.runtime.refresh("配置变更");
|
|
1863
|
+
const saved = revoked ? `已撤销 "${modelId}" 的全部覆盖,回落到发现值与清单` : `已保存 "${modelId}" 的参数`;
|
|
1864
|
+
return {
|
|
1865
|
+
ok: true,
|
|
1866
|
+
summary: outcome.ok ? `${saved},并按新配置重新发现。` : `${saved},但重新发现没有成功:${outcome.error ?? "原因未知"}`
|
|
1867
|
+
};
|
|
1868
|
+
} catch (error) {
|
|
1869
|
+
return {
|
|
1870
|
+
ok: false,
|
|
1871
|
+
summary: `保存失败:${message(error)}`
|
|
1872
|
+
};
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
};
|
|
1876
|
+
}
|
|
1877
|
+
//#endregion
|
|
1878
|
+
//#region src/relay.ts
|
|
1879
|
+
/** 邮箱本身在模块求值时就建好,因此不在任何事务里。 */
|
|
1880
|
+
const mailbox = {
|
|
1881
|
+
jobs: [],
|
|
1882
|
+
wake: void 0
|
|
1883
|
+
};
|
|
1884
|
+
/** 叫醒通道。叫醒动作本身可以发生在事务里:它只是 resolve 一个 promise。 */
|
|
1885
|
+
function wake() {
|
|
1886
|
+
const resume = mailbox.wake;
|
|
1887
|
+
mailbox.wake = void 0;
|
|
1888
|
+
resume?.();
|
|
1889
|
+
}
|
|
1890
|
+
/**
|
|
1891
|
+
* 通道:有活就起一个,起完立刻回来看还有没有。
|
|
1892
|
+
*
|
|
1893
|
+
* 作业之间互不相干,因此起而不等——等着前一个只会把「同一刻该跑的那几轮」串成一条队列,而
|
|
1894
|
+
* `ApertureRuntime` 的单飞判定本来就是用来合并它们的。
|
|
1895
|
+
*/
|
|
1896
|
+
async function drain() {
|
|
1897
|
+
for (;;) {
|
|
1898
|
+
if (mailbox.jobs.length === 0) await new Promise((resolve) => {
|
|
1899
|
+
mailbox.wake = resolve;
|
|
1900
|
+
});
|
|
1901
|
+
for (const job of mailbox.jobs.splice(0)) job();
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
drain();
|
|
1905
|
+
/**
|
|
1906
|
+
* 在 HMR 事务之外跑一件事。
|
|
1907
|
+
*
|
|
1908
|
+
* @param job - 要跑的工作;它以及它引发的全部异步续体都在事务之外执行。
|
|
1909
|
+
* @returns 该工作的结果。
|
|
1910
|
+
*/
|
|
1911
|
+
function outside(job) {
|
|
1912
|
+
return new Promise((resolve, reject) => {
|
|
1913
|
+
mailbox.jobs.push(() => {
|
|
1914
|
+
Promise.resolve().then(job).then(resolve, reject);
|
|
1915
|
+
});
|
|
1916
|
+
wake();
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1919
|
+
//#endregion
|
|
1920
|
+
//#region src/remote.ts
|
|
1921
|
+
/** 包名,同时是端点 id 的前缀。 */
|
|
1922
|
+
const PANEL_PACKAGE = "dsh-aperture";
|
|
1923
|
+
/** 线上命名空间,也是 Web Client 端注入的服务名(`remote.aperturePanel`)。 */
|
|
1924
|
+
const PANEL_NAMESPACE = "aperturePanel";
|
|
1925
|
+
/**
|
|
1926
|
+
* 一个端点的宿主侧调用描述符。
|
|
1927
|
+
*
|
|
1928
|
+
* @param method - 端点方法名,同时也是宿主服务上的方法名。
|
|
1929
|
+
* @param parameters - 参数名,按宿主方法的形参顺序;省略即无参数。
|
|
1930
|
+
* @returns 一个结果为 JSON 的直调描述符。
|
|
1931
|
+
*/
|
|
1932
|
+
function panelDescriptor(method, parameters = []) {
|
|
1933
|
+
return {
|
|
1934
|
+
id: `${PANEL_PACKAGE}#${PANEL_NAMESPACE}/${method}`,
|
|
1935
|
+
service: PANEL_NAMESPACE,
|
|
1936
|
+
namespace: PANEL_NAMESPACE,
|
|
1937
|
+
method,
|
|
1938
|
+
invocation: { kind: "direct" },
|
|
1939
|
+
parameters: parameters.map((name) => ({
|
|
1940
|
+
name,
|
|
1941
|
+
wire: name,
|
|
1942
|
+
source: "json",
|
|
1943
|
+
codec: { mode: "src-json" }
|
|
1944
|
+
})),
|
|
1945
|
+
result: { mode: "src-json" }
|
|
1946
|
+
};
|
|
1947
|
+
}
|
|
1948
|
+
/**
|
|
1949
|
+
* 本插件暴露给浏览器的全部端点。
|
|
1950
|
+
*
|
|
1951
|
+
* 端点名有一处不显眼的约束:api-gateway 在客户端为每个命名空间建一个 `RemoteNamespaceService`,
|
|
1952
|
+
* 端点会成为它的属性,因此与它自己的成员重名会被 `validateContribution` 拒绝,**整份贡献一起
|
|
1953
|
+
* 撤回**(浏览器里只剩一行 console.error,界面安静地什么都不出现)。预置名有 `ctx` / `empty` /
|
|
1954
|
+
* `invokeRemote` / `methods` / `name` / `namespace` 与 `has` / `install` / `installDirect` /
|
|
1955
|
+
* `installScoped` / `assertMethodAvailable` / `remove`——新端点起名时先对一遍这份名单。
|
|
1956
|
+
*/
|
|
1957
|
+
const PANEL_INVOCATIONS = [
|
|
1958
|
+
panelDescriptor("status"),
|
|
1959
|
+
panelDescriptor("refresh"),
|
|
1960
|
+
panelDescriptor("edit", ["id", "patch"])
|
|
1961
|
+
];
|
|
1962
|
+
/**
|
|
1963
|
+
* 登记进 Typert 注册表的贡献。
|
|
1964
|
+
*
|
|
1965
|
+
* `schemas`/`model` 是生成器的产物,这里没有生成器,因此它们如实为空:本插件不导出可复用的
|
|
1966
|
+
* schema,也没有需要反射的业务类型。端点本身仍然完整。
|
|
1967
|
+
*/
|
|
1968
|
+
const PANEL_CONTRIBUTION = {
|
|
1969
|
+
package: PANEL_PACKAGE,
|
|
1970
|
+
face: "host",
|
|
1971
|
+
schemas: [],
|
|
1972
|
+
invocations: PANEL_INVOCATIONS,
|
|
1973
|
+
model: {
|
|
1974
|
+
services: [],
|
|
1975
|
+
events: [],
|
|
1976
|
+
objects: []
|
|
1977
|
+
}
|
|
1978
|
+
};
|
|
1979
|
+
/**
|
|
1980
|
+
* `aperturePanel` 宿主服务:方法与描述符一一对应,实现全部委托给 {@link PanelOps}。
|
|
1981
|
+
*
|
|
1982
|
+
* 方法签名必须与描述符的参数顺序一致——`edit` 的两个形参名字与描述符里的两个参数同名,
|
|
1983
|
+
* 顺序也相同,网关就是按描述符顺序把 wire 参数位置传入的。
|
|
1984
|
+
*/
|
|
1985
|
+
var AperturePanelService = class extends TypertRemoteService {
|
|
1986
|
+
ops;
|
|
1987
|
+
/**
|
|
1988
|
+
* @param ctx - 挂载上下文。
|
|
1989
|
+
* @param ops - 端点实现。
|
|
1990
|
+
*/
|
|
1991
|
+
constructor(ctx, ops) {
|
|
1992
|
+
super(ctx, PANEL_NAMESPACE);
|
|
1993
|
+
this.ops = ops;
|
|
1994
|
+
}
|
|
1995
|
+
/** 最近一次刷新的报告。 */
|
|
1996
|
+
status() {
|
|
1997
|
+
return this.ops.status();
|
|
1998
|
+
}
|
|
1999
|
+
/** 立刻重新发现并发布。 */
|
|
2000
|
+
refresh() {
|
|
2001
|
+
return this.ops.refresh();
|
|
2002
|
+
}
|
|
2003
|
+
/**
|
|
2004
|
+
* 写入一个模型的参数。
|
|
2005
|
+
*
|
|
2006
|
+
* @param id - 模型 id。
|
|
2007
|
+
* @param patch - 要改的字段;`null` 表示撤销这个模型的全部覆盖。
|
|
2008
|
+
* @returns 成败与一句人话。
|
|
2009
|
+
*/
|
|
2010
|
+
edit(id, patch) {
|
|
2011
|
+
return this.ops.edit(id, patch);
|
|
2012
|
+
}
|
|
2013
|
+
};
|
|
2014
|
+
//#endregion
|
|
2015
|
+
//#region src/index.ts
|
|
48
2016
|
/** 出现在加载器诊断里的插件名。 */
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
ctx.effect(() => ctx.settings.configure({ auto: false }, ctx.fiber), 'aperture settings presentation');
|
|
118
|
-
const initial = readConfig();
|
|
119
|
-
logger.info('dsh-aperture: %s', initial.instanceRoot === undefined
|
|
120
|
-
? '还没有可用的 baseUrl,发现功能处于休眠'
|
|
121
|
-
: `正在监视 ${initial.instanceRoot} 的模型`);
|
|
122
|
-
// 插件加载本身就是启动发现的那个动作:走到这里配置已解析完毕(组合层 + 用户层,默认值全部
|
|
123
|
-
// 补齐),所以第一轮刷新看到的就是生效配置。第一轮照样走 `outside`:插件本身可能是被源码热重载
|
|
124
|
-
// 在事务里重建的,而那一代实例的发现同样要能写设置。
|
|
125
|
-
void outside(() => runtime.refresh('插件加载'));
|
|
126
|
-
// 配置页需要宿主半边的 Remote 面(报告、按行写模型参数、立刻刷新),而 Typert 注册表只有 Web
|
|
127
|
-
// 这类装配了网关的 profile 才有。其余 profile 里这一整块被跳过:发现照常运行,只是没有可点按
|
|
128
|
-
// 的界面。
|
|
129
|
-
ctx.inject(['typert'], (panelCtx) => {
|
|
130
|
-
const ops = createPanelOps({ runtime, config: readConfig, settings: ctx.settings });
|
|
131
|
-
panelCtx.effect(() => panelCtx.typert.register(PANEL_CONTRIBUTION), 'aperture panel invocations');
|
|
132
|
-
panelCtx.plugin(AperturePanelService, ops);
|
|
133
|
-
});
|
|
2017
|
+
const name = "dsh-aperture";
|
|
2018
|
+
/**
|
|
2019
|
+
* settings 是必需依赖:把发现的模型清单发布进 `llm-pi-ai` **就是**本插件的职责,而同一次
|
|
2020
|
+
* 注册又让插件自己的 `aperture` 段变得可编辑。声明它意味着框架会把插件挂在 PENDING 直到
|
|
2021
|
+
* settings 就绪,provider 被替换时卸载插件、恢复后重新加载——而不是留下一个已加载却无处
|
|
2022
|
+
* 发布的实例。
|
|
2023
|
+
*
|
|
2024
|
+
* `typert` 则刻意**不**声明:配置页只是顺手提供的便利,没有它的部署(例如 headless profile)
|
|
2025
|
+
* 也该照样获得发现能力,因此它在下面按需注入,不在就安静跳过。
|
|
2026
|
+
*/
|
|
2027
|
+
const inject = ["settings"];
|
|
2028
|
+
/**
|
|
2029
|
+
* 发布网关的模型清单:现在发布,之后有任何变化也发布。
|
|
2030
|
+
*
|
|
2031
|
+
* @param ctx - 插件上下文,其中 `settings` 已就绪。
|
|
2032
|
+
* @param config - 组合层的 `aperture` 段,已按 `Config` schema 校验并带上默认值;根级 volatile
|
|
2033
|
+
* 使它成为活引用,读值走 `config.get()`。
|
|
2034
|
+
* @throws Error 当配置自身矛盾(路由键不合文法、模型覆盖重复或无法服务),或存储的 `aperture`
|
|
2035
|
+
* 段非法时抛出——框架的失败路径正是“坏配置要响亮”的实现方式。
|
|
2036
|
+
*/
|
|
2037
|
+
function apply(ctx, config) {
|
|
2038
|
+
const logger = ctx.logger;
|
|
2039
|
+
const catalog = new ModelCatalog();
|
|
2040
|
+
const readConfig = memoizedConfig(() => configValue(config));
|
|
2041
|
+
const runtime = new ApertureRuntime({
|
|
2042
|
+
config: readConfig,
|
|
2043
|
+
settings: ctx.settings,
|
|
2044
|
+
logger,
|
|
2045
|
+
catalog
|
|
2046
|
+
});
|
|
2047
|
+
let timer;
|
|
2048
|
+
const armInterval = () => {
|
|
2049
|
+
if (timer !== void 0) {
|
|
2050
|
+
clearInterval(timer);
|
|
2051
|
+
timer = void 0;
|
|
2052
|
+
}
|
|
2053
|
+
const { refreshIntervalMinutes } = readConfig();
|
|
2054
|
+
if (refreshIntervalMinutes > 0) {
|
|
2055
|
+
timer = setInterval(() => void outside(() => runtime.refresh("定时")), refreshIntervalMinutes * 6e4);
|
|
2056
|
+
timer.unref?.();
|
|
2057
|
+
}
|
|
2058
|
+
};
|
|
2059
|
+
ctx.effect(() => {
|
|
2060
|
+
armInterval();
|
|
2061
|
+
return () => {
|
|
2062
|
+
if (timer !== void 0) {
|
|
2063
|
+
clearInterval(timer);
|
|
2064
|
+
timer = void 0;
|
|
2065
|
+
}
|
|
2066
|
+
};
|
|
2067
|
+
}, "aperture refresh interval");
|
|
2068
|
+
ctx.on("loader/volatile-update", () => {
|
|
2069
|
+
armInterval();
|
|
2070
|
+
outside(() => runtime.refresh("配置变更"));
|
|
2071
|
+
});
|
|
2072
|
+
ctx.effect(() => ctx.settings.configure({ auto: false }, ctx.fiber), "aperture settings presentation");
|
|
2073
|
+
const initial = readConfig();
|
|
2074
|
+
logger.info("dsh-aperture: %s", initial.instanceRoot === void 0 ? "还没有可用的 baseUrl,发现功能处于休眠" : `正在监视 ${initial.instanceRoot} 的模型`);
|
|
2075
|
+
outside(() => runtime.refresh("插件加载"));
|
|
2076
|
+
ctx.inject(["typert"], (panelCtx) => {
|
|
2077
|
+
const ops = createPanelOps({
|
|
2078
|
+
runtime,
|
|
2079
|
+
config: readConfig,
|
|
2080
|
+
settings: ctx.settings
|
|
2081
|
+
});
|
|
2082
|
+
panelCtx.effect(() => panelCtx.typert.register(PANEL_CONTRIBUTION), "aperture panel invocations");
|
|
2083
|
+
panelCtx.plugin(AperturePanelService, ops);
|
|
2084
|
+
});
|
|
134
2085
|
}
|
|
2086
|
+
//#endregion
|
|
2087
|
+
export { APERTURE_NAMESPACE, AperturePanelService, Config, DEFAULT_CONTEXT_WINDOW, DEFAULT_MODEL_METADATA_URL, DEFAULT_PLACEHOLDER_CREDENTIAL, ModelCatalog, PANEL_CONTRIBUTION, PANEL_INVOCATIONS, PANEL_NAMESPACE, PANEL_PACKAGE, PI_AI_NAMESPACE, apply, applySync, buildModelsEndpoint, buildProfilePlan, buildRegistry, buildReport, buildRouteBaseUrl, classifyProtocol, configValue, createPanelOps, fetchModelsListing, inject, isDeepSeekFamily, name, normalizeBaseUrl, planSync, resolveConfig };
|