Task.ts 171 KB

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