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/file-snapshot.ts CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { createHash } from "node:crypto";
4
4
  import { readFile, stat } from "node:fs/promises";
5
+ import { t } from "./i18n.ts";
5
6
 
6
7
  export interface FileSignature {
7
8
  exists: boolean;
@@ -72,5 +73,5 @@ export async function readStableTextFileSnapshot(path: string): Promise<StableTe
72
73
  return { source, signature: after, contentHash: hashTextContent(source) };
73
74
  }
74
75
  }
75
- throw new Error(`${path} 在读取期间持续变化;请停止其它写入后重试。`);
76
+ throw new Error(t("{path} 在读取期间持续变化;请停止其它写入后重试。", { path }));
76
77
  }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
6
6
  import { persistManagedConfiguration } from "./configuration-persistence.ts";
7
+ import { t } from "./i18n.ts";
7
8
  import { registerAllFromState } from "./provider-registrar.ts";
8
9
  import { deleteRequestHeaderProfileFromDocument, upsertRequestHeaderProfileInDocument } from "./state-document.ts";
9
10
  import type { RequestHeaderProfileDraft, StateDocument, StoredProvider } from "./types.ts";
@@ -32,7 +33,7 @@ function notifyHeaderProfileRefresh(
32
33
  ctx.ui.notify(successMessage, "info");
33
34
  return;
34
35
  }
35
- ctx.ui.notify(`${successMessage},但以下接入未能刷新,已保留上一版 runtime:\n- ${warnings.join("\n- ")}`, "warning");
36
+ ctx.ui.notify(t("{successMessage},但以下接入未能刷新,已保留上一版 runtime:\n- {warnings}", { successMessage, warnings: warnings.join("\n- ") }), "warning");
36
37
  }
37
38
 
38
39
  export async function saveRequestHeaderProfileConfiguration(
@@ -49,7 +50,7 @@ export async function saveRequestHeaderProfileConfiguration(
49
50
  removedProviderIds: [],
50
51
  }));
51
52
  const warnings = await registerAllFromState(pi, nextState);
52
- notifyHeaderProfileRefresh(ctx, `已保存请求头 ${draft.profileId.trim()}`, warnings);
53
+ notifyHeaderProfileRefresh(ctx, t("已保存请求头 {profileId}", { profileId: draft.profileId.trim() }), warnings);
53
54
  }
54
55
 
55
56
  export async function deleteRequestHeaderProfileConfiguration(
@@ -64,5 +65,5 @@ export async function deleteRequestHeaderProfileConfiguration(
64
65
  removedProviderIds: [],
65
66
  }));
66
67
  const warnings = await registerAllFromState(pi, nextState);
67
- notifyHeaderProfileRefresh(ctx, `已删除请求头 ${profileId}`, warnings);
68
+ notifyHeaderProfileRefresh(ctx, t("已删除请求头 {profileId}", { profileId }), warnings);
68
69
  }
