-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathextension.ts
More file actions
412 lines (335 loc) · 14.6 KB
/
extension.ts
File metadata and controls
412 lines (335 loc) · 14.6 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
import * as vscode from "vscode"
import * as dotenvx from "@dotenvx/dotenvx"
import * as path from "path"
import * as ZgsmCore from "./core/costrict"
// Load environment variables from .env file
try {
// Specify path to .env file in the project root directory
const envPath = path.join(__dirname, "..", ".env")
dotenvx.config({ path: envPath })
} catch (e) {
// Silently handle environment loading errors
console.warn("Failed to load environment variables:", e)
}
// import type { CloudUserInfo, AuthState } from "@roo-code/types"
// import { CloudService, BridgeOrchestrator } from "@roo-code/cloud"
import { TelemetryService, PostHogTelemetryClient } from "@roo-code/telemetry"
import "./utils/path" // Necessary to have access to String.prototype.toPosix.
import { createOutputChannelLogger, createDualLogger } from "./utils/outputChannelLogger"
import { Package } from "./shared/package"
import { formatLanguage } from "./shared/language"
import { ContextProxy } from "./core/config/ContextProxy"
import { ClineProvider } from "./core/webview/ClineProvider"
import { DIFF_VIEW_URI_SCHEME } from "./integrations/editor/DiffViewProvider"
import { TerminalRegistry } from "./integrations/terminal/TerminalRegistry"
import { McpServerManager } from "./services/mcp/McpServerManager"
// import { CodeIndexManager } from "./services/code-index/manager"
import { MdmService } from "./services/mdm/MdmService"
import { migrateSettings } from "./utils/migrateSettings"
import { autoImportSettings } from "./utils/autoImportSettings"
import { API } from "./extension/api"
import { ZgsmAuthConfig } from "./core/costrict/auth/index"
import {
handleUri,
registerCommands,
registerCodeActions,
registerTerminalActions,
CodeActionProvider,
} from "./activate"
import { initializeI18n } from "./i18n"
import { getCommand } from "./utils/commands"
/**
* Built using https://github.com/microsoft/vscode-webview-ui-toolkit
*
* Inspired by:
* - https://github.com/microsoft/vscode-webview-ui-toolkit-samples/tree/main/default/weather-webview
* - https://github.com/microsoft/vscode-webview-ui-toolkit-samples/tree/main/frameworks/hello-world-react-cra
*/
let outputChannel: vscode.OutputChannel
let extensionContext: vscode.ExtensionContext
// let cloudService: CloudService | undefined
// let authStateChangedHandler: ((data: { state: AuthState; previousState: AuthState }) => Promise<void>) | undefined
// let settingsUpdatedHandler: (() => void) | undefined
// let userInfoHandler: ((data: { userInfo: CloudUserInfo }) => Promise<void>) | undefined
// This method is called when your extension is activated.
// Your extension is activated the very first time the command is executed.
export async function activate(context: vscode.ExtensionContext) {
extensionContext = context
outputChannel = vscode.window.createOutputChannel(Package.outputChannel)
context.subscriptions.push(outputChannel)
outputChannel.appendLine(`${Package.name} extension activated - ${JSON.stringify(Package)}`)
// Migrate old settings to new
await migrateSettings(context, outputChannel)
// Initialize telemetry service.
TelemetryService.createInstance()
// try {
// telemetryService.register(new PostHogTelemetryClient())
// } catch (error) {
// console.warn("Failed to register PostHogTelemetryClient:", error)
// }
// Create logger for cloud services.
const cloudLogger = createDualLogger(createOutputChannelLogger(outputChannel))
// Initialize MDM service
const mdmService = await MdmService.createInstance(cloudLogger)
// Initialize i18n for internationalization support.
initializeI18n(context.globalState.get("language") ?? formatLanguage(vscode.env.language))
// Initialize terminal shell execution handlers.
TerminalRegistry.initialize()
// Get default commands from configuration.
const defaultCommands = vscode.workspace.getConfiguration(Package.name).get<string[]>("allowedCommands") || []
// Initialize global state if not already set.
if (!context.globalState.get("allowedCommands")) {
context.globalState.update("allowedCommands", defaultCommands)
}
const contextProxy = await ContextProxy.getInstance(context)
// // Initialize code index managers for all workspace folders.
// const codeIndexManagers: CodeIndexManager[] = []
// if (vscode.workspace.workspaceFolders) {
// for (const folder of vscode.workspace.workspaceFolders) {
// const manager = CodeIndexManager.getInstance(context, folder.uri.fsPath)
// if (manager) {
// codeIndexManagers.push(manager)
// try {
// await manager.initialize(contextProxy)
// } catch (error) {
// outputChannel.appendLine(
// `[CodeIndexManager] Error during background CodeIndexManager configuration/indexing for ${folder.uri.fsPath}: ${error.message || error}`,
// )
// }
// context.subscriptions.push(manager)
// }
// }
// }
// Initialize the provider *before* the Roo Code Cloud service.
const provider = new ClineProvider(context, outputChannel, "sidebar", contextProxy, mdmService)
// // Initialize Roo Code Cloud service.
// const postStateListener = () => ClineProvider.getVisibleInstance()?.postStateToWebview()
// authStateChangedHandler = async (data: { state: AuthState; previousState: AuthState }) => {
// postStateListener()
// // Check if user has logged out
// if (data.state === "logged-out") {
// try {
// // Disconnect the bridge when user logs out
// // When userInfo is null and remoteControlEnabled is false, BridgeOrchestrator
// // will disconnect. The options parameter is not needed for disconnection.
// await BridgeOrchestrator.connectOrDisconnect(null, false)
// cloudLogger("[CloudService] BridgeOrchestrator disconnected on logout")
// } catch (error) {
// cloudLogger(
// `[CloudService] Failed to disconnect BridgeOrchestrator on logout: ${
// error instanceof Error ? error.message : String(error)
// }`,
// )
// }
// }
// }
// settingsUpdatedHandler = async () => {
// const userInfo = CloudService.instance.getUserInfo()
// if (userInfo && CloudService.instance.cloudAPI) {
// try {
// const config = await CloudService.instance.cloudAPI.bridgeConfig()
// const isCloudAgent =
// typeof process.env.ROO_CODE_CLOUD_TOKEN === "string" && process.env.ROO_CODE_CLOUD_TOKEN.length > 0
// const remoteControlEnabled = isCloudAgent
// ? true
// : (CloudService.instance.getUserSettings()?.settings?.extensionBridgeEnabled ?? false)
// cloudLogger(`[CloudService] Settings updated - remoteControlEnabled = ${remoteControlEnabled}`)
// await BridgeOrchestrator.connectOrDisconnect(userInfo, remoteControlEnabled, {
// ...config,
// provider,
// sessionId: vscode.env.sessionId,
// })
// } catch (error) {
// cloudLogger(
// `[CloudService] Failed to update BridgeOrchestrator on settings change: ${error instanceof Error ? error.message : String(error)}`,
// )
// }
// }
// postStateListener()
// }
// userInfoHandler = async ({ userInfo }: { userInfo: CloudUserInfo }) => {
// postStateListener()
// if (!CloudService.instance.cloudAPI) {
// cloudLogger("[CloudService] CloudAPI is not initialized")
// return
// }
// try {
// const config = await CloudService.instance.cloudAPI.bridgeConfig()
// const isCloudAgent =
// typeof process.env.ROO_CODE_CLOUD_TOKEN === "string" && process.env.ROO_CODE_CLOUD_TOKEN.length > 0
// cloudLogger(`[CloudService] isCloudAgent = ${isCloudAgent}, socketBridgeUrl = ${config.socketBridgeUrl}`)
// const remoteControlEnabled = isCloudAgent
// ? true
// : (CloudService.instance.getUserSettings()?.settings?.extensionBridgeEnabled ?? false)
// await BridgeOrchestrator.connectOrDisconnect(userInfo, remoteControlEnabled, {
// ...config,
// provider,
// sessionId: vscode.env.sessionId,
// })
// } catch (error) {
// cloudLogger(
// `[CloudService] Failed to fetch bridgeConfig: ${error instanceof Error ? error.message : String(error)}`,
// )
// }
// }
// cloudService = await CloudService.createInstance(context, cloudLogger, {
// "auth-state-changed": authStateChangedHandler,
// "settings-updated": settingsUpdatedHandler,
// "user-info": userInfoHandler,
// })
// try {
// if (cloudService.telemetryClient) {
// TelemetryService.instance.register(cloudService.telemetryClient)
// }
// } catch (error) {
// outputChannel.appendLine(
// `[CloudService] Failed to register TelemetryClient: ${error instanceof Error ? error.message : String(error)}`,
// )
// }
// // Add to subscriptions for proper cleanup on deactivate.
// context.subscriptions.push(cloudService)
// // Finish initializing the provider.
// TelemetryService.instance.setProvider(provider)
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(ClineProvider.sideBarId, provider, {
webviewOptions: { retainContextWhenHidden: true },
}),
)
// Auto-import configuration if specified in settings.
try {
await autoImportSettings(outputChannel, {
providerSettingsManager: provider.providerSettingsManager,
contextProxy: provider.contextProxy,
customModesManager: provider.customModesManager,
})
} catch (error) {
outputChannel.appendLine(
`[AutoImport] Error during auto-import: ${error instanceof Error ? error.message : String(error)}`,
)
}
registerCommands({ context, outputChannel, provider })
/**
* We use the text document content provider API to show the left side for diff
* view by creating a virtual document for the original content. This makes it
* readonly so users know to edit the right side if they want to keep their changes.
*
* This API allows you to create readonly documents in VSCode from arbitrary
* sources, and works by claiming an uri-scheme for which your provider then
* returns text contents. The scheme must be provided when registering a
* provider and cannot change afterwards.
*
* Note how the provider doesn't create uris for virtual documents - its role
* is to provide contents given such an uri. In return, content providers are
* wired into the open document logic so that providers are always considered.
*
* https://code.visualstudio.com/api/extension-guides/virtual-documents
*/
const diffContentProvider = new (class implements vscode.TextDocumentContentProvider {
provideTextDocumentContent(uri: vscode.Uri): string {
return Buffer.from(uri.query, "base64").toString("utf-8")
}
})()
context.subscriptions.push(
vscode.workspace.registerTextDocumentContentProvider(DIFF_VIEW_URI_SCHEME, diffContentProvider),
)
context.subscriptions.push(vscode.window.registerUriHandler({ handleUri }))
// Register code actions provider.
context.subscriptions.push(
vscode.languages.registerCodeActionsProvider({ pattern: "**/*" }, new CodeActionProvider(), {
providedCodeActionKinds: CodeActionProvider.providedCodeActionKinds,
}),
)
// Register the 'User Manual' command
context.subscriptions.push(
vscode.commands.registerCommand(getCommand("view.userHelperDoc"), () => {
vscode.env.openExternal(vscode.Uri.parse(`${ZgsmAuthConfig.getInstance().getDefaultSite()}`))
}),
)
// Register the 'Report Issue' command
context.subscriptions.push(
vscode.commands.registerCommand(getCommand("view.issue"), () => {
vscode.env.openExternal(vscode.Uri.parse(`${ZgsmAuthConfig.getInstance().getDefaultApiBaseUrl()}/issue/`))
}),
)
registerCodeActions(context)
registerTerminalActions(context)
// Allows other extensions to activate once Costrict is ready.
vscode.commands.executeCommand(`${Package.name}.activationCompleted`)
// Implements the `RooCodeAPI` interface.
const socketPath = process.env.ROO_CODE_IPC_SOCKET_PATH
const enableLogging = typeof socketPath === "string"
// Watch the core files and automatically reload the extension host.
if (process.env.NODE_ENV === "development") {
const watchPaths = [
{ path: context.extensionPath, pattern: "**/*.ts" },
{ path: path.join(context.extensionPath, "../packages/types"), pattern: "**/*.ts" },
{ path: path.join(context.extensionPath, "../packages/telemetry"), pattern: "**/*.ts" },
{ path: path.join(context.extensionPath, "node_modules/@roo-code/cloud"), pattern: "**/*" },
]
console.log(
`♻️♻️♻️ Core auto-reloading: Watching for changes in ${watchPaths.map(({ path }) => path).join(", ")}`,
)
// Create a debounced reload function to prevent excessive reloads
let reloadTimeout: NodeJS.Timeout | undefined
const DEBOUNCE_DELAY = 1_000
const debouncedReload = (uri: vscode.Uri) => {
if (reloadTimeout) {
clearTimeout(reloadTimeout)
}
console.log(`♻️ ${uri.fsPath} changed; scheduling reload...`)
reloadTimeout = setTimeout(() => {
console.log(`♻️ Reloading host after debounce delay...`)
vscode.commands.executeCommand("workbench.action.reloadWindow")
}, DEBOUNCE_DELAY)
}
watchPaths.forEach(({ path: watchPath, pattern }) => {
const relPattern = new vscode.RelativePattern(vscode.Uri.file(watchPath), pattern)
const watcher = vscode.workspace.createFileSystemWatcher(relPattern, false, false, false)
// Listen to all change types to ensure symlinked file updates trigger reloads.
watcher.onDidChange(debouncedReload)
watcher.onDidCreate(debouncedReload)
watcher.onDidDelete(debouncedReload)
context.subscriptions.push(watcher)
})
// Clean up the timeout on deactivation
context.subscriptions.push({
dispose: () => {
if (reloadTimeout) {
clearTimeout(reloadTimeout)
}
},
})
}
ZgsmCore.activate(context, provider, outputChannel)
return new API(outputChannel, provider, socketPath, enableLogging)
}
// This method is called when your extension is deactivated.
export async function deactivate() {
await ZgsmCore.deactivate()
outputChannel.appendLine(`${Package.name} extension deactivated`)
// if (cloudService && CloudService.hasInstance()) {
// try {
// if (authStateChangedHandler) {
// CloudService.instance.off("auth-state-changed", authStateChangedHandler)
// }
// if (settingsUpdatedHandler) {
// CloudService.instance.off("settings-updated", settingsUpdatedHandler)
// }
// if (userInfoHandler) {
// CloudService.instance.off("user-info", userInfoHandler as any)
// }
// outputChannel.appendLine("CloudService event handlers cleaned up")
// } catch (error) {
// outputChannel.appendLine(
// `Failed to clean up CloudService event handlers: ${error instanceof Error ? error.message : String(error)}`,
// )
// }
// }
// const bridge = BridgeOrchestrator.getInstance()
// if (bridge) {
// await bridge.disconnect()
// }
await McpServerManager.cleanup(extensionContext)
TelemetryService.instance.shutdown()
TerminalRegistry.cleanup()
}