pi-model-manager 0.3.5 → 0.4.0

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/package.json CHANGED
@@ -1,83 +1,85 @@
1
- {
2
- "name": "pi-model-manager",
3
- "version": "0.3.5",
4
- "description": "A TUI model and provider manager for Pi with native models.json persistence, request-header profiles, proxy routing, and protocol compatibility.",
5
- "type": "module",
6
- "main": "./index.ts",
7
- "scripts": {
8
- "test": "node --experimental-strip-types --import ./tests/register-test-loader.mjs --test --test-reporter=spec tests/*.test.ts"
9
- },
10
- "files": [
11
- "NOTICE",
12
- "README.en.md",
13
- "index.ts",
14
- "i18n.ts",
15
- "ui-language-settings.ts",
16
- "state-store.ts",
17
- "state-metadata-store.ts",
18
- "state-cache.ts",
19
- "state-document.ts",
20
- "openai-responses-payload.ts",
21
- "openai-service-tier.ts",
22
- "claude-code-compat.ts",
23
- "builtin-model-catalog.ts",
24
- "models-json-manager.ts",
25
- "models-json-sync.ts",
26
- "provider-registrar.ts",
27
- "provider-transport.ts",
28
- "local-proxy-service.ts",
29
- "request-pipeline.ts",
30
- "model-mutations.ts",
31
- "header-profile-mutations.ts",
32
- "rescue.ts",
33
- "atomic-write.ts",
34
- "common.ts",
35
- "config-value-reference.ts",
36
- "configuration-persistence.ts",
37
- "configuration-lock.ts",
38
- "file-snapshot.ts",
39
- "sensitive-redaction.ts",
40
- "compat-settings.ts",
41
- "runtime-base-url.ts",
42
- "types.ts",
43
- "tui/",
44
- "presets/"
45
- ],
46
- "keywords": [
47
- "pi-package",
48
- "pi-extension",
49
- "pi",
50
- "model-manager",
51
- "provider-manager",
52
- "models-json",
53
- "client-headers",
54
- "openai",
55
- "anthropic"
56
- ],
57
- "author": "Qihuanxishini",
58
- "license": "AGPL-3.0-only",
59
- "repository": {
60
- "type": "git",
61
- "url": "git+https://github.com/Qihuanxishini/pi-model-manager.git"
62
- },
63
- "homepage": "https://github.com/Qihuanxishini/pi-model-manager#readme",
64
- "bugs": {
65
- "url": "https://github.com/Qihuanxishini/pi-model-manager/issues"
66
- },
67
- "pi": {
68
- "extensions": [
69
- "./index.ts"
70
- ]
71
- },
72
- "peerDependencies": {
73
- "@earendil-works/pi-coding-agent": ">=0.85.1",
74
- "@earendil-works/pi-ai": ">=0.85.1",
75
- "@earendil-works/pi-tui": ">=0.75.0"
76
- },
77
- "dependencies": {
78
- "http-proxy-agent": "^9.1.0",
79
- "https-proxy-agent": "^9.1.0",
80
- "minimatch": "^10.2.6",
81
- "proper-lockfile": "^4.1.2"
82
- }
83
- }
1
+ {
2
+ "name": "pi-model-manager",
3
+ "version": "0.4.0",
4
+ "description": "A TUI model and provider manager for Pi with native models.json persistence, request-header profiles, proxy routing, and protocol compatibility.",
5
+ "type": "module",
6
+ "main": "./index.ts",
7
+ "scripts": {
8
+ "test": "node --experimental-strip-types --import ./tests/register-test-loader.mjs --test --test-reporter=spec tests/*.test.ts",
9
+ "test:runtime": "node --experimental-strip-types --import ./tests/register-runtime-loader.mjs --test --test-reporter=spec tests/*-wire.test.ts"
10
+ },
11
+ "files": [
12
+ "NOTICE",
13
+ "README.en.md",
14
+ "index.ts",
15
+ "i18n.ts",
16
+ "ui-language-settings.ts",
17
+ "state-store.ts",
18
+ "state-metadata-store.ts",
19
+ "state-cache.ts",
20
+ "state-document.ts",
21
+ "openai-responses-payload.ts",
22
+ "openai-service-tier.ts",
23
+ "claude-code-compat.ts",
24
+ "builtin-model-catalog.ts",
25
+ "models-json-manager.ts",
26
+ "models-json-sync.ts",
27
+ "provider-registrar.ts",
28
+ "provider-transport.ts",
29
+ "local-proxy-service.ts",
30
+ "request-pipeline.ts",
31
+ "model-mutations.ts",
32
+ "header-profile-mutations.ts",
33
+ "rescue.ts",
34
+ "atomic-write.ts",
35
+ "proper-lockfile.d.ts",
36
+ "common.ts",
37
+ "config-value-reference.ts",
38
+ "configuration-persistence.ts",
39
+ "configuration-lock.ts",
40
+ "file-snapshot.ts",
41
+ "sensitive-redaction.ts",
42
+ "compat-settings.ts",
43
+ "runtime-base-url.ts",
44
+ "types.ts",
45
+ "tui/",
46
+ "presets/"
47
+ ],
48
+ "keywords": [
49
+ "pi-package",
50
+ "pi-extension",
51
+ "pi",
52
+ "model-manager",
53
+ "provider-manager",
54
+ "models-json",
55
+ "client-headers",
56
+ "openai",
57
+ "anthropic"
58
+ ],
59
+ "author": "Qihuanxishini",
60
+ "license": "AGPL-3.0-only",
61
+ "repository": {
62
+ "type": "git",
63
+ "url": "git+https://github.com/Qihuanxishini/pi-model-manager.git"
64
+ },
65
+ "homepage": "https://github.com/Qihuanxishini/pi-model-manager#readme",
66
+ "bugs": {
67
+ "url": "https://github.com/Qihuanxishini/pi-model-manager/issues"
68
+ },
69
+ "pi": {
70
+ "extensions": [
71
+ "./index.ts"
72
+ ]
73
+ },
74
+ "peerDependencies": {
75
+ "@earendil-works/pi-coding-agent": "*",
76
+ "@earendil-works/pi-ai": "*",
77
+ "@earendil-works/pi-tui": "*"
78
+ },
79
+ "dependencies": {
80
+ "http-proxy-agent": "^9.1.0",
81
+ "https-proxy-agent": "^9.1.0",
82
+ "minimatch": "^10.2.6",
83
+ "proper-lockfile": "^4.1.2"
84
+ }
85
+ }
@@ -1,15 +1,15 @@
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,prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,effort-2025-11-24",
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,prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,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.263 (external, sdk-cli)",
7
+ "user-agent": "claude-cli/2.1.296 (external, sdk-cli)",
8
8
  "x-app": "cli",
