pi-model-manager 0.4.5 → 0.4.6
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 -1
- package/README.md +3 -1
- package/i18n.ts +1 -0
- package/local-proxy-service.ts +153 -61
- package/openai-responses-recovery.ts +8 -7
- package/package.json +5 -4
- package/presets/builtin-client-headers.ts +6 -6
- package/request-pipeline.ts +2 -0
package/README.en.md
CHANGED
|
@@ -8,7 +8,7 @@ English · [简体中文](./README.md)
|
|
|
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
|
|
|
11
|
-
> This extension requires Pi `>=0.85.1`.
|
|
11
|
+
> This extension requires Pi `>=0.85.1` and Node.js `22.x >=22.21.0` or `>=24.5.0`.
|
|
12
12
|
|
|
13
13
|
## Interface preview
|
|
14
14
|
|
|
@@ -209,6 +209,8 @@ Base URL represents the API root. Both OpenAI protocols and Anthropic append `/v
|
|
|
209
209
|
|
|
210
210
|
Standard Anthropic endpoints are converted to Pi's native SDK representation in `models.json`, so they also work without the extension. Custom version paths use private `state.json` metadata and require the extension's transport adapter. Toggling the proxy changes only the transport route, preserving the final endpoint, application headers, and payload. Proxy failures are reported.
|
|
211
211
|
|
|
212
|
+
Proxy egress uses native Node agents. Requests with the same provider, proxy URL, and upstream protocol can reuse connections. Changing the proxy URL sends new requests through a new pool; an old pool is reclaimed after 30 seconds with no active requests. Removing a temporary route does not interrupt SSE. Session shutdown aborts active forwarding and releases the pools. Whether switching nodes in a proxy client closes existing connections is controlled by that client; the extension does not monitor node selection.
|
|
213
|
+
|
|
212
214
|
### Chat protocol compatibility
|
|
213
215
|
|
|
214
216
|
When the API protocol is `openai-completions` (OpenAI Chat), the provider editor shows **Protocol compatibility**. Switch with `←` / `→`, or press `Enter` for the full descriptions; the setting applies to every model in that provider.
|
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
一个面向 [Pi](https://github.com/earendil-works/pi) 的 TUI 模型与接入管理扩展。它以 Pi 原生 `models.json` 为模型配置的唯一权威来源,并提供接入/模型编辑、请求头身份、代理路由和协议兼容配置。
|
|
10
10
|
|
|
11
|
-
> 本扩展要求 Pi `>=0.85.1`。
|
|
11
|
+
> 本扩展要求 Pi `>=0.85.1`,Node.js `22.x >=22.21.0` 或 `>=24.5.0`。
|
|
12
12
|
|
|
13
13
|
## 界面预览
|
|
14
14
|
|
|
@@ -211,6 +211,8 @@ Base URL 表示 API 根地址:OpenAI 两种协议和 Anthropic 只填域名时
|
|
|
211
211
|
|
|
212
212
|
Anthropic 标准端点在写入 `models.json` 时转换为 Pi 原生 SDK 所需形式,因此未加载扩展时也能使用;自定义版本路径通过 `state.json` 私有标记衔接,依赖扩展的发送适配。代理开关只改变传输路线,最终端点、业务请求头和 payload 保持一致;代理失败会报错。
|
|
213
213
|
|
|
214
|
+
代理出站使用 Node 原生 Agent,同一接入、代理地址和上游协议下的请求可复用连接。修改代理地址后新请求使用新池;旧池无在途请求并空闲 30 秒后回收。临时路由清理不会中断 SSE;会话关闭会中止在途转发并释放连接池。切换代理软件内的节点是否中断旧连接由该软件控制,插件不监听节点选择。
|
|
215
|
+
|
|
214
216
|
### Chat 协议兼容
|
|
215
217
|
|
|
216
218
|
当 API 协议为 `openai-completions`(OpenAI Chat)时,接入编辑器会显示「协议兼容」。用 `←` / `→` 切换,或按 `Enter` 查看完整说明;该设置作用于接入内的所有模型。
|
package/i18n.ts
CHANGED
|
@@ -281,6 +281,7 @@ const ENGLISH_MESSAGES = {
|
|
|
281
281
|
"已删除请求头 {profileId}": "Deleted header profile {profileId}",
|
|
282
282
|
"代理地址无效:{url}": "Invalid proxy URL: {url}",
|
|
283
283
|
"代理地址目前只支持 http:// 或 https:// 代理": "Only http:// or https:// proxies are currently supported",
|
|
284
|
+
"接入代理要求 Node.js 22.21.0(22.x)或 24.5.0 及以上;当前版本为 {version}": "Provider proxies require Node.js 22.21.0 (22.x) or 24.5.0 and later; the current version is {version}",
|
|
284
285
|
"代理请求失败:{code}": "Proxy request failed: {code}",
|
|
285
286
|
"代理安全拦截:上游返回了重定向至 {target},已拒绝跟随": "Proxy security block: upstream redirected to {target}; following it was refused",
|
|
286
287
|
"拒绝转发:目标 Origin {actual} 与注册路由 {expected} 不一致": "Forwarding refused: target origin {actual} does not match the registered route {expected}",
|
package/local-proxy-service.ts
CHANGED
|
@@ -7,14 +7,15 @@
|
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
8
8
|
import http, { type IncomingHttpHeaders, type IncomingMessage, type ServerResponse } from "node:http";
|
|
9
9
|
import https from "node:https";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
10
|
+
import { isIP } from "node:net";
|
|
11
|
+
import { TLSSocket } from "node:tls";
|
|
12
12
|
import { t } from "./i18n.ts";
|
|
13
13
|
import { redactSensitiveText, redactUrlForDisplay } from "./sensitive-redaction.ts";
|
|
14
14
|
import type { StoredProvider } from "./types.ts";
|
|
15
15
|
import { DEFAULT_PROVIDER_HTTP_PROXY_URL } from "./types.ts";
|
|
16
16
|
|
|
17
17
|
export interface ProviderProxyRoute {
|
|
18
|
+
providerId: string;
|
|
18
19
|
upstreamOrigin: string;
|
|
19
20
|
proxyUrl: string;
|
|
20
21
|
}
|
|
@@ -24,6 +25,20 @@ export interface TemporaryLocalProxyRoute {
|
|
|
24
25
|
close(): void;
|
|
25
26
|
}
|
|
26
27
|
|
|
28
|
+
interface ProxyAgentPool {
|
|
29
|
+
key: string;
|
|
30
|
+
agent: http.Agent;
|
|
31
|
+
activeRequests: number;
|
|
32
|
+
idleTimer?: ReturnType<typeof setTimeout>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface ProxyRequestOptions extends http.RequestOptions {
|
|
36
|
+
proxyAbortSignal: AbortSignal;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const AGENT_POOL_IDLE_MS = 30_000;
|
|
40
|
+
const AGENT_POOLS = new Map<string, ProxyAgentPool>();
|
|
41
|
+
const UPSTREAM_REQUESTS = new Map<http.ClientRequest, AbortController>();
|
|
27
42
|
const ROUTES = new Map<string, ProviderProxyRoute>();
|
|
28
43
|
let server: http.Server | undefined;
|
|
29
44
|
let listenPromise: Promise<number> | undefined;
|
|
@@ -78,9 +93,88 @@ function stripHopByHopHeaders(headers: IncomingHttpHeaders): Record<string, stri
|
|
|
78
93
|
return next;
|
|
79
94
|
}
|
|
80
95
|
|
|
81
|
-
function
|
|
82
|
-
|
|
83
|
-
|
|
96
|
+
function ensureNativeProxySupport(): void {
|
|
97
|
+
const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
|
|
98
|
+
if ((major === 22 && minor >= 21) || (major === 24 && minor >= 5) || major > 24) return;
|
|
99
|
+
// [喵喵喵]: 旧 Node 会忽略 proxyEnv;必须拒绝请求,不能让已开启的代理静默变成直连。
|
|
100
|
+
throw new Error(t("接入代理要求 Node.js 22.21.0(22.x)或 24.5.0 及以上;当前版本为 {version}", {
|
|
101
|
+
version: process.versions.node,
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function createProxyAgent(protocol: string, proxyUrl: string): http.Agent {
|
|
106
|
+
const proxyEnv = { HTTP_PROXY: proxyUrl, HTTPS_PROXY: proxyUrl, NO_PROXY: "" };
|
|
107
|
+
const Agent = protocol === "https:" ? https.Agent : http.Agent;
|
|
108
|
+
const agent = new Agent({ keepAlive: true, maxFreeSockets: 2, proxyEnv });
|
|
109
|
+
const proxy = new URL(proxyUrl);
|
|
110
|
+
const proxyHost = proxy.hostname.replace(/^\[|\]$/g, "");
|
|
111
|
+
const proxyServername = proxy.protocol === "https:" && !isIP(proxyHost) ? proxyHost : undefined;
|
|
112
|
+
const createConnection = agent.createConnection.bind(agent);
|
|
113
|
+
// [喵喵喵]: CONNECT 完成前 socket 尚未入原生池;单独销毁 ClientRequest 无法取消这一段建连。
|
|
114
|
+
agent.createConnection = (options, callback) => {
|
|
115
|
+
const { proxyAbortSignal: signal, ...connectionOptions } = options as ProxyRequestOptions;
|
|
116
|
+
let pending = true;
|
|
117
|
+
let socket: ReturnType<typeof createConnection>;
|
|
118
|
+
const abort = () => socket?.destroy(signal?.reason instanceof Error ? signal.reason : undefined);
|
|
119
|
+
const cleanup = () => {
|
|
120
|
+
pending = false;
|
|
121
|
+
signal?.removeEventListener("abort", abort);
|
|
122
|
+
socket?.off("close", cleanup);
|
|
123
|
+
};
|
|
124
|
+
socket = createConnection(connectionOptions, (error, connectedSocket) => {
|
|
125
|
+
cleanup();
|
|
126
|
+
callback?.(error, connectedSocket);
|
|
127
|
+
});
|
|
128
|
+
// [喵喵喵]: 原生代理 TLS 不自动发送 SNI;握手前设置代理域名,不能误用上游目标域名。
|
|
129
|
+
if (proxyServername && socket instanceof TLSSocket) socket.setServername(proxyServername);
|
|
130
|
+
if (pending && socket && signal) {
|
|
131
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
132
|
+
socket.once("close", cleanup);
|
|
133
|
+
if (signal.aborted) abort();
|
|
134
|
+
}
|
|
135
|
+
return socket;
|
|
136
|
+
};
|
|
137
|
+
return agent;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function acquireAgentPool(route: ProviderProxyRoute, protocol: string): ProxyAgentPool {
|
|
141
|
+
const proxyUrl = parseHttpProxyUrl(route.proxyUrl).toString();
|
|
142
|
+
const key = JSON.stringify([route.providerId, proxyUrl, protocol]);
|
|
143
|
+
let pool = AGENT_POOLS.get(key);
|
|
144
|
+
if (!pool) {
|
|
145
|
+
pool = {
|
|
146
|
+
key,
|
|
147
|
+
agent: createProxyAgent(protocol, proxyUrl),
|
|
148
|
+
activeRequests: 0,
|
|
149
|
+
};
|
|
150
|
+
AGENT_POOLS.set(key, pool);
|
|
151
|
+
}
|
|
152
|
+
if (pool.idleTimer) {
|
|
153
|
+
clearTimeout(pool.idleTimer);
|
|
154
|
+
pool.idleTimer = undefined;
|
|
155
|
+
}
|
|
156
|
+
pool.activeRequests += 1;
|
|
157
|
+
return pool;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function releaseAgentPool(pool: ProxyAgentPool): void {
|
|
161
|
+
pool.activeRequests -= 1;
|
|
162
|
+
if (pool.activeRequests !== 0 || AGENT_POOLS.get(pool.key) !== pool) return;
|
|
163
|
+
// [喵喵喵]: 只回收没有在途请求的整个池;临时路由可能在 SSE 响应头到达时就已删除。
|
|
164
|
+
pool.idleTimer = setTimeout(() => {
|
|
165
|
+
if (AGENT_POOLS.get(pool.key) !== pool || pool.activeRequests !== 0) return;
|
|
166
|
+
AGENT_POOLS.delete(pool.key);
|
|
167
|
+
pool.agent.destroy();
|
|
168
|
+
}, AGENT_POOL_IDLE_MS);
|
|
169
|
+
pool.idleTimer.unref();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function destroyProxyAgentPools(): void {
|
|
173
|
+
for (const pool of AGENT_POOLS.values()) {
|
|
174
|
+
if (pool.idleTimer) clearTimeout(pool.idleTimer);
|
|
175
|
+
pool.agent.destroy();
|
|
176
|
+
}
|
|
177
|
+
AGENT_POOLS.clear();
|
|
84
178
|
}
|
|
85
179
|
|
|
86
180
|
function getHostHeader(url: URL): string {
|
|
@@ -151,11 +245,18 @@ function buildForwardRequestHeaders(target: URL, request: IncomingMessage): Reco
|
|
|
151
245
|
return headers;
|
|
152
246
|
}
|
|
153
247
|
|
|
154
|
-
function bindClientAbort(
|
|
248
|
+
function bindClientAbort(
|
|
249
|
+
request: IncomingMessage,
|
|
250
|
+
response: ServerResponse,
|
|
251
|
+
upstreamRequest: http.ClientRequest,
|
|
252
|
+
abortController: AbortController,
|
|
253
|
+
): void {
|
|
155
254
|
const destroyUpstream = () => {
|
|
255
|
+
abortController.abort();
|
|
156
256
|
if (!upstreamRequest.destroyed) upstreamRequest.destroy();
|
|
157
257
|
};
|
|
158
258
|
const destroyUpstreamWithError = (error: Error) => {
|
|
259
|
+
abortController.abort(error);
|
|
159
260
|
if (!upstreamRequest.destroyed) upstreamRequest.destroy(error);
|
|
160
261
|
};
|
|
161
262
|
const onResponseClose = () => {
|
|
@@ -177,44 +278,6 @@ function writeUpstreamRequestError(response: ServerResponse, error: Error): void
|
|
|
177
278
|
writeProxyError(response, error);
|
|
178
279
|
}
|
|
179
280
|
|
|
180
|
-
function forwardPlainHttp(target: URL, proxy: URL, request: IncomingMessage, response: ServerResponse, route: ProviderProxyRoute): void {
|
|
181
|
-
ensureSupportedProxyProtocol(proxy);
|
|
182
|
-
const headers = buildForwardRequestHeaders(target, request);
|
|
183
|
-
const agent = new HttpProxyAgent(proxy);
|
|
184
|
-
const upstreamRequest = http.request({
|
|
185
|
-
hostname: target.hostname,
|
|
186
|
-
port: getUrlPort(target),
|
|
187
|
-
method: request.method,
|
|
188
|
-
path: `${target.pathname}${target.search}`,
|
|
189
|
-
headers,
|
|
190
|
-
agent,
|
|
191
|
-
}, (upstreamResponse) => pipeResponse(upstreamResponse, response, route));
|
|
192
|
-
upstreamRequest.once("close", () => agent.destroy());
|
|
193
|
-
bindClientAbort(request, response, upstreamRequest);
|
|
194
|
-
upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
|
|
195
|
-
// [喵喵喵]: 请求体直接流向上游,避免图像等大 payload 在本地代理中形成完整内存副本 (2026-07-17)
|
|
196
|
-
// [喵喵喵]: 等代理完成请求头重建后再流式读取 body,避免 chunked 请求在异步建连期间重复写入 HTTP 头。
|
|
197
|
-
upstreamRequest.once("socket", () => request.pipe(upstreamRequest));
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
function forwardHttps(target: URL, proxy: URL, request: IncomingMessage, response: ServerResponse, route: ProviderProxyRoute): void {
|
|
201
|
-
ensureSupportedProxyProtocol(proxy);
|
|
202
|
-
const headers = buildForwardRequestHeaders(target, request);
|
|
203
|
-
const agent = new HttpsProxyAgent(proxy);
|
|
204
|
-
const upstreamRequest = https.request({
|
|
205
|
-
hostname: target.hostname,
|
|
206
|
-
port: getUrlPort(target),
|
|
207
|
-
method: request.method,
|
|
208
|
-
path: `${target.pathname}${target.search}`,
|
|
209
|
-
headers,
|
|
210
|
-
agent,
|
|
211
|
-
}, (upstreamResponse) => pipeResponse(upstreamResponse, response, route));
|
|
212
|
-
upstreamRequest.once("close", () => agent.destroy());
|
|
213
|
-
bindClientAbort(request, response, upstreamRequest);
|
|
214
|
-
upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
|
|
215
|
-
upstreamRequest.once("socket", () => request.pipe(upstreamRequest));
|
|
216
|
-
}
|
|
217
|
-
|
|
218
281
|
function forwardRequest(route: ProviderProxyRoute, request: IncomingMessage, response: ServerResponse, routePath: string): void {
|
|
219
282
|
const target = new URL(routePath, route.upstreamOrigin);
|
|
220
283
|
// [喵喵喵]: 强制校验解析后的 target.origin 严格等于受管的 upstreamOrigin,阻断 SSRF 任意上游转发
|
|
@@ -224,16 +287,36 @@ function forwardRequest(route: ProviderProxyRoute, request: IncomingMessage, res
|
|
|
224
287
|
expected: route.upstreamOrigin,
|
|
225
288
|
}));
|
|
226
289
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
forwardPlainHttp(target, proxy, request, response, route);
|
|
230
|
-
return;
|
|
290
|
+
if (target.protocol !== "http:" && target.protocol !== "https:") {
|
|
291
|
+
throw new Error(t("不支持的上游协议:{protocol}", { protocol: target.protocol }));
|
|
231
292
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
293
|
+
const headers = buildForwardRequestHeaders(target, request);
|
|
294
|
+
const abortController = new AbortController();
|
|
295
|
+
const pool = acquireAgentPool(route, target.protocol);
|
|
296
|
+
const transport = target.protocol === "https:" ? https : http;
|
|
297
|
+
const options: ProxyRequestOptions = {
|
|
298
|
+
method: request.method,
|
|
299
|
+
headers,
|
|
300
|
+
agent: pool.agent,
|
|
301
|
+
signal: abortController.signal,
|
|
302
|
+
proxyAbortSignal: abortController.signal,
|
|
303
|
+
};
|
|
304
|
+
let upstreamRequest: http.ClientRequest;
|
|
305
|
+
try {
|
|
306
|
+
upstreamRequest = transport.request(target, options, (upstreamResponse) => pipeResponse(upstreamResponse, response, route));
|
|
307
|
+
} catch (error) {
|
|
308
|
+
releaseAgentPool(pool);
|
|
309
|
+
throw error;
|
|
235
310
|
}
|
|
236
|
-
|
|
311
|
+
UPSTREAM_REQUESTS.set(upstreamRequest, abortController);
|
|
312
|
+
upstreamRequest.once("close", () => {
|
|
313
|
+
UPSTREAM_REQUESTS.delete(upstreamRequest);
|
|
314
|
+
releaseAgentPool(pool);
|
|
315
|
+
});
|
|
316
|
+
bindClientAbort(request, response, upstreamRequest, abortController);
|
|
317
|
+
upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
|
|
318
|
+
// [喵喵喵]: 请求体直接流向上游,避免图像等大 payload 在本地代理中形成完整内存副本 (2026-07-17)
|
|
319
|
+
upstreamRequest.once("socket", () => request.pipe(upstreamRequest));
|
|
237
320
|
}
|
|
238
321
|
|
|
239
322
|
function handleRequest(request: IncomingMessage, response: ServerResponse): void {
|
|
@@ -312,6 +395,7 @@ async function ensureServer(): Promise<number> {
|
|
|
312
395
|
}
|
|
313
396
|
|
|
314
397
|
async function ensureServerForRoute(): Promise<number> {
|
|
398
|
+
ensureNativeProxySupport();
|
|
315
399
|
const port = await ensureServer();
|
|
316
400
|
if (closingPromise) throw new Error(t("本地代理服务正在关闭,请稍后重试"));
|
|
317
401
|
return port;
|
|
@@ -322,6 +406,7 @@ export async function getLocalProxyBaseUrl(routeId: string, upstreamRuntimeBaseU
|
|
|
322
406
|
const proxy = parseHttpProxyUrl(proxyUrl);
|
|
323
407
|
const port = await ensureServerForRoute();
|
|
324
408
|
ROUTES.set(routeId, {
|
|
409
|
+
providerId: routeId,
|
|
325
410
|
upstreamOrigin: upstream.origin,
|
|
326
411
|
proxyUrl: proxy.toString(),
|
|
327
412
|
});
|
|
@@ -338,7 +423,7 @@ export async function openTemporaryLocalProxyRoute(
|
|
|
338
423
|
const proxy = parseHttpProxyUrl(proxyUrl);
|
|
339
424
|
const port = await ensureServerForRoute();
|
|
340
425
|
const routeId = `${providerId}/model-list/${randomUUID()}`;
|
|
341
|
-
const route = { upstreamOrigin: upstream.origin, proxyUrl: proxy.toString() };
|
|
426
|
+
const route = { providerId, upstreamOrigin: upstream.origin, proxyUrl: proxy.toString() };
|
|
342
427
|
ROUTES.set(routeId, route);
|
|
343
428
|
const basePath = trimTrailingSlashes(upstream.pathname || "");
|
|
344
429
|
return {
|
|
@@ -386,21 +471,28 @@ async function closeServerLifecycle(): Promise<void> {
|
|
|
386
471
|
}
|
|
387
472
|
}
|
|
388
473
|
const current = server;
|
|
389
|
-
|
|
474
|
+
const pendingClose = current?.listening
|
|
475
|
+
? new Promise<void>((resolve, reject) => {
|
|
476
|
+
current.close((error) => error ? reject(error) : resolve());
|
|
477
|
+
})
|
|
478
|
+
: undefined;
|
|
479
|
+
current?.closeAllConnections();
|
|
480
|
+
for (const [upstreamRequest, abortController] of UPSTREAM_REQUESTS) {
|
|
481
|
+
abortController.abort();
|
|
482
|
+
upstreamRequest.destroy();
|
|
483
|
+
}
|
|
484
|
+
UPSTREAM_REQUESTS.clear();
|
|
485
|
+
destroyProxyAgentPools();
|
|
390
486
|
try {
|
|
391
|
-
|
|
392
|
-
await new Promise<void>((resolve, reject) => {
|
|
393
|
-
current.close((error) => error ? reject(error) : resolve());
|
|
394
|
-
});
|
|
395
|
-
}
|
|
487
|
+
await pendingClose;
|
|
396
488
|
} finally {
|
|
397
|
-
clearServerState(current);
|
|
489
|
+
if (current) clearServerState(current);
|
|
398
490
|
}
|
|
399
491
|
}
|
|
400
492
|
|
|
401
493
|
export async function closeLocalProxyServer(): Promise<void> {
|
|
402
494
|
if (closingPromise) return closingPromise;
|
|
403
|
-
const operation =
|
|
495
|
+
const operation = Promise.resolve().then(closeServerLifecycle);
|
|
404
496
|
closingPromise = operation;
|
|
405
497
|
try {
|
|
406
498
|
await operation;
|
|
@@ -108,7 +108,7 @@ function stripQuarantinedItemIds(
|
|
|
108
108
|
}
|
|
109
109
|
|
|
110
110
|
function isRecoverableError(message: string): boolean {
|
|
111
|
-
return /created under a different Azure OpenAI resource/i.test(message)
|
|
111
|
+
return /created under a different (?:Azure|\*{3}) OpenAI resource/i.test(message)
|
|
112
112
|
|| /\bItem with id ['"][^'"\r\n]+['"] (?:was )?not found\b/i.test(message)
|
|
113
113
|
|| /\bwas provided without its required ['"]reasoning['"] item\b/i.test(message)
|
|
114
114
|
|| /\binvalid_encrypted_content\b/i.test(message)
|
|
@@ -122,17 +122,18 @@ function notify(ctx: ExtensionContext, key: MessageKey, snapshot: RequestSnapsho
|
|
|
122
122
|
export function createOpenAIResponsesRecovery() {
|
|
123
123
|
let lastRequest: RequestSnapshot | undefined;
|
|
124
124
|
let pendingRecovery: RequestSnapshot | undefined;
|
|
125
|
-
let attempted = false;
|
|
126
125
|
|
|
127
126
|
return {
|
|
128
127
|
beginActivity(): void {
|
|
129
128
|
lastRequest = undefined;
|
|
130
129
|
pendingRecovery = undefined;
|
|
131
|
-
attempted = false;
|
|
132
130
|
},
|
|
133
131
|
|
|
134
|
-
|
|
132
|
+
beginRequest(): void {
|
|
135
133
|
lastRequest = undefined;
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
transform(payload: unknown, ctx: ExtensionContext, state: StateDocument): unknown | undefined {
|
|
136
137
|
const model = enabledModel(ctx, state);
|
|
137
138
|
if (!model || !isObjectRecord(payload) || payload.model !== model.id || payload.store === true
|
|
138
139
|
|| !Array.isArray(payload.input)) return undefined;
|
|
@@ -148,7 +149,7 @@ export function createOpenAIResponsesRecovery() {
|
|
|
148
149
|
},
|
|
149
150
|
|
|
150
151
|
async recover(event: AgentBeforeSettleEvent, ctx: ExtensionContext): Promise<BoundaryResult | undefined> {
|
|
151
|
-
if (!lastRequest ||
|
|
152
|
+
if (!lastRequest || event.outcome !== "error") return undefined;
|
|
152
153
|
const snapshot = lastRequest;
|
|
153
154
|
const model = enabledModel(ctx, await readCachedState());
|
|
154
155
|
if (!model || scopeFor(model) !== snapshot.state.scope || ctx.sessionManager.getSessionId() !== snapshot.sessionId) return undefined;
|
|
@@ -161,9 +162,9 @@ export function createOpenAIResponsesRecovery() {
|
|
|
161
162
|
if (!snapshot.state.itemIds.length) return undefined;
|
|
162
163
|
|
|
163
164
|
// [喵喵喵]: 只记录失败请求携带的旧 item ID;无法定位具体失效项时成组剥离,不触碰推理密文、正文和 call_id。
|
|
164
|
-
// [喵喵喵]:
|
|
165
|
+
// [喵喵喵]: 原始历史保留,仅追加分支状态与失败回复的上下文省略;恢复不设次数上限,旧 ID 已全部剥离时不再原样重放。
|
|
165
166
|
// [喵喵喵]: 错误 assistant 尚在上下文时 canContinue 为 false;省略它后由宿主重新校验,不能提前据此拒绝恢复。
|
|
166
|
-
|
|
167
|
+
lastRequest = undefined;
|
|
167
168
|
pendingRecovery = snapshot;
|
|
168
169
|
notify(ctx, "{model}:将剥离本次失败历史的 item ID,保留思维链并自动重试一次。", snapshot);
|
|
169
170
|
return {
|
package/package.json
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-model-manager",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.6",
|
|
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
|
+
"engines": {
|
|
7
|
+
"node": "^22.21.0 || >=24.5.0"
|
|
8
|
+
},
|
|
6
9
|
"main": "./index.ts",
|
|
7
10
|
"scripts": {
|
|
8
11
|
"test": "node --experimental-strip-types --import ./tests/register-test-loader.mjs --test --test-reporter=spec tests/*.test.ts",
|
|
@@ -74,13 +77,11 @@
|
|
|
74
77
|
]
|
|
75
78
|
},
|
|
76
79
|
"peerDependencies": {
|
|
77
|
-
"@earendil-works/pi-coding-agent": "*",
|
|
78
80
|
"@earendil-works/pi-ai": "*",
|
|
81
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
79
82
|
"@earendil-works/pi-tui": "*"
|
|
80
83
|
},
|
|
81
84
|
"dependencies": {
|
|
82
|
-
"http-proxy-agent": "^9.1.0",
|
|
83
|
-
"https-proxy-agent": "^9.1.0",
|
|
84
85
|
"minimatch": "^10.2.6",
|
|
85
86
|
"proper-lockfile": "^4.1.2"
|
|
86
87
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Claude Code 请求头来自真实客户端捕获;Codex 采用 codex-proxy-rs 的通用 Rust CLI 画像。
|
|
2
2
|
|
|
3
3
|
export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
|
|
4
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.319 (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.12.1",
|
|
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
|
-
"originator": "
|
|
21
|
-
"user-agent": "
|
|
22
|
-
"
|
|
20
|
+
"originator": "codex_cli_rs",
|
|
21
|
+
"user-agent": "codex_cli_rs/0.167.0 (Windows 10.0.26100; x86_64) unknown",
|
|
22
|
+
"version": "0.167.0",
|
|
23
23
|
};
|
package/request-pipeline.ts
CHANGED
|
@@ -81,6 +81,8 @@ export function createRequestPipeline(): RequestPipeline {
|
|
|
81
81
|
}
|
|
82
82
|
},
|
|
83
83
|
async transform(initialPayload, ctx) {
|
|
84
|
+
// [喵喵喵]: 配置读取失败也不能沿用旧请求快照;这里只开始新请求,不清理待确认的恢复结果。
|
|
85
|
+
recovery.beginRequest();
|
|
84
86
|
let payload = initialPayload;
|
|
85
87
|
let changed = false;
|
|
86
88
|
if (!ctx.model || (ctx.model.api !== "anthropic-messages" && ctx.model.api !== "openai-responses")) return undefined;
|