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.
@@ -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 { readFile } from "node:fs/promises";
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
- readModelsJsonSnapshot,
23
- renameModelInDoc,
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
- export function buildModelsJsonProviderEntry(
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 [providerId, provider] of Object.entries(document.providers)) {
147
- if (provider.models.length === 0) {
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 async function syncStateToModelsJson(document: StateDocument, removedProviderIds: string[] = []): Promise<void> {
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
- oldProviderId: string,
171
- newProviderId: string,
172
- ): Promise<void> {
173
- const snapshot = await readModelsJsonSnapshot();
174
- const renamedDocument = renameProviderInDoc(snapshot.document, oldProviderId, newProviderId);
175
- const nextDocument = buildSynchronizedModelsDocument(document, renamedDocument);
176
- await writeModelsJsonSnapshot(snapshot, nextDocument);
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 async function syncModelRenameToModelsJson(
188
+ export function buildModelsDocumentWithoutModel(
180
189
  document: StateDocument,
190
+ sourceDocument: ModelsJsonDocument,
181
191
  providerId: string,
182
- oldModelId: string,
183
- newModelId: string,
184
- ): Promise<void> {
185
- const snapshot = await readModelsJsonSnapshot();
186
- const renamedDocument = renameModelInDoc(snapshot.document, providerId, oldModelId, newModelId);
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 removeEnabledModelPattern(patterns: string[], fullModelId: string): string[] {
238
- return patterns.filter((pattern) => !sameModelPatternBase(splitThinkingSuffix(pattern).base, fullModelId));
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
- async function atomicWriteJson(path: string, value: unknown): Promise<void> {
242
- await atomicWriteText(path, stringifyJson(value));
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
- async function readSettingsFile(path: string): Promise<Record<string, unknown>> {
246
- const source = await readFile(path, "utf8");
247
- const parsed = JSON.parse(stripJsonNoise(source));
248
- if (!isObjectRecord(parsed)) throw new Error(`${path} 根节点必须是对象`);
249
- return parsed;
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
- async function updateProjectEnabledModels(cwd: string, update: (patterns: string[]) => string[]): Promise<EnabledModelUpdate> {
253
- const path = join(cwd, CONFIG_DIR_NAME, "settings.json");
254
- const settings = await readSettingsFile(path);
255
- const current = settings.enabledModels;
256
- if (!Array.isArray(current)) return { mode: "all-enabled" };
257
- const patterns = current.filter((item): item is string => typeof item === "string");
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 flushGlobalSettingsWrite(settings: SettingsManager): Promise<void> {
267
- await settings.flush();
268
- const errors = settings.drainErrors();
269
- if (errors.length > 0) {
270
- const detail = errors.map((entry) => `${entry.scope}: ${entry.error.message}`).join("; ");
271
- throw new Error(`settings.json enabledModels 写入失败:${detail}`);
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 updateGlobalEnabledModels(cwd: string, update: (patterns: string[]) => string[]): Promise<EnabledModelUpdate> {
276
- const settings = SettingsManager.create(cwd, getAgentDir());
277
- const current = settings.getGlobalSettings().enabledModels;
278
- if (!Array.isArray(current) || current.length === 0) return { mode: "all-enabled" };
279
- const patterns = current.filter((item): item is string => typeof item === "string");
280
- if (patterns.length === 0) return { mode: "all-enabled" };
281
- const next = update(patterns);
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
- const settings = SettingsManager.create(cwd, getAgentDir());
294
- const projectEnabled = settings.getProjectSettings().enabledModels;
295
- const update = (patterns: string[]) => upsertEnabledModelPattern(patterns, fullModelId, replacedFullModelId);
296
- if (Array.isArray(projectEnabled)) {
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
- const settings = SettingsManager.create(cwd, getAgentDir());
304
- const projectEnabled = settings.getProjectSettings().enabledModels;
305
- const update = (patterns: string[]) => removeEnabledModelPattern(patterns, fullModelId);
306
- if (Array.isArray(projectEnabled)) {
307
- return updateProjectEnabledModels(cwd, update);
308
- }
309
- return updateGlobalEnabledModels(cwd, update);
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
- const settings = SettingsManager.create(cwd, getAgentDir());
336
- const projectEnabled = settings.getProjectSettings().enabledModels;
337
- const update = (patterns: string[]) => replaceEnabledProviderPatterns(patterns, oldProviderId, newProviderId);
338
- if (Array.isArray(projectEnabled)) {
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
- export function normalizeOpenAIResponsesInstructionsPayload(payload: unknown): PayloadRecord | undefined {
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.1.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.5"
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
- export const ANTHROPIC_INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
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
- export function getRecommendedClientHeaderProfile(api: ApiKind): ClientHeaderProfileId {
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") {
@@ -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
- export const PROVIDER_PRESETS: ProviderPreset[] = [
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
- export function getProtocolDisplayName(api: ApiKind): string {
79
- return findPresetForApi(api).shortLabel;
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
  }
@@ -1,6 +1,6 @@
1
1
  // thinkingLevelMap 的协议默认值与持久化归一化。
2
2
 
3
- import type { ApiKind, CompatSettings, ThinkingLevelMap } from "../types.ts";
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
- export function buildThinkingLevelMap(api: ApiKind, reasoning: boolean): ThinkingLevelMap | undefined {
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
- export function applyProtocolThinkingLevelLimits(
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 { ...thinkingLevelMap, ...EXTENDED_THINKING_LEVEL_MAP };
53
+ return { ...EXTENDED_THINKING_LEVEL_MAP, ...thinkingLevelMap };
54
54
  }
55
55
 
56
- export function mergeThinkingLevelMap(
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
- }
@@ -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
- export function buildProviderConfig(
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);
@@ -1,7 +1,4 @@
1
- // runtime-base-url.ts
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 stripTrailingV1(baseUrl: string): string {
13
- const trimmed = trimTrailingSlashes(baseUrl);
14
- return trimmed.toLowerCase().endsWith("/v1") ? trimmed.slice(0, -3) : trimmed;
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 hasRootPathWithoutQueryOrHash(url: URL): boolean {
18
- return (url.pathname === "" || url.pathname === "/") && !url.search && !url.hash;
17
+ function trimPathTrailingSlashes(pathname: string): string {
18
+ const trimmed = pathname.replace(/\/+$/, "");
19
+ return trimmed || "/";
19
20
  }
20
21
 
21
- function appendV1ForRootUrl(baseUrl: string): string {
22
- const trimmed = trimTrailingSlashes(baseUrl);
23
- try {
24
- const parsed = new URL(trimmed);
25
- if (hasRootPathWithoutQueryOrHash(parsed)) {
26
- return `${trimmed}/v1`;
27
- }
28
- } catch {
29
- return trimmed;
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 trimmed;
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 trimmed = trimTrailingSlashes(baseUrl);
36
- try {
37
- const parsed = new URL(trimmed);
38
- // Google Generative Language 的根域名不是可直接请求的模型 API 根路径;
39
- // pi 的 google-generative-ai 适配器需要带版本段的 baseUrl。
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
- return trimmed;
70
+ parsed.pathname = trimPathTrailingSlashes(parsed.pathname);
71
+ return parsed.toString();
47
72
  }
48
73
 
49
74
  export function resolveRuntimeBaseUrl(api: ApiKind, baseUrl: string): string {