9
9
  "x-stainless-arch": "x64",
10
10
  "x-stainless-lang": "js",
11
11
  "x-stainless-os": "Windows",
12
- "x-stainless-package-version": "0.112.1",
12
+ "x-stainless-package-version": "0.128.0",
13
13
  "x-stainless-retry-count": "0",
14
14
  "x-stainless-runtime": "node",
15
15
  "x-stainless-runtime-version": "v26.3.0",
@@ -18,6 +18,6 @@ export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
18
18
 
19
19
  export const CODEX_CLI_CLIENT_HEADERS: Record<string, string> = {
20
20
  "originator": "codex-tui",
21
- "user-agent": "codex-tui/0.152.1 (Windows 10.0.26200; x86_64) unknown (codex-tui; 0.152.1)",
21
+ "user-agent": "codex-tui/0.162.1 (Windows 10.0.26300; x86_64) WindowsTerminal (codex-tui; 0.162.1)",
22
22
  "x-codex-beta-features": "remote_compaction_v2",
23
23
  };
@@ -66,7 +66,7 @@ const PROVIDER_PRESETS: ProviderPreset[] = [
66
66
  apiKey: "$GEMINI_API_KEY",
67
67
  authHeader: false,
68
68
  contextWindow: 1048576,
69
- maxTokens: 65536,
69
+ maxTokens: 64000,
70
70
  inputKinds: ["text", "image"],
71
71
  defaultReasoning: true,
72
72
  },
