Skip to main content

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

1//! `agents tasks list` — inspection leaf over `schedules`.
2//!
3//! Scope is one or more `--target` entries (the shared `Target`:
4//! `me` / `instance=L[,parent=P]` / `tag=T`). Each resolves to an AIH
5//! and the listing returns the schedule rows whose
6//! `agent_instance_hierarchy` equals it — exact match, no subtree
7//! descent. Only the NEWEST version of each `(name, aih)` lists;
8//! `--overwrite`-shadowed versions stay on disk (per-version run
9//! history) but never surface here. `--oneshot` / `--interval` filter
10//! by kind; `--pending` / `--exhausted` filter by readiness (derived
11//! from the schedule's newest `tasks_runs` entry); `--after-id` /
12//! `--count` paginate forward by ascending row id.
13
14use crate::cli::command::CommandRequest;
15
16/// The same `Target` every hierarchy-scoped read command uses
17/// (`agents instances list`, `agents logs read all`, …).
18pub use crate::cli::command::agents::logs::read::all::Target;
19
20#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
21#[schemars(rename = "cli.command.tasks.list.Request")]
22pub struct Request {
23    pub path_type: Path,
24    /// One or more targets to list schedules for. Each resolves to a
25    /// single AIH (`me` → the cli's own; `instance=L[,parent=P]`;
26    /// `tag=T` BOUND-only — PENDING / ABSENT error), and rows whose
27    /// `agent_instance_hierarchy` equals any resolved AIH are returned.
28    pub targets: Vec<Target>,
29    /// Filter to oneshot rows only. Mutually exclusive with `interval`.
30    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
31    pub oneshot: bool,
32    /// Filter to recurring rows only. Mutually exclusive with `oneshot`.
33    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
34    pub interval: bool,
35    /// Show only schedules currently runnable — oneshots that
36    /// have never fired, and interval rows whose interval has
37    /// elapsed. Mutually exclusive with `exhausted`.
38    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
39    pub pending: bool,
40    /// Show only schedules NOT currently runnable — fired
41    /// oneshots (visible briefly before the runner deletes
42    /// them) and interval rows that are cooling down. Mutually
43    /// exclusive with `pending`.
44    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
45    pub exhausted: bool,
46    /// Skip rows with `schedules.id <= after_id`. Use the highest
47    /// `id` from a previous page to paginate forward.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    #[schemars(extend("omitempty" = true))]
50    pub after_id: Option<i64>,
51    /// Per-target row cap — each target's query returns at most this
52    /// many rows (ascending id, after `after_id`). `None` = unlimited.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    #[schemars(extend("omitempty" = true))]
55    pub count: Option<u64>,
56    pub jq: Option<String>,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
60#[schemars(rename = "cli.command.tasks.list.Path")]
61pub enum Path {
62    #[serde(rename = "tasks/list")]
63    AgentsTasksList,
64}
65
66impl CommandRequest for Request {
67    fn into_command(&self) -> Vec<String> {
68        let mut argv = vec![
69            "tasks".to_string(),
70            "list".to_string(),
71        ];
72        for target in &self.targets {
73            argv.push("--target".to_string());
74            argv.push(target.into_arg_string());
75        }
76        if self.oneshot {
77            argv.push("--oneshot".to_string());
78        }
79        if self.interval {
80            argv.push("--interval".to_string());
81        }
82        if self.pending {
83            argv.push("--pending".to_string());
84        }
85        if self.exhausted {
86            argv.push("--exhausted".to_string());
87        }
88        if let Some(after_id) = self.after_id {
89            argv.push("--after-id".to_string());
90            argv.push(after_id.to_string());
91        }
92        if let Some(c) = self.count {
93            argv.push("--count".to_string());
94            argv.push(c.to_string());
95        }
96        if let Some(jq) = &self.jq {
97            argv.push("--jq".to_string());
98            argv.push(jq.clone());
99        }
100        argv
101    }
102}
103
104/// The plugin that registered a schedule. All three fields are present
105/// together or the whole object is absent (the `schedules` table
106/// enforces all-or-nothing on its `plugin_*` columns).
107#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
108#[schemars(rename = "cli.command.tasks.list.Plugin")]
109pub struct Plugin {
110    pub owner: String,
111    pub repository: String,
112    pub version: String,
113}
114
115/// One schedule row.
116#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
117#[schemars(rename = "cli.command.tasks.list.ResponseItem")]
118pub struct ResponseItem {
119    /// The `schedules` row id. Monotonic; pass the highest `id` from a
120    /// page as the next request's `after_id` to paginate forward.
121    pub id: i64,
122    /// The `--name` passed to `agents tasks schedule`. Unique per
123    /// `agent_instance_hierarchy`.
124    pub name: String,
125    pub agent_instance_hierarchy: String,
126    pub command: Vec<String>,
127    pub description: String,
128    pub created_at: i64,
129    /// Unix seconds of the most recent invocation — this row's newest
130    /// `tasks_runs` entry. `None` until the runner has fired this
131    /// version at least once (runs are tracked per-version).
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    #[schemars(extend("omitempty" = true))]
134    pub last_ran_at: Option<i64>,
135    /// `None` for a oneshot; `Some("30s" / "1h" / "1d12h" / …)`
136    /// for a recurring schedule, formatted as humantime so the
137    /// list output reads naturally without a unit-conversion
138    /// step at the consumer. The CLI parser accepts the same
139    /// shape on `agents tasks schedule --interval`.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    #[schemars(extend("omitempty" = true))]
142    pub interval: Option<String>,
143    /// This row's version: `1` for a freshly scheduled task,
144    /// `max + 1` for each `tasks schedule --overwrite` (each version
145    /// is its own row; only the newest lists).
146    pub version: u64,
147    /// The plugin that registered this schedule (its `(owner,
148    /// repository, version)` coordinate), or `None` when it was not
149    /// scheduled by a plugin.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    #[schemars(extend("omitempty" = true))]
152    pub plugin: Option<Plugin>,
153}
154
155#[derive(clap::Args)]
156#[command(group(
157    clap::ArgGroup::new("kind")
158        .multiple(false)
159        .args(["oneshot", "interval"])
160))]
161#[command(group(
162    clap::ArgGroup::new("readiness")
163        .multiple(false)
164        .args(["pending", "exhausted"])
165))]
166pub struct Args {
167    /// One or more `--target instance=L[,parent=P]` entries. Also
168    /// accepts `--target tag=T` and `--target me`. Lists schedules
169    /// whose `agent_instance_hierarchy` equals each resolved AIH.
170    #[arg(long = "target", required = true)]
171    pub targets: Vec<String>,
172    /// Filter to oneshot rows only. Mutually exclusive with `--interval`.
173    #[arg(long)]
174    pub oneshot: bool,
175    /// Filter to recurring rows only. Mutually exclusive with `--oneshot`.
176    #[arg(long)]
177    pub interval: bool,
178    /// Only schedules currently runnable. Mutually exclusive with `--exhausted`.
179    #[arg(long)]
180    pub pending: bool,
181    /// Only schedules NOT currently runnable. Mutually exclusive with `--pending`.
182    #[arg(long)]
183    pub exhausted: bool,
184    /// Skip rows with `schedules.id <= after_id`; use the highest
185    /// `id` from the previous page to paginate forward.
186    #[arg(long)]
187    pub after_id: Option<i64>,
188    #[arg(long)]
189    pub count: Option<u64>,
190    #[arg(long)]
191    pub jq: Option<String>,
192}
193
194#[derive(clap::Args)]
195#[command(args_conflicts_with_subcommands = true)]
196pub struct Command {
197    #[command(flatten)]
198    pub args: Args,
199    #[command(subcommand)]
200    pub schema: Option<Schema>,
201}
202
203#[derive(clap::Subcommand)]
204pub enum Schema {
205    /// Emit the JSON Schema for this leaf's `Request` type and exit.
206    RequestSchema(request_schema::Args),
207    /// Emit the JSON Schema for this leaf's `Response` type and exit.
208    ResponseSchema(response_schema::Args),
209}
210
211impl TryFrom<Args> for Request {
212    type Error = crate::cli::command::FromArgsError;
213    fn try_from(args: Args) -> Result<Self, Self::Error> {
214        let targets = args
215            .targets
216            .iter()
217            .map(|s| {
218                s.parse::<Target>().map_err(|msg| {
219                    crate::cli::command::FromArgsError::path_parse("target", msg)
220                })
221            })
222            .collect::<Result<Vec<_>, _>>()?;
223        Ok(Self {
224            path_type: Path::AgentsTasksList,
225            targets,
226            oneshot: args.oneshot,
227            interval: args.interval,
228            pending: args.pending,
229            exhausted: args.exhausted,
230            after_id: args.after_id,
231            count: args.count,
232            jq: args.jq,
233        })
234    }
235}
236
237#[cfg(feature = "cli-executor")]
238pub async fn execute<E: crate::cli::command::CommandExecutor>(
239    executor: &E,
240    mut request: Request,
241    agent_arguments: Option<&crate::cli::command::AgentArguments>,
242) -> Result<E::Stream<ResponseItem>, E::Error> {
243    request.jq = None;
244    executor.execute(request, agent_arguments).await
245}
246
247#[cfg(feature = "cli-executor")]
248pub async fn execute_jq<E: crate::cli::command::CommandExecutor>(
249    executor: &E,
250    mut request: Request,
251    jq: String,
252    agent_arguments: Option<&crate::cli::command::AgentArguments>,
253) -> Result<E::Stream<serde_json::Value>, E::Error> {
254    request.jq = Some(jq);
255    executor.execute(request, agent_arguments).await
256}
257
258#[cfg(feature = "mcp")]
259impl crate::cli::command::CommandResponse for ResponseItem {
260    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
261        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
262    }
263}
264
265pub mod request_schema;
266
267pub mod response_schema;