@@ -79,6 +79,8 @@ import { getModelMaxOutputTokens } from "../../shared/api"
7979import { McpHub } from "../../services/mcp/McpHub"
8080import { McpServerManager } from "../../services/mcp/McpServerManager"
8181import { RepoPerTaskCheckpointService } from "../../services/checkpoints"
82+ import { UsageEventStore , UsageRecorder } from "../../services/stats"
83+ import type { UsageRecordingContext } from "../../services/stats"
8284
8385// integrations
8486import { DiffViewProvider } from "../../integrations/editor/DiffViewProvider"
@@ -270,6 +272,14 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
270272
271273 providerRef : WeakRef < ClineProvider >
272274 private readonly globalStoragePath : string
275+
276+ /**
277+ * Usage 이벤트 기록기. API attempt의 terminal finalize에서만 호출된다.
278+ * store 초기화 실패 시 null이며, 이 경우 기록을 조용히 건너뛴다.
279+ * (아키텍처 보고서 섹션 5.5-5.8, rollback: writer를 optional service로 주입)
280+ */
281+ private readonly usageRecorder : UsageRecorder | null = null
282+
273283 abort : boolean = false
274284 currentRequestAbortController ?: AbortController
275285 skipPrevResponseIdOnce : boolean = false
@@ -520,6 +530,16 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
520530 this . enableCheckpoints = enableCheckpoints
521531 this . checkpointTimeout = checkpointTimeout
522532
533+ // Initialize usage recorder (best-effort: failure results in null recorder)
534+ // Store initialization is deferred to first append; here we only construct the recorder.
535+ // If the store fails at runtime, UsageRecorder catches errors internally.
536+ try {
537+ const store = new UsageEventStore ( this . globalStoragePath )
538+ this . usageRecorder = new UsageRecorder ( store )
539+ } catch ( err ) {
540+ console . warn ( `[Task#${ this . taskId } ] Failed to initialize UsageRecorder, stats will be skipped:` , err )
541+ }
542+
523543 this . parentTask = parentTask
524544 this . taskNumber = taskNumber
525545 this . initialStatus = initialStatus
@@ -3154,7 +3174,44 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
31543174 cacheReadTokens : tokens . cacheRead ,
31553175 cost : tokens . total ?? costResult . totalCost ,
31563176 } )
3177+
3178+ // ── Usage Stats: terminal finalize ──────────────────────────
3179+ // captureUsageData is the single terminal boundary for completed/cancelled
3180+ // API attempts. We record the final usage event here.
3181+ // (Architecture report section 5.5-5.8: terminal finalize only, no chunk-level append)
3182+ if ( this . usageRecorder ) {
3183+ const requestKey = `${ this . taskId } :${ currentItem . retryAttempt ?? 0 } `
3184+ const ctx : UsageRecordingContext = {
3185+ taskId : this . taskId ,
3186+ parentTaskId : this . parentTaskId ,
3187+ provider : String (
3188+ this . apiConfiguration . apiProvider && ! isRetiredProvider ( this . apiConfiguration . apiProvider )
3189+ ? this . apiConfiguration . apiProvider
3190+ : "unknown" ,
3191+ ) ,
3192+ model : getModelId ( this . apiConfiguration ) || "unknown" ,
3193+ mode : this . _taskMode || defaultModeSlug ,
3194+ attempt : currentItem . retryAttempt ?? 0 ,
3195+ inputTokens : tokens . input ,
3196+ outputTokens : tokens . output ,
3197+ cacheWriteTokens : tokens . cacheWrite ,
3198+ cacheReadTokens : tokens . cacheRead ,
3199+ totalCost : tokens . total ,
3200+ // V1 semantics: provider-reported values, inclusion unknown
3201+ // (aggregator handles double-counting via inclusion metadata)
3202+ cacheReadInInput : "unknown" ,
3203+ cacheWriteInInput : "unknown" ,
3204+ reasoningInOutput : "unknown" ,
3205+ costSource : "provider" ,
3206+ tokenSource : "provider" ,
3207+ }
3208+ // Fire-and-forget: store error must not block task
3209+ this . usageRecorder
3210+ . finalizeUsageEvent ( requestKey , status , ctx )
3211+ . catch ( ( ) => { } )
31573212 }
3213+ // ── End Usage Stats ──────────────────────────────────────────
3214+ }
31583215 }
31593216
31603217 try {
@@ -3262,6 +3319,43 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
32623319 // Clean up partial state
32633320 await abortStream ( cancelReason , streamingFailedMessage )
32643321
3322+ // ── Usage Stats: terminal finalize for failed/cancelled ───────
3323+ // This catch block is the terminal path for streaming failures and
3324+ // user cancellations. Record the partial usage with the appropriate status.
3325+ // (Architecture report section 5.5-5.8: terminal finalize only)
3326+ if ( this . usageRecorder ) {
3327+ const requestKey = `${ this . taskId } :${ currentItem . retryAttempt ?? 0 } `
3328+ const failedStatus : "failed" | "cancelled" = this . abort ? "cancelled" : "failed"
3329+ const ctx : UsageRecordingContext = {
3330+ taskId : this . taskId ,
3331+ parentTaskId : this . parentTaskId ,
3332+ provider : String (
3333+ this . apiConfiguration . apiProvider &&
3334+ ! isRetiredProvider ( this . apiConfiguration . apiProvider )
3335+ ? this . apiConfiguration . apiProvider
3336+ : "unknown" ,
3337+ ) ,
3338+ model : getModelId ( this . apiConfiguration ) || "unknown" ,
3339+ mode : this . _taskMode || defaultModeSlug ,
3340+ attempt : currentItem . retryAttempt ?? 0 ,
3341+ inputTokens : inputTokens ,
3342+ outputTokens : outputTokens ,
3343+ cacheWriteTokens : cacheWriteTokens ,
3344+ cacheReadTokens : cacheReadTokens ,
3345+ totalCost : totalCost ,
3346+ cacheReadInInput : "unknown" ,
3347+ cacheWriteInInput : "unknown" ,
3348+ reasoningInOutput : "unknown" ,
3349+ costSource : "provider" ,
3350+ tokenSource : "provider" ,
3351+ }
3352+ // Fire-and-forget: store error must not block task
3353+ this . usageRecorder
3354+ . finalizeUsageEvent ( requestKey , failedStatus , ctx )
3355+ . catch ( ( ) => { } )
3356+ }
3357+ // ── End Usage Stats ──────────────────────────────────────────
3358+
32653359 if ( this . abort ) {
32663360 // User cancelled - abort the entire task
32673361 this . abortReason = cancelReason
0 commit comments