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.
@@ -5,9 +5,11 @@
5
5
 
6
6
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
7
  import { hasStringRecordEntries } from "../common.ts";
8
- import { findPresetForApi } from "../presets/providers.ts";
8
+ import { switchProviderDraftApiPreset } from "../presets/providers.ts";
9
+ import { redactUrlForDisplay } from "../sensitive-redaction.ts";
10
+ import { resolveRuntimeBaseUrl } from "../runtime-base-url.ts";
9
11
  import { DEFAULT_PROVIDER_HTTP_PROXY_URL } from "../types.ts";
10
- import { showPersistentFormMenu, padLabel, type HorizontalDirection, type MenuCursor } from "./persistent-menu.ts";
12
+ import { showOptionPicker, showPersistentFormMenu, padLabel, type MenuCursor } from "./persistent-menu.ts";
11
13
  import {
12
14
  API_CHOICES,
13
15
  BUILT_IN_PROFILE_CHOICES,
@@ -21,6 +23,8 @@ interface FieldRow {
21
23
  id: string;
22
24
  label: string;
23
25
  value: string;
26
+ // 开关类字段可用 ←→ 就地切换;其余字段需要 Enter 进入输入或选择器。
27
+ adjustable?: boolean;
24
28
  }
25
29
 
26
30
  function buildRows(
@@ -38,37 +42,20 @@ function buildRows(
38
42
  { id: "providerId", label: "接入 ID(必填)", value: draft.providerId || "<必填>" },
39
43
  { id: "providerName", label: "名称", value: draft.providerName || "<空>" },
40
44
  { id: "baseUrl", label: "Base URL", value: draft.baseUrl },
41
- { id: "httpProxyEnabled", label: "本机代理", value: draft.httpProxyEnabled ? "开启" : "关闭" },
42
- { id: "httpProxyUrl", label: "代理地址", value: draft.httpProxyEnabled ? (draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL) : "关闭时不使用" },
45
+ { id: "httpProxyEnabled", label: "本机代理", value: draft.httpProxyEnabled ? "开启" : "关闭", adjustable: true },
46
+ { id: "httpProxyUrl", label: "代理地址", value: draft.httpProxyEnabled ? redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL) : "关闭时不使用" },
43
47
  { id: "apiKey", label: "API key", value: maskSecret(draft.apiKey) },
44
48
  { id: "authHeader", label: "认证头", value: draft.authHeader ? "Bearer" : "默认" },
45
49
  { id: "clientHeaderProfile", label: "请求头", value: profileDisplay },
46
50
  ];
47
51
  }
48
52
 
49
- async function selectChoice<T extends { id: string; label: string }>(
50
- ctx: ExtensionCommandContext,
51
- title: string,
52
- choices: T[],
53
- currentId: string,
54
- ): Promise<T | undefined> {
55
- const labels = choices.map((c) => c.id === currentId ? `${c.label} ← 当前` : c.label);
56
- const picked = await ctx.ui.select(title, labels);
57
- if (!picked) return undefined;
58
- const index = labels.indexOf(picked);
59
- return index >= 0 ? choices[index] : undefined;
60
- }
61
53
 
62
- function cycleSwitchState(current: boolean, direction: HorizontalDirection): boolean {
63
- const states = [false, true];
64
- const currentIndex = current ? 1 : 0;
65
- const delta = direction === "right" ? 1 : -1;
66
- return states[(currentIndex + delta + states.length) % states.length]!;
67
- }
68
54
 
