pi-model-manager 0.1.0 → 0.3.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 +119 -23
- package/README.md +119 -23
- package/atomic-write.ts +4 -32
- package/common.ts +0 -17
- package/configuration-lock.ts +136 -0
- package/configuration-persistence.ts +289 -38
- package/file-snapshot.ts +76 -0
- package/header-profile-mutations.ts +29 -7
- package/index.ts +43 -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 +12 -7
- package/presets/builtin-client-headers.ts +7 -7
- package/presets/client-headers.ts +2 -15
- package/presets/providers.ts +30 -4
- package/presets/thinking.ts +5 -13
- package/provider-registrar.ts +9 -2
- package/runtime-base-url.ts +64 -33
- package/sensitive-redaction.ts +46 -0
- package/state-cache.ts +2 -1
- package/state-document.ts +37 -14
- package/state-metadata-store.ts +65 -31
- package/state-store.ts +85 -31
- package/tui/dashboard.ts +60 -21
- package/tui/editor-model.ts +74 -99
- package/tui/editor-provider.ts +69 -68
- package/tui/header-profiles-panel.ts +96 -24
- package/tui/model-list-fetch.ts +136 -114
- package/tui/model-list-validation.ts +79 -0
- package/tui/model-picker.ts +5 -3
- package/tui/persistent-menu.ts +309 -84
- package/tui/ui-helpers.ts +217 -111
- package/types.ts +7 -14
- package/models-json-mutations.ts +0 -90
- package/tui/models-json-panel.ts +0 -269
package/state-store.ts
CHANGED
|
@@ -3,20 +3,30 @@
|
|
|
3
3
|
// StateDocument 合成层:从 Pi 原生 models.json 读取模型定义,再叠加
|
|
4
4
|
// state.json 中的插件私有元数据,提供 TUI 与运行时注册使用的统一视图。
|
|
5
5
|
|
|
6
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
7
|
import { getBuiltinProviderDefaults } from "./builtin-model-catalog.ts";
|
|
7
8
|
import { mergeCompatSettings } from "./compat-settings.ts";
|
|
8
|
-
import { cloneJson, hasStringRecordEntries, isObjectRecord } from "./common.ts";
|
|
9
|
-
import {
|
|
9
|
+
import { cloneJson, cloneStringRecord, hasStringRecordEntries, isObjectRecord } from "./common.ts";
|
|
10
|
+
import { readStableTextFileSnapshot } from "./file-snapshot.ts";
|
|
11
|
+
import {
|
|
12
|
+
getModelsJsonPath,
|
|
13
|
+
hasPluginManagedProviderMarker,
|
|
14
|
+
readModelsJsonSnapshot,
|
|
15
|
+
type ModelsJsonDocument,
|
|
16
|
+
type ModelsJsonModelEntry,
|
|
17
|
+
type ModelsJsonProviderEntry,
|
|
18
|
+
} from "./models-json-manager.ts";
|
|
10
19
|
import {
|
|
11
20
|
getClientHeadersForProfile,
|
|
12
21
|
stripManagedClientHeaders,
|
|
13
22
|
} from "./presets/client-headers.ts";
|
|
14
23
|
import { normalizeThinkingLevelMap } from "./presets/thinking.ts";
|
|
15
24
|
import {
|
|
25
|
+
CONFIGURATION_TRANSACTION_PATH,
|
|
16
26
|
getStatePath as getMetadataStatePath,
|
|
17
|
-
|
|
18
|
-
writeMetadataState,
|
|
27
|
+
readMetadataStateSnapshot,
|
|
19
28
|
type MetadataDocument,
|
|
29
|
+
type ParsedMetadataStateFile,
|
|
20
30
|
} from "./state-metadata-store.ts";
|
|
21
31
|
import type {
|
|
22
32
|
ApiKind,
|
|
@@ -31,13 +41,11 @@ import type {
|
|
|
31
41
|
} from "./types.ts";
|
|
32
42
|
import { ZERO_COST } from "./types.ts";
|
|
33
43
|
|
|
34
|
-
export { STATE_PATH } from "./state-metadata-store.ts";
|
|
35
|
-
|
|
36
44
|
const API_KINDS = new Set<ApiKind>(["openai-completions", "openai-responses", "anthropic-messages", "google-generative-ai"]);
|
|
37
45
|
const INPUT_KINDS = new Set<ModelInputKind>(["text", "image"]);
|
|
38
46
|
|
|
39
47
|
function createEmptyStateDocument(): StateDocument {
|
|
40
|
-
return { version:
|
|
48
|
+
return { version: 2, providers: {}, managedProviderIds: [], requestHeaderProfiles: {}, clientHeaderCaptures: {} };
|
|
41
49
|
}
|
|
42
50
|
|
|
43
51
|
function asApiKind(value: unknown): ApiKind | undefined {
|
|
@@ -98,6 +106,7 @@ function buildStoredModelFromModelsJson(
|
|
|
98
106
|
providerApi: ApiKind,
|
|
99
107
|
providerBaseUrl: string,
|
|
100
108
|
providerCompat: CompatSettings | undefined,
|
|
109
|
+
managed: boolean,
|
|
101
110
|
clientHeaderProfile: StoredProvider["clientHeaderProfile"],
|
|
102
111
|
customClientHeaders: Record<string, string>,
|
|
103
112
|
model: ModelsJsonModelEntry,
|
|
@@ -108,14 +117,18 @@ function buildStoredModelFromModelsJson(
|
|
|
108
117
|
const effectiveApi = asApiKind(explicitApi) ?? providerApi;
|
|
109
118
|
const modelCompat = model.compat ? cloneJson(model.compat) : undefined;
|
|
110
119
|
const effectiveCompat = mergeCompatSettings(providerCompat, modelCompat);
|
|
111
|
-
const profileHeaders =
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
120
|
+
const profileHeaders = managed
|
|
121
|
+
? getClientHeadersForProfile(
|
|
122
|
+
clientHeaderProfile,
|
|
123
|
+
effectiveApi,
|
|
124
|
+
customClientHeaders,
|
|
125
|
+
metadata.clientHeaderCaptures,
|
|
126
|
+
effectiveCompat,
|
|
127
|
+
)
|
|
128
|
+
: undefined;
|
|
129
|
+
const nativeHeaders = managed
|
|
130
|
+
? stripManagedClientHeaders(model.headers, profileHeaders)
|
|
131
|
+
: cloneStringRecord(model.headers);
|
|
119
132
|
const stored: StoredModel = {
|
|
120
133
|
id: model.id,
|
|
121
134
|
reasoning: model.reasoning ?? false,
|
|
@@ -143,6 +156,7 @@ async function buildStoredProviderFromModelsJson(
|
|
|
143
156
|
providerId: string,
|
|
144
157
|
entry: ModelsJsonProviderEntry,
|
|
145
158
|
metadata: MetadataDocument,
|
|
159
|
+
requirePluginManagedProviderMarker: boolean,
|
|
146
160
|
): Promise<StoredProvider | undefined> {
|
|
147
161
|
const rawModels = entry.models ?? [];
|
|
148
162
|
if (rawModels.length === 0) return undefined;
|
|
@@ -154,8 +168,10 @@ async function buildStoredProviderFromModelsJson(
|
|
|
154
168
|
if (!api || !baseUrl) return undefined;
|
|
155
169
|
|
|
156
170
|
const providerMetadata = metadata.providers[providerId];
|
|
157
|
-
const
|
|
158
|
-
|
|
171
|
+
const managed = metadata.managedProviderIds.includes(providerId)
|
|
172
|
+
&& (!requirePluginManagedProviderMarker || hasPluginManagedProviderMarker(entry));
|
|
173
|
+
const clientHeaderProfile = managed ? providerMetadata?.clientHeaderProfile ?? "recommended" : "disabled";
|
|
174
|
+
const customClientHeaders = managed && clientHeaderProfile === "custom"
|
|
159
175
|
? resolveProviderCustomHeaders(providerMetadata, metadata)
|
|
160
176
|
: {};
|
|
161
177
|
const providerCompat = entry.compat ? cloneJson(entry.compat) : undefined;
|
|
@@ -165,6 +181,7 @@ async function buildStoredProviderFromModelsJson(
|
|
|
165
181
|
api,
|
|
166
182
|
baseUrl,
|
|
167
183
|
providerCompat,
|
|
184
|
+
managed,
|
|
168
185
|
clientHeaderProfile,
|
|
169
186
|
customClientHeaders,
|
|
170
187
|
model,
|
|
@@ -177,6 +194,7 @@ async function buildStoredProviderFromModelsJson(
|
|
|
177
194
|
name: entry.name || providerId,
|
|
178
195
|
api,
|
|
179
196
|
baseUrl,
|
|
197
|
+
managed,
|
|
180
198
|
clientHeaderProfile,
|
|
181
199
|
models,
|
|
182
200
|
};
|
|
@@ -185,50 +203,86 @@ async function buildStoredProviderFromModelsJson(
|
|
|
185
203
|
if (entry.headers !== undefined) provider.headers = cloneJson(entry.headers);
|
|
186
204
|
if (providerCompat) provider.compat = providerCompat;
|
|
187
205
|
if (entry.modelOverrides !== undefined) provider.modelOverrides = cloneJson(entry.modelOverrides);
|
|
188
|
-
if (provider.clientHeaderProfile === "custom" && providerMetadata?.requestHeaderProfileId) {
|
|
206
|
+
if (managed && provider.clientHeaderProfile === "custom" && providerMetadata?.requestHeaderProfileId) {
|
|
189
207
|
provider.requestHeaderProfileId = providerMetadata.requestHeaderProfileId;
|
|
190
208
|
}
|
|
191
|
-
if (provider.clientHeaderProfile === "custom" && hasStringRecordEntries(providerMetadata?.customClientHeaders)) {
|
|
209
|
+
if (managed && provider.clientHeaderProfile === "custom" && hasStringRecordEntries(providerMetadata?.customClientHeaders)) {
|
|
192
210
|
provider.customClientHeaders = cloneJson(providerMetadata!.customClientHeaders!);
|
|
193
211
|
}
|
|
194
|
-
if (providerMetadata?.httpProxyEnabled !== undefined) provider.httpProxyEnabled = providerMetadata.httpProxyEnabled;
|
|
195
|
-
if (providerMetadata?.httpProxyUrl !== undefined) provider.httpProxyUrl = providerMetadata.httpProxyUrl;
|
|
212
|
+
if (managed && providerMetadata?.httpProxyEnabled !== undefined) provider.httpProxyEnabled = providerMetadata.httpProxyEnabled;
|
|
213
|
+
if (managed && providerMetadata?.httpProxyUrl !== undefined) provider.httpProxyUrl = providerMetadata.httpProxyUrl;
|
|
196
214
|
return provider;
|
|
197
215
|
}
|
|
198
216
|
|
|
199
217
|
export async function buildStateDocumentFromModelsJson(
|
|
200
218
|
document: ModelsJsonDocument,
|
|
201
219
|
metadata: MetadataDocument,
|
|
220
|
+
requirePluginManagedProviderMarker = false,
|
|
202
221
|
): Promise<StateDocument> {
|
|
203
222
|
const providers: StateDocument["providers"] = {};
|
|
204
223
|
for (const [providerId, entry] of Object.entries(document.providers)) {
|
|
205
|
-
const provider = await buildStoredProviderFromModelsJson(
|
|
224
|
+
const provider = await buildStoredProviderFromModelsJson(
|
|
225
|
+
providerId,
|
|
226
|
+
entry,
|
|
227
|
+
metadata,
|
|
228
|
+
requirePluginManagedProviderMarker,
|
|
229
|
+
);
|
|
206
230
|
if (provider) providers[providerId] = provider;
|
|
207
231
|
}
|
|
208
232
|
return {
|
|
209
|
-
version:
|
|
233
|
+
version: 2,
|
|
210
234
|
providers,
|
|
235
|
+
managedProviderIds: Object.entries(providers)
|
|
236
|
+
.filter(([, provider]) => provider.managed)
|
|
237
|
+
.map(([providerId]) => providerId),
|
|
211
238
|
requestHeaderProfiles: metadata.requestHeaderProfiles,
|
|
212
239
|
clientHeaderCaptures: metadata.clientHeaderCaptures,
|
|
213
240
|
};
|
|
214
241
|
}
|
|
215
242
|
|
|
216
|
-
export async function
|
|
217
|
-
|
|
243
|
+
export async function buildStateDocumentFromSources(
|
|
244
|
+
modelsDocument: ModelsJsonDocument,
|
|
245
|
+
metadataFile: ParsedMetadataStateFile,
|
|
246
|
+
): Promise<StateDocument> {
|
|
218
247
|
const state = await buildStateDocumentFromModelsJson(
|
|
219
|
-
|
|
220
|
-
metadata,
|
|
248
|
+
modelsDocument,
|
|
249
|
+
metadataFile.metadata,
|
|
250
|
+
metadataFile.requirePluginManagedProviderMarker,
|
|
221
251
|
);
|
|
222
|
-
for (const [providerId, provider] of Object.entries(legacyProviders)) {
|
|
252
|
+
for (const [providerId, provider] of Object.entries(metadataFile.legacyProviders)) {
|
|
223
253
|
if (!state.providers[providerId]) state.providers[providerId] = provider;
|
|
254
|
+
if (!state.managedProviderIds.includes(providerId)) state.managedProviderIds.push(providerId);
|
|
224
255
|
}
|
|
225
256
|
return state;
|
|
226
257
|
}
|
|
227
258
|
|
|
228
|
-
export async function
|
|
229
|
-
|
|
259
|
+
export async function readState(): Promise<StateDocument> {
|
|
260
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
261
|
+
const journalBefore = await readStableTextFileSnapshot(CONFIGURATION_TRANSACTION_PATH);
|
|
262
|
+
if (journalBefore.source !== undefined) {
|
|
263
|
+
if (attempt < 2) await delay(10);
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
const [modelsSnapshot, metadataSnapshot] = await Promise.all([
|
|
267
|
+
readModelsJsonSnapshot(),
|
|
268
|
+
readMetadataStateSnapshot(),
|
|
269
|
+
]);
|
|
270
|
+
const [modelsAfter, metadataAfter, journalAfter] = await Promise.all([
|
|
271
|
+
readStableTextFileSnapshot(getModelsJsonPath()),
|
|
272
|
+
readStableTextFileSnapshot(getMetadataStatePath()),
|
|
273
|
+
readStableTextFileSnapshot(CONFIGURATION_TRANSACTION_PATH),
|
|
274
|
+
]);
|
|
275
|
+
if (
|
|
276
|
+
journalAfter.source === undefined
|
|
277
|
+
&& modelsAfter.contentHash === modelsSnapshot.contentHash
|
|
278
|
+
&& metadataAfter.contentHash === metadataSnapshot.contentHash
|
|
279
|
+
) {
|
|
280
|
+
return buildStateDocumentFromSources(modelsSnapshot.document, metadataSnapshot);
|
|
281
|
+
}
|
|
282
|
+
if (attempt < 2) await delay(10);
|
|
283
|
+
}
|
|
284
|
+
throw new Error("models.json/state.json 正在事务更新或持续变化;请稍后重试。");
|
|
230
285
|
}
|
|
231
|
-
|
|
232
286
|
export function getStatePath(): string {
|
|
233
287
|
return getMetadataStatePath();
|
|
234
288
|
}
|
package/tui/dashboard.ts
CHANGED
|
@@ -37,44 +37,51 @@ import { editModel } from "./editor-model.ts";
|
|
|
37
37
|
import { editProvider } from "./editor-provider.ts";
|
|
38
38
|
import { showPersistentShortcutMenu, type MenuCursor } from "./persistent-menu.ts";
|
|
39
39
|
import {
|
|
40
|
-
PROVIDER_CONSOLE_HEADER,
|
|
41
40
|
formatModelListHeader,
|
|
42
41
|
formatModelListRow,
|
|
42
|
+
formatProviderConsoleHeader,
|
|
43
43
|
formatProviderConsoleRow,
|
|
44
44
|
formatProviderDetailLines,
|
|
45
45
|
formatProviderEndpointLine,
|
|
46
46
|
formatProviderSummaryLine,
|
|
47
|
+
getModelColumnWidths,
|
|
48
|
+
getProviderDisplayLabel,
|
|
49
|
+
getProviderNameColumnWidth,
|
|
47
50
|
} from "./ui-helpers.ts";
|
|
48
51
|
import { runHeaderProfilesPanel } from "./header-profiles-panel.ts";
|
|
49
52
|
|
|
50
53
|
interface DashboardRow {
|
|
51
54
|
providerId: string;
|
|
52
55
|
label: string;
|
|
56
|
+
searchText: string;
|
|
53
57
|
}
|
|
54
58
|
|
|
55
59
|
interface ProviderMenuRow {
|
|
56
60
|
modelId: string;
|
|
57
61
|
model: StoredModel;
|
|
58
62
|
label: string;
|
|
63
|
+
searchText: string;
|
|
59
64
|
}
|
|
60
65
|
|
|
61
|
-
function buildRows(document: StateDocument): DashboardRow[] {
|
|
66
|
+
function buildRows(document: StateDocument, builtInProviderIds: ReadonlySet<string>): DashboardRow[] {
|
|
62
67
|
return Object.keys(document.providers)
|
|
68
|
+
.filter((providerId) => !builtInProviderIds.has(providerId))
|
|
63
69
|
.sort((a, b) => a.localeCompare(b))
|
|
64
|
-
.map((providerId) =>
|
|
65
|
-
providerId
|
|
66
|
-
label
|
|
67
|
-
|
|
70
|
+
.map((providerId) => {
|
|
71
|
+
const provider = document.providers[providerId]!;
|
|
72
|
+
const label = formatProviderConsoleRow(providerId, provider, 81, { requestHeaderProfiles: document.requestHeaderProfiles });
|
|
73
|
+
// [喵喵喵]: label 已被列宽截断,搜索需要补上完整的接入 ID 与名称。
|
|
74
|
+
return { providerId, label, searchText: `${providerId} ${getProviderDisplayName(providerId, provider)} ${label}` };
|
|
75
|
+
});
|
|
68
76
|
}
|
|
69
77
|
|
|
70
78
|
function buildProviderMenuRows(provider: StoredProvider): ProviderMenuRow[] {
|
|
71
79
|
return [...provider.models]
|
|
72
80
|
.sort((a, b) => a.id.localeCompare(b.id))
|
|
73
|
-
.map((model) =>
|
|
74
|
-
|
|
75
|
-
model,
|
|
76
|
-
|
|
77
|
-
}));
|
|
81
|
+
.map((model) => {
|
|
82
|
+
const label = formatModelListRow(provider, model);
|
|
83
|
+
return { modelId: model.id, model, label, searchText: `${model.id} ${model.name ?? ""} ${label}` };
|
|
84
|
+
});
|
|
78
85
|
}
|
|
79
86
|
|
|
80
87
|
function notifyValidationErrors(ctx: ExtensionCommandContext, title: string, errors: string[]): void {
|
|
@@ -233,11 +240,12 @@ async function showProviderMenu(pi: ExtensionAPI, ctx: ExtensionCommandContext,
|
|
|
233
240
|
return true;
|
|
234
241
|
}
|
|
235
242
|
const rows = buildProviderMenuRows(currentProvider);
|
|
243
|
+
const modelColumns = getModelColumnWidths(currentProvider.models);
|
|
236
244
|
const action = await showPersistentShortcutMenu<ProviderShortcut>(
|
|
237
245
|
ctx,
|
|
238
246
|
`/model-manager / ${getProviderDisplayName(providerId, currentProvider)}`,
|
|
239
247
|
"",
|
|
240
|
-
rows.map((row, index) => ({ id: `${index}`, label: row.label })),
|
|
248
|
+
rows.map((row, index) => ({ id: `${index}`, label: row.label, searchText: row.searchText })),
|
|
241
249
|
cursor,
|
|
242
250
|
[
|
|
243
251
|
{ input: "a", shortcut: "add-model" },
|
|
@@ -249,9 +257,20 @@ async function showProviderMenu(pi: ExtensionAPI, ctx: ExtensionCommandContext,
|
|
|
249
257
|
formatProviderSummaryLine(currentProvider, state.requestHeaderProfiles),
|
|
250
258
|
formatProviderEndpointLine(currentProvider),
|
|
251
259
|
],
|
|
252
|
-
tableHeader: formatModelListHeader(currentProvider),
|
|
260
|
+
tableHeader: (width) => formatModelListHeader(currentProvider, width, modelColumns),
|
|
261
|
+
formatRow: (menuRow, width, theme) => {
|
|
262
|
+
const row = rows[Number.parseInt(menuRow.id, 10)];
|
|
263
|
+
return row ? formatModelListRow(currentProvider, row.model, width, { ...modelColumns, theme }) : menuRow.label;
|
|
264
|
+
},
|
|
253
265
|
visibleRows: Math.min(12, Math.max(1, rows.length)),
|
|
254
|
-
|
|
266
|
+
hints: [
|
|
267
|
+
{ key: "↑↓", label: "选择" },
|
|
268
|
+
{ key: "Enter", label: "编辑模型" },
|
|
269
|
+
{ key: "A", label: "添加模型" },
|
|
270
|
+
{ key: "E", label: "编辑接入" },
|
|
271
|
+
{ key: "D", label: "删除模型" },
|
|
272
|
+
{ key: "Esc", label: "返回" },
|
|
273
|
+
],
|
|
255
274
|
emptyLabel: "暂无模型;按 a 添加第一个模型",
|
|
256
275
|
},
|
|
257
276
|
);
|
|
@@ -323,11 +342,15 @@ export async function runDashboard(pi: ExtensionAPI, ctx: ExtensionCommandContex
|
|
|
323
342
|
const cursor: MenuCursor = { index: 0 };
|
|
324
343
|
while (true) {
|
|
325
344
|
const state = await readState();
|
|
326
|
-
const
|
|
327
|
-
const
|
|
345
|
+
const builtInProviderIds = await getBuiltinProviderIds();
|
|
346
|
+
const rows = buildRows(state, builtInProviderIds);
|
|
347
|
+
const nameWidth = getProviderNameColumnWidth(
|
|
348
|
+
rows.map((row) => getProviderDisplayLabel(row.providerId, state.providers[row.providerId]!)),
|
|
349
|
+
);
|
|
350
|
+
const modelCount = rows.reduce((sum, row) => sum + (state.providers[row.providerId]?.models.length ?? 0), 0);
|
|
328
351
|
const profileCount = Object.keys(state.requestHeaderProfiles).length;
|
|
329
352
|
const captureCount = Object.keys(state.clientHeaderCaptures).length;
|
|
330
|
-
const menuRows = rows.map((r, index) => ({ id: `${index}`, label: r.label }));
|
|
353
|
+
const menuRows = rows.map((r, index) => ({ id: `${index}`, label: r.label, searchText: r.searchText }));
|
|
331
354
|
const action = await showPersistentShortcutMenu<DashboardShortcut>(
|
|
332
355
|
ctx,
|
|
333
356
|
"/model-manager",
|
|
@@ -341,13 +364,29 @@ export async function runDashboard(pi: ExtensionAPI, ctx: ExtensionCommandContex
|
|
|
341
364
|
],
|
|
342
365
|
{
|
|
343
366
|
summaryLines: [`${rows.length} 接入 · ${modelCount} 模型 · ${captureCount} 内置抓包 · ${profileCount} 自定义请求头`],
|
|
344
|
-
tableHeader:
|
|
345
|
-
|
|
367
|
+
tableHeader: (width) => formatProviderConsoleHeader(width, { nameWidth }),
|
|
368
|
+
formatRow: (menuRow, width, theme) => {
|
|
369
|
+
const row = rows[Number.parseInt(menuRow.id, 10)];
|
|
370
|
+
const provider = row ? state.providers[row.providerId] : undefined;
|
|
371
|
+
return row && provider
|
|
372
|
+
? formatProviderConsoleRow(row.providerId, provider, width, { requestHeaderProfiles: state.requestHeaderProfiles, theme, nameWidth })
|
|
373
|
+
: menuRow.label;
|
|
374
|
+
},
|
|
375
|
+
getDetailLines: (selectedRow, theme) => {
|
|
346
376
|
const row = rows[Number.parseInt(selectedRow?.id ?? "", 10)];
|
|
347
377
|
const provider = row ? state.providers[row.providerId] : undefined;
|
|
348
|
-
return row && provider
|
|
378
|
+
return row && provider
|
|
379
|
+
? formatProviderDetailLines(row.providerId, provider, { requestHeaderProfiles: state.requestHeaderProfiles, theme })
|
|
380
|
+
: [];
|
|
349
381
|
},
|
|
350
|
-
|
|
382
|
+
hints: [
|
|
383
|
+
{ key: "↑↓", label: "选择" },
|
|
384
|
+
{ key: "Enter", label: "进入" },
|
|
385
|
+
{ key: "N", label: "新建接入" },
|
|
386
|
+
{ key: "D", label: "删除接入" },
|
|
387
|
+
{ key: "H", label: "请求头" },
|
|
388
|
+
{ key: "Esc", label: "退出" },
|
|
389
|
+
],
|
|
351
390
|
emptyLabel: "暂无自定义接入;按 n 新建",
|
|
352
391
|
},
|
|
353
392
|
);
|
package/tui/editor-model.ts
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
// 关键差异:
|
|
5
5
|
// - 请求头已经收敛到接入级;模型编辑器只编辑模型自身能力
|
|
6
6
|
// - 提供"从上游拉取模型 ID 列表"入口(OpenAI/Anthropic/Google)
|
|
7
|
-
// -
|
|
7
|
+
// - 视觉支持用开关式 select,保存时仍映射为 text / text,image
|
|
8
8
|
|
|
9
|
-
import type
|
|
10
|
-
import type { AnthropicThinkingProtocol, BuiltInClientHeaderProfileId, ModelDraft, ReasoningMode, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
|
|
9
|
+
import { BorderedLoader, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import type { AnthropicThinkingProtocol, BuiltInClientHeaderProfileId, ModelDraft, ModelListFetchOutcome, ReasoningMode, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
|
|
11
11
|
import { fetchModelIds } from "./model-list-fetch.ts";
|
|
12
12
|
import { pickModelIdFromList } from "./model-picker.ts";
|
|
13
|
-
import {
|
|
13
|
+
import { showOptionPicker, showPersistentFormMenu, padLabel, type MenuCursor } from "./persistent-menu.ts";
|
|
14
14
|
import {
|
|
15
15
|
describeVisionInput,
|
|
16
16
|
formatApiShort,
|
|
@@ -22,6 +22,8 @@ interface FieldRow {
|
|
|
22
22
|
id: string;
|
|
23
23
|
label: string;
|
|
24
24
|
value: string;
|
|
25
|
+
// 开关类字段可用 ←→ 就地切换;其余字段需要 Enter 进入输入或选择器。
|
|
26
|
+
adjustable?: boolean;
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
|
|
@@ -50,32 +52,23 @@ function getIntegerFieldLabel(field: "contextWindow" | "maxTokens"): string {
|
|
|
50
52
|
return field === "contextWindow" ? "上下文窗口" : "最大输出";
|
|
51
53
|
}
|
|
52
54
|
|
|
53
|
-
function cycleSwitchState(current: boolean, direction: HorizontalDirection): boolean {
|
|
54
|
-
const states = [false, true];
|
|
55
|
-
const currentIndex = current ? 1 : 0;
|
|
56
|
-
const delta = direction === "right" ? 1 : -1;
|
|
57
|
-
return states[(currentIndex + delta + states.length) % states.length]!;
|
|
58
|
-
}
|
|
59
55
|
|
|
60
|
-
|
|
56
|
+
// 开关字段在两个方向上都是取反,因此不看 direction;返回是否真的切换了字段。
|
|
57
|
+
function applyHorizontalToggle(draft: ModelDraft, fieldId: string): boolean {
|
|
61
58
|
if (fieldId === "visionInput") {
|
|
62
|
-
|
|
63
|
-
draft.inputKinds = enabled ? ["text", "image"] : ["text"];
|
|
59
|
+
draft.inputKinds = supportsVisionInput(draft.inputKinds) ? ["text"] : ["text", "image"];
|
|
64
60
|
return true;
|
|
65
61
|
}
|
|
66
62
|
if (fieldId === "reasoning") {
|
|
67
|
-
|
|
68
|
-
draft.reasoningMode = enabled ? "enabled" : "disabled";
|
|
63
|
+
draft.reasoningMode = draft.reasoningMode === "enabled" ? "disabled" : "enabled";
|
|
69
64
|
return true;
|
|
70
65
|
}
|
|
71
66
|
if (fieldId === "anthropicThinkingProtocol") {
|
|
72
|
-
|
|
73
|
-
draft.anthropicThinkingProtocol = enabled ? "adaptive" : "legacy";
|
|
67
|
+
draft.anthropicThinkingProtocol = draft.anthropicThinkingProtocol === "adaptive" ? "legacy" : "adaptive";
|
|
74
68
|
return true;
|
|
75
69
|
}
|
|
76
70
|
if (fieldId === "openAIServiceTier") {
|
|
77
|
-
|
|
78
|
-
draft.openAIServiceTier = enabled ? "priority" : undefined;
|
|
71
|
+
draft.openAIServiceTier = draft.openAIServiceTier === "priority" ? undefined : "priority";
|
|
79
72
|
return true;
|
|
80
73
|
}
|
|
81
74
|
return false;
|
|
@@ -86,18 +79,19 @@ function buildRows(draft: ModelDraft): FieldRow[] {
|
|
|
86
79
|
{ id: "modelId", label: "模型 ID", value: draft.modelId || "<未填写>" },
|
|
87
80
|
{ id: "fetch", label: "重新拉取", value: "上游模型列表" },
|
|
88
81
|
{ id: "modelName", label: "显示名称", value: draft.modelName || "默认 = 模型 ID" },
|
|
89
|
-
{ id: "visionInput", label: "
|
|
90
|
-
{ id: "reasoning", label: "Thinking", value: describeReasoningMode(draft.reasoningMode) },
|
|
82
|
+
{ id: "visionInput", label: "视觉支持", value: describeVisionInput(draft.inputKinds), adjustable: true },
|
|
83
|
+
{ id: "reasoning", label: "Thinking", value: describeReasoningMode(draft.reasoningMode), adjustable: true },
|
|
91
84
|
];
|
|
92
85
|
if (shouldShowAnthropicThinkingProtocol(draft)) {
|
|
93
86
|
rows.push({
|
|
94
87
|
id: "anthropicThinkingProtocol",
|
|
95
88
|
label: "Adaptive",
|
|
96
89
|
value: describeAnthropicThinkingProtocol(draft.anthropicThinkingProtocol!),
|
|
90
|
+
adjustable: true,
|
|
97
91
|
});
|
|
98
92
|
}
|
|
99
93
|
if (shouldShowOpenAIServiceTier(draft)) {
|
|
100
|
-
rows.push({ id: "openAIServiceTier", label: "Fast mode", value: describeOpenAIServiceTier(draft) });
|
|
94
|
+
rows.push({ id: "openAIServiceTier", label: "Fast mode", value: describeOpenAIServiceTier(draft), adjustable: true });
|
|
101
95
|
}
|
|
102
96
|
rows.push(
|
|
103
97
|
{ id: "contextWindow", label: "上下文窗口", value: String(draft.contextWindow) },
|
|
@@ -106,13 +100,6 @@ function buildRows(draft: ModelDraft): FieldRow[] {
|
|
|
106
100
|
return rows;
|
|
107
101
|
}
|
|
108
102
|
|
|
109
|
-
function getAdjustableRowIds(draft: ModelDraft): string[] {
|
|
110
|
-
const ids = ["visionInput", "reasoning"];
|
|
111
|
-
if (shouldShowAnthropicThinkingProtocol(draft)) ids.push("anthropicThinkingProtocol");
|
|
112
|
-
if (shouldShowOpenAIServiceTier(draft)) ids.push("openAIServiceTier");
|
|
113
|
-
return ids;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
103
|
function getSelectedCustomHeaders(
|
|
117
104
|
draft: ModelDraft,
|
|
118
105
|
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
|
|
@@ -127,8 +114,7 @@ async function pickModelFromUpstream(
|
|
|
127
114
|
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
|
|
128
115
|
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
|
|
129
116
|
): Promise<void> {
|
|
130
|
-
|
|
131
|
-
const outcome = await fetchModelIds({
|
|
117
|
+
const params = {
|
|
132
118
|
providerId: draft.providerId,
|
|
133
119
|
api: draft.api,
|
|
134
120
|
baseUrl: draft.baseUrl,
|
|
@@ -139,7 +125,22 @@ async function pickModelFromUpstream(
|
|
|
139
125
|
httpProxyEnabled: draft.httpProxyEnabled,
|
|
140
126
|
httpProxyUrl: draft.httpProxyUrl,
|
|
141
127
|
clientHeaderCaptures,
|
|
128
|
+
};
|
|
129
|
+
const outcome = await ctx.ui.custom<ModelListFetchOutcome>((tui, theme, _keybindings, done) => {
|
|
130
|
+
const loader = new BorderedLoader(tui, theme, "正在拉取模型列表,总计最多 10 秒…", { cancellable: true });
|
|
131
|
+
let settled = false;
|
|
132
|
+
const finish = (result: ModelListFetchOutcome) => {
|
|
133
|
+
if (settled) return;
|
|
134
|
+
settled = true;
|
|
135
|
+
done(result);
|
|
136
|
+
};
|
|
137
|
+
loader.onAbort = () => finish({ status: "cancelled" });
|
|
138
|
+
fetchModelIds(params, loader.signal)
|
|
139
|
+
.then(finish)
|
|
140
|
+
.catch((error) => finish({ status: "failed", message: error instanceof Error ? error.message : String(error) }));
|
|
141
|
+
return loader;
|
|
142
142
|
});
|
|
143
|
+
if (outcome.status === "cancelled") return;
|
|
143
144
|
if (outcome.status === "failed") {
|
|
144
145
|
ctx.ui.notify(`拉取失败:${outcome.message}`, "warning");
|
|
145
146
|
const fallback = await ctx.ui.input(`手动输入模型 ID(当前:${draft.modelId || "<空>"})`, draft.modelId);
|
|
@@ -205,85 +206,51 @@ async function editField(
|
|
|
205
206
|
return;
|
|
206
207
|
}
|
|
207
208
|
if (fieldId === "visionInput") {
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
VISION_INPUT_CHOICES.map((choice) => ({
|
|
215
|
-
id: choice.enabled ? "enabled" : "disabled",
|
|
216
|
-
label: choice.enabled === current ? `${choice.label} ← 当前` : choice.label,
|
|
217
|
-
})),
|
|
218
|
-
cursor,
|
|
219
|
-
);
|
|
220
|
-
if (action.type === "cancel") return;
|
|
221
|
-
const choice = VISION_INPUT_CHOICES.find((candidate) => (candidate.enabled ? "enabled" : "disabled") === action.id);
|
|
209
|
+
const choices = VISION_INPUT_CHOICES.map((choice) => ({
|
|
210
|
+
id: choice.enabled ? "enabled" : "disabled",
|
|
211
|
+
label: choice.label,
|
|
212
|
+
kinds: choice.kinds,
|
|
213
|
+
}));
|
|
214
|
+
const choice = await showOptionPicker(ctx, "视觉支持", choices, supportsVisionInput(draft.inputKinds) ? "enabled" : "disabled");
|
|
222
215
|
if (choice) draft.inputKinds = [...choice.kinds];
|
|
223
216
|
return;
|
|
224
217
|
}
|
|
225
218
|
if (fieldId === "reasoning") {
|
|
226
|
-
const
|
|
227
|
-
{ mode: "disabled", label: "关闭 — 不发送模型推理参数" },
|
|
228
|
-
{ mode: "enabled", label: "开启 — 启用模型推理参数" },
|
|
229
|
-
];
|
|
230
|
-
const cursor: MenuCursor = { index: choices.findIndex((choice) => choice.mode === draft.reasoningMode) };
|
|
231
|
-
const action = await showPersistentMenu(
|
|
219
|
+
const choice = await showOptionPicker(
|
|
232
220
|
ctx,
|
|
233
221
|
"Thinking",
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
id:
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
cursor,
|
|
222
|
+
[
|
|
223
|
+
{ id: "disabled" as ReasoningMode, label: "关闭 — 不发送模型推理参数" },
|
|
224
|
+
{ id: "enabled" as ReasoningMode, label: "开启 — 启用模型推理参数" },
|
|
225
|
+
],
|
|
226
|
+
draft.reasoningMode,
|
|
240
227
|
);
|
|
241
|
-
if (
|
|
242
|
-
const choice = choices.find((candidate) => candidate.mode === action.id);
|
|
243
|
-
if (choice) draft.reasoningMode = choice.mode;
|
|
228
|
+
if (choice) draft.reasoningMode = choice.id;
|
|
244
229
|
return;
|
|
245
230
|
}
|
|
246
231
|
if (fieldId === "anthropicThinkingProtocol") {
|
|
247
|
-
const
|
|
248
|
-
{ protocol: "adaptive", label: "开启:新版模型,发送 thinking.type=adaptive 和 output_config.effort" },
|
|
249
|
-
{ protocol: "legacy", label: "关闭:旧版接口,发送 thinking.type=enabled 和 budget_tokens" },
|
|
250
|
-
];
|
|
251
|
-
const current = draft.anthropicThinkingProtocol ?? "legacy";
|
|
252
|
-
const cursor: MenuCursor = { index: choices.findIndex((choice) => choice.protocol === current) };
|
|
253
|
-
const action = await showPersistentMenu(
|
|
232
|
+
const choice = await showOptionPicker(
|
|
254
233
|
ctx,
|
|
255
234
|
"Adaptive",
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
id:
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
cursor,
|
|
235
|
+
[
|
|
236
|
+
{ id: "adaptive" as AnthropicThinkingProtocol, label: "开启:新版模型,发送 thinking.type=adaptive 和 output_config.effort" },
|
|
237
|
+
{ id: "legacy" as AnthropicThinkingProtocol, label: "关闭:旧版接口,发送 thinking.type=enabled 和 budget_tokens" },
|
|
238
|
+
],
|
|
239
|
+
draft.anthropicThinkingProtocol ?? "legacy",
|
|
262
240
|
);
|
|
263
|
-
if (
|
|
264
|
-
const choice = choices.find((candidate) => candidate.protocol === action.id);
|
|
265
|
-
if (choice) draft.anthropicThinkingProtocol = choice.protocol;
|
|
241
|
+
if (choice) draft.anthropicThinkingProtocol = choice.id;
|
|
266
242
|
return;
|
|
267
243
|
}
|
|
268
244
|
if (fieldId === "openAIServiceTier") {
|
|
269
|
-
const
|
|
270
|
-
{ id: "disabled", tier: undefined, label: "关闭 — 不发送 service_tier(默认)" },
|
|
271
|
-
{ id: "priority", tier: "priority", label: "开启 — service_tier=priority,可能消耗 Fast / priority 额度" },
|
|
272
|
-
];
|
|
273
|
-
const current = draft.openAIServiceTier === "priority" ? "priority" : "disabled";
|
|
274
|
-
const cursor: MenuCursor = { index: choices.findIndex((choice) => choice.id === current) };
|
|
275
|
-
const action = await showPersistentMenu(
|
|
245
|
+
const choice = await showOptionPicker(
|
|
276
246
|
ctx,
|
|
277
247
|
"Fast mode",
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
id:
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
cursor,
|
|
248
|
+
[
|
|
249
|
+
{ id: "disabled", tier: undefined, label: "关闭 — 不发送 service_tier(默认)" },
|
|
250
|
+
{ id: "priority", tier: "priority", label: "开启 — service_tier=priority,可能消耗 Fast / priority 额度" },
|
|
251
|
+
] as const satisfies readonly { id: string; tier: ModelDraft["openAIServiceTier"]; label: string }[],
|
|
252
|
+
draft.openAIServiceTier === "priority" ? "priority" : "disabled",
|
|
284
253
|
);
|
|
285
|
-
if (action.type === "cancel") return;
|
|
286
|
-
const choice = choices.find((candidate) => candidate.id === action.id);
|
|
287
254
|
if (choice) draft.openAIServiceTier = choice.tier;
|
|
288
255
|
return;
|
|
289
256
|
}
|
|
@@ -308,11 +275,14 @@ export async function editModel(
|
|
|
308
275
|
}
|
|
309
276
|
const cursor: MenuCursor = { index: 0 };
|
|
310
277
|
while (true) {
|
|
311
|
-
|
|
312
|
-
const
|
|
278
|
+
// [喵喵喵]: 字段行的排版在开关切换后要原样重建,抽成函数避免两处写法飘移。
|
|
279
|
+
const toMenuRows = (fieldRows: FieldRow[]) => fieldRows.map((row) => ({
|
|
313
280
|
id: row.id,
|
|
314
281
|
label: `${padLabel(row.label, 16)}${row.value}`,
|
|
282
|
+
adjustable: row.adjustable,
|
|
315
283
|
}));
|
|
284
|
+
const rows = buildRows(draft);
|
|
285
|
+
const menuRows = toMenuRows(rows);
|
|
316
286
|
const action = await showPersistentFormMenu(
|
|
317
287
|
ctx,
|
|
318
288
|
titlePrefix,
|
|
@@ -320,20 +290,25 @@ export async function editModel(
|
|
|
320
290
|
menuRows,
|
|
321
291
|
cursor,
|
|
322
292
|
{
|
|
323
|
-
adjustableRowIds: getAdjustableRowIds(draft),
|
|
324
293
|
summaryLines: [
|
|
325
294
|
`接入 ${draft.providerId} · API ${formatApiShort(draft.api)}`,
|
|
326
295
|
"Ctrl+S 保存并启用模型;不切换当前会话模型",
|
|
327
296
|
],
|
|
328
|
-
|
|
297
|
+
onAdjust: (id) => {
|
|
298
|
+
if (!applyHorizontalToggle(draft, id)) return undefined;
|
|
299
|
+
return toMenuRows(buildRows(draft));
|
|
300
|
+
},
|
|
301
|
+
hints: [
|
|
302
|
+
{ key: "↑↓", label: "选择" },
|
|
303
|
+
{ key: "←→", label: "切换选项" },
|
|
304
|
+
{ key: "Enter", label: "编辑" },
|
|
305
|
+
{ key: "Ctrl+S", label: "保存并启用" },
|
|
306
|
+
{ key: "Esc", label: "返回" },
|
|
307
|
+
],
|
|
329
308
|
},
|
|
330
309
|
);
|
|
331
310
|
if (action.type === "cancel") return { action: "cancel" };
|
|
332
311
|
if (action.type === "save") return { action: "save", draft };
|
|
333
|
-
if (action.type === "adjust") {
|
|
334
|
-
applyHorizontalToggle(draft, action.id, action.direction);
|
|
335
|
-
continue;
|
|
336
|
-
}
|
|
337
312
|
await editField(ctx, draft, action.id, requestHeaderProfiles, clientHeaderCaptures);
|
|
338
313
|
}
|
|
339
314
|
}
|