-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathapi.ts
More file actions
568 lines (461 loc) · 16.5 KB
/
Copy pathapi.ts
File metadata and controls
568 lines (461 loc) · 16.5 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
import { EventEmitter } from "events"
import fs from "fs/promises"
import * as path from "path"
import * as os from "os"
import * as vscode from "vscode"
import pWaitFor from "p-wait-for"
import {
type RooCodeAPI,
type RooCodeSettings,
type RooCodeEvents,
type ProviderSettings,
type ProviderSettingsEntry,
type TaskEvent,
type CreateTaskOptions,
RooCodeEventName,
TaskCommandName,
isSecretStateKey,
IpcOrigin,
IpcMessageType,
} from "@roo-code/types"
import { IpcServer } from "@roo-code/ipc"
import { Package } from "../shared/package"
import { ClineProvider } from "../core/webview/ClineProvider"
import { openClineInNewTab } from "../activate/registerCommands"
import { getCommands } from "../services/command/commands"
import { getModels } from "../api/providers/fetchers/modelCache"
export class API extends EventEmitter<RooCodeEvents> implements RooCodeAPI {
private readonly outputChannel: vscode.OutputChannel
private readonly sidebarProvider: ClineProvider
private readonly context: vscode.ExtensionContext
private readonly ipc?: IpcServer
private readonly log: (...args: unknown[]) => void
private logfile?: string
constructor(
outputChannel: vscode.OutputChannel,
provider: ClineProvider,
socketPath?: string,
enableLogging = false,
) {
super()
this.outputChannel = outputChannel
this.sidebarProvider = provider
this.context = provider.context
if (enableLogging) {
this.log = (...args: unknown[]) => {
this.outputChannelLog(...args)
console.log(args)
}
this.logfile = path.join(os.tmpdir(), "roo-code-messages.log")
} else {
this.log = () => {}
}
this.registerListeners(this.sidebarProvider)
if (socketPath) {
const ipc = (this.ipc = new IpcServer(socketPath, this.log))
ipc.listen()
this.log(`[API] ipc server started: socketPath=${socketPath}, pid=${process.pid}, ppid=${process.ppid}`)
ipc.on(IpcMessageType.TaskCommand, async (clientId, command) => {
const sendResponse = (eventName: RooCodeEventName, payload: unknown[]) => {
ipc.send(clientId, {
type: IpcMessageType.TaskEvent,
origin: IpcOrigin.Server,
data: { eventName, payload } as TaskEvent,
})
}
switch (command.commandName) {
case TaskCommandName.StartNewTask:
this.log(
`[API] StartNewTask -> ${command.data.text}, ${JSON.stringify(command.data.configuration)}`,
)
await this.startNewTask(command.data)
break
case TaskCommandName.CancelTask:
this.log(`[API] CancelTask`)
await this.cancelCurrentTask()
break
case TaskCommandName.CloseTask:
this.log(`[API] CloseTask`)
await vscode.commands.executeCommand("workbench.action.files.saveFiles")
await vscode.commands.executeCommand("workbench.action.closeWindow")
break
case TaskCommandName.ResumeTask:
this.log(`[API] ResumeTask -> ${command.data}`)
try {
await this.resumeTask(command.data)
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
this.log(`[API] ResumeTask failed for taskId ${command.data}: ${errorMessage}`)
// Don't rethrow - we want to prevent IPC server crashes.
// The error is logged for debugging purposes.
}
break
case TaskCommandName.SendMessage:
this.log(`[API] SendMessage -> ${command.data.text}`)
await this.sendMessage(command.data.text, command.data.images)
break
case TaskCommandName.GetCommands:
try {
const commands = await getCommands(this.sidebarProvider.cwd)
sendResponse(RooCodeEventName.CommandsResponse, [
commands.map((cmd) => ({
name: cmd.name,
source: cmd.source,
filePath: cmd.filePath,
description: cmd.description,
argumentHint: cmd.argumentHint,
})),
])
} catch (error) {
sendResponse(RooCodeEventName.CommandsResponse, [[]])
}
break
case TaskCommandName.GetModes:
try {
const modes = await this.sidebarProvider.getModes()
sendResponse(RooCodeEventName.ModesResponse, [modes])
} catch (error) {
sendResponse(RooCodeEventName.ModesResponse, [[]])
}
break
case TaskCommandName.GetModels:
try {
sendResponse(RooCodeEventName.ModelsResponse, [{}])
} catch (error) {
sendResponse(RooCodeEventName.ModelsResponse, [{}])
}
break
case TaskCommandName.DeleteQueuedMessage:
this.log(`[API] DeleteQueuedMessage -> ${command.data}`)
try {
this.deleteQueuedMessage(command.data)
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
this.log(`[API] DeleteQueuedMessage failed for messageId ${command.data}: ${errorMessage}`)
}
break
}
})
}
}
public override emit<K extends keyof RooCodeEvents>(
eventName: K,
...args: K extends keyof RooCodeEvents ? RooCodeEvents[K] : never
) {
const data = { eventName: eventName as RooCodeEventName, payload: args } as TaskEvent
this.ipc?.broadcast({ type: IpcMessageType.TaskEvent, origin: IpcOrigin.Server, data })
return super.emit(eventName, ...args)
}
public async startNewTask({
configuration,
text,
images,
newTab,
}: {
configuration: RooCodeSettings
text?: string
images?: string[]
newTab?: boolean
}) {
let provider: ClineProvider
if (newTab) {
await vscode.commands.executeCommand("workbench.action.files.revert")
await vscode.commands.executeCommand("workbench.action.closeAllEditors")
provider = await openClineInNewTab({ context: this.context, outputChannel: this.outputChannel })
this.registerListeners(provider)
} else {
await vscode.commands.executeCommand(`${Package.name}.SidebarProvider.focus`)
provider = this.sidebarProvider
}
await provider.removeClineFromStack()
await provider.postStateToWebview()
await provider.postMessageToWebview({ type: "action", action: "chatButtonClicked" })
await provider.postMessageToWebview({ type: "invoke", invoke: "newChat", text, images })
const options: CreateTaskOptions = {
consecutiveMistakeLimit: Number.MAX_SAFE_INTEGER,
}
const task = await provider.createTask(text, images, undefined, options, configuration)
if (!task) {
throw new Error("Failed to create task due to policy restrictions")
}
return task.taskId
}
public async resumeTask(taskId: string): Promise<void> {
await vscode.commands.executeCommand(`${Package.name}.SidebarProvider.focus`)
await this.waitForWebviewLaunch(5_000)
const { historyItem } = await this.sidebarProvider.getTaskWithId(taskId)
await this.sidebarProvider.createTaskWithHistoryItem(historyItem)
if (this.sidebarProvider.viewLaunched) {
await this.sidebarProvider.postMessageToWebview({ type: "action", action: "chatButtonClicked" })
} else {
this.log(
`[API#resumeTask] webview not launched after resume for task ${taskId}; continuing in headless mode`,
)
}
}
public async isTaskInHistory(taskId: string): Promise<boolean> {
try {
await this.sidebarProvider.getTaskWithId(taskId)
return true
} catch {
return false
}
}
public getCurrentTaskStack() {
return this.sidebarProvider.getCurrentTaskStack()
}
public async clearCurrentTask(_lastMessage?: string) {
// Legacy finishSubTask removed; clear current by closing active task instance.
await this.sidebarProvider.removeClineFromStack()
await this.sidebarProvider.postStateToWebview()
}
public async cancelCurrentTask() {
await this.sidebarProvider.cancelTask()
}
public async sendMessage(text?: string, images?: string[]) {
const currentTask = this.sidebarProvider.getCurrentTask()
// In headless/sandbox flows the webview may not be launched, so routing
// through invoke=sendMessage drops the message. Deliver directly to the
// task ask-response channel instead.
if (!this.sidebarProvider.viewLaunched) {
if (!currentTask) {
this.log("[API#sendMessage] no current task in headless mode; message dropped")
return
}
await currentTask.submitUserMessage(text ?? "", images)
return
}
await this.sidebarProvider.postMessageToWebview({ type: "invoke", invoke: "sendMessage", text, images })
}
public deleteQueuedMessage(messageId: string) {
const currentTask = this.sidebarProvider.getCurrentTask()
if (!currentTask) {
this.log(`[API#deleteQueuedMessage] no current task; ignoring delete for messageId ${messageId}`)
return
}
currentTask.messageQueueService.removeMessage(messageId)
}
public async pressPrimaryButton() {
await this.sidebarProvider.postMessageToWebview({ type: "invoke", invoke: "primaryButtonClick" })
}
public async pressSecondaryButton() {
await this.sidebarProvider.postMessageToWebview({ type: "invoke", invoke: "secondaryButtonClick" })
}
public async approveCurrentAsk() {
this.sidebarProvider.getCurrentTask()?.approveAsk()
}
public isReady() {
return this.sidebarProvider.viewLaunched
}
private async waitForWebviewLaunch(timeoutMs: number): Promise<boolean> {
try {
await pWaitFor(() => this.sidebarProvider.viewLaunched, {
timeout: timeoutMs,
interval: 50,
})
return true
} catch {
this.log(`[API#waitForWebviewLaunch] webview did not launch within ${timeoutMs}ms`)
return false
}
}
private registerListeners(provider: ClineProvider) {
provider.on(RooCodeEventName.TaskCreated, (task) => {
// Task Lifecycle
task.on(RooCodeEventName.TaskStarted, async () => {
this.emit(RooCodeEventName.TaskStarted, task.taskId)
await this.fileLog(`[${new Date().toISOString()}] taskStarted -> ${task.taskId}\n`)
})
task.on(RooCodeEventName.TaskCompleted, async (_, tokenUsage, toolUsage) => {
this.emit(RooCodeEventName.TaskCompleted, task.taskId, tokenUsage, toolUsage, {
isSubtask: !!task.parentTaskId,
})
await this.fileLog(
`[${new Date().toISOString()}] taskCompleted -> ${task.taskId} | ${JSON.stringify(tokenUsage, null, 2)} | ${JSON.stringify(toolUsage, null, 2)}\n`,
)
})
task.on(RooCodeEventName.TaskAborted, () => {
this.emit(RooCodeEventName.TaskAborted, task.taskId)
})
task.on(RooCodeEventName.TaskFocused, () => {
this.emit(RooCodeEventName.TaskFocused, task.taskId)
})
task.on(RooCodeEventName.TaskUnfocused, () => {
this.emit(RooCodeEventName.TaskUnfocused, task.taskId)
})
task.on(RooCodeEventName.TaskActive, () => {
this.emit(RooCodeEventName.TaskActive, task.taskId)
})
task.on(RooCodeEventName.TaskInteractive, () => {
this.emit(RooCodeEventName.TaskInteractive, task.taskId)
})
task.on(RooCodeEventName.TaskResumable, () => {
this.emit(RooCodeEventName.TaskResumable, task.taskId)
})
task.on(RooCodeEventName.TaskIdle, () => {
this.emit(RooCodeEventName.TaskIdle, task.taskId)
})
// Subtask Lifecycle
task.on(RooCodeEventName.TaskPaused, () => {
this.emit(RooCodeEventName.TaskPaused, task.taskId)
})
task.on(RooCodeEventName.TaskUnpaused, () => {
this.emit(RooCodeEventName.TaskUnpaused, task.taskId)
})
task.on(RooCodeEventName.TaskSpawned, (childTaskId) => {
this.emit(RooCodeEventName.TaskSpawned, task.taskId, childTaskId)
})
task.on(RooCodeEventName.TaskDelegated as any, (childTaskId: string) => {
;(this.emit as any)(RooCodeEventName.TaskDelegated, task.taskId, childTaskId)
})
task.on(RooCodeEventName.TaskDelegationCompleted as any, (childTaskId: string, summary: string) => {
;(this.emit as any)(RooCodeEventName.TaskDelegationCompleted, task.taskId, childTaskId, summary)
})
task.on(RooCodeEventName.TaskDelegationResumed as any, (childTaskId: string) => {
;(this.emit as any)(RooCodeEventName.TaskDelegationResumed, task.taskId, childTaskId)
})
// Task Execution
task.on(RooCodeEventName.Message, async (message) => {
this.emit(RooCodeEventName.Message, { taskId: task.taskId, ...message })
if (message.message.partial !== true) {
await this.fileLog(`[${new Date().toISOString()}] ${JSON.stringify(message.message, null, 2)}\n`)
}
})
task.on(RooCodeEventName.TaskModeSwitched, (taskId, mode) => {
this.emit(RooCodeEventName.TaskModeSwitched, taskId, mode)
})
task.on(RooCodeEventName.TaskAskResponded, () => {
this.emit(RooCodeEventName.TaskAskResponded, task.taskId)
})
task.on(RooCodeEventName.QueuedMessagesUpdated, (taskId, messages) => {
this.emit(RooCodeEventName.QueuedMessagesUpdated, taskId, messages)
})
// Task Analytics
task.on(RooCodeEventName.TaskToolFailed, (taskId, tool, error) => {
this.emit(RooCodeEventName.TaskToolFailed, taskId, tool, error)
})
task.on(RooCodeEventName.TaskTokenUsageUpdated, (_, tokenUsage, toolUsage) => {
this.emit(RooCodeEventName.TaskTokenUsageUpdated, task.taskId, tokenUsage, toolUsage)
})
// Let's go!
this.emit(RooCodeEventName.TaskCreated, task.taskId)
})
}
// Logging
private outputChannelLog(...args: unknown[]) {
for (const arg of args) {
if (arg === null) {
this.outputChannel.appendLine("null")
} else if (arg === undefined) {
this.outputChannel.appendLine("undefined")
} else if (typeof arg === "string") {
this.outputChannel.appendLine(arg)
} else if (arg instanceof Error) {
this.outputChannel.appendLine(`Error: ${arg.message}\n${arg.stack || ""}`)
} else {
try {
this.outputChannel.appendLine(
JSON.stringify(
arg,
(key, value) => {
if (typeof value === "bigint") return `BigInt(${value})`
if (typeof value === "function") return `Function: ${value.name || "anonymous"}`
if (typeof value === "symbol") return value.toString()
return value
},
2,
),
)
} catch (error) {
this.outputChannel.appendLine(`[Non-serializable object: ${Object.prototype.toString.call(arg)}]`)
}
}
}
}
private async fileLog(message: string) {
if (!this.logfile) {
return
}
try {
await fs.appendFile(this.logfile, message, "utf8")
} catch (_) {
this.logfile = undefined
}
}
// Global Settings Management
public getConfiguration(): RooCodeSettings {
return Object.fromEntries(
Object.entries(this.sidebarProvider.getValues()).filter(([key]) => !isSecretStateKey(key)),
)
}
public async setConfiguration(values: RooCodeSettings) {
await this.sidebarProvider.contextProxy.setValues(values)
await this.sidebarProvider.providerSettingsManager.saveConfig(values.currentApiConfigName || "default", values)
await this.sidebarProvider.postStateToWebview()
}
// Provider Profile Management
public getProfiles(): string[] {
return this.sidebarProvider.getProviderProfileEntries().map(({ name }) => name)
}
public getProfileEntry(name: string): ProviderSettingsEntry | undefined {
return this.sidebarProvider.getProviderProfileEntry(name)
}
public async createProfile(name: string, profile?: ProviderSettings, activate: boolean = true) {
const entry = this.getProfileEntry(name)
if (entry) {
throw new Error(`Profile with name "${name}" already exists`)
}
const id = await this.sidebarProvider.upsertProviderProfile(name, profile ?? {}, activate)
if (!id) {
throw new Error(`Failed to create profile with name "${name}"`)
}
return id
}
public async updateProfile(
name: string,
profile: ProviderSettings,
activate: boolean = true,
): Promise<string | undefined> {
const entry = this.getProfileEntry(name)
if (!entry) {
throw new Error(`Profile with name "${name}" does not exist`)
}
const id = await this.sidebarProvider.upsertProviderProfile(name, profile, activate)
if (!id) {
throw new Error(`Failed to update profile with name "${name}"`)
}
return id
}
public async upsertProfile(
name: string,
profile: ProviderSettings,
activate: boolean = true,
): Promise<string | undefined> {
const id = await this.sidebarProvider.upsertProviderProfile(name, profile, activate)
if (!id) {
throw new Error(`Failed to upsert profile with name "${name}"`)
}
return id
}
public async deleteProfile(name: string): Promise<void> {
const entry = this.getProfileEntry(name)
if (!entry) {
throw new Error(`Profile with name "${name}" does not exist`)
}
await this.sidebarProvider.deleteProviderProfile(entry)
}
public getActiveProfile(): string | undefined {
return this.getConfiguration().currentApiConfigName
}
public async setActiveProfile(name: string): Promise<string | undefined> {
const entry = this.getProfileEntry(name)
if (!entry) {
throw new Error(`Profile with name "${name}" does not exist`)
}
await this.sidebarProvider.activateProviderProfile({ name })
return this.getActiveProfile()
}
public get storagePath(): string {
return this.context.globalStorageUri.fsPath
}
}