monacopilot 0.9.22 → 0.9.23
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 +77 -0
- package/build/index.d.mts +45 -1
- package/build/index.d.ts +45 -1
- package/build/index.js +7 -7
- package/build/index.mjs +7 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
- [Changing the Provider and Model](#changing-the-provider-and-model)
|
|
14
14
|
- [Copilot Completion Request Options](#copilot-completion-request-options)
|
|
15
15
|
- [Custom Headers](#custom-headers)
|
|
16
|
+
- [Custom Prompt](#custom-prompt)
|
|
16
17
|
- [Configuration Options](#configuration-options)
|
|
17
18
|
- [External Context](#external-context)
|
|
18
19
|
- [Filename](#filename)
|
|
@@ -40,6 +41,8 @@ To install Monacopilot, run:
|
|
|
40
41
|
npm install monacopilot
|
|
41
42
|
```
|
|
42
43
|
|
|
44
|
+
For TypeScript users, You can import most of the types from `monacopilot` package.
|
|
45
|
+
|
|
43
46
|
## Usage
|
|
44
47
|
|
|
45
48
|
#### Setting Up the API Key
|
|
@@ -145,6 +148,80 @@ copilot.complete({
|
|
|
145
148
|
});
|
|
146
149
|
```
|
|
147
150
|
|
|
151
|
+
### Custom Prompt
|
|
152
|
+
|
|
153
|
+
You can customize the prompt used for generating completions by providing a `customPrompt` function in the options parameter of the `copilot.complete` method. This allows you to tailor the AI's behavior to your specific needs.
|
|
154
|
+
|
|
155
|
+
#### Usage
|
|
156
|
+
|
|
157
|
+
```javascript
|
|
158
|
+
copilot.complete({
|
|
159
|
+
body,
|
|
160
|
+
options: {
|
|
161
|
+
customPrompt: metadata => ({
|
|
162
|
+
system: 'Your custom system prompt here',
|
|
163
|
+
user: 'Your custom user prompt here',
|
|
164
|
+
}),
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
#### Parameters
|
|
170
|
+
|
|
171
|
+
The `customPrompt` function receives a `completionMetadata` object with the following properties:
|
|
172
|
+
|
|
173
|
+
| Property | Type | Description |
|
|
174
|
+
| ---------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
175
|
+
| language | string | The programming language of the code |
|
|
176
|
+
| cursorPosition | {lineNumber: number, column: number} | The current cursor position in the editor |
|
|
177
|
+
| filename | string \| undefined | The name of the file being edited. Only available if you have provided the `filename` option in the `registerCopilot` function. |
|
|
178
|
+
| technologies | string[] \| undefined | An array of technologies used in the project. Only available if you have provided the `technologies` option in the `registerCopilot` function. |
|
|
179
|
+
| externalContext | object \| undefined | Additional context from related files. Only available if you have provided the `externalContext` option in the `registerCopilot` function. |
|
|
180
|
+
| textAfterCursor | string | The text that appears after the cursor |
|
|
181
|
+
| textBeforeCursor | string | The text that appears before the cursor |
|
|
182
|
+
| editorState | object | An object containing the `completionMode` property |
|
|
183
|
+
|
|
184
|
+
The `editorState.completionMode` can be one of the following:
|
|
185
|
+
|
|
186
|
+
| Mode | Description |
|
|
187
|
+
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
188
|
+
| fill-in-the-middle | Indicates that the cursor is positioned within the existing text. In this mode, the AI will generate content to be inserted at the cursor position. |
|
|
189
|
+
| completion | Indicates that the cursor is at the end of the existing text. In this mode, the AI will generate content to continue or complete the text from the cursor position. |
|
|
190
|
+
|
|
191
|
+
For additional `completionMetadata` needs, please [open an issue](https://github.com/arshad-yaseen/monacopilot/issues/new).
|
|
192
|
+
|
|
193
|
+
The `customPrompt` function should return an object with two properties:
|
|
194
|
+
|
|
195
|
+
| Property | Type | Description |
|
|
196
|
+
| -------- | ------ | ----------------------------------------------------- |
|
|
197
|
+
| system | string | A string representing the system prompt for the model |
|
|
198
|
+
| user | string | A string representing the user prompt for the model |
|
|
199
|
+
|
|
200
|
+
#### Example
|
|
201
|
+
|
|
202
|
+
Here's an example of a custom prompt that focuses on generating React component code:
|
|
203
|
+
|
|
204
|
+
```javascript
|
|
205
|
+
const customPrompt = ({textBeforeCursor, textAfterCursor}) => ({
|
|
206
|
+
system:
|
|
207
|
+
'You are an AI assistant specialized in writing React components. Focus on creating clean, reusable, and well-structured components.',
|
|
208
|
+
user: `Please complete the following React component:
|
|
209
|
+
|
|
210
|
+
${textBeforeCursor}
|
|
211
|
+
// Cursor position
|
|
212
|
+
${textAfterCursor}
|
|
213
|
+
|
|
214
|
+
Use modern React practices and hooks where appropriate. If you're adding new props, make sure to include proper TypeScript types. Please provide only the finished code without additional comments or explanations.`,
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
copilot.complete({
|
|
218
|
+
body,
|
|
219
|
+
options: {customPrompt},
|
|
220
|
+
});
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
By using a custom prompt, you can guide the model to generate completions that better fit your coding style, project requirements, or specific technologies you're working with.
|
|
224
|
+
|
|
148
225
|
## Configuration Options
|
|
149
226
|
|
|
150
227
|
### External Context
|
package/build/index.d.mts
CHANGED
|
@@ -2,6 +2,7 @@ import * as monaco from 'monaco-editor';
|
|
|
2
2
|
|
|
3
3
|
type Monaco = typeof monaco;
|
|
4
4
|
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
5
|
+
type CursorPosition = monaco.IPosition;
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Options for configuring the Copilot instance.
|
|
@@ -102,20 +103,63 @@ interface CompletionRequestOptions {
|
|
|
102
103
|
* Additional headers to include in the provider's completion requests.
|
|
103
104
|
*/
|
|
104
105
|
headers?: Record<string, string>;
|
|
106
|
+
/**
|
|
107
|
+
* Custom prompt generator function for the completion request.
|
|
108
|
+
* This function allows you to override the default system and user prompts
|
|
109
|
+
* used in the completion request, providing more control over the AI's context and behavior.
|
|
110
|
+
*
|
|
111
|
+
* @param completionMetadata - Metadata about the current completion context
|
|
112
|
+
* @returns An object containing custom 'system' and 'user' prompts
|
|
113
|
+
*/
|
|
114
|
+
customPrompt?: CustomPrompt;
|
|
105
115
|
}
|
|
116
|
+
type CustomPrompt = (completionMetadata: CompletionMetadata) => {
|
|
117
|
+
system: string;
|
|
118
|
+
user: string;
|
|
119
|
+
};
|
|
106
120
|
interface CompletionResponse {
|
|
107
121
|
completion: string | null;
|
|
108
122
|
error?: string;
|
|
109
123
|
}
|
|
110
124
|
type CompletionMode = 'fill-in-the-middle' | 'completion';
|
|
111
125
|
interface CompletionMetadata {
|
|
126
|
+
/**
|
|
127
|
+
* The programming language of the code.
|
|
128
|
+
*/
|
|
112
129
|
language: string | undefined;
|
|
130
|
+
/**
|
|
131
|
+
* The name of the file being edited.
|
|
132
|
+
*/
|
|
113
133
|
filename: Filename | undefined;
|
|
134
|
+
/**
|
|
135
|
+
* The technologies used in the completion.
|
|
136
|
+
*/
|
|
114
137
|
technologies: Technologies | undefined;
|
|
138
|
+
/**
|
|
139
|
+
* Additional context from related files.
|
|
140
|
+
*/
|
|
115
141
|
externalContext: ExternalContext | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* The text that appears after the cursor.
|
|
144
|
+
*/
|
|
116
145
|
textAfterCursor: string;
|
|
146
|
+
/**
|
|
147
|
+
* The text that appears before the cursor.
|
|
148
|
+
*/
|
|
117
149
|
textBeforeCursor: string;
|
|
150
|
+
/**
|
|
151
|
+
* The current cursor position.
|
|
152
|
+
*/
|
|
153
|
+
cursorPosition: CursorPosition | undefined;
|
|
154
|
+
/**
|
|
155
|
+
* The current state of the editor.
|
|
156
|
+
*/
|
|
118
157
|
editorState: {
|
|
158
|
+
/**
|
|
159
|
+
* The mode of the completion.
|
|
160
|
+
* - `fill-in-the-middle`: Indicates that the cursor is positioned within the existing text. In this mode, the AI will generate content to be inserted at the cursor position.
|
|
161
|
+
* - `completion`: Indicates that the cursor is at the end of the existing text. In this mode, the AI will generate content to continue or complete the text from the cursor position.
|
|
162
|
+
*/
|
|
119
163
|
completionMode: CompletionMode;
|
|
120
164
|
};
|
|
121
165
|
}
|
|
@@ -151,4 +195,4 @@ declare class Copilot {
|
|
|
151
195
|
*/
|
|
152
196
|
declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
|
|
153
197
|
|
|
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 };
|
|
198
|
+
export { type CompletionMetadata, 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
|
@@ -2,6 +2,7 @@ import * as monaco from 'monaco-editor';
|
|
|
2
2
|
|
|
3
3
|
type Monaco = typeof monaco;
|
|
4
4
|
type StandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
|
|
5
|
+
type CursorPosition = monaco.IPosition;
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Options for configuring the Copilot instance.
|
|
@@ -102,20 +103,63 @@ interface CompletionRequestOptions {
|
|
|
102
103
|
* Additional headers to include in the provider's completion requests.
|
|
103
104
|
*/
|
|
104
105
|
headers?: Record<string, string>;
|
|
106
|
+
/**
|
|
107
|
+
* Custom prompt generator function for the completion request.
|
|
108
|
+
* This function allows you to override the default system and user prompts
|
|
109
|
+
* used in the completion request, providing more control over the AI's context and behavior.
|
|
110
|
+
*
|
|
111
|
+
* @param completionMetadata - Metadata about the current completion context
|
|
112
|
+
* @returns An object containing custom 'system' and 'user' prompts
|
|
113
|
+
*/
|
|
114
|
+
customPrompt?: CustomPrompt;
|
|
105
115
|
}
|
|
116
|
+
type CustomPrompt = (completionMetadata: CompletionMetadata) => {
|
|
117
|
+
system: string;
|
|
118
|
+
user: string;
|
|
119
|
+
};
|
|
106
120
|
interface CompletionResponse {
|
|
107
121
|
completion: string | null;
|
|
108
122
|
error?: string;
|
|
109
123
|
}
|
|
110
124
|
type CompletionMode = 'fill-in-the-middle' | 'completion';
|
|
111
125
|
interface CompletionMetadata {
|
|
126
|
+
/**
|
|
127
|
+
* The programming language of the code.
|
|
128
|
+
*/
|
|
112
129
|
language: string | undefined;
|
|
130
|
+
/**
|
|
131
|
+
* The name of the file being edited.
|
|
132
|
+
*/
|
|
113
133
|
filename: Filename | undefined;
|
|
134
|
+
/**
|
|
135
|
+
* The technologies used in the completion.
|
|
136
|
+
*/
|
|
114
137
|
technologies: Technologies | undefined;
|
|
138
|
+
/**
|
|
139
|
+
* Additional context from related files.
|
|
140
|
+
*/
|
|
115
141
|
externalContext: ExternalContext | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* The text that appears after the cursor.
|
|
144
|
+
*/
|
|
116
145
|
textAfterCursor: string;
|
|
146
|
+
/**
|
|
147
|
+
* The text that appears before the cursor.
|
|
148
|
+
*/
|
|
117
149
|
textBeforeCursor: string;
|
|
150
|
+
/**
|
|
151
|
+
* The current cursor position.
|
|
152
|
+
*/
|
|
153
|
+
cursorPosition: CursorPosition | undefined;
|
|
154
|
+
/**
|
|
155
|
+
* The current state of the editor.
|
|
156
|
+
*/
|
|
118
157
|
editorState: {
|
|
158
|
+
/**
|
|
159
|
+
* The mode of the completion.
|
|
160
|
+
* - `fill-in-the-middle`: Indicates that the cursor is positioned within the existing text. In this mode, the AI will generate content to be inserted at the cursor position.
|
|
161
|
+
* - `completion`: Indicates that the cursor is at the end of the existing text. In this mode, the AI will generate content to continue or complete the text from the cursor position.
|
|
162
|
+
*/
|
|
119
163
|
completionMode: CompletionMode;
|
|
120
164
|
};
|
|
121
165
|
}
|
|
@@ -151,4 +195,4 @@ declare class Copilot {
|
|
|
151
195
|
*/
|
|
152
196
|
declare const registerCopilot: (monaco: Monaco, editor: StandaloneCodeEditor, options: RegisterCopilotOptions) => CopilotRegistration;
|
|
153
197
|
|
|
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 };
|
|
198
|
+
export { type CompletionMetadata, 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,11 +1,11 @@
|
|
|
1
|
-
"use strict";var S=Object.defineProperty;var
|
|
1
|
+
"use strict";var S=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var he=Object.prototype.hasOwnProperty;var fe=(o,e)=>{for(var t in e)S(o,t,{get:e[t],enumerable:!0})},Ee=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ge(e))!he.call(o,n)&&n!==t&&S(o,n,{get:()=>e[n],enumerable:!(r=Ce(e,n))||r.enumerable});return o};var Pe=o=>Ee(S({},"__esModule",{value:!0}),o);var De={};fe(De,{Copilot:()=>O,registerCopilot:()=>me});module.exports=Pe(De);var V={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini","claude-3.5-sonnet":"claude-3.5-sonnet-20240620","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307"},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",j={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions",anthropic:"https://api.anthropic.com/v1/messages"},W=.3;var G=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var x=class o{constructor(){}static getInstance(){return o.instance||(o.instance=new o),o.instance}error(e,t){console.error(this.styleMessage(t.message,e,"error")),t.stack&&console.error(this.styleStackTrace(t.stack))}warn(e,t){console.warn(this.styleMessage(t,e,"warning"))}styleMessage(e,t,r){let n=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",a=100,s="\u2500".repeat(a-2),l=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((w,de)=>{let ue=w.split(" "),_=[],C="";return ue.forEach(U=>{(C+U).length>de&&(_.push(C.trim()),C=""),C+=U+" "}),C.trim()&&_.push(C.trim()),_})(e,a-4),P=[l,...m.map(w=>`\u2502 ${w.padEnd(a-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
|
|
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
|
|
7
|
+
`)}getTimestamp(){return new Date().toISOString()}};var h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logger.error(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};h.instance=new h;var B=h;var d=(o,e)=>B.getInstance().handleError(o,e);var Y={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var K=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((a,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{a(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],X=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),g=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),z=o=>{let e=o.split(`
|
|
8
|
+
`);return e[e.length-1].length+1};var $=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),H=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var J=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},Te=(o,e)=>J(o,"GET",e),xe=(o,e,t)=>J(o,"POST",{...t,body:e}),R={GET:Te,POST:xe};var Z=(o,e)=>{let t=y(o,e);return!!t&&!G.has(t)},Q=(o,e)=>{let t=X(o,e).trim(),r=g(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var I="<<CURSOR>>",ee=o=>o==="javascript"?"latest JavaScript":o,oe=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Me=o=>{let e=ee(o.language),t=oe(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},ye=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${M(o)}`:"",r=ee(e);return`The code is written${r?` in ${r}`:""}${t}.`},Re=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:a,externalContext:s}=o,l=oe(n),c=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${l} for a code snippet. The code is part of ${c}.
|
|
9
9
|
|
|
10
10
|
`;return p+=ye(r,t),p+=`
|
|
11
11
|
|
|
@@ -23,7 +23,7 @@ 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}${a}
|
|
27
27
|
</code>`,s&&s.length>0&&(p+=`
|
|
28
28
|
|
|
29
29
|
Additional context from related files:
|
|
@@ -31,8 +31,8 @@ Additional context from related files:
|
|
|
31
31
|
`,p+=s.map(m=>`// Path: ${m.path}
|
|
32
32
|
${m.content}
|
|
33
33
|
`).join(`
|
|
34
|
-
`)),p.endsWith(".")?p:`${p}.`};var
|
|
34
|
+
`)),p.endsWith(".")?p:`${p}.`};function q(o){return{system:Me(o),user:Re(o)}}var te=(o,e,t,r)=>{let{system:n,user:i}=r?r(o):q(o),a={model:ve(e),temperature:W},s=[{role:"system",content:n},{role:"user",content:i}],l={openai:{messages:s},groq:{messages:s},anthropic:{system:n,messages:[{role:"user",content:i}],max_tokens:Le(e)}};return{...a,...l[t]}},re=(o,e)=>{let t={"Content-Type":"application/json"},r={openai:{Authorization:`Bearer ${o}`},groq:{Authorization:`Bearer ${o}`},anthropic:{"x-api-key":o,"anthropic-version":"2023-06-01"}};return{...t,...r[e]}},ne=(o,e)=>{let r={openai:Ie,groq:Oe,anthropic:be}[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r(o)},Ie=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the openai response"},Oe=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the groq response"},be=o=>o.content?typeof o.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:o.content}:{completion:null,error:"No completion found in the anthropic response"},ve=o=>V[o],ie=o=>j[o],Le=o=>Y[o]||4096;var O=class{constructor(e,t={}){this.validateInputs(e,t),this.apiKey=e,this.provider=t.provider??T,this.model=t.model??k}async complete({body:e,options:t}){let{completionMetadata:r}=e,{headers:n={},customPrompt:i}=t??{};try{let a=te(r,this.model,this.provider,i),s=ie(this.provider),l=re(this.apiKey,this.provider),c={...n,...l},p=await R.POST(s,a,{headers:c});return ne(p,this.provider)}catch(a){return{error:d(a,"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,a=n??k;if(!D[i].includes(a)){let s=M(D[i]);throw new Error(`Model ${a} 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],a=i.split(`
|
|
35
35
|
`).slice(1,-1).join(`
|
|
36
|
-
`);r=r.replace(i,
|
|
36
|
+
`);r=r.replace(i,a)}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!
|
|
38
|
+
`),this}build(){return this.formattedCompletion}};var v=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!Z(this.cursorPosition,this.model)&&!Q(this.cursorPosition,this.model)}};var A=class A{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(A.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return g(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};A.MAX_CACHE_SIZE=10;var L=A;var Ae="application/json",se=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:a})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:Ne({filename:o,position:a,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":Ae},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Ne=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let a=we(e,t),s=$(e,t),l=H(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:l,cursorPosition:e,editorState:{completionMode:a}}},we=(o,e)=>{let t=$(o,e),r=H(o,e);return t&&r?"fill-in-the-middle":"completion"};var le=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=z(o),a=y(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(a)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function ae(o){return b.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var _e=300,pe=K(se,_e),N=new L,Se=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:a})=>{if(!new v(t,e).shouldProvideCompletions())return u([]);let s=N.getCompletionCache(t,e).map(l=>({insertText:l.completion,range:l.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let l=pe({...a,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{pe.cancel()});let c=await l;if(c){let p=ae(c),m=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),P=le(p,m,t,e);return N.addCompletionCache({completion:p,range:P,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:p,range:P}])}}catch(l){if(typeof l=="string"&&(l==="Cancelled"||l==="AbortError")||l instanceof Error&&(l.message==="Cancelled"||l.name==="AbortError"))return u([]);d(l,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},ce=Se;var f=new WeakMap,E=null,me=(o,e,t)=>{E&&E.deregister();let r=[];f.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,l,c,p)=>{let m=f.get(e);if(m)return ce({monaco:o,model:s,position:l,token:p,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let l=f.get(e);if(!l)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;l.isCompletionVisible&&c?(l.isCompletionAccepted=!0,l.isCompletionVisible=!1):l.isCompletionAccepted=!1});r.push(i);let a={deregister:()=>{r.forEach(s=>s.dispose()),N.clearCompletionCache(),f.delete(e),E=null}};return E=a,a}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 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"},_={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",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.",a=100,s="\u2500".repeat(a-2),l=`\u250C${s}\u2510`,c=`\u2514${s}\u2518`,m=((N,ce)=>{let me=N.split(" "),w=[],C="";return me.forEach(F=>{(C+F).length>ce&&(w.push(C.trim()),C=""),C+=F+" "}),C.trim()&&w.push(C.trim()),w})(e,a-4),P=[l,...m.map(N=>`\u2502 ${N.padEnd(a-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 D=h;var d=(o,e)=>D.getInstance().handleError(o,e);var
|
|
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
|
|
7
|
+
`)}getTimestamp(){return new Date().toISOString()}};var h=class h{constructor(){this.logger=x.getInstance()}static getInstance(){return h.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logger.error(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}};h.instance=new h;var D=h;var d=(o,e)=>D.getInstance().handleError(o,e);var G={"claude-3.5-sonnet":8192,"claude-3-opus":4096,"claude-3-haiku":4096,"claude-3-sonnet":4096};var Y=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((a,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{a(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 k=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),B=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var z=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},de=(o,e)=>z(o,"GET",e),ue=(o,e,t)=>z(o,"POST",{...t,body:e}),R={GET:de,POST:ue};var J=(o,e)=>{let t=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"}},Ce=o=>{let e=Q(o.language),t=ee(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},ge=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${M(o)}`:"",r=Q(e);return`The code is written${r?` in ${r}`:""}${t}.`},he=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:a,externalContext:s}=o,l=ee(n),c=e?`the file named "${e}"`:"a larger project",p=`You are tasked with ${l} for a code snippet. The code is part of ${c}.
|
|
9
9
|
|
|
10
10
|
`;return p+=ge(r,t),p+=`
|
|
11
11
|
|
|
@@ -23,7 +23,7 @@ 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}${a}
|
|
27
27
|
</code>`,s&&s.length>0&&(p+=`
|
|
28
28
|
|
|
29
29
|
Additional context from related files:
|
|
@@ -31,8 +31,8 @@ Additional context from related files:
|
|
|
31
31
|
`,p+=s.map(m=>`// Path: ${m.path}
|
|
32
32
|
${m.content}
|
|
33
33
|
`).join(`
|
|
34
|
-
`)),p.endsWith(".")?p:`${p}.`};var
|
|
34
|
+
`)),p.endsWith(".")?p:`${p}.`};function $(o){return{system:Ce(o),user:he(o)}}var oe=(o,e,t,r)=>{let{system:n,user:i}=r?r(o):$(o),a={model:Te(e),temperature:j},s=[{role:"system",content:n},{role:"user",content:i}],l={openai:{messages:s},groq:{messages:s},anthropic:{system:n,messages:[{role:"user",content:i}],max_tokens:xe(e)}};return{...a,...l[t]}},te=(o,e)=>{let t={"Content-Type":"application/json"},r={openai:{Authorization:`Bearer ${o}`},groq:{Authorization:`Bearer ${o}`},anthropic:{"x-api-key":o,"anthropic-version":"2023-06-01"}};return{...t,...r[e]}},re=(o,e)=>{let r={openai:fe,groq:Ee,anthropic:Pe}[e];if(!r)throw new Error(`Unsupported provider: ${e}`);return r(o)},fe=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the openai response"},Ee=o=>o.choices?.length?{completion:o.choices[0].message.content}:{completion:null,error:"No completion found in the groq response"},Pe=o=>o.content?typeof o.content!="string"?{completion:null,error:"Completion content is not a string"}:{completion:o.content}:{completion:null,error:"No completion found in the anthropic response"},Te=o=>U[o],ne=o=>V[o],xe=o=>G[o]||4096;var H=class{constructor(e,t={}){this.validateInputs(e,t),this.apiKey=e,this.provider=t.provider??T,this.model=t.model??S}async complete({body:e,options:t}){let{completionMetadata:r}=e,{headers:n={},customPrompt:i}=t??{};try{let a=oe(r,this.model,this.provider,i),s=ne(this.provider),l=te(this.apiKey,this.provider),c={...n,...l},p=await R.POST(s,a,{headers:c});return re(p,this.provider)}catch(a){return{error:d(a,"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,a=n??S;if(!_[i].includes(a)){let s=M(_[i]);throw new Error(`Model ${a} 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],a=i.split(`
|
|
35
35
|
`).slice(1,-1).join(`
|
|
36
|
-
`);r=r.replace(i,
|
|
36
|
+
`);r=r.replace(i,a)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
|
|
37
37
|
|
|
38
|
-
`),this}build(){return this.formattedCompletion}};var
|
|
38
|
+
`),this}build(){return this.formattedCompletion}};var b=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!J(this.cursorPosition,this.model)&&!Z(this.cursorPosition,this.model)}};var L=class L{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(L.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return g(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};L.MAX_CACHE_SIZE=10;var v=L;var Me="application/json",ie=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:a})=>{try{let{completion:s}=await R.POST(e,{completionMetadata:ye({filename:o,position:a,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":Me},error:"Error while fetching completion item"});return s}catch(s){return d(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},ye=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let a=Re(e,t),s=k(e,t),l=B(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:l,cursorPosition:e,editorState:{completionMode:a}}},Re=(o,e)=>{let t=k(o,e),r=B(o,e);return t&&r?"fill-in-the-middle":"completion"};var se=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=X(o),a=y(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(a)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function le(o){return O.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var u=o=>({items:o,enableForwardStability:!0});var Ie=300,ae=Y(ie,Ie),A=new v,Oe=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:a})=>{if(!new b(t,e).shouldProvideCompletions())return u([]);let s=A.getCompletionCache(t,e).map(l=>({insertText:l.completion,range:l.range}));if(s.length)return i(),u(s);if(r.isCancellationRequested||n)return u([]);try{let l=ae({...a,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{ae.cancel()});let c=await l;if(c){let p=le(c),m=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),P=se(p,m,t,e);return A.addCompletionCache({completion:p,range:P,textBeforeCursorInLine:g(t,e)}),i(),u([{insertText:p,range:P}])}}catch(l){if(typeof l=="string"&&(l==="Cancelled"||l==="AbortError")||l instanceof Error&&(l.message==="Cancelled"||l.name==="AbortError"))return u([]);d(l,"FETCH_COMPLETION_ITEM_ERROR")}return u([])},pe=Oe;var f=new WeakMap,E=null,be=(o,e,t)=>{E&&E.deregister();let r=[];f.set(e,{isCompletionAccepted:!1,isCompletionVisible:!1});try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,l,c,p)=>{let m=f.get(e);if(m)return pe({monaco:o,model:s,position:l,token:p,isCompletionAccepted:m.isCompletionAccepted,onShowCompletion:()=>{m.isCompletionVisible=!0},options:t})},freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let l=f.get(e);if(!l)return;let c=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;l.isCompletionVisible&&c?(l.isCompletionAccepted=!0,l.isCompletionVisible=!1):l.isCompletionAccepted=!1});r.push(i);let a={deregister:()=>{r.forEach(s=>s.dispose()),A.clearCompletionCache(),f.delete(e),E=null}};return E=a,a}catch(n){return d(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose()),f.delete(e),E=null}}}};export{H as Copilot,be as registerCopilot};
|