monacopilot 0.14.2 → 0.15.1

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
@@ -288,7 +288,7 @@ registerCompletion(monaco, editor, {
288
288
 
289
289
  ### Caching Completions
290
290
 
291
- Monacopilot caches completions by default. It uses a FIFO (First In First Out) strategy, reusing cached completions when the context and cursor position match while editing. To disable caching:
291
+ Monacopilot caches completions by default. It uses a FIFO (First In First Out) strategy, reusing cached completions when the context and cursor position match while editing (default: `true`). To disable caching:
292
292
 
293
293
  ```javascript
294
294
  registerCompletion(monaco, editor, {
@@ -419,11 +419,12 @@ The default provider is `anthropic`, and the default model is `claude-3-5-haiku`
419
419
 
420
420
  There are other providers and models available. Here is a list:
421
421
 
422
- | Provider | Models |
423
- | --------- | --------------------------------------------------------- |
424
- | Groq | `llama-3-70b` |
425
- | OpenAI | `gpt-4o`, `gpt-4o-mini`, `o1-preview`, `o1-mini` |
426
- | Anthropic | `claude-3-5-sonnet`, `claude-3-haiku`, `claude-3-5-haiku` |
422
+ | Provider | Models |
423
+ | --------- | ----------------------------------------------------------- |
424
+ | Groq | `llama-3-70b` |
425
+ | OpenAI | `gpt-4o`, `gpt-4o-mini`, `o1-mini (beta model)` |
426
+ | Anthropic | `claude-3-5-sonnet`, `claude-3-haiku`, `claude-3-5-haiku` |
427
+ | Google | `gemini-1.5-pro`, `gemini-1.5-flash`, `gemini-1.5-flash-8b` |
427
428
 
428
429
  ### Custom Model
429
430
 
package/build/index.d.mts CHANGED
@@ -4,67 +4,47 @@ import { ChatCompletion } from 'openai/resources/chat/completions';
4
4
  import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
5
5
  import * as monaco_editor from 'monaco-editor';
6
6
 
7
- type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-preview' | 'o1-mini';
7
+ /**
8
+ * Models available for OpenAI provider.
9
+ */
10
+ type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-mini';
11
+ /**
12
+ * Models available for Groq provider.
13
+ */
8
14
  type GroqModel = 'llama-3-70b';
15
+ /**
16
+ * Models available for Anthropic provider.
17
+ */
9
18
  type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-5-haiku' | 'claude-3-haiku';
10
- type CopilotModel = OpenAIModel | GroqModel | AnthropicModel;
11
- type CopilotProvider = 'openai' | 'groq' | 'anthropic';
19
+ /**
20
+ * Models available for Google provider.
21
+ */
22
+ type GoogleModel = 'gemini-1.5-flash' | 'gemini-1.5-flash-8b' | 'gemini-1.5-pro';
23
+ /**
24
+ * Union of all predefined Copilot models.
25
+ */
26
+ type CopilotModel = OpenAIModel | GroqModel | AnthropicModel | GoogleModel;
27
+ /**
28
+ * Providers supported by Copilot.
29
+ */
30
+ type CopilotProvider = 'openai' | 'groq' | 'anthropic' | 'google';
31
+ /**
32
+ * Specific ChatCompletion types for each provider.
33
+ */
12
34
  type OpenAIChatCompletion = ChatCompletion;
13
35
  type GroqChatCompletion = ChatCompletion$1;
14
36
  type AnthropicChatCompletion = Message;
15
- type PromptData = {
16
- system: string;
17
- user: string;
18
- };
19
37
  /**
20
- * Options for configuring the Copilot instance.
38
+ * Data structure representing the prompt data.
21
39
  */
22
- interface CopilotOptions {
23
- /**
24
- * The provider to use (e.g., 'openai', 'anthropic', 'groq').
25
- * If not specified, a default provider will be used.
26
- */
27
- provider?: CopilotProvider;
28
- /**
29
- * The model to use for copilot LLM requests.
30
- * This can be either:
31
- * 1. A predefined model name (e.g. 'claude-3-5-haiku'): Use this option if you want to use a model that is built into Monacopilot.
32
- * If you choose this option, also set the `provider` property to the corresponding provider of the model.
33
- * 2. A custom model configuration object: Use this option if you want to use a LLM from a third-party service or your own custom model.
34
- *
35
- * If not specified, a default model will be used.
36
- */
37
- model?: CopilotModel | CustomCopilotModel;
38
- }
39
- type CustomCopilotModel = {
40
- /**
41
- * A function to configure the custom model.
42
- * This function takes the API key and the prompt data and returns the configuration for the custom model.
43
- *
44
- * @param {string} apiKey - The API key for authentication.
45
- * @param {Object} prompt - An object containing 'system' and 'user' messages generated by Monacopilot.
46
- * @returns {Object} An object that may include:
47
- * - endpoint: The URL for the custom model's API (required)
48
- * - headers: Additional HTTP headers for the API request (optional)
49
- * - body: The request body data for the custom model API (optional)
50
- */
51
- config: CustomCopilotModelConfig;
52
- /**
53
- * A function to transform the response from the custom model.
54
- * This function takes the raw response from the custom model API
55
- * and returns the model generated text or null.
56
- *
57
- * @param response - The raw response from the custom model API.
58
- * The type is 'unknown' because different APIs
59
- * may return responses in different formats.
60
- * @returns The model generated text or null if no valid text could be extracted.
61
- */
62
- transformResponse: CustomCopilotModelTransformResponse;
63
- };
64
- type CustomCopilotModelConfig = (apiKey: string, prompt: {
40
+ interface PromptData {
65
41
  system: string;
66
42
  user: string;
67
- }) => {
43
+ }
44
+ /**
45
+ * Function type for configuring a custom model.
46
+ */
47
+ type CustomCopilotModelConfig = (apiKey: string, prompt: PromptData) => {
68
48
  /**
69
49
  * The URL endpoint for the custom model's API.
70
50
  */
@@ -79,6 +59,9 @@ type CustomCopilotModelConfig = (apiKey: string, prompt: {
79
59
  */
80
60
  body?: Record<string, unknown>;
81
61
  };
62
+ /**
63
+ * Function type for transforming the response from a custom model.
64
+ */
82
65
  type CustomCopilotModelTransformResponse = (response: unknown) => {
83
66
  /**
84
67
  * The text generated by the custom model.
@@ -89,6 +72,77 @@ type CustomCopilotModelTransformResponse = (response: unknown) => {
89
72
  */
90
73
  completion?: string | null;
91
74
  };
75
+ /**
76
+ * Definition of a custom Copilot model.
77
+ */
78
+ interface CustomCopilotModel {
79
+ /**
80
+ * Function to configure the custom model.
81
+ */
82
+ config: CustomCopilotModelConfig;
83
+ /**
84
+ * Function to transform the response from the custom model.
85
+ */
86
+ transformResponse: CustomCopilotModelTransformResponse;
87
+ }
88
+ /**
89
+ * Configuration options for initializing a Copilot instance.
90
+ * The `model` property is type-safe and varies based on the specified `provider`.
91
+ */
92
+ type CopilotOptions = {
93
+ /**
94
+ * Specifies the provider for the Copilot instance.
95
+ * Supported providers include 'openai', 'anthropic', 'groq', and 'google'.
96
+ */
97
+ provider: 'openai';
98
+ /**
99
+ * Defines the model to be used for Copilot LLM (Language Model) requests.
100
+ * This must be a model from the 'openai' provider.
101
+ */
102
+ model?: OpenAIModel;
103
+ } | {
104
+ /**
105
+ * Specifies the 'groq' provider for the Copilot instance.
106
+ */
107
+ provider: 'groq';
108
+ /**
109
+ * Defines the model to be used for Copilot LLM requests.
110
+ * This must be a model from the 'groq' provider.
111
+ */
112
+ model?: GroqModel;
113
+ } | {
114
+ /**
115
+ * Specifies the 'anthropic' provider for the Copilot instance.
116
+ */
117
+ provider: 'anthropic';
118
+ /**
119
+ * Defines the model to be used for Copilot LLM requests.
120
+ * This must be a model from the 'anthropic' provider.
121
+ */
122
+ model?: AnthropicModel;
123
+ } | {
124
+ /**
125
+ * Specifies the 'google' provider for the Copilot instance.
126
+ */
127
+ provider: 'google';
128
+ /**
129
+ * Defines the model to be used for Copilot LLM requests.
130
+ * This must be a model from the 'google' provider.
131
+ */
132
+ model?: GoogleModel;
133
+ } | {
134
+ /**
135
+ * When no provider is specified, only custom models are allowed.
136
+ */
137
+ provider?: undefined;
138
+ /**
139
+ * Defines the model to be used for Copilot LLM requests.
140
+ * Must be a custom model when no provider is specified.
141
+ * For more information, refer to the documentation:
142
+ * @see https://github.com/arshad-yaseen/monacopilot?tab=readme-ov-file#custom-model
143
+ */
144
+ model?: CustomCopilotModel;
145
+ };
92
146
 
93
147
  type Monaco = typeof monaco;
94
148
  type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
package/build/index.d.ts CHANGED
@@ -4,67 +4,47 @@ import { ChatCompletion } from 'openai/resources/chat/completions';
4
4
  import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
5
5
  import * as monaco_editor from 'monaco-editor';
6
6
 
7
- type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-preview' | 'o1-mini';
7
+ /**
8
+ * Models available for OpenAI provider.
9
+ */
10
+ type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-mini';
11
+ /**
12
+ * Models available for Groq provider.
13
+ */
8
14
  type GroqModel = 'llama-3-70b';
15
+ /**
16
+ * Models available for Anthropic provider.
17
+ */
9
18
  type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-5-haiku' | 'claude-3-haiku';
10
- type CopilotModel = OpenAIModel | GroqModel | AnthropicModel;
11
- type CopilotProvider = 'openai' | 'groq' | 'anthropic';
19
+ /**
20
+ * Models available for Google provider.
21
+ */
22
+ type GoogleModel = 'gemini-1.5-flash' | 'gemini-1.5-flash-8b' | 'gemini-1.5-pro';
23
+ /**
24
+ * Union of all predefined Copilot models.
25
+ */
26
+ type CopilotModel = OpenAIModel | GroqModel | AnthropicModel | GoogleModel;
27
+ /**
28
+ * Providers supported by Copilot.
29
+ */
30
+ type CopilotProvider = 'openai' | 'groq' | 'anthropic' | 'google';
31
+ /**
32
+ * Specific ChatCompletion types for each provider.
33
+ */
12
34
  type OpenAIChatCompletion = ChatCompletion;
13
35
  type GroqChatCompletion = ChatCompletion$1;
14
36
  type AnthropicChatCompletion = Message;
15
- type PromptData = {
16
- system: string;
17
- user: string;
18
- };
19
37
  /**
20
- * Options for configuring the Copilot instance.
38
+ * Data structure representing the prompt data.
21
39
  */
22
- interface CopilotOptions {
23
- /**
24
- * The provider to use (e.g., 'openai', 'anthropic', 'groq').
25
- * If not specified, a default provider will be used.
26
- */
27
- provider?: CopilotProvider;
28
- /**
29
- * The model to use for copilot LLM requests.
30
- * This can be either:
31
- * 1. A predefined model name (e.g. 'claude-3-5-haiku'): Use this option if you want to use a model that is built into Monacopilot.
32
- * If you choose this option, also set the `provider` property to the corresponding provider of the model.
33
- * 2. A custom model configuration object: Use this option if you want to use a LLM from a third-party service or your own custom model.
34
- *
35
- * If not specified, a default model will be used.
36
- */
37
- model?: CopilotModel | CustomCopilotModel;
38
- }
39
- type CustomCopilotModel = {
40
- /**
41
- * A function to configure the custom model.
42
- * This function takes the API key and the prompt data and returns the configuration for the custom model.
43
- *
44
- * @param {string} apiKey - The API key for authentication.
45
- * @param {Object} prompt - An object containing 'system' and 'user' messages generated by Monacopilot.
46
- * @returns {Object} An object that may include:
47
- * - endpoint: The URL for the custom model's API (required)
48
- * - headers: Additional HTTP headers for the API request (optional)
49
- * - body: The request body data for the custom model API (optional)
50
- */
51
- config: CustomCopilotModelConfig;
52
- /**
53
- * A function to transform the response from the custom model.
54
- * This function takes the raw response from the custom model API
55
- * and returns the model generated text or null.
56
- *
57
- * @param response - The raw response from the custom model API.
58
- * The type is 'unknown' because different APIs
59
- * may return responses in different formats.
60
- * @returns The model generated text or null if no valid text could be extracted.
61
- */
62
- transformResponse: CustomCopilotModelTransformResponse;
63
- };
64
- type CustomCopilotModelConfig = (apiKey: string, prompt: {
40
+ interface PromptData {
65
41
  system: string;
66
42
  user: string;
67
- }) => {
43
+ }
44
+ /**
45
+ * Function type for configuring a custom model.
46
+ */
47
+ type CustomCopilotModelConfig = (apiKey: string, prompt: PromptData) => {
68
48
  /**
69
49
  * The URL endpoint for the custom model's API.
70
50
  */
@@ -79,6 +59,9 @@ type CustomCopilotModelConfig = (apiKey: string, prompt: {
79
59
  */
80
60
  body?: Record<string, unknown>;
81
61
  };
62
+ /**
63
+ * Function type for transforming the response from a custom model.
64
+ */
82
65
  type CustomCopilotModelTransformResponse = (response: unknown) => {
83
66
  /**
84
67
  * The text generated by the custom model.
@@ -89,6 +72,77 @@ type CustomCopilotModelTransformResponse = (response: unknown) => {
89
72
  */
90
73
  completion?: string | null;
91
74
  };
75
+ /**
76
+ * Definition of a custom Copilot model.
77
+ */
78
+ interface CustomCopilotModel {
79
+ /**
80
+ * Function to configure the custom model.
81
+ */
82
+ config: CustomCopilotModelConfig;
83
+ /**
84
+ * Function to transform the response from the custom model.
85
+ */
86
+ transformResponse: CustomCopilotModelTransformResponse;
87
+ }
88
+ /**
89
+ * Configuration options for initializing a Copilot instance.
90
+ * The `model` property is type-safe and varies based on the specified `provider`.
91
+ */
92
+ type CopilotOptions = {
93
+ /**
94
+ * Specifies the provider for the Copilot instance.
95
+ * Supported providers include 'openai', 'anthropic', 'groq', and 'google'.
96
+ */
97
+ provider: 'openai';
98
+ /**
99
+ * Defines the model to be used for Copilot LLM (Language Model) requests.
100
+ * This must be a model from the 'openai' provider.
101
+ */
102
+ model?: OpenAIModel;
103
+ } | {
104
+ /**
105
+ * Specifies the 'groq' provider for the Copilot instance.
106
+ */
107
+ provider: 'groq';
108
+ /**
109
+ * Defines the model to be used for Copilot LLM requests.
110
+ * This must be a model from the 'groq' provider.
111
+ */
112
+ model?: GroqModel;
113
+ } | {
114
+ /**
115
+ * Specifies the 'anthropic' provider for the Copilot instance.
116
+ */
117
+ provider: 'anthropic';
118
+ /**
119
+ * Defines the model to be used for Copilot LLM requests.
120
+ * This must be a model from the 'anthropic' provider.
121
+ */
122
+ model?: AnthropicModel;
123
+ } | {
124
+ /**
125
+ * Specifies the 'google' provider for the Copilot instance.
126
+ */
127
+ provider: 'google';
128
+ /**
129
+ * Defines the model to be used for Copilot LLM requests.
130
+ * This must be a model from the 'google' provider.
131
+ */
132
+ model?: GoogleModel;
133
+ } | {
134
+ /**
135
+ * When no provider is specified, only custom models are allowed.
136
+ */
137
+ provider?: undefined;
138
+ /**
139
+ * Defines the model to be used for Copilot LLM requests.
140
+ * Must be a custom model when no provider is specified.
141
+ * For more information, refer to the documentation:
142
+ * @see https://github.com/arshad-yaseen/monacopilot?tab=readme-ov-file#custom-model
143
+ */
144
+ model?: CustomCopilotModel;
145
+ };
92
146
 
93
147
  type Monaco = typeof monaco;
94
148
  type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
package/build/index.js CHANGED
@@ -1,16 +1,18 @@
1
- "use strict";var $=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Me=(t,e)=>{for(var o in e)$(t,o,{get:e[o],enumerable:!0})},be=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Oe(e))!Ee.call(t,n)&&n!==o&&$(t,n,{get:()=>e[n],enumerable:!(r=Te(e,n))||r.enumerable});return t};var ve=t=>be($({},"__esModule",{value:!0}),t);var We={};Me(We,{Copilot:()=>_,registerCompletion:()=>G,registerCopilot:()=>xe});module.exports=ve(We);var H=["groq","openai","anthropic"],X={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3-5-sonnet":"claude-3-5-sonnet-20241022","claude-3-haiku":"claude-3-haiku-20240307","claude-3-5-haiku":"claude-3-5-haiku-20241022","o1-preview":"o1-preview","o1-mini":"o1-mini"},V={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-preview","o1-mini"],anthropic:["claude-3-5-sonnet","claude-3-haiku","claude-3-5-haiku"]},J="anthropic",Z="claude-3-5-haiku",Q={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=.1;var ee={"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-haiku":4096};var Ie={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:U(t),temperature:v,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},Ae={createRequestBody:(t,e)=>({model:U(t),temperature:v,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?t.choices[0].message.content:null},Le={createRequestBody:(t,e)=>({model:U(t),temperature:v,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:we(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>{if(!t.content||!Array.isArray(t.content)||!t.content.length)return null;let e=t.content[0];return!e||typeof e!="object"?null:"text"in e&&typeof e.text=="string"?e.text:null}},j={openai:Ie,groq:Ae,anthropic:Le},te=(t,e,o)=>j[e].createRequestBody(t,o),oe=(t,e)=>j[e].createHeaders(t),re=(t,e)=>j[e].parseCompletion(t),U=t=>X[t],ne=t=>Q[t],we=t=>ee[t]||4096;var ie="\x1B[91m",se="\x1B[93m",I="\x1B[0m",W="\x1B[1m",R=t=>{let e,o;t instanceof Error?(e=t.message,o=t.stack):typeof t=="string"?e=t:e="An unknown error occurred";let r=`${ie}${W}[MONACOPILOT ERROR] ${e}${I}`;return console.error(o?`${r}
2
- ${ie}Stack trace:${I}
3
- ${o}`:r),{message:e,stack:o}},ae=t=>{console.warn(`${se}${W}[MONACOPILOT WARN] ${t}${I}`)};var A=(t,e,o)=>console.warn(`${se}${W}[MONACOPILOT DEPRECATED] "${t}" is deprecated${o?` in ${o}`:""}. Please use "${e}" instead. It will be removed in a future version.${I}`);var L=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((s,l)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=l,o=setTimeout(()=>{s(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},M=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var z=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1];var w=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),le=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),T=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),pe=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())}),K=(t,e,o={})=>{if(e<=0)return"";let r=t.split(`
4
- `),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(l=>l==="")?`
1
+ 'use strict';
2
+
3
+ var U=["groq","openai","anthropic","google"],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-20241022","claude-3-haiku":"claude-3-haiku-20240307","claude-3-5-haiku":"claude-3-5-haiku-20241022","o1-mini":"o1-mini","gemini-1.5-flash-8b":"gemini-1.5-flash-8b","gemini-1.5-flash":"gemini-1.5-flash","gemini-1.5-pro":"gemini-1.5-pro"},K={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-mini"],anthropic:["claude-3-5-sonnet","claude-3-haiku","claude-3-5-haiku"],google:["gemini-1.5-flash-8b","gemini-1.5-pro","gemini-1.5-flash"]},Z="anthropic",Q="claude-3-5-haiku",O={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages",google:"https://generativelanguage.googleapis.com/v1beta/models"},M=.1;var ee={"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-haiku":4096};var fe={createEndpoint:()=>O.openai,createRequestBody:(t,e)=>{let o=t==="o1-mini";return {model:A(t),...!o&&{temperature:M},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?t.choices[0].message.content:null},Pe={createEndpoint:()=>O.groq,createRequestBody:(t,e)=>({model:A(t),temperature:M,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?t.choices[0].message.content:null},ye={createEndpoint:()=>O.anthropic,createRequestBody:(t,e)=>({model:A(t),temperature:M,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:ee[t]}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>{if(!t.content||!Array.isArray(t.content)||!t.content.length)return null;let e=t.content[0];return !e||typeof e!="object"?null:"text"in e&&typeof e.text=="string"?e.text:null}},xe={createEndpoint:(t,e)=>`${O.google}/${t}:generateContent?key=${e}`,createRequestBody:(t,e)=>({model:A(t),system_instruction:{parts:{text:e.system}},contents:[{parts:{text:e.user}}]}),createHeaders:()=>({"Content-Type":"application/json"}),parseCompletion:t=>{if(!t.candidates?.length||!t.candidates[0]?.content||!t.candidates[0].content?.parts?.length)return null;let e=t.candidates[0].content;return "text"in e.parts[0]&&typeof e.parts[0].text=="string"?e.parts[0].text:null}},I={openai:fe,groq:Pe,anthropic:ye,google:xe},te=(t,e,o)=>I[o].createEndpoint(t,e),oe=(t,e,o)=>I[e].createRequestBody(t,o),re=(t,e)=>I[e].createHeaders(t),ne=(t,e)=>I[e].parseCompletion(t),A=t=>J[t];var Re="\x1B[91m",ie="\x1B[93m",W="\x1B[0m",z="\x1B[1m",y=t=>{let e;t instanceof Error?e=t.message:typeof t=="string"?e=t:e="An unknown error occurred";let o=`${Re}${z}[MONACOPILOT ERROR] ${e}${W}`;return console.error(o),{message:e}},se=t=>{console.warn(`${ie}${z}[MONACOPILOT WARN] ${t}${W}`);};var L=(t,e,o)=>console.warn(`${ie}${z}[MONACOPILOT DEPRECATED] "${t}" is deprecated${o?` in ${o}`:""}. Please use "${e}" instead. It will be removed in a future version.${W}`);var T=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`,Y=(t,e,o={})=>{if(e<=0)return "";let r=t.split(`
4
+ `),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(a=>a==="")?`
5
5
  `.repeat(e):s.join(`
6
6
  `)}let i=r.slice(0,e);return i.every(s=>s==="")?`
7
7
  `.repeat(e):i.join(`
8
- `)};var ce=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(`${i.statusText||o.fallbackError||"Network error"}`);return i.json()},Ne=(t,e)=>ce(t,"GET",e),_e=(t,e,o)=>ce(t,"POST",{...o,body:e}),N={GET:Ne,POST:_e};var de=(t,e)=>{let o=w(t,e).trim(),r=le(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var De=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:n}=t,i=M([n,...e].filter(l=>typeof l=="string"&&!!l));return[`You are an expert ${i?`${i} `:""}developer assistant specialized in precise code completion and generation.`,`Your primary task is to provide accurate, context-aware code completions that seamlessly integrate with existing codebases${o?` in '${o}'`:""}.`,`You must:
9
- - Generate only the exact code required
10
- - Maintain strict adherence to provided instructions
11
- - Follow established code patterns and conventions
12
- - Consider the full context before generating code`,r?.length?"Analyze and incorporate context from all provided related files to ensure consistent and appropriate code generation.":"",n?`Apply ${n}-specific best practices, idioms, and syntax conventions in all generated code.`:""].filter(Boolean).join(`
13
- `)},Se=t=>t?.length?t.map(({path:e,content:o})=>`
8
+ `)};var w=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],D=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),ae=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),h=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),S=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var le=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){let s=`
9
+ `+(JSON.stringify(await i.json(),null,2)||"");throw new Error(`${i.statusText||o.fallbackError||"Network error"}${s}`)}return i.json()},Oe=(t,e)=>le(t,"GET",e),Te=(t,e,o)=>le(t,"POST",{...o,body:e}),N={GET:Oe,POST:Te};var pe=(t,e)=>{let o=D(t,e).trim(),r=ae(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var F=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((s,a)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=a,o=setTimeout(()=>{s(t(...i)),r=null;},e);});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null);},n};var ve=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:n}=t,i=T([n,...e].filter(a=>typeof a=="string"&&!!a));return [`You are an expert ${i?`${i} `:""}developer assistant specialized in precise code completion.`,`Your primary task is to provide accurate, context-aware code completions that seamlessly integrate with existing codebases${o?` in '${o}'`:""}.`,`You must:
10
+ - Generate only the exact code required.
11
+ - Maintain strict adherence to provided instructions.
12
+ - Follow established code patterns and conventions.
13
+ - Consider the full context before generating code.`,r?.length?"Analyze and incorporate context from all provided related files to ensure consistent and appropriate code completion.":"",n?`Apply ${n}-specific best practices, idioms, and syntax conventions in all generated code.`:""].filter(Boolean).join(`
14
+
15
+ `)},Ee=t=>t?.length?t.map(({path:e,content:o})=>`
14
16
  <related_file>
15
17
  <path>${e}</path>
16
18
  <content_context>
@@ -20,118 +22,35 @@ ${o}
20
22
  </content_context>
21
23
  </related_file>`.trim()).join(`
22
24
 
23
- `):"",ke=(t="",e)=>{let{relatedFiles:o}=e;return`
25
+ `):"",be=(t="",e)=>{let{relatedFiles:o}=e;return `
24
26
  <task_context>
25
27
  <primary_instructions>
26
28
  ${t.trim()}
27
- </primary_instructions>
28
- ${o?.length?`
29
+ </primary_instructions>${o?.length?`
29
30
  <reference_files>
30
- ${Se(o)}
31
+ ${Ee(o)}
31
32
  </reference_files>`:""}
32
- </task_context>`.trim()},me=(t,e)=>({system:De(e),user:ke(t,e)});var ue="<cursor>",Be=t=>{let{textBeforeCursor:e="",textAfterCursor:o="",editorState:{completionMode:r},language:n}=t,i=`<code_file>
33
- ${e}${ue}${o}
34
- </code_file>`,l=`
35
- <instructions>
36
- <context>
37
- Below is a ${n||"code"} file with the token '${ue}' marking the exact cursor position where code completion is needed.
38
-
39
- ${i}
40
- </context>
41
-
42
- <critical_rules>
43
- 1. NEVER REPEAT ANY TEXT THAT APPEARS BEFORE THE CURSOR
44
- 2. Start your completion EXACTLY from the cursor position
45
- 3. If user types 'const ' and cursor is after it, DO NOT include 'const ' in your completion
46
- 4. ONLY provide the remaining part of the code that should appear after the cursor
47
- 5. Violation of these rules will cause code duplication and syntax errors
48
- </critical_rules>
49
-
50
- <primary_objectives>
51
- 1. Generate code that is syntactically correct and follows ${n||"the language"}'s best practices
52
- 2. Ensure seamless integration with existing code structure
53
- 3. Maintain consistent naming conventions and coding style
54
- 4. Provide only the exact code needed at the cursor position
55
- </primary_objectives>
56
-
57
- <strict_requirements>
58
- - Output MUST contain only the NEW code to be inserted at cursor position
59
- - NEVER repeat any code that appears before the cursor position
60
- - DO NOT include any code that appears before the cursor
61
- - DO NOT include explanatory comments or documentation
62
- - DO NOT wrap output in markdown code blocks
63
- - DO NOT include placeholder text or TODO comments
64
- - AVOID generating code beyond the immediate logical completion
65
- </strict_requirements>
66
-
67
- <completion_mode>
68
- Active Mode: ${r}
69
- Specific Instructions: ${{continue:"-- Analyze the code structure and continue writing from the cursor position, maintaining logical flow.",insert:"-- Insert a precise, contextually appropriate code snippet at the cursor position while preserving surrounding code integrity.",complete:"-- Complete the current statement or block with syntactically correct and logically coherent code."}[r]||""}
70
- </completion_mode>
33
+ </task_context>`.trim()},ce=(t,e)=>({system:ve(e),user:be(t,e)});var Me=({textBeforeCursor:t="",textAfterCursor:e="",editorState:{completionMode:o},language:r,...n})=>{let i=`
34
+ Given the ${r||"code"} context:
71
35
 
72
- <code_analysis_steps>
73
- 1. Analyze the code context before and after the cursor
74
- 2. Identify the current scope and available variables/functions
75
- 3. Determine the logical flow and required completion
76
- 4. Remove any duplicate text that appears before cursor
77
- 5. Verify completion starts exactly at cursor position
78
- </code_analysis_steps>
36
+ ${t}<cursor>${e}
79
37
 
80
- <examples>
81
- <example>
82
- Context: "const <cursor>"
83
- CORRECT COMPLETION: "myVariable = 42"
84
- INCORRECT COMPLETION: "const myVariable = 42"
85
- </example>
38
+ CRITICAL RULES:
39
+ 1. NEVER repeat text before <cursor>
40
+ 2. Start EXACTLY at cursor position
41
+ 3. Output ONLY new code
42
+ 4. No explanations/comments
43
+ 5. Do not add unnecessary quotes or backticks around code
44
+ 6. Follow ${o} mode: ${o==="continue"?"continue writing":o==="insert"?"insert exactly missing code between":"complete block"}
45
+ 7. Respect Monaco editor subwordSmart inline suggest mode (MANDATORY)
86
46
 
87
- <example>
88
- Context: "function hello<cursor>"
89
- CORRECT COMPLETION: "(name: string) {\\n return 'Hello ' + name;\\n}"
90
- INCORRECT COMPLETION: "function hello(name: string) {\\n return 'Hello ' + name;\\n}"
91
- </example>
92
-
93
- <example>
94
- Context: "const randomNumber = Math.floor(Math.ran<cursor>00);"
95
- CORRECT COMPLETION: "dom() * 1"
96
- INCORRECT COMPLETION: "Math.random() * 1"
97
- </example>
98
-
99
- <example>
100
- Context: "const result = 'Hello' + ' W<cursor>';"
101
- CORRECT COMPLETION: "orld"
102
- INCORRECT COMPLETION: "orld';"
103
- </example>
104
-
105
- <example>
106
- Context: "function isPalindrome(<cursor>)"
107
- CORRECT COMPLETION: "str) {
108
- return str === str.split('').reverse().join('');
109
- }"
110
- INCORRECT COMPLETION: "(str) {
111
- return str === str.split('').reverse().join('');
112
- }"
113
- </example>
114
- </examples>
115
-
116
- <error_prevention>
117
- - Verify that generated code doesn't introduce syntax errors
118
- - Ensure variable and function references are valid in the current scope
119
- - Check for proper bracket and parenthesis matching
120
- - Maintain consistent indentation with surrounding code
121
- - Respect language-specific type safety requirements
122
- - NEVER duplicate text that appears before cursor
123
- </error_prevention>
124
-
125
- <final_validation>
126
- Before providing the completion:
127
- 1. Confirm the output contains ONLY the new code after cursor position
128
- 2. Double-check no text before cursor is duplicated
129
- 3. Verify it fits seamlessly at the cursor position
130
- 4. Ensure it follows the active completion mode requirements
131
- 5. Check for consistency with existing code style
132
- </final_validation>
133
- </instructions>`.trim();return me(l,t)},Ce=Be;var _=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??J,this.model=o.model??Z,this.validateInputs()}validateInputs(){if(!H.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${M(H)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!V[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${M(V[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},l=this.generatePrompt(n,s),{endpoint:d,requestBody:p,headers:u}=this.prepareRequestDetails(l);try{let m=await this.sendCompletionRequest(d,p,{...u,...i});return this.processCompletionResponse(m)}catch(m){return this.handleCompletionError(m)}}generatePrompt(e,o){let r=Ce(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=ne(this.provider),r,n=oe(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let i=this.model.config(this.apiKey,e);o=i.endpoint??o,r=i.body??{},n={...n,...i.headers}}else r=te(this.model,this.provider,e);return{endpoint:o,requestBody:r,headers:n}}async sendCompletionRequest(e,o,r){return N.POST(e,o,{headers:r})}processCompletionResponse(e){if(typeof this.model=="object"&&"transformResponse"in this.model){let o=this.model.transformResponse(e);return"completion"in o&&A("completion","text","Copilot.options.model.transformResponse"),{completion:o.text??o.completion??null,raw:e}}else return{completion:re(e,this.provider),raw:e}}handleCompletionError(e){return{error:R(e).message,completion:null}}};var D=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],s=i.split(`
47
+ Analyze context, maintain style, ensure syntax correctness. Provide ONLY the completion code without any explanations or comments.`.trim();return ce(i,{textBeforeCursor:t,textAfterCursor:e,editorState:{completionMode:o},language:r,...n})},de=Me;var G=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??Z,this.model=o.model??Q,this.validateInputs();}validateInputs(){if(!U.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${T(U)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!K[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${T(K[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},a=this.generatePrompt(n,s),{endpoint:l,requestBody:m,headers:c}=this.prepareRequestDetails(a);try{let d=await this.sendCompletionRequest(l,m,{...c,...i});return this.processCompletionResponse(d)}catch(d){return this.handleCompletionError(d)}}generatePrompt(e,o){let r=de(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=te(this.model,this.apiKey,this.provider),r,n=re(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let i=this.model.config(this.apiKey,e);o=i.endpoint??o,r=i.body??{},n={...n,...i.headers};}else r=oe(this.model,this.provider,e);return {endpoint:o,requestBody:r,headers:n}}async sendCompletionRequest(e,o,r){return N.POST(e,o,{headers:r})}processCompletionResponse(e){if(typeof this.model=="object"&&"transformResponse"in this.model){let o=this.model.transformResponse(e);return "completion"in o&&L("completion","text","Copilot.options.model.transformResponse"),{completion:o.text??o.completion??null,raw:e}}else return {completion:ne(e,this.provider),raw:e}}handleCompletionError(e){return {error:y(e).message,completion:null}}};var _=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],s=i.split(`
134
48
  `).slice(1,-1).join(`
135
- `);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
49
+ `);r=r.replace(i,s);}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
50
+
51
+ `),this}build(){return this.formattedCompletion}};var B=class{constructor(e,o){this.cursorPos=e,this.mdl=o;}shouldProvideCompletions(){return !pe(this.cursorPos,this.mdl)}};var q=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e);}enqueue(e){let o;return this.size===this.capacity&&(o=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,o}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==void 0)}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.size=0;}getSize(){return this.size}isEmpty(){return this.size===0}isFull(){return this.size===this.capacity}};var g=class g{constructor(){this.cache=new q(g.MAX_CACHE_SIZE);}get(e,o){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,o))}add(e){this.cache.enqueue(e);}clear(){this.cache.clear();}isValidCacheItem(e,o,r){let n=r.getValueInRange(e.range);return h(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:a,endLineNumber:l,endColumn:m}=n,{lineNumber:c,column:d}=o,p=c===s&&d===a;if(s===l)return p||i.startsWith(r)&&c===s&&d>=a-g.LOOK_AROUND&&d<=m+g.LOOK_AROUND;let u=i.startsWith(r)&&c>=s&&c<=l&&(c===s&&d>=a-g.LOOK_AROUND||c===l&&d<=m+g.LOOK_AROUND||c>s&&c<l);return p||u}};g.MAX_CACHE_SIZE=10,g.LOOK_AROUND=10;var k=g;var $=class{constructor(e){this.monaco=e;}computeInsertionRange(e,o,r){if(!o)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let n=w(e,r),i=o[0];if(!n||i===n)return this.calculateRangeWithoutOverlap(e,o);let s=r.getOffsetAt(e),a=h(e,r),l=S(e,r);if(s>=r.getValue().length||!l.length)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let m=this.getSuffixOverlapLength(o,a),c=this.computeMaxOverlapLength(o,l),d=m>0?r.getPositionAt(s-m):e,p=s+c,u=r.getPositionAt(p);return new this.monaco.Range(d.lineNumber,d.column,u.lineNumber,u.column)}calculateRangeWithoutOverlap(e,o){let r=e.lineNumber,n=e.column,i=o.split(`
52
+ `),s=i.length-1,a=r+s,l=s===0?n+i[0].length:i[s].length+1;return new this.monaco.Range(r,n,a,l)}computeMaxOverlapLength(e,o){let r=this.getPrefixOverlapLength(e,o),n=this.getSuffixPrefixOverlapLength(e,o),i=Math.max(r,n);return i===0&&(i=this.getInternalOverlapLength(e,o)),i}getSuffixOverlapLength(e,o){let r=Math.min(e.length,o.length),n=0;for(let i=1;i<=r;i++)e.substring(0,i)===o.slice(-i)&&(n=i);return n}getPrefixOverlapLength(e,o){let r=Math.min(e.length,o.length);for(let n=0;n<r;n++)if(e[n]!==o[n])return n;return r}getSuffixPrefixOverlapLength(e,o){let r=Math.min(e.length,o.length);for(let n=r;n>0;n--)if(e.slice(-n)===o.slice(0,n))return n;return 0}getInternalOverlapLength(e,o){for(let r=1;r<e.length;r++)if(o.startsWith(e.substring(r)))return e.length-r;return 0}};var Ie="application/json",me=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:n}=await N.POST(e,o,{headers:{"Content-Type":Ie},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return {completion:r}},ue=({pos:t,mdl:e,options:o})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:a}=o,l=Ae(t,e),c=!!s?.length?3:2,d=a?Math.floor(a/c):void 0,p=(P,C,V)=>{let b=P(t,e);return C?Y(b,C,V):b},u=(P,C)=>!P||!C?P:P.map(({content:V,...b})=>({...b,content:Y(V,C)})),j=p(h,d,{from:"end"}),E=p(S,d),R=u(s,d);return {filename:r,language:n,technologies:i,relatedFiles:R,textBeforeCursor:j,textAfterCursor:E,cursorPosition:t,editorState:{completionMode:l}}},Ae=(t,e)=>{let o=w(t,e),r=D(t,e);return o?"insert":r.trim()?"complete":"continue"};var ge=t=>_.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),f=t=>({items:t,enableForwardStability:!0,suppressSuggestions:!0});var X={onTyping:300,onIdle:600,onDemand:0},we=t=>({onTyping:F(t,X.onTyping),onIdle:F(t,X.onIdle),onDemand:F(t,X.onDemand)}),H=new k,De=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{let{trigger:a="onIdle",endpoint:l,enableCaching:m=!0,onError:c,requestHandler:d}=s;if(!new B(o,e).shouldProvideCompletions())return f([]);if(m){let p=H.get(o,e).map(u=>({insertText:u.completion,range:u.range}));if(p.length>0)return i(),f(p)}if(r.isCancellationRequested||n)return f([]);try{let u=we(d??me)[a];r.onCancellationRequested(()=>{u.cancel();});let j=ue({pos:o,mdl:e,options:s}),{completion:E}=await u({endpoint:l,body:{completionMetadata:j}});if(E){let R=ge(E),C=new $(t).computeInsertionRange(o,R,e);return m&&H.add({completion:R,range:C,textBeforeCursor:h(o,e)}),i(),f([{insertText:R,range:C}])}}catch(p){if(Se(p))return f([]);c?c(p):y(p);}return f([])},Se=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,Ce=De;var x=new WeakMap,v=null,he=(t,e,o)=>{v&&v.deregister();let r=[],n={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};x.set(e,n),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let i=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(l,m,c,d)=>{let p=x.get(e);if(!(!p||o.trigger==="onDemand"&&!p.isManualTrigger))return Ce({monaco:t,mdl:l,pos:m,token:d,isCompletionAccepted:p.isCompletionAccepted,onShowCompletion:()=>{p.isCompletionVisible=!0,p.isManualTrigger=!1;},options:o})},freeInlineCompletions:()=>{}});r.push(i);let s=e.onKeyDown(l=>{let m=x.get(e);if(!m)return;let c=l.keyCode===t.KeyCode.Tab||l.keyCode===t.KeyCode.RightArrow&&l.metaKey;m.isCompletionVisible&&c?(m.isCompletionAccepted=!0,m.isCompletionVisible=!1):m.isCompletionAccepted=!1;});r.push(s);let a={deregister:()=>{r.forEach(l=>l.dispose()),H.clear(),x.delete(e),v=null;},trigger:()=>Ne(e)};return v=a,a}catch(i){return o.onError?o.onError(i):y(i),{deregister:()=>{r.forEach(s=>s.dispose()),x.delete(e),v=null;},trigger:()=>{}}}},Ne=t=>{let e=x.get(t);if(!e){se("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isManualTrigger=!0,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{});},Fe=(...t)=>(L("registerCopilot","registerCompletion"),he(...t));
136
53
 
137
- `),this}build(){return this.formattedCompletion}};var S=class{constructor(e,o){this.cursorPos=e,this.mdl=o}shouldProvideCompletions(){return!de(this.cursorPos,this.mdl)}};var k=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e)}enqueue(e){let o;return this.size===this.capacity&&(o=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,o}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==void 0)}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.size=0}getSize(){return this.size}isEmpty(){return this.size===0}isFull(){return this.size===this.capacity}};var F=class F{constructor(){this.cache=new k(F.MAX_CACHE_SIZE)}get(e,o){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,o))}add(e){this.cache.enqueue(e)}clear(){this.cache.clear()}isValidCacheItem(e,o,r){let n=r.getValueInRange(e.range);return T(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:l,endColumn:d}=n,{lineNumber:p,column:u}=o,m=p===s&&u===l,c=i.startsWith(r)&&p===s&&u>=l-r.length&&u<=d+r.length;return m||c}};F.MAX_CACHE_SIZE=10;var B=F;var Fe="application/json",ge=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:n}=await N.POST(e,o,{headers:{"Content-Type":Fe},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return{completion:r}},he=({pos:t,mdl:e,options:o})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:l}=o,d=qe(t,e),u=!!s?.length?3:2,m=l?Math.floor(l/u):void 0,c=(g,f,a)=>{let x=g(t,e);return f?K(x,f,a):x},C=(g,f)=>!g||!f?g:g.map(({content:a,...x})=>({...x,content:K(a,f)})),E=c(T,m,{from:"end"}),y=c(pe,m),h=C(s,m);return{filename:r,language:n,technologies:i,relatedFiles:h,textBeforeCursor:E,textAfterCursor:y,cursorPosition:t,editorState:{completionMode:d}}},qe=(t,e)=>{let o=z(t,e),r=w(t,e);return o?"insert":r.trim()?"complete":"continue"};var fe=(t,e,o,r)=>{if(!r)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let n=o.getOffsetAt(e),i=o.getValue().substring(0,n),s=o.getValue().substring(n),l=0,d=0,p=0,u=0,m=r.length,c=i.length,C=s.length;if(n>=o.getValue().length)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(C===0)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let E=Math.min(m,c);for(let a=1;a<=E;a++){let x=r.substring(0,a),Re=i.slice(-a);x===Re&&(u=a)}let y=Math.min(m,C);for(let a=0;a<y&&r[a]===s[a];a++)l++;for(let a=1;a<=y;a++)r.slice(-a)===s.slice(0,a)&&(d=a);if(p=Math.max(l,d),p===0){for(let a=1;a<m;a++)if(s.startsWith(r.substring(a))){p=m-a;break}}let h=u>0?o.getPositionAt(n-u):e,g=n+p,f=o.getPositionAt(g);return new t.Range(h.lineNumber,h.column,f.lineNumber,f.column)},ye=t=>D.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),P=t=>({items:t,enableForwardStability:!0});var Y={onTyping:300,onIdle:600,onDemand:0},He=t=>({onTyping:L(t,Y.onTyping),onIdle:L(t,Y.onIdle),onDemand:L(t,Y.onDemand)}),q=new B,Ve=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{let{trigger:l="onIdle",endpoint:d,enableCaching:p=!0,onError:u,requestHandler:m}=s;if(!new S(o,e).shouldProvideCompletions())return P([]);if(p){let c=q.get(o,e).map(C=>({insertText:C.completion,range:C.range}));if(c.length>0)return i(),P(c)}if(r.isCancellationRequested||n)return P([]);try{let C=He(m??ge)[l];r.onCancellationRequested(()=>{C.cancel()});let E=he({pos:o,mdl:e,options:s}),{completion:y}=await C({endpoint:d,body:{completionMetadata:E}});if(y){let h=ye(y),g=fe(t,o,e,h);return p&&q.add({completion:h,range:g,textBeforeCursor:T(o,e)}),i(),P([{insertText:h,range:g}])}}catch(c){if(je(c))return P([]);u?u(c):R(c)}return P([])},je=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,Pe=Ve;var O=new WeakMap,b=null,G=(t,e,o)=>{b&&b.deregister();let r=[],n={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};O.set(e,n),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let i=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(d,p,u,m)=>{let c=O.get(e);if(!(!c||o.trigger==="onDemand"&&!c.isManualTrigger))return Pe({monaco:t,mdl:d,pos:p,token:m,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0,c.isManualTrigger=!1},options:o})},freeInlineCompletions:()=>{}});r.push(i);let s=e.onKeyDown(d=>{let p=O.get(e);if(!p)return;let u=d.keyCode===t.KeyCode.Tab||d.keyCode===t.KeyCode.RightArrow&&d.metaKey;p.isCompletionVisible&&u?(p.isCompletionAccepted=!0,p.isCompletionVisible=!1):p.isCompletionAccepted=!1});r.push(s);let l={deregister:()=>{r.forEach(d=>d.dispose()),q.clear(),O.delete(e),b=null},trigger:()=>Ue(e)};return b=l,l}catch(i){return o.onError?o.onError(i):R(i),{deregister:()=>{r.forEach(s=>s.dispose()),O.delete(e),b=null},trigger:()=>{}}}},Ue=t=>{let e=O.get(t);if(!e){ae("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isManualTrigger=!0,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{})},xe=(...t)=>(A("registerCopilot","registerCompletion"),G(...t));0&&(module.exports={Copilot,registerCompletion,registerCopilot});
54
+ exports.Copilot = G;
55
+ exports.registerCompletion = he;
56
+ exports.registerCopilot = Fe;
package/build/index.mjs CHANGED
@@ -1,16 +1,16 @@
1
- var q=["groq","openai","anthropic"],Y={"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-20241022","claude-3-haiku":"claude-3-haiku-20240307","claude-3-5-haiku":"claude-3-5-haiku-20241022","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-haiku","claude-3-5-haiku"]},G="anthropic",X="claude-3-5-haiku",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"},v=.1;var Z={"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-haiku":4096};var xe={createRequestBody:(t,e)=>{let r=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:V(t),temperature:v,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},Re={createRequestBody:(t,e)=>({model:V(t),temperature:v,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?t.choices[0].message.content:null},Te={createRequestBody:(t,e)=>({model:V(t),temperature:v,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:Oe(t)}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>{if(!t.content||!Array.isArray(t.content)||!t.content.length)return null;let e=t.content[0];return!e||typeof e!="object"?null:"text"in e&&typeof e.text=="string"?e.text:null}},H={openai:xe,groq:Re,anthropic:Te},Q=(t,e,o)=>H[e].createRequestBody(t,o),ee=(t,e)=>H[e].createHeaders(t),te=(t,e)=>H[e].parseCompletion(t),V=t=>Y[t],oe=t=>J[t],Oe=t=>Z[t]||4096;var re="\x1B[91m",ne="\x1B[93m",I="\x1B[0m",j="\x1B[1m",R=t=>{let e,o;t instanceof Error?(e=t.message,o=t.stack):typeof t=="string"?e=t:e="An unknown error occurred";let r=`${re}${j}[MONACOPILOT ERROR] ${e}${I}`;return console.error(o?`${r}
2
- ${re}Stack trace:${I}
3
- ${o}`:r),{message:e,stack:o}},ie=t=>{console.warn(`${ne}${j}[MONACOPILOT WARN] ${t}${I}`)};var A=(t,e,o)=>console.warn(`${ne}${j}[MONACOPILOT DEPRECATED] "${t}" is deprecated${o?` in ${o}`:""}. Please use "${e}" instead. It will be removed in a future version.${I}`);var L=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((s,l)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=l,o=setTimeout(()=>{s(t(...i)),r=null},e)});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},n},M=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var U=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1];var w=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),se=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),T=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),ae=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())}),W=(t,e,o={})=>{if(e<=0)return"";let r=t.split(`
4
- `),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(l=>l==="")?`
1
+ var U=["groq","openai","anthropic","google"],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-20241022","claude-3-haiku":"claude-3-haiku-20240307","claude-3-5-haiku":"claude-3-5-haiku-20241022","o1-mini":"o1-mini","gemini-1.5-flash-8b":"gemini-1.5-flash-8b","gemini-1.5-flash":"gemini-1.5-flash","gemini-1.5-pro":"gemini-1.5-pro"},K={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini","o1-mini"],anthropic:["claude-3-5-sonnet","claude-3-haiku","claude-3-5-haiku"],google:["gemini-1.5-flash-8b","gemini-1.5-pro","gemini-1.5-flash"]},Z="anthropic",Q="claude-3-5-haiku",O={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages",google:"https://generativelanguage.googleapis.com/v1beta/models"},M=.1;var ee={"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-haiku":4096};var fe={createEndpoint:()=>O.openai,createRequestBody:(t,e)=>{let o=t==="o1-mini";return {model:A(t),...!o&&{temperature:M},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?t.choices[0].message.content:null},Pe={createEndpoint:()=>O.groq,createRequestBody:(t,e)=>({model:A(t),temperature:M,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?t.choices[0].message.content:null},ye={createEndpoint:()=>O.anthropic,createRequestBody:(t,e)=>({model:A(t),temperature:M,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:ee[t]}),createHeaders:t=>({"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"}),parseCompletion:t=>{if(!t.content||!Array.isArray(t.content)||!t.content.length)return null;let e=t.content[0];return !e||typeof e!="object"?null:"text"in e&&typeof e.text=="string"?e.text:null}},xe={createEndpoint:(t,e)=>`${O.google}/${t}:generateContent?key=${e}`,createRequestBody:(t,e)=>({model:A(t),system_instruction:{parts:{text:e.system}},contents:[{parts:{text:e.user}}]}),createHeaders:()=>({"Content-Type":"application/json"}),parseCompletion:t=>{if(!t.candidates?.length||!t.candidates[0]?.content||!t.candidates[0].content?.parts?.length)return null;let e=t.candidates[0].content;return "text"in e.parts[0]&&typeof e.parts[0].text=="string"?e.parts[0].text:null}},I={openai:fe,groq:Pe,anthropic:ye,google:xe},te=(t,e,o)=>I[o].createEndpoint(t,e),oe=(t,e,o)=>I[e].createRequestBody(t,o),re=(t,e)=>I[e].createHeaders(t),ne=(t,e)=>I[e].parseCompletion(t),A=t=>J[t];var Re="\x1B[91m",ie="\x1B[93m",W="\x1B[0m",z="\x1B[1m",y=t=>{let e;t instanceof Error?e=t.message:typeof t=="string"?e=t:e="An unknown error occurred";let o=`${Re}${z}[MONACOPILOT ERROR] ${e}${W}`;return console.error(o),{message:e}},se=t=>{console.warn(`${ie}${z}[MONACOPILOT WARN] ${t}${W}`);};var L=(t,e,o)=>console.warn(`${ie}${z}[MONACOPILOT DEPRECATED] "${t}" is deprecated${o?` in ${o}`:""}. Please use "${e}" instead. It will be removed in a future version.${W}`);var T=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`,Y=(t,e,o={})=>{if(e<=0)return "";let r=t.split(`
2
+ `),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(a=>a==="")?`
5
3
  `.repeat(e):s.join(`
6
4
  `)}let i=r.slice(0,e);return i.every(s=>s==="")?`
7
5
  `.repeat(e):i.join(`
8
- `)};var le=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(`${i.statusText||o.fallbackError||"Network error"}`);return i.json()},Ee=(t,e)=>le(t,"GET",e),Me=(t,e,o)=>le(t,"POST",{...o,body:e}),N={GET:Ee,POST:Me};var pe=(t,e)=>{let o=w(t,e).trim(),r=se(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var be=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:n}=t,i=M([n,...e].filter(l=>typeof l=="string"&&!!l));return[`You are an expert ${i?`${i} `:""}developer assistant specialized in precise code completion and generation.`,`Your primary task is to provide accurate, context-aware code completions that seamlessly integrate with existing codebases${o?` in '${o}'`:""}.`,`You must:
9
- - Generate only the exact code required
10
- - Maintain strict adherence to provided instructions
11
- - Follow established code patterns and conventions
12
- - Consider the full context before generating code`,r?.length?"Analyze and incorporate context from all provided related files to ensure consistent and appropriate code generation.":"",n?`Apply ${n}-specific best practices, idioms, and syntax conventions in all generated code.`:""].filter(Boolean).join(`
13
- `)},ve=t=>t?.length?t.map(({path:e,content:o})=>`
6
+ `)};var w=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],D=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),ae=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),h=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),S=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var le=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){let s=`
7
+ `+(JSON.stringify(await i.json(),null,2)||"");throw new Error(`${i.statusText||o.fallbackError||"Network error"}${s}`)}return i.json()},Oe=(t,e)=>le(t,"GET",e),Te=(t,e,o)=>le(t,"POST",{...o,body:e}),N={GET:Oe,POST:Te};var pe=(t,e)=>{let o=D(t,e).trim(),r=ae(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var F=(t,e)=>{let o=null,r=null,n=(...i)=>new Promise((s,a)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=a,o=setTimeout(()=>{s(t(...i)),r=null;},e);});return n.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null);},n};var ve=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:n}=t,i=T([n,...e].filter(a=>typeof a=="string"&&!!a));return [`You are an expert ${i?`${i} `:""}developer assistant specialized in precise code completion.`,`Your primary task is to provide accurate, context-aware code completions that seamlessly integrate with existing codebases${o?` in '${o}'`:""}.`,`You must:
8
+ - Generate only the exact code required.
9
+ - Maintain strict adherence to provided instructions.
10
+ - Follow established code patterns and conventions.
11
+ - Consider the full context before generating code.`,r?.length?"Analyze and incorporate context from all provided related files to ensure consistent and appropriate code completion.":"",n?`Apply ${n}-specific best practices, idioms, and syntax conventions in all generated code.`:""].filter(Boolean).join(`
12
+
13
+ `)},Ee=t=>t?.length?t.map(({path:e,content:o})=>`
14
14
  <related_file>
15
15
  <path>${e}</path>
16
16
  <content_context>
@@ -20,118 +20,33 @@ ${o}
20
20
  </content_context>
21
21
  </related_file>`.trim()).join(`
22
22
 
23
- `):"",Ie=(t="",e)=>{let{relatedFiles:o}=e;return`
23
+ `):"",be=(t="",e)=>{let{relatedFiles:o}=e;return `
24
24
  <task_context>
25
25
  <primary_instructions>
26
26
  ${t.trim()}
27
- </primary_instructions>
28
- ${o?.length?`
27
+ </primary_instructions>${o?.length?`
29
28
  <reference_files>
30
- ${ve(o)}
29
+ ${Ee(o)}
31
30
  </reference_files>`:""}
32
- </task_context>`.trim()},ce=(t,e)=>({system:be(e),user:Ie(t,e)});var de="<cursor>",Ae=t=>{let{textBeforeCursor:e="",textAfterCursor:o="",editorState:{completionMode:r},language:n}=t,i=`<code_file>
33
- ${e}${de}${o}
34
- </code_file>`,l=`
35
- <instructions>
36
- <context>
37
- Below is a ${n||"code"} file with the token '${de}' marking the exact cursor position where code completion is needed.
31
+ </task_context>`.trim()},ce=(t,e)=>({system:ve(e),user:be(t,e)});var Me=({textBeforeCursor:t="",textAfterCursor:e="",editorState:{completionMode:o},language:r,...n})=>{let i=`
32
+ Given the ${r||"code"} context:
38
33
 
39
- ${i}
40
- </context>
34
+ ${t}<cursor>${e}
41
35
 
42
- <critical_rules>
43
- 1. NEVER REPEAT ANY TEXT THAT APPEARS BEFORE THE CURSOR
44
- 2. Start your completion EXACTLY from the cursor position
45
- 3. If user types 'const ' and cursor is after it, DO NOT include 'const ' in your completion
46
- 4. ONLY provide the remaining part of the code that should appear after the cursor
47
- 5. Violation of these rules will cause code duplication and syntax errors
48
- </critical_rules>
36
+ CRITICAL RULES:
37
+ 1. NEVER repeat text before <cursor>
38
+ 2. Start EXACTLY at cursor position
39
+ 3. Output ONLY new code
40
+ 4. No explanations/comments
41
+ 5. Do not add unnecessary quotes or backticks around code
42
+ 6. Follow ${o} mode: ${o==="continue"?"continue writing":o==="insert"?"insert exactly missing code between":"complete block"}
43
+ 7. Respect Monaco editor subwordSmart inline suggest mode (MANDATORY)
49
44
 
50
- <primary_objectives>
51
- 1. Generate code that is syntactically correct and follows ${n||"the language"}'s best practices
52
- 2. Ensure seamless integration with existing code structure
53
- 3. Maintain consistent naming conventions and coding style
54
- 4. Provide only the exact code needed at the cursor position
55
- </primary_objectives>
56
-
57
- <strict_requirements>
58
- - Output MUST contain only the NEW code to be inserted at cursor position
59
- - NEVER repeat any code that appears before the cursor position
60
- - DO NOT include any code that appears before the cursor
61
- - DO NOT include explanatory comments or documentation
62
- - DO NOT wrap output in markdown code blocks
63
- - DO NOT include placeholder text or TODO comments
64
- - AVOID generating code beyond the immediate logical completion
65
- </strict_requirements>
66
-
67
- <completion_mode>
68
- Active Mode: ${r}
69
- Specific Instructions: ${{continue:"-- Analyze the code structure and continue writing from the cursor position, maintaining logical flow.",insert:"-- Insert a precise, contextually appropriate code snippet at the cursor position while preserving surrounding code integrity.",complete:"-- Complete the current statement or block with syntactically correct and logically coherent code."}[r]||""}
70
- </completion_mode>
71
-
72
- <code_analysis_steps>
73
- 1. Analyze the code context before and after the cursor
74
- 2. Identify the current scope and available variables/functions
75
- 3. Determine the logical flow and required completion
76
- 4. Remove any duplicate text that appears before cursor
77
- 5. Verify completion starts exactly at cursor position
78
- </code_analysis_steps>
79
-
80
- <examples>
81
- <example>
82
- Context: "const <cursor>"
83
- CORRECT COMPLETION: "myVariable = 42"
84
- INCORRECT COMPLETION: "const myVariable = 42"
85
- </example>
86
-
87
- <example>
88
- Context: "function hello<cursor>"
89
- CORRECT COMPLETION: "(name: string) {\\n return 'Hello ' + name;\\n}"
90
- INCORRECT COMPLETION: "function hello(name: string) {\\n return 'Hello ' + name;\\n}"
91
- </example>
92
-
93
- <example>
94
- Context: "const randomNumber = Math.floor(Math.ran<cursor>00);"
95
- CORRECT COMPLETION: "dom() * 1"
96
- INCORRECT COMPLETION: "Math.random() * 1"
97
- </example>
98
-
99
- <example>
100
- Context: "const result = 'Hello' + ' W<cursor>';"
101
- CORRECT COMPLETION: "orld"
102
- INCORRECT COMPLETION: "orld';"
103
- </example>
104
-
105
- <example>
106
- Context: "function isPalindrome(<cursor>)"
107
- CORRECT COMPLETION: "str) {
108
- return str === str.split('').reverse().join('');
109
- }"
110
- INCORRECT COMPLETION: "(str) {
111
- return str === str.split('').reverse().join('');
112
- }"
113
- </example>
114
- </examples>
115
-
116
- <error_prevention>
117
- - Verify that generated code doesn't introduce syntax errors
118
- - Ensure variable and function references are valid in the current scope
119
- - Check for proper bracket and parenthesis matching
120
- - Maintain consistent indentation with surrounding code
121
- - Respect language-specific type safety requirements
122
- - NEVER duplicate text that appears before cursor
123
- </error_prevention>
124
-
125
- <final_validation>
126
- Before providing the completion:
127
- 1. Confirm the output contains ONLY the new code after cursor position
128
- 2. Double-check no text before cursor is duplicated
129
- 3. Verify it fits seamlessly at the cursor position
130
- 4. Ensure it follows the active completion mode requirements
131
- 5. Check for consistency with existing code style
132
- </final_validation>
133
- </instructions>`.trim();return ce(l,t)},me=Ae;var z=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??X,this.validateInputs()}validateInputs(){if(!q.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${M(q)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!$[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${M($[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},l=this.generatePrompt(n,s),{endpoint:d,requestBody:p,headers:u}=this.prepareRequestDetails(l);try{let m=await this.sendCompletionRequest(d,p,{...u,...i});return this.processCompletionResponse(m)}catch(m){return this.handleCompletionError(m)}}generatePrompt(e,o){let r=me(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=oe(this.provider),r,n=ee(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let i=this.model.config(this.apiKey,e);o=i.endpoint??o,r=i.body??{},n={...n,...i.headers}}else r=Q(this.model,this.provider,e);return{endpoint:o,requestBody:r,headers:n}}async sendCompletionRequest(e,o,r){return N.POST(e,o,{headers:r})}processCompletionResponse(e){if(typeof this.model=="object"&&"transformResponse"in this.model){let o=this.model.transformResponse(e);return"completion"in o&&A("completion","text","Copilot.options.model.transformResponse"),{completion:o.text??o.completion??null,raw:e}}else return{completion:te(e,this.provider),raw:e}}handleCompletionError(e){return{error:R(e).message,completion:null}}};var _=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],s=i.split(`
45
+ Analyze context, maintain style, ensure syntax correctness. Provide ONLY the completion code without any explanations or comments.`.trim();return ce(i,{textBeforeCursor:t,textAfterCursor:e,editorState:{completionMode:o},language:r,...n})},de=Me;var G=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??Z,this.model=o.model??Q,this.validateInputs();}validateInputs(){if(!U.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${T(U)}. For custom models, provider specification is not needed.`);if(typeof this.model=="string"&&!K[this.provider].includes(this.model))throw new Error(`Model "${this.model}" is not supported by the "${this.provider}" provider. Supported models: ${T(K[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:n}=o,{headers:i={},customPrompt:s}=r??{},a=this.generatePrompt(n,s),{endpoint:l,requestBody:m,headers:c}=this.prepareRequestDetails(a);try{let d=await this.sendCompletionRequest(l,m,{...c,...i});return this.processCompletionResponse(d)}catch(d){return this.handleCompletionError(d)}}generatePrompt(e,o){let r=de(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=te(this.model,this.apiKey,this.provider),r,n=re(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let i=this.model.config(this.apiKey,e);o=i.endpoint??o,r=i.body??{},n={...n,...i.headers};}else r=oe(this.model,this.provider,e);return {endpoint:o,requestBody:r,headers:n}}async sendCompletionRequest(e,o,r){return N.POST(e,o,{headers:r})}processCompletionResponse(e){if(typeof this.model=="object"&&"transformResponse"in this.model){let o=this.model.transformResponse(e);return "completion"in o&&L("completion","text","Copilot.options.model.transformResponse"),{completion:o.text??o.completion??null,raw:e}}else return {completion:ne(e,this.provider),raw:e}}handleCompletionError(e){return {error:y(e).message,completion:null}}};var _=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],s=i.split(`
134
46
  `).slice(1,-1).join(`
135
- `);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
47
+ `);r=r.replace(i,s);}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
48
+
49
+ `),this}build(){return this.formattedCompletion}};var B=class{constructor(e,o){this.cursorPos=e,this.mdl=o;}shouldProvideCompletions(){return !pe(this.cursorPos,this.mdl)}};var q=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e);}enqueue(e){let o;return this.size===this.capacity&&(o=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,o}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==void 0)}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.size=0;}getSize(){return this.size}isEmpty(){return this.size===0}isFull(){return this.size===this.capacity}};var g=class g{constructor(){this.cache=new q(g.MAX_CACHE_SIZE);}get(e,o){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,o))}add(e){this.cache.enqueue(e);}clear(){this.cache.clear();}isValidCacheItem(e,o,r){let n=r.getValueInRange(e.range);return h(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:a,endLineNumber:l,endColumn:m}=n,{lineNumber:c,column:d}=o,p=c===s&&d===a;if(s===l)return p||i.startsWith(r)&&c===s&&d>=a-g.LOOK_AROUND&&d<=m+g.LOOK_AROUND;let u=i.startsWith(r)&&c>=s&&c<=l&&(c===s&&d>=a-g.LOOK_AROUND||c===l&&d<=m+g.LOOK_AROUND||c>s&&c<l);return p||u}};g.MAX_CACHE_SIZE=10,g.LOOK_AROUND=10;var k=g;var $=class{constructor(e){this.monaco=e;}computeInsertionRange(e,o,r){if(!o)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let n=w(e,r),i=o[0];if(!n||i===n)return this.calculateRangeWithoutOverlap(e,o);let s=r.getOffsetAt(e),a=h(e,r),l=S(e,r);if(s>=r.getValue().length||!l.length)return new this.monaco.Range(e.lineNumber,e.column,e.lineNumber,e.column);let m=this.getSuffixOverlapLength(o,a),c=this.computeMaxOverlapLength(o,l),d=m>0?r.getPositionAt(s-m):e,p=s+c,u=r.getPositionAt(p);return new this.monaco.Range(d.lineNumber,d.column,u.lineNumber,u.column)}calculateRangeWithoutOverlap(e,o){let r=e.lineNumber,n=e.column,i=o.split(`
50
+ `),s=i.length-1,a=r+s,l=s===0?n+i[0].length:i[s].length+1;return new this.monaco.Range(r,n,a,l)}computeMaxOverlapLength(e,o){let r=this.getPrefixOverlapLength(e,o),n=this.getSuffixPrefixOverlapLength(e,o),i=Math.max(r,n);return i===0&&(i=this.getInternalOverlapLength(e,o)),i}getSuffixOverlapLength(e,o){let r=Math.min(e.length,o.length),n=0;for(let i=1;i<=r;i++)e.substring(0,i)===o.slice(-i)&&(n=i);return n}getPrefixOverlapLength(e,o){let r=Math.min(e.length,o.length);for(let n=0;n<r;n++)if(e[n]!==o[n])return n;return r}getSuffixPrefixOverlapLength(e,o){let r=Math.min(e.length,o.length);for(let n=r;n>0;n--)if(e.slice(-n)===o.slice(0,n))return n;return 0}getInternalOverlapLength(e,o){for(let r=1;r<e.length;r++)if(o.startsWith(e.substring(r)))return e.length-r;return 0}};var Ie="application/json",me=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:n}=await N.POST(e,o,{headers:{"Content-Type":Ie},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return {completion:r}},ue=({pos:t,mdl:e,options:o})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:a}=o,l=Ae(t,e),c=!!s?.length?3:2,d=a?Math.floor(a/c):void 0,p=(P,C,V)=>{let b=P(t,e);return C?Y(b,C,V):b},u=(P,C)=>!P||!C?P:P.map(({content:V,...b})=>({...b,content:Y(V,C)})),j=p(h,d,{from:"end"}),E=p(S,d),R=u(s,d);return {filename:r,language:n,technologies:i,relatedFiles:R,textBeforeCursor:j,textAfterCursor:E,cursorPosition:t,editorState:{completionMode:l}}},Ae=(t,e)=>{let o=w(t,e),r=D(t,e);return o?"insert":r.trim()?"complete":"continue"};var ge=t=>_.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),f=t=>({items:t,enableForwardStability:!0,suppressSuggestions:!0});var X={onTyping:300,onIdle:600,onDemand:0},we=t=>({onTyping:F(t,X.onTyping),onIdle:F(t,X.onIdle),onDemand:F(t,X.onDemand)}),H=new k,De=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{let{trigger:a="onIdle",endpoint:l,enableCaching:m=!0,onError:c,requestHandler:d}=s;if(!new B(o,e).shouldProvideCompletions())return f([]);if(m){let p=H.get(o,e).map(u=>({insertText:u.completion,range:u.range}));if(p.length>0)return i(),f(p)}if(r.isCancellationRequested||n)return f([]);try{let u=we(d??me)[a];r.onCancellationRequested(()=>{u.cancel();});let j=ue({pos:o,mdl:e,options:s}),{completion:E}=await u({endpoint:l,body:{completionMetadata:j}});if(E){let R=ge(E),C=new $(t).computeInsertionRange(o,R,e);return m&&H.add({completion:R,range:C,textBeforeCursor:h(o,e)}),i(),f([{insertText:R,range:C}])}}catch(p){if(Se(p))return f([]);c?c(p):y(p);}return f([])},Se=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,Ce=De;var x=new WeakMap,v=null,he=(t,e,o)=>{v&&v.deregister();let r=[],n={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};x.set(e,n),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let i=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(l,m,c,d)=>{let p=x.get(e);if(!(!p||o.trigger==="onDemand"&&!p.isManualTrigger))return Ce({monaco:t,mdl:l,pos:m,token:d,isCompletionAccepted:p.isCompletionAccepted,onShowCompletion:()=>{p.isCompletionVisible=!0,p.isManualTrigger=!1;},options:o})},freeInlineCompletions:()=>{}});r.push(i);let s=e.onKeyDown(l=>{let m=x.get(e);if(!m)return;let c=l.keyCode===t.KeyCode.Tab||l.keyCode===t.KeyCode.RightArrow&&l.metaKey;m.isCompletionVisible&&c?(m.isCompletionAccepted=!0,m.isCompletionVisible=!1):m.isCompletionAccepted=!1;});r.push(s);let a={deregister:()=>{r.forEach(l=>l.dispose()),H.clear(),x.delete(e),v=null;},trigger:()=>Ne(e)};return v=a,a}catch(i){return o.onError?o.onError(i):y(i),{deregister:()=>{r.forEach(s=>s.dispose()),x.delete(e),v=null;},trigger:()=>{}}}},Ne=t=>{let e=x.get(t);if(!e){se("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isManualTrigger=!0,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{});},Fe=(...t)=>(L("registerCopilot","registerCompletion"),he(...t));
136
51
 
137
- `),this}build(){return this.formattedCompletion}};var D=class{constructor(e,o){this.cursorPos=e,this.mdl=o}shouldProvideCompletions(){return!pe(this.cursorPos,this.mdl)}};var S=class{constructor(e){this.capacity=e;this.head=0;this.tail=0;this.size=0;this.buffer=new Array(e)}enqueue(e){let o;return this.size===this.capacity&&(o=this.dequeue()),this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.size++,o}dequeue(){if(this.size===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.size--,e}getAll(){return this.buffer.filter(e=>e!==void 0)}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.size=0}getSize(){return this.size}isEmpty(){return this.size===0}isFull(){return this.size===this.capacity}};var B=class B{constructor(){this.cache=new S(B.MAX_CACHE_SIZE)}get(e,o){return this.cache.getAll().filter(r=>this.isValidCacheItem(r,e,o))}add(e){this.cache.enqueue(e)}clear(){this.cache.clear()}isValidCacheItem(e,o,r){let n=r.getValueInRange(e.range);return T(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:l,endColumn:d}=n,{lineNumber:p,column:u}=o,m=p===s&&u===l,c=i.startsWith(r)&&p===s&&u>=l-r.length&&u<=d+r.length;return m||c}};B.MAX_CACHE_SIZE=10;var k=B;var Le="application/json",ue=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:n}=await N.POST(e,o,{headers:{"Content-Type":Le},fallbackError:"Error while fetching completion item"});if(n)throw new Error(n);return{completion:r}},Ce=({pos:t,mdl:e,options:o})=>{let{filename:r,language:n,technologies:i,relatedFiles:s,maxContextLines:l}=o,d=we(t,e),u=!!s?.length?3:2,m=l?Math.floor(l/u):void 0,c=(g,f,a)=>{let x=g(t,e);return f?W(x,f,a):x},C=(g,f)=>!g||!f?g:g.map(({content:a,...x})=>({...x,content:W(a,f)})),E=c(T,m,{from:"end"}),y=c(ae,m),h=C(s,m);return{filename:r,language:n,technologies:i,relatedFiles:h,textBeforeCursor:E,textAfterCursor:y,cursorPosition:t,editorState:{completionMode:d}}},we=(t,e)=>{let o=U(t,e),r=w(t,e);return o?"insert":r.trim()?"complete":"continue"};var ge=(t,e,o,r)=>{if(!r)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let n=o.getOffsetAt(e),i=o.getValue().substring(0,n),s=o.getValue().substring(n),l=0,d=0,p=0,u=0,m=r.length,c=i.length,C=s.length;if(n>=o.getValue().length)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(C===0)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let E=Math.min(m,c);for(let a=1;a<=E;a++){let x=r.substring(0,a),Pe=i.slice(-a);x===Pe&&(u=a)}let y=Math.min(m,C);for(let a=0;a<y&&r[a]===s[a];a++)l++;for(let a=1;a<=y;a++)r.slice(-a)===s.slice(0,a)&&(d=a);if(p=Math.max(l,d),p===0){for(let a=1;a<m;a++)if(s.startsWith(r.substring(a))){p=m-a;break}}let h=u>0?o.getPositionAt(n-u):e,g=n+p,f=o.getPositionAt(g);return new t.Range(h.lineNumber,h.column,f.lineNumber,f.column)},he=t=>_.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),P=t=>({items:t,enableForwardStability:!0});var K={onTyping:300,onIdle:600,onDemand:0},_e=t=>({onTyping:L(t,K.onTyping),onIdle:L(t,K.onIdle),onDemand:L(t,K.onDemand)}),F=new k,De=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{let{trigger:l="onIdle",endpoint:d,enableCaching:p=!0,onError:u,requestHandler:m}=s;if(!new D(o,e).shouldProvideCompletions())return P([]);if(p){let c=F.get(o,e).map(C=>({insertText:C.completion,range:C.range}));if(c.length>0)return i(),P(c)}if(r.isCancellationRequested||n)return P([]);try{let C=_e(m??ue)[l];r.onCancellationRequested(()=>{C.cancel()});let E=Ce({pos:o,mdl:e,options:s}),{completion:y}=await C({endpoint:d,body:{completionMetadata:E}});if(y){let h=he(y),g=ge(t,o,e,h);return p&&F.add({completion:h,range:g,textBeforeCursor:T(o,e)}),i(),P([{insertText:h,range:g}])}}catch(c){if(Se(c))return P([]);u?u(c):R(c)}return P([])},Se=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,fe=De;var O=new WeakMap,b=null,ye=(t,e,o)=>{b&&b.deregister();let r=[],n={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};O.set(e,n),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let i=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(d,p,u,m)=>{let c=O.get(e);if(!(!c||o.trigger==="onDemand"&&!c.isManualTrigger))return fe({monaco:t,mdl:d,pos:p,token:m,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0,c.isManualTrigger=!1},options:o})},freeInlineCompletions:()=>{}});r.push(i);let s=e.onKeyDown(d=>{let p=O.get(e);if(!p)return;let u=d.keyCode===t.KeyCode.Tab||d.keyCode===t.KeyCode.RightArrow&&d.metaKey;p.isCompletionVisible&&u?(p.isCompletionAccepted=!0,p.isCompletionVisible=!1):p.isCompletionAccepted=!1});r.push(s);let l={deregister:()=>{r.forEach(d=>d.dispose()),F.clear(),O.delete(e),b=null},trigger:()=>ke(e)};return b=l,l}catch(i){return o.onError?o.onError(i):R(i),{deregister:()=>{r.forEach(s=>s.dispose()),O.delete(e),b=null},trigger:()=>{}}}},ke=t=>{let e=O.get(t);if(!e){ie("Completion is not registered. Use `registerCompletion` to register completion first.");return}e.isManualTrigger=!0,t.trigger("keyboard","editor.action.inlineSuggest.trigger",{})},Be=(...t)=>(A("registerCopilot","registerCompletion"),ye(...t));export{z as Copilot,ye as registerCompletion,Be as registerCopilot};
52
+ export { G as Copilot, he as registerCompletion, Fe as registerCopilot };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monacopilot",
3
- "version": "0.14.2",
3
+ "version": "0.15.1",
4
4
  "description": "AI auto-completion plugin for Monaco Editor",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",
@@ -25,6 +25,7 @@
25
25
  "@anthropic-ai/sdk": "^0.27.3",
26
26
  "@commitlint/cli": "^19.5.0",
27
27
  "@commitlint/config-conventional": "^19.5.0",
28
+ "@google/generative-ai": "^0.21.0",
28
29
  "@ianvs/prettier-plugin-sort-imports": "^4.2.1",
29
30
  "@release-it/conventional-changelog": "^8.0.2",
30
31
  "@typescript-eslint/eslint-plugin": "^7.3.1",
@@ -60,5 +61,6 @@
60
61
  }
61
62
  ],
62
63
  "license": "MIT",
63
- "author": "Arshad Yaseen <m@arshadyaseen.com> (https://arshadyaseen.com)"
64
+ "author": "Arshad Yaseen <m@arshadyaseen.com> (https://arshadyaseen.com)",
65
+ "dependencies": {}
64
66
  }