pi-web-ui 0.111.0 → 0.113.0

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 (88) hide show
  1. package/CHANGELOG.md +92 -2
  2. package/bin/frp-manager.mjs +9 -2
  3. package/bin/pi-web-ui.mjs +325 -45
  4. package/dist/server/agent-service-daemon.js +29 -4
  5. package/dist/server/agent-service.js +1527 -510
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/canvas/canvas-agent-tool.js +8 -0
  11. package/dist/server/canvas/canvas-orchestrator.js +128 -22
  12. package/dist/server/canvas/pstack-skills-data.js +498 -0
  13. package/dist/server/client-state.js +28 -0
  14. package/dist/server/delegate-mode.js +6 -3
  15. package/dist/server/delegate-task.js +18 -3
  16. package/dist/server/dispatch-domain-handlers.js +39 -11
  17. package/dist/server/dsh/dsh-agent-service.js +294 -15
  18. package/dist/server/dsh/dsh-serialize.js +1 -1
  19. package/dist/server/durable/durable-driver.js +112 -107
  20. package/dist/server/durable/durable-event-projector.js +253 -0
  21. package/dist/server/durable/durable-loader.js +1 -14
  22. package/dist/server/durable/durable-models.js +107 -0
  23. package/dist/server/durable/index.js +0 -4
  24. package/dist/server/engine-probe.js +111 -48
  25. package/dist/server/eval-tool.js +28 -3
  26. package/dist/server/goal-service.js +7 -0
  27. package/dist/server/index.js +371 -57
  28. package/dist/server/json-utils.js +57 -0
  29. package/dist/server/marker-service.js +8 -0
  30. package/dist/server/message-window.js +43 -10
  31. package/dist/server/model-admin.js +247 -163
  32. package/dist/server/model-resolver.js +66 -44
  33. package/dist/server/plan-manager.js +3 -6
  34. package/dist/server/plugin-api-catalog.js +1 -0
  35. package/dist/server/plugin-assets.js +238 -0
  36. package/dist/server/plugin-facilities.js +22 -0
  37. package/dist/server/plugin-ui-slots.js +1 -0
  38. package/dist/server/plugins.js +209 -11
  39. package/dist/server/preset-fields.js +25 -1
  40. package/dist/server/preset-share.js +5 -2
  41. package/dist/server/prompt-assembler.js +2 -1
  42. package/dist/server/prompt-composer.js +18 -8
  43. package/dist/server/protocol-version.js +1 -1
  44. package/dist/server/queue-utils.js +156 -0
  45. package/dist/server/remote-ssh-service.js +110 -12
  46. package/dist/server/sdk-builtin-extensions.js +85 -0
  47. package/dist/server/serialize.js +1 -1
  48. package/dist/server/server-config.js +66 -0
  49. package/dist/server/session-parser.js +49 -13
  50. package/dist/server/session-search.js +4 -3
  51. package/dist/server/settings-service.js +74 -53
  52. package/dist/server/setup-page.js +632 -0
  53. package/dist/server/skill-discovery.js +361 -59
  54. package/dist/server/skill-maintenance.js +231 -0
  55. package/dist/server/skill-tool.js +32 -3
  56. package/dist/server/soft-cap.js +30 -6
  57. package/dist/server/subagent-helpers.js +22 -1
  58. package/dist/server/subagent-notify.js +93 -0
  59. package/dist/server/subagent-security-gate.js +282 -0
  60. package/dist/server/subagent-templates.js +8 -0
  61. package/dist/server/subagents.js +390 -48
  62. package/dist/server/terminals.js +196 -8
  63. package/dist/server/text-quote.js +61 -0
  64. package/dist/server/tool-approval.js +63 -4
  65. package/dist/server/tool-guards.js +208 -0
  66. package/dist/server/tool-host-factories.js +48 -10
  67. package/dist/server/tool-manager.js +106 -28
  68. package/dist/server/tool-overrides.js +21 -11
  69. package/dist/server/universal/driver-base.js +8 -0
  70. package/dist/server/universal/drivers/claude-code.js +116 -7
  71. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  72. package/dist/server/universal/index.js +0 -1
  73. package/dist/server/universal/universal-session.js +106 -10
  74. package/dist/server/worktree-service.js +189 -1
  75. package/docs/dsh-engine.md +1 -5
  76. package/package.json +1 -1
  77. package/plugin-sdk/client-utils.mjs +192 -5
  78. package/plugin-sdk/index.d.ts +63 -1
  79. package/plugin-sdk/index.mjs +94 -0
  80. package/plugin-sdk/package.json +5 -1
  81. package/plugins/catalog.json +21 -0
  82. package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
  83. package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
  84. package/web/dist/assets/index-BwL7qBh6.css +1 -0
  85. package/web/dist/index.html +11 -2
  86. package/web/dist/sw.js +1 -1
  87. package/web/dist/assets/index-B0ajS__T.js +0 -697
  88. package/web/dist/assets/index-BHik5WGG.css +0 -1
