-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathTask.ts
More file actions
4896 lines (4304 loc) · 174 KB
/
Task.ts
File metadata and controls
4896 lines (4304 loc) · 174 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as path from "path"
import * as vscode from "vscode"
import os from "os"
import crypto from "crypto"
import { v7 as uuidv7 } from "uuid"
import EventEmitter from "events"
import { AskIgnoredError } from "./AskIgnoredError"
// Note: Anthropic SDK import retained for types used by the API handler interface
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import debounce from "lodash.debounce"
import delay from "delay"
import pWaitFor from "p-wait-for"
import { serializeError } from "serialize-error"
import { Package } from "../../shared/package"
import { formatToolInvocation } from "../tools/helpers/toolResultFormatting"
import {
type TaskLike,
type TaskMetadata,
type TaskEvents,
type ProviderSettings,
type TokenUsage,
type ToolUsage,
type ToolName,
type ContextCondense,
type ContextTruncation,
type ClineMessage,
type ClineSay,
type ClineAsk,
type ToolProgressStatus,
type HistoryItem,
type CreateTaskOptions,
type ModelInfo,
type ClineApiReqCancelReason,
type ClineApiReqInfo,
RooCodeEventName,
TelemetryEventName,
TaskStatus,
TodoItem,
getApiProtocol,
getModelId,
isRetiredProvider,
isIdleAsk,
isInteractiveAsk,
isResumableAsk,
QueuedMessage,
DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
MAX_CHECKPOINT_TIMEOUT_SECONDS,
MIN_CHECKPOINT_TIMEOUT_SECONDS,
ConsecutiveMistakeError,
MAX_MCP_TOOLS_THRESHOLD,
countEnabledMcpTools,
} from "@roo-code/types"
import { TelemetryService } from "@roo-code/telemetry"
import { CloudService, BridgeOrchestrator } from "@roo-code/cloud"
// api
import { ApiHandler, ApiHandlerCreateMessageMetadata, buildApiHandler } from "../../api"
import type { AssistantModelMessage } from "ai"
import { ApiStream, GroundingSource } from "../../api/transform/stream"
import { maybeRemoveImageBlocks } from "../../api/transform/image-cleaning"
import { applyCacheBreakpoints, UNIVERSAL_CACHE_OPTIONS } from "../../api/transform/cache-breakpoints"
// shared
import { findLastIndex } from "../../shared/array"
import { combineApiRequests } from "../../shared/combineApiRequests"
import { combineCommandSequences } from "../../shared/combineCommandSequences"
import { t } from "../../i18n"
import { getApiMetrics, hasTokenUsageChanged, hasToolUsageChanged } from "../../shared/getApiMetrics"
import { ClineAskResponse } from "../../shared/WebviewMessage"
import { defaultModeSlug, getModeBySlug } from "../../shared/modes"
import { DiffStrategy, type ToolUse, type ToolParamName, toolParamNames } from "../../shared/tools"
import { getModelMaxOutputTokens } from "../../shared/api"
// services
import { McpHub } from "../../services/mcp/McpHub"
import { McpServerManager } from "../../services/mcp/McpServerManager"
import { RepoPerTaskCheckpointService } from "../../services/checkpoints"
// integrations
import { DiffViewProvider } from "../../integrations/editor/DiffViewProvider"
import { findToolName } from "../../integrations/misc/export-markdown"
import { RooTerminalProcess } from "../../integrations/terminal/types"
import { TerminalRegistry } from "../../integrations/terminal/TerminalRegistry"
import { OutputInterceptor } from "../../integrations/terminal/OutputInterceptor"
// utils
import { calculateApiCostAnthropic, calculateApiCostOpenAI } from "../../shared/cost"
import { getWorkspacePath } from "../../utils/path"
import { sanitizeToolUseId } from "../../utils/tool-id"
import { getTaskDirectoryPath } from "../../utils/storage"
// prompts
import { formatResponse } from "../prompts/responses"
import { SYSTEM_PROMPT } from "../prompts/system"
import { buildNativeToolsArrayWithRestrictions } from "./build-tools"
// core modules
import { ToolRepetitionDetector } from "../tools/ToolRepetitionDetector"
import { restoreTodoListForTask } from "../tools/UpdateTodoListTool"
import { FileContextTracker } from "../context-tracking/FileContextTracker"
import { RooIgnoreController } from "../ignore/RooIgnoreController"
import { RooProtectedController } from "../protect/RooProtectedController"
import { type AssistantMessageContent, presentAssistantMessage } from "../assistant-message"
import { NativeToolCallParser } from "../assistant-message/NativeToolCallParser"
import { manageContext, willManageContext } from "../context-management"
import { ClineProvider } from "../webview/ClineProvider"
import { MultiSearchReplaceDiffStrategy } from "../diff/strategies/multi-search-replace"
import {
type ApiMessage,
readApiMessages,
saveApiMessages,
readTaskMessages,
saveTaskMessages,
taskMetadata,
type RooMessage,
type RooUserMessage,
type RooAssistantMessage,
type RooToolMessage,
type RooReasoningMessage,
type TextPart,
type ImagePart,
type ToolCallPart,
type ToolResultPart,
type UserContentPart,
type AnyToolCallBlock,
type AnyToolResultBlock,
isRooUserMessage,
isRooAssistantMessage,
isRooToolMessage,
isRooReasoningMessage,
isRooRoleMessage,
isAnyToolResultBlock,
getToolCallId,
getToolCallName,
getToolResultContent,
readRooMessages,
saveRooMessages,
} from "../task-persistence"
import { getEnvironmentDetails } from "../environment/getEnvironmentDetails"
import { checkContextWindowExceededError } from "../context/context-management/context-error-handling"
import {
type CheckpointDiffOptions,
type CheckpointRestoreOptions,
getCheckpointService,
checkpointSave,
checkpointRestore,
checkpointDiff,
} from "../checkpoints"
import { processUserContentMentions } from "../mentions/processUserContentMentions"
import { getMessagesSinceLastSummary, summarizeConversation, getEffectiveApiHistory } from "../condense"
import { MessageQueueService } from "../message-queue/MessageQueueService"
import { AutoApprovalHandler, checkAutoApproval } from "../auto-approval"
import { MessageManager } from "../message-manager"
import { validateAndFixToolResultIds } from "./validateToolResultIds"
import { mergeConsecutiveApiMessages } from "./mergeConsecutiveApiMessages"
const MAX_EXPONENTIAL_BACKOFF_SECONDS = 600 // 10 minutes
const DEFAULT_USAGE_COLLECTION_TIMEOUT_MS = 5000 // 5 seconds
const FORCED_CONTEXT_REDUCTION_PERCENT = 75 // Keep 75% of context (remove 25%) on context window errors
const MAX_CONTEXT_WINDOW_RETRIES = 3 // Maximum retries for context window errors
export interface TaskOptions extends CreateTaskOptions {
provider: ClineProvider
apiConfiguration: ProviderSettings
enableCheckpoints?: boolean
checkpointTimeout?: number
enableBridge?: boolean
consecutiveMistakeLimit?: number
task?: string
images?: string[]
historyItem?: HistoryItem
experiments?: Record<string, boolean>
startTask?: boolean
rootTask?: Task
parentTask?: Task
taskNumber?: number
onCreated?: (task: Task) => void
initialTodos?: TodoItem[]
workspacePath?: string
/** Initial status for the task's history item (e.g., "active" for child tasks) */
initialStatus?: "active" | "delegated" | "completed"
}
export class Task extends EventEmitter<TaskEvents> implements TaskLike {
readonly taskId: string
readonly rootTaskId?: string
readonly parentTaskId?: string
childTaskId?: string
pendingNewTaskToolCallId?: string
readonly instanceId: string
readonly metadata: TaskMetadata
todoList?: TodoItem[]
readonly rootTask: Task | undefined = undefined
readonly parentTask: Task | undefined = undefined
readonly taskNumber: number
readonly workspacePath: string
/**
* The mode associated with this task. Persisted across sessions
* to maintain user context when reopening tasks from history.
*
* ## Lifecycle
*
* ### For new tasks:
* 1. Initially `undefined` during construction
* 2. Asynchronously initialized from provider state via `initializeTaskMode()`
* 3. Falls back to `defaultModeSlug` if provider state is unavailable
*
* ### For history items:
* 1. Immediately set from `historyItem.mode` during construction
* 2. Falls back to `defaultModeSlug` if mode is not stored in history
*
* ## Important
* This property should NOT be accessed directly until `taskModeReady` promise resolves.
* Use `getTaskMode()` for async access or `taskMode` getter for sync access after initialization.
*
* @private
* @see {@link getTaskMode} - For safe async access
* @see {@link taskMode} - For sync access after initialization
* @see {@link waitForModeInitialization} - To ensure initialization is complete
*/
private _taskMode: string | undefined
/**
* Promise that resolves when the task mode has been initialized.
* This ensures async mode initialization completes before the task is used.
*
* ## Purpose
* - Prevents race conditions when accessing task mode
* - Ensures provider state is properly loaded before mode-dependent operations
* - Provides a synchronization point for async initialization
*
* ## Resolution timing
* - For history items: Resolves immediately (sync initialization)
* - For new tasks: Resolves after provider state is fetched (async initialization)
*
* @private
* @see {@link waitForModeInitialization} - Public method to await this promise
*/
private taskModeReady: Promise<void>
/**
* The API configuration name (provider profile) associated with this task.
* Persisted across sessions to maintain the provider profile when reopening tasks from history.
*
* ## Lifecycle
*
* ### For new tasks:
* 1. Initially `undefined` during construction
* 2. Asynchronously initialized from provider state via `initializeTaskApiConfigName()`
* 3. Falls back to "default" if provider state is unavailable
*
* ### For history items:
* 1. Immediately set from `historyItem.apiConfigName` during construction
* 2. Falls back to undefined if not stored in history (for backward compatibility)
*
* ## Important
* If you need a non-`undefined` provider profile (e.g., for profile-dependent operations),
* wait for `taskApiConfigReady` first (or use `getTaskApiConfigName()`).
* The sync `taskApiConfigName` getter may return `undefined` for backward compatibility.
*
* @private
* @see {@link getTaskApiConfigName} - For safe async access
* @see {@link taskApiConfigName} - For sync access after initialization
*/
private _taskApiConfigName: string | undefined
/**
* Promise that resolves when the task API config name has been initialized.
* This ensures async API config name initialization completes before the task is used.
*
* ## Purpose
* - Prevents race conditions when accessing task API config name
* - Ensures provider state is properly loaded before profile-dependent operations
* - Provides a synchronization point for async initialization
*
* ## Resolution timing
* - For history items: Resolves immediately (sync initialization)
* - For new tasks: Resolves after provider state is fetched (async initialization)
*
* @private
*/
private taskApiConfigReady: Promise<void>
providerRef: WeakRef<ClineProvider>
private readonly globalStoragePath: string
abort: boolean = false
currentRequestAbortController?: AbortController
skipPrevResponseIdOnce: boolean = false
// TaskStatus
idleAsk?: ClineMessage
resumableAsk?: ClineMessage
interactiveAsk?: ClineMessage
didFinishAbortingStream = false
abandoned = false
abortReason?: ClineApiReqCancelReason
isInitialized = false
isPaused: boolean = false
// API
apiConfiguration: ProviderSettings
api: ApiHandler
private static lastGlobalApiRequestTime?: number
private autoApprovalHandler: AutoApprovalHandler
/**
* Reset the global API request timestamp. This should only be used for testing.
* @internal
*/
static resetGlobalApiRequestTime(): void {
Task.lastGlobalApiRequestTime = undefined
}
toolRepetitionDetector: ToolRepetitionDetector
rooIgnoreController?: RooIgnoreController
rooProtectedController?: RooProtectedController
fileContextTracker: FileContextTracker
terminalProcess?: RooTerminalProcess
// Editing
diffViewProvider: DiffViewProvider
diffStrategy?: DiffStrategy
didEditFile: boolean = false
// LLM Messages & Chat Messages
apiConversationHistory: RooMessage[] = []
clineMessages: ClineMessage[] = []
// Ask
private askResponse?: ClineAskResponse
private askResponseText?: string
private askResponseImages?: string[]
public lastMessageTs?: number
private autoApprovalTimeoutRef?: NodeJS.Timeout
// Tool Use
consecutiveMistakeCount: number = 0
consecutiveMistakeLimit: number
consecutiveMistakeCountForApplyDiff: Map<string, number> = new Map()
consecutiveMistakeCountForEditFile: Map<string, number> = new Map()
consecutiveNoToolUseCount: number = 0
consecutiveNoAssistantMessagesCount: number = 0
toolUsage: ToolUsage = {}
// Checkpoints
enableCheckpoints: boolean
checkpointTimeout: number
checkpointService?: RepoPerTaskCheckpointService
checkpointServiceInitializing = false
// Task Bridge
enableBridge: boolean
// Message Queue Service
public readonly messageQueueService: MessageQueueService
private messageQueueStateChangedHandler: (() => void) | undefined
// Streaming
isWaitingForFirstChunk = false
isStreaming = false
currentStreamingContentIndex = 0
currentStreamingDidCheckpoint = false
assistantMessageContent: AssistantMessageContent[] = []
presentAssistantMessageLocked = false
presentAssistantMessageHasPendingUpdates = false
userMessageContent: Array<TextPart | ImagePart> = []
userMessageContentReady = false
pendingToolResults: Array<ToolResultPart> = []
/**
* Flag indicating whether the assistant message for the current streaming session
* has been saved to API conversation history.
*
* This is critical for parallel tool calling: tools should NOT execute until
* the assistant message is saved. Otherwise, if a tool like `new_task` triggers
* `flushPendingToolResultsToHistory()`, the user message with tool_results would
* appear BEFORE the assistant message with tool_uses, causing API errors.
*
* Reset to `false` at the start of each API request.
* Set to `true` after the assistant message is saved in `recursivelyMakeClineRequests`.
*/
assistantMessageSavedToHistory = false
/**
* Push a tool result to pendingToolResults, preventing duplicates.
* Duplicate toolCallIds cause API errors.
*
* @param toolResult - The ToolResultPart to add
* @returns true if added, false if duplicate was skipped
*/
public pushToolResultToUserContent(toolResult: ToolResultPart): boolean {
const existingResult = this.pendingToolResults.find(
(block): block is ToolResultPart =>
block.type === "tool-result" && block.toolCallId === toolResult.toolCallId,
)
if (existingResult) {
console.warn(
`[Task#pushToolResultToUserContent] Skipping duplicate tool_result for toolCallId: ${toolResult.toolCallId}`,
)
return false
}
this.pendingToolResults.push(toolResult)
return true
}
/**
* Handle a tool call streaming event (tool_call_start, tool_call_delta, or tool_call_end).
* This is used both for processing events from NativeToolCallParser (legacy providers)
* and for direct AI SDK events (DeepSeek, Moonshot, etc.).
*
* @param event - The tool call event to process
*/
private handleToolCallEvent(
event:
| { type: "tool_call_start"; id: string; name: string }
| { type: "tool_call_delta"; id: string; delta: string }
| { type: "tool_call_end"; id: string },
): void {
if (event.type === "tool_call_start") {
// Guard against duplicate tool_call_start events for the same tool ID.
// This can occur due to stream retry, reconnection, or API quirks.
// Without this check, duplicate tool_use blocks with the same ID would
// be added to assistantMessageContent, causing API 400 errors:
// "tool_use ids must be unique"
if (this.streamingToolCallIndices.has(event.id)) {
console.warn(
`[Task#${this.taskId}] Ignoring duplicate tool_call_start for ID: ${event.id} (tool: ${event.name})`,
)
return
}
// Initialize streaming in NativeToolCallParser
NativeToolCallParser.startStreamingToolCall(event.id, event.name as ToolName)
// Before adding a new tool, finalize any preceding text block
// This prevents the text block from blocking tool presentation
const lastBlock = this.assistantMessageContent[this.assistantMessageContent.length - 1]
if (lastBlock?.type === "text" && lastBlock.partial) {
lastBlock.partial = false
}
// Track the index where this tool will be stored
const toolUseIndex = this.assistantMessageContent.length
this.streamingToolCallIndices.set(event.id, toolUseIndex)
// Create initial partial tool use
const partialToolUse: ToolUse = {
type: "tool_use",
name: event.name as ToolName,
params: {},
partial: true,
}
// Store the ID for native protocol
;(partialToolUse as any).id = event.id
// Add to content and present
this.assistantMessageContent.push(partialToolUse)
this.userMessageContentReady = false
presentAssistantMessage(this)
} else if (event.type === "tool_call_delta") {
// Process chunk using streaming JSON parser
const partialToolUse = NativeToolCallParser.processStreamingChunk(event.id, event.delta)
if (partialToolUse) {
// Get the index for this tool call
const toolUseIndex = this.streamingToolCallIndices.get(event.id)
if (toolUseIndex !== undefined) {
// Store the ID for native protocol
;(partialToolUse as any).id = event.id
// Update the existing tool use with new partial data
this.assistantMessageContent[toolUseIndex] = partialToolUse
// Present updated tool use
presentAssistantMessage(this)
}
}
} else if (event.type === "tool_call_end") {
// Finalize the streaming tool call
const finalToolUse = NativeToolCallParser.finalizeStreamingToolCall(event.id)
// Get the index for this tool call
const toolUseIndex = this.streamingToolCallIndices.get(event.id)
if (finalToolUse) {
// Store the tool call ID
;(finalToolUse as any).id = event.id
// Get the index and replace partial with final
if (toolUseIndex !== undefined) {
this.assistantMessageContent[toolUseIndex] = finalToolUse
}
// Clean up tracking
this.streamingToolCallIndices.delete(event.id)
// Mark that we have new content to process
this.userMessageContentReady = false
// Present the finalized tool call
presentAssistantMessage(this)
} else if (toolUseIndex !== undefined) {
// finalizeStreamingToolCall returned null (malformed JSON or missing args)
// Mark the tool as non-partial so it's presented as complete, but execution
// will be short-circuited in presentAssistantMessage with a structured tool_result.
const existingToolUse = this.assistantMessageContent[toolUseIndex]
if (existingToolUse && existingToolUse.type === "tool_use") {
existingToolUse.partial = false
// Ensure it has the ID for native protocol
;(existingToolUse as any).id = event.id
}
// Clean up tracking
this.streamingToolCallIndices.delete(event.id)
// Mark that we have new content to process
this.userMessageContentReady = false
// Present the tool call - validation will handle missing params
presentAssistantMessage(this)
}
}
}
didRejectTool = false
didAlreadyUseTool = false
didToolFailInCurrentTurn = false
didCompleteReadingStream = false
private _started = false
// No streaming parser is required.
assistantMessageParser?: undefined
private providerProfileChangeListener?: (config: { name: string; provider?: string }) => void
// Native tool call streaming state (track which index each tool is at)
private streamingToolCallIndices: Map<string, number> = new Map()
// Cached model info for current streaming session (set at start of each API request)
// This prevents excessive getModel() calls during tool execution
cachedStreamingModel?: { id: string; info: ModelInfo }
// Token Usage Cache
private tokenUsageSnapshot?: TokenUsage
private tokenUsageSnapshotAt?: number
// Tool Usage Cache
private toolUsageSnapshot?: ToolUsage
// Token Usage Throttling - Debounced emit function
private readonly TOKEN_USAGE_EMIT_INTERVAL_MS = 2000 // 2 seconds
private debouncedEmitTokenUsage: ReturnType<typeof debounce>
// Cloud Sync Tracking
private cloudSyncedMessageTimestamps: Set<number> = new Set()
// Initial status for the task's history item (set at creation time to avoid race conditions)
private readonly initialStatus?: "active" | "delegated" | "completed"
// MessageManager for high-level message operations (lazy initialized)
private _messageManager?: MessageManager
constructor({
provider,
apiConfiguration,
enableCheckpoints = true,
checkpointTimeout = DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
enableBridge = false,
consecutiveMistakeLimit = DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
task,
images,
historyItem,
experiments: experimentsConfig,
startTask = true,
rootTask,
parentTask,
taskNumber = -1,
onCreated,
initialTodos,
workspacePath,
initialStatus,
}: TaskOptions) {
super()
if (startTask && !task && !images && !historyItem) {
throw new Error("Either historyItem or task/images must be provided")
}
if (
!checkpointTimeout ||
checkpointTimeout > MAX_CHECKPOINT_TIMEOUT_SECONDS ||
checkpointTimeout < MIN_CHECKPOINT_TIMEOUT_SECONDS
) {
throw new Error(
"checkpointTimeout must be between " +
MIN_CHECKPOINT_TIMEOUT_SECONDS +
" and " +
MAX_CHECKPOINT_TIMEOUT_SECONDS +
" seconds",
)
}
this.taskId = historyItem ? historyItem.id : uuidv7()
this.rootTaskId = historyItem ? historyItem.rootTaskId : rootTask?.taskId
this.parentTaskId = historyItem ? historyItem.parentTaskId : parentTask?.taskId
this.childTaskId = undefined
this.metadata = {
task: historyItem ? historyItem.task : task,
images: historyItem ? [] : images,
}
// Normal use-case is usually retry similar history task with new workspace.
this.workspacePath = parentTask
? parentTask.workspacePath
: (workspacePath ?? getWorkspacePath(path.join(os.homedir(), "Desktop")))
this.instanceId = crypto.randomUUID().slice(0, 8)
this.taskNumber = -1
this.rooIgnoreController = new RooIgnoreController(this.cwd)
this.rooProtectedController = new RooProtectedController(this.cwd)
this.fileContextTracker = new FileContextTracker(provider, this.taskId)
this.rooIgnoreController.initialize().catch((error) => {
console.error("Failed to initialize RooIgnoreController:", error)
})
this.apiConfiguration = apiConfiguration
this.api = buildApiHandler(this.apiConfiguration)
this.autoApprovalHandler = new AutoApprovalHandler()
this.consecutiveMistakeLimit = consecutiveMistakeLimit ?? DEFAULT_CONSECUTIVE_MISTAKE_LIMIT
this.providerRef = new WeakRef(provider)
this.globalStoragePath = provider.context.globalStorageUri.fsPath
this.diffViewProvider = new DiffViewProvider(this.cwd, this)
this.enableCheckpoints = enableCheckpoints
this.checkpointTimeout = checkpointTimeout
this.enableBridge = enableBridge
this.parentTask = parentTask
this.taskNumber = taskNumber
this.initialStatus = initialStatus
// Store the task's mode and API config name when it's created.
// For history items, use the stored values; for new tasks, we'll set them
// after getting state.
if (historyItem) {
this._taskMode = historyItem.mode || defaultModeSlug
this._taskApiConfigName = historyItem.apiConfigName
this.taskModeReady = Promise.resolve()
this.taskApiConfigReady = Promise.resolve()
TelemetryService.instance.captureTaskRestarted(this.taskId)
} else {
// For new tasks, don't set the mode/apiConfigName yet - wait for async initialization.
this._taskMode = undefined
this._taskApiConfigName = undefined
this.taskModeReady = this.initializeTaskMode(provider)
this.taskApiConfigReady = this.initializeTaskApiConfigName(provider)
TelemetryService.instance.captureTaskCreated(this.taskId)
}
this.assistantMessageParser = undefined
this.messageQueueService = new MessageQueueService()
this.messageQueueStateChangedHandler = () => {
this.emit(RooCodeEventName.TaskUserMessage, this.taskId)
this.emit(RooCodeEventName.QueuedMessagesUpdated, this.taskId, this.messageQueueService.messages)
this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory()
}
this.messageQueueService.on("stateChanged", this.messageQueueStateChangedHandler)
// Listen for provider profile changes to update parser state
this.setupProviderProfileChangeListener(provider)
// Set up diff strategy
this.diffStrategy = new MultiSearchReplaceDiffStrategy()
this.toolRepetitionDetector = new ToolRepetitionDetector(this.consecutiveMistakeLimit)
// Initialize todo list if provided
if (initialTodos && initialTodos.length > 0) {
this.todoList = initialTodos
}
// Initialize debounced token usage emit function
// Uses debounce with maxWait to achieve throttle-like behavior:
// - leading: true - Emit immediately on first call
// - trailing: true - Emit final state when updates stop
// - maxWait - Ensures at most one emit per interval during rapid updates (throttle behavior)
this.debouncedEmitTokenUsage = debounce(
(tokenUsage: TokenUsage, toolUsage: ToolUsage) => {
const tokenChanged = hasTokenUsageChanged(tokenUsage, this.tokenUsageSnapshot)
const toolChanged = hasToolUsageChanged(toolUsage, this.toolUsageSnapshot)
if (tokenChanged || toolChanged) {
this.emit(RooCodeEventName.TaskTokenUsageUpdated, this.taskId, tokenUsage, toolUsage)
this.tokenUsageSnapshot = tokenUsage
this.tokenUsageSnapshotAt = this.clineMessages.at(-1)?.ts
// Deep copy tool usage for snapshot
this.toolUsageSnapshot = JSON.parse(JSON.stringify(toolUsage))
}
},
this.TOKEN_USAGE_EMIT_INTERVAL_MS,
{ leading: true, trailing: true, maxWait: this.TOKEN_USAGE_EMIT_INTERVAL_MS },
)
onCreated?.(this)
if (startTask) {
this._started = true
if (task || images) {
this.runLifecycleTaskInBackground(this.startTask(task, images), "startTask")
} else if (historyItem) {
this.runLifecycleTaskInBackground(this.resumeTaskFromHistory(), "resumeTaskFromHistory")
} else {
throw new Error("Either historyItem or task/images must be provided")
}
}
}
private runLifecycleTaskInBackground(taskPromise: Promise<void>, operation: "startTask" | "resumeTaskFromHistory") {
void taskPromise.catch((error) => {
if (this.shouldIgnoreBackgroundLifecycleError(error)) {
return
}
console.error(
`[Task#${operation}] task ${this.taskId}.${this.instanceId} failed: ${
error instanceof Error ? error.message : String(error)
}`,
)
})
}
private shouldIgnoreBackgroundLifecycleError(error: unknown): boolean {
if (error instanceof AskIgnoredError) {
return true
}
if (this.abandoned === true || this.abort === true || this.abortReason === "user_cancelled") {
return true
}
if (!(error instanceof Error)) {
return false
}
const abortedByCurrentTask =
error.message.includes(`[RooCode#ask] task ${this.taskId}.${this.instanceId} aborted`) ||
error.message.includes(`[RooCode#say] task ${this.taskId}.${this.instanceId} aborted`)
return abortedByCurrentTask
}
/**
* Initialize the task mode from the provider state.
* This method handles async initialization with proper error handling.
*
* ## Flow
* 1. Attempts to fetch the current mode from provider state
* 2. Sets `_taskMode` to the fetched mode or `defaultModeSlug` if unavailable
* 3. Handles errors gracefully by falling back to default mode
* 4. Logs any initialization errors for debugging
*
* ## Error handling
* - Network failures when fetching provider state
* - Provider not yet initialized
* - Invalid state structure
*
* All errors result in fallback to `defaultModeSlug` to ensure task can proceed.
*
* @private
* @param provider - The ClineProvider instance to fetch state from
* @returns Promise that resolves when initialization is complete
*/
private async initializeTaskMode(provider: ClineProvider): Promise<void> {
try {
const state = await provider.getState()
this._taskMode = state?.mode || defaultModeSlug
} catch (error) {
// If there's an error getting state, use the default mode
this._taskMode = defaultModeSlug
// Use the provider's log method for better error visibility
const errorMessage = `Failed to initialize task mode: ${error instanceof Error ? error.message : String(error)}`
provider.log(errorMessage)
}
}
/**
* Initialize the task API config name from the provider state.
* This method handles async initialization with proper error handling.
*
* ## Flow
* 1. Attempts to fetch the current API config name from provider state
* 2. Sets `_taskApiConfigName` to the fetched name or "default" if unavailable
* 3. Handles errors gracefully by falling back to "default"
* 4. Logs any initialization errors for debugging
*
* ## Error handling
* - Network failures when fetching provider state
* - Provider not yet initialized
* - Invalid state structure
*
* All errors result in fallback to "default" to ensure task can proceed.
*
* @private
* @param provider - The ClineProvider instance to fetch state from
* @returns Promise that resolves when initialization is complete
*/
private async initializeTaskApiConfigName(provider: ClineProvider): Promise<void> {
try {
const state = await provider.getState()
// Avoid clobbering a newer value that may have been set while awaiting provider state
// (e.g., user switches provider profile immediately after task creation).
if (this._taskApiConfigName === undefined) {
this._taskApiConfigName = state?.currentApiConfigName ?? "default"
}
} catch (error) {
// If there's an error getting state, use the default profile (unless a newer value was set).
if (this._taskApiConfigName === undefined) {
this._taskApiConfigName = "default"
}
// Use the provider's log method for better error visibility
const errorMessage = `Failed to initialize task API config name: ${error instanceof Error ? error.message : String(error)}`
provider.log(errorMessage)
}
}
/**
* Sets up a listener for provider profile changes.
*
* @private
* @param provider - The ClineProvider instance to listen to
*/
private setupProviderProfileChangeListener(provider: ClineProvider): void {
// Only set up listener if provider has the on method (may not exist in test mocks)
if (typeof provider.on !== "function") {
return
}
this.providerProfileChangeListener = async () => {
try {
const newState = await provider.getState()
if (newState?.apiConfiguration) {
this.updateApiConfiguration(newState.apiConfiguration)
}
} catch (error) {
console.error(
`[Task#${this.taskId}.${this.instanceId}] Failed to update API configuration on profile change:`,
error,
)
}
}
provider.on(RooCodeEventName.ProviderProfileChanged, this.providerProfileChangeListener)
}
/**
* Wait for the task mode to be initialized before proceeding.
* This method ensures that any operations depending on the task mode
* will have access to the correct mode value.
*
* ## When to use
* - Before accessing mode-specific configurations
* - When switching between tasks with different modes
* - Before operations that depend on mode-based permissions
*
* ## Example usage
* ```typescript
* // Wait for mode initialization before mode-dependent operations
* await task.waitForModeInitialization();
* const mode = task.taskMode; // Now safe to access synchronously
*
* // Or use with getTaskMode() for a one-liner
* const mode = await task.getTaskMode(); // Internally waits for initialization
* ```
*
* @returns Promise that resolves when the task mode is initialized
* @public
*/
public async waitForModeInitialization(): Promise<void> {
return this.taskModeReady
}
/**
* Get the task mode asynchronously, ensuring it's properly initialized.
* This is the recommended way to access the task mode as it guarantees
* the mode is available before returning.
*
* ## Async behavior
* - Internally waits for `taskModeReady` promise to resolve
* - Returns the initialized mode or `defaultModeSlug` as fallback
* - Safe to call multiple times - subsequent calls return immediately if already initialized
*
* ## Example usage
* ```typescript
* // Safe async access
* const mode = await task.getTaskMode();
* console.log(`Task is running in ${mode} mode`);
*
* // Use in conditional logic
* if (await task.getTaskMode() === 'architect') {
* // Perform architect-specific operations
* }
* ```
*
* @returns Promise resolving to the task mode string
* @public
*/
public async getTaskMode(): Promise<string> {
await this.taskModeReady
return this._taskMode || defaultModeSlug
}
/**
* Get the task mode synchronously. This should only be used when you're certain
* that the mode has already been initialized (e.g., after waitForModeInitialization).
*
* ## When to use
* - In synchronous contexts where async/await is not available
* - After explicitly waiting for initialization via `waitForModeInitialization()`
* - In event handlers or callbacks where mode is guaranteed to be initialized
*
* ## Example usage
* ```typescript
* // After ensuring initialization
* await task.waitForModeInitialization();
* const mode = task.taskMode; // Safe synchronous access
*
* // In an event handler after task is started
* task.on('taskStarted', () => {
* console.log(`Task started in ${task.taskMode} mode`); // Safe here
* });
* ```
*
* @throws {Error} If the mode hasn't been initialized yet
* @returns The task mode string
* @public
*/
public get taskMode(): string {
if (this._taskMode === undefined) {
throw new Error("Task mode accessed before initialization. Use getTaskMode() or wait for taskModeReady.")
}
return this._taskMode
}
/**
* Wait for the task API config name to be initialized before proceeding.
* This method ensures that any operations depending on the task's provider profile
* will have access to the correct value.
*
* ## When to use
* - Before accessing provider profile-specific configurations
* - When switching between tasks with different provider profiles
* - Before operations that depend on the provider profile
*
* @returns Promise that resolves when the task API config name is initialized
* @public
*/
public async waitForApiConfigInitialization(): Promise<void> {
return this.taskApiConfigReady
}
/**
* Get the task API config name asynchronously, ensuring it's properly initialized.
* This is the recommended way to access the task's provider profile as it guarantees
* the value is available before returning.
*
* ## Async behavior
* - Internally waits for `taskApiConfigReady` promise to resolve
* - Returns the initialized API config name or undefined as fallback
* - Safe to call multiple times - subsequent calls return immediately if already initialized
*
* @returns Promise resolving to the task API config name string or undefined
* @public
*/
public async getTaskApiConfigName(): Promise<string | undefined> {
await this.taskApiConfigReady
return this._taskApiConfigName
}
/**
* Get the task API config name synchronously. This should only be used when you're certain
* that the value has already been initialized (e.g., after waitForApiConfigInitialization).
*
* ## When to use