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.
@@ -0,0 +1,79 @@
1
+ // 模型列表响应的资源与终端安全边界。
2
+
3
+ import { isObjectRecord } from "../common.ts";
4
+ import type { ApiKind } from "../types.ts";
5
+
6
+ const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
7
+ const MAX_MODEL_COUNT = 5_000;
8
+ const MAX_MODEL_ID_LENGTH = 256;
9
+ const UNSAFE_TERMINAL_TEXT_PATTERN = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u;
10
+
11
+ function waitWithSignal<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
12
+ if (signal.aborted) return Promise.reject(signal.reason);
13
+ return new Promise<T>((resolve, reject) => {
14
+ const abort = () => reject(signal.reason instanceof Error ? signal.reason : new Error("模型发现已取消"));
15
+ signal.addEventListener("abort", abort, { once: true });
16
+ operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
17
+ });
18
+ }
19
+
20
+ function validateModelId(id: string): string {
21
+ if (!id || id.length > MAX_MODEL_ID_LENGTH) {
22
+ throw new Error(`上游模型 ID 长度必须为 1-${MAX_MODEL_ID_LENGTH} 个字符`);
23
+ }
24
+ if (UNSAFE_TERMINAL_TEXT_PATTERN.test(id)) {
25
+ throw new Error("上游模型 ID 包含控制字符或终端转义序列,已拒绝显示");
26
+ }
27
+ return id;
28
+ }
29
+
30
+ export function extractValidatedModelIds(envelope: unknown, api: ApiKind): string[] {
31
+ if (!isObjectRecord(envelope)) return [];
32
+ const rawModels = api === "google-generative-ai" ? envelope.models : envelope.data;
33
+ if (!Array.isArray(rawModels)) return [];
34
+ if (rawModels.length > MAX_MODEL_COUNT) {
35
+ throw new Error(`上游返回 ${rawModels.length} 个模型,超过上限 ${MAX_MODEL_COUNT}`);
36
+ }
37
+ const ids = new Set<string>();
38
+ for (const model of rawModels) {
39
+ if (!isObjectRecord(model)) continue;
40
+ const rawId = api === "google-generative-ai" ? model.name : model.id;
41
+ if (typeof rawId !== "string") continue;
42
+ const id = api === "google-generative-ai" ? rawId.replace(/^models\//, "") : rawId;
43
+ ids.add(validateModelId(id));
44
+ }
45
+ return [...ids].sort((left, right) => left.localeCompare(right));
46
+ }
47
+
48
+ export async function readBoundedResponseText(response: Response, signal: AbortSignal): Promise<string> {
49
+ const declaredLength = Number.parseInt(response.headers.get("content-length") ?? "", 10);
50
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
51
+ throw new Error(`模型列表响应体超过 ${MAX_RESPONSE_BYTES} 字节上限`);
52
+ }
53
+ if (!response.body) {
54
+ const text = await waitWithSignal(response.text(), signal);
55
+ if (Buffer.byteLength(text, "utf8") > MAX_RESPONSE_BYTES) throw new Error(`模型列表响应体超过 ${MAX_RESPONSE_BYTES} 字节上限`);
56
+ return text;
57
+ }
58
+
59
+ const reader = response.body.getReader();
60
+ const decoder = new TextDecoder();
61
+ let totalBytes = 0;
62
+ let text = "";
63
+ try {
64
+ while (true) {
65
+ const chunk = await waitWithSignal(reader.read(), signal);
66
+ if (chunk.done) break;
67
+ totalBytes += chunk.value.byteLength;
68
+ if (totalBytes > MAX_RESPONSE_BYTES) {
69
+ await reader.cancel("response too large");
70
+ throw new Error(`模型列表响应体超过 ${MAX_RESPONSE_BYTES} 字节上限`);
71
+ }
72
+ text += decoder.decode(chunk.value, { stream: true });
73
+ }
74
+ text += decoder.decode();
75
+ return text;
76
+ } finally {
77
+ reader.releaseLock();
78
+ }
79
+ }
@@ -7,7 +7,7 @@
7
7
  // 表单页另有 Ctrl+S 保存;列表页可注册单键快捷操作,并用 / 做轻量过滤。
