monacopilot 0.9.29 → 0.9.31

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,4 +1,4 @@
1
- ![Hero Image](https://i.postimg.cc/PrsQ1KLb/Frame-1.png)
1
+ ![Hero Image](https://i.postimg.cc/GhpGVjVG/monacopilot-banner.png)
2
2
 
3
3
  # Monacopilot
4
4
 
@@ -16,11 +16,11 @@
16
16
  - [Custom Headers](#custom-headers)
17
17
  - [Custom Prompt](#custom-prompt)
18
18
  - [Configuration Options](#configuration-options)
19
+ - [Get Completions in Real-Time](#get-completions-in-real-time)
19
20
  - [External Context](#external-context)
20
21
  - [Filename](#filename)
21
22
  - [Completions for Specific Technologies](#completions-for-specific-technologies)
22
23
  - [Cost Overview](#cost-overview)
23
- - [FAQ](#faq)
24
24
  - [Contributing](#contributing)
25
25
 
26
26
  [Demo Video](https://github.com/user-attachments/assets/4af4e24a-1b05-4bee-84aa-1521ad7098cd)
@@ -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,26 +159,47 @@ 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
  ```
165
177
 
178
+ > Please make sure you are using a better model, especially for coding tasks, to get the best and most accurate completions. Otherwise, you may experience poor performance or inaccurate completions.
179
+
166
180
  #### Configuration
167
181
 
168
182
  The `model` option accepts an object with two functions:
169
183
 
170
- 1. `config`: A function that receives the API key and prompt data, and returns the configuration for the custom model API request.
184
+ | Function | Description | Type |
185
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
186
+ | `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 }` |
187
+ | `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 }` |
188
+
189
+ The `config` function must return an object with the following properties:
171
190
 
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.
191
+ | Property | Type | Description |
192
+ | ---------- | --------------------- | -------------------------------------------- |
193
+ | `endpoint` | `string` | The URL of the custom model API endpoint. |
194
+ | `body` | `object \| undefined` | The body of the custom model API request. |
195
+ | `headers` | `object \| undefined` | The headers of the custom model API request. |
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
+ The `transformResponse` function must return an object with the following structure:
198
+
199
+ | Property | Type | Description |
200
+ | ------------ | --------------------- | ----------------------------------------------------------- |
201
+ | `completion` | `string \| null` | The generated completion text to be inserted in the editor. |
202
+ | `error` | `string \| undefined` | An error message if something went wrong. |
179
203
 
180
204
  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
205
 
@@ -255,10 +279,10 @@ For additional `completionMetadata` needs, please [open an issue](https://github
255
279
 
256
280
  The `customPrompt` function should return an object with two properties:
257
281
 
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 |
282
+ | Property | Type | Description |
283
+ | -------- | --------------------- | ----------------------------------------------------- |
284
+ | system | `string \| undefined` | A string representing the system prompt for the model |
285
+ | user | `string \| undefined` | A string representing the user prompt for the model |
262
286
 
263
287
  #### Example
264
288
 
@@ -287,6 +311,26 @@ By using a custom prompt, you can guide the model to generate completions that b
287
311
 
288
312
  ## Configuration Options
289
313
 
314
+ ### Get Completions in Real-Time
315
+
316
+ The `trigger` option determines when Copilot provides code completions. You can choose between receiving suggestions in real-time as you type or after a brief pause.
317
+
318
+ ```javascript
319
+ registerCopilot(monaco, editor, {
320
+ // ...other options
321
+ trigger: 'onTyping',
322
+ });
323
+ ```
324
+
325
+ | Trigger | Description | Notes |
326
+ | -------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
327
+ | `'onIdle'` (default) | Copilot provides completions after a brief pause in typing. | This approach is less resource-intensive, as it only initiates a request when the editor is idle. However, compared to `onTyping` it may result in a bit reduced experience with completions. |
328
+ | `'onTyping'` | Copilot provides completions in real-time as you type. | This approach is best suited for models with low response latency, such as Groq. Please note that this trigger mode initiates additional background requests to deliver real-time suggestions. |
329
+
330
+ [OnTyping Demo](https://github.com/user-attachments/assets/22c2ce44-334c-4963-b853-01b890b8e39f)
331
+
332
+ If you prefer real-time completions, you can set the `trigger` option to `'onTyping'`. This is ideal for those who need immediate or fast completion experiences.
333
+
290
334
  ### External Context
291
335
 
292
336
  Enhance the accuracy and relevance of Copilot's completions by providing additional code context from your workspace.
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[];
@@ -100,6 +100,18 @@ interface RegisterCopilotOptions {
100
100
  * The API endpoint where you started the completion service.
101
101
  */
102
102
  endpoint: Endpoint;
103
+ /**
104
+ * Specifies when Copilot should provide code completions.
105
+ *
106
+ * Options:
107
+ * - `'onIdle'`: Copilot provides completions after a brief pause in typing.
108
+ * - `'onTyping'`: Copilot offers completions in real-time as you type.
109
+ * - *Note:* Best suited for models with low response latency (e.g., Groq).
110
+ * - *Consideration:* May initiate additional background requests to deliver real-time suggestions.
111
+ *
112
+ * @default 'onIdle'
113
+ */
114
+ trigger?: 'onTyping' | 'onIdle';
103
115
  /**
104
116
  * The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
105
117
  * For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
@@ -264,4 +276,4 @@ declare class Copilot {
264
276
  */
265
277
  declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
266
278
 
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 };
279
+ 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[];
@@ -100,6 +100,18 @@ interface RegisterCopilotOptions {
100
100
  * The API endpoint where you started the completion service.
101
101
  */
102
102
  endpoint: Endpoint;
103
+ /**
104
+ * Specifies when Copilot should provide code completions.
105
+ *
106
+ * Options:
107
+ * - `'onIdle'`: Copilot provides completions after a brief pause in typing.
108
+ * - `'onTyping'`: Copilot offers completions in real-time as you type.
109
+ * - *Note:* Best suited for models with low response latency (e.g., Groq).
110
+ * - *Consideration:* May initiate additional background requests to deliver real-time suggestions.
111
+ *
112
+ * @default 'onIdle'
113
+ */
114
+ trigger?: 'onTyping' | 'onIdle';
103
115
  /**
104
116
  * The name of the file you are editing. This is used to provide more relevant completions based on the file's purpose.
105
117
  * For example, if you are editing a file named `utils.js`, the completions will be more relevant to utility functions.
@@ -264,4 +276,4 @@ declare class Copilot {
264
276
  */
265
277
  declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
266
278
 
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 };
279
+ 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,38 +1,38 @@
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 B=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Te=Object.prototype.hasOwnProperty;var Pe=(o,e)=>{for(var t in e)B(o,t,{get:e[t],enumerable:!0})},ye=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ee(e))!Te.call(o,n)&&n!==t&&B(o,n,{get:()=>e[n],enumerable:!(r=fe(e,n))||r.enumerable});return o};var xe=o=>ye(B({},"__esModule",{value:!0}),o);var qe={};Pe(qe,{Copilot:()=>L,registerCopilot:()=>ge});module.exports=xe(qe);var k=["groq","openai","anthropic"],X={"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"},H={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"]},z="llama-3-70b",J="groq",Z={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},R=.3;var Q=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var O=class o{constructor(){}static getInstance(){return o.instance||(o.instance=new o),o.instance}error(e,t){console.error(this.styleMessage(t.message,e,"error")),t.stack&&console.error(this.styleStackTrace(t.stack))}warn(e,t){console.warn(this.styleMessage(t,e,"warning"))}styleMessage(e,t,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",a=100,s="\u2500".repeat(a-2),p=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((f,M)=>{let he=f.split(" "),S=[],C="";return he.forEach(K=>{(C+K).length>M&&(S.push(C.trim()),C=""),C+=K+" "}),C.trim()&&S.push(C.trim()),S})(e,a-4),h=[p,...m.map(f=>`\u2502 ${f.padEnd(a-4)} \u2502`),c].join(`
2
2
  `);return`
3
- \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${o}]\x1B[0m \x1B[2m${i}\x1B[0m
3
+ \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${t}]\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 E=class E{constructor(){this.logger=O.getInstance()}static getInstance(){return E.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logger.error(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};E.instance=new E;var $=E;var d=(o,e)=>$.getInstance().handleError(o,e);var q=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((a,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{a(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},T=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var I=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],ee=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),g=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),oe=o=>{let e=o.split(`
8
+ `);return e[e.length-1].length+1};var F=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),U=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var te=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},Me=(o,e)=>te(o,"GET",e),Re=(o,e,t)=>te(o,"POST",{...t,body:e}),b={GET:Me,POST:Re};var re=(o,e)=>{let t=I(o,e);return!!t&&!Q.has(t)},ne=(o,e)=>{let t=ee(o,e).trim(),r=g(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var v="<<CURSOR>>",ie=o=>o==="javascript"?"latest JavaScript":o,se=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Oe=o=>{let e=ie(o.language),t=se(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},Ie=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${T(o)}`:"",r=ie(e);return`The code is written${r?` in ${r}`:""}${t}.`},be=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:a,externalContext:s}=o,p=se(n),c=e?`the file named "${e}"`:"a larger project",l=`You are tasked with ${p} for a code snippet. The code is part of ${c}.
9
9
 
10
- `;return p+=be(r,o),p+=`
10
+ `;return l+=Ie(r,t),l+=`
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 '${v}'.
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.
19
- `),p+=` - Optimize for readability and performance where possible.
17
+ `,n==="fill-in-the-middle"?l+=` - If filling in the middle, replace '${v}' entirely with your completion.
18
+ `:n==="completion"&&(l+=` - If completing the code, start from '${v}' and provide a logical continuation.
19
+ `),l+=` - 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 (\`\`\`).
22
22
 
23
23
  Here's the code snippet for completion:
24
24
 
25
25
  <code>
26
- ${i}${b}${l}
27
- </code>`,s&&s.length>0&&(p+=`
26
+ ${i}${v}${a}
27
+ </code>`,s&&s.length>0&&(l+=`
28
28
 
29
29
  Additional context from related files:
30
30
 
31
- `,p+=s.map(c=>`// Path: ${c.path}
32
- ${c.content}
31
+ `,l+=s.map(m=>`// Path: ${m.path}
32
+ ${m.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
+ `)),l.endsWith(".")?l:`${l}.`};function V(o){return{system:Oe(o),user:be(o)}}var ae={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var ve={createRequestBody:(o,e)=>{let r=o==="o1-preview"||o==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:Y(o),temperature:R,messages:r}},createHeaders:o=>({"Content-Type":"application/json",Authorization:`Bearer ${o}`}),parseCompletion:o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the OpenAI response"}},Le={createRequestBody:(o,e)=>({model:Y(o),temperature:R,messages:[{role:"system",content:e.system},{role:"user",content:e.user}]}),createHeaders:o=>({"Content-Type":"application/json",Authorization:`Bearer ${o}`}),parseCompletion:o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the Groq response"}},Ne={createRequestBody:(o,e)=>({model:Y(o),temperature:R,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:Ae(o)}),createHeaders:o=>({"Content-Type":"application/json","x-api-key":o,"anthropic-version":"2023-06-01"}),parseCompletion:o=>o.content?typeof o.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:o.content}:{completion:null,error:"No completion found in the Anthropic response"}},j={openai:ve,groq:Le,anthropic:Ne},le=(o,e,t)=>j[e].createRequestBody(o,t),pe=(o,e)=>j[e].createHeaders(o),me=(o,e)=>j[e].parseCompletion(o),Y=o=>X[o],ce=o=>Z[o],Ae=o=>ae[o]||4096;var L=class{constructor(e,t={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=t.provider??J,this.model=t.model??z,this.validateInputs()}validateInputs(){if(!k.includes(this.provider))throw new Error(`The provider "${this.provider}" is not supported. Please choose a supported provider: ${T(k)}. If you're using a custom model, you don't need to specify a provider.`);if(typeof this.model=="string"&&!H[this.provider].includes(this.model)){let e=T(H[this.provider]);throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${e}`)}}generatePrompt(e,t){let r=V(e);return t?{...r,...t(e)}:r}prepareRequest(e,t){let r=ce(this.provider),n,i=pe(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=le(this.model,this.provider,e);let a={...i,...t};return{endpoint:r,requestBody:n,headers:a}}async complete(e){let{body:t,options:r}=e,{completionMetadata:n}=t,{headers:i={},customPrompt:a}=r??{},s=this.generatePrompt(n,a),{endpoint:p,requestBody:c,headers:l}=this.prepareRequest(s,i);try{let m=await b.POST(p,c,{headers:l});return typeof this.model=="object"&&"transformResponse"in this.model?this.model.transformResponse(m):me(m,this.provider)}catch(m){return{error:d(m,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}};var N=class o{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new o(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],a=i.split(`
35
35
  `).slice(1,-1).join(`
36
- `);r=r.replace(i,l)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
36
+ `);r=r.replace(i,a)}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 A=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!re(this.cursorPosition,this.model)&&!ne(this.cursorPosition,this.model)}};var _=class _{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(_.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return g(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};_.MAX_CACHE_SIZE=10;var w=_;var we="application/json",W=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:a})=>{try{let{completion:s}=await b.POST(e,{completionMetadata:_e({filename:o,position:a,model:i,language:t,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:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let a=De(e,t),s=F(e,t),p=U(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:p,cursorPosition:e,editorState:{completionMode:a}}},De=(o,e)=>{let t=F(o,e),r=U(o,e);return t&&r?"fill-in-the-middle":"completion"};var de=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=oe(o),a=I(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(a)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function ue(o){return N.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var Se=300,Be=600,ke={onTyping:q(W,Se),onIdle:q(W,Be)},D=new w,He=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:a})=>{let{trigger:s="onIdle",...p}=a;if(!new A(t,e).shouldProvideCompletions())return u([]);let c=D.getCompletionCache(t,e).map(l=>({insertText:l.completion,range:l.range}));if(c.length>0)return i(),u(c);if(r.isCancellationRequested||n)return u([]);try{let l=s==="onTyping"?"onTyping":"onIdle",m=ke[l];r.onCancellationRequested(()=>{m.cancel()});let h=await m({...p,text:e.getValue(),model:e,position:t});if(h){let x=ue(h),f=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),M=de(x,f,t,e);return D.addCompletionCache({completion:x,range:M,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:x,range:M}])}}catch(l){if($e(l))return u([]);d(l,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},$e=o=>typeof o=="string"&&(o==="Cancelled"||o==="AbortError")||o instanceof Error&&(o.message==="Cancelled"||o.name==="AbortError"),Ce=He;var P=new WeakMap,y=null,ge=(o,e,t)=>{y&&y.deregister();let r=[];P.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,p,c,l)=>{let m=P.get(e);if(m)return Ce({monaco:o,model:s,position:p,token:l,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let p=P.get(e);if(!p)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;p.isCompletionVisible&&c?(p.isCompletionAccepted=!0,p.isCompletionVisible=!1):p.isCompletionAccepted=!1});r.push(i);let a={deregister:()=>{r.forEach(s=>s.dispose()),D.clearCompletionCache(),P.delete(e),y=null}};return y=a,a}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),P.delete(e),y=null}}}};0&&(module.exports={Copilot,registerCopilot});
package/build/index.mjs CHANGED
@@ -1,38 +1,38 @@
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 S=["groq","openai","anthropic"],K={"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"]},X="llama-3-70b",z="groq",J={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},R=.3;var Z=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var O=class o{constructor(){}static getInstance(){return o.instance||(o.instance=new o),o.instance}error(e,t){console.error(this.styleMessage(t.message,e,"error")),t.stack&&console.error(this.styleStackTrace(t.stack))}warn(e,t){console.warn(this.styleMessage(t,e,"warning"))}styleMessage(e,t,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",a=100,s="\u2500".repeat(a-2),p=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((f,M)=>{let Ce=f.split(" "),D=[],C="";return Ce.forEach(W=>{(C+W).length>M&&(D.push(C.trim()),C=""),C+=W+" "}),C.trim()&&D.push(C.trim()),D})(e,a-4),h=[p,...m.map(f=>`\u2502 ${f.padEnd(a-4)} \u2502`),c].join(`
2
2
  `);return`
3
- \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${o}]\x1B[0m \x1B[2m${i}\x1B[0m
3
+ \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${t}]\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 E=class E{constructor(){this.logger=O.getInstance()}static getInstance(){return E.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logger.error(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};E.instance=new E;var k=E;var d=(o,e)=>k.getInstance().handleError(o,e);var H=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((a,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{a(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},T=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var I=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],Q=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),g=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),ee=o=>{let e=o.split(`
8
+ `);return e[e.length-1].length+1};var $=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),q=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var oe=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},ge=(o,e)=>oe(o,"GET",e),he=(o,e,t)=>oe(o,"POST",{...t,body:e}),b={GET:ge,POST:he};var te=(o,e)=>{let t=I(o,e);return!!t&&!Z.has(t)},re=(o,e)=>{let t=Q(o,e).trim(),r=g(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var v="<<CURSOR>>",ne=o=>o==="javascript"?"latest JavaScript":o,ie=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},fe=o=>{let e=ne(o.language),t=ie(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},Ee=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${T(o)}`:"",r=ne(e);return`The code is written${r?` in ${r}`:""}${t}.`},Te=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:a,externalContext:s}=o,p=ie(n),c=e?`the file named "${e}"`:"a larger project",l=`You are tasked with ${p} for a code snippet. The code is part of ${c}.
9
9
 
10
- `;return p+=fe(r,o),p+=`
10
+ `;return l+=Ee(r,t),l+=`
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 '${v}'.
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.
19
- `),p+=` - Optimize for readability and performance where possible.
17
+ `,n==="fill-in-the-middle"?l+=` - If filling in the middle, replace '${v}' entirely with your completion.
18
+ `:n==="completion"&&(l+=` - If completing the code, start from '${v}' and provide a logical continuation.
19
+ `),l+=` - 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 (\`\`\`).
22
22
 
23
23
  Here's the code snippet for completion:
24
24
 
25
25
  <code>
26
- ${i}${b}${l}
27
- </code>`,s&&s.length>0&&(p+=`
26
+ ${i}${v}${a}
27
+ </code>`,s&&s.length>0&&(l+=`
28
28
 
29
29
  Additional context from related files:
30
30
 
31
- `,p+=s.map(c=>`// Path: ${c.path}
32
- ${c.content}
31
+ `,l+=s.map(m=>`// Path: ${m.path}
32
+ ${m.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
+ `)),l.endsWith(".")?l:`${l}.`};function F(o){return{system:fe(o),user:Te(o)}}var se={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Pe={createRequestBody:(o,e)=>{let r=o==="o1-preview"||o==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:V(o),temperature:R,messages:r}},createHeaders:o=>({"Content-Type":"application/json",Authorization:`Bearer ${o}`}),parseCompletion:o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the OpenAI response"}},ye={createRequestBody:(o,e)=>({model:V(o),temperature:R,messages:[{role:"system",content:e.system},{role:"user",content:e.user}]}),createHeaders:o=>({"Content-Type":"application/json",Authorization:`Bearer ${o}`}),parseCompletion:o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the Groq response"}},xe={createRequestBody:(o,e)=>({model:V(o),temperature:R,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:Me(o)}),createHeaders:o=>({"Content-Type":"application/json","x-api-key":o,"anthropic-version":"2023-06-01"}),parseCompletion:o=>o.content?typeof o.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:o.content}:{completion:null,error:"No completion found in the Anthropic response"}},U={openai:Pe,groq:ye,anthropic:xe},ae=(o,e,t)=>U[e].createRequestBody(o,t),le=(o,e)=>U[e].createHeaders(o),pe=(o,e)=>U[e].parseCompletion(o),V=o=>K[o],me=o=>J[o],Me=o=>se[o]||4096;var j=class{constructor(e,t={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=t.provider??z,this.model=t.model??X,this.validateInputs()}validateInputs(){if(!S.includes(this.provider))throw new Error(`The provider "${this.provider}" is not supported. Please choose a supported provider: ${T(S)}. 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=T(B[this.provider]);throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${e}`)}}generatePrompt(e,t){let r=F(e);return t?{...r,...t(e)}:r}prepareRequest(e,t){let r=me(this.provider),n,i=le(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=ae(this.model,this.provider,e);let a={...i,...t};return{endpoint:r,requestBody:n,headers:a}}async complete(e){let{body:t,options:r}=e,{completionMetadata:n}=t,{headers:i={},customPrompt:a}=r??{},s=this.generatePrompt(n,a),{endpoint:p,requestBody:c,headers:l}=this.prepareRequest(s,i);try{let m=await b.POST(p,c,{headers:l});return typeof this.model=="object"&&"transformResponse"in this.model?this.model.transformResponse(m):pe(m,this.provider)}catch(m){return{error:d(m,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}};var L=class o{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new o(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],a=i.split(`
35
35
  `).slice(1,-1).join(`
36
- `);r=r.replace(i,l)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
36
+ `);r=r.replace(i,a)}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 N=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!te(this.cursorPosition,this.model)&&!re(this.cursorPosition,this.model)}};var w=class w{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(w.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return g(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};w.MAX_CACHE_SIZE=10;var A=w;var Re="application/json",G=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:a})=>{try{let{completion:s}=await b.POST(e,{completionMetadata:Oe({filename:o,position:a,model:i,language:t,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}},Oe=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let a=Ie(e,t),s=$(e,t),p=q(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:p,cursorPosition:e,editorState:{completionMode:a}}},Ie=(o,e)=>{let t=$(o,e),r=q(o,e);return t&&r?"fill-in-the-middle":"completion"};var ce=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=ee(o),a=I(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(a)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function de(o){return L.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var be=300,ve=600,Le={onTyping:H(G,be),onIdle:H(G,ve)},_=new A,Ne=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:a})=>{let{trigger:s="onIdle",...p}=a;if(!new N(t,e).shouldProvideCompletions())return u([]);let c=_.getCompletionCache(t,e).map(l=>({insertText:l.completion,range:l.range}));if(c.length>0)return i(),u(c);if(r.isCancellationRequested||n)return u([]);try{let l=s==="onTyping"?"onTyping":"onIdle",m=Le[l];r.onCancellationRequested(()=>{m.cancel()});let h=await m({...p,text:e.getValue(),model:e,position:t});if(h){let x=de(h),f=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),M=ce(x,f,t,e);return _.addCompletionCache({completion:x,range:M,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:x,range:M}])}}catch(l){if(Ae(l))return u([]);d(l,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},Ae=o=>typeof o=="string"&&(o==="Cancelled"||o==="AbortError")||o instanceof Error&&(o.message==="Cancelled"||o.name==="AbortError"),ue=Ne;var P=new WeakMap,y=null,we=(o,e,t)=>{y&&y.deregister();let r=[];P.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,p,c,l)=>{let m=P.get(e);if(m)return ue({monaco:o,model:s,position:p,token:l,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let p=P.get(e);if(!p)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;p.isCompletionVisible&&c?(p.isCompletionAccepted=!0,p.isCompletionVisible=!1):p.isCompletionAccepted=!1});r.push(i);let a={deregister:()=>{r.forEach(s=>s.dispose()),_.clearCompletionCache(),P.delete(e),y=null}};return y=a,a}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),P.delete(e),y=null}}}};export{j as Copilot,we 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.31",
4
4
  "description": "AI auto-completion plugin for Monaco Editor",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",