|
| 1 | +import { Disposable } from '#/_base/di/lifecycle'; |
| 2 | +import { LifecycleScope } from '#/app/scopes'; |
| 3 | +import { ScopeActivation, registerScopedService } from '#/_base/di/scope'; |
| 4 | +import { defineState } from '#/state/state'; |
| 5 | +import { createUserMessage } from '#/kosong/contract/message'; |
| 6 | +import type { ContextMessage } from '#/agent/contextMemory/types'; |
| 7 | +import type { AfterStepContext } from '#/agent/loop/loop'; |
| 8 | +import { IAgentLoopService } from '#/agent/loop/loop'; |
| 9 | +import { TurnStarted } from '#/agent/loop/turnEvents'; |
| 10 | +import { StepRequest } from '#/agent/loop/stepRequest'; |
| 11 | +import { LOOP_CONTROL_SECTION, type LoopControl } from '#/agent/loop/configSection'; |
| 12 | +import { IConfigService } from '#/app/config/config'; |
| 13 | +import { IEventBus } from '#/app/event/eventBus'; |
| 14 | +import { IFlagService } from '#/app/flag/flag'; |
| 15 | +import { ITelemetryService } from '#/app/telemetry/telemetry'; |
| 16 | +import { IAgentStateService } from '#/agent/state/agentState'; |
| 17 | +import { TURN_BUDGET_CONTINUATION_FLAG_ID } from './flag'; |
| 18 | +import { |
| 19 | + IAgentTurnBudgetService, |
| 20 | + TURN_BUDGET_COMPLETION_THRESHOLD, |
| 21 | + TURN_BUDGET_DIMINISHING_MIN_DELTA_TOKENS, |
| 22 | + TURN_BUDGET_MAX_DIMINISHING_CONTINUATIONS, |
| 23 | + turnBudgetNudgeText, |
| 24 | +} from './turnBudget'; |
| 25 | + |
| 26 | +export const turnBudgetTokensUsedKey = defineState<number>('turnBudget.tokensUsed', () => 0); |
| 27 | +export const turnBudgetContinuationsKey = defineState<number>('turnBudget.continuations', () => 0); |
| 28 | +export const turnBudgetLastDeltaTokensKey = defineState<number>( |
| 29 | + 'turnBudget.lastDeltaTokens', |
| 30 | + () => 0, |
| 31 | +); |
| 32 | + |
| 33 | +class TurnBudgetContinuationRequest extends StepRequest { |
| 34 | + readonly kind = 'turn-budget-continuation'; |
| 35 | + |
| 36 | + constructor(private readonly message: ContextMessage) { |
| 37 | + super(); |
| 38 | + } |
| 39 | + |
| 40 | + override resolveContextMessages(): readonly ContextMessage[] { |
| 41 | + return [this.message]; |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +export class AgentTurnBudgetService extends Disposable implements IAgentTurnBudgetService { |
| 46 | + declare readonly _serviceBrand: undefined; |
| 47 | + |
| 48 | + constructor( |
| 49 | + @IAgentLoopService private readonly loopService: IAgentLoopService, |
| 50 | + @IFlagService private readonly flags: IFlagService, |
| 51 | + @IConfigService private readonly config: IConfigService, |
| 52 | + @IEventBus private readonly eventBus: IEventBus, |
| 53 | + @ITelemetryService private readonly telemetry: ITelemetryService, |
| 54 | + @IAgentStateService private readonly states: IAgentStateService, |
| 55 | + ) { |
| 56 | + super(); |
| 57 | + this.states.contributeState(turnBudgetTokensUsedKey); |
| 58 | + this.states.contributeState(turnBudgetContinuationsKey); |
| 59 | + this.states.contributeState(turnBudgetLastDeltaTokensKey); |
| 60 | + this._register(this.eventBus.subscribe(TurnStarted, () => this.reset())); |
| 61 | + this._register( |
| 62 | + this.loopService.hooks.onDidFinishStep.register('turn-budget', async (context, next) => { |
| 63 | + await next(); |
| 64 | + this.maybeContinue(context); |
| 65 | + }), |
| 66 | + ); |
| 67 | + } |
| 68 | + |
| 69 | + private get tokensUsed(): number { |
| 70 | + return this.states.get(turnBudgetTokensUsedKey); |
| 71 | + } |
| 72 | + |
| 73 | + private set tokensUsed(value: number) { |
| 74 | + this.states.set(turnBudgetTokensUsedKey, value); |
| 75 | + } |
| 76 | + |
| 77 | + private get continuations(): number { |
| 78 | + return this.states.get(turnBudgetContinuationsKey); |
| 79 | + } |
| 80 | + |
| 81 | + private set continuations(value: number) { |
| 82 | + this.states.set(turnBudgetContinuationsKey, value); |
| 83 | + } |
| 84 | + |
| 85 | + private get lastDeltaTokens(): number { |
| 86 | + return this.states.get(turnBudgetLastDeltaTokensKey); |
| 87 | + } |
| 88 | + |
| 89 | + private set lastDeltaTokens(value: number) { |
| 90 | + this.states.set(turnBudgetLastDeltaTokensKey, value); |
| 91 | + } |
| 92 | + |
| 93 | + private reset(): void { |
| 94 | + this.tokensUsed = 0; |
| 95 | + this.continuations = 0; |
| 96 | + this.lastDeltaTokens = 0; |
| 97 | + } |
| 98 | + |
| 99 | + private budgetTokens(): number { |
| 100 | + return this.config.get<LoopControl>(LOOP_CONTROL_SECTION)?.turnBudgetTokens ?? 0; |
| 101 | + } |
| 102 | + |
| 103 | + private maybeContinue(context: AfterStepContext): void { |
| 104 | + if (!this.flags.enabled(TURN_BUDGET_CONTINUATION_FLAG_ID)) return; |
| 105 | + if (context.stopTurn || context.signal.aborted) return; |
| 106 | + const budget = this.budgetTokens(); |
| 107 | + if (budget <= 0) return; |
| 108 | + |
| 109 | + const delta = context.usage.output; |
| 110 | + const used = this.tokensUsed + delta; |
| 111 | + const previousDelta = this.lastDeltaTokens; |
| 112 | + this.lastDeltaTokens = delta; |
| 113 | + this.tokensUsed = used; |
| 114 | + |
| 115 | + if (context.finishReason === 'tool_calls') return; |
| 116 | + if (context.finishReason !== 'completed') return; |
| 117 | + if (this.loopService.status().hasPendingRequests) return; |
| 118 | + |
| 119 | + const diminishing = |
| 120 | + this.continuations >= TURN_BUDGET_MAX_DIMINISHING_CONTINUATIONS && |
| 121 | + delta < TURN_BUDGET_DIMINISHING_MIN_DELTA_TOKENS && |
| 122 | + previousDelta < TURN_BUDGET_DIMINISHING_MIN_DELTA_TOKENS; |
| 123 | + if (diminishing) return; |
| 124 | + if (used >= budget * TURN_BUDGET_COMPLETION_THRESHOLD) return; |
| 125 | + |
| 126 | + const pct = Math.round((used / budget) * 100); |
| 127 | + this.continuations += 1; |
| 128 | + this.telemetry.track2('budget_continuation', { |
| 129 | + turn_id: context.turnId, |
| 130 | + continuation_count: this.continuations, |
| 131 | + tokens_used: used, |
| 132 | + budget_tokens: budget, |
| 133 | + }); |
| 134 | + const message: ContextMessage = { |
| 135 | + ...createUserMessage(turnBudgetNudgeText(pct, used, budget)), |
| 136 | + origin: { kind: 'retry', trigger: 'token_budget' }, |
| 137 | + }; |
| 138 | + this.loopService.enqueue(new TurnBudgetContinuationRequest(message)); |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +registerScopedService( |
| 143 | + LifecycleScope.Agent, |
| 144 | + IAgentTurnBudgetService, |
| 145 | + AgentTurnBudgetService, |
| 146 | + ScopeActivation.OnScopeCreated, |
| 147 | + 'turnBudget', |
| 148 | +); |
0 commit comments