harness-tools + app: task tool, subagent spawner, board wiring (M4)
The `task` tool delegates to a SubagentSpawner (owned by the composition root): resolves the agent, enforces the depth limit, applies permission intersection, filters tools per-agent, and runs the child session foreground or background. Foreground returns the child's final text; background registers on the job board and detaches under the parent run token. The run loop injects the board into primary-agent requests and reconciles terminal jobs each step. Integration tests cover foreground run + alias reuse continuing the same child session, depth-limit and unknown-agent rejection, and board prompt injection. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,8 @@ pub struct RunConfig {
|
||||
pub instructions: Vec<String>,
|
||||
/// Pricing for `model`, from models.dev metadata. `None` leaves cost at 0.
|
||||
pub cost: Option<crate::types::ModelCost>,
|
||||
/// Whether to append the background job board to requests (primary/delegating agents).
|
||||
pub inject_job_board: bool,
|
||||
}
|
||||
|
||||
/// Adds a step's usage/cost onto the persisted session and republishes it. Cost accounting is
|
||||
@@ -198,6 +200,22 @@ pub async fn run_session(
|
||||
wire_messages.extend(convert_message(message, &parts));
|
||||
}
|
||||
|
||||
// Append the (synthetic, non-persisted) job board to the last user message so the
|
||||
// orchestrator sees running/reusable subtasks. docs/04-multiagent.md.
|
||||
if run_config.inject_job_board {
|
||||
if let Some(board) = &ctx.job_board {
|
||||
if let Some(block) = board.format_for_prompt() {
|
||||
if let Some(last_user) = wire_messages
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|m| m.role == WireRole::User)
|
||||
{
|
||||
last_user.content.push(WireContent::Text { text: block });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let system_blocks = system::assemble(
|
||||
system::env_header(&ctx.cwd),
|
||||
&run_config.agent_prompt,
|
||||
@@ -260,6 +278,15 @@ pub async fn run_session(
|
||||
}
|
||||
Ok(outcome) => {
|
||||
accumulate_session_usage(&ctx, &outcome.usage, outcome.cost, now_fn()).await;
|
||||
// A completed step means the orchestrator has now seen any terminal jobs
|
||||
// that were on the board this turn; mark them reconciled.
|
||||
if run_config.inject_job_board {
|
||||
if let Some(board) = &ctx.job_board {
|
||||
if let Err(e) = board.reconcile_terminal(now_fn()).await {
|
||||
tracing::warn!(error = %e, "failed to reconcile job board");
|
||||
}
|
||||
}
|
||||
}
|
||||
match outcome.result {
|
||||
StepResult::Continue => continue,
|
||||
StepResult::Stop => return RunOutcome::Stopped,
|
||||
@@ -376,11 +403,14 @@ mod tests {
|
||||
permissions,
|
||||
static_rules: Vec::new(),
|
||||
extra_rules: Arc::new(std::sync::Mutex::new(Vec::new())),
|
||||
parent_rules: Vec::new(),
|
||||
session_id,
|
||||
cwd: cwd.clone(),
|
||||
data_dir: cwd.join("tool-output"),
|
||||
cancel: CancellationToken::new(),
|
||||
now: 1,
|
||||
spawner: None,
|
||||
job_board: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,6 +492,7 @@ mod tests {
|
||||
output: 15.0,
|
||||
..Default::default()
|
||||
}),
|
||||
inject_job_board: false,
|
||||
};
|
||||
|
||||
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
|
||||
@@ -569,6 +600,7 @@ mod tests {
|
||||
max_steps: 10,
|
||||
instructions: Vec::new(),
|
||||
cost: None,
|
||||
inject_job_board: false,
|
||||
};
|
||||
|
||||
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
|
||||
@@ -578,4 +610,128 @@ mod tests {
|
||||
let messages = store.messages(session_id).await.unwrap();
|
||||
assert_eq!(messages.len(), 1);
|
||||
}
|
||||
|
||||
/// Records the last request it was asked to stream so tests can assert on prompt content.
|
||||
struct CapturingProvider {
|
||||
last: StdMutex<Option<LlmRequest>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Provider for CapturingProvider {
|
||||
fn id(&self) -> &str {
|
||||
"mock"
|
||||
}
|
||||
async fn list_models(&self) -> Result<Vec<ModelInfo>, ProviderError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn stream(
|
||||
&self,
|
||||
req: LlmRequest,
|
||||
_cancel: CancellationToken,
|
||||
) -> Result<LlmEventStream, ProviderError> {
|
||||
*self.last.lock().unwrap() = Some(req);
|
||||
let events = vec![
|
||||
Ok(LlmEvent::TextStart { id: "t".into() }),
|
||||
Ok(LlmEvent::TextDelta {
|
||||
id: "t".into(),
|
||||
text: "ok".into(),
|
||||
}),
|
||||
Ok(LlmEvent::TextEnd { id: "t".into() }),
|
||||
Ok(LlmEvent::Finish {
|
||||
reason: FinishReason::Stop,
|
||||
usage: usage(1, 1),
|
||||
}),
|
||||
];
|
||||
Ok(Box::pin(futures::stream::iter(events)))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn job_board_is_injected_into_the_last_user_message() {
|
||||
use crate::engine::jobs::{JobBoard, LaunchSpec};
|
||||
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let bus = EventBus::new();
|
||||
let model = ModelRef::new("mock", "mock-model");
|
||||
let session = Session::new_root("orchestrator", model.clone(), 1);
|
||||
let session_id = session.id.clone();
|
||||
store.upsert_session(session).await.unwrap();
|
||||
|
||||
let user_message = Message::new_user(session_id.clone(), 1);
|
||||
store.upsert_message(user_message.clone()).await.unwrap();
|
||||
store
|
||||
.upsert_part(Part {
|
||||
id: crate::types::PartId::new(),
|
||||
message_id: user_message.id.clone(),
|
||||
session_id: session_id.clone(),
|
||||
idx: 0,
|
||||
body: PartBody::Text {
|
||||
text: "carry on".into(),
|
||||
synthetic: false,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// A board with one running job for this session.
|
||||
let board = std::sync::Arc::new(
|
||||
JobBoard::load(store.clone(), bus.clone(), &session_id, 2)
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
board
|
||||
.register_launch(
|
||||
LaunchSpec {
|
||||
task_id: "t1".into(),
|
||||
parent_session: session_id.clone(),
|
||||
child_session: SessionId::new(),
|
||||
agent: "explorer".into(),
|
||||
description: "map auth".into(),
|
||||
objective: Some("map the auth flow".into()),
|
||||
},
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let cwd = tempfile::tempdir().unwrap();
|
||||
let mut ctx = make_ctx(store, bus, session_id, cwd.path().to_path_buf()).await;
|
||||
ctx.job_board = Some(board);
|
||||
let run_config = RunConfig {
|
||||
agent_name: "orchestrator".into(),
|
||||
agent_prompt: "You orchestrate.".into(),
|
||||
model,
|
||||
temperature: None,
|
||||
max_steps: 1,
|
||||
instructions: Vec::new(),
|
||||
cost: None,
|
||||
inject_job_board: true,
|
||||
};
|
||||
|
||||
let provider = std::sync::Arc::new(CapturingProvider {
|
||||
last: StdMutex::new(None),
|
||||
});
|
||||
let outcome = run_session(provider.clone(), ctx, &run_config, || 2).await;
|
||||
assert!(matches!(outcome, RunOutcome::Stopped));
|
||||
|
||||
let req = provider.last.lock().unwrap().clone().expect("a request");
|
||||
let last_user = req
|
||||
.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|m| m.role == WireRole::User)
|
||||
.expect("a user message");
|
||||
let text: String = last_user
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
WireContent::Text { text } => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(text.contains("Background Job Board"), "got: {text}");
|
||||
assert!(text.contains("exp-1"), "got: {text}");
|
||||
assert!(text.contains("map the auth flow"), "got: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user