pi-auto-web-search 0.1.1 → 0.1.2

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.
@@ -12,7 +12,6 @@ import {
12
12
  import { homedir } from "node:os";
13
13
  import { dirname, join } from "node:path";
14
14
  import { ConfigStore, type CloudflareOAuthConfig } from "./config.ts";
15
- import { resolveSecret } from "./secrets.ts";
16
15
 
17
16
  /** 默认令牌文件路径。 */
18
17
  export const DEFAULT_TOKEN_PATH = join(homedir(), ".pi", "agent", "search-oauth.json");
@@ -160,27 +159,14 @@ export function buildAuthorizeUrl(config: CloudflareOAuthConfig, state: string,
160
159
  return url.toString();
161
160
  }
162
161
 
163
- /** 把 account_id 写进缺少 accountId 的 cloudflare 实例,返回被更新的实例 id;配置文件不存在时跳过。 */
162
+ /** 仅在登录后给使用该身份且未绑定账号的实例写入 accountId。 */
164
163
  export function backfillAccountId(
165
164
  configPath: string,
166
165
  accountId: string,
167
166
  env: NodeJS.ProcessEnv = process.env,
168
167
  ): string[] {
169
- if (!accountId || !configPath || !existsSync(configPath)) return [];
170
- const updated: string[] = [];
171
- new ConfigStore(configPath).update((file) => {
172
- if (!Array.isArray(file.instances)) return;
173
- for (const entry of file.instances) {
174
- if (!isRecord(entry) || entry.preset !== "cloudflare") continue;
175
- if (typeof entry.id !== "string") continue;
176
- // 用户已经写了具体账号就不覆盖;未解析的变量按待回填处理。
177
- const current = typeof entry.accountId === "string" ? resolveSecret(entry.accountId, env) : undefined;
178
- if (current) continue;
179
- entry.accountId = accountId;
180
- updated.push(entry.id);
181
- }
182
- }, env);
183
- return updated;
168
+ if (!accountId.trim() || !configPath) return [];
169
+ return new ConfigStore(configPath).backfillCloudflareAccountId(accountId, env);
184
170
  }
185
171
 
186
172
  function isRecord(value: unknown): value is Record<string, unknown> {
package/src/config.ts CHANGED
@@ -2,14 +2,17 @@ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, s
2
2
  import { dirname } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { parse, stringify } from "comment-json";
5
+ import { FETCH_FORMATS, type FetchOutputFormat } from "./adapters/types.ts";
5
6
  import { assertBaseUrl } from "./base-url.ts";
6
7
  import { parseQuotaPeriod, type KeyQuotaConfig } from "./key-quota.ts";
7
8
  import { resolveSecret, secretVariables } from "./secrets.ts";
8
- import { PRESETS, isPresetId, type AuthSetting, type AuthType, type ChainKind, type Preset } from "./presets.ts";
9
+ import { CLOUDFLARE_TOOL_PATHS, PRESETS, isPresetId, type AuthSetting, type AuthType, type ChainKind, type Preset } from "./presets.ts";
9
10
 
10
11
  export type InstanceMode = "sdk" | "pool" | "proxy";
11
12
 
12
- export type InstanceStatus = "ready" | "unconfigured";
13
+ export type InstanceStatus = "ready" | "partial" | "unconfigured";
14
+
15
+ export type ToolOperation = "search" | "map" | FetchOutputFormat;
13
16
 
14
17
  export const ERROR_CLASSES = [
15
18
  "auth",
@@ -55,6 +58,9 @@ export interface ResolvedInstance {
55
58
  baseUrl: string;
56
59
  keys: string[];
57
60
  auth: AuthSetting;
61
+ usesCloudflareOAuth: boolean;
62
+ /** 用户配置的账号绑定,保留未解析的变量引用。 */
63
+ accountIdSetting?: string;
58
64
  accountId?: string;
59
65
  /** 模型名,仅 xai 这类按模型调用的供应商使用。 */
60
66
  model?: string;
@@ -69,6 +75,7 @@ export interface ResolvedInstance {
69
75
  userAgent?: string;
70
76
  /** 按密钥的调用次数硬限额;未配置时继承供应商默认限额,显式 false/null 关闭。 */
71
77
  keyQuota?: KeyQuotaConfig;
78
+ missingAccountFor: ("search" | FetchOutputFormat)[];
72
79
  status: InstanceStatus;
73
80
  warnings: string[];
74
81
  }
@@ -102,6 +109,8 @@ export interface LoadedConfig {
102
109
  warnings: string[];
103
110
  }
104
111
 
112
+ const CLOUDFLARE_OPERATIONS = ["search", ...FETCH_FORMATS] as const;
113
+
105
114
  const MODES: readonly InstanceMode[] = ["sdk", "pool", "proxy"];
106
115
 
107
116
  const AUTH_TYPES: readonly AuthType[] = ["bearer", "header", "query", "body", "none"];
@@ -279,38 +288,38 @@ function resolveInstance(
279
288
  const warnings: string[] = [];
280
289
  const keys = keyList(raw.keys, label, warnings, mode);
281
290
  const resolvedKeys = keys.filter((key) => resolveSecret(key, env) !== undefined);
282
- const cloudflareOAuthEligible =
283
- preset.id === "cloudflare" && mode === "sdk" && auth.type === "bearer" && keys.length === 0;
291
+ const enabled = booleanValue(raw.enabled, `${label}.enabled`, true);
292
+ const usesCloudflareOAuth = enabled && preset.id === "cloudflare" && mode === "sdk"
293
+ && auth.type === "bearer" && keys.length === 0;
294
+ const oauthToken = usesCloudflareOAuth ? options?.cloudflareOAuthToken : undefined;
284
295
  let status: InstanceStatus = "ready";
285
296
  if (auth.type === "none" && keys.length === 0) {
286
297
  status = "ready";
287
- } else if (cloudflareOAuthEligible && options?.cloudflareOAuthToken) {
298
+ } else if (oauthToken) {
288
299
  status = "ready";
289
300
  } else if (resolvedKeys.length === 0) {
290
301
  status = "unconfigured";
291
302
  const missing = missingVariables(keys, env);
292
- if (cloudflareOAuthEligible) {
303
+ if (usesCloudflareOAuth) {
293
304
  warnings.push("未配置 API Token,也未登录 Cloudflare OAuth(在 /search 登录)");
294
305
  } else {
295
306
  warnings.push(missing.length ? `凭证变量未设置:${missing.join(", ")}` : "没有可用凭证");
296
307
  }
297
308
  }
298
309
 
299
- let accountId: string | undefined;
300
- if (raw.accountId !== undefined) {
301
- const value = requiredString(raw.accountId, `${label}.accountId`);
302
- const resolved = resolveSecret(value, env);
303
- if (resolved === undefined) {
304
- const missing = missingVariables([value], env);
305
- warnings.push(`accountId 变量未设置:${missing.join(", ") || value}`);
306
- } else {
307
- accountId = resolved;
308
- }
310
+ const paths = resolvePaths(raw.paths, preset, label);
311
+ const accountIdSetting = raw.accountId === undefined ? undefined : stringValue(raw.accountId, `${label}.accountId`).trim();
312
+ const accountId = (accountIdSetting ? resolveSecret(accountIdSetting, env) : oauthToken?.accountId)?.trim() || undefined;
313
+ const missingAccountFor = preset.requiresAccountId && !accountId
314
+ ? CLOUDFLARE_OPERATIONS.filter((op) => paths[CLOUDFLARE_TOOL_PATHS[op]]?.includes("{accountId}"))
315
+ : [];
316
+ if (missingAccountFor.length > 0) {
317
+ const missing = accountIdSetting ? missingVariables([accountIdSetting], env) : [];
318
+ if (missing.length) warnings.push(`accountId 变量未设置:${missing.join(", ")}`);
319
+ const allBlocked = missingAccountFor.length === CLOUDFLARE_OPERATIONS.length;
320
+ warnings.push(allBlocked ? "缺少 accountId" : `缺少 accountId,以下操作不可用:${missingAccountFor.join("、")}`);
321
+ if (status === "ready") status = allBlocked ? "unconfigured" : "partial";
309
322
  }
310
- if (!accountId && cloudflareOAuthEligible && options?.cloudflareOAuthToken?.accountId) {
311
- accountId = options.cloudflareOAuthToken.accountId;
312
- }
313
- if (preset.requiresAccountId && !accountId) warnings.push("accountId 待回填,OAuth 登录后自动写入");
314
323
 
315
324
  return {
316
325
  id,
@@ -319,13 +328,16 @@ function resolveInstance(
319
328
  baseUrl,
320
329
  keys,
321
330
  auth,
331
+ usesCloudflareOAuth,
332
+ accountIdSetting,
322
333
  accountId,
323
334
  model: raw.model === undefined ? undefined : requiredString(raw.model, `${label}.model`),
324
335
  xSearch: booleanValue(raw.xSearch, `${label}.xSearch`, false),
325
- paths: resolvePaths(raw.paths, preset, label),
336
+ paths,
337
+ missingAccountFor,
326
338
  concurrency: integerInRange(raw.concurrency, `${label}.concurrency`, 1, 64, 4),
327
339
  cooldownSeconds: integerInRange(raw.cooldownSeconds, `${label}.cooldownSeconds`, 0, 86_400, 600),
328
- enabled: booleanValue(raw.enabled, `${label}.enabled`, true),
340
+ enabled,
329
341
  failover: booleanValue(raw.failover, `${label}.failover`, true),
330
342
  priority: raw.priority === undefined
331
343
  ? undefined
@@ -341,12 +353,27 @@ function chainPosition(instance: ResolvedInstance, kind: ChainKind): number | un
341
353
  return instance.priority ?? instance.preset.defaultPriority[kind];
342
354
  }
343
355
 
344
- /** 实例可被调用:已启用且凭证已配置;链构建与传输层都用这一条判断。 */
356
+ /** 实例已启用且至少一个操作已就绪。 */
345
357
  export function callableInstance(instance: ResolvedInstance): boolean {
346
- return instance.enabled && instance.status === "ready";
358
+ return instance.enabled && instance.status !== "unconfigured";
359
+ }
360
+
361
+ /** 返回本地可见的缺配置原因;部分可用的实例按本次操作判断。 */
362
+ export function instanceUnavailableReason(instance: ResolvedInstance, operation: ToolOperation): string | undefined {
363
+ if (!instance.enabled) return "已禁用";
364
+ if (instance.status === "unconfigured") return instance.warnings.join(";") || "未配置";
365
+ if (operation !== "map" && instance.missingAccountFor.includes(operation)) {
366
+ return `缺少 accountId,${operation} 不可用`;
367
+ }
368
+ return undefined;
347
369
  }
348
370
 
349
371
  function buildChain(value: unknown, kind: ChainKind, field: string, instances: ResolvedInstance[]): string[] {
372
+ const available = (instance: ResolvedInstance): boolean => {
373
+ if (instance.status !== "partial") return callableInstance(instance);
374
+ if (kind === "search") return !instanceUnavailableReason(instance, "search");
375
+ return FETCH_FORMATS.some((format) => !instanceUnavailableReason(instance, format));
376
+ };
350
377
  if (value !== undefined) {
351
378
  if (!Array.isArray(value)) invalid(`${field} 必须是数组`);
352
379
  const byId = new Map(instances.map((instance) => [instance.id, instance]));
@@ -356,13 +383,13 @@ function buildChain(value: unknown, kind: ChainKind, field: string, instances: R
356
383
  if (!instance) invalid(`${field} 引用了不存在的实例:${id}`);
357
384
  return instance;
358
385
  })
359
- .filter(callableInstance)
386
+ .filter(available)
360
387
  .map((instance) => instance.id);
361
388
  }
362
389
 
363
390
  const order = new Map(instances.map((instance, index) => [instance.id, index]));
364
391
  return instances
365
- .filter((instance) => callableInstance(instance) && chainPosition(instance, kind) !== undefined)
392
+ .filter((instance) => available(instance) && chainPosition(instance, kind) !== undefined)
366
393
  .sort((left, right) => {
367
394
  const position = (chainPosition(left, kind) ?? 0) - (chainPosition(right, kind) ?? 0);
368
395
  if (position !== 0) return position;
@@ -391,20 +418,18 @@ function errorClassList(value: unknown, label: string, fallback: readonly ErrorC
391
418
  });
392
419
  }
393
420
 
394
- function resolveFailover(value: unknown, chainLength: number): FailoverConfig {
421
+ function resolveFailover(value: unknown): FailoverConfig {
395
422
  const raw = optionalRecord(value, "failover");
396
423
  const on = errorClassList(raw.on, "failover.on", DEFAULT_FAILOVER.on);
397
424
  const stopOn = errorClassList(raw.stopOn, "failover.stopOn", DEFAULT_FAILOVER.stopOn);
398
425
  const overlap = on.filter((name) => stopOn.includes(name));
399
426
  if (overlap.length) invalid(`failover.on 与 failover.stopOn 不能重叠:${overlap.join(", ")}`);
400
427
 
401
- const ceiling = Math.max(1, chainLength);
402
- const fallbackAttempts = Math.min(DEFAULT_FAILOVER.maxAttempts, ceiling);
403
428
  return {
404
429
  enabled: booleanValue(raw.enabled, "failover.enabled", DEFAULT_FAILOVER.enabled),
405
430
  on,
406
431
  stopOn,
407
- maxAttempts: integerInRange(raw.maxAttempts, "failover.maxAttempts", 1, ceiling, fallbackAttempts),
432
+ maxAttempts: integerAtLeast(raw.maxAttempts, "failover.maxAttempts", 1, DEFAULT_FAILOVER.maxAttempts),
408
433
  retrySameInstance: integerAtLeast(
409
434
  raw.retrySameInstance,
410
435
  "failover.retrySameInstance",
@@ -462,7 +487,7 @@ export function resolveConfig(
462
487
  searchChain,
463
488
  fetchChain,
464
489
  limits: resolveLimits(file.limits),
465
- failover: resolveFailover(file.failover, Math.max(searchChain.length, fetchChain.length)),
490
+ failover: resolveFailover(file.failover),
466
491
  cloudflareOAuth: resolveCloudflareOAuth(file.cloudflareOAuth),
467
492
  userAgent: file.userAgent === undefined ? undefined : stringValue(file.userAgent, "userAgent"),
468
493
  warnings: instances.flatMap((instance) => instance.warnings.map((warning) => `${instance.id}: ${warning}`)),
@@ -510,6 +535,23 @@ export class ConfigStore {
510
535
  return loaded;
511
536
  }
512
537
 
538
+ /** 从同一份配置快照选择 OAuth 回填目标,没有目标时保留原文件。 */
539
+ backfillCloudflareAccountId(accountId: string, env: NodeJS.ProcessEnv): string[] {
540
+ const { raw, text, exists } = this.read();
541
+ if (!exists) return [];
542
+ const file = parseConfigText(text, this.path);
543
+ const { instances } = resolveConfig(file, env);
544
+ const updated: string[] = [];
545
+ if (!Array.isArray(file.instances)) return updated;
546
+ for (const [index, instance] of instances.entries()) {
547
+ if (!instance.usesCloudflareOAuth || instance.accountIdSetting) continue;
548
+ file.instances[index].accountId = accountId;
549
+ updated.push(instance.id);
550
+ }
551
+ if (updated.length > 0) this.write(file, raw, exists);
552
+ return updated;
553
+ }
554
+
513
555
  save(file: ConfigFile, env: NodeJS.ProcessEnv = process.env, options?: ResolveConfigOptions): void {
514
556
  const { raw, exists } = this.read();
515
557
  resolveConfig(file, env, options);
package/src/http.ts CHANGED
@@ -5,7 +5,7 @@ import { joinUrl } from "./base-url.ts";
5
5
  import { callableInstance } from "./config.ts";
6
6
  import type { ErrorClass, LoadedConfig, ResolvedInstance } from "./config.ts";
7
7
  import { KeyPool, KeyPoolExhausted, maskKey, type KeyState } from "./key-pool.ts";
8
- import { UsageStore, type QuotaReservation } from "./key-quota.ts";
8
+ import { QuotaStorageError, UsageStore, type QuotaReservation } from "./key-quota.ts";
9
9
  import type { PresetId } from "./presets.ts";
10
10
  import { resolveSecret } from "./secrets.ts";
11
11
 
@@ -34,11 +34,13 @@ export class ProviderError extends Error {
34
34
  readonly instance: string;
35
35
  readonly status?: number;
36
36
  readonly code: ErrorClass;
37
+ readonly quotaStorageError?: QuotaStorageError;
37
38
  readonly retryAfter?: number;
38
39
  readonly requestId?: string;
39
40
  /** 链上没有尝试的实例,failover 提前结束或取消时一并带出。 */
40
41
  readonly unattempted: ProviderSkip[];
41
- /** 链上逐次尝试的结果,按发生顺序排列,只保留定位信息与错误摘要。 */
42
+ readonly skipped: string[];
43
+ /** 记录每个失败候选及失败阶段,按实际顺序排列。 */
42
44
  readonly attempts: ProviderAttempt[];
43
45
 
44
46
  constructor(init: {
@@ -46,9 +48,11 @@ export class ProviderError extends Error {
46
48
  code: ErrorClass;
47
49
  message: string;
48
50
  status?: number;
51
+ quotaStorageError?: QuotaStorageError;
49
52
  retryAfter?: number;
50
53
  requestId?: string;
51
54
  unattempted?: ProviderSkip[];
55
+ skipped?: string[];
52
56
  attempts?: ProviderAttempt[];
53
57
  }) {
54
58
  super(init.message);
@@ -56,9 +60,11 @@ export class ProviderError extends Error {
56
60
  this.instance = init.instance;
57
61
  this.code = init.code;
58
62
  this.status = init.status;
63
+ this.quotaStorageError = init.quotaStorageError;
59
64
  this.retryAfter = init.retryAfter;
60
65
  this.requestId = init.requestId;
61
66
  this.unattempted = init.unattempted ?? [];
67
+ this.skipped = init.skipped ?? [];
62
68
  this.attempts = init.attempts ?? [];
63
69
  }
64
70
  }
@@ -67,6 +73,8 @@ export class ProviderError extends Error {
67
73
  export interface ProviderAttempt {
68
74
  instance: string;
69
75
  provider: PresetId;
76
+ /** 失败发生在构造参数、本地准备还是业务请求发出之后。 */
77
+ stage: "build" | "prepare" | "request";
70
78
  code: ErrorClass;
71
79
  status?: number;
72
80
  message: string;
@@ -114,6 +122,8 @@ export interface ProviderResponse<T = unknown> {
114
122
  rateLimit?: RateLimitInfo;
115
123
  /** 实际使用凭证的摘要。 */
116
124
  keyMasked?: string;
125
+ /** 此前失败的候选实例,仅供本地诊断。 */
126
+ attempts?: ProviderAttempt[];
117
127
  /** 换过实例后成功。 */
118
128
  degraded?: boolean;
119
129
  }
@@ -126,6 +136,7 @@ export interface HttpClientOptions {
126
136
  clock?: () => number;
127
137
  /** Cloudflare OAuth 令牌来源;仅在 cloudflare sdk 实例未配置静态 keys 时使用。 */
128
138
  cloudflareOAuth?: { accessToken(): Promise<string> };
139
+ onInstanceFailure?: (failure: ProviderAttempt) => void;
129
140
  /** 按密钥的调用次数限额存储;省略时使用仅内存实例。 */
130
141
  usage?: UsageStore;
131
142
  }
@@ -307,6 +318,7 @@ export class HttpClient {
307
318
  private readonly fetchImpl: typeof globalThis.fetch;
308
319
  private readonly clock: () => number;
309
320
  private readonly cloudflareOAuth?: { accessToken(): Promise<string> };
321
+ private readonly onInstanceFailure?: HttpClientOptions["onInstanceFailure"];
310
322
  private readonly usage: UsageStore;
311
323
  private readonly pools = new Map<string, { signature: string; pool: KeyPool }>();
312
324
  private readonly semaphores = new Map<string, Semaphore>();
@@ -319,6 +331,7 @@ export class HttpClient {
319
331
  this.fetchImpl = options.fetch ?? globalThis.fetch;
320
332
  this.clock = options.clock ?? Date.now;
321
333
  this.cloudflareOAuth = options.cloudflareOAuth;
334
+ this.onInstanceFailure = options.onInstanceFailure;
322
335
  this.usage = options.usage ?? new UsageStore({ clock: this.clock });
323
336
  this.instances = new Map(config.instances.map((instance) => [instance.id, instance]));
324
337
  }
@@ -327,7 +340,7 @@ export class HttpClient {
327
340
  async execute(
328
341
  chain: string[],
329
342
  build: (instance: ResolvedInstance) => RequestSpec,
330
- options: RequestOptions = {},
343
+ options: RequestOptions & { skipped?: string[] } = {},
331
344
  check?: (response: ProviderResponse) => void,
332
345
  ): Promise<ProviderResponse> {
333
346
  const candidates = chain
@@ -351,26 +364,39 @@ export class HttpClient {
351
364
 
352
365
  for (const instance of candidates) {
353
366
  if (tried >= limit) break;
354
- if (options.signal?.aborted) throw abortedRequest(instance.id, skipsOf(candidates.slice(tried)), attempts);
367
+ if (options.signal?.aborted) throw abortedRequest(instance.id, skipsOf(candidates.slice(tried)), attempts, options.skipped);
355
368
 
369
+ let spec: RequestSpec | undefined;
370
+ let dispatched = false;
356
371
  tried += 1;
357
372
  try {
358
- const response = await this.request(build(instance), options, check);
373
+ spec = build(instance);
374
+ const response = await this.request(spec, options, check, () => { dispatched = true; });
375
+ response.attempts = attempts;
359
376
  if (tried > 1) response.degraded = true;
360
377
  return response;
361
378
  } catch (error) {
379
+ const stopForStorage = (storage: QuotaStorageError) => new ProviderError({
380
+ instance: instance.id, code: "invalidRequest", message: storage.message, quotaStorageError: storage,
381
+ attempts, skipped: options.skipped, unattempted: skipsOf(candidates.slice(dispatched ? tried : tried - 1)),
382
+ });
383
+ if (error instanceof QuotaStorageError) throw stopForStorage(error);
362
384
  const failure = toProviderError(instance.id, error);
363
385
  // 取消不是供应商失败:已发生的尝试照常带出,取消本身只报一次。
364
- if (failure.code === "aborted" || options.signal?.aborted) {
365
- throw abortedRequest(instance.id, skipsOf(candidates.slice(tried)), attempts);
386
+ if (!failure.quotaStorageError && (failure.code === "aborted" || options.signal?.aborted)) {
387
+ const remaining = candidates.slice(dispatched ? tried : tried - 1);
388
+ throw abortedRequest(instance.id, skipsOf(remaining), attempts, options.skipped);
366
389
  }
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
- });
390
+ if (failure.code !== "aborted") {
391
+ const hop: ProviderAttempt = {
392
+ stage: dispatched ? "request" : spec ? "prepare" : "build",
393
+ instance: instance.id, provider: instance.preset.id,
394
+ code: failure.code, status: failure.status, message: failure.message,
395
+ };
396
+ attempts.push(hop);
397
+ this.onInstanceFailure?.(hop);
398
+ }
399
+ if (failure.quotaStorageError) throw stopForStorage(failure.quotaStorageError);
374
400
  lastError = failure;
375
401
  if (!this.shouldContinue(instance, failure)) break;
376
402
  }
@@ -386,6 +412,7 @@ export class HttpClient {
386
412
  retryAfter: lastError.retryAfter,
387
413
  requestId: lastError.requestId,
388
414
  message: lastError.message,
415
+ skipped: options.skipped,
389
416
  attempts,
390
417
  });
391
418
  }
@@ -399,6 +426,7 @@ export class HttpClient {
399
426
  message: aggregateMessage(remaining, summary),
400
427
  requestId: lastError?.requestId,
401
428
  unattempted: remaining,
429
+ skipped: options.skipped,
402
430
  attempts,
403
431
  });
404
432
  }
@@ -408,16 +436,10 @@ export class HttpClient {
408
436
  spec: RequestSpec,
409
437
  options: RequestOptions = {},
410
438
  check?: (response: ProviderResponse) => void,
439
+ onDispatch?: () => void,
411
440
  ): Promise<ProviderResponse> {
412
441
  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
- ) {
442
+ if (instance.usesCloudflareOAuth && this.cloudflareOAuth) {
421
443
  let token: string;
422
444
  try {
423
445
  token = await this.cloudflareOAuth.accessToken();
@@ -428,10 +450,11 @@ export class HttpClient {
428
450
  message: errorMessage(error),
429
451
  });
430
452
  }
431
- const response = await this.attempt(spec, token, options);
453
+ const response = await this.attempt(spec, token, options, onDispatch);
432
454
  check?.(response);
433
455
  return response;
434
456
  }
457
+ const keys = this.resolveKeys(instance);
435
458
  const pool = this.poolFor(instance, keys);
436
459
  const attempted = new Set<string>();
437
460
  const quotaBlocked = new Set<string>();
@@ -447,6 +470,10 @@ export class HttpClient {
447
470
  key = picked.key;
448
471
  reservation = picked.reservation;
449
472
  } catch (error) {
473
+ if (error instanceof QuotaStorageError) {
474
+ if (lastError) throw new ProviderError({ ...lastError, message: lastError.message, quotaStorageError: error });
475
+ throw error;
476
+ }
450
477
  if (error instanceof KeyPoolExhausted && quotaBlocked.size > 0 && !lastError && instance.keyQuota) {
451
478
  throw new ProviderError({
452
479
  instance: instance.id,
@@ -458,12 +485,12 @@ export class HttpClient {
458
485
  }
459
486
 
460
487
  let sameKeyRetries = 0;
461
- let settled = false;
488
+ let settlementStarted = false;
462
489
  try {
463
490
  for (;;) {
464
491
  let response: ProviderResponse;
465
492
  try {
466
- response = await this.attempt(spec, key, options);
493
+ response = await this.attempt(spec, key, options, onDispatch);
467
494
  check?.(response);
468
495
  } catch (error) {
469
496
  const failure = toProviderError(instance.id, error);
@@ -477,21 +504,26 @@ export class HttpClient {
477
504
  }
478
505
 
479
506
  // 超时时请求可能已到达上游并计费,保守计入额度;其他明确未计费错误释放预占。
480
- settled = true;
481
- if (failure.code === "timeout") reservation?.commit();
482
- else reservation?.release();
507
+ settlementStarted = true;
508
+ try {
509
+ if (failure.code === "timeout") reservation?.commit();
510
+ else reservation?.release();
511
+ } catch (storage) {
512
+ if (!(storage instanceof QuotaStorageError)) throw storage;
513
+ throw new ProviderError({ ...failure, message: failure.message, quotaStorageError: storage });
514
+ }
483
515
 
484
516
  if (!pool || !ROTATABLE.has(failure.code)) throw failure;
485
517
  break;
486
518
  }
487
519
 
488
520
  if (pool && key !== undefined) pool.markSuccess(key);
489
- settled = true;
521
+ settlementStarted = true;
490
522
  reservation?.commit();
491
523
  return response;
492
524
  }
493
525
  } finally {
494
- if (!settled) reservation?.release();
526
+ if (!settlementStarted) reservation?.release();
495
527
  }
496
528
  }
497
529
  }
@@ -511,12 +543,7 @@ export class HttpClient {
511
543
  attempted.add(key);
512
544
  return { key };
513
545
  }
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
- }
546
+ const reservation = this.usage.tryReserve(instance.preset.id, key, instance.keyQuota);
520
547
  if (reservation) {
521
548
  attempted.add(key);
522
549
  return { key, reservation };
@@ -624,6 +651,7 @@ export class HttpClient {
624
651
  spec: RequestSpec,
625
652
  key: string | undefined,
626
653
  options: RequestOptions,
654
+ onDispatch?: () => void,
627
655
  ): Promise<ProviderResponse> {
628
656
  const instance = spec.instance;
629
657
  let release: (() => void) | undefined;
@@ -643,6 +671,7 @@ export class HttpClient {
643
671
  }, timeoutMs);
644
672
  options.signal?.addEventListener("abort", onCallerAbort, { once: true });
645
673
  const request = this.buildRequest(spec, key);
674
+ onDispatch?.();
646
675
  const response = await this.fetchImpl(request.url, {
647
676
  method: spec.method ?? "GET",
648
677
  headers: request.headers,
@@ -716,8 +745,9 @@ function abortedRequest(
716
745
  instance: string,
717
746
  remaining: ProviderSkip[] = [],
718
747
  attempts: ProviderAttempt[] = [],
748
+ skipped: string[] = [],
719
749
  ): ProviderError {
720
- return new ProviderError({ instance, code: "aborted", message: "请求已取消", unattempted: remaining, attempts });
750
+ return new ProviderError({ instance, code: "aborted", message: "请求已取消", unattempted: remaining, attempts, skipped });
721
751
  }
722
752
 
723
753
  /** 把链上剩下的实例映射成实例与供应商,用于失败输出。 */