@vessel-agent/agent 0.0.0-stage → 2.3.0-beta.3

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.
@@ -0,0 +1,651 @@
1
+ /**
2
+ * Conversation 预算内核(0.19 S4)。
3
+ *
4
+ * - 限额来自 Team policy(`policyFor`),默认全部不限;环检测始终开启;
5
+ * - 发送侧 `checkDelivery` 同步检查并预留 hop / 有向边;接收侧 `canStartTurn` 只读;
6
+ * - 环检测是**滑动窗口限速**:同一有向边在每个 `cooldownSeconds` 窗口内最多
7
+ * `maxRepeats` 次;越界只拒绝本次投递(带 `retry_after`),**不落持久 blocked**。
8
+ * 按整条 conversation 生命周期累积会把正常的多轮 hub-and-spoke 判死;
9
+ * - 所有检查由投递 / turn 开始触发,没有定时器或轮询;
10
+ * - 人工 override 只能抬高限额或清除;状态落 `ConversationStore`。
11
+ *
12
+ * @module @vessel-agent/agent
13
+ */
14
+
15
+ import type { TeamBudgetPolicy, TeamPolicy } from '@vessel-agent/config';
16
+ import { type Logger, noopLogger } from '@vessel-agent/core';
17
+ import {
18
+ type ConversationStore,
19
+ MAX_CONVERSATION_EDGES,
20
+ type StoredConversation,
21
+ type StoredConversationEdge,
22
+ } from './conversation-store.js';
23
+ import { errorText } from './error-text.js';
24
+ import { RESERVED_PRINCIPALS } from './team-address.js';
25
+ import {
26
+ AgentError,
27
+ type BudgetBlockReason,
28
+ type BudgetCheckResult,
29
+ type BudgetDeliveryInput,
30
+ type BudgetDimension,
31
+ type BudgetOverrideInput,
32
+ type BudgetOverrideResult,
33
+ type BudgetStatusInput,
34
+ type BudgetTurnBlockedInput,
35
+ type BudgetTurnFinishedInput,
36
+ type BudgetTurnInput,
37
+ type BudgetTurnStartedInput,
38
+ type BudgetWarning,
39
+ type ConversationBudgetEdge,
40
+ type ConversationBudgetPort,
41
+ type ConversationBudgetStatus,
42
+ } from './types.js';
43
+
44
+ export const DEFAULT_CYCLE_MAX_REPEATS = 2;
45
+ export const DEFAULT_CYCLE_COOLDOWN_SECONDS = 60;
46
+ export const DEFAULT_WARNING_THRESHOLD = 0.8;
47
+ export const MAX_STATUS_CONVERSATIONS = 20;
48
+
49
+ /** conversation_id:`conv_` + 生成器;接受的显式格式见 `isValidConversationId` */
50
+ const CONVERSATION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
51
+
52
+ /**
53
+ * 保留字:这些 from / to 不是 agent 投递,不参与环检测。
54
+ *
55
+ * 清单来自 `team-address.ts` 的保留 principal 词典(`RESERVED_PRINCIPALS`),
56
+ * 不在这里另写一份字符串列表 —— 两处各写一份就会分叉。
57
+ *
58
+ * `main` 不在此列 —— 它是 agent(role single),与其它 agent 一样走 hop / cycle /
59
+ * turns 限制。它曾被放进来,是因为人类消息的 `from` 一度就是 `main`。
60
+ */
61
+ const NON_AGENT_IDS = RESERVED_PRINCIPALS;
62
+
63
+ export function isValidConversationId(value: unknown): value is string {
64
+ return typeof value === 'string' && CONVERSATION_ID_PATTERN.test(value);
65
+ }
66
+
67
+ export function generateConversationId(newId: () => string): string {
68
+ return `conv_${newId()}`;
69
+ }
70
+
71
+ export interface ConversationBudgetOptions {
72
+ store: ConversationStore;
73
+ /** 按 origin team 解析 policy;无 team / 无 policy 时只有默认环检测 */
74
+ policyFor: (teamId?: string) => TeamPolicy | undefined;
75
+ now?: () => number;
76
+ logger?: Logger;
77
+ }
78
+
79
+ interface ResolvedLimits {
80
+ maxHops?: number;
81
+ maxTurns?: number;
82
+ maxTokens?: number;
83
+ maxWallClockMs?: number;
84
+ warningThreshold: number;
85
+ maxRepeats: number;
86
+ cooldownMs: number;
87
+ }
88
+
89
+ function positiveInteger(value: unknown): number | undefined {
90
+ if (typeof value !== 'number' || !Number.isFinite(value)) return undefined;
91
+ const floored = Math.floor(value);
92
+ return floored >= 1 ? floored : undefined;
93
+ }
94
+
95
+ /** 运行时再校验一遍:手改 team.json 的非法值按“未配置”忽略,不让整条预算失效 */
96
+ export function resolveBudgetLimits(policy: TeamPolicy | undefined): ResolvedLimits {
97
+ const budget: TeamBudgetPolicy | undefined =
98
+ policy?.budget && typeof policy.budget === 'object' ? policy.budget : undefined;
99
+ const cycle = budget?.cycle;
100
+ const thresholdRaw = budget?.warningThreshold;
101
+ const warningThreshold =
102
+ typeof thresholdRaw === 'number' &&
103
+ Number.isFinite(thresholdRaw) &&
104
+ thresholdRaw > 0 &&
105
+ thresholdRaw < 1
106
+ ? thresholdRaw
107
+ : DEFAULT_WARNING_THRESHOLD;
108
+ const maxWallClockSeconds = positiveInteger(budget?.maxWallClockSeconds);
109
+ return {
110
+ ...(positiveInteger(budget?.maxHops) !== undefined
111
+ ? { maxHops: positiveInteger(budget?.maxHops) }
112
+ : {}),
113
+ ...(positiveInteger(budget?.maxTurns) !== undefined
114
+ ? { maxTurns: positiveInteger(budget?.maxTurns) }
115
+ : {}),
116
+ ...(positiveInteger(budget?.maxTokens) !== undefined
117
+ ? { maxTokens: positiveInteger(budget?.maxTokens) }
118
+ : {}),
119
+ ...(maxWallClockSeconds !== undefined ? { maxWallClockMs: maxWallClockSeconds * 1000 } : {}),
120
+ warningThreshold,
121
+ maxRepeats: positiveInteger(cycle?.maxRepeats) ?? DEFAULT_CYCLE_MAX_REPEATS,
122
+ // 窗口必须 > 0:0 会让窗口恒空 = 关掉环检测,违反「不可关闭」。手改 team.json
123
+ // 写成 0 / 负数按未配置忽略,回落到缺省 60s。
124
+ cooldownMs: (positiveInteger(cycle?.cooldownSeconds) ?? DEFAULT_CYCLE_COOLDOWN_SECONDS) * 1000,
125
+ };
126
+ }
127
+
128
+ function isAgentId(value: string): boolean {
129
+ return value !== '' && !NON_AGENT_IDS.has(value);
130
+ }
131
+
132
+ export class ConversationBudget implements ConversationBudgetPort {
133
+ private readonly store: ConversationStore;
134
+ private readonly policyFor: (teamId?: string) => TeamPolicy | undefined;
135
+ private readonly now: () => number;
136
+ private readonly logger: Logger;
137
+ /** 进程内告警去重:conversation → dimension */
138
+ private readonly warned = new Map<string, Set<BudgetDimension>>();
139
+ /** 尚未交给 service 发布的告警 */
140
+ private readonly pendingWarnings = new Map<string, BudgetWarning[]>();
141
+ /** 接收侧 hold:conversation → agent ids(release 时返回) */
142
+ private readonly holds = new Map<string, Set<string>>();
143
+
144
+ constructor(options: ConversationBudgetOptions) {
145
+ this.store = options.store;
146
+ this.policyFor = options.policyFor;
147
+ this.now = options.now ?? Date.now;
148
+ this.logger = options.logger ?? noopLogger;
149
+ }
150
+
151
+ checkDelivery(input: BudgetDeliveryInput): BudgetCheckResult {
152
+ if (!this.store.available) return this.unavailable();
153
+ const now = this.now();
154
+ const mode = input.mode ?? 'delivery';
155
+ const existing = this.store.get(input.conversation_id);
156
+ // wake:不 ensure 新 conversation;不存在就跳过全部检查、不落记录。
157
+ if (mode === 'wake' && existing === undefined) return { ok: true };
158
+ if (
159
+ input.origin_explicit === true &&
160
+ existing?.team_id !== undefined &&
161
+ input.team_id !== undefined &&
162
+ existing.team_id !== input.team_id
163
+ ) {
164
+ return this.failed('hops', 'conversation_team_mismatch', existing.hops, null);
165
+ }
166
+ const teamId = existing?.team_id ?? input.team_id;
167
+ const limits = this.limitsFor(teamId);
168
+ // 迁移(0.42):旧版本把 cycle 越界升级成持久 blocked。cycle 现在是窗口限速,
169
+ // 读到旧标记就地清掉,本次投递按滑动窗口自行恢复(不动 store 版本、不加字段)。
170
+ if (existing?.blocked?.dimension === 'cycle') {
171
+ delete existing.blocked;
172
+ this.store.markDirty();
173
+ }
174
+ if (existing?.blocked !== undefined) {
175
+ const blocked = existing.blocked;
176
+ // wake 只做汇总唤醒,不被 blocked 拦(cycle 已不落 blocked,见上)。
177
+ if (mode !== 'wake') {
178
+ return this.failed(
179
+ blocked.dimension,
180
+ blocked.reason,
181
+ this.currentValue(existing, blocked.dimension, now),
182
+ this.effectiveMax(existing, limits, blocked.dimension),
183
+ );
184
+ }
185
+ }
186
+
187
+ // delivery / read_only 才查 hops / wall-clock / turns / tokens。
188
+ // wake 跳过这些维度(只保留 cycle)。
189
+ if (mode !== 'wake') {
190
+ const hops = existing?.hops ?? 0;
191
+ const maxHops = this.effectiveMax(existing, limits, 'hops');
192
+ if (maxHops !== undefined && hops + 1 > maxHops) {
193
+ return this.failed('hops', 'budget_exceeded', hops, maxHops);
194
+ }
195
+
196
+ const created = existing?.created_at ?? now;
197
+ const wallClock = now - created;
198
+ const maxWallClock = this.effectiveMax(existing, limits, 'wall_clock');
199
+ if (maxWallClock !== undefined && wallClock > maxWallClock) {
200
+ return this.failed('wall_clock', 'budget_exceeded', wallClock, maxWallClock);
201
+ }
202
+
203
+ const turns = existing?.turns ?? 0;
204
+ const maxTurns = this.effectiveMax(existing, limits, 'turns');
205
+ if (maxTurns !== undefined && turns >= maxTurns) {
206
+ return this.failed('turns', 'budget_exceeded', turns, maxTurns);
207
+ }
208
+
209
+ const tokens = existing?.total_tokens ?? 0;
210
+ const maxTokens = this.effectiveMax(existing, limits, 'tokens');
211
+ if (maxTokens !== undefined && tokens >= maxTokens) {
212
+ return this.failed('tokens', 'budget_exceeded', tokens, maxTokens);
213
+ }
214
+ }
215
+
216
+ // 边处理:bump = 检查并计数;check = 只检查;skip = 同 run 去重后整体跳过。
217
+ // 计数是滑动窗口:一条有向边的重复只在「最近一个 cooldown 窗口」内计,
218
+ // 即「同一有向边每个 cooldownSeconds 窗口最多 maxRepeats 次」。窗口外按 0 计,
219
+ // 否则 (from,to) 会在整条 conversation 生命周期里累积,把多轮往返判死。
220
+ const edgeMode = input.edge ?? (mode === 'read_only' ? 'check' : 'bump');
221
+ let edgeCount = 0;
222
+ const hasEdge = isAgentId(input.from) && isAgentId(input.to);
223
+ if (edgeMode !== 'skip' && hasEdge) {
224
+ const edge = existing?.edges.find(
225
+ (entry) => entry.from === input.from && entry.to === input.to,
226
+ );
227
+ const cooldownMs = this.cooldownMsFor(existing, limits);
228
+ edgeCount = edge !== undefined && this.withinWindow(edge, now, cooldownMs) ? edge.count : 0;
229
+ const maxRepeats = this.effectiveMax(existing, limits, 'cycle') ?? DEFAULT_CYCLE_MAX_REPEATS;
230
+ if (edgeCount + 1 > maxRepeats) {
231
+ // 只限速,不落持久 blocked:窗口滑过后下一次投递自动恢复,
232
+ // 不需要人工 override(永久 block 会把正常协作判死)。
233
+ const retryAfter = (edge?.last_ts ?? now) + cooldownMs;
234
+ return this.failed('cycle', 'cycle_detected', edgeCount, maxRepeats, retryAfter);
235
+ }
236
+ }
237
+
238
+ if (mode === 'read_only') return { ok: true };
239
+
240
+ // wake 只在已有记录上计边;不存在时上面已返回。
241
+ const conversation = existing ?? this.store.ensure(input.conversation_id, teamId, now);
242
+ if (mode === 'delivery') {
243
+ conversation.last_activity = now;
244
+ conversation.hops += 1;
245
+ }
246
+ if (edgeMode === 'bump' && hasEdge) {
247
+ // baseCount = 窗口内的次数;窗口已滑过就从头计(1)。
248
+ this.bumpEdge(conversation, input.from, input.to, edgeCount, now);
249
+ }
250
+ this.store.markDirty();
251
+ if (mode === 'delivery') this.collectWarnings(conversation, limits, now);
252
+ return { ok: true };
253
+ }
254
+
255
+ canStartTurn(input: BudgetTurnInput): BudgetCheckResult {
256
+ if (!this.store.available) return this.unavailable();
257
+ const now = this.now();
258
+ const conversation = this.store.get(input.conversation_id);
259
+ const teamId = conversation?.team_id ?? input.team_id;
260
+ const limits = this.limitsFor(teamId);
261
+
262
+ const turns = conversation?.turns ?? 0;
263
+ const maxTurns = this.effectiveMax(conversation, limits, 'turns');
264
+ if (maxTurns !== undefined && turns >= maxTurns) {
265
+ return this.failed('turns', 'budget_exceeded', turns, maxTurns);
266
+ }
267
+
268
+ const tokens = conversation?.total_tokens ?? 0;
269
+ const maxTokens = this.effectiveMax(conversation, limits, 'tokens');
270
+ if (maxTokens !== undefined && tokens >= maxTokens) {
271
+ return this.failed('tokens', 'budget_exceeded', tokens, maxTokens);
272
+ }
273
+
274
+ const wallClock = conversation === undefined ? 0 : now - conversation.created_at;
275
+ const maxWallClock = this.effectiveMax(conversation, limits, 'wall_clock');
276
+ if (maxWallClock !== undefined && wallClock > maxWallClock) {
277
+ return this.failed('wall_clock', 'budget_exceeded', wallClock, maxWallClock);
278
+ }
279
+
280
+ // 迁移(0.42):同 checkDelivery —— 旧 cycle blocked 就地清掉(窗口限速自愈)。
281
+ if (conversation?.blocked?.dimension === 'cycle') {
282
+ delete conversation.blocked;
283
+ this.store.markDirty();
284
+ }
285
+ if (conversation?.blocked !== undefined) {
286
+ const blocked = conversation.blocked;
287
+ return this.failed(
288
+ blocked.dimension,
289
+ blocked.reason,
290
+ this.currentValue(conversation, blocked.dimension, now),
291
+ this.effectiveMax(conversation, limits, blocked.dimension),
292
+ );
293
+ }
294
+
295
+ if (conversation !== undefined) this.collectWarnings(conversation, limits, now);
296
+ return { ok: true };
297
+ }
298
+
299
+ noteTurnStarted(input: BudgetTurnStartedInput): void {
300
+ if (!this.store.available) return;
301
+ const now = this.now();
302
+ const conversation = this.store.ensure(input.conversation_id, input.team_id, now);
303
+ conversation.turns += 1;
304
+ conversation.last_activity = now;
305
+ this.store.markDirty();
306
+ }
307
+
308
+ noteTurnFinished(input: BudgetTurnFinishedInput): void {
309
+ if (!this.store.available) return;
310
+ const now = this.now();
311
+ const conversation = this.store.ensure(input.conversation_id, input.team_id, now);
312
+ const usage = input.usage;
313
+ if (usage !== undefined) {
314
+ const total =
315
+ typeof usage.total_tokens === 'number' && Number.isFinite(usage.total_tokens)
316
+ ? usage.total_tokens
317
+ : (usage.prompt_tokens ?? 0) + (usage.completion_tokens ?? 0);
318
+ if (Number.isFinite(total)) conversation.total_tokens += total;
319
+ }
320
+ conversation.last_activity = now;
321
+ void this.store.force();
322
+ }
323
+
324
+ status(input: BudgetStatusInput): ConversationBudgetStatus[] {
325
+ if (!this.store.available) {
326
+ throw new AgentError('budget_unavailable', 'budget_unavailable');
327
+ }
328
+ if (input.conversation_id !== undefined) {
329
+ const conversation = this.store.get(input.conversation_id);
330
+ if (conversation === undefined || conversation.team_id !== input.team_id) return [];
331
+ return [this.toStatus(conversation)];
332
+ }
333
+ return this.store
334
+ .all()
335
+ .filter((conversation) => conversation.team_id === input.team_id)
336
+ .sort((left, right) => right.last_activity - left.last_activity)
337
+ .slice(0, MAX_STATUS_CONVERSATIONS)
338
+ .map((conversation) => this.toStatus(conversation));
339
+ }
340
+
341
+ override(input: BudgetOverrideInput): BudgetOverrideResult {
342
+ if (!this.store.available) {
343
+ throw new AgentError('budget_unavailable', 'budget_unavailable');
344
+ }
345
+ const conversation = this.store.get(input.conversation_id);
346
+ if (conversation === undefined) {
347
+ throw new AgentError('invalid_input', `conversation_not_found: ${input.conversation_id}`);
348
+ }
349
+ if (conversation.team_id !== undefined && conversation.team_id !== input.team_id) {
350
+ // 不泄漏跨 Team conversation 的存在性
351
+ throw new AgentError('invalid_input', `conversation_not_found: ${input.conversation_id}`);
352
+ }
353
+
354
+ const now = this.now();
355
+ const limits = this.limitsFor(conversation.team_id ?? input.team_id);
356
+ const previous = conversation.overrides[input.dimension]?.max ?? null;
357
+
358
+ if (input.max !== null) {
359
+ if (typeof input.max !== 'number' || !Number.isFinite(input.max) || input.max <= 0) {
360
+ throw new AgentError('invalid_input', 'max must be a positive finite number or null');
361
+ }
362
+ if (input.dimension === 'cycle') {
363
+ const currentMax =
364
+ conversation.overrides.cycle?.max ?? limits.maxRepeats ?? DEFAULT_CYCLE_MAX_REPEATS;
365
+ if (input.max <= currentMax) {
366
+ throw new AgentError(
367
+ 'invalid_input',
368
+ `cycle max must be greater than current maxRepeats (${currentMax})`,
369
+ );
370
+ }
371
+ } else {
372
+ const current = this.currentValue(conversation, input.dimension, now);
373
+ if (input.max <= current) {
374
+ throw new AgentError(
375
+ 'invalid_input',
376
+ `${input.dimension} max must be greater than current value (${current})`,
377
+ );
378
+ }
379
+ }
380
+ conversation.overrides[input.dimension] = {
381
+ max: input.max,
382
+ by: 'human',
383
+ via: input.via ?? 'api',
384
+ at: now,
385
+ };
386
+ if (conversation.blocked?.dimension === input.dimension) delete conversation.blocked;
387
+ } else {
388
+ delete conversation.overrides[input.dimension];
389
+ }
390
+
391
+ // cycle 的人工干预同时清零该 conversation 的 cycle 边,否则下一次投递仍会被
392
+ // 旧边计数挡住(override 只抬高上限不足以恢复)。
393
+ if (input.dimension === 'cycle') {
394
+ for (const edge of conversation.edges) edge.count = 0;
395
+ if (conversation.blocked?.dimension === 'cycle') delete conversation.blocked;
396
+ }
397
+
398
+ if (conversation.team_id === undefined) conversation.team_id = input.team_id;
399
+ void this.store.force();
400
+ return {
401
+ conversation_id: input.conversation_id,
402
+ dimension: input.dimension,
403
+ previous_max: previous,
404
+ max: input.max,
405
+ status: this.toStatus(conversation),
406
+ };
407
+ }
408
+
409
+ /** 清除接收侧 hold 与 blocked;返回需要重新 pump 的 agent id */
410
+ release(conversationId: string): string[] {
411
+ const holders = this.holds.get(conversationId);
412
+ this.holds.delete(conversationId);
413
+ this.pendingWarnings.delete(conversationId);
414
+ const conversation = this.store.get(conversationId);
415
+ if (conversation?.blocked !== undefined) {
416
+ delete conversation.blocked;
417
+ void this.store.force();
418
+ }
419
+ return holders === undefined ? [] : [...holders];
420
+ }
421
+
422
+ /** 接收侧 hold 记账(service 在 hold 时调用) */
423
+ noteHold(conversationId: string, agentId: string): void {
424
+ let holders = this.holds.get(conversationId);
425
+ if (holders === undefined) {
426
+ holders = new Set();
427
+ this.holds.set(conversationId, holders);
428
+ }
429
+ holders.add(agentId);
430
+ }
431
+
432
+ clearHold(conversationId: string, agentId: string): void {
433
+ const holders = this.holds.get(conversationId);
434
+ if (holders === undefined) return;
435
+ holders.delete(agentId);
436
+ if (holders.size === 0) this.holds.delete(conversationId);
437
+ }
438
+
439
+ /** 接收侧 turn 被挡:持久化 state.blocked(unavailable 时无状态可写) */
440
+ noteTurnBlocked(input: BudgetTurnBlockedInput): void {
441
+ if (!this.store.available || input.reason === 'budget_unavailable') return;
442
+ const now = this.now();
443
+ const conversation = this.store.ensure(input.conversation_id, input.team_id, now);
444
+ conversation.blocked = { dimension: input.dimension, reason: input.reason, at: now };
445
+ void this.store.force();
446
+ }
447
+
448
+ /** 取走 service 尚未发布的告警(每个 conversation+dimension 进程内只发一次) */
449
+ takeWarnings(conversationId: string): BudgetWarning[] {
450
+ const warnings = this.pendingWarnings.get(conversationId) ?? [];
451
+ this.pendingWarnings.delete(conversationId);
452
+ return warnings;
453
+ }
454
+
455
+ async flush(): Promise<void> {
456
+ await this.store.flush();
457
+ }
458
+
459
+ private limitsFor(teamId: string | undefined): ResolvedLimits {
460
+ try {
461
+ return resolveBudgetLimits(this.policyFor(teamId));
462
+ } catch (error) {
463
+ // 自定义 resolver 抛错不放大成投递失败;按默认策略继续(环检测仍生效)
464
+ this.logger.warn('conversation_budget.policy_failed', { error: errorText(error) });
465
+ return resolveBudgetLimits(undefined);
466
+ }
467
+ }
468
+
469
+ private effectiveMax(
470
+ conversation: StoredConversation | undefined,
471
+ limits: ResolvedLimits,
472
+ dimension: BudgetDimension,
473
+ ): number | undefined {
474
+ const override = conversation?.overrides?.[dimension];
475
+ if (override !== undefined && typeof override.max === 'number') return override.max;
476
+ switch (dimension) {
477
+ case 'hops':
478
+ return limits.maxHops;
479
+ case 'turns':
480
+ return limits.maxTurns;
481
+ case 'tokens':
482
+ return limits.maxTokens;
483
+ case 'wall_clock':
484
+ return limits.maxWallClockMs;
485
+ case 'cycle':
486
+ return limits.maxRepeats;
487
+ default:
488
+ return undefined;
489
+ }
490
+ }
491
+
492
+ private cooldownMsFor(
493
+ _conversation: StoredConversation | undefined,
494
+ limits: ResolvedLimits,
495
+ ): number {
496
+ return limits.cooldownMs;
497
+ }
498
+
499
+ /**
500
+ * 边计数是否仍在窗口内。窗口 = `cooldownSeconds`,从该边上一次成功投递起算:
501
+ * 这意味着「同一条有向边最多每 `cooldownMs / maxRepeats` 打一次」,而不会在
502
+ * 整条 conversation 生命周期内累积。
503
+ */
504
+ private withinWindow(edge: StoredConversationEdge, now: number, cooldownMs: number): boolean {
505
+ return now - edge.last_ts <= cooldownMs;
506
+ }
507
+
508
+ private currentValue(
509
+ conversation: Pick<StoredConversation, 'hops' | 'turns' | 'total_tokens' | 'created_at'>,
510
+ dimension: BudgetDimension,
511
+ now: number,
512
+ ): number {
513
+ switch (dimension) {
514
+ case 'hops':
515
+ return conversation.hops;
516
+ case 'turns':
517
+ return conversation.turns;
518
+ case 'tokens':
519
+ return conversation.total_tokens;
520
+ case 'wall_clock':
521
+ return Math.max(0, now - conversation.created_at);
522
+ case 'cycle':
523
+ return 0;
524
+ default:
525
+ return 0;
526
+ }
527
+ }
528
+
529
+ private bumpEdge(
530
+ conversation: Pick<StoredConversation, 'edges'>,
531
+ from: string,
532
+ to: string,
533
+ baseCount: number,
534
+ now: number,
535
+ ): void {
536
+ const existing = conversation.edges.find((edge) => edge.from === from && edge.to === to);
537
+ if (existing !== undefined) {
538
+ existing.count = baseCount + 1;
539
+ existing.last_ts = now;
540
+ } else {
541
+ conversation.edges.push({ from, to, count: 1, last_ts: now });
542
+ }
543
+ if (conversation.edges.length > MAX_CONVERSATION_EDGES) {
544
+ conversation.edges.sort((left, right) => left.last_ts - right.last_ts);
545
+ conversation.edges.splice(0, conversation.edges.length - MAX_CONVERSATION_EDGES);
546
+ }
547
+ }
548
+
549
+ /** 已配置维度到 80% 且未满 100% 时记录一次告警 */
550
+ private collectWarnings(
551
+ conversation: StoredConversation,
552
+ limits: ResolvedLimits,
553
+ now: number,
554
+ ): void {
555
+ const dimensions: Array<Exclude<BudgetDimension, 'cycle'>> = [
556
+ 'hops',
557
+ 'turns',
558
+ 'tokens',
559
+ 'wall_clock',
560
+ ];
561
+ for (const dimension of dimensions) {
562
+ const max = this.effectiveMax(conversation, limits, dimension);
563
+ if (max === undefined || max <= 0) continue;
564
+ const current = this.currentValue(conversation, dimension, now);
565
+ const ratio = current / max;
566
+ if (ratio < limits.warningThreshold || ratio >= 1) continue;
567
+ let warned = this.warned.get(conversation.conversation_id);
568
+ if (warned?.has(dimension)) continue;
569
+ if (warned === undefined) {
570
+ warned = new Set();
571
+ this.warned.set(conversation.conversation_id, warned);
572
+ }
573
+ warned.add(dimension);
574
+ const list = this.pendingWarnings.get(conversation.conversation_id) ?? [];
575
+ list.push({
576
+ conversation_id: conversation.conversation_id,
577
+ ...(conversation.team_id !== undefined ? { team_id: conversation.team_id } : {}),
578
+ dimension,
579
+ current,
580
+ max,
581
+ threshold: limits.warningThreshold,
582
+ });
583
+ this.pendingWarnings.set(conversation.conversation_id, list);
584
+ }
585
+ }
586
+
587
+ private toStatus(conversation: StoredConversation): ConversationBudgetStatus {
588
+ const now = this.now();
589
+ const limits = this.limitsFor(conversation.team_id);
590
+ const maxRepeats =
591
+ this.effectiveMax(conversation, limits, 'cycle') ?? DEFAULT_CYCLE_MAX_REPEATS;
592
+ const edges: ConversationBudgetEdge[] = conversation.edges.map((edge) => {
593
+ // blocked_until 只在窗口内越界时给出:窗口滑过后该边自动可再用。
594
+ const blockedUntil =
595
+ this.withinWindow(edge, now, limits.cooldownMs) && edge.count + 1 > maxRepeats
596
+ ? edge.last_ts + limits.cooldownMs
597
+ : undefined;
598
+ return {
599
+ from: edge.from,
600
+ to: edge.to,
601
+ count: edge.count,
602
+ last_ts: edge.last_ts,
603
+ ...(blockedUntil !== undefined && blockedUntil > now
604
+ ? { blocked_until: blockedUntil }
605
+ : {}),
606
+ };
607
+ });
608
+ return {
609
+ conversation_id: conversation.conversation_id,
610
+ ...(conversation.team_id !== undefined ? { team_id: conversation.team_id } : {}),
611
+ created_at: conversation.created_at,
612
+ last_activity: conversation.last_activity,
613
+ hops: conversation.hops,
614
+ turns: conversation.turns,
615
+ total_tokens: conversation.total_tokens,
616
+ wall_clock_ms: Math.max(0, now - conversation.created_at),
617
+ edges,
618
+ overrides: Object.fromEntries(
619
+ Object.entries(conversation.overrides).map(([key, value]) => [key, { ...value }]),
620
+ ) as ConversationBudgetStatus['overrides'],
621
+ ...(conversation.blocked !== undefined ? { blocked: { ...conversation.blocked } } : {}),
622
+ };
623
+ }
624
+
625
+ private unavailable(): BudgetCheckResult {
626
+ return {
627
+ ok: false,
628
+ dimension: 'hops',
629
+ reason: 'budget_unavailable',
630
+ current: 0,
631
+ max: null,
632
+ };
633
+ }
634
+
635
+ private failed(
636
+ dimension: BudgetDimension,
637
+ reason: BudgetBlockReason,
638
+ current: number,
639
+ max: number | null | undefined,
640
+ retryAfter?: number,
641
+ ): BudgetCheckResult {
642
+ return {
643
+ ok: false,
644
+ dimension,
645
+ reason,
646
+ current,
647
+ max: max ?? null,
648
+ ...(retryAfter !== undefined ? { retry_after_ts: retryAfter } : {}),
649
+ };
650
+ }
651
+ }