monacopilot 0.9.29 → 0.9.30

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
@@ -103,8 +103,10 @@ registerCopilot(monaco, editor, {
103
103
  });
104
104
  ```
105
105
 
106
- - `endpoint`: The URL of the API endpoint that we created in the previous step.
107
- - `language`: The language of the editor.
106
+ | Parameter | Type | Description |
107
+ | ---------- | -------- | ----------------------------------------------------------------- |
108
+ | `endpoint` | `string` | The URL of the API endpoint that we created in the previous step. |
109
+ | `language` | `string` | The language of the editor. |
108
110
 
109
111
  🎉 Hurray! Monacopilot is now connected to the Monaco Editor. Start typing and see completions in the editor.
110
112
 
@@ -139,6 +141,7 @@ You can use a custom AI model that isn't built into Monacopilot by setting up a
139
141
 
140
142
  ```javascript
141
143
  const copilot = new Copilot(process.env.HUGGINGFACE_API_KEY, {
144
+ // provider: 'huggingface', You don't need to set the provider if you are using a custom model.
142
145
  model: {
143
146
  config: (apiKey, prompt) => ({
144
147
  endpoint:
@@ -156,9 +159,18 @@ const copilot = new Copilot(process.env.HUGGINGFACE_API_KEY, {
156
159
  },
157
160
  },
158
161
  }),
159
- transformResponse: response => ({
160
- completion: response[0].generated_text,
161
- }),
162
+ transformResponse: response => {
163
+ if (response.error) {
164
+ return {
165
+ completion: null,
166
+ error: response.error,
167
+ };
168
+ }
169
+
170
+ return {
171
+ completion: response[0].generated_text,
172
+ };
173
+ },
162
174
  },
163
175
  });
