pi-model-manager 0.4.4 → 0.4.5
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 +3 -3
- package/README.md +3 -3
- package/codex-compat.ts +43 -0
- package/configuration-lock.ts +112 -109
- package/configuration-persistence.ts +7 -0
- package/header-profile-mutations.ts +42 -14
- package/i18n.ts +10 -6
- package/local-proxy-service.ts +9 -10
- package/model-mutations.ts +16 -1
- package/models-json-manager.ts +5 -1
- package/openai-responses-recovery.ts +23 -51
- package/package.json +87 -86
- package/presets/builtin-client-headers.ts +5 -5
- package/presets/client-headers.ts +11 -2
- package/presets/codex-client-headers.ts +27 -0
- package/provider-registrar.ts +6 -11
- package/provider-transport.ts +13 -9
- package/state-metadata-store.ts +16 -3
- package/state-store.ts +5 -12
- package/tui/editor-model.ts +2 -2
- package/tui/editor-provider.ts +3 -3
- package/tui/model-list-fetch.ts +2 -2
- package/types.ts +1 -1
package/README.en.md
CHANGED
|
@@ -255,8 +255,8 @@ Fast and Ultrafast require support from the upstream service, account, and model
|
|
|
255
255
|
|
|
256
256
|
The current built-in values were derived from real client requests with authentication fields removed:
|
|
257
257
|
|
|
258
|
-
- Claude Code `2.1.
|
|
259
|
-
- Codex TUI `0.
|
|
258
|
+
- Claude Code `2.1.312`
|
|
259
|
+
- Codex TUI `0.165.0`
|
|
260
260
|
|
|
261
261
|
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
262
|
|
|
@@ -318,7 +318,7 @@ pi -e .
|
|
|
318
318
|
|
|
319
319
|
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
320
|
|
|
321
|
-
Tests have separate stub and real-host entry points. The current real-host verification baseline is Pi `
|
|
321
|
+
Tests have separate stub and real-host entry points. The current real-host verification baseline is Pi `1.4.0`:
|
|
322
322
|
|
|
323
323
|
```bash
|
|
324
324
|
npm test
|
package/README.md
CHANGED
|
@@ -259,8 +259,8 @@ Fast 和 Ultrafast 需要上游、账号及模型支持,可能产生额外费
|
|
|
259
259
|
|
|
260
260
|
当前内置值来自真实客户端请求并已移除认证信息:
|
|
261
261
|
|
|
262
|
-
- Claude Code `2.1.
|
|
263
|
-
- Codex TUI `0.
|
|
262
|
+
- Claude Code `2.1.312`
|
|
263
|
+
- Codex TUI `0.165.0`
|
|
264
264
|
|
|
265
265
|
这些值只用于兼容需要识别客户端身份的 API 中转,不代替 API key。公开仓库和 npm 包**不包含请求捕获工具、用户抓包、认证头或本机状态**。如果内置值不适合你的服务,请关闭身份头或创建自定义请求头。
|
|
266
266
|
|
|
@@ -322,7 +322,7 @@ pi -e .
|
|
|
322
322
|
|
|
323
323
|
扩展由 Pi 直接加载 TypeScript 入口,不需要单独构建步骤。开发时请勿提交 `state.json`、`bootstrap-meta.json`、`node_modules` 或任何请求捕获数据。
|
|
324
324
|
|
|
325
|
-
测试分为替身测试和真实宿主测试,当前真实宿主验证基线为 Pi `
|
|
325
|
+
测试分为替身测试和真实宿主测试,当前真实宿主验证基线为 Pi `1.4.0`:
|
|
326
326
|
|
|
327
327
|
```bash
|
|
328
328
|
npm test
|
package/codex-compat.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Codex 客户端画像与请求级协议头;不持有跨模型共享的可变会话状态。
|
|
2
|
+
|
|
3
|
+
import { isObjectRecord } from "./common.ts";
|
|
4
|
+
import { codexIdentityFromUserAgent } from "./presets/codex-client-headers.ts";
|
|
5
|
+
import type { ApiKind } from "./types.ts";
|
|
6
|
+
|
|
7
|
+
function setDefaultProtocolHeader(headers: Headers, name: string, value: string | undefined): void {
|
|
8
|
+
if (!value || headers.has(name)) return;
|
|
9
|
+
try {
|
|
10
|
+
headers.set(name, value);
|
|
11
|
+
} catch {
|
|
12
|
+
// [喵喵喵]: 与官方可选协议头一致,无法表示为 HTTP header 时跳过投影,不阻断业务正文。
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** 在 SDK 完成构造后收口 Codex 指纹;仅修改本次请求,不更改缓存与会话亲和契约。 */
|
|
17
|
+
export async function applyCodexRequestHeaders(
|
|
18
|
+
request: Request,
|
|
19
|
+
api: ApiKind,
|
|
20
|
+
sessionId: string | undefined,
|
|
21
|
+
explicitHeaderNames: ReadonlySet<string>,
|
|
22
|
+
): Promise<void> {
|
|
23
|
+
for (const name of [...request.headers.keys()]) {
|
|
24
|
+
if (name.startsWith("x-stainless-") && !explicitHeaderNames.has(name)) request.headers.delete(name);
|
|
25
|
+
}
|
|
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
|
+
if (api !== "openai-responses") return;
|
|
30
|
+
|
|
31
|
+
// [喵喵喵]: 身份来自本次请求选项,不依赖 prompt_cache_key;关闭缓存也不改变线程身份。
|
|
32
|
+
// 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;
|
|
37
|
+
|
|
38
|
+
// [喵喵喵]: 读取已序列化的请求副本,确保 model/tier 来自所有 payload transform 完成后的实际正文。
|
|
39
|
+
const payload: unknown = await request.clone().json().catch(() => undefined);
|
|
40
|
+
if (!isObjectRecord(payload) || typeof payload.model !== "string" || !payload.model) return;
|
|
41
|
+
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}`);
|
|
43
|
+
}
|
package/configuration-lock.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// 跨 Pi 进程的配置 mutation 锁。只约束遵守本锁的插件写入,外部编辑器冲突另由内容签名检测。
|
|
2
2
|
|
|
3
3
|
import { hostname } from "node:os";
|
|
4
|
-
import {
|
|
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
7
|
import { t } from "./i18n.ts";
|
|
@@ -15,25 +15,16 @@ interface ConfigurationLockRecord {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
interface HeldConfigurationLock {
|
|
18
|
-
handle: FileHandle;
|
|
19
18
|
record: ConfigurationLockRecord;
|
|
19
|
+
ownerFileName: string;
|
|
20
|
+
recordSourcePath: string;
|
|
20
21
|
}
|
|
21
22
|
|
|
22
23
|
const LOCK_PATH = join(STATE_DIR, "config.lock");
|
|
23
|
-
const
|
|
24
|
+
const LOCK_WAIT_MS = 1_600;
|
|
25
|
+
const LOCK_RETRY_MS = 25;
|
|
24
26
|
const INVALID_LOCK_STALE_MS = 30_000;
|
|
25
|
-
const
|
|
26
|
-
// [喵喵喵]: 持有期上限需远大于任何合理单次事务耗时(本地文件 I/O),避免误抢活跃锁;仅作为 PID 复用死锁的兑底
|
|
27
|
-
const MAX_LOCK_HOLD_MS = 600_000;
|
|
28
|
-
|
|
29
|
-
function isLockExpired(record: ConfigurationLockRecord): boolean {
|
|
30
|
-
const started = Date.parse(record.startedAt);
|
|
31
|
-
return Number.isFinite(started) && Date.now() - started > MAX_LOCK_HOLD_MS;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function sleep(ms: number): Promise<void> {
|
|
35
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
36
|
-
}
|
|
27
|
+
const OWNER_FILE_PATTERN = /^owner-([a-z0-9-]+)\.json$/i;
|
|
37
28
|
|
|
38
29
|
function getErrorCode(error: unknown): string | undefined {
|
|
39
30
|
return error instanceof Error && "code" in error
|
|
@@ -41,6 +32,10 @@ function getErrorCode(error: unknown): string | undefined {
|
|
|
41
32
|
: undefined;
|
|
42
33
|
}
|
|
43
34
|
|
|
35
|
+
function isWindowsDirectoryBusy(error: unknown): boolean {
|
|
36
|
+
return process.platform === "win32" && ["EPERM", "EBUSY"].includes(getErrorCode(error) ?? "");
|
|
37
|
+
}
|
|
38
|
+
|
|
44
39
|
function parseLockRecord(source: string): ConfigurationLockRecord | undefined {
|
|
45
40
|
try {
|
|
46
41
|
const parsed = JSON.parse(source) as Partial<ConfigurationLockRecord>;
|
|
@@ -56,8 +51,7 @@ function parseLockRecord(source: string): ConfigurationLockRecord | undefined {
|
|
|
56
51
|
|
|
57
52
|
function isSameHostProcessRunning(record: ConfigurationLockRecord): boolean {
|
|
58
53
|
if (record.hostname !== hostname()) return true;
|
|
59
|
-
// [喵喵喵]:
|
|
60
|
-
if (isLockExpired(record)) return false;
|
|
54
|
+
// [喵喵喵]: 不按持有时长抢占活跃进程;暂停或慢磁盘不能使尚未结束的事务失去互斥。
|
|
61
55
|
try {
|
|
62
56
|
process.kill(record.pid, 0);
|
|
63
57
|
return true;
|
|
@@ -66,127 +60,136 @@ function isSameHostProcessRunning(record: ConfigurationLockRecord): boolean {
|
|
|
66
60
|
}
|
|
67
61
|
}
|
|
68
62
|
|
|
69
|
-
async function
|
|
70
|
-
let source: string;
|
|
63
|
+
async function removeEmptyDirectory(path: string): Promise<boolean> {
|
|
71
64
|
try {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
return getErrorCode(error) === "ENOENT";
|
|
75
|
-
}
|
|
76
|
-
const record = parseLockRecord(source);
|
|
77
|
-
if (record && isSameHostProcessRunning(record)) return false;
|
|
78
|
-
if (!record) {
|
|
79
|
-
try {
|
|
80
|
-
const lockStats = await stat(LOCK_PATH);
|
|
81
|
-
if (Date.now() - lockStats.mtimeMs < INVALID_LOCK_STALE_MS) return false;
|
|
82
|
-
} catch (error) {
|
|
83
|
-
return getErrorCode(error) === "ENOENT";
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// [喵喵喵]: 先原子重命名到临时路径再清理,防止 TOCTOU 竞态误删刚刚获取的新锁
|
|
88
|
-
const stalePath = `${LOCK_PATH}.stale.${randomUUID()}`;
|
|
89
|
-
try {
|
|
90
|
-
await rename(LOCK_PATH, stalePath);
|
|
65
|
+
await rmdir(path);
|
|
66
|
+
return true;
|
|
91
67
|
} catch (error) {
|
|
92
|
-
|
|
68
|
+
const code = getErrorCode(error);
|
|
69
|
+
if (code === "ENOENT") return true;
|
|
70
|
+
// [喵喵喵]: Windows 同路径删除竞争可能返回 EPERM/EBUSY;视为未回收,由获取流程有界等待,不能当作删除成功。
|
|
71
|
+
if (code === "ENOTEMPTY" || code === "EEXIST" || code === "ENOTDIR" || code === "EBUSY"
|
|
72
|
+
|| isWindowsDirectoryBusy(error)) return false;
|
|
73
|
+
throw error;
|
|
93
74
|
}
|
|
75
|
+
}
|
|
94
76
|
|
|
77
|
+
async function removeInactiveLock(): Promise<boolean> {
|
|
95
78
|
try {
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
79
|
+
const stats = await lstat(LOCK_PATH);
|
|
80
|
+
if (!stats.isDirectory()) {
|
|
81
|
+
if (!stats.isFile()) return false;
|
|
82
|
+
const record = parseLockRecord(await readFile(LOCK_PATH, "utf8"));
|
|
83
|
+
if (record ? isSameHostProcessRunning(record) : Date.now() - stats.mtimeMs < INVALID_LOCK_STALE_MS) return false;
|
|
84
|
+
// [喵喵喵]: 旧进程不认识目录协议;自动搬走旧文件仍会重现抢锁竞态,必须人工核对后处理。
|
|
85
|
+
throw new Error(t("检测到旧版失效配置锁;请确认没有旧版 Pi 正在保存,再手动移除:{path}", { path: LOCK_PATH }));
|
|
86
|
+
}
|
|
87
|
+
const entries = await readdir(LOCK_PATH);
|
|
88
|
+
if (entries.length === 0) {
|
|
89
|
+
return Date.now() - stats.mtimeMs >= INVALID_LOCK_STALE_MS && await removeEmptyDirectory(LOCK_PATH);
|
|
90
|
+
}
|
|
91
|
+
if (entries.length !== 1) return false;
|
|
92
|
+
const name = entries[0]!;
|
|
93
|
+
const match = OWNER_FILE_PATTERN.exec(name);
|
|
94
|
+
if (!match) return false;
|
|
95
|
+
const ownerPath = join(LOCK_PATH, name);
|
|
96
|
+
const record = parseLockRecord(await readFile(ownerPath, "utf8"));
|
|
97
|
+
if (record) {
|
|
98
|
+
if (record.token !== match[1] || isSameHostProcessRunning(record)) return false;
|
|
99
|
+
} else if (Date.now() - (await lstat(ownerPath)).mtimeMs < INVALID_LOCK_STALE_MS) {
|
|
101
100
|
return false;
|
|
102
101
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
return false;
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
// [喵喵喵]: 用 link 原子放回:目标已存在时以 EEXIST 失败,绝不覆盖他人在空窗期新建的锁
|
|
113
|
-
async function restoreMovedLock(stalePath: string): Promise<void> {
|
|
114
|
-
try {
|
|
115
|
-
await link(stalePath, LOCK_PATH);
|
|
102
|
+
// [喵喵喵]: 只删读到的唯一旧标记。若另一回收者已完成且新锁已发布,新 token 会使 rmdir 以非空失败。
|
|
103
|
+
await unlink(ownerPath).catch((error: unknown) => {
|
|
104
|
+
if (getErrorCode(error) !== "ENOENT") throw error;
|
|
105
|
+
});
|
|
106
|
+
return removeEmptyDirectory(LOCK_PATH);
|
|
116
107
|
} catch (error) {
|
|
117
|
-
if (getErrorCode(error) === "
|
|
108
|
+
if (getErrorCode(error) === "ENOENT") return true;
|
|
109
|
+
if (isWindowsDirectoryBusy(error)) return false;
|
|
118
110
|
throw error;
|
|
119
111
|
}
|
|
120
|
-
await unlink(stalePath).catch(() => undefined);
|
|
121
112
|
}
|
|
122
113
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
114
|
+
async function discardOwnClaim(ownerFileName: string): Promise<void> {
|
|
115
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
116
|
+
while (true) {
|
|
117
|
+
try {
|
|
118
|
+
await unlink(join(LOCK_PATH, ownerFileName));
|
|
119
|
+
break;
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (["ENOENT", "ENOTDIR"].includes(getErrorCode(error) ?? "")) break;
|
|
122
|
+
if (!isWindowsDirectoryBusy(error) || Date.now() >= deadline) throw error;
|
|
123
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
|
|
124
|
+
}
|
|
130
125
|
}
|
|
131
|
-
await
|
|
132
|
-
.filter((name) => name.startsWith(STALE_LOCK_NAME_PREFIX))
|
|
133
|
-
.map(async (name) => {
|
|
134
|
-
const stalePath = join(STATE_DIR, name);
|
|
135
|
-
try {
|
|
136
|
-
const stats = await stat(stalePath);
|
|
137
|
-
if (Date.now() - stats.mtimeMs < INVALID_LOCK_STALE_MS) return;
|
|
138
|
-
await unlink(stalePath);
|
|
139
|
-
} catch {
|
|
140
|
-
// 并发清理或文件已消失时静默跳过
|
|
141
|
-
}
|
|
142
|
-
}));
|
|
126
|
+
await removeEmptyDirectory(LOCK_PATH);
|
|
143
127
|
}
|
|
144
128
|
|
|
145
129
|
async function acquireConfigurationLock(): Promise<HeldConfigurationLock> {
|
|
146
130
|
await mkdir(STATE_DIR, { recursive: true });
|
|
147
|
-
await sweepAbandonedStaleLocks();
|
|
148
131
|
const record: ConfigurationLockRecord = {
|
|
149
|
-
token: randomUUID(),
|
|
150
|
-
pid: process.pid,
|
|
151
|
-
hostname: hostname(),
|
|
152
|
-
startedAt: new Date().toISOString(),
|
|
132
|
+
token: randomUUID(), pid: process.pid, hostname: hostname(), startedAt: new Date().toISOString(),
|
|
153
133
|
};
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
134
|
+
const ownerFileName = `owner-${record.token}.json`;
|
|
135
|
+
const recordSourcePath = join(STATE_DIR, `config.lock.source.${record.token}`);
|
|
136
|
+
await writeFile(recordSourcePath, `${JSON.stringify(record)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
137
|
+
let acquired = false;
|
|
138
|
+
try {
|
|
139
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
140
|
+
while (true) {
|
|
141
|
+
let created = false;
|
|
158
142
|
try {
|
|
159
|
-
await
|
|
160
|
-
|
|
161
|
-
return { handle, record };
|
|
143
|
+
await mkdir(LOCK_PATH, { mode: 0o700 });
|
|
144
|
+
created = true;
|
|
162
145
|
} catch (error) {
|
|
163
|
-
|
|
164
|
-
await unlink(LOCK_PATH).catch(() => undefined);
|
|
165
|
-
throw error;
|
|
146
|
+
if (getErrorCode(error) !== "EEXIST" && !isWindowsDirectoryBusy(error)) throw error;
|
|
166
147
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
148
|
+
if (created) {
|
|
149
|
+
try {
|
|
150
|
+
// [喵喵喵]: 完整记录以硬链接原子发布后不再修改,避免半写记录在暂停后被判为损坏旧锁、却又恢复为活跃锁。
|
|
151
|
+
await link(recordSourcePath, join(LOCK_PATH, ownerFileName));
|
|
152
|
+
// [喵喵喵]: 空目录被回收后,旧初始化者可能把标记发布到新目录;只有独占自身标记才允许进入事务。
|
|
153
|
+
const entries = await readdir(LOCK_PATH);
|
|
154
|
+
if (entries.length === 1 && entries[0] === ownerFileName) {
|
|
155
|
+
acquired = true;
|
|
156
|
+
return { record, ownerFileName, recordSourcePath };
|
|
157
|
+
}
|
|
158
|
+
} catch (error) {
|
|
159
|
+
// [喵喵喵]: 删除挂起在 Windows 上也会令后续 mkdir/link/readdir 返回忙;只有完成发布并确认独占才算成功。
|
|
160
|
+
if (!["ENOENT", "ENOTDIR"].includes(getErrorCode(error) ?? "") && !isWindowsDirectoryBusy(error)) {
|
|
161
|
+
await discardOwnClaim(ownerFileName);
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
await discardOwnClaim(ownerFileName);
|
|
166
|
+
} else if (await removeInactiveLock()) {
|
|
167
|
+
if (Date.now() < deadline) continue;
|
|
168
|
+
}
|
|
169
|
+
if (Date.now() >= deadline) break;
|
|
170
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
|
|
172
171
|
}
|
|
172
|
+
throw new Error(t("另一个 Pi 进程正在保存模型配置;无法在限定时间内获取锁:{path}", { path: LOCK_PATH }));
|
|
173
|
+
} finally {
|
|
174
|
+
if (!acquired) await unlink(recordSourcePath);
|
|
173
175
|
}
|
|
174
|
-
throw new Error(t("另一个 Pi 进程正在保存模型配置;无法在限定时间内获取锁:{path}", { path: LOCK_PATH }));
|
|
175
176
|
}
|
|
176
177
|
|
|
177
178
|
async function releaseConfigurationLock(lock: HeldConfigurationLock): Promise<void> {
|
|
178
|
-
await lock.handle.close();
|
|
179
|
-
let current: ConfigurationLockRecord | undefined;
|
|
180
179
|
try {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
180
|
+
const ownerPath = join(LOCK_PATH, lock.ownerFileName);
|
|
181
|
+
const current = await readFile(ownerPath, "utf8").then(parseLockRecord).catch((error: unknown) => {
|
|
182
|
+
if (getErrorCode(error) !== "ENOENT") throw error;
|
|
183
|
+
return undefined;
|
|
184
|
+
});
|
|
185
|
+
if (current?.token !== lock.record.token) {
|
|
186
|
+
throw new Error(t("配置锁所有权在释放前发生变化,已保留锁文件供检查:{path}", { path: LOCK_PATH }));
|
|
187
|
+
}
|
|
188
|
+
await unlink(ownerPath);
|
|
189
|
+
await removeEmptyDirectory(LOCK_PATH);
|
|
190
|
+
} finally {
|
|
191
|
+
await unlink(lock.recordSourcePath);
|
|
188
192
|
}
|
|
189
|
-
await unlink(LOCK_PATH);
|
|
190
193
|
}
|
|
191
194
|
|
|
192
195
|
export async function withConfigurationLock<T>(operation: () => Promise<T>): Promise<T> {
|
|
@@ -232,7 +232,14 @@ async function persistConfigurationInsideLock(
|
|
|
232
232
|
const migratedSource = metadataSnapshot.metadata.version < 5
|
|
233
233
|
? migrateManagedBaseUrls(latest, sourceWithLegacyProviders)
|
|
234
234
|
: sourceWithLegacyProviders;
|
|
235
|
+
const existingProviderIds = new Set(Object.keys(latest.providers));
|
|
235
236
|
const change = prepare(latest);
|
|
237
|
+
// [喵喵喵]: 原生扩展可只保存覆盖项而不列 models;目录过滤掉的节点仍占用 ID,不允许新建时覆盖。
|
|
238
|
+
for (const providerId of change.changedProviderIds) {
|
|
239
|
+
if (!existingProviderIds.has(providerId) && Object.hasOwn(modelsSnapshot.document.providers, providerId)) {
|
|
240
|
+
throw new Error(t("models.json 中已存在接入:{providerId}", { providerId }));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
236
243
|
const nextModels = mutateModels(migratedSource, change);
|
|
237
244
|
const modelsTarget = nextModels === modelsSnapshot.document && modelsSnapshot.source !== undefined
|
|
238
245
|
? modelsSnapshot.source
|
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
6
6
|
import { persistManagedConfiguration } from "./configuration-persistence.ts";
|
|
7
7
|
import { t } from "./i18n.ts";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { formatUnknownError } from "./common.ts";
|
|
9
|
+
import { reconcileProvider } from "./provider-registrar.ts";
|
|
10
|
+
import { deleteRequestHeaderProfileFromDocument, upsertRequestHeaderProfileInDocument, validateRequestHeaderProfileDraft } from "./state-document.ts";
|
|
10
11
|
import type { RequestHeaderProfileDraft, StateDocument, StoredProvider } from "./types.ts";
|
|
11
12
|
|
|
12
13
|
function providerReferencesProfile(provider: StoredProvider, profileId: string): boolean {
|
|
@@ -24,6 +25,20 @@ function findProfileProviderIds(
|
|
|
24
25
|
.map(([providerId]) => providerId);
|
|
25
26
|
}
|
|
26
27
|
|
|
28
|
+
async function refreshProfileProviders(pi: ExtensionAPI, document: StateDocument, providerIds: string[]): Promise<string[]> {
|
|
29
|
+
const warnings: string[] = [];
|
|
30
|
+
for (const providerId of providerIds) {
|
|
31
|
+
const provider = document.providers[providerId];
|
|
32
|
+
if (!provider) continue;
|
|
33
|
+
try {
|
|
34
|
+
await reconcileProvider(pi, providerId, provider, document.requestHeaderProfiles, document.clientHeaderCaptures);
|
|
35
|
+
} catch (error) {
|
|
36
|
+
warnings.push(`${providerId}: ${formatUnknownError(error)}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return warnings;
|
|
40
|
+
}
|
|
41
|
+
|
|
27
42
|
function notifyHeaderProfileRefresh(
|
|
28
43
|
ctx: ExtensionCommandContext,
|
|
29
44
|
successMessage: string,
|
|
@@ -44,12 +59,21 @@ export async function saveRequestHeaderProfileConfiguration(
|
|
|
44
59
|
oldProfileId: string | undefined,
|
|
45
60
|
): Promise<void> {
|
|
46
61
|
const profileId = draft.profileId.trim();
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
62
|
+
let affectedProviderIds: string[] = [];
|
|
63
|
+
const nextState = await persistManagedConfiguration(ctx, (latest) => {
|
|
64
|
+
if (oldProfileId && !latest.requestHeaderProfiles[oldProfileId]) {
|
|
65
|
+
throw new Error(t("请求头不存在:{profileId}", { profileId: oldProfileId }));
|
|
66
|
+
}
|
|
67
|
+
const errors = validateRequestHeaderProfileDraft(draft, latest, oldProfileId);
|
|
68
|
+
if (errors.length > 0) throw new Error(errors.join("\n"));
|
|
69
|
+
affectedProviderIds = findProfileProviderIds(latest, [profileId, ...(oldProfileId ? [oldProfileId] : [])]);
|
|
70
|
+
return {
|
|
71
|
+
document: upsertRequestHeaderProfileInDocument(latest, oldProfileId, draft),
|
|
72
|
+
changedProviderIds: affectedProviderIds,
|
|
73
|
+
removedProviderIds: [],
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
const warnings = await refreshProfileProviders(pi, nextState, affectedProviderIds);
|
|
53
77
|
notifyHeaderProfileRefresh(ctx, t("已保存请求头 {profileId}", { profileId: draft.profileId.trim() }), warnings);
|
|
54
78
|
}
|
|
55
79
|
|
|
@@ -59,11 +83,15 @@ export async function deleteRequestHeaderProfileConfiguration(
|
|
|
59
83
|
_state: StateDocument,
|
|
60
84
|
profileId: string,
|
|
61
85
|
): Promise<void> {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
86
|
+
let affectedProviderIds: string[] = [];
|
|
87
|
+
const nextState = await persistManagedConfiguration(ctx, (latest) => {
|
|
88
|
+
affectedProviderIds = findProfileProviderIds(latest, [profileId]);
|
|
89
|
+
return {
|
|
90
|
+
document: deleteRequestHeaderProfileFromDocument(latest, profileId),
|
|
91
|
+
changedProviderIds: affectedProviderIds,
|
|
92
|
+
removedProviderIds: [],
|
|
93
|
+
};
|
|
94
|
+
});
|
|
95
|
+
const warnings = await refreshProfileProviders(pi, nextState, affectedProviderIds);
|
|
68
96
|
notifyHeaderProfileRefresh(ctx, t("已删除请求头 {profileId}", { profileId }), warnings);
|
|
69
97
|
}
|
package/i18n.ts
CHANGED
|
@@ -6,6 +6,7 @@ export const DEFAULT_UI_LANGUAGE: UiLanguage = "zh-CN";
|
|
|
6
6
|
|
|
7
7
|
const ENGLISH_MESSAGES = {
|
|
8
8
|
"Base URL 必须使用 http 或 https": "Base URL must use http or https",
|
|
9
|
+
"Base URL 格式错误:{error}": "Invalid Base URL: {error}",
|
|
9
10
|
"Base URL 不支持查询参数(?)或片段(#);请填写 API 根地址": "Base URL cannot contain query parameters (?) or fragments (#); enter the API root URL",
|
|
10
11
|
"Base URL 不支持内嵌认证;请使用 API key 或请求头配置": "Base URL cannot contain credentials; use the API key or header configuration",
|
|
11
12
|
"请求模型不属于当前接入配置:{modelId}": "Request model is not part of the current provider configuration: {modelId}",
|
|
@@ -107,9 +108,9 @@ const ENGLISH_MESSAGES = {
|
|
|
107
108
|
"未知 Responses 流结束模式:{value}": "Unknown Responses stream completion mode: {value}",
|
|
108
109
|
"跨资源自动恢复": "State recovery",
|
|
109
110
|
"关闭 — 不检测或自动恢复跨资源状态错误": "Off — do not detect or recover cross-resource state errors",
|
|
110
|
-
"开启 —
|
|
111
|
-
"
|
|
112
|
-
"
|
|
111
|
+
"开启 — 仅在指定错误后剥离旧 item ID 并重试一次,保留思维链": "On — strip old item IDs and retry once only for matching errors; preserve reasoning",
|
|
112
|
+
"跨资源自动恢复已开启:仅在指定错误后剥离旧 item ID 并重试一次;完整保留思维链,每次提示结果。": "State recovery is on: strip old item IDs and retry matching errors once, preserve reasoning in full, and report each result.",
|
|
113
|
+
"跨资源自动恢复已关闭:不检测或自动处理资源归属、item ID 与加密状态错误。": "State recovery is off: resource ownership, item ID, and encrypted state errors are not detected or recovered.",
|
|
113
114
|
"接入 ID 必填,且不能与已有或 pi 内置接入重复": "Provider ID is required and must not duplicate an existing or built-in Pi provider",
|
|
114
115
|
"Ctrl+S 保存并同步 models.json;不切换当前会话模型": "Ctrl+S saves and syncs models.json without switching the current session model",
|
|
115
116
|
"选择 API 协议": "Select API protocol",
|
|
@@ -259,6 +260,7 @@ const ENGLISH_MESSAGES = {
|
|
|
259
260
|
"写入 {targetPath} 失败;完整内容已保留在临时文件:{tempPath}:{error}": "Failed to write {targetPath}; the complete content remains in temporary file {tempPath}: {error}",
|
|
260
261
|
"另一个 Pi 进程正在保存模型配置;无法在限定时间内获取锁:{path}": "Another Pi process is saving the model configuration; the lock could not be acquired in time: {path}",
|
|
261
262
|
"配置锁所有权在释放前发生变化,已保留锁文件供检查:{path}": "The configuration lock ownership changed before release; the lock file was retained for inspection: {path}",
|
|
263
|
+
"检测到旧版失效配置锁;请确认没有旧版 Pi 正在保存,再手动移除:{path}": "An inactive legacy configuration lock was detected; confirm that no older Pi process is saving before removing it manually: {path}",
|
|
262
264
|
"{path} 必须是对象": "{path} must be an object",
|
|
263
265
|
"{path}.oldSource 必须是字符串或 null": "{path}.oldSource must be a string or null",
|
|
264
266
|
"{path} 缺少有效内容或签名": "{path} is missing valid content or a signature",
|
|
@@ -280,6 +282,8 @@ const ENGLISH_MESSAGES = {
|
|
|
280
282
|
"代理地址无效:{url}": "Invalid proxy URL: {url}",
|
|
281
283
|
"代理地址目前只支持 http:// 或 https:// 代理": "Only http:// or https:// proxies are currently supported",
|
|
282
284
|
"代理请求失败:{code}": "Proxy request failed: {code}",
|
|
285
|
+
"代理安全拦截:上游返回了重定向至 {target},已拒绝跟随": "Proxy security block: upstream redirected to {target}; following it was refused",
|
|
286
|
+
"拒绝转发:目标 Origin {actual} 与注册路由 {expected} 不一致": "Forwarding refused: target origin {actual} does not match the registered route {expected}",
|
|
283
287
|
"无错误消息": "no error message",
|
|
284
288
|
"未知代理错误": "Unknown proxy error",
|
|
285
289
|
"不支持的上游协议:{protocol}": "Unsupported upstream protocol: {protocol}",
|
|
@@ -334,8 +338,8 @@ const ENGLISH_MESSAGES = {
|
|
|
334
338
|
"Fast mode 状态读取失败,本次请求未注入 service_tier": "Failed to read Fast mode state; service_tier was not injected for this request",
|
|
335
339
|
"跨资源恢复状态处理失败,本次请求未执行自动恢复": "Failed to process state recovery; automatic recovery was not applied to this request",
|
|
336
340
|
"跨资源自动恢复准备失败,未自动重试": "Failed to prepare cross-resource recovery; no automatic retry was made",
|
|
337
|
-
"{model}
|
|
338
|
-
"{model}
|
|
341
|
+
"{model}:将剥离本次失败历史的 item ID,保留思维链并自动重试一次。": "{model}: stripping item IDs from the failed history, preserving reasoning, and retrying once.",
|
|
342
|
+
"{model}:跨资源自动恢复成功;思维链完整保留,后续新 item ID 正常保留。": "{model}: cross-resource recovery succeeded; reasoning remains intact and new item IDs will be preserved.",
|
|
339
343
|
"{model}:跨资源自动恢复重试失败,已停止自动重试。": "{model}: cross-resource recovery retry failed; automatic retries have stopped.",
|
|
340
344
|
"{model}:跨资源自动恢复已取消,未继续重试。": "{model}: cross-resource recovery was cancelled; no further retry was made.",
|
|
341
345
|
"{reason},已切换到 {fullId}": "{reason}; switched to {fullId}",
|
|
@@ -435,7 +439,7 @@ function interpolate(template: string, values: TranslationValues): string {
|
|
|
435
439
|
}
|
|
436
440
|
|
|
437
441
|
export function t(key: MessageKey, values: TranslationValues = {}): string {
|
|
438
|
-
const template = currentLanguage === "en" ? ENGLISH_MESSAGES[key] : key;
|
|
442
|
+
const template = currentLanguage === "en" ? ENGLISH_MESSAGES[key] ?? key : key;
|
|
439
443
|
return interpolate(template, values);
|
|
440
444
|
}
|
|
441
445
|
|
package/local-proxy-service.ts
CHANGED
|
@@ -95,20 +95,19 @@ function ensureSupportedProxyProtocol(proxy: URL): void {
|
|
|
95
95
|
|
|
96
96
|
function pipeResponse(upstreamResponse: IncomingMessage, response: ServerResponse, route: ProviderProxyRoute): void {
|
|
97
97
|
const statusCode = upstreamResponse.statusCode ?? 502;
|
|
98
|
-
// [喵喵喵]:
|
|
98
|
+
// [喵喵喵]: 同源绝对 Location 也可能让 SDK 离开本地代理直连上游;所有带 Location 的重定向均在代理层拒绝。
|
|
99
99
|
if (statusCode >= 300 && statusCode < 400 && upstreamResponse.headers.location) {
|
|
100
|
+
let target = "[invalid Location]";
|
|
100
101
|
try {
|
|
101
|
-
|
|
102
|
-
if (target.origin !== route.upstreamOrigin) {
|
|
103
|
-
response.writeHead(502, { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" });
|
|
104
|
-
response.end(t("代理安全拦截:上游返回了跨域重定向至 {target},已拒绝跟随", { target: target.origin }));
|
|
105
|
-
// [喵喵喵]: 拦截后主动销毁上游响应,避免未消费的 body 占用 socket 直到超时
|
|
106
|
-
upstreamResponse.destroy();
|
|
107
|
-
return;
|
|
108
|
-
}
|
|
102
|
+
target = new URL(upstreamResponse.headers.location, route.upstreamOrigin).origin;
|
|
109
103
|
} catch {
|
|
110
|
-
// 非法
|
|
104
|
+
// [喵喵喵]: 非法 Location 同样拒绝,不把未知跳转交给客户端。
|
|
111
105
|
}
|
|
106
|
+
const message = t("代理安全拦截:上游返回了重定向至 {target},已拒绝跟随", { target });
|
|
107
|
+
response.writeHead(502, { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" });
|
|
108
|
+
response.end(message);
|
|
109
|
+
upstreamResponse.destroy();
|
|
110
|
+
return;
|
|
112
111
|
}
|
|
113
112
|
const headers = stripHopByHopHeaders(upstreamResponse.headers);
|
|
114
113
|
response.writeHead(statusCode, upstreamResponse.statusMessage, headers);
|
package/model-mutations.ts
CHANGED
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
} from "./models-json-sync.ts";
|
|
24
24
|
import { reconcileProvider, unregisterManagedProvider } from "./provider-registrar.ts";
|
|
25
25
|
import { withModelRescue } from "./rescue.ts";
|
|
26
|
-
import { deleteModelFromDocument, deleteProviderFromDocument, getModelFullId, upsertModelInDocument, upsertProviderInDocument } from "./state-document.ts";
|
|
26
|
+
import { deleteModelFromDocument, deleteProviderFromDocument, getModelFullId, upsertModelInDocument, upsertProviderInDocument, validateModelDraft, validateProviderDraft } from "./state-document.ts";
|
|
27
27
|
import type { StateDocument, StoredProvider } from "./types.ts";
|
|
28
28
|
import type { createModelDraftForStoredProvider, createProviderDraft } from "./state-document.ts";
|
|
29
29
|
|
|
@@ -87,6 +87,12 @@ export async function saveProviderConfiguration(
|
|
|
87
87
|
await assertProviderIsEditable(draft.providerId);
|
|
88
88
|
if (oldProviderId) await assertProviderIsEditable(oldProviderId);
|
|
89
89
|
const prepare = (latest: StateDocument) => {
|
|
90
|
+
if (oldProviderId && !latest.providers[oldProviderId]) {
|
|
91
|
+
throw new Error(t("接入配置已不存在:{providerId}", { providerId: oldProviderId }));
|
|
92
|
+
}
|
|
93
|
+
// [喵喵喵]: UI 校验之后可能有其它进程保存;必须在锁内针对最新状态重验创建和重命名前提。
|
|
94
|
+
const errors = validateProviderDraft(draft, latest, new Set(), oldProviderId);
|
|
95
|
+
if (errors.length > 0) throw new Error(errors.join("\n"));
|
|
90
96
|
const document = upsertProviderInDocument(latest, oldProviderId, draft);
|
|
91
97
|
return { document, changedProviderIds: [draft.providerId], removedProviderIds: [] };
|
|
92
98
|
};
|
|
@@ -139,6 +145,11 @@ export async function saveModelConfiguration(
|
|
|
139
145
|
await assertProviderIsEditable(draft.providerId);
|
|
140
146
|
const newModelId = draft.modelId.trim();
|
|
141
147
|
const prepare = (latest: StateDocument) => {
|
|
148
|
+
if (replacedModelId && !latest.providers[draft.providerId]?.models.some((model) => model.id === replacedModelId)) {
|
|
149
|
+
throw new Error(t("模型不存在:{fullId}", { fullId: getModelFullId(draft.providerId, replacedModelId) }));
|
|
150
|
+
}
|
|
151
|
+
const errors = validateModelDraft(draft, latest, replacedModelId);
|
|
152
|
+
if (errors.length > 0) throw new Error(errors.join("\n"));
|
|
142
153
|
const document = upsertModelInDocument(latest, draft, { replacedModelId });
|
|
143
154
|
return { document, changedProviderIds: [draft.providerId], removedProviderIds: [] };
|
|
144
155
|
};
|
|
@@ -175,7 +186,11 @@ export async function saveNewProviderWithModelConfiguration(
|
|
|
175
186
|
): Promise<void> {
|
|
176
187
|
await assertProviderIsEditable(providerDraft.providerId);
|
|
177
188
|
const prepare = (latest: StateDocument) => {
|
|
189
|
+
const providerErrors = validateProviderDraft(providerDraft, latest, new Set());
|
|
190
|
+
if (providerErrors.length > 0) throw new Error(providerErrors.join("\n"));
|
|
178
191
|
const withProvider = upsertProviderInDocument(latest, undefined, providerDraft);
|
|
192
|
+
const modelErrors = validateModelDraft(modelDraft, withProvider);
|
|
193
|
+
if (modelErrors.length > 0) throw new Error(modelErrors.join("\n"));
|
|
179
194
|
const document = upsertModelInDocument(withProvider, modelDraft);
|
|
180
195
|
return { document, changedProviderIds: [providerDraft.providerId], removedProviderIds: [] };
|
|
181
196
|
};
|
package/models-json-manager.ts
CHANGED
|
@@ -98,7 +98,11 @@ function createEmpty(): ModelsJsonDocument {
|
|
|
98
98
|
function parseModelsJson(source: string): ModelsJsonDocument {
|
|
99
99
|
const parsed = JSON.parse(stripJsonNoise(source));
|
|
100
100
|
if (!isObjectRecord(parsed)) throw new Error(t("models.json 根节点必须是对象"));
|
|
101
|
-
|
|
101
|
+
// [喵喵喵]: 字段缺失可以初始化;已有字段类型损坏必须拒写,不能把原始内容当空目录覆盖。
|
|
102
|
+
if (Object.hasOwn(parsed, "providers") && !isObjectRecord(parsed.providers)) {
|
|
103
|
+
throw new Error(t("{path} 必须是对象", { path: "models.json.providers" }));
|
|
104
|
+
}
|
|
105
|
+
const providers = parsed.providers ?? {};
|
|
102
106
|
return { ...parsed, providers: providers as Record<string, ModelsJsonProviderEntry> };
|
|
103
107
|
}
|
|
104
108
|
|