pi-web-ui 0.112.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 (37) hide show
  1. package/CHANGELOG.md +38 -1
  2. package/bin/pi-web-ui.mjs +325 -45
  3. package/dist/server/agent-service-daemon.js +29 -4
  4. package/dist/server/agent-service.js +215 -35
  5. package/dist/server/canvas/canvas-agent-tool.js +2 -0
  6. package/dist/server/canvas/canvas-orchestrator.js +40 -1
  7. package/dist/server/canvas/pstack-skills-data.js +498 -0
  8. package/dist/server/dispatch-domain-handlers.js +36 -11
  9. package/dist/server/dsh/dsh-agent-service.js +52 -4
  10. package/dist/server/durable/durable-driver.js +37 -98
  11. package/dist/server/durable/durable-event-projector.js +253 -0
  12. package/dist/server/engine-probe.js +35 -11
  13. package/dist/server/index.js +67 -41
  14. package/dist/server/model-admin.js +185 -63
  15. package/dist/server/plugins.js +10 -6
  16. package/dist/server/remote-ssh-service.js +110 -12
  17. package/dist/server/serialize.js +1 -1
  18. package/dist/server/settings-service.js +36 -48
  19. package/dist/server/setup-page.js +632 -0
  20. package/dist/server/skill-discovery.js +361 -59
  21. package/dist/server/skill-maintenance.js +231 -0
  22. package/dist/server/skill-tool.js +32 -3
  23. package/dist/server/soft-cap.js +29 -7
  24. package/dist/server/subagents.js +246 -31
  25. package/dist/server/tool-host-factories.js +2 -0
  26. package/dist/server/tool-manager.js +106 -28
  27. package/dist/server/universal/drivers/claude-code.js +96 -4
  28. package/dist/server/universal/universal-session.js +19 -0
  29. package/package.json +1 -1
  30. package/plugins/catalog.json +10 -0
  31. package/web/dist/assets/{TerminalPanel-Dqr1dK28.js → TerminalPanel-3wojLfLk.js} +2 -2
  32. package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
  33. package/web/dist/assets/index-BwL7qBh6.css +1 -0
  34. package/web/dist/index.html +2 -2
  35. package/web/dist/sw.js +1 -1
  36. package/web/dist/assets/index-Dh8BX-lP.js +0 -720
  37. package/web/dist/assets/index-DqrC1I_a.css +0 -1
@@ -19,7 +19,7 @@
19
19
  // MUST be imported before the SDK is loaded so on-disk patches apply cleanly.
20
20
  import "./patch-remote-catalog.js";
21
21
  import "./patch-turn-end-boundary.js";
22
- import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
22
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
23
23
  import { readFile, stat } from "node:fs/promises";
24
24
  import { createServer, request as proxyRequest } from "node:http";
25
25
  import { createConnection } from "node:net";
@@ -63,6 +63,7 @@ import { initHttpProxy } from "./http-proxy.js";
63
63
  import { globalLspPool } from "./lsp-tool.js";
64
64
  import { buildPiWebTokenCookie, decodeCookieToken, isTlsRequest } from "./auth-cookie.js";
65
65
  import { isLoopbackAddress, loadServerFileConfig, saveServerFileConfig, tokenWarning } from "./server-config.js";
66
+ import { renderSetupHtml } from "./setup-page.js";
66
67
  import { getAppVersion, getPkgRoot } from "./pkg-info.js";
67
68
  import { handleFileMessage, handleScmMessage, handleBgServerMessage, handlePresetAndDshMessage, handleModelAndProviderMessage, handleTerminalMessage, handleSessionLifecycleMessage, handlePlanAndGoalMessage, handleScheduleMessage, handleSettingsMessage, handleInteractiveResponseMessage, handleRemoteSshMessage, } from "./dispatch-domain-handlers.js";
