pi-model-manager 0.2.0 → 0.3.1
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 +118 -23
- package/README.md +118 -23
- package/atomic-write.ts +4 -2
- package/common.ts +3 -2
- package/configuration-lock.ts +3 -2
- package/configuration-persistence.ts +24 -19
- package/file-snapshot.ts +2 -1
- package/header-profile-mutations.ts +4 -3
- package/i18n.ts +403 -0
- package/index.ts +39 -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 +5 -4
- package/presets/builtin-client-headers.ts +7 -7
- package/presets/client-headers.ts +9 -9
- package/presets/providers.ts +6 -3
- package/provider-registrar.ts +4 -3
- package/request-pipeline.ts +3 -2
- package/rescue.ts +4 -3
- package/runtime-base-url.ts +9 -3
- package/state-document.ts +58 -34
- package/state-metadata-store.ts +38 -37
- package/state-store.ts +2 -1
- package/tui/dashboard.ts +110 -53
- package/tui/editor-model.ts +78 -116
- package/tui/editor-provider.ts +77 -76
- package/tui/header-profiles-panel.ts +100 -76
- package/tui/model-list-fetch.ts +9 -8
- package/tui/model-list-validation.ts +8 -7
- package/tui/model-picker.ts +18 -11
- package/tui/persistent-menu.ts +231 -87
- package/tui/ui-helpers.ts +184 -121
- package/ui-language-settings.ts +47 -0
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
// 管理可复用的客户端请求头。接入编辑器只选择已存在的请求头,
|
|
4
4
|
// 不在模型内部新增一次性 JSON,避免配置分散。
|
|
5
5
|
|
|
6
|
-
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
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 {
|
|
@@ -14,13 +15,16 @@ import {
|
|
|
14
15
|
validateRequestHeaderProfileDraft,
|
|
15
16
|
} from "../state-document.ts";
|
|
16
17
|
import { readState } from "../state-store.ts";
|
|
17
|
-
import type { RequestHeaderProfileDraft, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
|
|
18
|
+
import type { RequestHeaderProfileDraft, StateDocument, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
|
|
18
19
|
import { padLabel, showPersistentFormMenu, showPersistentShortcutMenu, type MenuCursor } from "./persistent-menu.ts";
|
|
19
|
-
import { fitColumn } from "./ui-helpers.ts";
|
|
20
|
+
import { fitColumn, formatDetailField, formatDetailTitle } from "./ui-helpers.ts";
|
|
20
21
|
|
|
21
22
|
interface ProfileRow {
|
|
22
23
|
profileId: string;
|
|
23
24
|
label: string;
|
|
25
|
+
searchText: string;
|
|
26
|
+
// [喵喵喵]: 引用计数要遍历全部 Provider,每帧重算浪费;构造行时算一次即可。
|
|
27
|
+
usedCount: number;
|
|
24
28
|
}
|
|
25
29
|
|
|
26
30
|
interface FieldRow {
|
|
@@ -36,29 +40,36 @@ interface HeaderTemplate {
|
|
|
36
40
|
headers: Record<string, string>;
|
|
37
41
|
}
|
|
38
42
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
+
}
|
|
59
65
|
|
|
60
|
-
function
|
|
61
|
-
return profileIds.map((profileId) =>
|
|
66
|
+
function buildProfileRows(document: StateDocument, profileIds: string[]): ProfileRow[] {
|
|
67
|
+
return profileIds.map((profileId) => {
|
|
68
|
+
const profile = document.requestHeaderProfiles[profileId]!;
|
|
69
|
+
const usedCount = countModelsUsingRequestHeaderProfile(document, profileId);
|
|
70
|
+
const label = formatProfileRow(profileId, profile, usedCount);
|
|
71
|
+
return { profileId, label, usedCount, searchText: `${profileId} ${profile.name} ${label}` };
|
|
72
|
+
});
|
|
62
73
|
}
|
|
63
74
|
|
|
64
75
|
function formatCapturedAt(capturedAt: string): string {
|
|
@@ -66,8 +77,8 @@ function formatCapturedAt(capturedAt: string): string {
|
|
|
66
77
|
}
|
|
67
78
|
|
|
68
79
|
function formatCaptureLine(label: string, capture: StoredClientHeaderCapture | undefined): string {
|
|
69
|
-
if (!capture) return ` ${padLabel(label, 12)}
|
|
70
|
-
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 })}`;
|
|
71
82
|
}
|
|
72
83
|
|
|
73
84
|
interface ProfileTableCells {
|
|
@@ -114,85 +125,91 @@ function formatProfileRow(
|
|
|
114
125
|
|
|
115
126
|
function formatProfileTableHeader(menuWidth: number): string {
|
|
116
127
|
return ` ${formatProfileTableRow({
|
|
117
|
-
profileId: "自定义 ID",
|
|
128
|
+
profileId: t("自定义 ID"),
|
|
118
129
|
headers: "Headers",
|
|
119
130
|
used: "Used",
|
|
120
|
-
name: "名称",
|
|
131
|
+
name: t("名称"),
|
|
121
132
|
}, Math.max(0, menuWidth - 2))}`;
|
|
122
133
|
}
|
|
123
134
|
|
|
124
|
-
function formatProfileDetailLines(
|
|
135
|
+
function formatProfileDetailLines(
|
|
136
|
+
profileId: string,
|
|
137
|
+
profile: StoredRequestHeaderProfile,
|
|
138
|
+
usedCount: number,
|
|
139
|
+
theme?: Theme,
|
|
140
|
+
): string[] {
|
|
125
141
|
const headerNames = Object.keys(profile.headers);
|
|
126
142
|
const preview = headerNames.length > 0
|
|
127
143
|
? headerNames.slice(0, 6).join(", ") + (headerNames.length > 6 ? ", ..." : "")
|
|
128
144
|
: "<empty>";
|
|
129
145
|
return [
|
|
130
|
-
`${profile.name} (${profileId})`,
|
|
131
|
-
|
|
132
|
-
|
|
146
|
+
formatDetailTitle(`${profile.name} (${profileId})`, theme),
|
|
147
|
+
formatDetailField("usage", `${usedCount} models`, theme),
|
|
148
|
+
formatDetailField("headers", preview, theme),
|
|
133
149
|
];
|
|
134
150
|
}
|
|
135
151
|
|
|
136
152
|
function buildEditorRows(draft: RequestHeaderProfileDraft): FieldRow[] {
|
|
137
153
|
return [
|
|
138
|
-
{ id: "profileId", label: "请求头 ID", value: draft.profileId || "<未填写>" },
|
|
139
|
-
{ id: "profileName", label: "请求头名称", value: draft.profileName || "<未填写>" },
|
|
140
|
-
{ id: "template", label: "快速模板", value: "选择后填充" },
|
|
141
|
-
{ 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("未配置") },
|
|
142
158
|
];
|
|
143
159
|
}
|
|
144
160
|
|
|
145
161
|
function notifyValidationErrors(ctx: ExtensionCommandContext, errors: string[]): void {
|
|
146
|
-
ctx.ui.notify(
|
|
162
|
+
ctx.ui.notify(t("请求头无效:\n{errors}", { errors: errors.map((error) => `- ${error}`).join("\n") }), "warning");
|
|
147
163
|
}
|
|
148
164
|
|
|
149
165
|
function formatHeadersEditorText(headers: Record<string, string>): string {
|
|
150
166
|
if (Object.keys(headers).length > 0) return JSON.stringify(headers, null, 2);
|
|
151
167
|
return `{
|
|
152
|
-
// 可先返回上一级选择“快速模板”,也可在这里填写:
|
|
168
|
+
// ${t("可先返回上一级选择“快速模板”,也可在这里填写:")}
|
|
153
169
|
// "user-agent": "custom-client/1.0"
|
|
154
170
|
}
|
|
155
171
|
`;
|
|
156
172
|
}
|
|
157
173
|
|
|
158
174
|
async function editHeaders(ctx: ExtensionCommandContext, draft: RequestHeaderProfileDraft): Promise<void> {
|
|
159
|
-
ctx.ui.notify("结构:JSON 对象;key 是客户端 header 名,value 是字符串。复杂示例请用“快速模板”。", "info");
|
|
175
|
+
ctx.ui.notify(t("结构:JSON 对象;key 是客户端 header 名,value 是字符串。复杂示例请用“快速模板”。"), "info");
|
|
160
176
|
while (true) {
|
|
161
|
-
const answer = await ctx.ui.editor("请求头 JSON", formatHeadersEditorText(draft.headers));
|
|
177
|
+
const answer = await ctx.ui.editor(t("请求头 JSON"), formatHeadersEditorText(draft.headers));
|
|
162
178
|
if (answer === undefined) return;
|
|
163
179
|
try {
|
|
164
|
-
draft.headers = parseStringRecordJson(answer, "请求头");
|
|
180
|
+
draft.headers = parseStringRecordJson(answer, t("请求头"));
|
|
165
181
|
return;
|
|
166
182
|
} catch (error) {
|
|
167
|
-
ctx.ui.notify(
|
|
183
|
+
ctx.ui.notify(t("请求头 JSON 无效:{error}", { error: formatUnknownError(error) }), "warning");
|
|
168
184
|
}
|
|
169
185
|
}
|
|
170
186
|
}
|
|
171
187
|
|
|
172
188
|
async function applyTemplate(ctx: ExtensionCommandContext, draft: RequestHeaderProfileDraft): Promise<void> {
|
|
173
|
-
const
|
|
174
|
-
const
|
|
189
|
+
const templates = getHeaderTemplates();
|
|
190
|
+
const labels = templates.map((template) => `${template.label} — ${template.description}`);
|
|
191
|
+
const picked = await ctx.ui.select(t("选择请求头模板"), labels);
|
|
175
192
|
if (!picked) return;
|
|
176
193
|
const index = labels.indexOf(picked);
|
|
177
194
|
if (index < 0) return;
|
|
178
|
-
const template =
|
|
195
|
+
const template = templates[index]!;
|
|
179
196
|
draft.headers = { ...template.headers };
|
|
180
197
|
ctx.ui.notify(
|
|
181
198
|
template.id === "empty"
|
|
182
|
-
? "已清空请求头"
|
|
183
|
-
:
|
|
199
|
+
? t("已清空请求头")
|
|
200
|
+
: t("已填充模板:{template},可继续进入“请求头 JSON”微调。", { template: template.label }),
|
|
184
201
|
"info",
|
|
185
202
|
);
|
|
186
203
|
}
|
|
187
204
|
|
|
188
205
|
async function editField(ctx: ExtensionCommandContext, draft: RequestHeaderProfileDraft, fieldId: string): Promise<void> {
|
|
189
206
|
if (fieldId === "profileId") {
|
|
190
|
-
const value = await ctx.ui.input("请求头 ID(接入引用这个 ID;字母/数字/._-)", draft.profileId);
|
|
207
|
+
const value = await ctx.ui.input(t("请求头 ID(接入引用这个 ID;字母/数字/._-)"), draft.profileId);
|
|
191
208
|
if (value !== undefined) draft.profileId = value.trim();
|
|
192
209
|
return;
|
|
193
210
|
}
|
|
194
211
|
if (fieldId === "profileName") {
|
|
195
|
-
const value = await ctx.ui.input("请求头名称(显示用)", draft.profileName);
|
|
212
|
+
const value = await ctx.ui.input(t("请求头名称(显示用)"), draft.profileName);
|
|
196
213
|
if (value !== undefined) draft.profileName = value.trim();
|
|
197
214
|
return;
|
|
198
215
|
}
|
|
@@ -223,9 +240,14 @@ async function editProfile(
|
|
|
223
240
|
cursor,
|
|
224
241
|
{
|
|
225
242
|
summaryLines: [
|
|
226
|
-
"认证类敏感 header 会被拒绝;API key 请放在接入配置中",
|
|
243
|
+
t("认证类敏感 header 会被拒绝;API key 请放在接入配置中"),
|
|
244
|
+
],
|
|
245
|
+
hints: [
|
|
246
|
+
{ key: "↑↓", label: t("选择") },
|
|
247
|
+
{ key: "Enter", label: t("编辑") },
|
|
248
|
+
{ key: "Ctrl+S", label: t("保存并同步") },
|
|
249
|
+
{ key: "Esc", label: t("返回") },
|
|
227
250
|
],
|
|
228
|
-
footer: "↑↓ 选择 Enter 编辑 Ctrl+S 保存并同步 Esc 返回",
|
|
229
251
|
},
|
|
230
252
|
);
|
|
231
253
|
if (action.type === "cancel") return { action: "cancel" };
|
|
@@ -250,7 +272,7 @@ async function saveProfile(
|
|
|
250
272
|
await saveRequestHeaderProfileConfiguration(pi, ctx, state, draft, oldProfileId);
|
|
251
273
|
return true;
|
|
252
274
|
} catch (error) {
|
|
253
|
-
ctx.ui.notify(
|
|
275
|
+
ctx.ui.notify(t("保存失败:{error}", { error: formatUnknownError(error) }), "error");
|
|
254
276
|
return false;
|
|
255
277
|
}
|
|
256
278
|
}
|
|
@@ -259,20 +281,23 @@ async function deleteProfile(pi: ExtensionAPI, ctx: ExtensionCommandContext, pro
|
|
|
259
281
|
const state = await readState();
|
|
260
282
|
const profile = state.requestHeaderProfiles[profileId];
|
|
261
283
|
if (!profile) {
|
|
262
|
-
ctx.ui.notify(
|
|
284
|
+
ctx.ui.notify(t("请求头不存在:{profileId}", { profileId }), "warning");
|
|
263
285
|
return true;
|
|
264
286
|
}
|
|
265
287
|
const affected = countModelsUsingRequestHeaderProfile(state, profileId);
|
|
266
288
|
const ok = await ctx.ui.confirm(
|
|
267
|
-
|
|
268
|
-
|
|
289
|
+
t("删除请求头 {profileId}", { profileId }),
|
|
290
|
+
t("将删除 {name}。{affected}", {
|
|
291
|
+
name: profile.name,
|
|
292
|
+
affected: affected > 0 ? t("\n{count} 个模型会自动改回“自动推荐”。", { count: affected }) : "",
|
|
293
|
+
}),
|
|
269
294
|
);
|
|
270
295
|
if (!ok) return false;
|
|
271
296
|
try {
|
|
272
297
|
await deleteRequestHeaderProfileConfiguration(pi, ctx, state, profileId);
|
|
273
298
|
return true;
|
|
274
299
|
} catch (error) {
|
|
275
|
-
ctx.ui.notify(
|
|
300
|
+
ctx.ui.notify(t("删除失败:{error}", { error: formatUnknownError(error) }), "error");
|
|
276
301
|
return false;
|
|
277
302
|
}
|
|
278
303
|
}
|
|
@@ -281,10 +306,10 @@ async function editStoredProfile(pi: ExtensionAPI, ctx: ExtensionCommandContext,
|
|
|
281
306
|
const state = await readState();
|
|
282
307
|
const profile = state.requestHeaderProfiles[profileId];
|
|
283
308
|
if (!profile) {
|
|
284
|
-
ctx.ui.notify(
|
|
309
|
+
ctx.ui.notify(t("请求头不存在:{profileId}", { profileId }), "warning");
|
|
285
310
|
return true;
|
|
286
311
|
}
|
|
287
|
-
const outcome = await editProfile(ctx, createRequestHeaderProfileDraftFromStored(profileId, profile),
|
|
312
|
+
const outcome = await editProfile(ctx, createRequestHeaderProfileDraftFromStored(profileId, profile), t("编辑请求头 {profileId}", { profileId }));
|
|
288
313
|
if (outcome.action !== "save") return false;
|
|
289
314
|
return saveProfile(pi, ctx, outcome.draft, profileId);
|
|
290
315
|
}
|
|
@@ -296,19 +321,12 @@ export async function runHeaderProfilesPanel(pi: ExtensionAPI, ctx: ExtensionCom
|
|
|
296
321
|
while (true) {
|
|
297
322
|
const state = await readState();
|
|
298
323
|
const profileIds = Object.keys(state.requestHeaderProfiles).sort((a, b) => a.localeCompare(b));
|
|
299
|
-
const rows =
|
|
300
|
-
const profile = state.requestHeaderProfiles[row.profileId]!;
|
|
301
|
-
const usedCount = countModelsUsingRequestHeaderProfile(state, row.profileId);
|
|
302
|
-
return {
|
|
303
|
-
...row,
|
|
304
|
-
label: formatProfileRow(row.profileId, profile, usedCount),
|
|
305
|
-
};
|
|
306
|
-
});
|
|
324
|
+
const rows = buildProfileRows(state, profileIds);
|
|
307
325
|
const action = await showPersistentShortcutMenu<HeaderProfileShortcut>(
|
|
308
326
|
ctx,
|
|
309
|
-
"/model-manager / 请求头",
|
|
327
|
+
t("/model-manager / 请求头"),
|
|
310
328
|
"",
|
|
311
|
-
rows.map((row, index) => ({ id: `${index}`, label: row.label })),
|
|
329
|
+
rows.map((row, index) => ({ id: `${index}`, label: row.label, searchText: row.searchText })),
|
|
312
330
|
cursor,
|
|
313
331
|
[
|
|
314
332
|
{ input: "n", shortcut: "new-profile" },
|
|
@@ -326,30 +344,36 @@ export async function runHeaderProfilesPanel(pi: ExtensionAPI, ctx: ExtensionCom
|
|
|
326
344
|
const row = rows[Number.parseInt(menuRow.id, 10)];
|
|
327
345
|
const profile = row ? state.requestHeaderProfiles[row.profileId] : undefined;
|
|
328
346
|
return row && profile
|
|
329
|
-
? formatProfileRow(row.profileId, profile,
|
|
347
|
+
? formatProfileRow(row.profileId, profile, row.usedCount, width)
|
|
330
348
|
: menuRow.label;
|
|
331
349
|
},
|
|
332
|
-
getDetailLines: (selectedRow) => {
|
|
350
|
+
getDetailLines: (selectedRow, theme) => {
|
|
333
351
|
const row = rows[Number.parseInt(selectedRow?.id ?? "", 10)];
|
|
334
352
|
const profile = row ? state.requestHeaderProfiles[row.profileId] : undefined;
|
|
335
353
|
return row && profile
|
|
336
|
-
? formatProfileDetailLines(row.profileId, profile,
|
|
354
|
+
? formatProfileDetailLines(row.profileId, profile, row.usedCount, theme)
|
|
337
355
|
: [];
|
|
338
356
|
},
|
|
339
|
-
|
|
340
|
-
|
|
357
|
+
hints: [
|
|
358
|
+
{ key: "↑↓", label: t("选择") },
|
|
359
|
+
{ key: "Enter", label: t("编辑请求头") },
|
|
360
|
+
{ key: "N", label: t("新建自定义") },
|
|
361
|
+
{ key: "D", label: t("删除") },
|
|
362
|
+
{ key: "Esc", label: t("返回") },
|
|
363
|
+
],
|
|
364
|
+
emptyLabel: t("暂无自定义请求头;按 n 新建"),
|
|
341
365
|
},
|
|
342
366
|
);
|
|
343
367
|
if (action.type === "cancel") return;
|
|
344
368
|
if (action.type === "shortcut") {
|
|
345
369
|
if (action.shortcut === "new-profile") {
|
|
346
|
-
const outcome = await editProfile(ctx, createRequestHeaderProfileDraft(), "新建请求头");
|
|
370
|
+
const outcome = await editProfile(ctx, createRequestHeaderProfileDraft(), t("新建请求头"));
|
|
347
371
|
if (outcome.action === "save") await saveProfile(pi, ctx, outcome.draft, undefined);
|
|
348
372
|
continue;
|
|
349
373
|
}
|
|
350
374
|
const selectedProfileId = rows[cursor.index]?.profileId;
|
|
351
375
|
if (!selectedProfileId) {
|
|
352
|
-
ctx.ui.notify("没有可删除的请求头。", "info");
|
|
376
|
+
ctx.ui.notify(t("没有可删除的请求头。"), "info");
|
|
353
377
|
continue;
|
|
354
378
|
}
|
|
355
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,8 @@
|
|
|
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";
|
|
8
|
+
import { padLabel } from "./persistent-menu.ts";
|
|
7
9
|
|
|
8
10
|
const MODEL_PAGE_SIZE = 8;
|
|
9
11
|
const EXACT_MATCH_SCORE = 50_000;
|
|
@@ -123,8 +125,8 @@ function isPlainTextInput(data: string): boolean {
|
|
|
123
125
|
|
|
124
126
|
function formatPageText(modelCount: number, selectedIndex: number): string {
|
|
125
127
|
const pageCount = getPageCount(modelCount);
|
|
126
|
-
if (pageCount === 0) return "页码 0 / 0";
|
|
127
|
-
return
|
|
128
|
+
if (pageCount === 0) return t("页码 0 / 0");
|
|
129
|
+
return t("页码 {page} / {pages}", { page: Math.floor(selectedIndex / MODEL_PAGE_SIZE) + 1, pages: pageCount });
|
|
128
130
|
}
|
|
129
131
|
|
|
130
132
|
export async function pickModelIdFromList(
|
|
@@ -227,36 +229,41 @@ export async function pickModelIdFromList(
|
|
|
227
229
|
selectedIndex = clampSelectedIndex(selectedIndex, matchedModelIds.length);
|
|
228
230
|
const pageStart = getPageStart(selectedIndex);
|
|
229
231
|
const visibleModelIds = matchedModelIds.slice(pageStart, pageStart + MODEL_PAGE_SIZE);
|
|
230
|
-
const border = theme.fg("borderMuted", "─".repeat(Math.max(0,
|
|
232
|
+
const border = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
|
|
231
233
|
const queryCursor = focused ? `${CURSOR_MARKER}${theme.fg("accent", "▌")}` : "";
|
|
232
234
|
const searchLine = searchText
|
|
233
|
-
? `${theme.fg("muted", "搜索: ")}${searchText}${queryCursor}`
|
|
234
|
-
: `${theme.fg("muted", "搜索: ")}${queryCursor}${theme.fg("dim", "<直接输入搜索>")}`;
|
|
235
|
+
? `${theme.fg("muted", t("搜索: "))}${searchText}${queryCursor}`
|
|
236
|
+
: `${theme.fg("muted", t("搜索: "))}${queryCursor}${theme.fg("dim", t("<直接输入搜索>"))}`;
|
|
235
237
|
const lines: string[] = [
|
|
236
238
|
border,
|
|
237
239
|
theme.fg("accent", theme.bold(title)),
|
|
238
240
|
searchLine,
|
|
239
|
-
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
|
+
})),
|
|
240
246
|
"",
|
|
241
247
|
];
|
|
242
248
|
|
|
243
249
|
if (visibleModelIds.length === 0) {
|
|
244
|
-
lines.push(theme.fg("warning", "没有匹配模型;Backspace 删除搜索词,Esc 返回后可手动输入。"));
|
|
250
|
+
lines.push(theme.fg("warning", t("没有匹配模型;Backspace 删除搜索词,Esc 返回后可手动输入。")));
|
|
245
251
|
} else {
|
|
246
252
|
for (let rowIndex = 0; rowIndex < visibleModelIds.length; rowIndex += 1) {
|
|
247
253
|
const absoluteIndex = pageStart + rowIndex;
|
|
248
254
|
const modelId = visibleModelIds[rowIndex]!;
|
|
249
255
|
const selected = absoluteIndex === selectedIndex;
|
|
250
|
-
const currentSuffix = modelId === normalizedCurrentModelId ? theme.fg("dim", " ← 当前") : "";
|
|
256
|
+
const currentSuffix = modelId === normalizedCurrentModelId ? theme.fg("dim", t(" ← 当前")) : "";
|
|
251
257
|
const prefix = selected ? "❯ " : " ";
|
|
252
|
-
const rowText = `${prefix}${modelId}${currentSuffix}
|
|
253
|
-
|
|
258
|
+
const rowText = truncateToWidth(`${prefix}${modelId}${currentSuffix}`, width);
|
|
259
|
+
// [喵喵喵]: 与列表菜单用同一种选中表现(背景色),避免两套选择器手感不一致。
|
|
260
|
+
lines.push(selected ? theme.bg("selectedBg", padLabel(rowText, width)) : rowText);
|
|
254
261
|
}
|
|
255
262
|
}
|
|
256
263
|
|
|
257
264
|
lines.push(
|
|
258
265
|
"",
|
|
259
|
-
theme.fg("dim", "↑↓ 选择 · ←→/PgUp/PgDn 翻页 · 输入搜索 · Backspace 删除 · Enter 确认 · Esc 取消"),
|
|
266
|
+
theme.fg("dim", t("↑↓ 选择 · ←→/PgUp/PgDn 翻页 · 输入搜索 · Backspace 删除 · Enter 确认 · Esc 取消")),
|
|
260
267
|
border,
|
|
261
268
|
);
|
|
262
269
|
return lines.map((line) => truncateToWidth(line, width));
|