monacopilot 0.11.7 → 0.11.8

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/build/index.d.ts CHANGED
@@ -1,63 +1,6 @@
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
-
61
4
  type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-preview' | 'o1-mini';
62
5
  type GroqModel = 'llama-3-70b';
63
6
  type AnthropicModel = 'claude-3.5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' | 'claude-3-sonnet';
@@ -140,26 +83,38 @@ type CustomCopilotModelTransformResponse = (response: unknown) => {
140
83
  */
141
84
  completion: string | null;
142
85
  };
143
- type CustomPrompt<T> = (metadata: T) => Partial<PromptData>;
144
86
 
145
87
  type Monaco = typeof monaco;
146
88
  type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
147
89
  type CursorPosition = monaco.IPosition;
148
- type EditorSelection = monaco.Selection;
149
90
 
150
91
  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
+ };
151
109
  interface RegisterCompletionOptions {
152
110
  /**
153
- * The API endpoint to fetch the completion item from.
111
+ * Language of the current model
154
112
  */
155
- endpoint: Endpoint;
113
+ language: string;
156
114
  /**
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.
115
+ * The API endpoint where you started the completion service.
161
116
  */
162
- context: Context;
117
+ endpoint: Endpoint;
163
118
  /**
164
119
  * Specifies when the completion service should provide code completions.
165
120
  *
@@ -173,6 +128,36 @@ interface RegisterCompletionOptions {
173
128
  * @default 'onIdle'
174
129
  */
175
130
  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;
176
161
  /**
177
162
  * Callback function that is called when an error occurs during the completion request.
178
163
  * This function allows you to handle errors gracefully and provide appropriate feedback to the user.
@@ -203,23 +188,23 @@ interface CompletionRegistration {
203
188
  */
204
189
  deregister: () => void;
205
190
  }