68
69
  import { RemoteSshService, isRemoteWorkspaceUri, serveRemoteWorkspaceFile, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
@@ -232,6 +233,47 @@ if (process.platform === "win32") {
232
233
  process.env.PATH = `${windowsBashDir()}${delimiter}${process.env.PATH ?? ""}`;
233
234
  void ensureWindowsBash();
234
235
  }
236
+ else if (process.platform === "darwin") {
237
+ // macOS launchd 用户代理或 GUI 下,PATH 默认仅 /usr/bin:/bin:/usr/sbin:/sbin。
238
+ // 自动补齐 Homebrew 与常见本地工具目录,确保 claude / git / node 等安装后开箱可用。
239
+ const macPaths = [
240
+ "/opt/homebrew/bin",
241
+ "/usr/local/bin",
242
+ join(homedir(), ".local", "bin"),
243
+ join(homedir(), "Library", "pnpm"),
244
+ join(homedir(), ".bun", "bin"),
245
+ join(homedir(), ".local", "share", "fnm", "current", "bin"),
246
+ ];
247
+ // fnm / nvm 在 macOS 下版本目录自动扫入 PATH
248
+ const fnmVersions = join(homedir(), ".local", "share", "fnm", "node-versions");
249
+ if (existsSync(fnmVersions)) {
250
+ try {
251
+ for (const v of readdirSync(fnmVersions)) {
252
+ macPaths.push(join(fnmVersions, v, "installation", "bin"));
253
+ }
254
+ }
255
+ catch {
256
+ /* ignore */
257
+ }
258
+ }
259
+ const nvmVersions = join(homedir(), ".nvm", "versions", "node");
260
+ if (existsSync(nvmVersions)) {
261
+ try {
262
+ for (const v of readdirSync(nvmVersions)) {
263
+ macPaths.push(join(nvmVersions, v, "bin"));
264
+ }
265
+ }
266
+ catch {
267
+ /* ignore */
268
+ }
269
+ }
270
+ const curParts = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
271
+ const curSet = new Set(curParts);
272
+ const toAdd = macPaths.filter((p) => existsSync(p) && !curSet.has(p));
273
+ if (toAdd.length > 0) {
274
+ process.env.PATH = `${toAdd.join(delimiter)}${delimiter}${process.env.PATH ?? ""}`;
275
+ }
276
+ }
235
277
  const app = express();
236
278
  // Host 白名单(防 DNS rebinding,审查 #352):无 token 部署下 HTTP 路由此前
237
279
  // 不校验 Host,恶意网页让自己的域名解析到 127.0.0.1 即可打满全部 API。
@@ -287,54 +329,28 @@ export function setupGate(req, res, next) {
287
329
  return;
288
330
  }
289
331
  }
332
+ // 5. 跨站 Fetch 探测防御(Sec-Fetch-Site 防御):
333
+ // 如果是来自外部网站的跨站子资源探测/嵌入(非顶层页面导航),直接拦截。
334
+ // 浏览器地址栏直接输入/回车或者外链跳转到 setup 页时,sec-fetch-site 可能是 cross-site/none,
335
+ // 但其 sec-fetch-dest 是 document / mode 是 navigate;只有跨站的子请求(如 fetch/xhr/image/iframe)才需要阻断。
336
+ const secFetchSite = typeof req.headers["sec-fetch-site"] === "string" ? req.headers["sec-fetch-site"].toLowerCase() : "";
337
+ const secFetchMode = typeof req.headers["sec-fetch-mode"] === "string" ? req.headers["sec-fetch-mode"].toLowerCase() : "";
338
+ if (secFetchSite === "cross-site" && secFetchMode !== "navigate") {
339
+ res.status(403).end("cross-site request to setup rejected");
340
+ return;
341
+ }
290
342
  next();
291
343
  }
