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