pi-model-manager 0.4.8 → 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.
package/tui/ui-helpers.ts CHANGED
@@ -2,21 +2,16 @@
2
2
  //
3
3
  // 共用展示助手:把 stored / draft 数据格式化成 UI 字符串。
4
4
  //
5
- // dashboard 行设计准则:信息密度千万不要满。
6
- // - 主列表使用固定列 + 选中详情;行内只放扫描所需信息
7
- // - api 用短标签(Responses / Claude),详情区再显示完整上下文
8
- // - auth 状态文本化为 key/env/cmd/auth?,避免把可选的外部认证误报成缺失
9
- // - contextWindow 用 K/M 简写
5
+ // 工作区模型表按可用列宽收敛;接入摘要与完整端点供详情区复用。
10
6
 
11
7
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
12
8
  import { t } from "../i18n.ts";
13
- import { getApiKeyEnvVarName, getAuthStatusText, getProviderDisplayName } from "../state-document.ts";
9
+ import { getAuthStatusText, getProviderDisplayName } from "../state-document.ts";
14
10
  import { getClientHeaderProfileDisplay, getClientHeaderProfileLabel, resolveClientHeaderProfile } from "../presets/client-headers.ts";
15
11
  import { redactUrlForDisplay } from "../sensitive-redaction.ts";