292
- const SETUP_PAGE = `<!doctype html><html lang="zh"><head><meta charset="utf-8">
293
- <meta name="viewport" content="width=device-width,initial-scale=1">
294
- <title>pi-web-ui 本地配置</title>
295
- <style>body{font-family:system-ui,sans-serif;max-width:560px;margin:40px auto;padding:0 16px;
296
- background:#16181d;color:#e6e6e6}label{display:block;margin:14px 0 4px;color:#9aa}input{width:100%;
297
- box-sizing:border-box;padding:8px;border-radius:6px;border:1px solid #444;background:#222;color:#eee}
298
- button{margin-top:18px;padding:9px 22px;border:0;border-radius:6px;background:#4c8dff;color:#fff;
299
- font-size:15px;cursor:pointer}.hint{color:#9aa;font-size:13px;margin-top:4px}#msg{margin-top:14px;
300
- white-space:pre-wrap}.warn{color:#e0a63c}.ok{color:#6fbf73}.err{color:#e06c6c}</style></head><body>
301
- <h2>pi-web-ui 本地配置</h2>
302
- <p class="hint">本页只能在本机打开(回环地址)。token 修改立即生效;监听地址 / 端口 /
303
- 白名单保存后需重启服务(<code>pi-web-ui server restart</code>)。命令行旗标与环境变量
304
- 的优先级高于这里的保存值。</p>
305
- <label>访问口令 token(留空 = 清除)</label><input id="token" type="password" autocomplete="new-password">
306
- <div class="hint" id="twarn"></div>
307
- <label>监听地址 host(127.0.0.1 仅本机,0.0.0.0 允许局域网)</label><input id="host">
308
- <label>端口 port</label><input id="port" inputmode="numeric">
309
- <label>Host 白名单(逗号分隔,空 = 关闭严格模式)</label><input id="allowHosts">
310
- <label>额外 Origin 白名单(反代场景,逗号分隔)</label><input id="allowOrigins">
311
- <div><button id="save">保存</button></div>
312
- <div id="msg"></div>
313
- <script>
314
- const $=id=>document.getElementById(id);
315
- const msg=(t,c)=>{const m=$("msg");m.className=c||"";m.textContent=t;};
316
- fetch("/api/setup/status").then(r=>{if(!r.ok)throw new Error(r.status+" "+r.statusText);return r.json();})
317
- .then(s=>{$("host").value=s.host||"";$("port").value=s.port||"";
318
- $("allowHosts").value=s.allowHosts||"";$("allowOrigins").value=s.allowOrigins||"";
319
- $("twarn").textContent=s.tokenSet?("已设置口令"+(s.tokenWarning?":"+s.tokenWarning:"")):"当前未设置口令(本机直连无需口令)";})
320
- .catch(e=>msg("读取状态失败:"+e.message,"err"));
321
- $("save").onclick=()=>{msg("保存中…","");
322
- fetch("/api/setup/save",{method:"POST",headers:{"Content-Type":"application/json"},
323
- body:JSON.stringify({token:$("token").value,host:$("host").value,port:$("port").value,
324
- allowHosts:$("allowHosts").value,allowOrigins:$("allowOrigins").value})})
325
- .then(r=>r.json().then(j=>({st:r.status,j})))
326
- .then(({st,j})=>{if(!j.ok){msg("保存失败:"+(j.error||st),"err");return;}
327
- msg((j.restartRequired?"已保存,token 已生效;host/port/白名单需重启服务后生效。"
328
- :"已保存并生效。")+"\n"+JSON.stringify(j.saved,null,2),"ok");$("token").value="";})
329
- .catch(e=>msg("请求失败:"+e.message,"err"});};
330
- </script></body></html>`;
331
344
  app.get("/setup", setupGate, (_req, res) => {
332
345
  res.setHeader("Content-Type", "text/html; charset=utf-8");
333
- res.end(SETUP_PAGE);
346
+ res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
347
+ res.end(renderSetupHtml());
334
348
  });
