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    BidRequest, GetAgentBidsStatusItem, 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. Forwarded to the `getAgentBids`
51    /// `status` query param — the server owns the filtering (taskfast#941).
52    #[arg(long)]
53    pub status: Option<BidStatusFilter>,
54}
55
56/// clap-friendly mirror of the generated `GetAgentBidsStatusItem` enum. Lives
57/// here rather than in the codegen because `ValueEnum` needs kebab-case
58/// variants — cheaper to maintain a thin mirror than to teach clap about
59/// foreign serde attrs.
60#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
61pub enum BidStatusFilter {
62    Pending,
63    AcceptedPendingEscrow,
64    Accepted,
65    Rejected,
66    Withdrawn,
67}
68
69impl From<BidStatusFilter> for GetAgentBidsStatusItem {
70    fn from(f: BidStatusFilter) -> Self {
71        match f {
72            BidStatusFilter::Pending => Self::Pending,
73            BidStatusFilter::AcceptedPendingEscrow => Self::AcceptedPendingEscrow,
74            BidStatusFilter::Accepted => Self::Accepted,
75            BidStatusFilter::Rejected => Self::Rejected,
76            BidStatusFilter::Withdrawn => Self::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    // Server owns the status filtering (taskfast#941): forward `--status` as
138    // the `status` query param and return the page as-is. No client-side
139    // post-filter, so `meta` describes the result set directly.
140    let status = args.status.map(|f| vec![GetAgentBidsStatusItem::from(f)]);
141    let resp = match client
142        .inner()
143        .get_agent_bids(
144            None,
145            args.cursor.as_deref(),
146            taskfast_client::page_limit(args.limit),
147            status.as_ref(),
148        )
149        .await
150    {
151        Ok(v) => v.into_inner(),
152        Err(e) => return Err(map_api_error(e).await.into()),
153    };
154    Ok(json!({
155        "bids": resp.data,
156        "meta": resp.meta,
157    }))
158}
159
160async fn create(ctx: &Ctx, args: CreateArgs) -> CmdResult {
161    // Fail on bad UUID before any HTTP so typos never cost a round-trip.
162    let task_id = Uuid::parse_str(&args.task_id)
163        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
164    // Reject empty/whitespace-only price upfront. Server owns the decimal
165    // validation — we just make sure we're not sending something obviously
166    // malformed that would waste a 422.
167    if args.price.trim().is_empty() {
168        return Err(CmdError::Usage("--price must not be empty".into()));
169    }
170
171    if ctx.dry_run {
172        return Ok(Envelope::success(
173            ctx.environment,
174            ctx.dry_run,
175            json!({
176                "action": "would_create_bid",
177                "task_id": task_id.to_string(),
178                "price": args.price,
179                "pitch": args.pitch,
180            }),
181        ));
182    }
183
184    let client = ctx.client()?;
185    let body = BidRequest {
186        price: args.price.clone(),
187        pitch: args.pitch.clone(),
188    };
189    let bid = match client.inner().create_bid(&task_id, &body).await {
190        Ok(v) => v.into_inner(),
191        Err(e) => return Err(map_api_error(e).await.into()),
192    };
193    Ok(Envelope::success(
194        ctx.environment,
195        ctx.dry_run,
196        json!({ "bid": bid }),
197    ))
198}
199
200async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
201    let bid_id = Uuid::parse_str(&args.id)
202        .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
203
204    if ctx.dry_run {
205        return Ok(Envelope::success(
206            ctx.environment,
207            ctx.dry_run,
208            json!({
209                "action": "would_cancel_bid",
210                "bid_id": bid_id.to_string(),
211            }),
212        ));
213    }
214
215    let client = ctx.client()?;
216    let bid = match client.inner().withdraw_bid(&bid_id).await {
217        Ok(v) => v.into_inner(),
218        Err(e) => return Err(map_api_error(e).await.into()),
219    };
220    Ok(Envelope::success(
221        ctx.environment,
222        ctx.dry_run,
223        json!({ "bid": bid }),
224    ))
225}
226
227async fn accept(ctx: &Ctx, args: AcceptArgs) -> CmdResult {
228    let bid_id = Uuid::parse_str(&args.id)
229        .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
230
231    if ctx.dry_run {
232        return Ok(Envelope::success(
233            ctx.environment,
234            ctx.dry_run,
235            json!({
236                "action": "would_accept_bid",
237                "bid_id": bid_id.to_string(),
238            }),
239        ));
240    }
241
242    let client = ctx.client()?;
243    let resp = match client.inner().accept_bid(&bid_id).await {
244        Ok(v) => v.into_inner(),
245        Err(e) => return Err(map_api_error(e).await.into()),
246    };
247    Ok(Envelope::success(
248        ctx.environment,
249        ctx.dry_run,
250        json!({ "bid": resp }),
251    ))
252}
253
254async fn reject(ctx: &Ctx, args: RejectArgs) -> CmdResult {
255    let bid_id = Uuid::parse_str(&args.id)
256        .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
257
258    // Refuse an explicit but empty --reason pre-HTTP so orchestrators see a
259    // never-retry Usage error, not a server-side 4xx. Mirrors task dispute.
260    let reason_field = match args.reason.as_deref() {
261        Some(s) if s.trim().is_empty() => {
262            return Err(CmdError::Usage(
263                "--reason must not be empty when passed".into(),
264            ));
265        }
266        Some(s) => Some(
267            RejectBidBodyReason::try_from(s)
268                .map_err(|e| CmdError::Usage(format!("--reason invalid: {e}")))?,
269        ),
270        None => None,
271    };
272
273    if ctx.dry_run {
274        return Ok(Envelope::success(
275            ctx.environment,
276            ctx.dry_run,
277            json!({
278                "action": "would_reject_bid",
279                "bid_id": bid_id.to_string(),
280                "reason": args.reason,
281            }),
282        ));
283    }
284
285    let client = ctx.client()?;
286    let body = RejectBidBody {
287        reason: reason_field,
288    };
289    let resp = match client.inner().reject_bid(&bid_id, &body).await {
290        Ok(v) => v.into_inner(),
291        Err(e) => return Err(map_api_error(e).await.into()),
292    };
293    Ok(Envelope::success(
294        ctx.environment,
295        ctx.dry_run,
296        json!({ "bid": resp }),
297    ))
298}