OXYGENHUB
# 2a83f5303458 oxygenhub / crates / hub / src / assistants.rs
28.7 KiB · Rust · last changed Variables for pipelines at the site, organisation and repository 1 month ago source blame history raw
1
//! AI assistants (hub spec §13.4, #97): chat-completion endpoints the hub
2
//! may ask to review a proposal or draft its description. Assistants are
3
//! kept at three levels, site, organisation and repository, and combined
4
//! downwards: a repository sees its organisation's and the site's beside
5
//! its own, the innermost of a name wins, and one disabled at an outer
6
//! level is off for everything inside it. Each level adds a prompt; the
7
//! prompt in force for a repository is the site's, the organisation's and
8
//! the repository's own, each under a heading. Tokens are sealed with
9
//! ChaCha20-Poly1305 under `keys/assistants.key`, shown masked, and never
10
//! leave the server.
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
/// The request shapes an assistant may speak.
21
pub const APIS: [&str; 2] = ["chat-completions", "anthropic-messages"];
22
/// Characters of context (prompt, description, diffs) a call may carry
23
/// unless the assistant says otherwise.
24
pub const DEFAULT_BUDGET: i64 = 120_000;
25
/// How long one call may take.
26
pub const CALL_TIMEOUT: Duration = Duration::from_secs(60);
27
/// The most an answer is kept.
28
const MAX_ANSWER: usize = 64 * 1024;
29
30
pub use crate::levels::Scope;
31
32
#[derive(Clone, Debug, FromRow)]
33
pub struct Assistant {
34
    pub id: i64,
35
    pub scope: String,
36
    pub scope_id: i64,
37
    pub name: String,
38
    pub endpoint: String,
39
    /// One of [`APIS`].
40
    pub api: String,
41
    pub model: String,
42
    /// Extra request headers, one `Name: value` per line.
43
    pub headers: String,
44
    /// The sealed token; empty when the endpoint needs none.
45
    pub token: Vec<u8>,
46
    pub enabled: bool,
47
    pub budget: i64,
48
    pub created_ms: i64,
49
    pub updated_ms: i64,
50
}
51
52
impl Assistant {
53
    pub fn scope(&self) -> Scope {
54
        match self.scope.as_str() {
55
            "org" => Scope::Org(self.scope_id),
56
            "repo" => Scope::Repo(self.scope_id),
57
            _ => Scope::Site,
58
        }
59
    }
60
61
    pub fn has_token(&self) -> bool {
62
        !self.token.is_empty()
63
    }
64
65
    /// The extra headers as pairs; malformed lines are skipped.
66
    pub fn header_list(&self) -> Vec<(String, String)> {
67
        parse_headers(&self.headers).unwrap_or_default()
68
    }
69
}
70
71
/// What a settings form supplies for an assistant.
72
#[derive(Clone, Debug, Default)]
73
pub struct Fields {
74
    pub name: String,
75
    pub endpoint: String,
76
    pub api: String,
77
    pub model: String,
78
    pub headers: String,
79
    pub enabled: bool,
80
    pub budget: i64,
81
}
82
83
/// `Name: value` lines to pairs: `Err(line)` names the first bad one.
84
pub fn parse_headers(text: &str) -> Result<Vec<(String, String)>, String> {
85
    let mut out = vec![];
86
    for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) {
87
        let Some((name, value)) = line.split_once(':') else { return Err(line.to_string()) };
88
        let (name, value) = (name.trim(), value.trim());
89
        let name_ok = !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
90
        if !name_ok || value.chars().any(|c| c.is_control()) {
91
            return Err(line.to_string());
92
        }
93
        out.push((name.to_string(), value.to_string()));
94
    }
95
    Ok(out)
