Skip to main content

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

1//! `laboratories create` — create + start a laboratory container (a podman
2//! container the conduit dials as a client-side MCP server). Inputs name the
3//! container per state (`--id`), pick its base image (`--image`), and add
4//! repeatable bind mounts (`--mount host=…,container=…`) and environment
5//! entries (`--env KEY=VALUE`). `--client` is required (a required arg-group,
6//! leaving room to add `--server` later). The leaf echoes back what it created.
7
8use std::str::FromStr;
9
10use crate::cli::command::CommandRequest;
11use crate::laboratories::{EnvVar, Mount};
12
13/// Default working directory new agents start in, when `--cwd` is omitted (and
14/// `#[serde(default)]` for older clients that don't send the field).
15fn default_cwd() -> String {
16    "/".to_string()
17}
18
19#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
20#[schemars(rename = "cli.command.laboratories.create.Request")]
21pub struct Request {
22    pub path_type: Path,
23    pub kind: Kind,
24    pub id: String,
25    /// The base image, split (`registry` + `name` + tag XOR digest) —
26    /// a joined reference string is never accepted, so unqualified
27    /// short names are unrepresentable.
28    pub image: crate::laboratories::LaboratoryImage,
29    pub mounts: Vec<Mount>,
30    pub env: Vec<EnvVar>,
31    /// Default working directory new agents start in; defaults to `/`.
32    #[serde(default = "default_cwd")]
33    pub cwd: String,
34    /// The EXACT machine id (as `laboratories list` reports it) whose
35    /// laboratory host should own the container. Provided together
36    /// with `machine_state` or not at all; neither ⇒ the current
37    /// machine + the daemon's own state.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    #[schemars(extend("omitempty" = true))]
40    pub machine: Option<String>,
41    /// The state (on `machine`) whose laboratory host should own the
42    /// container. Paired with `machine` — both or neither.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    #[schemars(extend("omitempty" = true))]
45    pub machine_state: Option<String>,
46    #[serde(flatten)]
47    pub base: crate::cli::command::RequestBase,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
51#[schemars(rename = "cli.command.laboratories.create.Path")]
52pub enum Path {
53    #[serde(rename = "laboratories/create")]
54    LaboratoriesCreate,
55}
56
57/// Which side of the conduit the laboratory serves. Only `Client` (a
58/// client-side MCP server the conduit dials) exists today; the tag-by-`by`
59/// shape leaves room to add `Server` later.
60#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
61#[serde(tag = "by", rename_all = "snake_case")]
62#[schemars(rename = "cli.command.laboratories.create.Kind")]
63pub enum Kind {
64    // No variant-level `#[schemars(title = "...")]`: a single-variant enum
65    // collapses and hoists the variant title to the schema's top-level
66    // `title`, which the JS codegen then uses as the module path — a title
67    // of "Client" would clobber `src/client.ts`. Let `rename` drive it.
68    Client,
69}
70
71impl CommandRequest for Request {
72    fn request_base(&self) -> &crate::cli::command::RequestBase {
73        &self.base
74    }
75
76    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
77        Some(&mut self.base)
78    }
79}
80
81/// Echo of the created laboratory, from the owning host's reply.
82#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
83#[schemars(rename = "cli.command.laboratories.create.Response")]
84pub struct Response {
85    pub id: String,
86    pub image: crate::laboratories::LaboratoryImage,
87    pub mounts: Vec<Mount>,
88    pub env: Vec<EnvVar>,
89    pub cwd: String,
90    /// Unix seconds when the container was created, from podman's own
91    /// record on the owning host. `None` when the host didn't report
92    /// it.
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    #[schemars(extend("omitempty" = true))]
95    pub created_at: Option<i64>,
96    /// The machine whose laboratory host owns the container.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    #[schemars(extend("omitempty" = true))]
99    pub machine: Option<crate::machine::MachineIdentity>,
100    /// The state (on that machine) whose laboratory host owns the
101    /// container.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    #[schemars(extend("omitempty" = true))]
104    pub machine_state: Option<String>,
105}
106
107#[derive(clap::Args)]
108#[command(
109    group(clap::ArgGroup::new("side").required(true).args(["client"])),
110    group(clap::ArgGroup::new("id_required").required(true).args(["id"])),
111    group(clap::ArgGroup::new("image_source").required(true).args(["registry", "image_inline"])),
112)]
113pub struct Args {
114    /// Create a client-side laboratory (an MCP server the conduit dials).
115    /// Required (part of the `side` arg-group, which will gain `--server`).
116    #[arg(long)]
117    pub client: bool,
118    /// Laboratory id — names the per-state container.
119    #[arg(long)]
120    pub id: Option<String>,
121    /// The image host — e.g. `docker.io`, `ghcr.io`,
122    /// `registry.example.com:5000`. Must be unambiguously a registry
123    /// (domain, host:port, or localhost) — short names are refused.
124    /// Mutually exclusive with `--image-inline`.
125    #[arg(long, requires = "name")]
126    pub registry: Option<String>,
127    /// The image repository path — e.g. `library/bash`. Requires
128    /// `--registry`.
129    #[arg(long, requires = "registry")]
130    pub name: Option<String>,
131    /// Image tag (mutually exclusive with `--digest`; requires
132    /// `--registry`).
133    #[arg(long, conflicts_with_all = ["digest", "image_inline"], requires = "registry")]
134    pub tag: Option<String>,
135    /// Image digest, `<algorithm>:<64 hex>` (mutually exclusive with
136    /// `--tag`; requires `--registry`).
137    #[arg(long, conflicts_with = "image_inline", requires = "registry")]
138    pub digest: Option<String>,
139    /// The image spec INLINE, as a JSON string literal of
140    /// Containerfile content (quoted + escaped on the command line;
141    /// e.g. `--image-inline "\"FROM docker.io/library/bash:latest\n\""`).
142    /// The host builds it on every create against an empty context.
143    /// Mutually exclusive with the `--registry` family.
144    #[arg(long)]
145    pub image_inline: Option<String>,
146    /// Repeatable `--mount host=…,container=…` bind mount.
147    #[arg(long = "mount")]
148    pub mounts: Vec<String>,
149    /// Repeatable `--env KEY=VALUE` environment entry.
150    #[arg(long = "env")]
151    pub env: Vec<String>,
152    /// Default working directory new agents start in; defaults to `/`.
153    #[arg(long)]
154    pub cwd: Option<String>,
155    /// The EXACT machine id (from `laboratories list`) whose host
156    /// should own the container. Requires `--machine-state`; neither ⇒
157    /// the current machine + the daemon's own state.
158    #[arg(long, requires = "machine_state")]
159    pub machine: Option<String>,
160    /// The state (on `--machine`) whose host should own the container.
161    /// Requires `--machine` — both or neither.
162    #[arg(long, requires = "machine")]
163    pub machine_state: Option<String>,
164    #[command(flatten)]
165    pub base: crate::cli::command::RequestBaseArgs,
166}
167
168#[derive(clap::Args)]
169#[command(args_conflicts_with_subcommands = true)]
170pub struct Command {
171    #[command(flatten)]
172    pub args: Args,
173    #[command(subcommand)]
174    pub schema: Option<Schema>,
175}
176
177#[derive(clap::Subcommand)]
178pub enum Schema {
179    /// Emit the JSON Schema for this leaf's `Request` type and exit.
180    RequestSchema(request_schema::Args),
181    /// Emit the JSON Schema for this leaf's `Response` type and exit.
182    ResponseSchema(response_schema::Args),
183}
184
185impl TryFrom<Args> for Request {
186    type Error = crate::cli::command::FromArgsError;
187    fn try_from(args: Args) -> Result<Self, Self::Error> {
188        let id = args.id.ok_or_else(|| {
189            crate::cli::command::FromArgsError::path_parse("id", "--id is required".to_string())
190        })?;
191        // The image source: --image-inline XOR the --registry family.
192        // Clap enforces the coarse exclusivity; this is the friendly
193        // authoritative pass.
194        let image = match (args.image_inline, args.registry) {
195            (Some(inline_json), None) => {
196                // The ARGV value is a JSON string literal; the typed
197                // Request holds the PLAIN decoded Containerfile text.
198                let containerfile: String = serde_json::from_str(&inline_json)
199                    .map_err(|e| {
200                        crate::cli::command::FromArgsError::path_parse(
201                            "image-inline",
202                            format!(
203                                "--image-inline must be a JSON string literal \
204                                 (quoted + escaped): {e}"
205                            ),
206                        )
207                    })?;
208                crate::laboratories::LaboratoryImage::Inline(
209                    crate::laboratories::InlineLaboratoryImage { containerfile },
210                )
211            }
212            (None, Some(registry)) => {
213                let name = args.name.ok_or_else(|| {
214                    crate::cli::command::FromArgsError::path_parse(
215                        "name",
216                        "--name is required with --registry".to_string(),
217                    )
218                })?;
219                let pin = match (args.tag, args.digest) {
220                    (Some(tag), None) => {
221                        crate::laboratories::LaboratoryImagePin::Tag(tag)
222                    }
223                    (None, Some(digest)) => {
224                        crate::laboratories::LaboratoryImagePin::Digest(digest)
225                    }
226                    _ => {
227                        return Err(crate::cli::command::FromArgsError::path_parse(
228                            "image",
229                            "exactly one of --tag, --digest is required \
230                             with --registry"
231                                .to_string(),
232                        ));
233                    }
234                };
235                crate::laboratories::LaboratoryImage::Registry(
236                    crate::laboratories::RegistryLaboratoryImage {
237                        registry,
238                        name,
239                        pin,
240                    },
241                )
242            }
243            _ => {
244                return Err(crate::cli::command::FromArgsError::path_parse(
245                    "image",
246                    "exactly one of --image-inline, --registry is required"
247                        .to_string(),
248                ));
249            }
250        };
251        if !args.client {
252            return Err(crate::cli::command::FromArgsError::path_parse(
253                "client",
254                "--client is required".to_string(),
255            ));
256        }
257        let mounts = args
258            .mounts
259            .iter()
260            .map(|s| {
261                s.parse::<Mount>()
262                    .map_err(|m| crate::cli::command::FromArgsError::path_parse("mount", m))
263            })
264            .collect::<Result<Vec<_>, _>>()?;
265        let env = args
266            .env
267            .iter()
268            .map(|s| {
269                s.parse::<EnvVar>()
270                    .map_err(|m| crate::cli::command::FromArgsError::path_parse("env", m))
271            })
272            .collect::<Result<Vec<_>, _>>()?;
273        let cwd = args.cwd.unwrap_or_else(default_cwd);
274        // Both-or-neither, re-validated beyond clap's mutual
275        // `requires` (which only runs for argv-built requests).
276        if args.machine.is_some() != args.machine_state.is_some() {
277            return Err(crate::cli::command::FromArgsError::path_parse(
278                "machine",
279                "--machine and --machine-state must be provided together".to_string(),
280            ));
281        }
282        Ok(Self {
283            path_type: Path::LaboratoriesCreate,
284            kind: Kind::Client,
285            id,
286            image,
287            mounts,
288            env,
289            cwd,
290            machine: args.machine,
291            machine_state: args.machine_state,
292            base: args.base.into(),
293        })
294    }
295}
296
297#[cfg(feature = "cli-executor")]
298pub async fn execute<E: crate::cli::command::CommandExecutor>(
299    executor: &E,
300    mut request: Request,
301    identity: Option<&crate::identity::Identity>,
302) -> Result<Response, E::Error> {
303    request.base.clear_transform();
304    executor.execute_one(request, identity).await
305}
306
307#[cfg(feature = "cli-executor")]
308pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
309    executor: &E,
310    mut request: Request,
311    transform: crate::cli::command::Transform,
312    identity: Option<&crate::identity::Identity>,
313) -> Result<serde_json::Value, E::Error> {
314    request.base.set_transform(transform);
315    executor.execute_one(request, identity).await
316}
317
318#[cfg(feature = "mcp")]
319impl crate::cli::command::CommandResponse for Response {
320    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
321        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
322    }
323}
324
325pub mod request_schema;
326
327pub mod response_schema;
328
329/// One `/listen` broadcast run of `laboratories create`: the actual
330/// [`Request`], the producer's
331/// [`Identity`](crate::identity::Identity), and the
332/// unary response future. See [`crate::daemon::command_listener`].
333#[cfg(all(feature = "cli", feature = "daemon"))]
334pub struct ListenerExecution {
335    pub request: Request,
336    pub identity: crate::identity::Identity,
337    pub response: crate::daemon::command_listener::UnaryResponse<Response>,
338}