monacopilot 0.11.5 → 0.11.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -8
- package/build/index.d.mts +208 -83
- package/build/index.d.ts +208 -83
- package/build/index.js +99 -41
- package/build/index.mjs +99 -41
- package/package.json +1 -1
package/build/index.d.ts
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
2
2
|
import * as monaco_editor from 'monaco-editor';
|
|
3
3
|
|
|
4
|
+
type CurrentFileName = string;
|
|
5
|
+
type Technologies = string[];
|
|
6
|
+
type RelatedFile = {
|
|
7
|
+
/**
|
|
8
|
+
* The relative path from the current editing code in the editor to an external file.
|
|
9
|
+
*
|
|
10
|
+
* Examples:
|
|
11
|
+
* - To include a file `utils.js` in the same directory, set as `./utils.js`.
|
|
12
|
+
* - To include a file `utils.js` in the parent directory, set as `../utils.js`.
|
|
13
|
+
* - To include a file `utils.js` in the child directory, set as `./child/utils.js`.
|
|
14
|
+
*/
|
|
15
|
+
path: string;
|
|
16
|
+
/**
|
|
17
|
+
* The content of the external file as a string.
|
|
18
|
+
*/
|
|
19
|
+
content: string;
|
|
20
|
+
};
|
|
21
|
+
type Context = {
|
|
22
|
+
/**
|
|
23
|
+
* The programming language of the current file being edited.
|
|
24
|
+
*/
|
|
25
|
+
currentLanguage: string;
|
|
26
|
+
/**
|
|
27
|
+
* The resolved programming language of the current file being edited.
|
|
28
|
+
* This is used to provide more specific language-based completions and suggestions,
|
|
29
|
+
* especially when the initial language might be ambiguous (e.g., 'javascript' could be resolved to 'JavaScript (ES2024)').
|
|
30
|
+
*/
|
|
31
|
+
resolvedCurrentLanguage: string;
|
|
32
|
+
/**
|
|
33
|
+
* The name of the file you are currently editing.
|
|
34
|
+
*/
|
|
35
|
+
currentFileName?: CurrentFileName;
|
|
36
|
+
/**
|
|
37
|
+
* The related files with the adjusted maximum lines.
|
|
38
|
+
*/
|
|
39
|
+
relatedFiles?: RelatedFile[];
|
|
40
|
+
/**
|
|
41
|
+
* The technologies (libraries, frameworks, etc.) you want to use for the completion.
|
|
42
|
+
* This can provide technology-specific completions.
|
|
43
|
+
* If you don't specify a technology, the completion will be specific to the language (provided as the `language`).
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ['react', 'nextjs', 'tailwindcss', 'tanstack/react-query']
|
|
47
|
+
* ['tensorflow', 'keras', 'numpy', 'pandas']
|
|
48
|
+
* etc.
|
|
49
|
+
*/
|
|
50
|
+
technologies?: Technologies;
|
|
51
|
+
/**
|
|
52
|
+
* The maximum number of lines of code to include in the context sent to the Language Model (LLM).
|
|
53
|
+
* This helps to reduce the cost of the completion request.
|
|
54
|
+
*
|
|
55
|
+
* @default undefined - No limit is applied if not specified
|
|
56
|
+
*/
|
|
57
|
+
maxContextLines?: number;
|
|
58
|
+
};
|
|
59
|
+
type BuildContextOptions = Omit<Context, 'resolvedCurrentLanguage'>;
|
|
60
|
+
|
|
4
61
|
type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-preview' | 'o1-mini';
|
|
5
62
|
type GroqModel = 'llama-3-70b';
|
|
6
63
|
type AnthropicModel = 'claude-3.5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' | 'claude-3-sonnet';
|
|
@@ -83,38 +140,26 @@ type CustomCopilotModelTransformResponse = (response: unknown) => {
|
|
|
83
140
|
*/
|
|
84
141
|
completion: string | null;
|
|
85
142
|
};
|
|
143
|
+
type CustomPrompt<T> = (metadata: T) => Partial<PromptData>;
|
|
86
144
|
|
|
87
145
|
type Monaco = typeof monaco;
|
|
88
146
|
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
89
147
|
type CursorPosition = monaco.IPosition;
|
|
148
|
+
type EditorSelection = monaco.Selection;
|
|
90
149
|
|
|
91
150
|
type Endpoint = string;
|
|
92
|
-
type Filename = string;
|
|
93
|
-
type Technologies = string[];
|
|
94
|
-
type RelatedFile = {
|
|
95
|
-
/**
|
|
96
|
-
* The relative path from the current editing code in the editor to an external file.
|
|
97
|
-
*
|
|
98
|
-
* Examples:
|
|
99
|
-
* - To include a file `utils.js` in the same directory, set as `./utils.js`.
|
|
100
|
-
* - To include a file `utils.js` in the parent directory, set as `../utils.js`.
|
|
101
|
-
* - To include a file `utils.js` in the child directory, set as `./child/utils.js`.
|
|
102
|
-
*/
|
|
103
|
-
path: string;
|
|
104
|
-
/**
|
|
105
|
-
* The content of the external file as a string.
|
|
106
|
-
*/
|
|
107
|
-
content: string;
|
|
108
|
-
};
|
|
109
151
|
interface RegisterCompletionOptions {
|
|
110
152
|
/**
|
|
111
|
-
*
|
|
153
|
+
* The API endpoint to fetch the completion item from.
|
|
112
154
|
*/
|
|
113
|
-
|
|
155
|
+
endpoint: Endpoint;
|
|
114
156
|
/**
|
|
115
|
-
* The
|
|
157
|
+
* The context object containing contextual information for generating relevant completions.
|
|
158
|
+
|
|
159
|
+
* This object is created by the `buildContext` function from monacopilot.
|
|
160
|
+
* It helps tailor completions to the specific project environment and coding context.
|
|
116
161
|
*/
|
|
117
|
-
|
|
162
|
+
context: Context;
|
|
118
163
|
/**
|
|
119
164
|
* Specifies when the completion service should provide code completions.
|
|
120
165
|
*
|
|
@@ -128,36 +173,6 @@ interface RegisterCompletionOptions {
|
|
|
128
173
|
* @default 'onIdle'
|
|
129
174
|
*/
|
|
130
175
|
trigger?: 'onTyping' | 'onIdle' | 'onDemand';
|
|
131
|
-
/**
|
|
132
|
-
* The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
|
|
133
|
-
* For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
|
|
134
|
-
*/
|
|
135
|
-
filename?: Filename;
|
|
136
|
-
/**
|
|
137
|
-
* The technologies (libraries, frameworks, etc.) you want to use for the completion.
|
|
138
|
-
* This can provide technology-specific completions.
|
|
139
|
-
* If you don't specify a technology, the completion will be specific to the language (provided as the `language`).
|
|
140
|
-
*
|
|
141
|
-
* @example
|
|
142
|
-
* ['react', 'nextjs', 'tailwindcss', 'tanstack/react-query']
|
|
143
|
-
* ['tensorflow', 'keras', 'numpy', 'pandas']
|
|
144
|
-
* etc.
|
|
145
|
-
*/
|
|
146
|
-
technologies?: Technologies;
|
|
147
|
-
/**
|
|
148
|
-
* Helps to give more relevant completions based on the full context.
|
|
149
|
-
* You can include things like the contents/codes of other files in the same workspace.
|
|
150
|
-
*/
|
|
151
|
-
relatedFiles?: RelatedFile[];
|
|
152
|
-
/**
|
|
153
|
-
* The maximum number of lines of code to include in the completion request.
|
|
154
|
-
* This limits the request size to the model to prevent `429 Too Many Requests` errors
|
|
155
|
-
* and reduce costs for long code.
|
|
156
|
-
*
|
|
157
|
-
* It is recommended to set `maxContextLines` to `60` or less if you are using `Groq` as your provider,
|
|
158
|
-
* since `Groq` does not implement pay-as-you-go pricing and has only low rate limits.
|
|
159
|
-
*/
|
|
160
|
-
maxContextLines?: number;
|
|
161
176
|
/**
|
|
162
177
|
* Callback function that is called when an error occurs during the completion request.
|
|
163
178
|
* This function allows you to handle errors gracefully and provide appropriate feedback to the user.
|
|
@@ -188,23 +203,23 @@ interface CompletionRegistration {
|
|
|
188
203
|
*/
|
|
189
204
|
deregister: () => void;
|
|
190
205
|
}
|
|
191
|
-
interface
|
|
206
|
+
interface CompletionApiRequest {
|
|
192
207
|
/**
|
|
193
208
|
* The body of the completion request.
|
|
194
209
|
*/
|
|
195
|
-
body:
|
|
210
|
+
body: CompletionApiRequestBody;
|
|
196
211
|
/**
|
|
197
212
|
* Additional options to include in the completion request.
|
|
198
213
|
*/
|
|
199
|
-
options?:
|
|
214
|
+
options?: CompletionApiRequestOptions;
|
|
200
215
|
}
|
|
201
|
-
interface
|
|
216
|
+
interface CompletionApiRequestBody {
|
|
202
217
|
/**
|
|
203
218
|
* The metadata required to generate the completion.
|
|
204
219
|
*/
|
|
205
|
-
|
|
220
|
+
metadata: CompletionMetadata;
|
|
206
221
|
}
|
|
207
|
-
interface
|
|
222
|
+
interface CompletionApiRequestOptions {
|
|
208
223
|
/**
|
|
209
224
|
* Custom headers to include in the request to the AI provider.
|
|
210
225
|
*/
|
|
@@ -214,34 +229,21 @@ interface CompletionRequestOptions {
|
|
|
214
229
|
* This function allows you to override the default system and user prompts
|
|
215
230
|
* used in the completion request, providing more control over the AI's context and behavior.
|
|
216
231
|
*
|
|
217
|
-
* @param
|
|
232
|
+
* @param metadata - Metadata about the current completion context
|
|
218
233
|
* @returns An object containing custom 'system' and 'user' prompts
|
|
219
234
|
*/
|
|
220
|
-
customPrompt?: CustomPrompt
|
|
235
|
+
customPrompt?: CustomPrompt<CompletionMetadata>;
|
|
221
236
|
}
|
|
222
|
-
|
|
223
|
-
interface CompletionResponse {
|
|
237
|
+
interface CompletionApiResponse {
|
|
224
238
|
completion: string | null;
|
|
225
239
|
error?: string;
|
|
226
240
|
}
|
|
227
241
|
type CompletionMode = 'insert' | 'complete' | 'continue';
|
|
228
242
|
interface CompletionMetadata {
|
|
229
243
|
/**
|
|
230
|
-
* The
|
|
231
|
-
*/
|
|
232
|
-
language: string | undefined;
|
|
233
|
-
/**
|
|
234
|
-
* The name of the file being edited.
|
|
235
|
-
*/
|
|
236
|
-
filename: Filename | undefined;
|
|
237
|
-
/**
|
|
238
|
-
* The technologies used in the completion.
|
|
239
|
-
*/
|
|
240
|
-
technologies: Technologies | undefined;
|
|
241
|
-
/**
|
|
242
|
-
* Additional context from related files.
|
|
244
|
+
* The context object containing contextual information for generating relevant completions.
|
|
243
245
|
*/
|
|
244
|
-
|
|
246
|
+
context?: Context;
|
|
245
247
|
/**
|
|
246
248
|
* The text that appears after the cursor.
|
|
247
249
|
*/
|
|
@@ -258,11 +260,6 @@ interface CompletionMetadata {
|
|
|
258
260
|
* The current state of the editor.
|
|
259
261
|
*/
|
|
260
262
|
editorState: {
|
|
261
|
-
/**
|
|
262
|
-
* The mode of the completion.
|
|
263
|
-
* - `fill-in-the-middle`: Indicates that the cursor is positioned within the existing text. In this mode, the AI will generate content to be inserted at the cursor position.
|
|
264
|
-
* - `completion`: Indicates that the cursor is at the end of the existing text. In this mode, the AI will generate content to continue or complete the text from the cursor position.
|
|
265
|
-
*/
|
|
266
263
|
completionMode: CompletionMode;
|
|
267
264
|
};
|
|
268
265
|
}
|
|
@@ -272,7 +269,114 @@ type FetchCompletionItemReturn = {
|
|
|
272
269
|
};
|
|
273
270
|
interface FetchCompletionItemParams {
|
|
274
271
|
endpoint: string;
|
|
275
|
-
body:
|
|
272
|
+
body: CompletionApiRequestBody;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
interface SelectionActionsRegistration {
|
|
276
|
+
deregister: () => void;
|
|
277
|
+
}
|
|
278
|
+
type SelectionAction = 'modify';
|
|
279
|
+
interface RegisterSelectionActionsOptions {
|
|
280
|
+
actions: SelectionAction[];
|
|
281
|
+
modify: ModifyOptions;
|
|
282
|
+
onError?: (error: Error) => void;
|
|
283
|
+
}
|
|
284
|
+
interface ModifyOptions {
|
|
285
|
+
/**
|
|
286
|
+
* The API endpoint to fetch the modified text from.
|
|
287
|
+
*/
|
|
288
|
+
endpoint: string;
|
|
289
|
+
/**
|
|
290
|
+
* The context object containing contextual information for generating relevant modifications.
|
|
291
|
+
*/
|
|
292
|
+
context: Context;
|
|
293
|
+
/**
|
|
294
|
+
* The text to display as a placeholder in the text area where users input their modification instructions.
|
|
295
|
+
*/
|
|
296
|
+
placeholder?: string;
|
|
297
|
+
/**
|
|
298
|
+
* Custom fetch modified text handler. This function overrides the default modified text fetch handler.
|
|
299
|
+
* It allows you to customize how modified text requests are made and responses are processed.
|
|
300
|
+
* You can implement your own logic for fetching and processing modified text.
|
|
301
|
+
* The function should return either a string (the modified text to be replaced with the selected text) or null.
|
|
302
|
+
* @param params - The parameters for the modified text request.
|
|
303
|
+
* @param {string} params.endpoint - The endpoint to fetch the modified text from.
|
|
304
|
+
* @param {ModifyApiRequestBody} params.body - The body of the modified text request.
|
|
305
|
+
* @returns {Promise<{modifiedText: string | null}>} An object containing the modified text or null if no modified text is available.
|
|
306
|
+
*/
|
|
307
|
+
requestHandler?: FetchModifiedTextHandler;
|
|
308
|
+
}
|
|
309
|
+
interface ModifyMetadata {
|
|
310
|
+
/**
|
|
311
|
+
* The context object containing contextual information for generating relevant modifications.
|
|
312
|
+
*/
|
|
313
|
+
context?: Context;
|
|
314
|
+
/**
|
|
315
|
+
* The full text of the current file.
|
|
316
|
+
*/
|
|
317
|
+
fullText: string;
|
|
318
|
+
/**
|
|
319
|
+
* The selected text range in the file.
|
|
320
|
+
*/
|
|
321
|
+
selection: EditorSelection | null;
|
|
322
|
+
/**
|
|
323
|
+
* The selected text.
|
|
324
|
+
* This will be null if the user has a cursor position and no text is selected.
|
|
325
|
+
*/
|
|
326
|
+
selectedText: string | null;
|
|
327
|
+
/**
|
|
328
|
+
* The current cursor position.
|
|
329
|
+
*/
|
|
330
|
+
cursorPosition: CursorPosition | null;
|
|
331
|
+
/**
|
|
332
|
+
* The text before the cursor position.
|
|
333
|
+
* This will be null if the user has selected text instead of having a cursor position.
|
|
334
|
+
*/
|
|
335
|
+
textBeforeCursor: string | null;
|
|
336
|
+
/**
|
|
337
|
+
* The text after the cursor position.
|
|
338
|
+
* This will be null if the user has selected text instead of having a cursor position.
|
|
339
|
+
*/
|
|
340
|
+
textAfterCursor: string | null;
|
|
341
|
+
/**
|
|
342
|
+
* The user-provided instructions for modifying the selected text.
|
|
343
|
+
*/
|
|
344
|
+
prompt: string;
|
|
345
|
+
}
|
|
346
|
+
interface FetchModifiedTextParams {
|
|
347
|
+
endpoint: string;
|
|
348
|
+
body: ModifyApiRequestBody;
|
|
349
|
+
}
|
|
350
|
+
interface FetchModifiedTextReturn {
|
|
351
|
+
modifiedText: string | null;
|
|
352
|
+
}
|
|
353
|
+
type FetchModifiedTextHandler = (params: FetchModifiedTextParams) => Promise<FetchModifiedTextReturn>;
|
|
354
|
+
interface ModifyApiRequest {
|
|
355
|
+
body: ModifyApiRequestBody;
|
|
356
|
+
options?: ModifyApiRequestOptions;
|
|
357
|
+
}
|
|
358
|
+
interface ModifyApiRequestOptions {
|
|
359
|
+
/**
|
|
360
|
+
* Custom headers to include in the request to the AI provider.
|
|
361
|
+
*/
|
|
362
|
+
headers?: Record<string, string>;
|
|
363
|
+
/**
|
|
364
|
+
* Custom prompt generator function for the modify request.
|
|
365
|
+
* This function allows you to override the default system and user prompts
|
|
366
|
+
* used in the modify request, providing more control over the AI's context and behavior.
|
|
367
|
+
*
|
|
368
|
+
* @param metadata - Metadata about the current modify context
|
|
369
|
+
* @returns An object containing custom 'system' and 'user' prompts
|
|
370
|
+
*/
|
|
371
|
+
customPrompt?: ModifyCustomPrompt;
|
|
372
|
+
}
|
|
373
|
+
type ModifyCustomPrompt = (metadata: ModifyMetadata) => Partial<PromptData>;
|
|
374
|
+
interface ModifyApiRequestBody {
|
|
375
|
+
metadata: ModifyMetadata;
|
|
376
|
+
}
|
|
377
|
+
interface ModifyApiResponse {
|
|
378
|
+
modifiedText: string | null;
|
|
379
|
+
error?: string;
|
|
276
380
|
}
|
|
277
381
|
|
|
278
382
|
declare class Copilot {
|
|
@@ -281,12 +385,16 @@ declare class Copilot {
|
|
|
281
385
|
private model;
|
|
282
386
|
constructor(apiKey: string, options?: CopilotOptions);
|
|
283
387
|
private validateInputs;
|
|
284
|
-
complete(request:
|
|
388
|
+
complete(request: CompletionApiRequest): Promise<CompletionApiResponse>;
|
|
389
|
+
modify(request: ModifyApiRequest): Promise<ModifyApiResponse>;
|
|
390
|
+
private makeApiCall;
|
|
285
391
|
private generatePrompt;
|
|
286
392
|
private prepareRequestDetails;
|
|
287
393
|
private sendCompletionRequest;
|
|
288
394
|
private processCompletionResponse;
|
|
395
|
+
private processModifyResponse;
|
|
289
396
|
private handleCompletionError;
|
|
397
|
+
private handleModifyError;
|
|
290
398
|
}
|
|
291
399
|
|
|
292
400
|
/**
|
|
@@ -302,4 +410,21 @@ declare const registerCompletion: (monaco: Monaco, editor: StandaloneCodeEditor,
|
|
|
302
410
|
*/
|
|
303
411
|
declare const registerCopilot: (monaco: typeof monaco_editor, editor: monaco_editor.editor.IStandaloneCodeEditor, options: RegisterCompletionOptions) => CompletionRegistration;
|
|
304
412
|
|
|
305
|
-
|
|
413
|
+
/**
|
|
414
|
+
* Registers the selection action functionality with the Monaco editor.
|
|
415
|
+
*
|
|
416
|
+
* @param monaco - The Monaco instance.
|
|
417
|
+
* @param editor - The editor instance.
|
|
418
|
+
* @param options - Options for the action functionality.
|
|
419
|
+
* @returns A SelectionActionsRegistration object with a deregister method.
|
|
420
|
+
*/
|
|
421
|
+
declare const registerSelectionActions: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterSelectionActionsOptions) => SelectionActionsRegistration;
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Builds a context object containing contextual information for generating relevant completions/suggestions.
|
|
425
|
+
* @param options - The options for building the context.
|
|
426
|
+
* @returns The context object.
|
|
427
|
+
*/
|
|
428
|
+
declare const buildContext: (options: BuildContextOptions) => Context;
|
|
429
|
+
|
|
430
|
+
export { type CompletionApiRequest, type CompletionApiRequestBody, type CompletionApiRequestOptions, type CompletionMetadata, type CompletionRegistration, type Context, Copilot, type CopilotModel, type CopilotOptions, type CopilotProvider, type CustomCopilotModel, type CustomCopilotModelConfig, type CustomCopilotModelTransformResponse, type Monaco, type RegisterCompletionOptions, type StandaloneCodeEditor, buildContext, registerCompletion, registerCopilot, registerSelectionActions };
|
package/build/index.js
CHANGED
|
@@ -1,46 +1,104 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`),n=
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
<
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
<current_file path="${t}">
|
|
23
|
-
<code>
|
|
24
|
-
${o}${Te}${r}
|
|
25
|
-
</code>
|
|
26
|
-
</current_file>
|
|
27
|
-
</context>
|
|
28
|
-
`,u=n?.map(({path:l,content:C})=>`
|
|
29
|
-
<related_file path="${l}">
|
|
30
|
-
<code>
|
|
31
|
-
${C}
|
|
32
|
-
</code>
|
|
1
|
+
"use strict";var z=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var rt=(t,e)=>{for(var o in e)z(t,o,{get:e[o],enumerable:!0})},st=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nt(e))!it.call(t,i)&&i!==o&&z(t,i,{get:()=>e[i],enumerable:!(n=ot(e,i))||n.enumerable});return t};var at=t=>st(z({},"__esModule",{value:!0}),t);var wt={};rt(wt,{Copilot:()=>$,buildContext:()=>et,registerCompletion:()=>le,registerCopilot:()=>_e,registerSelectionActions:()=>Qe});module.exports=at(wt);var Z=["groq","openai","anthropic"],ce={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3.5-sonnet":"claude-3.5-sonnet-20240620","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307","o1-preview":"o1-preview","o1-mini":"o1-mini"},Q={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-preview","o1-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},pe="llama-3-70b",me="groq",ue={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},N=.1;var Ce="diff-added-line",fe="diff-deleted-line",ee={isWholeLine:!0,showIfCollapsed:!0};var ge={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var dt={createRequestBody:(t,e)=>{let n=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:ne(t),temperature:N,messages:n}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},lt={createRequestBody:(t,e)=>({model:ne(t),temperature:N,messages:[{role:"system",content:e.system},{role:"user",content:e.user}]}),createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},ct={createRequestBody:(t,e)=>({model:ne(t),temperature:N,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:pt(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>!t.content||typeof t.content!="string"?null:t.content},te={openai:dt,groq:lt,anthropic:ct},he=(t,e,o)=>te[e].createRequestBody(t,o),Ee=(t,e)=>te[e].createHeaders(t),oe=(t,e)=>te[e].parseCompletion(t),ne=t=>ce[t],Te=t=>ue[t],pt=t=>ge[t]||4096;var g=class g{constructor(){}static getInstance(){return g.instance}error(e){let o,n;e instanceof Error?(o=e.message,n=e.stack):typeof e=="string"?o=e:o="An unknown error occurred";let i=`${g.RED}${g.BOLD}[MONACOPILOT ERROR] ${o}${g.RESET}`;return console.error(i),n&&console.error(`${g.RED}[MONACOPILOT ERROR] Stack trace:${g.RESET}
|
|
2
|
+
${n}`),{message:o,stack:n}}warning(e){console.warn(`${g.YELLOW}${g.BOLD}[MONACOPILOT WARN] ${e}${g.RESET}`)}information(e){console.log(`${g.BOLD}[MONACOPILOT] ${e}${g.RESET}`)}};g.instance=new g,g.RED="\x1B[31m",g.YELLOW="\x1B[33m",g.RESET="\x1B[0m",g.BOLD="\x1B[1m";var ie=g,y=ie.getInstance();var w=(t,e,o={})=>{let n=null,i=null,r=(...s)=>new Promise((a,d)=>{n&&(clearTimeout(n),i&&i("Cancelled")),i=d,n=setTimeout(()=>{(!o.shouldExecute||o.shouldExecute())&&a(t(...s)),i=null},e)});return r.cancel=()=>{n&&(clearTimeout(n),i&&i("Cancelled"),n=null,i=null)},r},b=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`,B=()=>Math.random().toString(36).slice(2,11);var re=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1];var F=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),A=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),Se=(t,e)=>e.getLineContent(t).trim()==="",R=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),P=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())}),M=(t,e,o={})=>{if(e<=0)return"";let n=t.split(`
|
|
3
|
+
`),i=n.length;if(e>=i)return t;if(o.from==="end"){let s=n.slice(-e);return s.every(a=>a==="")?`
|
|
4
|
+
`.repeat(e):s.join(`
|
|
5
|
+
`)}let r=n.slice(0,e);return r.every(s=>s==="")?`
|
|
6
|
+
`.repeat(e):r.join(`
|
|
7
|
+
`)},x=(t,e,o,n)=>({startLineNumber:t,startColumn:e,endLineNumber:o,endColumn:n}),ye=(t,e,o)=>{if(!o)return x(t.lineNumber,t.column,t.lineNumber,t.column);let n=e.getOffsetAt(t),i=e.getValue().substring(n),r=0,s=0,a=0,d=o.length,l=i.length;if(n>=e.getValue().length||l===0)return x(t.lineNumber,t.column,t.lineNumber,t.column);let c=Math.min(d,l);for(let u=0;u<c&&o[u]===i[u];u++)r++;for(let u=1;u<=c;u++){let h=o.slice(-u),E=i.slice(0,u);h===E&&(s=u)}if(a=Math.max(r,s),a===0)for(let u=1;u<d;u++){let h=o.substring(u);if(i.startsWith(h)){a=d-u;break}}let m=n+a,C=e.getPositionAt(m);return x(t.lineNumber,t.column,C.lineNumber,C.column)},W=(t,e)=>{t.setSelection({startLineNumber:e.startLineNumber,startColumn:e.startColumn,endLineNumber:e.startLineNumber,endColumn:e.startColumn})};var xe=async(t,e,o={})=>{let n={"Content-Type":"application/json",...o.headers},i=e==="POST"&&o.body?JSON.stringify(o.body):void 0,r=await fetch(t,{method:e,headers:n,body:i,signal:o.signal});if(!r.ok)throw new Error(`${r.statusText||o.fallbackError||"Network error"}`);return r.json()},mt=(t,e)=>xe(t,"GET",e),ut=(t,e,o)=>xe(t,"POST",{...o,body:e}),D={GET:mt,POST:ut};var Me=(t,e)=>{let o=F(t,e).trim(),n=A(t,e).trim();return t.column<=3&&(o!==""||n!=="")};var Ct=(t,e)=>{let o=t.length,n=e.length,i=Array.from({length:o+1},()=>Array(n+1).fill(0));for(let d=1;d<=o;d++)for(let l=1;l<=n;l++)t[d-1]===e[l-1]?i[d][l]=i[d-1][l-1]+1:i[d][l]=Math.max(i[d-1][l],i[d][l-1]);let r=o,s=n,a=[];for(;r>0&&s>0;)t[r-1]===e[s-1]?(a.unshift({type:"equal",line:t[r-1]}),r--,s--):i[r][s]===i[r-1][s]?(a.unshift({type:"deleted",line:t[r-1]}),r--):(a.unshift({type:"added",line:e[s-1]}),s--);for(;r>0;)a.unshift({type:"deleted",line:t[r-1]}),r--;for(;s>0;)a.unshift({type:"added",line:e[s-1]}),s--;return a},ft=(t,e)=>{let o=t.split(`
|
|
8
|
+
`),n=e.split(`
|
|
9
|
+
`);return Ct(o,n)},Oe=(t,e,o,n)=>{let i=ft(e,o),r=t.getModel();if(!r)return null;let s=[],a=[],d=n.startLineNumber;i.forEach((h,E)=>{let{type:T,line:S}=h,tt=S.length,X=1,J=tt+1;E===0&&(X=n.startColumn),E===i.length-1&&(J=n.endColumn),T==="equal"?(a.push(S),d++):T==="deleted"?(a.push(S),s.push({range:x(d,X,d,J),options:{...ee,className:fe}}),d++):T==="added"&&(a.push(S),s.push({range:x(d,X,d,J),options:{...ee,className:Ce}}),d++)});let l=a.join(`
|
|
10
|
+
`),c=null,m=n.startLineNumber+a.length-1,C=a.length>1?a[a.length-1].length+1:n.endColumn,u=x(n.startLineNumber,n.startColumn,m,C);return r.pushEditOperations([],[{range:n,text:l}],()=>null),c=t.createDecorationsCollection(s),{clear:()=>{c&&c.clear(),r.pushEditOperations([],[{range:u,text:e}],()=>null)}}};var gt=t=>{let{technologies:e,resolvedCurrentLanguage:o,currentFileName:n,relatedFiles:i}=t??{},r=o||b(e),s=`You are an expert ${r?`${r} `:""}developer assistant.`,a="Your task is to provide precise and contextually relevant code completions, modifications, or generations",d=n?`for the file '${n}'`:"",l=i&&i.length>0?"Consider the context of the current and related files provided.":"";return`${s}
|
|
11
|
+
${a} ${d}.
|
|
12
|
+
Ensure that your responses integrate seamlessly with the existing code and maintain consistency with the project's style and conventions.
|
|
13
|
+
${l}
|
|
14
|
+
Before providing the completion or modification, think through the problem step-by-step, considering best practices and any potential edge cases.`.trim()},ht=t=>t?.length?t.map(({path:e,content:o})=>`
|
|
15
|
+
<related_file>
|
|
16
|
+
<path>${e}</path>
|
|
17
|
+
<content>
|
|
18
|
+
\`\`\`
|
|
19
|
+
${o}
|
|
20
|
+
\`\`\`
|
|
21
|
+
</content>
|
|
33
22
|
</related_file>
|
|
34
|
-
|
|
35
|
-
`)
|
|
23
|
+
`.trim()).join(`
|
|
24
|
+
`):"",Et=(t="",e)=>{let{relatedFiles:o}=e??{},n=o?ht(o):"";return`
|
|
36
25
|
<task>
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
26
|
+
<instructions>
|
|
27
|
+
${t.trim()}
|
|
28
|
+
</instructions>
|
|
29
|
+
${n}
|
|
40
30
|
</task>
|
|
41
|
-
|
|
42
|
-
${
|
|
31
|
+
`.trim()},k=(t,e)=>({system:gt(e),user:Et(t,e)});var Ae="<cursor>",Re=t=>{let{textBeforeCursor:e="",textAfterCursor:o="",context:n,editorState:{completionMode:i}}=t,r=`<code_file>
|
|
32
|
+
${e}${Ae}${o}
|
|
33
|
+
</code_file>`,a=`
|
|
34
|
+
You are an AI coding assistant. Your task is to provide code completions based on the current cursor position in the code.
|
|
35
|
+
|
|
36
|
+
Below is the code file with a special token '${Ae}' indicating the current cursor position.
|
|
37
|
+
|
|
38
|
+
${r}
|
|
39
|
+
|
|
40
|
+
Please provide the code that should be inserted at the cursor position, following these guidelines:
|
|
41
|
+
|
|
42
|
+
- Carefully analyze the code context before and after the cursor to understand what code is needed.
|
|
43
|
+
- Follow best practices and maintain a consistent coding style with the existing code.
|
|
44
|
+
- Ensure the generated code integrates smoothly with the existing codebase.
|
|
45
|
+
- Do **not** include any code that is before the cursor in your response.
|
|
46
|
+
- Do **not** include any explanations, comments, or placeholders.
|
|
47
|
+
- Avoid wrapping your completion with markdown code blocks (\`\`\` or \`).
|
|
48
|
+
- Provide **only** the necessary code to be inserted at the cursor location.
|
|
49
|
+
|
|
50
|
+
Depending on the completion mode, adjust your completion accordingly:
|
|
51
|
+
|
|
52
|
+
- **Completion Mode**: ${i}
|
|
53
|
+
${{continue:"-- Continue writing the code from the current cursor location.",insert:"-- Insert the appropriate code snippet at the cursor point.",complete:"-- Supply the necessary code to finish the ongoing statement or block."}[i]||""}
|
|
54
|
+
|
|
55
|
+
Remember to output **only** the code that should be inserted at the cursor, without any additional formatting or explanations.
|
|
56
|
+
`.trim();return k(a,n)};var Tt="<cursor>",Pe=t=>{let{textBeforeCursor:e="",textAfterCursor:o="",context:n,prompt:i,selectedText:r,selection:s,fullText:a}=t,d="";return r&&s?d=`
|
|
57
|
+
You are a helpful assistant proficient in code editing.
|
|
58
|
+
|
|
59
|
+
**Task:** ${i}
|
|
60
|
+
|
|
61
|
+
**Instructions:**
|
|
62
|
+
- Modify only the code between lines **${s.startLineNumber}** and **${s.endLineNumber}**.
|
|
63
|
+
- Preserve all code outside the specified lines exactly as it is.
|
|
64
|
+
- Ensure the modified code integrates seamlessly with the existing code.
|
|
65
|
+
- Maintain the original formatting and indentation.
|
|
66
|
+
- Do **not** include any additional text or explanations.
|
|
67
|
+
- Return **only** the modified code between the specified lines.
|
|
68
|
+
|
|
69
|
+
**Full Code Context:**
|
|
70
|
+
\`\`\`
|
|
71
|
+
${a}
|
|
72
|
+
\`\`\`
|
|
73
|
+
|
|
74
|
+
**Code to Modify:**
|
|
75
|
+
\`\`\`
|
|
76
|
+
${r}
|
|
77
|
+
\`\`\`
|
|
78
|
+
`:d=`
|
|
79
|
+
You are a helpful assistant proficient in code editing.
|
|
80
|
+
|
|
81
|
+
**Task:** ${i}
|
|
82
|
+
|
|
83
|
+
**Instructions:**
|
|
84
|
+
- Make the modifications at the cursor position indicated by **<cursor>**.
|
|
85
|
+
- Preserve all code outside the cursor position exactly as it is.
|
|
86
|
+
- Ensure the modified code integrates seamlessly with the existing code.
|
|
87
|
+
- Maintain the original formatting and indentation.
|
|
88
|
+
- Do **not** include any additional text or explanations.
|
|
89
|
+
- Return **only** the modified code inserted at the cursor position.
|
|
90
|
+
|
|
91
|
+
**Full Code Context:**
|
|
92
|
+
\`\`\`
|
|
93
|
+
${a}
|
|
94
|
+
\`\`\`
|
|
95
|
+
|
|
96
|
+
**Code with Cursor Position:**
|
|
97
|
+
\`\`\`
|
|
98
|
+
${e}${Tt}${o}
|
|
99
|
+
\`\`\`
|
|
100
|
+
`,k(d.trim(),n)};var $=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??me,this.model=o.model??pe,this.validateInputs()}validateInputs(){if(!Z.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${b(Z)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!Q[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${b(Q[this.provider])}`)}async complete(e){let{body:o,options:n}=e,{metadata:i}=o,{headers:r={},customPrompt:s}=n??{};return this.makeApiCall(i,s,Re,this.processCompletionResponse.bind(this),r,this.handleCompletionError.bind(this))}async modify(e){let{body:o,options:n}=e,{metadata:i}=o,{headers:r={},customPrompt:s}=n??{};return this.makeApiCall(i,s,Pe,this.processModifyResponse.bind(this),r,this.handleModifyError.bind(this))}async makeApiCall(e,o,n,i,r={},s){let a=this.generatePrompt(e,o,n),{endpoint:d,requestBody:l,headers:c}=this.prepareRequestDetails(a);try{let m=await this.sendCompletionRequest(d,l,{...c,...r});return i(m)}catch(m){return s(m)}}generatePrompt(e,o,n){let i=n(e);return o?{...i,...o(e)}:i}prepareRequestDetails(e){let o=Te(this.provider),n,i=Ee(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let r=this.model.config(this.apiKey,e);o=r.endpoint??o,n=r.body??{},i={...i,...r.headers}}else n=he(this.model,this.provider,e);return{endpoint:o,requestBody:n,headers:i}}async sendCompletionRequest(e,o,n){return D.POST(e,o,{headers:n})}processCompletionResponse(e){return typeof this.model=="object"&&"transformResponse"in this.model?{completion:this.model.transformResponse(e).text}:{completion:oe(e,this.provider)}}processModifyResponse(e){return typeof this.model=="object"&&"transformResponse"in this.model?{modifiedText:this.model.transformResponse(e).text}:{modifiedText:oe(e,this.provider)}}handleCompletionError(e){return{error:y.error(e).message,completion:null}}handleModifyError(e){return{error:y.error(e).message,modifiedText:null}}};var se=class{constructor(){this.stateMap=new WeakMap}getOrCreateState(e){let o=this.stateMap.get(e);return o||(o={widgetState:{widgets:new Set},isSelectionActionsWidgetOpen:!1,disposables:[]},this.stateMap.set(e,o)),o}getWidgetState(e){return this.getOrCreateState(e).widgetState}setCleanup(e,o){this.getOrCreateState(e).cleanup=o}getCleanup(e){return this.getOrCreateState(e).cleanup}setDiffDecorationState(e,o){this.getOrCreateState(e).diffDecorationState=o}getDiffDecorationState(e){return this.getOrCreateState(e).diffDecorationState}disposeWidgets(e){let o=this.getWidgetState(e);o.widgets.size>0&&(o.widgets.forEach(n=>{e.removeContentWidget({getId:()=>n,getDomNode:()=>document.createElement("div"),getPosition:()=>null})}),o.widgets.clear()),this.setSelectionActionsWidgetOpen(e,!1)}disposeDiffDecorations(e){let o=this.getDiffDecorationState(e);o&&o.clear(),this.setDiffDecorationState(e,{clear:()=>{}})}setSelectionActionsWidgetOpen(e,o){o&&f.clearState(e),this.getOrCreateState(e).isSelectionActionsWidgetOpen=o}isSelectionActionsWidgetOpen(e){return this.getOrCreateState(e).isSelectionActionsWidgetOpen??!1}addDisposable(e,o){this.getOrCreateState(e).disposables.push(o)}clearState(e){this.disposeWidgets(e),this.disposeDiffDecorations(e),this.setSelectionActionsWidgetOpen(e,!1),this.getCleanup(e)?.();let o=this.getOrCreateState(e);o.disposables.forEach(n=>n.dispose()),o.disposables=[],this.stateMap.delete(e)}},p=new se;var ae=class{constructor(){this.stateMap=new WeakMap}getState(e){return this.stateMap.has(e)||this.stateMap.set(e,this.getInitialState()),this.stateMap.get(e)||this.getInitialState()}setState(e,o){let n=this.getState(e);this.stateMap.set(e,{...n,...o})}clearState(e){this.getState(e).disposables.forEach(({dispose:n})=>n()),this.stateMap.delete(e)}getInitialState(){return{isAccepted:!1,isVisible:!1,isManualTrigger:!1,disposables:[]}}canShowCompletion(e){return!p.isSelectionActionsWidgetOpen(e)}addDisposable(e,o){this.getState(e).disposables.push(o)}},f=new ae;var q=class q{constructor(){this.cache=[]}get(e,o){return this.cache.filter(n=>this.isValidCacheItem(n,e,o))}add(e){let o=[...this.cache.slice(-(q.MAX_CACHE_SIZE-1)),e];this.cache=o}clear(){this.cache=[]}isValidCacheItem(e,o,n){let i=n.getValueInRange(e.range);return A(o,n).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,o,i)}isPositionValid(e,o,n){let{range:i,completion:r}=e,{startLineNumber:s,startColumn:a,endColumn:d}=i,{lineNumber:l,column:c}=o,m=l===s&&c===a,C=r.startsWith(n)&&l===s&&c>=a-n.length&&c<=d+n.length;return m||C}};q.MAX_CACHE_SIZE=10;var U=q;var I=class t{constructor(e){this.formattedCode="";this.formattedCode=e}static create(e){return new t(e)}setCode(e){return this.formattedCode=e,this}removeInvalidLineBreaks(){return this.formattedCode=this.formattedCode.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCode=this.removeMarkdownCodeBlocks(this.formattedCode),this}removeMarkdownCodeBlocks(e){let o=/```[\s\S]*?```/g,n=e,i;for(;(i=o.exec(e))!==null;){let r=i[0],s=r.split(`
|
|
43
101
|
`).slice(1,-1).join(`
|
|
44
|
-
`);
|
|
102
|
+
`);n=n.replace(r,s)}return n.trim()}removeExcessiveNewlines(){return this.formattedCode=this.formattedCode.replace(/\n{3,}/g,`
|
|
45
103
|
|
|
46
|
-
`),this}build(){return this.
|
|
104
|
+
`),this}build(){return this.formattedCode}};var Y=class{constructor(e,o){this.cursorPos=e,this.mdl=o}shouldProvideCompletions(){return!Me(this.cursorPos,this.mdl)}};var St="application/json",De=async t=>{let{endpoint:e,body:o}=t,{completion:n,error:i}=await D.POST(e,o,{headers:{"Content-Type":St},fallbackError:"Error while fetching completion item"});if(i)throw new Error(i);return{completion:n}},Ie=({pos:t,mdl:e,options:o})=>{let{context:n}=o,{maxContextLines:i}=n??{},r=yt(t,e),s=i?M(R(t,e),i,{from:"end"}):R(t,e),a=i?M(P(t,e),i):P(t,e);return{textBeforeCursor:s,textAfterCursor:a,cursorPosition:t,editorState:{completionMode:r},context:n}},yt=(t,e)=>{let o=re(t,e),n=F(t,e);return o?"insert":n.trim()?"complete":"continue"};var be=t=>I.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),O=t=>({items:t,enableForwardStability:!0});var de={onTyping:300,onIdle:600,onDemand:0},Mt=(t,e)=>({onTyping:w(t,de.onTyping,{shouldExecute:()=>f.canShowCompletion(e)}),onIdle:w(t,de.onIdle,{shouldExecute:()=>f.canShowCompletion(e)}),onDemand:w(t,de.onDemand,{shouldExecute:()=>f.canShowCompletion(e)})}),L=new U,Ot=async({mdl:t,editor:e,pos:o,token:n,isCompletionAccepted:i,onShowCompletion:r,options:s})=>{let{trigger:a="onIdle",endpoint:d,onError:l,requestHandler:c}=s;if(!new Y(o,t).shouldProvideCompletions())return O([]);let m=L.get(o,t).map(C=>({insertText:C.completion,range:{...C.range,endColumn:o.column}}));if(m.length>0)return r(),O(m);if(n.isCancellationRequested||i)return O([]);try{let u=Mt(c??De,e)[a];n.onCancellationRequested(()=>{u.cancel()});let h=Ie({pos:o,mdl:t,options:s}),{completion:E}=await u({endpoint:d,body:{metadata:h}});if(E&&f.canShowCompletion(e)){let T=be(E),S=ye(o,t,E);return L.add({completion:T,range:S,textBeforeCursorInLine:A(o,t)}),r(),O([{insertText:T,range:S}])}}catch(C){if(At(C))return O([]);l?l(C):y.error(C)}return O([])},At=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,Le=Ot;var _=null,le=(t,e,o)=>{_&&_.deregister(),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let n=t.languages.registerInlineCompletionsProvider(o.context.currentLanguage,{provideInlineCompletions:(s,a,d,l)=>{let c=f.getState(e);if(!(!f.canShowCompletion(e)||o.trigger==="onDemand"&&!c.isManualTrigger))return Le({mdl:s,editor:e,pos:a,token:l,isCompletionAccepted:c.isAccepted,onShowCompletion:()=>{f.setState(e,{isVisible:!0,isManualTrigger:!1})},options:o})},freeInlineCompletions:()=>{}});f.addDisposable(e,n);let i=e.onKeyDown(s=>{let a=f.getState(e),d=s.keyCode===t.KeyCode.Tab||s.keyCode===t.KeyCode.RightArrow&&s.metaKey;a.isVisible&&d?f.setState(e,{isAccepted:!0,isVisible:!1}):f.setState(e,{isAccepted:!1})});f.addDisposable(e,i);let r={deregister:()=>{L.clear(),f.clearState(e),_=null},trigger:()=>Rt(e)};return _=r,r}catch(n){return o.onError?o.onError(n):y.error(n),{deregister:()=>{L.clear(),f.clearState(e),_=null},trigger:()=>{}}}},Rt=t=>{f.canShowCompletion(t)&&(f.setState(t,{isManualTrigger:!0}),t.trigger("keyboard","editor.action.inlineSuggest.trigger",{}))},_e=(...t)=>(y.warning("The `registerCopilot` function is deprecated. Use `registerCompletion` instead."),le(...t));var ve="action-buttons-widget",Ne="action-buttons-widget-button-key",we="modify-widget",H="modify-widget-close-button",G="modify-widget-prompt-container",Be="modify-widget-prompt-textarea",v="modify-widget-prompt-submit-button",Fe="modify-widget-accept-button",We="modify-widget-reject-button",ke="modify-widget-loading-container",j="modify-widget-loading-dot",$e="modify-widget-footer",Ue="modify-button",qe="modify-button-key",Ye="modify-button-text",He="Describe the modifications you want to make",Ge="modify-widget-cancel-button",je="modify-widget-cancel-button-text";var Pt="application/json",Ve=async t=>{let{endpoint:e,body:o}=t,{modifiedText:n,error:i}=await D.POST(e,o,{headers:{"Content-Type":Pt},fallbackError:"Error while fetching modified text"});if(i)throw new Error(i);return{modifiedText:n}},Ke=({pos:t,mdl:e,selection:o,prompt:n,options:i})=>{let{context:r}=i,{maxContextLines:s}=r??{},a=t?s?M(R(t,e),s,{from:"end"}):R(t,e):null,d=t?s?M(P(t,e),s):P(t,e):null;return{textBeforeCursor:a,textAfterCursor:d,cursorPosition:t,prompt:n,selectedText:o.isEmpty()?null:e.getValueInRange(o),fullText:e.getValue(),selection:o,context:r}};var Xe=t=>I.create(t).removeMarkdownCodeSyntax().removeInvalidLineBreaks().removeExcessiveNewlines().build();var Je=async(t,e,o,n,i,r)=>{let s=t.getModel();if(!s)return;let a=s.getValueInRange(e);i.dataset.fetching="true";let d=document.createElement("button");d.className=Ge;let l=document.createElement("span");l.textContent="Cancel",l.className=je;let c=document.createElement("span");c.className=ke;let m=document.createElement("span");m.className=j;let C=document.createElement("span");C.className=j;let u=document.createElement("span");u.className=j,c.appendChild(m),c.appendChild(C),c.appendChild(u),d.appendChild(l),d.appendChild(c),r.appendChild(d),r.insertBefore(d,r.firstChild),i.appendChild(r);let h=r.querySelector(`.${v}`);h instanceof HTMLButtonElement&&(h.disabled=!0);try{let{modifiedText:E}=await Ve({endpoint:n.endpoint,body:{metadata:Ke({mdl:s,pos:t.getPosition(),prompt:o,options:n,selection:e})}}),T=E?Xe(E):null;if(i.dataset.fetching="false",d.remove(),h instanceof HTMLButtonElement&&(h.disabled=!1),!T){p.disposeWidgets(t);return}let S=Oe(t,a,T,e);if(!S)return;p.setDiffDecorationState(t,S),W(t,e),Dt(t,r,e,T,i)}catch(E){throw i.dataset.fetching="false",d.remove(),h instanceof HTMLButtonElement&&(h.disabled=!1),E}},Dt=(t,e,o,n,i)=>{i.querySelector(`.${G}`)?.remove(),e.querySelector(`.${v}`)?.remove(),i.querySelector(`.${H}`)?.remove();let d=()=>{p.disposeDiffDecorations(t),p.setSelectionActionsWidgetOpen(t,!1)},l=document.createElement("button");l.className=Fe,l.textContent="Accept",l.onclick=()=>{d(),It(t,o,n),p.disposeWidgets(t)};let c=document.createElement("button");c.className=We,c.textContent="Reject",c.onclick=()=>{d(),bt(t),p.disposeWidgets(t)};let m=document.createElement("div");m.className="modify-widget-controls",m.appendChild(l),m.appendChild(c),e.appendChild(m)},It=(t,e,o)=>{let n=t.getModel();n&&n.pushEditOperations([],[{range:e,text:o}],()=>null)},bt=t=>{p.disposeWidgets(t),p.disposeDiffDecorations(t)};var V=(t,e,o)=>{p.disposeWidgets(t),p.disposeDiffDecorations(t);let n=_t(t,e,o);t.addContentWidget(n);let i=p.getWidgetState(t);i&&(i.widgets.add(n.getId()),p.setSelectionActionsWidgetOpen(t,!0));let r=p.getCleanup(t);r&&r();let s=setTimeout(()=>{let a=n.getDomNode().querySelector("textarea");a&&a.focus()},10);p.setCleanup(t,()=>clearTimeout(s))},_t=(t,e,o)=>{let n=`modify-widget-${B()}`,i=document.createElement("div");i.className=we;let r=document.createElement("button");r.textContent="\u2715",r.className=H,r.onclick=()=>{p.disposeWidgets(t),p.disposeDiffDecorations(t),p.setSelectionActionsWidgetOpen(t,!1)},i.appendChild(r);let s=document.createElement("div");s.className=G;let a=document.createElement("textarea");a.className=Be,a.placeholder=o.placeholder||He,a.rows=2;let d=document.createElement("div");d.className=$e;let l=document.createElement("button");l.textContent="Submit",l.className=v;let c=()=>{let m=a.value.trim();m&&Je(t,e,m,o,i,d)};return l.onclick=c,s.appendChild(a),d.appendChild(l),i.appendChild(s),i.appendChild(d),a.addEventListener("keydown",m=>{m.key==="Enter"&&(m.preventDefault(),c())}),{getId:()=>n,getDomNode:()=>i,getPosition:()=>({position:e.isEmpty()?t.getPosition():e.getStartPosition(),preference:[1,2,0]})}};var ze=(t,e,o,n)=>{let i=document.createElement("button");i.className=Ue;let r=document.createElement("span");r.textContent="Modify",r.className=Ye;let s=document.createElement("span");s.textContent="\u2318K",s.className=`${qe} ${Ne}`,s.setAttribute("aria-hidden","true"),i.appendChild(r),i.appendChild(s);let a=()=>{V(t,o,n)};i.addEventListener("click",a),i.setAttribute("title","Modify selected code"),i.setAttribute("aria-label","Modify selected code (Command + K)"),i.setAttribute("role","button"),e.appendChild(i)};var K=null,Qe=(t,e,o)=>{K&&K.deregister(),p.getWidgetState(e);let n=()=>{p.clearState(e),K=null};try{let i=e.onMouseUp(()=>{let a=e.getSelection();a&&!a.isEmpty()&&!p.isSelectionActionsWidgetOpen(e)&&(Ze(e,a,o),p.setSelectionActionsWidgetOpen(e,!0))});p.addDisposable(e,i);let r=e.onDidChangeCursorSelection(a=>{a.source==="keyboard"&&!a.selection.isEmpty()&&!p.isSelectionActionsWidgetOpen(e)&&(Ze(e,a.selection,o),p.setSelectionActionsWidgetOpen(e,!0))});p.addDisposable(e,r),e.addCommand(t.KeyMod.CtrlCmd|t.KeyCode.KeyK,()=>{let a=e.getSelection();if(a){let d=e.getModel();if(d&&!Se(a.startLineNumber,d))return;p.setSelectionActionsWidgetOpen(e,!0),V(e,a,o.modify)}}),e.addCommand(t.KeyCode.Escape,()=>{p.disposeWidgets(e),p.disposeDiffDecorations(e),p.setSelectionActionsWidgetOpen(e,!1);let a=e.getSelection();a&&W(e,a)});let s={deregister:n};return K=s,s}catch(i){return o.onError?o.onError(i):y.error(i),{deregister:n}}},Ze=(t,e,o)=>{let n=vt(t,e,o);t.addContentWidget(n),p.getWidgetState(t).widgets.add(n.getId())},vt=(t,e,o)=>{let n=`action-buttons-widget-${B()}`,i=document.createElement("div");return i.className=ve,o.actions.includes("modify")&&ze(t,i,e,o.modify),{getId:()=>n,getDomNode:()=>i,getPosition:()=>({position:e.getStartPosition(),preference:[1,2,0]})}};var et=t=>{let{maxContextLines:e,relatedFiles:o,...n}=t,r=!!o?.length?3:2,s=e?Math.floor(e/r):void 0;return{relatedFiles:((l,c)=>!l||!c?l:l.map(({content:m,...C})=>({...C,content:M(m,c)})))(o,s),maxContextLines:s,resolvedCurrentLanguage:Nt(n.currentLanguage),...n}},Nt=t=>t==="javascript"?"Latest JavaScript (ES2024)":t;0&&(module.exports={Copilot,buildContext,registerCompletion,registerCopilot,registerSelectionActions});
|