use clap::Args;
#[derive(Clone, Copy, Debug)]
pub enum InstructionsScope {
AgentCompletions,
FunctionExecutions,
FunctionInventionsRecursive,
LaboratoryExecutions,
}
impl InstructionsScope {
pub const ALL: &'static [Self] = &[
Self::AgentCompletions,
Self::FunctionExecutions,
Self::FunctionInventionsRecursive,
Self::LaboratoryExecutions,
];
pub fn table_name(self) -> &'static str {
match self {
Self::AgentCompletions => "agent_completions_instructions",
Self::FunctionExecutions => "function_executions_instructions",
Self::FunctionInventionsRecursive => "function_inventions_recursive_instructions",
Self::LaboratoryExecutions => "laboratory_executions_instructions",
}
}
}
#[derive(Args, Clone, Debug)]
pub struct InstructionsIdArg {
#[arg(long)]
pub instructions_id: String,
}
impl InstructionsIdArg {
pub fn verify(
&self,
cli_config: &crate::Config,
scope: InstructionsScope,
) -> Result<(), crate::error::Error> {
verify(cli_config, scope, &self.instructions_id)
}
}
pub fn issue(
cli_config: &crate::Config,
scope: InstructionsScope,
content: &str,
) -> Result<String, crate::error::Error> {
let client = fs_client(cli_config);
let id = generate_id();
let table = scope.table_name();
objectiveai_sdk::filesystem::config::db::execute(
&client,
&format!(
"CREATE TABLE IF NOT EXISTS {table} (instructions_id TEXT PRIMARY KEY NOT NULL)"
),
[],
)?;
objectiveai_sdk::filesystem::config::db::execute(
&client,
&format!("INSERT OR IGNORE INTO {table} (instructions_id) VALUES (?1)"),
objectiveai_sdk::filesystem::config::db::params![id],
)?;
Ok(format!("{content}\n\n Instructions ID: {id}"))
}
pub fn verify(
cli_config: &crate::Config,
scope: InstructionsScope,
id: &str,
) -> Result<(), crate::error::Error> {
let client = fs_client(cli_config);
let table = scope.table_name();
let sql = format!("SELECT 1 FROM {table} WHERE instructions_id = ?1");
let result = objectiveai_sdk::filesystem::config::db::query_one(
&client,
&sql,
objectiveai_sdk::filesystem::config::db::params![id],
|row| row.get::<_, i64>(0),
);
match result {
Ok(Some(_)) => Ok(()),
Ok(None) => Err(crate::error::Error::UnknownInstructionsId),
Err(e) if e.to_string().contains("no such table") => {
Err(crate::error::Error::UnknownInstructionsId)
}
Err(e) => Err(e.into()),
}
}
pub fn clear_all(cli_config: &crate::Config) -> Result<usize, crate::error::Error> {
let client = fs_client(cli_config);
for scope in InstructionsScope::ALL {
let table = scope.table_name();
objectiveai_sdk::filesystem::config::db::execute(
&client,
&format!("DROP TABLE IF EXISTS {table}"),
[],
)?;
}
Ok(InstructionsScope::ALL.len())
}
fn fs_client(cli_config: &crate::Config) -> objectiveai_sdk::filesystem::Client {
objectiveai_sdk::filesystem::Client::new(
cli_config.config_base_dir.as_deref(),
cli_config.commit_author_name.as_deref(),
cli_config.commit_author_email.as_deref(),
)
}
fn generate_id() -> String {
let bits: u128 = uuid::Uuid::new_v4().as_u128();
format!("{:0>22}", base62::encode(bits))
}