monacopilot 0.14.2 → 0.15.1
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 +7 -6
- package/build/index.d.mts +106 -52
- package/build/index.d.ts +106 -52
- package/build/index.js +34 -115
- package/build/index.mjs +30 -115
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -288,7 +288,7 @@ registerCompletion(monaco, editor, {
|
|
|
288
288
|
|
|
289
289
|
### Caching Completions
|
|
290
290
|
|
|
291
|
-
Monacopilot caches completions by default. It uses a FIFO (First In First Out) strategy, reusing cached completions when the context and cursor position match while editing. To disable caching:
|
|
291
|
+
Monacopilot caches completions by default. It uses a FIFO (First In First Out) strategy, reusing cached completions when the context and cursor position match while editing (default: `true`). To disable caching:
|
|
292
292
|
|
|
293
293
|
```javascript
|
|
294
294
|
registerCompletion(monaco, editor, {
|
|
@@ -419,11 +419,12 @@ The default provider is `anthropic`, and the default model is `claude-3-5-haiku`
|
|
|
419
419
|
|
|
420
420
|
There are other providers and models available. Here is a list:
|
|
421
421
|
|
|
422
|
-
| Provider | Models
|
|
423
|
-
| --------- |
|
|
424
|
-
| Groq | `llama-3-70b`
|
|
425
|
-
| OpenAI | `gpt-4o`, `gpt-4o-mini`, `o1-
|
|
426
|
-
| Anthropic | `claude-3-5-sonnet`, `claude-3-haiku`, `claude-3-5-haiku`
|
|
422
|
+
| Provider | Models |
|
|
423
|
+
| --------- | ----------------------------------------------------------- |
|
|
424
|
+
| Groq | `llama-3-70b` |
|
|
425
|
+
| OpenAI | `gpt-4o`, `gpt-4o-mini`, `o1-mini (beta model)` |
|
|
426
|
+
| Anthropic | `claude-3-5-sonnet`, `claude-3-haiku`, `claude-3-5-haiku` |
|
|
427
|
+
| Google | `gemini-1.5-pro`, `gemini-1.5-flash`, `gemini-1.5-flash-8b` |
|
|
427
428
|
|
|
428
429
|
### Custom Model
|
|
429
430
|
|
package/build/index.d.mts
CHANGED
|
@@ -4,67 +4,47 @@ import { ChatCompletion } from 'openai/resources/chat/completions';
|
|
|
4
4
|
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
5
5
|
import * as monaco_editor from 'monaco-editor';
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Models available for OpenAI provider.
|
|
9
|
+
*/
|
|
10
|
+
type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-mini';
|
|
11
|
+
/**
|
|
12
|
+
* Models available for Groq provider.
|
|
13
|
+
*/
|
|
8
14
|
type GroqModel = 'llama-3-70b';
|
|
15
|
+
/**
|
|
16
|
+
* Models available for Anthropic provider.
|
|
17
|
+
*/
|
|
9
18
|
type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-5-haiku' | 'claude-3-haiku';
|
|
10
|
-
|
|
11
|
-
|
|
19
|
+
/**
|
|
20
|
+
* Models available for Google provider.
|
|
21
|
+
*/
|
|
22
|
+
type GoogleModel = 'gemini-1.5-flash' | 'gemini-1.5-flash-8b' | 'gemini-1.5-pro';
|
|
23
|
+
/**
|
|
24
|
+
* Union of all predefined Copilot models.
|
|
25
|
+
*/
|
|
26
|
+
type CopilotModel = OpenAIModel | GroqModel | AnthropicModel | GoogleModel;
|
|
27
|
+
/**
|
|
28
|
+
* Providers supported by Copilot.
|
|
29
|
+
*/
|
|
30
|
+
type CopilotProvider = 'openai' | 'groq' | 'anthropic' | 'google';
|
|
31
|
+
/**
|
|
32
|
+
* Specific ChatCompletion types for each provider.
|
|
33
|
+
*/
|
|
12
34
|
type OpenAIChatCompletion = ChatCompletion;
|
|
13
35
|
type GroqChatCompletion = ChatCompletion$1;
|
|
14
36
|
type AnthropicChatCompletion = Message;
|
|
15
|
-
type PromptData = {
|
|
16
|
-
system: string;
|
|
17
|
-
user: string;
|
|
18
|
-
};
|
|
19
37
|
/**
|
|
20
|
-
*
|
|
38
|
+
* Data structure representing the prompt data.
|
|
21
39
|
*/
|
|
22
|
-
interface
|
|
23
|
-
/**
|
|
24
|
-
* The provider to use (e.g., 'openai', 'anthropic', 'groq').
|
|
25
|
-
* If not specified, a default provider will be used.
|
|
26
|
-
*/
|
|
27
|
-
provider?: CopilotProvider;
|
|
28
|
-
/**
|
|
29
|
-
* The model to use for copilot LLM requests.
|
|
30
|
-
* This can be either:
|
|
31
|
-
* 1. A predefined model name (e.g. 'claude-3-5-haiku'): Use this option if you want to use a model that is built into Monacopilot.
|
|
32
|
-
* If you choose this option, also set the `provider` property to the corresponding provider of the model.
|
|
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.
|
|
34
|
-
*
|
|
35
|
-
* If not specified, a default model will be used.
|
|
36
|
-
*/
|
|
37
|
-
model?: CopilotModel | CustomCopilotModel;
|
|
38
|
-
}
|
|
39
|
-
type CustomCopilotModel = {
|
|
40
|
-
/**
|
|
41
|
-
* A function to configure the custom model.
|
|
42
|
-
* This function takes the API key and the prompt data and returns the configuration for the custom model.
|
|
43
|
-
*
|
|
44
|
-
* @param {string} apiKey - The API key for authentication.
|
|
45
|
-
* @param {Object} prompt - An object containing 'system' and 'user' messages generated by Monacopilot.
|
|
46
|
-
* @returns {Object} An object that may include:
|
|
47
|
-
* - endpoint: The URL for the custom model's API (required)
|
|
48
|
-
* - headers: Additional HTTP headers for the API request (optional)
|
|
49
|
-
* - body: The request body data for the custom model API (optional)
|
|
50
|
-
*/
|
|
51
|
-
config: CustomCopilotModelConfig;
|
|
52
|
-
/**
|
|
53
|
-
* A function to transform the response from the custom model.
|
|
54
|
-
* This function takes the raw response from the custom model API
|
|
55
|
-
* and returns the model generated text or null.
|
|
56
|
-
*
|
|
57
|
-
* @param response - The raw response from the custom model API.
|
|
58
|
-
* The type is 'unknown' because different APIs
|
|
59
|
-
* may return responses in different formats.
|
|
60
|
-
* @returns The model generated text or null if no valid text could be extracted.
|
|
61
|
-
*/
|
|
62
|
-
transformResponse: CustomCopilotModelTransformResponse;
|
|
63
|
-
};
|
|
64
|
-
type CustomCopilotModelConfig = (apiKey: string, prompt: {
|
|
40
|
+
interface PromptData {
|
|
65
41
|
system: string;
|
|
66
42
|
user: string;
|
|
67
|
-
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Function type for configuring a custom model.
|
|
46
|
+
*/
|
|
47
|
+
type CustomCopilotModelConfig = (apiKey: string, prompt: PromptData) => {
|
|
68
48
|
/**
|
|
69
49
|
* The URL endpoint for the custom model's API.
|
|
70
50
|
*/
|
|
@@ -79,6 +59,9 @@ type CustomCopilotModelConfig = (apiKey: string, prompt: {
|
|
|
79
59
|
*/
|
|
80
60
|
body?: Record<string, unknown>;
|
|
81
61
|
};
|
|
62
|
+
/**
|
|
63
|
+
* Function type for transforming the response from a custom model.
|
|
64
|
+
*/
|
|
82
65
|
type CustomCopilotModelTransformResponse = (response: unknown) => {
|
|
83
66
|
/**
|
|
84
67
|
* The text generated by the custom model.
|
|
@@ -89,6 +72,77 @@ type CustomCopilotModelTransformResponse = (response: unknown) => {
|
|
|
89
72
|
*/
|
|
90
73
|
completion?: string | null;
|
|
91
74
|
};
|
|
75
|
+
/**
|
|
76
|
+
* Definition of a custom Copilot model.
|
|
77
|
+
*/
|
|
78
|
+
interface CustomCopilotModel {
|
|
79
|
+
/**
|
|
80
|
+
* Function to configure the custom model.
|
|
81
|
+
*/
|
|
82
|
+
config: CustomCopilotModelConfig;
|
|
83
|
+
/**
|
|
84
|
+
* Function to transform the response from the custom model.
|
|
85
|
+
*/
|
|
86
|
+
transformResponse: CustomCopilotModelTransformResponse;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Configuration options for initializing a Copilot instance.
|
|
90
|
+
* The `model` property is type-safe and varies based on the specified `provider`.
|
|
91
|
+
*/
|
|
92
|
+
type CopilotOptions = {
|
|
93
|
+
/**
|
|
94
|
+
* Specifies the provider for the Copilot instance.
|
|
95
|
+
* Supported providers include 'openai', 'anthropic', 'groq', and 'google'.
|
|
96
|
+
*/
|
|
97
|
+
provider: 'openai';
|
|
98
|
+
/**
|
|
99
|
+
* Defines the model to be used for Copilot LLM (Language Model) requests.
|
|
100
|
+
* This must be a model from the 'openai' provider.
|
|
101
|
+
*/
|
|
102
|
+
model?: OpenAIModel;
|
|
103
|
+
} | {
|
|
104
|
+
/**
|
|
105
|
+
* Specifies the 'groq' provider for the Copilot instance.
|
|
106
|
+
*/
|
|
107
|
+
provider: 'groq';
|
|
108
|
+
/**
|
|
109
|
+
* Defines the model to be used for Copilot LLM requests.
|
|
110
|
+
* This must be a model from the 'groq' provider.
|
|
111
|
+
*/
|
|
112
|
+
model?: GroqModel;
|
|
113
|
+
} | {
|
|
114
|
+
/**
|
|
115
|
+
* Specifies the 'anthropic' provider for the Copilot instance.
|
|
116
|
+
*/
|
|
117
|
+
provider: 'anthropic';
|
|
118
|
+
/**
|
|
119
|
+
* Defines the model to be used for Copilot LLM requests.
|
|
120
|
+
* This must be a model from the 'anthropic' provider.
|
|
121
|
+
*/
|
|
122
|
+
model?: AnthropicModel;
|
|
123
|
+
} | {
|
|
124
|
+
/**
|
|
125
|
+
* Specifies the 'google' provider for the Copilot instance.
|
|
126
|
+
*/
|
|
127
|
+
provider: 'google';
|
|
128
|
+
/**
|
|
129
|
+
* Defines the model to be used for Copilot LLM requests.
|
|
130
|
+
* This must be a model from the 'google' provider.
|
|
131
|
+
*/
|
|
132
|
+
model?: GoogleModel;
|
|
133
|
+
} | {
|
|
134
|
+
/**
|
|
135
|
+
* When no provider is specified, only custom models are allowed.
|
|
136
|
+
*/
|
|
137
|
+
provider?: undefined;
|
|
138
|
+
/**
|
|
139
|
+
* Defines the model to be used for Copilot LLM requests.
|
|
140
|
+
* Must be a custom model when no provider is specified.
|
|
141
|
+
* For more information, refer to the documentation:
|
|
142
|
+
* @see https://github.com/arshad-yaseen/monacopilot?tab=readme-ov-file#custom-model
|
|
143
|
+
*/
|
|
144
|
+
model?: CustomCopilotModel;
|
|
145
|
+
};
|
|
92
146
|
|
|
93
147
|
type Monaco = typeof monaco;
|
|
94
148
|
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
package/build/index.d.ts
CHANGED
|
@@ -4,67 +4,47 @@ import { ChatCompletion } from 'openai/resources/chat/completions';
|
|
|
4
4
|
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
5
5
|
import * as monaco_editor from 'monaco-editor';
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Models available for OpenAI provider.
|
|
9
|
+
*/
|
|
10
|
+
type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-mini';
|
|
11
|
+
/**
|
|
12
|
+
* Models available for Groq provider.
|
|
13
|
+
*/
|
|
8
14
|
type GroqModel = 'llama-3-70b';
|
|
15
|
+
/**
|
|
16
|
+
* Models available for Anthropic provider.
|
|
17
|
+
*/
|
|
9
18
|
type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-5-haiku' | 'claude-3-haiku';
|
|
10
|
-
|
|
11
|
-
|
|
19
|
+
/**
|
|
20
|
+
* Models available for Google provider.
|
|
21
|
+
*/
|
|
22
|
+
type GoogleModel = 'gemini-1.5-flash' | 'gemini-1.5-flash-8b' | 'gemini-1.5-pro';
|
|
23
|
+
/**
|
|
24
|
+
* Union of all predefined Copilot models.
|
|
25
|
+
*/
|
|
26
|
+
type CopilotModel = OpenAIModel | GroqModel | AnthropicModel | GoogleModel;
|
|
27
|
+
/**
|
|
28
|
+
* Providers supported by Copilot.
|
|
29
|
+
*/
|
|
30
|
+
type CopilotProvider = 'openai' | 'groq' | 'anthropic' | 'google';
|
|
31
|
+
/**
|
|
32
|
+
* Specific ChatCompletion types for each provider.
|
|
33
|
+
*/
|
|
12
34
|
type OpenAIChatCompletion = ChatCompletion;
|
|
13
35
|
type GroqChatCompletion = ChatCompletion$1;
|
|
14
36
|
type AnthropicChatCompletion = Message;
|
|
15
|
-
type PromptData = {
|
|
16
|
-
system: string;
|
|
17
|
-
user: string;
|
|
18
|
-
};
|
|
19
37
|
/**
|
|
20
|
-
*
|
|
38
|
+
* Data structure representing the prompt data.
|
|
21
39
|
*/
|
|
22
|
-
interface
|
|
23
|
-
/**
|
|
24
|
-
* The provider to use (e.g., 'openai', 'anthropic', 'groq').
|
|
25
|
-
* If not specified, a default provider will be used.
|
|
26
|
-
*/
|
|
27
|
-
provider?: CopilotProvider;
|
|
28
|
-
/**
|
|
29
|
-
* The model to use for copilot LLM requests.
|
|
30
|
-
* This can be either:
|
|
31
|
-
* 1. A predefined model name (e.g. 'claude-3-5-haiku'): Use this option if you want to use a model that is built into Monacopilot.
|
|
32
|
-
* If you choose this option, also set the `provider` property to the corresponding provider of the model.
|
|
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.
|
|
34
|
-
*
|
|
35
|
-
* If not specified, a default model will be used.
|
|
36
|
-
*/
|
|
37
|
-
model?: CopilotModel | CustomCopilotModel;
|
|
38
|
-
}
|
|
39
|
-
type CustomCopilotModel = {
|
|
40
|
-
/**
|
|
41
|
-
* A function to configure the custom model.
|
|
42
|
-
* This function takes the API key and the prompt data and returns the configuration for the custom model.
|
|
43
|
-
*
|
|
44
|
-
* @param {string} apiKey - The API key for authentication.
|
|
45
|
-
* @param {Object} prompt - An object containing 'system' and 'user' messages generated by Monacopilot.
|
|
46
|
-
* @returns {Object} An object that may include:
|
|
47
|
-
* - endpoint: The URL for the custom model's API (required)
|
|
48
|
-
* - headers: Additional HTTP headers for the API request (optional)
|
|
49
|
-
* - body: The request body data for the custom model API (optional)
|
|
50
|
-
*/
|
|
51
|
-
config: CustomCopilotModelConfig;
|
|
52
|
-
/**
|
|
53
|
-
* A function to transform the response from the custom model.
|
|
54
|
-
* This function takes the raw response from the custom model API
|
|
55
|
-
* and returns the model generated text or null.
|
|
56
|
-
*
|
|
57
|
-
* @param response - The raw response from the custom model API.
|
|
58
|
-
* The type is 'unknown' because different APIs
|
|
59
|
-
* may return responses in different formats.
|
|
60
|
-
* @returns The model generated text or null if no valid text could be extracted.
|
|
61
|
-
*/
|
|
62
|
-
transformResponse: CustomCopilotModelTransformResponse;
|
|
63
|
-
};
|
|
64
|
-
type CustomCopilotModelConfig = (apiKey: string, prompt: {
|
|
40
|
+
interface PromptData {
|
|
65
41
|
system: string;
|
|
66
42
|
user: string;
|
|
67
|
-
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Function type for configuring a custom model.
|
|
46
|
+
*/
|
|
47
|
+
type CustomCopilotModelConfig = (apiKey: string, prompt: PromptData) => {
|
|
68
48
|
/**
|
|
69
49
|
* The URL endpoint for the custom model's API.
|
|
70
50
|
*/
|
|
@@ -79,6 +59,9 @@ type CustomCopilotModelConfig = (apiKey: string, prompt: {
|
|
|
79
59
|
*/
|
|
80
60
|
body?: Record<string, unknown>;
|
|
81
61
|
};
|
|
62
|
+
/**
|
|
63
|
+
* Function type for transforming the response from a custom model.
|
|
64
|
+
*/
|
|
82
65
|
type CustomCopilotModelTransformResponse = (response: unknown) => {
|
|
83
66
|
/**
|
|
84
67
|
* The text generated by the custom model.
|
|
@@ -89,6 +72,77 @@ type CustomCopilotModelTransformResponse = (response: unknown) => {
|
|
|
89
72
|
*/
|
|
90
73
|
completion?: string | null;
|
|
91
74
|
};
|
|
75
|
+
/**
|
|
76
|
+
* Definition of a custom Copilot model.
|
|
77
|
+
*/
|
|
78
|
+
interface CustomCopilotModel {
|
|
79
|
+
/**
|
|
80
|
+
* Function to configure the custom model.
|
|
81
|
+
*/
|
|
82
|
+
config: CustomCopilotModelConfig;
|
|
83
|
+
/**
|
|
84
|
+
* Function to transform the response from the custom model.
|
|
85
|
+
*/
|
|
86
|
+
transformResponse: CustomCopilotModelTransformResponse;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Configuration options for initializing a Copilot instance.
|
|
90
|
+
* The `model` property is type-safe and varies based on the specified `provider`.
|
|
91
|
+
*/
|
|
92
|
+
type CopilotOptions = {
|
|
93
|
+
/**
|
|
94
|
+
* Specifies the provider for the Copilot instance.
|
|
95
|
+
* Supported providers include 'openai', 'anthropic', 'groq', and 'google'.
|
|
96
|
+
*/
|
|
97
|
+
provider: 'openai';
|
|
98
|
+
/**
|
|
99
|
+
* Defines the model to be used for Copilot LLM (Language Model) requests.
|
|
100
|
+
* This must be a model from the 'openai' provider.
|
|
101
|
+
*/
|
|
102
|
+
model?: OpenAIModel;
|
|
103
|
+
} | {
|
|
104
|
+
/**
|
|
105
|
+
* Specifies the 'groq' provider for the Copilot instance.
|
|
106
|
+
*/
|
|
107
|
+
provider: 'groq';
|
|
108
|
+
/**
|
|
109
|
+
* Defines the model to be used for Copilot LLM requests.
|
|
110
|
+
* This must be a model from the 'groq' provider.
|
|
111
|
+
*/
|
|
112
|
+
model?: GroqModel;
|
|
113
|
+
} | {
|
|
114
|
+
/**
|
|
115
|
+
* Specifies the 'anthropic' provider for the Copilot instance.
|
|
116
|
+
*/
|
|
117
|
+
provider: 'anthropic';
|
|
118
|
+
/**
|
|
119
|
+
* Defines the model to be used for Copilot LLM requests.
|
|
120
|
+
* This must be a model from the 'anthropic' provider.
|
|
121
|
+
*/
|
|
122
|
+
model?: AnthropicModel;
|
|
123
|
+
} | {
|
|
124
|
+
/**
|
|
125
|
+
* Specifies the 'google' provider for the Copilot instance.
|
|
126
|
+
*/
|
|
127
|
+
provider: 'google';
|
|
128
|
+
/**
|
|
129
|
+
* Defines the model to be used for Copilot LLM requests.
|
|
130
|
+
* This must be a model from the 'google' provider.
|
|
131
|
+
*/
|
|
132
|
+
model?: GoogleModel;
|
|
133
|
+
} | {
|
|
134
|
+
/**
|
|
135
|
+
* When no provider is specified, only custom models are allowed.
|
|
136
|
+
*/
|
|
137
|
+
provider?: undefined;
|
|
138
|
+
/**
|
|
139
|
+
* Defines the model to be used for Copilot LLM requests.
|
|
140
|
+
* Must be a custom model when no provider is specified.
|
|
141
|
+
* For more information, refer to the documentation:
|
|
142
|
+
* @see https://github.com/arshad-yaseen/monacopilot?tab=readme-ov-file#custom-model
|
|
143
|
+
*/
|
|
144
|
+
model?: CustomCopilotModel;
|
|
145
|
+
};
|
|
92
146
|
|
|
93
147
|
type Monaco = typeof monaco;
|
|
94
148
|
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
package/build/index.js
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
`),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var U=["groq","openai","anthropic","google"],J={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3-5-sonnet":"claude-3-5-sonnet-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"},K={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"]},Z="anthropic",Q="claude-3-5-haiku",O={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"},M=.1;var ee={"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-haiku":4096};var fe={createEndpoint:()=>O.openai,createRequestBody:(t,e)=>{let o=t==="o1-mini";return {model:A(t),...!o&&{temperature:M},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},Pe={createEndpoint:()=>O.groq,createRequestBody:(t,e)=>({model:A(t),temperature:M,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},ye={createEndpoint:()=>O.anthropic,createRequestBody:(t,e)=>({model:A(t),temperature:M,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:ee[t]}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>{if(!t.content||!Array.isArray(t.content)||!t.content.length)return null;let e=t.content[0];return !e||typeof e!="object"?null:"text"in e&&typeof e.text=="string"?e.text:null}},xe={createEndpoint:(t,e)=>`${O.google}/${t}:generateContent?key=${e}`,createRequestBody:(t,e)=>({model:A(t),system_instruction:{parts:{text:e.system}},contents:[{parts:{text:e.user}}]}),createHeaders:()=>({"Content-Type":"application/json"}),parseCompletion:t=>{if(!t.candidates?.length||!t.candidates[0]?.content||!t.candidates[0].content?.parts?.length)return null;let e=t.candidates[0].content;return "text"in e.parts[0]&&typeof e.parts[0].text=="string"?e.parts[0].text:null}},I={openai:fe,groq:Pe,anthropic:ye,google:xe},te=(t,e,o)=>I[o].createEndpoint(t,e),oe=(t,e,o)=>I[e].createRequestBody(t,o),re=(t,e)=>I[e].createHeaders(t),ne=(t,e)=>I[e].parseCompletion(t),A=t=>J[t];var Re="\x1B[91m",ie="\x1B[93m",W="\x1B[0m",z="\x1B[1m",y=t=>{let e;t instanceof Error?e=t.message:typeof t=="string"?e=t:e="An unknown error occurred";let o=`${Re}${z}[MONACOPILOT ERROR] ${e}${W}`;return console.error(o),{message:e}},se=t=>{console.warn(`${ie}${z}[MONACOPILOT WARN] ${t}${W}`);};var L=(t,e,o)=>console.warn(`${ie}${z}[MONACOPILOT DEPRECATED] "${t}" is deprecated${o?` in ${o}`:""}. Please use "${e}" instead. It will be removed in a future version.${W}`);var T=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`,Y=(t,e,o={})=>{if(e<=0)return "";let r=t.split(`
|
|
4
|
+
`),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(a=>a==="")?`
|
|
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
|
|
9
|
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
|
|
8
|
+
`)};var w=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],D=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),ae=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),h=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),S=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var le=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){let s=`
|
|
9
|
+
`+(JSON.stringify(await i.json(),null,2)||"");throw new Error(`${i.statusText||o.fallbackError||"Network error"}${s}`)}return i.json()},Oe=(t,e)=>le(t,"GET",e),Te=(t,e,o)=>le(t,"POST",{...o,body:e}),N={GET:Oe,POST:Te};var pe=(t,e)=>{let o=D(t,e).trim(),r=ae(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var F=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((s,a)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=a,o=setTimeout(()=>{s(t(...i)),r=null;},e);});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null);},n};var ve=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:n}=t,i=T([n,...e].filter(a=>typeof a=="string"&&!!a));return [`You are an expert ${i?`${i} `:""}developer assistant specialized in precise code completion.`,`Your primary task is to provide accurate, context-aware code completions that seamlessly integrate with existing codebases${o?` in '${o}'`:""}.`,`You must:
|
|
10
|
+
- Generate only the exact code required.
|
|
11
|
+
- Maintain strict adherence to provided instructions.
|
|
12
|
+
- Follow established code patterns and conventions.
|
|
13
|
+
- Consider the full context before generating code.`,r?.length?"Analyze and incorporate context from all provided related files to ensure consistent and appropriate code completion.":"",n?`Apply ${n}-specific best practices, idioms, and syntax conventions in all generated code.`:""].filter(Boolean).join(`
|
|
14
|
+
|
|
15
|
+
`)},Ee=t=>t?.length?t.map(({path:e,content:o})=>`
|
|
14
16
|
<related_file>
|
|
15
17
|
<path>${e}</path>
|
|
16
18
|
<content_context>
|
|
@@ -20,118 +22,35 @@ ${o}
|
|
|
20
22
|
</content_context>
|
|
21
23
|
</related_file>`.trim()).join(`
|
|
22
24
|
|
|
23
|
-
`):"",
|
|
25
|
+
`):"",be=(t="",e)=>{let{relatedFiles:o}=e;return `
|
|
24
26
|
<task_context>
|
|
25
27
|
<primary_instructions>
|
|
26
28
|
${t.trim()}
|
|
27
|
-
</primary_instructions
|
|
28
|
-
${o?.length?`
|
|
29
|
+
</primary_instructions>${o?.length?`
|
|
29
30
|
<reference_files>
|
|
30
|
-
${
|
|
31
|
+
${Ee(o)}
|
|
31
32
|
</reference_files>`:""}
|
|
32
|
-
</task_context>`.trim()},
|
|
33
|
-
${
|
|
34
|
-
</code_file>`,l=`
|
|
35
|
-
<instructions>
|
|
36
|
-
<context>
|
|
37
|
-
Below is a ${n||"code"} file with the token '${ue}' marking the exact cursor position where code completion is needed.
|
|
38
|
-
|
|
39
|
-
${i}
|
|
40
|
-
</context>
|
|
41
|
-
|
|
42
|
-
<critical_rules>
|
|
43
|
-
1. NEVER REPEAT ANY TEXT THAT APPEARS BEFORE THE CURSOR
|
|
44
|
-
2. Start your completion EXACTLY from the cursor position
|
|
45
|
-
3. If user types 'const ' and cursor is after it, DO NOT include 'const ' in your completion
|
|
46
|
-
4. ONLY provide the remaining part of the code that should appear after the cursor
|
|
47
|
-
5. Violation of these rules will cause code duplication and syntax errors
|
|
48
|
-
</critical_rules>
|
|
49
|
-
|
|
50
|
-
<primary_objectives>
|
|
51
|
-
1. Generate code that is syntactically correct and follows ${n||"the language"}'s best practices
|
|
52
|
-
2. Ensure seamless integration with existing code structure
|
|
53
|
-
3. Maintain consistent naming conventions and coding style
|
|
54
|
-
4. Provide only the exact code needed at the cursor position
|
|
55
|
-
</primary_objectives>
|
|
56
|
-
|
|
57
|
-
<strict_requirements>
|
|
58
|
-
- Output MUST contain only the NEW code to be inserted at cursor position
|
|
59
|
-
- NEVER repeat any code that appears before the cursor position
|
|
60
|
-
- DO NOT include any code that appears before the cursor
|
|
61
|
-
- DO NOT include explanatory comments or documentation
|
|
62
|
-
- DO NOT wrap output in markdown code blocks
|
|
63
|
-
- DO NOT include placeholder text or TODO comments
|
|
64
|
-
- AVOID generating code beyond the immediate logical completion
|
|
65
|
-
</strict_requirements>
|
|
66
|
-
|
|
67
|
-
<completion_mode>
|
|
68
|
-
Active Mode: ${r}
|
|
69
|
-
Specific Instructions: ${{continue:"-- Analyze the code structure and continue writing from the cursor position, maintaining logical flow.",insert:"-- Insert a precise, contextually appropriate code snippet at the cursor position while preserving surrounding code integrity.",complete:"-- Complete the current statement or block with syntactically correct and logically coherent code."}[r]||""}
|
|
70
|
-
</completion_mode>
|
|
33
|
+
</task_context>`.trim()},ce=(t,e)=>({system:ve(e),user:be(t,e)});var Me=({textBeforeCursor:t="",textAfterCursor:e="",editorState:{completionMode:o},language:r,...n})=>{let i=`
|
|
34
|
+
Given the ${r||"code"} context:
|
|
71
35
|
|
|
72
|
-
|
|
73
|
-
1. Analyze the code context before and after the cursor
|
|
74
|
-
2. Identify the current scope and available variables/functions
|
|
75
|
-
3. Determine the logical flow and required completion
|
|
76
|
-
4. Remove any duplicate text that appears before cursor
|
|
77
|
-
5. Verify completion starts exactly at cursor position
|
|
78
|
-
</code_analysis_steps>
|
|
36
|
+
${t}<cursor>${e}
|
|
79
37
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
38
|
+
CRITICAL RULES:
|
|
39
|
+
1. NEVER repeat text before <cursor>
|
|
40
|
+
2. Start EXACTLY at cursor position
|
|
41
|
+
3. Output ONLY new code
|
|
42
|
+
4. No explanations/comments
|
|
43
|
+
5. Do not add unnecessary quotes or backticks around code
|
|
44
|
+
6. Follow ${o} mode: ${o==="continue"?"continue writing":o==="insert"?"insert exactly missing code between":"complete block"}
|
|
45
|
+
7. Respect Monaco editor subwordSmart inline suggest mode (MANDATORY)
|
|
86
46
|
|
|
87
|
-
|
|
88
|
-
Context: "function hello<cursor>"
|
|
89
|
-
CORRECT COMPLETION: "(name: string) {\\n return 'Hello ' + name;\\n}"
|
|
90
|
-
INCORRECT COMPLETION: "function hello(name: string) {\\n return 'Hello ' + name;\\n}"
|
|
91
|
-
</example>
|
|
92
|
-
|
|
93
|
-
<example>
|
|
94
|
-
Context: "const randomNumber = Math.floor(Math.ran<cursor>00);"
|
|
95
|
-
CORRECT COMPLETION: "dom() * 1"
|
|
96
|
-
INCORRECT COMPLETION: "Math.random() * 1"
|
|
97
|
-
</example>
|
|
98
|
-
|
|
99
|
-
<example>
|
|
100
|
-
Context: "const result = 'Hello' + ' W<cursor>';"
|
|
101
|
-
CORRECT COMPLETION: "orld"
|
|
102
|
-
INCORRECT COMPLETION: "orld';"
|
|
103
|
-
</example>
|
|
104
|
-
|
|
105
|
-
<example>
|
|
106
|
-
Context: "function isPalindrome(<cursor>)"
|
|
107
|
-
CORRECT COMPLETION: "str) {
|
|
108
|
-
return str === str.split('').reverse().join('');
|
|
109
|
-
}"
|
|
110
|
-
INCORRECT COMPLETION: "(str) {
|
|
111
|
-
return str === str.split('').reverse().join('');
|
|
112
|
-
}"
|
|
113
|
-
</example>
|
|
114
|
-
</examples>
|
|
115
|
-
|
|
116
|
-
<error_prevention>
|
|
117
|
-
- Verify that generated code doesn't introduce syntax errors
|
|
118
|
-
- Ensure variable and function references are valid in the current scope
|
|
119
|
-
- Check for proper bracket and parenthesis matching
|
|
120
|
-
- Maintain consistent indentation with surrounding code
|
|
121
|
-
- Respect language-specific type safety requirements
|
|
122
|
-
- NEVER duplicate text that appears before cursor
|
|
123
|
-
</error_prevention>
|
|
124
|
-
|
|
125
|
-
<final_validation>
|
|
126
|
-
Before providing the completion:
|
|
127
|
-
1. Confirm the output contains ONLY the new code after cursor position
|
|
128
|
-
2. Double-check no text before cursor is duplicated
|
|
129
|
-
3. Verify it fits seamlessly at the cursor position
|
|
130
|
-
4. Ensure it follows the active completion mode requirements
|
|
131
|
-
5. Check for consistency with existing code style
|
|
132
|
-
</final_validation>
|
|
133
|
-
</instructions>`.trim();return me(l,t)},Ce=Be;var _=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??J,this.model=o.model??Z,this.validateInputs()}validateInputs(){if(!H.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${M(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: ${M(V[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},l=this.generatePrompt(n,s),{endpoint:d,requestBody:p,headers:u}=this.prepareRequestDetails(l);try{let m=await this.sendCompletionRequest(d,p,{...u,...i});return this.processCompletionResponse(m)}catch(m){return this.handleCompletionError(m)}}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 N.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&&A("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:R(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,n;for(;(n=o.exec(e))!==null;){let i=n[0],s=i.split(`
|
|
47
|
+
Analyze context, maintain style, ensure syntax correctness. Provide ONLY the completion code without any explanations or comments.`.trim();return ce(i,{textBeforeCursor:t,textAfterCursor:e,editorState:{completionMode:o},language:r,...n})},de=Me;var G=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??Q,this.validateInputs();}validateInputs(){if(!U.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${T(U)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!K[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${T(K[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},a=this.generatePrompt(n,s),{endpoint:l,requestBody:m,headers:c}=this.prepareRequestDetails(a);try{let d=await this.sendCompletionRequest(l,m,{...c,...i});return this.processCompletionResponse(d)}catch(d){return this.handleCompletionError(d)}}generatePrompt(e,o){let r=de(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=te(this.model,this.apiKey,this.provider),r,n=re(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=oe(this.model,this.provider,e);return {endpoint:o,requestBody:r,headers:n}}async sendCompletionRequest(e,o,r){return N.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&&L("completion","text","Copilot.options.model.transformResponse"),{completion:o.text??o.completion??null,raw:e}}else return {completion:ne(e,this.provider),raw:e}}handleCompletionError(e){return {error:y(e).message,completion:null}}};var _=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(`
|
|
134
48
|
`).slice(1,-1).join(`
|
|
135
|
-
`);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
49
|
+
`);r=r.replace(i,s);}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
50
|
+
|
|
51
|
+
`),this}build(){return this.formattedCompletion}};var B=class{constructor(e,o){this.cursorPos=e,this.mdl=o;}shouldProvideCompletions(){return !pe(this.cursorPos,this.mdl)}};var q=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 g=class g{constructor(){this.cache=new q(g.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 h(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:a,endLineNumber:l,endColumn:m}=n,{lineNumber:c,column:d}=o,p=c===s&&d===a;if(s===l)return p||i.startsWith(r)&&c===s&&d>=a-g.LOOK_AROUND&&d<=m+g.LOOK_AROUND;let u=i.startsWith(r)&&c>=s&&c<=l&&(c===s&&d>=a-g.LOOK_AROUND||c===l&&d<=m+g.LOOK_AROUND||c>s&&c<l);return p||u}};g.MAX_CACHE_SIZE=10,g.LOOK_AROUND=10;var k=g;var $=class{constructor(e){this.monaco=e;}computeInsertionRange(e,o,r){if(!o)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let n=w(e,r),i=o[0];if(!n||i===n)return this.calculateRangeWithoutOverlap(e,o);let s=r.getOffsetAt(e),a=h(e,r),l=S(e,r);if(s>=r.getValue().length||!l.length)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let m=this.getSuffixOverlapLength(o,a),c=this.computeMaxOverlapLength(o,l),d=m>0?r.getPositionAt(s-m):e,p=s+c,u=r.getPositionAt(p);return new this.monaco.Range(d.lineNumber,d.column,u.lineNumber,u.column)}calculateRangeWithoutOverlap(e,o){let r=e.lineNumber,n=e.column,i=o.split(`
|
|
52
|
+
`),s=i.length-1,a=r+s,l=s===0?n+i[0].length:i[s].length+1;return new this.monaco.Range(r,n,a,l)}computeMaxOverlapLength(e,o){let r=this.getPrefixOverlapLength(e,o),n=this.getSuffixPrefixOverlapLength(e,o),i=Math.max(r,n);return i===0&&(i=this.getInternalOverlapLength(e,o)),i}getSuffixOverlapLength(e,o){let r=Math.min(e.length,o.length),n=0;for(let i=1;i<=r;i++)e.substring(0,i)===o.slice(-i)&&(n=i);return n}getPrefixOverlapLength(e,o){let r=Math.min(e.length,o.length);for(let n=0;n<r;n++)if(e[n]!==o[n])return n;return r}getSuffixPrefixOverlapLength(e,o){let r=Math.min(e.length,o.length);for(let n=r;n>0;n--)if(e.slice(-n)===o.slice(0,n))return n;return 0}getInternalOverlapLength(e,o){for(let r=1;r<e.length;r++)if(o.startsWith(e.substring(r)))return e.length-r;return 0}};var Ie="application/json",me=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:n}=await N.POST(e,o,{headers:{"Content-Type":Ie},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return {completion:r}},ue=({pos:t,mdl:e,options:o})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:a}=o,l=Ae(t,e),c=!!s?.length?3:2,d=a?Math.floor(a/c):void 0,p=(P,C,V)=>{let b=P(t,e);return C?Y(b,C,V):b},u=(P,C)=>!P||!C?P:P.map(({content:V,...b})=>({...b,content:Y(V,C)})),j=p(h,d,{from:"end"}),E=p(S,d),R=u(s,d);return {filename:r,language:n,technologies:i,relatedFiles:R,textBeforeCursor:j,textAfterCursor:E,cursorPosition:t,editorState:{completionMode:l}}},Ae=(t,e)=>{let o=w(t,e),r=D(t,e);return o?"insert":r.trim()?"complete":"continue"};var ge=t=>_.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),f=t=>({items:t,enableForwardStability:!0,suppressSuggestions:!0});var X={onTyping:300,onIdle:600,onDemand:0},we=t=>({onTyping:F(t,X.onTyping),onIdle:F(t,X.onIdle),onDemand:F(t,X.onDemand)}),H=new k,De=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{let{trigger:a="onIdle",endpoint:l,enableCaching:m=!0,onError:c,requestHandler:d}=s;if(!new B(o,e).shouldProvideCompletions())return f([]);if(m){let p=H.get(o,e).map(u=>({insertText:u.completion,range:u.range}));if(p.length>0)return i(),f(p)}if(r.isCancellationRequested||n)return f([]);try{let u=we(d??me)[a];r.onCancellationRequested(()=>{u.cancel();});let j=ue({pos:o,mdl:e,options:s}),{completion:E}=await u({endpoint:l,body:{completionMetadata:j}});if(E){let R=ge(E),C=new $(t).computeInsertionRange(o,R,e);return m&&H.add({completion:R,range:C,textBeforeCursor:h(o,e)}),i(),f([{insertText:R,range:C}])}}catch(p){if(Se(p))return f([]);c?c(p):y(p);}return f([])},Se=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,Ce=De;var x=new WeakMap,v=null,he=(t,e,o)=>{v&&v.deregister();let r=[],n={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};x.set(e,n),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let i=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(l,m,c,d)=>{let p=x.get(e);if(!(!p||o.trigger==="onDemand"&&!p.isManualTrigger))return Ce({monaco:t,mdl:l,pos:m,token:d,isCompletionAccepted:p.isCompletionAccepted,onShowCompletion:()=>{p.isCompletionVisible=!0,p.isManualTrigger=!1;},options:o})},freeInlineCompletions:()=>{}});r.push(i);let s=e.onKeyDown(l=>{let m=x.get(e);if(!m)return;let c=l.keyCode===t.KeyCode.Tab||l.keyCode===t.KeyCode.RightArrow&&l.metaKey;m.isCompletionVisible&&c?(m.isCompletionAccepted=!0,m.isCompletionVisible=!1):m.isCompletionAccepted=!1;});r.push(s);let a={deregister:()=>{r.forEach(l=>l.dispose()),H.clear(),x.delete(e),v=null;},trigger:()=>Ne(e)};return v=a,a}catch(i){return o.onError?o.onError(i):y(i),{deregister:()=>{r.forEach(s=>s.dispose()),x.delete(e),v=null;},trigger:()=>{}}}},Ne=t=>{let e=x.get(t);if(!e){se("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isManualTrigger=!0,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{});},Fe=(...t)=>(L("registerCopilot","registerCompletion"),he(...t));
|
|
136
53
|
|
|
137
|
-
|
|
54
|
+
exports.Copilot = G;
|
|
55
|
+
exports.registerCompletion = he;
|
|
56
|
+
exports.registerCopilot = Fe;
|
package/build/index.mjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var
|
|
2
|
-
|
|
3
|
-
${o}`:r),{message:e,stack:o}},ie=t=>{console.warn(`${ne}${j}[MONACOPILOT WARN] ${t}${I}`)};var A=(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.${I}`);var L=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((s,l)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=l,o=setTimeout(()=>{s(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},M=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),T=(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
|
-
`),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(l=>l==="")?`
|
|
1
|
+
var U=["groq","openai","anthropic","google"],J={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3-5-sonnet":"claude-3-5-sonnet-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"},K={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"]},Z="anthropic",Q="claude-3-5-haiku",O={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"},M=.1;var ee={"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-haiku":4096};var fe={createEndpoint:()=>O.openai,createRequestBody:(t,e)=>{let o=t==="o1-mini";return {model:A(t),...!o&&{temperature:M},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},Pe={createEndpoint:()=>O.groq,createRequestBody:(t,e)=>({model:A(t),temperature:M,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},ye={createEndpoint:()=>O.anthropic,createRequestBody:(t,e)=>({model:A(t),temperature:M,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:ee[t]}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>{if(!t.content||!Array.isArray(t.content)||!t.content.length)return null;let e=t.content[0];return !e||typeof e!="object"?null:"text"in e&&typeof e.text=="string"?e.text:null}},xe={createEndpoint:(t,e)=>`${O.google}/${t}:generateContent?key=${e}`,createRequestBody:(t,e)=>({model:A(t),system_instruction:{parts:{text:e.system}},contents:[{parts:{text:e.user}}]}),createHeaders:()=>({"Content-Type":"application/json"}),parseCompletion:t=>{if(!t.candidates?.length||!t.candidates[0]?.content||!t.candidates[0].content?.parts?.length)return null;let e=t.candidates[0].content;return "text"in e.parts[0]&&typeof e.parts[0].text=="string"?e.parts[0].text:null}},I={openai:fe,groq:Pe,anthropic:ye,google:xe},te=(t,e,o)=>I[o].createEndpoint(t,e),oe=(t,e,o)=>I[e].createRequestBody(t,o),re=(t,e)=>I[e].createHeaders(t),ne=(t,e)=>I[e].parseCompletion(t),A=t=>J[t];var Re="\x1B[91m",ie="\x1B[93m",W="\x1B[0m",z="\x1B[1m",y=t=>{let e;t instanceof Error?e=t.message:typeof t=="string"?e=t:e="An unknown error occurred";let o=`${Re}${z}[MONACOPILOT ERROR] ${e}${W}`;return console.error(o),{message:e}},se=t=>{console.warn(`${ie}${z}[MONACOPILOT WARN] ${t}${W}`);};var L=(t,e,o)=>console.warn(`${ie}${z}[MONACOPILOT DEPRECATED] "${t}" is deprecated${o?` in ${o}`:""}. Please use "${e}" instead. It will be removed in a future version.${W}`);var T=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`,Y=(t,e,o={})=>{if(e<=0)return "";let r=t.split(`
|
|
2
|
+
`),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(a=>a==="")?`
|
|
5
3
|
`.repeat(e):s.join(`
|
|
6
4
|
`)}let i=r.slice(0,e);return i.every(s=>s==="")?`
|
|
7
5
|
`.repeat(e):i.join(`
|
|
8
|
-
`)};var
|
|
9
|
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
|
|
6
|
+
`)};var w=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],D=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),ae=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),h=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),S=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var le=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){let s=`
|
|
7
|
+
`+(JSON.stringify(await i.json(),null,2)||"");throw new Error(`${i.statusText||o.fallbackError||"Network error"}${s}`)}return i.json()},Oe=(t,e)=>le(t,"GET",e),Te=(t,e,o)=>le(t,"POST",{...o,body:e}),N={GET:Oe,POST:Te};var pe=(t,e)=>{let o=D(t,e).trim(),r=ae(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var F=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((s,a)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=a,o=setTimeout(()=>{s(t(...i)),r=null;},e);});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null);},n};var ve=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:n}=t,i=T([n,...e].filter(a=>typeof a=="string"&&!!a));return [`You are an expert ${i?`${i} `:""}developer assistant specialized in precise code completion.`,`Your primary task is to provide accurate, context-aware code completions that seamlessly integrate with existing codebases${o?` in '${o}'`:""}.`,`You must:
|
|
8
|
+
- Generate only the exact code required.
|
|
9
|
+
- Maintain strict adherence to provided instructions.
|
|
10
|
+
- Follow established code patterns and conventions.
|
|
11
|
+
- Consider the full context before generating code.`,r?.length?"Analyze and incorporate context from all provided related files to ensure consistent and appropriate code completion.":"",n?`Apply ${n}-specific best practices, idioms, and syntax conventions in all generated code.`:""].filter(Boolean).join(`
|
|
12
|
+
|
|
13
|
+
`)},Ee=t=>t?.length?t.map(({path:e,content:o})=>`
|
|
14
14
|
<related_file>
|
|
15
15
|
<path>${e}</path>
|
|
16
16
|
<content_context>
|
|
@@ -20,118 +20,33 @@ ${o}
|
|
|
20
20
|
</content_context>
|
|
21
21
|
</related_file>`.trim()).join(`
|
|
22
22
|
|
|
23
|
-
`):"",
|
|
23
|
+
`):"",be=(t="",e)=>{let{relatedFiles:o}=e;return `
|
|
24
24
|
<task_context>
|
|
25
25
|
<primary_instructions>
|
|
26
26
|
${t.trim()}
|
|
27
|
-
</primary_instructions
|
|
28
|
-
${o?.length?`
|
|
27
|
+
</primary_instructions>${o?.length?`
|
|
29
28
|
<reference_files>
|
|
30
|
-
${
|
|
29
|
+
${Ee(o)}
|
|
31
30
|
</reference_files>`:""}
|
|
32
|
-
</task_context>`.trim()},ce=(t,e)=>({system:
|
|
33
|
-
${
|
|
34
|
-
</code_file>`,l=`
|
|
35
|
-
<instructions>
|
|
36
|
-
<context>
|
|
37
|
-
Below is a ${n||"code"} file with the token '${de}' marking the exact cursor position where code completion is needed.
|
|
31
|
+
</task_context>`.trim()},ce=(t,e)=>({system:ve(e),user:be(t,e)});var Me=({textBeforeCursor:t="",textAfterCursor:e="",editorState:{completionMode:o},language:r,...n})=>{let i=`
|
|
32
|
+
Given the ${r||"code"} context:
|
|
38
33
|
|
|
39
|
-
|
|
40
|
-
</context>
|
|
34
|
+
${t}<cursor>${e}
|
|
41
35
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
36
|
+
CRITICAL RULES:
|
|
37
|
+
1. NEVER repeat text before <cursor>
|
|
38
|
+
2. Start EXACTLY at cursor position
|
|
39
|
+
3. Output ONLY new code
|
|
40
|
+
4. No explanations/comments
|
|
41
|
+
5. Do not add unnecessary quotes or backticks around code
|
|
42
|
+
6. Follow ${o} mode: ${o==="continue"?"continue writing":o==="insert"?"insert exactly missing code between":"complete block"}
|
|
43
|
+
7. Respect Monaco editor subwordSmart inline suggest mode (MANDATORY)
|
|
49
44
|
|
|
50
|
-
|
|
51
|
-
1. Generate code that is syntactically correct and follows ${n||"the language"}'s best practices
|
|
52
|
-
2. Ensure seamless integration with existing code structure
|
|
53
|
-
3. Maintain consistent naming conventions and coding style
|
|
54
|
-
4. Provide only the exact code needed at the cursor position
|
|
55
|
-
</primary_objectives>
|
|
56
|
-
|
|
57
|
-
<strict_requirements>
|
|
58
|
-
- Output MUST contain only the NEW code to be inserted at cursor position
|
|
59
|
-
- NEVER repeat any code that appears before the cursor position
|
|
60
|
-
- DO NOT include any code that appears before the cursor
|
|
61
|
-
- DO NOT include explanatory comments or documentation
|
|
62
|
-
- DO NOT wrap output in markdown code blocks
|
|
63
|
-
- DO NOT include placeholder text or TODO comments
|
|
64
|
-
- AVOID generating code beyond the immediate logical completion
|
|
65
|
-
</strict_requirements>
|
|
66
|
-
|
|
67
|
-
<completion_mode>
|
|
68
|
-
Active Mode: ${r}
|
|
69
|
-
Specific Instructions: ${{continue:"-- Analyze the code structure and continue writing from the cursor position, maintaining logical flow.",insert:"-- Insert a precise, contextually appropriate code snippet at the cursor position while preserving surrounding code integrity.",complete:"-- Complete the current statement or block with syntactically correct and logically coherent code."}[r]||""}
|
|
70
|
-
</completion_mode>
|
|
71
|
-
|
|
72
|
-
<code_analysis_steps>
|
|
73
|
-
1. Analyze the code context before and after the cursor
|
|
74
|
-
2. Identify the current scope and available variables/functions
|
|
75
|
-
3. Determine the logical flow and required completion
|
|
76
|
-
4. Remove any duplicate text that appears before cursor
|
|
77
|
-
5. Verify completion starts exactly at cursor position
|
|
78
|
-
</code_analysis_steps>
|
|
79
|
-
|
|
80
|
-
<examples>
|
|
81
|
-
<example>
|
|
82
|
-
Context: "const <cursor>"
|
|
83
|
-
CORRECT COMPLETION: "myVariable = 42"
|
|
84
|
-
INCORRECT COMPLETION: "const myVariable = 42"
|
|
85
|
-
</example>
|
|
86
|
-
|
|
87
|
-
<example>
|
|
88
|
-
Context: "function hello<cursor>"
|
|
89
|
-
CORRECT COMPLETION: "(name: string) {\\n return 'Hello ' + name;\\n}"
|
|
90
|
-
INCORRECT COMPLETION: "function hello(name: string) {\\n return 'Hello ' + name;\\n}"
|
|
91
|
-
</example>
|
|
92
|
-
|
|
93
|
-
<example>
|
|
94
|
-
Context: "const randomNumber = Math.floor(Math.ran<cursor>00);"
|
|
95
|
-
CORRECT COMPLETION: "dom() * 1"
|
|
96
|
-
INCORRECT COMPLETION: "Math.random() * 1"
|
|
97
|
-
</example>
|
|
98
|
-
|
|
99
|
-
<example>
|
|
100
|
-
Context: "const result = 'Hello' + ' W<cursor>';"
|
|
101
|
-
CORRECT COMPLETION: "orld"
|
|
102
|
-
INCORRECT COMPLETION: "orld';"
|
|
103
|
-
</example>
|
|
104
|
-
|
|
105
|
-
<example>
|
|
106
|
-
Context: "function isPalindrome(<cursor>)"
|
|
107
|
-
CORRECT COMPLETION: "str) {
|
|
108
|
-
return str === str.split('').reverse().join('');
|
|
109
|
-
}"
|
|
110
|
-
INCORRECT COMPLETION: "(str) {
|
|
111
|
-
return str === str.split('').reverse().join('');
|
|
112
|
-
}"
|
|
113
|
-
</example>
|
|
114
|
-
</examples>
|
|
115
|
-
|
|
116
|
-
<error_prevention>
|
|
117
|
-
- Verify that generated code doesn't introduce syntax errors
|
|
118
|
-
- Ensure variable and function references are valid in the current scope
|
|
119
|
-
- Check for proper bracket and parenthesis matching
|
|
120
|
-
- Maintain consistent indentation with surrounding code
|
|
121
|
-
- Respect language-specific type safety requirements
|
|
122
|
-
- NEVER duplicate text that appears before cursor
|
|
123
|
-
</error_prevention>
|
|
124
|
-
|
|
125
|
-
<final_validation>
|
|
126
|
-
Before providing the completion:
|
|
127
|
-
1. Confirm the output contains ONLY the new code after cursor position
|
|
128
|
-
2. Double-check no text before cursor is duplicated
|
|
129
|
-
3. Verify it fits seamlessly at the cursor position
|
|
130
|
-
4. Ensure it follows the active completion mode requirements
|
|
131
|
-
5. Check for consistency with existing code style
|
|
132
|
-
</final_validation>
|
|
133
|
-
</instructions>`.trim();return ce(l,t)},me=Ae;var z=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??G,this.model=o.model??X,this.validateInputs()}validateInputs(){if(!q.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${M(q)}. 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: ${M($[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},l=this.generatePrompt(n,s),{endpoint:d,requestBody:p,headers:u}=this.prepareRequestDetails(l);try{let m=await this.sendCompletionRequest(d,p,{...u,...i});return this.processCompletionResponse(m)}catch(m){return this.handleCompletionError(m)}}generatePrompt(e,o){let r=me(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=oe(this.provider),r,n=ee(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=Q(this.model,this.provider,e);return{endpoint:o,requestBody:r,headers:n}}async sendCompletionRequest(e,o,r){return N.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&&A("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:R(e).message,completion:null}}};var _=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(`
|
|
45
|
+
Analyze context, maintain style, ensure syntax correctness. Provide ONLY the completion code without any explanations or comments.`.trim();return ce(i,{textBeforeCursor:t,textAfterCursor:e,editorState:{completionMode:o},language:r,...n})},de=Me;var G=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??Q,this.validateInputs();}validateInputs(){if(!U.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${T(U)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!K[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${T(K[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},a=this.generatePrompt(n,s),{endpoint:l,requestBody:m,headers:c}=this.prepareRequestDetails(a);try{let d=await this.sendCompletionRequest(l,m,{...c,...i});return this.processCompletionResponse(d)}catch(d){return this.handleCompletionError(d)}}generatePrompt(e,o){let r=de(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=te(this.model,this.apiKey,this.provider),r,n=re(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=oe(this.model,this.provider,e);return {endpoint:o,requestBody:r,headers:n}}async sendCompletionRequest(e,o,r){return N.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&&L("completion","text","Copilot.options.model.transformResponse"),{completion:o.text??o.completion??null,raw:e}}else return {completion:ne(e,this.provider),raw:e}}handleCompletionError(e){return {error:y(e).message,completion:null}}};var _=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(`
|
|
134
46
|
`).slice(1,-1).join(`
|
|
135
|
-
`);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
47
|
+
`);r=r.replace(i,s);}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
48
|
+
|
|
49
|
+
`),this}build(){return this.formattedCompletion}};var B=class{constructor(e,o){this.cursorPos=e,this.mdl=o;}shouldProvideCompletions(){return !pe(this.cursorPos,this.mdl)}};var q=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 g=class g{constructor(){this.cache=new q(g.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 h(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:a,endLineNumber:l,endColumn:m}=n,{lineNumber:c,column:d}=o,p=c===s&&d===a;if(s===l)return p||i.startsWith(r)&&c===s&&d>=a-g.LOOK_AROUND&&d<=m+g.LOOK_AROUND;let u=i.startsWith(r)&&c>=s&&c<=l&&(c===s&&d>=a-g.LOOK_AROUND||c===l&&d<=m+g.LOOK_AROUND||c>s&&c<l);return p||u}};g.MAX_CACHE_SIZE=10,g.LOOK_AROUND=10;var k=g;var $=class{constructor(e){this.monaco=e;}computeInsertionRange(e,o,r){if(!o)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let n=w(e,r),i=o[0];if(!n||i===n)return this.calculateRangeWithoutOverlap(e,o);let s=r.getOffsetAt(e),a=h(e,r),l=S(e,r);if(s>=r.getValue().length||!l.length)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let m=this.getSuffixOverlapLength(o,a),c=this.computeMaxOverlapLength(o,l),d=m>0?r.getPositionAt(s-m):e,p=s+c,u=r.getPositionAt(p);return new this.monaco.Range(d.lineNumber,d.column,u.lineNumber,u.column)}calculateRangeWithoutOverlap(e,o){let r=e.lineNumber,n=e.column,i=o.split(`
|
|
50
|
+
`),s=i.length-1,a=r+s,l=s===0?n+i[0].length:i[s].length+1;return new this.monaco.Range(r,n,a,l)}computeMaxOverlapLength(e,o){let r=this.getPrefixOverlapLength(e,o),n=this.getSuffixPrefixOverlapLength(e,o),i=Math.max(r,n);return i===0&&(i=this.getInternalOverlapLength(e,o)),i}getSuffixOverlapLength(e,o){let r=Math.min(e.length,o.length),n=0;for(let i=1;i<=r;i++)e.substring(0,i)===o.slice(-i)&&(n=i);return n}getPrefixOverlapLength(e,o){let r=Math.min(e.length,o.length);for(let n=0;n<r;n++)if(e[n]!==o[n])return n;return r}getSuffixPrefixOverlapLength(e,o){let r=Math.min(e.length,o.length);for(let n=r;n>0;n--)if(e.slice(-n)===o.slice(0,n))return n;return 0}getInternalOverlapLength(e,o){for(let r=1;r<e.length;r++)if(o.startsWith(e.substring(r)))return e.length-r;return 0}};var Ie="application/json",me=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:n}=await N.POST(e,o,{headers:{"Content-Type":Ie},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return {completion:r}},ue=({pos:t,mdl:e,options:o})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:a}=o,l=Ae(t,e),c=!!s?.length?3:2,d=a?Math.floor(a/c):void 0,p=(P,C,V)=>{let b=P(t,e);return C?Y(b,C,V):b},u=(P,C)=>!P||!C?P:P.map(({content:V,...b})=>({...b,content:Y(V,C)})),j=p(h,d,{from:"end"}),E=p(S,d),R=u(s,d);return {filename:r,language:n,technologies:i,relatedFiles:R,textBeforeCursor:j,textAfterCursor:E,cursorPosition:t,editorState:{completionMode:l}}},Ae=(t,e)=>{let o=w(t,e),r=D(t,e);return o?"insert":r.trim()?"complete":"continue"};var ge=t=>_.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),f=t=>({items:t,enableForwardStability:!0,suppressSuggestions:!0});var X={onTyping:300,onIdle:600,onDemand:0},we=t=>({onTyping:F(t,X.onTyping),onIdle:F(t,X.onIdle),onDemand:F(t,X.onDemand)}),H=new k,De=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{let{trigger:a="onIdle",endpoint:l,enableCaching:m=!0,onError:c,requestHandler:d}=s;if(!new B(o,e).shouldProvideCompletions())return f([]);if(m){let p=H.get(o,e).map(u=>({insertText:u.completion,range:u.range}));if(p.length>0)return i(),f(p)}if(r.isCancellationRequested||n)return f([]);try{let u=we(d??me)[a];r.onCancellationRequested(()=>{u.cancel();});let j=ue({pos:o,mdl:e,options:s}),{completion:E}=await u({endpoint:l,body:{completionMetadata:j}});if(E){let R=ge(E),C=new $(t).computeInsertionRange(o,R,e);return m&&H.add({completion:R,range:C,textBeforeCursor:h(o,e)}),i(),f([{insertText:R,range:C}])}}catch(p){if(Se(p))return f([]);c?c(p):y(p);}return f([])},Se=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,Ce=De;var x=new WeakMap,v=null,he=(t,e,o)=>{v&&v.deregister();let r=[],n={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};x.set(e,n),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let i=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(l,m,c,d)=>{let p=x.get(e);if(!(!p||o.trigger==="onDemand"&&!p.isManualTrigger))return Ce({monaco:t,mdl:l,pos:m,token:d,isCompletionAccepted:p.isCompletionAccepted,onShowCompletion:()=>{p.isCompletionVisible=!0,p.isManualTrigger=!1;},options:o})},freeInlineCompletions:()=>{}});r.push(i);let s=e.onKeyDown(l=>{let m=x.get(e);if(!m)return;let c=l.keyCode===t.KeyCode.Tab||l.keyCode===t.KeyCode.RightArrow&&l.metaKey;m.isCompletionVisible&&c?(m.isCompletionAccepted=!0,m.isCompletionVisible=!1):m.isCompletionAccepted=!1;});r.push(s);let a={deregister:()=>{r.forEach(l=>l.dispose()),H.clear(),x.delete(e),v=null;},trigger:()=>Ne(e)};return v=a,a}catch(i){return o.onError?o.onError(i):y(i),{deregister:()=>{r.forEach(s=>s.dispose()),x.delete(e),v=null;},trigger:()=>{}}}},Ne=t=>{let e=x.get(t);if(!e){se("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isManualTrigger=!0,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{});},Fe=(...t)=>(L("registerCopilot","registerCompletion"),he(...t));
|
|
136
51
|
|
|
137
|
-
|
|
52
|
+
export { G as Copilot, he as registerCompletion, Fe as registerCopilot };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "monacopilot",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.1",
|
|
4
4
|
"description": "AI auto-completion plugin for Monaco Editor",
|
|
5
5
|
"main": "./build/index.js",
|
|
6
6
|
"module": "./build/index.mjs",
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
"@anthropic-ai/sdk": "^0.27.3",
|
|
26
26
|
"@commitlint/cli": "^19.5.0",
|
|
27
27
|
"@commitlint/config-conventional": "^19.5.0",
|
|
28
|
+
"@google/generative-ai": "^0.21.0",
|
|
28
29
|
"@ianvs/prettier-plugin-sort-imports": "^4.2.1",
|
|
29
30
|
"@release-it/conventional-changelog": "^8.0.2",
|
|
30
31
|
"@typescript-eslint/eslint-plugin": "^7.3.1",
|
|
@@ -60,5 +61,6 @@
|
|
|
60
61
|
}
|
|
61
62
|
],
|
|
62
63
|
"license": "MIT",
|
|
63
|
-
"author": "Arshad Yaseen <m@arshadyaseen.com> (https://arshadyaseen.com)"
|
|
64
|
+
"author": "Arshad Yaseen <m@arshadyaseen.com> (https://arshadyaseen.com)",
|
|
65
|
+
"dependencies": {}
|
|
64
66
|
}
|