e71846aa Andy McCall 1 month ago ↶
1
2
3
4
5
6
7
8
9
10
11
12
use crate :: db:: { now_ms, Pool} ;
13
use crate :: Shared;
14
use rand:: RngCore;
15
use ring:: aead;
16
use sqlx:: FromRow;
17
use std:: path:: Path;
18
use std:: time:: Duration;
19
20
21
pub const APIS : [ & str ; 2 ] = [ " chat-completions" , " anthropic-messages" ] ;
22
23
24
pub const DEFAULT_BUDGET : i64 = 120_000 ;
5360cea3 Andy McCall 21 days ago ↶
25
26
27
pub const CALL_TIMEOUT : Duration = Duration:: from_secs( 90 ) ;
28
29
30
31
pub const BACKGROUND_TIMEOUT : Duration = Duration:: from_secs( 300 ) ;
32
33
34
pub const MAX_ANSWER_TOKENS : u32 = 16_000 ;
e71846aa Andy McCall 1 month ago ↶
35
36
const MAX_ANSWER : usize = 64 * 1024 ;
37
2a83f530 Andy McCall 1 month ago ↶
38
pub use crate :: levels:: Scope;
e71846aa Andy McCall 1 month ago ↶
39
40
# [ derive ( Clone, Debug, FromRow ) ]
41
pub struct Assistant {
42
pub id : i64 ,
43
pub scope : String,
44
pub scope_id : i64 ,
45
pub name : String,
46
pub endpoint : String,
47
48
pub api : String,
49
pub model : String,
50
51
pub headers : String,
52
53
pub token : Vec< u8 > ,
54
pub enabled : bool ,
55
pub budget : i64 ,
56
pub created_ms : i64 ,
57
pub updated_ms : i64 ,
58
}
59
60
impl Assistant {
61
pub fn scope ( & self ) -> Scope {
62
match self .scope.as_str ( ) {
63
" org" => Scope:: Org( self .scope_id) ,
64
" repo" => Scope:: Repo( self .scope_id) ,
65
_ => Scope:: Site,
66
}
67
}
68
69
pub fn has_token ( & self ) -> bool {
70
! self .token.is_empty ( )
71
}
72
73
74
pub fn header_list ( & self ) -> Vec< ( String, String) > {
75
parse_headers ( & self .headers) .unwrap_or_default ( )
76
}
77
}
78
79
80
# [ derive ( Clone, Debug, Default ) ]
81
pub struct Fields {
82
pub name : String,
83
pub endpoint : String,
84
pub api : String,
85
pub model : String,
86
pub headers : String,
87
pub enabled : bool ,
88
pub budget : i64 ,
89
}
90
91
92
pub fn parse_headers ( text : & str ) -> Result< Vec< ( String, String) > , String> {
93
let mut out = vec! [ ] ;
94
for line in text.lines ( ) .map ( str :: trim) .filter ( | l | ! l.is_empty ( ) ) {
95
let Some ( ( name, value) ) = line.split_once ( ' :' ) else { return Err ( line.to_string ( ) ) } ;
96
let ( name, value) = ( name.trim ( ) , value.trim ( ) ) ;
97
let name_ok = ! name.is_empty ( ) & & name.chars ( ) .all ( | c | c.is_ascii_alphanumeric ( ) | | c = = ' -' | | c = = ' _' ) ;
98
if ! name_ok | | value.chars ( ) .any ( | c | c.is_control ( ) ) {
99
return Err ( line.to_string ( ) ) ;
100
}
101
out.push ( ( name.to_string ( ) , value.to_string ( ) ) ) ;
102
}
103
Ok ( out)
104
}
105
106
107
108
109
# [ derive ( Clone ) ]
110
pub struct SecretKey ( [u8 ; 32]) ;
111
112
impl SecretKey {
113
pub fn load_or_create ( keys : & Path) -> anyhow:: Result< SecretKey> {
4ac01a73 Andy McCall 1 month ago ↶
114
SecretKey:: load_or_create_named( keys, " assistants.key" )
115
}
116
117
118
119
pub fn load_or_create_named ( keys : & Path, file : & str ) -> anyhow:: Result< SecretKey> {
e71846aa Andy McCall 1 month ago ↶
120
std:: fs:: create_dir_all( keys) ? ;
4ac01a73 Andy McCall 1 month ago ↶
121
let path = keys.join ( file) ;
e71846aa Andy McCall 1 month ago ↶
122
if let Ok ( bytes) = std:: fs:: read( & path) {
123
if bytes.len ( ) = = 32 {
124
return Ok ( SecretKey( bytes.try_into ( ) .unwrap ( ) ) ) ;
125
}
126
}
127
let mut k = [ 0 u8 ; 32 ] ;
128
rand:: rngs:: OsRng.fill_bytes ( & mut k) ;
129
std:: fs:: write( & path, k) ? ;
130
# [ cfg ( unix ) ]
131
{
132
use std:: os:: unix:: fs:: PermissionsExt;
133
std:: fs:: set_permissions( & path, std:: fs:: Permissions:: from_mode( 0o600 ) ) ? ;
134
}
135
Ok ( SecretKey( k) )
136
}
137
138
fn key ( & self ) -> aead:: LessSafeKey {
139
aead:: LessSafeKey:: new( aead:: UnboundKey:: new( & aead:: CHACHA20_POLY1305 , & self .0 ) .expect ( " key length" ) )
140
}
141
142
143
144
pub fn seal ( & self , plain : & str ) -> Vec< u8 > {
145
if plain.is_empty ( ) {
146
return vec! [ ] ;
147
}
148
let mut nonce = [ 0 u8 ; 12 ] ;
149
rand:: rngs:: OsRng.fill_bytes ( & mut nonce) ;
150
let mut out = plain.as_bytes ( ) .to_vec ( ) ;
151
self .key ( ) .seal_in_place_append_tag ( aead:: Nonce:: assume_unique_for_key( nonce) , aead:: Aad:: empty( ) , & mut out) .expect ( " seal" ) ;
152
let mut sealed = nonce.to_vec ( ) ;
153
sealed.extend ( out) ;
154
sealed
155
}
156
157
158
159
pub fn open ( & self , sealed : & [u8 ]) -> Option< String> {
160
if sealed.is_empty ( ) {
161
return Some ( String :: new( ) ) ;
162
}
163
let ( nonce, rest) = sealed.split_at_checked ( 12 ) ? ;
164
let mut buf = rest.to_vec ( ) ;
165
let nonce = aead:: Nonce:: try_assume_unique_for_key( nonce) .ok ( ) ? ;
166
let plain = self .key ( ) .open_in_place ( nonce, aead:: Aad:: empty( ) , & mut buf) .ok ( ) ? ;
167
String :: from_utf8( plain.to_vec ( ) ) .ok ( )
168
}
169
}
170
171
172
173
pub async fn list ( pool : & Pool, scope : Scope) -> sqlx:: Result< Vec< Assistant> > {
174
sqlx:: query_as( " SELECT * FROM assistants WHERE scope = ? AND scope_id = ? ORDER BY name" )
175
.bind ( scope.kind ( ) )
176
.bind ( scope.id ( ) )
177
.fetch_all ( pool)
178
.await
179
}
180
181
pub async fn get ( pool : & Pool, id : i64 ) -> sqlx:: Result< Option< Assistant> > {
182
sqlx:: query_as( " SELECT * FROM assistants WHERE id = ?" ) .bind ( id) .fetch_optional ( pool) .await
183
}
184
185
186
pub async fn create ( pool : & Pool, scope : Scope, f : & Fields, token : & [u8 ]) -> sqlx:: Result< Option< Assistant> > {
187
let now = now_ms ( ) ;
188
let r = sqlx:: query_as(
189
" INSERT INTO assistants (scope, scope_id, name, endpoint, api, model, headers, token, enabled, budget, created_ms, updated_ms) \
190
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING *" ,
191
)
192
.bind ( scope.kind ( ) )
193
.bind ( scope.id ( ) )
194
.bind ( & f.name)
195
.bind ( & f.endpoint)
196
.bind ( & f.api)
197
.bind ( & f.model)
198
.bind ( & f.headers)
199
.bind ( token)
200
.bind ( f.enabled)
201
.bind ( f.budget)
202
.bind ( now)
203
.bind ( now)
204
.fetch_optional ( pool)
205
.await? ;
206
Ok ( r)
207
}
208
209
210
211
pub async fn update ( pool : & Pool, id : i64 , f : & Fields, token : Option< & [ u8 ] > ) -> sqlx:: Result< bool > {
212
let r = match token {
213
Some ( t) => sqlx:: query(
214
" UPDATE assistants SET name = ?, endpoint = ?, api = ?, model = ?, headers = ?, enabled = ?, budget = ?, token = ?, updated_ms = ? \
215
WHERE id = ? AND NOT EXISTS (SELECT 1 FROM assistants o WHERE o.scope = assistants.scope AND o.scope_id = assistants.scope_id AND o.name = ? AND o.id <> ?)" ,
216
)
217
.bind ( & f.name)
218
.bind ( & f.endpoint)
219
.bind ( & f.api)
220
.bind ( & f.model)
221
.bind ( & f.headers)
222
.bind ( f.enabled)
223
.bind ( f.budget)
224
.bind ( t)
225
.bind ( now_ms ( ) )
226
.bind ( id)
227
.bind ( & f.name)
228
.bind ( id)
229
.execute ( pool)
230
.await? ,
231
None => sqlx:: query(
232
" UPDATE assistants SET name = ?, endpoint = ?, api = ?, model = ?, headers = ?, enabled = ?, budget = ?, updated_ms = ? \
233
WHERE id = ? AND NOT EXISTS (SELECT 1 FROM assistants o WHERE o.scope = assistants.scope AND o.scope_id = assistants.scope_id AND o.name = ? AND o.id <> ?)" ,
234
)
235
.bind ( & f.name)
236
.bind ( & f.endpoint)
237
.bind ( & f.api)
238
.bind ( & f.model)
239
.bind ( & f.headers)
240
.bind ( f.enabled)
241
.bind ( f.budget)
242
.bind ( now_ms ( ) )
243
.bind ( id)
244
.bind ( & f.name)
245
.bind ( id)
246
.execute ( pool)
247
.await? ,
248
} ;
249
Ok ( r.rows_affected ( ) = = 1 )
250
}
251
ed89fae5 Andy McCall 1 month ago ↶
252
253
254
255
pub async fn rename_in_history ( pool : & Pool, scope : Scope, owner_hint : & str , old : & str , new : & str ) -> sqlx:: Result< ( ) > {
256
if old = = new | | old.is_empty ( ) | | new.is_empty ( ) {
257
return Ok ( ( ) ) ;
258
}
259
let like = format! ( " %{old} %" ) ;
260
match scope {
261
Scope:: Site => {
ffb67a81 Andy McCall 22 days ago
262
for table in [ " proposal_reviews" , " proposal_comments" ] {
263
sqlx:: query( & format! ( " UPDATE {table} SET via = ? WHERE via = ?" ) ) .bind ( new) .bind ( old) .execute ( pool) .await? ;
264
}
ed89fae5 Andy McCall 1 month ago ↶
265
sqlx:: query( " UPDATE proposal_events SET event = replace(event, ?, ?) WHERE event LIKE ?" )
266
.bind ( old)
267
.bind ( new)
268
.bind ( & like)
269
.execute ( pool)
270
.await? ;
271
}
272
Scope:: Org( _ ) => {
273
let in_org = " proposal_id IN (SELECT p.id FROM proposals p JOIN repositories r ON r.id = p.repo_id WHERE r.owner = ?)" ;
ffb67a81 Andy McCall 22 days ago
274
for table in [ " proposal_reviews" , " proposal_comments" ] {
275
sqlx:: query( & format! ( " UPDATE {table} SET via = ? WHERE via = ? AND {in_org} " ) )
276
.bind ( new)
277
.bind ( old)
278
.bind ( owner_hint)
279
.execute ( pool)
280
.await? ;
281
}
ed89fae5 Andy McCall 1 month ago ↶
282
sqlx:: query( & format! ( " UPDATE proposal_events SET event = replace(event, ?, ?) WHERE event LIKE ? AND {in_org} " ) )
283
.bind ( old)
284
.bind ( new)
285
.bind ( & like)
286
.bind ( owner_hint)
287
.execute ( pool)
288
.await? ;
289
}
290
Scope:: Repo( id) => {
291
let in_repo = " proposal_id IN (SELECT id FROM proposals WHERE repo_id = ?)" ;
ffb67a81 Andy McCall 22 days ago
292
for table in [ " proposal_reviews" , " proposal_comments" ] {
293
sqlx:: query( & format! ( " UPDATE {table} SET via = ? WHERE via = ? AND {in_repo} " ) )
294
.bind ( new)
295
.bind ( old)
296
.bind ( id)
297
.execute ( pool)
298
.await? ;
299
}
ed89fae5 Andy McCall 1 month ago ↶
300
sqlx:: query( & format! ( " UPDATE proposal_events SET event = replace(event, ?, ?) WHERE event LIKE ? AND {in_repo} " ) )
301
.bind ( old)
302
.bind ( new)
303
.bind ( & like)
304
.bind ( id)
305
.execute ( pool)
306
.await? ;
307
}
308
}
309
Ok ( ( ) )
310
}
311
e71846aa Andy McCall 1 month ago ↶
312
pub async fn set_enabled ( pool : & Pool, id : i64 , enabled : bool ) -> sqlx:: Result< ( ) > {
313
sqlx:: query( " UPDATE assistants SET enabled = ?, updated_ms = ? WHERE id = ?" )
314
.bind ( enabled)
315
.bind ( now_ms ( ) )
316
.bind ( id)
317
.execute ( pool)
318
.await? ;
319
Ok ( ( ) )
320
}
321
322
pub async fn delete ( pool : & Pool, id : i64 ) -> sqlx:: Result< ( ) > {
323
sqlx:: query( " DELETE FROM assistants WHERE id = ?" ) .bind ( id) .execute ( pool) .await? ;
324
Ok ( ( ) )
325
}
326
327
328
329
pub async fn delete_scope ( pool : & Pool, scope : Scope) -> sqlx:: Result< ( ) > {
330
sqlx:: query( " DELETE FROM assistants WHERE scope = ? AND scope_id = ?" ) .bind ( scope.kind ( ) ) .bind ( scope.id ( ) ) .execute ( pool) .await? ;
331
sqlx:: query( " DELETE FROM assistant_prompts WHERE scope = ? AND scope_id = ?" ) .bind ( scope.kind ( ) ) .bind ( scope.id ( ) ) .execute ( pool) .await? ;
332
Ok ( ( ) )
333
}
334
335
336
pub async fn prompt ( pool : & Pool, scope : Scope) -> sqlx:: Result< String> {
337
Ok ( sqlx:: query_scalar( " SELECT prompt FROM assistant_prompts WHERE scope = ? AND scope_id = ?" )
338
.bind ( scope.kind ( ) )
339
.bind ( scope.id ( ) )
340
.fetch_optional ( pool)
341
.await?
342
.unwrap_or_default ( ) )
343
}
344
345
pub async fn set_prompt ( pool : & Pool, scope : Scope, text : & str ) -> sqlx:: Result< ( ) > {
346
if text.trim ( ) .is_empty ( ) {
347
sqlx:: query( " DELETE FROM assistant_prompts WHERE scope = ? AND scope_id = ?" )
348
.bind ( scope.kind ( ) )
349
.bind ( scope.id ( ) )
350
.execute ( pool)
351
.await? ;
352
} else {
353
sqlx:: query(
354
" INSERT INTO assistant_prompts (scope, scope_id, prompt, updated_ms) VALUES (?, ?, ?, ?) \
355
ON CONFLICT (scope, scope_id) DO UPDATE SET prompt = excluded.prompt, updated_ms = excluded.updated_ms" ,
356
)
357
.bind ( scope.kind ( ) )
358
.bind ( scope.id ( ) )
359
.bind ( text.trim ( ) )
360
.bind ( now_ms ( ) )
361
.execute ( pool)
362
.await? ;
363
}
364
Ok ( ( ) )
365
}
366
367
368
369
370
371
# [ derive ( Clone, Debug ) ]
372
pub struct Available {
373
pub assistant : Assistant,
374
375
pub from : String,
376
377
pub off_above : bool ,
378
}
379
380
impl Available {
381
pub fn on ( & self ) -> bool {
382
self .assistant.enabled & & ! self .off_above
383
}
384
}
385
386
387
388
389
pub async fn available ( pool : & Pool, scope : Scope, owner : & str ) -> sqlx:: Result< Vec< Available> > {
2a83f530 Andy McCall 1 month ago ↶
390
let mut levels = crate :: levels:: above( pool, scope, owner) .await? ;
e71846aa Andy McCall 1 month ago ↶
391
levels.push ( ( scope, String :: new( ) ) ) ;
392
let mut out: Vec< Available> = vec! [ ] ;
393
let mut off: Vec< String> = vec! [ ] ;
394
for ( level, from) in levels {
395
for a in list ( pool, level) .await? {
396
let off_above = off.iter ( ) .any ( | n | n.eq_ignore_ascii_case ( & a.name) ) ;
397
if ! a.enabled & & ! off.iter ( ) .any ( | n | n.eq_ignore_ascii_case ( & a.name) ) {
398
off.push ( a.name.clone ( ) ) ;
399
}
400
out.retain ( | o | ! o.assistant.name.eq_ignore_ascii_case ( & a.name) ) ;
401
out.push ( Available { assistant: a, from: from.clone ( ) , off_above } ) ;
402
}
403
}
404
Ok ( out)
405
}
406
407
408
pub async fn enabled_for_repo ( pool : & Pool, repo : & crate:: db:: repos:: RepoRow) -> sqlx:: Result< Vec< Assistant> > {
409
Ok ( available ( pool, Scope:: Repo( repo.id) , & repo.owner) .await? .into_iter ( ) .filter ( Available:: on) .map ( | a | a.assistant ) .collect ( ) )
410
}
411
412
413
414
pub async fn inherited_prompts ( pool : & Pool, scope : Scope, owner : & str ) -> sqlx:: Result< Vec< ( String, String) > > {
415
let mut out = vec! [ ] ;
2a83f530 Andy McCall 1 month ago ↶
416
for ( level, from) in crate :: levels:: above( pool, scope, owner) .await? {
e71846aa Andy McCall 1 month ago ↶
417
let text = prompt ( pool, level) .await? ;
418
if ! text.is_empty ( ) {
419
out.push ( ( from, text) ) ;
420
}
421
}
422
Ok ( out)
423
}
424
425
426
427
pub async fn prompt_for_repo ( pool : & Pool, repo : & crate:: db:: repos:: RepoRow) -> sqlx:: Result< String> {
428
let scope = Scope:: Repo( repo.id) ;
429
let mut parts = inherited_prompts ( pool, scope, & repo.owner) .await? ;
430
let own = prompt ( pool, scope) .await? ;
431
if ! own.is_empty ( ) {
432
parts.push ( ( " this repository" .to_string ( ) , own) ) ;
433
}
434
Ok ( parts.into_iter ( ) .map ( | ( from , text ) | format! ( " ## Instructions from {from} \n \n {text} \n " ) ) .collect:: < Vec< _ > > ( ) .join ( " \n " ) )
435
}
436
437
438
439
440
441
5360cea3 Andy McCall 21 days ago ↶
442
pub async fn ask ( app : & Shared, a : & Assistant, system : & str , user : & str , wait : Duration) -> Result< String, String> {
e71846aa Andy McCall 1 month ago ↶
443
let Some ( token) = app.assistant_key.open ( & a.token) else {
444
return Err ( " its token cannot be read: set it again" .into ( ) ) ;
445
} ;
9a777fec Andy McCall 21 days ago ↶
446
let client = crate :: net:: client( & a.endpoint, & app.config.outbound.allow, wait) .await? ;
e71846aa Andy McCall 1 month ago ↶
447
let mut req = client.post ( & a.endpoint) .header ( " content-type" , " application/json" ) ;
448
let body = match a.api.as_str ( ) {
449
" anthropic-messages" => {
450
if ! token.is_empty ( ) {
451
req = req.header ( " x-api-key" , & token) ;
452
}
453
req = req.header ( " anthropic-version" , " 2023-06-01" ) ;
454
serde_json:: json! ( {
455
" model" : a.model,
5360cea3 Andy McCall 21 days ago ↶
456
" max_tokens" : MAX_ANSWER_TOKENS ,
e71846aa Andy McCall 1 month ago ↶
457
" system" : system,
458
" messages" : [ { " role" : " user" , " content" : user } ] ,
459
} )
460
}
461
_ => {
462
if ! token.is_empty ( ) {
463
req = req.header ( " authorization" , format! ( " Bearer {token} " ) ) ;
464
}
5360cea3 Andy McCall 21 days ago ↶
465
466
467
e71846aa Andy McCall 1 month ago ↶
468
serde_json:: json! ( {
469
" model" : a.model,
470
" messages" : [
471
{ " role" : " system" , " content" : system } ,
472
{ " role" : " user" , " content" : user } ,
473
] ,
474
} )
475
}
476
} ;
477
for ( name, value) in a.header_list ( ) {
478
req = req.header ( name, value) ;
479
}
480
let r = req.json ( & body) .send ( ) .await.map_err ( | e | {
481
if e.is_timeout ( ) {
5360cea3 Andy McCall 21 days ago ↶
482
format! ( " no answer within {} seconds" , wait.as_secs ( ) )
e71846aa Andy McCall 1 month ago ↶
483
} else {
484
scrub ( & e.to_string ( ) , & token)
485
}
486
} ) ? ;
487
let status = r.status ( ) ;
488
let text: String = r.text ( ) .await.unwrap_or_default ( ) .chars ( ) .take ( MAX_ANSWER ) .collect ( ) ;
489
if ! status.is_success ( ) {
490
let why = serde_json:: from_str:: < serde_json:: Value> ( & text)
491
.ok ( )
492
.and_then ( | v | v[ " error" ] [ " message" ] .as_str ( ) .or ( v[ " error" ] .as_str ( ) ) .or ( v[ " message" ] .as_str ( ) ) .map ( str :: to_string) )
493
.unwrap_or_else ( | | text.lines ( ) .next ( ) .unwrap_or ( " " ) .chars ( ) .take ( 160 ) .collect ( ) ) ;
494
return Err ( scrub ( & format! ( " {} {} " , status.as_u16 ( ) , why.trim ( ) ) , & token) ) ;
495
}
496
let v: serde_json:: Value = serde_json:: from_str( & text) .map_err ( | _| " the answer was not JSON" .to_string ( ) ) ? ;
5360cea3 Andy McCall 21 days ago ↶
497
let ( answer, stop) = answer_of ( & a.api, & v) ;
498
finish ( answer, stop)
499
}
500
501
502
# [ derive ( Debug, PartialEq, Eq ) ]
503
enum Stop {
504
505
Done,
506
507
Length,
508
509
Declined( Option< String> ) ,
510
}
511
512
513
514
fn answer_of ( api : & str , v : & serde_json:: Value) -> ( String, Stop) {
515
match api {
516
" anthropic-messages" => {
517
let text = v[ " content" ]
518
.as_array ( )
519
.map ( | parts | {
520
parts
521
.iter ( )
522
.filter ( | p | p[ " type" ] .as_str ( ) .is_none_or ( | t | t = = " text" ) )
523
.filter_map ( | p | p[ " text" ] .as_str ( ) )
524
.collect:: < Vec< _ > > ( )
525
.join ( " " )
526
} )
527
.unwrap_or_default ( ) ;
528
let stop = match v[ " stop_reason" ] .as_str ( ) {
529
Some ( " max_tokens" ) => Stop:: Length,
530
Some ( " refusal" ) => Stop:: Declined( v[ " stop_details" ] [ " category" ] .as_str ( ) .map ( str :: to_string) ) ,
531
_ => Stop:: Done,
532
} ;
533
( text, stop)
534
}
535
_ => {
536
let choice = & v[ " choices" ] [ 0 ] ;
537
let text = match & choice[ " message" ] [ " content" ] {
538
serde_json:: Value:: String( s) => s.clone ( ) ,
539
serde_json:: Value:: Array( parts) => parts.iter ( ) .filter_map ( | p | p[ " text" ] .as_str ( ) ) .collect:: < Vec< _ > > ( ) .join ( " " ) ,
540
_ => String :: new( ) ,
541
} ;
542
let stop = match choice[ " finish_reason" ] .as_str ( ) {
543
Some ( " length" ) => Stop:: Length,
544
Some ( " content_filter" ) => Stop:: Declined( None ) ,
545
_ => Stop:: Done,
546
} ;
547
( text, stop)
548
}
e71846aa Andy McCall 1 month ago ↶
549
}
550
}
551
5360cea3 Andy McCall 21 days ago ↶
552
553
554
fn finish ( answer : String, stop : Stop) -> Result< String, String> {
555
match stop {
556
Stop:: Declined( category) => Err ( match category {
557
Some ( c) => format! ( " it declined to answer ({c} )" ) ,
558
None => " it declined to answer" .into ( ) ,
559
} ) ,
560
Stop:: Length if answer.trim ( ) .is_empty ( ) => {
561
Err ( " it ran out of room before writing an answer (it spent its length limit thinking): try a smaller proposal" .into ( ) )
562
}
563
Stop:: Length => Ok ( format! ( " {} \n \n *(Cut short: the answer reached its length limit.)*" , answer.trim_end ( ) ) ) ,
564
Stop:: Done if answer.trim ( ) .is_empty ( ) => Err ( " the answer carried no text" .into ( ) ) ,
565
Stop:: Done => Ok ( answer) ,
566
}
567
}
568
155cab14 Andy McCall 1 month ago ↶
569
570
571
pub const PRESETS : & [ ( & str , & str , & str , & str , & str ) ] = & [
572
( " anthropic" , " Anthropic (Claude)" , " Claude" , " https://api.anthropic.com/v1/messages" , " anthropic-messages" ) ,
573
( " openai" , " OpenAI (ChatGPT)" , " ChatGPT" , " https://api.openai.com/v1/chat/completions" , " chat-completions" ) ,
574
( " gemini" , " Google Gemini" , " Gemini" , " https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" , " chat-completions" ) ,
575
( " deepseek" , " DeepSeek" , " DeepSeek" , " https://api.deepseek.com/chat/completions" , " chat-completions" ) ,
576
( " mistral" , " Mistral" , " Mistral" , " https://api.mistral.ai/v1/chat/completions" , " chat-completions" ) ,
577
( " perplexity" , " Perplexity" , " Perplexity" , " https://api.perplexity.ai/chat/completions" , " chat-completions" ) ,
578
( " ollama" , " Ollama (on your network)" , " Ollama" , " http://localhost:11434/v1/chat/completions" , " chat-completions" ) ,
579
] ;
580
581
582
583
pub fn models_url ( endpoint : & str ) -> Option< String> {
584
let e = endpoint.trim_end_matches ( ' /' ) ;
585
e.strip_suffix ( " /chat/completions" ) .or_else ( | | e.strip_suffix ( " /messages" ) ) .map ( | base | format! ( " {base} /models" ) )
586
}
587
588
589
590
9a777fec Andy McCall 21 days ago ↶
591
pub async fn list_models ( endpoint : & str , api : & str , token : & str , allow : & [String]) -> Result< Vec< String> , String> {
155cab14 Andy McCall 1 month ago ↶
592
let url = models_url ( endpoint) .ok_or ( " this endpoint has no model list next to it" ) ? ;
9a777fec Andy McCall 21 days ago ↶
593
let client = crate :: net:: client( & url, allow, std:: time:: Duration:: from_secs( 15 ) ) .await? ;
155cab14 Andy McCall 1 month ago ↶
594
let mut req = client.get ( & url) ;
595
if api = = " anthropic-messages" {
596
req = req.header ( " anthropic-version" , " 2023-06-01" ) ;
597
if ! token.is_empty ( ) {
598
req = req.header ( " x-api-key" , token) ;
599
}
600
} else if ! token.is_empty ( ) {
601
req = req.header ( " authorization" , format! ( " Bearer {token} " ) ) ;
602
}
603
let r = req.send ( ) .await.map_err ( | e | scrub ( & e.to_string ( ) , token) ) ? ;
604
let status = r.status ( ) ;
605
if ! status.is_success ( ) {
606
return Err ( format! ( " the model list answered {} " , status.as_u16 ( ) ) ) ;
607
}
608
let v: serde_json:: Value = r.json ( ) .await.map_err ( | _| " the model list was not JSON" .to_string ( ) ) ? ;
609
let skip = [ " embed" , " tts" , " whisper" , " dall-e" , " moderation" , " audio" , " image" , " realtime" , " transcribe" , " search-preview" ] ;
610
let mut out: Vec< String> = v[ " data" ]
611
.as_array ( )
612
.or ( v[ " models" ] .as_array ( ) )
613
.ok_or ( " the model list had no data" ) ?
614
.iter ( )
615
.filter_map ( | m | m[ " id" ] .as_str ( ) .or ( m[ " name" ] .as_str ( ) ) )
616
.map ( | id | id.strip_prefix ( " models/" ) .unwrap_or ( id) .to_string ( ) )
617
.filter ( | id | ! skip.iter ( ) .any ( | s | id.to_lowercase ( ) .contains ( s) ) )
618
.collect ( ) ;
619
out.sort ( ) ;
620
out.dedup ( ) ;
621
if out.is_empty ( ) {
622
return Err ( " the model list was empty" .into ( ) ) ;
623
}
624
Ok ( out)
625
}
626
e71846aa Andy McCall 1 month ago ↶
627
628
pub async fn test ( app : & Shared, a : & Assistant) -> Result< String, String> {
5360cea3 Andy McCall 21 days ago ↶
629
let answer =
630
ask ( app, a, " You are being connected to an OxygenHub site. Answer briefly." , " Reply with the single word OK." , CALL_TIMEOUT )
631
.await? ;
e71846aa Andy McCall 1 month ago ↶
632
Ok ( answer.trim ( ) .chars ( ) .take ( 80 ) .collect ( ) )
633
}
634
635
636
fn scrub ( text : & str , token : & str ) -> String {
637
if token.is_empty ( ) {
638
text.to_string ( )
639
} else {
640
text.replace ( token, " ***" )
641
}
642
}
643
644
# [ cfg ( test ) ]
645
mod tests {
646
use super :: * ;
647
648
# [ test ]
649
fn tokens_seal_and_open_only_under_their_key ( ) {
650
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
651
let k = SecretKey:: load_or_create( dir.path ( ) ) .unwrap ( ) ;
652
let sealed = k.seal ( " sk-very-secret" ) ;
653
assert_ne! ( sealed, b " sk-very-secret" ) ;
654
assert! ( ! String :: from_utf8_lossy( & sealed) .contains ( " secret" ) ) ;
655
assert_eq! ( k.open ( & sealed) .as_deref ( ) , Some ( " sk-very-secret" ) ) ;
656
assert_eq! ( SecretKey:: load_or_create( dir.path ( ) ) .unwrap ( ) .open ( & sealed) .as_deref ( ) , Some ( " sk-very-secret" ) , " the key is kept" ) ;
657
let other = SecretKey:: load_or_create( tempfile:: tempdir( ) .unwrap ( ) .path ( ) ) .unwrap ( ) ;
658
assert_eq! ( other.open ( & sealed) , None ) ;
659
assert_eq! ( k.open ( & [ 1 , 2 , 3 ] ) , None ) ;
660
assert_eq! ( k.seal ( " " ) , Vec : : < u8 > :: new( ) ) ;
661
assert_eq! ( k.open ( & [ ] ) .as_deref ( ) , Some ( " " ) ) ;
5360cea3 Andy McCall 21 days ago ↶
662
}
663
664
# [ test ]
665
fn answers_say_why_they_stopped ( ) {
666
let a = | v : serde_json:: Value| {
667
let ( text, stop) = answer_of ( " anthropic-messages" , & v) ;
668
finish ( text, stop)
669
} ;
670
671
let thought = serde_json:: json! ( { " stop_reason" : " max_tokens" , " content" : [ { " type" : " thinking" , " thinking" : " " } ] } ) ;
672
assert! ( a ( thought) .unwrap_err ( ) .contains ( " ran out of room" ) ) ;
673
let cut = serde_json:: json! ( { " stop_reason" : " max_tokens" , " content" : [ { " type" : " thinking" , " thinking" : " " } , { " type" : " text" , " text" : " Half" } ] } ) ;
674
assert! ( a ( cut) .unwrap ( ) .starts_with ( " Half\n \n *(Cut short" ) ) ;
675
let declined = serde_json:: json! ( { " stop_reason" : " refusal" , " stop_details" : { " category" : " cyber" } , " content" : [ ] } ) ;
676
assert_eq! ( a ( declined) .unwrap_err ( ) , " it declined to answer (cyber)" ) ;
677
let ok = serde_json:: json! ( { " stop_reason" : " end_turn" , " content" : [ { " type" : " text" , " text" : " Fine." } ] } ) ;
678
assert_eq! ( a ( ok) .unwrap ( ) , " Fine." ) ;
679
let chat = | v : serde_json:: Value| {
680
let ( text, stop) = answer_of ( " chat-completions" , & v) ;
681
finish ( text, stop)
682
} ;
683
assert! ( chat ( serde_json:: json! ( { " choices" : [ { " finish_reason" : " length" , " message" : { " content" : " " } } ] } ) )
684
.unwrap_err ( )
685
.contains ( " ran out of room" ) ) ;
686
assert_eq! (
687
chat ( serde_json:: json! ( { " choices" : [ { " finish_reason" : " content_filter" , " message" : { " content" : " " } } ] } ) ) .unwrap_err ( ) ,
688
" it declined to answer"
689
) ;
690
assert_eq! (
691
chat ( serde_json:: json! ( { " choices" : [ { " finish_reason" : " stop" , " message" : { " content" : " Yes." } } ] } ) ) .unwrap ( ) ,
692
" Yes."
693
) ;
e71846aa Andy McCall 1 month ago ↶
694
}
695
696
# [ test ]
c08cec37 Andy McCall 20 days ago ↶
697
fn a_refusal_for_length_is_told_from_others ( ) {
698
for e in [
699
" 400 This model's maximum context length is 8192 tokens. Please reduce the length of the messages." ,
700
" 400 prompt is too long: 210000 tokens > 200000 maximum" ,
701
" 413 Request too large" ,
702
" 400 input length exceeds the context window" ,
703
] {
704
assert! ( super :: too_long( e) , " {e}" ) ;
705
}
706
for e in [ " 401 invalid api key" , " 500 too long a queue" , " no answer within 90 seconds" , " 400 model not found" ] {
707
assert! ( ! super :: too_long( e) , " {e}" ) ;
708
}
709
}
710
711
# [ test ]
e71846aa Andy McCall 1 month ago ↶
712
fn headers_parse_or_name_the_bad_line ( ) {
713
assert_eq! (
714
parse_headers ( " X-Org: acme\n \n OpenAI-Beta : v1 " ) .unwrap ( ) ,
715
vec! [ ( " X-Org" .into ( ) , " acme" .into ( ) ) , ( " OpenAI-Beta" .into ( ) , " v1" .into ( ) ) ]
716
) ;
717
assert_eq! ( parse_headers ( " no colon" ) .unwrap_err ( ) , " no colon" ) ;
718
assert_eq! ( parse_headers ( " bad name: x" ) .unwrap_err ( ) , " bad name: x" ) ;
719
}
720
}
7d2eb590 Andy McCall 1 month ago ↶
721
722
723
724
725
pub const CALLS_PER_HOUR : usize = 30 ;
726
727
728
# [ derive ( Default ) ]
729
pub struct Gate {
730
busy : std:: collections:: HashSet< ( i64 , String) > ,
731
recent : std:: collections:: HashMap< i64 , Vec< i64 > > ,
732
}
733
734
impl Gate {
735
736
fn take ( & mut self , repo_id : i64 , proposal_id : i64 , name : & str ) -> Result< ( ) , String> {
737
let key = ( proposal_id, name.to_lowercase ( ) ) ;
738
if self .busy.contains ( & key) {
739
return Err ( format! ( " {name} is already answering this proposal" ) ) ;
740
}
741
let now = now_ms ( ) ;
742
let calls = self .recent.entry ( repo_id) .or_default ( ) ;
743
calls.retain ( | t | now - * t < 3_600_000 ) ;
744
if calls.len ( ) > = CALLS_PER_HOUR {
745
return Err ( format! ( " this repository has asked assistants {CALLS_PER_HOUR} times in the last hour; try later" ) ) ;
746
}
747
calls.push ( now) ;
748
self .busy.insert ( key) ;
749
Ok ( ( ) )
750
}
751
752
fn release ( & mut self , proposal_id : i64 , name : & str ) {
753
self .busy.remove ( & ( proposal_id, name.to_lowercase ( ) ) ) ;
754
}
755
}
756
757
758
759
pub fn review_context (
760
row : & crate:: db:: repos:: RepoRow,
761
p : & crate:: db:: proposals:: ProposalRow,
762
loaded : & crate:: web:: proposals:: Loaded,
763
budget : usize ,
764
) -> String {
765
let mut head =
766
format! ( " # Proposal #{} : {} \n \n Repository {} /{} · into {} · by {} \n \n " , p.number, p.title, row.owner, row.name, p.target, p.author) ;
767
if ! p.body.trim ( ) .is_empty ( ) {
768
head.push_str ( " ## Description\n \n " ) ;
769
head.push_str ( p.body.trim ( ) ) ;
770
head.push_str ( " \n \n " ) ;
771
}
772
context_text ( head, & loaded.changes, & loaded.diffs, budget)
773
}
774
775
776
pub fn draft_context (
777
row : & crate:: db:: repos:: RepoRow,
778
title : & str ,
779
target : & str ,
780
changes : & [crate:: repos:: view:: ChangeView],
781
diffs : & [oxy_core:: repo:: FileDiff],
782
budget : usize ,
783
) -> String {
784
let head = format! (
785
" # Proposal: {} \n \n Repository {} /{} · into {} \n \n " ,
786
if title.trim ( ) .is_empty ( ) { " (untitled)" } else { title.trim ( ) } ,
787
row.owner,
788
row.name,
789
target
790
) ;
791
context_text ( head, changes, diffs, budget)
792
}
793
794
795
796
fn context_text ( mut text : String, changes : & [crate:: repos:: view:: ChangeView], diffs : & [oxy_core:: repo:: FileDiff], budget : usize ) -> String {
797
text.push_str ( & format! ( " ## Changes ({} )\n \n " , changes.len ( ) ) ) ;
798
for c in changes {
799
text.push_str ( & format! ( " - {} {} \n " , c.short, c.title) ) ;
800
let body = c.body.trim ( ) ;
801
if ! body.is_empty ( ) {
802
for line in body.lines ( ) .take ( 20 ) {
803
text.push_str ( " " ) ;
804
text.push_str ( line) ;
805
text.push ( ' \n ' ) ;
806
}
807
}
808
}
c08cec37 Andy McCall 20 days ago ↶
809
810
811
text.push_str ( & format! ( " \n ## Files ({} )\n \n " , diffs.len ( ) ) ) ;
812
let mut parts: Vec< ( String, String) > = Vec :: with_capacity( diffs.len ( ) ) ;
7d2eb590 Andy McCall 1 month ago ↶
813
for f in diffs {
c08cec37 Andy McCall 20 days ago ↶
814
let ( added, removed) = f.hunks.iter ( ) .fold ( ( 0 , 0 ) , | ( a , r ) , h | ( a + h.added.len ( ) , r + h.removed.len ( ) ) ) ;
815
text.push_str ( & format! ( " - {} ({} , +{added} -{removed} )\n " , f.path, f.kind) ) ;
816
let mut diff = format! ( " ### {} ({} )\n " , f.path, f.kind) ;
7d2eb590 Andy McCall 1 month ago ↶
817
if let Some ( from) = & f.from {
818
diff.push_str ( & format! ( " renamed from {from} \n " ) ) ;
819
}
820
let binary = f.hunks.iter ( ) .any ( | h | h.added.iter ( ) .chain ( h.removed.iter ( ) .map ( | ( _, l ) | l ) ) .any ( | l | l.contains ( & 0 ) ) ) ;
821
if binary {
822
diff.push_str ( " (binary)\n \n " ) ;
c08cec37 Andy McCall 20 days ago ↶
823
parts.push ( ( f.path.clone ( ) , diff) ) ;
7d2eb590 Andy McCall 1 month ago ↶
824
continue ;
825
}
826
diff.push_str ( " ```\n " ) ;
827
for h in & f.hunks {
828
diff.push_str ( & format! ( " @@ after line {} @@\n " , h.base_line) ) ;
829
for ( _ , l) in & h.removed {
830
diff.push ( ' -' ) ;
831
diff.push_str ( String :: from_utf8_lossy( l) .trim_end_matches ( ' \n ' ) ) ;
832
diff.push ( ' \n ' ) ;
833
}
834
for l in & h.added {
835
diff.push ( ' +' ) ;
836
diff.push_str ( String :: from_utf8_lossy( l) .trim_end_matches ( ' \n ' ) ) ;
837
diff.push ( ' \n ' ) ;
838
}
839
}
840
diff.push_str ( " ```\n \n " ) ;
c08cec37 Andy McCall 20 days ago ↶
841
parts.push ( ( f.path.clone ( ) , diff) ) ;
7d2eb590 Andy McCall 1 month ago ↶
842
}
c08cec37 Andy McCall 20 days ago ↶
843
text.push_str ( " \n ## Diff\n \n " ) ;
844
845
846
847
let head = text.chars ( ) .count ( ) ;
848
let mut room = budget.saturating_sub ( head + 200 ) ;
849
let mut left_out = Vec :: new( ) ;
850
for ( path, diff) in parts {
851
let n = diff.chars ( ) .count ( ) ;
852
if n < = room {
853
text.push_str ( & diff) ;
854
room - = n;
855
} else if room > = 1_500 {
856
let keep = room - 80 ;
857
text.extend ( diff.chars ( ) .take ( keep) ) ;
858
text.push_str ( " \n (the rest of this file was cut to fit)\n ```\n \n " ) ;
859
left_out.push ( format! ( " {path} (cut)" ) ) ;
860
room = 0 ;
861
} else {
862
left_out.push ( path) ;
863
}
864
}
865
if ! left_out.is_empty ( ) {
866
let names: String = left_out.join ( " , " ) .chars ( ) .take ( room.max ( 400 ) ) .collect ( ) ;
867
text.push_str ( & format! ( " (left out to fit the context budget, {} file(s): {names} )\n " , left_out.len ( ) ) ) ;
7d2eb590 Andy McCall 1 month ago ↶
868
}
869
text
870
}
871
872
873
874
pub fn review_system_prompt ( a : & Assistant, site : & str , prompts : & str ) -> String {
875
let mut s = format! (
876
" You are {name} , an AI assistant reviewing a proposal on {site} , an OxygenHub site. \
877
A person asked for your review; it is recorded as a review comment made via you, under their name. \
878
You cannot approve: only people approve. Answer in Markdown: start with a one-paragraph summary, \
879
then findings (correctness first, then clarity), each naming the file and quoting the lines it is about; \
880
keep praise out unless something is notably well done; say so plainly when you find nothing wrong." ,
881
name = a.name
882
) ;
883
if ! prompts.trim ( ) .is_empty ( ) {
884
s.push_str ( " \n \n " ) ;
885
s.push_str ( prompts.trim ( ) ) ;
886
}
887
s
888
}
889
890
891
892
893
894
pub async fn request_review (
895
app : & Shared,
896
row : & crate:: db:: repos:: RepoRow,
897
p : & crate:: db:: proposals:: ProposalRow,
898
by : & crate:: db:: accounts:: Account,
899
a : Assistant,
900
) -> Result< ( ) , String> {
901
app.assistant_gate.lock ( ) .unwrap_or_else ( | e | e.into_inner ( ) ) .take ( row.id, p.id, & a.name) ? ;
902
let pool = & app.db;
903
crate :: db:: proposals:: add_event( pool, p.id, & by.username, & format! ( " asked {} to review" , a.name) , " " ) .await.ok ( ) ;
904
crate :: db:: accounts:: audit(
905
pool,
906
Some ( by) ,
907
" assistant.asked" ,
908
& format! ( " {} /{} " , row.owner, row.name) ,
909
& format! ( " {} #{} " , a.name, p.number) ,
910
)
911
.await
912
.ok ( ) ;
913
let ( app, row, p, by) = ( app.clone ( ) , row.clone ( ) , p.clone ( ) , by.clone ( ) ) ;
914
tokio:: spawn( async move {
915
let outcome = answer_review ( & app, & row, & p, & a) .await;
916
app.assistant_gate.lock ( ) .unwrap_or_else ( | e | e.into_inner ( ) ) .release ( p.id, & a.name) ;
917
match outcome {
918
Ok ( body) => {
919
if crate :: db:: proposals:: add_review_via( & app.db, p.id, by.id, & by.username, " comment" , & body, & a.name) .await.is_ok ( ) {
920
crate :: db:: proposals:: add_event( & app.db, p.id, & by.username, & format! ( " review.comment via {} " , a.name) , " " ) .await.ok ( ) ;
921
crate :: web:: proposals:: reviewed( & app, & row, & p, & by, " comment" ) .await;
922
crate :: hooks:: emit(
923
& app,
924
& row,
925
" review" ,
926
& by.username,
927
serde_json:: json! ( { " number" : p.number, " verdict" : " comment" , " via" : a.name } ) ,
928
)
929
.await;
930
}
931
}
932
Err ( why) => {
933
crate :: db:: proposals:: add_event( & app.db, p.id, & by.username, & format! ( " {} did not answer" , a.name) , & why) .await.ok ( ) ;
934
}
935
}
936
} ) ;
937
Ok ( ( ) )
938
}
939
940
async fn answer_review (
941
app : & Shared,
942
row : & crate:: db:: repos:: RepoRow,
943
p : & crate:: db:: proposals:: ProposalRow,
944
a : & Assistant,
945
) -> Result< String, String> {
946
let repo = crate :: repos:: names:: RepoName:: new( & row.owner, & row.name) .ok_or ( " bad repository name" ) ? ;
947
let loaded = crate :: web:: proposals:: load( app, & repo, p.clone ( ) ) .await.map_err ( | e | format! ( " the proposal could not be loaded: {e} " ) ) ? ;
948
let budget = usize :: try_from( a.budget) .unwrap_or ( DEFAULT_BUDGET as usize ) .max ( 1_000 ) ;
949
let prompts = prompt_for_repo ( & app.db, row) .await.map_err ( | e | e.to_string ( ) ) ? ;
950
let system = review_system_prompt ( a, & app.config.site.name, & prompts) ;
119fd17d Andy McCall 19 days ago ↶
951
ask_within ( app, a, & system, budget, BACKGROUND_TIMEOUT , | room | review_context ( row, p, & loaded, room) , | _| { } ) .await
c08cec37 Andy McCall 20 days ago ↶
952
}
953
954
955
956
957
958
async fn ask_within (
959
app : & Shared,
960
a : & Assistant,
961
system : & str ,
962
budget : usize ,
963
wait : Duration,
964
context : impl Fn( usize ) -> String,
119fd17d Andy McCall 19 days ago ↶
965
mut part : impl FnMut( &str ) ,
c08cec37 Andy McCall 20 days ago ↶
966
) -> Result< String, String> {
967
let room = | b : usize | b.saturating_sub ( system.chars ( ) .count ( ) ) ;
119fd17d Andy McCall 19 days ago ↶
968
969
970
match ask_streaming ( app, a, system, & context ( room ( budget) ) , wait, & mut part) .await {
c08cec37 Andy McCall 20 days ago ↶
971
Err ( e) if too_long ( & e) => {
972
let smaller = ( budget / 3 ) .max ( 1_000 ) ;
973
tracing:: info! ( " assistant {}: too long at {budget} characters ({e}); asking again at {smaller}" , a.name) ;
119fd17d Andy McCall 19 days ago ↶
974
ask_streaming ( app, a, system, & context ( room ( smaller) ) , wait, & mut part) .await.map_err ( | e2 | {
c08cec37 Andy McCall 20 days ago ↶
975
format! (
976
" the proposal was too large for {} 's model at {budget} characters and again at {smaller} ({e2} ): lower this assistant's context budget" ,
977
a.name
978
)
979
} )
980
}
981
Err ( e) if e.starts_with ( " no answer within" ) => Err ( format! (
982
" {e} : a large proposal on a slow or local model can take longer; lower this assistant's context budget, or use a faster model"
983
) ) ,
984
other => other,
985
}
986
}
987
988
989
fn too_long ( e : & str ) -> bool {
990
let l = e.to_lowercase ( ) ;
991
( l.starts_with ( " 400" ) | | l.starts_with ( " 413" ) | | l.starts_with ( " 422" ) )
992
& & [
993
" too long" ,
994
" too large" ,
995
" context length" ,
996
" context window" ,
997
" maximum context" ,
998
" too many tokens" ,
999
" exceeds" ,
1000
" reduce the length" ,
1001
" input length" ,
1002
]
1003
.iter ( )
1004
.any ( | k | l.contains ( k) )
ffb67a81 Andy McCall 22 days ago
1005
}
1006
1007
1008
1009
1010
pub fn summary_system_prompt ( a : & Assistant, site : & str , prompts : & str ) -> String {
1011
let mut s = format! (
1012
" You are {name} , an AI assistant working on {site} , an OxygenHub site, with a next-generation version control system \
1013
called Oxygen (its command is oxy). A proposal is Oxygen's equivalent of a merge request or pull request. \
1014
Please summarise the proposal and comment on it. A person asked for this; it is posted as a comment made via you, \
1015
under their name. Answer in Markdown: a short summary of what the proposal changes and why, then anything a reviewer \
1016
should look at closely; keep to what the description and the diff show." ,
1017
name = a.name
1018
) ;
1019
if ! prompts.trim ( ) .is_empty ( ) {
1020
s.push_str ( " \n \n " ) ;
1021
s.push_str ( prompts.trim ( ) ) ;
1022
}
1023
s
1024
}
1025
1026
1027
1028
pub async fn request_summary (
1029
app : & Shared,
1030
row : & crate:: db:: repos:: RepoRow,
1031
p : & crate:: db:: proposals:: ProposalRow,
1032
by : & crate:: db:: accounts:: Account,
1033
a : Assistant,
1034
) -> Result< ( ) , String> {
1035
app.assistant_gate.lock ( ) .unwrap_or_else ( | e | e.into_inner ( ) ) .take ( row.id, p.id, & a.name) ? ;
1036
let pool = & app.db;
1037
crate :: db:: proposals:: add_event( pool, p.id, & by.username, & format! ( " asked {} for a summary" , a.name) , " " ) .await.ok ( ) ;
1038
crate :: db:: accounts:: audit(
1039
pool,
1040
Some ( by) ,
1041
" assistant.asked" ,
1042
& format! ( " {} /{} " , row.owner, row.name) ,
1043
& format! ( " {} #{} summary" , a.name, p.number) ,
1044
)
1045
.await
1046
.ok ( ) ;
1047
let ( app, row, p, by) = ( app.clone ( ) , row.clone ( ) , p.clone ( ) , by.clone ( ) ) ;
1048
tokio:: spawn( async move {
1049
let outcome = answer_summary ( & app, & row, & p, & a) .await;
1050
app.assistant_gate.lock ( ) .unwrap_or_else ( | e | e.into_inner ( ) ) .release ( p.id, & a.name) ;
1051
match outcome {
1052
Ok ( body) => {
1053
crate :: db:: proposals:: add_comment_via( & app.db, p.id, by.id, & by.username, & body, & a.name) .await.ok ( ) ;
1054
}
1055
Err ( why) => {
1056
crate :: db:: proposals:: add_event( & app.db, p.id, & by.username, & format! ( " {} did not answer" , a.name) , & why) .await.ok ( ) ;
1057
}
1058
}
1059
} ) ;
1060
Ok ( ( ) )
1061
}
1062
1063
async fn answer_summary (
1064
app : & Shared,
1065
row : & crate:: db:: repos:: RepoRow,
1066
p : & crate:: db:: proposals:: ProposalRow,
1067
a : & Assistant,
1068
) -> Result< String, String> {
1069
let repo = crate :: repos:: names:: RepoName:: new( & row.owner, & row.name) .ok_or ( " bad repository name" ) ? ;
1070
let loaded = crate :: web:: proposals:: load( app, & repo, p.clone ( ) ) .await.map_err ( | e | format! ( " the proposal could not be loaded: {e} " ) ) ? ;
1071
let budget = usize :: try_from( a.budget) .unwrap_or ( DEFAULT_BUDGET as usize ) .max ( 1_000 ) ;
1072
let prompts = prompt_for_repo ( & app.db, row) .await.map_err ( | e | e.to_string ( ) ) ? ;
1073
let system = summary_system_prompt ( a, & app.config.site.name, & prompts) ;
119fd17d Andy McCall 19 days ago ↶
1074
ask_within ( app, a, & system, budget, BACKGROUND_TIMEOUT , | room | review_context ( row, p, & loaded, room) , | _| { } ) .await
7d2eb590 Andy McCall 1 month ago ↶
1075
}
1076
1077
1078
1079
1080
pub fn draft_system_prompt ( a : & Assistant, site : & str , prompts : & str ) -> String {
1081
let mut s = format! (
1082
" You are {name} , an AI assistant drafting the description of a proposal on {site} , an OxygenHub site, \
1083
for the person who will open or edit it; they read and change your draft before saving, and the draft is theirs. \
1084
Write Markdown for the description field only: no title line, no greeting, no sign-off. \
1085
Say what the changes do and why, what a reviewer should look at, and how to verify them; \
1086
keep to what the diff shows, and keep it short." ,
1087
name = a.name
1088
) ;
1089
if ! prompts.trim ( ) .is_empty ( ) {
1090
s.push_str ( " \n \n " ) ;
1091
s.push_str ( prompts.trim ( ) ) ;
1092
}
1093
s
1094
}
1095
1096
1097
pub struct Draft < 'a > {
1098
1099
1100
pub slot : i64 ,
1101
pub title : & 'a str ,
1102
pub target : & 'a str ,
1103
pub changes : & 'a [crate:: repos:: view:: ChangeView],
1104
pub diffs : & 'a [oxy_core:: repo:: FileDiff],
1105
}
1106
1107
1108
1109
pub async fn draft_description (
119fd17d Andy McCall 19 days ago ↶
1110
app : & Shared,
1111
row : & crate:: db:: repos:: RepoRow,
1112
by : & crate:: db:: accounts:: Account,
1113
a : & Assistant,
1114
d : Draft< '_ > ,
1115
) -> Result< String, String> {
1116
draft_description_streaming ( app, row, by, a, d, | _| { } ) .await
1117
}
1118
1119
1120
1121
pub async fn draft_description_streaming (
7d2eb590 Andy McCall 1 month ago ↶
1122
app : & Shared,
1123
row : & crate:: db:: repos:: RepoRow,
1124
by : & crate:: db:: accounts:: Account,
1125
a : & Assistant,
1126
d : Draft< '_ > ,
119fd17d Andy McCall 19 days ago ↶
1127
part : impl FnMut( &str ) ,
7d2eb590 Andy McCall 1 month ago ↶
1128
) -> Result< String, String> {
1129
let Draft { slot, title, target, changes, diffs } = d;
1130
app.assistant_gate.lock ( ) .unwrap_or_else ( | e | e.into_inner ( ) ) .take ( row.id, slot, & a.name) ? ;
1131
crate :: db:: accounts:: audit( & app.db, Some ( by) , " assistant.drafted" , & format! ( " {} /{} " , row.owner, row.name) , & a.name) .await.ok ( ) ;
1132
let budget = usize :: try_from( a.budget) .unwrap_or ( DEFAULT_BUDGET as usize ) .max ( 1_000 ) ;
1133
let prompts = prompt_for_repo ( & app.db, row) .await.map_err ( | e | e.to_string ( ) ) ;
1134
let outcome = match prompts {
1135
Ok ( prompts) => {
1136
let system = draft_system_prompt ( a, & app.config.site.name, & prompts) ;
119fd17d Andy McCall 19 days ago ↶
1137
ask_within ( app, a, & system, budget, CALL_TIMEOUT , | room | draft_context ( row, title, target, changes, diffs, room) , part) .await
7d2eb590 Andy McCall 1 month ago ↶
1138
}
1139
Err ( e) => Err ( e) ,
1140
} ;
1141
app.assistant_gate.lock ( ) .unwrap_or_else ( | e | e.into_inner ( ) ) .release ( slot, & a.name) ;
1142
outcome.map ( | t | t.trim ( ) .to_string ( ) )
1143
}