monacopilot 0.19.17 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -1
- package/build/index.d.mts +6 -67
- package/build/index.d.ts +6 -67
- package/build/index.js +14 -21
- package/build/index.mjs +14 -21
- package/package.json +2 -2
package/README.md
CHANGED
package/build/index.d.mts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { CustomPrompt, Copilot as Copilot$1, PromptData } from '@monacopilot/core';
|
|
2
|
-
export {
|
|
1
|
+
import { Endpoint, Filename, Technologies, RelatedFile, BaseCopilotMetadata, CustomPrompt, Copilot as Copilot$1, PromptData } from '@monacopilot/core';
|
|
2
|
+
export { CopilotOptions, CustomCopilotModel, MistralModel, Model, Provider } from '@monacopilot/core';
|
|
3
3
|
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
4
4
|
|
|
5
5
|
type Monaco = typeof monaco;
|
|
6
6
|
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
7
|
-
type CursorPosition = monaco.IPosition;
|
|
8
7
|
type EditorRange = monaco.IRange;
|
|
9
8
|
|
|
10
9
|
type FetchCompletionItemHandler = (params: FetchCompletionItemParams) => Promise<FetchCompletionItemReturn>;
|
|
@@ -16,24 +15,7 @@ interface FetchCompletionItemParams {
|
|
|
16
15
|
body: CompletionRequestBody;
|
|
17
16
|
}
|
|
18
17
|
|
|
19
|
-
type
|
|
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
|
-
};
|
|
18
|
+
type CompletionMetadata = BaseCopilotMetadata;
|
|
37
19
|
interface RegisterCompletionOptions {
|
|
38
20
|
/**
|
|
39
21
|
* Language of the current model
|
|
@@ -49,7 +31,6 @@ interface RegisterCompletionOptions {
|
|
|
49
31
|
* Options:
|
|
50
32
|
* - `'onIdle'`: Provides completions after a brief pause in typing.
|
|
51
33
|
* - `'onTyping'`: Provides completions in real-time as you type.
|
|
52
|
-
* - *Note:* Best suited for models with low response latency (e.g., Groq).
|
|
53
34
|
* - *Consideration:* May initiate additional background requests to deliver real-time suggestions.
|
|
54
35
|
* - `'onDemand'`: Completions are not provided automatically. You need to trigger the completion manually, possibly by using the `trigger` function from `registerCompletion` return.
|
|
55
36
|
*
|
|
@@ -159,11 +140,12 @@ interface CompletionRequestOptions {
|
|
|
159
140
|
headers?: Record<string, string>;
|
|
160
141
|
/**
|
|
161
142
|
* Custom prompt generator function for the completion request.
|
|
162
|
-
* This function allows you to override the default
|
|
143
|
+
* This function allows you to override the default prompt
|
|
163
144
|
* used in the completion request, providing more control over the AI's context and behavior.
|
|
164
145
|
*
|
|
165
146
|
* @param completionMetadata - Metadata about the current completion context
|
|
166
|
-
* @returns
|
|
147
|
+
* @returns A partial PromptData object that can override context and/or instruction
|
|
148
|
+
* @see {@link https://github.com/arshad-yaseen/monacopilot/blob/main/packages/monacopilot/src/prompt.ts | Monacopilot default prompt implementation}
|
|
167
149
|
*/
|
|
168
150
|
customPrompt?: CustomPrompt<CompletionMetadata>;
|
|
169
151
|
}
|
|
@@ -181,49 +163,6 @@ interface CompletionResponse {
|
|
|
181
163
|
*/
|
|
182
164
|
raw?: unknown;
|
|
183
165
|
}
|
|
184
|
-
type CompletionMode = 'insert' | 'complete' | 'continue';
|
|
185
|
-
interface CompletionMetadata {
|
|
186
|
-
/**
|
|
187
|
-
* The programming language of the code.
|
|
188
|
-
*/
|
|
189
|
-
language: string | undefined;
|
|
190
|
-
/**
|
|
191
|
-
* The name of the file being edited.
|
|
192
|
-
*/
|
|
193
|
-
filename: Filename | undefined;
|
|
194
|
-
/**
|
|
195
|
-
* The technologies used in the completion.
|
|
196
|
-
*/
|
|
197
|
-
technologies: Technologies | undefined;
|
|
198
|
-
/**
|
|
199
|
-
* Additional context from related files.
|
|
200
|
-
*/
|
|
201
|
-
relatedFiles: RelatedFile[] | undefined;
|
|
202
|
-
/**
|
|
203
|
-
* The text that appears after the cursor.
|
|
204
|
-
*/
|
|
205
|
-
textAfterCursor: string;
|
|
206
|
-
/**
|
|
207
|
-
* The text that appears before the cursor.
|
|
208
|
-
*/
|
|
209
|
-
textBeforeCursor: string;
|
|
210
|
-
/**
|
|
211
|
-
* The current cursor position.
|
|
212
|
-
*/
|
|
213
|
-
cursorPosition: CursorPosition;
|
|
214
|
-
/**
|
|
215
|
-
* The current state of the editor.
|
|
216
|
-
*/
|
|
217
|
-
editorState: {
|
|
218
|
-
/**
|
|
219
|
-
* The mode of the completion.
|
|
220
|
-
* - `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.
|
|
221
|
-
* - `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.
|
|
222
|
-
* - `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.
|
|
223
|
-
*/
|
|
224
|
-
completionMode: CompletionMode;
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
166
|
|
|
228
167
|
declare class CompletionCopilot extends Copilot$1<CompletionMetadata> {
|
|
229
168
|
complete(request: CompletionRequest): Promise<CompletionResponse>;
|
package/build/index.d.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { CustomPrompt, Copilot as Copilot$1, PromptData } from '@monacopilot/core';
|
|
2
|
-
export {
|
|
1
|
+
import { Endpoint, Filename, Technologies, RelatedFile, BaseCopilotMetadata, CustomPrompt, Copilot as Copilot$1, PromptData } from '@monacopilot/core';
|
|
2
|
+
export { CopilotOptions, CustomCopilotModel, MistralModel, Model, Provider } from '@monacopilot/core';
|
|
3
3
|
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
|
|
4
4
|
|
|
5
5
|
type Monaco = typeof monaco;
|
|
6
6
|
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
7
|
-
type CursorPosition = monaco.IPosition;
|
|
8
7
|
type EditorRange = monaco.IRange;
|
|
9
8
|
|
|
10
9
|
type FetchCompletionItemHandler = (params: FetchCompletionItemParams) => Promise<FetchCompletionItemReturn>;
|
|
@@ -16,24 +15,7 @@ interface FetchCompletionItemParams {
|
|
|
16
15
|
body: CompletionRequestBody;
|
|
17
16
|
}
|
|
18
17
|
|
|
19
|
-
type
|
|
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
|
-
};
|
|
18
|
+
type CompletionMetadata = BaseCopilotMetadata;
|
|
37
19
|
interface RegisterCompletionOptions {
|
|
38
20
|
/**
|
|
39
21
|
* Language of the current model
|
|
@@ -49,7 +31,6 @@ interface RegisterCompletionOptions {
|
|
|
49
31
|
* Options:
|
|
50
32
|
* - `'onIdle'`: Provides completions after a brief pause in typing.
|
|
51
33
|
* - `'onTyping'`: Provides completions in real-time as you type.
|
|
52
|
-
* - *Note:* Best suited for models with low response latency (e.g., Groq).
|
|
53
34
|
* - *Consideration:* May initiate additional background requests to deliver real-time suggestions.
|
|
54
35
|
* - `'onDemand'`: Completions are not provided automatically. You need to trigger the completion manually, possibly by using the `trigger` function from `registerCompletion` return.
|
|
55
36
|
*
|
|
@@ -159,11 +140,12 @@ interface CompletionRequestOptions {
|
|
|
159
140
|
headers?: Record<string, string>;
|
|
160
141
|
/**
|
|
161
142
|
* Custom prompt generator function for the completion request.
|
|
162
|
-
* This function allows you to override the default
|
|
143
|
+
* This function allows you to override the default prompt
|
|
163
144
|
* used in the completion request, providing more control over the AI's context and behavior.
|
|
164
145
|
*
|
|
165
146
|
* @param completionMetadata - Metadata about the current completion context
|
|
166
|
-
* @returns
|
|
147
|
+
* @returns A partial PromptData object that can override context and/or instruction
|
|
148
|
+
* @see {@link https://github.com/arshad-yaseen/monacopilot/blob/main/packages/monacopilot/src/prompt.ts | Monacopilot default prompt implementation}
|
|
167
149
|
*/
|
|
168
150
|
customPrompt?: CustomPrompt<CompletionMetadata>;
|
|
169
151
|
}
|
|
@@ -181,49 +163,6 @@ interface CompletionResponse {
|
|
|
181
163
|
*/
|
|
182
164
|
raw?: unknown;
|
|
183
165
|
}
|
|
184
|
-
type CompletionMode = 'insert' | 'complete' | 'continue';
|
|
185
|
-
interface CompletionMetadata {
|
|
186
|
-
/**
|
|
187
|
-
* The programming language of the code.
|
|
188
|
-
*/
|
|
189
|
-
language: string | undefined;
|
|
190
|
-
/**
|
|
191
|
-
* The name of the file being edited.
|
|
192
|
-
*/
|
|
193
|
-
filename: Filename | undefined;
|
|
194
|
-
/**
|
|
195
|
-
* The technologies used in the completion.
|
|
196
|
-
*/
|
|
197
|
-
technologies: Technologies | undefined;
|
|
198
|
-
/**
|
|
199
|
-
* Additional context from related files.
|
|
200
|
-
*/
|
|
201
|
-
relatedFiles: RelatedFile[] | undefined;
|
|
202
|
-
/**
|
|
203
|
-
* The text that appears after the cursor.
|
|
204
|
-
*/
|
|
205
|
-
textAfterCursor: string;
|
|
206
|
-
/**
|
|
207
|
-
* The text that appears before the cursor.
|
|
208
|
-
*/
|
|
209
|
-
textBeforeCursor: string;
|
|
210
|
-
/**
|
|
211
|
-
* The current cursor position.
|
|
212
|
-
*/
|
|
213
|
-
cursorPosition: CursorPosition;
|
|
214
|
-
/**
|
|
215
|
-
* The current state of the editor.
|
|
216
|
-
*/
|
|
217
|
-
editorState: {
|
|
218
|
-
/**
|
|
219
|
-
* The mode of the completion.
|
|
220
|
-
* - `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.
|
|
221
|
-
* - `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.
|
|
222
|
-
* - `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.
|
|
223
|
-
*/
|
|
224
|
-
completionMode: CompletionMode;
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
166
|
|
|
228
167
|
declare class CompletionCopilot extends Copilot$1<CompletionMetadata> {
|
|
229
168
|
complete(request: CompletionRequest): Promise<CompletionResponse>;
|
package/build/index.js
CHANGED
|
@@ -1,28 +1,21 @@
|
|
|
1
|
-
'use strict';var core=require('@monacopilot/core');var
|
|
2
|
-
`),r=
|
|
1
|
+
'use strict';var core=require('@monacopilot/core');var k=n=>!n||n.length===0?"":n.length===1?n[0]:`${n.slice(0,-1).join(", ")} and ${n.slice(-1)}`;var D=(n,e,o={})=>{if(e<=0)return "";let t=n.split(`
|
|
2
|
+
`),r=t.length;if(e>=r)return n;if(o.truncateDirection==="keepEnd"){let s=t.slice(-e);return s.every(a=>a==="")?`
|
|
3
3
|
`.repeat(e):s.join(`
|
|
4
|
-
`)}let i=
|
|
4
|
+
`)}let i=t.slice(0,e);return i.every(s=>s==="")?`
|
|
5
5
|
`.repeat(e):i.join(`
|
|
6
|
-
`)};var
|
|
7
|
-
${
|
|
6
|
+
`)};var oe="<|developer_cursor_is_here|>",B=n=>({instruction:ne(),context:re(n),fileContent:ie(n)}),ne=()=>"You are an expert code assistant completing code in an editor. Provide concise, accurate code that seamlessly integrates with the existing context.",re=n=>{let{technologies:e=[],filename:o,relatedFiles:t=[],language:r}=n,i=k([r,...e].filter(l=>!!l)),s=t.length===0?"":t.map(({path:l,content:p})=>`### ${l}
|
|
7
|
+
${p}`).join(`
|
|
8
8
|
|
|
9
|
-
`),
|
|
9
|
+
`),a=[i?`Technology stack: ${i}`:"",`File: ${o||"unknown"}`].filter(Boolean).join(`
|
|
10
|
+
`);return `${s?`${s}
|
|
10
11
|
|
|
11
|
-
|
|
12
|
-
Mode: ${a}
|
|
13
|
-
|
|
14
|
-
Here is the code context with the ${N} marker indicating where to ${l.toLowerCase()} the code:
|
|
15
|
-
\`\`\`
|
|
16
|
-
${i}${N}${s}
|
|
12
|
+
`:""}${a}`},ie=n=>{let{textBeforeCursor:e,textAfterCursor:o}=n;return `**Current code:**
|
|
17
13
|
\`\`\`
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
`+
|
|
21
|
-
`);
|
|
22
|
-
`+e.slice(1).map(r=>{let i=r.length-r.trimStart().length,s=Math.min(o,i),a=r.slice(s);return " ".repeat(this.currentColumn-1)+a}).join(`
|
|
23
|
-
`),this)}removeMarkdownCodeBlocks(e){let t=e.split(`
|
|
24
|
-
`),o=[],r=false;for(let i=0;i<t.length;i++){let s=t[i],a=s.trim().startsWith("```");if(a&&!r){r=true;continue}if(a&&r){r=false;continue}o.push(s);}return o.join(`
|
|
14
|
+
${e}${oe}${o}
|
|
15
|
+
\`\`\``};var v=class extends core.Copilot{async complete(e){let{body:o,options:t}=e,{customPrompt:r,headers:i}=t??{},{completionMetadata:s}=o,{text:a,raw:l,error:p}=await this.makeAIRequest(s,{customPrompt:r,customHeaders:i});return {completion:a,raw:l,error:p}}getDefaultPrompt(e){return B(e)}};var f=(n,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:n.lineNumber,endColumn:n.column}),j=(n,e)=>e.getValueInRange({startLineNumber:n.lineNumber,startColumn:n.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 P=class P{constructor(){this.cache=new T(P.MAX_CACHE_SIZE);}get(e,o){return this.cache.getAll().filter(t=>this.isValidCacheItem(t,e,o))}add(e){e.completion.trim()&&this.cache.enqueue(e);}clear(){this.cache.clear();}isValidCacheItem(e,o,t){let r=e.textBeforeCursor.trim(),i=f(o,t),s=i,a=t.getLineContent(o.lineNumber);if(o.column===a.length+1&&o.lineNumber<t.getLineCount()){let p=t.getLineContent(o.lineNumber+1);s=i+`
|
|
16
|
+
`+p;}if(!(s.trim().includes(r)||r.includes(s.trim())))return false;let l=t.getValueInRange(e.range);return this.isPartialMatch(l,e.completion)?this.isPositionValid(e,o):false}isPartialMatch(e,o){let t=e.trim(),r=o.trim();return r.startsWith(t)||t.startsWith(r)}isPositionValid(e,o){let{range:t}=e,{startLineNumber:r,startColumn:i,endLineNumber:s,endColumn:a}=t,{lineNumber:l,column:p}=o;return l<r||l>s?false:r===s?p>=i-1&&p<=a+1:l===r?p>=i-1:l===s?p<=a+1:true}};P.MAX_CACHE_SIZE=20;var M=P;var L=class{constructor(e){this.formattedCompletion="";this.formattedCompletion=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=e.split(`
|
|
17
|
+
`),t=[],r=false;for(let i=0;i<o.length;i++){let s=o[i],a=s.trim().startsWith("```");if(a&&!r){r=true;continue}if(a&&r){r=false;continue}t.push(s);}return t.join(`
|
|
25
18
|
`)}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
26
19
|
|
|
27
|
-
`),this}build(){return this.formattedCompletion}};var
|
|
28
|
-
`),s=i.length-1,a=
|
|
20
|
+
`),this}build(){return this.formattedCompletion}};var O=class{findOverlaps(e,o,t){if(!e)return {startOverlapLength:0,maxOverlapLength:0};let r=e.length,i=o.length,s=t.length,a=0,l=0,p=0,d=Math.min(r,i);for(let c=1;c<=d;c++){let C=e.substring(0,c),g=o.slice(-c);C===g&&(p=c);}let m=Math.min(r,s);for(let c=0;c<m&&e[c]===t[c];c++)a++;for(let c=1;c<=m;c++)e.slice(-c)===t.slice(0,c)&&(l=c);let u=Math.max(a,l);if(u===0){for(let c=1;c<r;c++)if(t.startsWith(e.substring(c))){u=r-c;break}}return {startOverlapLength:p,maxOverlapLength:u}}};var A=class{constructor(e){this.monaco=e;this.textOverlapCalculator=new O;}computeInsertionRange(e,o,t){if(!o)return this.createEmptyRange(e);let r=t.getOffsetAt(e),i=t.getValue().substring(0,r),s=t.getValue().substring(r);if(r>=t.getValue().length)return this.createEmptyRange(e);if(s.length===0)return this.createEmptyRange(e);let{startOverlapLength:a,maxOverlapLength:l}=this.textOverlapCalculator.findOverlaps(o,i,s),p=a>0?t.getPositionAt(r-a):e,d=r+l,m=t.getPositionAt(d);return new this.monaco.Range(p.lineNumber,p.column,m.lineNumber,m.column)}computeCacheRange(e,o){let t=e.lineNumber,r=e.column,i=o.split(`
|
|
21
|
+
`),s=i.length-1,a=t+s,l=s===0?r+i[0].length:i[s].length+1;return new this.monaco.Range(t,r,a,l)}createEmptyRange(e){return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column)}};var K=100,U=true,V="onIdle",H=120,$=400,z=0;var G=async n=>{let{endpoint:e,body:o}=n,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok)throw new Error(`Error while fetching completion item: ${t.statusText}`);let{completion:r,error:i}=await t.json();if(i)throw new Error(i);return {completion:r}},W=({pos:n,mdl:e,options:o})=>{let{filename:t,language:r,technologies:i,relatedFiles:s,maxContextLines:a=K}=o,p=s&&s.length>0?3:2,d=a?Math.floor(a/p):void 0,m=(E,y,S)=>{let b=E(n,e);return y?D(b,y,S):b},u=(E,y)=>!E||!y?E:E.map(({content:S,...b})=>({...b,content:D(S,y)})),c=m(f,d,{truncateDirection:"keepEnd"}),C=m(j,d,{truncateDirection:"keepStart"}),g=u(s,d);return {filename:t,language:r,technologies:i,relatedFiles:g,textBeforeCursor:c,textAfterCursor:C,cursorPosition:n}};var X=(n,e=300)=>{let o=null,t=null,r=(...i)=>{if(t)return t.args=i,t.promise;let s,a,l=new Promise((p,d)=>{s=p,a=d;});return t={args:i,promise:l,resolve:s,reject:a},o&&(clearTimeout(o),o=null),o=setTimeout(async()=>{let p=t;if(p){t=null,o=null;try{let d=await n(...p.args);p.resolve(d);}catch(d){p.reject(d);}}},e),l};return r.cancel=()=>{o&&(clearTimeout(o),o=null),t&&(t.reject(new Error("Cancelled")),t=null);},r};var Y=n=>typeof n=="string"?n==="Cancelled"||n==="AbortError":n instanceof Error?n.message==="Cancelled"||n.name==="AbortError":false;var h=n=>({items:n,enableForwardStability:true});var I=new M,Z=async({monaco:n,mdl:e,pos:o,token:t,isCompletionAccepted:r,options:i})=>{let{trigger:s=V,endpoint:a,enableCaching:l=U,onError:p,requestHandler:d}=i;if(l&&!r){let m=I.get(o,e).map(u=>({insertText:u.completion,range:u.range}));if(m.length>0)return h(m)}if(t.isCancellationRequested)return h([]);try{let m=X(d??G,{onTyping:H,onIdle:$,onDemand:z}[s]);t.onCancellationRequested(()=>{m.cancel();});let u=W({pos:o,mdl:e,options:i}),{completion:c}=await m({endpoint:a,body:{completionMetadata:u}});if(c){let C=new L(c).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),g=new A(n);return l&&I.add({completion:C,range:g.computeCacheRange(o,C),textBeforeCursor:f(o,e)}),h([{insertText:C,range:g.computeInsertionRange(o,C,e)}])}}catch(m){if(Y(m))return h([]);p?p(m):core.logger.warn("Cannot provide completion",m);}return h([])};var N=new WeakMap,x=n=>N.get(n),J=(n,e)=>{N.set(n,e);},w=n=>{N.delete(n);},Q=()=>({isCompletionAccepted:false,isCompletionVisible:false,isExplicitlyTriggered:false,hasRejectedCurrentCompletion:false});var ee=(n,e,o)=>{let t=x(e);return t?n.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(r,i,s,a)=>{if(!(o.trigger==="onDemand"&&!t.isExplicitlyTriggered))return Z({monaco:n,mdl:r,pos:i,token:a,isCompletionAccepted:t.isCompletionAccepted,options:o})},handleItemDidShow:(r,i,s)=>{t.isExplicitlyTriggered=false,t.hasRejectedCurrentCompletion=false,!t.isCompletionAccepted&&(t.isCompletionVisible=true,o.onCompletionShown?.(s,i.range));},freeInlineCompletions:()=>{}}):null};var le={TAB:(n,e)=>e.keyCode===n.KeyCode.Tab,CMD_RIGHT_ARROW:(n,e)=>e.keyCode===n.KeyCode.RightArrow&&e.metaKey},F=class{constructor(e,o,t){this.monaco=e;this.state=o;this.options=t;}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(le).some(o=>o(this.monaco,e))}},te=(n,e,o,t)=>{let r=new F(n,o,t);return e.onKeyDown(i=>r.handleKeyEvent(i))};var R=null,pe=(n,e,o)=>{R&&R.deregister();let t=[];J(e,Q()),e.updateOptions({inlineSuggest:{enabled:true}});try{let r=x(e);if(!r)return core.logger.warn("Completion is not registered properly. State not found."),me();let i=ee(n,e,o);i&&t.push(i);let s=te(n,e,r,o);t.push(s);let a={deregister:()=>{t.forEach(l=>l.dispose()),I.clear(),w(e),R=null;},trigger:()=>ce(e)};return R=a,a}catch(r){return o.onError?o.onError(r):core.logger.report(r),{deregister:()=>{t.forEach(i=>i.dispose()),w(e),R=null;},trigger:()=>{}}}},ce=n=>{let e=x(n);if(!e){core.logger.warn("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isExplicitlyTriggered=true,n.trigger("keyboard","editor.action.inlineSuggest.trigger",{});},me=()=>({deregister:()=>{},trigger:()=>{}});var ut=v;exports.CompletionCopilot=v;exports.Copilot=ut;exports.registerCompletion=pe;
|
package/build/index.mjs
CHANGED
|
@@ -1,28 +1,21 @@
|
|
|
1
|
-
import {Copilot,logger}from'@monacopilot/core';var
|
|
2
|
-
`),r=
|
|
1
|
+
import {Copilot,logger}from'@monacopilot/core';var k=n=>!n||n.length===0?"":n.length===1?n[0]:`${n.slice(0,-1).join(", ")} and ${n.slice(-1)}`;var D=(n,e,o={})=>{if(e<=0)return "";let t=n.split(`
|
|
2
|
+
`),r=t.length;if(e>=r)return n;if(o.truncateDirection==="keepEnd"){let s=t.slice(-e);return s.every(a=>a==="")?`
|
|
3
3
|
`.repeat(e):s.join(`
|
|
4
|
-
`)}let i=
|
|
4
|
+
`)}let i=t.slice(0,e);return i.every(s=>s==="")?`
|
|
5
5
|
`.repeat(e):i.join(`
|
|
6
|
-
`)};var
|
|
7
|
-
${
|
|
6
|
+
`)};var oe="<|developer_cursor_is_here|>",B=n=>({instruction:ne(),context:re(n),fileContent:ie(n)}),ne=()=>"You are an expert code assistant completing code in an editor. Provide concise, accurate code that seamlessly integrates with the existing context.",re=n=>{let{technologies:e=[],filename:o,relatedFiles:t=[],language:r}=n,i=k([r,...e].filter(l=>!!l)),s=t.length===0?"":t.map(({path:l,content:p})=>`### ${l}
|
|
7
|
+
${p}`).join(`
|
|
8
8
|
|
|
9
|
-
`),
|
|
9
|
+
`),a=[i?`Technology stack: ${i}`:"",`File: ${o||"unknown"}`].filter(Boolean).join(`
|
|
10
|
+
`);return `${s?`${s}
|
|
10
11
|
|
|
11
|
-
|
|
12
|
-
Mode: ${a}
|
|
13
|
-
|
|
14
|
-
Here is the code context with the ${N} marker indicating where to ${l.toLowerCase()} the code:
|
|
15
|
-
\`\`\`
|
|
16
|
-
${i}${N}${s}
|
|
12
|
+
`:""}${a}`},ie=n=>{let{textBeforeCursor:e,textAfterCursor:o}=n;return `**Current code:**
|
|
17
13
|
\`\`\`
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
`+
|
|
21
|
-
`);
|
|
22
|
-
`+e.slice(1).map(r=>{let i=r.length-r.trimStart().length,s=Math.min(o,i),a=r.slice(s);return " ".repeat(this.currentColumn-1)+a}).join(`
|
|
23
|
-
`),this)}removeMarkdownCodeBlocks(e){let t=e.split(`
|
|
24
|
-
`),o=[],r=false;for(let i=0;i<t.length;i++){let s=t[i],a=s.trim().startsWith("```");if(a&&!r){r=true;continue}if(a&&r){r=false;continue}o.push(s);}return o.join(`
|
|
14
|
+
${e}${oe}${o}
|
|
15
|
+
\`\`\``};var v=class extends Copilot{async complete(e){let{body:o,options:t}=e,{customPrompt:r,headers:i}=t??{},{completionMetadata:s}=o,{text:a,raw:l,error:p}=await this.makeAIRequest(s,{customPrompt:r,customHeaders:i});return {completion:a,raw:l,error:p}}getDefaultPrompt(e){return B(e)}};var f=(n,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:n.lineNumber,endColumn:n.column}),j=(n,e)=>e.getValueInRange({startLineNumber:n.lineNumber,startColumn:n.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 P=class P{constructor(){this.cache=new T(P.MAX_CACHE_SIZE);}get(e,o){return this.cache.getAll().filter(t=>this.isValidCacheItem(t,e,o))}add(e){e.completion.trim()&&this.cache.enqueue(e);}clear(){this.cache.clear();}isValidCacheItem(e,o,t){let r=e.textBeforeCursor.trim(),i=f(o,t),s=i,a=t.getLineContent(o.lineNumber);if(o.column===a.length+1&&o.lineNumber<t.getLineCount()){let p=t.getLineContent(o.lineNumber+1);s=i+`
|
|
16
|
+
`+p;}if(!(s.trim().includes(r)||r.includes(s.trim())))return false;let l=t.getValueInRange(e.range);return this.isPartialMatch(l,e.completion)?this.isPositionValid(e,o):false}isPartialMatch(e,o){let t=e.trim(),r=o.trim();return r.startsWith(t)||t.startsWith(r)}isPositionValid(e,o){let{range:t}=e,{startLineNumber:r,startColumn:i,endLineNumber:s,endColumn:a}=t,{lineNumber:l,column:p}=o;return l<r||l>s?false:r===s?p>=i-1&&p<=a+1:l===r?p>=i-1:l===s?p<=a+1:true}};P.MAX_CACHE_SIZE=20;var M=P;var L=class{constructor(e){this.formattedCompletion="";this.formattedCompletion=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=e.split(`
|
|
17
|
+
`),t=[],r=false;for(let i=0;i<o.length;i++){let s=o[i],a=s.trim().startsWith("```");if(a&&!r){r=true;continue}if(a&&r){r=false;continue}t.push(s);}return t.join(`
|
|
25
18
|
`)}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
26
19
|
|
|
27
|
-
`),this}build(){return this.formattedCompletion}};var
|
|
28
|
-
`),s=i.length-1,a=
|
|
20
|
+
`),this}build(){return this.formattedCompletion}};var O=class{findOverlaps(e,o,t){if(!e)return {startOverlapLength:0,maxOverlapLength:0};let r=e.length,i=o.length,s=t.length,a=0,l=0,p=0,d=Math.min(r,i);for(let c=1;c<=d;c++){let C=e.substring(0,c),g=o.slice(-c);C===g&&(p=c);}let m=Math.min(r,s);for(let c=0;c<m&&e[c]===t[c];c++)a++;for(let c=1;c<=m;c++)e.slice(-c)===t.slice(0,c)&&(l=c);let u=Math.max(a,l);if(u===0){for(let c=1;c<r;c++)if(t.startsWith(e.substring(c))){u=r-c;break}}return {startOverlapLength:p,maxOverlapLength:u}}};var A=class{constructor(e){this.monaco=e;this.textOverlapCalculator=new O;}computeInsertionRange(e,o,t){if(!o)return this.createEmptyRange(e);let r=t.getOffsetAt(e),i=t.getValue().substring(0,r),s=t.getValue().substring(r);if(r>=t.getValue().length)return this.createEmptyRange(e);if(s.length===0)return this.createEmptyRange(e);let{startOverlapLength:a,maxOverlapLength:l}=this.textOverlapCalculator.findOverlaps(o,i,s),p=a>0?t.getPositionAt(r-a):e,d=r+l,m=t.getPositionAt(d);return new this.monaco.Range(p.lineNumber,p.column,m.lineNumber,m.column)}computeCacheRange(e,o){let t=e.lineNumber,r=e.column,i=o.split(`
|
|
21
|
+
`),s=i.length-1,a=t+s,l=s===0?r+i[0].length:i[s].length+1;return new this.monaco.Range(t,r,a,l)}createEmptyRange(e){return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column)}};var K=100,U=true,V="onIdle",H=120,$=400,z=0;var G=async n=>{let{endpoint:e,body:o}=n,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok)throw new Error(`Error while fetching completion item: ${t.statusText}`);let{completion:r,error:i}=await t.json();if(i)throw new Error(i);return {completion:r}},W=({pos:n,mdl:e,options:o})=>{let{filename:t,language:r,technologies:i,relatedFiles:s,maxContextLines:a=K}=o,p=s&&s.length>0?3:2,d=a?Math.floor(a/p):void 0,m=(E,y,S)=>{let b=E(n,e);return y?D(b,y,S):b},u=(E,y)=>!E||!y?E:E.map(({content:S,...b})=>({...b,content:D(S,y)})),c=m(f,d,{truncateDirection:"keepEnd"}),C=m(j,d,{truncateDirection:"keepStart"}),g=u(s,d);return {filename:t,language:r,technologies:i,relatedFiles:g,textBeforeCursor:c,textAfterCursor:C,cursorPosition:n}};var X=(n,e=300)=>{let o=null,t=null,r=(...i)=>{if(t)return t.args=i,t.promise;let s,a,l=new Promise((p,d)=>{s=p,a=d;});return t={args:i,promise:l,resolve:s,reject:a},o&&(clearTimeout(o),o=null),o=setTimeout(async()=>{let p=t;if(p){t=null,o=null;try{let d=await n(...p.args);p.resolve(d);}catch(d){p.reject(d);}}},e),l};return r.cancel=()=>{o&&(clearTimeout(o),o=null),t&&(t.reject(new Error("Cancelled")),t=null);},r};var Y=n=>typeof n=="string"?n==="Cancelled"||n==="AbortError":n instanceof Error?n.message==="Cancelled"||n.name==="AbortError":false;var h=n=>({items:n,enableForwardStability:true});var I=new M,Z=async({monaco:n,mdl:e,pos:o,token:t,isCompletionAccepted:r,options:i})=>{let{trigger:s=V,endpoint:a,enableCaching:l=U,onError:p,requestHandler:d}=i;if(l&&!r){let m=I.get(o,e).map(u=>({insertText:u.completion,range:u.range}));if(m.length>0)return h(m)}if(t.isCancellationRequested)return h([]);try{let m=X(d??G,{onTyping:H,onIdle:$,onDemand:z}[s]);t.onCancellationRequested(()=>{m.cancel();});let u=W({pos:o,mdl:e,options:i}),{completion:c}=await m({endpoint:a,body:{completionMetadata:u}});if(c){let C=new L(c).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),g=new A(n);return l&&I.add({completion:C,range:g.computeCacheRange(o,C),textBeforeCursor:f(o,e)}),h([{insertText:C,range:g.computeInsertionRange(o,C,e)}])}}catch(m){if(Y(m))return h([]);p?p(m):logger.warn("Cannot provide completion",m);}return h([])};var N=new WeakMap,x=n=>N.get(n),J=(n,e)=>{N.set(n,e);},w=n=>{N.delete(n);},Q=()=>({isCompletionAccepted:false,isCompletionVisible:false,isExplicitlyTriggered:false,hasRejectedCurrentCompletion:false});var ee=(n,e,o)=>{let t=x(e);return t?n.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(r,i,s,a)=>{if(!(o.trigger==="onDemand"&&!t.isExplicitlyTriggered))return Z({monaco:n,mdl:r,pos:i,token:a,isCompletionAccepted:t.isCompletionAccepted,options:o})},handleItemDidShow:(r,i,s)=>{t.isExplicitlyTriggered=false,t.hasRejectedCurrentCompletion=false,!t.isCompletionAccepted&&(t.isCompletionVisible=true,o.onCompletionShown?.(s,i.range));},freeInlineCompletions:()=>{}}):null};var le={TAB:(n,e)=>e.keyCode===n.KeyCode.Tab,CMD_RIGHT_ARROW:(n,e)=>e.keyCode===n.KeyCode.RightArrow&&e.metaKey},F=class{constructor(e,o,t){this.monaco=e;this.state=o;this.options=t;}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(le).some(o=>o(this.monaco,e))}},te=(n,e,o,t)=>{let r=new F(n,o,t);return e.onKeyDown(i=>r.handleKeyEvent(i))};var R=null,pe=(n,e,o)=>{R&&R.deregister();let t=[];J(e,Q()),e.updateOptions({inlineSuggest:{enabled:true}});try{let r=x(e);if(!r)return logger.warn("Completion is not registered properly. State not found."),me();let i=ee(n,e,o);i&&t.push(i);let s=te(n,e,r,o);t.push(s);let a={deregister:()=>{t.forEach(l=>l.dispose()),I.clear(),w(e),R=null;},trigger:()=>ce(e)};return R=a,a}catch(r){return o.onError?o.onError(r):logger.report(r),{deregister:()=>{t.forEach(i=>i.dispose()),w(e),R=null;},trigger:()=>{}}}},ce=n=>{let e=x(n);if(!e){logger.warn("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isExplicitlyTriggered=true,n.trigger("keyboard","editor.action.inlineSuggest.trigger",{});},me=()=>({deregister:()=>{},trigger:()=>{}});var ut=v;export{v as CompletionCopilot,ut as Copilot,pe as registerCompletion};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "monacopilot",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
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.
|
|
40
|
+
"@monacopilot/core": "1.0.0"
|
|
41
41
|
},
|
|
42
42
|
"peerDependencies": {
|
|
43
43
|
"monaco-editor": ">=0.41.0"
|