monacopilot 0.9.20 → 0.9.22
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 +25 -8
- package/build/index.d.mts +21 -7
- package/build/index.d.ts +21 -7
- package/build/index.js +11 -11
- package/build/index.mjs +10 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
- [Examples](#examples)
|
|
10
10
|
- [Installation](#installation)
|
|
11
11
|
- [Usage](#usage)
|
|
12
|
-
- [Copilot
|
|
12
|
+
- [Copilot Options](#copilot-options)
|
|
13
13
|
- [Changing the Provider and Model](#changing-the-provider-and-model)
|
|
14
|
+
- [Copilot Completion Request Options](#copilot-completion-request-options)
|
|
14
15
|
- [Custom Headers](#custom-headers)
|
|
15
16
|
- [Configuration Options](#configuration-options)
|
|
16
17
|
- [External Context](#external-context)
|
|
@@ -29,6 +30,7 @@ https://github.com/user-attachments/assets/4af4e24a-1b05-4bee-84aa-1521ad7098cd
|
|
|
29
30
|
Here are some examples of how to use Monacopilot in different project setups:
|
|
30
31
|
|
|
31
32
|
- Next.js ([app](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/nextjs/app) | [pages](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/nextjs/pages))
|
|
33
|
+
- [Remix](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/remix)
|
|
32
34
|
|
|
33
35
|
## Installation
|
|
34
36
|
|
|
@@ -66,16 +68,22 @@ const copilot = new Copilot(process.env.GROQ_API_KEY);
|
|
|
66
68
|
app.use(express.json());
|
|
67
69
|
|
|
68
70
|
app.post('/copilot', async (req, res) => {
|
|
69
|
-
const completion = await copilot.complete(
|
|
71
|
+
const completion = await copilot.complete({
|
|
72
|
+
body: req.body,
|
|
73
|
+
});
|
|
70
74
|
res.status(200).json(completion);
|
|
71
75
|
});
|
|
72
76
|
|
|
73
77
|
app.listen(port);
|
|
74
78
|
```
|
|
75
79
|
|
|
80
|
+
Great! Now Monacopilot is all set up to send completion requests to the `/copilot` endpoint and get those completions back. It's like a high-five between your code and the AI!
|
|
81
|
+
|
|
82
|
+
The `copilot.complete` method processes the request body sent by Monacopilot and returns the corresponding completion.
|
|
83
|
+
|
|
76
84
|
#### Register Copilot with the Monaco Editor
|
|
77
85
|
|
|
78
|
-
|
|
86
|
+
Now, let's integrate Copilot with the Monaco editor. Here's how you can do it:
|
|
79
87
|
|
|
80
88
|
```javascript
|
|
81
89
|
import * as monaco from 'monaco-editor';
|
|
@@ -91,7 +99,10 @@ registerCopilot(monaco, editor, {
|
|
|
91
99
|
});
|
|
92
100
|
```
|
|
93
101
|
|
|
94
|
-
|
|
102
|
+
- `endpoint`: The URL of the API endpoint that we created in the previous step.
|
|
103
|
+
- `language`: The language of the editor.
|
|
104
|
+
|
|
105
|
+
## Copilot Options
|
|
95
106
|
|
|
96
107
|
### Changing the Provider and Model
|
|
97
108
|
|
|
@@ -116,14 +127,20 @@ The default provider is `groq` and the default model is `llama-3-70b`.
|
|
|
116
127
|
| Anthropic | Claude-3-Sonnet | Versatile and powerful, offering a great balance between performance and efficiency for various coding needs |
|
|
117
128
|
| Anthropic | Claude-3-Haiku | Streamlined model optimized for speed, perfect for quick completions and real-time coding assistance |
|
|
118
129
|
|
|
130
|
+
## Copilot Completion Request Options
|
|
131
|
+
|
|
119
132
|
### Custom Headers
|
|
120
133
|
|
|
121
|
-
You can add custom headers to the provider's completion requests. For example, if you select `OpenAI` as your provider, you can add a custom header to the OpenAI
|
|
134
|
+
You can add custom headers to the provider's completion requests. For example, if you select `OpenAI` as your provider, you can add a custom header to the OpenAI completion requests made by Monacopilot.
|
|
122
135
|
|
|
123
136
|
```javascript
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
137
|
+
copilot.complete({
|
|
138
|
+
body,
|
|
139
|
+
options: {
|
|
140
|
+
// ...other options
|
|
141
|
+
headers: {
|
|
142
|
+
'X-Custom-Header': 'custom-value',
|
|
143
|
+
},
|
|
127
144
|
},
|
|
128
145
|
});
|
|
129
146
|
```
|
package/build/index.d.mts
CHANGED
|
@@ -18,10 +18,6 @@ interface CopilotOptions {
|
|
|
18
18
|
* If not specified, a default model will be used.
|
|
19
19
|
*/
|
|
20
20
|
model?: CompletionModel;
|
|
21
|
-
/**
|
|
22
|
-
* Additional headers to include in the completion requests.
|
|
23
|
-
*/
|
|
24
|
-
headers?: Record<string, string>;
|
|
25
21
|
}
|
|
26
22
|
type Endpoint = string;
|
|
27
23
|
type Filename = string;
|
|
@@ -86,8 +82,27 @@ type AnthropicModel = 'claude-3.5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' |
|
|
|
86
82
|
type CompletionModel = OpenAIModel | GroqModel | AnthropicModel;
|
|
87
83
|
type CompletionProvider = 'openai' | 'groq' | 'anthropic';
|
|
88
84
|
interface CompletionRequest {
|
|
85
|
+
/**
|
|
86
|
+
* The body of the completion request.
|
|
87
|
+
*/
|
|
88
|
+
body: CompletionRequestBody;
|
|
89
|
+
/**
|
|
90
|
+
* Additional options to include in the completion request.
|
|
91
|
+
*/
|
|
92
|
+
options?: CompletionRequestOptions;
|
|
93
|
+
}
|
|
94
|
+
interface CompletionRequestBody {
|
|
95
|
+
/**
|
|
96
|
+
* The metadata required to generate the completion.
|
|
97
|
+
*/
|
|
89
98
|
completionMetadata: CompletionMetadata;
|
|
90
99
|
}
|
|
100
|
+
interface CompletionRequestOptions {
|
|
101
|
+
/**
|
|
102
|
+
* Additional headers to include in the provider's completion requests.
|
|
103
|
+
*/
|
|
104
|
+
headers?: Record<string, string>;
|
|
105
|
+
}
|
|
91
106
|
interface CompletionResponse {
|
|
92
107
|
completion: string | null;
|
|
93
108
|
error?: string;
|
|
@@ -112,7 +127,6 @@ declare class Copilot {
|
|
|
112
127
|
private readonly apiKey;
|
|
113
128
|
private readonly provider;
|
|
114
129
|
private readonly model;
|
|
115
|
-
private readonly headers;
|
|
116
130
|
/**
|
|
117
131
|
* Initializes the Copilot with an API key and optional configuration.
|
|
118
132
|
* @param apiKey - The API key for the chosen provider.
|
|
@@ -124,7 +138,7 @@ declare class Copilot {
|
|
|
124
138
|
* @param params - The metadata required to generate the completion.
|
|
125
139
|
* @returns A promise resolving to the completed text snippet or an error.
|
|
126
140
|
*/
|
|
127
|
-
complete({
|
|
141
|
+
complete({ body, options, }: CompletionRequest): Promise<CompletionResponse>;
|
|
128
142
|
private validateInputs;
|
|
129
143
|
}
|
|
130
144
|
|
|
@@ -137,4 +151,4 @@ declare class Copilot {
|
|
|
137
151
|
*/
|
|
138
152
|
declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
|
|
139
153
|
|
|
140
|
-
export { type CompletionRequest, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
|
|
154
|
+
export { type CompletionModel, type CompletionProvider, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
|
package/build/index.d.ts
CHANGED
|
@@ -18,10 +18,6 @@ interface CopilotOptions {
|
|
|
18
18
|
* If not specified, a default model will be used.
|
|
19
19
|
*/
|
|
20
20
|
model?: CompletionModel;
|
|
21
|
-
/**
|
|
22
|
-
* Additional headers to include in the completion requests.
|
|
23
|
-
*/
|
|
24
|
-
headers?: Record<string, string>;
|
|
25
21
|
}
|
|
26
22
|
type Endpoint = string;
|
|
27
23
|
type Filename = string;
|
|
@@ -86,8 +82,27 @@ type AnthropicModel = 'claude-3.5-sonnet' | 'claude-3-opus' | 'claude-3-haiku' |
|
|
|
86
82
|
type CompletionModel = OpenAIModel | GroqModel | AnthropicModel;
|
|
87
83
|
type CompletionProvider = 'openai' | 'groq' | 'anthropic';
|
|
88
84
|
interface CompletionRequest {
|
|
85
|
+
/**
|
|
86
|
+
* The body of the completion request.
|
|
87
|
+
*/
|
|
88
|
+
body: CompletionRequestBody;
|
|
89
|
+
/**
|
|
90
|
+
* Additional options to include in the completion request.
|
|
91
|
+
*/
|
|
92
|
+
options?: CompletionRequestOptions;
|
|
93
|
+
}
|
|
94
|
+
interface CompletionRequestBody {
|
|
95
|
+
/**
|
|
96
|
+
* The metadata required to generate the completion.
|
|
97
|
+
*/
|
|
89
98
|
completionMetadata: CompletionMetadata;
|
|
90
99
|
}
|
|
100
|
+
interface CompletionRequestOptions {
|
|
101
|
+
/**
|
|
102
|
+
* Additional headers to include in the provider's completion requests.
|
|
103
|
+
*/
|
|
104
|
+
headers?: Record<string, string>;
|
|
105
|
+
}
|
|
91
106
|
interface CompletionResponse {
|
|
92
107
|
completion: string | null;
|
|
93
108
|
error?: string;
|
|
@@ -112,7 +127,6 @@ declare class Copilot {
|
|
|
112
127
|
private readonly apiKey;
|
|
113
128
|
private readonly provider;
|
|
114
129
|
private readonly model;
|
|
115
|
-
private readonly headers;
|
|
116
130
|
/**
|
|
117
131
|
* Initializes the Copilot with an API key and optional configuration.
|
|
118
132
|
* @param apiKey - The API key for the chosen provider.
|
|
@@ -124,7 +138,7 @@ declare class Copilot {
|
|
|
124
138
|
* @param params - The metadata required to generate the completion.
|
|
125
139
|
* @returns A promise resolving to the completed text snippet or an error.
|
|
126
140
|
*/
|
|
127
|
-
complete({
|
|
141
|
+
complete({ body, options, }: CompletionRequest): Promise<CompletionResponse>;
|
|
128
142
|
private validateInputs;
|
|
129
143
|
}
|
|
130
144
|
|
|
@@ -137,4 +151,4 @@ declare class Copilot {
|
|
|
137
151
|
*/
|
|
138
152
|
declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
|
|
139
153
|
|
|
140
|
-
export { type CompletionRequest, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
|
|
154
|
+
export { type CompletionModel, type CompletionProvider, type CompletionRequest, type CompletionRequestBody, type CompletionRequestOptions, type CompletionResponse, Copilot, type CopilotOptions, type CopilotRegistration, type Monaco, type RegisterCopilotOptions, type StandaloneCodeEditor, registerCopilot };
|
package/build/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var S=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var Ee=(o,e)=>{for(var t in e)S(o,t,{get:e[t],enumerable:!0})},
|
|
1
|
+
"use strict";var S=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var Ee=(o,e)=>{for(var t in e)S(o,t,{get:e[t],enumerable:!0})},Pe=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of he(e))!fe.call(o,n)&&n!==t&&S(o,n,{get:()=>e[n],enumerable:!(r=ge(e,n))||r.enumerable});return o};var Te=o=>Pe(S({},"__esModule",{value:!0}),o);var Se={};Ee(Se,{Copilot:()=>b,registerCopilot:()=>de});module.exports=Te(Se);var U={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3.5-sonnet":"claude-3.5-sonnet-20240620","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307"},D={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},k="llama-3-70b",T="groq",V={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},j=.3;var W=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var x=class o{constructor(){}static getInstance(){return o.instance||(o.instance=new o),o.instance}error(e,t){console.error(this.styleMessage(t.message,e,"error")),t.stack&&console.error(this.styleStackTrace(t.stack))}warn(e,t){console.warn(this.styleMessage(t,e,"warning"))}styleMessage(e,t,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((w,ue)=>{let Ce=w.split(" "),_=[],C="";return Ce.forEach(F=>{(C+F).length>ue&&(_.push(C.trim()),C=""),C+=F+" "}),C.trim()&&_.push(C.trim()),_})(e,l-4),P=[a,...m.map(w=>`\u2502 ${w.padEnd(l-4)} \u2502`),c].join(`
|
|
2
2
|
`);return`
|
|
3
3
|
\x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${t}]\x1B[0m \x1B[2m${i}\x1B[0m
|
|
4
|
-
${
|
|
4
|
+
${P}
|
|
5
5
|
`}styleStackTrace(e){return e.split(`
|
|
6
6
|
`).map((n,i)=>i===0?`\x1B[31m${n}\x1B[0m`:`\x1B[2m${n}\x1B[0m`).join(`
|
|
7
|
-
`)}getTimestamp(){return new Date().toISOString()}};var h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logger.error(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};h.instance=new h;var B=h;var d=(o,e)=>B.getInstance().handleError(o,e);var G={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Y=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((
|
|
8
|
-
`);return e[e.length-1].length+1};var $=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),H=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var z=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},xe=(o,e)=>z(o,"GET",e),
|
|
7
|
+
`)}getTimestamp(){return new Date().toISOString()}};var h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logger.error(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};h.instance=new h;var B=h;var d=(o,e)=>B.getInstance().handleError(o,e);var G={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Y=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},M=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var y=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],K=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),g=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),X=o=>{let e=o.split(`
|
|
8
|
+
`);return e[e.length-1].length+1};var $=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),H=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var z=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},xe=(o,e)=>z(o,"GET",e),Me=(o,e,t)=>z(o,"POST",{...t,body:e}),R={GET:xe,POST:Me};var J=(o,e)=>{let t=y(o,e);return!!t&&!W.has(t)},Z=(o,e)=>{let t=K(o,e).trim(),r=g(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var I="<<CURSOR>>",Q=o=>o==="javascript"?"latest JavaScript":o,ee=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},oe=o=>{let e=Q(o.language),t=ee(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},ye=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${M(o)}`:"",r=Q(e);return`The code is written${r?` in ${r}`:""}${t}.`},te=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=o,a=ee(n),c=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
|
|
9
9
|
|
|
10
|
-
`;return p+=
|
|
10
|
+
`;return p+=ye(r,t),p+=`
|
|
11
11
|
|
|
12
12
|
Here are the details about how the completion should be generated:
|
|
13
13
|
- The cursor position is marked with '${I}'.
|
|
@@ -23,16 +23,16 @@ Here are the details about how the completion should be generated:
|
|
|
23
23
|
Here's the code snippet for completion:
|
|
24
24
|
|
|
25
25
|
<code>
|
|
26
|
-
${i}${I}${
|
|
26
|
+
${i}${I}${l}
|
|
27
27
|
</code>`,s&&s.length>0&&(p+=`
|
|
28
28
|
|
|
29
29
|
Additional context from related files:
|
|
30
30
|
|
|
31
|
-
`,p+=s.map(
|
|
32
|
-
${
|
|
31
|
+
`,p+=s.map(m=>`// Path: ${m.path}
|
|
32
|
+
${m.content}
|
|
33
33
|
`).join(`
|
|
34
|
-
`)),p.endsWith(".")?p:`${p}.`};var re=(o,e,t)=>{let r=oe(o),n=te(o),
|
|
34
|
+
`)),p.endsWith(".")?p:`${p}.`};var re=(o,e,t)=>{let r=oe(o),n=te(o),l={model:Oe(e),temperature:j},s={openai:{messages:[{role:"system",content:r},{role:"user",content:n}]},groq:{messages:[{role:"system",content:r},{role:"user",content:n}]},anthropic:{system:r,messages:[{role:"user",content:n}],max_tokens:ve(e)}};return{...l,...s[t]}},ne=(o,e)=>{let t={"Content-Type":"application/json"},r={openai:{Authorization:`Bearer ${o}`},groq:{Authorization:`Bearer ${o}`},anthropic:{"x-api-key":o,"anthropic-version":"2023-06-01"}};return{...t,...r[e]}},ie=(o,e)=>{let r={openai:Re,groq:Ie,anthropic:be}[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r(o)},Re=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the openai response"},Ie=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the groq response"},be=o=>o.content?typeof o.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:o.content}:{completion:null,error:"No completion found in the anthropic response"},Oe=o=>U[o],se=o=>V[o],ve=o=>G[o]||4096;var b=class{constructor(e,t={}){this.validateInputs(e,t),this.apiKey=e,this.provider=t.provider??T,this.model=t.model??k}async complete({body:e,options:t}){let{completionMetadata:r}=e,{headers:n={}}=t??{};try{let i=re(r,this.model,this.provider),l=se(this.provider),s=ne(this.apiKey,this.provider),a={...n,...s},c=await R.POST(l,i,{headers:a});return ie(c,this.provider)}catch(i){return{error:d(i,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}validateInputs(e,t){if(!e)throw new Error(`Please provide ${this.provider??T} API key.`);let{provider:r,model:n}=t;if(r&&!n||!r&&n)throw new Error("Both provider and model must be specified together");let i=r??T,l=n??k;if(!D[i].includes(l)){let s=M(D[i]);throw new Error(`Model ${l} is not supported by ${i} provider. Supported models: ${s}`)}}};var O=class o{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new o(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],l=i.split(`
|
|
35
35
|
`).slice(1,-1).join(`
|
|
36
|
-
`);r=r.replace(i,
|
|
36
|
+
`);r=r.replace(i,l)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
37
37
|
|
|
38
|
-
`),this}build(){return this.formattedCompletion}};var v=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!J(this.cursorPosition,this.model)&&!Z(this.cursorPosition,this.model)}};var A=class A{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(A.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return g(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};A.MAX_CACHE_SIZE=10;var L=A;var Le="application/json",le=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:
|
|
38
|
+
`),this}build(){return this.formattedCompletion}};var v=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!J(this.cursorPosition,this.model)&&!Z(this.cursorPosition,this.model)}};var A=class A{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(A.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return g(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};A.MAX_CACHE_SIZE=10;var L=A;var Le="application/json",le=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{body:{completionMetadata:Ae({filename:o,position:l,model:i,language:t,technologies:r,externalContext:n})}},{headers:{"Content-Type":Le},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Ae=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let l=Ne(e,t),s=$(e,t),a=H(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,editorState:{completionMode:l}}},Ne=(o,e)=>{let t=$(o,e),r=H(o,e);return t&&r?"fill-in-the-middle":"completion"};var ae=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=X(o),l=y(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function pe(o){return O.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var we=300,ce=Y(le,we),N=new L,_e=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new v(t,e).shouldProvideCompletions())return u([]);let s=N.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let a=ce({...l,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{ce.cancel()});let c=await a;if(c){let p=pe(c),m=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),P=ae(p,m,t,e);return N.addCompletionCache({completion:p,range:P,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:p,range:P}])}}catch(a){if(typeof a=="string"&&(a==="Cancelled"||a==="AbortError")||a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return u([]);d(a,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},me=_e;var f=new WeakMap,E=null,de=(o,e,t)=>{E&&E.deregister();let r=[];f.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,a,c,p)=>{let m=f.get(e);if(m)return me({monaco:o,model:s,position:a,token:p,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=f.get(e);if(!a)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&c?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),N.clearCompletionCache(),f.delete(e),E=null}};return E=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),f.delete(e),E=null}}}};0&&(module.exports={Copilot,registerCopilot});
|
package/build/index.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
1
|
+
var F={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3.5-sonnet":"claude-3.5-sonnet-20240620","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307"},_={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"],anthropic:["claude-3.5-sonnet","claude-3-opus","claude-3-haiku","claude-3-sonnet"]},S="llama-3-70b",T="groq",U={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},V=.3;var j=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var x=class o{constructor(){}static getInstance(){return o.instance||(o.instance=new o),o.instance}error(e,t){console.error(this.styleMessage(t.message,e,"error")),t.stack&&console.error(this.styleStackTrace(t.stack))}warn(e,t){console.warn(this.styleMessage(t,e,"warning"))}styleMessage(e,t,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",l=100,s="\u2500".repeat(l-2),a=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((N,me)=>{let de=N.split(" "),w=[],C="";return de.forEach(q=>{(C+q).length>me&&(w.push(C.trim()),C=""),C+=q+" "}),C.trim()&&w.push(C.trim()),w})(e,l-4),P=[a,...m.map(N=>`\u2502 ${N.padEnd(l-4)} \u2502`),c].join(`
|
|
2
2
|
`);return`
|
|
3
3
|
\x1B[1m\x1B[37m[${n}]\x1B[0m${r==="error"?"\x1B[31m":"\x1B[33m"} [${t}]\x1B[0m \x1B[2m${i}\x1B[0m
|
|
4
|
-
${
|
|
4
|
+
${P}
|
|
5
5
|
`}styleStackTrace(e){return e.split(`
|
|
6
6
|
`).map((n,i)=>i===0?`\x1B[31m${n}\x1B[0m`:`\x1B[2m${n}\x1B[0m`).join(`
|
|
7
|
-
`)}getTimestamp(){return new Date().toISOString()}};var h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logger.error(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};h.instance=new h;var
|
|
8
|
-
`);return e[e.length-1].length+1};var
|
|
7
|
+
`)}getTimestamp(){return new Date().toISOString()}};var h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logger.error(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};h.instance=new h;var D=h;var d=(o,e)=>D.getInstance().handleError(o,e);var W={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var G=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},M=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var y=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],Y=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),g=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),K=o=>{let e=o.split(`
|
|
8
|
+
`);return e[e.length-1].length+1};var k=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),B=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var X=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},ue=(o,e)=>X(o,"GET",e),Ce=(o,e,t)=>X(o,"POST",{...t,body:e}),R={GET:ue,POST:Ce};var z=(o,e)=>{let t=y(o,e);return!!t&&!j.has(t)},J=(o,e)=>{let t=Y(o,e).trim(),r=g(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var I="<<CURSOR>>",Z=o=>o==="javascript"?"latest JavaScript":o,Q=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},ee=o=>{let e=Z(o.language),t=Q(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},ge=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${M(o)}`:"",r=Z(e);return`The code is written${r?` in ${r}`:""}${t}.`},oe=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=o,a=Q(n),c=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
|
|
9
9
|
|
|
10
10
|
`;return p+=ge(r,t),p+=`
|
|
11
11
|
|
|
@@ -23,16 +23,16 @@ Here are the details about how the completion should be generated:
|
|
|
23
23
|
Here's the code snippet for completion:
|
|
24
24
|
|
|
25
25
|
<code>
|
|
26
|
-
${i}${I}${
|
|
26
|
+
${i}${I}${l}
|
|
27
27
|
</code>`,s&&s.length>0&&(p+=`
|
|
28
28
|
|
|
29
29
|
Additional context from related files:
|
|
30
30
|
|
|
31
|
-
`,p+=s.map(
|
|
32
|
-
${
|
|
31
|
+
`,p+=s.map(m=>`// Path: ${m.path}
|
|
32
|
+
${m.content}
|
|
33
33
|
`).join(`
|
|
34
|
-
`)),p.endsWith(".")?p:`${p}.`};var te=(o,e,t)=>{let r=ee(o),n=oe(o),
|
|
34
|
+
`)),p.endsWith(".")?p:`${p}.`};var te=(o,e,t)=>{let r=ee(o),n=oe(o),l={model:Pe(e),temperature:V},s={openai:{messages:[{role:"system",content:r},{role:"user",content:n}]},groq:{messages:[{role:"system",content:r},{role:"user",content:n}]},anthropic:{system:r,messages:[{role:"user",content:n}],max_tokens:Te(e)}};return{...l,...s[t]}},re=(o,e)=>{let t={"Content-Type":"application/json"},r={openai:{Authorization:`Bearer ${o}`},groq:{Authorization:`Bearer ${o}`},anthropic:{"x-api-key":o,"anthropic-version":"2023-06-01"}};return{...t,...r[e]}},ne=(o,e)=>{let r={openai:he,groq:fe,anthropic:Ee}[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r(o)},he=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the openai response"},fe=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the groq response"},Ee=o=>o.content?typeof o.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:o.content}:{completion:null,error:"No completion found in the anthropic response"},Pe=o=>F[o],ie=o=>U[o],Te=o=>W[o]||4096;var $=class{constructor(e,t={}){this.validateInputs(e,t),this.apiKey=e,this.provider=t.provider??T,this.model=t.model??S}async complete({body:e,options:t}){let{completionMetadata:r}=e,{headers:n={}}=t??{};try{let i=te(r,this.model,this.provider),l=ie(this.provider),s=re(this.apiKey,this.provider),a={...n,...s},c=await R.POST(l,i,{headers:a});return ne(c,this.provider)}catch(i){return{error:d(i,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}validateInputs(e,t){if(!e)throw new Error(`Please provide ${this.provider??T} API key.`);let{provider:r,model:n}=t;if(r&&!n||!r&&n)throw new Error("Both provider and model must be specified together");let i=r??T,l=n??S;if(!_[i].includes(l)){let s=M(_[i]);throw new Error(`Model ${l} is not supported by ${i} provider. Supported models: ${s}`)}}};var b=class o{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new o(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],l=i.split(`
|
|
35
35
|
`).slice(1,-1).join(`
|
|
36
|
-
`);r=r.replace(i,
|
|
36
|
+
`);r=r.replace(i,l)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
37
37
|
|
|
38
|
-
`),this}build(){return this.formattedCompletion}};var O=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!z(this.cursorPosition,this.model)&&!J(this.cursorPosition,this.model)}};var L=class L{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(L.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return g(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};L.MAX_CACHE_SIZE=10;var v=L;var xe="application/json",se=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:
|
|
38
|
+
`),this}build(){return this.formattedCompletion}};var O=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!z(this.cursorPosition,this.model)&&!J(this.cursorPosition,this.model)}};var L=class L{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(L.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return g(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};L.MAX_CACHE_SIZE=10;var v=L;var xe="application/json",se=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await R.POST(e,{body:{completionMetadata:Me({filename:o,position:l,model:i,language:t,technologies:r,externalContext:n})}},{headers:{"Content-Type":xe},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Me=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let l=ye(e,t),s=k(e,t),a=B(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,editorState:{completionMode:l}}},ye=(o,e)=>{let t=k(o,e),r=B(o,e);return t&&r?"fill-in-the-middle":"completion"};var le=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=K(o),l=y(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function ae(o){return b.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var Re=300,pe=G(se,Re),A=new v,Ie=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new O(t,e).shouldProvideCompletions())return u([]);let s=A.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let a=pe({...l,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{pe.cancel()});let c=await a;if(c){let p=ae(c),m=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),P=le(p,m,t,e);return A.addCompletionCache({completion:p,range:P,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:p,range:P}])}}catch(a){if(typeof a=="string"&&(a==="Cancelled"||a==="AbortError")||a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return u([]);d(a,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},ce=Ie;var f=new WeakMap,E=null,be=(o,e,t)=>{E&&E.deregister();let r=[];f.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,a,c,p)=>{let m=f.get(e);if(m)return ce({monaco:o,model:s,position:a,token:p,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let a=f.get(e);if(!a)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;a.isCompletionVisible&&c?(a.isCompletionAccepted=!0,a.isCompletionVisible=!1):a.isCompletionAccepted=!1});r.push(i);let l={deregister:()=>{r.forEach(s=>s.dispose()),A.clearCompletionCache(),f.delete(e),E=null}};return E=l,l}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),f.delete(e),E=null}}}};export{$ as Copilot,be as registerCopilot};
|