File size: 5,642 Bytes
b5cf8f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d72d60
b5cf8f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a90d86
b5cf8f3
 
 
 
 
 
3d5c0f9
b5cf8f3
 
 
 
 
 
 
 
 
 
 
0317226
 
b5cf8f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { fetchSSE } from './fetch-sse';

interface llmParams {
  model?: string;
  temperature?: number;
  max_tokens?: number;
  top_p?: number;
  frequency_penalty?: number;
  presence_penalty?: number;
  stop?: Array<string>;
}

type CursorStyle =
  | 'line'
  | 'block'
  | 'underline'
  | 'line-thin'
  | 'block-outline'
  | 'underline-thin';

export interface Config {
  llmKey?: string;
  llmUrl?: string;
  llmParams?: llmParams;
  customCompletionFunction?: (code: string) => Promise<string>;
  maxCodeLinesTollm?: number;
  cursorStyleLoading?: CursorStyle;
  cursorStyleNormal?: CursorStyle;
  assistantMessage?: string;
}

export const defaultllmParams: llmParams = {
  model: '',
  temperature: 0,
  max_tokens: 64,
  top_p: 1.0,
  frequency_penalty: 0.0,
  presence_penalty: 0.0,
};

export const defaultConfig: Config = {
  llmKey: '',
  llmUrl: 'https://matthoffner-ggml-coding-llm.hf.space/completion',
  llmParams: defaultllmParams,
  cursorStyleLoading: 'underline',
  cursorStyleNormal: 'line',
  assistantMessage: '',
};

function minimizeWhitespace(code:string) {
  return code
    .split('\n')
    .map((line:string) => line.trim())
    .join('\n');
}

async function fetchCompletionFromllm(
  code: string,
  config: Config,
  controller: AbortController,
  handleInsertion: (text: string) => void
): Promise<void> {
  const handleMessage = (message: string) => {
    handleInsertion(message);
  };

  let text = ''

  return new Promise(async (resolve, reject) => {
    await fetchSSE(config.llmUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: `Bearer ${config.llmKey}`,
      },
      body: JSON.stringify({
        prompt: code,
        ...config.llmParams,
      }),
      signal: controller.signal,
      onMessage: (data) => {
        let lastResponse;
        if (data === "[DONE]") {
          text = text.trim();
          return resolve();
        }
        try {
          const response = JSON.parse(data);
          if ((lastResponse = response == null ? void 0 : response) == null ? void 0 : lastResponse.length) {
            text += response || '';
            handleMessage == null ? void 0 : handleMessage(text);
          }
        } catch (err) {
          console.warn("llm stream SEE event unexpected error", err);
          return reject(err);
        }
      },
      onError: (error: any) => {
        console.error(error);
      }
    });
  })
}

const handleCompletion = async (
  editor: monaco.editor.IStandaloneCodeEditor,
  config: Config,
  controller: AbortController,
  cursorStyleLoading: () => void,
  cursorStyleNormal: () => void
) => {
  const currentPosition = editor.getPosition();
  if (!currentPosition) {
    return;
  }
  const currentLineNumber = currentPosition.lineNumber;
  const startLineNumber = !config.maxCodeLinesTollm
    ? 1
    : Math.max(1, currentLineNumber - config.maxCodeLinesTollm);
  const endLineNumber = currentLineNumber;
  const code = editor
    .getModel()!
    .getLinesContent()
    .slice(startLineNumber - 1, endLineNumber)
    .join('\n');

  cursorStyleLoading();


  let lastText = ''
  const handleInsertion = (text: string) => {
    const position = editor.getPosition();
    if (!position) {
      return;
    }
    const offset = editor.getModel()?.getOffsetAt(position);
    if (!offset) {
      return;
    }

    const edits = [
      {
        range: {
          startLineNumber: position.lineNumber,
          startColumn: position.column,
          endLineNumber: position.lineNumber,
          endColumn: position.column,
        },
        text: text.slice(lastText.length),
      },
    ];

    lastText = text
    editor.executeEdits('', edits);
  };


  try {
    let newCode = '';
    if (config.customCompletionFunction) {
      newCode = await config.customCompletionFunction(code);
      handleInsertion(newCode);
    } else {
      await fetchCompletionFromllm(code, config, controller, handleInsertion);
    }
    cursorStyleNormal();
  } catch (error) {
    cursorStyleNormal();
    console.error('MonacoEditorCopilot error:', error);
  }
};

const MonacoEditorCopilot = (
  editor: monaco.editor.IStandaloneCodeEditor,
  config: Config
) => {
  const mergedConfig: Config = {
    ...defaultConfig,
    ...config,
    llmParams: { ...defaultllmParams, ...config.llmParams },
  };

  const cursorStyleLoading = () => {
    editor.updateOptions({ cursorStyle: mergedConfig.cursorStyleLoading });
  };

  const cursorStyleNormal = () => {
    editor.updateOptions({ cursorStyle: mergedConfig.cursorStyleNormal });
  };

  cursorStyleNormal();

  let controller: AbortController | null = null;

  const cancel  = () => {
    if (controller) {
      controller.abort();
    }
    cursorStyleNormal();
  }

  const keyDownHandler =  editor.onKeyDown(cancel);
  const mouseDownHandler = editor.onMouseDown(cancel);

  let copilotAction: monaco.editor.IActionDescriptor | null = {
    id: 'copilot-completion',
    label: 'Trigger Copilot Completion',
    keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyB],
    contextMenuGroupId: 'navigation',
    contextMenuOrder: 1.5,
    run: async () => {
      controller = new AbortController();
      await handleCompletion(
        editor,
        mergedConfig,
        controller,
        cursorStyleLoading,
        cursorStyleNormal
      );
    },
  };

  editor.addAction(copilotAction);

  const dispose = () => {
    keyDownHandler.dispose();
    mouseDownHandler.dispose();
  };

  return dispose;
};

export default MonacoEditorCopilot;