package/i18n.ts ADDED
@@ -0,0 +1,403 @@
1
+ export const SUPPORTED_UI_LANGUAGES = ["zh-CN", "en"] as const;
2
+
3
+ export type UiLanguage = (typeof SUPPORTED_UI_LANGUAGES)[number];
4
+
5
+ export const DEFAULT_UI_LANGUAGE: UiLanguage = "zh-CN";
6
+
7
+ const ENGLISH_MESSAGES = {
8
+ "语言 / Language": "Language",
9
+ "简体中文": "Simplified Chinese",
10
+ "English": "English",
11
+ "语言已切换为 {language}": "Language switched to {language}",
12
+ "语言设置保存失败:{error}": "Failed to save language setting: {error}",
13
+ "读取语言设置失败,已使用简体中文:{error}": "Failed to load the language setting; using Simplified Chinese: {error}",
14
+ "语言设置根节点必须是对象": "The language settings root must be an object",
15
+ "不支持的语言设置版本:{version}": "Unsupported language settings version: {version}",
16
+ "不支持的界面语言:{language}": "Unsupported interface language: {language}",
17
+
18
+ "过滤:": "Filter: ",
19
+ "搜索:": "Search: ",
20
+ "<输入关键词>": "<type keywords>",
21
+ "保留过滤": "Keep filter",
22
+ "清空搜索": "Clear search",
23
+ "继续输入": "Continue typing",
24
+ "清空过滤": "Clear filter",
25
+ "搜索": "Search",
26
+ "无匹配项:{query}": "No matches: {query}",
27
+ "暂无条目": "No entries",
28
+ "← 当前": "← current",
29
+ "移动": "Move",
30
+ "选择": "Select",
31
+ "返回": "Back",
32
+ "进入": "Open",
33
+ "编辑": "Edit",
34
+ "退出": "Exit",
35
+ "切换选项": "Toggle",
36
+ "保存并同步": "Save & sync",
37
+ "保存并启用": "Save & enable",
38
+
39
+ "<未填写>": "<not set>",
40
+ "<必填>": "<required>",
41
+ "<空>": "<empty>",
42
+ "<无模型>": "<no models>",
43
+ "<未选择>": "<not selected>",
44
+ "<未配置>": "<not configured>",
45
+ "默认": "Default",
46
+ "开启": "On",
47
+ "关闭": "Off",
48
+ "关闭时不使用": "Not used while off",
49
+ "自动推荐": "Recommended",
50
+ "不添加": "Disabled",
51
+ "自定义请求头": "Custom headers",
52
+ "内联自定义请求头({count}项)": "Inline custom headers ({count})",
53
+ "自定义:{id} — {name}": "Custom: {id} — {name}",
54
+ "自定义请求头(未选择)": "Custom headers (not selected)",
55
+ "自定义请求头缺失:{id}": "Missing custom header profile: {id}",
56
+
57
+ "接入": "Provider",
58
+ "模型": "Models",
59
+ "请求头": "Headers",
60
+ "代理": "Proxy",
61
+ "认证": "Auth",
62
+ "状态": "Status",
63
+ "模型 ID": "Model ID",
64
+ "显示名": "Display name",
65
+ "输入": "Input",
66
+ "上下文": "Context",
67
+ "输出": "Output",
68
+ "文本": "Text",
69
+ "文本,视觉": "Text,Vision",
70
+ "开": "On",
71
+ "关": "Off",
72
+ "API 协议": "API protocol",
73
+ "接入 ID(必填)": "Provider ID (required)",
74
+ "名称": "Name",
75
+ "本机代理": "Local proxy",
76
+ "代理地址": "Proxy URL",
77
+ "认证头": "Auth header",
78
+ "接入 ID 必填,且不能与已有或 pi 内置接入重复": "Provider ID is required and must not duplicate an existing or built-in Pi provider",
79
+ "Ctrl+S 保存并同步 models.json;不切换当前会话模型": "Ctrl+S saves and syncs models.json without switching the current session model",
80
+ "选择 API 协议": "Select API protocol",
81
+ "认证头(API key 放在哪里)": "Auth header (where the API key is sent)",
82
+ "默认 — 交给协议 SDK / 接入默认行为": "Default — use the protocol SDK/provider behavior",
83
+ "Bearer — 强制 Authorization: Bearer <apiKey>": "Bearer — force Authorization: Bearer <apiKey>",
84
+ "本机代理(仅当前接入点)": "Local proxy (this provider only)",
85
+ "关闭 — 请求直连上游": "Off — connect directly to upstream",
86
+ "开启 — 通过 {url}": "On — route through {url}",
87
+ "接入 ID(必填,最多 48 个字符;仅字母、数字、点、下划线和连字符;当前:{current})": "Provider ID (required, max 48 characters; letters, digits, dots, underscores, and hyphens only; current: {current})",
88
+ "名称(显示用,可留空;当前:{current})": "Name (optional display label; current: {current})",
89
+ "代理地址(http/https;当前:{current},留空保持原值)": "Proxy URL (http/https; current: {current}; leave blank to keep it)",
90
+ "API key(可选;明文 / $ENV_VAR / !command;当前:{current},留空清除)": "API key (optional; literal / $ENV_VAR / !command; current: {current}; leave blank to clear)",
91
+ "Base URL(http/https)(当前:{current},留空保持原值)": "Base URL (http/https; current: {current}; leave blank to keep it)",
92
+
93
+ "重新拉取": "Refresh list",
94
+ "上游模型列表": "Upstream model list",
95
+ "显示名称": "Display name",
96
+ "默认 = 模型 ID": "Default = model ID",
97
+ "视觉支持": "Vision input",
98
+ "上下文窗口": "Context window",
99
+ "最大输出": "Max output",
100
+ "开启 · 新版协议": "On · current protocol",
101
+ "关闭 · Legacy": "Off · Legacy",
102
+ "开启 · priority": "On · priority",
103
+ "正在拉取模型列表,总计最多 10 秒…": "Fetching the model list (10 seconds maximum)…",
104
+ "拉取失败:{error}": "Fetch failed: {error}",
105
+ "手动输入模型 ID(当前:{current})": "Enter a model ID manually (current: {current})",
106
+ "上游返回空列表": "Upstream returned an empty list",
107
+ "选择模型 ID(共 {count} 个)": "Select a model ID ({count} available)",
108
+ "{label}(当前:{current},留空保持原值)": "{label} (current: {current}; leave blank to keep it)",
109
+ "{label} 必须是正整数": "{label} must be a positive integer",
110
+ "模型 ID(当前:{current},传给上游 API 的模型字段)": "Model ID (current: {current}; sent as the upstream API model field)",
111
+ "显示名称(当前:{current},可空默认用模型 ID;输入空格清空)": "Display name (current: {current}; blank uses the model ID; enter a space to clear)",
112
+ "关闭 — 仅文本输入": "Off — text input only",
113
+ "开启 — 文本 + 图片输入": "On — text and image input",
114
+ "关闭 — 不发送模型推理参数": "Off — do not send reasoning parameters",
115
+ "开启 — 启用模型推理参数": "On — enable reasoning parameters",
116
+ "开启:新版模型,发送 thinking.type=adaptive 和 output_config.effort": "On: current models; send thinking.type=adaptive and output_config.effort",
117
+ "关闭:旧版接口,发送 thinking.type=enabled 和 budget_tokens": "Off: legacy API; send thinking.type=enabled and budget_tokens",
118
+ "关闭 — 不发送 service_tier(默认)": "Off — do not send service_tier (default)",
119
+ "开启 — service_tier=priority,可能消耗 Fast / priority 额度": "On — service_tier=priority; may consume Fast/priority quota",
120
+ "接入 {providerId} · API {api}": "Provider {providerId} · API {api}",
121
+ "Ctrl+S 保存并启用模型;不切换当前会话模型": "Ctrl+S saves and enables the model without switching the current session model",
122
+
123
+ "页码 0 / 0": "Page 0 / 0",
124
+ "页码 {page} / {pages}": "Page {page} / {pages}",
125
+ "搜索: ": "Search: ",
126
+ "<直接输入搜索>": "<type to search>",
127
+ "匹配 {matched} / {total} · {page}": "Matches {matched} / {total} · {page}",
128
+ "没有匹配模型;Backspace 删除搜索词,Esc 返回后可手动输入。": "No matching models. Use Backspace to edit the search, or Esc to enter an ID manually.",
129
+ " ← 当前": " ← current",
130
+ "↑↓ 选择 · ←→/PgUp/PgDn 翻页 · 输入搜索 · Backspace 删除 · Enter 确认 · Esc 取消": "↑↓ select · ←→/PgUp/PgDn page · type to search · Backspace delete · Enter confirm · Esc cancel",
131
+
132
+ "OpenAI Responses · 标准 instructions/input wire": "OpenAI Responses · standard instructions/input wire",
133
+ "OpenAI Chat · 传统 chat/completions 兼容": "OpenAI Chat · legacy chat/completions compatibility",
134
+ "Anthropic Messages · Claude / Claude Code 兼容": "Anthropic Messages · Claude / Claude Code compatibility",
135
+ "Google Gemini · Gemini 原生 API": "Google Gemini · native Gemini API",
136
+
137
+ "请确认改动": "Confirm changes",
138
+ "{warnings}\n\n继续保存?": "{warnings}\n\nContinue saving?",
139
+ "{title}:\n{errors}": "{title}:\n{errors}",
140
+ "接入配置无效": "Invalid provider configuration",
141
+ "模型配置无效": "Invalid model configuration",
142
+ "保存失败:{error}": "Save failed: {error}",
143
+ "删除失败:{error}": "Delete failed: {error}",
144
+ "删除接入 {providerId}": "Delete provider {providerId}",
145
+ "将删除 {name} 下全部 {count} 个模型。": "Delete {name} and all of its models ({count}).",
146
+ "删除模型 {fullId}": "Delete model {fullId}",
147
+ "这是该接入下最后一个模型;删除后接入也会从 models.json 中移除。": "This is the provider's last model; deleting it will also remove the provider from models.json.",
148
+ "只删除该模型,接入保留。": "Delete only this model and keep the provider.",
149
+ "模型不存在:{fullId}": "Model not found: {fullId}",
150
+ "编辑模型 {fullId}": "Edit model {fullId}",
151
+ "接入配置已不存在:{providerId}": "Provider configuration no longer exists: {providerId}",
152
+ "编辑模型": "Edit model",
153
+ "添加模型": "Add model",
154
+ "编辑接入": "Edit provider",
155
+ "删除模型": "Delete model",
156
+ "暂无模型;按 a 添加第一个模型": "No models. Press A to add the first model.",
157
+ "添加模型到 {providerId}": "Add model to {providerId}",
158
+ "编辑接入 {providerId}": "Edit provider {providerId}",
159
+ "没有可删除的模型;删除接入请返回上一级按 d。": "There are no models to delete. Return to the previous menu and press D to delete the provider.",
160
+ "新建接入配置": "New provider configuration",
161
+ "请继续添加第一个模型;取消模型编辑则不会创建该接入。": "Add the first model next. Cancelling the model editor will leave the provider uncreated.",
162
+ "新建接入": "New provider",
163
+ "删除接入": "Delete provider",
164
+ "{providers} 接入 · {models} 模型 · {captures} 内置抓包 · {profiles} 自定义请求头": "Providers: {providers} · Models: {models} · Built-in captures: {captures} · Custom headers: {profiles}",
165
+ "请求头管理": "Headers",
166
+ "暂无自定义接入;按 n 新建": "No custom providers. Press N to create one.",
167
+ "没有可删除的接入。": "There are no providers to delete.",
168
+
169
+ "OpenAI 兼容端点使用的终端 Codex TUI 请求头。": "Terminal Codex TUI headers for OpenAI-compatible endpoints.",
170
+ "Anthropic 兼容端点常用的 ClaudeCode 请求头。": "Common ClaudeCode headers for Anthropic-compatible endpoints.",
171
+ "清空": "Clear",
172
+ "清空当前请求头,重新手动填写。": "Clear the current headers and enter them manually.",
173
+ "未抓包": "Not captured",
174
+ "已抓包 {time} · {count} headers": "Captured {time} · {count} headers",
175
+ "自定义 ID": "Custom ID",
176
+ "请求头 ID": "Header ID",
177
+ "请求头名称": "Header name",
178
+ "快速模板": "Quick template",
179
+ "选择后填充": "Select to populate",
180
+ "请求头 JSON": "Header JSON",
181
+ "{count}项": "{count} entries",
182
+ "未配置": "Not configured",
183
+ "请求头无效:\n{errors}": "Invalid headers:\n{errors}",
184
+ "结构:JSON 对象;key 是客户端 header 名,value 是字符串。复杂示例请用“快速模板”。": "Format: a JSON object whose keys are client header names and values are strings. Use Quick template for complete examples.",
185
+ "请求头 JSON 无效:{error}": "Invalid header JSON: {error}",
186
+ "选择请求头模板": "Select a header template",
187
+ "已清空请求头": "Headers cleared",
188
+ "已填充模板:{template},可继续进入“请求头 JSON”微调。": "Template applied: {template}. Open Header JSON to customize it.",
189
+ "请求头 ID(接入引用这个 ID;字母/数字/._-)": "Header ID (referenced by providers; letters/digits/._-)",
190
+ "请求头名称(显示用)": "Header name (display only)",
191
+ "认证类敏感 header 会被拒绝;API key 请放在接入配置中": "Sensitive authentication headers are rejected; configure the API key on the provider instead",
192
+ "请求头不存在:{profileId}": "Header profile not found: {profileId}",
193
+ "删除请求头 {profileId}": "Delete header profile {profileId}",
194
+ "将删除 {name}。{affected}": "Delete {name}.{affected}",
195
+ "\n{count} 个模型会自动改回“自动推荐”。": "\nAffected models ({count}) will automatically revert to Recommended.",
196
+ "编辑请求头 {profileId}": "Edit header profile {profileId}",
197
+ "/model-manager / 请求头": "/model-manager / Headers",
198
+ "编辑请求头": "Edit headers",
199
+ "新建自定义": "New custom profile",
200
+ "删除": "Delete",
201
+ "暂无自定义请求头;按 n 新建": "No custom header profiles. Press N to create one.",
202
+ "新建请求头": "New header profile",
203
+ "没有可删除的请求头。": "There are no header profiles to delete.",
204
+
205
+ "模型接入与请求配置 / Model and provider settings": "Model and provider settings / 模型接入与请求配置",
206
+ "/model-manager 需要 TUI 交互模式": "/model-manager requires interactive TUI mode",
207
+
208
+ "可先返回上一级选择“快速模板”,也可在这里填写:": "Return to Quick template first, or enter headers here:",
209
+
210
+ "恢复未完成配置事务失败:{error}(为避免读取半完成配置,本次暂不注册模型)": "Failed to recover an incomplete configuration transaction: {error} (models will not be registered this time to avoid reading a partially written configuration)",
211
+ "读取 models.json/state.json 失败:{error}(本次启动仅使用内存空配置,不覆盖原文件)": "Failed to read models.json/state.json: {error} (this startup will use an empty in-memory configuration without overwriting the files)",
212
+ "注册模型目录失败:{warning}": "Failed to register the model catalog: {warning}",
213
+ "读取/注册模型配置失败:{error}": "Failed to read/register the model configuration: {error}",
214
+ "激活模型接入失败:{warning}": "Failed to activate a model provider: {warning}",
215
+ "恢复、读取或激活模型配置失败:{error}": "Failed to recover, read, or activate the model configuration: {error}",
216
+ "[pi-model-manager] 已补全 {count} 个接入的请求地址({providerIds}),现在 models.json 存的就是实际请求根地址": "[pi-model-manager] Normalized request URLs for {count} provider(s) ({providerIds}); models.json now contains the actual request root URLs",
217
+
218
+ "{label} JSON 必须是对象": "{label} JSON must be an object",
219
+ "{label} {key} 的值必须是字符串": "The value of {label} {key} must be a string",
220
+ "写入 {targetPath} 失败:{error}": "Failed to write {targetPath}: {error}",
221
+ "写入 {targetPath} 失败;完整内容已保留在临时文件:{tempPath}:{error}": "Failed to write {targetPath}; the complete content remains in temporary file {tempPath}: {error}",
222
+ "另一个 Pi 进程正在保存模型配置;无法在限定时间内获取锁:{path}": "Another Pi process is saving the model configuration; the lock could not be acquired in time: {path}",
223
+ "配置锁所有权在释放前发生变化,已保留锁文件供检查:{path}": "The configuration lock ownership changed before release; the lock file was retained for inspection: {path}",
224
+ "{path} 必须是对象": "{path} must be an object",
225
+ "{path}.oldSource 必须是字符串或 null": "{path}.oldSource must be a string or null",
226
+ "{path} 缺少有效内容或签名": "{path} is missing valid content or a signature",
227
+ "{path} 内容签名校验失败": "Content signature verification failed for {path}",
228
+ "事务意图文件格式无效": "The transaction intent file is invalid",
229
+ "{path} 的当前内容既不是事务旧版本,也不是目标版本;已保留 {transactionPath},不会覆盖外部修改。": "The current content of {path} matches neither the old nor target transaction version; {transactionPath} was retained and external changes will not be overwritten.",
230
+ "{path} 写入后内容签名不匹配;已保留 {transactionPath} 供恢复。": "The content signature of {path} did not match after writing; {transactionPath} was retained for recovery.",
231
+ "无法解析未完成事务 {transactionPath}:{error}": "Failed to parse incomplete transaction {transactionPath}: {error}",
232
+ "{path} 已被其它进程或编辑器修改;已取消本次保存,请重新打开 /model-manager 后重试。": "{path} was modified by another process or editor; the save was cancelled. Reopen /model-manager and try again.",
233
+ "配置事务未完成:{error}。下次启动或保存会尝试恢复。": "The configuration transaction did not complete: {error}. Recovery will be attempted on the next startup or save.",
234
+ "models.json/state.json 未完整保存:{error}": "models.json/state.json were not fully saved: {error}",
235
+ "models.json/state.json 已写入,但当前会话 registry 重载失败:{error}。可执行 /reload 重试。": "models.json/state.json were written, but the current session registry failed to reload: {error}. Run /reload to retry.",
236
+ "{path} 在读取期间持续变化;请停止其它写入后重试。": "{path} kept changing while being read; stop other writers and try again.",
237
+
238
+ "{successMessage},但以下接入未能刷新,已保留上一版 runtime:\n- {warnings}": "{successMessage}, but the following providers could not be refreshed and retain their previous runtime:\n- {warnings}",
239
+ "已保存请求头 {profileId}": "Saved header profile {profileId}",
240
+ "已删除请求头 {profileId}": "Deleted header profile {profileId}",
241
+ "代理地址无效:{url}": "Invalid proxy URL: {url}",
242
+ "代理地址目前只支持 http:// 或 https:// 代理": "Only http:// or https:// proxies are currently supported",
243
+ "代理请求失败:{code}": "Proxy request failed: {code}",
244
+ "无错误消息": "no error message",
245
+ "未知代理错误": "Unknown proxy error",
246
+ "不支持的上游协议:{protocol}": "Unsupported upstream protocol: {protocol}",
247
+ "本地代理服务正在关闭,请稍后重试": "The local proxy service is shutting down; try again shortly",
248
+ "本地代理转发服务监听地址异常": "The local proxy forwarding service returned an invalid listen address",
249
+
250
+ "内置接入 {providerId} 不允许通过 /model-manager 编辑或删除。": "Built-in provider {providerId} cannot be edited or deleted through /model-manager.",
251
+ "当前未限制 enabledModels,重启后默认可选": "enabledModels is unrestricted; the model will be available by default after restart",
252
+ "已写入项目 enabledModels": "Written to project enabledModels",
253
+ "已写入全局 enabledModels": "Written to global enabledModels",
254
+ "已在 enabledModels 中": "Already present in enabledModels",
255
+ "已保存并启用模型": "Saved and enabled model",
256
+ "已创建并启用模型": "Created and enabled model",
257
+ "{messagePrefix} {fullId}({availability})": "{messagePrefix} {fullId} ({availability})",
258
+ "已保存模型 {fullId},但启用校验有警告:\n- {warnings}": "Saved model {fullId}, but availability verification reported warnings:\n- {warnings}",
259
+ "已保存模型 {fullId},但启用同步/校验失败:{error}": "Saved model {fullId}, but availability synchronization/verification failed: {error}",
260
+ "models.json/state.json 已保存,但当前会话接入刷新失败:{error}。可执行 /reload 重试。": "models.json/state.json were saved, but the current session provider refresh failed: {error}. Run /reload to retry.",
261
+ "已保存接入 {providerId}": "Saved provider {providerId}",
262
+ "已同步项目 enabledModels 中的接入重命名": "Synchronized the provider rename in project enabledModels",
263
+ "已同步全局 enabledModels 中的接入重命名": "Synchronized the provider rename in global enabledModels",
264
+ "接入已保存,但 enabledModels 同步失败:{error}": "The provider was saved, but enabledModels synchronization failed: {error}",
265
+ "接入 {oldProviderId} 已重命名为 {providerId}": "Provider {oldProviderId} was renamed to {providerId}",
266
+ "模型 {oldFullId} 已重命名为 {newFullId}": "Model {oldFullId} was renamed to {newFullId}",
267
+ "接入已删除,但 enabledModels 清理失败:{error}": "The provider was deleted, but enabledModels cleanup failed: {error}",
268
+ "已删除接入 {providerId}": "Deleted provider {providerId}",
269
+ "接入 {providerId} 已删除": "Provider {providerId} was deleted",
270
+ "模型已删除,但 enabledModels 清理失败:{error}": "The model was deleted, but enabledModels cleanup failed: {error}",
271
+ "已删除模型 {fullId}": "Deleted model {fullId}",
272
+ "模型 {fullId} 已删除": "Model {fullId} was deleted",
273
+
274
+ "models.json 根节点必须是对象": "The models.json root must be an object",
275
+ "models.json 中不存在待重命名接入:{providerId}": "Provider to rename was not found in models.json: {providerId}",
276
+ "models.json 中已存在接入:{providerId}": "Provider already exists in models.json: {providerId}",
277
+ "models.json 中不存在接入:{providerId}": "Provider was not found in models.json: {providerId}",
278
+ "models.json 中不存在待重命名模型:{fullId}": "Model to rename was not found in models.json: {fullId}",
279
+ "models.json 中已存在模型:{fullId}": "Model already exists in models.json: {fullId}",
280
+ "接入不存在:{providerId}": "Provider not found: {providerId}",
281
+ "{path} 根节点必须是对象": "The root of {path} must be an object",
282
+ "{path} 已被未遵守 Pi 文件锁的编辑器修改;已取消 enabledModels 同步,请重试。": "{path} was modified by an editor that did not honor Pi's file lock; enabledModels synchronization was cancelled. Try again.",
283
+ "{label} 未找到模型 {fullId}": "{label} could not find model {fullId}",
284
+ "{label} 找到模型 {fullId},但 API key 未配置或不可解析": "{label} found model {fullId}, but its API key is missing or cannot be resolved",
285
+ "{label} 请求认证解析失败:{error}": "{label} failed to resolve request authentication: {error}",
286
+ "当前会话 registry": "Current session registry",
287
+ "原生 models.json registry": "Native models.json registry",
288
+ "原生 models.json registry 校验失败:{error}": "Native models.json registry verification failed: {error}",
289
+
290
+ ";恢复上一版 runtime 也失败:{error}": "; restoring the previous runtime also failed: {error}",
291
+ ";已恢复上一版 runtime": "; restored the previous runtime",
292
+ ";新配置未注册到当前 runtime": "; the new configuration was not registered in the current runtime",
293
+ "ClaudeCode metadata 注入失败,本次请求仅使用请求头": "ClaudeCode metadata injection failed; this request will use headers only",
294
+ "OpenAI Responses instructions 标准化失败,本次请求使用原始 payload": "OpenAI Responses instruction normalization failed; this request will use the original payload",
295
+ "Fast mode 状态读取失败,本次请求未注入 service_tier": "Failed to read Fast mode state; service_tier was not injected for this request",
296
+ "{reason},已切换到 {fullId}": "{reason}; switched to {fullId}",
297
+ "{reason},已自动切换到 {fullId}": "{reason}; automatically switched to {fullId}",
298
+ "{reason},但当前没有其它可用模型。请使用 /model-manager 添加模型或 /login 配置认证。": "{reason}, but no other model is currently available. Use /model-manager to add a model or /login to configure authentication.",
299
+
300
+ "{label} 必须使用 http 或 https": "{label} must use http or https",
301
+ "{label} 不是有效 URL": "{label} is not a valid URL",
302
+ "代理地址必须包含主机名": "The proxy URL must include a hostname",
303
+ "代理地址不是有效 URL": "The proxy URL is invalid",
304
+ "接入 ID 不能为空": "Provider ID must not be empty",
305
+ "接入 ID 只能包含字母、数字、点、下划线和连字符": "Provider ID may contain only letters, digits, dots, underscores, and hyphens",
306
+ "接入 ID 最多 {count} 个字符": "Provider ID must be at most {count} characters",
307
+ "接入 ID 已存在:{id}": "Provider ID already exists: {id}",
308
+ "接入 ID 与 pi 内置接入冲突:{id}(请改用其它 ID)": "Provider ID conflicts with a built-in Pi provider: {id} (use a different ID)",
309
+ "Base URL 不能为空": "Base URL must not be empty",
310
+ "请选择一个自定义请求头": "Select a custom header profile",
311
+ "自定义请求头不存在:{profileId}": "Custom header profile not found: {profileId}",
312
+ "模型 ID 不能为空": "Model ID must not be empty",
313
+ "接入配置不存在:{providerId}": "Provider configuration not found: {providerId}",
314
+ "上下文窗口必须是正整数": "Context window must be a positive integer",
315
+ "最大输出必须是正整数": "Max output must be a positive integer",
316
+ "模型已存在:{modelId}": "Model already exists: {modelId}",
317
+ "将修改接入级配置:{changes},会影响该接入下 {count} 个模型。": "Provider-level settings will change ({changes}), affecting {count} model(s) under this provider.",
318
+ "请求头 ID 不能为空": "Header profile ID must not be empty",
319
+ "请求头 ID 只能包含字母、数字、点、下划线和连字符": "Header profile ID may contain only letters, digits, dots, underscores, and hyphens",
320
+ "请求头 ID 是插件内置保留名:{profileId}": "Header profile ID is reserved by the plugin: {profileId}",
321
+ "请求头 ID 已存在:{profileId}": "Header profile ID already exists: {profileId}",
322
+ "请求头名称不能为空": "Header profile name must not be empty",
323
+ "请求头至少需要 1 项": "At least one header is required",
324
+ "请求头包含会明文落盘的敏感字段:{headers}(请改用 provider API key / 环境变量 / !command)": "Headers contain sensitive fields that would be stored in plaintext: {headers} (use the provider API key, an environment variable, or !command instead)",
325
+ "upsertModel:接入不存在:{providerId}": "upsertModel: provider not found: {providerId}",
326
+
327
+ "必须是非空字符串": "must be a non-empty string",
328
+ "必须是字符串": "must be a string",
329
+ "必须是 boolean": "must be a boolean",
330
+ "必须是正整数": "must be a positive integer",
331
+ "必须是对象": "must be an object",
332
+ "值必须是字符串": "value must be a string",
333
+ "必须是字符串数组": "must be an array of strings",
334
+ "必须是字符串或 null": "must be a string or null",
335
+ "必须是有限数字": "must be a finite number",
336
+ "必须是非负数": "must be non-negative",
337
+ "必须是数组": "must be an array",
338
+ "必须是 text 或 image": "must be text or image",
339
+ "必须是合法 API 协议": "must be a valid API protocol",
340
+ "必须是合法请求头配置": "must be a valid header profile",
341
+ "必须是合法 service tier": "must be a valid service tier",
342
+ "状态文件格式无效:{details}": "Invalid state file format: {details}",
343
+ "状态文件版本不受支持:{version}": "Unsupported state file version: {version}",
344
+ "读取状态文件失败:{error}": "Failed to read the state file: {error}",
345
+ "state.json {path}: {message}": "state.json {path}: {message}",
346
+ "未知 API 协议:{value}": "unknown API protocol: {value}",
347
+ "未知请求头:{value}": "unknown request-header profile: {value}",
348
+ "未知 OpenAI service tier:{value}": "unknown OpenAI service tier: {value}",
349
+ "必须是非空数组": "must be a non-empty array",
350
+ "必须是非负数字": "must be a non-negative number",
351
+ "未知 thinking level": "unknown thinking level",
352
+ "不能使用插件内置请求头保留名": "cannot use a request-header name reserved by the plugin",
353
+ "只能保存 ClaudeCode/Codex 内置 profile 的抓包数据": "only captured data for the built-in ClaudeCode/Codex profiles can be saved",
354
+ "根节点必须是对象": "root must be an object",
355
+ "不支持的版本:{version}": "unsupported version: {version}",
356
+ "models.json/state.json 正在事务更新或持续变化;请稍后重试。": "models.json/state.json is being updated by a transaction or changing continuously. Please try again shortly.",
357
+ "模型发现已取消": "Model discovery was cancelled",
358
+ "临时模型注册失败,无法解析模型列表认证": "Temporary model registration failed; model-list authentication could not be resolved",
359
+ "请求认证解析失败": "Failed to resolve request authentication",
360
+ "API key 未配置或解析为空,无法拉取模型列表": "The API key is not configured or resolved to an empty value; the model list cannot be fetched",
361
+ "模型列表请求总计超时(10 秒)": "The model-list request timed out after 10 seconds",
362
+ "上游模型 ID 长度必须为 1-{maxLength} 个字符": "Upstream model IDs must be 1-{maxLength} characters long",
363
+ "上游模型 ID 包含控制字符或终端转义序列,已拒绝显示": "An upstream model ID contains control characters or terminal escape sequences and was rejected",
364
+ "上游返回 {count} 个模型,超过上限 {maxCount}": "The upstream returned {count} models, exceeding the limit of {maxCount}",
365
+ "模型列表响应体超过 {maxBytes} 字节上限": "The model-list response exceeds the {maxBytes}-byte limit",
366
+ } as const;
367
+
368
+ export type MessageKey = keyof typeof ENGLISH_MESSAGES;
369
+ export type TranslationValues = Readonly<Record<string, string | number>>;
370
+
371
+ let currentLanguage: UiLanguage = DEFAULT_UI_LANGUAGE;
372
+
373
+ export function isUiLanguage(value: unknown): value is UiLanguage {
374
+ return typeof value === "string" && (SUPPORTED_UI_LANGUAGES as readonly string[]).includes(value);
375
+ }
376
+
377
+ export function getUiLanguage(): UiLanguage {
378
+ return currentLanguage;
379
+ }
380
+
381
+ export function setUiLanguage(language: UiLanguage): void {
382
+ currentLanguage = language;
383
+ }
384
+
385
+ function interpolate(template: string, values: TranslationValues): string {
386
+ return template.replace(/\{([A-Za-z][A-Za-z0-9]*)\}/g, (placeholder, name: string) => {
387
+ const value = values[name];
388
+ return value === undefined ? placeholder : String(value);
389
+ });
390
+ }
391
+
392
+ export function t(key: MessageKey, values: TranslationValues = {}): string {
393
+ const template = currentLanguage === "en" ? ENGLISH_MESSAGES[key] : key;
394
+ return interpolate(template, values);
395
+ }
396
+
397
+ export function joinLocalizedList(items: readonly string[]): string {
398
+ return items.join(currentLanguage === "en" ? ", " : "、");
399
+ }
400
+
401
+ export function getEnglishMessageEntries(): ReadonlyArray<readonly [MessageKey, string]> {
402
+ return Object.entries(ENGLISH_MESSAGES) as Array<[MessageKey, string]>;
403
+ }
package/index.ts CHANGED
@@ -10,8 +10,11 @@
10
10
 
