pi-web-ui 0.105.1 → 0.106.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 (74) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/README.md +193 -797
  3. package/README.zh-CN.md +186 -625
  4. package/README.zh-TW.md +781 -0
  5. package/bin/frp-manager.mjs +1488 -0
  6. package/bin/pi-web-ui.mjs +27 -0
  7. package/deploy/nginx-subpath.conf +16 -1
  8. package/dist/server/agent-service-daemon.js +34 -0
  9. package/dist/server/agent-service.js +227 -44
  10. package/dist/server/claim-files-tool.js +8 -1
  11. package/dist/server/client-state.js +136 -30
  12. package/dist/server/conversation-read-tool.js +12 -4
  13. package/dist/server/delegate-task.js +9 -1
  14. package/dist/server/dispatch-domain-handlers.js +15 -0
  15. package/dist/server/dsh/dsh-agent-service.js +838 -241
  16. package/dist/server/dsh/dsh-client.js +59 -18
  17. package/dist/server/dsh/dsh-market-service.js +233 -0
  18. package/dist/server/dsh/dsh-serialize.js +11 -3
  19. package/dist/server/dsh/dsh-sessions.js +64 -2
  20. package/dist/server/dsh/preset-clones.js +12 -1
  21. package/dist/server/dsh/runtime/goal-rpc.mjs +183 -45
  22. package/dist/server/engine-capabilities.js +72 -0
  23. package/dist/server/engine-probe.js +243 -0
  24. package/dist/server/goal-service.js +23 -12
  25. package/dist/server/i18n.js +20 -1
  26. package/dist/server/index.js +171 -66
  27. package/dist/server/locales.js +1 -0
  28. package/dist/server/mcp-agent-tool.js +10 -7
  29. package/dist/server/mcp-bridge.js +428 -24
  30. package/dist/server/model-admin.js +172 -74
  31. package/dist/server/model-resolver.js +221 -0
  32. package/dist/server/plugin-installer.js +4 -2
  33. package/dist/server/plugins.js +71 -11
  34. package/dist/server/present-files-tool.js +10 -2
  35. package/dist/server/preset-fields.js +14 -0
  36. package/dist/server/preset-share.js +2 -0
  37. package/dist/server/protocol-version.js +1 -1
  38. package/dist/server/schedule-agent-tool.js +2 -1
  39. package/dist/server/scm-commitmsg.js +3 -2
  40. package/dist/server/settings-service.js +10 -2
  41. package/dist/server/skill-discovery.js +161 -0
  42. package/dist/server/skill-tool.js +2 -1
  43. package/dist/server/slash-commands.js +154 -73
  44. package/dist/server/subagent-templates-hant.js +215 -0
  45. package/dist/server/subagent-templates.js +49 -2
  46. package/dist/server/subagents.js +22 -12
  47. package/dist/server/terminals.js +2 -2
  48. package/dist/server/tool-manager.js +3 -0
  49. package/dist/server/universal/driver-base.js +56 -0
  50. package/dist/server/universal/drivers/claude-code.js +462 -0
  51. package/dist/server/universal/drivers/dsh-driver.js +376 -0
  52. package/dist/server/universal/drivers/mock-driver.js +103 -0
  53. package/dist/server/universal/index.js +10 -0
  54. package/dist/server/universal/session-store.js +100 -0
  55. package/dist/server/universal/universal-attachments.js +175 -0
  56. package/dist/server/universal/universal-service.js +149 -0
  57. package/dist/server/universal/universal-session.js +2610 -0
  58. package/dist/server/universal/universal-types.js +4 -0
  59. package/dist/server/update-check.js +4 -1
  60. package/dist/server/worktree-service.js +1 -1
  61. package/dist/server/worktree-tool.js +9 -7
  62. package/package.json +3 -2
  63. package/plugin-sdk/index.d.ts +12 -2
  64. package/plugins/catalog.json +39 -5
  65. package/themes/dark-teal.css +20 -23
  66. package/themes/md-preview.css +1 -2
  67. package/themes/wallpaper-obsidian.css +693 -0
  68. package/web/dist/assets/{TerminalPanel-Mk4laCAL.js → TerminalPanel-CfxKLDW9.js} +2 -2
  69. package/web/dist/assets/index-BtcP6BDk.css +1 -0
  70. package/web/dist/assets/index-XVtCzcHR.js +690 -0
  71. package/web/dist/index.html +2 -2
  72. package/web/dist/sw.js +1 -1
  73. package/web/dist/assets/index-BDLVjBeK.js +0 -690
  74. package/web/dist/assets/index-BQC6lADz.css +0 -1
