pi-model-manager 0.4.4 → 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.
@@ -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 { HttpProxyAgent } from "http-proxy-agent";
11
- import { HttpsProxyAgent } from "https-proxy-agent";
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 getUrlPort(url: URL): number {
82
- if (url.port) return Number.parseInt(url.port, 10);
83
- return url.protocol === "https:" ? 443 : 80;
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 {
@@ -95,20 +189,19 @@ function ensureSupportedProxyProtocol(proxy: URL): void {
95
189
 
96
190
  function pipeResponse(upstreamResponse: IncomingMessage, response: ServerResponse, route: ProviderProxyRoute): void {
97
191
  const statusCode = upstreamResponse.statusCode ?? 502;
98
- // [喵喵喵]: 上游返回 3xx 重定向时,若重定向目标跨域,直接在代理层拦截,防止客户端在跟随重定向时泄露真实 IP
192
+ // [喵喵喵]: 同源绝对 Location 也可能让 SDK 离开本地代理直连上游;所有带 Location 的重定向均在代理层拒绝。
99
193
  if (statusCode >= 300 && statusCode < 400 && upstreamResponse.headers.location) {
194
+ let target = "[invalid Location]";
100
195
  try {
101
- const target = new URL(upstreamResponse.headers.location, route.upstreamOrigin);
102
- if (target.origin !== route.upstreamOrigin) {
103
- response.writeHead(502, { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" });
104
- response.end(t("代理安全拦截:上游返回了跨域重定向至 {target},已拒绝跟随", { target: target.origin }));
105
- // [喵喵喵]: 拦截后主动销毁上游响应,避免未消费的 body 占用 socket 直到超时
106
- upstreamResponse.destroy();
107
- return;
108
- }
196
+ target = new URL(upstreamResponse.headers.location, route.upstreamOrigin).origin;
109
197
  } catch {
110
- // 非法 location 则继续透传交由客户端处理
198
+ // [喵喵喵]: 非法 Location 同样拒绝,不把未知跳转交给客户端。
111
199
  }
200
+ const message = t("代理安全拦截:上游返回了重定向至 {target},已拒绝跟随", { target });
201
+ response.writeHead(502, { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" });
202
+ response.end(message);
203
+ upstreamResponse.destroy();
204
+ return;
112
205
  }
113
206
  const headers = stripHopByHopHeaders(upstreamResponse.headers);
114
207
  response.writeHead(statusCode, upstreamResponse.statusMessage, headers);
@@ -152,11 +245,18 @@ function buildForwardRequestHeaders(target: URL, request: IncomingMessage): Reco
152
245
  return headers;
153
246
  }
154
247
 
155
- function bindClientAbort(request: IncomingMessage, response: ServerResponse, upstreamRequest: http.ClientRequest): void {
248
+ function bindClientAbort(
249
+ request: IncomingMessage,
250
+ response: ServerResponse,
251
+ upstreamRequest: http.ClientRequest,
252
+ abortController: AbortController,
253
+ ): void {
156
254
  const destroyUpstream = () => {
255
+ abortController.abort();
157
256
  if (!upstreamRequest.destroyed) upstreamRequest.destroy();
158
257
  };
159
258
  const destroyUpstreamWithError = (error: Error) => {
259
+ abortController.abort(error);
160
260
  if (!upstreamRequest.destroyed) upstreamRequest.destroy(error);
161
261
  };
162
262
  const onResponseClose = () => {
@@ -178,44 +278,6 @@ function writeUpstreamRequestError(response: ServerResponse, error: Error): void
178
278
  writeProxyError(response, error);
179
279
  }
180
280
 
181
- function forwardPlainHttp(target: URL, proxy: URL, request: IncomingMessage, response: ServerResponse, route: ProviderProxyRoute): void {
182
- ensureSupportedProxyProtocol(proxy);
183
- const headers = buildForwardRequestHeaders(target, request);
184
- const agent = new HttpProxyAgent(proxy);
185
- const upstreamRequest = http.request({
186
- hostname: target.hostname,
187
- port: getUrlPort(target),
188
- method: request.method,
189
- path: `${target.pathname}${target.search}`,
190
- headers,
191
- agent,
192
- }, (upstreamResponse) => pipeResponse(upstreamResponse, response, route));
193
- upstreamRequest.once("close", () => agent.destroy());
194
- bindClientAbort(request, response, upstreamRequest);
195
- upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
196
- // [喵喵喵]: 请求体直接流向上游,避免图像等大 payload 在本地代理中形成完整内存副本 (2026-07-17)
197
- // [喵喵喵]: 等代理完成请求头重建后再流式读取 body,避免 chunked 请求在异步建连期间重复写入 HTTP 头。
198
- upstreamRequest.once("socket", () => request.pipe(upstreamRequest));
199
- }
200
-
201
- function forwardHttps(target: URL, proxy: URL, request: IncomingMessage, response: ServerResponse, route: ProviderProxyRoute): void {
202
- ensureSupportedProxyProtocol(proxy);
203
- const headers = buildForwardRequestHeaders(target, request);
204
- const agent = new HttpsProxyAgent(proxy);
205
- const upstreamRequest = https.request({
206
- hostname: target.hostname,
207
- port: getUrlPort(target),
208
- method: request.method,
209
- path: `${target.pathname}${target.search}`,
210
- headers,
211
- agent,
212
- }, (upstreamResponse) => pipeResponse(upstreamResponse, response, route));
213
- upstreamRequest.once("close", () => agent.destroy());
214
- bindClientAbort(request, response, upstreamRequest);
215
- upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
216
- upstreamRequest.once("socket", () => request.pipe(upstreamRequest));
217
- }
218
-
219
281
  function forwardRequest(route: ProviderProxyRoute, request: IncomingMessage, response: ServerResponse, routePath: string): void {
220
282
  const target = new URL(routePath, route.upstreamOrigin);
221
283
  // [喵喵喵]: 强制校验解析后的 target.origin 严格等于受管的 upstreamOrigin,阻断 SSRF 任意上游转发
@@ -225,16 +287,36 @@ function forwardRequest(route: ProviderProxyRoute, request: IncomingMessage, res
225
287
  expected: route.upstreamOrigin,
226
288
  }));
227
289
  }
228
- const proxy = new URL(route.proxyUrl);
229
- if (target.protocol === "http:") {
230
- forwardPlainHttp(target, proxy, request, response, route);
231
- return;
290
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
291
+ throw new Error(t("不支持的上游协议:{protocol}", { protocol: target.protocol }));
232
292
  }
233
- if (target.protocol === "https:") {
234
- forwardHttps(target, proxy, request, response, route);
235
- return;
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;
236
310
  }
237
- throw new Error(t("不支持的上游协议:{protocol}", { protocol: target.protocol }));
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));
238
320
  }
239
321
 
240
322
  function handleRequest(request: IncomingMessage, response: ServerResponse): void {
@@ -313,6 +395,7 @@ async function ensureServer(): Promise<number> {
313
395
  }
314
396
 
315
397
  async function ensureServerForRoute(): Promise<number> {
398
+ ensureNativeProxySupport();
316
399
  const port = await ensureServer();
317
400
  if (closingPromise) throw new Error(t("本地代理服务正在关闭,请稍后重试"));
318
401
  return port;
@@ -323,6 +406,7 @@ export async function getLocalProxyBaseUrl(routeId: string, upstreamRuntimeBaseU
323
406
  const proxy = parseHttpProxyUrl(proxyUrl);
324
407
  const port = await ensureServerForRoute();
325
408
  ROUTES.set(routeId, {
409
+ providerId: routeId,
326
410
  upstreamOrigin: upstream.origin,
327
411
  proxyUrl: proxy.toString(),
328
412
  });
@@ -339,7 +423,7 @@ export async function openTemporaryLocalProxyRoute(
339
423
  const proxy = parseHttpProxyUrl(proxyUrl);
340
424
  const port = await ensureServerForRoute();
341
425
  const routeId = `${providerId}/model-list/${randomUUID()}`;
342
- const route = { upstreamOrigin: upstream.origin, proxyUrl: proxy.toString() };
426
+ const route = { providerId, upstreamOrigin: upstream.origin, proxyUrl: proxy.toString() };
343
427
  ROUTES.set(routeId, route);
344
428
  const basePath = trimTrailingSlashes(upstream.pathname || "");
345
429
  return {
@@ -387,21 +471,28 @@ async function closeServerLifecycle(): Promise<void> {
387
471
  }
388
472
  }
389
473
  const current = server;
390
- if (!current) return;
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();
391
486
  try {
392
- if (current.listening) {
393
- await new Promise<void>((resolve, reject) => {
394
- current.close((error) => error ? reject(error) : resolve());
395
- });
396
- }
487
+ await pendingClose;
397
488
  } finally {
398
- clearServerState(current);
489
+ if (current) clearServerState(current);
399
490
  }
400
491
  }
401
492
 
402
493
  export async function closeLocalProxyServer(): Promise<void> {
403
494
  if (closingPromise) return closingPromise;
404
- const operation = closeServerLifecycle();
495
+ const operation = Promise.resolve().then(closeServerLifecycle);
405
496
  closingPromise = operation;
406
497
  try {
407
498
  await operation;
@@ -23,7 +23,7 @@ import {
23
23
  } from "./models-json-sync.ts";
24
24
  import { reconcileProvider, unregisterManagedProvider } from "./provider-registrar.ts";
25
25
  import { withModelRescue } from "./rescue.ts";
26
- import { deleteModelFromDocument, deleteProviderFromDocument, getModelFullId, upsertModelInDocument, upsertProviderInDocument } from "./state-document.ts";
26
+ import { deleteModelFromDocument, deleteProviderFromDocument, getModelFullId, upsertModelInDocument, upsertProviderInDocument, validateModelDraft, validateProviderDraft } from "./state-document.ts";
27
27
  import type { StateDocument, StoredProvider } from "./types.ts";
28
28
  import type { createModelDraftForStoredProvider, createProviderDraft } from "./state-document.ts";
29
29
 
@@ -87,6 +87,12 @@ export async function saveProviderConfiguration(
87
87
  await assertProviderIsEditable(draft.providerId);
88
88
  if (oldProviderId) await assertProviderIsEditable(oldProviderId);
89
89
  const prepare = (latest: StateDocument) => {
90
+ if (oldProviderId && !latest.providers[oldProviderId]) {
91
+ throw new Error(t("接入配置已不存在:{providerId}", { providerId: oldProviderId }));
92
+ }
93
+ // [喵喵喵]: UI 校验之后可能有其它进程保存;必须在锁内针对最新状态重验创建和重命名前提。
94
+ const errors = validateProviderDraft(draft, latest, new Set(), oldProviderId);
95
+ if (errors.length > 0) throw new Error(errors.join("\n"));
90
96
  const document = upsertProviderInDocument(latest, oldProviderId, draft);
91
97
  return { document, changedProviderIds: [draft.providerId], removedProviderIds: [] };
92
98
  };
@@ -139,6 +145,11 @@ export async function saveModelConfiguration(
139
145
  await assertProviderIsEditable(draft.providerId);
140
146
  const newModelId = draft.modelId.trim();
141
147
  const prepare = (latest: StateDocument) => {
148
+ if (replacedModelId && !latest.providers[draft.providerId]?.models.some((model) => model.id === replacedModelId)) {
149
+ throw new Error(t("模型不存在:{fullId}", { fullId: getModelFullId(draft.providerId, replacedModelId) }));
150
+ }
151
+ const errors = validateModelDraft(draft, latest, replacedModelId);
152
+ if (errors.length > 0) throw new Error(errors.join("\n"));
142
153
  const document = upsertModelInDocument(latest, draft, { replacedModelId });
143
154
  return { document, changedProviderIds: [draft.providerId], removedProviderIds: [] };
144
155
  };
@@ -175,7 +186,11 @@ export async function saveNewProviderWithModelConfiguration(
175
186
  ): Promise<void> {
176
187
  await assertProviderIsEditable(providerDraft.providerId);
177
188
  const prepare = (latest: StateDocument) => {
189
+ const providerErrors = validateProviderDraft(providerDraft, latest, new Set());
190
+ if (providerErrors.length > 0) throw new Error(providerErrors.join("\n"));
178
191
  const withProvider = upsertProviderInDocument(latest, undefined, providerDraft);
192
+ const modelErrors = validateModelDraft(modelDraft, withProvider);
193
+ if (modelErrors.length > 0) throw new Error(modelErrors.join("\n"));
179
194
  const document = upsertModelInDocument(withProvider, modelDraft);
180
195
  return { document, changedProviderIds: [providerDraft.providerId], removedProviderIds: [] };
181
196
  };
@@ -98,7 +98,11 @@ function createEmpty(): ModelsJsonDocument {
98
98
  function parseModelsJson(source: string): ModelsJsonDocument {
99
99
  const parsed = JSON.parse(stripJsonNoise(source));
100
100
  if (!isObjectRecord(parsed)) throw new Error(t("models.json 根节点必须是对象"));
101
- const providers = isObjectRecord(parsed.providers) ? parsed.providers : {};
101
+ // [喵喵喵]: 字段缺失可以初始化;已有字段类型损坏必须拒写,不能把原始内容当空目录覆盖。
102
+ if (Object.hasOwn(parsed, "providers") && !isObjectRecord(parsed.providers)) {
103
+ throw new Error(t("{path} 必须是对象", { path: "models.json.providers" }));
104
+ }
105
+ const providers = parsed.providers ?? {};
102
106
  return { ...parsed, providers: providers as Record<string, ModelsJsonProviderEntry> };
103
107
  }
104
108
 
@@ -1,6 +1,6 @@
1
1
  // openai-responses-recovery.ts
2
2
  //
3
- // Responses 跨资源状态恢复:按失败请求隔离旧状态,正常请求及后续新状态不降级。
3
+ // Responses 跨资源状态恢复:仅在指定错误后剥离失败历史的 item ID,完整保留推理内容。
4
4
 
5
5
  import { createHash } from "node:crypto";
6
6
  import type {
@@ -57,19 +57,13 @@ function isReplayState(value: unknown): value is ReplayState {
57
57
 
58
58
  function collectState(payload: Record<string, unknown>, scope: string): ReplayState {
59
59
  const itemIds = new Set<string>();
60
- const encryptedHashes = new Set<string>();
61
60
  for (const item of payload.input as unknown[]) {
62
61
  if (!isObjectRecord(item)) continue;
63
62
  // [喵喵喵]: msg_pi_* 是 Pi 本地生成的占位 ID;压缩后可能复用,不能当成上游资源 ID 隔离。
64
63
  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
64
  }
69
- return {
70
- version: 1, scope, itemIds: [...itemIds], encryptedHashes: [...encryptedHashes],
71
- previousResponseIds: typeof payload.previous_response_id === "string" ? [payload.previous_response_id] : [],
72
- };
65
+ // [喵喵喵]: 延用既有分支记录格式,但不再记录或清理密文哈希及 response 引用。
66
+ return { version: 1, scope, itemIds: [...itemIds], encryptedHashes: [], previousResponseIds: [] };
73
67
  }
74
68
 
75
69
  function canReplayItem(item: unknown): boolean {
@@ -87,58 +81,36 @@ function canReplayItem(item: unknown): boolean {
87
81
  }
88
82
  }
89
83
 
90
- function stripQuarantinedState(
84
+ function stripQuarantinedItemIds(
91
85
  payload: Record<string, unknown>,
92
86
  ctx: ExtensionContext,
93
87
  scope: string,
94
88
  ): Record<string, unknown> | undefined {
95
89
  const itemIds = new Set<string>();
96
- const encryptedHashes = new Set<string>();
97
- const previousResponseIds = new Set<string>();
98
- // [喵喵喵]: 只读当前分支的恢复记录,重载后继续隔离旧状态,不污染其它分支或其它模型。
90
+ // [喵喵喵]: 仅剥离当前分支已报错的历史 ID;重载后继续生效,其它分支及后续新 ID 不受影响。
99
91
  for (const entry of ctx.sessionManager.getBranch()) {
100
92
  if (entry.type !== "custom" || entry.customType !== RECOVERY_ENTRY_TYPE
101
93
  || !isReplayState(entry.data) || entry.data.scope !== scope) continue;
102
94
  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
95
  }
106
- if (!itemIds.size && !encryptedHashes.size && !previousResponseIds.size) return undefined;
96
+ if (!itemIds.size) return undefined;
107
97
 
108
98
  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
- }
99
+ const input = (payload.input as unknown[]).map((item) => {
100
+ if (!isObjectRecord(item) || typeof item.id !== "string" || !itemIds.has(item.id)) return item;
101
+ // [喵喵喵]: reasoning、message 和 function_call 的旧 ID 必须一起剥离,避免残留关联校验;密文与 call_id 原样保留。
123
102
  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];
103
+ delete next.id;
104
+ changed = true;
105
+ return next;
132
106
  });
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;
107
+ return changed ? { ...payload, input } : undefined;
138
108
  }
139
109
 
140
110
  function isRecoverableError(message: string): boolean {
141
- 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
+ || /\bItem with id ['"][^'"\r\n]+['"] (?:was )?not found\b/i.test(message)
113
+ || /\bwas provided without its required ['"]reasoning['"] item\b/i.test(message)
142
114
  || /\binvalid_encrypted_content\b/i.test(message)
143
115
  || /\bencrypted content(?:\s+\S+)?(?:\s+for item\s+\S+)?\s+could not be (?:verified|decrypted)\b/i.test(message);
144
116
  }
@@ -150,23 +122,25 @@ function notify(ctx: ExtensionContext, key: MessageKey, snapshot: RequestSnapsho
150
122
  export function createOpenAIResponsesRecovery() {
151
123
  let lastRequest: RequestSnapshot | undefined;
152
124
  let pendingRecovery: RequestSnapshot | undefined;
153
- let attempted = false;
154
125
 
155
126
  return {
156
127
  beginActivity(): void {
157
128
  lastRequest = undefined;
158
129
  pendingRecovery = undefined;
159
- attempted = false;
160
130
  },
161
131
 
162
- transform(payload: unknown, ctx: ExtensionContext, state: StateDocument): unknown | undefined {
132
+ beginRequest(): void {
163
133
  lastRequest = undefined;
134
+ },
135
+
136
+ transform(payload: unknown, ctx: ExtensionContext, state: StateDocument): unknown | undefined {
164
137
  const model = enabledModel(ctx, state);
165
- if (!model || !isObjectRecord(payload) || payload.model !== model.id || !Array.isArray(payload.input)) return undefined;
166
- // [喵喵喵]: 服务端引用、压缩项及未知资源项无法安全重建,不把不完整历史误当成完整回放。
138
+ if (!model || !isObjectRecord(payload) || payload.model !== model.id || payload.store === true
139
+ || !Array.isArray(payload.input)) return undefined;
140
+ // [喵喵喵]: 服务端引用、压缩项及未知资源项的 ID 可能不可省略,不对这些请求自动剥离重放。
167
141
  if (!payload.input.every(canReplayItem)) return undefined;
168
142
  const scope = scopeFor(model);
169
- const transformed = stripQuarantinedState(payload, ctx, scope);
143
+ const transformed = stripQuarantinedItemIds(payload, ctx, scope);
170
144
  lastRequest = {
171
145
  state: collectState(transformed ?? payload, scope), provider: model.provider,
172
146
  model: model.id, sessionId: ctx.sessionManager.getSessionId(),
@@ -175,7 +149,7 @@ export function createOpenAIResponsesRecovery() {
175
149
  },
176
150
 
177
151
  async recover(event: AgentBeforeSettleEvent, ctx: ExtensionContext): Promise<BoundaryResult | undefined> {
178
- if (!lastRequest || attempted || event.outcome !== "error") return undefined;
152
+ if (!lastRequest || event.outcome !== "error") return undefined;
179
153
  const snapshot = lastRequest;
180
154
  const model = enabledModel(ctx, await readCachedState());
181
155
  if (!model || scopeFor(model) !== snapshot.state.scope || ctx.sessionManager.getSessionId() !== snapshot.sessionId) return undefined;
@@ -185,15 +159,14 @@ export function createOpenAIResponsesRecovery() {
185
159
  if (!failedEntry || !message || message.role !== "assistant" || message.stopReason !== "error"
186
160
  || message.provider !== snapshot.provider || message.model !== snapshot.model || message.api !== "openai-responses"
187
161
  || 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;
162
+ if (!snapshot.state.itemIds.length) return undefined;
190
163
 
191
- // [喵喵喵]: 报错通常不指明具体失效项,只能隔离该失败请求携带的旧状态;不触碰正文和 call_id。
192
- // [喵喵喵]: 原始历史保留,仅追加分支状态与失败回复的上下文省略;同一次用户运行最多恢复一次。
164
+ // [喵喵喵]: 只记录失败请求携带的旧 item ID;无法定位具体失效项时成组剥离,不触碰推理密文、正文和 call_id。
165
+ // [喵喵喵]: 原始历史保留,仅追加分支状态与失败回复的上下文省略;恢复不设次数上限,旧 ID 已全部剥离时不再原样重放。
193
166
  // [喵喵喵]: 错误 assistant 尚在上下文时 canContinue 为 false;省略它后由宿主重新校验,不能提前据此拒绝恢复。
194
- attempted = true;
167
+ lastRequest = undefined;
195
168
  pendingRecovery = snapshot;
196
- notify(ctx, "{model}:已隔离本次失败携带的旧状态,正在自动重试一次。", snapshot);
169
+ notify(ctx, "{model}:将剥离本次失败历史的 item ID,保留思维链并自动重试一次。", snapshot);
197
170
  return {
198
171
  entries: [
199
172
  // [喵喵喵]: 边界 entries 是整体替换,必须保留前序扩展的提案后再追加恢复记录。
@@ -216,7 +189,7 @@ export function createOpenAIResponsesRecovery() {
216
189
  } else if (message.stopReason === "aborted") {
217
190
  notify(ctx, "{model}:跨资源自动恢复已取消,未继续重试。", snapshot, true);
218
191
  } else {
219
- notify(ctx, "{model}:跨资源自动恢复成功;后续新推理状态正常保留。", snapshot);
192
+ notify(ctx, "{model}:跨资源自动恢复成功;思维链完整保留,后续新 item ID 正常保留。", snapshot);
220
193
  }
221
194
  },
222
195