pi-auto-web-search 0.1.1
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/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +195 -0
- package/README_EN.md +195 -0
- package/extensions/web-search.ts +18 -0
- package/package.json +56 -0
- package/src/adapters/anysearch.ts +107 -0
- package/src/adapters/cloudflare.ts +139 -0
- package/src/adapters/deepseek.ts +108 -0
- package/src/adapters/exa.ts +161 -0
- package/src/adapters/firecrawl.ts +202 -0
- package/src/adapters/index.ts +22 -0
- package/src/adapters/tavily.ts +148 -0
- package/src/adapters/tencent.ts +172 -0
- package/src/adapters/types.ts +122 -0
- package/src/adapters/util.ts +93 -0
- package/src/adapters/xai.ts +176 -0
- package/src/base-url.ts +40 -0
- package/src/cloudflare-oauth.ts +551 -0
- package/src/config.ts +547 -0
- package/src/http.ts +777 -0
- package/src/key-pool.ts +144 -0
- package/src/key-quota.ts +532 -0
- package/src/presets.ts +129 -0
- package/src/search-service.ts +411 -0
- package/src/secrets.ts +78 -0
- package/src/settings-ui.ts +1279 -0
- package/src/tools.ts +928 -0
|
@@ -0,0 +1,1279 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import type { ExtensionCommandContext, KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Container, hyperlink, Input, Spacer, Text, type Component, type TUI } from "@earendil-works/pi-tui";
|
|
4
|
+
import { DEFAULT_XAI_MODEL } from "./adapters/xai.ts";
|
|
5
|
+
import {
|
|
6
|
+
callableInstance,
|
|
7
|
+
type ConfigFile,
|
|
8
|
+
type ConfigStore,
|
|
9
|
+
type InstanceMode,
|
|
10
|
+
type LoadedConfig,
|
|
11
|
+
type ResolveConfigOptions,
|
|
12
|
+
type ResolvedInstance,
|
|
13
|
+
} from "./config.ts";
|
|
14
|
+
import {
|
|
15
|
+
parseAuthorizationCode,
|
|
16
|
+
type LoginResult,
|
|
17
|
+
type LogoutResult,
|
|
18
|
+
type OAuthToken,
|
|
19
|
+
} from "./cloudflare-oauth.ts";
|
|
20
|
+
import { maskKey, type KeyState } from "./key-pool.ts";
|
|
21
|
+
import {
|
|
22
|
+
formatInstanceQuotaSummary,
|
|
23
|
+
formatQuotaPeriod,
|
|
24
|
+
formatResetTime,
|
|
25
|
+
parseQuotaPeriod,
|
|
26
|
+
type UsageStore,
|
|
27
|
+
} from "./key-quota.ts";
|
|
28
|
+
import { isPresetId, PRESETS, type PresetId } from "./presets.ts";
|
|
29
|
+
import { resolveSecret, secretVariables } from "./secrets.ts";
|
|
30
|
+
|
|
31
|
+
/** 面板用到的 Cloudflare OAuth 能力,由 CloudflareOAuth 实现。 */
|
|
32
|
+
export interface PanelOAuth {
|
|
33
|
+
loadToken(): OAuthToken | undefined;
|
|
34
|
+
beginLogin(): { authorizeUrl: string; state: string; expiresAt: number };
|
|
35
|
+
completeLogin(code: string, state: string): Promise<LoginResult>;
|
|
36
|
+
logout(): Promise<LogoutResult>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 面板用到的服务能力,由 SearchService 实现。 */
|
|
40
|
+
export interface PanelService {
|
|
41
|
+
search(request: { query: string; limit?: number; instance?: string }): Promise<{
|
|
42
|
+
instance: string;
|
|
43
|
+
providerUsed: string;
|
|
44
|
+
degraded: boolean;
|
|
45
|
+
results: readonly { title: string; url: string }[];
|
|
46
|
+
}>;
|
|
47
|
+
extract(request: { url: string; instance?: string }): Promise<{
|
|
48
|
+
url: string;
|
|
49
|
+
title?: string;
|
|
50
|
+
content: string;
|
|
51
|
+
instance: string;
|
|
52
|
+
providerUsed: string;
|
|
53
|
+
degraded: boolean;
|
|
54
|
+
}>;
|
|
55
|
+
poolState(instanceId: string): KeyState[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 面板用到的运行期状态,由 SearchRuntime 实现。 */
|
|
59
|
+
export interface PanelSource {
|
|
60
|
+
readonly configPath: string;
|
|
61
|
+
readonly env: NodeJS.ProcessEnv;
|
|
62
|
+
readonly store: ConfigStore;
|
|
63
|
+
readonly usage?: UsageStore;
|
|
64
|
+
snapshot(): { config: LoadedConfig; service: PanelService };
|
|
65
|
+
/** 配置写入后丢弃缓存,让下一次 snapshot 重新解析。 */
|
|
66
|
+
reload(): void;
|
|
67
|
+
recordFailure(instance: string, message: string): void;
|
|
68
|
+
clearFailure(instance: string): void;
|
|
69
|
+
lastFailure(instance: string): string | undefined;
|
|
70
|
+
cloudflareOAuth?(config?: LoadedConfig): PanelOAuth;
|
|
71
|
+
resolveOptions?(): ResolveConfigOptions;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface PanelOptions {
|
|
75
|
+
source: PanelSource;
|
|
76
|
+
env?: NodeJS.ProcessEnv;
|
|
77
|
+
/** 失败翻译,由调用方注入,避免面板与工具层互相依赖。 */
|
|
78
|
+
failureText?: (error: unknown, configPath: string) => string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 面板行的固定文案,集中一处便于测试引用的同时保持改词只改一处。 */
|
|
82
|
+
export const PANEL_CHOICES = {
|
|
83
|
+
create: "+ 新建实例",
|
|
84
|
+
exit: "退出",
|
|
85
|
+
edit: "编辑",
|
|
86
|
+
test: "测试连接",
|
|
87
|
+
remove: "删除",
|
|
88
|
+
back: "返回",
|
|
89
|
+
keys: "管理凭据",
|
|
90
|
+
keyAdd: "+ 添加凭据",
|
|
91
|
+
keyRemove: "- 移除凭据",
|
|
92
|
+
keyReplace: "替换全部凭据",
|
|
93
|
+
keyReplacePool: "替换网关凭据",
|
|
94
|
+
keyClear: "清空全部凭据",
|
|
95
|
+
keysDone: "完成,继续下一步",
|
|
96
|
+
keysAddMore: "+ 继续添加下一组凭据",
|
|
97
|
+
keyQuota: "调用限额(按密钥)",
|
|
98
|
+
quotaLimit: "修改单密钥限额次数",
|
|
99
|
+
quotaPeriod: "修改重置周期",
|
|
100
|
+
quotaUsage: "查看各密钥用量与校准",
|
|
101
|
+
quotaDisable: "关闭单密钥限额",
|
|
102
|
+
quotaRestoreDefault: "恢复默认限额",
|
|
103
|
+
quotaResetKey: "清零当前周期已用次数",
|
|
104
|
+
quotaCalibrateKey: "手动设置已用次数",
|
|
105
|
+
model: "修改模型(model)",
|
|
106
|
+
baseUrl: "修改 baseUrl",
|
|
107
|
+
accountId: "修改 accountId",
|
|
108
|
+
xSearch: "x_search 开关",
|
|
109
|
+
xSearchOn: "开启",
|
|
110
|
+
xSearchOff: "关闭",
|
|
111
|
+
enabled: "启用或禁用",
|
|
112
|
+
enable: "启用",
|
|
113
|
+
disable: "禁用",
|
|
114
|
+
cfAuthOAuth: "Cloudflare OAuth 浏览器授权登录(推荐,自动回填 Account ID)",
|
|
115
|
+
cfAuthApiToken: "手动填写 API Token",
|
|
116
|
+
cfOAuthLogin: "Cloudflare OAuth 登录",
|
|
117
|
+
cfOAuthRelogin: "重新登录 Cloudflare OAuth",
|
|
118
|
+
cfOAuthLogout: "退出 Cloudflare OAuth",
|
|
119
|
+
} as const;
|
|
120
|
+
|
|
121
|
+
const PANEL_TITLE = "搜索实例";
|
|
122
|
+
|
|
123
|
+
const TEST_QUERY = "pi coding agent";
|
|
124
|
+
|
|
125
|
+
const TEST_FETCH_URL = "https://example.com/";
|
|
126
|
+
|
|
127
|
+
const MODES: readonly InstanceMode[] = ["sdk", "pool", "proxy"];
|
|
128
|
+
|
|
129
|
+
/** 新建实例时凭证输入框的占位提示,只给变量名,不预填真实值。 */
|
|
130
|
+
const KEY_PLACEHOLDER: Readonly<Record<PresetId, string>> = {
|
|
131
|
+
tavily: "${TAVILY_API_KEY}",
|
|
132
|
+
exa: "${EXA_API_KEY}",
|
|
133
|
+
firecrawl: "${FIRECRAWL_API_KEY}",
|
|
134
|
+
deepseek: "${DEEPSEEK_API_KEY}",
|
|
135
|
+
xai: "${XAI_API_KEY}",
|
|
136
|
+
cloudflare: "${CF_API_TOKEN}",
|
|
137
|
+
anysearch: "anysearch 可匿名,留空即可",
|
|
138
|
+
tencent: "${TENCENTCLOUD_WSA_APIKEY}",
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** 面板里显示的一行。 */
|
|
142
|
+
export interface InstanceRow {
|
|
143
|
+
id: string;
|
|
144
|
+
/** 一行摘要,凭证已打码。 */
|
|
145
|
+
label: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
interface Deps {
|
|
149
|
+
source: PanelSource;
|
|
150
|
+
env: NodeJS.ProcessEnv;
|
|
151
|
+
failureText: (error: unknown, configPath: string) => string;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
type PanelState =
|
|
155
|
+
| { ok: true; config: LoadedConfig; service: PanelService }
|
|
156
|
+
| { ok: false; error: string };
|
|
157
|
+
|
|
158
|
+
type WriteResult = { ok: true; config: LoadedConfig } | { ok: false; error: string };
|
|
159
|
+
|
|
160
|
+
/** 凭证展示:变量引用只显示变量名,字面量只留前四位。 */
|
|
161
|
+
export function maskedKey(key: string): string {
|
|
162
|
+
return secretVariables(key).length > 0 ? key : maskKey(key);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 面板列表:每个实例一行,带状态、打码后的凭证、冷却与上次错误。 */
|
|
166
|
+
export function instanceRows(
|
|
167
|
+
source: PanelSource,
|
|
168
|
+
config: LoadedConfig,
|
|
169
|
+
service?: PanelService,
|
|
170
|
+
): InstanceRow[] {
|
|
171
|
+
return config.instances.map((instance) => ({
|
|
172
|
+
id: instance.id,
|
|
173
|
+
label: rowLabel(source, instance, service),
|
|
174
|
+
}));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** /search 无参数时打开面板:列出实例、新建、编辑、删除、测试连接。 */
|
|
178
|
+
export async function openSearchPanel(
|
|
179
|
+
ctx: ExtensionCommandContext,
|
|
180
|
+
options: PanelOptions,
|
|
181
|
+
): Promise<void> {
|
|
182
|
+
const deps: Deps = {
|
|
183
|
+
source: options.source,
|
|
184
|
+
env: options.env ?? options.source.env,
|
|
185
|
+
failureText: options.failureText ?? ((error) => messageOf(error)),
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
for (;;) {
|
|
189
|
+
const loaded = loadPanel(deps.source);
|
|
190
|
+
if (!loaded.ok) {
|
|
191
|
+
ctx.ui.notify(`读取配置失败:${loaded.error}`, "error");
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const rows = instanceRows(deps.source, loaded.config, loaded.service);
|
|
196
|
+
const title = `${PANEL_TITLE}(${deps.source.configPath})`;
|
|
197
|
+
const choices = [...rows.map((row) => row.label), PANEL_CHOICES.create, PANEL_CHOICES.exit];
|
|
198
|
+
const choice = await ctx.ui.select(title, choices);
|
|
199
|
+
if (choice === undefined || choice === PANEL_CHOICES.exit) return;
|
|
200
|
+
if (choice === PANEL_CHOICES.create) {
|
|
201
|
+
await createInstance(ctx, deps);
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const row = rows.find((item) => item.label === choice);
|
|
206
|
+
if (row) await manageInstance(ctx, deps, row.id);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function rowLabel(source: PanelSource, instance: ResolvedInstance, service?: PanelService): string {
|
|
211
|
+
const parts: string[] = [instance.id, instance.preset.id, instance.mode, stateOf(instance)];
|
|
212
|
+
|
|
213
|
+
const masked = instance.keys.map(maskedKey);
|
|
214
|
+
if (masked.length > 0) {
|
|
215
|
+
parts.push(`凭证 ${masked.join(", ")}`);
|
|
216
|
+
} else if (isCloudflareOAuthInstance(instance) && source.cloudflareOAuth?.().loadToken()) {
|
|
217
|
+
parts.push("OAuth 已登录");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const quota = formatInstanceQuotaSummary(source.usage, instance, source.env);
|
|
221
|
+
if (quota) parts.push(quota);
|
|
222
|
+
|
|
223
|
+
const cooling = service?.poolState(instance.id).filter((state) => state.cooling) ?? [];
|
|
224
|
+
if (cooling.length > 0) {
|
|
225
|
+
const seconds = Math.max(...cooling.map((state) => state.cooldownSecondsLeft));
|
|
226
|
+
parts.push(`冷却中 ${seconds}s`);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const lastError = source.lastFailure(instance.id);
|
|
230
|
+
if (lastError) parts.push(`上次错误 ${clip(lastError, 40)}`);
|
|
231
|
+
|
|
232
|
+
return parts.join(" · ");
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** 状态词:已禁用、已配置、未配置(附上警告里的变量名)。 */
|
|
236
|
+
function stateOf(instance: ResolvedInstance): string {
|
|
237
|
+
if (!instance.enabled) return "已禁用";
|
|
238
|
+
if (callableInstance(instance)) return "已配置";
|
|
239
|
+
const reason = instance.warnings.join(";");
|
|
240
|
+
return reason ? `未配置(${reason})` : "未配置";
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function manageInstance(ctx: ExtensionCommandContext, deps: Deps, id: string): Promise<void> {
|
|
244
|
+
const loaded = loadPanel(deps.source);
|
|
245
|
+
const instance = loaded.ok ? loaded.config.instances.find((item) => item.id === id) : undefined;
|
|
246
|
+
const actions: string[] = [];
|
|
247
|
+
if (instance && instance.preset.id === "cloudflare" && instance.mode === "sdk" && deps.source.cloudflareOAuth) {
|
|
248
|
+
const loggedIn = deps.source.cloudflareOAuth(loaded.ok ? loaded.config : undefined).loadToken() !== undefined;
|
|
249
|
+
actions.push(loggedIn ? PANEL_CHOICES.cfOAuthRelogin : PANEL_CHOICES.cfOAuthLogin);
|
|
250
|
+
if (loggedIn) actions.push(PANEL_CHOICES.cfOAuthLogout);
|
|
251
|
+
}
|
|
252
|
+
actions.push(PANEL_CHOICES.edit, PANEL_CHOICES.test, PANEL_CHOICES.remove, PANEL_CHOICES.back);
|
|
253
|
+
|
|
254
|
+
const action = await ctx.ui.select(`实例 ${id}`, actions);
|
|
255
|
+
if (action === PANEL_CHOICES.cfOAuthLogin || action === PANEL_CHOICES.cfOAuthRelogin) {
|
|
256
|
+
await runCloudflareLogin(ctx, deps);
|
|
257
|
+
} else if (action === PANEL_CHOICES.cfOAuthLogout) {
|
|
258
|
+
await runCloudflareLogout(ctx, deps);
|
|
259
|
+
} else if (action === PANEL_CHOICES.edit) {
|
|
260
|
+
await editInstance(ctx, deps, id);
|
|
261
|
+
} else if (action === PANEL_CHOICES.test) {
|
|
262
|
+
await testInstance(ctx, deps, id);
|
|
263
|
+
} else if (action === PANEL_CHOICES.remove) {
|
|
264
|
+
await removeInstance(ctx, deps, id);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** 三步新建:供应商 → 接入模式 → 凭据与相关字段。 */
|
|
269
|
+
async function createInstance(ctx: ExtensionCommandContext, deps: Deps): Promise<void> {
|
|
270
|
+
const presetId = await choosePreset(ctx);
|
|
271
|
+
if (presetId === undefined) return;
|
|
272
|
+
|
|
273
|
+
const mode = await chooseMode(ctx);
|
|
274
|
+
if (mode === undefined) return;
|
|
275
|
+
|
|
276
|
+
const preset = PRESETS[presetId];
|
|
277
|
+
const rawId = await ctx.ui.input(
|
|
278
|
+
`实例名称(直接回车自动生成 ${presetId}-随机后缀;按 Esc 取消)`,
|
|
279
|
+
"",
|
|
280
|
+
);
|
|
281
|
+
if (rawId === undefined) return;
|
|
282
|
+
const id = rawId.trim() || randomInstanceId(presetId, instanceIds(deps.source));
|
|
283
|
+
|
|
284
|
+
// Cloudflare sdk 模式支持浏览器 OAuth 登录,先让用户选认证方式,避免直接落进空白密钥输入框。
|
|
285
|
+
let useCloudflareOAuth = false;
|
|
286
|
+
if (presetId === "cloudflare" && mode === "sdk" && deps.source.cloudflareOAuth) {
|
|
287
|
+
const authMethod = await ctx.ui.select("Cloudflare 认证方式", [
|
|
288
|
+
PANEL_CHOICES.cfAuthOAuth,
|
|
289
|
+
PANEL_CHOICES.cfAuthApiToken,
|
|
290
|
+
]);
|
|
291
|
+
if (authMethod === undefined) return;
|
|
292
|
+
useCloudflareOAuth = authMethod === PANEL_CHOICES.cfAuthOAuth;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
let keys: string[] = [];
|
|
296
|
+
if (!useCloudflareOAuth) {
|
|
297
|
+
const collected = await collectCredentials(ctx, presetId, mode);
|
|
298
|
+
if (collected === undefined) return;
|
|
299
|
+
keys = collected;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
let model: string | undefined;
|
|
303
|
+
if (presetId === "xai") {
|
|
304
|
+
const rawModel = await ctx.ui.input(
|
|
305
|
+
`xAI 模型名(留空使用默认 ${DEFAULT_XAI_MODEL},例如 grok-4.7)`,
|
|
306
|
+
DEFAULT_XAI_MODEL,
|
|
307
|
+
);
|
|
308
|
+
if (rawModel === undefined) return;
|
|
309
|
+
model = rawModel.trim() || undefined;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
let baseUrl: string | undefined;
|
|
313
|
+
if (mode !== "sdk") {
|
|
314
|
+
baseUrl = (await ctx.ui.input(baseUrlPrompt(presetId, "create", mode), preset.baseUrl))?.trim();
|
|
315
|
+
if (!baseUrl) return;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
let accountId: string | undefined;
|
|
319
|
+
if (preset.requiresAccountId && !useCloudflareOAuth) {
|
|
320
|
+
accountId = (await ctx.ui.input(
|
|
321
|
+
"Cloudflare Account ID(支持 ${CF_ACCOUNT_ID};留空可在 OAuth 登录后自动回填)",
|
|
322
|
+
"${CF_ACCOUNT_ID}",
|
|
323
|
+
))?.trim();
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const draft: Record<string, unknown> = { id, preset: presetId, mode, keys };
|
|
327
|
+
if (model) draft.model = model;
|
|
328
|
+
if (baseUrl) draft.baseUrl = baseUrl;
|
|
329
|
+
if (accountId) draft.accountId = accountId;
|
|
330
|
+
|
|
331
|
+
const result = write(deps, (file) => {
|
|
332
|
+
instanceList(file).push(draft);
|
|
333
|
+
});
|
|
334
|
+
if (!result.ok) {
|
|
335
|
+
ctx.ui.notify(`未写入:${result.error}。原文件未改动。`, "error");
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (useCloudflareOAuth) {
|
|
340
|
+
await runCloudflareLogin(ctx, deps);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const created = result.config.instances.find((instance) => instance.id === id);
|
|
345
|
+
ctx.ui.notify(createdSummary(created), "info");
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async function editInstance(ctx: ExtensionCommandContext, deps: Deps, id: string): Promise<void> {
|
|
349
|
+
const loaded = loadPanel(deps.source);
|
|
350
|
+
if (!loaded.ok) {
|
|
351
|
+
ctx.ui.notify(`读取配置失败:${loaded.error}`, "error");
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
const instance = loaded.config.instances.find((item) => item.id === id);
|
|
355
|
+
if (instance === undefined) return;
|
|
356
|
+
|
|
357
|
+
const masked = instance.keys.map(maskedKey).join(", ") || (isCloudflareOAuthInstance(instance) ? "OAuth" : "无");
|
|
358
|
+
const fields = [
|
|
359
|
+
PANEL_CHOICES.keys,
|
|
360
|
+
PANEL_CHOICES.keyQuota,
|
|
361
|
+
PANEL_CHOICES.baseUrl,
|
|
362
|
+
...(instance.preset.requiresAccountId ? [PANEL_CHOICES.accountId] : []),
|
|
363
|
+
...(instance.preset.id === "xai" ? [PANEL_CHOICES.model, PANEL_CHOICES.xSearch] : []),
|
|
364
|
+
PANEL_CHOICES.enabled,
|
|
365
|
+
PANEL_CHOICES.back,
|
|
366
|
+
];
|
|
367
|
+
const field = await ctx.ui.select(`实例 ${id} · 凭证 ${masked}`, fields);
|
|
368
|
+
if (field === undefined || field === PANEL_CHOICES.back) return;
|
|
369
|
+
|
|
370
|
+
if (field === PANEL_CHOICES.keys) {
|
|
371
|
+
await manageKeys(ctx, deps, id);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
if (field === PANEL_CHOICES.keyQuota) {
|
|
376
|
+
await manageKeyQuota(ctx, deps, id);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (field === PANEL_CHOICES.model) {
|
|
381
|
+
const current = instance.model ?? `${DEFAULT_XAI_MODEL}(默认)`;
|
|
382
|
+
const text = await ctx.ui.input(
|
|
383
|
+
`xAI 模型名(当前:${current};留空恢复默认 ${DEFAULT_XAI_MODEL})`,
|
|
384
|
+
instance.model ?? DEFAULT_XAI_MODEL,
|
|
385
|
+
);
|
|
386
|
+
if (text === undefined) return;
|
|
387
|
+
commit(ctx, deps, `已更新 ${id} 的模型`, (file) => {
|
|
388
|
+
const raw = rawInstance(file, id);
|
|
389
|
+
const value = text.trim();
|
|
390
|
+
if (value) raw.model = value;
|
|
391
|
+
else delete raw.model;
|
|
392
|
+
});
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
if (field === PANEL_CHOICES.baseUrl) {
|
|
397
|
+
const text = await ctx.ui.input(
|
|
398
|
+
baseUrlPrompt(instance.preset.id, "edit", instance.mode, instance.baseUrl),
|
|
399
|
+
instance.baseUrl,
|
|
400
|
+
);
|
|
401
|
+
if (text === undefined) return;
|
|
402
|
+
commit(ctx, deps, `已更新 ${id} 的 baseUrl`, (file) => {
|
|
403
|
+
const raw = rawInstance(file, id);
|
|
404
|
+
const value = text.trim();
|
|
405
|
+
if (value) raw.baseUrl = value;
|
|
406
|
+
else delete raw.baseUrl;
|
|
407
|
+
});
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
if (field === PANEL_CHOICES.accountId) {
|
|
412
|
+
const text = await ctx.ui.input("新 accountId(留空表示待回填)", instance.accountId ?? "${CF_ACCOUNT_ID}");
|
|
413
|
+
if (text === undefined) return;
|
|
414
|
+
commit(ctx, deps, `已更新 ${id} 的 accountId`, (file) => {
|
|
415
|
+
const raw = rawInstance(file, id);
|
|
416
|
+
const value = text.trim();
|
|
417
|
+
if (value) raw.accountId = value;
|
|
418
|
+
else delete raw.accountId;
|
|
419
|
+
});
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
if (field === PANEL_CHOICES.xSearch) {
|
|
424
|
+
const current = instance.xSearch ? "开启" : "关闭";
|
|
425
|
+
const choice = await ctx.ui.select(`实例 ${id} x_search 当前${current}`, [
|
|
426
|
+
PANEL_CHOICES.xSearchOn,
|
|
427
|
+
PANEL_CHOICES.xSearchOff,
|
|
428
|
+
]);
|
|
429
|
+
if (choice === undefined) return;
|
|
430
|
+
commit(ctx, deps, `已更新 ${id} 的 x_search 开关`, (file) => {
|
|
431
|
+
rawInstance(file, id).xSearch = choice === PANEL_CHOICES.xSearchOn;
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
if (field === PANEL_CHOICES.enabled) {
|
|
436
|
+
const current = instance.enabled ? "已启用" : "已禁用";
|
|
437
|
+
const choice = await ctx.ui.select(`实例 ${id} 当前${current}`, [
|
|
438
|
+
PANEL_CHOICES.enable,
|
|
439
|
+
PANEL_CHOICES.disable,
|
|
440
|
+
]);
|
|
441
|
+
if (choice === undefined) return;
|
|
442
|
+
commit(ctx, deps, `已更新 ${id} 的启用状态`, (file) => {
|
|
443
|
+
rawInstance(file, id).enabled = choice === PANEL_CHOICES.enable;
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
async function removeInstance(ctx: ExtensionCommandContext, deps: Deps, id: string): Promise<void> {
|
|
449
|
+
const confirmed = await ctx.ui.confirm(
|
|
450
|
+
`删除实例 ${id}?`,
|
|
451
|
+
"会从配置里移除该实例,以及它在搜索链、抓取链上的引用。",
|
|
452
|
+
);
|
|
453
|
+
if (!confirmed) return;
|
|
454
|
+
|
|
455
|
+
const result = write(deps, (file) => removeInstanceFrom(file, id));
|
|
456
|
+
if (!result.ok) {
|
|
457
|
+
ctx.ui.notify(`未写入:${result.error}。原文件未改动。`, "error");
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
const remaining = result.config.instances.length;
|
|
461
|
+
ctx.ui.notify(remaining === 0 ? `已删除 ${id},配置里没有实例了` : `已删除 ${id}`, "info");
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function testInstance(ctx: ExtensionCommandContext, deps: Deps, id: string): Promise<void> {
|
|
465
|
+
const loaded = loadPanel(deps.source);
|
|
466
|
+
if (!loaded.ok) {
|
|
467
|
+
ctx.ui.notify(`读取配置失败:${loaded.error}`, "error");
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const instance = loaded.config.instances.find((item) => item.id === id);
|
|
471
|
+
if (instance === undefined) return;
|
|
472
|
+
|
|
473
|
+
if (!callableInstance(instance)) {
|
|
474
|
+
const reason = instance.warnings.join(";") || "已禁用";
|
|
475
|
+
ctx.ui.notify(`无法测试 ${id}:${reason}`, "warning");
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const started = Date.now();
|
|
480
|
+
try {
|
|
481
|
+
const { service } = deps.source.snapshot();
|
|
482
|
+
if (instance.preset.id === "cloudflare") {
|
|
483
|
+
const response = await service.extract({ url: TEST_FETCH_URL, instance: id });
|
|
484
|
+
deps.source.clearFailure(id);
|
|
485
|
+
const degraded = response.degraded ? ",已降级" : "";
|
|
486
|
+
const lines = [
|
|
487
|
+
`连接正常:${response.instance}(${response.providerUsed})`,
|
|
488
|
+
`抓取 ${TEST_FETCH_URL} 返回 ${response.content.length} 字符,耗时 ${formatDuration(Date.now() - started)}${degraded}`,
|
|
489
|
+
];
|
|
490
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
const response = await service.search({
|
|
494
|
+
query: TEST_QUERY,
|
|
495
|
+
limit: 3,
|
|
496
|
+
instance: id,
|
|
497
|
+
});
|
|
498
|
+
deps.source.clearFailure(id);
|
|
499
|
+
const degraded = response.degraded ? ",已降级" : "";
|
|
500
|
+
const lines = [
|
|
501
|
+
`连接正常:${response.instance}(${response.providerUsed})`,
|
|
502
|
+
`返回 ${response.results.length} 条,耗时 ${formatDuration(Date.now() - started)}${degraded}`,
|
|
503
|
+
];
|
|
504
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
505
|
+
} catch (error) {
|
|
506
|
+
deps.source.recordFailure(id, messageOf(error));
|
|
507
|
+
ctx.ui.notify(`连接失败:${deps.failureText(error, deps.source.configPath)}`, "error");
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function loadPanel(source: PanelSource): PanelState {
|
|
512
|
+
try {
|
|
513
|
+
const { config, service } = source.snapshot();
|
|
514
|
+
return { ok: true, config, service };
|
|
515
|
+
} catch (error) {
|
|
516
|
+
return { ok: false, error: messageOf(error) };
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** 复用 ConfigStore 的原子写、JSONC 保留与并发保护;失败时原文件不被改动。 */
|
|
521
|
+
function write(deps: Deps, mutate: (file: ConfigFile) => void): WriteResult {
|
|
522
|
+
try {
|
|
523
|
+
const config = deps.source.store.update(mutate, deps.env, deps.source.resolveOptions?.());
|
|
524
|
+
deps.source.reload();
|
|
525
|
+
return { ok: true, config };
|
|
526
|
+
} catch (error) {
|
|
527
|
+
return { ok: false, error: messageOf(error) };
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** 写入后给出结果;非法输入或写入失败时说明原文件未改动。 */
|
|
532
|
+
function commit(
|
|
533
|
+
ctx: ExtensionCommandContext,
|
|
534
|
+
deps: Deps,
|
|
535
|
+
done: string,
|
|
536
|
+
mutate: (file: ConfigFile) => void,
|
|
537
|
+
): boolean {
|
|
538
|
+
const result = write(deps, mutate);
|
|
539
|
+
if (!result.ok) {
|
|
540
|
+
ctx.ui.notify(`未写入:${result.error}。原文件未改动。`, "error");
|
|
541
|
+
return false;
|
|
542
|
+
}
|
|
543
|
+
if (done) ctx.ui.notify(done, "info");
|
|
544
|
+
return true;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/** 新建后的提示:缺什么就提示变量名,不把未配置当成失败。 */
|
|
548
|
+
function createdSummary(instance: ResolvedInstance | undefined): string {
|
|
549
|
+
if (!instance) return "已写入配置";
|
|
550
|
+
const quotaNote = instance.keyQuota
|
|
551
|
+
? `;单密钥限额 ${instance.keyQuota.limit} 次/${formatQuotaPeriod(instance.keyQuota.period)}(可在编辑页调整)`
|
|
552
|
+
: "";
|
|
553
|
+
if (callableInstance(instance)) return `已创建 ${instance.id},可以调用${quotaNote}`;
|
|
554
|
+
const reason = instance.warnings.join(";") || "凭证待填写";
|
|
555
|
+
return `已创建 ${instance.id}。${reason}${quotaNote}`;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
async function choosePreset(ctx: ExtensionCommandContext): Promise<PresetId | undefined> {
|
|
559
|
+
const ids = Object.keys(PRESETS);
|
|
560
|
+
const choice = await ctx.ui.select("供应商", ids);
|
|
561
|
+
return choice !== undefined && isPresetId(choice) ? choice : undefined;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
async function chooseMode(ctx: ExtensionCommandContext): Promise<InstanceMode | undefined> {
|
|
565
|
+
const choice = await ctx.ui.select(
|
|
566
|
+
"接入模式(sdk 直连官方;pool 上游密钥池需 baseUrl;proxy 自定义代理需 baseUrl)",
|
|
567
|
+
[...MODES],
|
|
568
|
+
);
|
|
569
|
+
const mode = MODES.find((item) => item === choice);
|
|
570
|
+
return mode;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** 随机生成实例 id:供应商名加 4 位随机十六进制后缀,避免碰撞已有实例。 */
|
|
574
|
+
function randomInstanceId(presetId: PresetId, used: readonly string[]): string {
|
|
575
|
+
const taken = new Set(used);
|
|
576
|
+
for (let attempt = 0; attempt < 32; attempt += 1) {
|
|
577
|
+
const candidate = `${presetId}-${randomBytes(2).toString("hex")}`;
|
|
578
|
+
if (!taken.has(candidate)) return candidate;
|
|
579
|
+
}
|
|
580
|
+
let index = 1;
|
|
581
|
+
while (taken.has(`${presetId}-${index}`)) index += 1;
|
|
582
|
+
return `${presetId}-${index}`;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function instanceIds(source: PanelSource): string[] {
|
|
586
|
+
const loaded = loadPanel(source);
|
|
587
|
+
return loaded.ok ? loaded.config.instances.map((instance) => instance.id) : [];
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** 各供应商 baseUrl 需要填写到的路径层级说明;与 base-url.ts 的 canonicalBase/joinUrl 一致。 */
|
|
591
|
+
const BASE_URL_GUIDE: Readonly<Record<PresetId, string>> = {
|
|
592
|
+
tavily: "只需填到域名或反代前缀(如 https://proxy.example.com),不要包含 /search 或 /extract",
|
|
593
|
+
exa: "只需填到域名或反代前缀(如 https://proxy.example.com),不要包含 /search 或 /contents",
|
|
594
|
+
firecrawl: "只需填到域名或反代前缀(如 https://proxy.example.com),结尾 /v2 会自动处理,不要包含 /search 或 /scrape",
|
|
595
|
+
deepseek: "只需填到域名或反代前缀(如 https://proxy.example.com),结尾 /v1 会自动处理,不要包含 /tools/search",
|
|
596
|
+
xai: "只需填到域名或反代前缀(如 https://proxy.example.com 或 .../v1),结尾 /v1 会自动处理,不要包含 /responses",
|
|
597
|
+
cloudflare: "只需填到域名或 /client 前缀(如 https://proxy.example.com/client,结尾 /v4 会自动处理),不要包含 /accounts/...",
|
|
598
|
+
anysearch: "只需填到域名或反代前缀(如 https://proxy.example.com),结尾 /v1 会自动处理,不要包含 /search",
|
|
599
|
+
tencent: "只需填到域名或反代前缀(如 https://api.wsa.cloud.tencent.com),不要包含 /SearchPro",
|
|
600
|
+
};
|
|
601
|
+
|
|
602
|
+
function baseUrlPrompt(
|
|
603
|
+
presetId: PresetId,
|
|
604
|
+
kind: "create" | "edit",
|
|
605
|
+
mode: InstanceMode,
|
|
606
|
+
currentBaseUrl?: string,
|
|
607
|
+
): string {
|
|
608
|
+
const preset = PRESETS[presetId];
|
|
609
|
+
const guide = BASE_URL_GUIDE[presetId];
|
|
610
|
+
if (kind === "create") {
|
|
611
|
+
return `baseUrl(${mode} 模式必填;官方默认:${preset.baseUrl})\n${guide}`;
|
|
612
|
+
}
|
|
613
|
+
const tail = mode === "sdk" ? `留空恢复官方默认 ${preset.baseUrl}` : `${mode} 模式必填`;
|
|
614
|
+
return `新 baseUrl(当前:${currentBaseUrl ?? preset.baseUrl};${tail})\n${guide}`;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function isCloudflareOAuthInstance(instance: ResolvedInstance): boolean {
|
|
618
|
+
return instance.preset.id === "cloudflare"
|
|
619
|
+
&& instance.mode === "sdk"
|
|
620
|
+
&& instance.auth.type === "bearer"
|
|
621
|
+
&& instance.keys.length === 0;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** 新建时采集凭证:pool 模式只填单个网关密钥,sdk/proxy 支持逗号批量或逐组连续添加。 */
|
|
625
|
+
async function collectCredentials(
|
|
626
|
+
ctx: ExtensionCommandContext,
|
|
627
|
+
presetId: PresetId,
|
|
628
|
+
mode: InstanceMode,
|
|
629
|
+
): Promise<string[] | undefined> {
|
|
630
|
+
const first = await ctx.ui.input(
|
|
631
|
+
createCredentialPrompt(presetId, mode, 1),
|
|
632
|
+
KEY_PLACEHOLDER[presetId],
|
|
633
|
+
);
|
|
634
|
+
if (first === undefined) return undefined;
|
|
635
|
+
const keys = uniqueKeys(splitKeys(first));
|
|
636
|
+
if (mode === "pool" || keys.length === 0) return keys;
|
|
637
|
+
|
|
638
|
+
for (;;) {
|
|
639
|
+
const summary = keys.map(maskedKey).join(", ");
|
|
640
|
+
const next = await ctx.ui.select(
|
|
641
|
+
`已添加 ${keys.length} 组凭证(${summary}),${mode} 模式支持多密钥轮换`,
|
|
642
|
+
[PANEL_CHOICES.keysDone, PANEL_CHOICES.keysAddMore],
|
|
643
|
+
);
|
|
644
|
+
if (next === undefined) return undefined;
|
|
645
|
+
if (next === PANEL_CHOICES.keysDone) return keys;
|
|
646
|
+
|
|
647
|
+
const extra = await ctx.ui.input(
|
|
648
|
+
createCredentialPrompt(presetId, mode, keys.length + 1),
|
|
649
|
+
KEY_PLACEHOLDER[presetId],
|
|
650
|
+
);
|
|
651
|
+
if (extra === undefined) return undefined;
|
|
652
|
+
const added = splitKeys(extra);
|
|
653
|
+
if (added.length === 0) return keys;
|
|
654
|
+
for (const key of added) {
|
|
655
|
+
if (!keys.includes(key)) keys.push(key);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** 编辑页凭据管理:sdk/proxy 支持添加、逐条移除、替换与清空;pool 模式支持替换与清空。 */
|
|
661
|
+
async function manageKeys(ctx: ExtensionCommandContext, deps: Deps, id: string): Promise<void> {
|
|
662
|
+
for (;;) {
|
|
663
|
+
const loaded = loadPanel(deps.source);
|
|
664
|
+
if (!loaded.ok) {
|
|
665
|
+
ctx.ui.notify(`读取配置失败:${loaded.error}`, "error");
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
const instance = loaded.config.instances.find((item) => item.id === id);
|
|
669
|
+
if (instance === undefined) return;
|
|
670
|
+
|
|
671
|
+
const maskedList = instance.keys.map(maskedKey).join(", ") || "无";
|
|
672
|
+
const title = `实例 ${id} 凭据管理(共 ${instance.keys.length} 组:${maskedList})`;
|
|
673
|
+
const actions = instance.mode === "pool"
|
|
674
|
+
? [
|
|
675
|
+
PANEL_CHOICES.keyReplacePool,
|
|
676
|
+
...(instance.keys.length > 0 ? [PANEL_CHOICES.keyClear] : []),
|
|
677
|
+
PANEL_CHOICES.back,
|
|
678
|
+
]
|
|
679
|
+
: [
|
|
680
|
+
PANEL_CHOICES.keyAdd,
|
|
681
|
+
...(instance.keys.length > 0 ? [PANEL_CHOICES.keyRemove] : []),
|
|
682
|
+
PANEL_CHOICES.keyReplace,
|
|
683
|
+
...(instance.keys.length > 0 ? [PANEL_CHOICES.keyClear] : []),
|
|
684
|
+
PANEL_CHOICES.back,
|
|
685
|
+
];
|
|
686
|
+
|
|
687
|
+
const action = await ctx.ui.select(title, actions);
|
|
688
|
+
if (action === undefined || action === PANEL_CHOICES.back) return;
|
|
689
|
+
|
|
690
|
+
if (action === PANEL_CHOICES.keyAdd) {
|
|
691
|
+
const text = await ctx.ui.input(
|
|
692
|
+
addCredentialPrompt(instance.preset.id),
|
|
693
|
+
KEY_PLACEHOLDER[instance.preset.id],
|
|
694
|
+
);
|
|
695
|
+
if (text === undefined) continue;
|
|
696
|
+
const added = splitKeys(text);
|
|
697
|
+
if (added.length === 0) continue;
|
|
698
|
+
let count = 0;
|
|
699
|
+
let total = instance.keys.length;
|
|
700
|
+
const saved = commit(ctx, deps, "", (file) => {
|
|
701
|
+
const raw = rawInstance(file, id);
|
|
702
|
+
const current = Array.isArray(raw.keys)
|
|
703
|
+
? raw.keys.filter((item): item is string => typeof item === "string")
|
|
704
|
+
: [];
|
|
705
|
+
for (const key of added) {
|
|
706
|
+
if (!current.includes(key)) {
|
|
707
|
+
current.push(key);
|
|
708
|
+
count += 1;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
raw.keys = current;
|
|
712
|
+
total = current.length;
|
|
713
|
+
});
|
|
714
|
+
if (!saved) continue;
|
|
715
|
+
if (count > 0) ctx.ui.notify(`已添加 ${count} 组凭证(当前共 ${total} 组)`, "info");
|
|
716
|
+
else ctx.ui.notify("输入的凭证已存在,未重复添加", "info");
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
if (action === PANEL_CHOICES.keyRemove) {
|
|
721
|
+
const items = instance.keys.map((key, index) => `#${index + 1} ${maskedKey(key)}`);
|
|
722
|
+
const picked = await ctx.ui.select(`选择要从 ${id} 移除的凭证`, [...items, PANEL_CHOICES.back]);
|
|
723
|
+
if (picked === undefined || picked === PANEL_CHOICES.back) continue;
|
|
724
|
+
const index = items.indexOf(picked);
|
|
725
|
+
if (index < 0) continue;
|
|
726
|
+
const remaining = instance.keys.length - 1;
|
|
727
|
+
commit(ctx, deps, `已移除第 ${index + 1} 组凭证(剩余 ${remaining} 组)`, (file) => {
|
|
728
|
+
const raw = rawInstance(file, id);
|
|
729
|
+
const current = Array.isArray(raw.keys)
|
|
730
|
+
? raw.keys.filter((item): item is string => typeof item === "string")
|
|
731
|
+
: [];
|
|
732
|
+
current.splice(index, 1);
|
|
733
|
+
raw.keys = current;
|
|
734
|
+
});
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
if (action === PANEL_CHOICES.keyReplace || action === PANEL_CHOICES.keyReplacePool) {
|
|
739
|
+
const text = await ctx.ui.input(
|
|
740
|
+
editCredentialPrompt(instance.preset.id, maskedList, instance.mode),
|
|
741
|
+
KEY_PLACEHOLDER[instance.preset.id],
|
|
742
|
+
);
|
|
743
|
+
if (text === undefined) continue;
|
|
744
|
+
commit(ctx, deps, `已更新 ${id} 的凭证`, (file) => {
|
|
745
|
+
rawInstance(file, id).keys = uniqueKeys(splitKeys(text));
|
|
746
|
+
});
|
|
747
|
+
continue;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
if (action === PANEL_CHOICES.keyClear) {
|
|
751
|
+
commit(ctx, deps, `已清空 ${id} 的全部凭证`, (file) => {
|
|
752
|
+
rawInstance(file, id).keys = [];
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/** 编辑页按密钥调用限额管理:设置单密钥上限、自定义轮转周期、查看或校准用量。 */
|
|
759
|
+
async function manageKeyQuota(ctx: ExtensionCommandContext, deps: Deps, id: string): Promise<void> {
|
|
760
|
+
for (;;) {
|
|
761
|
+
const loaded = loadPanel(deps.source);
|
|
762
|
+
if (!loaded.ok) {
|
|
763
|
+
ctx.ui.notify(`读取配置失败:${loaded.error}`, "error");
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
const instance = loaded.config.instances.find((item) => item.id === id);
|
|
767
|
+
if (instance === undefined) return;
|
|
768
|
+
|
|
769
|
+
const raw = findRawInstance(loaded.config.file, id);
|
|
770
|
+
const quota = instance.keyQuota;
|
|
771
|
+
const defaultQuota = instance.preset.defaultKeyQuota;
|
|
772
|
+
const ruleLabel = quota
|
|
773
|
+
? `单密钥 ${quota.limit} 次/${formatQuotaPeriod(quota.period)}`
|
|
774
|
+
: defaultQuota
|
|
775
|
+
? "已关闭(已覆盖默认限额)"
|
|
776
|
+
: "未启用";
|
|
777
|
+
const usageSummary = formatInstanceQuotaSummary(deps.source.usage, instance, deps.env);
|
|
778
|
+
const title = usageSummary
|
|
779
|
+
? `实例 ${id} 调用限额(${ruleLabel} · ${usageSummary})`
|
|
780
|
+
: `实例 ${id} 调用限额(${ruleLabel})`;
|
|
781
|
+
|
|
782
|
+
const actions: string[] = [PANEL_CHOICES.quotaLimit];
|
|
783
|
+
if (quota) actions.push(PANEL_CHOICES.quotaPeriod);
|
|
784
|
+
if (quota && deps.source.usage && instance.keys.length > 0) actions.push(PANEL_CHOICES.quotaUsage);
|
|
785
|
+
if (quota) actions.push(PANEL_CHOICES.quotaDisable);
|
|
786
|
+
if (defaultQuota && raw?.keyQuota !== undefined) actions.push(PANEL_CHOICES.quotaRestoreDefault);
|
|
787
|
+
actions.push(PANEL_CHOICES.back);
|
|
788
|
+
|
|
789
|
+
const action = await ctx.ui.select(title, actions);
|
|
790
|
+
if (action === undefined || action === PANEL_CHOICES.back) return;
|
|
791
|
+
|
|
792
|
+
if (action === PANEL_CHOICES.quotaLimit) {
|
|
793
|
+
const current = quota ? String(quota.limit) : "未启用";
|
|
794
|
+
const defaultPeriod = quota?.period ?? defaultQuota?.period ?? "month";
|
|
795
|
+
const text = await ctx.ui.input(
|
|
796
|
+
`单密钥每周期最大调用次数(正整数;当前:${current},周期:${formatQuotaPeriod(defaultPeriod)})`,
|
|
797
|
+
String(quota?.limit ?? defaultQuota?.limit ?? 2000),
|
|
798
|
+
);
|
|
799
|
+
if (text === undefined || !text.trim()) continue;
|
|
800
|
+
const parsed = Number(text.trim());
|
|
801
|
+
if (!Number.isInteger(parsed) || parsed < 1) {
|
|
802
|
+
ctx.ui.notify("限额次数必须是不小于 1 的整数", "error");
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
commit(ctx, deps, `已更新 ${id} 单密钥限额为 ${parsed} 次/${formatQuotaPeriod(defaultPeriod)}`, (file) => {
|
|
806
|
+
rawInstance(file, id).keyQuota = { limit: parsed, period: defaultPeriod };
|
|
807
|
+
});
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
if (action === PANEL_CHOICES.quotaPeriod && quota) {
|
|
812
|
+
const text = await ctx.ui.input(
|
|
813
|
+
`重置周期(当前:${quota.period} / ${formatQuotaPeriod(quota.period)})\n`
|
|
814
|
+
+ "自然周期:month(自然月,默认)、week(自然周)、day(自然日)、year(自然年)\n"
|
|
815
|
+
+ "自定义时长:24h、7d、30d、2w 等",
|
|
816
|
+
quota.period,
|
|
817
|
+
);
|
|
818
|
+
if (text === undefined || !text.trim()) continue;
|
|
819
|
+
const parsed = parseQuotaPeriod(text);
|
|
820
|
+
if (!parsed) {
|
|
821
|
+
ctx.ui.notify("不支持的周期(支持 day、week、month、year,或 24h、7d、30d、2w 等)", "error");
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
commit(ctx, deps, `已更新 ${id} 重置周期为 ${formatQuotaPeriod(parsed.canonical)}(${parsed.canonical})`, (file) => {
|
|
825
|
+
rawInstance(file, id).keyQuota = { limit: quota.limit, period: parsed.canonical };
|
|
826
|
+
});
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
if (action === PANEL_CHOICES.quotaUsage && quota && deps.source.usage) {
|
|
831
|
+
await manageQuotaUsage(ctx, deps, instance, quota);
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
if (action === PANEL_CHOICES.quotaDisable) {
|
|
836
|
+
commit(ctx, deps, `已关闭 ${id} 的单密钥调用限额`, (file) => {
|
|
837
|
+
const target = rawInstance(file, id);
|
|
838
|
+
if (defaultQuota) target.keyQuota = false;
|
|
839
|
+
else delete target.keyQuota;
|
|
840
|
+
});
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
if (action === PANEL_CHOICES.quotaRestoreDefault && defaultQuota) {
|
|
845
|
+
commit(
|
|
846
|
+
ctx,
|
|
847
|
+
deps,
|
|
848
|
+
`已恢复 ${id} 的默认限额(${defaultQuota.limit} 次/${formatQuotaPeriod(defaultQuota.period)})`,
|
|
849
|
+
(file) => {
|
|
850
|
+
delete rawInstance(file, id).keyQuota;
|
|
851
|
+
},
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
async function manageQuotaUsage(
|
|
858
|
+
ctx: ExtensionCommandContext,
|
|
859
|
+
deps: Deps,
|
|
860
|
+
instance: ResolvedInstance,
|
|
861
|
+
quota: NonNullable<ResolvedInstance["keyQuota"]>,
|
|
862
|
+
): Promise<void> {
|
|
863
|
+
const usage = deps.source.usage;
|
|
864
|
+
if (!usage) return;
|
|
865
|
+
const rawKeys = instance.mode === "pool" ? instance.keys.slice(0, 1) : instance.keys;
|
|
866
|
+
|
|
867
|
+
for (;;) {
|
|
868
|
+
const entries = rawKeys.map((rawKey, index) => {
|
|
869
|
+
const resolved = resolveSecret(rawKey, deps.env);
|
|
870
|
+
const masked = maskedKey(rawKey);
|
|
871
|
+
if (!resolved) {
|
|
872
|
+
return {
|
|
873
|
+
rawKey,
|
|
874
|
+
resolved: undefined as string | undefined,
|
|
875
|
+
masked,
|
|
876
|
+
label: `#${index + 1} ${masked} · 环境变量未设置`,
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
let detail: string;
|
|
880
|
+
try {
|
|
881
|
+
const snap = usage.snapshotOne(instance.preset.id, resolved, quota);
|
|
882
|
+
const resetText = snap.windowEnd === undefined ? "" : `,重置 ${formatResetTime(snap.windowEnd)}`;
|
|
883
|
+
detail = `已用 ${snap.used}/${snap.limit}(剩余 ${snap.remaining}${resetText})`;
|
|
884
|
+
} catch (error) {
|
|
885
|
+
detail = `用量读取失败:${messageOf(error)}`;
|
|
886
|
+
}
|
|
887
|
+
return {
|
|
888
|
+
rawKey,
|
|
889
|
+
resolved,
|
|
890
|
+
masked,
|
|
891
|
+
label: `#${index + 1} ${masked} · ${detail}`,
|
|
892
|
+
};
|
|
893
|
+
});
|
|
894
|
+
|
|
895
|
+
const picked = await ctx.ui.select(
|
|
896
|
+
`实例 ${instance.id} 各密钥用量(周期:${formatQuotaPeriod(quota.period)})`,
|
|
897
|
+
[...entries.map((entry) => entry.label), PANEL_CHOICES.back],
|
|
898
|
+
);
|
|
899
|
+
if (picked === undefined || picked === PANEL_CHOICES.back) return;
|
|
900
|
+
|
|
901
|
+
const entry = entries.find((item) => item.label === picked);
|
|
902
|
+
if (!entry) continue;
|
|
903
|
+
if (!entry.resolved) {
|
|
904
|
+
ctx.ui.notify("该凭证对应的环境变量未设置,无法调整用量", "warning");
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
const action = await ctx.ui.select(`密钥 ${entry.masked}`, [
|
|
909
|
+
PANEL_CHOICES.quotaCalibrateKey,
|
|
910
|
+
PANEL_CHOICES.quotaResetKey,
|
|
911
|
+
PANEL_CHOICES.back,
|
|
912
|
+
]);
|
|
913
|
+
if (action === undefined || action === PANEL_CHOICES.back) continue;
|
|
914
|
+
|
|
915
|
+
if (action === PANEL_CHOICES.quotaResetKey) {
|
|
916
|
+
try {
|
|
917
|
+
usage.setUsage(instance.preset.id, entry.resolved, quota, 0);
|
|
918
|
+
ctx.ui.notify(`已清零 ${entry.masked} 在当前周期的已用次数`, "info");
|
|
919
|
+
} catch (error) {
|
|
920
|
+
ctx.ui.notify(`写入用量失败:${messageOf(error)}`, "error");
|
|
921
|
+
}
|
|
922
|
+
continue;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
if (action === PANEL_CHOICES.quotaCalibrateKey) {
|
|
926
|
+
let current = 0;
|
|
927
|
+
try {
|
|
928
|
+
current = usage.snapshotOne(instance.preset.id, entry.resolved, quota).used;
|
|
929
|
+
} catch {
|
|
930
|
+
current = 0;
|
|
931
|
+
}
|
|
932
|
+
const text = await ctx.ui.input(
|
|
933
|
+
`输入 ${entry.masked} 当前周期已用次数(非负整数;当前:${current}/${quota.limit})`,
|
|
934
|
+
String(current),
|
|
935
|
+
);
|
|
936
|
+
if (text === undefined || !text.trim()) continue;
|
|
937
|
+
const next = Number(text.trim());
|
|
938
|
+
if (!Number.isInteger(next) || next < 0) {
|
|
939
|
+
ctx.ui.notify("已用次数必须是不小于 0 的整数", "error");
|
|
940
|
+
continue;
|
|
941
|
+
}
|
|
942
|
+
try {
|
|
943
|
+
usage.setUsage(instance.preset.id, entry.resolved, quota, next);
|
|
944
|
+
ctx.ui.notify(`已更新 ${entry.masked} 当前周期已用次数为 ${next}/${quota.limit}`, "info");
|
|
945
|
+
} catch (error) {
|
|
946
|
+
ctx.ui.notify(`写入用量失败:${messageOf(error)}`, "error");
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function uniqueKeys(keys: string[]): string[] {
|
|
953
|
+
return [...new Set(keys)];
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/** pi 的 ExtensionInputComponent 忽略 placeholder 参数,因此各供应商的格式说明必须写进标题。 */
|
|
957
|
+
function createCredentialPrompt(presetId: PresetId, mode: InstanceMode, index: number): string {
|
|
958
|
+
const nth = index > 1 ? `第 ${index} 组` : "";
|
|
959
|
+
const multiHint = mode === "pool"
|
|
960
|
+
? "pool 模式只需填写 1 个上游网关密钥;留空稍后填写"
|
|
961
|
+
: index > 1
|
|
962
|
+
? "可继续填 1 组或逗号分隔多组;留空结束添加"
|
|
963
|
+
: "支持环境变量 ${VAR},多组可用逗号分隔或下一步继续添加;留空稍后填写";
|
|
964
|
+
if (presetId === "tencent") {
|
|
965
|
+
return (
|
|
966
|
+
`腾讯云元宝搜索${nth}服务 API Key(在控制台「概览 > 服务 API KEY 方式」创建,格式如 sk-...)\n`
|
|
967
|
+
+ `示例:\${TENCENTCLOUD_WSA_APIKEY};${multiHint}`
|
|
968
|
+
);
|
|
969
|
+
}
|
|
970
|
+
if (presetId === "cloudflare") {
|
|
971
|
+
return `Cloudflare ${nth}API Token(示例:\${CF_API_TOKEN};${multiHint})`;
|
|
972
|
+
}
|
|
973
|
+
if (presetId === "anysearch") {
|
|
974
|
+
return index > 1
|
|
975
|
+
? `AnySearch ${nth}凭证(逗号分隔可填多组;留空结束添加)`
|
|
976
|
+
: "AnySearch 凭证(免 Key 可直接匿名使用,回车留空即可;如有 Key 可填写)";
|
|
977
|
+
}
|
|
978
|
+
return `${presetId} ${nth}API Key(示例:${KEY_PLACEHOLDER[presetId]};${multiHint})`;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
function addCredentialPrompt(presetId: PresetId): string {
|
|
982
|
+
if (presetId === "tencent") {
|
|
983
|
+
return (
|
|
984
|
+
"添加腾讯云元宝搜索服务 API Key(格式如 sk-...;可逗号分隔多组)\n"
|
|
985
|
+
+ "示例:${TENCENTCLOUD_WSA_APIKEY}"
|
|
986
|
+
);
|
|
987
|
+
}
|
|
988
|
+
if (presetId === "cloudflare") {
|
|
989
|
+
return "添加 Cloudflare API Token(示例:${CF_API_TOKEN};可逗号分隔多组)";
|
|
990
|
+
}
|
|
991
|
+
return `添加 ${presetId} API Key(示例:${KEY_PLACEHOLDER[presetId]};可逗号分隔多组)`;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
function editCredentialPrompt(presetId: PresetId, masked: string, mode: InstanceMode): string {
|
|
995
|
+
const scope = mode === "pool" ? "单个网关密钥" : "多组密钥用逗号分隔";
|
|
996
|
+
if (presetId === "tencent") {
|
|
997
|
+
return (
|
|
998
|
+
`腾讯云元宝搜索新服务 API Key(当前 ${masked};留空清空)\n`
|
|
999
|
+
+ `示例:\${TENCENTCLOUD_WSA_APIKEY},${scope}`
|
|
1000
|
+
);
|
|
1001
|
+
}
|
|
1002
|
+
if (presetId === "cloudflare") {
|
|
1003
|
+
return `Cloudflare 新 API Token(当前 ${masked};示例:\${CF_API_TOKEN};留空清空并改用 OAuth)`;
|
|
1004
|
+
}
|
|
1005
|
+
if (presetId === "anysearch") {
|
|
1006
|
+
return `AnySearch 新凭证(当前 ${masked};留空即匿名调用)`;
|
|
1007
|
+
}
|
|
1008
|
+
return `新凭证(当前 ${masked};示例:${KEY_PLACEHOLDER[presetId]},${scope};留空清空)`;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
type OAuthDialogOutcome =
|
|
1012
|
+
| { kind: "ok"; result: LoginResult }
|
|
1013
|
+
| { kind: "error"; message: string }
|
|
1014
|
+
| { kind: "cancelled" };
|
|
1015
|
+
|
|
1016
|
+
/** 打开 Cloudflare OAuth 登录页面(优先使用 pi 原生 LoginDialogComponent),完成换发与 accountId 回填。 */
|
|
1017
|
+
export async function runCloudflareLogin(ctx: ExtensionCommandContext, options: PanelOptions): Promise<boolean> {
|
|
1018
|
+
const loaded = loadPanel(options.source);
|
|
1019
|
+
if (!loaded.ok) {
|
|
1020
|
+
ctx.ui.notify(`读取配置失败:${loaded.error}`, "error");
|
|
1021
|
+
return false;
|
|
1022
|
+
}
|
|
1023
|
+
const oauth = options.source.cloudflareOAuth?.(loaded.config);
|
|
1024
|
+
if (!oauth) {
|
|
1025
|
+
ctx.ui.notify("当前运行环境未启用 Cloudflare OAuth", "error");
|
|
1026
|
+
return false;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
const { authorizeUrl, state } = oauth.beginLogin();
|
|
1030
|
+
const outcome = ctx.mode === "tui" && typeof ctx.ui.custom === "function"
|
|
1031
|
+
? (await showCloudflareLoginDialog(ctx, oauth, authorizeUrl, state)) ?? { kind: "cancelled" as const }
|
|
1032
|
+
: await showCloudflareLoginFallback(ctx, oauth, authorizeUrl, state);
|
|
1033
|
+
|
|
1034
|
+
if (outcome.kind === "cancelled") {
|
|
1035
|
+
ctx.ui.notify("已取消 Cloudflare OAuth 登录", "info");
|
|
1036
|
+
return false;
|
|
1037
|
+
}
|
|
1038
|
+
if (outcome.kind === "error") {
|
|
1039
|
+
ctx.ui.notify(`Cloudflare OAuth 登录失败:${outcome.message}`, "error");
|
|
1040
|
+
return false;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
options.source.reload();
|
|
1044
|
+
const parts = ["Cloudflare OAuth 登录成功"];
|
|
1045
|
+
if (outcome.result.token.account_id) parts.push(`Account ID:${outcome.result.token.account_id}`);
|
|
1046
|
+
if (outcome.result.updatedInstances.length > 0) {
|
|
1047
|
+
parts.push(`已回填实例:${outcome.result.updatedInstances.join(", ")}`);
|
|
1048
|
+
}
|
|
1049
|
+
if (outcome.result.warning) parts.push(`注意:${outcome.result.warning}`);
|
|
1050
|
+
ctx.ui.notify(parts.join(";"), outcome.result.warning ? "warning" : "info");
|
|
1051
|
+
return true;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/** 撤销远端 Cloudflare OAuth 授权并删除本地令牌文件。 */
|
|
1055
|
+
export async function runCloudflareLogout(ctx: ExtensionCommandContext, options: PanelOptions): Promise<void> {
|
|
1056
|
+
const loaded = loadPanel(options.source);
|
|
1057
|
+
if (!loaded.ok) {
|
|
1058
|
+
ctx.ui.notify(`读取配置失败:${loaded.error}`, "error");
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
const oauth = options.source.cloudflareOAuth?.(loaded.config);
|
|
1062
|
+
if (!oauth) {
|
|
1063
|
+
ctx.ui.notify("当前运行环境未启用 Cloudflare OAuth", "error");
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
const result = await oauth.logout();
|
|
1068
|
+
options.source.reload();
|
|
1069
|
+
if (!result.token) {
|
|
1070
|
+
ctx.ui.notify("当前未登录 Cloudflare OAuth", "info");
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
if (result.warning) {
|
|
1074
|
+
ctx.ui.notify(`已清除本地 Cloudflare OAuth 令牌(${result.warning})`, "warning");
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
ctx.ui.notify("已退出 Cloudflare OAuth 并清除本地令牌", "info");
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/** 动态铺满终端宽度的分隔线,完全依赖宿主传入的 theme,不依赖内部单例。 */
|
|
1081
|
+
class Divider implements Component {
|
|
1082
|
+
private readonly theme: Theme;
|
|
1083
|
+
|
|
1084
|
+
constructor(theme: Theme) {
|
|
1085
|
+
this.theme = theme;
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
render(width: number): string[] {
|
|
1089
|
+
return [this.theme.fg("dim", "─".repeat(Math.max(1, width)))];
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
invalidate(): void {}
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
/** Cloudflare OAuth 交互式登录页:展示可点击链接、操作指引、粘贴输入框与换发进度。 */
|
|
1096
|
+
class CloudflareLoginDialog extends Container {
|
|
1097
|
+
readonly input: Input;
|
|
1098
|
+
private readonly tui: TUI;
|
|
1099
|
+
private readonly theme: Theme;
|
|
1100
|
+
private readonly keybindings: KeybindingsManager;
|
|
1101
|
+
private readonly statusText: Text;
|
|
1102
|
+
private readonly onCancel: () => void;
|
|
1103
|
+
private submitting = false;
|
|
1104
|
+
private _focused = false;
|
|
1105
|
+
|
|
1106
|
+
get focused(): boolean {
|
|
1107
|
+
return this._focused;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
set focused(value: boolean) {
|
|
1111
|
+
this._focused = value;
|
|
1112
|
+
this.input.focused = value;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
constructor(
|
|
1116
|
+
tui: TUI,
|
|
1117
|
+
theme: Theme,
|
|
1118
|
+
keybindings: KeybindingsManager,
|
|
1119
|
+
authorizeUrl: string,
|
|
1120
|
+
onSubmit: (raw: string) => Promise<void>,
|
|
1121
|
+
onCancel: () => void,
|
|
1122
|
+
) {
|
|
1123
|
+
super();
|
|
1124
|
+
this.tui = tui;
|
|
1125
|
+
this.theme = theme;
|
|
1126
|
+
this.keybindings = keybindings;
|
|
1127
|
+
this.onCancel = onCancel;
|
|
1128
|
+
|
|
1129
|
+
const clickHint = process.platform === "darwin" ? "Cmd+Click 打开" : "Ctrl+Click 打开";
|
|
1130
|
+
this.addChild(new Divider(theme));
|
|
1131
|
+
this.addChild(new Text(theme.fg("accent", theme.bold("Cloudflare OAuth 登录")), 1, 0));
|
|
1132
|
+
this.addChild(new Spacer(1));
|
|
1133
|
+
this.addChild(new Text(theme.fg("accent", hyperlink(authorizeUrl, authorizeUrl)), 1, 0));
|
|
1134
|
+
this.addChild(new Text(theme.fg("dim", `(${clickHint},或直接复制上方链接到浏览器)`), 1, 0));
|
|
1135
|
+
this.addChild(new Spacer(1));
|
|
1136
|
+
this.addChild(
|
|
1137
|
+
new Text(
|
|
1138
|
+
theme.fg(
|
|
1139
|
+
"text",
|
|
1140
|
+
"1. 在浏览器中打开上方链接并同意 Cloudflare 授权。\n"
|
|
1141
|
+
+ "2. 授权完成后,把回调页显示的授权码(code)或完整回调链接粘贴到下方并回车:",
|
|
1142
|
+
),
|
|
1143
|
+
1,
|
|
1144
|
+
0,
|
|
1145
|
+
),
|
|
1146
|
+
);
|
|
1147
|
+
this.addChild(new Spacer(1));
|
|
1148
|
+
|
|
1149
|
+
this.input = new Input();
|
|
1150
|
+
this.input.onSubmit = () => {
|
|
1151
|
+
if (this.submitting) return;
|
|
1152
|
+
this.submitting = true;
|
|
1153
|
+
const raw = this.input.getValue();
|
|
1154
|
+
this.setStatus("正在向 Cloudflare 换取令牌并获取 Account ID...");
|
|
1155
|
+
void onSubmit(raw);
|
|
1156
|
+
};
|
|
1157
|
+
this.input.onEscape = () => this.onCancel();
|
|
1158
|
+
this.addChild(this.input);
|
|
1159
|
+
|
|
1160
|
+
this.statusText = new Text(theme.fg("dim", "Enter 提交 · Esc 取消"), 1, 0);
|
|
1161
|
+
this.addChild(this.statusText);
|
|
1162
|
+
this.addChild(new Divider(theme));
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
setStatus(message: string): void {
|
|
1166
|
+
this.statusText.setText(this.theme.fg("warning", message));
|
|
1167
|
+
this.tui.requestRender();
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
handleInput(data: string): void {
|
|
1171
|
+
if (this.keybindings.matches(data, "tui.select.cancel") || data === "\x1b") {
|
|
1172
|
+
this.onCancel();
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
if (!this.submitting) this.input.handleInput(data);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
async function showCloudflareLoginDialog(
|
|
1180
|
+
ctx: ExtensionCommandContext,
|
|
1181
|
+
oauth: PanelOAuth,
|
|
1182
|
+
authorizeUrl: string,
|
|
1183
|
+
state: string,
|
|
1184
|
+
): Promise<OAuthDialogOutcome> {
|
|
1185
|
+
return ctx.ui.custom<OAuthDialogOutcome>((tui, theme, keybindings, done) => {
|
|
1186
|
+
return new CloudflareLoginDialog(
|
|
1187
|
+
tui,
|
|
1188
|
+
theme,
|
|
1189
|
+
keybindings,
|
|
1190
|
+
authorizeUrl,
|
|
1191
|
+
async (raw) => {
|
|
1192
|
+
try {
|
|
1193
|
+
const parsed = parseAuthorizationCode(raw, state);
|
|
1194
|
+
const result = await oauth.completeLogin(parsed.code, state);
|
|
1195
|
+
done({ kind: "ok", result });
|
|
1196
|
+
} catch (error) {
|
|
1197
|
+
done({ kind: "error", message: messageOf(error) });
|
|
1198
|
+
}
|
|
1199
|
+
},
|
|
1200
|
+
() => done({ kind: "cancelled" }),
|
|
1201
|
+
);
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
async function showCloudflareLoginFallback(
|
|
1206
|
+
ctx: ExtensionCommandContext,
|
|
1207
|
+
oauth: PanelOAuth,
|
|
1208
|
+
authorizeUrl: string,
|
|
1209
|
+
state: string,
|
|
1210
|
+
): Promise<OAuthDialogOutcome> {
|
|
1211
|
+
const raw = await ctx.ui.input(
|
|
1212
|
+
`Cloudflare OAuth 登录\n请在浏览器打开:\n${authorizeUrl}\n授权后粘贴回调页显示的授权码(code)或完整回调链接`,
|
|
1213
|
+
"code 或完整回调链接",
|
|
1214
|
+
);
|
|
1215
|
+
if (raw === undefined) return { kind: "cancelled" };
|
|
1216
|
+
try {
|
|
1217
|
+
const parsed = parseAuthorizationCode(raw, state);
|
|
1218
|
+
const result = await oauth.completeLogin(parsed.code, state);
|
|
1219
|
+
return { kind: "ok", result };
|
|
1220
|
+
} catch (error) {
|
|
1221
|
+
return { kind: "error", message: messageOf(error) };
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
/** 凭证输入:逗号、空格或换行分隔。 */
|
|
1226
|
+
function splitKeys(text: string): string[] {
|
|
1227
|
+
return text
|
|
1228
|
+
.split(/[\s,]+/)
|
|
1229
|
+
.map((item) => item.trim())
|
|
1230
|
+
.filter(Boolean);
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
/** instances 数组;字段存在但不是数组时报错,避免覆盖用户数据。 */
|
|
1234
|
+
function instanceList(file: ConfigFile): unknown[] {
|
|
1235
|
+
if (file.instances === undefined) file.instances = [];
|
|
1236
|
+
if (!Array.isArray(file.instances)) throw new Error("instances 必须是数组");
|
|
1237
|
+
return file.instances;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
function findRawInstance(file: ConfigFile, id: string): Record<string, unknown> | undefined {
|
|
1241
|
+
if (!Array.isArray(file.instances)) return undefined;
|
|
1242
|
+
const found = file.instances.find((item) => isRecord(item) && item.id === id);
|
|
1243
|
+
return isRecord(found) ? found : undefined;
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
function rawInstance(file: ConfigFile, id: string): Record<string, unknown> {
|
|
1247
|
+
const found = instanceList(file).find((item) => isRecord(item) && item.id === id);
|
|
1248
|
+
if (!isRecord(found)) throw new Error(`实例不存在:${id}`);
|
|
1249
|
+
return found;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
/** 删实例并清理显式链里的引用;删到空时保留合法的空配置。 */
|
|
1253
|
+
function removeInstanceFrom(file: ConfigFile, id: string): void {
|
|
1254
|
+
const list = instanceList(file);
|
|
1255
|
+
const index = list.findIndex((item) => isRecord(item) && item.id === id);
|
|
1256
|
+
if (index < 0) throw new Error(`实例不存在:${id}`);
|
|
1257
|
+
list.splice(index, 1);
|
|
1258
|
+
for (const field of ["defaultChain", "fetchChain"] as const) {
|
|
1259
|
+
const chain = file[field];
|
|
1260
|
+
if (Array.isArray(chain)) file[field] = chain.filter((item) => item !== id);
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
1265
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
function messageOf(error: unknown): string {
|
|
1269
|
+
return error instanceof Error ? error.message : String(error);
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
function clip(text: string, limit: number): string {
|
|
1273
|
+
return text.length > limit ? `${text.slice(0, limit)}…` : text;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
/** 秒级与毫秒级的时长写法。 */
|
|
1277
|
+
function formatDuration(elapsedMs: number): string {
|
|
1278
|
+
return elapsedMs < 1_000 ? `${elapsedMs} ms` : `${(elapsedMs / 1_000).toFixed(1)} s`;
|
|
1279
|
+
}
|