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