monacopilot 0.19.0-beta.8 → 0.19.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.d.mts +246 -0
- package/build/index.d.ts +246 -0
- package/build/index.js +42 -0
- package/build/index.mjs +42 -0
- package/package.json +2 -2
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { CustomPrompt, Copilot as Copilot$1, Provider, Model, PromptData } from '@monacopilot/core';
|
|
2
|
+
export { AnthropicModel, CopilotOptions, CustomCopilotModel, DeepSeekModel, GoogleModel, GroqModel, Model, OpenAIModel, Provider } from '@monacopilot/core';
|
|
3
|
+
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
4
|
+
|
|
5
|
+
type Monaco = typeof monaco;
|
|
6
|
+
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
7
|
+
type CursorPosition = monaco.IPosition;
|
|
8
|
+
type EditorRange = monaco.IRange;
|
|
9
|
+
|
|
10
|
+
type FetchCompletionItemHandler = (params: FetchCompletionItemParams) => Promise<FetchCompletionItemReturn>;
|
|
11
|
+
type FetchCompletionItemReturn = {
|
|
12
|
+
completion: string | null;
|
|
13
|
+
};
|
|
14
|
+
interface FetchCompletionItemParams {
|
|
15
|
+
endpoint: string;
|
|
16
|
+
body: CompletionRequestBody;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type Endpoint = string;
|
|
20
|
+
type Filename = string;
|
|
21
|
+
type Technologies = string[];
|
|
22
|
+
type RelatedFile = {
|
|
23
|
+
/**
|
|
24
|
+
* The relative path from the current editing code in the editor to an external file.
|
|
25
|
+
*
|
|
26
|
+
* Examples:
|
|
27
|
+
* - To include a file `utils.js` in the same directory, set as `./utils.js`.
|
|
28
|
+
* - To include a file `utils.js` in the parent directory, set as `../utils.js`.
|
|
29
|
+
* - To include a file `utils.js` in the child directory, set as `./child/utils.js`.
|
|
30
|
+
*/
|
|
31
|
+
path: string;
|
|
32
|
+
/**
|
|
33
|
+
* The content of the external file as a string.
|
|
34
|
+
*/
|
|
35
|
+
content: string;
|
|
36
|
+
};
|
|
37
|
+
interface RegisterCompletionOptions {
|
|
38
|
+
/**
|
|
39
|
+
* Language of the current model
|
|
40
|
+
*/
|
|
41
|
+
language: string;
|
|
42
|
+
/**
|
|
43
|
+
* The API endpoint where you started the completion service.
|
|
44
|
+
*/
|
|
45
|
+
endpoint: Endpoint;
|
|
46
|
+
/**
|
|
47
|
+
* Specifies when the completion service should provide code completions.
|
|
48
|
+
*
|
|
49
|
+
* Options:
|
|
50
|
+
* - `'onIdle'`: Provides completions after a brief pause in typing.
|
|
51
|
+
* - `'onTyping'`: Provides completions in real-time as you type.
|
|
52
|
+
* - *Note:* Best suited for models with low response latency (e.g., Groq).
|
|
53
|
+
* - *Consideration:* May initiate additional background requests to deliver real-time suggestions.
|
|
54
|
+
* - `'onDemand'`: Completions are not provided automatically. You need to trigger the completion manually, possibly by using the `trigger` function from `registerCompletion` return.
|
|
55
|
+
*
|
|
56
|
+
* @default 'onIdle'
|
|
57
|
+
*/
|
|
58
|
+
trigger?: 'onTyping' | 'onIdle' | 'onDemand';
|
|
59
|
+
/**
|
|
60
|
+
* The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
|
|
61
|
+
* For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
|
|
62
|
+
*/
|
|
63
|
+
filename?: Filename;
|
|
64
|
+
/**
|
|
65
|
+
* The technologies (libraries, frameworks, etc.) you want to use for the completion.
|
|
66
|
+
* This can provide technology-specific completions.
|
|
67
|
+
* If you don't specify a technology, the completion will be specific to the language (provided as the `language`).
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ['react', 'nextjs', 'tailwindcss', 'tanstack/react-query']
|
|
71
|
+
* ['tensorflow', 'keras', 'numpy', 'pandas']
|
|
72
|
+
* etc.
|
|
73
|
+
*/
|
|
74
|
+
technologies?: Technologies;
|
|
75
|
+
/**
|
|
76
|
+
* Helps to give more relevant completions based on the full context.
|
|
77
|
+
* You can include things like the contents/codes of other files in the same workspace.
|
|
78
|
+
*/
|
|
79
|
+
relatedFiles?: RelatedFile[];
|
|
80
|
+
/**
|
|
81
|
+
* The maximum number of lines of code to include in the completion request.
|
|
82
|
+
* This limits the request size to the model to prevent `429 Too Many Requests` errors
|
|
83
|
+
* and reduce costs for long code.
|
|
84
|
+
*
|
|
85
|
+
* It is recommended to set `maxContextLines` to `60` or less if you are using `Groq` as your provider,
|
|
86
|
+
* since `Groq` does not implement pay-as-you-go pricing and has only low rate limits.
|
|
87
|
+
*/
|
|
88
|
+
maxContextLines?: number;
|
|
89
|
+
/**
|
|
90
|
+
* Determines if completions should be cached.
|
|
91
|
+
* Enabling caching can enhance performance by reusing previous results when the cursor position and context remain the same while editing.
|
|
92
|
+
* @default true
|
|
93
|
+
*/
|
|
94
|
+
enableCaching?: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* When an error occurs during the completion process or requests, Monacopilot will log it to the console by default
|
|
97
|
+
* rather than throwing errors. This ensures smooth editing even when completions are unavailable.
|
|
98
|
+
* You can provide this callback to handle errors yourself, which will disable the default console logging.
|
|
99
|
+
* @param error - The error object containing information about the encountered error.
|
|
100
|
+
*/
|
|
101
|
+
onError?: (error: Error) => void;
|
|
102
|
+
/**
|
|
103
|
+
* Custom fetch completion handler. This function overrides the default fetch completion handler.
|
|
104
|
+
* It allows you to customize how completion requests are made and responses are processed.
|
|
105
|
+
* You can implement your own logic for fetching and processing completions.
|
|
106
|
+
* The function should return either a string (the completion to be inserted into the editor) or null.
|
|
107
|
+
* @param params - The parameters for the completion request.
|
|
108
|
+
* @param {string} params.endpoint - The endpoint to fetch the completion from.
|
|
109
|
+
* @param {CompletionRequestBody} params.body - The body of the completion request.
|
|
110
|
+
* @returns {Promise<{completion: string | null}>} An object containing the completion or null if no completion is available.
|
|
111
|
+
*/
|
|
112
|
+
requestHandler?: FetchCompletionItemHandler;
|
|
113
|
+
/**
|
|
114
|
+
* Callback function that is triggered when a completion is shown in the editor.
|
|
115
|
+
* @param completion - The completion text that is being shown.
|
|
116
|
+
* @param range - The editor range where the completion will be inserted.
|
|
117
|
+
*/
|
|
118
|
+
onCompletionShown?: (completion: string, range: EditorRange | undefined) => void;
|
|
119
|
+
/**
|
|
120
|
+
* Callback function triggered when a completion is accepted by the user.
|
|
121
|
+
*/
|
|
122
|
+
onCompletionAccepted?: () => void;
|
|
123
|
+
/**
|
|
124
|
+
* Callback function triggered when a completion is rejected by the user.
|
|
125
|
+
*/
|
|
126
|
+
onCompletionRejected?: () => void;
|
|
127
|
+
}
|
|
128
|
+
interface CompletionRegistration {
|
|
129
|
+
/**
|
|
130
|
+
* Triggers the completion.
|
|
131
|
+
*/
|
|
132
|
+
trigger: () => void;
|
|
133
|
+
/**
|
|
134
|
+
* Deregisters the completion provider and cleans up all associated resources.
|
|
135
|
+
* This should be called when unmounting the editor or when completion features
|
|
136
|
+
* are no longer needed to prevent memory leaks and ensure proper cleanup.
|
|
137
|
+
*/
|
|
138
|
+
deregister: () => void;
|
|
139
|
+
}
|
|
140
|
+
interface CompletionRequest {
|
|
141
|
+
/**
|
|
142
|
+
* The body of the completion request.
|
|
143
|
+
*/
|
|
144
|
+
body: CompletionRequestBody;
|
|
145
|
+
/**
|
|
146
|
+
* Additional options to include in the completion request.
|
|
147
|
+
*/
|
|
148
|
+
options?: CompletionRequestOptions;
|
|
149
|
+
}
|
|
150
|
+
interface CompletionRequestBody {
|
|
151
|
+
/**
|
|
152
|
+
* The metadata required to generate the completion.
|
|
153
|
+
*/
|
|
154
|
+
completionMetadata: CompletionMetadata;
|
|
155
|
+
}
|
|
156
|
+
interface CompletionRequestOptions {
|
|
157
|
+
/**
|
|
158
|
+
* Custom headers to include in the request to the LLM provider.
|
|
159
|
+
*/
|
|
160
|
+
headers?: Record<string, string>;
|
|
161
|
+
/**
|
|
162
|
+
* Custom prompt generator function for the completion request.
|
|
163
|
+
* This function allows you to override the default system and user prompts
|
|
164
|
+
* used in the completion request, providing more control over the AI's context and behavior.
|
|
165
|
+
*
|
|
166
|
+
* @param completionMetadata - Metadata about the current completion context
|
|
167
|
+
* @returns An object containing custom 'system' and 'user' prompts
|
|
168
|
+
*/
|
|
169
|
+
customPrompt?: CustomPrompt<CompletionMetadata>;
|
|
170
|
+
}
|
|
171
|
+
interface CompletionResponse {
|
|
172
|
+
/**
|
|
173
|
+
* The completion text.
|
|
174
|
+
*/
|
|
175
|
+
completion: string | null;
|
|
176
|
+
/**
|
|
177
|
+
* The error message.
|
|
178
|
+
*/
|
|
179
|
+
error?: string;
|
|
180
|
+
/**
|
|
181
|
+
* The raw response from the LLM.
|
|
182
|
+
*/
|
|
183
|
+
raw?: unknown;
|
|
184
|
+
}
|
|
185
|
+
type CompletionMode = 'insert' | 'complete' | 'continue';
|
|
186
|
+
interface CompletionMetadata {
|
|
187
|
+
/**
|
|
188
|
+
* The programming language of the code.
|
|
189
|
+
*/
|
|
190
|
+
language: string | undefined;
|
|
191
|
+
/**
|
|
192
|
+
* The name of the file being edited.
|
|
193
|
+
*/
|
|
194
|
+
filename: Filename | undefined;
|
|
195
|
+
/**
|
|
196
|
+
* The technologies used in the completion.
|
|
197
|
+
*/
|
|
198
|
+
technologies: Technologies | undefined;
|
|
199
|
+
/**
|
|
200
|
+
* Additional context from related files.
|
|
201
|
+
*/
|
|
202
|
+
relatedFiles: RelatedFile[] | undefined;
|
|
203
|
+
/**
|
|
204
|
+
* The text that appears after the cursor.
|
|
205
|
+
*/
|
|
206
|
+
textAfterCursor: string;
|
|
207
|
+
/**
|
|
208
|
+
* The text that appears before the cursor.
|
|
209
|
+
*/
|
|
210
|
+
textBeforeCursor: string;
|
|
211
|
+
/**
|
|
212
|
+
* The current cursor position.
|
|
213
|
+
*/
|
|
214
|
+
cursorPosition: CursorPosition;
|
|
215
|
+
/**
|
|
216
|
+
* The current state of the editor.
|
|
217
|
+
*/
|
|
218
|
+
editorState: {
|
|
219
|
+
/**
|
|
220
|
+
* The mode of the completion.
|
|
221
|
+
* - `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.
|
|
222
|
+
* - `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.
|
|
223
|
+
* - `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.
|
|
224
|
+
*/
|
|
225
|
+
completionMode: CompletionMode;
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
declare class CompletionCopilot extends Copilot$1<Provider, Model, CompletionMetadata> {
|
|
230
|
+
complete(request: CompletionRequest): Promise<CompletionResponse>;
|
|
231
|
+
protected getDefaultPrompt(metadata: CompletionMetadata): PromptData;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Registers completion functionality with the Monaco editor.
|
|
236
|
+
* @param monaco - The Monaco instance.
|
|
237
|
+
* @param editor - The editor instance.
|
|
238
|
+
* @param options - Options for the completion.
|
|
239
|
+
* @returns A CompletionRegistration object with deregister and trigger methods.
|
|
240
|
+
*/
|
|
241
|
+
declare const registerCompletion: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCompletionOptions) => CompletionRegistration;
|
|
242
|
+
|
|
243
|
+
/** @deprecated Use `CompletionCopilot` instead */
|
|
244
|
+
declare const Copilot: typeof CompletionCopilot;
|
|
245
|
+
|
|
246
|
+
export { CompletionCopilot, type CompletionMetadata, type CompletionRegistration, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, Copilot, type Monaco, type RegisterCompletionOptions, type StandaloneCodeEditor, registerCompletion };
|
package/build/index.d.ts
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { CustomPrompt, Copilot as Copilot$1, Provider, Model, PromptData } from '@monacopilot/core';
|
|
2
|
+
export { AnthropicModel, CopilotOptions, CustomCopilotModel, DeepSeekModel, GoogleModel, GroqModel, Model, OpenAIModel, Provider } from '@monacopilot/core';
|
|
3
|
+
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
4
|
+
|
|
5
|
+
type Monaco = typeof monaco;
|
|
6
|
+
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
7
|
+
type CursorPosition = monaco.IPosition;
|
|
8
|
+
type EditorRange = monaco.IRange;
|
|
9
|
+
|
|
10
|
+
type FetchCompletionItemHandler = (params: FetchCompletionItemParams) => Promise<FetchCompletionItemReturn>;
|
|
11
|
+
type FetchCompletionItemReturn = {
|
|
12
|
+
completion: string | null;
|
|
13
|
+
};
|
|
14
|
+
interface FetchCompletionItemParams {
|
|
15
|
+
endpoint: string;
|
|
16
|
+
body: CompletionRequestBody;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type Endpoint = string;
|
|
20
|
+
type Filename = string;
|
|
21
|
+
type Technologies = string[];
|
|
22
|
+
type RelatedFile = {
|
|
23
|
+
/**
|
|
24
|
+
* The relative path from the current editing code in the editor to an external file.
|
|
25
|
+
*
|
|
26
|
+
* Examples:
|
|
27
|
+
* - To include a file `utils.js` in the same directory, set as `./utils.js`.
|
|
28
|
+
* - To include a file `utils.js` in the parent directory, set as `../utils.js`.
|
|
29
|
+
* - To include a file `utils.js` in the child directory, set as `./child/utils.js`.
|
|
30
|
+
*/
|
|
31
|
+
path: string;
|
|
32
|
+
/**
|
|
33
|
+
* The content of the external file as a string.
|
|
34
|
+
*/
|
|
35
|
+
content: string;
|
|
36
|
+
};
|
|
37
|
+
interface RegisterCompletionOptions {
|
|
38
|
+
/**
|
|
39
|
+
* Language of the current model
|
|
40
|
+
*/
|
|
41
|
+
language: string;
|
|
42
|
+
/**
|
|
43
|
+
* The API endpoint where you started the completion service.
|
|
44
|
+
*/
|
|
45
|
+
endpoint: Endpoint;
|
|
46
|
+
/**
|
|
47
|
+
* Specifies when the completion service should provide code completions.
|
|
48
|
+
*
|
|
49
|
+
* Options:
|
|
50
|
+
* - `'onIdle'`: Provides completions after a brief pause in typing.
|
|
51
|
+
* - `'onTyping'`: Provides completions in real-time as you type.
|
|
52
|
+
* - *Note:* Best suited for models with low response latency (e.g., Groq).
|
|
53
|
+
* - *Consideration:* May initiate additional background requests to deliver real-time suggestions.
|
|
54
|
+
* - `'onDemand'`: Completions are not provided automatically. You need to trigger the completion manually, possibly by using the `trigger` function from `registerCompletion` return.
|
|
55
|
+
*
|
|
56
|
+
* @default 'onIdle'
|
|
57
|
+
*/
|
|
58
|
+
trigger?: 'onTyping' | 'onIdle' | 'onDemand';
|
|
59
|
+
/**
|
|
60
|
+
* The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
|
|
61
|
+
* For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
|
|
62
|
+
*/
|
|
63
|
+
filename?: Filename;
|
|
64
|
+
/**
|
|
65
|
+
* The technologies (libraries, frameworks, etc.) you want to use for the completion.
|
|
66
|
+
* This can provide technology-specific completions.
|
|
67
|
+
* If you don't specify a technology, the completion will be specific to the language (provided as the `language`).
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ['react', 'nextjs', 'tailwindcss', 'tanstack/react-query']
|
|
71
|
+
* ['tensorflow', 'keras', 'numpy', 'pandas']
|
|
72
|
+
* etc.
|
|
73
|
+
*/
|
|
74
|
+
technologies?: Technologies;
|
|
75
|
+
/**
|
|
76
|
+
* Helps to give more relevant completions based on the full context.
|
|
77
|
+
* You can include things like the contents/codes of other files in the same workspace.
|
|
78
|
+
*/
|
|
79
|
+
relatedFiles?: RelatedFile[];
|
|
80
|
+
/**
|
|
81
|
+
* The maximum number of lines of code to include in the completion request.
|
|
82
|
+
* This limits the request size to the model to prevent `429 Too Many Requests` errors
|
|
83
|
+
* and reduce costs for long code.
|
|
84
|
+
*
|
|
85
|
+
* It is recommended to set `maxContextLines` to `60` or less if you are using `Groq` as your provider,
|
|
86
|
+
* since `Groq` does not implement pay-as-you-go pricing and has only low rate limits.
|
|
87
|
+
*/
|
|
88
|
+
maxContextLines?: number;
|
|
89
|
+
/**
|
|
90
|
+
* Determines if completions should be cached.
|
|
91
|
+
* Enabling caching can enhance performance by reusing previous results when the cursor position and context remain the same while editing.
|
|
92
|
+
* @default true
|
|
93
|
+
*/
|
|
94
|
+
enableCaching?: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* When an error occurs during the completion process or requests, Monacopilot will log it to the console by default
|
|
97
|
+
* rather than throwing errors. This ensures smooth editing even when completions are unavailable.
|
|
98
|
+
* You can provide this callback to handle errors yourself, which will disable the default console logging.
|
|
99
|
+
* @param error - The error object containing information about the encountered error.
|
|
100
|
+
*/
|
|
101
|
+
onError?: (error: Error) => void;
|
|
102
|
+
/**
|
|
103
|
+
* Custom fetch completion handler. This function overrides the default fetch completion handler.
|
|
104
|
+
* It allows you to customize how completion requests are made and responses are processed.
|
|
105
|
+
* You can implement your own logic for fetching and processing completions.
|
|
106
|
+
* The function should return either a string (the completion to be inserted into the editor) or null.
|
|
107
|
+
* @param params - The parameters for the completion request.
|
|
108
|
+
* @param {string} params.endpoint - The endpoint to fetch the completion from.
|
|
109
|
+
* @param {CompletionRequestBody} params.body - The body of the completion request.
|
|
110
|
+
* @returns {Promise<{completion: string | null}>} An object containing the completion or null if no completion is available.
|
|
111
|
+
*/
|
|
112
|
+
requestHandler?: FetchCompletionItemHandler;
|
|
113
|
+
/**
|
|
114
|
+
* Callback function that is triggered when a completion is shown in the editor.
|
|
115
|
+
* @param completion - The completion text that is being shown.
|
|
116
|
+
* @param range - The editor range where the completion will be inserted.
|
|
117
|
+
*/
|
|
118
|
+
onCompletionShown?: (completion: string, range: EditorRange | undefined) => void;
|
|
119
|
+
/**
|
|
120
|
+
* Callback function triggered when a completion is accepted by the user.
|
|
121
|
+
*/
|
|
122
|
+
onCompletionAccepted?: () => void;
|
|
123
|
+
/**
|
|
124
|
+
* Callback function triggered when a completion is rejected by the user.
|
|
125
|
+
*/
|
|
126
|
+
onCompletionRejected?: () => void;
|
|
127
|
+
}
|
|
128
|
+
interface CompletionRegistration {
|
|
129
|
+
/**
|
|
130
|
+
* Triggers the completion.
|
|
131
|
+
*/
|
|
132
|
+
trigger: () => void;
|
|
133
|
+
/**
|
|
134
|
+
* Deregisters the completion provider and cleans up all associated resources.
|
|
135
|
+
* This should be called when unmounting the editor or when completion features
|
|
136
|
+
* are no longer needed to prevent memory leaks and ensure proper cleanup.
|
|
137
|
+
*/
|
|
138
|
+
deregister: () => void;
|
|
139
|
+
}
|
|
140
|
+
interface CompletionRequest {
|
|
141
|
+
/**
|
|
142
|
+
* The body of the completion request.
|
|
143
|
+
*/
|
|
144
|
+
body: CompletionRequestBody;
|
|
145
|
+
/**
|
|
146
|
+
* Additional options to include in the completion request.
|
|
147
|
+
*/
|
|
148
|
+
options?: CompletionRequestOptions;
|
|
149
|
+
}
|
|
150
|
+
interface CompletionRequestBody {
|
|
151
|
+
/**
|
|
152
|
+
* The metadata required to generate the completion.
|
|
153
|
+
*/
|
|
154
|
+
completionMetadata: CompletionMetadata;
|
|
155
|
+
}
|
|
156
|
+
interface CompletionRequestOptions {
|
|
157
|
+
/**
|
|
158
|
+
* Custom headers to include in the request to the LLM provider.
|
|
159
|
+
*/
|
|
160
|
+
headers?: Record<string, string>;
|
|
161
|
+
/**
|
|
162
|
+
* Custom prompt generator function for the completion request.
|
|
163
|
+
* This function allows you to override the default system and user prompts
|
|
164
|
+
* used in the completion request, providing more control over the AI's context and behavior.
|
|
165
|
+
*
|
|
166
|
+
* @param completionMetadata - Metadata about the current completion context
|
|
167
|
+
* @returns An object containing custom 'system' and 'user' prompts
|
|
168
|
+
*/
|
|
169
|
+
customPrompt?: CustomPrompt<CompletionMetadata>;
|
|
170
|
+
}
|
|
171
|
+
interface CompletionResponse {
|
|
172
|
+
/**
|
|
173
|
+
* The completion text.
|
|
174
|
+
*/
|
|
175
|
+
completion: string | null;
|
|
176
|
+
/**
|
|
177
|
+
* The error message.
|
|
178
|
+
*/
|
|
179
|
+
error?: string;
|
|
180
|
+
/**
|
|
181
|
+
* The raw response from the LLM.
|
|
182
|
+
*/
|
|
183
|
+
raw?: unknown;
|
|
184
|
+
}
|
|
185
|
+
type CompletionMode = 'insert' | 'complete' | 'continue';
|
|
186
|
+
interface CompletionMetadata {
|
|
187
|
+
/**
|
|
188
|
+
* The programming language of the code.
|
|
189
|
+
*/
|
|
190
|
+
language: string | undefined;
|
|
191
|
+
/**
|
|
192
|
+
* The name of the file being edited.
|
|
193
|
+
*/
|
|
194
|
+
filename: Filename | undefined;
|
|
195
|
+
/**
|
|
196
|
+
* The technologies used in the completion.
|
|
197
|
+
*/
|
|
198
|
+
technologies: Technologies | undefined;
|
|
199
|
+
/**
|
|
200
|
+
* Additional context from related files.
|
|
201
|
+
*/
|
|
202
|
+
relatedFiles: RelatedFile[] | undefined;
|
|
203
|
+
/**
|
|
204
|
+
* The text that appears after the cursor.
|
|
205
|
+
*/
|
|
206
|
+
textAfterCursor: string;
|
|
207
|
+
/**
|
|
208
|
+
* The text that appears before the cursor.
|
|
209
|
+
*/
|
|
210
|
+
textBeforeCursor: string;
|
|
211
|
+
/**
|
|
212
|
+
* The current cursor position.
|
|
213
|
+
*/
|
|
214
|
+
cursorPosition: CursorPosition;
|
|
215
|
+
/**
|
|
216
|
+
* The current state of the editor.
|
|
217
|
+
*/
|
|
218
|
+
editorState: {
|
|
219
|
+
/**
|
|
220
|
+
* The mode of the completion.
|
|
221
|
+
* - `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.
|
|
222
|
+
* - `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.
|
|
223
|
+
* - `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.
|
|
224
|
+
*/
|
|
225
|
+
completionMode: CompletionMode;
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
declare class CompletionCopilot extends Copilot$1<Provider, Model, CompletionMetadata> {
|
|
230
|
+
complete(request: CompletionRequest): Promise<CompletionResponse>;
|
|
231
|
+
protected getDefaultPrompt(metadata: CompletionMetadata): PromptData;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Registers completion functionality with the Monaco editor.
|
|
236
|
+
* @param monaco - The Monaco instance.
|
|
237
|
+
* @param editor - The editor instance.
|
|
238
|
+
* @param options - Options for the completion.
|
|
239
|
+
* @returns A CompletionRegistration object with deregister and trigger methods.
|
|
240
|
+
*/
|
|
241
|
+
declare const registerCompletion: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCompletionOptions) => CompletionRegistration;
|
|
242
|
+
|
|
243
|
+
/** @deprecated Use `CompletionCopilot` instead */
|
|
244
|
+
declare const Copilot: typeof CompletionCopilot;
|
|
245
|
+
|
|
246
|
+
export { CompletionCopilot, type CompletionMetadata, type CompletionRegistration, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, Copilot, type Monaco, type RegisterCompletionOptions, type StandaloneCodeEditor, registerCompletion };
|
package/build/index.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use strict';var core=require('@monacopilot/core');var q=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`,K=t=>t.charAt(0).toUpperCase()+t.slice(1),O=(t,e,o={})=>{if(e<=0)return "";let n=t.split(`
|
|
2
|
+
`),r=n.length;if(e>=r)return t;if(o.from==="end"){let s=n.slice(-e);return s.every(l=>l==="")?`
|
|
3
|
+
`.repeat(e):s.join(`
|
|
4
|
+
`)}let i=n.slice(0,e);return i.every(s=>s==="")?`
|
|
5
|
+
`.repeat(e):i.join(`
|
|
6
|
+
`)};var J=t=>!t||t.length===0?"":t.map(({path:e,content:o})=>`
|
|
7
|
+
<related_file>
|
|
8
|
+
<filePath>${e}</filePath>
|
|
9
|
+
<fileContent>
|
|
10
|
+
\`\`\`
|
|
11
|
+
${o}
|
|
12
|
+
\`\`\`
|
|
13
|
+
</fileContent>
|
|
14
|
+
</related_file>`.trim()).join(`
|
|
15
|
+
|
|
16
|
+
`),j=t=>{let{technologies:e=[],filename:o,relatedFiles:n,language:r,textBeforeCursor:i="",textAfterCursor:s="",editorState:{completionMode:l}}=t,p=q([r,...e].filter(a=>typeof a=="string"&&!!a)),d=`
|
|
17
|
+
You are an expert code completion assistant.
|
|
18
|
+
|
|
19
|
+
**Context:**
|
|
20
|
+
File: ${o||"Untitled"}
|
|
21
|
+
Language: ${r||"Undetermined"}
|
|
22
|
+
Mode: ${l}
|
|
23
|
+
Stack: ${p||"None"}`,c=`
|
|
24
|
+
**Related Files:**
|
|
25
|
+
${J(n)}
|
|
26
|
+
|
|
27
|
+
**Source:**
|
|
28
|
+
\`\`\`
|
|
29
|
+
${i}<cursor>${s}
|
|
30
|
+
\`\`\`
|
|
31
|
+
|
|
32
|
+
${K(l)} the code at <cursor>.
|
|
33
|
+
|
|
34
|
+
Output only the raw code to be inserted at the cursor location without any additional text or comments.`;return {system:d,user:c}};var v=class extends core.Copilot{async complete(e){let{body:o,options:n}=e,{customPrompt:r,headers:i}=n??{},{completionMetadata:s}=o,{text:l,raw:p,error:d}=await this.makeAIRequest(s,{customPrompt:r,customHeaders:i});return {completion:l,raw:p,error:d}}getDefaultPrompt(e){return j(e)}};var V=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1];var H=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),E=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),B=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var T=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 A=class A{constructor(){this.cache=new T(A.MAX_CACHE_SIZE);}get(e,o){return this.cache.getAll().filter(n=>this.isValidCacheItem(n,e,o))}add(e){this.cache.enqueue(e);}clear(){this.cache.clear();}isValidCacheItem(e,o,n){let r=n.getValueInRange(e.range),i=E(o,n);return i.length<e.textBeforeCursor.length||!i.startsWith(e.textBeforeCursor)?false:this.isPositionValid(e,o,r)}isPositionValid(e,o,n){let{range:r,completion:i}=e,{startLineNumber:s,startColumn:l,endLineNumber:p,endColumn:d}=r,{lineNumber:c,column:a}=o;if(!i.startsWith(n))return false;let u=c===s&&a===l;if(s===p)return u||c===s&&a>=l&&a<=d;let g=c>s&&c<p?true:c===s&&a>=l||c===p&&a<=d;return u||g}};A.MAX_CACHE_SIZE=10;var I=A;var S=class{constructor(e,o,n){this.formattedCompletion="";this.currentColumn=0;this.textBeforeCursorInLine="";this.formattedCompletion=e,this.currentColumn=o,this.textBeforeCursorInLine=n;}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}indentByColumn(){let e=this.formattedCompletion.split(`
|
|
35
|
+
`);if(e.length<=1||this.textBeforeCursorInLine.trim()!=="")return this;let o=" ".repeat(this.currentColumn-1);return this.formattedCompletion=e[0]+`
|
|
36
|
+
`+e.slice(1).map(n=>o+n).join(`
|
|
37
|
+
`),this}removeMarkdownCodeBlocks(e){let o=/```[\s\S]*?```/g,n=e,r;for(;(r=o.exec(e))!==null;){let i=r[0],s=i.split(`
|
|
38
|
+
`).slice(1,-1).join(`
|
|
39
|
+
`);n=n.replace(i,s);}return n.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
40
|
+
|
|
41
|
+
`),this}build(){return this.formattedCompletion}};var w=class{constructor(e){this.monaco=e;}computeInsertionRange(e,o,n){if(!o)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let r=n.getOffsetAt(e),i=n.getValue().substring(0,r),s=n.getValue().substring(r),l=0,p=0,d=0,c=0,a=o.length,u=i.length,g=s.length;if(r>=n.getValue().length)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(g===0)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let y=Math.min(a,u);for(let m=1;m<=y;m++){let b=o.substring(0,m),Q=i.slice(-m);b===Q&&(c=m);}let C=Math.min(a,g);for(let m=0;m<C&&o[m]===s[m];m++)l++;for(let m=1;m<=C;m++)o.slice(-m)===s.slice(0,m)&&(p=m);if(d=Math.max(l,p),d===0){for(let m=1;m<a;m++)if(s.startsWith(o.substring(m))){d=a-m;break}}let R=c>0?n.getPositionAt(r-c):e,h=r+d,f=n.getPositionAt(h);return new this.monaco.Range(R.lineNumber,R.column,f.lineNumber,f.column)}computeCacheRange(e,o){let n=e.lineNumber,r=e.column,i=o.split(`
|
|
42
|
+
`),s=i.length-1,l=n+s,p=s===0?r+i[0].length:i[s].length+1;return new this.monaco.Range(n,r,l,p)}};var z=async t=>{let{endpoint:e,body:o}=t,{completion:n,error:r}=await core.HTTP.post(e,o,{headers:{"Content-Type":"application/json"},fallbackError:"Error while fetching completion item"});if(r)throw new Error(r);return {completion:n}},$=({pos:t,mdl:e,options:o})=>{let{filename:n,language:r,technologies:i,relatedFiles:s,maxContextLines:l}=o,p=oe(t,e),c=!!s?.length?3:2,a=l?Math.floor(l/c):void 0,u=(h,f,m)=>{let b=h(t,e);return f?O(b,f,m):b},g=(h,f)=>!h||!f?h:h.map(({content:m,...b})=>({...b,content:O(m,f)})),y=u(E,a,{from:"end"}),C=u(B,a),R=g(s,a);return {filename:n,language:r,technologies:i,relatedFiles:R,textBeforeCursor:y,textAfterCursor:C,cursorPosition:t,editorState:{completionMode:p}}},oe=(t,e)=>{let o=V(t,e),n=B(t,e);return o?"insert":n.trim()?"complete":"continue"};var F=(t,e=600,o=200)=>{let n=null,r=0,i=null,s=null,l=false,p=(...d)=>{if(l)return Promise.resolve(void 0);i=d;let c=Date.now(),a=c-r;r=c,n&&(clearTimeout(n),n=null);let u=a<o?e:o;return s=new Promise((g,y)=>{n=setTimeout(async()=>{l=true;try{if(i){let C=await t(...i);g(C);}else g(void 0);}catch(C){y(C);}finally{l=false,n=null,i=null;}},u);}),s};return p.cancel=()=>{n&&(clearTimeout(n),n=null),i=null;},p};var x=t=>({items:t,enableForwardStability:true,suppressSuggestions:true});var ie=t=>({onTyping:F(t,600,200),onIdle:F(t,600,400),onDemand:F(t,0,0)}),L=new I,_=async({monaco:t,mdl:e,pos:o,token:n,isCompletionAccepted:r,options:i})=>{let{trigger:s="onIdle",endpoint:l,enableCaching:p=true,onError:d,requestHandler:c}=i;if(p){let a=L.get(o,e).map(u=>({insertText:u.completion,range:u.range}));if(a.length>0)return x(a)}if(n.isCancellationRequested||r)return x([]);try{let u=ie(c??z)[s];n.onCancellationRequested(()=>{u.cancel();});let g=$({pos:o,mdl:e,options:i}),{completion:y}=await u({endpoint:l,body:{completionMetadata:g}});if(y){let C=new S(y,o.column,H(o,e)).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().indentByColumn().build(),R=new w(t),h=R.computeInsertionRange(o,C,e),f=R.computeCacheRange(o,C);return p&&L.add({completion:C,range:f,textBeforeCursor:E(o,e)}),x([{insertText:C,range:h}])}}catch(a){if(se(a))return x([]);d?d(a):core.logger.warn("Cannot provide completion",a);}return x([])},se=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":false;var N=new WeakMap,M=t=>N.get(t),W=(t,e)=>{N.set(t,e);},k=t=>{N.delete(t);},U=()=>({isCompletionAccepted:false,isCompletionVisible:false,isExplicitlyTriggered:false,hasRejectedCurrentCompletion:false});var G=(t,e,o)=>{let n=M(e);return n?t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(r,i,s,l)=>{if(!(o.trigger==="onDemand"&&!n.isExplicitlyTriggered))return _({monaco:t,mdl:r,pos:i,token:l,isCompletionAccepted:n.isCompletionAccepted,options:o})},handleItemDidShow:(r,i,s)=>{n.isExplicitlyTriggered=false,n.hasRejectedCurrentCompletion=false,!n.isCompletionAccepted&&(n.isCompletionVisible=true,o.onCompletionShown?.(s,i.range));},freeInlineCompletions:()=>{}}):null},X=t=>{let e=M(t);if(!e){core.logger.warn("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isExplicitlyTriggered=true,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{});};var ae={TAB:(t,e)=>e.keyCode===t.KeyCode.Tab,CMD_RIGHT_ARROW:(t,e)=>e.keyCode===t.KeyCode.RightArrow&&e.metaKey},D=class{constructor(e,o,n){this.monaco=e;this.state=o;this.options=n;}handleKeyEvent(e){let o={monaco:this.monaco,event:e,state:this.state,options:this.options};this.handleCompletionAcceptance(o),this.handleCompletionRejection(o);}handleCompletionAcceptance(e){return e.state.isCompletionVisible&&this.isAcceptanceKey(e.event)?(e.options.onCompletionAccepted?.(),e.state.isCompletionAccepted=true,e.state.isCompletionVisible=false,true):(e.state.isCompletionAccepted=false,false)}handleCompletionRejection(e){return this.shouldRejectCompletion(e)?(e.options.onCompletionRejected?.(),e.state.hasRejectedCurrentCompletion=true,true):false}shouldRejectCompletion(e){return e.state.isCompletionVisible&&!e.state.hasRejectedCurrentCompletion&&!e.state.isCompletionAccepted&&!this.isAcceptanceKey(e.event)}isAcceptanceKey(e){return Object.values(ae).some(o=>o(this.monaco,e))}},Y=(t,e,o,n)=>{let r=new D(t,o,n);return e.onKeyDown(i=>r.handleKeyEvent(i))};var P=null,me=(t,e,o)=>{P&&P.deregister();let n=[];W(e,U()),e.updateOptions({inlineSuggest:{enabled:true,mode:"subwordSmart"}});try{let r=M(e);if(!r)return core.logger.warn("Completion is not registered properly. State not found."),pe();let i=G(t,e,o);i&&n.push(i);let s=Y(t,e,r,o);n.push(s);let l={deregister:()=>{n.forEach(p=>p.dispose()),L.clear(),k(e),P=null;},trigger:()=>X(e)};return P=l,l}catch(r){return o.onError?o.onError(r):core.logger.report(r),{deregister:()=>{n.forEach(i=>i.dispose()),k(e),P=null;},trigger:()=>{}}}},pe=()=>({deregister:()=>{},trigger:()=>{}});var lt=v;exports.CompletionCopilot=v;exports.Copilot=lt;exports.registerCompletion=me;
|
package/build/index.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import {Copilot,logger,HTTP}from'@monacopilot/core';var q=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`,K=t=>t.charAt(0).toUpperCase()+t.slice(1),O=(t,e,o={})=>{if(e<=0)return "";let n=t.split(`
|
|
2
|
+
`),r=n.length;if(e>=r)return t;if(o.from==="end"){let s=n.slice(-e);return s.every(l=>l==="")?`
|
|
3
|
+
`.repeat(e):s.join(`
|
|
4
|
+
`)}let i=n.slice(0,e);return i.every(s=>s==="")?`
|
|
5
|
+
`.repeat(e):i.join(`
|
|
6
|
+
`)};var J=t=>!t||t.length===0?"":t.map(({path:e,content:o})=>`
|
|
7
|
+
<related_file>
|
|
8
|
+
<filePath>${e}</filePath>
|
|
9
|
+
<fileContent>
|
|
10
|
+
\`\`\`
|
|
11
|
+
${o}
|
|
12
|
+
\`\`\`
|
|
13
|
+
</fileContent>
|
|
14
|
+
</related_file>`.trim()).join(`
|
|
15
|
+
|
|
16
|
+
`),j=t=>{let{technologies:e=[],filename:o,relatedFiles:n,language:r,textBeforeCursor:i="",textAfterCursor:s="",editorState:{completionMode:l}}=t,p=q([r,...e].filter(a=>typeof a=="string"&&!!a)),d=`
|
|
17
|
+
You are an expert code completion assistant.
|
|
18
|
+
|
|
19
|
+
**Context:**
|
|
20
|
+
File: ${o||"Untitled"}
|
|
21
|
+
Language: ${r||"Undetermined"}
|
|
22
|
+
Mode: ${l}
|
|
23
|
+
Stack: ${p||"None"}`,c=`
|
|
24
|
+
**Related Files:**
|
|
25
|
+
${J(n)}
|
|
26
|
+
|
|
27
|
+
**Source:**
|
|
28
|
+
\`\`\`
|
|
29
|
+
${i}<cursor>${s}
|
|
30
|
+
\`\`\`
|
|
31
|
+
|
|
32
|
+
${K(l)} the code at <cursor>.
|
|
33
|
+
|
|
34
|
+
Output only the raw code to be inserted at the cursor location without any additional text or comments.`;return {system:d,user:c}};var v=class extends Copilot{async complete(e){let{body:o,options:n}=e,{customPrompt:r,headers:i}=n??{},{completionMetadata:s}=o,{text:l,raw:p,error:d}=await this.makeAIRequest(s,{customPrompt:r,customHeaders:i});return {completion:l,raw:p,error:d}}getDefaultPrompt(e){return j(e)}};var V=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1];var H=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),E=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),B=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var T=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 A=class A{constructor(){this.cache=new T(A.MAX_CACHE_SIZE);}get(e,o){return this.cache.getAll().filter(n=>this.isValidCacheItem(n,e,o))}add(e){this.cache.enqueue(e);}clear(){this.cache.clear();}isValidCacheItem(e,o,n){let r=n.getValueInRange(e.range),i=E(o,n);return i.length<e.textBeforeCursor.length||!i.startsWith(e.textBeforeCursor)?false:this.isPositionValid(e,o,r)}isPositionValid(e,o,n){let{range:r,completion:i}=e,{startLineNumber:s,startColumn:l,endLineNumber:p,endColumn:d}=r,{lineNumber:c,column:a}=o;if(!i.startsWith(n))return false;let u=c===s&&a===l;if(s===p)return u||c===s&&a>=l&&a<=d;let g=c>s&&c<p?true:c===s&&a>=l||c===p&&a<=d;return u||g}};A.MAX_CACHE_SIZE=10;var I=A;var S=class{constructor(e,o,n){this.formattedCompletion="";this.currentColumn=0;this.textBeforeCursorInLine="";this.formattedCompletion=e,this.currentColumn=o,this.textBeforeCursorInLine=n;}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}indentByColumn(){let e=this.formattedCompletion.split(`
|
|
35
|
+
`);if(e.length<=1||this.textBeforeCursorInLine.trim()!=="")return this;let o=" ".repeat(this.currentColumn-1);return this.formattedCompletion=e[0]+`
|
|
36
|
+
`+e.slice(1).map(n=>o+n).join(`
|
|
37
|
+
`),this}removeMarkdownCodeBlocks(e){let o=/```[\s\S]*?```/g,n=e,r;for(;(r=o.exec(e))!==null;){let i=r[0],s=i.split(`
|
|
38
|
+
`).slice(1,-1).join(`
|
|
39
|
+
`);n=n.replace(i,s);}return n.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
40
|
+
|
|
41
|
+
`),this}build(){return this.formattedCompletion}};var w=class{constructor(e){this.monaco=e;}computeInsertionRange(e,o,n){if(!o)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let r=n.getOffsetAt(e),i=n.getValue().substring(0,r),s=n.getValue().substring(r),l=0,p=0,d=0,c=0,a=o.length,u=i.length,g=s.length;if(r>=n.getValue().length)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(g===0)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let y=Math.min(a,u);for(let m=1;m<=y;m++){let b=o.substring(0,m),Q=i.slice(-m);b===Q&&(c=m);}let C=Math.min(a,g);for(let m=0;m<C&&o[m]===s[m];m++)l++;for(let m=1;m<=C;m++)o.slice(-m)===s.slice(0,m)&&(p=m);if(d=Math.max(l,p),d===0){for(let m=1;m<a;m++)if(s.startsWith(o.substring(m))){d=a-m;break}}let R=c>0?n.getPositionAt(r-c):e,h=r+d,f=n.getPositionAt(h);return new this.monaco.Range(R.lineNumber,R.column,f.lineNumber,f.column)}computeCacheRange(e,o){let n=e.lineNumber,r=e.column,i=o.split(`
|
|
42
|
+
`),s=i.length-1,l=n+s,p=s===0?r+i[0].length:i[s].length+1;return new this.monaco.Range(n,r,l,p)}};var z=async t=>{let{endpoint:e,body:o}=t,{completion:n,error:r}=await HTTP.post(e,o,{headers:{"Content-Type":"application/json"},fallbackError:"Error while fetching completion item"});if(r)throw new Error(r);return {completion:n}},$=({pos:t,mdl:e,options:o})=>{let{filename:n,language:r,technologies:i,relatedFiles:s,maxContextLines:l}=o,p=oe(t,e),c=!!s?.length?3:2,a=l?Math.floor(l/c):void 0,u=(h,f,m)=>{let b=h(t,e);return f?O(b,f,m):b},g=(h,f)=>!h||!f?h:h.map(({content:m,...b})=>({...b,content:O(m,f)})),y=u(E,a,{from:"end"}),C=u(B,a),R=g(s,a);return {filename:n,language:r,technologies:i,relatedFiles:R,textBeforeCursor:y,textAfterCursor:C,cursorPosition:t,editorState:{completionMode:p}}},oe=(t,e)=>{let o=V(t,e),n=B(t,e);return o?"insert":n.trim()?"complete":"continue"};var F=(t,e=600,o=200)=>{let n=null,r=0,i=null,s=null,l=false,p=(...d)=>{if(l)return Promise.resolve(void 0);i=d;let c=Date.now(),a=c-r;r=c,n&&(clearTimeout(n),n=null);let u=a<o?e:o;return s=new Promise((g,y)=>{n=setTimeout(async()=>{l=true;try{if(i){let C=await t(...i);g(C);}else g(void 0);}catch(C){y(C);}finally{l=false,n=null,i=null;}},u);}),s};return p.cancel=()=>{n&&(clearTimeout(n),n=null),i=null;},p};var x=t=>({items:t,enableForwardStability:true,suppressSuggestions:true});var ie=t=>({onTyping:F(t,600,200),onIdle:F(t,600,400),onDemand:F(t,0,0)}),L=new I,_=async({monaco:t,mdl:e,pos:o,token:n,isCompletionAccepted:r,options:i})=>{let{trigger:s="onIdle",endpoint:l,enableCaching:p=true,onError:d,requestHandler:c}=i;if(p){let a=L.get(o,e).map(u=>({insertText:u.completion,range:u.range}));if(a.length>0)return x(a)}if(n.isCancellationRequested||r)return x([]);try{let u=ie(c??z)[s];n.onCancellationRequested(()=>{u.cancel();});let g=$({pos:o,mdl:e,options:i}),{completion:y}=await u({endpoint:l,body:{completionMetadata:g}});if(y){let C=new S(y,o.column,H(o,e)).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().indentByColumn().build(),R=new w(t),h=R.computeInsertionRange(o,C,e),f=R.computeCacheRange(o,C);return p&&L.add({completion:C,range:f,textBeforeCursor:E(o,e)}),x([{insertText:C,range:h}])}}catch(a){if(se(a))return x([]);d?d(a):logger.warn("Cannot provide completion",a);}return x([])},se=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":false;var N=new WeakMap,M=t=>N.get(t),W=(t,e)=>{N.set(t,e);},k=t=>{N.delete(t);},U=()=>({isCompletionAccepted:false,isCompletionVisible:false,isExplicitlyTriggered:false,hasRejectedCurrentCompletion:false});var G=(t,e,o)=>{let n=M(e);return n?t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(r,i,s,l)=>{if(!(o.trigger==="onDemand"&&!n.isExplicitlyTriggered))return _({monaco:t,mdl:r,pos:i,token:l,isCompletionAccepted:n.isCompletionAccepted,options:o})},handleItemDidShow:(r,i,s)=>{n.isExplicitlyTriggered=false,n.hasRejectedCurrentCompletion=false,!n.isCompletionAccepted&&(n.isCompletionVisible=true,o.onCompletionShown?.(s,i.range));},freeInlineCompletions:()=>{}}):null},X=t=>{let e=M(t);if(!e){logger.warn("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isExplicitlyTriggered=true,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{});};var ae={TAB:(t,e)=>e.keyCode===t.KeyCode.Tab,CMD_RIGHT_ARROW:(t,e)=>e.keyCode===t.KeyCode.RightArrow&&e.metaKey},D=class{constructor(e,o,n){this.monaco=e;this.state=o;this.options=n;}handleKeyEvent(e){let o={monaco:this.monaco,event:e,state:this.state,options:this.options};this.handleCompletionAcceptance(o),this.handleCompletionRejection(o);}handleCompletionAcceptance(e){return e.state.isCompletionVisible&&this.isAcceptanceKey(e.event)?(e.options.onCompletionAccepted?.(),e.state.isCompletionAccepted=true,e.state.isCompletionVisible=false,true):(e.state.isCompletionAccepted=false,false)}handleCompletionRejection(e){return this.shouldRejectCompletion(e)?(e.options.onCompletionRejected?.(),e.state.hasRejectedCurrentCompletion=true,true):false}shouldRejectCompletion(e){return e.state.isCompletionVisible&&!e.state.hasRejectedCurrentCompletion&&!e.state.isCompletionAccepted&&!this.isAcceptanceKey(e.event)}isAcceptanceKey(e){return Object.values(ae).some(o=>o(this.monaco,e))}},Y=(t,e,o,n)=>{let r=new D(t,o,n);return e.onKeyDown(i=>r.handleKeyEvent(i))};var P=null,me=(t,e,o)=>{P&&P.deregister();let n=[];W(e,U()),e.updateOptions({inlineSuggest:{enabled:true,mode:"subwordSmart"}});try{let r=M(e);if(!r)return logger.warn("Completion is not registered properly. State not found."),pe();let i=G(t,e,o);i&&n.push(i);let s=Y(t,e,r,o);n.push(s);let l={deregister:()=>{n.forEach(p=>p.dispose()),L.clear(),k(e),P=null;},trigger:()=>X(e)};return P=l,l}catch(r){return o.onError?o.onError(r):logger.report(r),{deregister:()=>{n.forEach(i=>i.dispose()),k(e),P=null;},trigger:()=>{}}}},pe=()=>({deregister:()=>{},trigger:()=>{}});var lt=v;export{v as CompletionCopilot,lt as Copilot,me as registerCompletion};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "monacopilot",
|
|
3
|
-
"version": "0.19.
|
|
3
|
+
"version": "0.19.4",
|
|
4
4
|
"description": "AI auto-completion plugin for Monaco Editor",
|
|
5
5
|
"main": "./build/index.js",
|
|
6
6
|
"module": "./build/index.mjs",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"license": "MIT",
|
|
38
38
|
"author": "Arshad Yaseen <m@arshadyaseen.com> (https://arshadyaseen.com)",
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@monacopilot/core": "0.19.
|
|
40
|
+
"@monacopilot/core": "0.19.4"
|
|
41
41
|
},
|
|
42
42
|
"scripts": {
|
|
43
43
|
"build": "tsup src/index.ts",
|