@@ -105,6 +105,10 @@ export function switchProviderDraftApiPreset(draft: ProviderDraft, nextApi: ApiK
105
105
  }
106
106
  // [喵喵喵]: 版本路径规则随协议而变(OpenAI 要 /v1、Anthropic 不要),
107
107
  // 保留的自定义地址必须按新协议重新归一化,否则切完协议就指向错误端点。
108
- draft.baseUrl = replaceBaseUrl ? nextPreset.baseUrl : resolveRuntimeBaseUrl(nextApi, draft.baseUrl);
108
+ try {
109
+ draft.baseUrl = replaceBaseUrl ? nextPreset.baseUrl : resolveRuntimeBaseUrl(nextApi, draft.baseUrl);
110
+ } catch {
111
+ draft.baseUrl = nextPreset.baseUrl;
112
+ }
109
113
  if (replaceApiKey) draft.apiKey = nextPreset.apiKey;
110
114
  }
@@ -0,0 +1,18 @@
1
+ // proper-lockfile 4.x 不自带类型声明;这里仅为本仓库实际用到的 API 提供最小签名。
2
+ declare module "proper-lockfile" {
3
+ export interface LockOptions {
4
+ realpath?: boolean | null;
5
+ retries?: number | { retries: number; factor: number; minTimeout: number; maxTimeout: number };
6
+ }
7
+
8
+ export function lock(path: string, options?: LockOptions): Promise<() => Promise<void>>;
9
+ export function unlock(path: string, options?: LockOptions): Promise<void>;
10
+ export function check(path: string, options?: LockOptions): Promise<boolean>;
11
+
12
+ const properLockfile: {
13
+ lock: typeof lock;
14
+ unlock: typeof unlock;
15
+ check: typeof check;
16
+ };
17
+ export default properLockfile;
18
+ }
@@ -8,6 +8,88 @@ import { getProviderHttpProxyUrl, openTemporaryLocalProxyRoute } from "./local-p
8
8
  import { appendUrlPath, resolveRuntimeBaseUrl, validateRequestBaseUrl } from "./runtime-base-url.ts";
9
9
  import type { ApiKind, StoredProvider } from "./types.ts";
10
10
 
