Skip to main content

taskfast_cli/cmd/
bid.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast bid` — read + mutate operations on bids.
3//!
4//! Read (am-4yr): `list` over `GET /agents/me/bids`.
5//! Worker mutations (am-e3u.8): `create` + `cancel`. No EIP-712 — API key
6//! alone authorizes both (`BidRequest { price, pitch? }`; withdraw has no
7//! body). Poster mutations (am-e3u.11): `accept` + `reject`. No signing —
8//! am-4w2 shipped the two-phase deferred-escrow flow, so the API call
9//! just locks the bid; the poster signs the on-chain escrow later via the
10//! web UI URL surfaced in the response.
11
12use clap::{Args, Parser, Subcommand, ValueEnum};
13use serde_json::json;
14use uuid::Uuid;
15
16use super::{CmdError, CmdResult, Ctx};
17use crate::envelope::Envelope;
18
19use taskfast_client::api::types::{
20    BidDetailStatus, BidRequest, RejectBidBody, RejectBidBodyReason,
21};
22use taskfast_client::map_api_error;
23use taskfast_client::TaskFastClient;
24
25#[derive(Debug, Subcommand)]
26pub enum Command {
27    /// GET /agents/me/bids — bids placed by this agent.
28    List(ListArgs),
29    /// Worker: place a bid on an open task.
30    Create(CreateArgs),
31    /// Worker: withdraw a pending bid.
32    Cancel(CancelArgs),
33    /// Poster: accept a bid (two-phase; poster signs escrow later via web UI).
34    Accept(AcceptArgs),
35    /// Poster: reject a pending bid with an optional reason.
36    Reject(RejectArgs),
37}
38
39#[derive(Debug, Parser)]
40pub struct ListArgs {
41    /// Opaque pagination cursor from a previous response's `next_cursor`.
42    #[arg(long)]
43    pub cursor: Option<String>,
44
45    /// Max items per page. Defaults to 20 — small enough to keep the
46    /// envelope readable in a typical worker loop tick.
47    #[arg(long, default_value_t = 20)]
48    pub limit: i64,
49
50    /// Filter results by bid status. Applied client-side — the
51    /// `getAgentBids` endpoint has no status query param, so filtering here
52    /// avoids a jq/grep fallback at call sites without forcing a spec change.
53    #[arg(long)]
54    pub status: Option<BidStatusFilter>,
55}
56
57/// clap-friendly mirror of the generated `BidDetailStatus` enum. Lives here
58/// rather than in the codegen because `ValueEnum` needs `Clone + PartialEq`
59/// (which the generated enum already has) plus kebab-case — it's cheaper to
60/// maintain a 4-variant mirror than to teach clap about foreign serde attrs.
61#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
62pub enum BidStatusFilter {
63    Pending,
64    Accepted,
65    Rejected,
66    Withdrawn,
67}
68
69impl BidStatusFilter {
70    fn matches(self, status: BidDetailStatus) -> bool {
71        matches!(
72            (self, status),
73            (Self::Pending, BidDetailStatus::Pending)
74                | (Self::Accepted, BidDetailStatus::Accepted)
75                | (Self::Rejected, BidDetailStatus::Rejected)
76                | (Self::Withdrawn, BidDetailStatus::Withdrawn)
77        )
78    }
79}
80
81#[derive(Debug, Parser)]
82pub struct CreateArgs {
83    /// Target task UUID.
84    pub task_id: String,
85
86    /// Offered price as a decimal string, e.g. `75.00`. Pass-through; server
87    /// owns the canonical decimal parsing + min/max policy.
88    #[arg(long)]
89    pub price: String,
90
91    /// Optional pitch — free-form "why this agent fits" blurb shown to the poster.
92    #[arg(long)]
93    pub pitch: Option<String>,
94}
95
96#[derive(Debug, Parser)]
97pub struct CancelArgs {
98    /// Bid UUID to withdraw. Must belong to this agent and be `:pending`.
99    pub id: String,
100}
101
102#[derive(Debug, Args)]
103pub struct AcceptArgs {
104    /// Bid UUID to accept. Caller must be the poster of the parent task.
105    pub id: String,
106}
107
108#[derive(Debug, Args)]
109pub struct RejectArgs {
110    /// Bid UUID to reject. Caller must be the poster; bid must be `:pending`.
111    pub id: String,
112    /// Optional reason (<=500 chars), stored on the bid.
113    #[arg(long)]
114    pub reason: Option<String>,
115}
116
117pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
118    match cmd {
119        Command::List(args) => list(ctx, args).await,
120        Command::Create(args) => create(ctx, args).await,
121        Command::Cancel(args) => cancel(ctx, args).await,
122        Command::Accept(args) => accept(ctx, args).await,
123        Command::Reject(args) => reject(ctx, args).await,
124    }
125}
126
127async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
128    let client = ctx.client()?;
129    let data = list_bids(&client, &args).await?;
130    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
131}
132
133async fn list_bids(
134    client: &TaskFastClient,
135    args: &ListArgs,
136) -> Result<serde_json::Value, CmdError> {
137    let resp = match client
138        .inner()
139        .get_agent_bids(
140            args.cursor.as_deref(),
141            taskfast_client::page_limit(args.limit),
142        )
143        .await
144    {
145        Ok(v) => v.into_inner(),
146        Err(e) => return Err(map_api_error(e).await.into()),
147    };
148    // Client-side filter: server has no status query param on /agents/me/bids.
149    // Bids lacking a status field (shouldn't happen on real responses) are
150    // dropped when a filter is supplied so we don't silently pass them through.
151    // `meta` describes the *server* page pre-filter; `filtered_count` is added
152    // when a filter applies so consumers can distinguish page semantics from
153    // the filtered result count.
154    let filter_applied = args.status.is_some();
155    let bids = match args.status {
156        Some(f) => resp
157            .data
158            .into_iter()
159            .filter(|b| b.status.is_some_and(|s| f.matches(s)))
160            .collect::<Vec<_>>(),
161        None => resp.data,
162    };
163    if filter_applied {
164        Ok(json!({
165            "bids": bids,
166            "meta": resp.meta,
167            "filtered_count": bids.len(),
168        }))
169    } else {
170        Ok(json!({
171            "bids": bids,
172            "meta": resp.meta,
173        }))
174    }
175}
176
177async fn create(ctx: &Ctx, args: CreateArgs) -> CmdResult {
178    // Fail on bad UUID before any HTTP so typos never cost a round-trip.
179    let task_id = Uuid::parse_str(&args.task_id)
180        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
181    // Reject empty/whitespace-only price upfront. Server owns the decimal
182    // validation — we just make sure we're not sending something obviously
183    // malformed that would waste a 422.
184    if args.price.trim().is_empty() {
185        return Err(CmdError::Usage("--price must not be empty".into()));
186    }
187
188    if ctx.dry_run {
189        return Ok(Envelope::success(
190            ctx.environment,
191            ctx.dry_run,
192            json!({
193                "action": "would_create_bid",
194                "task_id": task_id.to_string(),
195                "price": args.price,
196                "pitch": args.pitch,
197            }),
198        ));
199    }
200
201    let client = ctx.client()?;
202    let body = BidRequest {
203        price: args.price.clone(),
204        pitch: args.pitch.clone(),
205    };
206    let bid = match client.inner().create_bid(&task_id, &body).await {
207        Ok(v) => v.into_inner(),
208        Err(e) => return Err(map_api_error(e).await.into()),
209    };
210    Ok(Envelope::success(
211        ctx.environment,
212        ctx.dry_run,
213        json!({ "bid": bid }),
214    ))
215}
216
217async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
218    let bid_id = Uuid::parse_str(&args.id)
219        .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
220
221    if ctx.dry_run {
222        return Ok(Envelope::success(
223            ctx.environment,
224            ctx.dry_run,
225            json!({
226                "action": "would_cancel_bid",
227                "bid_id": bid_id.to_string(),
228            }),
229        ));
230    }
231
232    let client = ctx.client()?;
233    let bid = match client.inner().withdraw_bid(&bid_id).await {
234        Ok(v) => v.into_inner(),
235        Err(e) => return Err(map_api_error(e).await.into()),
236    };
237    Ok(Envelope::success(
238        ctx.environment,
239        ctx.dry_run,
240        json!({ "bid": bid }),
241    ))
242}
243
244async fn accept(ctx: &Ctx, args: AcceptArgs) -> CmdResult {
245    let bid_id = Uuid::parse_str(&args.id)
246        .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
247
248    if ctx.dry_run {
249        return Ok(Envelope::success(
250            ctx.environment,
251            ctx.dry_run,
252            json!({
253                "action": "would_accept_bid",
254                "bid_id": bid_id.to_string(),
255            }),
256        ));
257    }
258
259    let client = ctx.client()?;
260    let resp = match client.inner().accept_bid(&bid_id).await {
261        Ok(v) => v.into_inner(),
262        Err(e) => return Err(map_api_error(e).await.into()),
263    };
264    Ok(Envelope::success(
265        ctx.environment,
266        ctx.dry_run,
267        json!({ "bid": resp }),
268    ))
269}
270
271async fn reject(ctx: &Ctx, args: RejectArgs) -> CmdResult {
272    let bid_id = Uuid::parse_str(&args.id)
273        .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
274
275    // Refuse an explicit but empty --reason pre-HTTP so orchestrators see a
276    // never-retry Usage error, not a server-side 4xx. Mirrors task dispute.
277    let reason_field = match args.reason.as_deref() {
278        Some(s) if s.trim().is_empty() => {
279            return Err(CmdError::Usage(
280                "--reason must not be empty when passed".into(),
281            ));
282        }
283        Some(s) => Some(
284            RejectBidBodyReason::try_from(s)
285                .map_err(|e| CmdError::Usage(format!("--reason invalid: {e}")))?,
286        ),
287        None => None,
288    };
289
290    if ctx.dry_run {
291        return Ok(Envelope::success(
292            ctx.environment,
293            ctx.dry_run,
294            json!({
295                "action": "would_reject_bid",
296                "bid_id": bid_id.to_string(),
297                "reason": args.reason,
298            }),
299        ));
300    }
301
302    let client = ctx.client()?;
303    let body = RejectBidBody {
304        reason: reason_field,
305    };
306    let resp = match client.inner().reject_bid(&bid_id, &body).await {
307        Ok(v) => v.into_inner(),
308        Err(e) => return Err(map_api_error(e).await.into()),
309    };
310    Ok(Envelope::success(
311        ctx.environment,
312        ctx.dry_run,
313        json!({ "bid": resp }),
314    ))
315}