@@ -136,10 +136,18 @@ export class MarkerService {
136
136
  .then(() => this.processAssistantText(conversationId, text))
137
137
  .catch((e) => {
138
138
  console.error("[markers] handleAssistantText failed:", e);
139
+ })
140
+ .finally(() => {
141
+ if (this.chains.get(conversationId) === next) {
142
+ this.chains.delete(conversationId);
143
+ }
139
144
  });
140
145
  this.chains.set(conversationId, next);
141
146
  return next;
142
147
  }
148
+ clearConversation(conversationId) {
149
+ this.chains.delete(conversationId);
150
+ }
143
151
  async processAssistantText(conversationId, text) {
144
152
  if (!text || !this.settings.markersEnabled)
145
153
  return;
@@ -12,7 +12,7 @@ export const DEFAULT_HISTORY_PAGE = 30;
12
12
  /** 单次翻页上限,防止一条消息把几千条历史一次拉下来。 */
13
13
  const MAX_PAGE = 2000;
14
14
  /** 最多为几个对话保留全量缓存(LRU)—— 引用的是引擎已序列化好的对象,只有指针开销。 */
15
- const MAX_CACHED_CONVERSATIONS = 4;
15
+ const MAX_CACHED_CONVERSATIONS = 64;
16
16
  const OFF_CONFIG = { windowSize: 0, charBudget: 0, pageSize: DEFAULT_HISTORY_PAGE };
17
17
  const DEFAULT_CONFIG = {
18
18
  windowSize: DEFAULT_HISTORY_WINDOW,
@@ -150,19 +150,51 @@ export class MessageWindowTap {
150
150
  }
151
151
  this.send(msg);
152
152
  }
153
+ /**
154
+ * 按需回水:从运行时或存储中恢复某个会话的全量消息基线,
155
+ * 供 LRU 逐出、冷启动或跨连接无快照状态下立即恢复翻页服务能力。
156
+ */
157
+ rehydrate(convId, full, start) {
158
+ const entry = this.entry(convId);
159
+ entry.full = full;
160
+ if (start !== undefined && Number.isFinite(start) && start >= 0) {
161
+ entry.start = Math.min(full.length, start);
162
+ }
163
+ else if (entry.start < 0) {
164
+ entry.start = pickWindowStart(full, this.cfg);
165
+ }
166
+ }
153
167
  /** 客户端往上翻页:把窗口起点往前扩 `count` 条(`all` = 一路拉到最早)。
154
- * `conversationId` 缺省时回退最近一次快照的会话(老客户端兼容);
155
- * 显式传入时只服务该会话——多标签/后台流式会顶掉 `lastConversationId`,
156
- * 若前端明确说自己正在看哪个会话就必须以它为准,避免跨会话串台。 */
157
- loadEarlier(count, all, conversationId) {
158
- const convId = conversationId || this.lastConversationId;
168
+ * - `conversationId`: 会话 ID(缺省回退最近一次快照会话);
169
+ * - `beforeId`: 客户端首条消息的 ID(优先使用该不可变锚点,不受压缩/重试导致的下标漂移影响);
170
+ * - `before`: 客户端当前窗口起点下标(自描述游标,entry 丢失或失忆时作为截断右边界);
171
+ * 返回 boolean: true = 已命中并下发 earlier_messages; false = entry 未命中(调用方可尝试回水)。 */
172
+ loadEarlier(countOrOpts, all, conversationId, beforeId, before) {
173
+ const opts = typeof countOrOpts === "object" && countOrOpts !== null
174
+ ? countOrOpts
175
+ : { count: countOrOpts, all, conversationId, beforeId, before };
176
+ const convId = opts.conversationId || this.lastConversationId;
159
177
  const entry = convId ? this.convs.get(convId) : undefined;
160
178
  if (!entry || !convId)
161
- return;
179
+ return false;
162
180
  const total = entry.full.length;
163
- const page = all ? entry.start : Math.min(MAX_PAGE, Math.max(1, Math.floor(count ?? this.cfg.pageSize) || 1));
164
- const start = all ? 0 : Math.max(0, entry.start - page);
165
- const messages = start < entry.start ? entry.full.slice(start, entry.start) : [];
181
+ // 确定翻页右边界(end):
182
+ // 1. 优先使用不可变消息 ID beforeId 定位(防数组位移);
183
+ // 2. 其次使用客户端自描述下标 before(自描述游标);
184
+ // 3. 最后回退服务端自身记录的 entry.start(若小于 0 则说明未初始化,回退 total)。
185
+ let end = entry.start >= 0 ? entry.start : total;
186
+ if (opts.beforeId) {
187
+ const idx = entry.full.findIndex((m) => m.id === opts.beforeId);
188
+ if (idx >= 0) {
189
+ end = idx;
190
+ }
191
+ }
192
+ else if (typeof opts.before === "number" && Number.isFinite(opts.before) && opts.before >= 0) {
193
+ end = Math.min(total, opts.before);
194
+ }
195
+ const page = opts.all ? end : Math.min(MAX_PAGE, Math.max(1, Math.floor(opts.count ?? this.cfg.pageSize) || 1));
196
+ const start = opts.all ? 0 : Math.max(0, end - page);
197
+ const messages = start < end ? entry.full.slice(start, end) : [];
166
198
  entry.start = start;
167
199
  this.send({
168
200
  type: "earlier_messages",
@@ -171,6 +203,7 @@ export class MessageWindowTap {
171
203
  historyStart: start,
172
204
  historyTotal: total,
173
205
  });
206
+ return true;
174
207
  }
175
208
  /** 取(或建)对话窗口;LRU 超限时淘汰最久未用的那个。 */
176
209
  entry(convId) {
@@ -14,6 +14,7 @@
14
14
  import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
15
15
  import { dirname, join } from "node:path";
16
16
  import { writeJsonAtomicSync } from "./atomic-file.js";
17
+ import { stripJsonComments } from "./json-utils.js";
17
18
  import { enrichBatch } from "./model-enrich.js";
18
19
  import { pick } from "./i18n.js";
19
20
  import { ProviderOAuthFlowManager } from "./provider-oauth-flow.js";
@@ -77,49 +78,6 @@ function atomicWriteCredentialJson(path, data) {
77
78
  /* best-effort (win) */
78
79
  }
79
80
  }
80
- /** Strip // and /* *\/ comments without touching string literals (URLs contain //). */
81
- function stripJsonComments(src) {
82
- let out = "";
83
- let inString = false;
84
- let i = 0;
85
- while (i < src.length) {
86
- const c = src[i];
87
- const next = src[i + 1];
88
- if (inString) {
89
- out += c;
90
- if (c === "\\") {
91
- out += next ?? "";
92
- i += 2;
93
- continue;
94
- }
95
- if (c === '"')
96
- inString = false;
97
- i++;
98
- continue;
99
- }
100
- if (c === '"') {
101
- inString = true;
102
- out += c;
103
- i++;
104
- continue;
105
- }
106
- if (c === "/" && next === "/") {
107
- while (i < src.length && src[i] !== "\n")
108
- i++;
109
- continue;
110
- }
111
- if (c === "/" && next === "*") {
112
- i += 2;
113
- while (i < src.length && !(src[i] === "*" && src[i + 1] === "/"))
114
- i++;
115
- i += 2;
116
- continue;
117
- }
118
- out += c;
119
- i++;
120
- }
121
- return out;
122
- }
123
81
  /** Merge a UI-submitted provider config into the existing models.json entry.
124
82
  *
125
83
  * 表单(`UiProviderConfig`)只承载 UI 认识的字段:provider 级 name/api/baseUrl/
@@ -171,6 +129,12 @@ export function mergeProviderConfigEntry(prevEntry, config, models) {
171
129
  merged.maxTokens = Number(model.maxTokens);
172
130
  else
173
131
  delete merged.maxTokens;
132
+ // thinkingLevelMap:表单带了就覆盖,没带(undefined)= 保留磁盘上的手写映射,
133
+ // 与 api/baseUrl/cost/compat 同语义。注意不能 `else delete`——那会把用户在
134
+ // models.json 里手写的 xhigh/max 映射抹掉,档位又会退回 off…high。
135
+ const thinkingLevelMap = sanitizeThinkingLevelMap(model.thinkingLevelMap);
136
+ if (thinkingLevelMap)
137
+ merged.thinkingLevelMap = thinkingLevelMap;
174
138
  return merged;
175
139
  });
176
140
  const mergedEntry = { ...prevEntry };
@@ -203,11 +167,205 @@ function boolMeta(v) {
203
167
  function strArrMeta(v) {
204
168
  return Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
205
169
  }
170
+ /**
171
+ * 体系化启发式推断模型是否具备推理/深度思考能力:
172
+ * 1. 显式端点元数据优先(reasoning / supports_reasoning / modalities 包含 reasoning);
173
+ * 2. 业界主流推理模型命名特征正则库:
174
+ * - thinking / reasoner / reasoning 显式词
175
+ * - OpenAI o1 / o3 / o4 系列(如 o1, o1-mini, o1-preview, o3-mini, o3-high, o4 等)
176
+ * - DeepSeek R1 / Reasoner 系列(如 deepseek-r1, r1-distill 等)
177
+ * - 阿里千问 QwQ 系列(如 qwq-32b, qwq-32b-preview)
178
+ * - 智谱 GLM-Zero 系列(如 glm-4-zero, glm-zero)
179
+ * - CoT (Chain of Thought) 显式标记
180
+ */
181
+ export function detectReasoningCapability(id, rawMeta) {
182
+ if (!id)
183
+ return false;
184
+ const r = rawMeta ?? {};
185
+ const modalities = strArrMeta(r.modalities) ?? strArrMeta(r.input_modalities);
186
+ if (boolMeta(r.reasoning) === true ||
187
+ boolMeta(r.supports_reasoning) === true ||
188
+ modalities?.includes("reasoning") === true) {
189
+ return true;
190
+ }
191
+ const lower = id.toLowerCase();
192
+ const REASONING_PATTERNS = [
193
+ /thinking|reasoner|reasoning/i,
194
+ /(?:^|[-_/])o[134](?:[-_](?:mini|preview|high|low|medium|max))?(?:[-_/]|$)/i,
195
+ /(?:^|[-_/])(?:deepseek[-_])?r1(?:[-_/]|$)/i,
196
+ /(?:^|[-_/])qwq(?:[-_]\d+b)?(?:[-_/]|$)/i,
197
+ /(?:^|[-_/])(?:glm[-_]4[-_]?zero|glm[-_]?zero)(?:[-_/]|$)/i,
198
+ /(?:^|[-_/])cot(?:[-_/]|$)/i,
199
+ ];
200
+ return REASONING_PATTERNS.some((pattern) => pattern.test(lower));
201
+ }
202
+ // ---------------------------------------------------------------------------
203
+ // 思考档位(models.json 的模型级 thinkingLevelMap)
204
+ // ---------------------------------------------------------------------------
205
+ /** pi-ai 的思考档位,同时也是 `thinkingLevelMap` 认识的全部键(顺序 = 下拉顺序)。 */
206
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
207
+ /** pi-ai 默认开放给「推理模型」的档位(没有 thinkingLevelMap 时就是这个集合)。 */
208
+ const DEFAULT_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
209
+ /** 网关/推理端点常见的档位字面值 → pi 档位(查表前先归一化,见 normalizeLevelToken)。 */
210
+ const THINKING_LEVEL_ALIASES = {
211
+ off: "off",
212
+ none: "off",
213
+ no: "off",
214
+ "none-thinking": "off",
215
+ nothink: "off",
216
+ "no-think": "off",
217
+ disabled: "off",
218
+ disable: "off",
219
+ minimal: "minimal",
220
+ min: "minimal",
221
+ minimum: "minimal",
222
+ low: "low",
223
+ medium: "medium",
224
+ med: "medium",
225
+ mid: "medium",
226
+ middle: "medium",
227
+ high: "high",
228
+ xhigh: "xhigh",
229
+ "x-high": "xhigh",
230
+ "extra-high": "xhigh",
231
+ "very-high": "xhigh",
232
+ max: "max",
233
+ maximum: "max",
234
+ ultra: "max",
235
+ };
236
+ /** `/v1/models` 条目里可能携带推理档位的字段名(各家字段拼写不一)。 */
237
+ const THINKING_LEVEL_META_KEYS = [
238
+ "reasoning_levels",
239
+ "reasoningLevels",
240
+ "supported_reasoning_levels",
241
+ "supportedReasoningLevels",
242
+ "thinking_levels",
243
+ "supported_thinking_levels",
244
+ "supportedThinkingLevels",
245
+ ];
246
+ function normalizeLevelToken(token) {
247
+ return token
248
+ .trim()
249
+ .toLowerCase()
250
+ .replace(/[\s_]+/g, "-");
251
+ }
252
+ /** 档位元数据可能是数组、对象数组(`.effort`)、字典或逗号串——统一摊平成字面值列表。 */
253
+ function collectLevelTokens(value, out, depth = 0) {
254
+ if (depth > 2 || value === null || value === undefined)
255
+ return;
256
+ if (typeof value === "string") {
257
+ for (const part of value.split(/[,;|]/))
258
+ if (part.trim())
259
+ out.push(part);
260
+ return;
261
+ }
262
+ if (Array.isArray(value)) {
263
+ for (const item of value) {
264
+ if (typeof item === "string") {
265
+ out.push(item);
266
+ continue;
267
+ }
268
+ if (item && typeof item === "object") {
269
+ const row = item;
270
+ for (const key of ["effort", "level", "name", "id", "value", "type"]) {
271
+ if (typeof row[key] === "string") {
272
+ out.push(row[key]);
273
+ break;
274
+ }
275
+ }
276
+ }
277
+ }
278
+ return;
279
+ }
280
+ if (typeof value === "object") {
281
+ const row = value;
282
+ // 形如 { levels: [...] } / { supported: [...] } 的包裹
283
+ for (const key of ["levels", "values", "supported"]) {
284
+ if (key in row) {
285
+ collectLevelTokens(row[key], out, depth + 1);
286
+ return;
287
+ }
288
+ }
289
+ // 形如 { low: true, high: {…} } 的字典(false/null 表示不支持)
290
+ for (const [key, val] of Object.entries(row)) {
291
+ if (val === false || val === null || val === undefined)
292
+ continue;
293
+ out.push(key);
294
+ }
295
+ }
296
+ }
297
+ /** 从网关 `/models` 条目的推理档位元数据推导 pi-ai 的模型级 `thinkingLevelMap`。
298
+ *
299
+ * 背景:pi-ai 的 `getSupportedThinkingLevels()` 只有在模型带 `thinkingLevelMap`
300
+ * 且 `xhigh` / `max` 有显式映射时才开放这两档(见 pi-ai dist/models.js),否则
301
+ * 自定义服务商(vLLM / 聚合网关)永远只能选到 `off`…`high`。网关自己在
302
+ * `reasoning_levels` / `supported_reasoning_levels[].effort` 里报了能力,这里就
303
+ * 把它翻译成 pi 的映射:报了的档位映射成网关字面值,没报的显式写 `null`(= 不支持)。
304
+ *
305
+ * 两条保守规则:
306
+ * - `off` 永不隐藏(不写 `null`):关掉思考总是合法的,而且多数网关也没有
307
+ * `none` / `off` 这个字面值;只有在网关明确报了这类字面值时才映射过去。
308
+ * - 推导结果与 pi 默认能力(`off` + `minimal/low/medium/high`)完全一致时不返回
309
+ * 任何映射,避免每次刷新都把 models.json 无谓改写一遍。
310
+ *
311
+ * 纯函数,单测见 tests/unit/model-admin-thinking-levels.test.ts。
312
+ */
313
+ export function buildThinkingLevelMapFromMeta(raw) {
314
+ const meta = raw ?? {};
315
+ const tokens = [];
316
+ for (const key of THINKING_LEVEL_META_KEYS) {
317
+ if (key in meta)
318
+ collectLevelTokens(meta[key], tokens);
319
+ }
320
+ if (tokens.length === 0)
321
+ return undefined;
322
+ const advertised = new Map();
323
+ for (const token of tokens) {
324
+ const level = THINKING_LEVEL_ALIASES[normalizeLevelToken(token)];
325
+ if (level && !advertised.has(level))
326
+ advertised.set(level, token.trim());
327
+ }
328
+ // 只报了「关思考」类字面值 = 这模型压根不推理,别当成档位元数据。
329
+ if (![...advertised.keys()].some((level) => level !== "off"))
330
+ return undefined;
331
+ const map = {};
332
+ for (const level of THINKING_LEVELS) {
333
+ if (level === "off") {
334
+ const offLiteral = advertised.get("off");
335
+ if (offLiteral)
336
+ map.off = offLiteral;
337
+ continue;
338
+ }
339
+ map[level] = advertised.get(level) ?? null;
340
+ }
341
+ const enabled = THINKING_LEVELS.filter((level) => map[level] !== null);
342
+ const sameAsDefault = enabled.length === DEFAULT_THINKING_LEVELS.length &&
343
+ enabled.every((level, i) => level === DEFAULT_THINKING_LEVELS[i]);
344
+ if (sameAsDefault && map.off === undefined)
345
+ return undefined;
346
+ return map;
347
+ }
348
+ /** 只保留 pi 认识的 7 个档位键,值归一化成「非空字符串」或 `null`。
349
+ * models.json 的模型 schema 只列这 7 个键,未知键写进去既无意义也可能被拒。 */
350
+ export function sanitizeThinkingLevelMap(value) {
351
+ if (!value || typeof value !== "object" || Array.isArray(value))
352
+ return undefined;
353
+ const src = value;
354
+ const out = {};
355
+ for (const level of THINKING_LEVELS) {
356
+ const raw = src[level];
357
+ if (raw === null)
358
+ out[level] = null;
359
+ else if (typeof raw === "string" && raw.trim())
360
+ out[level] = raw.trim();
361
+ }
362
+ return Object.keys(out).length > 0 ? out : undefined;
363
+ }
206
364
  /** Best-effort extraction of model metadata from an OpenAI-compatible
207
365
  * /models `data[]` item. Most endpoints only return `{ id }` — the extra
208
366
  * fields (context_window / max_model_len / modalities / supports_vision /
209
- * reasoning / display_name) come from vLLM and other extended
210
- * implementations, and are filled into the form when present. */
367
+ * reasoning / display_name / 推理档位) come from vLLM, 聚合网关 and other
368
+ * extended implementations, and are filled into the form when present. */
211
369
  function parseOpenAiModel(m) {
212
370
  const r = (m ?? {});
213
371
  const id = typeof r.id === "string" ? r.id : "";
@@ -218,19 +376,19 @@ function parseOpenAiModel(m) {
218
376
  boolMeta(r.supports_vision) === true ||
219
377
  boolMeta(r.vision) === true ||
220
378
  strArrMeta(r.input)?.includes("image") === true;
221
- // 名字兜底:很多端点(如 Antigravity-Manager 的 /v1/models)只给 id 不给
222
- // 元数据;id 含 thinking 即视为思考模型(与反代自身的 is_thinking_model
223
- // 同口径)。只增不减:取消勾选靠手填(编辑页/刷新合并都只补缺)。
224
- const reasoning = boolMeta(r.reasoning) === true ||
225
- boolMeta(r.supports_reasoning) === true ||
226
- modalities?.includes("reasoning") === true ||
227
- id.toLowerCase().includes("thinking");
379
+ // 名字与元数据兜底:端点未提供 reasoning 时通过通用推理模型特征推断。
380
+ // 只增不减:取消勾选靠手填(编辑页/刷新合并都只补缺)。
381
+ // 网关自报推理档位同样是「这是推理模型」的铁证(如聚合网关的 glm-5.3,
382
+ // 名字认不出来,但 reasoning_levels 报了 low/high/max)。
383
+ const thinkingLevelMap = buildThinkingLevelMapFromMeta(r);
384
+ const reasoning = detectReasoningCapability(id, r) || thinkingLevelMap !== undefined;
228
385
  const contextWindow = numMeta(r.context_window) ?? numMeta(r.context_length) ?? numMeta(r.max_model_len) ?? numMeta(r.max_context_length);
229
386
  const maxTokens = numMeta(r.max_tokens) ?? numMeta(r.max_output_tokens) ?? numMeta(r.max_completion_tokens);
230
387
  return {
231
388
  id,
232
389
  ...(name ? { name } : {}),
233
390
  ...(reasoning ? { reasoning: true } : {}),
391
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
234
392
  ...(vision ? { input: ["text", "image"] } : {}),
235
393
  ...(contextWindow ? { contextWindow } : {}),
236
394
  ...(maxTokens ? { maxTokens } : {}),
@@ -244,12 +402,14 @@ function parseGoogleModel(m) {
244
402
  const rawName = typeof r.name === "string" ? r.name : "";
245
403
  const id = rawName.replace(/^models\//, "");
246
404
  const displayName = typeof r.displayName === "string" ? r.displayName : undefined;
247
- // 与 OpenAI 形状同口径的名字兜底(见 parseOpenAiModel)。
248
- const reasoning = id.toLowerCase().includes("thinking");
405
+ // 与 OpenAI 形状同口径的推断兜底(见 detectReasoningCapability)。
406
+ const thinkingLevelMap = buildThinkingLevelMapFromMeta(r);
407
+ const reasoning = detectReasoningCapability(id, r) || thinkingLevelMap !== undefined;
249
408
  return {
250
409
  id,
251
410
  ...(displayName && displayName !== id ? { name: displayName } : {}),
252
411
  ...(reasoning ? { reasoning: true } : {}),
412
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
253
413
  ...(numMeta(r.inputTokenLimit) ? { contextWindow: numMeta(r.inputTokenLimit) } : {}),
254
414
  ...(numMeta(r.outputTokenLimit) ? { maxTokens: numMeta(r.outputTokenLimit) } : {}),
255
415
  };
@@ -532,7 +692,17 @@ export class ModelAdminService {
532
692
  catch {
533
693
  // runtime not ready
534
694
  }
535
- for (const id of ["anthropic", "openai", "google", "deepseek", "groq", "mistral", "openrouter", "ollama"]) {
695
+ for (const id of [
696
+ "anthropic",
697
+ "openai",
698
+ "google",
699
+ "deepseek",
700
+ "groq",
701
+ "mistral",
702
+ "openrouter",
703
+ "ollama",
704
+ "llama.cpp",
705
+ ]) {
536
706
  ids.add(id);
537
707
  }
538
708
  return [...ids];
@@ -547,7 +717,18 @@ export class ModelAdminService {
547
717
  catch {
548
718
  // no file yet / unparsable — start fresh
549
719
  }
550
- data[pid] = { type: "api_key", key: apiKey };
720
+ if (pid === "llama.cpp") {
721
+ const prevLlama = (data[pid] ?? {});
722
+ const baseUrl = prevLlama.env?.LLAMA_BASE_URL || process.env.LLAMA_BASE_URL || "http://127.0.0.1:8080";
723
+ data[pid] = {
724
+ type: "api_key",
725
+ key: apiKey || "local",
726
+ env: { LLAMA_BASE_URL: baseUrl },
727
+ };
728
+ }
729
+ else {
730
+ data[pid] = { type: "api_key", key: apiKey };
731
+ }
551
732
  atomicWriteCredentialJson(authPath, data);
552
733
  try {
553
734
  chmodSync(this.providerKeysPath(), CREDENTIAL_FILE_MODE);
@@ -1183,6 +1364,7 @@ export class ModelAdminService {
1183
1364
  { id: "groq", name: "Groq" },
1184
1365
  { id: "mistral", name: "Mistral" },
1185
1366
  { id: "ollama", name: "Ollama" },
1367
+ { id: "llama.cpp", name: "llama.cpp" },
1186
1368
  ];
1187
1369
  const allIds = new Set();
1188
1370
  providers = [];
@@ -1193,7 +1375,8 @@ export class ModelAdminService {
1193
1375
  (b.id === "deepseek" && process.env.DEEPSEEK_API_KEY) ||
1194
1376
  (b.id === "openai" && process.env.OPENAI_API_KEY) ||
1195
1377
  (b.id === "openrouter" && process.env.OPENROUTER_API_KEY) ||
1196
- (b.id === "google" && (process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY)));
1378
+ (b.id === "google" && (process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY)) ||
1379
+ (b.id === "llama.cpp" && process.env.LLAMA_BASE_URL));
1197
1380
  providers.push({
1198
1381
  id: b.id,
1199
1382
  name: b.name,
@@ -1237,49 +1420,6 @@ export class ModelAdminService {
1237
1420
  modelsConfigPath() {
1238
1421
  return join(this.host.agentDir, "models.json");
1239
1422
  }
1240
- /** Strip // and /* *\/ comments without touching string literals (URLs contain //). */
1241
- static stripJsonComments(src) {
1242
- let out = "";
1243
- let inString = false;
1244
- let i = 0;
1245
- while (i < src.length) {
1246
- const c = src[i];
1247
- const next = src[i + 1];
1248
- if (inString) {
1249
- out += c;
1250
- if (c === "\\") {
1251
- out += next ?? "";
1252
- i += 2;
1253
- continue;
1254
- }
1255
- if (c === '"')
1256
- inString = false;
1257
- i++;
1258
- continue;
1259
- }
1260
- if (c === '"') {
1261
- inString = true;
1262
- out += c;
1263
- i++;
1264
- continue;
1265
- }
1266
- if (c === "/" && next === "/") {
1267
- while (i < src.length && src[i] !== "\n")
1268
- i++;
1269
- continue;
1270
- }
1271
- if (c === "/" && next === "*") {
1272
- i += 2;
1273
- while (i < src.length && !(src[i] === "*" && src[i + 1] === "/"))
1274
- i++;
1275
- i += 2;
1276
- continue;
1277
- }
1278
- out += c;
1279
- i++;
1280
- }
1281
- return out;
1282
- }
1283
1423
  /** Read + parse models.json (tolerating // and /* *\/ comments like the SDK). */
1284
1424
  readModelsConfig() {
1285
1425
  const path = this.modelsConfigPath();
@@ -1304,6 +1444,9 @@ export class ModelAdminService {
1304
1444
  input: Array.isArray(m.input) ? m.input : undefined,
1305
1445
  contextWindow: m.contextWindow,
1306
1446
  maxTokens: m.maxTokens,
1447
+ // 思考档位映射必须下发:前端模型行拿不到它就会在保存往返里丢掉,
1448
+ // 编辑页也无法展示网关自报的 xhigh/max 能力。
1449
+ thinkingLevelMap: sanitizeThinkingLevelMap(m.thinkingLevelMap),
1307
1450
  }))
1308
1451
  : [];
1309
1452
  return {
@@ -1346,69 +1489,8 @@ export class ModelAdminService {
1346
1489
  }
1347
1490
  this.host.flushSnapshot();
1348
1491
  }
1349
- /** Numeric metadata value (NaN/string "unknown" → undefined). */
1350
- static numMeta(v) {
1351
- return typeof v === "number" && Number.isFinite(v) ? v : undefined;
1352
- }
1353
- static boolMeta(v) {
1354
- return typeof v === "boolean" ? v : undefined;
1355
- }
1356
- static strArrMeta(v) {
1357
- return Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
1358
- }
1359
- /** Best-effort extraction of model metadata from an OpenAI-compatible
1360
- * /models `data[]` item. Most endpoints only return `{ id }` — the extra
1361
- * fields (context_window / max_model_len / modalities / supports_vision /
1362
- * reasoning / display_name) come from vLLM and other extended
1363
- * implementations, and are filled into the form when present. */
1364
- static parseOpenAiModel(m) {
1365
- const r = (m ?? {});
1366
- const id = typeof r.id === "string" ? r.id : "";
1367
- const name = (typeof r.name === "string" && r.name.trim() ? r.name : undefined) ??
1368
- (typeof r.display_name === "string" && r.display_name.trim() ? r.display_name : undefined);
1369
- const modalities = strArrMeta(r.modalities) ?? strArrMeta(r.input_modalities);
1370
- const vision = modalities?.includes("image") === true ||
1371
- boolMeta(r.supports_vision) === true ||
1372
- boolMeta(r.vision) === true ||
1373
- strArrMeta(r.input)?.includes("image") === true;
1374
- // 名字兜底(同模块级 parseOpenAiModel):只给 id 的端点靠 id 含 thinking
1375
- // 视为思考模型,只增不减,手填合并只补缺。
1376
- const reasoning = boolMeta(r.reasoning) === true ||
1377
- boolMeta(r.supports_reasoning) === true ||
1378
- modalities?.includes("reasoning") === true ||
1379
- id.toLowerCase().includes("thinking");
1380
- const contextWindow = numMeta(r.context_window) ??
1381
- numMeta(r.context_length) ??
1382
- numMeta(r.max_model_len) ??
1383
- numMeta(r.max_context_length);
1384
- const maxTokens = numMeta(r.max_tokens) ?? numMeta(r.max_output_tokens) ?? numMeta(r.max_completion_tokens);
1385
- return {
1386
- id,
1387
- ...(name ? { name } : {}),
1388
- ...(reasoning ? { reasoning: true } : {}),
1389
- ...(vision ? { input: ["text", "image"] } : {}),
1390
- ...(contextWindow ? { contextWindow } : {}),
1391
- ...(maxTokens ? { maxTokens } : {}),
1392
- };
1393
- }
1394
- /** google-generative-ai /models shape:
1395
- * { models: [{ name: "models/gemini-flash", displayName, inputTokenLimit,
1396
- * outputTokenLimit, supportedGenerationMethods }] } */
1397
- static parseGoogleModel(m) {
1398
- const r = (m ?? {});
1399
- const rawName = typeof r.name === "string" ? r.name : "";
1400
- const id = rawName.replace(/^models\//, "");
1401
- const displayName = typeof r.displayName === "string" ? r.displayName : undefined;
1402
- // 与 OpenAI 形状同口径的名字兜底(见模块级 parseOpenAiModel)。
1403
- const reasoning = id.toLowerCase().includes("thinking");
1404
- return {
1405
- id,
1406
- ...(displayName && displayName !== id ? { name: displayName } : {}),
1407
- ...(reasoning ? { reasoning: true } : {}),
1408
- ...(numMeta(r.inputTokenLimit) ? { contextWindow: numMeta(r.inputTokenLimit) } : {}),
1409
- ...(numMeta(r.outputTokenLimit) ? { maxTokens: numMeta(r.outputTokenLimit) } : {}),
1410
- };
1411
- }
1492
+ // 模型元数据解析(numMeta/boolMeta/strArrMeta/parseOpenAiModel/parseGoogleModel)
1493
+ // 单源在模块级:这几份曾是静态方法里的死副本,改一处漏一处(#771 白改一遍)。
1412
1494
  /** Probe a custom provider's OpenAI-compatible /models endpoint (server-side
1413
1495
  * because the baseUrl is often a LAN/loopback host the browser can't reach
1414
1496
  * cross-origin) and return the advertised models. reqId is echoed back
@@ -1764,10 +1846,12 @@ export class ModelAdminService {
1764
1846
  * toModelRow itself only trims); absent values keep being inherited
1765
1847
  * from sibling models at compose time. */
1766
1848
  static toModelRow(m) {
1849
+ const thinkingLevelMap = sanitizeThinkingLevelMap(m.thinkingLevelMap);
1767
1850
  return {
1768
1851
  id: m.id.trim(),
1769
1852
  ...(m.name?.trim() ? { name: m.name.trim() } : {}),
1770
1853
  ...(m.reasoning ? { reasoning: true } : {}),
1854
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
1771
1855
  ...(m.input?.length ? { input: m.input } : {}),
1772
1856
  ...(m.contextWindow ? { contextWindow: Number(m.contextWindow) } : {}),
1773
1857
  ...(m.maxTokens ? { maxTokens: Number(m.maxTokens) } : {}),