pi-model-manager 0.4.6 → 0.4.8
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 +17 -12
- package/README.md +17 -12
- package/codex-compat.ts +8 -12
- package/configuration-lock.ts +73 -9
- package/configuration-persistence.ts +84 -11
- package/i18n.ts +5 -1
- package/index.ts +5 -5
- package/local-proxy-service.ts +6 -38
- package/package.json +5 -5
- package/presets/builtin-client-headers.ts +4 -5
- package/presets/client-headers.ts +3 -30
- package/presets/providers.ts +3 -4
- package/presets/thinking.ts +2 -13
- package/provider-registrar.ts +145 -27
- package/provider-transport.ts +23 -5
- package/runtime-base-url.ts +11 -0
- package/state-cache.ts +17 -2
- package/state-document.ts +13 -2
- package/state-metadata-store.ts +29 -11
- package/state-store.ts +30 -27
- package/tui/dashboard.ts +29 -29
- package/tui/editor-model.ts +11 -1
- package/tui/editor-provider.ts +2 -2
- package/tui/header-profiles-panel.ts +6 -6
- package/tui/model-list-fetch.ts +28 -10
- package/tui/model-list-validation.ts +1 -0
- package/types.ts +5 -0
package/README.en.md
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
English · [简体中文](./README.md)
|
|
4
4
|
|
|
5
|
-
[](https://github.com/earendil-works/pi)
|
|
6
6
|
[](./LICENSE)
|
|
7
7
|
[](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.
|
|
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
|
|
|
@@ -205,7 +205,9 @@ Each provider can define:
|
|
|
205
205
|
|
|
206
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.
|
|
207
207
|
|
|
208
|
-
Base URL represents the API root
|
|
208
|
+
Base URL represents the API root, to which the protocol endpoint is appended. For example, Anthropic with `https://gw.example.com/xxx` uses `/xxx/messages` for chat and `/xxx/models` for discovery. When entering a URL or switching protocols in the provider editor, a bare domain gets `/v1` for OpenAI / Anthropic or `/v1beta` for Gemini, including custom gateway domains. Gemini converts a final `/v1` path segment to `/v1beta`; switching from Gemini back to OpenAI / Anthropic converts a final `/v1beta` to `/v1`. The host, port, and path prefix are preserved, as are other explicit paths such as `/custom`, `/v1alpha`, and `/v2`.
|
|
209
|
+
|
|
210
|
+
The converted URL appears immediately in the form and, once saved, is shared by chat and model discovery. This version conversion only runs during those configuration actions: it does not migrate unedited URLs or rewrite model-specific endpoints or unmanaged native providers. Base URLs cannot contain query parameters (`?`), fragments (`#`), or embedded credentials; parameters generated by the SDK remain supported.
|
|
209
211
|
|
|
210
212
|
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
213
|
|
|
@@ -233,7 +235,7 @@ Model capabilities include:
|
|
|
233
235
|
|
|
234
236
|
### Responses service tiers
|
|
235
237
|
|
|
236
|
-
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.
|
|
238
|
+
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.
|
|
237
239
|
|
|
238
240
|
| Tier | Request behavior |
|
|
239
241
|
| --- | --- |
|
|
@@ -252,13 +254,10 @@ Fast and Ultrafast require support from the upstream service, account, and model
|
|
|
252
254
|
| Recommended | Claude Code for Anthropic Messages, Codex for OpenAI Completions/Responses, and no identity headers for other protocols |
|
|
253
255
|
| Disabled | Adds no extension-managed client identity headers |
|
|
254
256
|
| Claude Code | Uses the built-in Claude Code compatibility headers and adds required Anthropic request metadata |
|
|
255
|
-
| Codex | Uses the built-in Codex
|
|
257
|
+
| Codex | Uses the built-in Codex Rust CLI compatibility headers |
|
|
256
258
|
| Custom | Uses a reusable JSON header set created in the header-profile panel |
|
|
257
259
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
- Claude Code `2.1.312`
|
|
261
|
-
- Codex TUI `0.165.0`
|
|
260
|
+
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).
|
|
262
261
|
|
|
263
262
|
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.
|
|
264
263
|
|
|
@@ -266,6 +265,8 @@ Custom profiles reject authentication-related sensitive headers. Put authenticat
|
|
|
266
265
|
|
|
267
266
|
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.
|
|
268
267
|
|
|
268
|
+
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.
|
|
269
|
+
|
|
269
270
|
## Configuration files
|
|
270
271
|
|
|
271
272
|
| Path | Purpose |
|
|
@@ -277,6 +278,8 @@ The extension generates client headers, proxy routes, and dynamic registrations
|
|
|
277
278
|
|
|
278
279
|
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.
|
|
279
280
|
|
|
281
|
+
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.
|
|
282
|
+
|
|
280
283
|
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.
|
|
281
284
|
|
|
282
285
|
## Secrets and security
|
|
@@ -302,11 +305,13 @@ Additional considerations:
|
|
|
302
305
|
|
|
303
306
|
| Component | Requirement |
|
|
304
307
|
| --- | --- |
|
|
305
|
-
| `@earendil-works/pi-coding-agent` | `>=0.
|
|
308
|
+
| `@earendil-works/pi-coding-agent` | `>=0.87.0` |
|
|
306
309
|
| `@earendil-works/pi-ai` | `>=0.85.1` |
|
|
307
310
|
| `@earendil-works/pi-tui` | `>=0.75.0` |
|
|
308
311
|
| Runtime mode | `/model-manager` requires the Pi TUI |
|
|
309
312
|
|
|
313
|
+
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.
|
|
314
|
+
|
|
310
315
|
The TUI copy defaults to Simplified Chinese; press `L` on the dashboard to switch to English.
|
|
311
316
|
|
|
312
317
|
## Local development
|
|
@@ -320,7 +325,7 @@ pi -e .
|
|
|
320
325
|
|
|
321
326
|
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.
|
|
322
327
|
|
|
323
|
-
Tests have separate stub and real-host entry points. The current real-host verification baseline is Pi `1.
|
|
328
|
+
Tests have separate stub and real-host entry points. The current real-host verification baseline is Pi `1.5.2`:
|
|
324
329
|
|
|
325
330
|
```bash
|
|
326
331
|
npm test
|
|
@@ -329,7 +334,7 @@ PI_TEST_RUNTIME_ROOT="/path/to/node_modules/@earendil-works/pi-coding-agent" npm
|
|
|
329
334
|
|
|
330
335
|
`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.
|
|
331
336
|
|
|
332
|
-
Host-provided packages
|
|
337
|
+
Host-provided packages declare minimum requirements in `peerDependencies`, matching the compatibility table above. Runtime modules are supplied by Pi.
|
|
333
338
|
|
|
334
339
|
Inspect the public package contents with:
|
|
335
340
|
|
package/README.md
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
[English](./README.en.md) · 简体中文
|
|
4
4
|
|
|
5
|
-
[](https://github.com/earendil-works/pi)
|
|
6
6
|
[](./LICENSE)
|
|
7
7
|
[](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.
|
|
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
|
|
|
@@ -207,7 +207,9 @@ pi install npm:pi-model-manager
|
|
|
207
207
|
|
|
208
208
|
新建模型时,扩展会尝试从上游读取模型列表;整次发现共用一个 10 秒上限,可按 `Esc` 手动取消。列表与聊天使用同一 API 根地址和配置的认证信息,错误会区分认证失败、接口不存在、限流和上游异常。失败或取消后仍可手动输入模型 ID。
|
|
209
209
|
|
|
210
|
-
Base URL 表示 API
|
|
210
|
+
Base URL 表示 API 根地址,再追加协议端点。例如 Anthropic 的 `https://gw.example.com/xxx` 请求 `/xxx/messages`,模型列表请求 `/xxx/models`。在接入编辑器中输入地址或切换协议时,只填域名会按协议补 `/v1`(OpenAI / Anthropic)或 `/v1beta`(Gemini,包括自定义中转域名)。Gemini 会将末尾完整路径段 `/v1` 转为 `/v1beta`;从 Gemini 切回 OpenAI / Anthropic 时,末尾 `/v1beta` 转为 `/v1`。域名、端口和路径前缀保留,其他显式路径(如 `/custom`、`/v1alpha`、`/v2`)不改写。
|
|
211
|
+
|
|
212
|
+
转换后的地址会立即显示在表单中,保存后统一用于聊天和模型列表。此版本转换只发生在上述配置操作中,不自动迁移未编辑的存量地址,也不改写模型级独立地址或未接管的原生接入。Base URL 不支持查询参数(`?`)、片段(`#`)或内嵌认证;SDK 正常生成的请求参数不受影响。
|
|
211
213
|
|
|
212
214
|
Anthropic 标准端点在写入 `models.json` 时转换为 Pi 原生 SDK 所需形式,因此未加载扩展时也能使用;自定义版本路径通过 `state.json` 私有标记衔接,依赖扩展的发送适配。代理开关只改变传输路线,最终端点、业务请求头和 payload 保持一致;代理失败会报错。
|
|
213
215
|
|
|
@@ -237,7 +239,7 @@ Anthropic 标准端点在写入 `models.json` 时转换为 Pi 原生 SDK 所需
|
|
|
237
239
|
|
|
238
240
|
#### Responses 速度档位
|
|
239
241
|
|
|
240
|
-
|
|
242
|
+
当接入已由插件接管且 API 协议为 `openai-responses` 时,模型编辑器会显示 **Fast mode**。未接管时隐藏该项并提示先保存接入配置。用 `←` / `→` 循环切换三档,或按 `Enter` 查看完整说明;模型列表也会显示所选档位。英文界面对应 Standard / Fast / Ultrafast。
|
|
241
243
|
|
|
242
244
|
| 档位 | 请求行为 |
|
|
243
245
|
| --- | --- |
|
|
@@ -256,13 +258,10 @@ Fast 和 Ultrafast 需要上游、账号及模型支持,可能产生额外费
|
|
|
256
258
|
| 自动推荐 | Anthropic Messages 使用 Claude Code;OpenAI Completions/Responses 使用 Codex;其他协议不附加身份头 |
|
|
257
259
|
| 不添加 | 不添加扩展管理的客户端身份请求头 |
|
|
258
260
|
| Claude Code | 使用内置 Claude Code 兼容请求头,并为 Anthropic 请求补充必要的兼容 metadata |
|
|
259
|
-
| Codex | 使用内置 Codex
|
|
261
|
+
| Codex | 使用内置 Codex Rust CLI 兼容请求头 |
|
|
260
262
|
| 自定义 | 使用在请求头面板中创建的可复用 JSON 请求头集合 |
|
|
261
263
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
- Claude Code `2.1.312`
|
|
265
|
-
- Codex TUI `0.165.0`
|
|
264
|
+
内置画像位于 `presets/builtin-client-headers.ts`,不包含认证信息;本机抓包缓存存在时优先使用缓存。Codex 使用 `codex_cli_rs` 画像,字段以 [codex-proxy-rs](https://github.com/zyycn/codex-proxy-rs) 为参考。
|
|
266
265
|
|
|
267
266
|
这些值只用于兼容需要识别客户端身份的 API 中转,不代替 API key。公开仓库和 npm 包**不包含请求捕获工具、用户抓包、认证头或本机状态**。如果内置值不适合你的服务,请关闭身份头或创建自定义请求头。
|
|
268
267
|
|
|
@@ -270,6 +269,8 @@ Fast 和 Ultrafast 需要上游、账号及模型支持,可能产生额外费
|
|
|
270
269
|
|
|
271
270
|
显式原生请求头覆盖内置模板;选择自定义请求头时,自定义值拥有最终优先级。同名字段按大小写不敏感方式合并。自定义 `anthropic-beta` 清单完整保留,Adaptive Thinking 不会修改它。
|
|
272
271
|
|
|
272
|
+
生成头来源快照与实际写入的模型同步;只保存其他模型不会更新未改写模型的快照。缺少来源记录时,只记录与当前画像同值的字段,无法确认来源的旧值作为原生覆盖保留,不按历史值或头名自动清理。因此「不添加」不会删除这类旧覆盖,如需移除须核对后手动编辑 `models.json`。
|
|
273
|
+
|
|
273
274
|
## 配置文件
|
|
274
275
|
|
|
275
276
|
| 路径 | 用途 |
|
|
@@ -281,6 +282,8 @@ Fast 和 Ultrafast 需要上游、账号及模型支持,可能产生额外费
|
|
|
281
282
|
|
|
282
283
|
插件自身的配置写入由跨进程锁串行化,`enabledModels` 还同时遵守 Pi 的 `proper-lockfile` 锁;`models.json` 与 `state.json` 通过事务意图文件在中断后恢复,读取方不会采用事务进行中的半完成组合。外部编辑器不受这些锁约束,因此保存前仍会校验内容签名;检测到外部修改时会取消保存而不是覆盖。
|
|
283
284
|
|
|
285
|
+
配置锁记录 PID 和系统进程创建时间,以识别 PID 复用;不会按持锁时长强行回收。查询失败时不抢占可能活跃的锁,自身身份无法确认时拒绝持锁写入。Windows 使用 `pwsh`,Linux 使用 `/proc`,macOS 使用 `/bin/ps`;当前进程的身份在进程内缓存。
|
|
286
|
+
|
|
284
287
|
旧端点配置会升级到 v5 元数据,保持原最终聊天地址,迁移前的双文件快照保存在插件配置目录的 `base-url-v5-*.json`。快照包含原始配置,应按凭据文件保护;回退时需配套恢复代码、`models.json` 和 `state.json`。
|
|
285
288
|
|
|
286
289
|
## 密钥与安全
|
|
@@ -306,11 +309,13 @@ ${ANTHROPIC_API_KEY}
|
|
|
306
309
|
|
|
307
310
|
| 组件 | 要求 |
|
|
308
311
|
| --- | --- |
|
|
309
|
-
| `@earendil-works/pi-coding-agent` | `>=0.
|
|
312
|
+
| `@earendil-works/pi-coding-agent` | `>=0.87.0` |
|
|
310
313
|
| `@earendil-works/pi-ai` | `>=0.85.1` |
|
|
311
314
|
| `@earendil-works/pi-tui` | `>=0.75.0` |
|
|
312
315
|
| 运行模式 | `/model-manager` 需要 Pi TUI |
|
|
313
316
|
|
|
317
|
+
Pi `0.87.0` 是 `agent_before_settle` 的 API 下限,不代表已逐版本验证兼容性;当前真实宿主检查基线为 Pi `1.5.2`,更早版本未逐一验证。
|
|
318
|
+
|
|
314
319
|
默认 TUI 文案为简体中文;可在主面板按 `L` 切换为 English。
|
|
315
320
|
|
|
316
321
|
## 本地开发
|
|
@@ -324,7 +329,7 @@ pi -e .
|
|
|
324
329
|
|
|
325
330
|
扩展由 Pi 直接加载 TypeScript 入口,不需要单独构建步骤。开发时请勿提交 `state.json`、`bootstrap-meta.json`、`node_modules` 或任何请求捕获数据。
|
|
326
331
|
|
|
327
|
-
测试分为替身测试和真实宿主测试,当前真实宿主验证基线为 Pi `1.
|
|
332
|
+
测试分为替身测试和真实宿主测试,当前真实宿主验证基线为 Pi `1.5.2`:
|
|
328
333
|
|
|
329
334
|
```bash
|
|
330
335
|
npm test
|
|
@@ -333,7 +338,7 @@ PI_TEST_RUNTIME_ROOT="/path/to/node_modules/@earendil-works/pi-coding-agent" npm
|
|
|
333
338
|
|
|
334
339
|
`npm test` 使用测试替身,并跳过真实宿主用例;`test:runtime` 只运行 `tests/*-wire.test.ts`,包括完整内置接入目录保护与协议转发检查。`PI_TEST_RUNTIME_ROOT` 指向已安装的 Pi 包目录,Windows Git Bash 下使用 `C:/...` 形式。这些测试使用本地响应与虚拟凭据,不调用外部模型服务。
|
|
335
340
|
|
|
336
|
-
宿主提供的包在 `peerDependencies`
|
|
341
|
+
宿主提供的包在 `peerDependencies` 中声明最低要求,与上方兼容性表一致;运行时仍复用 Pi 提供的模块。
|
|
337
342
|
|
|
338
343
|
验证公开包内容:
|
|
339
344
|
|
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
|
-
/**
|
|
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
|
}
|
package/configuration-lock.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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 {
|
|
39
|
-
import type
|
|
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
|
-
|
|
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,
|
|
234
|
-
:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
"
|
|
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",
|
|
@@ -336,6 +338,8 @@ const ENGLISH_MESSAGES = {
|
|
|
336
338
|
";新配置未注册到当前 runtime": "; the new configuration was not registered in the current runtime",
|
|
337
339
|
"ClaudeCode metadata 注入失败,本次请求仅使用请求头": "ClaudeCode metadata injection failed; this request will use headers only",
|
|
338
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.",
|
|
339
343
|
"Fast mode 状态读取失败,本次请求未注入 service_tier": "Failed to read Fast mode state; service_tier was not injected for this request",
|
|
340
344
|
"跨资源恢复状态处理失败,本次请求未执行自动恢复": "Failed to process state recovery; automatic recovery was not applied to this request",
|
|
341
345
|
"跨资源自动恢复准备失败,未自动重试": "Failed to prepare cross-resource recovery; no automatic retry was made",
|