monacopilot 0.13.2 → 0.14.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 +16 -19
- package/build/index.d.mts +2 -2
- package/build/index.d.ts +2 -2
- package/build/index.js +73 -38
- package/build/index.mjs +73 -38
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -72,9 +72,9 @@ import {Copilot} from 'monacopilot';
|
|
|
72
72
|
|
|
73
73
|
const app = express();
|
|
74
74
|
const port = process.env.PORT || 3000;
|
|
75
|
-
const copilot = new Copilot(process.env.
|
|
76
|
-
provider: '
|
|
77
|
-
model: '
|
|
75
|
+
const copilot = new Copilot(process.env.ANTHROPIC_API_KEY!, {
|
|
76
|
+
provider: 'anthropic',
|
|
77
|
+
model: 'claude-3-5-haiku',
|
|
78
78
|
});
|
|
79
79
|
|
|
80
80
|
app.use(express.json());
|
|
@@ -87,7 +87,7 @@ app.post('/complete', async (req, res) => {
|
|
|
87
87
|
// Process raw LLM response if needed
|
|
88
88
|
// `raw` can be undefined if an error occurred, which happens when `error` is present
|
|
89
89
|
if (raw) {
|
|
90
|
-
calculateCost(raw.usage.
|
|
90
|
+
calculateCost(raw.usage.input_tokens);
|
|
91
91
|
}
|
|
92
92
|
|
|
93
93
|
// Handle errors if present
|
|
@@ -145,9 +145,6 @@ registerCompletion(monaco, editor, {
|
|
|
145
145
|
endpoint: 'https://api.example.com/complete',
|
|
146
146
|
// The language of the editor.
|
|
147
147
|
language: 'javascript',
|
|
148
|
-
// If you are using Groq as your provider, it's recommended to set `maxContextLines` to `60` or less.
|
|
149
|
-
// This is because Groq has low rate limits and doesn't offer pay-as-you-go pricing.
|
|
150
|
-
maxContextLines: 60,
|
|
151
148
|
});
|
|
152
149
|
```
|
|
153
150
|
|
|
@@ -168,11 +165,11 @@ registerCompletion(monaco, editor, {
|
|
|
168
165
|
});
|
|
169
166
|
```
|
|
170
167
|
|
|
171
|
-
| Trigger | Description | Notes
|
|
172
|
-
| -------------------- | --------------------------------------------------- |
|
|
173
|
-
| `'onIdle'` (default) | Provides completions after a brief pause in typing. | This approach is less resource-intensive, as it only initiates a request when the editor is idle.
|
|
174
|
-
| `'onTyping'` | Provides completions in real-time as you type. | Best suited for models with low response latency, such as Groq models. This trigger mode initiates additional background requests to deliver real-time suggestions, a method known as predictive caching. |
|
|
175
|
-
| `'onDemand'` | Does not provide completions automatically. | Completions are triggered manually using the `trigger` function from the `registerCompletion` return. This allows for precise control over when completions are provided.
|
|
168
|
+
| Trigger | Description | Notes |
|
|
169
|
+
| -------------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
170
|
+
| `'onIdle'` (default) | Provides completions after a brief pause in typing. | This approach is less resource-intensive, as it only initiates a request when the editor is idle. |
|
|
171
|
+
| `'onTyping'` | Provides completions in real-time as you type. | Best suited for models with low response latency, such as Groq models or Claude 3-5 Haiku. This trigger mode initiates additional background requests to deliver real-time suggestions, a method known as predictive caching. |
|
|
172
|
+
| `'onDemand'` | Does not provide completions automatically. | Completions are triggered manually using the `trigger` function from the `registerCompletion` return. This allows for precise control over when completions are provided. |
|
|
176
173
|
|
|
177
174
|
[OnTyping Demo](https://github.com/user-attachments/assets/22c2ce44-334c-4963-b853-01b890b8e39f)
|
|
178
175
|
|
|
@@ -416,17 +413,17 @@ const copilot = new Copilot(process.env.OPENAI_API_KEY, {
|
|
|
416
413
|
});
|
|
417
414
|
```
|
|
418
415
|
|
|
419
|
-
The default provider is `
|
|
416
|
+
The default provider is `anthropic`, and the default model is `claude-3-5-haiku`.
|
|
420
417
|
|
|
421
|
-
> **Tip:** Even though the default provider and model are `
|
|
418
|
+
> **Tip:** Even though the default provider and model are `anthropic` and `claude-3-5-haiku`, it's always recommended to specify a provider and model when using Monacopilot. This ensures your code remains consistent even if the default settings change in future updates.
|
|
422
419
|
|
|
423
420
|
There are other providers and models available. Here is a list:
|
|
424
421
|
|
|
425
|
-
| Provider | Models
|
|
426
|
-
| --------- |
|
|
427
|
-
| Groq | `llama-3-70b`
|
|
428
|
-
| OpenAI | `gpt-4o`, `gpt-4o-mini`, `o1-preview`, `o1-mini`
|
|
429
|
-
| Anthropic | `claude-3-5-sonnet`, `claude-3-
|
|
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` |
|
|
430
427
|
|
|
431
428
|
### Custom Model
|
|
432
429
|
|
package/build/index.d.mts
CHANGED
|
@@ -6,7 +6,7 @@ import * as monaco_editor from 'monaco-editor';
|
|
|
6
6
|
|
|
7
7
|
type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-preview' | 'o1-mini';
|
|
8
8
|
type GroqModel = 'llama-3-70b';
|
|
9
|
-
type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-
|
|
9
|
+
type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-5-haiku' | 'claude-3-haiku';
|
|
10
10
|
type CopilotModel = OpenAIModel | GroqModel | AnthropicModel;
|
|
11
11
|
type CopilotProvider = 'openai' | 'groq' | 'anthropic';
|
|
12
12
|
type OpenAIChatCompletion = ChatCompletion;
|
|
@@ -28,7 +28,7 @@ interface CopilotOptions {
|
|
|
28
28
|
/**
|
|
29
29
|
* The model to use for copilot LLM requests.
|
|
30
30
|
* This can be either:
|
|
31
|
-
* 1. A predefined model name (e.g. 'claude-3-
|
|
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
32
|
* If you choose this option, also set the `provider` property to the corresponding provider of the model.
|
|
33
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
34
|
*
|
package/build/index.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ import * as monaco_editor from 'monaco-editor';
|
|
|
6
6
|
|
|
7
7
|
type OpenAIModel = 'gpt-4o' | 'gpt-4o-mini' | 'o1-preview' | 'o1-mini';
|
|
8
8
|
type GroqModel = 'llama-3-70b';
|
|
9
|
-
type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-
|
|
9
|
+
type AnthropicModel = 'claude-3-5-sonnet' | 'claude-3-5-haiku' | 'claude-3-haiku';
|
|
10
10
|
type CopilotModel = OpenAIModel | GroqModel | AnthropicModel;
|
|
11
11
|
type CopilotProvider = 'openai' | 'groq' | 'anthropic';
|
|
12
12
|
type OpenAIChatCompletion = ChatCompletion;
|
|
@@ -28,7 +28,7 @@ interface CopilotOptions {
|
|
|
28
28
|
/**
|
|
29
29
|
* The model to use for copilot LLM requests.
|
|
30
30
|
* This can be either:
|
|
31
|
-
* 1. A predefined model name (e.g. 'claude-3-
|
|
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
32
|
* If you choose this option, also set the `provider` property to the corresponding provider of the model.
|
|
33
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
34
|
*
|
package/build/index.js
CHANGED
|
@@ -1,59 +1,94 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var $=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var Oe=(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 Re(e))!Me.call(t,n)&&n!==o&&$(t,n,{get:()=>e[n],enumerable:!(r=Te(e,n))||r.enumerable});return t};var Ee=t=>be($({},"__esModule",{value:!0}),t);var Ue={};Oe(Ue,{Copilot:()=>D,registerCompletion:()=>Y,registerCopilot:()=>xe});module.exports=Ee(Ue);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"},E=.1;var ee={"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-haiku":4096};var ve={createRequestBody:(t,e)=>{let r=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:U(t),temperature:E,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},Ie={createRequestBody:(t,e)=>({model:U(t),temperature:E,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},Ae={createRequestBody:(t,e)=>({model:U(t),temperature:E,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:ve,groq:Ie,anthropic:Ae},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",v="\x1B[0m",z="\x1B[1m",f=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}${z}[MONACOPILOT ERROR] ${e}${v}`;return console.error(o?`${r}
|
|
2
2
|
${ie}Stack trace:${v}
|
|
3
|
-
${o}`:r),{message:e,stack:o}},ae=t=>{console.warn(`${se}${
|
|
4
|
-
`),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(
|
|
3
|
+
${o}`:r),{message:e,stack:o}},ae=t=>{console.warn(`${se}${z}[MONACOPILOT WARN] ${t}${v}`)};var I=(t,e,o)=>console.warn(`${se}${z}[MONACOPILOT DEPRECATED] "${t}" is deprecated${o?` in ${o}`:""}. Please use "${e}" instead. It will be removed in a future version.${v}`);var A=(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},R=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`;var W=(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),y=(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(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()},
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
${
|
|
13
|
-
|
|
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()},_e=(t,e)=>ce(t,"GET",e),De=(t,e,o)=>ce(t,"POST",{...o,body:e}),_={GET:_e,POST:De};var de=(t,e)=>{let o=w(t,e).trim(),r=le(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var Le=t=>{let{technologies:e=[],filename:o,relatedFiles:r,language:n}=t,i=R([n,...e].filter(a=>typeof a=="string"&&!!a));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
|
+
`)},ke=t=>t?.length?t.map(({path:e,content:o})=>`
|
|
14
14
|
<related_file>
|
|
15
15
|
<path>${e}</path>
|
|
16
|
-
<
|
|
16
|
+
<content_context>
|
|
17
17
|
\`\`\`
|
|
18
18
|
${o}
|
|
19
19
|
\`\`\`
|
|
20
|
-
</
|
|
21
|
-
</related_file
|
|
22
|
-
|
|
23
|
-
`):"",
|
|
24
|
-
<
|
|
25
|
-
<
|
|
20
|
+
</content_context>
|
|
21
|
+
</related_file>`.trim()).join(`
|
|
22
|
+
|
|
23
|
+
`):"",Se=(t="",e)=>{let{relatedFiles:o}=e;return`
|
|
24
|
+
<task_context>
|
|
25
|
+
<primary_instructions>
|
|
26
26
|
${t.trim()}
|
|
27
|
-
</
|
|
28
|
-
${
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
</primary_instructions>
|
|
28
|
+
${o?.length?`
|
|
29
|
+
<reference_files>
|
|
30
|
+
${ke(o)}
|
|
31
|
+
</reference_files>`:""}
|
|
32
|
+
</task_context>`.trim()},me=(t,e)=>({system:Le(e),user:Se(t,e)});var ue="<cursor>",Be=t=>{let{textBeforeCursor:e="",textAfterCursor:o="",editorState:{completionMode:r},language:n}=t,i=`<code_file>
|
|
31
33
|
${e}${ue}${o}
|
|
32
|
-
</code_file>`,
|
|
33
|
-
|
|
34
|
+
</code_file>`,a=`
|
|
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>
|
|
34
41
|
|
|
35
|
-
|
|
42
|
+
<primary_objectives>
|
|
43
|
+
1. Generate code that is syntactically correct and follows ${n||"the language"}'s best practices
|
|
44
|
+
2. Ensure seamless integration with existing code structure
|
|
45
|
+
3. Maintain consistent naming conventions and coding style
|
|
46
|
+
4. Provide only the exact code needed at the cursor position
|
|
47
|
+
</primary_objectives>
|
|
36
48
|
|
|
37
|
-
|
|
49
|
+
<strict_requirements>
|
|
50
|
+
- Output MUST contain only the code to be inserted at cursor position
|
|
51
|
+
- DO NOT include any code that appears before the cursor
|
|
52
|
+
- DO NOT include explanatory comments or documentation
|
|
53
|
+
- DO NOT wrap output in markdown code blocks
|
|
54
|
+
- DO NOT include placeholder text or TODO comments
|
|
55
|
+
- AVOID generating code beyond the immediate logical completion
|
|
56
|
+
</strict_requirements>
|
|
38
57
|
|
|
39
|
-
|
|
58
|
+
<completion_mode>
|
|
59
|
+
Active Mode: ${r}
|
|
60
|
+
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]||""}
|
|
61
|
+
</completion_mode>
|
|
40
62
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
63
|
+
<code_analysis_steps>
|
|
64
|
+
1. Analyze the code context before and after the cursor
|
|
65
|
+
2. Identify the current scope and available variables/functions
|
|
66
|
+
3. Determine the logical flow and required completion
|
|
67
|
+
4. Verify syntax compatibility with surrounding code
|
|
68
|
+
5. Ensure completion maintains code integrity
|
|
69
|
+
</code_analysis_steps>
|
|
48
70
|
|
|
49
|
-
|
|
71
|
+
<examples>
|
|
72
|
+
[Previous examples section remains the same]
|
|
73
|
+
</examples>
|
|
50
74
|
|
|
51
|
-
|
|
52
|
-
|
|
75
|
+
<error_prevention>
|
|
76
|
+
- Verify that generated code doesn't introduce syntax errors
|
|
77
|
+
- Ensure variable and function references are valid in the current scope
|
|
78
|
+
- Check for proper bracket and parenthesis matching
|
|
79
|
+
- Maintain consistent indentation with surrounding code
|
|
80
|
+
- Respect language-specific type safety requirements
|
|
81
|
+
</error_prevention>
|
|
53
82
|
|
|
54
|
-
|
|
55
|
-
|
|
83
|
+
<final_validation>
|
|
84
|
+
Before providing the completion:
|
|
85
|
+
1. Confirm the output contains ONLY the necessary code
|
|
86
|
+
2. Verify it fits seamlessly at the cursor position
|
|
87
|
+
3. Ensure it follows the active completion mode requirements
|
|
88
|
+
4. Check for consistency with existing code style
|
|
89
|
+
</final_validation>
|
|
90
|
+
</instructions>`.trim();return me(a,t)},Ce=Be;var D=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: ${R(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: ${R(V[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:p,headers:m}=this.prepareRequestDetails(a);try{let u=await this.sendCompletionRequest(l,p,{...m,...i});return this.processCompletionResponse(u)}catch(u){return this.handleCompletionError(u)}}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 _.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&&I("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:f(e).message,completion:null}}};var L=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(`
|
|
56
91
|
`).slice(1,-1).join(`
|
|
57
92
|
`);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
58
93
|
|
|
59
|
-
`),this}build(){return this.formattedCompletion}};var
|
|
94
|
+
`),this}build(){return this.formattedCompletion}};var k=class{constructor(e,o){this.cursorPos=e,this.mdl=o}shouldProvideCompletions(){return!de(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 q=class q{constructor(){this.cache=new S(q.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 y(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,n)}isPositionValid(e,o,r){let{range:n,completion:i}=e,{startLineNumber:s,startColumn:a,endColumn:l}=n,{lineNumber:p,column:m}=o,u=p===s&&m===a,c=i.startsWith(r)&&p===s&&m>=a-r.length&&m<=l+r.length;return u||c}};q.MAX_CACHE_SIZE=10;var B=q;var qe="application/json",ge=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:n}=await _.POST(e,o,{headers:{"Content-Type":qe},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:a}=o,l=Fe(t,e),m=!!s?.length?3:2,u=a?Math.floor(a/m):void 0,c=(g,T,N)=>{let b=g(t,e);return T?K(b,T,N):b},C=(g,T)=>!g||!T?g:g.map(({content:N,...b})=>({...b,content:K(N,T)})),d=c(y,u,{from:"end"}),O=c(pe,u),x=C(s,u);return{filename:r,language:n,technologies:i,relatedFiles:x,textBeforeCursor:d,textAfterCursor:O,cursorPosition:t,editorState:{completionMode:l}}},Fe=(t,e)=>{let o=W(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(n),s=0,a=0,l=0,p=r.length,m=i.length;if(n>=o.getValue().length)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(m===0)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let u=Math.min(p,m);for(let d=0;d<u&&r[d]===i[d];d++)s++;for(let d=1;d<=u;d++)r.slice(-d)===i.slice(0,d)&&(a=d);if(l=Math.max(s,a),l===0){for(let d=1;d<p;d++)if(i.startsWith(r.substring(d))){l=p-d;break}}let c=n+l,C=o.getPositionAt(c);return new t.Range(e.lineNumber,e.column,C.lineNumber,C.column)},ye=t=>L.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),h=t=>({items:t,enableForwardStability:!0});var G={onTyping:300,onIdle:600,onDemand:0},$e=t=>({onTyping:A(t,G.onTyping),onIdle:A(t,G.onIdle),onDemand:A(t,G.onDemand)}),F=new B,He=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{let{trigger:a="onIdle",endpoint:l,enableCaching:p=!0,onError:m,requestHandler:u}=s;if(!new k(o,e).shouldProvideCompletions())return h([]);if(p){let c=F.get(o,e).map(C=>({insertText:C.completion,range:C.range}));if(c.length>0)return i(),h(c)}if(r.isCancellationRequested||n)return h([]);try{let C=$e(u??ge)[a];r.onCancellationRequested(()=>{C.cancel()});let d=he({pos:o,mdl:e,options:s}),{completion:O}=await C({endpoint:l,body:{completionMetadata:d}});if(O){let x=ye(O),g=fe(t,o,e,x);return p&&F.add({completion:x,range:g,textBeforeCursor:y(o,e)}),i(),h([{insertText:x,range:g}])}}catch(c){if(Ve(c))return h([]);m?m(c):f(c)}return h([])},Ve=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,Pe=He;var P=new WeakMap,M=null,Y=(t,e,o)=>{M&&M.deregister();let r=[],n={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};P.set(e,n),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let i=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(l,p,m,u)=>{let c=P.get(e);if(!(!c||o.trigger==="onDemand"&&!c.isManualTrigger))return Pe({monaco:t,mdl:l,pos:p,token:u,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0,c.isManualTrigger=!1},options:o})},freeInlineCompletions:()=>{}});r.push(i);let s=e.onKeyDown(l=>{let p=P.get(e);if(!p)return;let m=l.keyCode===t.KeyCode.Tab||l.keyCode===t.KeyCode.RightArrow&&l.metaKey;p.isCompletionVisible&&m?(p.isCompletionAccepted=!0,p.isCompletionVisible=!1):p.isCompletionAccepted=!1});r.push(s);let a={deregister:()=>{r.forEach(l=>l.dispose()),F.clear(),P.delete(e),M=null},trigger:()=>je(e)};return M=a,a}catch(i){return o.onError?o.onError(i):f(i),{deregister:()=>{r.forEach(s=>s.dispose()),P.delete(e),M=null},trigger:()=>{}}}},je=t=>{let e=P.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)=>(I("registerCopilot","registerCompletion"),Y(...t));0&&(module.exports={Copilot,registerCompletion,registerCopilot});
|
package/build/index.mjs
CHANGED
|
@@ -1,59 +1,94 @@
|
|
|
1
|
-
var N=["groq","openai","anthropic"],
|
|
1
|
+
var N=["groq","openai","anthropic"],G={"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"]},Y="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"},E=.1;var Z={"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-haiku":4096};var Pe={createRequestBody:(t,e)=>{let r=t==="o1-preview"||t==="o1-mini"?[{role:"user",content:e.user}]:[{role:"system",content:e.system},{role:"user",content:e.user}];return{model:V(t),temperature:E,messages:r}},createHeaders:t=>({"Content-Type":"application/json",Authorization:`Bearer ${t}`}),parseCompletion:t=>t.choices?.length?t.choices[0].message.content:null},xe={createRequestBody:(t,e)=>({model:V(t),temperature:E,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:E,system:e.system,messages:[{role:"user",content:e.user}],max_tokens:Re(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:Pe,groq:xe,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=>G[t],oe=t=>J[t],Re=t=>Z[t]||4096;var re="\x1B[91m",ne="\x1B[93m",v="\x1B[0m",j="\x1B[1m",f=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}${v}`;return console.error(o?`${r}
|
|
2
2
|
${re}Stack trace:${v}
|
|
3
|
-
${o}`:r),{message:e,stack:o}},ie=t=>{console.warn(`${ne}${j}[MONACOPILOT WARN] ${t}${v}`)};var I=(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.${v}`);var A=(t,e)=>{let o=null,r=null,i=(...n)=>new Promise((s,
|
|
4
|
-
`),i=r.length;if(e>=i)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(
|
|
3
|
+
${o}`:r),{message:e,stack:o}},ie=t=>{console.warn(`${ne}${j}[MONACOPILOT WARN] ${t}${v}`)};var I=(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.${v}`);var A=(t,e)=>{let o=null,r=null,i=(...n)=>new Promise((s,a)=>{o&&(clearTimeout(o),r&&r("Cancelled")),r=a,o=setTimeout(()=>{s(t(...n)),r=null},e)});return i.cancel=()=>{o&&(clearTimeout(o),r&&r("Cancelled"),o=null,r=null)},i},R=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),y=(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())}),z=(t,e,o={})=>{if(e<=0)return"";let r=t.split(`
|
|
4
|
+
`),i=r.length;if(e>=i)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 n=r.slice(0,e);return n.every(s=>s==="")?`
|
|
7
7
|
`.repeat(e):n.join(`
|
|
8
|
-
`)};var le=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},i=e==="POST"&&o.body?JSON.stringify(o.body):void 0,n=await fetch(t,{method:e,headers:r,body:i,signal:o.signal});if(!n.ok)throw new Error(`${n.statusText||o.fallbackError||"Network error"}`);return n.json()},Me=(t,e)=>le(t,"GET",e),
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
${
|
|
13
|
-
|
|
8
|
+
`)};var le=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},i=e==="POST"&&o.body?JSON.stringify(o.body):void 0,n=await fetch(t,{method:e,headers:r,body:i,signal:o.signal});if(!n.ok)throw new Error(`${n.statusText||o.fallbackError||"Network error"}`);return n.json()},Me=(t,e)=>le(t,"GET",e),Oe=(t,e,o)=>le(t,"POST",{...o,body:e}),_={GET:Me,POST:Oe};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:i}=t,n=R([i,...e].filter(a=>typeof a=="string"&&!!a));return[`You are an expert ${n?`${n} `:""}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.":"",i?`Apply ${i}-specific best practices, idioms, and syntax conventions in all generated code.`:""].filter(Boolean).join(`
|
|
13
|
+
`)},Ee=t=>t?.length?t.map(({path:e,content:o})=>`
|
|
14
14
|
<related_file>
|
|
15
15
|
<path>${e}</path>
|
|
16
|
-
<
|
|
16
|
+
<content_context>
|
|
17
17
|
\`\`\`
|
|
18
18
|
${o}
|
|
19
19
|
\`\`\`
|
|
20
|
-
</
|
|
21
|
-
</related_file
|
|
22
|
-
|
|
23
|
-
`):"",ve=(t="",e)=>{let{relatedFiles:o}=e
|
|
24
|
-
<
|
|
25
|
-
<
|
|
20
|
+
</content_context>
|
|
21
|
+
</related_file>`.trim()).join(`
|
|
22
|
+
|
|
23
|
+
`):"",ve=(t="",e)=>{let{relatedFiles:o}=e;return`
|
|
24
|
+
<task_context>
|
|
25
|
+
<primary_instructions>
|
|
26
26
|
${t.trim()}
|
|
27
|
-
</
|
|
28
|
-
${
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
</primary_instructions>
|
|
28
|
+
${o?.length?`
|
|
29
|
+
<reference_files>
|
|
30
|
+
${Ee(o)}
|
|
31
|
+
</reference_files>`:""}
|
|
32
|
+
</task_context>`.trim()},ce=(t,e)=>({system:be(e),user:ve(t,e)});var de="<cursor>",Ie=t=>{let{textBeforeCursor:e="",textAfterCursor:o="",editorState:{completionMode:r},language:i}=t,n=`<code_file>
|
|
31
33
|
${e}${de}${o}
|
|
32
|
-
</code_file>`,
|
|
33
|
-
|
|
34
|
+
</code_file>`,a=`
|
|
35
|
+
<instructions>
|
|
36
|
+
<context>
|
|
37
|
+
Below is a ${i||"code"} file with the token '${de}' marking the exact cursor position where code completion is needed.
|
|
38
|
+
|
|
39
|
+
${n}
|
|
40
|
+
</context>
|
|
34
41
|
|
|
35
|
-
|
|
42
|
+
<primary_objectives>
|
|
43
|
+
1. Generate code that is syntactically correct and follows ${i||"the language"}'s best practices
|
|
44
|
+
2. Ensure seamless integration with existing code structure
|
|
45
|
+
3. Maintain consistent naming conventions and coding style
|
|
46
|
+
4. Provide only the exact code needed at the cursor position
|
|
47
|
+
</primary_objectives>
|
|
36
48
|
|
|
37
|
-
|
|
49
|
+
<strict_requirements>
|
|
50
|
+
- Output MUST contain only the code to be inserted at cursor position
|
|
51
|
+
- DO NOT include any code that appears before the cursor
|
|
52
|
+
- DO NOT include explanatory comments or documentation
|
|
53
|
+
- DO NOT wrap output in markdown code blocks
|
|
54
|
+
- DO NOT include placeholder text or TODO comments
|
|
55
|
+
- AVOID generating code beyond the immediate logical completion
|
|
56
|
+
</strict_requirements>
|
|
38
57
|
|
|
39
|
-
|
|
58
|
+
<completion_mode>
|
|
59
|
+
Active Mode: ${r}
|
|
60
|
+
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]||""}
|
|
61
|
+
</completion_mode>
|
|
40
62
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
63
|
+
<code_analysis_steps>
|
|
64
|
+
1. Analyze the code context before and after the cursor
|
|
65
|
+
2. Identify the current scope and available variables/functions
|
|
66
|
+
3. Determine the logical flow and required completion
|
|
67
|
+
4. Verify syntax compatibility with surrounding code
|
|
68
|
+
5. Ensure completion maintains code integrity
|
|
69
|
+
</code_analysis_steps>
|
|
48
70
|
|
|
49
|
-
|
|
71
|
+
<examples>
|
|
72
|
+
[Previous examples section remains the same]
|
|
73
|
+
</examples>
|
|
50
74
|
|
|
51
|
-
|
|
52
|
-
|
|
75
|
+
<error_prevention>
|
|
76
|
+
- Verify that generated code doesn't introduce syntax errors
|
|
77
|
+
- Ensure variable and function references are valid in the current scope
|
|
78
|
+
- Check for proper bracket and parenthesis matching
|
|
79
|
+
- Maintain consistent indentation with surrounding code
|
|
80
|
+
- Respect language-specific type safety requirements
|
|
81
|
+
</error_prevention>
|
|
53
82
|
|
|
54
|
-
|
|
55
|
-
|
|
83
|
+
<final_validation>
|
|
84
|
+
Before providing the completion:
|
|
85
|
+
1. Confirm the output contains ONLY the necessary code
|
|
86
|
+
2. Verify it fits seamlessly at the cursor position
|
|
87
|
+
3. Ensure it follows the active completion mode requirements
|
|
88
|
+
4. Check for consistency with existing code style
|
|
89
|
+
</final_validation>
|
|
90
|
+
</instructions>`.trim();return ce(a,t)},me=Ie;var W=class{constructor(e,o={}){if(!e)throw new Error("Please provide an API key.");this.apiKey=e,this.provider=o.provider??Y,this.model=o.model??X,this.validateInputs()}validateInputs(){if(!N.includes(this.provider))throw new Error(`Unsupported provider "${this.provider}". Please choose from: ${R(N)}. 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: ${R($[this.provider])}`)}async complete(e){let{body:o,options:r}=e,{completionMetadata:i}=o,{headers:n={},customPrompt:s}=r??{},a=this.generatePrompt(i,s),{endpoint:l,requestBody:p,headers:m}=this.prepareRequestDetails(a);try{let u=await this.sendCompletionRequest(l,p,{...m,...n});return this.processCompletionResponse(u)}catch(u){return this.handleCompletionError(u)}}generatePrompt(e,o){let r=me(e);return o?{...r,...o(e)}:r}prepareRequestDetails(e){let o=oe(this.provider),r,i=ee(this.apiKey,this.provider);if(typeof this.model=="object"&&"config"in this.model){let n=this.model.config(this.apiKey,e);o=n.endpoint??o,r=n.body??{},i={...i,...n.headers}}else r=Q(this.model,this.provider,e);return{endpoint:o,requestBody:r,headers:i}}async sendCompletionRequest(e,o,r){return _.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&&I("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:f(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,i;for(;(i=o.exec(e))!==null;){let n=i[0],s=n.split(`
|
|
56
91
|
`).slice(1,-1).join(`
|
|
57
92
|
`);r=r.replace(n,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
58
93
|
|
|
59
|
-
`),this}build(){return this.formattedCompletion}};var
|
|
94
|
+
`),this}build(){return this.formattedCompletion}};var L=class{constructor(e,o){this.cursorPos=e,this.mdl=o}shouldProvideCompletions(){return!pe(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 B=class B{constructor(){this.cache=new k(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 i=r.getValueInRange(e.range);return y(o,r).startsWith(e.textBeforeCursor)&&this.isPositionValid(e,o,i)}isPositionValid(e,o,r){let{range:i,completion:n}=e,{startLineNumber:s,startColumn:a,endColumn:l}=i,{lineNumber:p,column:m}=o,u=p===s&&m===a,c=n.startsWith(r)&&p===s&&m>=a-r.length&&m<=l+r.length;return u||c}};B.MAX_CACHE_SIZE=10;var S=B;var Ae="application/json",ue=async t=>{let{endpoint:e,body:o}=t,{completion:r,error:i}=await _.POST(e,o,{headers:{"Content-Type":Ae},fallbackError:"Error while fetching completion item"});if(i)throw new Error(i);return{completion:r}},Ce=({pos:t,mdl:e,options:o})=>{let{filename:r,language:i,technologies:n,relatedFiles:s,maxContextLines:a}=o,l=we(t,e),m=!!s?.length?3:2,u=a?Math.floor(a/m):void 0,c=(g,T,F)=>{let b=g(t,e);return T?z(b,T,F):b},C=(g,T)=>!g||!T?g:g.map(({content:F,...b})=>({...b,content:z(F,T)})),d=c(y,u,{from:"end"}),O=c(ae,u),x=C(s,u);return{filename:r,language:i,technologies:n,relatedFiles:x,textBeforeCursor:d,textAfterCursor:O,cursorPosition:t,editorState:{completionMode:l}}},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 i=o.getOffsetAt(e),n=o.getValue().substring(i),s=0,a=0,l=0,p=r.length,m=n.length;if(i>=o.getValue().length)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);if(m===0)return new t.Range(e.lineNumber,e.column,e.lineNumber,e.column);let u=Math.min(p,m);for(let d=0;d<u&&r[d]===n[d];d++)s++;for(let d=1;d<=u;d++)r.slice(-d)===n.slice(0,d)&&(a=d);if(l=Math.max(s,a),l===0){for(let d=1;d<p;d++)if(n.startsWith(r.substring(d))){l=p-d;break}}let c=i+l,C=o.getPositionAt(c);return new t.Range(e.lineNumber,e.column,C.lineNumber,C.column)},he=t=>D.create(t).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build(),h=t=>({items:t,enableForwardStability:!0});var K={onTyping:300,onIdle:600,onDemand:0},De=t=>({onTyping:A(t,K.onTyping),onIdle:A(t,K.onIdle),onDemand:A(t,K.onDemand)}),q=new S,Le=async({monaco:t,mdl:e,pos:o,token:r,isCompletionAccepted:i,onShowCompletion:n,options:s})=>{let{trigger:a="onIdle",endpoint:l,enableCaching:p=!0,onError:m,requestHandler:u}=s;if(!new L(o,e).shouldProvideCompletions())return h([]);if(p){let c=q.get(o,e).map(C=>({insertText:C.completion,range:C.range}));if(c.length>0)return n(),h(c)}if(r.isCancellationRequested||i)return h([]);try{let C=De(u??ue)[a];r.onCancellationRequested(()=>{C.cancel()});let d=Ce({pos:o,mdl:e,options:s}),{completion:O}=await C({endpoint:l,body:{completionMetadata:d}});if(O){let x=he(O),g=ge(t,o,e,x);return p&&q.add({completion:x,range:g,textBeforeCursor:y(o,e)}),n(),h([{insertText:x,range:g}])}}catch(c){if(ke(c))return h([]);m?m(c):f(c)}return h([])},ke=t=>typeof t=="string"?t==="Cancelled"||t==="AbortError":t instanceof Error?t.message==="Cancelled"||t.name==="AbortError":!1,fe=Le;var P=new WeakMap,M=null,ye=(t,e,o)=>{M&&M.deregister();let r=[],i={isCompletionAccepted:!1,isCompletionVisible:!1,isManualTrigger:!1};P.set(e,i),e.updateOptions({inlineSuggest:{enabled:!0,mode:"subwordSmart"}});try{let n=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:(l,p,m,u)=>{let c=P.get(e);if(!(!c||o.trigger==="onDemand"&&!c.isManualTrigger))return fe({monaco:t,mdl:l,pos:p,token:u,isCompletionAccepted:c.isCompletionAccepted,onShowCompletion:()=>{c.isCompletionVisible=!0,c.isManualTrigger=!1},options:o})},freeInlineCompletions:()=>{}});r.push(n);let s=e.onKeyDown(l=>{let p=P.get(e);if(!p)return;let m=l.keyCode===t.KeyCode.Tab||l.keyCode===t.KeyCode.RightArrow&&l.metaKey;p.isCompletionVisible&&m?(p.isCompletionAccepted=!0,p.isCompletionVisible=!1):p.isCompletionAccepted=!1});r.push(s);let a={deregister:()=>{r.forEach(l=>l.dispose()),q.clear(),P.delete(e),M=null},trigger:()=>Se(e)};return M=a,a}catch(n){return o.onError?o.onError(n):f(n),{deregister:()=>{r.forEach(s=>s.dispose()),P.delete(e),M=null},trigger:()=>{}}}},Se=t=>{let e=P.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)=>(I("registerCopilot","registerCompletion"),ye(...t));export{W as Copilot,ye as registerCompletion,Be as registerCopilot};
|