pi-model-manager 0.4.3 → 0.4.4
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/claude-code-compat.ts +17 -1
- package/i18n.ts +11 -0
- package/index.ts +5 -0
- package/openai-responses-recovery.ts +230 -0
- package/package.json +2 -1
- package/presets/builtin-client-headers.ts +4 -4
- package/provider-transport.ts +9 -1
- package/request-pipeline.ts +27 -2
- package/state-document.ts +11 -0
- package/state-metadata-store.ts +6 -0
- package/state-store.ts +3 -0
- package/tui/editor-provider.ts +26 -0
- package/types.ts +3 -0
package/claude-code-compat.ts
CHANGED
|
@@ -19,7 +19,8 @@ let currentClaudeCodeUserId = createClaudeCodeUserId();
|
|
|
19
19
|
function createClaudeCodeUserId(): string {
|
|
20
20
|
const sessionId = randomUUID();
|
|
21
21
|
const hash = createHash("sha256").update(`anthropic_user_${sessionId}`).digest("hex");
|
|
22
|
-
|
|
22
|
+
// [喵喵喵]: 当前客户端将身份序列化为 JSON 字符串;仅生成匿名标识,不采集真实账户信息 (2026-10-25)。
|
|
23
|
+
return JSON.stringify({ device_id: hash, account_uuid: "", session_id: sessionId });
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
export function resetClaudeCodeMetadataSession(): void {
|
|
@@ -30,6 +31,21 @@ function isPayloadRecord(payload: unknown): payload is PayloadRecord {
|
|
|
30
31
|
return isObjectRecord(payload);
|
|
31
32
|
}
|
|
32
33
|
|
|
34
|
+
/** 从实际 payload 的身份信息提取可安全放入请求头的会话 UUID。 */
|
|
35
|
+
export function getClaudeCodeSessionId(payload: unknown): string | undefined {
|
|
36
|
+
if (!isPayloadRecord(payload) || !isObjectRecord(payload.metadata)) return undefined;
|
|
37
|
+
if (typeof payload.metadata.user_id !== "string") return undefined;
|
|
38
|
+
try {
|
|
39
|
+
const identity: unknown = JSON.parse(payload.metadata.user_id);
|
|
40
|
+
if (!isObjectRecord(identity) || typeof identity.session_id !== "string") return undefined;
|
|
41
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(identity.session_id)
|
|
42
|
+
? identity.session_id
|
|
43
|
+
: undefined;
|
|
44
|
+
} catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
33
49
|
export function injectClaudeCodeMetadata(
|
|
34
50
|
payload: unknown,
|
|
35
51
|
model: ActiveModelRef | undefined,
|
package/i18n.ts
CHANGED
|
@@ -105,6 +105,11 @@ const ENGLISH_MESSAGES = {
|
|
|
105
105
|
"兼容模式:正式终态事件已转交后主动结束,不等待上游关闭连接。": "Compatibility mode: finish after forwarding the formal terminal event without waiting for upstream to close.",
|
|
106
106
|
"标准模式:等待上游正常结束流。若回复完成后长期卡住,可启用兼容模式。": "Standard mode: wait for upstream to finish the stream normally. Enable compatibility mode if completed replies remain stuck.",
|
|
107
107
|
"未知 Responses 流结束模式:{value}": "Unknown Responses stream completion mode: {value}",
|
|
108
|
+
"跨资源自动恢复": "State recovery",
|
|
109
|
+
"关闭 — 不检测或自动恢复跨资源状态错误": "Off — do not detect or recover cross-resource state errors",
|
|
110
|
+
"开启 — 仅在指定错误后隔离旧状态并重试一次,逐次提示": "On — isolate old state and retry once only for matching errors; report each recovery",
|
|
111
|
+
"跨资源自动恢复已开启:仅在指定错误后重试一次;隔离旧状态,保留新推理,每次提示结果。": "State recovery is on: retry matching errors once, isolate old state, preserve new reasoning, and report each result.",
|
|
112
|
+
"跨资源自动恢复已关闭:不检测或自动处理资源归属与加密状态错误。": "State recovery is off: resource ownership and encrypted state errors are not detected or recovered.",
|
|
108
113
|
"接入 ID 必填,且不能与已有或 pi 内置接入重复": "Provider ID is required and must not duplicate an existing or built-in Pi provider",
|
|
109
114
|
"Ctrl+S 保存并同步 models.json;不切换当前会话模型": "Ctrl+S saves and syncs models.json without switching the current session model",
|
|
110
115
|
"选择 API 协议": "Select API protocol",
|
|
@@ -327,6 +332,12 @@ const ENGLISH_MESSAGES = {
|
|
|
327
332
|
"ClaudeCode metadata 注入失败,本次请求仅使用请求头": "ClaudeCode metadata injection failed; this request will use headers only",
|
|
328
333
|
"OpenAI Responses instructions 标准化失败,本次请求使用原始 payload": "OpenAI Responses instruction normalization failed; this request will use the original payload",
|
|
329
334
|
"Fast mode 状态读取失败,本次请求未注入 service_tier": "Failed to read Fast mode state; service_tier was not injected for this request",
|
|
335
|
+
"跨资源恢复状态处理失败,本次请求未执行自动恢复": "Failed to process state recovery; automatic recovery was not applied to this request",
|
|
336
|
+
"跨资源自动恢复准备失败,未自动重试": "Failed to prepare cross-resource recovery; no automatic retry was made",
|
|
337
|
+
"{model}:已隔离本次失败携带的旧状态,正在自动重试一次。": "{model}: isolated old state from the failed request; retrying once.",
|
|
338
|
+
"{model}:跨资源自动恢复成功;后续新推理状态正常保留。": "{model}: cross-resource recovery succeeded; new reasoning state will be preserved.",
|
|
339
|
+
"{model}:跨资源自动恢复重试失败,已停止自动重试。": "{model}: cross-resource recovery retry failed; automatic retries have stopped.",
|
|
340
|
+
"{model}:跨资源自动恢复已取消,未继续重试。": "{model}: cross-resource recovery was cancelled; no further retry was made.",
|
|
330
341
|
"{reason},已切换到 {fullId}": "{reason}; switched to {fullId}",
|
|
331
342
|
"{reason},已自动切换到 {fullId}": "{reason}; automatically switched to {fullId}",
|
|
332
343
|
"{reason},但当前没有其它可用模型。请使用 /model-manager 添加模型或 /login 配置认证。": "{reason}, but no other model is currently available. Use /model-manager to add a model or /login to configure authentication.",
|
package/index.ts
CHANGED
|
@@ -62,6 +62,7 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
|
|
|
62
62
|
const requestPipeline = createRequestPipeline();
|
|
63
63
|
pi.on("session_start", async (event, ctx) => {
|
|
64
64
|
resetClaudeCodeMetadataSession();
|
|
65
|
+
requestPipeline.beginActivity();
|
|
65
66
|
const transportErrors: string[] = [];
|
|
66
67
|
let migratedBaseUrlProviderIds: string[] = [];
|
|
67
68
|
try {
|
|
@@ -115,6 +116,10 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
|
|
|
115
116
|
});
|
|
116
117
|
|
|
117
118
|
pi.on("before_provider_request", async (event, ctx) => requestPipeline.transform(event.payload, ctx));
|
|
119
|
+
pi.on("before_agent_start", () => requestPipeline.beginActivity());
|
|
120
|
+
pi.on("agent_before_settle", (event, ctx) => requestPipeline.recover(event, ctx));
|
|
121
|
+
pi.on("turn_end", (event, ctx) => requestPipeline.observeResult(event, ctx));
|
|
122
|
+
pi.on("agent_settled", (event, ctx) => requestPipeline.finishActivity(event.aborted, ctx));
|
|
118
123
|
pi.on("session_shutdown", async () => {
|
|
119
124
|
await closeLocalProxyServer();
|
|
120
125
|
});
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// openai-responses-recovery.ts
|
|
2
|
+
//
|
|
3
|
+
// Responses 跨资源状态恢复:按失败请求隔离旧状态,正常请求及后续新状态不降级。
|
|
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
|
+
const encryptedHashes = new Set<string>();
|
|
61
|
+
for (const item of payload.input as unknown[]) {
|
|
62
|
+
if (!isObjectRecord(item)) continue;
|
|
63
|
+
// [喵喵喵]: msg_pi_* 是 Pi 本地生成的占位 ID;压缩后可能复用,不能当成上游资源 ID 隔离。
|
|
64
|
+
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
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
version: 1, scope, itemIds: [...itemIds], encryptedHashes: [...encryptedHashes],
|
|
71
|
+
previousResponseIds: typeof payload.previous_response_id === "string" ? [payload.previous_response_id] : [],
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function canReplayItem(item: unknown): boolean {
|
|
76
|
+
if (!isObjectRecord(item)) return true;
|
|
77
|
+
switch (item.type) {
|
|
78
|
+
case "item_reference":
|
|
79
|
+
case "compaction": return false;
|
|
80
|
+
case "reasoning":
|
|
81
|
+
case "message":
|
|
82
|
+
case "function_call":
|
|
83
|
+
case "function_call_output": return true;
|
|
84
|
+
default:
|
|
85
|
+
// [喵喵喵]: 未知资源项的 id 可能是必填或依赖服务端状态,不能套用工具调用的剥离规则。
|
|
86
|
+
return typeof item.id !== "string" && !Object.keys(item).some((key) => key.startsWith("encrypted"));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function stripQuarantinedState(
|
|
91
|
+
payload: Record<string, unknown>,
|
|
92
|
+
ctx: ExtensionContext,
|
|
93
|
+
scope: string,
|
|
94
|
+
): Record<string, unknown> | undefined {
|
|
95
|
+
const itemIds = new Set<string>();
|
|
96
|
+
const encryptedHashes = new Set<string>();
|
|
97
|
+
const previousResponseIds = new Set<string>();
|
|
98
|
+
// [喵喵喵]: 只读当前分支的恢复记录,重载后继续隔离旧状态,不污染其它分支或其它模型。
|
|
99
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
100
|
+
if (entry.type !== "custom" || entry.customType !== RECOVERY_ENTRY_TYPE
|
|
101
|
+
|| !isReplayState(entry.data) || entry.data.scope !== scope) continue;
|
|
102
|
+
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
|
+
}
|
|
106
|
+
if (!itemIds.size && !encryptedHashes.size && !previousResponseIds.size) return undefined;
|
|
107
|
+
|
|
108
|
+
let changed = false;
|
|
109
|
+
const input = (payload.input as unknown[]).flatMap((item) => {
|
|
110
|
+
if (!isObjectRecord(item)) return [item];
|
|
111
|
+
const encryptedKeys = Object.keys(item).filter((key) => key.startsWith("encrypted"));
|
|
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
|
+
}
|
|
123
|
+
const next = { ...item };
|
|
124
|
+
for (const key of encryptedKeys) delete next[key];
|
|
125
|
+
if (item.type === "message" && item.role === "assistant") {
|
|
126
|
+
// [喵喵喵]: output message 仍需 id;沿用 Pi 的本地占位 ID 方式,保留正文、拒答、状态与 phase。
|
|
127
|
+
next.id = `msg_pi_recovery_${digest(item).slice(0, 32)}`;
|
|
128
|
+
} else {
|
|
129
|
+
delete next.id;
|
|
130
|
+
}
|
|
131
|
+
return [next];
|
|
132
|
+
});
|
|
133
|
+
const dropPrevious = typeof payload.previous_response_id === "string" && previousResponseIds.has(payload.previous_response_id);
|
|
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;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function isRecoverableError(message: string): boolean {
|
|
141
|
+
return /created under a different Azure OpenAI resource/i.test(message)
|
|
142
|
+
|| /\binvalid_encrypted_content\b/i.test(message)
|
|
143
|
+
|| /\bencrypted content(?:\s+\S+)?(?:\s+for item\s+\S+)?\s+could not be (?:verified|decrypted)\b/i.test(message);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function notify(ctx: ExtensionContext, key: MessageKey, snapshot: RequestSnapshot, warning = false): void {
|
|
147
|
+
if (ctx.hasUI) ctx.ui.notify(`[pi-model-manager] ${t(key, { model: `${snapshot.provider}/${snapshot.model}` })}`, warning ? "warning" : "info");
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function createOpenAIResponsesRecovery() {
|
|
151
|
+
let lastRequest: RequestSnapshot | undefined;
|
|
152
|
+
let pendingRecovery: RequestSnapshot | undefined;
|
|
153
|
+
let attempted = false;
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
beginActivity(): void {
|
|
157
|
+
lastRequest = undefined;
|
|
158
|
+
pendingRecovery = undefined;
|
|
159
|
+
attempted = false;
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
transform(payload: unknown, ctx: ExtensionContext, state: StateDocument): unknown | undefined {
|
|
163
|
+
lastRequest = undefined;
|
|
164
|
+
const model = enabledModel(ctx, state);
|
|
165
|
+
if (!model || !isObjectRecord(payload) || payload.model !== model.id || !Array.isArray(payload.input)) return undefined;
|
|
166
|
+
// [喵喵喵]: 服务端引用、压缩项及未知资源项无法安全重建,不把不完整历史误当成完整回放。
|
|
167
|
+
if (!payload.input.every(canReplayItem)) return undefined;
|
|
168
|
+
const scope = scopeFor(model);
|
|
169
|
+
const transformed = stripQuarantinedState(payload, ctx, scope);
|
|
170
|
+
lastRequest = {
|
|
171
|
+
state: collectState(transformed ?? payload, scope), provider: model.provider,
|
|
172
|
+
model: model.id, sessionId: ctx.sessionManager.getSessionId(),
|
|
173
|
+
};
|
|
174
|
+
return transformed;
|
|
175
|
+
},
|
|
176
|
+
|
|
177
|
+
async recover(event: AgentBeforeSettleEvent, ctx: ExtensionContext): Promise<BoundaryResult | undefined> {
|
|
178
|
+
if (!lastRequest || attempted || event.outcome !== "error") return undefined;
|
|
179
|
+
const snapshot = lastRequest;
|
|
180
|
+
const model = enabledModel(ctx, await readCachedState());
|
|
181
|
+
if (!model || scopeFor(model) !== snapshot.state.scope || ctx.sessionManager.getSessionId() !== snapshot.sessionId) return undefined;
|
|
182
|
+
const failedEntry = event.context.contextEntries.findLast((entry) =>
|
|
183
|
+
entry.messages.some((message) => message.role === "assistant"));
|
|
184
|
+
const message = failedEntry?.messages.findLast((candidate) => candidate.role === "assistant");
|
|
185
|
+
if (!failedEntry || !message || message.role !== "assistant" || message.stopReason !== "error"
|
|
186
|
+
|| message.provider !== snapshot.provider || message.model !== snapshot.model || message.api !== "openai-responses"
|
|
187
|
+
|| message.content.length > 0 || !isRecoverableError(message.errorMessage ?? "")) return undefined;
|
|
188
|
+
const { itemIds, encryptedHashes, previousResponseIds } = snapshot.state;
|
|
189
|
+
if (!itemIds.length && !encryptedHashes.length && !previousResponseIds.length) return undefined;
|
|
190
|
+
|
|
191
|
+
// [喵喵喵]: 报错通常不指明具体失效项,只能隔离该失败请求携带的旧状态;不触碰正文和 call_id。
|
|
192
|
+
// [喵喵喵]: 原始历史保留,仅追加分支状态与失败回复的上下文省略;同一次用户运行最多恢复一次。
|
|
193
|
+
// [喵喵喵]: 错误 assistant 尚在上下文时 canContinue 为 false;省略它后由宿主重新校验,不能提前据此拒绝恢复。
|
|
194
|
+
attempted = true;
|
|
195
|
+
pendingRecovery = snapshot;
|
|
196
|
+
notify(ctx, "{model}:已隔离本次失败携带的旧状态,正在自动重试一次。", snapshot);
|
|
197
|
+
return {
|
|
198
|
+
entries: [
|
|
199
|
+
// [喵喵喵]: 边界 entries 是整体替换,必须保留前序扩展的提案后再追加恢复记录。
|
|
200
|
+
...event.entries,
|
|
201
|
+
{ type: "custom", customType: RECOVERY_ENTRY_TYPE, data: snapshot.state },
|
|
202
|
+
{ type: "context_edit", targetId: failedEntry.sourceEntry.id, replacement: null },
|
|
203
|
+
],
|
|
204
|
+
continue: true,
|
|
205
|
+
};
|
|
206
|
+
},
|
|
207
|
+
|
|
208
|
+
observeResult(event: TurnEndEvent, ctx: ExtensionContext): void {
|
|
209
|
+
const message = event.message;
|
|
210
|
+
if (!pendingRecovery || message.role !== "assistant" || message.provider !== pendingRecovery.provider
|
|
211
|
+
|| message.model !== pendingRecovery.model || message.api !== "openai-responses") return;
|
|
212
|
+
const snapshot = pendingRecovery;
|
|
213
|
+
pendingRecovery = undefined;
|
|
214
|
+
if (message.stopReason === "error") {
|
|
215
|
+
notify(ctx, "{model}:跨资源自动恢复重试失败,已停止自动重试。", snapshot, true);
|
|
216
|
+
} else if (message.stopReason === "aborted") {
|
|
217
|
+
notify(ctx, "{model}:跨资源自动恢复已取消,未继续重试。", snapshot, true);
|
|
218
|
+
} else {
|
|
219
|
+
notify(ctx, "{model}:跨资源自动恢复成功;后续新推理状态正常保留。", snapshot);
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
|
|
223
|
+
finishActivity(aborted: boolean, ctx: ExtensionContext): void {
|
|
224
|
+
if (!pendingRecovery) return;
|
|
225
|
+
notify(ctx, aborted ? "{model}:跨资源自动恢复已取消,未继续重试。"
|
|
226
|
+
: "{model}:跨资源自动恢复重试失败,已停止自动重试。", pendingRecovery, true);
|
|
227
|
+
pendingRecovery = undefined;
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-model-manager",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.4",
|
|
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
5
|
"type": "module",
|
|
6
6
|
"main": "./index.ts",
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"state-metadata-store.ts",
|
|
19
19
|
"state-cache.ts",
|
|
20
20
|
"state-document.ts",
|
|
21
|
+
"openai-responses-recovery.ts",
|
|
21
22
|
"openai-responses-payload.ts",
|
|
22
23
|
"openai-service-tier.ts",
|
|
23
24
|
"claude-code-compat.ts",
|
|
@@ -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,context-1m-2025-08-07,interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,
|
|
4
|
+
"anthropic-beta": "claude-code-20250219,context-1m-2025-08-07,interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,mid-conversation-tool-changes-2026-07-01,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.310 (external, sdk-cli)",
|
|
8
8
|
"x-app": "cli",
|
|
9
9
|
"x-stainless-arch": "x64",
|
|
10
10
|
"x-stainless-lang": "js",
|
|
@@ -13,11 +13,11 @@ export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
|
|
|
13
13
|
"x-stainless-retry-count": "0",
|
|
14
14
|
"x-stainless-runtime": "node",
|
|
15
15
|
"x-stainless-runtime-version": "v26.3.0",
|
|
16
|
-
"x-stainless-timeout": "
|
|
16
|
+
"x-stainless-timeout": "600",
|
|
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.164.0 (Windows 10.0.26300; x86_64) unknown (codex-tui; 0.164.0)",
|
|
22
22
|
"x-codex-beta-features": "remote_compaction_v2",
|
|
23
23
|
};
|
package/provider-transport.ts
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
import { lazyStream, type Provider } from "@earendil-works/pi-ai";
|
|
4
4
|
import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import {
|
|
5
|
+
import { getClaudeCodeSessionId } from "./claude-code-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";
|
|
@@ -97,6 +98,7 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
|
|
|
97
98
|
return [model.id, { api, baseUrl }];
|
|
98
99
|
}));
|
|
99
100
|
const proxyUrl = provider.httpProxyEnabled ? getProviderHttpProxyUrl(provider) : undefined;
|
|
101
|
+
const usesClaudeCodeHeaders = resolveClientHeaderProfile(provider.clientHeaderProfile, "anthropic-messages") === "claude-code";
|
|
100
102
|
|
|
101
103
|
const wrap = (stream: Provider["streamSimple"]): Provider["streamSimple"] => (model, context, options) => lazyStream(model, async () => {
|
|
102
104
|
const endpoint = endpoints.get(model.id);
|
|
@@ -147,6 +149,12 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
|
|
|
147
149
|
// [喵喵喵]: 仅替换 SDK 明确追加的端点路径,保留 beta 等请求参数,不对 URL 做全局 /v1 替换。
|
|
148
150
|
url.pathname = new URL(appendUrlPath(endpoint.baseUrl, "messages")).pathname;
|
|
149
151
|
request = new Request(url, request);
|
|
152
|
+
if (usesClaudeCodeHeaders) {
|
|
153
|
+
// [喵喵喵]: 从已构造的 body 取会话 ID,避免重试或会话重置后读取全局状态造成头与 metadata 错配。
|
|
154
|
+
const payload: unknown = await request.clone().json().catch(() => undefined);
|
|
155
|
+
const sessionId = getClaudeCodeSessionId(payload);
|
|
156
|
+
if (sessionId) request.headers.set("x-claude-code-session-id", sessionId);
|
|
157
|
+
}
|
|
150
158
|
}
|
|
151
159
|
let response: Response;
|
|
152
160
|
if (!proxyUrl) {
|
package/request-pipeline.ts
CHANGED
|
@@ -3,11 +3,12 @@
|
|
|
3
3
|
// 统一协调 before_provider_request payload transform。每个请求内共享一次
|
|
4
4
|
// StateDocument;跨请求由 state-cache.ts 按配置文件签名复用状态。
|
|
5
5
|
|
|
6
|
-
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type { AgentBeforeSettleEvent, BoundaryResult, ExtensionContext, TurnEndEvent } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { injectClaudeCodeMetadata } from "./claude-code-compat.ts";
|
|
8
8
|
import { formatUnknownError } from "./common.ts";
|
|
9
9
|
import { t, type MessageKey } from "./i18n.ts";
|
|
10
10
|
import { normalizeManagedOpenAIResponsesPayload } from "./openai-responses-payload.ts";
|
|
11
|
+
import { createOpenAIResponsesRecovery } from "./openai-responses-recovery.ts";
|
|
11
12
|
import { injectOpenAIServiceTier } from "./openai-service-tier.ts";
|
|
12
13
|
import { readCachedState } from "./state-cache.ts";
|
|
13
14
|
import type { StateDocument } from "./types.ts";
|
|
@@ -49,12 +50,36 @@ const REQUEST_TRANSFORMS: RequestTransform[] = [
|
|
|
49
50
|
|
|
50
51
|
export interface RequestPipeline {
|
|
51
52
|
transform(payload: unknown, ctx: ExtensionContext): Promise<unknown | undefined>;
|
|
53
|
+
beginActivity(): void;
|
|
54
|
+
recover(event: AgentBeforeSettleEvent, ctx: ExtensionContext): Promise<BoundaryResult | undefined>;
|
|
55
|
+
observeResult(event: TurnEndEvent, ctx: ExtensionContext): void;
|
|
56
|
+
finishActivity(aborted: boolean, ctx: ExtensionContext): void;
|
|
52
57
|
}
|
|
53
58
|
|
|
54
59
|
export function createRequestPipeline(): RequestPipeline {
|
|
55
60
|
const notifiedTransformErrors = new Set<string>();
|
|
61
|
+
const recovery = createOpenAIResponsesRecovery();
|
|
62
|
+
const transforms: RequestTransform[] = [
|
|
63
|
+
...REQUEST_TRANSFORMS,
|
|
64
|
+
{
|
|
65
|
+
id: "openai-responses-recovery",
|
|
66
|
+
warning: "跨资源恢复状态处理失败,本次请求未执行自动恢复",
|
|
67
|
+
run: recovery.transform,
|
|
68
|
+
},
|
|
69
|
+
];
|
|
56
70
|
|
|
57
71
|
return {
|
|
72
|
+
beginActivity: recovery.beginActivity,
|
|
73
|
+
observeResult: recovery.observeResult,
|
|
74
|
+
finishActivity: recovery.finishActivity,
|
|
75
|
+
async recover(event, ctx) {
|
|
76
|
+
try {
|
|
77
|
+
return await recovery.recover(event, ctx);
|
|
78
|
+
} catch {
|
|
79
|
+
if (ctx.hasUI) ctx.ui.notify(`[pi-model-manager] ${t("跨资源自动恢复准备失败,未自动重试")}`, "warning");
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
},
|
|
58
83
|
async transform(initialPayload, ctx) {
|
|
59
84
|
let payload = initialPayload;
|
|
60
85
|
let changed = false;
|
|
@@ -73,7 +98,7 @@ export function createRequestPipeline(): RequestPipeline {
|
|
|
73
98
|
const storedModel = provider?.models.find((model) => model.id === ctx.model!.id);
|
|
74
99
|
if (!provider?.managed || !storedModel || (storedModel.api ?? provider.api) !== ctx.model.api) return undefined;
|
|
75
100
|
|
|
76
|
-
for (const transform of
|
|
101
|
+
for (const transform of transforms) {
|
|
77
102
|
try {
|
|
78
103
|
const nextPayload = await transform.run(payload, ctx, state);
|
|
79
104
|
if (nextPayload !== undefined) {
|
package/state-document.ts
CHANGED
|
@@ -91,6 +91,7 @@ export function createProviderDraft(api: ApiKind = "openai-responses"): Provider
|
|
|
91
91
|
httpProxyEnabled: false,
|
|
92
92
|
httpProxyUrl: DEFAULT_PROVIDER_HTTP_PROXY_URL,
|
|
93
93
|
openAIResponsesStreamCompletionMode: "standard",
|
|
94
|
+
openAIResponsesAutoRecoveryEnabled: false,
|
|
94
95
|
selectedIndex: 0,
|
|
95
96
|
};
|
|
96
97
|
}
|
|
@@ -112,6 +113,7 @@ export function createProviderDraftFromStored(providerId: string, stored: Stored
|
|
|
112
113
|
httpProxyEnabled: stored.httpProxyEnabled ?? false,
|
|
113
114
|
httpProxyUrl: stored.httpProxyUrl?.trim() || DEFAULT_PROVIDER_HTTP_PROXY_URL,
|
|
114
115
|
openAIResponsesStreamCompletionMode: stored.openAIResponsesStreamCompletionMode ?? "standard",
|
|
116
|
+
openAIResponsesAutoRecoveryEnabled: stored.openAIResponsesAutoRecoveryEnabled ?? false,
|
|
115
117
|
selectedIndex: 0,
|
|
116
118
|
};
|
|
117
119
|
}
|
|
@@ -295,6 +297,10 @@ export function getProviderChangeWarnings(
|
|
|
295
297
|
&& (current.openAIResponsesStreamCompletionMode ?? "standard") !== (draft.openAIResponsesStreamCompletionMode ?? "standard")) {
|
|
296
298
|
changes.push(t("流结束兼容"));
|
|
297
299
|
}
|
|
300
|
+
if (draft.api === "openai-responses"
|
|
301
|
+
&& (current.openAIResponsesAutoRecoveryEnabled ?? false) !== (draft.openAIResponsesAutoRecoveryEnabled ?? false)) {
|
|
302
|
+
changes.push(t("跨资源自动恢复"));
|
|
303
|
+
}
|
|
298
304
|
if ((current.clientHeaderProfile ?? "recommended") !== draft.clientHeaderProfile
|
|
299
305
|
|| (current.requestHeaderProfileId ?? "") !== (draft.requestHeaderProfileId ?? ""))
|
|
300
306
|
changes.push(t("请求头"));
|
|
@@ -375,6 +381,11 @@ function buildProviderFromDraft(
|
|
|
375
381
|
} else {
|
|
376
382
|
delete next.openAIResponsesStreamCompletionMode;
|
|
377
383
|
}
|
|
384
|
+
if (draft.api === "openai-responses" && draft.openAIResponsesAutoRecoveryEnabled) {
|
|
385
|
+
next.openAIResponsesAutoRecoveryEnabled = true;
|
|
386
|
+
} else {
|
|
387
|
+
delete next.openAIResponsesAutoRecoveryEnabled;
|
|
388
|
+
}
|
|
378
389
|
if (draft.clientHeaderProfile === "custom" && draft.requestHeaderProfileId?.trim()) {
|
|
379
390
|
next.requestHeaderProfileId = draft.requestHeaderProfileId.trim();
|
|
380
391
|
} else {
|
package/state-metadata-store.ts
CHANGED
|
@@ -46,6 +46,7 @@ interface ProviderMetadata {
|
|
|
46
46
|
httpProxyEnabled?: boolean;
|
|
47
47
|
httpProxyUrl?: string;
|
|
48
48
|
openAIResponsesStreamCompletionMode?: OpenAIResponsesStreamCompletionMode;
|
|
49
|
+
openAIResponsesAutoRecoveryEnabled?: boolean;
|
|
49
50
|
anthropicApiRoot?: boolean;
|
|
50
51
|
}
|
|
51
52
|
|
|
@@ -256,6 +257,8 @@ function readProviderMetadata(raw: unknown, path: string): ProviderMetadata {
|
|
|
256
257
|
if (httpProxyUrl !== undefined) metadata.httpProxyUrl = httpProxyUrl;
|
|
257
258
|
const streamCompletionMode = readOptionalOpenAIResponsesStreamCompletionMode(raw, "openAIResponsesStreamCompletionMode", path);
|
|
258
259
|
if (streamCompletionMode !== undefined) metadata.openAIResponsesStreamCompletionMode = streamCompletionMode;
|
|
260
|
+
const autoRecoveryEnabled = readOptionalBoolean(raw, "openAIResponsesAutoRecoveryEnabled", path);
|
|
261
|
+
if (autoRecoveryEnabled !== undefined) metadata.openAIResponsesAutoRecoveryEnabled = autoRecoveryEnabled;
|
|
259
262
|
return metadata;
|
|
260
263
|
}
|
|
261
264
|
|
|
@@ -327,6 +330,8 @@ function readStoredProvider(raw: unknown, path: string, managed: boolean): Store
|
|
|
327
330
|
if (httpProxyUrl !== undefined) provider.httpProxyUrl = httpProxyUrl;
|
|
328
331
|
const streamCompletionMode = readOptionalOpenAIResponsesStreamCompletionMode(raw, "openAIResponsesStreamCompletionMode", path);
|
|
329
332
|
if (streamCompletionMode !== undefined) provider.openAIResponsesStreamCompletionMode = streamCompletionMode;
|
|
333
|
+
const autoRecoveryEnabled = readOptionalBoolean(raw, "openAIResponsesAutoRecoveryEnabled", path);
|
|
334
|
+
if (autoRecoveryEnabled !== undefined) provider.openAIResponsesAutoRecoveryEnabled = autoRecoveryEnabled;
|
|
330
335
|
return provider;
|
|
331
336
|
}
|
|
332
337
|
|
|
@@ -403,6 +408,7 @@ function extractProviderMetadata(provider: StoredProvider): ProviderMetadata {
|
|
|
403
408
|
if (provider.openAIResponsesStreamCompletionMode === "terminal-event") {
|
|
404
409
|
metadata.openAIResponsesStreamCompletionMode = "terminal-event";
|
|
405
410
|
}
|
|
411
|
+
if (provider.openAIResponsesAutoRecoveryEnabled) metadata.openAIResponsesAutoRecoveryEnabled = true;
|
|
406
412
|
return metadata;
|
|
407
413
|
}
|
|
408
414
|
|
package/state-store.ts
CHANGED
|
@@ -250,6 +250,9 @@ async function buildStoredProviderFromModelsJson(
|
|
|
250
250
|
if (managed && providerMetadata?.openAIResponsesStreamCompletionMode !== undefined) {
|
|
251
251
|
provider.openAIResponsesStreamCompletionMode = providerMetadata.openAIResponsesStreamCompletionMode;
|
|
252
252
|
}
|
|
253
|
+
if (managed && providerMetadata?.openAIResponsesAutoRecoveryEnabled !== undefined) {
|
|
254
|
+
provider.openAIResponsesAutoRecoveryEnabled = providerMetadata.openAIResponsesAutoRecoveryEnabled;
|
|
255
|
+
}
|
|
253
256
|
return provider;
|
|
254
257
|
}
|
|
255
258
|
|
package/tui/editor-provider.ts
CHANGED
|
@@ -112,6 +112,12 @@ function buildRows(
|
|
|
112
112
|
value: describeOpenAIResponsesStreamCompletionMode(getOpenAIResponsesStreamCompletionMode(draft)),
|
|
113
113
|
adjustable: true,
|
|
114
114
|
});
|
|
115
|
+
rows.push({
|
|
116
|
+
id: "openAIResponsesAutoRecoveryEnabled",
|
|
117
|
+
label: t("跨资源自动恢复"),
|
|
118
|
+
value: draft.openAIResponsesAutoRecoveryEnabled ? t("开启") : t("关闭"),
|
|
119
|
+
adjustable: true,
|
|
120
|
+
});
|
|
115
121
|
}
|
|
116
122
|
rows.push(
|
|
117
123
|
{ id: "httpProxyEnabled", label: t("本机代理"), value: draft.httpProxyEnabled ? t("开启") : t("关闭"), adjustable: true },
|
|
@@ -135,6 +141,10 @@ function applyHorizontalToggle(draft: ProviderDraft, fieldId: string, direction:
|
|
|
135
141
|
draft.openAIResponsesStreamCompletionMode = cycleOpenAIResponsesStreamCompletionMode(getOpenAIResponsesStreamCompletionMode(draft), direction);
|
|
136
142
|
return true;
|
|
137
143
|
}
|
|
144
|
+
if (fieldId === "openAIResponsesAutoRecoveryEnabled") {
|
|
145
|
+
draft.openAIResponsesAutoRecoveryEnabled = !draft.openAIResponsesAutoRecoveryEnabled;
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
138
148
|
if (fieldId !== "httpProxyEnabled") return false;
|
|
139
149
|
draft.httpProxyEnabled = !draft.httpProxyEnabled;
|
|
140
150
|
if (draft.httpProxyEnabled && !draft.httpProxyUrl.trim()) draft.httpProxyUrl = DEFAULT_PROVIDER_HTTP_PROXY_URL;
|
|
@@ -206,6 +216,19 @@ async function editField(
|
|
|
206
216
|
if (choice) draft.openAIResponsesStreamCompletionMode = choice.id as OpenAIResponsesStreamCompletionMode;
|
|
207
217
|
return;
|
|
208
218
|
}
|
|
219
|
+
if (fieldId === "openAIResponsesAutoRecoveryEnabled") {
|
|
220
|
+
const choice = await showOptionPicker(
|
|
221
|
+
ctx,
|
|
222
|
+
t("跨资源自动恢复"),
|
|
223
|
+
[
|
|
224
|
+
{ id: "disabled", label: t("关闭 — 不检测或自动恢复跨资源状态错误") },
|
|
225
|
+
{ id: "enabled", label: t("开启 — 仅在指定错误后隔离旧状态并重试一次,逐次提示") },
|
|
226
|
+
],
|
|
227
|
+
draft.openAIResponsesAutoRecoveryEnabled ? "enabled" : "disabled",
|
|
228
|
+
);
|
|
229
|
+
if (choice) draft.openAIResponsesAutoRecoveryEnabled = choice.id === "enabled";
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
209
232
|
if (fieldId === "authHeader") {
|
|
210
233
|
const choice = await showOptionPicker(
|
|
211
234
|
ctx,
|
|
@@ -311,6 +334,9 @@ export async function editProvider(
|
|
|
311
334
|
}
|
|
312
335
|
if (draft.api === "openai-responses") {
|
|
313
336
|
summaryLines.push(getOpenAIResponsesStreamCompletionModeHint(getOpenAIResponsesStreamCompletionMode(draft)));
|
|
337
|
+
summaryLines.push(draft.openAIResponsesAutoRecoveryEnabled
|
|
338
|
+
? t("跨资源自动恢复已开启:仅在指定错误后重试一次;隔离旧状态,保留新推理,每次提示结果。")
|
|
339
|
+
: t("跨资源自动恢复已关闭:不检测或自动处理资源归属与加密状态错误。"));
|
|
314
340
|
}
|
|
315
341
|
return summaryLines;
|
|
316
342
|
};
|
package/types.ts
CHANGED
|
@@ -91,6 +91,8 @@ export interface StoredProvider {
|
|
|
91
91
|
httpProxyUrl?: string;
|
|
92
92
|
/** Responses 终态事件已完整转交后,是否主动结束本地 SSE 流。 */
|
|
93
93
|
openAIResponsesStreamCompletionMode?: OpenAIResponsesStreamCompletionMode;
|
|
94
|
+
/** 仅在跨资源或加密状态错误后隔离旧状态并自动重试一次。 */
|
|
95
|
+
openAIResponsesAutoRecoveryEnabled?: boolean;
|
|
94
96
|
models: StoredModel[];
|
|
95
97
|
}
|
|
96
98
|
|
|
@@ -113,6 +115,7 @@ export interface ProviderDraft {
|
|
|
113
115
|
openAIChatCompatibilityMode?: OpenAIChatCompatibilityMode;
|
|
114
116
|
/** Responses 流结束模式;terminal-event 不等待上游关闭连接。 */
|
|
115
117
|
openAIResponsesStreamCompletionMode?: OpenAIResponsesStreamCompletionMode;
|
|
118
|
+
openAIResponsesAutoRecoveryEnabled?: boolean;
|
|
116
119
|
baseUrl: string;
|
|
117
120
|
apiKey: string;
|
|
118
121
|
authHeader: boolean;
|