monacopilot 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Monacopilot
2
2
 
3
- Extended [Monaco Editor](https://microsoft.github.io/monaco-editor/) with AI auto-completion, inspired by [GitHub Copilot](https://github.com/features/copilot/).
3
+ [Monaco Editor](https://microsoft.github.io/monaco-editor/) with AI auto-completion, inspired by [GitHub Copilot](https://github.com/features/copilot/).
4
4
 
5
5
  ## Documentation
6
6
 
@@ -11,3 +11,7 @@ Extended [Monaco Editor](https://microsoft.github.io/monaco-editor/) with AI aut
11
11
  For guidelines on contributing, Please read the [contributing guide](https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md).
12
12
 
13
13
  We welcome contributions from the community to enhance Monacopilot's capabilities and make it even more powerful ❤️
14
+
15
+ ## Security
16
+
17
+ MonacoPilot does not store or use your code; it only provides AI completions.
package/build/index.d.mts CHANGED
@@ -1,7 +1,12 @@
1
- import { EditorProps } from '@monaco-editor/react';
2
- export { BeforeMount, DiffBeforeMount, DiffEditor, DiffEditorProps, DiffOnMount, Monaco, MonacoDiffEditor, OnChange, OnMount, OnValidate, Theme, loader, useMonaco } from '@monaco-editor/react';
3
- import React from 'react';
1
+ import * as monaco from 'monaco-editor';
4
2
 
3
+ type Monaco = typeof monaco;
4
+
5
+ type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
6
+
7
+ interface CopilotOptions {
8
+ model: CompletionModel | undefined;
9
+ }
5
10
  type Endpoint = string;
6
11
  type Filename = string;
7
12
  type Technologies = string[];
@@ -20,17 +25,20 @@ type ExternalContext = {
20
25
  */
21
26
  content: string;
22
27
  }[];
23
- interface MonaCopilotProps extends EditorProps {
28
+ interface RegisterCopilotOptions {
24
29
  /**
25
- * The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
26
- * For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
30
+ * Language of the current model
27
31
  */
28
- filename?: Filename;
32
+ language: string;
29
33
  /**
30
34
  * The API endpoint where you started the completion service.
31
- * [Learn more](https://monacopilot.vercel.app/copilot/setup#integrating-copilot-to-the-editor)
32
35
  */
33
- endpoint?: Endpoint;
36
+ endpoint: Endpoint;
37
+ /**
38
+ * The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
39
+ * For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
40
+ */
41
+ filename?: Filename;
34
42
  /**
35
43
  * The technologies (libraries, frameworks, etc.) you want to use for the completion.
36
44
  * This can provide technology-specific completions.
@@ -63,19 +71,15 @@ interface CompletionMetadata {
63
71
  filename: Filename | undefined;
64
72
  technologies: Technologies | undefined;
65
73
  externalContext: ExternalContext | undefined;
66
- codeAfterCursor: string;
67
- codeBeforeCursor: string;
74
+ textAfterCursor: string;
75
+ textBeforeCursor: string;
68
76
  editorState: {
69
77
  completionMode: CompletionMode;
70
78
  };
71
79
  }
72
80
 
73
- interface CopilotOptions {
74
- model: CompletionModel | undefined;
75
- }
76
-
77
81
  /**
78
- * Copilot class for handling code completions using the Groq API.
82
+ * Copilot class for handling completions using the Groq API.
79
83
  */
80
84
  declare class Copilot {
81
85
  private readonly apiKey;
@@ -89,13 +93,21 @@ declare class Copilot {
89
93
  /**
90
94
  * Sends a completion request to Groq API and returns the completion.
91
95
  * @param {CompletionRequest} params - The metadata required to generate the completion.
92
- * @returns {Promise<CompletionResponse>} The completed code snippet or an error.
96
+ * @returns {Promise<CompletionResponse>} The completed text snippet or an error.
93
97
  */
94
98
  complete({ completionMetadata, }: CompletionRequest): Promise<CompletionResponse>;
95
99
  private createRequestBody;
96
100
  private createHeaders;
97
101
  }
98
102
 
99
- declare const MonaCopilot: ({ filename, endpoint, technologies, externalContext, onMount, ...props }: MonaCopilotProps) => React.JSX.Element;
103
+ /**
104
+ * Registers the Copilot with the Monaco editor.
105
+ * @param monaco The Monaco instance.
106
+ * @param editor The editor instance.
107
+ * @param options The options for the Copilot.
108
+ *
109
+ * @returns A function to unregister the Copilot. Use this to clean up the Copilot.
110
+ */
111
+ declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => (() => void);
100
112
 
101
- export { type CompletionRequest, type CompletionResponse, Copilot, type Endpoint, type MonaCopilotProps, type Technologies, MonaCopilot as default };
113
+ export { type CompletionRequest, type CompletionResponse, Copilot, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
package/build/index.d.ts CHANGED
@@ -1,7 +1,12 @@
1
- import { EditorProps } from '@monaco-editor/react';
2
- export { BeforeMount, DiffBeforeMount, DiffEditor, DiffEditorProps, DiffOnMount, Monaco, MonacoDiffEditor, OnChange, OnMount, OnValidate, Theme, loader, useMonaco } from '@monaco-editor/react';
3
- import React from 'react';
1
+ import * as monaco from 'monaco-editor';
4
2
 
3
+ type Monaco = typeof monaco;
4
+
5
+ type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
6
+
7
+ interface CopilotOptions {
8
+ model: CompletionModel | undefined;
9
+ }
5
10
  type Endpoint = string;
6
11
  type Filename = string;
7
12
  type Technologies = string[];
@@ -20,17 +25,20 @@ type ExternalContext = {
20
25
  */
21
26
  content: string;
22
27
  }[];
23
- interface MonaCopilotProps extends EditorProps {
28
+ interface RegisterCopilotOptions {
24
29
  /**
25
- * The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
26
- * For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
30
+ * Language of the current model
27
31
  */
28
- filename?: Filename;
32
+ language: string;
29
33
  /**
30
34
  * The API endpoint where you started the completion service.
31
- * [Learn more](https://monacopilot.vercel.app/copilot/setup#integrating-copilot-to-the-editor)
32
35
  */
33
- endpoint?: Endpoint;
36
+ endpoint: Endpoint;
37
+ /**
38
+ * The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
39
+ * For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
40
+ */
41
+ filename?: Filename;
34
42
  /**
35
43
  * The technologies (libraries, frameworks, etc.) you want to use for the completion.
36
44
  * This can provide technology-specific completions.
@@ -63,19 +71,15 @@ interface CompletionMetadata {
63
71
  filename: Filename | undefined;
64
72
  technologies: Technologies | undefined;
65
73
  externalContext: ExternalContext | undefined;
66
- codeAfterCursor: string;
67
- codeBeforeCursor: string;
74
+ textAfterCursor: string;
75
+ textBeforeCursor: string;
68
76
  editorState: {
69
77
  completionMode: CompletionMode;
70
78
  };
71
79
  }
72
80
 
73
- interface CopilotOptions {
74
- model: CompletionModel | undefined;
75
- }
76
-
77
81
  /**
78
- * Copilot class for handling code completions using the Groq API.
82
+ * Copilot class for handling completions using the Groq API.
79
83
  */
80
84
  declare class Copilot {
81
85
  private readonly apiKey;
@@ -89,13 +93,21 @@ declare class Copilot {
89
93
  /**
90
94
  * Sends a completion request to Groq API and returns the completion.
91
95
  * @param {CompletionRequest} params - The metadata required to generate the completion.
92
- * @returns {Promise<CompletionResponse>} The completed code snippet or an error.
96
+ * @returns {Promise<CompletionResponse>} The completed text snippet or an error.
93
97
  */
94
98
  complete({ completionMetadata, }: CompletionRequest): Promise<CompletionResponse>;
95
99
  private createRequestBody;
96
100
  private createHeaders;
97
101
  }
98
102
 
99
- declare const MonaCopilot: ({ filename, endpoint, technologies, externalContext, onMount, ...props }: MonaCopilotProps) => React.JSX.Element;
103
+ /**
104
+ * Registers the Copilot with the Monaco editor.
105
+ * @param monaco The Monaco instance.
106
+ * @param editor The editor instance.
107
+ * @param options The options for the Copilot.
108
+ *
109
+ * @returns A function to unregister the Copilot. Use this to clean up the Copilot.
110
+ */
111
+ declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => (() => void);
100
112
 
101
- export { type CompletionRequest, type CompletionResponse, Copilot, type Endpoint, type MonaCopilotProps, type Technologies, MonaCopilot as default };
113
+ export { type CompletionRequest, type CompletionResponse, Copilot, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
package/build/index.js CHANGED
@@ -1,29 +1,12 @@
1
- "use strict";var Pe=Object.create;var M=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,be=Object.prototype.hasOwnProperty;var Oe=(e,t)=>{for(var o in t)M(e,o,{get:t[o],enumerable:!0})},j=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Me(t))!be.call(e,n)&&n!==o&&M(e,n,{get:()=>t[n],enumerable:!(r=Re(t,n))||r.enumerable});return e};var xe=(e,t,o)=>(o=e!=null?Pe(Le(e)):{},j(t||!e||!e.__esModule?M(o,"default",{value:e,enumerable:!0}):o,e)),Ie=e=>j(M({},"__esModule",{value:!0}),e);var ke={};Oe(ke,{Copilot:()=>I,DiffEditor:()=>f.DiffEditor,default:()=>Te,loader:()=>f.loader,useMonaco:()=>f.useMonaco});module.exports=Ie(ke);var G={scrollBeyondLastColumn:0,codeLens:!1,minimap:{enabled:!1},quickSuggestions:!1,folding:!1,foldingHighlight:!1,foldingImportsByDefault:!1,links:!1,fontSize:14,wordWrap:"on",automaticLayout:!0};var H={llama:"llama3-70b-8192"},L="llama",U="https://api.groq.com/openai/v1/chat/completions";var W={javascript:1,typescript:2,typescriptreact:3,python:4,vue:5,php:6,dart:7,javascriptreact:8,go:9,css:10,cpp:11,html:12,scss:13,markdown:14,csharp:15,java:16,json:17,rust:18,ruby:19,c:20},v={" ":1,"!":2,'"':3,"#":4,$:5,"%":6,"&":7,"'":8,"(":9,")":10,"*":11,"+":12,",":13,"-":14,".":15,"/":16,0:17,1:18,2:19,3:20,4:21,5:22,6:23,7:24,8:25,9:26,":":27,";":28,"<":29,"=":30,">":31,"?":32,"@":33,A:34,B:35,C:36,D:37,E:38,F:39,G:40,H:41,I:42,J:43,K:44,L:45,M:46,N:47,O:48,P:49,Q:50,R:51,S:52,T:53,U:54,V:55,W:56,X:57,Y:58,Z:59,"[":60,"\\":61,"]":62,"^":63,_:64,"`":65,a:66,b:67,c:68,d:69,e:70,f:71,g:72,h:73,i:74,j:75,k:76,l:77,m:78,n:79,o:80,p:81,q:82,r:83,s:84,t:85,u:86,v:87,w:88,x:89,y:90,z:91,"{":92,"|":93,"}":94,"~":95},d=[.9978708359643611,.7001905605239328,-.1736749244124868,-.22994157947320112,.13406692641682572,-.007751370662011853,.0057783222035240715,.41910878254476003,-.1621657125711092,.13770814958908187,-.06036011308184006,-.07351180985800129,0,-.05584878151248109,.30618794079412015,-.1282197982598485,.10951859303997555,.1700461782788777,-.3346057842644757,.22497985923128136,0,-.44038101825774356,-.6540115939236782,.16595600081341702,.20733910722385135,-.1337033766105696,-.06923072125290894,-.05806684191976292,.3583334671633344,-.47357732824944315,.17810871365594377,.42268219963946685,0,0,-.16379620467004602,-.43893868831061167,0,.11570094006709251,.9326431262654882,-.9990110509203912,-.44125275652726503,-.15840786997162004,-.4600396256644451,-.018814811994044403,.09230944537175266,.025814790934742798,-1.0940162204190154,-.9407503631235489,-.9854303778694269,-1.1045822488262245,-1.1417299456573262,-1.5623704405345513,-.4157473855795939,-1.0244257735561713,-.7477401944601753,-1.1275109699068402,-.0714715633552533,-1.1408628006786907,-1.0409898655074672,-.2288889836518878,-.5469549893760344,-.181946611106845,.1264329316374918,0,0,.312206968554707,-.3656436392517924,.23655650686038968,.1014912419901576,0,.06287549221765308,0,0,.19027065218932154,-.8519502045974378,0,.23753599905971923,.2488809322489166,.019969251907983224,0,.06916505526229488,.29053356359188204,-.14484456555431657,.014768129429370188,-.15051464926341374,.07614835502776021,-.3317489901313935,0,0,.04921938684669103,-.28248576768353445,-.9708816204525345,-1.3560464522265527,.014165375212383239,-.23924166472544983,.10006595730248855,.09867233147279562,.32330430333220644,-.058625706114180595,.17149853105783947,.4436484054395367,.047189049576707255,.16832520944790552,.1117259900942179,-.35469010329927253,0,-.1528189124465582,-.3804848349564939,.07278077320753953,.13263786480064088,.22920682659292527,1.1512955314336537,0,.016939862282340023,.4242994650403408,.12759835577444986,-.5577261135825583,-.19764560943067672,-.4042102444736004,.12063461617733708,-.2933966817484834,.2715683893968593,0,-.7138548251238751,0,-.023066228703035277,0,-.06383043976746139,.09683723720709651,-.7337151424080791,0,-.27191370124625525,.2819781269656171,-.08711496549050252,.11048604909969338,-.0934849550450534,.0721001250772912,.2589126797890794,.6729582659532254,-.21921032738244908,-.21535277468651456,-.45474006124091354,-.05861820126419139,-.007875306207720204,-.056661261678809284,.17727881404222662,.23603713348534658,.17485861412377932,-.5737483768696752,-.38220029570342745,-.5202722985519168,-.37187947527657256,.47155277792990113,-.12077912346691123,.47825628981545326,.4736704404000214,-.1615218651546898,.18362447973513005,0,0,-.18183417425866824,0,0,-.2538532305733833,-.1303692690676528,-.4073577969188216,.04172985870928789,-.1704527388573901,0,0,.7536858953385828,-.44703159588787644,0,-.7246484085580873,-.21378128540782063,0,.037461090552656146,-.16205852364367032,-.10973952064404884,.017468043407647377,-.1288980387397392,0,0,0,-1.218692715379445,.05536949662193305,-.3763799844799116,-.1845001725624579,-.1615576298149558,0,-.15373262203249874,-.04603412604270418,0,-.3068149681460828,.09412352468269412,0,.09116543650609721,.06065865264082559,.05688267379386188,-.05873945477722306,0,.14532465133322153,.1870857769705463,.36304258043185555,.1411392422180405,.0630388629716367,0,-1.1170522012450395,.16133697772771127,.15908534390781448,-.23485453704002232,-.1419980841417892,.21909510179526218,.39948420260153766,.40802294284289187,.15403767653746853,0,.19764784115096676,.584914157527457,0,-.4573883817015294],V=-.3043572714994554,K=.15;var Y=(e,t=1e3)=>{let o=null;return(...n)=>(o&&clearTimeout(o),new Promise((i,s)=>{o=setTimeout(()=>{e(...n).then(i).catch(s)},t)}))},S=(e,t)=>{let o={...t};for(let r in e)typeof e[r]=="object"&&!Array.isArray(e[r])?t[r]&&typeof t[r]=="object"&&!Array.isArray(t[r])?o[r]=S(e[r],t[r]):o[r]={...e[r]}:o[r]=e[r];return o},z=e=>!e||e.length===0?"":e.length===1?e[0]:`${e.slice(0,-1).join(", ")} and ${e.slice(-1)}`,N=e=>e.split("").reverse().join("");var J=(e,t)=>e[t]||"",$=e=>e.split(`
2
- `)[e.split(`
3
- `).length-1].length;var X=(e,t)=>e.split(`
4
- `)[t-1];var Q=async(e,t,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=t==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(e,{method:t,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${o.error||"Network error"}: ${i.statusText}`);return i.json()},Ae=(e,t)=>Q(e,"GET",t),we=(e,t,o)=>Q(e,"POST",{...o,body:t}),b={GET:Ae,POST:we};var E="<<CURSOR>>",Z=e=>e==="javascript"?"latest JavaScript":e,ee=e=>{switch(e){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code";default:return"completing the code"}},te=e=>{let t=Z(e.language),o=ee(e.editorState.completionMode);return`You are an expert ${t||""} code completion assistant known for exceptional skill in ${o}.`},_e=(e,t)=>{if(!e?.length&&!t)return"";let o=z(e),r=Z(t);return`The code is written${r?` in ${r}`:""}${o?` using ${o}`:""}.`},oe=e=>{let{filename:t,language:o,technologies:r,editorState:n,codeBeforeCursor:i,codeAfterCursor:s,externalContext:c}=e,l=ee(n.completionMode),p=t?`the file named ${t}`:"a larger project",a=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${E}'. Your task is to assist with ${l}. This code is part of ${p}. Please `;switch(n.completionMode){case"fill-in-the-middle":a+=`generate a completion to fill the middle of the code around '${E}'. Ensure the completion replaces '${E}' precisely, maintaining consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":a+=`provide the necessary completion for '${E}' while ensuring consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break}a+=` Output only the necessary completion code, without additional explanations or content.${_e(r,o)}`;let h=`${i}${E}${s}
1
+ "use strict";var b=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var re=Object.prototype.hasOwnProperty;var ne=(t,e)=>{for(var o in e)b(t,o,{get:e[o],enumerable:!0})},ie=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of oe(e))!re.call(t,n)&&n!==o&&b(t,n,{get:()=>e[n],enumerable:!(r=te(e,n))||r.enumerable});return t};var se=t=>ie(b({},"__esModule",{value:!0}),t);var fe={};ne(fe,{Copilot:()=>O,registerCopilot:()=>ee});module.exports=se(fe);var B=(t,e=1e3)=>{let o=null;return(...n)=>(o&&clearTimeout(o),new Promise((i,s)=>{o=setTimeout(()=>{t(...n).then(i).catch(s)},e)}))},$=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),h=(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 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 q=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=e==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(t,{method:e,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${o.error||"Network error"}: ${i.statusText}`);return i.json()},le=(t,e)=>q(t,"GET",e),me=(t,e,o)=>q(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,n=Math.min(o.length,e.length);for(let i=1;i<=n;i++){let s=e.slice(-i),l=o.slice(0,i);if(s===l)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.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=25,f=[],k=(t,e)=>f.filter(o=>{let r=e.getValueInRange(o.range);return h(t,e)===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}),F=t=>{f.length>=ae&&f.shift(),f.push(t)},L=()=>{f.length=0};var U={llama:"llama3-70b-8192"},y="llama",G="https://api.groq.com/openai/v1/chat/completions";var j=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var H=(t,e)=>{let o=x(t,e);return!!o&&!j.has(o)},W=(t,e)=>{let o=_(t,e).trim(),r=h(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var K=(t,e,o,r)=>{let n=(t.match(/\n/g)||[]).length,i=D(t),s=x(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+n,endColumn:t.includes(s)?o.lineNumber===e.startLineNumber&&n===0?o.column+i:i:o.column}},V=(t,e,o)=>new P(t,e).format(o),u=t=>({items:t,enableForwardStability:!0});var R=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!H(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 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))}},c=t=>new v(t);var E="<<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";default:return"completing the code"}},z=t=>{let e=Y(t.language),o=J(t.editorState.completionMode);return`You are an expert ${e||""} code completion assistant known for exceptional skill in ${o}.`},ce=(t,e)=>{if(!t?.length&&!e)return"";let o=$(t),r=Y(e);return`The code is written${r?` in ${r}`:""}${o?` using ${o}`:""}.`},Q=t=>{let{filename:e,language:o,technologies:r,editorState:n,textBeforeCursor:i,textAfterCursor:s,externalContext:l}=t,p=J(n.completionMode),d=e?`the file named ${e}`:"a larger project",m=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${E}'. Your task is to assist with ${p}. This code is part of ${d}. Please `;switch(n.completionMode){case"fill-in-the-middle":m+=`generate a completion to fill the middle of the code around '${E}'. Ensure the completion replaces '${E}' precisely, maintaining consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":m+=`provide the necessary completion for '${E}' while ensuring consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break}m+=` Output only the necessary completion code, without additional explanations or content.${ce(r,o)}`;let a=`${i}${E}${s}
5
4
 
6
- `;return c&&c.length>0&&(h+=c.map(m=>`// Path: ${m.path}
7
- ${m.content}
5
+ `;return l&&l.length>0&&(a+=l.map(C=>`// Path: ${C.path}
6
+ ${C.content}
8
7
  `).join(`
9
- `)),a+=`
8
+ `)),m+=`
10
9
 
11
10
  <code>
12
- ${h}
13
- </code>`,a.endsWith(".")?a:`${a}.`};var ve=2e3,Se=new Set(['"',"'","}","]",")",","," ",":","."]),re=(e,t)=>{let r=t.getLineContent(e.lineNumber).substring(e.column-1);return/^\s*$/.test(r)},ne=(e,t)=>{let o=t.getLineContent(e.lineNumber),r=J(o,e.column-1);return!Se.has(r)&&!!r},T=(e,t)=>{let o=t.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:e.lineNumber,endColumn:e.column}),r=t.getValueInRange({startLineNumber:e.lineNumber,startColumn:e.column,endLineNumber:t.getLineCount(),endColumn:t.getLineMaxColumn(t.getLineCount())});return{codeBeforeCursor:o,codeAfterCursor:r}},ie=(e,t)=>{let o=t.getLineContent(e.lineNumber),r=o.slice(e.column-1).trim(),n=o.slice(0,e.column-1).trim();return e.column<=3&&(r!==""||n!=="")},se=(e,t)=>{let o=t.getLineContent(e.lineNumber),[r,n]=[o.slice(0,e.column-1).trim(),o.slice(e.column-1).trim()];return r&&n?"fill-in-the-middle":"completion"},ce=(e,t,o=ve)=>t-e<o;var Ne="application/json",ae="Error while fetching completion item",le=async({filename:e,endpoint:t,language:o,technologies:r,externalContext:n,model:i,position:s,token:c})=>{let l=new AbortController;if(c.isCancellationRequested)return l.abort(),null;try{let{completion:p}=await b.POST(t,{completionMetadata:$e({filename:e,position:s,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Ne},error:ae,signal:l.signal});return p||null}catch(p){return console.error(ae,p),null}},$e=({filename:e,position:t,model:o,language:r,technologies:n,externalContext:i})=>{let s=se(t,o),{codeBeforeCursor:c,codeAfterCursor:l}=T(t,o);return{filename:e,language:r,technologies:n,externalContext:i,codeBeforeCursor:c,codeAfterCursor:l,editorState:{completionMode:s}}},pe=(e,t)=>{let{codeBeforeCursor:o}=T(e,t);return`${e.lineNumber}:${e.column}:${o}`};var D=class{constructor(){this.previousLabel=0,this.previousLabelTimestamp=Date.now()-3600*1e3,this.probabilityAccept=0}},me=e=>{let t=new D,o=t.previousLabel,r=0;e.properties.afterCursorWhitespace==="true"&&(r=1);let n=(Date.now()-t.previousLabelTimestamp)/1e3,i=Math.log(1+n),s=0,c=0,l=0,p=0;if(e.prefix){s=Math.log(1+$(e.prefix));let _=e.prefix.slice(-1);c=v[_]??0}let a=e.prefix?.trimEnd();if(a){l=Math.log(1+$(a));let _=a.slice(-1);p=v[_]??0}let h=e.measurements.documentLength?Math.log(1+e.measurements.documentLength):0,m=e.measurements.promptEndPos?Math.log(1+e.measurements.promptEndPos):0,R=e.measurements.promptEndPos&&e.measurements.documentLength?(e.measurements.promptEndPos+.5)/(1+e.measurements.documentLength):0,ye=e.properties.languageId?W[e.properties.languageId]:0,g=V;g+=d[0]*o+d[1]*r+d[2]*i,g+=d[3]*s+d[4]*l,g+=d[5]*h+d[6]*m,g+=d[7]*R,g+=d[8+ye],g+=d[29+c],g+=d[125+p];let k=1/(1+Math.exp(-g));return t.probabilityAccept=k,k};var O=class{constructor(t,o,r,n){this.cursorPosition=t,this.model=o,this.language=r,this.lastCompletionTime=n}calculateContextualScore(t,o,r){let{codeBeforeCursor:n}=T(t,o),i=re(t,o),s=o.getValueLength(),c=o.getOffsetAt(t);return me({properties:{afterCursorWhitespace:String(i),languageId:r},measurements:{documentLength:s,promptEndPos:c},prefix:n})}shouldProvideCompletions(){let t=Date.now();return this.calculateContextualScore(this.cursorPosition,this.model,this.language)>K&&!ne(this.cursorPosition,this.model)&&!ie(this.cursorPosition,this.model)&&!ce(this.lastCompletionTime,t)}};var x=class{static getModel(){return this.model}static setModel(t){this.model=t}};x.model=L;var F=x;var B=class{constructor(t){this.error=t}logError(t,o,r){console.error(`${t}: ${o}`,r)}monacopilotError(t){this.logError("MONACO_PILOT_ERROR",t,this.error)}apiError(t){this.logError("API_ERROR",t,this.error)}completionError(t){this.logError("COMPLETION_ERROR",t,this.error)}predictionError(t){this.logError("PREDICTION_ERROR",t,this.error)}editorError(t){this.logError("EDITOR_ERROR",t,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},u=e=>new B(e);var q=class extends Error{constructor(o,r,n){super(r);this.code=o;this.details=n;this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}},y=class extends q{constructor(t,o){super("COMPLETION_ERROR",t,o)}};var I=class{constructor(t,o){if(!t)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=t,F.setModel(o?.model||L)}async complete({completionMetadata:t}){try{let o=F.getModel(),r=this.createRequestBody(t,o),n=this.createHeaders(),i=await b.POST(U,r,{headers:n});if(!i.choices||i.choices.length===0)throw new y("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(o){return o instanceof y?u(o).completionError("Failed to fetch completion"):o instanceof Error?u(o).apiError("Failed to fetch completion"):u(o).apiError("Unknown error during completion"),{error:"Failed to generate completion"}}}createRequestBody(t,o){return{model:H[o],messages:[{role:"system",content:te(t)},{role:"user",content:oe(t)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var de={conso:"le.log($1)","new P":`romise((resolve, reject) => {
14
- $1
15
- })`,"new A":"rray","new S":"et","throw n":"ew Error($1)",setTimeout:`(() => {
16
- $1
17
- }, $2)`,setInterval:`(() => {
18
- $1
19
- }, $2)`,"async f":`unction $1() {
20
- $2
21
- }`,"async (":`) => {
22
- $1
23
- }`,"async =>":` {
24
- $1
25
- }`,") =>":` {
26
- $1
27
- }`,"=>":` {
28
- $1
29
- }`,"new M":"ap","new W":"eakMap"};var ue=[{language:"javascript",snippets:de}];var A=class{constructor(){this.predictions=new Map,this.loadPredictions()}predictCode(t,o){try{let r=this.predictions.get(t);if(!r)return"";let n=N(o);return this.findMatchingPrediction(r,n)}catch(r){return u(r).predictionError("Error while predicting code"),""}}loadPredictions(){ue.forEach(t=>{this.predictions.set(t.language,t.snippets)})}findMatchingPrediction(t,o){for(let[r,n]of Object.entries(t))if(o.startsWith(N(r)))return n;return""}};var P=xe(require("react")),Ee=require("@monaco-editor/react");var De=new A,w=new Map,ge=Date.now(),Fe=Y(le,250),fe=({monaco:e,filename:t,endpoint:o,technologies:r,language:n,externalContext:i})=>{if(!(!n||!o))try{let s=e.languages.registerInlineCompletionsProvider(n,{provideInlineCompletions:async(c,l,p,a)=>Be(e,c,l,p,a,{language:n,filename:t,endpoint:o,technologies:r,externalContext:i}),freeInlineCompletions:()=>{}});return()=>{s.dispose(),w.clear()}}catch(s){u(s).editorError("Error while registering copilot")}},Be=async(e,t,o,r,n,i)=>{if(!new O(o,t,i.language,ge).shouldProvideCompletions())return C([]);let c=pe(o,t),l=w.get(c);if(l&&!l.isExpired())return C([l.completion]);if(n.isCancellationRequested)return C([]);let p=t.getValue(),a=new e.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=De.predictCode(i.language,X(p,o.lineNumber));if(h){let m=he(h,a,!0);return Ce(c,m),C([m])}try{let m=await Fe({...i,code:p,model:t,position:o,token:n});if(m){ge=Date.now();let R=he(m,a);return Ce(c,R),C([R])}}catch(m){u(m).completionError("Failed to fetch completion item")}return C([])},he=(e,t,o=!1)=>({insertText:{snippet:e},range:t,completeBracketPairs:o}),Ce=(e,t)=>{w.set(e,{completion:t,timestamp:Date.now(),isExpired:()=>Date.now()-w.get(e).timestamp>6e4})},C=e=>({items:e,enableForwardStability:!0});var qe=({filename:e,endpoint:t,technologies:o,externalContext:r,onMount:n,...i})=>{let s=P.default.useRef(),c=P.default.useCallback((l,p)=>{try{s.current=fe({monaco:p,filename:e,endpoint:t,technologies:o,externalContext:r,language:i.language})}catch(a){u(a).monacopilotError("Error while registering copilot")}n?.(l,p)},[e,t,o,r,n,i.language]);return P.default.useEffect(()=>()=>{s.current?.()},[]),P.default.createElement(Ee.Editor,{...i,onMount:c,options:S(i.options,G)})},Te=qe;var f=require("@monaco-editor/react");0&&(module.exports={Copilot,DiffEditor,loader,useMonaco});
11
+ ${a}
12
+ </code>`,m.endsWith(".")?m:`${m}.`};var pe="application/json",X=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:n,model:i,position:s,token:l})=>{let p=new AbortController;if(l.isCancellationRequested)return p.abort(),null;try{let{completion:d}=await T.POST(e,{completionMetadata:de({filename:t,position:s,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":pe},error:"Error while fetching completion item",signal:p.signal});return d||null}catch(d){return c(d).completionError("Error while fetching completion item"),null}},de=({filename:t,position:e,model:o,language:r,technologies:n,externalContext:i})=>{let s=ue(e,o),l=g(e,o),p=I(e,o);return{filename:t,language:r,technologies:n,externalContext:i,textBeforeCursor:l,textAfterCursor:p,editorState:{completionMode:s}}},ue=(t,e)=>{let o=g(t,e),r=I(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),n=this.createHeaders(),i=await T.POST(G,r,{headers:n});if(!i.choices||i.choices.length===0)throw new Error("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(o){return o instanceof Error?c(o).apiError("Failed to fetch completion"):c(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=200,he=B(X,Ce),ge=async({monaco:t,model:e,position:o,context:r,token:n,hasCompletionBeenAccepted:i,onShowCompletion:s,options:l})=>{let p=e.getValue(),d=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column);if(!new R(o,e).shouldProvideCompletions())return u([]);let m=k(o,e).map(a=>({insertText:a.completion,range:a.range}));if(m.length)return s(),u(m);if(n.isCancellationRequested)return u([]);if(i)return u([]);try{let a=await he({...l,text:p,model:e,position:o,token:n});if(a){let C=V(e,o,a),S=K(C,d,o,e);return F({completion:C,range:S,textBeforeCursorInLine:h(o,e)}),s(),u([{insertText:C,range:S}])}}catch(a){c(a).completionError("Failed to fetch completion item")}return u([])},Z=ge;var w=!1,A=!1,ee=(t,e,o)=>{try{let r=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:async(n,i,s,l)=>Z({monaco:t,model:n,position:i,context:s,token:l,hasCompletionBeenAccepted:w,onShowCompletion:()=>A=!0,options:o}),freeInlineCompletions:()=>{}});return e.onKeyDown(n=>{A&&(n.keyCode===t.KeyCode.Tab||n.keyCode===t.KeyCode.RightArrow&&n.metaKey)?(w=!0,A=!1):w=!1}),()=>{r.dispose(),L()}}catch(r){return c(r).editorError("Error while registering Copilot"),()=>{L()}}};0&&(module.exports={Copilot,registerCopilot});
package/build/index.mjs CHANGED
@@ -1,29 +1,12 @@
1
- var q={scrollBeyondLastColumn:0,codeLens:!1,minimap:{enabled:!1},quickSuggestions:!1,folding:!1,foldingHighlight:!1,foldingImportsByDefault:!1,links:!1,fontSize:14,wordWrap:"on",automaticLayout:!0};var k={llama:"llama3-70b-8192"},P="llama",j="https://api.groq.com/openai/v1/chat/completions";var G={javascript:1,typescript:2,typescriptreact:3,python:4,vue:5,php:6,dart:7,javascriptreact:8,go:9,css:10,cpp:11,html:12,scss:13,markdown:14,csharp:15,java:16,json:17,rust:18,ruby:19,c:20},A={" ":1,"!":2,'"':3,"#":4,$:5,"%":6,"&":7,"'":8,"(":9,")":10,"*":11,"+":12,",":13,"-":14,".":15,"/":16,0:17,1:18,2:19,3:20,4:21,5:22,6:23,7:24,8:25,9:26,":":27,";":28,"<":29,"=":30,">":31,"?":32,"@":33,A:34,B:35,C:36,D:37,E:38,F:39,G:40,H:41,I:42,J:43,K:44,L:45,M:46,N:47,O:48,P:49,Q:50,R:51,S:52,T:53,U:54,V:55,W:56,X:57,Y:58,Z:59,"[":60,"\\":61,"]":62,"^":63,_:64,"`":65,a:66,b:67,c:68,d:69,e:70,f:71,g:72,h:73,i:74,j:75,k:76,l:77,m:78,n:79,o:80,p:81,q:82,r:83,s:84,t:85,u:86,v:87,w:88,x:89,y:90,z:91,"{":92,"|":93,"}":94,"~":95},d=[.9978708359643611,.7001905605239328,-.1736749244124868,-.22994157947320112,.13406692641682572,-.007751370662011853,.0057783222035240715,.41910878254476003,-.1621657125711092,.13770814958908187,-.06036011308184006,-.07351180985800129,0,-.05584878151248109,.30618794079412015,-.1282197982598485,.10951859303997555,.1700461782788777,-.3346057842644757,.22497985923128136,0,-.44038101825774356,-.6540115939236782,.16595600081341702,.20733910722385135,-.1337033766105696,-.06923072125290894,-.05806684191976292,.3583334671633344,-.47357732824944315,.17810871365594377,.42268219963946685,0,0,-.16379620467004602,-.43893868831061167,0,.11570094006709251,.9326431262654882,-.9990110509203912,-.44125275652726503,-.15840786997162004,-.4600396256644451,-.018814811994044403,.09230944537175266,.025814790934742798,-1.0940162204190154,-.9407503631235489,-.9854303778694269,-1.1045822488262245,-1.1417299456573262,-1.5623704405345513,-.4157473855795939,-1.0244257735561713,-.7477401944601753,-1.1275109699068402,-.0714715633552533,-1.1408628006786907,-1.0409898655074672,-.2288889836518878,-.5469549893760344,-.181946611106845,.1264329316374918,0,0,.312206968554707,-.3656436392517924,.23655650686038968,.1014912419901576,0,.06287549221765308,0,0,.19027065218932154,-.8519502045974378,0,.23753599905971923,.2488809322489166,.019969251907983224,0,.06916505526229488,.29053356359188204,-.14484456555431657,.014768129429370188,-.15051464926341374,.07614835502776021,-.3317489901313935,0,0,.04921938684669103,-.28248576768353445,-.9708816204525345,-1.3560464522265527,.014165375212383239,-.23924166472544983,.10006595730248855,.09867233147279562,.32330430333220644,-.058625706114180595,.17149853105783947,.4436484054395367,.047189049576707255,.16832520944790552,.1117259900942179,-.35469010329927253,0,-.1528189124465582,-.3804848349564939,.07278077320753953,.13263786480064088,.22920682659292527,1.1512955314336537,0,.016939862282340023,.4242994650403408,.12759835577444986,-.5577261135825583,-.19764560943067672,-.4042102444736004,.12063461617733708,-.2933966817484834,.2715683893968593,0,-.7138548251238751,0,-.023066228703035277,0,-.06383043976746139,.09683723720709651,-.7337151424080791,0,-.27191370124625525,.2819781269656171,-.08711496549050252,.11048604909969338,-.0934849550450534,.0721001250772912,.2589126797890794,.6729582659532254,-.21921032738244908,-.21535277468651456,-.45474006124091354,-.05861820126419139,-.007875306207720204,-.056661261678809284,.17727881404222662,.23603713348534658,.17485861412377932,-.5737483768696752,-.38220029570342745,-.5202722985519168,-.37187947527657256,.47155277792990113,-.12077912346691123,.47825628981545326,.4736704404000214,-.1615218651546898,.18362447973513005,0,0,-.18183417425866824,0,0,-.2538532305733833,-.1303692690676528,-.4073577969188216,.04172985870928789,-.1704527388573901,0,0,.7536858953385828,-.44703159588787644,0,-.7246484085580873,-.21378128540782063,0,.037461090552656146,-.16205852364367032,-.10973952064404884,.017468043407647377,-.1288980387397392,0,0,0,-1.218692715379445,.05536949662193305,-.3763799844799116,-.1845001725624579,-.1615576298149558,0,-.15373262203249874,-.04603412604270418,0,-.3068149681460828,.09412352468269412,0,.09116543650609721,.06065865264082559,.05688267379386188,-.05873945477722306,0,.14532465133322153,.1870857769705463,.36304258043185555,.1411392422180405,.0630388629716367,0,-1.1170522012450395,.16133697772771127,.15908534390781448,-.23485453704002232,-.1419980841417892,.21909510179526218,.39948420260153766,.40802294284289187,.15403767653746853,0,.19764784115096676,.584914157527457,0,-.4573883817015294],H=-.3043572714994554,U=.15;var W=(e,t=1e3)=>{let o=null;return(...n)=>(o&&clearTimeout(o),new Promise((i,s)=>{o=setTimeout(()=>{e(...n).then(i).catch(s)},t)}))},w=(e,t)=>{let o={...t};for(let r in e)typeof e[r]=="object"&&!Array.isArray(e[r])?t[r]&&typeof t[r]=="object"&&!Array.isArray(t[r])?o[r]=w(e[r],t[r]):o[r]={...e[r]}:o[r]=e[r];return o},V=e=>!e||e.length===0?"":e.length===1?e[0]:`${e.slice(0,-1).join(", ")} and ${e.slice(-1)}`,_=e=>e.split("").reverse().join("");var K=(e,t)=>e[t]||"",v=e=>e.split(`
2
- `)[e.split(`
3
- `).length-1].length;var Y=(e,t)=>e.split(`
4
- `)[t-1];var z=async(e,t,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=t==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(e,{method:t,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${o.error||"Network error"}: ${i.statusText}`);return i.json()},Ce=(e,t)=>z(e,"GET",t),fe=(e,t,o)=>z(e,"POST",{...o,body:t}),R={GET:Ce,POST:fe};var f="<<CURSOR>>",J=e=>e==="javascript"?"latest JavaScript":e,X=e=>{switch(e){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code";default:return"completing the code"}},Q=e=>{let t=J(e.language),o=X(e.editorState.completionMode);return`You are an expert ${t||""} code completion assistant known for exceptional skill in ${o}.`},Ee=(e,t)=>{if(!e?.length&&!t)return"";let o=V(e),r=J(t);return`The code is written${r?` in ${r}`:""}${o?` using ${o}`:""}.`},Z=e=>{let{filename:t,language:o,technologies:r,editorState:n,codeBeforeCursor:i,codeAfterCursor:s,externalContext:c}=e,l=X(n.completionMode),p=t?`the file named ${t}`:"a larger project",a=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${f}'. Your task is to assist with ${l}. This code is part of ${p}. Please `;switch(n.completionMode){case"fill-in-the-middle":a+=`generate a completion to fill the middle of the code around '${f}'. Ensure the completion replaces '${f}' precisely, maintaining consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":a+=`provide the necessary completion for '${f}' while ensuring consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break}a+=` Output only the necessary completion code, without additional explanations or content.${Ee(r,o)}`;let h=`${i}${f}${s}
1
+ var 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),h=(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}),O=(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()},Z=(t,e)=>D(t,"GET",e),ee=(t,e,o)=>D(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),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 te=25,f=[],q=(t,e)=>f.filter(o=>{let r=e.getValueInRange(o.range);return h(t,e)===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=>{f.length>=te&&f.shift(),f.push(t)},b=()=>{f.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)},H=(t,e)=>{let o=$(t,e).trim(),r=h(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var W=(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),u=t=>({items:t,enableForwardStability:!0});var R=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!j(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 I=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))}},c=t=>new L(t);var E="<<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";default:return"completing the code"}},J=t=>{let e=V(t.language),o=Y(t.editorState.completionMode);return`You are an expert ${e||""} code completion assistant known for exceptional skill in ${o}.`},oe=(t,e)=>{if(!t?.length&&!e)return"";let o=B(t),r=V(e);return`The code is written${r?` in ${r}`:""}${o?` using ${o}`:""}.`},z=t=>{let{filename:e,language:o,technologies:r,editorState:i,textBeforeCursor:n,textAfterCursor:s,externalContext:l}=t,p=Y(i.completionMode),d=e?`the file named ${e}`:"a larger project",m=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${E}'. Your task is to assist with ${p}. This code is part of ${d}. Please `;switch(i.completionMode){case"fill-in-the-middle":m+=`generate a completion to fill the middle of the code around '${E}'. Ensure the completion replaces '${E}' precisely, maintaining consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":m+=`provide the necessary completion for '${E}' while ensuring consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break}m+=` Output only the necessary completion code, without additional explanations or content.${oe(r,o)}`;let a=`${n}${E}${s}
5
4
 
6
- `;return c&&c.length>0&&(h+=c.map(m=>`// Path: ${m.path}
7
- ${m.content}
5
+ `;return l&&l.length>0&&(a+=l.map(C=>`// Path: ${C.path}
6
+ ${C.content}
8
7
  `).join(`
9
- `)),a+=`
8
+ `)),m+=`
10
9
 
11
10
  <code>
12
- ${h}
13
- </code>`,a.endsWith(".")?a:`${a}.`};var Te=2e3,ye=new Set(['"',"'","}","]",")",","," ",":","."]),ee=(e,t)=>{let r=t.getLineContent(e.lineNumber).substring(e.column-1);return/^\s*$/.test(r)},te=(e,t)=>{let o=t.getLineContent(e.lineNumber),r=K(o,e.column-1);return!ye.has(r)&&!!r},E=(e,t)=>{let o=t.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:e.lineNumber,endColumn:e.column}),r=t.getValueInRange({startLineNumber:e.lineNumber,startColumn:e.column,endLineNumber:t.getLineCount(),endColumn:t.getLineMaxColumn(t.getLineCount())});return{codeBeforeCursor:o,codeAfterCursor:r}},oe=(e,t)=>{let o=t.getLineContent(e.lineNumber),r=o.slice(e.column-1).trim(),n=o.slice(0,e.column-1).trim();return e.column<=3&&(r!==""||n!=="")},re=(e,t)=>{let o=t.getLineContent(e.lineNumber),[r,n]=[o.slice(0,e.column-1).trim(),o.slice(e.column-1).trim()];return r&&n?"fill-in-the-middle":"completion"},ne=(e,t,o=Te)=>t-e<o;var Pe="application/json",ie="Error while fetching completion item",se=async({filename:e,endpoint:t,language:o,technologies:r,externalContext:n,model:i,position:s,token:c})=>{let l=new AbortController;if(c.isCancellationRequested)return l.abort(),null;try{let{completion:p}=await R.POST(t,{completionMetadata:Re({filename:e,position:s,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Pe},error:ie,signal:l.signal});return p||null}catch(p){return console.error(ie,p),null}},Re=({filename:e,position:t,model:o,language:r,technologies:n,externalContext:i})=>{let s=re(t,o),{codeBeforeCursor:c,codeAfterCursor:l}=E(t,o);return{filename:e,language:r,technologies:n,externalContext:i,codeBeforeCursor:c,codeAfterCursor:l,editorState:{completionMode:s}}},ce=(e,t)=>{let{codeBeforeCursor:o}=E(e,t);return`${e.lineNumber}:${e.column}:${o}`};var S=class{constructor(){this.previousLabel=0,this.previousLabelTimestamp=Date.now()-3600*1e3,this.probabilityAccept=0}},ae=e=>{let t=new S,o=t.previousLabel,r=0;e.properties.afterCursorWhitespace==="true"&&(r=1);let n=(Date.now()-t.previousLabelTimestamp)/1e3,i=Math.log(1+n),s=0,c=0,l=0,p=0;if(e.prefix){s=Math.log(1+v(e.prefix));let I=e.prefix.slice(-1);c=A[I]??0}let a=e.prefix?.trimEnd();if(a){l=Math.log(1+v(a));let I=a.slice(-1);p=A[I]??0}let h=e.measurements.documentLength?Math.log(1+e.measurements.documentLength):0,m=e.measurements.promptEndPos?Math.log(1+e.measurements.promptEndPos):0,y=e.measurements.promptEndPos&&e.measurements.documentLength?(e.measurements.promptEndPos+.5)/(1+e.measurements.documentLength):0,he=e.properties.languageId?G[e.properties.languageId]:0,g=H;g+=d[0]*o+d[1]*r+d[2]*i,g+=d[3]*s+d[4]*l,g+=d[5]*h+d[6]*m,g+=d[7]*y,g+=d[8+he],g+=d[29+c],g+=d[125+p];let B=1/(1+Math.exp(-g));return t.probabilityAccept=B,B};var M=class{constructor(t,o,r,n){this.cursorPosition=t,this.model=o,this.language=r,this.lastCompletionTime=n}calculateContextualScore(t,o,r){let{codeBeforeCursor:n}=E(t,o),i=ee(t,o),s=o.getValueLength(),c=o.getOffsetAt(t);return ae({properties:{afterCursorWhitespace:String(i),languageId:r},measurements:{documentLength:s,promptEndPos:c},prefix:n})}shouldProvideCompletions(){let t=Date.now();return this.calculateContextualScore(this.cursorPosition,this.model,this.language)>U&&!te(this.cursorPosition,this.model)&&!oe(this.cursorPosition,this.model)&&!ne(this.lastCompletionTime,t)}};var L=class{static getModel(){return this.model}static setModel(t){this.model=t}};L.model=P;var N=L;var $=class{constructor(t){this.error=t}logError(t,o,r){console.error(`${t}: ${o}`,r)}monacopilotError(t){this.logError("MONACO_PILOT_ERROR",t,this.error)}apiError(t){this.logError("API_ERROR",t,this.error)}completionError(t){this.logError("COMPLETION_ERROR",t,this.error)}predictionError(t){this.logError("PREDICTION_ERROR",t,this.error)}editorError(t){this.logError("EDITOR_ERROR",t,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},u=e=>new $(e);var D=class extends Error{constructor(o,r,n){super(r);this.code=o;this.details=n;this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}},T=class extends D{constructor(t,o){super("COMPLETION_ERROR",t,o)}};var F=class{constructor(t,o){if(!t)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=t,N.setModel(o?.model||P)}async complete({completionMetadata:t}){try{let o=N.getModel(),r=this.createRequestBody(t,o),n=this.createHeaders(),i=await R.POST(j,r,{headers:n});if(!i.choices||i.choices.length===0)throw new T("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(o){return o instanceof T?u(o).completionError("Failed to fetch completion"):o instanceof Error?u(o).apiError("Failed to fetch completion"):u(o).apiError("Unknown error during completion"),{error:"Failed to generate completion"}}}createRequestBody(t,o){return{model:k[o],messages:[{role:"system",content:Q(t)},{role:"user",content:Z(t)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var le={conso:"le.log($1)","new P":`romise((resolve, reject) => {
14
- $1
15
- })`,"new A":"rray","new S":"et","throw n":"ew Error($1)",setTimeout:`(() => {
16
- $1
17
- }, $2)`,setInterval:`(() => {
18
- $1
19
- }, $2)`,"async f":`unction $1() {
20
- $2
21
- }`,"async (":`) => {
22
- $1
23
- }`,"async =>":` {
24
- $1
25
- }`,") =>":` {
26
- $1
27
- }`,"=>":` {
28
- $1
29
- }`,"new M":"ap","new W":"eakMap"};var pe=[{language:"javascript",snippets:le}];var b=class{constructor(){this.predictions=new Map,this.loadPredictions()}predictCode(t,o){try{let r=this.predictions.get(t);if(!r)return"";let n=_(o);return this.findMatchingPrediction(r,n)}catch(r){return u(r).predictionError("Error while predicting code"),""}}loadPredictions(){pe.forEach(t=>{this.predictions.set(t.language,t.snippets)})}findMatchingPrediction(t,o){for(let[r,n]of Object.entries(t))if(o.startsWith(_(r)))return n;return""}};import x from"react";import{Editor as Oe}from"@monaco-editor/react";var Me=new b,O=new Map,me=Date.now(),Le=W(se,250),ge=({monaco:e,filename:t,endpoint:o,technologies:r,language:n,externalContext:i})=>{if(!(!n||!o))try{let s=e.languages.registerInlineCompletionsProvider(n,{provideInlineCompletions:async(c,l,p,a)=>be(e,c,l,p,a,{language:n,filename:t,endpoint:o,technologies:r,externalContext:i}),freeInlineCompletions:()=>{}});return()=>{s.dispose(),O.clear()}}catch(s){u(s).editorError("Error while registering copilot")}},be=async(e,t,o,r,n,i)=>{if(!new M(o,t,i.language,me).shouldProvideCompletions())return C([]);let c=ce(o,t),l=O.get(c);if(l&&!l.isExpired())return C([l.completion]);if(n.isCancellationRequested)return C([]);let p=t.getValue(),a=new e.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=Me.predictCode(i.language,Y(p,o.lineNumber));if(h){let m=de(h,a,!0);return ue(c,m),C([m])}try{let m=await Le({...i,code:p,model:t,position:o,token:n});if(m){me=Date.now();let y=de(m,a);return ue(c,y),C([y])}}catch(m){u(m).completionError("Failed to fetch completion item")}return C([])},de=(e,t,o=!1)=>({insertText:{snippet:e},range:t,completeBracketPairs:o}),ue=(e,t)=>{O.set(e,{completion:t,timestamp:Date.now(),isExpired:()=>Date.now()-O.get(e).timestamp>6e4})},C=e=>({items:e,enableForwardStability:!0});var xe=({filename:e,endpoint:t,technologies:o,externalContext:r,onMount:n,...i})=>{let s=x.useRef(),c=x.useCallback((l,p)=>{try{s.current=ge({monaco:p,filename:e,endpoint:t,technologies:o,externalContext:r,language:i.language})}catch(a){u(a).monacopilotError("Error while registering copilot")}n?.(l,p)},[e,t,o,r,n,i.language]);return x.useEffect(()=>()=>{s.current?.()},[]),x.createElement(Oe,{...i,onMount:c,options:w(i.options,q)})},Ie=xe;import{DiffEditor as Xt,useMonaco as Qt,loader as Zt}from"@monaco-editor/react";export{F as Copilot,Xt as DiffEditor,Ie as default,Zt as loader,Qt as useMonaco};
11
+ ${a}
12
+ </code>`,m.endsWith(".")?m:`${m}.`};var re="application/json",Q=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:i,model:n,position:s,token:l})=>{let p=new AbortController;if(l.isCancellationRequested)return p.abort(),null;try{let{completion:d}=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",signal:p.signal});return d||null}catch(d){return c(d).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),l=g(e,o),p=O(e,o);return{filename:t,language:r,technologies:i,externalContext:n,textBeforeCursor:l,textAfterCursor:p,editorState:{completionMode:s}}},ie=(t,e)=>{let o=g(t,e),r=O(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,I.setModel(o?.model||y)}async complete({completionMetadata:e}){try{let o=I.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?c(o).apiError("Failed to fetch completion"):c(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=200,le=S(Q,se),me=async({monaco:t,model:e,position:o,context:r,token:i,hasCompletionBeenAccepted:n,onShowCompletion:s,options:l})=>{let p=e.getValue(),d=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column);if(!new R(o,e).shouldProvideCompletions())return u([]);let m=q(o,e).map(a=>({insertText:a.completion,range:a.range}));if(m.length)return s(),u(m);if(i.isCancellationRequested)return u([]);if(n)return u([]);try{let a=await le({...l,text:p,model:e,position:o,token:i});if(a){let C=K(e,o,a),A=W(C,d,o,e);return k({completion:C,range:A,textBeforeCursorInLine:h(o,e)}),s(),u([{insertText:C,range:A}])}}catch(a){c(a).completionError("Failed to fetch completion item")}return u([])},X=me;var v=!1,w=!1,ae=(t,e,o)=>{try{let r=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:async(i,n,s,l)=>X({monaco:t,model:i,position:n,context:s,token:l,hasCompletionBeenAccepted:v,onShowCompletion:()=>w=!0,options:o}),freeInlineCompletions:()=>{}});return e.onKeyDown(i=>{w&&(i.keyCode===t.KeyCode.Tab||i.keyCode===t.KeyCode.RightArrow&&i.metaKey)?(v=!0,w=!1):v=!1}),()=>{r.dispose(),b()}}catch(r){return c(r).editorError("Error while registering Copilot"),()=>{b()}}};export{N as Copilot,ae as registerCopilot};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "monacopilot",
3
- "version": "0.9.0",
4
- "description": "Extended Monaco Editor with AI auto-completion and new themes for React.",
3
+ "version": "0.9.2",
4
+ "description": "AI auto-completion for Monaco Editor",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",
7
7
  "types": "./build/index.d.ts",
@@ -45,13 +45,10 @@
45
45
  "ai-editor"
46
46
  ],
47
47
  "homepage": "https://monacopilot.vercel.app",
48
- "license": "MIT",
49
- "author": "Arshad Yaseen <m@arshadyaseen.com>",
50
- "peerDependencies": {
51
- "react": "^18.2.0",
52
- "react-dom": "^18.2.0"
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "https://github.com/arshad-yaseen/monacopilot"
53
51
  },
54
- "dependencies": {
55
- "@monaco-editor/react": "^4.6.0"
56
- }
52
+ "license": "MIT",
53
+ "author": "Arshad Yaseen <m@arshadyaseen.com>"
57
54
  }