69
- function applyHorizontalToggle(draft: ProviderDraft, fieldId: string, direction: HorizontalDirection): boolean {
55
+ // 开关字段在两个方向上都是取反,因此不看 direction;返回是否真的切换了字段。
56
+ function applyHorizontalToggle(draft: ProviderDraft, fieldId: string): boolean {
70
57
  if (fieldId !== "httpProxyEnabled") return false;
71
- draft.httpProxyEnabled = cycleSwitchState(draft.httpProxyEnabled, direction);
58
+ draft.httpProxyEnabled = !draft.httpProxyEnabled;
72
59
  if (draft.httpProxyEnabled && !draft.httpProxyUrl.trim()) draft.httpProxyUrl = DEFAULT_PROVIDER_HTTP_PROXY_URL;
73
60
  return true;
74
61
  }
@@ -79,22 +66,18 @@ async function editClientHeaderProfile(
79
66
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
80
67
  ): Promise<void> {
81
68
  const choices = [
82
- ...BUILT_IN_PROFILE_CHOICES.map((choice) => ({
83
- id: choice.id,
84
- label: draft.clientHeaderProfile === choice.id ? `${choice.label} ← 当前` : choice.label,
85
- })),
69
+ ...BUILT_IN_PROFILE_CHOICES.map((choice) => ({ id: choice.id as string, label: choice.label })),
86
70
  ...Object.entries(requestHeaderProfiles)
87
71
  .sort(([a], [b]) => a.localeCompare(b))
88
72
  .map(([profileId, profile]) => ({
89
73
  id: `custom:${profileId}`,
90
- label: draft.clientHeaderProfile === "custom" && draft.requestHeaderProfileId === profileId
91
- ? `自定义:${profileId} — ${profile.name} ← 当前`
92
- : `自定义:${profileId} — ${profile.name}`,
74
+ label: `自定义:${profileId} — ${profile.name}`,
93
75
  })),
94
76
  ];
95
- const picked = await ctx.ui.select("请求头", choices.map((choice) => choice.label));
96
- if (!picked) return;
97
- const choice = choices.find((candidate) => candidate.label === picked);
77
+ const currentId = draft.clientHeaderProfile === "custom" && draft.requestHeaderProfileId
78
+ ? `custom:${draft.requestHeaderProfileId}`
79
+ : draft.clientHeaderProfile;
80
+ const choice = await showOptionPicker(ctx, "请求头", choices, currentId);
98
81
  if (!choice) return;
99
82
  if (choice.id.startsWith("custom:")) {
100
83
  draft.clientHeaderProfile = "custom";
@@ -112,20 +95,21 @@ async function editField(
112
95
  requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
113
96
  ): Promise<void> {
114
97
  if (fieldId === "api") {
115
- const choice = await selectChoice(ctx, "选择 API 协议", API_CHOICES, draft.api);
116
- if (choice) {
117
- draft.api = choice.id;
118
- const preset = findPresetForApi(draft.api);
119
- if (!draft.baseUrl.trim()) draft.baseUrl = preset.baseUrl;
120
- }
98
+ const choice = await showOptionPicker(ctx, "选择 API 协议", API_CHOICES, draft.api);
99
+ if (choice) switchProviderDraftApiPreset(draft, choice.id);
121
100
  return;
122
101
  }
123
102
  if (fieldId === "authHeader") {
124
- const choice = await ctx.ui.select("认证头(API key 放在哪里)", [
125
- "默认 — 交给协议 SDK / 接入默认行为",
126
- "Bearer — 强制 Authorization: Bearer <apiKey>",
127
- ]);
128
- if (choice) draft.authHeader = choice.startsWith("Bearer");
103
+ const choice = await showOptionPicker(
104
+ ctx,
105
+ "认证头(API key 放在哪里)",
106
+ [
107
+ { id: "default", label: "默认 — 交给协议 SDK / 接入默认行为" },
108
+ { id: "bearer", label: "Bearer — 强制 Authorization: Bearer <apiKey>" },
109
+ ],
110
+ draft.authHeader ? "bearer" : "default",
111
+ );
112
+ if (choice) draft.authHeader = choice.id === "bearer";
129
113
  return;
130
114
  }
131
115
  if (fieldId === "clientHeaderProfile") {
@@ -133,12 +117,17 @@ async function editField(
133
117
  return;
134
118
  }
135
119
  if (fieldId === "httpProxyEnabled") {
136
- const choice = await ctx.ui.select("本机代理(仅当前接入点)", [
137
- "关闭 — 请求直连上游",
138
- `开启 — 通过 ${draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL}`,
139
- ]);
120
+ const choice = await showOptionPicker(
121
+ ctx,
122
+ "本机代理(仅当前接入点)",
123
+ [
124
+ { id: "disabled", label: "关闭 — 请求直连上游" },
125
+ { id: "enabled", label: `开启 — 通过 ${redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL)}` },
126
+ ],
127
+ draft.httpProxyEnabled ? "enabled" : "disabled",
128
+ );
140
129
  if (!choice) return;
141
- draft.httpProxyEnabled = choice.startsWith("开启");
130
+ draft.httpProxyEnabled = choice.id === "enabled";
142
131
  if (draft.httpProxyEnabled && !draft.httpProxyUrl.trim()) draft.httpProxyUrl = DEFAULT_PROVIDER_HTTP_PROXY_URL;
143
132
  return;
144
133
  }
@@ -155,6 +144,12 @@ async function editField(
155
144
  if (value !== undefined) draft.providerName = value.trim();
156
145
  return;
157
146
  }
147
+ if (fieldId === "httpProxyUrl") {
148
+ const currentLabel = redactUrlForDisplay(draft.httpProxyUrl || DEFAULT_PROVIDER_HTTP_PROXY_URL);
149
+ const value = await ctx.ui.input(`代理地址(http/https;当前:${currentLabel},留空保持原值)`, "");
150
+ if (value?.trim()) draft.httpProxyUrl = value.trim();
151
+ return;
152
+ }
158
153
  if (fieldId === "apiKey") {
159
154
  const currentLabel = draft.apiKey ? maskSecret(draft.apiKey) : "<空>";
160
155
  const value = await ctx.ui.input(`API key(可选;明文 / $ENV_VAR / !command;当前:${currentLabel},留空清除)`, "");
@@ -162,17 +157,15 @@ async function editField(
162
157
  draft.apiKey = value.trim();
163
158
  return;
164
159
  }
165
- const prompt = ({
166
- baseUrl: "Base URL(http/https)",
167
- httpProxyUrl: "代理地址(http://host:port 或 https://host:port)",
168
- apiKey: "API key(可选;明文 / $ENV_VAR / !command)",
169
- } as Record<string, string>)[fieldId];
170
- const current = (draft as any)[fieldId] as string;
171
- const value = await ctx.ui.input(`${prompt ?? fieldId}(当前:${current || "<空>"},留空保持原值)`, current);
160
+ // [喵喵喵]: baseUrl 是唯一走通用文本输入的字段,显式列出才能保持 draft 的类型检查。
161
+ if (fieldId !== "baseUrl") return;
162
+ const value = await ctx.ui.input(`Base URL(http/https)(当前:${draft.baseUrl || "<空>"},留空保持原值)`, draft.baseUrl);
172
163
  if (value === undefined) return;
173
164
  const trimmed = value.trim();
174
165
  if (!trimmed) return;
175
- (draft as any)[fieldId] = trimmed;
166
+ // [喵喵喵]: 当场归一化成 SDK 可直接使用的根地址,让 models.json 存的就是最终请求地址;
167
+ // 否则插件未加载时 pi 会用未补全的值直接请求,补全结果也无法在界面上核对。
168
+ draft.baseUrl = resolveRuntimeBaseUrl(draft.api, trimmed);
176
169
  }
177
170
 
178
171
  export type ProviderEditOutcome =
@@ -187,11 +180,14 @@ export async function editProvider(
187
180
  ): Promise<ProviderEditOutcome> {
188
181
  const cursor: MenuCursor = { index: 0 };
189
182
  while (true) {
190
- const rows = buildRows(draft, requestHeaderProfiles);
191
- const menuRows = rows.map((r) => ({
192
- id: r.id,
193
- label: `${padLabel(r.label, 16)}${r.value}`,
183
+ // [喵喵喵]: 字段行的排版在开关切换后要原样重建,抽成函数避免两处写法飘移。
184
+ const toMenuRows = (fieldRows: FieldRow[]) => fieldRows.map((row) => ({
185
+ id: row.id,
186
+ label: `${padLabel(row.label, 16)}${row.value}`,
187
+ adjustable: row.adjustable,
194
188
  }));
189
+ const rows = buildRows(draft, requestHeaderProfiles);
190
+ const menuRows = toMenuRows(rows);
195
191
  const action = await showPersistentFormMenu(
196
192
  ctx,
197
193
  titlePrefix,
@@ -199,21 +195,26 @@ export async function editProvider(
199
195
  menuRows,
200
196
  cursor,
201
197
  {
202
- adjustableRowIds: ["httpProxyEnabled"],
203
198
  summaryLines: [
204
199
  `API ${formatApiShort(draft.api)} · 请求头 ${describeProfile(draft.clientHeaderProfile, draft.api, draft.requestHeaderProfileId, requestHeaderProfiles)}`,
205
200
  "接入 ID 必填,且不能与已有或 pi 内置接入重复",
206
201
  "Ctrl+S 保存并同步 models.json;不切换当前会话模型",
207
202
  ],
208
- footer: "↑↓ 选择 ←→ 切换选项 Enter 编辑 Ctrl+S 保存并同步 Esc 返回",
203
+ onAdjust: (id) => {
204
+ if (!applyHorizontalToggle(draft, id)) return undefined;
205
+ return toMenuRows(buildRows(draft, requestHeaderProfiles));
206
+ },
207
+ hints: [
208
+ { key: "↑↓", label: "选择" },
209
+ { key: "←→", label: "切换选项" },
210
+ { key: "Enter", label: "编辑" },
211
+ { key: "Ctrl+S", label: "保存并同步" },
212
+ { key: "Esc", label: "返回" },
213
+ ],
209
214
  },
210
215
  );
211
216
  if (action.type === "cancel") return { action: "cancel" };
212
217
  if (action.type === "save") return { action: "save", draft };
213
- if (action.type === "adjust") {
214
- applyHorizontalToggle(draft, action.id, action.direction);
215
- continue;
216
- }
217
218
  await editField(ctx, draft, action.id, requestHeaderProfiles);
218
219
  }
219
220
  }
@@ -3,7 +3,7 @@
3
3
  // 管理可复用的客户端请求头。接入编辑器只选择已存在的请求头,
4
4
  // 不在模型内部新增一次性 JSON,避免配置分散。
5
5
 
6
- import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
6
+ import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
7
7
  import { formatUnknownError, parseStringRecordJson } from "../common.ts";
8
8
  import { deleteRequestHeaderProfileConfiguration, saveRequestHeaderProfileConfiguration } from "../header-profile-mutations.ts";
9
9
  import { CLAUDE_CODE_CLIENT_HEADERS, CODEX_CLI_CLIENT_HEADERS } from "../presets/builtin-client-headers.ts";
@@ -14,12 +14,16 @@ import {
14
14
  validateRequestHeaderProfileDraft,
15
15
  } from "../state-document.ts";
16
16
  import { readState } from "../state-store.ts";
17
- import type { RequestHeaderProfileDraft, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
17
+ import type { RequestHeaderProfileDraft, StateDocument, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
18
18
  import { padLabel, showPersistentFormMenu, showPersistentShortcutMenu, type MenuCursor } from "./persistent-menu.ts";
19
+ import { fitColumn, formatDetailField, formatDetailTitle } from "./ui-helpers.ts";
19
20
 
20
21
  interface ProfileRow {
21
22
  profileId: string;
22
23
  label: string;
24
+ searchText: string;
25
+ // [喵喵喵]: 引用计数要遍历全部 Provider,每帧重算浪费;构造行时算一次即可。
26
+ usedCount: number;
23
27
  }
24
28
 
25
29
  interface FieldRow {
@@ -56,8 +60,13 @@ const HEADER_TEMPLATES: HeaderTemplate[] = [
56
60
  },
57
61
  ];
58
62
 
59
- function buildRows(profileIds: string[]): ProfileRow[] {
60
- return profileIds.map((profileId) => ({ profileId, label: "" }));
63
+ function buildProfileRows(document: StateDocument, profileIds: string[]): ProfileRow[] {
64
+ return profileIds.map((profileId) => {
65
+ const profile = document.requestHeaderProfiles[profileId]!;
66
+ const usedCount = countModelsUsingRequestHeaderProfile(document, profileId);
67
+ const label = formatProfileRow(profileId, profile, usedCount);
68
+ return { profileId, label, usedCount, searchText: `${profileId} ${profile.name} ${label}` };
69
+ });
61
70
  }
62
71
 
63
72
  function formatCapturedAt(capturedAt: string): string {
@@ -69,19 +78,71 @@ function formatCaptureLine(label: string, capture: StoredClientHeaderCapture | u
69
78
  return ` ${padLabel(label, 12)} 已抓包 ${formatCapturedAt(capture.capturedAt)} · ${Object.keys(capture.headers).length} headers`;
70
79
  }
71
80
 
72
- function formatProfileRow(profileId: string, profile: StoredRequestHeaderProfile, usedCount: number): string {
73
- return `${padLabel(profileId, 22)} ${padLabel(`${Object.keys(profile.headers).length} headers`, 12)} ${padLabel(`${usedCount} models`, 10)} ${profile.name}`.trimEnd();
81
+ interface ProfileTableCells {
82
+ profileId: string;
83
+ headers: string;
84
+ used: string;
85
+ name: string;
86
+ }
87
+
88
+ function formatProfileTableRow(cells: ProfileTableCells, availableWidth: number): string {
89
+ if (availableWidth >= 64) {
90
+ return [
91
+ fitColumn(cells.profileId, 22),
92
+ fitColumn(cells.headers, 12),
93
+ fitColumn(cells.used, 10),
94
+ fitColumn(cells.name, Math.max(10, availableWidth - 47)),
95
+ ].join(" ");
96
+ }
97
+ if (availableWidth >= 46) {
98
+ return [fitColumn(cells.profileId, 22), fitColumn(cells.headers, 12), fitColumn(cells.used, 10)].join(" ");
99
+ }
100
+ if (availableWidth >= 33) {
101
+ return [fitColumn(cells.profileId, 20), fitColumn(cells.headers, 12)].join(" ");
102
+ }
103
+ return [
104
+ fitColumn(cells.profileId, Math.max(8, availableWidth - 11)),
105
+ fitColumn(cells.headers, 10),
106
+ ].join(" ");
107
+ }
108
+
109
+ function formatProfileRow(
110
+ profileId: string,
111
+ profile: StoredRequestHeaderProfile,
112
+ usedCount: number,
113
+ availableWidth = 78,
114
+ ): string {
115
+ return formatProfileTableRow({
116
+ profileId,
117
+ headers: `${Object.keys(profile.headers).length} headers`,
118
+ used: `${usedCount} models`,
119
+ name: profile.name,
120
+ }, availableWidth);
121
+ }
122
+
123
+ function formatProfileTableHeader(menuWidth: number): string {
124
+ return ` ${formatProfileTableRow({
125
+ profileId: "自定义 ID",
126
+ headers: "Headers",
127
+ used: "Used",
128
+ name: "名称",
129
+ }, Math.max(0, menuWidth - 2))}`;
74
130
  }
75
131
 
76
- function formatProfileDetailLines(profileId: string, profile: StoredRequestHeaderProfile, usedCount: number): string[] {
132
+ function formatProfileDetailLines(
133
+ profileId: string,
134
+ profile: StoredRequestHeaderProfile,
135
+ usedCount: number,
136
+ theme?: Theme,
137
+ ): string[] {
77
138
  const headerNames = Object.keys(profile.headers);
78
139
  const preview = headerNames.length > 0
79
140
  ? headerNames.slice(0, 6).join(", ") + (headerNames.length > 6 ? ", ..." : "")
80
141
  : "<empty>";
81
142
  return [
82
- `${profile.name} (${profileId})`,
83
- ` usage ${usedCount} models`,
84
- ` headers ${preview}`,
143
+ formatDetailTitle(`${profile.name} (${profileId})`, theme),
144
+ formatDetailField("usage", `${usedCount} models`, theme),
145
+ formatDetailField("headers", preview, theme),
85
146
  ];
86
147
  }
87
148
 
@@ -177,7 +238,12 @@ async function editProfile(
177
238
  summaryLines: [
178
239
  "认证类敏感 header 会被拒绝;API key 请放在接入配置中",
179
240
  ],
180
- footer: "↑↓ 选择 Enter 编辑 Ctrl+S 保存并同步 Esc 返回",
241
+ hints: [
242
+ { key: "↑↓", label: "选择" },
243
+ { key: "Enter", label: "编辑" },
244
+ { key: "Ctrl+S", label: "保存并同步" },
245
+ { key: "Esc", label: "返回" },
246
+ ],
181
247
  },
182
248
  );
183
249
  if (action.type === "cancel") return { action: "cancel" };
@@ -248,19 +314,12 @@ export async function runHeaderProfilesPanel(pi: ExtensionAPI, ctx: ExtensionCom
248
314
  while (true) {
249
315
  const state = await readState();
250
316
  const profileIds = Object.keys(state.requestHeaderProfiles).sort((a, b) => a.localeCompare(b));
251
- const rows = buildRows(profileIds).map((row) => {
252
- const profile = state.requestHeaderProfiles[row.profileId]!;
253
- const usedCount = countModelsUsingRequestHeaderProfile(state, row.profileId);
254
- return {
255
- ...row,
256
- label: formatProfileRow(row.profileId, profile, usedCount),
257
- };
258
- });
317
+ const rows = buildProfileRows(state, profileIds);
259
318
  const action = await showPersistentShortcutMenu<HeaderProfileShortcut>(
260
319
  ctx,
261
320
  "/model-manager / 请求头",
262
321
  "",
263
- rows.map((row, index) => ({ id: `${index}`, label: row.label })),
322
+ rows.map((row, index) => ({ id: `${index}`, label: row.label, searchText: row.searchText })),
264
323
  cursor,
265
324
  [
266
325
  { input: "n", shortcut: "new-profile" },
@@ -273,15 +332,28 @@ export async function runHeaderProfilesPanel(pi: ExtensionAPI, ctx: ExtensionCom
273
332
  formatCaptureLine("Codex", state.clientHeaderCaptures["codex-cli"]),
274
333
  `Custom profiles: ${rows.length}`,
275
334
  ],
276
- tableHeader: `${padLabel("自定义 ID", 22)} ${padLabel("Headers", 12)} ${padLabel("Used", 10)} 名称`,
277
- getDetailLines: (selectedRow) => {
335
+ tableHeader: formatProfileTableHeader,
336
+ formatRow: (menuRow, width) => {
337
+ const row = rows[Number.parseInt(menuRow.id, 10)];
338
+ const profile = row ? state.requestHeaderProfiles[row.profileId] : undefined;
339
+ return row && profile
340
+ ? formatProfileRow(row.profileId, profile, row.usedCount, width)
341
+ : menuRow.label;
342
+ },
343
+ getDetailLines: (selectedRow, theme) => {
278
344
  const row = rows[Number.parseInt(selectedRow?.id ?? "", 10)];
279
345
  const profile = row ? state.requestHeaderProfiles[row.profileId] : undefined;
280
346
  return row && profile
281
- ? formatProfileDetailLines(row.profileId, profile, countModelsUsingRequestHeaderProfile(state, row.profileId))
347
+ ? formatProfileDetailLines(row.profileId, profile, row.usedCount, theme)
282
348
  : [];
283
349
  },
284
- footer: "↑↓ 选择 Enter 编辑请求头 n 新建自定义 d 删除 Esc 返回",
350
+ hints: [
351
+ { key: "↑↓", label: "选择" },
352
+ { key: "Enter", label: "编辑请求头" },
353
+ { key: "N", label: "新建自定义" },
354
+ { key: "D", label: "删除" },
355
+ { key: "Esc", label: "返回" },
356
+ ],
285
357
  emptyLabel: "暂无自定义请求头;按 n 新建",
286
358
  },
287
359
  );