monacopilot 0.9.25 → 0.9.27

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
@@ -11,7 +11,8 @@
11
11
  - [Usage](#usage)
12
12
  - [Copilot Options](#copilot-options)
13
13
  - [Changing the Provider and Model](#changing-the-provider-and-model)
14
- - [Copilot Completion Request Options](#copilot-completion-request-options)
14
+ - [Custom Model](#custom-model)
15
+ - [Completion Request Options](#completion-request-options)
15
16
  - [Custom Headers](#custom-headers)
16
17
  - [Custom Prompt](#custom-prompt)
17
18
  - [Configuration Options](#configuration-options)
@@ -120,19 +121,63 @@ const copilot = new Copilot(process.env.OPENAI_API_KEY, {
120
121
 
121
122
  The default provider is `groq` and the default model is `llama-3-70b`.
122
123
 
123
- | Provider | Model | Description |
124
- | --------- | ----------------- | ------------------------------------------------------------------------------------------------------------------ |
125
- | Groq | llama-3-70b | Ultra-fast inference (<0.5s response time), balancing speed and quality for a wide range of coding tasks |
126
- | OpenAI | gpt-4o | State-of-the-art model excelling in high-quality, context-aware completions |
127
- | OpenAI | gpt-4o-mini | Compact version of gpt-4o, offering cost-effective completions with good performance |
128
- | OpenAI | o1-preview | Think and reason before providing completions, great for complex reasoning and generating high-quality completions |
129
- | OpenAI | o1-mini | Fastest at reasoning and generating completions, providing low-latency completions with reasoning |
130
- | Anthropic | Claude-3.5-Sonnet | Advanced AI with broad knowledge, ideal for diverse coding scenarios and natural language understanding |
131
- | Anthropic | Claude-3-Opus | Top-tier AI model, exceptional at handling intricate tasks and providing detailed, nuanced completions |
132
- | Anthropic | Claude-3-Sonnet | Versatile and powerful, offering a great balance between performance and efficiency for various coding needs |
133
- | Anthropic | Claude-3-Haiku | Streamlined model optimized for speed, perfect for quick completions and real-time coding assistance |
134
-
135
- ## Copilot Completion Request Options
124
+ There are other providers and models available. Here is a list:
125
+
126
+ | Provider | Models |
127
+ | --------- | ------------------------------------------------------------------------- |
128
+ | Groq | `llama-3-70b` |
129
+ | OpenAI | `gpt-4o`, `gpt-4o-mini`, `o1-preview`, `o1-mini` |
130
+ | Anthropic | `claude-3.5-Sonnet`, `claude-3-opus`, `claude-3-sonnet`, `claude-3-haiku` |
131
+
132
+ ### Custom Model
133
+
134
+ You can use a custom AI model that isn't built into Monacopilot by setting up a `model` when you create a new Copilot. This feature lets you connect to AI models from other services or your own custom-built models.
135
+
136
+ #### Example
137
+
138
+ ```javascript
139
+ const copilot = new Copilot(process.env.HUGGINGFACE_API_KEY, {
140
+ model: {
141
+ config: (apiKey, prompt) => ({
142
+ endpoint:
143
+ 'https://api-inference.huggingface.co/models/openai-community/gpt2',
144
+ headers: {
145
+ Authorization: `Bearer ${apiKey}`,
146
+ 'Content-Type': 'application/json',
147
+ },
148
+ body: {
149
+ inputs: prompt.user,
150
+ parameters: {
151
+ max_length: 100,
152
+ num_return_sequences: 1,
153
+ temperature: 0.7,
154
+ },
155
+ },
156
+ }),
157
+ transformResponse: response => ({
158
+ completion: response[0].generated_text,
159
+ }),
160
+ },
161
+ });
162
+ ```
163
+
164
+ #### Configuration
165
+
166
+ The `model` option accepts an object with two functions:
167
+
168
+ 1. `config`: A function that receives the API key and prompt data, and returns the configuration for the custom model API request.
169
+
170
+ - `endpoint`: The URL for the custom model's API (required)
171
+ - `body`: The request body data for the custom model API (optional)
172
+ - `headers`: Additional HTTP headers for the API request (optional)
173
+
174
+ 2. `transformResponse`: A function that takes the raw response from the custom model API and converts it into an object with the following structure:
175
+ - `completion`: A string containing the generated text from the model to be used as the completion.
176
+ - `error`: A string describing any error that occurred during the completion process (optional)
177
+
178
+ 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.
179
+
180
+ ## Completion Request Options
136
181
 
137
182
  ### Custom Headers
138
183
 
package/build/index.d.mts CHANGED
@@ -14,12 +14,65 @@ interface CopilotOptions {
14
14
  */
15
15
  provider?: CompletionProvider;
16
16
  /**
17
- * The specific model to use for completions.
18
- * Must be compatible with the chosen provider.
17
+ * The model to use for generating completions.
18
+ * This can be either:
19
+ * 1. A predefined model name (e.g. 'claude-3-opus'): Use this option if you want to use a model that is built into Monacopilot.
20
+ * If you choose this option, also set the `provider` property to the corresponding provider of the model.
21
+ * 2. A custom model configuration object: Use this option if you want to use a AI model from a third-party service or your own custom model.
22
+ *
19
23
  * If not specified, a default model will be used.
20
24
  */
21
- model?: CompletionModel;
25
+ model?: CompletionModel | CustomModel;
22
26
  }
27
+ type CustomModel = {
28
+ /**
29
+ * A function to configure the custom model.
30
+ * This function takes the API key and the prompt data and returns the configuration for the custom model.
31
+ *
32
+ * @param {string} apiKey - The API key for authentication.
33
+ * @param {Object} prompt - An object containing 'system' and 'user' messages generated by Monacopilot.
34
+ * @returns {Object} An object that may include:
35
+ * - endpoint: The URL for the custom model's API (required)
36
+ * - headers: Additional HTTP headers for the API request (optional)
37
+ * - body: The request body data for the custom model API (optional)
38
+ */
39
+ config: CustomModelConfig;
40
+ /**
41
+ * A function to transform the response from the custom model.
42
+ * This function takes the raw response from the custom model API
43
+ * and converts it into a CompletionResponse object.
44
+ *
45
+ * @param response - The raw response from the custom model API.
46
+ * The type is 'unknown' because different APIs
47
+ * may return responses in different formats.
48
+ * @returns A CompletionResponse object containing the completion text
49
+ * or an error message. The completion should be the actual
50
+ * text to be inserted or used as the completion, without
51
+ * any metadata or additional structure.
52
+ */
53
+ transformResponse: CustomModelResponse;
54
+ };
55
+ type CustomModelConfig = (apiKey: string, prompt: {
56
+ system: string;
57
+ user: string;
58
+ }) => {
59
+ /**
60
+ * The URL endpoint for the custom model's API.
61
+ * This is where the completion request will be sent.
62
+ */
63
+ endpoint: Endpoint;
64
+ /**
65
+ * Additional HTTP headers to include with the API request.
66
+ * Use this to add any necessary authentication or custom headers.
67
+ */
68
+ headers?: Record<string, string>;
69
+ /**
70
+ * The data to be sent in the request body to the custom model API.
71
+ * This should contain all necessary parameters for generating a completion.
72
+ */
73
+ body?: Record<string, unknown>;
74
+ };
75
+ type CustomModelResponse = (response: unknown) => CompletionResponse;
23
76
  type Endpoint = string;
24
77
  type Filename = string;
25
78
  type Technologies = string[];
@@ -82,6 +135,10 @@ type GroqModel = 'llama-3-70b';
82
135
  type AnthropicModel = 'claude-3.5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' | 'claude-3-sonnet';
83
136
  type CompletionModel = OpenAIModel | GroqModel | AnthropicModel;
84
137
  type CompletionProvider = 'openai' | 'groq' | 'anthropic';
138
+ type PromptData = {
139
+ system: string;
140
+ user: string;
141
+ };
85
142
  interface CompletionRequest {
86
143
  /**
87
144
  * The body of the completion request.
@@ -113,10 +170,7 @@ interface CompletionRequestOptions {
113
170
  */
114
171
  customPrompt?: CustomPrompt;
115
172
  }
116
- type CustomPrompt = (completionMetadata: CompletionMetadata) => {
117
- system?: string;
118
- user?: string;
119
- };
173
+ type CustomPrompt = (completionMetadata: CompletionMetadata) => Partial<PromptData>;
120
174
  interface CompletionResponse {
121
175
  completion: string | null;
122
176
  error?: string;
@@ -164,26 +218,41 @@ interface CompletionMetadata {
164
218
  };
165
219
  }
166
220
 
167
- /**
168
- * Copilot class for handling completions using various AI providers.
169
- */
170
221
  declare class Copilot {
171
222
  private readonly apiKey;
172
223
  private readonly provider;
173
224
  private readonly model;
174
225
  /**
175
- * Initializes the Copilot with an API key and optional configuration.
226
+ * Initializes the Copilot instance with an API key and optional configuration.
176
227
  * @param apiKey - The API key for the chosen provider.
177
- * @param options - Options for configuring the Copilot instance.
228
+ * @param options - Optional configuration for the Copilot instance.
178
229
  */
179
230
  constructor(apiKey: string, options?: CopilotOptions);
180
231
  /**
181
- * Sends a completion request to the API and returns the completion.
182
- * @param params - The metadata required to generate the completion.
183
- * @returns A promise resolving to the completed text snippet or an error.
232
+ * Validates the inputs provided to the constructor.
233
+ * Ensures the selected model is supported by the provider.
184
234
  */
185
- complete({ body, options, }: CompletionRequest): Promise<CompletionResponse>;
186
235
  private validateInputs;
236
+ /**
237
+ * Generates the prompt based on the completion metadata and any custom prompt function.
238
+ * @param completionMetadata - The metadata for the completion.
239
+ * @param customPrompt - An optional custom prompt function.
240
+ * @returns The generated prompt.
241
+ */
242
+ private generatePrompt;
243
+ /**
244
+ * Prepares the request details including endpoint, request body, and headers.
245
+ * @param prompt - The generated prompt.
246
+ * @param customHeaders - Any custom headers to include.
247
+ * @returns An object containing the endpoint, request body, and headers.
248
+ */
249
+ private prepareRequest;
250
+ /**
251
+ * Sends a completion request to the API and returns the completion.
252
+ * @param request - The completion request containing the body and options.
253
+ * @returns A promise resolving to the completion response or an error.
254
+ */
255
+ complete(request: CompletionRequest): Promise<CompletionResponse>;
187
256
  }
188
257
 
189
258
  /**
package/build/index.d.ts CHANGED
@@ -14,12 +14,65 @@ interface CopilotOptions {
14
14
  */
15
15
  provider?: CompletionProvider;
16
16
  /**
17
- * The specific model to use for completions.
18
- * Must be compatible with the chosen provider.
17
+ * The model to use for generating completions.
18
+ * This can be either:
19
+ * 1. A predefined model name (e.g. 'claude-3-opus'): Use this option if you want to use a model that is built into Monacopilot.
20
+ * If you choose this option, also set the `provider` property to the corresponding provider of the model.
21
+ * 2. A custom model configuration object: Use this option if you want to use a AI model from a third-party service or your own custom model.
22
+ *
19
23
  * If not specified, a default model will be used.
20
24
  */
21
- model?: CompletionModel;
25
+ model?: CompletionModel | CustomModel;
22
26
  }
27
+ type CustomModel = {
28
+ /**
29
+ * A function to configure the custom model.
30
+ * This function takes the API key and the prompt data and returns the configuration for the custom model.
31
+ *
32
+ * @param {string} apiKey - The API key for authentication.
33
+ * @param {Object} prompt - An object containing 'system' and 'user' messages generated by Monacopilot.
34
+ * @returns {Object} An object that may include:
35
+ * - endpoint: The URL for the custom model's API (required)
36
+ * - headers: Additional HTTP headers for the API request (optional)
37
+ * - body: The request body data for the custom model API (optional)
38
+ */
39
+ config: CustomModelConfig;
40
+ /**
41
+ * A function to transform the response from the custom model.
42
+ * This function takes the raw response from the custom model API
43
+ * and converts it into a CompletionResponse object.
44
+ *
45
+ * @param response - The raw response from the custom model API.
46
+ * The type is 'unknown' because different APIs
47
+ * may return responses in different formats.
48
+ * @returns A CompletionResponse object containing the completion text
49
+ * or an error message. The completion should be the actual
50
+ * text to be inserted or used as the completion, without
51
+ * any metadata or additional structure.
52
+ */
53
+ transformResponse: CustomModelResponse;
54
+ };
55
+ type CustomModelConfig = (apiKey: string, prompt: {
56
+ system: string;
57
+ user: string;
58
+ }) => {
59
+ /**
60
+ * The URL endpoint for the custom model's API.
61
+ * This is where the completion request will be sent.
62
+ */
63
+ endpoint: Endpoint;
64
+ /**
65
+ * Additional HTTP headers to include with the API request.
66
+ * Use this to add any necessary authentication or custom headers.
67
+ */
68
+ headers?: Record<string, string>;
69
+ /**
70
+ * The data to be sent in the request body to the custom model API.
71
+ * This should contain all necessary parameters for generating a completion.
72
+ */
73
+ body?: Record<string, unknown>;
74
+ };
75
+ type CustomModelResponse = (response: unknown) => CompletionResponse;
23
76
  type Endpoint = string;
24
77
  type Filename = string;
25
78
  type Technologies = string[];
@@ -82,6 +135,10 @@ type GroqModel = 'llama-3-70b';
82
135
  type AnthropicModel = 'claude-3.5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' | 'claude-3-sonnet';
83
136
  type CompletionModel = OpenAIModel | GroqModel | AnthropicModel;
84
137
  type CompletionProvider = 'openai' | 'groq' | 'anthropic';
138
+ type PromptData = {
139
+ system: string;
140
+ user: string;
141
+ };
85
142
  interface CompletionRequest {
86
143
  /**
87
144
  * The body of the completion request.
@@ -113,10 +170,7 @@ interface CompletionRequestOptions {
113
170
  */
114
171
  customPrompt?: CustomPrompt;
115
172
  }
116
- type CustomPrompt = (completionMetadata: CompletionMetadata) => {
117
- system?: string;
118
- user?: string;
119
- };
173
+ type CustomPrompt = (completionMetadata: CompletionMetadata) => Partial<PromptData>;
120
174
  interface CompletionResponse {
121
175
  completion: string | null;
122
176
  error?: string;
@@ -164,26 +218,41 @@ interface CompletionMetadata {
164
218
  };
165
219
  }
166
220
 
167
- /**
168
- * Copilot class for handling completions using various AI providers.
169
- */
170
221
  declare class Copilot {
171
222
  private readonly apiKey;
172
223
  private readonly provider;
173
224
  private readonly model;
174
225
  /**
175
- * Initializes the Copilot with an API key and optional configuration.
226
+ * Initializes the Copilot instance with an API key and optional configuration.
176
227
  * @param apiKey - The API key for the chosen provider.
177
- * @param options - Options for configuring the Copilot instance.
228
+ * @param options - Optional configuration for the Copilot instance.
178
229
  */
179
230
  constructor(apiKey: string, options?: CopilotOptions);
180
231
  /**
181
- * Sends a completion request to the API and returns the completion.
182
- * @param params - The metadata required to generate the completion.
183
- * @returns A promise resolving to the completed text snippet or an error.
232
+ * Validates the inputs provided to the constructor.
233
+ * Ensures the selected model is supported by the provider.
184
234
  */
185
- complete({ body, options, }: CompletionRequest): Promise<CompletionResponse>;
186
235
  private validateInputs;
236
+ /**
237
+ * Generates the prompt based on the completion metadata and any custom prompt function.
238
+ * @param completionMetadata - The metadata for the completion.
239
+ * @param customPrompt - An optional custom prompt function.
240
+ * @returns The generated prompt.
241
+ */
242
+ private generatePrompt;
243
+ /**
244
+ * Prepares the request details including endpoint, request body, and headers.
245
+ * @param prompt - The generated prompt.
246
+ * @param customHeaders - Any custom headers to include.
247
+ * @returns An object containing the endpoint, request body, and headers.
248
+ */
249
+ private prepareRequest;
250
+ /**
251
+ * Sends a completion request to the API and returns the completion.
252
+ * @param request - The completion request containing the body and options.
253
+ * @returns A promise resolving to the completion response or an error.
254
+ */
255
+ complete(request: CompletionRequest): Promise<CompletionResponse>;
187
256
  }
188
257
 
189
258
  /**
package/build/index.js CHANGED
@@ -1,21 +1,21 @@
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","o1-preview":"o1-preview","o1-mini":"o1-mini"},D={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"]},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(`
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(`
2
2
  `);return`
3
- \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${t}]\x1B[0m \x1B[2m${i}\x1B[0m
4
- ${P}
3
+ \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${o}]\x1B[0m \x1B[2m${i}\x1B[0m
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 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}.
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}.
9
9
 
10
- `;return p+=Me(r,t),p+=`
10
+ `;return p+=be(r,o),p+=`
11
11
 
12
12
  Here are the details about how the completion should be generated:
13
- - The cursor position is marked with '${I}'.
13
+ - The cursor position is marked with '${b}'.
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 '${I}' entirely with your completion.
18
- `:n==="completion"&&(p+=` - If completing the code, start from '${I}' and provide a logical continuation.
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
19
  `),p+=` - Optimize for readability and performance where possible.
20
20
 
21
21
  Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
@@ -23,16 +23,16 @@ Here are the details about how the completion should be generated:
23
23
  Here's the code snippet for completion:
24
24
 
25
25
  <code>
26
- ${i}${I}${l}
26
+ ${i}${b}${l}
27
27
  </code>`,s&&s.length>0&&(p+=`
28
28
 
29
29
  Additional context from related files:
30
30
 
31
- `,p+=s.map(m=>`// Path: ${m.path}
32
- ${m.content}
31
+ `,p+=s.map(c=>`// Path: ${c.path}
32
+ ${c.content}
33
33
  `).join(`
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(`
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(`
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!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});
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});
package/build/index.mjs CHANGED
@@ -1,21 +1,21 @@
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","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"]},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(`
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(`
2
2
  `);return`
3
- \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${t}]\x1B[0m \x1B[2m${i}\x1B[0m
4
- ${P}
3
+ \x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${o}]\x1B[0m \x1B[2m${i}\x1B[0m
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 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}.
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}.
9
9
 
10
- `;return p+=ge(r,t),p+=`
10
+ `;return p+=fe(r,o),p+=`
11
11
 
12
12
  Here are the details about how the completion should be generated:
13
- - The cursor position is marked with '${I}'.
13
+ - The cursor position is marked with '${b}'.
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 '${I}' entirely with your completion.
18
- `:n==="completion"&&(p+=` - If completing the code, start from '${I}' and provide a logical continuation.
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
19
  `),p+=` - Optimize for readability and performance where possible.
20
20
 
21
21
  Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
@@ -23,16 +23,16 @@ Here are the details about how the completion should be generated:
23
23
  Here's the code snippet for completion:
24
24
 
25
25
  <code>
26
- ${i}${I}${l}
26
+ ${i}${b}${l}
27
27
  </code>`,s&&s.length>0&&(p+=`
28
28
 
29
29
  Additional context from related files:
30
30
 
31
- `,p+=s.map(m=>`// Path: ${m.path}
32
- ${m.content}
31
+ `,p+=s.map(c=>`// Path: ${c.path}
32
+ ${c.content}
33
33
  `).join(`
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(`
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(`
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 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};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monacopilot",
3
- "version": "0.9.25",
3
+ "version": "0.9.27",
4
4
  "description": "AI auto-completion plugin for Monaco Editor",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",
@@ -21,13 +21,13 @@
21
21
  "release": "release-it"
22
22
  },
23
23
  "devDependencies": {
24
- "@anthropic-ai/sdk": "^0.27.1",
24
+ "@anthropic-ai/sdk": "^0.27.3",
25
25
  "@ianvs/prettier-plugin-sort-imports": "^4.2.1",
26
26
  "@typescript-eslint/eslint-plugin": "^7.3.1",
27
27
  "eslint": "^8.57.0",
28
28
  "groq-sdk": "^0.3.2",
29
29
  "monaco-editor": "^0.50.0",
30
- "openai": "^4.56.0",
30
+ "openai": "^4.60.1",
31
31
  "prettier": "^3.2.5",
32
32
  "release-it": "^17.2.1",
33
33
  "tsup": "^8.0.2",