11
+ const RESPONSES_TERMINAL_EVENTS = new Set([
12
+ "response.completed",
13
+ "response.incomplete",
14
+ "response.failed",
15
+ "error",
16
+ ]);
17
+
18
+ function findSseFrameBoundary(buffer: Uint8Array): number {
19
+ for (let index = 0; index < buffer.length; index += 1) {
20
+ if (buffer[index] === 10 && buffer[index + 1] === 10) return index + 2;
21
+ if (buffer[index] === 13 && buffer[index + 1] === 13) return index + 2;
22
+ if (buffer[index] === 13 && buffer[index + 1] === 10 && buffer[index + 2] === 13 && buffer[index + 3] === 10) return index + 4;
23
+ }
24
+ return -1;
25
+ }
26
+
27
+ function isResponsesTerminalFrame(frame: Uint8Array): boolean {
28
+ const text = new TextDecoder().decode(frame);
29
+ let eventType: string | undefined;
30
+ const dataLines: string[] = [];
31
+ for (const line of text.split(/\r?\n|\r/)) {
32
+ if (line.startsWith("event:")) eventType = line.slice("event:".length).trim();
33
+ if (line.startsWith("data:")) dataLines.push(line.slice("data:".length).trimStart());
34
+ }
35
+ if (eventType && RESPONSES_TERMINAL_EVENTS.has(eventType)) return true;
36
+ const data = dataLines.join("\n").trim();
37
+ if (!data || data === "[DONE]") return false;
38
+ try {
39
+ const parsed = JSON.parse(data) as { type?: unknown };
40
+ return typeof parsed.type === "string" && RESPONSES_TERMINAL_EVENTS.has(parsed.type);
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+
46
+ function appendBytes(left: Uint8Array, right: Uint8Array): Uint8Array {
47
+ const combined = new Uint8Array(left.length + right.length);
48
+ combined.set(left);
49
+ combined.set(right, left.length);
50
+ return combined;
51
+ }
52
+
53
+ function wrapResponsesTerminalStream(response: Response): Response {
54
+ if (!response.body || !response.ok) return response;
55
+ const reader = response.body.getReader();
56
+ let buffer = new Uint8Array();
57
+ let terminal = false;
58
+ const body = new ReadableStream<Uint8Array>({
59
+ async pull(controller) {
60
+ while (!terminal) {
61
+ const boundary = findSseFrameBoundary(buffer);
62
+ if (boundary >= 0) {
63
+ const frame = buffer.slice(0, boundary);
64
+ buffer = buffer.slice(boundary);
65
+ terminal = isResponsesTerminalFrame(frame);
66
+ controller.enqueue(frame);
67
+ if (terminal) {
68
+ controller.close();
69
+ await reader.cancel().catch(() => {});
70
+ }
71
+ return;
72
+ }
73
+ const next = await reader.read();
74
+ if (next.done) {
75
+ if (buffer.length > 0) controller.enqueue(buffer);
76
+ controller.close();
77
+ return;
78
+ }
79
+ buffer = appendBytes(buffer, next.value);
80
+ }
81
+ },
82
+ cancel(reason) {
83
+ return reader.cancel(reason);
84
+ },
85
+ });
86
+ return new Response(body, {
87
+ status: response.status,
88
+ statusText: response.statusText,
89
+ headers: response.headers,
90
+ });
91
+ }
92
+
11
93
  export function createProviderTransport(runtime: ModelRuntime, native: Provider, provider: StoredProvider): Provider {
12
94
  const endpoints = new Map(provider.models.map((model) => {
13
95
  const api = model.api ?? provider.api;
@@ -48,7 +130,11 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
48
130
  if (proxyUrl) throw new Error(t("该协议尚不支持接入级代理:{api}", { api: model.api }));
49
131
  return stream(upstreamModel, context, options);
50
132
  }
51
- if (!proxyUrl && model.api !== "anthropic-messages") return stream(upstreamModel, context, options);
133
+ if (!proxyUrl
134
+ && model.api !== "anthropic-messages"
135
+ && !(model.api === "openai-responses" && provider.openAIResponsesStreamCompletionMode === "terminal-event")) {
136
+ return stream(upstreamModel, context, options);
137
+ }
52
138
  const fetchImpl = options?.fetch ?? globalThis.fetch;
53
139
  const transportFetch: typeof fetch = async (input, init) => {
54
140
  let request = new Request(input, init);
@@ -62,14 +148,25 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
62
148
  url.pathname = new URL(appendUrlPath(endpoint.baseUrl, "messages")).pathname;
63
149
  request = new Request(url, request);
64
150
  }
65
- if (!proxyUrl) return fetchImpl(request);
66
- const route = await openTemporaryLocalProxyRoute(native.id, request.url, proxyUrl);
67
- try {
68
- return await fetchImpl(new Request(route.url, request));
69
- } finally {
70
- // [喵喵喵]: 收到响应头时转发端已经取得路由;删除查找项不会中断已建立的 SSE 流。
71
- route.close();
151
+ let response: Response;
152
+ if (!proxyUrl) {
153
+ response = await fetchImpl(request);
154
+ } else {
155
+ const route = await openTemporaryLocalProxyRoute(native.id, request.url, proxyUrl);
156
+ try {
157
+ // [喵喵喵]: 经由本地代理转发时强制禁止自动跟随重定向,防止客户端绕过代理直连上游
158
+ response = await fetchImpl(new Request(route.url, new Request(request, { redirect: "manual" })));
159
+ } finally {
160
+ // [喵喵喵]: 收到响应头时转发端已经取得路由;删除查找项不会中断已建立的 SSE 流。
161
+ route.close();
162
+ }
163
+ }
164
+ if (model.api === "openai-responses"
165
+ && provider.openAIResponsesStreamCompletionMode === "terminal-event") {
166
+ // [喵喵喵]: 某些中转已发出正式终态事件却保持连接;完整转交该 frame 后即可按协议结束本地流。
167
+ return wrapResponsesTerminalStream(response);
72
168
  }
169
+ return response;
73
170
  };
74
171
  return stream(upstreamModel, context, { ...options, fetch: transportFetch });
75
172
  });
@@ -57,9 +57,14 @@ export function fromNativeBaseUrl(
57
57
  legacyNormalization = false,
58
58
  ): string {
59
59
  if (api !== "anthropic-messages" || anthropicApiRoot) return baseUrl;
60
- const url = new URL(baseUrl.trim());
61
- trimPath(url);
62
- // [喵喵喵]: 旧版插件在注册前剥去末尾 /v1;读取旧配置必须先复现该行为再显式补回版本路径。
63
- if (legacyNormalization && url.pathname.toLowerCase().endsWith("/v1")) url.pathname = url.pathname.slice(0, -3) || "/";
64
- return appendUrlPath(formatUrl(url), "v1");
60
+ try {
61
+ const url = new URL(baseUrl.trim());
62
+ trimPath(url);
63
+ // [喵喵喵]: 旧版插件在注册前剥去末尾 /v1;读取旧配置必须先复现该行为再显式补回版本路径。
64
+ if (legacyNormalization && url.pathname.toLowerCase().endsWith("/v1")) url.pathname = url.pathname.slice(0, -3) || "/";
65
+ return appendUrlPath(formatUrl(url), "v1");
66
+ } catch {
67
+ // [喵喵喵]: 受控简化 — 解析失败的 Base URL 原样返回交由上层校验拦截;边界:非交互调用方(如状态读回)拿不到提示;升级:出现排查诉求时为读回路径接入统一的告警通道
68
+ return baseUrl;
69
+ }
65
70
  }
package/state-document.ts CHANGED
@@ -90,6 +90,7 @@ export function createProviderDraft(api: ApiKind = "openai-responses"): Provider
90
90
  customClientHeaders: {},
91
91
  httpProxyEnabled: false,
92
92
  httpProxyUrl: DEFAULT_PROVIDER_HTTP_PROXY_URL,
93
+ openAIResponsesStreamCompletionMode: "standard",
93
94
  selectedIndex: 0,
94
95
  };
95
96
  }
@@ -110,6 +111,7 @@ export function createProviderDraftFromStored(providerId: string, stored: Stored
110
111
  customClientHeaders: cloneStringRecord(stored.customClientHeaders),
111
112
  httpProxyEnabled: stored.httpProxyEnabled ?? false,
112
113
  httpProxyUrl: stored.httpProxyUrl?.trim() || DEFAULT_PROVIDER_HTTP_PROXY_URL,
114
+ openAIResponsesStreamCompletionMode: stored.openAIResponsesStreamCompletionMode ?? "standard",
113
115
  selectedIndex: 0,
114
116
  };
115
117
  }