8
8
 
9
9
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
10
- import { Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
10
+ import { CURSOR_MARKER, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
11
11
 
12
12
  export interface MenuRow {
13
13
  id: string;
@@ -17,7 +17,8 @@ export interface MenuRow {
17
17
 
18
18
  export interface PersistentMenuOptions {
19
19
  summaryLines?: readonly string[];
20
- tableHeader?: string;
20
+ tableHeader?: string | ((width: number) => string);
21
+ formatRow?: (row: MenuRow, width: number) => string;
21
22
  getDetailLines?: (selectedRow: MenuRow | undefined) => readonly string[];
22
23
  footer?: string;
23
24
  emptyLabel?: string;
@@ -80,6 +81,32 @@ function isSearchTextInput(data: string): boolean {
80
81
  return data.length > 0 && !data.startsWith("\x1b") && !/[\u0000-\u001f\u007f]/.test(data);
81
82
  }
82
83
 
84
+ function fitSearchQueryAroundCursor(query: string, cursor: number, cursorGlyph: string, maxWidth: number): string {
85
+ if (maxWidth <= 0) return "";
86
+ const characters = Array.from(query);
87
+ const cursorWidth = visibleWidth(cursorGlyph);
88
+ const textBudget = Math.max(0, maxWidth - cursorWidth);
89
+ let beforeCursor = "";
90
+ let beforeWidth = 0;
91
+ for (let index = Math.min(cursor, characters.length) - 1; index >= 0; index -= 1) {
92
+ const character = characters[index]!;
93
+ const characterWidth = visibleWidth(character);
94
+ if (beforeWidth + characterWidth > textBudget) break;
95
+ beforeCursor = character + beforeCursor;
96
+ beforeWidth += characterWidth;
97
+ }
98
+ let afterCursor = "";
99
+ let afterWidth = 0;
100
+ for (let index = Math.min(cursor, characters.length); index < characters.length; index += 1) {
101
+ const character = characters[index]!;
102
+ const characterWidth = visibleWidth(character);
103
+ if (beforeWidth + afterWidth + characterWidth > textBudget) break;
104
+ afterCursor += character;
105
+ afterWidth += characterWidth;
106
+ }
107
+ return `${beforeCursor}${cursorGlyph}${afterCursor}`;
108
+ }
109
+
83
110
  function createPersistentMenu<TAction extends MenuAction | FormMenuAction | ShortcutMenuAction>(
84
111
  ctx: ExtensionCommandContext,
85
112
  title: string,
@@ -97,6 +124,8 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
97
124
  let selectedIndex = clampIndex(cursor.index, rows.length);
98
125
  let searchActive = false;
99
126
  let searchQuery = "";
127
+ let searchCursor = 0;
128
+ let focused = false;
100
129
  const visibleRows = options.visibleRows ?? 18;
101
130
  const searchable = options.searchable ?? false;
102
131
 
@@ -104,7 +133,7 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
104
133
 
105
134
  const syncCursor = (activeRows: MenuRow[]): void => {
106
135
  const row = activeRows[selectedIndex];
107
- cursor.index = row ? rows.indexOf(row) : rows.length;
136
+ if (row) cursor.index = rows.indexOf(row);
108
137
  };
109
138
 
110
139
  const requestRender = (): void => {
@@ -118,11 +147,22 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
118
147
  if (!searchable || (!searchActive && !searchQuery)) return false;
119
148
  searchActive = false;
120
149
  searchQuery = "";
150
+ searchCursor = 0;
121
151
  selectedIndex = clampIndex(cursor.index, rows.length);
122
152
  requestRender();
123
153
  return true;
124
154
  };
125
155
 
156
+ const replaceSearchQuery = (nextQuery: string, nextCursor: number): void => {
157
+ const selectedRow = getActiveRows()[selectedIndex];
158
+ searchQuery = nextQuery;
159
+ searchCursor = clampIndex(nextCursor, Array.from(searchQuery).length + 1);
160
+ const nextRows = getActiveRows();
161
+ const retainedIndex = selectedRow ? nextRows.indexOf(selectedRow) : -1;
162
+ selectedIndex = retainedIndex >= 0 ? retainedIndex : 0;
163
+ requestRender();
164
+ };
165
+
126
166
  const pickSelected = (): void => {
127
167
  const activeRows = getActiveRows();
128
168
  const row = activeRows[selectedIndex];
@@ -137,6 +177,12 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
137
177
  };
138
178
 
139
179
  return {
180
+ get focused(): boolean {
181
+ return focused;
182
+ },
183
+ set focused(value: boolean) {
184
+ focused = value;
185
+ },
140
186
  invalidate(): void {},
141
187
  handleInput(data: string): void {
142
188
  if (createSaveAction && matchesKey(data, Key.ctrl("s"))) {
@@ -164,11 +210,39 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
164
210
  return;
165
211
  }
166
212
 
167
- // 搜索激活后,可打印字符必须进入查询,不能触发同名的菜单快捷键。
168
213
  if (searchable && searchActive) {
214
+ const queryCharacters = Array.from(searchQuery);
169
215
  if (matchesKey(data, Key.backspace)) {
170
- searchQuery = searchQuery.slice(0, -1);
171
- selectedIndex = 0;
216
+ if (searchCursor > 0) {
217
+ queryCharacters.splice(searchCursor - 1, 1);
218
+ replaceSearchQuery(queryCharacters.join(""), searchCursor - 1);
219
+ }
220
+ return;
221
+ }
222
+ if (matchesKey(data, Key.delete)) {
223
+ if (searchCursor < queryCharacters.length) {
224
+ queryCharacters.splice(searchCursor, 1);
225
+ replaceSearchQuery(queryCharacters.join(""), searchCursor);
226
+ }
227
+ return;
228
+ }
229
+ if (matchesKey(data, Key.left)) {
230
+ searchCursor = Math.max(0, searchCursor - 1);
231
+ requestRender();
232
+ return;
233
+ }
234
+ if (matchesKey(data, Key.right)) {
235
+ searchCursor = Math.min(queryCharacters.length, searchCursor + 1);
236
+ requestRender();
237
+ return;
238
+ }
239
+ if (matchesKey(data, Key.home)) {
240
+ searchCursor = 0;
241
+ requestRender();
242
+ return;
243
+ }
244
+ if (matchesKey(data, Key.end)) {
245
+ searchCursor = queryCharacters.length;
172
246
  requestRender();
173
247
  return;
174
248
  }
@@ -177,9 +251,8 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
177
251
  return;
178
252
  }
179
253
  if (isSearchTextInput(data)) {
180
- searchQuery += data;
181
- selectedIndex = 0;
182
- requestRender();
254
+ queryCharacters.splice(searchCursor, 0, ...Array.from(data));
255
+ replaceSearchQuery(queryCharacters.join(""), searchCursor + Array.from(data).length);
183
256
  return;
184
257
  }
185
258
  }
@@ -192,6 +265,7 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
192
265
  }
193
266
  if (searchable && data === "/") {
194
267
  searchActive = true;
268
+ searchCursor = Array.from(searchQuery).length;
195
269
  requestRender();
196
270
  return;
197
271
  }
@@ -252,13 +326,20 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
252
326
  lines.push(truncateToWidth(theme.fg("dim", line), width));
253
327
  }
254
328
  if (searchable && searchActive) {
255
- lines.push(truncateToWidth(theme.fg("accent", `搜索:${searchQuery || "<输入关键词>"}`), width));
329
+ const cursorGlyph = focused ? `${CURSOR_MARKER}${theme.fg("accent", "▌")}` : "";
330
+ const searchPrefix = theme.fg("accent", "搜索:");
331
+ const queryWidth = Math.max(0, width - visibleWidth(searchPrefix));
332
+ const queryDisplay = searchQuery
333
+ ? fitSearchQueryAroundCursor(searchQuery, searchCursor, cursorGlyph, queryWidth)
334
+ : `${cursorGlyph}${theme.fg("dim", "<输入关键词>")}`;
335
+ lines.push(truncateToWidth(`${searchPrefix}${queryDisplay}`, width, ""));
256
336
  }
257
337
  lines.push("");
258
338
 
259
- if (options.tableHeader) {
260
- lines.push(truncateToWidth(theme.fg("dim", options.tableHeader), width));
261
- }
339
+ const tableHeader = typeof options.tableHeader === "function"
340
+ ? options.tableHeader(width)
341
+ : options.tableHeader;
342
+ if (tableHeader) lines.push(truncateToWidth(theme.fg("dim", tableHeader), width));
262
343
 
263
344
  if (shownRows.length === 0) {
264
345
  const emptyLabel = searchQuery ? `无匹配项:${searchQuery}` : options.emptyLabel ?? "暂无条目";
@@ -269,7 +350,8 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
269
350
  const row = shownRows[i]!;
270
351
  const selected = absoluteIndex === selectedIndex;
271
352
  const prefix = selected ? "❯ " : " ";
272
- const line = `${prefix}${row.label}`;
353
+ const rowLabel = options.formatRow?.(row, Math.max(0, width - visibleWidth(prefix))) ?? row.label;
354
+ const line = `${prefix}${rowLabel}`;
273
355
  lines.push(truncateToWidth(selected ? theme.fg("accent", line) : line, width));
274
356
  for (const description of getDescriptionLines(row)) {
275
357
  lines.push(truncateToWidth(theme.fg("dim", ` ${description}`), width));
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,
@@ -25,16 +26,6 @@ export function maskSecret(value: string | undefined): string {
25
26
  if (getApiKeyEnvVarName(value) || value.startsWith("!")) return value;
26
27
  return "********";
27
28
  }
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
29
  function formatContextWindow(contextWindow: number): string {
39
30
  if (contextWindow >= 1_000_000) return `${(contextWindow / 1_000_000).toFixed(contextWindow % 1_000_000 === 0 ? 0 : 1)}M`;
40
31
  if (contextWindow >= 1_000) return `${Math.round(contextWindow / 1_000)}K`;
@@ -56,18 +47,14 @@ export function fitColumn(text: string, columns: number, align: ColumnAlign = "l
56
47
  return align === "right" ? pad + clipped : clipped + pad;
57
48
  }
58
49
 
59
- export function joinFixedColumns(columns: readonly FixedColumn[], gap = " "): string {
50
+ function joinFixedColumns(columns: readonly FixedColumn[], gap = " "): string {
60
51
  return columns.map((column) => fitColumn(column.text, column.width, column.align)).join(gap).trimEnd();
61
52
  }
62
53
 
63
- export function formatTableHeader(line: string): string {
54
+ function formatTableHeader(line: string): string {
64
55
  return ` ${line}`;
65
56
  }
66
57
 
67
- function sanitizeEndpoint(value: string): string {
68
- return value.replace(/([?&](?:key|api_key|api-key)=)[^&]+/gi, "$1REDACTED");
69
- }
70
-
71
58
  export function formatApiShort(api: ApiKind): string {
72
59
  if (api === "openai-responses") return "Responses";
73
60
  if (api === "openai-completions") return "Chat";
@@ -94,7 +81,7 @@ function getProviderProxyText(provider: StoredProvider): string {
94
81
  return provider.httpProxyEnabled ? "proxy" : "direct";
95
82
  }
96
83
 
97
- export function formatProviderHeaderProfile(
84
+ function formatProviderHeaderProfile(
98
85
  provider: StoredProvider,
99
86
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
100
87
  ): string {
@@ -114,54 +101,83 @@ export function formatProviderHeaderProfile(
114
101
  return CLIENT_HEADER_PROFILE_LABELS[provider.clientHeaderProfile];
115
102
  }
116
103
 
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" },
104
+ interface ProviderConsoleCells {
105
+ provider: string;
106
+ api: string;
107
+ models: string;
108
+ headers: string;
109
+ proxy: string;
110
+ auth: string;
111
+ status: string;
112
+ }
113
+
114
+ function getProviderConsoleColumns(cells: ProviderConsoleCells, availableWidth: number): FixedColumn[] {
115
+ if (availableWidth >= 81) {
116
+ return [
117
+ { text: cells.provider, width: 22 },
118
+ { text: cells.api, width: 9 },
119
+ { text: cells.models, width: 6, align: "right" },
120
+ { text: cells.headers, width: 15 },
121
+ { text: cells.proxy, width: 6 },
122
+ { text: cells.auth, width: 6 },
123
+ { text: cells.status, width: 5 },
124
+ ];
125
+ }
126
+ if (availableWidth >= 64) {
127
+ return [
128
+ { text: cells.provider, width: 20 },
129
+ { text: cells.api, width: 9 },
130
+ { text: cells.models, width: 6, align: "right" },
131
+ { text: cells.proxy, width: 6 },
132
+ { text: cells.auth, width: 6 },
133
+ { text: cells.status, width: 5 },
134
+ ];
135
+ }
136
+ if (availableWidth >= 48) {
137
+ return [
138
+ { text: cells.provider, width: 20 },
139
+ { text: cells.api, width: 9 },
140
+ { text: cells.models, width: 6, align: "right" },
141
+ { text: cells.status, width: 5 },
142
+ ];
143
+ }
144
+ return [
145
+ { text: cells.provider, width: Math.max(10, availableWidth - 26) },
146
+ { text: cells.api, width: 9 },
147
+ { text: cells.models, width: 6, align: "right" },
148
+ { text: cells.status, width: 5 },
135
149
  ];
136
- if (provider.api === "openai-responses") columns.push({ text: "Fast", width: 8 });
137
- return columns;
138
150
  }
139
151
 
140
- export function formatModelListHeader(provider: StoredProvider): string {
141
- return formatTableHeader(joinFixedColumns(getModelListColumns(provider)));
152
+ export function formatProviderConsoleHeader(menuWidth: number): string {
153
+ return formatTableHeader(joinFixedColumns(getProviderConsoleColumns({
154
+ provider: "接入",
155
+ api: "API",
156
+ models: "模型",
157
+ headers: "请求头",
158
+ proxy: "代理",
159
+ auth: "认证",
160
+ status: "状态",
161
+ }, Math.max(0, menuWidth - 2))));
142
162
  }
143
163
 
144
164
  export function formatProviderConsoleRow(
145
165
  providerId: string,
146
166
  provider: StoredProvider,
147
167
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
168
+ availableWidth = 81,
148
169
  ): string {
149
170
  const name = getProviderDisplayName(providerId, provider);
150
171
  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)}`;
172
+ return joinFixedColumns(getProviderConsoleColumns({
173
+ provider: displayName,
174
+ api: formatApiShort(provider.api),
175
+ models: String(provider.models.length),
176
+ headers: formatProviderHeaderProfile(provider, requestHeaderProfiles),
177
+ proxy: getProviderProxyText(provider),
178
+ auth: getAuthKind(provider.apiKey),
179
+ status: getProviderStatus(provider),
180
+ }, availableWidth));
165
181
  }
166
182
 
167
183
  export function formatProviderDetailLines(
@@ -174,8 +190,8 @@ export function formatProviderDetailLines(
174
190
  const modelIds = provider.models.map((model) => model.id).join(", ") || "<无模型>";
175
191
  return [
176
192
  title,
177
- ` endpoint ${sanitizeEndpoint(provider.baseUrl)}`,
178
- ` proxy ${provider.httpProxyEnabled ? sanitizeEndpoint(provider.httpProxyUrl ?? "http://127.0.0.1:7890") : "direct"}`,
193
+ ` endpoint ${redactUrlForDisplay(provider.baseUrl)}`,
194
+ ` proxy ${provider.httpProxyEnabled ? redactUrlForDisplay(provider.httpProxyUrl ?? "http://127.0.0.1:7890") : "direct"}`,
179
195
  ` api ${formatApiShort(provider.api)} · headers ${formatProviderHeaderProfile(provider, requestHeaderProfiles)} · auth ${getAuthKind(provider.apiKey)}`,
180
196
  ` models ${modelIds}`,
181
197
  ];
@@ -189,26 +205,8 @@ export function formatProviderSummaryLine(
189
205
  }
190
206
 
191
207
  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(" · ")}`;
208
+ const proxy = provider.httpProxyEnabled ? ` · proxy ${redactUrlForDisplay(provider.httpProxyUrl ?? "http://127.0.0.1:7890")}` : "";
209
+ return `endpoint ${redactUrlForDisplay(provider.baseUrl)}${proxy}`;
212
210
  }
213
211
 
214
212
  function formatModelNameCell(model: StoredModel): string {
@@ -223,30 +221,82 @@ function formatModelThinkingCell(model: StoredModel): string {
223
221
  return model.reasoning ? "开" : "关";
224
222
  }
225
223
 
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
- ]);
224
+ interface ModelListCells {
225
+ modelId: string;
226
+ name: string;
227
+ input: string;
228
+ thinking: string;
229
+ context: string;
230
+ output: string;
231
+ fast: string;
235
232
  }
236
233
 
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 });
234
+ function getModelListColumns(provider: StoredProvider, cells: ModelListCells, availableWidth: number): FixedColumn[] {
235
+ const fullWidth = provider.api === "openai-responses" ? 98 : 88;
236
+ if (availableWidth >= fullWidth) {
237
+ const columns: FixedColumn[] = [
238
+ { text: cells.modelId, width: 30 },
239
+ { text: cells.name, width: 16 },
240
+ { text: cells.input, width: 10 },
241
+ { text: cells.thinking, width: 8 },
242
+ { text: cells.context, width: 7, align: "right" },
243
+ { text: cells.output, width: 7, align: "right" },
244
+ ];
245
+ if (provider.api === "openai-responses") columns.push({ text: cells.fast, width: 8 });
246
+ return columns;
248
247
  }
249
- return joinFixedColumns(columns);
248
+ if (availableWidth >= 75) {
249
+ return [
250
+ { text: cells.modelId, width: 28 },
251
+ { text: cells.name, width: 14 },
252
+ { text: cells.input, width: 10 },
253
+ { text: cells.thinking, width: 8 },
254
+ { text: cells.context, width: 7, align: "right" },
255
+ ];
256
+ }
257
+ if (availableWidth >= 57) {
258
+ return [
259
+ { text: cells.modelId, width: 26 },
260
+ { text: cells.input, width: 10 },
261
+ { text: cells.thinking, width: 8 },
262
+ { text: cells.context, width: 7, align: "right" },
263
+ ];
264
+ }
265
+ return [
266
+ { text: cells.modelId, width: Math.max(10, availableWidth - 22) },
267
+ { text: cells.input, width: 10 },
268
+ { text: cells.thinking, width: 8 },
269
+ ];
270
+ }
271
+
272
+ function getModelListCells(model?: StoredModel): ModelListCells {
273
+ return model
274
+ ? {
275
+ modelId: model.id,
276
+ name: formatModelNameCell(model),
277
+ input: formatModelInputCell(model),
278
+ thinking: formatModelThinkingCell(model),
279
+ context: formatContextWindow(model.contextWindow),
280
+ output: formatContextWindow(model.maxTokens),
281
+ fast: model.openAIServiceTier === "priority" ? "priority" : "off",
282
+ }
283
+ : {
284
+ modelId: "模型 ID",
285
+ name: "显示名",
286
+ input: "输入",
287
+ thinking: "Thinking",
288
+ context: "上下文",
289
+ output: "输出",
290
+ fast: "Fast",
291
+ };
292
+ }
293
+
294
+ export function formatModelListHeader(provider: StoredProvider, menuWidth = 100): string {
295
+ return formatTableHeader(joinFixedColumns(getModelListColumns(provider, getModelListCells(), Math.max(0, menuWidth - 2))));
296
+ }
297
+
298
+ export function formatModelListRow(provider: StoredProvider, model: StoredModel, availableWidth = 98): string {
299
+ return joinFixedColumns(getModelListColumns(provider, getModelListCells(model), availableWidth));
250
300
  }
251
301
 
252
302
  export const API_CHOICES: { id: ApiKind; label: string }[] = [
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 };