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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// openai-responses-recovery.ts
|
|
2
2
|
//
|
|
3
|
-
// Responses
|
|
3
|
+
// Responses 跨资源状态恢复:仅在指定错误后剥离失败历史的 item ID,完整保留推理内容。
|
|
4
4
|
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
6
|
import type {
|
|
@@ -57,19 +57,13 @@ function isReplayState(value: unknown): value is ReplayState {
|
|
|
57
57
|
|
|
58
58
|
function collectState(payload: Record<string, unknown>, scope: string): ReplayState {
|
|
59
59
|
const itemIds = new Set<string>();
|
|
60
|
-
const encryptedHashes = new Set<string>();
|
|
61
60
|
for (const item of payload.input as unknown[]) {
|
|
62
61
|
if (!isObjectRecord(item)) continue;
|
|
63
62
|
// [喵喵喵]: msg_pi_* 是 Pi 本地生成的占位 ID;压缩后可能复用,不能当成上游资源 ID 隔离。
|
|
64
63
|
if (typeof item.id === "string" && !item.id.startsWith("msg_pi_")) itemIds.add(item.id);
|
|
65
|
-
for (const [key, value] of Object.entries(item)) {
|
|
66
|
-
if (key.startsWith("encrypted") && value !== undefined) encryptedHashes.add(digest([key, value]));
|
|
67
|
-
}
|
|
68
64
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
previousResponseIds: typeof payload.previous_response_id === "string" ? [payload.previous_response_id] : [],
|
|
72
|
-
};
|
|
65
|
+
// [喵喵喵]: 延用既有分支记录格式,但不再记录或清理密文哈希及 response 引用。
|
|
66
|
+
return { version: 1, scope, itemIds: [...itemIds], encryptedHashes: [], previousResponseIds: [] };
|
|
73
67
|
}
|
|
74
68
|
|
|
75
69
|
function canReplayItem(item: unknown): boolean {
|
|
@@ -87,58 +81,36 @@ function canReplayItem(item: unknown): boolean {
|
|
|
87
81
|
}
|
|
88
82
|
}
|
|
89
83
|
|
|
90
|
-
function
|
|
84
|
+
function stripQuarantinedItemIds(
|
|
91
85
|
payload: Record<string, unknown>,
|
|
92
86
|
ctx: ExtensionContext,
|
|
93
87
|
scope: string,
|
|
94
88
|
): Record<string, unknown> | undefined {
|
|
95
89
|
const itemIds = new Set<string>();
|
|
96
|
-
|
|
97
|
-
const previousResponseIds = new Set<string>();
|
|
98
|
-
// [喵喵喵]: 只读当前分支的恢复记录,重载后继续隔离旧状态,不污染其它分支或其它模型。
|
|
90
|
+
// [喵喵喵]: 仅剥离当前分支已报错的历史 ID;重载后继续生效,其它分支及后续新 ID 不受影响。
|
|
99
91
|
for (const entry of ctx.sessionManager.getBranch()) {
|
|
100
92
|
if (entry.type !== "custom" || entry.customType !== RECOVERY_ENTRY_TYPE
|
|
101
93
|
|| !isReplayState(entry.data) || entry.data.scope !== scope) continue;
|
|
102
94
|
for (const id of entry.data.itemIds) itemIds.add(id);
|
|
103
|
-
for (const hash of entry.data.encryptedHashes) encryptedHashes.add(hash);
|
|
104
|
-
for (const id of entry.data.previousResponseIds) previousResponseIds.add(id);
|
|
105
95
|
}
|
|
106
|
-
if (!itemIds.size
|
|
96
|
+
if (!itemIds.size) return undefined;
|
|
107
97
|
|
|
108
98
|
let changed = false;
|
|
109
|
-
const input = (payload.input as unknown[]).
|
|
110
|
-
if (!isObjectRecord(item)) return
|
|
111
|
-
|
|
112
|
-
const quarantined = (typeof item.id === "string" && itemIds.has(item.id))
|
|
113
|
-
|| encryptedKeys.some((key) => item[key] !== undefined && encryptedHashes.has(digest([key, item[key]])));
|
|
114
|
-
if (!quarantined) return [item];
|
|
115
|
-
changed = true;
|
|
116
|
-
if (item.type === "reasoning") {
|
|
117
|
-
// [喵喵喵]: 失效密文不能伪造新的 reasoning id;按 Pi 的摘要优先规则回放可读文本,不生成缺字段的 reasoning。
|
|
118
|
-
const text = [item.summary, item.content].map((blocks) => Array.isArray(blocks)
|
|
119
|
-
? blocks.filter(isObjectRecord).map((block) => typeof block.text === "string" ? block.text : "").filter(Boolean).join("\n\n")
|
|
120
|
-
: "").find(Boolean);
|
|
121
|
-
return text ? [{ type: "message", role: "assistant", content: text }] : [];
|
|
122
|
-
}
|
|
99
|
+
const input = (payload.input as unknown[]).map((item) => {
|
|
100
|
+
if (!isObjectRecord(item) || typeof item.id !== "string" || !itemIds.has(item.id)) return item;
|
|
101
|
+
// [喵喵喵]: reasoning、message 和 function_call 的旧 ID 必须一起剥离,避免残留关联校验;密文与 call_id 原样保留。
|
|
123
102
|
const next = { ...item };
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
next.id = `msg_pi_recovery_${digest(item).slice(0, 32)}`;
|
|
128
|
-
} else {
|
|
129
|
-
delete next.id;
|
|
130
|
-
}
|
|
131
|
-
return [next];
|
|
103
|
+
delete next.id;
|
|
104
|
+
changed = true;
|
|
105
|
+
return next;
|
|
132
106
|
});
|
|
133
|
-
|
|
134
|
-
if (!changed && !dropPrevious) return undefined;
|
|
135
|
-
const next: Record<string, unknown> = { ...payload, input };
|
|
136
|
-
if (dropPrevious) delete next.previous_response_id;
|
|
137
|
-
return next;
|
|
107
|
+
return changed ? { ...payload, input } : undefined;
|
|
138
108
|
}
|
|
139
109
|
|
|
140
110
|
function isRecoverableError(message: string): boolean {
|
|
141
111
|
return /created under a different Azure OpenAI resource/i.test(message)
|
|
112
|
+
|| /\bItem with id ['"][^'"\r\n]+['"] (?:was )?not found\b/i.test(message)
|
|
113
|
+
|| /\bwas provided without its required ['"]reasoning['"] item\b/i.test(message)
|
|
142
114
|
|| /\binvalid_encrypted_content\b/i.test(message)
|
|
143
115
|
|| /\bencrypted content(?:\s+\S+)?(?:\s+for item\s+\S+)?\s+could not be (?:verified|decrypted)\b/i.test(message);
|
|
144
116
|
}
|
|
@@ -162,11 +134,12 @@ export function createOpenAIResponsesRecovery() {
|
|
|
162
134
|
transform(payload: unknown, ctx: ExtensionContext, state: StateDocument): unknown | undefined {
|
|
163
135
|
lastRequest = undefined;
|
|
164
136
|
const model = enabledModel(ctx, state);
|
|
165
|
-
if (!model || !isObjectRecord(payload) || payload.model !== model.id ||
|
|
166
|
-
|
|
137
|
+
if (!model || !isObjectRecord(payload) || payload.model !== model.id || payload.store === true
|
|
138
|
+
|| !Array.isArray(payload.input)) return undefined;
|
|
139
|
+
// [喵喵喵]: 服务端引用、压缩项及未知资源项的 ID 可能不可省略,不对这些请求自动剥离重放。
|
|
167
140
|
if (!payload.input.every(canReplayItem)) return undefined;
|
|
168
141
|
const scope = scopeFor(model);
|
|
169
|
-
const transformed =
|
|
142
|
+
const transformed = stripQuarantinedItemIds(payload, ctx, scope);
|
|
170
143
|
lastRequest = {
|
|
171
144
|
state: collectState(transformed ?? payload, scope), provider: model.provider,
|
|
172
145
|
model: model.id, sessionId: ctx.sessionManager.getSessionId(),
|
|
@@ -185,15 +158,14 @@ export function createOpenAIResponsesRecovery() {
|
|
|
185
158
|
if (!failedEntry || !message || message.role !== "assistant" || message.stopReason !== "error"
|
|
186
159
|
|| message.provider !== snapshot.provider || message.model !== snapshot.model || message.api !== "openai-responses"
|
|
187
160
|
|| message.content.length > 0 || !isRecoverableError(message.errorMessage ?? "")) return undefined;
|
|
188
|
-
|
|
189
|
-
if (!itemIds.length && !encryptedHashes.length && !previousResponseIds.length) return undefined;
|
|
161
|
+
if (!snapshot.state.itemIds.length) return undefined;
|
|
190
162
|
|
|
191
|
-
// [喵喵喵]:
|
|
163
|
+
// [喵喵喵]: 只记录失败请求携带的旧 item ID;无法定位具体失效项时成组剥离,不触碰推理密文、正文和 call_id。
|
|
192
164
|
// [喵喵喵]: 原始历史保留,仅追加分支状态与失败回复的上下文省略;同一次用户运行最多恢复一次。
|
|
193
165
|
// [喵喵喵]: 错误 assistant 尚在上下文时 canContinue 为 false;省略它后由宿主重新校验,不能提前据此拒绝恢复。
|
|
194
166
|
attempted = true;
|
|
195
167
|
pendingRecovery = snapshot;
|
|
196
|
-
notify(ctx, "{model}
|
|
168
|
+
notify(ctx, "{model}:将剥离本次失败历史的 item ID,保留思维链并自动重试一次。", snapshot);
|
|
197
169
|
return {
|
|
198
170
|
entries: [
|
|
199
171
|
// [喵喵喵]: 边界 entries 是整体替换,必须保留前序扩展的提案后再追加恢复记录。
|
|
@@ -216,7 +188,7 @@ export function createOpenAIResponsesRecovery() {
|
|
|
216
188
|
} else if (message.stopReason === "aborted") {
|
|
217
189
|
notify(ctx, "{model}:跨资源自动恢复已取消,未继续重试。", snapshot, true);
|
|
218
190
|
} else {
|
|
219
|
-
notify(ctx, "{model}
|
|
191
|
+
notify(ctx, "{model}:跨资源自动恢复成功;思维链完整保留,后续新 item ID 正常保留。", snapshot);
|
|
220
192
|
}
|
|
221
193
|
},
|
|
222
194
|
|
package/package.json
CHANGED
|
@@ -1,86 +1,87 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "pi-model-manager",
|
|
3
|
-
"version": "0.4.
|
|
4
|
-
"description": "A TUI model and provider manager for Pi with native models.json persistence, request-header profiles, proxy routing, and protocol compatibility.",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "./index.ts",
|
|
7
|
-
"scripts": {
|
|
8
|
-
"test": "node --experimental-strip-types --import ./tests/register-test-loader.mjs --test --test-reporter=spec tests/*.test.ts",
|
|
9
|
-
"test:runtime": "node --experimental-strip-types --import ./tests/register-runtime-loader.mjs --test --test-reporter=spec tests/*-wire.test.ts"
|
|
10
|
-
},
|
|
11
|
-
"files": [
|
|
12
|
-
"NOTICE",
|
|
13
|
-
"README.en.md",
|
|
14
|
-
"index.ts",
|
|
15
|
-
"i18n.ts",
|
|
16
|
-
"ui-language-settings.ts",
|
|
17
|
-
"state-store.ts",
|
|
18
|
-
"state-metadata-store.ts",
|
|
19
|
-
"state-cache.ts",
|
|
20
|
-
"state-document.ts",
|
|
21
|
-
"openai-responses-recovery.ts",
|
|
22
|
-
"openai-responses-payload.ts",
|
|
23
|
-
"openai-service-tier.ts",
|
|
24
|
-
"claude-code-compat.ts",
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
"models-json-
|
|
28
|
-
"
|
|
29
|
-
"provider-
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"configuration-
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
"pi-
|
|
52
|
-
"pi",
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
"
|
|
62
|
-
"
|
|
63
|
-
|
|
64
|
-
"
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
"
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
"@earendil-works/pi-
|
|
78
|
-
"@earendil-works/pi-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
"
|
|
83
|
-
"
|
|
84
|
-
"
|
|
85
|
-
|
|
86
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-model-manager",
|
|
3
|
+
"version": "0.4.5",
|
|
4
|
+
"description": "A TUI model and provider manager for Pi with native models.json persistence, request-header profiles, proxy routing, and protocol compatibility.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./index.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "node --experimental-strip-types --import ./tests/register-test-loader.mjs --test --test-reporter=spec tests/*.test.ts",
|
|
9
|
+
"test:runtime": "node --experimental-strip-types --import ./tests/register-runtime-loader.mjs --test --test-reporter=spec tests/*-wire.test.ts"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"NOTICE",
|
|
13
|
+
"README.en.md",
|
|
14
|
+
"index.ts",
|
|
15
|
+
"i18n.ts",
|
|
16
|
+
"ui-language-settings.ts",
|
|
17
|
+
"state-store.ts",
|
|
18
|
+
"state-metadata-store.ts",
|
|
19
|
+
"state-cache.ts",
|
|
20
|
+
"state-document.ts",
|
|
21
|
+
"openai-responses-recovery.ts",
|
|
22
|
+
"openai-responses-payload.ts",
|
|
23
|
+
"openai-service-tier.ts",
|
|
24
|
+
"claude-code-compat.ts",
|
|
25
|
+
"codex-compat.ts",
|
|
26
|
+
"builtin-model-catalog.ts",
|
|
27
|
+
"models-json-manager.ts",
|
|
28
|
+
"models-json-sync.ts",
|
|
29
|
+
"provider-registrar.ts",
|
|
30
|
+
"provider-transport.ts",
|
|
31
|
+
"local-proxy-service.ts",
|
|
32
|
+
"request-pipeline.ts",
|
|
33
|
+
"model-mutations.ts",
|
|
34
|
+
"header-profile-mutations.ts",
|
|
35
|
+
"rescue.ts",
|
|
36
|
+
"atomic-write.ts",
|
|
37
|
+
"proper-lockfile.d.ts",
|
|
38
|
+
"common.ts",
|
|
39
|
+
"config-value-reference.ts",
|
|
40
|
+
"configuration-persistence.ts",
|
|
41
|
+
"configuration-lock.ts",
|
|
42
|
+
"file-snapshot.ts",
|
|
43
|
+
"sensitive-redaction.ts",
|
|
44
|
+
"compat-settings.ts",
|
|
45
|
+
"runtime-base-url.ts",
|
|
46
|
+
"types.ts",
|
|
47
|
+
"tui/",
|
|
48
|
+
"presets/"
|
|
49
|
+
],
|
|
50
|
+
"keywords": [
|
|
51
|
+
"pi-package",
|
|
52
|
+
"pi-extension",
|
|
53
|
+
"pi",
|
|
54
|
+
"model-manager",
|
|
55
|
+
"provider-manager",
|
|
56
|
+
"models-json",
|
|
57
|
+
"client-headers",
|
|
58
|
+
"openai",
|
|
59
|
+
"anthropic"
|
|
60
|
+
],
|
|
61
|
+
"author": "Qihuanxishini",
|
|
62
|
+
"license": "AGPL-3.0-only",
|
|
63
|
+
"repository": {
|
|
64
|
+
"type": "git",
|
|
65
|
+
"url": "git+https://github.com/Qihuanxishini/pi-model-manager.git"
|
|
66
|
+
},
|
|
67
|
+
"homepage": "https://github.com/Qihuanxishini/pi-model-manager#readme",
|
|
68
|
+
"bugs": {
|
|
69
|
+
"url": "https://github.com/Qihuanxishini/pi-model-manager/issues"
|
|
70
|
+
},
|
|
71
|
+
"pi": {
|
|
72
|
+
"extensions": [
|
|
73
|
+
"./index.ts"
|
|
74
|
+
]
|
|
75
|
+
},
|
|
76
|
+
"peerDependencies": {
|
|
77
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
78
|
+
"@earendil-works/pi-ai": "*",
|
|
79
|
+
"@earendil-works/pi-tui": "*"
|
|
80
|
+
},
|
|
81
|
+
"dependencies": {
|
|
82
|
+
"http-proxy-agent": "^9.1.0",
|
|
83
|
+
"https-proxy-agent": "^9.1.0",
|
|
84
|
+
"minimatch": "^10.2.6",
|
|
85
|
+
"proper-lockfile": "^4.1.2"
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// 由私有 request-capture-service 根据真实客户端请求生成;公开插件仅消费这些脱敏后的内置值。
|
|
2
2
|
|
|
3
3
|
export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
|
|
4
|
-
"anthropic-beta": "claude-code-20250219,
|
|
4
|
+
"anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14,context-management-2025-06-27,mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,effort-2025-11-24",
|
|
5
5
|
"anthropic-dangerous-direct-browser-access": "true",
|
|
6
6
|
"anthropic-version": "2023-06-01",
|
|
7
|
-
"user-agent": "claude-cli/2.1.
|
|
7
|
+
"user-agent": "claude-cli/2.1.312 (external, sdk-cli)",
|
|
8
8
|
"x-app": "cli",
|
|
9
9
|
"x-stainless-arch": "x64",
|
|
10
10
|
"x-stainless-lang": "js",
|
|
@@ -12,12 +12,12 @@ export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
|
|
|
12
12
|
"x-stainless-package-version": "0.128.0",
|
|
13
13
|
"x-stainless-retry-count": "0",
|
|
14
14
|
"x-stainless-runtime": "node",
|
|
15
|
-
"x-stainless-runtime-version": "v26.
|
|
16
|
-
"x-stainless-timeout": "
|
|
15
|
+
"x-stainless-runtime-version": "v26.12.1",
|
|
16
|
+
"x-stainless-timeout": "300",
|
|
17
17
|
};
|
|
18
18
|
|
|
19
19
|
export const CODEX_CLI_CLIENT_HEADERS: Record<string, string> = {
|
|
20
20
|
"originator": "codex-tui",
|
|
21
|
-
"user-agent": "codex-tui/0.
|
|
21
|
+
"user-agent": "codex-tui/0.165.0 (Windows 10.0.26300; x86_64) xterm-256color (codex-tui; 0.165.0)",
|
|
22
22
|
"x-codex-beta-features": "remote_compaction_v2",
|
|
23
23
|
};
|
|
@@ -4,8 +4,9 @@
|
|
|
4
4
|
// [喵喵喵]: 内置值由私有抓包工具生成,公开插件不携带捕获能力 (2026-07-26)
|
|
5
5
|
|
|
6
6
|
import { cloneStringRecord, hasStringRecordEntries } from "../common.ts";
|
|
7
|
+
import { buildCodexClientHeaders } from "./codex-client-headers.ts";
|
|
7
8
|
import { t } from "../i18n.ts";
|
|
8
|
-
import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, CompatSettings, StoredClientHeaderCapture } from "../types.ts";
|
|
9
|
+
import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, CompatSettings, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
|
|
9
10
|
import { CLAUDE_CODE_CLIENT_HEADERS, CODEX_CLI_CLIENT_HEADERS } from "./builtin-client-headers.ts";
|
|
10
11
|
|
|
11
12
|
const ANTHROPIC_INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
|
|
@@ -68,6 +69,14 @@ export function stripManagedClientHeaders(
|
|
|
68
69
|
return hasStringRecordEntries(nativeHeaders) ? nativeHeaders : undefined;
|
|
69
70
|
}
|
|
70
71
|
|
|
72
|
+
export function resolveProviderCustomHeaders(
|
|
73
|
+
selection: { requestHeaderProfileId?: string; customClientHeaders?: Record<string, string> },
|
|
74
|
+
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
|
|
75
|
+
): Record<string, string> {
|
|
76
|
+
const profileId = selection.requestHeaderProfileId;
|
|
77
|
+
return (profileId && requestHeaderProfiles[profileId]?.headers) || selection.customClientHeaders || {};
|
|
78
|
+
}
|
|
79
|
+
|
|
71
80
|
function getRecommendedClientHeaderProfile(api: ApiKind): ClientHeaderProfileId {
|
|
72
81
|
if (api === "anthropic-messages") return "claude-code";
|
|
73
82
|
if (api === "openai-completions" || api === "openai-responses") return "codex-cli";
|
|
@@ -97,7 +106,7 @@ export function getClientHeadersForProfile(
|
|
|
97
106
|
const headers = hasStringRecordEntries(clientHeaderCaptures[resolved]?.headers)
|
|
98
107
|
? clientHeaderCaptures[resolved]!.headers
|
|
99
108
|
: CODEX_CLI_CLIENT_HEADERS;
|
|
100
|
-
return
|
|
109
|
+
return buildCodexClientHeaders(headers);
|
|
101
110
|
}
|
|
102
111
|
return hasStringRecordEntries(customHeaders) ? cloneStringRecord(customHeaders) : undefined;
|
|
103
112
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Codex 稳定身份画像;插件与私有捕获同步工具共用,避免刷新后把生成版本误当成显式配置。
|
|
2
|
+
|
|
3
|
+
export function codexIdentityFromUserAgent(userAgent: string | null | undefined): Record<string, string> {
|
|
4
|
+
const match = userAgent?.match(/^(codex[-_a-z0-9]*)\/(\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0-9.-]+)?)(?:\s|$)/i);
|
|
5
|
+
return match ? { originator: match[1]!, version: match[2]! } : {};
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** 用同一份 UA 补全身份画像;显式字段仍可覆盖生成值。 */
|
|
9
|
+
export function buildCodexClientHeaders(
|
|
10
|
+
headers: Record<string, string>,
|
|
11
|
+
overrides: Record<string, string> = {},
|
|
12
|
+
): Record<string, string> {
|
|
13
|
+
const base = Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]));
|
|
14
|
+
const explicit = Object.fromEntries(Object.entries(overrides).map(([name, value]) => [name.toLowerCase(), value]));
|
|
15
|
+
// [喵喵喵]: 旧抓包只有三头;版本取自该份 UA,不能拼入另一个内置版本。
|
|
16
|
+
return { ...base, ...codexIdentityFromUserAgent(explicit["user-agent"] ?? base["user-agent"]), ...explicit };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 记录自动生成的字段和值;显式覆盖即使恰好等于模板,也不能被归入生成值。 */
|
|
20
|
+
export function getGeneratedCodexClientHeaders(
|
|
21
|
+
headers: Record<string, string>,
|
|
22
|
+
overrides: Record<string, string> = {},
|
|
23
|
+
): Record<string, string> {
|
|
24
|
+
const explicitNames = new Set(Object.keys(overrides).map((name) => name.toLowerCase()));
|
|
25
|
+
return Object.fromEntries(Object.entries(buildCodexClientHeaders(headers, overrides))
|
|
26
|
+
.filter(([name]) => !explicitNames.has(name)));
|
|
27
|
+
}
|
package/provider-registrar.ts
CHANGED
|
@@ -3,11 +3,12 @@
|
|
|
3
3
|
import { ModelRuntime, type ExtensionAPI, type ProviderConfig } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import type { Provider } from "@earendil-works/pi-ai";
|
|
5
5
|
import { isBuiltinProviderId } from "./builtin-model-catalog.ts";
|
|
6
|
+
import { buildCodexClientHeaders } from "./presets/codex-client-headers.ts";
|
|
6
7
|
import { mergeCompatSettings } from "./compat-settings.ts";
|
|
7
8
|
import { formatUnknownError } from "./common.ts";
|
|
8
9
|
import { t } from "./i18n.ts";
|
|
9
10
|
import { removeProviderLocalProxyRoutes } from "./local-proxy-service.ts";
|
|
10
|
-
import { getClientHeadersForProfile, mergeModelRequestHeaders } from "./presets/client-headers.ts";
|
|
11
|
+
import { getClientHeadersForProfile, mergeModelRequestHeaders, resolveClientHeaderProfile, resolveProviderCustomHeaders } from "./presets/client-headers.ts";
|
|
11
12
|
import { createProviderTransport } from "./provider-transport.ts";
|
|
12
13
|
import { resolveRuntimeBaseUrl } from "./runtime-base-url.ts";
|
|
13
14
|
import type { ApiKind, BuiltInClientHeaderProfileId, StateDocument, StoredClientHeaderCapture, StoredModel, StoredProvider, StoredRequestHeaderProfile } from "./types.ts";
|
|
@@ -44,7 +45,7 @@ async function buildNativeProvider(providerId: string, provider: StoredProvider,
|
|
|
44
45
|
runtime.registerProvider(providerId, config);
|
|
45
46
|
const native = runtime.getProvider(providerId);
|
|
46
47
|
if (!native) throw new Error(t("无法构建接入:{providerId}", { providerId }));
|
|
47
|
-
return createProviderTransport(
|
|
48
|
+
return createProviderTransport(native, provider);
|
|
48
49
|
}
|
|
49
50
|
|
|
50
51
|
function asManagedApi(value: string | undefined, fallback: ApiKind): ApiKind {
|
|
@@ -78,6 +79,9 @@ export function buildModelRequestHeaders(
|
|
|
78
79
|
effectiveCompat,
|
|
79
80
|
);
|
|
80
81
|
const explicitHeaders = mergeModelRequestHeaders(provider.headers, model.headers);
|
|
82
|
+
if (resolveClientHeaderProfile(provider.clientHeaderProfile, effectiveApi) === "codex-cli") {
|
|
83
|
+
return buildCodexClientHeaders(profileHeaders ?? {}, explicitHeaders);
|
|
84
|
+
}
|
|
81
85
|
return provider.clientHeaderProfile === "custom"
|
|
82
86
|
? mergeModelRequestHeaders(explicitHeaders, profileHeaders)
|
|
83
87
|
: mergeModelRequestHeaders(profileHeaders, explicitHeaders);
|
|
@@ -105,15 +109,6 @@ function buildModelConfig(
|
|
|
105
109
|
};
|
|
106
110
|
}
|
|
107
111
|
|
|
108
|
-
function resolveProviderCustomHeaders(
|
|
109
|
-
provider: StoredProvider,
|
|
110
|
-
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
|
|
111
|
-
): Record<string, string> {
|
|
112
|
-
const profileId = provider.requestHeaderProfileId;
|
|
113
|
-
if (profileId && requestHeaderProfiles[profileId]) return requestHeaderProfiles[profileId].headers;
|
|
114
|
-
return provider.customClientHeaders ?? {};
|
|
115
|
-
}
|
|
116
|
-
|
|
117
112
|
/** 注销本扩展实际注册的动态 provider,并同步清理代理路由和回滚快照。 */
|
|
118
113
|
export function unregisterManagedProvider(pi: ExtensionAPI, providerId: string): void {
|
|
119
114
|
removeProviderLocalProxyRoutes(providerId);
|
package/provider-transport.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// 在 Pi 已构造请求后选择传输路线;协议判断始终使用真实网关地址。
|
|
2
2
|
|
|
3
3
|
import { lazyStream, type Provider } from "@earendil-works/pi-ai";
|
|
4
|
-
import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
5
4
|
import { getClaudeCodeSessionId } from "./claude-code-compat.ts";
|
|
5
|
+
import { applyCodexRequestHeaders } from "./codex-compat.ts";
|
|
6
6
|
import { mergeModelRequestHeaders, resolveClientHeaderProfile } from "./presets/client-headers.ts";
|
|
7
7
|
import { t } from "./i18n.ts";
|
|
8
8
|
import { getProviderHttpProxyUrl, openTemporaryLocalProxyRoute } from "./local-proxy-service.ts";
|
|
@@ -91,23 +91,22 @@ function wrapResponsesTerminalStream(response: Response): Response {
|
|
|
91
91
|
});
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
export function createProviderTransport(
|
|
94
|
+
export function createProviderTransport(native: Provider, provider: StoredProvider): Provider {
|
|
95
95
|
const endpoints = new Map(provider.models.map((model) => {
|
|
96
96
|
const api = model.api ?? provider.api;
|
|
97
97
|
const baseUrl = resolveRuntimeBaseUrl(api as ApiKind, model.baseUrl ?? provider.baseUrl);
|
|
98
|
-
|
|
98
|
+
const profile = resolveClientHeaderProfile(provider.clientHeaderProfile, api as ApiKind);
|
|
99
|
+
const explicitHeaderNames = new Set(Object.keys(mergeModelRequestHeaders(provider.headers, model.headers) ?? {}));
|
|
100
|
+
return [model.id, { api, baseUrl, profile, explicitHeaderNames }];
|
|
99
101
|
}));
|
|
100
102
|
const proxyUrl = provider.httpProxyEnabled ? getProviderHttpProxyUrl(provider) : undefined;
|
|
101
|
-
const usesClaudeCodeHeaders = resolveClientHeaderProfile(provider.clientHeaderProfile, "anthropic-messages") === "claude-code";
|
|
102
103
|
|
|
103
104
|
const wrap = (stream: Provider["streamSimple"]): Provider["streamSimple"] => (model, context, options) => lazyStream(model, async () => {
|
|
104
105
|
const endpoint = endpoints.get(model.id);
|
|
105
106
|
if (!endpoint || endpoint.api !== model.api) throw new Error(t("请求模型不属于当前接入配置:{modelId}", { modelId: model.id }));
|
|
106
107
|
validateRequestBaseUrl(endpoint.baseUrl);
|
|
107
|
-
// [喵喵喵]:
|
|
108
|
-
|
|
109
|
-
if (!resolved) throw new Error(t("请求认证解析失败"));
|
|
110
|
-
options = { ...options, headers: mergeModelRequestHeaders(options?.headers, resolved.auth.headers) };
|
|
108
|
+
// [喵喵喵]: models.json 已保存完整模型头,由宿主在 transformHeaders 前解析;发送层不能再次合并配置而复活被删除的头。
|
|
109
|
+
options = { ...options };
|
|
111
110
|
// [喵喵喵]: models.json 会叠加在动态 provider 之上;还原用户侧 API 根地址,不能让原生持久化形式参与路径拼接。
|
|
112
111
|
const upstreamModel = { ...model, baseUrl: endpoint.baseUrl };
|
|
113
112
|
if (model.api === "google-generative-ai") {
|
|
@@ -132,7 +131,9 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
|
|
|
132
131
|
if (proxyUrl) throw new Error(t("该协议尚不支持接入级代理:{api}", { api: model.api }));
|
|
133
132
|
return stream(upstreamModel, context, options);
|
|
134
133
|
}
|
|
134
|
+
const usesCodexHeaders = endpoint.profile === "codex-cli";
|
|
135
135
|
if (!proxyUrl
|
|
136
|
+
&& !usesCodexHeaders
|
|
136
137
|
&& model.api !== "anthropic-messages"
|
|
137
138
|
&& !(model.api === "openai-responses" && provider.openAIResponsesStreamCompletionMode === "terminal-event")) {
|
|
138
139
|
return stream(upstreamModel, context, options);
|
|
@@ -149,13 +150,16 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
|
|
|
149
150
|
// [喵喵喵]: 仅替换 SDK 明确追加的端点路径,保留 beta 等请求参数,不对 URL 做全局 /v1 替换。
|
|
150
151
|
url.pathname = new URL(appendUrlPath(endpoint.baseUrl, "messages")).pathname;
|
|
151
152
|
request = new Request(url, request);
|
|
152
|
-
if (
|
|
153
|
+
if (endpoint.profile === "claude-code") {
|
|
153
154
|
// [喵喵喵]: 从已构造的 body 取会话 ID,避免重试或会话重置后读取全局状态造成头与 metadata 错配。
|
|
154
155
|
const payload: unknown = await request.clone().json().catch(() => undefined);
|
|
155
156
|
const sessionId = getClaudeCodeSessionId(payload);
|
|
156
157
|
if (sessionId) request.headers.set("x-claude-code-session-id", sessionId);
|
|
157
158
|
}
|
|
158
159
|
}
|
|
160
|
+
if (usesCodexHeaders) {
|
|
161
|
+
await applyCodexRequestHeaders(request, model.api as ApiKind, options?.sessionId, endpoint.explicitHeaderNames);
|
|
162
|
+
}
|
|
159
163
|
let response: Response;
|
|
160
164
|
if (!proxyUrl) {
|
|
161
165
|
response = await fetchImpl(request);
|
package/state-metadata-store.ts
CHANGED
|
@@ -9,6 +9,9 @@ import { join } from "node:path";
|
|
|
9
9
|
import { cloneJson, isObjectRecord, stringifyJson, stripJsonNoise } from "./common.ts";
|
|
10
10
|
import { readStableTextFileSnapshot, type FileSignature } from "./file-snapshot.ts";
|
|
11
11
|
import { t } from "./i18n.ts";
|
|
12
|
+
import { mergeCompatSettings } from "./compat-settings.ts";
|
|
13
|
+
import { getClientHeadersForProfile, mergeModelRequestHeaders, resolveClientHeaderProfile } from "./presets/client-headers.ts";
|
|
14
|
+
import { getGeneratedCodexClientHeaders } from "./presets/codex-client-headers.ts";
|
|
12
15
|
import { fromNativeBaseUrl, toNativeBaseUrl } from "./runtime-base-url.ts";
|
|
13
16
|
import type {
|
|
14
17
|
ApiKind,
|
|
@@ -53,6 +56,7 @@ interface ProviderMetadata {
|
|
|
53
56
|
interface ModelMetadata {
|
|
54
57
|
openAIServiceTier?: OpenAIServiceTier;
|
|
55
58
|
anthropicApiRoot?: boolean;
|
|
59
|
+
generatedClientHeaders?: Record<string, string>;
|
|
56
60
|
}
|
|
57
61
|
|
|
58
62
|
export interface MetadataDocument {
|
|
@@ -269,6 +273,8 @@ function readModelMetadata(raw: unknown, path: string): ModelMetadata {
|
|
|
269
273
|
if (anthropicApiRoot) metadata.anthropicApiRoot = true;
|
|
270
274
|
const openAIServiceTier = readOptionalOpenAIServiceTier(raw, "openAIServiceTier", path);
|
|
271
275
|
if (openAIServiceTier) metadata.openAIServiceTier = openAIServiceTier;
|
|
276
|
+
const generatedClientHeaders = readOptionalStringRecord(raw, "generatedClientHeaders", path);
|
|
277
|
+
if (generatedClientHeaders !== undefined) metadata.generatedClientHeaders = generatedClientHeaders;
|
|
272
278
|
return metadata;
|
|
273
279
|
}
|
|
274
280
|
|
|
@@ -412,10 +418,17 @@ function extractProviderMetadata(provider: StoredProvider): ProviderMetadata {
|
|
|
412
418
|
return metadata;
|
|
413
419
|
}
|
|
414
420
|
|
|
415
|
-
function extractModelMetadata(model: StoredModel, provider: StoredProvider): ModelMetadata {
|
|
421
|
+
function extractModelMetadata(model: StoredModel, provider: StoredProvider, state?: StateDocument): ModelMetadata {
|
|
416
422
|
const metadata: ModelMetadata = {};
|
|
417
|
-
|
|
423
|
+
const api = model.api ?? provider.api;
|
|
424
|
+
if (toNativeBaseUrl(api, model.baseUrl ?? provider.baseUrl).anthropicApiRoot) metadata.anthropicApiRoot = true;
|
|
418
425
|
if (model.openAIServiceTier) metadata.openAIServiceTier = model.openAIServiceTier;
|
|
426
|
+
if (state && resolveClientHeaderProfile(provider.clientHeaderProfile, api) === "codex-cli") {
|
|
427
|
+
const headers = getClientHeadersForProfile(provider.clientHeaderProfile, api, {}, state.clientHeaderCaptures,
|
|
428
|
+
mergeCompatSettings(provider.compat, model.compat));
|
|
429
|
+
// [喵喵喵]: 来源随双文件事务一起保存;显式值与模板相同也保留,UA 派生值不能在回读后变成显式覆盖。
|
|
430
|
+
metadata.generatedClientHeaders = getGeneratedCodexClientHeaders(headers ?? {}, mergeModelRequestHeaders(provider.headers, model.headers));
|
|
431
|
+
}
|
|
419
432
|
return metadata;
|
|
420
433
|
}
|
|
421
434
|
|
|
@@ -517,7 +530,7 @@ function extractMetadata(state: StateDocument): MetadataDocument {
|
|
|
517
530
|
const providerMetadata = extractProviderMetadata(provider);
|
|
518
531
|
if (Object.keys(providerMetadata).length > 0) metadata.providers[providerId] = providerMetadata;
|
|
519
532
|
for (const model of provider.models) {
|
|
520
|
-
const modelMetadata = extractModelMetadata(model, provider);
|
|
533
|
+
const modelMetadata = extractModelMetadata(model, provider, state);
|
|
521
534
|
if (Object.keys(modelMetadata).length > 0) metadata.models[getFullModelId(providerId, model.id)] = modelMetadata;
|
|
522
535
|
}
|
|
523
536
|
}
|
package/state-store.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
import {
|
|
21
21
|
getClientHeadersForProfile,
|
|
22
22
|
stripManagedClientHeaders,
|
|
23
|
+
resolveProviderCustomHeaders,
|
|
23
24
|
} from "./presets/client-headers.ts";
|
|
24
25
|
import { normalizeThinkingLevelMap } from "./presets/thinking.ts";
|
|
25
26
|
import { fromNativeBaseUrl, resolveRuntimeBaseUrl, toNativeBaseUrl } from "./runtime-base-url.ts";
|
|
@@ -94,15 +95,6 @@ function readModelInput(model: ModelsJsonModelEntry): ModelInputKind[] {
|
|
|
94
95
|
return input && input.length > 0 ? [...new Set(input)] : ["text"];
|
|
95
96
|
}
|
|
96
97
|
|
|
97
|
-
function resolveProviderCustomHeaders(
|
|
98
|
-
providerMetadata: MetadataDocument["providers"][string] | undefined,
|
|
99
|
-
metadata: MetadataDocument,
|
|
100
|
-
): Record<string, string> {
|
|
101
|
-
const profileId = providerMetadata?.requestHeaderProfileId;
|
|
102
|
-
if (profileId && metadata.requestHeaderProfiles[profileId]) return metadata.requestHeaderProfiles[profileId].headers;
|
|
103
|
-
return providerMetadata?.customClientHeaders ?? {};
|
|
104
|
-
}
|
|
105
|
-
|
|
106
98
|
function stripProviderInheritedHeaders(
|
|
107
99
|
modelHeaders: Record<string, string> | undefined,
|
|
108
100
|
providerHeaders: Record<string, string> | undefined,
|
|
@@ -146,8 +138,10 @@ function buildStoredModelFromModelsJson(
|
|
|
146
138
|
effectiveCompat,
|
|
147
139
|
)
|
|
148
140
|
: undefined;
|
|
141
|
+
const modelMetadata = metadata.models[getFullModelId(providerId, model.id)];
|
|
149
142
|
const nativeHeaders = managed
|
|
150
|
-
? stripProviderInheritedHeaders(stripManagedClientHeaders(model.headers,
|
|
143
|
+
? stripProviderInheritedHeaders(stripManagedClientHeaders(model.headers,
|
|
144
|
+
modelMetadata?.generatedClientHeaders ?? profileHeaders), providerHeaders)
|
|
151
145
|
: cloneStringRecord(model.headers);
|
|
152
146
|
const stored: StoredModel = {
|
|
153
147
|
id: model.id,
|
|
@@ -158,7 +152,6 @@ function buildStoredModelFromModelsJson(
|
|
|
158
152
|
cost: readModelCost(model),
|
|
159
153
|
};
|
|
160
154
|
if (explicitApi && explicitApi !== providerApi) stored.api = explicitApi;
|
|
161
|
-
const modelMetadata = metadata.models[getFullModelId(providerId, model.id)];
|
|
162
155
|
let modelBaseUrl = model.baseUrl ?? providerBaseUrl;
|
|
163
156
|
if (managed && model.baseUrl) {
|
|
164
157
|
modelBaseUrl = fromNativeBaseUrl(effectiveApi, model.baseUrl, modelMetadata?.anthropicApiRoot, metadata.version < 5);
|
|
@@ -206,7 +199,7 @@ async function buildStoredProviderFromModelsJson(
|
|
|
206
199
|
: nativeBaseUrl;
|
|
207
200
|
const clientHeaderProfile = managed ? providerMetadata?.clientHeaderProfile ?? "recommended" : "disabled";
|
|
208
201
|
const customClientHeaders = managed && clientHeaderProfile === "custom"
|
|
209
|
-
? resolveProviderCustomHeaders(providerMetadata, metadata)
|
|
202
|
+
? resolveProviderCustomHeaders(providerMetadata ?? {}, metadata.requestHeaderProfiles)
|
|
210
203
|
: {};
|
|
211
204
|
const providerCompat = entry.compat ? cloneJson(entry.compat) : undefined;
|
|
212
205
|
const models = rawModels
|