pi-model-manager 0.4.1 → 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/README.en.md +19 -5
- package/README.md +19 -5
- package/claude-code-compat.ts +17 -1
- package/i18n.ts +15 -3
- package/index.ts +5 -0
- package/openai-responses-recovery.ts +230 -0
- package/openai-service-tier.ts +4 -2
- 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 +13 -2
- package/state-metadata-store.ts +7 -1
- package/state-store.ts +3 -0
- package/tui/editor-model.ts +11 -10
- package/tui/editor-provider.ts +26 -0
- package/tui/ui-helpers.ts +10 -3
- package/types.ts +4 -1
package/README.en.md
CHANGED
|
@@ -4,7 +4,7 @@ English · [简体中文](./README.md)
|
|
|
4
4
|
|
|
5
5
|
[](https://github.com/earendil-works/pi)
|
|
6
6
|
[](./LICENSE)
|
|
7
|
-
[](https://www.npmjs.com/package/pi-model-manager)
|
|
8
8
|
|
|
9
9
|
A TUI model and provider manager for [Pi](https://github.com/earendil-works/pi). It keeps Pi's native `models.json` as the single source of truth for model configuration while adding provider/model editing, client-header identities, proxy routing, and protocol compatibility controls.
|
|
10
10
|
|
|
@@ -91,7 +91,7 @@ Ctrl+S 保存并启用模型;不切换当前会话模型
|
|
|
91
91
|
显示名称 默认 = 模型 ID
|
|
92
92
|
❯ 视觉支持 ◀ 开启 ▶
|
|
93
93
|
Thinking ◀ 开启 ▶
|
|
94
|
-
Fast mode ◀
|
|
94
|
+
Fast mode ◀ 标准 ▶
|
|
95
95
|
上下文窗口 ◀ 1050000 ▶
|
|
96
96
|
最大输出 ◀ 128000 ▶
|
|
97
97
|
请求头 跟随接入(Auto→Codex)
|
|
@@ -132,7 +132,7 @@ Ctrl+S 保存并启用模型;不切换当前会话模型
|
|
|
132
132
|
- Fetch model IDs from compatible upstream APIs or enter them manually.
|
|
133
133
|
- Configure context window, maximum output, vision support, and reasoning support.
|
|
134
134
|
- Choose Anthropic Adaptive Thinking or Legacy Thinking.
|
|
135
|
-
-
|
|
135
|
+
- Select Standard, Fast (`priority`), or Ultrafast (`ultrafast`) service tiers per OpenAI Responses model.
|
|
136
136
|
- Route each provider directly or through its own HTTP(S) proxy.
|
|
137
137
|
- Use recommended, disabled, Claude Code, Codex, or custom client-header profiles.
|
|
138
138
|
- Reference API keys as literals, `$ENV_VAR` / `${ENV_VAR}`, or Pi `!command` values.
|
|
@@ -226,9 +226,23 @@ Model capabilities include:
|
|
|
226
226
|
- Vision support (text only, or text + image input)
|
|
227
227
|
- Reasoning support
|
|
228
228
|
- Anthropic Adaptive/Legacy Thinking
|
|
229
|
-
- OpenAI Responses Fast
|
|
229
|
+
- OpenAI Responses Standard / Fast / Ultrafast service tiers
|
|
230
230
|
- Context window and maximum output tokens
|
|
231
231
|
|
|
232
|
+
### Responses service tiers
|
|
233
|
+
|
|
234
|
+
For `openai-responses`, the model editor shows **Fast mode**. Cycle through the three tiers with `←` / `→`, or press `Enter` for the full descriptions. The model list also shows the selected tier. The Chinese UI uses 标准 / Fast / Ultrafast.
|
|
235
|
+
|
|
236
|
+
| Tier | Request behavior |
|
|
237
|
+
| --- | --- |
|
|
238
|
+
| Standard | Default; does not inject `service_tier`, leaving the upstream default policy unchanged |
|
|
239
|
+
| Fast | Injects `service_tier: "priority"` |
|
|
240
|
+
| Ultrafast | Injects `service_tier: "ultrafast"` |
|
|
241
|
+
|
|
242
|
+
An explicit `service_tier` already present in the request takes precedence and is not overwritten. Standard does not force `service_tier: "default"`; switching back to Standard does not remove a value explicitly set by the caller. Existing Fast settings remain `priority`.
|
|
243
|
+
|
|
244
|
+
Fast and Ultrafast require support from the upstream service, account, and model, and may incur additional charges. The extension only injects request parameters; it does not detect the tier ultimately served or billed. Refer to the upstream response and billing records.
|
|
245
|
+
|
|
232
246
|
## Client-header profiles
|
|
233
247
|
|
|
234
248
|
| Profile | Behavior |
|
|
@@ -255,7 +269,7 @@ Explicit native headers override built-in templates; selecting a custom profile
|
|
|
255
269
|
| Path | Purpose |
|
|
256
270
|
| --- | --- |
|
|
257
271
|
| `~/.pi/agent/models.json` | Native Pi provider and model definitions; the single source of truth for model configuration |
|
|
258
|
-
| `~/.pi/agent/extensions/pi-model-manager/state.json` | Private metadata such as header choices, custom profiles, proxy switches,
|
|
272
|
+
| `~/.pi/agent/extensions/pi-model-manager/state.json` | Private metadata such as header choices, custom profiles, proxy switches, Responses service tiers, and Anthropic custom endpoint markers |
|
|
259
273
|
|
|
260
274
|
The extension generates client headers, proxy routes, and dynamic registrations only for explicitly managed providers. Ownership requires both a managed ID in `state.json` and a `piModelManager.managed` marker on the Provider node in `models.json`; this prevents a deleted Provider ID from silently taking ownership of an unrelated native Provider that later reuses the same ID. Native providers without this ownership evidence remain unmanaged: saving unrelated settings does not rewrite their existing headers or unknown native fields. Built-in Pi providers cannot be edited or deleted through this extension.
|
|
261
275
|
|
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
[](https://github.com/earendil-works/pi)
|
|
6
6
|
[](./LICENSE)
|
|
7
|
-
[](https://www.npmjs.com/package/pi-model-manager)
|
|
8
8
|
|
|
9
9
|
一个面向 [Pi](https://github.com/earendil-works/pi) 的 TUI 模型与接入管理扩展。它以 Pi 原生 `models.json` 为模型配置的唯一权威来源,并提供接入/模型编辑、请求头身份、代理路由和协议兼容配置。
|
|
10
10
|
|
|
@@ -91,7 +91,7 @@ Ctrl+S 保存并启用模型;不切换当前会话模型
|
|
|
91
91
|
显示名称 默认 = 模型 ID
|
|
92
92
|
❯ 视觉支持 ◀ 开启 ▶
|
|
93
93
|
Thinking ◀ 开启 ▶
|
|
94
|
-
Fast mode ◀
|
|
94
|
+
Fast mode ◀ 标准 ▶
|
|
95
95
|
上下文窗口 ◀ 1050000 ▶
|
|
96
96
|
最大输出 ◀ 128000 ▶
|
|
97
97
|
请求头 跟随接入(Auto→Codex)
|
|
@@ -132,7 +132,7 @@ Ctrl+S 保存并启用模型;不切换当前会话模型
|
|
|
132
132
|
- 从兼容上游拉取模型 ID,也可手动填写模型。
|
|
133
133
|
- 配置上下文窗口、最大输出、视觉支持和 Thinking。
|
|
134
134
|
- 支持 Anthropic Adaptive Thinking 与 Legacy Thinking。
|
|
135
|
-
-
|
|
135
|
+
- 为 OpenAI Responses 模型选择标准、Fast(`priority`)或 Ultrafast(`ultrafast`)速度档位。
|
|
136
136
|
- 为每个接入单独配置直连或 HTTP(S) 代理。
|
|
137
137
|
- 提供自动推荐、禁用、Claude Code、Codex 和自定义请求头模式。
|
|
138
138
|
- API key 支持字面值、`$ENV_VAR` / `${ENV_VAR}` 和 Pi 的 `!command` 引用。
|
|
@@ -230,9 +230,23 @@ Anthropic 标准端点在写入 `models.json` 时转换为 Pi 原生 SDK 所需
|
|
|
230
230
|
- 视觉支持(仅文本或文本 + 图片输入)
|
|
231
231
|
- Thinking 开关
|
|
232
232
|
- Anthropic Adaptive/Legacy Thinking 协议
|
|
233
|
-
- OpenAI Responses Fast
|
|
233
|
+
- OpenAI Responses 标准 / Fast / Ultrafast 速度档位
|
|
234
234
|
- Context window 与最大输出 token
|
|
235
235
|
|
|
236
|
+
#### Responses 速度档位
|
|
237
|
+
|
|
238
|
+
当 API 协议为 `openai-responses` 时,模型编辑器会显示 **Fast mode**。用 `←` / `→` 循环切换三档,或按 `Enter` 查看完整说明;模型列表也会显示所选档位。英文界面对应 Standard / Fast / Ultrafast。
|
|
239
|
+
|
|
240
|
+
| 档位 | 请求行为 |
|
|
241
|
+
| --- | --- |
|
|
242
|
+
| 标准 | 默认选项;不主动注入 `service_tier`,沿用上游默认策略 |
|
|
243
|
+
| Fast | 注入 `service_tier: "priority"` |
|
|
244
|
+
| Ultrafast | 注入 `service_tier: "ultrafast"` |
|
|
245
|
+
|
|
246
|
+
请求中已有显式 `service_tier` 时,扩展不会覆盖。标准档不等于强制发送 `service_tier: "default"`;切换回标准也不会删除调用方显式设置的值。已有 Fast 配置继续保留为 `priority`。
|
|
247
|
+
|
|
248
|
+
Fast 和 Ultrafast 需要上游、账号及模型支持,可能产生额外费用。扩展只负责请求参数注入,不检测上游最终执行或计费的档位;请以上游响应及账单为准。
|
|
249
|
+
|
|
236
250
|
## 请求头模式
|
|
237
251
|
|
|
238
252
|
| 模式 | 行为 |
|
|
@@ -259,7 +273,7 @@ Anthropic 标准端点在写入 `models.json` 时转换为 Pi 原生 SDK 所需
|
|
|
259
273
|
| 路径 | 用途 |
|
|
260
274
|
| --- | --- |
|
|
261
275
|
| `~/.pi/agent/models.json` | Pi 原生接入与模型定义;模型配置的唯一权威来源 |
|
|
262
|
-
| `~/.pi/agent/extensions/pi-model-manager/state.json` | 请求头选择、自定义请求头、代理开关、
|
|
276
|
+
| `~/.pi/agent/extensions/pi-model-manager/state.json` | 请求头选择、自定义请求头、代理开关、Responses 速度档位和 Anthropic 自定义端点标记等私有元数据 |
|
|
263
277
|
|
|
264
278
|
扩展只会为明确受管理的 Provider 生成请求头、代理路由和动态注册配置。所有权由 `state.json` 的受管理 ID 与 `models.json` Provider 节点中的 `piModelManager.managed` 标记共同确认,防止已删除的 Provider ID 在日后被同名原生配置复用时遭到插件接管。没有这些所有权信息的原生 Provider 保持未管理,其已有 Header 和未知原生字段不会因保存其它配置而被改写;Pi 内置 Provider 不在本扩展中提供编辑或删除入口。
|
|
265
279
|
|
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",
|
|
@@ -129,7 +134,7 @@ const ENGLISH_MESSAGES = {
|
|
|
129
134
|
"最大输出": "Max output",
|
|
130
135
|
"开启 · 新版协议": "On · current protocol",
|
|
131
136
|
"关闭 · Legacy": "Off · Legacy",
|
|
132
|
-
"
|
|
137
|
+
"标准": "Standard",
|
|
133
138
|
"正在拉取模型列表,总计最多 10 秒…": "Fetching the model list (10 seconds maximum)…",
|
|
134
139
|
"拉取失败:{error}": "Fetch failed: {error}",
|
|
135
140
|
"手动输入模型 ID(当前:{current})": "Enter a model ID manually (current: {current})",
|
|
@@ -145,8 +150,9 @@ const ENGLISH_MESSAGES = {
|
|
|
145
150
|
"开启 — 启用模型推理参数": "On — enable reasoning parameters",
|
|
146
151
|
"开启:新版模型,发送 thinking.type=adaptive 和 output_config.effort": "On: current models; send thinking.type=adaptive and output_config.effort",
|
|
147
152
|
"关闭:旧版接口,发送 thinking.type=enabled 和 budget_tokens": "Off: legacy API; send thinking.type=enabled and budget_tokens",
|
|
148
|
-
"
|
|
149
|
-
"
|
|
153
|
+
"标准 — 不发送 service_tier": "Standard — do not send service_tier",
|
|
154
|
+
"Fast — service_tier=priority,可能产生额外费用": "Fast — service_tier=priority; extra charges may apply",
|
|
155
|
+
"Ultrafast — service_tier=ultrafast,需上游支持且可能产生额外费用": "Ultrafast — service_tier=ultrafast; requires upstream support and may cost extra",
|
|
150
156
|
"接入 {providerId} · API {api}": "Provider {providerId} · API {api}",
|
|
151
157
|
"Ctrl+S 保存并启用模型;不切换当前会话模型": "Ctrl+S saves and enables the model without switching the current session model",
|
|
152
158
|
|
|
@@ -326,6 +332,12 @@ const ENGLISH_MESSAGES = {
|
|
|
326
332
|
"ClaudeCode metadata 注入失败,本次请求仅使用请求头": "ClaudeCode metadata injection failed; this request will use headers only",
|
|
327
333
|
"OpenAI Responses instructions 标准化失败,本次请求使用原始 payload": "OpenAI Responses instruction normalization failed; this request will use the original payload",
|
|
328
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.",
|
|
329
341
|
"{reason},已切换到 {fullId}": "{reason}; switched to {fullId}",
|
|
330
342
|
"{reason},已自动切换到 {fullId}": "{reason}; automatically switched to {fullId}",
|
|
331
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/openai-service-tier.ts
CHANGED
|
@@ -24,13 +24,15 @@ export function injectOpenAIServiceTier(
|
|
|
24
24
|
if (!model || model.api !== "openai-responses") return undefined;
|
|
25
25
|
if (!isPayloadRecord(payload)) return undefined;
|
|
26
26
|
if (payload.model !== model.id) return undefined;
|
|
27
|
+
// [喵喵喵]: 调用方的显式档位保持优先;默认档只是不注入,不强制改写上游策略。
|
|
27
28
|
if ("service_tier" in payload) return undefined;
|
|
28
29
|
|
|
29
30
|
const storedModel = state.providers[model.provider]?.models.find((candidate) => candidate.id === model.id);
|
|
30
|
-
|
|
31
|
+
const tier = storedModel?.openAIServiceTier;
|
|
32
|
+
if (tier !== "priority" && tier !== "ultrafast") return undefined;
|
|
31
33
|
|
|
32
34
|
return {
|
|
33
35
|
...payload,
|
|
34
|
-
service_tier:
|
|
36
|
+
service_tier: tier,
|
|
35
37
|
};
|
|
36
38
|
}
|
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 {
|
|
@@ -424,8 +435,8 @@ export function buildModelFromDraft(
|
|
|
424
435
|
|
|
425
436
|
if (thinkingLevelMap) next.thinkingLevelMap = thinkingLevelMap;
|
|
426
437
|
|
|
427
|
-
if (effectiveApi === "openai-responses" && draft.openAIServiceTier === "priority") {
|
|
428
|
-
next.openAIServiceTier =
|
|
438
|
+
if (effectiveApi === "openai-responses" && (draft.openAIServiceTier === "priority" || draft.openAIServiceTier === "ultrafast")) {
|
|
439
|
+
next.openAIServiceTier = draft.openAIServiceTier;
|
|
429
440
|
}
|
|
430
441
|
|
|
431
442
|
// [喵喵喵]: 仅在启用推理时维护 Adaptive 思考协议;关闭推理时彻底清理兼容标记,避免误剥离协议头
|
package/state-metadata-store.ts
CHANGED
|
@@ -37,7 +37,7 @@ const BUILT_IN_CLIENT_HEADER_PROFILE_IDS = new Set<BuiltInClientHeaderProfileId>
|
|
|
37
37
|
const RESERVED_REQUEST_HEADER_PROFILE_IDS = new Set(["claude-code", "codex-cli", "claude-code-live", "codex-cli-live"]);
|
|
38
38
|
const INPUT_KINDS = new Set<ModelInputKind>(["text", "image"]);
|
|
39
39
|
const THINKING_LEVELS = new Set(Object.freeze(["off", "minimal", "low", "medium", "high", "xhigh", "max"]));
|
|
40
|
-
const OPENAI_SERVICE_TIERS = new Set<OpenAIServiceTier>(["priority"]);
|
|
40
|
+
const OPENAI_SERVICE_TIERS = new Set<OpenAIServiceTier>(["priority", "ultrafast"]);
|
|
41
41
|
|
|
42
42
|
interface ProviderMetadata {
|
|
43
43
|
clientHeaderProfile?: ClientHeaderProfileId;
|
|
@@ -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-model.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { showOptionPicker, showPersistentFormMenu, padLabel, markAdjustableValue
|
|
|
15
15
|
import {
|
|
16
16
|
describeVisionInput,
|
|
17
17
|
formatApiShort,
|
|
18
|
+
formatOpenAIServiceTier,
|
|
18
19
|
getVisionInputChoices,
|
|
19
20
|
supportsVisionInput,
|
|
20
21
|
} from "./ui-helpers.ts";
|
|
@@ -45,10 +46,6 @@ function describeAnthropicThinkingProtocol(protocol: AnthropicThinkingProtocol):
|
|
|
45
46
|
return protocol === "adaptive" ? t("开启 · 新版协议") : t("关闭 · Legacy");
|
|
46
47
|
}
|
|
47
48
|
|
|
48
|
-
function describeOpenAIServiceTier(draft: ModelDraft): string {
|
|
49
|
-
return draft.openAIServiceTier === "priority" ? t("开启 · priority") : t("关闭");
|
|
50
|
-
}
|
|
51
|
-
|
|
52
49
|
function getIntegerFieldLabel(field: "contextWindow" | "maxTokens"): string {
|
|
53
50
|
return field === "contextWindow" ? t("上下文窗口") : t("最大输出");
|
|
54
51
|
}
|
|
@@ -111,7 +108,7 @@ export function parsePositiveIntegerWithUnit(rawInput: string): number | undefin
|
|
|
111
108
|
return Math.round(num);
|
|
112
109
|
}
|
|
113
110
|
|
|
114
|
-
//
|
|
111
|
+
// 开关字段在两个方向上取反;档位字段按 direction 在选项间步进。
|
|
115
112
|
function applyHorizontalToggle(draft: ModelDraft, fieldId: string, direction: HorizontalDirection): boolean {
|
|
116
113
|
if (fieldId === "visionInput") {
|
|
117
114
|
draft.inputKinds = supportsVisionInput(draft.inputKinds) ? ["text"] : ["text", "image"];
|
|
@@ -126,7 +123,10 @@ function applyHorizontalToggle(draft: ModelDraft, fieldId: string, direction: Ho
|
|
|
126
123
|
return true;
|
|
127
124
|
}
|
|
128
125
|
if (fieldId === "openAIServiceTier") {
|
|
129
|
-
|
|
126
|
+
const tiers: readonly ModelDraft["openAIServiceTier"][] = [undefined, "priority", "ultrafast"];
|
|
127
|
+
const currentIndex = tiers.indexOf(draft.openAIServiceTier);
|
|
128
|
+
const step = direction === "left" ? -1 : 1;
|
|
129
|
+
draft.openAIServiceTier = tiers[(currentIndex + step + tiers.length) % tiers.length];
|
|
130
130
|
return true;
|
|
131
131
|
}
|
|
132
132
|
if (fieldId === "contextWindow") {
|
|
@@ -157,7 +157,7 @@ function buildRows(draft: ModelDraft): FieldRow[] {
|
|
|
157
157
|
});
|
|
158
158
|
}
|
|
159
159
|
if (shouldShowOpenAIServiceTier(draft)) {
|
|
160
|
-
rows.push({ id: "openAIServiceTier", label: "Fast mode", value:
|
|
160
|
+
rows.push({ id: "openAIServiceTier", label: "Fast mode", value: formatOpenAIServiceTier(draft.openAIServiceTier), adjustable: true });
|
|
161
161
|
}
|
|
162
162
|
rows.push(
|
|
163
163
|
{ id: "contextWindow", label: t("上下文窗口"), value: String(draft.contextWindow), adjustable: true },
|
|
@@ -312,10 +312,11 @@ async function editField(
|
|
|
312
312
|
ctx,
|
|
313
313
|
"Fast mode",
|
|
314
314
|
[
|
|
315
|
-
{ id: "
|
|
316
|
-
{ id: "priority", tier: "priority", label: t("
|
|
315
|
+
{ id: "default", tier: undefined, label: t("标准 — 不发送 service_tier") },
|
|
316
|
+
{ id: "priority", tier: "priority", label: t("Fast — service_tier=priority,可能产生额外费用") },
|
|
317
|
+
{ id: "ultrafast", tier: "ultrafast", label: t("Ultrafast — service_tier=ultrafast,需上游支持且可能产生额外费用") },
|
|
317
318
|
] as const satisfies readonly { id: string; tier: ModelDraft["openAIServiceTier"]; label: string }[],
|
|
318
|
-
draft.openAIServiceTier
|
|
319
|
+
draft.openAIServiceTier ?? "default",
|
|
319
320
|
);
|
|
320
321
|
if (choice) draft.openAIServiceTier = choice.tier;
|
|
321
322
|
return;
|
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/tui/ui-helpers.ts
CHANGED
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
ApiKind,
|
|
18
18
|
ClientHeaderProfileId,
|
|
19
19
|
ModelInputKind,
|
|
20
|
+
OpenAIServiceTier,
|
|
20
21
|
StoredModel,
|
|
21
22
|
StoredProvider,
|
|
22
23
|
StoredRequestHeaderProfile,
|
|
@@ -241,6 +242,12 @@ function formatModelThinkingCell(model: StoredModel): string {
|
|
|
241
242
|
return model.reasoning ? t("开") : t("关");
|
|
242
243
|
}
|
|
243
244
|
|
|
245
|
+
export function formatOpenAIServiceTier(tier: OpenAIServiceTier | undefined): string {
|
|
246
|
+
if (tier === "priority") return "Fast";
|
|
247
|
+
if (tier === "ultrafast") return "Ultrafast";
|
|
248
|
+
return t("标准");
|
|
249
|
+
}
|
|
250
|
+
|
|
244
251
|
interface ModelListCells {
|
|
245
252
|
modelId: string;
|
|
246
253
|
name: string;
|
|
@@ -289,8 +296,8 @@ function getModelListColumns(
|
|
|
289
296
|
const thinking: FixedColumn = { text: cells.thinking, width: 8, color: cells.thinking === t("开") ? "accent" : cells.thinking === t("关") ? "dim" : undefined };
|
|
290
297
|
const context: FixedColumn = { text: cells.context, width: 7, align: "right" };
|
|
291
298
|
const output: FixedColumn = { text: cells.output, width: 7, align: "right" };
|
|
292
|
-
// [喵喵喵]: priority
|
|
293
|
-
const fast: FixedColumn = { text: cells.fast, width: 8, color: cells.fast === "
|
|
299
|
+
// [喵喵喵]: priority / ultrafast 都可能额外计费,用 warning 提醒而不是当普通开关。
|
|
300
|
+
const fast: FixedColumn = { text: cells.fast, width: 8, color: cells.fast === "Fast" || cells.fast === "Ultrafast" ? "warning" : cells.fast === t("标准") ? "dim" : undefined };
|
|
294
301
|
|
|
295
302
|
const fullWidth = provider.api === "openai-responses" ? 98 : 88;
|
|
296
303
|
if (availableWidth >= fullWidth) {
|
|
@@ -329,7 +336,7 @@ function getModelListCells(model?: StoredModel): ModelListCells {
|
|
|
329
336
|
thinking: formatModelThinkingCell(model),
|
|
330
337
|
context: formatContextWindow(model.contextWindow),
|
|
331
338
|
output: formatContextWindow(model.maxTokens),
|
|
332
|
-
fast: model.openAIServiceTier
|
|
339
|
+
fast: formatOpenAIServiceTier(model.openAIServiceTier),
|
|
333
340
|
}
|
|
334
341
|
: {
|
|
335
342
|
modelId: t("模型 ID"),
|
package/types.ts
CHANGED
|
@@ -17,7 +17,7 @@ export type OpenAIResponsesStreamCompletionMode = "standard" | "terminal-event";
|
|
|
17
17
|
export type BuiltInClientHeaderProfileId = "claude-code" | "codex-cli";
|
|
18
18
|
export type ClientHeaderProfileId = "recommended" | "disabled" | BuiltInClientHeaderProfileId | "custom";
|
|
19
19
|
export type CompatSettings = Record<string, unknown>;
|
|
20
|
-
export type OpenAIServiceTier = "priority";
|
|
20
|
+
export type OpenAIServiceTier = "priority" | "ultrafast";
|
|
21
21
|
|
|
22
22
|
export const DEFAULT_PROVIDER_HTTP_PROXY_URL = "http://127.0.0.1:7890";
|
|
23
23
|
|
|
@@ -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;
|