dsh-nvidia-models-panel 1.3.21 → 1.3.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (7) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +104 -104
  3. package/package.json +51 -51
  4. package/src/client.js +1261 -1222
  5. package/src/group.js +652 -649
  6. package/src/index.js +1253 -1253
  7. package/src/usage.js +285 -285
package/src/index.js CHANGED
@@ -1,1253 +1,1253 @@
1
- /** Host half of the Nvidia Models Panel bundle. */
2
-
3
- import {
4
- createHealthRegistry,
5
- createGroupAdapter,
6
- createGroupState,
7
- makeSchema,
8
- foldGroupEvent,
9
- AUTO_MEMBER_ID,
10
- AUTO_MEMBER_NAME,
11
- AUTO_MEMBER_DESC,
12
- isAutoMemberId,
13
- } from './group.js';
14
-
15
- import { createUsageRegistry } from './usage.js';
16
-
17
- export const inject = ['commands', 'configEditor'];
18
-
19
- /** NVIDIA NIM public endpoints (model list is anonymous-readable; completions need a key). */
20
- const NIM_MODELS_URL = 'https://integrate.api.nvidia.com/v1/models';
21
- const NIM_COMPLETIONS_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';
22
-
23
- /**
24
- * 旧版「一键配置」给所有模型硬编码的上下文窗口(131072 = 128K)。
25
- * 绝大多数 NVIDIA NIM 模型的 /v1/models 不返回 context_window,这个 128K 的
26
- * 保守值会让 pi-ai 在本会话这种长上下文下误判为「silent context overflow」,
27
- * 把一次正常应答报成致命的 CONTEXT_WINDOW_EXCEEDED。见 inferContextWindow。
28
- */
29
- const LEGACY_CONTEXT_WINDOW = 131072;
30
-
31
- /**
32
- * 未上报 context_window 时的宽松默认窗口。宁可声明得宽松一点:
33
- * 声明过小 → pi-ai 误判溢出(假失败);声明偏大 → 真超长时上游返回真实报错(诚实失败)。
34
- */
35
- const DEFAULT_CONTEXT_WINDOW = 1048576;
36
-
37
- /**
38
- * 解析某模型应使用的上下文窗口:优先用上游 /v1/models 上报的 context_window,
39
- * 缺省时按模型族给合理值,最后回落到宽松默认,绝不沿用旧的 128K。
40
- * 导出以便单测。
41
- * @param {string} id 模型 id
42
- * @param {number} [upstreamCtx] 上游上报的 context_window(若有)
43
- */
44
- export function inferContextWindow(id, upstreamCtx) {
45
- if (Number.isFinite(upstreamCtx) && upstreamCtx > 0) return Math.round(upstreamCtx);
46
- const s = String(id || '');
47
- // 明确的长上下文模型族。
48
- if (/deepseek-v4|nemotron-3-ultra|nemotron-3\.5-(super|ultra)|llama-3\.1|mistral-large/i.test(s)) return 1048576;
49
- if (/nemotron|llama|mistral|qwen|glm|kimi|step|minimax|gpt-oss|muse/i.test(s)) return 262144;
50
- return DEFAULT_CONTEXT_WINDOW;
51
- }
52
-
53
- /** Chinese blurbs per publisher prefix, used to build per-model descriptions. */
54
- const PUBLISHER_BLURBS = {
55
- nvidia: 'NVIDIA 官方',
56
- 'nv-mistralai': 'NVIDIA 与 Mistral 联合优化',
57
- meta: 'Meta Llama 系列',
58
- 'deepseek-ai': 'DeepSeek 系列',
59
- 'z-ai': '智谱 GLM 系列',
60
- moonshotai: '月之暗面 Kimi 系列',
61
- qwen: '阿里通义千问系列',
62
- google: 'Google 开源模型',
63
- microsoft: '微软 Phi 系列',
64
- mistralai: 'Mistral AI 系列',
65
- openai: 'OpenAI 开源模型',
66
- '01-ai': '零一万物 Yi 系列',
67
- ai21labs: 'AI21 Jamba 系列',
68
- ibm: 'IBM Granite 系列',
69
- bigcode: 'BigCode 代码模型',
70
- databricks: 'Databricks 模型',
71
- snowflake: 'Snowflake Arctic 系列',
72
- writer: 'Writer Palmyra 系列',
73
- poolside: 'Poolside 代码模型',
74
- minimaxai: 'MiniMax 系列',
75
- 'stepfun-ai': '阶跃星辰系列',
76
- zyphra: 'Zyphra 系列',
77
- adept: 'Adept 模型',
78
- aisingapore: 'AI Singapore SEA-LION 系列',
79
- };
80
-
81
- /** Built-in fallback shown when the upstream API is unreachable. */
82
- const BUILTIN_MODELS = [
83
- { id: 'nvidia/llama-3.1-nemotron-70b-instruct', name: 'Llama 3.1 Nemotron 70B', description: 'NVIDIA 旗舰推理模型,擅长复杂推理、编码与数学' },
84
- { id: 'nvidia/nemotron-3-ultra-550b-a55b', name: 'Nemotron 3 Ultra 550B', description: 'NVIDIA 官方超大参数模型,推理与编码能力极强' },
85
- { id: 'nvidia/nemotron-3-super-120b-a12b', name: 'Nemotron 3 Super 120B', description: 'NVIDIA 官方高性能均衡型,适合企业级任务' },
86
- { id: 'nvidia/nemotron-3.5-lightning-30b-a3b', name: 'Nemotron 3.5 Lightning 30B', description: 'NVIDIA 官方轻量高速 MoE,响应快成本低' },
87
- { id: 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning', name: 'Nemotron 3 Nano Omni 30B', description: 'NVIDIA 官方全模态模型,支持文本与图像' },
88
- { id: 'deepseek-ai/deepseek-v4.1-flash', name: 'DeepSeek V4.1 Flash', description: 'DeepSeek 系列,长上下文,支持文本与图像' },
89
- { id: 'moonshotai/kimi-k3', name: 'Kimi K3', description: '月之暗面 Kimi 系列,百万级上下文窗口' },
90
- { id: 'z-ai/glm-5.3', name: 'GLM-5.3', description: '智谱 GLM 系列,强推理与长上下文' },
91
- { id: 'meta/llama-3.2-90b-vision-instruct', name: 'Llama 3.2 90B Vision', description: 'Meta Llama 系列,多语言视觉理解' },
92
- { id: 'mistralai/mistral-7b-instruct-v0.3', name: 'Mistral 7B Instruct v0.3', description: 'Mistral AI 系列,轻量高效通用模型' },
93
- ];
94
-
95
- /** Build a short Chinese blurb for one model id. */
96
- function describeModel(id) {
97
- const slash = id.indexOf('/');
98
- const publisher = slash > 0 ? id.slice(0, slash) : '';
99
- const bare = slash > 0 ? id.slice(slash + 1) : id;
100
- const who = PUBLISHER_BLURBS[publisher] || (publisher ? publisher + ' 发布' : 'NVIDIA NIM 托管');
101
- let kind = '通用大语言模型';
102
- const lower = bare.toLowerCase();
103
- if (/vision|vl|omni|diffusion|image/.test(lower)) kind = '支持视觉/多模态输入';
104
- else if (/coder|code/.test(lower)) kind = '专攻代码生成与补全';
105
- else if (/embed|rerank|reward/.test(lower)) kind = '检索/评测类模型';
106
- else if (/reason|thinking|r1/.test(lower)) kind = '强化推理能力';
107
- return who + ',' + kind + '。';
108
- }
109
-
110
- /** True for model families the chat-completions probe cannot meaningfully call. */
111
- function isNonChatModel(id) {
112
- // embed/rerank/reward/diffusion——不是对话模型;
113
- // guard/safety/calibration/parse/translate——是专用模型,放进模型组只会每一轮都失败。
114
- return /embed|rerank|reward|diffusion|guard|safety|calibration|nemotron-parse|riva-translate/i.test(String(id || ''));
115
- }
116
-
117
- /** Context-bound key resolver installed during apply(); prefers env, then the credential store. */
118
- let resolveKeyFromContext = async () => '';
119
-
120
- /** Run one operation against the credentials service; resolves null when unavailable. */
121
- function withCredentials(ctx, operation) {
122
- return new Promise((done) => {
123
- try {
124
- ctx.inject(['credentials'], (scoped) => {
125
- try {
126
- done(Promise.resolve(operation(scoped.credentials)).catch(() => null));
127
- } catch {
128
- done(null);
129
- }
130
- });
131
- } catch {
132
- done(null);
133
- }
134
- });
135
- }
136
-
137
- /** NVIDIA Key 是否已配置(凭据服务不可用时按「已配置」处理,避免误拦截)。 */
138
- async function hasNvidiaKey(ctx) {
139
- const info = await withCredentials(ctx, (credentials) => credentials.describe(NVIDIA_KEY_REF));
140
- if (!info || info.unavailable) return true; // 无法判定时不拦截,交给上游返回真实错误
141
- return Boolean(info.configured);
142
- }
143
-
144
- /** Run one operation against the configEditor service; resolves null when unavailable. */
145
- function withConfigEditor(ctx, operation) {
146
- return new Promise((done) => {
147
- try {
148
- ctx.inject(['configEditor'], (scoped) => {
149
- try {
150
- done(Promise.resolve(operation(scoped.configEditor)).catch(() => null));
151
- } catch {
152
- done(null);
153
- }
154
- });
155
- } catch {
156
- done(null);
157
- }
158
- });
159
- }
160
-
161
- const LLM_PLUGIN_NAME = '@deepseek-ai/dsh-llm-pi-ai';
162
-
163
- /**
164
- * configEditor.entries() yields Loader Entry objects, so the plugin identity
165
- * lives at entry.options.id / entry.options.name (see dsh-config-editor
166
- * lib/index.js entries() and edit()). Tolerant of the other plausible shapes.
167
- */
168
- function entryIdentifiers(entry) {
169
- const values = [];
170
- const push = (value) => { if (typeof value === 'string' && value) values.push(value); };
171
- try {
172
- push(entry.id);
173
- push(entry.name);
174
- const options = entry.options;
175
- if (options && typeof options === 'object') {
176
- push(options.id);
177
- push(options.name);
178
- push(options.group);
179
- }
180
- } catch {
181
- // An unreadable entry simply cannot be matched by identifier.
182
- }
183
- return values;
184
- }
185
-
186
- /** Does this entry address the llm-pi-ai plugin (any id/patchId/name form)? */
187
- function isLlmPiAiEntry(entry) {
188
- return entryIdentifiers(entry).some((value) =>
189
- value === LLM_PLUGIN_NAME || value === 'llm-pi-ai' || value.endsWith(':llm-pi-ai'));
190
- }
191
-
192
- /** Compact, secret-free dump of entries, used only to diagnose a failed lookup. */
193
- function describeEntries(entries) {
194
- return entries.slice(0, 20).map((entry) => {
195
- const out = {};
196
- try {
197
- const options = entry.options || {};
198
- if (typeof options.id === 'string') out.id = options.id;
199
- if (typeof options.name === 'string') out.name = options.name;
200
- if (options.config !== undefined) out.hasConfig = true;
201
- if (entry.fiber) out.active = entry.fiber.state === 2;
202
- } catch {
203
- out.unreadable = true;
204
- }
205
- return out;
206
- });
207
- }
208
-
209
- /**
210
- * Detect models live and write the AVAILABLE ones into the llm-pi-ai nvidia
211
- * provider, so the chat model picker offers exactly what can be called.
212
- * Shared by the panel button (POST action=configure) and the slash command.
213
- * `probeResults` (id → 'ok' | 'unavailable') from the panel's per-model probe
214
- * filters the list; without it, non-chat families are the only ones dropped.
215
- */
216
- async function configureNvidiaModels(ctx, probeResults) {
217
- const configEditor = await withConfigEditor(ctx, (editor) => editor);
218
- if (!configEditor) {
219
- return { ok: false, error: 'configEditor 服务不可用,无法写入配置' };
220
- }
221
- const detection = await detectNvidiaModels();
222
- const allModels = detection.models;
223
- if (detection.source === 'live') lastDetectedModels = normalizeGroupMembers(allModels);
224
- const source = detection.source === 'live' ? 'NVIDIA API 实时检测' : '内置目录';
225
- let available;
226
- let droppedUnavailable = 0;
227
- let droppedNonChat = 0;
228
- if (probeResults && typeof probeResults === 'object' && Object.keys(probeResults).length > 0) {
229
- available = allModels.filter((m) => probeResults[m.id] === 'ok');
230
- droppedUnavailable = allModels.length - available.length;
231
- } else {
232
- available = allModels.filter((m) => !isNonChatModel(m.id));
233
- droppedNonChat = allModels.length - available.length;
234
- }
235
- if (available.length === 0) {
236
- return { ok: false, error: '没有试调用通过的可用模型,未写入。请先确认 API Key 有效后重新试调用。' };
237
- }
238
- // Locate the llm-pi-ai row by identity across every plausible field and
239
- // fall back to the configuration() projection before giving up.
240
- let entries;
241
- try {
242
- entries = configEditor.entries();
243
- } catch (error) {
244
- return { ok: false, error: '读取配置条目失败:' + String((error && error.message) || error) };
245
- }
246
- if (!Array.isArray(entries)) {
247
- return { ok: false, error: '配置条目返回异常:' + JSON.stringify(entries).slice(0, 200) };
248
- }
249
- let configs = [];
250
- try {
251
- configs = configEditor.configuration();
252
- } catch {
253
- configs = [];
254
- }
255
- let llmEntry = entries.find(isLlmPiAiEntry);
256
- let llmHit = null;
257
- if (llmEntry) {
258
- llmHit = (Array.isArray(configs) ? configs : []).find((c) => c && c.entry === llmEntry) || null;
259
- } else {
260
- llmHit = (Array.isArray(configs) ? configs : []).find((c) => c && isLlmPiAiEntry(c.entry)) || null;
261
- if (llmHit) llmEntry = llmHit.entry;
262
- }
263
- if (!llmEntry) {
264
- return {
265
- ok: false,
266
- error: '未找到 llm-pi-ai 配置项(entries 共 ' + entries.length + ' 条)。诊断信息:' + JSON.stringify(describeEntries(entries)).slice(0, 900),
267
- };
268
- }
269
- let existingCount = 0;
270
- if (llmHit && llmHit.override && llmHit.override.providers && llmHit.override.providers.nvidia) {
271
- const models = llmHit.override.providers.nvidia.models;
272
- existingCount = Array.isArray(models) ? models.length : 0;
273
- }
274
- const nextModels = available.map((m) => ({
275
- id: m.id,
276
- name: m.name + ' - ' + m.description,
277
- contextWindow: inferContextWindow(m.id, m.upstreamCtx),
278
- maxTokens: 8192,
279
- input: /vision|vl|omni|diffusion|image/i.test(m.id) ? ['text', 'image'] : ['text'],
280
- }));
281
- try {
282
- await configEditor.edit(llmEntry, (current, inherited) => {
283
- // Start from inherited ∪ override so unrelated providers and fields survive.
284
- const base = { ...(inherited || {}), ...(current || {}) };
285
- const baseProviders = base.providers || {};
286
- const baseNvidia = baseProviders.nvidia || {};
287
- return {
288
- ...base,
289
- providers: {
290
- ...baseProviders,
291
- nvidia: {
292
- ...baseNvidia,
293
- apiKeyEnv: baseNvidia.apiKeyEnv || 'NVIDIA_API_KEY',
294
- models: nextModels,
295
- },
296
- },
297
- };
298
- });
299
- } catch (error) {
300
- return { ok: false, error: '写入配置失败:' + String((error && error.message) || error) };
301
- }
302
- const droppedNote = droppedUnavailable > 0
303
- ? ',剔除 ' + droppedUnavailable + ' 个试调用未通过的模型'
304
- : (droppedNonChat > 0 ? ',跳过 ' + droppedNonChat + ' 个非对话模型' : '');
305
- return {
306
- ok: true,
307
- message: '已' + (existingCount ? '更新(原 ' + existingCount + ' 个模型)' : '写入') + ' nvidia 供应商:' + nextModels.length + ' 个【试调用可用】模型' + droppedNote + '(来源:' + source + ')。模型名称后附简介,现在对话框的模型选择器即可选用;凭据与正式路由共用,下一次请求即生效。',
308
- };
309
- }
310
-
311
- /** Query NVIDIA NIM for the live model list; falls back to the built-in catalog. */
312
- async function detectNvidiaModels() {
313
- const controller = new AbortController();
314
- const timer = setTimeout(() => controller.abort(), 15000);
315
- try {
316
- const apiKey = await resolveKeyFromContext();
317
- const headers = { accept: 'application/json' };
318
- if (apiKey) headers.authorization = 'Bearer ' + apiKey;
319
- const upstream = await fetch(NIM_MODELS_URL, { headers, signal: controller.signal });
320
- if (!upstream.ok) {
321
- return { ok: false, reason: 'NVIDIA API 返回 HTTP ' + upstream.status, source: 'builtin', models: BUILTIN_MODELS };
322
- }
323
- const data = await upstream.json();
324
- const raw = Array.isArray(data && data.data) ? data.data : [];
325
- if (raw.length === 0) {
326
- return { ok: false, reason: 'NVIDIA API 返回了空列表', source: 'builtin', models: BUILTIN_MODELS };
327
- }
328
- const models = raw.map((m) => ({
329
- id: String(m.id || ''),
330
- name: String(m.id || '').split('/').pop() || String(m.id || ''),
331
- description: describeModel(String(m.id || '')),
332
- upstreamCtx: (Number.isFinite(m.context_window) && m.context_window > 0)
333
- ? m.context_window
334
- : (Number.isFinite(m.context_length) && m.context_length > 0 ? m.context_length : undefined),
335
- })).filter((m) => m.id);
336
- models.sort((a, b) => a.id.localeCompare(b.id));
337
- return { ok: true, source: 'live', count: models.length, models, keyFound: Boolean(apiKey) };
338
- } catch (error) {
339
- const reason = error && error.name === 'AbortError' ? '连接超时(15 秒)' : String((error && error.message) || error);
340
- return { ok: false, reason: '无法访问 NVIDIA API:' + reason, source: 'builtin', models: BUILTIN_MODELS };
341
- } finally {
342
- clearTimeout(timer);
343
- }
344
- }
345
-
346
- /**
347
- * Probe one model with a streaming completion call. Availability is decided by
348
- * the FIRST response byte, not the full completion — thinking models can take
349
- * a long time to finish, but their first chunk arrives in seconds. The stream
350
- * is aborted as soon as the first byte lands.
351
- */
352
- async function probeStreaming(id, apiKey, maxTokens, timeoutMs) {
353
- const controller = new AbortController();
354
- const timer = setTimeout(() => controller.abort(), timeoutMs);
355
- try {
356
- const headers = { 'content-type': 'application/json', accept: 'text/event-stream' };
357
- if (apiKey) headers.authorization = 'Bearer ' + apiKey;
358
- const response = await fetch(NIM_COMPLETIONS_URL, {
359
- method: 'POST',
360
- headers,
361
- signal: controller.signal,
362
- body: JSON.stringify({
363
- model: id,
364
- messages: [{ role: 'user', content: 'ping' }],
365
- max_tokens: maxTokens,
366
- stream: true,
367
- }),
368
- });
369
- if (!response.ok) {
370
- return { kind: 'http-error', response };
371
- }
372
- if (!response.body || typeof response.body.getReader !== 'function') {
373
- // No streaming body support: a 200 still means the endpoint accepted the model.
374
- return { kind: 'ok-no-stream' };
375
- }
376
- const reader = response.body.getReader();
377
- try {
378
- const first = await reader.read();
379
- if (first && first.done) {
380
- return { kind: 'ok-no-stream' };
381
- }
382
- return { kind: 'ok-stream' };
383
- } finally {
384
- try { reader.releaseLock(); } catch { /* the abort below already tore the stream down */ }
385
- controller.abort();
386
- }
387
- } catch (error) {
388
- return { kind: 'network-error', error };
389
- } finally {
390
- clearTimeout(timer);
391
- }
392
- }
393
-
394
- /** Extract NVIDIA's error message from a failed response, best-effort. */
395
- async function extractErrorHint(response) {
396
- try {
397
- const errBody = await response.json();
398
- const msg = errBody && errBody.detail ? String(errBody.detail) : (errBody && errBody.message ? String(errBody.message) : '');
399
- return msg ? ':' + msg.slice(0, 160) : '';
400
- } catch {
401
- return '';
402
- }
403
- }
404
-
405
- /**
406
- * Probe one model with a real completion call. Thinking/reasoning models
407
- * reject tiny output budgets, so the first attempt uses max_tokens=1024 and
408
- * a 400/422 response retries once with a larger budget before declaring fail.
409
- * Availability is confirmed by the first streamed byte, so slow thinkers are
410
- * not misjudged as timeouts.
411
- */
412
- async function testNvidiaModel(id) {
413
- if (isNonChatModel(id)) {
414
- return { id, status: 'skip', detail: '非对话模型(embed/rerank 等),未试调用' };
415
- }
416
- try {
417
- const apiKey = await resolveKeyFromContext();
418
- let probe = await probeStreaming(id, apiKey, 1024, 30000);
419
- if (probe.kind === 'http-error' && (probe.response.status === 400 || probe.response.status === 422)) {
420
- const firstHint = await extractErrorHint(probe.response);
421
- probe = await probeStreaming(id, apiKey, 8192, 45000);
422
- if (probe.kind === 'ok-stream' || probe.kind === 'ok-no-stream') {
423
- return { id, status: 'ok', detail: '试调用成功(需较大输出预算)' };
424
- }
425
- if (probe.kind === 'http-error') {
426
- const hint = (await extractErrorHint(probe.response)) || firstHint;
427
- const map = { 401: '鉴权失败(401)——需要有效的 NVIDIA API Key', 403: '无权限(403)——当前密钥无权调用该模型', 404: '模型不可用(404)——端点不接受该模型', 429: '限流(429)——请求过于频繁或配额耗尽' };
428
- const known = map[probe.response.status];
429
- return { id, status: 'fail', detail: (known || '调用失败(HTTP ' + probe.response.status + ')') + hint };
430
- }
431
- const abortRetry = probe.error && probe.error.name === 'AbortError';
432
- return { id, status: 'fail', detail: abortRetry ? '首包超时(45 秒无响应)' : '网络错误:' + String((probe.error && probe.error.message) || probe.error) };
433
- }
434
- if (probe.kind === 'ok-stream') {
435
- return { id, status: 'ok', detail: '试调用成功(流式首包确认)' };
436
- }
437
- if (probe.kind === 'ok-no-stream') {
438
- return { id, status: 'ok', detail: '端点返回 200(无流式数据)' };
439
- }
440
- if (probe.kind === 'http-error') {
441
- const hint = await extractErrorHint(probe.response);
442
- const map = {
443
- 401: '鉴权失败(401)——需要有效的 NVIDIA API Key',
444
- 403: '无权限(403)——当前密钥无权调用该模型',
445
- 404: '模型不可用(404)——端点不接受该模型',
446
- 429: '限流(429)——请求过于频繁或配额耗尽',
447
- };
448
- const known = map[probe.response.status];
449
- return { id, status: 'fail', detail: (known || '调用失败(HTTP ' + probe.response.status + ')') + hint };
450
- }
451
- const abortFirst = probe.error && probe.error.name === 'AbortError';
452
- return { id, status: 'fail', detail: abortFirst ? '首包超时(30 秒无响应)' : '网络错误:' + String((probe.error && probe.error.message) || probe.error) };
453
- } catch (error) {
454
- return { id, status: 'fail', detail: '网络错误:' + String((error && error.message) || error) };
455
- }
456
- }
457
-
458
- /** Read and parse a bounded JSON body; empty or malformed bodies yield {}. */
459
- async function readJsonBody(request) {
460
- const reader = request && request.body && request.body.getReader ? request.body.getReader() : undefined;
461
- if (!reader) return {};
462
- const chunks = [];
463
- let size = 0;
464
- try {
465
- for (;;) {
466
- const { done, value } = await reader.read();
467
- if (done) break;
468
- size += value.byteLength;
469
- if (size > 65536) { await reader.cancel(); return {}; }
470
- chunks.push(value);
471
- }
472
- } catch {
473
- return {};
474
- }
475
- const bytes = new Uint8Array(size);
476
- let offset = 0;
477
- for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
478
- try {
479
- const text = new TextDecoder().decode(bytes);
480
- const parsed = JSON.parse(text);
481
- return parsed && typeof parsed === 'object' ? parsed : {};
482
- } catch {
483
- return {};
484
- }
485
- }
486
-
487
- /** The credential reference this panel manages (matches the llm-pi-ai nvidia route). */
488
- const NVIDIA_KEY_REF = 'NVIDIA_API_KEY';
489
-
490
- /* ───────────────────────────── NVIDIA 模型组(自愈式故障转移) ───────────────────────────── */
491
-
492
- /**
493
- * 组内健康登记表(熔断器)。进程级单例:所有会话共享同一份模型健康视图,
494
- * 这样一个会话把某个模型判定为不可用后,其它会话也会短路跳过它。
495
- */
496
- const groupHealth = createHealthRegistry({ failThreshold: 2, baseCooldownMs: 20000, maxCooldownMs: 300000 });
497
-
498
- /**
499
- * 调用日志持久化文件(放在 profile 目录而非插件目录):市场重装会替换 node_modules
500
- * 里的插件实体目录、放到那里会跟着丢;profile 目录稳定。无 DSH_PROFILE_DIR 时返回空,
501
- * 静默降级为纯内存(便于测试与非 DSH 环境)。
502
- */
503
- function defaultUsageFilePath() {
504
- const dir = process.env.DSH_PROFILE_DIR;
505
- if (!dir) return '';
506
- return dir.replace(/\/+$/, '') + '/nvidia-usage.json';
507
- }
508
-
509
- /** 文件型 storage(ESM 用动态 import):全量快照覆盖写,读写失败一律静默。 */
510
- function makeFileStorage() {
511
- // Never touch the real profile usage file while running under `node --test`
512
- // (smoke tests exercise apply()/stream and would otherwise pollute it).
513
- if (process.env.NODE_TEST_CONTEXT) return null;
514
- const file = defaultUsageFilePath();
515
- if (!file) return null;
516
- return {
517
- async load() {
518
- try {
519
- const fs = await import('node:fs/promises');
520
- return JSON.parse(await fs.readFile(file, 'utf8'));
521
- } catch { return null; }
522
- },
523
- async save(data) {
524
- try {
525
- const fs = await import('node:fs/promises');
526
- const tmp = file + '.tmp';
527
- await fs.writeFile(tmp, JSON.stringify(data), 'utf8');
528
- await fs.rename(tmp, file); // atomic replace
529
- } catch { /* best-effort */ }
530
- },
531
- };
532
- }
533
-
534
- /** 当日调用用量登记表(进程级单例):模型组每次尝试都记一条,供面板「调用日志」展示。 */
535
- const groupUsage = createUsageRegistry({ retentionDays: 7, maxLogPerDay: 200, storage: makeFileStorage() });
536
-
537
- /** 组运行参数(内存态,可被 setGroupConfig 覆盖)。 */
538
- const groupConfig = {
539
- firstByteTimeoutMs: 15000,
540
- firstTextTimeoutMs: 30000,
541
- preferredModel: '',
542
- autoRefreshMs: 300000,
543
- };
544
-
545
- /**
546
- * 输入框 dock 徽标的共享状态(进程级内存,重启归零)。
547
- * 记录最近一次真正产出正文的成员、最近一次切换来源/时间、累计切换次数,
548
- * 由 buildGroupAdapter 的 onAttempt / onFailover 更新,route `dockStatus` 暴露给 client。
549
- */
550
- const dockGroupState = {
551
- sessionId: null,
552
- memberId: '',
553
- memberName: '',
554
- switchFrom: '',
555
- switchAt: 0,
556
- switchCount: 0,
557
- updatedAt: 0,
558
- };
559
-
560
- /** 成员的短友好名(优先配置里的 name,否则取 id 最后一段)。 */
561
- function friendlyMemberName(member) {
562
- if (!member) return '';
563
- if (member.name) return String(member.name);
564
- const id = String(member.id || '');
565
- const tail = id.split('/').pop();
566
- return tail || id;
567
- }
568
-
569
- /**
570
- * 自动发现:最近一次实时检测到的模型(面板点「检测」、configure 成功或后台自动刷新时更新)。
571
- * 组成员解析顺序:已配置模型 → 最近检测到的对话模型 → 内置种子。
572
- */
573
- let lastDetectedModels = [];
574
-
575
- /**
576
- * 内置“种子”组成员:都是 NVIDIA 官方已验证可流式返回的对话模型,
577
- * 让模型组在用户尚未「一键配置」时也能立即工作(自愈开箱即用)。
578
- */
579
- const AUTO_SEED_MODELS = [
580
- { id: 'nvidia/nemotron-3.5-lightning-30b-a3b', name: 'Nemotron 3.5 Lightning 30B', description: 'NVIDIA 官方轻量高速 MoE', inputModalities: ['text'] },
581
- { id: 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning', name: 'Nemotron 3 Nano Omni 30B', description: 'NVIDIA 官方全模态模型', inputModalities: ['text', 'image'] },
582
- { id: 'nvidia/nemotron-3-ultra-550b-a55b', name: 'Nemotron 3 Ultra 550B', description: 'NVIDIA 官方超大参数模型', inputModalities: ['text'] },
583
- { id: 'deepseek-ai/deepseek-v4.1-flash', name: 'DeepSeek V4.1 Flash', description: 'DeepSeek 高速长上下文', inputModalities: ['text', 'image'] },
584
- ];
585
-
586
- /** 把一组模型条目(id/name/description)规整成组成员形态。 */
587
- function normalizeGroupMembers(list) {
588
- return (Array.isArray(list) ? list : []).map((m) => ({
589
- id: String(m.id || ''),
590
- name: String(m.name || m.id || ''),
591
- description: String(m.description || ''),
592
- inputModalities: Array.isArray(m.input) ? m.input : (Array.isArray(m.inputModalities) ? m.inputModalities : (/vision|vl|omni|diffusion|image/i.test(String(m.id || '')) ? ['text', 'image'] : ['text'])),
593
- // 组成员也不再用「未知即 128K」:优先上游值/推断值,再没有就留 null(不虚假声明)。
594
- contextWindow: Number.isFinite(m.contextWindow) ? m.contextWindow : (Number.isFinite(m.upstreamCtx) ? m.upstreamCtx : inferContextWindow(m.id)),
595
- maxTokens: Number.isFinite(m.maxTokens) ? m.maxTokens : null,
596
- })).filter((m) => m.id && !isNonChatModel(m.id));
597
- }
598
-
599
- /** 解析当前组合成员:已配置 > 最近检测 > 内置种子(自动发现,开箱即用)。 */
600
- async function resolveGroupMembers(ctx) {
601
- const configured = await readNvidiaConfigModels(ctx);
602
- if (configured && configured.length) return configured;
603
- const detected = normalizeGroupMembers(lastDetectedModels);
604
- if (detected.length) return detected;
605
- return normalizeGroupMembers(AUTO_SEED_MODELS);
606
- }
607
-
608
- /** 从 llm-pi-ai 的 nvidia 供应商配置里读出当前组成员(与 configure 写入的模型列表同源)。 */
609
- async function readNvidiaConfigModels(ctx) {
610
- const configEditor = await withConfigEditor(ctx, (editor) => editor);
611
- if (!configEditor) return null;
612
- let entries;
613
- try { entries = configEditor.entries(); } catch { return null; }
614
- if (!Array.isArray(entries)) return null;
615
- let configs = [];
616
- try { configs = configEditor.configuration(); } catch { configs = []; }
617
- let llmHit = (Array.isArray(configs) ? configs : []).find((c) => c && isLlmPiAiEntry(c.entry)) || null;
618
- if (!llmHit) {
619
- const llmEntry = entries.find(isLlmPiAiEntry);
620
- if (llmEntry) llmHit = { entry: llmEntry, override: llmEntry.options && llmEntry.options.config };
621
- }
622
- const nvidia = llmHit && llmHit.override && llmHit.override.providers && llmHit.override.providers.nvidia;
623
- const models = nvidia && Array.isArray(nvidia.models) ? nvidia.models : [];
624
- return models.map((m) => {
625
- const declared = Number.isFinite(m.contextWindow) ? m.contextWindow : (Number.isFinite(m.context) ? m.context : null);
626
- // 旧版「一键配置」把所有模型写成 131072;这类遗留值按模型族自愈为更合理的窗口,
627
- // 避免 pi-ai 因声明过小而把正常应答误判成上下文溢出。
628
- const contextWindow = (declared && declared !== LEGACY_CONTEXT_WINDOW)
629
- ? declared
630
- : inferContextWindow(m.id, declared === LEGACY_CONTEXT_WINDOW ? undefined : declared);
631
- return {
632
- id: String(m.id || ''),
633
- name: String(m.name || m.id || ''),
634
- description: String(m.description || ''),
635
- inputModalities: Array.isArray(m.input) ? m.input : (m.inputModalities || ['text']),
636
- contextWindow,
637
- maxTokens: Number.isFinite(m.maxTokens) ? m.maxTokens : null,
638
- };
639
- }).filter((m) => m.id && !isNonChatModel(m.id));
640
- }
641
-
642
- /** 取得一个会话对象(best-effort,用于把故障转移事件写进会话投影)。 */
643
- function sessionFor(ctx, sessionId) {
644
- try {
645
- const sessions = ctx.get ? ctx.get('sessions') : undefined;
646
- if (!sessions || typeof sessions.get !== 'function' || !sessionId) return null;
647
- return sessions.get(sessionId) || null;
648
- } catch {
649
- return null;
650
- }
651
- }
652
-
653
- // —— 会话事件写入:只使用 harness 官方的 plugin record API ——
654
- // 背景:session.append() 无法写 ignorable 标记。用它写 harness 词表外的
655
- // 类型(如 nvidia-group/*)会让会话日志下次加载时被持久化层拒绝:
656
- // "contains event type ... unknown to this harness and not marked ignorable"
657
- // appendPluginRecord() 写的 plugin: 记录会自动带 ignorable:true,未知
658
- // 类型可被安全跳过,不会再把整段会话历史卡死。
659
- const GROUP_RECORD_PROBE = 'plugin:dsh-nvidia-models-panel/probe';
660
- const GROUP_RECORD_FAILOVER = 'plugin:dsh-nvidia-models-panel/failover';
661
- let dshSessionApi; // undefined=未加载;null=不可用;对象={ appendPluginRecord }
662
- function getSessionApi() {
663
- if (dshSessionApi !== undefined) return Promise.resolve(dshSessionApi);
664
- return import('@deepseek-ai/dsh-session').then(
665
- (mod) => (dshSessionApi = typeof mod?.appendPluginRecord === 'function' ? mod : null),
666
- () => (dshSessionApi = null),
667
- );
668
- }
669
-
670
- /** 把一条组事件作为 plugin record 追加进会话(best-effort;失败不影响主流程)。 */
671
- function appendGroupEvent(ctx, sessionId, type, data) {
672
- try {
673
- const session = sessionFor(ctx, sessionId);
674
- if (!session) return;
675
- // 旧 harness 没有 appendPluginRecord 时宁可不写,绝不退回
676
- // session.append() 写不可忽略的未知类型(那会再次损坏会话)。
677
- void getSessionApi().then((api) => {
678
- if (!api || typeof api.appendPluginRecord !== 'function') return;
679
- try { api.appendPluginRecord(session, type, data); } catch { /* best-effort */ }
680
- });
681
- } catch {
682
- // 会话不可用时,看板仍能靠 groupStatus 的实时快照工作。
683
- }
684
- }
685
-
686
- /** 没有 Key / 凭据失效时给出的统一可读提示。 */
687
- const NO_KEY_MESSAGE = 'NVIDIA API Key 未配置或已失效,请在 NVIDIA 模型面板顶部保存 Key 后重试。';
688
-
689
- /**
690
- * 包装 llm.stream:把上游的「缺凭据 / 401 / 403」错误翻译成带 NO_API_KEY 码的
691
- * 友好失败。这类错误对所有成员都一样,group.js 会识别为致命错误直接停止故障转移。
692
- */
693
- function translateKeyError(failure) {
694
- if (!failure || typeof failure !== 'object') return failure;
695
- const code = String(failure.code || '');
696
- const status = failure.status;
697
- const msg = String(failure.message || '');
698
- const isKeyIssue = code === 'MISSING_CREDENTIAL' || code === 'NO_API_KEY'
699
- || status === 401 || status === 403
700
- || /api.?key|credential|unauthoriz|authentication|invalid.?token/i.test(msg);
701
- if (!isKeyIssue) return failure;
702
- return { code: 'NO_API_KEY', message: NO_KEY_MESSAGE, status };
703
- }
704
-
705
- function streamChildWithFriendlyKeyErrors(llm, childOptions) {
706
- const source = llm.stream(childOptions);
707
- return (async function* () {
708
- try {
709
- for await (const chunk of source) {
710
- // finish error 块:翻译其 failure。
711
- if (chunk && chunk.type === 'finish' && chunk.reason && (chunk.reason.kind === 'error' || chunk.reason.kind === 'aborted')) {
712
- const failure = translateKeyError(chunk.reason.failure);
713
- if (failure !== chunk.reason.failure) {
714
- yield { ...chunk, reason: { ...chunk.reason, failure } };
715
- continue;
716
- }
717
- }
718
- yield chunk;
719
- }
720
- } catch (error) {
721
- // 抛出的错误里也可能是缺凭据。
722
- const failure = translateKeyError(error && typeof error === 'object'
723
- ? { code: error.code, status: error.status, message: error.message }
724
- : { message: String(error) });
725
- if (failure && failure.code === 'NO_API_KEY') {
726
- yield { type: 'finish', reason: { kind: 'error', failure } };
727
- } else {
728
- throw error;
729
- }
730
- }
731
- })();
732
- }
733
-
734
- /** 构造“模型组”适配器:内部按健康度顺序把请求转给真正的 nvidia 路由。 */
735
- function buildGroupAdapter(ctx, llm) {
736
- return createGroupAdapter({
737
- groupId: 'nvidia-group',
738
- groupName: 'NVIDIA 模型组',
739
- getMembers: async () => {
740
- const members = await resolveGroupMembers(ctx);
741
- return members;
742
- },
743
- // 用注入到的 llm 服务实例直接调用(外层 ctx 未声明注入 llm,不能在请求时访问 ctx.llm)。
744
- // 同时把「没有 Key / 凭据失效」的上游错误翻译成可读提示——这种错误对所有成员都一样,
745
- // 由 group.js 识别为致命错误直接停止故障转移,避免无谓地逐个重试。
746
- streamChild: (childOptions) => streamChildWithFriendlyKeyErrors(llm, childOptions),
747
- health: groupHealth,
748
- firstByteTimeoutMs: () => groupConfig.firstByteTimeoutMs,
749
- firstTextTimeoutMs: () => groupConfig.firstTextTimeoutMs,
750
- onAttempt: (info) => {
751
- // dock 徽标:只在「真正产出正文」的成功尝试里更新当前模型名。
752
- // info.error 为空且 info.emitted 为真代表该成员给出了可见正文(而非纯思考/失败)。
753
- if (!info.error && info.emitted && info.member) {
754
- dockGroupState.memberId = String(info.member.id || '');
755
- dockGroupState.memberName = friendlyMemberName(info.member);
756
- dockGroupState.sessionId = info.sessionId || dockGroupState.sessionId;
757
- dockGroupState.updatedAt = Date.now();
758
- }
759
- appendGroupEvent(ctx, info.sessionId, GROUP_RECORD_PROBE, {
760
- member: info.member.id,
761
- status: info.error ? 'fail' : 'ok',
762
- error: info.error ? describeErrorSafe(info.error) : '',
763
- });
764
- // 当日用量:每个成员每次尝试都记一条(含失败的、被跳过的切换)。
765
- try {
766
- const usage = info.usage || {};
767
- groupUsage.record({
768
- sessionId: info.sessionId,
769
- memberId: info.member && info.member.id,
770
- ok: !info.error,
771
- failover: Boolean(info.failover),
772
- failoverFrom: info.failoverFrom || '',
773
- firstByteMs: info.firstByteMs,
774
- elapsedMs: info.elapsedMs,
775
- inputTokens: usage.inputTokens || usage.promptTokens,
776
- outputTokens: usage.outputTokens || usage.completionTokens,
777
- error: info.error ? describeErrorSafe(info.error) : '',
778
- });
779
- } catch {
780
- // 统计失败不影响主流程。
781
- }
782
- },
783
- onFailover: (info) => {
784
- // dock 徽标:记录「刚从哪个模型切换过来」,供几秒内的橙色高亮提示。
785
- if (info.from) {
786
- dockGroupState.switchFrom = friendlyMemberName(info.from);
787
- dockGroupState.switchAt = Date.now();
788
- dockGroupState.switchCount += 1;
789
- dockGroupState.sessionId = info.sessionId || dockGroupState.sessionId;
790
- }
791
- appendGroupEvent(ctx, info.sessionId, GROUP_RECORD_FAILOVER, {
792
- from: info.from ? info.from.id : '',
793
- to: info.to ? info.to.id : '',
794
- error: info.error ? describeErrorSafe(info.error) : '',
795
- exhausted: Boolean(info.exhausted),
796
- });
797
- },
798
- });
799
- }
800
-
801
- /** 本地小工具:把错误压成短句(不依赖 group.js 的导出细节)。 */
802
- function describeErrorSafe(error) {
803
- if (!error) return 'unknown error';
804
- if (typeof error === 'string') return error;
805
- if (error.message) return String(error.message);
806
- if (error.code) return String(error.code);
807
- return String(error);
808
- }
809
-
810
- /** 组状态快照:组成员 + 健康 + 冷却剩余,供看板渲染。 */
811
- async function groupStatusSnapshot(ctx) {
812
- const members = (await resolveGroupMembers(ctx)) || [];
813
- const snapshot = groupHealth.snapshot(members.map((m) => m.id));
814
- return {
815
- ok: true,
816
- group: 'nvidia-group',
817
- config: { firstByteTimeoutMs: groupConfig.firstByteTimeoutMs, firstTextTimeoutMs: groupConfig.firstTextTimeoutMs, preferredModel: groupConfig.preferredModel },
818
- members: members.map((m) => {
819
- const h = snapshot[m.id] || {};
820
- return {
821
- id: m.id,
822
- name: m.name || m.id,
823
- description: m.description || '',
824
- status: h.ok === true ? 'ok' : (h.ok === false ? 'failed' : 'unknown'),
825
- failCount: h.failCount || 0,
826
- successCount: h.successCount || 0,
827
- lastError: h.lastError || '',
828
- cooldownRemainingMs: groupHealth.cooldownRemainingMs(m.id),
829
- lastFirstByteMs: typeof h.lastFirstByteMs === 'number' ? h.lastFirstByteMs : null,
830
- };
831
- }),
832
- };
833
- }
834
-
835
- /** 输入框 dock 徽标状态:当前实际出正文的模型 + 切换/熔断计数。 */
836
- async function dockStatusSnapshot(ctx, sessionId) {
837
- const members = (await resolveGroupMembers(ctx)) || [];
838
- const cooling = members.filter((m) => groupHealth.cooldownRemainingMs(m.id) > 0).length;
839
- // 「刚切换」提示保留 6 秒,之后回落到常态绿色。
840
- const SWITCH_NOTICE_MS = 6000;
841
- const justSwitched = Boolean(dockGroupState.switchFrom) && (Date.now() - dockGroupState.switchAt < SWITCH_NOTICE_MS);
842
- // 当前会话已切到别的模型时隐藏徽标:读会话最新 request/header 的 provider。
843
- // best-effort:读不到 header 时保持原逻辑,避免误隐藏。
844
- let currentProvider = '';
845
- let currentModel = '';
846
- try {
847
- const session = sessionFor(ctx, sessionId);
848
- const header = session && typeof session.requestHeader === 'function' ? session.requestHeader() : null;
849
- if (header && header.config) {
850
- if (typeof header.config.provider === 'string') {
851
- currentProvider = header.config.provider;
852
- }
853
- if (typeof header.config.model === 'string') {
854
- currentModel = header.config.model;
855
- }
856
- }
857
- } catch {
858
- currentProvider = '';
859
- currentModel = '';
860
- }
861
- const usingGroup = !currentProvider || currentProvider === 'nvidia-group';
862
- // best-effort: 读不到 model 信息时不隐藏;只有明确选了非 auto 的具体模型才隐藏。
863
- const isAutoModel = !currentModel || isAutoMemberId(currentModel);
864
- return {
865
- ok: true,
866
- active: Boolean(dockGroupState.memberName) && usingGroup && isAutoModel,
867
- memberName: dockGroupState.memberName || '',
868
- memberId: dockGroupState.memberId || '',
869
- switchFrom: justSwitched ? dockGroupState.switchFrom : '',
870
- switchCount: dockGroupState.switchCount || 0,
871
- cooldownCount: cooling,
872
- updatedAt: dockGroupState.updatedAt || 0,
873
- };
874
- }
875
-
876
- /** 探测所有成员(用现有 probeStreaming 快速首包探测),刷新健康表。 */
877
- async function probeGroup(ctx) {
878
- const members = (await resolveGroupMembers(ctx)) || [];
879
- const apiKey = await resolveKeyFromContext();
880
- const out = [];
881
- for (const m of members) {
882
- groupHealth.recordProbeStart(m.id);
883
- const probe = await probeStreaming(m.id, apiKey, 512, 8000);
884
- if (probe.kind === 'ok-stream' || probe.kind === 'ok-no-stream') {
885
- groupHealth.recordSuccess(m.id, null);
886
- out.push({ id: m.id, status: 'ok' });
887
- } else {
888
- const detail = probe.kind === 'http-error'
889
- ? '调用失败(HTTP ' + probe.response.status + ')'
890
- : (probe.error && probe.error.name === 'AbortError'
891
- ? '首包超时(8 秒无响应)'
892
- : '网络错误:' + String((probe.error && probe.error.message) || probe.error));
893
- groupHealth.recordFailure(m.id, { message: detail });
894
- out.push({ id: m.id, status: 'fail', detail });
895
- }
896
- appendGroupEvent(ctx, null, GROUP_RECORD_PROBE, { member: m.id, status: out[out.length - 1].status === 'ok' ? 'ok' : 'fail', error: out[out.length - 1].detail || '' });
897
- }
898
- return { ok: true, probed: out.length, results: out };
899
- }
900
-
901
- /** POST /api/nvidia-models — actions: detect | test | keyStatus | setKey | clearKey | configure | groupStatus | probeGroup | resetGroup | getGroupConfig | setGroupConfig | usageStats | resetUsage | checkUpdate | dockStatus. */
902
- function createNvidiaModelsRoute(ctx) {
903
- return {
904
- path: '/api/nvidia-models',
905
- methods: ['POST'],
906
- requestBody: 'buffered',
907
- fetch: async (request) => {
908
- const body = await readJsonBody(request);
909
- const action = body && typeof body.action === 'string' ? body.action : 'detect';
910
- let result;
911
- // 需要 Key 的 action 在没有配置 Key 时统一早退,给出一致的可读提示。
912
- // keyStatus/setKey/clearKey/resetGroup/resetUsage/checkUpdate 不拦(它们本就用于修复无 Key 状态)。
913
- const NEED_KEY_ACTIONS = new Set(['detect', 'test', 'configure', 'probeGroup', 'groupStatus', 'dockStatus', 'usageStats']);
914
- if (NEED_KEY_ACTIONS.has(action) && !(await hasNvidiaKey(ctx))) {
915
- result = { ok: false, code: 'NO_API_KEY', message: '未配置 NVIDIA API Key,请先在面板上方保存后再继续。' };
916
- } else if (action === 'test' && typeof body.model === 'string' && body.model) {
917
- result = await testNvidiaModel(body.model);
918
- } else if (action === 'keyStatus') {
919
- const info = await withCredentials(ctx, (credentials) => credentials.describe(NVIDIA_KEY_REF));
920
- result = info && typeof info === 'object'
921
- ? { configured: Boolean(info.configured), source: info.source || null, writable: info.writable !== false }
922
- : { configured: false, source: null, writable: false, unavailable: true };
923
- } else if (action === 'setKey' && typeof body.key === 'string' && body.key.trim()) {
924
- const key = body.key.trim();
925
- const saved = await withCredentials(ctx, async (credentials) => {
926
- await credentials.set(NVIDIA_KEY_REF, key);
927
- return credentials.describe(NVIDIA_KEY_REF);
928
- });
929
- if (!saved || typeof saved !== 'object') {
930
- result = { saved: false, error: '凭据服务不可用,无法保存' };
931
- } else if (!saved.configured) {
932
- result = { saved: false, error: '保存后校验未通过(凭据存储未确认写入)' };
933
- } else {
934
- result = { saved: true, source: saved.source || 'stored' };
935
- }
936
- } else if (action === 'clearKey') {
937
- const cleared = await withCredentials(ctx, async (credentials) => {
938
- await credentials.unset(NVIDIA_KEY_REF);
939
- return credentials.describe(NVIDIA_KEY_REF);
940
- });
941
- result = cleared && typeof cleared === 'object' && !cleared.configured
942
- ? { cleared: true }
943
- : { cleared: false, error: '清除失败或凭据服务不可用' };
944
- } else if (action === 'configure') {
945
- result = await configureNvidiaModels(ctx, body.results);
946
- } else if (action === 'groupStatus') {
947
- result = await groupStatusSnapshot(ctx);
948
- } else if (action === 'probeGroup') {
949
- result = await probeGroup(ctx);
950
- } else if (action === 'resetGroup') {
951
- if (typeof body.model === 'string' && body.model) groupHealth.reset(body.model);
952
- else groupHealth.reset();
953
- result = await groupStatusSnapshot(ctx);
954
- } else if (action === 'getGroupConfig') {
955
- result = { ok: true, config: { ...groupConfig } };
956
- } else if (action === 'setGroupConfig') {
957
- if (body.config && typeof body.config === 'object') {
958
- if (Number.isFinite(body.config.firstByteTimeoutMs) && body.config.firstByteTimeoutMs >= 1000) {
959
- groupConfig.firstByteTimeoutMs = Math.min(120000, Math.round(body.config.firstByteTimeoutMs));
960
- }
961
- if (Number.isFinite(body.config.firstTextTimeoutMs) && body.config.firstTextTimeoutMs >= 5000) {
962
- groupConfig.firstTextTimeoutMs = Math.min(180000, Math.round(body.config.firstTextTimeoutMs));
963
- }
964
- if (typeof body.config.preferredModel === 'string') {
965
- groupConfig.preferredModel = body.config.preferredModel;
966
- }
967
- if (Number.isFinite(body.config.autoRefreshMs) && body.config.autoRefreshMs >= 60000) {
968
- groupConfig.autoRefreshMs = Math.min(3600000, Math.round(body.config.autoRefreshMs));
969
- }
970
- }
971
- result = { ok: true, config: { ...groupConfig } };
972
- } else if (action === 'usageStats') {
973
- result = { ok: true, stats: groupUsage.snapshot(typeof body.day === 'string' && body.day ? body.day : undefined) };
974
- } else if (action === 'resetUsage') {
975
- if (typeof body.day === 'string' && body.day) groupUsage.reset(body.day);
976
- else groupUsage.reset();
977
- result = { ok: true, stats: groupUsage.snapshot() };
978
- } else if (action === 'checkUpdate') {
979
- result = await checkUpdate(ctx);
980
- } else if (action === 'dockStatus') {
981
- result = await dockStatusSnapshot(ctx, body.sessionId);
982
- } else {
983
- result = await detectNvidiaModels();
984
- if (result && result.source === 'live') lastDetectedModels = normalizeGroupMembers(result.models);
985
- }
986
- return new Response(JSON.stringify(result), {
987
- status: 200,
988
- headers: { 'content-type': 'application/json' },
989
- });
990
- },
991
- };
992
- }
993
-
994
- /** Command: write the NVIDIA model list into the llm-pi-ai nvidia provider. */
995
- const GITHUB_REPO = 'windxxf/dsh-nvidia-models-panel';
996
- const GITHUB_RELEASES_URL = 'https://github.com/' + GITHUB_REPO + '/releases';
997
-
998
- /**
999
- * 读取 GitHub 远端最新版本。
1000
- * 首选 raw.githubusercontent.com 的 HEAD/package.json(也是 dshmarket 的判定方式)——
1001
- * 这个通道不吃 GitHub REST API 的匿名速率限制(每小时 60 次,很容易被耗尽)。
1002
- * 令牌缓存 30 分钟,避免每次挂载面板都发请求。
1003
- */
1004
- let _updateCache = { at: 0, version: null };
1005
- const UPDATE_CACHE_MS = 30 * 60 * 1000;
1006
-
1007
- async function fetchLatestVersion() {
1008
- if (_updateCache.version && Date.now() - _updateCache.at < UPDATE_CACHE_MS) {
1009
- return _updateCache.version;
1010
- }
1011
- let version = null;
1012
- const url = 'https://raw.githubusercontent.com/' + GITHUB_REPO + '/HEAD/package.json';
1013
- // 网络间歇性抖动时重试一次(github 443 在本机时断时续)。
1014
- for (let attempt = 0; attempt < 2 && !version; attempt += 1) {
1015
- try {
1016
- const res = await fetch(url, { signal: AbortSignal.timeout(8000) });
1017
- if (res.ok) {
1018
- const data = await res.json();
1019
- if (data && typeof data.version === 'string') version = data.version;
1020
- }
1021
- } catch { /* 网络不通,下一轮重试 */ }
1022
- if (!version && attempt === 0) await new Promise((r) => setTimeout(r, 500));
1023
- }
1024
- if (version) _updateCache = { at: Date.now(), version };
1025
- return version;
1026
- }
1027
-
1028
- async function checkUpdate(ctx) {
1029
- // 获取插件自身版本(尽力而为,失败不阻塞)。
1030
- let currentVersion = null;
1031
- try {
1032
- const pkg = await readOwnPackageJson();
1033
- if (typeof pkg.version === 'string') currentVersion = pkg.version;
1034
- } catch { /* 忽略 */ }
1035
-
1036
- let latestVersion = null;
1037
- try {
1038
- latestVersion = await fetchLatestVersion();
1039
- } catch { /* 忽略 */ }
1040
- const reachable = Boolean(latestVersion);
1041
-
1042
- const latestTag = latestVersion ? ('v' + latestVersion.replace(/^v/, '')) : null;
1043
- const hasUpdate = Boolean(currentVersion && latestVersion && semverGt(latestVersion, currentVersion));
1044
- const message = hasUpdate
1045
- ? ('发现新版本 ' + latestTag + ',当前 ' + currentVersion)
1046
- : (!reachable
1047
- ? '检查失败:暂时无法连接 GitHub(网络问题),请稍后重试'
1048
- : '已是最新版本');
1049
- return {
1050
- ok: true,
1051
- currentVersion,
1052
- latestTag,
1053
- latestUrl: GITHUB_RELEASES_URL,
1054
- hasUpdate,
1055
- reachable,
1056
- message,
1057
- };
1058
- }
1059
-
1060
- /** 读取插件自身 package.json 的内容(用于读取当前版本号)。 */
1061
- async function readOwnPackageJson() {
1062
- const { readFile } = await import('node:fs/promises');
1063
- const { fileURLToPath } = await import('node:url');
1064
- // index.js 在 src/ 下,package.json 在上一层;两个候选都试,兼容不同加载布局。
1065
- const candidates = [
1066
- fileURLToPath(new URL('../package.json', import.meta.url)),
1067
- fileURLToPath(new URL('./package.json', import.meta.url)),
1068
- ];
1069
- let lastErr;
1070
- for (const path of candidates) {
1071
- try {
1072
- return JSON.parse(await readFile(path, 'utf8'));
1073
- } catch (err) { lastErr = err; }
1074
- }
1075
- throw lastErr || new Error('package.json not found');
1076
- }
1077
-
1078
- /** 语义版本比较:v1.3.8 / 1.3.8 / 1.3.8-rc1 等,仅比较数字段。 */
1079
- function semverGt(a, b) {
1080
- const norm = (s) => String(s || '').replace(/^v/, '').split(/[.\-]/).map((p) => Number(p) || 0);
1081
- const x = norm(a), y = norm(b);
1082
- for (let i = 0; i < Math.max(x.length, y.length); i += 1) {
1083
- const xi = x[i] || 0, yi = y[i] || 0;
1084
- if (xi !== yi) return xi > yi;
1085
- }
1086
- return false;
1087
- }
1088
-
1089
- export function apply(ctx) {
1090
- const disposers = [];
1091
-
1092
- // 每次加载 / 重载插件时清空上一次残留的模型健康(失败计数 + 熔断冷却)。
1093
- // 健康表是进程级单例缓存:旧版本(多模态硬过滤)可能把一批本来可用的成员
1094
- // 反复判失败、推进熔断,重载后如果沿用旧状态,刚修好的成员仍会被跳过。
1095
- // 清零是安全的——真正的上游不可用仍由 FAILOVER 与看板实时探测照常兜底。
1096
- try { groupHealth.reset(); } catch { /* 忽略 */ }
1097
-
1098
- // 同步清空 dock 徽标状态:重载后没有"当前模型"可报,徽标回落为不显示,
1099
- // 直到模型组下一次真正产出正文才重新点亮。
1100
- try {
1101
- dockGroupState.sessionId = null;
1102
- dockGroupState.memberId = '';
1103
- dockGroupState.memberName = '';
1104
- dockGroupState.switchFrom = '';
1105
- dockGroupState.switchAt = 0;
1106
- dockGroupState.switchCount = 0;
1107
- dockGroupState.updatedAt = 0;
1108
- } catch { /* 忽略 */ }
1109
-
1110
- // 从磁盘读回调用日志快照(重载/重启不丢)。fire-and-forget:hydrate 内部已
1111
- // 全量 try/catch,失败静默;不阻塞插件激活。
1112
- try { Promise.resolve(groupUsage.hydrate()).catch(() => {}); } catch { /* 忽略 */ }
1113
-
1114
- // Slash-command handlers run against an agent invocation ({ agent, rawInput }),
1115
- // NOT the plugin context — so both handlers close over the plugin ctx instead.
1116
- disposers.push(ctx.commands.register({
1117
- name: 'nvidia-models-detect',
1118
- title: '检测 NVIDIA 可用模型',
1119
- description: '实时查询 NVIDIA NIM API,列出当前可用模型及简介',
1120
- handler: async () => {
1121
- const result = await detectNvidiaModels();
1122
- const head = result.source === 'live'
1123
- ? '实时检测到 ' + result.count + ' 个可用模型(来自 NVIDIA API):'
1124
- : 'NVIDIA API 不可达(' + result.reason + '),以下为内置目录:';
1125
- const list = result.models.map((m) => '- ' + m.name + ' (' + m.id + '):' + m.description).join('\n');
1126
- return { kind: 'success', text: head + '\n\n' + list + '\n\n运行 /nvidia-models-configure 可将模型写入 llm-pi-ai 的 nvidia 供应商。' };
1127
- },
1128
- }));
1129
-
1130
- disposers.push(ctx.commands.register({
1131
- name: 'nvidia-models-configure',
1132
- title: '配置 NVIDIA 模型到设置',
1133
- description: '把检测到的模型批量写入 llm-pi-ai 的 nvidia 供应商模型列表',
1134
- handler: async () => {
1135
- const result = await configureNvidiaModels(ctx);
1136
- return result.ok
1137
- ? { kind: 'success', text: result.message }
1138
- : { kind: 'error', text: result.error };
1139
- },
1140
- }));
1141
-
1142
- // Install the credential-resolver closure: stored key first (it outranks the
1143
- // environment by design), then the plain environment variable.
1144
- resolveKeyFromContext = async () => {
1145
- try {
1146
- const resolved = await new Promise((done) => {
1147
- ctx.inject(['credentials'], (scoped) => {
1148
- try {
1149
- done((async () => {
1150
- const credentials = scoped.credentials;
1151
- try {
1152
- const hit = await credentials.resolve('NVIDIA_API_KEY');
1153
- if (hit && typeof hit.value === 'string' && hit.value.trim()) return hit.value.trim();
1154
- } catch {
1155
- // The reference form may be rejected; fall through to env.
1156
- }
1157
- return '';
1158
- })());
1159
- } catch {
1160
- done();
1161
- }
1162
- });
1163
- });
1164
- if (resolved) return resolved;
1165
- } catch {
1166
- // Credential seam unavailable; env fallback below.
1167
- }
1168
- const fromEnv = process.env.NVIDIA_API_KEY;
1169
- return fromEnv && fromEnv.trim() ? fromEnv.trim() : '';
1170
- };
1171
-
1172
- ctx.inject(['connection'], (scoped) => {
1173
- const connection = scoped.connection;
1174
- const unregisterRoute = connection.fetch.register(createNvidiaModelsRoute(ctx), 'nvidia-models: /api/nvidia-models route');
1175
- scoped.effect(() => unregisterRoute, 'nvidia-models: /api route');
1176
- });
1177
-
1178
- // 注册「NVIDIA 模型组」LLM 适配器(provider = nvidia-group)。
1179
- // 用可选注入:没有 llm 服务时插件其余功能照常可用,仅模型组不可用。
1180
- ctx.inject(['llm'], (scoped) => {
1181
- try {
1182
- const llm = scoped.llm;
1183
- const adapter = buildGroupAdapter(ctx, llm);
1184
- // registerAdapter 自身以 ctx.effect 挂载,随 fiber 释放,无需手动注销。
1185
- llm.registerAdapter(['nvidia-group'], adapter);
1186
- } catch (error) {
1187
- // 适配器注册失败不应拖垮插件;面板会显示模型组不可用。
1188
- try { console.warn('[nvidia-models-panel] 注册 nvidia-group 适配器失败:' + describeErrorSafe(error)); } catch { /* 忽略 */ }
1189
- }
1190
- });
1191
-
1192
- // 注册会话投影 nvidiaHealth:把故障转移/探测事件折成看板状态。
1193
- ctx.inject(['sessionProjections'], (scoped) => {
1194
- try {
1195
- const registry = scoped.sessionProjections;
1196
- // register() 是 thenable,且内部以 ctx.effect 挂载(随 fiber 释放)。
1197
- Promise.resolve(registry.register({
1198
- key: 'nvidiaHealth',
1199
- stateVersion: 1,
1200
- stateSchema: makeSchema(),
1201
- init: () => createGroupState(),
1202
- apply: (state, event) => foldGroupEvent(state, event),
1203
- wire: {
1204
- viewSchema: makeSchema(),
1205
- view: (state) => state,
1206
- summary: false,
1207
- },
1208
- })).catch((error) => {
1209
- try { console.warn('[nvidia-models-panel] 注册 nvidiaHealth 投影失败:' + describeErrorSafe(error)); } catch { /* 忽略 */ }
1210
- });
1211
- } catch (error) {
1212
- try { console.warn('[nvidia-models-panel] 注册 nvidiaHealth 投影失败:' + describeErrorSafe(error)); } catch { /* 忽略 */ }
1213
- }
1214
- });
1215
-
1216
- // 自动发现守护:周期性静默拉取 NVIDIA 模型目录,刷新 lastDetectedModels,
1217
- // 让「NVIDIA 模型组」自动跟上新上架/下架的模型,无需用户手动点「检测」。
1218
- // 仅在已有 API Key 时才探测;失败静默(不打扰用户),退避由定时器自然承担。
1219
- const startAutoDiscovery = () => {
1220
- let stopped = false;
1221
- let timer = null;
1222
- const tick = async () => {
1223
- if (stopped) return;
1224
- try {
1225
- const key = await resolveKeyFromContext();
1226
- if (key) {
1227
- const detection = await detectNvidiaModels();
1228
- if (detection && detection.source === 'live') {
1229
- lastDetectedModels = normalizeGroupMembers(detection.models);
1230
- }
1231
- }
1232
- } catch {
1233
- // 自动发现是尽力而为,失败静默。
1234
- }
1235
- if (stopped) return;
1236
- const ms = Math.max(60000, Number(groupConfig.autoRefreshMs) || 300000);
1237
- timer = setTimeout(tick, ms);
1238
- if (timer && typeof timer.unref === 'function') timer.unref();
1239
- };
1240
- // 首次延迟 20s,避开启动高峰。
1241
- timer = setTimeout(tick, 20000);
1242
- if (timer && typeof timer.unref === 'function') timer.unref();
1243
- return () => { stopped = true; if (timer) clearTimeout(timer); };
1244
- };
1245
- disposers.push(startAutoDiscovery());
1246
-
1247
- return () => {
1248
- resolveKeyFromContext = async () => '';
1249
- for (const dispose of disposers) {
1250
- if (typeof dispose === 'function') dispose();
1251
- }
1252
- };
1253
- }
1
+ /** Host half of the Nvidia Models Panel bundle. */
2
+
3
+ import {
4
+ createHealthRegistry,
5
+ createGroupAdapter,
6
+ createGroupState,
7
+ makeSchema,
8
+ foldGroupEvent,
9
+ AUTO_MEMBER_ID,
10
+ AUTO_MEMBER_NAME,
11
+ AUTO_MEMBER_DESC,
12
+ isAutoMemberId,
13
+ } from './group.js';
14
+
15
+ import { createUsageRegistry } from './usage.js';
16
+
17
+ export const inject = ['commands', 'configEditor'];
18
+
19
+ /** NVIDIA NIM public endpoints (model list is anonymous-readable; completions need a key). */
20
+ const NIM_MODELS_URL = 'https://integrate.api.nvidia.com/v1/models';
21
+ const NIM_COMPLETIONS_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';
22
+
23
+ /**
24
+ * 旧版「一键配置」给所有模型硬编码的上下文窗口(131072 = 128K)。
25
+ * 绝大多数 NVIDIA NIM 模型的 /v1/models 不返回 context_window,这个 128K 的
26
+ * 保守值会让 pi-ai 在本会话这种长上下文下误判为「silent context overflow」,
27
+ * 把一次正常应答报成致命的 CONTEXT_WINDOW_EXCEEDED。见 inferContextWindow。
28
+ */
29
+ const LEGACY_CONTEXT_WINDOW = 131072;
30
+
31
+ /**
32
+ * 未上报 context_window 时的宽松默认窗口。宁可声明得宽松一点:
33
+ * 声明过小 → pi-ai 误判溢出(假失败);声明偏大 → 真超长时上游返回真实报错(诚实失败)。
34
+ */
35
+ const DEFAULT_CONTEXT_WINDOW = 1048576;
36
+
37
+ /**
38
+ * 解析某模型应使用的上下文窗口:优先用上游 /v1/models 上报的 context_window,
39
+ * 缺省时按模型族给合理值,最后回落到宽松默认,绝不沿用旧的 128K。
40
+ * 导出以便单测。
41
+ * @param {string} id 模型 id
42
+ * @param {number} [upstreamCtx] 上游上报的 context_window(若有)
43
+ */
44
+ export function inferContextWindow(id, upstreamCtx) {
45
+ if (Number.isFinite(upstreamCtx) && upstreamCtx > 0) return Math.round(upstreamCtx);
46
+ const s = String(id || '');
47
+ // 明确的长上下文模型族。
48
+ if (/deepseek-v4|nemotron-3-ultra|nemotron-3\.5-(super|ultra)|llama-3\.1|mistral-large/i.test(s)) return 1048576;
49
+ if (/nemotron|llama|mistral|qwen|glm|kimi|step|minimax|gpt-oss|muse/i.test(s)) return 262144;
50
+ return DEFAULT_CONTEXT_WINDOW;
51
+ }
52
+
53
+ /** Chinese blurbs per publisher prefix, used to build per-model descriptions. */
54
+ const PUBLISHER_BLURBS = {
55
+ nvidia: 'NVIDIA 官方',
56
+ 'nv-mistralai': 'NVIDIA 与 Mistral 联合优化',
57
+ meta: 'Meta Llama 系列',
58
+ 'deepseek-ai': 'DeepSeek 系列',
59
+ 'z-ai': '智谱 GLM 系列',
60
+ moonshotai: '月之暗面 Kimi 系列',
61
+ qwen: '阿里通义千问系列',
62
+ google: 'Google 开源模型',
63
+ microsoft: '微软 Phi 系列',
64
+ mistralai: 'Mistral AI 系列',
65
+ openai: 'OpenAI 开源模型',
66
+ '01-ai': '零一万物 Yi 系列',
67
+ ai21labs: 'AI21 Jamba 系列',
68
+ ibm: 'IBM Granite 系列',
69
+ bigcode: 'BigCode 代码模型',
70
+ databricks: 'Databricks 模型',
71
+ snowflake: 'Snowflake Arctic 系列',
72
+ writer: 'Writer Palmyra 系列',
73
+ poolside: 'Poolside 代码模型',
74
+ minimaxai: 'MiniMax 系列',
75
+ 'stepfun-ai': '阶跃星辰系列',
76
+ zyphra: 'Zyphra 系列',
77
+ adept: 'Adept 模型',
78
+ aisingapore: 'AI Singapore SEA-LION 系列',
79
+ };
80
+
81
+ /** Built-in fallback shown when the upstream API is unreachable. */
82
+ const BUILTIN_MODELS = [
83
+ { id: 'nvidia/llama-3.1-nemotron-70b-instruct', name: 'Llama 3.1 Nemotron 70B', description: 'NVIDIA 旗舰推理模型,擅长复杂推理、编码与数学' },
84
+ { id: 'nvidia/nemotron-3-ultra-550b-a55b', name: 'Nemotron 3 Ultra 550B', description: 'NVIDIA 官方超大参数模型,推理与编码能力极强' },
85
+ { id: 'nvidia/nemotron-3-super-120b-a12b', name: 'Nemotron 3 Super 120B', description: 'NVIDIA 官方高性能均衡型,适合企业级任务' },
86
+ { id: 'nvidia/nemotron-3.5-lightning-30b-a3b', name: 'Nemotron 3.5 Lightning 30B', description: 'NVIDIA 官方轻量高速 MoE,响应快成本低' },
87
+ { id: 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning', name: 'Nemotron 3 Nano Omni 30B', description: 'NVIDIA 官方全模态模型,支持文本与图像' },
88
+ { id: 'deepseek-ai/deepseek-v4.1-flash', name: 'DeepSeek V4.1 Flash', description: 'DeepSeek 系列,长上下文,支持文本与图像' },
89
+ { id: 'moonshotai/kimi-k3', name: 'Kimi K3', description: '月之暗面 Kimi 系列,百万级上下文窗口' },
90
+ { id: 'z-ai/glm-5.3', name: 'GLM-5.3', description: '智谱 GLM 系列,强推理与长上下文' },
91
+ { id: 'meta/llama-3.2-90b-vision-instruct', name: 'Llama 3.2 90B Vision', description: 'Meta Llama 系列,多语言视觉理解' },
92
+ { id: 'mistralai/mistral-7b-instruct-v0.3', name: 'Mistral 7B Instruct v0.3', description: 'Mistral AI 系列,轻量高效通用模型' },
93
+ ];
94
+
95
+ /** Build a short Chinese blurb for one model id. */
96
+ function describeModel(id) {
97
+ const slash = id.indexOf('/');
98
+ const publisher = slash > 0 ? id.slice(0, slash) : '';
99
+ const bare = slash > 0 ? id.slice(slash + 1) : id;
100
+ const who = PUBLISHER_BLURBS[publisher] || (publisher ? publisher + ' 发布' : 'NVIDIA NIM 托管');
101
+ let kind = '通用大语言模型';
102
+ const lower = bare.toLowerCase();
103
+ if (/vision|vl|omni|diffusion|image/.test(lower)) kind = '支持视觉/多模态输入';
104
+ else if (/coder|code/.test(lower)) kind = '专攻代码生成与补全';
105
+ else if (/embed|rerank|reward/.test(lower)) kind = '检索/评测类模型';
106
+ else if (/reason|thinking|r1/.test(lower)) kind = '强化推理能力';
107
+ return who + ',' + kind + '。';
108
+ }
109
+
110
+ /** True for model families the chat-completions probe cannot meaningfully call. */
111
+ function isNonChatModel(id) {
112
+ // embed/rerank/reward/diffusion——不是对话模型;
113
+ // guard/safety/calibration/parse/translate——是专用模型,放进模型组只会每一轮都失败。
114
+ return /embed|rerank|reward|diffusion|guard|safety|calibration|nemotron-parse|riva-translate/i.test(String(id || ''));
115
+ }
116
+
117
+ /** Context-bound key resolver installed during apply(); prefers env, then the credential store. */
118
+ let resolveKeyFromContext = async () => '';
119
+
120
+ /** Run one operation against the credentials service; resolves null when unavailable. */
121
+ function withCredentials(ctx, operation) {
122
+ return new Promise((done) => {
123
+ try {
124
+ ctx.inject(['credentials'], (scoped) => {
125
+ try {
126
+ done(Promise.resolve(operation(scoped.credentials)).catch(() => null));
127
+ } catch {
128
+ done(null);
129
+ }
130
+ });
131
+ } catch {
132
+ done(null);
133
+ }
134
+ });
135
+ }
136
+
137
+ /** NVIDIA Key 是否已配置(凭据服务不可用时按「已配置」处理,避免误拦截)。 */
138
+ async function hasNvidiaKey(ctx) {
139
+ const info = await withCredentials(ctx, (credentials) => credentials.describe(NVIDIA_KEY_REF));
140
+ if (!info || info.unavailable) return true; // 无法判定时不拦截,交给上游返回真实错误
141
+ return Boolean(info.configured);
142
+ }
143
+
144
+ /** Run one operation against the configEditor service; resolves null when unavailable. */
145
+ function withConfigEditor(ctx, operation) {
146
+ return new Promise((done) => {
147
+ try {
148
+ ctx.inject(['configEditor'], (scoped) => {
149
+ try {
150
+ done(Promise.resolve(operation(scoped.configEditor)).catch(() => null));
151
+ } catch {
152
+ done(null);
153
+ }
154
+ });
155
+ } catch {
156
+ done(null);
157
+ }
158
+ });
159
+ }
160
+
161
+ const LLM_PLUGIN_NAME = '@deepseek-ai/dsh-llm-pi-ai';
162
+
163
+ /**
164
+ * configEditor.entries() yields Loader Entry objects, so the plugin identity
165
+ * lives at entry.options.id / entry.options.name (see dsh-config-editor
166
+ * lib/index.js entries() and edit()). Tolerant of the other plausible shapes.
167
+ */
168
+ function entryIdentifiers(entry) {
169
+ const values = [];
170
+ const push = (value) => { if (typeof value === 'string' && value) values.push(value); };
171
+ try {
172
+ push(entry.id);
173
+ push(entry.name);
174
+ const options = entry.options;
175
+ if (options && typeof options === 'object') {
176
+ push(options.id);
177
+ push(options.name);
178
+ push(options.group);
179
+ }
180
+ } catch {
181
+ // An unreadable entry simply cannot be matched by identifier.
182
+ }
183
+ return values;
184
+ }
185
+
186
+ /** Does this entry address the llm-pi-ai plugin (any id/patchId/name form)? */
187
+ function isLlmPiAiEntry(entry) {
188
+ return entryIdentifiers(entry).some((value) =>
189
+ value === LLM_PLUGIN_NAME || value === 'llm-pi-ai' || value.endsWith(':llm-pi-ai'));
190
+ }
191
+
192
+ /** Compact, secret-free dump of entries, used only to diagnose a failed lookup. */
193
+ function describeEntries(entries) {
194
+ return entries.slice(0, 20).map((entry) => {
195
+ const out = {};
196
+ try {
197
+ const options = entry.options || {};
198
+ if (typeof options.id === 'string') out.id = options.id;
199
+ if (typeof options.name === 'string') out.name = options.name;
200
+ if (options.config !== undefined) out.hasConfig = true;
201
+ if (entry.fiber) out.active = entry.fiber.state === 2;
202
+ } catch {
203
+ out.unreadable = true;
204
+ }
205
+ return out;
206
+ });
207
+ }
208
+
209
+ /**
210
+ * Detect models live and write the AVAILABLE ones into the llm-pi-ai nvidia
211
+ * provider, so the chat model picker offers exactly what can be called.
212
+ * Shared by the panel button (POST action=configure) and the slash command.
213
+ * `probeResults` (id → 'ok' | 'unavailable') from the panel's per-model probe
214
+ * filters the list; without it, non-chat families are the only ones dropped.
215
+ */
216
+ async function configureNvidiaModels(ctx, probeResults) {
217
+ const configEditor = await withConfigEditor(ctx, (editor) => editor);
218
+ if (!configEditor) {
219
+ return { ok: false, error: 'configEditor 服务不可用,无法写入配置' };
220
+ }
221
+ const detection = await detectNvidiaModels();
222
+ const allModels = detection.models;
223
+ if (detection.source === 'live') lastDetectedModels = normalizeGroupMembers(allModels);
224
+ const source = detection.source === 'live' ? 'NVIDIA API 实时检测' : '内置目录';
225
+ let available;
226
+ let droppedUnavailable = 0;
227
+ let droppedNonChat = 0;
228
+ if (probeResults && typeof probeResults === 'object' && Object.keys(probeResults).length > 0) {
229
+ available = allModels.filter((m) => probeResults[m.id] === 'ok');
230
+ droppedUnavailable = allModels.length - available.length;
231
+ } else {
232
+ available = allModels.filter((m) => !isNonChatModel(m.id));
233
+ droppedNonChat = allModels.length - available.length;
234
+ }
235
+ if (available.length === 0) {
236
+ return { ok: false, error: '没有试调用通过的可用模型,未写入。请先确认 API Key 有效后重新试调用。' };
237
+ }
238
+ // Locate the llm-pi-ai row by identity across every plausible field and
239
+ // fall back to the configuration() projection before giving up.
240
+ let entries;
241
+ try {
242
+ entries = configEditor.entries();
243
+ } catch (error) {
244
+ return { ok: false, error: '读取配置条目失败:' + String((error && error.message) || error) };
245
+ }
246
+ if (!Array.isArray(entries)) {
247
+ return { ok: false, error: '配置条目返回异常:' + JSON.stringify(entries).slice(0, 200) };
248
+ }
249
+ let configs = [];
250
+ try {
251
+ configs = configEditor.configuration();
252
+ } catch {
253
+ configs = [];
254
+ }
255
+ let llmEntry = entries.find(isLlmPiAiEntry);
256
+ let llmHit = null;
257
+ if (llmEntry) {
258
+ llmHit = (Array.isArray(configs) ? configs : []).find((c) => c && c.entry === llmEntry) || null;
259
+ } else {
260
+ llmHit = (Array.isArray(configs) ? configs : []).find((c) => c && isLlmPiAiEntry(c.entry)) || null;
261
+ if (llmHit) llmEntry = llmHit.entry;
262
+ }
263
+ if (!llmEntry) {
264
+ return {
265
+ ok: false,
266
+ error: '未找到 llm-pi-ai 配置项(entries 共 ' + entries.length + ' 条)。诊断信息:' + JSON.stringify(describeEntries(entries)).slice(0, 900),
267
+ };
268
+ }
269
+ let existingCount = 0;
270
+ if (llmHit && llmHit.override && llmHit.override.providers && llmHit.override.providers.nvidia) {
271
+ const models = llmHit.override.providers.nvidia.models;
272
+ existingCount = Array.isArray(models) ? models.length : 0;
273
+ }
274
+ const nextModels = available.map((m) => ({
275
+ id: m.id,
276
+ name: m.name + ' - ' + m.description,
277
+ contextWindow: inferContextWindow(m.id, m.upstreamCtx),
278
+ maxTokens: 8192,
279
+ input: /vision|vl|omni|diffusion|image/i.test(m.id) ? ['text', 'image'] : ['text'],
280
+ }));
281
+ try {
282
+ await configEditor.edit(llmEntry, (current, inherited) => {
283
+ // Start from inherited ∪ override so unrelated providers and fields survive.
284
+ const base = { ...(inherited || {}), ...(current || {}) };
285
+ const baseProviders = base.providers || {};
286
+ const baseNvidia = baseProviders.nvidia || {};
287
+ return {
288
+ ...base,
289
+ providers: {
290
+ ...baseProviders,
291
+ nvidia: {
292
+ ...baseNvidia,
293
+ apiKeyEnv: baseNvidia.apiKeyEnv || 'NVIDIA_API_KEY',
294
+ models: nextModels,
295
+ },
296
+ },
297
+ };
298
+ });
299
+ } catch (error) {
300
+ return { ok: false, error: '写入配置失败:' + String((error && error.message) || error) };
301
+ }
302
+ const droppedNote = droppedUnavailable > 0
303
+ ? ',剔除 ' + droppedUnavailable + ' 个试调用未通过的模型'
304
+ : (droppedNonChat > 0 ? ',跳过 ' + droppedNonChat + ' 个非对话模型' : '');
305
+ return {
306
+ ok: true,
307
+ message: '已' + (existingCount ? '更新(原 ' + existingCount + ' 个模型)' : '写入') + ' nvidia 供应商:' + nextModels.length + ' 个【试调用可用】模型' + droppedNote + '(来源:' + source + ')。模型名称后附简介,现在对话框的模型选择器即可选用;凭据与正式路由共用,下一次请求即生效。',
308
+ };
309
+ }
310
+
311
+ /** Query NVIDIA NIM for the live model list; falls back to the built-in catalog. */
312
+ async function detectNvidiaModels() {
313
+ const controller = new AbortController();
314
+ const timer = setTimeout(() => controller.abort(), 15000);
315
+ try {
316
+ const apiKey = await resolveKeyFromContext();
317
+ const headers = { accept: 'application/json' };
318
+ if (apiKey) headers.authorization = 'Bearer ' + apiKey;
319
+ const upstream = await fetch(NIM_MODELS_URL, { headers, signal: controller.signal });
320
+ if (!upstream.ok) {
321
+ return { ok: false, reason: 'NVIDIA API 返回 HTTP ' + upstream.status, source: 'builtin', models: BUILTIN_MODELS };
322
+ }
323
+ const data = await upstream.json();
324
+ const raw = Array.isArray(data && data.data) ? data.data : [];
325
+ if (raw.length === 0) {
326
+ return { ok: false, reason: 'NVIDIA API 返回了空列表', source: 'builtin', models: BUILTIN_MODELS };
327
+ }
328
+ const models = raw.map((m) => ({
329
+ id: String(m.id || ''),
330
+ name: String(m.id || '').split('/').pop() || String(m.id || ''),
331
+ description: describeModel(String(m.id || '')),
332
+ upstreamCtx: (Number.isFinite(m.context_window) && m.context_window > 0)
333
+ ? m.context_window
334
+ : (Number.isFinite(m.context_length) && m.context_length > 0 ? m.context_length : undefined),
335
+ })).filter((m) => m.id);
336
+ models.sort((a, b) => a.id.localeCompare(b.id));
337
+ return { ok: true, source: 'live', count: models.length, models, keyFound: Boolean(apiKey) };
338
+ } catch (error) {
339
+ const reason = error && error.name === 'AbortError' ? '连接超时(15 秒)' : String((error && error.message) || error);
340
+ return { ok: false, reason: '无法访问 NVIDIA API:' + reason, source: 'builtin', models: BUILTIN_MODELS };
341
+ } finally {
342
+ clearTimeout(timer);
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Probe one model with a streaming completion call. Availability is decided by
348
+ * the FIRST response byte, not the full completion — thinking models can take
349
+ * a long time to finish, but their first chunk arrives in seconds. The stream
350
+ * is aborted as soon as the first byte lands.
351
+ */
352
+ async function probeStreaming(id, apiKey, maxTokens, timeoutMs) {
353
+ const controller = new AbortController();
354
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
355
+ try {
356
+ const headers = { 'content-type': 'application/json', accept: 'text/event-stream' };
357
+ if (apiKey) headers.authorization = 'Bearer ' + apiKey;
358
+ const response = await fetch(NIM_COMPLETIONS_URL, {
359
+ method: 'POST',
360
+ headers,
361
+ signal: controller.signal,
362
+ body: JSON.stringify({
363
+ model: id,
364
+ messages: [{ role: 'user', content: 'ping' }],
365
+ max_tokens: maxTokens,
366
+ stream: true,
367
+ }),
368
+ });
369
+ if (!response.ok) {
370
+ return { kind: 'http-error', response };
371
+ }
372
+ if (!response.body || typeof response.body.getReader !== 'function') {
373
+ // No streaming body support: a 200 still means the endpoint accepted the model.
374
+ return { kind: 'ok-no-stream' };
375
+ }
376
+ const reader = response.body.getReader();
377
+ try {
378
+ const first = await reader.read();
379
+ if (first && first.done) {
380
+ return { kind: 'ok-no-stream' };
381
+ }
382
+ return { kind: 'ok-stream' };
383
+ } finally {
384
+ try { reader.releaseLock(); } catch { /* the abort below already tore the stream down */ }
385
+ controller.abort();
386
+ }
387
+ } catch (error) {
388
+ return { kind: 'network-error', error };
389
+ } finally {
390
+ clearTimeout(timer);
391
+ }
392
+ }
393
+
394
+ /** Extract NVIDIA's error message from a failed response, best-effort. */
395
+ async function extractErrorHint(response) {
396
+ try {
397
+ const errBody = await response.json();
398
+ const msg = errBody && errBody.detail ? String(errBody.detail) : (errBody && errBody.message ? String(errBody.message) : '');
399
+ return msg ? ':' + msg.slice(0, 160) : '';
400
+ } catch {
401
+ return '';
402
+ }
403
+ }
404
+
405
+ /**
406
+ * Probe one model with a real completion call. Thinking/reasoning models
407
+ * reject tiny output budgets, so the first attempt uses max_tokens=1024 and
408
+ * a 400/422 response retries once with a larger budget before declaring fail.
409
+ * Availability is confirmed by the first streamed byte, so slow thinkers are
410
+ * not misjudged as timeouts.
411
+ */
412
+ async function testNvidiaModel(id) {
413
+ if (isNonChatModel(id)) {
414
+ return { id, status: 'skip', detail: '非对话模型(embed/rerank 等),未试调用' };
415
+ }
416
+ try {
417
+ const apiKey = await resolveKeyFromContext();
418
+ let probe = await probeStreaming(id, apiKey, 1024, 30000);
419
+ if (probe.kind === 'http-error' && (probe.response.status === 400 || probe.response.status === 422)) {
420
+ const firstHint = await extractErrorHint(probe.response);
421
+ probe = await probeStreaming(id, apiKey, 8192, 45000);
422
+ if (probe.kind === 'ok-stream' || probe.kind === 'ok-no-stream') {
423
+ return { id, status: 'ok', detail: '试调用成功(需较大输出预算)' };
424
+ }
425
+ if (probe.kind === 'http-error') {
426
+ const hint = (await extractErrorHint(probe.response)) || firstHint;
427
+ const map = { 401: '鉴权失败(401)——需要有效的 NVIDIA API Key', 403: '无权限(403)——当前密钥无权调用该模型', 404: '模型不可用(404)——端点不接受该模型', 429: '限流(429)——请求过于频繁或配额耗尽' };
428
+ const known = map[probe.response.status];
429
+ return { id, status: 'fail', detail: (known || '调用失败(HTTP ' + probe.response.status + ')') + hint };
430
+ }
431
+ const abortRetry = probe.error && probe.error.name === 'AbortError';
432
+ return { id, status: 'fail', detail: abortRetry ? '首包超时(45 秒无响应)' : '网络错误:' + String((probe.error && probe.error.message) || probe.error) };
433
+ }
434
+ if (probe.kind === 'ok-stream') {
435
+ return { id, status: 'ok', detail: '试调用成功(流式首包确认)' };
436
+ }
437
+ if (probe.kind === 'ok-no-stream') {
438
+ return { id, status: 'ok', detail: '端点返回 200(无流式数据)' };
439
+ }
440
+ if (probe.kind === 'http-error') {
441
+ const hint = await extractErrorHint(probe.response);
442
+ const map = {
443
+ 401: '鉴权失败(401)——需要有效的 NVIDIA API Key',
444
+ 403: '无权限(403)——当前密钥无权调用该模型',
445
+ 404: '模型不可用(404)——端点不接受该模型',
446
+ 429: '限流(429)——请求过于频繁或配额耗尽',
447
+ };
448
+ const known = map[probe.response.status];
449
+ return { id, status: 'fail', detail: (known || '调用失败(HTTP ' + probe.response.status + ')') + hint };
450
+ }
451
+ const abortFirst = probe.error && probe.error.name === 'AbortError';
452
+ return { id, status: 'fail', detail: abortFirst ? '首包超时(30 秒无响应)' : '网络错误:' + String((probe.error && probe.error.message) || probe.error) };
453
+ } catch (error) {
454
+ return { id, status: 'fail', detail: '网络错误:' + String((error && error.message) || error) };
455
+ }
456
+ }
457
+
458
+ /** Read and parse a bounded JSON body; empty or malformed bodies yield {}. */
459
+ async function readJsonBody(request) {
460
+ const reader = request && request.body && request.body.getReader ? request.body.getReader() : undefined;
461
+ if (!reader) return {};
462
+ const chunks = [];
463
+ let size = 0;
464
+ try {
465
+ for (;;) {
466
+ const { done, value } = await reader.read();
467
+ if (done) break;
468
+ size += value.byteLength;
469
+ if (size > 65536) { await reader.cancel(); return {}; }
470
+ chunks.push(value);
471
+ }
472
+ } catch {
473
+ return {};
474
+ }
475
+ const bytes = new Uint8Array(size);
476
+ let offset = 0;
477
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
478
+ try {
479
+ const text = new TextDecoder().decode(bytes);
480
+ const parsed = JSON.parse(text);
481
+ return parsed && typeof parsed === 'object' ? parsed : {};
482
+ } catch {
483
+ return {};
484
+ }
485
+ }
486
+
487
+ /** The credential reference this panel manages (matches the llm-pi-ai nvidia route). */
488
+ const NVIDIA_KEY_REF = 'NVIDIA_API_KEY';
489
+
490
+ /* ───────────────────────────── NVIDIA 模型组(自愈式故障转移) ───────────────────────────── */
491
+
492
+ /**
493
+ * 组内健康登记表(熔断器)。进程级单例:所有会话共享同一份模型健康视图,
494
+ * 这样一个会话把某个模型判定为不可用后,其它会话也会短路跳过它。
495
+ */
496
+ const groupHealth = createHealthRegistry({ failThreshold: 2, baseCooldownMs: 20000, maxCooldownMs: 300000 });
497
+
498
+ /**
499
+ * 调用日志持久化文件(放在 profile 目录而非插件目录):市场重装会替换 node_modules
500
+ * 里的插件实体目录、放到那里会跟着丢;profile 目录稳定。无 DSH_PROFILE_DIR 时返回空,
501
+ * 静默降级为纯内存(便于测试与非 DSH 环境)。
502
+ */
503
+ function defaultUsageFilePath() {
504
+ const dir = process.env.DSH_PROFILE_DIR;
505
+ if (!dir) return '';
506
+ return dir.replace(/\/+$/, '') + '/nvidia-usage.json';
507
+ }
508
+
509
+ /** 文件型 storage(ESM 用动态 import):全量快照覆盖写,读写失败一律静默。 */
510
+ function makeFileStorage() {
511
+ // Never touch the real profile usage file while running under `node --test`
512
+ // (smoke tests exercise apply()/stream and would otherwise pollute it).
513
+ if (process.env.NODE_TEST_CONTEXT) return null;
514
+ const file = defaultUsageFilePath();
515
+ if (!file) return null;
516
+ return {
517
+ async load() {
518
+ try {
519
+ const fs = await import('node:fs/promises');
520
+ return JSON.parse(await fs.readFile(file, 'utf8'));
521
+ } catch { return null; }
522
+ },
523
+ async save(data) {
524
+ try {
525
+ const fs = await import('node:fs/promises');
526
+ const tmp = file + '.tmp';
527
+ await fs.writeFile(tmp, JSON.stringify(data), 'utf8');
528
+ await fs.rename(tmp, file); // atomic replace
529
+ } catch { /* best-effort */ }
530
+ },
531
+ };
532
+ }
533
+
534
+ /** 当日调用用量登记表(进程级单例):模型组每次尝试都记一条,供面板「调用日志」展示。 */
535
+ const groupUsage = createUsageRegistry({ retentionDays: 7, maxLogPerDay: 200, storage: makeFileStorage() });
536
+
537
+ /** 组运行参数(内存态,可被 setGroupConfig 覆盖)。 */
538
+ const groupConfig = {
539
+ firstByteTimeoutMs: 15000,
540
+ firstTextTimeoutMs: 30000,
541
+ preferredModel: '',
542
+ autoRefreshMs: 300000,
543
+ };
544
+
545
+ /**
546
+ * 输入框 dock 徽标的共享状态(进程级内存,重启归零)。
547
+ * 记录最近一次真正产出正文的成员、最近一次切换来源/时间、累计切换次数,
548
+ * 由 buildGroupAdapter 的 onAttempt / onFailover 更新,route `dockStatus` 暴露给 client。
549
+ */
550
+ const dockGroupState = {
551
+ sessionId: null,
552
+ memberId: '',
553
+ memberName: '',
554
+ switchFrom: '',
555
+ switchAt: 0,
556
+ switchCount: 0,
557
+ updatedAt: 0,
558
+ };
559
+
560
+ /** 成员的短友好名(优先配置里的 name,否则取 id 最后一段)。 */
561
+ function friendlyMemberName(member) {
562
+ if (!member) return '';
563
+ if (member.name) return String(member.name);
564
+ const id = String(member.id || '');
565
+ const tail = id.split('/').pop();
566
+ return tail || id;
567
+ }
568
+
569
+ /**
570
+ * 自动发现:最近一次实时检测到的模型(面板点「检测」、configure 成功或后台自动刷新时更新)。
571
+ * 组成员解析顺序:已配置模型 → 最近检测到的对话模型 → 内置种子。
572
+ */
573
+ let lastDetectedModels = [];
574
+
575
+ /**
576
+ * 内置“种子”组成员:都是 NVIDIA 官方已验证可流式返回的对话模型,
577
+ * 让模型组在用户尚未「一键配置」时也能立即工作(自愈开箱即用)。
578
+ */
579
+ const AUTO_SEED_MODELS = [
580
+ { id: 'nvidia/nemotron-3.5-lightning-30b-a3b', name: 'Nemotron 3.5 Lightning 30B', description: 'NVIDIA 官方轻量高速 MoE', inputModalities: ['text'] },
581
+ { id: 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning', name: 'Nemotron 3 Nano Omni 30B', description: 'NVIDIA 官方全模态模型', inputModalities: ['text', 'image'] },
582
+ { id: 'nvidia/nemotron-3-ultra-550b-a55b', name: 'Nemotron 3 Ultra 550B', description: 'NVIDIA 官方超大参数模型', inputModalities: ['text'] },
583
+ { id: 'deepseek-ai/deepseek-v4.1-flash', name: 'DeepSeek V4.1 Flash', description: 'DeepSeek 高速长上下文', inputModalities: ['text', 'image'] },
584
+ ];
585
+
586
+ /** 把一组模型条目(id/name/description)规整成组成员形态。 */
587
+ function normalizeGroupMembers(list) {
588
+ return (Array.isArray(list) ? list : []).map((m) => ({
589
+ id: String(m.id || ''),
590
+ name: String(m.name || m.id || ''),
591
+ description: String(m.description || ''),
592
+ inputModalities: Array.isArray(m.input) ? m.input : (Array.isArray(m.inputModalities) ? m.inputModalities : (/vision|vl|omni|diffusion|image/i.test(String(m.id || '')) ? ['text', 'image'] : ['text'])),
593
+ // 组成员也不再用「未知即 128K」:优先上游值/推断值,再没有就留 null(不虚假声明)。
594
+ contextWindow: Number.isFinite(m.contextWindow) ? m.contextWindow : (Number.isFinite(m.upstreamCtx) ? m.upstreamCtx : inferContextWindow(m.id)),
595
+ maxTokens: Number.isFinite(m.maxTokens) ? m.maxTokens : null,
596
+ })).filter((m) => m.id && !isNonChatModel(m.id));
597
+ }
598
+
599
+ /** 解析当前组合成员:已配置 > 最近检测 > 内置种子(自动发现,开箱即用)。 */
600
+ async function resolveGroupMembers(ctx) {
601
+ const configured = await readNvidiaConfigModels(ctx);
602
+ if (configured && configured.length) return configured;
603
+ const detected = normalizeGroupMembers(lastDetectedModels);
604
+ if (detected.length) return detected;
605
+ return normalizeGroupMembers(AUTO_SEED_MODELS);
606
+ }
607
+
608
+ /** 从 llm-pi-ai 的 nvidia 供应商配置里读出当前组成员(与 configure 写入的模型列表同源)。 */
609
+ async function readNvidiaConfigModels(ctx) {
610
+ const configEditor = await withConfigEditor(ctx, (editor) => editor);
611
+ if (!configEditor) return null;
612
+ let entries;
613
+ try { entries = configEditor.entries(); } catch { return null; }
614
+ if (!Array.isArray(entries)) return null;
615
+ let configs = [];
616
+ try { configs = configEditor.configuration(); } catch { configs = []; }
617
+ let llmHit = (Array.isArray(configs) ? configs : []).find((c) => c && isLlmPiAiEntry(c.entry)) || null;
618
+ if (!llmHit) {
619
+ const llmEntry = entries.find(isLlmPiAiEntry);
620
+ if (llmEntry) llmHit = { entry: llmEntry, override: llmEntry.options && llmEntry.options.config };
621
+ }
622
+ const nvidia = llmHit && llmHit.override && llmHit.override.providers && llmHit.override.providers.nvidia;
623
+ const models = nvidia && Array.isArray(nvidia.models) ? nvidia.models : [];
624
+ return models.map((m) => {
625
+ const declared = Number.isFinite(m.contextWindow) ? m.contextWindow : (Number.isFinite(m.context) ? m.context : null);
626
+ // 旧版「一键配置」把所有模型写成 131072;这类遗留值按模型族自愈为更合理的窗口,
627
+ // 避免 pi-ai 因声明过小而把正常应答误判成上下文溢出。
628
+ const contextWindow = (declared && declared !== LEGACY_CONTEXT_WINDOW)
629
+ ? declared
630
+ : inferContextWindow(m.id, declared === LEGACY_CONTEXT_WINDOW ? undefined : declared);
631
+ return {
632
+ id: String(m.id || ''),
633
+ name: String(m.name || m.id || ''),
634
+ description: String(m.description || ''),
635
+ inputModalities: Array.isArray(m.input) ? m.input : (m.inputModalities || ['text']),
636
+ contextWindow,
637
+ maxTokens: Number.isFinite(m.maxTokens) ? m.maxTokens : null,
638
+ };
639
+ }).filter((m) => m.id && !isNonChatModel(m.id));
640
+ }
641
+
642
+ /** 取得一个会话对象(best-effort,用于把故障转移事件写进会话投影)。 */
643
+ function sessionFor(ctx, sessionId) {
644
+ try {
645
+ const sessions = ctx.get ? ctx.get('sessions') : undefined;
646
+ if (!sessions || typeof sessions.get !== 'function' || !sessionId) return null;
647
+ return sessions.get(sessionId) || null;
648
+ } catch {
649
+ return null;
650
+ }
651
+ }
652
+
653
+ // —— 会话事件写入:只使用 harness 官方的 plugin record API ——
654
+ // 背景:session.append() 无法写 ignorable 标记。用它写 harness 词表外的
655
+ // 类型(如 nvidia-group/*)会让会话日志下次加载时被持久化层拒绝:
656
+ // "contains event type ... unknown to this harness and not marked ignorable"
657
+ // appendPluginRecord() 写的 plugin: 记录会自动带 ignorable:true,未知
658
+ // 类型可被安全跳过,不会再把整段会话历史卡死。
659
+ const GROUP_RECORD_PROBE = 'plugin:dsh-nvidia-models-panel/probe';
660
+ const GROUP_RECORD_FAILOVER = 'plugin:dsh-nvidia-models-panel/failover';
661
+ let dshSessionApi; // undefined=未加载;null=不可用;对象={ appendPluginRecord }
662
+ function getSessionApi() {
663
+ if (dshSessionApi !== undefined) return Promise.resolve(dshSessionApi);
664
+ return import('@deepseek-ai/dsh-session').then(
665
+ (mod) => (dshSessionApi = typeof mod?.appendPluginRecord === 'function' ? mod : null),
666
+ () => (dshSessionApi = null),
667
+ );
668
+ }
669
+
670
+ /** 把一条组事件作为 plugin record 追加进会话(best-effort;失败不影响主流程)。 */
671
+ function appendGroupEvent(ctx, sessionId, type, data) {
672
+ try {
673
+ const session = sessionFor(ctx, sessionId);
674
+ if (!session) return;
675
+ // 旧 harness 没有 appendPluginRecord 时宁可不写,绝不退回
676
+ // session.append() 写不可忽略的未知类型(那会再次损坏会话)。
677
+ void getSessionApi().then((api) => {
678
+ if (!api || typeof api.appendPluginRecord !== 'function') return;
679
+ try { api.appendPluginRecord(session, type, data); } catch { /* best-effort */ }
680
+ });
681
+ } catch {
682
+ // 会话不可用时,看板仍能靠 groupStatus 的实时快照工作。
683
+ }
684
+ }
685
+
686
+ /** 没有 Key / 凭据失效时给出的统一可读提示。 */
687
+ const NO_KEY_MESSAGE = 'NVIDIA API Key 未配置或已失效,请在 NVIDIA 模型面板顶部保存 Key 后重试。';
688
+
689
+ /**
690
+ * 包装 llm.stream:把上游的「缺凭据 / 401 / 403」错误翻译成带 NO_API_KEY 码的
691
+ * 友好失败。这类错误对所有成员都一样,group.js 会识别为致命错误直接停止故障转移。
692
+ */
693
+ function translateKeyError(failure) {
694
+ if (!failure || typeof failure !== 'object') return failure;
695
+ const code = String(failure.code || '');
696
+ const status = failure.status;
697
+ const msg = String(failure.message || '');
698
+ const isKeyIssue = code === 'MISSING_CREDENTIAL' || code === 'NO_API_KEY'
699
+ || status === 401 || status === 403
700
+ || /api.?key|credential|unauthoriz|authentication|invalid.?token/i.test(msg);
701
+ if (!isKeyIssue) return failure;
702
+ return { code: 'NO_API_KEY', message: NO_KEY_MESSAGE, status };
703
+ }
704
+
705
+ function streamChildWithFriendlyKeyErrors(llm, childOptions) {
706
+ const source = llm.stream(childOptions);
707
+ return (async function* () {
708
+ try {
709
+ for await (const chunk of source) {
710
+ // finish error 块:翻译其 failure。
711
+ if (chunk && chunk.type === 'finish' && chunk.reason && (chunk.reason.kind === 'error' || chunk.reason.kind === 'aborted')) {
712
+ const failure = translateKeyError(chunk.reason.failure);
713
+ if (failure !== chunk.reason.failure) {
714
+ yield { ...chunk, reason: { ...chunk.reason, failure } };
715
+ continue;
716
+ }
717
+ }
718
+ yield chunk;
719
+ }
720
+ } catch (error) {
721
+ // 抛出的错误里也可能是缺凭据。
722
+ const failure = translateKeyError(error && typeof error === 'object'
723
+ ? { code: error.code, status: error.status, message: error.message }
724
+ : { message: String(error) });
725
+ if (failure && failure.code === 'NO_API_KEY') {
726
+ yield { type: 'finish', reason: { kind: 'error', failure } };
727
+ } else {
728
+ throw error;
729
+ }
730
+ }
731
+ })();
732
+ }
733
+
734
+ /** 构造“模型组”适配器:内部按健康度顺序把请求转给真正的 nvidia 路由。 */
735
+ function buildGroupAdapter(ctx, llm) {
736
+ return createGroupAdapter({
737
+ groupId: 'nvidia-group',
738
+ groupName: 'NVIDIA 模型组',
739
+ getMembers: async () => {
740
+ const members = await resolveGroupMembers(ctx);
741
+ return members;
742
+ },
743
+ // 用注入到的 llm 服务实例直接调用(外层 ctx 未声明注入 llm,不能在请求时访问 ctx.llm)。
744
+ // 同时把「没有 Key / 凭据失效」的上游错误翻译成可读提示——这种错误对所有成员都一样,
745
+ // 由 group.js 识别为致命错误直接停止故障转移,避免无谓地逐个重试。
746
+ streamChild: (childOptions) => streamChildWithFriendlyKeyErrors(llm, childOptions),
747
+ health: groupHealth,
748
+ firstByteTimeoutMs: () => groupConfig.firstByteTimeoutMs,
749
+ firstTextTimeoutMs: () => groupConfig.firstTextTimeoutMs,
750
+ onAttempt: (info) => {
751
+ // dock 徽标:只在「真正产出正文」的成功尝试里更新当前模型名。
752
+ // info.error 为空且 info.emitted 为真代表该成员给出了可见正文(而非纯思考/失败)。
753
+ if (!info.error && info.emitted && info.member) {
754
+ dockGroupState.memberId = String(info.member.id || '');
755
+ dockGroupState.memberName = friendlyMemberName(info.member);
756
+ dockGroupState.sessionId = info.sessionId || dockGroupState.sessionId;
757
+ dockGroupState.updatedAt = Date.now();
758
+ }
759
+ appendGroupEvent(ctx, info.sessionId, GROUP_RECORD_PROBE, {
760
+ member: info.member.id,
761
+ status: info.error ? 'fail' : 'ok',
762
+ error: info.error ? describeErrorSafe(info.error) : '',
763
+ });
764
+ // 当日用量:每个成员每次尝试都记一条(含失败的、被跳过的切换)。
765
+ try {
766
+ const usage = info.usage || {};
767
+ groupUsage.record({
768
+ sessionId: info.sessionId,
769
+ memberId: info.member && info.member.id,
770
+ ok: !info.error,
771
+ failover: Boolean(info.failover),
772
+ failoverFrom: info.failoverFrom || '',
773
+ firstByteMs: info.firstByteMs,
774
+ elapsedMs: info.elapsedMs,
775
+ inputTokens: usage.inputTokens || usage.promptTokens,
776
+ outputTokens: usage.outputTokens || usage.completionTokens,
777
+ error: info.error ? describeErrorSafe(info.error) : '',
778
+ });
779
+ } catch {
780
+ // 统计失败不影响主流程。
781
+ }
782
+ },
783
+ onFailover: (info) => {
784
+ // dock 徽标:记录「刚从哪个模型切换过来」,供几秒内的橙色高亮提示。
785
+ if (info.from) {
786
+ dockGroupState.switchFrom = friendlyMemberName(info.from);
787
+ dockGroupState.switchAt = Date.now();
788
+ dockGroupState.switchCount += 1;
789
+ dockGroupState.sessionId = info.sessionId || dockGroupState.sessionId;
790
+ }
791
+ appendGroupEvent(ctx, info.sessionId, GROUP_RECORD_FAILOVER, {
792
+ from: info.from ? info.from.id : '',
793
+ to: info.to ? info.to.id : '',
794
+ error: info.error ? describeErrorSafe(info.error) : '',
795
+ exhausted: Boolean(info.exhausted),
796
+ });
797
+ },
798
+ });
799
+ }
800
+
801
+ /** 本地小工具:把错误压成短句(不依赖 group.js 的导出细节)。 */
802
+ function describeErrorSafe(error) {
803
+ if (!error) return 'unknown error';
804
+ if (typeof error === 'string') return error;
805
+ if (error.message) return String(error.message);
806
+ if (error.code) return String(error.code);
807
+ return String(error);
808
+ }
809
+
810
+ /** 组状态快照:组成员 + 健康 + 冷却剩余,供看板渲染。 */
811
+ async function groupStatusSnapshot(ctx) {
812
+ const members = (await resolveGroupMembers(ctx)) || [];
813
+ const snapshot = groupHealth.snapshot(members.map((m) => m.id));
814
+ return {
815
+ ok: true,
816
+ group: 'nvidia-group',
817
+ config: { firstByteTimeoutMs: groupConfig.firstByteTimeoutMs, firstTextTimeoutMs: groupConfig.firstTextTimeoutMs, preferredModel: groupConfig.preferredModel },
818
+ members: members.map((m) => {
819
+ const h = snapshot[m.id] || {};
820
+ return {
821
+ id: m.id,
822
+ name: m.name || m.id,
823
+ description: m.description || '',
824
+ status: h.ok === true ? 'ok' : (h.ok === false ? 'failed' : 'unknown'),
825
+ failCount: h.failCount || 0,
826
+ successCount: h.successCount || 0,
827
+ lastError: h.lastError || '',
828
+ cooldownRemainingMs: groupHealth.cooldownRemainingMs(m.id),
829
+ lastFirstByteMs: typeof h.lastFirstByteMs === 'number' ? h.lastFirstByteMs : null,
830
+ };
831
+ }),
832
+ };
833
+ }
834
+
835
+ /** 输入框 dock 徽标状态:当前实际出正文的模型 + 切换/熔断计数。 */
836
+ async function dockStatusSnapshot(ctx, sessionId) {
837
+ const members = (await resolveGroupMembers(ctx)) || [];
838
+ const cooling = members.filter((m) => groupHealth.cooldownRemainingMs(m.id) > 0).length;
839
+ // 「刚切换」提示保留 6 秒,之后回落到常态绿色。
840
+ const SWITCH_NOTICE_MS = 6000;
841
+ const justSwitched = Boolean(dockGroupState.switchFrom) && (Date.now() - dockGroupState.switchAt < SWITCH_NOTICE_MS);
842
+ // 当前会话已切到别的模型时隐藏徽标:读会话最新 request/header 的 provider。
843
+ // best-effort:读不到 header 时保持原逻辑,避免误隐藏。
844
+ let currentProvider = '';
845
+ let currentModel = '';
846
+ try {
847
+ const session = sessionFor(ctx, sessionId);
848
+ const header = session && typeof session.requestHeader === 'function' ? session.requestHeader() : null;
849
+ if (header && header.config) {
850
+ if (typeof header.config.provider === 'string') {
851
+ currentProvider = header.config.provider;
852
+ }
853
+ if (typeof header.config.model === 'string') {
854
+ currentModel = header.config.model;
855
+ }
856
+ }
857
+ } catch {
858
+ currentProvider = '';
859
+ currentModel = '';
860
+ }
861
+ const usingGroup = !currentProvider || currentProvider === 'nvidia-group';
862
+ // best-effort: 读不到 model 信息时不隐藏;只有明确选了非 auto 的具体模型才隐藏。
863
+ const isAutoModel = !currentModel || isAutoMemberId(currentModel);
864
+ return {
865
+ ok: true,
866
+ active: Boolean(dockGroupState.memberName) && usingGroup && isAutoModel,
867
+ memberName: dockGroupState.memberName || '',
868
+ memberId: dockGroupState.memberId || '',
869
+ switchFrom: justSwitched ? dockGroupState.switchFrom : '',
870
+ switchCount: dockGroupState.switchCount || 0,
871
+ cooldownCount: cooling,
872
+ updatedAt: dockGroupState.updatedAt || 0,
873
+ };
874
+ }
875
+
876
+ /** 探测所有成员(用现有 probeStreaming 快速首包探测),刷新健康表。 */
877
+ async function probeGroup(ctx) {
878
+ const members = (await resolveGroupMembers(ctx)) || [];
879
+ const apiKey = await resolveKeyFromContext();
880
+ const out = [];
881
+ for (const m of members) {
882
+ groupHealth.recordProbeStart(m.id);
883
+ const probe = await probeStreaming(m.id, apiKey, 512, 8000);
884
+ if (probe.kind === 'ok-stream' || probe.kind === 'ok-no-stream') {
885
+ groupHealth.recordSuccess(m.id, null);
886
+ out.push({ id: m.id, status: 'ok' });
887
+ } else {
888
+ const detail = probe.kind === 'http-error'
889
+ ? '调用失败(HTTP ' + probe.response.status + ')'
890
+ : (probe.error && probe.error.name === 'AbortError'
891
+ ? '首包超时(8 秒无响应)'
892
+ : '网络错误:' + String((probe.error && probe.error.message) || probe.error));
893
+ groupHealth.recordFailure(m.id, { message: detail });
894
+ out.push({ id: m.id, status: 'fail', detail });
895
+ }
896
+ appendGroupEvent(ctx, null, GROUP_RECORD_PROBE, { member: m.id, status: out[out.length - 1].status === 'ok' ? 'ok' : 'fail', error: out[out.length - 1].detail || '' });
897
+ }
898
+ return { ok: true, probed: out.length, results: out };
899
+ }
900
+
901
+ /** POST /api/nvidia-models — actions: detect | test | keyStatus | setKey | clearKey | configure | groupStatus | probeGroup | resetGroup | getGroupConfig | setGroupConfig | usageStats | resetUsage | checkUpdate | dockStatus. */
902
+ function createNvidiaModelsRoute(ctx) {
903
+ return {
904
+ path: '/api/nvidia-models',
905
+ methods: ['POST'],
906
+ requestBody: 'buffered',
907
+ fetch: async (request) => {
908
+ const body = await readJsonBody(request);
909
+ const action = body && typeof body.action === 'string' ? body.action : 'detect';
910
+ let result;
911
+ // 需要 Key 的 action 在没有配置 Key 时统一早退,给出一致的可读提示。
912
+ // keyStatus/setKey/clearKey/resetGroup/resetUsage/checkUpdate 不拦(它们本就用于修复无 Key 状态)。
913
+ const NEED_KEY_ACTIONS = new Set(['detect', 'test', 'configure', 'probeGroup', 'groupStatus', 'dockStatus', 'usageStats']);
914
+ if (NEED_KEY_ACTIONS.has(action) && !(await hasNvidiaKey(ctx))) {
915
+ result = { ok: false, code: 'NO_API_KEY', message: '未配置 NVIDIA API Key,请先在面板上方保存后再继续。' };
916
+ } else if (action === 'test' && typeof body.model === 'string' && body.model) {
917
+ result = await testNvidiaModel(body.model);
918
+ } else if (action === 'keyStatus') {
919
+ const info = await withCredentials(ctx, (credentials) => credentials.describe(NVIDIA_KEY_REF));
920
+ result = info && typeof info === 'object'
921
+ ? { configured: Boolean(info.configured), source: info.source || null, writable: info.writable !== false }
922
+ : { configured: false, source: null, writable: false, unavailable: true };
923
+ } else if (action === 'setKey' && typeof body.key === 'string' && body.key.trim()) {
924
+ const key = body.key.trim();
925
+ const saved = await withCredentials(ctx, async (credentials) => {
926
+ await credentials.set(NVIDIA_KEY_REF, key);
927
+ return credentials.describe(NVIDIA_KEY_REF);
928
+ });
929
+ if (!saved || typeof saved !== 'object') {
930
+ result = { saved: false, error: '凭据服务不可用,无法保存' };
931
+ } else if (!saved.configured) {
932
+ result = { saved: false, error: '保存后校验未通过(凭据存储未确认写入)' };
933
+ } else {
934
+ result = { saved: true, source: saved.source || 'stored' };
935
+ }
936
+ } else if (action === 'clearKey') {
937
+ const cleared = await withCredentials(ctx, async (credentials) => {
938
+ await credentials.unset(NVIDIA_KEY_REF);
939
+ return credentials.describe(NVIDIA_KEY_REF);
940
+ });
941
+ result = cleared && typeof cleared === 'object' && !cleared.configured
942
+ ? { cleared: true }
943
+ : { cleared: false, error: '清除失败或凭据服务不可用' };
944
+ } else if (action === 'configure') {
945
+ result = await configureNvidiaModels(ctx, body.results);
946
+ } else if (action === 'groupStatus') {
947
+ result = await groupStatusSnapshot(ctx);
948
+ } else if (action === 'probeGroup') {
949
+ result = await probeGroup(ctx);
950
+ } else if (action === 'resetGroup') {
951
+ if (typeof body.model === 'string' && body.model) groupHealth.reset(body.model);
952
+ else groupHealth.reset();
953
+ result = await groupStatusSnapshot(ctx);
954
+ } else if (action === 'getGroupConfig') {
955
+ result = { ok: true, config: { ...groupConfig } };
956
+ } else if (action === 'setGroupConfig') {
957
+ if (body.config && typeof body.config === 'object') {
958
+ if (Number.isFinite(body.config.firstByteTimeoutMs) && body.config.firstByteTimeoutMs >= 1000) {
959
+ groupConfig.firstByteTimeoutMs = Math.min(120000, Math.round(body.config.firstByteTimeoutMs));
960
+ }
961
+ if (Number.isFinite(body.config.firstTextTimeoutMs) && body.config.firstTextTimeoutMs >= 5000) {
962
+ groupConfig.firstTextTimeoutMs = Math.min(180000, Math.round(body.config.firstTextTimeoutMs));
963
+ }
964
+ if (typeof body.config.preferredModel === 'string') {
965
+ groupConfig.preferredModel = body.config.preferredModel;
966
+ }
967
+ if (Number.isFinite(body.config.autoRefreshMs) && body.config.autoRefreshMs >= 60000) {
968
+ groupConfig.autoRefreshMs = Math.min(3600000, Math.round(body.config.autoRefreshMs));
969
+ }
970
+ }
971
+ result = { ok: true, config: { ...groupConfig } };
972
+ } else if (action === 'usageStats') {
973
+ result = { ok: true, stats: groupUsage.snapshot(typeof body.day === 'string' && body.day ? body.day : undefined) };
974
+ } else if (action === 'resetUsage') {
975
+ if (typeof body.day === 'string' && body.day) groupUsage.reset(body.day);
976
+ else groupUsage.reset();
977
+ result = { ok: true, stats: groupUsage.snapshot() };
978
+ } else if (action === 'checkUpdate') {
979
+ result = await checkUpdate(ctx);
980
+ } else if (action === 'dockStatus') {
981
+ result = await dockStatusSnapshot(ctx, body.sessionId);
982
+ } else {
983
+ result = await detectNvidiaModels();
984
+ if (result && result.source === 'live') lastDetectedModels = normalizeGroupMembers(result.models);
985
+ }
986
+ return new Response(JSON.stringify(result), {
987
+ status: 200,
988
+ headers: { 'content-type': 'application/json' },
989
+ });
990
+ },
991
+ };
992
+ }
993
+
994
+ /** Command: write the NVIDIA model list into the llm-pi-ai nvidia provider. */
995
+ const GITHUB_REPO = 'windxxf/dsh-nvidia-models-panel';
996
+ const GITHUB_RELEASES_URL = 'https://github.com/' + GITHUB_REPO + '/releases';
997
+
998
+ /**
999
+ * 读取 GitHub 远端最新版本。
1000
+ * 首选 raw.githubusercontent.com 的 HEAD/package.json(也是 dshmarket 的判定方式)——
1001
+ * 这个通道不吃 GitHub REST API 的匿名速率限制(每小时 60 次,很容易被耗尽)。
1002
+ * 令牌缓存 30 分钟,避免每次挂载面板都发请求。
1003
+ */
1004
+ let _updateCache = { at: 0, version: null };
1005
+ const UPDATE_CACHE_MS = 30 * 60 * 1000;
1006
+
1007
+ async function fetchLatestVersion() {
1008
+ if (_updateCache.version && Date.now() - _updateCache.at < UPDATE_CACHE_MS) {
1009
+ return _updateCache.version;
1010
+ }
1011
+ let version = null;
1012
+ const url = 'https://raw.githubusercontent.com/' + GITHUB_REPO + '/HEAD/package.json';
1013
+ // 网络间歇性抖动时重试一次(github 443 在本机时断时续)。
1014
+ for (let attempt = 0; attempt < 2 && !version; attempt += 1) {
1015
+ try {
1016
+ const res = await fetch(url, { signal: AbortSignal.timeout(8000) });
1017
+ if (res.ok) {
1018
+ const data = await res.json();
1019
+ if (data && typeof data.version === 'string') version = data.version;
1020
+ }
1021
+ } catch { /* 网络不通,下一轮重试 */ }
1022
+ if (!version && attempt === 0) await new Promise((r) => setTimeout(r, 500));
1023
+ }
1024
+ if (version) _updateCache = { at: Date.now(), version };
1025
+ return version;
1026
+ }
1027
+
1028
+ async function checkUpdate(ctx) {
1029
+ // 获取插件自身版本(尽力而为,失败不阻塞)。
1030
+ let currentVersion = null;
1031
+ try {
1032
+ const pkg = await readOwnPackageJson();
1033
+ if (typeof pkg.version === 'string') currentVersion = pkg.version;
1034
+ } catch { /* 忽略 */ }
1035
+
1036
+ let latestVersion = null;
1037
+ try {
1038
+ latestVersion = await fetchLatestVersion();
1039
+ } catch { /* 忽略 */ }
1040
+ const reachable = Boolean(latestVersion);
1041
+
1042
+ const latestTag = latestVersion ? ('v' + latestVersion.replace(/^v/, '')) : null;
1043
+ const hasUpdate = Boolean(currentVersion && latestVersion && semverGt(latestVersion, currentVersion));
1044
+ const message = hasUpdate
1045
+ ? ('发现新版本 ' + latestTag + ',当前 ' + currentVersion)
1046
+ : (!reachable
1047
+ ? '检查失败:暂时无法连接 GitHub(网络问题),请稍后重试'
1048
+ : '已是最新版本');
1049
+ return {
1050
+ ok: true,
1051
+ currentVersion,
1052
+ latestTag,
1053
+ latestUrl: GITHUB_RELEASES_URL,
1054
+ hasUpdate,
1055
+ reachable,
1056
+ message,
1057
+ };
1058
+ }
1059
+
1060
+ /** 读取插件自身 package.json 的内容(用于读取当前版本号)。 */
1061
+ async function readOwnPackageJson() {
1062
+ const { readFile } = await import('node:fs/promises');
1063
+ const { fileURLToPath } = await import('node:url');
1064
+ // index.js 在 src/ 下,package.json 在上一层;两个候选都试,兼容不同加载布局。
1065
+ const candidates = [
1066
+ fileURLToPath(new URL('../package.json', import.meta.url)),
1067
+ fileURLToPath(new URL('./package.json', import.meta.url)),
1068
+ ];
1069
+ let lastErr;
1070
+ for (const path of candidates) {
1071
+ try {
1072
+ return JSON.parse(await readFile(path, 'utf8'));
1073
+ } catch (err) { lastErr = err; }
1074
+ }
1075
+ throw lastErr || new Error('package.json not found');
1076
+ }
1077
+
1078
+ /** 语义版本比较:v1.3.8 / 1.3.8 / 1.3.8-rc1 等,仅比较数字段。 */
1079
+ function semverGt(a, b) {
1080
+ const norm = (s) => String(s || '').replace(/^v/, '').split(/[.\-]/).map((p) => Number(p) || 0);
1081
+ const x = norm(a), y = norm(b);
1082
+ for (let i = 0; i < Math.max(x.length, y.length); i += 1) {
1083
+ const xi = x[i] || 0, yi = y[i] || 0;
1084
+ if (xi !== yi) return xi > yi;
1085
+ }
1086
+ return false;
1087
+ }
1088
+
1089
+ export function apply(ctx) {
1090
+ const disposers = [];
1091
+
1092
+ // 每次加载 / 重载插件时清空上一次残留的模型健康(失败计数 + 熔断冷却)。
1093
+ // 健康表是进程级单例缓存:旧版本(多模态硬过滤)可能把一批本来可用的成员
1094
+ // 反复判失败、推进熔断,重载后如果沿用旧状态,刚修好的成员仍会被跳过。
1095
+ // 清零是安全的——真正的上游不可用仍由 FAILOVER 与看板实时探测照常兜底。
1096
+ try { groupHealth.reset(); } catch { /* 忽略 */ }
1097
+
1098
+ // 同步清空 dock 徽标状态:重载后没有"当前模型"可报,徽标回落为不显示,
1099
+ // 直到模型组下一次真正产出正文才重新点亮。
1100
+ try {
1101
+ dockGroupState.sessionId = null;
1102
+ dockGroupState.memberId = '';
1103
+ dockGroupState.memberName = '';
1104
+ dockGroupState.switchFrom = '';
1105
+ dockGroupState.switchAt = 0;
1106
+ dockGroupState.switchCount = 0;
1107
+ dockGroupState.updatedAt = 0;
1108
+ } catch { /* 忽略 */ }
1109
+
1110
+ // 从磁盘读回调用日志快照(重载/重启不丢)。fire-and-forget:hydrate 内部已
1111
+ // 全量 try/catch,失败静默;不阻塞插件激活。
1112
+ try { Promise.resolve(groupUsage.hydrate()).catch(() => {}); } catch { /* 忽略 */ }
1113
+
1114
+ // Slash-command handlers run against an agent invocation ({ agent, rawInput }),
1115
+ // NOT the plugin context — so both handlers close over the plugin ctx instead.
1116
+ disposers.push(ctx.commands.register({
1117
+ name: 'nvidia-models-detect',
1118
+ title: '检测 NVIDIA 可用模型',
1119
+ description: '实时查询 NVIDIA NIM API,列出当前可用模型及简介',
1120
+ handler: async () => {
1121
+ const result = await detectNvidiaModels();
1122
+ const head = result.source === 'live'
1123
+ ? '实时检测到 ' + result.count + ' 个可用模型(来自 NVIDIA API):'
1124
+ : 'NVIDIA API 不可达(' + result.reason + '),以下为内置目录:';
1125
+ const list = result.models.map((m) => '- ' + m.name + ' (' + m.id + '):' + m.description).join('\n');
1126
+ return { kind: 'success', text: head + '\n\n' + list + '\n\n运行 /nvidia-models-configure 可将模型写入 llm-pi-ai 的 nvidia 供应商。' };
1127
+ },
1128
+ }));
1129
+
1130
+ disposers.push(ctx.commands.register({
1131
+ name: 'nvidia-models-configure',
1132
+ title: '配置 NVIDIA 模型到设置',
1133
+ description: '把检测到的模型批量写入 llm-pi-ai 的 nvidia 供应商模型列表',
1134
+ handler: async () => {
1135
+ const result = await configureNvidiaModels(ctx);
1136
+ return result.ok
1137
+ ? { kind: 'success', text: result.message }
1138
+ : { kind: 'error', text: result.error };
1139
+ },
1140
+ }));
1141
+
1142
+ // Install the credential-resolver closure: stored key first (it outranks the
1143
+ // environment by design), then the plain environment variable.
1144
+ resolveKeyFromContext = async () => {
1145
+ try {
1146
+ const resolved = await new Promise((done) => {
1147
+ ctx.inject(['credentials'], (scoped) => {
1148
+ try {
1149
+ done((async () => {
1150
+ const credentials = scoped.credentials;
1151
+ try {
1152
+ const hit = await credentials.resolve('NVIDIA_API_KEY');
1153
+ if (hit && typeof hit.value === 'string' && hit.value.trim()) return hit.value.trim();
1154
+ } catch {
1155
+ // The reference form may be rejected; fall through to env.
1156
+ }
1157
+ return '';
1158
+ })());
1159
+ } catch {
1160
+ done();
1161
+ }
1162
+ });
1163
+ });
1164
+ if (resolved) return resolved;
1165
+ } catch {
1166
+ // Credential seam unavailable; env fallback below.
1167
+ }
1168
+ const fromEnv = process.env.NVIDIA_API_KEY;
1169
+ return fromEnv && fromEnv.trim() ? fromEnv.trim() : '';
1170
+ };
1171
+
1172
+ ctx.inject(['connection'], (scoped) => {
1173
+ const connection = scoped.connection;
1174
+ const unregisterRoute = connection.fetch.register(createNvidiaModelsRoute(ctx), 'nvidia-models: /api/nvidia-models route');
1175
+ scoped.effect(() => unregisterRoute, 'nvidia-models: /api route');
1176
+ });
1177
+
1178
+ // 注册「NVIDIA 模型组」LLM 适配器(provider = nvidia-group)。
1179
+ // 用可选注入:没有 llm 服务时插件其余功能照常可用,仅模型组不可用。
1180
+ ctx.inject(['llm'], (scoped) => {
1181
+ try {
1182
+ const llm = scoped.llm;
1183
+ const adapter = buildGroupAdapter(ctx, llm);
1184
+ // registerAdapter 自身以 ctx.effect 挂载,随 fiber 释放,无需手动注销。
1185
+ llm.registerAdapter(['nvidia-group'], adapter);
1186
+ } catch (error) {
1187
+ // 适配器注册失败不应拖垮插件;面板会显示模型组不可用。
1188
+ try { console.warn('[nvidia-models-panel] 注册 nvidia-group 适配器失败:' + describeErrorSafe(error)); } catch { /* 忽略 */ }
1189
+ }
1190
+ });
1191
+
1192
+ // 注册会话投影 nvidiaHealth:把故障转移/探测事件折成看板状态。
1193
+ ctx.inject(['sessionProjections'], (scoped) => {
1194
+ try {
1195
+ const registry = scoped.sessionProjections;
1196
+ // register() 是 thenable,且内部以 ctx.effect 挂载(随 fiber 释放)。
1197
+ Promise.resolve(registry.register({
1198
+ key: 'nvidiaHealth',
1199
+ stateVersion: 1,
1200
+ stateSchema: makeSchema(),
1201
+ init: () => createGroupState(),
1202
+ apply: (state, event) => foldGroupEvent(state, event),
1203
+ wire: {
1204
+ viewSchema: makeSchema(),
1205
+ view: (state) => state,
1206
+ summary: false,
1207
+ },
1208
+ })).catch((error) => {
1209
+ try { console.warn('[nvidia-models-panel] 注册 nvidiaHealth 投影失败:' + describeErrorSafe(error)); } catch { /* 忽略 */ }
1210
+ });
1211
+ } catch (error) {
1212
+ try { console.warn('[nvidia-models-panel] 注册 nvidiaHealth 投影失败:' + describeErrorSafe(error)); } catch { /* 忽略 */ }
1213
+ }
1214
+ });
1215
+
1216
+ // 自动发现守护:周期性静默拉取 NVIDIA 模型目录,刷新 lastDetectedModels,
1217
+ // 让「NVIDIA 模型组」自动跟上新上架/下架的模型,无需用户手动点「检测」。
1218
+ // 仅在已有 API Key 时才探测;失败静默(不打扰用户),退避由定时器自然承担。
1219
+ const startAutoDiscovery = () => {
1220
+ let stopped = false;
1221
+ let timer = null;
1222
+ const tick = async () => {
1223
+ if (stopped) return;
1224
+ try {
1225
+ const key = await resolveKeyFromContext();
1226
+ if (key) {
1227
+ const detection = await detectNvidiaModels();
1228
+ if (detection && detection.source === 'live') {
1229
+ lastDetectedModels = normalizeGroupMembers(detection.models);
1230
+ }
1231
+ }
1232
+ } catch {
1233
+ // 自动发现是尽力而为,失败静默。
1234
+ }
1235
+ if (stopped) return;
1236
+ const ms = Math.max(60000, Number(groupConfig.autoRefreshMs) || 300000);
1237
+ timer = setTimeout(tick, ms);
1238
+ if (timer && typeof timer.unref === 'function') timer.unref();
1239
+ };
1240
+ // 首次延迟 20s,避开启动高峰。
1241
+ timer = setTimeout(tick, 20000);
1242
+ if (timer && typeof timer.unref === 'function') timer.unref();
1243
+ return () => { stopped = true; if (timer) clearTimeout(timer); };
1244
+ };
1245
+ disposers.push(startAutoDiscovery());
1246
+
1247
+ return () => {
1248
+ resolveKeyFromContext = async () => '';
1249
+ for (const dispose of disposers) {
1250
+ if (typeof dispose === 'function') dispose();
1251
+ }
1252
+ };
1253
+ }