monacopilot 0.9.7 → 0.9.8

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.js CHANGED
@@ -1,19 +1,61 @@
1
- "use strict";var I=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var re=Object.prototype.hasOwnProperty;var ne=(t,e)=>{for(var o in e)I(t,o,{get:e[o],enumerable:!0})},ie=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of oe(e))!re.call(t,i)&&i!==o&&I(t,i,{get:()=>e[i],enumerable:!(r=te(e,i))||r.enumerable});return t};var se=t=>ie(I({},"__esModule",{value:!0}),t);var fe={};ne(fe,{Copilot:()=>O,registerCopilot:()=>ee});module.exports=se(fe);var b=()=>{},S=(t,e=1e3)=>{let o=null;return(...i)=>(o&&clearTimeout(o),new Promise((n,s)=>{o=setTimeout(()=>{t(...i).then(n).catch(s)},e)}))},B=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var x=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],$=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),u=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),_=t=>{let e=t.split(`
2
- `);return e[e.length-1].length};var g=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),L=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var D=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},i=e==="POST"&&o.body?JSON.stringify(o.body):void 0,n=await fetch(t,{method:e,headers:r,body:i,signal:o.signal});if(!n.ok)throw new Error(`${o.error||"Network error"}: ${n.statusText}`);return n.json()},le=(t,e)=>D(t,"GET",e),me=(t,e,o)=>D(t,"POST",{...o,body:e}),T={GET:le,POST:me};var P=class{constructor(e,o){this.formattedCompletion="";this.originalCompletion="";this.model=e,this.cursorPosition=o,this.lineCount=e.getLineCount()}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
3
- `&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=g(this.cursorPosition,this.model).trim(),o=this.normalise(this.formattedCompletion),r=0,i=Math.min(o.length,e.length);for(let n=1;n<=i;n++){let s=e.slice(-n),m=o.slice(0,n);if(s===m)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.lineCount;e++){let o=this.model.getLineContent(e);if(this.normalise(o)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}format(e){return this.originalCompletion=e,this.formattedCompletion=e,this.ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().trimStart(),this.formattedCompletion}};var ae=10,h=[],q=(t,e)=>h.filter(o=>{let r=e.getValueInRange(o.range);return u(t,e).startsWith(o.textBeforeCursorInLine)&&(o.range.startLineNumber===t.lineNumber&&t.column===o.range.startColumn||o.completion.startsWith(r)&&o.range.startLineNumber===t.lineNumber&&t.column>=o.range.startColumn-r.length&&t.column<=o.range.endColumn)}),k=t=>{h.length>=ae&&h.shift(),h.push(t)},F=()=>{h.length=0};var U={llama:"llama3-70b-8192"},y="llama",G="https://api.groq.com/openai/v1/chat/completions";var j=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var W=(t,e)=>{let o=x(t,e);return!!o&&!j.has(o)},H=(t,e)=>{let o=$(t,e).trim(),r=u(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var K=(t,e,o,r)=>{let i=(t.match(/\n/g)||[]).length,n=_(t),s=x(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+i,endColumn:t.includes(s)?o.lineNumber===e.startLineNumber&&i===0?o.column+n:n:o.column}},V=(t,e,o)=>new P(t,e).format(o),c=t=>({items:t,enableForwardStability:!0});var R=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!W(this.cursorPosition,this.model)&&!H(this.cursorPosition,this.model)}};var M=class{static getModel(){return this.model}static setModel(e){this.model=e}};M.model=y;var N=M;var v=class{constructor(e){this.error=e}logError(e,o,r){console.error(`${e}: ${o}`,r)}monacopilotError(e){this.logError("MONACO_PILOT_ERROR",e,this.error)}apiError(e){this.logError("API_ERROR",e,this.error)}completionError(e){this.logError("COMPLETION_ERROR",e,this.error)}predictionError(e){this.logError("PREDICTION_ERROR",e,this.error)}editorError(e){this.logError("EDITOR_ERROR",e,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},a=t=>new v(t);var f="<cursor>",Y=t=>t==="javascript"?"latest JavaScript":t,J=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},z=t=>{let e=Y(t.language),o=J(t.editorState.completionMode);return`You are a world-class${e?` ${e}`:""} coding assistant renowned for your exceptional expertise in ${o}.`},pe=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${B(t)}`:"",r=Y(e);return`The code is written${r?` in ${r}`:""}${o}.`},Q=t=>{let{filename:e,language:o,technologies:r,editorState:i,textBeforeCursor:n,textAfterCursor:s,externalContext:m}=t,p=J(i.completionMode),E=e?`the file named ${e}`:"a larger project",l=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${f}'.
4
- Your task is to assist with ${p}. This code is part of ${E}. Please `;switch(i.completionMode){case"fill-in-the-middle":l+=`generate a completion to fill the middle of the code around '${f}'.
5
- Ensure the completion replaces '${f}' precisely, maintaining consistency, semantic accuracy, and relevance to the context.
6
- The completion must start exactly from the cursor position without any preceding or following characters,
7
- and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":l+=`provide the necessary completion for '${f}' while ensuring consistency, semantic accuracy, and relevance to the context.
8
- The completion must start exactly from the cursor position without any preceding or following characters,
9
- and it should not introduce any syntactical or semantic errors to the existing code.`;break}l+=` Output only the necessary completion code, without additional explanations or content.
10
- ${pe(r,o)}`;let d=`${n}${f}${s}
11
-
12
- `;return m&&m.length>0&&(d+=m.map(C=>`// Path: ${C.path}
13
- ${C.content}
14
- `).join(`
15
- `)),l+=`
1
+ "use strict";var b=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var ne=Object.prototype.hasOwnProperty;var ie=(t,e)=>{for(var o in e)b(t,o,{get:e[o],enumerable:!0})},se=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of re(e))!ne.call(t,i)&&i!==o&&b(t,i,{get:()=>e[i],enumerable:!(r=oe(e,i))||r.enumerable});return t};var le=t=>se(b({},"__esModule",{value:!0}),t);var Ee={};ie(Ee,{Copilot:()=>M,registerCopilot:()=>te});module.exports=le(Ee);var O=()=>{},S=(t,e=1e3)=>{let o=null;return(...i)=>(o&&clearTimeout(o),new Promise((n,s)=>{o=setTimeout(()=>{t(...i).then(n).catch(s)},e)}))},_=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var E=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],B=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),u=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),D=t=>{let e=t.split(`
2
+ `);return e[e.length-1].length};var C=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),I=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var $=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},i=e==="POST"&&o.body?JSON.stringify(o.body):void 0,n=await fetch(t,{method:e,headers:r,body:i,signal:o.signal});if(!n.ok)throw new Error(`${o.error||"Network error"}: ${n.statusText}`);return n.json()},ae=(t,e)=>$(t,"GET",e),me=(t,e,o)=>$(t,"POST",{...o,body:e}),x={GET:ae,POST:me};var T=class{constructor(e,o){this.formattedCompletion="";this.originalCompletion="";this.model=e,this.cursorPosition=o,this.lineCount=e.getLineCount()}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
3
+ `&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=C(this.cursorPosition,this.model).trim(),o=this.normalise(this.formattedCompletion),r=0,i=Math.min(o.length,e.length);for(let n=1;n<=i;n++){let s=e.slice(-n),l=o.slice(0,n);if(s===l)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.lineCount;e++){let o=this.model.getLineContent(e);if(this.normalise(o)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}format(e){return this.originalCompletion=e,this.formattedCompletion=e,this.ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().trimStart(),this.formattedCompletion}};var pe=10,g=[],k=(t,e)=>g.filter(o=>{let r=e.getValueInRange(o.range);return u(t,e).startsWith(o.textBeforeCursorInLine)&&(o.range.startLineNumber===t.lineNumber&&t.column===o.range.startColumn||o.completion.startsWith(r)&&o.range.startLineNumber===t.lineNumber&&t.column>=o.range.startColumn-r.length&&t.column<=o.range.endColumn)}),q=t=>{g.length>=pe&&g.shift(),g.push(t)},F=()=>{g.length=0};var U={llama:"llama3-70b-8192"},y="llama",G="https://api.groq.com/openai/v1/chat/completions",j={temperature:.3};var H=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var W=(t,e)=>{let o=E(t,e);return!!o&&!H.has(o)},K=(t,e)=>{let o=B(t,e).trim(),r=u(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var Y=(t,e,o,r)=>{let i=(t.match(/\n/g)||[]).length,n=D(t),s=E(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+i,endColumn:t.includes(s)?o.lineNumber===e.startLineNumber&&i===0?o.column+n:n:o.column}},z=(t,e,o)=>new T(t,e).format(o),c=t=>({items:t,enableForwardStability:!0});var P=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!W(this.cursorPosition,this.model)&&!K(this.cursorPosition,this.model)}};var R=class{static getModel(){return this.model}static setModel(e){this.model=e}};R.model=y;var L=R;var v=class{constructor(e){this.error=e}logError(e,o,r){console.error(`${e}: ${o}`,r)}monacopilotError(e){this.logError("MONACO_PILOT_ERROR",e,this.error)}apiError(e){this.logError("API_ERROR",e,this.error)}completionError(e){this.logError("COMPLETION_ERROR",e,this.error)}predictionError(e){this.logError("PREDICTION_ERROR",e,this.error)}editorError(e){this.logError("EDITOR_ERROR",e,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},m=t=>new v(t);var h="<<CURSOR>>",V=t=>t==="javascript"?"latest JavaScript":t,J=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Q=t=>{let e=V(t.language),o=J(t.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${o} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions.
4
+
5
+ ### Instructions:
6
+ - Provide only the requested code completion without any additional explanations or markdown.
7
+ - Ensure your suggestions seamlessly integrate with the existing code structure and style.
8
+ - Maintain consistent indentation and formatting with the surrounding code.
9
+ - Start your completion exactly at the cursor position (${h}).
10
+ - Do not repeat any existing code before or after the cursor.
11
+ - Respect the project's coding conventions, naming styles, and design patterns.
12
+ - Consider the broader context of the file and project when making suggestions.
13
+ - Optimize for readability, maintainability, and performance where applicable.
14
+ - Handle potential errors and edge cases in your completions when appropriate.
15
+ - Utilize modern language features and best practices specific to${r}.
16
+ - If multiple valid completions exist, choose the most likely and idiomatic one.
17
+ - If you cannot provide a meaningful completion, return an empty string.
18
+
19
+ ### Formatting Rules:
20
+ - Do not include any markdown or code block syntax.
21
+ - Insert newlines after opening brackets ({, [, () and before closing brackets (}, ], )).
22
+ - Add newlines after commas in multi-line structures.
23
+ - Do not suggest newlines after spaces or existing newlines.
24
+ - Match the indentation level of the current line for new lines.
25
+
26
+ Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},ce=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${_(t)}`:"",r=V(e);return`The code is written${r?` in ${r}`:""}${o}.`},X=t=>{let{filename:e,language:o,technologies:r,editorState:i,textBeforeCursor:n,textAfterCursor:s,externalContext:l}=t,p=J(i.completionMode),f=e?`the file named "${e}"`:"a larger project",a=`You are tasked with ${p} for a code snippet. The code is part of ${f}.
27
+
28
+ Your objective is to:
29
+ 1. Analyze the provided code snippet and its context.
30
+ 2. Generate a completion that seamlessly integrates with the existing code.
31
+ 3. Ensure your completion is syntactically correct and semantically meaningful.
32
+ 4. Adhere to the project's coding style and conventions.
33
+ 5. Consider the broader context of the file and any provided external context.
34
+
35
+ ${ce(r,o)}
16
36
 
17
- <code>
18
- ${d}
19
- </code>`,l.endsWith(".")?l:`${l}.`};var ce="application/json",X=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:i,model:n,position:s})=>{try{let{completion:m}=await T.POST(e,{completionMetadata:de({filename:t,position:s,model:n,language:o,technologies:r,externalContext:i})},{headers:{"Content-Type":ce},error:"Error while fetching completion item"});return m||null}catch(m){return a(m).completionError("Error while fetching completion item"),null}},de=({filename:t,position:e,model:o,language:r,technologies:i,externalContext:n})=>{let s=ue(e,o),m=g(e,o),p=L(e,o);return{filename:t,language:r,technologies:i,externalContext:n,textBeforeCursor:m,textAfterCursor:p,editorState:{completionMode:s}}},ue=(t,e)=>{let o=g(t,e),r=L(t,e);return o&&r?"fill-in-the-middle":"completion"};var O=class{constructor(e,o){if(!e)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=e,N.setModel(o?.model||y)}async complete({completionMetadata:e}){try{let o=N.getModel(),r=this.createRequestBody(e,o),i=this.createHeaders(),n=await T.POST(G,r,{headers:i});if(!n.choices||n.choices.length===0)throw new Error("No completion choices received from API");return{completion:n.choices[0].message.content}}catch(o){return o instanceof Error?a(o).apiError("Failed to fetch completion"):a(o).apiError("Unknown error while fetching completion"),{error:"Failed to generate completion"}}}createRequestBody(e,o){return{model:U[o],messages:[{role:"system",content:z(e)},{role:"user",content:Q(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var Ce=300,ge=S(X,Ce),he=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:i,onShowCompletion:n,options:s})=>{let m=e.getValue(),p=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column);if(!new R(o,e).shouldProvideCompletions())return c([]);let E=q(o,e).map(l=>({insertText:l.completion,range:l.range}));if(E.length)return n(),c(E);if(r.isCancellationRequested)return c([]);if(i)return c([]);try{let l=await ge({...s,text:m,model:e,position:o});if(l){let d=V(e,o,l),C=K(d,p,o,e);return k({completion:d,range:C,textBeforeCursorInLine:u(o,e)}),n(),c([{insertText:d,range:C}])}}catch(l){a(l).completionError("Failed to fetch completion item")}return c([])},Z=he;var w=!1,A=!1,ee=(t,e,o)=>{try{let r=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:async(n,s,m,p)=>Z({monaco:t,model:n,position:s,token:p,isCompletionAccepted:w,onShowCompletion:()=>A=!0,options:o}),freeInlineCompletions:b});return e.onKeyDown(n=>{A&&(n.keyCode===t.KeyCode.Tab||n.keyCode===t.KeyCode.RightArrow&&n.metaKey)?(w=!0,A=!1):w=!1}),{unregister:()=>{r.dispose(),F()}}}catch(r){return a(r).editorError("Error while registering Copilot"),{unregister:b}}};0&&(module.exports={Copilot,registerCopilot});
37
+ Specific instructions:
38
+ - The cursor position is marked with '${h}'.
39
+ - Your completion must start exactly at the cursor position.
40
+ - Do not repeat any code that appears before or after the cursor.
41
+ - Ensure your completion does not introduce any syntactical or logical errors.
42
+ - If filling in the middle, replace '${h}' entirely with your completion.
43
+ - If completing the code, start from '${h}' and provide a logical continuation.
44
+ - Consider any imports, function definitions, or class structures in the surrounding code.
45
+ - If applicable, use appropriate error handling and follow language-specific best practices.
46
+ - Optimize for readability and performance where possible.
47
+
48
+ Remember, output only the necessary completion code without any additional explanations or content.
49
+
50
+ Here's the code snippet for completion:
51
+
52
+ <code>
53
+ ${n}${h}${s}
54
+ </code>`;return l&&l.length>0&&(a+=`
55
+
56
+ Additional context from related files:
57
+
58
+ `,a+=l.map(d=>`// Path: ${d.path}
59
+ ${d.content}
60
+ `).join(`
61
+ `)),a.endsWith(".")?a:`${a}.`};var de="application/json",Z=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:i,model:n,position:s})=>{try{let{completion:l}=await x.POST(e,{completionMetadata:ue({filename:t,position:s,model:n,language:o,technologies:r,externalContext:i})},{headers:{"Content-Type":de},error:"Error while fetching completion item"});return l||null}catch(l){return m(l).completionError("Error while fetching completion item"),null}},ue=({filename:t,position:e,model:o,language:r,technologies:i,externalContext:n})=>{let s=Ce(e,o),l=C(e,o),p=I(e,o);return{filename:t,language:r,technologies:i,externalContext:n,textBeforeCursor:l,textAfterCursor:p,editorState:{completionMode:s}}},Ce=(t,e)=>{let o=C(t,e),r=I(t,e);return o&&r?"fill-in-the-middle":"completion"};var M=class{constructor(e,o){if(!e)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=e,L.setModel(o?.model||y)}async complete({completionMetadata:e}){try{let o=L.getModel(),r=this.createRequestBody(e,o),i=this.createHeaders(),n=await x.POST(G,r,{headers:i});if(!n.choices||n.choices.length===0)throw new Error("No completion choices received from API");return{completion:n.choices[0].message.content}}catch(o){return o instanceof Error?m(o).apiError("Failed to fetch completion"):m(o).apiError("Unknown error while fetching completion"),{error:"Failed to generate completion"}}}createRequestBody(e,o){return{...j,model:U[o],messages:[{role:"system",content:Q(e)},{role:"user",content:X(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var ge=300,he=S(Z,ge),fe=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:i,onShowCompletion:n,options:s})=>{let l=e.getValue(),p=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column);if(!new P(o,e).shouldProvideCompletions())return c([]);let f=k(o,e).map(a=>({insertText:a.completion,range:a.range}));if(f.length)return n(),c(f);if(r.isCancellationRequested)return c([]);if(i)return c([]);try{let a=await he({...s,text:l,model:e,position:o});if(a){let d=z(e,o,a),w=Y(d,p,o,e);return q({completion:d,range:w,textBeforeCursorInLine:u(o,e)}),n(),c([{insertText:d,range:w}])}}catch(a){m(a).completionError("Failed to fetch completion item")}return c([])},ee=fe;var A=!1,N=!1,te=(t,e,o)=>{try{let r=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:async(n,s,l,p)=>ee({monaco:t,model:n,position:s,token:p,isCompletionAccepted:A,onShowCompletion:()=>N=!0,options:o}),freeInlineCompletions:O});return e.onKeyDown(n=>{N&&(n.keyCode===t.KeyCode.Tab||n.keyCode===t.KeyCode.RightArrow&&n.metaKey)?(A=!0,N=!1):A=!1}),{unregister:()=>{r.dispose(),F()}}}catch(r){return m(r).editorError("Error while registering Copilot"),{unregister:O}}};0&&(module.exports={Copilot,registerCopilot});
package/build/index.mjs CHANGED
@@ -1,19 +1,61 @@
1
- var O=()=>{},A=(t,e=1e3)=>{let o=null;return(...i)=>(o&&clearTimeout(o),new Promise((n,s)=>{o=setTimeout(()=>{t(...i).then(n).catch(s)},e)}))},S=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var x=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],B=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),u=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),$=t=>{let e=t.split(`
2
- `);return e[e.length-1].length};var g=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),I=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var _=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},i=e==="POST"&&o.body?JSON.stringify(o.body):void 0,n=await fetch(t,{method:e,headers:r,body:i,signal:o.signal});if(!n.ok)throw new Error(`${o.error||"Network error"}: ${n.statusText}`);return n.json()},Z=(t,e)=>_(t,"GET",e),ee=(t,e,o)=>_(t,"POST",{...o,body:e}),T={GET:Z,POST:ee};var P=class{constructor(e,o){this.formattedCompletion="";this.originalCompletion="";this.model=e,this.cursorPosition=o,this.lineCount=e.getLineCount()}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
3
- `&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=g(this.cursorPosition,this.model).trim(),o=this.normalise(this.formattedCompletion),r=0,i=Math.min(o.length,e.length);for(let n=1;n<=i;n++){let s=e.slice(-n),m=o.slice(0,n);if(s===m)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.lineCount;e++){let o=this.model.getLineContent(e);if(this.normalise(o)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}format(e){return this.originalCompletion=e,this.formattedCompletion=e,this.ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().trimStart(),this.formattedCompletion}};var te=10,h=[],D=(t,e)=>h.filter(o=>{let r=e.getValueInRange(o.range);return u(t,e).startsWith(o.textBeforeCursorInLine)&&(o.range.startLineNumber===t.lineNumber&&t.column===o.range.startColumn||o.completion.startsWith(r)&&o.range.startLineNumber===t.lineNumber&&t.column>=o.range.startColumn-r.length&&t.column<=o.range.endColumn)}),q=t=>{h.length>=te&&h.shift(),h.push(t)},k=()=>{h.length=0};var F={llama:"llama3-70b-8192"},y="llama",U="https://api.groq.com/openai/v1/chat/completions";var G=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var j=(t,e)=>{let o=x(t,e);return!!o&&!G.has(o)},W=(t,e)=>{let o=B(t,e).trim(),r=u(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var H=(t,e,o,r)=>{let i=(t.match(/\n/g)||[]).length,n=$(t),s=x(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+i,endColumn:t.includes(s)?o.lineNumber===e.startLineNumber&&i===0?o.column+n:n:o.column}},K=(t,e,o)=>new P(t,e).format(o),c=t=>({items:t,enableForwardStability:!0});var R=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!j(this.cursorPosition,this.model)&&!W(this.cursorPosition,this.model)}};var M=class{static getModel(){return this.model}static setModel(e){this.model=e}};M.model=y;var b=M;var L=class{constructor(e){this.error=e}logError(e,o,r){console.error(`${e}: ${o}`,r)}monacopilotError(e){this.logError("MONACO_PILOT_ERROR",e,this.error)}apiError(e){this.logError("API_ERROR",e,this.error)}completionError(e){this.logError("COMPLETION_ERROR",e,this.error)}predictionError(e){this.logError("PREDICTION_ERROR",e,this.error)}editorError(e){this.logError("EDITOR_ERROR",e,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},a=t=>new L(t);var f="<cursor>",V=t=>t==="javascript"?"latest JavaScript":t,Y=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},J=t=>{let e=V(t.language),o=Y(t.editorState.completionMode);return`You are a world-class${e?` ${e}`:""} coding assistant renowned for your exceptional expertise in ${o}.`},oe=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${S(t)}`:"",r=V(e);return`The code is written${r?` in ${r}`:""}${o}.`},z=t=>{let{filename:e,language:o,technologies:r,editorState:i,textBeforeCursor:n,textAfterCursor:s,externalContext:m}=t,p=Y(i.completionMode),E=e?`the file named ${e}`:"a larger project",l=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${f}'.
4
- Your task is to assist with ${p}. This code is part of ${E}. Please `;switch(i.completionMode){case"fill-in-the-middle":l+=`generate a completion to fill the middle of the code around '${f}'.
5
- Ensure the completion replaces '${f}' precisely, maintaining consistency, semantic accuracy, and relevance to the context.
6
- The completion must start exactly from the cursor position without any preceding or following characters,
7
- and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":l+=`provide the necessary completion for '${f}' while ensuring consistency, semantic accuracy, and relevance to the context.
8
- The completion must start exactly from the cursor position without any preceding or following characters,
9
- and it should not introduce any syntactical or semantic errors to the existing code.`;break}l+=` Output only the necessary completion code, without additional explanations or content.
10
- ${oe(r,o)}`;let d=`${n}${f}${s}
11
-
12
- `;return m&&m.length>0&&(d+=m.map(C=>`// Path: ${C.path}
13
- ${C.content}
14
- `).join(`
15
- `)),l+=`
1
+ var M=()=>{},w=(t,e=1e3)=>{let o=null;return(...i)=>(o&&clearTimeout(o),new Promise((n,s)=>{o=setTimeout(()=>{t(...i).then(n).catch(s)},e)}))},S=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var E=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],_=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),u=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),B=t=>{let e=t.split(`
2
+ `);return e[e.length-1].length};var C=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),b=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var D=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},i=e==="POST"&&o.body?JSON.stringify(o.body):void 0,n=await fetch(t,{method:e,headers:r,body:i,signal:o.signal});if(!n.ok)throw new Error(`${o.error||"Network error"}: ${n.statusText}`);return n.json()},ee=(t,e)=>D(t,"GET",e),te=(t,e,o)=>D(t,"POST",{...o,body:e}),x={GET:ee,POST:te};var T=class{constructor(e,o){this.formattedCompletion="";this.originalCompletion="";this.model=e,this.cursorPosition=o,this.lineCount=e.getLineCount()}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
3
+ `&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=C(this.cursorPosition,this.model).trim(),o=this.normalise(this.formattedCompletion),r=0,i=Math.min(o.length,e.length);for(let n=1;n<=i;n++){let s=e.slice(-n),l=o.slice(0,n);if(s===l)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.lineCount;e++){let o=this.model.getLineContent(e);if(this.normalise(o)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}format(e){return this.originalCompletion=e,this.formattedCompletion=e,this.ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().trimStart(),this.formattedCompletion}};var oe=10,g=[],$=(t,e)=>g.filter(o=>{let r=e.getValueInRange(o.range);return u(t,e).startsWith(o.textBeforeCursorInLine)&&(o.range.startLineNumber===t.lineNumber&&t.column===o.range.startColumn||o.completion.startsWith(r)&&o.range.startLineNumber===t.lineNumber&&t.column>=o.range.startColumn-r.length&&t.column<=o.range.endColumn)}),k=t=>{g.length>=oe&&g.shift(),g.push(t)},q=()=>{g.length=0};var F={llama:"llama3-70b-8192"},y="llama",U="https://api.groq.com/openai/v1/chat/completions",G={temperature:.3};var j=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var H=(t,e)=>{let o=E(t,e);return!!o&&!j.has(o)},W=(t,e)=>{let o=_(t,e).trim(),r=u(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var K=(t,e,o,r)=>{let i=(t.match(/\n/g)||[]).length,n=B(t),s=E(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+i,endColumn:t.includes(s)?o.lineNumber===e.startLineNumber&&i===0?o.column+n:n:o.column}},Y=(t,e,o)=>new T(t,e).format(o),c=t=>({items:t,enableForwardStability:!0});var P=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!H(this.cursorPosition,this.model)&&!W(this.cursorPosition,this.model)}};var R=class{static getModel(){return this.model}static setModel(e){this.model=e}};R.model=y;var O=R;var I=class{constructor(e){this.error=e}logError(e,o,r){console.error(`${e}: ${o}`,r)}monacopilotError(e){this.logError("MONACO_PILOT_ERROR",e,this.error)}apiError(e){this.logError("API_ERROR",e,this.error)}completionError(e){this.logError("COMPLETION_ERROR",e,this.error)}predictionError(e){this.logError("PREDICTION_ERROR",e,this.error)}editorError(e){this.logError("EDITOR_ERROR",e,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},m=t=>new I(t);var h="<<CURSOR>>",z=t=>t==="javascript"?"latest JavaScript":t,V=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},J=t=>{let e=z(t.language),o=V(t.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${o} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions.
4
+
5
+ ### Instructions:
6
+ - Provide only the requested code completion without any additional explanations or markdown.
7
+ - Ensure your suggestions seamlessly integrate with the existing code structure and style.
8
+ - Maintain consistent indentation and formatting with the surrounding code.
9
+ - Start your completion exactly at the cursor position (${h}).
10
+ - Do not repeat any existing code before or after the cursor.
11
+ - Respect the project's coding conventions, naming styles, and design patterns.
12
+ - Consider the broader context of the file and project when making suggestions.
13
+ - Optimize for readability, maintainability, and performance where applicable.
14
+ - Handle potential errors and edge cases in your completions when appropriate.
15
+ - Utilize modern language features and best practices specific to${r}.
16
+ - If multiple valid completions exist, choose the most likely and idiomatic one.
17
+ - If you cannot provide a meaningful completion, return an empty string.
18
+
19
+ ### Formatting Rules:
20
+ - Do not include any markdown or code block syntax.
21
+ - Insert newlines after opening brackets ({, [, () and before closing brackets (}, ], )).
22
+ - Add newlines after commas in multi-line structures.
23
+ - Do not suggest newlines after spaces or existing newlines.
24
+ - Match the indentation level of the current line for new lines.
25
+
26
+ Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},re=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${S(t)}`:"",r=z(e);return`The code is written${r?` in ${r}`:""}${o}.`},Q=t=>{let{filename:e,language:o,technologies:r,editorState:i,textBeforeCursor:n,textAfterCursor:s,externalContext:l}=t,p=V(i.completionMode),f=e?`the file named "${e}"`:"a larger project",a=`You are tasked with ${p} for a code snippet. The code is part of ${f}.
27
+
28
+ Your objective is to:
29
+ 1. Analyze the provided code snippet and its context.
30
+ 2. Generate a completion that seamlessly integrates with the existing code.
31
+ 3. Ensure your completion is syntactically correct and semantically meaningful.
32
+ 4. Adhere to the project's coding style and conventions.
33
+ 5. Consider the broader context of the file and any provided external context.
34
+
35
+ ${re(r,o)}
16
36
 
17
- <code>
18
- ${d}
19
- </code>`,l.endsWith(".")?l:`${l}.`};var re="application/json",Q=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:i,model:n,position:s})=>{try{let{completion:m}=await T.POST(e,{completionMetadata:ne({filename:t,position:s,model:n,language:o,technologies:r,externalContext:i})},{headers:{"Content-Type":re},error:"Error while fetching completion item"});return m||null}catch(m){return a(m).completionError("Error while fetching completion item"),null}},ne=({filename:t,position:e,model:o,language:r,technologies:i,externalContext:n})=>{let s=ie(e,o),m=g(e,o),p=I(e,o);return{filename:t,language:r,technologies:i,externalContext:n,textBeforeCursor:m,textAfterCursor:p,editorState:{completionMode:s}}},ie=(t,e)=>{let o=g(t,e),r=I(t,e);return o&&r?"fill-in-the-middle":"completion"};var N=class{constructor(e,o){if(!e)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=e,b.setModel(o?.model||y)}async complete({completionMetadata:e}){try{let o=b.getModel(),r=this.createRequestBody(e,o),i=this.createHeaders(),n=await T.POST(U,r,{headers:i});if(!n.choices||n.choices.length===0)throw new Error("No completion choices received from API");return{completion:n.choices[0].message.content}}catch(o){return o instanceof Error?a(o).apiError("Failed to fetch completion"):a(o).apiError("Unknown error while fetching completion"),{error:"Failed to generate completion"}}}createRequestBody(e,o){return{model:F[o],messages:[{role:"system",content:J(e)},{role:"user",content:z(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var se=300,le=A(Q,se),me=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:i,onShowCompletion:n,options:s})=>{let m=e.getValue(),p=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column);if(!new R(o,e).shouldProvideCompletions())return c([]);let E=D(o,e).map(l=>({insertText:l.completion,range:l.range}));if(E.length)return n(),c(E);if(r.isCancellationRequested)return c([]);if(i)return c([]);try{let l=await le({...s,text:m,model:e,position:o});if(l){let d=K(e,o,l),C=H(d,p,o,e);return q({completion:d,range:C,textBeforeCursorInLine:u(o,e)}),n(),c([{insertText:d,range:C}])}}catch(l){a(l).completionError("Failed to fetch completion item")}return c([])},X=me;var v=!1,w=!1,ae=(t,e,o)=>{try{let r=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:async(n,s,m,p)=>X({monaco:t,model:n,position:s,token:p,isCompletionAccepted:v,onShowCompletion:()=>w=!0,options:o}),freeInlineCompletions:O});return e.onKeyDown(n=>{w&&(n.keyCode===t.KeyCode.Tab||n.keyCode===t.KeyCode.RightArrow&&n.metaKey)?(v=!0,w=!1):v=!1}),{unregister:()=>{r.dispose(),k()}}}catch(r){return a(r).editorError("Error while registering Copilot"),{unregister:O}}};export{N as Copilot,ae as registerCopilot};
37
+ Specific instructions:
38
+ - The cursor position is marked with '${h}'.
39
+ - Your completion must start exactly at the cursor position.
40
+ - Do not repeat any code that appears before or after the cursor.
41
+ - Ensure your completion does not introduce any syntactical or logical errors.
42
+ - If filling in the middle, replace '${h}' entirely with your completion.
43
+ - If completing the code, start from '${h}' and provide a logical continuation.
44
+ - Consider any imports, function definitions, or class structures in the surrounding code.
45
+ - If applicable, use appropriate error handling and follow language-specific best practices.
46
+ - Optimize for readability and performance where possible.
47
+
48
+ Remember, output only the necessary completion code without any additional explanations or content.
49
+
50
+ Here's the code snippet for completion:
51
+
52
+ <code>
53
+ ${n}${h}${s}
54
+ </code>`;return l&&l.length>0&&(a+=`
55
+
56
+ Additional context from related files:
57
+
58
+ `,a+=l.map(d=>`// Path: ${d.path}
59
+ ${d.content}
60
+ `).join(`
61
+ `)),a.endsWith(".")?a:`${a}.`};var ne="application/json",X=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:i,model:n,position:s})=>{try{let{completion:l}=await x.POST(e,{completionMetadata:ie({filename:t,position:s,model:n,language:o,technologies:r,externalContext:i})},{headers:{"Content-Type":ne},error:"Error while fetching completion item"});return l||null}catch(l){return m(l).completionError("Error while fetching completion item"),null}},ie=({filename:t,position:e,model:o,language:r,technologies:i,externalContext:n})=>{let s=se(e,o),l=C(e,o),p=b(e,o);return{filename:t,language:r,technologies:i,externalContext:n,textBeforeCursor:l,textAfterCursor:p,editorState:{completionMode:s}}},se=(t,e)=>{let o=C(t,e),r=b(t,e);return o&&r?"fill-in-the-middle":"completion"};var L=class{constructor(e,o){if(!e)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=e,O.setModel(o?.model||y)}async complete({completionMetadata:e}){try{let o=O.getModel(),r=this.createRequestBody(e,o),i=this.createHeaders(),n=await x.POST(U,r,{headers:i});if(!n.choices||n.choices.length===0)throw new Error("No completion choices received from API");return{completion:n.choices[0].message.content}}catch(o){return o instanceof Error?m(o).apiError("Failed to fetch completion"):m(o).apiError("Unknown error while fetching completion"),{error:"Failed to generate completion"}}}createRequestBody(e,o){return{...G,model:F[o],messages:[{role:"system",content:J(e)},{role:"user",content:Q(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var le=300,ae=w(X,le),me=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:i,onShowCompletion:n,options:s})=>{let l=e.getValue(),p=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column);if(!new P(o,e).shouldProvideCompletions())return c([]);let f=$(o,e).map(a=>({insertText:a.completion,range:a.range}));if(f.length)return n(),c(f);if(r.isCancellationRequested)return c([]);if(i)return c([]);try{let a=await ae({...s,text:l,model:e,position:o});if(a){let d=Y(e,o,a),N=K(d,p,o,e);return k({completion:d,range:N,textBeforeCursorInLine:u(o,e)}),n(),c([{insertText:d,range:N}])}}catch(a){m(a).completionError("Failed to fetch completion item")}return c([])},Z=me;var v=!1,A=!1,pe=(t,e,o)=>{try{let r=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:async(n,s,l,p)=>Z({monaco:t,model:n,position:s,token:p,isCompletionAccepted:v,onShowCompletion:()=>A=!0,options:o}),freeInlineCompletions:M});return e.onKeyDown(n=>{A&&(n.keyCode===t.KeyCode.Tab||n.keyCode===t.KeyCode.RightArrow&&n.metaKey)?(v=!0,A=!1):v=!1}),{unregister:()=>{r.dispose(),q()}}}catch(r){return m(r).editorError("Error while registering Copilot"),{unregister:M}}};export{L as Copilot,pe as registerCopilot};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monacopilot",
3
- "version": "0.9.7",
3
+ "version": "0.9.8",
4
4
  "description": "AI auto-completion for Monaco Editor",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",