Skip to content

Commit dae27f9

Browse files
committed
Add auth flow and download server bin
1 parent 254e3a7 commit dae27f9

6 files changed

Lines changed: 322 additions & 77 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
bin/

autoload/codeium.vim

Lines changed: 49 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
let g:_codeium_version = '1.0.0'
2-
let g:ide = 'jetbrains'
3-
let g:api_key = ''
4-
51
let s:hlgroup = 'CodeiumSuggestion'
62
let s:annot_hlgroup = 'CodeiumAnnotation'
73
let s:request_nonce = 0
@@ -13,13 +9,6 @@ if empty(prop_type_get(s:annot_hlgroup))
139
call prop_type_add(s:annot_hlgroup, {'highlight': s:annot_hlgroup})
1410
endif
1511

16-
function! s:Log(str) abort
17-
let fname = expand('~') . '/codeium.log'
18-
execute 'redir >> ' . l:fname
19-
echo a:str
20-
redir END
21-
endfunction
22-
2312
function! codeium#CompletionText() abort
2413
try
2514
return remove(s:, 'completion_text')
@@ -65,23 +54,28 @@ function! codeium#Accept() abort
6554
let delete_text = move_to_end . "\<C-O>d0" . move_to_start . repeat("\<C-O>DJ", end_row - start_row) . "\<C-O>dl"
6655
endif
6756

57+
call codeium#server#Request('AcceptCompletion', {'metadata': codeium#server#RequestMetadata(), "completion_id": current_completion.completion.completion_id})
6858
return delete_text . insert_text
6959
endif
7060

7161
return default
7262
endfunction
7363

7464
function! s:HandleCompletionsResult(out, status) abort
75-
let response_text = join(a:out, '')
76-
if empty(response_text)
77-
call s:Log('Null response')
78-
elseif exists('b:_codeium_completions')
79-
let response = json_decode(response_text)
80-
let completionItems = response->get('completionItems', [])
81-
82-
let b:_codeium_completions.items = completionItems
83-
let b:_codeium_completions.index = 0
84-
call s:RenderCurrentCompletion()
65+
if exists('b:_codeium_completions')
66+
let response_text = join(a:out, '')
67+
try
68+
let response = json_decode(response_text)
69+
let completionItems = response->get('completionItems', [])
70+
71+
let b:_codeium_completions.items = completionItems
72+
let b:_codeium_completions.index = 0
73+
74+
call s:RenderCurrentCompletion()
75+
catch
76+
call codeium#log#Error("Invalid response from language server")
77+
call codeium#log#Exception()
78+
endtry
8579
endif
8680
endfunction
8781

@@ -111,7 +105,7 @@ function! s:RenderCurrentCompletion() abort
111105
let start_offset = current_completion.range->get('startOffset', 0)
112106
let [start_row, start_col] = codeium#util#OffsetToPosition(start_offset + 1)
113107
if start_row != line('.')
114-
call s:Log("Ignoring completion, line number is not the current line.")
108+
call codeium#log#Info("Ignoring completion, line number is not the current line.")
115109
return ''
116110
endif
117111

@@ -147,46 +141,20 @@ function! s:RenderCurrentCompletion() abort
147141
endfor
148142
endfunction
149143

150-
function! s:GetCompletionRequestData() abort
151-
let metadata = {
152-
\ "api_key": g:api_key,
153-
\ "ide_name": g:ide,
154-
\ "extension_version": g:_codeium_version,
155-
\ }
156-
157-
let document = codeium#doc#GetCurrentDocument()
158-
let editor_options = codeium#doc#GetEditorOptions()
159-
160-
let api_server_params = {
161-
\ "api_timeout_ms": 5000,
162-
\ "first_temperature":0.2,
163-
\ "max_completions": 10,
164-
\ "max_newlines":20,
165-
\ "max_tokens":256,
166-
\ "min_log_probability":-15.0,
167-
\ "temperature":0.2,
168-
\ "top_k":50,
169-
\ "top_p":1.0
170-
\ }
171-
172-
return {
173-
\ "metadata": metadata,
174-
\ "document": document,
175-
\ "editor_options": editor_options,
176-
\ "api_server_params": api_server_params
177-
\ }
178-
endfunction
179-
180144
function! codeium#Clear(...) abort
181145
if exists('g:_codeium_timer')
182146
call timer_stop(remove(g:, '_codeium_timer'))
183147
endif
184148

