mod child;
mod depth;
mod execute;
mod parse;
use std::{collections::BTreeSet, sync::Arc};
use async_trait::async_trait;
use mentra::tool::{
ParallelToolContext, RuntimeToolDescriptor, ToolApprovalCategory, ToolAuthorizationPreview,
ToolCapability, ToolContext, ToolDefinition, ToolDurability, ToolExecutionCategory,
ToolExecutor, ToolResult, ToolSideEffectLevel,
};
use serde_json::{Value, json};
use crate::runtime::dispatch::HookDispatch;
use parse::{INPUT_FIELD, Mode, Spawn, parse};
pub(crate) use parse::{LOCAL_TARGET, Mode as SpawnMode, is_target_name, parse as parse_spawn};
pub use child::{ChildContext, ChildSpec};
pub use depth::DEFAULT_DELEGATION_DEPTH;
pub(crate) use child::ChildPolicy;
pub const SPAWN: &str = "spawn";
const DESCRIPTION: &str = "\
Hand work to something else and read the result back.
Takes one string. If it starts with `!`, the rest runs as a shell command in \
this workspace and you get its output — `!cargo test -q`. Anything else is a \
task handed to a subagent, which works on it and returns a final answer — \
`find every TODO under src/ and summarise them`.
To delegate a task whose own text starts with `!`, double it: `!!important, …`.
Commands are put to the operator before they run, so ask for one command that \
does the job rather than several that each need answering.";
fn targets_paragraph(targets: &[String]) -> String {
format!(
"A command can also say where it runs: `!@<target> <command>` runs it on that target \
rather than here — `!@{first} <command>`. Registered targets: {names}. A command with \
no `@` runs where basis itself is running, which is what you want unless the work \
needs one of those targets.",
first = targets[0],
names = listed(targets),
)
}
fn listed(targets: &[String]) -> String {
targets
.iter()
.map(|name| format!("`{name}`"))
.collect::<Vec<_>>()
.join(", ")
}
#[derive(Default)]
pub struct SpawnTool {
depth: depth::Depth,
targets: Vec<String>,
policy: Option<ChildPolicy>,
workspaces: Option<Arc<HookDispatch>>,
}
impl std::fmt::Debug for SpawnTool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SpawnTool")
.field("depth", &self.depth)
.field("targets", &self.targets)
.field("policy", &self.policy.as_ref().map(|_| "<child policy>"))
.field(
"workspaces",
&self.workspaces.as_ref().map(|_| "<registry>"),
)
.finish()
}
}
impl SpawnTool {
pub fn new() -> Self {
Self::default()
}
pub fn with_targets(targets: impl IntoIterator<Item = String>) -> Self {
Self::with_targets_and_depth(targets, depth::DEFAULT_DELEGATION_DEPTH)
}
pub fn with_targets_and_depth(
targets: impl IntoIterator<Item = String>,
max_depth: usize,
) -> Self {
Self {
depth: depth::Depth::new(max_depth),
targets: targets
.into_iter()
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
policy: None,
workspaces: None,
}
}
#[must_use]
pub fn with_child_policy<F>(self, policy: F) -> Self
where
F: Fn(&ChildContext<'_>) -> ChildSpec + Send + Sync + 'static,
{
self.with_child_policy_arc(Arc::new(policy))
}
#[must_use]
pub(crate) fn with_child_policy_arc(self, policy: ChildPolicy) -> Self {
Self {
policy: Some(policy),
..self
}
}
#[must_use]
pub(crate) fn with_workspaces(self, workspaces: Arc<HookDispatch>) -> Self {
Self {
workspaces: Some(workspaces),
..self
}
}
fn denied_to_parent(&self, workspace_dir: &std::path::Path) -> BTreeSet<String> {
self.workspaces
.as_ref()
.map(|registry| registry.foreign_tools(workspace_dir))
.unwrap_or_default()
}
fn child_spec(
&self,
prompt: &str,
parent_agent_id: &str,
workspace_dir: &std::path::Path,
) -> ChildSpec {
match &self.policy {
Some(policy) => policy(&ChildContext::new(prompt, parent_agent_id, workspace_dir)),
None => ChildSpec::inherit(),
}
}
fn authorize_target(&self, spawn: &Spawn) -> Result<(), String> {
let Some(target) = spawn.target() else {
return Ok(());
};
if self.targets.iter().any(|name| name == target) {
return Ok(());
}
Err(if self.targets.is_empty() {
format!(
"spawn has no command targets registered, so `!@{target}` has nowhere to run; \
write the command with no `@` to run it where basis is running"
)
} else {
format!(
"spawn has no command target named `{target}`; the registered targets are {}, \
and a command with no `@` runs where basis is running",
listed(&self.targets)
)
})
}
}
impl ToolDefinition for SpawnTool {
fn descriptor(&self) -> RuntimeToolDescriptor {
RuntimeToolDescriptor::builder(SPAWN)
.description(description(&self.targets))
.input_schema(input_schema(&self.targets))
.capabilities(vec![
ToolCapability::ProcessExec,
ToolCapability::FilesystemWrite,
ToolCapability::Delegation,
])
.side_effect_level(ToolSideEffectLevel::Process)
.durability(ToolDurability::Ephemeral)
.execution_category(ToolExecutionCategory::ExclusiveLocalMutation)
.approval_category(ToolApprovalCategory::Process)
.build()
}
}
fn description(targets: &[String]) -> String {
if targets.is_empty() {
return DESCRIPTION.to_string();
}
format!("{DESCRIPTION}\n\n{}", targets_paragraph(targets))
}
fn input_schema(targets: &[String]) -> Value {
let mut description = "A shell command when it starts with `!`, otherwise a task to \
delegate. Write `!!` to begin a task with a literal `!`."
.to_string();
if !targets.is_empty() {
description.push_str(&format!(
" Write `!@<target> <command>` to run a command on one of this runtime's targets \
({}).",
listed(targets)
));
}
json!({
"type": "object",
"properties": {
INPUT_FIELD: {
"type": "string",
"description": description,
}
},
"required": [INPUT_FIELD],
})
}
#[async_trait]
impl ToolExecutor for SpawnTool {
fn authorization_preview(
&self,
ctx: &ParallelToolContext,
input: &Value,
) -> Result<ToolAuthorizationPreview, String> {
let spawn = parse(input)?;
self.authorize_target(&spawn)?;
if spawn.mode() == Mode::Agent {
self.depth.authorize_delegation(&ctx.agent_id)?;
}
let cwd = ctx.resolve_working_directory(None)?;
let child = match spawn.mode() {
Mode::Agent => self
.child_spec(spawn.body(), &ctx.agent_id, &cwd)
.preview_value(),
Mode::Command => None,
};
Ok(preview(&spawn, cwd, &self.descriptor(), input, child))
}
fn execution_category(&self, input: &Value) -> ToolExecutionCategory {
parse(input).map_or(ToolExecutionCategory::ExclusiveLocalMutation, |spawn| {
execution_category(spawn.mode())
})
}
async fn execute_mut(&self, mut ctx: ToolContext<'_>, input: Value) -> ToolResult {
let spawn = parse(&input)?;
match spawn.mode() {
Mode::Command => {
self.authorize_target(&spawn)?;
execute::command(&ctx, spawn.body(), spawn.target()).await
}
Mode::Agent => {
let depth = self.depth.authorize_delegation(&ctx.agent_id)?;
let (spec, denied) = if self.policy.is_none() {
(ChildSpec::inherit(), BTreeSet::new())
} else {
let cwd = ctx.resolve_working_directory(None)?;
let spec = self.child_spec(spawn.body(), &ctx.agent_id, &cwd);
let denied = match spec.overrides_roster() {
true => self.denied_to_parent(&cwd),
false => BTreeSet::new(),
};
(spec, denied)
};
execute::delegate(&self.depth, &mut ctx, spawn.body(), depth, spec, denied).await
}
}
}
}
fn preview(
spawn: &Spawn,
cwd: std::path::PathBuf,
descriptor: &RuntimeToolDescriptor,
raw_input: &Value,
child: Option<Value>,
) -> ToolAuthorizationPreview {
let mut structured_input = json!({
"mode": spawn.mode().as_str(),
"body": spawn.body(),
"cwd": cwd,
"target": spawn.target().unwrap_or(LOCAL_TARGET),
});
if let Some(child) = child {
structured_input
.as_object_mut()
.expect("built as an object two lines up")
.insert("child".to_string(), child);
}
ToolAuthorizationPreview {
working_directory: cwd,
capabilities: capabilities(spawn.mode()),
side_effect_level: side_effect_level(spawn.mode()),
durability: descriptor.durability,
execution_category: execution_category(spawn.mode()),
approval_category: approval_category(spawn.mode()),
raw_input: raw_input.clone(),
structured_input,
}
}
const fn side_effect_level(mode: Mode) -> ToolSideEffectLevel {
match mode {
Mode::Command => ToolSideEffectLevel::Process,
Mode::Agent => ToolSideEffectLevel::LocalState,
}
}
fn capabilities(mode: Mode) -> Vec<ToolCapability> {
match mode {
Mode::Command => vec![ToolCapability::ProcessExec, ToolCapability::FilesystemWrite],
Mode::Agent => vec![ToolCapability::Delegation],
}
}
const fn approval_category(mode: Mode) -> ToolApprovalCategory {
match mode {
Mode::Command => ToolApprovalCategory::Process,
Mode::Agent => ToolApprovalCategory::Delegation,
}
}
const fn execution_category(mode: Mode) -> ToolExecutionCategory {
match mode {
Mode::Command => ToolExecutionCategory::ExclusiveLocalMutation,
Mode::Agent => ToolExecutionCategory::Delegation,
}
}
#[cfg(test)]
mod tests;