Skip to main content

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

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