forked from RooCodeInc/Roo-Code
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCline.ts
More file actions
2614 lines (2251 loc) · 94.7 KB
/
Cline.ts
File metadata and controls
2614 lines (2251 loc) · 94.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as path from "path"
import os from "os"
import crypto from "crypto"
import EventEmitter from "events"
import { Anthropic } from "@anthropic-ai/sdk"
import cloneDeep from "clone-deep"
import delay from "delay"
import pWaitFor from "p-wait-for"
import { serializeError } from "serialize-error"
import * as vscode from "vscode"
// schemas
import { TokenUsage, ToolUsage, ToolName, ModelInfo, CreatorModeConfig } from "../schemas"
// api
import { ApiHandler, buildApiHandler } from "../api"
import { ApiStream } from "../api/transform/stream"
// shared
import { ApiConfiguration } from "../shared/api"
import { findLastIndex } from "../shared/array"
import { combineApiRequests } from "../shared/combineApiRequests"
import { combineCommandSequences } from "../shared/combineCommandSequences"
import {
ClineApiReqCancelReason,
ClineApiReqInfo,
ClineAsk,
ClineMessage,
ClineSay,
ToolProgressStatus,
} from "../shared/ExtensionMessage"
import { getApiMetrics } from "../shared/getApiMetrics"
import { HistoryItem } from "../shared/HistoryItem"
import { ClineAskResponse } from "../shared/WebviewMessage"
import { defaultModeSlug, getModeBySlug, getFullModeDetails, isToolAllowedForMode } from "../shared/modes"
import { EXPERIMENT_IDS, experiments as Experiments, ExperimentId } from "../shared/experiments"
import { formatLanguage } from "../shared/language"
import { ToolParamName, ToolResponse, DiffStrategy } from "../shared/tools"
// services
import { UrlContentFetcher } from "../services/browser/UrlContentFetcher"
import { listFiles } from "../services/glob/list-files"
import { BrowserSession } from "../services/browser/BrowserSession"
import { McpHub } from "../services/mcp/McpHub"
import { McpServerManager } from "../services/mcp/McpServerManager"
import { telemetryService } from "../services/telemetry/TelemetryService"
import { CheckpointServiceOptions, RepoPerTaskCheckpointService } from "../services/checkpoints"
// integrations
import { DIFF_VIEW_URI_SCHEME, DiffViewProvider } from "../integrations/editor/DiffViewProvider"
import { findToolName, formatContentBlockToMarkdown } from "../integrations/misc/export-markdown"
import { RooTerminalProcess } from "../integrations/terminal/types"
import { Terminal } from "../integrations/terminal/Terminal"
import { TerminalRegistry } from "../integrations/terminal/TerminalRegistry"
// utils
import { calculateApiCostAnthropic } from "../utils/cost"
import { arePathsEqual, getWorkspacePath } from "../utils/path"
// tools
import { fetchInstructionsTool } from "./tools/fetchInstructionsTool"
import { listFilesTool } from "./tools/listFilesTool"
import { readFileTool } from "./tools/readFileTool"
import { writeToFileTool } from "./tools/writeToFileTool"
import { applyDiffTool } from "./tools/applyDiffTool"
import { insertContentTool } from "./tools/insertContentTool"
import { searchAndReplaceTool } from "./tools/searchAndReplaceTool"
import { listCodeDefinitionNamesTool } from "./tools/listCodeDefinitionNamesTool"
import { searchFilesTool } from "./tools/searchFilesTool"
import { browserActionTool } from "./tools/browserActionTool"
import { executeCommandTool } from "./tools/executeCommandTool"
import { useMcpToolTool } from "./tools/useMcpToolTool"
import { accessMcpResourceTool } from "./tools/accessMcpResourceTool"
import { askFollowupQuestionTool } from "./tools/askFollowupQuestionTool"
import { switchModeTool } from "./tools/switchModeTool"
import { attemptCompletionTool } from "./tools/attemptCompletionTool"
import { newTaskTool } from "./tools/newTaskTool"
import { readMemories } from "../utils/memory"
// prompts
import { formatResponse } from "./prompts/responses"
import { SYSTEM_PROMPT } from "./prompts/system"
// ... everything else
import { parseMentions } from "./mentions"
import { FileContextTracker } from "./context-tracking/FileContextTracker"
import { RooIgnoreController } from "./ignore/RooIgnoreController"
import { type AssistantMessageContent, parseAssistantMessage } from "./assistant-message"
import { truncateConversationIfNeeded } from "./sliding-window"
import { ClineProvider } from "./webview/ClineProvider"
import { validateToolUse } from "./mode-validator"
import { MultiSearchReplaceDiffStrategy } from "./diff/strategies/multi-search-replace"
import { readApiMessages, saveApiMessages, readTaskMessages, saveTaskMessages, taskMetadata } from "./task-persistence"
import { pearaiDeployWebappTool } from "./tools/pearaiDeployWebappTool"
type UserContent = Array<Anthropic.Messages.ContentBlockParam>
export type ClineEvents = {
message: [{ action: "created" | "updated"; message: ClineMessage }]
taskStarted: []
taskModeSwitched: [taskId: string, mode: string]
taskPaused: []
taskUnpaused: []
taskAskResponded: []
taskAborted: []
taskSpawned: [taskId: string]
taskCompleted: [taskId: string, tokenUsage: TokenUsage, toolUsage: ToolUsage]
taskTokenUsageUpdated: [taskId: string, tokenUsage: TokenUsage]
taskToolFailed: [taskId: string, tool: ToolName, error: string]
}
export type ClineOptions = {
provider: ClineProvider
apiConfiguration: ApiConfiguration
customInstructions?: string
enableDiff?: boolean
enableCheckpoints?: boolean
fuzzyMatchThreshold?: number
consecutiveMistakeLimit?: number
task?: string
images?: string[]
historyItem?: HistoryItem
experiments?: Record<string, boolean>
startTask?: boolean
rootTask?: Cline
parentTask?: Cline
taskNumber?: number
onCreated?: (cline: Cline) => void
pearaiModels?: Record<string, ModelInfo>
creatorModeConfig?: CreatorModeConfig
}
export class Cline extends EventEmitter<ClineEvents> {
readonly taskId: string
readonly instanceId: string
readonly rootTask: Cline | undefined = undefined
readonly parentTask: Cline | undefined = undefined
readonly taskNumber: number
readonly workspacePath: string
isPaused: boolean = false
pausedModeSlug: string = defaultModeSlug
private pauseInterval: NodeJS.Timeout | undefined
public creatorModeConfig: CreatorModeConfig
readonly apiConfiguration: ApiConfiguration
api: ApiHandler
private promptCacheKey: string
rooIgnoreController?: RooIgnoreController
private fileContextTracker: FileContextTracker
private urlContentFetcher: UrlContentFetcher
browserSession: BrowserSession
didEditFile: boolean = false
customInstructions?: string
diffStrategy?: DiffStrategy
diffEnabled: boolean = false
fuzzyMatchThreshold: number
apiConversationHistory: (Anthropic.MessageParam & { ts?: number })[] = []
clineMessages: ClineMessage[] = []
private askResponse?: ClineAskResponse
private askResponseText?: string
private askResponseImages?: string[]
private lastMessageTs?: number
// Not private since it needs to be accessible by tools.
consecutiveMistakeCount: number = 0
consecutiveMistakeLimit: number
consecutiveMistakeCountForApplyDiff: Map<string, number> = new Map()
// Not private since it needs to be accessible by tools.
providerRef: WeakRef<ClineProvider>
private readonly globalStoragePath: string
private abort: boolean = false
didFinishAbortingStream = false
abandoned = false
diffViewProvider: DiffViewProvider
private lastApiRequestTime?: number
isInitialized = false
// checkpoints
private enableCheckpoints: boolean
private checkpointService?: RepoPerTaskCheckpointService
private checkpointServiceInitializing = false
// streaming
isWaitingForFirstChunk = false
isStreaming = false
private currentStreamingContentIndex = 0
private assistantMessageContent: AssistantMessageContent[] = []
private presentAssistantMessageLocked = false
private presentAssistantMessageHasPendingUpdates = false
userMessageContent: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] = []
private userMessageContentReady = false
didRejectTool = false
private didAlreadyUseTool = false
private didCompleteReadingStream = false
// metrics
private toolUsage: ToolUsage = {}
// terminal
public terminalProcess?: RooTerminalProcess
constructor({
provider,
apiConfiguration,
customInstructions,
enableDiff = false,
enableCheckpoints = true,
fuzzyMatchThreshold = 1.0,
consecutiveMistakeLimit = 3,
task,
images,
historyItem,
startTask = true,
rootTask,
parentTask,
taskNumber = -1,
onCreated,
creatorModeConfig,
}: ClineOptions) {
super()
if (startTask && !task && !images && !historyItem) {
throw new Error("Either historyItem or task/images must be provided")
}
this.taskId = historyItem ? historyItem.id : crypto.randomUUID()
// normal use-case is usually retry similar history task with new workspace
this.workspacePath = parentTask
? parentTask.workspacePath
: getWorkspacePath(path.join(os.homedir(), "Desktop"))
this.instanceId = crypto.randomUUID().slice(0, 8)
this.taskNumber = -1
this.rooIgnoreController = new RooIgnoreController(this.cwd)
this.fileContextTracker = new FileContextTracker(provider, this.taskId)
this.rooIgnoreController.initialize().catch((error) => {
console.error("Failed to initialize RooIgnoreController:", error)
})
this.creatorModeConfig = creatorModeConfig ?? historyItem?.creatorModeConfig ?? { creatorMode: false }
this.apiConfiguration = {
...apiConfiguration,
creatorModeConfig: this.creatorModeConfig
}
this.api = buildApiHandler(this.apiConfiguration)
this.promptCacheKey = crypto.randomUUID()
this.urlContentFetcher = new UrlContentFetcher(provider.context)
this.browserSession = new BrowserSession(provider.context)
this.customInstructions = customInstructions
this.diffEnabled = enableDiff
this.fuzzyMatchThreshold = fuzzyMatchThreshold
this.consecutiveMistakeLimit = consecutiveMistakeLimit
this.providerRef = new WeakRef(provider)
this.globalStoragePath = provider.context.globalStorageUri.fsPath
this.diffViewProvider = new DiffViewProvider(this.cwd)
this.enableCheckpoints = enableCheckpoints
this.creatorModeConfig = creatorModeConfig ?? historyItem?.creatorModeConfig ?? { creatorMode: false }
this.rootTask = rootTask
this.parentTask = parentTask
this.taskNumber = taskNumber
if (historyItem) {
telemetryService.captureTaskRestarted(this.taskId)
} else {
telemetryService.captureTaskCreated(this.taskId)
}
this.diffStrategy = new MultiSearchReplaceDiffStrategy(this.fuzzyMatchThreshold)
onCreated?.(this)
onCreated?.(this)
if (startTask) {
if (task || images) {
this.startTask(task, images)
} else if (historyItem) {
this.resumeTaskFromHistory()
} else {
throw new Error("Either historyItem or task/images must be provided")
}
}
}
static create(options: ClineOptions): [Cline, Promise<void>] {
const instance = new Cline({ ...options, startTask: false })
const { images, task, historyItem } = options
let promise
if (images || task) {
promise = instance.startTask(task, images)
} else if (historyItem) {
promise = instance.resumeTaskFromHistory()
} else {
throw new Error("Either historyItem or task/images must be provided")
}
return [instance, promise]
}
get cwd() {
return this.workspacePath
}
// Storing task to disk for history
private async getSavedApiConversationHistory(): Promise<Anthropic.MessageParam[]> {
return readApiMessages({ taskId: this.taskId, globalStoragePath: this.globalStoragePath })
}
private async addToApiConversationHistory(message: Anthropic.MessageParam) {
const messageWithTs = { ...message, ts: Date.now() }
this.apiConversationHistory.push(messageWithTs)
await this.saveApiConversationHistory()
}
async overwriteApiConversationHistory(newHistory: Anthropic.MessageParam[]) {
this.apiConversationHistory = newHistory
await this.saveApiConversationHistory()
}
private async saveApiConversationHistory() {
try {
await saveApiMessages({
messages: this.apiConversationHistory,
taskId: this.taskId,
globalStoragePath: this.globalStoragePath,
})
} catch (error) {
// in the off chance this fails, we don't want to stop the task
console.error("Failed to save API conversation history:", error)
}
}
private async getSavedClineMessages(): Promise<ClineMessage[]> {
return readTaskMessages({ taskId: this.taskId, globalStoragePath: this.globalStoragePath })
}
private async addToClineMessages(message: ClineMessage) {
this.clineMessages.push(message)
await this.providerRef.deref()?.postStateToWebview()
this.emit("message", { action: "created", message })
await this.saveClineMessages()
}
public async overwriteClineMessages(newMessages: ClineMessage[]) {
// Reset the the prompt cache key since we've altered the conversation history.
this.promptCacheKey = crypto.randomUUID()
this.clineMessages = newMessages
await this.saveClineMessages()
}
private async updateClineMessage(partialMessage: ClineMessage) {
await this.providerRef.deref()?.postMessageToWebview({ type: "partialMessage", partialMessage })
this.emit("message", { action: "updated", message: partialMessage })
}
private async saveClineMessages() {
try {
await saveTaskMessages({
messages: this.clineMessages,
taskId: this.taskId,
globalStoragePath: this.globalStoragePath,
})
const { historyItem, tokenUsage } = await taskMetadata({
messages: this.clineMessages,
taskId: this.taskId,
taskNumber: this.taskNumber,
globalStoragePath: this.globalStoragePath,
workspace: this.cwd,
creatorModeConfig: this.creatorModeConfig,
})
this.emit("taskTokenUsageUpdated", this.taskId, tokenUsage)
await this.providerRef.deref()?.updateTaskHistory(historyItem)
} catch (error) {
console.error("Failed to save cline messages:", error)
}
}
// Communicate with webview
// partial has three valid states true (partial message), false (completion of partial message), undefined (individual complete message)
async ask(
type: ClineAsk,
text?: string,
partial?: boolean,
progressStatus?: ToolProgressStatus,
): Promise<{ response: ClineAskResponse; text?: string; images?: string[] }> {
// If this Cline instance was aborted by the provider, then the only
// thing keeping us alive is a promise still running in the background,
// in which case we don't want to send its result to the webview as it
// is attached to a new instance of Cline now. So we can safely ignore
// the result of any active promises, and this class will be
// deallocated. (Although we set Cline = undefined in provider, that
// simply removes the reference to this instance, but the instance is
// still alive until this promise resolves or rejects.)
if (this.abort) {
throw new Error(`[Cline#ask] task ${this.taskId}.${this.instanceId} aborted`)
}
let askTs: number
if (partial !== undefined) {
const lastMessage = this.clineMessages.at(-1)
const isUpdatingPreviousPartial =
lastMessage && lastMessage.partial && lastMessage.type === "ask" && lastMessage.ask === type
if (partial) {
if (isUpdatingPreviousPartial) {
// Existing partial message, so update it.
lastMessage.text = text
lastMessage.partial = partial
lastMessage.progressStatus = progressStatus
// TODO: Be more efficient about saving and posting only new
// data or one whole message at a time so ignore partial for
// saves, and only post parts of partial message instead of
// whole array in new listener.
this.updateClineMessage(lastMessage)
throw new Error("Current ask promise was ignored (#1)")
} else {
// This is a new partial message, so add it with partial
// state.
askTs = Date.now()
this.lastMessageTs = askTs
await this.addToClineMessages({ ts: askTs, type: "ask", ask: type, text, partial })
throw new Error("Current ask promise was ignored (#2)")
}
} else {
if (isUpdatingPreviousPartial) {
// This is the complete version of a previously partial
// message, so replace the partial with the complete version.
this.askResponse = undefined
this.askResponseText = undefined
this.askResponseImages = undefined
/*
Bug for the history books:
In the webview we use the ts as the chatrow key for the virtuoso list. Since we would update this ts right at the end of streaming, it would cause the view to flicker. The key prop has to be stable otherwise react has trouble reconciling items between renders, causing unmounting and remounting of components (flickering).
The lesson here is if you see flickering when rendering lists, it's likely because the key prop is not stable.
So in this case we must make sure that the message ts is never altered after first setting it.
*/
askTs = lastMessage.ts
this.lastMessageTs = askTs
// lastMessage.ts = askTs
lastMessage.text = text
lastMessage.partial = false
lastMessage.progressStatus = progressStatus
await this.saveClineMessages()
this.updateClineMessage(lastMessage)
} else {
// This is a new and complete message, so add it like normal.
this.askResponse = undefined
this.askResponseText = undefined
this.askResponseImages = undefined
askTs = Date.now()
this.lastMessageTs = askTs
await this.addToClineMessages({ ts: askTs, type: "ask", ask: type, text })
}
}
} else {
// This is a new non-partial message, so add it like normal.
this.askResponse = undefined
this.askResponseText = undefined
this.askResponseImages = undefined
askTs = Date.now()
this.lastMessageTs = askTs
await this.addToClineMessages({ ts: askTs, type: "ask", ask: type, text })
}
await pWaitFor(() => this.askResponse !== undefined || this.lastMessageTs !== askTs, { interval: 100 })
if (this.lastMessageTs !== askTs) {
// Could happen if we send multiple asks in a row i.e. with
// command_output. It's important that when we know an ask could
// fail, it is handled gracefully.
throw new Error("Current ask promise was ignored")
}
const result = { response: this.askResponse!, text: this.askResponseText, images: this.askResponseImages }
this.askResponse = undefined
this.askResponseText = undefined
this.askResponseImages = undefined
this.emit("taskAskResponded")
return result
}
async handleWebviewAskResponse(askResponse: ClineAskResponse, text?: string, images?: string[]) {
this.askResponse = askResponse
this.askResponseText = text
this.askResponseImages = images
}
async handleTerminalOperation(terminalOperation: "continue" | "abort") {
if (terminalOperation === "continue") {
this.terminalProcess?.continue()
} else if (terminalOperation === "abort") {
this.terminalProcess?.abort()
}
}
async say(
type: ClineSay,
text?: string,
images?: string[],
partial?: boolean,
checkpoint?: Record<string, unknown>,
progressStatus?: ToolProgressStatus,
): Promise<undefined> {
if (this.abort) {
throw new Error(`[Cline#say] task ${this.taskId}.${this.instanceId} aborted`)
}
if (partial !== undefined) {
const lastMessage = this.clineMessages.at(-1)
const isUpdatingPreviousPartial =
lastMessage && lastMessage.partial && lastMessage.type === "say" && lastMessage.say === type
if (partial) {
if (isUpdatingPreviousPartial) {
// existing partial message, so update it
lastMessage.text = text
lastMessage.images = images
lastMessage.partial = partial
lastMessage.progressStatus = progressStatus
this.updateClineMessage(lastMessage)
} else {
// this is a new partial message, so add it with partial state
const sayTs = Date.now()
this.lastMessageTs = sayTs
await this.addToClineMessages({ ts: sayTs, type: "say", say: type, text, images, partial })
}
} else {
// New now have a complete version of a previously partial message.
if (isUpdatingPreviousPartial) {
// This is the complete version of a previously partial
// message, so replace the partial with the complete version.
this.lastMessageTs = lastMessage.ts
// lastMessage.ts = sayTs
lastMessage.text = text
lastMessage.images = images
lastMessage.partial = false
lastMessage.progressStatus = progressStatus
// Instead of streaming partialMessage events, we do a save
// and post like normal to persist to disk.
await this.saveClineMessages()
// More performant than an entire postStateToWebview.
this.updateClineMessage(lastMessage)
} else {
// This is a new and complete message, so add it like normal.
const sayTs = Date.now()
this.lastMessageTs = sayTs
await this.addToClineMessages({ ts: sayTs, type: "say", say: type, text, images })
}
}
} else {
// this is a new non-partial message, so add it like normal
const sayTs = Date.now()
this.lastMessageTs = sayTs
await this.addToClineMessages({ ts: sayTs, type: "say", say: type, text, images, checkpoint })
}
}
async sayAndCreateMissingParamError(toolName: ToolName, paramName: string, relPath?: string) {
await this.say(
"error",
`Agent tried to use ${toolName}${
relPath ? ` for '${relPath.toPosix()}'` : ""
} without value for required parameter '${paramName}'. Retrying...`,
)
return formatResponse.toolError(formatResponse.missingToolParameterError(paramName))
}
// Task lifecycle
private async startTask(task?: string, images?: string[]): Promise<void> {
// conversationHistory (for API) and clineMessages (for webview) need to be in sync
// if the extension process were killed, then on restart the clineMessages might not be empty, so we need to set it to [] when we create a new Cline client (otherwise webview would show stale messages from previous session)
this.clineMessages = []
this.apiConversationHistory = []
await this.providerRef.deref()?.postStateToWebview()
await this.say("text", task, images)
this.isInitialized = true
let imageBlocks: Anthropic.ImageBlockParam[] = formatResponse.imageBlocks(images)
console.log(`[subtasks] task ${this.taskId}.${this.instanceId} starting`)
// PearAI memories
const memories = readMemories()
let memoryBlocks: Anthropic.TextBlockParam[] = []
if (memories.length > 0) {
const memoryContext = memories.map((m) => m.memory).join("\n\n")
memoryBlocks.push({
type: "text",
text: `<memories>\n<relevant user context from past, refer these if required/>\n${memoryContext}\n</memories>`,
})
}
await this.initiateTaskLoop([
{
type: "text",
text: `<task>\n${task}\n</task>`,
},
...memoryBlocks,
...imageBlocks,
])
}
async resumePausedTask(lastMessage: string) {
// release this Cline instance from paused state
this.isPaused = false
this.emit("taskUnpaused")
// fake an answer from the subtask that it has completed running and this is the result of what it has done
// add the message to the chat history and to the webview ui
try {
await this.say("subtask_result", lastMessage)
await this.addToApiConversationHistory({
role: "user",
content: [
{
type: "text",
text: `[new_task completed] Result: ${lastMessage}`,
},
],
})
} catch (error) {
this.providerRef
.deref()
?.log(`Error failed to add reply from subtast into conversation of parent task, error: ${error}`)
throw error
}
}
private async resumeTaskFromHistory() {
const modifiedClineMessages = await this.getSavedClineMessages()
// Remove any resume messages that may have been added before
const lastRelevantMessageIndex = findLastIndex(
modifiedClineMessages,
(m) => !(m.ask === "resume_task" || m.ask === "resume_completed_task"),
)
if (lastRelevantMessageIndex !== -1) {
modifiedClineMessages.splice(lastRelevantMessageIndex + 1)
}
// since we don't use api_req_finished anymore, we need to check if the last api_req_started has a cost value, if it doesn't and no cancellation reason to present, then we remove it since it indicates an api request without any partial content streamed
const lastApiReqStartedIndex = findLastIndex(
modifiedClineMessages,
(m) => m.type === "say" && m.say === "api_req_started",
)
if (lastApiReqStartedIndex !== -1) {
const lastApiReqStarted = modifiedClineMessages[lastApiReqStartedIndex]
const { cost, cancelReason }: ClineApiReqInfo = JSON.parse(lastApiReqStarted.text || "{}")
if (cost === undefined && cancelReason === undefined) {
modifiedClineMessages.splice(lastApiReqStartedIndex, 1)
}
}
await this.overwriteClineMessages(modifiedClineMessages)
this.clineMessages = await this.getSavedClineMessages()
// Now present the cline messages to the user and ask if they want to
// resume (NOTE: we ran into a bug before where the
// apiConversationHistory wouldn't be initialized when opening a old
// task, and it was because we were waiting for resume).
// This is important in case the user deletes messages without resuming
// the task first.
this.apiConversationHistory = await this.getSavedApiConversationHistory()
const lastClineMessage = this.clineMessages
.slice()
.reverse()
.find((m) => !(m.ask === "resume_task" || m.ask === "resume_completed_task")) // could be multiple resume tasks
let askType: ClineAsk
if (lastClineMessage?.ask === "completion_result") {
askType = "resume_completed_task"
} else {
askType = "resume_task"
}
this.isInitialized = true
const { response, text, images } = await this.ask(askType) // calls poststatetowebview
let responseText: string | undefined
let responseImages: string[] | undefined
if (response === "messageResponse") {
await this.say("user_feedback", text, images)
responseText = text
responseImages = images
}
// Make sure that the api conversation history can be resumed by the API,
// even if it goes out of sync with cline messages.
let existingApiConversationHistory: Anthropic.Messages.MessageParam[] =
await this.getSavedApiConversationHistory()
// v2.0 xml tags refactor caveat: since we don't use tools anymore, we need to replace all tool use blocks with a text block since the API disallows conversations with tool uses and no tool schema
const conversationWithoutToolBlocks = existingApiConversationHistory.map((message) => {
if (Array.isArray(message.content)) {
const newContent = message.content.map((block) => {
if (block.type === "tool_use") {
// it's important we convert to the new tool schema format so the model doesn't get confused about how to invoke tools
const inputAsXml = Object.entries(block.input as Record<string, string>)
.map(([key, value]) => `<${key}>\n${value}\n</${key}>`)
.join("\n")
return {
type: "text",
text: `<${block.name}>\n${inputAsXml}\n</${block.name}>`,
} as Anthropic.Messages.TextBlockParam
} else if (block.type === "tool_result") {
// Convert block.content to text block array, removing images
const contentAsTextBlocks = Array.isArray(block.content)
? block.content.filter((item) => item.type === "text")
: [{ type: "text", text: block.content }]
const textContent = contentAsTextBlocks.map((item) => item.text).join("\n\n")
const toolName = findToolName(block.tool_use_id, existingApiConversationHistory)
return {
type: "text",
text: `[${toolName} Result]\n\n${textContent}`,
} as Anthropic.Messages.TextBlockParam
}
return block
})
return { ...message, content: newContent }
}
return message
})
existingApiConversationHistory = conversationWithoutToolBlocks
// FIXME: remove tool use blocks altogether
// 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
// if there's no tool use and only a text block, then we can just add a user message
// (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)
// 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'
let modifiedOldUserContent: UserContent // either the last message if its user message, or the user message before the last (assistant) message
let modifiedApiConversationHistory: Anthropic.Messages.MessageParam[] // need to remove the last user message to replace with new modified user message
if (existingApiConversationHistory.length > 0) {
const lastMessage = existingApiConversationHistory[existingApiConversationHistory.length - 1]
if (lastMessage.role === "assistant") {
const content = Array.isArray(lastMessage.content)
? lastMessage.content
: [{ type: "text", text: lastMessage.content }]
const hasToolUse = content.some((block) => block.type === "tool_use")
if (hasToolUse) {
const toolUseBlocks = content.filter(
(block) => block.type === "tool_use",
) as Anthropic.Messages.ToolUseBlock[]
const toolResponses: Anthropic.ToolResultBlockParam[] = toolUseBlocks.map((block) => ({
type: "tool_result",
tool_use_id: block.id,
content: "Task was interrupted before this tool call could be completed.",
}))
modifiedApiConversationHistory = [...existingApiConversationHistory] // no changes
modifiedOldUserContent = [...toolResponses]
} else {
modifiedApiConversationHistory = [...existingApiConversationHistory]
modifiedOldUserContent = []
}
} else if (lastMessage.role === "user") {
const previousAssistantMessage: Anthropic.Messages.MessageParam | undefined =
existingApiConversationHistory[existingApiConversationHistory.length - 2]
const existingUserContent: UserContent = Array.isArray(lastMessage.content)
? lastMessage.content
: [{ type: "text", text: lastMessage.content }]
if (previousAssistantMessage && previousAssistantMessage.role === "assistant") {
const assistantContent = Array.isArray(previousAssistantMessage.content)
? previousAssistantMessage.content
: [{ type: "text", text: previousAssistantMessage.content }]
const toolUseBlocks = assistantContent.filter(
(block) => block.type === "tool_use",
) as Anthropic.Messages.ToolUseBlock[]
if (toolUseBlocks.length > 0) {
const existingToolResults = existingUserContent.filter(
(block) => block.type === "tool_result",
) as Anthropic.ToolResultBlockParam[]
const missingToolResponses: Anthropic.ToolResultBlockParam[] = toolUseBlocks
.filter(
(toolUse) => !existingToolResults.some((result) => result.tool_use_id === toolUse.id),
)
.map((toolUse) => ({
type: "tool_result",
tool_use_id: toolUse.id,
content: "Task was interrupted before this tool call could be completed.",
}))
modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1) // removes the last user message
modifiedOldUserContent = [...existingUserContent, ...missingToolResponses]
} else {
modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1)
modifiedOldUserContent = [...existingUserContent]
}
} else {
modifiedApiConversationHistory = existingApiConversationHistory.slice(0, -1)
modifiedOldUserContent = [...existingUserContent]
}
} else {
throw new Error("Unexpected: Last message is not a user or assistant message")
}
} else {
throw new Error("Unexpected: No existing API conversation history")
}
let newUserContent: UserContent = [...modifiedOldUserContent]
const agoText = ((): string => {
const timestamp = lastClineMessage?.ts ?? Date.now()
const now = Date.now()
const diff = now - timestamp
const minutes = Math.floor(diff / 60000)
const hours = Math.floor(minutes / 60)
const days = Math.floor(hours / 24)
if (days > 0) {
return `${days} day${days > 1 ? "s" : ""} ago`
}
if (hours > 0) {
return `${hours} hour${hours > 1 ? "s" : ""} ago`
}
if (minutes > 0) {
return `${minutes} minute${minutes > 1 ? "s" : ""} ago`
}
return "just now"
})()
const lastTaskResumptionIndex = newUserContent.findIndex(
(x) => x.type === "text" && x.text.startsWith("[TASK RESUMPTION]"),
)
if (lastTaskResumptionIndex !== -1) {
newUserContent.splice(lastTaskResumptionIndex, newUserContent.length - lastTaskResumptionIndex)
}
const wasRecent = lastClineMessage?.ts && Date.now() - lastClineMessage.ts < 30_000
newUserContent.push({
type: "text",
text:
`[TASK RESUMPTION] This task was interrupted ${agoText}. It may or may not be complete, so please reassess the task context. Be aware that the project state may have changed since then. If the task has not been completed, retry the last step before interruption and proceed with completing the task.\n\nNote: If you previously attempted a tool use that the user did not provide a result for, you should assume the tool use was not successful and assess whether you should retry. If the last tool was a browser_action, the browser has been closed and you must launch a new browser if needed.${
wasRecent
? "\n\nIMPORTANT: If the last tool use was a write_to_file that was interrupted, the file was reverted back to its original state before the interrupted edit, and you do NOT need to re-read the file as you already have its up-to-date contents."
: ""
}` +
(responseText
? `\n\nNew instructions for task continuation:\n<user_message>\n${responseText}\n</user_message>`
: ""),
})
if (responseImages && responseImages.length > 0) {
newUserContent.push(...formatResponse.imageBlocks(responseImages))
}
await this.overwriteApiConversationHistory(modifiedApiConversationHistory)
console.log(`[subtasks] task ${this.taskId}.${this.instanceId} resuming from history item`)
await this.initiateTaskLoop(newUserContent)
}
private async initiateTaskLoop(userContent: UserContent): Promise<void> {
// Kicks off the checkpoints initialization process in the background.
this.getCheckpointService()
let nextUserContent = userContent
let includeFileDetails = true
this.emit("taskStarted")
while (!this.abort) {
const didEndLoop = await this.recursivelyMakeClineRequests(nextUserContent, includeFileDetails)
includeFileDetails = false // we only need file details the first time
// The way this agentic loop works is that cline will be given a
// task that he then calls tools to complete. Unless there's an
// attempt_completion call, we keep responding back to him with his
// tool's responses until he either attempt_completion or does not
// use anymore tools. If he does not use anymore tools, we ask him
// to consider if he's completed the task and then call
// attempt_completion, otherwise proceed with completing the task.
// There is a MAX_REQUESTS_PER_TASK limit to prevent infinite
// requests, but Cline is prompted to finish the task as efficiently
// as he can.
if (didEndLoop) {
// For now a task never 'completes'. This will only happen if
// the user hits max requests and denies resetting the count.
break
} else {
nextUserContent = [{ type: "text", text: formatResponse.noToolsUsed() }]
this.consecutiveMistakeCount++
}
}
}
async abortTask(isAbandoned = false) {
console.log(`[subtasks] aborting task ${this.taskId}.${this.instanceId}`)
// Will stop any autonomously running promises.
if (isAbandoned) {
this.abandoned = true
}
this.abort = true
this.emit("taskAborted")
// Stop waiting for child task completion.
if (this.pauseInterval) {
clearInterval(this.pauseInterval)
this.pauseInterval = undefined
}
// Release any terminals associated with this task.
TerminalRegistry.releaseTerminalsForTask(this.taskId)
this.urlContentFetcher.closeBrowser()
this.browserSession.closeBrowser()
this.rooIgnoreController?.dispose()
this.fileContextTracker.dispose()
// If we're not streaming then `abortStream` (which reverts the diff
// view changes) won't be called, so we need to revert the changes here.
if (this.isStreaming && this.diffViewProvider.isEditing) {
await this.diffViewProvider.revertChanges()
}
// Save the countdown message in the automatic retry or other content
await this.saveClineMessages()
}
// Tools
async *attemptApiRequest(previousApiReqIndex: number, retryAttempt: number = 0): ApiStream {
let mcpHub: McpHub | undefined
const { apiConfiguration, mcpEnabled, autoApprovalEnabled, alwaysApproveResubmit, requestDelaySeconds } =
(await this.providerRef.deref()?.getState()) ?? {}
let rateLimitDelay = 0
// Only apply rate limiting if this isn't the first request
if (this.lastApiRequestTime) {
const now = Date.now()
const timeSinceLastRequest = now - this.lastApiRequestTime
const rateLimit = apiConfiguration?.rateLimitSeconds || 0
rateLimitDelay = Math.ceil(Math.max(0, rateLimit * 1000 - timeSinceLastRequest) / 1000)
}
// Only show rate limiting message if we're not retrying. If retrying, we'll include the delay there.
if (rateLimitDelay > 0 && retryAttempt === 0) {
// Show countdown timer
for (let i = rateLimitDelay; i > 0; i--) {
const delayMessage = `Rate limiting for ${i} seconds...`
await this.say("api_req_retry_delayed", delayMessage, undefined, true)
await delay(1000)
}
}
// Update last request time before making the request
this.lastApiRequestTime = Date.now()
if (mcpEnabled ?? true) {
const provider = this.providerRef.deref()
if (!provider) {
throw new Error("Provider reference lost during view transition")
}
// Wait for MCP hub initialization through McpServerManager
mcpHub = await McpServerManager.getInstance(provider.context, provider)
if (!mcpHub) {
throw new Error("Failed to get MCP hub from server manager")
}