use anyhow::Result;
use serde::{Deserialize, Serialize};
use crate::tools::send::Addressee;
pub(crate) const MAX_STEPS: usize = 10;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Step {
pub addressee: Addressee,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub place: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub extract: Option<crate::extract::Extract>,
}
impl Step {
#[must_use]
pub(crate) fn worker() -> Self {
Self {
addressee: Addressee::Worker,
place: None,
branch: None,
name: None,
extract: None,
}
}
#[must_use]
pub(crate) fn role(&self) -> crate::Role {
match self.addressee {
Addressee::Worker | Addressee::WorkerBranch => crate::Role::Worker,
Addressee::Role => crate::Role::Custom,
Addressee::Manager => crate::Role::Manager,
Addressee::Guest | Addressee::Assistant => crate::Role::Assistant,
}
}
#[must_use]
pub(crate) fn label(&self) -> String {
match self.addressee {
Addressee::Worker => crate::Role::Worker.display_label().to_string(),
Addressee::WorkerBranch => {
display_label(crate::Role::Worker, "", self.branch.as_deref())
}
Addressee::Role => display_label(
crate::Role::Custom,
self.name.as_deref().unwrap_or_default(),
self.branch.as_deref(),
),
other => other.as_str().to_string(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Chain {
pub id: String,
pub task: String,
pub user: String,
pub channel: String,
pub workspace: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub inherited: Option<String>,
pub current: Step,
pub step: usize,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub next: Vec<Step>,
}
impl Chain {
#[must_use]
pub(crate) fn total(&self) -> usize {
self.step + self.next.len()
}
}
#[derive(Clone, Debug)]
pub enum Stored {
Ordinary,
Step(Box<Chain>),
Unreadable(Option<String>),
}
impl Stored {
#[must_use]
pub(crate) fn parse(raw: Option<String>) -> Self {
match raw {
None => Self::Ordinary,
Some(raw) => match serde_json::from_str(&raw) {
Ok(chain) => Self::Step(Box::new(chain)),
Err(e) => {
tracing::error!(
error = %e,
"a stored chain is unreadable — its step must be abandoned, not delivered",
);
Self::Unreadable(named_chain_id(&raw))
}
},
}
}
#[must_use]
pub(crate) fn step(&self) -> Option<&Chain> {
match self {
Self::Step(chain) => Some(chain),
Self::Ordinary | Self::Unreadable(_) => None,
}
}
#[must_use]
pub(crate) fn is_unreadable(&self) -> bool {
matches!(self, Self::Unreadable(_))
}
#[must_use]
pub(crate) fn unreadable_chain(&self) -> Option<&str> {
match self {
Self::Unreadable(id) => id.as_deref(),
Self::Ordinary | Self::Step(_) => None,
}
}
}
fn named_chain_id(raw: &str) -> Option<String> {
serde_json::from_str::<serde_json::Value>(raw)
.ok()?
.get("id")?
.as_str()
.map(str::to_string)
}
#[must_use]
pub(crate) fn record_id(chain_id: &str, step: usize) -> String {
format!("chain_{chain_id}_{step}")
}
#[must_use]
pub(crate) fn record_parts(record: &str) -> Option<(&str, usize)> {
let rest = record.strip_prefix("chain_")?;
let (chain_id, step) = rest.rsplit_once('_')?;
Some((chain_id, step.parse().ok()?))
}
fn launch_job(
content: String,
workspace_name: String,
launch: crate::Launch,
) -> crate::agent::message_router::AgentJob {
crate::agent::message_router::AgentJob {
content,
workspace_name,
user_name: crate::users::ADMIN_USER_NAME.to_string(),
channel: "gui".to_string(),
kind: crate::agent::message_router::MessageKind::UserMessage,
role: launch.role,
reply_target: None,
pending_job_id: None,
originating_workspace: None,
custom_role: Some(launch),
reply_to_custom: None,
urgent: false,
extract: None,
}
}
#[derive(Clone, Copy)]
pub(crate) enum BusyFolder<'a> {
Refuse,
Chain(&'a Chain),
Ignore,
}
impl BusyFolder<'_> {
fn chain(&self) -> Option<&Chain> {
match self {
Self::Chain(chain) => Some(chain),
Self::Refuse | Self::Ignore => None,
}
}
pub(crate) fn check(&self, folder: &crate::Workspace, target: Option<&str>) -> Result<()> {
let caller = crate::agent::tool_agent_id().ok();
let (ignore, chain) = match self {
Self::Refuse => (caller.as_deref(), None),
Self::Chain(chain) => (target, Some(chain.id.as_str())),
Self::Ignore => return Ok(()),
};
refuse_busy_folder_excluding(folder, ignore, chain)
}
}
pub(crate) fn refuse_busy_folder(folder: &crate::Workspace) -> Result<()> {
BusyFolder::Refuse.check(folder, None)
}
fn refuse_busy_folder_excluding(
folder: &crate::Workspace,
ignore: Option<&str>,
chain: Option<&str>,
) -> Result<()> {
let Some(running) = crate::agent::registry::AGENT_REGISTRY.worker_in_folder_excluding_chain(
folder.as_path(),
ignore,
chain,
) else {
return Ok(());
};
let working = if running.role == crate::Role::Worker.as_str() {
"a worker"
} else {
"a custom role"
};
let folder = folder.path.trim_end_matches(std::path::MAIN_SEPARATOR);
Err(anyhow::anyhow!(
"usage: {working} is already working in {folder}; the message was not sent, because two \
agents in one folder overwrite each other's edits and parallel agents that can collide \
must not be started in one folder — hint: split the work across different folders, or wait \
for the running one to finish, then send again."
))
}
#[expect(clippy::too_many_arguments)] pub(crate) async fn custom_role(
name: &str,
message: &str,
branch: Option<&str>,
workspace: &crate::Workspace,
asker: Option<crate::agent::message_router::Asker>,
busy: BusyFolder<'_>,
extract: Option<&crate::extract::Extract>,
answered_for: crate::agent::message_router::AnsweredFor,
) -> Result<String> {
anyhow::ensure!(
!message.trim().is_empty(),
"usage: the launch message must not be empty"
);
let role = crate::custom_role::get(name)
.await?
.ok_or_else(|| anyhow::anyhow!("no custom role named '{name}'"))?;
let identifier = branch.map(str::trim).filter(|id| !id.is_empty());
if let Some(id) = identifier {
crate::custom_role::validate_identifier(id)?;
}
let agent_id = match identifier {
Some(id) => crate::session::custom_role_agent_id(name, Some(id)),
None => match role.behavior {
crate::custom_role::CustomRoleBehavior::Continuous => {
crate::session::custom_role_agent_id(name, None)
}
crate::custom_role::CustomRoleBehavior::OneOff => {
crate::session::custom_role_run_agent_id(name)
}
},
};
busy.check(workspace, Some(&agent_id))?;
let launch = crate::Launch {
role: crate::Role::Custom,
name: name.to_string(),
identifier: identifier.map(str::to_string),
prompt: role.prompt,
tools: role.tools,
agent_id: agent_id.clone(),
reply_to: asker.map(Box::new),
chain: busy.chain().cloned().map(Box::new),
extract: extract.cloned(),
};
let id = hand_over_launch(launch, message, &workspace.name, answered_for).await?;
Ok(crate::send_outcome::acknowledged(
format!(
"custom role '{name}' launched on branch {agent_id} in {}",
workspace.name
),
id.as_deref(),
))
}
#[expect(clippy::too_many_arguments)] pub(crate) async fn worker_branch(
caller_ws: &crate::Workspace,
branch: &str,
message: &str,
place: Option<&crate::Workspace>,
asker: Option<crate::Launch>,
busy: BusyFolder<'_>,
extract: Option<&crate::extract::Extract>,
answered_for: crate::agent::message_router::AnsweredFor,
) -> Result<String> {
anyhow::ensure!(
!message.trim().is_empty(),
"usage: the message must not be empty"
);
let branch = branch.trim();
crate::custom_role::validate_worker_branch(branch)?;
let workspace_name = place.map_or_else(|| caller_ws.name.clone(), |ws| ws.path.clone());
let folder = place.unwrap_or(caller_ws);
let agent_id = crate::session::worker_branch_agent_id(branch);
busy.check(folder, Some(&agent_id))?;
let reply_to = asker.map(|launch| crate::agent::message_router::Asker {
launch,
workspace: caller_ws.name.clone(),
});
let launch = crate::Launch {
role: crate::Role::Worker,
name: String::new(),
identifier: Some(branch.to_string()),
prompt: String::new(),
tools: Vec::new(),
agent_id: agent_id.clone(),
reply_to: reply_to.map(Box::new),
chain: busy.chain().cloned().map(Box::new),
extract: extract.cloned(),
};
let id = hand_over_launch(launch, message, &workspace_name, answered_for).await?;
let folder = folder.path.trim_end_matches(std::path::MAIN_SEPARATOR);
let ack = format!(
"Worker branch '{branch}' is on it in {folder}; its report arrives as a <worker-report> message."
);
Ok(crate::send_outcome::acknowledged(ack, id.as_deref()))
}
pub(crate) async fn hand_over_launch(
launch: crate::Launch,
message: &str,
workspace_name: &str,
answered_for: crate::agent::message_router::AnsweredFor,
) -> Result<Option<String>> {
let target = launch.agent_id.clone();
let job = launch_job(message.to_string(), workspace_name.to_string(), launch);
crate::agent::message_router::hand_over(job, &target, "launch", answered_for).await
}
#[must_use]
pub(crate) fn display_label(role: crate::Role, name: &str, identifier: Option<&str>) -> String {
match role {
crate::Role::Worker => format!("Worker branch \"{}\"", identifier.unwrap_or_default()),
_ => match identifier {
Some(id) => format!("Custom role \"{name}\" — branch \"{id}\""),
None => format!("Custom role \"{name}\""),
},
}
}
pub(crate) async fn stop(agent_id: &str) -> Result<()> {
crate::agent::registry::AGENT_REGISTRY.cancel_by_parent_key(
&crate::agent::registry::ParentKey::Launch(agent_id.to_string()),
);
crate::session::store()
.set_launch_stopped(agent_id, true)
.await?;
crate::jobs::delete_pending_jobs_for(agent_id).await?;
if let Some(workspace) = crate::session::store()
.session_workspace_name(agent_id)
.await
{
crate::workspace_index::release_path_named_engine(&workspace);
}
Ok(())
}
pub(crate) async fn launch_workspace(place: Option<&str>) -> Result<crate::Workspace> {
match place.map(str::trim).filter(|w| !w.is_empty()) {
None => Ok(crate::users::personal_workspace_struct(
crate::users::ADMIN_USER_NAME,
)),
Some(raw) => crate::users::resolve_workspace(raw).await?.ok_or_else(|| {
anyhow::anyhow!(
"usage: the place must be a managed workspace name or an absolute path \
to an existing directory"
)
}),
}
}