Skip to main content

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

1//! `tasks create` — schedule an ObjectiveAI command. The command runs
2//! after `--delay-secs`; with `--repeat` it re-runs every
3//! `--delay-secs` (measured from each run's COMPLETION), and
4//! `--repeat-count` caps the number of SUCCESSFUL runs (errored runs
5//! do not consume the budget — a failing counted repeat retries).
6//! The task runs with the identity it was created with — agent
7//! arguments and the plugin trio — and its runs carry the
8//! daemon-authored `task` identity flag on the `/listen` broadcast.
9//!
10//! `--command` takes the full command-request JSON (the same shape
11//! the `--request` front door accepts); it is stored opaquely and
12//! validated daemon-side at create.
13
14use crate::cli::command::CommandRequest;
15
16// No `PartialEq`: the embedded root [`crate::cli::command::Request`]
17// doesn't derive it.
18#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
19#[schemars(rename = "cli.command.tasks.create.Request")]
20pub struct Request {
21    pub path_type: Path,
22    /// The task's user-chosen name — REQUIRED, laboratory-style.
23    /// Unique per creating plugin (non-plugin creators share one
24    /// namespace); `tasks delete --id` and re-creation resolve
25    /// against it. This is the caller's handle, distinct from the
26    /// daemon's internal surrogate key.
27    pub id: String,
28    /// The command to run — the full typed command request.
29    /// Schema-opaque (`serde_json::Value`) ON PURPOSE: embedding the
30    /// root request enum's schema in a leaf transitively expands the
31    /// whole command tree, which downstream generated TypeScript
32    /// cannot emit declarations for (TS7056) — the same reason the
33    /// root aggregate is json_schema_ignore'd. The Rust type is the
34    /// validation; the wire shape is unchanged.
35    #[schemars(with = "serde_json::Value")]
36    pub command: Box<crate::cli::command::Request>,
37    /// Seconds until the (first) run; with `repeat`, also the interval
38    /// between runs, measured from each run's completion.
39    pub delay_secs: u64,
40    /// Re-run every `delay_secs` instead of running once.
41    #[serde(default)]
42    pub repeat: bool,
43    /// Cap on SUCCESSFUL runs — only valid with `repeat`.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    #[schemars(extend("omitempty" = true))]
46    pub repeat_count: Option<u64>,
47    #[serde(flatten)]
48    pub base: crate::cli::command::RequestBase,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
52#[schemars(rename = "cli.command.tasks.create.Path")]
53pub enum Path {
54    #[serde(rename = "tasks/create")]
55    TasksCreate,
56}
57
58impl CommandRequest for Request {
59    fn request_base(&self) -> &crate::cli::command::RequestBase {
60        &self.base
61    }
62
63    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
64        Some(&mut self.base)
65    }
66}
67
68/// The created task's id.
69#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
70#[schemars(rename = "cli.command.tasks.create.Response")]
71pub struct Response {
72    pub id: String,
73}
74
75#[derive(clap::Args)]
76#[command(group(clap::ArgGroup::new("id_required").required(true).args(["id"])))]
77#[command(group(clap::ArgGroup::new("command_required").required(true).args(["command"])))]
78#[command(group(clap::ArgGroup::new("delay_required").required(true).args(["delay_secs"])))]
79pub struct Args {
80    /// The task's name — unique per creating plugin. Required.
81    #[arg(long)]
82    pub id: Option<String>,
83    /// The command to run: a full command-request JSON object (the
84    /// same shape `--request` accepts).
85    #[arg(long)]
86    pub command: Option<String>,
87    /// Seconds until the (first) run; with --repeat, also the interval
88    /// between runs.
89    #[arg(long)]
90    pub delay_secs: Option<u64>,
91    /// Re-run every --delay-secs instead of running once.
92    #[arg(long)]
93    pub repeat: bool,
94    /// Cap on successful runs (errored runs don't consume the budget).
95    /// Requires --repeat.
96    #[arg(long, requires = "repeat")]
97    pub repeat_count: Option<u64>,
98    #[command(flatten)]
99    pub base: crate::cli::command::RequestBaseArgs,
100}
101
102#[derive(clap::Args)]
103#[command(args_conflicts_with_subcommands = true)]
104pub struct Command {
105    #[command(flatten)]
106    pub args: Args,
107    #[command(subcommand)]
108    pub schema: Option<Schema>,
109}
110
111#[derive(clap::Subcommand)]
112pub enum Schema {
113    /// Emit the JSON Schema for this leaf's `Request` type and exit.
114    RequestSchema(request_schema::Args),
115    /// Emit the JSON Schema for this leaf's `Response` type and exit.
116    ResponseSchema(response_schema::Args),
117}
118
119impl TryFrom<Args> for Request {
120    type Error = crate::cli::command::FromArgsError;
121    fn try_from(args: Args) -> Result<Self, Self::Error> {
122        let id = args.id.ok_or_else(|| {
123            crate::cli::command::FromArgsError::path_parse(
124                "id",
125                "--id is required".to_string(),
126            )
127        })?;
128        let command = args.command.ok_or_else(|| {
129            crate::cli::command::FromArgsError::path_parse(
130                "command",
131                "--command is required".to_string(),
132            )
133        })?;
134        // Typed parse — deserialization IS the validation.
135        let command: Box<crate::cli::command::Request> =
136            serde_json::from_str(&command).map(Box::new).map_err(|e| {
137                crate::cli::command::FromArgsError::path_parse(
138                    "command",
139                    format!("--command is not a valid command request: {e}"),
140                )
141            })?;
142        let delay_secs = args.delay_secs.ok_or_else(|| {
143            crate::cli::command::FromArgsError::path_parse(
144                "delay_secs",
145                "--delay-secs is required".to_string(),
146            )
147        })?;
148        Ok(Self {
149            path_type: Path::TasksCreate,
150            id,
151            command,
152            delay_secs,
153            repeat: args.repeat,
154            repeat_count: args.repeat_count,
155            base: args.base.into(),
156        })
157    }
158}
159
160#[cfg(feature = "mcp")]
161impl crate::cli::command::CommandResponse for Response {
162    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
163        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
164    }
165}
166
167#[cfg(feature = "cli-executor")]
168pub async fn execute<E: crate::cli::command::CommandExecutor>(
169    executor: &E,
170    mut request: Request,
171    identity: Option<&crate::identity::Identity>,
172) -> Result<Response, E::Error> {
173    request.base.clear_transform();
174    executor.execute_one(request, identity).await
175}
176
177#[cfg(feature = "cli-executor")]
178pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
179    executor: &E,
180    mut request: Request,
181    transform: crate::cli::command::Transform,
182    identity: Option<&crate::identity::Identity>,
183) -> Result<serde_json::Value, E::Error> {
184    request.base.set_transform(transform);
185    executor.execute_one(request, identity).await
186}
187
188pub mod request_schema;
189
190pub mod response_schema;
191
192/// One `/listen` broadcast run of `tasks create`: the actual
193/// [`Request`], the producer's
194/// [`Identity`](crate::identity::Identity), and the
195/// unary response future. See [`crate::daemon::command_listener`].
196#[cfg(all(feature = "cli", feature = "daemon"))]
197pub struct ListenerExecution {
198    pub request: Request,
199    pub identity: crate::identity::Identity,
200    pub response: crate::daemon::command_listener::UnaryResponse<Response>,
201}