monacopilot 0.9.16 → 0.9.17
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/LICENSE +21 -21
- package/README.md +1 -2
- package/build/index.js +15 -12
- package/build/index.mjs +16 -13
- package/package.json +8 -6
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 Arshad Yaseen
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Arshad Yaseen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -26,8 +26,7 @@ https://github.com/user-attachments/assets/4af4e24a-1b05-4bee-84aa-1521ad7098cd
|
|
|
26
26
|
|
|
27
27
|
Here are some examples of how to use Monacopilot in different project setups:
|
|
28
28
|
|
|
29
|
-
-
|
|
30
|
-
- [Next.js Pages Router](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/nextjs/pages-router)
|
|
29
|
+
- Next.js ([app](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/nextjs/app) | [pages](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/nextjs/pages))
|
|
31
30
|
|
|
32
31
|
## Installation
|
|
33
32
|
|
package/build/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var A=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var pe=Object.prototype.hasOwnProperty;var ce=(o,e)=>{for(var t in e)A(o,t,{get:e[t],enumerable:!0})},de=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of me(e))!pe.call(o,n)&&n!==t&&A(o,n,{get:()=>e[n],enumerable:!(r=ae(e,n))||r.enumerable});return o};var ue=o=>de(A({},"__esModule",{value:!0}),o);var ye={};ce(ye,{Copilot:()=>y,registerCopilot:()=>ie});module.exports=ue(ye);var k={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini"},w={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"]},F="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,s="\u2500".repeat(i-2),l=`\u250C${s}\u2510`,a=`\u2514${s}\u2518`,m=((C,se)=>{let le=C.split(" "),N=[],g="";return le.forEach(B=>{(g+B).length>se&&(N.push(g.trim()),g=""),g+=B+" "}),g.trim()&&N.push(g.trim()),N})(e,i-4),u=[l,...m.map(C=>`\u2502 ${C.padEnd(i-4)} \u2502`),a].join(`
|
|
2
2
|
`);return`
|
|
3
3
|
\x1B[1m\x1B[37m[${r}]\x1B[0m \x1B[31m[${t}]\x1B[0m \x1B[2m${n}\x1B[0m
|
|
4
4
|
${u}
|
|
5
|
-
`}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var
|
|
6
|
-
`);return e[e.length-1].length};var
|
|
5
|
+
`}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var _=f;var p=(o,e)=>_.getInstance().handleError(o,e);var V=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((s,l)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=l,t=setTimeout(()=>{s(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},E=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var T=(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+1};var S=(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()},Ce=(o,e)=>Y(o,"GET",e),ge=(o,e,t)=>Y(o,"POST",{...t,body:e}),P={GET:Ce,POST:ge};var K=(o,e)=>{let t=T(o,e);return!!t&&!j.has(t)},J=(o,e)=>{let t=W(o,e).trim(),r=h(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var x="<<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.`},he=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${E(o)}`:"",r=X(e);return`The code is written${r?` in ${r}`:""}${t}.`},Q=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:s,externalContext:l}=o,a=z(n),c=e?`the file named "${e}"`:"a larger project",m=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
|
|
7
7
|
|
|
8
|
-
`;return m+=
|
|
8
|
+
`;return m+=he(r,t),m+=`
|
|
9
9
|
|
|
10
10
|
Here are the details about how the completion should be generated:
|
|
11
|
-
- The cursor position is marked with '${
|
|
11
|
+
- The cursor position is marked with '${x}'.
|
|
12
12
|
- Your completion must start exactly at the cursor position.
|
|
13
13
|
- Do not repeat any code that appears before or after the cursor.
|
|
14
14
|
- Ensure your completion does not introduce any syntactical or logical errors.
|
|
15
|
-
`,n==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${
|
|
16
|
-
`:n==="completion"&&(m+=` - If completing the code, start from '${
|
|
15
|
+
`,n==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${x}' entirely with your completion.
|
|
16
|
+
`:n==="completion"&&(m+=` - If completing the code, start from '${x}' and provide a logical continuation.
|
|
17
17
|
`),m+=` - Optimize for readability and performance where possible.
|
|
18
18
|
|
|
19
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 (\`\`\`).
|
|
@@ -21,13 +21,16 @@ Here are the details about how the completion should be generated:
|
|
|
21
21
|
Here's the code snippet for completion:
|
|
22
22
|
|
|
23
23
|
<code>
|
|
24
|
-
${i}${
|
|
25
|
-
</code>`,
|
|
24
|
+
${i}${x}${s}
|
|
25
|
+
</code>`,l&&l.length>0&&(m+=`
|
|
26
26
|
|
|
27
27
|
Additional context from related files:
|
|
28
28
|
|
|
29
|
-
`,m+=
|
|
29
|
+
`,m+=l.map(u=>`// Path: ${u.path}
|
|
30
30
|
${u.content}
|
|
31
31
|
`).join(`
|
|
32
|
-
`)),m.endsWith(".")?m:`${m}.`};var
|
|
33
|
-
|
|
32
|
+
`)),m.endsWith(".")?m:`${m}.`};var fe="application/json",ee=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:s})=>{try{let{completion:l}=await P.POST(e,{completionMetadata:Ee({filename:o,position:s,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":fe},error:"Error while fetching completion item"});return l}catch(l){return l instanceof Error&&(l.message==="Cancelled"||l.name==="AbortError")||p(l,"FETCH_COMPLETION_ITEM_ERROR"),null}},Ee=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let s=Te(e,t),l=S(e,t),a=D(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:l,textAfterCursor:a,editorState:{completionMode:s}}},Te=(o,e)=>{let t=S(o,e),r=D(o,e);return t&&r?"fill-in-the-middle":"completion"};var y=class{constructor(e,t){let{provider:r,model:n}=t||{};if(r&&!n)throw new Error("You must provide a model when setting a provider");if(n&&!r)throw new Error("You must provide a provider when setting a model");if(this.model=n||F,this.provider=r||H,!w[this.provider].includes(this.model))throw new Error(`Model ${this.model} is not supported by ${this.provider} provider. Supported models: ${E(w[this.provider])}`);if(!e)throw new Error(`Please provide ${this.provider} API key.`);this.apiKey=e}async complete({completionMetadata:e}){try{let t=this.createRequestBody(e),r=this.createHeaders(),n=this.getEndpoint(),i=await P.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(){return k[this.model]}createRequestBody(e){return{...q,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){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new o(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 t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],s=i.split(`
|
|
33
|
+
`).slice(1,-1).join(`
|
|
34
|
+
`);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
35
|
+
|
|
36
|
+
`),this}build(){return this.formattedCompletion}};var I=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!K(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 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}};O.MAX_CACHE_SIZE=10;var R=O;var te=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=G(o),s=T(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(s)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function oe(o){return M.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var d=o=>({items:o,enableForwardStability:!0});var Pe=300,re=V(ee,Pe),b=new R,xe=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{if(!new I(t,e).shouldProvideCompletions())return d([]);let l=b.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(l.length)return i(),d(l);if(r.isCancellationRequested||n)return d([]);try{let a=re({...s,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{re.cancel()});let c=await a;if(c){let m=oe(c),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)}),i(),d([{insertText:m,range:C}])}}catch(a){if(a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return d([]);p(a,"FETCH_COMPLETION_ITEM_ERROR")}return d([])},ne=xe;var L=!1,v=!1,ie=(o,e,t)=>{let r=[];try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,l,a,c)=>ne({monaco:o,model:s,position:l,token:c,isCompletionAccepted:L,onShowCompletion:()=>v=!0,options:t}),freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let l=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;v&&l?(L=!0,v=!1):L=!1});return r.push(i),{deregister:()=>{r.forEach(s=>s.dispose()),b.clearCompletionCache(),L=!1,v=!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,19 +1,19 @@
|
|
|
1
|
-
var
|
|
1
|
+
var B={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini"},N={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"]},k="llama-3-70b",F="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(),n="Please create an issue on GitHub if the issue persists.",i=80,s="\u2500".repeat(i-2),l=`\u250C${s}\u2510`,a=`\u2514${s}\u2518`,m=((C,ne)=>{let ie=C.split(" "),v=[],g="";return ie.forEach($=>{(g+$).length>ne&&(v.push(g.trim()),g=""),g+=$+" "}),g.trim()&&v.push(g.trim()),v})(e,i-4),u=[l,...m.map(C=>`\u2502 ${C.padEnd(i-4)} \u2502`),a].join(`
|
|
2
2
|
`);return`
|
|
3
|
-
\x1B[1m\x1B[37m[${r}]\x1B[0m \x1B[31m[${t}]\x1B[0m \x1B[2m${
|
|
3
|
+
\x1B[1m\x1B[37m[${r}]\x1B[0m \x1B[31m[${t}]\x1B[0m \x1B[2m${n}\x1B[0m
|
|
4
4
|
${u}
|
|
5
|
-
`}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var
|
|
6
|
-
`);return e[e.length-1].length};var
|
|
5
|
+
`}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var A=f;var p=(o,e)=>A.getInstance().handleError(o,e);var j=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((s,l)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=l,t=setTimeout(()=>{s(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},E=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var T=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],V=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),h=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),W=o=>{let e=o.split(`
|
|
6
|
+
`);return e[e.length-1].length+1};var w=(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 G=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()},se=(o,e)=>G(o,"GET",e),le=(o,e,t)=>G(o,"POST",{...t,body:e}),P={GET:se,POST:le};var Y=(o,e)=>{let t=T(o,e);return!!t&&!q.has(t)},K=(o,e)=>{let t=V(o,e).trim(),r=h(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var x="<<CURSOR>>",J=o=>o==="javascript"?"latest JavaScript":o,X=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=J(o.language),t=X(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.`},ae=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${E(o)}`:"",r=J(e);return`The code is written${r?` in ${r}`:""}${t}.`},Z=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:s,externalContext:l}=o,a=X(n),c=e?`the file named "${e}"`:"a larger project",m=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
|
|
7
7
|
|
|
8
|
-
`;return m+=
|
|
8
|
+
`;return m+=ae(r,t),m+=`
|
|
9
9
|
|
|
10
10
|
Here are the details about how the completion should be generated:
|
|
11
|
-
- The cursor position is marked with '${
|
|
11
|
+
- The cursor position is marked with '${x}'.
|
|
12
12
|
- Your completion must start exactly at the cursor position.
|
|
13
13
|
- Do not repeat any code that appears before or after the cursor.
|
|
14
14
|
- Ensure your completion does not introduce any syntactical or logical errors.
|
|
15
|
-
`,
|
|
16
|
-
`:
|
|
15
|
+
`,n==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${x}' entirely with your completion.
|
|
16
|
+
`:n==="completion"&&(m+=` - If completing the code, start from '${x}' and provide a logical continuation.
|
|
17
17
|
`),m+=` - Optimize for readability and performance where possible.
|
|
18
18
|
|
|
19
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 (\`\`\`).
|
|
@@ -21,13 +21,16 @@ Here are the details about how the completion should be generated:
|
|
|
21
21
|
Here's the code snippet for completion:
|
|
22
22
|
|
|
23
23
|
<code>
|
|
24
|
-
${
|
|
25
|
-
</code>`,
|
|
24
|
+
${i}${x}${s}
|
|
25
|
+
</code>`,l&&l.length>0&&(m+=`
|
|
26
26
|
|
|
27
27
|
Additional context from related files:
|
|
28
28
|
|
|
29
|
-
`,m+=
|
|
29
|
+
`,m+=l.map(u=>`// Path: ${u.path}
|
|
30
30
|
${u.content}
|
|
31
31
|
`).join(`
|
|
32
|
-
`)),m.endsWith(".")?m:`${m}.`};var
|
|
33
|
-
|
|
32
|
+
`)),m.endsWith(".")?m:`${m}.`};var me="application/json",Q=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:s})=>{try{let{completion:l}=await P.POST(e,{completionMetadata:pe({filename:o,position:s,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":me},error:"Error while fetching completion item"});return l}catch(l){return l instanceof Error&&(l.message==="Cancelled"||l.name==="AbortError")||p(l,"FETCH_COMPLETION_ITEM_ERROR"),null}},pe=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let s=ce(e,t),l=w(e,t),a=_(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:l,textAfterCursor:a,editorState:{completionMode:s}}},ce=(o,e)=>{let t=w(o,e),r=_(o,e);return t&&r?"fill-in-the-middle":"completion"};var D=class{constructor(e,t){let{provider:r,model:n}=t||{};if(r&&!n)throw new Error("You must provide a model when setting a provider");if(n&&!r)throw new Error("You must provide a provider when setting a model");if(this.model=n||k,this.provider=r||F,!N[this.provider].includes(this.model))throw new Error(`Model ${this.model} is not supported by ${this.provider} provider. Supported models: ${E(N[this.provider])}`);if(!e)throw new Error(`Please provide ${this.provider} API key.`);this.apiKey=e}async complete({completionMetadata:e}){try{let t=this.createRequestBody(e),r=this.createHeaders(),n=this.getEndpoint(),i=await P.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 H[this.provider]}getModelId(){return B[this.model]}createRequestBody(e){return{...U,model:this.getModelId(),messages:[{role:"system",content:z(e)},{role:"user",content:Z(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var y=class o{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new o(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 t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],s=i.split(`
|
|
33
|
+
`).slice(1,-1).join(`
|
|
34
|
+
`);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
35
|
+
|
|
36
|
+
`),this}build(){return this.formattedCompletion}};var M=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!Y(this.cursorPosition,this.model)&&!K(this.cursorPosition,this.model)}};var R=class R{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(R.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}};R.MAX_CACHE_SIZE=10;var I=R;var ee=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=W(o),s=T(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(s)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function te(o){return y.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var d=o=>({items:o,enableForwardStability:!0});var de=300,oe=j(Q,de),O=new I,ue=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{if(!new M(t,e).shouldProvideCompletions())return d([]);let l=O.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(l.length)return i(),d(l);if(r.isCancellationRequested||n)return d([]);try{let a=oe({...s,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{oe.cancel()});let c=await a;if(c){let m=te(c),u=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),C=ee(m,u,t,e);return O.addCompletionCache({completion:m,range:C,textBeforeCursorInLine:h(t,e)}),i(),d([{insertText:m,range:C}])}}catch(a){if(a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return d([]);p(a,"FETCH_COMPLETION_ITEM_ERROR")}return d([])},re=ue;var b=!1,L=!1,Ce=(o,e,t)=>{let r=[];try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,l,a,c)=>re({monaco:o,model:s,position:l,token:c,isCompletionAccepted:b,onShowCompletion:()=>L=!0,options:t}),freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let l=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;L&&l?(b=!0,L=!1):b=!1});return r.push(i),{deregister:()=>{r.forEach(s=>s.dispose()),O.clearCompletionCache(),b=!1,L=!1}}}catch(n){return p(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose())}}}};export{D as Copilot,Ce as registerCopilot};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "monacopilot",
|
|
3
|
-
"version": "0.9.
|
|
4
|
-
"description": "AI auto-completion for Monaco Editor",
|
|
3
|
+
"version": "0.9.17",
|
|
4
|
+
"description": "AI auto-completion plugin for Monaco Editor",
|
|
5
5
|
"main": "./build/index.js",
|
|
6
6
|
"module": "./build/index.mjs",
|
|
7
7
|
"types": "./build/index.d.ts",
|
|
@@ -11,12 +11,13 @@
|
|
|
11
11
|
"scripts": {
|
|
12
12
|
"build": "tsup src/index.ts",
|
|
13
13
|
"dev": "tsup src/index.ts --watch",
|
|
14
|
-
"
|
|
14
|
+
"test": "vitest",
|
|
15
|
+
"dev:test-ui": "pnpm -C tests/ui dev",
|
|
15
16
|
"type-check": "tsc --noEmit",
|
|
16
17
|
"lint": "eslint . --ext .ts,.tsx --fix",
|
|
17
|
-
"lint:test": "pnpm -C
|
|
18
|
+
"lint:test-ui": "pnpm -C tests/ui lint",
|
|
18
19
|
"format": "prettier --write .",
|
|
19
|
-
"pre-commit": "pnpm type-check && pnpm lint && pnpm lint:test",
|
|
20
|
+
"pre-commit": "pnpm format && pnpm type-check && pnpm lint && pnpm lint:test-ui",
|
|
20
21
|
"release": "release-it"
|
|
21
22
|
},
|
|
22
23
|
"devDependencies": {
|
|
@@ -30,7 +31,8 @@
|
|
|
30
31
|
"prettier": "^3.2.5",
|
|
31
32
|
"release-it": "^17.2.1",
|
|
32
33
|
"tsup": "^8.0.2",
|
|
33
|
-
"typescript": "^5.4.3"
|
|
34
|
+
"typescript": "^5.4.3",
|
|
35
|
+
"vitest": "^2.0.5"
|
|
34
36
|
},
|
|
35
37
|
"keywords": [
|
|
36
38
|
"monaco-editor",
|