Task.ts 171 KB

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