pi-model-manager 0.3.3 → 0.3.5
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 +26 -7
- package/README.md +26 -7
- package/atomic-write.ts +2 -2
- package/configuration-persistence.ts +32 -1
- package/i18n.ts +19 -7
- package/index.ts +9 -2
- package/local-proxy-service.ts +3 -2
- package/models-json-sync.ts +30 -3
- package/openai-responses-payload.ts +6 -8
- package/package.json +4 -2
- package/presets/builtin-client-headers.ts +3 -3
- package/presets/client-headers.ts +10 -13
- package/presets/providers.ts +4 -4
- package/provider-registrar.ts +36 -117
- package/provider-transport.ts +82 -0
- package/request-pipeline.ts +22 -17
- package/runtime-base-url.ts +45 -65
- package/state-document.ts +28 -21
- package/state-metadata-store.ts +21 -7
- package/state-store.ts +21 -4
- package/tui/editor-provider.ts +26 -29
- package/tui/model-list-fetch.ts +22 -70
- package/types.ts +3 -3
package/state-metadata-store.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { join } from "node:path";
|
|
|
9
9
|
import { cloneJson, isObjectRecord, stringifyJson, stripJsonNoise } from "./common.ts";
|
|
10
10
|
import { readStableTextFileSnapshot, type FileSignature } from "./file-snapshot.ts";
|
|
11
11
|
import { t } from "./i18n.ts";
|
|
12
|
+
import { fromNativeBaseUrl, toNativeBaseUrl } from "./runtime-base-url.ts";
|
|
12
13
|
import type {
|
|
13
14
|
ApiKind,
|
|
14
15
|
BuiltInClientHeaderProfileId,
|
|
@@ -43,14 +44,16 @@ interface ProviderMetadata {
|
|
|
43
44
|
customClientHeaders?: Record<string, string>;
|
|
44
45
|
httpProxyEnabled?: boolean;
|
|
45
46
|
httpProxyUrl?: string;
|
|
47
|
+
anthropicApiRoot?: boolean;
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
interface ModelMetadata {
|
|
49
51
|
openAIServiceTier?: OpenAIServiceTier;
|
|
52
|
+
anthropicApiRoot?: boolean;
|
|
50
53
|
}
|
|
51
54
|
|
|
52
55
|
export interface MetadataDocument {
|
|
53
|
-
version: 4;
|
|
56
|
+
version: 4 | 5;
|
|
54
57
|
/** 明确由插件创建或接管的 Provider ID。 */
|
|
55
58
|
managedProviderIds: string[];
|
|
56
59
|
providers: Record<string, ProviderMetadata>;
|
|
@@ -72,7 +75,7 @@ export interface MetadataStateSnapshot extends ParsedMetadataStateFile {
|
|
|
72
75
|
}
|
|
73
76
|
|
|
74
77
|
export function createEmptyMetadata(): MetadataDocument {
|
|
75
|
-
return { version:
|
|
78
|
+
return { version: 5, managedProviderIds: [], providers: {}, models: {}, requestHeaderProfiles: {}, clientHeaderCaptures: {} };
|
|
76
79
|
}
|
|
77
80
|
function fail(path: string, message: string): never {
|
|
78
81
|
throw new Error(t("state.json {path}: {message}", { path, message }));
|
|
@@ -224,6 +227,8 @@ function readStoredModel(raw: unknown, path: string): StoredModel {
|
|
|
224
227
|
function readProviderMetadata(raw: unknown, path: string): ProviderMetadata {
|
|
225
228
|
if (!isObjectRecord(raw)) fail(path, t("必须是对象"));
|
|
226
229
|
const metadata: ProviderMetadata = {};
|
|
230
|
+
const anthropicApiRoot = readOptionalBoolean(raw, "anthropicApiRoot", path);
|
|
231
|
+
if (anthropicApiRoot) metadata.anthropicApiRoot = true;
|
|
227
232
|
const clientHeaderProfile = readOptionalClientHeaderProfile(raw, "clientHeaderProfile", path);
|
|
228
233
|
if (clientHeaderProfile) metadata.clientHeaderProfile = clientHeaderProfile;
|
|
229
234
|
const requestHeaderProfileId = readOptionalString(raw, "requestHeaderProfileId", path);
|
|
@@ -240,6 +245,8 @@ function readProviderMetadata(raw: unknown, path: string): ProviderMetadata {
|
|
|
240
245
|
function readModelMetadata(raw: unknown, path: string): ModelMetadata {
|
|
241
246
|
if (!isObjectRecord(raw)) fail(path, t("必须是对象"));
|
|
242
247
|
const metadata: ModelMetadata = {};
|
|
248
|
+
const anthropicApiRoot = readOptionalBoolean(raw, "anthropicApiRoot", path);
|
|
249
|
+
if (anthropicApiRoot) metadata.anthropicApiRoot = true;
|
|
243
250
|
const openAIServiceTier = readOptionalOpenAIServiceTier(raw, "openAIServiceTier", path);
|
|
244
251
|
if (openAIServiceTier) metadata.openAIServiceTier = openAIServiceTier;
|
|
245
252
|
return metadata;
|
|
@@ -361,6 +368,7 @@ function getFullModelId(providerId: string, modelId: string): string {
|
|
|
361
368
|
|
|
362
369
|
function extractProviderMetadata(provider: StoredProvider): ProviderMetadata {
|
|
363
370
|
const metadata: ProviderMetadata = {};
|
|
371
|
+
if (toNativeBaseUrl(provider.api, provider.baseUrl).anthropicApiRoot) metadata.anthropicApiRoot = true;
|
|
364
372
|
if (provider.clientHeaderProfile !== "recommended") metadata.clientHeaderProfile = provider.clientHeaderProfile;
|
|
365
373
|
if (provider.clientHeaderProfile === "custom" && provider.requestHeaderProfileId) {
|
|
366
374
|
metadata.clientHeaderProfile = "custom";
|
|
@@ -376,21 +384,23 @@ function extractProviderMetadata(provider: StoredProvider): ProviderMetadata {
|
|
|
376
384
|
return metadata;
|
|
377
385
|
}
|
|
378
386
|
|
|
379
|
-
function extractModelMetadata(model: StoredModel): ModelMetadata {
|
|
387
|
+
function extractModelMetadata(model: StoredModel, provider: StoredProvider): ModelMetadata {
|
|
380
388
|
const metadata: ModelMetadata = {};
|
|
389
|
+
if (toNativeBaseUrl(model.api ?? provider.api, model.baseUrl ?? provider.baseUrl).anthropicApiRoot) metadata.anthropicApiRoot = true;
|
|
381
390
|
if (model.openAIServiceTier) metadata.openAIServiceTier = model.openAIServiceTier;
|
|
382
391
|
return metadata;
|
|
383
392
|
}
|
|
384
393
|
|
|
385
394
|
function extractMetadataFromLegacyState(legacy: StateDocument): MetadataDocument {
|
|
386
395
|
const metadata = createEmptyMetadata();
|
|
396
|
+
metadata.version = 4;
|
|
387
397
|
metadata.managedProviderIds = Object.keys(legacy.providers);
|
|
388
398
|
metadata.requestHeaderProfiles = cloneJson(legacy.requestHeaderProfiles);
|
|
389
399
|
metadata.clientHeaderCaptures = cloneJson(legacy.clientHeaderCaptures);
|
|
390
400
|
for (const [providerId, provider] of Object.entries(legacy.providers)) {
|
|
391
401
|
metadata.providers[providerId] = extractProviderMetadata(provider);
|
|
392
402
|
for (const model of provider.models) {
|
|
393
|
-
const modelMetadata = extractModelMetadata(model);
|
|
403
|
+
const modelMetadata = extractModelMetadata(model, provider);
|
|
394
404
|
if (Object.keys(modelMetadata).length > 0) metadata.models[getFullModelId(providerId, model.id)] = modelMetadata;
|
|
395
405
|
}
|
|
396
406
|
}
|
|
@@ -408,6 +418,9 @@ function parseLegacyState(parsed: Record<string, unknown>): ParsedMetadataStateF
|
|
|
408
418
|
}
|
|
409
419
|
const common = readCommonMetadataFields(parsed, createEmptyMetadata());
|
|
410
420
|
const legacy = { version: 2, providers, managedProviderIds: Object.keys(providers), requestHeaderProfiles: common.requestHeaderProfiles, clientHeaderCaptures: common.clientHeaderCaptures } satisfies StateDocument;
|
|
421
|
+
for (const provider of Object.values(providers)) {
|
|
422
|
+
provider.baseUrl = fromNativeBaseUrl(provider.api, provider.baseUrl, false, true);
|
|
423
|
+
}
|
|
411
424
|
return {
|
|
412
425
|
metadata: extractMetadataFromLegacyState(legacy),
|
|
413
426
|
legacyProviders: providers,
|
|
@@ -417,6 +430,7 @@ function parseLegacyState(parsed: Record<string, unknown>): ParsedMetadataStateF
|
|
|
417
430
|
|
|
418
431
|
function parseMetadataState(parsed: Record<string, unknown>): ParsedMetadataStateFile {
|
|
419
432
|
const metadata = readCommonMetadataFields(parsed, createEmptyMetadata());
|
|
433
|
+
metadata.version = parsed.version === 5 ? 5 : 4;
|
|
420
434
|
const rawProviders = parsed.providers;
|
|
421
435
|
if (rawProviders !== undefined) {
|
|
422
436
|
if (!isObjectRecord(rawProviders)) fail(".providers", t("必须是对象"));
|
|
@@ -443,14 +457,14 @@ function parseMetadataState(parsed: Record<string, unknown>): ParsedMetadataStat
|
|
|
443
457
|
return {
|
|
444
458
|
metadata,
|
|
445
459
|
legacyProviders: {},
|
|
446
|
-
requirePluginManagedProviderMarker: parsed.version === 4,
|
|
460
|
+
requirePluginManagedProviderMarker: parsed.version === 4 || parsed.version === 5,
|
|
447
461
|
};
|
|
448
462
|
}
|
|
449
463
|
|
|
450
464
|
function parseStateFile(source: string): ParsedMetadataStateFile {
|
|
451
465
|
const parsed = JSON.parse(stripJsonNoise(source));
|
|
452
466
|
if (!isObjectRecord(parsed)) fail("", t("根节点必须是对象"));
|
|
453
|
-
if (parsed.version === 4 || parsed.version === 3 || parsed.version === 2) return parseMetadataState(parsed);
|
|
467
|
+
if (parsed.version === 5 || parsed.version === 4 || parsed.version === 3 || parsed.version === 2) return parseMetadataState(parsed);
|
|
454
468
|
if (parsed.version === undefined || parsed.version === 1) return parseLegacyState(parsed);
|
|
455
469
|
fail(".version", t("不支持的版本:{version}", { version: String(parsed.version) }));
|
|
456
470
|
}
|
|
@@ -475,7 +489,7 @@ function extractMetadata(state: StateDocument): MetadataDocument {
|
|
|
475
489
|
const providerMetadata = extractProviderMetadata(provider);
|
|
476
490
|
if (Object.keys(providerMetadata).length > 0) metadata.providers[providerId] = providerMetadata;
|
|
477
491
|
for (const model of provider.models) {
|
|
478
|
-
const modelMetadata = extractModelMetadata(model);
|
|
492
|
+
const modelMetadata = extractModelMetadata(model, provider);
|
|
479
493
|
if (Object.keys(modelMetadata).length > 0) metadata.models[getFullModelId(providerId, model.id)] = modelMetadata;
|
|
480
494
|
}
|
|
481
495
|
}
|
package/state-store.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
stripManagedClientHeaders,
|
|
23
23
|
} from "./presets/client-headers.ts";
|
|
24
24
|
import { normalizeThinkingLevelMap } from "./presets/thinking.ts";
|
|
25
|
+
import { fromNativeBaseUrl, resolveRuntimeBaseUrl, toNativeBaseUrl } from "./runtime-base-url.ts";
|
|
25
26
|
import {
|
|
26
27
|
CONFIGURATION_TRANSACTION_PATH,
|
|
27
28
|
getStatePath as getMetadataStatePath,
|
|
@@ -106,6 +107,7 @@ function buildStoredModelFromModelsJson(
|
|
|
106
107
|
providerId: string,
|
|
107
108
|
providerApi: ApiKind,
|
|
108
109
|
providerBaseUrl: string,
|
|
110
|
+
providerNativeBaseUrl: string,
|
|
109
111
|
providerCompat: CompatSettings | undefined,
|
|
110
112
|
managed: boolean,
|
|
111
113
|
clientHeaderProfile: StoredProvider["clientHeaderProfile"],
|
|
@@ -139,14 +141,25 @@ function buildStoredModelFromModelsJson(
|
|
|
139
141
|
cost: readModelCost(model),
|
|
140
142
|
};
|
|
141
143
|
if (explicitApi && explicitApi !== providerApi) stored.api = explicitApi;
|
|
142
|
-
|
|
144
|
+
const modelMetadata = metadata.models[getFullModelId(providerId, model.id)];
|
|
145
|
+
let modelBaseUrl = model.baseUrl ?? providerBaseUrl;
|
|
146
|
+
if (managed && model.baseUrl) {
|
|
147
|
+
modelBaseUrl = fromNativeBaseUrl(effectiveApi, model.baseUrl, modelMetadata?.anthropicApiRoot, metadata.version < 5);
|
|
148
|
+
} else if (managed && effectiveApi !== providerApi) {
|
|
149
|
+
const inheritedBaseUrl = metadata.version < 5
|
|
150
|
+
? (providerApi === "anthropic-messages"
|
|
151
|
+
? toNativeBaseUrl(providerApi, providerBaseUrl).baseUrl
|
|
152
|
+
: resolveRuntimeBaseUrl(providerApi, providerNativeBaseUrl))
|
|
153
|
+
: providerNativeBaseUrl;
|
|
154
|
+
modelBaseUrl = fromNativeBaseUrl(effectiveApi, inheritedBaseUrl, modelMetadata?.anthropicApiRoot);
|
|
155
|
+
}
|
|
156
|
+
if (modelBaseUrl !== providerBaseUrl) stored.baseUrl = modelBaseUrl;
|
|
143
157
|
if (nativeHeaders) stored.headers = nativeHeaders;
|
|
144
158
|
if (model.name) stored.name = model.name;
|
|
145
159
|
const storedThinkingLevelMap = model.thinkingLevelMap ? cloneJson(model.thinkingLevelMap) as ThinkingLevelMap : undefined;
|
|
146
160
|
const thinkingLevelMap = normalizeThinkingLevelMap(effectiveApi, stored.reasoning, storedThinkingLevelMap);
|
|
147
161
|
if (thinkingLevelMap) stored.thinkingLevelMap = thinkingLevelMap;
|
|
148
162
|
if (modelCompat) stored.compat = modelCompat;
|
|
149
|
-
const modelMetadata = metadata.models[getFullModelId(providerId, model.id)];
|
|
150
163
|
if (effectiveApi === "openai-responses" && modelMetadata?.openAIServiceTier) {
|
|
151
164
|
stored.openAIServiceTier = modelMetadata.openAIServiceTier;
|
|
152
165
|
}
|
|
@@ -165,12 +178,15 @@ async function buildStoredProviderFromModelsJson(
|
|
|
165
178
|
const firstModel = rawModels[0];
|
|
166
179
|
const builtInDefaults = await getBuiltinProviderDefaults(providerId);
|
|
167
180
|
const api = asApiKind(entry.api) ?? asApiKind(firstModel?.api) ?? asApiKind(builtInDefaults?.api);
|
|
168
|
-
const
|
|
169
|
-
if (!api || !
|
|
181
|
+
const nativeBaseUrl = entry.baseUrl ?? firstModel?.baseUrl ?? builtInDefaults?.baseUrl;
|
|
182
|
+
if (!api || !nativeBaseUrl) return undefined;
|
|
170
183
|
|
|
171
184
|
const providerMetadata = metadata.providers[providerId];
|
|
172
185
|
const managed = metadata.managedProviderIds.includes(providerId)
|
|
173
186
|
&& (!requirePluginManagedProviderMarker || hasPluginManagedProviderMarker(entry));
|
|
187
|
+
const baseUrl = managed
|
|
188
|
+
? fromNativeBaseUrl(api, nativeBaseUrl, providerMetadata?.anthropicApiRoot, metadata.version < 5)
|
|
189
|
+
: nativeBaseUrl;
|
|
174
190
|
const clientHeaderProfile = managed ? providerMetadata?.clientHeaderProfile ?? "recommended" : "disabled";
|
|
175
191
|
const customClientHeaders = managed && clientHeaderProfile === "custom"
|
|
176
192
|
? resolveProviderCustomHeaders(providerMetadata, metadata)
|
|
@@ -181,6 +197,7 @@ async function buildStoredProviderFromModelsJson(
|
|
|
181
197
|
providerId,
|
|
182
198
|
api,
|
|
183
199
|
baseUrl,
|
|
200
|
+
nativeBaseUrl,
|
|
184
201
|
providerCompat,
|
|
185
202
|
managed,
|
|
186
203
|
clientHeaderProfile,
|
package/tui/editor-provider.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { t } from "../i18n.ts";
|
|
|
9
9
|
import { switchProviderDraftApiPreset } from "../presets/providers.ts";
|
|
10
10
|
import { redactUrlForDisplay } from "../sensitive-redaction.ts";
|
|
11
11
|
import { resolveRuntimeBaseUrl } from "../runtime-base-url.ts";
|
|
12
|
-
import { DEFAULT_PROVIDER_HTTP_PROXY_URL, type
|
|
12
|
+
import { DEFAULT_PROVIDER_HTTP_PROXY_URL, type OpenAIChatCompatibilityMode } from "../types.ts";
|
|
13
13
|
import { showOptionPicker, showPersistentFormMenu, padLabel, type HorizontalDirection, type MenuCursor } from "./persistent-menu.ts";
|
|
14
14
|
import {
|
|
15
15
|
describeProfile,
|
|
@@ -28,31 +28,29 @@ interface FieldRow {
|
|
|
28
28
|
adjustable?: boolean;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
const
|
|
31
|
+
const OPENAI_CHAT_COMPATIBILITY_MODE_ORDER: readonly OpenAIChatCompatibilityMode[] = ["standard", "compatible"];
|
|
32
32
|
|
|
33
|
-
function
|
|
34
|
-
return draft.
|
|
33
|
+
function getOpenAIChatCompatibilityMode(draft: ProviderDraft): OpenAIChatCompatibilityMode {
|
|
34
|
+
return draft.openAIChatCompatibilityMode ?? "standard";
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
function
|
|
38
|
-
if (
|
|
39
|
-
|
|
40
|
-
return t("自动 · Pi 默认");
|
|
37
|
+
function describeOpenAIChatCompatibilityMode(mode: OpenAIChatCompatibilityMode): string {
|
|
38
|
+
if (mode === "compatible") return t("兼容 · system");
|
|
39
|
+
return t("标准 · Pi 默认");
|
|
41
40
|
}
|
|
42
41
|
|
|
43
|
-
function
|
|
44
|
-
if (
|
|
45
|
-
|
|
46
|
-
return t("自动模式:由 Pi 判断系统提示词使用 developer 或 system role。");
|
|
42
|
+
function getOpenAIChatCompatibilityModeHint(mode: OpenAIChatCompatibilityMode): string {
|
|
43
|
+
if (mode === "compatible") return t("兼容模式:系统提示词强制使用 system role,适合忽略 developer 的中转。");
|
|
44
|
+
return t("标准模式:保持 Pi 默认兼容判断。");
|
|
47
45
|
}
|
|
48
46
|
|
|
49
|
-
function
|
|
50
|
-
|
|
47
|
+
function cycleOpenAIChatCompatibilityMode(
|
|
48
|
+
mode: OpenAIChatCompatibilityMode,
|
|
51
49
|
direction: HorizontalDirection,
|
|
52
|
-
):
|
|
53
|
-
const index =
|
|
50
|
+
): OpenAIChatCompatibilityMode {
|
|
51
|
+
const index = OPENAI_CHAT_COMPATIBILITY_MODE_ORDER.indexOf(mode);
|
|
54
52
|
const offset = direction === "right" ? 1 : -1;
|
|
55
|
-
return
|
|
53
|
+
return OPENAI_CHAT_COMPATIBILITY_MODE_ORDER[(index + offset + OPENAI_CHAT_COMPATIBILITY_MODE_ORDER.length) % OPENAI_CHAT_COMPATIBILITY_MODE_ORDER.length]!;
|
|
56
54
|
}
|
|
57
55
|
|
|
58
56
|
function buildRows(
|
|
@@ -73,9 +71,9 @@ function buildRows(
|
|
|
73
71
|
];
|
|
74
72
|
if (draft.api === "openai-completions") {
|
|
75
73
|
rows.push({
|
|
76
|
-
id: "
|
|
74
|
+
id: "openAIChatCompatibilityMode",
|
|
77
75
|
label: t("协议兼容"),
|
|
78
|
-
value:
|
|
76
|
+
value: describeOpenAIChatCompatibilityMode(getOpenAIChatCompatibilityMode(draft)),
|
|
79
77
|
adjustable: true,
|
|
80
78
|
});
|
|
81
79
|
}
|
|
@@ -91,10 +89,10 @@ function buildRows(
|
|
|
91
89
|
|
|
92
90
|
|
|
93
91
|
|
|
94
|
-
//
|
|
92
|
+
// 二值开关的两个方向都取反。
|
|
95
93
|
function applyHorizontalToggle(draft: ProviderDraft, fieldId: string, direction: HorizontalDirection): boolean {
|
|
96
|
-
if (fieldId === "
|
|
97
|
-
draft.
|
|
94
|
+
if (fieldId === "openAIChatCompatibilityMode") {
|
|
95
|
+
draft.openAIChatCompatibilityMode = cycleOpenAIChatCompatibilityMode(getOpenAIChatCompatibilityMode(draft), direction);
|
|
98
96
|
return true;
|
|
99
97
|
}
|
|
100
98
|
if (fieldId !== "httpProxyEnabled") return false;
|
|
@@ -142,18 +140,17 @@ async function editField(
|
|
|
142
140
|
if (choice) switchProviderDraftApiPreset(draft, choice.id);
|
|
143
141
|
return;
|
|
144
142
|
}
|
|
145
|
-
if (fieldId === "
|
|
143
|
+
if (fieldId === "openAIChatCompatibilityMode") {
|
|
146
144
|
const choice = await showOptionPicker(
|
|
147
145
|
ctx,
|
|
148
146
|
t("选择协议兼容"),
|
|
149
147
|
[
|
|
150
|
-
{ id: "
|
|
151
|
-
{ id: "
|
|
152
|
-
{ id: "system", label: t("兼容 — 强制 system role,适合忽略 developer 的中转") },
|
|
148
|
+
{ id: "standard", label: t("标准 — 保持 Pi 默认兼容判断") },
|
|
149
|
+
{ id: "compatible", label: t("兼容 — 强制 system role,适合忽略 developer 的中转") },
|
|
153
150
|
],
|
|
154
|
-
|
|
151
|
+
getOpenAIChatCompatibilityMode(draft),
|
|
155
152
|
);
|
|
156
|
-
if (choice) draft.
|
|
153
|
+
if (choice) draft.openAIChatCompatibilityMode = choice.id as OpenAIChatCompatibilityMode;
|
|
157
154
|
return;
|
|
158
155
|
}
|
|
159
156
|
if (fieldId === "authHeader") {
|
|
@@ -252,7 +249,7 @@ export async function editProvider(
|
|
|
252
249
|
t("Ctrl+S 保存并同步 models.json;不切换当前会话模型"),
|
|
253
250
|
];
|
|
254
251
|
if (draft.api === "openai-completions") {
|
|
255
|
-
summaryLines.push(
|
|
252
|
+
summaryLines.push(getOpenAIChatCompatibilityModeHint(getOpenAIChatCompatibilityMode(draft)));
|
|
256
253
|
}
|
|
257
254
|
return summaryLines;
|
|
258
255
|
};
|
package/tui/model-list-fetch.ts
CHANGED
|
@@ -5,8 +5,8 @@ import { ModelRuntime, type ProviderConfig } from "@earendil-works/pi-coding-age
|
|
|
5
5
|
import { formatUnknownError } from "../common.ts";
|
|
6
6
|
import { t } from "../i18n.ts";
|
|
7
7
|
import { openTemporaryLocalProxyRoute, type TemporaryLocalProxyRoute } from "../local-proxy-service.ts";
|
|
8
|
-
import { getClientHeadersForProfile } from "../presets/client-headers.ts";
|
|
9
|
-
import { appendUrlPath, resolveRuntimeBaseUrl } from "../runtime-base-url.ts";
|
|
8
|
+
import { getClientHeadersForProfile, mergeModelRequestHeaders } from "../presets/client-headers.ts";
|
|
9
|
+
import { appendUrlPath, resolveRuntimeBaseUrl, validateRequestBaseUrl } from "../runtime-base-url.ts";
|
|
10
10
|
import { isSensitiveHeaderName, redactSensitiveText } from "../sensitive-redaction.ts";
|
|
11
11
|
import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, ModelListFetchOutcome, StoredClientHeaderCapture } from "../types.ts";
|
|
12
12
|
import { extractValidatedModelIds, readBoundedResponseText } from "./model-list-validation.ts";
|
|
@@ -31,37 +31,6 @@ const emptyCredentialStore = {
|
|
|
31
31
|
},
|
|
32
32
|
};
|
|
33
33
|
|
|
34
|
-
function hasRootPath(baseUrl: string): boolean {
|
|
35
|
-
try {
|
|
36
|
-
const pathname = new URL(baseUrl.trim()).pathname.replace(/\/+$/, "");
|
|
37
|
-
return pathname === "";
|
|
38
|
-
} catch {
|
|
39
|
-
return false;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function buildOpenAIUrl(baseUrl: string, api: Extract<ApiKind, "openai-completions" | "openai-responses">): string {
|
|
44
|
-
return appendUrlPath(resolveRuntimeBaseUrl(api, baseUrl), "models");
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function buildAnthropicUrl(baseUrl: string): string {
|
|
48
|
-
return hasRootPath(baseUrl)
|
|
49
|
-
? appendUrlPath(baseUrl, "v1", "models")
|
|
50
|
-
: appendUrlPath(baseUrl, "models");
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function buildOriginOpenAIUrl(baseUrl: string): string {
|
|
54
|
-
const parsed = new URL(baseUrl.trim());
|
|
55
|
-
parsed.pathname = "/v1/models";
|
|
56
|
-
parsed.hash = "";
|
|
57
|
-
return parsed.toString();
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function buildGoogleUrl(baseUrl: string, apiKey: string): string {
|
|
61
|
-
const url = new URL(appendUrlPath(baseUrl, "models"));
|
|
62
|
-
url.searchParams.set("key", apiKey);
|
|
63
|
-
return url.toString();
|
|
64
|
-
}
|
|
65
34
|
|
|
66
35
|
function throwIfAborted(signal: AbortSignal): void {
|
|
67
36
|
if (!signal.aborted) return;
|
|
@@ -118,6 +87,7 @@ async function resolveFetchAuth(
|
|
|
118
87
|
credentials: emptyCredentialStore,
|
|
119
88
|
modelsPath: null,
|
|
120
89
|
allowModelNetwork: false,
|
|
90
|
+
refreshOnCreate: false,
|
|
121
91
|
}), signal);
|
|
122
92
|
runtime.registerProvider(TEMP_PROVIDER_ID, providerConfig);
|
|
123
93
|
const model = runtime.getModel(TEMP_PROVIDER_ID, TEMP_MODEL_ID);
|
|
@@ -172,7 +142,13 @@ async function requestModelIds(
|
|
|
172
142
|
: undefined;
|
|
173
143
|
const response = await fetch(temporaryProxyRoute?.url ?? url, { headers, signal });
|
|
174
144
|
const text = await readBoundedResponseText(response, signal);
|
|
175
|
-
if (!response.ok)
|
|
145
|
+
if (!response.ok) {
|
|
146
|
+
const reason = response.status === 401 || response.status === 403 ? t("认证失败,请检查 API key 和认证头")
|
|
147
|
+
: response.status === 404 ? t("模型列表接口不存在,可继续手动添加模型")
|
|
148
|
+
: response.status === 429 ? t("模型列表请求被限流,请稍后重试")
|
|
149
|
+
: response.status >= 500 ? t("模型列表上游服务异常") : t("模型列表请求失败");
|
|
150
|
+
throw new Error(`${reason} (HTTP ${response.status}): ${text.slice(0, 240)}`);
|
|
151
|
+
}
|
|
176
152
|
return extractValidatedModelIds(JSON.parse(text), api);
|
|
177
153
|
} finally {
|
|
178
154
|
temporaryProxyRoute?.close();
|
|
@@ -197,6 +173,8 @@ async function fetchModelIdsWithSignal(
|
|
|
197
173
|
signal: AbortSignal,
|
|
198
174
|
redactionSecrets: string[],
|
|
199
175
|
): Promise<ModelListFetchOutcome> {
|
|
176
|
+
throwIfAborted(signal);
|
|
177
|
+
validateRequestBaseUrl(params.baseUrl);
|
|
200
178
|
const profileHeaders = getClientHeadersForProfile(
|
|
201
179
|
params.clientHeaderProfile,
|
|
202
180
|
params.api,
|
|
@@ -205,47 +183,21 @@ async function fetchModelIdsWithSignal(
|
|
|
205
183
|
);
|
|
206
184
|
const auth = await resolveFetchAuth(params, profileHeaders, signal);
|
|
207
185
|
redactionSecrets.push(...auth.redactionSecrets);
|
|
208
|
-
const
|
|
186
|
+
const defaults: Record<string, string> = { accept: "application/json" };
|
|
187
|
+
if (params.api === "anthropic-messages") {
|
|
188
|
+
defaults["x-api-key"] = auth.apiKey;
|
|
189
|
+
defaults["anthropic-version"] = "2023-06-01";
|
|
190
|
+
} else if (params.api === "google-generative-ai") defaults["x-goog-api-key"] = auth.apiKey;
|
|
191
|
+
else defaults.authorization = `Bearer ${auth.apiKey}`;
|
|
192
|
+
const headers = mergeModelRequestHeaders(defaults, auth.headers)!;
|
|
209
193
|
const proxyConfig = params.httpProxyEnabled
|
|
210
194
|
? { providerId: params.providerId, proxyUrl: params.httpProxyUrl }
|
|
211
195
|
: undefined;
|
|
212
196
|
|
|
213
|
-
|
|
214
|
-
const modelIds = await requestModelIds(
|
|
215
|
-
buildGoogleUrl(resolveRuntimeBaseUrl(params.api, params.baseUrl), auth.apiKey),
|
|
216
|
-
headers,
|
|
217
|
-
params.api,
|
|
218
|
-
proxyConfig,
|
|
219
|
-
signal,
|
|
220
|
-
);
|
|
221
|
-
return { status: "loaded", modelIds };
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
if (params.api === "anthropic-messages") {
|
|
225
|
-
const anthropicVersion = headers["anthropic-version"] ?? "2023-06-01";
|
|
226
|
-
const apiKeyHeaders = { ...headers, "x-api-key": auth.apiKey, "anthropic-version": anthropicVersion };
|
|
227
|
-
try {
|
|
228
|
-
const modelIds = await requestModelIds(buildAnthropicUrl(params.baseUrl), apiKeyHeaders, params.api, proxyConfig, signal);
|
|
229
|
-
return { status: "loaded", modelIds };
|
|
230
|
-
} catch {
|
|
231
|
-
throwIfAborted(signal);
|
|
232
|
-
}
|
|
233
|
-
const bearerHeaders: Record<string, string> = { ...headers, Authorization: `Bearer ${auth.apiKey}`, "anthropic-version": anthropicVersion };
|
|
234
|
-
delete bearerHeaders["x-api-key"];
|
|
235
|
-
try {
|
|
236
|
-
const modelIds = await requestModelIds(buildAnthropicUrl(params.baseUrl), bearerHeaders, params.api, proxyConfig, signal);
|
|
237
|
-
return { status: "loaded", modelIds };
|
|
238
|
-
} catch {
|
|
239
|
-
throwIfAborted(signal);
|
|
240
|
-
}
|
|
241
|
-
const fallbackHeaders = { ...headers, Authorization: `Bearer ${auth.apiKey}` };
|
|
242
|
-
const modelIds = await requestModelIds(buildOriginOpenAIUrl(params.baseUrl), fallbackHeaders, params.api, proxyConfig, signal);
|
|
243
|
-
return { status: "loaded", modelIds };
|
|
244
|
-
}
|
|
245
|
-
|
|
197
|
+
// [喵喵喵]: 列表与聊天共享 API 根地址;错误不触发跨路径或跨认证形式的探测。
|
|
246
198
|
const modelIds = await requestModelIds(
|
|
247
|
-
|
|
248
|
-
|
|
199
|
+
appendUrlPath(resolveRuntimeBaseUrl(params.api, params.baseUrl), "models"),
|
|
200
|
+
headers,
|
|
249
201
|
params.api,
|
|
250
202
|
proxyConfig,
|
|
251
203
|
signal,
|
package/types.ts
CHANGED
|
@@ -12,7 +12,7 @@ type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "
|
|
|
12
12
|
export type ThinkingLevelMap = Partial<Record<ThinkingLevel, string | null>>;
|
|
13
13
|
export type ReasoningMode = "enabled" | "disabled";
|
|
14
14
|
export type AnthropicThinkingProtocol = "adaptive" | "legacy";
|
|
15
|
-
export type
|
|
15
|
+
export type OpenAIChatCompatibilityMode = "standard" | "compatible";
|
|
16
16
|
export type BuiltInClientHeaderProfileId = "claude-code" | "codex-cli";
|
|
17
17
|
export type ClientHeaderProfileId = "recommended" | "disabled" | BuiltInClientHeaderProfileId | "custom";
|
|
18
18
|
export type CompatSettings = Record<string, unknown>;
|
|
@@ -106,8 +106,8 @@ export interface ProviderDraft {
|
|
|
106
106
|
providerId: string;
|
|
107
107
|
providerName: string;
|
|
108
108
|
api: ApiKind;
|
|
109
|
-
/** Chat Completions
|
|
110
|
-
|
|
109
|
+
/** Chat Completions 系统提示词兼容模式;standard 保持 Pi 默认判断。 */
|
|
110
|
+
openAIChatCompatibilityMode?: OpenAIChatCompatibilityMode;
|
|
111
111
|
baseUrl: string;
|
|
112
112
|
apiKey: string;
|
|
113
113
|
authHeader: boolean;
|