pi-model-manager 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  English · [简体中文](./README.md)
4
4
 
5
- [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.84.2-6f42c1)](https://github.com/earendil-works/pi)
5
+ [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.85.1-6f42c1)](https://github.com/earendil-works/pi)
6
6
  [![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](./LICENSE)
7
- [![Version](https://img.shields.io/badge/version-0.3.2-2f81f7.svg)](https://github.com/Qihuanxishini/pi-model-manager)
7
+ [![Version](https://img.shields.io/badge/version-0.3.6-2f81f7.svg)](https://github.com/Qihuanxishini/pi-model-manager)
8
8
 
9
9
  A TUI model and provider manager for [Pi](https://github.com/earendil-works/pi). It keeps Pi's native `models.json` as the single source of truth for model configuration while adding provider/model editing, client-header identities, proxy routing, and protocol compatibility controls.
10
10
 
11
- > The current stable version is `0.3.2` and requires Pi `>=0.84.2`.
11
+ > This extension requires Pi `>=0.85.1`.
12
12
 
13
13
  ## Interface preview
14
14
 
@@ -128,6 +128,7 @@ Ctrl+S 保存并启用模型;不切换当前会话模型
128
128
  - Create, edit, and delete providers and models from the `/model-manager` TUI.
129
129
  - Start in Simplified Chinese and press `L` on the dashboard to switch to English; the language preference is saved.
130
130
  - Supports `openai-completions`, `openai-responses`, `anthropic-messages`, and `google-generative-ai`.
131
+ - Choose Pi's standard default behavior or a `system`-role compatibility mode for OpenAI Chat providers.
131
132
  - Fetch model IDs from compatible upstream APIs or enter them manually.
132
133
  - Configure context window, maximum output, vision support, and reasoning support.
133
134
  - Choose Anthropic Adaptive Thinking or Legacy Thinking.
@@ -202,9 +203,22 @@ Each provider can define:
202
203
  - Provider-specific HTTP(S) proxy
203
204
  - One or more models
204
205
 
205
- When adding a model, the extension attempts to fetch the upstream model list. The complete discovery flow, including authentication fallbacks, shares one 10-second limit and can be cancelled with `Esc`. You can still enter a model ID manually after failure or cancellation.
206
+ When adding a model, the extension attempts to fetch the upstream model list. The complete discovery flow shares one 10-second limit and can be cancelled with `Esc`. Discovery uses the same API root and configured credentials as chat, and distinguishes authentication failures, missing endpoints, rate limits, and upstream errors. You can still enter a model ID manually after failure or cancellation.
206
207
 
207
- The base URL is normalized as you enter it into the root address each protocol's SDK expects: OpenAI variants get `/v1` appended, Anthropic has `/v1` stripped, and Google gets `/v1beta` on its official host. A non-root path you type explicitly (such as `https://gw.example.com/custom`) is never rewritten. Switching the API protocol re-normalizes the address for the new protocol. As a result `models.json` always stores the actual request root, so Pi can use it directly even when this extension is not loaded.
208
+ Base URL represents the API root. Both OpenAI protocols and Anthropic append `/v1` to a bare domain, preserve explicit paths, and then append the protocol endpoint. For example, Anthropic with `https://gw.example.com/xxx` uses `/xxx/messages` for chat and `/xxx/models` for discovery. Google appends `/v1beta` to its official root and preserves custom paths. Base URLs cannot contain query parameters (`?`), fragments (`#`), or embedded credentials; parameters generated by the SDK remain supported.
209
+
210
+ Standard Anthropic endpoints are converted to Pi's native SDK representation in `models.json`, so they also work without the extension. Custom version paths use private `state.json` metadata and require the extension's transport adapter. Toggling the proxy changes only the transport route, preserving the final endpoint, application headers, and payload. Proxy failures are reported.
211
+
212
+ ### Chat protocol compatibility
213
+
214
+ When the API protocol is `openai-completions` (OpenAI Chat), the provider editor shows **Protocol compatibility**. Switch with `←` / `→`, or press `Enter` for the full descriptions; the setting applies to every model in that provider.
215
+
216
+ | Mode | Persisted behavior | Use when |
217
+ | --- | --- | --- |
218
+ | Standard · Pi default | Removes the `compat.supportsDeveloperRole` override and retains Pi's default endpoint compatibility decision | A regular Chat provider |
219
+ | Compatible · system | Writes `compat.supportsDeveloperRole: false`; system prompts for reasoning models use the `system` role | A gateway does not correctly handle the `developer` role, causing system prompts or persona instructions to fail |
220
+
221
+ Use **Standard · Pi default** first. Select **Compatible · system** only when the endpoint requires the `system` role; switching back to Standard restores Pi's default decision.
208
222
 
209
223
  Model capabilities include:
210
224
 
@@ -227,24 +241,28 @@ Model capabilities include:
227
241
 
228
242
  The current built-in values were derived from real client requests with authentication fields removed:
229
243
 
230
- - Claude Code `2.1.243`
231
- - Codex TUI `0.149.1`
244
+ - Claude Code `2.1.278`
245
+ - Codex TUI `0.155.1`
232
246
 
233
247
  These headers only help API gateways that require a recognized client identity; they do not replace an API key. The public repository and npm package contain **no request-capture tooling, user captures, authentication headers, or machine-local state**. Disable identity headers or create a custom profile if a built-in profile does not fit your endpoint.
234
248
 
235
249
  Custom profiles reject authentication-related sensitive headers. Put authentication material in the provider's API-key setting instead.
236
250
 
251
+ Explicit native headers override built-in templates; selecting a custom profile gives its values final priority. Header names are merged case-insensitively. Custom `anthropic-beta` lists are preserved in full, including when Adaptive Thinking is enabled.
252
+
237
253
  ## Configuration files
238
254
 
239
255
  | Path | Purpose |
240
256
  | --- | --- |
241
257
  | `~/.pi/agent/models.json` | Native Pi provider and model definitions; the single source of truth for model configuration |
242
- | `~/.pi/agent/extensions/pi-model-manager/state.json` | Extension metadata such as header choices, custom profiles, proxy switches, and Fast mode |
258
+ | `~/.pi/agent/extensions/pi-model-manager/state.json` | Private metadata such as header choices, custom profiles, proxy switches, Fast mode, and Anthropic custom endpoint markers |
243
259
 
244
260
  The extension generates client headers, proxy routes, and dynamic registrations only for explicitly managed providers. Ownership requires both a managed ID in `state.json` and a `piModelManager.managed` marker on the Provider node in `models.json`; this prevents a deleted Provider ID from silently taking ownership of an unrelated native Provider that later reuses the same ID. Native providers without this ownership evidence remain unmanaged: saving unrelated settings does not rewrite their existing headers or unknown native fields. Built-in Pi providers cannot be edited or deleted through this extension.
245
261
 
246
262
  Plugin configuration writes are serialized with a cross-process lock, and `enabledModels` also honors Pi's `proper-lockfile` lock. An intent journal makes the `models.json` / `state.json` pair recoverable after interruption, and readers reject an in-progress half-written pair. External editors do not honor these locks, so content hashes are still checked before saving; an external change cancels the save instead of being overwritten.
247
263
 
264
+ Older endpoint configurations migrate to v5 metadata while preserving their final chat addresses. A pre-migration snapshot of both files is stored as `base-url-v5-*.json` in the extension configuration directory. These snapshots contain raw configuration and must be protected like credential files. A rollback requires restoring the matching code, `models.json`, and `state.json` together.
265
+
248
266
  ## Secrets and security
249
267
 
250
268
  Pi extensions run with the current user's permissions and have full system access. Review the source before installing any third-party extension.
@@ -268,7 +286,8 @@ Additional considerations:
268
286
 
269
287
  | Component | Requirement |
270
288
  | --- | --- |
271
- | `@earendil-works/pi-coding-agent` | `>=0.84.2` |
289
+ | `@earendil-works/pi-coding-agent` | `>=0.85.1` |
290
+ | `@earendil-works/pi-ai` | `>=0.85.1` |
272
291
  | `@earendil-works/pi-tui` | `>=0.75.0` |
273
292
  | Runtime mode | `/model-manager` requires the Pi TUI |
274
293
 
package/README.md CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  [English](./README.en.md) · 简体中文
4
4
 
5
- [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.84.2-6f42c1)](https://github.com/earendil-works/pi)
5
+ [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.85.1-6f42c1)](https://github.com/earendil-works/pi)
6
6
  [![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](./LICENSE)
7
- [![Version](https://img.shields.io/badge/version-0.3.2-2f81f7.svg)](https://github.com/Qihuanxishini/pi-model-manager)
7
+ [![Version](https://img.shields.io/badge/version-0.3.6-2f81f7.svg)](https://github.com/Qihuanxishini/pi-model-manager)
8
8
 
9
9
  一个面向 [Pi](https://github.com/earendil-works/pi) 的 TUI 模型与接入管理扩展。它以 Pi 原生 `models.json` 为模型配置的唯一权威来源,并提供接入/模型编辑、请求头身份、代理路由和协议兼容配置。
10
10
 
11
- > 当前稳定版为 `0.3.2`,要求 Pi `>=0.84.2`。
11
+ > 本扩展要求 Pi `>=0.85.1`。
12
12
 
13
13
  ## 界面预览
14
14
 
@@ -128,6 +128,7 @@ Ctrl+S 保存并启用模型;不切换当前会话模型
128
128
  - 在 `/model-manager` TUI 中新增、编辑和删除接入与模型。
129
129
  - 界面默认使用简体中文;可在主面板按 `L` 切换为 English,语言选择会持久保存。
130
130
  - 原生支持 `openai-completions`、`openai-responses`、`anthropic-messages` 和 `google-generative-ai`。
131
+ - 为 OpenAI Chat 接入提供标准 Pi 默认行为与 `system` role 兼容模式。
131
132
  - 从兼容上游拉取模型 ID,也可手动填写模型。
132
133
  - 配置上下文窗口、最大输出、视觉支持和 Thinking。
133
134
  - 支持 Anthropic Adaptive Thinking 与 Legacy Thinking。
@@ -204,9 +205,22 @@ pi install npm:pi-model-manager
204
205
  - 接入级 HTTP(S) 代理
205
206
  - 一个或多个模型
206
207
 
207
- 新建模型时,扩展会尝试从上游读取模型列表;整次发现(包括认证回退)共用一个 10 秒上限,可按 `Esc` 手动取消。失败或取消后仍可手动输入模型 ID。
208
+ 新建模型时,扩展会尝试从上游读取模型列表;整次发现共用一个 10 秒上限,可按 `Esc` 手动取消。列表与聊天使用同一 API 根地址和配置的认证信息,错误会区分认证失败、接口不存在、限流和上游异常。失败或取消后仍可手动输入模型 ID。
208
209
 
209
- Base URL 在填入时就会归一化为各协议 SDK 可直接使用的根地址:OpenAI 系补上 `/v1`,Anthropic 剔除 `/v1`,Google 在官方域名上补 `/v1beta`;你显式填的非根路径(如 `https://gw.example.com/custom`)不会被改写。切换 API 协议时地址会按新协议重新归一化。因此 `models.json` 里存的就是实际请求根地址,本扩展未加载时 Pi 也能直接使用。
210
+ Base URL 表示 API 根地址:OpenAI 两种协议和 Anthropic 只填域名时补 `/v1`,显式填写路径时保留该路径,再追加协议端点。例如 Anthropic 的 `https://gw.example.com/xxx` 请求 `/xxx/messages`,模型列表请求 `/xxx/models`。Google 在官方根地址上补 `/v1beta`,自定义路径保持原样。Base URL 不支持查询参数(`?`)、片段(`#`)或内嵌认证;SDK 正常生成的请求参数不受影响。
211
+
212
+ Anthropic 标准端点在写入 `models.json` 时转换为 Pi 原生 SDK 所需形式,因此未加载扩展时也能使用;自定义版本路径通过 `state.json` 私有标记衔接,依赖扩展的发送适配。代理开关只改变传输路线,最终端点、业务请求头和 payload 保持一致;代理失败会报错。
213
+
214
+ ### Chat 协议兼容
215
+
216
+ 当 API 协议为 `openai-completions`(OpenAI Chat)时,接入编辑器会显示「协议兼容」。用 `←` / `→` 切换,或按 `Enter` 查看完整说明;该设置作用于接入内的所有模型。
217
+
218
+ | 模式 | 保存行为 | 使用场景 |
219
+ | --- | --- | --- |
220
+ | 标准 · Pi 默认 | 移除 `compat.supportsDeveloperRole` 覆写,保留 Pi 对端点的默认兼容判断 | 常规 Chat 接入 |
221
+ | 兼容 · system | 写入 `compat.supportsDeveloperRole: false`;reasoning 模型的系统提示词使用 `system` role | 中转不能正确处理 `developer` role,导致系统提示词或人设失效 |
222
+
223
+ 优先使用「标准 · Pi 默认」。只有确认接入需要 `system` role 时才选择「兼容 · system」;切换回标准会恢复 Pi 的默认判断。
210
224
 
211
225
  ### 模型能力
212
226
 
@@ -231,24 +245,28 @@ Base URL 在填入时就会归一化为各协议 SDK 可直接使用的根地址
231
245
 
232
246
  当前内置值来自真实客户端请求并已移除认证信息:
233
247
 
234
- - Claude Code `2.1.243`
235
- - Codex TUI `0.149.1`
248
+ - Claude Code `2.1.278`
249
+ - Codex TUI `0.155.1`
236
250
 
237
251
  这些值只用于兼容需要识别客户端身份的 API 中转,不代替 API key。公开仓库和 npm 包**不包含请求捕获工具、用户抓包、认证头或本机状态**。如果内置值不适合你的服务,请关闭身份头或创建自定义请求头。
238
252
 
239
253
  自定义请求头会拒绝认证类敏感字段;认证信息应放在接入的 API key 配置中。
240
254
 
255
+ 显式原生请求头覆盖内置模板;选择自定义请求头时,自定义值拥有最终优先级。同名字段按大小写不敏感方式合并。自定义 `anthropic-beta` 清单完整保留,Adaptive Thinking 不会修改它。
256
+
241
257
  ## 配置文件
242
258
 
243
259
  | 路径 | 用途 |
244
260
  | --- | --- |
245
261
  | `~/.pi/agent/models.json` | Pi 原生接入与模型定义;模型配置的唯一权威来源 |
246
- | `~/.pi/agent/extensions/pi-model-manager/state.json` | 请求头选择、自定义请求头、代理开关和 Fast mode 等扩展私有元数据 |
262
+ | `~/.pi/agent/extensions/pi-model-manager/state.json` | 请求头选择、自定义请求头、代理开关、Fast mode 和 Anthropic 自定义端点标记等私有元数据 |
247
263
 
248
264
  扩展只会为明确受管理的 Provider 生成请求头、代理路由和动态注册配置。所有权由 `state.json` 的受管理 ID 与 `models.json` Provider 节点中的 `piModelManager.managed` 标记共同确认,防止已删除的 Provider ID 在日后被同名原生配置复用时遭到插件接管。没有这些所有权信息的原生 Provider 保持未管理,其已有 Header 和未知原生字段不会因保存其它配置而被改写;Pi 内置 Provider 不在本扩展中提供编辑或删除入口。
249
265
 
250
266
  插件自身的配置写入由跨进程锁串行化,`enabledModels` 还同时遵守 Pi 的 `proper-lockfile` 锁;`models.json` 与 `state.json` 通过事务意图文件在中断后恢复,读取方不会采用事务进行中的半完成组合。外部编辑器不受这些锁约束,因此保存前仍会校验内容签名;检测到外部修改时会取消保存而不是覆盖。
251
267
 
268
+ 旧端点配置会升级到 v5 元数据,保持原最终聊天地址,迁移前的双文件快照保存在插件配置目录的 `base-url-v5-*.json`。快照包含原始配置,应按凭据文件保护;回退时需配套恢复代码、`models.json` 和 `state.json`。
269
+
252
270
  ## 密钥与安全
253
271
 
254
272
  Pi 扩展以当前用户权限运行并拥有完整系统访问能力。安装任何第三方扩展前都应审阅源码。
@@ -272,7 +290,8 @@ ${ANTHROPIC_API_KEY}
272
290
 
273
291
  | 组件 | 要求 |
274
292
  | --- | --- |
275
- | `@earendil-works/pi-coding-agent` | `>=0.84.2` |
293
+ | `@earendil-works/pi-coding-agent` | `>=0.85.1` |
294
+ | `@earendil-works/pi-ai` | `>=0.85.1` |
276
295
  | `@earendil-works/pi-tui` | `>=0.75.0` |
277
296
  | 运行模式 | `/model-manager` 需要 Pi TUI |
278
297
 
package/atomic-write.ts CHANGED
@@ -56,13 +56,13 @@ async function renameWithRetry(sourcePath: string, targetPath: string): Promise<
56
56
 
57
57
 
58
58
 
59
- export async function atomicWriteText(targetPath: string, content: string): Promise<void> {
59
+ export async function atomicWriteText(targetPath: string, content: string, mode?: number): Promise<void> {
60
60
  await mkdir(dirname(targetPath), { recursive: true });
61
61
  const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
62
62
  let tempHasCompleteContent = false;
63
63
 
64
64
  try {
65
- await writeFile(tempPath, content, "utf8");
65
+ await writeFile(tempPath, content, { encoding: "utf8", mode });
66
66
  tempHasCompleteContent = true;
67
67
  await renameWithRetry(tempPath, targetPath);
68
68
  } catch (error) {
@@ -7,6 +7,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
7
  // 声明成最小契约,session_start 的 ExtensionContext 也能直接复用这些函数。
8
8
  type RegistryRefreshContext = Pick<ExtensionContext, "modelRegistry">;
9
9
  import { unlink } from "node:fs/promises";
10
+ import { join } from "node:path";
10
11
  import { atomicWriteText } from "./atomic-write.ts";
11
12
  import { formatUnknownError, isObjectRecord, stringifyJson } from "./common.ts";
12
13
  import { withConfigurationLock } from "./configuration-lock.ts";
@@ -24,11 +25,13 @@ import {
24
25
  buildModelsDocumentWithSynchronizedModel,
25
26
  buildModelsDocumentWithoutModel,
26
27
  buildSynchronizedModelsDocument,
28
+ migrateManagedBaseUrls,
27
29
  } from "./models-json-sync.ts";
28
30
  import { invalidateStateCache } from "./state-cache.ts";
29
31
  import {
30
32
  CONFIGURATION_TRANSACTION_PATH,
31
33
  STATE_PATH,
34
+ STATE_DIR,
32
35
  readMetadataStateSnapshot,
33
36
  serializeMetadataState,
34
37
  } from "./state-metadata-store.ts";
@@ -178,6 +181,17 @@ async function writeConfigurationTransaction(
178
181
  assertSnapshotStillCurrent(MODELS_JSON_PATH, modelsSnapshot.contentHash),
179
182
  assertSnapshotStillCurrent(STATE_PATH, metadataSnapshot.contentHash),
180
183
  ]);
184
+ if (metadataSnapshot.metadata.version < 5) {
185
+ const backupPath = join(STATE_DIR, `base-url-v5-${hashTextContent(journal.modelsJson.oldHash + journal.metadataState.oldHash).slice(0, 16)}.json`);
186
+ const backup = await readStableTextFileSnapshot(backupPath);
187
+ if (backup.source === undefined) await atomicWriteText(backupPath, stringifyJson(journal), 0o600);
188
+ else {
189
+ const saved = parseTransactionJournal(backup.source);
190
+ if (saved.modelsJson.oldHash !== journal.modelsJson.oldHash || saved.metadataState.oldHash !== journal.metadataState.oldHash) {
191
+ throw new Error(t("迁移备份内容不匹配:{path}", { path: backupPath }));
192
+ }
193
+ }
194
+ }
181
195
  await atomicWriteText(TRANSACTION_PATH, stringifyJson(journal));
182
196
 
183
197
  try {
@@ -215,8 +229,11 @@ async function persistConfigurationInsideLock(
215
229
  [],
216
230
  Object.keys(metadataSnapshot.legacyProviders),
217
231
  );
232
+ const migratedSource = metadataSnapshot.metadata.version < 5
233
+ ? migrateManagedBaseUrls(latest, sourceWithLegacyProviders)
234
+ : sourceWithLegacyProviders;
218
235
  const change = prepare(latest);
219
- const nextModels = mutateModels(sourceWithLegacyProviders, change);
236
+ const nextModels = mutateModels(migratedSource, change);
220
237
  const modelsTarget = nextModels === modelsSnapshot.document && modelsSnapshot.source !== undefined
221
238
  ? modelsSnapshot.source
222
239
  : stringifyJson(nextModels);
@@ -224,6 +241,20 @@ async function persistConfigurationInsideLock(
224
241
  return change.document;
225
242
  }
226
243
 
244
+ /** 在 catalog 注册前完成地址语义升级,避免 models.json 原生覆盖与私有元数据版本不一致。 */
245
+ export async function migrateManagedEndpointConfiguration(): Promise<boolean> {
246
+ return withConfigurationLock(async () => {
247
+ await recoverPendingConfigurationTransactionInsideLock();
248
+ if ((await readMetadataStateSnapshot()).metadata.version >= 5) return false;
249
+ await persistConfigurationInsideLock(
250
+ (document) => ({ document, changedProviderIds: [], removedProviderIds: [] }),
251
+ (source) => source,
252
+ );
253
+ invalidateStateCache();
254
+ return true;
255
+ });
256
+ }
257
+
227
258
  async function refreshRegistryAfterPersistence(
228
259
  ctx: RegistryRefreshContext,
229
260
  persist: () => Promise<StateDocument>,
package/i18n.ts CHANGED
@@ -5,6 +5,19 @@ export type UiLanguage = (typeof SUPPORTED_UI_LANGUAGES)[number];
5
5
  export const DEFAULT_UI_LANGUAGE: UiLanguage = "zh-CN";
6
6
 
7
7
  const ENGLISH_MESSAGES = {
8
+ "Base URL 必须使用 http 或 https": "Base URL must use http or https",
9
+ "Base URL 不支持查询参数(?)或片段(#);请填写 API 根地址": "Base URL cannot contain query parameters (?) or fragments (#); enter the API root URL",
10
+ "Base URL 不支持内嵌认证;请使用 API key 或请求头配置": "Base URL cannot contain credentials; use the API key or header configuration",
11
+ "请求模型不属于当前接入配置:{modelId}": "Request model is not part of the current provider configuration: {modelId}",
12
+ "该协议尚不支持接入级代理:{api}": "Provider-level proxy is not supported for this API: {api}",
13
+ "Anthropic 请求路径与当前适配契约不符": "Anthropic request path does not match the transport contract",
14
+ "无法构建接入:{providerId}": "Failed to construct provider: {providerId}",
15
+ "请求配置读取失败,本次使用原始 payload": "Failed to read request configuration; using the original payload",
16
+ "认证失败,请检查 API key 和认证头": "Authentication failed; check the API key and authentication headers",
17
+ "模型列表接口不存在,可继续手动添加模型": "The model list endpoint is unavailable; models can still be added manually",
18
+ "模型列表请求被限流,请稍后重试": "The model list request was rate-limited; try again later",
19
+ "模型列表上游服务异常": "The upstream model list service failed",
20
+ "模型列表请求失败": "The model list request failed",
8
21
  "语言 / Language": "Language",
9
22
  "简体中文": "Simplified Chinese",
10
23
  "English": "English",
@@ -83,6 +96,15 @@ const ENGLISH_MESSAGES = {
83
96
  "兼容 — 强制 system role,适合忽略 developer 的中转": "Compatible — force the system role for relays that ignore developer",
84
97
  "标准模式:保持 Pi 默认兼容判断。": "Standard mode: keep Pi's default compatibility detection.",
85
98
  "兼容模式:系统提示词强制使用 system role,适合忽略 developer 的中转。": "Compatibility mode: the system prompt always uses the system role for relays that ignore developer.",
99
+ "流结束兼容": "Stream completion",
100
+ "兼容 · 终态即结束": "Compatible · end on terminal event",
101
+ "标准 · 等待连接关闭": "Standard · wait for connection close",
102
+ "选择流结束兼容": "Select stream completion mode",
103
+ "标准 — 等待上游正常关闭连接": "Standard — wait for upstream to close the connection",
104
+ "兼容 — 收到正式终态事件后主动结束": "Compatible — finish after receiving a formal terminal event",
105
+ "兼容模式:正式终态事件已转交后主动结束,不等待上游关闭连接。": "Compatibility mode: finish after forwarding the formal terminal event without waiting for upstream to close.",
106
+ "标准模式:等待上游正常结束流。若回复完成后长期卡住,可启用兼容模式。": "Standard mode: wait for upstream to finish the stream normally. Enable compatibility mode if completed replies remain stuck.",
107
+ "未知 Responses 流结束模式:{value}": "Unknown Responses stream completion mode: {value}",
86
108
  "接入 ID 必填,且不能与已有或 pi 内置接入重复": "Provider ID is required and must not duplicate an existing or built-in Pi provider",
87
109
  "Ctrl+S 保存并同步 models.json;不切换当前会话模型": "Ctrl+S saves and syncs models.json without switching the current session model",
88
110
  "选择 API 协议": "Select API protocol",
@@ -221,7 +243,9 @@ const ENGLISH_MESSAGES = {
221
243
  "读取/注册模型配置失败:{error}": "Failed to read/register the model configuration: {error}",
222
244
  "激活模型接入失败:{warning}": "Failed to activate a model provider: {warning}",
223
245
  "恢复、读取或激活模型配置失败:{error}": "Failed to recover, read, or activate the model configuration: {error}",
224
- "[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",
246
+ "[pi-model-manager] 已规范化 {count} 个接入的 API 根地址({providerIds})": "[pi-model-manager] Normalized API root URLs for {count} provider(s) ({providerIds})",
247
+ "[pi-model-manager] 已升级端点配置;迁移前快照保存在插件配置目录的 base-url-v5-*.json": "[pi-model-manager] Endpoint configuration upgraded; pre-migration snapshots are saved as base-url-v5-*.json in the plugin configuration directory",
248
+ "迁移备份内容不匹配:{path}": "Migration backup content does not match: {path}",
225
249
 
226
250
  "{label} JSON 必须是对象": "{label} JSON must be an object",
227
251
  "{label} {key} 的值必须是字符串": "The value of {label} {key} must be a string",
package/index.ts CHANGED
@@ -12,7 +12,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
12
  import { formatUnknownError } from "./common.ts";
13
13
  import { DEFAULT_UI_LANGUAGE, joinLocalizedList, setUiLanguage, t } from "./i18n.ts";
14
14
  import { readUiLanguage } from "./ui-language-settings.ts";
15
- import { persistManagedConfiguration, recoverPendingConfigurationTransaction } from "./configuration-persistence.ts";
15
+ import { persistManagedConfiguration, recoverPendingConfigurationTransaction, migrateManagedEndpointConfiguration } from "./configuration-persistence.ts";
16
16
  import { resetClaudeCodeMetadataSession } from "./claude-code-compat.ts";
17
17
  import { findProvidersNeedingBaseUrlNormalization, normalizeProviderBaseUrlsInDocument } from "./state-document.ts";
18
18
  import { closeLocalProxyServer } from "./local-proxy-service.ts";
@@ -35,8 +35,10 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
35
35
  }
36
36
 
37
37
  let configurationBlocked = false;
38
+ let migratedEndpointConfiguration = false;
38
39
  try {
39
40
  await recoverPendingConfigurationTransaction();
41
+ migratedEndpointConfiguration = await migrateManagedEndpointConfiguration();
40
42
  } catch (error) {
41
43
  configurationBlocked = true;
42
44
  summary.startupErrors.push(t("恢复未完成配置事务失败:{error}(为避免读取半完成配置,本次暂不注册模型)", { error: formatUnknownError(error) }));
@@ -65,6 +67,7 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
65
67
  try {
66
68
  if (configurationBlocked) {
67
69
  await recoverPendingConfigurationTransaction();
70
+ migratedEndpointConfiguration = await migrateManagedEndpointConfiguration() || migratedEndpointConfiguration;
68
71
  configurationBlocked = false;
69
72
  }
70
73
  const currentState = await readState();
@@ -96,9 +99,13 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
96
99
  for (const error of transportErrors) {
97
100
  ctx.ui.notify(`[pi-model-manager] ${error}`, "error");
98
101
  }
102
+ if (migratedEndpointConfiguration) {
103
+ ctx.ui.notify(t("[pi-model-manager] 已升级端点配置;迁移前快照保存在插件配置目录的 base-url-v5-*.json"), "info");
104
+ migratedEndpointConfiguration = false;
105
+ }
99
106
  if (migratedBaseUrlProviderIds.length > 0) {
100
107
  ctx.ui.notify(
101
- t("[pi-model-manager] 已补全 {count} 个接入的请求地址({providerIds}),现在 models.json 存的就是实际请求根地址", {
108
+ t("[pi-model-manager] 已规范化 {count} 个接入的 API 根地址({providerIds})", {
102
109
  count: migratedBaseUrlProviderIds.length,
103
110
  providerIds: joinLocalizedList(migratedBaseUrlProviderIds),
104
111
  }),
@@ -178,7 +178,8 @@ function forwardPlainHttp(target: URL, proxy: URL, request: IncomingMessage, res
178
178
  bindClientAbort(request, response, upstreamRequest);
179
179
  upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
180
180
  // [喵喵喵]: 请求体直接流向上游,避免图像等大 payload 在本地代理中形成完整内存副本 (2026-07-17)
181
- request.pipe(upstreamRequest);
181
+ // [喵喵喵]: 等代理完成请求头重建后再流式读取 body,避免 chunked 请求在异步建连期间重复写入 HTTP 头。
182
+ upstreamRequest.once("socket", () => request.pipe(upstreamRequest));
182
183
  }
183
184
 
184
185
  function forwardHttps(target: URL, proxy: URL, request: IncomingMessage, response: ServerResponse): void {
@@ -196,7 +197,7 @@ function forwardHttps(target: URL, proxy: URL, request: IncomingMessage, respons
196
197
  upstreamRequest.once("close", () => agent.destroy());
197
198
  bindClientAbort(request, response, upstreamRequest);
198
199
  upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
199
- request.pipe(upstreamRequest);
200
+ upstreamRequest.once("socket", () => request.pipe(upstreamRequest));
200
201
  }
201
202
 
202
203
  function forwardRequest(route: ProviderProxyRoute, request: IncomingMessage, response: ServerResponse, routePath: string): void {
@@ -30,6 +30,7 @@ import {
30
30
  type ModelsJsonProviderEntry,
31
31
  } from "./models-json-manager.ts";
32
32
  import { buildModelRequestHeaders } from "./provider-registrar.ts";
33
+ import { toNativeBaseUrl } from "./runtime-base-url.ts";
33
34
  import type {
34
35
  BuiltInClientHeaderProfileId,
35
36
  StateDocument,
@@ -85,8 +86,11 @@ function buildModelsJsonModelEntry(
85
86
  else delete next.name;
86
87
  if (model.api) next.api = model.api;
87
88
  else delete next.api;
88
- if (model.baseUrl) next.baseUrl = model.baseUrl;
89
- else delete next.baseUrl;
89
+ if (model.baseUrl || (provider.managed && model.api && model.api !== provider.api)) {
90
+ next.baseUrl = provider.managed
91
+ ? toNativeBaseUrl(model.api ?? provider.api, model.baseUrl ?? provider.baseUrl).baseUrl
92
+ : model.baseUrl;
93
+ } else delete next.baseUrl;
90
94
  next.reasoning = model.reasoning;
91
95
  if (model.thinkingLevelMap) next.thinkingLevelMap = { ...model.thinkingLevelMap };
92
96
  else delete next.thinkingLevelMap;
@@ -111,7 +115,7 @@ function buildModelsJsonProviderEntry(
111
115
  const next: ModelsJsonProviderEntry = existing ? { ...existing } : {};
112
116
  if (provider.name) next.name = provider.name;
113
117
  else delete next.name;
114
- next.baseUrl = provider.baseUrl;
118
+ next.baseUrl = provider.managed ? toNativeBaseUrl(provider.api, provider.baseUrl).baseUrl : provider.baseUrl;
115
119
  next.api = provider.api;
116
120
  if (provider.apiKey) next.apiKey = provider.apiKey;
117
121
  else delete next.apiKey;
@@ -162,6 +166,29 @@ export function buildSynchronizedModelsDocument(
162
166
  return nextDocument;
163
167
  }
164
168
 
169
+ /** 版本升级只转换地址字段,保留源文件中的模型、兼容参数及其他扩展字段。 */
170
+ export function migrateManagedBaseUrls(document: StateDocument, source: ModelsJsonDocument): ModelsJsonDocument {
171
+ let result = source;
172
+ for (const [providerId, provider] of Object.entries(document.providers)) {
173
+ const entry = source.providers[providerId];
174
+ if (!provider.managed || !entry) continue;
175
+ if (provider.api !== "anthropic-messages" && !provider.models.some((model) => model.api === "anthropic-messages")) continue;
176
+ const models = new Map(provider.models.map((model) => [model.id, model]));
177
+ const next = {
178
+ ...entry,
179
+ baseUrl: toNativeBaseUrl(provider.api, provider.baseUrl).baseUrl,
180
+ models: entry.models?.map((raw) => {
181
+ const model = models.get(raw.id);
182
+ if (!model) return raw;
183
+ if (!raw.baseUrl && !model.baseUrl && (!model.api || model.api === provider.api)) return raw;
184
+ return { ...raw, baseUrl: toNativeBaseUrl(model.api ?? provider.api, model.baseUrl ?? provider.baseUrl).baseUrl };
185
+ }),
186
+ };
187
+ result = setProviderInDoc(result, providerId, next);
188
+ }
189
+ return result;
190
+ }
191
+
165
192
  export function buildModelsDocumentWithSynchronizedModel(
166
193
  document: StateDocument,
167
194
  sourceDocument: ModelsJsonDocument,
@@ -1,7 +1,6 @@
1
1
  // openai-responses-payload.ts
2
2
  //
3
- // 将 pi 内置 openai-responses 的 system/developer input 形态调整为标准
4
- // OpenAI Responses wire format:顶层 instructions + 纯对话 input。
3
+ // 为受管理的 Responses 接入提取首条系统规则,保持顶层 instructions 的接入约定。
5
4
 
6
5
  import { isObjectRecord } from "./common.ts";
7
6
  import type { StateDocument } from "./types.ts";
@@ -41,13 +40,10 @@ function extractTextInstruction(content: unknown): string | undefined {
41
40
  return instruction.trim() ? instruction : undefined;
42
41
  }
43
42
 
44
- function hasNonEmptyInstructions(payload: PayloadRecord): boolean {
45
- return typeof payload.instructions === "string" && payload.instructions.trim().length > 0;
46
- }
47
43
 
48
44
  function normalizeOpenAIResponsesInstructionsPayload(payload: unknown): PayloadRecord | undefined {
49
45
  if (!isPayloadRecord(payload)) return undefined;
50
- if (hasNonEmptyInstructions(payload)) return undefined;
46
+ if (payload.instructions !== undefined) return undefined;
51
47
 
52
48
  const input = payload.input;
53
49
  if (!Array.isArray(input) || input.length === 0) return undefined;
@@ -73,8 +69,10 @@ export function normalizeManagedOpenAIResponsesPayload(
73
69
  if (!model || model.api !== "openai-responses") return undefined;
74
70
  if (!isPayloadRecord(payload) || payload.model !== model.id) return undefined;
75
71
 
76
- const storedModel = state.providers[model.provider]?.models.find((candidate) => candidate.id === model.id);
77
- if (!storedModel) return undefined;
72
+ const provider = state.providers[model.provider];
73
+ if (!provider?.managed) return undefined;
74
+ const storedModel = provider.models.find((candidate) => candidate.id === model.id);
75
+ if (!storedModel || (storedModel.api ?? provider.api) !== model.api) return undefined;
78
76
 
79
77
  return normalizeOpenAIResponsesInstructionsPayload(payload);
80
78
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-model-manager",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
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",
@@ -24,6 +24,7 @@
24
24
  "models-json-manager.ts",
25
25
  "models-json-sync.ts",
26
26
  "provider-registrar.ts",
27
+ "provider-transport.ts",
27
28
  "local-proxy-service.ts",
28
29
  "request-pipeline.ts",
29
30
  "model-mutations.ts",
@@ -69,7 +70,8 @@
69
70
  ]
70
71
  },
71
72
  "peerDependencies": {
72
- "@earendil-works/pi-coding-agent": ">=0.84.2",
73
+ "@earendil-works/pi-coding-agent": ">=0.85.1",
74
+ "@earendil-works/pi-ai": ">=0.85.1",
73
75
  "@earendil-works/pi-tui": ">=0.75.0"
74
76
  },
75
77
  "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,fallback-credit-2026-06-01",
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,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,effort-2025-11-24",
5
5
  "anthropic-dangerous-direct-browser-access": "true",
6
6
  "anthropic-version": "2023-06-01",
7
- "user-agent": "claude-cli/2.1.243 (external, sdk-cli)",
7
+ "user-agent": "claude-cli/2.1.278 (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.149.1 (Windows 10.0.26200; x86_64) unknown (codex-tui; 0.149.1)",
21
+ "user-agent": "codex-tui/0.155.1 (Windows 10.0.26200; x86_64) unknown (codex-tui; 0.155.1)",
22
22
  "x-codex-beta-features": "remote_compaction_v2",
23
23
  };
@@ -41,22 +41,15 @@ function cloneHeadersForCompat(
41
41
  return cloned;
42
42
  }
43
43
 
44
- function deleteHeaderCaseInsensitive(headers: Record<string, string>, name: string): void {
45
- const normalized = name.toLowerCase();
46
- for (const existingName of Object.keys(headers)) {
47
- if (existingName.toLowerCase() === normalized) delete headers[existingName];
48
- }
49
- }
50
44
 
51
- /** 模型原生 headers 先保留,插件 profile 对同名字段拥有最终覆盖权。 */
45
+ /** 按大小写不敏感的字段名合并请求头,后者覆盖前者。 */
52
46
  export function mergeModelRequestHeaders(
53
47
  nativeHeaders: Record<string, string> | undefined,
54
48
  profileHeaders: Record<string, string> | undefined,
55
49
  ): Record<string, string> | undefined {
56
- const merged = cloneStringRecord(nativeHeaders);
57
- for (const [name, value] of Object.entries(profileHeaders ?? {})) {
58
- deleteHeaderCaseInsensitive(merged, name);
59
- merged[name] = value;
50
+ const merged: Record<string, string> = {};
51
+ for (const headers of [nativeHeaders, profileHeaders]) {
52
+ for (const [name, value] of Object.entries(headers ?? {})) merged[name.toLowerCase()] = value;
60
53
  }
61
54
  return hasStringRecordEntries(merged) ? merged : undefined;
62
55
  }
@@ -67,7 +60,11 @@ export function stripManagedClientHeaders(
67
60
  profileHeaders: Record<string, string> | undefined,
68
61
  ): Record<string, string> | undefined {
69
62
  const nativeHeaders = cloneStringRecord(storedHeaders);
70
- for (const name of Object.keys(profileHeaders ?? {})) deleteHeaderCaseInsensitive(nativeHeaders, name);
63
+ for (const [name, value] of Object.entries(profileHeaders ?? {})) {
64
+ for (const [storedName, storedValue] of Object.entries(nativeHeaders)) {
65
+ if (storedName.toLowerCase() === name.toLowerCase() && storedValue === value) delete nativeHeaders[storedName];
66
+ }
67
+ }
71
68
  return hasStringRecordEntries(nativeHeaders) ? nativeHeaders : undefined;
72
69
  }
73
70
 
@@ -102,7 +99,7 @@ export function getClientHeadersForProfile(
102
99
  : CODEX_CLI_CLIENT_HEADERS;
103
100
  return cloneStringRecord(headers);
104
101
  }
105
- return hasStringRecordEntries(customHeaders) ? cloneHeadersForCompat(customHeaders, api, compat) : undefined;
102
+ return hasStringRecordEntries(customHeaders) ? cloneStringRecord(customHeaders) : undefined;
106
103
  }
107
104
  export function getClientHeaderProfileDisplay(profile: ClientHeaderProfileId, api: ApiKind): string {
108
105
  const resolved = resolveClientHeaderProfile(profile, api);
@@ -49,7 +49,7 @@ const PROVIDER_PRESETS: ProviderPreset[] = [
49
49
  label: "Anthropic Messages — Claude thinking",
50
50
  shortLabel: "Anthropic Messages",
51
51
  defaultProviderName: "anthropic",
52
- baseUrl: "https://api.anthropic.com",
52
+ baseUrl: "https://api.anthropic.com/v1",
53
53
  apiKey: "$ANTHROPIC_API_KEY",
54
54
  authHeader: false,
55
55
  contextWindow: 200000,