monacopilot 0.18.19 → 0.19.0-beta.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/package.json +45 -68
- package/build/index.d.mts +0 -359
- package/build/index.d.ts +0 -359
- package/build/index.js +0 -44
- package/build/index.mjs +0 -44
package/package.json
CHANGED
|
@@ -1,69 +1,46 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"monaco-editor",
|
|
48
|
-
"monaco",
|
|
49
|
-
"ai",
|
|
50
|
-
"auto-completion",
|
|
51
|
-
"code-completion",
|
|
52
|
-
"copilot",
|
|
53
|
-
"github-copilot"
|
|
54
|
-
],
|
|
55
|
-
"repository": {
|
|
56
|
-
"type": "git",
|
|
57
|
-
"url": "git+https://github.com/arshad-yaseen/monacopilot.git"
|
|
58
|
-
},
|
|
59
|
-
"homepage": "https://copilot.arshadyaseen.com",
|
|
60
|
-
"maintainers": [
|
|
61
|
-
{
|
|
62
|
-
"name": "Arshad Yaseen",
|
|
63
|
-
"email": "m@arshadyaseen.com",
|
|
64
|
-
"url": "https://arshadyaseen.com"
|
|
65
|
-
}
|
|
66
|
-
],
|
|
67
|
-
"license": "MIT",
|
|
68
|
-
"author": "Arshad Yaseen <m@arshadyaseen.com> (https://arshadyaseen.com)"
|
|
69
|
-
}
|
|
2
|
+
"name": "monacopilot",
|
|
3
|
+
"version": "0.19.0-beta.8",
|
|
4
|
+
"description": "AI auto-completion plugin for Monaco Editor",
|
|
5
|
+
"main": "./build/index.js",
|
|
6
|
+
"module": "./build/index.mjs",
|
|
7
|
+
"types": "./build/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"build"
|
|
10
|
+
],
|
|
11
|
+
"devDependencies": {
|
|
12
|
+
"monaco-editor": "^0.52.0",
|
|
13
|
+
"tsup": "^8.0.2",
|
|
14
|
+
"typescript": "^5.4.3"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"monaco-editor",
|
|
18
|
+
"monaco",
|
|
19
|
+
"ai",
|
|
20
|
+
"auto-completion",
|
|
21
|
+
"code-completion",
|
|
22
|
+
"copilot",
|
|
23
|
+
"github-copilot"
|
|
24
|
+
],
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/arshad-yaseen/monacopilot.git"
|
|
28
|
+
},
|
|
29
|
+
"homepage": "https://copilot.arshadyaseen.com",
|
|
30
|
+
"maintainers": [
|
|
31
|
+
{
|
|
32
|
+
"name": "Arshad Yaseen",
|
|
33
|
+
"email": "m@arshadyaseen.com",
|
|
34
|
+
"url": "https://arshadyaseen.com"
|
|
35
|
+
}
|
|
36
|
+
],
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"author": "Arshad Yaseen <m@arshadyaseen.com> (https://arshadyaseen.com)",
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@monacopilot/core": "0.19.0-beta.8"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsup src/index.ts",
|
|
44
|
+
"dev": "tsup src/index.ts --watch"
|
|
45
|
+
}
|
|
46
|
+
}
|
package/build/index.d.mts
DELETED
|
@@ -1,359 +0,0 @@
|
|
|
1
|
-
import { MessageCreateParams, Message } from '@anthropic-ai/sdk/resources';
|
|
2
|
-
import { GenerateContentRequest, GenerateContentResponse } from '@google/generative-ai';
|
|
3
|
-
import { ChatCompletionCreateParamsBase as ChatCompletionCreateParamsBase$1, ChatCompletion as ChatCompletion$1 } from 'groq-sdk/resources/chat/completions';
|
|
4
|
-
import { ChatCompletionCreateParamsBase, ChatCompletion } from 'openai/resources/chat/completions';
|
|
5
|
-
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
6
|
-
|
|
7
|
-
declare const MODEL_IDS: Record<Model, string>;
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Providers supported by Copilot.
|
|
11
|
-
*/
|
|
12
|
-
type Provider = 'openai' | 'groq' | 'anthropic' | 'google' | 'deepseek';
|
|
13
|
-
type DeepSeekChatCompletionType = {
|
|
14
|
-
choices: {
|
|
15
|
-
text: string;
|
|
16
|
-
}[];
|
|
17
|
-
};
|
|
18
|
-
type DeepSeekChatCompletionCreateParamsBase = {
|
|
19
|
-
model: (typeof MODEL_IDS)['v3'];
|
|
20
|
-
prompt: string;
|
|
21
|
-
suffix: string;
|
|
22
|
-
temperature: number;
|
|
23
|
-
max_tokens: number;
|
|
24
|
-
};
|
|
25
|
-
/**
|
|
26
|
-
* Core type mapping for provider-specific implementations
|
|
27
|
-
*/
|
|
28
|
-
interface ProviderImplementationMap {
|
|
29
|
-
openai: {
|
|
30
|
-
Model: 'gpt-4o' | 'gpt-4o-mini' | 'o1-mini';
|
|
31
|
-
Params: ChatCompletionCreateParamsBase;
|
|
32
|
-
Completion: ChatCompletion;
|
|
33
|
-
};
|
|
34
|
-
groq: {
|
|
35
|
-
Model: 'llama-3-70b';
|
|
36
|
-
Params: ChatCompletionCreateParamsBase$1;
|
|
37
|
-
Completion: ChatCompletion$1;
|
|
38
|
-
};
|
|
39
|
-
anthropic: {
|
|
40
|
-
Model: 'claude-3-5-sonnet' | 'claude-3-5-haiku' | 'claude-3-haiku';
|
|
41
|
-
Params: MessageCreateParams;
|
|
42
|
-
Completion: Message;
|
|
43
|
-
};
|
|
44
|
-
google: {
|
|
45
|
-
Model: 'gemini-1.5-flash' | 'gemini-1.5-flash-8b' | 'gemini-1.5-pro';
|
|
46
|
-
Params: GenerateContentRequest;
|
|
47
|
-
Completion: GenerateContentResponse;
|
|
48
|
-
};
|
|
49
|
-
deepseek: {
|
|
50
|
-
Model: 'v3';
|
|
51
|
-
Params: DeepSeekChatCompletionCreateParamsBase;
|
|
52
|
-
Completion: DeepSeekChatCompletionType;
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Models available for each provider (maintained as individual exports)
|
|
57
|
-
*/
|
|
58
|
-
type OpenAIModel = ProviderImplementationMap['openai']['Model'];
|
|
59
|
-
type GroqModel = ProviderImplementationMap['groq']['Model'];
|
|
60
|
-
type AnthropicModel = ProviderImplementationMap['anthropic']['Model'];
|
|
61
|
-
type GoogleModel = ProviderImplementationMap['google']['Model'];
|
|
62
|
-
type DeepSeekModel = ProviderImplementationMap['deepseek']['Model'];
|
|
63
|
-
/**
|
|
64
|
-
* Union of all predefined Copilot models
|
|
65
|
-
*/
|
|
66
|
-
type Model = {
|
|
67
|
-
[K in Provider]: ProviderImplementationMap[K]['Model'];
|
|
68
|
-
}[Provider];
|
|
69
|
-
type OpenAIChatCompletion = ChatCompletion;
|
|
70
|
-
type DeepSeekChatCompletion = DeepSeekChatCompletionType;
|
|
71
|
-
type GroqChatCompletion = ChatCompletion$1;
|
|
72
|
-
type AnthropicChatCompletion = Message;
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Data structure representing the prompt data.
|
|
76
|
-
*/
|
|
77
|
-
interface PromptData {
|
|
78
|
-
system: string;
|
|
79
|
-
user: string;
|
|
80
|
-
}
|
|
81
|
-
/**
|
|
82
|
-
* Custom model configuration types
|
|
83
|
-
*/
|
|
84
|
-
type CustomCopilotModelConfig = (apiKey: string, prompt: PromptData) => {
|
|
85
|
-
/** The URL endpoint for the custom model's API */
|
|
86
|
-
endpoint: string;
|
|
87
|
-
/** Additional HTTP headers */
|
|
88
|
-
headers?: Record<string, string>;
|
|
89
|
-
/** Request body data */
|
|
90
|
-
body?: Record<string, unknown>;
|
|
91
|
-
};
|
|
92
|
-
type CustomCopilotModelTransformResponse = (response: unknown) => {
|
|
93
|
-
/** The generated text */
|
|
94
|
-
text: string | null;
|
|
95
|
-
};
|
|
96
|
-
interface CustomCopilotModel {
|
|
97
|
-
/** Configuration function */
|
|
98
|
-
config: CustomCopilotModelConfig;
|
|
99
|
-
/** Response transformer */
|
|
100
|
-
transformResponse: CustomCopilotModelTransformResponse;
|
|
101
|
-
}
|
|
102
|
-
type CustomOptions = {
|
|
103
|
-
provider?: undefined;
|
|
104
|
-
model: CustomCopilotModel;
|
|
105
|
-
};
|
|
106
|
-
type CopilotOptions = ProviderOptions<'openai'> | ProviderOptions<'groq'> | ProviderOptions<'anthropic'> | ProviderOptions<'google'> | ProviderOptions<'deepseek'> | CustomOptions;
|
|
107
|
-
type ProviderOptions<T extends Provider> = {
|
|
108
|
-
provider: T;
|
|
109
|
-
model: ProviderImplementationMap[T]['Model'];
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
type Monaco = typeof monaco;
|
|
113
|
-
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
114
|
-
type CursorPosition = monaco.IPosition;
|
|
115
|
-
type EditorRange = monaco.IRange;
|
|
116
|
-
|
|
117
|
-
type FetchCompletionItemHandler = (params: FetchCompletionItemParams) => Promise<FetchCompletionItemReturn>;
|
|
118
|
-
type FetchCompletionItemReturn = {
|
|
119
|
-
completion: string | null;
|
|
120
|
-
};
|
|
121
|
-
interface FetchCompletionItemParams {
|
|
122
|
-
endpoint: string;
|
|
123
|
-
body: CompletionRequestBody;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
type Endpoint = string;
|
|
127
|
-
type Filename = string;
|
|
128
|
-
type Technologies = string[];
|
|
129
|
-
type RelatedFile = {
|
|
130
|
-
/**
|
|
131
|
-
* The relative path from the current editing code in the editor to an external file.
|
|
132
|
-
*
|
|
133
|
-
* Examples:
|
|
134
|
-
* - To include a file `utils.js` in the same directory, set as `./utils.js`.
|
|
135
|
-
* - To include a file `utils.js` in the parent directory, set as `../utils.js`.
|
|
136
|
-
* - To include a file `utils.js` in the child directory, set as `./child/utils.js`.
|
|
137
|
-
*/
|
|
138
|
-
path: string;
|
|
139
|
-
/**
|
|
140
|
-
* The content of the external file as a string.
|
|
141
|
-
*/
|
|
142
|
-
content: string;
|
|
143
|
-
};
|
|
144
|
-
interface RegisterCompletionOptions {
|
|
145
|
-
/**
|
|
146
|
-
* Language of the current model
|
|
147
|
-
*/
|
|
148
|
-
language: string;
|
|
149
|
-
/**
|
|
150
|
-
* The API endpoint where you started the completion service.
|
|
151
|
-
*/
|
|
152
|
-
endpoint: Endpoint;
|
|
153
|
-
/**
|
|
154
|
-
* Specifies when the completion service should provide code completions.
|
|
155
|
-
*
|
|
156
|
-
* Options:
|
|
157
|
-
* - `'onIdle'`: Provides completions after a brief pause in typing.
|
|
158
|
-
* - `'onTyping'`: Provides completions in real-time as you type.
|
|
159
|
-
* - *Note:* Best suited for models with low response latency (e.g., Groq).
|
|
160
|
-
* - *Consideration:* May initiate additional background requests to deliver real-time suggestions.
|
|
161
|
-
* - `'onDemand'`: Completions are not provided automatically. You need to trigger the completion manually, possibly by using the `trigger` function from `registerCompletion` return.
|
|
162
|
-
*
|
|
163
|
-
* @default 'onIdle'
|
|
164
|
-
*/
|
|
165
|
-
trigger?: 'onTyping' | 'onIdle' | 'onDemand';
|
|
166
|
-
/**
|
|
167
|
-
* The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
|
|
168
|
-
* For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
|
|
169
|
-
*/
|
|
170
|
-
filename?: Filename;
|
|
171
|
-
/**
|
|
172
|
-
* The technologies (libraries, frameworks, etc.) you want to use for the completion.
|
|
173
|
-
* This can provide technology-specific completions.
|
|
174
|
-
* If you don't specify a technology, the completion will be specific to the language (provided as the `language`).
|
|
175
|
-
*
|
|
176
|
-
* @example
|
|
177
|
-
* ['react', 'nextjs', 'tailwindcss', 'tanstack/react-query']
|
|
178
|
-
* ['tensorflow', 'keras', 'numpy', 'pandas']
|
|
179
|
-
* etc.
|
|
180
|
-
*/
|
|
181
|
-
technologies?: Technologies;
|
|
182
|
-
/**
|
|
183
|
-
* Helps to give more relevant completions based on the full context.
|
|
184
|
-
* You can include things like the contents/codes of other files in the same workspace.
|
|
185
|
-
*/
|
|
186
|
-
relatedFiles?: RelatedFile[];
|
|
187
|
-
/**
|
|
188
|
-
* The maximum number of lines of code to include in the completion request.
|
|
189
|
-
* This limits the request size to the model to prevent `429 Too Many Requests` errors
|
|
190
|
-
* and reduce costs for long code.
|
|
191
|
-
*
|
|
192
|
-
* It is recommended to set `maxContextLines` to `60` or less if you are using `Groq` as your provider,
|
|
193
|
-
* since `Groq` does not implement pay-as-you-go pricing and has only low rate limits.
|
|
194
|
-
*/
|
|
195
|
-
maxContextLines?: number;
|
|
196
|
-
/**
|
|
197
|
-
* Determines if completions should be cached.
|
|
198
|
-
* Enabling caching can enhance performance by reusing previous results when the cursor position and context remain the same while editing.
|
|
199
|
-
* @default true
|
|
200
|
-
*/
|
|
201
|
-
enableCaching?: boolean;
|
|
202
|
-
/**
|
|
203
|
-
* When an error occurs during the completion process or requests, Monacopilot will log it to the console by default
|
|
204
|
-
* rather than throwing errors. This ensures smooth editing even when completions are unavailable.
|
|
205
|
-
* You can provide this callback to handle errors yourself, which will disable the default console logging.
|
|
206
|
-
* @param error - The error object containing information about the encountered error.
|
|
207
|
-
*/
|
|
208
|
-
onError?: (error: Error) => void;
|
|
209
|
-
/**
|
|
210
|
-
* Custom fetch completion handler. This function overrides the default fetch completion handler.
|
|
211
|
-
* It allows you to customize how completion requests are made and responses are processed.
|
|
212
|
-
* You can implement your own logic for fetching and processing completions.
|
|
213
|
-
* The function should return either a string (the completion to be inserted into the editor) or null.
|
|
214
|
-
* @param params - The parameters for the completion request.
|
|
215
|
-
* @param {string} params.endpoint - The endpoint to fetch the completion from.
|
|
216
|
-
* @param {CompletionRequestBody} params.body - The body of the completion request.
|
|
217
|
-
* @returns {Promise<{completion: string | null}>} An object containing the completion or null if no completion is available.
|
|
218
|
-
*/
|
|
219
|
-
requestHandler?: FetchCompletionItemHandler;
|
|
220
|
-
/**
|
|
221
|
-
* Callback function that is triggered when a completion is shown in the editor.
|
|
222
|
-
* @param completion - The completion text that is being shown.
|
|
223
|
-
* @param range - The editor range where the completion will be inserted.
|
|
224
|
-
*/
|
|
225
|
-
onCompletionShown?: (completion: string, range: EditorRange | undefined) => void;
|
|
226
|
-
/**
|
|
227
|
-
* Callback function triggered when a completion is accepted by the user.
|
|
228
|
-
*/
|
|
229
|
-
onCompletionAccepted?: () => void;
|
|
230
|
-
/**
|
|
231
|
-
* Callback function triggered when a completion is rejected by the user.
|
|
232
|
-
*/
|
|
233
|
-
onCompletionRejected?: () => void;
|
|
234
|
-
}
|
|
235
|
-
interface CompletionRegistration {
|
|
236
|
-
/**
|
|
237
|
-
* Triggers the completion.
|
|
238
|
-
*/
|
|
239
|
-
trigger: () => void;
|
|
240
|
-
/**
|
|
241
|
-
* Deregisters the completion provider and cleans up all associated resources.
|
|
242
|
-
* This should be called when unmounting the editor or when completion features
|
|
243
|
-
* are no longer needed to prevent memory leaks and ensure proper cleanup.
|
|
244
|
-
*/
|
|
245
|
-
deregister: () => void;
|
|
246
|
-
}
|
|
247
|
-
interface CompletionRequest {
|
|
248
|
-
/**
|
|
249
|
-
* The body of the completion request.
|
|
250
|
-
*/
|
|
251
|
-
body: CompletionRequestBody;
|
|
252
|
-
/**
|
|
253
|
-
* Additional options to include in the completion request.
|
|
254
|
-
*/
|
|
255
|
-
options?: CompletionRequestOptions;
|
|
256
|
-
}
|
|
257
|
-
interface CompletionRequestBody {
|
|
258
|
-
/**
|
|
259
|
-
* The metadata required to generate the completion.
|
|
260
|
-
*/
|
|
261
|
-
completionMetadata: CompletionMetadata;
|
|
262
|
-
}
|
|
263
|
-
interface CompletionRequestOptions {
|
|
264
|
-
/**
|
|
265
|
-
* Custom headers to include in the request to the LLM provider.
|
|
266
|
-
*/
|
|
267
|
-
headers?: Record<string, string>;
|
|
268
|
-
/**
|
|
269
|
-
* Custom prompt generator function for the completion request.
|
|
270
|
-
* This function allows you to override the default system and user prompts
|
|
271
|
-
* used in the completion request, providing more control over the AI's context and behavior.
|
|
272
|
-
*
|
|
273
|
-
* @param completionMetadata - Metadata about the current completion context
|
|
274
|
-
* @returns An object containing custom 'system' and 'user' prompts
|
|
275
|
-
*/
|
|
276
|
-
customPrompt?: CustomPrompt;
|
|
277
|
-
}
|
|
278
|
-
type CustomPrompt = (completionMetadata: CompletionMetadata) => Partial<PromptData>;
|
|
279
|
-
interface CompletionResponse {
|
|
280
|
-
/**
|
|
281
|
-
* The completion text.
|
|
282
|
-
*/
|
|
283
|
-
completion: string | null;
|
|
284
|
-
/**
|
|
285
|
-
* The error message.
|
|
286
|
-
*/
|
|
287
|
-
error?: string;
|
|
288
|
-
/**
|
|
289
|
-
* The raw response from the LLM.
|
|
290
|
-
*/
|
|
291
|
-
raw?: unknown;
|
|
292
|
-
}
|
|
293
|
-
type CompletionMode = 'insert' | 'complete' | 'continue';
|
|
294
|
-
interface CompletionMetadata {
|
|
295
|
-
/**
|
|
296
|
-
* The programming language of the code.
|
|
297
|
-
*/
|
|
298
|
-
language: string | undefined;
|
|
299
|
-
/**
|
|
300
|
-
* The name of the file being edited.
|
|
301
|
-
*/
|
|
302
|
-
filename: Filename | undefined;
|
|
303
|
-
/**
|
|
304
|
-
* The technologies used in the completion.
|
|
305
|
-
*/
|
|
306
|
-
technologies: Technologies | undefined;
|
|
307
|
-
/**
|
|
308
|
-
* Additional context from related files.
|
|
309
|
-
*/
|
|
310
|
-
relatedFiles: RelatedFile[] | undefined;
|
|
311
|
-
/**
|
|
312
|
-
* The text that appears after the cursor.
|
|
313
|
-
*/
|
|
314
|
-
textAfterCursor: string;
|
|
315
|
-
/**
|
|
316
|
-
* The text that appears before the cursor.
|
|
317
|
-
*/
|
|
318
|
-
textBeforeCursor: string;
|
|
319
|
-
/**
|
|
320
|
-
* The current cursor position.
|
|
321
|
-
*/
|
|
322
|
-
cursorPosition: CursorPosition;
|
|
323
|
-
/**
|
|
324
|
-
* The current state of the editor.
|
|
325
|
-
*/
|
|
326
|
-
editorState: {
|
|
327
|
-
/**
|
|
328
|
-
* The mode of the completion.
|
|
329
|
-
* - `insert`: Indicates that there is a character immediately after the cursor. In this mode, the LLM will generate content to be inserted at the cursor position.
|
|
330
|
-
* - `complete`: Indicates that there is a character after the cursor but not immediately. In this mode, the LLM will generate content to complete the text from the cursor position.
|
|
331
|
-
* - `continue`: Indicates that there is no character after the cursor. In this mode, the LLM will generate content to continue the text from the cursor position.
|
|
332
|
-
*/
|
|
333
|
-
completionMode: CompletionMode;
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
/**
|
|
338
|
-
* Registers completion functionality with the Monaco editor.
|
|
339
|
-
* @param monaco - The Monaco instance.
|
|
340
|
-
* @param editor - The editor instance.
|
|
341
|
-
* @param options - Options for the completion.
|
|
342
|
-
* @returns A CompletionRegistration object with deregister and trigger methods.
|
|
343
|
-
*/
|
|
344
|
-
declare const registerCompletion: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCompletionOptions) => CompletionRegistration;
|
|
345
|
-
|
|
346
|
-
declare class Copilot {
|
|
347
|
-
private readonly apiKey;
|
|
348
|
-
private provider;
|
|
349
|
-
private model;
|
|
350
|
-
constructor(apiKey: string, options: CopilotOptions);
|
|
351
|
-
complete(request: CompletionRequest): Promise<CompletionResponse>;
|
|
352
|
-
private generatePrompt;
|
|
353
|
-
private prepareRequestDetails;
|
|
354
|
-
private sendCompletionRequest;
|
|
355
|
-
private processCompletionResponse;
|
|
356
|
-
private handleCompletionError;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
export { type AnthropicChatCompletion, type AnthropicModel, type CompletionMetadata, type CompletionRegistration, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, Copilot, type CopilotOptions, type CustomCopilotModel, type CustomCopilotModelConfig, type CustomCopilotModelTransformResponse, type DeepSeekChatCompletion, type DeepSeekModel, type GoogleModel, type GroqChatCompletion, type GroqModel, type Model, type Monaco, type OpenAIChatCompletion, type OpenAIModel, type Provider, type RegisterCompletionOptions, type StandaloneCodeEditor, registerCompletion };
|
package/build/index.d.ts
DELETED
|
@@ -1,359 +0,0 @@
|
|
|
1
|
-
import { MessageCreateParams, Message } from '@anthropic-ai/sdk/resources';
|
|
2
|
-
import { GenerateContentRequest, GenerateContentResponse } from '@google/generative-ai';
|
|
3
|
-
import { ChatCompletionCreateParamsBase as ChatCompletionCreateParamsBase$1, ChatCompletion as ChatCompletion$1 } from 'groq-sdk/resources/chat/completions';
|
|
4
|
-
import { ChatCompletionCreateParamsBase, ChatCompletion } from 'openai/resources/chat/completions';
|
|
5
|
-
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
6
|
-
|
|
7
|
-
declare const MODEL_IDS: Record<Model, string>;
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Providers supported by Copilot.
|
|
11
|
-
*/
|
|
12
|
-
type Provider = 'openai' | 'groq' | 'anthropic' | 'google' | 'deepseek';
|
|
13
|
-
type DeepSeekChatCompletionType = {
|
|
14
|
-
choices: {
|
|
15
|
-
text: string;
|
|
16
|
-
}[];
|
|
17
|
-
};
|
|
18
|
-
type DeepSeekChatCompletionCreateParamsBase = {
|
|
19
|
-
model: (typeof MODEL_IDS)['v3'];
|
|
20
|
-
prompt: string;
|
|
21
|
-
suffix: string;
|
|
22
|
-
temperature: number;
|
|
23
|
-
max_tokens: number;
|
|
24
|
-
};
|
|
25
|
-
/**
|
|
26
|
-
* Core type mapping for provider-specific implementations
|
|
27
|
-
*/
|
|
28
|
-
interface ProviderImplementationMap {
|
|
29
|
-
openai: {
|
|
30
|
-
Model: 'gpt-4o' | 'gpt-4o-mini' | 'o1-mini';
|
|
31
|
-
Params: ChatCompletionCreateParamsBase;
|
|
32
|
-
Completion: ChatCompletion;
|
|
33
|
-
};
|
|
34
|
-
groq: {
|
|
35
|
-
Model: 'llama-3-70b';
|
|
36
|
-
Params: ChatCompletionCreateParamsBase$1;
|
|
37
|
-
Completion: ChatCompletion$1;
|
|
38
|
-
};
|
|
39
|
-
anthropic: {
|
|
40
|
-
Model: 'claude-3-5-sonnet' | 'claude-3-5-haiku' | 'claude-3-haiku';
|
|
41
|
-
Params: MessageCreateParams;
|
|
42
|
-
Completion: Message;
|
|
43
|
-
};
|
|
44
|
-
google: {
|
|
45
|
-
Model: 'gemini-1.5-flash' | 'gemini-1.5-flash-8b' | 'gemini-1.5-pro';
|
|
46
|
-
Params: GenerateContentRequest;
|
|
47
|
-
Completion: GenerateContentResponse;
|
|
48
|
-
};
|
|
49
|
-
deepseek: {
|
|
50
|
-
Model: 'v3';
|
|
51
|
-
Params: DeepSeekChatCompletionCreateParamsBase;
|
|
52
|
-
Completion: DeepSeekChatCompletionType;
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Models available for each provider (maintained as individual exports)
|
|
57
|
-
*/
|
|
58
|
-
type OpenAIModel = ProviderImplementationMap['openai']['Model'];
|
|
59
|
-
type GroqModel = ProviderImplementationMap['groq']['Model'];
|
|
60
|
-
type AnthropicModel = ProviderImplementationMap['anthropic']['Model'];
|
|
61
|
-
type GoogleModel = ProviderImplementationMap['google']['Model'];
|
|
62
|
-
type DeepSeekModel = ProviderImplementationMap['deepseek']['Model'];
|
|
63
|
-
/**
|
|
64
|
-
* Union of all predefined Copilot models
|
|
65
|
-
*/
|
|
66
|
-
type Model = {
|
|
67
|
-
[K in Provider]: ProviderImplementationMap[K]['Model'];
|
|
68
|
-
}[Provider];
|
|
69
|
-
type OpenAIChatCompletion = ChatCompletion;
|
|
70
|
-
type DeepSeekChatCompletion = DeepSeekChatCompletionType;
|
|
71
|
-
type GroqChatCompletion = ChatCompletion$1;
|
|
72
|
-
type AnthropicChatCompletion = Message;
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Data structure representing the prompt data.
|
|
76
|
-
*/
|
|
77
|
-
interface PromptData {
|
|
78
|
-
system: string;
|
|
79
|
-
user: string;
|
|
80
|
-
}
|
|
81
|
-
/**
|
|
82
|
-
* Custom model configuration types
|
|
83
|
-
*/
|
|
84
|
-
type CustomCopilotModelConfig = (apiKey: string, prompt: PromptData) => {
|
|
85
|
-
/** The URL endpoint for the custom model's API */
|
|
86
|
-
endpoint: string;
|
|
87
|
-
/** Additional HTTP headers */
|
|
88
|
-
headers?: Record<string, string>;
|
|
89
|
-
/** Request body data */
|
|
90
|
-
body?: Record<string, unknown>;
|
|
91
|
-
};
|
|
92
|
-
type CustomCopilotModelTransformResponse = (response: unknown) => {
|
|
93
|
-
/** The generated text */
|
|
94
|
-
text: string | null;
|
|
95
|
-
};
|
|
96
|
-
interface CustomCopilotModel {
|
|
97
|
-
/** Configuration function */
|
|
98
|
-
config: CustomCopilotModelConfig;
|
|
99
|
-
/** Response transformer */
|
|
100
|
-
transformResponse: CustomCopilotModelTransformResponse;
|
|
101
|
-
}
|
|
102
|
-
type CustomOptions = {
|
|
103
|
-
provider?: undefined;
|
|
104
|
-
model: CustomCopilotModel;
|
|
105
|
-
};
|
|
106
|
-
type CopilotOptions = ProviderOptions<'openai'> | ProviderOptions<'groq'> | ProviderOptions<'anthropic'> | ProviderOptions<'google'> | ProviderOptions<'deepseek'> | CustomOptions;
|
|
107
|
-
type ProviderOptions<T extends Provider> = {
|
|
108
|
-
provider: T;
|
|
109
|
-
model: ProviderImplementationMap[T]['Model'];
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
type Monaco = typeof monaco;
|
|
113
|
-
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
114
|
-
type CursorPosition = monaco.IPosition;
|
|
115
|
-
type EditorRange = monaco.IRange;
|
|
116
|
-
|
|
117
|
-
type FetchCompletionItemHandler = (params: FetchCompletionItemParams) => Promise<FetchCompletionItemReturn>;
|
|
118
|
-
type FetchCompletionItemReturn = {
|
|
119
|
-
completion: string | null;
|
|
120
|
-
};
|
|
121
|
-
interface FetchCompletionItemParams {
|
|
122
|
-
endpoint: string;
|
|
123
|
-
body: CompletionRequestBody;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
type Endpoint = string;
|
|
127
|
-
type Filename = string;
|
|
128
|
-
type Technologies = string[];
|
|
129
|
-
type RelatedFile = {
|
|
130
|
-
/**
|
|
131
|
-
* The relative path from the current editing code in the editor to an external file.
|
|
132
|
-
*
|
|
133
|
-
* Examples:
|
|
134
|
-
* - To include a file `utils.js` in the same directory, set as `./utils.js`.
|
|
135
|
-
* - To include a file `utils.js` in the parent directory, set as `../utils.js`.
|
|
136
|
-
* - To include a file `utils.js` in the child directory, set as `./child/utils.js`.
|
|
137
|
-
*/
|
|
138
|
-
path: string;
|
|
139
|
-
/**
|
|
140
|
-
* The content of the external file as a string.
|
|
141
|
-
*/
|
|
142
|
-
content: string;
|
|
143
|
-
};
|
|
144
|
-
interface RegisterCompletionOptions {
|
|
145
|
-
/**
|
|
146
|
-
* Language of the current model
|
|
147
|
-
*/
|
|
148
|
-
language: string;
|
|
149
|
-
/**
|
|
150
|
-
* The API endpoint where you started the completion service.
|
|
151
|
-
*/
|
|
152
|
-
endpoint: Endpoint;
|
|
153
|
-
/**
|
|
154
|
-
* Specifies when the completion service should provide code completions.
|
|
155
|
-
*
|
|
156
|
-
* Options:
|
|
157
|
-
* - `'onIdle'`: Provides completions after a brief pause in typing.
|
|
158
|
-
* - `'onTyping'`: Provides completions in real-time as you type.
|
|
159
|
-
* - *Note:* Best suited for models with low response latency (e.g., Groq).
|
|
160
|
-
* - *Consideration:* May initiate additional background requests to deliver real-time suggestions.
|
|
161
|
-
* - `'onDemand'`: Completions are not provided automatically. You need to trigger the completion manually, possibly by using the `trigger` function from `registerCompletion` return.
|
|
162
|
-
*
|
|
163
|
-
* @default 'onIdle'
|
|
164
|
-
*/
|
|
165
|
-
trigger?: 'onTyping' | 'onIdle' | 'onDemand';
|
|
166
|
-
/**
|
|
167
|
-
* The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
|
|
168
|
-
* For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
|
|
169
|
-
*/
|
|
170
|
-
filename?: Filename;
|
|
171
|
-
/**
|
|
172
|
-
* The technologies (libraries, frameworks, etc.) you want to use for the completion.
|
|
173
|
-
* This can provide technology-specific completions.
|
|
174
|
-
* If you don't specify a technology, the completion will be specific to the language (provided as the `language`).
|
|
175
|
-
*
|
|
176
|
-
* @example
|
|
177
|
-
* ['react', 'nextjs', 'tailwindcss', 'tanstack/react-query']
|
|
178
|
-
* ['tensorflow', 'keras', 'numpy', 'pandas']
|
|
179
|
-
* etc.
|
|
180
|
-
*/
|
|
181
|
-
technologies?: Technologies;
|
|
182
|
-
/**
|
|
183
|
-
* Helps to give more relevant completions based on the full context.
|
|
184
|
-
* You can include things like the contents/codes of other files in the same workspace.
|
|
185
|
-
*/
|
|
186
|
-
relatedFiles?: RelatedFile[];
|
|
187
|
-
/**
|
|
188
|
-
* The maximum number of lines of code to include in the completion request.
|
|
189
|
-
* This limits the request size to the model to prevent `429 Too Many Requests` errors
|
|
190
|
-
* and reduce costs for long code.
|
|
191
|
-
*
|
|
192
|
-
* It is recommended to set `maxContextLines` to `60` or less if you are using `Groq` as your provider,
|
|
193
|
-
* since `Groq` does not implement pay-as-you-go pricing and has only low rate limits.
|
|
194
|
-
*/
|
|
195
|
-
maxContextLines?: number;
|
|
196
|
-
/**
|
|
197
|
-
* Determines if completions should be cached.
|
|
198
|
-
* Enabling caching can enhance performance by reusing previous results when the cursor position and context remain the same while editing.
|
|
199
|
-
* @default true
|
|
200
|
-
*/
|
|
201
|
-
enableCaching?: boolean;
|
|
202
|
-
/**
|
|
203
|
-
* When an error occurs during the completion process or requests, Monacopilot will log it to the console by default
|
|
204
|
-
* rather than throwing errors. This ensures smooth editing even when completions are unavailable.
|
|
205
|
-
* You can provide this callback to handle errors yourself, which will disable the default console logging.
|
|
206
|
-
* @param error - The error object containing information about the encountered error.
|
|
207
|
-
*/
|
|
208
|
-
onError?: (error: Error) => void;
|
|
209
|
-
/**
|
|
210
|
-
* Custom fetch completion handler. This function overrides the default fetch completion handler.
|
|
211
|
-
* It allows you to customize how completion requests are made and responses are processed.
|
|
212
|
-
* You can implement your own logic for fetching and processing completions.
|
|
213
|
-
* The function should return either a string (the completion to be inserted into the editor) or null.
|
|
214
|
-
* @param params - The parameters for the completion request.
|
|
215
|
-
* @param {string} params.endpoint - The endpoint to fetch the completion from.
|
|
216
|
-
* @param {CompletionRequestBody} params.body - The body of the completion request.
|
|
217
|
-
* @returns {Promise<{completion: string | null}>} An object containing the completion or null if no completion is available.
|
|
218
|
-
*/
|
|
219
|
-
requestHandler?: FetchCompletionItemHandler;
|
|
220
|
-
/**
|
|
221
|
-
* Callback function that is triggered when a completion is shown in the editor.
|
|
222
|
-
* @param completion - The completion text that is being shown.
|
|
223
|
-
* @param range - The editor range where the completion will be inserted.
|
|
224
|
-
*/
|
|
225
|
-
onCompletionShown?: (completion: string, range: EditorRange | undefined) => void;
|
|
226
|
-
/**
|
|
227
|
-
* Callback function triggered when a completion is accepted by the user.
|
|
228
|
-
*/
|
|
229
|
-
onCompletionAccepted?: () => void;
|
|
230
|
-
/**
|
|
231
|
-
* Callback function triggered when a completion is rejected by the user.
|
|
232
|
-
*/
|
|
233
|
-
onCompletionRejected?: () => void;
|
|
234
|
-
}
|
|
235
|
-
interface CompletionRegistration {
|
|
236
|
-
/**
|
|
237
|
-
* Triggers the completion.
|
|
238
|
-
*/
|
|
239
|
-
trigger: () => void;
|
|
240
|
-
/**
|
|
241
|
-
* Deregisters the completion provider and cleans up all associated resources.
|
|
242
|
-
* This should be called when unmounting the editor or when completion features
|
|
243
|
-
* are no longer needed to prevent memory leaks and ensure proper cleanup.
|
|
244
|
-
*/
|
|
245
|
-
deregister: () => void;
|
|
246
|
-
}
|
|
247
|
-
interface CompletionRequest {
|
|
248
|
-
/**
|
|
249
|
-
* The body of the completion request.
|
|
250
|
-
*/
|
|
251
|
-
body: CompletionRequestBody;
|
|
252
|
-
/**
|
|
253
|
-
* Additional options to include in the completion request.
|
|
254
|
-
*/
|
|
255
|
-
options?: CompletionRequestOptions;
|
|
256
|
-
}
|
|
257
|
-
interface CompletionRequestBody {
|
|
258
|
-
/**
|
|
259
|
-
* The metadata required to generate the completion.
|
|
260
|
-
*/
|
|
261
|
-
completionMetadata: CompletionMetadata;
|
|
262
|
-
}
|
|
263
|
-
interface CompletionRequestOptions {
|
|
264
|
-
/**
|
|
265
|
-
* Custom headers to include in the request to the LLM provider.
|
|
266
|
-
*/
|
|
267
|
-
headers?: Record<string, string>;
|
|
268
|
-
/**
|
|
269
|
-
* Custom prompt generator function for the completion request.
|
|
270
|
-
* This function allows you to override the default system and user prompts
|
|
271
|
-
* used in the completion request, providing more control over the AI's context and behavior.
|
|
272
|
-
*
|
|
273
|
-
* @param completionMetadata - Metadata about the current completion context
|
|
274
|
-
* @returns An object containing custom 'system' and 'user' prompts
|
|
275
|
-
*/
|
|
276
|
-
customPrompt?: CustomPrompt;
|
|
277
|
-
}
|
|
278
|
-
type CustomPrompt = (completionMetadata: CompletionMetadata) => Partial<PromptData>;
|
|
279
|
-
interface CompletionResponse {
|
|
280
|
-
/**
|
|
281
|
-
* The completion text.
|
|
282
|
-
*/
|
|
283
|
-
completion: string | null;
|
|
284
|
-
/**
|
|
285
|
-
* The error message.
|
|
286
|
-
*/
|
|
287
|
-
error?: string;
|
|
288
|
-
/**
|
|
289
|
-
* The raw response from the LLM.
|
|
290
|
-
*/
|
|
291
|
-
raw?: unknown;
|
|
292
|
-
}
|
|
293
|
-
type CompletionMode = 'insert' | 'complete' | 'continue';
|
|
294
|
-
interface CompletionMetadata {
|
|
295
|
-
/**
|
|
296
|
-
* The programming language of the code.
|
|
297
|
-
*/
|
|
298
|
-
language: string | undefined;
|
|
299
|
-
/**
|
|
300
|
-
* The name of the file being edited.
|
|
301
|
-
*/
|
|
302
|
-
filename: Filename | undefined;
|
|
303
|
-
/**
|
|
304
|
-
* The technologies used in the completion.
|
|
305
|
-
*/
|
|
306
|
-
technologies: Technologies | undefined;
|
|
307
|
-
/**
|
|
308
|
-
* Additional context from related files.
|
|
309
|
-
*/
|
|
310
|
-
relatedFiles: RelatedFile[] | undefined;
|
|
311
|
-
/**
|
|
312
|
-
* The text that appears after the cursor.
|
|
313
|
-
*/
|
|
314
|
-
textAfterCursor: string;
|
|
315
|
-
/**
|
|
316
|
-
* The text that appears before the cursor.
|
|
317
|
-
*/
|
|
318
|
-
textBeforeCursor: string;
|
|
319
|
-
/**
|
|
320
|
-
* The current cursor position.
|
|
321
|
-
*/
|
|
322
|
-
cursorPosition: CursorPosition;
|
|
323
|
-
/**
|
|
324
|
-
* The current state of the editor.
|
|
325
|
-
*/
|
|
326
|
-
editorState: {
|
|
327
|
-
/**
|
|
328
|
-
* The mode of the completion.
|
|
329
|
-
* - `insert`: Indicates that there is a character immediately after the cursor. In this mode, the LLM will generate content to be inserted at the cursor position.
|
|
330
|
-
* - `complete`: Indicates that there is a character after the cursor but not immediately. In this mode, the LLM will generate content to complete the text from the cursor position.
|
|
331
|
-
* - `continue`: Indicates that there is no character after the cursor. In this mode, the LLM will generate content to continue the text from the cursor position.
|
|
332
|
-
*/
|
|
333
|
-
completionMode: CompletionMode;
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
/**
|
|
338
|
-
* Registers completion functionality with the Monaco editor.
|
|
339
|
-
* @param monaco - The Monaco instance.
|
|
340
|
-
* @param editor - The editor instance.
|
|
341
|
-
* @param options - Options for the completion.
|
|
342
|
-
* @returns A CompletionRegistration object with deregister and trigger methods.
|
|
343
|
-
*/
|
|
344
|
-
declare const registerCompletion: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCompletionOptions) => CompletionRegistration;
|
|
345
|
-
|
|
346
|
-
declare class Copilot {
|
|
347
|
-
private readonly apiKey;
|
|
348
|
-
private provider;
|
|
349
|
-
private model;
|
|
350
|
-
constructor(apiKey: string, options: CopilotOptions);
|
|
351
|
-
complete(request: CompletionRequest): Promise<CompletionResponse>;
|
|
352
|
-
private generatePrompt;
|
|
353
|
-
private prepareRequestDetails;
|
|
354
|
-
private sendCompletionRequest;
|
|
355
|
-
private processCompletionResponse;
|
|
356
|
-
private handleCompletionError;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
export { type AnthropicChatCompletion, type AnthropicModel, type CompletionMetadata, type CompletionRegistration, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, Copilot, type CopilotOptions, type CustomCopilotModel, type CustomCopilotModelConfig, type CustomCopilotModelTransformResponse, type DeepSeekChatCompletion, type DeepSeekModel, type GoogleModel, type GroqChatCompletion, type GroqModel, type Model, type Monaco, type OpenAIChatCompletion, type OpenAIModel, type Provider, type RegisterCompletionOptions, type StandaloneCodeEditor, registerCompletion };
|
package/build/index.js
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
'use strict';var xe="\x1B[91m",be="\x1B[93m",te="\x1B[0m",oe="\x1B[1m",re=o=>o instanceof Error?o.message:typeof o=="string"?o:"An unknown error occurred",S=o=>{let e=re(o),t=`${xe}${oe}[MONACOPILOT ERROR] ${e}${te}`;return console.error(t),{message:e}},v=(o,e)=>{console.warn(`${be}${oe}[MONACOPILOT WARN] ${o}${e?`
|
|
2
|
-
${re(e)}`:""}${te}`);};var ne=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1];var ie=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),O=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),W=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var w=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e);}enqueue(e){let t;return this.size===this.capacity&&(t=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,t}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=undefined,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==undefined)}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.size=0;}getSize(){return this.size}isEmpty(){return this.size===0}isFull(){return this.size===this.capacity}};var _=class _{constructor(){this.cache=new w(_.MAX_CACHE_SIZE);}get(e,t){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,t))}add(e){this.cache.enqueue(e);}clear(){this.cache.clear();}isValidCacheItem(e,t,r){let n=r.getValueInRange(e.range),i=O(t,r);return i.length<e.textBeforeCursor.length||!i.startsWith(e.textBeforeCursor)?false:this.isPositionValid(e,t,n)}isPositionValid(e,t,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:l,endLineNumber:p,endColumn:d}=n,{lineNumber:c,column:a}=t;if(!i.startsWith(r))return false;let u=c===s&&a===l;if(s===p)return u||c===s&&a>=l&&a<=d;let f=c>s&&c<p?true:c===s&&a>=l||c===p&&a<=d;return u||f}};_.MAX_CACHE_SIZE=10;var L=_;var N=class{constructor(e,t,r){this.formattedCompletion="";this.currentColumn=0;this.textBeforeCursorInLine="";this.formattedCompletion=e,this.currentColumn=t,this.textBeforeCursorInLine=r;}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}indentByColumn(){let e=this.formattedCompletion.split(`
|
|
3
|
-
`);if(e.length<=1||this.textBeforeCursorInLine.trim()!=="")return this;let t=" ".repeat(this.currentColumn-1);return this.formattedCompletion=e[0]+`
|
|
4
|
-
`+e.slice(1).map(r=>t+r).join(`
|
|
5
|
-
`),this}removeMarkdownCodeBlocks(e){let t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],s=i.split(`
|
|
6
|
-
`).slice(1,-1).join(`
|
|
7
|
-
`);r=r.replace(i,s);}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
8
|
-
|
|
9
|
-
`),this}build(){return this.formattedCompletion}};var B=class{constructor(e){this.monaco=e;}computeInsertionRange(e,t,r){if(!t)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let n=r.getOffsetAt(e),i=r.getValue().substring(0,n),s=r.getValue().substring(n),l=0,p=0,d=0,c=0,a=t.length,u=i.length,f=s.length;if(n>=r.getValue().length)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(f===0)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let T=Math.min(a,u);for(let m=1;m<=T;m++){let b=t.substring(0,m),Te=i.slice(-m);b===Te&&(c=m);}let C=Math.min(a,f);for(let m=0;m<C&&t[m]===s[m];m++)l++;for(let m=1;m<=C;m++)t.slice(-m)===s.slice(0,m)&&(p=m);if(d=Math.max(l,p),d===0){for(let m=1;m<a;m++)if(s.startsWith(t.substring(m))){d=a-m;break}}let x=c>0?r.getPositionAt(n-c):e,y=n+d,h=r.getPositionAt(y);return new this.monaco.Range(x.lineNumber,x.column,h.lineNumber,h.column)}computeCacheRange(e,t){let r=e.lineNumber,n=e.column,i=t.split(`
|
|
10
|
-
`),s=i.length-1,l=r+s,p=s===0?n+i[0].length:i[s].length+1;return new this.monaco.Range(r,n,l,p)}};var se="application/json";var ve=async(o,e,t={})=>{let r=t.timeout??3e4,n=AbortSignal.timeout(r),i=t.signal?AbortSignal.any([n,t.signal]):n,s={"Content-Type":"application/json",...t.headers},l=t.body?JSON.stringify(t.body):undefined,p=await fetch(o,{method:e,headers:s,body:l,signal:i});if(!p.ok){let d=await p.json().catch(()=>null),c=d?`
|
|
11
|
-
${JSON.stringify(d,null,2)}`:"",a=t.fallbackError||"Network request failed";throw new Error(`${a} (${p.status})${c}`)}return p.json()},Oe=(o,e,t)=>ve(o,"POST",{...t,body:e}),F={post:Oe};var A=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`,ae=o=>o.charAt(0).toUpperCase()+o.slice(1),X=(o,e,t={})=>{if(e<=0)return "";let r=o.split(`
|
|
12
|
-
`),n=r.length;if(e>=n)return o;if(t.from==="end"){let s=r.slice(-e);return s.every(l=>l==="")?`
|
|
13
|
-
`.repeat(e):s.join(`
|
|
14
|
-
`)}let i=r.slice(0,e);return i.every(s=>s==="")?`
|
|
15
|
-
`.repeat(e):i.join(`
|
|
16
|
-
`)};var le=async o=>{let{endpoint:e,body:t}=o,{completion:r,error:n}=await F.post(e,t,{headers:{"Content-Type":se},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return {completion:r}},pe=({pos:o,mdl:e,options:t})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:l}=t,p=Ie(o,e),c=!!s?.length?3:2,a=l?Math.floor(l/c):undefined,u=(y,h,m)=>{let b=y(o,e);return h?X(b,h,m):b},f=(y,h)=>!y||!h?y:y.map(({content:m,...b})=>({...b,content:X(m,h)})),T=u(O,a,{from:"end"}),C=u(W,a),x=f(s,a);return {filename:r,language:n,technologies:i,relatedFiles:x,textBeforeCursor:T,textAfterCursor:C,cursorPosition:o,editorState:{completionMode:p}}},Ie=(o,e)=>{let t=ne(o,e),r=W(o,e);return t?"insert":r.trim()?"complete":"continue"};var I=o=>({items:o,enableForwardStability:true,suppressSuggestions:true});var q=(o,e=600,t=200)=>{let r=null,n=0,i=null,s=null,l=false,p=(...d)=>{if(l)return Promise.resolve(undefined);i=d;let c=Date.now(),a=c-n;n=c,r&&(clearTimeout(r),r=null);let u=a<t?e:t;return s=new Promise((f,T)=>{r=setTimeout(async()=>{l=true;try{if(i){let C=await o(...i);f(C);}else f(void 0);}catch(C){T(C);}finally{l=false,r=null,i=null;}},u);}),s};return p.cancel=()=>{r&&(clearTimeout(r),r=null),i=null;},p};var ke=o=>({onTyping:q(o,600,200),onIdle:q(o,600,400),onDemand:q(o,0,0)}),$=new L,me=async({monaco:o,mdl:e,pos:t,token:r,isCompletionAccepted:n,options:i})=>{let{trigger:s="onIdle",endpoint:l,enableCaching:p=true,onError:d,requestHandler:c}=i;if(p){let a=$.get(t,e).map(u=>({insertText:u.completion,range:u.range}));if(a.length>0)return I(a)}if(r.isCancellationRequested||n)return I([]);try{let u=ke(c??le)[s];r.onCancellationRequested(()=>{u.cancel();});let f=pe({pos:t,mdl:e,options:i}),{completion:T}=await u({endpoint:l,body:{completionMetadata:f}});if(T){let C=new N(T,t.column,ie(t,e)).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().indentByColumn().build(),x=new B(o),y=x.computeInsertionRange(t,C,e),h=x.computeCacheRange(t,C);return p&&$.add({completion:C,range:h,textBeforeCursor:O(t,e)}),I([{insertText:C,range:y}])}}catch(a){if(De(a))return I([]);d?d(a):v("Cannot provide completion",a);}return I([])},De=o=>typeof o=="string"?o==="Cancelled"||o==="AbortError":o instanceof Error?o.message==="Cancelled"||o.name==="AbortError":false;var G=new WeakMap,k=o=>G.get(o),ce=(o,e)=>{G.set(o,e);},Y=o=>{G.delete(o);},de=()=>({isCompletionAccepted:false,isCompletionVisible:false,isExplicitlyTriggered:false,hasRejectedCurrentCompletion:false});var ue=(o,e,t)=>{let r=k(e);return r?o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(n,i,s,l)=>{if(!(t.trigger==="onDemand"&&!r.isExplicitlyTriggered))return me({monaco:o,mdl:n,pos:i,token:l,isCompletionAccepted:r.isCompletionAccepted,options:t})},handleItemDidShow:(n,i,s)=>{r.isExplicitlyTriggered=false,r.hasRejectedCurrentCompletion=false,!r.isCompletionAccepted&&(r.isCompletionVisible=true,t.onCompletionShown?.(s,i.range));},freeInlineCompletions:()=>{}}):null},Ce=o=>{let e=k(o);if(!e){v("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isExplicitlyTriggered=true,o.trigger("keyboard","editor.action.inlineSuggest.trigger",{});};var Se={TAB:(o,e)=>e.keyCode===o.KeyCode.Tab,CMD_RIGHT_ARROW:(o,e)=>e.keyCode===o.KeyCode.RightArrow&&e.metaKey},J=class{constructor(e,t,r){this.monaco=e;this.state=t;this.options=r;}handleKeyEvent(e){let t={monaco:this.monaco,event:e,state:this.state,options:this.options};this.handleCompletionAcceptance(t),this.handleCompletionRejection(t);}handleCompletionAcceptance(e){return e.state.isCompletionVisible&&this.isAcceptanceKey(e.event)?(e.options.onCompletionAccepted?.(),e.state.isCompletionAccepted=true,e.state.isCompletionVisible=false,true):(e.state.isCompletionAccepted=false,false)}handleCompletionRejection(e){return this.shouldRejectCompletion(e)?(e.options.onCompletionRejected?.(),e.state.hasRejectedCurrentCompletion=true,true):false}shouldRejectCompletion(e){return e.state.isCompletionVisible&&!e.state.hasRejectedCurrentCompletion&&!e.state.isCompletionAccepted&&!this.isAcceptanceKey(e.event)}isAcceptanceKey(e){return Object.values(Se).some(t=>t(this.monaco,e))}},ge=(o,e,t,r)=>{let n=new J(o,t,r);return e.onKeyDown(i=>n.handleKeyEvent(i))};var D=null,we=(o,e,t)=>{D&&D.deregister();let r=[];ce(e,de()),e.updateOptions({inlineSuggest:{enabled:true,mode:"subwordSmart"}});try{let n=k(e);if(!n)return v("Completion is not registered properly. State not found."),Le();let i=ue(o,e,t);i&&r.push(i);let s=ge(o,e,n,t);r.push(s);let l={deregister:()=>{r.forEach(p=>p.dispose()),$.clear(),Y(e),D=null;},trigger:()=>Ce(e)};return D=l,l}catch(n){return t.onError?t.onError(n):S(n),{deregister:()=>{r.forEach(i=>i.dispose()),Y(e),D=null;},trigger:()=>{}}}},Le=()=>({deregister:()=>{},trigger:()=>{}});var Z=["groq","openai","anthropic","google","deepseek"],P={"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-20241022","claude-3-haiku":"claude-3-haiku-20240307","claude-3-5-haiku":"claude-3-5-haiku-20241022","o1-mini":"o1-mini","gemini-1.5-flash-8b":"gemini-1.5-flash-8b","gemini-1.5-flash":"gemini-1.5-flash","gemini-1.5-pro":"gemini-1.5-pro",v3:"deepseek-chat"},Q={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-mini"],anthropic:["claude-3-5-sonnet","claude-3-haiku","claude-3-5-haiku"],google:["gemini-1.5-flash-8b","gemini-1.5-pro","gemini-1.5-flash"],deepseek:["v3"]},E={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages",google:"https://generativelanguage.googleapis.com/v1beta/models",deepseek:"https://api.deepseek.com/beta/completions"};var g=class{};var j=class extends g{createEndpoint(){return E.anthropic}createRequestBody(e,t){return {model:P[e],temperature:.1,system:t.system,messages:[{role:"user",content:t.user}],max_tokens:500}}createHeaders(e){return {"Content-Type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01"}}parseCompletion(e){let t=e.content?.[0];return t&&"text"in t?t.text:null}};var H=class extends g{createEndpoint(){return E.deepseek}createRequestBody(e,t,r){return {model:P[e],prompt:r.textBeforeCursor,suffix:r.textAfterCursor,temperature:.1,max_tokens:500}}createHeaders(e){return {"Content-Type":"application/json",Authorization:`Bearer ${e}`}}parseCompletion(e){return typeof e.choices?.[0]?.text=="string"?e.choices[0].text:null}};var K=class extends g{createEndpoint(e,t){return `${E.google}/${P[e]}:generateContent?key=${t}`}createRequestBody(e,t){return {systemInstruction:{role:"system",parts:[{text:t.system}]},generationConfig:{temperature:.1,maxOutputTokens:500},contents:[{role:"user",parts:[{text:t.user}]}]}}createHeaders(){return {"Content-Type":"application/json"}}parseCompletion(e){return e.candidates?.[0]?.content?.parts?.[0]?.text??null}};var V=class extends g{createEndpoint(){return E.groq}createRequestBody(e,t){return {model:P[e],temperature:.1,max_tokens:500,messages:[{role:"system",content:t.system},{role:"user",content:t.user}]}}createHeaders(e){return {"Content-Type":"application/json",Authorization:`Bearer ${e}`}}parseCompletion(e){return e.choices?.[0]?.message.content??null}};var U=class extends g{createEndpoint(){return E.openai}createRequestBody(e,t){let r=e==="o1-mini";return {model:P[e],...!r&&{temperature:.1},max_completion_tokens:500,messages:[{role:"system",content:t.system},{role:"user",content:t.user}]}}createHeaders(e){return {"Content-Type":"application/json",Authorization:`Bearer ${e}`}}parseCompletion(e){return e.choices?.[0]?.message.content??null}};var z={openai:new U,groq:new V,anthropic:new j,google:new K,deepseek:new H},fe=(o,e,t)=>z[t].createEndpoint(o,e),he=(o,e,t,r)=>z[e].createRequestBody(o,t,r),Pe=(o,e)=>z[e].createHeaders(o),Ee=(o,e)=>z[e].parseCompletion(o);var _e=o=>!o||o.length===0?"":o.map(({path:e,content:t})=>`
|
|
17
|
-
<related_file>
|
|
18
|
-
<filePath>${e}</filePath>
|
|
19
|
-
<fileContent>
|
|
20
|
-
\`\`\`
|
|
21
|
-
${t}
|
|
22
|
-
\`\`\`
|
|
23
|
-
</fileContent>
|
|
24
|
-
</related_file>`.trim()).join(`
|
|
25
|
-
|
|
26
|
-
`),ye=o=>{let{technologies:e=[],filename:t,relatedFiles:r,language:n,textBeforeCursor:i="",textAfterCursor:s="",editorState:{completionMode:l}}=o,p=A([n,...e].filter(a=>typeof a=="string"&&!!a)),d=`
|
|
27
|
-
You are an expert code completion assistant.
|
|
28
|
-
|
|
29
|
-
**Context:**
|
|
30
|
-
File: ${t||"Untitled"}
|
|
31
|
-
Language: ${n||"Undetermined"}
|
|
32
|
-
Mode: ${l}
|
|
33
|
-
Stack: ${p||"None"}`,c=`
|
|
34
|
-
**Related Files:**
|
|
35
|
-
${_e(r)}
|
|
36
|
-
|
|
37
|
-
**Source:**
|
|
38
|
-
\`\`\`
|
|
39
|
-
${i}<cursor>${s}
|
|
40
|
-
\`\`\`
|
|
41
|
-
|
|
42
|
-
${ae(l)} the code at <cursor>.
|
|
43
|
-
|
|
44
|
-
Output only the raw code to be inserted at the cursor location without any additional text or comments.`;return {system:d,user:c}};var Re=(o,e)=>{if(!o)throw new Error("Please provide an API key.");if(!e||typeof e=="object"&&Object.keys(e).length===0)throw new Error("Please provide options.")},Me=(o,e)=>{if(typeof o=="object"){if(e!==undefined)throw new Error("Provider should not be specified when using a custom model.");if(!("config"in o)||!("transformResponse"in o))throw new Error("Please ensure both config and transformResponse are provided for custom model.");return}if(!e||!Z.includes(e))throw new Error(`Provider must be specified and supported when using built-in models. Please choose from: ${A(Z)}`);if(typeof o=="string"&&!Q[e].includes(o))throw new Error(`Model "${o}" is not supported by the "${e}" provider. Supported models: ${A(Q[e])}`)};var ee=class{constructor(e,t){Re(e,t),this.apiKey=e,this.provider=t.provider,this.model=t.model,Me(this.model,this.provider);}async complete(e){let{body:t,options:r}=e,{completionMetadata:n}=t,{headers:i={},customPrompt:s}=r??{},l=this.generatePrompt(n,s),{endpoint:p,requestBody:d,headers:c}=this.prepareRequestDetails(l,n);try{let a=await this.sendCompletionRequest(p,d,{...c,...i});return this.processCompletionResponse(a)}catch(a){return this.handleCompletionError(a)}}generatePrompt(e,t){let r=ye(e);return t?{...r,...t(e)}:r}prepareRequestDetails(e,t){if(typeof this.model=="object"&&"config"in this.model){let r=this.model.config(this.apiKey,e),n=r.endpoint,i=r.body??{},s=r.headers??{};return {endpoint:n,requestBody:i,headers:s}}else {if(!this.provider)throw new Error("Provider is required for non-custom models");let r=fe(this.model,this.apiKey,this.provider),n=Pe(this.apiKey,this.provider),i=he(this.model,this.provider,e,t);return {endpoint:r,requestBody:i,headers:n}}}async sendCompletionRequest(e,t,r){return F.post(e,t,{headers:r})}processCompletionResponse(e){if(typeof this.model=="object"&&"transformResponse"in this.model)return {completion:this.model.transformResponse(e).text??null,raw:e};if(!this.provider)throw new Error("Provider is required for non-custom models");return {completion:Ee(e,this.provider),raw:e}}handleCompletionError(e){return {error:S(e).message,completion:null}}};exports.Copilot=ee;exports.registerCompletion=we;
|
package/build/index.mjs
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
var xe="\x1B[91m",be="\x1B[93m",te="\x1B[0m",oe="\x1B[1m",re=o=>o instanceof Error?o.message:typeof o=="string"?o:"An unknown error occurred",S=o=>{let e=re(o),t=`${xe}${oe}[MONACOPILOT ERROR] ${e}${te}`;return console.error(t),{message:e}},v=(o,e)=>{console.warn(`${be}${oe}[MONACOPILOT WARN] ${o}${e?`
|
|
2
|
-
${re(e)}`:""}${te}`);};var ne=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1];var ie=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),O=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),W=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var w=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e);}enqueue(e){let t;return this.size===this.capacity&&(t=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,t}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=undefined,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==undefined)}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.size=0;}getSize(){return this.size}isEmpty(){return this.size===0}isFull(){return this.size===this.capacity}};var _=class _{constructor(){this.cache=new w(_.MAX_CACHE_SIZE);}get(e,t){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,t))}add(e){this.cache.enqueue(e);}clear(){this.cache.clear();}isValidCacheItem(e,t,r){let n=r.getValueInRange(e.range),i=O(t,r);return i.length<e.textBeforeCursor.length||!i.startsWith(e.textBeforeCursor)?false:this.isPositionValid(e,t,n)}isPositionValid(e,t,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:l,endLineNumber:p,endColumn:d}=n,{lineNumber:c,column:a}=t;if(!i.startsWith(r))return false;let u=c===s&&a===l;if(s===p)return u||c===s&&a>=l&&a<=d;let f=c>s&&c<p?true:c===s&&a>=l||c===p&&a<=d;return u||f}};_.MAX_CACHE_SIZE=10;var L=_;var N=class{constructor(e,t,r){this.formattedCompletion="";this.currentColumn=0;this.textBeforeCursorInLine="";this.formattedCompletion=e,this.currentColumn=t,this.textBeforeCursorInLine=r;}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}indentByColumn(){let e=this.formattedCompletion.split(`
|
|
3
|
-
`);if(e.length<=1||this.textBeforeCursorInLine.trim()!=="")return this;let t=" ".repeat(this.currentColumn-1);return this.formattedCompletion=e[0]+`
|
|
4
|
-
`+e.slice(1).map(r=>t+r).join(`
|
|
5
|
-
`),this}removeMarkdownCodeBlocks(e){let t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],s=i.split(`
|
|
6
|
-
`).slice(1,-1).join(`
|
|
7
|
-
`);r=r.replace(i,s);}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
8
|
-
|
|
9
|
-
`),this}build(){return this.formattedCompletion}};var B=class{constructor(e){this.monaco=e;}computeInsertionRange(e,t,r){if(!t)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let n=r.getOffsetAt(e),i=r.getValue().substring(0,n),s=r.getValue().substring(n),l=0,p=0,d=0,c=0,a=t.length,u=i.length,f=s.length;if(n>=r.getValue().length)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(f===0)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let T=Math.min(a,u);for(let m=1;m<=T;m++){let b=t.substring(0,m),Te=i.slice(-m);b===Te&&(c=m);}let C=Math.min(a,f);for(let m=0;m<C&&t[m]===s[m];m++)l++;for(let m=1;m<=C;m++)t.slice(-m)===s.slice(0,m)&&(p=m);if(d=Math.max(l,p),d===0){for(let m=1;m<a;m++)if(s.startsWith(t.substring(m))){d=a-m;break}}let x=c>0?r.getPositionAt(n-c):e,y=n+d,h=r.getPositionAt(y);return new this.monaco.Range(x.lineNumber,x.column,h.lineNumber,h.column)}computeCacheRange(e,t){let r=e.lineNumber,n=e.column,i=t.split(`
|
|
10
|
-
`),s=i.length-1,l=r+s,p=s===0?n+i[0].length:i[s].length+1;return new this.monaco.Range(r,n,l,p)}};var se="application/json";var ve=async(o,e,t={})=>{let r=t.timeout??3e4,n=AbortSignal.timeout(r),i=t.signal?AbortSignal.any([n,t.signal]):n,s={"Content-Type":"application/json",...t.headers},l=t.body?JSON.stringify(t.body):undefined,p=await fetch(o,{method:e,headers:s,body:l,signal:i});if(!p.ok){let d=await p.json().catch(()=>null),c=d?`
|
|
11
|
-
${JSON.stringify(d,null,2)}`:"",a=t.fallbackError||"Network request failed";throw new Error(`${a} (${p.status})${c}`)}return p.json()},Oe=(o,e,t)=>ve(o,"POST",{...t,body:e}),F={post:Oe};var A=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`,ae=o=>o.charAt(0).toUpperCase()+o.slice(1),X=(o,e,t={})=>{if(e<=0)return "";let r=o.split(`
|
|
12
|
-
`),n=r.length;if(e>=n)return o;if(t.from==="end"){let s=r.slice(-e);return s.every(l=>l==="")?`
|
|
13
|
-
`.repeat(e):s.join(`
|
|
14
|
-
`)}let i=r.slice(0,e);return i.every(s=>s==="")?`
|
|
15
|
-
`.repeat(e):i.join(`
|
|
16
|
-
`)};var le=async o=>{let{endpoint:e,body:t}=o,{completion:r,error:n}=await F.post(e,t,{headers:{"Content-Type":se},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return {completion:r}},pe=({pos:o,mdl:e,options:t})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:l}=t,p=Ie(o,e),c=!!s?.length?3:2,a=l?Math.floor(l/c):undefined,u=(y,h,m)=>{let b=y(o,e);return h?X(b,h,m):b},f=(y,h)=>!y||!h?y:y.map(({content:m,...b})=>({...b,content:X(m,h)})),T=u(O,a,{from:"end"}),C=u(W,a),x=f(s,a);return {filename:r,language:n,technologies:i,relatedFiles:x,textBeforeCursor:T,textAfterCursor:C,cursorPosition:o,editorState:{completionMode:p}}},Ie=(o,e)=>{let t=ne(o,e),r=W(o,e);return t?"insert":r.trim()?"complete":"continue"};var I=o=>({items:o,enableForwardStability:true,suppressSuggestions:true});var q=(o,e=600,t=200)=>{let r=null,n=0,i=null,s=null,l=false,p=(...d)=>{if(l)return Promise.resolve(undefined);i=d;let c=Date.now(),a=c-n;n=c,r&&(clearTimeout(r),r=null);let u=a<t?e:t;return s=new Promise((f,T)=>{r=setTimeout(async()=>{l=true;try{if(i){let C=await o(...i);f(C);}else f(void 0);}catch(C){T(C);}finally{l=false,r=null,i=null;}},u);}),s};return p.cancel=()=>{r&&(clearTimeout(r),r=null),i=null;},p};var ke=o=>({onTyping:q(o,600,200),onIdle:q(o,600,400),onDemand:q(o,0,0)}),$=new L,me=async({monaco:o,mdl:e,pos:t,token:r,isCompletionAccepted:n,options:i})=>{let{trigger:s="onIdle",endpoint:l,enableCaching:p=true,onError:d,requestHandler:c}=i;if(p){let a=$.get(t,e).map(u=>({insertText:u.completion,range:u.range}));if(a.length>0)return I(a)}if(r.isCancellationRequested||n)return I([]);try{let u=ke(c??le)[s];r.onCancellationRequested(()=>{u.cancel();});let f=pe({pos:t,mdl:e,options:i}),{completion:T}=await u({endpoint:l,body:{completionMetadata:f}});if(T){let C=new N(T,t.column,ie(t,e)).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().indentByColumn().build(),x=new B(o),y=x.computeInsertionRange(t,C,e),h=x.computeCacheRange(t,C);return p&&$.add({completion:C,range:h,textBeforeCursor:O(t,e)}),I([{insertText:C,range:y}])}}catch(a){if(De(a))return I([]);d?d(a):v("Cannot provide completion",a);}return I([])},De=o=>typeof o=="string"?o==="Cancelled"||o==="AbortError":o instanceof Error?o.message==="Cancelled"||o.name==="AbortError":false;var G=new WeakMap,k=o=>G.get(o),ce=(o,e)=>{G.set(o,e);},Y=o=>{G.delete(o);},de=()=>({isCompletionAccepted:false,isCompletionVisible:false,isExplicitlyTriggered:false,hasRejectedCurrentCompletion:false});var ue=(o,e,t)=>{let r=k(e);return r?o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(n,i,s,l)=>{if(!(t.trigger==="onDemand"&&!r.isExplicitlyTriggered))return me({monaco:o,mdl:n,pos:i,token:l,isCompletionAccepted:r.isCompletionAccepted,options:t})},handleItemDidShow:(n,i,s)=>{r.isExplicitlyTriggered=false,r.hasRejectedCurrentCompletion=false,!r.isCompletionAccepted&&(r.isCompletionVisible=true,t.onCompletionShown?.(s,i.range));},freeInlineCompletions:()=>{}}):null},Ce=o=>{let e=k(o);if(!e){v("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isExplicitlyTriggered=true,o.trigger("keyboard","editor.action.inlineSuggest.trigger",{});};var Se={TAB:(o,e)=>e.keyCode===o.KeyCode.Tab,CMD_RIGHT_ARROW:(o,e)=>e.keyCode===o.KeyCode.RightArrow&&e.metaKey},J=class{constructor(e,t,r){this.monaco=e;this.state=t;this.options=r;}handleKeyEvent(e){let t={monaco:this.monaco,event:e,state:this.state,options:this.options};this.handleCompletionAcceptance(t),this.handleCompletionRejection(t);}handleCompletionAcceptance(e){return e.state.isCompletionVisible&&this.isAcceptanceKey(e.event)?(e.options.onCompletionAccepted?.(),e.state.isCompletionAccepted=true,e.state.isCompletionVisible=false,true):(e.state.isCompletionAccepted=false,false)}handleCompletionRejection(e){return this.shouldRejectCompletion(e)?(e.options.onCompletionRejected?.(),e.state.hasRejectedCurrentCompletion=true,true):false}shouldRejectCompletion(e){return e.state.isCompletionVisible&&!e.state.hasRejectedCurrentCompletion&&!e.state.isCompletionAccepted&&!this.isAcceptanceKey(e.event)}isAcceptanceKey(e){return Object.values(Se).some(t=>t(this.monaco,e))}},ge=(o,e,t,r)=>{let n=new J(o,t,r);return e.onKeyDown(i=>n.handleKeyEvent(i))};var D=null,we=(o,e,t)=>{D&&D.deregister();let r=[];ce(e,de()),e.updateOptions({inlineSuggest:{enabled:true,mode:"subwordSmart"}});try{let n=k(e);if(!n)return v("Completion is not registered properly. State not found."),Le();let i=ue(o,e,t);i&&r.push(i);let s=ge(o,e,n,t);r.push(s);let l={deregister:()=>{r.forEach(p=>p.dispose()),$.clear(),Y(e),D=null;},trigger:()=>Ce(e)};return D=l,l}catch(n){return t.onError?t.onError(n):S(n),{deregister:()=>{r.forEach(i=>i.dispose()),Y(e),D=null;},trigger:()=>{}}}},Le=()=>({deregister:()=>{},trigger:()=>{}});var Z=["groq","openai","anthropic","google","deepseek"],P={"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-20241022","claude-3-haiku":"claude-3-haiku-20240307","claude-3-5-haiku":"claude-3-5-haiku-20241022","o1-mini":"o1-mini","gemini-1.5-flash-8b":"gemini-1.5-flash-8b","gemini-1.5-flash":"gemini-1.5-flash","gemini-1.5-pro":"gemini-1.5-pro",v3:"deepseek-chat"},Q={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-mini"],anthropic:["claude-3-5-sonnet","claude-3-haiku","claude-3-5-haiku"],google:["gemini-1.5-flash-8b","gemini-1.5-pro","gemini-1.5-flash"],deepseek:["v3"]},E={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages",google:"https://generativelanguage.googleapis.com/v1beta/models",deepseek:"https://api.deepseek.com/beta/completions"};var g=class{};var j=class extends g{createEndpoint(){return E.anthropic}createRequestBody(e,t){return {model:P[e],temperature:.1,system:t.system,messages:[{role:"user",content:t.user}],max_tokens:500}}createHeaders(e){return {"Content-Type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01"}}parseCompletion(e){let t=e.content?.[0];return t&&"text"in t?t.text:null}};var H=class extends g{createEndpoint(){return E.deepseek}createRequestBody(e,t,r){return {model:P[e],prompt:r.textBeforeCursor,suffix:r.textAfterCursor,temperature:.1,max_tokens:500}}createHeaders(e){return {"Content-Type":"application/json",Authorization:`Bearer ${e}`}}parseCompletion(e){return typeof e.choices?.[0]?.text=="string"?e.choices[0].text:null}};var K=class extends g{createEndpoint(e,t){return `${E.google}/${P[e]}:generateContent?key=${t}`}createRequestBody(e,t){return {systemInstruction:{role:"system",parts:[{text:t.system}]},generationConfig:{temperature:.1,maxOutputTokens:500},contents:[{role:"user",parts:[{text:t.user}]}]}}createHeaders(){return {"Content-Type":"application/json"}}parseCompletion(e){return e.candidates?.[0]?.content?.parts?.[0]?.text??null}};var V=class extends g{createEndpoint(){return E.groq}createRequestBody(e,t){return {model:P[e],temperature:.1,max_tokens:500,messages:[{role:"system",content:t.system},{role:"user",content:t.user}]}}createHeaders(e){return {"Content-Type":"application/json",Authorization:`Bearer ${e}`}}parseCompletion(e){return e.choices?.[0]?.message.content??null}};var U=class extends g{createEndpoint(){return E.openai}createRequestBody(e,t){let r=e==="o1-mini";return {model:P[e],...!r&&{temperature:.1},max_completion_tokens:500,messages:[{role:"system",content:t.system},{role:"user",content:t.user}]}}createHeaders(e){return {"Content-Type":"application/json",Authorization:`Bearer ${e}`}}parseCompletion(e){return e.choices?.[0]?.message.content??null}};var z={openai:new U,groq:new V,anthropic:new j,google:new K,deepseek:new H},fe=(o,e,t)=>z[t].createEndpoint(o,e),he=(o,e,t,r)=>z[e].createRequestBody(o,t,r),Pe=(o,e)=>z[e].createHeaders(o),Ee=(o,e)=>z[e].parseCompletion(o);var _e=o=>!o||o.length===0?"":o.map(({path:e,content:t})=>`
|
|
17
|
-
<related_file>
|
|
18
|
-
<filePath>${e}</filePath>
|
|
19
|
-
<fileContent>
|
|
20
|
-
\`\`\`
|
|
21
|
-
${t}
|
|
22
|
-
\`\`\`
|
|
23
|
-
</fileContent>
|
|
24
|
-
</related_file>`.trim()).join(`
|
|
25
|
-
|
|
26
|
-
`),ye=o=>{let{technologies:e=[],filename:t,relatedFiles:r,language:n,textBeforeCursor:i="",textAfterCursor:s="",editorState:{completionMode:l}}=o,p=A([n,...e].filter(a=>typeof a=="string"&&!!a)),d=`
|
|
27
|
-
You are an expert code completion assistant.
|
|
28
|
-
|
|
29
|
-
**Context:**
|
|
30
|
-
File: ${t||"Untitled"}
|
|
31
|
-
Language: ${n||"Undetermined"}
|
|
32
|
-
Mode: ${l}
|
|
33
|
-
Stack: ${p||"None"}`,c=`
|
|
34
|
-
**Related Files:**
|
|
35
|
-
${_e(r)}
|
|
36
|
-
|
|
37
|
-
**Source:**
|
|
38
|
-
\`\`\`
|
|
39
|
-
${i}<cursor>${s}
|
|
40
|
-
\`\`\`
|
|
41
|
-
|
|
42
|
-
${ae(l)} the code at <cursor>.
|
|
43
|
-
|
|
44
|
-
Output only the raw code to be inserted at the cursor location without any additional text or comments.`;return {system:d,user:c}};var Re=(o,e)=>{if(!o)throw new Error("Please provide an API key.");if(!e||typeof e=="object"&&Object.keys(e).length===0)throw new Error("Please provide options.")},Me=(o,e)=>{if(typeof o=="object"){if(e!==undefined)throw new Error("Provider should not be specified when using a custom model.");if(!("config"in o)||!("transformResponse"in o))throw new Error("Please ensure both config and transformResponse are provided for custom model.");return}if(!e||!Z.includes(e))throw new Error(`Provider must be specified and supported when using built-in models. Please choose from: ${A(Z)}`);if(typeof o=="string"&&!Q[e].includes(o))throw new Error(`Model "${o}" is not supported by the "${e}" provider. Supported models: ${A(Q[e])}`)};var ee=class{constructor(e,t){Re(e,t),this.apiKey=e,this.provider=t.provider,this.model=t.model,Me(this.model,this.provider);}async complete(e){let{body:t,options:r}=e,{completionMetadata:n}=t,{headers:i={},customPrompt:s}=r??{},l=this.generatePrompt(n,s),{endpoint:p,requestBody:d,headers:c}=this.prepareRequestDetails(l,n);try{let a=await this.sendCompletionRequest(p,d,{...c,...i});return this.processCompletionResponse(a)}catch(a){return this.handleCompletionError(a)}}generatePrompt(e,t){let r=ye(e);return t?{...r,...t(e)}:r}prepareRequestDetails(e,t){if(typeof this.model=="object"&&"config"in this.model){let r=this.model.config(this.apiKey,e),n=r.endpoint,i=r.body??{},s=r.headers??{};return {endpoint:n,requestBody:i,headers:s}}else {if(!this.provider)throw new Error("Provider is required for non-custom models");let r=fe(this.model,this.apiKey,this.provider),n=Pe(this.apiKey,this.provider),i=he(this.model,this.provider,e,t);return {endpoint:r,requestBody:i,headers:n}}}async sendCompletionRequest(e,t,r){return F.post(e,t,{headers:r})}processCompletionResponse(e){if(typeof this.model=="object"&&"transformResponse"in this.model)return {completion:this.model.transformResponse(e).text??null,raw:e};if(!this.provider)throw new Error("Provider is required for non-custom models");return {completion:Ee(e,this.provider),raw:e}}handleCompletionError(e){return {error:S(e).message,completion:null}}};export{ee as Copilot,we as registerCompletion};
|