16
12
  import type {
17
13
  ApiKind,
18
14
  ClientHeaderProfileId,
19
- ModelInputKind,
20
15
  OpenAIServiceTier,
21
16
  StoredModel,
22
17
  StoredProvider,
@@ -26,7 +21,6 @@ import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
26
21
 
27
22
  export function maskSecret(value: string | undefined): string {
28
23
  if (!value) return t("<未填写>");
29
- if (getApiKeyEnvVarName(value) || value.startsWith("!")) return value;
30
24
  return "********";
31
25
  }
32
26
  function formatContextWindow(contextWindow: number): string {
@@ -83,11 +77,6 @@ function getAuthKind(apiKey: string | undefined): string {
83
77
  return "key";
84
78
  }
85
79
 
86
- function getProviderStatus(provider: StoredProvider): string {
87
- const auth = getAuthKind(provider.apiKey);
88
- return auth === "miss" || auth === "auth?" ? "check" : "ready";
89
- }
90
-
91
80
  function getProviderProxyText(provider: StoredProvider): string {
92
81
  return provider.httpProxyEnabled ? "proxy" : "direct";
93
82
  }
@@ -112,122 +101,67 @@ function formatProviderHeaderProfile(
112
101
  return getClientHeaderProfileLabel(provider.clientHeaderProfile);
113
102
  }
114
103
 
115
- interface ProviderConsoleCells {
116
- provider: string;
117
- api: string;
118
- models: string;
119
- headers: string;
120
- proxy: string;
121
- auth: string;
122
- status: string;
123
- }
124
-
125
- export interface ProviderTableOptions {
126
- requestHeaderProfiles?: Record<string, StoredRequestHeaderProfile>;
127
- theme?: Theme;
128
- // 按当前数据收敛后的接入列宽;表头与数据行必须传同一个值才能对齐。
129
- nameWidth?: number;
130
- }
131
-
132
- const PROVIDER_NAME_COLUMN_LIMIT = 22;
133
- const PROVIDER_NAME_COLUMN_MIN = 12;
134
-
135
- export function getProviderDisplayLabel(providerId: string, provider: StoredProvider): string {
136
- const name = getProviderDisplayName(providerId, provider);
137
- return name === providerId ? providerId : `${name} (${providerId})`;
138
- }
139
-
140
- export function getProviderNameColumnWidth(displayLabels: readonly string[]): number {
141
- const longest = displayLabels.reduce((max, label) => Math.max(max, visibleWidth(label)), 0);
142
- return Math.min(PROVIDER_NAME_COLUMN_LIMIT, Math.max(PROVIDER_NAME_COLUMN_MIN, longest));
143
- }
144
-
145
- function getAuthColor(auth: string): ThemeColor | undefined {
146
- return auth === "miss" || auth === "auth?" ? "warning" : undefined;
147
- }
148
-
149
- function getProviderConsoleColumns(cells: ProviderConsoleCells, availableWidth: number, nameWidth: number): FixedColumn[] {
150
- const provider: FixedColumn = { text: cells.provider, width: Math.min(nameWidth, PROVIDER_NAME_COLUMN_LIMIT) };
151
- const api: FixedColumn = { text: cells.api, width: 9 };
152
- const models: FixedColumn = { text: cells.models, width: 6, align: "right" };
153
- const headers: FixedColumn = { text: cells.headers, width: 15, color: cells.headers === "Off" ? "dim" : undefined };
154
- const proxy: FixedColumn = { text: cells.proxy, width: 6, color: cells.proxy === "proxy" ? "accent" : "dim" };
155
- const auth: FixedColumn = { text: cells.auth, width: 6, color: getAuthColor(cells.auth) };
156
- const status: FixedColumn = { text: cells.status, width: 5, color: cells.status === "ready" ? "success" : "warning" };
157
- if (availableWidth >= 81) return [provider, api, models, headers, proxy, auth, status];
158
- if (availableWidth >= 64) return [provider, api, models, proxy, auth, status];
159
- if (availableWidth >= 48) return [provider, api, models, status];
160
- return [{ ...provider, width: Math.max(10, availableWidth - 26) }, api, models, status];
104
+ export function formatProviderSummaryLine(
105
+ provider: StoredProvider,
106
+ requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
107
+ ): string {
108
+ return `${formatApiShort(provider.api)} · ${provider.models.length} ${t("模型")} · headers ${formatProviderHeaderProfile(provider, requestHeaderProfiles)} · proxy ${getProviderProxyText(provider)} · auth ${getAuthKind(provider.apiKey)}`;
161
109
  }
162
110
 
163
- export function formatProviderConsoleHeader(menuWidth: number, options: ProviderTableOptions = {}): string {
164
- return formatTableHeader(joinFixedColumns(getProviderConsoleColumns({
165
- provider: t("接入"),
166
- api: "API",
167
- models: t("模型"),
168
- headers: t("请求头"),
169
- proxy: t("代理"),
170
- auth: t("认证"),
171
- status: t("状态"),
172
- }, Math.max(0, menuWidth - 2), options.nameWidth ?? PROVIDER_NAME_COLUMN_LIMIT)));
111
+ export function formatProviderEndpointLine(provider: StoredProvider): string {
112
+ const proxy = provider.httpProxyEnabled ? ` · proxy ${redactUrlForDisplay(provider.httpProxyUrl ?? "http://127.0.0.1:7890")}` : "";
113
+ return `endpoint ${redactUrlForDisplay(provider.baseUrl)}${proxy}`;
173
114
  }
174
115
 
175
- export function formatProviderConsoleRow(
176
- providerId: string,
177
- provider: StoredProvider,
178
- availableWidth = 81,
179
- options: ProviderTableOptions = {},
180
- ): string {
181
- return joinFixedColumns(getProviderConsoleColumns({
182
- provider: getProviderDisplayLabel(providerId, provider),
183
- api: formatApiShort(provider.api),
184
- models: String(provider.models.length),
185
- headers: formatProviderHeaderProfile(provider, options.requestHeaderProfiles ?? {}),
186
- proxy: getProviderProxyText(provider),
187
- auth: getAuthKind(provider.apiKey),
188
- status: getProviderStatus(provider),
189
- }, availableWidth, options.nameWidth ?? PROVIDER_NAME_COLUMN_LIMIT), options.theme);
116
+ function getProviderListColumns(providerId: string, provider: StoredProvider | undefined, availableWidth: number): FixedColumn[] {
117
+ const authKind = provider ? getAuthKind(provider.apiKey) : "";
118
+ const id: FixedColumn = { text: provider ? providerId : `${t("接入")} ID`, width: 16 };
119
+ const name: FixedColumn = { text: provider ? getProviderDisplayName(providerId, provider) : t("名称"), width: 14 };
120
+ const api: FixedColumn = { text: provider ? formatApiShort(provider.api) : "API", width: 9 };
121
+ const models: FixedColumn = { text: provider ? String(provider.models.length) : t("模型"), width: 6, align: "right" };
122
+ const auth: FixedColumn = { text: provider ? authKind : t("认证"), width: 6, color: authKind === "auth?" || authKind === "miss" ? "warning" : undefined };
123
+ const proxy: FixedColumn = { text: provider ? getProviderProxyText(provider) : t("代理"), width: 6 };
124
+ const endpoint: FixedColumn = { text: provider ? redactUrlForDisplay(provider.baseUrl) : "Base URL", width: 20 };
125
+ const columns = [id, name, api, models, auth, proxy, endpoint];
126
+ const totalWidth = () => columns.reduce((sum, column) => sum + column.width, 0) + Math.max(0, columns.length - 1) * 2;
127
+ for (const column of [endpoint, name, proxy, auth, api, models]) {
128
+ if (totalWidth() <= availableWidth) break;
129
+ columns.splice(columns.indexOf(column), 1);
130
+ }
131
+ const remaining = availableWidth - totalWidth();
132
+ if (columns.includes(endpoint)) {
133
+ const idExtra = Math.min(12, Math.floor(remaining / 3));
134
+ id.width += idExtra;
135
+ endpoint.width += remaining - idExtra;
136
+ } else id.width = Math.max(0, id.width + remaining);
137
+ return columns;
190
138
  }
191
139
 
192
- // [喵喵喵]: 详情区分三级(标题/字段名/值),否则整块同一灰度无法扫读;
193
- // 缩进与标签列宽必须在所有面板一致,否则切面板时详情区会跳动。
194
- const DETAIL_LABEL_WIDTH = 10;
195
-
196
- export function formatDetailTitle(title: string, theme?: Theme): string {
197
- return theme ? theme.fg("text", title) : title;
140
+ export function formatProviderListHeader(menuWidth: number): string {
141
+ return formatTableHeader(joinFixedColumns(getProviderListColumns("", undefined, Math.max(0, menuWidth - 2))));
198
142
  }
199
143
 
200
- export function formatDetailField(label: string, value: string, theme?: Theme): string {
201
- const labelCell = ` ${fitColumn(label, DETAIL_LABEL_WIDTH)}`;
202
- return theme ? `${theme.fg("dim", labelCell)}${theme.fg("text", value)}` : `${labelCell}${value}`;
144
+ export function formatProviderListRow(providerId: string, provider: StoredProvider, availableWidth: number, theme: Theme): string {
145
+ return joinFixedColumns(getProviderListColumns(providerId, provider, availableWidth), theme);
203
146
  }
204
147
 
205
- export function formatProviderDetailLines(
206
- providerId: string,
207
- provider: StoredProvider,
208
- options: ProviderTableOptions = {},
209
- ): string[] {
210
- const { theme, requestHeaderProfiles = {} } = options;
211
- const modelIds = provider.models.map((model) => model.id).join(", ") || t("<无模型>");
212
- return [
213
- formatDetailTitle(getProviderDisplayLabel(providerId, provider), theme),
214
- formatDetailField("endpoint", redactUrlForDisplay(provider.baseUrl), theme),
215
- formatDetailField("proxy", provider.httpProxyEnabled ? redactUrlForDisplay(provider.httpProxyUrl ?? "http://127.0.0.1:7890") : "direct", theme),
216
- formatDetailField("api", `${formatApiShort(provider.api)} · headers ${formatProviderHeaderProfile(provider, requestHeaderProfiles)} · auth ${getAuthKind(provider.apiKey)}`, theme),
217
- formatDetailField("models", modelIds, theme),
218
- ];
148
+ function getHeaderProfileColumns(id: string, profile: StoredRequestHeaderProfile | undefined, usage: number, availableWidth: number): FixedColumn[] {
149
+ const name: FixedColumn = { text: profile?.name ?? t("名称"), width: 18 };
150
+ const identifier: FixedColumn = { text: profile ? id : "ID", width: 20 };
151
+ const fields: FixedColumn = { text: profile ? String(Object.keys(profile.headers).length) : t("字段"), width: 6, align: "right" };
152
+ const providers: FixedColumn = { text: profile ? String(usage) : t("使用接入"), width: 8, align: "right" };
153
+ const columns = [name, identifier, fields, providers];
154
+ if (availableWidth < 58) columns.splice(1, 1);
155
+ name.width = Math.max(1, availableWidth - columns.slice(1).reduce((sum, column) => sum + column.width + 2, 0));
156
+ return columns;
219
157
  }
220
158
 
221
- export function formatProviderSummaryLine(
222
- provider: StoredProvider,
223
- requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
224
- ): string {
225
- return `${formatApiShort(provider.api)} · ${provider.models.length} ${t("模型")} · headers ${formatProviderHeaderProfile(provider, requestHeaderProfiles)} · proxy ${getProviderProxyText(provider)} · auth ${getAuthKind(provider.apiKey)}`;
159
+ export function formatHeaderProfileListHeader(width: number): string {
160
+ return formatTableHeader(joinFixedColumns(getHeaderProfileColumns("", undefined, 0, Math.max(0, width - 2))));
226
161
  }
227
162
 
228
- export function formatProviderEndpointLine(provider: StoredProvider): string {
229
- const proxy = provider.httpProxyEnabled ? ` · proxy ${redactUrlForDisplay(provider.httpProxyUrl ?? "http://127.0.0.1:7890")}` : "";
230
- return `endpoint ${redactUrlForDisplay(provider.baseUrl)}${proxy}`;
163
+ export function formatHeaderProfileListRow(id: string, profile: StoredRequestHeaderProfile, usage: number, width: number): string {
164
+ return joinFixedColumns(getHeaderProfileColumns(id, profile, usage, width));
231
165
  }
232
166
 
233
167
  function formatModelNameCell(model: StoredModel): string {
@@ -248,6 +182,10 @@ export function formatOpenAIServiceTier(tier: OpenAIServiceTier | undefined): st
248
182
  return t("标准");
249
183
  }
250
184
 
185
+ export function formatModelSummaryLine(provider: StoredProvider, model: StoredModel): string {
186
+ return `${formatModelInputCell(model)} · Thinking ${formatModelThinkingCell(model)} · ${t("上下文")} ${formatContextWindow(model.contextWindow)} · ${t("输出")} ${formatContextWindow(model.maxTokens)}${provider.api === "openai-responses" ? ` · Fast ${formatOpenAIServiceTier(model.openAIServiceTier)}` : ""}`;
187
+ }
188
+
251
189
  interface ModelListCells {
252
190
  modelId: string;
253
191
  name: string;
@@ -292,39 +230,27 @@ function getModelListColumns(
292
230
  const modelIdWidth = options.modelIdWidth ?? MODEL_ID_COLUMN_LIMIT;
293
231
  const nameWidth = options.nameWidth ?? MODEL_NAME_COLUMN_LIMIT;
294
232
  const name: FixedColumn = { text: cells.name, width: nameWidth, color: cells.name === t("默认") ? "dim" : undefined };
295
- const input: FixedColumn = { text: cells.input, width: 10, color: cells.input === t("文本,视觉") ? "accent" : undefined };
296
- const thinking: FixedColumn = { text: cells.thinking, width: 8, color: cells.thinking === t("开") ? "accent" : cells.thinking === t("关") ? "dim" : undefined };
233
+ const input: FixedColumn = { text: cells.input, width: 10 };
234
+ const thinking: FixedColumn = { text: cells.thinking, width: 8, color: cells.thinking === t("关") ? "dim" : undefined };
297
235
  const context: FixedColumn = { text: cells.context, width: 7, align: "right" };
298
236
  const output: FixedColumn = { text: cells.output, width: 7, align: "right" };
299
237
  // [喵喵喵]: priority / ultrafast 都可能额外计费,用 warning 提醒而不是当普通开关。
300
238
  const fast: FixedColumn = { text: cells.fast, width: 8, color: cells.fast === "Fast" || cells.fast === "Ultrafast" ? "warning" : cells.fast === t("标准") ? "dim" : undefined };
301
239
 
302
- const fullWidth = provider.api === "openai-responses" ? 98 : 88;
303
- if (availableWidth >= fullWidth) {
304
- const columns: FixedColumn[] = [
305
- { text: cells.modelId, width: Math.min(modelIdWidth, 30) },
306
- { ...name, width: Math.min(nameWidth, 16) },
307
- input,
308
- thinking,
309
- context,
310
- output,
311
- ];
312
- if (provider.api === "openai-responses") columns.push(fast);
313
- return columns;
240
+ const id: FixedColumn = { text: cells.modelId, width: modelIdWidth };
241
+ const columns = [id, name, input, thinking, context, output];
242
+ if (provider.api === "openai-responses") columns.push(fast);
243
+ const totalWidth = () => columns.reduce((sum, column) => sum + column.width, 0) + Math.max(0, columns.length - 1) * 2;
244
+ for (const [column, minimum] of [[name, MODEL_NAME_COLUMN_MIN], [id, MODEL_ID_COLUMN_MIN]] as const) {
245
+ column.width -= Math.min(Math.max(0, column.width - minimum), Math.max(0, totalWidth() - availableWidth));
314
246
  }
315
- if (availableWidth >= 75) {
316
- return [
317
- { text: cells.modelId, width: Math.min(modelIdWidth, 28) },
318
- { ...name, width: Math.min(nameWidth, 14) },
319
- input,
320
- thinking,
321
- context,
322
- ];
247
+ for (const column of [name, context, output, fast, thinking, input]) {
248
+ if (totalWidth() <= availableWidth) break;
249
+ const index = columns.indexOf(column);
250
+ if (index >= 0) columns.splice(index, 1);
323
251
  }
324
- if (availableWidth >= 57) {
325
- return [{ text: cells.modelId, width: Math.min(modelIdWidth, 26) }, input, thinking, context];
326
- }
327
- return [{ text: cells.modelId, width: Math.max(10, availableWidth - 22) }, input, thinking];
252
+ id.width = Math.max(0, availableWidth - (totalWidth() - id.width));
253
+ return columns;
328
254
  }
329
255
 
330
256
  function getModelListCells(model?: StoredModel): ModelListCells {
@@ -377,6 +303,7 @@ export function getBuiltInProfileChoices(): { id: Exclude<ClientHeaderProfileId,
377
303
  { id: "disabled", label: t("不添加") },
378
304
  { id: "claude-code", label: "ClaudeCode" },
379
305
  { id: "codex-cli", label: "Codex" },
306
+ { id: "antigravity-cli", label: "Antigravity CLI" },
380
307
  ];
381
308
  }
382
309
 
@@ -391,19 +318,3 @@ export function describeProfile(
391
318
  const selected = requestHeaderProfiles[requestHeaderProfileId];
392
319
  return selected ? `${selected.name} (${requestHeaderProfileId})` : t("自定义请求头缺失:{id}", { id: requestHeaderProfileId });
393
320
  }
394
-
395
- export function getVisionInputChoices(): { enabled: boolean; kinds: ModelInputKind[]; label: string }[] {
396
- return [
397
- { enabled: false, kinds: ["text"], label: t("关闭 — 仅文本输入") },
398
- { enabled: true, kinds: ["text", "image"], label: t("开启 — 文本 + 图片输入") },
399
- ];
400
- }
401
-
402
- export function supportsVisionInput(kinds: ModelInputKind[]): boolean {
403
- return kinds.includes("image");
404
- }
405
-
406
- // 字段名已经说明了含义,值只需要跟 Thinking / Fast mode 一样给出开关状态。
407
- export function describeVisionInput(kinds: ModelInputKind[]): string {
408
- return supportsVisionInput(kinds) ? t("开启") : t("关闭");
409
- }
@@ -0,0 +1,127 @@
1
+ import { t } from "../i18n.ts";
2
+ import { switchProviderDraftApiPreset } from "../presets/providers.ts";
3
+ import { redactUrlForDisplay } from "../sensitive-redaction.ts";
4
+ import { resolveProviderDraftBaseUrl, validateRequestBaseUrl } from "../runtime-base-url.ts";
5
+ import { DEFAULT_PROVIDER_HTTP_PROXY_URL, type ProviderDraft, type ModelDraft, type StateDocument, type ClientHeaderProfileId } from "../types.ts";
6
+ import { describeProfile, getApiChoices, getBuiltInProfileChoices, maskSecret } from "./ui-helpers.ts";
7
+ import { CONTEXT_WINDOW_PRESETS, MAX_TOKENS_PRESETS, cycleNumericPreset, parsePositiveIntegerWithUnit } from "./model-values.ts";
8
+ import { ui, type Choice, type WorkbenchRow } from "./workbench-types.ts";
9
+
10
+ function text(id: string, label: string, value: string, apply: (value: string) => void, description?: string): WorkbenchRow {
11
+ return { id, label, value: value || t("<空>"), description, edit: { value, apply: (raw) => apply(raw.trim()) } };
12
+ }
13
+
14
+ function select<T extends string>(id: string, label: string, selected: T, options: { id: T; label: string; description?: string }[], apply: (id: T) => void, description?: string): WorkbenchRow {
15
+ return {
16
+ id, label, selected, options, select: (value) => apply(value as T), description,
17
+ value: options.find((option) => option.id === selected)?.label ?? selected,
18
+ adjust: (direction) => {
19
+ const index = options.findIndex((option) => option.id === selected);
20
+ apply(options[(index + direction + options.length) % options.length]!.id);
21
+ },
22
+ };
23
+ }
24
+
25
+ function toggle(id: string, label: string, value: boolean, apply: (value: boolean) => void, description?: string): WorkbenchRow {
26
+ return select(id, label, value ? "on" : "off", [
27
+ { id: "off", label: t("关闭") }, { id: "on", label: t("开启") },
28
+ ], (value) => apply(value === "on"), description);
29
+ }
30
+
31
+ export function providerFields(draft: ProviderDraft, isNewProvider: boolean, profiles: StateDocument["requestHeaderProfiles"], clearKey: () => Promise<void>, keyVisibility: { visible: boolean; toggle: () => void }): WorkbenchRow[] {
32
+ const basics = [
33
+ select("api", t("API 协议"), draft.api, getApiChoices(), (api) => switchProviderDraftApiPreset(draft, api), ui("切换协议会同步转换地址版本与默认认证变量;保存前不会发送请求。", "Switching updates the URL version and default auth variable; no request is sent before saving.")),
34
+ text("providerId", t("接入 ID(必填)"), draft.providerId, (value) => {
35
+ if (!/^[A-Za-z0-9._-]{1,48}$/.test(value)) throw new Error(t("接入 ID 只能包含字母、数字、点、下划线和连字符") + " · 1–48");
36
+ draft.providerId = value;
37
+ }),
38
+ text("providerName", t("名称"), draft.providerName, (value) => { draft.providerName = value; }),
39
+ { ...text("baseUrl", "Base URL", isNewProvider ? "" : draft.baseUrl, (value) => {
40
+ if (!value) return;
41
+ validateRequestBaseUrl(value);
42
+ draft.baseUrl = resolveProviderDraftBaseUrl(draft.api, value);
43
+ }), value: redactUrlForDisplay(draft.baseUrl) },
44
+ ].map((row) => ({ ...row, group: ui("基础连接", "Connection") }));
45
+ const profileChoices: Choice[] = [
46
+ ...getBuiltInProfileChoices(),
47
+ ...Object.entries(profiles).sort(([a], [b]) => a.localeCompare(b)).map(([id, profile]) => ({ id: `custom:${id}`, label: `${profile.name} (${id})` })),
48
+ ];
49
+ if (Object.keys(draft.customClientHeaders).length) profileChoices.push({ id: "inline", label: t("内联自定义请求头({count}项)", { count: Object.keys(draft.customClientHeaders).length }) });
50
+ const profileId = draft.clientHeaderProfile === "custom" ? (draft.requestHeaderProfileId ? `custom:${draft.requestHeaderProfileId}` : "inline") : draft.clientHeaderProfile;
51
+ const authentication: WorkbenchRow[] = [
52
+ {
53
+ id: "apiKey", label: "API key", value: keyVisibility.visible ? draft.apiKey || t("<未填写>") : maskSecret(draft.apiKey),
54
+ description: `${keyVisibility.visible ? `${draft.apiKey}\n` : ""}${ui("←→ 显示/隐藏 · Enter 输入新值替换,留空保留。支持明文、$ENV_VAR 和 !command;引用不会被执行。", "←→ show/hide · Enter replaces; empty keeps it. Supports literals, $ENV_VAR and !command; references are not evaluated.")}`,
55
+ adjust: () => keyVisibility.toggle(),
56
+ edit: { value: "", secret: true, apply: (value) => { if (value.trim()) draft.apiKey = value.trim(); } },
57
+ },
58
+ { id: "clear-key", label: ui("清除密钥", "Clear API key"), activate: clearKey },
59
+ select("authHeader", t("认证头"), draft.authHeader ? "bearer" : "default", [
60
+ { id: "default", label: t("默认"), description: t("默认 — 交给协议 SDK / 接入默认行为") },
61
+ { id: "bearer", label: "Bearer", description: t("Bearer — 强制 Authorization: Bearer <apiKey>") },
62
+ ], (value) => { draft.authHeader = value === "bearer"; }),
63
+ {
64
+ ...select("clientHeaderProfile", t("请求头"), profileId, profileChoices, (value) => {
65
+ if (value.startsWith("custom:")) { draft.clientHeaderProfile = "custom"; draft.requestHeaderProfileId = value.slice(7); }
66
+ else { draft.clientHeaderProfile = value === "inline" ? "custom" : value as ClientHeaderProfileId; delete draft.requestHeaderProfileId; }
67
+ }),
68
+ value: profileId === "inline" ? profileChoices.find((c) => c.id === "inline")?.label : describeProfile(draft.clientHeaderProfile, draft.api, draft.requestHeaderProfileId, profiles),
69
+ },
70
+ ];
71
+ const transport: WorkbenchRow[] = [
72
+ toggle("httpProxyEnabled", t("本机代理"), draft.httpProxyEnabled, (value) => {
73
+ draft.httpProxyEnabled = value;
74
+ if (value && !draft.httpProxyUrl.trim()) draft.httpProxyUrl = DEFAULT_PROVIDER_HTTP_PROXY_URL;
75
+ }, ui("仅影响当前接入;关闭时直连上游。", "Only this provider; disabled means direct connections.")),
76
+ { ...text("httpProxyUrl", t("代理地址"), "", (value) => {
77
+ if (!value) return;
78
+ if (draft.httpProxyEnabled) {
79
+ const url = new URL(value);
80
+ if (!["http:", "https:"].includes(url.protocol) || !url.hostname) throw new Error(t("代理地址目前只支持 http:// 或 https:// 代理"));
81
+ }
82
+ draft.httpProxyUrl = value;
83
+ }), value: redactUrlForDisplay(draft.httpProxyUrl), description: ui("输入新地址替换,留空保留;不回显已保存的代理凭据。", "Enter a replacement URL; empty keeps it. Stored proxy credentials are not shown.") },
84
+ ];
85
+ if (draft.api === "openai-completions") transport.push(select("openAIChatCompatibilityMode", t("协议兼容"), draft.openAIChatCompatibilityMode ?? "standard", [
86
+ { id: "standard", label: t("标准 · Pi 默认"), description: t("标准模式:保持 Pi 默认兼容判断。") },
87
+ { id: "compatible", label: t("兼容 · system"), description: t("兼容模式:系统提示词强制使用 system role,适合忽略 developer 的中转。") },
88
+ ], (value) => { draft.openAIChatCompatibilityMode = value; }));
89
+ if (draft.api === "openai-responses") transport.push(
90
+ select("openAIResponsesStreamCompletionMode", t("流结束兼容"), draft.openAIResponsesStreamCompletionMode ?? "standard", [
91
+ { id: "standard", label: t("标准 · 等待连接关闭"), description: t("标准模式:等待上游正常结束流。若回复完成后长期卡住,可启用兼容模式。") },
92
+ { id: "terminal-event", label: t("兼容 · 终态即结束"), description: t("兼容模式:正式终态事件已转交后主动结束,不等待上游关闭连接。") },
93
+ ], (value) => { draft.openAIResponsesStreamCompletionMode = value; }),
94
+ toggle("openAIResponsesAutoRecoveryEnabled", t("跨资源自动恢复"), draft.openAIResponsesAutoRecoveryEnabled ?? false, (value) => { draft.openAIResponsesAutoRecoveryEnabled = value; },
95
+ t("开启 — 仅在指定错误后剥离旧 item ID 并重试一次,保留思维链")),
96
+ );
97
+ return [...basics, ...authentication.map((row) => ({ ...row, group: ui("认证与请求头", "Authentication & headers") })), ...transport.map((row) => ({ ...row, group: ui("传输与兼容", "Transport & compatibility") }))];
98
+ }
99
+
100
+ export function modelFields(draft: ModelDraft, discover: () => Promise<void>): WorkbenchRow[] {
101
+ const rows: WorkbenchRow[] = [
102
+ text("modelId", t("模型 ID"), draft.modelId, (value) => { if (!value) throw new Error(t("模型 ID 不能为空")); draft.modelId = value; }),
103
+ { id: "fetch", label: t("上游模型列表"), value: ui("拉取并选择…", "Fetch and select…"), activate: discover, description: ui("最多 10 秒,Esc 取消;也可直接编辑模型 ID。", "Up to 10 seconds, Esc cancels; model IDs can also be entered manually.") },
104
+ text("modelName", t("显示名称"), draft.modelName, (value) => { draft.modelName = value; }, t("默认 = 模型 ID")),
105
+ toggle("visionInput", t("视觉支持"), draft.inputKinds.includes("image"), (value) => { draft.inputKinds = value ? ["text", "image"] : ["text"]; }),
106
+ toggle("reasoning", "Thinking", draft.reasoningMode === "enabled", (value) => { draft.reasoningMode = value ? "enabled" : "disabled"; }),
107
+ ];
108
+ if (draft.reasoningMode === "enabled" && draft.anthropicThinkingProtocol !== undefined) rows.push(select("anthropicThinkingProtocol", "Adaptive", draft.anthropicThinkingProtocol, [
109
+ { id: "legacy", label: t("关闭 · Legacy"), description: t("关闭:旧版接口,发送 thinking.type=enabled 和 budget_tokens") },
110
+ { id: "adaptive", label: t("开启 · 新版协议"), description: t("开启:新版模型,发送 thinking.type=adaptive 和 output_config.effort") },
111
+ ], (value) => { draft.anthropicThinkingProtocol = value; }));
112
+ if (draft.providerManaged && draft.api === "openai-responses") rows.push(select("openAIServiceTier", "Fast mode", draft.openAIServiceTier ?? "default", [
113
+ { id: "default", label: ui("标准", "Standard"), description: t("标准 — 不发送 service_tier") },
114
+ { id: "priority", label: "Fast", description: t("Fast — service_tier=priority,可能产生额外费用") },
115
+ { id: "ultrafast", label: "Ultrafast", description: t("Ultrafast — service_tier=ultrafast,需上游支持且可能产生额外费用") },
116
+ ], (value) => { draft.openAIServiceTier = value === "default" ? undefined : value; }));
117
+ for (const [id, label, presets] of [["contextWindow", t("上下文窗口"), CONTEXT_WINDOW_PRESETS], ["maxTokens", t("最大输出"), MAX_TOKENS_PRESETS]] as const) {
118
+ rows.push({ ...text(id, label, String(draft[id]), (value) => {
119
+ const parsed = parsePositiveIntegerWithUnit(value);
120
+ if (!Number.isSafeInteger(parsed) || parsed! <= 0) throw new Error(t("{label} 必须是正整数", { label }));
121
+ draft[id] = parsed!;
122
+ }, ui("←→ 调整预设;Enter 自定义,支持 K / M(十进制)。", "←→ presets; Enter for custom values, supports decimal K / M.")), adjust: (direction) => {
123
+ draft[id] = cycleNumericPreset(draft[id], presets, direction === -1 ? "left" : "right");
124
+ } });
125
+ }
126
+ return rows;
127
+ }
@@ -0,0 +1,80 @@
1
+ import { parseStringRecordJson } from "../common.ts";
2
+ import { t } from "../i18n.ts";
3
+ import { validateRequestHeaders } from "../state-document.ts";
4
+ import type { RequestHeaderProfileDraft } from "../types.ts";
5
+ import { ui, type WorkbenchRow } from "./workbench-types.ts";
6
+
7
+ export const NEW_HEADER_ROW = "header:new";
8
+ const rowId = (name: string) => `header:field:${name}`;
9
+
10
+ function checkedHeaders(headers: Record<string, string>): Record<string, string> {
11
+ const errors = validateRequestHeaders(headers);
12
+ if (errors.length) throw new Error(errors.join("\n"));
13
+ return headers;
14
+ }
15
+
16
+ export function headerJsonField(draft: RequestHeaderProfileDraft): WorkbenchRow {
17
+ return {
18
+ id: "headers-json", label: "Headers JSON",
19
+ edit: {
20
+ value: JSON.stringify(draft.headers, null, 2), multiline: true,
21
+ apply: (source) => { draft.headers = checkedHeaders(parseStringRecordJson(source, "Headers")); },
22
+ },
23
+ };
24
+ }
25
+
26
+ export function headerFields(draft: RequestHeaderProfileDraft, select: (id: string) => void): WorkbenchRow[] {
27
+ const fields: WorkbenchRow[] = [
28
+ { id: "profileName", label: ui("方案名称", "Profile name"), value: draft.profileName,
29
+ edit: { value: draft.profileName, apply: (value) => {
30
+ if (!value.trim()) throw new Error(t("请求头名称不能为空"));
31
+ draft.profileName = value.trim();
32
+ } } },
33
+ { id: "profileId", label: ui("方案 ID", "Profile ID"), value: draft.profileId,
34
+ description: ui("自动生成,可修改;接入通过此 ID 引用方案。", "Generated automatically; editable. Providers reference this ID."),
35
+ edit: { value: draft.profileId, apply: (value) => {
36
+ if (!value.trim()) throw new Error(t("请求头 ID 不能为空"));
37
+ if (!/^[A-Za-z0-9._-]+$/.test(value.trim())) throw new Error(t("请求头 ID 只能包含字母、数字、点、下划线和连字符"));
38
+ draft.profileId = value.trim();
39
+ } } },
40
+ ];
41
+ const entries = Object.entries(draft.headers);
42
+ for (const [index, [name, value]] of entries.entries()) {
43
+ fields.push({
44
+ id: rowId(name), label: name, value, group: index === 0 ? ui("请求头名称 / 值", "Header name / value") : undefined,
45
+ description: `${name}: ${value}\n${ui("Enter 编辑值 · Tab 切换名称和值", "Enter edits value · Tab switches name/value")}`,
46
+ pair: {
47
+ name, value, initial: "value",
48
+ apply: (newName, newValue) => {
49
+ newName = newName.trim();
50
+ if (entries.some(([existing]) => existing !== name && existing.toLowerCase() === newName.toLowerCase())) {
51
+ throw new Error(ui("请求头名称已存在:", "Header name already exists: ") + newName);
52
+ }
53
+ draft.headers = checkedHeaders(Object.fromEntries(entries.map(([key, current]) => key === name ? [newName, newValue] : [key, current])));
54
+ select(rowId(newName));
55
+ },
56
+ },
57
+ actions: [{ key: "d", label: ui("删除字段", "Delete field"), run: () => {
58
+ delete draft.headers[name];
59
+ select(entries[index + 1] ? rowId(entries[index + 1]![0]) : entries[index - 1] ? rowId(entries[index - 1]![0]) : NEW_HEADER_ROW);
60
+ } }],
61
+ });
62
+ }
63
+ fields.push({
64
+ id: NEW_HEADER_ROW, label: ui("+ 添加请求头", "+ Add header"), value: ui("名称 / 值", "Name / value"),
65
+ group: entries.length ? undefined : ui("请求头名称 / 值", "Header name / value"),
66
+ description: ui("自由填写请求头名称和值;API key 请放在接入的认证配置中。", "Enter a custom header name and value. Keep API keys in the provider credentials."),
67
+ pair: {
68
+ name: "", value: "", initial: "name",
69
+ apply: (name, value) => {
70
+ name = name.trim();
71
+ if (Object.keys(draft.headers).some((existing) => existing.toLowerCase() === name.toLowerCase())) {
72
+ throw new Error(ui("请求头名称已存在:", "Header name already exists: ") + name);
73
+ }
74
+ draft.headers = checkedHeaders(Object.fromEntries([...Object.entries(draft.headers), [name, value]]));
75
+ select(rowId(name));
76
+ },
77
+ },
78
+ });
79
+ return fields;
80
+ }
@@ -0,0 +1,67 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { getUiLanguage } from "../i18n.ts";
3
+
4
+ export function ui(zh: string, en: string): string {
5
+ return getUiLanguage() === "en" ? en : zh;
6
+ }
7
+
8
+ export interface Choice {
9
+ id: string;
10
+ label: string;
11
+ description?: string;
12
+ }
13
+
14
+ export interface WorkbenchRow {
15
+ id: string;
16
+ label: string;
17
+ value?: string;
18
+ group?: string;
19
+ description?: string;
20
+ searchText?: string;
21
+ format?: (width: number, theme: Theme) => string;
22
+ activate?: () => void | Promise<void>;
23
+ adjust?: (direction: -1 | 1) => void | Promise<void>;
24
+ actions?: WorkbenchAction[];
25
+ pair?: {
26
+ name: string;
27
+ value: string;
28
+ initial: "name" | "value";
29
+ apply: (name: string, value: string) => void;
30
+ };
31
+ options?: Choice[];
32
+ selected?: string;
33
+ select?: (id: string) => void | Promise<void>;
34
+ edit?: {
35
+ value: string;
36
+ multiline?: boolean;
37
+ secret?: boolean;
38
+ apply: (value: string) => void;
39
+ };
40
+ }
41
+
42
+ export interface WorkbenchAction {
43
+ label: string;
44
+ key: string;
45
+ requiresSelection?: boolean;
46
+ run: () => void | Promise<void>;
47
+ }
48
+
49
+ export interface WorkbenchPage {
50
+ id: string;
51
+ title: string;
52
+ summary?: string;
53
+ details?: string;
54
+ dirty?: boolean;
55
+ enterLabel?: string;
56
+ rows: WorkbenchRow[];
57
+ tableHeader?: (width: number) => string;
58
+ searchable?: boolean;
59
+ empty?: string;
60
+ actions: WorkbenchAction[];
61
+ save?: () => void | Promise<void>;
62
+ back: () => void | Promise<void>;
63
+ }
64
+
65
+ export interface WorkbenchView {
66
+ page: WorkbenchPage;
67
+ }