96
}
97
98
// -------------------------------------------------------------- sealing
99
100
/// The key that seals tokens, kept in `<data>/keys/assistants.key`.
101
#[derive(Clone)]
102
pub struct SecretKey([u8; 32]);
103
104
impl SecretKey {
105
    pub fn load_or_create(keys: &Path) -> anyhow::Result<SecretKey> {
106
        std::fs::create_dir_all(keys)?;
107
        let path = keys.join("assistants.key");
108
        if let Ok(bytes) = std::fs::read(&path) {
109
            if bytes.len() == 32 {
110
                return Ok(SecretKey(bytes.try_into().unwrap()));
111
            }
112
        }
113
        let mut k = [0u8; 32];
114
        rand::rngs::OsRng.fill_bytes(&mut k);
115
        std::fs::write(&path, k)?;
116
        #[cfg(unix)]
117
        {
118
            use std::os::unix::fs::PermissionsExt;
119
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
120
        }
121
        Ok(SecretKey(k))
122
    }
123
124
    fn key(&self) -> aead::LessSafeKey {
125
        aead::LessSafeKey::new(aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &self.0).expect("key length"))
126
    }
127
128
    /// Seal a token: a random nonce, then the ciphertext and tag. An
129
    /// empty token seals to nothing, meaning "no token".
130
    pub fn seal(&self, plain: &str) -> Vec<u8> {
131
        if plain.is_empty() {
132
            return vec![];
133
        }
134
        let mut nonce = [0u8; 12];
135
        rand::rngs::OsRng.fill_bytes(&mut nonce);
136
        let mut out = plain.as_bytes().to_vec();
137
        self.key().seal_in_place_append_tag(aead::Nonce::assume_unique_for_key(nonce), aead::Aad::empty(), &mut out).expect("seal");
138
        let mut sealed = nonce.to_vec();
139
        sealed.extend(out);
140
        sealed
141
    }
142
143
    /// The token back, or `None` when the bytes were sealed under another
144
    /// key or damaged. Nothing opens to an empty token.
145
    pub fn open(&self, sealed: &[u8]) -> Option<String> {
146
        if sealed.is_empty() {
147
            return Some(String::new());
148
        }
149
        let (nonce, rest) = sealed.split_at_checked(12)?;
150
        let mut buf = rest.to_vec();
151
        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).ok()?;
152
        let plain = self.key().open_in_place(nonce, aead::Aad::empty(), &mut buf).ok()?;
153
        String::from_utf8(plain.to_vec()).ok()
154
    }
155
}
156
157
// ------------------------------------------------------------- storage
158
159
pub async fn list(pool: &Pool, scope: Scope) -> sqlx::Result<Vec<Assistant>> {
160
    sqlx::query_as("SELECT * FROM assistants WHERE scope = ? AND scope_id = ? ORDER BY name")
161
        .bind(scope.kind())
162
        .bind(scope.id())
163
        .fetch_all(pool)
164
        .await
165
}
166
167
pub async fn get(pool: &Pool, id: i64) -> sqlx::Result<Option<Assistant>> {
168
    sqlx::query_as("SELECT * FROM assistants WHERE id = ?").bind(id).fetch_optional(pool).await
169
}
170
171
/// Add an assistant; `None` when the level already has one of that name.
172
pub async fn create(pool: &Pool, scope: Scope, f: &Fields, token: &[u8]) -> sqlx::Result<Option<Assistant>> {
173
    let now = now_ms();
174
    let r = sqlx::query_as(
175
        "INSERT INTO assistants (scope, scope_id, name, endpoint, api, model, headers, token, enabled, budget, created_ms, updated_ms) \
176
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING *",
177
    )
178
    .bind(scope.kind())
179
    .bind(scope.id())
180
    .bind(&f.name)
181
    .bind(&f.endpoint)
182
    .bind(&f.api)
183
    .bind(&f.model)
184
    .bind(&f.headers)
185
    .bind(token)
186
    .bind(f.enabled)
187
    .bind(f.budget)
188
    .bind(now)
189
    .bind(now)
190
    .fetch_optional(pool)
191
    .await?;
192
    Ok(r)
193
}
194
195
/// Change an assistant's details; `token` is `None` to keep the stored
196
/// one. False when the name is taken at that level.
197
pub async fn update(pool: &Pool, id: i64, f: &Fields, token: Option<&[u8]>) -> sqlx::Result<bool> {
198
    let r = match token {
199
        Some(t) => sqlx::query(
200
            "UPDATE assistants SET name = ?, endpoint = ?, api = ?, model = ?, headers = ?, enabled = ?, budget = ?, token = ?, updated_ms = ? \
201
             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 <> ?)",
202
        )
203
        .bind(&f.name)
204
        .bind(&f.endpoint)
205
        .bind(&f.api)
206
        .bind(&f.model)
207
        .bind(&f.headers)
208
        .bind(f.enabled)
209
        .bind(f.budget)
210
        .bind(t)
211
        .bind(now_ms())
212
        .bind(id)
213
        .bind(&f.name)
214
        .bind(id)
215
        .execute(pool)
216
        .await?,
217
        None => sqlx::query(
218
            "UPDATE assistants SET name = ?, endpoint = ?, api = ?, model = ?, headers = ?, enabled = ?, budget = ?, updated_ms = ? \
219
             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 <> ?)",
220
        )