@@ -254,7 +254,10 @@ export class ModelAdminService {
254
254
  constructor(host) {
255
255
  this.host = host;
256
256
  this.oauthFlows = new ProviderOAuthFlowManager({
257
- modelRuntime: host.modelRuntime,
257
+ modelRuntime: host.modelRuntime ??
258
+ (() => {
259
+ throw new Error("OAuth not supported without ModelRuntime");
260
+ }),
258
261
  emit: host.emit,
259
262
  isDisposed: host.isDisposed,
260
263
  onLoginSuccess: (provider) => this.onOAuthLoginSuccess(provider),
@@ -297,12 +300,12 @@ export class ModelAdminService {
297
300
  async logoutProviderOAuth(provider) {
298
301
  const providerId = provider.trim();
299
302
  try {
300
- const runtime = this.host.modelRuntime();
301
- if (!providerId || !runtime.getProvider(providerId)?.auth.oauth) {
303
+ const runtime = this.host.modelRuntime?.();
304
+ if (!runtime || !providerId || !runtime.getProvider(providerId)?.auth.oauth) {
302
305
  throw new Error("该服务商不支持 OAuth 登录");
303
306
  }
304
307
  await runtime.logout(providerId);
305
- this.host.invalidatePiConfig();
308
+ this.host.invalidatePiConfig?.();
306
309
  await this.host.pushModels();
307
310
  await this.listProviders();
308
311
  this.host.emit({ type: "provider_oauth_logout_result", provider: providerId, ok: true });
@@ -326,7 +329,7 @@ export class ModelAdminService {
326
329
  this.writeProviderKeys(keys);
327
330
  }
328
331
  this.host.onOAuthActivated?.(provider);
329
- this.host.invalidatePiConfig();
332
+ this.host.invalidatePiConfig?.();
330
333
  await this.host.pushModels();
331
334
  await this.listProviders();
332
335
  this.listProviderKeys();
@@ -478,12 +481,18 @@ export class ModelAdminService {
478
481
  const data = this.readProviderKeys();
479
482
  const ids = new Set(Object.keys(data));
480
483
  try {
481
- for (const p of this.host.modelRuntime().getProviders())
482
- ids.add(p.id);
484
+ const mr = this.host.modelRuntime?.();
485
+ if (mr) {
486
+ for (const p of mr.getProviders())
487
+ ids.add(p.id);
488
+ }
483
489
  }
484
490
  catch {
485
491
  // runtime not ready
486
492
  }
493
+ for (const id of ["anthropic", "openai", "google", "deepseek", "groq", "mistral", "openrouter", "ollama"]) {
494
+ ids.add(id);
495
+ }
487
496
  return [...ids];
488
497
  }
489
498
  /** Persist the ACTIVE key's apiKey into auth.json + runtime override + refresh. */
@@ -499,10 +508,12 @@ export class ModelAdminService {
499
508
  }
500
509
  data[pid] = { type: "api_key", key: apiKey };
501
510
  atomicWriteJson(authPath, data);
502
- const mr = this.host.modelRuntime();
503
- await mr.setRuntimeApiKey(pid, apiKey);
504
- await mr.refresh({ allowNetwork: true, providers: [pid] });
505
- this.host.invalidatePiConfig();
511
+ const mr = this.host.modelRuntime?.();
512
+ if (mr) {
513
+ await mr.setRuntimeApiKey(pid, apiKey);
514
+ await mr.refresh({ allowNetwork: true, providers: [pid] });
515
+ }
516
+ this.host.invalidatePiConfig?.();
506
517
  }
507
518
  /** Persist an api-key credential for a provider (auth.json) and apply it now.
508
519
  * Also records the key in provider-keys.json (as the active key), so it shows
@@ -730,10 +741,12 @@ export class ModelAdminService {
730
741
  }
731
742
  delete auth[pid];
732
743
  atomicWriteJson(authPath, auth);
733
- const mr = this.host.modelRuntime();
734
- await mr.removeRuntimeApiKey(pid);
735
- await mr.refresh({ providers: [pid] });
736
- this.host.invalidatePiConfig();
744
+ const mr = this.host.modelRuntime?.();
745
+ if (mr) {
746
+ await mr.removeRuntimeApiKey(pid);
747
+ await mr.refresh({ providers: [pid] });
748
+ }
749
+ this.host.invalidatePiConfig?.();
737
750
  this.host.emit({
738
751
  type: "notice",
739
752
  level: "info",
@@ -788,7 +801,7 @@ export class ModelAdminService {
788
801
  this.host.emit({ type: "notice", level: "error", text: "请填写服务商 ID", textEn: "Enter a provider ID" });
789
802
  return;
790
803
  }
791
- if (this.host.modelRuntime().isUsingOAuth(pid)) {
804
+ if (this.host.modelRuntime?.()?.isUsingOAuth(pid)) {
792
805
  this.host.emit({
793
806
  type: "notice",
794
807
  level: "error",
@@ -826,10 +839,12 @@ export class ModelAdminService {
826
839
  this.writeProviderKeys(keyData);
827
840
  // Drop the runtime override too, then re-read credentials so the
828
841
  // provider goes back to unconfigured and its models leave the list.
829
- const mr = this.host.modelRuntime();
830
- await mr.removeRuntimeApiKey(pid);
831
- await mr.refresh({ providers: [pid] });
832
- this.host.invalidatePiConfig();
842
+ const mr = this.host.modelRuntime?.();
843
+ if (mr) {
844
+ await mr.removeRuntimeApiKey(pid);
845
+ await mr.refresh({ providers: [pid] });
846
+ }
847
+ this.host.invalidatePiConfig?.();
833
848
  this.host.emit({
834
849
  type: "notice",
835
850
  level: "info",
@@ -869,10 +884,28 @@ export class ModelAdminService {
869
884
  fail("请填写服务商 ID", "Enter a provider ID");
870
885
  return;
871
886
  }
872
- const mr = this.host.modelRuntime();
873
- const p = mr.getProvider(pid);
874
- if (!p) {
875
- fail(`供应商 ${pid} 不存在`, `Provider ${pid} does not exist`);
887
+ const mr = this.host.modelRuntime?.();
888
+ const p = mr?.getProvider(pid);
889
+ if (!mr || !p) {
890
+ const { providers } = this.readModelsConfig();
891
+ const saved = providers[pid];
892
+ if (!saved) {
893
+ fail(`供应商 ${pid} 不存在`, `Provider ${pid} does not exist`);
894
+ return;
895
+ }
896
+ this.host.emit({
897
+ type: "clone_provider_result",
898
+ reqId,
899
+ ok: true,
900
+ config: {
901
+ providerId: `${pid}-clone`,
902
+ name: `${saved.name ?? pid} (副本)`,
903
+ baseUrl: saved.baseUrl,
904
+ api: saved.api,
905
+ hasApiKey: false,
906
+ models: Array.isArray(saved.models) ? saved.models : [],
907
+ },
908
+ });
876
909
  return;
877
910
  }
878
911
  const noBaseUrl = !p.baseUrl;
@@ -1038,48 +1071,108 @@ export class ModelAdminService {
1038
1071
  }
1039
1072
  /** Enumerate pi's built-in providers with auth capabilities and status. */
1040
1073
  async listProviders() {
1041
- const mr = this.host.modelRuntime();
1074
+ const mr = this.host.modelRuntime?.();
1042
1075
  let providers;
1043
- try {
1044
- providers = mr.getProviders().map((p) => {
1045
- const supportsApiKey = p.auth.apiKey !== undefined;
1046
- const supportsOAuth = p.auth.oauth !== undefined;
1047
- const oauthName = p.auth.oauth?.name;
1048
- try {
1049
- const st = mr.getProviderAuthStatus(p.id);
1050
- return {
1051
- id: p.id,
1052
- name: p.name,
1053
- configured: st?.configured ?? false,
1054
- source: st?.source,
1055
- supportsApiKey,
1056
- supportsOAuth,
1057
- oauthName,
1058
- usingOAuth: mr.isUsingOAuth(p.id),
1059
- };
1060
- }
1061
- catch {
1062
- // One odd provider must not blank the whole list.
1063
- return {
1064
- id: p.id,
1065
- name: p.name,
1066
- configured: false,
1067
- supportsApiKey,
1068
- supportsOAuth,
1069
- oauthName,
1076
+ if (mr) {
1077
+ try {
1078
+ providers = mr.getProviders().map((p) => {
1079
+ const supportsApiKey = p.auth.apiKey !== undefined;
1080
+ const supportsOAuth = p.auth.oauth !== undefined;
1081
+ const oauthName = p.auth.oauth?.name;
1082
+ try {
1083
+ const st = mr.getProviderAuthStatus(p.id);
1084
+ return {
1085
+ id: p.id,
1086
+ name: p.name,
1087
+ configured: st?.configured ?? false,
1088
+ source: st?.source,
1089
+ supportsApiKey,
1090
+ supportsOAuth,
1091
+ oauthName,
1092
+ usingOAuth: mr.isUsingOAuth(p.id),
1093
+ };
1094
+ }
1095
+ catch {
1096
+ // One odd provider must not blank the whole list.
1097
+ return {
1098
+ id: p.id,
1099
+ name: p.name,
1100
+ configured: false,
1101
+ supportsApiKey,
1102
+ supportsOAuth,
1103
+ oauthName,
1104
+ usingOAuth: false,
1105
+ };
1106
+ }
1107
+ });
1108
+ }
1109
+ catch (err) {
1110
+ this.host.emit({
1111
+ type: "notice",
1112
+ level: "error",
1113
+ text: `获取服务商列表失败:${err.message}`,
1114
+ textEn: `Failed to fetch provider list: ${err.message}`,
1115
+ });
1116
+ return;
1117
+ }
1118
+ }
1119
+ else {
1120
+ // 非 pi 引擎:根据 models.json + auth.json + provider-keys.json + 常见官方列表综合列出
1121
+ let auth = {};
1122
+ try {
1123
+ auth = JSON.parse(readFileSync(join(this.host.agentDir, "auth.json"), "utf8"));
1124
+ }
1125
+ catch {
1126
+ /* ignore */
1127
+ }
1128
+ const keyData = this.readProviderKeys();
1129
+ const { providers: custom } = this.readModelsConfig();
1130
+ const builtins = [
1131
+ { id: "anthropic", name: "Anthropic" },
1132
+ { id: "openai", name: "OpenAI" },
1133
+ { id: "deepseek", name: "DeepSeek" },
1134
+ { id: "google", name: "Google Gemini" },
1135
+ { id: "openrouter", name: "OpenRouter" },
1136
+ { id: "groq", name: "Groq" },
1137
+ { id: "mistral", name: "Mistral" },
1138
+ { id: "ollama", name: "Ollama" },
1139
+ ];
1140
+ const allIds = new Set();
1141
+ providers = [];
1142
+ for (const b of builtins) {
1143
+ allIds.add(b.id);
1144
+ const hasStored = Boolean(auth[b.id] || (keyData[b.id]?.keys.length ?? 0) > 0);
1145
+ const hasEnv = Boolean((b.id === "anthropic" && process.env.ANTHROPIC_API_KEY) ||
1146
+ (b.id === "deepseek" && process.env.DEEPSEEK_API_KEY) ||
1147
+ (b.id === "openai" && process.env.OPENAI_API_KEY) ||
1148
+ (b.id === "openrouter" && process.env.OPENROUTER_API_KEY) ||
1149
+ (b.id === "google" && (process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY)));
1150
+ providers.push({
1151
+ id: b.id,
1152
+ name: b.name,
1153
+ configured: hasStored || hasEnv,
1154
+ source: (hasStored ? "stored" : hasEnv ? "environment" : undefined),
1155
+ supportsApiKey: true,
1156
+ supportsOAuth: false,
1157
+ usingOAuth: false,
1158
+ });
1159
+ }
1160
+ for (const [cid, c] of Object.entries(custom)) {
1161
+ if (!allIds.has(cid)) {
1162
+ allIds.add(cid);
1163
+ const hasKey = typeof c.apiKey === "string" && c.apiKey.trim() !== "";
1164
+ const hasStored = Boolean(auth[cid] || (keyData[cid]?.keys.length ?? 0) > 0);
1165
+ providers.push({
1166
+ id: cid,
1167
+ name: c.name || cid,
1168
+ configured: hasKey || hasStored,
1169
+ source: (hasKey ? "stored" : hasStored ? "stored" : undefined),
1170
+ supportsApiKey: true,
1171
+ supportsOAuth: false,
1070
1172
  usingOAuth: false,
1071
- };
1173
+ });
1072
1174
  }
1073
- });
1074
- }
1075
- catch (err) {
1076
- this.host.emit({
1077
- type: "notice",
1078
- level: "error",
1079
- text: `获取服务商列表失败:${err.message}`,
1080
- textEn: `Failed to fetch provider list: ${err.message}`,
1081
- });
1082
- return;
1175
+ }
1083
1176
  }
1084
1177
  if (providers.length === 0) {
1085
1178
  this.host.emit({
@@ -1185,8 +1278,8 @@ export class ModelAdminService {
1185
1278
  * repush — same refresh tail that save_model_config runs. */
1186
1279
  async reloadModelsConfig() {
1187
1280
  try {
1188
- await this.host.modelRuntime().refresh();
1189
- this.host.invalidatePiConfig();
1281
+ await this.host.modelRuntime?.()?.refresh();
1282
+ this.host.invalidatePiConfig?.();
1190
1283
  await this.listModelsConfig();
1191
1284
  await this.host.pushModels();
1192
1285
  this.host.emit({
@@ -1442,7 +1535,7 @@ export class ModelAdminService {
1442
1535
  // 纯覆盖条目(只改 models,没有 provider 级 baseUrl)回退到运行时
1443
1536
  // 已知的地址——内置 provider 的 baseUrl 本来就不在 models.json 里。
1444
1537
  // 注意只拿来探测用,不写回磁盘:保持条目仍是纯覆盖。
1445
- const baseUrl = saved?.baseUrl?.trim() || (this.host.modelRuntime().getProvider(pid)?.baseUrl ?? "").trim() || undefined;
1538
+ const baseUrl = saved?.baseUrl?.trim() || (this.host.modelRuntime?.()?.getProvider(pid)?.baseUrl ?? "").trim() || undefined;
1446
1539
  if (!saved || !baseUrl) {
1447
1540
  this.host.emit({
1448
1541
  type: "notice",
@@ -1519,7 +1612,12 @@ export class ModelAdminService {
1519
1612
  async refreshBuiltinModels(reqId) {
1520
1613
  const done = (ok, error) => this.host.emit({ type: "refresh_builtin_result", reqId, ok, ...(error ? { error } : {}) });
1521
1614
  try {
1522
- const mr = this.host.modelRuntime();
1615
+ const mr = this.host.modelRuntime?.();
1616
+ if (!mr) {
1617
+ await this.listProviders();
1618
+ await this.host.pushModels();
1619
+ return done(true);
1620
+ }
1523
1621
  const res = await mr.refresh({
1524
1622
  allowNetwork: true,
1525
1623
  force: true,
@@ -1533,7 +1631,7 @@ export class ModelAdminService {
1533
1631
  if (graduated.length > 0) {
1534
1632
  await mr.refresh();
1535
1633
  }
1536
- this.host.invalidatePiConfig();
1634
+ this.host.invalidatePiConfig?.();
1537
1635
  await this.host.pushModels();
1538
1636
  await this.listProviders();
1539
1637
  const failures = [...res.errors.entries()].map(([pid, err]) => `${pid} (${err.message})`);
@@ -1656,14 +1754,14 @@ export class ModelAdminService {
1656
1754
  "key" in credential &&
1657
1755
  typeof credential.key === "string" &&
1658
1756
  credential.key.trim()) {
1659
- await this.host.modelRuntime().setRuntimeApiKey(pid, credential.key);
1757
+ await this.host.modelRuntime?.()?.setRuntimeApiKey(pid, credential.key);
1660
1758
  }
1661
1759
  }
1662
1760
  catch {
1663
1761
  // auth.json is optional; models.json can still use its own apiKey.
1664
1762
  }
1665
- await this.host.modelRuntime().refresh();
1666
- this.host.invalidatePiConfig();
1763
+ await this.host.modelRuntime?.()?.refresh();
1764
+ this.host.invalidatePiConfig?.();
1667
1765
  await this.listModelsConfig();
1668
1766
  await this.host.pushModels();
1669
1767
  }
@@ -1706,7 +1804,7 @@ export class ModelAdminService {
1706
1804
  return fail(`接口地址无效:${baseUrl}(仅支持 http/https,留空则自动继承)`, `Invalid baseUrl: ${baseUrl} (http/https only; leave blank to inherit)`);
1707
1805
  }
1708
1806
  }
1709
- if (!this.host.modelRuntime().getProvider(pid)) {
1807
+ if (this.host.modelRuntime && !this.host.modelRuntime().getProvider(pid)) {
1710
1808
  return fail(`供应商 ${pid} 不存在`, `Provider ${pid} does not exist`);
1711
1809
  }
1712
1810
  const { providers } = this.readModelsConfig();
@@ -1801,8 +1899,8 @@ export class ModelAdminService {
1801
1899
  }
1802
1900
  delete providers[providerId];
1803
1901
  atomicWriteJson(this.modelsConfigPath(), { providers });
1804
- await this.host.modelRuntime().refresh();
1805
- this.host.invalidatePiConfig();
1902
+ await this.host.modelRuntime?.()?.refresh();
1903
+ this.host.invalidatePiConfig?.();
1806
1904
  await this.listModelsConfig();
1807
1905
  await this.host.pushModels();
1808
1906
  this.host.emit({
@@ -0,0 +1,221 @@
1
+ /**
2
+ * model-resolver.ts — 跨引擎通用模型与服务商凭据解析器。
3
+ *
4
+ * 职责:
5
+ * 作为宿主级模型配置基础层的只读解析器,统一读取与解析:
6
+ * 1. `<agentDir>/models.json`(自定义服务商、BaseURL、API 类型、模型列表与内置覆盖)
7
+ * 2. `<agentDir>/auth.json`(持久化 API 密钥)
8
+ * 3. `<agentDir>/provider-keys.json`(多密钥管理与当前激活密钥)
9
+ * 4. 进程环境变量回退(如 ANTHROPIC_API_KEY, DEEPSEEK_API_KEY 等)
10
+ *
11
+ * 供 Claude Code CLI 驱动、DSH 引擎与 Pi 引擎统一调用,消除各引擎间的配置孤岛。
12
+ */
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { join } from "node:path";
16
+ function defaultAgentDir(agentDir) {
17
+ return agentDir && agentDir.trim()
18
+ ? agentDir.trim()
19
+ : (process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"));
20
+ }
21
+ /** 剥离 JSON 字符串中的 // 和 /* *\/ 注释(保护字符串字面量内的 URL) */
22
+ export function stripJsonComments(src) {
23
+ let out = "";
24
+ let inString = false;
25
+ let i = 0;
26
+ while (i < src.length) {
27
+ const c = src[i];
28
+ const next = src[i + 1];
29
+ if (inString) {
30
+ out += c;
31
+ if (c === "\\") {
32
+ out += next ?? "";
33
+ i += 2;
34
+ continue;
35
+ }
36
+ if (c === '"')
37
+ inString = false;
38
+ i++;
39
+ continue;
40
+ }
41
+ if (c === '"') {
42
+ inString = true;
43
+ out += c;
44
+ i++;
45
+ continue;
46
+ }
47
+ if (c === "/" && next === "/") {
48
+ while (i < src.length && src[i] !== "\n")
49
+ i++;
50
+ continue;
51
+ }
52
+ if (c === "/" && next === "*") {
53
+ i += 2;
54
+ while (i < src.length && !(src[i] === "*" && src[i + 1] === "/"))
55
+ i++;
56
+ i += 2;
57
+ continue;
58
+ }
59
+ out += c;
60
+ i++;
61
+ }
62
+ return out;
63
+ }
64
+ /** 读取并解析 models.json(容忍注释) */
65
+ export function readModelsJson(agentDir) {
66
+ const dir = defaultAgentDir(agentDir);
67
+ const filePath = join(dir, "models.json");
68
+ if (!existsSync(filePath))
69
+ return { providers: {} };
70
+ try {
71
+ const raw = readFileSync(filePath, "utf8");
72
+ const parsed = JSON.parse(stripJsonComments(raw));
73
+ return { providers: parsed?.providers ?? {} };
74
+ }
75
+ catch {
76
+ return { providers: {} };
77
+ }
78
+ }
79
+ /** 读取并解析 auth.json */
80
+ export function readAuthJson(agentDir) {
81
+ const dir = defaultAgentDir(agentDir);
82
+ const filePath = join(dir, "auth.json");
83
+ if (!existsSync(filePath))
84
+ return {};
85
+ try {
86
+ const raw = readFileSync(filePath, "utf8");
87
+ return JSON.parse(raw) ?? {};
88
+ }
89
+ catch {
90
+ return {};
91
+ }
92
+ }
93
+ /** 读取并解析 provider-keys.json */
94
+ export function readProviderKeysJson(agentDir) {
95
+ const dir = defaultAgentDir(agentDir);
96
+ const filePath = join(dir, "provider-keys.json");
97
+ if (!existsSync(filePath))
98
+ return {};
99
+ try {
100
+ const raw = readFileSync(filePath, "utf8");
101
+ return JSON.parse(raw);
102
+ }
103
+ catch {
104
+ return {};
105
+ }
106
+ }
107
+ /**
108
+ * 为指定 provider 解析完整凭据(BaseURL、API Key、API 类型、自定义 Headers)。
109
+ * 优先级:models.json 明确定义 > provider-keys.json 激活密钥 > auth.json > 环境变量。
110
+ */
111
+ export function resolveProviderCredential(agentDir, providerId) {
112
+ const dir = defaultAgentDir(agentDir);
113
+ const pid = providerId.trim();
114
+ const { providers } = readModelsJson(dir);
115
+ const prov = providers[pid];
116
+ let baseUrl = typeof prov?.baseUrl === "string" ? prov.baseUrl.trim() : undefined;
117
+ let apiKey = typeof prov?.apiKey === "string" ? prov.apiKey.trim() : undefined;
118
+ const api = typeof prov?.api === "string" ? prov.api.trim() : undefined;
119
+ const headers = prov?.headers && typeof prov.headers === "object" && !Array.isArray(prov.headers)
120
+ ? prov.headers
121
+ : undefined;
122
+ // 1. 若 models.json 未显式配置 apiKey,则从 provider-keys.json 取激活密钥
123
+ if (!apiKey) {
124
+ const multiKeys = readProviderKeysJson(dir);
125
+ const entry = multiKeys[pid];
126
+ if (entry?.keys && entry.keys.length > 0) {
127
+ const active = entry.keys.find((k) => k.name === entry.activeKeyName);
128
+ apiKey = active?.apiKey ?? entry.keys[0]?.apiKey;
129
+ }
130
+ }
131
+ // 2. 若仍无 apiKey,回落到 auth.json
132
+ if (!apiKey) {
133
+ const auth = readAuthJson(dir);
134
+ const authEntry = auth[pid];
135
+ if (authEntry && typeof authEntry === "object" && "key" in authEntry) {
136
+ const k = authEntry.key;
137
+ if (typeof k === "string" && k.trim())
138
+ apiKey = k.trim();
139
+ }
140
+ else if (typeof authEntry === "string" && authEntry.trim()) {
141
+ apiKey = authEntry.trim();
142
+ }
143
+ }
144
+ // 3. 环境变量兜底
145
+ if (!apiKey) {
146
+ const normPid = pid.toLowerCase();
147
+ if (normPid === "anthropic" || normPid.includes("claude")) {
148
+ apiKey = process.env.ANTHROPIC_API_KEY?.trim();
149
+ }
150
+ else if (normPid === "deepseek") {
151
+ apiKey = process.env.DEEPSEEK_API_KEY?.trim();
152
+ }
153
+ else if (normPid === "openai") {
154
+ apiKey = process.env.OPENAI_API_KEY?.trim();
155
+ }
156
+ else if (normPid === "openrouter") {
157
+ apiKey = process.env.OPENROUTER_API_KEY?.trim();
158
+ }
159
+ else if (normPid === "google" || normPid.includes("gemini")) {
160
+ apiKey = process.env.GEMINI_API_KEY?.trim() ?? process.env.GOOGLE_API_KEY?.trim();
161
+ }
162
+ }
163
+ if (!baseUrl) {
164
+ const normPid = pid.toLowerCase();
165
+ if (normPid === "anthropic" || normPid.includes("claude")) {
166
+ baseUrl = process.env.ANTHROPIC_BASE_URL?.trim();
167
+ }
168
+ else if (normPid === "deepseek") {
169
+ baseUrl = process.env.DEEPSEEK_BASE_URL?.trim();
170
+ }
171
+ else if (normPid === "openai") {
172
+ baseUrl = process.env.OPENAI_BASE_URL?.trim();
173
+ }
174
+ }
175
+ return {
176
+ providerId: pid,
177
+ baseUrl: baseUrl || undefined,
178
+ apiKey: apiKey || undefined,
179
+ api: api || undefined,
180
+ headers,
181
+ };
182
+ }
183
+ /**
184
+ * 从 models.json 中列出所有自定义模型。
185
+ * 可选 filter 谓词过滤 API 类型(如只挑 Claude 兼容的)。
186
+ */
187
+ export function listCustomModelsFromConfig(agentDir, filter) {
188
+ const dir = defaultAgentDir(agentDir);
189
+ const { providers } = readModelsJson(dir);
190
+ const results = [];
191
+ for (const [providerId, p] of Object.entries(providers)) {
192
+ const api = typeof p.api === "string" ? p.api.trim() : undefined;
193
+ const baseUrl = typeof p.baseUrl === "string" ? p.baseUrl.trim() : undefined;
194
+ const providerName = typeof p.name === "string" ? p.name.trim() : undefined;
195
+ if (filter && !filter({ providerId, api, baseUrl })) {
196
+ continue;
197
+ }
198
+ if (Array.isArray(p.models)) {
199
+ for (const m of p.models) {
200
+ if (!m || typeof m !== "object")
201
+ continue;
202
+ const row = m;
203
+ const modelId = typeof row.id === "string" ? row.id.trim() : "";
204
+ if (!modelId)
205
+ continue;
206
+ const name = typeof row.name === "string" && row.name.trim() ? row.name.trim() : modelId;
207
+ results.push({
208
+ providerId,
209
+ providerName,
210
+ modelId,
211
+ name,
212
+ api,
213
+ baseUrl,
214
+ reasoning: Boolean(row.reasoning),
215
+ vision: Array.isArray(row.input) ? row.input.includes("image") : undefined,
216
+ });
217
+ }
218
+ }
219
+ }
220
+ return results;
221
+ }
@@ -251,8 +251,10 @@ export class PluginInstaller {
251
251
  child.on("close", (code) => {
252
252
  if (cancelled)
253
253
  return finish(false, pick(l, "作业已取消", "Job cancelled", "plugininstaller.cancelled"));
254
- if (timedOut)
255
- return finish(false, pick(l, `作业超时(${Math.round(Math.max(1000, Number(this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS)) / 60000)} 分钟)已终止`, `Job timed out after ${Math.round(Math.max(1000, Number(this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS)) / 60000)} min and was killed`, "plugininstaller.timeout"));
254
+ if (timedOut) {
255
+ const min = Math.round(Math.max(1000, Number(this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS)) / 60000);
256
+ return finish(false, pick(l, `作业超时(${min} 分钟)已终止`, `Job timed out after ${min} min and was killed`, "plugininstaller.timeout", { min }));
257
+ }
256
258
  finish(code === 0, code === 0 ? undefined : `exit code ${code}`);
257
259
  });
258
260
  emit({ type: "plugin_job", jobId, action, pluginId, phase: "start" });