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
package/src/http.ts
ADDED
|
@@ -0,0 +1,777 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { joinUrl } from "./base-url.ts";
|
|
5
|
+
import { callableInstance } from "./config.ts";
|
|
6
|
+
import type { ErrorClass, LoadedConfig, ResolvedInstance } from "./config.ts";
|
|
7
|
+
import { KeyPool, KeyPoolExhausted, maskKey, type KeyState } from "./key-pool.ts";
|
|
8
|
+
import { UsageStore, type QuotaReservation } from "./key-quota.ts";
|
|
9
|
+
import type { PresetId } from "./presets.ts";
|
|
10
|
+
import { resolveSecret } from "./secrets.ts";
|
|
11
|
+
|
|
12
|
+
/** 一次调用失败的原因分类,取值与配置里的 failover.on / stopOn 一致。 */
|
|
13
|
+
export function classifyStatus(status: number): ErrorClass {
|
|
14
|
+
if (status === 401 || status === 403) return "auth";
|
|
15
|
+
if (status === 402 || status === 432 || status === 433) return "quota";
|
|
16
|
+
if (status === 429) return "rateLimit";
|
|
17
|
+
if (status >= 500) return "server";
|
|
18
|
+
return "invalidRequest";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 解析 Retry-After:秒数或 HTTP 日期;无效值返回 undefined。 */
|
|
22
|
+
export function parseRetryAfter(value: string | null, now: number = Date.now()): number | undefined {
|
|
23
|
+
if (!value) return undefined;
|
|
24
|
+
const text = value.trim();
|
|
25
|
+
if (!text) return undefined;
|
|
26
|
+
if (/^\d+$/.test(text)) return Number(text);
|
|
27
|
+
const at = Date.parse(text);
|
|
28
|
+
if (Number.isNaN(at)) return undefined;
|
|
29
|
+
return Math.max(0, Math.ceil((at - now) / 1000));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 传输层失败的统一错误:实例、状态码、分类、重试间隔与上游请求 id。 */
|
|
33
|
+
export class ProviderError extends Error {
|
|
34
|
+
readonly instance: string;
|
|
35
|
+
readonly status?: number;
|
|
36
|
+
readonly code: ErrorClass;
|
|
37
|
+
readonly retryAfter?: number;
|
|
38
|
+
readonly requestId?: string;
|
|
39
|
+
/** 链上没有尝试的实例,failover 提前结束或取消时一并带出。 */
|
|
40
|
+
readonly unattempted: ProviderSkip[];
|
|
41
|
+
/** 链上逐次尝试的结果,按发生顺序排列,只保留定位信息与错误摘要。 */
|
|
42
|
+
readonly attempts: ProviderAttempt[];
|
|
43
|
+
|
|
44
|
+
constructor(init: {
|
|
45
|
+
instance: string;
|
|
46
|
+
code: ErrorClass;
|
|
47
|
+
message: string;
|
|
48
|
+
status?: number;
|
|
49
|
+
retryAfter?: number;
|
|
50
|
+
requestId?: string;
|
|
51
|
+
unattempted?: ProviderSkip[];
|
|
52
|
+
attempts?: ProviderAttempt[];
|
|
53
|
+
}) {
|
|
54
|
+
super(init.message);
|
|
55
|
+
this.name = "ProviderError";
|
|
56
|
+
this.instance = init.instance;
|
|
57
|
+
this.code = init.code;
|
|
58
|
+
this.status = init.status;
|
|
59
|
+
this.retryAfter = init.retryAfter;
|
|
60
|
+
this.requestId = init.requestId;
|
|
61
|
+
this.unattempted = init.unattempted ?? [];
|
|
62
|
+
this.attempts = init.attempts ?? [];
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 一次失败尝试:实例、供应商、错误分类与拦截后的消息。 */
|
|
67
|
+
export interface ProviderAttempt {
|
|
68
|
+
instance: string;
|
|
69
|
+
provider: PresetId;
|
|
70
|
+
code: ErrorClass;
|
|
71
|
+
status?: number;
|
|
72
|
+
message: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 链上没有尝试的实例;带上 provider 让失败输出不必再查配置。 */
|
|
76
|
+
export interface ProviderSkip {
|
|
77
|
+
instance: string;
|
|
78
|
+
provider: PresetId;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 一次请求的目标:实例、端点、方法、参数。 */
|
|
82
|
+
export interface RequestSpec {
|
|
83
|
+
instance: ResolvedInstance;
|
|
84
|
+
/** 以 / 开头时直接当路径用,否则取实例的 paths 键。 */
|
|
85
|
+
path: string;
|
|
86
|
+
method?: "GET" | "POST";
|
|
87
|
+
body?: Record<string, unknown>;
|
|
88
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
89
|
+
/** crawl 用更长的超时。 */
|
|
90
|
+
kind?: "default" | "crawl";
|
|
91
|
+
/** 覆盖本次请求的超时毫秒数。 */
|
|
92
|
+
timeoutMs?: number;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface RequestOptions {
|
|
96
|
+
/** 调用方取消信号,与本次请求的超时信号一起生效。 */
|
|
97
|
+
signal?: AbortSignal;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 限流窗口元数据;reset 是 epoch 秒。 */
|
|
101
|
+
export interface RateLimitInfo {
|
|
102
|
+
limit?: number;
|
|
103
|
+
remaining?: number;
|
|
104
|
+
reset?: number;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 成功响应;data 是解析后的 JSON,解析不了时保留原文。 */
|
|
108
|
+
export interface ProviderResponse<T = unknown> {
|
|
109
|
+
instance: string;
|
|
110
|
+
status: number;
|
|
111
|
+
data: T;
|
|
112
|
+
requestId?: string;
|
|
113
|
+
/** 限流窗口元数据,AnySearch 等供应商从响应头带回。 */
|
|
114
|
+
rateLimit?: RateLimitInfo;
|
|
115
|
+
/** 实际使用凭证的摘要。 */
|
|
116
|
+
keyMasked?: string;
|
|
117
|
+
/** 换过实例后成功。 */
|
|
118
|
+
degraded?: boolean;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface HttpClientOptions {
|
|
122
|
+
env?: NodeJS.ProcessEnv;
|
|
123
|
+
/** 全局 User-Agent 覆盖,优先级低于实例、高于环境变量。 */
|
|
124
|
+
userAgent?: string;
|
|
125
|
+
fetch?: typeof globalThis.fetch;
|
|
126
|
+
clock?: () => number;
|
|
127
|
+
/** Cloudflare OAuth 令牌来源;仅在 cloudflare sdk 实例未配置静态 keys 时使用。 */
|
|
128
|
+
cloudflareOAuth?: { accessToken(): Promise<string> };
|
|
129
|
+
/** 按密钥的调用次数限额存储;省略时使用仅内存实例。 */
|
|
130
|
+
usage?: UsageStore;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 排队中的请求被取消时抛这个错误,避免把取消当成网络失败。 */
|
|
134
|
+
function abortError(): Error {
|
|
135
|
+
const error = new Error("请求已取消");
|
|
136
|
+
error.name = "AbortError";
|
|
137
|
+
return error;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
interface Waiter {
|
|
141
|
+
/** 拿到名额时调用,附带归还名额的函数。 */
|
|
142
|
+
grant(release: () => void): void;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 每个实例一个信号量,限制同时在途的请求数;排队中被取消会立即退出队列。 */
|
|
146
|
+
class Semaphore {
|
|
147
|
+
private active = 0;
|
|
148
|
+
private readonly waiting: Waiter[] = [];
|
|
149
|
+
private readonly limit: number;
|
|
150
|
+
|
|
151
|
+
constructor(limit: number) {
|
|
152
|
+
this.limit = limit;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async acquire(signal?: AbortSignal): Promise<() => void> {
|
|
156
|
+
if (signal?.aborted) throw abortError();
|
|
157
|
+
if (this.active < this.limit) {
|
|
158
|
+
this.active += 1;
|
|
159
|
+
return () => this.release();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return new Promise<() => void>((resolve, reject) => {
|
|
163
|
+
const waiter: Waiter = {
|
|
164
|
+
grant: (release) => {
|
|
165
|
+
signal?.removeEventListener("abort", onAbort);
|
|
166
|
+
resolve(release);
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
const onAbort = (): void => {
|
|
170
|
+
const index = this.waiting.indexOf(waiter);
|
|
171
|
+
if (index >= 0) this.waiting.splice(index, 1);
|
|
172
|
+
reject(abortError());
|
|
173
|
+
};
|
|
174
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
175
|
+
this.waiting.push(waiter);
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private release(): void {
|
|
180
|
+
const next = this.waiting.shift();
|
|
181
|
+
if (next) {
|
|
182
|
+
next.grant(() => this.release());
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
this.active -= 1;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const REQUEST_ID_HEADERS = ["x-request-id", "x-tavily-request-id", "x-proxy-request-id", "cf-ray"];
|
|
190
|
+
|
|
191
|
+
const PI_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
192
|
+
|
|
193
|
+
let defaultUserAgentCache: string | undefined;
|
|
194
|
+
|
|
195
|
+
/** 读取 pi 宿主版本;解析不到时降级,不抛错。 */
|
|
196
|
+
function piVersion(): string | undefined {
|
|
197
|
+
try {
|
|
198
|
+
let directory = dirname(fileURLToPath(import.meta.resolve(PI_PACKAGE)));
|
|
199
|
+
for (let depth = 0; depth < 6; depth++) {
|
|
200
|
+
const candidate = join(directory, "package.json");
|
|
201
|
+
if (existsSync(candidate)) {
|
|
202
|
+
const parsed = JSON.parse(readFileSync(candidate, "utf8")) as { name?: string; version?: string };
|
|
203
|
+
if (parsed.name === PI_PACKAGE) return parsed.version;
|
|
204
|
+
}
|
|
205
|
+
const parent = dirname(directory);
|
|
206
|
+
if (parent === directory) break;
|
|
207
|
+
directory = parent;
|
|
208
|
+
}
|
|
209
|
+
} catch {
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** 默认 User-Agent:pi/<版本> (<platform>; node/<版本>; <arch>)。 */
|
|
216
|
+
export function defaultUserAgent(): string {
|
|
217
|
+
if (defaultUserAgentCache === undefined) {
|
|
218
|
+
const version = piVersion();
|
|
219
|
+
const identity = version ? `pi/${version}` : "pi";
|
|
220
|
+
defaultUserAgentCache = `${identity} (${process.platform}; node/${process.version}; ${process.arch})`;
|
|
221
|
+
}
|
|
222
|
+
return defaultUserAgentCache;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
226
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function parseBodyText(text: string): unknown {
|
|
230
|
+
if (!text.trim()) return undefined;
|
|
231
|
+
try {
|
|
232
|
+
return JSON.parse(text);
|
|
233
|
+
} catch {
|
|
234
|
+
return text;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function errorDetail(data: unknown): string | undefined {
|
|
239
|
+
if (typeof data === "string") return data.trim().slice(0, 200) || undefined;
|
|
240
|
+
if (!isRecord(data)) return undefined;
|
|
241
|
+
for (const name of ["detail", "message", "error_description", "error"]) {
|
|
242
|
+
const value = data[name];
|
|
243
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
244
|
+
if (isRecord(value)) {
|
|
245
|
+
const nested = errorDetail(value);
|
|
246
|
+
if (nested) return nested;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function responseMessage(status: number, data: unknown, text: string): string {
|
|
253
|
+
// AnySearch 的 402 body 可能带新生成的凭据,只保留状态码。
|
|
254
|
+
if (status === 402) return "HTTP 402: 额度不足";
|
|
255
|
+
const detail = errorDetail(data) ?? text.trim().slice(0, 200);
|
|
256
|
+
return detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function requestIdOf(headers: Headers, data: unknown): string | undefined {
|
|
260
|
+
if (!isRecord(data)) return headerRequestId(headers);
|
|
261
|
+
for (const name of ["request_id", "requestId"]) {
|
|
262
|
+
const value = data[name];
|
|
263
|
+
if (typeof value === "string" && value) return value;
|
|
264
|
+
}
|
|
265
|
+
// 腾讯云把 RequestId 放在 Response 信封里。
|
|
266
|
+
const envelope = isRecord(data.Response) ? data.Response : undefined;
|
|
267
|
+
const nested = envelope?.RequestId;
|
|
268
|
+
if (typeof nested === "string" && nested) return nested;
|
|
269
|
+
return headerRequestId(headers);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function headerRequestId(headers: Headers): string | undefined {
|
|
273
|
+
for (const name of REQUEST_ID_HEADERS) {
|
|
274
|
+
const value = headers.get(name);
|
|
275
|
+
if (value) return value;
|
|
276
|
+
}
|
|
277
|
+
return undefined;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** 数值响应头;缺失或非法时返回 undefined。 */
|
|
281
|
+
function numberHeader(headers: Headers, name: string): number | undefined {
|
|
282
|
+
const value = headers.get(name);
|
|
283
|
+
if (!value) return undefined;
|
|
284
|
+
const parsed = Number(value.trim());
|
|
285
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 限流元数据;响应头一个都没有时返回 undefined。 */
|
|
289
|
+
function rateLimitOf(headers: Headers): RateLimitInfo | undefined {
|
|
290
|
+
const limit = numberHeader(headers, "x-ratelimit-limit");
|
|
291
|
+
const remaining = numberHeader(headers, "x-ratelimit-remaining");
|
|
292
|
+
const reset = numberHeader(headers, "x-ratelimit-reset");
|
|
293
|
+
if (limit === undefined && remaining === undefined && reset === undefined) return undefined;
|
|
294
|
+
return { limit, remaining, reset };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function errorMessage(error: unknown): string {
|
|
298
|
+
if (error instanceof Error) return error.message;
|
|
299
|
+
return String(error);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** 传输层:凭证池、并发闸门、超时与取消、鉴权落点、错误分类与换供应商。 */
|
|
303
|
+
export class HttpClient {
|
|
304
|
+
private readonly config: LoadedConfig;
|
|
305
|
+
private readonly env: NodeJS.ProcessEnv;
|
|
306
|
+
private readonly globalUserAgent?: string;
|
|
307
|
+
private readonly fetchImpl: typeof globalThis.fetch;
|
|
308
|
+
private readonly clock: () => number;
|
|
309
|
+
private readonly cloudflareOAuth?: { accessToken(): Promise<string> };
|
|
310
|
+
private readonly usage: UsageStore;
|
|
311
|
+
private readonly pools = new Map<string, { signature: string; pool: KeyPool }>();
|
|
312
|
+
private readonly semaphores = new Map<string, Semaphore>();
|
|
313
|
+
private readonly instances: Map<string, ResolvedInstance>;
|
|
314
|
+
|
|
315
|
+
constructor(config: LoadedConfig, options: HttpClientOptions = {}) {
|
|
316
|
+
this.config = config;
|
|
317
|
+
this.env = options.env ?? process.env;
|
|
318
|
+
this.globalUserAgent = options.userAgent ?? config.userAgent;
|
|
319
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
|
320
|
+
this.clock = options.clock ?? Date.now;
|
|
321
|
+
this.cloudflareOAuth = options.cloudflareOAuth;
|
|
322
|
+
this.usage = options.usage ?? new UsageStore({ clock: this.clock });
|
|
323
|
+
this.instances = new Map(config.instances.map((instance) => [instance.id, instance]));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** 按链逐个尝试实例;换不换下一个由 failover 配置决定。 */
|
|
327
|
+
async execute(
|
|
328
|
+
chain: string[],
|
|
329
|
+
build: (instance: ResolvedInstance) => RequestSpec,
|
|
330
|
+
options: RequestOptions = {},
|
|
331
|
+
check?: (response: ProviderResponse) => void,
|
|
332
|
+
): Promise<ProviderResponse> {
|
|
333
|
+
const candidates = chain
|
|
334
|
+
.map((id) => this.instances.get(id))
|
|
335
|
+
.filter((instance): instance is ResolvedInstance => instance !== undefined)
|
|
336
|
+
.filter(callableInstance);
|
|
337
|
+
if (candidates.length === 0) {
|
|
338
|
+
const detail = chain.length === 0 ? "链为空" : `${chain.join(", ")} 未启用或未配置`;
|
|
339
|
+
throw new ProviderError({
|
|
340
|
+
instance: chain[0] ?? "",
|
|
341
|
+
code: "invalidRequest",
|
|
342
|
+
message: `没有可调用的实例:${detail}`,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const failover = this.config.failover;
|
|
347
|
+
const limit = failover.enabled ? Math.min(failover.maxAttempts, candidates.length) : 1;
|
|
348
|
+
const attempts: ProviderAttempt[] = [];
|
|
349
|
+
let tried = 0;
|
|
350
|
+
let lastError: ProviderError | undefined;
|
|
351
|
+
|
|
352
|
+
for (const instance of candidates) {
|
|
353
|
+
if (tried >= limit) break;
|
|
354
|
+
if (options.signal?.aborted) throw abortedRequest(instance.id, skipsOf(candidates.slice(tried)), attempts);
|
|
355
|
+
|
|
356
|
+
tried += 1;
|
|
357
|
+
try {
|
|
358
|
+
const response = await this.request(build(instance), options, check);
|
|
359
|
+
if (tried > 1) response.degraded = true;
|
|
360
|
+
return response;
|
|
361
|
+
} catch (error) {
|
|
362
|
+
const failure = toProviderError(instance.id, error);
|
|
363
|
+
// 取消不是供应商失败:已发生的尝试照常带出,取消本身只报一次。
|
|
364
|
+
if (failure.code === "aborted" || options.signal?.aborted) {
|
|
365
|
+
throw abortedRequest(instance.id, skipsOf(candidates.slice(tried)), attempts);
|
|
366
|
+
}
|
|
367
|
+
attempts.push({
|
|
368
|
+
instance: instance.id,
|
|
369
|
+
provider: instance.preset.id,
|
|
370
|
+
code: failure.code,
|
|
371
|
+
status: failure.status,
|
|
372
|
+
message: failure.message,
|
|
373
|
+
});
|
|
374
|
+
lastError = failure;
|
|
375
|
+
if (!this.shouldContinue(instance, failure)) break;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const remaining = skipsOf(candidates.slice(tried));
|
|
380
|
+
// 只失败一个实例时沿用它的原话,但仍把这条尝试链留在错误里。
|
|
381
|
+
if (lastError && attempts.length === 1 && remaining.length === 0) {
|
|
382
|
+
throw new ProviderError({
|
|
383
|
+
instance: lastError.instance,
|
|
384
|
+
code: lastError.code,
|
|
385
|
+
status: lastError.status,
|
|
386
|
+
retryAfter: lastError.retryAfter,
|
|
387
|
+
requestId: lastError.requestId,
|
|
388
|
+
message: lastError.message,
|
|
389
|
+
attempts,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const summary = attempts.map((item) => `${item.instance}: ${item.code} ${item.message}`).join(";");
|
|
394
|
+
throw new ProviderError({
|
|
395
|
+
instance: lastError?.instance ?? candidates[0]?.id ?? "",
|
|
396
|
+
code: lastError?.code ?? "invalidRequest",
|
|
397
|
+
status: lastError?.status,
|
|
398
|
+
retryAfter: lastError?.retryAfter,
|
|
399
|
+
message: aggregateMessage(remaining, summary),
|
|
400
|
+
requestId: lastError?.requestId,
|
|
401
|
+
unattempted: remaining,
|
|
402
|
+
attempts,
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** 单实例请求;同一实例内按需换凭证,超本地密钥限额时硬拦截不发请求,失败抛 ProviderError。 */
|
|
407
|
+
async request(
|
|
408
|
+
spec: RequestSpec,
|
|
409
|
+
options: RequestOptions = {},
|
|
410
|
+
check?: (response: ProviderResponse) => void,
|
|
411
|
+
): Promise<ProviderResponse> {
|
|
412
|
+
const instance = spec.instance;
|
|
413
|
+
const keys = this.resolveKeys(instance);
|
|
414
|
+
if (
|
|
415
|
+
instance.preset.id === "cloudflare"
|
|
416
|
+
&& instance.mode === "sdk"
|
|
417
|
+
&& instance.auth.type === "bearer"
|
|
418
|
+
&& keys.length === 0
|
|
419
|
+
&& this.cloudflareOAuth
|
|
420
|
+
) {
|
|
421
|
+
let token: string;
|
|
422
|
+
try {
|
|
423
|
+
token = await this.cloudflareOAuth.accessToken();
|
|
424
|
+
} catch (error) {
|
|
425
|
+
throw new ProviderError({
|
|
426
|
+
instance: instance.id,
|
|
427
|
+
code: "auth",
|
|
428
|
+
message: errorMessage(error),
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
const response = await this.attempt(spec, token, options);
|
|
432
|
+
check?.(response);
|
|
433
|
+
return response;
|
|
434
|
+
}
|
|
435
|
+
const pool = this.poolFor(instance, keys);
|
|
436
|
+
const attempted = new Set<string>();
|
|
437
|
+
const quotaBlocked = new Set<string>();
|
|
438
|
+
const retrySameInstance = instance.mode === "pool" ? 0 : this.config.failover.retrySameInstance;
|
|
439
|
+
const idempotent = (spec.method ?? "GET") === "GET";
|
|
440
|
+
let lastError: ProviderError | undefined;
|
|
441
|
+
|
|
442
|
+
for (;;) {
|
|
443
|
+
let key: string | undefined;
|
|
444
|
+
let reservation: QuotaReservation | undefined;
|
|
445
|
+
try {
|
|
446
|
+
const picked = this.acquireWithQuota(instance, pool, keys, attempted, quotaBlocked);
|
|
447
|
+
key = picked.key;
|
|
448
|
+
reservation = picked.reservation;
|
|
449
|
+
} catch (error) {
|
|
450
|
+
if (error instanceof KeyPoolExhausted && quotaBlocked.size > 0 && !lastError && instance.keyQuota) {
|
|
451
|
+
throw new ProviderError({
|
|
452
|
+
instance: instance.id,
|
|
453
|
+
code: "quota",
|
|
454
|
+
message: this.usage.exhaustedMessage(instance.id, instance.preset.id, keys, instance.keyQuota),
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
throw withExhaustedInfo(instance.id, error, lastError, quotaBlocked.size);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
let sameKeyRetries = 0;
|
|
461
|
+
let settled = false;
|
|
462
|
+
try {
|
|
463
|
+
for (;;) {
|
|
464
|
+
let response: ProviderResponse;
|
|
465
|
+
try {
|
|
466
|
+
response = await this.attempt(spec, key, options);
|
|
467
|
+
check?.(response);
|
|
468
|
+
} catch (error) {
|
|
469
|
+
const failure = toProviderError(instance.id, error);
|
|
470
|
+
lastError = failure;
|
|
471
|
+
if (pool && key !== undefined) pool.markFailure(key, failure.code, failure.retryAfter);
|
|
472
|
+
|
|
473
|
+
// 同凭证重试只用于幂等请求的 5xx;超时不重试,POST 超时后结果未知。
|
|
474
|
+
if (idempotent && failure.code === "server" && sameKeyRetries < retrySameInstance) {
|
|
475
|
+
sameKeyRetries += 1;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// 超时时请求可能已到达上游并计费,保守计入额度;其他明确未计费错误释放预占。
|
|
480
|
+
settled = true;
|
|
481
|
+
if (failure.code === "timeout") reservation?.commit();
|
|
482
|
+
else reservation?.release();
|
|
483
|
+
|
|
484
|
+
if (!pool || !ROTATABLE.has(failure.code)) throw failure;
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
if (pool && key !== undefined) pool.markSuccess(key);
|
|
489
|
+
settled = true;
|
|
490
|
+
reservation?.commit();
|
|
491
|
+
return response;
|
|
492
|
+
}
|
|
493
|
+
} finally {
|
|
494
|
+
if (!settled) reservation?.release();
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
private acquireWithQuota(
|
|
500
|
+
instance: ResolvedInstance,
|
|
501
|
+
pool: KeyPool | undefined,
|
|
502
|
+
keys: string[],
|
|
503
|
+
attempted: Set<string>,
|
|
504
|
+
quotaBlocked: Set<string>,
|
|
505
|
+
): { key: string | undefined; reservation?: QuotaReservation } {
|
|
506
|
+
const excluded = new Set<string>([...attempted, ...quotaBlocked]);
|
|
507
|
+
for (;;) {
|
|
508
|
+
const key = takeKey(instance, pool, keys, excluded);
|
|
509
|
+
if (key === undefined) return { key: undefined };
|
|
510
|
+
if (!instance.keyQuota) {
|
|
511
|
+
attempted.add(key);
|
|
512
|
+
return { key };
|
|
513
|
+
}
|
|
514
|
+
let reservation: QuotaReservation | undefined;
|
|
515
|
+
try {
|
|
516
|
+
reservation = this.usage.tryReserve(instance.preset.id, key, instance.keyQuota);
|
|
517
|
+
} catch (error) {
|
|
518
|
+
throw invalidRequest(instance.id, errorMessage(error));
|
|
519
|
+
}
|
|
520
|
+
if (reservation) {
|
|
521
|
+
attempted.add(key);
|
|
522
|
+
return { key, reservation };
|
|
523
|
+
}
|
|
524
|
+
quotaBlocked.add(key);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** 实例凭证状态快照;pool 模式不在插件侧建池,返回空数组。 */
|
|
529
|
+
poolState(instanceId: string): KeyState[] {
|
|
530
|
+
return this.pools.get(instanceId)?.pool.snapshot() ?? [];
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
private shouldContinue(instance: ResolvedInstance, failure: ProviderError): boolean {
|
|
534
|
+
const failover = this.config.failover;
|
|
535
|
+
if (!failover.enabled || !instance.failover) return false;
|
|
536
|
+
if (failover.stopOn.includes(failure.code)) return false;
|
|
537
|
+
return failover.on.includes(failure.code);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
private resolveKeys(instance: ResolvedInstance): string[] {
|
|
541
|
+
const keys = instance.keys
|
|
542
|
+
.map((key) => resolveSecret(key, this.env))
|
|
543
|
+
.filter((key): key is string => key !== undefined && key !== "");
|
|
544
|
+
return instance.mode === "pool" ? keys.slice(0, 1) : keys;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
private poolFor(instance: ResolvedInstance, keys: string[]): KeyPool | undefined {
|
|
548
|
+
if (instance.mode === "pool" || keys.length === 0) return undefined;
|
|
549
|
+
const signature = `${instance.cooldownSeconds}\u0000${keys.join("\u0000")}`;
|
|
550
|
+
const cached = this.pools.get(instance.id);
|
|
551
|
+
if (cached && cached.signature === signature) return cached.pool;
|
|
552
|
+
const pool = new KeyPool(keys, { cooldownSeconds: instance.cooldownSeconds, clock: this.clock });
|
|
553
|
+
this.pools.set(instance.id, { signature, pool });
|
|
554
|
+
return pool;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
private semaphore(instance: ResolvedInstance): Semaphore {
|
|
558
|
+
let semaphore = this.semaphores.get(instance.id);
|
|
559
|
+
if (!semaphore) {
|
|
560
|
+
semaphore = new Semaphore(instance.concurrency);
|
|
561
|
+
this.semaphores.set(instance.id, semaphore);
|
|
562
|
+
}
|
|
563
|
+
return semaphore;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** 空字符串按契约表示不带标识;fetch 无法省略该头,只能发空值覆盖运行时默认的 node。 */
|
|
567
|
+
private userAgentFor(instance: ResolvedInstance): string | undefined {
|
|
568
|
+
const sources = [instance.userAgent, this.globalUserAgent, this.env.PI_SEARCH_USER_AGENT];
|
|
569
|
+
for (const raw of sources) {
|
|
570
|
+
if (raw === undefined) continue;
|
|
571
|
+
if (raw.trim() === "") return "";
|
|
572
|
+
const resolved = raw.includes("$") ? resolveSecret(raw, this.env) : raw;
|
|
573
|
+
if (resolved === undefined) continue;
|
|
574
|
+
return resolved.trim() === "" ? "" : resolved;
|
|
575
|
+
}
|
|
576
|
+
return defaultUserAgent();
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
private resolvePath(instance: ResolvedInstance, path: string): string {
|
|
580
|
+
const template = path.startsWith("/") ? path : instance.paths[path];
|
|
581
|
+
if (!template) throw invalidRequest(instance.id, `实例没有路径 ${path}`);
|
|
582
|
+
if (!template.includes("{accountId}")) return template;
|
|
583
|
+
if (!instance.accountId) throw invalidRequest(instance.id, "实例缺少 accountId");
|
|
584
|
+
return template.replaceAll("{accountId}", instance.accountId);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
private buildRequest(
|
|
588
|
+
spec: RequestSpec,
|
|
589
|
+
key: string | undefined,
|
|
590
|
+
): { url: string; headers: Record<string, string>; body?: string } {
|
|
591
|
+
const instance = spec.instance;
|
|
592
|
+
const auth = instance.auth;
|
|
593
|
+
if (auth.type !== "none" && key === undefined) throw invalidRequest(instance.id, "凭证未解析");
|
|
594
|
+
|
|
595
|
+
const url = new URL(joinUrl(instance.baseUrl, this.resolvePath(instance, spec.path)));
|
|
596
|
+
for (const [name, value] of Object.entries(spec.query ?? {})) {
|
|
597
|
+
if (value !== undefined) url.searchParams.set(name, String(value));
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const headers: Record<string, string> = { Accept: "application/json" };
|
|
601
|
+
const userAgent = this.userAgentFor(instance);
|
|
602
|
+
if (userAgent !== undefined) headers["User-Agent"] = userAgent;
|
|
603
|
+
|
|
604
|
+
if (key !== undefined && auth.type !== "none") {
|
|
605
|
+
if (auth.type === "bearer") {
|
|
606
|
+
headers.Authorization = `Bearer ${key}`;
|
|
607
|
+
} else {
|
|
608
|
+
const name = auth.name;
|
|
609
|
+
if (!name) throw invalidRequest(instance.id, `鉴权 ${auth.type} 缺少字段名`);
|
|
610
|
+
if (auth.type === "header") headers[name] = key;
|
|
611
|
+
else if (auth.type === "query") url.searchParams.set(name, key);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
let body = spec.body === undefined ? undefined : { ...spec.body };
|
|
616
|
+
if (key !== undefined && auth.type === "body" && auth.name) body = { ...(body ?? {}), [auth.name]: key };
|
|
617
|
+
|
|
618
|
+
const payload = body === undefined ? undefined : JSON.stringify(body);
|
|
619
|
+
if (payload !== undefined) headers["Content-Type"] = "application/json";
|
|
620
|
+
return { url: url.toString(), headers, body: payload };
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
private async attempt(
|
|
624
|
+
spec: RequestSpec,
|
|
625
|
+
key: string | undefined,
|
|
626
|
+
options: RequestOptions,
|
|
627
|
+
): Promise<ProviderResponse> {
|
|
628
|
+
const instance = spec.instance;
|
|
629
|
+
let release: (() => void) | undefined;
|
|
630
|
+
let timedOut = false;
|
|
631
|
+
let timer: NodeJS.Timeout | undefined;
|
|
632
|
+
const controller = new AbortController();
|
|
633
|
+
const onCallerAbort = () => controller.abort();
|
|
634
|
+
const timeoutMs = spec.timeoutMs
|
|
635
|
+
?? (spec.kind === "crawl" ? this.config.limits.crawlTimeoutMs : this.config.limits.timeoutMs);
|
|
636
|
+
|
|
637
|
+
try {
|
|
638
|
+
release = await this.semaphore(instance).acquire(options.signal);
|
|
639
|
+
if (options.signal?.aborted) throw abortedRequest(instance.id);
|
|
640
|
+
timer = setTimeout(() => {
|
|
641
|
+
timedOut = true;
|
|
642
|
+
controller.abort();
|
|
643
|
+
}, timeoutMs);
|
|
644
|
+
options.signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
645
|
+
const request = this.buildRequest(spec, key);
|
|
646
|
+
const response = await this.fetchImpl(request.url, {
|
|
647
|
+
method: spec.method ?? "GET",
|
|
648
|
+
headers: request.headers,
|
|
649
|
+
body: request.body,
|
|
650
|
+
signal: controller.signal,
|
|
651
|
+
});
|
|
652
|
+
const text = await response.text();
|
|
653
|
+
const data = parseBodyText(text);
|
|
654
|
+
const requestId = requestIdOf(response.headers, data);
|
|
655
|
+
|
|
656
|
+
if (!response.ok) {
|
|
657
|
+
throw new ProviderError({
|
|
658
|
+
instance: instance.id,
|
|
659
|
+
status: response.status,
|
|
660
|
+
code: classifyStatus(response.status),
|
|
661
|
+
message: responseMessage(response.status, data, text),
|
|
662
|
+
retryAfter: parseRetryAfter(response.headers.get("retry-after")),
|
|
663
|
+
requestId,
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
return {
|
|
668
|
+
instance: instance.id,
|
|
669
|
+
status: response.status,
|
|
670
|
+
data,
|
|
671
|
+
requestId,
|
|
672
|
+
rateLimit: rateLimitOf(response.headers),
|
|
673
|
+
keyMasked: key === undefined ? undefined : maskKey(key),
|
|
674
|
+
};
|
|
675
|
+
} catch (error) {
|
|
676
|
+
throw toTransportError(instance.id, error, timedOut, options.signal, timeoutMs);
|
|
677
|
+
} finally {
|
|
678
|
+
if (timer) clearTimeout(timer);
|
|
679
|
+
options.signal?.removeEventListener("abort", onCallerAbort);
|
|
680
|
+
release?.();
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** 同一实例内换凭证的失败类:冷却类与 5xx。 */
|
|
686
|
+
const ROTATABLE: ReadonlySet<ErrorClass> = new Set<ErrorClass>(["auth", "quota", "rateLimit", "server"]);
|
|
687
|
+
|
|
688
|
+
function takeKey(
|
|
689
|
+
instance: ResolvedInstance,
|
|
690
|
+
pool: KeyPool | undefined,
|
|
691
|
+
keys: string[],
|
|
692
|
+
attempted: Set<string>,
|
|
693
|
+
): string | undefined {
|
|
694
|
+
if (instance.auth.type === "none" && keys.length === 0) return undefined;
|
|
695
|
+
|
|
696
|
+
if (!pool) {
|
|
697
|
+
// pool 模式只有一个凭证,轮询在上游。
|
|
698
|
+
const key = keys[0];
|
|
699
|
+
if (key === undefined) throw invalidRequest(instance.id, "凭证未解析,检查环境变量");
|
|
700
|
+
if (attempted.has(key)) throw new KeyPoolExhausted(1);
|
|
701
|
+
attempted.add(key);
|
|
702
|
+
return key;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
const key = pool.acquire(attempted);
|
|
706
|
+
attempted.add(key);
|
|
707
|
+
return key;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function invalidRequest(instance: string, message: string): ProviderError {
|
|
711
|
+
return new ProviderError({ instance, code: "invalidRequest", message });
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/** 调用方取消时的统一错误;已发生的尝试与未尝试的实例一并带出,取消本身不算供应商失败。 */
|
|
715
|
+
function abortedRequest(
|
|
716
|
+
instance: string,
|
|
717
|
+
remaining: ProviderSkip[] = [],
|
|
718
|
+
attempts: ProviderAttempt[] = [],
|
|
719
|
+
): ProviderError {
|
|
720
|
+
return new ProviderError({ instance, code: "aborted", message: "请求已取消", unattempted: remaining, attempts });
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/** 把链上剩下的实例映射成实例与供应商,用于失败输出。 */
|
|
724
|
+
function skipsOf(instances: ResolvedInstance[]): ProviderSkip[] {
|
|
725
|
+
return instances.map((instance) => ({ instance: instance.id, provider: instance.preset.id }));
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/** 池内凭证都已尝试时,把池大小与本地限额拦截数补进最后一次失败的信息里。 */
|
|
729
|
+
function withExhaustedInfo(
|
|
730
|
+
instanceId: string,
|
|
731
|
+
error: unknown,
|
|
732
|
+
lastError: ProviderError | undefined,
|
|
733
|
+
quotaBlockedCount = 0,
|
|
734
|
+
): ProviderError {
|
|
735
|
+
if (error instanceof KeyPoolExhausted) {
|
|
736
|
+
const quotaNote = quotaBlockedCount > 0 ? `;其中 ${quotaBlockedCount} 组已达本地调用限额` : "";
|
|
737
|
+
if (!lastError) return new ProviderError({ instance: instanceId, code: "auth", message: `${error.message}${quotaNote}` });
|
|
738
|
+
return new ProviderError({
|
|
739
|
+
instance: instanceId,
|
|
740
|
+
code: lastError.code,
|
|
741
|
+
status: lastError.status,
|
|
742
|
+
retryAfter: lastError.retryAfter,
|
|
743
|
+
requestId: lastError.requestId,
|
|
744
|
+
message: `${lastError.message};${error.message}${quotaNote}`,
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
return lastError ?? toProviderError(instanceId, error);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
function toProviderError(instanceId: string, error: unknown): ProviderError {
|
|
751
|
+
if (error instanceof ProviderError) return error;
|
|
752
|
+
if (error instanceof KeyPoolExhausted) {
|
|
753
|
+
return new ProviderError({ instance: instanceId, code: "auth", message: error.message });
|
|
754
|
+
}
|
|
755
|
+
return new ProviderError({ instance: instanceId, code: "network", message: errorMessage(error) });
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
function toTransportError(
|
|
759
|
+
instanceId: string,
|
|
760
|
+
error: unknown,
|
|
761
|
+
timedOut: boolean,
|
|
762
|
+
signal: AbortSignal | undefined,
|
|
763
|
+
timeoutMs: number,
|
|
764
|
+
): ProviderError {
|
|
765
|
+
if (error instanceof ProviderError) return error;
|
|
766
|
+
if (signal?.aborted) return abortedRequest(instanceId);
|
|
767
|
+
if (timedOut) {
|
|
768
|
+
return new ProviderError({ instance: instanceId, code: "timeout", message: `请求超过 ${timeoutMs}ms 未完成` });
|
|
769
|
+
}
|
|
770
|
+
return new ProviderError({ instance: instanceId, code: "network", message: `连接失败:${errorMessage(error)}` });
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function aggregateMessage(remaining: ProviderSkip[], summary: string): string {
|
|
774
|
+
const detail = summary || "没有尝试任何实例";
|
|
775
|
+
if (remaining.length === 0) return `实例全部失败:${detail}`;
|
|
776
|
+
return `已尝试的实例都失败:${detail};未尝试:${remaining.map((item) => item.instance).join(", ")}`;
|
|
777
|
+
}
|