use std::str::FromStr;
use crate::cli::command::CommandRequest;
use crate::cli::command::path_ref::tokenize;
fn default_cwd() -> String {
"/".to_string()
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[schemars(rename = "cli.command.laboratories.create.Request")]
pub struct Request {
pub path_type: Path,
pub kind: Kind,
pub id: String,
pub image: crate::laboratories::LaboratoryImage,
pub mounts: Vec<Mount>,
pub env: Vec<EnvVar>,
#[serde(default = "default_cwd")]
pub cwd: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(extend("omitempty" = true))]
pub machine: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(extend("omitempty" = true))]
pub machine_state: Option<String>,
#[serde(flatten)]
pub base: crate::cli::command::RequestBase,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[schemars(rename = "cli.command.laboratories.create.Path")]
pub enum Path {
#[serde(rename = "laboratories/create")]
LaboratoriesCreate,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(tag = "by", rename_all = "snake_case")]
#[schemars(rename = "cli.command.laboratories.create.Kind")]
pub enum Kind {
Client,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[schemars(rename = "cli.command.laboratories.create.Mount")]
pub struct Mount {
pub host: String,
pub container: String,
}
impl FromStr for Mount {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut host: Option<String> = None;
let mut container: Option<String> = None;
for (k, v) in tokenize(s)? {
match k {
"host" => host = Some(v.to_string()),
"container" => container = Some(v.to_string()),
other => return Err(format!("unknown key: {other}")),
}
}
match (host, container) {
(Some(host), Some(container)) => Ok(Mount { host, container }),
(None, _) => Err("host is required".to_string()),
(_, None) => Err("container is required".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[schemars(rename = "cli.command.laboratories.create.EnvVar")]
pub struct EnvVar {
pub key: String,
pub value: String,
}
impl FromStr for EnvVar {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.split_once('=') {
Some((key, value)) => Ok(EnvVar {
key: key.to_string(),
value: value.to_string(),
}),
None => Err(format!("expected KEY=VALUE, got: {s}")),
}
}
}
impl CommandRequest for Request {
fn request_base(&self) -> &crate::cli::command::RequestBase {
&self.base
}
fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
Some(&mut self.base)
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[schemars(rename = "cli.command.laboratories.create.Response")]
pub struct Response {
pub id: String,
pub image: crate::laboratories::LaboratoryImage,
pub mounts: Vec<Mount>,
pub env: Vec<EnvVar>,
pub cwd: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(extend("omitempty" = true))]
pub created_at: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(extend("omitempty" = true))]
pub machine: Option<crate::machine::MachineIdentity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(extend("omitempty" = true))]
pub machine_state: Option<String>,
}
#[derive(clap::Args)]
#[command(
group(clap::ArgGroup::new("side").required(true).args(["client"])),
group(clap::ArgGroup::new("id_required").required(true).args(["id"])),
group(clap::ArgGroup::new("image_source").required(true).args(["registry", "image_inline"])),
)]
pub struct Args {
#[arg(long)]
pub client: bool,
#[arg(long)]
pub id: Option<String>,
#[arg(long, requires = "name")]
pub registry: Option<String>,
#[arg(long, requires = "registry")]
pub name: Option<String>,
#[arg(long, conflicts_with_all = ["digest", "image_inline"], requires = "registry")]
pub tag: Option<String>,
#[arg(long, conflicts_with = "image_inline", requires = "registry")]
pub digest: Option<String>,
#[arg(long)]
pub image_inline: Option<String>,
#[arg(long = "mount")]
pub mounts: Vec<String>,
#[arg(long = "env")]
pub env: Vec<String>,
#[arg(long)]
pub cwd: Option<String>,
#[arg(long, requires = "machine_state")]
pub machine: Option<String>,
#[arg(long, requires = "machine")]
pub machine_state: Option<String>,
#[command(flatten)]
pub base: crate::cli::command::RequestBaseArgs,
}
#[derive(clap::Args)]
#[command(args_conflicts_with_subcommands = true)]
pub struct Command {
#[command(flatten)]
pub args: Args,
#[command(subcommand)]
pub schema: Option<Schema>,
}
#[derive(clap::Subcommand)]
pub enum Schema {
RequestSchema(request_schema::Args),
ResponseSchema(response_schema::Args),
}
impl TryFrom<Args> for Request {
type Error = crate::cli::command::FromArgsError;
fn try_from(args: Args) -> Result<Self, Self::Error> {
let id = args.id.ok_or_else(|| {
crate::cli::command::FromArgsError::path_parse("id", "--id is required".to_string())
})?;
let image = match (args.image_inline, args.registry) {
(Some(inline_json), None) => {
let containerfile: String = serde_json::from_str(&inline_json)
.map_err(|e| {
crate::cli::command::FromArgsError::path_parse(
"image-inline",
format!(
"--image-inline must be a JSON string literal \
(quoted + escaped): {e}"
),
)
})?;
crate::laboratories::LaboratoryImage::Inline(
crate::laboratories::InlineLaboratoryImage { containerfile },
)
}
(None, Some(registry)) => {
let name = args.name.ok_or_else(|| {
crate::cli::command::FromArgsError::path_parse(
"name",
"--name is required with --registry".to_string(),
)
})?;
let pin = match (args.tag, args.digest) {
(Some(tag), None) => {
crate::laboratories::LaboratoryImagePin::Tag(tag)
}
(None, Some(digest)) => {
crate::laboratories::LaboratoryImagePin::Digest(digest)
}
_ => {
return Err(crate::cli::command::FromArgsError::path_parse(
"image",
"exactly one of --tag, --digest is required \
with --registry"
.to_string(),
));
}
};
crate::laboratories::LaboratoryImage::Registry(
crate::laboratories::RegistryLaboratoryImage {
registry,
name,
pin,
},
)
}
_ => {
return Err(crate::cli::command::FromArgsError::path_parse(
"image",
"exactly one of --image-inline, --registry is required"
.to_string(),
));
}
};
if !args.client {
return Err(crate::cli::command::FromArgsError::path_parse(
"client",
"--client is required".to_string(),
));
}
let mounts = args
.mounts
.iter()
.map(|s| {
s.parse::<Mount>()
.map_err(|m| crate::cli::command::FromArgsError::path_parse("mount", m))
})
.collect::<Result<Vec<_>, _>>()?;
let env = args
.env
.iter()
.map(|s| {
s.parse::<EnvVar>()
.map_err(|m| crate::cli::command::FromArgsError::path_parse("env", m))
})
.collect::<Result<Vec<_>, _>>()?;
let cwd = args.cwd.unwrap_or_else(default_cwd);
if args.machine.is_some() != args.machine_state.is_some() {
return Err(crate::cli::command::FromArgsError::path_parse(
"machine",
"--machine and --machine-state must be provided together".to_string(),
));
}
Ok(Self {
path_type: Path::LaboratoriesCreate,
kind: Kind::Client,
id,
image,
mounts,
env,
cwd,
machine: args.machine,
machine_state: args.machine_state,
base: args.base.into(),
})
}
}
#[cfg(feature = "cli-executor")]
pub async fn execute<E: crate::cli::command::CommandExecutor>(
executor: &E,
mut request: Request,
agent_arguments: Option<&crate::cli::command::AgentArguments>,
) -> Result<Response, E::Error> {
request.base.clear_transform();
executor.execute_one(request, agent_arguments).await
}
#[cfg(feature = "cli-executor")]
pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
executor: &E,
mut request: Request,
transform: crate::cli::command::Transform,
agent_arguments: Option<&crate::cli::command::AgentArguments>,
) -> Result<serde_json::Value, E::Error> {
request.base.set_transform(transform);
executor.execute_one(request, agent_arguments).await
}
#[cfg(feature = "mcp")]
impl crate::cli::command::CommandResponse for Response {
fn into_mcp(self) -> crate::cli::command::McpResponseItem {
crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
}
}
pub mod request_schema;
pub mod response_schema;
#[cfg(feature = "cli-listener")]
pub struct ListenerExecution {
pub request: Request,
pub agent_arguments: crate::cli::command::AgentArguments,
pub response: crate::cli::broadcast_listener::UnaryResponse<Response>,
}