use std::sync::Arc;
use ai::{Message, TextContent, UserContent, UserMessage, UserMessageContent};
use durable::{ConversationId, Tx};
use super::cell::CellCall;
use super::live::live;
use super::util::get;
use crate::scheduler::Result;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct GateRun {
pub conversation_id: ConversationId,
pub run: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RequestGate {
Allow,
Final {
note: String,
},
Block {
reason: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ToolBlock {
pub reason: String,
pub terminate: bool,
}
pub(crate) type GateRequest = Arc<dyn Fn(&GateRun) -> RequestGate + Send + Sync>;
pub(crate) type GateTool = Arc<dyn Fn(&GateRun, &CellCall) -> Option<ToolBlock> + Send + Sync>;
pub(crate) fn gate_run(tx: &mut Tx<'_>, conversation_id: ConversationId) -> Result<GateRun> {
let live = live(tx, conversation_id)?;
let first_input = get(&live, &["run", "inputs"])?
.and_then(|inputs| inputs.as_array().and_then(|inputs| inputs.first().cloned()))
.and_then(|input| input.as_u64());
let task = get(&live, &["run", "taskId"])?.and_then(|id| id.as_u64());
Ok(GateRun {
conversation_id,
run: first_input.or(task),
})
}
pub(crate) const FINAL_TOOL_CHOICE: &str = "none";
pub fn apply_final(note: &str, messages: &mut Vec<Message>, options: &mut ai::SimpleStreamOptions, timestamp: i64) {
options.tool_choice = Some(FINAL_TOOL_CHOICE.into());
messages.push(Message::User(UserMessage {
content: UserMessageContent::Blocks(vec![UserContent::Text(TextContent {
text: note.to_string(),
text_signature: None,
})]),
timestamp,
}));
}