pi-model-manager 0.4.5 → 0.4.7

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.85.1-6f42c1)](https://github.com/earendil-works/pi)
5
+ [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.87.0-6f42c1)](https://github.com/earendil-works/pi)
6
6
  [![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](./LICENSE)
7
7
  [![npm](https://img.shields.io/npm/v/pi-model-manager?color=2f81f7)](https://www.npmjs.com/package/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
- > This extension requires Pi `>=0.85.1`.
11
+ > This extension requires Pi `>=0.87.0` and Node.js `22.x >=22.21.0` or `>=24.5.0`. Configuration locking on Windows requires PowerShell 7 (`pwsh`). Provider proxies are not supported under Bun.
12
12
 
13
13
  ## Interface preview
14
14
 
@@ -209,6 +209,8 @@ Base URL represents the API root. Both OpenAI protocols and Anthropic append `/v
209
209
 
210
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
211
 
212
+ Proxy egress uses native Node agents. Requests with the same provider, proxy URL, and upstream protocol can reuse connections. Changing the proxy URL sends new requests through a new pool; an old pool is reclaimed after 30 seconds with no active requests. Removing a temporary route does not interrupt SSE. Session shutdown aborts active forwarding and releases the pools. Whether switching nodes in a proxy client closes existing connections is controlled by that client; the extension does not monitor node selection.
213
+
212
214
  ### Chat protocol compatibility
213
215
 
214
216
  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.
@@ -231,7 +233,7 @@ Model capabilities include:
231
233
 
232
234
  ### Responses service tiers
233
235
 
234
- For `openai-responses`, the model editor shows **Fast mode**. Cycle through the three tiers with `←` / `→`, or press `Enter` for the full descriptions. The model list also shows the selected tier. The Chinese UI uses 标准 / Fast / Ultrafast.
236
+ For managed providers using `openai-responses`, the model editor shows **Fast mode**. Unmanaged providers hide this option and show a prompt to save the provider configuration first. Cycle through the three tiers with `←` / `→`, or press `Enter` for the full descriptions. The model list also shows the selected tier. The Chinese UI uses 标准 / Fast / Ultrafast.
235
237
 
236
238
  | Tier | Request behavior |
237
239
  | --- | --- |
@@ -250,13 +252,10 @@ Fast and Ultrafast require support from the upstream service, account, and model
250
252
  | Recommended | Claude Code for Anthropic Messages, Codex for OpenAI Completions/Responses, and no identity headers for other protocols |
251
253
  | Disabled | Adds no extension-managed client identity headers |
252
254
  | Claude Code | Uses the built-in Claude Code compatibility headers and adds required Anthropic request metadata |
253
- | Codex | Uses the built-in Codex TUI compatibility headers |
255
+ | Codex | Uses the built-in Codex Rust CLI compatibility headers |
254
256
  | Custom | Uses a reusable JSON header set created in the header-profile panel |
255
257
 
256
- The current built-in values were derived from real client requests with authentication fields removed:
257
-
258
- - Claude Code `2.1.312`
259
- - Codex TUI `0.165.0`
258
+ Built-in profiles live in `presets/builtin-client-headers.ts` and contain no authentication material. Machine-local captures take precedence when present. Codex uses the `codex_cli_rs` identity, with fields based on [codex-proxy-rs](https://github.com/zyycn/codex-proxy-rs).
260
259
 
261
260
  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.
262
261
 
@@ -264,6 +263,8 @@ Custom profiles reject authentication-related sensitive headers. Put authenticat
264
263
 
265
264
  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.
266
265
 
266
+ Generated-header snapshots follow the models actually rewritten; saving another model does not update an untouched model's snapshot. When no source record exists, only fields matching the current profile are recorded. Older values of uncertain origin remain native overrides and are not automatically removed by historical value or header name. **Disabled** therefore does not remove those overrides; inspect them before editing `models.json` manually.
267
+
267
268
  ## Configuration files
268
269
 
269
270
  | Path | Purpose |
@@ -275,6 +276,8 @@ The extension generates client headers, proxy routes, and dynamic registrations
275
276
 
276
277
  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.
277
278
 
279
+ The configuration lock records both PID and system process start time to detect PID reuse; elapsed lock age never evicts an active owner. A failed identity query does not reclaim a potentially active lock, and writes cannot acquire a lock without verifying their own process identity. Queries use `pwsh` on Windows, `/proc` on Linux, and `/bin/ps` on macOS. The current process identity is cached within that process.
280
+
278
281
  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.
279
282
 
280
283
  ## Secrets and security
@@ -300,11 +303,13 @@ Additional considerations:
300
303
 
301
304
  | Component | Requirement |
302
305
  | --- | --- |
303
- | `@earendil-works/pi-coding-agent` | `>=0.85.1` |
306
+ | `@earendil-works/pi-coding-agent` | `>=0.87.0` |
304
307
  | `@earendil-works/pi-ai` | `>=0.85.1` |
305
308
  | `@earendil-works/pi-tui` | `>=0.75.0` |
306
309
  | Runtime mode | `/model-manager` requires the Pi TUI |
307
310
 
311
+ Pi `0.87.0` is the API floor for `agent_before_settle`, not a claim of compatibility verified across every release. Current real-host checks target Pi `1.5.2`; earlier releases have not been individually verified.
312
+
308
313
  The TUI copy defaults to Simplified Chinese; press `L` on the dashboard to switch to English.
309
314
 
310
315
  ## Local development
@@ -318,7 +323,7 @@ pi -e .
318
323
 
319
324
  Pi loads the TypeScript entry point directly; no separate build step is required. Do not commit `state.json`, `bootstrap-meta.json`, `node_modules`, or request-capture data.
320
325
 
321
- Tests have separate stub and real-host entry points. The current real-host verification baseline is Pi `1.4.0`:
326
+ Tests have separate stub and real-host entry points. The current real-host verification baseline is Pi `1.5.2`:
322
327
 
323
328
  ```bash
324
329
  npm test
@@ -327,7 +332,7 @@ PI_TEST_RUNTIME_ROOT="/path/to/node_modules/@earendil-works/pi-coding-agent" npm
327
332
 
328
333
  `npm test` uses test stubs and skips real-host cases. `test:runtime` runs only `tests/*-wire.test.ts`, covering the complete built-in provider guard and protocol transport. Set `PI_TEST_RUNTIME_ROOT` to the installed Pi package directory; use a `C:/...` path in Windows Git Bash. These tests use local responses and fake credentials without calling external model services.
329
334
 
330
- Host-provided packages use `"*"` in `peerDependencies`; supported versions are listed in the compatibility table above. Runtime modules are supplied by Pi.
335
+ Host-provided packages declare minimum requirements in `peerDependencies`, matching the compatibility table above. Runtime modules are supplied by Pi.
331
336
 
332
337
  Inspect the public package contents with:
333
338
 
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.85.1-6f42c1)](https://github.com/earendil-works/pi)
5
+ [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.87.0-6f42c1)](https://github.com/earendil-works/pi)
6
6
  [![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](./LICENSE)
7
7
  [![npm](https://img.shields.io/npm/v/pi-model-manager?color=2f81f7)](https://www.npmjs.com/package/pi-model-manager)
8
8
 
9
9
  一个面向 [Pi](https://github.com/earendil-works/pi) 的 TUI 模型与接入管理扩展。它以 Pi 原生 `models.json` 为模型配置的唯一权威来源,并提供接入/模型编辑、请求头身份、代理路由和协议兼容配置。
10
10
 
11
- > 本扩展要求 Pi `>=0.85.1`。
11
+ > 本扩展要求 Pi `>=0.87.0`,Node.js `22.x >=22.21.0` 或 `>=24.5.0`。Windows 配置锁需要 PowerShell 7(`pwsh`)。接入代理不支持 Bun。
12
12
 
13
13
  ## 界面预览
14
14
 
@@ -211,6 +211,8 @@ Base URL 表示 API 根地址:OpenAI 两种协议和 Anthropic 只填域名时
211
211
 
212
212
  Anthropic 标准端点在写入 `models.json` 时转换为 Pi 原生 SDK 所需形式,因此未加载扩展时也能使用;自定义版本路径通过 `state.json` 私有标记衔接,依赖扩展的发送适配。代理开关只改变传输路线,最终端点、业务请求头和 payload 保持一致;代理失败会报错。
213
213
 
214
+ 代理出站使用 Node 原生 Agent,同一接入、代理地址和上游协议下的请求可复用连接。修改代理地址后新请求使用新池;旧池无在途请求并空闲 30 秒后回收。临时路由清理不会中断 SSE;会话关闭会中止在途转发并释放连接池。切换代理软件内的节点是否中断旧连接由该软件控制,插件不监听节点选择。
215
+
214
216
  ### Chat 协议兼容
215
217
 
216
218
  当 API 协议为 `openai-completions`(OpenAI Chat)时,接入编辑器会显示「协议兼容」。用 `←` / `→` 切换,或按 `Enter` 查看完整说明;该设置作用于接入内的所有模型。
@@ -235,7 +237,7 @@ Anthropic 标准端点在写入 `models.json` 时转换为 Pi 原生 SDK 所需
235
237
 
236
238
  #### Responses 速度档位
237
239
 
238
- 当 API 协议为 `openai-responses` 时,模型编辑器会显示 **Fast mode**。用 `←` / `→` 循环切换三档,或按 `Enter` 查看完整说明;模型列表也会显示所选档位。英文界面对应 Standard / Fast / Ultrafast。
240
+ 当接入已由插件接管且 API 协议为 `openai-responses` 时,模型编辑器会显示 **Fast mode**。未接管时隐藏该项并提示先保存接入配置。用 `←` / `→` 循环切换三档,或按 `Enter` 查看完整说明;模型列表也会显示所选档位。英文界面对应 Standard / Fast / Ultrafast。
239
241
 
240
242
  | 档位 | 请求行为 |
241
243
  | --- | --- |
@@ -254,13 +256,10 @@ Fast 和 Ultrafast 需要上游、账号及模型支持,可能产生额外费
254
256
  | 自动推荐 | Anthropic Messages 使用 Claude Code;OpenAI Completions/Responses 使用 Codex;其他协议不附加身份头 |
255
257
  | 不添加 | 不添加扩展管理的客户端身份请求头 |
256
258
  | Claude Code | 使用内置 Claude Code 兼容请求头,并为 Anthropic 请求补充必要的兼容 metadata |
257
- | Codex | 使用内置 Codex TUI 兼容请求头 |
259
+ | Codex | 使用内置 Codex Rust CLI 兼容请求头 |
258
260
  | 自定义 | 使用在请求头面板中创建的可复用 JSON 请求头集合 |
259
261
 
260
- 当前内置值来自真实客户端请求并已移除认证信息:
261
-
262
- - Claude Code `2.1.312`
263
- - Codex TUI `0.165.0`
262
+ 内置画像位于 `presets/builtin-client-headers.ts`,不包含认证信息;本机抓包缓存存在时优先使用缓存。Codex 使用 `codex_cli_rs` 画像,字段以 [codex-proxy-rs](https://github.com/zyycn/codex-proxy-rs) 为参考。
264
263
 
265
264
  这些值只用于兼容需要识别客户端身份的 API 中转,不代替 API key。公开仓库和 npm 包**不包含请求捕获工具、用户抓包、认证头或本机状态**。如果内置值不适合你的服务,请关闭身份头或创建自定义请求头。
266
265
 
@@ -268,6 +267,8 @@ Fast 和 Ultrafast 需要上游、账号及模型支持,可能产生额外费
268
267
 
269
268
  显式原生请求头覆盖内置模板;选择自定义请求头时,自定义值拥有最终优先级。同名字段按大小写不敏感方式合并。自定义 `anthropic-beta` 清单完整保留,Adaptive Thinking 不会修改它。
270
269
 
270
+ 生成头来源快照与实际写入的模型同步;只保存其他模型不会更新未改写模型的快照。缺少来源记录时,只记录与当前画像同值的字段,无法确认来源的旧值作为原生覆盖保留,不按历史值或头名自动清理。因此「不添加」不会删除这类旧覆盖,如需移除须核对后手动编辑 `models.json`。
271
+
271
272
  ## 配置文件
272
273
 
273
274
  | 路径 | 用途 |
@@ -279,6 +280,8 @@ Fast 和 Ultrafast 需要上游、账号及模型支持,可能产生额外费
279
280
 
280
281
  插件自身的配置写入由跨进程锁串行化,`enabledModels` 还同时遵守 Pi 的 `proper-lockfile` 锁;`models.json` 与 `state.json` 通过事务意图文件在中断后恢复,读取方不会采用事务进行中的半完成组合。外部编辑器不受这些锁约束,因此保存前仍会校验内容签名;检测到外部修改时会取消保存而不是覆盖。
281
282
 
283
+ 配置锁记录 PID 和系统进程创建时间,以识别 PID 复用;不会按持锁时长强行回收。查询失败时不抢占可能活跃的锁,自身身份无法确认时拒绝持锁写入。Windows 使用 `pwsh`,Linux 使用 `/proc`,macOS 使用 `/bin/ps`;当前进程的身份在进程内缓存。
284
+
282
285
  旧端点配置会升级到 v5 元数据,保持原最终聊天地址,迁移前的双文件快照保存在插件配置目录的 `base-url-v5-*.json`。快照包含原始配置,应按凭据文件保护;回退时需配套恢复代码、`models.json` 和 `state.json`。
283
286
 
284
287
  ## 密钥与安全
@@ -304,11 +307,13 @@ ${ANTHROPIC_API_KEY}
304
307
 
305
308
  | 组件 | 要求 |
306
309
  | --- | --- |
307
- | `@earendil-works/pi-coding-agent` | `>=0.85.1` |
310
+ | `@earendil-works/pi-coding-agent` | `>=0.87.0` |
308
311
  | `@earendil-works/pi-ai` | `>=0.85.1` |
309
312
  | `@earendil-works/pi-tui` | `>=0.75.0` |
310
313
  | 运行模式 | `/model-manager` 需要 Pi TUI |
311
314
 
315
+ Pi `0.87.0` 是 `agent_before_settle` 的 API 下限,不代表已逐版本验证兼容性;当前真实宿主检查基线为 Pi `1.5.2`,更早版本未逐一验证。
316
+
312
317
  默认 TUI 文案为简体中文;可在主面板按 `L` 切换为 English。
313
318
 
314
319
  ## 本地开发
@@ -322,7 +327,7 @@ pi -e .
322
327
 
323
328
  扩展由 Pi 直接加载 TypeScript 入口,不需要单独构建步骤。开发时请勿提交 `state.json`、`bootstrap-meta.json`、`node_modules` 或任何请求捕获数据。
324
329
 
325
- 测试分为替身测试和真实宿主测试,当前真实宿主验证基线为 Pi `1.4.0`:
330
+ 测试分为替身测试和真实宿主测试,当前真实宿主验证基线为 Pi `1.5.2`:
326
331
 
327
332
  ```bash
328
333
  npm test
@@ -331,7 +336,7 @@ PI_TEST_RUNTIME_ROOT="/path/to/node_modules/@earendil-works/pi-coding-agent" npm
331
336
 
332
337
  `npm test` 使用测试替身,并跳过真实宿主用例;`test:runtime` 只运行 `tests/*-wire.test.ts`,包括完整内置接入目录保护与协议转发检查。`PI_TEST_RUNTIME_ROOT` 指向已安装的 Pi 包目录,Windows Git Bash 下使用 `C:/...` 形式。这些测试使用本地响应与虚拟凭据,不调用外部模型服务。
333
338
 
334
- 宿主提供的包在 `peerDependencies` 中声明为 `"*"`,实际支持版本见上方兼容性表;运行时仍复用 Pi 提供的模块。
339
+ 宿主提供的包在 `peerDependencies` 中声明最低要求,与上方兼容性表一致;运行时仍复用 Pi 提供的模块。
335
340
 
336
341
  验证公开包内容:
337
342
 
package/codex-compat.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  // Codex 客户端画像与请求级协议头;不持有跨模型共享的可变会话状态。
2
2
 
3
3
  import { isObjectRecord } from "./common.ts";
4
- import { codexIdentityFromUserAgent } from "./presets/codex-client-headers.ts";
5
4
  import type { ApiKind } from "./types.ts";
6
5
 
7
- function setDefaultProtocolHeader(headers: Headers, name: string, value: string | undefined): void {
8
- if (!value || headers.has(name)) return;
6
+ function setDefaultProtocolHeader(headers: Headers, name: string, value: string | undefined, explicitHeaderNames: ReadonlySet<string>): void {
7
+ if (!value || headers.has(name) || explicitHeaderNames.has(name)) return;
9
8
  try {
10
9
  headers.set(name, value);
11
10
  } catch {
@@ -13,7 +12,7 @@ function setDefaultProtocolHeader(headers: Headers, name: string, value: string
13
12
  }
14
13
  }
15
14
 
16
- /** 在 SDK 完成构造后收口 Codex 指纹;仅修改本次请求,不更改缓存与会话亲和契约。 */
15
+ /** 移除 SDK 默认指纹并补齐请求级协议头,保留配置与头钩子的显式结果。 */
17
16
  export async function applyCodexRequestHeaders(
18
17
  request: Request,
19
18
  api: ApiKind,
@@ -23,21 +22,18 @@ export async function applyCodexRequestHeaders(
23
22
  for (const name of [...request.headers.keys()]) {
24
23
  if (name.startsWith("x-stainless-") && !explicitHeaderNames.has(name)) request.headers.delete(name);
25
24
  }
26
- for (const [name, value] of Object.entries(codexIdentityFromUserAgent(request.headers.get("user-agent")))) {
27
- if (!explicitHeaderNames.has(name)) request.headers.set(name, value);
28
- }
29
25
  if (api !== "openai-responses") return;
30
26
 
31
27
  // [喵喵喵]: 身份来自本次请求选项,不依赖 prompt_cache_key;关闭缓存也不改变线程身份。
32
28
  // session_id / x-session-id 属于 Pi 的接入亲和配置,不是这些 Codex 头的别名,必须保留。
33
- setDefaultProtocolHeader(request.headers, "session-id", sessionId);
34
- setDefaultProtocolHeader(request.headers, "thread-id", sessionId);
35
- setDefaultProtocolHeader(request.headers, "x-client-request-id", request.headers.get("thread-id") ?? request.headers.get("session-id") ?? sessionId);
36
- if (request.headers.has("x-codex-routing-hint")) return;
29
+ setDefaultProtocolHeader(request.headers, "session-id", sessionId, explicitHeaderNames);
30
+ setDefaultProtocolHeader(request.headers, "thread-id", sessionId, explicitHeaderNames);
31
+ setDefaultProtocolHeader(request.headers, "x-client-request-id", request.headers.get("thread-id") ?? request.headers.get("session-id") ?? sessionId, explicitHeaderNames);
32
+ if (request.headers.has("x-codex-routing-hint") || explicitHeaderNames.has("x-codex-routing-hint")) return;
37
33
 
38
34
  // [喵喵喵]: 读取已序列化的请求副本,确保 model/tier 来自所有 payload transform 完成后的实际正文。
39
35
  const payload: unknown = await request.clone().json().catch(() => undefined);
40
36
  if (!isObjectRecord(payload) || typeof payload.model !== "string" || !payload.model) return;
41
37
  const tier = typeof payload.service_tier === "string" && payload.service_tier ? `;tier=${payload.service_tier}` : "";
42
- setDefaultProtocolHeader(request.headers, "x-codex-routing-hint", `model=${payload.model}${tier}`);
38
+ setDefaultProtocolHeader(request.headers, "x-codex-routing-hint", `model=${payload.model}${tier}`, explicitHeaderNames);
43
39
  }
@@ -4,6 +4,8 @@ import { hostname } from "node:os";
4
4
  import { mkdir, readFile, readdir, lstat, unlink, rmdir, writeFile, link } from "node:fs/promises";
5
5
  import { join } from "node:path";
6
6
  import { randomUUID } from "node:crypto";
7
+ import { execFile } from "node:child_process";
8
+ import { promisify } from "node:util";
7
9
  import { t } from "./i18n.ts";
8
10
  import { STATE_DIR } from "./state-metadata-store.ts";
9
11
 
@@ -12,6 +14,7 @@ interface ConfigurationLockRecord {
12
14
  pid: number;
13
15
  hostname: string;
14
16
  startedAt: string;
17
+ processStartedAt?: string;
15
18
  }
16
19
 
17
20
  interface HeldConfigurationLock {
@@ -25,6 +28,50 @@ const LOCK_WAIT_MS = 1_600;
25
28
  const LOCK_RETRY_MS = 25;
26
29
  const INVALID_LOCK_STALE_MS = 30_000;
27
30
  const OWNER_FILE_PATTERN = /^owner-([a-z0-9-]+)\.json$/i;
31
+ const execFileAsync = promisify(execFile);
32
+ let ownProcessStartedAt: Promise<string> | undefined;
33
+
34
+ async function readProcessStartedAt(pid: number): Promise<string> {
35
+ if (process.platform === "linux") {
36
+ const [stat, bootId] = await Promise.all([
37
+ readFile(`/proc/${pid}/stat`, "utf8"),
38
+ readFile("/proc/sys/kernel/random/boot_id", "utf8"),
39
+ ]);
40
+ // [喵喵喵]: comm 可以包含空格和括号,须从最后一个右括号后定位第 22 字段;boot ID 区分重启。
41
+ const ticks = stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[19];
42
+ if (!ticks || !/^\d+$/.test(ticks) || !bootId.trim()) throw new Error("Invalid process start identity");
43
+ return `linux:${bootId.trim()}:${ticks}`;
44
+ }
45
+ if (process.platform === "win32") {
46
+ const { stdout } = await execFileAsync("pwsh", ["-NoProfile", "-NonInteractive", "-Command",
47
+ `$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [Text.Encoding]::UTF8; (Get-Process -Id ${pid}).StartTime.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)`,
48
+ ], { timeout: 1_500, maxBuffer: 8_192, windowsHide: true });
49
+ const ticks = stdout.trim();
50
+ if (!/^\d+$/.test(ticks)) throw new Error("Invalid process start identity");
51
+ return `win32:${ticks}`;
52
+ }
53
+ if (process.platform === "darwin") {
54
+ const { stdout } = await execFileAsync("/bin/ps", ["-p", String(pid), "-o", "lstart="], {
55
+ timeout: 1_500, maxBuffer: 8_192, env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
56
+ });
57
+ if (!stdout.trim()) throw new Error("Missing process start identity");
58
+ return `darwin:${stdout.trim()}`;
59
+ }
60
+ throw new Error(`Unsupported platform: ${process.platform}`);
61
+ }
62
+
63
+ function getOwnProcessStartedAt(): Promise<string> {
64
+ return ownProcessStartedAt ??= readProcessStartedAt(process.pid).catch(() => {
65
+ ownProcessStartedAt = undefined;
66
+ throw new Error(t("无法确认当前进程的创建时间,未获取配置锁;请检查系统进程查询权限(Windows 需要 PowerShell 7 / pwsh)。"));
67
+ });
68
+ }
69
+
70
+ function lockPublicationError(error: unknown): Error {
71
+ return new Error(t("无法发布配置锁的硬链接({code}):{path};请检查目录权限、文件系统硬链接支持或目录占用。", {
72
+ code: getErrorCode(error) ?? "UNKNOWN", path: LOCK_PATH,
73
+ }), { cause: error });
74
+ }
28
75
 
29
76
  function getErrorCode(error: unknown): string | undefined {
30
77
  return error instanceof Error && "code" in error
@@ -49,15 +96,22 @@ function parseLockRecord(source: string): ConfigurationLockRecord | undefined {
49
96
  }
50
97
  }
51
98
 
52
- function isSameHostProcessRunning(record: ConfigurationLockRecord): boolean {
99
+ async function isSameHostProcessRunning(record: ConfigurationLockRecord, identities: Map<string, Promise<string | undefined>>): Promise<boolean> {
53
100
  if (record.hostname !== hostname()) return true;
54
101
  // [喵喵喵]: 不按持有时长抢占活跃进程;暂停或慢磁盘不能使尚未结束的事务失去互斥。
55
102
  try {
56
103
  process.kill(record.pid, 0);
57
- return true;
58
104
  } catch (error) {
59
105
  return getErrorCode(error) !== "ESRCH";
60
106
  }
107
+ if (typeof record.processStartedAt !== "string" || !record.processStartedAt) return true;
108
+ let identity = identities.get(record.token);
109
+ if (!identity) {
110
+ identity = (record.pid === process.pid ? getOwnProcessStartedAt() : readProcessStartedAt(record.pid)).catch(() => undefined);
111
+ identities.set(record.token, identity);
112
+ }
113
+ const current = await identity;
114
+ return current === undefined || current === record.processStartedAt;
61
115
  }
62
116
 
63
117
  async function removeEmptyDirectory(path: string): Promise<boolean> {
@@ -74,13 +128,13 @@ async function removeEmptyDirectory(path: string): Promise<boolean> {
74
128
  }
75
129
  }
76
130
 
77
- async function removeInactiveLock(): Promise<boolean> {
131
+ async function removeInactiveLock(identities: Map<string, Promise<string | undefined>>): Promise<boolean> {
78
132
  try {
79
133
  const stats = await lstat(LOCK_PATH);
80
134
  if (!stats.isDirectory()) {
81
135
  if (!stats.isFile()) return false;
82
136
  const record = parseLockRecord(await readFile(LOCK_PATH, "utf8"));
83
- if (record ? isSameHostProcessRunning(record) : Date.now() - stats.mtimeMs < INVALID_LOCK_STALE_MS) return false;
137
+ if (record ? await isSameHostProcessRunning(record, identities) : Date.now() - stats.mtimeMs < INVALID_LOCK_STALE_MS) return false;
84
138
  // [喵喵喵]: 旧进程不认识目录协议;自动搬走旧文件仍会重现抢锁竞态,必须人工核对后处理。
85
139
  throw new Error(t("检测到旧版失效配置锁;请确认没有旧版 Pi 正在保存,再手动移除:{path}", { path: LOCK_PATH }));
86
140
  }
@@ -95,7 +149,7 @@ async function removeInactiveLock(): Promise<boolean> {
95
149
  const ownerPath = join(LOCK_PATH, name);
96
150
  const record = parseLockRecord(await readFile(ownerPath, "utf8"));
97
151
  if (record) {
98
- if (record.token !== match[1] || isSameHostProcessRunning(record)) return false;
152
+ if (record.token !== match[1] || await isSameHostProcessRunning(record, identities)) return false;
99
153
  } else if (Date.now() - (await lstat(ownerPath)).mtimeMs < INVALID_LOCK_STALE_MS) {
100
154
  return false;
101
155
  }
@@ -130,11 +184,14 @@ async function acquireConfigurationLock(): Promise<HeldConfigurationLock> {
130
184
  await mkdir(STATE_DIR, { recursive: true });
131
185
  const record: ConfigurationLockRecord = {
132
186
  token: randomUUID(), pid: process.pid, hostname: hostname(), startedAt: new Date().toISOString(),
187
+ processStartedAt: await getOwnProcessStartedAt(),
133
188
  };
134
189
  const ownerFileName = `owner-${record.token}.json`;
135
190
  const recordSourcePath = join(STATE_DIR, `config.lock.source.${record.token}`);
136
191
  await writeFile(recordSourcePath, `${JSON.stringify(record)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
137
192
  let acquired = false;
193
+ let lastLinkError: unknown;
194
+ const identities = new Map<string, Promise<string | undefined>>();
138
195
  try {
139
196
  const deadline = Date.now() + LOCK_WAIT_MS;
140
197
  while (true) {
@@ -148,7 +205,13 @@ async function acquireConfigurationLock(): Promise<HeldConfigurationLock> {
148
205
  if (created) {
149
206
  try {
150
207
  // [喵喵喵]: 完整记录以硬链接原子发布后不再修改,避免半写记录在暂停后被判为损坏旧锁、却又恢复为活跃锁。
151
- await link(recordSourcePath, join(LOCK_PATH, ownerFileName));
208
+ try {
209
+ await link(recordSourcePath, join(LOCK_PATH, ownerFileName));
210
+ lastLinkError = undefined;
211
+ } catch (error) {
212
+ lastLinkError = error;
213
+ throw error;
214
+ }
152
215
  // [喵喵喵]: 空目录被回收后,旧初始化者可能把标记发布到新目录;只有独占自身标记才允许进入事务。
153
216
  const entries = await readdir(LOCK_PATH);
154
217
  if (entries.length === 1 && entries[0] === ownerFileName) {
@@ -159,17 +222,18 @@ async function acquireConfigurationLock(): Promise<HeldConfigurationLock> {
159
222
  // [喵喵喵]: 删除挂起在 Windows 上也会令后续 mkdir/link/readdir 返回忙;只有完成发布并确认独占才算成功。
160
223
  if (!["ENOENT", "ENOTDIR"].includes(getErrorCode(error) ?? "") && !isWindowsDirectoryBusy(error)) {
161
224
  await discardOwnClaim(ownerFileName);
162
- throw error;
225
+ throw error === lastLinkError ? lockPublicationError(error) : error;
163
226
  }
164
227
  }
165
228
  await discardOwnClaim(ownerFileName);
166
- } else if (await removeInactiveLock()) {
229
+ } else if (await removeInactiveLock(identities)) {
167
230
  if (Date.now() < deadline) continue;
168
231
  }
169
232
  if (Date.now() >= deadline) break;
170
233
  await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
171
234
  }
172
- throw new Error(t("另一个 Pi 进程正在保存模型配置;无法在限定时间内获取锁:{path}", { path: LOCK_PATH }));
235
+ if (lastLinkError) throw lockPublicationError(lastLinkError);
236
+ throw new Error(t("无法在限定时间内获取锁:{path};持有者仍在运行或身份无法确认,请核对锁记录后重试。", { path: LOCK_PATH }));
173
237
  } finally {
174
238
  if (!acquired) await unlink(recordSourcePath);
175
239
  }
@@ -11,7 +11,7 @@ import { join } from "node:path";
11
11
  import { atomicWriteText, SECURE_FILE_MODE } from "./atomic-write.ts";
12
12
  import { formatUnknownError, isObjectRecord, stringifyJson } from "./common.ts";
13
13
  import { withConfigurationLock } from "./configuration-lock.ts";
14
- import { hashTextContent, readStableTextFileSnapshot } from "./file-snapshot.ts";
14
+ import { hashTextContent, readFileSignature, readStableTextFileSnapshot } from "./file-snapshot.ts";
15
15
  import { t } from "./i18n.ts";
16
16
  import {
17
17
  MODELS_JSON_PATH,
@@ -34,9 +34,11 @@ import {
34
34
  STATE_DIR,
35
35
  readMetadataStateSnapshot,
36
36
  serializeMetadataState,
37
+ type MetadataDocument,
37
38
  } from "./state-metadata-store.ts";
38
- import { buildStateDocumentFromSources } from "./state-store.ts";
39
- import type { StateDocument } from "./types.ts";
39
+ import { getClientHeadersForProfile, resolveClientHeaderProfile } from "./presets/client-headers.ts";
40
+ import { buildStateDocumentFromSources, tryReadStateSnapshot, type StateSourceSnapshot } from "./state-store.ts";
41
+ import type { ApiKind, StateDocument } from "./types.ts";
40
42
 
41
43
  interface PreparedConfigurationChange {
42
44
  document: StateDocument;
@@ -153,6 +155,8 @@ async function recoverPendingConfigurationTransactionInsideLock(): Promise<boole
153
155
  }
154
156
 
155
157
  export async function recoverPendingConfigurationTransaction(): Promise<boolean> {
158
+ // [喵喵喵]: 无意图文件时不取写锁;后续读配置仍检查事务与双文件签名,不能把此处当作一致性凭证。
159
+ if (!(await readFileSignature(TRANSACTION_PATH)).exists) return false;
156
160
  return withConfigurationLock(recoverPendingConfigurationTransactionInsideLock);
157
161
  }
158
162
 
@@ -167,9 +171,8 @@ async function writeConfigurationTransaction(
167
171
  modelsSnapshot: Awaited<ReturnType<typeof readModelsJsonSnapshot>>,
168
172
  metadataSnapshot: Awaited<ReturnType<typeof readMetadataStateSnapshot>>,
169
173
  modelsTarget: string,
170
- nextState: StateDocument,
174
+ metadataTarget: string,
171
175
  ): Promise<void> {
172
- const metadataTarget = serializeMetadataState(nextState);
173
176
  const journal: ConfigurationTransactionJournal = {
174
177
  version: 1,
175
178
  createdAt: new Date().toISOString(),
@@ -210,9 +213,46 @@ type ModelsDocumentMutation = (
210
213
  change: PreparedConfigurationChange,
211
214
  ) => ModelsJsonDocument;
212
215
 
216
+ function migrateGeneratedClaudeCodeBetas(
217
+ source: ModelsJsonDocument,
218
+ state: StateDocument,
219
+ metadata: MetadataDocument,
220
+ ): ModelsJsonDocument {
221
+ let result = source;
222
+ for (const [providerId, provider] of Object.entries(state.providers)) {
223
+ const entry = source.providers[providerId];
224
+ if (!provider.managed || !entry?.models) continue;
225
+ let changed = false;
226
+ const models = entry.models.map((model) => {
227
+ if (resolveClientHeaderProfile(provider.clientHeaderProfile, (model.api ?? provider.api) as ApiKind) !== "claude-code") return model;
228
+ const generated = metadata.models[`${providerId}/${model.id}`]?.generatedClientHeaders;
229
+ const beta = Object.entries(generated ?? {}).find(([name]) => name.toLowerCase() === "anthropic-beta");
230
+ if (!beta) return model;
231
+ const owned = Object.entries(model.headers ?? {}).filter(([name, value]) => name.toLowerCase() === "anthropic-beta" && value === beta[1]);
232
+ if (owned.length === 0) return model;
233
+ // [喵喵喵]: 只删除来源快照证明仍属插件的旧值;不按 beta 内容猜测归属,不改写模型其它字段。
234
+ const headers = { ...model.headers };
235
+ for (const [name] of owned) delete headers[name];
236
+ const next = { ...model };
237
+ if (Object.keys(headers).length > 0) next.headers = headers;
238
+ else delete next.headers;
239
+ changed = true;
240
+ return next;
241
+ });
242
+ if (changed) result = { ...result, providers: { ...result.providers, [providerId]: { ...entry, models } } };
243
+ }
244
+ return result;
245
+ }
246
+
247
+ function hasCapturedClaudeCodeBeta(state: StateDocument): boolean {
248
+ return Object.keys(state.clientHeaderCaptures["claude-code"]?.headers ?? {}).some((name) => name.toLowerCase() === "anthropic-beta");
249
+ }
250
+
213
251
  async function persistConfigurationInsideLock(
214
252
  prepare: PrepareConfigurationChange,
215
253
  mutateModels: ModelsDocumentMutation,
254
+ isModelRewritten: (providerId: string, modelId: string, change: PreparedConfigurationChange) => boolean
255
+ = (providerId, _modelId, change) => change.changedProviderIds.includes(providerId),
216
256
  ): Promise<StateDocument> {
217
257
  await recoverPendingConfigurationTransactionInsideLock();
218
258
  const [modelsSnapshot, metadataSnapshot] = await Promise.all([
@@ -220,6 +260,15 @@ async function persistConfigurationInsideLock(
220
260
  readMetadataStateSnapshot(),
221
261
  ]);
222
262
  const latest = await buildStateDocumentFromSources(modelsSnapshot.document, metadataSnapshot);
263
+ if (hasCapturedClaudeCodeBeta(latest)) {
264
+ latest.clientHeaderCaptures = {
265
+ ...latest.clientHeaderCaptures,
266
+ "claude-code": {
267
+ ...latest.clientHeaderCaptures["claude-code"]!,
268
+ headers: getClientHeadersForProfile("claude-code", "anthropic-messages", {}, latest.clientHeaderCaptures)!,
269
+ },
270
+ };
271
+ }
223
272
  const sourceWithOwnershipMarkers = metadataSnapshot.requirePluginManagedProviderMarker
224
273
  ? modelsSnapshot.document
225
274
  : markManagedProvidersInDoc(modelsSnapshot.document, latest.managedProviderIds);
@@ -229,9 +278,10 @@ async function persistConfigurationInsideLock(
229
278
  [],
230
279
  Object.keys(metadataSnapshot.legacyProviders),
231
280
  );
281
+ const sourceWithCurrentHeaders = migrateGeneratedClaudeCodeBetas(sourceWithLegacyProviders, latest, metadataSnapshot.metadata);
232
282
  const migratedSource = metadataSnapshot.metadata.version < 5
233
- ? migrateManagedBaseUrls(latest, sourceWithLegacyProviders)
234
- : sourceWithLegacyProviders;
283
+ ? migrateManagedBaseUrls(latest, sourceWithCurrentHeaders)
284
+ : sourceWithCurrentHeaders;
235
285
  const existingProviderIds = new Set(Object.keys(latest.providers));
236
286
  const change = prepare(latest);
237
287
  // [喵喵喵]: 原生扩展可只保存覆盖项而不列 models;目录过滤掉的节点仍占用 ID,不允许新建时覆盖。
@@ -244,21 +294,41 @@ async function persistConfigurationInsideLock(
244
294
  const modelsTarget = nextModels === modelsSnapshot.document && modelsSnapshot.source !== undefined
245
295
  ? modelsSnapshot.source
246
296
  : stringifyJson(nextModels);
247
- await writeConfigurationTransaction(modelsSnapshot, metadataSnapshot, modelsTarget, change.document);
297
+ const metadataTarget = serializeMetadataState(change.document, {
298
+ previous: metadataSnapshot.metadata,
299
+ models: nextModels,
300
+ isModelRewritten: (providerId, modelId) => Object.hasOwn(metadataSnapshot.legacyProviders, providerId)
301
+ || isModelRewritten(providerId, modelId, change),
302
+ });
303
+ await writeConfigurationTransaction(modelsSnapshot, metadataSnapshot, modelsTarget, metadataTarget);
248
304
  return change.document;
249
305
  }
250
306
 
251
- /** 在 catalog 注册前完成地址语义升级,避免 models.json 原生覆盖与私有元数据版本不一致。 */
307
+ async function needsConfigurationMigration(snapshot: StateSourceSnapshot): Promise<boolean> {
308
+ if (snapshot.metadata.metadata.version < 5) return true;
309
+ const state = await buildStateDocumentFromSources(snapshot.models.document, snapshot.metadata);
310
+ if (hasCapturedClaudeCodeBeta(state)
311
+ || migrateGeneratedClaudeCodeBetas(snapshot.models.document, state, snapshot.metadata.metadata) !== snapshot.models.document) return true;
312
+ return Object.entries(state.providers).some(([providerId, provider]) => provider.managed
313
+ && provider.models.some((model) => snapshot.metadata.metadata.models[`${providerId}/${model.id}`]?.generatedClientHeaders === undefined));
314
+ }
315
+
316
+ /** 在 catalog 注册前升级地址语义、清理自动画像 beta,并初始化缺少的生成头快照。 */
252
317
  export async function migrateManagedEndpointConfiguration(): Promise<boolean> {
318
+ const snapshot = await tryReadStateSnapshot();
319
+ if (snapshot && !(await needsConfigurationMigration(snapshot))) return false;
253
320
  return withConfigurationLock(async () => {
254
321
  await recoverPendingConfigurationTransactionInsideLock();
255
- if ((await readMetadataStateSnapshot()).metadata.version >= 5) return false;
322
+ // [喵喵喵]: 锁外快照只用于免写判断;等待锁期间配置可能已被其它会话迁移,写入前须重新判定。
323
+ const [models, metadata] = await Promise.all([readModelsJsonSnapshot(), readMetadataStateSnapshot()]);
324
+ if (!(await needsConfigurationMigration({ models, metadata }))) return false;
325
+ const migrateEndpoints = metadata.metadata.version < 5;
256
326
  await persistConfigurationInsideLock(
257
327
  (document) => ({ document, changedProviderIds: [], removedProviderIds: [] }),
258
328
  (source) => source,
259
329
  );
260
330
  invalidateStateCache();
261
- return true;
331
+ return migrateEndpoints;
262
332
  });
263
333
  }
264
334
 
@@ -327,6 +397,7 @@ export async function persistModelConfiguration(
327
397
  providerId,
328
398
  modelId,
329
399
  ),
400
+ (candidateProviderId, candidateModelId) => candidateProviderId === providerId && candidateModelId === modelId,
330
401
  ));
331
402
  }
332
403
 
@@ -346,6 +417,7 @@ export async function persistModelRenameConfiguration(
346
417
  newModelId,
347
418
  oldModelId,
348
419
  ),
420
+ (candidateProviderId, candidateModelId) => candidateProviderId === providerId && candidateModelId === newModelId,
349
421
  ));
350
422
  }
351
423
 
@@ -358,5 +430,6 @@ export async function persistModelDeletionConfiguration(
358
430
  return refreshRegistryAfterPersistence(ctx, () => persistConfigurationInsideLock(
359
431
  prepare,
360
432
  (source, change) => buildModelsDocumentWithoutModel(change.document, source, providerId, modelId),
433
+ () => false,
361
434
  ));
362
435
  }
package/i18n.ts CHANGED
@@ -258,7 +258,9 @@ const ENGLISH_MESSAGES = {
258
258
  "{label} {key} 的值必须是字符串": "The value of {label} {key} must be a string",
259
259
  "写入 {targetPath} 失败:{error}": "Failed to write {targetPath}: {error}",
260
260
  "写入 {targetPath} 失败;完整内容已保留在临时文件:{tempPath}:{error}": "Failed to write {targetPath}; the complete content remains in temporary file {tempPath}: {error}",
261
- "另一个 Pi 进程正在保存模型配置;无法在限定时间内获取锁:{path}": "Another Pi process is saving the model configuration; the lock could not be acquired in time: {path}",
261
+ "无法在限定时间内获取锁:{path};持有者仍在运行或身份无法确认,请核对锁记录后重试。": "The lock could not be acquired in time: {path}; the owner is still running or its identity could not be verified. Check the lock record before retrying.",
262
+ "无法确认当前进程的创建时间,未获取配置锁;请检查系统进程查询权限(Windows 需要 PowerShell 7 / pwsh)。": "The current process start time could not be verified, so no configuration lock was acquired. Check process query permissions (Windows requires PowerShell 7 / pwsh).",
263
+ "无法发布配置锁的硬链接({code}):{path};请检查目录权限、文件系统硬链接支持或目录占用。": "Could not publish the configuration lock hard link ({code}): {path}; check directory permissions, filesystem hard-link support, or directory contention.",
262
264
  "配置锁所有权在释放前发生变化,已保留锁文件供检查:{path}": "The configuration lock ownership changed before release; the lock file was retained for inspection: {path}",
263
265
  "检测到旧版失效配置锁;请确认没有旧版 Pi 正在保存,再手动移除:{path}": "An inactive legacy configuration lock was detected; confirm that no older Pi process is saving before removing it manually: {path}",
264
266
  "{path} 必须是对象": "{path} must be an object",
@@ -281,6 +283,7 @@ const ENGLISH_MESSAGES = {
281
283
  "已删除请求头 {profileId}": "Deleted header profile {profileId}",
282
284
  "代理地址无效:{url}": "Invalid proxy URL: {url}",
283
285
  "代理地址目前只支持 http:// 或 https:// 代理": "Only http:// or https:// proxies are currently supported",
286
+ "接入代理要求 Node.js 22.21.0(22.x)或 24.5.0 及以上;当前版本为 {version}": "Provider proxies require Node.js 22.21.0 (22.x) or 24.5.0 and later; the current version is {version}",
284
287
  "代理请求失败:{code}": "Proxy request failed: {code}",
285
288
  "代理安全拦截:上游返回了重定向至 {target},已拒绝跟随": "Proxy security block: upstream redirected to {target}; following it was refused",
286
289
  "拒绝转发:目标 Origin {actual} 与注册路由 {expected} 不一致": "Forwarding refused: target origin {actual} does not match the registered route {expected}",
@@ -335,6 +338,8 @@ const ENGLISH_MESSAGES = {
335
338
  ";新配置未注册到当前 runtime": "; the new configuration was not registered in the current runtime",
336
339
  "ClaudeCode metadata 注入失败,本次请求仅使用请求头": "ClaudeCode metadata injection failed; this request will use headers only",
337
340
  "OpenAI Responses instructions 标准化失败,本次请求使用原始 payload": "OpenAI Responses instruction normalization failed; this request will use the original payload",
341
+ "接入代理不支持 Bun {version};请使用 Node.js 22.21.0(22.x)或 24.5.0 及以上运行 Pi。": "Provider proxies are not supported under Bun {version}; run Pi with Node.js 22.21.0 (22.x) or 24.5.0 and later.",
342
+ "Fast mode 需要先接管该接入;请先保存接入配置。": "Fast mode requires a managed provider; save the provider configuration first.",
338
343
  "Fast mode 状态读取失败,本次请求未注入 service_tier": "Failed to read Fast mode state; service_tier was not injected for this request",
339
344
  "跨资源恢复状态处理失败,本次请求未执行自动恢复": "Failed to process state recovery; automatic recovery was not applied to this request",
340
345
  "跨资源自动恢复准备失败,未自动重试": "Failed to prepare cross-resource recovery; no automatic retry was made",