pi-model-manager 0.4.5 → 0.4.7
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 +16 -11
- package/README.md +16 -11
- package/codex-compat.ts +8 -12
- package/configuration-lock.ts +73 -9
- package/configuration-persistence.ts +84 -11
- package/i18n.ts +6 -1
- package/index.ts +5 -5
- package/local-proxy-service.ts +158 -98
- package/openai-responses-recovery.ts +8 -7
- package/package.json +8 -7
- package/presets/builtin-client-headers.ts +6 -7
- package/presets/client-headers.ts +3 -30
- package/provider-registrar.ts +145 -27
- package/provider-transport.ts +23 -5
- package/request-pipeline.ts +2 -0
- package/state-cache.ts +17 -2
- package/state-document.ts +13 -2
- package/state-metadata-store.ts +29 -11
- package/state-store.ts +30 -27
- package/tui/dashboard.ts +29 -29
- package/tui/editor-model.ts +11 -1
- package/tui/header-profiles-panel.ts +6 -6
- package/tui/model-list-fetch.ts +28 -10
- package/tui/model-list-validation.ts +1 -0
- package/types.ts +5 -0
package/index.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// pi-model-manager 主入口
|
|
2
2
|
//
|
|
3
|
-
// factory 阶段(pi
|
|
4
|
-
// session_start
|
|
3
|
+
// factory 阶段(pi 会等待)读取配置并注册完整 provider,本地代理按请求启动。
|
|
4
|
+
// session_start 核对配置与注册状态,session_shutdown 幂等关闭代理服务。
|
|
5
5
|
//
|
|
6
6
|
// models.json 是模型定义唯一来源;state.json 只保存请求头 profile、抓包缓存、service_tier 等插件私有元数据。
|
|
7
7
|
// 启动期通知用 session_start 事件 + ctx.ui.notify(factory 期没有 ctx)。
|
|
@@ -19,7 +19,6 @@ import { closeLocalProxyServer } from "./local-proxy-service.ts";
|
|
|
19
19
|
import { registerAllFromState, registerCatalogFromState } from "./provider-registrar.ts";
|
|
20
20
|
import { createRequestPipeline } from "./request-pipeline.ts";
|
|
21
21
|
import { createEmptyState, readState } from "./state-store.ts";
|
|
22
|
-
import { runDashboard } from "./tui/dashboard.ts";
|
|
23
22
|
|
|
24
23
|
interface StartupSummary {
|
|
25
24
|
startupErrors: string[];
|
|
@@ -57,7 +56,7 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
|
|
|
57
56
|
}
|
|
58
57
|
}
|
|
59
58
|
|
|
60
|
-
// ---- 2. session_start
|
|
59
|
+
// ---- 2. session_start 同步接入状态并汇报 ----
|
|
61
60
|
let notified = false;
|
|
62
61
|
const requestPipeline = createRequestPipeline();
|
|
63
62
|
pi.on("session_start", async (event, ctx) => {
|
|
@@ -72,7 +71,7 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
|
|
|
72
71
|
configurationBlocked = false;
|
|
73
72
|
}
|
|
74
73
|
const currentState = await readState();
|
|
75
|
-
for (const warning of await registerAllFromState(pi, currentState)) {
|
|
74
|
+
for (const warning of await registerAllFromState(pi, currentState, ctx)) {
|
|
76
75
|
transportErrors.push(t("激活模型接入失败:{warning}", { warning }));
|
|
77
76
|
}
|
|
78
77
|
// [喵喵喵]: 一次性补齐早期版本留在 models.json 里的半成品 baseUrl;
|
|
@@ -132,6 +131,7 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
|
|
|
132
131
|
ctx.ui.notify(t("/model-manager 需要 TUI 交互模式"), "error");
|
|
133
132
|
return;
|
|
134
133
|
}
|
|
134
|
+
const { runDashboard } = await import("./tui/dashboard.ts");
|
|
135
135
|
await runDashboard(pi, ctx);
|
|
136
136
|
},
|
|
137
137
|
});
|
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;
|
|
@@ -61,10 +76,6 @@ function parseHttpProxyUrl(proxyUrl: string | undefined): URL {
|
|
|
61
76
|
return parsed;
|
|
62
77
|
}
|
|
63
78
|
|
|
64
|
-
export function isProviderHttpProxyEnabled(provider: StoredProvider): boolean {
|
|
65
|
-
return provider.httpProxyEnabled === true;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
79
|
export function getProviderHttpProxyUrl(provider: StoredProvider): string {
|
|
69
80
|
return normalizeHttpProxyUrl(provider.httpProxyUrl);
|
|
70
81
|
}
|
|
@@ -78,9 +89,93 @@ function stripHopByHopHeaders(headers: IncomingHttpHeaders): Record<string, stri
|
|
|
78
89
|
return next;
|
|
79
90
|
}
|
|
80
91
|
|
|
81
|
-
function
|
|
82
|
-
if (
|
|
83
|
-
|
|
92
|
+
function ensureNativeProxySupport(): void {
|
|
93
|
+
if (process.versions.bun) {
|
|
94
|
+
throw new Error(t("接入代理不支持 Bun {version};请使用 Node.js 22.21.0(22.x)或 24.5.0 及以上运行 Pi。", {
|
|
95
|
+
version: process.versions.bun,
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
|
|
99
|
+
if ((major === 22 && minor >= 21) || (major === 24 && minor >= 5) || major > 24) return;
|
|
100
|
+
// [喵喵喵]: 旧 Node 会忽略 proxyEnv;必须拒绝请求,不能让已开启的代理静默变成直连。
|
|
101
|
+
throw new Error(t("接入代理要求 Node.js 22.21.0(22.x)或 24.5.0 及以上;当前版本为 {version}", {
|
|
102
|
+
version: process.versions.node,
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function createProxyAgent(protocol: string, proxyUrl: string): http.Agent {
|
|
107
|
+
const proxyEnv = { HTTP_PROXY: proxyUrl, HTTPS_PROXY: proxyUrl, NO_PROXY: "" };
|
|
108
|
+
const Agent = protocol === "https:" ? https.Agent : http.Agent;
|
|
109
|
+
const agent = new Agent({ keepAlive: true, maxFreeSockets: 2, proxyEnv });
|
|
110
|
+
const proxy = new URL(proxyUrl);
|
|
111
|
+
const proxyHost = proxy.hostname.replace(/^\[|\]$/g, "");
|
|
112
|
+
const proxyServername = proxy.protocol === "https:" && !isIP(proxyHost) ? proxyHost : undefined;
|
|
113
|
+
const createConnection = agent.createConnection.bind(agent);
|
|
114
|
+
// [喵喵喵]: CONNECT 完成前 socket 尚未入原生池;单独销毁 ClientRequest 无法取消这一段建连。
|
|
115
|
+
agent.createConnection = (options, callback) => {
|
|
116
|
+
const { proxyAbortSignal: signal, ...connectionOptions } = options as ProxyRequestOptions;
|
|
117
|
+
let pending = true;
|
|
118
|
+
let socket: ReturnType<typeof createConnection>;
|
|
119
|
+
const abort = () => socket?.destroy(signal?.reason instanceof Error ? signal.reason : undefined);
|
|
120
|
+
const cleanup = () => {
|
|
121
|
+
pending = false;
|
|
122
|
+
signal?.removeEventListener("abort", abort);
|
|
123
|
+
socket?.off("close", cleanup);
|
|
124
|
+
};
|
|
125
|
+
socket = createConnection(connectionOptions, (error, connectedSocket) => {
|
|
126
|
+
cleanup();
|
|
127
|
+
callback?.(error, connectedSocket);
|
|
128
|
+
});
|
|
129
|
+
// [喵喵喵]: 原生代理 TLS 不自动发送 SNI;握手前设置代理域名,不能误用上游目标域名。
|
|
130
|
+
if (proxyServername && socket instanceof TLSSocket) socket.setServername(proxyServername);
|
|
131
|
+
if (pending && socket && signal) {
|
|
132
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
133
|
+
socket.once("close", cleanup);
|
|
134
|
+
if (signal.aborted) abort();
|
|
135
|
+
}
|
|
136
|
+
return socket;
|
|
137
|
+
};
|
|
138
|
+
return agent;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function acquireAgentPool(route: ProviderProxyRoute, protocol: string): ProxyAgentPool {
|
|
142
|
+
const proxyUrl = parseHttpProxyUrl(route.proxyUrl).toString();
|
|
143
|
+
const key = JSON.stringify([route.providerId, proxyUrl, protocol]);
|
|
144
|
+
let pool = AGENT_POOLS.get(key);
|
|
145
|
+
if (!pool) {
|
|
146
|
+
pool = {
|
|
147
|
+
key,
|
|
148
|
+
agent: createProxyAgent(protocol, proxyUrl),
|
|
149
|
+
activeRequests: 0,
|
|
150
|
+
};
|
|
151
|
+
AGENT_POOLS.set(key, pool);
|
|
152
|
+
}
|
|
153
|
+
if (pool.idleTimer) {
|
|
154
|
+
clearTimeout(pool.idleTimer);
|
|
155
|
+
pool.idleTimer = undefined;
|
|
156
|
+
}
|
|
157
|
+
pool.activeRequests += 1;
|
|
158
|
+
return pool;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function releaseAgentPool(pool: ProxyAgentPool): void {
|
|
162
|
+
pool.activeRequests -= 1;
|
|
163
|
+
if (pool.activeRequests !== 0 || AGENT_POOLS.get(pool.key) !== pool) return;
|
|
164
|
+
// [喵喵喵]: 只回收没有在途请求的整个池;临时路由可能在 SSE 响应头到达时就已删除。
|
|
165
|
+
pool.idleTimer = setTimeout(() => {
|
|
166
|
+
if (AGENT_POOLS.get(pool.key) !== pool || pool.activeRequests !== 0) return;
|
|
167
|
+
AGENT_POOLS.delete(pool.key);
|
|
168
|
+
pool.agent.destroy();
|
|
169
|
+
}, AGENT_POOL_IDLE_MS);
|
|
170
|
+
pool.idleTimer.unref();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function destroyProxyAgentPools(): void {
|
|
174
|
+
for (const pool of AGENT_POOLS.values()) {
|
|
175
|
+
if (pool.idleTimer) clearTimeout(pool.idleTimer);
|
|
176
|
+
pool.agent.destroy();
|
|
177
|
+
}
|
|
178
|
+
AGENT_POOLS.clear();
|
|
84
179
|
}
|
|
85
180
|
|
|
86
181
|
function getHostHeader(url: URL): string {
|
|
@@ -151,11 +246,18 @@ function buildForwardRequestHeaders(target: URL, request: IncomingMessage): Reco
|
|
|
151
246
|
return headers;
|
|
152
247
|
}
|
|
153
248
|
|
|
154
|
-
function bindClientAbort(
|
|
249
|
+
function bindClientAbort(
|
|
250
|
+
request: IncomingMessage,
|
|
251
|
+
response: ServerResponse,
|
|
252
|
+
upstreamRequest: http.ClientRequest,
|
|
253
|
+
abortController: AbortController,
|
|
254
|
+
): void {
|
|
155
255
|
const destroyUpstream = () => {
|
|
256
|
+
abortController.abort();
|
|
156
257
|
if (!upstreamRequest.destroyed) upstreamRequest.destroy();
|
|
157
258
|
};
|
|
158
259
|
const destroyUpstreamWithError = (error: Error) => {
|
|
260
|
+
abortController.abort(error);
|
|
159
261
|
if (!upstreamRequest.destroyed) upstreamRequest.destroy(error);
|
|
160
262
|
};
|
|
161
263
|
const onResponseClose = () => {
|
|
@@ -177,44 +279,6 @@ function writeUpstreamRequestError(response: ServerResponse, error: Error): void
|
|
|
177
279
|
writeProxyError(response, error);
|
|
178
280
|
}
|
|
179
281
|
|
|
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
282
|
function forwardRequest(route: ProviderProxyRoute, request: IncomingMessage, response: ServerResponse, routePath: string): void {
|
|
219
283
|
const target = new URL(routePath, route.upstreamOrigin);
|
|
220
284
|
// [喵喵喵]: 强制校验解析后的 target.origin 严格等于受管的 upstreamOrigin,阻断 SSRF 任意上游转发
|
|
@@ -224,16 +288,36 @@ function forwardRequest(route: ProviderProxyRoute, request: IncomingMessage, res
|
|
|
224
288
|
expected: route.upstreamOrigin,
|
|
225
289
|
}));
|
|
226
290
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
forwardPlainHttp(target, proxy, request, response, route);
|
|
230
|
-
return;
|
|
291
|
+
if (target.protocol !== "http:" && target.protocol !== "https:") {
|
|
292
|
+
throw new Error(t("不支持的上游协议:{protocol}", { protocol: target.protocol }));
|
|
231
293
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
294
|
+
const headers = buildForwardRequestHeaders(target, request);
|
|
295
|
+
const abortController = new AbortController();
|
|
296
|
+
const pool = acquireAgentPool(route, target.protocol);
|
|
297
|
+
const transport = target.protocol === "https:" ? https : http;
|
|
298
|
+
const options: ProxyRequestOptions = {
|
|
299
|
+
method: request.method,
|
|
300
|
+
headers,
|
|
301
|
+
agent: pool.agent,
|
|
302
|
+
signal: abortController.signal,
|
|
303
|
+
proxyAbortSignal: abortController.signal,
|
|
304
|
+
};
|
|
305
|
+
let upstreamRequest: http.ClientRequest;
|
|
306
|
+
try {
|
|
307
|
+
upstreamRequest = transport.request(target, options, (upstreamResponse) => pipeResponse(upstreamResponse, response, route));
|
|
308
|
+
} catch (error) {
|
|
309
|
+
releaseAgentPool(pool);
|
|
310
|
+
throw error;
|
|
235
311
|
}
|
|
236
|
-
|
|
312
|
+
UPSTREAM_REQUESTS.set(upstreamRequest, abortController);
|
|
313
|
+
upstreamRequest.once("close", () => {
|
|
314
|
+
UPSTREAM_REQUESTS.delete(upstreamRequest);
|
|
315
|
+
releaseAgentPool(pool);
|
|
316
|
+
});
|
|
317
|
+
bindClientAbort(request, response, upstreamRequest, abortController);
|
|
318
|
+
upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
|
|
319
|
+
// [喵喵喵]: 请求体直接流向上游,避免图像等大 payload 在本地代理中形成完整内存副本 (2026-07-17)
|
|
320
|
+
upstreamRequest.once("socket", () => request.pipe(upstreamRequest));
|
|
237
321
|
}
|
|
238
322
|
|
|
239
323
|
function handleRequest(request: IncomingMessage, response: ServerResponse): void {
|
|
@@ -312,23 +396,12 @@ async function ensureServer(): Promise<number> {
|
|
|
312
396
|
}
|
|
313
397
|
|
|
314
398
|
async function ensureServerForRoute(): Promise<number> {
|
|
399
|
+
ensureNativeProxySupport();
|
|
315
400
|
const port = await ensureServer();
|
|
316
401
|
if (closingPromise) throw new Error(t("本地代理服务正在关闭,请稍后重试"));
|
|
317
402
|
return port;
|
|
318
403
|
}
|
|
319
404
|
|
|
320
|
-
export async function getLocalProxyBaseUrl(routeId: string, upstreamRuntimeBaseUrl: string, proxyUrl: string): Promise<string> {
|
|
321
|
-
const upstream = new URL(upstreamRuntimeBaseUrl);
|
|
322
|
-
const proxy = parseHttpProxyUrl(proxyUrl);
|
|
323
|
-
const port = await ensureServerForRoute();
|
|
324
|
-
ROUTES.set(routeId, {
|
|
325
|
-
upstreamOrigin: upstream.origin,
|
|
326
|
-
proxyUrl: proxy.toString(),
|
|
327
|
-
});
|
|
328
|
-
const basePath = trimTrailingSlashes(upstream.pathname || "");
|
|
329
|
-
return `http://127.0.0.1:${port}/${encodeURIComponent(routeId)}${basePath}${upstream.search}`;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
405
|
export async function openTemporaryLocalProxyRoute(
|
|
333
406
|
providerId: string,
|
|
334
407
|
upstreamUrl: string,
|
|
@@ -338,7 +411,7 @@ export async function openTemporaryLocalProxyRoute(
|
|
|
338
411
|
const proxy = parseHttpProxyUrl(proxyUrl);
|
|
339
412
|
const port = await ensureServerForRoute();
|
|
340
413
|
const routeId = `${providerId}/model-list/${randomUUID()}`;
|
|
341
|
-
const route = { upstreamOrigin: upstream.origin, proxyUrl: proxy.toString() };
|
|
414
|
+
const route = { providerId, upstreamOrigin: upstream.origin, proxyUrl: proxy.toString() };
|
|
342
415
|
ROUTES.set(routeId, route);
|
|
343
416
|
const basePath = trimTrailingSlashes(upstream.pathname || "");
|
|
344
417
|
return {
|
|
@@ -349,29 +422,9 @@ export async function openTemporaryLocalProxyRoute(
|
|
|
349
422
|
};
|
|
350
423
|
}
|
|
351
424
|
|
|
352
|
-
function isProviderRouteId(routeId: string, providerId: string): boolean {
|
|
353
|
-
return routeId === providerId || routeId.startsWith(`${providerId}/`);
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
export function snapshotProviderLocalProxyRoutes(providerId: string): Map<string, ProviderProxyRoute> {
|
|
357
|
-
return new Map(
|
|
358
|
-
[...ROUTES.entries()]
|
|
359
|
-
.filter(([routeId]) => isProviderRouteId(routeId, providerId))
|
|
360
|
-
.map(([routeId, route]): [string, ProviderProxyRoute] => [routeId, { ...route }]),
|
|
361
|
-
);
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
export function restoreProviderLocalProxyRoutes(
|
|
365
|
-
providerId: string,
|
|
366
|
-
snapshot: ReadonlyMap<string, ProviderProxyRoute>,
|
|
367
|
-
): void {
|
|
368
|
-
removeProviderLocalProxyRoutes(providerId);
|
|
369
|
-
for (const [routeId, route] of snapshot) ROUTES.set(routeId, { ...route });
|
|
370
|
-
}
|
|
371
|
-
|
|
372
425
|
export function removeProviderLocalProxyRoutes(providerId: string): void {
|
|
373
426
|
for (const routeId of ROUTES.keys()) {
|
|
374
|
-
if (
|
|
427
|
+
if (routeId.startsWith(`${providerId}/`)) ROUTES.delete(routeId);
|
|
375
428
|
}
|
|
376
429
|
}
|
|
377
430
|
|
|
@@ -386,21 +439,28 @@ async function closeServerLifecycle(): Promise<void> {
|
|
|
386
439
|
}
|
|
387
440
|
}
|
|
388
441
|
const current = server;
|
|
389
|
-
|
|
442
|
+
const pendingClose = current?.listening
|
|
443
|
+
? new Promise<void>((resolve, reject) => {
|
|
444
|
+
current.close((error) => error ? reject(error) : resolve());
|
|
445
|
+
})
|
|
446
|
+
: undefined;
|
|
447
|
+
current?.closeAllConnections();
|
|
448
|
+
for (const [upstreamRequest, abortController] of UPSTREAM_REQUESTS) {
|
|
449
|
+
abortController.abort();
|
|
450
|
+
upstreamRequest.destroy();
|
|
451
|
+
}
|
|
452
|
+
UPSTREAM_REQUESTS.clear();
|
|
453
|
+
destroyProxyAgentPools();
|
|
390
454
|
try {
|
|
391
|
-
|
|
392
|
-
await new Promise<void>((resolve, reject) => {
|
|
393
|
-
current.close((error) => error ? reject(error) : resolve());
|
|
394
|
-
});
|
|
395
|
-
}
|
|
455
|
+
await pendingClose;
|
|
396
456
|
} finally {
|
|
397
|
-
clearServerState(current);
|
|
457
|
+
if (current) clearServerState(current);
|
|
398
458
|
}
|
|
399
459
|
}
|
|
400
460
|
|
|
401
461
|
export async function closeLocalProxyServer(): Promise<void> {
|
|
402
462
|
if (closingPromise) return closingPromise;
|
|
403
|
-
const operation =
|
|
463
|
+
const operation = Promise.resolve().then(closeServerLifecycle);
|
|
404
464
|
closingPromise = operation;
|
|
405
465
|
try {
|
|
406
466
|
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.7",
|
|
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,14 +77,12 @@
|
|
|
74
77
|
]
|
|
75
78
|
},
|
|
76
79
|
"peerDependencies": {
|
|
77
|
-
"@earendil-works/pi-
|
|
78
|
-
"@earendil-works/pi-
|
|
79
|
-
"@earendil-works/pi-tui": "
|
|
80
|
+
"@earendil-works/pi-ai": ">=0.85.1",
|
|
81
|
+
"@earendil-works/pi-coding-agent": ">=0.87.0",
|
|
82
|
+
"@earendil-works/pi-tui": ">=0.75.0"
|
|
80
83
|
},
|
|
81
84
|
"dependencies": {
|
|
82
|
-
"
|
|
83
|
-
"https-proxy-agent": "^9.1.0",
|
|
84
|
-
"minimatch": "^10.2.6",
|
|
85
|
+
"minimatch": "^11.0.9",
|
|
85
86
|
"proper-lockfile": "^4.1.2"
|
|
86
87
|
}
|
|
87
88
|
}
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Claude Code 身份字段来自真实客户端捕获,协议 beta 由 Pi 按请求生成;Codex 采用 codex-proxy-rs 的通用 Rust CLI 画像。
|
|
2
2
|
|
|
3
3
|
export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
|
|
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
4
|
"anthropic-dangerous-direct-browser-access": "true",
|
|
6
5
|
"anthropic-version": "2023-06-01",
|
|
7
|
-
"user-agent": "claude-cli/2.1.
|
|
6
|
+
"user-agent": "claude-cli/2.1.330 (external, sdk-cli)",
|
|
8
7
|
"x-app": "cli",
|
|
9
8
|
"x-stainless-arch": "x64",
|
|
10
9
|
"x-stainless-lang": "js",
|
|
@@ -13,11 +12,11 @@ export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
|
|
|
13
12
|
"x-stainless-retry-count": "0",
|
|
14
13
|
"x-stainless-runtime": "node",
|
|
15
14
|
"x-stainless-runtime-version": "v26.12.1",
|
|
16
|
-
"x-stainless-timeout": "
|
|
15
|
+
"x-stainless-timeout": "600",
|
|
17
16
|
};
|
|
18
17
|
|
|
19
18
|
export const CODEX_CLI_CLIENT_HEADERS: Record<string, string> = {
|
|
20
|
-
"originator": "
|
|
21
|
-
"user-agent": "
|
|
22
|
-
"
|
|
19
|
+
"originator": "codex_cli_rs",
|
|
20
|
+
"user-agent": "codex_cli_rs/0.171.0 (Windows 10.0.26100; x86_64) unknown",
|
|
21
|
+
"version": "0.171.0",
|
|
23
22
|
};
|
|
@@ -6,12 +6,9 @@
|
|
|
6
6
|
import { cloneStringRecord, hasStringRecordEntries } from "../common.ts";
|
|
7
7
|
import { buildCodexClientHeaders } from "./codex-client-headers.ts";
|
|
8
8
|
import { t } from "../i18n.ts";
|
|
9
|
-
import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId,
|
|
9
|
+
import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
|
|
10
10
|
import { CLAUDE_CODE_CLIENT_HEADERS, CODEX_CLI_CLIENT_HEADERS } from "./builtin-client-headers.ts";
|
|
11
11
|
|
|
12
|
-
const ANTHROPIC_INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
|
|
13
|
-
|
|
14
|
-
|
|
15
12
|
export function getClientHeaderProfileLabel(profile: ClientHeaderProfileId): string {
|
|
16
13
|
if (profile === "recommended") return t("自动推荐");
|
|
17
14
|
if (profile === "disabled") return t("不添加");
|
|
@@ -19,30 +16,6 @@ export function getClientHeaderProfileLabel(profile: ClientHeaderProfileId): str
|
|
|
19
16
|
return profile === "claude-code" ? "ClaudeCode" : "Codex";
|
|
20
17
|
}
|
|
21
18
|
|
|
22
|
-
function removeAnthropicBetaFeature(headers: Record<string, string>, feature: string): void {
|
|
23
|
-
const betaHeaderKey = Object.keys(headers).find((name) => name.toLowerCase() === "anthropic-beta");
|
|
24
|
-
if (!betaHeaderKey) return;
|
|
25
|
-
const retained = headers[betaHeaderKey]!
|
|
26
|
-
.split(",")
|
|
27
|
-
.map((value) => value.trim())
|
|
28
|
-
.filter((value) => value && value !== feature);
|
|
29
|
-
if (retained.length > 0) headers[betaHeaderKey] = retained.join(",");
|
|
30
|
-
else delete headers[betaHeaderKey];
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function cloneHeadersForCompat(
|
|
34
|
-
headers: Record<string, string>,
|
|
35
|
-
api: ApiKind,
|
|
36
|
-
compat?: CompatSettings,
|
|
37
|
-
): Record<string, string> {
|
|
38
|
-
const cloned = cloneStringRecord(headers);
|
|
39
|
-
if (api === "anthropic-messages" && compat?.forceAdaptiveThinking === true) {
|
|
40
|
-
removeAnthropicBetaFeature(cloned, ANTHROPIC_INTERLEAVED_THINKING_BETA);
|
|
41
|
-
}
|
|
42
|
-
return cloned;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
|
|
46
19
|
/** 按大小写不敏感的字段名合并请求头,后者覆盖前者。 */
|
|
47
20
|
export function mergeModelRequestHeaders(
|
|
48
21
|
nativeHeaders: Record<string, string> | undefined,
|
|
@@ -92,7 +65,6 @@ export function getClientHeadersForProfile(
|
|
|
92
65
|
api: ApiKind,
|
|
93
66
|
customHeaders: Record<string, string>,
|
|
94
67
|
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>> = {},
|
|
95
|
-
compat?: CompatSettings,
|
|
96
68
|
): Record<string, string> | undefined {
|
|
97
69
|
const resolved = resolveClientHeaderProfile(profile, api);
|
|
98
70
|
if (resolved === "disabled") return undefined;
|
|
@@ -100,7 +72,8 @@ export function getClientHeadersForProfile(
|
|
|
100
72
|
const headers = hasStringRecordEntries(clientHeaderCaptures[resolved]?.headers)
|
|
101
73
|
? clientHeaderCaptures[resolved]!.headers
|
|
102
74
|
: CLAUDE_CODE_CLIENT_HEADERS;
|
|
103
|
-
|
|
75
|
+
// [喵喵喵]: 显式 beta 会禁用 Pi 的协议能力推导;抓包缓存只提供身份字段,不重放其条件性 beta。
|
|
76
|
+
return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "anthropic-beta"));
|
|
104
77
|
}
|
|
105
78
|
if (resolved === "codex-cli") {
|
|
106
79
|
const headers = hasStringRecordEntries(clientHeaderCaptures[resolved]?.headers)
|