monacopilot 0.14.0 → 0.14.2
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/build/index.js +117 -39
- package/build/index.mjs +120 -42
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -1,59 +1,137 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
${ie}Stack trace:${
|
|
3
|
-
${o}`:r),{message:e,stack:o}},ae=t=>{console.warn(`${se}${W}[MONACOPILOT WARN] ${t}${
|
|
4
|
-
`),n=r.length;if(e>=n)return t;if(o.from==="end"){let s=r.slice(-e);return s.every(
|
|
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==="")?`
|
|
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()},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})=>`
|
|
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
|
+
`):"",ke=(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
|
+
${Se(o)}
|
|
31
|
+
</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>
|
|
31
33
|
${e}${ue}${o}
|
|
32
|
-
</code_file>`,
|
|
33
|
-
|
|
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>
|
|
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>
|
|
34
79
|
|
|
35
|
-
|
|
80
|
+
<examples>
|
|
81
|
+
<example>
|
|
82
|
+
Context: "const <cursor>"
|
|
83
|
+
CORRECT COMPLETION: "myVariable = 42"
|
|
84
|
+
INCORRECT COMPLETION: "const myVariable = 42"
|
|
85
|
+
</example>
|
|
36
86
|
|
|
37
|
-
|
|
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>
|
|
38
92
|
|
|
39
|
-
|
|
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>
|
|
40
98
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
- Avoid wrapping your completion with markdown code blocks (\`\`\` or \`).
|
|
47
|
-
- Provide **only** the necessary code to be inserted at the cursor location.
|
|
99
|
+
<example>
|
|
100
|
+
Context: "const result = 'Hello' + ' W<cursor>';"
|
|
101
|
+
CORRECT COMPLETION: "orld"
|
|
102
|
+
INCORRECT COMPLETION: "orld';"
|
|
103
|
+
</example>
|
|
48
104
|
|
|
49
|
-
|
|
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>
|
|
50
115
|
|
|
51
|
-
|
|
52
|
-
|
|
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>
|
|
53
124
|
|
|
54
|
-
|
|
55
|
-
|
|
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(`
|
|
56
134
|
`).slice(1,-1).join(`
|
|
57
135
|
`);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
58
136
|
|
|
59
|
-
`),this}build(){return this.formattedCompletion}};var
|
|
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});
|
package/build/index.mjs
CHANGED
|
@@ -1,59 +1,137 @@
|
|
|
1
|
-
var
|
|
2
|
-
${re}Stack trace:${
|
|
3
|
-
${o}`:r),{message:e,stack:o}},ie=t=>{console.warn(`${ne}${
|
|
4
|
-
`),
|
|
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==="")?`
|
|
5
5
|
`.repeat(e):s.join(`
|
|
6
|
-
`)}let
|
|
7
|
-
`.repeat(e):
|
|
8
|
-
`)};var le=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
${
|
|
13
|
-
|
|
6
|
+
`)}let i=r.slice(0,e);return i.every(s=>s==="")?`
|
|
7
|
+
`.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})=>`
|
|
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
|
+
`):"",Ie=(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
|
+
${ve(o)}
|
|
31
|
+
</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>
|
|
31
33
|
${e}${de}${o}
|
|
32
|
-
</code_file>`,
|
|
33
|
-
|
|
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.
|
|
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>
|
|
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>
|
|
34
79
|
|
|
35
|
-
|
|
80
|
+
<examples>
|
|
81
|
+
<example>
|
|
82
|
+
Context: "const <cursor>"
|
|
83
|
+
CORRECT COMPLETION: "myVariable = 42"
|
|
84
|
+
INCORRECT COMPLETION: "const myVariable = 42"
|
|
85
|
+
</example>
|
|
36
86
|
|
|
37
|
-
|
|
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>
|
|
38
92
|
|
|
39
|
-
|
|
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>
|
|
40
98
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
- Avoid wrapping your completion with markdown code blocks (\`\`\` or \`).
|
|
47
|
-
- Provide **only** the necessary code to be inserted at the cursor location.
|
|
99
|
+
<example>
|
|
100
|
+
Context: "const result = 'Hello' + ' W<cursor>';"
|
|
101
|
+
CORRECT COMPLETION: "orld"
|
|
102
|
+
INCORRECT COMPLETION: "orld';"
|
|
103
|
+
</example>
|
|
48
104
|
|
|
49
|
-
|
|
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>
|
|
50
115
|
|
|
51
|
-
|
|
52
|
-
|
|
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>
|
|
53
124
|
|
|
54
|
-
|
|
55
|
-
|
|
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(`
|
|
56
134
|
`).slice(1,-1).join(`
|
|
57
|
-
`);r=r.replace(
|
|
135
|
+
`);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
58
136
|
|
|
59
|
-
`),this}build(){return this.formattedCompletion}};var
|
|
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};
|