@@ -128,6 +130,7 @@ function createModelDraftFromProvider(providerDraft: ProviderDraft): ModelDraft
128
130
  customClientHeaders: cloneStringRecord(providerDraft.customClientHeaders),
129
131
  httpProxyEnabled: providerDraft.httpProxyEnabled,
130
132
  httpProxyUrl: providerDraft.httpProxyUrl,
133
+
131
134
  modelId: "",
132
135
  modelName: "",
133
136
  // 新建模型默认开启视觉输入;不支持图片的模型可在编辑器里关闭。
@@ -171,6 +174,7 @@ export function createModelDraftFromStoredModel(
171
174
  customClientHeaders: cloneStringRecord(stored.customClientHeaders),
172
175
  httpProxyEnabled: stored.httpProxyEnabled ?? false,
173
176
  httpProxyUrl: stored.httpProxyUrl?.trim() || DEFAULT_PROVIDER_HTTP_PROXY_URL,
177
+
174
178
  modelId: model.id,
175
179
  modelName: model.name ?? "",
176
180
  inputKinds: [...(model.input ?? preset.inputKinds)],
@@ -287,6 +291,10 @@ export function getProviderChangeWarnings(
287
291
  && getOpenAIChatCompatibilityMode(current.compat) !== (draft.openAIChatCompatibilityMode ?? "standard")) {
288
292
  changes.push(t("协议兼容"));
289
293
  }
294
+ if (draft.api === "openai-responses"
295
+ && (current.openAIResponsesStreamCompletionMode ?? "standard") !== (draft.openAIResponsesStreamCompletionMode ?? "standard")) {
296
+ changes.push(t("流结束兼容"));
297
+ }
290
298
  if ((current.clientHeaderProfile ?? "recommended") !== draft.clientHeaderProfile
291
299
  || (current.requestHeaderProfileId ?? "") !== (draft.requestHeaderProfileId ?? ""))
292
300
  changes.push(t("请求头"));
@@ -362,6 +370,11 @@ function buildProviderFromDraft(
362
370
  else delete next.httpProxyEnabled;
363
371
  if (draft.httpProxyEnabled || httpProxyUrl !== DEFAULT_PROVIDER_HTTP_PROXY_URL) next.httpProxyUrl = httpProxyUrl;
364
372
  else delete next.httpProxyUrl;
373
+ if (draft.api === "openai-responses" && draft.openAIResponsesStreamCompletionMode === "terminal-event") {
374
+ next.openAIResponsesStreamCompletionMode = "terminal-event";
375
+ } else {
376
+ delete next.openAIResponsesStreamCompletionMode;
377
+ }
365
378
  if (draft.clientHeaderProfile === "custom" && draft.requestHeaderProfileId?.trim()) {
366
379
  next.requestHeaderProfileId = draft.requestHeaderProfileId.trim();
367
380
  } else {
@@ -415,7 +428,8 @@ export function buildModelFromDraft(
415
428
  next.openAIServiceTier = "priority";
416
429
  }
417
430
 
418
- if (effectiveApi === "anthropic-messages" && draft.anthropicThinkingProtocol) {
431
+ // [喵喵喵]: 仅在启用推理时维护 Adaptive 思考协议;关闭推理时彻底清理兼容标记,避免误剥离协议头
432
+ if (effectiveApi === "anthropic-messages" && draft.reasoningMode === "enabled" && draft.anthropicThinkingProtocol) {
419
433
  const existingOverride = existing?.compat?.forceAdaptiveThinking;
420
434
  const providerForcesAdaptiveThinking = providerCompat?.forceAdaptiveThinking === true;
421
435
  if (draft.anthropicThinkingProtocol === "adaptive") {
@@ -426,6 +440,11 @@ export function buildModelFromDraft(
426
440
  } else {
427
441
  delete compat.forceAdaptiveThinking;
428
442
  }
443
+ } else if (effectiveApi === "anthropic-messages" && draft.reasoningMode !== "enabled" && providerCompat?.forceAdaptiveThinking === true) {
444
+ // [喵喵喵]: 关闭推理但接入级强制 adaptive 时显式写 false 覆盖继承值,否则合并后仍会注入 beta 请求头
445
+ compat.forceAdaptiveThinking = false;
446
+ } else {
447
+ delete compat.forceAdaptiveThinking;
429
448
  }
430
449
 
431
450
  if (Object.keys(compat).length > 0) next.compat = compat;
@@ -435,9 +454,20 @@ export function buildModelFromDraft(
435
454
 
436
455
  // ========== 请求头 ==========
437
456
 
438
- export function createRequestHeaderProfileDraft(): RequestHeaderProfileDraft {
457
+ export function createRequestHeaderProfileDraft(existingIds?: Iterable<string>): RequestHeaderProfileDraft {
458
+ let profileId = "custom-headers";
459
+ if (existingIds) {
460
+ const set = new Set(existingIds);
461
+ if (set.has(profileId)) {
462
+ let counter = 1;
463
+ while (set.has(`custom-headers-${counter}`)) {
464
+ counter += 1;
465
+ }
466
+ profileId = `custom-headers-${counter}`;
467
+ }
468
+ }
439
469
  return {
440
- profileId: "custom-headers",
470
+ profileId,
441
471
  profileName: t("自定义请求头"),
442
472
  headers: {},
443
473
  selectedIndex: 0,
@@ -22,6 +22,7 @@ import type {
22
22
  StoredModel,
23
23
  StoredProvider,
24
24
  StoredRequestHeaderProfile,
25
+ OpenAIResponsesStreamCompletionMode,
25
26
  ThinkingLevelMap,
26
27
  TokenCost,
27
28
  } from "./types.ts";
@@ -44,6 +45,7 @@ interface ProviderMetadata {
44
45
  customClientHeaders?: Record<string, string>;
45
46
  httpProxyEnabled?: boolean;
46
47
  httpProxyUrl?: string;
48
+ openAIResponsesStreamCompletionMode?: OpenAIResponsesStreamCompletionMode;
47
49
  anthropicApiRoot?: boolean;
48
50
  }
49
51
 
@@ -158,6 +160,19 @@ function readOptionalOpenAIServiceTier(record: Record<string, unknown>, key: str
158
160
  return value as OpenAIServiceTier;
159
161
  }
160
162
 
163
+ function readOptionalOpenAIResponsesStreamCompletionMode(
164
+ record: Record<string, unknown>,
165
+ key: string,
166
+ path: string,
167
+ ): OpenAIResponsesStreamCompletionMode | undefined {
168
+ const value = readOptionalString(record, key, path);
169
+ if (value === undefined) return undefined;
170
+ if (value !== "standard" && value !== "terminal-event") {
171
+ fail(`${path}.${key}`, t("未知 Responses 流结束模式:{value}", { value }));
172
+ }
173
+ return value;
174
+ }
175
+
161
176
  function readInputKinds(record: Record<string, unknown>, key: string, path: string): ModelInputKind[] {
162
177
  const value = record[key];
163
178
  if (!Array.isArray(value) || value.length === 0) fail(`${path}.${key}`, t("必须是非空数组"));
@@ -239,6 +254,8 @@ function readProviderMetadata(raw: unknown, path: string): ProviderMetadata {
239
254
  if (httpProxyEnabled !== undefined) metadata.httpProxyEnabled = httpProxyEnabled;
240
255
  const httpProxyUrl = readOptionalString(raw, "httpProxyUrl", path);
241
256
  if (httpProxyUrl !== undefined) metadata.httpProxyUrl = httpProxyUrl;
257
+ const streamCompletionMode = readOptionalOpenAIResponsesStreamCompletionMode(raw, "openAIResponsesStreamCompletionMode", path);
258
+ if (streamCompletionMode !== undefined) metadata.openAIResponsesStreamCompletionMode = streamCompletionMode;
242
259
  return metadata;
243
260
  }
244
261
 
@@ -308,6 +325,8 @@ function readStoredProvider(raw: unknown, path: string, managed: boolean): Store
308
325
  if (httpProxyEnabled !== undefined) provider.httpProxyEnabled = httpProxyEnabled;
309
326
  const httpProxyUrl = readOptionalString(raw, "httpProxyUrl", path);
310
327
  if (httpProxyUrl !== undefined) provider.httpProxyUrl = httpProxyUrl;
328
+ const streamCompletionMode = readOptionalOpenAIResponsesStreamCompletionMode(raw, "openAIResponsesStreamCompletionMode", path);
329
+ if (streamCompletionMode !== undefined) provider.openAIResponsesStreamCompletionMode = streamCompletionMode;
311
330
  return provider;
312
331
  }
313
332
 
@@ -381,6 +400,9 @@ function extractProviderMetadata(provider: StoredProvider): ProviderMetadata {
381
400
  if (provider.httpProxyEnabled) metadata.httpProxyEnabled = true;
382
401
  const httpProxyUrl = provider.httpProxyUrl?.trim();
383
402
  if (httpProxyUrl) metadata.httpProxyUrl = httpProxyUrl;
403
+ if (provider.openAIResponsesStreamCompletionMode === "terminal-event") {
404
+ metadata.openAIResponsesStreamCompletionMode = "terminal-event";
405
+ }
384
406
  return metadata;
385
407
  }
386
408
 
package/state-store.ts CHANGED
@@ -103,12 +103,29 @@ function resolveProviderCustomHeaders(
103
103
  return providerMetadata?.customClientHeaders ?? {};
104
104
  }
105
105
 
106
+ function stripProviderInheritedHeaders(
107
+ modelHeaders: Record<string, string> | undefined,
108
+ providerHeaders: Record<string, string> | undefined,
109
+ ): Record<string, string> | undefined {
110
+ if (!modelHeaders || !providerHeaders) return modelHeaders;
111
+ const result = cloneStringRecord(modelHeaders);
112
+ for (const [pName, pValue] of Object.entries(providerHeaders)) {
113
+ for (const [mName, mValue] of Object.entries(result)) {
114
+ if (mName.toLowerCase() === pName.toLowerCase() && mValue === pValue) {
115
+ delete result[mName];
116
+ }
117
+ }
118
+ }
119
+ return hasStringRecordEntries(result) ? result : undefined;
120
+ }
121
+
106
122
  function buildStoredModelFromModelsJson(
107
123
  providerId: string,
108
124
  providerApi: ApiKind,
109
125
  providerBaseUrl: string,
110
126
  providerNativeBaseUrl: string,
111
127
  providerCompat: CompatSettings | undefined,
128
+ providerHeaders: Record<string, string> | undefined,
112
129
  managed: boolean,
113
130
  clientHeaderProfile: StoredProvider["clientHeaderProfile"],
114
131
  customClientHeaders: Record<string, string>,
@@ -130,14 +147,14 @@ function buildStoredModelFromModelsJson(
130
147
  )
131
148
  : undefined;
132
149
  const nativeHeaders = managed
133
- ? stripManagedClientHeaders(model.headers, profileHeaders)
150
+ ? stripProviderInheritedHeaders(stripManagedClientHeaders(model.headers, profileHeaders), providerHeaders)
134
151
  : cloneStringRecord(model.headers);
135
152
  const stored: StoredModel = {
136
153
  id: model.id,
137
154
  reasoning: model.reasoning ?? false,
138
155
  input: readModelInput(model),
139
156
  contextWindow: model.contextWindow && model.contextWindow > 0 ? model.contextWindow : 128000,
140
- maxTokens: model.maxTokens && model.maxTokens > 0 ? model.maxTokens : 16384,
157
+ maxTokens: model.maxTokens && model.maxTokens > 0 ? model.maxTokens : 16000,
141
158
  cost: readModelCost(model),
142
159
  };
143
160
  if (explicitApi && explicitApi !== providerApi) stored.api = explicitApi;
@@ -199,6 +216,7 @@ async function buildStoredProviderFromModelsJson(
199
216
  baseUrl,
200
217
  nativeBaseUrl,
201
218
  providerCompat,
219
+ entry.headers,
202
220
  managed,
203
221
  clientHeaderProfile,
204
222
  customClientHeaders,
@@ -229,6 +247,9 @@ async function buildStoredProviderFromModelsJson(
229
247
  }
230
248
  if (managed && providerMetadata?.httpProxyEnabled !== undefined) provider.httpProxyEnabled = providerMetadata.httpProxyEnabled;
231
249
  if (managed && providerMetadata?.httpProxyUrl !== undefined) provider.httpProxyUrl = providerMetadata.httpProxyUrl;
250
+ if (managed && providerMetadata?.openAIResponsesStreamCompletionMode !== undefined) {
251
+ provider.openAIResponsesStreamCompletionMode = providerMetadata.openAIResponsesStreamCompletionMode;
252
+ }
232
253
  return provider;
233
254
  }
234
255