monacopilot 0.9.22 → 0.9.24

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
@@ -13,6 +13,7 @@
13
13
  - [Changing the Provider and Model](#changing-the-provider-and-model)
14
14
  - [Copilot Completion Request Options](#copilot-completion-request-options)
15
15
  - [Custom Headers](#custom-headers)
16
+ - [Custom Prompt](#custom-prompt)
16
17
  - [Configuration Options](#configuration-options)
17
18
  - [External Context](#external-context)
18
19
  - [Filename](#filename)
@@ -40,6 +41,8 @@ To install Monacopilot, run:
40
41
  npm install monacopilot
41
42
  ```
42
43
 
44
+ 🧩 For TypeScript users, You can import most of the types from `monacopilot` package.
45
+
43
46
  ## Usage
44
47
 
45
48
  #### Setting Up the API Key
@@ -145,6 +148,94 @@ copilot.complete({
145
148
  });
146
149
  ```
147
150
 
151
+ ### Custom Prompt
152
+
153
+ You can customize the prompt used for generating completions by providing a `customPrompt` function in the options parameter of the `copilot.complete` method. This allows you to tailor the AI's behavior to your specific needs.
154
+
155
+ #### Usage
156
+
157
+ ```javascript
158
+ copilot.complete({
159
+ body,
160
+ options: {
161
+ customPrompt: metadata => ({
162
+ system: 'Your custom system prompt here',
163
+ user: 'Your custom user prompt here',
164
+ }),
165
+ },
166
+ });
167
+ ```
168
+
169
+ The `system` and `user` prompts in the `customPrompt` function are optional. Omitting either uses the default prompt for that field. Example of customizing only the system prompt:
170
+
171
+ ```javascript
172
+ copilot.complete({
173
+ body,
174
+ options: {
175
+ customPrompt: metadata => ({
176
+ system:
177
+ 'You are an AI assistant specialized in writing React components, focusing on creating clean...',
178
+ }),
179
+ },
180
+ });
181
+ ```
182
+
183
+ #### Parameters
184
+
185
+ The `customPrompt` function receives a `completionMetadata` object with the following properties:
186
+
187
+ | Property | Type | Description |
188
+ | ---------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
189
+ | language | `string` | The programming language of the code |
190
+ | cursorPosition | `{lineNumber: number, column: number}` | The current cursor position in the editor |
191
+ | filename | `string \| undefined` | The name of the file being edited. Only available if you have provided the `filename` option in the `registerCopilot` function. |
192
+ | technologies | `string[] \| undefined` | An array of technologies used in the project. Only available if you have provided the `technologies` option in the `registerCopilot` function. |
193
+ | externalContext | `object \| undefined` | Additional context from related files. Only available if you have provided the `externalContext` option in the `registerCopilot` function. |
194
+ | textAfterCursor | `string` | The text that appears after the cursor |
195
+ | textBeforeCursor | `string` | The text that appears before the cursor |
196
+ | editorState | `object` | An object containing the `completionMode` property |
197
+
198
+ The `editorState.completionMode` can be one of the following:
199
+
200
+ | Mode | Description |
201
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
202
+ | fill-in-the-middle | Indicates that the cursor is positioned within the existing text. In this mode, the AI will generate content to be inserted at the cursor position. |
203
+ | completion | Indicates that the cursor is at the end of the existing text. In this mode, the AI will generate content to continue or complete the text from the cursor position. |
204
+
205
+ For additional `completionMetadata` needs, please [open an issue](https://github.com/arshad-yaseen/monacopilot/issues/new).
206
+
207
+ The `customPrompt` function should return an object with two properties:
208
+
209
+ | Property | Type | Description |
210
+ | -------- | ------ | ----------------------------------------------------- |
211
+ | system | string | A string representing the system prompt for the model |
212
+ | user | string | A string representing the user prompt for the model |
213
+
214
+ #### Example
215
+
216
+ Here's an example of a custom prompt that focuses on generating React component code:
217
+
218
+ ```javascript
219
+ const customPrompt = ({textBeforeCursor, textAfterCursor}) => ({
220
+ system:
221
+ 'You are an AI assistant specialized in writing React components. Focus on creating clean, reusable, and well-structured components.',
222
+ user: `Please complete the following React component:
223
+
224
+ ${textBeforeCursor}
225
+ // Cursor position
226
+ ${textAfterCursor}
227
+
228
+ Use modern React practices and hooks where appropriate. If you're adding new props, make sure to include proper TypeScript types. Please provide only the finished code without additional comments or explanations.`,
229
+ });
230
+
231
+ copilot.complete({
232
+ body,
233
+ options: {customPrompt},
234
+ });
235
+ ```
236
+
237
+ By using a custom prompt, you can guide the model to generate completions that better fit your coding style, project requirements, or specific technologies you're working with.
238
+
148
239
  ## Configuration Options
149
240
 
150
241
  ### External Context
package/build/index.d.mts CHANGED
@@ -2,6 +2,7 @@ import * as monaco from 'monaco-editor';
2
2
 
3
3
  type Monaco = typeof monaco;
4
4
  type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
5
+ type CursorPosition = monaco.IPosition;
5
6
 
6
7
  /**
7
8
  * Options for configuring the Copilot instance.
@@ -102,20 +103,63 @@ interface CompletionRequestOptions {
102
103
  * Additional headers to include in the provider's completion requests.
103
104
  */
104
105
  headers?: Record<string, string>;
106
+ /**
107
+ * Custom prompt generator function for the completion request.
108
+ * This function allows you to override the default system and user prompts
109
+ * used in the completion request, providing more control over the AI's context and behavior.
110
+ *
111
+ * @param completionMetadata - Metadata about the current completion context
112
+ * @returns An object containing custom 'system' and 'user' prompts
113
+ */
114
+ customPrompt?: CustomPrompt;
105
115
  }
116
+ type CustomPrompt = (completionMetadata: CompletionMetadata) => {
117
+ system?: string;
118
+ user?: string;
119
+ };
106
120
  interface CompletionResponse {
107
121
  completion: string | null;
108
122
  error?: string;
109
123
  }
110
124
  type CompletionMode = 'fill-in-the-middle' | 'completion';
111
125
  interface CompletionMetadata {
126
+ /**
127
+ * The programming language of the code.
128
+ */
112
129
  language: string | undefined;
130
+ /**
131
+ * The name of the file being edited.
132
+ */
113
133
  filename: Filename | undefined;
134
+ /**
135
+ * The technologies used in the completion.
136
+ */
114
137
  technologies: Technologies | undefined;
138
+ /**
139
+ * Additional context from related files.
140
+ */
115
141
  externalContext: ExternalContext | undefined;
142
+ /**
143
+ * The text that appears after the cursor.
144
+ */
116
145
  textAfterCursor: string;
146
+ /**
147
+ * The text that appears before the cursor.
148
+ */
117
149
  textBeforeCursor: string;
150
+ /**
151
+ * The current cursor position.
152
+ */
153
+ cursorPosition: CursorPosition | undefined;
154
+ /**
155
+ * The current state of the editor.
156
+ */
118
157
  editorState: {
158
+ /**
159
+ * The mode of the completion.
160
+ * - `fill-in-the-middle`: Indicates that the cursor is positioned within the existing text. In this mode, the AI will generate content to be inserted at the cursor position.
161
+ * - `completion`: Indicates that the cursor is at the end of the existing text. In this mode, the AI will generate content to continue or complete the text from the cursor position.
162
+ */
119
163
  completionMode: CompletionMode;
120
164
  };
121
165
  }
@@ -151,4 +195,4 @@ declare class Copilot {
151
195
  */
152
196
  declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
153
197
 
154
- export { type CompletionModel, type CompletionProvider, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
198
+ 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 };
package/build/index.d.ts CHANGED
@@ -2,6 +2,7 @@ import * as monaco from 'monaco-editor';
2
2
 
3
3
  type Monaco = typeof monaco;
4
4
  type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
5
+ type CursorPosition = monaco.IPosition;
5
6
 
6
7
  /**
7
8
  * Options for configuring the Copilot instance.
@@ -102,20 +103,63 @@ interface CompletionRequestOptions {
102
103
  * Additional headers to include in the provider's completion requests.
103
104
  */
104
105
  headers?: Record<string, string>;
106
+ /**
107
+ * Custom prompt generator function for the completion request.
108
+ * This function allows you to override the default system and user prompts
109
+ * used in the completion request, providing more control over the AI's context and behavior.
110
+ *
111
+ * @param completionMetadata - Metadata about the current completion context
112
+ * @returns An object containing custom 'system' and 'user' prompts
113
+ */
114
+ customPrompt?: CustomPrompt;
105
115
  }
116
+ type CustomPrompt = (completionMetadata: CompletionMetadata) => {
117
+ system?: string;
118
+ user?: string;
119
+ };
106
120
  interface CompletionResponse {
107
121
  completion: string | null;
108
122
  error?: string;
109
123
  }
110
124
  type CompletionMode = 'fill-in-the-middle' | 'completion';
111
125
  interface CompletionMetadata {
126
+ /**
127
+ * The programming language of the code.
128
+ */
112
129
  language: string | undefined;
130
+ /**
131
+ * The name of the file being edited.
132
+ */
113
133
  filename: Filename | undefined;
134
+ /**
135
+ * The technologies used in the completion.
136
+ */
114
137
  technologies: Technologies | undefined;
138
+ /**
139
+ * Additional context from related files.
140
+ */
115
141
  externalContext: ExternalContext | undefined;
142
+ /**
143
+ * The text that appears after the cursor.
144
+ */
116
145
  textAfterCursor: string;
146
+ /**
147
+ * The text that appears before the cursor.
148
+ */
117
149
  textBeforeCursor: string;
150
+ /**
151
+ * The current cursor position.
152
+ */
153
+ cursorPosition: CursorPosition | undefined;
154
+ /**
155
+ * The current state of the editor.
156
+ */
118
157
  editorState: {
158
+ /**
159
+ * The mode of the completion.
160
+ * - `fill-in-the-middle`: Indicates that the cursor is positioned within the existing text. In this mode, the AI will generate content to be inserted at the cursor position.
161
+ * - `completion`: Indicates that the cursor is at the end of the existing text. In this mode, the AI will generate content to continue or complete the text from the cursor position.
162
+ */
119
163
  completionMode: CompletionMode;
120
164
  };
121
165
  }
@@ -151,4 +195,4 @@ declare class Copilot {
151
195
  */
152
196
  declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
153
197
 
154
- export { type CompletionModel, type CompletionProvider, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
198
+ 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 };
package/build/index.js CHANGED
@@ -1,13 +1,13 @@
1
- "use strict";var S=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var Ee=(o,e)=>{for(var t in e)S(o,t,{get:e[t],enumerable:!0})},Pe=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of he(e))!fe.call(o,n)&&n!==t&&S(o,n,{get:()=>e[n],enumerable:!(r=ge(e,n))||r.enumerable});return o};var Te=o=>Pe(S({},"__esModule",{value:!0}),o);var Se={};Ee(Se,{Copilot:()=>b,registerCopilot:()=>de});module.exports=Te(Se);var 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"},D={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},k="llama-3-70b",T="groq",V={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},j=.3;var W=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var x=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.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((w,ue)=>{let Ce=w.split(" "),_=[],C="";return Ce.forEach(F=>{(C+F).length>ue&&(_.push(C.trim()),C=""),C+=F+" "}),C.trim()&&_.push(C.trim()),_})(e,l-4),P=[a,...m.map(w=>`\u2502 ${w.padEnd(l-4)} \u2502`),c].join(`
1
+ "use strict";var S=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var he=Object.prototype.hasOwnProperty;var fe=(o,e)=>{for(var t in e)S(o,t,{get:e[t],enumerable:!0})},Ee=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ge(e))!he.call(o,n)&&n!==t&&S(o,n,{get:()=>e[n],enumerable:!(r=Ce(e,n))||r.enumerable});return o};var Pe=o=>Ee(S({},"__esModule",{value:!0}),o);var De={};fe(De,{Copilot:()=>O,registerCopilot:()=>me});module.exports=Pe(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"},D={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},k="llama-3-70b",T="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"},W=.3;var G=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var x=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.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((w,de)=>{let ue=w.split(" "),_=[],C="";return ue.forEach(U=>{(C+U).length>de&&(_.push(C.trim()),C=""),C+=U+" "}),C.trim()&&_.push(C.trim()),_})(e,l-4),P=[a,...m.map(w=>`\u2502 ${w.padEnd(l-4)} \u2502`),c].join(`
2
2
  `);return`
3
3
  \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${t}]\x1B[0m \x1B[2m${i}\x1B[0m
4
4
  ${P}
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 h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.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"}}};h.instance=new h;var B=h;var d=(o,e)=>B.getInstance().handleError(o,e);var G={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Y=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},M=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var y=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],K=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),g=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),X=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}),H=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var z=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()},xe=(o,e)=>z(o,"GET",e),Me=(o,e,t)=>z(o,"POST",{...t,body:e}),R={GET:xe,POST:Me};var J=(o,e)=>{let t=y(o,e);return!!t&&!W.has(t)},Z=(o,e)=>{let t=K(o,e).trim(),r=g(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var I="<<CURSOR>>",Q=o=>o==="javascript"?"latest JavaScript":o,ee=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=Q(o.language),t=ee(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.`},ye=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${M(o)}`:"",r=Q(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:l,externalContext:s}=o,a=ee(n),c=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
7
+ `)}getTimestamp(){return new Date().toISOString()}};var h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.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"}}};h.instance=new h;var B=h;var d=(o,e)=>B.getInstance().handleError(o,e);var Y={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var K=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},y=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var M=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],X=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),g=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),z=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}),H=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var J=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()},Te=(o,e)=>J(o,"GET",e),xe=(o,e,t)=>J(o,"POST",{...t,body:e}),R={GET:Te,POST:xe};var Z=(o,e)=>{let t=M(o,e);return!!t&&!G.has(t)},Q=(o,e)=>{let t=X(o,e).trim(),r=g(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var I="<<CURSOR>>",ee=o=>o==="javascript"?"latest JavaScript":o,oe=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},ye=o=>{let e=ee(o.language),t=oe(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.`},Me=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${y(o)}`:"",r=ee(e);return`The code is written${r?` in ${r}`:""}${t}.`},Re=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=o,a=oe(n),c=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
9
9
 
10
- `;return p+=ye(r,t),p+=`
10
+ `;return p+=Me(r,t),p+=`
11
11
 
12
12
  Here are the details about how the completion should be generated:
13
13
  - The cursor position is marked with '${I}'.
@@ -31,8 +31,8 @@ Additional context from related files:
31
31
  `,p+=s.map(m=>`// Path: ${m.path}
32
32
  ${m.content}
33
33
  `).join(`
34
- `)),p.endsWith(".")?p:`${p}.`};var re=(o,e,t)=>{let r=oe(o),n=te(o),l={model:Oe(e),temperature:j},s={openai:{messages:[{role:"system",content:r},{role:"user",content:n}]},groq:{messages:[{role:"system",content:r},{role:"user",content:n}]},anthropic:{system:r,messages:[{role:"user",content:n}],max_tokens:ve(e)}};return{...l,...s[t]}},ne=(o,e)=>{let t={"Content-Type":"application/json"},r={openai:{Authorization:`Bearer ${o}`},groq:{Authorization:`Bearer ${o}`},anthropic:{"x-api-key":o,"anthropic-version":"2023-06-01"}};return{...t,...r[e]}},ie=(o,e)=>{let r={openai:Re,groq:Ie,anthropic:be}[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r(o)},Re=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the openai response"},Ie=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the groq response"},be=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"},Oe=o=>U[o],se=o=>V[o],ve=o=>G[o]||4096;var b=class{constructor(e,t={}){this.validateInputs(e,t),this.apiKey=e,this.provider=t.provider??T,this.model=t.model??k}async complete({body:e,options:t}){let{completionMetadata:r}=e,{headers:n={}}=t??{};try{let i=re(r,this.model,this.provider),l=se(this.provider),s=ne(this.apiKey,this.provider),a={...n,...s},c=await R.POST(l,i,{headers:a});return ie(c,this.provider)}catch(i){return{error:d(i,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}validateInputs(e,t){if(!e)throw new Error(`Please provide ${this.provider??T} API key.`);let{provider:r,model:n}=t;if(r&&!n||!r&&n)throw new Error("Both provider and model must be specified together");let i=r??T,l=n??k;if(!D[i].includes(l)){let s=M(D[i]);throw new Error(`Model ${l} is not supported by ${i} provider. Supported models: ${s}`)}}};var O=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],l=i.split(`
34
+ `)),p.endsWith(".")?p:`${p}.`};function q(o){return{system:ye(o),user:Re(o)}}var te=(o,e,t,r)=>{let n=q(o),i=r?r(o):{},l=i.system??n.system,s=i.user??n.user,a={model:ve(e),temperature:W},c=[{role:"system",content:l},{role:"user",content:s}],p={openai:{messages:c},groq:{messages:c},anthropic:{system:l,messages:[{role:"user",content:s}],max_tokens:Le(e)}};return{...a,...p[t]}},re=(o,e)=>{let t={"Content-Type":"application/json"},r={openai:{Authorization:`Bearer ${o}`},groq:{Authorization:`Bearer ${o}`},anthropic:{"x-api-key":o,"anthropic-version":"2023-06-01"}};return{...t,...r[e]}},ne=(o,e)=>{let r={openai:Ie,groq:Oe,anthropic:be}[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r(o)},Ie=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the openai response"},Oe=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the groq response"},be=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"},ve=o=>V[o],ie=o=>j[o],Le=o=>Y[o]||4096;var O=class{constructor(e,t={}){this.validateInputs(e,t),this.apiKey=e,this.provider=t.provider??T,this.model=t.model??k}async complete({body:e,options:t}){let{completionMetadata:r}=e,{headers:n={},customPrompt:i}=t??{};try{let l=te(r,this.model,this.provider,i),s=ie(this.provider),a=re(this.apiKey,this.provider),c={...n,...a},p=await R.POST(s,l,{headers:c});return ne(p,this.provider)}catch(l){return{error:d(l,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}validateInputs(e,t){if(!e)throw new Error(`Please provide ${this.provider??T} API key.`);let{provider:r,model:n}=t;if(r&&!n||!r&&n)throw new Error("Both provider and model must be specified together");let i=r??T,l=n??k;if(!D[i].includes(l)){let s=y(D[i]);throw new Error(`Model ${l} is not supported by ${i} provider. Supported models: ${s}`)}}};var b=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],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,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!J(this.cursorPosition,this.model)&&!Z(this.cursorPosition,this.model)}};var A=class A{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(A.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}};A.MAX_CACHE_SIZE=10;var L=A;var Le="application/json",le=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{body:{completionMetadata:Ae({filename:o,position:l,model:i,language:t,technologies:r,externalContext:n})}},{headers:{"Content-Type":Le},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Ae=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let l=Ne(e,t),s=$(e,t),a=H(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,editorState:{completionMode:l}}},Ne=(o,e)=>{let t=$(o,e),r=H(o,e);return t&&r?"fill-in-the-middle":"completion"};var ae=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=X(o),l=y(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function pe(o){return O.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var we=300,ce=Y(le,we),N=new L,_e=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new v(t,e).shouldProvideCompletions())return u([]);let s=N.getCompletionCache(t,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:t});r.onCancellationRequested(()=>{ce.cancel()});let c=await a;if(c){let p=pe(c),m=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),P=ae(p,m,t,e);return N.addCompletionCache({completion:p,range:P,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:p,range:P}])}}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=_e;var f=new WeakMap,E=null,de=(o,e,t)=>{E&&E.deregister();let r=[];f.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,a,c,p)=>{let m=f.get(e);if(m)return me({monaco:o,model:s,position:a,token:p,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=f.get(e);if(!a)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&c?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),N.clearCompletionCache(),f.delete(e),E=null}};return E=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),f.delete(e),E=null}}}};0&&(module.exports={Copilot,registerCopilot});
38
+ `),this}build(){return this.formattedCompletion}};var v=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!Z(this.cursorPosition,this.model)&&!Q(this.cursorPosition,this.model)}};var A=class A{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(A.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}};A.MAX_CACHE_SIZE=10;var L=A;var Ae="application/json",se=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:Ne({filename:o,position:l,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":Ae},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Ne=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let l=we(e,t),s=$(e,t),a=H(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,cursorPosition:e,editorState:{completionMode:l}}},we=(o,e)=>{let t=$(o,e),r=H(o,e);return t&&r?"fill-in-the-middle":"completion"};var le=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=z(o),l=M(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function ae(o){return b.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var _e=300,pe=K(se,_e),N=new L,Se=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new v(t,e).shouldProvideCompletions())return u([]);let s=N.getCompletionCache(t,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=pe({...l,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{pe.cancel()});let c=await a;if(c){let p=ae(c),m=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),P=le(p,m,t,e);return N.addCompletionCache({completion:p,range:P,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:p,range:P}])}}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([])},ce=Se;var f=new WeakMap,E=null,me=(o,e,t)=>{E&&E.deregister();let r=[];f.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,a,c,p)=>{let m=f.get(e);if(m)return ce({monaco:o,model:s,position:a,token:p,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=f.get(e);if(!a)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&c?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),N.clearCompletionCache(),f.delete(e),E=null}};return E=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),f.delete(e),E=null}}}};0&&(module.exports={Copilot,registerCopilot});
package/build/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
- var F={"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"},_={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},S="llama-3-70b",T="groq",U={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},V=.3;var j=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var x=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.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((N,me)=>{let de=N.split(" "),w=[],C="";return de.forEach(q=>{(C+q).length>me&&(w.push(C.trim()),C=""),C+=q+" "}),C.trim()&&w.push(C.trim()),w})(e,l-4),P=[a,...m.map(N=>`\u2502 ${N.padEnd(l-4)} \u2502`),c].join(`
1
+ var 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"},_={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},S="llama-3-70b",T="groq",V={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},j=.3;var W=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var x=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.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((N,ce)=>{let me=N.split(" "),w=[],C="";return me.forEach(F=>{(C+F).length>ce&&(w.push(C.trim()),C=""),C+=F+" "}),C.trim()&&w.push(C.trim()),w})(e,l-4),P=[a,...m.map(N=>`\u2502 ${N.padEnd(l-4)} \u2502`),c].join(`
2
2
  `);return`
3
3
  \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${t}]\x1B[0m \x1B[2m${i}\x1B[0m
4
4
  ${P}
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 h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.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"}}};h.instance=new h;var D=h;var d=(o,e)=>D.getInstance().handleError(o,e);var W={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var G=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},M=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var y=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],Y=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),g=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),K=o=>{let e=o.split(`
8
- `);return e[e.length-1].length+1};var k=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),B=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var X=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()},ue=(o,e)=>X(o,"GET",e),Ce=(o,e,t)=>X(o,"POST",{...t,body:e}),R={GET:ue,POST:Ce};var z=(o,e)=>{let t=y(o,e);return!!t&&!j.has(t)},J=(o,e)=>{let t=Y(o,e).trim(),r=g(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var I="<<CURSOR>>",Z=o=>o==="javascript"?"latest JavaScript":o,Q=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},ee=o=>{let e=Z(o.language),t=Q(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.`},ge=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${M(o)}`:"",r=Z(e);return`The code is written${r?` in ${r}`:""}${t}.`},oe=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=o,a=Q(n),c=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
7
+ `)}getTimestamp(){return new Date().toISOString()}};var h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.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"}}};h.instance=new h;var D=h;var d=(o,e)=>D.getInstance().handleError(o,e);var G={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Y=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},y=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var M=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],K=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),g=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),X=o=>{let e=o.split(`
8
+ `);return e[e.length-1].length+1};var k=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),B=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var z=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()},de=(o,e)=>z(o,"GET",e),ue=(o,e,t)=>z(o,"POST",{...t,body:e}),R={GET:de,POST:ue};var J=(o,e)=>{let t=M(o,e);return!!t&&!W.has(t)},Z=(o,e)=>{let t=K(o,e).trim(),r=g(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var I="<<CURSOR>>",Q=o=>o==="javascript"?"latest JavaScript":o,ee=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Ce=o=>{let e=Q(o.language),t=ee(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.`},ge=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${y(o)}`:"",r=Q(e);return`The code is written${r?` in ${r}`:""}${t}.`},he=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=o,a=ee(n),c=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
9
9
 
10
10
  `;return p+=ge(r,t),p+=`
11
11
 
@@ -31,8 +31,8 @@ Additional context from related files:
31
31
  `,p+=s.map(m=>`// Path: ${m.path}
32
32
  ${m.content}
33
33
  `).join(`
34
- `)),p.endsWith(".")?p:`${p}.`};var te=(o,e,t)=>{let r=ee(o),n=oe(o),l={model:Pe(e),temperature:V},s={openai:{messages:[{role:"system",content:r},{role:"user",content:n}]},groq:{messages:[{role:"system",content:r},{role:"user",content:n}]},anthropic:{system:r,messages:[{role:"user",content:n}],max_tokens:Te(e)}};return{...l,...s[t]}},re=(o,e)=>{let t={"Content-Type":"application/json"},r={openai:{Authorization:`Bearer ${o}`},groq:{Authorization:`Bearer ${o}`},anthropic:{"x-api-key":o,"anthropic-version":"2023-06-01"}};return{...t,...r[e]}},ne=(o,e)=>{let r={openai:he,groq:fe,anthropic:Ee}[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r(o)},he=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the openai response"},fe=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the groq response"},Ee=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"},Pe=o=>F[o],ie=o=>U[o],Te=o=>W[o]||4096;var $=class{constructor(e,t={}){this.validateInputs(e,t),this.apiKey=e,this.provider=t.provider??T,this.model=t.model??S}async complete({body:e,options:t}){let{completionMetadata:r}=e,{headers:n={}}=t??{};try{let i=te(r,this.model,this.provider),l=ie(this.provider),s=re(this.apiKey,this.provider),a={...n,...s},c=await R.POST(l,i,{headers:a});return ne(c,this.provider)}catch(i){return{error:d(i,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}validateInputs(e,t){if(!e)throw new Error(`Please provide ${this.provider??T} API key.`);let{provider:r,model:n}=t;if(r&&!n||!r&&n)throw new Error("Both provider and model must be specified together");let i=r??T,l=n??S;if(!_[i].includes(l)){let s=M(_[i]);throw new Error(`Model ${l} is not supported by ${i} provider. Supported models: ${s}`)}}};var b=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],l=i.split(`
34
+ `)),p.endsWith(".")?p:`${p}.`};function $(o){return{system:Ce(o),user:he(o)}}var oe=(o,e,t,r)=>{let n=$(o),i=r?r(o):{},l=i.system??n.system,s=i.user??n.user,a={model:Te(e),temperature:j},c=[{role:"system",content:l},{role:"user",content:s}],p={openai:{messages:c},groq:{messages:c},anthropic:{system:l,messages:[{role:"user",content:s}],max_tokens:xe(e)}};return{...a,...p[t]}},te=(o,e)=>{let t={"Content-Type":"application/json"},r={openai:{Authorization:`Bearer ${o}`},groq:{Authorization:`Bearer ${o}`},anthropic:{"x-api-key":o,"anthropic-version":"2023-06-01"}};return{...t,...r[e]}},re=(o,e)=>{let r={openai:fe,groq:Ee,anthropic:Pe}[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r(o)},fe=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the openai response"},Ee=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the groq response"},Pe=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"},Te=o=>U[o],ne=o=>V[o],xe=o=>G[o]||4096;var H=class{constructor(e,t={}){this.validateInputs(e,t),this.apiKey=e,this.provider=t.provider??T,this.model=t.model??S}async complete({body:e,options:t}){let{completionMetadata:r}=e,{headers:n={},customPrompt:i}=t??{};try{let l=oe(r,this.model,this.provider,i),s=ne(this.provider),a=te(this.apiKey,this.provider),c={...n,...a},p=await R.POST(s,l,{headers:c});return re(p,this.provider)}catch(l){return{error:d(l,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}validateInputs(e,t){if(!e)throw new Error(`Please provide ${this.provider??T} API key.`);let{provider:r,model:n}=t;if(r&&!n||!r&&n)throw new Error("Both provider and model must be specified together");let i=r??T,l=n??S;if(!_[i].includes(l)){let s=y(_[i]);throw new Error(`Model ${l} is not supported by ${i} provider. Supported models: ${s}`)}}};var O=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],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,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!z(this.cursorPosition,this.model)&&!J(this.cursorPosition,this.model)}};var L=class L{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(L.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}};L.MAX_CACHE_SIZE=10;var v=L;var xe="application/json",se=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{body:{completionMetadata:Me({filename:o,position:l,model:i,language:t,technologies:r,externalContext:n})}},{headers:{"Content-Type":xe},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Me=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let l=ye(e,t),s=k(e,t),a=B(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,editorState:{completionMode:l}}},ye=(o,e)=>{let t=k(o,e),r=B(o,e);return t&&r?"fill-in-the-middle":"completion"};var le=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=K(o),l=y(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function ae(o){return b.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var Re=300,pe=G(se,Re),A=new v,Ie=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new O(t,e).shouldProvideCompletions())return u([]);let s=A.getCompletionCache(t,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=pe({...l,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{pe.cancel()});let c=await a;if(c){let p=ae(c),m=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),P=le(p,m,t,e);return A.addCompletionCache({completion:p,range:P,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:p,range:P}])}}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([])},ce=Ie;var f=new WeakMap,E=null,be=(o,e,t)=>{E&&E.deregister();let r=[];f.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,a,c,p)=>{let m=f.get(e);if(m)return ce({monaco:o,model:s,position:a,token:p,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=f.get(e);if(!a)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&c?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),A.clearCompletionCache(),f.delete(e),E=null}};return E=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),f.delete(e),E=null}}}};export{$ as Copilot,be as registerCopilot};
38
+ `),this}build(){return this.formattedCompletion}};var b=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!J(this.cursorPosition,this.model)&&!Z(this.cursorPosition,this.model)}};var L=class L{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(L.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}};L.MAX_CACHE_SIZE=10;var v=L;var ye="application/json",ie=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:Me({filename:o,position:l,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":ye},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Me=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let l=Re(e,t),s=k(e,t),a=B(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,cursorPosition:e,editorState:{completionMode:l}}},Re=(o,e)=>{let t=k(o,e),r=B(o,e);return t&&r?"fill-in-the-middle":"completion"};var se=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=X(o),l=M(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function le(o){return O.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var Ie=300,ae=Y(ie,Ie),A=new v,Oe=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new b(t,e).shouldProvideCompletions())return u([]);let s=A.getCompletionCache(t,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=ae({...l,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{ae.cancel()});let c=await a;if(c){let p=le(c),m=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),P=se(p,m,t,e);return A.addCompletionCache({completion:p,range:P,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:p,range:P}])}}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([])},pe=Oe;var f=new WeakMap,E=null,be=(o,e,t)=>{E&&E.deregister();let r=[];f.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,a,c,p)=>{let m=f.get(e);if(m)return pe({monaco:o,model:s,position:a,token:p,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=f.get(e);if(!a)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&c?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),A.clearCompletionCache(),f.delete(e),E=null}};return E=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),f.delete(e),E=null}}}};export{H as Copilot,be as registerCopilot};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monacopilot",
3
- "version": "0.9.22",
3
+ "version": "0.9.24",
4
4
  "description": "AI auto-completion plugin for Monaco Editor",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",