Skip to main content

objectiveai_sdk/cli/command/daemon/spawn/
mod.rs

1//! `daemon spawn` — start (or confirm) the per-state plugin daemon.
2//!
3//! Two modes, selected by `dangerous_advanced.foreground`:
4//! - **launcher** (unset/false): probe the per-state daemon lock; if a
5//!   daemon already holds it, return readiness immediately, otherwise
6//!   re-exec this binary as `daemon spawn` with `foreground: true`
7//!   detached and return once it is up.
8//! - **foreground** (true): THIS process becomes the resident daemon —
9//!   it acquires the lock, launches every `daemon: true` plugin as
10//!   `<exec> daemon begin` (leashed), binds a per-plugin socket, emits
11//!   one readiness item, then serves until any plugin exits.
12//!
13//! Streaming leaf: the foreground daemon yields the readiness item as
14//! its first line (the launcher's handshake) and keeps the stream open
15//! while it serves; the launcher yields exactly one readiness item.
16
17use crate::cli::command::CommandRequest;
18
19#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
20#[schemars(rename = "cli.command.daemon.spawn.Request")]
21pub struct Request {
22    pub path_type: Path,
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    #[schemars(extend("omitempty" = true))]
25    pub dangerous_advanced: Option<RequestDangerousAdvanced>,
26    #[serde(flatten)]
27    pub base: crate::cli::command::RequestBase,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
31#[schemars(rename = "cli.command.daemon.spawn.Path")]
32pub enum Path {
33    #[serde(rename = "daemon/spawn")]
34    DaemonSpawn,
35}
36
37#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
38#[schemars(rename = "cli.command.daemon.spawn.RequestDangerousAdvanced")]
39pub struct RequestDangerousAdvanced {
40    /// `Some(true)` → THIS process becomes the resident daemon. When
41    /// unset/false, `daemon spawn` re-execs itself with this set and
42    /// returns once the daemon is up.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    #[schemars(extend("omitempty" = true))]
45    pub foreground: Option<bool>,
46}
47
48impl CommandRequest for Request {
49    fn request_base(&self) -> &crate::cli::command::RequestBase {
50        &self.base
51    }
52
53    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
54        Some(&mut self.base)
55    }
56}
57
58/// One daemon-spawn stream item. The foreground daemon emits this once
59/// it is ready (readiness handshake) and the launcher emits it once the
60/// daemon is confirmed up.
61#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
62#[schemars(rename = "cli.command.daemon.spawn.ResponseItem")]
63pub struct ResponseItem {
64    pub ok: bool,
65}
66
67#[derive(clap::Args)]
68pub struct Args {
69    /// Raw JSON for `RequestDangerousAdvanced` (e.g. `{"foreground":true}`).
70    #[arg(long)]
71    pub dangerous_advanced: Option<String>,
72    #[command(flatten)]
73    pub base: crate::cli::command::RequestBaseArgs,
74}
75
76#[derive(clap::Args)]
77#[command(args_conflicts_with_subcommands = true)]
78pub struct Command {
79    #[command(flatten)]
80    pub args: Args,
81    #[command(subcommand)]
82    pub schema: Option<Schema>,
83}
84
85#[derive(clap::Subcommand)]
86pub enum Schema {
87    /// Emit the JSON Schema for this leaf's `Request` type and exit.
88    RequestSchema(request_schema::Args),
89    /// Emit the JSON Schema for this leaf's `Response` type and exit.
90    ResponseSchema(response_schema::Args),
91}
92
93impl TryFrom<Args> for Request {
94    type Error = crate::cli::command::FromArgsError;
95    fn try_from(args: Args) -> Result<Self, Self::Error> {
96        let dangerous_advanced: Option<RequestDangerousAdvanced> =
97            if let Some(s) = args.dangerous_advanced {
98                let mut de = serde_json::Deserializer::from_str(&s);
99                let v = serde_path_to_error::deserialize(&mut de).map_err(|source| {
100                    crate::cli::command::FromArgsError {
101                        field: "dangerous_advanced",
102                        source: source.into(),
103                    }
104                })?;
105                Some(v)
106            } else {
107                None
108            };
109        Ok(Self {
110            path_type: Path::DaemonSpawn,
111            dangerous_advanced,
112            base: args.base.into(),
113        })
114    }
115}
116
117#[cfg(feature = "cli-executor")]
118pub async fn execute<E: crate::cli::command::CommandExecutor>(
119    executor: &E,
120    mut request: Request,
121    agent_arguments: Option<&crate::cli::command::AgentArguments>,
122) -> Result<E::Stream<ResponseItem>, E::Error> {
123    request.base.clear_transform();
124    executor.execute(request, agent_arguments).await
125}
126
127#[cfg(feature = "cli-executor")]
128pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
129    executor: &E,
130    mut request: Request,
131    transform: crate::cli::command::Transform,
132    agent_arguments: Option<&crate::cli::command::AgentArguments>,
133) -> Result<E::Stream<serde_json::Value>, E::Error> {
134    request.base.set_transform(transform);
135    executor.execute(request, agent_arguments).await
136}
137
138#[cfg(feature = "mcp")]
139impl crate::cli::command::CommandResponse for ResponseItem {
140    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
141        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
142    }
143}
144
145pub mod request_schema;
146
147pub mod response_schema;