pi-model-manager 0.1.0 → 0.3.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.
@@ -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
  }
@@ -0,0 +1,79 @@
1
+ // 模型列表响应的资源与终端安全边界。
2
+
3
+ import { isObjectRecord } from "../common.ts";
4
+ import type { ApiKind } from "../types.ts";
5
+
6
+ const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
7
+ const MAX_MODEL_COUNT = 5_000;
8
+ const MAX_MODEL_ID_LENGTH = 256;
9
+ const UNSAFE_TERMINAL_TEXT_PATTERN = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u;
10
+
11
+ function waitWithSignal<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
12
+ if (signal.aborted) return Promise.reject(signal.reason);
13
+ return new Promise<T>((resolve, reject) => {
14
+ const abort = () => reject(signal.reason instanceof Error ? signal.reason : new Error("模型发现已取消"));
15
+ signal.addEventListener("abort", abort, { once: true });
16
+ operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
17
+ });
18
+ }
19
+
20
+ function validateModelId(id: string): string {
21
+ if (!id || id.length > MAX_MODEL_ID_LENGTH) {
22
+ throw new Error(`上游模型 ID 长度必须为 1-${MAX_MODEL_ID_LENGTH} 个字符`);
23
+ }
24
+ if (UNSAFE_TERMINAL_TEXT_PATTERN.test(id)) {
25
+ throw new Error("上游模型 ID 包含控制字符或终端转义序列,已拒绝显示");
26
+ }
27
+ return id;
28
+ }
29
+
30
+ export function extractValidatedModelIds(envelope: unknown, api: ApiKind): string[] {
31
+ if (!isObjectRecord(envelope)) return [];
32
+ const rawModels = api === "google-generative-ai" ? envelope.models : envelope.data;
33
+ if (!Array.isArray(rawModels)) return [];
34
+ if (rawModels.length > MAX_MODEL_COUNT) {
35
+ throw new Error(`上游返回 ${rawModels.length} 个模型,超过上限 ${MAX_MODEL_COUNT}`);
36
+ }
37
+ const ids = new Set<string>();
38
+ for (const model of rawModels) {
39
+ if (!isObjectRecord(model)) continue;
40
+ const rawId = api === "google-generative-ai" ? model.name : model.id;
41
+ if (typeof rawId !== "string") continue;
42
+ const id = api === "google-generative-ai" ? rawId.replace(/^models\//, "") : rawId;
43
+ ids.add(validateModelId(id));
44
+ }
45
+ return [...ids].sort((left, right) => left.localeCompare(right));
46
+ }
47
+
48
+ export async function readBoundedResponseText(response: Response, signal: AbortSignal): Promise<string> {
49
+ const declaredLength = Number.parseInt(response.headers.get("content-length") ?? "", 10);
50
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
51
+ throw new Error(`模型列表响应体超过 ${MAX_RESPONSE_BYTES} 字节上限`);
52
+ }
53
+ if (!response.body) {
54
+ const text = await waitWithSignal(response.text(), signal);
55
+ if (Buffer.byteLength(text, "utf8") > MAX_RESPONSE_BYTES) throw new Error(`模型列表响应体超过 ${MAX_RESPONSE_BYTES} 字节上限`);
56
+ return text;
57
+ }
58
+
59
+ const reader = response.body.getReader();
60
+ const decoder = new TextDecoder();
61
+ let totalBytes = 0;
62
+ let text = "";
63
+ try {
64
+ while (true) {
65
+ const chunk = await waitWithSignal(reader.read(), signal);
66
+ if (chunk.done) break;
67
+ totalBytes += chunk.value.byteLength;
68
+ if (totalBytes > MAX_RESPONSE_BYTES) {
69
+ await reader.cancel("response too large");
70
+ throw new Error(`模型列表响应体超过 ${MAX_RESPONSE_BYTES} 字节上限`);
71
+ }
72
+ text += decoder.decode(chunk.value, { stream: true });
73
+ }
74
+ text += decoder.decode();
75
+ return text;
76
+ } finally {
77
+ reader.releaseLock();
78
+ }
79
+ }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
6
6
  import { CURSOR_MARKER, Key, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
7
+ import { padLabel } from "./persistent-menu.ts";
7
8
 
8
9
  const MODEL_PAGE_SIZE = 8;
9
10
  const EXACT_MATCH_SCORE = 50_000;
@@ -227,7 +228,7 @@ export async function pickModelIdFromList(
227
228
  selectedIndex = clampSelectedIndex(selectedIndex, matchedModelIds.length);
228
229
  const pageStart = getPageStart(selectedIndex);
229
230
  const visibleModelIds = matchedModelIds.slice(pageStart, pageStart + MODEL_PAGE_SIZE);
230
- const border = theme.fg("borderMuted", "─".repeat(Math.max(0, Math.min(width, 100))));
231
+ const border = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
231
232
  const queryCursor = focused ? `${CURSOR_MARKER}${theme.fg("accent", "▌")}` : "";
232
233
  const searchLine = searchText
233
234
  ? `${theme.fg("muted", "搜索: ")}${searchText}${queryCursor}`
@@ -249,8 +250,9 @@ export async function pickModelIdFromList(
249
250
  const selected = absoluteIndex === selectedIndex;
250
251
  const currentSuffix = modelId === normalizedCurrentModelId ? theme.fg("dim", " ← 当前") : "";
251
252
  const prefix = selected ? "❯ " : " ";
252
- const rowText = `${prefix}${modelId}${currentSuffix}`;
253
- lines.push(selected ? theme.fg("accent", rowText) : rowText);
253
+ const rowText = truncateToWidth(`${prefix}${modelId}${currentSuffix}`, width);
254
+ // [喵喵喵]: 与列表菜单用同一种选中表现(背景色),避免两套选择器手感不一致。
255
+ lines.push(selected ? theme.bg("selectedBg", padLabel(rowText, width)) : rowText);
254
256
  }
255
257
  }
256
258