Task.ts 149 KB

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