-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathextension.ts
More file actions
655 lines (593 loc) · 20.6 KB
/
Copy pathextension.ts
File metadata and controls
655 lines (593 loc) · 20.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
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
import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
import OpenAI from "openai";
import MarkdownIt from "markdown-it";
import type { SessionMessage } from "./session";
import {
SessionManager,
getCompactPromptTokenThreshold,
type LlmStreamProgress,
type PermissionScope,
type SessionEntry,
type SkillInfo,
type UserPromptContent,
type UserToolPermission,
} from "./session";
import {
resolveSettingsSources,
type DeepcodingSettings,
type ReasoningEffort,
type ResolvedDeepcodingSettings,
} from "./settings";
import { setShellIfWindows } from "./common/shell-utils";
const DEFAULT_MODEL = "deepseek-v4-pro";
const DEFAULT_BASE_URL = "https://api.deepseek.com";
type ReasoningMessageParams = {
reasoning_content?: string;
};
const VALID_PERMISSION_SCOPES = new Set<PermissionScope>([
"read-in-cwd",
"read-out-cwd",
"write-in-cwd",
"write-out-cwd",
"delete-in-cwd",
"delete-out-cwd",
"query-git-log",
"mutate-git-log",
"network",
"mcp",
]);
class DeepcodingViewProvider implements vscode.WebviewViewProvider {
public static readonly viewType = "deepcode.chatView";
private readonly context: vscode.ExtensionContext;
private webviewView: vscode.WebviewView | undefined;
private readonly md: MarkdownIt;
private readonly sessionManager: SessionManager;
constructor(context: vscode.ExtensionContext) {
this.context = context;
this.md = new MarkdownIt({
html: false,
linkify: false,
breaks: true,
});
this.sessionManager = new SessionManager({
projectRoot: this.getWorkspaceRoot(),
createOpenAIClient: () => this.createOpenAIClient(),
getResolvedSettings: () => this.resolveCurrentSettings(),
renderMarkdown: (text) => this.md.render(text),
onAssistantMessage: (message: SessionMessage, shouldConnect: boolean) => {
if (!this.webviewView) {
return;
}
if (message.visible === false) {
return;
}
if (message.role !== "tool") {
const reasoningContent = (message.messageParams as ReasoningMessageParams | null)?.reasoning_content;
message.html = this.md.render(message.content || reasoningContent || "");
}
this.webviewView.webview.postMessage({ type: "appendMessage", message, shouldConnect });
},
onSessionEntryUpdated: (entry) => {
if (!this.webviewView) {
return;
}
this.webviewView.webview.postMessage({
type: "sessionStatus",
sessionId: entry.id,
status: entry.status,
askPermissions: entry.askPermissions,
processes: this.serializeProcesses(entry.processes),
tokenTelemetry: this.buildTokenTelemetry(entry),
});
},
onLlmStreamProgress: (progress: LlmStreamProgress) => {
if (!this.webviewView) {
return;
}
this.webviewView.webview.postMessage({
type: "llmStreamProgress",
progress,
});
},
});
void this.initializeMcpServers();
}
dispose(): void {
this.sessionManager.dispose();
}
resolveWebviewView(webviewView: vscode.WebviewView): void {
this.webviewView = webviewView;
webviewView.webview.options = {
enableScripts: true,
localResourceRoots: [this.context.extensionUri],
};
webviewView.webview.html = this.getWebviewHtml(webviewView.webview);
webviewView.webview.onDidReceiveMessage(async (message) => {
if (message?.type === "ready") {
// webview 已准备好,发送初始数据
this.loadInitialSession();
// 同时请求 skills 列表
this.sendSkillsList();
} else if (message?.type === "requestSkills") {
// 请求 skills 列表
this.sendSkillsList();
} else if (message?.type === "userPrompt") {
const prompt = String(message.prompt || "").trim();
const images = Array.isArray(message.images)
? message.images.filter((image: unknown): image is string => typeof image === "string" && image.length > 0)
: [];
const permissions = parseUserToolPermissions(message.permissions);
const alwaysAllows = parsePermissionScopes(message.alwaysAllows);
if (!prompt && images.length === 0 && permissions.length === 0 && alwaysAllows.length === 0) {
return;
}
// 获取 skills
const skills = message.skills || [];
await this.handlePrompt(prompt, skills, images, {
permissions: permissions.length > 0 ? permissions : undefined,
alwaysAllows: alwaysAllows.length > 0 ? alwaysAllows : undefined,
});
} else if (message?.type === "interrupt") {
// 中断当前会话
this.sessionManager.interruptActiveSession();
} else if (message?.type === "denyPermission") {
const sessionId = String(message.sessionId || this.sessionManager.getActiveSessionId() || "").trim();
if (sessionId) {
this.handlePermissionDenied(sessionId);
}
} else if (message?.type === "createNewSession") {
await this.createNewSession();
} else if (message?.type === "selectSession") {
const sessionId = String(message.sessionId || "").trim();
if (sessionId) {
this.loadSession(sessionId);
await this.sendSkillsList(sessionId);
}
} else if (message?.type === "backToList") {
this.showSessionsList();
} else if (message?.type === "openFile") {
const filePath = String(message.filePath || "").trim();
const line = Number(message.line || 1);
if (filePath) {
await this.openFileInEditor(filePath, line);
}
} else if (message?.type === "copyText") {
const text = String(message.text || "");
if (text) {
await vscode.env.clipboard.writeText(text);
}
}
});
}
private async loadInitialSession(): Promise<void> {
const sessions = this.sessionManager.listSessions();
const sessionsList = sessions.map((s) => ({
id: s.id,
summary: s.summary || "Untitled",
createTime: s.createTime,
updateTime: s.updateTime,
status: s.status,
}));
if (sessions.length === 0) {
// 没有历史会话,显示新对话界面
this.sendMessage({
type: "initializeEmpty",
sessions: sessionsList,
status: null,
tokenTelemetry: this.buildTokenTelemetry(null),
});
return;
}
// 显示最新的对话
const latestSession = sessions[0];
this.loadSession(latestSession.id);
}
private loadSession(sessionId: string): void {
const session = this.sessionManager.getSession(sessionId);
if (!session) {
return;
}
// 设置为活动会话
this.sessionManager.setActiveSessionId(sessionId);
const messages = this.sessionManager.listSessionMessages(sessionId);
// 获取所有会话列表
const sessions = this.sessionManager.listSessions();
const sessionsList = sessions.map((s) => ({
id: s.id,
summary: s.summary || "Untitled",
createTime: s.createTime,
updateTime: s.updateTime,
status: s.status,
}));
// 发送对话信息到 webview
this.sendMessage({
type: "loadSession",
sessionId,
summary: session.summary || "Untitled",
status: session.status,
askPermissions: session.askPermissions,
processes: this.serializeProcesses(session.processes),
tokenTelemetry: this.buildTokenTelemetry(session),
sessions: sessionsList,
messages: messages
.filter((m) => m.visible)
.map((m) => ({
role: m.role,
content: m.content,
html:
m.role !== "tool"
? this.md.render(m.content || (m.messageParams as ReasoningMessageParams | null)?.reasoning_content || "")
: undefined,
meta: m.meta,
})),
});
}
private showSessionsList(): void {
const sessions = this.sessionManager.listSessions();
this.sendMessage({
type: "showSessionsList",
sessions: sessions.map((s) => ({
id: s.id,
summary: s.summary || "Untitled",
createTime: s.createTime,
updateTime: s.updateTime,
status: s.status,
})),
});
}
private async createNewSession(): Promise<void> {
// 清除当前活动会话
this.sessionManager.setActiveSessionId(null);
// 获取所有会话列表
const sessions = this.sessionManager.listSessions();
const sessionsList = sessions.map((s) => ({
id: s.id,
summary: s.summary || "Untitled",
createTime: s.createTime,
updateTime: s.updateTime,
status: s.status,
}));
this.sendMessage({
type: "initializeEmpty",
sessions: sessionsList,
status: null,
tokenTelemetry: this.buildTokenTelemetry(null),
});
await this.sendSkillsList();
}
private sendMessage(message: unknown): void {
if (!this.webviewView) {
return;
}
this.webviewView.webview.postMessage(message);
}
private async sendSkillsList(sessionId?: string): Promise<void> {
if (!this.webviewView) {
return;
}
const skills = await this.sessionManager.listSkills(
sessionId ?? this.sessionManager.getActiveSessionId() ?? undefined
);
this.sendMessage({ type: "skillsList", skills });
}
private async handlePrompt(
prompt: string,
skills?: SkillInfo[],
imageUrls?: string[],
options: { permissions?: UserToolPermission[]; alwaysAllows?: PermissionScope[] } = {}
): Promise<void> {
if (!this.webviewView) {
return;
}
const webview = this.webviewView.webview;
const normalizedImages = Array.isArray(imageUrls) ? imageUrls.filter(Boolean) : [];
const displayPrompt = prompt || (normalizedImages.length > 0 ? "粘贴的图像" : "");
const isPermissionContinue =
prompt === "/continue" &&
normalizedImages.length === 0 &&
((options.permissions?.length ?? 0) > 0 || (options.alwaysAllows?.length ?? 0) > 0);
// 先显示用户消息(原始文本,不做 HTML 格式化)
if (displayPrompt && !isPermissionContinue) {
webview.postMessage({ type: "userMessage", content: displayPrompt });
}
webview.postMessage({ type: "loading", value: true });
try {
const userPrompt: UserPromptContent = {
text: prompt,
skills,
imageUrls: normalizedImages,
permissions: options.permissions,
alwaysAllows: options.alwaysAllows,
};
await this.sessionManager.handleUserPrompt(userPrompt);
await this.sendSkillsList();
const activeSessionId = this.sessionManager.getActiveSessionId();
const activeSession = activeSessionId ? this.sessionManager.getSession(activeSessionId) : null;
if (activeSessionId && activeSession) {
webview.postMessage({
type: "sessionStatus",
sessionId: activeSessionId,
status: activeSession.status,
askPermissions: activeSession.askPermissions,
processes: this.serializeProcesses(activeSession.processes),
tokenTelemetry: this.buildTokenTelemetry(activeSession),
});
}
// 发送更新后的会话列表(可能创建了新会话)
const sessions = this.sessionManager.listSessions();
const sessionsList = sessions.map((s) => ({
id: s.id,
summary: s.summary || "Untitled",
createTime: s.createTime,
updateTime: s.updateTime,
status: s.status,
}));
webview.postMessage({
type: "showSessionsList",
sessions: sessionsList,
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
webview.postMessage({
type: "assistant",
html: this.md.render(`Request failed: ${message}`),
});
} finally {
webview.postMessage({ type: "loading", value: false });
}
}
private handlePermissionDenied(sessionId: string): void {
this.sessionManager.denySessionPermission(sessionId);
const session = this.sessionManager.getSession(sessionId);
if (session) {
this.sendMessage({
type: "sessionStatus",
sessionId,
status: session.status,
askPermissions: session.askPermissions,
processes: this.serializeProcesses(session.processes),
tokenTelemetry: this.buildTokenTelemetry(session),
});
}
this.showSessionsList();
}
private createOpenAIClient(): {
client: OpenAI | null;
model: string;
baseURL: string;
thinkingEnabled: boolean;
reasoningEffort: ReasoningEffort;
debugLogEnabled: boolean;
notify?: string;
webSearchTool?: string;
env?: Record<string, string>;
machineId?: string;
} {
const settings = this.resolveCurrentSettings();
const { apiKey, baseURL, model, thinkingEnabled, reasoningEffort, debugLogEnabled, notify, webSearchTool, env } =
settings;
const machineId = vscode.env.machineId;
if (!apiKey) {
return {
client: null,
model,
baseURL,
thinkingEnabled,
reasoningEffort,
debugLogEnabled,
notify,
webSearchTool,
env,
machineId,
};
}
const client = new OpenAI({
apiKey,
baseURL: baseURL || undefined,
defaultHeaders: settings.headers,
});
return {
client,
model,
baseURL,
thinkingEnabled,
reasoningEffort,
debugLogEnabled,
notify,
webSearchTool,
env,
machineId,
};
}
private buildTokenTelemetry(session: SessionEntry | null): {
model: string;
thinkingEnabled: boolean;
reasoningEffort: ReasoningEffort;
activeTokens: number;
compactPromptTokenThreshold: number;
usage: unknown | null;
} {
const settings = this.resolveCurrentSettings();
return {
model: settings.model,
thinkingEnabled: settings.thinkingEnabled,
reasoningEffort: settings.reasoningEffort,
activeTokens: session?.activeTokens ?? 0,
compactPromptTokenThreshold: getCompactPromptTokenThreshold(settings.model),
usage: session?.usage ?? null,
};
}
private async initializeMcpServers(): Promise<void> {
try {
await this.sessionManager.initMcpServers(this.resolveCurrentSettings().mcpServers);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
void vscode.window.showErrorMessage(`Failed to initialize MCP servers: ${message}`);
}
}
private resolveCurrentSettings(): ResolvedDeepcodingSettings {
return resolveSettingsSources(
this.readUserSettings(),
this.readProjectSettings(),
{
model: DEFAULT_MODEL,
baseURL: DEFAULT_BASE_URL,
},
process.env
);
}
private readUserSettings(): DeepcodingSettings | null {
try {
const settingsPath = path.join(os.homedir(), ".deepcode", "settings.json");
if (!fs.existsSync(settingsPath)) {
return null;
}
const raw = fs.readFileSync(settingsPath, "utf8");
return JSON.parse(raw) as DeepcodingSettings;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
vscode.window.showErrorMessage(`Failed to read ~/.deepcode/settings.json: ${message}`);
return null;
}
}
private readProjectSettings(): DeepcodingSettings | null {
const workspaceRoot = this.getWorkspaceRoot();
try {
const settingsPath = path.join(workspaceRoot, ".deepcode", "settings.json");
if (!fs.existsSync(settingsPath)) {
return null;
}
const raw = fs.readFileSync(settingsPath, "utf8");
return JSON.parse(raw) as DeepcodingSettings;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
vscode.window.showErrorMessage(
`Failed to read ${path.join(workspaceRoot, ".deepcode", "settings.json")}: ${message}`
);
return null;
}
}
private getWorkspaceRoot(): string {
const workspace = vscode.workspace.workspaceFolders?.[0];
if (workspace) {
return workspace.uri.fsPath;
}
return process.cwd();
}
private serializeProcesses(
processes: Map<string, { startTime: string; command: string }> | null
): Record<string, { startTime: string; command: string }> | null {
if (!processes || processes.size === 0) {
return null;
}
const serialized: Record<string, { startTime: string; command: string }> = {};
for (const [pid, entry] of processes.entries()) {
serialized[pid] = entry;
}
return serialized;
}
private getWebviewHtml(webview: vscode.Webview): string {
const nonce = getNonce();
const csp = webview.cspSource;
// 读取 HTML 模板文件
const htmlPath = vscode.Uri.joinPath(this.context.extensionUri, "resources", "webview.html");
let html = fs.readFileSync(htmlPath.fsPath, "utf8");
// 获取 CSS 文件 URI
const cssPath = vscode.Uri.joinPath(this.context.extensionUri, "resources", "webview.css");
const cssUri = webview.asWebviewUri(cssPath);
const attachmentsJsPath = vscode.Uri.joinPath(this.context.extensionUri, "resources", "prompt-attachments.js");
const attachmentsJsUri = webview.asWebviewUri(attachmentsJsPath);
// 获取 Logo 文件 URI
const iconPath = vscode.Uri.joinPath(this.context.extensionUri, "resources", "deepcoding_icon.png");
const iconUri = webview.asWebviewUri(iconPath);
// 替换占位符
html = html.replace(/\{\{nonce\}\}/g, nonce);
html = html.replace(/\{\{cspSource\}\}/g, csp);
html = html.replace(/\{\{cssUri\}\}/g, cssUri.toString());
html = html.replace(/\{\{attachmentsJsUri\}\}/g, attachmentsJsUri.toString());
html = html.replace(/\{\{iconUri\}\}/g, iconUri.toString());
html = html.replace(/\{\{workspaceRoot\}\}/g, JSON.stringify(this.getWorkspaceRoot()));
return html;
}
private async openFileInEditor(filePath: string, line: number): Promise<void> {
const document = await vscode.workspace.openTextDocument(vscode.Uri.file(filePath));
const editor = await vscode.window.showTextDocument(document, {
preview: false,
preserveFocus: false,
});
const targetLine = Number.isFinite(line) && line > 0 ? Math.floor(line) - 1 : 0;
const safeLine = Math.min(Math.max(0, targetLine), Math.max(0, document.lineCount - 1));
const position = new vscode.Position(safeLine, 0);
const selection = new vscode.Selection(position, position);
editor.selection = selection;
editor.revealRange(new vscode.Range(position, position), vscode.TextEditorRevealType.InCenter);
}
}
function parseUserToolPermissions(value: unknown): UserToolPermission[] {
if (!Array.isArray(value)) {
return [];
}
const result: UserToolPermission[] = [];
for (const item of value) {
if (!item || typeof item !== "object") {
continue;
}
const record = item as { toolCallId?: unknown; permission?: unknown };
if (typeof record.toolCallId !== "string" || !record.toolCallId.trim()) {
continue;
}
if (record.permission !== "allow" && record.permission !== "deny") {
continue;
}
result.push({ toolCallId: record.toolCallId, permission: record.permission });
}
return result;
}
function parsePermissionScopes(value: unknown): PermissionScope[] {
if (!Array.isArray(value)) {
return [];
}
const result: PermissionScope[] = [];
for (const item of value) {
if (typeof item !== "string" || !VALID_PERMISSION_SCOPES.has(item as PermissionScope)) {
continue;
}
const scope = item as PermissionScope;
if (!result.includes(scope)) {
result.push(scope);
}
}
return result;
}
export function activate(context: vscode.ExtensionContext): void {
process.env.NoDefaultCurrentDirectoryInExePath = "1";
try {
setShellIfWindows();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
void vscode.window.showErrorMessage(message);
}
const provider = new DeepcodingViewProvider(context);
context.subscriptions.push(provider);
context.subscriptions.push(vscode.window.registerWebviewViewProvider(DeepcodingViewProvider.viewType, provider));
context.subscriptions.push(
vscode.commands.registerCommand("deepcode.openView", async () => {
await vscode.commands.executeCommand("workbench.view.extension.deepcode");
await vscode.commands.executeCommand("deepcode.chatView.focus");
})
);
}
export function deactivate(): void {
// no-op
}
function getNonce(): string {
let text = "";
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i += 1) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}