-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathutils.ts
More file actions
410 lines (348 loc) · 13 KB
/
utils.ts
File metadata and controls
410 lines (348 loc) · 13 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
import { CreateUIMessage, TextUIPart, UIMessagePart } from "ai";
import { Descendant, Editor, Point, Range, Transforms } from "slate";
import { ANSWER_TAG, FILE_REFERENCE_PREFIX, FILE_REFERENCE_REGEX } from "./constants";
import { getBrowsePath, BrowseHighlightRange } from "@/app/[domain]/browse/hooks/utils";
import { SINGLE_TENANT_ORG_DOMAIN } from "@/lib/constants";
import {
CustomEditor,
CustomText,
FileReference,
FileSource,
LanguageModelInfo,
MentionData,
MentionElement,
ParagraphElement,
SBChatMessage,
SBChatMessagePart,
SBChatMessageToolTypes,
SearchScope,
Source,
} from "./types";
export const insertMention = (editor: CustomEditor, data: MentionData, target?: Range | null) => {
const mention: MentionElement = {
type: 'mention',
data,
children: [{ text: '' }],
}
if (target) {
Transforms.select(editor, target)
}
Transforms.insertNodes(editor, mention)
Transforms.move(editor)
}
// @see: https://github.com/ianstormtaylor/slate/issues/4162#issuecomment-1127062098
export function word(
editor: CustomEditor,
location: Range,
options: {
terminator?: string[]
include?: boolean
directions?: 'both' | 'left' | 'right'
} = {},
): Range | undefined {
const { terminator = [' '], include = false, directions = 'both' } = options
const { selection } = editor
if (!selection) return
// Get start and end, modify it as we move along.
let [start, end] = Range.edges(location)
let point: Point = start
function move(direction: 'right' | 'left'): boolean {
const next =
direction === 'right'
? Editor.after(editor, point, {
unit: 'character',
})
: Editor.before(editor, point, { unit: 'character' })
const wordNext =
next &&
Editor.string(
editor,
direction === 'right' ? { anchor: point, focus: next } : { anchor: next, focus: point },
)
const last = wordNext && wordNext[direction === 'right' ? 0 : wordNext.length - 1]
if (next && last && !terminator.includes(last)) {
point = next
if (point.offset === 0) {
// Means we've wrapped to beginning of another block
return false
}
} else {
return false
}
return true
}
// Move point and update start & end ranges
// Move forwards
if (directions !== 'left') {
point = end
while (move('right'));
end = point
}
// Move backwards
if (directions !== 'right') {
point = start
while (move('left'));
start = point
}
if (include) {
return {
anchor: Editor.before(editor, start, { unit: 'offset' }) ?? start,
focus: Editor.after(editor, end, { unit: 'offset' }) ?? end,
}
}
return { anchor: start, focus: end }
}
export const isMentionElement = (element: Descendant): element is MentionElement => {
return 'type' in element && element.type === 'mention';
}
export const isCustomTextElement = (element: Descendant): element is CustomText => {
return 'text' in element && typeof element.text === 'string';
}
export const isParagraphElement = (element: Descendant): element is ParagraphElement => {
return 'type' in element && element.type === 'paragraph';
}
export const slateContentToString = (children: Descendant[]): string => {
return children.map((child) => {
if (isCustomTextElement(child)) {
return child.text;
}
else if (isMentionElement(child)) {
const { type } = child.data;
switch (type) {
case 'file':
return `${fileReferenceToString({ repo: child.data.repo, path: child.data.path })} `;
}
}
else if (isParagraphElement(child)) {
return `${slateContentToString(child.children)}\n`;
}
else {
return "";
}
}).join("");
}
export const getAllMentionElements = (children: Descendant[]): MentionElement[] => {
return children.flatMap((child) => {
if (isCustomTextElement(child)) {
return [];
}
if (isMentionElement(child)) {
return [child];
}
return getAllMentionElements(child.children);
});
}
// @see: https://stackoverflow.com/a/74102147
export const resetEditor = (editor: CustomEditor) => {
const point = { path: [0, 0], offset: 0 }
editor.selection = { anchor: point, focus: point };
editor.history = { redos: [], undos: [] };
editor.children = [{
type: "paragraph",
children: [{ text: "" }]
}];
}
export const addLineNumbers = (source: string, lineOffset = 1) => {
return source.split('\n').map((line, index) => `${index + lineOffset}:${line}`).join('\n');
}
export const truncateFileContent = (
source: string,
maxCharacters: number,
): { content: string; wasTruncated: boolean } => {
if (source.length <= maxCharacters) {
return { content: source, wasTruncated: false };
}
const cutoff = source.lastIndexOf('\n', maxCharacters);
const effectiveCutoff = cutoff > 0 ? cutoff : maxCharacters;
const truncated = source.substring(0, effectiveCutoff);
const totalLines = source.split('\n').length;
const includedLines = truncated.split('\n').length;
return {
content: truncated + `\n\n... [truncated: showing ${includedLines} of ${totalLines} lines]`,
wasTruncated: true,
};
};
const CONTEXT_WINDOW_ERROR_PATTERNS = [
/maximum context length/i,
/prompt is too long/i,
/context.?length.?exceeded/i,
/exceeds? the maximum.*tokens?/i,
/token.?limit/i,
/request.?too.?large/i,
/input.?too.?long/i,
/request payload size exceeds/i,
/max_tokens/i,
/reduce the length/i,
];
export const isContextWindowError = (errorMessage: string): boolean => {
return CONTEXT_WINDOW_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage));
};
export const CONTEXT_WINDOW_USER_MESSAGE =
'The conversation exceeded the model\'s context window limit. ' +
'Try removing some attached files, starting a new conversation, or switching to a model with a larger context window.';
export const createUIMessage = (text: string, mentions: MentionData[], selectedSearchScopes: SearchScope[]): CreateUIMessage<SBChatMessage> => {
// Converts applicable mentions into sources.
const sources: Source[] = mentions
.map((mention) => {
if (mention.type === 'file') {
const fileSource: FileSource = {
type: 'file',
path: mention.path,
repo: mention.repo,
name: mention.name,
language: mention.language,
revision: mention.revision,
}
return fileSource;
}
return undefined;
})
.filter((source) => source !== undefined);
return {
role: 'user',
parts: [
{
type: 'text',
text,
},
...sources.map((data) => ({
type: 'data-source',
data,
})) as UIMessagePart<{ source: Source }, SBChatMessageToolTypes>[],
],
metadata: {
selectedSearchScopes,
},
}
}
export const getFileReferenceId = ({ repo, path, range }: Omit<FileReference, 'type' | 'id'>) => {
return `file-reference-${repo}::${path}${range ? `-${range.startLine}-${range.endLine}` : ''}`;
}
export const fileReferenceToString = ({ repo, path, range }: Omit<FileReference, 'type' | 'id'>) => {
return `${FILE_REFERENCE_PREFIX}{${repo}::${path}${range ? `:${range.startLine}-${range.endLine}` : ''}}`;
}
export const createFileReference = ({ repo, path, startLine, endLine }: { repo: string, path: string, startLine?: string, endLine?: string }): FileReference => {
const range = startLine && endLine ? {
startLine: parseInt(startLine),
endLine: parseInt(endLine),
} : startLine ? {
startLine: parseInt(startLine),
endLine: parseInt(startLine),
} : undefined;
return {
type: 'file',
id: getFileReferenceId({ repo, path, range }),
repo,
path,
range,
}
}
/**
* Converts LLM text that includes references (e.g., @file:...) into a portable
* Markdown format. Practically, this means converting references into Markdown
* links and removing the answer tag.
*/
export const convertLLMOutputToPortableMarkdown = (text: string, baseUrl: string): string => {
return text
.replace(ANSWER_TAG, '')
.replace(FILE_REFERENCE_REGEX, (_, repo, fileName, startLine, endLine) => {
const displayName = fileName.split('/').pop() || fileName;
let linkText = displayName;
if (startLine) {
if (endLine && startLine !== endLine) {
linkText += `:${startLine}-${endLine}`;
} else {
linkText += `:${startLine}`;
}
}
// Construct highlight range for line numbers
const highlightRange: BrowseHighlightRange | undefined = startLine ? {
start: { lineNumber: parseInt(startLine) },
end: { lineNumber: parseInt(endLine || startLine) },
} : undefined;
// Construct full browse URL
const browsePath = getBrowsePath({
repoName: repo,
path: fileName,
pathType: 'blob',
domain: SINGLE_TENANT_ORG_DOMAIN,
highlightRange,
});
const fullUrl = `${baseUrl}${browsePath}`;
return `[${linkText}](${fullUrl})`;
})
.trim();
}
// Groups message parts into groups based on step-start delimiters.
export const groupMessageIntoSteps = (parts: SBChatMessagePart[]) => {
if (!parts || parts.length === 0) {
return [];
}
const steps: SBChatMessagePart[][] = [];
let currentStep: SBChatMessagePart[] = [];
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.type === 'step-start') {
if (currentStep.length > 0) {
steps.push([...currentStep]);
}
currentStep = [part];
} else {
currentStep.push(part);
}
}
if (currentStep.length > 0) {
steps.push(currentStep);
}
return steps;
}
// LLMs like to not follow instructions... this takes care of some common mistakes they tend to make.
export const repairReferences = (text: string): string => {
return text
// Fix missing colon: @file{...} -> @file:{...}
.replace(/@file\{([^}]+)\}/g, '@file:{$1}')
// Fix missing braces: @file:filename -> @file:{filename}
.replace(/@file:([^\s{]\S*?)(\s|[,;!?](?:\s|$)|\.(?:\s|$)|$)/g, '@file:{$1}$2')
// Fix multiple ranges: keep only first range
.replace(/@file:\{(.+?):(\d+-\d+),[\d,-]+\}/g, '@file:{$1:$2}')
// Fix malformed ranges
.replace(/@file:\{(.+?):(\d+)-(\d+)-(\d+)\}/g, '@file:{$1:$2-$3}')
// Fix extra closing parenthesis: @file:{...)} -> @file:{...}
.replace(/@file:\{([^}]+)\)\}/g, '@file:{$1}')
// Fix extra colon at end: @file:{...range:} -> @file:{...range}
.replace(/@file:\{(.+?):(\d+(?:-\d+)?):?\}/g, '@file:{$1:$2}')
// Fix inline code blocks around file references: `@file:{...}` -> @file:{...}
.replace(/`(@file:\{[^}]+\})`/g, '$1')
// Fix malformed inline code blocks: `@file:{...`} -> @file:{...}
.replace(/`(@file:\{[^`]+)`\}/g, '$1}');
};
// Attempts to find the part of the assistant's message
// that contains the answer.
export const getAnswerPartFromAssistantMessage = (message: SBChatMessage, isStreaming: boolean): TextUIPart | undefined => {
const lastTextPart = message.parts
.findLast((part) => part.type === 'text')
if (lastTextPart?.text.startsWith(ANSWER_TAG)) {
return lastTextPart;
}
// If the agent did not include the answer tag, then fallback to using the last text part.
// Only do this when we are no longer streaming since the agent may still be thinking.
if (!isStreaming && lastTextPart) {
return lastTextPart;
}
return undefined;
}
/**
* Generates a unique key given a LanguageModelInfo object.
*/
export const getLanguageModelKey = (model: LanguageModelInfo) => {
return `${model.provider}-${model.model}-${model.displayName}`;
}
/**
* Given a file reference and a list of file sources, attempts to resolve the file source that the reference points to.
*/
export const tryResolveFileReference = (reference: FileReference, sources: FileSource[]): FileSource | undefined => {
return sources.find(
(source) => source.repo.endsWith(reference.repo) &&
source.path.endsWith(reference.path)
);
}