monacopilot 0.9.12 → 0.9.13
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 +12 -8
- package/build/index.d.ts +12 -8
- package/build/index.js +17 -13
- package/build/index.mjs +17 -13
- package/package.json +2 -1
package/build/index.d.mts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import * as monaco from 'monaco-editor';
|
|
2
2
|
|
|
3
3
|
type Monaco = typeof monaco;
|
|
4
|
-
|
|
5
4
|
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
6
5
|
|
|
7
6
|
interface CopilotOptions {
|
|
8
|
-
|
|
7
|
+
provider?: CompletionProvider;
|
|
8
|
+
model?: CompletionModel;
|
|
9
9
|
}
|
|
10
10
|
type Endpoint = string;
|
|
11
11
|
type Filename = string;
|
|
@@ -64,12 +64,13 @@ interface CopilotRegistration {
|
|
|
64
64
|
deregister: () => void;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
type CompletionModel = 'llama';
|
|
67
|
+
type CompletionModel = 'llama-3-70b' | 'gpt-4o';
|
|
68
|
+
type CompletionProvider = 'openai' | 'groq';
|
|
68
69
|
interface CompletionRequest {
|
|
69
70
|
completionMetadata: CompletionMetadata;
|
|
70
71
|
}
|
|
71
72
|
interface CompletionResponse {
|
|
72
|
-
completion
|
|
73
|
+
completion: string | null;
|
|
73
74
|
error?: string;
|
|
74
75
|
}
|
|
75
76
|
type CompletionMode = 'fill-in-the-middle' | 'completion';
|
|
@@ -86,24 +87,27 @@ interface CompletionMetadata {
|
|
|
86
87
|
}
|
|
87
88
|
|
|
88
89
|
/**
|
|
89
|
-
* Copilot class for handling completions using the
|
|
90
|
+
* Copilot class for handling completions using the API.
|
|
90
91
|
*/
|
|
91
92
|
declare class Copilot {
|
|
92
93
|
private readonly apiKey;
|
|
93
94
|
private readonly model;
|
|
95
|
+
private readonly provider;
|
|
94
96
|
/**
|
|
95
97
|
* Initializes the Copilot with an API key and optional configuration.
|
|
96
|
-
* @param {string} apiKey - The
|
|
97
|
-
* @param {CopilotOptions} [options] - Optional parameters to configure the completion model.
|
|
98
|
+
* @param {string} apiKey - The API key.
|
|
99
|
+
* @param {CopilotOptions<CompletionProvider>} [options] - Optional parameters to configure the completion model.
|
|
98
100
|
* @throws {Error} If the API key is not provided.
|
|
99
101
|
*/
|
|
100
102
|
constructor(apiKey: string, options?: CopilotOptions);
|
|
101
103
|
/**
|
|
102
|
-
* Sends a completion request to
|
|
104
|
+
* Sends a completion request to API and returns the completion.
|
|
103
105
|
* @param {CompletionRequest} params - The metadata required to generate the completion.
|
|
104
106
|
* @returns {Promise<CompletionResponse>} The completed text snippet or an error.
|
|
105
107
|
*/
|
|
106
108
|
complete({ completionMetadata, }: CompletionRequest): Promise<CompletionResponse>;
|
|
109
|
+
private getEndpoint;
|
|
110
|
+
private getModelId;
|
|
107
111
|
private createRequestBody;
|
|
108
112
|
private createHeaders;
|
|
109
113
|
}
|
package/build/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import * as monaco from 'monaco-editor';
|
|
2
2
|
|
|
3
3
|
type Monaco = typeof monaco;
|
|
4
|
-
|
|
5
4
|
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
6
5
|
|
|
7
6
|
interface CopilotOptions {
|
|
8
|
-
|
|
7
|
+
provider?: CompletionProvider;
|
|
8
|
+
model?: CompletionModel;
|
|
9
9
|
}
|
|
10
10
|
type Endpoint = string;
|
|
11
11
|
type Filename = string;
|
|
@@ -64,12 +64,13 @@ interface CopilotRegistration {
|
|
|
64
64
|
deregister: () => void;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
type CompletionModel = 'llama';
|
|
67
|
+
type CompletionModel = 'llama-3-70b' | 'gpt-4o';
|
|
68
|
+
type CompletionProvider = 'openai' | 'groq';
|
|
68
69
|
interface CompletionRequest {
|
|
69
70
|
completionMetadata: CompletionMetadata;
|
|
70
71
|
}
|
|
71
72
|
interface CompletionResponse {
|
|
72
|
-
completion
|
|
73
|
+
completion: string | null;
|
|
73
74
|
error?: string;
|
|
74
75
|
}
|
|
75
76
|
type CompletionMode = 'fill-in-the-middle' | 'completion';
|
|
@@ -86,24 +87,27 @@ interface CompletionMetadata {
|
|
|
86
87
|
}
|
|
87
88
|
|
|
88
89
|
/**
|
|
89
|
-
* Copilot class for handling completions using the
|
|
90
|
+
* Copilot class for handling completions using the API.
|
|
90
91
|
*/
|
|
91
92
|
declare class Copilot {
|
|
92
93
|
private readonly apiKey;
|
|
93
94
|
private readonly model;
|
|
95
|
+
private readonly provider;
|
|
94
96
|
/**
|
|
95
97
|
* Initializes the Copilot with an API key and optional configuration.
|
|
96
|
-
* @param {string} apiKey - The
|
|
97
|
-
* @param {CopilotOptions} [options] - Optional parameters to configure the completion model.
|
|
98
|
+
* @param {string} apiKey - The API key.
|
|
99
|
+
* @param {CopilotOptions<CompletionProvider>} [options] - Optional parameters to configure the completion model.
|
|
98
100
|
* @throws {Error} If the API key is not provided.
|
|
99
101
|
*/
|
|
100
102
|
constructor(apiKey: string, options?: CopilotOptions);
|
|
101
103
|
/**
|
|
102
|
-
* Sends a completion request to
|
|
104
|
+
* Sends a completion request to API and returns the completion.
|
|
103
105
|
* @param {CompletionRequest} params - The metadata required to generate the completion.
|
|
104
106
|
* @returns {Promise<CompletionResponse>} The completed text snippet or an error.
|
|
105
107
|
*/
|
|
106
108
|
complete({ completionMetadata, }: CompletionRequest): Promise<CompletionResponse>;
|
|
109
|
+
private getEndpoint;
|
|
110
|
+
private getModelId;
|
|
107
111
|
private createRequestBody;
|
|
108
112
|
private createHeaders;
|
|
109
113
|
}
|
package/build/index.js
CHANGED
|
@@ -1,29 +1,33 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);return
|
|
3
|
-
|
|
1
|
+
"use strict";var S=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var ce=(o,e)=>{for(var t in e)S(o,t,{get:e[t],enumerable:!0})},ue=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of pe(e))!de.call(o,n)&&n!==t&&S(o,n,{get:()=>e[n],enumerable:!(r=me(e,n))||r.enumerable});return o};var Ce=o=>ue(S({},"__esModule",{value:!0}),o);var Me={};ce(Me,{Copilot:()=>M,registerCopilot:()=>se});module.exports=Ce(Me);var F={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06"},_={groq:["llama-3-70b"],openai:["gpt-4o"]},k="llama-3-70b",H="groq",U={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions"},q={temperature:.3};var j=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var f=class f{static getInstance(){return f.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logError(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}styleMessage(e,t){let r=this.getTimestamp(),n="Please create an issue on GitHub if the issue persists.",i=80,l="\u2500".repeat(i-2),s=`\u250C${l}\u2510`,a=`\u2514${l}\u2518`,m=((C,le)=>{let ae=C.split(" "),A=[],g="";return ae.forEach($=>{(g+$).length>le&&(A.push(g.trim()),g=""),g+=$+" "}),g.trim()&&A.push(g.trim()),A})(e,i-4),u=[s,...m.map(C=>`\u2502 ${C.padEnd(i-4)} \u2502`),a].join(`
|
|
2
|
+
`);return`
|
|
3
|
+
\x1B[1m\x1B[37m[${r}]\x1B[0m \x1B[31m[${t}]\x1B[0m \x1B[2m${n}\x1B[0m
|
|
4
|
+
${u}
|
|
5
|
+
`}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var w=f;var p=(o,e)=>w.getInstance().handleError(o,e);var V=()=>{},W=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},T=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var P=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],G=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),h=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),K=o=>{let e=o.split(`
|
|
6
|
+
`);return e[e.length-1].length};var E=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),D=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var Y=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},ge=(o,e)=>Y(o,"GET",e),he=(o,e,t)=>Y(o,"POST",{...t,body:e}),x={GET:ge,POST:he};var J=(o,e)=>{let t=P(o,e);return!!t&&!j.has(t)},X=(o,e)=>{let t=G(o,e).trim(),r=h(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var y="<<CURSOR>>",z=o=>o==="javascript"?"latest JavaScript":o,Z=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Q=o=>{let e=z(o.language),t=Z(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},fe=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${T(o)}`:"",r=z(e);return`The code is written${r?` in ${r}`:""}${t}.`},ee=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=o,a=Z(n),d=e?`the file named "${e}"`:"a larger project",m=`You are tasked with ${a} for a code snippet. The code is part of ${d}.
|
|
4
7
|
|
|
5
|
-
`;return m+=
|
|
8
|
+
`;return m+=fe(r,t),m+=`
|
|
6
9
|
|
|
7
10
|
Here are the details about how the completion should be generated:
|
|
8
|
-
- The cursor position is marked with '${
|
|
11
|
+
- The cursor position is marked with '${y}'.
|
|
9
12
|
- Your completion must start exactly at the cursor position.
|
|
10
13
|
- Do not repeat any code that appears before or after the cursor.
|
|
11
14
|
- Ensure your completion does not introduce any syntactical or logical errors.
|
|
12
|
-
`,n==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${
|
|
13
|
-
`:n==="completion"&&(m+=` - If completing the code, start from '${
|
|
15
|
+
`,n==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${y}' entirely with your completion.
|
|
16
|
+
`:n==="completion"&&(m+=` - If completing the code, start from '${y}' and provide a logical continuation.
|
|
14
17
|
`),m+=` - Optimize for readability and performance where possible.
|
|
15
18
|
|
|
16
|
-
Remember
|
|
19
|
+
Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
|
|
17
20
|
|
|
18
21
|
Here's the code snippet for completion:
|
|
19
22
|
|
|
20
23
|
<code>
|
|
21
|
-
${i}${
|
|
22
|
-
</code>`,
|
|
24
|
+
${i}${y}${l}
|
|
25
|
+
</code>`,s&&s.length>0&&(m+=`
|
|
23
26
|
|
|
24
27
|
Additional context from related files:
|
|
25
28
|
|
|
26
|
-
`,m+=
|
|
27
|
-
${
|
|
29
|
+
`,m+=s.map(u=>`// Path: ${u.path}
|
|
30
|
+
${u.content}
|
|
28
31
|
`).join(`
|
|
29
|
-
`)),m.endsWith(".")?m:`${m}.`};var
|
|
32
|
+
`)),m.endsWith(".")?m:`${m}.`};var Ee="application/json",te=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await x.POST(e,{completionMetadata:Te({filename:o,position:l,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":Ee},error:"Error while fetching completion item"});return s}catch(s){return s instanceof Error&&(s.message==="Cancelled"||s.name==="AbortError")||p(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Te=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let l=Pe(e,t),s=E(e,t),a=D(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,editorState:{completionMode:l}}},Pe=(o,e)=>{let t=E(o,e),r=D(o,e);return t&&r?"fill-in-the-middle":"completion"};var M=class{constructor(e,t){let r=t?.model||k,n=t?.provider||H;if(!e)throw new Error(`Please provide ${n} API key.`);this.apiKey=e,this.model=r,this.provider=n}async complete({completionMetadata:e}){try{let t=this.createRequestBody(e),r=this.createHeaders(),n=this.getEndpoint(),i=await x.POST(n,t,{headers:r});if(!i.choices?.length)throw new Error("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(t){return{error:p(t,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}getEndpoint(){return U[this.provider]}getModelId(){if(!_[this.provider].includes(this.model))throw new Error(`Model ${this.model} is not supported by ${this.provider} provider. Supported models: ${T(_[this.provider])}`);return F[this.model]}createRequestBody(e){return{...q,model:this.getModelId(),messages:[{role:"system",content:Q(e)},{role:"user",content:ee(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var R=class o{constructor(e,t){this.originalCompletion="";this.formattedCompletion="";this.model=e,this.cursorPosition=t}static create(e,t){return new o(e,t)}setCompletion(e){return this.originalCompletion=e,this.formattedCompletion=e,this}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
|
|
33
|
+
`&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=E(this.cursorPosition,this.model).trim(),t=this.normalise(this.formattedCompletion),r=0,n=Math.min(t.length,e.length);for(let i=1;i<=n;i++){let l=e.slice(-i),s=t.slice(0,i);if(l===s)r=i;else break}return r>0&&(this.formattedCompletion=this.formattedCompletion.slice(r)),this}preventDuplicateLines(){for(let e=this.cursorPosition.lineNumber+1;e<this.cursorPosition.lineNumber+3&&e<this.model.getLineCount();e++){let t=this.model.getLineContent(e);if(this.normalise(t)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){let e=/^```[\s\S]*?\n([\s\S]*?)\n```$/,t=this.formattedCompletion.match(e);return t&&(this.formattedCompletion=t[1].trim()),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}build(){return this.formattedCompletion}};var I=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!J(this.cursorPosition,this.model)&&!X(this.cursorPosition,this.model)}};var b=class b{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(b.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return h(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};b.MAX_CACHE_SIZE=10;var O=b;var oe=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=K(o),l=P(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&n===0?t.column+i:i:t.column}};function re(o,e,t){return R.create(o,e).setCompletion(t).ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().removeMarkdownCodeSyntax().trimStart().build()}var c=o=>({items:o,enableForwardStability:!0});var xe=300,ne=W(te,xe),L=new O,ye=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new I(t,e).shouldProvideCompletions())return c([]);let s=L.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),c(s);if(r.isCancellationRequested||n)return c([]);try{let a=ne({...l,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{ne.cancel()});let d=await a;if(d){let m=re(e,t,d),u=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),C=oe(m,u,t,e);return L.addCompletionCache({completion:m,range:C,textBeforeCursorInLine:h(t,e)}),i(),c([{insertText:m,range:C}])}}catch(a){if(a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return c([]);p(a,"FETCH_COMPLETION_ITEM_ERROR")}return c([])},ie=ye;var v=!1,N=!1,se=(o,e,t)=>{let r=[];try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(l,s,a,d)=>ie({monaco:o,model:l,position:s,token:d,isCompletionAccepted:v,onShowCompletion:()=>N=!0,options:t}),freeInlineCompletions:V});r.push(n);let i=e.onKeyDown(l=>{let s=l.keyCode===o.KeyCode.Tab||l.keyCode===o.KeyCode.RightArrow&&l.metaKey;N&&s?(v=!0,N=!1):v=!1});return r.push(i),{deregister:()=>{r.forEach(l=>l.dispose()),L.clearCompletionCache(),v=!1,N=!1}}}catch(n){return p(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose())}}}};0&&(module.exports={Copilot,registerCopilot});
|
package/build/index.mjs
CHANGED
|
@@ -1,29 +1,33 @@
|
|
|
1
|
-
var A=
|
|
2
|
-
`);return
|
|
3
|
-
|
|
1
|
+
var $={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06"},A={groq:["llama-3-70b"],openai:["gpt-4o"]},F="llama-3-70b",k="groq",H={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions"},U={temperature:.3};var q=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var f=class f{static getInstance(){return f.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logError(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}styleMessage(e,t){let r=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",n=80,l="\u2500".repeat(n-2),s=`\u250C${l}\u2510`,a=`\u2514${l}\u2518`,m=((C,ie)=>{let se=C.split(" "),N=[],g="";return se.forEach(B=>{(g+B).length>ie&&(N.push(g.trim()),g=""),g+=B+" "}),g.trim()&&N.push(g.trim()),N})(e,n-4),u=[s,...m.map(C=>`\u2502 ${C.padEnd(n-4)} \u2502`),a].join(`
|
|
2
|
+
`);return`
|
|
3
|
+
\x1B[1m\x1B[37m[${r}]\x1B[0m \x1B[31m[${t}]\x1B[0m \x1B[2m${i}\x1B[0m
|
|
4
|
+
${u}
|
|
5
|
+
`}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var S=f;var p=(o,e)=>S.getInstance().handleError(o,e);var j=()=>{},V=(o,e)=>{let t=null,r=null,i=(...n)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...n)),r=null},e)});return i.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},i},T=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var P=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],W=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),h=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),G=o=>{let e=o.split(`
|
|
6
|
+
`);return e[e.length-1].length};var E=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),_=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var K=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},i=e==="POST"&&t.body?JSON.stringify(t.body):void 0,n=await fetch(o,{method:e,headers:r,body:i,signal:t.signal});if(!n.ok)throw new Error(`${t.error||"Network error"}: ${n.statusText}`);return n.json()},le=(o,e)=>K(o,"GET",e),ae=(o,e,t)=>K(o,"POST",{...t,body:e}),x={GET:le,POST:ae};var Y=(o,e)=>{let t=P(o,e);return!!t&&!q.has(t)},J=(o,e)=>{let t=W(o,e).trim(),r=h(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var y="<<CURSOR>>",X=o=>o==="javascript"?"latest JavaScript":o,z=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Z=o=>{let e=X(o.language),t=z(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},me=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${T(o)}`:"",r=X(e);return`The code is written${r?` in ${r}`:""}${t}.`},Q=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:i},textBeforeCursor:n,textAfterCursor:l,externalContext:s}=o,a=z(i),d=e?`the file named "${e}"`:"a larger project",m=`You are tasked with ${a} for a code snippet. The code is part of ${d}.
|
|
4
7
|
|
|
5
|
-
`;return m+=
|
|
8
|
+
`;return m+=me(r,t),m+=`
|
|
6
9
|
|
|
7
10
|
Here are the details about how the completion should be generated:
|
|
8
|
-
- The cursor position is marked with '${
|
|
11
|
+
- The cursor position is marked with '${y}'.
|
|
9
12
|
- Your completion must start exactly at the cursor position.
|
|
10
13
|
- Do not repeat any code that appears before or after the cursor.
|
|
11
14
|
- Ensure your completion does not introduce any syntactical or logical errors.
|
|
12
|
-
`,
|
|
13
|
-
`:
|
|
15
|
+
`,i==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${y}' entirely with your completion.
|
|
16
|
+
`:i==="completion"&&(m+=` - If completing the code, start from '${y}' and provide a logical continuation.
|
|
14
17
|
`),m+=` - Optimize for readability and performance where possible.
|
|
15
18
|
|
|
16
|
-
Remember
|
|
19
|
+
Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
|
|
17
20
|
|
|
18
21
|
Here's the code snippet for completion:
|
|
19
22
|
|
|
20
23
|
<code>
|
|
21
|
-
${
|
|
22
|
-
</code>`,
|
|
24
|
+
${n}${y}${l}
|
|
25
|
+
</code>`,s&&s.length>0&&(m+=`
|
|
23
26
|
|
|
24
27
|
Additional context from related files:
|
|
25
28
|
|
|
26
|
-
`,m+=
|
|
27
|
-
${
|
|
29
|
+
`,m+=s.map(u=>`// Path: ${u.path}
|
|
30
|
+
${u.content}
|
|
28
31
|
`).join(`
|
|
29
|
-
`)),m.endsWith(".")?m:`${m}.`};var
|
|
32
|
+
`)),m.endsWith(".")?m:`${m}.`};var pe="application/json",ee=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:i,model:n,position:l})=>{try{let{completion:s}=await x.POST(e,{completionMetadata:de({filename:o,position:l,model:n,language:t,technologies:r,externalContext:i})},{headers:{"Content-Type":pe},error:"Error while fetching completion item"});return s}catch(s){return s instanceof Error&&(s.message==="Cancelled"||s.name==="AbortError")||p(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},de=({filename:o,position:e,model:t,language:r,technologies:i,externalContext:n})=>{let l=ce(e,t),s=E(e,t),a=_(e,t);return{filename:o,language:r,technologies:i,externalContext:n,textBeforeCursor:s,textAfterCursor:a,editorState:{completionMode:l}}},ce=(o,e)=>{let t=E(o,e),r=_(o,e);return t&&r?"fill-in-the-middle":"completion"};var D=class{constructor(e,t){let r=t?.model||F,i=t?.provider||k;if(!e)throw new Error(`Please provide ${i} API key.`);this.apiKey=e,this.model=r,this.provider=i}async complete({completionMetadata:e}){try{let t=this.createRequestBody(e),r=this.createHeaders(),i=this.getEndpoint(),n=await x.POST(i,t,{headers:r});if(!n.choices?.length)throw new Error("No completion choices received from API");return{completion:n.choices[0].message.content}}catch(t){return{error:p(t,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}getEndpoint(){return H[this.provider]}getModelId(){if(!A[this.provider].includes(this.model))throw new Error(`Model ${this.model} is not supported by ${this.provider} provider. Supported models: ${T(A[this.provider])}`);return $[this.model]}createRequestBody(e){return{...U,model:this.getModelId(),messages:[{role:"system",content:Z(e)},{role:"user",content:Q(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var M=class o{constructor(e,t){this.originalCompletion="";this.formattedCompletion="";this.model=e,this.cursorPosition=t}static create(e,t){return new o(e,t)}setCompletion(e){return this.originalCompletion=e,this.formattedCompletion=e,this}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
|
|
33
|
+
`&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=E(this.cursorPosition,this.model).trim(),t=this.normalise(this.formattedCompletion),r=0,i=Math.min(t.length,e.length);for(let n=1;n<=i;n++){let l=e.slice(-n),s=t.slice(0,n);if(l===s)r=n;else break}return r>0&&(this.formattedCompletion=this.formattedCompletion.slice(r)),this}preventDuplicateLines(){for(let e=this.cursorPosition.lineNumber+1;e<this.cursorPosition.lineNumber+3&&e<this.model.getLineCount();e++){let t=this.model.getLineContent(e);if(this.normalise(t)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){let e=/^```[\s\S]*?\n([\s\S]*?)\n```$/,t=this.formattedCompletion.match(e);return t&&(this.formattedCompletion=t[1].trim()),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}build(){return this.formattedCompletion}};var R=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!Y(this.cursorPosition,this.model)&&!J(this.cursorPosition,this.model)}};var O=class O{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(O.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let i=r.getValueInRange(e.range);return h(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,i)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};O.MAX_CACHE_SIZE=10;var I=O;var te=(o,e,t,r)=>{let i=(o.match(/\n/g)||[]).length,n=G(o),l=P(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+i,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&i===0?t.column+n:n:t.column}};function oe(o,e,t){return M.create(o,e).setCompletion(t).ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().removeMarkdownCodeSyntax().trimStart().build()}var c=o=>({items:o,enableForwardStability:!0});var ue=300,re=V(ee,ue),b=new I,Ce=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:i,onShowCompletion:n,options:l})=>{if(!new R(t,e).shouldProvideCompletions())return c([]);let s=b.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return n(),c(s);if(r.isCancellationRequested||i)return c([]);try{let a=re({...l,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{re.cancel()});let d=await a;if(d){let m=oe(e,t,d),u=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),C=te(m,u,t,e);return b.addCompletionCache({completion:m,range:C,textBeforeCursorInLine:h(t,e)}),n(),c([{insertText:m,range:C}])}}catch(a){if(a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return c([]);p(a,"FETCH_COMPLETION_ITEM_ERROR")}return c([])},ne=Ce;var L=!1,v=!1,ge=(o,e,t)=>{let r=[];try{let i=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(l,s,a,d)=>ne({monaco:o,model:l,position:s,token:d,isCompletionAccepted:L,onShowCompletion:()=>v=!0,options:t}),freeInlineCompletions:j});r.push(i);let n=e.onKeyDown(l=>{let s=l.keyCode===o.KeyCode.Tab||l.keyCode===o.KeyCode.RightArrow&&l.metaKey;v&&s?(L=!0,v=!1):L=!1});return r.push(n),{deregister:()=>{r.forEach(l=>l.dispose()),b.clearCompletionCache(),L=!1,v=!1}}}catch(i){return p(i,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(n=>n.dispose())}}}};export{D as Copilot,ge as registerCopilot};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "monacopilot",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.13",
|
|
4
4
|
"description": "AI auto-completion for Monaco Editor",
|
|
5
5
|
"main": "./build/index.js",
|
|
6
6
|
"module": "./build/index.mjs",
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
"eslint": "^8.57.0",
|
|
28
28
|
"groq-sdk": "^0.3.2",
|
|
29
29
|
"monaco-editor": "^0.50.0",
|
|
30
|
+
"openai": "^4.56.0",
|
|
30
31
|
"prettier": "^3.2.5",
|
|
31
32
|
"release-it": "^17.2.1",
|
|
32
33
|
"tsup": "^8.0.2",
|