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