pi-model-manager 0.3.0 → 0.3.2
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 +26 -24
- package/README.md +25 -23
- package/atomic-write.ts +4 -2
- package/common.ts +3 -2
- package/configuration-lock.ts +3 -2
- package/configuration-persistence.ts +13 -12
- package/file-snapshot.ts +2 -1
- package/header-profile-mutations.ts +4 -3
- package/i18n.ts +403 -0
- package/index.ts +20 -9
- package/local-proxy-service.ts +10 -9
- package/model-mutations.ts +24 -21
- package/models-json-manager.ts +8 -7
- package/models-json-sync.ts +11 -10
- package/package.json +4 -2
- package/presets/builtin-client-headers.ts +3 -3
- package/presets/client-headers.ts +9 -9
- package/presets/providers.ts +2 -2
- package/provider-registrar.ts +4 -3
- package/request-pipeline.ts +3 -2
- package/rescue.ts +4 -3
- package/state-document.ts +35 -34
- package/state-metadata-store.ts +38 -37
- package/state-store.ts +2 -1
- package/tui/dashboard.ts +75 -44
- package/tui/editor-model.ts +36 -35
- package/tui/editor-provider.ts +35 -34
- package/tui/header-profiles-panel.ts +69 -62
- package/tui/model-list-fetch.ts +9 -8
- package/tui/model-list-validation.ts +8 -7
- package/tui/model-picker.ts +13 -8
- package/tui/persistent-menu.ts +12 -11
- package/tui/ui-helpers.ts +49 -42
- package/ui-language-settings.ts +47 -0
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { formatUnknownError, parseStringRecordJson } from "../common.ts";
|
|
8
|
+
import { t } from "../i18n.ts";
|
|
8
9
|
import { deleteRequestHeaderProfileConfiguration, saveRequestHeaderProfileConfiguration } from "../header-profile-mutations.ts";
|
|
9
10
|
import { CLAUDE_CODE_CLIENT_HEADERS, CODEX_CLI_CLIENT_HEADERS } from "../presets/builtin-client-headers.ts";
|
|
10
11
|
import {
|
|
@@ -39,26 +40,28 @@ interface HeaderTemplate {
|
|
|
39
40
|
headers: Record<string, string>;
|
|
40
41
|
}
|
|
41
42
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
43
|
+
function getHeaderTemplates(): HeaderTemplate[] {
|
|
44
|
+
return [
|
|
45
|
+
{
|
|
46
|
+
id: "codex-cli",
|
|
47
|
+
label: "Codex",
|
|
48
|
+
description: t("OpenAI 兼容端点使用的终端 Codex TUI 请求头。"),
|
|
49
|
+
headers: CODEX_CLI_CLIENT_HEADERS,
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
id: "claude-code",
|
|
53
|
+
label: "ClaudeCode",
|
|
54
|
+
description: t("Anthropic 兼容端点常用的 ClaudeCode 请求头。"),
|
|
55
|
+
headers: CLAUDE_CODE_CLIENT_HEADERS,
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
id: "empty",
|
|
59
|
+
label: t("清空"),
|
|
60
|
+
description: t("清空当前请求头,重新手动填写。"),
|
|
61
|
+
headers: {},
|
|
62
|
+
},
|
|
63
|
+
];
|
|
64
|
+
}
|
|
62
65
|
|
|
63
66
|
function buildProfileRows(document: StateDocument, profileIds: string[]): ProfileRow[] {
|
|
64
67
|
return profileIds.map((profileId) => {
|
|
@@ -74,8 +77,8 @@ function formatCapturedAt(capturedAt: string): string {
|
|
|
74
77
|
}
|
|
75
78
|
|
|
76
79
|
function formatCaptureLine(label: string, capture: StoredClientHeaderCapture | undefined): string {
|
|
77
|
-
if (!capture) return ` ${padLabel(label, 12)}
|
|
78
|
-
return ` ${padLabel(label, 12)} 已抓包
|
|
80
|
+
if (!capture) return ` ${padLabel(label, 12)} ${t("未抓包")}`;
|
|
81
|
+
return ` ${padLabel(label, 12)} ${t("已抓包 {time} · {count} headers", { time: formatCapturedAt(capture.capturedAt), count: Object.keys(capture.headers).length })}`;
|
|
79
82
|
}
|
|
80
83
|
|
|
81
84
|
interface ProfileTableCells {
|
|
@@ -122,10 +125,10 @@ function formatProfileRow(
|
|
|
122
125
|
|
|
123
126
|
function formatProfileTableHeader(menuWidth: number): string {
|
|
124
127
|
return ` ${formatProfileTableRow({
|
|
125
|
-
profileId: "自定义 ID",
|
|
128
|
+
profileId: t("自定义 ID"),
|
|
126
129
|
headers: "Headers",
|
|
127
130
|
used: "Used",
|
|
128
|
-
name: "名称",
|
|
131
|
+
name: t("名称"),
|
|
129
132
|
}, Math.max(0, menuWidth - 2))}`;
|
|
130
133
|
}
|
|
131
134
|
|
|
@@ -148,64 +151,65 @@ function formatProfileDetailLines(
|
|
|
148
151
|
|
|
149
152
|
function buildEditorRows(draft: RequestHeaderProfileDraft): FieldRow[] {
|
|
150
153
|
return [
|
|
151
|
-
{ id: "profileId", label: "请求头 ID", value: draft.profileId || "<未填写>" },
|
|
152
|
-
{ id: "profileName", label: "请求头名称", value: draft.profileName || "<未填写>" },
|
|
153
|
-
{ id: "template", label: "快速模板", value: "选择后填充" },
|
|
154
|
-
{ id: "headers", label: "请求头 JSON", value: Object.keys(draft.headers).length > 0 ?
|
|
154
|
+
{ id: "profileId", label: t("请求头 ID"), value: draft.profileId || t("<未填写>") },
|
|
155
|
+
{ id: "profileName", label: t("请求头名称"), value: draft.profileName || t("<未填写>") },
|
|
156
|
+
{ id: "template", label: t("快速模板"), value: t("选择后填充") },
|
|
157
|
+
{ id: "headers", label: t("请求头 JSON"), value: Object.keys(draft.headers).length > 0 ? t("{count}项", { count: Object.keys(draft.headers).length }) : t("未配置") },
|
|
155
158
|
];
|
|
156
159
|
}
|
|
157
160
|
|
|
158
161
|
function notifyValidationErrors(ctx: ExtensionCommandContext, errors: string[]): void {
|
|
159
|
-
ctx.ui.notify(
|
|
162
|
+
ctx.ui.notify(t("请求头无效:\n{errors}", { errors: errors.map((error) => `- ${error}`).join("\n") }), "warning");
|
|
160
163
|
}
|
|
161
164
|
|
|
162
165
|
function formatHeadersEditorText(headers: Record<string, string>): string {
|
|
163
166
|
if (Object.keys(headers).length > 0) return JSON.stringify(headers, null, 2);
|
|
164
167
|
return `{
|
|
165
|
-
// 可先返回上一级选择“快速模板”,也可在这里填写:
|
|
168
|
+
// ${t("可先返回上一级选择“快速模板”,也可在这里填写:")}
|
|
166
169
|
// "user-agent": "custom-client/1.0"
|
|
167
170
|
}
|
|
168
171
|
`;
|
|
169
172
|
}
|
|
170
173
|
|
|
171
174
|
async function editHeaders(ctx: ExtensionCommandContext, draft: RequestHeaderProfileDraft): Promise<void> {
|
|
172
|
-
ctx.ui.notify("结构:JSON 对象;key 是客户端 header 名,value 是字符串。复杂示例请用“快速模板”。", "info");
|
|
175
|
+
ctx.ui.notify(t("结构:JSON 对象;key 是客户端 header 名,value 是字符串。复杂示例请用“快速模板”。"), "info");
|
|
173
176
|
while (true) {
|
|
174
|
-
const answer = await ctx.ui.editor("请求头 JSON", formatHeadersEditorText(draft.headers));
|
|
177
|
+
const answer = await ctx.ui.editor(t("请求头 JSON"), formatHeadersEditorText(draft.headers));
|
|
175
178
|
if (answer === undefined) return;
|
|
176
179
|
try {
|
|
177
|
-
draft.headers = parseStringRecordJson(answer, "请求头");
|
|
180
|
+
draft.headers = parseStringRecordJson(answer, t("请求头"));
|
|
178
181
|
return;
|
|
179
182
|
} catch (error) {
|
|
180
|
-
ctx.ui.notify(
|
|
183
|
+
ctx.ui.notify(t("请求头 JSON 无效:{error}", { error: formatUnknownError(error) }), "warning");
|
|
181
184
|
}
|
|
182
185
|
}
|
|
183
186
|
}
|
|
184
187
|
|
|
185
188
|
async function applyTemplate(ctx: ExtensionCommandContext, draft: RequestHeaderProfileDraft): Promise<void> {
|
|
186
|
-
const
|
|
187
|
-
const
|
|
189
|
+
const templates = getHeaderTemplates();
|
|
190
|
+
const labels = templates.map((template) => `${template.label} — ${template.description}`);
|
|
191
|
+
const picked = await ctx.ui.select(t("选择请求头模板"), labels);
|
|
188
192
|
if (!picked) return;
|
|
189
193
|
const index = labels.indexOf(picked);
|
|
190
194
|
if (index < 0) return;
|
|
191
|
-
const template =
|
|
195
|
+
const template = templates[index]!;
|
|
192
196
|
draft.headers = { ...template.headers };
|
|
193
197
|
ctx.ui.notify(
|
|
194
198
|
template.id === "empty"
|
|
195
|
-
? "已清空请求头"
|
|
196
|
-
:
|
|
199
|
+
? t("已清空请求头")
|
|
200
|
+
: t("已填充模板:{template},可继续进入“请求头 JSON”微调。", { template: template.label }),
|
|
197
201
|
"info",
|
|
198
202
|
);
|
|
199
203
|
}
|
|
200
204
|
|
|
201
205
|
async function editField(ctx: ExtensionCommandContext, draft: RequestHeaderProfileDraft, fieldId: string): Promise<void> {
|
|
202
206
|
if (fieldId === "profileId") {
|
|
203
|
-
const value = await ctx.ui.input("请求头 ID(接入引用这个 ID;字母/数字/._-)", draft.profileId);
|
|
207
|
+
const value = await ctx.ui.input(t("请求头 ID(接入引用这个 ID;字母/数字/._-)"), draft.profileId);
|
|
204
208
|
if (value !== undefined) draft.profileId = value.trim();
|
|
205
209
|
return;
|
|
206
210
|
}
|
|
207
211
|
if (fieldId === "profileName") {
|
|
208
|
-
const value = await ctx.ui.input("请求头名称(显示用)", draft.profileName);
|
|
212
|
+
const value = await ctx.ui.input(t("请求头名称(显示用)"), draft.profileName);
|
|
209
213
|
if (value !== undefined) draft.profileName = value.trim();
|
|
210
214
|
return;
|
|
211
215
|
}
|
|
@@ -236,13 +240,13 @@ async function editProfile(
|
|
|
236
240
|
cursor,
|
|
237
241
|
{
|
|
238
242
|
summaryLines: [
|
|
239
|
-
"认证类敏感 header 会被拒绝;API key 请放在接入配置中",
|
|
243
|
+
t("认证类敏感 header 会被拒绝;API key 请放在接入配置中"),
|
|
240
244
|
],
|
|
241
245
|
hints: [
|
|
242
|
-
{ key: "↑↓", label: "选择" },
|
|
243
|
-
{ key: "Enter", label: "编辑" },
|
|
244
|
-
{ key: "Ctrl+S", label: "保存并同步" },
|
|
245
|
-
{ key: "Esc", label: "返回" },
|
|
246
|
+
{ key: "↑↓", label: t("选择") },
|
|
247
|
+
{ key: "Enter", label: t("编辑") },
|
|
248
|
+
{ key: "Ctrl+S", label: t("保存并同步") },
|
|
249
|
+
{ key: "Esc", label: t("返回") },
|
|
246
250
|
],
|
|
247
251
|
},
|
|
248
252
|
);
|
|
@@ -268,7 +272,7 @@ async function saveProfile(
|
|
|
268
272
|
await saveRequestHeaderProfileConfiguration(pi, ctx, state, draft, oldProfileId);
|
|
269
273
|
return true;
|
|
270
274
|
} catch (error) {
|
|
271
|
-
ctx.ui.notify(
|
|
275
|
+
ctx.ui.notify(t("保存失败:{error}", { error: formatUnknownError(error) }), "error");
|
|
272
276
|
return false;
|
|
273
277
|
}
|
|
274
278
|
}
|
|
@@ -277,20 +281,23 @@ async function deleteProfile(pi: ExtensionAPI, ctx: ExtensionCommandContext, pro
|
|
|
277
281
|
const state = await readState();
|
|
278
282
|
const profile = state.requestHeaderProfiles[profileId];
|
|
279
283
|
if (!profile) {
|
|
280
|
-
ctx.ui.notify(
|
|
284
|
+
ctx.ui.notify(t("请求头不存在:{profileId}", { profileId }), "warning");
|
|
281
285
|
return true;
|
|
282
286
|
}
|
|
283
287
|
const affected = countModelsUsingRequestHeaderProfile(state, profileId);
|
|
284
288
|
const ok = await ctx.ui.confirm(
|
|
285
|
-
|
|
286
|
-
|
|
289
|
+
t("删除请求头 {profileId}", { profileId }),
|
|
290
|
+
t("将删除 {name}。{affected}", {
|
|
291
|
+
name: profile.name,
|
|
292
|
+
affected: affected > 0 ? t("\n{count} 个模型会自动改回“自动推荐”。", { count: affected }) : "",
|
|
293
|
+
}),
|
|
287
294
|
);
|
|
288
295
|
if (!ok) return false;
|
|
289
296
|
try {
|
|
290
297
|
await deleteRequestHeaderProfileConfiguration(pi, ctx, state, profileId);
|
|
291
298
|
return true;
|
|
292
299
|
} catch (error) {
|
|
293
|
-
ctx.ui.notify(
|
|
300
|
+
ctx.ui.notify(t("删除失败:{error}", { error: formatUnknownError(error) }), "error");
|
|
294
301
|
return false;
|
|
295
302
|
}
|
|
296
303
|
}
|
|
@@ -299,10 +306,10 @@ async function editStoredProfile(pi: ExtensionAPI, ctx: ExtensionCommandContext,
|
|
|
299
306
|
const state = await readState();
|
|
300
307
|
const profile = state.requestHeaderProfiles[profileId];
|
|
301
308
|
if (!profile) {
|
|
302
|
-
ctx.ui.notify(
|
|
309
|
+
ctx.ui.notify(t("请求头不存在:{profileId}", { profileId }), "warning");
|
|
303
310
|
return true;
|
|
304
311
|
}
|
|
305
|
-
const outcome = await editProfile(ctx, createRequestHeaderProfileDraftFromStored(profileId, profile),
|
|
312
|
+
const outcome = await editProfile(ctx, createRequestHeaderProfileDraftFromStored(profileId, profile), t("编辑请求头 {profileId}", { profileId }));
|
|
306
313
|
if (outcome.action !== "save") return false;
|
|
307
314
|
return saveProfile(pi, ctx, outcome.draft, profileId);
|
|
308
315
|
}
|
|
@@ -317,7 +324,7 @@ export async function runHeaderProfilesPanel(pi: ExtensionAPI, ctx: ExtensionCom
|
|
|
317
324
|
const rows = buildProfileRows(state, profileIds);
|
|
318
325
|
const action = await showPersistentShortcutMenu<HeaderProfileShortcut>(
|
|
319
326
|
ctx,
|
|
320
|
-
"/model-manager / 请求头",
|
|
327
|
+
t("/model-manager / 请求头"),
|
|
321
328
|
"",
|
|
322
329
|
rows.map((row, index) => ({ id: `${index}`, label: row.label, searchText: row.searchText })),
|
|
323
330
|
cursor,
|
|
@@ -348,25 +355,25 @@ export async function runHeaderProfilesPanel(pi: ExtensionAPI, ctx: ExtensionCom
|
|
|
348
355
|
: [];
|
|
349
356
|
},
|
|
350
357
|
hints: [
|
|
351
|
-
{ key: "↑↓", label: "选择" },
|
|
352
|
-
{ key: "Enter", label: "编辑请求头" },
|
|
353
|
-
{ key: "N", label: "新建自定义" },
|
|
354
|
-
{ key: "D", label: "删除" },
|
|
355
|
-
{ key: "Esc", label: "返回" },
|
|
358
|
+
{ key: "↑↓", label: t("选择") },
|
|
359
|
+
{ key: "Enter", label: t("编辑请求头") },
|
|
360
|
+
{ key: "N", label: t("新建自定义") },
|
|
361
|
+
{ key: "D", label: t("删除") },
|
|
362
|
+
{ key: "Esc", label: t("返回") },
|
|
356
363
|
],
|
|
357
|
-
emptyLabel: "暂无自定义请求头;按 n 新建",
|
|
364
|
+
emptyLabel: t("暂无自定义请求头;按 n 新建"),
|
|
358
365
|
},
|
|
359
366
|
);
|
|
360
367
|
if (action.type === "cancel") return;
|
|
361
368
|
if (action.type === "shortcut") {
|
|
362
369
|
if (action.shortcut === "new-profile") {
|
|
363
|
-
const outcome = await editProfile(ctx, createRequestHeaderProfileDraft(), "新建请求头");
|
|
370
|
+
const outcome = await editProfile(ctx, createRequestHeaderProfileDraft(), t("新建请求头"));
|
|
364
371
|
if (outcome.action === "save") await saveProfile(pi, ctx, outcome.draft, undefined);
|
|
365
372
|
continue;
|
|
366
373
|
}
|
|
367
374
|
const selectedProfileId = rows[cursor.index]?.profileId;
|
|
368
375
|
if (!selectedProfileId) {
|
|
369
|
-
ctx.ui.notify("没有可删除的请求头。", "info");
|
|
376
|
+
ctx.ui.notify(t("没有可删除的请求头。"), "info");
|
|
370
377
|
continue;
|
|
371
378
|
}
|
|
372
379
|
await deleteProfile(pi, ctx, selectedProfileId);
|
package/tui/model-list-fetch.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import { ModelRuntime, type ProviderConfig } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { formatUnknownError } from "../common.ts";
|
|
6
|
+
import { t } from "../i18n.ts";
|
|
6
7
|
import { openTemporaryLocalProxyRoute, type TemporaryLocalProxyRoute } from "../local-proxy-service.ts";
|
|
7
8
|
import { getClientHeadersForProfile } from "../presets/client-headers.ts";
|
|
8
9
|
import { appendUrlPath, resolveRuntimeBaseUrl } from "../runtime-base-url.ts";
|
|
@@ -64,13 +65,13 @@ function buildGoogleUrl(baseUrl: string, apiKey: string): string {
|
|
|
64
65
|
|
|
65
66
|
function throwIfAborted(signal: AbortSignal): void {
|
|
66
67
|
if (!signal.aborted) return;
|
|
67
|
-
throw signal.reason instanceof Error ? signal.reason : new Error("模型发现已取消");
|
|
68
|
+
throw signal.reason instanceof Error ? signal.reason : new Error(t("模型发现已取消"));
|
|
68
69
|
}
|
|
69
70
|
|
|
70
71
|
function waitWithSignal<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
71
72
|
if (signal.aborted) return Promise.reject(signal.reason);
|
|
72
73
|
return new Promise<T>((resolve, reject) => {
|
|
73
|
-
const abort = () => reject(signal.reason instanceof Error ? signal.reason : new Error("模型发现已取消"));
|
|
74
|
+
const abort = () => reject(signal.reason instanceof Error ? signal.reason : new Error(t("模型发现已取消")));
|
|
74
75
|
signal.addEventListener("abort", abort, { once: true });
|
|
75
76
|
operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
76
77
|
});
|
|
@@ -120,11 +121,11 @@ async function resolveFetchAuth(
|
|
|
120
121
|
}), signal);
|
|
121
122
|
runtime.registerProvider(TEMP_PROVIDER_ID, providerConfig);
|
|
122
123
|
const model = runtime.getModel(TEMP_PROVIDER_ID, TEMP_MODEL_ID);
|
|
123
|
-
if (!model) throw new Error("临时模型注册失败,无法解析模型列表认证");
|
|
124
|
+
if (!model) throw new Error(t("临时模型注册失败,无法解析模型列表认证"));
|
|
124
125
|
const resolvedAuth = await waitWithSignal(runtime.getAuth(model), signal);
|
|
125
|
-
if (!resolvedAuth) throw new Error("请求认证解析失败");
|
|
126
|
+
if (!resolvedAuth) throw new Error(t("请求认证解析失败"));
|
|
126
127
|
const apiKey = resolvedAuth.auth.apiKey;
|
|
127
|
-
if (!apiKey) throw new Error("API key 未配置或解析为空,无法拉取模型列表");
|
|
128
|
+
if (!apiKey) throw new Error(t("API key 未配置或解析为空,无法拉取模型列表"));
|
|
128
129
|
|
|
129
130
|
const headers: Record<string, string> = {};
|
|
130
131
|
for (const [name, value] of Object.entries(resolvedAuth.auth.headers ?? {})) {
|
|
@@ -258,12 +259,12 @@ export async function fetchModelIds(
|
|
|
258
259
|
): Promise<ModelListFetchOutcome> {
|
|
259
260
|
const controller = new AbortController();
|
|
260
261
|
let timedOut = false;
|
|
261
|
-
const cancel = () => controller.abort(cancellationSignal?.reason ?? new Error("模型发现已取消"));
|
|
262
|
+
const cancel = () => controller.abort(cancellationSignal?.reason ?? new Error(t("模型发现已取消")));
|
|
262
263
|
if (cancellationSignal?.aborted) cancel();
|
|
263
264
|
else cancellationSignal?.addEventListener("abort", cancel, { once: true });
|
|
264
265
|
const timeout = setTimeout(() => {
|
|
265
266
|
timedOut = true;
|
|
266
|
-
controller.abort(new Error("模型列表请求总计超时(10 秒)"));
|
|
267
|
+
controller.abort(new Error(t("模型列表请求总计超时(10 秒)")));
|
|
267
268
|
}, MODEL_LIST_TIMEOUT_MS);
|
|
268
269
|
const redactionSecrets = [params.apiKey.trim()].filter(Boolean);
|
|
269
270
|
try {
|
|
@@ -271,7 +272,7 @@ export async function fetchModelIds(
|
|
|
271
272
|
} catch (error) {
|
|
272
273
|
if (cancellationSignal?.aborted) return { status: "cancelled" };
|
|
273
274
|
const message = timedOut
|
|
274
|
-
? "模型列表请求总计超时(10 秒)"
|
|
275
|
+
? t("模型列表请求总计超时(10 秒)")
|
|
275
276
|
: redactSensitiveText(formatUnknownError(error), redactionSecrets);
|
|
276
277
|
return { status: "failed", message };
|
|
277
278
|
} finally {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// 模型列表响应的资源与终端安全边界。
|
|
2
2
|
|
|
3
3
|
import { isObjectRecord } from "../common.ts";
|
|
4
|
+
import { t } from "../i18n.ts";
|
|
4
5
|
import type { ApiKind } from "../types.ts";
|
|
5
6
|
|
|
6
7
|
const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
|
|
@@ -11,7 +12,7 @@ const UNSAFE_TERMINAL_TEXT_PATTERN = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u
|
|
|
11
12
|
function waitWithSignal<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
12
13
|
if (signal.aborted) return Promise.reject(signal.reason);
|
|
13
14
|
return new Promise<T>((resolve, reject) => {
|
|
14
|
-
const abort = () => reject(signal.reason instanceof Error ? signal.reason : new Error("模型发现已取消"));
|
|
15
|
+
const abort = () => reject(signal.reason instanceof Error ? signal.reason : new Error(t("模型发现已取消")));
|
|
15
16
|
signal.addEventListener("abort", abort, { once: true });
|
|
16
17
|
operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
17
18
|
});
|
|
@@ -19,10 +20,10 @@ function waitWithSignal<T>(operation: Promise<T>, signal: AbortSignal): Promise<
|
|
|
19
20
|
|
|
20
21
|
function validateModelId(id: string): string {
|
|
21
22
|
if (!id || id.length > MAX_MODEL_ID_LENGTH) {
|
|
22
|
-
throw new Error(
|
|
23
|
+
throw new Error(t("上游模型 ID 长度必须为 1-{maxLength} 个字符", { maxLength: MAX_MODEL_ID_LENGTH }));
|
|
23
24
|
}
|
|
24
25
|
if (UNSAFE_TERMINAL_TEXT_PATTERN.test(id)) {
|
|
25
|
-
throw new Error("上游模型 ID 包含控制字符或终端转义序列,已拒绝显示");
|
|
26
|
+
throw new Error(t("上游模型 ID 包含控制字符或终端转义序列,已拒绝显示"));
|
|
26
27
|
}
|
|
27
28
|
return id;
|
|
28
29
|
}
|
|
@@ -32,7 +33,7 @@ export function extractValidatedModelIds(envelope: unknown, api: ApiKind): strin
|
|
|
32
33
|
const rawModels = api === "google-generative-ai" ? envelope.models : envelope.data;
|
|
33
34
|
if (!Array.isArray(rawModels)) return [];
|
|
34
35
|
if (rawModels.length > MAX_MODEL_COUNT) {
|
|
35
|
-
throw new Error(
|
|
36
|
+
throw new Error(t("上游返回 {count} 个模型,超过上限 {maxCount}", { count: rawModels.length, maxCount: MAX_MODEL_COUNT }));
|
|
36
37
|
}
|
|
37
38
|
const ids = new Set<string>();
|
|
38
39
|
for (const model of rawModels) {
|
|
@@ -48,11 +49,11 @@ export function extractValidatedModelIds(envelope: unknown, api: ApiKind): strin
|
|
|
48
49
|
export async function readBoundedResponseText(response: Response, signal: AbortSignal): Promise<string> {
|
|
49
50
|
const declaredLength = Number.parseInt(response.headers.get("content-length") ?? "", 10);
|
|
50
51
|
if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
|
|
51
|
-
throw new Error(
|
|
52
|
+
throw new Error(t("模型列表响应体超过 {maxBytes} 字节上限", { maxBytes: MAX_RESPONSE_BYTES }));
|
|
52
53
|
}
|
|
53
54
|
if (!response.body) {
|
|
54
55
|
const text = await waitWithSignal(response.text(), signal);
|
|
55
|
-
if (Buffer.byteLength(text, "utf8") > MAX_RESPONSE_BYTES) throw new Error(
|
|
56
|
+
if (Buffer.byteLength(text, "utf8") > MAX_RESPONSE_BYTES) throw new Error(t("模型列表响应体超过 {maxBytes} 字节上限", { maxBytes: MAX_RESPONSE_BYTES }));
|
|
56
57
|
return text;
|
|
57
58
|
}
|
|
58
59
|
|
|
@@ -67,7 +68,7 @@ export async function readBoundedResponseText(response: Response, signal: AbortS
|
|
|
67
68
|
totalBytes += chunk.value.byteLength;
|
|
68
69
|
if (totalBytes > MAX_RESPONSE_BYTES) {
|
|
69
70
|
await reader.cancel("response too large");
|
|
70
|
-
throw new Error(
|
|
71
|
+
throw new Error(t("模型列表响应体超过 {maxBytes} 字节上限", { maxBytes: MAX_RESPONSE_BYTES }));
|
|
71
72
|
}
|
|
72
73
|
text += decoder.decode(chunk.value, { stream: true });
|
|
73
74
|
}
|
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 { t } from "../i18n.ts";
|
|
7
8
|
import { padLabel } from "./persistent-menu.ts";
|
|
8
9
|
|
|
9
10
|
const MODEL_PAGE_SIZE = 8;
|
|
@@ -124,8 +125,8 @@ function isPlainTextInput(data: string): boolean {
|
|
|
124
125
|
|
|
125
126
|
function formatPageText(modelCount: number, selectedIndex: number): string {
|
|
126
127
|
const pageCount = getPageCount(modelCount);
|
|
127
|
-
if (pageCount === 0) return "页码 0 / 0";
|
|
128
|
-
return
|
|
128
|
+
if (pageCount === 0) return t("页码 0 / 0");
|
|
129
|
+
return t("页码 {page} / {pages}", { page: Math.floor(selectedIndex / MODEL_PAGE_SIZE) + 1, pages: pageCount });
|
|
129
130
|
}
|
|
130
131
|
|
|
131
132
|
export async function pickModelIdFromList(
|
|
@@ -231,24 +232,28 @@ export async function pickModelIdFromList(
|
|
|
231
232
|
const border = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
|
|
232
233
|
const queryCursor = focused ? `${CURSOR_MARKER}${theme.fg("accent", "▌")}` : "";
|
|
233
234
|
const searchLine = searchText
|
|
234
|
-
? `${theme.fg("muted", "搜索: ")}${searchText}${queryCursor}`
|
|
235
|
-
: `${theme.fg("muted", "搜索: ")}${queryCursor}${theme.fg("dim", "<直接输入搜索>")}`;
|
|
235
|
+
? `${theme.fg("muted", t("搜索: "))}${searchText}${queryCursor}`
|
|
236
|
+
: `${theme.fg("muted", t("搜索: "))}${queryCursor}${theme.fg("dim", t("<直接输入搜索>"))}`;
|
|
236
237
|
const lines: string[] = [
|
|
237
238
|
border,
|
|
238
239
|
theme.fg("accent", theme.bold(title)),
|
|
239
240
|
searchLine,
|
|
240
|
-
theme.fg("dim",
|
|
241
|
+
theme.fg("dim", t("匹配 {matched} / {total} · {page}", {
|
|
242
|
+
matched: matchedModelIds.length,
|
|
243
|
+
total: sortedModelIds.length,
|
|
244
|
+
page: formatPageText(matchedModelIds.length, selectedIndex),
|
|
245
|
+
})),
|
|
241
246
|
"",
|
|
242
247
|
];
|
|
243
248
|
|
|
244
249
|
if (visibleModelIds.length === 0) {
|
|
245
|
-
lines.push(theme.fg("warning", "没有匹配模型;Backspace 删除搜索词,Esc 返回后可手动输入。"));
|
|
250
|
+
lines.push(theme.fg("warning", t("没有匹配模型;Backspace 删除搜索词,Esc 返回后可手动输入。")));
|
|
246
251
|
} else {
|
|
247
252
|
for (let rowIndex = 0; rowIndex < visibleModelIds.length; rowIndex += 1) {
|
|
248
253
|
const absoluteIndex = pageStart + rowIndex;
|
|
249
254
|
const modelId = visibleModelIds[rowIndex]!;
|
|
250
255
|
const selected = absoluteIndex === selectedIndex;
|
|
251
|
-
const currentSuffix = modelId === normalizedCurrentModelId ? theme.fg("dim", " ← 当前") : "";
|
|
256
|
+
const currentSuffix = modelId === normalizedCurrentModelId ? theme.fg("dim", t(" ← 当前")) : "";
|
|
252
257
|
const prefix = selected ? "❯ " : " ";
|
|
253
258
|
const rowText = truncateToWidth(`${prefix}${modelId}${currentSuffix}`, width);
|
|
254
259
|
// [喵喵喵]: 与列表菜单用同一种选中表现(背景色),避免两套选择器手感不一致。
|
|
@@ -258,7 +263,7 @@ export async function pickModelIdFromList(
|
|
|
258
263
|
|
|
259
264
|
lines.push(
|
|
260
265
|
"",
|
|
261
|
-
theme.fg("dim", "↑↓ 选择 · ←→/PgUp/PgDn 翻页 · 输入搜索 · Backspace 删除 · Enter 确认 · Esc 取消"),
|
|
266
|
+
theme.fg("dim", t("↑↓ 选择 · ←→/PgUp/PgDn 翻页 · 输入搜索 · Backspace 删除 · Enter 确认 · Esc 取消")),
|
|
262
267
|
border,
|
|
263
268
|
);
|
|
264
269
|
return lines.map((line) => truncateToWidth(line, width));
|
package/tui/persistent-menu.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import type { ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
10
10
|
import { CURSOR_MARKER, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
11
|
+
import { t } from "../i18n.ts";
|
|
11
12
|
|
|
12
13
|
export interface MenuRow {
|
|
13
14
|
id: string;
|
|
@@ -238,23 +239,23 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
|
|
|
238
239
|
// 输入态显示带光标的搜索行;Tab 退出后仍需告知用户过滤仍生效。
|
|
239
240
|
const renderQueryLine = (width: number): string => {
|
|
240
241
|
if (!searchActive) {
|
|
241
|
-
return truncateToWidth(`${theme.fg("dim", "过滤:")}${searchQuery}`, width, "");
|
|
242
|
+
return truncateToWidth(`${theme.fg("dim", t("过滤:"))}${searchQuery}`, width, "");
|
|
242
243
|
}
|
|
243
244
|
const cursorGlyph = focused ? `${CURSOR_MARKER}${theme.fg("accent", "▌")}` : "";
|
|
244
|
-
const searchPrefix = theme.fg("accent", "搜索:");
|
|
245
|
+
const searchPrefix = theme.fg("accent", t("搜索:"));
|
|
245
246
|
const queryWidth = Math.max(0, width - visibleWidth(searchPrefix));
|
|
246
247
|
const queryDisplay = searchQuery
|
|
247
248
|
? fitSearchQueryAroundCursor(searchQuery, searchCursor, cursorGlyph, queryWidth)
|
|
248
|
-
: `${cursorGlyph}${theme.fg("dim", "<输入关键词>")}`;
|
|
249
|
+
: `${cursorGlyph}${theme.fg("dim", t("<输入关键词>"))}`;
|
|
249
250
|
return truncateToWidth(`${searchPrefix}${queryDisplay}`, width, "");
|
|
250
251
|
};
|
|
251
252
|
|
|
252
253
|
const getHints = (): MenuHint[] => {
|
|
253
254
|
const hints: MenuHint[] = [...(options.hints ?? [])];
|
|
254
255
|
if (!searchable) return hints;
|
|
255
|
-
if (searchActive) hints.push({ key: "Tab", label: "保留过滤" }, { key: "Esc", label: "清空搜索" });
|
|
256
|
-
else if (searchQuery) hints.push({ key: "Tab", label: "继续输入" }, { key: "Esc", label: "清空过滤" });
|
|
257
|
-
else hints.push({ key: "/", label: "搜索" });
|
|
256
|
+
if (searchActive) hints.push({ key: "Tab", label: t("保留过滤") }, { key: "Esc", label: t("清空搜索") });
|
|
257
|
+
else if (searchQuery) hints.push({ key: "Tab", label: t("继续输入") }, { key: "Esc", label: t("清空过滤") });
|
|
258
|
+
else hints.push({ key: "/", label: t("搜索") });
|
|
258
259
|
return hints;
|
|
259
260
|
};
|
|
260
261
|
|
|
@@ -473,7 +474,7 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
|
|
|
473
474
|
|
|
474
475
|
const bodyLines: string[] = [];
|
|
475
476
|
if (shownRows.length === 0) {
|
|
476
|
-
const emptyLabel = searchQuery ?
|
|
477
|
+
const emptyLabel = searchQuery ? t("无匹配项:{query}", { query: searchQuery }) : options.emptyLabel ?? t("暂无条目");
|
|
477
478
|
bodyLines.push(truncateToWidth(theme.fg("dim", ` ${emptyLabel}`), width));
|
|
478
479
|
} else {
|
|
479
480
|
for (let offset = 0; offset < shownRows.length; offset += 1) {
|
|
@@ -525,14 +526,14 @@ export async function showOptionPicker<TChoice extends { id: string; label: stri
|
|
|
525
526
|
"",
|
|
526
527
|
choices.map((choice) => ({
|
|
527
528
|
id: choice.id,
|
|
528
|
-
label: choice.id === currentId ? `${choice.label} ←
|
|
529
|
+
label: choice.id === currentId ? `${choice.label} ${t("← 当前")}` : choice.label,
|
|
529
530
|
})),
|
|
530
531
|
cursor,
|
|
531
532
|
{
|
|
532
533
|
hints: [
|
|
533
|
-
{ key: "↑↓", label: "移动" },
|
|
534
|
-
{ key: "Enter", label: "选择" },
|
|
535
|
-
{ key: "Esc", label: "返回" },
|
|
534
|
+
{ key: "↑↓", label: t("移动") },
|
|
535
|
+
{ key: "Enter", label: t("选择") },
|
|
536
|
+
{ key: "Esc", label: t("返回") },
|
|
536
537
|
],
|
|
537
538
|
},
|
|
538
539
|
);
|