164
176
  ```
@@ -167,15 +179,25 @@ const copilot = new Copilot(process.env.HUGGINGFACE_API_KEY, {
167
179
 
168
180
  The `model` option accepts an object with two functions:
169
181
 
170
- 1. `config`: A function that receives the API key and prompt data, and returns the configuration for the custom model API request.
182
+ | Function | Description | Type |
183
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
184
+ | `config` | A function that receives the API key and prompt data, and returns the configuration for the custom model API request. | `(apiKey: string, prompt: {system: string, user: string}) => { endpoint: string, body?: object, headers?: object }` |
185
+ | `transformResponse` | A function that takes the raw/parsed response from the custom model API and converts it into an object with the following structure: | `(response: unknown) => { completion: string \| null, error?: string }` |
186
+
187
+ The `config` function must return an object with the following properties:
188
+
189
+ | Property | Type | Description |
190
+ | ---------- | --------------------- | -------------------------------------------- |
191
+ | `endpoint` | `string` | The URL of the custom model API endpoint. |
192
+ | `body` | `object \| undefined` | The body of the custom model API request. |
193
+ | `headers` | `object \| undefined` | The headers of the custom model API request. |
171
194
 
172
- - `endpoint`: The URL for the custom model's API.
173
- - `body`: (optional) The request body data for the custom model API.
174
- - `headers`: (optional) Additional HTTP headers for the API request.
195
+ The `transformResponse` function must return an object with the following structure:
175
196
 
176
- 2. `transformResponse`: A function that takes the raw response from the custom model API and converts it into an object with the following structure:
177
- - `completion`: A string containing the generated text from the model to be used as the completion.
178
- - `error`: (optional) A string describing any error that occurred during the completion process.
197
+ | Property | Type | Description |
198
+ | ------------ | --------------------- | ----------------------------------------------------------- |
199
+ | `completion` | `string \| null` | The generated completion text to be inserted in the editor. |
200
+ | `error` | `string \| undefined` | An error message if something went wrong. |
179
201
 
180
202
  This structure allows for easy integration of the custom model's output with the rest of the Monacopilot system, providing either the generated completion text or an error message if something went wrong.
181
203
 
@@ -255,10 +277,10 @@ For additional `completionMetadata` needs, please [open an issue](https://github
255
277
 
256
278
  The `customPrompt` function should return an object with two properties:
257
279
 
258
- | Property | Type | Description |
259
- | -------- | ------ | ----------------------------------------------------- |
260
- | system | string | A string representing the system prompt for the model |
261
- | user | string | A string representing the user prompt for the model |
280
+ | Property | Type | Description |
281
+ | -------- | --------------------- | ----------------------------------------------------- |
282
+ | system | `string \| undefined` | A string representing the system prompt for the model |
283
+ | user | `string \| undefined` | A string representing the user prompt for the model |
262
284
 
263
285
  #### Example
264
286
 
package/build/index.d.mts CHANGED
@@ -50,7 +50,7 @@ type CustomModel = {
50
50
  * text to be inserted or used as the completion, without
51
51
  * any metadata or additional structure.
52
52
  */
53
- transformResponse: CustomModelResponse;
53
+ transformResponse: CustomModelTransformResponse;
54
54
  };
55
55
  type CustomModelConfig = (apiKey: string, prompt: {
56
56
  system: string;
@@ -72,7 +72,7 @@ type CustomModelConfig = (apiKey: string, prompt: {
72
72
  */
73
73
  body?: Record<string, unknown>;
74
74
  };
75
- type CustomModelResponse = (response: unknown) => CompletionResponse;
75
+ type CustomModelTransformResponse = (response: unknown) => CompletionResponse;
76
76
  type Endpoint = string;
77
77
  type Filename = string;
78
78
  type Technologies = string[];
@@ -264,4 +264,4 @@ declare class Copilot {
264
264
  */
265
265
  declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
266
266
 
267
- export { type CompletionMetadata, type CompletionModel, type CompletionProvider, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
267
+ export { type CompletionMetadata, type CompletionModel, type CompletionProvider, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type CustomModel, type CustomModelConfig, type CustomModelTransformResponse, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
package/build/index.d.ts CHANGED
@@ -50,7 +50,7 @@ type CustomModel = {
50
50
  * text to be inserted or used as the completion, without
51
51
  * any metadata or additional structure.
52
52
  */
53
- transformResponse: CustomModelResponse;
53
+ transformResponse: CustomModelTransformResponse;
54
54
  };
55
55
  type CustomModelConfig = (apiKey: string, prompt: {
56
56
  system: string;
@@ -72,7 +72,7 @@ type CustomModelConfig = (apiKey: string, prompt: {
72
72
  */
73
73
  body?: Record<string, unknown>;
74
74
  };
75
- type CustomModelResponse = (response: unknown) => CompletionResponse;
75
+ type CustomModelTransformResponse = (response: unknown) => CompletionResponse;
76
76
  type Endpoint = string;
77
77
  type Filename = string;
78
78
  type Technologies = string[];
@@ -264,4 +264,4 @@ declare class Copilot {
264
264
  */
265
265
  declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
266
266
 
267
- export { type CompletionMetadata, type CompletionModel, type CompletionProvider, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
267
+ export { type CompletionMetadata, type CompletionModel, type CompletionProvider, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type CustomModel, type CustomModelConfig, type CustomModelTransformResponse, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
package/build/index.js CHANGED
@@ -1,21 +1,21 @@
1
- "use strict";var B=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Te=(t,e)=>{for(var o in e)B(t,o,{get:e[o],enumerable:!0})},Pe=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of fe(e))!Ee.call(t,n)&&n!==o&&B(t,n,{get:()=>e[n],enumerable:!(r=he(e,n))||r.enumerable});return t};var ye=t=>Pe(B({},"__esModule",{value:!0}),t);var De={};Te(De,{Copilot:()=>I,registerCopilot:()=>ue});module.exports=ye(De);var V={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3.5-sonnet":"claude-3.5-sonnet-20240620","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307","o1-preview":"o1-preview","o1-mini":"o1-mini"},S={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-preview","o1-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},W="llama-3-70b",G="groq",Y={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},P=.3;var K=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var y=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}error(e,o){console.error(this.styleMessage(o.message,e,"error")),o.stack&&console.error(this.styleStackTrace(o.stack))}warn(e,o){console.warn(this.styleMessage(o,e,"warning"))}styleMessage(e,o,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,m=`\u2514${s}\u2518`,c=((w,Ce)=>{let ge=w.split(" "),_=[],C="";return ge.forEach(j=>{(C+j).length>Ce&&(_.push(C.trim()),C=""),C+=j+" "}),C.trim()&&_.push(C.trim()),_})(e,l-4),h=[a,...c.map(w=>`\u2502 ${w.padEnd(l-4)} \u2502`),m].join(`
1
+ "use strict";var S=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Te=Object.prototype.hasOwnProperty;var Pe=(t,e)=>{for(var o in e)S(t,o,{get:e[o],enumerable:!0})},ye=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ee(e))!Te.call(t,n)&&n!==o&&S(t,n,{get:()=>e[n],enumerable:!(r=fe(e,n))||r.enumerable});return t};var xe=t=>ye(S({},"__esModule",{value:!0}),t);var ke={};Pe(ke,{Copilot:()=>O,registerCopilot:()=>Ce});module.exports=xe(ke);var D=["groq","openai","anthropic"],W={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3.5-sonnet":"claude-3.5-sonnet-20240620","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307","o1-preview":"o1-preview","o1-mini":"o1-mini"},B={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-preview","o1-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},G="llama-3-70b",Y="groq",K={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},y=.3;var X=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var x=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}error(e,o){console.error(this.styleMessage(o.message,e,"error")),o.stack&&console.error(this.styleStackTrace(o.stack))}warn(e,o){console.warn(this.styleMessage(o,e,"warning"))}styleMessage(e,o,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,m=`\u2514${s}\u2518`,c=((w,ge)=>{let he=w.split(" "),_=[],C="";return he.forEach(U=>{(C+U).length>ge&&(_.push(C.trim()),C=""),C+=U+" "}),C.trim()&&_.push(C.trim()),_})(e,l-4),h=[a,...c.map(w=>`\u2502 ${w.padEnd(l-4)} \u2502`),m].join(`
2
2
  `);return`
3
3
  \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${o}]\x1B[0m \x1B[2m${i}\x1B[0m
4
4
  ${h}
5
5
  `}styleStackTrace(e){return e.split(`
6
6
  `).map((n,i)=>i===0?`\x1B[31m${n}\x1B[0m`:`\x1B[2m${n}\x1B[0m`).join(`
7
- `)}getTimestamp(){return new Date().toISOString()}};var f=class f{constructor(){this.logger=y.getInstance()}static getInstance(){return f.instance}handleError(e,o){let r=this.getErrorDetails(e);return this.logger.error(o,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};f.instance=new f;var D=f;var d=(t,e)=>D.getInstance().handleError(t,e);var X=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((l,s)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=s,o=setTimeout(()=>{l(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},x=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var M=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],z=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),g=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),J=t=>{let e=t.split(`
8
- `);return e[e.length-1].length+1};var k=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),$=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var Z=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()},xe=(t,e)=>Z(t,"GET",e),Me=(t,e,o)=>Z(t,"POST",{...o,body:e}),R={GET:xe,POST:Me};var Q=(t,e)=>{let o=M(t,e);return!!o&&!K.has(o)},ee=(t,e)=>{let o=z(t,e).trim(),r=g(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var b="<<CURSOR>>",te=t=>t==="javascript"?"latest JavaScript":t,oe=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Re=t=>{let e=te(t.language),o=oe(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. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},be=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${x(t)}`:"",r=te(e);return`The code is written${r?` in ${r}`:""}${o}.`},Ie=t=>{let{filename:e,language:o,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=t,a=oe(n),m=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${m}.
7
+ `)}getTimestamp(){return new Date().toISOString()}};var f=class f{constructor(){this.logger=x.getInstance()}static getInstance(){return f.instance}handleError(e,o){let r=this.getErrorDetails(e);return this.logger.error(o,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};f.instance=new f;var k=f;var d=(t,e)=>k.getInstance().handleError(t,e);var z=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((l,s)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=s,o=setTimeout(()=>{l(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},E=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var M=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],J=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),g=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),Z=t=>{let e=t.split(`
8
+ `);return e[e.length-1].length+1};var H=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),$=(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()},Me=(t,e)=>Q(t,"GET",e),Re=(t,e,o)=>Q(t,"POST",{...o,body:e}),R={GET:Me,POST:Re};var ee=(t,e)=>{let o=M(t,e);return!!o&&!X.has(o)},te=(t,e)=>{let o=J(t,e).trim(),r=g(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var I="<<CURSOR>>",oe=t=>t==="javascript"?"latest JavaScript":t,re=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Ie=t=>{let e=oe(t.language),o=re(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. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},Oe=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${E(t)}`:"",r=oe(e);return`The code is written${r?` in ${r}`:""}${o}.`},be=t=>{let{filename:e,language:o,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=t,a=re(n),m=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${m}.
9
9
 
10
- `;return p+=be(r,o),p+=`
10
+ `;return p+=Oe(r,o),p+=`
11
11
 
12
12
  Here are the details about how the completion should be generated:
13
- - The cursor position is marked with '${b}'.
13
+ - The cursor position is marked with '${I}'.
14
14
  - Your completion must start exactly at the cursor position.
15
15
  - Do not repeat any code that appears before or after the cursor.
16
16
  - Ensure your completion does not introduce any syntactical or logical errors.
17
- `,n==="fill-in-the-middle"?p+=` - If filling in the middle, replace '${b}' entirely with your completion.
18
- `:n==="completion"&&(p+=` - If completing the code, start from '${b}' and provide a logical continuation.
17
+ `,n==="fill-in-the-middle"?p+=` - If filling in the middle, replace '${I}' entirely with your completion.
18
+ `:n==="completion"&&(p+=` - If completing the code, start from '${I}' and provide a logical continuation.
19
19
  `),p+=` - Optimize for readability and performance where possible.
20
20
 
21
21
  Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
@@ -23,7 +23,7 @@ Here are the details about how the completion should be generated:
23
23
  Here's the code snippet for completion:
24
24
 
25
25
  <code>
26
- ${i}${b}${l}
26
+ ${i}${I}${l}
27
27
  </code>`,s&&s.length>0&&(p+=`
28
28
 
29
29
  Additional context from related files:
@@ -31,8 +31,8 @@ Additional context from related files:
31
31
  `,p+=s.map(c=>`// Path: ${c.path}
32
32
  ${c.content}
33
33
  `).join(`
34
- `)),p.endsWith(".")?p:`${p}.`};function H(t){return{system:Re(t),user:Ie(t)}}var re={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Oe={createRequestBody:(t,e)=>{let r=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:F(t),temperature:P,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the OpenAI response"}},ve={createRequestBody:(t,e)=>({model:F(t),temperature:P,messages:[{role:"system",content:e.system},{role:"user",content:e.user}]}),createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the Groq response"}},Le={createRequestBody:(t,e)=>({model:F(t),temperature:P,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:Ae(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>t.content?typeof t.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:t.content}:{completion:null,error:"No completion found in the Anthropic response"}},q={openai:Oe,groq:ve,anthropic:Le},ne=(t,e,o)=>{let r=q[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r.createRequestBody(t,o)},ie=(t,e)=>{let o=q[e];if(!o)throw new Error(`Unsupported provider: ${e}`);return o.createHeaders(t)},se=(t,e)=>{let o=q[e];if(!o)throw new Error(`Unsupported provider: ${e}`);return o.parseCompletion(t)},F=t=>V[t],ae=t=>Y[t],Ae=t=>re[t]||4096;var I=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??G,this.model=o.model??W,this.validateInputs()}validateInputs(){if(typeof this.model=="string"&&!S[this.provider].includes(this.model)){let e=x(S[this.provider]);throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${e}`)}}generatePrompt(e,o){let r=H(e);return o?{...r,...o(e)}:r}prepareRequest(e,o){let r=ae(this.provider),n,i=ie(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let s=this.model.config(this.apiKey,e);r=s.endpoint??r,n=s.body??{},i={...i,...s.headers}}else n=ne(this.model,this.provider,e);let l={...i,...o};return{endpoint:r,requestBody:n,headers:l}}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:l}=r??{},s=this.generatePrompt(n,l),{endpoint:a,requestBody:m,headers:p}=this.prepareRequest(s,i);try{let c=await R.POST(a,m,{headers:p});return typeof this.model=="object"&&"transformResponse"in this.model?this.model.transformResponse(c):se(c,this.provider)}catch(c){return{error:d(c,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}};var O=class t{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new t(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let o=/```[\s\S]*?```/g,r=e,n;for(;(n=o.exec(e))!==null;){let i=n[0],l=i.split(`
34
+ `)),p.endsWith(".")?p:`${p}.`};function q(t){return{system:Ie(t),user:be(t)}}var ne={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var ve={createRequestBody:(t,e)=>{let r=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:V(t),temperature:y,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the OpenAI response"}},Le={createRequestBody:(t,e)=>({model:V(t),temperature:y,messages:[{role:"system",content:e.system},{role:"user",content:e.user}]}),createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the Groq response"}},Ne={createRequestBody:(t,e)=>({model:V(t),temperature:y,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:Ae(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>t.content?typeof t.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:t.content}:{completion:null,error:"No completion found in the Anthropic response"}},F={openai:ve,groq:Le,anthropic:Ne},ie=(t,e,o)=>F[e].createRequestBody(t,o),se=(t,e)=>F[e].createHeaders(t),ae=(t,e)=>F[e].parseCompletion(t),V=t=>W[t],le=t=>K[t],Ae=t=>ne[t]||4096;var O=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??Y,this.model=o.model??G,this.validateInputs()}validateInputs(){if(!D.includes(this.provider))throw new Error(`The provider "${this.provider}" is not supported. Please choose a supported provider: ${E(D)}. If you're using a custom model, you don't need to specify a provider.`);if(typeof this.model=="string"&&!B[this.provider].includes(this.model)){let e=E(B[this.provider]);throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${e}`)}}generatePrompt(e,o){let r=q(e);return o?{...r,...o(e)}:r}prepareRequest(e,o){let r=le(this.provider),n,i=se(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let s=this.model.config(this.apiKey,e);r=s.endpoint??r,n=s.body??{},i={...i,...s.headers}}else n=ie(this.model,this.provider,e);let l={...i,...o};return{endpoint:r,requestBody:n,headers:l}}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:l}=r??{},s=this.generatePrompt(n,l),{endpoint:a,requestBody:m,headers:p}=this.prepareRequest(s,i);try{let c=await R.POST(a,m,{headers:p});return typeof this.model=="object"&&"transformResponse"in this.model?this.model.transformResponse(c):ae(c,this.provider)}catch(c){return{error:d(c,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}};var b=class t{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new t(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let o=/```[\s\S]*?```/g,r=e,n;for(;(n=o.exec(e))!==null;){let i=n[0],l=i.split(`
35
35
  `).slice(1,-1).join(`
36
36
  `);r=r.replace(i,l)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
37
37
 
38
- `),this}build(){return this.formattedCompletion}};var v=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!Q(this.cursorPosition,this.model)&&!ee(this.cursorPosition,this.model)}};var A=class A{constructor(){this.cache=[]}getCompletionCache(e,o){return this.cache.filter(r=>this.isCacheItemValid(r,e,o))}addCompletionCache(e){this.cache=[...this.cache.slice(-(A.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,o,r){let n=r.getValueInRange(e.range);return g(o,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){return e.range.startLineNumber===o.lineNumber&&o.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===o.lineNumber&&o.column>=e.range.startColumn-r.length&&o.column<=e.range.endColumn}};A.MAX_CACHE_SIZE=10;var L=A;var Ne="application/json",le=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:we({filename:t,position:l,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Ne},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},we=({filename:t,position:e,model:o,language:r,technologies:n,externalContext:i})=>{let l=_e(e,o),s=k(e,o),a=$(e,o);return{filename:t,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,cursorPosition:e,editorState:{completionMode:l}}},_e=(t,e)=>{let o=k(t,e),r=$(t,e);return o&&r?"fill-in-the-middle":"completion"};var pe=(t,e,o,r)=>{let n=(t.match(/\n/g)||[]).length,i=J(t),l=M(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+n,endColumn:t.includes(l)?o.lineNumber===e.startLineNumber&&n===0?o.column+(i-1):i:o.column}};function ce(t){return O.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=t=>({items:t,enableForwardStability:!0});var Be=300,me=X(le,Be),N=new L,Se=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new v(o,e).shouldProvideCompletions())return u([]);let s=N.getCompletionCache(o,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let a=me({...l,text:e.getValue(),model:e,position:o});r.onCancellationRequested(()=>{me.cancel()});let m=await a;if(m){let p=ce(m),c=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=pe(p,c,o,e);return N.addCompletionCache({completion:p,range:h,textBeforeCursorInLine:g(o,e)}),i(),u([{insertText:p,range:h}])}}catch(a){if(typeof a=="string"&&(a==="Cancelled"||a==="AbortError")||a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return u([]);d(a,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},de=Se;var E=new WeakMap,T=null,ue=(t,e,o)=>{T&&T.deregister();let r=[];E.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(s,a,m,p)=>{let c=E.get(e);if(c)return de({monaco:t,model:s,position:a,token:p,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0},options:o})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=E.get(e);if(!a)return;let m=s.keyCode===t.KeyCode.Tab||s.keyCode===t.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&m?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),N.clearCompletionCache(),E.delete(e),T=null}};return T=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),E.delete(e),T=null}}}};0&&(module.exports={Copilot,registerCopilot});
38
+ `),this}build(){return this.formattedCompletion}};var v=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!ee(this.cursorPosition,this.model)&&!te(this.cursorPosition,this.model)}};var N=class N{constructor(){this.cache=[]}getCompletionCache(e,o){return this.cache.filter(r=>this.isCacheItemValid(r,e,o))}addCompletionCache(e){this.cache=[...this.cache.slice(-(N.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,o,r){let n=r.getValueInRange(e.range);return g(o,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){return e.range.startLineNumber===o.lineNumber&&o.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===o.lineNumber&&o.column>=e.range.startColumn-r.length&&o.column<=e.range.endColumn}};N.MAX_CACHE_SIZE=10;var L=N;var we="application/json",pe=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:_e({filename:t,position:l,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":we},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},_e=({filename:t,position:e,model:o,language:r,technologies:n,externalContext:i})=>{let l=Se(e,o),s=H(e,o),a=$(e,o);return{filename:t,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,cursorPosition:e,editorState:{completionMode:l}}},Se=(t,e)=>{let o=H(t,e),r=$(t,e);return o&&r?"fill-in-the-middle":"completion"};var ce=(t,e,o,r)=>{let n=(t.match(/\n/g)||[]).length,i=Z(t),l=M(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+n,endColumn:t.includes(l)?o.lineNumber===e.startLineNumber&&n===0?o.column+(i-1):i:o.column}};function me(t){return b.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=t=>({items:t,enableForwardStability:!0});var De=300,de=z(pe,De),A=new L,Be=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new v(o,e).shouldProvideCompletions())return u([]);let s=A.getCompletionCache(o,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let a=de({...l,text:e.getValue(),model:e,position:o});r.onCancellationRequested(()=>{de.cancel()});let m=await a;if(m){let p=me(m),c=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=ce(p,c,o,e);return A.addCompletionCache({completion:p,range:h,textBeforeCursorInLine:g(o,e)}),i(),u([{insertText:p,range:h}])}}catch(a){if(typeof a=="string"&&(a==="Cancelled"||a==="AbortError")||a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return u([]);d(a,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},ue=Be;var T=new WeakMap,P=null,Ce=(t,e,o)=>{P&&P.deregister();let r=[];T.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(s,a,m,p)=>{let c=T.get(e);if(c)return ue({monaco:t,model:s,position:a,token:p,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0},options:o})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=T.get(e);if(!a)return;let m=s.keyCode===t.KeyCode.Tab||s.keyCode===t.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&m?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),A.clearCompletionCache(),T.delete(e),P=null}};return P=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),T.delete(e),P=null}}}};0&&(module.exports={Copilot,registerCopilot});
package/build/index.mjs CHANGED
@@ -1,21 +1,21 @@
1
- var j={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3.5-sonnet":"claude-3.5-sonnet-20240620","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307","o1-preview":"o1-preview","o1-mini":"o1-mini"},_={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-preview","o1-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},V="llama-3-70b",W="groq",G={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},P=.3;var Y=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var y=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}error(e,o){console.error(this.styleMessage(o.message,e,"error")),o.stack&&console.error(this.styleStackTrace(o.stack))}warn(e,o){console.warn(this.styleMessage(o,e,"warning"))}styleMessage(e,o,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,m=`\u2514${s}\u2518`,c=((N,de)=>{let ue=N.split(" "),w=[],C="";return ue.forEach(U=>{(C+U).length>de&&(w.push(C.trim()),C=""),C+=U+" "}),C.trim()&&w.push(C.trim()),w})(e,l-4),h=[a,...c.map(N=>`\u2502 ${N.padEnd(l-4)} \u2502`),m].join(`
1
+ var _=["groq","openai","anthropic"],U={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3.5-sonnet":"claude-3.5-sonnet-20240620","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307","o1-preview":"o1-preview","o1-mini":"o1-mini"},S={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-preview","o1-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},W="llama-3-70b",G="groq",Y={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},y=.3;var K=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var x=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}error(e,o){console.error(this.styleMessage(o.message,e,"error")),o.stack&&console.error(this.styleStackTrace(o.stack))}warn(e,o){console.warn(this.styleMessage(o,e,"warning"))}styleMessage(e,o,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,m=`\u2514${s}\u2518`,c=((A,ue)=>{let Ce=A.split(" "),w=[],C="";return Ce.forEach(j=>{(C+j).length>ue&&(w.push(C.trim()),C=""),C+=j+" "}),C.trim()&&w.push(C.trim()),w})(e,l-4),h=[a,...c.map(A=>`\u2502 ${A.padEnd(l-4)} \u2502`),m].join(`
2
2
  `);return`
3
3
  \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${o}]\x1B[0m \x1B[2m${i}\x1B[0m
4
4
  ${h}
5
5
  `}styleStackTrace(e){return e.split(`
6
6
  `).map((n,i)=>i===0?`\x1B[31m${n}\x1B[0m`:`\x1B[2m${n}\x1B[0m`).join(`
7
- `)}getTimestamp(){return new Date().toISOString()}};var f=class f{constructor(){this.logger=y.getInstance()}static getInstance(){return f.instance}handleError(e,o){let r=this.getErrorDetails(e);return this.logger.error(o,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};f.instance=new f;var B=f;var d=(t,e)=>B.getInstance().handleError(t,e);var K=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((l,s)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=s,o=setTimeout(()=>{l(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},x=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var M=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],X=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),g=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),z=t=>{let e=t.split(`
8
- `);return e[e.length-1].length+1};var S=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),D=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var J=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()},Ce=(t,e)=>J(t,"GET",e),ge=(t,e,o)=>J(t,"POST",{...o,body:e}),R={GET:Ce,POST:ge};var Z=(t,e)=>{let o=M(t,e);return!!o&&!Y.has(o)},Q=(t,e)=>{let o=X(t,e).trim(),r=g(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var b="<<CURSOR>>",ee=t=>t==="javascript"?"latest JavaScript":t,te=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},he=t=>{let e=ee(t.language),o=te(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. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},fe=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${x(t)}`:"",r=ee(e);return`The code is written${r?` in ${r}`:""}${o}.`},Ee=t=>{let{filename:e,language:o,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=t,a=te(n),m=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${m}.
7
+ `)}getTimestamp(){return new Date().toISOString()}};var f=class f{constructor(){this.logger=x.getInstance()}static getInstance(){return f.instance}handleError(e,o){let r=this.getErrorDetails(e);return this.logger.error(o,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};f.instance=new f;var D=f;var d=(t,e)=>D.getInstance().handleError(t,e);var X=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((l,s)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=s,o=setTimeout(()=>{l(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},E=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var M=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],z=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),g=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),J=t=>{let e=t.split(`
8
+ `);return e[e.length-1].length+1};var B=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),k=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var Z=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()},ge=(t,e)=>Z(t,"GET",e),he=(t,e,o)=>Z(t,"POST",{...o,body:e}),R={GET:ge,POST:he};var Q=(t,e)=>{let o=M(t,e);return!!o&&!K.has(o)},ee=(t,e)=>{let o=z(t,e).trim(),r=g(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var I="<<CURSOR>>",te=t=>t==="javascript"?"latest JavaScript":t,oe=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},fe=t=>{let e=te(t.language),o=oe(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. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},Ee=(t,e)=>{if(!t?.length&&!e)return"";let o=t?` using ${E(t)}`:"",r=te(e);return`The code is written${r?` in ${r}`:""}${o}.`},Te=t=>{let{filename:e,language:o,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=t,a=oe(n),m=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${m}.
9
9
 
10
- `;return p+=fe(r,o),p+=`
10
+ `;return p+=Ee(r,o),p+=`
11
11
 
12
12
  Here are the details about how the completion should be generated:
13
- - The cursor position is marked with '${b}'.
13
+ - The cursor position is marked with '${I}'.
14
14
  - Your completion must start exactly at the cursor position.
15
15
  - Do not repeat any code that appears before or after the cursor.
16
16
  - Ensure your completion does not introduce any syntactical or logical errors.
17
- `,n==="fill-in-the-middle"?p+=` - If filling in the middle, replace '${b}' entirely with your completion.
18
- `:n==="completion"&&(p+=` - If completing the code, start from '${b}' and provide a logical continuation.
17
+ `,n==="fill-in-the-middle"?p+=` - If filling in the middle, replace '${I}' entirely with your completion.
18
+ `:n==="completion"&&(p+=` - If completing the code, start from '${I}' and provide a logical continuation.
19
19
  `),p+=` - Optimize for readability and performance where possible.
20
20
 
21
21
  Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
@@ -23,7 +23,7 @@ Here are the details about how the completion should be generated:
23
23
  Here's the code snippet for completion:
24
24
 
25
25
  <code>
26
- ${i}${b}${l}
26
+ ${i}${I}${l}
27
27
  </code>`,s&&s.length>0&&(p+=`
28
28
 
29
29
  Additional context from related files:
@@ -31,8 +31,8 @@ Additional context from related files:
31
31
  `,p+=s.map(c=>`// Path: ${c.path}
32
32
  ${c.content}
33
33
  `).join(`
34
- `)),p.endsWith(".")?p:`${p}.`};function k(t){return{system:he(t),user:Ee(t)}}var oe={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Te={createRequestBody:(t,e)=>{let r=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:H(t),temperature:P,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the OpenAI response"}},Pe={createRequestBody:(t,e)=>({model:H(t),temperature:P,messages:[{role:"system",content:e.system},{role:"user",content:e.user}]}),createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the Groq response"}},ye={createRequestBody:(t,e)=>({model:H(t),temperature:P,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:xe(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>t.content?typeof t.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:t.content}:{completion:null,error:"No completion found in the Anthropic response"}},$={openai:Te,groq:Pe,anthropic:ye},re=(t,e,o)=>{let r=$[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r.createRequestBody(t,o)},ne=(t,e)=>{let o=$[e];if(!o)throw new Error(`Unsupported provider: ${e}`);return o.createHeaders(t)},ie=(t,e)=>{let o=$[e];if(!o)throw new Error(`Unsupported provider: ${e}`);return o.parseCompletion(t)},H=t=>j[t],se=t=>G[t],xe=t=>oe[t]||4096;var q=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??W,this.model=o.model??V,this.validateInputs()}validateInputs(){if(typeof this.model=="string"&&!_[this.provider].includes(this.model)){let e=x(_[this.provider]);throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${e}`)}}generatePrompt(e,o){let r=k(e);return o?{...r,...o(e)}:r}prepareRequest(e,o){let r=se(this.provider),n,i=ne(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let s=this.model.config(this.apiKey,e);r=s.endpoint??r,n=s.body??{},i={...i,...s.headers}}else n=re(this.model,this.provider,e);let l={...i,...o};return{endpoint:r,requestBody:n,headers:l}}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:l}=r??{},s=this.generatePrompt(n,l),{endpoint:a,requestBody:m,headers:p}=this.prepareRequest(s,i);try{let c=await R.POST(a,m,{headers:p});return typeof this.model=="object"&&"transformResponse"in this.model?this.model.transformResponse(c):ie(c,this.provider)}catch(c){return{error:d(c,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}};var I=class t{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new t(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let o=/```[\s\S]*?```/g,r=e,n;for(;(n=o.exec(e))!==null;){let i=n[0],l=i.split(`
34
+ `)),p.endsWith(".")?p:`${p}.`};function H(t){return{system:fe(t),user:Te(t)}}var re={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Pe={createRequestBody:(t,e)=>{let r=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:q(t),temperature:y,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the OpenAI response"}},ye={createRequestBody:(t,e)=>({model:q(t),temperature:y,messages:[{role:"system",content:e.system},{role:"user",content:e.user}]}),createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?{completion:t.choices[0].message.content}:{completion:null,error:"No completion found in the Groq response"}},xe={createRequestBody:(t,e)=>({model:q(t),temperature:y,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:Me(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>t.content?typeof t.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:t.content}:{completion:null,error:"No completion found in the Anthropic response"}},$={openai:Pe,groq:ye,anthropic:xe},ne=(t,e,o)=>$[e].createRequestBody(t,o),ie=(t,e)=>$[e].createHeaders(t),se=(t,e)=>$[e].parseCompletion(t),q=t=>U[t],ae=t=>Y[t],Me=t=>re[t]||4096;var F=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??G,this.model=o.model??W,this.validateInputs()}validateInputs(){if(!_.includes(this.provider))throw new Error(`The provider "${this.provider}" is not supported. Please choose a supported provider: ${E(_)}. If you're using a custom model, you don't need to specify a provider.`);if(typeof this.model=="string"&&!S[this.provider].includes(this.model)){let e=E(S[this.provider]);throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${e}`)}}generatePrompt(e,o){let r=H(e);return o?{...r,...o(e)}:r}prepareRequest(e,o){let r=ae(this.provider),n,i=ie(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let s=this.model.config(this.apiKey,e);r=s.endpoint??r,n=s.body??{},i={...i,...s.headers}}else n=ne(this.model,this.provider,e);let l={...i,...o};return{endpoint:r,requestBody:n,headers:l}}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:l}=r??{},s=this.generatePrompt(n,l),{endpoint:a,requestBody:m,headers:p}=this.prepareRequest(s,i);try{let c=await R.POST(a,m,{headers:p});return typeof this.model=="object"&&"transformResponse"in this.model?this.model.transformResponse(c):se(c,this.provider)}catch(c){return{error:d(c,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}};var O=class t{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new t(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let o=/```[\s\S]*?```/g,r=e,n;for(;(n=o.exec(e))!==null;){let i=n[0],l=i.split(`
35
35
  `).slice(1,-1).join(`
36
36
  `);r=r.replace(i,l)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
37
37
 
38
- `),this}build(){return this.formattedCompletion}};var O=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!Z(this.cursorPosition,this.model)&&!Q(this.cursorPosition,this.model)}};var L=class L{constructor(){this.cache=[]}getCompletionCache(e,o){return this.cache.filter(r=>this.isCacheItemValid(r,e,o))}addCompletionCache(e){this.cache=[...this.cache.slice(-(L.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,o,r){let n=r.getValueInRange(e.range);return g(o,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){return e.range.startLineNumber===o.lineNumber&&o.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===o.lineNumber&&o.column>=e.range.startColumn-r.length&&o.column<=e.range.endColumn}};L.MAX_CACHE_SIZE=10;var v=L;var Me="application/json",ae=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:Re({filename:t,position:l,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Me},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Re=({filename:t,position:e,model:o,language:r,technologies:n,externalContext:i})=>{let l=be(e,o),s=S(e,o),a=D(e,o);return{filename:t,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,cursorPosition:e,editorState:{completionMode:l}}},be=(t,e)=>{let o=S(t,e),r=D(t,e);return o&&r?"fill-in-the-middle":"completion"};var le=(t,e,o,r)=>{let n=(t.match(/\n/g)||[]).length,i=z(t),l=M(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+n,endColumn:t.includes(l)?o.lineNumber===e.startLineNumber&&n===0?o.column+(i-1):i:o.column}};function pe(t){return I.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=t=>({items:t,enableForwardStability:!0});var Ie=300,ce=K(ae,Ie),A=new v,Oe=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new O(o,e).shouldProvideCompletions())return u([]);let s=A.getCompletionCache(o,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let a=ce({...l,text:e.getValue(),model:e,position:o});r.onCancellationRequested(()=>{ce.cancel()});let m=await a;if(m){let p=pe(m),c=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=le(p,c,o,e);return A.addCompletionCache({completion:p,range:h,textBeforeCursorInLine:g(o,e)}),i(),u([{insertText:p,range:h}])}}catch(a){if(typeof a=="string"&&(a==="Cancelled"||a==="AbortError")||a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return u([]);d(a,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},me=Oe;var E=new WeakMap,T=null,ve=(t,e,o)=>{T&&T.deregister();let r=[];E.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(s,a,m,p)=>{let c=E.get(e);if(c)return me({monaco:t,model:s,position:a,token:p,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0},options:o})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=E.get(e);if(!a)return;let m=s.keyCode===t.KeyCode.Tab||s.keyCode===t.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&m?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),A.clearCompletionCache(),E.delete(e),T=null}};return T=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),E.delete(e),T=null}}}};export{q as Copilot,ve as registerCopilot};
38
+ `),this}build(){return this.formattedCompletion}};var b=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!Q(this.cursorPosition,this.model)&&!ee(this.cursorPosition,this.model)}};var L=class L{constructor(){this.cache=[]}getCompletionCache(e,o){return this.cache.filter(r=>this.isCacheItemValid(r,e,o))}addCompletionCache(e){this.cache=[...this.cache.slice(-(L.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,o,r){let n=r.getValueInRange(e.range);return g(o,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){return e.range.startLineNumber===o.lineNumber&&o.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===o.lineNumber&&o.column>=e.range.startColumn-r.length&&o.column<=e.range.endColumn}};L.MAX_CACHE_SIZE=10;var v=L;var Re="application/json",le=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:Ie({filename:t,position:l,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Re},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Ie=({filename:t,position:e,model:o,language:r,technologies:n,externalContext:i})=>{let l=Oe(e,o),s=B(e,o),a=k(e,o);return{filename:t,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,cursorPosition:e,editorState:{completionMode:l}}},Oe=(t,e)=>{let o=B(t,e),r=k(t,e);return o&&r?"fill-in-the-middle":"completion"};var pe=(t,e,o,r)=>{let n=(t.match(/\n/g)||[]).length,i=J(t),l=M(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+n,endColumn:t.includes(l)?o.lineNumber===e.startLineNumber&&n===0?o.column+(i-1):i:o.column}};function ce(t){return O.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=t=>({items:t,enableForwardStability:!0});var be=300,me=X(le,be),N=new v,ve=async({monaco:t,model:e,position:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new b(o,e).shouldProvideCompletions())return u([]);let s=N.getCompletionCache(o,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let a=me({...l,text:e.getValue(),model:e,position:o});r.onCancellationRequested(()=>{me.cancel()});let m=await a;if(m){let p=ce(m),c=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=pe(p,c,o,e);return N.addCompletionCache({completion:p,range:h,textBeforeCursorInLine:g(o,e)}),i(),u([{insertText:p,range:h}])}}catch(a){if(typeof a=="string"&&(a==="Cancelled"||a==="AbortError")||a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return u([]);d(a,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},de=ve;var T=new WeakMap,P=null,Le=(t,e,o)=>{P&&P.deregister();let r=[];T.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(s,a,m,p)=>{let c=T.get(e);if(c)return de({monaco:t,model:s,position:a,token:p,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0},options:o})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=T.get(e);if(!a)return;let m=s.keyCode===t.KeyCode.Tab||s.keyCode===t.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&m?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),N.clearCompletionCache(),T.delete(e),P=null}};return P=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),T.delete(e),P=null}}}};export{F as Copilot,Le as registerCopilot};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monacopilot",
3
- "version": "0.9.29",
3
+ "version": "0.9.30",
4
4
  "description": "AI auto-completion plugin for Monaco Editor",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",