185-
" Cancel anny existing request.
149+
" Cancel any existing request.
186150
if exists('b:_codeium_completions')
187151
let request_id = b:_codeium_completions->get('request_id', 0)
188152
if request_id > 0
189-
call codeium#server#Request('42100', 'CancelRequest', {'request_id': request_id})
153+
try
154+
call codeium#server#Request('CancelRequest', {'request_id': request_id})
155+
catch
156+
call codeium#log#Exception()
157+
endtry
190158
endif
191159
call s:RenderCurrentCompletion()
192160
unlet! b:_codeium_completions
@@ -235,7 +203,23 @@ function! codeium#Complete(...) abort
235203
call timer_stop(remove(g:, '_codeium_timer'))
236204
endif
237205

238-
let data = s:GetCompletionRequestData()
206+
let data = {
207+
\ "metadata": codeium#server#RequestMetadata(),
208+
\ "document": codeium#doc#GetCurrentDocument(),
209+
\ "editor_options": codeium#doc#GetEditorOptions(),
210+
\ "api_server_params": {
211+
\ "api_timeout_ms": 5000,
212+
\ "first_temperature":0.2,
213+
\ "max_completions": 10,
214+
\ "max_newlines":20,
215+
\ "max_tokens":256,
216+
\ "min_log_probability":-15.0,
217+
\ "temperature":0.2,
218+
\ "top_k":50,
219+
\ "top_p":1.0
220+
\ }
221+
\ }
222+
239223
if exists('b:_codeium_completions.request_data') && b:_codeium_completions.request_data ==# data
240224
return
241225
endif
@@ -247,13 +231,17 @@ function! codeium#Complete(...) abort
247231
let request_id = s:request_nonce
248232
let data.metadata.request_id = request_id
249233

250-
let request_job = codeium#server#Request('42100', 'GetCompletions', data, function('s:HandleCompletionsResult', []))
234+
try
235+
let request_job = codeium#server#Request('GetCompletions', data, function('s:HandleCompletionsResult', []))
251236

252-
let b:_codeium_completions = {
253-
\ "request_data": request_data,
254-
\ "request_id": request_id,
255-
\ "job": request_job
256-
\ }
237+
let b:_codeium_completions = {
238+
\ "request_data": request_data,
239+
\ "request_id": request_id,
240+
\ "job": request_job
241+
\ }
242+
catch
243+
call codeium#log#Exception()
244+
endtry
257245
endfunction
258246

259247
function! codeium#DebouncedComplete(...) abort

