Skip to main content

objectiveai_sdk/cli/command/python/
mod.rs

1//! `python` — run a Python snippet and return its output as JSON.
2//!
3//! Executes `--code` in the embedded Python runtime with the optional
4//! `--input` JSON value exposed to the script as the global `input`,
5//! and returns the script's output (its trailing expression value,
6//! else captured stdout) as a `serde_json::Value`. No output → JSON
7//! `null`.
8//!
9//! With `--no-objectiveai`, the in-process `objectiveai.execute(...)`
10//! host call is disabled: it raises inside the script instead of
11//! dispatching a CLI command.
12
13use crate::cli::command::CommandRequest;
14
15#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
16#[schemars(rename = "cli.command.python.Request")]
17pub struct Request {
18    pub path_type: Path,
19    /// Python source to execute.
20    pub code: String,
21    /// Optional JSON value exposed to the code as the global `input`.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    #[schemars(extend("omitempty" = true))]
24    pub input: Option<serde_json::Value>,
25    /// When set, `objectiveai.execute(...)` inside the embedded python
26    /// raises instead of dispatching a CLI command.
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    #[schemars(extend("omitempty" = true))]
29    pub no_objectiveai: Option<bool>,
30    #[serde(flatten)]
31    pub base: crate::cli::command::RequestBase,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
35#[schemars(rename = "cli.command.python.Path")]
36pub enum Path {
37    #[serde(rename = "python")]
38    Python,
39}
40
41impl CommandRequest for Request {
42    fn request_base(&self) -> &crate::cli::command::RequestBase {
43        &self.base
44    }
45
46    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
47        Some(&mut self.base)
48    }
49}
50
51/// Whatever the script produced, as raw JSON (no output → `null`).
52pub type Response = serde_json::Value;
53
54#[derive(clap::Args)]
55#[command(group(clap::ArgGroup::new("code_required").required(true).args(["code"])))]
56pub struct Args {
57    /// Python source to execute.
58    #[arg(long)]
59    pub code: Option<String>,
60    /// Optional JSON value exposed to the code as the global `input`.
61    #[arg(long, value_parser = parse_json)]
62    pub input: Option<serde_json::Value>,
63    /// Disable `objectiveai.execute(...)` inside the script: the host
64    /// call raises instead of dispatching a CLI command.
65    #[arg(long)]
66    pub no_objectiveai: bool,
67    #[command(flatten)]
68    pub base: crate::cli::command::RequestBaseArgs,
69}
70
71#[derive(clap::Args)]
72#[command(args_conflicts_with_subcommands = true)]
73pub struct Command {
74    #[command(flatten)]
75    pub args: Args,
76    #[command(subcommand)]
77    pub schema: Option<Schema>,
78}
79
80#[derive(clap::Subcommand)]
81pub enum Schema {
82    /// Emit the JSON Schema for this leaf's `Request` type and exit.
83    RequestSchema(request_schema::Args),
84    /// Emit the JSON Schema for this leaf's `Response` type and exit.
85    ResponseSchema(response_schema::Args),
86}
87
88/// `--input` value parser: parse the flag's string as a JSON value.
89fn parse_json(s: &str) -> Result<serde_json::Value, String> {
90    serde_json::from_str(s).map_err(|e| e.to_string())
91}
92
93impl TryFrom<Args> for Request {
94    type Error = crate::cli::command::FromArgsError;
95    fn try_from(args: Args) -> Result<Self, Self::Error> {
96        Ok(Self {
97            path_type: Path::Python,
98            code: args.code.ok_or_else(|| {
99                crate::cli::command::FromArgsError::path_parse(
100                    "code",
101                    "--code is required".to_string(),
102                )
103            })?,
104            input: args.input,
105            no_objectiveai: args.no_objectiveai.then_some(true),
106            base: args.base.into(),
107        })
108    }
109}
110
111#[cfg(feature = "cli-executor")]
112pub async fn execute<E: crate::cli::command::CommandExecutor>(
113    executor: &E,
114    mut request: Request,
115    agent_arguments: Option<&crate::cli::command::AgentArguments>,
116) -> Result<Response, E::Error> {
117    request.base.clear_transform();
118    executor.execute_one(request, agent_arguments).await
119}
120
121#[cfg(feature = "cli-executor")]
122pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
123    executor: &E,
124    mut request: Request,
125    transform: crate::cli::command::Transform,
126    agent_arguments: Option<&crate::cli::command::AgentArguments>,
127) -> Result<serde_json::Value, E::Error> {
128    request.base.set_transform(transform);
129    executor.execute_one(request, agent_arguments).await
130}
131
132pub mod request_schema;
133
134pub mod response_schema;