Task.ts 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235
  1. import * as path from "path"
  2. import * as vscode from "vscode"
  3. import os from "os"
  4. import crypto from "crypto"
  5. import EventEmitter from "events"
  6. import { Anthropic } from "@anthropic-ai/sdk"
  7. import OpenAI from "openai"
  8. import delay from "delay"
  9. import pWaitFor from "p-wait-for"
  10. import { serializeError } from "serialize-error"
  11. import { Package } from "../../shared/package"
  12. import {
  13. type TaskLike,
  14. type TaskMetadata,
  15. type TaskEvents,
  16. type ProviderSettings,
  17. type TokenUsage,
  18. type ToolUsage,
  19. type ToolName,
  20. type ContextCondense,
  21. type ClineMessage,
  22. type ClineSay,
  23. type ClineAsk,
  24. type ToolProgressStatus,
  25. type HistoryItem,
  26. type CreateTaskOptions,
  27. RooCodeEventName,
  28. TelemetryEventName,
  29. TaskStatus,
  30. TodoItem,
  31. getApiProtocol,
  32. getModelId,
  33. isIdleAsk,
  34. isInteractiveAsk,
  35. isResumableAsk,
  36. QueuedMessage,
  37. DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
  38. DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
  39. MAX_CHECKPOINT_TIMEOUT_SECONDS,
  40. MIN_CHECKPOINT_TIMEOUT_SECONDS,
  41. TOOL_PROTOCOL,
  42. ToolProtocol,
  43. } from "@roo-code/types"
  44. import { TelemetryService } from "@roo-code/telemetry"
  45. import { CloudService, BridgeOrchestrator } from "@roo-code/cloud"
  46. // api
  47. import { ApiHandler, ApiHandlerCreateMessageMetadata, buildApiHandler } from "../../api"
  48. import { ApiStream, GroundingSource } from "../../api/transform/stream"
  49. import { maybeRemoveImageBlocks } from "../../api/transform/image-cleaning"
  50. // shared
  51. import { findLastIndex } from "../../shared/array"
  52. import { combineApiRequests } from "../../shared/combineApiRequests"
  53. import { combineCommandSequences } from "../../shared/combineCommandSequences"
  54. import { t } from "../../i18n"
  55. import { ClineApiReqCancelReason, ClineApiReqInfo } from "../../shared/ExtensionMessage"
  56. import { getApiMetrics, hasTokenUsageChanged } from "../../shared/getApiMetrics"
  57. import { ClineAskResponse } from "../../shared/WebviewMessage"
  58. import { defaultModeSlug, getModeBySlug, getGroupName } from "../../shared/modes"
  59. import { DiffStrategy } from "../../shared/tools"
  60. import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
  61. import { getModelMaxOutputTokens } from "../../shared/api"
  62. // services
  63. import { UrlContentFetcher } from "../../services/browser/UrlContentFetcher"
  64. import { BrowserSession } from "../../services/browser/BrowserSession"
  65. import { McpHub } from "../../services/mcp/McpHub"
  66. import { McpServerManager } from "../../services/mcp/McpServerManager"
  67. import { RepoPerTaskCheckpointService } from "../../services/checkpoints"
  68. // integrations
  69. import { DiffViewProvider } from "../../integrations/editor/DiffViewProvider"
  70. import { findToolName } from "../../integrations/misc/export-markdown"
  71. import { RooTerminalProcess } from "../../integrations/terminal/types"
  72. import { TerminalRegistry } from "../../integrations/terminal/TerminalRegistry"
  73. // utils
  74. import { calculateApiCostAnthropic, calculateApiCostOpenAI } from "../../shared/cost"
  75. import { getWorkspacePath } from "../../utils/path"
  76. // prompts
  77. import { formatResponse } from "../prompts/responses"
  78. import { SYSTEM_PROMPT } from "../prompts/system"
  79. import { nativeTools, getMcpServerTools } from "../prompts/tools/native-tools"
  80. // core modules
  81. import { ToolRepetitionDetector } from "../tools/ToolRepetitionDetector"
  82. import { restoreTodoListForTask } from "../tools/UpdateTodoListTool"
  83. import { FileContextTracker } from "../context-tracking/FileContextTracker"
  84. import { RooIgnoreController } from "../ignore/RooIgnoreController"
  85. import { RooProtectedController } from "../protect/RooProtectedController"
  86. import { type AssistantMessageContent, presentAssistantMessage } from "../assistant-message"
  87. import { AssistantMessageParser } from "../assistant-message/AssistantMessageParser"
  88. import { NativeToolCallParser } from "../assistant-message/NativeToolCallParser"
  89. import { manageContext } from "../context-management"
  90. import { ClineProvider } from "../webview/ClineProvider"
  91. import { MultiSearchReplaceDiffStrategy } from "../diff/strategies/multi-search-replace"
  92. import { MultiFileSearchReplaceDiffStrategy } from "../diff/strategies/multi-file-search-replace"
  93. import {
  94. type ApiMessage,
  95. readApiMessages,
  96. saveApiMessages,
  97. readTaskMessages,
  98. saveTaskMessages,
  99. taskMetadata,
  100. } from "../task-persistence"
  101. import { getEnvironmentDetails } from "../environment/getEnvironmentDetails"
  102. import { checkContextWindowExceededError } from "../context/context-management/context-error-handling"
  103. import {
  104. type CheckpointDiffOptions,
  105. type CheckpointRestoreOptions,
  106. getCheckpointService,
  107. checkpointSave,
  108. checkpointRestore,
  109. checkpointDiff,
  110. } from "../checkpoints"
  111. import { processUserContentMentions } from "../mentions/processUserContentMentions"
  112. import { getMessagesSinceLastSummary, summarizeConversation } from "../condense"
  113. import { MessageQueueService } from "../message-queue/MessageQueueService"
  114. import { AutoApprovalHandler, checkAutoApproval } from "../auto-approval"
  115. const MAX_EXPONENTIAL_BACKOFF_SECONDS = 600 // 10 minutes
  116. const DEFAULT_USAGE_COLLECTION_TIMEOUT_MS = 5000 // 5 seconds
  117. const FORCED_CONTEXT_REDUCTION_PERCENT = 75 // Keep 75% of context (remove 25%) on context window errors
  118. const MAX_CONTEXT_WINDOW_RETRIES = 3 // Maximum retries for context window errors
  119. export interface TaskOptions extends CreateTaskOptions {
  120. provider: ClineProvider
  121. apiConfiguration: ProviderSettings
  122. enableDiff?: boolean
  123. enableCheckpoints?: boolean
  124. checkpointTimeout?: number
  125. enableBridge?: boolean
  126. fuzzyMatchThreshold?: number
  127. consecutiveMistakeLimit?: number
  128. task?: string
  129. images?: string[]
  130. historyItem?: HistoryItem
  131. experiments?: Record<string, boolean>
  132. startTask?: boolean
  133. rootTask?: Task
  134. parentTask?: Task
  135. taskNumber?: number
  136. onCreated?: (task: Task) => void
  137. initialTodos?: TodoItem[]
  138. workspacePath?: string
  139. }
  140. export class Task extends EventEmitter<TaskEvents> implements TaskLike {
  141. readonly taskId: string
  142. readonly rootTaskId?: string
  143. readonly parentTaskId?: string
  144. childTaskId?: string
  145. readonly instanceId: string
  146. readonly metadata: TaskMetadata
  147. todoList?: TodoItem[]
  148. readonly rootTask: Task | undefined = undefined
  149. readonly parentTask: Task | undefined = undefined
  150. readonly taskNumber: number
  151. readonly workspacePath: string
  152. /**
  153. * The mode associated with this task. Persisted across sessions
  154. * to maintain user context when reopening tasks from history.
  155. *
  156. * ## Lifecycle
  157. *
  158. * ### For new tasks:
  159. * 1. Initially `undefined` during construction
  160. * 2. Asynchronously initialized from provider state via `initializeTaskMode()`
  161. * 3. Falls back to `defaultModeSlug` if provider state is unavailable
  162. *
  163. * ### For history items:
  164. * 1. Immediately set from `historyItem.mode` during construction
  165. * 2. Falls back to `defaultModeSlug` if mode is not stored in history
  166. *
  167. * ## Important
  168. * This property should NOT be accessed directly until `taskModeReady` promise resolves.
  169. * Use `getTaskMode()` for async access or `taskMode` getter for sync access after initialization.
  170. *
  171. * @private
  172. * @see {@link getTaskMode} - For safe async access
  173. * @see {@link taskMode} - For sync access after initialization
  174. * @see {@link waitForModeInitialization} - To ensure initialization is complete
  175. */
  176. private _taskMode: string | undefined
  177. /**
  178. * Promise that resolves when the task mode has been initialized.
  179. * This ensures async mode initialization completes before the task is used.
  180. *
  181. * ## Purpose
  182. * - Prevents race conditions when accessing task mode
  183. * - Ensures provider state is properly loaded before mode-dependent operations
  184. * - Provides a synchronization point for async initialization
  185. *
  186. * ## Resolution timing
  187. * - For history items: Resolves immediately (sync initialization)
  188. * - For new tasks: Resolves after provider state is fetched (async initialization)
  189. *
  190. * @private
  191. * @see {@link waitForModeInitialization} - Public method to await this promise
  192. */
  193. private taskModeReady: Promise<void>
  194. providerRef: WeakRef<ClineProvider>
  195. private readonly globalStoragePath: string
  196. abort: boolean = false
  197. // TaskStatus
  198. idleAsk?: ClineMessage
  199. resumableAsk?: ClineMessage
  200. interactiveAsk?: ClineMessage
  201. didFinishAbortingStream = false
  202. abandoned = false
  203. abortReason?: ClineApiReqCancelReason
  204. isInitialized = false
  205. isPaused: boolean = false
  206. pausedModeSlug: string = defaultModeSlug
  207. private pauseInterval: NodeJS.Timeout | undefined
  208. // API
  209. readonly apiConfiguration: ProviderSettings
  210. api: ApiHandler
  211. private static lastGlobalApiRequestTime?: number
  212. private autoApprovalHandler: AutoApprovalHandler
  213. /**
  214. * Reset the global API request timestamp. This should only be used for testing.
  215. * @internal
  216. */
  217. static resetGlobalApiRequestTime(): void {
  218. Task.lastGlobalApiRequestTime = undefined
  219. }
  220. toolRepetitionDetector: ToolRepetitionDetector
  221. rooIgnoreController?: RooIgnoreController
  222. rooProtectedController?: RooProtectedController
  223. fileContextTracker: FileContextTracker
  224. urlContentFetcher: UrlContentFetcher
  225. terminalProcess?: RooTerminalProcess
  226. // Computer User
  227. browserSession: BrowserSession
  228. // Editing
  229. diffViewProvider: DiffViewProvider
  230. diffStrategy?: DiffStrategy
  231. diffEnabled: boolean = false
  232. fuzzyMatchThreshold: number
  233. didEditFile: boolean = false
  234. // LLM Messages & Chat Messages
  235. apiConversationHistory: ApiMessage[] = []
  236. clineMessages: ClineMessage[] = []
  237. // Ask
  238. private askResponse?: ClineAskResponse
  239. private askResponseText?: string
  240. private askResponseImages?: string[]
  241. public lastMessageTs?: number
  242. // Tool Use
  243. consecutiveMistakeCount: number = 0
  244. consecutiveMistakeLimit: number
  245. consecutiveMistakeCountForApplyDiff: Map<string, number> = new Map()
  246. toolUsage: ToolUsage = {}
  247. // Checkpoints
  248. enableCheckpoints: boolean
  249. checkpointTimeout: number
  250. checkpointService?: RepoPerTaskCheckpointService
  251. checkpointServiceInitializing = false
  252. // Task Bridge
  253. enableBridge: boolean
  254. // Message Queue Service
  255. public readonly messageQueueService: MessageQueueService
  256. private messageQueueStateChangedHandler: (() => void) | undefined
  257. // Streaming
  258. isWaitingForFirstChunk = false
  259. isStreaming = false
  260. currentStreamingContentIndex = 0
  261. currentStreamingDidCheckpoint = false
  262. assistantMessageContent: AssistantMessageContent[] = []
  263. presentAssistantMessageLocked = false
  264. presentAssistantMessageHasPendingUpdates = false
  265. userMessageContent: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolResultBlockParam)[] = []
  266. userMessageContentReady = false
  267. didRejectTool = false
  268. didAlreadyUseTool = false
  269. didCompleteReadingStream = false
  270. assistantMessageParser: AssistantMessageParser
  271. // Token Usage Cache
  272. private tokenUsageSnapshot?: TokenUsage
  273. private tokenUsageSnapshotAt?: number
  274. constructor({
  275. provider,
  276. apiConfiguration,
  277. enableDiff = false,
  278. enableCheckpoints = true,
  279. checkpointTimeout = DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
  280. enableBridge = false,
  281. fuzzyMatchThreshold = 1.0,
  282. consecutiveMistakeLimit = DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
  283. task,
  284. images,
  285. historyItem,
  286. startTask = true,
  287. rootTask,
  288. parentTask,
  289. taskNumber = -1,
  290. onCreated,
  291. initialTodos,
  292. workspacePath,
  293. }: TaskOptions) {
  294. super()
  295. if (startTask && !task && !images && !historyItem) {
  296. throw new Error("Either historyItem or task/images must be provided")
  297. }
  298. if (
  299. !checkpointTimeout ||
  300. checkpointTimeout > MAX_CHECKPOINT_TIMEOUT_SECONDS ||
  301. checkpointTimeout < MIN_CHECKPOINT_TIMEOUT_SECONDS
  302. ) {
  303. throw new Error(
  304. "checkpointTimeout must be between " +
  305. MIN_CHECKPOINT_TIMEOUT_SECONDS +
  306. " and " +
  307. MAX_CHECKPOINT_TIMEOUT_SECONDS +
  308. " seconds",
  309. )
  310. }
  311. this.taskId = historyItem ? historyItem.id : crypto.randomUUID()
  312. this.rootTaskId = historyItem ? historyItem.rootTaskId : rootTask?.taskId
  313. this.parentTaskId = historyItem ? historyItem.parentTaskId : parentTask?.taskId
  314. this.childTaskId = undefined
  315. this.metadata = {
  316. task: historyItem ? historyItem.task : task,
  317. images: historyItem ? [] : images,
  318. }
  319. // Normal use-case is usually retry similar history task with new workspace.
  320. this.workspacePath = parentTask
  321. ? parentTask.workspacePath
  322. : (workspacePath ?? getWorkspacePath(path.join(os.homedir(), "Desktop")))
  323. this.instanceId = crypto.randomUUID().slice(0, 8)
  324. this.taskNumber = -1
  325. this.rooIgnoreController = new RooIgnoreController(this.cwd)
  326. this.rooProtectedController = new RooProtectedController(this.cwd)
  327. this.fileContextTracker = new FileContextTracker(provider, this.taskId)
  328. this.rooIgnoreController.initialize().catch((error) => {
  329. console.error("Failed to initialize RooIgnoreController:", error)
  330. })
  331. this.apiConfiguration = apiConfiguration
  332. this.api = buildApiHandler(apiConfiguration)
  333. this.autoApprovalHandler = new AutoApprovalHandler()
  334. this.urlContentFetcher = new UrlContentFetcher(provider.context)
  335. this.browserSession = new BrowserSession(provider.context)
  336. this.diffEnabled = enableDiff
  337. this.fuzzyMatchThreshold = fuzzyMatchThreshold
  338. this.consecutiveMistakeLimit = consecutiveMistakeLimit ?? DEFAULT_CONSECUTIVE_MISTAKE_LIMIT
  339. this.providerRef = new WeakRef(provider)
  340. this.globalStoragePath = provider.context.globalStorageUri.fsPath
  341. this.diffViewProvider = new DiffViewProvider(this.cwd, this)
  342. this.enableCheckpoints = enableCheckpoints
  343. this.checkpointTimeout = checkpointTimeout
  344. this.enableBridge = enableBridge
  345. this.parentTask = parentTask
  346. this.taskNumber = taskNumber
  347. // Store the task's mode when it's created.
  348. // For history items, use the stored mode; for new tasks, we'll set it
  349. // after getting state.
  350. if (historyItem) {
  351. this._taskMode = historyItem.mode || defaultModeSlug
  352. this.taskModeReady = Promise.resolve()
  353. TelemetryService.instance.captureTaskRestarted(this.taskId)
  354. } else {
  355. // For new tasks, don't set the mode yet - wait for async initialization.
  356. this._taskMode = undefined
  357. this.taskModeReady = this.initializeTaskMode(provider)
  358. TelemetryService.instance.captureTaskCreated(this.taskId)
  359. }
  360. // Initialize the assistant message parser.
  361. this.assistantMessageParser = new AssistantMessageParser()
  362. this.messageQueueService = new MessageQueueService()
  363. this.messageQueueStateChangedHandler = () => {
  364. this.emit(RooCodeEventName.TaskUserMessage, this.taskId)
  365. this.providerRef.deref()?.postStateToWebview()
  366. }
  367. this.messageQueueService.on("stateChanged", this.messageQueueStateChangedHandler)
  368. // Only set up diff strategy if diff is enabled.
  369. if (this.diffEnabled) {
  370. // Default to old strategy, will be updated if experiment is enabled.
  371. this.diffStrategy = new MultiSearchReplaceDiffStrategy(this.fuzzyMatchThreshold)
  372. // Check experiment asynchronously and update strategy if needed.
  373. provider.getState().then((state) => {
  374. const isMultiFileApplyDiffEnabled = experiments.isEnabled(
  375. state.experiments ?? {},
  376. EXPERIMENT_IDS.MULTI_FILE_APPLY_DIFF,
  377. )
  378. if (isMultiFileApplyDiffEnabled) {
  379. this.diffStrategy = new MultiFileSearchReplaceDiffStrategy(this.fuzzyMatchThreshold)
  380. }
  381. })
  382. }
  383. this.toolRepetitionDetector = new ToolRepetitionDetector(this.consecutiveMistakeLimit)
  384. // Initialize todo list if provided
  385. if (initialTodos && initialTodos.length > 0) {
  386. this.todoList = initialTodos
  387. }
  388. onCreated?.(this)
  389. if (startTask) {
  390. if (task || images) {
  391. this.startTask(task, images)
  392. } else if (historyItem) {
  393. this.resumeTaskFromHistory()
  394. } else {
  395. throw new Error("Either historyItem or task/images must be provided")
  396. }
  397. }
  398. }
  399. /**
  400. * Initialize the task mode from the provider state.
  401. * This method handles async initialization with proper error handling.
  402. *
  403. * ## Flow
  404. * 1. Attempts to fetch the current mode from provider state
  405. * 2. Sets `_taskMode` to the fetched mode or `defaultModeSlug` if unavailable
  406. * 3. Handles errors gracefully by falling back to default mode
  407. * 4. Logs any initialization errors for debugging
  408. *
  409. * ## Error handling
  410. * - Network failures when fetching provider state
  411. * - Provider not yet initialized
  412. * - Invalid state structure
  413. *
  414. * All errors result in fallback to `defaultModeSlug` to ensure task can proceed.
  415. *
  416. * @private
  417. * @param provider - The ClineProvider instance to fetch state from
  418. * @returns Promise that resolves when initialization is complete
  419. */
  420. private async initializeTaskMode(provider: ClineProvider): Promise<void> {
  421. try {
  422. const state = await provider.getState()
  423. this._taskMode = state?.mode || defaultModeSlug
  424. } catch (error) {
  425. // If there's an error getting state, use the default mode
  426. this._taskMode = defaultModeSlug
  427. // Use the provider's log method for better error visibility
  428. const errorMessage = `Failed to initialize task mode: ${error instanceof Error ? error.message : String(error)}`
  429. provider.log(errorMessage)
  430. }
  431. }
  432. /**
  433. * Wait for the task mode to be initialized before proceeding.
  434. * This method ensures that any operations depending on the task mode
  435. * will have access to the correct mode value.
  436. *
  437. * ## When to use
  438. * - Before accessing mode-specific configurations
  439. * - When switching between tasks with different modes
  440. * - Before operations that depend on mode-based permissions
  441. *
  442. * ## Example usage
  443. * ```typescript
  444. * // Wait for mode initialization before mode-dependent operations
  445. * await task.waitForModeInitialization();
  446. * const mode = task.taskMode; // Now safe to access synchronously
  447. *
  448. * // Or use with getTaskMode() for a one-liner
  449. * const mode = await task.getTaskMode(); // Internally waits for initialization
  450. * ```
  451. *
  452. * @returns Promise that resolves when the task mode is initialized
  453. * @public
  454. */
  455. public async waitForModeInitialization(): Promise<void> {
  456. return this.taskModeReady
  457. }
  458. /**
  459. * Get the task mode asynchronously, ensuring it's properly initialized.
  460. * This is the recommended way to access the task mode as it guarantees
  461. * the mode is available before returning.
  462. *
  463. * ## Async behavior
  464. * - Internally waits for `taskModeReady` promise to resolve
  465. * - Returns the initialized mode or `defaultModeSlug` as fallback
  466. * - Safe to call multiple times - subsequent calls return immediately if already initialized
  467. *
  468. * ## Example usage
  469. * ```typescript
  470. * // Safe async access
  471. * const mode = await task.getTaskMode();
  472. * console.log(`Task is running in ${mode} mode`);
  473. *
  474. * // Use in conditional logic
  475. * if (await task.getTaskMode() === 'architect') {
  476. * // Perform architect-specific operations
  477. * }
  478. * ```
  479. *
  480. * @returns Promise resolving to the task mode string
  481. * @public
  482. */
  483. public async getTaskMode(): Promise<string> {
  484. await this.taskModeReady
  485. return this._taskMode || defaultModeSlug
  486. }
  487. /**
  488. * Get the task mode synchronously. This should only be used when you're certain
  489. * that the mode has already been initialized (e.g., after waitForModeInitialization).
  490. *
  491. * ## When to use
  492. * - In synchronous contexts where async/await is not available
  493. * - After explicitly waiting for initialization via `waitForModeInitialization()`
  494. * - In event handlers or callbacks where mode is guaranteed to be initialized
  495. *
  496. * ## Example usage
  497. * ```typescript
  498. * // After ensuring initialization
  499. * await task.waitForModeInitialization();
  500. * const mode = task.taskMode; // Safe synchronous access
  501. *
  502. * // In an event handler after task is started
  503. * task.on('taskStarted', () => {
  504. * console.log(`Task started in ${task.taskMode} mode`); // Safe here
  505. * });
  506. * ```
  507. *
  508. * @throws {Error} If the mode hasn't been initialized yet
  509. * @returns The task mode string
  510. * @public
  511. */
  512. public get taskMode(): string {
  513. if (this._taskMode === undefined) {
  514. throw new Error("Task mode accessed before initialization. Use getTaskMode() or wait for taskModeReady.")
  515. }
  516. return this._taskMode
  517. }
  518. static create(options: TaskOptions): [Task, Promise<void>] {
  519. const instance = new Task({ ...options, startTask: false })
  520. const { images, task, historyItem } = options
  521. let promise
  522. if (images || task) {
  523. promise = instance.startTask(task, images)
  524. } else if (historyItem) {
  525. promise = instance.resumeTaskFromHistory()
  526. } else {
  527. throw new Error("Either historyItem or task/images must be provided")
  528. }
  529. return [instance, promise]
  530. }
  531. // API Messages
  532. private async getSavedApiConversationHistory(): Promise<ApiMessage[]> {
  533. return readApiMessages({ taskId: this.taskId, globalStoragePath: this.globalStoragePath })
  534. }
  535. private async addToApiConversationHistory(message: Anthropic.MessageParam) {
  536. // Capture the encrypted_content from the provider (e.g., OpenAI Responses API) if present.
  537. // We only persist data reported by the current response body.
  538. const handler = this.api as ApiHandler & {
  539. getResponseId?: () => string | undefined
  540. getEncryptedContent?: () => { encrypted_content: string; id?: string } | undefined
  541. }
  542. if (message.role === "assistant") {
  543. const responseId = handler.getResponseId?.()
  544. const reasoningData = handler.getEncryptedContent?.()
  545. // If we have encrypted_content, add it as a reasoning item before the assistant message
  546. if (reasoningData?.encrypted_content) {
  547. this.apiConversationHistory.push({
  548. type: "reasoning",
  549. summary: [],
  550. encrypted_content: reasoningData.encrypted_content,
  551. ...(reasoningData.id ? { id: reasoningData.id } : {}),
  552. ts: Date.now(),
  553. } as any)
  554. }
  555. const messageWithTs = {
  556. ...message,
  557. ...(responseId ? { id: responseId } : {}),
  558. ts: Date.now(),
  559. }
  560. this.apiConversationHistory.push(messageWithTs)
  561. } else {
  562. const messageWithTs = { ...message, ts: Date.now() }
  563. this.apiConversationHistory.push(messageWithTs)
  564. }
  565. await this.saveApiConversationHistory()
  566. }
  567. async overwriteApiConversationHistory(newHistory: ApiMessage[]) {
  568. this.apiConversationHistory = newHistory
  569. await this.saveApiConversationHistory()
  570. }
  571. private async saveApiConversationHistory() {
  572. try {
  573. await saveApiMessages({
  574. messages: this.apiConversationHistory,
  575. taskId: this.taskId,
  576. globalStoragePath: this.globalStoragePath,
  577. })
  578. } catch (error) {
  579. // In the off chance this fails, we don't want to stop the task.
  580. console.error("Failed to save API conversation history:", error)
  581. }
  582. }
  583. // Cline Messages
  584. private async getSavedClineMessages(): Promise<ClineMessage[]> {
  585. return readTaskMessages({ taskId: this.taskId, globalStoragePath: this.globalStoragePath })
  586. }
  587. private async addToClineMessages(message: ClineMessage) {
  588. this.clineMessages.push(message)
  589. const provider = this.providerRef.deref()
  590. await provider?.postStateToWebview()
  591. this.emit(RooCodeEventName.Message, { action: "created", message })
  592. await this.saveClineMessages()
  593. const shouldCaptureMessage = message.partial !== true && CloudService.isEnabled()
  594. if (shouldCaptureMessage) {
  595. CloudService.instance.captureEvent({
  596. event: TelemetryEventName.TASK_MESSAGE,
  597. properties: { taskId: this.taskId, message },
  598. })
  599. }
  600. }
  601. public async overwriteClineMessages(newMessages: ClineMessage[]) {
  602. this.clineMessages = newMessages
  603. restoreTodoListForTask(this)
  604. await this.saveClineMessages()
  605. }
  606. private async updateClineMessage(message: ClineMessage) {
  607. const provider = this.providerRef.deref()
  608. await provider?.postMessageToWebview({ type: "messageUpdated", clineMessage: message })
  609. this.emit(RooCodeEventName.Message, { action: "updated", message })
  610. const shouldCaptureMessage = message.partial !== true && CloudService.isEnabled()
  611. if (shouldCaptureMessage) {
  612. CloudService.instance.captureEvent({
  613. event: TelemetryEventName.TASK_MESSAGE,
  614. properties: { taskId: this.taskId, message },
  615. })
  616. }
  617. }
  618. private async saveClineMessages() {
  619. try {
  620. await saveTaskMessages({
  621. messages: this.clineMessages,
  622. taskId: this.taskId,
  623. globalStoragePath: this.globalStoragePath,
  624. })
  625. const { historyItem, tokenUsage } = await taskMetadata({
  626. taskId: this.taskId,
  627. rootTaskId: this.rootTaskId,
  628. parentTaskId: this.parentTaskId,
  629. taskNumber: this.taskNumber,
  630. messages: this.clineMessages,
  631. globalStoragePath: this.globalStoragePath,
  632. workspace: this.cwd,
  633. mode: this._taskMode || defaultModeSlug, // Use the task's own mode, not the current provider mode.
  634. })
  635. if (hasTokenUsageChanged(tokenUsage, this.tokenUsageSnapshot)) {
  636. this.emit(RooCodeEventName.TaskTokenUsageUpdated, this.taskId, tokenUsage)
  637. this.tokenUsageSnapshot = undefined
  638. this.tokenUsageSnapshotAt = undefined
  639. }
  640. await this.providerRef.deref()?.updateTaskHistory(historyItem)
  641. } catch (error) {
  642. console.error("Failed to save Roo messages:", error)
  643. }
  644. }
  645. private findMessageByTimestamp(ts: number): ClineMessage | undefined {
  646. for (let i = this.clineMessages.length - 1; i >= 0; i--) {
  647. if (this.clineMessages[i].ts === ts) {
  648. return this.clineMessages[i]
  649. }
  650. }
  651. return undefined
  652. }
  653. // Note that `partial` has three valid states true (partial message),
  654. // false (completion of partial message), undefined (individual complete
  655. // message).
  656. async ask(
  657. type: ClineAsk,
  658. text?: string,
  659. partial?: boolean,
  660. progressStatus?: ToolProgressStatus,
  661. isProtected?: boolean,
  662. ): Promise<{ response: ClineAskResponse; text?: string; images?: string[] }> {
  663. // If this Cline instance was aborted by the provider, then the only
  664. // thing keeping us alive is a promise still running in the background,
  665. // in which case we don't want to send its result to the webview as it
  666. // is attached to a new instance of Cline now. So we can safely ignore
  667. // the result of any active promises, and this class will be
  668. // deallocated. (Although we set Cline = undefined in provider, that
  669. // simply removes the reference to this instance, but the instance is
  670. // still alive until this promise resolves or rejects.)
  671. if (this.abort) {
  672. throw new Error(`[RooCode#ask] task ${this.taskId}.${this.instanceId} aborted`)
  673. }
  674. let askTs: number
  675. if (partial !== undefined) {
  676. const lastMessage = this.clineMessages.at(-1)
  677. const isUpdatingPreviousPartial =
  678. lastMessage && lastMessage.partial && lastMessage.type === "ask" && lastMessage.ask === type
  679. if (partial) {
  680. if (isUpdatingPreviousPartial) {
  681. // Existing partial message, so update it.
  682. lastMessage.text = text
  683. lastMessage.partial = partial
  684. lastMessage.progressStatus = progressStatus
  685. lastMessage.isProtected = isProtected
  686. // TODO: Be more efficient about saving and posting only new
  687. // data or one whole message at a time so ignore partial for
  688. // saves, and only post parts of partial message instead of
  689. // whole array in new listener.
  690. this.updateClineMessage(lastMessage)
  691. // console.log("Task#ask: current ask promise was ignored (#1)")
  692. throw new Error("Current ask promise was ignored (#1)")
  693. } else {
  694. // This is a new partial message, so add it with partial
  695. // state.
  696. askTs = Date.now()
  697. this.lastMessageTs = askTs
  698. console.log(`Task#ask: new partial ask -> ${type} @ ${askTs}`)
  699. await this.addToClineMessages({ ts: askTs, type: "ask", ask: type, text, partial, isProtected })
  700. // console.log("Task#ask: current ask promise was ignored (#2)")
  701. throw new Error("Current ask promise was ignored (#2)")
  702. }
  703. } else {
  704. if (isUpdatingPreviousPartial) {
  705. // This is the complete version of a previously partial
  706. // message, so replace the partial with the complete version.
  707. this.askResponse = undefined
  708. this.askResponseText = undefined
  709. this.askResponseImages = undefined
  710. // Bug for the history books:
  711. // In the webview we use the ts as the chatrow key for the
  712. // virtuoso list. Since we would update this ts right at the
  713. // end of streaming, it would cause the view to flicker. The
  714. // key prop has to be stable otherwise react has trouble
  715. // reconciling items between renders, causing unmounting and
  716. // remounting of components (flickering).
  717. // The lesson here is if you see flickering when rendering
  718. // lists, it's likely because the key prop is not stable.
  719. // So in this case we must make sure that the message ts is
  720. // never altered after first setting it.
  721. askTs = lastMessage.ts
  722. console.log(`Task#ask: updating previous partial ask -> ${type} @ ${askTs}`)
  723. this.lastMessageTs = askTs
  724. lastMessage.text = text
  725. lastMessage.partial = false
  726. lastMessage.progressStatus = progressStatus
  727. lastMessage.isProtected = isProtected
  728. await this.saveClineMessages()
  729. this.updateClineMessage(lastMessage)
  730. } else {
  731. // This is a new and complete message, so add it like normal.
  732. this.askResponse = undefined
  733. this.askResponseText = undefined
  734. this.askResponseImages = undefined
  735. askTs = Date.now()
  736. console.log(`Task#ask: new complete ask -> ${type} @ ${askTs}`)
  737. this.lastMessageTs = askTs
  738. await this.addToClineMessages({ ts: askTs, type: "ask", ask: type, text, isProtected })
  739. }
  740. }
  741. } else {
  742. // This is a new non-partial message, so add it like normal.
  743. this.askResponse = undefined
  744. this.askResponseText = undefined
  745. this.askResponseImages = undefined
  746. askTs = Date.now()
  747. console.log(`Task#ask: new complete ask -> ${type} @ ${askTs}`)
  748. this.lastMessageTs = askTs
  749. await this.addToClineMessages({ ts: askTs, type: "ask", ask: type, text, isProtected })
  750. }
  751. let timeouts: NodeJS.Timeout[] = []
  752. // Automatically approve if the ask according to the user's settings.
  753. const provider = this.providerRef.deref()
  754. const state = provider ? await provider.getState() : undefined
  755. const approval = await checkAutoApproval({ state, ask: type, text, isProtected })
  756. if (approval.decision === "approve") {
  757. this.approveAsk()
  758. } else if (approval.decision === "deny") {
  759. this.denyAsk()
  760. } else if (approval.decision === "timeout") {
  761. timeouts.push(
  762. setTimeout(() => {
  763. const { askResponse, text, images } = approval.fn()
  764. this.handleWebviewAskResponse(askResponse, text, images)
  765. }, approval.timeout),
  766. )
  767. }
  768. // The state is mutable if the message is complete and the task will
  769. // block (via the `pWaitFor`).
  770. const isBlocking = !(this.askResponse !== undefined || this.lastMessageTs !== askTs)
  771. const isMessageQueued = !this.messageQueueService.isEmpty()
  772. const isStatusMutable = !partial && isBlocking && !isMessageQueued && approval.decision === "ask"
  773. if (isBlocking) {
  774. console.log(`Task#ask will block -> type: ${type}`)
  775. }
  776. if (isStatusMutable) {
  777. console.log(`Task#ask: status is mutable -> type: ${type}`)
  778. const statusMutationTimeout = 2_000
  779. if (isInteractiveAsk(type)) {
  780. timeouts.push(
  781. setTimeout(() => {
  782. const message = this.findMessageByTimestamp(askTs)
  783. if (message) {
  784. this.interactiveAsk = message
  785. this.emit(RooCodeEventName.TaskInteractive, this.taskId)
  786. provider?.postMessageToWebview({ type: "interactionRequired" })
  787. }
  788. }, statusMutationTimeout),
  789. )
  790. } else if (isResumableAsk(type)) {
  791. timeouts.push(
  792. setTimeout(() => {
  793. const message = this.findMessageByTimestamp(askTs)
  794. if (message) {
  795. this.resumableAsk = message
  796. this.emit(RooCodeEventName.TaskResumable, this.taskId)
  797. }
  798. }, statusMutationTimeout),
  799. )
  800. } else if (isIdleAsk(type)) {
  801. timeouts.push(
  802. setTimeout(() => {
  803. const message = this.findMessageByTimestamp(askTs)
  804. if (message) {
  805. this.idleAsk = message
  806. this.emit(RooCodeEventName.TaskIdle, this.taskId)
  807. }
  808. }, statusMutationTimeout),
  809. )
  810. }
  811. } else if (isMessageQueued) {
  812. console.log(`Task#ask: will process message queue -> type: ${type}`)
  813. const message = this.messageQueueService.dequeueMessage()
  814. if (message) {
  815. // Check if this is a tool approval ask that needs to be handled.
  816. if (
  817. type === "tool" ||
  818. type === "command" ||
  819. type === "browser_action_launch" ||
  820. type === "use_mcp_server"
  821. ) {
  822. // For tool approvals, we need to approve first, then send
  823. // the message if there's text/images.
  824. this.handleWebviewAskResponse("yesButtonClicked", message.text, message.images)
  825. } else {
  826. // For other ask types (like followup or command_output), fulfill the ask
  827. // directly.
  828. this.handleWebviewAskResponse("messageResponse", message.text, message.images)
  829. }
  830. }
  831. }
  832. // Wait for askResponse to be set
  833. await pWaitFor(() => this.askResponse !== undefined || this.lastMessageTs !== askTs, { interval: 100 })
  834. if (this.lastMessageTs !== askTs) {
  835. // Could happen if we send multiple asks in a row i.e. with
  836. // command_output. It's important that when we know an ask could
  837. // fail, it is handled gracefully.
  838. console.log("Task#ask: current ask promise was ignored")
  839. throw new Error("Current ask promise was ignored")
  840. }
  841. const result = { response: this.askResponse!, text: this.askResponseText, images: this.askResponseImages }
  842. this.askResponse = undefined
  843. this.askResponseText = undefined
  844. this.askResponseImages = undefined
  845. // Cancel the timeouts if they are still running.
  846. timeouts.forEach((timeout) => clearTimeout(timeout))
  847. // Switch back to an active state.
  848. if (this.idleAsk || this.resumableAsk || this.interactiveAsk) {
  849. this.idleAsk = undefined
  850. this.resumableAsk = undefined
  851. this.interactiveAsk = undefined
  852. this.emit(RooCodeEventName.TaskActive, this.taskId)
  853. }
  854. this.emit(RooCodeEventName.TaskAskResponded)
  855. return result
  856. }
  857. handleWebviewAskResponse(askResponse: ClineAskResponse, text?: string, images?: string[]) {
  858. this.askResponse = askResponse
  859. this.askResponseText = text
  860. this.askResponseImages = images
  861. // Create a checkpoint whenever the user sends a message.
  862. // Use allowEmpty=true to ensure a checkpoint is recorded even if there are no file changes.
  863. // Suppress the checkpoint_saved chat row for this particular checkpoint to keep the timeline clean.
  864. if (askResponse === "messageResponse") {
  865. void this.checkpointSave(false, true)
  866. }
  867. // Mark the last follow-up question as answered
  868. if (askResponse === "messageResponse" || askResponse === "yesButtonClicked") {
  869. // Find the last unanswered follow-up message using findLastIndex
  870. const lastFollowUpIndex = findLastIndex(
  871. this.clineMessages,
  872. (msg) => msg.type === "ask" && msg.ask === "followup" && !msg.isAnswered,
  873. )
  874. if (lastFollowUpIndex !== -1) {
  875. // Mark this follow-up as answered
  876. this.clineMessages[lastFollowUpIndex].isAnswered = true
  877. // Save the updated messages
  878. this.saveClineMessages().catch((error) => {
  879. console.error("Failed to save answered follow-up state:", error)
  880. })
  881. }
  882. }
  883. }
  884. public approveAsk({ text, images }: { text?: string; images?: string[] } = {}) {
  885. this.handleWebviewAskResponse("yesButtonClicked", text, images)
  886. }
  887. public denyAsk({ text, images }: { text?: string; images?: string[] } = {}) {
  888. this.handleWebviewAskResponse("noButtonClicked", text, images)
  889. }
  890. public async submitUserMessage(
  891. text: string,
  892. images?: string[],
  893. mode?: string,
  894. providerProfile?: string,
  895. ): Promise<void> {
  896. try {
  897. text = (text ?? "").trim()
  898. images = images ?? []
  899. if (text.length === 0 && images.length === 0) {
  900. return
  901. }
  902. const provider = this.providerRef.deref()
  903. if (provider) {
  904. if (mode) {
  905. await provider.setMode(mode)
  906. }
  907. if (providerProfile) {
  908. await provider.setProviderProfile(providerProfile)
  909. }
  910. this.emit(RooCodeEventName.TaskUserMessage, this.taskId)
  911. provider.postMessageToWebview({ type: "invoke", invoke: "sendMessage", text, images })
  912. } else {
  913. console.error("[Task#submitUserMessage] Provider reference lost")
  914. }
  915. } catch (error) {
  916. console.error("[Task#submitUserMessage] Failed to submit user message:", error)
  917. }
  918. }
  919. async handleTerminalOperation(terminalOperation: "continue" | "abort") {
  920. if (terminalOperation === "continue") {
  921. this.terminalProcess?.continue()
  922. } else if (terminalOperation === "abort") {
  923. this.terminalProcess?.abort()
  924. }
  925. }
  926. public async condenseContext(): Promise<void> {
  927. const systemPrompt = await this.getSystemPrompt()
  928. // Get condensing configuration
  929. const state = await this.providerRef.deref()?.getState()
  930. // These properties may not exist in the state type yet, but are used for condensing configuration
  931. const customCondensingPrompt = state?.customCondensingPrompt
  932. const condensingApiConfigId = state?.condensingApiConfigId
  933. const listApiConfigMeta = state?.listApiConfigMeta
  934. // Determine API handler to use
  935. let condensingApiHandler: ApiHandler | undefined
  936. if (condensingApiConfigId && listApiConfigMeta && Array.isArray(listApiConfigMeta)) {
  937. // Find matching config by ID
  938. const matchingConfig = listApiConfigMeta.find((config) => config.id === condensingApiConfigId)
  939. if (matchingConfig) {
  940. const profile = await this.providerRef.deref()?.providerSettingsManager.getProfile({
  941. id: condensingApiConfigId,
  942. })
  943. // Ensure profile and apiProvider exist before trying to build handler
  944. if (profile && profile.apiProvider) {
  945. condensingApiHandler = buildApiHandler(profile)
  946. }
  947. }
  948. }
  949. const { contextTokens: prevContextTokens } = this.getTokenUsage()
  950. const {
  951. messages,
  952. summary,
  953. cost,
  954. newContextTokens = 0,
  955. error,
  956. } = await summarizeConversation(
  957. this.apiConversationHistory,
  958. this.api, // Main API handler (fallback)
  959. systemPrompt, // Default summarization prompt (fallback)
  960. this.taskId,
  961. prevContextTokens,
  962. false, // manual trigger
  963. customCondensingPrompt, // User's custom prompt
  964. condensingApiHandler, // Specific handler for condensing
  965. )
  966. if (error) {
  967. this.say(
  968. "condense_context_error",
  969. error,
  970. undefined /* images */,
  971. false /* partial */,
  972. undefined /* checkpoint */,
  973. undefined /* progressStatus */,
  974. { isNonInteractive: true } /* options */,
  975. )
  976. return
  977. }
  978. await this.overwriteApiConversationHistory(messages)
  979. const contextCondense: ContextCondense = { summary, cost, newContextTokens, prevContextTokens }
  980. await this.say(
  981. "condense_context",
  982. undefined /* text */,
  983. undefined /* images */,
  984. false /* partial */,
  985. undefined /* checkpoint */,
  986. undefined /* progressStatus */,
  987. { isNonInteractive: true } /* options */,
  988. contextCondense,
  989. )
  990. // Process any queued messages after condensing completes
  991. this.processQueuedMessages()
  992. }
  993. async say(
  994. type: ClineSay,
  995. text?: string,
  996. images?: string[],
  997. partial?: boolean,
  998. checkpoint?: Record<string, unknown>,
  999. progressStatus?: ToolProgressStatus,
  1000. options: {
  1001. isNonInteractive?: boolean
  1002. } = {},
  1003. contextCondense?: ContextCondense,
  1004. ): Promise<undefined> {
  1005. if (this.abort) {
  1006. throw new Error(`[RooCode#say] task ${this.taskId}.${this.instanceId} aborted`)
  1007. }
  1008. if (partial !== undefined) {
  1009. const lastMessage = this.clineMessages.at(-1)
  1010. const isUpdatingPreviousPartial =
  1011. lastMessage && lastMessage.partial && lastMessage.type === "say" && lastMessage.say === type
  1012. if (partial) {
  1013. if (isUpdatingPreviousPartial) {
  1014. // Existing partial message, so update it.
  1015. lastMessage.text = text
  1016. lastMessage.images = images
  1017. lastMessage.partial = partial
  1018. lastMessage.progressStatus = progressStatus
  1019. this.updateClineMessage(lastMessage)
  1020. } else {
  1021. // This is a new partial message, so add it with partial state.
  1022. const sayTs = Date.now()
  1023. if (!options.isNonInteractive) {
  1024. this.lastMessageTs = sayTs
  1025. }
  1026. await this.addToClineMessages({
  1027. ts: sayTs,
  1028. type: "say",
  1029. say: type,
  1030. text,
  1031. images,
  1032. partial,
  1033. contextCondense,
  1034. })
  1035. }
  1036. } else {
  1037. // New now have a complete version of a previously partial message.
  1038. // This is the complete version of a previously partial
  1039. // message, so replace the partial with the complete version.
  1040. if (isUpdatingPreviousPartial) {
  1041. if (!options.isNonInteractive) {
  1042. this.lastMessageTs = lastMessage.ts
  1043. }
  1044. lastMessage.text = text
  1045. lastMessage.images = images
  1046. lastMessage.partial = false
  1047. lastMessage.progressStatus = progressStatus
  1048. // Instead of streaming partialMessage events, we do a save
  1049. // and post like normal to persist to disk.
  1050. await this.saveClineMessages()
  1051. // More performant than an entire `postStateToWebview`.
  1052. this.updateClineMessage(lastMessage)
  1053. } else {
  1054. // This is a new and complete message, so add it like normal.
  1055. const sayTs = Date.now()
  1056. if (!options.isNonInteractive) {
  1057. this.lastMessageTs = sayTs
  1058. }
  1059. await this.addToClineMessages({
  1060. ts: sayTs,
  1061. type: "say",
  1062. say: type,
  1063. text,
  1064. images,
  1065. contextCondense,
  1066. })
  1067. }
  1068. }
  1069. } else {
  1070. // This is a new non-partial message, so add it like normal.
  1071. const sayTs = Date.now()
  1072. // A "non-interactive" message is a message is one that the user
  1073. // does not need to respond to. We don't want these message types
  1074. // to trigger an update to `lastMessageTs` since they can be created
  1075. // asynchronously and could interrupt a pending ask.
  1076. if (!options.isNonInteractive) {
  1077. this.lastMessageTs = sayTs
  1078. }
  1079. await this.addToClineMessages({
  1080. ts: sayTs,
  1081. type: "say",
  1082. say: type,
  1083. text,
  1084. images,
  1085. checkpoint,
  1086. contextCondense,
  1087. })
  1088. }
  1089. }
  1090. async sayAndCreateMissingParamError(toolName: ToolName, paramName: string, relPath?: string) {
  1091. await this.say(
  1092. "error",
  1093. `Roo tried to use ${toolName}${
  1094. relPath ? ` for '${relPath.toPosix()}'` : ""
  1095. } without value for required parameter '${paramName}'. Retrying...`,
  1096. )
  1097. return formatResponse.toolError(formatResponse.missingToolParameterError(paramName))
  1098. }
  1099. // Lifecycle
  1100. // Start / Resume / Abort / Dispose
  1101. private async startTask(task?: string, images?: string[]): Promise<void> {
  1102. if (this.enableBridge) {
  1103. try {
  1104. await BridgeOrchestrator.subscribeToTask(this)
  1105. } catch (error) {
  1106. console.error(
  1107. `[Task#startTask] BridgeOrchestrator.subscribeToTask() failed: ${error instanceof Error ? error.message : String(error)}`,
  1108. )
  1109. }
  1110. }
  1111. // `conversationHistory` (for API) and `clineMessages` (for webview)
  1112. // need to be in sync.
  1113. // If the extension process were killed, then on restart the
  1114. // `clineMessages` might not be empty, so we need to set it to [] when
  1115. // we create a new Cline client (otherwise webview would show stale
  1116. // messages from previous session).
  1117. this.clineMessages = []
  1118. this.apiConversationHistory = []
  1119. // The todo list is already set in the constructor if initialTodos were provided
  1120. // No need to add any messages - the todoList property is already set
  1121. await this.providerRef.deref()?.postStateToWebview()
  1122. await this.say("text", task, images)
  1123. this.isInitialized = true
  1124. let imageBlocks: Anthropic.ImageBlockParam[] = formatResponse.imageBlocks(images)
  1125. // Task starting
  1126. await this.initiateTaskLoop([
  1127. {
  1128. type: "text",
  1129. text: `<task>\n${task}\n</task>`,
  1130. },
  1131. ...imageBlocks,
  1132. ])
  1133. }
  1134. private async resumeTaskFromHistory() {
  1135. if (this.enableBridge) {
  1136. try {
  1137. await BridgeOrchestrator.subscribeToTask(this)
  1138. } catch (error) {
  1139. console.error(
  1140. `[Task#resumeTaskFromHistory] BridgeOrchestrator.subscribeToTask() failed: ${error instanceof Error ? error.message : String(error)}`,
  1141. )
  1142. }
  1143. }
  1144. const modifiedClineMessages = await this.getSavedClineMessages()
  1145. // Remove any resume messages that may have been added before.
  1146. const lastRelevantMessageIndex = findLastIndex(
  1147. modifiedClineMessages,
  1148. (m) => !(m.ask === "resume_task" || m.ask === "resume_completed_task"),
  1149. )
  1150. if (lastRelevantMessageIndex !== -1) {
  1151. modifiedClineMessages.splice(lastRelevantMessageIndex + 1)
  1152. }
  1153. // Remove any trailing reasoning-only UI messages that were not part of the persisted API conversation
  1154. while (modifiedClineMessages.length > 0) {
  1155. const last = modifiedClineMessages[modifiedClineMessages.length - 1]
  1156. if (last.type === "say" && last.say === "reasoning") {
  1157. modifiedClineMessages.pop()
  1158. } else {
  1159. break
  1160. }
  1161. }
  1162. // Since we don't use `api_req_finished` anymore, we need to check if the
  1163. // last `api_req_started` has a cost value, if it doesn't and no
  1164. // cancellation reason to present, then we remove it since it indicates
  1165. // an api request without any partial content streamed.
  1166. const lastApiReqStartedIndex = findLastIndex(
  1167. modifiedClineMessages,
  1168. (m) => m.type === "say" && m.say === "api_req_started",
  1169. )
  1170. if (lastApiReqStartedIndex !== -1) {
  1171. const lastApiReqStarted = modifiedClineMessages[lastApiReqStartedIndex]
  1172. const { cost, cancelReason }: ClineApiReqInfo = JSON.parse(lastApiReqStarted.text || "{}")
  1173. if (cost === undefined && cancelReason === undefined) {
  1174. modifiedClineMessages.splice(lastApiReqStartedIndex, 1)
  1175. }
  1176. }
  1177. await this.overwriteClineMessages(modifiedClineMessages)
  1178. this.clineMessages = await this.getSavedClineMessages()
  1179. // Now present the cline messages to the user and ask if they want to
  1180. // resume (NOTE: we ran into a bug before where the
  1181. // apiConversationHistory wouldn't be initialized when opening a old
  1182. // task, and it was because we were waiting for resume).
  1183. // This is important in case the user deletes messages without resuming
  1184. // the task first.
  1185. this.apiConversationHistory = await this.getSavedApiConversationHistory()
  1186. const lastClineMessage = this.clineMessages
  1187. .slice()
  1188. .reverse()
  1189. .find((m) => !(m.ask === "resume_task" || m.ask === "resume_completed_task")) // Could be multiple resume tasks.
  1190. let askType: ClineAsk
  1191. if (lastClineMessage?.ask === "completion_result") {
  1192. askType = "resume_completed_task"
  1193. } else {
  1194. askType = "resume_task"
  1195. }
  1196. this.isInitialized = true
  1197. const { response, text, images } = await this.ask(askType) // Calls `postStateToWebview`.
  1198. let responseText: string | undefined
  1199. let responseImages: string[] | undefined
  1200. if (response === "messageResponse") {
  1201. await this.say("user_feedback", text, images)
  1202. responseText = text
  1203. responseImages = images
  1204. }
  1205. // Make sure that the api conversation history can be resumed by the API,
  1206. // even if it goes out of sync with cline messages.
  1207. let existingApiConversationHistory: ApiMessage[] = await this.getSavedApiConversationHistory()
  1208. // v2.0 xml tags refactor caveat: since we don't use tools anymore, we need to replace all tool use blocks with a text block since the API disallows conversations with tool uses and no tool schema
  1209. const conversationWithoutToolBlocks = existingApiConversationHistory.map((message) => {
  1210. if (Array.isArray(message.content)) {
  1211. const newContent = message.content.map((block) => {
  1212. if (block.type === "tool_use") {
  1213. // It's important we convert to the new tool schema
  1214. // format so the model doesn't get confused about how to
  1215. // invoke tools.
  1216. const inputAsXml = Object.entries(block.input as Record<string, string>)
  1217. .map(([key, value]) => `<${key}>\n${value}\n</${key}>`)
  1218. .join("\n")
  1219. return {
  1220. type: "text",
  1221. text: `<${block.name}>\n${inputAsXml}\n</${block.name}>`,
  1222. } as Anthropic.Messages.TextBlockParam
  1223. } else if (block.type === "tool_result") {
  1224. // Convert block.content to text block array, removing images
  1225. const contentAsTextBlocks = Array.isArray(block.content)
  1226. ? block.content.filter((item) => item.type === "text")
  1227. : [{ type: "text", text: block.content }]
  1228. const textContent = contentAsTextBlocks.map((item) => item.text).join("\n\n")
  1229. const toolName = findToolName(block.tool_use_id, existingApiConversationHistory)
  1230. return {
  1231. type: "text",
  1232. text: `[${toolName} Result]\n\n${textContent}`,
  1233. } as Anthropic.Messages.TextBlockParam
  1234. }
  1235. return block
  1236. })
  1237. return { ...message, content: newContent }
  1238. }
  1239. return message
  1240. })
  1241. existingApiConversationHistory = conversationWithoutToolBlocks
  1242. // FIXME: remove tool use blocks altogether
  1243. // if the last message is an assistant message, we need to check if there's tool use since every tool use has to have a tool response
  1244. // if there's no tool use and only a text block, then we can just add a user message
  1245. // (note this isn't relevant anymore since we use custom tool prompts instead of tool use blocks, but this is here for legacy purposes in case users resume old tasks)
  1246. // if the last message is a user message, we can need to get the assistant message before it to see if it made tool calls, and if so, fill in the remaining tool responses with 'interrupted'
  1247. let modifiedOldUserContent: Anthropic.Messages.ContentBlockParam[] // either the last message if its user message, or the user message before the last (assistant) message
  1248. let modifiedApiConversationHistory: ApiMessage[] // need to remove the last user message to replace with new modified user message
  1249. if (existingApiConversationHistory.length > 0) {
  1250. const lastMessage = existingApiConversationHistory[existingApiConversationHistory.length - 1]
  1251. if (lastMessage.role === "assistant") {
  1252. const content = Array.isArray(lastMessage.content)
  1253. ? lastMessage.content
  1254. : [{ type: "text", text: lastMessage.content }]
  1255. const hasToolUse = content.some((block) => block.type === "tool_use")
  1256. if (hasToolUse) {
  1257. const toolUseBlocks = content.filter(
  1258. (block) => block.type === "tool_use",
  1259. ) as Anthropic.Messages.ToolUseBlock[]
  1260. const toolResponses: Anthropic.ToolResultBlockParam[] = toolUseBlocks.map((block) => ({
  1261. type: "tool_result",
  1262. tool_use_id: block.id,
  1263. content: "Task was interrupted before this tool call could be completed.",
  1264. }))
  1265. modifiedApiConversationHistory = [...existingApiConversationHistory] // no changes
  1266. modifiedOldUserContent = [...toolResponses]
  1267. } else {
  1268. modifiedApiConversationHistory = [...existingApiConversationHistory]
  1269. modifiedOldUserContent = []
  1270. }
  1271. } else if (lastMessage.role === "user") {
  1272. const previousAssistantMessage: ApiMessage | undefined =
  1273. existingApiConversationHistory[existingApiConversationHistory.length - 2]
  1274. const existingUserContent: Anthropic.Messages.ContentBlockParam[] = Array.isArray(lastMessage.content)
  1275. ? lastMessage.content
  1276. : [{ type: "text", text: lastMessage.content }]
  1277. if (previousAssistantMessage && previousAssistantMessage.role === "assistant") {
  1278. const assistantContent = Array.isArray(previousAssistantMessage.content)
  1279. ? previousAssistantMessage.content
  1280. : [{ type: "text", text: previousAssistantMessage.content }]
  1281. const toolUseBlocks = assistantContent.filter(
  1282. (block) => block.type === "tool_use",
  1283. ) as Anthropic.Messages.ToolUseBlock[]
  1284. if (toolUseBlocks.length > 0) {
  1285. const existingToolResults = existingUserContent.filter(
  1286. (block) => block.type === "tool_result",
  1287. ) as Anthropic.ToolResultBlockParam[]
  1288. const missingToolResponses: Anthropic.ToolResultBlockParam[] = toolUseBlocks
  1289. .filter(
  1290. (toolUse) => !existingToolResults.some((result) => result.tool_use_id === toolUse.id),
  1291. )
  1292. .map((toolUse) => ({
  1293. type: "tool_result",
  1294. tool_use_id: toolUse.id,
  1295. content: "Task was interrupted before this tool call could be completed.",
  1296. }))
  1297. modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1) // removes the last user message
  1298. modifiedOldUserContent = [...existingUserContent, ...missingToolResponses]
  1299. } else {
  1300. modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1)
  1301. modifiedOldUserContent = [...existingUserContent]
  1302. }
  1303. } else {
  1304. modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1)
  1305. modifiedOldUserContent = [...existingUserContent]
  1306. }
  1307. } else {
  1308. throw new Error("Unexpected: Last message is not a user or assistant message")
  1309. }
  1310. } else {
  1311. throw new Error("Unexpected: No existing API conversation history")
  1312. }
  1313. let newUserContent: Anthropic.Messages.ContentBlockParam[] = [...modifiedOldUserContent]
  1314. const agoText = ((): string => {
  1315. const timestamp = lastClineMessage?.ts ?? Date.now()
  1316. const now = Date.now()
  1317. const diff = now - timestamp
  1318. const minutes = Math.floor(diff / 60000)
  1319. const hours = Math.floor(minutes / 60)
  1320. const days = Math.floor(hours / 24)
  1321. if (days > 0) {
  1322. return `${days} day${days > 1 ? "s" : ""} ago`
  1323. }
  1324. if (hours > 0) {
  1325. return `${hours} hour${hours > 1 ? "s" : ""} ago`
  1326. }
  1327. if (minutes > 0) {
  1328. return `${minutes} minute${minutes > 1 ? "s" : ""} ago`
  1329. }
  1330. return "just now"
  1331. })()
  1332. if (responseText) {
  1333. newUserContent.push({
  1334. type: "text",
  1335. text: `\n\nNew instructions for task continuation:\n<user_message>\n${responseText}\n</user_message>`,
  1336. })
  1337. }
  1338. if (responseImages && responseImages.length > 0) {
  1339. newUserContent.push(...formatResponse.imageBlocks(responseImages))
  1340. }
  1341. // Ensure we have at least some content to send to the API.
  1342. // If newUserContent is empty, add a minimal resumption message.
  1343. if (newUserContent.length === 0) {
  1344. newUserContent.push({
  1345. type: "text",
  1346. text: "[TASK RESUMPTION] Resuming task...",
  1347. })
  1348. }
  1349. await this.overwriteApiConversationHistory(modifiedApiConversationHistory)
  1350. // Task resuming from history item.
  1351. await this.initiateTaskLoop(newUserContent)
  1352. }
  1353. public async abortTask(isAbandoned = false) {
  1354. // Aborting task
  1355. // Will stop any autonomously running promises.
  1356. if (isAbandoned) {
  1357. this.abandoned = true
  1358. }
  1359. this.abort = true
  1360. this.emit(RooCodeEventName.TaskAborted)
  1361. try {
  1362. this.dispose() // Call the centralized dispose method
  1363. } catch (error) {
  1364. console.error(`Error during task ${this.taskId}.${this.instanceId} disposal:`, error)
  1365. // Don't rethrow - we want abort to always succeed
  1366. }
  1367. // Save the countdown message in the automatic retry or other content.
  1368. try {
  1369. // Save the countdown message in the automatic retry or other content.
  1370. await this.saveClineMessages()
  1371. } catch (error) {
  1372. console.error(`Error saving messages during abort for task ${this.taskId}.${this.instanceId}:`, error)
  1373. }
  1374. }
  1375. public dispose(): void {
  1376. console.log(`[Task#dispose] disposing task ${this.taskId}.${this.instanceId}`)
  1377. // Dispose message queue and remove event listeners.
  1378. try {
  1379. if (this.messageQueueStateChangedHandler) {
  1380. this.messageQueueService.removeListener("stateChanged", this.messageQueueStateChangedHandler)
  1381. this.messageQueueStateChangedHandler = undefined
  1382. }
  1383. this.messageQueueService.dispose()
  1384. } catch (error) {
  1385. console.error("Error disposing message queue:", error)
  1386. }
  1387. // Remove all event listeners to prevent memory leaks.
  1388. try {
  1389. this.removeAllListeners()
  1390. } catch (error) {
  1391. console.error("Error removing event listeners:", error)
  1392. }
  1393. // Stop waiting for child task completion.
  1394. if (this.pauseInterval) {
  1395. clearInterval(this.pauseInterval)
  1396. this.pauseInterval = undefined
  1397. }
  1398. if (this.enableBridge) {
  1399. BridgeOrchestrator.getInstance()
  1400. ?.unsubscribeFromTask(this.taskId)
  1401. .catch((error) =>
  1402. console.error(
  1403. `[Task#dispose] BridgeOrchestrator#unsubscribeFromTask() failed: ${error instanceof Error ? error.message : String(error)}`,
  1404. ),
  1405. )
  1406. }
  1407. // Release any terminals associated with this task.
  1408. try {
  1409. // Release any terminals associated with this task.
  1410. TerminalRegistry.releaseTerminalsForTask(this.taskId)
  1411. } catch (error) {
  1412. console.error("Error releasing terminals:", error)
  1413. }
  1414. try {
  1415. this.urlContentFetcher.closeBrowser()
  1416. } catch (error) {
  1417. console.error("Error closing URL content fetcher browser:", error)
  1418. }
  1419. try {
  1420. this.browserSession.closeBrowser()
  1421. } catch (error) {
  1422. console.error("Error closing browser session:", error)
  1423. }
  1424. try {
  1425. if (this.rooIgnoreController) {
  1426. this.rooIgnoreController.dispose()
  1427. this.rooIgnoreController = undefined
  1428. }
  1429. } catch (error) {
  1430. console.error("Error disposing RooIgnoreController:", error)
  1431. // This is the critical one for the leak fix.
  1432. }
  1433. try {
  1434. this.fileContextTracker.dispose()
  1435. } catch (error) {
  1436. console.error("Error disposing file context tracker:", error)
  1437. }
  1438. try {
  1439. // If we're not streaming then `abortStream` won't be called.
  1440. if (this.isStreaming && this.diffViewProvider.isEditing) {
  1441. this.diffViewProvider.revertChanges().catch(console.error)
  1442. }
  1443. } catch (error) {
  1444. console.error("Error reverting diff changes:", error)
  1445. }
  1446. }
  1447. // Subtasks
  1448. // Spawn / Wait / Complete
  1449. public async startSubtask(message: string, initialTodos: TodoItem[], mode: string) {
  1450. const provider = this.providerRef.deref()
  1451. if (!provider) {
  1452. throw new Error("Provider not available")
  1453. }
  1454. const newTask = await provider.createTask(message, undefined, this, { initialTodos })
  1455. if (newTask) {
  1456. this.isPaused = true // Pause parent.
  1457. this.childTaskId = newTask.taskId
  1458. await provider.handleModeSwitch(mode) // Set child's mode.
  1459. await delay(500) // Allow mode change to take effect.
  1460. this.emit(RooCodeEventName.TaskPaused, this.taskId)
  1461. this.emit(RooCodeEventName.TaskSpawned, newTask.taskId)
  1462. }
  1463. return newTask
  1464. }
  1465. // Used when a sub-task is launched and the parent task is waiting for it to
  1466. // finish.
  1467. // TBD: Add a timeout to prevent infinite waiting.
  1468. public async waitForSubtask() {
  1469. await new Promise<void>((resolve) => {
  1470. this.pauseInterval = setInterval(() => {
  1471. if (!this.isPaused) {
  1472. clearInterval(this.pauseInterval)
  1473. this.pauseInterval = undefined
  1474. resolve()
  1475. }
  1476. }, 1000)
  1477. })
  1478. }
  1479. public async completeSubtask(lastMessage: string) {
  1480. this.isPaused = false
  1481. this.childTaskId = undefined
  1482. this.emit(RooCodeEventName.TaskUnpaused, this.taskId)
  1483. // Fake an answer from the subtask that it has completed running and
  1484. // this is the result of what it has done add the message to the chat
  1485. // history and to the webview ui.
  1486. try {
  1487. await this.say("subtask_result", lastMessage)
  1488. await this.addToApiConversationHistory({
  1489. role: "user",
  1490. content: [{ type: "text", text: `[new_task completed] Result: ${lastMessage}` }],
  1491. })
  1492. } catch (error) {
  1493. this.providerRef
  1494. .deref()
  1495. ?.log(`Error failed to add reply from subtask into conversation of parent task, error: ${error}`)
  1496. throw error
  1497. }
  1498. }
  1499. // Task Loop
  1500. private async initiateTaskLoop(userContent: Anthropic.Messages.ContentBlockParam[]): Promise<void> {
  1501. // Kicks off the checkpoints initialization process in the background.
  1502. getCheckpointService(this)
  1503. let nextUserContent = userContent
  1504. let includeFileDetails = true
  1505. this.emit(RooCodeEventName.TaskStarted)
  1506. while (!this.abort) {
  1507. const didEndLoop = await this.recursivelyMakeClineRequests(nextUserContent, includeFileDetails)
  1508. includeFileDetails = false // We only need file details the first time.
  1509. // The way this agentic loop works is that cline will be given a
  1510. // task that he then calls tools to complete. Unless there's an
  1511. // attempt_completion call, we keep responding back to him with his
  1512. // tool's responses until he either attempt_completion or does not
  1513. // use anymore tools. If he does not use anymore tools, we ask him
  1514. // to consider if he's completed the task and then call
  1515. // attempt_completion, otherwise proceed with completing the task.
  1516. // There is a MAX_REQUESTS_PER_TASK limit to prevent infinite
  1517. // requests, but Cline is prompted to finish the task as efficiently
  1518. // as he can.
  1519. if (didEndLoop) {
  1520. // For now a task never 'completes'. This will only happen if
  1521. // the user hits max requests and denies resetting the count.
  1522. break
  1523. } else {
  1524. nextUserContent = [{ type: "text", text: formatResponse.noToolsUsed() }]
  1525. this.consecutiveMistakeCount++
  1526. }
  1527. }
  1528. }
  1529. public async recursivelyMakeClineRequests(
  1530. userContent: Anthropic.Messages.ContentBlockParam[],
  1531. includeFileDetails: boolean = false,
  1532. ): Promise<boolean> {
  1533. interface StackItem {
  1534. userContent: Anthropic.Messages.ContentBlockParam[]
  1535. includeFileDetails: boolean
  1536. retryAttempt?: number
  1537. }
  1538. const stack: StackItem[] = [{ userContent, includeFileDetails, retryAttempt: 0 }]
  1539. while (stack.length > 0) {
  1540. const currentItem = stack.pop()!
  1541. const currentUserContent = currentItem.userContent
  1542. const currentIncludeFileDetails = currentItem.includeFileDetails
  1543. if (this.abort) {
  1544. throw new Error(`[RooCode#recursivelyMakeRooRequests] task ${this.taskId}.${this.instanceId} aborted`)
  1545. }
  1546. if (this.consecutiveMistakeLimit > 0 && this.consecutiveMistakeCount >= this.consecutiveMistakeLimit) {
  1547. const { response, text, images } = await this.ask(
  1548. "mistake_limit_reached",
  1549. t("common:errors.mistake_limit_guidance"),
  1550. )
  1551. if (response === "messageResponse") {
  1552. currentUserContent.push(
  1553. ...[
  1554. { type: "text" as const, text: formatResponse.tooManyMistakes(text) },
  1555. ...formatResponse.imageBlocks(images),
  1556. ],
  1557. )
  1558. await this.say("user_feedback", text, images)
  1559. // Track consecutive mistake errors in telemetry.
  1560. TelemetryService.instance.captureConsecutiveMistakeError(this.taskId)
  1561. }
  1562. this.consecutiveMistakeCount = 0
  1563. }
  1564. // In this Cline request loop, we need to check if this task instance
  1565. // has been asked to wait for a subtask to finish before continuing.
  1566. const provider = this.providerRef.deref()
  1567. if (this.isPaused && provider) {
  1568. provider.log(`[subtasks] paused ${this.taskId}.${this.instanceId}`)
  1569. await this.waitForSubtask()
  1570. provider.log(`[subtasks] resumed ${this.taskId}.${this.instanceId}`)
  1571. const currentMode = (await provider.getState())?.mode ?? defaultModeSlug
  1572. if (currentMode !== this.pausedModeSlug) {
  1573. // The mode has changed, we need to switch back to the paused mode.
  1574. await provider.handleModeSwitch(this.pausedModeSlug)
  1575. // Delay to allow mode change to take effect before next tool is executed.
  1576. await delay(500)
  1577. provider.log(
  1578. `[subtasks] task ${this.taskId}.${this.instanceId} has switched back to '${this.pausedModeSlug}' from '${currentMode}'`,
  1579. )
  1580. }
  1581. }
  1582. // Getting verbose details is an expensive operation, it uses ripgrep to
  1583. // top-down build file structure of project which for large projects can
  1584. // take a few seconds. For the best UX we show a placeholder api_req_started
  1585. // message with a loading spinner as this happens.
  1586. // Determine API protocol based on provider and model
  1587. const modelId = getModelId(this.apiConfiguration)
  1588. const apiProtocol = getApiProtocol(this.apiConfiguration.apiProvider, modelId)
  1589. await this.say(
  1590. "api_req_started",
  1591. JSON.stringify({
  1592. apiProtocol,
  1593. }),
  1594. )
  1595. const {
  1596. showRooIgnoredFiles = false,
  1597. includeDiagnosticMessages = true,
  1598. maxDiagnosticMessages = 50,
  1599. maxReadFileLine = -1,
  1600. } = (await this.providerRef.deref()?.getState()) ?? {}
  1601. const parsedUserContent = await processUserContentMentions({
  1602. userContent: currentUserContent,
  1603. cwd: this.cwd,
  1604. urlContentFetcher: this.urlContentFetcher,
  1605. fileContextTracker: this.fileContextTracker,
  1606. rooIgnoreController: this.rooIgnoreController,
  1607. showRooIgnoredFiles,
  1608. includeDiagnosticMessages,
  1609. maxDiagnosticMessages,
  1610. maxReadFileLine,
  1611. })
  1612. const environmentDetails = await getEnvironmentDetails(this, currentIncludeFileDetails)
  1613. // Add environment details as its own text block, separate from tool
  1614. // results.
  1615. const finalUserContent = [...parsedUserContent, { type: "text" as const, text: environmentDetails }]
  1616. await this.addToApiConversationHistory({ role: "user", content: finalUserContent })
  1617. TelemetryService.instance.captureConversationMessage(this.taskId, "user")
  1618. // Since we sent off a placeholder api_req_started message to update the
  1619. // webview while waiting to actually start the API request (to load
  1620. // potential details for example), we need to update the text of that
  1621. // message.
  1622. const lastApiReqIndex = findLastIndex(this.clineMessages, (m) => m.say === "api_req_started")
  1623. this.clineMessages[lastApiReqIndex].text = JSON.stringify({
  1624. apiProtocol,
  1625. } satisfies ClineApiReqInfo)
  1626. await this.saveClineMessages()
  1627. await provider?.postStateToWebview()
  1628. try {
  1629. let cacheWriteTokens = 0
  1630. let cacheReadTokens = 0
  1631. let inputTokens = 0
  1632. let outputTokens = 0
  1633. let totalCost: number | undefined
  1634. // We can't use `api_req_finished` anymore since it's a unique case
  1635. // where it could come after a streaming message (i.e. in the middle
  1636. // of being updated or executed).
  1637. // Fortunately `api_req_finished` was always parsed out for the GUI
  1638. // anyways, so it remains solely for legacy purposes to keep track
  1639. // of prices in tasks from history (it's worth removing a few months
  1640. // from now).
  1641. const updateApiReqMsg = (cancelReason?: ClineApiReqCancelReason, streamingFailedMessage?: string) => {
  1642. if (lastApiReqIndex < 0 || !this.clineMessages[lastApiReqIndex]) {
  1643. return
  1644. }
  1645. const existingData = JSON.parse(this.clineMessages[lastApiReqIndex].text || "{}")
  1646. // Calculate total tokens and cost using provider-aware function
  1647. const modelId = getModelId(this.apiConfiguration)
  1648. const apiProtocol = getApiProtocol(this.apiConfiguration.apiProvider, modelId)
  1649. const costResult =
  1650. apiProtocol === "anthropic"
  1651. ? calculateApiCostAnthropic(
  1652. this.api.getModel().info,
  1653. inputTokens,
  1654. outputTokens,
  1655. cacheWriteTokens,
  1656. cacheReadTokens,
  1657. )
  1658. : calculateApiCostOpenAI(
  1659. this.api.getModel().info,
  1660. inputTokens,
  1661. outputTokens,
  1662. cacheWriteTokens,
  1663. cacheReadTokens,
  1664. )
  1665. this.clineMessages[lastApiReqIndex].text = JSON.stringify({
  1666. ...existingData,
  1667. tokensIn: costResult.totalInputTokens,
  1668. tokensOut: costResult.totalOutputTokens,
  1669. cacheWrites: cacheWriteTokens,
  1670. cacheReads: cacheReadTokens,
  1671. cost: totalCost ?? costResult.totalCost,
  1672. cancelReason,
  1673. streamingFailedMessage,
  1674. } satisfies ClineApiReqInfo)
  1675. }
  1676. const abortStream = async (cancelReason: ClineApiReqCancelReason, streamingFailedMessage?: string) => {
  1677. if (this.diffViewProvider.isEditing) {
  1678. await this.diffViewProvider.revertChanges() // closes diff view
  1679. }
  1680. // if last message is a partial we need to update and save it
  1681. const lastMessage = this.clineMessages.at(-1)
  1682. if (lastMessage && lastMessage.partial) {
  1683. // lastMessage.ts = Date.now() DO NOT update ts since it is used as a key for virtuoso list
  1684. lastMessage.partial = false
  1685. // instead of streaming partialMessage events, we do a save and post like normal to persist to disk
  1686. console.log("updating partial message", lastMessage)
  1687. }
  1688. // Update `api_req_started` to have cancelled and cost, so that
  1689. // we can display the cost of the partial stream and the cancellation reason
  1690. updateApiReqMsg(cancelReason, streamingFailedMessage)
  1691. await this.saveClineMessages()
  1692. // Signals to provider that it can retrieve the saved messages
  1693. // from disk, as abortTask can not be awaited on in nature.
  1694. this.didFinishAbortingStream = true
  1695. }
  1696. // Reset streaming state for each new API request
  1697. this.currentStreamingContentIndex = 0
  1698. this.currentStreamingDidCheckpoint = false
  1699. this.assistantMessageContent = []
  1700. this.didCompleteReadingStream = false
  1701. this.userMessageContent = []
  1702. this.userMessageContentReady = false
  1703. this.didRejectTool = false
  1704. this.didAlreadyUseTool = false
  1705. this.presentAssistantMessageLocked = false
  1706. this.presentAssistantMessageHasPendingUpdates = false
  1707. this.assistantMessageParser.reset()
  1708. await this.diffViewProvider.reset()
  1709. // Yields only if the first chunk is successful, otherwise will
  1710. // allow the user to retry the request (most likely due to rate
  1711. // limit error, which gets thrown on the first chunk).
  1712. const stream = this.attemptApiRequest()
  1713. let assistantMessage = ""
  1714. let reasoningMessage = ""
  1715. let pendingGroundingSources: GroundingSource[] = []
  1716. this.isStreaming = true
  1717. try {
  1718. const iterator = stream[Symbol.asyncIterator]()
  1719. let item = await iterator.next()
  1720. while (!item.done) {
  1721. const chunk = item.value
  1722. item = await iterator.next()
  1723. if (!chunk) {
  1724. // Sometimes chunk is undefined, no idea that can cause
  1725. // it, but this workaround seems to fix it.
  1726. continue
  1727. }
  1728. switch (chunk.type) {
  1729. case "reasoning": {
  1730. reasoningMessage += chunk.text
  1731. // Only apply formatting if the message contains sentence-ending punctuation followed by **
  1732. let formattedReasoning = reasoningMessage
  1733. if (reasoningMessage.includes("**")) {
  1734. // Add line breaks before **Title** patterns that appear after sentence endings
  1735. // This targets section headers like "...end of sentence.**Title Here**"
  1736. // Handles periods, exclamation marks, and question marks
  1737. formattedReasoning = reasoningMessage.replace(
  1738. /([.!?])\*\*([^*\n]+)\*\*/g,
  1739. "$1\n\n**$2**",
  1740. )
  1741. }
  1742. await this.say("reasoning", formattedReasoning, undefined, true)
  1743. break
  1744. }
  1745. case "usage":
  1746. inputTokens += chunk.inputTokens
  1747. outputTokens += chunk.outputTokens
  1748. cacheWriteTokens += chunk.cacheWriteTokens ?? 0
  1749. cacheReadTokens += chunk.cacheReadTokens ?? 0
  1750. totalCost = chunk.totalCost
  1751. break
  1752. case "grounding":
  1753. // Handle grounding sources separately from regular content
  1754. // to prevent state persistence issues - store them separately
  1755. if (chunk.sources && chunk.sources.length > 0) {
  1756. pendingGroundingSources.push(...chunk.sources)
  1757. }
  1758. break
  1759. case "tool_call": {
  1760. // Convert native tool call to ToolUse format
  1761. const toolUse = NativeToolCallParser.parseToolCall({
  1762. id: chunk.id,
  1763. name: chunk.name as ToolName,
  1764. arguments: chunk.arguments,
  1765. })
  1766. if (!toolUse) {
  1767. console.error(`Failed to parse tool call for task ${this.taskId}:`, chunk)
  1768. break
  1769. }
  1770. // Store the tool call ID on the ToolUse object for later reference
  1771. // This is needed to create tool_result blocks that reference the correct tool_use_id
  1772. toolUse.id = chunk.id
  1773. // Add the tool use to assistant message content
  1774. this.assistantMessageContent.push(toolUse)
  1775. // Mark that we have new content to process
  1776. this.userMessageContentReady = false
  1777. // Present the tool call to user
  1778. presentAssistantMessage(this)
  1779. break
  1780. }
  1781. case "text": {
  1782. assistantMessage += chunk.text
  1783. // Parse raw assistant message chunk into content blocks.
  1784. const prevLength = this.assistantMessageContent.length
  1785. this.assistantMessageContent = this.assistantMessageParser.processChunk(chunk.text)
  1786. if (this.assistantMessageContent.length > prevLength) {
  1787. // New content we need to present, reset to
  1788. // false in case previous content set this to true.
  1789. this.userMessageContentReady = false
  1790. }
  1791. // Present content to user.
  1792. presentAssistantMessage(this)
  1793. break
  1794. }
  1795. }
  1796. if (this.abort) {
  1797. console.log(`aborting stream, this.abandoned = ${this.abandoned}`)
  1798. if (!this.abandoned) {
  1799. // Only need to gracefully abort if this instance
  1800. // isn't abandoned (sometimes OpenRouter stream
  1801. // hangs, in which case this would affect future
  1802. // instances of Cline).
  1803. await abortStream("user_cancelled")
  1804. }
  1805. break // Aborts the stream.
  1806. }
  1807. if (this.didRejectTool) {
  1808. // `userContent` has a tool rejection, so interrupt the
  1809. // assistant's response to present the user's feedback.
  1810. assistantMessage += "\n\n[Response interrupted by user feedback]"
  1811. // Instead of setting this preemptively, we allow the
  1812. // present iterator to finish and set
  1813. // userMessageContentReady when its ready.
  1814. // this.userMessageContentReady = true
  1815. break
  1816. }
  1817. if (this.didAlreadyUseTool) {
  1818. assistantMessage +=
  1819. "\n\n[Response interrupted by a tool use result. Only one tool may be used at a time and should be placed at the end of the message.]"
  1820. break
  1821. }
  1822. }
  1823. // Create a copy of current token values to avoid race conditions
  1824. const currentTokens = {
  1825. input: inputTokens,
  1826. output: outputTokens,
  1827. cacheWrite: cacheWriteTokens,
  1828. cacheRead: cacheReadTokens,
  1829. total: totalCost,
  1830. }
  1831. const drainStreamInBackgroundToFindAllUsage = async (apiReqIndex: number) => {
  1832. const timeoutMs = DEFAULT_USAGE_COLLECTION_TIMEOUT_MS
  1833. const startTime = performance.now()
  1834. const modelId = getModelId(this.apiConfiguration)
  1835. // Local variables to accumulate usage data without affecting the main flow
  1836. let bgInputTokens = currentTokens.input
  1837. let bgOutputTokens = currentTokens.output
  1838. let bgCacheWriteTokens = currentTokens.cacheWrite
  1839. let bgCacheReadTokens = currentTokens.cacheRead
  1840. let bgTotalCost = currentTokens.total
  1841. // Helper function to capture telemetry and update messages
  1842. const captureUsageData = async (
  1843. tokens: {
  1844. input: number
  1845. output: number
  1846. cacheWrite: number
  1847. cacheRead: number
  1848. total?: number
  1849. },
  1850. messageIndex: number = apiReqIndex,
  1851. ) => {
  1852. if (
  1853. tokens.input > 0 ||
  1854. tokens.output > 0 ||
  1855. tokens.cacheWrite > 0 ||
  1856. tokens.cacheRead > 0
  1857. ) {
  1858. // Update the shared variables atomically
  1859. inputTokens = tokens.input
  1860. outputTokens = tokens.output
  1861. cacheWriteTokens = tokens.cacheWrite
  1862. cacheReadTokens = tokens.cacheRead
  1863. totalCost = tokens.total
  1864. // Update the API request message with the latest usage data
  1865. updateApiReqMsg()
  1866. await this.saveClineMessages()
  1867. // Update the specific message in the webview
  1868. const apiReqMessage = this.clineMessages[messageIndex]
  1869. if (apiReqMessage) {
  1870. await this.updateClineMessage(apiReqMessage)
  1871. }
  1872. // Capture telemetry with provider-aware cost calculation
  1873. const modelId = getModelId(this.apiConfiguration)
  1874. const apiProtocol = getApiProtocol(this.apiConfiguration.apiProvider, modelId)
  1875. // Use the appropriate cost function based on the API protocol
  1876. const costResult =
  1877. apiProtocol === "anthropic"
  1878. ? calculateApiCostAnthropic(
  1879. this.api.getModel().info,
  1880. tokens.input,
  1881. tokens.output,
  1882. tokens.cacheWrite,
  1883. tokens.cacheRead,
  1884. )
  1885. : calculateApiCostOpenAI(
  1886. this.api.getModel().info,
  1887. tokens.input,
  1888. tokens.output,
  1889. tokens.cacheWrite,
  1890. tokens.cacheRead,
  1891. )
  1892. TelemetryService.instance.captureLlmCompletion(this.taskId, {
  1893. inputTokens: costResult.totalInputTokens,
  1894. outputTokens: costResult.totalOutputTokens,
  1895. cacheWriteTokens: tokens.cacheWrite,
  1896. cacheReadTokens: tokens.cacheRead,
  1897. cost: tokens.total ?? costResult.totalCost,
  1898. })
  1899. }
  1900. }
  1901. try {
  1902. // Continue processing the original stream from where the main loop left off
  1903. let usageFound = false
  1904. let chunkCount = 0
  1905. // Use the same iterator that the main loop was using
  1906. while (!item.done) {
  1907. // Check for timeout
  1908. if (performance.now() - startTime > timeoutMs) {
  1909. console.warn(
  1910. `[Background Usage Collection] Timed out after ${timeoutMs}ms for model: ${modelId}, processed ${chunkCount} chunks`,
  1911. )
  1912. // Clean up the iterator before breaking
  1913. if (iterator.return) {
  1914. await iterator.return(undefined)
  1915. }
  1916. break
  1917. }
  1918. const chunk = item.value
  1919. item = await iterator.next()
  1920. chunkCount++
  1921. if (chunk && chunk.type === "usage") {
  1922. usageFound = true
  1923. bgInputTokens += chunk.inputTokens
  1924. bgOutputTokens += chunk.outputTokens
  1925. bgCacheWriteTokens += chunk.cacheWriteTokens ?? 0
  1926. bgCacheReadTokens += chunk.cacheReadTokens ?? 0
  1927. bgTotalCost = chunk.totalCost
  1928. }
  1929. }
  1930. if (
  1931. usageFound ||
  1932. bgInputTokens > 0 ||
  1933. bgOutputTokens > 0 ||
  1934. bgCacheWriteTokens > 0 ||
  1935. bgCacheReadTokens > 0
  1936. ) {
  1937. // We have usage data either from a usage chunk or accumulated tokens
  1938. await captureUsageData(
  1939. {
  1940. input: bgInputTokens,
  1941. output: bgOutputTokens,
  1942. cacheWrite: bgCacheWriteTokens,
  1943. cacheRead: bgCacheReadTokens,
  1944. total: bgTotalCost,
  1945. },
  1946. lastApiReqIndex,
  1947. )
  1948. } else {
  1949. console.warn(
  1950. `[Background Usage Collection] Suspicious: request ${apiReqIndex} is complete, but no usage info was found. Model: ${modelId}`,
  1951. )
  1952. }
  1953. } catch (error) {
  1954. console.error("Error draining stream for usage data:", error)
  1955. // Still try to capture whatever usage data we have collected so far
  1956. if (
  1957. bgInputTokens > 0 ||
  1958. bgOutputTokens > 0 ||
  1959. bgCacheWriteTokens > 0 ||
  1960. bgCacheReadTokens > 0
  1961. ) {
  1962. await captureUsageData(
  1963. {
  1964. input: bgInputTokens,
  1965. output: bgOutputTokens,
  1966. cacheWrite: bgCacheWriteTokens,
  1967. cacheRead: bgCacheReadTokens,
  1968. total: bgTotalCost,
  1969. },
  1970. lastApiReqIndex,
  1971. )
  1972. }
  1973. }
  1974. }
  1975. // Start the background task and handle any errors
  1976. drainStreamInBackgroundToFindAllUsage(lastApiReqIndex).catch((error) => {
  1977. console.error("Background usage collection failed:", error)
  1978. })
  1979. } catch (error) {
  1980. // Abandoned happens when extension is no longer waiting for the
  1981. // Cline instance to finish aborting (error is thrown here when
  1982. // any function in the for loop throws due to this.abort).
  1983. if (!this.abandoned) {
  1984. // Determine cancellation reason
  1985. const cancelReason: ClineApiReqCancelReason = this.abort ? "user_cancelled" : "streaming_failed"
  1986. const streamingFailedMessage = this.abort
  1987. ? undefined
  1988. : (error.message ?? JSON.stringify(serializeError(error), null, 2))
  1989. // Clean up partial state
  1990. await abortStream(cancelReason, streamingFailedMessage)
  1991. if (this.abort) {
  1992. // User cancelled - abort the entire task
  1993. this.abortReason = cancelReason
  1994. await this.abortTask()
  1995. } else {
  1996. // Stream failed - log the error and retry with the same content
  1997. // The existing rate limiting will prevent rapid retries
  1998. console.error(
  1999. `[Task#${this.taskId}.${this.instanceId}] Stream failed, will retry: ${streamingFailedMessage}`,
  2000. )
  2001. // Apply exponential backoff similar to first-chunk errors when auto-resubmit is enabled
  2002. const stateForBackoff = await this.providerRef.deref()?.getState()
  2003. if (stateForBackoff?.autoApprovalEnabled && stateForBackoff?.alwaysApproveResubmit) {
  2004. await this.backoffAndAnnounce(
  2005. currentItem.retryAttempt ?? 0,
  2006. error,
  2007. streamingFailedMessage,
  2008. )
  2009. // Check if task was aborted during the backoff
  2010. if (this.abort) {
  2011. console.log(
  2012. `[Task#${this.taskId}.${this.instanceId}] Task aborted during mid-stream retry backoff`,
  2013. )
  2014. // Abort the entire task
  2015. this.abortReason = "user_cancelled"
  2016. await this.abortTask()
  2017. break
  2018. }
  2019. }
  2020. // Push the same content back onto the stack to retry, incrementing the retry attempt counter
  2021. stack.push({
  2022. userContent: currentUserContent,
  2023. includeFileDetails: false,
  2024. retryAttempt: (currentItem.retryAttempt ?? 0) + 1,
  2025. })
  2026. // Continue to retry the request
  2027. continue
  2028. }
  2029. }
  2030. } finally {
  2031. this.isStreaming = false
  2032. }
  2033. // Need to call here in case the stream was aborted.
  2034. if (this.abort || this.abandoned) {
  2035. throw new Error(
  2036. `[RooCode#recursivelyMakeRooRequests] task ${this.taskId}.${this.instanceId} aborted`,
  2037. )
  2038. }
  2039. this.didCompleteReadingStream = true
  2040. // Set any blocks to be complete to allow `presentAssistantMessage`
  2041. // to finish and set `userMessageContentReady` to true.
  2042. // (Could be a text block that had no subsequent tool uses, or a
  2043. // text block at the very end, or an invalid tool use, etc. Whatever
  2044. // the case, `presentAssistantMessage` relies on these blocks either
  2045. // to be completed or the user to reject a block in order to proceed
  2046. // and eventually set userMessageContentReady to true.)
  2047. const partialBlocks = this.assistantMessageContent.filter((block) => block.partial)
  2048. partialBlocks.forEach((block) => (block.partial = false))
  2049. // Can't just do this b/c a tool could be in the middle of executing.
  2050. // this.assistantMessageContent.forEach((e) => (e.partial = false))
  2051. // Now that the stream is complete, finalize any remaining partial content blocks
  2052. this.assistantMessageParser.finalizeContentBlocks()
  2053. // Preserve tool_use blocks that were added via native protocol (not parsed from text)
  2054. // These come from tool_call chunks and are added directly to assistantMessageContent
  2055. const nativeToolBlocks = this.assistantMessageContent.filter((block) => block.type === "tool_use")
  2056. const parsedBlocks = this.assistantMessageParser.getContentBlocks()
  2057. // Merge: parser blocks + native tool blocks that aren't in parser
  2058. this.assistantMessageContent = [...parsedBlocks, ...nativeToolBlocks]
  2059. if (partialBlocks.length > 0) {
  2060. // If there is content to update then it will complete and
  2061. // update `this.userMessageContentReady` to true, which we
  2062. // `pWaitFor` before making the next request. All this is really
  2063. // doing is presenting the last partial message that we just set
  2064. // to complete.
  2065. presentAssistantMessage(this)
  2066. }
  2067. // Note: updateApiReqMsg() is now called from within drainStreamInBackgroundToFindAllUsage
  2068. // to ensure usage data is captured even when the stream is interrupted. The background task
  2069. // uses local variables to accumulate usage data before atomically updating the shared state.
  2070. // Complete the reasoning message if it exists
  2071. // We can't use say() here because the reasoning message may not be the last message
  2072. // (other messages like text blocks or tool uses may have been added after it during streaming)
  2073. if (reasoningMessage) {
  2074. const lastReasoningIndex = findLastIndex(
  2075. this.clineMessages,
  2076. (m) => m.type === "say" && m.say === "reasoning",
  2077. )
  2078. if (lastReasoningIndex !== -1 && this.clineMessages[lastReasoningIndex].partial) {
  2079. this.clineMessages[lastReasoningIndex].partial = false
  2080. await this.updateClineMessage(this.clineMessages[lastReasoningIndex])
  2081. }
  2082. }
  2083. await this.saveClineMessages()
  2084. await this.providerRef.deref()?.postStateToWebview()
  2085. // Reset parser after each complete conversation round
  2086. this.assistantMessageParser.reset()
  2087. // Now add to apiConversationHistory.
  2088. // Need to save assistant responses to file before proceeding to
  2089. // tool use since user can exit at any moment and we wouldn't be
  2090. // able to save the assistant's response.
  2091. let didEndLoop = false
  2092. // Check if we have any content to process (text or tool uses)
  2093. const hasTextContent = assistantMessage.length > 0
  2094. const hasToolUses = this.assistantMessageContent.some((block) => block.type === "tool_use")
  2095. if (hasTextContent || hasToolUses) {
  2096. // Display grounding sources to the user if they exist
  2097. if (pendingGroundingSources.length > 0) {
  2098. const citationLinks = pendingGroundingSources.map((source, i) => `[${i + 1}](${source.url})`)
  2099. const sourcesText = `${t("common:gemini.sources")} ${citationLinks.join(", ")}`
  2100. await this.say("text", sourcesText, undefined, false, undefined, undefined, {
  2101. isNonInteractive: true,
  2102. })
  2103. }
  2104. // Check if we should preserve reasoning in the assistant message
  2105. let finalAssistantMessage = assistantMessage
  2106. if (reasoningMessage && this.api.getModel().info.preserveReasoning) {
  2107. // Prepend reasoning in XML tags to the assistant message so it's included in API history
  2108. finalAssistantMessage = `<think>${reasoningMessage}</think>\n${assistantMessage}`
  2109. }
  2110. // Build the assistant message content array
  2111. const assistantContent: Array<Anthropic.TextBlockParam | Anthropic.ToolUseBlockParam> = []
  2112. // Add text content if present
  2113. if (finalAssistantMessage) {
  2114. assistantContent.push({
  2115. type: "text" as const,
  2116. text: finalAssistantMessage,
  2117. })
  2118. }
  2119. // Add tool_use blocks with their IDs for native protocol
  2120. const toolUseBlocks = this.assistantMessageContent.filter((block) => block.type === "tool_use")
  2121. for (const toolUse of toolUseBlocks) {
  2122. // Get the tool call ID that was stored during parsing
  2123. const toolCallId = (toolUse as any).id
  2124. if (toolCallId) {
  2125. // nativeArgs is already in the correct API format for all tools
  2126. const input = toolUse.nativeArgs || toolUse.params
  2127. assistantContent.push({
  2128. type: "tool_use" as const,
  2129. id: toolCallId,
  2130. name: toolUse.name,
  2131. input,
  2132. })
  2133. }
  2134. }
  2135. await this.addToApiConversationHistory({
  2136. role: "assistant",
  2137. content: assistantContent,
  2138. })
  2139. TelemetryService.instance.captureConversationMessage(this.taskId, "assistant")
  2140. // NOTE: This comment is here for future reference - this was a
  2141. // workaround for `userMessageContent` not getting set to true.
  2142. // It was due to it not recursively calling for partial blocks
  2143. // when `didRejectTool`, so it would get stuck waiting for a
  2144. // partial block to complete before it could continue.
  2145. // In case the content blocks finished it may be the api stream
  2146. // finished after the last parsed content block was executed, so
  2147. // we are able to detect out of bounds and set
  2148. // `userMessageContentReady` to true (note you should not call
  2149. // `presentAssistantMessage` since if the last block i
  2150. // completed it will be presented again).
  2151. // const completeBlocks = this.assistantMessageContent.filter((block) => !block.partial) // If there are any partial blocks after the stream ended we can consider them invalid.
  2152. // if (this.currentStreamingContentIndex >= completeBlocks.length) {
  2153. // this.userMessageContentReady = true
  2154. // }
  2155. await pWaitFor(() => this.userMessageContentReady)
  2156. // If the model did not tool use, then we need to tell it to
  2157. // either use a tool or attempt_completion.
  2158. const didToolUse = this.assistantMessageContent.some((block) => block.type === "tool_use")
  2159. if (!didToolUse) {
  2160. this.userMessageContent.push({ type: "text", text: formatResponse.noToolsUsed() })
  2161. this.consecutiveMistakeCount++
  2162. }
  2163. if (this.userMessageContent.length > 0) {
  2164. stack.push({
  2165. userContent: [...this.userMessageContent], // Create a copy to avoid mutation issues
  2166. includeFileDetails: false, // Subsequent iterations don't need file details
  2167. })
  2168. // Add periodic yielding to prevent blocking
  2169. await new Promise((resolve) => setImmediate(resolve))
  2170. }
  2171. // Continue to next iteration instead of setting didEndLoop from recursive call
  2172. continue
  2173. } else {
  2174. // If there's no assistant_responses, that means we got no text
  2175. // or tool_use content blocks from API which we should assume is
  2176. // an error.
  2177. // IMPORTANT: For native tool protocol, we already added the user message to
  2178. // apiConversationHistory at line 1876. Since the assistant failed to respond,
  2179. // we need to remove that message before retrying to avoid having two consecutive
  2180. // user messages (which would cause tool_result validation errors).
  2181. const toolProtocol = vscode.workspace
  2182. .getConfiguration(Package.name)
  2183. .get<ToolProtocol>("toolProtocol", "xml")
  2184. const isNativeProtocol = toolProtocol === TOOL_PROTOCOL.NATIVE
  2185. if (isNativeProtocol && this.apiConversationHistory.length > 0) {
  2186. const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1]
  2187. if (lastMessage.role === "user") {
  2188. // Remove the last user message that we added earlier
  2189. this.apiConversationHistory.pop()
  2190. }
  2191. }
  2192. // Check if we should auto-retry or prompt the user
  2193. const state = await this.providerRef.deref()?.getState()
  2194. if (state?.autoApprovalEnabled && state?.alwaysApproveResubmit) {
  2195. // Auto-retry with backoff - don't persist failure message when retrying
  2196. const errorMsg =
  2197. "Unexpected API Response: The language model did not provide any assistant messages. This may indicate an issue with the API or the model's output."
  2198. await this.backoffAndAnnounce(
  2199. currentItem.retryAttempt ?? 0,
  2200. new Error("Empty assistant response"),
  2201. errorMsg,
  2202. )
  2203. // Check if task was aborted during the backoff
  2204. if (this.abort) {
  2205. console.log(
  2206. `[Task#${this.taskId}.${this.instanceId}] Task aborted during empty-assistant retry backoff`,
  2207. )
  2208. break
  2209. }
  2210. // Push the same content back onto the stack to retry, incrementing the retry attempt counter
  2211. stack.push({
  2212. userContent: currentUserContent,
  2213. includeFileDetails: false,
  2214. retryAttempt: (currentItem.retryAttempt ?? 0) + 1,
  2215. })
  2216. // Continue to retry the request
  2217. continue
  2218. } else {
  2219. // Prompt the user for retry decision
  2220. const { response } = await this.ask(
  2221. "api_req_failed",
  2222. "The model returned no assistant messages. This may indicate an issue with the API or the model's output.",
  2223. )
  2224. if (response === "yesButtonClicked") {
  2225. await this.say("api_req_retried")
  2226. // Push the same content back to retry
  2227. stack.push({
  2228. userContent: currentUserContent,
  2229. includeFileDetails: false,
  2230. retryAttempt: (currentItem.retryAttempt ?? 0) + 1,
  2231. })
  2232. // Continue to retry the request
  2233. continue
  2234. } else {
  2235. // User declined to retry
  2236. // For native protocol, re-add the user message we removed
  2237. if (isNativeProtocol) {
  2238. await this.addToApiConversationHistory({
  2239. role: "user",
  2240. content: currentUserContent,
  2241. })
  2242. }
  2243. await this.say(
  2244. "error",
  2245. "Unexpected API Response: The language model did not provide any assistant messages. This may indicate an issue with the API or the model's output.",
  2246. )
  2247. await this.addToApiConversationHistory({
  2248. role: "assistant",
  2249. content: [{ type: "text", text: "Failure: I did not provide a response." }],
  2250. })
  2251. }
  2252. }
  2253. }
  2254. // If we reach here without continuing, return false (will always be false for now)
  2255. return false
  2256. } catch (error) {
  2257. // This should never happen since the only thing that can throw an
  2258. // error is the attemptApiRequest, which is wrapped in a try catch
  2259. // that sends an ask where if noButtonClicked, will clear current
  2260. // task and destroy this instance. However to avoid unhandled
  2261. // promise rejection, we will end this loop which will end execution
  2262. // of this instance (see `startTask`).
  2263. return true // Needs to be true so parent loop knows to end task.
  2264. }
  2265. }
  2266. // If we exit the while loop normally (stack is empty), return false
  2267. return false
  2268. }
  2269. private async getSystemPrompt(): Promise<string> {
  2270. const { mcpEnabled } = (await this.providerRef.deref()?.getState()) ?? {}
  2271. let mcpHub: McpHub | undefined
  2272. if (mcpEnabled ?? true) {
  2273. const provider = this.providerRef.deref()
  2274. if (!provider) {
  2275. throw new Error("Provider reference lost during view transition")
  2276. }
  2277. // Wait for MCP hub initialization through McpServerManager
  2278. mcpHub = await McpServerManager.getInstance(provider.context, provider)
  2279. if (!mcpHub) {
  2280. throw new Error("Failed to get MCP hub from server manager")
  2281. }
  2282. // Wait for MCP servers to be connected before generating system prompt
  2283. await pWaitFor(() => !mcpHub!.isConnecting, { timeout: 10_000 }).catch(() => {
  2284. console.error("MCP servers failed to connect in time")
  2285. })
  2286. }
  2287. const rooIgnoreInstructions = this.rooIgnoreController?.getInstructions()
  2288. const state = await this.providerRef.deref()?.getState()
  2289. const {
  2290. browserViewportSize,
  2291. mode,
  2292. customModes,
  2293. customModePrompts,
  2294. customInstructions,
  2295. experiments,
  2296. enableMcpServerCreation,
  2297. browserToolEnabled,
  2298. language,
  2299. maxConcurrentFileReads,
  2300. maxReadFileLine,
  2301. apiConfiguration,
  2302. } = state ?? {}
  2303. return await (async () => {
  2304. const provider = this.providerRef.deref()
  2305. if (!provider) {
  2306. throw new Error("Provider not available")
  2307. }
  2308. // Align browser tool enablement with generateSystemPrompt: require model image support,
  2309. // mode to include the browser group, and the user setting to be enabled.
  2310. const modeConfig = getModeBySlug(mode ?? defaultModeSlug, customModes)
  2311. const modeSupportsBrowser = modeConfig?.groups.some((group) => getGroupName(group) === "browser") ?? false
  2312. // Check if model supports browser capability (images)
  2313. const modelInfo = this.api.getModel().info
  2314. const modelSupportsBrowser = (modelInfo as any)?.supportsImages === true
  2315. const canUseBrowserTool = modelSupportsBrowser && modeSupportsBrowser && (browserToolEnabled ?? true)
  2316. return SYSTEM_PROMPT(
  2317. provider.context,
  2318. this.cwd,
  2319. canUseBrowserTool,
  2320. mcpHub,
  2321. this.diffStrategy,
  2322. browserViewportSize ?? "900x600",
  2323. mode ?? defaultModeSlug,
  2324. customModePrompts,
  2325. customModes,
  2326. customInstructions,
  2327. this.diffEnabled,
  2328. experiments,
  2329. enableMcpServerCreation,
  2330. language,
  2331. rooIgnoreInstructions,
  2332. maxReadFileLine !== -1,
  2333. {
  2334. maxConcurrentFileReads: maxConcurrentFileReads ?? 5,
  2335. todoListEnabled: apiConfiguration?.todoListEnabled ?? true,
  2336. useAgentRules:
  2337. vscode.workspace.getConfiguration(Package.name).get<boolean>("useAgentRules") ?? true,
  2338. newTaskRequireTodos: vscode.workspace
  2339. .getConfiguration(Package.name)
  2340. .get<boolean>("newTaskRequireTodos", false),
  2341. toolProtocol: vscode.workspace
  2342. .getConfiguration(Package.name)
  2343. .get<ToolProtocol>("toolProtocol", "xml"),
  2344. },
  2345. undefined, // todoList
  2346. this.api.getModel().id,
  2347. )
  2348. })()
  2349. }
  2350. private getCurrentProfileId(state: any): string {
  2351. return (
  2352. state?.listApiConfigMeta?.find((profile: any) => profile.name === state?.currentApiConfigName)?.id ??
  2353. "default"
  2354. )
  2355. }
  2356. private async handleContextWindowExceededError(): Promise<void> {
  2357. const state = await this.providerRef.deref()?.getState()
  2358. const { profileThresholds = {} } = state ?? {}
  2359. const { contextTokens } = this.getTokenUsage()
  2360. const modelInfo = this.api.getModel().info
  2361. const maxTokens = getModelMaxOutputTokens({
  2362. modelId: this.api.getModel().id,
  2363. model: modelInfo,
  2364. settings: this.apiConfiguration,
  2365. })
  2366. const contextWindow = modelInfo.contextWindow
  2367. // Get the current profile ID using the helper method
  2368. const currentProfileId = this.getCurrentProfileId(state)
  2369. // Log the context window error for debugging
  2370. console.warn(
  2371. `[Task#${this.taskId}] Context window exceeded for model ${this.api.getModel().id}. ` +
  2372. `Current tokens: ${contextTokens}, Context window: ${contextWindow}. ` +
  2373. `Forcing truncation to ${FORCED_CONTEXT_REDUCTION_PERCENT}% of current context.`,
  2374. )
  2375. // Force aggressive truncation by keeping only 75% of the conversation history
  2376. const truncateResult = await manageContext({
  2377. messages: this.apiConversationHistory,
  2378. totalTokens: contextTokens || 0,
  2379. maxTokens,
  2380. contextWindow,
  2381. apiHandler: this.api,
  2382. autoCondenseContext: true,
  2383. autoCondenseContextPercent: FORCED_CONTEXT_REDUCTION_PERCENT,
  2384. systemPrompt: await this.getSystemPrompt(),
  2385. taskId: this.taskId,
  2386. profileThresholds,
  2387. currentProfileId,
  2388. })
  2389. if (truncateResult.messages !== this.apiConversationHistory) {
  2390. await this.overwriteApiConversationHistory(truncateResult.messages)
  2391. }
  2392. if (truncateResult.summary) {
  2393. const { summary, cost, prevContextTokens, newContextTokens = 0 } = truncateResult
  2394. const contextCondense: ContextCondense = { summary, cost, newContextTokens, prevContextTokens }
  2395. await this.say(
  2396. "condense_context",
  2397. undefined /* text */,
  2398. undefined /* images */,
  2399. false /* partial */,
  2400. undefined /* checkpoint */,
  2401. undefined /* progressStatus */,
  2402. { isNonInteractive: true } /* options */,
  2403. contextCondense,
  2404. )
  2405. }
  2406. }
  2407. public async *attemptApiRequest(retryAttempt: number = 0): ApiStream {
  2408. const state = await this.providerRef.deref()?.getState()
  2409. const {
  2410. apiConfiguration,
  2411. autoApprovalEnabled,
  2412. alwaysApproveResubmit,
  2413. requestDelaySeconds,
  2414. mode,
  2415. autoCondenseContext = true,
  2416. autoCondenseContextPercent = 100,
  2417. profileThresholds = {},
  2418. } = state ?? {}
  2419. // Get condensing configuration for automatic triggers.
  2420. const customCondensingPrompt = state?.customCondensingPrompt
  2421. const condensingApiConfigId = state?.condensingApiConfigId
  2422. const listApiConfigMeta = state?.listApiConfigMeta
  2423. // Determine API handler to use for condensing.
  2424. let condensingApiHandler: ApiHandler | undefined
  2425. if (condensingApiConfigId && listApiConfigMeta && Array.isArray(listApiConfigMeta)) {
  2426. // Find matching config by ID
  2427. const matchingConfig = listApiConfigMeta.find((config) => config.id === condensingApiConfigId)
  2428. if (matchingConfig) {
  2429. const profile = await this.providerRef.deref()?.providerSettingsManager.getProfile({
  2430. id: condensingApiConfigId,
  2431. })
  2432. // Ensure profile and apiProvider exist before trying to build handler.
  2433. if (profile && profile.apiProvider) {
  2434. condensingApiHandler = buildApiHandler(profile)
  2435. }
  2436. }
  2437. }
  2438. let rateLimitDelay = 0
  2439. // Use the shared timestamp so that subtasks respect the same rate-limit
  2440. // window as their parent tasks.
  2441. if (Task.lastGlobalApiRequestTime) {
  2442. const now = performance.now()
  2443. const timeSinceLastRequest = now - Task.lastGlobalApiRequestTime
  2444. const rateLimit = apiConfiguration?.rateLimitSeconds || 0
  2445. rateLimitDelay = Math.ceil(Math.min(rateLimit, Math.max(0, rateLimit * 1000 - timeSinceLastRequest) / 1000))
  2446. }
  2447. // Only show rate limiting message if we're not retrying. If retrying, we'll include the delay there.
  2448. if (rateLimitDelay > 0 && retryAttempt === 0) {
  2449. // Show countdown timer
  2450. for (let i = rateLimitDelay; i > 0; i--) {
  2451. const delayMessage = `Rate limiting for ${i} seconds...`
  2452. await this.say("api_req_retry_delayed", delayMessage, undefined, true)
  2453. await delay(1000)
  2454. }
  2455. }
  2456. // Update last request time before making the request so that subsequent
  2457. // requests — even from new subtasks — will honour the provider's rate-limit.
  2458. Task.lastGlobalApiRequestTime = performance.now()
  2459. const systemPrompt = await this.getSystemPrompt()
  2460. const { contextTokens } = this.getTokenUsage()
  2461. if (contextTokens) {
  2462. const modelInfo = this.api.getModel().info
  2463. const maxTokens = getModelMaxOutputTokens({
  2464. modelId: this.api.getModel().id,
  2465. model: modelInfo,
  2466. settings: this.apiConfiguration,
  2467. })
  2468. const contextWindow = modelInfo.contextWindow
  2469. // Get the current profile ID using the helper method
  2470. const currentProfileId = this.getCurrentProfileId(state)
  2471. const truncateResult = await manageContext({
  2472. messages: this.apiConversationHistory,
  2473. totalTokens: contextTokens,
  2474. maxTokens,
  2475. contextWindow,
  2476. apiHandler: this.api,
  2477. autoCondenseContext,
  2478. autoCondenseContextPercent,
  2479. systemPrompt,
  2480. taskId: this.taskId,
  2481. customCondensingPrompt,
  2482. condensingApiHandler,
  2483. profileThresholds,
  2484. currentProfileId,
  2485. })
  2486. if (truncateResult.messages !== this.apiConversationHistory) {
  2487. await this.overwriteApiConversationHistory(truncateResult.messages)
  2488. }
  2489. if (truncateResult.error) {
  2490. await this.say("condense_context_error", truncateResult.error)
  2491. } else if (truncateResult.summary) {
  2492. const { summary, cost, prevContextTokens, newContextTokens = 0 } = truncateResult
  2493. const contextCondense: ContextCondense = { summary, cost, newContextTokens, prevContextTokens }
  2494. await this.say(
  2495. "condense_context",
  2496. undefined /* text */,
  2497. undefined /* images */,
  2498. false /* partial */,
  2499. undefined /* checkpoint */,
  2500. undefined /* progressStatus */,
  2501. { isNonInteractive: true } /* options */,
  2502. contextCondense,
  2503. )
  2504. }
  2505. }
  2506. // Properly type cleaned conversation history to include either standard Anthropic messages
  2507. // or provider-specific reasoning items (for encrypted continuity).
  2508. type ReasoningItemForRequest = {
  2509. type: "reasoning"
  2510. encrypted_content: string
  2511. id?: string
  2512. summary?: any[]
  2513. }
  2514. type CleanConversationMessage = Anthropic.Messages.MessageParam | ReasoningItemForRequest
  2515. const messagesSinceLastSummary = getMessagesSinceLastSummary(this.apiConversationHistory)
  2516. const cleanConversationHistory: CleanConversationMessage[] = maybeRemoveImageBlocks(
  2517. messagesSinceLastSummary,
  2518. this.api,
  2519. ).map((msg: ApiMessage): CleanConversationMessage => {
  2520. // Pass through reasoning items as-is (including id if present)
  2521. if (msg.type === "reasoning") {
  2522. return {
  2523. type: "reasoning",
  2524. summary: msg.summary,
  2525. encrypted_content: msg.encrypted_content!,
  2526. ...(msg.id ? { id: msg.id } : {}),
  2527. }
  2528. }
  2529. // For regular messages, just return role and content
  2530. return { role: msg.role!, content: msg.content as Anthropic.Messages.ContentBlockParam[] | string }
  2531. })
  2532. // Check auto-approval limits
  2533. const approvalResult = await this.autoApprovalHandler.checkAutoApprovalLimits(
  2534. state,
  2535. this.combineMessages(this.clineMessages.slice(1)),
  2536. async (type, data) => this.ask(type, data),
  2537. )
  2538. if (!approvalResult.shouldProceed) {
  2539. // User did not approve, task should be aborted
  2540. throw new Error("Auto-approval limit reached and user did not approve continuation")
  2541. }
  2542. // Determine if we should include native tools based on:
  2543. // 1. Tool protocol is set to NATIVE
  2544. // 2. Model supports native tools
  2545. const toolProtocol = vscode.workspace.getConfiguration(Package.name).get<ToolProtocol>("toolProtocol", "xml")
  2546. const modelInfo = this.api.getModel().info
  2547. const shouldIncludeTools = toolProtocol === TOOL_PROTOCOL.NATIVE && (modelInfo.supportsNativeTools ?? false)
  2548. // Build complete tools array: native tools + dynamic MCP tools
  2549. let allTools: OpenAI.Chat.ChatCompletionTool[] = nativeTools
  2550. if (shouldIncludeTools) {
  2551. const provider = this.providerRef.deref()
  2552. const mcpHub = provider?.getMcpHub()
  2553. const mcpTools = getMcpServerTools(mcpHub)
  2554. allTools = [...nativeTools, ...mcpTools]
  2555. }
  2556. const metadata: ApiHandlerCreateMessageMetadata = {
  2557. mode: mode,
  2558. taskId: this.taskId,
  2559. // Include tools and tool protocol when using native protocol and model supports it
  2560. ...(shouldIncludeTools ? { tools: allTools, tool_choice: "required", toolProtocol } : {}),
  2561. }
  2562. // The provider accepts reasoning items alongside standard messages; cast to the expected parameter type.
  2563. const stream = this.api.createMessage(
  2564. systemPrompt,
  2565. cleanConversationHistory as unknown as Anthropic.Messages.MessageParam[],
  2566. metadata,
  2567. )
  2568. const iterator = stream[Symbol.asyncIterator]()
  2569. try {
  2570. // Awaiting first chunk to see if it will throw an error.
  2571. this.isWaitingForFirstChunk = true
  2572. const firstChunk = await iterator.next()
  2573. yield firstChunk.value
  2574. this.isWaitingForFirstChunk = false
  2575. } catch (error) {
  2576. this.isWaitingForFirstChunk = false
  2577. const isContextWindowExceededError = checkContextWindowExceededError(error)
  2578. // If it's a context window error and we haven't exceeded max retries for this error type
  2579. if (isContextWindowExceededError && retryAttempt < MAX_CONTEXT_WINDOW_RETRIES) {
  2580. console.warn(
  2581. `[Task#${this.taskId}] Context window exceeded for model ${this.api.getModel().id}. ` +
  2582. `Retry attempt ${retryAttempt + 1}/${MAX_CONTEXT_WINDOW_RETRIES}. ` +
  2583. `Attempting automatic truncation...`,
  2584. )
  2585. await this.handleContextWindowExceededError()
  2586. // Retry the request after handling the context window error
  2587. yield* this.attemptApiRequest(retryAttempt + 1)
  2588. return
  2589. }
  2590. // note that this api_req_failed ask is unique in that we only present this option if the api hasn't streamed any content yet (ie it fails on the first chunk due), as it would allow them to hit a retry button. However if the api failed mid-stream, it could be in any arbitrary state where some tools may have executed, so that error is handled differently and requires cancelling the task entirely.
  2591. if (autoApprovalEnabled && alwaysApproveResubmit) {
  2592. let errorMsg
  2593. if (error.error?.metadata?.raw) {
  2594. errorMsg = JSON.stringify(error.error.metadata.raw, null, 2)
  2595. } else if (error.message) {
  2596. errorMsg = error.message
  2597. } else {
  2598. errorMsg = "Unknown error"
  2599. }
  2600. // Apply shared exponential backoff and countdown UX
  2601. await this.backoffAndAnnounce(retryAttempt, error, errorMsg)
  2602. // CRITICAL: Check if task was aborted during the backoff countdown
  2603. // This prevents infinite loops when users cancel during auto-retry
  2604. // Without this check, the recursive call below would continue even after abort
  2605. if (this.abort) {
  2606. throw new Error(
  2607. `[Task#attemptApiRequest] task ${this.taskId}.${this.instanceId} aborted during retry`,
  2608. )
  2609. }
  2610. // Delegate generator output from the recursive call with
  2611. // incremented retry count.
  2612. yield* this.attemptApiRequest(retryAttempt + 1)
  2613. return
  2614. } else {
  2615. const { response } = await this.ask(
  2616. "api_req_failed",
  2617. error.message ?? JSON.stringify(serializeError(error), null, 2),
  2618. )
  2619. if (response !== "yesButtonClicked") {
  2620. // This will never happen since if noButtonClicked, we will
  2621. // clear current task, aborting this instance.
  2622. throw new Error("API request failed")
  2623. }
  2624. await this.say("api_req_retried")
  2625. // Delegate generator output from the recursive call.
  2626. yield* this.attemptApiRequest()
  2627. return
  2628. }
  2629. }
  2630. // No error, so we can continue to yield all remaining chunks.
  2631. // (Needs to be placed outside of try/catch since it we want caller to
  2632. // handle errors not with api_req_failed as that is reserved for first
  2633. // chunk failures only.)
  2634. // This delegates to another generator or iterable object. In this case,
  2635. // it's saying "yield all remaining values from this iterator". This
  2636. // effectively passes along all subsequent chunks from the original
  2637. // stream.
  2638. yield* iterator
  2639. }
  2640. // Shared exponential backoff for retries (first-chunk and mid-stream)
  2641. private async backoffAndAnnounce(retryAttempt: number, error: any, header?: string): Promise<void> {
  2642. try {
  2643. const state = await this.providerRef.deref()?.getState()
  2644. const baseDelay = state?.requestDelaySeconds || 5
  2645. let exponentialDelay = Math.min(
  2646. Math.ceil(baseDelay * Math.pow(2, retryAttempt)),
  2647. MAX_EXPONENTIAL_BACKOFF_SECONDS,
  2648. )
  2649. // Respect provider rate limit window
  2650. let rateLimitDelay = 0
  2651. const rateLimit = state?.apiConfiguration?.rateLimitSeconds || 0
  2652. if (Task.lastGlobalApiRequestTime && rateLimit > 0) {
  2653. const elapsed = performance.now() - Task.lastGlobalApiRequestTime
  2654. rateLimitDelay = Math.ceil(Math.min(rateLimit, Math.max(0, rateLimit * 1000 - elapsed) / 1000))
  2655. }
  2656. // Prefer RetryInfo on 429 if present
  2657. if (error?.status === 429) {
  2658. const retryInfo = error?.errorDetails?.find(
  2659. (d: any) => d["@type"] === "type.googleapis.com/google.rpc.RetryInfo",
  2660. )
  2661. const match = retryInfo?.retryDelay?.match?.(/^(\d+)s$/)
  2662. if (match) {
  2663. exponentialDelay = Number(match[1]) + 1
  2664. }
  2665. }
  2666. const finalDelay = Math.max(exponentialDelay, rateLimitDelay)
  2667. if (finalDelay <= 0) return
  2668. // Build header text; fall back to error message if none provided
  2669. let headerText = header
  2670. if (!headerText) {
  2671. if (error?.error?.metadata?.raw) {
  2672. headerText = JSON.stringify(error.error.metadata.raw, null, 2)
  2673. } else if (error?.message) {
  2674. headerText = error.message
  2675. } else {
  2676. headerText = "Unknown error"
  2677. }
  2678. }
  2679. headerText = headerText ? `${headerText}\n\n` : ""
  2680. // Show countdown timer with exponential backoff
  2681. for (let i = finalDelay; i > 0; i--) {
  2682. // Check abort flag during countdown to allow early exit
  2683. if (this.abort) {
  2684. throw new Error(`[Task#${this.taskId}] Aborted during retry countdown`)
  2685. }
  2686. await this.say(
  2687. "api_req_retry_delayed",
  2688. `${headerText}Retry attempt ${retryAttempt + 1}\nRetrying in ${i} seconds...`,
  2689. undefined,
  2690. true,
  2691. )
  2692. await delay(1000)
  2693. }
  2694. await this.say(
  2695. "api_req_retry_delayed",
  2696. `${headerText}Retry attempt ${retryAttempt + 1}\nRetrying now...`,
  2697. undefined,
  2698. false,
  2699. )
  2700. } catch (err) {
  2701. console.error("Exponential backoff failed:", err)
  2702. }
  2703. }
  2704. // Checkpoints
  2705. public async checkpointSave(force: boolean = false, suppressMessage: boolean = false) {
  2706. return checkpointSave(this, force, suppressMessage)
  2707. }
  2708. public async checkpointRestore(options: CheckpointRestoreOptions) {
  2709. return checkpointRestore(this, options)
  2710. }
  2711. public async checkpointDiff(options: CheckpointDiffOptions) {
  2712. return checkpointDiff(this, options)
  2713. }
  2714. // Metrics
  2715. public combineMessages(messages: ClineMessage[]) {
  2716. return combineApiRequests(combineCommandSequences(messages))
  2717. }
  2718. public getTokenUsage(): TokenUsage {
  2719. return getApiMetrics(this.combineMessages(this.clineMessages.slice(1)))
  2720. }
  2721. public recordToolUsage(toolName: ToolName) {
  2722. if (!this.toolUsage[toolName]) {
  2723. this.toolUsage[toolName] = { attempts: 0, failures: 0 }
  2724. }
  2725. this.toolUsage[toolName].attempts++
  2726. }
  2727. public recordToolError(toolName: ToolName, error?: string) {
  2728. if (!this.toolUsage[toolName]) {
  2729. this.toolUsage[toolName] = { attempts: 0, failures: 0 }
  2730. }
  2731. this.toolUsage[toolName].failures++
  2732. if (error) {
  2733. this.emit(RooCodeEventName.TaskToolFailed, this.taskId, toolName, error)
  2734. }
  2735. }
  2736. // Getters
  2737. public get taskStatus(): TaskStatus {
  2738. if (this.interactiveAsk) {
  2739. return TaskStatus.Interactive
  2740. }
  2741. if (this.resumableAsk) {
  2742. return TaskStatus.Resumable
  2743. }
  2744. if (this.idleAsk) {
  2745. return TaskStatus.Idle
  2746. }
  2747. return TaskStatus.Running
  2748. }
  2749. public get taskAsk(): ClineMessage | undefined {
  2750. return this.idleAsk || this.resumableAsk || this.interactiveAsk
  2751. }
  2752. public get queuedMessages(): QueuedMessage[] {
  2753. return this.messageQueueService.messages
  2754. }
  2755. public get tokenUsage(): TokenUsage | undefined {
  2756. if (this.tokenUsageSnapshot && this.tokenUsageSnapshotAt) {
  2757. return this.tokenUsageSnapshot
  2758. }
  2759. this.tokenUsageSnapshot = this.getTokenUsage()
  2760. this.tokenUsageSnapshotAt = this.clineMessages.at(-1)?.ts
  2761. return this.tokenUsageSnapshot
  2762. }
  2763. public get cwd() {
  2764. return this.workspacePath
  2765. }
  2766. /**
  2767. * Process any queued messages by dequeuing and submitting them.
  2768. * This ensures that queued user messages are sent when appropriate,
  2769. * preventing them from getting stuck in the queue.
  2770. *
  2771. * @param context - Context string for logging (e.g., the calling tool name)
  2772. */
  2773. public processQueuedMessages(): void {
  2774. try {
  2775. if (!this.messageQueueService.isEmpty()) {
  2776. const queued = this.messageQueueService.dequeueMessage()
  2777. if (queued) {
  2778. setTimeout(() => {
  2779. this.submitUserMessage(queued.text, queued.images).catch((err) =>
  2780. console.error(`[Task] Failed to submit queued message:`, err),
  2781. )
  2782. }, 0)
  2783. }
  2784. }
  2785. } catch (e) {
  2786. console.error(`[Task] Queue processing error:`, e)
  2787. }
  2788. }
  2789. }