335
349
  app.get("/api/setup/status", setupGate, (_req, res) => {
350
+ res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
336
351
  res.json({
337
352
  ok: true,
353
+ token: AUTH_TOKEN,
338
354
  tokenSet: AUTH_TOKEN.length > 0,
339
355
  tokenWarning: AUTH_TOKEN ? tokenWarning(AUTH_TOKEN) : "",
340
356
  host: HOST,
@@ -409,6 +425,15 @@ app.post("/api/setup/save", setupGate, (req, res) => {
409
425
  (body.port !== undefined && body.port !== "" && body.port !== null && Number(body.port) !== PORT) ||
410
426
  (typeof body.allowHosts === "string" && norm(body.allowHosts) !== ALLOW_HOSTS.join(",")) ||
411
427
  (typeof body.allowOrigins === "string" && norm(body.allowOrigins) !== ALLOW_ORIGINS.join(","));
428
+ // 如果设置了新 token,直接给当前回环浏览器下发匹配的 cookie,避免保存后直接 401
429
+ if (AUTH_TOKEN) {
430
+ const secure = isTlsRequest(req);
431
+ res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, secure));
432
+ }
433
+ else if (tokenChanged && !AUTH_TOKEN) {
434
+ // 清除了 token,同时清理旧 cookie
435
+ res.setHeader("Set-Cookie", [buildPiWebTokenCookie("", 0, false), buildPiWebTokenCookie("", 0, true)]);
436
+ }
412
437
  res.json({
413
438
  ok: true,
414
439
  tokenApplied: tokenChanged,
@@ -1753,6 +1778,7 @@ async function confirmPluginInstallHelper(items) {
1753
1778
  // 远程 SSH 连接管理、环境探针与目录浏览服务
1754
1779
  const remoteSshService = new RemoteSshService(DATA_DIR);
1755
1780
  setGlobalRemoteSshService(remoteSshService);
1781
+ pluginMgr.provideService("host", "remoteSsh", remoteSshService);
1756
1782
  // 多引擎多模型多目录画布协作调度器 (Canvas Studio)
1757
1783
  const canvasOrchestrator = new CanvasOrchestrator(CWD, DATA_DIR, (eng) => ensureEngine(eng));
1758
1784
  setCanvasRuntime(canvasOrchestrator);
@@ -129,6 +129,12 @@ export function mergeProviderConfigEntry(prevEntry, config, models) {
129
129
  merged.maxTokens = Number(model.maxTokens);
130
130
  else
131
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;
132
138
  return merged;
133
139
  });
134
140
  const mergedEntry = { ...prevEntry };
@@ -193,11 +199,173 @@ export function detectReasoningCapability(id, rawMeta) {
193
199
  ];
194
200
  return REASONING_PATTERNS.some((pattern) => pattern.test(lower));
195
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
+ }
196
364
  /** Best-effort extraction of model metadata from an OpenAI-compatible
197
365
  * /models `data[]` item. Most endpoints only return `{ id }` — the extra
198
366
  * fields (context_window / max_model_len / modalities / supports_vision /
199
- * reasoning / display_name) come from vLLM and other extended
200
- * 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. */
201
369
  function parseOpenAiModel(m) {
202
370
  const r = (m ?? {});
203
371
  const id = typeof r.id === "string" ? r.id : "";
@@ -210,13 +378,17 @@ function parseOpenAiModel(m) {
210
378
  strArrMeta(r.input)?.includes("image") === true;
211
379
  // 名字与元数据兜底:端点未提供 reasoning 时通过通用推理模型特征推断。
212
380
  // 只增不减:取消勾选靠手填(编辑页/刷新合并都只补缺)。
213
- const reasoning = detectReasoningCapability(id, r);
381
+ // 网关自报推理档位同样是「这是推理模型」的铁证(如聚合网关的 glm-5.3,
382
+ // 名字认不出来,但 reasoning_levels 报了 low/high/max)。
383
+ const thinkingLevelMap = buildThinkingLevelMapFromMeta(r);
384
+ const reasoning = detectReasoningCapability(id, r) || thinkingLevelMap !== undefined;
214
385
  const contextWindow = numMeta(r.context_window) ?? numMeta(r.context_length) ?? numMeta(r.max_model_len) ?? numMeta(r.max_context_length);
215
386
  const maxTokens = numMeta(r.max_tokens) ?? numMeta(r.max_output_tokens) ?? numMeta(r.max_completion_tokens);
216
387
  return {
217
388
  id,
218
389
  ...(name ? { name } : {}),
219
390
  ...(reasoning ? { reasoning: true } : {}),
391
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
220
392
  ...(vision ? { input: ["text", "image"] } : {}),
221
393
  ...(contextWindow ? { contextWindow } : {}),
222
394
  ...(maxTokens ? { maxTokens } : {}),
@@ -231,11 +403,13 @@ function parseGoogleModel(m) {
231
403
  const id = rawName.replace(/^models\//, "");
232
404
  const displayName = typeof r.displayName === "string" ? r.displayName : undefined;
233
405
  // 与 OpenAI 形状同口径的推断兜底(见 detectReasoningCapability)。
234
- const reasoning = detectReasoningCapability(id, r);
406
+ const thinkingLevelMap = buildThinkingLevelMapFromMeta(r);
407
+ const reasoning = detectReasoningCapability(id, r) || thinkingLevelMap !== undefined;
235
408
  return {
236
409
  id,
237
410
  ...(displayName && displayName !== id ? { name: displayName } : {}),
238
411
  ...(reasoning ? { reasoning: true } : {}),
412
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
239
413
  ...(numMeta(r.inputTokenLimit) ? { contextWindow: numMeta(r.inputTokenLimit) } : {}),
240
414
  ...(numMeta(r.outputTokenLimit) ? { maxTokens: numMeta(r.outputTokenLimit) } : {}),
241
415
  };
@@ -1270,6 +1444,9 @@ export class ModelAdminService {
1270
1444
  input: Array.isArray(m.input) ? m.input : undefined,
1271
1445
  contextWindow: m.contextWindow,
1272
1446
  maxTokens: m.maxTokens,
1447
+ // 思考档位映射必须下发:前端模型行拿不到它就会在保存往返里丢掉,
1448
+ // 编辑页也无法展示网关自报的 xhigh/max 能力。
1449
+ thinkingLevelMap: sanitizeThinkingLevelMap(m.thinkingLevelMap),
1273
1450
  }))
1274
1451
  : [];
1275
1452
  return {
@@ -1312,65 +1489,8 @@ export class ModelAdminService {
1312
1489
  }
1313
1490
  this.host.flushSnapshot();
1314
1491
  }
1315
- /** Numeric metadata value (NaN/string "unknown" → undefined). */
1316
- static numMeta(v) {
1317
- return typeof v === "number" && Number.isFinite(v) ? v : undefined;
1318
- }
1319
- static boolMeta(v) {
1320
- return typeof v === "boolean" ? v : undefined;
1321
- }
1322
- static strArrMeta(v) {
1323
- return Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
1324
- }
1325
- /** Best-effort extraction of model metadata from an OpenAI-compatible
1326
- * /models `data[]` item. Most endpoints only return `{ id }` — the extra
1327
- * fields (context_window / max_model_len / modalities / supports_vision /
1328
- * reasoning / display_name) come from vLLM and other extended
1329
- * implementations, and are filled into the form when present. */
1330
- static parseOpenAiModel(m) {
1331
- const r = (m ?? {});
1332
- const id = typeof r.id === "string" ? r.id : "";
1333
- const name = (typeof r.name === "string" && r.name.trim() ? r.name : undefined) ??
1334
- (typeof r.display_name === "string" && r.display_name.trim() ? r.display_name : undefined);
1335
- const modalities = strArrMeta(r.modalities) ?? strArrMeta(r.input_modalities);
1336
- const vision = modalities?.includes("image") === true ||
1337
- boolMeta(r.supports_vision) === true ||
1338
- boolMeta(r.vision) === true ||
1339
- strArrMeta(r.input)?.includes("image") === true;
1340
- // 名字与元数据兜底:端点未提供 reasoning 时通过通用推理模型特征推断。
1341
- const reasoning = detectReasoningCapability(id, r);
1342
- const contextWindow = numMeta(r.context_window) ??
1343
- numMeta(r.context_length) ??
1344
- numMeta(r.max_model_len) ??
1345
- numMeta(r.max_context_length);
1346
- const maxTokens = numMeta(r.max_tokens) ?? numMeta(r.max_output_tokens) ?? numMeta(r.max_completion_tokens);
1347
- return {
1348
- id,
1349
- ...(name ? { name } : {}),
1350
- ...(reasoning ? { reasoning: true } : {}),
1351
- ...(vision ? { input: ["text", "image"] } : {}),
1352
- ...(contextWindow ? { contextWindow } : {}),
1353
- ...(maxTokens ? { maxTokens } : {}),
1354
- };
1355
- }
1356
- /** google-generative-ai /models shape:
1357
- * { models: [{ name: "models/gemini-flash", displayName, inputTokenLimit,
1358
- * outputTokenLimit, supportedGenerationMethods }] } */
1359
- static parseGoogleModel(m) {
1360
- const r = (m ?? {});
1361
- const rawName = typeof r.name === "string" ? r.name : "";
1362
- const id = rawName.replace(/^models\//, "");
1363
- const displayName = typeof r.displayName === "string" ? r.displayName : undefined;
1364
- // 与 OpenAI 形状同口径的推断兜底(见 detectReasoningCapability)。
1365
- const reasoning = detectReasoningCapability(id, r);
1366
- return {
1367
- id,
1368
- ...(displayName && displayName !== id ? { name: displayName } : {}),
1369
- ...(reasoning ? { reasoning: true } : {}),
1370
- ...(numMeta(r.inputTokenLimit) ? { contextWindow: numMeta(r.inputTokenLimit) } : {}),
1371
- ...(numMeta(r.outputTokenLimit) ? { maxTokens: numMeta(r.outputTokenLimit) } : {}),
1372
- };
1373
- }
1492
+ // 模型元数据解析(numMeta/boolMeta/strArrMeta/parseOpenAiModel/parseGoogleModel)
1493
+ // 单源在模块级:这几份曾是静态方法里的死副本,改一处漏一处(#771 白改一遍)。
1374
1494
  /** Probe a custom provider's OpenAI-compatible /models endpoint (server-side
1375
1495
  * because the baseUrl is often a LAN/loopback host the browser can't reach
1376
1496
  * cross-origin) and return the advertised models. reqId is echoed back
@@ -1726,10 +1846,12 @@ export class ModelAdminService {
1726
1846
  * toModelRow itself only trims); absent values keep being inherited
1727
1847
  * from sibling models at compose time. */
1728
1848
  static toModelRow(m) {
1849
+ const thinkingLevelMap = sanitizeThinkingLevelMap(m.thinkingLevelMap);
1729
1850
  return {
1730
1851
  id: m.id.trim(),
1731
1852
  ...(m.name?.trim() ? { name: m.name.trim() } : {}),
1732
1853
  ...(m.reasoning ? { reasoning: true } : {}),
1854
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
1733
1855
  ...(m.input?.length ? { input: m.input } : {}),
1734
1856
  ...(m.contextWindow ? { contextWindow: Number(m.contextWindow) } : {}),
1735
1857
  ...(m.maxTokens ? { maxTokens: Number(m.maxTokens) } : {}),
@@ -1693,7 +1693,7 @@ export class PluginManager {
1693
1693
  streamingHandlers = new Set();
1694
1694
  /** 插件间总线订阅:topic → 处理器集合(host.events.on 注册;反激活时清理该插件全部订阅)。 */
1695
1695
  busHandlers = new Map();
1696
- /** host.chatWait 的 run_end 等待者(emitRunEvent 里按 conversationId 唤醒)。 */
1696
+ /** host.chatWait 的 run_end 等待者(emitRunEvent 里按 runId / conversationId 唤醒)。 */
1697
1697
  chatWaiters = [];
1698
1698
  /** 激活期插件的能力门控快照(activate 开头写入、落盘 loaded 或失败即删):
1699
1699
  * canUse 在 host 对象可用之前(loaded.set 之前)也要能判定。 */
@@ -1761,11 +1761,13 @@ export class PluginManager {
1761
1761
  return true;
1762
1762
  return legacy(fam);
1763
1763
  }
1764
- /** host.chatWait 等待指定对话的 run_end(默认 120s 超时由调用方钳制后传入)。 */
1765
- waitRunEnd(conversationId, timeoutMs) {
1764
+ /** host.chatWait 等待指定对话的 run_end(默认 120s 超时由调用方钳制后传入)。
1765
+ * runId 优先:过户换持有方 / 撞 id 改名后 conversationId 已经对不上了。 */
1766
+ waitRunEnd(conversationId, timeoutMs, runId) {
1766
1767
  return new Promise((resolve) => {
1767
1768
  const entry = {
1768
1769
  conversationId,
1770
+ ...(runId ? { runId } : {}),
1769
1771
  done: (ended) => {
1770
1772
  clearTimeout(timer);
1771
1773
  const i = this.chatWaiters.indexOf(entry);
@@ -1830,9 +1832,11 @@ export class PluginManager {
1830
1832
  * 与 emitToolEvent 同级;订阅者崩了只记日志,不影响主流程)。
1831
1833
  * run_end 顺带唤醒 host.chatWait 的等待者(按 conversationId 匹配)。 */
1832
1834
  emitRunEvent(ev) {
1833
- if (ev.type === "run_end" && ev.conversationId) {
1835
+ if (ev.type === "run_end" && (ev.conversationId || ev.runId)) {
1834
1836
  for (const w of this.chatWaiters) {
1835
- if (w.conversationId !== ev.conversationId)
1837
+ const byRun = Boolean(ev.runId && w.runId && ev.runId === w.runId);
1838
+ const byConv = Boolean(ev.conversationId) && w.conversationId === ev.conversationId && !w.runId;
1839
+ if (!byRun && !byConv)
1836
1840
  continue;
1837
1841
  try {
1838
1842
  w.done(true);
@@ -3213,7 +3217,7 @@ export class PluginManager {
3213
3217
  return { ok: false, error: "无头调用未返回 conversationId" };
3214
3218
  // 默认 120s 超时;上下钳制防 100ms 误杀与无限等待。
3215
3219
  const timeoutMs = Math.max(1000, Math.min(Number(opts?.timeoutMs ?? 120_000) || 120_000, 600_000));
3216
- const ended = await self.waitRunEnd(cid, timeoutMs);
3220
+ const ended = await self.waitRunEnd(cid, timeoutMs, sent?.runId);
3217
3221
  if (!ended)
3218
3222
  return { ok: false, conversationId: cid, error: `等待运行结束超时(约${Math.round(timeoutMs / 1000)}s)` };
3219
3223
  return { ok: true, conversationId: cid };