Skip to main content

perspt_agent/tools/handlers/
interact.rs

1//! Governed interactive handlers (`ask_user` and `run_repo_script`).
2
3use std::collections::BTreeMap;
4use std::future::Future;
5use std::sync::Arc;
6
7use anyhow::{Context, Result};
8use perspt_sdk::{ProviderToolCall, ToolEntry};
9use serde::Deserialize;
10
11use super::{CandidateHandlerRegistry, CandidateToolHandler};
12use crate::candidate::CandidateWorkspace;
13use crate::toolloop::EffectOutcome;
14
15/// Host callback backing the `ask_user` tool.
16#[async_trait::async_trait]
17pub trait InteractionHandler: Send + Sync {
18    async fn ask_user(&self, question: &str) -> Result<String>;
19}
20
21/// Default fail-safe handler used in non-interactive headless/CI runs.
22#[derive(Debug, Clone, Copy, Default)]
23pub struct NonInteractiveHandler;
24
25#[async_trait::async_trait]
26impl InteractionHandler for NonInteractiveHandler {
27    async fn ask_user(&self, _question: &str) -> Result<String> {
28        Ok(
29            "interactive user input is unavailable in non-interactive mode; \
30             proceed autonomously under declared constraints."
31                .to_string(),
32        )
33    }
34}
35
36/// Closure-backed [`InteractionHandler`] for SDK callers and tests.
37pub struct FnInteractionHandler<F>(pub F);
38
39#[async_trait::async_trait]
40impl<F> InteractionHandler for FnInteractionHandler<F>
41where
42    F: Fn(&str) -> Result<String> + Send + Sync + 'static,
43{
44    async fn ask_user(&self, question: &str) -> Result<String> {
45        (self.0)(question)
46    }
47}
48
49/// Async closure-backed [`InteractionHandler`] for SDK callers and tests.
50pub struct AsyncFnInteractionHandler<F>(pub F);
51
52#[async_trait::async_trait]
53impl<F, Fut> InteractionHandler for AsyncFnInteractionHandler<F>
54where
55    F: Fn(String) -> Fut + Send + Sync + 'static,
56    Fut: Future<Output = Result<String>> + Send + 'static,
57{
58    async fn ask_user(&self, question: &str) -> Result<String> {
59        (self.0)(question.to_string()).await
60    }
61}
62
63pub(crate) struct AskUserHandler;
64
65#[async_trait::async_trait]
66impl CandidateToolHandler for AskUserHandler {
67    async fn apply(
68        &self,
69        workspace: &CandidateWorkspace,
70        call: &ProviderToolCall,
71        _entry: &ToolEntry,
72    ) -> Result<EffectOutcome> {
73        let question = call
74            .arguments
75            .get("question")
76            .and_then(serde_json::Value::as_str)
77            .context("ask_user requires a string 'question' argument")?;
78        let output = workspace.interaction_handler().ask_user(question).await?;
79        Ok(EffectOutcome {
80            output,
81            mutated: false,
82            completed: true,
83        })
84    }
85}
86
87#[derive(Deserialize)]
88struct PersptScriptsConfig {
89    #[serde(default)]
90    scripts: BTreeMap<String, toml::Value>,
91}
92
93pub(crate) struct RunRepoScriptHandler;
94
95#[async_trait::async_trait]
96impl CandidateToolHandler for RunRepoScriptHandler {
97    async fn apply(
98        &self,
99        workspace: &CandidateWorkspace,
100        call: &ProviderToolCall,
101        _entry: &ToolEntry,
102    ) -> Result<EffectOutcome> {
103        let name = call
104            .arguments
105            .get("name")
106            .and_then(serde_json::Value::as_str)
107            .context("run_repo_script requires a string 'name' argument")?;
108        let Some(raw_bytes) = workspace.overlay_bytes("perspt.toml")? else {
109            return Ok(tool_failure("perspt.toml not found in candidate workspace"));
110        };
111        let raw_toml = match String::from_utf8(raw_bytes) {
112            Ok(text) => text,
113            Err(_) => return Ok(tool_failure("perspt.toml is not valid UTF-8")),
114        };
115        let config: PersptScriptsConfig = match toml::from_str(&raw_toml) {
116            Ok(parsed) => parsed,
117            Err(err) => return Ok(tool_failure(&format!("invalid perspt.toml: {err}"))),
118        };
119        let Some(spec) = config.scripts.get(name) else {
120            return Ok(tool_failure(&format!(
121                "script {name:?} is not declared under [scripts] in perspt.toml"
122            )));
123        };
124        let Some(command) = script_command(spec) else {
125            return Ok(tool_failure(&format!(
126                "script {name:?} must be a command string or non-empty string array"
127            )));
128        };
129        let exec = workspace.run_governed_verifier(&command, None).await?;
130        if exec.success {
131            Ok(EffectOutcome {
132                output: exec.output,
133                mutated: false,
134                completed: true,
135            })
136        } else {
137            Ok(tool_failure(&format!(
138                "script {name:?} exited non-zero:\n{}",
139                exec.output
140            )))
141        }
142    }
143}
144
145fn script_command(value: &toml::Value) -> Option<String> {
146    match value {
147        toml::Value::String(cmd) => (!cmd.trim().is_empty()).then(|| cmd.clone()),
148        toml::Value::Array(items) if !items.is_empty() => {
149            let parts: Option<Vec<&str>> = items.iter().map(toml::Value::as_str).collect();
150            parts.map(shell_words::join)
151        }
152        _ => None,
153    }
154}
155
156fn tool_failure(message: &str) -> EffectOutcome {
157    EffectOutcome {
158        output: format!("tool failed: {message}"),
159        mutated: false,
160        completed: true,
161    }
162}
163
164pub(crate) fn register(registry: &mut CandidateHandlerRegistry) {
165    registry
166        .register("ask_user", Arc::new(AskUserHandler))
167        .expect("builtin ask_user registration must succeed");
168    registry
169        .register("run_repo_script", Arc::new(RunRepoScriptHandler))
170        .expect("builtin run_repo_script registration must succeed");
171}