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/key-pool.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import type { ErrorClass } from "./config.ts";
|
|
2
|
+
|
|
3
|
+
/** 会让凭证进入冷却的错误类,与 plan 的 AUTH / QUOTA / RATE_LIMIT 对应。 */
|
|
4
|
+
export type CooldownClass = "AUTH" | "QUOTA" | "RATE_LIMIT";
|
|
5
|
+
|
|
6
|
+
const COOLDOWN_CLASSES: Readonly<Record<ErrorClass, CooldownClass | undefined>> = {
|
|
7
|
+
auth: "AUTH",
|
|
8
|
+
quota: "QUOTA",
|
|
9
|
+
rateLimit: "RATE_LIMIT",
|
|
10
|
+
server: undefined,
|
|
11
|
+
network: undefined,
|
|
12
|
+
timeout: undefined,
|
|
13
|
+
invalidRequest: undefined,
|
|
14
|
+
aborted: undefined,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/** 错误类对应的冷却分类;不进冷却的错误类返回 undefined。 */
|
|
18
|
+
export function cooldownClassFor(errorClass: ErrorClass): CooldownClass | undefined {
|
|
19
|
+
return COOLDOWN_CLASSES[errorClass];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 本次请求里池内凭证都已尝试过。 */
|
|
23
|
+
export class KeyPoolExhausted extends Error {
|
|
24
|
+
readonly size: number;
|
|
25
|
+
|
|
26
|
+
constructor(size: number) {
|
|
27
|
+
super(`本次请求的所有凭证都已尝试(池内共 ${size} 个)`);
|
|
28
|
+
this.name = "KeyPoolExhausted";
|
|
29
|
+
this.size = size;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 凭证摘要,日志与面板只显示前四位。 */
|
|
34
|
+
export function maskKey(key: string): string {
|
|
35
|
+
return key.length > 6 ? `${key.slice(0, 4)}***` : "***";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 凭证状态快照,供面板与测试读取。 */
|
|
39
|
+
export interface KeyState {
|
|
40
|
+
masked: string;
|
|
41
|
+
cooling: boolean;
|
|
42
|
+
cooldownSecondsLeft: number;
|
|
43
|
+
reason?: CooldownClass;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface KeyPoolOptions {
|
|
47
|
+
/** 没有 Retry-After 时的冷却秒数。 */
|
|
48
|
+
cooldownSeconds?: number;
|
|
49
|
+
clock?: () => number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface KeyEntry {
|
|
53
|
+
key: string;
|
|
54
|
+
cooldownUntil: number;
|
|
55
|
+
reason?: CooldownClass;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 凭证池:去重、轮询、冷却只影响顺序,本次请求已试过的凭证跳过。 */
|
|
59
|
+
export class KeyPool {
|
|
60
|
+
readonly size: number;
|
|
61
|
+
/** 去重时被丢弃的凭证个数。 */
|
|
62
|
+
readonly duplicates: number;
|
|
63
|
+
|
|
64
|
+
private readonly entries: KeyEntry[] = [];
|
|
65
|
+
private readonly cooldownSeconds: number;
|
|
66
|
+
private readonly clock: () => number;
|
|
67
|
+
private cursor = 0;
|
|
68
|
+
|
|
69
|
+
constructor(keys: Iterable<string>, options: KeyPoolOptions = {}) {
|
|
70
|
+
this.cooldownSeconds = options.cooldownSeconds ?? 600;
|
|
71
|
+
this.clock = options.clock ?? Date.now;
|
|
72
|
+
|
|
73
|
+
const seen = new Set<string>();
|
|
74
|
+
let duplicates = 0;
|
|
75
|
+
for (const raw of keys) {
|
|
76
|
+
const key = raw.trim();
|
|
77
|
+
if (!key) continue;
|
|
78
|
+
if (seen.has(key)) {
|
|
79
|
+
duplicates += 1;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
seen.add(key);
|
|
83
|
+
this.entries.push({ key, cooldownUntil: 0 });
|
|
84
|
+
}
|
|
85
|
+
this.size = this.entries.length;
|
|
86
|
+
this.duplicates = duplicates;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 取本次请求下一个还没试过的凭证;冷却只改变顺序,不拒绝请求。 */
|
|
90
|
+
acquire(attempted: Iterable<string> = []): string {
|
|
91
|
+
const tried = new Set(attempted);
|
|
92
|
+
const candidates = this.entries.filter((entry) => !tried.has(entry.key));
|
|
93
|
+
if (candidates.length === 0) throw new KeyPoolExhausted(this.size);
|
|
94
|
+
|
|
95
|
+
const now = this.clock();
|
|
96
|
+
for (let offset = 0; offset < this.entries.length; offset++) {
|
|
97
|
+
const position = (this.cursor + offset) % this.entries.length;
|
|
98
|
+
const entry = this.entries[position];
|
|
99
|
+
if (!entry || tried.has(entry.key) || entry.cooldownUntil > now) continue;
|
|
100
|
+
this.cursor = (position + 1) % this.entries.length;
|
|
101
|
+
return entry.key;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// 全部在冷却期内,退到最早到期的一个,仍然放行。
|
|
105
|
+
return candidates.reduce((left, right) => (right.cooldownUntil < left.cooldownUntil ? right : left)).key;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 冷却类失败让凭证进入冷却;Retry-After 优先,其次实例冷却时长。 */
|
|
109
|
+
markFailure(key: string, errorClass: ErrorClass, retryAfterSeconds?: number): void {
|
|
110
|
+
const entry = this.require(key);
|
|
111
|
+
const reason = cooldownClassFor(errorClass);
|
|
112
|
+
if (!reason) return;
|
|
113
|
+
const seconds = retryAfterSeconds ?? this.cooldownSeconds;
|
|
114
|
+
entry.cooldownUntil = this.clock() + Math.max(0, seconds) * 1000;
|
|
115
|
+
entry.reason = reason;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 成功后立即清除冷却。 */
|
|
119
|
+
markSuccess(key: string): void {
|
|
120
|
+
const entry = this.require(key);
|
|
121
|
+
entry.cooldownUntil = 0;
|
|
122
|
+
entry.reason = undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 当前池内凭证状态;凭证值已打码。 */
|
|
126
|
+
snapshot(): KeyState[] {
|
|
127
|
+
const now = this.clock();
|
|
128
|
+
return this.entries.map((entry) => {
|
|
129
|
+
const cooling = entry.cooldownUntil > now;
|
|
130
|
+
return {
|
|
131
|
+
masked: maskKey(entry.key),
|
|
132
|
+
cooling,
|
|
133
|
+
cooldownSecondsLeft: cooling ? Math.round((entry.cooldownUntil - now) / 1000) : 0,
|
|
134
|
+
reason: cooling ? entry.reason : undefined,
|
|
135
|
+
};
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private require(key: string): KeyEntry {
|
|
140
|
+
const entry = this.entries.find((item) => item.key === key);
|
|
141
|
+
if (!entry) throw new Error(`凭证不在池内:${maskKey(key)}`);
|
|
142
|
+
return entry;
|
|
143
|
+
}
|
|
144
|
+
}
|
package/src/key-quota.ts
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
openSync,
|
|
7
|
+
readFileSync,
|
|
8
|
+
renameSync,
|
|
9
|
+
statSync,
|
|
10
|
+
unlinkSync,
|
|
11
|
+
writeFileSync,
|
|
12
|
+
} from "node:fs";
|
|
13
|
+
import { dirname } from "node:path";
|
|
14
|
+
import { maskKey } from "./key-pool.ts";
|
|
15
|
+
import type { PresetId } from "./presets.ts";
|
|
16
|
+
import { resolveSecret } from "./secrets.ts";
|
|
17
|
+
|
|
18
|
+
/** 单密钥调用限额配置。 */
|
|
19
|
+
export interface KeyQuotaConfig {
|
|
20
|
+
/** 每个周期内允许的最大调用次数(正整数)。 */
|
|
21
|
+
limit: number;
|
|
22
|
+
/** 周期:自然周期 day / week / month / year,或固定时长如 24h / 7d / 30d / 2w。 */
|
|
23
|
+
period: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type CalendarPeriod = "day" | "week" | "month" | "year";
|
|
27
|
+
|
|
28
|
+
export type ParsedQuotaPeriod =
|
|
29
|
+
| { kind: "calendar"; unit: CalendarPeriod; canonical: CalendarPeriod }
|
|
30
|
+
| { kind: "duration"; amount: number; unit: "h" | "d" | "w"; durationMs: number; canonical: string };
|
|
31
|
+
|
|
32
|
+
const CALENDAR_PERIODS: ReadonlySet<string> = new Set<CalendarPeriod>(["day", "week", "month", "year"]);
|
|
33
|
+
|
|
34
|
+
const DURATION_PATTERN = /^([1-9]\d*)(h|d|w)$/;
|
|
35
|
+
|
|
36
|
+
const UNIT_MS: Readonly<Record<"h" | "d" | "w", number>> = {
|
|
37
|
+
h: 60 * 60 * 1000,
|
|
38
|
+
d: 24 * 60 * 60 * 1000,
|
|
39
|
+
w: 7 * 24 * 60 * 60 * 1000,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** 固定时长上限(10 年),避免异常大数导致时间戳溢出。 */
|
|
43
|
+
const MAX_DURATION_MS = 3650 * 24 * 60 * 60 * 1000;
|
|
44
|
+
|
|
45
|
+
/** 解析并规范化限额周期;非法值返回 undefined。 */
|
|
46
|
+
export function parseQuotaPeriod(raw: string): ParsedQuotaPeriod | undefined {
|
|
47
|
+
const text = raw.trim().toLowerCase();
|
|
48
|
+
if (!text) return undefined;
|
|
49
|
+
if (CALENDAR_PERIODS.has(text)) {
|
|
50
|
+
const unit = text as CalendarPeriod;
|
|
51
|
+
return { kind: "calendar", unit, canonical: unit };
|
|
52
|
+
}
|
|
53
|
+
const match = DURATION_PATTERN.exec(text);
|
|
54
|
+
if (!match) return undefined;
|
|
55
|
+
const amount = Number(match[1]);
|
|
56
|
+
const unit = match[2] as "h" | "d" | "w";
|
|
57
|
+
if (!Number.isSafeInteger(amount) || amount < 1) return undefined;
|
|
58
|
+
const durationMs = amount * UNIT_MS[unit];
|
|
59
|
+
if (!Number.isFinite(durationMs) || durationMs > MAX_DURATION_MS) return undefined;
|
|
60
|
+
return { kind: "duration", amount, unit, durationMs, canonical: `${amount}${unit}` };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 将规范化后的周期翻译为简短中文标签。 */
|
|
64
|
+
export function formatQuotaPeriod(period: string): string {
|
|
65
|
+
const parsed = parseQuotaPeriod(period);
|
|
66
|
+
if (!parsed) return period;
|
|
67
|
+
if (parsed.kind === "calendar") {
|
|
68
|
+
switch (parsed.unit) {
|
|
69
|
+
case "day":
|
|
70
|
+
return "自然日";
|
|
71
|
+
case "week":
|
|
72
|
+
return "自然周";
|
|
73
|
+
case "month":
|
|
74
|
+
return "自然月";
|
|
75
|
+
case "year":
|
|
76
|
+
return "自然年";
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
switch (parsed.unit) {
|
|
80
|
+
case "h":
|
|
81
|
+
return `${parsed.amount}小时`;
|
|
82
|
+
case "d":
|
|
83
|
+
return `${parsed.amount}天`;
|
|
84
|
+
case "w":
|
|
85
|
+
return `${parsed.amount}周`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function pad2(value: number): string {
|
|
90
|
+
return String(value).padStart(2, "0");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 格式化本地重置时间,供错误提示与设置面板展示。 */
|
|
94
|
+
export function formatResetTime(timestamp: number): string {
|
|
95
|
+
const date = new Date(timestamp);
|
|
96
|
+
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface QuotaWindow {
|
|
100
|
+
windowKey: string;
|
|
101
|
+
windowStart: number;
|
|
102
|
+
windowEnd: number;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 计算给定时间点对应的自然周期窗口(按本地时区 00:00 对齐)。 */
|
|
106
|
+
export function calendarWindow(unit: CalendarPeriod, now: number): QuotaWindow {
|
|
107
|
+
const date = new Date(now);
|
|
108
|
+
const year = date.getFullYear();
|
|
109
|
+
const month = date.getMonth();
|
|
110
|
+
const day = date.getDate();
|
|
111
|
+
|
|
112
|
+
if (unit === "day") {
|
|
113
|
+
const start = new Date(year, month, day, 0, 0, 0, 0);
|
|
114
|
+
const end = new Date(year, month, day + 1, 0, 0, 0, 0);
|
|
115
|
+
return {
|
|
116
|
+
windowKey: `day:${year}-${pad2(month + 1)}-${pad2(day)}`,
|
|
117
|
+
windowStart: start.getTime(),
|
|
118
|
+
windowEnd: end.getTime(),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (unit === "week") {
|
|
123
|
+
// 周一 00:00 作为自然周起点。
|
|
124
|
+
const offset = (date.getDay() + 6) % 7;
|
|
125
|
+
const start = new Date(year, month, day - offset, 0, 0, 0, 0);
|
|
126
|
+
const end = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 7, 0, 0, 0, 0);
|
|
127
|
+
return {
|
|
128
|
+
windowKey: `week:${start.getFullYear()}-${pad2(start.getMonth() + 1)}-${pad2(start.getDate())}`,
|
|
129
|
+
windowStart: start.getTime(),
|
|
130
|
+
windowEnd: end.getTime(),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (unit === "month") {
|
|
135
|
+
const start = new Date(year, month, 1, 0, 0, 0, 0);
|
|
136
|
+
const end = new Date(year, month + 1, 1, 0, 0, 0, 0);
|
|
137
|
+
return {
|
|
138
|
+
windowKey: `month:${year}-${pad2(month + 1)}`,
|
|
139
|
+
windowStart: start.getTime(),
|
|
140
|
+
windowEnd: end.getTime(),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const start = new Date(year, 0, 1, 0, 0, 0, 0);
|
|
145
|
+
const end = new Date(year + 1, 0, 1, 0, 0, 0, 0);
|
|
146
|
+
return {
|
|
147
|
+
windowKey: `year:${year}`,
|
|
148
|
+
windowStart: start.getTime(),
|
|
149
|
+
windowEnd: end.getTime(),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** 密钥指纹:只落盘 SHA-256 哈希,不在用量文件里保存明文密钥。 */
|
|
154
|
+
export function keyFingerprint(presetId: PresetId, resolvedKey: string): string {
|
|
155
|
+
return createHash("sha256").update(`${presetId}\u0000${resolvedKey}`).digest("hex");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
interface StoredKeyUsage {
|
|
159
|
+
preset: PresetId;
|
|
160
|
+
masked: string;
|
|
161
|
+
period: string;
|
|
162
|
+
windowKey: string;
|
|
163
|
+
windowStart: number;
|
|
164
|
+
windowEnd: number;
|
|
165
|
+
count: number;
|
|
166
|
+
updatedAt: number;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
interface StoredUsageFile {
|
|
170
|
+
version: 1;
|
|
171
|
+
keys: Record<string, StoredKeyUsage>;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** 单密钥在当前周期的用量快照。 */
|
|
175
|
+
export interface KeyUsageSnapshot {
|
|
176
|
+
masked: string;
|
|
177
|
+
used: number;
|
|
178
|
+
inFlight: number;
|
|
179
|
+
limit: number;
|
|
180
|
+
remaining: number;
|
|
181
|
+
exhausted: boolean;
|
|
182
|
+
period: string;
|
|
183
|
+
windowStart?: number;
|
|
184
|
+
windowEnd?: number;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 单次请求的配额预占句柄;发送成功或超时后提交,未计费失败或取消时释放。 */
|
|
188
|
+
export interface QuotaReservation {
|
|
189
|
+
commit(): void;
|
|
190
|
+
release(): void;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export interface UsageStoreOptions {
|
|
194
|
+
/** 用量落盘路径;省略时仅在内存中保存,便于单测隔离。 */
|
|
195
|
+
filePath?: string;
|
|
196
|
+
clock?: () => number;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
200
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function emptyUsageFile(): StoredUsageFile {
|
|
204
|
+
return { version: 1, keys: {} };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function parseStoredEntry(value: unknown): StoredKeyUsage | undefined {
|
|
208
|
+
if (!isRecord(value)) return undefined;
|
|
209
|
+
if (
|
|
210
|
+
typeof value.preset !== "string"
|
|
211
|
+
|| typeof value.masked !== "string"
|
|
212
|
+
|| typeof value.period !== "string"
|
|
213
|
+
|| typeof value.windowKey !== "string"
|
|
214
|
+
|| typeof value.windowStart !== "number"
|
|
215
|
+
|| typeof value.windowEnd !== "number"
|
|
216
|
+
|| typeof value.count !== "number"
|
|
217
|
+
|| typeof value.updatedAt !== "number"
|
|
218
|
+
) {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
if (!Number.isInteger(value.count) || value.count < 0) return undefined;
|
|
222
|
+
return {
|
|
223
|
+
preset: value.preset as PresetId,
|
|
224
|
+
masked: value.masked,
|
|
225
|
+
period: value.period,
|
|
226
|
+
windowKey: value.windowKey,
|
|
227
|
+
windowStart: value.windowStart,
|
|
228
|
+
windowEnd: value.windowEnd,
|
|
229
|
+
count: value.count,
|
|
230
|
+
updatedAt: value.updatedAt,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function fileSignature(path: string): string {
|
|
235
|
+
try {
|
|
236
|
+
const stats = statSync(path);
|
|
237
|
+
return `${stats.ino}:${stats.mtimeMs}:${stats.size}`;
|
|
238
|
+
} catch {
|
|
239
|
+
return "missing";
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** 按密钥统计与硬拦截调用次数,支持自然周期与自定义固定周期轮转。 */
|
|
244
|
+
export class UsageStore {
|
|
245
|
+
readonly filePath?: string;
|
|
246
|
+
private readonly clock: () => number;
|
|
247
|
+
private readonly inFlight = new Map<string, number>();
|
|
248
|
+
private memory: StoredUsageFile = emptyUsageFile();
|
|
249
|
+
private cache?: { signature: string; data: StoredUsageFile };
|
|
250
|
+
|
|
251
|
+
constructor(options: UsageStoreOptions = {}) {
|
|
252
|
+
this.filePath = options.filePath;
|
|
253
|
+
this.clock = options.clock ?? Date.now;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** 同步检查并预占 1 次配额;已达上限时返回 undefined,阻止超额请求发出。 */
|
|
257
|
+
tryReserve(presetId: PresetId, resolvedKey: string, quota: KeyQuotaConfig): QuotaReservation | undefined {
|
|
258
|
+
const parsed = this.requirePeriod(quota.period);
|
|
259
|
+
const fp = keyFingerprint(presetId, resolvedKey);
|
|
260
|
+
const now = this.clock();
|
|
261
|
+
const data = this.readFile();
|
|
262
|
+
const active = this.resolveActive(data.keys[fp], parsed, now);
|
|
263
|
+
const inflight = this.inFlight.get(fp) ?? 0;
|
|
264
|
+
|
|
265
|
+
if (active.count + inflight >= quota.limit) return undefined;
|
|
266
|
+
|
|
267
|
+
this.inFlight.set(fp, inflight + 1);
|
|
268
|
+
let settled = false;
|
|
269
|
+
|
|
270
|
+
const decrementInFlight = (): void => {
|
|
271
|
+
const next = (this.inFlight.get(fp) ?? 1) - 1;
|
|
272
|
+
if (next > 0) this.inFlight.set(fp, next);
|
|
273
|
+
else this.inFlight.delete(fp);
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
commit: () => {
|
|
278
|
+
if (settled) return;
|
|
279
|
+
settled = true;
|
|
280
|
+
try {
|
|
281
|
+
this.mutateEntry(fp, presetId, resolvedKey, parsed, (current) => current + 1);
|
|
282
|
+
} finally {
|
|
283
|
+
decrementInFlight();
|
|
284
|
+
}
|
|
285
|
+
},
|
|
286
|
+
release: () => {
|
|
287
|
+
if (settled) return;
|
|
288
|
+
settled = true;
|
|
289
|
+
decrementInFlight();
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** 手动校准或清零某把密钥在当前周期的已用次数。 */
|
|
295
|
+
setUsage(presetId: PresetId, resolvedKey: string, quota: KeyQuotaConfig, count: number): KeyUsageSnapshot {
|
|
296
|
+
if (!Number.isInteger(count) || count < 0) {
|
|
297
|
+
throw new Error("已用次数必须是不小于 0 的整数");
|
|
298
|
+
}
|
|
299
|
+
const parsed = this.requirePeriod(quota.period);
|
|
300
|
+
const fp = keyFingerprint(presetId, resolvedKey);
|
|
301
|
+
this.mutateEntry(fp, presetId, resolvedKey, parsed, () => count);
|
|
302
|
+
return this.snapshotOne(presetId, resolvedKey, quota);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** 读取单把密钥在当前周期的用量快照。 */
|
|
306
|
+
snapshotOne(presetId: PresetId, resolvedKey: string, quota: KeyQuotaConfig): KeyUsageSnapshot {
|
|
307
|
+
return this.snapshot(presetId, [resolvedKey], quota)[0]!;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** 读取一组已解析密钥在当前周期的用量快照。 */
|
|
311
|
+
snapshot(presetId: PresetId, resolvedKeys: readonly string[], quota: KeyQuotaConfig): KeyUsageSnapshot[] {
|
|
312
|
+
const parsed = this.requirePeriod(quota.period);
|
|
313
|
+
const now = this.clock();
|
|
314
|
+
const data = this.readFile();
|
|
315
|
+
return resolvedKeys.map((key) => {
|
|
316
|
+
const fp = keyFingerprint(presetId, key);
|
|
317
|
+
const active = this.resolveActive(data.keys[fp], parsed, now);
|
|
318
|
+
const inflight = this.inFlight.get(fp) ?? 0;
|
|
319
|
+
const used = active.count;
|
|
320
|
+
const remaining = Math.max(0, quota.limit - used - inflight);
|
|
321
|
+
return {
|
|
322
|
+
masked: maskKey(key),
|
|
323
|
+
used,
|
|
324
|
+
inFlight: inflight,
|
|
325
|
+
limit: quota.limit,
|
|
326
|
+
remaining,
|
|
327
|
+
exhausted: used + inflight >= quota.limit,
|
|
328
|
+
period: parsed.canonical,
|
|
329
|
+
windowStart: active.windowStart,
|
|
330
|
+
windowEnd: active.windowEnd,
|
|
331
|
+
};
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** 实例下所有密钥都达限额时的错误说明,附带周期与最早重置时间。 */
|
|
336
|
+
exhaustedMessage(
|
|
337
|
+
instanceId: string,
|
|
338
|
+
presetId: PresetId,
|
|
339
|
+
resolvedKeys: readonly string[],
|
|
340
|
+
quota: KeyQuotaConfig,
|
|
341
|
+
): string {
|
|
342
|
+
const unique = [...new Set(resolvedKeys)];
|
|
343
|
+
const items = this.snapshot(presetId, unique, quota);
|
|
344
|
+
const periodLabel = formatQuotaPeriod(quota.period);
|
|
345
|
+
const totalUsed = items.reduce((sum, item) => sum + item.used, 0);
|
|
346
|
+
const totalInFlight = items.reduce((sum, item) => sum + item.inFlight, 0);
|
|
347
|
+
const totalLimit = items.length * quota.limit;
|
|
348
|
+
const resets = items.map((item) => item.windowEnd).filter((value): value is number => value !== undefined);
|
|
349
|
+
const earliest = resets.length > 0 ? Math.min(...resets) : undefined;
|
|
350
|
+
const inflightHint = totalInFlight > 0 ? `,含 ${totalInFlight} 个进行中请求` : "";
|
|
351
|
+
const resetHint = earliest === undefined ? "" : `,最早 ${formatResetTime(earliest)} 重置`;
|
|
352
|
+
return `实例 ${instanceId} 所有凭证均已达到本地调用限额(${totalUsed}/${totalLimit}${inflightHint},单密钥 ${quota.limit} 次/${periodLabel}${resetHint})`;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
private requirePeriod(period: string): ParsedQuotaPeriod {
|
|
356
|
+
const parsed = parseQuotaPeriod(period);
|
|
357
|
+
if (!parsed) throw new Error(`不支持的限额周期:${period}`);
|
|
358
|
+
return parsed;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private resolveActive(
|
|
362
|
+
entry: StoredKeyUsage | undefined,
|
|
363
|
+
parsed: ParsedQuotaPeriod,
|
|
364
|
+
now: number,
|
|
365
|
+
): { count: number; windowKey?: string; windowStart?: number; windowEnd?: number } {
|
|
366
|
+
if (parsed.kind === "calendar") {
|
|
367
|
+
const window = calendarWindow(parsed.unit, now);
|
|
368
|
+
if (entry && entry.period === parsed.canonical && entry.windowKey === window.windowKey) {
|
|
369
|
+
return { count: entry.count, ...window };
|
|
370
|
+
}
|
|
371
|
+
return { count: 0, ...window };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
if (entry && entry.period === parsed.canonical && now >= entry.windowStart && now < entry.windowEnd) {
|
|
375
|
+
return {
|
|
376
|
+
count: entry.count,
|
|
377
|
+
windowKey: entry.windowKey,
|
|
378
|
+
windowStart: entry.windowStart,
|
|
379
|
+
windowEnd: entry.windowEnd,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
return { count: 0 };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
private mutateEntry(
|
|
386
|
+
fp: string,
|
|
387
|
+
presetId: PresetId,
|
|
388
|
+
resolvedKey: string,
|
|
389
|
+
parsed: ParsedQuotaPeriod,
|
|
390
|
+
updater: (current: number) => number,
|
|
391
|
+
): void {
|
|
392
|
+
const now = this.clock();
|
|
393
|
+
const data = this.readFile(true);
|
|
394
|
+
const active = this.resolveActive(data.keys[fp], parsed, now);
|
|
395
|
+
const nextCount = updater(active.count);
|
|
396
|
+
|
|
397
|
+
if (nextCount <= 0) {
|
|
398
|
+
delete data.keys[fp];
|
|
399
|
+
} else {
|
|
400
|
+
let windowStart = active.windowStart;
|
|
401
|
+
let windowEnd = active.windowEnd;
|
|
402
|
+
let windowKey = active.windowKey;
|
|
403
|
+
if (parsed.kind === "duration" && (windowStart === undefined || windowEnd === undefined || !windowKey)) {
|
|
404
|
+
windowStart = now;
|
|
405
|
+
windowEnd = now + parsed.durationMs;
|
|
406
|
+
windowKey = `${parsed.canonical}:${windowStart}`;
|
|
407
|
+
}
|
|
408
|
+
data.keys[fp] = {
|
|
409
|
+
preset: presetId,
|
|
410
|
+
masked: maskKey(resolvedKey),
|
|
411
|
+
period: parsed.canonical,
|
|
412
|
+
windowKey: windowKey!,
|
|
413
|
+
windowStart: windowStart!,
|
|
414
|
+
windowEnd: windowEnd!,
|
|
415
|
+
count: nextCount,
|
|
416
|
+
updatedAt: now,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
this.writeFile(data);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
private readFile(force = false): StoredUsageFile {
|
|
424
|
+
if (!this.filePath) {
|
|
425
|
+
return { version: 1, keys: { ...this.memory.keys } };
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const sig = fileSignature(this.filePath);
|
|
429
|
+
if (!force && this.cache?.signature === sig) {
|
|
430
|
+
return this.cache.data;
|
|
431
|
+
}
|
|
432
|
+
if (sig === "missing" || !existsSync(this.filePath)) {
|
|
433
|
+
const empty = emptyUsageFile();
|
|
434
|
+
this.cache = { signature: "missing", data: empty };
|
|
435
|
+
return empty;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const text = readFileSync(this.filePath, "utf8");
|
|
439
|
+
if (!text.trim()) {
|
|
440
|
+
const empty = emptyUsageFile();
|
|
441
|
+
this.cache = { signature: sig, data: empty };
|
|
442
|
+
return empty;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
let parsed: unknown;
|
|
446
|
+
try {
|
|
447
|
+
parsed = JSON.parse(text);
|
|
448
|
+
} catch {
|
|
449
|
+
throw new Error(`用量记录文件无法解析:${this.filePath}`);
|
|
450
|
+
}
|
|
451
|
+
if (!isRecord(parsed) || parsed.version !== 1 || !isRecord(parsed.keys)) {
|
|
452
|
+
throw new Error(`用量记录文件格式无效:${this.filePath}`);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const keys: Record<string, StoredKeyUsage> = {};
|
|
456
|
+
for (const [fp, rawEntry] of Object.entries(parsed.keys)) {
|
|
457
|
+
const entry = parseStoredEntry(rawEntry);
|
|
458
|
+
if (!entry) throw new Error(`用量记录文件包含损坏条目(${fp.slice(0, 8)}):${this.filePath}`);
|
|
459
|
+
keys[fp] = entry;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const data: StoredUsageFile = { version: 1, keys };
|
|
463
|
+
this.cache = { signature: sig, data };
|
|
464
|
+
return data;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
private writeFile(data: StoredUsageFile): void {
|
|
468
|
+
if (!this.filePath) {
|
|
469
|
+
this.memory = { version: 1, keys: { ...data.keys } };
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
mkdirSync(dirname(this.filePath), { recursive: true });
|
|
474
|
+
const temp = `${this.filePath}.${randomUUID()}.tmp`;
|
|
475
|
+
const content = `${JSON.stringify(data, null, 2)}\n`;
|
|
476
|
+
const fd = openSync(temp, "wx", 0o600);
|
|
477
|
+
try {
|
|
478
|
+
try {
|
|
479
|
+
writeFileSync(fd, content, "utf8");
|
|
480
|
+
} finally {
|
|
481
|
+
closeSync(fd);
|
|
482
|
+
}
|
|
483
|
+
renameSync(temp, this.filePath);
|
|
484
|
+
this.cache = { signature: fileSignature(this.filePath), data };
|
|
485
|
+
} finally {
|
|
486
|
+
if (existsSync(temp)) unlinkSync(temp);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** 格式化实例的限额与当前用量摘要,供设置面板与 /search status 复用;用量文件损坏时不阻断面板打开。 */
|
|
492
|
+
export function formatInstanceQuotaSummary(
|
|
493
|
+
usage: UsageStore | undefined,
|
|
494
|
+
instance: { preset: { id: PresetId }; mode: string; keys: readonly string[]; keyQuota?: KeyQuotaConfig },
|
|
495
|
+
env: NodeJS.ProcessEnv,
|
|
496
|
+
): string | undefined {
|
|
497
|
+
const quota = instance.keyQuota;
|
|
498
|
+
if (!quota) return undefined;
|
|
499
|
+
const periodLabel = formatQuotaPeriod(quota.period);
|
|
500
|
+
const rawKeys = instance.mode === "pool" ? instance.keys.slice(0, 1) : instance.keys;
|
|
501
|
+
const resolved = [
|
|
502
|
+
...new Set(
|
|
503
|
+
rawKeys
|
|
504
|
+
.map((key) => resolveSecret(key, env))
|
|
505
|
+
.filter((key): key is string => key !== undefined && key !== ""),
|
|
506
|
+
),
|
|
507
|
+
];
|
|
508
|
+
if (!usage || resolved.length === 0) {
|
|
509
|
+
return `限额 ${quota.limit}/${periodLabel}`;
|
|
510
|
+
}
|
|
511
|
+
try {
|
|
512
|
+
const items = usage.snapshot(instance.preset.id, resolved, quota);
|
|
513
|
+
if (items.length === 1) {
|
|
514
|
+
const item = items[0]!;
|
|
515
|
+
return item.exhausted
|
|
516
|
+
? `额度已满 ${item.used}/${item.limit}(${periodLabel})`
|
|
517
|
+
: `额度 ${item.used}/${item.limit}(${periodLabel})`;
|
|
518
|
+
}
|
|
519
|
+
const totalUsed = items.reduce((sum, item) => sum + item.used, 0);
|
|
520
|
+
const totalLimit = items.length * quota.limit;
|
|
521
|
+
const fullCount = items.filter((item) => item.exhausted).length;
|
|
522
|
+
if (fullCount === items.length) {
|
|
523
|
+
return `额度已满 ${totalUsed}/${totalLimit}(${periodLabel})`;
|
|
524
|
+
}
|
|
525
|
+
if (fullCount > 0) {
|
|
526
|
+
return `额度 ${totalUsed}/${totalLimit}(${periodLabel},${fullCount}/${items.length} 组已满)`;
|
|
527
|
+
}
|
|
528
|
+
return `额度 ${totalUsed}/${totalLimit}(${periodLabel})`;
|
|
529
|
+
} catch {
|
|
530
|
+
return `额度异常(${quota.limit}/${periodLabel})`;
|
|
531
|
+
}
|
|
532
|
+
}
|