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.
- package/README.en.md +119 -23
- package/README.md +119 -23
- package/atomic-write.ts +4 -32
- package/common.ts +0 -17
- package/configuration-lock.ts +136 -0
- package/configuration-persistence.ts +289 -38
- package/file-snapshot.ts +76 -0
- package/header-profile-mutations.ts +29 -7
- package/index.ts +43 -10
- package/local-proxy-service.ts +93 -30
- package/model-mutations.ts +58 -32
- package/models-json-manager.ts +43 -79
- package/models-json-sync.ts +117 -93
- package/openai-responses-payload.ts +1 -1
- package/package.json +12 -7
- package/presets/builtin-client-headers.ts +7 -7
- package/presets/client-headers.ts +2 -15
- package/presets/providers.ts +30 -4
- package/presets/thinking.ts +5 -13
- package/provider-registrar.ts +9 -2
- package/runtime-base-url.ts +64 -33
- package/sensitive-redaction.ts +46 -0
- package/state-cache.ts +2 -1
- package/state-document.ts +37 -14
- package/state-metadata-store.ts +65 -31
- package/state-store.ts +85 -31
- package/tui/dashboard.ts +60 -21
- package/tui/editor-model.ts +74 -99
- package/tui/editor-provider.ts +69 -68
- package/tui/header-profiles-panel.ts +96 -24
- package/tui/model-list-fetch.ts +136 -114
- package/tui/model-list-validation.ts +79 -0
- package/tui/model-picker.ts +5 -3
- package/tui/persistent-menu.ts +309 -84
- package/tui/ui-helpers.ts +217 -111
- package/types.ts +7 -14
- package/models-json-mutations.ts +0 -90
- package/tui/models-json-panel.ts +0 -269
package/tui/model-list-fetch.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
// 从上游 API 拉取模型列表(OpenAI / Anthropic / Google)。
|
|
2
|
-
//
|
|
2
|
+
// 整次发现共享一个 10 秒 AbortSignal,并限制响应体、模型数量与终端不安全字符。
|
|
3
3
|
|
|
4
4
|
import { ModelRuntime, type ProviderConfig } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import { formatUnknownError
|
|
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
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
|
43
|
+
return appendUrlPath(resolveRuntimeBaseUrl(api, baseUrl), "models");
|
|
49
44
|
}
|
|
50
45
|
|
|
51
46
|
function buildAnthropicUrl(baseUrl: string): string {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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(
|
|
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
|
|
83
|
-
if (!
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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]) =>
|
|
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
|
-
|
|
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
|
|
170
|
+
? await openProxyRouteWithSignal(proxyConfig, url, signal)
|
|
175
171
|
: undefined;
|
|
176
|
-
const response = await fetch(temporaryProxyRoute?.url ?? url, { headers, signal
|
|
177
|
-
const text = await response
|
|
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
|
|
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
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
-
|
|
207
|
-
|
|
217
|
+
proxyConfig,
|
|
218
|
+
signal,
|
|
208
219
|
);
|
|
209
|
-
|
|
210
|
-
|
|
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
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
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
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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
|
-
|
|
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: "
|
|
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
|
+
}
|
package/tui/model-picker.ts
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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
|
|