OXYGENHUB
# e71846aa07b9 oxygenhub / crates / hub / src / web / assistants.rs
7.5 KiB · Rust · last changed AI assistants: settings per site, organisation and repository 1 month ago source blame history raw
1
//! The AI assistants panel (hub spec §13.4, #97) shared by the
2
//! administration, organisation and repository settings pages: the
3
//! level's own assistants, the ones it inherits, and its prompt.
4
5
use crate::assistants::{self, Assistant, Available, Fields, Scope, APIS, DEFAULT_BUDGET};
6
use crate::auth::Viewer;
7
use crate::db::accounts;
8
use crate::Shared;
9
use serde::Deserialize;
10
11
/// Whose panel.
12
pub struct Where {
13
    pub scope: Scope,
14
    /// The owner name, so a repository finds its organisation.
15
    pub owner: String,
16
    /// What the audit log names.
17
    pub label: String,
18
}
19
20
#[derive(Deserialize)]
21
pub struct AssistantForm {
22
    #[serde(rename = "_csrf")]
23
    pub csrf_token: String,
24
    #[serde(default)]
25
    action: String,
26
    #[serde(default)]
27
    id: Option<i64>,
28
    #[serde(default)]
29
    name: String,
30
    #[serde(default)]
31
    endpoint: String,
32
    #[serde(default)]
33
    api: String,
34
    #[serde(default)]
35
    model: String,
36
    #[serde(default)]
37
    headers: String,
38
    #[serde(default)]
39
    token: String,
40
    #[serde(default)]
41
    enabled: Option<String>,
42
    #[serde(default)]
43
    budget: String,
44
    #[serde(default)]
45
    prompt: String,
46
}
47
48
/// Everything the panel shows.
49
pub struct Panel {
50
    /// The level's own assistants, each with whether a level above turned
51
    /// its name off.
52
    pub own: Vec<Available>,
53
    /// The ones the levels above provide, outermost first.
54
    pub inherited: Vec<Available>,
55
    pub prompt: String,
56
    /// (where from, text) for each level above that set a prompt.
57
    pub inherited_prompts: Vec<(String, String)>,
58
    pub apis: Vec<&'static str>,
59
    pub default_budget: i64,
60
}
61
62
pub async fn panel(app: &Shared, at: &Where) -> sqlx::Result<Panel> {
63
    let (own, inherited): (Vec<_>, Vec<_>) =
64
        assistants::available(&app.db, at.scope, &at.owner).await?.into_iter().partition(|a| a.from.is_empty());
65
    Ok(Panel {
66
        own,
67
        inherited,
68
        prompt: assistants::prompt(&app.db, at.scope).await?,
69
        inherited_prompts: assistants::inherited_prompts(&app.db, at.scope, &at.owner).await?,
70
        apis: APIS.to_vec(),
71
        default_budget: DEFAULT_BUDGET,
72
    })
73
}
74
75
fn name_ok(name: &str) -> bool {
76
    !name.is_empty() && name.chars().count() <= 40 && name.chars().all(|c| c.is_alphanumeric() || matches!(c, ' ' | '.' | '-' | '_'))
77
}
78
79
fn endpoint_ok(url: &str) -> bool {
80
    (url.starts_with("http://") || url.starts_with("https://")) && url.len() <= 2000 && !url.contains(char::is_whitespace)
81
}
82
83
/// The form's details checked: `Err` is the message for the person.
84
fn fields(f: &AssistantForm) -> Result<Fields, String> {
85
    let name = f.name.trim().to_string();
86
    if !name_ok(&name) {
87
        return Err("An assistant's name is up to 40 letters, digits, spaces, dots, dashes or underscores.".into());
88
    }
89
    let endpoint = f.endpoint.trim().to_string();
90
    if !endpoint_ok(&endpoint) {
91
        return Err("The endpoint is the full URL the request is posted to, starting with https://.".into());
92
    }
93
    if !APIS.contains(&f.api.as_str()) {
94
        return Err("The API is chat-completions or anthropic-messages.".into());
95
    }
96
    let model = f.model.trim().to_string();
97
    if model.is_empty() || model.len() > 100 || model.contains(char::is_whitespace) {
98
        return Err("A model name is needed, such as claude-opus-5-5 or gpt-5.".into());
99
    }
100
    let headers = f.headers.trim().to_string();
101
    if let Err(line) = assistants::parse_headers(&headers) {
102
        return Err(format!("Extra headers are one Name: value per line; this line is not: {line}"));
103
    }
104
    if headers.lines().count() > 10 {
105
        return Err("Up to ten extra headers.".into());
106
    }
107
    let budget = if f.budget.trim().is_empty() {
108
        DEFAULT_BUDGET
109
    } else {
110
        match f.budget.trim().parse::<i64>() {
111
            Ok(n) if (1_000..=2_000_000).contains(&n) => n,
112
            _ => return Err("The context budget is a number of characters from 1000 to 2000000.".into()),
113
        }
114
    };
115
    Ok(Fields { name, endpoint, api: f.api.clone(), model, headers, enabled: f.enabled.is_some(), budget })
116
}
117
118
/// Apply the panel's form: `Ok(notice)` or `Err(message for the user)`.
119
pub async fn apply(app: &Shared, viewer: &Viewer, at: &Where, f: AssistantForm) -> sqlx::Result<Result<String, String>> {
120
    let owned = |a: Option<Assistant>| a.filter(|a| a.scope() == at.scope);
121
    let actor = viewer.account();
122
    Ok(Ok(match (f.action.as_str(), f.id) {
123
        ("add", None) => {
124
            let fields = match fields(&f) {
125
                Ok(x) => x,
126
                Err(e) => return Ok(Err(e)),
127
            };
128
            let token = app.assistant_key.seal(f.token.trim());
129
            match assistants::create(&app.db, at.scope, &fields, &token).await? {
130
                Some(a) => {
131
                    accounts::audit(&app.db, actor, "assistant.added", &at.label, &a.name).await.ok();
132
                    format!("{} added.", a.name)
133
                }
134
                None => return Ok(Err(format!("There is already an assistant called {} here.", fields.name))),
135
            }
136
        }
137
        ("update", Some(id)) => {
138
            let Some(a) = owned(assistants::get(&app.db, id).await?) else { return Ok(Err("No such assistant.".into())) };
139
            let fields = match fields(&f) {
140
                Ok(x) => x,
141
                Err(e) => return Ok(Err(e)),
142
            };
143
            let token = f.token.trim();
144
            let sealed = (!token.is_empty()).then(|| app.assistant_key.seal(token));
145
            if !assistants::update(&app.db, id, &fields, sealed.as_deref()).await? {
146
                return Ok(Err(format!("There is already an assistant called {} here.", fields.name)));
147
            }
148
            accounts::audit(&app.db, actor, "assistant.updated", &at.label, &a.name).await.ok();
149
            format!("{} updated.", fields.name)
150
        }
151
        ("toggle", Some(id)) => {
152
            let Some(a) = owned(assistants::get(&app.db, id).await?) else { return Ok(Err("No such assistant.".into())) };
153
            assistants::set_enabled(&app.db, id, !a.enabled).await?;
154
            accounts::audit(&app.db, actor, if a.enabled { "assistant.disabled" } else { "assistant.enabled" }, &at.label, &a.name)
155
                .await
156
                .ok();
157
            format!("{} is {}.", a.name, if a.enabled { "off" } else { "on" })
158
        }
159
        ("delete", Some(id)) => {
160
            let Some(a) = owned(assistants::get(&app.db, id).await?) else { return Ok(Err("No such assistant.".into())) };
161
            assistants::delete(&app.db, id).await?;
162
            accounts::audit(&app.db, actor, "assistant.deleted", &at.label, &a.name).await.ok();
163
            format!("{} deleted.", a.name)
164
        }
165
        ("test", Some(id)) => {
166
            let Some(a) = owned(assistants::get(&app.db, id).await?) else { return Ok(Err("No such assistant.".into())) };
167
            match assistants::test(app, &a).await {
168
                Ok(answer) => format!("{} answered: {answer}", a.name),
169
                Err(why) => return Ok(Err(format!("{} did not answer: {why}", a.name))),
170
            }
171
        }
172
        ("prompt", _) => {
173
            if f.prompt.chars().count() > 20_000 {
174
                return Ok(Err("A prompt is up to 20000 characters.".into()));
175
            }
176
            assistants::set_prompt(&app.db, at.scope, &f.prompt).await?;
177
            accounts::audit(&app.db, actor, "assistant.prompt", &at.label, "").await.ok();
178
            if f.prompt.trim().is_empty() {
179
                "Prompt cleared.".to_string()
180
            } else {
181
                "Prompt saved.".to_string()
182
            }
183
        }
184
        _ => return Ok(Err("Unknown action.".into())),
185
    }))
186
}