11
11
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
12
  import { formatUnknownError } from "./common.ts";
13
- import { recoverPendingConfigurationTransaction } from "./configuration-persistence.ts";
13
+ import { DEFAULT_UI_LANGUAGE, joinLocalizedList, setUiLanguage, t } from "./i18n.ts";
14
+ import { readUiLanguage } from "./ui-language-settings.ts";
15
+ import { persistManagedConfiguration, recoverPendingConfigurationTransaction } from "./configuration-persistence.ts";
14
16
  import { resetClaudeCodeMetadataSession } from "./claude-code-compat.ts";
17
+ import { findProvidersNeedingBaseUrlNormalization, normalizeProviderBaseUrlsInDocument } from "./state-document.ts";
15
18
  import { closeLocalProxyServer } from "./local-proxy-service.ts";
16
19
  import { registerAllFromState, registerCatalogFromState } from "./provider-registrar.ts";
17
20
  import { createRequestPipeline } from "./request-pipeline.ts";
@@ -24,25 +27,31 @@ interface StartupSummary {
24
27
 
25
28
  export default async function modelManagerExtension(pi: ExtensionAPI): Promise<void> {
26
29
  const summary: StartupSummary = { startupErrors: [] };
30
+ setUiLanguage(DEFAULT_UI_LANGUAGE);
31
+ try {
32
+ setUiLanguage(await readUiLanguage());
33
+ } catch (error) {
34
+ summary.startupErrors.push(t("读取语言设置失败,已使用简体中文:{error}", { error: formatUnknownError(error) }));
35
+ }
27
36
 
28
37
  let configurationBlocked = false;
29
38
  try {
30
39
  await recoverPendingConfigurationTransaction();
31
40
  } catch (error) {
32
41
  configurationBlocked = true;
33
- summary.startupErrors.push(`恢复未完成配置事务失败:${formatUnknownError(error)}(为避免读取半完成配置,本次暂不注册模型)`);
42
+ summary.startupErrors.push(t("恢复未完成配置事务失败:{error}(为避免读取半完成配置,本次暂不注册模型)", { error: formatUnknownError(error) }));
34
43
  }
35
44
  if (!configurationBlocked) {
36
45
  try {
37
46
  const stateForStartup = await readState().catch((error) => {
38
- summary.startupErrors.push(`读取 models.json/state.json 失败:${formatUnknownError(error)}(本次启动仅使用内存空配置,不覆盖原文件)`);
47
+ summary.startupErrors.push(t("读取 models.json/state.json 失败:{error}(本次启动仅使用内存空配置,不覆盖原文件)", { error: formatUnknownError(error) }));
39
48
  return createEmptyState();
40
49
  });
41
50
  for (const warning of await registerCatalogFromState(pi, stateForStartup)) {
42
- summary.startupErrors.push(`注册模型目录失败:${warning}`);
51
+ summary.startupErrors.push(t("注册模型目录失败:{warning}", { warning }));
43
52
  }
44
53
  } catch (error) {
45
- summary.startupErrors.push(`读取/注册模型配置失败:${formatUnknownError(error)}`);
54
+ summary.startupErrors.push(t("读取/注册模型配置失败:{error}", { error: formatUnknownError(error) }));
46
55
  }
47
56
  }
48
57
 
@@ -52,6 +61,7 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
52
61
  pi.on("session_start", async (event, ctx) => {
53
62
  resetClaudeCodeMetadataSession();
54
63
  const transportErrors: string[] = [];
64
+ let migratedBaseUrlProviderIds: string[] = [];
55
65
  try {
56
66
  if (configurationBlocked) {
57
67
  await recoverPendingConfigurationTransaction();
@@ -59,11 +69,22 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
59
69
  }
60
70
  const currentState = await readState();
61
71
  for (const warning of await registerAllFromState(pi, currentState)) {
62
- transportErrors.push(`激活模型接入失败:${warning}`);
72
+ transportErrors.push(t("激活模型接入失败:{warning}", { warning }));
73
+ }
74
+ // [喵喵喵]: 一次性补齐早期版本留在 models.json 里的半成品 baseUrl;
75
+ // 归一化幂等,写完后后续启动检测不到差异,不会重复写盘。
76
+ const staleBaseUrlProviderIds = findProvidersNeedingBaseUrlNormalization(currentState);
77
+ if (staleBaseUrlProviderIds.length > 0) {
78
+ await persistManagedConfiguration(ctx, (latest) => ({
79
+ document: normalizeProviderBaseUrlsInDocument(latest, staleBaseUrlProviderIds),
80
+ changedProviderIds: [...staleBaseUrlProviderIds],
81
+ removedProviderIds: [],
82
+ }));
83
+ migratedBaseUrlProviderIds = staleBaseUrlProviderIds;
63
84
  }
64
85
  } catch (error) {
65
86
  configurationBlocked = true;
66
- transportErrors.push(`恢复、读取或激活模型配置失败:${formatUnknownError(error)}`);
87
+ transportErrors.push(t("恢复、读取或激活模型配置失败:{error}", { error: formatUnknownError(error) }));
67
88
  }
68
89
 
69
90
  if (event.reason === "startup" && !notified) {
@@ -75,6 +96,15 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
75
96
  for (const error of transportErrors) {
76
97
  ctx.ui.notify(`[pi-model-manager] ${error}`, "error");
77
98
  }
99
+ if (migratedBaseUrlProviderIds.length > 0) {
100
+ ctx.ui.notify(
101
+ t("[pi-model-manager] 已补全 {count} 个接入的请求地址({providerIds}),现在 models.json 存的就是实际请求根地址", {
102
+ count: migratedBaseUrlProviderIds.length,
103
+ providerIds: joinLocalizedList(migratedBaseUrlProviderIds),
104
+ }),
105
+ "info",
106
+ );
107
+ }
78
108
  });
79
109
 
80
110
  pi.on("before_provider_request", async (event, ctx) => requestPipeline.transform(event.payload, ctx));
@@ -84,10 +114,10 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
84
114
 
85
115
  // ---- 3. 命令:/model-manager → TUI 面板 ----
86
116
  pi.registerCommand("model-manager", {
87
- description: "模型接入与请求配置",
117
+ description: t("模型接入与请求配置 / Model and provider settings"),
88
118
  handler: async (_args, ctx) => {
89
119
  if (ctx.mode !== "tui") {
90
- ctx.ui.notify("/model-manager 需要 TUI 交互模式", "error");
120
+ ctx.ui.notify(t("/model-manager 需要 TUI 交互模式"), "error");
91
121
  return;
92
122
  }
93
123
  await runDashboard(pi, ctx);