use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
use crate::tools::traits::{ToolExecutor, ToolResult};
pub const FINISH_TASK_TOOL_NAME: &str = "finish_task";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FinishStatus {
Completed,
Failed,
Cancelled,
}
impl std::fmt::Display for FinishStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
FinishStatus::Completed => "completed",
FinishStatus::Failed => "failed",
FinishStatus::Cancelled => "cancelled",
};
write!(f, "{s}")
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct ChangeEntry {
pub file: Option<String>,
pub lines_added: Option<i64>,
pub lines_removed: Option<i64>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct FinishTaskArgs {
pub status: FinishStatus,
pub summary: String,
#[serde(default)]
pub changes: Vec<ChangeEntry>,
pub tests_run: Option<i64>,
pub tests_passed: Option<i64>,
}
pub fn render_finish_summary(args: &FinishTaskArgs) -> String {
let mut out = format!("Task {}: {}", args.status, args.summary);
if !args.changes.is_empty() {
out.push_str("\nChanges:");
for change in &args.changes {
let file = change.file.as_deref().unwrap_or("<unknown file>");
let added = change.lines_added.unwrap_or(0);
let removed = change.lines_removed.unwrap_or(0);
out.push_str(&format!("\n - {file} (+{added}/-{removed})"));
}
}
match (args.tests_run, args.tests_passed) {
(Some(run), Some(passed)) => out.push_str(&format!("\nTests: {passed}/{run} passed")),
(Some(run), None) => out.push_str(&format!("\nTests run: {run}")),
(None, Some(passed)) => out.push_str(&format!("\nTests passed: {passed}")),
(None, None) => {}
}
out
}
#[derive(Debug, Default)]
pub struct FinishTaskTool;
impl FinishTaskTool {
pub fn new() -> Self {
Self
}
}
#[async_trait]
impl ToolExecutor for FinishTaskTool {
fn name(&self) -> &str {
FINISH_TASK_TOOL_NAME
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": FINISH_TASK_TOOL_NAME,
"description": "Signal task completion with a structured, machine-readable report. Call this exactly once when the task is finished (successfully, failed, or cancelled) instead of ending your turn with prose.",
"parameters": {
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": ["completed", "failed", "cancelled"],
"description": "Outcome of the task."
},
"summary": {
"type": "string",
"description": "Free-text summary of what was done."
},
"changes": {
"type": "array",
"description": "Files changed, if any.",
"items": {
"type": "object",
"properties": {
"file": { "type": "string" },
"lines_added": { "type": "integer" },
"lines_removed": { "type": "integer" }
}
}
},
"tests_run": {
"type": "integer",
"description": "Number of tests run, if applicable."
},
"tests_passed": {
"type": "integer",
"description": "Number of tests that passed, if applicable."
}
},
"required": ["status", "summary"],
"additionalProperties": false
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
match serde_json::from_value::<FinishTaskArgs>(args) {
Ok(parsed) => ToolResult::ok(render_finish_summary(&parsed)),
Err(e) => ToolResult::err(format!(
"finish_task arguments did not match the expected shape ({e}). \
'status' must be one of completed/failed/cancelled and 'summary' must be a string."
)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn name_matches_constant() {
let tool = FinishTaskTool::new();
assert_eq!(tool.name(), FINISH_TASK_TOOL_NAME);
assert_eq!(FINISH_TASK_TOOL_NAME, "finish_task");
}
#[test]
fn schema_has_required_fields_and_enum() {
let schema = FinishTaskTool::new().schema();
let params = &schema["function"]["parameters"];
let required: Vec<&str> = params["required"]
.as_array()
.expect("required array")
.iter()
.filter_map(|v| v.as_str())
.collect();
assert_eq!(required, vec!["status", "summary"]);
let enum_values: Vec<&str> = params["properties"]["status"]["enum"]
.as_array()
.expect("enum array")
.iter()
.filter_map(|v| v.as_str())
.collect();
assert_eq!(enum_values, vec!["completed", "failed", "cancelled"]);
assert_eq!(params["additionalProperties"], json!(false));
}
#[test]
fn status_display_and_roundtrip() {
assert_eq!(FinishStatus::Completed.to_string(), "completed");
assert_eq!(FinishStatus::Failed.to_string(), "failed");
assert_eq!(FinishStatus::Cancelled.to_string(), "cancelled");
}
#[test]
fn render_includes_status_and_summary() {
let args = FinishTaskArgs {
status: FinishStatus::Completed,
summary: "did the thing".to_string(),
changes: vec![],
tests_run: None,
tests_passed: None,
};
let rendered = render_finish_summary(&args);
assert_eq!(rendered, "Task completed: did the thing");
}
#[tokio::test]
async fn execute_valid_args_renders_summary() {
let tool = FinishTaskTool::new();
let result = tool
.execute(json!({"status": "completed", "summary": "wrote the feature"}))
.await;
assert!(!result.is_error());
assert_eq!(result.content(), "Task completed: wrote the feature");
}
#[tokio::test]
async fn execute_with_changes_and_tests_renders_all_fields() {
let tool = FinishTaskTool::new();
let result = tool
.execute(json!({
"status": "completed",
"summary": "added the widget",
"changes": [
{"file": "src/widget.rs", "lines_added": 42, "lines_removed": 3},
{"file": "src/lib.rs", "lines_added": 1, "lines_removed": 0}
],
"tests_run": 12,
"tests_passed": 12
}))
.await;
assert!(!result.is_error());
let content = result.content();
assert!(content.contains("Task completed: added the widget"));
assert!(content.contains("src/widget.rs (+42/-3)"));
assert!(content.contains("src/lib.rs (+1/-0)"));
assert!(content.contains("Tests: 12/12 passed"));
}
#[tokio::test]
async fn execute_with_only_tests_run_renders_run_count() {
let tool = FinishTaskTool::new();
let result = tool
.execute(json!({
"status": "failed",
"summary": "tests did not all pass",
"tests_run": 5
}))
.await;
assert!(!result.is_error());
assert!(result.content().contains("Tests run: 5"));
assert!(!result.content().contains("passed\n"));
}
#[tokio::test]
async fn execute_bypassing_schema_validation_is_recoverable() {
let tool = FinishTaskTool::new();
let result = tool.execute(json!({"status": "completed"})).await;
assert!(result.is_error());
assert!(!result.is_fatal(), "must be recoverable, not fatal");
assert!(
result
.content()
.contains("did not match the expected shape")
);
}
#[tokio::test]
async fn execute_unknown_status_bypassing_schema_validation_is_recoverable() {
let tool = FinishTaskTool::new();
let result = tool
.execute(json!({"status": "in_progress", "summary": "still going"}))
.await;
assert!(result.is_error());
assert!(!result.is_fatal());
}
}