Skip to main content

objectiveai_sdk/cli/command/functions/execute/standard/
mod.rs

1//! `functions execute standard` — async handler stub.
2
3use crate::agent::completions::message::Message;  // unused placeholder to keep imports tidy
4use crate::cli::command::CommandRequest;
5use crate::functions::expression::InputValue;
6use super::{FunctionArgs, FunctionSpec, ProfileArgs, ProfileSpec};
7
8#[allow(dead_code)]
9type _UnusedMessage = Message;
10
11#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
12#[schemars(rename = "cli.command.functions.execute.standard.Request")]
13pub struct Request {
14    pub path_type: Path,
15    pub function: FunctionSpec,
16    pub profile: ProfileSpec,
17    pub input: RequestInput,
18    pub continuation: Option<String>,
19    pub retry_token: Option<String>,
20    pub split: bool,
21    pub invert: bool,
22    pub dangerous_advanced: Option<RequestDangerousAdvanced>,
23    pub jq: Option<String>,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
27#[schemars(rename = "cli.command.functions.execute.standard.Path")]
28pub enum Path {
29    #[serde(rename = "functions/execute/standard")]
30    FunctionsExecuteStandard,
31}
32
33#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
34#[schemars(rename = "cli.command.functions.execute.standard.RequestInput")]
35pub enum RequestInput {
36    #[schemars(title = "Inline")]
37    Inline(InputValue),
38    #[schemars(title = "File")]
39    File(std::path::PathBuf),
40    #[schemars(title = "PythonInline")]
41    PythonInline(String),
42    #[schemars(title = "PythonFile")]
43    PythonFile(std::path::PathBuf),
44}
45
46impl RequestInput {
47    fn push_flags(&self, out: &mut Vec<String>) {
48        match self {
49            RequestInput::Inline(v) => {
50                out.push("--input-inline".to_string());
51                out.push(serde_json::to_string(v).expect("input serializes"));
52            }
53            RequestInput::File(p) => {
54                out.push("--input-file".to_string());
55                out.push(p.to_string_lossy().into_owned());
56            }
57            RequestInput::PythonInline(code) => {
58                out.push("--input-python-inline".to_string());
59                out.push(code.clone());
60            }
61            RequestInput::PythonFile(p) => {
62                out.push("--input-python-file".to_string());
63                out.push(p.to_string_lossy().into_owned());
64            }
65        }
66    }
67}
68
69impl CommandRequest for Request {
70    fn into_command(&self) -> Vec<String> {
71        let mut argv = vec![
72            "functions".to_string(),
73            "execute".to_string(),
74            "standard".to_string(),
75        ];
76        self.function.push_flags(&mut argv);
77        self.profile.push_flags(&mut argv);
78        self.input.push_flags(&mut argv);
79        if let Some(c) = &self.continuation {
80            argv.push("--continuation".to_string());
81            argv.push(c.clone());
82        }
83        if let Some(t) = &self.retry_token {
84            argv.push("--retry-token".to_string());
85            argv.push(t.clone());
86        }
87        if self.split {
88            argv.push("--split".to_string());
89        }
90        if self.invert {
91            argv.push("--invert".to_string());
92        }
93        if let Some(advanced) = &self.dangerous_advanced {
94            argv.push("--dangerous-advanced".to_string());
95            argv.push(
96                serde_json::to_string(advanced)
97                    .expect("RequestDangerousAdvanced serializes"),
98            );
99        }
100        if let Some(jq) = &self.jq {
101            argv.push("--jq".to_string());
102            argv.push(jq.clone());
103        }
104        argv
105    }
106}
107
108#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
109#[schemars(rename = "cli.command.functions.execute.standard.RequestDangerousAdvanced")]
110pub struct RequestDangerousAdvanced {
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    #[schemars(extend("omitempty" = true))]
113    pub stream: Option<bool>,
114    /// Deterministic seed for downstream mock agents. Forwarded
115    /// to every per-task `AgentCompletionCreateParams.seed`.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    #[schemars(extend("omitempty" = true))]
118    pub seed: Option<i64>,
119}
120
121#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
122#[serde(untagged)]
123#[schemars(rename = "cli.command.functions.execute.standard.ResponseItem")]
124pub enum ResponseItem {
125    #[schemars(title = "Chunk")]
126    Chunk(crate::functions::executions::response::streaming::FunctionExecutionChunk),
127    #[schemars(title = "Id")]
128    Id(String),
129}
130
131/// Non-chunk variant of [`ResponseItem`]. Returned by the unary `execute`
132/// path (with `dangerous_advanced.stream` cleared) when the cli emits a
133/// single bare id string.
134pub type Response = String;
135
136/// Exactly-one-of `--input-inline | --input-file | --input-python-inline
137/// | --input-python-file`. Scoped to its own `#[group]` annotation on a
138/// dedicated sub-struct so the `required = true, multiple = false`
139/// enforcement only applies to these fields — hoisting the annotation
140/// to the outer [`Args`] would pull every field into the "input_group"
141/// group via clap derive's default-group rule. Mirrors the
142/// `super::{FunctionArgs, ProfileArgs}` pattern.
143#[derive(clap::Args)]
144#[group(id = "input_group", required = true, multiple = false)]
145pub struct InputArgs {
146    /// Inline JSON input value.
147    #[arg(long, group = "input_group")]
148    pub input_inline: Option<String>,
149    /// Path to a JSON file containing the input value.
150    #[arg(long, group = "input_group")]
151    pub input_file: Option<std::path::PathBuf>,
152    /// Inline Python that produces the input value.
153    #[arg(long, group = "input_group")]
154    pub input_python_inline: Option<String>,
155    /// Path to a Python file that produces the input value.
156    #[arg(long, group = "input_group")]
157    pub input_python_file: Option<std::path::PathBuf>,
158}
159
160#[derive(clap::Args)]
161pub struct Args {
162    /// Exactly one of `--function`, `--function-inline`,
163    /// `--function-file`, `--function-python-inline`,
164    /// `--function-python-file`.
165    #[command(flatten)]
166    pub function: FunctionArgs,
167    /// Exactly one of `--profile`, `--profile-inline`,
168    /// `--profile-file`, `--profile-python-inline`,
169    /// `--profile-python-file`.
170    #[command(flatten)]
171    pub profile: ProfileArgs,
172    /// Exactly one of `--input-inline`, `--input-file`,
173    /// `--input-python-inline`, `--input-python-file`.
174    #[command(flatten)]
175    pub input: InputArgs,
176    /// Continuation token from a previous response.
177    #[arg(long)]
178    pub continuation: Option<String>,
179    /// Retry token from a previous execution.
180    #[arg(long)]
181    pub retry_token: Option<String>,
182    /// Treat input as an array and execute once per element.
183    #[arg(long)]
184    pub split: bool,
185    /// Invert outputs after expressions evaluate.
186    #[arg(long)]
187    pub invert: bool,
188    /// Advanced opt-in flags as inline JSON.
189    #[arg(long)]
190    pub dangerous_advanced: Option<String>,
191    /// jq filter applied to the JSON output.
192    #[arg(long)]
193    pub jq: Option<String>,
194}
195
196#[derive(clap::Args)]
197#[command(args_conflicts_with_subcommands = true)]
198pub struct Command {
199    #[command(flatten)]
200    pub args: Args,
201    #[command(subcommand)]
202    pub schema: Option<Schema>,
203}
204
205#[derive(clap::Subcommand)]
206pub enum Schema {
207    /// Emit the JSON Schema for this leaf's `Request` type and exit.
208    RequestSchema(request_schema::Args),
209    /// Emit the JSON Schema for this leaf's `Response` type and exit.
210    ResponseSchema(response_schema::Args),
211}
212
213impl TryFrom<Args> for Request {
214    type Error = crate::cli::command::FromArgsError;
215    fn try_from(args: Args) -> Result<Self, Self::Error> {
216        let function = FunctionSpec::try_from(args.function)?;
217        let profile = ProfileSpec::try_from(args.profile)?;
218        let input = if let Some(s) = args.input.input_inline {
219            let mut de = serde_json::Deserializer::from_str(&s);
220            let v = serde_path_to_error::deserialize(&mut de)
221                .map_err(|e| crate::cli::command::FromArgsError::json("input_inline", e))?;
222            RequestInput::Inline(v)
223        } else if let Some(p) = args.input.input_file {
224            RequestInput::File(p)
225        } else if let Some(s) = args.input.input_python_inline {
226            RequestInput::PythonInline(s)
227        } else {
228            RequestInput::PythonFile(args.input.input_python_file.unwrap())
229        };
230        let dangerous_advanced: Option<RequestDangerousAdvanced> =
231            if let Some(s) = args.dangerous_advanced {
232                let mut de = serde_json::Deserializer::from_str(&s);
233                let v = serde_path_to_error::deserialize(&mut de)
234                    .map_err(|e| crate::cli::command::FromArgsError::json("dangerous_advanced", e))?;
235                Some(v)
236            } else {
237                None
238            };
239        Ok(Self { path_type: Path::FunctionsExecuteStandard,
240            function,
241            profile,
242            input,
243            continuation: args.continuation,
244            retry_token: args.retry_token,
245            split: args.split,
246            invert: args.invert,
247            dangerous_advanced,
248            jq: args.jq,
249        })
250    }
251}
252
253#[cfg(feature = "cli-executor")]
254pub async fn execute_streaming<E: crate::cli::command::CommandExecutor>(
255    executor: &E,
256    mut request: Request,
257
258        agent_arguments: Option<&crate::cli::command::AgentArguments>,
259    ) -> Result<E::Stream<ResponseItem>, E::Error> {
260    request.jq = None;
261    let mut advanced = request.dangerous_advanced.unwrap_or_default();
262    advanced.stream = Some(true);
263    request.dangerous_advanced = Some(advanced);
264    executor.execute(request, agent_arguments).await
265}
266
267#[cfg(feature = "cli-executor")]
268pub async fn execute_streaming_jq<E: crate::cli::command::CommandExecutor>(
269    executor: &E,
270    mut request: Request,
271    jq: String,
272
273        agent_arguments: Option<&crate::cli::command::AgentArguments>,
274    ) -> Result<E::Stream<serde_json::Value>, E::Error> {
275    request.jq = Some(jq);
276    let mut advanced = request.dangerous_advanced.unwrap_or_default();
277    advanced.stream = Some(true);
278    request.dangerous_advanced = Some(advanced);
279    executor.execute(request, agent_arguments).await
280}
281
282#[cfg(feature = "cli-executor")]
283pub async fn execute<E: crate::cli::command::CommandExecutor>(
284    executor: &E,
285    mut request: Request,
286
287        agent_arguments: Option<&crate::cli::command::AgentArguments>,
288    ) -> Result<Response, E::Error> {
289    request.jq = None;
290    if let Some(advanced) = request.dangerous_advanced.as_mut() {
291        advanced.stream = None;
292    }
293    executor.execute_one(request, agent_arguments).await
294}
295
296#[cfg(feature = "cli-executor")]
297pub async fn execute_jq<E: crate::cli::command::CommandExecutor>(
298    executor: &E,
299    mut request: Request,
300    jq: String,
301
302        agent_arguments: Option<&crate::cli::command::AgentArguments>,
303    ) -> Result<serde_json::Value, E::Error> {
304    request.jq = Some(jq);
305    if let Some(advanced) = request.dangerous_advanced.as_mut() {
306        advanced.stream = None;
307    }
308    executor.execute_one(request, agent_arguments).await
309}
310
311#[cfg(feature = "mcp")]
312impl crate::cli::command::CommandResponse for ResponseItem {
313    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
314        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
315    }
316}
317
318pub mod request_schema;
319
320
321pub mod response_schema;