Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/workbench/contrib/chat/common/widget/annotations.ts
5220 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
import { MarkdownString } from '../../../../../base/common/htmlContent.js';
6
import { basename } from '../../../../../base/common/resources.js';
7
import { URI } from '../../../../../base/common/uri.js';
8
import { IRange } from '../../../../../editor/common/core/range.js';
9
import { isLocation } from '../../../../../editor/common/languages.js';
10
import { IChatProgressRenderableResponseContent, IChatProgressResponseContent, appendMarkdownString, canMergeMarkdownStrings } from '../model/chatModel.js';
11
import { IChatAgentVulnerabilityDetails } from '../chatService/chatService.js';
12
13
export const contentRefUrl = 'http://_vscodecontentref_'; // must be lowercase for URI
14
15
export function annotateSpecialMarkdownContent(response: Iterable<IChatProgressResponseContent>): IChatProgressRenderableResponseContent[] {
16
let refIdPool = 0;
17
18
const result: IChatProgressRenderableResponseContent[] = [];
19
for (const item of response) {
20
const previousItemIndex = result.findLastIndex(p => p.kind !== 'textEditGroup' && p.kind !== 'undoStop');
21
const previousItem = result[previousItemIndex];
22
if (item.kind === 'inlineReference') {
23
let label: string | undefined = item.name;
24
if (!label) {
25
if (URI.isUri(item.inlineReference)) {
26
label = basename(item.inlineReference);
27
} else if (isLocation(item.inlineReference)) {
28
label = basename(item.inlineReference.uri);
29
} else {
30
label = item.inlineReference.name;
31
}
32
}
33
34
const refId = refIdPool++;
35
const printUri = URI.parse(contentRefUrl).with({ path: String(refId) });
36
const markdownText = `[${label}](${printUri.toString()})`;
37
38
const annotationMetadata = { [refId]: item };
39
40
if (previousItem?.kind === 'markdownContent') {
41
const merged = appendMarkdownString(previousItem.content, new MarkdownString(markdownText));
42
result[previousItemIndex] = { ...previousItem, content: merged, inlineReferences: { ...annotationMetadata, ...(previousItem.inlineReferences || {}) } };
43
} else {
44
result.push({ content: new MarkdownString(markdownText), inlineReferences: annotationMetadata, kind: 'markdownContent' });
45
}
46
} else if (item.kind === 'markdownContent' && previousItem?.kind === 'markdownContent' && canMergeMarkdownStrings(previousItem.content, item.content)) {
47
const merged = appendMarkdownString(previousItem.content, item.content);
48
result[previousItemIndex] = { ...previousItem, content: merged };
49
} else if (item.kind === 'markdownVuln') {
50
const vulnText = encodeURIComponent(JSON.stringify(item.vulnerabilities));
51
const markdownText = `<vscode_annotation details='${vulnText}'>${item.content.value}</vscode_annotation>`;
52
if (previousItem?.kind === 'markdownContent') {
53
// Since this is inside a codeblock, it needs to be merged into the previous markdown content.
54
const merged = appendMarkdownString(previousItem.content, new MarkdownString(markdownText));
55
result[previousItemIndex] = { ...previousItem, content: merged };
56
} else {
57
result.push({ content: new MarkdownString(markdownText), kind: 'markdownContent' });
58
}
59
} else if (item.kind === 'codeblockUri') {
60
if (previousItem?.kind === 'markdownContent') {
61
const isEditText = item.isEdit ? ` isEdit` : '';
62
const subAgentText = item.subAgentInvocationId ? ` subAgentInvocationId="${encodeURIComponent(item.subAgentInvocationId)}"` : '';
63
const markdownText = `<vscode_codeblock_uri${isEditText}${subAgentText}>${item.uri.toString()}</vscode_codeblock_uri>`;
64
const merged = appendMarkdownString(previousItem.content, new MarkdownString(markdownText));
65
// delete the previous and append to ensure that we don't reorder the edit before the undo stop containing it
66
result.splice(previousItemIndex, 1);
67
result.push({ ...previousItem, content: merged });
68
}
69
} else {
70
result.push(item);
71
}
72
}
73
74
return result;
75
}
76
77
export interface IMarkdownVulnerability {
78
readonly title: string;
79
readonly description: string;
80
readonly range: IRange;
81
}
82
export function extractCodeblockUrisFromText(text: string): { uri: URI; isEdit?: boolean; subAgentInvocationId?: string; textWithoutResult: string } | undefined {
83
const match = /<vscode_codeblock_uri( isEdit)?( subAgentInvocationId="([^"]*)")?>([\s\S]*?)<\/vscode_codeblock_uri>/ms.exec(text);
84
if (match) {
85
const [all, isEdit, , encodedSubAgentId, uriString] = match;
86
if (uriString) {
87
const result = URI.parse(uriString);
88
const textWithoutResult = text.substring(0, match.index) + text.substring(match.index + all.length);
89
let subAgentInvocationId: string | undefined;
90
if (encodedSubAgentId) {
91
try {
92
subAgentInvocationId = decodeURIComponent(encodedSubAgentId);
93
} catch {
94
subAgentInvocationId = encodedSubAgentId;
95
}
96
}
97
return { uri: result, textWithoutResult, isEdit: !!isEdit, subAgentInvocationId };
98
}
99
}
100
return undefined;
101
}
102
103
export function extractSubAgentInvocationIdFromText(text: string): string | undefined {
104
const match = /<vscode_codeblock_uri[^>]* subAgentInvocationId="([^"]*)"/ms.exec(text);
105
if (match) {
106
try {
107
return decodeURIComponent(match[1]);
108
} catch {
109
return match[1];
110
}
111
}
112
return undefined;
113
}
114
115
export function hasCodeblockUriTag(text: string): boolean {
116
return text.includes('<vscode_codeblock_uri');
117
}
118
119
export function extractVulnerabilitiesFromText(text: string): { newText: string; vulnerabilities: IMarkdownVulnerability[] } {
120
const vulnerabilities: IMarkdownVulnerability[] = [];
121
let newText = text;
122
let match: RegExpExecArray | null;
123
while ((match = /<vscode_annotation details='(.*?)'>(.*?)<\/vscode_annotation>/ms.exec(newText)) !== null) {
124
const [full, details, content] = match;
125
const start = match.index;
126
const textBefore = newText.substring(0, start);
127
const linesBefore = textBefore.split('\n').length - 1;
128
const linesInside = content.split('\n').length - 1;
129
130
const previousNewlineIdx = textBefore.lastIndexOf('\n');
131
const startColumn = start - (previousNewlineIdx + 1) + 1;
132
const endPreviousNewlineIdx = (textBefore + content).lastIndexOf('\n');
133
const endColumn = start + content.length - (endPreviousNewlineIdx + 1) + 1;
134
135
try {
136
const vulnDetails: IChatAgentVulnerabilityDetails[] = JSON.parse(decodeURIComponent(details));
137
vulnDetails.forEach(({ title, description }) => vulnerabilities.push({
138
title, description, range: { startLineNumber: linesBefore + 1, startColumn, endLineNumber: linesBefore + linesInside + 1, endColumn }
139
}));
140
} catch (err) {
141
// Something went wrong with encoding this text, just ignore it
142
}
143
newText = newText.substring(0, start) + content + newText.substring(start + full.length);
144
}
145
146
return { newText, vulnerabilities };
147
}
148
149