monacopilot 0.9.26 → 0.9.28
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 +56 -5
- package/build/index.d.mts +85 -16
- package/build/index.d.ts +85 -16
- package/build/index.js +15 -15
- package/build/index.mjs +15 -15
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
- [Usage](#usage)
|
|
12
12
|
- [Copilot Options](#copilot-options)
|
|
13
13
|
- [Changing the Provider and Model](#changing-the-provider-and-model)
|
|
14
|
+
- [Custom Model](#custom-model)
|
|
14
15
|
- [Completion Request Options](#completion-request-options)
|
|
15
16
|
- [Custom Headers](#custom-headers)
|
|
16
17
|
- [Custom Prompt](#custom-prompt)
|
|
@@ -22,15 +23,15 @@
|
|
|
22
23
|
- [FAQ](#faq)
|
|
23
24
|
- [Contributing](#contributing)
|
|
24
25
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
https://github.com/user-attachments/assets/4af4e24a-1b05-4bee-84aa-1521ad7098cd
|
|
26
|
+
[Demo Video](https://github.com/user-attachments/assets/4af4e24a-1b05-4bee-84aa-1521ad7098cd)
|
|
28
27
|
|
|
29
28
|
## Examples
|
|
30
29
|
|
|
31
30
|
Here are some examples of how to use Monacopilot in different project setups:
|
|
32
31
|
|
|
33
|
-
- Next.js
|
|
32
|
+
- Next.js
|
|
33
|
+
- [App Router](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/nextjs/app)
|
|
34
|
+
- [Pages Router](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/nextjs/pages)
|
|
34
35
|
- [Remix](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/remix)
|
|
35
36
|
|
|
36
37
|
## Installation
|
|
@@ -105,6 +106,8 @@ registerCopilot(monaco, editor, {
|
|
|
105
106
|
- `endpoint`: The URL of the API endpoint that we created in the previous step.
|
|
106
107
|
- `language`: The language of the editor.
|
|
107
108
|
|
|
109
|
+
🎉 Hurray! Monacopilot is now connected to the Monaco Editor. Start typing and see completions in the editor.
|
|
110
|
+
|
|
108
111
|
## Copilot Options
|
|
109
112
|
|
|
110
113
|
### Changing the Provider and Model
|
|
@@ -126,7 +129,55 @@ There are other providers and models available. Here is a list:
|
|
|
126
129
|
| --------- | ------------------------------------------------------------------------- |
|
|
127
130
|
| Groq | `llama-3-70b` |
|
|
128
131
|
| OpenAI | `gpt-4o`, `gpt-4o-mini`, `o1-preview`, `o1-mini` |
|
|
129
|
-
| Anthropic | `
|
|
132
|
+
| Anthropic | `claude-3.5-Sonnet`, `claude-3-opus`, `claude-3-sonnet`, `claude-3-haiku` |
|
|
133
|
+
|
|
134
|
+
### Custom Model
|
|
135
|
+
|
|
136
|
+
You can use a custom AI model that isn't built into Monacopilot by setting up a `model` when you create a new Copilot. This feature lets you connect to AI models from other services or your own custom-built models.
|
|
137
|
+
|
|
138
|
+
#### Example
|
|
139
|
+
|
|
140
|
+
```javascript
|
|
141
|
+
const copilot = new Copilot(process.env.HUGGINGFACE_API_KEY, {
|
|
142
|
+
model: {
|
|
143
|
+
config: (apiKey, prompt) => ({
|
|
144
|
+
endpoint:
|
|
145
|
+
'https://api-inference.huggingface.co/models/openai-community/gpt2',
|
|
146
|
+
headers: {
|
|
147
|
+
Authorization: `Bearer ${apiKey}`,
|
|
148
|
+
'Content-Type': 'application/json',
|
|
149
|
+
},
|
|
150
|
+
body: {
|
|
151
|
+
inputs: prompt.user,
|
|
152
|
+
parameters: {
|
|
153
|
+
max_length: 100,
|
|
154
|
+
num_return_sequences: 1,
|
|
155
|
+
temperature: 0.7,
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
}),
|
|
159
|
+
transformResponse: response => ({
|
|
160
|
+
completion: response[0].generated_text,
|
|
161
|
+
}),
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
#### Configuration
|
|
167
|
+
|
|
168
|
+
The `model` option accepts an object with two functions:
|
|
169
|
+
|
|
170
|
+
1. `config`: A function that receives the API key and prompt data, and returns the configuration for the custom model API request.
|
|
171
|
+
|
|
172
|
+
- `endpoint`: The URL for the custom model's API (required)
|
|
173
|
+
- `body`: The request body data for the custom model API (optional)
|
|
174
|
+
- `headers`: Additional HTTP headers for the API request (optional)
|
|
175
|
+
|
|
176
|
+
2. `transformResponse`: A function that takes the raw response from the custom model API and converts it into an object with the following structure:
|
|
177
|
+
- `completion`: A string containing the generated text from the model to be used as the completion.
|
|
178
|
+
- `error`: A string describing any error that occurred during the completion process (optional)
|
|
179
|
+
|
|
180
|
+
This structure allows for easy integration of the custom model's output with the rest of the Monacopilot system, providing either the generated completion text or an error message if something went wrong.
|
|
130
181
|
|
|
131
182
|
## Completion Request Options
|
|
132
183
|
|
package/build/index.d.mts
CHANGED
|
@@ -14,12 +14,65 @@ interface CopilotOptions {
|
|
|
14
14
|
*/
|
|
15
15
|
provider?: CompletionProvider;
|
|
16
16
|
/**
|
|
17
|
-
* The
|
|
18
|
-
*
|
|
17
|
+
* The model to use for generating completions.
|
|
18
|
+
* This can be either:
|
|
19
|
+
* 1. A predefined model name (e.g. 'claude-3-opus'): Use this option if you want to use a model that is built into Monacopilot.
|
|
20
|
+
* If you choose this option, also set the `provider` property to the corresponding provider of the model.
|
|
21
|
+
* 2. A custom model configuration object: Use this option if you want to use a AI model from a third-party service or your own custom model.
|
|
22
|
+
*
|
|
19
23
|
* If not specified, a default model will be used.
|
|
20
24
|
*/
|
|
21
|
-
model?: CompletionModel;
|
|
25
|
+
model?: CompletionModel | CustomModel;
|
|
22
26
|
}
|
|
27
|
+
type CustomModel = {
|
|
28
|
+
/**
|
|
29
|
+
* A function to configure the custom model.
|
|
30
|
+
* This function takes the API key and the prompt data and returns the configuration for the custom model.
|
|
31
|
+
*
|
|
32
|
+
* @param {string} apiKey - The API key for authentication.
|
|
33
|
+
* @param {Object} prompt - An object containing 'system' and 'user' messages generated by Monacopilot.
|
|
34
|
+
* @returns {Object} An object that may include:
|
|
35
|
+
* - endpoint: The URL for the custom model's API (required)
|
|
36
|
+
* - headers: Additional HTTP headers for the API request (optional)
|
|
37
|
+
* - body: The request body data for the custom model API (optional)
|
|
38
|
+
*/
|
|
39
|
+
config: CustomModelConfig;
|
|
40
|
+
/**
|
|
41
|
+
* A function to transform the response from the custom model.
|
|
42
|
+
* This function takes the raw response from the custom model API
|
|
43
|
+
* and converts it into a CompletionResponse object.
|
|
44
|
+
*
|
|
45
|
+
* @param response - The raw response from the custom model API.
|
|
46
|
+
* The type is 'unknown' because different APIs
|
|
47
|
+
* may return responses in different formats.
|
|
48
|
+
* @returns A CompletionResponse object containing the completion text
|
|
49
|
+
* or an error message. The completion should be the actual
|
|
50
|
+
* text to be inserted or used as the completion, without
|
|
51
|
+
* any metadata or additional structure.
|
|
52
|
+
*/
|
|
53
|
+
transformResponse: CustomModelResponse;
|
|
54
|
+
};
|
|
55
|
+
type CustomModelConfig = (apiKey: string, prompt: {
|
|
56
|
+
system: string;
|
|
57
|
+
user: string;
|
|
58
|
+
}) => {
|
|
59
|
+
/**
|
|
60
|
+
* The URL endpoint for the custom model's API.
|
|
61
|
+
* This is where the completion request will be sent.
|
|
62
|
+
*/
|
|
63
|
+
endpoint: Endpoint;
|
|
64
|
+
/**
|
|
65
|
+
* Additional HTTP headers to include with the API request.
|
|
66
|
+
* Use this to add any necessary authentication or custom headers.
|
|
67
|
+
*/
|
|
68
|
+
headers?: Record<string, string>;
|
|
69
|
+
/**
|
|
70
|
+
* The data to be sent in the request body to the custom model API.
|
|
71
|
+
* This should contain all necessary parameters for generating a completion.
|
|
72
|
+
*/
|
|
73
|
+
body?: Record<string, unknown>;
|
|
74
|
+
};
|
|
75
|
+
type CustomModelResponse = (response: unknown) => CompletionResponse;
|
|
23
76
|
type Endpoint = string;
|
|
24
77
|
type Filename = string;
|
|
25
78
|
type Technologies = string[];
|
|
@@ -82,6 +135,10 @@ type GroqModel = 'llama-3-70b';
|
|
|
82
135
|
type AnthropicModel = 'claude-3.5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' | 'claude-3-sonnet';
|
|
83
136
|
type CompletionModel = OpenAIModel | GroqModel | AnthropicModel;
|
|
84
137
|
type CompletionProvider = 'openai' | 'groq' | 'anthropic';
|
|
138
|
+
type PromptData = {
|
|
139
|
+
system: string;
|
|
140
|
+
user: string;
|
|
141
|
+
};
|
|
85
142
|
interface CompletionRequest {
|
|
86
143
|
/**
|
|
87
144
|
* The body of the completion request.
|
|
@@ -113,10 +170,7 @@ interface CompletionRequestOptions {
|
|
|
113
170
|
*/
|
|
114
171
|
customPrompt?: CustomPrompt;
|
|
115
172
|
}
|
|
116
|
-
type CustomPrompt = (completionMetadata: CompletionMetadata) =>
|
|
117
|
-
system?: string;
|
|
118
|
-
user?: string;
|
|
119
|
-
};
|
|
173
|
+
type CustomPrompt = (completionMetadata: CompletionMetadata) => Partial<PromptData>;
|
|
120
174
|
interface CompletionResponse {
|
|
121
175
|
completion: string | null;
|
|
122
176
|
error?: string;
|
|
@@ -164,26 +218,41 @@ interface CompletionMetadata {
|
|
|
164
218
|
};
|
|
165
219
|
}
|
|
166
220
|
|
|
167
|
-
/**
|
|
168
|
-
* Copilot class for handling completions using various AI providers.
|
|
169
|
-
*/
|
|
170
221
|
declare class Copilot {
|
|
171
222
|
private readonly apiKey;
|
|
172
223
|
private readonly provider;
|
|
173
224
|
private readonly model;
|
|
174
225
|
/**
|
|
175
|
-
* Initializes the Copilot with an API key and optional configuration.
|
|
226
|
+
* Initializes the Copilot instance with an API key and optional configuration.
|
|
176
227
|
* @param apiKey - The API key for the chosen provider.
|
|
177
|
-
* @param options -
|
|
228
|
+
* @param options - Optional configuration for the Copilot instance.
|
|
178
229
|
*/
|
|
179
230
|
constructor(apiKey: string, options?: CopilotOptions);
|
|
180
231
|
/**
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
* @returns A promise resolving to the completed text snippet or an error.
|
|
232
|
+
* Validates the inputs provided to the constructor.
|
|
233
|
+
* Ensures the selected model is supported by the provider.
|
|
184
234
|
*/
|
|
185
|
-
complete({ body, options, }: CompletionRequest): Promise<CompletionResponse>;
|
|
186
235
|
private validateInputs;
|
|
236
|
+
/**
|
|
237
|
+
* Generates the prompt based on the completion metadata and any custom prompt function.
|
|
238
|
+
* @param completionMetadata - The metadata for the completion.
|
|
239
|
+
* @param customPrompt - An optional custom prompt function.
|
|
240
|
+
* @returns The generated prompt.
|
|
241
|
+
*/
|
|
242
|
+
private generatePrompt;
|
|
243
|
+
/**
|
|
244
|
+
* Prepares the request details including endpoint, request body, and headers.
|
|
245
|
+
* @param prompt - The generated prompt.
|
|
246
|
+
* @param customHeaders - Any custom headers to include.
|
|
247
|
+
* @returns An object containing the endpoint, request body, and headers.
|
|
248
|
+
*/
|
|
249
|
+
private prepareRequest;
|
|
250
|
+
/**
|
|
251
|
+
* Sends a completion request to the API and returns the completion.
|
|
252
|
+
* @param request - The completion request containing the body and options.
|
|
253
|
+
* @returns A promise resolving to the completion response or an error.
|
|
254
|
+
*/
|
|
255
|
+
complete(request: CompletionRequest): Promise<CompletionResponse>;
|
|
187
256
|
}
|
|
188
257
|
|
|
189
258
|
/**
|
package/build/index.d.ts
CHANGED
|
@@ -14,12 +14,65 @@ interface CopilotOptions {
|
|
|
14
14
|
*/
|
|
15
15
|
provider?: CompletionProvider;
|
|
16
16
|
/**
|
|
17
|
-
* The
|
|
18
|
-
*
|
|
17
|
+
* The model to use for generating completions.
|
|
18
|
+
* This can be either:
|
|
19
|
+
* 1. A predefined model name (e.g. 'claude-3-opus'): Use this option if you want to use a model that is built into Monacopilot.
|
|
20
|
+
* If you choose this option, also set the `provider` property to the corresponding provider of the model.
|
|
21
|
+
* 2. A custom model configuration object: Use this option if you want to use a AI model from a third-party service or your own custom model.
|
|
22
|
+
*
|
|
19
23
|
* If not specified, a default model will be used.
|
|
20
24
|
*/
|
|
21
|
-
model?: CompletionModel;
|
|
25
|
+
model?: CompletionModel | CustomModel;
|
|
22
26
|
}
|
|
27
|
+
type CustomModel = {
|
|
28
|
+
/**
|
|
29
|
+
* A function to configure the custom model.
|
|
30
|
+
* This function takes the API key and the prompt data and returns the configuration for the custom model.
|
|
31
|
+
*
|
|
32
|
+
* @param {string} apiKey - The API key for authentication.
|
|
33
|
+
* @param {Object} prompt - An object containing 'system' and 'user' messages generated by Monacopilot.
|
|
34
|
+
* @returns {Object} An object that may include:
|
|
35
|
+
* - endpoint: The URL for the custom model's API (required)
|
|
36
|
+
* - headers: Additional HTTP headers for the API request (optional)
|
|
37
|
+
* - body: The request body data for the custom model API (optional)
|
|
38
|
+
*/
|
|
39
|
+
config: CustomModelConfig;
|
|
40
|
+
/**
|
|
41
|
+
* A function to transform the response from the custom model.
|
|
42
|
+
* This function takes the raw response from the custom model API
|
|
43
|
+
* and converts it into a CompletionResponse object.
|
|
44
|
+
*
|
|
45
|
+
* @param response - The raw response from the custom model API.
|
|
46
|
+
* The type is 'unknown' because different APIs
|
|
47
|
+
* may return responses in different formats.
|
|
48
|
+
* @returns A CompletionResponse object containing the completion text
|
|
49
|
+
* or an error message. The completion should be the actual
|
|
50
|
+
* text to be inserted or used as the completion, without
|
|
51
|
+
* any metadata or additional structure.
|
|
52
|
+
*/
|
|
53
|
+
transformResponse: CustomModelResponse;
|
|
54
|
+
};
|
|
55
|
+
type CustomModelConfig = (apiKey: string, prompt: {
|
|
56
|
+
system: string;
|
|
57
|
+
user: string;
|
|
58
|
+
}) => {
|
|
59
|
+
/**
|
|
60
|
+
* The URL endpoint for the custom model's API.
|
|
61
|
+
* This is where the completion request will be sent.
|
|
62
|
+
*/
|
|
63
|
+
endpoint: Endpoint;
|
|
64
|
+
/**
|
|
65
|
+
* Additional HTTP headers to include with the API request.
|
|
66
|
+
* Use this to add any necessary authentication or custom headers.
|
|
67
|
+
*/
|
|
68
|
+
headers?: Record<string, string>;
|
|
69
|
+
/**
|
|
70
|
+
* The data to be sent in the request body to the custom model API.
|
|
71
|
+
* This should contain all necessary parameters for generating a completion.
|
|
72
|
+
*/
|
|
73
|
+
body?: Record<string, unknown>;
|
|
74
|
+
};
|
|
75
|
+
type CustomModelResponse = (response: unknown) => CompletionResponse;
|
|
23
76
|
type Endpoint = string;
|
|
24
77
|
type Filename = string;
|
|
25
78
|
type Technologies = string[];
|
|
@@ -82,6 +135,10 @@ type GroqModel = 'llama-3-70b';
|
|
|
82
135
|
type AnthropicModel = 'claude-3.5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' | 'claude-3-sonnet';
|
|
83
136
|
type CompletionModel = OpenAIModel | GroqModel | AnthropicModel;
|
|
84
137
|
type CompletionProvider = 'openai' | 'groq' | 'anthropic';
|
|
138
|
+
type PromptData = {
|
|
139
|
+
system: string;
|
|
140
|
+
user: string;
|
|
141
|
+
};
|
|
85
142
|
interface CompletionRequest {
|
|
86
143
|
/**
|
|
87
144
|
* The body of the completion request.
|
|
@@ -113,10 +170,7 @@ interface CompletionRequestOptions {
|
|
|
113
170
|
*/
|
|
114
171
|
customPrompt?: CustomPrompt;
|
|
115
172
|
}
|
|
116
|
-
type CustomPrompt = (completionMetadata: CompletionMetadata) =>
|
|
117
|
-
system?: string;
|
|
118
|
-
user?: string;
|
|
119
|
-
};
|
|
173
|
+
type CustomPrompt = (completionMetadata: CompletionMetadata) => Partial<PromptData>;
|
|
120
174
|
interface CompletionResponse {
|
|
121
175
|
completion: string | null;
|
|
122
176
|
error?: string;
|
|
@@ -164,26 +218,41 @@ interface CompletionMetadata {
|
|
|
164
218
|
};
|
|
165
219
|
}
|
|
166
220
|
|
|
167
|
-
/**
|
|
168
|
-
* Copilot class for handling completions using various AI providers.
|
|
169
|
-
*/
|
|
170
221
|
declare class Copilot {
|
|
171
222
|
private readonly apiKey;
|
|
172
223
|
private readonly provider;
|
|
173
224
|
private readonly model;
|
|
174
225
|
/**
|
|
175
|
-
* Initializes the Copilot with an API key and optional configuration.
|
|
226
|
+
* Initializes the Copilot instance with an API key and optional configuration.
|
|
176
227
|
* @param apiKey - The API key for the chosen provider.
|
|
177
|
-
* @param options -
|
|
228
|
+
* @param options - Optional configuration for the Copilot instance.
|
|
178
229
|
*/
|
|
179
230
|
constructor(apiKey: string, options?: CopilotOptions);
|
|
180
231
|
/**
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
* @returns A promise resolving to the completed text snippet or an error.
|
|
232
|
+
* Validates the inputs provided to the constructor.
|
|
233
|
+
* Ensures the selected model is supported by the provider.
|
|
184
234
|
*/
|
|
185
|
-
complete({ body, options, }: CompletionRequest): Promise<CompletionResponse>;
|
|
186
235
|
private validateInputs;
|
|
236
|
+
/**
|
|
237
|
+
* Generates the prompt based on the completion metadata and any custom prompt function.
|
|
238
|
+
* @param completionMetadata - The metadata for the completion.
|
|
239
|
+
* @param customPrompt - An optional custom prompt function.
|
|
240
|
+
* @returns The generated prompt.
|
|
241
|
+
*/
|
|
242
|
+
private generatePrompt;
|
|
243
|
+
/**
|
|
244
|
+
* Prepares the request details including endpoint, request body, and headers.
|
|
245
|
+
* @param prompt - The generated prompt.
|
|
246
|
+
* @param customHeaders - Any custom headers to include.
|
|
247
|
+
* @returns An object containing the endpoint, request body, and headers.
|
|
248
|
+
*/
|
|
249
|
+
private prepareRequest;
|
|
250
|
+
/**
|
|
251
|
+
* Sends a completion request to the API and returns the completion.
|
|
252
|
+
* @param request - The completion request containing the body and options.
|
|
253
|
+
* @returns A promise resolving to the completion response or an error.
|
|
254
|
+
*/
|
|
255
|
+
complete(request: CompletionRequest): Promise<CompletionResponse>;
|
|
187
256
|
}
|
|
188
257
|
|
|
189
258
|
/**
|
package/build/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var B=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Te=(t,e)=>{for(var o in e)B(t,o,{get:e[o],enumerable:!0})},Pe=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of fe(e))!Ee.call(t,n)&&n!==o&&B(t,n,{get:()=>e[n],enumerable:!(r=he(e,n))||r.enumerable});return t};var ye=t=>Pe(B({},"__esModule",{value:!0}),t);var De={};Te(De,{Copilot:()=>I,registerCopilot:()=>ue});module.exports=ye(De);var V={"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"},S={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"]},W="llama-3-70b",G="groq",Y={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},P=.3;var K=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var y=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}error(e,o){console.error(this.styleMessage(o.message,e,"error")),o.stack&&console.error(this.styleStackTrace(o.stack))}warn(e,o){console.warn(this.styleMessage(o,e,"warning"))}styleMessage(e,o,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,m=`\u2514${s}\u2518`,c=((w,Ce)=>{let ge=w.split(" "),_=[],C="";return ge.forEach(j=>{(C+j).length>Ce&&(_.push(C.trim()),C=""),C+=j+" "}),C.trim()&&_.push(C.trim()),_})(e,l-4),h=[a,...c.map(w=>`\u2502 ${w.padEnd(l-4)} \u2502`),m].join(`
|
|
2
2
|
`);return`
|
|
3
|
-
\x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${
|
|
4
|
-
${
|
|
3
|
+
\x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${o}]\x1B[0m \x1B[2m${i}\x1B[0m
|
|
4
|
+
${h}
|
|
5
5
|
`}styleStackTrace(e){return e.split(`
|
|
6
6
|
`).map((n,i)=>i===0?`\x1B[31m${n}\x1B[0m`:`\x1B[2m${n}\x1B[0m`).join(`
|
|
7
|
-
`)}getTimestamp(){return new Date().toISOString()}};var
|
|
8
|
-
`);return e[e.length-1].length+1};var
|
|
7
|
+
`)}getTimestamp(){return new Date().toISOString()}};var f=class f{constructor(){this.logger=y.getInstance()}static getInstance(){return f.instance}handleError(e,o){let r=this.getErrorDetails(e);return this.logger.error(o,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};f.instance=new f;var D=f;var d=(t,e)=>D.getInstance().handleError(t,e);var X=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((l,s)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=s,o=setTimeout(()=>{l(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},x=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var M=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],z=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),g=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),J=t=>{let e=t.split(`
|
|
8
|
+
`);return e[e.length-1].length+1};var k=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),$=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var Z=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=e==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(t,{method:e,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${o.error||"Network error"}: ${i.statusText}`);return i.json()},xe=(t,e)=>Z(t,"GET",e),Me=(t,e,o)=>Z(t,"POST",{...o,body:e}),R={GET:xe,POST:Me};var Q=(t,e)=>{let o=M(t,e);return!!o&&!K.has(o)},ee=(t,e)=>{let o=z(t,e).trim(),r=g(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var b="<<CURSOR>>",te=t=>t==="javascript"?"latest JavaScript":t,oe=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Re=t=>{let e=te(t.language),o=oe(t.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${o} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},be=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${x(t)}`:"",r=te(e);return`The code is written${r?` in ${r}`:""}${o}.`},Ie=t=>{let{filename:e,language:o,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=t,a=oe(n),m=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${m}.
|
|
9
9
|
|
|
10
|
-
`;return p+=
|
|
10
|
+
`;return p+=be(r,o),p+=`
|
|
11
11
|
|
|
12
12
|
Here are the details about how the completion should be generated:
|
|
13
|
-
- The cursor position is marked with '${
|
|
13
|
+
- The cursor position is marked with '${b}'.
|
|
14
14
|
- Your completion must start exactly at the cursor position.
|
|
15
15
|
- Do not repeat any code that appears before or after the cursor.
|
|
16
16
|
- Ensure your completion does not introduce any syntactical or logical errors.
|
|
17
|
-
`,n==="fill-in-the-middle"?p+=` - If filling in the middle, replace '${
|
|
18
|
-
`:n==="completion"&&(p+=` - If completing the code, start from '${
|
|
17
|
+
`,n==="fill-in-the-middle"?p+=` - If filling in the middle, replace '${b}' entirely with your completion.
|
|
18
|
+
`:n==="completion"&&(p+=` - If completing the code, start from '${b}' and provide a logical continuation.
|
|
19
19
|
`),p+=` - Optimize for readability and performance where possible.
|
|
20
20
|
|
|
21
21
|
Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
|
|
@@ -23,16 +23,16 @@ Here are the details about how the completion should be generated:
|
|
|
23
23
|
Here's the code snippet for completion:
|
|
24
24
|
|
|
25
25
|
<code>
|
|
26
|
-
${i}${
|
|
26
|
+
${i}${b}${l}
|
|
27
27
|
</code>`,s&&s.length>0&&(p+=`
|
|
28
28
|
|
|
29
29
|
Additional context from related files:
|
|
30
30
|
|
|
31
|
-
`,p+=s.map(
|
|
32
|
-
${
|
|
31
|
+
`,p+=s.map(c=>`// Path: ${c.path}
|
|
32
|
+
${c.content}
|
|
33
33
|
`).join(`
|
|
34
|
-
`)),p.endsWith(".")?p:`${p}.`};function
|
|
34
|
+
`)),p.endsWith(".")?p:`${p}.`};function H(t){return{system:Re(t),user:Ie(t)}}var re={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Oe={createRequestBody:(t,e)=>{let r=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:F(t),temperature:P,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the OpenAI response"}},ve={createRequestBody:(t,e)=>({model:F(t),temperature:P,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?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the Groq response"}},Le={createRequestBody:(t,e)=>({model:F(t),temperature:P,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:Ae(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>t.content?typeof t.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:t.content}:{completion:null,error:"No completion found in the Anthropic response"}},q={openai:Oe,groq:ve,anthropic:Le},ne=(t,e,o)=>{let r=q[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r.createRequestBody(t,o)},ie=(t,e)=>{let o=q[e];if(!o)throw new Error(`Unsupported provider: ${e}`);return o.createHeaders(t)},se=(t,e)=>{let o=q[e];if(!o)throw new Error(`Unsupported provider: ${e}`);return o.parseCompletion(t)},F=t=>V[t],ae=t=>Y[t],Ae=t=>re[t]||4096;var I=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??G,this.model=o.model??W,this.validateInputs()}validateInputs(){if(typeof this.model=="string"&&!S[this.provider].includes(this.model)){let e=x(S[this.provider]);throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${e}`)}}generatePrompt(e,o){let r=H(e);return o?{...r,...o(e)}:r}prepareRequest(e,o){let r=ae(this.provider),n,i=ie(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let s=this.model.config(this.apiKey,e);r=s.endpoint??r,n=s.body??{},i={...i,...s.headers}}else n=ne(this.model,this.provider,e);let l={...i,...o};return{endpoint:r,requestBody:n,headers:l}}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:l}=r??{},s=this.generatePrompt(n,l),{endpoint:a,requestBody:m,headers:p}=this.prepareRequest(s,i);try{let c=await R.POST(a,m,{headers:p});return typeof this.model=="object"&&"transformResponse"in this.model?this.model.transformResponse(c):se(c,this.provider)}catch(c){return{error:d(c,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}};var O=class t{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new t(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let o=/```[\s\S]*?```/g,r=e,n;for(;(n=o.exec(e))!==null;){let i=n[0],l=i.split(`
|
|
35
35
|
`).slice(1,-1).join(`
|
|
36
|
-
`);r=r.replace(i,
|
|
36
|
+
`);r=r.replace(i,l)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
37
37
|
|
|
38
|
-
`),this}build(){return this.formattedCompletion}};var v=class{constructor(e,
|
|
38
|
+
`),this}build(){return this.formattedCompletion}};var v=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!Q(this.cursorPosition,this.model)&&!ee(this.cursorPosition,this.model)}};var A=class A{constructor(){this.cache=[]}getCompletionCache(e,o){return this.cache.filter(r=>this.isCacheItemValid(r,e,o))}addCompletionCache(e){this.cache=[...this.cache.slice(-(A.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,o,r){let n=r.getValueInRange(e.range);return g(o,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){return e.range.startLineNumber===o.lineNumber&&o.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===o.lineNumber&&o.column>=e.range.startColumn-r.length&&o.column<=e.range.endColumn}};A.MAX_CACHE_SIZE=10;var L=A;var Ne="application/json",le=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:we({filename:t,position:l,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Ne},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},we=({filename:t,position:e,model:o,language:r,technologies:n,externalContext:i})=>{let l=_e(e,o),s=k(e,o),a=$(e,o);return{filename:t,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,cursorPosition:e,editorState:{completionMode:l}}},_e=(t,e)=>{let o=k(t,e),r=$(t,e);return o&&r?"fill-in-the-middle":"completion"};var pe=(t,e,o,r)=>{let n=(t.match(/\n/g)||[]).length,i=J(t),l=M(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+n,endColumn:t.includes(l)?o.lineNumber===e.startLineNumber&&n===0?o.column+(i-1):i:o.column}};function ce(t){return O.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=t=>({items:t,enableForwardStability:!0});var Be=300,me=X(le,Be),N=new L,Se=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new v(o,e).shouldProvideCompletions())return u([]);let s=N.getCompletionCache(o,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let a=me({...l,text:e.getValue(),model:e,position:o});r.onCancellationRequested(()=>{me.cancel()});let m=await a;if(m){let p=ce(m),c=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=pe(p,c,o,e);return N.addCompletionCache({completion:p,range:h,textBeforeCursorInLine:g(o,e)}),i(),u([{insertText:p,range:h}])}}catch(a){if(typeof a=="string"&&(a==="Cancelled"||a==="AbortError")||a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return u([]);d(a,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},de=Se;var E=new WeakMap,T=null,ue=(t,e,o)=>{T&&T.deregister();let r=[];E.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(s,a,m,p)=>{let c=E.get(e);if(c)return de({monaco:t,model:s,position:a,token:p,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0},options:o})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=E.get(e);if(!a)return;let m=s.keyCode===t.KeyCode.Tab||s.keyCode===t.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&m?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),N.clearCompletionCache(),E.delete(e),T=null}};return T=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),E.delete(e),T=null}}}};0&&(module.exports={Copilot,registerCopilot});
|
package/build/index.mjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j={"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"]},V="llama-3-70b",W="groq",G={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},P=.3;var Y=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var y=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}error(e,o){console.error(this.styleMessage(o.message,e,"error")),o.stack&&console.error(this.styleStackTrace(o.stack))}warn(e,o){console.warn(this.styleMessage(o,e,"warning"))}styleMessage(e,o,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,m=`\u2514${s}\u2518`,c=((N,de)=>{let ue=N.split(" "),w=[],C="";return ue.forEach(U=>{(C+U).length>de&&(w.push(C.trim()),C=""),C+=U+" "}),C.trim()&&w.push(C.trim()),w})(e,l-4),h=[a,...c.map(N=>`\u2502 ${N.padEnd(l-4)} \u2502`),m].join(`
|
|
2
2
|
`);return`
|
|
3
|
-
\x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${
|
|
4
|
-
${
|
|
3
|
+
\x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${o}]\x1B[0m \x1B[2m${i}\x1B[0m
|
|
4
|
+
${h}
|
|
5
5
|
`}styleStackTrace(e){return e.split(`
|
|
6
6
|
`).map((n,i)=>i===0?`\x1B[31m${n}\x1B[0m`:`\x1B[2m${n}\x1B[0m`).join(`
|
|
7
|
-
`)}getTimestamp(){return new Date().toISOString()}};var
|
|
8
|
-
`);return e[e.length-1].length+1};var
|
|
7
|
+
`)}getTimestamp(){return new Date().toISOString()}};var f=class f{constructor(){this.logger=y.getInstance()}static getInstance(){return f.instance}handleError(e,o){let r=this.getErrorDetails(e);return this.logger.error(o,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};f.instance=new f;var B=f;var d=(t,e)=>B.getInstance().handleError(t,e);var K=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((l,s)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=s,o=setTimeout(()=>{l(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},x=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var M=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],X=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),g=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),z=t=>{let e=t.split(`
|
|
8
|
+
`);return e[e.length-1].length+1};var S=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),D=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var J=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=e==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(t,{method:e,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${o.error||"Network error"}: ${i.statusText}`);return i.json()},Ce=(t,e)=>J(t,"GET",e),ge=(t,e,o)=>J(t,"POST",{...o,body:e}),R={GET:Ce,POST:ge};var Z=(t,e)=>{let o=M(t,e);return!!o&&!Y.has(o)},Q=(t,e)=>{let o=X(t,e).trim(),r=g(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var b="<<CURSOR>>",ee=t=>t==="javascript"?"latest JavaScript":t,te=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},he=t=>{let e=ee(t.language),o=te(t.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${o} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},fe=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${x(t)}`:"",r=ee(e);return`The code is written${r?` in ${r}`:""}${o}.`},Ee=t=>{let{filename:e,language:o,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=t,a=te(n),m=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${m}.
|
|
9
9
|
|
|
10
|
-
`;return p+=
|
|
10
|
+
`;return p+=fe(r,o),p+=`
|
|
11
11
|
|
|
12
12
|
Here are the details about how the completion should be generated:
|
|
13
|
-
- The cursor position is marked with '${
|
|
13
|
+
- The cursor position is marked with '${b}'.
|
|
14
14
|
- Your completion must start exactly at the cursor position.
|
|
15
15
|
- Do not repeat any code that appears before or after the cursor.
|
|
16
16
|
- Ensure your completion does not introduce any syntactical or logical errors.
|
|
17
|
-
`,n==="fill-in-the-middle"?p+=` - If filling in the middle, replace '${
|
|
18
|
-
`:n==="completion"&&(p+=` - If completing the code, start from '${
|
|
17
|
+
`,n==="fill-in-the-middle"?p+=` - If filling in the middle, replace '${b}' entirely with your completion.
|
|
18
|
+
`:n==="completion"&&(p+=` - If completing the code, start from '${b}' and provide a logical continuation.
|
|
19
19
|
`),p+=` - Optimize for readability and performance where possible.
|
|
20
20
|
|
|
21
21
|
Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
|
|
@@ -23,16 +23,16 @@ Here are the details about how the completion should be generated:
|
|
|
23
23
|
Here's the code snippet for completion:
|
|
24
24
|
|
|
25
25
|
<code>
|
|
26
|
-
${i}${
|
|
26
|
+
${i}${b}${l}
|
|
27
27
|
</code>`,s&&s.length>0&&(p+=`
|
|
28
28
|
|
|
29
29
|
Additional context from related files:
|
|
30
30
|
|
|
31
|
-
`,p+=s.map(
|
|
32
|
-
${
|
|
31
|
+
`,p+=s.map(c=>`// Path: ${c.path}
|
|
32
|
+
${c.content}
|
|
33
33
|
`).join(`
|
|
34
|
-
`)),p.endsWith(".")?p:`${p}.`};function
|
|
34
|
+
`)),p.endsWith(".")?p:`${p}.`};function k(t){return{system:he(t),user:Ee(t)}}var oe={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Te={createRequestBody:(t,e)=>{let r=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:H(t),temperature:P,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the OpenAI response"}},Pe={createRequestBody:(t,e)=>({model:H(t),temperature:P,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?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the Groq response"}},ye={createRequestBody:(t,e)=>({model:H(t),temperature:P,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:xe(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>t.content?typeof t.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:t.content}:{completion:null,error:"No completion found in the Anthropic response"}},$={openai:Te,groq:Pe,anthropic:ye},re=(t,e,o)=>{let r=$[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r.createRequestBody(t,o)},ne=(t,e)=>{let o=$[e];if(!o)throw new Error(`Unsupported provider: ${e}`);return o.createHeaders(t)},ie=(t,e)=>{let o=$[e];if(!o)throw new Error(`Unsupported provider: ${e}`);return o.parseCompletion(t)},H=t=>j[t],se=t=>G[t],xe=t=>oe[t]||4096;var q=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??W,this.model=o.model??V,this.validateInputs()}validateInputs(){if(typeof this.model=="string"&&!_[this.provider].includes(this.model)){let e=x(_[this.provider]);throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${e}`)}}generatePrompt(e,o){let r=k(e);return o?{...r,...o(e)}:r}prepareRequest(e,o){let r=se(this.provider),n,i=ne(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let s=this.model.config(this.apiKey,e);r=s.endpoint??r,n=s.body??{},i={...i,...s.headers}}else n=re(this.model,this.provider,e);let l={...i,...o};return{endpoint:r,requestBody:n,headers:l}}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:l}=r??{},s=this.generatePrompt(n,l),{endpoint:a,requestBody:m,headers:p}=this.prepareRequest(s,i);try{let c=await R.POST(a,m,{headers:p});return typeof this.model=="object"&&"transformResponse"in this.model?this.model.transformResponse(c):ie(c,this.provider)}catch(c){return{error:d(c,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}};var I=class t{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new t(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let o=/```[\s\S]*?```/g,r=e,n;for(;(n=o.exec(e))!==null;){let i=n[0],l=i.split(`
|
|
35
35
|
`).slice(1,-1).join(`
|
|
36
|
-
`);r=r.replace(i,
|
|
36
|
+
`);r=r.replace(i,l)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
37
37
|
|
|
38
|
-
`),this}build(){return this.formattedCompletion}};var
|
|
38
|
+
`),this}build(){return this.formattedCompletion}};var O=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!Z(this.cursorPosition,this.model)&&!Q(this.cursorPosition,this.model)}};var L=class L{constructor(){this.cache=[]}getCompletionCache(e,o){return this.cache.filter(r=>this.isCacheItemValid(r,e,o))}addCompletionCache(e){this.cache=[...this.cache.slice(-(L.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,o,r){let n=r.getValueInRange(e.range);return g(o,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){return e.range.startLineNumber===o.lineNumber&&o.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===o.lineNumber&&o.column>=e.range.startColumn-r.length&&o.column<=e.range.endColumn}};L.MAX_CACHE_SIZE=10;var v=L;var Me="application/json",ae=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:Re({filename:t,position:l,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Me},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Re=({filename:t,position:e,model:o,language:r,technologies:n,externalContext:i})=>{let l=be(e,o),s=S(e,o),a=D(e,o);return{filename:t,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,cursorPosition:e,editorState:{completionMode:l}}},be=(t,e)=>{let o=S(t,e),r=D(t,e);return o&&r?"fill-in-the-middle":"completion"};var le=(t,e,o,r)=>{let n=(t.match(/\n/g)||[]).length,i=z(t),l=M(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+n,endColumn:t.includes(l)?o.lineNumber===e.startLineNumber&&n===0?o.column+(i-1):i:o.column}};function pe(t){return I.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=t=>({items:t,enableForwardStability:!0});var Ie=300,ce=K(ae,Ie),A=new v,Oe=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new O(o,e).shouldProvideCompletions())return u([]);let s=A.getCompletionCache(o,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let a=ce({...l,text:e.getValue(),model:e,position:o});r.onCancellationRequested(()=>{ce.cancel()});let m=await a;if(m){let p=pe(m),c=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=le(p,c,o,e);return A.addCompletionCache({completion:p,range:h,textBeforeCursorInLine:g(o,e)}),i(),u([{insertText:p,range:h}])}}catch(a){if(typeof a=="string"&&(a==="Cancelled"||a==="AbortError")||a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return u([]);d(a,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},me=Oe;var E=new WeakMap,T=null,ve=(t,e,o)=>{T&&T.deregister();let r=[];E.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(s,a,m,p)=>{let c=E.get(e);if(c)return me({monaco:t,model:s,position:a,token:p,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0},options:o})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=E.get(e);if(!a)return;let m=s.keyCode===t.KeyCode.Tab||s.keyCode===t.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&m?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),A.clearCompletionCache(),E.delete(e),T=null}};return T=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),E.delete(e),T=null}}}};export{q as Copilot,ve as registerCopilot};
|