Task.ts 174 KB

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