pi-model-manager 0.1.0 → 0.2.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.
package/tui/dashboard.ts CHANGED
@@ -37,9 +37,9 @@ import { editModel } from "./editor-model.ts";
37
37
  import { editProvider } from "./editor-provider.ts";
38
38
  import { showPersistentShortcutMenu, type MenuCursor } from "./persistent-menu.ts";
39
39
  import {
40
- PROVIDER_CONSOLE_HEADER,
41
40
  formatModelListHeader,
42
41
  formatModelListRow,
42
+ formatProviderConsoleHeader,
43
43
  formatProviderConsoleRow,
44
44
  formatProviderDetailLines,
45
45
  formatProviderEndpointLine,
@@ -58,8 +58,9 @@ interface ProviderMenuRow {
58
58
  label: string;
59
59
  }
60
60
 
61
- function buildRows(document: StateDocument): DashboardRow[] {
61
+ function buildRows(document: StateDocument, builtInProviderIds: ReadonlySet<string>): DashboardRow[] {
62
62
  return Object.keys(document.providers)
63
+ .filter((providerId) => !builtInProviderIds.has(providerId))
63
64
  .sort((a, b) => a.localeCompare(b))
64
65
  .map((providerId) => ({
65
66
  providerId,
@@ -249,7 +250,11 @@ async function showProviderMenu(pi: ExtensionAPI, ctx: ExtensionCommandContext,
249
250
  formatProviderSummaryLine(currentProvider, state.requestHeaderProfiles),
250
251
  formatProviderEndpointLine(currentProvider),
251
252
  ],
252
- tableHeader: formatModelListHeader(currentProvider),
253
+ tableHeader: (width) => formatModelListHeader(currentProvider, width),
254
+ formatRow: (menuRow, width) => {
255
+ const row = rows[Number.parseInt(menuRow.id, 10)];
256
+ return row ? formatModelListRow(currentProvider, row.model, width) : menuRow.label;
257
+ },
253
258
  visibleRows: Math.min(12, Math.max(1, rows.length)),
254
259
  footer: "↑↓ 选择 Enter 编辑模型 a 添加模型 e 编辑接入 d 删除模型 Esc 返回",
255
260
  emptyLabel: "暂无模型;按 a 添加第一个模型",
@@ -323,8 +328,9 @@ export async function runDashboard(pi: ExtensionAPI, ctx: ExtensionCommandContex
323
328
  const cursor: MenuCursor = { index: 0 };
324
329
  while (true) {
325
330
  const state = await readState();
326
- const rows = buildRows(state);
327
- const modelCount = Object.values(state.providers).reduce((sum, provider) => sum + provider.models.length, 0);
331
+ const builtInProviderIds = await getBuiltinProviderIds();
332
+ const rows = buildRows(state, builtInProviderIds);
333
+ const modelCount = rows.reduce((sum, row) => sum + (state.providers[row.providerId]?.models.length ?? 0), 0);
328
334
  const profileCount = Object.keys(state.requestHeaderProfiles).length;
329
335
  const captureCount = Object.keys(state.clientHeaderCaptures).length;
330
336
  const menuRows = rows.map((r, index) => ({ id: `${index}`, label: r.label }));
@@ -341,7 +347,14 @@ export async function runDashboard(pi: ExtensionAPI, ctx: ExtensionCommandContex
341
347
  ],
342
348
  {
343
349
  summaryLines: [`${rows.length} 接入 · ${modelCount} 模型 · ${captureCount} 内置抓包 · ${profileCount} 自定义请求头`],
344
- tableHeader: PROVIDER_CONSOLE_HEADER,
350
+ tableHeader: formatProviderConsoleHeader,
351
+ formatRow: (menuRow, width) => {
352
+ const row = rows[Number.parseInt(menuRow.id, 10)];
353
+ const provider = row ? state.providers[row.providerId] : undefined;
354
+ return row && provider
355
+ ? formatProviderConsoleRow(row.providerId, provider, state.requestHeaderProfiles, width)
356
+ : menuRow.label;
357
+ },
345
358
  getDetailLines: (selectedRow) => {
346
359
  const row = rows[Number.parseInt(selectedRow?.id ?? "", 10)];
347
360
  const provider = row ? state.providers[row.providerId] : undefined;
@@ -6,8 +6,8 @@
6
6
  // - 提供"从上游拉取模型 ID 列表"入口(OpenAI/Anthropic/Google)
7
7
  // - 支持视觉用开关式 select,保存时仍映射为 text / text,image
8
8
 
9
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
10
- import type { AnthropicThinkingProtocol, BuiltInClientHeaderProfileId, ModelDraft, ReasoningMode, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
9
+ import { BorderedLoader, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
10
+ import type { AnthropicThinkingProtocol, BuiltInClientHeaderProfileId, ModelDraft, ModelListFetchOutcome, ReasoningMode, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
11
11
  import { fetchModelIds } from "./model-list-fetch.ts";
12
12
  import { pickModelIdFromList } from "./model-picker.ts";
13
13
  import { showPersistentFormMenu, showPersistentMenu, padLabel, type HorizontalDirection, type MenuCursor } from "./persistent-menu.ts";
@@ -127,8 +127,7 @@ async function pickModelFromUpstream(
127
127
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
128
128
  clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
129
129
  ): Promise<void> {
130
- ctx.ui.notify("正在拉取模型列表(10 秒超时)…", "info");
131
- const outcome = await fetchModelIds({
130
+ const params = {
132
131
  providerId: draft.providerId,
133
132
  api: draft.api,
134
133
  baseUrl: draft.baseUrl,
@@ -139,7 +138,22 @@ async function pickModelFromUpstream(
139
138
  httpProxyEnabled: draft.httpProxyEnabled,
140
139
  httpProxyUrl: draft.httpProxyUrl,
141
140
  clientHeaderCaptures,
141
+ };
142
+ const outcome = await ctx.ui.custom<ModelListFetchOutcome>((tui, theme, _keybindings, done) => {
143
+ const loader = new BorderedLoader(tui, theme, "正在拉取模型列表,总计最多 10 秒…", { cancellable: true });
144
+ let settled = false;
145
+ const finish = (result: ModelListFetchOutcome) => {
146
+ if (settled) return;
147
+ settled = true;
148
+ done(result);
149
+ };
150
+ loader.onAbort = () => finish({ status: "cancelled" });
151
+ fetchModelIds(params, loader.signal)
152
+ .then(finish)
153
+ .catch((error) => finish({ status: "failed", message: error instanceof Error ? error.message : String(error) }));
154
+ return loader;
142
155
  });
156
+ if (outcome.status === "cancelled") return;
143
157
  if (outcome.status === "failed") {
144
158
  ctx.ui.notify(`拉取失败:${outcome.message}`, "warning");
145
159
  const fallback = await ctx.ui.input(`手动输入模型 ID(当前:${draft.modelId || "<空>"})`, draft.modelId);
@@ -5,7 +5,8 @@
5
5
 
6
6
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
7
  import { hasStringRecordEntries } from "../common.ts";
8
- import { findPresetForApi } from "../presets/providers.ts";
8
+ import { switchProviderDraftApiPreset } from "../presets/providers.ts";
9
+ import { redactUrlForDisplay } from "../sensitive-redaction.ts";
9
10
  import { DEFAULT_PROVIDER_HTTP_PROXY_URL } from "../types.ts";
10
11
  import { showPersistentFormMenu, padLabel, type HorizontalDirection, type MenuCursor } from "./persistent-menu.ts";
11
12
  import {
@@ -39,7 +40,7 @@ function buildRows(
39
40
  { id: "providerName", label: "名称", value: draft.providerName || "<空>" },
40
41
  { id: "baseUrl", label: "Base URL", value: draft.baseUrl },
41
42
  { id: "httpProxyEnabled", label: "本机代理", value: draft.httpProxyEnabled ? "开启" : "关闭" },
42
- { id: "httpProxyUrl", label: "代理地址", value: draft.httpProxyEnabled ? (draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL) : "关闭时不使用" },
43
+ { id: "httpProxyUrl", label: "代理地址", value: draft.httpProxyEnabled ? redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL) : "关闭时不使用" },
43
44
  { id: "apiKey", label: "API key", value: maskSecret(draft.apiKey) },
44
45
  { id: "authHeader", label: "认证头", value: draft.authHeader ? "Bearer" : "默认" },
45
46
  { id: "clientHeaderProfile", label: "请求头", value: profileDisplay },
@@ -113,11 +114,7 @@ async function editField(
113
114
  ): Promise<void> {
114
115
  if (fieldId === "api") {
115
116
  const choice = await selectChoice(ctx, "选择 API 协议", API_CHOICES, draft.api);
116
- if (choice) {
117
- draft.api = choice.id;
118
- const preset = findPresetForApi(draft.api);
119
- if (!draft.baseUrl.trim()) draft.baseUrl = preset.baseUrl;
120
- }
117
+ if (choice) switchProviderDraftApiPreset(draft, choice.id);
121
118
  return;
122
119
  }
123
120
  if (fieldId === "authHeader") {
@@ -135,7 +132,7 @@ async function editField(
135
132
  if (fieldId === "httpProxyEnabled") {
136
133
  const choice = await ctx.ui.select("本机代理(仅当前接入点)", [
137
134
  "关闭 — 请求直连上游",
138
- `开启 — 通过 ${draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL}`,
135
+ `开启 — 通过 ${redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL)}`,
139
136
  ]);
140
137
  if (!choice) return;
141
138
  draft.httpProxyEnabled = choice.startsWith("开启");
@@ -155,6 +152,12 @@ async function editField(
155
152
  if (value !== undefined) draft.providerName = value.trim();
156
153
  return;
157
154
  }
155
+ if (fieldId === "httpProxyUrl") {
156
+ const currentLabel = redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL);
157
+ const value = await ctx.ui.input(`代理地址(http/https;当前:${currentLabel},留空保持原值)`, "");
158
+ if (value?.trim()) draft.httpProxyUrl = value.trim();
159
+ return;
160
+ }
158
161
  if (fieldId === "apiKey") {
159
162
  const currentLabel = draft.apiKey ? maskSecret(draft.apiKey) : "<空>";
160
163
  const value = await ctx.ui.input(`API key(可选;明文 / $ENV_VAR / !command;当前:${currentLabel},留空清除)`, "");
@@ -164,8 +167,6 @@ async function editField(
164
167
  }
165
168
  const prompt = ({
166
169
  baseUrl: "Base URL(http/https)",
167
- httpProxyUrl: "代理地址(http://host:port 或 https://host:port)",
168
- apiKey: "API key(可选;明文 / $ENV_VAR / !command)",
169
170
  } as Record<string, string>)[fieldId];
170
171
  const current = (draft as any)[fieldId] as string;
171
172
  const value = await ctx.ui.input(`${prompt ?? fieldId}(当前:${current || "<空>"},留空保持原值)`, current);
@@ -16,6 +16,7 @@ import {
16
16
  import { readState } from "../state-store.ts";
17
17
  import type { RequestHeaderProfileDraft, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
18
18
  import { padLabel, showPersistentFormMenu, showPersistentShortcutMenu, type MenuCursor } from "./persistent-menu.ts";
19
+ import { fitColumn } from "./ui-helpers.ts";
19
20
 
20
21
  interface ProfileRow {
21
22
  profileId: string;
@@ -69,8 +70,55 @@ function formatCaptureLine(label: string, capture: StoredClientHeaderCapture | u
69
70
  return ` ${padLabel(label, 12)} 已抓包 ${formatCapturedAt(capture.capturedAt)} · ${Object.keys(capture.headers).length} headers`;
70
71
  }
71
72
 
72
- function formatProfileRow(profileId: string, profile: StoredRequestHeaderProfile, usedCount: number): string {
73
- return `${padLabel(profileId, 22)} ${padLabel(`${Object.keys(profile.headers).length} headers`, 12)} ${padLabel(`${usedCount} models`, 10)} ${profile.name}`.trimEnd();
73
+ interface ProfileTableCells {
74
+ profileId: string;
75
+ headers: string;
76
+ used: string;
77
+ name: string;
78
+ }
79
+
80
+ function formatProfileTableRow(cells: ProfileTableCells, availableWidth: number): string {
81
+ if (availableWidth >= 64) {
82
+ return [
83
+ fitColumn(cells.profileId, 22),
84
+ fitColumn(cells.headers, 12),
85
+ fitColumn(cells.used, 10),
86
+ fitColumn(cells.name, Math.max(10, availableWidth - 47)),
87
+ ].join(" ");
88
+ }
89
+ if (availableWidth >= 46) {
90
+ return [fitColumn(cells.profileId, 22), fitColumn(cells.headers, 12), fitColumn(cells.used, 10)].join(" ");
91
+ }
92
+ if (availableWidth >= 33) {
93
+ return [fitColumn(cells.profileId, 20), fitColumn(cells.headers, 12)].join(" ");
94
+ }
95
+ return [
96
+ fitColumn(cells.profileId, Math.max(8, availableWidth - 11)),
97
+ fitColumn(cells.headers, 10),
98
+ ].join(" ");
99
+ }
100
+
101
+ function formatProfileRow(
102
+ profileId: string,
103
+ profile: StoredRequestHeaderProfile,
104
+ usedCount: number,
105
+ availableWidth = 78,
106
+ ): string {
107
+ return formatProfileTableRow({
108
+ profileId,
109
+ headers: `${Object.keys(profile.headers).length} headers`,
110
+ used: `${usedCount} models`,
111
+ name: profile.name,
112
+ }, availableWidth);
113
+ }
114
+
115
+ function formatProfileTableHeader(menuWidth: number): string {
116
+ return ` ${formatProfileTableRow({
117
+ profileId: "自定义 ID",
118
+ headers: "Headers",
119
+ used: "Used",
120
+ name: "名称",
121
+ }, Math.max(0, menuWidth - 2))}`;
74
122
  }
75
123
 
76
124
  function formatProfileDetailLines(profileId: string, profile: StoredRequestHeaderProfile, usedCount: number): string[] {
@@ -273,7 +321,14 @@ export async function runHeaderProfilesPanel(pi: ExtensionAPI, ctx: ExtensionCom
273
321
  formatCaptureLine("Codex", state.clientHeaderCaptures["codex-cli"]),
274
322
  `Custom profiles: ${rows.length}`,
275
323
  ],
276
- tableHeader: `${padLabel("自定义 ID", 22)} ${padLabel("Headers", 12)} ${padLabel("Used", 10)} 名称`,
324
+ tableHeader: formatProfileTableHeader,
325
+ formatRow: (menuRow, width) => {
326
+ const row = rows[Number.parseInt(menuRow.id, 10)];
327
+ const profile = row ? state.requestHeaderProfiles[row.profileId] : undefined;
328
+ return row && profile
329
+ ? formatProfileRow(row.profileId, profile, countModelsUsingRequestHeaderProfile(state, row.profileId), width)
330
+ : menuRow.label;
331
+ },
277
332
  getDetailLines: (selectedRow) => {
278
333
  const row = rows[Number.parseInt(selectedRow?.id ?? "", 10)];
279
334
  const profile = row ? state.requestHeaderProfiles[row.profileId] : undefined;
@@ -1,12 +1,14 @@
1
1
  // 从上游 API 拉取模型列表(OpenAI / Anthropic / Google)。
2
- // 拉取失败 / 取消时给用户 fallback 到手动输入。
2
+ // 整次发现共享一个 10 秒 AbortSignal,并限制响应体、模型数量与终端不安全字符。
3
3
 
4
4
  import { ModelRuntime, type ProviderConfig } from "@earendil-works/pi-coding-agent";
5
- import { formatUnknownError, isObjectRecord } from "../common.ts";
5
+ import { formatUnknownError } from "../common.ts";
6
6
  import { openTemporaryLocalProxyRoute, type TemporaryLocalProxyRoute } from "../local-proxy-service.ts";
7
7
  import { getClientHeadersForProfile } from "../presets/client-headers.ts";
8
- import { resolveRuntimeBaseUrl } from "../runtime-base-url.ts";
8
+ import { appendUrlPath, resolveRuntimeBaseUrl } from "../runtime-base-url.ts";
9
+ import { isSensitiveHeaderName, redactSensitiveText } from "../sensitive-redaction.ts";
9
10
  import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, ModelListFetchOutcome, StoredClientHeaderCapture } from "../types.ts";
11
+ import { extractValidatedModelIds, readBoundedResponseText } from "./model-list-validation.ts";
10
12
 
11
13
  const MODEL_LIST_TIMEOUT_MS = 10_000;
12
14
  const TEMP_PROVIDER_ID = "pi-model-manager-fetch";
@@ -28,71 +30,50 @@ const emptyCredentialStore = {
28
30
  },
29
31
  };
30
32
 
31
- function escapeRegExp(value: string): string {
32
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33
- }
34
-
35
- function redactSecrets(message: string, secrets: string[]): string {
36
- let redacted = message;
37
- for (const secret of secrets) {
38
- if (secret.length < 3) continue;
39
- redacted = redacted.replace(new RegExp(escapeRegExp(secret), "g"), "REDACTED");
33
+ function hasRootPath(baseUrl: string): boolean {
34
+ try {
35
+ const pathname = new URL(baseUrl.trim()).pathname.replace(/\/+$/, "");
36
+ return pathname === "";
37
+ } catch {
38
+ return false;
40
39
  }
41
- redacted = redacted.replace(/([?&]key=)[^&\s]+/gi, "$1REDACTED");
42
- redacted = redacted.replace(/(Authorization:\s*Bearer\s+)[^\s,;]+/gi, "$1REDACTED");
43
- redacted = redacted.replace(/((?:x-api-key|api-key)\s*[:=]\s*)[^\s,;]+/gi, "$1REDACTED");
44
- return redacted;
45
40
  }
46
41
 
47
42
  function buildOpenAIUrl(baseUrl: string, api: Extract<ApiKind, "openai-completions" | "openai-responses">): string {
48
- return `${resolveRuntimeBaseUrl(api, baseUrl)}/models`;
43
+ return appendUrlPath(resolveRuntimeBaseUrl(api, baseUrl), "models");
49
44
  }
50
45
 
51
46
  function buildAnthropicUrl(baseUrl: string): string {
52
- // 根路径(无 path)追加 /v1/models,自定义后缀直接追加 /models
53
- const trimmed = baseUrl.trim().replace(/\/+$/, "");
54
- try {
55
- const parsed = new URL(trimmed);
56
- if ((parsed.pathname === "" || parsed.pathname === "/") && !parsed.search && !parsed.hash) {
57
- return `${trimmed}/v1/models`;
58
- }
59
- } catch {
60
- return `${trimmed}/models`;
61
- }
62
- return `${trimmed}/models`;
47
+ return hasRootPath(baseUrl)
48
+ ? appendUrlPath(baseUrl, "v1", "models")
49
+ : appendUrlPath(baseUrl, "models");
63
50
  }
64
51
 
65
- /** 从 baseUrl 提取主机根路径(不含路径部分)。
66
- * 例:"https://api.deepseek.com/anthropic" → "https://api.deepseek.com" */
67
- function deriveOrigin(url: string): string {
68
- try {
69
- const parsed = new URL(url);
70
- return `${parsed.protocol}//${parsed.host}`;
71
- } catch {
72
- return url;
73
- }
52
+ function buildOriginOpenAIUrl(baseUrl: string): string {
53
+ const parsed = new URL(baseUrl.trim());
54
+ parsed.pathname = "/v1/models";
55
+ parsed.hash = "";
56
+ return parsed.toString();
74
57
  }
75
58
 
76
59
  function buildGoogleUrl(baseUrl: string, apiKey: string): string {
77
- const url = new URL(`${baseUrl.replace(/\/+$/, "")}/models`);
60
+ const url = new URL(appendUrlPath(baseUrl, "models"));
78
61
  url.searchParams.set("key", apiKey);
79
62
  return url.toString();
80
63
  }
81
64
 
82
- function extractModelIds(envelope: unknown, api: ApiKind): string[] {
83
- if (!isObjectRecord(envelope)) return [];
84
- if (api === "google-generative-ai") {
85
- const models = envelope.models;
86
- if (!Array.isArray(models)) return [];
87
- return models
88
- .map((m) => isObjectRecord(m) && typeof m.name === "string" ? m.name.replace(/^models\//, "") : undefined)
89
- .filter((id): id is string => Boolean(id));
90
- }
91
- const data = envelope.data;
92
- if (!Array.isArray(data)) return [];
93
- return data
94
- .map((m) => isObjectRecord(m) && typeof m.id === "string" ? m.id : undefined)
95
- .filter((id): id is string => Boolean(id));
65
+ function throwIfAborted(signal: AbortSignal): void {
66
+ if (!signal.aborted) return;
67
+ throw signal.reason instanceof Error ? signal.reason : new Error("模型发现已取消");
68
+ }
69
+
70
+ function waitWithSignal<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
71
+ if (signal.aborted) return Promise.reject(signal.reason);
72
+ return new Promise<T>((resolve, reject) => {
73
+ const abort = () => reject(signal.reason instanceof Error ? signal.reason : new Error("模型发现已取消"));
74
+ signal.addEventListener("abort", abort, { once: true });
75
+ operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
76
+ });
96
77
  }
97
78
 
98
79
  interface ResolvedFetchAuth {
@@ -104,13 +85,14 @@ interface ResolvedFetchAuth {
104
85
  function collectSensitiveHeaderValues(headers: Record<string, string> | undefined): string[] {
105
86
  if (!headers) return [];
106
87
  return Object.entries(headers)
107
- .filter(([name]) => /authorization|cookie|api-key|x-api-key|secret|token|key/i.test(name))
88
+ .filter(([name]) => isSensitiveHeaderName(name))
108
89
  .map(([, value]) => value);
109
90
  }
110
91
 
111
92
  async function resolveFetchAuth(
112
93
  params: FetchModelIdsParams,
113
94
  profileHeaders: Record<string, string> | undefined,
95
+ signal: AbortSignal,
114
96
  ): Promise<ResolvedFetchAuth> {
115
97
  const providerConfig: ProviderConfig = {
116
98
  name: "pi-model-manager model list probe",
@@ -131,16 +113,15 @@ async function resolveFetchAuth(
131
113
  }],
132
114
  };
133
115
 
134
- const runtime = await ModelRuntime.create({
116
+ const runtime = await waitWithSignal(ModelRuntime.create({
135
117
  credentials: emptyCredentialStore,
136
118
  modelsPath: null,
137
119
  allowModelNetwork: false,
138
- });
120
+ }), signal);
139
121
  runtime.registerProvider(TEMP_PROVIDER_ID, providerConfig);
140
122
  const model = runtime.getModel(TEMP_PROVIDER_ID, TEMP_MODEL_ID);
141
123
  if (!model) throw new Error("临时模型注册失败,无法解析模型列表认证");
142
-
143
- const resolvedAuth = await runtime.getAuth(model);
124
+ const resolvedAuth = await waitWithSignal(runtime.getAuth(model), signal);
144
125
  if (!resolvedAuth) throw new Error("请求认证解析失败");
145
126
  const apiKey = resolvedAuth.auth.apiKey;
146
127
  if (!apiKey) throw new Error("API key 未配置或解析为空,无法拉取模型列表");
@@ -155,31 +136,45 @@ async function resolveFetchAuth(
155
136
  redactionSecrets: [params.apiKey.trim(), apiKey, ...collectSensitiveHeaderValues(headers)].filter(Boolean),
156
137
  };
157
138
  }
139
+
158
140
  interface ModelListProxyConfig {
159
141
  providerId: string;
160
142
  proxyUrl: string;
161
143
  }
162
144
 
145
+ async function openProxyRouteWithSignal(
146
+ proxyConfig: ModelListProxyConfig,
147
+ url: string,
148
+ signal: AbortSignal,
149
+ ): Promise<TemporaryLocalProxyRoute> {
150
+ const routePromise = openTemporaryLocalProxyRoute(proxyConfig.providerId, url, proxyConfig.proxyUrl);
151
+ try {
152
+ return await waitWithSignal(routePromise, signal);
153
+ } catch (error) {
154
+ routePromise.then((route) => route.close(), () => undefined);
155
+ throw error;
156
+ }
157
+ }
158
+
163
159
  async function requestModelIds(
164
160
  url: string,
165
161
  headers: Record<string, string>,
166
162
  api: ApiKind,
167
163
  proxyConfig: ModelListProxyConfig | undefined,
164
+ signal: AbortSignal,
168
165
  ): Promise<string[]> {
169
- const controller = new AbortController();
170
- const timeout = setTimeout(() => controller.abort(new Error("模型列表请求超时")), MODEL_LIST_TIMEOUT_MS);
166
+ throwIfAborted(signal);
171
167
  let temporaryProxyRoute: TemporaryLocalProxyRoute | undefined;
172
168
  try {
173
169
  temporaryProxyRoute = proxyConfig
174
- ? await openTemporaryLocalProxyRoute(proxyConfig.providerId, url, proxyConfig.proxyUrl)
170
+ ? await openProxyRouteWithSignal(proxyConfig, url, signal)
175
171
  : undefined;
176
- const response = await fetch(temporaryProxyRoute?.url ?? url, { headers, signal: controller.signal });
177
- const text = await response.text();
172
+ const response = await fetch(temporaryProxyRoute?.url ?? url, { headers, signal });
173
+ const text = await readBoundedResponseText(response, signal);
178
174
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${text.slice(0, 240)}`);
179
- return extractModelIds(JSON.parse(text), api).sort((a, b) => a.localeCompare(b));
175
+ return extractValidatedModelIds(JSON.parse(text), api);
180
176
  } finally {
181
177
  temporaryProxyRoute?.close();
182
- clearTimeout(timeout);
183
178
  }
184
179
  }
185
180
 
@@ -196,64 +191,91 @@ export interface FetchModelIdsParams {
196
191
  clientHeaderCaptures?: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>;
197
192
  }
198
193
 
194
+ async function fetchModelIdsWithSignal(
195
+ params: FetchModelIdsParams,
196
+ signal: AbortSignal,
197
+ redactionSecrets: string[],
198
+ ): Promise<ModelListFetchOutcome> {
199
+ const profileHeaders = getClientHeadersForProfile(
200
+ params.clientHeaderProfile,
201
+ params.api,
202
+ params.customClientHeaders,
203
+ params.clientHeaderCaptures ?? {},
204
+ );
205
+ const auth = await resolveFetchAuth(params, profileHeaders, signal);
206
+ redactionSecrets.push(...auth.redactionSecrets);
207
+ const headers: Record<string, string> = { Accept: "application/json", ...auth.headers };
208
+ const proxyConfig = params.httpProxyEnabled
209
+ ? { providerId: params.providerId, proxyUrl: params.httpProxyUrl }
210
+ : undefined;
199
211
 
200
- export async function fetchModelIds(params: FetchModelIdsParams): Promise<ModelListFetchOutcome> {
201
- const redactionSecrets = [params.apiKey.trim()].filter(Boolean);
202
- try {
203
- const profileHeaders = getClientHeadersForProfile(
204
- params.clientHeaderProfile,
212
+ if (params.api === "google-generative-ai") {
213
+ const modelIds = await requestModelIds(
214
+ buildGoogleUrl(resolveRuntimeBaseUrl(params.api, params.baseUrl), auth.apiKey),
215
+ headers,
205
216
  params.api,
206
- params.customClientHeaders,
207
- params.clientHeaderCaptures ?? {},
217
+ proxyConfig,
218
+ signal,
208
219
  );
209
- const auth = await resolveFetchAuth(params, profileHeaders);
210
- redactionSecrets.push(...auth.redactionSecrets);
211
- const headers: Record<string, string> = { Accept: "application/json", ...auth.headers };
212
- const proxyConfig = params.httpProxyEnabled
213
- ? { providerId: params.providerId, proxyUrl: params.httpProxyUrl }
214
- : undefined;
220
+ return { status: "loaded", modelIds };
221
+ }
215
222
 
216
- if (params.api === "google-generative-ai") {
217
- const modelIds = await requestModelIds(
218
- buildGoogleUrl(resolveRuntimeBaseUrl(params.api, params.baseUrl), auth.apiKey),
219
- headers,
220
- params.api,
221
- proxyConfig,
222
- );
223
+ if (params.api === "anthropic-messages") {
224
+ const anthropicVersion = headers["anthropic-version"] ?? "2023-06-01";
225
+ const apiKeyHeaders = { ...headers, "x-api-key": auth.apiKey, "anthropic-version": anthropicVersion };
226
+ try {
227
+ const modelIds = await requestModelIds(buildAnthropicUrl(params.baseUrl), apiKeyHeaders, params.api, proxyConfig, signal);
223
228
  return { status: "loaded", modelIds };
229
+ } catch {
230
+ throwIfAborted(signal);
224
231
  }
225
- if (params.api === "anthropic-messages") {
226
- // 优先 x-api-key(多数 Anthropic 兼容端点),失败 fallback 到 Bearer
227
- const apiKeyHeaders = { ...headers, "x-api-key": auth.apiKey, "anthropic-version": headers["anthropic-version"] ?? "2023-06-01" };
228
- try {
229
- const modelIds = await requestModelIds(buildAnthropicUrl(params.baseUrl), apiKeyHeaders, params.api, proxyConfig);
230
- return { status: "loaded", modelIds };
231
- } catch {
232
- const bearerHeaders = { ...headers, Authorization: `Bearer ${auth.apiKey}`, "anthropic-version": headers["anthropic-version"] ?? "2023-06-01" };
233
- delete (bearerHeaders as any)["x-api-key"];
234
- try {
235
- const modelIds = await requestModelIds(buildAnthropicUrl(params.baseUrl), bearerHeaders, params.api, proxyConfig);
236
- return { status: "loaded", modelIds };
237
- } catch {
238
- // 最终 fallback:尝试派生主机根路径,用 OpenAI 格式 /v1/models 拉取
239
- // 兼容 DeepSeek 等同时提供 Anthropic 代理 + OpenAI 模型列表端点的服务
240
- const origin = deriveOrigin(params.baseUrl);
241
- const fallbackUrl = `${origin}/v1/models`;
242
- const fallbackHeaders = { ...headers, Authorization: `Bearer ${auth.apiKey}` };
243
- const modelIds = await requestModelIds(fallbackUrl, fallbackHeaders, params.api, proxyConfig);
244
- return { status: "loaded", modelIds };
245
- }
246
- }
232
+ const bearerHeaders: Record<string, string> = { ...headers, Authorization: `Bearer ${auth.apiKey}`, "anthropic-version": anthropicVersion };
233
+ delete bearerHeaders["x-api-key"];
234
+ try {
235
+ const modelIds = await requestModelIds(buildAnthropicUrl(params.baseUrl), bearerHeaders, params.api, proxyConfig, signal);
236
+ return { status: "loaded", modelIds };
237
+ } catch {
238
+ throwIfAborted(signal);
247
239
  }
248
- // openai-completions / openai-responses
249
- const modelIds = await requestModelIds(
250
- buildOpenAIUrl(params.baseUrl, params.api),
251
- { ...headers, Authorization: `Bearer ${auth.apiKey}` },
252
- params.api,
253
- proxyConfig,
254
- );
240
+ const fallbackHeaders = { ...headers, Authorization: `Bearer ${auth.apiKey}` };
241
+ const modelIds = await requestModelIds(buildOriginOpenAIUrl(params.baseUrl), fallbackHeaders, params.api, proxyConfig, signal);
255
242
  return { status: "loaded", modelIds };
243
+ }
244
+
245
+ const modelIds = await requestModelIds(
246
+ buildOpenAIUrl(params.baseUrl, params.api),
247
+ { ...headers, Authorization: `Bearer ${auth.apiKey}` },
248
+ params.api,
249
+ proxyConfig,
250
+ signal,
251
+ );
252
+ return { status: "loaded", modelIds };
253
+ }
254
+
255
+ export async function fetchModelIds(
256
+ params: FetchModelIdsParams,
257
+ cancellationSignal?: AbortSignal,
258
+ ): Promise<ModelListFetchOutcome> {
259
+ const controller = new AbortController();
260
+ let timedOut = false;
261
+ const cancel = () => controller.abort(cancellationSignal?.reason ?? new Error("模型发现已取消"));
262
+ if (cancellationSignal?.aborted) cancel();
263
+ else cancellationSignal?.addEventListener("abort", cancel, { once: true });
264
+ const timeout = setTimeout(() => {
265
+ timedOut = true;
266
+ controller.abort(new Error("模型列表请求总计超时(10 秒)"));
267
+ }, MODEL_LIST_TIMEOUT_MS);
268
+ const redactionSecrets = [params.apiKey.trim()].filter(Boolean);
269
+ try {
270
+ return await fetchModelIdsWithSignal(params, controller.signal, redactionSecrets);
256
271
  } catch (error) {
257
- return { status: "failed", message: redactSecrets(formatUnknownError(error), redactionSecrets) };
272
+ if (cancellationSignal?.aborted) return { status: "cancelled" };
273
+ const message = timedOut
274
+ ? "模型列表请求总计超时(10 秒)"
275
+ : redactSensitiveText(formatUnknownError(error), redactionSecrets);
276
+ return { status: "failed", message };
277
+ } finally {
278
+ clearTimeout(timeout);
279
+ cancellationSignal?.removeEventListener("abort", cancel);
258
280
  }
259
281
  }