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.
@@ -4,24 +4,27 @@
4
4
  // 关键差异:
5
5
  // - 请求头已经收敛到接入级;模型编辑器只编辑模型自身能力
6
6
  // - 提供"从上游拉取模型 ID 列表"入口(OpenAI/Anthropic/Google)
7
- // - 支持视觉用开关式 select,保存时仍映射为 text / text,image
7
+ // - 视觉支持用开关式 select,保存时仍映射为 text / text,image
8
8
 
9
9
  import { BorderedLoader, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
10
+ import { t } from "../i18n.ts";
10
11
  import type { AnthropicThinkingProtocol, BuiltInClientHeaderProfileId, ModelDraft, ModelListFetchOutcome, ReasoningMode, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
11
12
  import { fetchModelIds } from "./model-list-fetch.ts";
12
13
  import { pickModelIdFromList } from "./model-picker.ts";
13
- import { showPersistentFormMenu, showPersistentMenu, padLabel, type HorizontalDirection, type MenuCursor } from "./persistent-menu.ts";
14
+ import { showOptionPicker, showPersistentFormMenu, padLabel, type MenuCursor } from "./persistent-menu.ts";
14
15
  import {
15
16
  describeVisionInput,
16
17
  formatApiShort,
18
+ getVisionInputChoices,
17
19
  supportsVisionInput,
18
- VISION_INPUT_CHOICES,
19
20
  } from "./ui-helpers.ts";
20
21
 
21
22
  interface FieldRow {
22
23
  id: string;
23
24
  label: string;
24
25
  value: string;
26
+ // 开关类字段可用 ←→ 就地切换;其余字段需要 Enter 进入输入或选择器。
27
+ adjustable?: boolean;
25
28
  }
26
29
 
27
30
 
@@ -35,47 +38,38 @@ function shouldShowAnthropicThinkingProtocol(draft: ModelDraft): boolean {
35
38
 
36
39
 
37
40
  function describeReasoningMode(mode: ReasoningMode): string {
38
- return mode === "enabled" ? "开启" : "关闭";
41
+ return mode === "enabled" ? t("开启") : t("关闭");
39
42
  }
40
43
 
41
44
  function describeAnthropicThinkingProtocol(protocol: AnthropicThinkingProtocol): string {
42
- return protocol === "adaptive" ? "开启 · 新版协议" : "关闭 · Legacy";
45
+ return protocol === "adaptive" ? t("开启 · 新版协议") : t("关闭 · Legacy");
43
46
  }
44
47
 
45
48
  function describeOpenAIServiceTier(draft: ModelDraft): string {
46
- return draft.openAIServiceTier === "priority" ? "开启 · priority" : "关闭";
49
+ return draft.openAIServiceTier === "priority" ? t("开启 · priority") : t("关闭");
47
50
  }
48
51
 
49
52
  function getIntegerFieldLabel(field: "contextWindow" | "maxTokens"): string {
50
- return field === "contextWindow" ? "上下文窗口" : "最大输出";
53
+ return field === "contextWindow" ? t("上下文窗口") : t("最大输出");
51
54
  }
52
55
 
53
- function cycleSwitchState(current: boolean, direction: HorizontalDirection): boolean {
54
- const states = [false, true];
55
- const currentIndex = current ? 1 : 0;
56
- const delta = direction === "right" ? 1 : -1;
57
- return states[(currentIndex + delta + states.length) % states.length]!;
58
- }
59
56
 
60
- function applyHorizontalToggle(draft: ModelDraft, fieldId: string, direction: HorizontalDirection): boolean {
57
+ // 开关字段在两个方向上都是取反,因此不看 direction;返回是否真的切换了字段。
58
+ function applyHorizontalToggle(draft: ModelDraft, fieldId: string): boolean {
61
59
  if (fieldId === "visionInput") {
62
- const enabled = cycleSwitchState(supportsVisionInput(draft.inputKinds), direction);
63
- draft.inputKinds = enabled ? ["text", "image"] : ["text"];
60
+ draft.inputKinds = supportsVisionInput(draft.inputKinds) ? ["text"] : ["text", "image"];
64
61
  return true;
65
62
  }
66
63
  if (fieldId === "reasoning") {
67
- const enabled = cycleSwitchState(draft.reasoningMode === "enabled", direction);
68
- draft.reasoningMode = enabled ? "enabled" : "disabled";
64
+ draft.reasoningMode = draft.reasoningMode === "enabled" ? "disabled" : "enabled";
69
65
  return true;
70
66
  }
71
67
  if (fieldId === "anthropicThinkingProtocol") {
72
- const enabled = cycleSwitchState(draft.anthropicThinkingProtocol === "adaptive", direction);
73
- draft.anthropicThinkingProtocol = enabled ? "adaptive" : "legacy";
68
+ draft.anthropicThinkingProtocol = draft.anthropicThinkingProtocol === "adaptive" ? "legacy" : "adaptive";
74
69
  return true;
75
70
  }
76
71
  if (fieldId === "openAIServiceTier") {
77
- const enabled = cycleSwitchState(draft.openAIServiceTier === "priority", direction);
78
- draft.openAIServiceTier = enabled ? "priority" : undefined;
72
+ draft.openAIServiceTier = draft.openAIServiceTier === "priority" ? undefined : "priority";
79
73
  return true;
80
74
  }
81
75
  return false;
@@ -83,36 +77,30 @@ function applyHorizontalToggle(draft: ModelDraft, fieldId: string, direction: Ho
83
77
 
84
78
  function buildRows(draft: ModelDraft): FieldRow[] {
85
79
  const rows: FieldRow[] = [
86
- { id: "modelId", label: "模型 ID", value: draft.modelId || "<未填写>" },
87
- { id: "fetch", label: "重新拉取", value: "上游模型列表" },
88
- { id: "modelName", label: "显示名称", value: draft.modelName || "默认 = 模型 ID" },
89
- { id: "visionInput", label: "支持视觉", value: describeVisionInput(draft.inputKinds) },
90
- { id: "reasoning", label: "Thinking", value: describeReasoningMode(draft.reasoningMode) },
80
+ { id: "modelId", label: t("模型 ID"), value: draft.modelId || t("<未填写>") },
81
+ { id: "fetch", label: t("重新拉取"), value: t("上游模型列表") },
82
+ { id: "modelName", label: t("显示名称"), value: draft.modelName || t("默认 = 模型 ID") },
83
+ { id: "visionInput", label: t("视觉支持"), value: describeVisionInput(draft.inputKinds), adjustable: true },
84
+ { id: "reasoning", label: "Thinking", value: describeReasoningMode(draft.reasoningMode), adjustable: true },
91
85
  ];
92
86
  if (shouldShowAnthropicThinkingProtocol(draft)) {
93
87
  rows.push({
94
88
  id: "anthropicThinkingProtocol",
95
89
  label: "Adaptive",
96
90
  value: describeAnthropicThinkingProtocol(draft.anthropicThinkingProtocol!),
91
+ adjustable: true,
97
92
  });
98
93
  }
99
94
  if (shouldShowOpenAIServiceTier(draft)) {
100
- rows.push({ id: "openAIServiceTier", label: "Fast mode", value: describeOpenAIServiceTier(draft) });
95
+ rows.push({ id: "openAIServiceTier", label: "Fast mode", value: describeOpenAIServiceTier(draft), adjustable: true });
101
96
  }
102
97
  rows.push(
103
- { id: "contextWindow", label: "上下文窗口", value: String(draft.contextWindow) },
104
- { id: "maxTokens", label: "最大输出", value: String(draft.maxTokens) },
98
+ { id: "contextWindow", label: t("上下文窗口"), value: String(draft.contextWindow) },
99
+ { id: "maxTokens", label: t("最大输出"), value: String(draft.maxTokens) },
105
100
  );
106
101
  return rows;
107
102
  }
108
103
 
109
- function getAdjustableRowIds(draft: ModelDraft): string[] {
110
- const ids = ["visionInput", "reasoning"];
111
- if (shouldShowAnthropicThinkingProtocol(draft)) ids.push("anthropicThinkingProtocol");
112
- if (shouldShowOpenAIServiceTier(draft)) ids.push("openAIServiceTier");
113
- return ids;
114
- }
115
-
116
104
  function getSelectedCustomHeaders(
117
105
  draft: ModelDraft,
118
106
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
@@ -140,7 +128,7 @@ async function pickModelFromUpstream(
140
128
  clientHeaderCaptures,
141
129
  };
142
130
  const outcome = await ctx.ui.custom<ModelListFetchOutcome>((tui, theme, _keybindings, done) => {
143
- const loader = new BorderedLoader(tui, theme, "正在拉取模型列表,总计最多 10 秒…", { cancellable: true });
131
+ const loader = new BorderedLoader(tui, theme, t("正在拉取模型列表,总计最多 10 秒…"), { cancellable: true });
144
132
  let settled = false;
145
133
  const finish = (result: ModelListFetchOutcome) => {
146
134
  if (settled) return;
@@ -155,20 +143,20 @@ async function pickModelFromUpstream(
155
143
  });
156
144
  if (outcome.status === "cancelled") return;
157
145
  if (outcome.status === "failed") {
158
- ctx.ui.notify(`拉取失败:${outcome.message}`, "warning");
159
- const fallback = await ctx.ui.input(`手动输入模型 ID(当前:${draft.modelId || "<空>"})`, draft.modelId);
146
+ ctx.ui.notify(t("拉取失败:{error}", { error: outcome.message }), "warning");
147
+ const fallback = await ctx.ui.input(t("手动输入模型 ID(当前:{current})", { current: draft.modelId || t("<空>") }), draft.modelId);
160
148
  if (fallback !== undefined) {
161
149
  draft.modelId = fallback.trim() || draft.modelId;
162
150
  }
163
151
  return;
164
152
  }
165
153
  if (outcome.modelIds.length === 0) {
166
- ctx.ui.notify("上游返回空列表", "warning");
154
+ ctx.ui.notify(t("上游返回空列表"), "warning");
167
155
  return;
168
156
  }
169
157
  const picked = await pickModelIdFromList(
170
158
  ctx,
171
- `选择模型 ID(共 ${outcome.modelIds.length} 个)`,
159
+ t("选择模型 ID(共 {count} 个)", { count: outcome.modelIds.length }),
172
160
  outcome.modelIds,
173
161
  draft.modelId,
174
162
  );
@@ -180,13 +168,13 @@ async function pickModelFromUpstream(
180
168
  async function editIntField(ctx: ExtensionCommandContext, draft: ModelDraft, field: "contextWindow" | "maxTokens"): Promise<void> {
181
169
  const label = getIntegerFieldLabel(field);
182
170
  const current = String(draft[field]);
183
- const value = await ctx.ui.input(`${label}(当前:${current},留空保持原值)`, current);
171
+ const value = await ctx.ui.input(t("{label}(当前:{current},留空保持原值)", { label, current }), current);
184
172
  if (value === undefined) return;
185
173
  const trimmed = value.trim();
186
174
  if (!trimmed) return;
187
175
  const parsed = Number.parseInt(trimmed, 10);
188
176
  if (!Number.isFinite(parsed) || parsed <= 0) {
189
- ctx.ui.notify(`${label} 必须是正整数`, "warning");
177
+ ctx.ui.notify(t("{label} 必须是正整数", { label }), "warning");
190
178
  return;
191
179
  }
192
180
  draft[field] = parsed;
@@ -200,7 +188,7 @@ async function editField(
200
188
  clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
201
189
  ): Promise<void> {
202
190
  if (fieldId === "modelId") {
203
- const value = await ctx.ui.input(`模型 ID(当前:${draft.modelId || "<空>"},传给上游 API 的模型字段)`, draft.modelId);
191
+ const value = await ctx.ui.input(t("模型 ID(当前:{current},传给上游 API 的模型字段)", { current: draft.modelId || t("<空>") }), draft.modelId);
204
192
  if (value !== undefined) {
205
193
  const trimmed = value.trim();
206
194
  if (trimmed) {
@@ -214,90 +202,56 @@ async function editField(
214
202
  return;
215
203
  }
216
204
  if (fieldId === "modelName") {
217
- const value = await ctx.ui.input(`显示名称(当前:${draft.modelName || "<空>"},可空默认用模型 ID;输入空格清空)`, draft.modelName);
205
+ const value = await ctx.ui.input(t("显示名称(当前:{current},可空默认用模型 ID;输入空格清空)", { current: draft.modelName || t("<空>") }), draft.modelName);
218
206
  if (value !== undefined) draft.modelName = value.trim();
219
207
  return;
220
208
  }
221
209
  if (fieldId === "visionInput") {
222
- const current = supportsVisionInput(draft.inputKinds);
223
- const cursor: MenuCursor = { index: VISION_INPUT_CHOICES.findIndex((choice) => choice.enabled === current) };
224
- const action = await showPersistentMenu(
225
- ctx,
226
- "支持视觉输入",
227
- "↑↓ 移动 · Enter 选择 · Esc 返回",
228
- VISION_INPUT_CHOICES.map((choice) => ({
229
- id: choice.enabled ? "enabled" : "disabled",
230
- label: choice.enabled === current ? `${choice.label} ← 当前` : choice.label,
231
- })),
232
- cursor,
233
- );
234
- if (action.type === "cancel") return;
235
- const choice = VISION_INPUT_CHOICES.find((candidate) => (candidate.enabled ? "enabled" : "disabled") === action.id);
210
+ const choices = getVisionInputChoices().map((choice) => ({
211
+ id: choice.enabled ? "enabled" : "disabled",
212
+ label: choice.label,
213
+ kinds: choice.kinds,
214
+ }));
215
+ const choice = await showOptionPicker(ctx, t("视觉支持"), choices, supportsVisionInput(draft.inputKinds) ? "enabled" : "disabled");
236
216
  if (choice) draft.inputKinds = [...choice.kinds];
237
217
  return;
238
218
  }
239
219
  if (fieldId === "reasoning") {
240
- const choices: Array<{ mode: ReasoningMode; label: string }> = [
241
- { mode: "disabled", label: "关闭 — 不发送模型推理参数" },
242
- { mode: "enabled", label: "开启 — 启用模型推理参数" },
243
- ];
244
- const cursor: MenuCursor = { index: choices.findIndex((choice) => choice.mode === draft.reasoningMode) };
245
- const action = await showPersistentMenu(
220
+ const choice = await showOptionPicker(
246
221
  ctx,
247
222
  "Thinking",
248
- "↑↓ 移动 · Enter 选择 · Esc 返回",
249
- choices.map((choice) => ({
250
- id: choice.mode,
251
- label: choice.mode === draft.reasoningMode ? `${choice.label} ← 当前` : choice.label,
252
- })),
253
- cursor,
223
+ [
224
+ { id: "disabled" as ReasoningMode, label: t("关闭 — 不发送模型推理参数") },
225
+ { id: "enabled" as ReasoningMode, label: t("开启 — 启用模型推理参数") },
226
+ ],
227
+ draft.reasoningMode,
254
228
  );
255
- if (action.type === "cancel") return;
256
- const choice = choices.find((candidate) => candidate.mode === action.id);
257
- if (choice) draft.reasoningMode = choice.mode;
229
+ if (choice) draft.reasoningMode = choice.id;
258
230
  return;
259
231
  }
260
232
  if (fieldId === "anthropicThinkingProtocol") {
261
- const choices: Array<{ protocol: AnthropicThinkingProtocol; label: string }> = [
262
- { protocol: "adaptive", label: "开启:新版模型,发送 thinking.type=adaptive 和 output_config.effort" },
263
- { protocol: "legacy", label: "关闭:旧版接口,发送 thinking.type=enabled 和 budget_tokens" },
264
- ];
265
- const current = draft.anthropicThinkingProtocol ?? "legacy";
266
- const cursor: MenuCursor = { index: choices.findIndex((choice) => choice.protocol === current) };
267
- const action = await showPersistentMenu(
233
+ const choice = await showOptionPicker(
268
234
  ctx,
269
235
  "Adaptive",
270
- "↑↓ 移动 · Enter 选择 · Esc 返回",
271
- choices.map((choice) => ({
272
- id: choice.protocol,
273
- label: choice.protocol === current ? `${choice.label} ← 当前` : choice.label,
274
- })),
275
- cursor,
236
+ [
237
+ { id: "adaptive" as AnthropicThinkingProtocol, label: t("开启:新版模型,发送 thinking.type=adaptive 和 output_config.effort") },
238
+ { id: "legacy" as AnthropicThinkingProtocol, label: t("关闭:旧版接口,发送 thinking.type=enabled 和 budget_tokens") },
239
+ ],
240
+ draft.anthropicThinkingProtocol ?? "legacy",
276
241
  );
277
- if (action.type === "cancel") return;
278
- const choice = choices.find((candidate) => candidate.protocol === action.id);
279
- if (choice) draft.anthropicThinkingProtocol = choice.protocol;
242
+ if (choice) draft.anthropicThinkingProtocol = choice.id;
280
243
  return;
281
244
  }
282
245
  if (fieldId === "openAIServiceTier") {
283
- const choices: Array<{ id: "disabled" | "priority"; tier: ModelDraft["openAIServiceTier"]; label: string }> = [
284
- { id: "disabled", tier: undefined, label: "关闭 — 不发送 service_tier(默认)" },
285
- { id: "priority", tier: "priority", label: "开启 — service_tier=priority,可能消耗 Fast / priority 额度" },
286
- ];
287
- const current = draft.openAIServiceTier === "priority" ? "priority" : "disabled";
288
- const cursor: MenuCursor = { index: choices.findIndex((choice) => choice.id === current) };
289
- const action = await showPersistentMenu(
246
+ const choice = await showOptionPicker(
290
247
  ctx,
291
248
  "Fast mode",
292
- "↑↓ 移动 · Enter 选择 · Esc 返回",
293
- choices.map((choice) => ({
294
- id: choice.id,
295
- label: choice.id === current ? `${choice.label} ← 当前` : choice.label,
296
- })),
297
- cursor,
249
+ [
250
+ { id: "disabled", tier: undefined, label: t("关闭 — 不发送 service_tier(默认)") },
251
+ { id: "priority", tier: "priority", label: t("开启 — service_tier=priority,可能消耗 Fast / priority 额度") },
252
+ ] as const satisfies readonly { id: string; tier: ModelDraft["openAIServiceTier"]; label: string }[],
253
+ draft.openAIServiceTier === "priority" ? "priority" : "disabled",
298
254
  );
299
- if (action.type === "cancel") return;
300
- const choice = choices.find((candidate) => candidate.id === action.id);
301
255
  if (choice) draft.openAIServiceTier = choice.tier;
302
256
  return;
303
257
  }
@@ -322,11 +276,14 @@ export async function editModel(
322
276
  }
323
277
  const cursor: MenuCursor = { index: 0 };
324
278
  while (true) {
325
- const rows = buildRows(draft);
326
- const menuRows = rows.map((row) => ({
279
+ // [喵喵喵]: 字段行的排版在开关切换后要原样重建,抽成函数避免两处写法飘移。
280
+ const toMenuRows = (fieldRows: FieldRow[]) => fieldRows.map((row) => ({
327
281
  id: row.id,
328
282
  label: `${padLabel(row.label, 16)}${row.value}`,
283
+ adjustable: row.adjustable,
329
284
  }));
285
+ const rows = buildRows(draft);
286
+ const menuRows = toMenuRows(rows);
330
287
  const action = await showPersistentFormMenu(
331
288
  ctx,
332
289
  titlePrefix,
@@ -334,20 +291,25 @@ export async function editModel(
334
291
  menuRows,
335
292
  cursor,
336
293
  {
337
- adjustableRowIds: getAdjustableRowIds(draft),
338
294
  summaryLines: [
339
- `接入 ${draft.providerId} · API ${formatApiShort(draft.api)}`,
340
- "Ctrl+S 保存并启用模型;不切换当前会话模型",
295
+ t("接入 {providerId} · API {api}", { providerId: draft.providerId, api: formatApiShort(draft.api) }),
296
+ t("Ctrl+S 保存并启用模型;不切换当前会话模型"),
297
+ ],
298
+ onAdjust: (id) => {
299
+ if (!applyHorizontalToggle(draft, id)) return undefined;
300
+ return toMenuRows(buildRows(draft));
301
+ },
302
+ hints: [
303
+ { key: "↑↓", label: t("选择") },
304
+ { key: "←→", label: t("切换选项") },
305
+ { key: "Enter", label: t("编辑") },
306
+ { key: "Ctrl+S", label: t("保存并启用") },
307
+ { key: "Esc", label: t("返回") },
341
308
  ],
342
- footer: "↑↓ 选择 ←→ 切换选项 Enter 编辑 Ctrl+S 保存并启用 Esc 返回",
343
309
  },
344
310
  );
345
311
  if (action.type === "cancel") return { action: "cancel" };
346
312
  if (action.type === "save") return { action: "save", draft };
347
- if (action.type === "adjust") {
348
- applyHorizontalToggle(draft, action.id, action.direction);
349
- continue;
350
- }
351
313
  await editField(ctx, draft, action.id, requestHeaderProfiles, clientHeaderCaptures);
352
314
  }
353
315
  }
@@ -5,15 +5,17 @@
5
5
 
6
6
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
7
  import { hasStringRecordEntries } from "../common.ts";
8
+ import { t } from "../i18n.ts";
8
9
  import { switchProviderDraftApiPreset } from "../presets/providers.ts";
9
10
  import { redactUrlForDisplay } from "../sensitive-redaction.ts";
11
+ import { resolveRuntimeBaseUrl } from "../runtime-base-url.ts";
10
12
  import { DEFAULT_PROVIDER_HTTP_PROXY_URL } from "../types.ts";
11
- import { showPersistentFormMenu, padLabel, type HorizontalDirection, type MenuCursor } from "./persistent-menu.ts";
13
+ import { showOptionPicker, showPersistentFormMenu, padLabel, type MenuCursor } from "./persistent-menu.ts";
12
14
  import {
13
- API_CHOICES,
14
- BUILT_IN_PROFILE_CHOICES,
15
15
  describeProfile,
16
16
  formatApiShort,
17
+ getApiChoices,
18
+ getBuiltInProfileChoices,
17
19
  maskSecret,
18
20
  } from "./ui-helpers.ts";
19
21
  import type { ClientHeaderProfileId, ProviderDraft, StoredRequestHeaderProfile } from "../types.ts";
@@ -22,6 +24,8 @@ interface FieldRow {
22
24
  id: string;
23
25
  label: string;
24
26
  value: string;
27
+ // 开关类字段可用 ←→ 就地切换;其余字段需要 Enter 进入输入或选择器。
28
+ adjustable?: boolean;
25
29
  }
26
30
 
27
31
  function buildRows(
@@ -32,44 +36,27 @@ function buildRows(
32
36
  && !draft.requestHeaderProfileId
33
37
  && hasStringRecordEntries(draft.customClientHeaders);
34
38
  const profileDisplay = inlineCustomProfile
35
- ? `内联自定义请求头(${Object.keys(draft.customClientHeaders).length}项)`
39
+ ? t("内联自定义请求头({count}项)", { count: Object.keys(draft.customClientHeaders).length })
36
40
  : describeProfile(draft.clientHeaderProfile, draft.api, draft.requestHeaderProfileId, requestHeaderProfiles);
37
41
  return [
38
- { id: "api", label: "API 协议", value: draft.api },
39
- { id: "providerId", label: "接入 ID(必填)", value: draft.providerId || "<必填>" },
40
- { id: "providerName", label: "名称", value: draft.providerName || "<空>" },
42
+ { id: "api", label: t("API 协议"), value: draft.api },
43
+ { id: "providerId", label: t("接入 ID(必填)"), value: draft.providerId || t("<必填>") },
44
+ { id: "providerName", label: t("名称"), value: draft.providerName || t("<空>") },
41
45
  { id: "baseUrl", label: "Base URL", value: draft.baseUrl },
42
- { id: "httpProxyEnabled", label: "本机代理", value: draft.httpProxyEnabled ? "开启" : "关闭" },
43
- { id: "httpProxyUrl", label: "代理地址", value: draft.httpProxyEnabled ? redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL) : "关闭时不使用" },
46
+ { id: "httpProxyEnabled", label: t("本机代理"), value: draft.httpProxyEnabled ? t("开启") : t("关闭"), adjustable: true },
47
+ { id: "httpProxyUrl", label: t("代理地址"), value: draft.httpProxyEnabled ? redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL) : t("关闭时不使用") },
44
48
  { id: "apiKey", label: "API key", value: maskSecret(draft.apiKey) },
45
- { id: "authHeader", label: "认证头", value: draft.authHeader ? "Bearer" : "默认" },
46
- { id: "clientHeaderProfile", label: "请求头", value: profileDisplay },
49
+ { id: "authHeader", label: t("认证头"), value: draft.authHeader ? "Bearer" : t("默认") },
50
+ { id: "clientHeaderProfile", label: t("请求头"), value: profileDisplay },
47
51
  ];
48
52
  }
49
53
 
50
- async function selectChoice<T extends { id: string; label: string }>(
51
- ctx: ExtensionCommandContext,
52
- title: string,
53
- choices: T[],
54
- currentId: string,
55
- ): Promise<T | undefined> {
56
- const labels = choices.map((c) => c.id === currentId ? `${c.label} ← 当前` : c.label);
57
- const picked = await ctx.ui.select(title, labels);
58
- if (!picked) return undefined;
59
- const index = labels.indexOf(picked);
60
- return index >= 0 ? choices[index] : undefined;
61
- }
62
54
 
63
- function cycleSwitchState(current: boolean, direction: HorizontalDirection): boolean {
64
- const states = [false, true];
65
- const currentIndex = current ? 1 : 0;
66
- const delta = direction === "right" ? 1 : -1;
67
- return states[(currentIndex + delta + states.length) % states.length]!;
68
- }
69
55
 
70
- function applyHorizontalToggle(draft: ProviderDraft, fieldId: string, direction: HorizontalDirection): boolean {
56
+ // 开关字段在两个方向上都是取反,因此不看 direction;返回是否真的切换了字段。
57
+ function applyHorizontalToggle(draft: ProviderDraft, fieldId: string): boolean {
71
58
  if (fieldId !== "httpProxyEnabled") return false;
72
- draft.httpProxyEnabled = cycleSwitchState(draft.httpProxyEnabled, direction);
59
+ draft.httpProxyEnabled = !draft.httpProxyEnabled;
73
60
  if (draft.httpProxyEnabled && !draft.httpProxyUrl.trim()) draft.httpProxyUrl = DEFAULT_PROVIDER_HTTP_PROXY_URL;
74
61
  return true;
75
62
  }
@@ -80,22 +67,18 @@ async function editClientHeaderProfile(
80
67
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
81
68
  ): Promise<void> {
82
69
  const choices = [
83
- ...BUILT_IN_PROFILE_CHOICES.map((choice) => ({
84
- id: choice.id,
85
- label: draft.clientHeaderProfile === choice.id ? `${choice.label} ← 当前` : choice.label,
86
- })),
70
+ ...getBuiltInProfileChoices().map((choice) => ({ id: choice.id as string, label: choice.label })),
87
71
  ...Object.entries(requestHeaderProfiles)
88
72
  .sort(([a], [b]) => a.localeCompare(b))
89
73
  .map(([profileId, profile]) => ({
90
74
  id: `custom:${profileId}`,
91
- label: draft.clientHeaderProfile === "custom" && draft.requestHeaderProfileId === profileId
92
- ? `自定义:${profileId} — ${profile.name} ← 当前`
93
- : `自定义:${profileId} — ${profile.name}`,
75
+ label: t("自定义:{id} — {name}", { id: profileId, name: profile.name }),
94
76
  })),
95
77
  ];
96
- const picked = await ctx.ui.select("请求头", choices.map((choice) => choice.label));
97
- if (!picked) return;
98
- const choice = choices.find((candidate) => candidate.label === picked);
78
+ const currentId = draft.clientHeaderProfile === "custom" && draft.requestHeaderProfileId
79
+ ? `custom:${draft.requestHeaderProfileId}`
80
+ : draft.clientHeaderProfile;
81
+ const choice = await showOptionPicker(ctx, t("请求头"), choices, currentId);
99
82
  if (!choice) return;
100
83
  if (choice.id.startsWith("custom:")) {
101
84
  draft.clientHeaderProfile = "custom";
@@ -113,16 +96,21 @@ async function editField(
113
96
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
114
97
  ): Promise<void> {
115
98
  if (fieldId === "api") {
116
- const choice = await selectChoice(ctx, "选择 API 协议", API_CHOICES, draft.api);
99
+ const choice = await showOptionPicker(ctx, t("选择 API 协议"), getApiChoices(), draft.api);
117
100
  if (choice) switchProviderDraftApiPreset(draft, choice.id);
118
101
  return;
119
102
  }
120
103
  if (fieldId === "authHeader") {
121
- const choice = await ctx.ui.select("认证头(API key 放在哪里)", [
122
- "默认 — 交给协议 SDK / 接入默认行为",
123
- "Bearer — 强制 Authorization: Bearer <apiKey>",
124
- ]);
125
- if (choice) draft.authHeader = choice.startsWith("Bearer");
104
+ const choice = await showOptionPicker(
105
+ ctx,
106
+ t("认证头(API key 放在哪里)"),
107
+ [
108
+ { id: "default", label: t("默认 — 交给协议 SDK / 接入默认行为") },
109
+ { id: "bearer", label: t("Bearer — 强制 Authorization: Bearer <apiKey>") },
110
+ ],
111
+ draft.authHeader ? "bearer" : "default",
112
+ );
113
+ if (choice) draft.authHeader = choice.id === "bearer";
126
114
  return;
127
115
  }
128
116
  if (fieldId === "clientHeaderProfile") {
@@ -130,50 +118,55 @@ async function editField(
130
118
  return;
131
119
  }
132
120
  if (fieldId === "httpProxyEnabled") {
133
- const choice = await ctx.ui.select("本机代理(仅当前接入点)", [
134
- "关闭 — 请求直连上游",
135
- `开启 — 通过 ${redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL)}`,
136
- ]);
121
+ const choice = await showOptionPicker(
122
+ ctx,
123
+ t("本机代理(仅当前接入点)"),
124
+ [
125
+ { id: "disabled", label: t("关闭 — 请求直连上游") },
126
+ { id: "enabled", label: t("开启 — 通过 {url}", { url: redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL) }) },
127
+ ],
128
+ draft.httpProxyEnabled ? "enabled" : "disabled",
129
+ );
137
130
  if (!choice) return;
138
- draft.httpProxyEnabled = choice.startsWith("开启");
131
+ draft.httpProxyEnabled = choice.id === "enabled";
139
132
  if (draft.httpProxyEnabled && !draft.httpProxyUrl.trim()) draft.httpProxyUrl = DEFAULT_PROVIDER_HTTP_PROXY_URL;
140
133
  return;
141
134
  }
142
135
  if (fieldId === "providerId") {
143
136
  const value = await ctx.ui.input(
144
- `接入 ID(必填,最多 48 个字符;仅字母、数字、点、下划线和连字符;当前:${draft.providerId || "<空>"})`,
137
+ t("接入 ID(必填,最多 48 个字符;仅字母、数字、点、下划线和连字符;当前:{current})", { current: draft.providerId || t("<空>") }),
145
138
  draft.providerId,
146
139
  );
147
140
  if (value !== undefined) draft.providerId = value.trim();
148
141
  return;
149
142
  }
150
143
  if (fieldId === "providerName") {
151
- const value = await ctx.ui.input(`名称(显示用,可留空;当前:${draft.providerName || "<空>"})`, draft.providerName);
144
+ const value = await ctx.ui.input(t("名称(显示用,可留空;当前:{current})", { current: draft.providerName || t("<空>") }), draft.providerName);
152
145
  if (value !== undefined) draft.providerName = value.trim();
153
146
  return;
154
147
  }
155
148
  if (fieldId === "httpProxyUrl") {
156
149
  const currentLabel = redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL);
157
- const value = await ctx.ui.input(`代理地址(http/https;当前:${currentLabel},留空保持原值)`, "");
150
+ const value = await ctx.ui.input(t("代理地址(http/https;当前:{current},留空保持原值)", { current: currentLabel }), "");
158
151
  if (value?.trim()) draft.httpProxyUrl = value.trim();
159
152
  return;
160
153
  }
161
154
  if (fieldId === "apiKey") {
162
- const currentLabel = draft.apiKey ? maskSecret(draft.apiKey) : "<空>";
163
- const value = await ctx.ui.input(`API key(可选;明文 / $ENV_VAR / !command;当前:${currentLabel},留空清除)`, "");
155
+ const currentLabel = draft.apiKey ? maskSecret(draft.apiKey) : t("<空>");
156
+ const value = await ctx.ui.input(t("API key(可选;明文 / $ENV_VAR / !command;当前:{current},留空清除)", { current: currentLabel }), "");
164
157
  if (value === undefined) return;
165
158
  draft.apiKey = value.trim();
166
159
  return;
167
160
  }
168
- const prompt = ({
169
- baseUrl: "Base URL(http/https)",
170
- } as Record<string, string>)[fieldId];
171
- const current = (draft as any)[fieldId] as string;
172
- const value = await ctx.ui.input(`${prompt ?? fieldId}(当前:${current || "<空>"},留空保持原值)`, current);
161
+ // [喵喵喵]: baseUrl 是唯一走通用文本输入的字段,显式列出才能保持 draft 的类型检查。
162
+ if (fieldId !== "baseUrl") return;
163
+ const value = await ctx.ui.input(t("Base URL(http/https)(当前:{current},留空保持原值)", { current: draft.baseUrl || t("<空>") }), draft.baseUrl);
173
164
  if (value === undefined) return;
174
165
  const trimmed = value.trim();
175
166
  if (!trimmed) return;
176
- (draft as any)[fieldId] = trimmed;
167
+ // [喵喵喵]: 当场归一化成 SDK 可直接使用的根地址,让 models.json 存的就是最终请求地址;
168
+ // 否则插件未加载时 pi 会用未补全的值直接请求,补全结果也无法在界面上核对。
169
+ draft.baseUrl = resolveRuntimeBaseUrl(draft.api, trimmed);
177
170
  }
178
171
 
179
172
  export type ProviderEditOutcome =
@@ -188,11 +181,14 @@ export async function editProvider(
188
181
  ): Promise<ProviderEditOutcome> {
189
182
  const cursor: MenuCursor = { index: 0 };
190
183
  while (true) {
191
- const rows = buildRows(draft, requestHeaderProfiles);
192
- const menuRows = rows.map((r) => ({
193
- id: r.id,
194
- label: `${padLabel(r.label, 16)}${r.value}`,
184
+ // [喵喵喵]: 字段行的排版在开关切换后要原样重建,抽成函数避免两处写法飘移。
185
+ const toMenuRows = (fieldRows: FieldRow[]) => fieldRows.map((row) => ({
186
+ id: row.id,
187
+ label: `${padLabel(row.label, 16)}${row.value}`,
188
+ adjustable: row.adjustable,
195
189
  }));
190
+ const rows = buildRows(draft, requestHeaderProfiles);
191
+ const menuRows = toMenuRows(rows);
196
192
  const action = await showPersistentFormMenu(
197
193
  ctx,
198
194
  titlePrefix,
@@ -200,21 +196,26 @@ export async function editProvider(
200
196
  menuRows,
201
197
  cursor,
202
198
  {
203
- adjustableRowIds: ["httpProxyEnabled"],
204
199
  summaryLines: [
205
- `API ${formatApiShort(draft.api)} · 请求头 ${describeProfile(draft.clientHeaderProfile, draft.api, draft.requestHeaderProfileId, requestHeaderProfiles)}`,
206
- "接入 ID 必填,且不能与已有或 pi 内置接入重复",
207
- "Ctrl+S 保存并同步 models.json;不切换当前会话模型",
200
+ `API ${formatApiShort(draft.api)} · ${t("请求头")} ${describeProfile(draft.clientHeaderProfile, draft.api, draft.requestHeaderProfileId, requestHeaderProfiles)}`,
201
+ t("接入 ID 必填,且不能与已有或 pi 内置接入重复"),
202
+ t("Ctrl+S 保存并同步 models.json;不切换当前会话模型"),
203
+ ],
204
+ onAdjust: (id) => {
205
+ if (!applyHorizontalToggle(draft, id)) return undefined;
206
+ return toMenuRows(buildRows(draft, requestHeaderProfiles));
207
+ },
208
+ hints: [
209
+ { key: "↑↓", label: t("选择") },
210
+ { key: "←→", label: t("切换选项") },
211
+ { key: "Enter", label: t("编辑") },
212
+ { key: "Ctrl+S", label: t("保存并同步") },
213
+ { key: "Esc", label: t("返回") },
208
214
  ],
209
- footer: "↑↓ 选择 ←→ 切换选项 Enter 编辑 Ctrl+S 保存并同步 Esc 返回",
210
215
  },
211
216
  );
212
217
  if (action.type === "cancel") return { action: "cancel" };
213
218
  if (action.type === "save") return { action: "save", draft };
214
- if (action.type === "adjust") {
215
- applyHorizontalToggle(draft, action.id, action.direction);
216
- continue;
217
- }
218
219
  await editField(ctx, draft, action.id, requestHeaderProfiles);
219
220
  }
220
221
  }