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.
@@ -6,6 +6,7 @@
6
6
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
7
  import { formatUnknownError } from "./common.ts";
8
8
  import { isBuiltinProviderId } from "./builtin-model-catalog.ts";
9
+ import { t } from "./i18n.ts";
9
10
  import {
10
11
  persistManagedConfiguration,
11
12
  persistModelConfiguration,
@@ -31,14 +32,14 @@ type ModelDraft = ReturnType<typeof createModelDraftForStoredProvider>;
31
32
 
32
33
  async function assertProviderIsEditable(providerId: string): Promise<void> {
33
34
  if (await isBuiltinProviderId(providerId)) {
34
- throw new Error(`内置接入 ${providerId} 不允许通过 /model-manager 编辑或删除。`);
35
+ throw new Error(t("内置接入 {providerId} 不允许通过 /model-manager 编辑或删除。", { providerId }));
35
36
  }
36
37
  }
37
38
 
38
39
  function formatEnableNote(mode: "all-enabled" | "updated" | "unchanged", scope?: "global" | "project"): string {
39
- if (mode === "all-enabled") return "当前未限制 enabledModels,重启后默认可选";
40
- if (mode === "updated") return `已写入${scope === "project" ? "项目" : "全局"} enabledModels`;
41
- return "已在 enabledModels 中";
40
+ if (mode === "all-enabled") return t("当前未限制 enabledModels,重启后默认可选");
41
+ if (mode === "updated") return scope === "project" ? t("已写入项目 enabledModels") : t("已写入全局 enabledModels");
42
+ return t("已在 enabledModels 中");
42
43
  }
43
44
 
44
45
  async function notifyModelAvailability(
@@ -46,7 +47,7 @@ async function notifyModelAvailability(
46
47
  providerId: string,
47
48
  modelId: string,
48
49
  replacedFullId?: string,
49
- messagePrefix = "已保存并启用模型",
50
+ messagePrefix = t("已保存并启用模型"),
50
51
  ): Promise<void> {
51
52
  const fullId = getModelFullId(providerId, modelId);
52
53
  try {
@@ -54,12 +55,12 @@ async function notifyModelAvailability(
54
55
  const verification = await verifyNativeModelAvailable(ctx, providerId, modelId);
55
56
  const enableNote = formatEnableNote(enableOutcome.mode, enableOutcome.scope);
56
57
  if (verification.ok) {
57
- ctx.ui.notify(`${messagePrefix} ${fullId}(${enableNote})`, "info");
58
+ ctx.ui.notify(t("{messagePrefix} {fullId}({availability})", { messagePrefix, fullId, availability: enableNote }), "info");
58
59
  } else {
59
- ctx.ui.notify(`已保存模型 ${fullId},但启用校验有警告:\n- ${verification.warnings.join("\n- ")}`, "warning");
60
+ ctx.ui.notify(t("已保存模型 {fullId},但启用校验有警告:\n- {warnings}", { fullId, warnings: verification.warnings.join("\n- ") }), "warning");
60
61
  }
61
62
  } catch (error) {
62
- ctx.ui.notify(`已保存模型 ${fullId},但启用同步/校验失败:${formatUnknownError(error)}`, "warning");
63
+ ctx.ui.notify(t("已保存模型 {fullId},但启用同步/校验失败:{error}", { fullId, error: formatUnknownError(error) }), "warning");
63
64
  }
64
65
  }
65
66
 
@@ -72,7 +73,7 @@ async function reconcilePersistedProviderRuntime(
72
73
  try {
73
74
  await reconcileProvider(pi, providerId, provider, document.requestHeaderProfiles, document.clientHeaderCaptures);
74
75
  } catch (error) {
75
- throw new Error(`models.json/state.json 已保存,但当前会话接入刷新失败:${formatUnknownError(error)}。可执行 /reload 重试。`);
76
+ throw new Error(t("models.json/state.json 已保存,但当前会话接入刷新失败:{error}。可执行 /reload 重试。", { error: formatUnknownError(error) }));
76
77
  }
77
78
  }
78
79
 
@@ -102,7 +103,7 @@ export async function saveProviderConfiguration(
102
103
  await reconcilePersistedProviderRuntime(pi, draft.providerId, stored, nextState);
103
104
  if (oldProviderId && oldProviderId !== draft.providerId) unregisterManagedProvider(pi, oldProviderId);
104
105
 
105
- ctx.ui.notify(`已保存接入 ${draft.providerId}`, "info");
106
+ ctx.ui.notify(t("已保存接入 {providerId}", { providerId: draft.providerId }), "info");
106
107
 
107
108
  if (oldProviderId && oldProviderId !== draft.providerId) {
108
109
  try {
@@ -112,13 +113,15 @@ export async function saveProviderConfiguration(
112
113
  draft.providerId,
113
114
  );
114
115
  if (outcome.mode === "updated") {
115
- ctx.ui.notify(`已同步${outcome.scope === "project" ? "项目" : "全局"} enabledModels 中的接入重命名`, "info");
116
+ ctx.ui.notify(outcome.scope === "project"
117
+ ? t("已同步项目 enabledModels 中的接入重命名")
118
+ : t("已同步全局 enabledModels 中的接入重命名"), "info");
116
119
  }
117
120
  } catch (error) {
118
- ctx.ui.notify(`接入已保存,但 enabledModels 同步失败:${formatUnknownError(error)}`, "warning");
121
+ ctx.ui.notify(t("接入已保存,但 enabledModels 同步失败:{error}", { error: formatUnknownError(error) }), "warning");
119
122
  }
120
123
  await withModelRescue(ctx, pi, { providerId: oldProviderId }, {
121
- reason: `接入 ${oldProviderId} 已重命名为 ${draft.providerId}`,
124
+ reason: t("接入 {oldProviderId} 已重命名为 {providerId}", { oldProviderId, providerId: draft.providerId }),
122
125
  preferred: renamedCurrentModelId
123
126
  ? { providerId: draft.providerId, modelId: renamedCurrentModelId }
124
127
  : undefined,
@@ -156,7 +159,7 @@ export async function saveModelConfiguration(
156
159
  pi,
157
160
  { providerId: draft.providerId, modelId: replacedModelId },
158
161
  {
159
- reason: `模型 ${oldFullId} 已重命名为 ${newFullId}`,
162
+ reason: t("模型 {oldFullId} 已重命名为 {newFullId}", { oldFullId, newFullId }),
160
163
  preferred: { providerId: draft.providerId, modelId: draft.modelId.trim() },
161
164
  },
162
165
  );
@@ -179,7 +182,7 @@ export async function saveNewProviderWithModelConfiguration(
179
182
  const nextState = await persistManagedConfiguration(ctx, prepare);
180
183
  const stored = nextState.providers[providerDraft.providerId]!;
181
184
  await reconcilePersistedProviderRuntime(pi, providerDraft.providerId, stored, nextState);
182
- await notifyModelAvailability(ctx, providerDraft.providerId, modelDraft.modelId.trim(), undefined, "已创建并启用模型");
185
+ await notifyModelAvailability(ctx, providerDraft.providerId, modelDraft.modelId.trim(), undefined, t("已创建并启用模型"));
183
186
  }
184
187
 
185
188
  export async function deleteProviderConfiguration(
@@ -197,11 +200,11 @@ export async function deleteProviderConfiguration(
197
200
  try {
198
201
  await removeProviderFromNextPiStart(ctx.cwd, providerId);
199
202
  } catch (error) {
200
- ctx.ui.notify(`接入已删除,但 enabledModels 清理失败:${formatUnknownError(error)}`, "warning");
203
+ ctx.ui.notify(t("接入已删除,但 enabledModels 清理失败:{error}", { error: formatUnknownError(error) }), "warning");
201
204
  }
202
205
  unregisterManagedProvider(pi, providerId);
203
- ctx.ui.notify(`已删除接入 ${providerId}`, "info");
204
- await withModelRescue(ctx, pi, { providerId }, { reason: `接入 ${providerId} 已删除` });
206
+ ctx.ui.notify(t("已删除接入 {providerId}", { providerId }), "info");
207
+ await withModelRescue(ctx, pi, { providerId }, { reason: t("接入 {providerId} 已删除", { providerId }) });
205
208
  }
206
209
 
207
210
  export async function deleteModelConfiguration(
@@ -227,10 +230,10 @@ export async function deleteModelConfiguration(
227
230
  try {
228
231
  await removeModelFromNextPiStart(ctx.cwd, fullId);
229
232
  } catch (error) {
230
- ctx.ui.notify(`模型已删除,但 enabledModels 清理失败:${formatUnknownError(error)}`, "warning");
233
+ ctx.ui.notify(t("模型已删除,但 enabledModels 清理失败:{error}", { error: formatUnknownError(error) }), "warning");
231
234
  }
232
235
  if (stored) await reconcilePersistedProviderRuntime(pi, providerId, stored, nextState);
233
236
  else unregisterManagedProvider(pi, providerId);
234
- ctx.ui.notify(`已删除模型 ${fullId}`, "info");
235
- await withModelRescue(ctx, pi, { providerId, modelId }, { reason: `模型 ${fullId} 已删除` });
237
+ ctx.ui.notify(t("已删除模型 {fullId}", { fullId }), "info");
238
+ await withModelRescue(ctx, pi, { providerId, modelId }, { reason: t("模型 {fullId} 已删除", { fullId }) });
236
239
  }
@@ -9,6 +9,7 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent";
9
9
  import { join } from "node:path";
10
10
  import { cloneJson, isObjectRecord, stripJsonNoise } from "./common.ts";
11
11
  import { readStableTextFileSnapshot, type FileSignature } from "./file-snapshot.ts";
12
+ import { t } from "./i18n.ts";
12
13
  import type { TokenCost } from "./types.ts";
13
14
 
14
15
  export const MODELS_JSON_PATH = join(getAgentDir(), "models.json");
@@ -96,7 +97,7 @@ function createEmpty(): ModelsJsonDocument {
96
97
 
97
98
  function parseModelsJson(source: string): ModelsJsonDocument {
98
99
  const parsed = JSON.parse(stripJsonNoise(source));
99
- if (!isObjectRecord(parsed)) throw new Error("models.json 根节点必须是对象");
100
+ if (!isObjectRecord(parsed)) throw new Error(t("models.json 根节点必须是对象"));
100
101
  const providers = isObjectRecord(parsed.providers) ? parsed.providers : {};
101
102
  return { ...parsed, providers: providers as Record<string, ModelsJsonProviderEntry> };
102
103
  }
@@ -141,8 +142,8 @@ export function renameProviderInDoc(
141
142
  const next = cloneJson(doc);
142
143
  if (oldProviderId === newProviderId) return next;
143
144
  const source = next.providers[oldProviderId];
144
- if (!source) throw new Error(`models.json 中不存在待重命名接入:${oldProviderId}`);
145
- if (next.providers[newProviderId]) throw new Error(`models.json 中已存在接入:${newProviderId}`);
145
+ if (!source) throw new Error(t("models.json 中不存在待重命名接入:{providerId}", { providerId: oldProviderId }));
146
+ if (next.providers[newProviderId]) throw new Error(t("models.json 中已存在接入:{providerId}", { providerId: newProviderId }));
146
147
  next.providers[newProviderId] = source;
147
148
  delete next.providers[oldProviderId];
148
149
  return next;
@@ -156,7 +157,7 @@ export function setModelInDoc(
156
157
  ): ModelsJsonDocument {
157
158
  const next = cloneJson(doc);
158
159
  const provider = next.providers[providerId];
159
- if (!provider) throw new Error(`models.json 中不存在接入:${providerId}`);
160
+ if (!provider) throw new Error(t("models.json 中不存在接入:{providerId}", { providerId }));
160
161
  let replaced = false;
161
162
  const models = (provider.models ?? []).flatMap((current) => {
162
163
  if (current.id !== model.id && current.id !== replacedModelId) return [current];
@@ -178,12 +179,12 @@ export function renameModelInDoc(
178
179
  const next = cloneJson(doc);
179
180
  if (oldModelId === newModelId) return next;
180
181
  const provider = next.providers[providerId];
181
- if (!provider) throw new Error(`models.json 中不存在接入:${providerId}`);
182
+ if (!provider) throw new Error(t("models.json 中不存在接入:{providerId}", { providerId }));
182
183
  const models = provider.models ?? [];
183
184
  const source = models.find((model) => model.id === oldModelId);
184
- if (!source) throw new Error(`models.json 中不存在待重命名模型:${providerId}/${oldModelId}`);
185
+ if (!source) throw new Error(t("models.json 中不存在待重命名模型:{fullId}", { fullId: `${providerId}/${oldModelId}` }));
185
186
  if (models.some((model) => model.id === newModelId)) {
186
- throw new Error(`models.json 中已存在模型:${providerId}/${newModelId}`);
187
+ throw new Error(t("models.json 中已存在模型:{fullId}", { fullId: `${providerId}/${newModelId}` }));
187
188
  }
188
189
  source.id = newModelId;
189
190
  return next;
@@ -18,6 +18,7 @@ import { atomicWriteText } from "./atomic-write.ts";
18
18
  import { cloneJson, formatUnknownError, isObjectRecord, stringifyJson, stripJsonNoise } from "./common.ts";
19
19
  import { withConfigurationLock } from "./configuration-lock.ts";
20
20
  import { readStableTextFileSnapshot } from "./file-snapshot.ts";
21
+ import { t } from "./i18n.ts";
21
22
  import {
22
23
  deleteModelInDoc,
23
24
  deleteProviderInDoc,
@@ -169,9 +170,9 @@ export function buildModelsDocumentWithSynchronizedModel(
169
170
  replacedModelId?: string,
170
171
  ): ModelsJsonDocument {
171
172
  const provider = document.providers[providerId];
172
- if (!provider) throw new Error(`接入不存在:${providerId}`);
173
+ if (!provider) throw new Error(t("接入不存在:{providerId}", { providerId }));
173
174
  const model = provider.models.find((candidate) => candidate.id === modelId);
174
- if (!model) throw new Error(`模型不存在:${providerId}/${modelId}`);
175
+ if (!model) throw new Error(t("模型不存在:{fullId}", { fullId: `${providerId}/${modelId}` }));
175
176
  const sourceModel = sourceDocument.providers[providerId]?.models?.find(
176
177
  (candidate) => candidate.id === modelId || candidate.id === replacedModelId,
177
178
  );
@@ -281,7 +282,7 @@ async function updateLockedSettings(
281
282
  try {
282
283
  const snapshot = await readStableTextFileSnapshot(path);
283
284
  const settings = snapshot.source === undefined ? {} : JSON.parse(stripJsonNoise(snapshot.source));
284
- if (!isObjectRecord(settings)) throw new Error(`${path} 根节点必须是对象`);
285
+ if (!isObjectRecord(settings)) throw new Error(t("{path} 根节点必须是对象", { path }));
285
286
  const current = settings.enabledModels;
286
287
  if (!Array.isArray(current)) return { configured: false, outcome: { mode: "all-enabled" } };
287
288
  const patterns = current.filter((item): item is string => typeof item === "string");
@@ -292,7 +293,7 @@ async function updateLockedSettings(
292
293
  }
293
294
  const currentSnapshot = await readStableTextFileSnapshot(path);
294
295
  if (currentSnapshot.contentHash !== snapshot.contentHash) {
295
- throw new Error(`${path} 已被未遵守 Pi 文件锁的编辑器修改;已取消 enabledModels 同步,请重试。`);
296
+ throw new Error(t("{path} 已被未遵守 Pi 文件锁的编辑器修改;已取消 enabledModels 同步,请重试。", { path }));
296
297
  }
297
298
  settings.enabledModels = next;
298
299
  await atomicWriteText(path, stringifyJson(settings));
@@ -374,15 +375,15 @@ async function verifyRegistryModel(
374
375
  const warnings: string[] = [];
375
376
  const model = registry.find(providerId, modelId);
376
377
  if (!model) {
377
- warnings.push(`${label} 未找到模型 ${providerId}/${modelId}`);
378
+ warnings.push(t("{label} 未找到模型 {fullId}", { label, fullId: `${providerId}/${modelId}` }));
378
379
  return warnings;
379
380
  }
380
381
  if (!registry.hasConfiguredAuth(model)) {
381
- warnings.push(`${label} 找到模型 ${providerId}/${modelId},但 API key 未配置或不可解析`);
382
+ warnings.push(t("{label} 找到模型 {fullId},但 API key 未配置或不可解析", { label, fullId: `${providerId}/${modelId}` }));
382
383
  return warnings;
383
384
  }
384
385
  const auth = await registry.getApiKeyAndHeaders(model);
385
- if (!auth.ok) warnings.push(`${label} 请求认证解析失败:${auth.error}`);
386
+ if (!auth.ok) warnings.push(t("{label} 请求认证解析失败:{error}", { label, error: auth.error }));
386
387
  return warnings;
387
388
  }
388
389
 
@@ -393,7 +394,7 @@ export async function verifyNativeModelAvailable(
393
394
  modelId: string,
394
395
  ): Promise<NativeModelVerification> {
395
396
  const warnings: string[] = [];
396
- warnings.push(...await verifyRegistryModel("当前会话 registry", ctx.modelRegistry, providerId, modelId));
397
+ warnings.push(...await verifyRegistryModel(t("当前会话 registry"), ctx.modelRegistry, providerId, modelId));
397
398
  try {
398
399
  const agentDir = getAgentDir();
399
400
  const runtime = await ModelRuntime.create({
@@ -402,9 +403,9 @@ export async function verifyNativeModelAvailable(
402
403
  allowModelNetwork: false,
403
404
  });
404
405
  const registry = new ModelRegistry(runtime);
405
- warnings.push(...await verifyRegistryModel("原生 models.json registry", registry, providerId, modelId));
406
+ warnings.push(...await verifyRegistryModel(t("原生 models.json registry"), registry, providerId, modelId));
406
407
  } catch (error) {
407
- warnings.push(`原生 models.json registry 校验失败:${formatUnknownError(error)}`);
408
+ warnings.push(t("原生 models.json registry 校验失败:{error}", { error: formatUnknownError(error) }));
408
409
  }
409
410
  return { ok: warnings.length === 0, warnings };
410
411
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-model-manager",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "A TUI model and provider manager for Pi with native models.json persistence, request-header profiles, proxy routing, and protocol compatibility.",
5
5
  "type": "module",
6
6
  "main": "./index.ts",
@@ -11,6 +11,8 @@
11
11
  "NOTICE",
12
12
  "README.en.md",
13
13
  "index.ts",
14
+ "i18n.ts",
15
+ "ui-language-settings.ts",
14
16
  "state-store.ts",
15
17
  "state-metadata-store.ts",
16
18
  "state-cache.ts",
@@ -67,7 +69,7 @@
67
69
  ]
68
70
  },
69
71
  "peerDependencies": {
70
- "@earendil-works/pi-coding-agent": ">=0.82.0",
72
+ "@earendil-works/pi-coding-agent": ">=0.84.2",
71
73
  "@earendil-works/pi-tui": ">=0.75.0"
72
74
  },
73
75
  "dependencies": {
@@ -1,10 +1,10 @@
1
1
  // 由私有 request-capture-service 根据真实客户端请求生成;公开插件仅消费这些脱敏后的内置值。
2
2
 
3
3
  export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
4
- "anthropic-beta": "claude-code-20250219,context-1m-2025-08-07,interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,effort-2025-11-24",
4
+ "anthropic-beta": "claude-code-20250219,context-1m-2025-08-07,interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,effort-2025-11-24,fallback-credit-2026-06-01",
5
5
  "anthropic-dangerous-direct-browser-access": "true",
6
6
  "anthropic-version": "2023-06-01",
7
- "user-agent": "claude-cli/2.1.232 (external, sdk-cli)",
7
+ "user-agent": "claude-cli/2.1.243 (external, sdk-cli)",
8
8
  "x-app": "cli",
9
9
  "x-stainless-arch": "x64",
10
10
  "x-stainless-lang": "js",
@@ -18,6 +18,6 @@ export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
18
18
 
19
19
  export const CODEX_CLI_CLIENT_HEADERS: Record<string, string> = {
20
20
  "originator": "codex-tui",
21
- "user-agent": "codex-tui/0.147.0 (Windows 10.0.26200; x86_64) unknown (codex-tui; 0.147.0)",
21
+ "user-agent": "codex-tui/0.149.1 (Windows 10.0.26200; x86_64) unknown (codex-tui; 0.149.1)",
22
22
  "x-codex-beta-features": "remote_compaction_v2",
23
23
  };
@@ -4,19 +4,19 @@
4
4
  // [喵喵喵]: 内置值由私有抓包工具生成,公开插件不携带捕获能力 (2026-07-26)
5
5
 
6
6
  import { cloneStringRecord, hasStringRecordEntries } from "../common.ts";
7
+ import { t } from "../i18n.ts";
7
8
  import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, CompatSettings, StoredClientHeaderCapture } from "../types.ts";
8
9
  import { CLAUDE_CODE_CLIENT_HEADERS, CODEX_CLI_CLIENT_HEADERS } from "./builtin-client-headers.ts";
9
10
 
10
11
  const ANTHROPIC_INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
11
12
 
12
13
 
13
- export const CLIENT_HEADER_PROFILE_LABELS: Record<ClientHeaderProfileId, string> = {
14
- recommended: "自动推荐",
15
- disabled: "不添加",
16
- "claude-code": "ClaudeCode",
17
- "codex-cli": "Codex",
18
- custom: "自定义请求头",
19
- };
14
+ export function getClientHeaderProfileLabel(profile: ClientHeaderProfileId): string {
15
+ if (profile === "recommended") return t("自动推荐");
16
+ if (profile === "disabled") return t("不添加");
17
+ if (profile === "custom") return t("自定义请求头");
18
+ return profile === "claude-code" ? "ClaudeCode" : "Codex";
19
+ }
20
20
 
21
21
  function removeAnthropicBetaFeature(headers: Record<string, string>, feature: string): void {
22
22
  const betaHeaderKey = Object.keys(headers).find((name) => name.toLowerCase() === "anthropic-beta");
@@ -107,7 +107,7 @@ export function getClientHeadersForProfile(
107
107
  export function getClientHeaderProfileDisplay(profile: ClientHeaderProfileId, api: ApiKind): string {
108
108
  const resolved = resolveClientHeaderProfile(profile, api);
109
109
  if (profile === "recommended") {
110
- return `${CLIENT_HEADER_PROFILE_LABELS.recommended} → ${CLIENT_HEADER_PROFILE_LABELS[resolved]}`;
110
+ return `${getClientHeaderProfileLabel("recommended")} → ${getClientHeaderProfileLabel(resolved)}`;
111
111
  }
112
- return CLIENT_HEADER_PROFILE_LABELS[profile];
112
+ return getClientHeaderProfileLabel(profile);
113
113
  }
@@ -20,7 +20,7 @@ export interface ProviderPreset {
20
20
  const PROVIDER_PRESETS: ProviderPreset[] = [
21
21
  {
22
22
  api: "openai-responses",
23
- label: "OpenAI Responses — 标准 instructions / input",
23
+ label: "OpenAI Responses — instructions / input",
24
24
  shortLabel: "OpenAI Responses",
25
25
  defaultProviderName: "openai-responses",
26
26
  baseUrl: "https://api.openai.com/v1",
@@ -33,7 +33,7 @@ const PROVIDER_PRESETS: ProviderPreset[] = [
33
33
  },
34
34
  {
35
35
  api: "openai-completions",
36
- label: "OpenAI Chat Completions — 通用 OpenAI 兼容",
36
+ label: "OpenAI Chat Completions — OpenAI-compatible",
37
37
  shortLabel: "OpenAI Chat",
38
38
  defaultProviderName: "openai-chat",
39
39
  baseUrl: "https://api.openai.com/v1",
@@ -11,6 +11,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
11
  import { isBuiltinProviderId } from "./builtin-model-catalog.ts";
12
12
  import { mergeCompatSettings } from "./compat-settings.ts";
13
13
  import { formatUnknownError } from "./common.ts";
14
+ import { t } from "./i18n.ts";
14
15
  import {
15
16
  getLocalProxyBaseUrl,
16
17
  getProviderHttpProxyUrl,
@@ -197,10 +198,10 @@ function replaceManagedProviderConfig(
197
198
  rollbackError = restoreError;
198
199
  }
199
200
  const rollbackNote = rollbackError
200
- ? `;恢复上一版 runtime 也失败:${formatUnknownError(rollbackError)}`
201
+ ? t(";恢复上一版 runtime 也失败:{error}", { error: formatUnknownError(rollbackError) })
201
202
  : previousConfig
202
- ? ";已恢复上一版 runtime"
203
- : ";新配置未注册到当前 runtime";
203
+ ? t(";已恢复上一版 runtime")
204
+ : t(";新配置未注册到当前 runtime");
204
205
  throw new Error(`${formatUnknownError(error)}${rollbackNote}`);
205
206
  }
206
207
  }
@@ -6,6 +6,7 @@
6
6
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
7
  import { injectClaudeCodeMetadata } from "./claude-code-compat.ts";
8
8
  import { formatUnknownError } from "./common.ts";
9
+ import { t, type MessageKey } from "./i18n.ts";
9
10
  import { normalizeManagedOpenAIResponsesPayload } from "./openai-responses-payload.ts";
10
11
  import { injectOpenAIServiceTier } from "./openai-service-tier.ts";
11
12
  import { readCachedState } from "./state-cache.ts";
@@ -15,7 +16,7 @@ type StateLoader = () => Promise<StateDocument>;
15
16
 
16
17
  type RequestTransform = {
17
18
  id: string;
18
- warning: string;
19
+ warning: MessageKey;
19
20
  run(payload: unknown, ctx: ExtensionContext, loadState: StateLoader): Promise<unknown | undefined> | unknown | undefined;
20
21
  };
21
22
 
@@ -77,7 +78,7 @@ export function createRequestPipeline(): RequestPipeline {
77
78
  } catch (error) {
78
79
  if (!notifiedTransformErrors.has(transform.id) && ctx.hasUI) {
79
80
  notifiedTransformErrors.add(transform.id);
80
- ctx.ui.notify(`[pi-model-manager] ${transform.warning}:${formatUnknownError(error)}`, "warning");
81
+ ctx.ui.notify(`[pi-model-manager] ${t(transform.warning)}: ${formatUnknownError(error)}`, "warning");
81
82
  }
82
83
  }
83
84
  }
package/rescue.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  // 调用方负责先同步 registry/runtime,避免救援阶段再次触发全目录刷新。
14
14
 
15
15
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
16
+ import { t } from "./i18n.ts";
16
17
 
17
18
  interface AffectedRef {
18
19
  providerId: string;
@@ -45,7 +46,7 @@ export async function withModelRescue(
45
46
  if (replacement && ctx.modelRegistry.hasConfiguredAuth(replacement)) {
46
47
  if (await pi.setModel(replacement)) {
47
48
  ctx.ui.notify(
48
- `${options.reason},已切换到 ${options.preferred.providerId}/${options.preferred.modelId}`,
49
+ t("{reason},已切换到 {fullId}", { reason: options.reason, fullId: `${options.preferred.providerId}/${options.preferred.modelId}` }),
49
50
  "info",
50
51
  );
51
52
  return;
@@ -56,14 +57,14 @@ export async function withModelRescue(
56
57
  const fallback = ctx.modelRegistry.getAvailable()[0];
57
58
  if (fallback && await pi.setModel(fallback)) {
58
59
  ctx.ui.notify(
59
- `${options.reason},已自动切换到 ${fallback.provider}/${fallback.id}`,
60
+ t("{reason},已自动切换到 {fullId}", { reason: options.reason, fullId: `${fallback.provider}/${fallback.id}` }),
60
61
  "info",
61
62
  );
62
63
  return;
63
64
  }
64
65
 
65
66
  ctx.ui.notify(
66
- `${options.reason},但当前没有其它可用模型。请使用 /model-manager 添加模型或 /login 配置认证。`,
67
+ t("{reason},但当前没有其它可用模型。请使用 /model-manager 添加模型或 /login 配置认证。", { reason: options.reason }),
67
68
  "warning",
68
69
  );
69
70
  }
package/state-document.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  getSingleConfigValueEnvVarName,
16
16
  isCommandConfigValue,
17
17
  } from "./config-value-reference.ts";
18
+ import { joinLocalizedList, t } from "./i18n.ts";
18
19
  import { findPresetForApi } from "./presets/providers.ts";
19
20
  import { normalizeThinkingLevelMap } from "./presets/thinking.ts";
20
21
  import { isSensitiveHeaderName } from "./sensitive-redaction.ts";
@@ -181,20 +182,20 @@ function validateUrl(url: string, label: string, errors: string[]): void {
181
182
  try {
182
183
  const parsed = new URL(url);
183
184
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
184
- errors.push(`${label} 必须使用 http 或 https`);
185
+ errors.push(t("{label} 必须使用 http 或 https", { label }));
185
186
  }
186
187
  } catch {
187
- errors.push(`${label} 不是有效 URL`);
188
+ errors.push(t("{label} 不是有效 URL", { label }));
188
189
  }
189
190
  }
190
191
 
191
192
  function validateHttpProxyUrl(url: string, errors: string[]): void {
192
193
  try {
193
194
  const parsed = new URL(url);
194
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") errors.push("代理地址目前只支持 http:// 或 https:// 代理");
195
- if (!parsed.hostname) errors.push("代理地址必须包含主机名");
195
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") errors.push(t("代理地址目前只支持 http:// 或 https:// 代理"));
196
+ if (!parsed.hostname) errors.push(t("代理地址必须包含主机名"));
196
197
  } catch {
197
- errors.push("代理地址不是有效 URL");
198
+ errors.push(t("代理地址不是有效 URL"));
198
199
  }
199
200
  }
200
201
 
@@ -207,25 +208,25 @@ export function validateProviderDraft(
207
208
  const errors: string[] = [];
208
209
  const id = draft.providerId.trim();
209
210
 
210
- if (!id) errors.push("接入 ID 不能为空");
211
- else if (!ID_PATTERN.test(id)) errors.push("接入 ID 只能包含字母、数字、点、下划线和连字符");
212
- else if (id.length > MAX_PROVIDER_ID_LENGTH) errors.push(`接入 ID 最多 ${MAX_PROVIDER_ID_LENGTH} 个字符`);
211
+ if (!id) errors.push(t("接入 ID 不能为空"));
212
+ else if (!ID_PATTERN.test(id)) errors.push(t("接入 ID 只能包含字母、数字、点、下划线和连字符"));
213
+ else if (id.length > MAX_PROVIDER_ID_LENGTH) errors.push(t("接入 ID 最多 {count} 个字符", { count: MAX_PROVIDER_ID_LENGTH }));
213
214
 
214
215
  if (id && oldProviderId !== id && document.providers[id]) {
215
- errors.push(`接入 ID 已存在:${id}`);
216
+ errors.push(t("接入 ID 已存在:{id}", { id }));
216
217
  }
217
218
  if (id && builtInProviderIds.has(id)) {
218
- errors.push(`接入 ID 与 pi 内置接入冲突:${id}(请改用其它 ID)`);
219
+ errors.push(t("接入 ID 与 pi 内置接入冲突:{id}(请改用其它 ID)", { id }));
219
220
  }
220
221
 
221
- if (!draft.baseUrl.trim()) errors.push("Base URL 不能为空");
222
+ if (!draft.baseUrl.trim()) errors.push(t("Base URL 不能为空"));
222
223
  else validateUrl(draft.baseUrl.trim(), "Base URL", errors);
223
224
 
224
225
 
225
226
  if (draft.clientHeaderProfile === "custom") {
226
227
  const profileId = draft.requestHeaderProfileId?.trim();
227
- if (!profileId && !hasStringRecordEntries(draft.customClientHeaders)) errors.push("请选择一个自定义请求头");
228
- else if (profileId && !document.requestHeaderProfiles[profileId]) errors.push(`自定义请求头不存在:${profileId}`);
228
+ if (!profileId && !hasStringRecordEntries(draft.customClientHeaders)) errors.push(t("请选择一个自定义请求头"));
229
+ else if (profileId && !document.requestHeaderProfiles[profileId]) errors.push(t("自定义请求头不存在:{profileId}", { profileId }));
229
230
  }
230
231
 
231
232
  if (draft.httpProxyEnabled) {
@@ -242,24 +243,24 @@ export function validateModelDraft(
242
243
  replacedModelId?: string,
243
244
  ): string[] {
244
245
  const errors: string[] = [];
245
- if (!draft.providerId.trim()) errors.push("接入 ID 不能为空");
246
- if (!draft.modelId.trim()) errors.push("模型 ID 不能为空");
246
+ if (!draft.providerId.trim()) errors.push(t("接入 ID 不能为空"));
247
+ if (!draft.modelId.trim()) errors.push(t("模型 ID 不能为空"));
247
248
 
248
249
  const provider = document.providers[draft.providerId];
249
- if (!provider) errors.push(`接入配置不存在:${draft.providerId}`);
250
+ if (!provider) errors.push(t("接入配置不存在:{providerId}", { providerId: draft.providerId }));
250
251
 
251
- if (!draft.baseUrl.trim()) errors.push("Base URL 不能为空");
252
+ if (!draft.baseUrl.trim()) errors.push(t("Base URL 不能为空"));
252
253
  else validateUrl(draft.baseUrl.trim(), "Base URL", errors);
253
254
 
254
255
 
255
256
  if (!Number.isInteger(draft.contextWindow) || draft.contextWindow <= 0)
256
- errors.push("上下文窗口必须是正整数");
257
+ errors.push(t("上下文窗口必须是正整数"));
257
258
  if (!Number.isInteger(draft.maxTokens) || draft.maxTokens <= 0)
258
- errors.push("最大输出必须是正整数");
259
+ errors.push(t("最大输出必须是正整数"));
259
260
 
260
261
  const duplicate = (provider?.models ?? []).find((m) => m.id === draft.modelId.trim());
261
262
  if (duplicate && duplicate.id !== replacedModelId)
262
- errors.push(`模型已存在:${draft.modelId.trim()}`);
263
+ errors.push(t("模型已存在:{modelId}", { modelId: draft.modelId.trim() }));
263
264
 
264
265
  return errors;
265
266
  }
@@ -274,17 +275,17 @@ export function getProviderChangeWarnings(
274
275
  const changes: string[] = [];
275
276
  if ((current.baseUrl ?? "") !== draft.baseUrl.trim()) changes.push("Base URL");
276
277
  if ((current.apiKey ?? "") !== draft.apiKey.trim()) changes.push("API key");
277
- if ((current.api ?? "") !== draft.api) changes.push("API 协议");
278
- if ((current.authHeader ?? false) !== draft.authHeader) changes.push("认证头");
278
+ if ((current.api ?? "") !== draft.api) changes.push(t("API 协议"));
279
+ if ((current.authHeader ?? false) !== draft.authHeader) changes.push(t("认证头"));
279
280
  if ((current.clientHeaderProfile ?? "recommended") !== draft.clientHeaderProfile
280
281
  || (current.requestHeaderProfileId ?? "") !== (draft.requestHeaderProfileId ?? ""))
281
- changes.push("请求头");
282
+ changes.push(t("请求头"));
282
283
  if ((current.httpProxyEnabled ?? false) !== draft.httpProxyEnabled
283
284
  || (current.httpProxyUrl?.trim() || DEFAULT_PROVIDER_HTTP_PROXY_URL) !== (draft.httpProxyUrl.trim() || DEFAULT_PROVIDER_HTTP_PROXY_URL)) {
284
- changes.push("本机代理");
285
+ changes.push(t("本机代理"));
285
286
  }
286
287
  if (changes.length === 0) return [];
287
- return [`将修改接入级配置:${changes.join("、")},会影响该接入下 ${affected} 个模型。`];
288
+ return [t("将修改接入级配置:{changes},会影响该接入下 {count} 个模型。", { changes: joinLocalizedList(changes), count: affected })];
288
289
  }
289
290
 
290
291
  // ========== build:draft → stored ==========
@@ -410,7 +411,7 @@ export function buildModelFromDraft(
410
411
  export function createRequestHeaderProfileDraft(): RequestHeaderProfileDraft {
411
412
  return {
412
413
  profileId: "custom-headers",
413
- profileName: "自定义请求头",
414
+ profileName: t("自定义请求头"),
414
415
  headers: {},
415
416
  selectedIndex: 0,
416
417
  };
@@ -446,17 +447,17 @@ export function validateRequestHeaderProfileDraft(
446
447
  ): string[] {
447
448
  const errors: string[] = [];
448
449
  const profileId = draft.profileId.trim();
449
- if (!profileId) errors.push("请求头 ID 不能为空");
450
- else if (!ID_PATTERN.test(profileId)) errors.push("请求头 ID 只能包含字母、数字、点、下划线和连字符");
451
- else if (RESERVED_REQUEST_HEADER_PROFILE_IDS.has(profileId)) errors.push(`请求头 ID 是插件内置保留名:${profileId}`);
450
+ if (!profileId) errors.push(t("请求头 ID 不能为空"));
451
+ else if (!ID_PATTERN.test(profileId)) errors.push(t("请求头 ID 只能包含字母、数字、点、下划线和连字符"));
452
+ else if (RESERVED_REQUEST_HEADER_PROFILE_IDS.has(profileId)) errors.push(t("请求头 ID 是插件内置保留名:{profileId}", { profileId }));
452
453
  if (profileId && oldProfileId !== profileId && document.requestHeaderProfiles[profileId]) {
453
- errors.push(`请求头 ID 已存在:${profileId}`);
454
+ errors.push(t("请求头 ID 已存在:{profileId}", { profileId }));
454
455
  }
455
- if (!draft.profileName.trim()) errors.push("请求头名称不能为空");
456
- if (!hasStringRecordEntries(draft.headers)) errors.push("请求头至少需要 1 项");
456
+ if (!draft.profileName.trim()) errors.push(t("请求头名称不能为空"));
457
+ if (!hasStringRecordEntries(draft.headers)) errors.push(t("请求头至少需要 1 项"));
457
458
  const sensitiveHeaders = Object.keys(draft.headers).filter(isSensitiveHeaderName);
458
459
  if (sensitiveHeaders.length > 0) {
459
- errors.push(`请求头包含会明文落盘的敏感字段:${sensitiveHeaders.join("、")}(请改用 provider API key / 环境变量 / !command)`);
460
+ errors.push(t("请求头包含会明文落盘的敏感字段:{headers}(请改用 provider API key / 环境变量 / !command)", { headers: joinLocalizedList(sensitiveHeaders) }));
460
461
  }
461
462
  return errors;
462
463
  }
@@ -560,7 +561,7 @@ export function upsertModelInDocument(
560
561
  ): StateDocument {
561
562
  const next: StateDocument = cloneJson(document);
562
563
  const provider = next.providers[draft.providerId];
563
- if (!provider) throw new Error(`upsertModel:接入不存在:${draft.providerId}`);
564
+ if (!provider) throw new Error(t("upsertModel:接入不存在:{providerId}", { providerId: draft.providerId }));
564
565
  const existing = (provider.models ?? []).find(
565
566
  (m) => m.id === options.replacedModelId || m.id === draft.modelId.trim(),
566
567
  );