use std::path::PathBuf;
use clap::{Parser, Subcommand, ValueEnum};
use serde_json::json;
use uuid::Uuid;
use super::{CmdError, CmdResult, Ctx};
use crate::envelope::Envelope;
use taskfast_client::api::types::{
CompletionSubmission, DisputeRequest, ListMyTasksStatus, ReassignTaskBody, TaskEditRequest,
};
use taskfast_client::map_api_error;
use taskfast_client::TaskFastClient;
#[derive(Debug, Subcommand)]
pub enum Command {
List(ListArgs),
Get(GetArgs),
Submit(SubmitArgs),
Approve(ApproveArgs),
Dispute(DisputeArgs),
Cancel(CancelArgs),
Claim(IdOnlyArgs),
Refuse(IdOnlyArgs),
Remedy(SubmitArgs),
Concede(IdOnlyArgs),
Abort(IdOnlyArgs),
Bids(BidsArgs),
Reassign(ReassignArgs),
Reopen(IdOnlyArgs),
Open(IdOnlyArgs),
Edit(EditArgs),
}
#[derive(Debug, Parser)]
pub struct ReassignArgs {
pub id: String,
#[arg(long)]
pub agent_id: String,
}
#[derive(Debug, Parser)]
pub struct EditArgs {
pub id: String,
#[arg(long)]
pub title: Option<String>,
#[arg(long)]
pub description: Option<String>,
#[arg(long)]
pub budget_max: Option<String>,
#[arg(long)]
pub review_window_hours: Option<i64>,
#[arg(long)]
pub remedy_window_hours: Option<i64>,
}
#[derive(Debug, Parser)]
pub struct ListArgs {
#[arg(long, default_value = "mine")]
pub kind: ListKind,
#[arg(long)]
pub status: Option<TaskStatus>,
#[arg(long)]
pub cursor: Option<String>,
#[arg(long, default_value_t = 20)]
pub limit: i64,
}
#[derive(Debug, Parser)]
pub struct GetArgs {
pub id: String,
}
#[derive(Debug, Parser)]
pub struct IdOnlyArgs {
pub id: String,
}
#[derive(Debug, Parser)]
pub struct BidsArgs {
pub id: String,
#[arg(long)]
pub cursor: Option<String>,
#[arg(long, default_value_t = 20)]
pub limit: i64,
}
#[derive(Debug, Parser)]
pub struct ApproveArgs {
pub id: String,
}
#[derive(Debug, Parser)]
pub struct DisputeArgs {
pub id: String,
#[arg(long)]
pub reason: String,
}
#[derive(Debug, Parser)]
pub struct CancelArgs {
pub id: String,
}
#[derive(Debug, Parser)]
pub struct SubmitArgs {
pub id: String,
#[arg(long)]
pub summary: String,
#[arg(long)]
pub artifact: Vec<PathBuf>,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ListKind {
Mine,
Queue,
Posted,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum TaskStatus {
InProgress,
UnderReview,
Disputed,
Remedied,
Assigned,
All,
}
impl From<TaskStatus> for ListMyTasksStatus {
fn from(s: TaskStatus) -> Self {
match s {
TaskStatus::InProgress => Self::InProgress,
TaskStatus::UnderReview => Self::UnderReview,
TaskStatus::Disputed => Self::Disputed,
TaskStatus::Remedied => Self::Remedied,
TaskStatus::Assigned => Self::Assigned,
TaskStatus::All => Self::All,
}
}
}
pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
match cmd {
Command::List(args) => list(ctx, args).await,
Command::Get(args) => get(ctx, args).await,
Command::Submit(args) => submit(ctx, args, SubmitKind::Completion).await,
Command::Approve(args) => approve(ctx, args).await,
Command::Dispute(args) => dispute(ctx, args).await,
Command::Cancel(args) => cancel(ctx, args).await,
Command::Claim(args) => claim(ctx, args).await,
Command::Refuse(args) => refuse(ctx, args).await,
Command::Remedy(args) => submit(ctx, args, SubmitKind::Remedy).await,
Command::Concede(args) => concede(ctx, args).await,
Command::Abort(args) => abort(ctx, args).await,
Command::Bids(args) => bids(ctx, args).await,
Command::Reassign(args) => reassign(ctx, args).await,
Command::Reopen(args) => reopen(ctx, args).await,
Command::Open(args) => open(ctx, args).await,
Command::Edit(args) => edit(ctx, args).await,
}
}
#[derive(Debug, Clone, Copy)]
enum SubmitKind {
Completion,
Remedy,
}
async fn approve(ctx: &Ctx, args: ApproveArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_approve",
"task_id": task_id.to_string(),
}),
));
}
let client = ctx.client()?;
let resp = match client.inner().approve_task(&task_id).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"task_id": resp.task_id,
"status": resp.status,
}),
))
}
async fn dispute(ctx: &Ctx, args: DisputeArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if args.reason.trim().is_empty() {
return Err(CmdError::Usage("--reason must not be empty".into()));
}
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_dispute",
"task_id": task_id.to_string(),
"reason": args.reason,
}),
));
}
let client = ctx.client()?;
let body = DisputeRequest {
reason: args.reason.clone(),
};
let resp = match client.inner().raise_dispute(&task_id, &body).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"task_id": resp.task_id,
"status": resp.status,
"dispute": resp.dispute,
"message": resp.message,
}),
))
}
async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_cancel",
"task_id": task_id.to_string(),
}),
));
}
let client = ctx.client()?;
let resp = match client.inner().cancel_task(&task_id).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"id": resp.id,
"status": resp.status,
}),
))
}
async fn submit(ctx: &Ctx, args: SubmitArgs, kind: SubmitKind) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
let resolved: Vec<ResolvedArtifact> = args
.artifact
.iter()
.map(|p| ResolvedArtifact::from_path(p))
.collect::<Result<_, _>>()?;
let action = match kind {
SubmitKind::Completion => "would_submit",
SubmitKind::Remedy => "would_remedy",
};
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": action,
"task_id": task_id.to_string(),
"summary": args.summary,
"artifacts": resolved.iter().map(|r| r.display_path()).collect::<Vec<_>>(),
}),
));
}
let client = ctx.client()?;
let mut artifact_ids: Vec<uuid::Uuid> = Vec::with_capacity(resolved.len());
let mut uploaded_meta: Vec<serde_json::Value> = Vec::with_capacity(resolved.len());
for r in resolved {
let bytes = std::fs::read(&r.path)
.map_err(|e| CmdError::Usage(format!("read {}: {e}", r.path.display())))?;
let artifact = client
.upload_artifact(&task_id, r.filename.clone(), r.content_type.clone(), bytes)
.await
.map_err(CmdError::from)?;
artifact_ids.push(artifact.id);
uploaded_meta.push(json!({
"id": artifact.id,
"filename": artifact.filename,
"content_type": artifact.content_type,
"size_bytes": artifact.size_bytes,
}));
}
let body = CompletionSubmission {
summary: args.summary.clone(),
artifact_ids: artifact_ids.clone(),
metadata: serde_json::Map::new(),
};
let result = match kind {
SubmitKind::Completion => match client.inner().submit_completion(&task_id, &body).await {
Ok(v) => {
serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
}
Err(e) => return Err(map_api_error(e).await.into()),
},
SubmitKind::Remedy => match client.inner().submit_remedy(&task_id, &body).await {
Ok(v) => {
serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
}
Err(e) => return Err(map_api_error(e).await.into()),
},
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"task_id": task_id.to_string(),
"artifacts": uploaded_meta,
"submission": result,
}),
))
}
async fn claim(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "action": "would_claim", "task_id": task_id.to_string() }),
));
}
let client = ctx.client()?;
let resp = match client.inner().claim_task(&task_id).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "claim": resp }),
))
}
async fn refuse(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "action": "would_refuse", "task_id": task_id.to_string() }),
));
}
let client = ctx.client()?;
let resp = match client.inner().refuse_task(&task_id).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "refuse": resp }),
))
}
async fn concede(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "action": "would_concede", "task_id": task_id.to_string() }),
));
}
let client = ctx.client()?;
let resp = match client.inner().concede_dispute(&task_id).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "concede": resp }),
))
}
async fn abort(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "action": "would_abort", "task_id": task_id.to_string() }),
));
}
let client = ctx.client()?;
let resp = match client.inner().abort_task(&task_id).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "abort": resp }),
))
}
async fn reassign(ctx: &Ctx, args: ReassignArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
let agent_id = Uuid::parse_str(&args.agent_id)
.map_err(|e| CmdError::Usage(format!("--agent-id must be a UUID: {e}")))?;
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_reassign",
"task_id": task_id.to_string(),
"agent_id": agent_id.to_string(),
}),
));
}
let client = ctx.client()?;
let body = ReassignTaskBody { agent_id };
let resp = match client.inner().reassign_task(&task_id, &body).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "reassign": resp }),
))
}
async fn reopen(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "action": "would_reopen", "task_id": task_id.to_string() }),
));
}
let client = ctx.client()?;
let resp = match client.inner().reopen_task(&task_id).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "reopen": resp }),
))
}
async fn open(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "action": "would_open", "task_id": task_id.to_string() }),
));
}
let client = ctx.client()?;
let resp = match client.inner().open_task(&task_id).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "open": resp }),
))
}
async fn edit(ctx: &Ctx, args: EditArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
let any_change = args.title.is_some()
|| args.description.is_some()
|| args.budget_max.is_some()
|| args.review_window_hours.is_some()
|| args.remedy_window_hours.is_some();
if !any_change {
return Err(CmdError::Usage(
"edit requires at least one of --title/--description/--budget-max/--review-window-hours/--remedy-window-hours".into(),
));
}
let body = TaskEditRequest {
title: args.title.clone(),
description: args.description.clone(),
budget_max: args.budget_max.clone(),
review_window_hours: args.review_window_hours,
remedy_window_hours: args.remedy_window_hours,
completion_criteria: Vec::new(),
};
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_edit",
"task_id": task_id.to_string(),
"patch": body,
}),
));
}
let client = ctx.client()?;
let resp = match client.inner().edit_task(&task_id, &body).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "task": resp }),
))
}
async fn bids(ctx: &Ctx, args: BidsArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
let client = ctx.client()?;
let resp = match client
.inner()
.list_task_bids(
&task_id,
args.cursor.as_deref(),
taskfast_client::page_limit(args.limit),
)
.await
{
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"task_id": task_id.to_string(),
"bids": resp.data,
"meta": resp.meta,
}),
))
}
struct ResolvedArtifact {
path: PathBuf,
filename: String,
content_type: String,
}
impl ResolvedArtifact {
fn from_path(p: &std::path::Path) -> Result<Self, CmdError> {
if !p.exists() {
return Err(CmdError::Usage(format!(
"artifact file not found: {}",
p.display()
)));
}
let filename = p
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| {
CmdError::Usage(format!("artifact path has no filename: {}", p.display()))
})?
.to_string();
let ext = p
.extension()
.and_then(|s| s.to_str())
.map(|s| s.to_ascii_lowercase())
.unwrap_or_default();
let content_type = content_type_for_ext(&ext).to_string();
Ok(Self {
path: p.to_path_buf(),
filename,
content_type,
})
}
fn display_path(&self) -> String {
self.path.display().to_string()
}
}
pub(super) fn content_type_for_ext(ext: &str) -> &'static str {
match ext {
"txt" => "text/plain",
"md" | "markdown" => "text/plain",
"csv" => "text/csv",
"json" => "application/json",
"xml" => "application/xml",
"pdf" => "application/pdf",
"doc" => "application/msword",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"svg" => "image/svg+xml",
"zip" => "application/zip",
"tar" => "application/x-tar",
"gz" => "application/gzip",
"html" | "htm" => "text/html",
"css" => "text/css",
"js" => "application/javascript",
_ => "application/octet-stream",
}
}
async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
if args.status.is_some() && !matches!(args.kind, ListKind::Mine) {
return Err(CmdError::Usage(
"--status is only valid with --kind=mine".into(),
));
}
let client = ctx.client()?;
let data = match args.kind {
ListKind::Mine => list_mine(&client, &args).await?,
ListKind::Queue => list_queue(&client, &args).await?,
ListKind::Posted => list_posted(&client, &args).await?,
};
Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
}
const ACTIVE_STATUSES: &[&str] = &[
"assigned",
"in_progress",
"under_review",
"disputed",
"remedied",
];
const ACTIVE_FETCH_MULTIPLIER: i64 = 2;
async fn list_mine(
client: &TaskFastClient,
args: &ListArgs,
) -> Result<serde_json::Value, CmdError> {
let apply_active_filter = args.status.is_none();
let status = args.status.map(ListMyTasksStatus::from);
let fetch_limit = if apply_active_filter {
args.limit.saturating_mul(ACTIVE_FETCH_MULTIPLIER)
} else {
args.limit
};
let resp = match client
.inner()
.list_my_tasks(
args.cursor.as_deref(),
taskfast_client::page_limit(fetch_limit),
status,
)
.await
{
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
let tasks = if apply_active_filter {
let limit_usize = usize::try_from(args.limit.max(0)).unwrap_or(usize::MAX);
resp.data
.into_iter()
.filter(|t| ACTIVE_STATUSES.contains(&t.status.as_str()))
.take(limit_usize)
.collect::<Vec<_>>()
} else {
resp.data
};
Ok(json!({
"kind": "mine",
"tasks": tasks,
"meta": resp.meta,
}))
}
async fn list_queue(
client: &TaskFastClient,
args: &ListArgs,
) -> Result<serde_json::Value, CmdError> {
let resp = match client
.inner()
.get_agent_queue(
args.cursor.as_deref(),
taskfast_client::page_limit(args.limit),
)
.await
{
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(json!({
"kind": "queue",
"tasks": resp.data,
"meta": resp.meta,
}))
}
async fn list_posted(
client: &TaskFastClient,
args: &ListArgs,
) -> Result<serde_json::Value, CmdError> {
let resp = match client
.inner()
.get_agent_posted_tasks(
args.cursor.as_deref(),
taskfast_client::page_limit(args.limit),
)
.await
{
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(json!({
"kind": "posted",
"tasks": resp.data,
"meta": resp.meta,
}))
}
async fn get(ctx: &Ctx, args: GetArgs) -> CmdResult {
let id = Uuid::parse_str(&args.id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
let client = ctx.client()?;
let task = match client.inner().get_task(&id).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "task": task }),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn task_status_maps_to_generated_enum() {
for (ours, theirs) in [
(TaskStatus::InProgress, ListMyTasksStatus::InProgress),
(TaskStatus::UnderReview, ListMyTasksStatus::UnderReview),
(TaskStatus::Disputed, ListMyTasksStatus::Disputed),
(TaskStatus::Remedied, ListMyTasksStatus::Remedied),
(TaskStatus::Assigned, ListMyTasksStatus::Assigned),
(TaskStatus::All, ListMyTasksStatus::All),
] {
assert_eq!(
ListMyTasksStatus::from(ours).to_string(),
theirs.to_string()
);
}
}
#[test]
fn content_type_maps_markdown_to_text_plain() {
assert_eq!(content_type_for_ext("md"), "text/plain");
assert_eq!(content_type_for_ext("markdown"), "text/plain");
assert_eq!(content_type_for_ext("json"), "application/json");
assert_eq!(
content_type_for_ext("unknownext"),
"application/octet-stream"
);
}
}