221
        .bind(&f.name)
222
        .bind(&f.endpoint)
223
        .bind(&f.api)
224
        .bind(&f.model)
225
        .bind(&f.headers)
226
        .bind(f.enabled)
227
        .bind(f.budget)
228
        .bind(now_ms())
229
        .bind(id)
230
        .bind(&f.name)
231
        .bind(id)
232
        .execute(pool)
233
        .await?,
234
    };
235
    Ok(r.rows_affected() == 1)
236
}
237
238
pub async fn set_enabled(pool: &Pool, id: i64, enabled: bool) -> sqlx::Result<()> {
239
    sqlx::query("UPDATE assistants SET enabled = ?, updated_ms = ? WHERE id = ?")
240
        .bind(enabled)
241
        .bind(now_ms())
242
        .bind(id)
243
        .execute(pool)
244
        .await?;
245
    Ok(())
246
}
247
248
pub async fn delete(pool: &Pool, id: i64) -> sqlx::Result<()> {
249
    sqlx::query("DELETE FROM assistants WHERE id = ?").bind(id).execute(pool).await?;
250
    Ok(())
251
}
252
253
/// Forget a level's assistants and prompt, when the organisation or
254
/// repository goes.
255
pub async fn delete_scope(pool: &Pool, scope: Scope) -> sqlx::Result<()> {
256
    sqlx::query("DELETE FROM assistants WHERE scope = ? AND scope_id = ?").bind(scope.kind()).bind(scope.id()).execute(pool).await?;
257
    sqlx::query("DELETE FROM assistant_prompts WHERE scope = ? AND scope_id = ?").bind(scope.kind()).bind(scope.id()).execute(pool).await?;
258
    Ok(())
259
}
260
261
/// The prompt a level adds, empty when none.
262
pub async fn prompt(pool: &Pool, scope: Scope) -> sqlx::Result<String> {
263
    Ok(sqlx::query_scalar("SELECT prompt FROM assistant_prompts WHERE scope = ? AND scope_id = ?")
264
        .bind(scope.kind())
265
        .bind(scope.id())
266
        .fetch_optional(pool)
267
        .await?
268
        .unwrap_or_default())
269
}
270
271
pub async fn set_prompt(pool: &Pool, scope: Scope, text: &str) -> sqlx::Result<()> {
272
    if text.trim().is_empty() {
273
        sqlx::query("DELETE FROM assistant_prompts WHERE scope = ? AND scope_id = ?")
274
            .bind(scope.kind())
275
            .bind(scope.id())
276
            .execute(pool)
277
            .await?;
278
    } else {
279
        sqlx::query(
280
            "INSERT INTO assistant_prompts (scope, scope_id, prompt, updated_ms) VALUES (?, ?, ?, ?) \
281
             ON CONFLICT (scope, scope_id) DO UPDATE SET prompt = excluded.prompt, updated_ms = excluded.updated_ms",
282
        )
283
        .bind(scope.kind())
284
        .bind(scope.id())
285
        .bind(text.trim())
286
        .bind(now_ms())
287
        .execute(pool)
288
        .await?;
289
    }
290
    Ok(())
291
}
292
293
// ----------------------------------------------------- what applies where
294
295
/// An assistant seen from a level: where it comes from, and whether it is
296
/// on once outer levels have had their say.
297
#[derive(Clone, Debug)]
298
pub struct Available {
299
    pub assistant: Assistant,
300
    /// `the site`, `the acme organisation`, or empty for the level's own.
301
    pub from: String,
302
    /// Off because a level above disabled an assistant of this name.
303
    pub off_above: bool,
304
}
305
306
impl Available {
307
    pub fn on(&self) -> bool {
308
        self.assistant.enabled && !self.off_above
309
    }
310
}
311
312
/// Every assistant a level sees, outermost first, one per name: the
313
/// innermost definition of a name wins, and a name disabled at an outer
314
/// level is off inside it whatever the inner level says.
315
pub async fn available(pool: &Pool, scope: Scope, owner: &str) -> sqlx::Result<Vec<Available>> {
316
    let mut levels = crate::levels::above(pool, scope, owner).await?;
317
    levels.push((scope, String::new()));
318
    let mut out: Vec<Available> = vec![];
319
    let mut off: Vec<String> = vec![];
320
    for (level, from) in levels {
321
        for a in list(pool, level).await? {
322
            let off_above = off.iter().any(|n| n.eq_ignore_ascii_case(&a.name));
323
            if !a.enabled && !off.iter().any(|n| n.eq_ignore_ascii_case(&a.name)) {
324
                off.push(a.name.clone());
325
            }
326
            out.retain(|o| !o.assistant.name.eq_ignore_ascii_case(&a.name));
327
            out.push(Available { assistant: a, from: from.clone(), off_above });
328
        }
329
    }
330
    Ok(out)
331
}
332
333
/// The assistants a repository may ask, by name.
334
pub async fn enabled_for_repo(pool: &Pool, repo: &crate::db::repos::RepoRow) -> sqlx::Result<Vec<Assistant>> {
335
    Ok(available(pool, Scope::Repo(repo.id), &repo.owner).await?.into_iter().filter(Available::on).map(|a| a.assistant).collect())
336
}
337
338
/// The prompts a level inherits, outermost first: (where from, text),
339
/// only the levels that set one.
340
pub async fn inherited_prompts(pool: &Pool, scope: Scope, owner: &str) -> sqlx::Result<Vec<(String, String)>> {
341
    let mut out = vec![];
342
    for (level, from) in crate::levels::above(pool, scope, owner).await? {
343
        let text = prompt(pool, level).await?;
344
        if !text.is_empty() {
345
            out.push((from, text));
346
        }
347
    }
348
    Ok(out)
349
}
350
351
/// The prompt in force for a repository: each level's text under a
352
/// heading, outermost first, so a project adds to what the site says.
353
pub async fn prompt_for_repo(pool: &Pool, repo: &crate::db::repos::RepoRow) -> sqlx::Result<String> {
354
    let scope = Scope::Repo(repo.id);
355
    let mut parts = inherited_prompts(pool, scope, &repo.owner).await?;
356
    let own = prompt(pool, scope).await?;
357
    if !own.is_empty() {
358
        parts.push(("this repository".to_string(), own));
359
    }
360
    Ok(parts.into_iter().map(|(from, text)| format!("## Instructions from {from}\n\n{text}\n")).collect::<Vec<_>>().join("\n"))
361
}
362
363
// -------------------------------------------------------------- calling
364
365
/// Ask an assistant: the system prompt and the request, the answer's
366
/// text. Errors are for the person who asked: a status and the first
367
/// line of what the endpoint said, or why no answer came.
368
pub async fn ask(app: &Shared, a: &Assistant, system: &str, user: &str) -> Result<String, String> {
369
    let Some(token) = app.assistant_key.open(&a.token) else {
370
        return Err("its token cannot be read: set it again".into());
371
    };
372
    let client = reqwest::Client::builder()
373
        .timeout(CALL_TIMEOUT)
374
        .user_agent(format!("oxygenhub/{}", env!("CARGO_PKG_VERSION")))
375
        .build()
376
        .map_err(|e| e.to_string())?;
377
    let mut req = client.post(&a.endpoint).header("content-type", "application/json");
378
    let body = match a.api.as_str() {
379
        "anthropic-messages" => {
380
            if !token.is_empty() {
381
                req = req.header("x-api-key", &token);
382
            }
383
            req = req.header("anthropic-version", "2023-06-01");
384
            serde_json::json!({
385
                "model": a.model,
386
                "max_tokens": 4096,
387
                "system": system,
388
                "messages": [{ "role": "user", "content": user }],
389
            })
390
        }
391
        _ => {
392
            if !token.is_empty() {
393
                req = req.header("authorization", format!("Bearer {token}"));
394
            }
395
            serde_json::json!({
396
                "model": a.model,
397
                "messages": [
398
                    { "role": "system", "content": system },
399
                    { "role": "user", "content": user },
400
                ],
401
            })
402
        }
403
    };
404
    for (name, value) in a.header_list() {
405
        req = req.header(name, value);
406
    }
407
    let r = req.json(&body).send().await.map_err(|e| {
408
        if e.is_timeout() {
409
            "no answer within 60 seconds".to_string()
410
        } else {
411
            scrub(&e.to_string(), &token)
412
        }
413
    })?;
414
    let status = r.status();
415
    let text: String = r.text().await.unwrap_or_default().chars().take(MAX_ANSWER).collect();
416
    if !status.is_success() {
417
        let why = serde_json::from_str::<serde_json::Value>(&text)
418
            .ok()
419
            .and_then(|v| v["error"]["message"].as_str().or(v["error"].as_str()).or(v["message"].as_str()).map(str::to_string))
420
            .unwrap_or_else(|| text.lines().next().unwrap_or("").chars().take(160).collect());
421
        return Err(scrub(&format!("{} {}", status.as_u16(), why.trim()), &token));
422
    }
423
    let v: serde_json::Value = serde_json::from_str(&text).map_err(|_| "the answer was not JSON".to_string())?;
424
    let answer = match a.api.as_str() {
425
        "anthropic-messages" => v["content"]
426
            .as_array()
427
            .map(|parts| parts.iter().filter_map(|p| p["text"].as_str()).collect::<Vec<_>>().join(""))
428
            .unwrap_or_default(),
429
        _ => match &v["choices"][0]["message"]["content"] {
430
            serde_json::Value::String(s) => s.clone(),
431
            serde_json::Value::Array(parts) => parts.iter().filter_map(|p| p["text"].as_str()).collect::<Vec<_>>().join(""),
432
            _ => String::new(),
433
        },
434
    };
435
    if answer.trim().is_empty() {
436
        return Err("the answer carried no text".into());
437
    }
438
    Ok(answer)
439
}
440
441
/// A tiny exchange, for the settings page's TEST: the start of the answer.
442
pub async fn test(app: &Shared, a: &Assistant) -> Result<String, String> {
443
    let answer = ask(app, a, "You are being connected to an OxygenHub site. Answer briefly.", "Reply with the single word OK.").await?;
444
    Ok(answer.trim().chars().take(80).collect())
445
}
446
447
/// Never let the token through in an error message.
448
fn scrub(text: &str, token: &str) -> String {
449
    if token.is_empty() {
450
        text.to_string()
451
    } else {
452
        text.replace(token, "***")
453
    }
454
}
455
456
#[cfg(test)]
457
mod tests {
458
    use super::*;
459
460
    #[test]
461
    fn tokens_seal_and_open_only_under_their_key() {
462
        let dir = tempfile::tempdir().unwrap();
463
        let k = SecretKey::load_or_create(dir.path()).unwrap();
464
        let sealed = k.seal("sk-very-secret");
465
        assert_ne!(sealed, b"sk-very-secret");
466
        assert!(!String::from_utf8_lossy(&sealed).contains("secret"));
467
        assert_eq!(k.open(&sealed).as_deref(), Some("sk-very-secret"));
468
        assert_eq!(SecretKey::load_or_create(dir.path()).unwrap().open(&sealed).as_deref(), Some("sk-very-secret"), "the key is kept");
469
        let other = SecretKey::load_or_create(tempfile::tempdir().unwrap().path()).unwrap();
470
        assert_eq!(other.open(&sealed), None);
471
        assert_eq!(k.open(&[1, 2, 3]), None);
472
        assert_eq!(k.seal(""), Vec::<u8>::new());
473
        assert_eq!(k.open(&[]).as_deref(), Some(""));
474
    }
475
476
    #[test]
477
    fn headers_parse_or_name_the_bad_line() {
478
        assert_eq!(
479
            parse_headers("X-Org: acme\n\n OpenAI-Beta : v1 ").unwrap(),
480
            vec![("X-Org".into(), "acme".into()), ("OpenAI-Beta".into(), "v1".into())]
481
        );
482
        assert_eq!(parse_headers("no colon").unwrap_err(), "no colon");
483
        assert_eq!(parse_headers("bad name: x").unwrap_err(), "bad name: x");
484
    }
485
}
486
487
// ------------------------------------------------------- reviewing
488
489
/// At most this many assistant calls per repository per hour.
490
pub const CALLS_PER_HOUR: usize = 30;
491
492
/// Who is answering what, and recent calls per repository.
493
#[derive(Default)]
494
pub struct Gate {
495
    busy: std::collections::HashSet<(i64, String)>,
496
    recent: std::collections::HashMap<i64, Vec<i64>>,
497
}
498
499
impl Gate {
500
    /// Take the slot for (proposal, assistant), or say why not.
501
    fn take(&mut self, repo_id: i64, proposal_id: i64, name: &str) -> Result<(), String> {
502
        let key = (proposal_id, name.to_lowercase());
503
        if self.busy.contains(&key) {
504
            return Err(format!("{name} is already answering this proposal"));
505
        }
506
        let now = now_ms();
507
        let calls = self.recent.entry(repo_id).or_default();
508
        calls.retain(|t| now - *t < 3_600_000);
509
        if calls.len() >= CALLS_PER_HOUR {
510
            return Err(format!("this repository has asked assistants {CALLS_PER_HOUR} times in the last hour; try later"));
511
        }
512
        calls.push(now);
513
        self.busy.insert(key);
514
        Ok(())
515
    }
516
517
    fn release(&mut self, proposal_id: i64, name: &str) {
518
        self.busy.remove(&(proposal_id, name.to_lowercase()));
519
    }
520
}
521
522
/// What a reviewer is told about a proposal: its title, description,
523
/// changes and diff, cut to `budget` characters.
524
pub fn review_context(
525
    row: &crate::db::repos::RepoRow,
526
    p: &crate::db::proposals::ProposalRow,
527
    loaded: &crate::web::proposals::Loaded,
528
    budget: usize,
529
) -> String {
530
    let mut head =
531
        format!("# Proposal #{}: {}\n\nRepository {}/{} · into {} · by {}\n\n", p.number, p.title, row.owner, row.name, p.target, p.author);
532
    if !p.body.trim().is_empty() {
533
        head.push_str("## Description\n\n");
534
        head.push_str(p.body.trim());
535
        head.push_str("\n\n");
536
    }
537
    context_text(head, &loaded.changes, &loaded.diffs, budget)
538
}
539
540
/// What a drafter is told: the title so far, the changes and the diff.
541
pub fn draft_context(
542
    row: &crate::db::repos::RepoRow,
543
    title: &str,
544
    target: &str,
545
    changes: &[crate::repos::view::ChangeView],
546
    diffs: &[oxy_core::repo::FileDiff],
547
    budget: usize,
548
) -> String {
549
    let head = format!(
550
        "# Proposal: {}\n\nRepository {}/{} · into {}\n\n",
551
        if title.trim().is_empty() { "(untitled)" } else { title.trim() },
552
        row.owner,
553
        row.name,
554
        target
555
    );
556
    context_text(head, changes, diffs, budget)
557
}
558
559
/// `head`, the list of changes, then the diff as `-`/`+` lines per hunk,
560
/// binary files noted, the diff cut so the whole fits `budget`.
561
fn context_text(mut text: String, changes: &[crate::repos::view::ChangeView], diffs: &[oxy_core::repo::FileDiff], budget: usize) -> String {
562
    text.push_str(&format!("## Changes ({})\n\n", changes.len()));
563
    for c in changes {
564
        text.push_str(&format!("- {} {}\n", c.short, c.title));
565
        let body = c.body.trim();
566
        if !body.is_empty() {
567
            for line in body.lines().take(20) {
568
                text.push_str("  ");
569
                text.push_str(line);
570
                text.push('\n');
571
            }
572
        }
573
    }
574
    text.push_str("\n## Diff\n\n");
575
    let head = text.chars().count();
576
    let mut diff = String::new();
577
    for f in diffs {
578
        diff.push_str(&format!("### {} ({})\n", f.path, f.kind));
579
        if let Some(from) = &f.from {
580
            diff.push_str(&format!("renamed from {from}\n"));
581
        }
582
        let binary = f.hunks.iter().any(|h| h.added.iter().chain(h.removed.iter().map(|(_, l)| l)).any(|l| l.contains(&0)));
583
        if binary {
584
            diff.push_str("(binary)\n\n");
585
            continue;
586
        }
587
        diff.push_str("```\n");
588
        for h in &f.hunks {
589
            diff.push_str(&format!("@@ after line {} @@\n", h.base_line));
590
            for (_, l) in &h.removed {
591
                diff.push('-');
592
                diff.push_str(String::from_utf8_lossy(l).trim_end_matches('\n'));
593
                diff.push('\n');
594
            }
595
            for l in &h.added {
596
                diff.push('+');
597
                diff.push_str(String::from_utf8_lossy(l).trim_end_matches('\n'));
598
                diff.push('\n');
599
            }
600
        }
601
        diff.push_str("```\n\n");
602
    }
603
    let room = budget.saturating_sub(head + 80);
604
    if diff.chars().count() > room {
605
        let cut: String = diff.chars().take(room).collect();
606
        text.push_str(&cut);
607
        text.push_str("\n\n(the diff was cut here to fit the context budget)\n");
608
    } else {
609
        text.push_str(&diff);
610
    }
611
    text
612
}
613
614
/// The system prompt for a review: who the assistant is, what a review
615
/// here is, then the prompts the levels set.
616
pub fn review_system_prompt(a: &Assistant, site: &str, prompts: &str) -> String {
617
    let mut s = format!(
618
        "You are {name}, an AI assistant reviewing a proposal on {site}, an OxygenHub site. \
619
         A person asked for your review; it is recorded as a review comment made via you, under their name. \
620
         You cannot approve: only people approve. Answer in Markdown: start with a one-paragraph summary, \
621
         then findings (correctness first, then clarity), each naming the file and quoting the lines it is about; \
622
         keep praise out unless something is notably well done; say so plainly when you find nothing wrong.",
623
        name = a.name
624
    );
625
    if !prompts.trim().is_empty() {
626
        s.push_str("\n\n");
627
        s.push_str(prompts.trim());
628
    }
629
    s
630
}
631
632
/// Ask `a` to review proposal `p` for `by`: records the request, calls the
633
/// endpoint in the background, and stores the answer as a `comment` review
634
/// via the assistant (or an event saying why none came). `Err` is for the
635
/// person who asked, when nothing was started.
636
pub async fn request_review(
637
    app: &Shared,
638
    row: &crate::db::repos::RepoRow,
639
    p: &crate::db::proposals::ProposalRow,
640
    by: &crate::db::accounts::Account,
641
    a: Assistant,
642
) -> Result<(), String> {
643
    app.assistant_gate.lock().unwrap_or_else(|e| e.into_inner()).take(row.id, p.id, &a.name)?;
644
    let pool = &app.db;
645
    crate::db::proposals::add_event(pool, p.id, &by.username, &format!("asked {} to review", a.name), "").await.ok();
646
    crate::db::accounts::audit(
647
        pool,
648
        Some(by),
649
        "assistant.asked",
650
        &format!("{}/{}", row.owner, row.name),
651
        &format!("{} #{}", a.name, p.number),
652
    )
653
    .await
654
    .ok();
655
    let (app, row, p, by) = (app.clone(), row.clone(), p.clone(), by.clone());
656
    tokio::spawn(async move {
657
        let outcome = answer_review(&app, &row, &p, &a).await;
658
        app.assistant_gate.lock().unwrap_or_else(|e| e.into_inner()).release(p.id, &a.name);
659
        match outcome {
660
            Ok(body) => {
661
                if crate::db::proposals::add_review_via(&app.db, p.id, by.id, &by.username, "comment", &body, &a.name).await.is_ok() {
662
                    crate::db::proposals::add_event(&app.db, p.id, &by.username, &format!("review.comment via {}", a.name), "").await.ok();
663
                    crate::web::proposals::reviewed(&app, &row, &p, &by, "comment").await;
664
                    crate::hooks::emit(
665
                        &app,
666
                        &row,
667
                        "review",
668
                        &by.username,
669
                        serde_json::json!({ "number": p.number, "verdict": "comment", "via": a.name }),
670
                    )
671
                    .await;
672
                }
673
            }
674
            Err(why) => {
675
                crate::db::proposals::add_event(&app.db, p.id, &by.username, &format!("{} did not answer", a.name), &why).await.ok();
676
            }
677
        }
678
    });
679
    Ok(())
680
}
681
682
async fn answer_review(
683
    app: &Shared,
684
    row: &crate::db::repos::RepoRow,
685
    p: &crate::db::proposals::ProposalRow,
686
    a: &Assistant,
687
) -> Result<String, String> {
688
    let repo = crate::repos::names::RepoName::new(&row.owner, &row.name).ok_or("bad repository name")?;
689
    let loaded = crate::web::proposals::load(app, &repo, p.clone()).await.map_err(|e| format!("the proposal could not be loaded: {e}"))?;
690
    let budget = usize::try_from(a.budget).unwrap_or(DEFAULT_BUDGET as usize).max(1_000);
691
    let prompts = prompt_for_repo(&app.db, row).await.map_err(|e| e.to_string())?;
692
    let system = review_system_prompt(a, &app.config.site.name, &prompts);
693
    let user = review_context(row, p, &loaded, budget.saturating_sub(system.chars().count()));
694
    ask(app, a, &system, &user).await
695
}
696
697
// -------------------------------------------------------- drafting
698
699
/// The system prompt for drafting a proposal's description.
700
pub fn draft_system_prompt(a: &Assistant, site: &str, prompts: &str) -> String {
701
    let mut s = format!(
702
        "You are {name}, an AI assistant drafting the description of a proposal on {site}, an OxygenHub site, \
703
         for the person who will open or edit it; they read and change your draft before saving, and the draft is theirs. \
704
         Write Markdown for the description field only: no title line, no greeting, no sign-off. \
705
         Say what the changes do and why, what a reviewer should look at, and how to verify them; \
706
         keep to what the diff shows, and keep it short.",
707
        name = a.name
708
    );
709
    if !prompts.trim().is_empty() {
710
        s.push_str("\n\n");
711
        s.push_str(prompts.trim());
712
    }
713
    s
714
}
715
716
/// What a description is drafted from.
717
pub struct Draft<'a> {
718
    /// The proposal's id, or minus the repository's for one not yet opened:
719
    /// one draft per assistant at a time for it.
720
    pub slot: i64,
721
    pub title: &'a str,
722
    pub target: &'a str,
723
    pub changes: &'a [crate::repos::view::ChangeView],
724
    pub diffs: &'a [oxy_core::repo::FileDiff],
725
}
726
727
/// Ask `a` for a description, now; the answer goes into the editor,
728
/// nothing is saved. `Err` is for the person.
729
pub async fn draft_description(
730
    app: &Shared,
731
    row: &crate::db::repos::RepoRow,
732
    by: &crate::db::accounts::Account,
733
    a: &Assistant,
734
    d: Draft<'_>,
735
) -> Result<String, String> {
736
    let Draft { slot, title, target, changes, diffs } = d;
737
    app.assistant_gate.lock().unwrap_or_else(|e| e.into_inner()).take(row.id, slot, &a.name)?;
738
    crate::db::accounts::audit(&app.db, Some(by), "assistant.drafted", &format!("{}/{}", row.owner, row.name), &a.name).await.ok();
739
    let budget = usize::try_from(a.budget).unwrap_or(DEFAULT_BUDGET as usize).max(1_000);
740
    let prompts = prompt_for_repo(&app.db, row).await.map_err(|e| e.to_string());
741
    let outcome = match prompts {
742
        Ok(prompts) => {
743
            let system = draft_system_prompt(a, &app.config.site.name, &prompts);
744
            let user = draft_context(row, title, target, changes, diffs, budget.saturating_sub(system.chars().count()));
745
            ask(app, a, &system, &user).await
746
        }
747
        Err(e) => Err(e),
748
    };
749
    app.assistant_gate.lock().unwrap_or_else(|e| e.into_inner()).release(slot, &a.name);
750
    outcome.map(|t| t.trim().to_string())
751
}