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