Skip to main content

objectiveai_sdk/cli/command/tasks/run/
mod.rs

1//! `agents tasks run` — fire every pending schedule in the caller's
2//! own subtree.
3//!
4//! Scope is fixed: every schedule whose `agent_instance_hierarchy` is
5//! the caller's own AIH or a descendant of it. Of those, the runner
6//! claims the pending ones (unfired oneshots + interval rows whose
7//! interval has elapsed — newest versions only), minting one
8//! `tasks_runs` row per firing, and dispatches each row's stored argv
9//! through the root `crate::run` in parallel — with the schedule's
10//! captured identity (and the plugin that registered it, if any)
11//! re-installed on the run ctx.
12//!
13//! Two output modes, selected by `stream_all`:
14//! * `--stream-all`: every item every task emits streams back, each
15//!   wrapped as a [`ValueResponseItem`].
16//! * default: exactly ONE [`SuccessResponseItem`] per task, emitted
17//!   when that task's stream completes — `success` is `false` iff the
18//!   task's final item was an error.
19//!
20//! The mode affects only the caller-visible stream: in BOTH modes the
21//! full per-item output is durably written to `tasks_logs`.
22
23use crate::cli::command::CommandRequest;
24
25/// The plugin that registered a schedule — the same shape `tasks list`
26/// surfaces.
27pub use crate::cli::command::tasks::list::Plugin;
28
29#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
30#[schemars(rename = "cli.command.tasks.run.Request")]
31pub struct Request {
32    pub path_type: Path,
33    /// Stream every item every fired task emits (each a
34    /// [`ValueResponseItem`]). When false — the default — each task
35    /// yields exactly one [`SuccessResponseItem`] summary instead; the
36    /// full output still lands in `tasks_logs` either way.
37    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
38    pub stream_all: bool,
39    #[serde(flatten)]
40    pub base: crate::cli::command::RequestBase,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
44#[schemars(rename = "cli.command.tasks.run.Path")]
45pub enum Path {
46    #[serde(rename = "tasks/run")]
47    AgentsTasksRun,
48}
49
50impl CommandRequest for Request {
51    fn into_command(&self) -> Vec<String> {
52        let mut argv = vec![
53            "tasks".to_string(),
54            "run".to_string(),
55        ];
56        if self.stream_all {
57            argv.push("--stream-all".to_string());
58        }
59        self.base.push_flags(&mut argv);
60        argv
61    }
62
63    fn request_base(&self) -> &crate::cli::command::RequestBase {
64        &self.base
65    }
66
67    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
68        Some(&mut self.base)
69    }
70}
71
72/// One stream item from `tasks run`. Untagged — the variants'
73/// required fields (`value` vs `success`) are disjoint, so the wire
74/// shape is just the inner object. Which variant flows is decided by
75/// the request's `stream_all`: `true` streams every emitted item as a
76/// [`ValueResponseItem`] (whose `value` is the typed root item for a
77/// no-transform command, or the post-transform JSON otherwise — see
78/// [`RunValue`]); `false` (default) yields exactly one
79/// [`SuccessResponseItem`] per task when its stream completes.
80#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
81#[serde(untagged)]
82#[schemars(rename = "cli.command.tasks.run.ResponseItem")]
83pub enum ResponseItem {
84    #[schemars(title = "Value")]
85    Value(ValueResponseItem),
86    #[schemars(title = "Success")]
87    Success(SuccessResponseItem),
88}
89
90/// One output item from one fired schedule's in-process stream
91/// (`stream_all` mode). The first four fields identify the source
92/// schedule; `value` is the typed root
93/// [`crate::cli::command::ResponseItem`] emitted by the scheduled cli
94/// leaf — boxed because the root union transitively contains *this*
95/// type (`agents → tasks → run`), and boxing is what makes the
96/// recursion sized.
97///
98/// The `value` field's JSON schema is opaqued to `serde_json::Value`
99/// (renders as bare `{}` aka JsonValue) so the published schema
100/// doesn't inline the entire root union — that's the TS7056 blowup
101/// the root and tier aggregates dodge by being `json_schema_ignore`.
102/// Downstream SDKs see `value: JsonValue` on the typed `execute`
103/// path; consumers that want to peer inside parse it case-by-case.
104#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
105#[schemars(rename = "cli.command.tasks.run.ValueResponseItem")]
106pub struct ValueResponseItem {
107    /// The source schedule's `agent_instance_hierarchy`.
108    pub agent_instance_hierarchy: String,
109    /// The source schedule's `--name`.
110    pub name: String,
111    /// The source schedule's version (`1` on first creation,
112    /// incremented per `schedule --overwrite`).
113    pub version: u64,
114    /// The plugin that registered the source schedule, if any.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    #[schemars(extend("omitempty" = true))]
117    pub plugin: Option<Plugin>,
118    /// What the scheduled command emitted — either the typed root item
119    /// (no transform) or post-transform JSON. See [`RunValue`]. Schema
120    /// is opaqued to `serde_json::Value`.
121    #[schemars(with = "serde_json::Value")]
122    pub value: RunValue,
123}
124
125/// The per-item value a fired schedule emits, mirroring the two root
126/// dispatch paths at the item level (untagged — the wire shape is just
127/// the inner value):
128/// - [`RunValue::ExecuteValue`]: the typed root
129///   [`crate::cli::command::ResponseItem`] from a no-transform command.
130///   Boxed because the root union transitively contains *this* type
131///   (`agents → tasks → run`), and its schema is opaqued to
132///   `serde_json::Value` so the published schema doesn't inline the
133///   entire root union (the TS7056 blowup the aggregates dodge).
134/// - [`RunValue::ExecuteTransformValue`]: the post-transform JSON from
135///   a command that carried a `--jq` / `--python` transform.
136///
137/// Deliberately does NOT derive `JsonSchema` and is `json_schema_ignore`d:
138/// its only use site ([`ValueResponseItem::value`]) opaques it to
139/// `serde_json::Value`, so its own schema is never referenced. Deriving
140/// it would publish a degenerate `anyOf` of two type-less `{}` variants
141/// (both arms are wire-opaque), which no SDK code generator can name.
142#[objectiveai_sdk_macros::json_schema_ignore]
143#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
144#[serde(untagged)]
145pub enum RunValue {
146    ExecuteValue(Box<crate::cli::command::ResponseItem>),
147    ExecuteTransformValue(serde_json::Value),
148}
149
150/// One per-task completion summary (default mode): the same schedule
151/// identity as [`ValueResponseItem`], with `success` in lieu of
152/// `value`. `success` is `false` iff the task's FINAL emitted item was
153/// an error (a task that emitted nothing is a success). The task's
154/// full output is in `tasks_logs` regardless.
155#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
156#[schemars(rename = "cli.command.tasks.run.SuccessResponseItem")]
157pub struct SuccessResponseItem {
158    /// The source schedule's `agent_instance_hierarchy`.
159    pub agent_instance_hierarchy: String,
160    /// The source schedule's `--name`.
161    pub name: String,
162    /// The source schedule's version (`1` on first creation,
163    /// incremented per `schedule --overwrite`).
164    pub version: u64,
165    /// The plugin that registered the source schedule, if any.
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    #[schemars(extend("omitempty" = true))]
168    pub plugin: Option<Plugin>,
169    /// Whether the task's stream completed without a trailing error.
170    pub success: bool,
171}
172
173#[derive(clap::Args)]
174pub struct Args {
175    /// Stream every item every fired task emits. Without this flag
176    /// each task yields exactly one `{.., success}` summary when it
177    /// completes; the full output lands in `tasks_logs` either way.
178    #[arg(long)]
179    pub stream_all: bool,
180    #[command(flatten)]
181    pub base: crate::cli::command::RequestBaseArgs,
182}
183
184#[derive(clap::Args)]
185#[command(args_conflicts_with_subcommands = true)]
186pub struct Command {
187    #[command(flatten)]
188    pub args: Args,
189    #[command(subcommand)]
190    pub schema: Option<Schema>,
191}
192
193#[derive(clap::Subcommand)]
194pub enum Schema {
195    /// Emit the JSON Schema for this leaf's `Request` type and exit.
196    RequestSchema(request_schema::Args),
197    /// Emit the JSON Schema for this leaf's `Response` type and exit.
198    ResponseSchema(response_schema::Args),
199}
200
201impl TryFrom<Args> for Request {
202    type Error = crate::cli::command::FromArgsError;
203    fn try_from(args: Args) -> Result<Self, Self::Error> {
204        Ok(Self {
205            path_type: Path::AgentsTasksRun,
206            stream_all: args.stream_all,
207            base: args.base.into(),
208        })
209    }
210}
211
212#[cfg(feature = "cli-executor")]
213pub async fn execute<E: crate::cli::command::CommandExecutor>(
214    executor: &E,
215    mut request: Request,
216    agent_arguments: Option<&crate::cli::command::AgentArguments>,
217) -> Result<E::Stream<ResponseItem>, E::Error> {
218    request.base.clear_transform();
219    executor.execute(request, agent_arguments).await
220}
221
222#[cfg(feature = "cli-executor")]
223pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
224    executor: &E,
225    mut request: Request,
226    transform: crate::cli::command::Transform,
227    agent_arguments: Option<&crate::cli::command::AgentArguments>,
228) -> Result<E::Stream<serde_json::Value>, E::Error> {
229    request.base.set_transform(transform);
230    executor.execute(request, agent_arguments).await
231}
232
233#[cfg(feature = "mcp")]
234impl crate::cli::command::CommandResponse for ResponseItem {
235    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
236        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
237    }
238}
239
240pub mod request_schema;
241
242pub mod response_schema;