Task.ts 147 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177
  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 { AskIgnoredError } from "./AskIgnoredError"
  7. import { Anthropic } from "@anthropic-ai/sdk"
  8. import OpenAI from "openai"
  9. import delay from "delay"
  10. import pWaitFor from "p-wait-for"
  11. import { serializeError } from "serialize-error"
  12. import { Package } from "../../shared/package"
  13. import { formatToolInvocation } from "../tools/helpers/toolResultFormatting"
  14. import {
  15. type TaskLike,
  16. type TaskMetadata,
  17. type TaskEvents,
  18. type ProviderSettings,
  19. type TokenUsage,
  20. type ToolUsage,
  21. type ToolName,
  22. type ContextCondense,
  23. type ContextTruncation,
  24. type ClineMessage,
  25. type ClineSay,
  26. type ClineAsk,
  27. type ToolProgressStatus,
  28. type HistoryItem,
  29. type CreateTaskOptions,
  30. type ModelInfo,
  31. RooCodeEventName,
  32. TelemetryEventName,
  33. TaskStatus,
  34. TodoItem,
  35. getApiProtocol,
  36. getModelId,
  37. isIdleAsk,
  38. isInteractiveAsk,
  39. isResumableAsk,
  40. isNativeProtocol,
  41. QueuedMessage,
  42. DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
  43. DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
  44. MAX_CHECKPOINT_TIMEOUT_SECONDS,
  45. MIN_CHECKPOINT_TIMEOUT_SECONDS,
  46. TOOL_PROTOCOL,
  47. } from "@roo-code/types"
  48. import { TelemetryService } from "@roo-code/telemetry"
  49. import { CloudService, BridgeOrchestrator } from "@roo-code/cloud"
  50. import { resolveToolProtocol } from "../../utils/resolveToolProtocol"
  51. // api
  52. import { ApiHandler, ApiHandlerCreateMessageMetadata, buildApiHandler } from "../../api"
  53. import { ApiStream, GroundingSource } from "../../api/transform/stream"
  54. import { maybeRemoveImageBlocks } from "../../api/transform/image-cleaning"
  55. // shared
  56. import { findLastIndex } from "../../shared/array"
  57. import { combineApiRequests } from "../../shared/combineApiRequests"
  58. import { combineCommandSequences } from "../../shared/combineCommandSequences"
  59. import { t } from "../../i18n"
  60. import { ClineApiReqCancelReason, ClineApiReqInfo } from "../../shared/ExtensionMessage"
  61. import { getApiMetrics, hasTokenUsageChanged } from "../../shared/getApiMetrics"
  62. import { ClineAskResponse } from "../../shared/WebviewMessage"
  63. import { defaultModeSlug, getModeBySlug, getGroupName } from "../../shared/modes"
  64. import { DiffStrategy, type ToolUse, type ToolParamName, toolParamNames } from "../../shared/tools"
  65. import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
  66. import { getModelMaxOutputTokens } from "../../shared/api"
  67. // services
  68. import { UrlContentFetcher } from "../../services/browser/UrlContentFetcher"
  69. import { BrowserSession } from "../../services/browser/BrowserSession"
  70. import { McpHub } from "../../services/mcp/McpHub"
  71. import { McpServerManager } from "../../services/mcp/McpServerManager"
  72. import { RepoPerTaskCheckpointService } from "../../services/checkpoints"
  73. // integrations
  74. import { DiffViewProvider } from "../../integrations/editor/DiffViewProvider"
  75. import { findToolName } from "../../integrations/misc/export-markdown"
  76. import { RooTerminalProcess } from "../../integrations/terminal/types"
  77. import { TerminalRegistry } from "../../integrations/terminal/TerminalRegistry"
  78. // utils
  79. import { calculateApiCostAnthropic, calculateApiCostOpenAI } from "../../shared/cost"
  80. import { getWorkspacePath } from "../../utils/path"
  81. // prompts
  82. import { formatResponse } from "../prompts/responses"
  83. import { SYSTEM_PROMPT } from "../prompts/system"
  84. import { buildNativeToolsArray } from "./build-tools"
  85. // core modules
  86. import { ToolRepetitionDetector } from "../tools/ToolRepetitionDetector"
  87. import { restoreTodoListForTask } from "../tools/UpdateTodoListTool"
  88. import { FileContextTracker } from "../context-tracking/FileContextTracker"
  89. import { RooIgnoreController } from "../ignore/RooIgnoreController"
  90. import { RooProtectedController } from "../protect/RooProtectedController"
  91. import { type AssistantMessageContent, presentAssistantMessage } from "../assistant-message"
  92. import { AssistantMessageParser } from "../assistant-message/AssistantMessageParser"
  93. import { NativeToolCallParser } from "../assistant-message/NativeToolCallParser"
  94. import { manageContext, willManageContext } from "../context-management"
  95. import { ClineProvider } from "../webview/ClineProvider"
  96. import { MultiSearchReplaceDiffStrategy } from "../diff/strategies/multi-search-replace"
  97. import { MultiFileSearchReplaceDiffStrategy } from "../diff/strategies/multi-file-search-replace"
  98. import {
  99. type ApiMessage,
  100. readApiMessages,
  101. saveApiMessages,
  102. readTaskMessages,
  103. saveTaskMessages,
  104. taskMetadata,
  105. } from "../task-persistence"
  106. import { getEnvironmentDetails } from "../environment/getEnvironmentDetails"
  107. import { checkContextWindowExceededError } from "../context/context-management/context-error-handling"
  108. import {
  109. type CheckpointDiffOptions,
  110. type CheckpointRestoreOptions,
  111. getCheckpointService,
  112. checkpointSave,
  113. checkpointRestore,
  114. checkpointDiff,
  115. } from "../checkpoints"
  116. import { processUserContentMentions } from "../mentions/processUserContentMentions"
  117. import { getMessagesSinceLastSummary, summarizeConversation, getEffectiveApiHistory } from "../condense"
  118. import { MessageQueueService } from "../message-queue/MessageQueueService"
  119. import { AutoApprovalHandler, checkAutoApproval } from "../auto-approval"
  120. import { MessageManager } from "../message-manager"
  121. const MAX_EXPONENTIAL_BACKOFF_SECONDS = 600 // 10 minutes
  122. const DEFAULT_USAGE_COLLECTION_TIMEOUT_MS = 5000 // 5 seconds
  123. const FORCED_CONTEXT_REDUCTION_PERCENT = 75 // Keep 75% of context (remove 25%) on context window errors
  124. const MAX_CONTEXT_WINDOW_RETRIES = 3 // Maximum retries for context window errors
  125. export interface TaskOptions extends CreateTaskOptions {
  126. provider: ClineProvider
  127. apiConfiguration: ProviderSettings
  128. enableDiff?: boolean
  129. enableCheckpoints?: boolean
  130. checkpointTimeout?: number
  131. enableBridge?: boolean
  132. fuzzyMatchThreshold?: number
  133. consecutiveMistakeLimit?: number
  134. task?: string
  135. images?: string[]
  136. historyItem?: HistoryItem
  137. experiments?: Record<string, boolean>
  138. startTask?: boolean
  139. rootTask?: Task
  140. parentTask?: Task
  141. taskNumber?: number
  142. onCreated?: (task: Task) => void
  143. initialTodos?: TodoItem[]
  144. workspacePath?: string
  145. /** Initial status for the task's history item (e.g., "active" for child tasks) */
  146. initialStatus?: "active" | "delegated" | "completed"
  147. }
  148. export class Task extends EventEmitter<TaskEvents> implements TaskLike {
  149. readonly taskId: string
  150. readonly rootTaskId?: string
  151. readonly parentTaskId?: string
  152. childTaskId?: string
  153. pendingNewTaskToolCallId?: string
  154. readonly instanceId: string
  155. readonly metadata: TaskMetadata
  156. todoList?: TodoItem[]
  157. readonly rootTask: Task | undefined = undefined
  158. readonly parentTask: Task | undefined = undefined
  159. readonly taskNumber: number
  160. readonly workspacePath: string
  161. /**
  162. * The mode associated with this task. Persisted across sessions
  163. * to maintain user context when reopening tasks from history.
  164. *
  165. * ## Lifecycle
  166. *
  167. * ### For new tasks:
  168. * 1. Initially `undefined` during construction
  169. * 2. Asynchronously initialized from provider state via `initializeTaskMode()`
  170. * 3. Falls back to `defaultModeSlug` if provider state is unavailable
  171. *
  172. * ### For history items:
  173. * 1. Immediately set from `historyItem.mode` during construction
  174. * 2. Falls back to `defaultModeSlug` if mode is not stored in history
  175. *
  176. * ## Important
  177. * This property should NOT be accessed directly until `taskModeReady` promise resolves.
  178. * Use `getTaskMode()` for async access or `taskMode` getter for sync access after initialization.
  179. *
  180. * @private
  181. * @see {@link getTaskMode} - For safe async access
  182. * @see {@link taskMode} - For sync access after initialization
  183. * @see {@link waitForModeInitialization} - To ensure initialization is complete
  184. */
  185. private _taskMode: string | undefined
  186. /**
  187. * Promise that resolves when the task mode has been initialized.
  188. * This ensures async mode initialization completes before the task is used.
  189. *
  190. * ## Purpose
  191. * - Prevents race conditions when accessing task mode
  192. * - Ensures provider state is properly loaded before mode-dependent operations
  193. * - Provides a synchronization point for async initialization
  194. *
  195. * ## Resolution timing
  196. * - For history items: Resolves immediately (sync initialization)
  197. * - For new tasks: Resolves after provider state is fetched (async initialization)
  198. *
  199. * @private
  200. * @see {@link waitForModeInitialization} - Public method to await this promise
  201. */
  202. private taskModeReady: Promise<void>
  203. providerRef: WeakRef<ClineProvider>
  204. private readonly globalStoragePath: string
  205. abort: boolean = false
  206. currentRequestAbortController?: AbortController
  207. skipPrevResponseIdOnce: boolean = false
  208. // TaskStatus
  209. idleAsk?: ClineMessage
  210. resumableAsk?: ClineMessage
  211. interactiveAsk?: ClineMessage
  212. didFinishAbortingStream = false
  213. abandoned = false
  214. abortReason?: ClineApiReqCancelReason
  215. isInitialized = false
  216. isPaused: boolean = false
  217. // API
  218. apiConfiguration: ProviderSettings
  219. api: ApiHandler
  220. private static lastGlobalApiRequestTime?: number
  221. private autoApprovalHandler: AutoApprovalHandler
  222. /**
  223. * Reset the global API request timestamp. This should only be used for testing.
  224. * @internal
  225. */
  226. static resetGlobalApiRequestTime(): void {
  227. Task.lastGlobalApiRequestTime = undefined
  228. }
  229. toolRepetitionDetector: ToolRepetitionDetector
  230. rooIgnoreController?: RooIgnoreController
  231. rooProtectedController?: RooProtectedController
  232. fileContextTracker: FileContextTracker
  233. urlContentFetcher: UrlContentFetcher
  234. terminalProcess?: RooTerminalProcess
  235. // Computer User
  236. browserSession: BrowserSession
  237. // Editing
  238. diffViewProvider: DiffViewProvider
  239. diffStrategy?: DiffStrategy
  240. diffEnabled: boolean = false
  241. fuzzyMatchThreshold: number
  242. didEditFile: boolean = false
  243. // LLM Messages & Chat Messages
  244. apiConversationHistory: ApiMessage[] = []
  245. clineMessages: ClineMessage[] = []
  246. // Ask
  247. private askResponse?: ClineAskResponse
  248. private askResponseText?: string
  249. private askResponseImages?: string[]
  250. public lastMessageTs?: number
  251. // Tool Use
  252. consecutiveMistakeCount: number = 0
  253. consecutiveMistakeLimit: number
  254. consecutiveMistakeCountForApplyDiff: Map<string, number> = new Map()
  255. toolUsage: ToolUsage = {}
  256. // Checkpoints
  257. enableCheckpoints: boolean
  258. checkpointTimeout: number
  259. checkpointService?: RepoPerTaskCheckpointService
  260. checkpointServiceInitializing = false
  261. // Task Bridge
  262. enableBridge: boolean
  263. // Message Queue Service
  264. public readonly messageQueueService: MessageQueueService
  265. private messageQueueStateChangedHandler: (() => void) | undefined
  266. // Streaming
  267. isWaitingForFirstChunk = false
  268. isStreaming = false
  269. currentStreamingContentIndex = 0
  270. currentStreamingDidCheckpoint = false
  271. assistantMessageContent: AssistantMessageContent[] = []
  272. presentAssistantMessageLocked = false
  273. presentAssistantMessageHasPendingUpdates = false
  274. userMessageContent: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolResultBlockParam)[] = []
  275. userMessageContentReady = false
  276. didRejectTool = false
  277. didAlreadyUseTool = false
  278. didToolFailInCurrentTurn = false
  279. didCompleteReadingStream = false
  280. assistantMessageParser?: AssistantMessageParser
  281. private providerProfileChangeListener?: (config: { name: string; provider?: string }) => void
  282. // Native tool call streaming state (track which index each tool is at)
  283. private streamingToolCallIndices: Map<string, number> = new Map()
  284. // Cached model info for current streaming session (set at start of each API request)
  285. // This prevents excessive getModel() calls during tool execution
  286. cachedStreamingModel?: { id: string; info: ModelInfo }
  287. // Token Usage Cache
  288. private tokenUsageSnapshot?: TokenUsage
  289. private tokenUsageSnapshotAt?: number
  290. // Cloud Sync Tracking
  291. private cloudSyncedMessageTimestamps: Set<number> = new Set()
  292. // Initial status for the task's history item (set at creation time to avoid race conditions)
  293. private readonly initialStatus?: "active" | "delegated" | "completed"
  294. // MessageManager for high-level message operations (lazy initialized)
  295. private _messageManager?: MessageManager
  296. constructor({
  297. provider,
  298. apiConfiguration,
  299. enableDiff = false,
  300. enableCheckpoints = true,
  301. checkpointTimeout = DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
  302. enableBridge = false,
  303. fuzzyMatchThreshold = 1.0,
  304. consecutiveMistakeLimit = DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
  305. task,
  306. images,
  307. historyItem,
  308. experiments: experimentsConfig,
  309. startTask = true,
  310. rootTask,
  311. parentTask,
  312. taskNumber = -1,
  313. onCreated,
  314. initialTodos,
  315. workspacePath,
  316. initialStatus,
  317. }: TaskOptions) {
  318. super()
  319. if (startTask && !task && !images && !historyItem) {
  320. throw new Error("Either historyItem or task/images must be provided")
  321. }
  322. if (
  323. !checkpointTimeout ||
  324. checkpointTimeout > MAX_CHECKPOINT_TIMEOUT_SECONDS ||
  325. checkpointTimeout < MIN_CHECKPOINT_TIMEOUT_SECONDS
  326. ) {
  327. throw new Error(
  328. "checkpointTimeout must be between " +
  329. MIN_CHECKPOINT_TIMEOUT_SECONDS +
  330. " and " +
  331. MAX_CHECKPOINT_TIMEOUT_SECONDS +
  332. " seconds",
  333. )
  334. }
  335. this.taskId = historyItem ? historyItem.id : crypto.randomUUID()
  336. this.rootTaskId = historyItem ? historyItem.rootTaskId : rootTask?.taskId
  337. this.parentTaskId = historyItem ? historyItem.parentTaskId : parentTask?.taskId
  338. this.childTaskId = undefined
  339. this.metadata = {
  340. task: historyItem ? historyItem.task : task,
  341. images: historyItem ? [] : images,
  342. }
  343. // Normal use-case is usually retry similar history task with new workspace.
  344. this.workspacePath = parentTask
  345. ? parentTask.workspacePath
  346. : (workspacePath ?? getWorkspacePath(path.join(os.homedir(), "Desktop")))
  347. this.instanceId = crypto.randomUUID().slice(0, 8)
  348. this.taskNumber = -1
  349. this.rooIgnoreController = new RooIgnoreController(this.cwd)
  350. this.rooProtectedController = new RooProtectedController(this.cwd)
  351. this.fileContextTracker = new FileContextTracker(provider, this.taskId)
  352. this.rooIgnoreController.initialize().catch((error) => {
  353. console.error("Failed to initialize RooIgnoreController:", error)
  354. })
  355. this.apiConfiguration = apiConfiguration
  356. this.api = buildApiHandler(apiConfiguration)
  357. this.autoApprovalHandler = new AutoApprovalHandler()
  358. this.urlContentFetcher = new UrlContentFetcher(provider.context)
  359. this.browserSession = new BrowserSession(provider.context, (isActive: boolean) => {
  360. // Add a message to indicate browser session status change
  361. this.say("browser_session_status", isActive ? "Browser session opened" : "Browser session closed")
  362. // Broadcast to browser panel
  363. this.broadcastBrowserSessionUpdate()
  364. // When a browser session becomes active, automatically open/reveal the Browser Session tab
  365. if (isActive) {
  366. try {
  367. // Lazy-load to avoid circular imports at module load time
  368. const { BrowserSessionPanelManager } = require("../webview/BrowserSessionPanelManager")
  369. const providerRef = this.providerRef.deref()
  370. if (providerRef) {
  371. BrowserSessionPanelManager.getInstance(providerRef)
  372. .show()
  373. .catch(() => {})
  374. }
  375. } catch (err) {
  376. console.error("[Task] Failed to auto-open Browser Session panel:", err)
  377. }
  378. }
  379. })
  380. this.diffEnabled = enableDiff
  381. this.fuzzyMatchThreshold = fuzzyMatchThreshold
  382. this.consecutiveMistakeLimit = consecutiveMistakeLimit ?? DEFAULT_CONSECUTIVE_MISTAKE_LIMIT
  383. this.providerRef = new WeakRef(provider)
  384. this.globalStoragePath = provider.context.globalStorageUri.fsPath
  385. this.diffViewProvider = new DiffViewProvider(this.cwd, this)
  386. this.enableCheckpoints = enableCheckpoints
  387. this.checkpointTimeout = checkpointTimeout
  388. this.enableBridge = enableBridge
  389. this.parentTask = parentTask
  390. this.taskNumber = taskNumber
  391. this.initialStatus = initialStatus
  392. // Store the task's mode when it's created.
  393. // For history items, use the stored mode; for new tasks, we'll set it
  394. // after getting state.
  395. if (historyItem) {
  396. this._taskMode = historyItem.mode || defaultModeSlug
  397. this.taskModeReady = Promise.resolve()
  398. TelemetryService.instance.captureTaskRestarted(this.taskId)
  399. } else {
  400. // For new tasks, don't set the mode yet - wait for async initialization.
  401. this._taskMode = undefined
  402. this.taskModeReady = this.initializeTaskMode(provider)
  403. TelemetryService.instance.captureTaskCreated(this.taskId)
  404. }
  405. // Initialize the assistant message parser only for XML protocol.
  406. // For native protocol, tool calls come as tool_call chunks, not XML.
  407. // experiments is always provided via TaskOptions (defaults to experimentDefault in provider)
  408. const modelInfo = this.api.getModel().info
  409. const toolProtocol = resolveToolProtocol(this.apiConfiguration, modelInfo)
  410. this.assistantMessageParser = toolProtocol !== "native" ? new AssistantMessageParser() : undefined
  411. this.messageQueueService = new MessageQueueService()
  412. this.messageQueueStateChangedHandler = () => {
  413. this.emit(RooCodeEventName.TaskUserMessage, this.taskId)
  414. this.providerRef.deref()?.postStateToWebview()
  415. }
  416. this.messageQueueService.on("stateChanged", this.messageQueueStateChangedHandler)
  417. // Listen for provider profile changes to update parser state
  418. this.setupProviderProfileChangeListener(provider)
  419. // Only set up diff strategy if diff is enabled.
  420. if (this.diffEnabled) {
  421. // Default to old strategy, will be updated if experiment is enabled.
  422. this.diffStrategy = new MultiSearchReplaceDiffStrategy(this.fuzzyMatchThreshold)
  423. // Check experiment asynchronously and update strategy if needed.
  424. provider.getState().then((state) => {
  425. const isMultiFileApplyDiffEnabled = experiments.isEnabled(
  426. state.experiments ?? {},
  427. EXPERIMENT_IDS.MULTI_FILE_APPLY_DIFF,
  428. )
  429. if (isMultiFileApplyDiffEnabled) {
  430. this.diffStrategy = new MultiFileSearchReplaceDiffStrategy(this.fuzzyMatchThreshold)
  431. }
  432. })
  433. }
  434. this.toolRepetitionDetector = new ToolRepetitionDetector(this.consecutiveMistakeLimit)
  435. // Initialize todo list if provided
  436. if (initialTodos && initialTodos.length > 0) {
  437. this.todoList = initialTodos
  438. }
  439. onCreated?.(this)
  440. if (startTask) {
  441. if (task || images) {
  442. this.startTask(task, images)
  443. } else if (historyItem) {
  444. this.resumeTaskFromHistory()
  445. } else {
  446. throw new Error("Either historyItem or task/images must be provided")
  447. }
  448. }
  449. }
  450. /**
  451. * Initialize the task mode from the provider state.
  452. * This method handles async initialization with proper error handling.
  453. *
  454. * ## Flow
  455. * 1. Attempts to fetch the current mode from provider state
  456. * 2. Sets `_taskMode` to the fetched mode or `defaultModeSlug` if unavailable
  457. * 3. Handles errors gracefully by falling back to default mode
  458. * 4. Logs any initialization errors for debugging
  459. *
  460. * ## Error handling
  461. * - Network failures when fetching provider state
  462. * - Provider not yet initialized
  463. * - Invalid state structure
  464. *
  465. * All errors result in fallback to `defaultModeSlug` to ensure task can proceed.
  466. *
  467. * @private
  468. * @param provider - The ClineProvider instance to fetch state from
  469. * @returns Promise that resolves when initialization is complete
  470. */
  471. private async initializeTaskMode(provider: ClineProvider): Promise<void> {
  472. try {
  473. const state = await provider.getState()
  474. this._taskMode = state?.mode || defaultModeSlug
  475. } catch (error) {
  476. // If there's an error getting state, use the default mode
  477. this._taskMode = defaultModeSlug
  478. // Use the provider's log method for better error visibility
  479. const errorMessage = `Failed to initialize task mode: ${error instanceof Error ? error.message : String(error)}`
  480. provider.log(errorMessage)
  481. }
  482. }
  483. /**
  484. * Sets up a listener for provider profile changes to automatically update the parser state.
  485. * This ensures the XML/native protocol parser stays synchronized with the current model.
  486. *
  487. * @private
  488. * @param provider - The ClineProvider instance to listen to
  489. */
  490. private setupProviderProfileChangeListener(provider: ClineProvider): void {
  491. // Only set up listener if provider has the on method (may not exist in test mocks)
  492. if (typeof provider.on !== "function") {
  493. return
  494. }
  495. this.providerProfileChangeListener = async () => {
  496. try {
  497. const newState = await provider.getState()
  498. if (newState?.apiConfiguration) {
  499. this.updateApiConfiguration(newState.apiConfiguration)
  500. }
  501. } catch (error) {
  502. console.error(
  503. `[Task#${this.taskId}.${this.instanceId}] Failed to update API configuration on profile change:`,
  504. error,
  505. )
  506. }
  507. }
  508. provider.on(RooCodeEventName.ProviderProfileChanged, this.providerProfileChangeListener)
  509. }
  510. /**
  511. * Wait for the task mode to be initialized before proceeding.
  512. * This method ensures that any operations depending on the task mode
  513. * will have access to the correct mode value.
  514. *
  515. * ## When to use
  516. * - Before accessing mode-specific configurations
  517. * - When switching between tasks with different modes
  518. * - Before operations that depend on mode-based permissions
  519. *
  520. * ## Example usage
  521. * ```typescript
  522. * // Wait for mode initialization before mode-dependent operations
  523. * await task.waitForModeInitialization();
  524. * const mode = task.taskMode; // Now safe to access synchronously
  525. *
  526. * // Or use with getTaskMode() for a one-liner
  527. * const mode = await task.getTaskMode(); // Internally waits for initialization
  528. * ```
  529. *
  530. * @returns Promise that resolves when the task mode is initialized
  531. * @public
  532. */
  533. public async waitForModeInitialization(): Promise<void> {
  534. return this.taskModeReady
  535. }
  536. /**
  537. * Get the task mode asynchronously, ensuring it's properly initialized.
  538. * This is the recommended way to access the task mode as it guarantees
  539. * the mode is available before returning.
  540. *
  541. * ## Async behavior
  542. * - Internally waits for `taskModeReady` promise to resolve
  543. * - Returns the initialized mode or `defaultModeSlug` as fallback
  544. * - Safe to call multiple times - subsequent calls return immediately if already initialized
  545. *
  546. * ## Example usage
  547. * ```typescript
  548. * // Safe async access
  549. * const mode = await task.getTaskMode();
  550. * console.log(`Task is running in ${mode} mode`);
  551. *
  552. * // Use in conditional logic
  553. * if (await task.getTaskMode() === 'architect') {
  554. * // Perform architect-specific operations
  555. * }
  556. * ```
  557. *
  558. * @returns Promise resolving to the task mode string
  559. * @public
  560. */
  561. public async getTaskMode(): Promise<string> {
  562. await this.taskModeReady
  563. return this._taskMode || defaultModeSlug
  564. }
  565. /**
  566. * Get the task mode synchronously. This should only be used when you're certain
  567. * that the mode has already been initialized (e.g., after waitForModeInitialization).
  568. *
  569. * ## When to use
  570. * - In synchronous contexts where async/await is not available
  571. * - After explicitly waiting for initialization via `waitForModeInitialization()`
  572. * - In event handlers or callbacks where mode is guaranteed to be initialized
  573. *
  574. * ## Example usage
  575. * ```typescript
  576. * // After ensuring initialization
  577. * await task.waitForModeInitialization();
  578. * const mode = task.taskMode; // Safe synchronous access
  579. *
  580. * // In an event handler after task is started
  581. * task.on('taskStarted', () => {
  582. * console.log(`Task started in ${task.taskMode} mode`); // Safe here
  583. * });
  584. * ```
  585. *
  586. * @throws {Error} If the mode hasn't been initialized yet
  587. * @returns The task mode string
  588. * @public
  589. */
  590. public get taskMode(): string {
  591. if (this._taskMode === undefined) {
  592. throw new Error("Task mode accessed before initialization. Use getTaskMode() or wait for taskModeReady.")
  593. }
  594. return this._taskMode
  595. }
  596. static create(options: TaskOptions): [Task, Promise<void>] {
  597. const instance = new Task({ ...options, startTask: false })
  598. const { images, task, historyItem } = options
  599. let promise
  600. if (images || task) {
  601. promise = instance.startTask(task, images)
  602. } else if (historyItem) {
  603. promise = instance.resumeTaskFromHistory()
  604. } else {
  605. throw new Error("Either historyItem or task/images must be provided")
  606. }
  607. return [instance, promise]
  608. }
  609. // API Messages
  610. private async getSavedApiConversationHistory(): Promise<ApiMessage[]> {
  611. return readApiMessages({ taskId: this.taskId, globalStoragePath: this.globalStoragePath })
  612. }
  613. private async addToApiConversationHistory(message: Anthropic.MessageParam, reasoning?: string) {
  614. // Capture the encrypted_content / thought signatures from the provider (e.g., OpenAI Responses API, Google GenAI) if present.
  615. // We only persist data reported by the current response body.
  616. const handler = this.api as ApiHandler & {
  617. getResponseId?: () => string | undefined
  618. getEncryptedContent?: () => { encrypted_content: string; id?: string } | undefined
  619. getThoughtSignature?: () => string | undefined
  620. getSummary?: () => any[] | undefined
  621. getReasoningDetails?: () => any[] | undefined
  622. }
  623. if (message.role === "assistant") {
  624. const responseId = handler.getResponseId?.()
  625. const reasoningData = handler.getEncryptedContent?.()
  626. const thoughtSignature = handler.getThoughtSignature?.()
  627. const reasoningSummary = handler.getSummary?.()
  628. const reasoningDetails = handler.getReasoningDetails?.()
  629. // Start from the original assistant message
  630. const messageWithTs: any = {
  631. ...message,
  632. ...(responseId ? { id: responseId } : {}),
  633. ts: Date.now(),
  634. }
  635. // Store reasoning_details array if present (for models like Gemini 3)
  636. if (reasoningDetails) {
  637. messageWithTs.reasoning_details = reasoningDetails
  638. }
  639. // Store reasoning: plain text (most providers) or encrypted (OpenAI Native)
  640. // Skip if reasoning_details already contains the reasoning (to avoid duplication)
  641. if (reasoning && !reasoningDetails) {
  642. const reasoningBlock = {
  643. type: "reasoning",
  644. text: reasoning,
  645. summary: reasoningSummary ?? ([] as any[]),
  646. }
  647. if (typeof messageWithTs.content === "string") {
  648. messageWithTs.content = [
  649. reasoningBlock,
  650. { type: "text", text: messageWithTs.content } satisfies Anthropic.Messages.TextBlockParam,
  651. ]
  652. } else if (Array.isArray(messageWithTs.content)) {
  653. messageWithTs.content = [reasoningBlock, ...messageWithTs.content]
  654. } else if (!messageWithTs.content) {
  655. messageWithTs.content = [reasoningBlock]
  656. }
  657. } else if (reasoningData?.encrypted_content) {
  658. // OpenAI Native encrypted reasoning
  659. const reasoningBlock = {
  660. type: "reasoning",
  661. summary: [] as any[],
  662. encrypted_content: reasoningData.encrypted_content,
  663. ...(reasoningData.id ? { id: reasoningData.id } : {}),
  664. }
  665. if (typeof messageWithTs.content === "string") {
  666. messageWithTs.content = [
  667. reasoningBlock,
  668. { type: "text", text: messageWithTs.content } satisfies Anthropic.Messages.TextBlockParam,
  669. ]
  670. } else if (Array.isArray(messageWithTs.content)) {
  671. messageWithTs.content = [reasoningBlock, ...messageWithTs.content]
  672. } else if (!messageWithTs.content) {
  673. messageWithTs.content = [reasoningBlock]
  674. }
  675. }
  676. // If we have a thought signature, append it as a dedicated content block
  677. // so it can be round-tripped in api_history.json and re-sent on subsequent calls.
  678. if (thoughtSignature) {
  679. const thoughtSignatureBlock = {
  680. type: "thoughtSignature",
  681. thoughtSignature,
  682. }
  683. if (typeof messageWithTs.content === "string") {
  684. messageWithTs.content = [
  685. { type: "text", text: messageWithTs.content } satisfies Anthropic.Messages.TextBlockParam,
  686. thoughtSignatureBlock,
  687. ]
  688. } else if (Array.isArray(messageWithTs.content)) {
  689. messageWithTs.content = [...messageWithTs.content, thoughtSignatureBlock]
  690. } else if (!messageWithTs.content) {
  691. messageWithTs.content = [thoughtSignatureBlock]
  692. }
  693. }
  694. this.apiConversationHistory.push(messageWithTs)
  695. } else {
  696. const messageWithTs = { ...message, ts: Date.now() }
  697. this.apiConversationHistory.push(messageWithTs)
  698. }
  699. await this.saveApiConversationHistory()
  700. }
  701. async overwriteApiConversationHistory(newHistory: ApiMessage[]) {
  702. this.apiConversationHistory = newHistory
  703. await this.saveApiConversationHistory()
  704. }
  705. /**
  706. * Flush any pending tool results to the API conversation history.
  707. *
  708. * This is critical for native tool protocol when the task is about to be
  709. * delegated (e.g., via new_task). Before delegation, if other tools were
  710. * called in the same turn before new_task, their tool_result blocks are
  711. * accumulated in `userMessageContent` but haven't been saved to the API
  712. * history yet. If we don't flush them before the parent is disposed,
  713. * the API conversation will be incomplete and cause 400 errors when
  714. * the parent resumes (missing tool_result for tool_use blocks).
  715. *
  716. * NOTE: The assistant message is typically already in history by the time
  717. * tools execute (added in recursivelyMakeClineRequests after streaming completes).
  718. * So we usually only need to flush the pending user message with tool_results.
  719. */
  720. public async flushPendingToolResultsToHistory(): Promise<void> {
  721. // Only flush if there's actually pending content to save
  722. if (this.userMessageContent.length === 0) {
  723. return
  724. }
  725. // Save the user message with tool_result blocks
  726. const userMessage: Anthropic.MessageParam = {
  727. role: "user",
  728. content: this.userMessageContent,
  729. }
  730. const userMessageWithTs = { ...userMessage, ts: Date.now() }
  731. this.apiConversationHistory.push(userMessageWithTs as ApiMessage)
  732. await this.saveApiConversationHistory()
  733. // Clear the pending content since it's now saved
  734. this.userMessageContent = []
  735. }
  736. private async saveApiConversationHistory() {
  737. try {
  738. await saveApiMessages({
  739. messages: this.apiConversationHistory,
  740. taskId: this.taskId,
  741. globalStoragePath: this.globalStoragePath,
  742. })
  743. } catch (error) {
  744. // In the off chance this fails, we don't want to stop the task.
  745. console.error("Failed to save API conversation history:", error)
  746. }
  747. }
  748. // Cline Messages
  749. private async getSavedClineMessages(): Promise<ClineMessage[]> {
  750. return readTaskMessages({ taskId: this.taskId, globalStoragePath: this.globalStoragePath })
  751. }
  752. private async addToClineMessages(message: ClineMessage) {
  753. this.clineMessages.push(message)
  754. const provider = this.providerRef.deref()
  755. await provider?.postStateToWebview()
  756. this.emit(RooCodeEventName.Message, { action: "created", message })
  757. await this.saveClineMessages()
  758. const shouldCaptureMessage = message.partial !== true && CloudService.isEnabled()
  759. if (shouldCaptureMessage) {
  760. CloudService.instance.captureEvent({
  761. event: TelemetryEventName.TASK_MESSAGE,
  762. properties: { taskId: this.taskId, message },
  763. })
  764. // Track that this message has been synced to cloud
  765. this.cloudSyncedMessageTimestamps.add(message.ts)
  766. }
  767. }
  768. public async overwriteClineMessages(newMessages: ClineMessage[]) {
  769. this.clineMessages = newMessages
  770. restoreTodoListForTask(this)
  771. await this.saveClineMessages()
  772. // When overwriting messages (e.g., during task resume), repopulate the cloud sync tracking Set
  773. // with timestamps from all non-partial messages to prevent re-syncing previously synced messages
  774. this.cloudSyncedMessageTimestamps.clear()
  775. for (const msg of newMessages) {
  776. if (msg.partial !== true) {
  777. this.cloudSyncedMessageTimestamps.add(msg.ts)
  778. }
  779. }
  780. }
  781. private async updateClineMessage(message: ClineMessage) {
  782. const provider = this.providerRef.deref()
  783. await provider?.postMessageToWebview({ type: "messageUpdated", clineMessage: message })
  784. this.emit(RooCodeEventName.Message, { action: "updated", message })
  785. // Check if we should sync to cloud and haven't already synced this message
  786. const shouldCaptureMessage = message.partial !== true && CloudService.isEnabled()
  787. const hasNotBeenSynced = !this.cloudSyncedMessageTimestamps.has(message.ts)
  788. if (shouldCaptureMessage && hasNotBeenSynced) {
  789. CloudService.instance.captureEvent({
  790. event: TelemetryEventName.TASK_MESSAGE,
  791. properties: { taskId: this.taskId, message },
  792. })
  793. // Track that this message has been synced to cloud
  794. this.cloudSyncedMessageTimestamps.add(message.ts)
  795. }
  796. }
  797. private async saveClineMessages() {
  798. try {
  799. await saveTaskMessages({
  800. messages: this.clineMessages,
  801. taskId: this.taskId,
  802. globalStoragePath: this.globalStoragePath,
  803. })
  804. const { historyItem, tokenUsage } = await taskMetadata({
  805. taskId: this.taskId,
  806. rootTaskId: this.rootTaskId,
  807. parentTaskId: this.parentTaskId,
  808. taskNumber: this.taskNumber,
  809. messages: this.clineMessages,
  810. globalStoragePath: this.globalStoragePath,
  811. workspace: this.cwd,
  812. mode: this._taskMode || defaultModeSlug, // Use the task's own mode, not the current provider mode.
  813. initialStatus: this.initialStatus,
  814. })
  815. if (hasTokenUsageChanged(tokenUsage, this.tokenUsageSnapshot)) {
  816. this.emit(RooCodeEventName.TaskTokenUsageUpdated, this.taskId, tokenUsage)
  817. this.tokenUsageSnapshot = undefined
  818. this.tokenUsageSnapshotAt = undefined
  819. }
  820. await this.providerRef.deref()?.updateTaskHistory(historyItem)
  821. } catch (error) {
  822. console.error("Failed to save Roo messages:", error)
  823. }
  824. }
  825. private findMessageByTimestamp(ts: number): ClineMessage | undefined {
  826. for (let i = this.clineMessages.length - 1; i >= 0; i--) {
  827. if (this.clineMessages[i].ts === ts) {
  828. return this.clineMessages[i]
  829. }
  830. }
  831. return undefined
  832. }
  833. // Note that `partial` has three valid states true (partial message),
  834. // false (completion of partial message), undefined (individual complete
  835. // message).
  836. async ask(
  837. type: ClineAsk,
  838. text?: string,
  839. partial?: boolean,
  840. progressStatus?: ToolProgressStatus,
  841. isProtected?: boolean,
  842. ): Promise<{ response: ClineAskResponse; text?: string; images?: string[] }> {
  843. // If this Cline instance was aborted by the provider, then the only
  844. // thing keeping us alive is a promise still running in the background,
  845. // in which case we don't want to send its result to the webview as it
  846. // is attached to a new instance of Cline now. So we can safely ignore
  847. // the result of any active promises, and this class will be
  848. // deallocated. (Although we set Cline = undefined in provider, that
  849. // simply removes the reference to this instance, but the instance is
  850. // still alive until this promise resolves or rejects.)
  851. if (this.abort) {
  852. throw new Error(`[RooCode#ask] task ${this.taskId}.${this.instanceId} aborted`)
  853. }
  854. let askTs: number
  855. if (partial !== undefined) {
  856. const lastMessage = this.clineMessages.at(-1)
  857. const isUpdatingPreviousPartial =
  858. lastMessage && lastMessage.partial && lastMessage.type === "ask" && lastMessage.ask === type
  859. if (partial) {
  860. if (isUpdatingPreviousPartial) {
  861. // Existing partial message, so update it.
  862. lastMessage.text = text
  863. lastMessage.partial = partial
  864. lastMessage.progressStatus = progressStatus
  865. lastMessage.isProtected = isProtected
  866. // TODO: Be more efficient about saving and posting only new
  867. // data or one whole message at a time so ignore partial for
  868. // saves, and only post parts of partial message instead of
  869. // whole array in new listener.
  870. this.updateClineMessage(lastMessage)
  871. // console.log("Task#ask: current ask promise was ignored (#1)")
  872. throw new AskIgnoredError("updating existing partial")
  873. } else {
  874. // This is a new partial message, so add it with partial
  875. // state.
  876. askTs = Date.now()
  877. this.lastMessageTs = askTs
  878. console.log(`Task#ask: new partial ask -> ${type} @ ${askTs}`)
  879. await this.addToClineMessages({ ts: askTs, type: "ask", ask: type, text, partial, isProtected })
  880. // console.log("Task#ask: current ask promise was ignored (#2)")
  881. throw new AskIgnoredError("new partial")
  882. }
  883. } else {
  884. if (isUpdatingPreviousPartial) {
  885. // This is the complete version of a previously partial
  886. // message, so replace the partial with the complete version.
  887. this.askResponse = undefined
  888. this.askResponseText = undefined
  889. this.askResponseImages = undefined
  890. // Bug for the history books:
  891. // In the webview we use the ts as the chatrow key for the
  892. // virtuoso list. Since we would update this ts right at the
  893. // end of streaming, it would cause the view to flicker. The
  894. // key prop has to be stable otherwise react has trouble
  895. // reconciling items between renders, causing unmounting and
  896. // remounting of components (flickering).
  897. // The lesson here is if you see flickering when rendering
  898. // lists, it's likely because the key prop is not stable.
  899. // So in this case we must make sure that the message ts is
  900. // never altered after first setting it.
  901. askTs = lastMessage.ts
  902. console.log(`Task#ask: updating previous partial ask -> ${type} @ ${askTs}`)
  903. this.lastMessageTs = askTs
  904. lastMessage.text = text
  905. lastMessage.partial = false
  906. lastMessage.progressStatus = progressStatus
  907. lastMessage.isProtected = isProtected
  908. await this.saveClineMessages()
  909. this.updateClineMessage(lastMessage)
  910. } else {
  911. // This is a new and complete message, so add it like normal.
  912. this.askResponse = undefined
  913. this.askResponseText = undefined
  914. this.askResponseImages = undefined
  915. askTs = Date.now()
  916. console.log(`Task#ask: new complete ask -> ${type} @ ${askTs}`)
  917. this.lastMessageTs = askTs
  918. await this.addToClineMessages({ ts: askTs, type: "ask", ask: type, text, isProtected })
  919. }
  920. }
  921. } else {
  922. // This is a new non-partial message, so add it like normal.
  923. this.askResponse = undefined
  924. this.askResponseText = undefined
  925. this.askResponseImages = undefined
  926. askTs = Date.now()
  927. console.log(`Task#ask: new complete ask -> ${type} @ ${askTs}`)
  928. this.lastMessageTs = askTs
  929. await this.addToClineMessages({ ts: askTs, type: "ask", ask: type, text, isProtected })
  930. }
  931. let timeouts: NodeJS.Timeout[] = []
  932. // Automatically approve if the ask according to the user's settings.
  933. const provider = this.providerRef.deref()
  934. const state = provider ? await provider.getState() : undefined
  935. const approval = await checkAutoApproval({ state, ask: type, text, isProtected })
  936. if (approval.decision === "approve") {
  937. this.approveAsk()
  938. } else if (approval.decision === "deny") {
  939. this.denyAsk()
  940. } else if (approval.decision === "timeout") {
  941. timeouts.push(
  942. setTimeout(() => {
  943. const { askResponse, text, images } = approval.fn()
  944. this.handleWebviewAskResponse(askResponse, text, images)
  945. }, approval.timeout),
  946. )
  947. }
  948. // The state is mutable if the message is complete and the task will
  949. // block (via the `pWaitFor`).
  950. const isBlocking = !(this.askResponse !== undefined || this.lastMessageTs !== askTs)
  951. const isMessageQueued = !this.messageQueueService.isEmpty()
  952. const isStatusMutable = !partial && isBlocking && !isMessageQueued && approval.decision === "ask"
  953. if (isBlocking) {
  954. console.log(`Task#ask will block -> type: ${type}`)
  955. }
  956. if (isStatusMutable) {
  957. console.log(`Task#ask: status is mutable -> type: ${type}`)
  958. const statusMutationTimeout = 2_000
  959. if (isInteractiveAsk(type)) {
  960. timeouts.push(
  961. setTimeout(() => {
  962. const message = this.findMessageByTimestamp(askTs)
  963. if (message) {
  964. this.interactiveAsk = message
  965. this.emit(RooCodeEventName.TaskInteractive, this.taskId)
  966. provider?.postMessageToWebview({ type: "interactionRequired" })
  967. }
  968. }, statusMutationTimeout),
  969. )
  970. } else if (isResumableAsk(type)) {
  971. timeouts.push(
  972. setTimeout(() => {
  973. const message = this.findMessageByTimestamp(askTs)
  974. if (message) {
  975. this.resumableAsk = message
  976. this.emit(RooCodeEventName.TaskResumable, this.taskId)
  977. }
  978. }, statusMutationTimeout),
  979. )
  980. } else if (isIdleAsk(type)) {
  981. timeouts.push(
  982. setTimeout(() => {
  983. const message = this.findMessageByTimestamp(askTs)
  984. if (message) {
  985. this.idleAsk = message
  986. this.emit(RooCodeEventName.TaskIdle, this.taskId)
  987. }
  988. }, statusMutationTimeout),
  989. )
  990. }
  991. } else if (isMessageQueued) {
  992. console.log(`Task#ask: will process message queue -> type: ${type}`)
  993. const message = this.messageQueueService.dequeueMessage()
  994. if (message) {
  995. // Check if this is a tool approval ask that needs to be handled.
  996. if (
  997. type === "tool" ||
  998. type === "command" ||
  999. type === "browser_action_launch" ||
  1000. type === "use_mcp_server"
  1001. ) {
  1002. // For tool approvals, we need to approve first, then send
  1003. // the message if there's text/images.
  1004. this.handleWebviewAskResponse("yesButtonClicked", message.text, message.images)
  1005. } else {
  1006. // For other ask types (like followup or command_output), fulfill the ask
  1007. // directly.
  1008. this.handleWebviewAskResponse("messageResponse", message.text, message.images)
  1009. }
  1010. }
  1011. }
  1012. // Wait for askResponse to be set
  1013. await pWaitFor(() => this.askResponse !== undefined || this.lastMessageTs !== askTs, { interval: 100 })
  1014. if (this.lastMessageTs !== askTs) {
  1015. // Could happen if we send multiple asks in a row i.e. with
  1016. // command_output. It's important that when we know an ask could
  1017. // fail, it is handled gracefully.
  1018. console.log("Task#ask: current ask promise was ignored")
  1019. throw new AskIgnoredError("superseded")
  1020. }
  1021. const result = { response: this.askResponse!, text: this.askResponseText, images: this.askResponseImages }
  1022. this.askResponse = undefined
  1023. this.askResponseText = undefined
  1024. this.askResponseImages = undefined
  1025. // Cancel the timeouts if they are still running.
  1026. timeouts.forEach((timeout) => clearTimeout(timeout))
  1027. // Switch back to an active state.
  1028. if (this.idleAsk || this.resumableAsk || this.interactiveAsk) {
  1029. this.idleAsk = undefined
  1030. this.resumableAsk = undefined
  1031. this.interactiveAsk = undefined
  1032. this.emit(RooCodeEventName.TaskActive, this.taskId)
  1033. }
  1034. this.emit(RooCodeEventName.TaskAskResponded)
  1035. return result
  1036. }
  1037. handleWebviewAskResponse(askResponse: ClineAskResponse, text?: string, images?: string[]) {
  1038. this.askResponse = askResponse
  1039. this.askResponseText = text
  1040. this.askResponseImages = images
  1041. // Create a checkpoint whenever the user sends a message.
  1042. // Use allowEmpty=true to ensure a checkpoint is recorded even if there are no file changes.
  1043. // Suppress the checkpoint_saved chat row for this particular checkpoint to keep the timeline clean.
  1044. if (askResponse === "messageResponse") {
  1045. void this.checkpointSave(false, true)
  1046. }
  1047. // Mark the last follow-up question as answered
  1048. if (askResponse === "messageResponse" || askResponse === "yesButtonClicked") {
  1049. // Find the last unanswered follow-up message using findLastIndex
  1050. const lastFollowUpIndex = findLastIndex(
  1051. this.clineMessages,
  1052. (msg) => msg.type === "ask" && msg.ask === "followup" && !msg.isAnswered,
  1053. )
  1054. if (lastFollowUpIndex !== -1) {
  1055. // Mark this follow-up as answered
  1056. this.clineMessages[lastFollowUpIndex].isAnswered = true
  1057. // Save the updated messages
  1058. this.saveClineMessages().catch((error) => {
  1059. console.error("Failed to save answered follow-up state:", error)
  1060. })
  1061. }
  1062. }
  1063. }
  1064. public approveAsk({ text, images }: { text?: string; images?: string[] } = {}) {
  1065. this.handleWebviewAskResponse("yesButtonClicked", text, images)
  1066. }
  1067. public denyAsk({ text, images }: { text?: string; images?: string[] } = {}) {
  1068. this.handleWebviewAskResponse("noButtonClicked", text, images)
  1069. }
  1070. /**
  1071. * Updates the API configuration and reinitializes the parser based on the new tool protocol.
  1072. * This should be called when switching between models/profiles with different tool protocols
  1073. * to prevent the parser from being left in an inconsistent state.
  1074. *
  1075. * @param newApiConfiguration - The new API configuration to use
  1076. */
  1077. public updateApiConfiguration(newApiConfiguration: ProviderSettings): void {
  1078. // Update the configuration and rebuild the API handler
  1079. this.apiConfiguration = newApiConfiguration
  1080. this.api = buildApiHandler(newApiConfiguration)
  1081. // Determine what the tool protocol should be
  1082. const modelInfo = this.api.getModel().info
  1083. const protocol = resolveToolProtocol(this.apiConfiguration, modelInfo)
  1084. const shouldUseXmlParser = protocol === "xml"
  1085. // Ensure parser state matches protocol requirement
  1086. const parserStateCorrect =
  1087. (shouldUseXmlParser && this.assistantMessageParser) || (!shouldUseXmlParser && !this.assistantMessageParser)
  1088. if (parserStateCorrect) {
  1089. return
  1090. }
  1091. // Fix parser state
  1092. if (shouldUseXmlParser && !this.assistantMessageParser) {
  1093. this.assistantMessageParser = new AssistantMessageParser()
  1094. } else if (!shouldUseXmlParser && this.assistantMessageParser) {
  1095. this.assistantMessageParser.reset()
  1096. this.assistantMessageParser = undefined
  1097. }
  1098. }
  1099. public async submitUserMessage(
  1100. text: string,
  1101. images?: string[],
  1102. mode?: string,
  1103. providerProfile?: string,
  1104. ): Promise<void> {
  1105. try {
  1106. text = (text ?? "").trim()
  1107. images = images ?? []
  1108. if (text.length === 0 && images.length === 0) {
  1109. return
  1110. }
  1111. const provider = this.providerRef.deref()
  1112. if (provider) {
  1113. if (mode) {
  1114. await provider.setMode(mode)
  1115. }
  1116. if (providerProfile) {
  1117. await provider.setProviderProfile(providerProfile)
  1118. // Update this task's API configuration to match the new profile
  1119. // This ensures the parser state is synchronized with the selected model
  1120. const newState = await provider.getState()
  1121. if (newState?.apiConfiguration) {
  1122. this.updateApiConfiguration(newState.apiConfiguration)
  1123. }
  1124. }
  1125. this.emit(RooCodeEventName.TaskUserMessage, this.taskId)
  1126. provider.postMessageToWebview({ type: "invoke", invoke: "sendMessage", text, images })
  1127. } else {
  1128. console.error("[Task#submitUserMessage] Provider reference lost")
  1129. }
  1130. } catch (error) {
  1131. console.error("[Task#submitUserMessage] Failed to submit user message:", error)
  1132. }
  1133. }
  1134. async handleTerminalOperation(terminalOperation: "continue" | "abort") {
  1135. if (terminalOperation === "continue") {
  1136. this.terminalProcess?.continue()
  1137. } else if (terminalOperation === "abort") {
  1138. this.terminalProcess?.abort()
  1139. }
  1140. }
  1141. public async condenseContext(): Promise<void> {
  1142. const systemPrompt = await this.getSystemPrompt()
  1143. // Get condensing configuration
  1144. const state = await this.providerRef.deref()?.getState()
  1145. // These properties may not exist in the state type yet, but are used for condensing configuration
  1146. const customCondensingPrompt = state?.customCondensingPrompt
  1147. const condensingApiConfigId = state?.condensingApiConfigId
  1148. const listApiConfigMeta = state?.listApiConfigMeta
  1149. // Determine API handler to use
  1150. let condensingApiHandler: ApiHandler | undefined
  1151. if (condensingApiConfigId && listApiConfigMeta && Array.isArray(listApiConfigMeta)) {
  1152. // Find matching config by ID
  1153. const matchingConfig = listApiConfigMeta.find((config) => config.id === condensingApiConfigId)
  1154. if (matchingConfig) {
  1155. const profile = await this.providerRef.deref()?.providerSettingsManager.getProfile({
  1156. id: condensingApiConfigId,
  1157. })
  1158. // Ensure profile and apiProvider exist before trying to build handler
  1159. if (profile && profile.apiProvider) {
  1160. condensingApiHandler = buildApiHandler(profile)
  1161. }
  1162. }
  1163. }
  1164. const { contextTokens: prevContextTokens } = this.getTokenUsage()
  1165. // Determine if we're using native tool protocol for proper message handling
  1166. const modelInfo = this.api.getModel().info
  1167. const protocol = resolveToolProtocol(this.apiConfiguration, modelInfo)
  1168. const useNativeTools = isNativeProtocol(protocol)
  1169. const {
  1170. messages,
  1171. summary,
  1172. cost,
  1173. newContextTokens = 0,
  1174. error,
  1175. condenseId,
  1176. } = await summarizeConversation(
  1177. this.apiConversationHistory,
  1178. this.api, // Main API handler (fallback)
  1179. systemPrompt, // Default summarization prompt (fallback)
  1180. this.taskId,
  1181. prevContextTokens,
  1182. false, // manual trigger
  1183. customCondensingPrompt, // User's custom prompt
  1184. condensingApiHandler, // Specific handler for condensing
  1185. useNativeTools, // Pass native tools flag for proper message handling
  1186. )
  1187. if (error) {
  1188. this.say(
  1189. "condense_context_error",
  1190. error,
  1191. undefined /* images */,
  1192. false /* partial */,
  1193. undefined /* checkpoint */,
  1194. undefined /* progressStatus */,
  1195. { isNonInteractive: true } /* options */,
  1196. )
  1197. return
  1198. }
  1199. await this.overwriteApiConversationHistory(messages)
  1200. const contextCondense: ContextCondense = {
  1201. summary,
  1202. cost,
  1203. newContextTokens,
  1204. prevContextTokens,
  1205. condenseId: condenseId!,
  1206. }
  1207. await this.say(
  1208. "condense_context",
  1209. undefined /* text */,
  1210. undefined /* images */,
  1211. false /* partial */,
  1212. undefined /* checkpoint */,
  1213. undefined /* progressStatus */,
  1214. { isNonInteractive: true } /* options */,
  1215. contextCondense,
  1216. )
  1217. // Process any queued messages after condensing completes
  1218. this.processQueuedMessages()
  1219. }
  1220. async say(
  1221. type: ClineSay,
  1222. text?: string,
  1223. images?: string[],
  1224. partial?: boolean,
  1225. checkpoint?: Record<string, unknown>,
  1226. progressStatus?: ToolProgressStatus,
  1227. options: {
  1228. isNonInteractive?: boolean
  1229. } = {},
  1230. contextCondense?: ContextCondense,
  1231. contextTruncation?: ContextTruncation,
  1232. ): Promise<undefined> {
  1233. if (this.abort) {
  1234. throw new Error(`[RooCode#say] task ${this.taskId}.${this.instanceId} aborted`)
  1235. }
  1236. if (partial !== undefined) {
  1237. const lastMessage = this.clineMessages.at(-1)
  1238. const isUpdatingPreviousPartial =
  1239. lastMessage && lastMessage.partial && lastMessage.type === "say" && lastMessage.say === type
  1240. if (partial) {
  1241. if (isUpdatingPreviousPartial) {
  1242. // Existing partial message, so update it.
  1243. lastMessage.text = text
  1244. lastMessage.images = images
  1245. lastMessage.partial = partial
  1246. lastMessage.progressStatus = progressStatus
  1247. this.updateClineMessage(lastMessage)
  1248. } else {
  1249. // This is a new partial message, so add it with partial state.
  1250. const sayTs = Date.now()
  1251. if (!options.isNonInteractive) {
  1252. this.lastMessageTs = sayTs
  1253. }
  1254. await this.addToClineMessages({
  1255. ts: sayTs,
  1256. type: "say",
  1257. say: type,
  1258. text,
  1259. images,
  1260. partial,
  1261. contextCondense,
  1262. contextTruncation,
  1263. })
  1264. }
  1265. } else {
  1266. // New now have a complete version of a previously partial message.
  1267. // This is the complete version of a previously partial
  1268. // message, so replace the partial with the complete version.
  1269. if (isUpdatingPreviousPartial) {
  1270. if (!options.isNonInteractive) {
  1271. this.lastMessageTs = lastMessage.ts
  1272. }
  1273. lastMessage.text = text
  1274. lastMessage.images = images
  1275. lastMessage.partial = false
  1276. lastMessage.progressStatus = progressStatus
  1277. // Instead of streaming partialMessage events, we do a save
  1278. // and post like normal to persist to disk.
  1279. await this.saveClineMessages()
  1280. // More performant than an entire `postStateToWebview`.
  1281. this.updateClineMessage(lastMessage)
  1282. } else {
  1283. // This is a new and complete message, so add it like normal.
  1284. const sayTs = Date.now()
  1285. if (!options.isNonInteractive) {
  1286. this.lastMessageTs = sayTs
  1287. }
  1288. await this.addToClineMessages({
  1289. ts: sayTs,
  1290. type: "say",
  1291. say: type,
  1292. text,
  1293. images,
  1294. contextCondense,
  1295. contextTruncation,
  1296. })
  1297. }
  1298. }
  1299. } else {
  1300. // This is a new non-partial message, so add it like normal.
  1301. const sayTs = Date.now()
  1302. // A "non-interactive" message is a message is one that the user
  1303. // does not need to respond to. We don't want these message types
  1304. // to trigger an update to `lastMessageTs` since they can be created
  1305. // asynchronously and could interrupt a pending ask.
  1306. if (!options.isNonInteractive) {
  1307. this.lastMessageTs = sayTs
  1308. }
  1309. await this.addToClineMessages({
  1310. ts: sayTs,
  1311. type: "say",
  1312. say: type,
  1313. text,
  1314. images,
  1315. checkpoint,
  1316. contextCondense,
  1317. contextTruncation,
  1318. })
  1319. }
  1320. // Broadcast browser session updates to panel when browser-related messages are added
  1321. if (type === "browser_action" || type === "browser_action_result" || type === "browser_session_status") {
  1322. this.broadcastBrowserSessionUpdate()
  1323. }
  1324. }
  1325. async sayAndCreateMissingParamError(toolName: ToolName, paramName: string, relPath?: string) {
  1326. await this.say(
  1327. "error",
  1328. `Roo tried to use ${toolName}${
  1329. relPath ? ` for '${relPath.toPosix()}'` : ""
  1330. } without value for required parameter '${paramName}'. Retrying...`,
  1331. )
  1332. const modelInfo = this.api.getModel().info
  1333. const state = await this.providerRef.deref()?.getState()
  1334. const toolProtocol = resolveToolProtocol(this.apiConfiguration, modelInfo)
  1335. return formatResponse.toolError(formatResponse.missingToolParameterError(paramName, toolProtocol))
  1336. }
  1337. // Lifecycle
  1338. // Start / Resume / Abort / Dispose
  1339. private async startTask(task?: string, images?: string[]): Promise<void> {
  1340. if (this.enableBridge) {
  1341. try {
  1342. await BridgeOrchestrator.subscribeToTask(this)
  1343. } catch (error) {
  1344. console.error(
  1345. `[Task#startTask] BridgeOrchestrator.subscribeToTask() failed: ${error instanceof Error ? error.message : String(error)}`,
  1346. )
  1347. }
  1348. }
  1349. // `conversationHistory` (for API) and `clineMessages` (for webview)
  1350. // need to be in sync.
  1351. // If the extension process were killed, then on restart the
  1352. // `clineMessages` might not be empty, so we need to set it to [] when
  1353. // we create a new Cline client (otherwise webview would show stale
  1354. // messages from previous session).
  1355. this.clineMessages = []
  1356. this.apiConversationHistory = []
  1357. // The todo list is already set in the constructor if initialTodos were provided
  1358. // No need to add any messages - the todoList property is already set
  1359. await this.providerRef.deref()?.postStateToWebview()
  1360. await this.say("text", task, images)
  1361. this.isInitialized = true
  1362. let imageBlocks: Anthropic.ImageBlockParam[] = formatResponse.imageBlocks(images)
  1363. // Task starting
  1364. await this.initiateTaskLoop([
  1365. {
  1366. type: "text",
  1367. text: `<task>\n${task}\n</task>`,
  1368. },
  1369. ...imageBlocks,
  1370. ]).catch((error) => {
  1371. // Swallow loop rejection when the task was intentionally abandoned/aborted
  1372. // during delegation or user cancellation to prevent unhandled rejections.
  1373. if (this.abandoned === true || this.abortReason === "user_cancelled") {
  1374. return
  1375. }
  1376. throw error
  1377. })
  1378. }
  1379. private async resumeTaskFromHistory() {
  1380. if (this.enableBridge) {
  1381. try {
  1382. await BridgeOrchestrator.subscribeToTask(this)
  1383. } catch (error) {
  1384. console.error(
  1385. `[Task#resumeTaskFromHistory] BridgeOrchestrator.subscribeToTask() failed: ${error instanceof Error ? error.message : String(error)}`,
  1386. )
  1387. }
  1388. }
  1389. const modifiedClineMessages = await this.getSavedClineMessages()
  1390. // Remove any resume messages that may have been added before.
  1391. const lastRelevantMessageIndex = findLastIndex(
  1392. modifiedClineMessages,
  1393. (m) => !(m.ask === "resume_task" || m.ask === "resume_completed_task"),
  1394. )
  1395. if (lastRelevantMessageIndex !== -1) {
  1396. modifiedClineMessages.splice(lastRelevantMessageIndex + 1)
  1397. }
  1398. // Remove any trailing reasoning-only UI messages that were not part of the persisted API conversation
  1399. while (modifiedClineMessages.length > 0) {
  1400. const last = modifiedClineMessages[modifiedClineMessages.length - 1]
  1401. if (last.type === "say" && last.say === "reasoning") {
  1402. modifiedClineMessages.pop()
  1403. } else {
  1404. break
  1405. }
  1406. }
  1407. // Since we don't use `api_req_finished` anymore, we need to check if the
  1408. // last `api_req_started` has a cost value, if it doesn't and no
  1409. // cancellation reason to present, then we remove it since it indicates
  1410. // an api request without any partial content streamed.
  1411. const lastApiReqStartedIndex = findLastIndex(
  1412. modifiedClineMessages,
  1413. (m) => m.type === "say" && m.say === "api_req_started",
  1414. )
  1415. if (lastApiReqStartedIndex !== -1) {
  1416. const lastApiReqStarted = modifiedClineMessages[lastApiReqStartedIndex]
  1417. const { cost, cancelReason }: ClineApiReqInfo = JSON.parse(lastApiReqStarted.text || "{}")
  1418. if (cost === undefined && cancelReason === undefined) {
  1419. modifiedClineMessages.splice(lastApiReqStartedIndex, 1)
  1420. }
  1421. }
  1422. await this.overwriteClineMessages(modifiedClineMessages)
  1423. this.clineMessages = await this.getSavedClineMessages()
  1424. // Now present the cline messages to the user and ask if they want to
  1425. // resume (NOTE: we ran into a bug before where the
  1426. // apiConversationHistory wouldn't be initialized when opening a old
  1427. // task, and it was because we were waiting for resume).
  1428. // This is important in case the user deletes messages without resuming
  1429. // the task first.
  1430. this.apiConversationHistory = await this.getSavedApiConversationHistory()
  1431. const lastClineMessage = this.clineMessages
  1432. .slice()
  1433. .reverse()
  1434. .find((m) => !(m.ask === "resume_task" || m.ask === "resume_completed_task")) // Could be multiple resume tasks.
  1435. let askType: ClineAsk
  1436. if (lastClineMessage?.ask === "completion_result") {
  1437. askType = "resume_completed_task"
  1438. } else {
  1439. askType = "resume_task"
  1440. }
  1441. this.isInitialized = true
  1442. const { response, text, images } = await this.ask(askType) // Calls `postStateToWebview`.
  1443. let responseText: string | undefined
  1444. let responseImages: string[] | undefined
  1445. if (response === "messageResponse") {
  1446. await this.say("user_feedback", text, images)
  1447. responseText = text
  1448. responseImages = images
  1449. }
  1450. // Make sure that the api conversation history can be resumed by the API,
  1451. // even if it goes out of sync with cline messages.
  1452. let existingApiConversationHistory: ApiMessage[] = await this.getSavedApiConversationHistory()
  1453. // v2.0 xml tags refactor caveat: since we don't use tools anymore for XML protocol,
  1454. // we need to replace all tool use blocks with a text block since the API disallows
  1455. // conversations with tool uses and no tool schema.
  1456. // For native protocol, we preserve tool_use and tool_result blocks as they're expected by the API.
  1457. const state = await this.providerRef.deref()?.getState()
  1458. const protocol = resolveToolProtocol(this.apiConfiguration, this.api.getModel().info)
  1459. const useNative = isNativeProtocol(protocol)
  1460. // Only convert tool blocks to text for XML protocol
  1461. // For native protocol, the API expects proper tool_use/tool_result structure
  1462. if (!useNative) {
  1463. const conversationWithoutToolBlocks = existingApiConversationHistory.map((message) => {
  1464. if (Array.isArray(message.content)) {
  1465. const newContent = message.content.map((block) => {
  1466. if (block.type === "tool_use") {
  1467. // Format tool invocation based on protocol
  1468. const params = block.input as Record<string, any>
  1469. const formattedText = formatToolInvocation(block.name, params, protocol)
  1470. return {
  1471. type: "text",
  1472. text: formattedText,
  1473. } as Anthropic.Messages.TextBlockParam
  1474. } else if (block.type === "tool_result") {
  1475. // Convert block.content to text block array, removing images
  1476. const contentAsTextBlocks = Array.isArray(block.content)
  1477. ? block.content.filter((item) => item.type === "text")
  1478. : [{ type: "text", text: block.content }]
  1479. const textContent = contentAsTextBlocks.map((item) => item.text).join("\n\n")
  1480. const toolName = findToolName(block.tool_use_id, existingApiConversationHistory)
  1481. return {
  1482. type: "text",
  1483. text: `[${toolName} Result]\n\n${textContent}`,
  1484. } as Anthropic.Messages.TextBlockParam
  1485. }
  1486. return block
  1487. })
  1488. return { ...message, content: newContent }
  1489. }
  1490. return message
  1491. })
  1492. existingApiConversationHistory = conversationWithoutToolBlocks
  1493. }
  1494. // FIXME: remove tool use blocks altogether
  1495. // 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
  1496. // if there's no tool use and only a text block, then we can just add a user message
  1497. // (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)
  1498. // 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'
  1499. let modifiedOldUserContent: Anthropic.Messages.ContentBlockParam[] // either the last message if its user message, or the user message before the last (assistant) message
  1500. let modifiedApiConversationHistory: ApiMessage[] // need to remove the last user message to replace with new modified user message
  1501. if (existingApiConversationHistory.length > 0) {
  1502. const lastMessage = existingApiConversationHistory[existingApiConversationHistory.length - 1]
  1503. if (lastMessage.role === "assistant") {
  1504. const content = Array.isArray(lastMessage.content)
  1505. ? lastMessage.content
  1506. : [{ type: "text", text: lastMessage.content }]
  1507. const hasToolUse = content.some((block) => block.type === "tool_use")
  1508. if (hasToolUse) {
  1509. const toolUseBlocks = content.filter(
  1510. (block) => block.type === "tool_use",
  1511. ) as Anthropic.Messages.ToolUseBlock[]
  1512. const toolResponses: Anthropic.ToolResultBlockParam[] = toolUseBlocks.map((block) => ({
  1513. type: "tool_result",
  1514. tool_use_id: block.id,
  1515. content: "Task was interrupted before this tool call could be completed.",
  1516. }))
  1517. modifiedApiConversationHistory = [...existingApiConversationHistory] // no changes
  1518. modifiedOldUserContent = [...toolResponses]
  1519. } else {
  1520. modifiedApiConversationHistory = [...existingApiConversationHistory]
  1521. modifiedOldUserContent = []
  1522. }
  1523. } else if (lastMessage.role === "user") {
  1524. const previousAssistantMessage: ApiMessage | undefined =
  1525. existingApiConversationHistory[existingApiConversationHistory.length - 2]
  1526. const existingUserContent: Anthropic.Messages.ContentBlockParam[] = Array.isArray(lastMessage.content)
  1527. ? lastMessage.content
  1528. : [{ type: "text", text: lastMessage.content }]
  1529. if (previousAssistantMessage && previousAssistantMessage.role === "assistant") {
  1530. const assistantContent = Array.isArray(previousAssistantMessage.content)
  1531. ? previousAssistantMessage.content
  1532. : [{ type: "text", text: previousAssistantMessage.content }]
  1533. const toolUseBlocks = assistantContent.filter(
  1534. (block) => block.type === "tool_use",
  1535. ) as Anthropic.Messages.ToolUseBlock[]
  1536. if (toolUseBlocks.length > 0) {
  1537. const existingToolResults = existingUserContent.filter(
  1538. (block) => block.type === "tool_result",
  1539. ) as Anthropic.ToolResultBlockParam[]
  1540. const missingToolResponses: Anthropic.ToolResultBlockParam[] = toolUseBlocks
  1541. .filter(
  1542. (toolUse) => !existingToolResults.some((result) => result.tool_use_id === toolUse.id),
  1543. )
  1544. .map((toolUse) => ({
  1545. type: "tool_result",
  1546. tool_use_id: toolUse.id,
  1547. content: "Task was interrupted before this tool call could be completed.",
  1548. }))
  1549. modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1) // removes the last user message
  1550. modifiedOldUserContent = [...existingUserContent, ...missingToolResponses]
  1551. } else {
  1552. modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1)
  1553. modifiedOldUserContent = [...existingUserContent]
  1554. }
  1555. } else {
  1556. modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1)
  1557. modifiedOldUserContent = [...existingUserContent]
  1558. }
  1559. } else {
  1560. throw new Error("Unexpected: Last message is not a user or assistant message")
  1561. }
  1562. } else {
  1563. throw new Error("Unexpected: No existing API conversation history")
  1564. }
  1565. let newUserContent: Anthropic.Messages.ContentBlockParam[] = [...modifiedOldUserContent]
  1566. const agoText = ((): string => {
  1567. const timestamp = lastClineMessage?.ts ?? Date.now()
  1568. const now = Date.now()
  1569. const diff = now - timestamp
  1570. const minutes = Math.floor(diff / 60000)
  1571. const hours = Math.floor(minutes / 60)
  1572. const days = Math.floor(hours / 24)
  1573. if (days > 0) {
  1574. return `${days} day${days > 1 ? "s" : ""} ago`
  1575. }
  1576. if (hours > 0) {
  1577. return `${hours} hour${hours > 1 ? "s" : ""} ago`
  1578. }
  1579. if (minutes > 0) {
  1580. return `${minutes} minute${minutes > 1 ? "s" : ""} ago`
  1581. }
  1582. return "just now"
  1583. })()
  1584. if (responseText) {
  1585. newUserContent.push({
  1586. type: "text",
  1587. text: `\n\nNew instructions for task continuation:\n<user_message>\n${responseText}\n</user_message>`,
  1588. })
  1589. }
  1590. if (responseImages && responseImages.length > 0) {
  1591. newUserContent.push(...formatResponse.imageBlocks(responseImages))
  1592. }
  1593. // Ensure we have at least some content to send to the API.
  1594. // If newUserContent is empty, add a minimal resumption message.
  1595. if (newUserContent.length === 0) {
  1596. newUserContent.push({
  1597. type: "text",
  1598. text: "[TASK RESUMPTION] Resuming task...",
  1599. })
  1600. }
  1601. await this.overwriteApiConversationHistory(modifiedApiConversationHistory)
  1602. // Task resuming from history item.
  1603. await this.initiateTaskLoop(newUserContent)
  1604. }
  1605. /**
  1606. * Cancels the current HTTP request if one is in progress.
  1607. * This immediately aborts the underlying stream rather than waiting for the next chunk.
  1608. */
  1609. public cancelCurrentRequest(): void {
  1610. if (this.currentRequestAbortController) {
  1611. console.log(`[Task#${this.taskId}.${this.instanceId}] Aborting current HTTP request`)
  1612. this.currentRequestAbortController.abort()
  1613. this.currentRequestAbortController = undefined
  1614. }
  1615. }
  1616. public async abortTask(isAbandoned = false) {
  1617. // Aborting task
  1618. // Will stop any autonomously running promises.
  1619. if (isAbandoned) {
  1620. this.abandoned = true
  1621. }
  1622. this.abort = true
  1623. this.emit(RooCodeEventName.TaskAborted)
  1624. try {
  1625. this.dispose() // Call the centralized dispose method
  1626. } catch (error) {
  1627. console.error(`Error during task ${this.taskId}.${this.instanceId} disposal:`, error)
  1628. // Don't rethrow - we want abort to always succeed
  1629. }
  1630. // Save the countdown message in the automatic retry or other content.
  1631. try {
  1632. // Save the countdown message in the automatic retry or other content.
  1633. await this.saveClineMessages()
  1634. } catch (error) {
  1635. console.error(`Error saving messages during abort for task ${this.taskId}.${this.instanceId}:`, error)
  1636. }
  1637. }
  1638. public dispose(): void {
  1639. console.log(`[Task#dispose] disposing task ${this.taskId}.${this.instanceId}`)
  1640. // Cancel any in-progress HTTP request
  1641. try {
  1642. this.cancelCurrentRequest()
  1643. } catch (error) {
  1644. console.error("Error cancelling current request:", error)
  1645. }
  1646. // Remove provider profile change listener
  1647. try {
  1648. if (this.providerProfileChangeListener) {
  1649. const provider = this.providerRef.deref()
  1650. if (provider) {
  1651. provider.off(RooCodeEventName.ProviderProfileChanged, this.providerProfileChangeListener)
  1652. }
  1653. this.providerProfileChangeListener = undefined
  1654. }
  1655. } catch (error) {
  1656. console.error("Error removing provider profile change listener:", error)
  1657. }
  1658. // Dispose message queue and remove event listeners.
  1659. try {
  1660. if (this.messageQueueStateChangedHandler) {
  1661. this.messageQueueService.removeListener("stateChanged", this.messageQueueStateChangedHandler)
  1662. this.messageQueueStateChangedHandler = undefined
  1663. }
  1664. this.messageQueueService.dispose()
  1665. } catch (error) {
  1666. console.error("Error disposing message queue:", error)
  1667. }
  1668. // Remove all event listeners to prevent memory leaks.
  1669. try {
  1670. this.removeAllListeners()
  1671. } catch (error) {
  1672. console.error("Error removing event listeners:", error)
  1673. }
  1674. if (this.enableBridge) {
  1675. BridgeOrchestrator.getInstance()
  1676. ?.unsubscribeFromTask(this.taskId)
  1677. .catch((error) =>
  1678. console.error(
  1679. `[Task#dispose] BridgeOrchestrator#unsubscribeFromTask() failed: ${error instanceof Error ? error.message : String(error)}`,
  1680. ),
  1681. )
  1682. }
  1683. // Release any terminals associated with this task.
  1684. try {
  1685. // Release any terminals associated with this task.
  1686. TerminalRegistry.releaseTerminalsForTask(this.taskId)
  1687. } catch (error) {
  1688. console.error("Error releasing terminals:", error)
  1689. }
  1690. try {
  1691. this.urlContentFetcher.closeBrowser()
  1692. } catch (error) {
  1693. console.error("Error closing URL content fetcher browser:", error)
  1694. }
  1695. try {
  1696. this.browserSession.closeBrowser()
  1697. } catch (error) {
  1698. console.error("Error closing browser session:", error)
  1699. }
  1700. // Also close the Browser Session panel when the task is disposed
  1701. try {
  1702. const provider = this.providerRef.deref()
  1703. if (provider) {
  1704. const { BrowserSessionPanelManager } = require("../webview/BrowserSessionPanelManager")
  1705. BrowserSessionPanelManager.getInstance(provider).dispose()
  1706. }
  1707. } catch (error) {
  1708. console.error("Error closing browser session panel:", error)
  1709. }
  1710. try {
  1711. if (this.rooIgnoreController) {
  1712. this.rooIgnoreController.dispose()
  1713. this.rooIgnoreController = undefined
  1714. }
  1715. } catch (error) {
  1716. console.error("Error disposing RooIgnoreController:", error)
  1717. // This is the critical one for the leak fix.
  1718. }
  1719. try {
  1720. this.fileContextTracker.dispose()
  1721. } catch (error) {
  1722. console.error("Error disposing file context tracker:", error)
  1723. }
  1724. try {
  1725. // If we're not streaming then `abortStream` won't be called.
  1726. if (this.isStreaming && this.diffViewProvider.isEditing) {
  1727. this.diffViewProvider.revertChanges().catch(console.error)
  1728. }
  1729. } catch (error) {
  1730. console.error("Error reverting diff changes:", error)
  1731. }
  1732. }
  1733. // Subtasks
  1734. // Spawn / Wait / Complete
  1735. public async startSubtask(message: string, initialTodos: TodoItem[], mode: string) {
  1736. const provider = this.providerRef.deref()
  1737. if (!provider) {
  1738. throw new Error("Provider not available")
  1739. }
  1740. const child = await (provider as any).delegateParentAndOpenChild({
  1741. parentTaskId: this.taskId,
  1742. message,
  1743. initialTodos,
  1744. mode,
  1745. })
  1746. return child
  1747. }
  1748. /**
  1749. * Resume parent task after delegation completion without showing resume ask.
  1750. * Used in metadata-driven subtask flow.
  1751. *
  1752. * This method:
  1753. * - Clears any pending ask states
  1754. * - Resets abort and streaming flags
  1755. * - Ensures next API call includes full context
  1756. * - Immediately continues task loop without user interaction
  1757. */
  1758. public async resumeAfterDelegation(): Promise<void> {
  1759. // Clear any ask states that might have been set during history load
  1760. this.idleAsk = undefined
  1761. this.resumableAsk = undefined
  1762. this.interactiveAsk = undefined
  1763. // Reset abort and streaming state to ensure clean continuation
  1764. this.abort = false
  1765. this.abandoned = false
  1766. this.abortReason = undefined
  1767. this.didFinishAbortingStream = false
  1768. this.isStreaming = false
  1769. this.isWaitingForFirstChunk = false
  1770. // Ensure next API call includes full context after delegation
  1771. this.skipPrevResponseIdOnce = true
  1772. // Mark as initialized and active
  1773. this.isInitialized = true
  1774. this.emit(RooCodeEventName.TaskActive, this.taskId)
  1775. // Load conversation history if not already loaded
  1776. if (this.apiConversationHistory.length === 0) {
  1777. this.apiConversationHistory = await this.getSavedApiConversationHistory()
  1778. }
  1779. // Add environment details to the existing last user message (which contains the tool_result)
  1780. // This avoids creating a new user message which would cause consecutive user messages
  1781. const environmentDetails = await getEnvironmentDetails(this, true)
  1782. let lastUserMsgIndex = -1
  1783. for (let i = this.apiConversationHistory.length - 1; i >= 0; i--) {
  1784. if (this.apiConversationHistory[i].role === "user") {
  1785. lastUserMsgIndex = i
  1786. break
  1787. }
  1788. }
  1789. if (lastUserMsgIndex >= 0) {
  1790. const lastUserMsg = this.apiConversationHistory[lastUserMsgIndex]
  1791. if (Array.isArray(lastUserMsg.content)) {
  1792. // Remove any existing environment_details blocks before adding fresh ones
  1793. const contentWithoutEnvDetails = lastUserMsg.content.filter(
  1794. (block: Anthropic.Messages.ContentBlockParam) => {
  1795. if (block.type === "text" && typeof block.text === "string") {
  1796. const isEnvironmentDetailsBlock =
  1797. block.text.trim().startsWith("<environment_details>") &&
  1798. block.text.trim().endsWith("</environment_details>")
  1799. return !isEnvironmentDetailsBlock
  1800. }
  1801. return true
  1802. },
  1803. )
  1804. // Add fresh environment details
  1805. lastUserMsg.content = [...contentWithoutEnvDetails, { type: "text" as const, text: environmentDetails }]
  1806. }
  1807. }
  1808. // Save the updated history
  1809. await this.saveApiConversationHistory()
  1810. // Continue task loop - pass empty array to signal no new user content needed
  1811. // The initiateTaskLoop will handle this by skipping user message addition
  1812. await this.initiateTaskLoop([])
  1813. }
  1814. // Task Loop
  1815. private async initiateTaskLoop(userContent: Anthropic.Messages.ContentBlockParam[]): Promise<void> {
  1816. // Kicks off the checkpoints initialization process in the background.
  1817. getCheckpointService(this)
  1818. let nextUserContent = userContent
  1819. let includeFileDetails = true
  1820. this.emit(RooCodeEventName.TaskStarted)
  1821. while (!this.abort) {
  1822. const didEndLoop = await this.recursivelyMakeClineRequests(nextUserContent, includeFileDetails)
  1823. includeFileDetails = false // We only need file details the first time.
  1824. // The way this agentic loop works is that cline will be given a
  1825. // task that he then calls tools to complete. Unless there's an
  1826. // attempt_completion call, we keep responding back to him with his
  1827. // tool's responses until he either attempt_completion or does not
  1828. // use anymore tools. If he does not use anymore tools, we ask him
  1829. // to consider if he's completed the task and then call
  1830. // attempt_completion, otherwise proceed with completing the task.
  1831. // There is a MAX_REQUESTS_PER_TASK limit to prevent infinite
  1832. // requests, but Cline is prompted to finish the task as efficiently
  1833. // as he can.
  1834. if (didEndLoop) {
  1835. // For now a task never 'completes'. This will only happen if
  1836. // the user hits max requests and denies resetting the count.
  1837. break
  1838. } else {
  1839. const modelInfo = this.api.getModel().info
  1840. const state = await this.providerRef.deref()?.getState()
  1841. const toolProtocol = resolveToolProtocol(this.apiConfiguration, modelInfo)
  1842. nextUserContent = [{ type: "text", text: formatResponse.noToolsUsed(toolProtocol) }]
  1843. this.consecutiveMistakeCount++
  1844. }
  1845. }
  1846. }
  1847. public async recursivelyMakeClineRequests(
  1848. userContent: Anthropic.Messages.ContentBlockParam[],
  1849. includeFileDetails: boolean = false,
  1850. ): Promise<boolean> {
  1851. interface StackItem {
  1852. userContent: Anthropic.Messages.ContentBlockParam[]
  1853. includeFileDetails: boolean
  1854. retryAttempt?: number
  1855. userMessageWasRemoved?: boolean // Track if user message was removed due to empty response
  1856. }
  1857. const stack: StackItem[] = [{ userContent, includeFileDetails, retryAttempt: 0 }]
  1858. while (stack.length > 0) {
  1859. const currentItem = stack.pop()!
  1860. const currentUserContent = currentItem.userContent
  1861. const currentIncludeFileDetails = currentItem.includeFileDetails
  1862. if (this.abort) {
  1863. throw new Error(`[RooCode#recursivelyMakeRooRequests] task ${this.taskId}.${this.instanceId} aborted`)
  1864. }
  1865. if (this.consecutiveMistakeLimit > 0 && this.consecutiveMistakeCount >= this.consecutiveMistakeLimit) {
  1866. const { response, text, images } = await this.ask(
  1867. "mistake_limit_reached",
  1868. t("common:errors.mistake_limit_guidance"),
  1869. )
  1870. if (response === "messageResponse") {
  1871. currentUserContent.push(
  1872. ...[
  1873. { type: "text" as const, text: formatResponse.tooManyMistakes(text) },
  1874. ...formatResponse.imageBlocks(images),
  1875. ],
  1876. )
  1877. await this.say("user_feedback", text, images)
  1878. // Track consecutive mistake errors in telemetry.
  1879. TelemetryService.instance.captureConsecutiveMistakeError(this.taskId)
  1880. }
  1881. this.consecutiveMistakeCount = 0
  1882. }
  1883. // Getting verbose details is an expensive operation, it uses ripgrep to
  1884. // top-down build file structure of project which for large projects can
  1885. // take a few seconds. For the best UX we show a placeholder api_req_started
  1886. // message with a loading spinner as this happens.
  1887. // Determine API protocol based on provider and model
  1888. const modelId = getModelId(this.apiConfiguration)
  1889. const apiProtocol = getApiProtocol(this.apiConfiguration.apiProvider, modelId)
  1890. await this.say(
  1891. "api_req_started",
  1892. JSON.stringify({
  1893. apiProtocol,
  1894. }),
  1895. )
  1896. const {
  1897. showRooIgnoredFiles = false,
  1898. includeDiagnosticMessages = true,
  1899. maxDiagnosticMessages = 50,
  1900. maxReadFileLine = -1,
  1901. } = (await this.providerRef.deref()?.getState()) ?? {}
  1902. const parsedUserContent = await processUserContentMentions({
  1903. userContent: currentUserContent,
  1904. cwd: this.cwd,
  1905. urlContentFetcher: this.urlContentFetcher,
  1906. fileContextTracker: this.fileContextTracker,
  1907. rooIgnoreController: this.rooIgnoreController,
  1908. showRooIgnoredFiles,
  1909. includeDiagnosticMessages,
  1910. maxDiagnosticMessages,
  1911. maxReadFileLine,
  1912. })
  1913. const environmentDetails = await getEnvironmentDetails(this, currentIncludeFileDetails)
  1914. // Remove any existing environment_details blocks before adding fresh ones.
  1915. // This prevents duplicate environment details when resuming tasks with XML tool calls,
  1916. // where the old user message content may already contain environment details from the previous session.
  1917. // We check for both opening and closing tags to ensure we're matching complete environment detail blocks,
  1918. // not just mentions of the tag in regular content.
  1919. const contentWithoutEnvDetails = parsedUserContent.filter((block) => {
  1920. if (block.type === "text" && typeof block.text === "string") {
  1921. // Check if this text block is a complete environment_details block
  1922. // by verifying it starts with the opening tag and ends with the closing tag
  1923. const isEnvironmentDetailsBlock =
  1924. block.text.trim().startsWith("<environment_details>") &&
  1925. block.text.trim().endsWith("</environment_details>")
  1926. return !isEnvironmentDetailsBlock
  1927. }
  1928. return true
  1929. })
  1930. // Add environment details as its own text block, separate from tool
  1931. // results.
  1932. let finalUserContent = [...contentWithoutEnvDetails, { type: "text" as const, text: environmentDetails }]
  1933. // Only add user message to conversation history if:
  1934. // 1. This is the first attempt (retryAttempt === 0), AND
  1935. // 2. The original userContent was not empty (empty signals delegation resume where
  1936. // the user message with tool_result and env details is already in history), OR
  1937. // 3. The message was removed in a previous iteration (userMessageWasRemoved === true)
  1938. // This prevents consecutive user messages while allowing re-add when needed
  1939. const isEmptyUserContent = currentUserContent.length === 0
  1940. const shouldAddUserMessage =
  1941. ((currentItem.retryAttempt ?? 0) === 0 && !isEmptyUserContent) || currentItem.userMessageWasRemoved
  1942. if (shouldAddUserMessage) {
  1943. await this.addToApiConversationHistory({ role: "user", content: finalUserContent })
  1944. TelemetryService.instance.captureConversationMessage(this.taskId, "user")
  1945. }
  1946. // Since we sent off a placeholder api_req_started message to update the
  1947. // webview while waiting to actually start the API request (to load
  1948. // potential details for example), we need to update the text of that
  1949. // message.
  1950. const lastApiReqIndex = findLastIndex(this.clineMessages, (m) => m.say === "api_req_started")
  1951. this.clineMessages[lastApiReqIndex].text = JSON.stringify({
  1952. apiProtocol,
  1953. } satisfies ClineApiReqInfo)
  1954. await this.saveClineMessages()
  1955. await this.providerRef.deref()?.postStateToWebview()
  1956. try {
  1957. let cacheWriteTokens = 0
  1958. let cacheReadTokens = 0
  1959. let inputTokens = 0
  1960. let outputTokens = 0
  1961. let totalCost: number | undefined
  1962. // We can't use `api_req_finished` anymore since it's a unique case
  1963. // where it could come after a streaming message (i.e. in the middle
  1964. // of being updated or executed).
  1965. // Fortunately `api_req_finished` was always parsed out for the GUI
  1966. // anyways, so it remains solely for legacy purposes to keep track
  1967. // of prices in tasks from history (it's worth removing a few months
  1968. // from now).
  1969. const updateApiReqMsg = (cancelReason?: ClineApiReqCancelReason, streamingFailedMessage?: string) => {
  1970. if (lastApiReqIndex < 0 || !this.clineMessages[lastApiReqIndex]) {
  1971. return
  1972. }
  1973. const existingData = JSON.parse(this.clineMessages[lastApiReqIndex].text || "{}")
  1974. // Calculate total tokens and cost using provider-aware function
  1975. const modelId = getModelId(this.apiConfiguration)
  1976. const apiProtocol = getApiProtocol(this.apiConfiguration.apiProvider, modelId)
  1977. const costResult =
  1978. apiProtocol === "anthropic"
  1979. ? calculateApiCostAnthropic(
  1980. streamModelInfo,
  1981. inputTokens,
  1982. outputTokens,
  1983. cacheWriteTokens,
  1984. cacheReadTokens,
  1985. )
  1986. : calculateApiCostOpenAI(
  1987. streamModelInfo,
  1988. inputTokens,
  1989. outputTokens,
  1990. cacheWriteTokens,
  1991. cacheReadTokens,
  1992. )
  1993. this.clineMessages[lastApiReqIndex].text = JSON.stringify({
  1994. ...existingData,
  1995. tokensIn: costResult.totalInputTokens,
  1996. tokensOut: costResult.totalOutputTokens,
  1997. cacheWrites: cacheWriteTokens,
  1998. cacheReads: cacheReadTokens,
  1999. cost: totalCost ?? costResult.totalCost,
  2000. cancelReason,
  2001. streamingFailedMessage,
  2002. } satisfies ClineApiReqInfo)
  2003. }
  2004. const abortStream = async (cancelReason: ClineApiReqCancelReason, streamingFailedMessage?: string) => {
  2005. if (this.diffViewProvider.isEditing) {
  2006. await this.diffViewProvider.revertChanges() // closes diff view
  2007. }
  2008. // if last message is a partial we need to update and save it
  2009. const lastMessage = this.clineMessages.at(-1)
  2010. if (lastMessage && lastMessage.partial) {
  2011. // lastMessage.ts = Date.now() DO NOT update ts since it is used as a key for virtuoso list
  2012. lastMessage.partial = false
  2013. // instead of streaming partialMessage events, we do a save and post like normal to persist to disk
  2014. console.log("updating partial message", lastMessage)
  2015. }
  2016. // Update `api_req_started` to have cancelled and cost, so that
  2017. // we can display the cost of the partial stream and the cancellation reason
  2018. updateApiReqMsg(cancelReason, streamingFailedMessage)
  2019. await this.saveClineMessages()
  2020. // Signals to provider that it can retrieve the saved messages
  2021. // from disk, as abortTask can not be awaited on in nature.
  2022. this.didFinishAbortingStream = true
  2023. }
  2024. // Reset streaming state for each new API request
  2025. this.currentStreamingContentIndex = 0
  2026. this.currentStreamingDidCheckpoint = false
  2027. this.assistantMessageContent = []
  2028. this.didCompleteReadingStream = false
  2029. this.userMessageContent = []
  2030. this.userMessageContentReady = false
  2031. this.didRejectTool = false
  2032. this.didAlreadyUseTool = false
  2033. // Reset tool failure flag for each new assistant turn - this ensures that tool failures
  2034. // only prevent attempt_completion within the same assistant message, not across turns
  2035. // (e.g., if a tool fails, then user sends a message saying "just complete anyway")
  2036. this.didToolFailInCurrentTurn = false
  2037. this.presentAssistantMessageLocked = false
  2038. this.presentAssistantMessageHasPendingUpdates = false
  2039. this.assistantMessageParser?.reset()
  2040. this.streamingToolCallIndices.clear()
  2041. // Clear any leftover streaming tool call state from previous interrupted streams
  2042. NativeToolCallParser.clearAllStreamingToolCalls()
  2043. NativeToolCallParser.clearRawChunkState()
  2044. await this.diffViewProvider.reset()
  2045. // Cache model info once per API request to avoid repeated calls during streaming
  2046. // This is especially important for tools and background usage collection
  2047. this.cachedStreamingModel = this.api.getModel()
  2048. const streamModelInfo = this.cachedStreamingModel.info
  2049. const cachedModelId = this.cachedStreamingModel.id
  2050. const streamProtocol = resolveToolProtocol(this.apiConfiguration, streamModelInfo)
  2051. const shouldUseXmlParser = streamProtocol === "xml"
  2052. // Yields only if the first chunk is successful, otherwise will
  2053. // allow the user to retry the request (most likely due to rate
  2054. // limit error, which gets thrown on the first chunk).
  2055. const stream = this.attemptApiRequest()
  2056. let assistantMessage = ""
  2057. let reasoningMessage = ""
  2058. let pendingGroundingSources: GroundingSource[] = []
  2059. this.isStreaming = true
  2060. try {
  2061. const iterator = stream[Symbol.asyncIterator]()
  2062. // Helper to race iterator.next() with abort signal
  2063. const nextChunkWithAbort = async () => {
  2064. const nextPromise = iterator.next()
  2065. // If we have an abort controller, race it with the next chunk
  2066. if (this.currentRequestAbortController) {
  2067. const abortPromise = new Promise<never>((_, reject) => {
  2068. const signal = this.currentRequestAbortController!.signal
  2069. if (signal.aborted) {
  2070. reject(new Error("Request cancelled by user"))
  2071. } else {
  2072. signal.addEventListener("abort", () => {
  2073. reject(new Error("Request cancelled by user"))
  2074. })
  2075. }
  2076. })
  2077. return await Promise.race([nextPromise, abortPromise])
  2078. }
  2079. // No abort controller, just return the next chunk normally
  2080. return await nextPromise
  2081. }
  2082. let item = await nextChunkWithAbort()
  2083. while (!item.done) {
  2084. const chunk = item.value
  2085. item = await nextChunkWithAbort()
  2086. if (!chunk) {
  2087. // Sometimes chunk is undefined, no idea that can cause
  2088. // it, but this workaround seems to fix it.
  2089. continue
  2090. }
  2091. switch (chunk.type) {
  2092. case "reasoning": {
  2093. reasoningMessage += chunk.text
  2094. // Only apply formatting if the message contains sentence-ending punctuation followed by **
  2095. let formattedReasoning = reasoningMessage
  2096. if (reasoningMessage.includes("**")) {
  2097. // Add line breaks before **Title** patterns that appear after sentence endings
  2098. // This targets section headers like "...end of sentence.**Title Here**"
  2099. // Handles periods, exclamation marks, and question marks
  2100. formattedReasoning = reasoningMessage.replace(
  2101. /([.!?])\*\*([^*\n]+)\*\*/g,
  2102. "$1\n\n**$2**",
  2103. )
  2104. }
  2105. await this.say("reasoning", formattedReasoning, undefined, true)
  2106. break
  2107. }
  2108. case "usage":
  2109. inputTokens += chunk.inputTokens
  2110. outputTokens += chunk.outputTokens
  2111. cacheWriteTokens += chunk.cacheWriteTokens ?? 0
  2112. cacheReadTokens += chunk.cacheReadTokens ?? 0
  2113. totalCost = chunk.totalCost
  2114. break
  2115. case "grounding":
  2116. // Handle grounding sources separately from regular content
  2117. // to prevent state persistence issues - store them separately
  2118. if (chunk.sources && chunk.sources.length > 0) {
  2119. pendingGroundingSources.push(...chunk.sources)
  2120. }
  2121. break
  2122. case "tool_call_partial": {
  2123. // Process raw tool call chunk through NativeToolCallParser
  2124. // which handles tracking, buffering, and emits events
  2125. const events = NativeToolCallParser.processRawChunk({
  2126. index: chunk.index,
  2127. id: chunk.id,
  2128. name: chunk.name,
  2129. arguments: chunk.arguments,
  2130. })
  2131. for (const event of events) {
  2132. if (event.type === "tool_call_start") {
  2133. // Initialize streaming in NativeToolCallParser
  2134. NativeToolCallParser.startStreamingToolCall(event.id, event.name as ToolName)
  2135. // Before adding a new tool, finalize any preceding text block
  2136. // This prevents the text block from blocking tool presentation
  2137. const lastBlock =
  2138. this.assistantMessageContent[this.assistantMessageContent.length - 1]
  2139. if (lastBlock?.type === "text" && lastBlock.partial) {
  2140. lastBlock.partial = false
  2141. }
  2142. // Track the index where this tool will be stored
  2143. const toolUseIndex = this.assistantMessageContent.length
  2144. this.streamingToolCallIndices.set(event.id, toolUseIndex)
  2145. // Create initial partial tool use
  2146. const partialToolUse: ToolUse = {
  2147. type: "tool_use",
  2148. name: event.name as ToolName,
  2149. params: {},
  2150. partial: true,
  2151. }
  2152. // Store the ID for native protocol
  2153. ;(partialToolUse as any).id = event.id
  2154. // Add to content and present
  2155. this.assistantMessageContent.push(partialToolUse)
  2156. this.userMessageContentReady = false
  2157. presentAssistantMessage(this)
  2158. } else if (event.type === "tool_call_delta") {
  2159. // Process chunk using streaming JSON parser
  2160. const partialToolUse = NativeToolCallParser.processStreamingChunk(
  2161. event.id,
  2162. event.delta,
  2163. )
  2164. if (partialToolUse) {
  2165. // Get the index for this tool call
  2166. const toolUseIndex = this.streamingToolCallIndices.get(event.id)
  2167. if (toolUseIndex !== undefined) {
  2168. // Store the ID for native protocol
  2169. ;(partialToolUse as any).id = event.id
  2170. // Update the existing tool use with new partial data
  2171. this.assistantMessageContent[toolUseIndex] = partialToolUse
  2172. // Present updated tool use
  2173. presentAssistantMessage(this)
  2174. }
  2175. }
  2176. } else if (event.type === "tool_call_end") {
  2177. // Finalize the streaming tool call
  2178. const finalToolUse = NativeToolCallParser.finalizeStreamingToolCall(event.id)
  2179. // Get the index for this tool call
  2180. const toolUseIndex = this.streamingToolCallIndices.get(event.id)
  2181. if (finalToolUse) {
  2182. // Store the tool call ID
  2183. ;(finalToolUse as any).id = event.id
  2184. // Get the index and replace partial with final
  2185. if (toolUseIndex !== undefined) {
  2186. this.assistantMessageContent[toolUseIndex] = finalToolUse
  2187. }
  2188. // Clean up tracking
  2189. this.streamingToolCallIndices.delete(event.id)
  2190. // Mark that we have new content to process
  2191. this.userMessageContentReady = false
  2192. // Present the finalized tool call
  2193. presentAssistantMessage(this)
  2194. } else if (toolUseIndex !== undefined) {
  2195. // finalizeStreamingToolCall returned null (malformed JSON or missing args)
  2196. // We still need to mark the tool as non-partial so it gets executed
  2197. // The tool's validation will catch any missing required parameters
  2198. const existingToolUse = this.assistantMessageContent[toolUseIndex]
  2199. if (existingToolUse && existingToolUse.type === "tool_use") {
  2200. existingToolUse.partial = false
  2201. // Ensure it has the ID for native protocol
  2202. ;(existingToolUse as any).id = event.id
  2203. }
  2204. // Clean up tracking
  2205. this.streamingToolCallIndices.delete(event.id)
  2206. // Mark that we have new content to process
  2207. this.userMessageContentReady = false
  2208. // Present the tool call - validation will handle missing params
  2209. presentAssistantMessage(this)
  2210. }
  2211. }
  2212. }
  2213. break
  2214. }
  2215. case "tool_call": {
  2216. // Legacy: Handle complete tool calls (for backward compatibility)
  2217. // Convert native tool call to ToolUse format
  2218. const toolUse = NativeToolCallParser.parseToolCall({
  2219. id: chunk.id,
  2220. name: chunk.name as ToolName,
  2221. arguments: chunk.arguments,
  2222. })
  2223. if (!toolUse) {
  2224. console.error(`Failed to parse tool call for task ${this.taskId}:`, chunk)
  2225. break
  2226. }
  2227. // Store the tool call ID on the ToolUse object for later reference
  2228. // This is needed to create tool_result blocks that reference the correct tool_use_id
  2229. toolUse.id = chunk.id
  2230. // Add the tool use to assistant message content
  2231. this.assistantMessageContent.push(toolUse)
  2232. // Mark that we have new content to process
  2233. this.userMessageContentReady = false
  2234. // Present the tool call to user - presentAssistantMessage will execute
  2235. // tools sequentially and accumulate all results in userMessageContent
  2236. presentAssistantMessage(this)
  2237. break
  2238. }
  2239. case "text": {
  2240. assistantMessage += chunk.text
  2241. // Use the protocol determined at the start of streaming
  2242. // Don't rely solely on parser existence - parser might exist from previous state
  2243. if (shouldUseXmlParser && this.assistantMessageParser) {
  2244. // XML protocol: Parse raw assistant message chunk into content blocks
  2245. const prevLength = this.assistantMessageContent.length
  2246. this.assistantMessageContent = this.assistantMessageParser.processChunk(chunk.text)
  2247. if (this.assistantMessageContent.length > prevLength) {
  2248. // New content we need to present, reset to
  2249. // false in case previous content set this to true.
  2250. this.userMessageContentReady = false
  2251. }
  2252. // Present content to user.
  2253. presentAssistantMessage(this)
  2254. } else {
  2255. // Native protocol: Text chunks are plain text, not XML tool calls
  2256. // Create or update a text content block directly
  2257. const lastBlock =
  2258. this.assistantMessageContent[this.assistantMessageContent.length - 1]
  2259. if (lastBlock?.type === "text" && lastBlock.partial) {
  2260. // Update existing partial text block
  2261. lastBlock.content = assistantMessage
  2262. } else {
  2263. // Create new text block
  2264. this.assistantMessageContent.push({
  2265. type: "text",
  2266. content: assistantMessage,
  2267. partial: true,
  2268. })
  2269. this.userMessageContentReady = false
  2270. }
  2271. // Present content to user
  2272. presentAssistantMessage(this)
  2273. }
  2274. break
  2275. }
  2276. }
  2277. if (this.abort) {
  2278. console.log(`aborting stream, this.abandoned = ${this.abandoned}`)
  2279. if (!this.abandoned) {
  2280. // Only need to gracefully abort if this instance
  2281. // isn't abandoned (sometimes OpenRouter stream
  2282. // hangs, in which case this would affect future
  2283. // instances of Cline).
  2284. await abortStream("user_cancelled")
  2285. }
  2286. break // Aborts the stream.
  2287. }
  2288. if (this.didRejectTool) {
  2289. // `userContent` has a tool rejection, so interrupt the
  2290. // assistant's response to present the user's feedback.
  2291. assistantMessage += "\n\n[Response interrupted by user feedback]"
  2292. // Instead of setting this preemptively, we allow the
  2293. // present iterator to finish and set
  2294. // userMessageContentReady when its ready.
  2295. // this.userMessageContentReady = true
  2296. break
  2297. }
  2298. if (this.didAlreadyUseTool) {
  2299. assistantMessage +=
  2300. "\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.]"
  2301. break
  2302. }
  2303. }
  2304. // Finalize any remaining streaming tool calls that weren't explicitly ended
  2305. // This is critical for MCP tools which need tool_call_end events to be properly
  2306. // converted from ToolUse to McpToolUse via finalizeStreamingToolCall()
  2307. const finalizeEvents = NativeToolCallParser.finalizeRawChunks()
  2308. for (const event of finalizeEvents) {
  2309. if (event.type === "tool_call_end") {
  2310. // Finalize the streaming tool call
  2311. const finalToolUse = NativeToolCallParser.finalizeStreamingToolCall(event.id)
  2312. // Get the index for this tool call
  2313. const toolUseIndex = this.streamingToolCallIndices.get(event.id)
  2314. if (finalToolUse) {
  2315. // Store the tool call ID
  2316. ;(finalToolUse as any).id = event.id
  2317. // Get the index and replace partial with final
  2318. if (toolUseIndex !== undefined) {
  2319. this.assistantMessageContent[toolUseIndex] = finalToolUse
  2320. }
  2321. // Clean up tracking
  2322. this.streamingToolCallIndices.delete(event.id)
  2323. // Mark that we have new content to process
  2324. this.userMessageContentReady = false
  2325. // Present the finalized tool call
  2326. presentAssistantMessage(this)
  2327. } else if (toolUseIndex !== undefined) {
  2328. // finalizeStreamingToolCall returned null (malformed JSON or missing args)
  2329. // We still need to mark the tool as non-partial so it gets executed
  2330. // The tool's validation will catch any missing required parameters
  2331. const existingToolUse = this.assistantMessageContent[toolUseIndex]
  2332. if (existingToolUse && existingToolUse.type === "tool_use") {
  2333. existingToolUse.partial = false
  2334. // Ensure it has the ID for native protocol
  2335. ;(existingToolUse as any).id = event.id
  2336. }
  2337. // Clean up tracking
  2338. this.streamingToolCallIndices.delete(event.id)
  2339. // Mark that we have new content to process
  2340. this.userMessageContentReady = false
  2341. // Present the tool call - validation will handle missing params
  2342. presentAssistantMessage(this)
  2343. }
  2344. }
  2345. }
  2346. // Create a copy of current token values to avoid race conditions
  2347. const currentTokens = {
  2348. input: inputTokens,
  2349. output: outputTokens,
  2350. cacheWrite: cacheWriteTokens,
  2351. cacheRead: cacheReadTokens,
  2352. total: totalCost,
  2353. }
  2354. const drainStreamInBackgroundToFindAllUsage = async (apiReqIndex: number) => {
  2355. const timeoutMs = DEFAULT_USAGE_COLLECTION_TIMEOUT_MS
  2356. const startTime = performance.now()
  2357. const modelId = getModelId(this.apiConfiguration)
  2358. // Local variables to accumulate usage data without affecting the main flow
  2359. let bgInputTokens = currentTokens.input
  2360. let bgOutputTokens = currentTokens.output
  2361. let bgCacheWriteTokens = currentTokens.cacheWrite
  2362. let bgCacheReadTokens = currentTokens.cacheRead
  2363. let bgTotalCost = currentTokens.total
  2364. // Helper function to capture telemetry and update messages
  2365. const captureUsageData = async (
  2366. tokens: {
  2367. input: number
  2368. output: number
  2369. cacheWrite: number
  2370. cacheRead: number
  2371. total?: number
  2372. },
  2373. messageIndex: number = apiReqIndex,
  2374. ) => {
  2375. if (
  2376. tokens.input > 0 ||
  2377. tokens.output > 0 ||
  2378. tokens.cacheWrite > 0 ||
  2379. tokens.cacheRead > 0
  2380. ) {
  2381. // Update the shared variables atomically
  2382. inputTokens = tokens.input
  2383. outputTokens = tokens.output
  2384. cacheWriteTokens = tokens.cacheWrite
  2385. cacheReadTokens = tokens.cacheRead
  2386. totalCost = tokens.total
  2387. // Update the API request message with the latest usage data
  2388. updateApiReqMsg()
  2389. await this.saveClineMessages()
  2390. // Update the specific message in the webview
  2391. const apiReqMessage = this.clineMessages[messageIndex]
  2392. if (apiReqMessage) {
  2393. await this.updateClineMessage(apiReqMessage)
  2394. }
  2395. // Capture telemetry with provider-aware cost calculation
  2396. const modelId = getModelId(this.apiConfiguration)
  2397. const apiProtocol = getApiProtocol(this.apiConfiguration.apiProvider, modelId)
  2398. // Use the appropriate cost function based on the API protocol
  2399. const costResult =
  2400. apiProtocol === "anthropic"
  2401. ? calculateApiCostAnthropic(
  2402. streamModelInfo,
  2403. tokens.input,
  2404. tokens.output,
  2405. tokens.cacheWrite,
  2406. tokens.cacheRead,
  2407. )
  2408. : calculateApiCostOpenAI(
  2409. streamModelInfo,
  2410. tokens.input,
  2411. tokens.output,
  2412. tokens.cacheWrite,
  2413. tokens.cacheRead,
  2414. )
  2415. TelemetryService.instance.captureLlmCompletion(this.taskId, {
  2416. inputTokens: costResult.totalInputTokens,
  2417. outputTokens: costResult.totalOutputTokens,
  2418. cacheWriteTokens: tokens.cacheWrite,
  2419. cacheReadTokens: tokens.cacheRead,
  2420. cost: tokens.total ?? costResult.totalCost,
  2421. })
  2422. }
  2423. }
  2424. try {
  2425. // Continue processing the original stream from where the main loop left off
  2426. let usageFound = false
  2427. let chunkCount = 0
  2428. // Use the same iterator that the main loop was using
  2429. while (!item.done) {
  2430. // Check for timeout
  2431. if (performance.now() - startTime > timeoutMs) {
  2432. console.warn(
  2433. `[Background Usage Collection] Timed out after ${timeoutMs}ms for model: ${modelId}, processed ${chunkCount} chunks`,
  2434. )
  2435. // Clean up the iterator before breaking
  2436. if (iterator.return) {
  2437. await iterator.return(undefined)
  2438. }
  2439. break
  2440. }
  2441. const chunk = item.value
  2442. item = await iterator.next()
  2443. chunkCount++
  2444. if (chunk && chunk.type === "usage") {
  2445. usageFound = true
  2446. bgInputTokens += chunk.inputTokens
  2447. bgOutputTokens += chunk.outputTokens
  2448. bgCacheWriteTokens += chunk.cacheWriteTokens ?? 0
  2449. bgCacheReadTokens += chunk.cacheReadTokens ?? 0
  2450. bgTotalCost = chunk.totalCost
  2451. }
  2452. }
  2453. if (
  2454. usageFound ||
  2455. bgInputTokens > 0 ||
  2456. bgOutputTokens > 0 ||
  2457. bgCacheWriteTokens > 0 ||
  2458. bgCacheReadTokens > 0
  2459. ) {
  2460. // We have usage data either from a usage chunk or accumulated tokens
  2461. await captureUsageData(
  2462. {
  2463. input: bgInputTokens,
  2464. output: bgOutputTokens,
  2465. cacheWrite: bgCacheWriteTokens,
  2466. cacheRead: bgCacheReadTokens,
  2467. total: bgTotalCost,
  2468. },
  2469. lastApiReqIndex,
  2470. )
  2471. } else {
  2472. console.warn(
  2473. `[Background Usage Collection] Suspicious: request ${apiReqIndex} is complete, but no usage info was found. Model: ${modelId}`,
  2474. )
  2475. }
  2476. } catch (error) {
  2477. console.error("Error draining stream for usage data:", error)
  2478. // Still try to capture whatever usage data we have collected so far
  2479. if (
  2480. bgInputTokens > 0 ||
  2481. bgOutputTokens > 0 ||
  2482. bgCacheWriteTokens > 0 ||
  2483. bgCacheReadTokens > 0
  2484. ) {
  2485. await captureUsageData(
  2486. {
  2487. input: bgInputTokens,
  2488. output: bgOutputTokens,
  2489. cacheWrite: bgCacheWriteTokens,
  2490. cacheRead: bgCacheReadTokens,
  2491. total: bgTotalCost,
  2492. },
  2493. lastApiReqIndex,
  2494. )
  2495. }
  2496. }
  2497. }
  2498. // Start the background task and handle any errors
  2499. drainStreamInBackgroundToFindAllUsage(lastApiReqIndex).catch((error) => {
  2500. console.error("Background usage collection failed:", error)
  2501. })
  2502. } catch (error) {
  2503. // Abandoned happens when extension is no longer waiting for the
  2504. // Cline instance to finish aborting (error is thrown here when
  2505. // any function in the for loop throws due to this.abort).
  2506. if (!this.abandoned) {
  2507. // Determine cancellation reason
  2508. const cancelReason: ClineApiReqCancelReason = this.abort ? "user_cancelled" : "streaming_failed"
  2509. const streamingFailedMessage = this.abort
  2510. ? undefined
  2511. : (error.message ?? JSON.stringify(serializeError(error), null, 2))
  2512. // Clean up partial state
  2513. await abortStream(cancelReason, streamingFailedMessage)
  2514. if (this.abort) {
  2515. // User cancelled - abort the entire task
  2516. this.abortReason = cancelReason
  2517. await this.abortTask()
  2518. } else {
  2519. // Stream failed - log the error and retry with the same content
  2520. // The existing rate limiting will prevent rapid retries
  2521. console.error(
  2522. `[Task#${this.taskId}.${this.instanceId}] Stream failed, will retry: ${streamingFailedMessage}`,
  2523. )
  2524. // Apply exponential backoff similar to first-chunk errors when auto-resubmit is enabled
  2525. const stateForBackoff = await this.providerRef.deref()?.getState()
  2526. if (stateForBackoff?.autoApprovalEnabled && stateForBackoff?.alwaysApproveResubmit) {
  2527. await this.backoffAndAnnounce(
  2528. currentItem.retryAttempt ?? 0,
  2529. error,
  2530. streamingFailedMessage,
  2531. )
  2532. // Check if task was aborted during the backoff
  2533. if (this.abort) {
  2534. console.log(
  2535. `[Task#${this.taskId}.${this.instanceId}] Task aborted during mid-stream retry backoff`,
  2536. )
  2537. // Abort the entire task
  2538. this.abortReason = "user_cancelled"
  2539. await this.abortTask()
  2540. break
  2541. }
  2542. }
  2543. // Push the same content back onto the stack to retry, incrementing the retry attempt counter
  2544. stack.push({
  2545. userContent: currentUserContent,
  2546. includeFileDetails: false,
  2547. retryAttempt: (currentItem.retryAttempt ?? 0) + 1,
  2548. })
  2549. // Continue to retry the request
  2550. continue
  2551. }
  2552. }
  2553. } finally {
  2554. this.isStreaming = false
  2555. // Clean up the abort controller when streaming completes
  2556. this.currentRequestAbortController = undefined
  2557. }
  2558. // Need to call here in case the stream was aborted.
  2559. if (this.abort || this.abandoned) {
  2560. throw new Error(
  2561. `[RooCode#recursivelyMakeRooRequests] task ${this.taskId}.${this.instanceId} aborted`,
  2562. )
  2563. }
  2564. this.didCompleteReadingStream = true
  2565. // Set any blocks to be complete to allow `presentAssistantMessage`
  2566. // to finish and set `userMessageContentReady` to true.
  2567. // (Could be a text block that had no subsequent tool uses, or a
  2568. // text block at the very end, or an invalid tool use, etc. Whatever
  2569. // the case, `presentAssistantMessage` relies on these blocks either
  2570. // to be completed or the user to reject a block in order to proceed
  2571. // and eventually set userMessageContentReady to true.)
  2572. const partialBlocks = this.assistantMessageContent.filter((block) => block.partial)
  2573. partialBlocks.forEach((block) => (block.partial = false))
  2574. // Can't just do this b/c a tool could be in the middle of executing.
  2575. // this.assistantMessageContent.forEach((e) => (e.partial = false))
  2576. // Now that the stream is complete, finalize any remaining partial content blocks (XML protocol only)
  2577. // Use the protocol determined at the start of streaming
  2578. if (shouldUseXmlParser && this.assistantMessageParser) {
  2579. this.assistantMessageParser.finalizeContentBlocks()
  2580. const parsedBlocks = this.assistantMessageParser.getContentBlocks()
  2581. // For XML protocol: Use only parsed blocks (includes both text and tool_use parsed from XML)
  2582. this.assistantMessageContent = parsedBlocks
  2583. }
  2584. // Present any partial blocks that were just completed
  2585. // For XML protocol: includes both text and tool_use blocks parsed from the text stream
  2586. // For native protocol: tool_use blocks were already presented during streaming via
  2587. // tool_call_partial events, but we still need to present them if they exist (e.g., malformed)
  2588. if (partialBlocks.length > 0) {
  2589. // If there is content to update then it will complete and
  2590. // update `this.userMessageContentReady` to true, which we
  2591. // `pWaitFor` before making the next request.
  2592. presentAssistantMessage(this)
  2593. }
  2594. // Note: updateApiReqMsg() is now called from within drainStreamInBackgroundToFindAllUsage
  2595. // to ensure usage data is captured even when the stream is interrupted. The background task
  2596. // uses local variables to accumulate usage data before atomically updating the shared state.
  2597. // Complete the reasoning message if it exists
  2598. // We can't use say() here because the reasoning message may not be the last message
  2599. // (other messages like text blocks or tool uses may have been added after it during streaming)
  2600. if (reasoningMessage) {
  2601. const lastReasoningIndex = findLastIndex(
  2602. this.clineMessages,
  2603. (m) => m.type === "say" && m.say === "reasoning",
  2604. )
  2605. if (lastReasoningIndex !== -1 && this.clineMessages[lastReasoningIndex].partial) {
  2606. this.clineMessages[lastReasoningIndex].partial = false
  2607. await this.updateClineMessage(this.clineMessages[lastReasoningIndex])
  2608. }
  2609. }
  2610. await this.saveClineMessages()
  2611. await this.providerRef.deref()?.postStateToWebview()
  2612. // Reset parser after each complete conversation round (XML protocol only)
  2613. this.assistantMessageParser?.reset()
  2614. // Now add to apiConversationHistory.
  2615. // Need to save assistant responses to file before proceeding to
  2616. // tool use since user can exit at any moment and we wouldn't be
  2617. // able to save the assistant's response.
  2618. let didEndLoop = false
  2619. // Check if we have any content to process (text or tool uses)
  2620. const hasTextContent = assistantMessage.length > 0
  2621. const hasToolUses = this.assistantMessageContent.some(
  2622. (block) => block.type === "tool_use" || block.type === "mcp_tool_use",
  2623. )
  2624. if (hasTextContent || hasToolUses) {
  2625. // Display grounding sources to the user if they exist
  2626. if (pendingGroundingSources.length > 0) {
  2627. const citationLinks = pendingGroundingSources.map((source, i) => `[${i + 1}](${source.url})`)
  2628. const sourcesText = `${t("common:gemini.sources")} ${citationLinks.join(", ")}`
  2629. await this.say("text", sourcesText, undefined, false, undefined, undefined, {
  2630. isNonInteractive: true,
  2631. })
  2632. }
  2633. // Build the assistant message content array
  2634. const assistantContent: Array<Anthropic.TextBlockParam | Anthropic.ToolUseBlockParam> = []
  2635. // Add text content if present
  2636. if (assistantMessage) {
  2637. assistantContent.push({
  2638. type: "text" as const,
  2639. text: assistantMessage,
  2640. })
  2641. }
  2642. // Add tool_use blocks with their IDs for native protocol
  2643. // This handles both regular ToolUse and McpToolUse types
  2644. const toolUseBlocks = this.assistantMessageContent.filter(
  2645. (block) => block.type === "tool_use" || block.type === "mcp_tool_use",
  2646. )
  2647. for (const block of toolUseBlocks) {
  2648. if (block.type === "mcp_tool_use") {
  2649. // McpToolUse already has the original tool name (e.g., "mcp_serverName_toolName")
  2650. // The arguments are the raw tool arguments (matching the simplified schema)
  2651. const mcpBlock = block as import("../../shared/tools").McpToolUse
  2652. if (mcpBlock.id) {
  2653. assistantContent.push({
  2654. type: "tool_use" as const,
  2655. id: mcpBlock.id,
  2656. name: mcpBlock.name, // Original dynamic name
  2657. input: mcpBlock.arguments, // Direct tool arguments
  2658. })
  2659. }
  2660. } else {
  2661. // Regular ToolUse
  2662. const toolUse = block as import("../../shared/tools").ToolUse
  2663. const toolCallId = toolUse.id
  2664. if (toolCallId) {
  2665. // nativeArgs is already in the correct API format for all tools
  2666. const input = toolUse.nativeArgs || toolUse.params
  2667. assistantContent.push({
  2668. type: "tool_use" as const,
  2669. id: toolCallId,
  2670. name: toolUse.name,
  2671. input,
  2672. })
  2673. }
  2674. }
  2675. }
  2676. await this.addToApiConversationHistory(
  2677. {
  2678. role: "assistant",
  2679. content: assistantContent,
  2680. },
  2681. reasoningMessage || undefined,
  2682. )
  2683. TelemetryService.instance.captureConversationMessage(this.taskId, "assistant")
  2684. // NOTE: This comment is here for future reference - this was a
  2685. // workaround for `userMessageContent` not getting set to true.
  2686. // It was due to it not recursively calling for partial blocks
  2687. // when `didRejectTool`, so it would get stuck waiting for a
  2688. // partial block to complete before it could continue.
  2689. // In case the content blocks finished it may be the api stream
  2690. // finished after the last parsed content block was executed, so
  2691. // we are able to detect out of bounds and set
  2692. // `userMessageContentReady` to true (note you should not call
  2693. // `presentAssistantMessage` since if the last block i
  2694. // completed it will be presented again).
  2695. // const completeBlocks = this.assistantMessageContent.filter((block) => !block.partial) // If there are any partial blocks after the stream ended we can consider them invalid.
  2696. // if (this.currentStreamingContentIndex >= completeBlocks.length) {
  2697. // this.userMessageContentReady = true
  2698. // }
  2699. await pWaitFor(() => this.userMessageContentReady)
  2700. // If the model did not tool use, then we need to tell it to
  2701. // either use a tool or attempt_completion.
  2702. const didToolUse = this.assistantMessageContent.some(
  2703. (block) => block.type === "tool_use" || block.type === "mcp_tool_use",
  2704. )
  2705. if (!didToolUse) {
  2706. const modelInfo = this.api.getModel().info
  2707. const state = await this.providerRef.deref()?.getState()
  2708. const toolProtocol = resolveToolProtocol(this.apiConfiguration, modelInfo)
  2709. this.userMessageContent.push({ type: "text", text: formatResponse.noToolsUsed(toolProtocol) })
  2710. this.consecutiveMistakeCount++
  2711. }
  2712. // Push to stack if there's content OR if we're paused waiting for a subtask.
  2713. // When paused, we push an empty item so the loop continues to the pause check.
  2714. if (this.userMessageContent.length > 0 || this.isPaused) {
  2715. stack.push({
  2716. userContent: [...this.userMessageContent], // Create a copy to avoid mutation issues
  2717. includeFileDetails: false, // Subsequent iterations don't need file details
  2718. })
  2719. // Add periodic yielding to prevent blocking
  2720. await new Promise((resolve) => setImmediate(resolve))
  2721. }
  2722. // Continue to next iteration instead of setting didEndLoop from recursive call
  2723. continue
  2724. } else {
  2725. // If there's no assistant_responses, that means we got no text
  2726. // or tool_use content blocks from API which we should assume is
  2727. // an error.
  2728. // IMPORTANT: For native tool protocol, we already added the user message to
  2729. // apiConversationHistory at line 1876. Since the assistant failed to respond,
  2730. // we need to remove that message before retrying to avoid having two consecutive
  2731. // user messages (which would cause tool_result validation errors).
  2732. let state = await this.providerRef.deref()?.getState()
  2733. if (
  2734. isNativeProtocol(resolveToolProtocol(this.apiConfiguration, this.api.getModel().info)) &&
  2735. this.apiConversationHistory.length > 0
  2736. ) {
  2737. const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1]
  2738. if (lastMessage.role === "user") {
  2739. // Remove the last user message that we added earlier
  2740. this.apiConversationHistory.pop()
  2741. }
  2742. }
  2743. // Check if we should auto-retry or prompt the user
  2744. // Reuse the state variable from above
  2745. if (state?.autoApprovalEnabled && state?.alwaysApproveResubmit) {
  2746. // Auto-retry with backoff - don't persist failure message when retrying
  2747. const errorMsg =
  2748. "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."
  2749. await this.backoffAndAnnounce(
  2750. currentItem.retryAttempt ?? 0,
  2751. new Error("Empty assistant response"),
  2752. errorMsg,
  2753. )
  2754. // Check if task was aborted during the backoff
  2755. if (this.abort) {
  2756. console.log(
  2757. `[Task#${this.taskId}.${this.instanceId}] Task aborted during empty-assistant retry backoff`,
  2758. )
  2759. break
  2760. }
  2761. // Push the same content back onto the stack to retry, incrementing the retry attempt counter
  2762. // Mark that user message was removed so it gets re-added on retry
  2763. stack.push({
  2764. userContent: currentUserContent,
  2765. includeFileDetails: false,
  2766. retryAttempt: (currentItem.retryAttempt ?? 0) + 1,
  2767. userMessageWasRemoved: true,
  2768. })
  2769. // Continue to retry the request
  2770. continue
  2771. } else {
  2772. // Prompt the user for retry decision
  2773. const { response } = await this.ask(
  2774. "api_req_failed",
  2775. "The model returned no assistant messages. This may indicate an issue with the API or the model's output.",
  2776. )
  2777. if (response === "yesButtonClicked") {
  2778. await this.say("api_req_retried")
  2779. // Push the same content back to retry
  2780. stack.push({
  2781. userContent: currentUserContent,
  2782. includeFileDetails: false,
  2783. retryAttempt: (currentItem.retryAttempt ?? 0) + 1,
  2784. })
  2785. // Continue to retry the request
  2786. continue
  2787. } else {
  2788. // User declined to retry
  2789. // For native protocol, re-add the user message we removed
  2790. // Reuse the state variable from above
  2791. if (
  2792. isNativeProtocol(resolveToolProtocol(this.apiConfiguration, this.api.getModel().info))
  2793. ) {
  2794. await this.addToApiConversationHistory({
  2795. role: "user",
  2796. content: currentUserContent,
  2797. })
  2798. }
  2799. await this.say(
  2800. "error",
  2801. "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.",
  2802. )
  2803. await this.addToApiConversationHistory({
  2804. role: "assistant",
  2805. content: [{ type: "text", text: "Failure: I did not provide a response." }],
  2806. })
  2807. }
  2808. }
  2809. }
  2810. // If we reach here without continuing, return false (will always be false for now)
  2811. return false
  2812. } catch (error) {
  2813. // This should never happen since the only thing that can throw an
  2814. // error is the attemptApiRequest, which is wrapped in a try catch
  2815. // that sends an ask where if noButtonClicked, will clear current
  2816. // task and destroy this instance. However to avoid unhandled
  2817. // promise rejection, we will end this loop which will end execution
  2818. // of this instance (see `startTask`).
  2819. return true // Needs to be true so parent loop knows to end task.
  2820. }
  2821. }
  2822. // If we exit the while loop normally (stack is empty), return false
  2823. return false
  2824. }
  2825. private async getSystemPrompt(): Promise<string> {
  2826. const { mcpEnabled } = (await this.providerRef.deref()?.getState()) ?? {}
  2827. let mcpHub: McpHub | undefined
  2828. if (mcpEnabled ?? true) {
  2829. const provider = this.providerRef.deref()
  2830. if (!provider) {
  2831. throw new Error("Provider reference lost during view transition")
  2832. }
  2833. // Wait for MCP hub initialization through McpServerManager
  2834. mcpHub = await McpServerManager.getInstance(provider.context, provider)
  2835. if (!mcpHub) {
  2836. throw new Error("Failed to get MCP hub from server manager")
  2837. }
  2838. // Wait for MCP servers to be connected before generating system prompt
  2839. await pWaitFor(() => !mcpHub!.isConnecting, { timeout: 10_000 }).catch(() => {
  2840. console.error("MCP servers failed to connect in time")
  2841. })
  2842. }
  2843. const rooIgnoreInstructions = this.rooIgnoreController?.getInstructions()
  2844. const state = await this.providerRef.deref()?.getState()
  2845. const {
  2846. browserViewportSize,
  2847. mode,
  2848. customModes,
  2849. customModePrompts,
  2850. customInstructions,
  2851. experiments,
  2852. enableMcpServerCreation,
  2853. browserToolEnabled,
  2854. language,
  2855. maxConcurrentFileReads,
  2856. maxReadFileLine,
  2857. apiConfiguration,
  2858. } = state ?? {}
  2859. return await (async () => {
  2860. const provider = this.providerRef.deref()
  2861. if (!provider) {
  2862. throw new Error("Provider not available")
  2863. }
  2864. // Align browser tool enablement with generateSystemPrompt: require model image support,
  2865. // mode to include the browser group, and the user setting to be enabled.
  2866. const modeConfig = getModeBySlug(mode ?? defaultModeSlug, customModes)
  2867. const modeSupportsBrowser = modeConfig?.groups.some((group) => getGroupName(group) === "browser") ?? false
  2868. // Check if model supports browser capability (images)
  2869. const modelInfo = this.api.getModel().info
  2870. const modelSupportsBrowser = (modelInfo as any)?.supportsImages === true
  2871. const canUseBrowserTool = modelSupportsBrowser && modeSupportsBrowser && (browserToolEnabled ?? true)
  2872. // Resolve the tool protocol based on profile, model, and provider settings
  2873. const toolProtocol = resolveToolProtocol(apiConfiguration ?? this.apiConfiguration, modelInfo)
  2874. return SYSTEM_PROMPT(
  2875. provider.context,
  2876. this.cwd,
  2877. canUseBrowserTool,
  2878. mcpHub,
  2879. this.diffStrategy,
  2880. browserViewportSize ?? "900x600",
  2881. mode ?? defaultModeSlug,
  2882. customModePrompts,
  2883. customModes,
  2884. customInstructions,
  2885. this.diffEnabled,
  2886. experiments,
  2887. enableMcpServerCreation,
  2888. language,
  2889. rooIgnoreInstructions,
  2890. maxReadFileLine !== -1,
  2891. {
  2892. maxConcurrentFileReads: maxConcurrentFileReads ?? 5,
  2893. todoListEnabled: apiConfiguration?.todoListEnabled ?? true,
  2894. browserToolEnabled: browserToolEnabled ?? true,
  2895. useAgentRules:
  2896. vscode.workspace.getConfiguration(Package.name).get<boolean>("useAgentRules") ?? true,
  2897. newTaskRequireTodos: vscode.workspace
  2898. .getConfiguration(Package.name)
  2899. .get<boolean>("newTaskRequireTodos", false),
  2900. toolProtocol,
  2901. isStealthModel: modelInfo?.isStealthModel,
  2902. },
  2903. undefined, // todoList
  2904. this.api.getModel().id,
  2905. )
  2906. })()
  2907. }
  2908. private getCurrentProfileId(state: any): string {
  2909. return (
  2910. state?.listApiConfigMeta?.find((profile: any) => profile.name === state?.currentApiConfigName)?.id ??
  2911. "default"
  2912. )
  2913. }
  2914. private async handleContextWindowExceededError(): Promise<void> {
  2915. const state = await this.providerRef.deref()?.getState()
  2916. const { profileThresholds = {} } = state ?? {}
  2917. const { contextTokens } = this.getTokenUsage()
  2918. const modelInfo = this.api.getModel().info
  2919. const maxTokens = getModelMaxOutputTokens({
  2920. modelId: this.api.getModel().id,
  2921. model: modelInfo,
  2922. settings: this.apiConfiguration,
  2923. })
  2924. const contextWindow = modelInfo.contextWindow
  2925. // Get the current profile ID using the helper method
  2926. const currentProfileId = this.getCurrentProfileId(state)
  2927. // Log the context window error for debugging
  2928. console.warn(
  2929. `[Task#${this.taskId}] Context window exceeded for model ${this.api.getModel().id}. ` +
  2930. `Current tokens: ${contextTokens}, Context window: ${contextWindow}. ` +
  2931. `Forcing truncation to ${FORCED_CONTEXT_REDUCTION_PERCENT}% of current context.`,
  2932. )
  2933. // Determine if we're using native tool protocol for proper message handling
  2934. const protocol = resolveToolProtocol(this.apiConfiguration, modelInfo)
  2935. const useNativeTools = isNativeProtocol(protocol)
  2936. // Send condenseTaskContextStarted to show in-progress indicator
  2937. await this.providerRef.deref()?.postMessageToWebview({ type: "condenseTaskContextStarted", text: this.taskId })
  2938. // Force aggressive truncation by keeping only 75% of the conversation history
  2939. const truncateResult = await manageContext({
  2940. messages: this.apiConversationHistory,
  2941. totalTokens: contextTokens || 0,
  2942. maxTokens,
  2943. contextWindow,
  2944. apiHandler: this.api,
  2945. autoCondenseContext: true,
  2946. autoCondenseContextPercent: FORCED_CONTEXT_REDUCTION_PERCENT,
  2947. systemPrompt: await this.getSystemPrompt(),
  2948. taskId: this.taskId,
  2949. profileThresholds,
  2950. currentProfileId,
  2951. useNativeTools,
  2952. })
  2953. if (truncateResult.messages !== this.apiConversationHistory) {
  2954. await this.overwriteApiConversationHistory(truncateResult.messages)
  2955. }
  2956. if (truncateResult.summary) {
  2957. const { summary, cost, prevContextTokens, newContextTokens = 0 } = truncateResult
  2958. const contextCondense: ContextCondense = { summary, cost, newContextTokens, prevContextTokens }
  2959. await this.say(
  2960. "condense_context",
  2961. undefined /* text */,
  2962. undefined /* images */,
  2963. false /* partial */,
  2964. undefined /* checkpoint */,
  2965. undefined /* progressStatus */,
  2966. { isNonInteractive: true } /* options */,
  2967. contextCondense,
  2968. )
  2969. } else if (truncateResult.truncationId) {
  2970. // Sliding window truncation occurred (fallback when condensing fails or is disabled)
  2971. const contextTruncation: ContextTruncation = {
  2972. truncationId: truncateResult.truncationId,
  2973. messagesRemoved: truncateResult.messagesRemoved ?? 0,
  2974. prevContextTokens: truncateResult.prevContextTokens,
  2975. newContextTokens: truncateResult.newContextTokensAfterTruncation ?? 0,
  2976. }
  2977. await this.say(
  2978. "sliding_window_truncation",
  2979. undefined /* text */,
  2980. undefined /* images */,
  2981. false /* partial */,
  2982. undefined /* checkpoint */,
  2983. undefined /* progressStatus */,
  2984. { isNonInteractive: true } /* options */,
  2985. undefined /* contextCondense */,
  2986. contextTruncation,
  2987. )
  2988. }
  2989. // Notify webview that context management is complete (removes in-progress spinner)
  2990. await this.providerRef.deref()?.postMessageToWebview({ type: "condenseTaskContextResponse", text: this.taskId })
  2991. }
  2992. public async *attemptApiRequest(retryAttempt: number = 0): ApiStream {
  2993. const state = await this.providerRef.deref()?.getState()
  2994. const {
  2995. apiConfiguration,
  2996. autoApprovalEnabled,
  2997. alwaysApproveResubmit,
  2998. requestDelaySeconds,
  2999. mode,
  3000. autoCondenseContext = true,
  3001. autoCondenseContextPercent = 100,
  3002. profileThresholds = {},
  3003. } = state ?? {}
  3004. // Get condensing configuration for automatic triggers.
  3005. const customCondensingPrompt = state?.customCondensingPrompt
  3006. const condensingApiConfigId = state?.condensingApiConfigId
  3007. const listApiConfigMeta = state?.listApiConfigMeta
  3008. // Determine API handler to use for condensing.
  3009. let condensingApiHandler: ApiHandler | undefined
  3010. if (condensingApiConfigId && listApiConfigMeta && Array.isArray(listApiConfigMeta)) {
  3011. // Find matching config by ID
  3012. const matchingConfig = listApiConfigMeta.find((config) => config.id === condensingApiConfigId)
  3013. if (matchingConfig) {
  3014. const profile = await this.providerRef.deref()?.providerSettingsManager.getProfile({
  3015. id: condensingApiConfigId,
  3016. })
  3017. // Ensure profile and apiProvider exist before trying to build handler.
  3018. if (profile && profile.apiProvider) {
  3019. condensingApiHandler = buildApiHandler(profile)
  3020. }
  3021. }
  3022. }
  3023. let rateLimitDelay = 0
  3024. // Use the shared timestamp so that subtasks respect the same rate-limit
  3025. // window as their parent tasks.
  3026. if (Task.lastGlobalApiRequestTime) {
  3027. const now = performance.now()
  3028. const timeSinceLastRequest = now - Task.lastGlobalApiRequestTime
  3029. const rateLimit = apiConfiguration?.rateLimitSeconds || 0
  3030. rateLimitDelay = Math.ceil(Math.min(rateLimit, Math.max(0, rateLimit * 1000 - timeSinceLastRequest) / 1000))
  3031. }
  3032. // Only show rate limiting message if we're not retrying. If retrying, we'll include the delay there.
  3033. if (rateLimitDelay > 0 && retryAttempt === 0) {
  3034. // Show countdown timer
  3035. for (let i = rateLimitDelay; i > 0; i--) {
  3036. const delayMessage = `Rate limiting for ${i} seconds...`
  3037. await this.say("api_req_retry_delayed", delayMessage, undefined, true)
  3038. await delay(1000)
  3039. }
  3040. }
  3041. // Update last request time before making the request so that subsequent
  3042. // requests — even from new subtasks — will honour the provider's rate-limit.
  3043. Task.lastGlobalApiRequestTime = performance.now()
  3044. const systemPrompt = await this.getSystemPrompt()
  3045. const { contextTokens } = this.getTokenUsage()
  3046. if (contextTokens) {
  3047. const modelInfo = this.api.getModel().info
  3048. const maxTokens = getModelMaxOutputTokens({
  3049. modelId: this.api.getModel().id,
  3050. model: modelInfo,
  3051. settings: this.apiConfiguration,
  3052. })
  3053. const contextWindow = modelInfo.contextWindow
  3054. // Get the current profile ID using the helper method
  3055. const currentProfileId = this.getCurrentProfileId(state)
  3056. // Determine if we're using native tool protocol for proper message handling
  3057. const modelInfoForProtocol = this.api.getModel().info
  3058. const protocol = resolveToolProtocol(this.apiConfiguration, modelInfoForProtocol)
  3059. const useNativeTools = isNativeProtocol(protocol)
  3060. // Check if context management will likely run (threshold check)
  3061. // This allows us to show an in-progress indicator to the user
  3062. // We use the centralized willManageContext helper to avoid duplicating threshold logic
  3063. const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1]
  3064. const lastMessageContent = lastMessage?.content
  3065. let lastMessageTokens = 0
  3066. if (lastMessageContent) {
  3067. lastMessageTokens = Array.isArray(lastMessageContent)
  3068. ? await this.api.countTokens(lastMessageContent)
  3069. : await this.api.countTokens([{ type: "text", text: lastMessageContent as string }])
  3070. }
  3071. const contextManagementWillRun = willManageContext({
  3072. totalTokens: contextTokens,
  3073. contextWindow,
  3074. maxTokens,
  3075. autoCondenseContext,
  3076. autoCondenseContextPercent,
  3077. profileThresholds,
  3078. currentProfileId,
  3079. lastMessageTokens,
  3080. })
  3081. // Send condenseTaskContextStarted BEFORE manageContext to show in-progress indicator
  3082. // This notification must be sent here (not earlier) because the early check uses stale token count
  3083. // (before user message is added to history), which could incorrectly skip showing the indicator
  3084. if (contextManagementWillRun && autoCondenseContext) {
  3085. await this.providerRef
  3086. .deref()
  3087. ?.postMessageToWebview({ type: "condenseTaskContextStarted", text: this.taskId })
  3088. }
  3089. const truncateResult = await manageContext({
  3090. messages: this.apiConversationHistory,
  3091. totalTokens: contextTokens,
  3092. maxTokens,
  3093. contextWindow,
  3094. apiHandler: this.api,
  3095. autoCondenseContext,
  3096. autoCondenseContextPercent,
  3097. systemPrompt,
  3098. taskId: this.taskId,
  3099. customCondensingPrompt,
  3100. condensingApiHandler,
  3101. profileThresholds,
  3102. currentProfileId,
  3103. useNativeTools,
  3104. })
  3105. if (truncateResult.messages !== this.apiConversationHistory) {
  3106. await this.overwriteApiConversationHistory(truncateResult.messages)
  3107. }
  3108. if (truncateResult.error) {
  3109. await this.say("condense_context_error", truncateResult.error)
  3110. } else if (truncateResult.summary) {
  3111. const { summary, cost, prevContextTokens, newContextTokens = 0, condenseId } = truncateResult
  3112. const contextCondense: ContextCondense = {
  3113. summary,
  3114. cost,
  3115. newContextTokens,
  3116. prevContextTokens,
  3117. condenseId,
  3118. }
  3119. await this.say(
  3120. "condense_context",
  3121. undefined /* text */,
  3122. undefined /* images */,
  3123. false /* partial */,
  3124. undefined /* checkpoint */,
  3125. undefined /* progressStatus */,
  3126. { isNonInteractive: true } /* options */,
  3127. contextCondense,
  3128. )
  3129. } else if (truncateResult.truncationId) {
  3130. // Sliding window truncation occurred (fallback when condensing fails or is disabled)
  3131. const contextTruncation: ContextTruncation = {
  3132. truncationId: truncateResult.truncationId,
  3133. messagesRemoved: truncateResult.messagesRemoved ?? 0,
  3134. prevContextTokens: truncateResult.prevContextTokens,
  3135. newContextTokens: truncateResult.newContextTokensAfterTruncation ?? 0,
  3136. }
  3137. await this.say(
  3138. "sliding_window_truncation",
  3139. undefined /* text */,
  3140. undefined /* images */,
  3141. false /* partial */,
  3142. undefined /* checkpoint */,
  3143. undefined /* progressStatus */,
  3144. { isNonInteractive: true } /* options */,
  3145. undefined /* contextCondense */,
  3146. contextTruncation,
  3147. )
  3148. }
  3149. // Notify webview that context management is complete (sets isCondensing = false)
  3150. // This removes the in-progress spinner and allows the completed result to show
  3151. if (contextManagementWillRun && autoCondenseContext) {
  3152. await this.providerRef
  3153. .deref()
  3154. ?.postMessageToWebview({ type: "condenseTaskContextResponse", text: this.taskId })
  3155. }
  3156. }
  3157. // Get the effective API history by filtering out condensed messages
  3158. // This allows non-destructive condensing where messages are tagged but not deleted,
  3159. // enabling accurate rewind operations while still sending condensed history to the API.
  3160. const effectiveHistory = getEffectiveApiHistory(this.apiConversationHistory)
  3161. const messagesSinceLastSummary = getMessagesSinceLastSummary(effectiveHistory)
  3162. const messagesWithoutImages = maybeRemoveImageBlocks(messagesSinceLastSummary, this.api)
  3163. const cleanConversationHistory = this.buildCleanConversationHistory(messagesWithoutImages as ApiMessage[])
  3164. // Check auto-approval limits
  3165. const approvalResult = await this.autoApprovalHandler.checkAutoApprovalLimits(
  3166. state,
  3167. this.combineMessages(this.clineMessages.slice(1)),
  3168. async (type, data) => this.ask(type, data),
  3169. )
  3170. if (!approvalResult.shouldProceed) {
  3171. // User did not approve, task should be aborted
  3172. throw new Error("Auto-approval limit reached and user did not approve continuation")
  3173. }
  3174. // Determine if we should include native tools based on:
  3175. // 1. Tool protocol is set to NATIVE
  3176. // 2. Model supports native tools
  3177. const modelInfo = this.api.getModel().info
  3178. const toolProtocol = resolveToolProtocol(this.apiConfiguration, modelInfo)
  3179. const shouldIncludeTools = toolProtocol === TOOL_PROTOCOL.NATIVE && (modelInfo.supportsNativeTools ?? false)
  3180. // Build complete tools array: native tools + dynamic MCP tools, filtered by mode restrictions
  3181. let allTools: OpenAI.Chat.ChatCompletionTool[] = []
  3182. if (shouldIncludeTools) {
  3183. const provider = this.providerRef.deref()
  3184. if (!provider) {
  3185. throw new Error("Provider reference lost during tool building")
  3186. }
  3187. allTools = await buildNativeToolsArray({
  3188. provider,
  3189. cwd: this.cwd,
  3190. mode,
  3191. customModes: state?.customModes,
  3192. experiments: state?.experiments,
  3193. apiConfiguration,
  3194. maxReadFileLine: state?.maxReadFileLine ?? -1,
  3195. browserToolEnabled: state?.browserToolEnabled ?? true,
  3196. modelInfo,
  3197. diffEnabled: this.diffEnabled,
  3198. })
  3199. }
  3200. // Parallel tool calls are disabled - feature is on hold
  3201. // Previously resolved from experiments.isEnabled(..., EXPERIMENT_IDS.MULTIPLE_NATIVE_TOOL_CALLS)
  3202. const parallelToolCallsEnabled = false
  3203. const metadata: ApiHandlerCreateMessageMetadata = {
  3204. mode: mode,
  3205. taskId: this.taskId,
  3206. suppressPreviousResponseId: this.skipPrevResponseIdOnce,
  3207. // Include tools and tool protocol when using native protocol and model supports it
  3208. ...(shouldIncludeTools
  3209. ? { tools: allTools, tool_choice: "auto", toolProtocol, parallelToolCalls: parallelToolCallsEnabled }
  3210. : {}),
  3211. }
  3212. // Create an AbortController to allow cancelling the request mid-stream
  3213. this.currentRequestAbortController = new AbortController()
  3214. const abortSignal = this.currentRequestAbortController.signal
  3215. // Reset the flag after using it
  3216. this.skipPrevResponseIdOnce = false
  3217. // The provider accepts reasoning items alongside standard messages; cast to the expected parameter type.
  3218. const stream = this.api.createMessage(
  3219. systemPrompt,
  3220. cleanConversationHistory as unknown as Anthropic.Messages.MessageParam[],
  3221. metadata,
  3222. )
  3223. const iterator = stream[Symbol.asyncIterator]()
  3224. // Set up abort handling - when the signal is aborted, clean up the controller reference
  3225. abortSignal.addEventListener("abort", () => {
  3226. console.log(`[Task#${this.taskId}.${this.instanceId}] AbortSignal triggered for current request`)
  3227. this.currentRequestAbortController = undefined
  3228. })
  3229. try {
  3230. // Awaiting first chunk to see if it will throw an error.
  3231. this.isWaitingForFirstChunk = true
  3232. // Race between the first chunk and the abort signal
  3233. const firstChunkPromise = iterator.next()
  3234. const abortPromise = new Promise<never>((_, reject) => {
  3235. if (abortSignal.aborted) {
  3236. reject(new Error("Request cancelled by user"))
  3237. } else {
  3238. abortSignal.addEventListener("abort", () => {
  3239. reject(new Error("Request cancelled by user"))
  3240. })
  3241. }
  3242. })
  3243. const firstChunk = await Promise.race([firstChunkPromise, abortPromise])
  3244. yield firstChunk.value
  3245. this.isWaitingForFirstChunk = false
  3246. } catch (error) {
  3247. this.isWaitingForFirstChunk = false
  3248. this.currentRequestAbortController = undefined
  3249. const isContextWindowExceededError = checkContextWindowExceededError(error)
  3250. // If it's a context window error and we haven't exceeded max retries for this error type
  3251. if (isContextWindowExceededError && retryAttempt < MAX_CONTEXT_WINDOW_RETRIES) {
  3252. console.warn(
  3253. `[Task#${this.taskId}] Context window exceeded for model ${this.api.getModel().id}. ` +
  3254. `Retry attempt ${retryAttempt + 1}/${MAX_CONTEXT_WINDOW_RETRIES}. ` +
  3255. `Attempting automatic truncation...`,
  3256. )
  3257. await this.handleContextWindowExceededError()
  3258. // Retry the request after handling the context window error
  3259. yield* this.attemptApiRequest(retryAttempt + 1)
  3260. return
  3261. }
  3262. // 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.
  3263. if (autoApprovalEnabled && alwaysApproveResubmit) {
  3264. let errorMsg
  3265. if (error.error?.metadata?.raw) {
  3266. errorMsg = JSON.stringify(error.error.metadata.raw, null, 2)
  3267. } else if (error.message) {
  3268. errorMsg = error.message
  3269. } else {
  3270. errorMsg = "Unknown error"
  3271. }
  3272. // Apply shared exponential backoff and countdown UX
  3273. await this.backoffAndAnnounce(retryAttempt, error, errorMsg)
  3274. // CRITICAL: Check if task was aborted during the backoff countdown
  3275. // This prevents infinite loops when users cancel during auto-retry
  3276. // Without this check, the recursive call below would continue even after abort
  3277. if (this.abort) {
  3278. throw new Error(
  3279. `[Task#attemptApiRequest] task ${this.taskId}.${this.instanceId} aborted during retry`,
  3280. )
  3281. }
  3282. // Delegate generator output from the recursive call with
  3283. // incremented retry count.
  3284. yield* this.attemptApiRequest(retryAttempt + 1)
  3285. return
  3286. } else {
  3287. const { response } = await this.ask(
  3288. "api_req_failed",
  3289. error.message ?? JSON.stringify(serializeError(error), null, 2),
  3290. )
  3291. if (response !== "yesButtonClicked") {
  3292. // This will never happen since if noButtonClicked, we will
  3293. // clear current task, aborting this instance.
  3294. throw new Error("API request failed")
  3295. }
  3296. await this.say("api_req_retried")
  3297. // Delegate generator output from the recursive call.
  3298. yield* this.attemptApiRequest()
  3299. return
  3300. }
  3301. }
  3302. // No error, so we can continue to yield all remaining chunks.
  3303. // (Needs to be placed outside of try/catch since it we want caller to
  3304. // handle errors not with api_req_failed as that is reserved for first
  3305. // chunk failures only.)
  3306. // This delegates to another generator or iterable object. In this case,
  3307. // it's saying "yield all remaining values from this iterator". This
  3308. // effectively passes along all subsequent chunks from the original
  3309. // stream.
  3310. yield* iterator
  3311. }
  3312. // Shared exponential backoff for retries (first-chunk and mid-stream)
  3313. private async backoffAndAnnounce(retryAttempt: number, error: any, header?: string): Promise<void> {
  3314. try {
  3315. const state = await this.providerRef.deref()?.getState()
  3316. const baseDelay = state?.requestDelaySeconds || 5
  3317. let exponentialDelay = Math.min(
  3318. Math.ceil(baseDelay * Math.pow(2, retryAttempt)),
  3319. MAX_EXPONENTIAL_BACKOFF_SECONDS,
  3320. )
  3321. // Respect provider rate limit window
  3322. let rateLimitDelay = 0
  3323. const rateLimit = state?.apiConfiguration?.rateLimitSeconds || 0
  3324. if (Task.lastGlobalApiRequestTime && rateLimit > 0) {
  3325. const elapsed = performance.now() - Task.lastGlobalApiRequestTime
  3326. rateLimitDelay = Math.ceil(Math.min(rateLimit, Math.max(0, rateLimit * 1000 - elapsed) / 1000))
  3327. }
  3328. // Prefer RetryInfo on 429 if present
  3329. if (error?.status === 429) {
  3330. const retryInfo = error?.errorDetails?.find(
  3331. (d: any) => d["@type"] === "type.googleapis.com/google.rpc.RetryInfo",
  3332. )
  3333. const match = retryInfo?.retryDelay?.match?.(/^(\d+)s$/)
  3334. if (match) {
  3335. exponentialDelay = Number(match[1]) + 1
  3336. }
  3337. }
  3338. const finalDelay = Math.max(exponentialDelay, rateLimitDelay)
  3339. if (finalDelay <= 0) return
  3340. // Build header text; fall back to error message if none provided
  3341. let headerText
  3342. if (error.status) {
  3343. // This sets the message as just the error code, for which
  3344. // ChatRow knows how to handle and use an i18n'd error string
  3345. // In development, hardcode headerText to an HTTP status code to check it
  3346. headerText = error.status
  3347. } else if (error?.message) {
  3348. headerText = error.message
  3349. } else {
  3350. headerText = "Unknown error"
  3351. }
  3352. headerText = headerText ? `${headerText}\n` : ""
  3353. // Show countdown timer with exponential backoff
  3354. for (let i = finalDelay; i > 0; i--) {
  3355. // Check abort flag during countdown to allow early exit
  3356. if (this.abort) {
  3357. throw new Error(`[Task#${this.taskId}] Aborted during retry countdown`)
  3358. }
  3359. await this.say("api_req_retry_delayed", `${headerText}\n↻ ${i}s...`, undefined, true)
  3360. await delay(1000)
  3361. }
  3362. await this.say("api_req_retry_delayed", headerText, undefined, false)
  3363. } catch (err) {
  3364. console.error("Exponential backoff failed:", err)
  3365. }
  3366. }
  3367. // Checkpoints
  3368. public async checkpointSave(force: boolean = false, suppressMessage: boolean = false) {
  3369. return checkpointSave(this, force, suppressMessage)
  3370. }
  3371. private buildCleanConversationHistory(
  3372. messages: ApiMessage[],
  3373. ): Array<
  3374. Anthropic.Messages.MessageParam | { type: "reasoning"; encrypted_content: string; id?: string; summary?: any[] }
  3375. > {
  3376. type ReasoningItemForRequest = {
  3377. type: "reasoning"
  3378. encrypted_content: string
  3379. id?: string
  3380. summary?: any[]
  3381. }
  3382. const cleanConversationHistory: (Anthropic.Messages.MessageParam | ReasoningItemForRequest)[] = []
  3383. for (const msg of messages) {
  3384. // Standalone reasoning: send encrypted, skip plain text
  3385. if (msg.type === "reasoning") {
  3386. if (msg.encrypted_content) {
  3387. cleanConversationHistory.push({
  3388. type: "reasoning",
  3389. summary: msg.summary,
  3390. encrypted_content: msg.encrypted_content!,
  3391. ...(msg.id ? { id: msg.id } : {}),
  3392. })
  3393. }
  3394. continue
  3395. }
  3396. // Preferred path: assistant message with embedded reasoning as first content block
  3397. if (msg.role === "assistant") {
  3398. const rawContent = msg.content
  3399. const contentArray: Anthropic.Messages.ContentBlockParam[] = Array.isArray(rawContent)
  3400. ? (rawContent as Anthropic.Messages.ContentBlockParam[])
  3401. : rawContent !== undefined
  3402. ? ([
  3403. { type: "text", text: rawContent } satisfies Anthropic.Messages.TextBlockParam,
  3404. ] as Anthropic.Messages.ContentBlockParam[])
  3405. : []
  3406. const [first, ...rest] = contentArray
  3407. // Check if this message has reasoning_details (OpenRouter format for Gemini 3, etc.)
  3408. const msgWithDetails = msg
  3409. if (msgWithDetails.reasoning_details && Array.isArray(msgWithDetails.reasoning_details)) {
  3410. // Build the assistant message with reasoning_details
  3411. let assistantContent: Anthropic.Messages.MessageParam["content"]
  3412. if (contentArray.length === 0) {
  3413. assistantContent = ""
  3414. } else if (contentArray.length === 1 && contentArray[0].type === "text") {
  3415. assistantContent = (contentArray[0] as Anthropic.Messages.TextBlockParam).text
  3416. } else {
  3417. assistantContent = contentArray
  3418. }
  3419. // Create message with reasoning_details property
  3420. cleanConversationHistory.push({
  3421. role: "assistant",
  3422. content: assistantContent,
  3423. reasoning_details: msgWithDetails.reasoning_details,
  3424. } as any)
  3425. continue
  3426. }
  3427. // Embedded reasoning: encrypted (send) or plain text (skip)
  3428. const hasEncryptedReasoning =
  3429. first && (first as any).type === "reasoning" && typeof (first as any).encrypted_content === "string"
  3430. const hasPlainTextReasoning =
  3431. first && (first as any).type === "reasoning" && typeof (first as any).text === "string"
  3432. if (hasEncryptedReasoning) {
  3433. const reasoningBlock = first as any
  3434. // Send as separate reasoning item (OpenAI Native)
  3435. cleanConversationHistory.push({
  3436. type: "reasoning",
  3437. summary: reasoningBlock.summary ?? [],
  3438. encrypted_content: reasoningBlock.encrypted_content,
  3439. ...(reasoningBlock.id ? { id: reasoningBlock.id } : {}),
  3440. })
  3441. // Send assistant message without reasoning
  3442. let assistantContent: Anthropic.Messages.MessageParam["content"]
  3443. if (rest.length === 0) {
  3444. assistantContent = ""
  3445. } else if (rest.length === 1 && rest[0].type === "text") {
  3446. assistantContent = (rest[0] as Anthropic.Messages.TextBlockParam).text
  3447. } else {
  3448. assistantContent = rest
  3449. }
  3450. cleanConversationHistory.push({
  3451. role: "assistant",
  3452. content: assistantContent,
  3453. } satisfies Anthropic.Messages.MessageParam)
  3454. continue
  3455. } else if (hasPlainTextReasoning) {
  3456. // Check if the model's preserveReasoning flag is set
  3457. // If true, include the reasoning block in API requests
  3458. // If false/undefined, strip it out (stored for history only, not sent back to API)
  3459. const shouldPreserveForApi = this.api.getModel().info.preserveReasoning === true
  3460. let assistantContent: Anthropic.Messages.MessageParam["content"]
  3461. if (shouldPreserveForApi) {
  3462. // Include reasoning block in the content sent to API
  3463. assistantContent = contentArray
  3464. } else {
  3465. // Strip reasoning out - stored for history only, not sent back to API
  3466. if (rest.length === 0) {
  3467. assistantContent = ""
  3468. } else if (rest.length === 1 && rest[0].type === "text") {
  3469. assistantContent = (rest[0] as Anthropic.Messages.TextBlockParam).text
  3470. } else {
  3471. assistantContent = rest
  3472. }
  3473. }
  3474. cleanConversationHistory.push({
  3475. role: "assistant",
  3476. content: assistantContent,
  3477. } satisfies Anthropic.Messages.MessageParam)
  3478. continue
  3479. }
  3480. }
  3481. // Default path for regular messages (no embedded reasoning)
  3482. if (msg.role) {
  3483. cleanConversationHistory.push({
  3484. role: msg.role,
  3485. content: msg.content as Anthropic.Messages.ContentBlockParam[] | string,
  3486. })
  3487. }
  3488. }
  3489. return cleanConversationHistory
  3490. }
  3491. public async checkpointRestore(options: CheckpointRestoreOptions) {
  3492. return checkpointRestore(this, options)
  3493. }
  3494. public async checkpointDiff(options: CheckpointDiffOptions) {
  3495. return checkpointDiff(this, options)
  3496. }
  3497. // Metrics
  3498. public combineMessages(messages: ClineMessage[]) {
  3499. return combineApiRequests(combineCommandSequences(messages))
  3500. }
  3501. public getTokenUsage(): TokenUsage {
  3502. return getApiMetrics(this.combineMessages(this.clineMessages.slice(1)))
  3503. }
  3504. public recordToolUsage(toolName: ToolName) {
  3505. if (!this.toolUsage[toolName]) {
  3506. this.toolUsage[toolName] = { attempts: 0, failures: 0 }
  3507. }
  3508. this.toolUsage[toolName].attempts++
  3509. }
  3510. public recordToolError(toolName: ToolName, error?: string) {
  3511. if (!this.toolUsage[toolName]) {
  3512. this.toolUsage[toolName] = { attempts: 0, failures: 0 }
  3513. }
  3514. this.toolUsage[toolName].failures++
  3515. if (error) {
  3516. this.emit(RooCodeEventName.TaskToolFailed, this.taskId, toolName, error)
  3517. }
  3518. }
  3519. // Getters
  3520. public get taskStatus(): TaskStatus {
  3521. if (this.interactiveAsk) {
  3522. return TaskStatus.Interactive
  3523. }
  3524. if (this.resumableAsk) {
  3525. return TaskStatus.Resumable
  3526. }
  3527. if (this.idleAsk) {
  3528. return TaskStatus.Idle
  3529. }
  3530. return TaskStatus.Running
  3531. }
  3532. public get taskAsk(): ClineMessage | undefined {
  3533. return this.idleAsk || this.resumableAsk || this.interactiveAsk
  3534. }
  3535. public get queuedMessages(): QueuedMessage[] {
  3536. return this.messageQueueService.messages
  3537. }
  3538. public get tokenUsage(): TokenUsage | undefined {
  3539. if (this.tokenUsageSnapshot && this.tokenUsageSnapshotAt) {
  3540. return this.tokenUsageSnapshot
  3541. }
  3542. this.tokenUsageSnapshot = this.getTokenUsage()
  3543. this.tokenUsageSnapshotAt = this.clineMessages.at(-1)?.ts
  3544. return this.tokenUsageSnapshot
  3545. }
  3546. public get cwd() {
  3547. return this.workspacePath
  3548. }
  3549. /**
  3550. * Provides convenient access to high-level message operations.
  3551. * Uses lazy initialization - the MessageManager is only created when first accessed.
  3552. * Subsequent accesses return the same cached instance.
  3553. *
  3554. * ## Important: Single Coordination Point
  3555. *
  3556. * **All MessageManager operations must go through this getter** rather than
  3557. * instantiating `new MessageManager(task)` directly. This ensures:
  3558. * - A single shared instance for consistent behavior
  3559. * - Centralized coordination of all rewind/message operations
  3560. * - Ability to add internal state or instrumentation in the future
  3561. *
  3562. * @example
  3563. * ```typescript
  3564. * // Correct: Use the getter
  3565. * await task.messageManager.rewindToTimestamp(ts)
  3566. *
  3567. * // Incorrect: Do NOT create new instances directly
  3568. * // const manager = new MessageManager(task) // Don't do this!
  3569. * ```
  3570. */
  3571. get messageManager(): MessageManager {
  3572. if (!this._messageManager) {
  3573. this._messageManager = new MessageManager(this)
  3574. }
  3575. return this._messageManager
  3576. }
  3577. /**
  3578. * Broadcast browser session updates to the browser panel (if open)
  3579. */
  3580. private broadcastBrowserSessionUpdate(): void {
  3581. const provider = this.providerRef.deref()
  3582. if (!provider) {
  3583. return
  3584. }
  3585. try {
  3586. const { BrowserSessionPanelManager } = require("../webview/BrowserSessionPanelManager")
  3587. const panelManager = BrowserSessionPanelManager.getInstance(provider)
  3588. // Get browser session messages
  3589. const browserSessionStartIndex = this.clineMessages.findIndex(
  3590. (m) =>
  3591. m.ask === "browser_action_launch" ||
  3592. (m.say === "browser_session_status" && m.text?.includes("opened")),
  3593. )
  3594. const browserSessionMessages =
  3595. browserSessionStartIndex !== -1 ? this.clineMessages.slice(browserSessionStartIndex) : []
  3596. const isBrowserSessionActive = this.browserSession?.isSessionActive() ?? false
  3597. // Update the panel asynchronously
  3598. panelManager.updateBrowserSession(browserSessionMessages, isBrowserSessionActive).catch((error: Error) => {
  3599. console.error("Failed to broadcast browser session update:", error)
  3600. })
  3601. } catch (error) {
  3602. // Silently fail if panel manager is not available
  3603. console.debug("Browser panel not available for update:", error)
  3604. }
  3605. }
  3606. /**
  3607. * Process any queued messages by dequeuing and submitting them.
  3608. * This ensures that queued user messages are sent when appropriate,
  3609. * preventing them from getting stuck in the queue.
  3610. *
  3611. * @param context - Context string for logging (e.g., the calling tool name)
  3612. */
  3613. public processQueuedMessages(): void {
  3614. try {
  3615. if (!this.messageQueueService.isEmpty()) {
  3616. const queued = this.messageQueueService.dequeueMessage()
  3617. if (queued) {
  3618. setTimeout(() => {
  3619. this.submitUserMessage(queued.text, queued.images).catch((err) =>
  3620. console.error(`[Task] Failed to submit queued message:`, err),
  3621. )
  3622. }, 0)
  3623. }
  3624. }
  3625. } catch (e) {
  3626. console.error(`[Task] Queue processing error:`, e)
  3627. }
  3628. }
  3629. }