pi-model-manager 0.4.6 → 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 +14 -11
- package/README.md +14 -11
- package/codex-compat.ts +8 -12
- package/configuration-lock.ts +73 -9
- package/configuration-persistence.ts +84 -11
- package/i18n.ts +5 -1
- package/index.ts +5 -5
- package/local-proxy-service.ts +6 -38
- package/package.json +5 -5
- package/presets/builtin-client-headers.ts +4 -5
- package/presets/client-headers.ts +3 -30
- package/provider-registrar.ts +145 -27
- package/provider-transport.ts +23 -5
- 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/state-metadata-store.ts
CHANGED
|
@@ -9,8 +9,8 @@ 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 {
|
|
13
|
-
import {
|
|
12
|
+
import { getClientHeadersForProfile, mergeModelRequestHeaders, resolveClientHeaderProfile, resolveProviderCustomHeaders } from "./presets/client-headers.ts";
|
|
13
|
+
import type { ModelsJsonDocument } from "./models-json-manager.ts";
|
|
14
14
|
import { getGeneratedCodexClientHeaders } from "./presets/codex-client-headers.ts";
|
|
15
15
|
import { fromNativeBaseUrl, toNativeBaseUrl } from "./runtime-base-url.ts";
|
|
16
16
|
import type {
|
|
@@ -69,6 +69,12 @@ export interface MetadataDocument {
|
|
|
69
69
|
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>;
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
interface HeaderSnapshotSource {
|
|
73
|
+
previous: MetadataDocument;
|
|
74
|
+
models: ModelsJsonDocument;
|
|
75
|
+
isModelRewritten(providerId: string, modelId: string): boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
72
78
|
export interface ParsedMetadataStateFile {
|
|
73
79
|
metadata: MetadataDocument;
|
|
74
80
|
legacyProviders: StateDocument["providers"];
|
|
@@ -423,11 +429,14 @@ function extractModelMetadata(model: StoredModel, provider: StoredProvider, stat
|
|
|
423
429
|
const api = model.api ?? provider.api;
|
|
424
430
|
if (toNativeBaseUrl(api, model.baseUrl ?? provider.baseUrl).anthropicApiRoot) metadata.anthropicApiRoot = true;
|
|
425
431
|
if (model.openAIServiceTier) metadata.openAIServiceTier = model.openAIServiceTier;
|
|
426
|
-
if (state
|
|
427
|
-
const headers = getClientHeadersForProfile(provider.clientHeaderProfile, api,
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
432
|
+
if (state) {
|
|
433
|
+
const headers = mergeModelRequestHeaders(undefined, getClientHeadersForProfile(provider.clientHeaderProfile, api,
|
|
434
|
+
resolveProviderCustomHeaders(provider, state.requestHeaderProfiles), state.clientHeaderCaptures)) ?? {};
|
|
435
|
+
const explicit = mergeModelRequestHeaders(provider.headers, model.headers) ?? {};
|
|
436
|
+
const profile = resolveClientHeaderProfile(provider.clientHeaderProfile, api);
|
|
437
|
+
metadata.generatedClientHeaders = profile === "codex-cli"
|
|
438
|
+
? getGeneratedCodexClientHeaders(headers, explicit)
|
|
439
|
+
: Object.fromEntries(Object.entries(headers).filter(([name]) => profile === "custom" || !Object.hasOwn(explicit, name.toLowerCase())));
|
|
431
440
|
}
|
|
432
441
|
return metadata;
|
|
433
442
|
}
|
|
@@ -518,7 +527,7 @@ export async function readMetadataStateSnapshot(): Promise<MetadataStateSnapshot
|
|
|
518
527
|
return { ...parsed, source: snapshot.source, signature: snapshot.signature, contentHash: snapshot.contentHash };
|
|
519
528
|
}
|
|
520
529
|
|
|
521
|
-
function extractMetadata(state: StateDocument): MetadataDocument {
|
|
530
|
+
function extractMetadata(state: StateDocument, source?: HeaderSnapshotSource): MetadataDocument {
|
|
522
531
|
const metadata = createEmptyMetadata();
|
|
523
532
|
metadata.managedProviderIds = Object.entries(state.providers)
|
|
524
533
|
.filter(([, provider]) => provider.managed)
|
|
@@ -529,16 +538,25 @@ function extractMetadata(state: StateDocument): MetadataDocument {
|
|
|
529
538
|
if (!provider.managed) continue;
|
|
530
539
|
const providerMetadata = extractProviderMetadata(provider);
|
|
531
540
|
if (Object.keys(providerMetadata).length > 0) metadata.providers[providerId] = providerMetadata;
|
|
541
|
+
const persistedModels = new Map(source?.models.providers[providerId]?.models?.map((model) => [model.id, model]));
|
|
532
542
|
for (const model of provider.models) {
|
|
543
|
+
const fullId = getFullModelId(providerId, model.id);
|
|
533
544
|
const modelMetadata = extractModelMetadata(model, provider, state);
|
|
534
|
-
if (
|
|
545
|
+
if (source && !source.isModelRewritten(providerId, model.id)) {
|
|
546
|
+
// [喵喵喵]: 定点保存不得用新画像重算未改写模型的来源;无记录时仅认领当前画像的同值字段。
|
|
547
|
+
const generated = source.previous.models[fullId]?.generatedClientHeaders ?? modelMetadata.generatedClientHeaders ?? {};
|
|
548
|
+
const persisted = mergeModelRequestHeaders(undefined, persistedModels.get(model.id)?.headers) ?? {};
|
|
549
|
+
modelMetadata.generatedClientHeaders = Object.fromEntries(Object.entries(generated)
|
|
550
|
+
.filter(([name, value]) => persisted[name.toLowerCase()] === value));
|
|
551
|
+
}
|
|
552
|
+
if (Object.keys(modelMetadata).length > 0) metadata.models[fullId] = modelMetadata;
|
|
535
553
|
}
|
|
536
554
|
}
|
|
537
555
|
return metadata;
|
|
538
556
|
}
|
|
539
557
|
|
|
540
|
-
export function serializeMetadataState(state: StateDocument): string {
|
|
541
|
-
return stringifyJson(extractMetadata(state));
|
|
558
|
+
export function serializeMetadataState(state: StateDocument, source?: HeaderSnapshotSource): string {
|
|
559
|
+
return stringifyJson(extractMetadata(state, source));
|
|
542
560
|
}
|
|
543
561
|
export function getStatePath(): string {
|
|
544
562
|
return STATE_PATH;
|
package/state-store.ts
CHANGED
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
|
|
6
6
|
import { setTimeout as delay } from "node:timers/promises";
|
|
7
7
|
import { getBuiltinProviderDefaults } from "./builtin-model-catalog.ts";
|
|
8
|
-
import { mergeCompatSettings } from "./compat-settings.ts";
|
|
9
8
|
import { cloneJson, cloneStringRecord, hasStringRecordEntries, isObjectRecord } from "./common.ts";
|
|
10
9
|
import { readStableTextFileSnapshot } from "./file-snapshot.ts";
|
|
11
10
|
import { t } from "./i18n.ts";
|
|
@@ -14,6 +13,7 @@ import {
|
|
|
14
13
|
hasPluginManagedProviderMarker,
|
|
15
14
|
readModelsJsonSnapshot,
|
|
16
15
|
type ModelsJsonDocument,
|
|
16
|
+
type ModelsJsonSnapshot,
|
|
17
17
|
type ModelsJsonModelEntry,
|
|
18
18
|
type ModelsJsonProviderEntry,
|
|
19
19
|
} from "./models-json-manager.ts";
|
|
@@ -29,11 +29,11 @@ import {
|
|
|
29
29
|
getStatePath as getMetadataStatePath,
|
|
30
30
|
readMetadataStateSnapshot,
|
|
31
31
|
type MetadataDocument,
|
|
32
|
+
type MetadataStateSnapshot,
|
|
32
33
|
type ParsedMetadataStateFile,
|
|
33
34
|
} from "./state-metadata-store.ts";
|
|
34
35
|
import type {
|
|
35
36
|
ApiKind,
|
|
36
|
-
CompatSettings,
|
|
37
37
|
ModelInputKind,
|
|
38
38
|
StateDocument,
|
|
39
39
|
StoredModel,
|
|
@@ -116,7 +116,6 @@ function buildStoredModelFromModelsJson(
|
|
|
116
116
|
providerApi: ApiKind,
|
|
117
117
|
providerBaseUrl: string,
|
|
118
118
|
providerNativeBaseUrl: string,
|
|
119
|
-
providerCompat: CompatSettings | undefined,
|
|
120
119
|
providerHeaders: Record<string, string> | undefined,
|
|
121
120
|
managed: boolean,
|
|
122
121
|
clientHeaderProfile: StoredProvider["clientHeaderProfile"],
|
|
@@ -128,14 +127,12 @@ function buildStoredModelFromModelsJson(
|
|
|
128
127
|
const explicitApi = typeof model.api === "string" && model.api ? model.api : undefined;
|
|
129
128
|
const effectiveApi = asApiKind(explicitApi) ?? providerApi;
|
|
130
129
|
const modelCompat = model.compat ? cloneJson(model.compat) : undefined;
|
|
131
|
-
const effectiveCompat = mergeCompatSettings(providerCompat, modelCompat);
|
|
132
130
|
const profileHeaders = managed
|
|
133
131
|
? getClientHeadersForProfile(
|
|
134
132
|
clientHeaderProfile,
|
|
135
133
|
effectiveApi,
|
|
136
134
|
customClientHeaders,
|
|
137
135
|
metadata.clientHeaderCaptures,
|
|
138
|
-
effectiveCompat,
|
|
139
136
|
)
|
|
140
137
|
: undefined;
|
|
141
138
|
const modelMetadata = metadata.models[getFullModelId(providerId, model.id)];
|
|
@@ -208,7 +205,6 @@ async function buildStoredProviderFromModelsJson(
|
|
|
208
205
|
api,
|
|
209
206
|
baseUrl,
|
|
210
207
|
nativeBaseUrl,
|
|
211
|
-
providerCompat,
|
|
212
208
|
entry.headers,
|
|
213
209
|
managed,
|
|
214
210
|
clientHeaderProfile,
|
|
@@ -291,29 +287,36 @@ export async function buildStateDocumentFromSources(
|
|
|
291
287
|
return state;
|
|
292
288
|
}
|
|
293
289
|
|
|
290
|
+
export interface StateSourceSnapshot {
|
|
291
|
+
models: ModelsJsonSnapshot;
|
|
292
|
+
metadata: MetadataStateSnapshot;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** 读取一致的双文件快照;事务存在或内容变化时返回 undefined,读取和解析错误仍向上传播。 */
|
|
296
|
+
export async function tryReadStateSnapshot(): Promise<StateSourceSnapshot | undefined> {
|
|
297
|
+
const journalBefore = await readStableTextFileSnapshot(CONFIGURATION_TRANSACTION_PATH);
|
|
298
|
+
if (journalBefore.source !== undefined) return undefined;
|
|
299
|
+
const [models, metadata] = await Promise.all([
|
|
300
|
+
readModelsJsonSnapshot(),
|
|
301
|
+
readMetadataStateSnapshot(),
|
|
302
|
+
]);
|
|
303
|
+
const [modelsAfter, metadataAfter, journalAfter] = await Promise.all([
|
|
304
|
+
readStableTextFileSnapshot(getModelsJsonPath()),
|
|
305
|
+
readStableTextFileSnapshot(getMetadataStatePath()),
|
|
306
|
+
readStableTextFileSnapshot(CONFIGURATION_TRANSACTION_PATH),
|
|
307
|
+
]);
|
|
308
|
+
if (journalAfter.source === undefined
|
|
309
|
+
&& modelsAfter.contentHash === models.contentHash
|
|
310
|
+
&& metadataAfter.contentHash === metadata.contentHash) {
|
|
311
|
+
return { models, metadata };
|
|
312
|
+
}
|
|
313
|
+
return undefined;
|
|
314
|
+
}
|
|
315
|
+
|
|
294
316
|
export async function readState(): Promise<StateDocument> {
|
|
295
317
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
296
|
-
const
|
|
297
|
-
if (
|
|
298
|
-
if (attempt < 2) await delay(10);
|
|
299
|
-
continue;
|
|
300
|
-
}
|
|
301
|
-
const [modelsSnapshot, metadataSnapshot] = await Promise.all([
|
|
302
|
-
readModelsJsonSnapshot(),
|
|
303
|
-
readMetadataStateSnapshot(),
|
|
304
|
-
]);
|
|
305
|
-
const [modelsAfter, metadataAfter, journalAfter] = await Promise.all([
|
|
306
|
-
readStableTextFileSnapshot(getModelsJsonPath()),
|
|
307
|
-
readStableTextFileSnapshot(getMetadataStatePath()),
|
|
308
|
-
readStableTextFileSnapshot(CONFIGURATION_TRANSACTION_PATH),
|
|
309
|
-
]);
|
|
310
|
-
if (
|
|
311
|
-
journalAfter.source === undefined
|
|
312
|
-
&& modelsAfter.contentHash === modelsSnapshot.contentHash
|
|
313
|
-
&& metadataAfter.contentHash === metadataSnapshot.contentHash
|
|
314
|
-
) {
|
|
315
|
-
return buildStateDocumentFromSources(modelsSnapshot.document, metadataSnapshot);
|
|
316
|
-
}
|
|
318
|
+
const snapshot = await tryReadStateSnapshot();
|
|
319
|
+
if (snapshot) return buildStateDocumentFromSources(snapshot.models.document, snapshot.metadata);
|
|
317
320
|
if (attempt < 2) await delay(10);
|
|
318
321
|
}
|
|
319
322
|
throw new Error(t("models.json/state.json 正在事务更新或持续变化;请稍后重试。"));
|
package/tui/dashboard.ts
CHANGED
|
@@ -125,17 +125,17 @@ async function saveProviderDraft(
|
|
|
125
125
|
draft: ReturnType<typeof createProviderDraft>,
|
|
126
126
|
oldProviderId: string | undefined,
|
|
127
127
|
): Promise<boolean> {
|
|
128
|
-
const state = await readState();
|
|
129
|
-
const builtInIds = await getBuiltinProviderIds();
|
|
130
|
-
const errors = validateProviderDraft(draft, state, builtInIds, oldProviderId);
|
|
131
|
-
if (errors.length > 0) {
|
|
132
|
-
notifyValidationErrors(ctx, t("接入配置无效"), errors);
|
|
133
|
-
return false;
|
|
134
|
-
}
|
|
135
|
-
const current = oldProviderId ? state.providers[oldProviderId] : state.providers[draft.providerId];
|
|
136
|
-
if (!(await confirmWarnings(ctx, getProviderChangeWarnings(current, draft)))) return false;
|
|
137
|
-
|
|
138
128
|
try {
|
|
129
|
+
const state = await readState();
|
|
130
|
+
const builtInIds = await getBuiltinProviderIds();
|
|
131
|
+
const errors = validateProviderDraft(draft, state, builtInIds, oldProviderId);
|
|
132
|
+
if (errors.length > 0) {
|
|
133
|
+
notifyValidationErrors(ctx, t("接入配置无效"), errors);
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
const current = oldProviderId ? state.providers[oldProviderId] : state.providers[draft.providerId];
|
|
137
|
+
if (!(await confirmWarnings(ctx, getProviderChangeWarnings(current, draft)))) return false;
|
|
138
|
+
|
|
139
139
|
await saveProviderConfiguration(pi, ctx, state, draft, oldProviderId);
|
|
140
140
|
return true;
|
|
141
141
|
} catch (error) {
|
|
@@ -150,13 +150,13 @@ async function saveModelDraft(
|
|
|
150
150
|
draft: ReturnType<typeof createModelDraftForStoredProvider>,
|
|
151
151
|
replacedModelId: string | undefined,
|
|
152
152
|
): Promise<boolean> {
|
|
153
|
-
const state = await readState();
|
|
154
|
-
const errors = validateModelDraft(draft, state, replacedModelId);
|
|
155
|
-
if (errors.length > 0) {
|
|
156
|
-
notifyValidationErrors(ctx, t("模型配置无效"), errors);
|
|
157
|
-
return false;
|
|
158
|
-
}
|
|
159
153
|
try {
|
|
154
|
+
const state = await readState();
|
|
155
|
+
const errors = validateModelDraft(draft, state, replacedModelId);
|
|
156
|
+
if (errors.length > 0) {
|
|
157
|
+
notifyValidationErrors(ctx, t("模型配置无效"), errors);
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
160
|
await saveModelConfiguration(pi, ctx, state, draft, replacedModelId);
|
|
161
161
|
return true;
|
|
162
162
|
} catch (error) {
|
|
@@ -171,20 +171,20 @@ async function saveNewProviderAndModelDraft(
|
|
|
171
171
|
providerDraft: ReturnType<typeof createProviderDraft>,
|
|
172
172
|
modelDraft: ReturnType<typeof createModelDraftForStoredProvider>,
|
|
173
173
|
): Promise<boolean> {
|
|
174
|
-
const state = await readState();
|
|
175
|
-
const builtInIds = await getBuiltinProviderIds();
|
|
176
|
-
const providerErrors = validateProviderDraft(providerDraft, state, builtInIds, undefined);
|
|
177
|
-
if (providerErrors.length > 0) {
|
|
178
|
-
notifyValidationErrors(ctx, t("接入配置无效"), providerErrors);
|
|
179
|
-
return false;
|
|
180
|
-
}
|
|
181
|
-
const providerState = upsertProviderInDocument(state, undefined, providerDraft);
|
|
182
|
-
const modelErrors = validateModelDraft(modelDraft, providerState, undefined);
|
|
183
|
-
if (modelErrors.length > 0) {
|
|
184
|
-
notifyValidationErrors(ctx, t("模型配置无效"), modelErrors);
|
|
185
|
-
return false;
|
|
186
|
-
}
|
|
187
174
|
try {
|
|
175
|
+
const state = await readState();
|
|
176
|
+
const builtInIds = await getBuiltinProviderIds();
|
|
177
|
+
const providerErrors = validateProviderDraft(providerDraft, state, builtInIds, undefined);
|
|
178
|
+
if (providerErrors.length > 0) {
|
|
179
|
+
notifyValidationErrors(ctx, t("接入配置无效"), providerErrors);
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
const providerState = upsertProviderInDocument(state, undefined, providerDraft);
|
|
183
|
+
const modelErrors = validateModelDraft(modelDraft, providerState, undefined);
|
|
184
|
+
if (modelErrors.length > 0) {
|
|
185
|
+
notifyValidationErrors(ctx, t("模型配置无效"), modelErrors);
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
188
|
await saveNewProviderWithModelConfiguration(pi, ctx, providerState, providerDraft, modelDraft);
|
|
189
189
|
return true;
|
|
190
190
|
} catch (error) {
|
package/tui/editor-model.ts
CHANGED
|
@@ -31,7 +31,7 @@ interface FieldRow {
|
|
|
31
31
|
|
|
32
32
|
|
|
33
33
|
function shouldShowOpenAIServiceTier(draft: ModelDraft): boolean {
|
|
34
|
-
return draft.api === "openai-responses";
|
|
34
|
+
return draft.providerManaged && draft.api === "openai-responses";
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
function shouldShowAnthropicThinkingProtocol(draft: ModelDraft): boolean {
|
|
@@ -182,6 +182,13 @@ async function pickModelFromUpstream(
|
|
|
182
182
|
): Promise<void> {
|
|
183
183
|
const params = {
|
|
184
184
|
providerId: draft.providerId,
|
|
185
|
+
providerManaged: draft.providerManaged,
|
|
186
|
+
providerHeaders: draft.providerHeaders,
|
|
187
|
+
modelHeaders: draft.modelHeaders,
|
|
188
|
+
compat: {
|
|
189
|
+
...draft.compat,
|
|
190
|
+
...(draft.api === "anthropic-messages" ? { forceAdaptiveThinking: draft.anthropicThinkingProtocol === "adaptive" } : {}),
|
|
191
|
+
},
|
|
185
192
|
api: draft.api,
|
|
186
193
|
baseUrl: draft.baseUrl,
|
|
187
194
|
apiKey: draft.apiKey,
|
|
@@ -360,6 +367,9 @@ export async function editModel(
|
|
|
360
367
|
summaryLines: [
|
|
361
368
|
t("接入 {providerId} · API {api}", { providerId: draft.providerId, api: formatApiShort(draft.api) }),
|
|
362
369
|
t("Ctrl+S 保存并启用模型;不切换当前会话模型"),
|
|
370
|
+
...(!draft.providerManaged && draft.api === "openai-responses"
|
|
371
|
+
? [t("Fast mode 需要先接管该接入;请先保存接入配置。")]
|
|
372
|
+
: []),
|
|
363
373
|
],
|
|
364
374
|
onAdjust: (id, direction) => {
|
|
365
375
|
if (!applyHorizontalToggle(draft, id, direction)) return undefined;
|
|
@@ -262,13 +262,13 @@ async function saveProfile(
|
|
|
262
262
|
draft: RequestHeaderProfileDraft,
|
|
263
263
|
oldProfileId: string | undefined,
|
|
264
264
|
): Promise<boolean> {
|
|
265
|
-
const state = await readState();
|
|
266
|
-
const errors = validateRequestHeaderProfileDraft(draft, state, oldProfileId);
|
|
267
|
-
if (errors.length > 0) {
|
|
268
|
-
notifyValidationErrors(ctx, errors);
|
|
269
|
-
return false;
|
|
270
|
-
}
|
|
271
265
|
try {
|
|
266
|
+
const state = await readState();
|
|
267
|
+
const errors = validateRequestHeaderProfileDraft(draft, state, oldProfileId);
|
|
268
|
+
if (errors.length > 0) {
|
|
269
|
+
notifyValidationErrors(ctx, errors);
|
|
270
|
+
return false;
|
|
271
|
+
}
|
|
272
272
|
await saveRequestHeaderProfileConfiguration(pi, ctx, state, draft, oldProfileId);
|
|
273
273
|
} catch (error) {
|
|
274
274
|
ctx.ui.notify(t("保存失败:{error}", { error: formatUnknownError(error) }), "error");
|
package/tui/model-list-fetch.ts
CHANGED
|
@@ -5,10 +5,11 @@ 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 {
|
|
8
|
+
import { mergeModelRequestHeaders } from "../presets/client-headers.ts";
|
|
9
|
+
import { buildModelRequestHeaders } from "../provider-registrar.ts";
|
|
9
10
|
import { appendUrlPath, resolveRuntimeBaseUrl, validateRequestBaseUrl } from "../runtime-base-url.ts";
|
|
10
11
|
import { isSensitiveHeaderName, redactSensitiveText } from "../sensitive-redaction.ts";
|
|
11
|
-
import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, ModelListFetchOutcome, StoredClientHeaderCapture } from "../types.ts";
|
|
12
|
+
import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, CompatSettings, ModelListFetchOutcome, StoredClientHeaderCapture } from "../types.ts";
|
|
12
13
|
import { extractValidatedModelIds, readBoundedResponseText } from "./model-list-validation.ts";
|
|
13
14
|
|
|
14
15
|
const MODEL_LIST_TIMEOUT_MS = 10_000;
|
|
@@ -61,7 +62,7 @@ function collectSensitiveHeaderValues(headers: Record<string, string> | undefine
|
|
|
61
62
|
|
|
62
63
|
async function resolveFetchAuth(
|
|
63
64
|
params: FetchModelIdsParams,
|
|
64
|
-
|
|
65
|
+
modelHeaders: Record<string, string> | undefined,
|
|
65
66
|
signal: AbortSignal,
|
|
66
67
|
): Promise<ResolvedFetchAuth> {
|
|
67
68
|
const providerConfig: ProviderConfig = {
|
|
@@ -70,11 +71,12 @@ async function resolveFetchAuth(
|
|
|
70
71
|
apiKey: params.apiKey.trim(),
|
|
71
72
|
api: params.api,
|
|
72
73
|
authHeader: params.authHeader,
|
|
73
|
-
headers:
|
|
74
|
+
headers: params.providerHeaders,
|
|
74
75
|
models: [{
|
|
75
76
|
id: TEMP_MODEL_ID,
|
|
76
77
|
name: TEMP_MODEL_ID,
|
|
77
78
|
api: params.api,
|
|
79
|
+
headers: modelHeaders,
|
|
78
80
|
reasoning: false,
|
|
79
81
|
input: ["text"],
|
|
80
82
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
@@ -162,6 +164,10 @@ async function requestModelIds(
|
|
|
162
164
|
|
|
163
165
|
export interface FetchModelIdsParams {
|
|
164
166
|
providerId: string;
|
|
167
|
+
providerManaged?: boolean;
|
|
168
|
+
providerHeaders?: Record<string, string>;
|
|
169
|
+
modelHeaders?: Record<string, string>;
|
|
170
|
+
compat?: CompatSettings;
|
|
165
171
|
api: ApiKind;
|
|
166
172
|
baseUrl: string;
|
|
167
173
|
apiKey: string;
|
|
@@ -180,13 +186,20 @@ async function fetchModelIdsWithSignal(
|
|
|
180
186
|
): Promise<ModelListFetchOutcome> {
|
|
181
187
|
throwIfAborted(signal);
|
|
182
188
|
validateRequestBaseUrl(params.baseUrl);
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
189
|
+
const modelHeaders = buildModelRequestHeaders(
|
|
190
|
+
{
|
|
191
|
+
api: params.api,
|
|
192
|
+
managed: params.providerManaged ?? true,
|
|
193
|
+
headers: params.providerHeaders,
|
|
194
|
+
compat: params.compat,
|
|
195
|
+
clientHeaderProfile: params.clientHeaderProfile,
|
|
196
|
+
customClientHeaders: params.customClientHeaders,
|
|
197
|
+
},
|
|
198
|
+
{ headers: params.modelHeaders },
|
|
199
|
+
{},
|
|
187
200
|
params.clientHeaderCaptures ?? {},
|
|
188
201
|
);
|
|
189
|
-
const auth = await resolveFetchAuth(params,
|
|
202
|
+
const auth = await resolveFetchAuth(params, modelHeaders, signal);
|
|
190
203
|
redactionSecrets.push(...auth.redactionSecrets);
|
|
191
204
|
const defaults: Record<string, string> = { accept: "application/json" };
|
|
192
205
|
if (params.api === "anthropic-messages") {
|
|
@@ -223,7 +236,12 @@ export async function fetchModelIds(
|
|
|
223
236
|
timedOut = true;
|
|
224
237
|
controller.abort(new Error(t("模型列表请求总计超时(10 秒)")));
|
|
225
238
|
}, MODEL_LIST_TIMEOUT_MS);
|
|
226
|
-
const redactionSecrets = [
|
|
239
|
+
const redactionSecrets = [
|
|
240
|
+
params.apiKey.trim(),
|
|
241
|
+
...collectSensitiveHeaderValues(params.providerHeaders),
|
|
242
|
+
...collectSensitiveHeaderValues(params.modelHeaders),
|
|
243
|
+
...collectSensitiveHeaderValues(params.customClientHeaders),
|
|
244
|
+
].filter(Boolean);
|
|
227
245
|
try {
|
|
228
246
|
return await fetchModelIdsWithSignal(params, controller.signal, redactionSecrets);
|
|
229
247
|
} catch (error) {
|
|
@@ -49,6 +49,7 @@ export function extractValidatedModelIds(envelope: unknown, api: ApiKind): strin
|
|
|
49
49
|
export async function readBoundedResponseText(response: Response, signal: AbortSignal): Promise<string> {
|
|
50
50
|
const declaredLength = Number.parseInt(response.headers.get("content-length") ?? "", 10);
|
|
51
51
|
if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
|
|
52
|
+
if (response.body) await waitWithSignal(response.body.cancel("response too large"), signal).catch(() => {});
|
|
52
53
|
throw new Error(t("模型列表响应体超过 {maxBytes} 字节上限", { maxBytes: MAX_RESPONSE_BYTES }));
|
|
53
54
|
}
|
|
54
55
|
if (!response.body) {
|
package/types.ts
CHANGED
|
@@ -130,6 +130,11 @@ export interface ProviderDraft {
|
|
|
130
130
|
export interface ModelDraft {
|
|
131
131
|
providerId: string;
|
|
132
132
|
providerName: string;
|
|
133
|
+
providerManaged: boolean;
|
|
134
|
+
/** 模型发现沿用的原生头与兼容参数,不作为表单可编辑字段。 */
|
|
135
|
+
providerHeaders?: Record<string, string>;
|
|
136
|
+
modelHeaders?: Record<string, string>;
|
|
137
|
+
compat?: CompatSettings;
|
|
133
138
|
api: ApiKind;
|
|
134
139
|
baseUrl: string;
|
|
135
140
|
apiKey: string;
|