pi-model-manager 0.1.0 → 0.2.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/README.en.md +9 -6
- package/README.md +9 -6
- package/atomic-write.ts +4 -32
- package/common.ts +0 -17
- package/configuration-lock.ts +136 -0
- package/configuration-persistence.ts +281 -34
- package/file-snapshot.ts +76 -0
- package/header-profile-mutations.ts +29 -7
- package/index.ts +24 -10
- package/local-proxy-service.ts +93 -30
- package/model-mutations.ts +58 -32
- package/models-json-manager.ts +43 -79
- package/models-json-sync.ts +117 -93
- package/openai-responses-payload.ts +1 -1
- package/package.json +11 -5
- package/presets/client-headers.ts +2 -15
- package/presets/providers.ts +27 -4
- package/presets/thinking.ts +5 -13
- package/provider-registrar.ts +9 -2
- package/runtime-base-url.ts +55 -30
- package/sensitive-redaction.ts +46 -0
- package/state-cache.ts +2 -1
- package/state-document.ts +14 -14
- package/state-metadata-store.ts +65 -31
- package/state-store.ts +85 -31
- package/tui/dashboard.ts +19 -6
- package/tui/editor-model.ts +18 -4
- package/tui/editor-provider.ts +11 -10
- package/tui/header-profiles-panel.ts +58 -3
- package/tui/model-list-fetch.ts +136 -114
- package/tui/model-list-validation.ts +79 -0
- package/tui/persistent-menu.ts +96 -14
- package/tui/ui-helpers.ts +146 -96
- package/types.ts +7 -14
- package/models-json-mutations.ts +0 -90
- package/tui/models-json-panel.ts +0 -269
package/models-json-sync.ts
CHANGED
|
@@ -9,21 +9,21 @@ import {
|
|
|
9
9
|
getAgentDir,
|
|
10
10
|
ModelRegistry,
|
|
11
11
|
ModelRuntime,
|
|
12
|
-
SettingsManager,
|
|
13
12
|
type ExtensionCommandContext,
|
|
14
13
|
} from "@earendil-works/pi-coding-agent";
|
|
15
|
-
import {
|
|
14
|
+
import { createRequire } from "node:module";
|
|
16
15
|
import { join } from "node:path";
|
|
17
16
|
import { minimatch } from "minimatch";
|
|
18
17
|
import { atomicWriteText } from "./atomic-write.ts";
|
|
19
18
|
import { cloneJson, formatUnknownError, isObjectRecord, stringifyJson, stripJsonNoise } from "./common.ts";
|
|
19
|
+
import { withConfigurationLock } from "./configuration-lock.ts";
|
|
20
|
+
import { readStableTextFileSnapshot } from "./file-snapshot.ts";
|
|
20
21
|
import {
|
|
22
|
+
deleteModelInDoc,
|
|
21
23
|
deleteProviderInDoc,
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
renameProviderInDoc,
|
|
24
|
+
markProviderEntryAsPluginManaged,
|
|
25
|
+
setModelInDoc,
|
|
25
26
|
setProviderInDoc,
|
|
26
|
-
writeModelsJsonSnapshot,
|
|
27
27
|
type ModelsJsonDocument,
|
|
28
28
|
type ModelsJsonModelEntry,
|
|
29
29
|
type ModelsJsonProviderEntry,
|
|
@@ -101,7 +101,7 @@ function buildModelsJsonModelEntry(
|
|
|
101
101
|
return next;
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
function buildModelsJsonProviderEntry(
|
|
105
105
|
provider: StoredProvider,
|
|
106
106
|
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
|
|
107
107
|
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>> = {},
|
|
@@ -131,20 +131,22 @@ export function buildModelsJsonProviderEntry(
|
|
|
131
131
|
clientHeaderCaptures,
|
|
132
132
|
existingModels.get(model.id),
|
|
133
133
|
));
|
|
134
|
-
return next;
|
|
134
|
+
return markProviderEntryAsPluginManaged(next);
|
|
135
135
|
}
|
|
136
136
|
|
|
137
137
|
export function buildSynchronizedModelsDocument(
|
|
138
138
|
document: StateDocument,
|
|
139
139
|
sourceDocument: ModelsJsonDocument,
|
|
140
140
|
removedProviderIds: string[] = [],
|
|
141
|
+
changedProviderIds: string[] = document.managedProviderIds,
|
|
141
142
|
): ModelsJsonDocument {
|
|
142
143
|
let nextDocument = sourceDocument;
|
|
143
144
|
for (const providerId of removedProviderIds) {
|
|
144
145
|
nextDocument = deleteProviderInDoc(nextDocument, providerId);
|
|
145
146
|
}
|
|
146
|
-
for (const
|
|
147
|
-
|
|
147
|
+
for (const providerId of [...new Set(changedProviderIds)]) {
|
|
148
|
+
const provider = document.providers[providerId];
|
|
149
|
+
if (!provider || provider.models.length === 0) {
|
|
148
150
|
nextDocument = deleteProviderInDoc(nextDocument, providerId);
|
|
149
151
|
continue;
|
|
150
152
|
}
|
|
@@ -159,36 +161,40 @@ export function buildSynchronizedModelsDocument(
|
|
|
159
161
|
return nextDocument;
|
|
160
162
|
}
|
|
161
163
|
|
|
162
|
-
export
|
|
163
|
-
const snapshot = await readModelsJsonSnapshot();
|
|
164
|
-
const nextDocument = buildSynchronizedModelsDocument(document, snapshot.document, removedProviderIds);
|
|
165
|
-
await writeModelsJsonSnapshot(snapshot, nextDocument);
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
export async function syncProviderRenameToModelsJson(
|
|
164
|
+
export function buildModelsDocumentWithSynchronizedModel(
|
|
169
165
|
document: StateDocument,
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const
|
|
176
|
-
|
|
166
|
+
sourceDocument: ModelsJsonDocument,
|
|
167
|
+
providerId: string,
|
|
168
|
+
modelId: string,
|
|
169
|
+
replacedModelId?: string,
|
|
170
|
+
): ModelsJsonDocument {
|
|
171
|
+
const provider = document.providers[providerId];
|
|
172
|
+
if (!provider) throw new Error(`接入不存在:${providerId}`);
|
|
173
|
+
const model = provider.models.find((candidate) => candidate.id === modelId);
|
|
174
|
+
if (!model) throw new Error(`模型不存在:${providerId}/${modelId}`);
|
|
175
|
+
const sourceModel = sourceDocument.providers[providerId]?.models?.find(
|
|
176
|
+
(candidate) => candidate.id === modelId || candidate.id === replacedModelId,
|
|
177
|
+
);
|
|
178
|
+
const entry = buildModelsJsonModelEntry(
|
|
179
|
+
provider,
|
|
180
|
+
model,
|
|
181
|
+
document.requestHeaderProfiles,
|
|
182
|
+
document.clientHeaderCaptures,
|
|
183
|
+
sourceModel,
|
|
184
|
+
);
|
|
185
|
+
return setModelInDoc(sourceDocument, providerId, entry, replacedModelId);
|
|
177
186
|
}
|
|
178
187
|
|
|
179
|
-
export
|
|
188
|
+
export function buildModelsDocumentWithoutModel(
|
|
180
189
|
document: StateDocument,
|
|
190
|
+
sourceDocument: ModelsJsonDocument,
|
|
181
191
|
providerId: string,
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
const nextDocument = buildSynchronizedModelsDocument(document, renamedDocument);
|
|
188
|
-
await writeModelsJsonSnapshot(snapshot, nextDocument);
|
|
192
|
+
modelId: string,
|
|
193
|
+
): ModelsJsonDocument {
|
|
194
|
+
return document.providers[providerId]
|
|
195
|
+
? deleteModelInDoc(sourceDocument, providerId, modelId)
|
|
196
|
+
: deleteProviderInDoc(sourceDocument, providerId);
|
|
189
197
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
198
|
function splitThinkingSuffix(pattern: string): { base: string; suffix: string } {
|
|
193
199
|
const index = pattern.lastIndexOf(":");
|
|
194
200
|
if (index < 0) return { base: pattern, suffix: "" };
|
|
@@ -234,55 +240,75 @@ function upsertEnabledModelPattern(patterns: string[], fullModelId: string, repl
|
|
|
234
240
|
return dedupeModelPatterns(next);
|
|
235
241
|
}
|
|
236
242
|
|
|
237
|
-
function
|
|
238
|
-
|
|
243
|
+
function removeEnabledModelPatterns(patterns: string[], fullModelIds: readonly string[]): string[] {
|
|
244
|
+
const removedIds = new Set(fullModelIds.map((fullModelId) => fullModelId.toLowerCase()));
|
|
245
|
+
return patterns.filter((pattern) => !removedIds.has(splitThinkingSuffix(pattern).base.toLowerCase()));
|
|
239
246
|
}
|
|
240
247
|
|
|
241
|
-
|
|
242
|
-
|
|
248
|
+
function removeEnabledProviderPatterns(patterns: string[], providerId: string): string[] {
|
|
249
|
+
const providerPrefix = `${providerId}/`.toLowerCase();
|
|
250
|
+
return patterns.filter((pattern) => !splitThinkingSuffix(pattern).base.toLowerCase().startsWith(providerPrefix));
|
|
243
251
|
}
|
|
244
252
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
253
|
+
interface SettingsFileLock {
|
|
254
|
+
lock(path: string, options: {
|
|
255
|
+
realpath: false;
|
|
256
|
+
retries: { retries: number; factor: number; minTimeout: number; maxTimeout: number };
|
|
257
|
+
}): Promise<() => Promise<void>>;
|
|
250
258
|
}
|
|
251
259
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
if (patterns.length === 0) return { mode: "all-enabled" };
|
|
259
|
-
const next = update(patterns);
|
|
260
|
-
if (JSON.stringify(next) === JSON.stringify(patterns)) return { mode: "unchanged", scope: "project" };
|
|
261
|
-
settings.enabledModels = next;
|
|
262
|
-
await atomicWriteJson(path, settings);
|
|
263
|
-
return { mode: "updated", scope: "project" };
|
|
260
|
+
const require = createRequire(import.meta.url);
|
|
261
|
+
const settingsFileLock = require("proper-lockfile") as SettingsFileLock;
|
|
262
|
+
|
|
263
|
+
interface LockedSettingsUpdate {
|
|
264
|
+
configured: boolean;
|
|
265
|
+
outcome: EnabledModelUpdate;
|
|
264
266
|
}
|
|
265
267
|
|
|
266
|
-
async function
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
268
|
+
async function updateLockedSettings(
|
|
269
|
+
path: string,
|
|
270
|
+
scope: "global" | "project",
|
|
271
|
+
update: (patterns: string[]) => string[],
|
|
272
|
+
): Promise<LockedSettingsUpdate> {
|
|
273
|
+
const initialSnapshot = await readStableTextFileSnapshot(path);
|
|
274
|
+
if (initialSnapshot.source === undefined) {
|
|
275
|
+
return { configured: false, outcome: { mode: "all-enabled" } };
|
|
276
|
+
}
|
|
277
|
+
const release = await settingsFileLock.lock(path, {
|
|
278
|
+
realpath: false,
|
|
279
|
+
retries: { retries: 10, factor: 1, minTimeout: 20, maxTimeout: 20 },
|
|
280
|
+
});
|
|
281
|
+
try {
|
|
282
|
+
const snapshot = await readStableTextFileSnapshot(path);
|
|
283
|
+
const settings = snapshot.source === undefined ? {} : JSON.parse(stripJsonNoise(snapshot.source));
|
|
284
|
+
if (!isObjectRecord(settings)) throw new Error(`${path} 根节点必须是对象`);
|
|
285
|
+
const current = settings.enabledModels;
|
|
286
|
+
if (!Array.isArray(current)) return { configured: false, outcome: { mode: "all-enabled" } };
|
|
287
|
+
const patterns = current.filter((item): item is string => typeof item === "string");
|
|
288
|
+
if (patterns.length === 0) return { configured: true, outcome: { mode: "all-enabled" } };
|
|
289
|
+
const next = update(patterns);
|
|
290
|
+
if (JSON.stringify(next) === JSON.stringify(patterns)) {
|
|
291
|
+
return { configured: true, outcome: { mode: "unchanged", scope } };
|
|
292
|
+
}
|
|
293
|
+
const currentSnapshot = await readStableTextFileSnapshot(path);
|
|
294
|
+
if (currentSnapshot.contentHash !== snapshot.contentHash) {
|
|
295
|
+
throw new Error(`${path} 已被未遵守 Pi 文件锁的编辑器修改;已取消 enabledModels 同步,请重试。`);
|
|
296
|
+
}
|
|
297
|
+
settings.enabledModels = next;
|
|
298
|
+
await atomicWriteText(path, stringifyJson(settings));
|
|
299
|
+
return { configured: true, outcome: { mode: "updated", scope } };
|
|
300
|
+
} finally {
|
|
301
|
+
await release();
|
|
272
302
|
}
|
|
273
303
|
}
|
|
274
304
|
|
|
275
|
-
async function
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
const
|
|
280
|
-
if (
|
|
281
|
-
|
|
282
|
-
if (JSON.stringify(next) === JSON.stringify(patterns)) return { mode: "unchanged", scope: "global" };
|
|
283
|
-
settings.setEnabledModels(next);
|
|
284
|
-
await flushGlobalSettingsWrite(settings);
|
|
285
|
-
return { mode: "updated", scope: "global" };
|
|
305
|
+
async function updateEnabledModelsForNextPiStart(
|
|
306
|
+
cwd: string,
|
|
307
|
+
update: (patterns: string[]) => string[],
|
|
308
|
+
): Promise<EnabledModelUpdate> {
|
|
309
|
+
const projectUpdate = await updateLockedSettings(join(cwd, CONFIG_DIR_NAME, "settings.json"), "project", update);
|
|
310
|
+
if (projectUpdate.configured) return projectUpdate.outcome;
|
|
311
|
+
return (await updateLockedSettings(join(getAgentDir(), "settings.json"), "global", update)).outcome;
|
|
286
312
|
}
|
|
287
313
|
|
|
288
314
|
export async function enableModelForNextPiStart(
|
|
@@ -290,23 +316,24 @@ export async function enableModelForNextPiStart(
|
|
|
290
316
|
fullModelId: string,
|
|
291
317
|
replacedFullModelId?: string,
|
|
292
318
|
): Promise<EnabledModelUpdate> {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
return updateProjectEnabledModels(cwd, update);
|
|
298
|
-
}
|
|
299
|
-
return updateGlobalEnabledModels(cwd, update);
|
|
319
|
+
return withConfigurationLock(() => updateEnabledModelsForNextPiStart(
|
|
320
|
+
cwd,
|
|
321
|
+
(patterns) => upsertEnabledModelPattern(patterns, fullModelId, replacedFullModelId),
|
|
322
|
+
));
|
|
300
323
|
}
|
|
301
324
|
|
|
302
325
|
export async function removeModelFromNextPiStart(cwd: string, fullModelId: string): Promise<EnabledModelUpdate> {
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
326
|
+
return withConfigurationLock(() => updateEnabledModelsForNextPiStart(
|
|
327
|
+
cwd,
|
|
328
|
+
(patterns) => removeEnabledModelPatterns(patterns, [fullModelId]),
|
|
329
|
+
));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export async function removeProviderFromNextPiStart(cwd: string, providerId: string): Promise<EnabledModelUpdate> {
|
|
333
|
+
return withConfigurationLock(() => updateEnabledModelsForNextPiStart(
|
|
334
|
+
cwd,
|
|
335
|
+
(patterns) => removeEnabledProviderPatterns(patterns, providerId),
|
|
336
|
+
));
|
|
310
337
|
}
|
|
311
338
|
|
|
312
339
|
function replaceEnabledProviderPatterns(
|
|
@@ -332,13 +359,10 @@ export async function replaceProviderInEnabledModelsForNextPiStart(
|
|
|
332
359
|
newProviderId: string,
|
|
333
360
|
): Promise<EnabledModelUpdate> {
|
|
334
361
|
if (oldProviderId === newProviderId) return { mode: "unchanged" };
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
return updateProjectEnabledModels(cwd, update);
|
|
340
|
-
}
|
|
341
|
-
return updateGlobalEnabledModels(cwd, update);
|
|
362
|
+
return withConfigurationLock(() => updateEnabledModelsForNextPiStart(
|
|
363
|
+
cwd,
|
|
364
|
+
(patterns) => replaceEnabledProviderPatterns(patterns, oldProviderId, newProviderId),
|
|
365
|
+
));
|
|
342
366
|
}
|
|
343
367
|
|
|
344
368
|
async function verifyRegistryModel(
|
|
@@ -45,7 +45,7 @@ function hasNonEmptyInstructions(payload: PayloadRecord): boolean {
|
|
|
45
45
|
return typeof payload.instructions === "string" && payload.instructions.trim().length > 0;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
function normalizeOpenAIResponsesInstructionsPayload(payload: unknown): PayloadRecord | undefined {
|
|
49
49
|
if (!isPayloadRecord(payload)) return undefined;
|
|
50
50
|
if (hasNonEmptyInstructions(payload)) return undefined;
|
|
51
51
|
|
package/package.json
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-model-manager",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "A TUI model and provider manager for Pi with native models.json persistence, request-header profiles, proxy routing, and protocol compatibility.",
|
|
5
5
|
"type": "module",
|
|
6
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
|
+
},
|
|
7
10
|
"files": [
|
|
8
11
|
"NOTICE",
|
|
9
12
|
"README.en.md",
|
|
@@ -23,12 +26,14 @@
|
|
|
23
26
|
"request-pipeline.ts",
|
|
24
27
|
"model-mutations.ts",
|
|
25
28
|
"header-profile-mutations.ts",
|
|
26
|
-
"models-json-mutations.ts",
|
|
27
29
|
"rescue.ts",
|
|
28
30
|
"atomic-write.ts",
|
|
29
31
|
"common.ts",
|
|
30
32
|
"config-value-reference.ts",
|
|
31
33
|
"configuration-persistence.ts",
|
|
34
|
+
"configuration-lock.ts",
|
|
35
|
+
"file-snapshot.ts",
|
|
36
|
+
"sensitive-redaction.ts",
|
|
32
37
|
"compat-settings.ts",
|
|
33
38
|
"runtime-base-url.ts",
|
|
34
39
|
"types.ts",
|
|
@@ -67,8 +72,9 @@
|
|
|
67
72
|
"@earendil-works/pi-tui": ">=0.75.0"
|
|
68
73
|
},
|
|
69
74
|
"dependencies": {
|
|
70
|
-
"http-proxy-agent": "9.1.0",
|
|
71
|
-
"https-proxy-agent": "9.1.0",
|
|
72
|
-
"minimatch": "10.2.
|
|
75
|
+
"http-proxy-agent": "^9.1.0",
|
|
76
|
+
"https-proxy-agent": "^9.1.0",
|
|
77
|
+
"minimatch": "^10.2.6",
|
|
78
|
+
"proper-lockfile": "^4.1.2"
|
|
73
79
|
}
|
|
74
80
|
}
|
|
@@ -7,7 +7,7 @@ import { cloneStringRecord, hasStringRecordEntries } from "../common.ts";
|
|
|
7
7
|
import type { ApiKind, BuiltInClientHeaderProfileId, ClientHeaderProfileId, CompatSettings, StoredClientHeaderCapture } from "../types.ts";
|
|
8
8
|
import { CLAUDE_CODE_CLIENT_HEADERS, CODEX_CLI_CLIENT_HEADERS } from "./builtin-client-headers.ts";
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
const ANTHROPIC_INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
export const CLIENT_HEADER_PROFILE_LABELS: Record<ClientHeaderProfileId, string> = {
|
|
@@ -71,7 +71,7 @@ export function stripManagedClientHeaders(
|
|
|
71
71
|
return hasStringRecordEntries(nativeHeaders) ? nativeHeaders : undefined;
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
-
|
|
74
|
+
function getRecommendedClientHeaderProfile(api: ApiKind): ClientHeaderProfileId {
|
|
75
75
|
if (api === "anthropic-messages") return "claude-code";
|
|
76
76
|
if (api === "openai-completions" || api === "openai-responses") return "codex-cli";
|
|
77
77
|
return "disabled";
|
|
@@ -104,19 +104,6 @@ export function getClientHeadersForProfile(
|
|
|
104
104
|
}
|
|
105
105
|
return hasStringRecordEntries(customHeaders) ? cloneHeadersForCompat(customHeaders, api, compat) : undefined;
|
|
106
106
|
}
|
|
107
|
-
|
|
108
|
-
export function normalizeClientHeaderProfile(value: unknown): ClientHeaderProfileId | undefined {
|
|
109
|
-
if (value === "recommended" || value === "protocol-default") return "recommended";
|
|
110
|
-
if (value === "disabled" || value === "claude-code" || value === "codex-cli" || value === "custom") return value;
|
|
111
|
-
return undefined;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
export function inferClientHeaderProfile(stored: unknown, modelHeaders: Record<string, string> | undefined): ClientHeaderProfileId {
|
|
115
|
-
const normalized = normalizeClientHeaderProfile(stored);
|
|
116
|
-
if (normalized) return normalized;
|
|
117
|
-
return hasStringRecordEntries(modelHeaders) ? "custom" : "recommended";
|
|
118
|
-
}
|
|
119
|
-
|
|
120
107
|
export function getClientHeaderProfileDisplay(profile: ClientHeaderProfileId, api: ApiKind): string {
|
|
121
108
|
const resolved = resolveClientHeaderProfile(profile, api);
|
|
122
109
|
if (profile === "recommended") {
|
package/presets/providers.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 4 种 API 协议的默认预设。新建接入/模型时用,便于一键填好常用字段。
|
|
2
2
|
|
|
3
|
-
import type { ApiKind, ModelInputKind } from "../types.ts";
|
|
3
|
+
import type { ApiKind, ModelInputKind, ProviderDraft } from "../types.ts";
|
|
4
4
|
|
|
5
5
|
export interface ProviderPreset {
|
|
6
6
|
api: ApiKind;
|
|
@@ -16,7 +16,7 @@ export interface ProviderPreset {
|
|
|
16
16
|
defaultReasoning: boolean;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
const PROVIDER_PRESETS: ProviderPreset[] = [
|
|
20
20
|
{
|
|
21
21
|
api: "openai-responses",
|
|
22
22
|
label: "OpenAI Responses — 标准 instructions / input",
|
|
@@ -75,6 +75,29 @@ export function findPresetForApi(api: ApiKind | undefined): ProviderPreset {
|
|
|
75
75
|
return PROVIDER_PRESETS.find((preset) => preset.api === api) ?? PROVIDER_PRESETS[0]!;
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
|
|
79
|
-
|
|
78
|
+
function normalizePresetUrl(value: string): string | undefined {
|
|
79
|
+
try {
|
|
80
|
+
const url = new URL(value.trim());
|
|
81
|
+
url.pathname = url.pathname.replace(/\/+$/, "") || "/";
|
|
82
|
+
return url.toString();
|
|
83
|
+
} catch {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function stillUsesPresetUrl(value: string, presetUrl: string): boolean {
|
|
89
|
+
const normalizedValue = normalizePresetUrl(value);
|
|
90
|
+
const normalizedPreset = normalizePresetUrl(presetUrl);
|
|
91
|
+
return normalizedValue !== undefined && normalizedValue === normalizedPreset;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function switchProviderDraftApiPreset(draft: ProviderDraft, nextApi: ApiKind): void {
|
|
95
|
+
if (draft.api === nextApi) return;
|
|
96
|
+
const previousPreset = findPresetForApi(draft.api);
|
|
97
|
+
const nextPreset = findPresetForApi(nextApi);
|
|
98
|
+
const replaceBaseUrl = stillUsesPresetUrl(draft.baseUrl, previousPreset.baseUrl);
|
|
99
|
+
const replaceApiKey = draft.apiKey === previousPreset.apiKey;
|
|
100
|
+
draft.api = nextApi;
|
|
101
|
+
if (replaceBaseUrl) draft.baseUrl = nextPreset.baseUrl;
|
|
102
|
+
if (replaceApiKey) draft.apiKey = nextPreset.apiKey;
|
|
80
103
|
}
|
package/presets/thinking.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// thinkingLevelMap 的协议默认值与持久化归一化。
|
|
2
2
|
|
|
3
|
-
import type { ApiKind,
|
|
3
|
+
import type { ApiKind, ThinkingLevelMap } from "../types.ts";
|
|
4
4
|
|
|
5
5
|
const EXTENDED_THINKING_LEVEL_MAP: ThinkingLevelMap = {
|
|
6
6
|
xhigh: "xhigh",
|
|
@@ -35,14 +35,14 @@ function isLegacyShiftedMaxLadder(map: ThinkingLevelMap): boolean {
|
|
|
35
35
|
&& map.max === undefined;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
function buildThinkingLevelMap(api: ApiKind, reasoning: boolean): ThinkingLevelMap | undefined {
|
|
39
39
|
if (!reasoning) return undefined;
|
|
40
40
|
if (api === "google-generative-ai") return { ...GOOGLE_GENERATIVE_AI_THINKING_LEVEL_MAP };
|
|
41
41
|
if (api === "openai-completions" || api === "openai-responses") return { ...OPENAI_THINKING_LEVEL_MAP };
|
|
42
42
|
return { ...EXTENDED_THINKING_LEVEL_MAP };
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
-
|
|
45
|
+
function applyProtocolThinkingLevelLimits(
|
|
46
46
|
api: ApiKind,
|
|
47
47
|
thinkingLevelMap: ThinkingLevelMap | undefined,
|
|
48
48
|
): ThinkingLevelMap | undefined {
|
|
@@ -50,10 +50,10 @@ export function applyProtocolThinkingLevelLimits(
|
|
|
50
50
|
return { ...(thinkingLevelMap ?? {}), ...GOOGLE_GENERATIVE_AI_THINKING_LEVEL_MAP };
|
|
51
51
|
}
|
|
52
52
|
if (!thinkingLevelMap) return undefined;
|
|
53
|
-
return { ...
|
|
53
|
+
return { ...EXTENDED_THINKING_LEVEL_MAP, ...thinkingLevelMap };
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
function mergeThinkingLevelMap(
|
|
57
57
|
defaultMap: ThinkingLevelMap | undefined,
|
|
58
58
|
storedMap: ThinkingLevelMap | undefined,
|
|
59
59
|
): ThinkingLevelMap | undefined {
|
|
@@ -71,11 +71,3 @@ export function normalizeThinkingLevelMap(
|
|
|
71
71
|
if (storedMap && isLegacyShiftedMaxLadder(storedMap)) return defaultMap;
|
|
72
72
|
return applyProtocolThinkingLevelLimits(api, mergeThinkingLevelMap(defaultMap, storedMap));
|
|
73
73
|
}
|
|
74
|
-
|
|
75
|
-
export function mergeCompatSettings(
|
|
76
|
-
providerCompat: CompatSettings | undefined,
|
|
77
|
-
modelCompat: CompatSettings | undefined,
|
|
78
|
-
): CompatSettings | undefined {
|
|
79
|
-
if (providerCompat && modelCompat) return { ...providerCompat, ...modelCompat };
|
|
80
|
-
return modelCompat ?? providerCompat;
|
|
81
|
-
}
|
package/provider-registrar.ts
CHANGED
|
@@ -31,7 +31,7 @@ type ProviderModelConfig = NonNullable<ProviderConfig["models"]>[number];
|
|
|
31
31
|
|
|
32
32
|
const REGISTERED_PROVIDER_CONFIGS = new Map<string, ProviderConfig>();
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
function buildProviderConfig(
|
|
35
35
|
provider: StoredProvider,
|
|
36
36
|
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
|
|
37
37
|
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>> = {},
|
|
@@ -112,6 +112,7 @@ export function buildModelRequestHeaders(
|
|
|
112
112
|
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
|
|
113
113
|
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
|
|
114
114
|
): Record<string, string> | undefined {
|
|
115
|
+
if (!provider.managed) return model.headers ? { ...model.headers } : undefined;
|
|
115
116
|
const customHeaders = provider.clientHeaderProfile === "custom"
|
|
116
117
|
? resolveProviderCustomHeaders(provider, requestHeaderProfiles)
|
|
117
118
|
: {};
|
|
@@ -167,7 +168,7 @@ export function unregisterManagedProvider(pi: ExtensionAPI, providerId: string):
|
|
|
167
168
|
}
|
|
168
169
|
|
|
169
170
|
async function canRegisterManagedProvider(providerId: string, provider: StoredProvider): Promise<boolean> {
|
|
170
|
-
return provider.models.length > 0 && !(await isBuiltinProviderId(providerId));
|
|
171
|
+
return provider.managed && provider.models.length > 0 && !(await isBuiltinProviderId(providerId));
|
|
171
172
|
}
|
|
172
173
|
|
|
173
174
|
function replaceManagedProviderConfig(
|
|
@@ -260,6 +261,12 @@ async function reconcileAllFromState(
|
|
|
260
261
|
reconcile: StateProviderReconciler,
|
|
261
262
|
): Promise<string[]> {
|
|
262
263
|
const warnings: string[] = [];
|
|
264
|
+
const activeProviderIds = new Set(
|
|
265
|
+
[...document.managedProviderIds].filter((providerId) => document.providers[providerId]?.managed),
|
|
266
|
+
);
|
|
267
|
+
for (const providerId of REGISTERED_PROVIDER_CONFIGS.keys()) {
|
|
268
|
+
if (!activeProviderIds.has(providerId)) unregisterManagedProvider(pi, providerId);
|
|
269
|
+
}
|
|
263
270
|
for (const [providerId, provider] of Object.entries(document.providers)) {
|
|
264
271
|
try {
|
|
265
272
|
await reconcile(pi, providerId, provider, document.requestHeaderProfiles, document.clientHeaderCaptures);
|
package/runtime-base-url.ts
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
// 将用户在 TUI 中填写的 Base URL 转成 pi 各内置 SDK 实际需要的 baseUrl。
|
|
4
|
-
// 约定:state.json 保存用户输入;注册到 pi 和 bootstrap 到 models.json 时使用运行时 URL。
|
|
1
|
+
// 将用户填写的 Base URL 转成各协议实际请求根地址,并提供保留 query/hash 的路径追加。
|
|
5
2
|
|
|
6
3
|
import type { ApiKind } from "./types.ts";
|
|
7
4
|
|
|
@@ -9,41 +6,69 @@ function trimTrailingSlashes(value: string): string {
|
|
|
9
6
|
return value.trim().replace(/\/+$/, "");
|
|
10
7
|
}
|
|
11
8
|
|
|
12
|
-
function
|
|
13
|
-
|
|
14
|
-
|
|
9
|
+
function parseBaseUrl(baseUrl: string): URL | undefined {
|
|
10
|
+
try {
|
|
11
|
+
return new URL(baseUrl.trim());
|
|
12
|
+
} catch {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
function
|
|
18
|
-
|
|
17
|
+
function trimPathTrailingSlashes(pathname: string): string {
|
|
18
|
+
const trimmed = pathname.replace(/\/+$/, "");
|
|
19
|
+
return trimmed || "/";
|
|
19
20
|
}
|
|
20
21
|
|
|
21
|
-
function
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
|
|
22
|
+
function hasRootPath(url: URL): boolean {
|
|
23
|
+
return trimPathTrailingSlashes(url.pathname) === "/";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function appendPathSegments(url: URL, segments: string[]): string {
|
|
27
|
+
const basePath = trimPathTrailingSlashes(url.pathname);
|
|
28
|
+
const suffix = segments.map((segment) => segment.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
|
|
29
|
+
url.pathname = `${basePath === "/" ? "" : basePath}/${suffix}` || "/";
|
|
30
|
+
return url.toString();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function appendUrlPath(baseUrl: string, ...segments: string[]): string {
|
|
34
|
+
const parsed = parseBaseUrl(baseUrl);
|
|
35
|
+
if (parsed) return appendPathSegments(parsed, segments);
|
|
36
|
+
const suffix = segments.map((segment) => segment.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
|
|
37
|
+
return `${trimTrailingSlashes(baseUrl)}/${suffix}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function stripTrailingV1(baseUrl: string): string {
|
|
41
|
+
const parsed = parseBaseUrl(baseUrl);
|
|
42
|
+
if (!parsed) {
|
|
43
|
+
const trimmed = trimTrailingSlashes(baseUrl);
|
|
44
|
+
return trimmed.toLowerCase().endsWith("/v1") ? trimmed.slice(0, -3) : trimmed;
|
|
45
|
+
}
|
|
46
|
+
const path = trimPathTrailingSlashes(parsed.pathname);
|
|
47
|
+
if (path.toLowerCase().endsWith("/v1")) {
|
|
48
|
+
parsed.pathname = path.slice(0, -3) || "/";
|
|
49
|
+
} else {
|
|
50
|
+
parsed.pathname = path;
|
|
30
51
|
}
|
|
31
|
-
return
|
|
52
|
+
return parsed.toString();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function appendV1ForRootUrl(baseUrl: string): string {
|
|
56
|
+
const parsed = parseBaseUrl(baseUrl);
|
|
57
|
+
if (!parsed) return trimTrailingSlashes(baseUrl);
|
|
58
|
+
if (hasRootPath(parsed)) return appendPathSegments(parsed, ["v1"]);
|
|
59
|
+
parsed.pathname = trimPathTrailingSlashes(parsed.pathname);
|
|
60
|
+
return parsed.toString();
|
|
32
61
|
}
|
|
33
62
|
|
|
34
63
|
function appendGoogleGenerativeApiVersionForRootUrl(baseUrl: string): string {
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
if (parsed.hostname === "generativelanguage.googleapis.com" && hasRootPathWithoutQueryOrHash(parsed)) {
|
|
41
|
-
return `${trimmed}/v1beta`;
|
|
42
|
-
}
|
|
43
|
-
} catch {
|
|
44
|
-
return trimmed;
|
|
64
|
+
const parsed = parseBaseUrl(baseUrl);
|
|
65
|
+
if (!parsed) return trimTrailingSlashes(baseUrl);
|
|
66
|
+
// Google Generative Language 的根域名不是可直接请求的模型 API 根路径。
|
|
67
|
+
if (parsed.hostname === "generativelanguage.googleapis.com" && hasRootPath(parsed)) {
|
|
68
|
+
return appendPathSegments(parsed, ["v1beta"]);
|
|
45
69
|
}
|
|
46
|
-
|
|
70
|
+
parsed.pathname = trimPathTrailingSlashes(parsed.pathname);
|
|
71
|
+
return parsed.toString();
|
|
47
72
|
}
|
|
48
73
|
|
|
49
74
|
export function resolveRuntimeBaseUrl(api: ApiKind, baseUrl: string): string {
|