monacopilot 0.12.9 → 0.13.0
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 +17 -11
- package/build/index.d.mts +23 -6
- package/build/index.d.ts +23 -6
- package/build/index.js +6 -6
- package/build/index.mjs +7 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
- [Changing the Provider and Model](#changing-the-provider-and-model)
|
|
33
33
|
- [Custom Model](#custom-model)
|
|
34
34
|
- [Completion Request Options](#completion-request-options)
|
|
35
|
-
- [Custom Headers for
|
|
35
|
+
- [Custom Headers for LLM Requests](#custom-headers-for-llm-requests)
|
|
36
36
|
- [Cross-Language API Handler Implementation](#cross-language-api-handler-implementation)
|
|
37
37
|
- [Contributing](#contributing)
|
|
38
38
|
|
|
@@ -50,6 +50,8 @@ Here are some examples of how to integrate Monacopilot into your project:
|
|
|
50
50
|
|
|
51
51
|
[Inline Completions Demo Video](https://github.com/user-attachments/assets/f2ec4ae1-f658-4002-af9c-c6b1bbad70d9)
|
|
52
52
|
|
|
53
|
+
In the demo, we are using the `onTyping` trigger mode with the Groq model, which is why you see such quick and fast completions. Groq provides very fast response times.
|
|
54
|
+
|
|
53
55
|
### Installation
|
|
54
56
|
|
|
55
57
|
To install Monacopilot, run:
|
|
@@ -78,13 +80,17 @@ const copilot = new Copilot(process.env.GROQ_API_KEY!, {
|
|
|
78
80
|
app.use(express.json());
|
|
79
81
|
|
|
80
82
|
app.post('/complete', async (req, res) => {
|
|
81
|
-
const {completion, error} = await copilot.complete({
|
|
83
|
+
const {completion, error, raw} = await copilot.complete({
|
|
82
84
|
body: req.body,
|
|
83
85
|
});
|
|
84
86
|
|
|
87
|
+
// Process raw LLM response if needed
|
|
88
|
+
if (raw) {
|
|
89
|
+
calculateCost(raw.usage.total_tokens);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Handle error if needed
|
|
85
93
|
if (error) {
|
|
86
|
-
// Handle error if needed
|
|
87
|
-
// ...
|
|
88
94
|
res.status(500).json({completion: null, error});
|
|
89
95
|
}
|
|
90
96
|
|
|
@@ -410,7 +416,7 @@ const copilot = new Copilot(process.env.OPENAI_API_KEY, {
|
|
|
410
416
|
|
|
411
417
|
The default provider is `groq`, and the default model is `llama-3-70b`.
|
|
412
418
|
|
|
413
|
-
> **Tip:**
|
|
419
|
+
> **Tip:** Even though the default provider and model are `groq` and `llama-3-70b`, it's always recommended to specify a provider and model when using Monacopilot. This ensures your code remains consistent even if the default settings change in future updates.
|
|
414
420
|
|
|
415
421
|
There are other providers and models available. Here is a list:
|
|
416
422
|
|
|
@@ -422,7 +428,7 @@ There are other providers and models available. Here is a list:
|
|
|
422
428
|
|
|
423
429
|
### Custom Model
|
|
424
430
|
|
|
425
|
-
You can use a custom
|
|
431
|
+
You can use a custom LLM that isn't built into Monacopilot by setting up a `model` when you create a new Copilot. This feature lets you connect to LLMs from other services or your own custom-built models.
|
|
426
432
|
|
|
427
433
|
Please ensure you are using a high-quality model, especially for coding tasks, to get the best and most accurate completions. Also, use a model with very low response latency (preferably under 1.5 seconds) to enjoy a great experience and utilize the full power of Monacopilot.
|
|
428
434
|
|
|
@@ -475,7 +481,7 @@ The `transformResponse` function must return an object with the `text` property.
|
|
|
475
481
|
|
|
476
482
|
## Completion Request Options
|
|
477
483
|
|
|
478
|
-
### Custom Headers for
|
|
484
|
+
### Custom Headers for LLM Requests
|
|
479
485
|
|
|
480
486
|
You can add custom headers to the provider's completion requests. For example, if you select `OpenAI` as your provider, you can add a custom header to the OpenAI completion requests made by Monacopilot.
|
|
481
487
|
|
|
@@ -583,8 +589,8 @@ While the example in this documentation uses JavaScript/Node.js (which is recomm
|
|
|
583
589
|
|
|
584
590
|
1. Create an endpoint that accepts POST requests (e.g., `/complete`).
|
|
585
591
|
2. The endpoint should expect a JSON body containing completion metadata.
|
|
586
|
-
3. Use the metadata to construct a prompt for your
|
|
587
|
-
4. Send the prompt to your chosen
|
|
592
|
+
3. Use the metadata to construct a prompt for your LLM.
|
|
593
|
+
4. Send the prompt to your chosen LLM and get the completion.
|
|
588
594
|
5. Return a JSON response with the following structure:
|
|
589
595
|
|
|
590
596
|
```json
|
|
@@ -607,11 +613,11 @@ While the example in this documentation uses JavaScript/Node.js (which is recomm
|
|
|
607
613
|
- The prompt should instruct the model to return only the completion text, without any additional formatting or explanations.
|
|
608
614
|
- The completion text should be ready for direct insertion into the editor.
|
|
609
615
|
|
|
610
|
-
Check out the [prompt.ts](https://github.com/arshad-yaseen/monacopilot/blob/main/src/helpers/completion/prompt.ts) file to see how Monacopilot generates the prompt. This will give you an idea of how to structure the prompt for your
|
|
616
|
+
Check out the [prompt.ts](https://github.com/arshad-yaseen/monacopilot/blob/main/src/helpers/completion/prompt.ts) file to see how Monacopilot generates the prompt. This will give you an idea of how to structure the prompt for your LLM to achieve the best completions.
|
|
611
617
|
|
|
612
618
|
### Metadata Overview
|
|
613
619
|
|
|
614
|
-
The request body's `completionMetadata` object contains essential information for crafting a prompt for the
|
|
620
|
+
The request body's `completionMetadata` object contains essential information for crafting a prompt for the LLM to generate accurate completions. See the [Completion Metadata](#completion-metadata) section for more details.
|
|
615
621
|
|
|
616
622
|
### Example Implementation (Python with FastAPI)
|
|
617
623
|
|
package/build/index.d.mts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { Message } from '@anthropic-ai/sdk/resources';
|
|
2
|
+
import { ChatCompletion as ChatCompletion$1 } from 'groq-sdk/resources/chat/completions';
|
|
3
|
+
import { ChatCompletion } from 'openai/resources/chat/completions';
|
|
1
4
|
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
2
5
|
import * as monaco_editor from 'monaco-editor';
|
|
3
6
|
|
|
@@ -6,6 +9,9 @@ type GroqModel = 'llama-3-70b';
|
|
|
6
9
|
type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' | 'claude-3-sonnet';
|
|
7
10
|
type CopilotModel = OpenAIModel | GroqModel | AnthropicModel;
|
|
8
11
|
type CopilotProvider = 'openai' | 'groq' | 'anthropic';
|
|
12
|
+
type OpenAIChatCompletion = ChatCompletion;
|
|
13
|
+
type GroqChatCompletion = ChatCompletion$1;
|
|
14
|
+
type AnthropicChatCompletion = Message;
|
|
9
15
|
type PromptData = {
|
|
10
16
|
system: string;
|
|
11
17
|
user: string;
|
|
@@ -20,11 +26,11 @@ interface CopilotOptions {
|
|
|
20
26
|
*/
|
|
21
27
|
provider?: CopilotProvider;
|
|
22
28
|
/**
|
|
23
|
-
* The model to use for copilot
|
|
29
|
+
* The model to use for copilot LLM requests.
|
|
24
30
|
* This can be either:
|
|
25
31
|
* 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.
|
|
26
32
|
* If you choose this option, also set the `provider` property to the corresponding provider of the model.
|
|
27
|
-
* 2. A custom model configuration object: Use this option if you want to use a
|
|
33
|
+
* 2. A custom model configuration object: Use this option if you want to use a LLM from a third-party service or your own custom model.
|
|
28
34
|
*
|
|
29
35
|
* If not specified, a default model will be used.
|
|
30
36
|
*/
|
|
@@ -212,7 +218,7 @@ interface CompletionRequestBody {
|
|
|
212
218
|
}
|
|
213
219
|
interface CompletionRequestOptions {
|
|
214
220
|
/**
|
|
215
|
-
* Custom headers to include in the request to the
|
|
221
|
+
* Custom headers to include in the request to the LLM provider.
|
|
216
222
|
*/
|
|
217
223
|
headers?: Record<string, string>;
|
|
218
224
|
/**
|
|
@@ -227,8 +233,18 @@ interface CompletionRequestOptions {
|
|
|
227
233
|
}
|
|
228
234
|
type CustomPrompt = (completionMetadata: CompletionMetadata) => Partial<PromptData>;
|
|
229
235
|
interface CompletionResponse {
|
|
236
|
+
/**
|
|
237
|
+
* The completion text.
|
|
238
|
+
*/
|
|
230
239
|
completion: string | null;
|
|
240
|
+
/**
|
|
241
|
+
* The error message.
|
|
242
|
+
*/
|
|
231
243
|
error?: string;
|
|
244
|
+
/**
|
|
245
|
+
* The raw response from the LLM.
|
|
246
|
+
*/
|
|
247
|
+
raw?: unknown;
|
|
232
248
|
}
|
|
233
249
|
type CompletionMode = 'insert' | 'complete' | 'continue';
|
|
234
250
|
interface CompletionMetadata {
|
|
@@ -266,8 +282,9 @@ interface CompletionMetadata {
|
|
|
266
282
|
editorState: {
|
|
267
283
|
/**
|
|
268
284
|
* The mode of the completion.
|
|
269
|
-
* - `
|
|
270
|
-
* - `
|
|
285
|
+
* - `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.
|
|
286
|
+
* - `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.
|
|
287
|
+
* - `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.
|
|
271
288
|
*/
|
|
272
289
|
completionMode: CompletionMode;
|
|
273
290
|
};
|
|
@@ -308,4 +325,4 @@ declare const registerCompletion: (monaco: Monaco, editor: StandaloneCodeEditor,
|
|
|
308
325
|
*/
|
|
309
326
|
declare const registerCopilot: (monaco: typeof monaco_editor, editor: monaco_editor.editor.IStandaloneCodeEditor, options: RegisterCompletionOptions) => CompletionRegistration;
|
|
310
327
|
|
|
311
|
-
export { type CompletionMetadata, type CompletionRegistration, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, Copilot, type CopilotModel, type CopilotOptions, type CopilotProvider, type CustomCopilotModel, type CustomCopilotModelConfig, type CustomCopilotModelTransformResponse, type Monaco, type RegisterCompletionOptions, type StandaloneCodeEditor, registerCompletion, registerCopilot };
|
|
328
|
+
export { type AnthropicChatCompletion, type AnthropicModel, type CompletionMetadata, type CompletionRegistration, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, Copilot, type CopilotModel, type CopilotOptions, type CopilotProvider, type CustomCopilotModel, type CustomCopilotModelConfig, type CustomCopilotModelTransformResponse, type GroqChatCompletion, type GroqModel, type Monaco, type OpenAIChatCompletion, type OpenAIModel, type RegisterCompletionOptions, type StandaloneCodeEditor, registerCompletion, registerCopilot };
|
package/build/index.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { Message } from '@anthropic-ai/sdk/resources';
|
|
2
|
+
import { ChatCompletion as ChatCompletion$1 } from 'groq-sdk/resources/chat/completions';
|
|
3
|
+
import { ChatCompletion } from 'openai/resources/chat/completions';
|
|
1
4
|
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
2
5
|
import * as monaco_editor from 'monaco-editor';
|
|
3
6
|
|
|
@@ -6,6 +9,9 @@ type GroqModel = 'llama-3-70b';
|
|
|
6
9
|
type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' | 'claude-3-sonnet';
|
|
7
10
|
type CopilotModel = OpenAIModel | GroqModel | AnthropicModel;
|
|
8
11
|
type CopilotProvider = 'openai' | 'groq' | 'anthropic';
|
|
12
|
+
type OpenAIChatCompletion = ChatCompletion;
|
|
13
|
+
type GroqChatCompletion = ChatCompletion$1;
|
|
14
|
+
type AnthropicChatCompletion = Message;
|
|
9
15
|
type PromptData = {
|
|
10
16
|
system: string;
|
|
11
17
|
user: string;
|
|
@@ -20,11 +26,11 @@ interface CopilotOptions {
|
|
|
20
26
|
*/
|
|
21
27
|
provider?: CopilotProvider;
|
|
22
28
|
/**
|
|
23
|
-
* The model to use for copilot
|
|
29
|
+
* The model to use for copilot LLM requests.
|
|
24
30
|
* This can be either:
|
|
25
31
|
* 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.
|
|
26
32
|
* If you choose this option, also set the `provider` property to the corresponding provider of the model.
|
|
27
|
-
* 2. A custom model configuration object: Use this option if you want to use a
|
|
33
|
+
* 2. A custom model configuration object: Use this option if you want to use a LLM from a third-party service or your own custom model.
|
|
28
34
|
*
|
|
29
35
|
* If not specified, a default model will be used.
|
|
30
36
|
*/
|
|
@@ -212,7 +218,7 @@ interface CompletionRequestBody {
|
|
|
212
218
|
}
|
|
213
219
|
interface CompletionRequestOptions {
|
|
214
220
|
/**
|
|
215
|
-
* Custom headers to include in the request to the
|
|
221
|
+
* Custom headers to include in the request to the LLM provider.
|
|
216
222
|
*/
|
|
217
223
|
headers?: Record<string, string>;
|
|
218
224
|
/**
|
|
@@ -227,8 +233,18 @@ interface CompletionRequestOptions {
|
|
|
227
233
|
}
|
|
228
234
|
type CustomPrompt = (completionMetadata: CompletionMetadata) => Partial<PromptData>;
|
|
229
235
|
interface CompletionResponse {
|
|
236
|
+
/**
|
|
237
|
+
* The completion text.
|
|
238
|
+
*/
|
|
230
239
|
completion: string | null;
|
|
240
|
+
/**
|
|
241
|
+
* The error message.
|
|
242
|
+
*/
|
|
231
243
|
error?: string;
|
|
244
|
+
/**
|
|
245
|
+
* The raw response from the LLM.
|
|
246
|
+
*/
|
|
247
|
+
raw?: unknown;
|
|
232
248
|
}
|
|
233
249
|
type CompletionMode = 'insert' | 'complete' | 'continue';
|
|
234
250
|
interface CompletionMetadata {
|
|
@@ -266,8 +282,9 @@ interface CompletionMetadata {
|
|
|
266
282
|
editorState: {
|
|
267
283
|
/**
|
|
268
284
|
* The mode of the completion.
|
|
269
|
-
* - `
|
|
270
|
-
* - `
|
|
285
|
+
* - `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.
|
|
286
|
+
* - `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.
|
|
287
|
+
* - `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.
|
|
271
288
|
*/
|
|
272
289
|
completionMode: CompletionMode;
|
|
273
290
|
};
|
|
@@ -308,4 +325,4 @@ declare const registerCompletion: (monaco: Monaco, editor: StandaloneCodeEditor,
|
|
|
308
325
|
*/
|
|
309
326
|
declare const registerCopilot: (monaco: typeof monaco_editor, editor: monaco_editor.editor.IStandaloneCodeEditor, options: RegisterCompletionOptions) => CompletionRegistration;
|
|
310
327
|
|
|
311
|
-
export { type CompletionMetadata, type CompletionRegistration, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, Copilot, type CopilotModel, type CopilotOptions, type CopilotProvider, type CustomCopilotModel, type CustomCopilotModelConfig, type CustomCopilotModelTransformResponse, type Monaco, type RegisterCompletionOptions, type StandaloneCodeEditor, registerCompletion, registerCopilot };
|
|
328
|
+
export { type AnthropicChatCompletion, type AnthropicModel, type CompletionMetadata, type CompletionRegistration, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, Copilot, type CopilotModel, type CopilotOptions, type CopilotProvider, type CustomCopilotModel, type CustomCopilotModelConfig, type CustomCopilotModelTransformResponse, type GroqChatCompletion, type GroqModel, type Monaco, type OpenAIChatCompletion, type OpenAIModel, type RegisterCompletionOptions, type StandaloneCodeEditor, registerCompletion, registerCopilot };
|
package/build/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var _=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var be=(t,e)=>{for(var o in e)_(t,o,{get:e[o],enumerable:!0})},Ee=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Te(e))!Me.call(t,n)&&n!==o&&_(t,n,{get:()=>e[n],enumerable:!(r=xe(e,n))||r.enumerable});return t};var Oe=t=>Ee(_({},"__esModule",{value:!0}),t);var Ue={};be(Ue,{Copilot:()=>D,registerCompletion:()=>G,registerCopilot:()=>Re});module.exports=Oe(Ue);var H=["groq","openai","anthropic"],X={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3-5-sonnet":"claude-3-5-sonnet-20241022","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"},V={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"]},J="llama-3-70b",Z="groq",Q={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},O=.1;var ee={"claude-3-5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var ve={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:U(t),temperature:O,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},Ie={createRequestBody:(t,e)=>({model:U(t),temperature:O,messages:[{role:"system",content:e.system},{role:"user",content:e.user}]}),createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},Ae={createRequestBody:(t,e)=>({model:U(t),temperature:O,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:we(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>!t.content||typeof t.content!="string"?null:t.content},j={openai:ve,groq:Ie,anthropic:Ae},te=(t,e,o)=>j[e].createRequestBody(t,o),oe=(t,e)=>j[e].createHeaders(t),re=(t,e)=>j[e].parseCompletion(t),U=t=>X[t],ne=t=>Q[t],we=t=>ee[t]||4096;var ie="\x1B[91m",se="\x1B[93m",v="\x1B[0m",W="\x1B[1m",h=t=>{let e,o;t instanceof Error?(e=t.message,o=t.stack):typeof t=="string"?e=t:e="An unknown error occurred";let r=`${ie}${W}[MONACOPILOT ERROR] ${e}${v}`;return console.error(o?`${r}
|
|
2
2
|
${ie}Stack trace:${v}
|
|
3
|
-
${o}`:r),{message:e,stack:o}},
|
|
3
|
+
${o}`:r),{message:e,stack:o}},ae=t=>{console.warn(`${se}${W}[MONACOPILOT WARN] ${t}${v}`)};var I=(t,e,o)=>console.warn(`${se}${W}[MONACOPILOT DEPRECATED] "${t}" is deprecated${o?` in ${o}`:""}. Please use "${e}" instead. It will be removed in a future version.${v}`);var A=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((s,d)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=d,o=setTimeout(()=>{s(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},T=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var z=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1];var w=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),le=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),f=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),pe=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())}),K=(t,e,o={})=>{if(e<=0)return"";let r=t.split(`
|
|
4
4
|
`),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(d=>d==="")?`
|
|
5
5
|
`.repeat(e):s.join(`
|
|
6
6
|
`)}let i=r.slice(0,e);return i.every(s=>s==="")?`
|
|
7
7
|
`.repeat(e):i.join(`
|
|
8
|
-
`)};var ce=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(`${i.statusText||o.fallbackError||"Network error"}`);return i.json()},Le=(t,e)=>ce(t,"GET",e),De=(t,e,o)=>ce(t,"POST",{...o,body:e}),L={GET:Le,POST:De};var de=(t,e)=>{let o=w(t,e).trim(),r=le(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var Se=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:n}=t,i=
|
|
8
|
+
`)};var ce=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(`${i.statusText||o.fallbackError||"Network error"}`);return i.json()},Le=(t,e)=>ce(t,"GET",e),De=(t,e,o)=>ce(t,"POST",{...o,body:e}),L={GET:Le,POST:De};var de=(t,e)=>{let o=w(t,e).trim(),r=le(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var Se=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:n}=t,i=T([n,...e].filter(c=>typeof c=="string"&&!!c)),s=`You are an expert ${i?`${i} `:""}developer assistant.`,d="Your task is to provide precise and contextually relevant code completions, modifications, or generations",a=o?`for the file '${o}'`:"",l=r&&r.length>0?"Consider the context of the current and related files provided.":"",m="Ensure that your responses integrate seamlessly with the existing code and maintain consistency with the project's style and conventions.",u="Before providing the completion or modification, think through the problem step-by-step, considering best practices and any potential edge cases.",p=n?`Pay special attention to ${n}-specific syntax and best practices.`:"";return`${s}
|
|
9
9
|
${d} ${a}.
|
|
10
10
|
${m}
|
|
11
11
|
${l}
|
|
@@ -30,7 +30,7 @@ ${t.trim()}
|
|
|
30
30
|
`.trim()},me=(t,e)=>({system:Se(e),user:ke(t,e)});var ue="<cursor>",Be=t=>{let{textBeforeCursor:e="",textAfterCursor:o="",editorState:{completionMode:r}}=t,n=`<code_file>
|
|
31
31
|
${e}${ue}${o}
|
|
32
32
|
</code_file>`,s=`
|
|
33
|
-
You are an
|
|
33
|
+
You are an expert coding assistant. Your task is to provide code completions based on the current cursor position in the code.
|
|
34
34
|
|
|
35
35
|
Below is the code file with a special token '${ue}' indicating the current cursor position.
|
|
36
36
|
|
|
@@ -52,8 +52,8 @@ Depending on the completion mode, adjust your completion accordingly:
|
|
|
52
52
|
${{continue:"-- Continue writing the code from the current cursor location.",insert:"-- Insert the appropriate code snippet at the cursor point.",complete:"-- Supply the necessary code to finish the ongoing statement or block."}[r]||""}
|
|
53
53
|
|
|
54
54
|
Remember to output **only** the code that should be inserted at the cursor, without any additional formatting or explanations.
|
|
55
|
-
`.trim();return me(s,t)},Ce=Be;var D=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??Z,this.model=o.model??J,this.validateInputs()}validateInputs(){if(!H.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${
|
|
55
|
+
`.trim();return me(s,t)},Ce=Be;var D=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??Z,this.model=o.model??J,this.validateInputs()}validateInputs(){if(!H.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${T(H)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!V[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${T(V[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},d=this.generatePrompt(n,s),{endpoint:a,requestBody:l,headers:m}=this.prepareRequestDetails(d);try{let u=await this.sendCompletionRequest(a,l,{...m,...i});return this.processCompletionResponse(u)}catch(u){return this.handleCompletionError(u)}}generatePrompt(e,o){let r=Ce(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=ne(this.provider),r,n=oe(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let i=this.model.config(this.apiKey,e);o=i.endpoint??o,r=i.body??{},n={...n,...i.headers}}else r=te(this.model,this.provider,e);return{endpoint:o,requestBody:r,headers:n}}async sendCompletionRequest(e,o,r){return L.POST(e,o,{headers:r})}processCompletionResponse(e){if(typeof this.model=="object"&&"transformResponse"in this.model){let o=this.model.transformResponse(e);return"completion"in o&&I("completion","text","Copilot.options.model.transformResponse"),{completion:o.text??o.completion??null,raw:e}}else return{completion:re(e,this.provider),raw:e}}handleCompletionError(e){return{error:h(e).message,completion:null}}};var S=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],s=i.split(`
|
|
56
56
|
`).slice(1,-1).join(`
|
|
57
57
|
`);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
58
58
|
|
|
59
|
-
`),this}build(){return this.formattedCompletion}};var F=class{constructor(e,o){this.cursorPos=e,this.mdl=o}shouldProvideCompletions(){return!de(this.cursorPos,this.mdl)}};var k=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e)}enqueue(e){let o;return this.size===this.capacity&&(o=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,o}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==void 0)}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 k($.MAX_CACHE_SIZE)}get(e,o){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,o))}add(e){this.cache.enqueue(e)}clear(){this.cache.clear()}isValidCacheItem(e,o,r){let n=r.getValueInRange(e.range);return f(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:d,endColumn:a}=n,{lineNumber:l,column:m}=o,u=l===s&&m===d,p=i.startsWith(r)&&l===s&&m>=d-r.length&&m<=a+r.length;return u||p}};$.MAX_CACHE_SIZE=10;var B=$;var $e="application/json",ge=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:n}=await L.POST(e,o,{headers:{"Content-Type":$e},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return{completion:r}},he=({pos:t,mdl:e,options:o})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:d}=o,a=
|
|
59
|
+
`),this}build(){return this.formattedCompletion}};var F=class{constructor(e,o){this.cursorPos=e,this.mdl=o}shouldProvideCompletions(){return!de(this.cursorPos,this.mdl)}};var k=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e)}enqueue(e){let o;return this.size===this.capacity&&(o=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,o}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==void 0)}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 k($.MAX_CACHE_SIZE)}get(e,o){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,o))}add(e){this.cache.enqueue(e)}clear(){this.cache.clear()}isValidCacheItem(e,o,r){let n=r.getValueInRange(e.range);return f(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:d,endColumn:a}=n,{lineNumber:l,column:m}=o,u=l===s&&m===d,p=i.startsWith(r)&&l===s&&m>=d-r.length&&m<=a+r.length;return u||p}};$.MAX_CACHE_SIZE=10;var B=$;var $e="application/json",ge=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:n}=await L.POST(e,o,{headers:{"Content-Type":$e},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return{completion:r}},he=({pos:t,mdl:e,options:o})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:d}=o,a=qe(t,e),m=!!s?.length?3:2,u=d?Math.floor(d/m):void 0,p=(g,x,N)=>{let E=g(t,e);return x?K(E,x,N):E},C=(g,x)=>!g||!x?g:g.map(({content:N,...E})=>({...E,content:K(N,x)})),c=p(f,u,{from:"end"}),b=p(pe,u),R=C(s,u);return{filename:r,language:n,technologies:i,relatedFiles:R,textBeforeCursor:c,textAfterCursor:b,cursorPosition:t,editorState:{completionMode:a}}},qe=(t,e)=>{let o=z(t,e),r=w(t,e);return o?"insert":r.trim()?"complete":"continue"};var fe=(t,e,o,r)=>{if(!r)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let n=o.getOffsetAt(e),i=o.getValue().substring(n),s=0,d=0,a=0,l=r.length,m=i.length;if(n>=o.getValue().length)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(m===0)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let u=Math.min(l,m);for(let c=0;c<u&&r[c]===i[c];c++)s++;for(let c=1;c<=u;c++)r.slice(-c)===i.slice(0,c)&&(d=c);if(a=Math.max(s,d),a===0){for(let c=1;c<l;c++)if(i.startsWith(r.substring(c))){a=l-c;break}}let p=n+a,C=o.getPositionAt(p);return new t.Range(e.lineNumber,e.column,C.lineNumber,C.column)},Pe=t=>S.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),P=t=>({items:t,enableForwardStability:!0});var Y={onTyping:300,onIdle:600,onDemand:0},_e=t=>({onTyping:A(t,Y.onTyping),onIdle:A(t,Y.onIdle),onDemand:A(t,Y.onDemand)}),q=new B,He=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{let{trigger:d="onIdle",endpoint:a,enableCaching:l=!0,onError:m,requestHandler:u}=s;if(!new F(o,e).shouldProvideCompletions())return P([]);if(l){let p=q.get(o,e).map(C=>({insertText:C.completion,range:C.range}));if(p.length>0)return i(),P(p)}if(r.isCancellationRequested||n)return P([]);try{let C=_e(u??ge)[d];r.onCancellationRequested(()=>{C.cancel()});let c=he({pos:o,mdl:e,options:s}),{completion:b}=await C({endpoint:a,body:{completionMetadata:c}});if(b){let R=Pe(b),g=fe(t,o,e,R);return l&&q.add({completion:R,range:g,textBeforeCursor:f(o,e)}),i(),P([{insertText:R,range:g}])}}catch(p){m?m(p):Ve(p)||h(p)}return P([])},Ve=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,ye=He;var y=new WeakMap,M=null,G=(t,e,o)=>{M&&M.deregister();let r=[],n={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};y.set(e,n),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let i=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(a,l,m,u)=>{let p=y.get(e);if(!(!p||o.trigger==="onDemand"&&!p.isManualTrigger))return ye({monaco:t,mdl:a,pos:l,token:u,isCompletionAccepted:p.isCompletionAccepted,onShowCompletion:()=>{p.isCompletionVisible=!0,p.isManualTrigger=!1},options:o})},freeInlineCompletions:()=>{}});r.push(i);let s=e.onKeyDown(a=>{let l=y.get(e);if(!l)return;let m=a.keyCode===t.KeyCode.Tab||a.keyCode===t.KeyCode.RightArrow&&a.metaKey;l.isCompletionVisible&&m?(l.isCompletionAccepted=!0,l.isCompletionVisible=!1):l.isCompletionAccepted=!1});r.push(s);let d={deregister:()=>{r.forEach(a=>a.dispose()),q.clear(),y.delete(e),M=null},trigger:()=>je(e)};return M=d,d}catch(i){return o.onError?o.onError(i):h(i),{deregister:()=>{r.forEach(s=>s.dispose()),y.delete(e),M=null},trigger:()=>{}}}},je=t=>{let e=y.get(t);if(!e){ae("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isManualTrigger=!0,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{})},Re=(...t)=>(I("registerCopilot","registerCompletion"),G(...t));0&&(module.exports={Copilot,registerCompletion,registerCopilot});
|
package/build/index.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
1
|
+
var N=["groq","openai","anthropic"],Y={"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-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"]},G="llama-3-70b",X="groq",J={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},O=.1;var Z={"claude-3-5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var ye={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:V(t),temperature:O,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},Re={createRequestBody:(t,e)=>({model:V(t),temperature:O,messages:[{role:"system",content:e.system},{role:"user",content:e.user}]}),createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},xe={createRequestBody:(t,e)=>({model:V(t),temperature:O,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:Te(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>!t.content||typeof t.content!="string"?null:t.content},H={openai:ye,groq:Re,anthropic:xe},Q=(t,e,o)=>H[e].createRequestBody(t,o),ee=(t,e)=>H[e].createHeaders(t),te=(t,e)=>H[e].parseCompletion(t),V=t=>Y[t],oe=t=>J[t],Te=t=>Z[t]||4096;var re="\x1B[91m",ne="\x1B[93m",v="\x1B[0m",j="\x1B[1m",h=t=>{let e,o;t instanceof Error?(e=t.message,o=t.stack):typeof t=="string"?e=t:e="An unknown error occurred";let r=`${re}${j}[MONACOPILOT ERROR] ${e}${v}`;return console.error(o?`${r}
|
|
2
2
|
${re}Stack trace:${v}
|
|
3
|
-
${o}`:r),{message:e,stack:o}},
|
|
3
|
+
${o}`:r),{message:e,stack:o}},ie=t=>{console.warn(`${ne}${j}[MONACOPILOT WARN] ${t}${v}`)};var I=(t,e,o)=>console.warn(`${ne}${j}[MONACOPILOT DEPRECATED] "${t}" is deprecated${o?` in ${o}`:""}. Please use "${e}" instead. It will be removed in a future version.${v}`);var A=(t,e)=>{let o=null,r=null,i=(...n)=>new Promise((s,d)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=d,o=setTimeout(()=>{s(t(...n)),r=null},e)});return i.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},i},T=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var U=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1];var w=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),se=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),f=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),ae=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())}),W=(t,e,o={})=>{if(e<=0)return"";let r=t.split(`
|
|
4
4
|
`),i=r.length;if(e>=i)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(d=>d==="")?`
|
|
5
5
|
`.repeat(e):s.join(`
|
|
6
6
|
`)}let n=r.slice(0,e);return n.every(s=>s==="")?`
|
|
7
7
|
`.repeat(e):n.join(`
|
|
8
|
-
`)};var le=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},i=e==="POST"&&o.body?JSON.stringify(o.body):void 0,n=await fetch(t,{method:e,headers:r,body:i,signal:o.signal});if(!n.ok)throw new Error(`${n.statusText||o.fallbackError||"Network error"}`);return n.json()},
|
|
8
|
+
`)};var le=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},i=e==="POST"&&o.body?JSON.stringify(o.body):void 0,n=await fetch(t,{method:e,headers:r,body:i,signal:o.signal});if(!n.ok)throw new Error(`${n.statusText||o.fallbackError||"Network error"}`);return n.json()},Me=(t,e)=>le(t,"GET",e),be=(t,e,o)=>le(t,"POST",{...o,body:e}),L={GET:Me,POST:be};var pe=(t,e)=>{let o=w(t,e).trim(),r=se(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var Ee=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:i}=t,n=T([i,...e].filter(c=>typeof c=="string"&&!!c)),s=`You are an expert ${n?`${n} `:""}developer assistant.`,d="Your task is to provide precise and contextually relevant code completions, modifications, or generations",a=o?`for the file '${o}'`:"",l=r&&r.length>0?"Consider the context of the current and related files provided.":"",m="Ensure that your responses integrate seamlessly with the existing code and maintain consistency with the project's style and conventions.",u="Before providing the completion or modification, think through the problem step-by-step, considering best practices and any potential edge cases.",p=i?`Pay special attention to ${i}-specific syntax and best practices.`:"";return`${s}
|
|
9
9
|
${d} ${a}.
|
|
10
10
|
${m}
|
|
11
11
|
${l}
|
|
@@ -27,10 +27,10 @@ ${t.trim()}
|
|
|
27
27
|
</instructions>
|
|
28
28
|
${r}
|
|
29
29
|
</task>
|
|
30
|
-
`.trim()},ce=(t,e)=>({system:
|
|
30
|
+
`.trim()},ce=(t,e)=>({system:Ee(e),user:ve(t,e)});var de="<cursor>",Ie=t=>{let{textBeforeCursor:e="",textAfterCursor:o="",editorState:{completionMode:r}}=t,i=`<code_file>
|
|
31
31
|
${e}${de}${o}
|
|
32
32
|
</code_file>`,s=`
|
|
33
|
-
You are an
|
|
33
|
+
You are an expert coding assistant. Your task is to provide code completions based on the current cursor position in the code.
|
|
34
34
|
|
|
35
35
|
Below is the code file with a special token '${de}' indicating the current cursor position.
|
|
36
36
|
|
|
@@ -52,8 +52,8 @@ Depending on the completion mode, adjust your completion accordingly:
|
|
|
52
52
|
${{continue:"-- Continue writing the code from the current cursor location.",insert:"-- Insert the appropriate code snippet at the cursor point.",complete:"-- Supply the necessary code to finish the ongoing statement or block."}[r]||""}
|
|
53
53
|
|
|
54
54
|
Remember to output **only** the code that should be inserted at the cursor, without any additional formatting or explanations.
|
|
55
|
-
`.trim();return ce(s,t)},me=Ie;var z=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??X,this.model=o.model??G,this.validateInputs()}validateInputs(){if(!
|
|
55
|
+
`.trim();return ce(s,t)},me=Ie;var z=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??X,this.model=o.model??G,this.validateInputs()}validateInputs(){if(!N.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${T(N)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!_[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${T(_[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:i}=o,{headers:n={},customPrompt:s}=r??{},d=this.generatePrompt(i,s),{endpoint:a,requestBody:l,headers:m}=this.prepareRequestDetails(d);try{let u=await this.sendCompletionRequest(a,l,{...m,...n});return this.processCompletionResponse(u)}catch(u){return this.handleCompletionError(u)}}generatePrompt(e,o){let r=me(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=oe(this.provider),r,i=ee(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let n=this.model.config(this.apiKey,e);o=n.endpoint??o,r=n.body??{},i={...i,...n.headers}}else r=Q(this.model,this.provider,e);return{endpoint:o,requestBody:r,headers:i}}async sendCompletionRequest(e,o,r){return L.POST(e,o,{headers:r})}processCompletionResponse(e){if(typeof this.model=="object"&&"transformResponse"in this.model){let o=this.model.transformResponse(e);return"completion"in o&&I("completion","text","Copilot.options.model.transformResponse"),{completion:o.text??o.completion??null,raw:e}}else return{completion:te(e,this.provider),raw:e}}handleCompletionError(e){return{error:h(e).message,completion:null}}};var D=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,i;for(;(i=o.exec(e))!==null;){let n=i[0],s=n.split(`
|
|
56
56
|
`).slice(1,-1).join(`
|
|
57
57
|
`);r=r.replace(n,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
58
58
|
|
|
59
|
-
`),this}build(){return this.formattedCompletion}};var S=class{constructor(e,o){this.cursorPos=e,this.mdl=o}shouldProvideCompletions(){return!pe(this.cursorPos,this.mdl)}};var F=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e)}enqueue(e){let o;return this.size===this.capacity&&(o=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,o}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==void 0)}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 B=class B{constructor(){this.cache=new F(B.MAX_CACHE_SIZE)}get(e,o){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,o))}add(e){this.cache.enqueue(e)}clear(){this.cache.clear()}isValidCacheItem(e,o,r){let i=r.getValueInRange(e.range);return f(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,i)}isPositionValid(e,o,r){let{range:i,completion:n}=e,{startLineNumber:s,startColumn:d,endColumn:a}=i,{lineNumber:l,column:m}=o,u=l===s&&m===d,p=n.startsWith(r)&&l===s&&m>=d-r.length&&m<=a+r.length;return u||p}};B.MAX_CACHE_SIZE=10;var k=B;var Ae="application/json",ue=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:i}=await L.POST(e,o,{headers:{"Content-Type":Ae},fallbackError:"Error while fetching completion item"});if(i)throw new Error(i);return{completion:r}},Ce=({pos:t,mdl:e,options:o})=>{let{filename:r,language:i,technologies:n,relatedFiles:s,maxContextLines:d}=o,a=we(t,e),m=!!s?.length?3:2,u=d?Math.floor(d/m):void 0,p=(g,
|
|
59
|
+
`),this}build(){return this.formattedCompletion}};var S=class{constructor(e,o){this.cursorPos=e,this.mdl=o}shouldProvideCompletions(){return!pe(this.cursorPos,this.mdl)}};var F=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e)}enqueue(e){let o;return this.size===this.capacity&&(o=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,o}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==void 0)}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 B=class B{constructor(){this.cache=new F(B.MAX_CACHE_SIZE)}get(e,o){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,o))}add(e){this.cache.enqueue(e)}clear(){this.cache.clear()}isValidCacheItem(e,o,r){let i=r.getValueInRange(e.range);return f(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,i)}isPositionValid(e,o,r){let{range:i,completion:n}=e,{startLineNumber:s,startColumn:d,endColumn:a}=i,{lineNumber:l,column:m}=o,u=l===s&&m===d,p=n.startsWith(r)&&l===s&&m>=d-r.length&&m<=a+r.length;return u||p}};B.MAX_CACHE_SIZE=10;var k=B;var Ae="application/json",ue=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:i}=await L.POST(e,o,{headers:{"Content-Type":Ae},fallbackError:"Error while fetching completion item"});if(i)throw new Error(i);return{completion:r}},Ce=({pos:t,mdl:e,options:o})=>{let{filename:r,language:i,technologies:n,relatedFiles:s,maxContextLines:d}=o,a=we(t,e),m=!!s?.length?3:2,u=d?Math.floor(d/m):void 0,p=(g,x,q)=>{let E=g(t,e);return x?W(E,x,q):E},C=(g,x)=>!g||!x?g:g.map(({content:q,...E})=>({...E,content:W(q,x)})),c=p(f,u,{from:"end"}),b=p(ae,u),R=C(s,u);return{filename:r,language:i,technologies:n,relatedFiles:R,textBeforeCursor:c,textAfterCursor:b,cursorPosition:t,editorState:{completionMode:a}}},we=(t,e)=>{let o=U(t,e),r=w(t,e);return o?"insert":r.trim()?"complete":"continue"};var ge=(t,e,o,r)=>{if(!r)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let i=o.getOffsetAt(e),n=o.getValue().substring(i),s=0,d=0,a=0,l=r.length,m=n.length;if(i>=o.getValue().length)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(m===0)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let u=Math.min(l,m);for(let c=0;c<u&&r[c]===n[c];c++)s++;for(let c=1;c<=u;c++)r.slice(-c)===n.slice(0,c)&&(d=c);if(a=Math.max(s,d),a===0){for(let c=1;c<l;c++)if(n.startsWith(r.substring(c))){a=l-c;break}}let p=i+a,C=o.getPositionAt(p);return new t.Range(e.lineNumber,e.column,C.lineNumber,C.column)},he=t=>D.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),P=t=>({items:t,enableForwardStability:!0});var K={onTyping:300,onIdle:600,onDemand:0},De=t=>({onTyping:A(t,K.onTyping),onIdle:A(t,K.onIdle),onDemand:A(t,K.onDemand)}),$=new k,Se=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:i,onShowCompletion:n,options:s})=>{let{trigger:d="onIdle",endpoint:a,enableCaching:l=!0,onError:m,requestHandler:u}=s;if(!new S(o,e).shouldProvideCompletions())return P([]);if(l){let p=$.get(o,e).map(C=>({insertText:C.completion,range:C.range}));if(p.length>0)return n(),P(p)}if(r.isCancellationRequested||i)return P([]);try{let C=De(u??ue)[d];r.onCancellationRequested(()=>{C.cancel()});let c=Ce({pos:o,mdl:e,options:s}),{completion:b}=await C({endpoint:a,body:{completionMetadata:c}});if(b){let R=he(b),g=ge(t,o,e,R);return l&&$.add({completion:R,range:g,textBeforeCursor:f(o,e)}),n(),P([{insertText:R,range:g}])}}catch(p){m?m(p):Fe(p)||h(p)}return P([])},Fe=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,fe=Se;var y=new WeakMap,M=null,Pe=(t,e,o)=>{M&&M.deregister();let r=[],i={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};y.set(e,i),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let n=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(a,l,m,u)=>{let p=y.get(e);if(!(!p||o.trigger==="onDemand"&&!p.isManualTrigger))return fe({monaco:t,mdl:a,pos:l,token:u,isCompletionAccepted:p.isCompletionAccepted,onShowCompletion:()=>{p.isCompletionVisible=!0,p.isManualTrigger=!1},options:o})},freeInlineCompletions:()=>{}});r.push(n);let s=e.onKeyDown(a=>{let l=y.get(e);if(!l)return;let m=a.keyCode===t.KeyCode.Tab||a.keyCode===t.KeyCode.RightArrow&&a.metaKey;l.isCompletionVisible&&m?(l.isCompletionAccepted=!0,l.isCompletionVisible=!1):l.isCompletionAccepted=!1});r.push(s);let d={deregister:()=>{r.forEach(a=>a.dispose()),$.clear(),y.delete(e),M=null},trigger:()=>ke(e)};return M=d,d}catch(n){return o.onError?o.onError(n):h(n),{deregister:()=>{r.forEach(s=>s.dispose()),y.delete(e),M=null},trigger:()=>{}}}},ke=t=>{let e=y.get(t);if(!e){ie("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isManualTrigger=!0,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{})},Be=(...t)=>(I("registerCopilot","registerCompletion"),Pe(...t));export{z as Copilot,Pe as registerCompletion,Be as registerCopilot};
|