206
- interface CompletionApiRequest {
191
+ interface CompletionRequest {
207
192
  /**
208
193
  * The body of the completion request.
209
194
  */
210
- body: CompletionApiRequestBody;
195
+ body: CompletionRequestBody;
211
196
  /**
212
197
  * Additional options to include in the completion request.
213
198
  */
214
- options?: CompletionApiRequestOptions;
199
+ options?: CompletionRequestOptions;
215
200
  }
216
- interface CompletionApiRequestBody {
201
+ interface CompletionRequestBody {
217
202
  /**
218
203
  * The metadata required to generate the completion.
219
204
  */
220
- metadata: CompletionMetadata;
205
+ completionMetadata: CompletionMetadata;
221
206
  }
222
- interface CompletionApiRequestOptions {
207
+ interface CompletionRequestOptions {
223
208
  /**
224
209
  * Custom headers to include in the request to the AI provider.
225
210
  */
@@ -229,21 +214,34 @@ interface CompletionApiRequestOptions {
229
214
  * This function allows you to override the default system and user prompts
230
215
  * used in the completion request, providing more control over the AI's context and behavior.
231
216
  *
232
- * @param metadata - Metadata about the current completion context
217
+ * @param completionMetadata - Metadata about the current completion context
233
218
  * @returns An object containing custom 'system' and 'user' prompts
234
219
  */
235
- customPrompt?: CustomPrompt<CompletionMetadata>;
220
+ customPrompt?: CustomPrompt;
236
221
  }
237
- interface CompletionApiResponse {
222
+ type CustomPrompt = (completionMetadata: CompletionMetadata) => Partial<PromptData>;
223
+ interface CompletionResponse {
238
224
  completion: string | null;
239
225
  error?: string;
240
226
  }
241
227
  type CompletionMode = 'insert' | 'complete' | 'continue';
242
228
  interface CompletionMetadata {
243
229
  /**
244
- * The context object containing contextual information for generating relevant completions.
230
+ * The programming language of the code.
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.
245
243
  */
246
- context?: Context;
244
+ relatedFiles: RelatedFile[] | undefined;
247
245
  /**
248
246
  * The text that appears after the cursor.
249
247
  */
@@ -260,6 +258,11 @@ interface CompletionMetadata {
260
258
  * The current state of the editor.
261
259
  */
262
260
  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
+ */
263
266
  completionMode: CompletionMode;
264
267
  };
265
268
  }
@@ -269,114 +272,7 @@ type FetchCompletionItemReturn = {
269
272
  };
270
273
  interface FetchCompletionItemParams {
271
274
  endpoint: string;
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;
275
+ body: CompletionRequestBody;
380
276
  }
381
277
 
382
278
  declare class Copilot {
@@ -385,16 +281,12 @@ declare class Copilot {
385
281
  private model;
386
282
  constructor(apiKey: string, options?: CopilotOptions);
387
283
  private validateInputs;
388
- complete(request: CompletionApiRequest): Promise<CompletionApiResponse>;
389
- modify(request: ModifyApiRequest): Promise<ModifyApiResponse>;
390
- private makeApiCall;
284
+ complete(request: CompletionRequest): Promise<CompletionResponse>;
391
285
  private generatePrompt;
392
286
  private prepareRequestDetails;
393
287
  private sendCompletionRequest;
394
288
  private processCompletionResponse;
395
- private processModifyResponse;
396
289
  private handleCompletionError;
397
- private handleModifyError;
398
290
  }
399
291
 
400
292
  /**
@@ -410,21 +302,4 @@ declare const registerCompletion: (monaco: Monaco, editor: StandaloneCodeEditor,
410
302
  */
411
303
  declare const registerCopilot: (monaco: typeof monaco_editor, editor: monaco_editor.editor.IStandaloneCodeEditor, options: RegisterCompletionOptions) => CompletionRegistration;
412
304
 
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 };
305
+ export { type CompletionMetadata, type CompletionRegistration, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, Copilot, type CopilotModel, type CopilotOptions, type CopilotProvider, type CustomCopilotModel, type CustomCopilotModelConfig, type CustomCopilotModelTransformResponse, type Monaco, type RegisterCompletionOptions, type StandaloneCodeEditor, registerCompletion, registerCopilot };
package/build/index.js CHANGED
@@ -1,104 +1,46 @@
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>
1
+ "use strict";var q=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var he=Object.prototype.hasOwnProperty;var fe=(e,t)=>{for(var o in t)q(e,o,{get:t[o],enumerable:!0})},Pe=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ge(t))!he.call(e,n)&&n!==o&&q(e,n,{get:()=>t[n],enumerable:!(r=Ce(t,n))||r.enumerable});return e};var ye=e=>Pe(q({},"__esModule",{value:!0}),e);var ke={};fe(ke,{Copilot:()=>D,registerCompletion:()=>G,registerCopilot:()=>ue});module.exports=ye(ke);var H=["groq","openai","anthropic"],X={"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"},$={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"]},z="llama-3-70b",J="groq",Z={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},v=.1;var I=(e,t)=>{let o=null,r=null,n=(...i)=>new Promise((s,a)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=a,o=setTimeout(()=>{s(e(...i)),r=null},t)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},E=e=>!e||e.length===0?"":e.length===1?e[0]:`${e.slice(0,-1).join(", ")} and ${e.slice(-1)}`;var _=(e,t)=>t.getLineContent(e.lineNumber)[e.column-1];var L=(e,t)=>t.getLineContent(e.lineNumber).slice(e.column-1),P=(e,t)=>t.getLineContent(e.lineNumber).slice(0,e.column-1),Q=(e,t)=>t.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:e.lineNumber,endColumn:e.column}),ee=(e,t)=>t.getValueInRange({startLineNumber:e.lineNumber,startColumn:e.column,endLineNumber:t.getLineCount(),endColumn:t.getLineMaxColumn(t.getLineCount())}),V=(e,t,o={})=>{if(t<=0)return"";let r=e.split(`
2
+ `),n=r.length;if(t>=n)return e;if(o.from==="end"){let s=r.slice(-t);return s.every(a=>a==="")?`
3
+ `.repeat(t):s.join(`
4
+ `)}let i=r.slice(0,t);return i.every(s=>s==="")?`
5
+ `.repeat(t):i.join(`
6
+ `)};var te=async(e,t,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=t==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(e,{method:t,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${i.statusText||o.fallbackError||"Network error"}`);return i.json()},Re=(e,t)=>te(e,"GET",t),xe=(e,t,o)=>te(e,"POST",{...o,body:t}),A={GET:Re,POST:xe};var oe=(e,t)=>{let o=L(e,t).trim(),r=P(e,t).trim();return e.column<=3&&(o!==""||r!=="")};var Te="<user-current-cursor-position-is-here>",Ee=e=>e==="javascript"?"JavaScript (ESNext)":e,Oe=e=>`You are an expert ${Ee(e.language)||E(e.technologies)} developer assistant with extensive experience in code completion and adhering to best coding practices. Your role is to provide precise and contextually relevant code completions without any errors, including syntax, punctuation, spaces, tabs, and line breaks. Focus on integrating seamlessly with the existing code and follow the user's instructions carefully.`,Me=e=>{let{filename:t="/",textBeforeCursor:o="",textAfterCursor:r="",relatedFiles:n,editorState:i}=e,p=`
7
+ <guidelines>
8
+ <instruction>${{continue:"Continue writing the code from where the cursor is positioned.",insert:"Insert the appropriate code snippet at the cursor position.",complete:"Provide the necessary code to complete the current statement or block."}[i.completionMode]}</instruction>
9
+ <steps>
10
+ <step>Analyze the provided code and any related files thoroughly.</step>
11
+ <step>Ensure the generated code integrates seamlessly with the existing code.</step>
12
+ <step>Adhere to best practices and maintain consistent coding style.</step>
13
+ <step>Do <strong>not</strong> include the code before the cursor in your response.</step>
14
+ <step>Do <strong>not</strong> wrap your completion with markdown code syntax (\`\`\`) or inline code syntax (\`).</step>
15
+ <step>Focus on correct syntax and language-specific conventions.</step>
16
+ <step>Do <strong>not</strong> add explanations, comments, or placeholders.</step>
17
+ <step>Return <strong>only</strong> the code required at the cursor position.</step>
18
+ </steps>
19
+ </guidelines>
20
+ `,c=`
21
+ <context>
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>
22
33
  </related_file>
23
- `.trim()).join(`
24
- `):"",Et=(t="",e)=>{let{relatedFiles:o}=e??{},n=o?ht(o):"";return`
34
+ `).join(`
35
+ `)||"";return`
25
36
  <task>
26
- <instructions>
27
- ${t.trim()}
28
- </instructions>
29
- ${n}
37
+ ${p}
38
+ ${c}
39
+ ${u}
30
40
  </task>
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(`
41
+ `};function j(e){return{system:Oe(e),user:Me(e)}}var re={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var be={createRequestBody:(e,t)=>{let r=e==="o1-preview"||e==="o1-mini"?[{role:"user",content:t.user}]:[{role:"system",content:t.system},{role:"user",content:t.user}];return{model:W(e),temperature:v,messages:r}},createHeaders:e=>({"Content-Type":"application/json",Authorization:`Bearer ${e}`}),parseCompletion:e=>e.choices?.length?e.choices[0].message.content:null},ve={createRequestBody:(e,t)=>({model:W(e),temperature:v,messages:[{role:"system",content:t.system},{role:"user",content:t.user}]}),createHeaders:e=>({"Content-Type":"application/json",Authorization:`Bearer ${e}`}),parseCompletion:e=>e.choices?.length?e.choices[0].message.content:null},Ie={createRequestBody:(e,t)=>({model:W(e),temperature:v,system:t.system,messages:[{role:"user",content:t.user}],max_tokens:Le(e)}),createHeaders:e=>({"Content-Type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01"}),parseCompletion:e=>!e.content||typeof e.content!="string"?null:e.content},U={openai:be,groq:ve,anthropic:Ie},ne=(e,t,o)=>U[t].createRequestBody(e,o),ie=(e,t)=>U[t].createHeaders(e),se=(e,t)=>U[t].parseCompletion(e),W=e=>X[e],le=e=>Z[e],Le=e=>re[e]||4096;var m=class m{constructor(){}static getInstance(){return m.instance}logError(t){let o,r;t instanceof Error?(o=t.message,r=t.stack):typeof t=="string"?o=t:o="An unknown error occurred";let n=`${m.RED}${m.BOLD}[MONACOPILOT ERROR] ${o}${m.RESET}`;return console.error(n),r&&console.error(`${m.RED}[MONACOPILOT ERROR] Stack trace:${m.RESET}
42
+ ${r}`),{message:o,stack:r}}warn(t){console.warn(`${m.YELLOW}${m.BOLD}[MONACOPILOT WARN] ${t}${m.RESET}`)}log(t){console.log(`${m.BOLD}[MONACOPILOT] ${t}${m.RESET}`)}};m.instance=new m,m.RED="\x1B[31m",m.YELLOW="\x1B[33m",m.RESET="\x1B[0m",m.BOLD="\x1B[1m";var K=m,g=K.getInstance();var D=class{constructor(t,o={}){if(!t)throw new Error("Please provide an API key.");this.apiKey=t,this.provider=o.provider??J,this.model=o.model??z,this.validateInputs()}validateInputs(){if(!H.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${E(H)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!$[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${E($[this.provider])}`)}async complete(t){let{body:o,options:r}=t,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},a=this.generatePrompt(n,s),{endpoint:p,requestBody:c,headers:u}=this.prepareRequestDetails(a);try{let l=await this.sendCompletionRequest(p,c,{...u,...i});return this.processCompletionResponse(l)}catch(l){return this.handleCompletionError(l)}}generatePrompt(t,o){let r=j(t);return o?{...r,...o(t)}:r}prepareRequestDetails(t){let o=le(this.provider),r,n=ie(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let i=this.model.config(this.apiKey,t);o=i.endpoint??o,r=i.body??{},n={...n,...i.headers}}else r=ne(this.model,this.provider,t);return{endpoint:o,requestBody:r,headers:n}}async sendCompletionRequest(t,o,r){return A.POST(t,o,{headers:r})}processCompletionResponse(t){if(typeof this.model=="object"&&"transformResponse"in this.model){let o=this.model.transformResponse(t);return"completion"in o&&g.warn("The `completion` property in `transformResponse` function is deprecated. Please use `text` instead."),{completion:o.text??o.completion}}else return{completion:se(t,this.provider)}}handleCompletionError(t){return{error:g.logError(t).message,completion:null}}};var S=class e{constructor(t){this.formattedCompletion="";this.formattedCompletion=t}static create(t){return new e(t)}setCompletion(t){return this.formattedCompletion=t,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(t){let o=/```[\s\S]*?```/g,r=t,n;for(;(n=o.exec(t))!==null;){let i=n[0],s=i.split(`
101
43
  `).slice(1,-1).join(`
102
- `);n=n.replace(r,s)}return n.trim()}removeExcessiveNewlines(){return this.formattedCode=this.formattedCode.replace(/\n{3,}/g,`
44
+ `);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
103
45
 
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});
46
+ `),this}build(){return this.formattedCompletion}};var w=class{constructor(t,o){this.cursorPos=t,this.mdl=o}shouldProvideCompletions(){return!oe(this.cursorPos,this.mdl)}};var B=class B{constructor(){this.cache=[]}get(t,o){return this.cache.filter(r=>this.isValidCacheItem(r,t,o))}add(t){let o=[...this.cache.slice(-(B.MAX_CACHE_SIZE-1)),t];this.cache=o}clear(){this.cache=[]}isValidCacheItem(t,o,r){let n=r.getValueInRange(t.range);return P(o,r).startsWith(t.textBeforeCursorInLine)&&this.isPositionValid(t,o,n)}isPositionValid(t,o,r){let{range:n,completion:i}=t,{startLineNumber:s,startColumn:a,endColumn:p}=n,{lineNumber:c,column:u}=o,l=c===s&&u===a,C=i.startsWith(r)&&c===s&&u>=a-r.length&&u<=p+r.length;return l||C}};B.MAX_CACHE_SIZE=10;var N=B;var Ae="application/json",ae=async e=>{let{endpoint:t,body:o}=e,{completion:r,error:n}=await A.POST(t,o,{headers:{"Content-Type":Ae},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return{completion:r}},pe=({pos:e,mdl:t,options:o})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:a}=o,p=De(e,t),u=!!s?.length?3:2,l=a?Math.floor(a/u):void 0,C=(x,T,k)=>{let b=x(e,t);return T?V(b,T,k):b},d=(x,T)=>!x||!T?x:x.map(({content:k,...b})=>({...b,content:V(k,T)})),h=C(Q,l,{from:"end"}),f=C(ee,l),M=d(s,l);return{filename:r,language:n,technologies:i,relatedFiles:M,textBeforeCursor:h,textAfterCursor:f,cursorPosition:e,editorState:{completionMode:p}}},De=(e,t)=>{let o=_(e,t),r=L(e,t);return o?"insert":r.trim()?"complete":"continue"};var ce=(e,t,o)=>{if(!o)return{startLineNumber:e.lineNumber,startColumn:e.column,endLineNumber:e.lineNumber,endColumn:e.column};let r=t.getOffsetAt(e),n=t.getValue().substring(r),i=0,s=0,a=0,p=o.length,c=n.length;if(r>=t.getValue().length)return{startLineNumber:e.lineNumber,startColumn:e.column,endLineNumber:e.lineNumber,endColumn:e.column};if(c===0)return{startLineNumber:e.lineNumber,startColumn:e.column,endLineNumber:e.lineNumber,endColumn:e.column};let u=Math.min(p,c);for(let d=0;d<u&&o[d]===n[d];d++)i++;for(let d=1;d<=u;d++){let h=o.slice(-d),f=n.slice(0,d);h===f&&(s=d)}if(a=Math.max(i,s),a===0)for(let d=1;d<p;d++){let h=o.substring(d);if(n.startsWith(h)){a=p-d;break}}let l=r+a,C=t.getPositionAt(l);return{startLineNumber:e.lineNumber,startColumn:e.column,endLineNumber:C.lineNumber,endColumn:C.column}},de=e=>S.create(e).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),y=e=>({items:e,enableForwardStability:!0});var Y={onTyping:300,onIdle:600,onDemand:0},we=e=>({onTyping:I(e,Y.onTyping),onIdle:I(e,Y.onIdle),onDemand:I(e,Y.onDemand)}),F=new N,Ne=async({mdl:e,pos:t,token:o,isCompletionAccepted:r,onShowCompletion:n,options:i})=>{let{trigger:s="onIdle",endpoint:a,onError:p,requestHandler:c}=i;if(!new w(t,e).shouldProvideCompletions())return y([]);let u=F.get(t,e).map(l=>({insertText:l.completion,range:{...l.range,endColumn:t.column}}));if(u.length>0)return n(),y(u);if(o.isCancellationRequested||r)return y([]);try{let C=we(c??ae)[s];o.onCancellationRequested(()=>{C.cancel()});let d=pe({pos:t,mdl:e,options:i}),{completion:h}=await C({endpoint:a,body:{completionMetadata:d}});if(h){let f=de(h),M=ce(t,e,f);return F.add({completion:f,range:M,textBeforeCursorInLine:P(t,e)}),n(),y([{insertText:f,range:M}])}}catch(l){p?p(l):Be(l)||g.logError(l)}return y([])},Be=e=>typeof e=="string"?e==="Cancelled"||e==="AbortError":e instanceof Error?e.message==="Cancelled"||e.name==="AbortError":!1,me=Ne;var R=new WeakMap,O=null,G=(e,t,o)=>{O&&O.deregister();let r=[],n={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};R.set(t,n),t.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let i=e.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(p,c,u,l)=>{let C=R.get(t);if(!(!C||o.trigger==="onDemand"&&!C.isManualTrigger))return me({mdl:p,pos:c,token:l,isCompletionAccepted:C.isCompletionAccepted,onShowCompletion:()=>{C.isCompletionVisible=!0,C.isManualTrigger=!1},options:o})},freeInlineCompletions:()=>{}});r.push(i);let s=t.onKeyDown(p=>{let c=R.get(t);if(!c)return;let u=p.keyCode===e.KeyCode.Tab||p.keyCode===e.KeyCode.RightArrow&&p.metaKey;c.isCompletionVisible&&u?(c.isCompletionAccepted=!0,c.isCompletionVisible=!1):c.isCompletionAccepted=!1});r.push(s);let a={deregister:()=>{r.forEach(p=>p.dispose()),F.clear(),R.delete(t),O=null},trigger:()=>Fe(t)};return O=a,a}catch(i){return o.onError?o.onError(i):g.logError(i),{deregister:()=>{r.forEach(s=>s.dispose()),R.delete(t),O=null},trigger:()=>{}}}},Fe=e=>{let t=R.get(e);if(!t){g.warn("Completion is not registered. Use `registerCompletion` to register completion first.");return}t.isManualTrigger=!0,e.trigger("keyboard","editor.action.inlineSuggest.trigger",{})},ue=(...e)=>(g.warn("The `registerCopilot` function is deprecated. Use `registerCompletion` instead."),G(...e));0&&(module.exports={Copilot,registerCompletion,registerCopilot});