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/tui/ui-helpers.ts CHANGED
@@ -11,6 +11,7 @@
11
11
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
12
12
  import { getApiKeyEnvVarName, getAuthStatusText, getProviderDisplayName } from "../state-document.ts";
13
13
  import { CLIENT_HEADER_PROFILE_LABELS, getClientHeaderProfileDisplay, resolveClientHeaderProfile } from "../presets/client-headers.ts";
14
+ import { redactUrlForDisplay } from "../sensitive-redaction.ts";
14
15
  import type {
15
16
  ApiKind,
16
17
  ClientHeaderProfileId,
@@ -19,22 +20,13 @@ import type {
19
20
  StoredProvider,
20
21
  StoredRequestHeaderProfile,
21
22
  } from "../types.ts";
23
+ import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
22
24
 
23
25
  export function maskSecret(value: string | undefined): string {
24
26
  if (!value) return "<未填写>";
25
27
  if (getApiKeyEnvVarName(value) || value.startsWith("!")) return value;
26
28
  return "********";
27
29
  }
28
-
29
- function authIcon(apiKey: string | undefined): string {
30
- const status = getAuthStatusText(apiKey);
31
- if (status === "no apiKey") return "?";
32
- if (status === "command apiKey") return "$";
33
- if (status.startsWith("env missing:")) return "⚠";
34
- if (status.startsWith("env ")) return "✓";
35
- return "•";
36
- }
37
-
38
30
  function formatContextWindow(contextWindow: number): string {
39
31
  if (contextWindow >= 1_000_000) return `${(contextWindow / 1_000_000).toFixed(contextWindow % 1_000_000 === 0 ? 0 : 1)}M`;
40
32
  if (contextWindow >= 1_000) return `${Math.round(contextWindow / 1_000)}K`;
@@ -48,6 +40,7 @@ interface FixedColumn {
48
40
  text: string;
49
41
  width: number;
50
42
  align?: ColumnAlign;
43
+ color?: ThemeColor;
51
44
  }
52
45
 
53
46
  export function fitColumn(text: string, columns: number, align: ColumnAlign = "left"): string {
@@ -56,18 +49,21 @@ export function fitColumn(text: string, columns: number, align: ColumnAlign = "l
56
49
  return align === "right" ? pad + clipped : clipped + pad;
57
50
  }
58
51
 
59
- export function joinFixedColumns(columns: readonly FixedColumn[], gap = " "): string {
60
- return columns.map((column) => fitColumn(column.text, column.width, column.align)).join(gap).trimEnd();
52
+ // [喵喵喵]: 先按纯文本对齐再着色;反过来会让列宽计算受 ANSI 序列干扰。
53
+ function joinFixedColumns(columns: readonly FixedColumn[], theme?: Theme, gap = " "): string {
54
+ return columns
55
+ .map((column) => {
56
+ const cell = fitColumn(column.text, column.width, column.align);
57
+ return theme && column.color ? theme.fg(column.color, cell) : cell;
58
+ })
59
+ .join(gap)
60
+ .trimEnd();
61
61
  }
62
62
 
63
- export function formatTableHeader(line: string): string {
63
+ function formatTableHeader(line: string): string {
64
64
  return ` ${line}`;
65
65
  }
66
66
 
67
- function sanitizeEndpoint(value: string): string {
68
- return value.replace(/([?&](?:key|api_key|api-key)=)[^&]+/gi, "$1REDACTED");
69
- }
70
-
71
67
  export function formatApiShort(api: ApiKind): string {
72
68
  if (api === "openai-responses") return "Responses";
73
69
  if (api === "openai-completions") return "Chat";
@@ -94,7 +90,7 @@ function getProviderProxyText(provider: StoredProvider): string {
94
90
  return provider.httpProxyEnabled ? "proxy" : "direct";
95
91
  }
96
92
 
97
- export function formatProviderHeaderProfile(
93
+ function formatProviderHeaderProfile(
98
94
  provider: StoredProvider,
99
95
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
100
96
  ): string {
@@ -114,70 +110,109 @@ export function formatProviderHeaderProfile(
114
110
  return CLIENT_HEADER_PROFILE_LABELS[provider.clientHeaderProfile];
115
111
  }
116
112
 
117
- export const PROVIDER_CONSOLE_HEADER = formatTableHeader(joinFixedColumns([
118
- { text: "接入", width: 22 },
119
- { text: "API", width: 9 },
120
- { text: "模型", width: 6, align: "right" },
121
- { text: "请求头", width: 15 },
122
- { text: "代理", width: 6 },
123
- { text: "认证", width: 6 },
124
- { text: "状态", width: 5 },
125
- ]));
126
-
127
- function getModelListColumns(provider: StoredProvider): FixedColumn[] {
128
- const columns: FixedColumn[] = [
129
- { text: "模型 ID", width: 30 },
130
- { text: "显示名", width: 16 },
131
- { text: "输入", width: 10 },
132
- { text: "Thinking", width: 8 },
133
- { text: "上下文", width: 7, align: "right" },
134
- { text: "输出", width: 7, align: "right" },
135
- ];
136
- if (provider.api === "openai-responses") columns.push({ text: "Fast", width: 8 });
137
- return columns;
113
+ interface ProviderConsoleCells {
114
+ provider: string;
115
+ api: string;
116
+ models: string;
117
+ headers: string;
118
+ proxy: string;
119
+ auth: string;
120
+ status: string;
138
121
  }
139
122
 
140
- export function formatModelListHeader(provider: StoredProvider): string {
141
- return formatTableHeader(joinFixedColumns(getModelListColumns(provider)));
123
+ export interface ProviderTableOptions {
124
+ requestHeaderProfiles?: Record<string, StoredRequestHeaderProfile>;
125
+ theme?: Theme;
126
+ // 按当前数据收敛后的接入列宽;表头与数据行必须传同一个值才能对齐。
127
+ nameWidth?: number;
128
+ }
129
+
130
+ const PROVIDER_NAME_COLUMN_LIMIT = 22;
131
+ const PROVIDER_NAME_COLUMN_MIN = 12;
132
+
133
+ export function getProviderDisplayLabel(providerId: string, provider: StoredProvider): string {
134
+ const name = getProviderDisplayName(providerId, provider);
135
+ return name === providerId ? providerId : `${name} (${providerId})`;
136
+ }
137
+
138
+ export function getProviderNameColumnWidth(displayLabels: readonly string[]): number {
139
+ const longest = displayLabels.reduce((max, label) => Math.max(max, visibleWidth(label)), 0);
140
+ return Math.min(PROVIDER_NAME_COLUMN_LIMIT, Math.max(PROVIDER_NAME_COLUMN_MIN, longest));
141
+ }
142
+
143
+ function getAuthColor(auth: string): ThemeColor | undefined {
144
+ return auth === "miss" || auth === "auth?" ? "warning" : undefined;
145
+ }
146
+
147
+ function getProviderConsoleColumns(cells: ProviderConsoleCells, availableWidth: number, nameWidth: number): FixedColumn[] {
148
+ const provider: FixedColumn = { text: cells.provider, width: Math.min(nameWidth, PROVIDER_NAME_COLUMN_LIMIT) };
149
+ const api: FixedColumn = { text: cells.api, width: 9 };
150
+ const models: FixedColumn = { text: cells.models, width: 6, align: "right" };
151
+ const headers: FixedColumn = { text: cells.headers, width: 15, color: cells.headers === "Off" ? "dim" : undefined };
152
+ const proxy: FixedColumn = { text: cells.proxy, width: 6, color: cells.proxy === "proxy" ? "accent" : "dim" };
153
+ const auth: FixedColumn = { text: cells.auth, width: 6, color: getAuthColor(cells.auth) };
154
+ const status: FixedColumn = { text: cells.status, width: 5, color: cells.status === "ready" ? "success" : "warning" };
155
+ if (availableWidth >= 81) return [provider, api, models, headers, proxy, auth, status];
156
+ if (availableWidth >= 64) return [provider, api, models, proxy, auth, status];
157
+ if (availableWidth >= 48) return [provider, api, models, status];
158
+ return [{ ...provider, width: Math.max(10, availableWidth - 26) }, api, models, status];
159
+ }
160
+
161
+ export function formatProviderConsoleHeader(menuWidth: number, options: ProviderTableOptions = {}): string {
162
+ return formatTableHeader(joinFixedColumns(getProviderConsoleColumns({
163
+ provider: "接入",
164
+ api: "API",
165
+ models: "模型",
166
+ headers: "请求头",
167
+ proxy: "代理",
168
+ auth: "认证",
169
+ status: "状态",
170
+ }, Math.max(0, menuWidth - 2), options.nameWidth ?? PROVIDER_NAME_COLUMN_LIMIT)));
142
171
  }
143
172
 
144
173
  export function formatProviderConsoleRow(
145
174
  providerId: string,
146
175
  provider: StoredProvider,
147
- requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
176
+ availableWidth = 81,
177
+ options: ProviderTableOptions = {},
148
178
  ): string {
149
- const name = getProviderDisplayName(providerId, provider);
150
- const displayName = name === providerId ? providerId : `${name} (${providerId})`;
151
- return joinFixedColumns([
152
- { text: displayName, width: 22 },
153
- { text: formatApiShort(provider.api), width: 9 },
154
- { text: String(provider.models.length), width: 6, align: "right" },
155
- { text: formatProviderHeaderProfile(provider, requestHeaderProfiles), width: 15 },
156
- { text: getProviderProxyText(provider), width: 6 },
157
- { text: getAuthKind(provider.apiKey), width: 6 },
158
- { text: getProviderStatus(provider), width: 5 },
159
- ]);
160
- }
161
- export function formatProviderRow(providerId: string, provider: StoredProvider): string {
162
- const name = getProviderDisplayName(providerId, provider);
163
- const head = name === providerId ? providerId : `${name} (${providerId})`;
164
- return `${head} · ${provider.api} · ${provider.models.length}模型 · ${authIcon(provider.apiKey)}`;
179
+ return joinFixedColumns(getProviderConsoleColumns({
180
+ provider: getProviderDisplayLabel(providerId, provider),
181
+ api: formatApiShort(provider.api),
182
+ models: String(provider.models.length),
183
+ headers: formatProviderHeaderProfile(provider, options.requestHeaderProfiles ?? {}),
184
+ proxy: getProviderProxyText(provider),
185
+ auth: getAuthKind(provider.apiKey),
186
+ status: getProviderStatus(provider),
187
+ }, availableWidth, options.nameWidth ?? PROVIDER_NAME_COLUMN_LIMIT), options.theme);
188
+ }
189
+
190
+ // [喵喵喵]: 详情区分三级(标题/字段名/值),否则整块同一灰度无法扫读;
191
+ // 缩进与标签列宽必须在所有面板一致,否则切面板时详情区会跳动。
192
+ const DETAIL_LABEL_WIDTH = 10;
193
+
194
+ export function formatDetailTitle(title: string, theme?: Theme): string {
195
+ return theme ? theme.fg("text", title) : title;
196
+ }
197
+
198
+ export function formatDetailField(label: string, value: string, theme?: Theme): string {
199
+ const labelCell = ` ${fitColumn(label, DETAIL_LABEL_WIDTH)}`;
200
+ return theme ? `${theme.fg("dim", labelCell)}${theme.fg("text", value)}` : `${labelCell}${value}`;
165
201
  }
166
202
 
167
203
  export function formatProviderDetailLines(
168
204
  providerId: string,
169
205
  provider: StoredProvider,
170
- requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
206
+ options: ProviderTableOptions = {},
171
207
  ): string[] {
172
- const name = getProviderDisplayName(providerId, provider);
173
- const title = name === providerId ? providerId : `${name} (${providerId})`;
208
+ const { theme, requestHeaderProfiles = {} } = options;
174
209
  const modelIds = provider.models.map((model) => model.id).join(", ") || "<无模型>";
175
210
  return [
176
- title,
177
- ` endpoint ${sanitizeEndpoint(provider.baseUrl)}`,
178
- ` proxy ${provider.httpProxyEnabled ? sanitizeEndpoint(provider.httpProxyUrl ?? "http://127.0.0.1:7890") : "direct"}`,
179
- ` api ${formatApiShort(provider.api)} · headers ${formatProviderHeaderProfile(provider, requestHeaderProfiles)} · auth ${getAuthKind(provider.apiKey)}`,
180
- ` models ${modelIds}`,
211
+ formatDetailTitle(getProviderDisplayLabel(providerId, provider), theme),
212
+ formatDetailField("endpoint", redactUrlForDisplay(provider.baseUrl), theme),
213
+ formatDetailField("proxy", provider.httpProxyEnabled ? redactUrlForDisplay(provider.httpProxyUrl ?? "http://127.0.0.1:7890") : "direct", theme),
214
+ formatDetailField("api", `${formatApiShort(provider.api)} · headers ${formatProviderHeaderProfile(provider, requestHeaderProfiles)} · auth ${getAuthKind(provider.apiKey)}`, theme),
215
+ formatDetailField("models", modelIds, theme),
181
216
  ];
182
217
  }
183
218
 
@@ -189,26 +224,8 @@ export function formatProviderSummaryLine(
189
224
  }
190
225
 
191
226
  export function formatProviderEndpointLine(provider: StoredProvider): string {
192
- const proxy = provider.httpProxyEnabled ? ` · proxy ${sanitizeEndpoint(provider.httpProxyUrl ?? "http://127.0.0.1:7890")}` : "";
193
- return `endpoint ${sanitizeEndpoint(provider.baseUrl)}${proxy}`;
194
- }
195
-
196
- function getThinkingFlag(model: StoredModel): string | undefined {
197
- if (!model.reasoning) return undefined;
198
- const map = model.thinkingLevelMap;
199
- if (map?.max === "max" && map.xhigh === "xhigh") return "think:xhigh/max";
200
- if (map?.max === "max") return "think:max";
201
- return "think";
202
- }
203
-
204
- export function formatModelRow(model: StoredModel): string {
205
- const flags: string[] = [];
206
- const thinkingFlag = getThinkingFlag(model);
207
- if (thinkingFlag) flags.push(thinkingFlag);
208
- flags.push(model.input.includes("image") ? "视觉" : "文本");
209
- flags.push(`${formatContextWindow(model.contextWindow)}ctx`);
210
- const suffix = model.name && model.name !== model.id ? ` “${model.name}”` : "";
211
- return `${model.id}${suffix} · ${flags.join(" · ")}`;
227
+ const proxy = provider.httpProxyEnabled ? ` · proxy ${redactUrlForDisplay(provider.httpProxyUrl ?? "http://127.0.0.1:7890")}` : "";
228
+ return `endpoint ${redactUrlForDisplay(provider.baseUrl)}${proxy}`;
212
229
  }
213
230
 
214
231
  function formatModelNameCell(model: StoredModel): string {
@@ -223,30 +240,118 @@ function formatModelThinkingCell(model: StoredModel): string {
223
240
  return model.reasoning ? "开" : "关";
224
241
  }
225
242
 
226
- export function formatModelConsoleRow(model: StoredModel): string {
227
- return joinFixedColumns([
228
- { text: model.id, width: 34 },
229
- { text: formatModelInputCell(model), width: 12 },
230
- { text: formatModelThinkingCell(model), width: 8 },
231
- { text: formatContextWindow(model.contextWindow), width: 7, align: "right" },
232
- { text: formatContextWindow(model.maxTokens), width: 7, align: "right" },
233
- { text: model.openAIServiceTier === "priority" ? "priority" : "-", width: 8 },
234
- ]);
235
- }
236
-
237
- export function formatModelListRow(provider: StoredProvider, model: StoredModel): string {
238
- const columns: FixedColumn[] = [
239
- { text: model.id, width: 30 },
240
- { text: formatModelNameCell(model), width: 16 },
241
- { text: formatModelInputCell(model), width: 10 },
242
- { text: formatModelThinkingCell(model), width: 8 },
243
- { text: formatContextWindow(model.contextWindow), width: 7, align: "right" },
244
- { text: formatContextWindow(model.maxTokens), width: 7, align: "right" },
245
- ];
246
- if (provider.api === "openai-responses") {
247
- columns.push({ text: model.openAIServiceTier === "priority" ? "priority" : "off", width: 8 });
243
+ interface ModelListCells {
244
+ modelId: string;
245
+ name: string;
246
+ input: string;
247
+ thinking: string;
248
+ context: string;
249
+ output: string;
250
+ fast: string;
251
+ }
252
+
253
+ export interface ModelTableOptions {
254
+ theme?: Theme;
255
+ // 按当前数据收敛后的列宽;表头与数据行必须传同一组值才能对齐。
256
+ modelIdWidth?: number;
257
+ nameWidth?: number;
258
+ }
259
+
260
+ const MODEL_ID_COLUMN_LIMIT = 30;
261
+ const MODEL_ID_COLUMN_MIN = 14;
262
+ const MODEL_NAME_COLUMN_LIMIT = 16;
263
+ const MODEL_NAME_COLUMN_MIN = 8;
264
+
265
+ export function getModelColumnWidths(models: readonly StoredModel[]): Required<Pick<ModelTableOptions, "modelIdWidth" | "nameWidth">> {
266
+ let longestId = 0;
267
+ let longestName = 0;
268
+ for (const model of models) {
269
+ longestId = Math.max(longestId, visibleWidth(model.id));
270
+ longestName = Math.max(longestName, visibleWidth(formatModelNameCell(model)));
271
+ }
272
+ return {
273
+ modelIdWidth: Math.min(MODEL_ID_COLUMN_LIMIT, Math.max(MODEL_ID_COLUMN_MIN, longestId)),
274
+ nameWidth: Math.min(MODEL_NAME_COLUMN_LIMIT, Math.max(MODEL_NAME_COLUMN_MIN, longestName)),
275
+ };
276
+ }
277
+
278
+ function getModelListColumns(
279
+ provider: StoredProvider,
280
+ cells: ModelListCells,
281
+ availableWidth: number,
282
+ options: ModelTableOptions,
283
+ ): FixedColumn[] {
284
+ const modelIdWidth = options.modelIdWidth ?? MODEL_ID_COLUMN_LIMIT;
285
+ const nameWidth = options.nameWidth ?? MODEL_NAME_COLUMN_LIMIT;
286
+ const name: FixedColumn = { text: cells.name, width: nameWidth, color: cells.name === "默认" ? "dim" : undefined };
287
+ const input: FixedColumn = { text: cells.input, width: 10, color: cells.input.includes("视觉") ? "accent" : undefined };
288
+ const thinking: FixedColumn = { text: cells.thinking, width: 8, color: cells.thinking === "开" ? "accent" : cells.thinking === "关" ? "dim" : undefined };
289
+ const context: FixedColumn = { text: cells.context, width: 7, align: "right" };
290
+ const output: FixedColumn = { text: cells.output, width: 7, align: "right" };
291
+ // [喵喵喵]: priority 会消耗 Fast 额度,用 warning 提醒而不是当普通开关。
292
+ const fast: FixedColumn = { text: cells.fast, width: 8, color: cells.fast === "priority" ? "warning" : cells.fast === "off" ? "dim" : undefined };
293
+
294
+ const fullWidth = provider.api === "openai-responses" ? 98 : 88;
295
+ if (availableWidth >= fullWidth) {
296
+ const columns: FixedColumn[] = [
297
+ { text: cells.modelId, width: Math.min(modelIdWidth, 30) },
298
+ { ...name, width: Math.min(nameWidth, 16) },
299
+ input,
300
+ thinking,
301
+ context,
302
+ output,
303
+ ];
304
+ if (provider.api === "openai-responses") columns.push(fast);
305
+ return columns;
306
+ }
307
+ if (availableWidth >= 75) {
308
+ return [
309
+ { text: cells.modelId, width: Math.min(modelIdWidth, 28) },
310
+ { ...name, width: Math.min(nameWidth, 14) },
311
+ input,
312
+ thinking,
313
+ context,
314
+ ];
315
+ }
316
+ if (availableWidth >= 57) {
317
+ return [{ text: cells.modelId, width: Math.min(modelIdWidth, 26) }, input, thinking, context];
248
318
  }
249
- return joinFixedColumns(columns);
319
+ return [{ text: cells.modelId, width: Math.max(10, availableWidth - 22) }, input, thinking];
320
+ }
321
+
322
+ function getModelListCells(model?: StoredModel): ModelListCells {
323
+ return model
324
+ ? {
325
+ modelId: model.id,
326
+ name: formatModelNameCell(model),
327
+ input: formatModelInputCell(model),
328
+ thinking: formatModelThinkingCell(model),
329
+ context: formatContextWindow(model.contextWindow),
330
+ output: formatContextWindow(model.maxTokens),
331
+ fast: model.openAIServiceTier === "priority" ? "priority" : "off",
332
+ }
333
+ : {
334
+ modelId: "模型 ID",
335
+ name: "显示名",
336
+ input: "输入",
337
+ thinking: "Thinking",
338
+ context: "上下文",
339
+ output: "输出",
340
+ fast: "Fast",
341
+ };
342
+ }
343
+
344
+ export function formatModelListHeader(provider: StoredProvider, menuWidth = 100, options: ModelTableOptions = {}): string {
345
+ return formatTableHeader(joinFixedColumns(getModelListColumns(provider, getModelListCells(), Math.max(0, menuWidth - 2), options)));
346
+ }
347
+
348
+ export function formatModelListRow(
349
+ provider: StoredProvider,
350
+ model: StoredModel,
351
+ availableWidth = 98,
352
+ options: ModelTableOptions = {},
353
+ ): string {
354
+ return joinFixedColumns(getModelListColumns(provider, getModelListCells(model), availableWidth, options), options.theme);
250
355
  }
251
356
 
252
357
  export const API_CHOICES: { id: ApiKind; label: string }[] = [
@@ -277,13 +382,14 @@ export function describeProfile(
277
382
 
278
383
  export const VISION_INPUT_CHOICES: { enabled: boolean; kinds: ModelInputKind[]; label: string }[] = [
279
384
  { enabled: false, kinds: ["text"], label: "关闭 — 仅文本输入" },
280
- { enabled: true, kinds: ["text", "image"], label: "开启 — 支持视觉(文本 + 图片)" },
385
+ { enabled: true, kinds: ["text", "image"], label: "开启 — 文本 + 图片输入" },
281
386
  ];
282
387
 
283
388
  export function supportsVisionInput(kinds: ModelInputKind[]): boolean {
284
389
  return kinds.includes("image");
285
390
  }
286
391
 
392
+ // 字段名已经说明了含义,值只需要跟 Thinking / Fast mode 一样给出开关状态。
287
393
  export function describeVisionInput(kinds: ModelInputKind[]): string {
288
- return supportsVisionInput(kinds) ? "开启 · 支持视觉" : "关闭 · 仅文本";
394
+ return supportsVisionInput(kinds) ? "开启" : "关闭";
289
395
  }
package/types.ts CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  export type ApiKind = "openai-completions" | "openai-responses" | "anthropic-messages" | "google-generative-ai";
10
10
  export type ModelInputKind = "text" | "image";
11
- export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
11
+ type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
12
12
  export type ThinkingLevelMap = Partial<Record<ThinkingLevel, string | null>>;
13
13
  export type ReasoningMode = "enabled" | "disabled";
14
14
  export type AnthropicThinkingProtocol = "adaptive" | "legacy";
@@ -73,6 +73,8 @@ export interface StoredProvider {
73
73
  name: string;
74
74
  api: ApiKind;
75
75
  baseUrl: string;
76
+ /** 运行时所有权,未接管的原生 Provider 不由插件生成请求头或动态注册。 */
77
+ managed: boolean;
76
78
  /** 可省略;认证也可由 auth.json、/login 或 CLI --api-key 提供。 */
77
79
  apiKey?: string;
78
80
  /** models.json 中不由 TUI 编辑、但必须跨保存和重命名保真的原生字段。 */
@@ -89,8 +91,10 @@ export interface StoredProvider {
89
91
  }
90
92
 
91
93
  export interface StateDocument {
92
- version: 1;
94
+ version: 2;
93
95
  providers: Record<string, StoredProvider>;
96
+ /** state.json 中明确由插件创建或接管的 Provider ID。 */
97
+ managedProviderIds: string[];
94
98
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>;
95
99
  clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>;
96
100
  }
@@ -146,20 +150,9 @@ export interface RequestHeaderProfileDraft {
146
150
 
147
151
  export type ModelListFetchOutcome =
148
152
  | { status: "loaded"; modelIds: string[] }
149
- | { status: "failed"; message: string };
150
-
151
- export type ModelSelectionOutcome =
152
- | { status: "selected"; modelId: string }
153
- | { status: "manual"; fallback: string }
153
+ | { status: "failed"; message: string }
154
154
  | { status: "cancelled" };
155
155
 
156
- export type DashboardAction =
157
- | { type: "new-provider" }
158
- | { type: "provider-menu"; providerId: string }
159
- | { type: "model-menu"; providerId: string; modelId: string }
160
- | { type: "open-models-json" }
161
- | { type: "cancel" };
162
-
163
156
  // ========== 常量 ==========
164
157
 
165
158
  export const ZERO_COST: TokenCost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
@@ -1,90 +0,0 @@
1
- // models-json-mutations.ts
2
- //
3
- // 原生 models.json 面板的事务层:集中处理 models.json 写入、插件 metadata 回写、
4
- // runtime registry 刷新、enabledModels 清理和模型救援。
5
-
6
- import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
- import { formatUnknownError } from "./common.ts";
8
- import { deleteModelInDoc, deleteProviderInDoc, readModelsJsonSnapshot, writeModelsJsonSnapshot } from "./models-json-manager.ts";
9
- import { removeModelFromNextPiStart } from "./models-json-sync.ts";
10
- import { reconcileProvider, unregisterManagedProvider } from "./provider-registrar.ts";
11
- import { withModelRescue } from "./rescue.ts";
12
- import { getModelFullId } from "./state-document.ts";
13
- import { invalidateStateCache } from "./state-cache.ts";
14
- import { readState, writeState } from "./state-store.ts";
15
- import type { StateDocument } from "./types.ts";
16
-
17
- async function refreshMetadataAfterNativeWrite(operation: string): Promise<StateDocument> {
18
- try {
19
- const state = await readState();
20
- await writeState(state);
21
- invalidateStateCache();
22
- return state;
23
- } catch (error) {
24
- throw new Error(`${operation} 已写入 models.json,但 state.json metadata 清理失败:${formatUnknownError(error)}`);
25
- }
26
- }
27
-
28
- async function refreshNativeMutationRuntime(
29
- pi: ExtensionAPI,
30
- ctx: ExtensionCommandContext,
31
- operation: string,
32
- state: StateDocument,
33
- providerId: string,
34
- ): Promise<void> {
35
- try {
36
- await ctx.modelRegistry.refresh();
37
- const provider = state.providers[providerId];
38
- if (provider) await reconcileProvider(pi, providerId, provider, state.requestHeaderProfiles, state.clientHeaderCaptures);
39
- else unregisterManagedProvider(pi, providerId);
40
- } catch (error) {
41
- throw new Error(`${operation} 已写入 models.json/state.json,但当前会话 registry 刷新失败:${formatUnknownError(error)}。可执行 /reload 重试。`);
42
- }
43
- }
44
-
45
- export async function deleteModelsJsonProviderConfiguration(
46
- pi: ExtensionAPI,
47
- ctx: ExtensionCommandContext,
48
- providerId: string,
49
- ): Promise<void> {
50
- const snapshot = await readModelsJsonSnapshot();
51
- const doc = snapshot.document;
52
- const removedModels = [...(doc.providers[providerId]?.models ?? [])].map((model) => model.id);
53
- await writeModelsJsonSnapshot(snapshot, deleteProviderInDoc(doc, providerId));
54
- invalidateStateCache();
55
- const state = await refreshMetadataAfterNativeWrite(`删除 ${providerId}`);
56
- await refreshNativeMutationRuntime(pi, ctx, `删除 ${providerId}`, state, providerId);
57
- try {
58
- for (const modelId of removedModels) {
59
- await removeModelFromNextPiStart(ctx.cwd, getModelFullId(providerId, modelId));
60
- }
61
- } catch (error) {
62
- ctx.ui.notify(`已删除 ${providerId},但 enabledModels 清理失败:${formatUnknownError(error)}`, "warning");
63
- }
64
- ctx.ui.notify(`已删除 ${providerId}`, "info");
65
- await withModelRescue(ctx, pi, { providerId }, { reason: `models.json 中的 ${providerId} 已删除` });
66
- }
67
-
68
- export async function deleteModelsJsonModelConfiguration(
69
- pi: ExtensionAPI,
70
- ctx: ExtensionCommandContext,
71
- providerId: string,
72
- modelId: string,
73
- ): Promise<void> {
74
- const fullId = getModelFullId(providerId, modelId);
75
- const snapshot = await readModelsJsonSnapshot();
76
- const doc = snapshot.document;
77
- let nextDoc = deleteModelInDoc(doc, providerId, modelId);
78
- if ((nextDoc.providers[providerId]?.models?.length ?? 0) === 0) nextDoc = deleteProviderInDoc(nextDoc, providerId);
79
- await writeModelsJsonSnapshot(snapshot, nextDoc);
80
- invalidateStateCache();
81
- const state = await refreshMetadataAfterNativeWrite(`删除 ${fullId}`);
82
- await refreshNativeMutationRuntime(pi, ctx, `删除 ${fullId}`, state, providerId);
83
- try {
84
- await removeModelFromNextPiStart(ctx.cwd, fullId);
85
- } catch (error) {
86
- ctx.ui.notify(`已删除 ${fullId},但 enabledModels 清理失败:${formatUnknownError(error)}`, "warning");
87
- }
88
- ctx.ui.notify(`已删除 ${fullId}`, "info");
89
- await withModelRescue(ctx, pi, { providerId, modelId }, { reason: `models.json 中的 ${fullId} 已删除` });
90
- }