@suifei/dsh-ai-team 0.4.94 → 0.4.96
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 +37 -0
- package/README.md +233 -233
- package/client.js +2 -0
- package/index.js +63 -82
- package/lib/diaglog.js +5 -3
- package/lib/host/service.js +2 -1
- package/lib/runtime/activation-budget.js +46 -46
- package/lib/runtime/failure-policy.js +157 -155
- package/lib/runtime/stop-guard.js +54 -0
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -54,6 +54,7 @@ import { describeTaskContext, describeWake, planWakes } from './lib/host/waker.j
|
|
|
54
54
|
import { describeCauseChain } from './lib/runtime/error-chain.js';
|
|
55
55
|
import { classifyWakeFailure, isMalformedTurnError } from './lib/runtime/wake-failure.js';
|
|
56
56
|
import { registerShellGuard } from './lib/runtime/shell-guard.js';
|
|
57
|
+
import { registerStopGuard } from './lib/runtime/stop-guard.js';
|
|
57
58
|
import { createActivationBudget } from './lib/runtime/activation-budget.js';
|
|
58
59
|
import { blocksActivation, probeProviderRegistration } from './lib/runtime/subagent-probe.js';
|
|
59
60
|
import { isRuntimeUnavailableFailure, resolveSubagentProviderName } from './lib/runtime/subagent-provider.js';
|
|
@@ -107,8 +108,6 @@ export const Config = z.object({
|
|
|
107
108
|
defaultWorkspace: z.string().default(''),
|
|
108
109
|
// 启动成员会话用的 subagent provider 名;留空按宿主实际注册的自动解析(默认 spawn)。
|
|
109
110
|
subagentProviderName: z.string().default('spawn'),
|
|
110
|
-
// 同一成员 30 分钟内允许的自动重建次数(失败→自愈→再失败的死循环闸门)。
|
|
111
|
-
autoReseatLimitPer30Min: z.number().step(1).min(1).max(100).default(6),
|
|
112
111
|
// 成员 shell 风险守卫:'warn' 只记诊断(默认),'block' 直接拒绝,'off' 不介入。
|
|
113
112
|
// 实机事故:成员写 serve.ps1 并用隐藏窗口拉起常驻进程,触发杀软报毒。
|
|
114
113
|
shellGuard: z.union(['off', 'warn', 'block']).default('warn'),
|
|
@@ -483,15 +482,26 @@ export function apply(ctx, config = {}) {
|
|
|
483
482
|
const runtimeUnavailable = isRuntimeUnavailableFailure(member);
|
|
484
483
|
if (member.routeStale !== true && runtimeUnavailable !== true) continue;
|
|
485
484
|
if (member.status === 'retired') continue;
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
485
|
+
// 一个成员一个会话:只有「路由过期」(Human 换了 provider/model,会话的路由在
|
|
486
|
+
// 创建时钉死)才新建会话。运行时不可用恢复后,已有会话原样复用——重新绑定同一
|
|
487
|
+
// 会话把成员拉回 running,之后照常经 subagents.sendMessage 投递(冷恢复归宿主);
|
|
488
|
+
// 还没有会话的才首次创建。
|
|
489
|
+
const reuse = member.routeStale !== true && typeof member.sessionId === 'string' && member.sessionId !== '';
|
|
490
|
+
if (reuse) {
|
|
491
|
+
void runtime.service.bindMemberSession(
|
|
492
|
+
{ actor: { kind: 'human', memberId: HUMAN_ID }, projectId: runtime.id },
|
|
493
|
+
{ memberId: member.id, sessionId: member.sessionId },
|
|
494
|
+
).then(() => {
|
|
495
|
+
diag.append({ ev: 'member.session.reused', projectId: runtime.id, memberId: member.id, sessionId: member.sessionId });
|
|
496
|
+
}).catch((error) => {
|
|
497
|
+
diag.append({ ev: 'member.route-reconcile.fail', projectId: runtime.id, memberId: member.id, message: error?.message ?? String(error) });
|
|
498
|
+
});
|
|
489
499
|
continue;
|
|
490
500
|
}
|
|
491
501
|
void activateMember({
|
|
492
502
|
payload: {
|
|
493
503
|
memberId: member.id,
|
|
494
|
-
force: true,
|
|
504
|
+
...(member.routeStale === true ? { force: true } : {}),
|
|
495
505
|
prompt: runtimeUnavailable && member.routeStale !== true
|
|
496
506
|
? '运行时已恢复(此前因 subagent provider 不可用而中断)。先读 tasks 与 thread 的当前状态,继续未完成的工作,不要重复已完成的事。'
|
|
497
507
|
: '模型/提供方已切换,会话按新路由重建。先读 tasks 与 thread 的当前状态,继续未完成的工作,不要重复已完成的事。',
|
|
@@ -781,10 +791,6 @@ export function apply(ctx, config = {}) {
|
|
|
781
791
|
// 本次请求的连续失败计数(按成员会话、10 分钟窗口)。
|
|
782
792
|
const requestAttempts = new Map();
|
|
783
793
|
const activationTasks = new Map();
|
|
784
|
-
// 自动重建预算:见 lib/runtime/activation-budget.js(issue #1 的 7 小时循环)。
|
|
785
|
-
const activationBudget = createActivationBudget({
|
|
786
|
-
limit: Number.isSafeInteger(config?.autoReseatLimitPer30Min) ? config.autoReseatLimitPer30Min : 6,
|
|
787
|
-
});
|
|
788
794
|
const pmoLastKick = new Map();
|
|
789
795
|
const pmoQuiet = new Set();
|
|
790
796
|
const pmoLastStall = new Map();
|
|
@@ -1023,10 +1029,9 @@ export function apply(ctx, config = {}) {
|
|
|
1023
1029
|
cause: causeChain,
|
|
1024
1030
|
});
|
|
1025
1031
|
console.warn('[ai-team] wake failed:', plan.memberId, error?.code ?? error?.message ?? error);
|
|
1026
|
-
//
|
|
1027
|
-
//
|
|
1028
|
-
//
|
|
1029
|
-
// 形态重建一次(重置会话),避免成员静默不再被唤醒。
|
|
1032
|
+
// 会话续接失败:不自动新建子智能体(见下方 legacySession 分支),只把成员
|
|
1033
|
+
// 记为 failed 并交给 Human;会话被占用(write handle busy)是瞬时状态,
|
|
1034
|
+
// 不算失败,下一次唤醒照常投递到同一会话。
|
|
1030
1035
|
// 注意:member 是 try 块内变量,catch 里必须从 state 取成员。
|
|
1031
1036
|
const targetMember = projectRuntime.service.state.members?.[plan.memberId];
|
|
1032
1037
|
const failureText = `${error?.code ?? ''} ${error?.message ?? String(error)}`;
|
|
@@ -1047,6 +1052,7 @@ export function apply(ctx, config = {}) {
|
|
|
1047
1052
|
|| failureCode === 'NOT_RESUMABLE'
|
|
1048
1053
|
|| failureCode === 'ENOTFOUND';
|
|
1049
1054
|
const legacySession = deadSessionPool
|
|
1055
|
+
&& classifyWakeFailure(causeChain) !== 'wake.session-busy'
|
|
1050
1056
|
&& typeof targetMember?.sessionId === 'string' && targetMember.sessionId !== '';
|
|
1051
1057
|
diag.append({
|
|
1052
1058
|
ev: 'wake.catch.probe.fail',
|
|
@@ -1056,51 +1062,27 @@ export function apply(ctx, config = {}) {
|
|
|
1056
1062
|
hasActivateMember: typeof activateMember === 'function',
|
|
1057
1063
|
});
|
|
1058
1064
|
if (legacySession) {
|
|
1059
|
-
//
|
|
1060
|
-
//
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
return;
|
|
1073
|
-
}
|
|
1065
|
+
// 一个成员一个会话(官方契约:可续接子智能体只在首次 startActivation 创建,
|
|
1066
|
+
// 之后一律 subagents.sendMessage,离线由宿主冷恢复)。原会话续接不上时插件
|
|
1067
|
+
// **不新建**子智能体:成员记为 failed(waker 不再唤醒它),给 Human 一条决策项,
|
|
1068
|
+
// 由 Human 手动重建(member.reseat)或排查宿主。实机教训:自愈重建在 il2c 两天
|
|
1069
|
+
// 建了 322 个子智能体(issue #1 也是这条路径)。
|
|
1070
|
+
diag.append({
|
|
1071
|
+
ev: 'member.session.unresumable.fail',
|
|
1072
|
+
projectId: projectRuntime.id,
|
|
1073
|
+
memberId: plan.memberId,
|
|
1074
|
+
sessionId: targetMember.sessionId,
|
|
1075
|
+
reason: plan.reason,
|
|
1076
|
+
failureCode,
|
|
1077
|
+
});
|
|
1074
1078
|
try {
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
},
|
|
1083
|
-
}, projectRuntime);
|
|
1084
|
-
diag.append({
|
|
1085
|
-
ev: 'member.autoreseat',
|
|
1086
|
-
projectId: projectRuntime.id,
|
|
1087
|
-
memberId: plan.memberId,
|
|
1088
|
-
oldSessionId: targetMember.sessionId,
|
|
1089
|
-
newSessionId: reseated?.sessionId ?? null,
|
|
1090
|
-
// 记下触发码:11-12/13 的 322 次重建事后无从区分成因。
|
|
1091
|
-
failureCode,
|
|
1092
|
-
reason: plan.reason,
|
|
1093
|
-
ok: reseated?.error === undefined,
|
|
1094
|
-
error: reseated?.error ?? null,
|
|
1095
|
-
});
|
|
1096
|
-
} catch (reseatError) {
|
|
1097
|
-
diag.append({
|
|
1098
|
-
ev: 'member.autoreseat.fail',
|
|
1099
|
-
projectId: projectRuntime.id,
|
|
1100
|
-
memberId: plan.memberId,
|
|
1101
|
-
message: reseatError?.message ?? String(reseatError),
|
|
1102
|
-
});
|
|
1103
|
-
}
|
|
1079
|
+
await projectRuntime.service.recordMemberFailure(plan.memberId, {
|
|
1080
|
+
category: 'session',
|
|
1081
|
+
code: failureCode,
|
|
1082
|
+
taskId: plan.taskId ?? null,
|
|
1083
|
+
message: `会话 ${targetMember.sessionId} 无法续接(${failureCode})。插件不会自动新建子智能体;请手动重建该成员或排查宿主。`,
|
|
1084
|
+
}, projectRuntime.id);
|
|
1085
|
+
} catch { /* ledger may be closed */ }
|
|
1104
1086
|
}
|
|
1105
1087
|
try {
|
|
1106
1088
|
await projectRuntime.service.recordWake(plan.memberId, {
|
|
@@ -1504,25 +1486,8 @@ export function apply(ctx, config = {}) {
|
|
|
1504
1486
|
if (runtime === null) return '[skillopt optimize] no active project runtime';
|
|
1505
1487
|
const jobId = 'job_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
|
1506
1488
|
const actor = { kind: 'human', memberId: HUMAN_ID };
|
|
1507
|
-
//
|
|
1508
|
-
//
|
|
1509
|
-
// 这一步让评审投递落在**新鲜会话**上,闭环才成立。
|
|
1510
|
-
try {
|
|
1511
|
-
const reviewer = Object.values(runtime.service.state.members ?? {})
|
|
1512
|
-
.find((member) => member.kind === 'agent' && (member.role === '评审' || member.name === '评审官'));
|
|
1513
|
-
if (reviewer !== undefined) {
|
|
1514
|
-
const refreshed = await activateMember({
|
|
1515
|
-
payload: {
|
|
1516
|
-
memberId: reviewer.id,
|
|
1517
|
-
force: true,
|
|
1518
|
-
prompt: '会话已刷新(评审官)。职责不变:只做 A/B 盲评,把一行 JSON 结论用 team 工具发到评审卡。',
|
|
1519
|
-
},
|
|
1520
|
-
}, runtime);
|
|
1521
|
-
diag.append({ ev: refreshed.error === undefined ? 'skillopt.reviewer.refreshed' : 'skillopt.reviewer.refresh.fail', projectId: runtime.id, memberId: reviewer.id, sessionId: refreshed.sessionId ?? null, message: refreshed.error?.message ?? null });
|
|
1522
|
-
}
|
|
1523
|
-
} catch (error) {
|
|
1524
|
-
diag.append({ ev: 'skillopt.reviewer.refresh.fail', projectId: runtime.id, message: error?.message ?? String(error) });
|
|
1525
|
-
}
|
|
1489
|
+
// 评审投递走评审官原有会话(subagents.sendMessage 负责冷恢复,0.4.88 起)。
|
|
1490
|
+
// 旧版本在每次评审前 force 重建评审官会话——每调一次就多一个子智能体。
|
|
1526
1491
|
const jobRecord = {
|
|
1527
1492
|
id: jobId,
|
|
1528
1493
|
state: 'judging',
|
|
@@ -1800,6 +1765,25 @@ export function apply(ctx, config = {}) {
|
|
|
1800
1765
|
} catch (error) {
|
|
1801
1766
|
diag.append({ ev: 'shell.guard.fail', message: error?.message ?? String(error) });
|
|
1802
1767
|
}
|
|
1768
|
+
// 停止即停:停止期间 PMO 与成员不得用宿主内置工具(send_message 等)互相唤醒或派生
|
|
1769
|
+
// 子智能体——实机停止后 PMO 收到「成员被停」通知,又用 send_message 把成员续跑了 25 分钟。
|
|
1770
|
+
let disposeStopGuard = () => {};
|
|
1771
|
+
try {
|
|
1772
|
+
const teamProjectOf = (sessionId) => {
|
|
1773
|
+
for (const runtime of booted?.runtimes?.values() ?? []) {
|
|
1774
|
+
const state = runtime.service.state;
|
|
1775
|
+
const inTeam = state.hostSessionId === sessionId
|
|
1776
|
+
|| Object.values(state.members ?? {}).some((member) => member?.sessionId === sessionId);
|
|
1777
|
+
if (!inTeam) continue;
|
|
1778
|
+
const project = state.projects?.[runtime.id];
|
|
1779
|
+
return { projectId: runtime.id, projectName: project?.name ?? '', stopped: project?.runState === 'stopped' };
|
|
1780
|
+
}
|
|
1781
|
+
return null;
|
|
1782
|
+
};
|
|
1783
|
+
disposeStopGuard = registerStopGuard({ tools: tools ?? serviceOf(ctx, 'tools'), projectOf: teamProjectOf, diag });
|
|
1784
|
+
} catch (error) {
|
|
1785
|
+
diag.append({ ev: 'stop.guard.fail', message: error?.message ?? String(error) });
|
|
1786
|
+
}
|
|
1803
1787
|
|
|
1804
1788
|
// 历史归档修复:成员是 host 的子会话,`archived-session-gate` 会沿 subagent
|
|
1805
1789
|
// 血缘上溯,父会话被归档即拒绝整条血缘 —— 回合以 {kind:'blocked'} 结束且不发
|
|
@@ -2250,11 +2234,7 @@ export function apply(ctx, config = {}) {
|
|
|
2250
2234
|
const eligible = includeAll ? member.status === 'failed' : isRuntimeUnavailableFailure(member);
|
|
2251
2235
|
if (eligible !== true) continue;
|
|
2252
2236
|
if (member.status === 'running') { skipped.push({ memberId: member.id, reason: 'running' }); continue; }
|
|
2253
|
-
|
|
2254
|
-
if (budget.allowed !== true) {
|
|
2255
|
-
skipped.push({ memberId: member.id, reason: 'budget' });
|
|
2256
|
-
continue;
|
|
2257
|
-
}
|
|
2237
|
+
// Human 点的批量恢复:显式意图,不受自动重建冷却限制。
|
|
2258
2238
|
const result = await activateMember({
|
|
2259
2239
|
payload: {
|
|
2260
2240
|
memberId: member.id,
|
|
@@ -2808,6 +2788,7 @@ export function apply(ctx, config = {}) {
|
|
|
2808
2788
|
disposed = true;
|
|
2809
2789
|
try { removeDiagSink(); } catch { /* sink already replaced */ }
|
|
2810
2790
|
try { disposeShellGuard(); } catch { /* already disposed */ }
|
|
2791
|
+
try { disposeStopGuard(); } catch { /* already disposed */ }
|
|
2811
2792
|
const cleanup = [];
|
|
2812
2793
|
for (const client of sseClients) {
|
|
2813
2794
|
try { client.res.end(); } catch { /* socket already gone */ }
|
package/lib/diaglog.js
CHANGED
|
@@ -32,11 +32,13 @@ export function isErrorEvent(ev) {
|
|
|
32
32
|
// 归档修复的**成功**行必须留在 `errors` 级别:否则「修没修」永远无法
|
|
33
33
|
// 判定(只有 boot 瞬间那一行 deferred.fail 可见)。
|
|
34
34
|
|| ev === 'host.repair.ok'
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
|| ev === 'member.
|
|
35
|
+
// 运行时恢复后复用原会话(不新建子智能体)同理:它决定「成员还会不会被唤醒」,
|
|
36
|
+
// 必须在发布默认级别可见,否则只能看到失败行而不知道有没有救回来。
|
|
37
|
+
|| ev === 'member.session.reused'
|
|
38
38
|
// Human 停止时中断了哪些成员:决定「停了之后还在跑」是不是插件的锅。
|
|
39
39
|
|| ev === 'team.interrupt'
|
|
40
|
+
// 停止期间团队会话想唤醒/派生智能体被拦下:停止是否真的停住的直接证据。
|
|
41
|
+
|| ev === 'team.stopped.blocked'
|
|
40
42
|
// 重建后旧会话有没有从工作区摘掉:决定工作区列表是否随自愈累积死会话。
|
|
41
43
|
|| ev === 'workspace.detach');
|
|
42
44
|
}
|
package/lib/host/service.js
CHANGED
|
@@ -1030,7 +1030,8 @@ export class TeamService {
|
|
|
1030
1030
|
// 之后 member.bind 就能把 ta 复活)。直接忽略,不写事件。
|
|
1031
1031
|
if (member.status === 'retired') return null;
|
|
1032
1032
|
const attempt = Number.isSafeInteger(failure.attempt) ? failure.attempt : (member.lastFailure?.attempt ?? 0) + 1;
|
|
1033
|
-
const fatal = failure.category === 'auth' || failure.category === 'billing' || failure.category === 'policy' || failure.category === 'unknown'
|
|
1033
|
+
const fatal = failure.category === 'auth' || failure.category === 'billing' || failure.category === 'policy' || failure.category === 'unknown'
|
|
1034
|
+
|| failure.category === 'session';
|
|
1034
1035
|
// Tool-argument and provider dumps can run to kilobytes; the ledger and
|
|
1035
1036
|
// the risk list only ever need a human-readable first act of the error.
|
|
1036
1037
|
const message = typeof failure.message === 'string' && failure.message.length > 400
|
|
@@ -1,46 +1,46 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 自动重建预算:把「失败 → 自愈重建 → 再失败」的死循环挡在插件这一侧。
|
|
3
|
-
*
|
|
4
|
-
* 实机报告(issue #1):一句「在吗」跑了 7 小时、派了两百多个子代理。触发链是
|
|
5
|
-
* 「唤醒失败(会话不可恢复/认证失败)→ 自动重建 → 新会话再失败 → 下一次唤醒再重建」;
|
|
6
|
-
* 只要唤醒源源不断(thread 回复、PMO 心跳),这个循环就没有上限。
|
|
7
|
-
*
|
|
8
|
-
* 这里给自动重建加一个滑动窗口额度:同一成员在 windowMs 内最多重建 limit 次,
|
|
9
|
-
* 超出后**不再自动重建**,改为写一条可见诊断并让成员保持 failed(等 Human 处理)。
|
|
10
|
-
* 正常团队工作远达不到这个阈值,只有循环才会撞上。
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
const DEFAULT_LIMIT = 6;
|
|
14
|
-
const DEFAULT_WINDOW_MS = 30 * 60 * 1000;
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* @param {{ limit?: number, windowMs?: number }} options
|
|
18
|
-
*/
|
|
19
|
-
export function createActivationBudget(options = {}) {
|
|
20
|
-
const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? options.limit : DEFAULT_LIMIT;
|
|
21
|
-
const windowMs = Number.isSafeInteger(options.windowMs) && options.windowMs > 0 ? options.windowMs : DEFAULT_WINDOW_MS;
|
|
22
|
-
/** @type {Map<string, number[]>} memberId -> 最近一次重建的时间戳 */
|
|
23
|
-
const taken = new Map();
|
|
24
|
-
return {
|
|
25
|
-
/** 记录一次重建并返回是否允许(先判后记,拒绝时不消耗额度)。 */
|
|
26
|
-
take(memberId, now = Date.now()) {
|
|
27
|
-
if (typeof memberId !== 'string' || memberId === '') return { allowed: true, count: 0 };
|
|
28
|
-
const recent = (taken.get(memberId) ?? []).filter((at) => now - at < windowMs);
|
|
29
|
-
if (recent.length >= limit) {
|
|
30
|
-
taken.set(memberId, recent);
|
|
31
|
-
return { allowed: false, count: recent.length, limit, windowMs };
|
|
32
|
-
}
|
|
33
|
-
recent.push(now);
|
|
34
|
-
taken.set(memberId, recent);
|
|
35
|
-
return { allowed: true, count: recent.length, limit, windowMs };
|
|
36
|
-
},
|
|
37
|
-
/** 只读查询,不消耗额度。 */
|
|
38
|
-
peek(memberId, now = Date.now()) {
|
|
39
|
-
const recent = (taken.get(memberId) ?? []).filter((at) => now - at < windowMs);
|
|
40
|
-
return recent.length;
|
|
41
|
-
},
|
|
42
|
-
reset(memberId) {
|
|
43
|
-
taken.delete(memberId);
|
|
44
|
-
},
|
|
45
|
-
};
|
|
46
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 自动重建预算:把「失败 → 自愈重建 → 再失败」的死循环挡在插件这一侧。
|
|
3
|
+
*
|
|
4
|
+
* 实机报告(issue #1):一句「在吗」跑了 7 小时、派了两百多个子代理。触发链是
|
|
5
|
+
* 「唤醒失败(会话不可恢复/认证失败)→ 自动重建 → 新会话再失败 → 下一次唤醒再重建」;
|
|
6
|
+
* 只要唤醒源源不断(thread 回复、PMO 心跳),这个循环就没有上限。
|
|
7
|
+
*
|
|
8
|
+
* 这里给自动重建加一个滑动窗口额度:同一成员在 windowMs 内最多重建 limit 次,
|
|
9
|
+
* 超出后**不再自动重建**,改为写一条可见诊断并让成员保持 failed(等 Human 处理)。
|
|
10
|
+
* 正常团队工作远达不到这个阈值,只有循环才会撞上。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const DEFAULT_LIMIT = 6;
|
|
14
|
+
const DEFAULT_WINDOW_MS = 30 * 60 * 1000;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {{ limit?: number, windowMs?: number }} options
|
|
18
|
+
*/
|
|
19
|
+
export function createActivationBudget(options = {}) {
|
|
20
|
+
const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? options.limit : DEFAULT_LIMIT;
|
|
21
|
+
const windowMs = Number.isSafeInteger(options.windowMs) && options.windowMs > 0 ? options.windowMs : DEFAULT_WINDOW_MS;
|
|
22
|
+
/** @type {Map<string, number[]>} memberId -> 最近一次重建的时间戳 */
|
|
23
|
+
const taken = new Map();
|
|
24
|
+
return {
|
|
25
|
+
/** 记录一次重建并返回是否允许(先判后记,拒绝时不消耗额度)。 */
|
|
26
|
+
take(memberId, now = Date.now()) {
|
|
27
|
+
if (typeof memberId !== 'string' || memberId === '') return { allowed: true, count: 0 };
|
|
28
|
+
const recent = (taken.get(memberId) ?? []).filter((at) => now - at < windowMs);
|
|
29
|
+
if (recent.length >= limit) {
|
|
30
|
+
taken.set(memberId, recent);
|
|
31
|
+
return { allowed: false, count: recent.length, limit, windowMs };
|
|
32
|
+
}
|
|
33
|
+
recent.push(now);
|
|
34
|
+
taken.set(memberId, recent);
|
|
35
|
+
return { allowed: true, count: recent.length, limit, windowMs };
|
|
36
|
+
},
|
|
37
|
+
/** 只读查询,不消耗额度。 */
|
|
38
|
+
peek(memberId, now = Date.now()) {
|
|
39
|
+
const recent = (taken.get(memberId) ?? []).filter((at) => now - at < windowMs);
|
|
40
|
+
return recent.length;
|
|
41
|
+
},
|
|
42
|
+
reset(memberId) {
|
|
43
|
+
taken.delete(memberId);
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|