1use std::sync::Arc;
4
5use anyhow::{Context, Result};
6use perspt_coding::OperationalSafetyBarrier;
7use perspt_sdk::{
8 ActorId, AgentDomainPackage, Capability, Conversation, EffectProposal, KernelState, ModelId,
9 ModelTransport, NodeTerminalOutcome, ProviderToolCall, StaticCatalog, ToolCatalog,
10 ToolChoicePolicy, ToolEntry, TurnOutput, exploration_capability,
11};
12
13use super::{CandidateHandlerRegistry, CandidateToolHandler, InteractionHandler};
14use crate::candidate::CandidateWorkspace;
15use crate::measure::CodingCandidateMeasurer;
16use crate::runtime::Psp9RunConfig;
17use crate::runtime::node::{
18 CodingContract, loop_kernel_state, session_grant_policy, worker_capability,
19};
20use crate::toolloop::{EffectExecutor as _, EffectOutcome, LoopBudgets, PromptEnvelope, ToolLoop};
21use crate::turn::{ActorKind, ActorTurnRunner};
22
23#[async_trait::async_trait]
25pub trait SubagentRunner: Send + Sync {
26 async fn run_subagent(
27 &self,
28 parent: &CandidateWorkspace,
29 role: &str,
30 goal: &str,
31 ) -> Result<EffectOutcome>;
32}
33
34pub(crate) struct SpawnAgentHandler;
35
36#[async_trait::async_trait]
37impl CandidateToolHandler for SpawnAgentHandler {
38 async fn apply(
39 &self,
40 workspace: &CandidateWorkspace,
41 call: &ProviderToolCall,
42 _entry: &ToolEntry,
43 ) -> Result<EffectOutcome> {
44 let role = call
45 .arguments
46 .get("role")
47 .and_then(serde_json::Value::as_str)
48 .context("spawn_agent requires a string 'role' argument")?;
49 let goal = call
50 .arguments
51 .get("goal")
52 .and_then(serde_json::Value::as_str)
53 .context("spawn_agent requires a string 'goal' argument")?;
54 let Some(runner) = workspace.subagent_runner() else {
55 return Ok(tool_failure(
56 "spawn_agent is disabled or withheld for this agent",
57 ));
58 };
59 runner.run_subagent(workspace, role, goal).await
60 }
61}
62
63pub(crate) struct RuntimeSubagentRunner {
64 pub(crate) transport: Arc<dyn ModelTransport>,
65 pub(crate) model: ModelId,
66 pub(crate) fallback_models: Vec<ModelId>,
67 pub(crate) domain: Arc<dyn AgentDomainPackage>,
68 pub(crate) tool_handlers: Arc<CandidateHandlerRegistry>,
69 pub(crate) extra_tool_entries: Vec<ToolEntry>,
70 pub(crate) interaction_handler: Arc<dyn InteractionHandler>,
71 pub(crate) config: Psp9RunConfig,
72 pub(crate) exclusions: Vec<std::path::PathBuf>,
73}
74
75#[async_trait::async_trait]
76impl SubagentRunner for RuntimeSubagentRunner {
77 async fn run_subagent(
78 &self,
79 parent: &CandidateWorkspace,
80 role: &str,
81 goal: &str,
82 ) -> Result<EffectOutcome> {
83 match role {
84 "explorer" => {
85 self.run_readonly_subagent(parent, role, ActorKind::Explorer, goal)
86 .await
87 }
88 "reviewer" => {
89 self.run_readonly_subagent(parent, role, ActorKind::Adjudicator, goal)
90 .await
91 }
92 "worker" => self.run_worker_subagent(parent, goal).await,
93 _ => Ok(tool_failure(&format!(
94 "unknown spawn_agent role {role:?}; expected explorer | worker | reviewer"
95 ))),
96 }
97 }
98}
99
100impl RuntimeSubagentRunner {
101 fn open_child(&self, parent: &CandidateWorkspace, name: &str) -> Result<CandidateWorkspace> {
102 let mut child = CandidateWorkspace::create_filtered(
103 parent.overlay_root(),
104 name,
105 0,
106 "subagent",
107 self.config.allow_unisolated_verifiers,
108 &self.exclusions,
109 )?;
110 child.set_tool_handlers(self.tool_handlers.clone());
111 child.set_interaction_handler(self.interaction_handler.clone());
112 child.set_verifier_timeouts(self.config.verifier_timeouts);
113 Ok(child)
115 }
116
117 async fn run_readonly_subagent(
118 &self,
119 parent: &CandidateWorkspace,
120 role: &str,
121 actor: ActorKind,
122 goal: &str,
123 ) -> Result<EffectOutcome> {
124 let child = self.open_child(parent, &format!("subagent-{role}"))?;
125 let catalog = StaticCatalog::with_base(self.extra_tool_entries.clone())?;
126 let capability = exploration_capability(ActorId::new(format!("subagent-{role}")));
127 let specs = catalog.specs_for(std::slice::from_ref(&capability), true);
128 let kernel_state = now_kernel_state();
129 let mut conversation = Conversation::with_system(format!(
130 "You are a read-only {role} subagent. Inspect the workspace and answer \
131 concisely. Write tools and subagents are withheld by capability policy."
132 ));
133 conversation.push_user(goal.to_string());
134 for turn in 0..4u32 {
135 let mut runner = ActorTurnRunner {
136 transport: self.transport.as_ref(),
137 model: self.model.clone(),
138 fallbacks: self.fallback_models.clone(),
139 recorder: None,
140 actor,
141 deadline_secs: self.config.turn_deadline_secs,
142 turn: turn + 1,
143 };
144 match runner
145 .run_turn(&conversation, &specs, ToolChoicePolicy::Auto)
146 .await?
147 {
148 TurnOutput::Text(answer) => {
149 return Ok(EffectOutcome {
150 output: answer,
151 mutated: false,
152 completed: true,
153 });
154 }
155 TurnOutput::ToolCalls(calls) => {
156 conversation.push_tool_calls(calls.clone());
157 for call in calls {
158 let out = apply_readonly_call(
159 &child,
160 &catalog,
161 &capability,
162 &kernel_state,
163 &call,
164 )
165 .await?;
166 conversation.push_tool_response(call.call_id, out);
167 }
168 }
169 }
170 }
171 Ok(tool_failure(&format!(
172 "{role} subagent did not finish within 4 turns"
173 )))
174 }
175
176 fn worker_budgets(&self, rho_floor: f64) -> LoopBudgets {
177 LoopBudgets {
178 max_turns: 6,
179 max_calls_per_turn: self.config.max_calls_per_turn.max(1),
180 rejection_budget: 2,
181 rho_gate: self.config.rho_gate.max(rho_floor),
182 declared_energy_floor: None,
183 context_soft_limit_chars: 120_000,
184 recovery_budget: 2,
185 turn_deadline_secs: self.config.turn_deadline_secs,
186 resident: self.config.resident,
187 }
188 }
189
190 async fn run_worker_subagent(
191 &self,
192 parent: &CandidateWorkspace,
193 goal: &str,
194 ) -> Result<EffectOutcome> {
195 let child = self.open_child(parent, "subagent-worker")?;
196 let catalog = StaticCatalog::with_base(self.extra_tool_entries.clone())?;
197 let (capability, kernel_state) = mint_worker_capability(parent.overlay_root(), &catalog)?;
198 let contract = CodingContract {
199 graph_revision: "subagent".into(),
200 node_id: "subagent-worker".into(),
201 generation: 0,
202 policy: perspt_policy::engine::PolicyEngine::new()?,
203 };
204 let barrier = OperationalSafetyBarrier::default();
205 let scope = perspt_sdk::DomainScope {
206 label: "subagent-worker".into(),
207 paths: Vec::new(),
208 };
209 let cadence = self.domain.verifier_suite(&scope).cadence;
210 let energy = self.domain.energy_model(&scope);
211 let measurer = CodingCandidateMeasurer::new(&child, "subagent-worker", 0)
212 .with_domain(self.domain.clone())
213 .with_max_parallel(self.config.max_parallel_verifiers)
214 .with_require_format(self.config.require_format)
215 .with_test_policy(self.config.test_policy, self.config.external_oracle.clone());
216 let outcome = ToolLoop {
217 transport: self.transport.as_ref(),
218 model: self.model.clone(),
219 fallback_models: self.fallback_models.clone(),
220 catalog: &catalog,
221 capabilities: vec![capability],
222 contract: Some(&contract),
223 barrier: Some(&barrier),
224 c_c_max: 0.25,
225 executor: &child,
226 measurer: &measurer,
227 budgets: self.worker_budgets(energy.rho_gate),
228 cadence,
229 kernel_state,
230 node_id: "subagent-worker".into(),
231 generation: 0,
232 system_prompt: PromptEnvelope {
233 text: format!(
234 "You are an isolated child worker subagent. Fulfill the goal strictly \
235 within the candidate overlay; recursive spawn_agent is withheld.\nGoal: {goal}"
236 ),
237 ..Default::default()
238 },
239 recorder: None,
240 partial_seed_root: None,
241 resumed_birth_deps: Vec::new(),
242 search_budget: None,
243 }
244 .run(goal)
245 .await?;
246 finish_worker_outcome(parent, &child, &outcome).await
247 }
248}
249
250fn mint_worker_capability(
251 root: &std::path::Path,
252 catalog: &StaticCatalog,
253) -> Result<(Capability, KernelState)> {
254 let raw = worker_capability("subagent-worker", "subagent", 0, 0, catalog, &[]);
256 let grant = session_grant_policy(root, "subagent", false, catalog, &[])?;
257 let minted = grant
258 .mint(raw)
259 .map_err(|e| anyhow::anyhow!("child grant intersection: {e}"))?;
260 Ok((minted, loop_kernel_state(&grant, "subagent")))
261}
262
263async fn finish_worker_outcome(
264 parent: &CandidateWorkspace,
265 child: &CandidateWorkspace,
266 outcome: &crate::toolloop::LoopOutcome,
267) -> Result<EffectOutcome> {
268 if matches!(outcome.outcome, NodeTerminalOutcome::HardPass) {
269 let imported = parent.import_child_mutations(child).await?;
270 let summary = serde_json::json!({
271 "status": "hard_pass",
272 "turns_used": outcome.turns_used,
273 "imported_paths": imported,
274 });
275 return Ok(EffectOutcome {
276 output: summary.to_string(),
277 mutated: false,
278 completed: true,
279 });
280 }
281 let summary = serde_json::json!({
282 "status": "did_not_pass",
283 "turns_used": outcome.turns_used,
284 "best_energy": outcome.trajectory.best_accepted_energy,
285 "imported_paths": Vec::<String>::new(),
286 });
287 Ok(tool_failure(&format!(
288 "worker subagent did not reach HardPass; mutations discarded ({summary})"
289 )))
290}
291
292async fn apply_readonly_call(
293 child: &CandidateWorkspace,
294 catalog: &StaticCatalog,
295 capability: &Capability,
296 kernel_state: &KernelState,
297 call: &ProviderToolCall,
298) -> Result<String> {
299 let Some(entry) = catalog.lookup(&call.name).cloned() else {
300 return Ok(format!("denied: unknown tool {:?}", call.name));
301 };
302 let mut proposal = EffectProposal::new(capability.holder.clone(), "subagent-ro", entry.effect);
303 if let Some(path) = call.arguments.get("path").and_then(|v| v.as_str()) {
304 proposal = proposal.with_path(path);
305 }
306 let witness =
307 perspt_sdk::check_admissibility(&proposal, std::slice::from_ref(capability), kernel_state);
308 if !matches!(witness.decision, perspt_sdk::AdmissibilityDecision::Allow) {
309 return Ok(format!("denied: {:?}", witness.decision));
310 }
311 let outcome = child.apply(call, &entry).await?;
312 Ok(outcome.output)
313}
314
315fn now_kernel_state() -> KernelState {
316 let mut state = KernelState::new();
317 let now_unix = std::time::SystemTime::now()
318 .duration_since(std::time::UNIX_EPOCH)
319 .map(|d| d.as_secs() as i64)
320 .unwrap_or(0);
321 state.set_witness("__now", now_unix.to_string());
322 state
323}
324
325fn tool_failure(message: &str) -> EffectOutcome {
326 EffectOutcome {
327 output: format!("tool failed: {message}"),
328 mutated: false,
329 completed: true,
330 }
331}
332
333pub(crate) fn register(registry: &mut CandidateHandlerRegistry) {
334 registry
335 .register("spawn_agent", Arc::new(SpawnAgentHandler))
336 .expect("builtin spawn_agent registration must succeed");
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342 use perspt_sdk::EffectKind;
343
344 #[test]
345 fn child_capabilities_never_grant_spawn_agent() {
346 let catalog = StaticCatalog::with_base(Vec::new()).unwrap();
347 let ro = exploration_capability(ActorId::new("subagent-explorer"));
348 assert!(!ro.effects.contains(&EffectKind::SpawnAgent));
349 assert!(!ro.effects.contains(&EffectKind::WriteArtifact));
350
351 let child_worker = worker_capability("s", "r", 0, 0, &catalog, &[]);
352 assert!(!child_worker.effects.contains(&EffectKind::SpawnAgent));
353 assert!(
354 !child_worker
355 .effects
356 .contains(&EffectKind::MutateDependencies)
357 );
358 }
359}