autoload/codeium/command.vim

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
command! CodeiumAuth exe codeium#command#Auth()
2+
3+
function! codeium#command#BrowserCommand() abort
4+
if has('win32') && executable('rundll32')
5+
return 'rundll32 url.dll,FileProtocolHandler'
6+
elseif isdirectory('/private') && executable('/usr/bin/open')
7+
return '/usr/bin/open'
8+
elseif executable('xdg-open')
9+
return 'xdg-open'
10+
else
11+
return ''
12+
endif
13+
endfunction
14+
15+
function! s:Uuid() abort
16+
if has('win32')
17+
return system('powershell -Command "[guid]::NewGuid()"')
18+
elseif executable('uuidgen')
19+
return system('uuidgen')
20+
endif
21+
22+
throw "Could not generate uuid. Please make sure uuidgen is installed."
23+
endfunction
24+
25+
function! s:ConfigDir() abort
26+
let config_dir = $XDG_CONFIG_HOME ?? $HOME . '/.config'
27+
return config_dir . '/codeium'
28+
endfunction
29+
30+
function! s:LoadApiKey() abort
31+
let config_path = s:ConfigDir() . '/config.json'
32+
if !filereadable(config_path)
33+
return ''
34+
endif
35+
36+
let config = json_decode(join(readfile(config_path), '') ?? "{}")
37+
return config->get('apiKey', '')
38+
endfunction
39+
40+
let s:api_key = s:LoadApiKey()
41+
42+
function! codeium#command#Auth() abort
43+
let uuid = trim(s:Uuid())
44+
let url = 'https://www.codeium.com/profile?response_type=token&redirect_uri=show-auth-token&state=' . uuid . '&scope=openid%20profile%20email&redirect_parameters_type=query'
45+
let browser = codeium#command#BrowserCommand()
46+
if !empty(browser)
47+
echo "Press ENTER to login to Codeium in your browser."
48+
49+
let c = getchar()
50+
while c isnot# 13 && c isnot# 10 && c isnot# 0
51+
let c = getchar()
52+
endwhile
53+
54+
try
55+
call system(browser . ' ' . "'" . url . "'")
56+
catch
57+
echo "Failed to open browser. Open " . url
58+
endtry
59+
60+
let api_key = ''
61+
let auth_token = input('Paste your token here: ')
62+
let tries = 0
63+
64+
while empty(api_key) && tries < 3
65+
let command = 'curl -s https://api.codeium.com/register_user/ ' .
66+
\ '--header "Content-Type: application/json" ' .
67+
\ '--data ' . "'" . json_encode({'firebase_id_token': auth_token}) . "'"
68+
let response = system(command)
69+
let res = json_decode(response)
70+
let api_key = res->get('api_key', '')
71+
if empty(api_key)
72+
let auth_token = input('Invalid token, please try again: ')
73+
endif
74+
let tries = tries + 1
75+
endwhile
76+
77+
if !empty(api_key)
78+
let s:api_key = api_key
79+
let config_dir = s:ConfigDir()
80+
let config_path = config_dir . '/config.json'
81+
82+
if filereadable(config_path)
83+
let config = json_decode(join(readfile(config_path), '') ?? "{}")
84+
else
85+
call mkdir(config_dir, "p")
86+
let config = {}
87+
endif
88+
89+
let config.apiKey = api_key
90+
try
91+
call writefile([json_encode(config)], config_path)
92+
catch
93+
call codeium#log#Error("Could not persist api key to config.json")
94+
endtry
95+
endif
96+
endif
97+
endfunction
98+
99+
function! codeium#command#ApiKey() abort
100+
return s:api_key
101+
endfunction

autoload/codeium/log.vim

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
if exists('g:loaded_codeium_log')
2+
finish
3+
endif
4+
let g:loaded_codeium_log = 1
5+
6+
if !exists('s:logfile')
7+
let s:logfile = tempname() . '-codeium.log'
8+
try
9+
call writefile([], s:logfile)
10+
catch
11+
endtry
12+
endif
13+
14+
function! codeium#log#Logfile() abort
15+
return s:logfile
16+
endfunction
17+
18+
function! codeium#log#Log(level, msg) abort
19+
let min_level = get(g:, 'codeium_log_level', 'WARN')
20+
for level in ['ERROR', 'WARN', 'INFO', 'DEBUG', 'TRACE']
21+
if level == a:level
22+
try
23+
if filewritable(s:logfile)
24+
call writefile(split(a:msg, "\n", 1), s:logfile, 'a')
25+
endif
26+
catch
27+
endtry
28+
endif
29+
if level == min_level
30+
break
31+
endif
32+
endfor
33+
endfunction
34+
35+
function! codeium#log#Error(msg) abort
36+
call codeium#log#Log('ERROR', a:msg)
37+
endfunction
38+
39+
function! codeium#log#Warn(msg) abort
40+
call codeium#log#Log('WARN', a:msg)
41+
endfunction
42+
43+
function! codeium#log#Info(msg) abort
44+
call codeium#log#Log('INFO', a:msg)
45+
endfunction
46+
47+
function! codeium#log#Debug(msg) abort
48+
call codeium#log#Log('DEBUG', a:msg)
49+
endfunction
50+
51+
function! codeium#log#Trace(msg) abort
52+
call codeium#log#Log('TRACE', a:msg)
53+
endfunction
54+
55+
function! codeium#log#Exception() abort
56+
if !empty(v:exception)
57+
call codeium#log#Error('Exception: ' . v:exception . ' [' . v:throwpoint . ']')
58+
endif
59+
endfunction

0 commit comments

Comments
 (0)