Skip to main content

objectiveai_sdk/cli/command/agents/logs/token_usage/subscribe/
mod.rs

1//! `agents logs token-usage subscribe` — wait for an agent's stored
2//! `total_tokens` snapshot to change, OR for its instance lock to
3//! drop. One-shot: yields exactly one result — a token-usage value
4//! (`Item`) or the literal string `"agents_inactive"` — then ends.
5//!
6//! With `--previous`, returns immediately when the stored value
7//! already differs; otherwise it subscribes.
8
9use crate::cli::command::CommandRequest;
10
11#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
12#[schemars(rename = "cli.command.agents.logs.token_usage.subscribe.Request")]
13pub struct Request {
14    pub path_type: Path,
15    /// The full agent instance hierarchy to watch.
16    pub agent_instance_hierarchy: String,
17    /// The last-seen `total_tokens`. When set and the stored value
18    /// already differs, the command returns immediately instead of
19    /// subscribing. `None` on the wire = always subscribe.
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    #[schemars(extend("omitempty" = true))]
22    pub previous: Option<i64>,
23    #[serde(flatten)]
24    pub base: crate::cli::command::RequestBase,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
28#[schemars(rename = "cli.command.agents.logs.token_usage.subscribe.Path")]
29pub enum Path {
30    #[serde(rename = "agents/logs/token-usage/subscribe")]
31    AgentsLogsTokenUsageSubscribe,
32}
33
34impl CommandRequest for Request {
35    fn request_base(&self) -> &crate::cli::command::RequestBase {
36        &self.base
37    }
38
39    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
40        Some(&mut self.base)
41    }
42}
43
44/// Subscribe's wire shape: either a token-usage snapshot (`Item`) or
45/// the literal string `"agents_inactive"`. `#[serde(untagged)]` so
46/// `Item` passes through as a plain object and `AgentsInactive` as a
47/// bare string — the same convention as `agents logs subscribe`.
48#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
49#[serde(untagged)]
50#[schemars(rename = "cli.command.agents.logs.token_usage.subscribe.ResponseItem")]
51pub enum ResponseItem {
52    #[schemars(title = "Item")]
53    Item(TokenUsage),
54    #[schemars(title = "AgentsInactive")]
55    AgentsInactive(AgentsInactiveTag),
56}
57
58/// A per-AIH token-usage snapshot.
59#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
60#[schemars(rename = "cli.command.agents.logs.token_usage.subscribe.TokenUsage")]
61pub struct TokenUsage {
62    pub agent_instance_hierarchy: String,
63    pub total_tokens: i64,
64}
65
66/// Single-variant enum whose lone variant serializes as the literal
67/// string `"agents_inactive"` (mirrors `logs::subscribe::AgentsInactiveTag`).
68#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
69#[schemars(rename = "cli.command.agents.logs.token_usage.subscribe.AgentsInactiveTag")]
70pub enum AgentsInactiveTag {
71    #[serde(rename = "agents_inactive")]
72    AgentsInactive,
73}
74
75#[derive(clap::Args)]
76#[command(group(clap::ArgGroup::new("aih_required").required(true).args(["agent_instance_hierarchy"])))]
77pub struct Args {
78    /// The full agent instance hierarchy to watch.
79    #[arg(long = "agent-instance-hierarchy")]
80    pub agent_instance_hierarchy: Option<String>,
81    /// Last-seen `total_tokens`; return immediately if the stored value
82    /// already differs.
83    #[arg(long)]
84    pub previous: Option<i64>,
85    #[command(flatten)]
86    pub base: crate::cli::command::RequestBaseArgs,
87}
88
89#[derive(clap::Args)]
90#[command(args_conflicts_with_subcommands = true)]
91pub struct Command {
92    #[command(flatten)]
93    pub args: Args,
94    #[command(subcommand)]
95    pub schema: Option<Schema>,
96}
97
98#[derive(clap::Subcommand)]
99pub enum Schema {
100    /// Emit the JSON Schema for this leaf's `Request` type and exit.
101    RequestSchema(request_schema::Args),
102    /// Emit the JSON Schema for this leaf's `Response` type and exit.
103    ResponseSchema(response_schema::Args),
104}
105
106impl TryFrom<Args> for Request {
107    type Error = crate::cli::command::FromArgsError;
108    fn try_from(args: Args) -> Result<Self, Self::Error> {
109        Ok(Self {
110            path_type: Path::AgentsLogsTokenUsageSubscribe,
111            agent_instance_hierarchy: args.agent_instance_hierarchy.ok_or_else(|| {
112                crate::cli::command::FromArgsError::path_parse(
113                    "agent-instance-hierarchy",
114                    "--agent-instance-hierarchy is required".to_string(),
115                )
116            })?,
117            previous: args.previous,
118            base: args.base.into(),
119        })
120    }
121}
122
123#[cfg(feature = "cli-executor")]
124pub async fn execute<E: crate::cli::command::CommandExecutor>(
125    executor: &E,
126    mut request: Request,
127    agent_arguments: Option<&crate::cli::command::AgentArguments>,
128) -> Result<E::Stream<ResponseItem>, E::Error> {
129    request.base.clear_transform();
130    executor.execute(request, agent_arguments).await
131}
132
133#[cfg(feature = "cli-executor")]
134pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
135    executor: &E,
136    mut request: Request,
137    transform: crate::cli::command::Transform,
138    agent_arguments: Option<&crate::cli::command::AgentArguments>,
139) -> Result<E::Stream<serde_json::Value>, E::Error> {
140    request.base.set_transform(transform);
141    executor.execute(request, agent_arguments).await
142}
143
144#[cfg(feature = "mcp")]
145impl crate::cli::command::CommandResponse for ResponseItem {
146    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
147        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
148    }
149}
150
151pub mod request_schema;
152
153pub mod response_schema;