pi-model-manager 0.4.3 → 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/claude-code-compat.ts +17 -1
- 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 +16 -1
- package/index.ts +5 -0
- 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 +202 -0
- package/package.json +87 -85
- package/presets/builtin-client-headers.ts +4 -4
- 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 +20 -8
- package/request-pipeline.ts +27 -2
- package/state-document.ts +11 -0
- package/state-metadata-store.ts +22 -3
- package/state-store.ts +8 -12
- package/tui/editor-model.ts +2 -2
- package/tui/editor-provider.ts +26 -0
- package/tui/model-list-fetch.ts +2 -2
- package/types.ts +3 -0
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
|
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// openai-responses-recovery.ts
|
|
2
|
+
//
|
|
3
|
+
// Responses 跨资源状态恢复:仅在指定错误后剥离失败历史的 item ID,完整保留推理内容。
|
|
4
|
+
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import type {
|
|
7
|
+
AgentBeforeSettleEvent,
|
|
8
|
+
BoundaryResult,
|
|
9
|
+
ExtensionContext,
|
|
10
|
+
TurnEndEvent,
|
|
11
|
+
} from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { isObjectRecord } from "./common.ts";
|
|
13
|
+
import { t, type MessageKey } from "./i18n.ts";
|
|
14
|
+
import { readCachedState } from "./state-cache.ts";
|
|
15
|
+
import type { StateDocument } from "./types.ts";
|
|
16
|
+
|
|
17
|
+
const RECOVERY_ENTRY_TYPE = "pi-model-manager:responses-state-recovery";
|
|
18
|
+
|
|
19
|
+
type ActiveModel = NonNullable<ExtensionContext["model"]>;
|
|
20
|
+
interface ReplayState {
|
|
21
|
+
version: 1;
|
|
22
|
+
scope: string;
|
|
23
|
+
itemIds: string[];
|
|
24
|
+
encryptedHashes: string[];
|
|
25
|
+
previousResponseIds: string[];
|
|
26
|
+
}
|
|
27
|
+
interface RequestSnapshot {
|
|
28
|
+
state: ReplayState;
|
|
29
|
+
provider: string;
|
|
30
|
+
model: string;
|
|
31
|
+
sessionId: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function digest(value: unknown): string {
|
|
35
|
+
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function scopeFor(model: ActiveModel): string {
|
|
39
|
+
return digest([model.provider, model.id, model.baseUrl]);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function enabledModel(ctx: ExtensionContext, state: StateDocument): ActiveModel | undefined {
|
|
43
|
+
const model = ctx.model;
|
|
44
|
+
if (model?.api !== "openai-responses") return undefined;
|
|
45
|
+
const provider = state.providers[model.provider];
|
|
46
|
+
const storedModel = provider?.models.find((candidate) => candidate.id === model.id);
|
|
47
|
+
if (!provider?.managed || !provider.openAIResponsesAutoRecoveryEnabled
|
|
48
|
+
|| !storedModel || (storedModel.api ?? provider.api) !== model.api) return undefined;
|
|
49
|
+
return model;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function isReplayState(value: unknown): value is ReplayState {
|
|
53
|
+
return isObjectRecord(value) && value.version === 1 && typeof value.scope === "string"
|
|
54
|
+
&& [value.itemIds, value.encryptedHashes, value.previousResponseIds]
|
|
55
|
+
.every((list) => Array.isArray(list) && list.every((item) => typeof item === "string"));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function collectState(payload: Record<string, unknown>, scope: string): ReplayState {
|
|
59
|
+
const itemIds = new Set<string>();
|
|
60
|
+
for (const item of payload.input as unknown[]) {
|
|
61
|
+
if (!isObjectRecord(item)) continue;
|
|
62
|
+
// [喵喵喵]: msg_pi_* 是 Pi 本地生成的占位 ID;压缩后可能复用,不能当成上游资源 ID 隔离。
|
|
63
|
+
if (typeof item.id === "string" && !item.id.startsWith("msg_pi_")) itemIds.add(item.id);
|
|
64
|
+
}
|
|
65
|
+
// [喵喵喵]: 延用既有分支记录格式,但不再记录或清理密文哈希及 response 引用。
|
|
66
|
+
return { version: 1, scope, itemIds: [...itemIds], encryptedHashes: [], previousResponseIds: [] };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function canReplayItem(item: unknown): boolean {
|
|
70
|
+
if (!isObjectRecord(item)) return true;
|
|
71
|
+
switch (item.type) {
|
|
72
|
+
case "item_reference":
|
|
73
|
+
case "compaction": return false;
|
|
74
|
+
case "reasoning":
|
|
75
|
+
case "message":
|
|
76
|
+
case "function_call":
|
|
77
|
+
case "function_call_output": return true;
|
|
78
|
+
default:
|
|
79
|
+
// [喵喵喵]: 未知资源项的 id 可能是必填或依赖服务端状态,不能套用工具调用的剥离规则。
|
|
80
|
+
return typeof item.id !== "string" && !Object.keys(item).some((key) => key.startsWith("encrypted"));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function stripQuarantinedItemIds(
|
|
85
|
+
payload: Record<string, unknown>,
|
|
86
|
+
ctx: ExtensionContext,
|
|
87
|
+
scope: string,
|
|
88
|
+
): Record<string, unknown> | undefined {
|
|
89
|
+
const itemIds = new Set<string>();
|
|
90
|
+
// [喵喵喵]: 仅剥离当前分支已报错的历史 ID;重载后继续生效,其它分支及后续新 ID 不受影响。
|
|
91
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
92
|
+
if (entry.type !== "custom" || entry.customType !== RECOVERY_ENTRY_TYPE
|
|
93
|
+
|| !isReplayState(entry.data) || entry.data.scope !== scope) continue;
|
|
94
|
+
for (const id of entry.data.itemIds) itemIds.add(id);
|
|
95
|
+
}
|
|
96
|
+
if (!itemIds.size) return undefined;
|
|
97
|
+
|
|
98
|
+
let changed = false;
|
|
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 原样保留。
|
|
102
|
+
const next = { ...item };
|
|
103
|
+
delete next.id;
|
|
104
|
+
changed = true;
|
|
105
|
+
return next;
|
|
106
|
+
});
|
|
107
|
+
return changed ? { ...payload, input } : undefined;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function isRecoverableError(message: string): boolean {
|
|
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)
|
|
114
|
+
|| /\binvalid_encrypted_content\b/i.test(message)
|
|
115
|
+
|| /\bencrypted content(?:\s+\S+)?(?:\s+for item\s+\S+)?\s+could not be (?:verified|decrypted)\b/i.test(message);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function notify(ctx: ExtensionContext, key: MessageKey, snapshot: RequestSnapshot, warning = false): void {
|
|
119
|
+
if (ctx.hasUI) ctx.ui.notify(`[pi-model-manager] ${t(key, { model: `${snapshot.provider}/${snapshot.model}` })}`, warning ? "warning" : "info");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function createOpenAIResponsesRecovery() {
|
|
123
|
+
let lastRequest: RequestSnapshot | undefined;
|
|
124
|
+
let pendingRecovery: RequestSnapshot | undefined;
|
|
125
|
+
let attempted = false;
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
beginActivity(): void {
|
|
129
|
+
lastRequest = undefined;
|
|
130
|
+
pendingRecovery = undefined;
|
|
131
|
+
attempted = false;
|
|
132
|
+
},
|
|
133
|
+
|
|
134
|
+
transform(payload: unknown, ctx: ExtensionContext, state: StateDocument): unknown | undefined {
|
|
135
|
+
lastRequest = undefined;
|
|
136
|
+
const model = enabledModel(ctx, state);
|
|
137
|
+
if (!model || !isObjectRecord(payload) || payload.model !== model.id || payload.store === true
|
|
138
|
+
|| !Array.isArray(payload.input)) return undefined;
|
|
139
|
+
// [喵喵喵]: 服务端引用、压缩项及未知资源项的 ID 可能不可省略,不对这些请求自动剥离重放。
|
|
140
|
+
if (!payload.input.every(canReplayItem)) return undefined;
|
|
141
|
+
const scope = scopeFor(model);
|
|
142
|
+
const transformed = stripQuarantinedItemIds(payload, ctx, scope);
|
|
143
|
+
lastRequest = {
|
|
144
|
+
state: collectState(transformed ?? payload, scope), provider: model.provider,
|
|
145
|
+
model: model.id, sessionId: ctx.sessionManager.getSessionId(),
|
|
146
|
+
};
|
|
147
|
+
return transformed;
|
|
148
|
+
},
|
|
149
|
+
|
|
150
|
+
async recover(event: AgentBeforeSettleEvent, ctx: ExtensionContext): Promise<BoundaryResult | undefined> {
|
|
151
|
+
if (!lastRequest || attempted || event.outcome !== "error") return undefined;
|
|
152
|
+
const snapshot = lastRequest;
|
|
153
|
+
const model = enabledModel(ctx, await readCachedState());
|
|
154
|
+
if (!model || scopeFor(model) !== snapshot.state.scope || ctx.sessionManager.getSessionId() !== snapshot.sessionId) return undefined;
|
|
155
|
+
const failedEntry = event.context.contextEntries.findLast((entry) =>
|
|
156
|
+
entry.messages.some((message) => message.role === "assistant"));
|
|
157
|
+
const message = failedEntry?.messages.findLast((candidate) => candidate.role === "assistant");
|
|
158
|
+
if (!failedEntry || !message || message.role !== "assistant" || message.stopReason !== "error"
|
|
159
|
+
|| message.provider !== snapshot.provider || message.model !== snapshot.model || message.api !== "openai-responses"
|
|
160
|
+
|| message.content.length > 0 || !isRecoverableError(message.errorMessage ?? "")) return undefined;
|
|
161
|
+
if (!snapshot.state.itemIds.length) return undefined;
|
|
162
|
+
|
|
163
|
+
// [喵喵喵]: 只记录失败请求携带的旧 item ID;无法定位具体失效项时成组剥离,不触碰推理密文、正文和 call_id。
|
|
164
|
+
// [喵喵喵]: 原始历史保留,仅追加分支状态与失败回复的上下文省略;同一次用户运行最多恢复一次。
|
|
165
|
+
// [喵喵喵]: 错误 assistant 尚在上下文时 canContinue 为 false;省略它后由宿主重新校验,不能提前据此拒绝恢复。
|
|
166
|
+
attempted = true;
|
|
167
|
+
pendingRecovery = snapshot;
|
|
168
|
+
notify(ctx, "{model}:将剥离本次失败历史的 item ID,保留思维链并自动重试一次。", snapshot);
|
|
169
|
+
return {
|
|
170
|
+
entries: [
|
|
171
|
+
// [喵喵喵]: 边界 entries 是整体替换,必须保留前序扩展的提案后再追加恢复记录。
|
|
172
|
+
...event.entries,
|
|
173
|
+
{ type: "custom", customType: RECOVERY_ENTRY_TYPE, data: snapshot.state },
|
|
174
|
+
{ type: "context_edit", targetId: failedEntry.sourceEntry.id, replacement: null },
|
|
175
|
+
],
|
|
176
|
+
continue: true,
|
|
177
|
+
};
|
|
178
|
+
},
|
|
179
|
+
|
|
180
|
+
observeResult(event: TurnEndEvent, ctx: ExtensionContext): void {
|
|
181
|
+
const message = event.message;
|
|
182
|
+
if (!pendingRecovery || message.role !== "assistant" || message.provider !== pendingRecovery.provider
|
|
183
|
+
|| message.model !== pendingRecovery.model || message.api !== "openai-responses") return;
|
|
184
|
+
const snapshot = pendingRecovery;
|
|
185
|
+
pendingRecovery = undefined;
|
|
186
|
+
if (message.stopReason === "error") {
|
|
187
|
+
notify(ctx, "{model}:跨资源自动恢复重试失败,已停止自动重试。", snapshot, true);
|
|
188
|
+
} else if (message.stopReason === "aborted") {
|
|
189
|
+
notify(ctx, "{model}:跨资源自动恢复已取消,未继续重试。", snapshot, true);
|
|
190
|
+
} else {
|
|
191
|
+
notify(ctx, "{model}:跨资源自动恢复成功;思维链完整保留,后续新 item ID 正常保留。", snapshot);
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
|
|
195
|
+
finishActivity(aborted: boolean, ctx: ExtensionContext): void {
|
|
196
|
+
if (!pendingRecovery) return;
|
|
197
|
+
notify(ctx, aborted ? "{model}:跨资源自动恢复已取消,未继续重试。"
|
|
198
|
+
: "{model}:跨资源自动恢复重试失败,已停止自动重试。", pendingRecovery, true);
|
|
199
|
+
pendingRecovery = undefined;
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
}
|
package/package.json
CHANGED
|
@@ -1,85 +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-
|
|
22
|
-
"openai-
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
"pi",
|
|
52
|
-
"
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
"
|
|
83
|
-
"
|
|
84
|
-
|
|
85
|
-
|
|
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.
|
|
15
|
+
"x-stainless-runtime-version": "v26.12.1",
|
|
16
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,9 @@
|
|
|
1
1
|
// 在 Pi 已构造请求后选择传输路线;协议判断始终使用真实网关地址。
|
|
2
2
|
|
|
3
3
|
import { lazyStream, type Provider } from "@earendil-works/pi-ai";
|
|
4
|
-
import
|
|
5
|
-
import {
|
|
4
|
+
import { getClaudeCodeSessionId } from "./claude-code-compat.ts";
|
|
5
|
+
import { applyCodexRequestHeaders } from "./codex-compat.ts";
|
|
6
|
+
import { mergeModelRequestHeaders, resolveClientHeaderProfile } from "./presets/client-headers.ts";
|
|
6
7
|
import { t } from "./i18n.ts";
|
|
7
8
|
import { getProviderHttpProxyUrl, openTemporaryLocalProxyRoute } from "./local-proxy-service.ts";
|
|
8
9
|
import { appendUrlPath, resolveRuntimeBaseUrl, validateRequestBaseUrl } from "./runtime-base-url.ts";
|
|
@@ -90,11 +91,13 @@ function wrapResponsesTerminalStream(response: Response): Response {
|
|
|
90
91
|
});
|
|
91
92
|
}
|
|
92
93
|
|
|
93
|
-
export function createProviderTransport(
|
|
94
|
+
export function createProviderTransport(native: Provider, provider: StoredProvider): Provider {
|
|
94
95
|
const endpoints = new Map(provider.models.map((model) => {
|
|
95
96
|
const api = model.api ?? provider.api;
|
|
96
97
|
const baseUrl = resolveRuntimeBaseUrl(api as ApiKind, model.baseUrl ?? provider.baseUrl);
|
|
97
|
-
|
|
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 }];
|
|
98
101
|
}));
|
|
99
102
|
const proxyUrl = provider.httpProxyEnabled ? getProviderHttpProxyUrl(provider) : undefined;
|
|
100
103
|
|
|
@@ -102,10 +105,8 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
|
|
|
102
105
|
const endpoint = endpoints.get(model.id);
|
|
103
106
|
if (!endpoint || endpoint.api !== model.api) throw new Error(t("请求模型不属于当前接入配置:{modelId}", { modelId: model.id }));
|
|
104
107
|
validateRequestBaseUrl(endpoint.baseUrl);
|
|
105
|
-
// [喵喵喵]:
|
|
106
|
-
|
|
107
|
-
if (!resolved) throw new Error(t("请求认证解析失败"));
|
|
108
|
-
options = { ...options, headers: mergeModelRequestHeaders(options?.headers, resolved.auth.headers) };
|
|
108
|
+
// [喵喵喵]: models.json 已保存完整模型头,由宿主在 transformHeaders 前解析;发送层不能再次合并配置而复活被删除的头。
|
|
109
|
+
options = { ...options };
|
|
109
110
|
// [喵喵喵]: models.json 会叠加在动态 provider 之上;还原用户侧 API 根地址,不能让原生持久化形式参与路径拼接。
|
|
110
111
|
const upstreamModel = { ...model, baseUrl: endpoint.baseUrl };
|
|
111
112
|
if (model.api === "google-generative-ai") {
|
|
@@ -130,7 +131,9 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
|
|
|
130
131
|
if (proxyUrl) throw new Error(t("该协议尚不支持接入级代理:{api}", { api: model.api }));
|
|
131
132
|
return stream(upstreamModel, context, options);
|
|
132
133
|
}
|
|
134
|
+
const usesCodexHeaders = endpoint.profile === "codex-cli";
|
|
133
135
|
if (!proxyUrl
|
|
136
|
+
&& !usesCodexHeaders
|
|
134
137
|
&& model.api !== "anthropic-messages"
|
|
135
138
|
&& !(model.api === "openai-responses" && provider.openAIResponsesStreamCompletionMode === "terminal-event")) {
|
|
136
139
|
return stream(upstreamModel, context, options);
|
|
@@ -147,6 +150,15 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
|
|
|
147
150
|
// [喵喵喵]: 仅替换 SDK 明确追加的端点路径,保留 beta 等请求参数,不对 URL 做全局 /v1 替换。
|
|
148
151
|
url.pathname = new URL(appendUrlPath(endpoint.baseUrl, "messages")).pathname;
|
|
149
152
|
request = new Request(url, request);
|
|
153
|
+
if (endpoint.profile === "claude-code") {
|
|
154
|
+
// [喵喵喵]: 从已构造的 body 取会话 ID,避免重试或会话重置后读取全局状态造成头与 metadata 错配。
|
|
155
|
+
const payload: unknown = await request.clone().json().catch(() => undefined);
|
|
156
|
+
const sessionId = getClaudeCodeSessionId(payload);
|
|
157
|
+
if (sessionId) request.headers.set("x-claude-code-session-id", sessionId);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (usesCodexHeaders) {
|
|
161
|
+
await applyCodexRequestHeaders(request, model.api as ApiKind, options?.sessionId, endpoint.explicitHeaderNames);
|
|
150
162
|
}
|
|
151
163
|
let response: Response;
|
|
152
164
|
if (!proxyUrl) {
|