pi-model-manager 0.4.9 → 0.4.10

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.
@@ -1,391 +0,0 @@
1
- // tui/editor-model.ts
2
- //
3
- // 模型编辑器:与 editor-provider 同款问答式表单。
4
- // 关键差异:
5
- // - 请求头已经收敛到接入级;模型编辑器只编辑模型自身能力
6
- // - 提供"从上游拉取模型 ID 列表"入口(OpenAI/Anthropic/Google)
7
- // - 视觉支持用开关式 select,保存时仍映射为 text / text,image
8
-
9
- import { BorderedLoader, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
10
- import { t } from "../i18n.ts";
11
- import { resolveProviderCustomHeaders } from "../presets/client-headers.ts";
12
- import type { AnthropicThinkingProtocol, BuiltInClientHeaderProfileId, ModelDraft, ModelListFetchOutcome, ReasoningMode, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
13
- import { fetchModelIds } from "./model-list-fetch.ts";
14
- import { pickModelIdFromList } from "./model-picker.ts";
15
- import { showOptionPicker, showPersistentFormMenu, padLabel, markAdjustableValue, type MenuCursor, type HorizontalDirection } from "./persistent-menu.ts";
16
- import {
17
- describeVisionInput,
18
- formatApiShort,
19
- formatOpenAIServiceTier,
20
- getVisionInputChoices,
21
- supportsVisionInput,
22
- } from "./ui-helpers.ts";
23
-
24
- interface FieldRow {
25
- id: string;
26
- label: string;
27
- value: string;
28
- // 开关类字段可用 ←→ 就地切换;其余字段需要 Enter 进入输入或选择器。
29
- adjustable?: boolean;
30
- }
31
-
32
-
33
- function shouldShowOpenAIServiceTier(draft: ModelDraft): boolean {
34
- return draft.providerManaged && draft.api === "openai-responses";
35
- }
36
-
37
- function shouldShowAnthropicThinkingProtocol(draft: ModelDraft): boolean {
38
- return draft.reasoningMode === "enabled" && draft.anthropicThinkingProtocol !== undefined;
39
- }
40
-
41
-
42
- function describeReasoningMode(mode: ReasoningMode): string {
43
- return mode === "enabled" ? t("开启") : t("关闭");
44
- }
45
-
46
- function describeAnthropicThinkingProtocol(protocol: AnthropicThinkingProtocol): string {
47
- return protocol === "adaptive" ? t("开启 · 新版协议") : t("关闭 · Legacy");
48
- }
49
-
50
- function getIntegerFieldLabel(field: "contextWindow" | "maxTokens"): string {
51
- return field === "contextWindow" ? t("上下文窗口") : t("最大输出");
52
- }
53
-
54
-
55
- // [喵喵喵]: 上下文窗口常用十进制档位 (128k ~ 500k)
56
- export const CONTEXT_WINDOW_PRESETS: readonly number[] = [
57
- 128_000,
58
- 200_000,
59
- 256_000,
60
- 272_000,
61
- 300_000,
62
- 400_000,
63
- 500_000,
64
- ];
65
-
66
- // [喵喵喵]: 输出上限与上下文统一十进制档位 (16k ~ 128k);宁小勿大——写小仅封顶略低,写超真实上限会被 API 直接拒绝
67
- export const MAX_TOKENS_PRESETS: readonly number[] = [
68
- 16_000,
69
- 32_000,
70
- 64_000,
71
- 128_000,
72
- ];
73
-
74
- export function cycleNumericPreset(
75
- current: number,
76
- presets: readonly number[],
77
- direction: HorizontalDirection,
78
- ): number {
79
- if (presets.length === 0) return current;
80
- if (direction === "left") {
81
- for (let i = presets.length - 1; i >= 0; i--) {
82
- if (presets[i] < current) return presets[i];
83
- }
84
- return presets[0];
85
- }
86
- for (let i = 0; i < presets.length; i++) {
87
- if (presets[i] > current) return presets[i];
88
- }
89
- return presets[presets.length - 1];
90
- }
91
-
92
- export function parsePositiveIntegerWithUnit(rawInput: string): number | undefined {
93
- const trimmed = rawInput.trim();
94
- if (!trimmed) return undefined;
95
-
96
- const match = /^([0-9]+(?:\.[0-9]+)?)\s*([kmKM])?$/i.exec(trimmed);
97
- if (!match) return undefined;
98
-
99
- const num = Number.parseFloat(match[1]);
100
- if (!Number.isFinite(num) || num <= 0) return undefined;
101
-
102
- const unit = match[2]?.toLowerCase();
103
- if (unit === "m") return Math.round(num * 1_000_000);
104
- if (unit === "k") return Math.round(num * 1_000);
105
-
106
- // 纯数字无单位时,若数值小于 1000(如输入 64、128、200),按习惯视作千倍处理
107
- if (num < 1000) return Math.round(num * 1_000);
108
-
109
- return Math.round(num);
110
- }
111
-
112
- // 开关字段在两个方向上取反;档位字段按 direction 在选项间步进。
113
- function applyHorizontalToggle(draft: ModelDraft, fieldId: string, direction: HorizontalDirection): boolean {
114
- if (fieldId === "visionInput") {
115
- draft.inputKinds = supportsVisionInput(draft.inputKinds) ? ["text"] : ["text", "image"];
116
- return true;
117
- }
118
- if (fieldId === "reasoning") {
119
- draft.reasoningMode = draft.reasoningMode === "enabled" ? "disabled" : "enabled";
120
- return true;
121
- }
122
- if (fieldId === "anthropicThinkingProtocol") {
123
- draft.anthropicThinkingProtocol = draft.anthropicThinkingProtocol === "adaptive" ? "legacy" : "adaptive";
124
- return true;
125
- }
126
- if (fieldId === "openAIServiceTier") {
127
- const tiers: readonly ModelDraft["openAIServiceTier"][] = [undefined, "priority", "ultrafast"];
128
- const currentIndex = tiers.indexOf(draft.openAIServiceTier);
129
- const step = direction === "left" ? -1 : 1;
130
- draft.openAIServiceTier = tiers[(currentIndex + step + tiers.length) % tiers.length];
131
- return true;
132
- }
133
- if (fieldId === "contextWindow") {
134
- draft.contextWindow = cycleNumericPreset(draft.contextWindow, CONTEXT_WINDOW_PRESETS, direction);
135
- return true;
136
- }
137
- if (fieldId === "maxTokens") {
138
- draft.maxTokens = cycleNumericPreset(draft.maxTokens, MAX_TOKENS_PRESETS, direction);
139
- return true;
140
- }
141
- return false;
142
- }
143
-
144
- function buildRows(draft: ModelDraft): FieldRow[] {
145
- const rows: FieldRow[] = [
146
- { id: "modelId", label: t("模型 ID"), value: draft.modelId || t("<未填写>") },
147
- { id: "fetch", label: t("重新拉取"), value: t("上游模型列表") },
148
- { id: "modelName", label: t("显示名称"), value: draft.modelName || t("默认 = 模型 ID") },
149
- { id: "visionInput", label: t("视觉支持"), value: describeVisionInput(draft.inputKinds), adjustable: true },
150
- { id: "reasoning", label: "Thinking", value: describeReasoningMode(draft.reasoningMode), adjustable: true },
151
- ];
152
- if (shouldShowAnthropicThinkingProtocol(draft)) {
153
- rows.push({
154
- id: "anthropicThinkingProtocol",
155
- label: "Adaptive",
156
- value: describeAnthropicThinkingProtocol(draft.anthropicThinkingProtocol!),
157
- adjustable: true,
158
- });
159
- }
160
- if (shouldShowOpenAIServiceTier(draft)) {
161
- rows.push({ id: "openAIServiceTier", label: "Fast mode", value: formatOpenAIServiceTier(draft.openAIServiceTier), adjustable: true });
162
- }
163
- rows.push(
164
- { id: "contextWindow", label: t("上下文窗口"), value: String(draft.contextWindow), adjustable: true },
165
- { id: "maxTokens", label: t("最大输出"), value: String(draft.maxTokens), adjustable: true },
166
- );
167
- return rows;
168
- }
169
-
170
- function getSelectedCustomHeaders(
171
- draft: ModelDraft,
172
- requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
173
- ): Record<string, string> {
174
- return draft.clientHeaderProfile === "custom" ? resolveProviderCustomHeaders(draft, requestHeaderProfiles) : {};
175
- }
176
-
177
- async function pickModelFromUpstream(
178
- ctx: ExtensionCommandContext,
179
- draft: ModelDraft,
180
- requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
181
- clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
182
- ): Promise<void> {
183
- const params = {
184
- providerId: draft.providerId,
185
- providerManaged: draft.providerManaged,
186
- providerHeaders: draft.providerHeaders,
187
- modelHeaders: draft.modelHeaders,
188
- compat: {
189
- ...draft.compat,
190
- ...(draft.api === "anthropic-messages" ? { forceAdaptiveThinking: draft.anthropicThinkingProtocol === "adaptive" } : {}),
191
- },
192
- api: draft.api,
193
- baseUrl: draft.baseUrl,
194
- apiKey: draft.apiKey,
195
- authHeader: draft.authHeader,
196
- clientHeaderProfile: draft.clientHeaderProfile,
197
- customClientHeaders: getSelectedCustomHeaders(draft, requestHeaderProfiles),
198
- httpProxyEnabled: draft.httpProxyEnabled,
199
- httpProxyUrl: draft.httpProxyUrl,
200
- clientHeaderCaptures,
201
- };
202
- const outcome = await ctx.ui.custom<ModelListFetchOutcome>((tui, theme, _keybindings, done) => {
203
- const loader = new BorderedLoader(tui, theme, t("正在拉取模型列表,总计最多 10 秒…"), { cancellable: true });
204
- let settled = false;
205
- const finish = (result: ModelListFetchOutcome) => {
206
- if (settled) return;
207
- settled = true;
208
- done(result);
209
- };
210
- loader.onAbort = () => finish({ status: "cancelled" });
211
- fetchModelIds(params, loader.signal)
212
- .then(finish)
213
- .catch((error) => finish({ status: "failed", message: error instanceof Error ? error.message : String(error) }));
214
- return loader;
215
- });
216
- if (outcome.status === "cancelled") return;
217
- if (outcome.status === "failed") {
218
- ctx.ui.notify(t("拉取失败:{error}", { error: outcome.message }), "warning");
219
- const fallback = await ctx.ui.input(t("手动输入模型 ID(当前:{current})", { current: draft.modelId || t("<空>") }), draft.modelId);
220
- if (fallback !== undefined) {
221
- draft.modelId = fallback.trim() || draft.modelId;
222
- }
223
- return;
224
- }
225
- if (outcome.modelIds.length === 0) {
226
- ctx.ui.notify(t("上游返回空列表"), "warning");
227
- return;
228
- }
229
- const picked = await pickModelIdFromList(
230
- ctx,
231
- t("选择模型 ID(共 {count} 个)", { count: outcome.modelIds.length }),
232
- outcome.modelIds,
233
- draft.modelId,
234
- );
235
- if (picked) {
236
- draft.modelId = picked;
237
- }
238
- }
239
-
240
- async function editIntField(ctx: ExtensionCommandContext, draft: ModelDraft, field: "contextWindow" | "maxTokens"): Promise<void> {
241
- const label = getIntegerFieldLabel(field);
242
- const current = String(draft[field]);
243
- const value = await ctx.ui.input(t("{label}(当前:{current},留空保持原值)", { label, current }), current);
244
- if (value === undefined) return;
245
- const trimmed = value.trim();
246
- if (!trimmed) return;
247
- const parsed = parsePositiveIntegerWithUnit(trimmed);
248
- if (parsed === undefined || parsed <= 0) {
249
- ctx.ui.notify(t("{label} 必须是正整数", { label }), "warning");
250
- return;
251
- }
252
- draft[field] = parsed;
253
- }
254
-
255
- async function editField(
256
- ctx: ExtensionCommandContext,
257
- draft: ModelDraft,
258
- fieldId: string,
259
- requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
260
- clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
261
- ): Promise<void> {
262
- if (fieldId === "modelId") {
263
- const value = await ctx.ui.input(t("模型 ID(当前:{current},传给上游 API 的模型字段)", { current: draft.modelId || t("<空>") }), draft.modelId);
264
- if (value !== undefined) {
265
- const trimmed = value.trim();
266
- if (trimmed) {
267
- draft.modelId = trimmed;
268
- }
269
- }
270
- return;
271
- }
272
- if (fieldId === "fetch") {
273
- await pickModelFromUpstream(ctx, draft, requestHeaderProfiles, clientHeaderCaptures);
274
- return;
275
- }
276
- if (fieldId === "modelName") {
277
- const value = await ctx.ui.input(t("显示名称(当前:{current},可空默认用模型 ID;输入空格清空)", { current: draft.modelName || t("<空>") }), draft.modelName);
278
- if (value !== undefined) draft.modelName = value.trim();
279
- return;
280
- }
281
- if (fieldId === "visionInput") {
282
- const choices = getVisionInputChoices().map((choice) => ({
283
- id: choice.enabled ? "enabled" : "disabled",
284
- label: choice.label,
285
- kinds: choice.kinds,
286
- }));
287
- const choice = await showOptionPicker(ctx, t("视觉支持"), choices, supportsVisionInput(draft.inputKinds) ? "enabled" : "disabled");
288
- if (choice) draft.inputKinds = [...choice.kinds];
289
- return;
290
- }
291
- if (fieldId === "reasoning") {
292
- const choice = await showOptionPicker(
293
- ctx,
294
- "Thinking",
295
- [
296
- { id: "disabled" as ReasoningMode, label: t("关闭 — 不发送模型推理参数") },
297
- { id: "enabled" as ReasoningMode, label: t("开启 — 启用模型推理参数") },
298
- ],
299
- draft.reasoningMode,
300
- );
301
- if (choice) draft.reasoningMode = choice.id;
302
- return;
303
- }
304
- if (fieldId === "anthropicThinkingProtocol") {
305
- const choice = await showOptionPicker(
306
- ctx,
307
- "Adaptive",
308
- [
309
- { id: "adaptive" as AnthropicThinkingProtocol, label: t("开启:新版模型,发送 thinking.type=adaptive 和 output_config.effort") },
310
- { id: "legacy" as AnthropicThinkingProtocol, label: t("关闭:旧版接口,发送 thinking.type=enabled 和 budget_tokens") },
311
- ],
312
- draft.anthropicThinkingProtocol ?? "legacy",
313
- );
314
- if (choice) draft.anthropicThinkingProtocol = choice.id;
315
- return;
316
- }
317
- if (fieldId === "openAIServiceTier") {
318
- const choice = await showOptionPicker(
319
- ctx,
320
- "Fast mode",
321
- [
322
- { id: "default", tier: undefined, label: t("标准 — 不发送 service_tier") },
323
- { id: "priority", tier: "priority", label: t("Fast — service_tier=priority,可能产生额外费用") },
324
- { id: "ultrafast", tier: "ultrafast", label: t("Ultrafast — service_tier=ultrafast,需上游支持且可能产生额外费用") },
325
- ] as const satisfies readonly { id: string; tier: ModelDraft["openAIServiceTier"]; label: string }[],
326
- draft.openAIServiceTier ?? "default",
327
- );
328
- if (choice) draft.openAIServiceTier = choice.tier;
329
- return;
330
- }
331
- if (fieldId === "contextWindow" || fieldId === "maxTokens") {
332
- await editIntField(ctx, draft, fieldId);
333
- }
334
- }
335
-
336
- export type ModelEditOutcome =
337
- | { action: "save"; draft: ModelDraft }
338
- | { action: "cancel" };
339
-
340
- export async function editModel(
341
- ctx: ExtensionCommandContext,
342
- draft: ModelDraft,
343
- titlePrefix: string,
344
- requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
345
- clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>> = {},
346
- ): Promise<ModelEditOutcome> {
347
- if (!draft.modelId.trim()) {
348
- await pickModelFromUpstream(ctx, draft, requestHeaderProfiles, clientHeaderCaptures);
349
- }
350
- const cursor: MenuCursor = { index: 0 };
351
- while (true) {
352
- // [喵喵喵]: 字段行的排版在开关切换后要原样重建,抽成函数避免两处写法飘移。
353
- const toMenuRows = (fieldRows: FieldRow[]) => fieldRows.map((row) => ({
354
- id: row.id,
355
- label: `${padLabel(row.label, 16)}${row.adjustable ? markAdjustableValue(row.value) : row.value}`,
356
- adjustable: row.adjustable,
357
- }));
358
- const rows = buildRows(draft);
359
- const menuRows = toMenuRows(rows);
360
- const action = await showPersistentFormMenu(
361
- ctx,
362
- titlePrefix,
363
- "",
364
- menuRows,
365
- cursor,
366
- {
367
- summaryLines: [
368
- t("接入 {providerId} · API {api}", { providerId: draft.providerId, api: formatApiShort(draft.api) }),
369
- t("Ctrl+S 保存并启用模型;不切换当前会话模型"),
370
- ...(!draft.providerManaged && draft.api === "openai-responses"
371
- ? [t("Fast mode 需要先接管该接入;请先保存接入配置。")]
372
- : []),
373
- ],
374
- onAdjust: (id, direction) => {
375
- if (!applyHorizontalToggle(draft, id, direction)) return undefined;
376
- return toMenuRows(buildRows(draft));
377
- },
378
- hints: [
379
- { key: "↑↓", label: t("选择") },
380
- { key: "←→", label: t("切换选项") },
381
- { key: "Enter", label: t("编辑") },
382
- { key: "Ctrl+S", label: t("保存并启用") },
383
- { key: "Esc", label: t("返回") },
384
- ],
385
- },
386
- );
387
- if (action.type === "cancel") return { action: "cancel" };
388
- if (action.type === "save") return { action: "save", draft };
389
- await editField(ctx, draft, action.id, requestHeaderProfiles, clientHeaderCaptures);
390
- }
391
- }