1use std::path::PathBuf;
24
25use alloy_primitives::{Address, Bytes};
26use clap::Parser;
27use serde_json::json;
28use uuid::Uuid;
29
30use super::wallet_args::{decode_0x_bytes, resolve_proxy_rpc_url, sign_and_send_submission_fee};
31use super::{validate_override_rpc_url, CmdError, CmdResult, Ctx};
32use crate::envelope::Envelope;
33
34use taskfast_client::api::types::{
35 CompletionCriterionInput, TaskDraftPrepareRequest, TaskDraftPrepareRequestAssignmentType,
36 TaskDraftPrepareRequestPickupDeadlineHours, TaskDraftSubmitRequest,
37 TaskDraftSubmitRequestSignature,
38};
39use taskfast_client::map_api_error;
40
41#[derive(Debug, Parser)]
42pub struct Args {
43 #[arg(long)]
45 pub title: String,
46
47 #[arg(long)]
50 pub description: String,
51
52 #[arg(long)]
55 pub budget: Option<String>,
56
57 #[arg(long, value_delimiter = ',')]
59 pub capabilities: Vec<String>,
60
61 #[arg(long = "criterion")]
67 pub criteria: Vec<String>,
68
69 #[arg(long)]
74 pub criteria_file: Option<PathBuf>,
75
76 #[arg(long)]
80 pub pickup_deadline_hours: i64,
81
82 #[arg(long)]
84 pub execution_deadline: Option<String>,
85
86 #[arg(long)]
91 pub venue: Option<String>,
92
93 #[arg(long, default_value = "open")]
96 pub assignment_type: AssignmentType,
97
98 #[arg(long)]
100 pub direct_agent_id: Option<String>,
101
102 #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
105 pub wallet_address: Option<String>,
106
107 #[arg(long, env = "TEMPO_KEY_SOURCE")]
111 pub keystore: Option<String>,
112
113 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
117 pub wallet_password_file: Option<PathBuf>,
118
119 #[arg(long, env = "TEMPO_RPC_URL")]
122 pub rpc_url: Option<String>,
123
124 #[arg(long)]
129 pub yes: bool,
130}
131
132#[derive(Debug, Clone, Copy, clap::ValueEnum)]
133pub enum AssignmentType {
134 Open,
135 Direct,
136}
137
138impl AssignmentType {
139 fn as_str(self) -> &'static str {
140 match self {
141 Self::Open => "open",
142 Self::Direct => "direct",
143 }
144 }
145}
146
147impl From<AssignmentType> for TaskDraftPrepareRequestAssignmentType {
148 fn from(a: AssignmentType) -> Self {
149 match a {
150 AssignmentType::Open => Self::Open,
151 AssignmentType::Direct => Self::Direct,
152 }
153 }
154}
155
156fn pickup_hours_to_wire(
161 hours: i64,
162) -> Result<TaskDraftPrepareRequestPickupDeadlineHours, CmdError> {
163 TaskDraftPrepareRequestPickupDeadlineHours::try_from(hours).map_err(|_| CmdError::Validation {
164 code: "pickup_deadline_invalid".into(),
165 message: format!(
166 "pickup window of {hours}h is not an allowed bidding window per the \
167 API contract; the server owns the valid set (422 pickup_deadline_required)"
168 ),
169 })
170}
171
172pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
173 let pre = preflight(ctx, &args)?;
177
178 let prep_body = TaskDraftPrepareRequest {
179 assignment_type: args.assignment_type.into(),
180 budget_max: args.budget.clone(),
181 completion_criteria: pre.completion_criteria,
182 description: args.description.clone(),
183 direct_agent_id: pre.direct_agent_id,
184 execution_deadline: pre.execution_deadline,
185 pickup_deadline_hours: pre.pickup_hours,
186 poster_wallet_address: pre
187 .wallet_address
188 .parse()
189 .map_err(|e| CmdError::Usage(format!("--wallet-address rejected by schema: {e}")))?,
190 required_capabilities: args.capabilities.clone(),
191 settlement_venue: args.venue.clone(),
192 title: args.title.clone(),
193 };
194
195 if ctx.dry_run {
198 let rpc_url = match pre.rpc_url_override {
199 Some(override_url) => override_url,
200 None => format!(
201 "{}/rpc/{}",
202 ctx.base_url().trim_end_matches('/'),
203 ctx.environment.network().as_str()
204 ),
205 };
206 return Ok(Envelope::success(
207 ctx.environment,
208 ctx.dry_run,
209 json!({
210 "action": "would_post",
211 "draft_id": serde_json::Value::Null,
212 "title": args.title,
213 "assignment_type": args.assignment_type.as_str(),
214 "budget_max": args.budget,
215 "settlement_venue": args.venue,
216 "required_capabilities": args.capabilities,
217 "completion_criteria_count": prep_body.completion_criteria.len(),
218 "rpc_url": rpc_url,
219 "wallet_address": pre.wallet_address,
220 }),
221 ));
222 }
223
224 let client = ctx.client()?;
225
226 let rpc_url = match pre.rpc_url_override {
231 Some(override_url) => override_url,
232 None => resolve_proxy_rpc_url(&client, ctx).await?,
233 };
234
235 let prep = match client.inner().prepare_task_draft(&prep_body).await {
237 Ok(r) => r.into_inner(),
238 Err(e) => return Err(map_api_error(e).await.into()),
239 };
240
241 let calldata = decode_0x_bytes(&prep.payload_to_sign)
242 .map_err(|e| CmdError::Server(format!("server returned invalid payload_to_sign: {e}")))?;
243
244 let keystore_path = super::wallet_args::resolve_keystore_path(
247 args.keystore.as_deref(),
248 ctx.keystore_path.as_deref(),
249 );
250 let signer = super::wallet_args::load_signer_and_validate(
251 keystore_path.as_deref(),
252 args.wallet_password_file.as_deref(),
253 Some(&pre.wallet_address),
254 "submission fee",
255 )?;
256
257 let tx_hash = sign_and_send_submission_fee(
258 ctx,
259 &client,
260 &rpc_url,
261 keystore_path,
262 signer,
263 &prep.token_address,
264 Bytes::from(calldata),
265 )
266 .await?;
267 let tx_hash_hex = format!("{tx_hash:#x}");
268
269 let signature: TaskDraftSubmitRequestSignature = tx_hash_hex
272 .parse()
273 .map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?;
274 let submit_body = TaskDraftSubmitRequest { signature };
275 let submitted = match client
276 .inner()
277 .submit_task_draft(&prep.draft_id, &submit_body)
278 .await
279 {
280 Ok(r) => r.into_inner(),
281 Err(e) => return Err(map_api_error(e).await.into()),
282 };
283
284 let blocked = submitted.status == "blocked_on_submission_fee_debt";
292 if blocked {
293 eprintln!(
296 "taskfast: task {} parked at blocked_on_submission_fee_debt — \
297 submission-fee transfer confirming on-chain; it opens automatically \
298 once confirmed. Poll `taskfast task get {}`.",
299 submitted.id, submitted.id
300 );
301 }
302 let message = blocked.then(|| {
303 "Task created. Submission fee transaction is pending on-chain \
304 confirmation before the task becomes actionable."
305 .to_string()
306 });
307
308 Ok(Envelope::success(
309 ctx.environment,
310 ctx.dry_run,
311 json!({
312 "task_id": submitted.id,
313 "draft_id": prep.draft_id,
314 "submission_fee_tx_hash": tx_hash_hex,
315 "status": submitted.status,
316 "submission_fee_status": submitted.submission_fee_status,
317 "message": message,
318 }),
319 ))
320}
321
322struct Preflight {
325 wallet_address: String,
326 direct_agent_id: Option<Uuid>,
327 execution_deadline: Option<chrono::DateTime<chrono::Utc>>,
328 completion_criteria: Vec<CompletionCriterionInput>,
329 pickup_hours: TaskDraftPrepareRequestPickupDeadlineHours,
330 rpc_url_override: Option<String>,
333}
334
335fn problem_text(e: &CmdError) -> String {
339 match e {
340 CmdError::Usage(m) => m.clone(),
341 CmdError::Validation { message, .. } => message.clone(),
342 other => other.to_string(),
343 }
344}
345
346fn preflight(ctx: &Ctx, args: &Args) -> Result<Preflight, CmdError> {
357 let mut problems: Vec<String> = Vec::new();
358 if args.description.trim().is_empty() {
363 problems.push(
364 "--description must not be empty (server requires a non-blank description)".into(),
365 );
366 }
367
368 if let Err(e) = ctx.enforce_budget_gate(args.budget.as_deref(), args.yes, "post a task") {
369 problems.push(problem_text(&e));
370 }
371
372 let wallet_address = match args
373 .wallet_address
374 .as_deref()
375 .or(ctx.wallet_address.as_deref())
376 {
377 Some(w) => match w.parse::<Address>() {
378 Ok(_) => Some(w.to_string()),
379 Err(e) => {
380 problems.push(format!("--wallet-address is not a valid EVM address: {e}"));
381 None
382 }
383 },
384 None => {
385 problems.push(
386 "--wallet-address (or TEMPO_WALLET_ADDRESS, or wallet_address in config) required to post a task".into(),
387 );
388 None
389 }
390 };
391
392 let direct_agent_id = match (args.assignment_type, args.direct_agent_id.as_deref()) {
393 (AssignmentType::Direct, Some(s)) => match Uuid::parse_str(s) {
394 Ok(u) => Some(Some(u)),
395 Err(e) => {
396 problems.push(format!("--direct-agent-id not a UUID: {e}"));
397 None
398 }
399 },
400 (AssignmentType::Direct, None) => {
401 problems.push("--assignment-type=direct requires --direct-agent-id".into());
402 None
403 }
404 (AssignmentType::Open, _) => Some(None),
405 };
406
407 let execution_deadline =
408 match parse_iso_opt(args.execution_deadline.as_deref(), "--execution-deadline") {
409 Ok(v) => Some(v),
410 Err(e) => {
411 problems.push(problem_text(&e));
412 None
413 }
414 };
415
416 let completion_criteria = match resolve_criteria(args.criteria_file.as_deref(), &args.criteria)
417 {
418 Ok(v) => Some(v),
419 Err(e) => {
420 problems.push(problem_text(&e));
421 None
422 }
423 };
424
425 let pickup_hours = match pickup_hours_to_wire(args.pickup_deadline_hours) {
426 Ok(w) => Some(w),
427 Err(e) => {
428 problems.push(problem_text(&e));
429 None
430 }
431 };
432
433 let rpc_url_override = match args.rpc_url.as_deref() {
434 Some(u) => match validate_override_rpc_url(
435 u,
436 ctx.environment.network(),
437 ctx.allow_custom_endpoints,
438 ) {
439 Ok(u) => Some(Some(u.to_string())),
440 Err(e) => {
441 problems.push(problem_text(&e));
442 None
443 }
444 },
445 None => Some(None),
446 };
447
448 if !problems.is_empty() {
449 let n = problems.len();
450 let list = problems
451 .iter()
452 .enumerate()
453 .map(|(i, p)| format!(" {}. {p}", i + 1))
454 .collect::<Vec<_>>()
455 .join("\n");
456 return Err(CmdError::Usage(format!(
457 "post preflight found {n} problem{}:\n{list}",
458 if n == 1 { "" } else { "s" }
459 )));
460 }
461
462 Ok(Preflight {
463 wallet_address: wallet_address.expect("no problems ⇒ wallet present"),
464 direct_agent_id: direct_agent_id.expect("no problems ⇒ direct id resolved"),
465 execution_deadline: execution_deadline.expect("no problems ⇒ deadline resolved"),
466 completion_criteria: completion_criteria.expect("no problems ⇒ criteria resolved"),
467 pickup_hours: pickup_hours.expect("no problems ⇒ pickup hours valid"),
468 rpc_url_override: rpc_url_override.expect("no problems ⇒ rpc override resolved"),
469 })
470}
471
472fn resolve_criteria(
479 file: Option<&std::path::Path>,
480 inline: &[String],
481) -> Result<Vec<CompletionCriterionInput>, CmdError> {
482 let mut out = Vec::with_capacity(inline.len());
483 if let Some(path) = file {
484 let raw = std::fs::read_to_string(path).map_err(|e| {
485 CmdError::Usage(format!("read --criteria-file {}: {e}", path.display()))
486 })?;
487 let parsed: Vec<CompletionCriterionInput> = serde_json::from_str(&raw).map_err(|e| {
488 CmdError::Usage(format!(
489 "--criteria-file {} is not a JSON array of CompletionCriterionInput: {e}",
490 path.display()
491 ))
492 })?;
493 out.extend(parsed);
494 }
495 for (i, raw) in inline.iter().enumerate() {
496 let one: CompletionCriterionInput = serde_json::from_str(raw)
497 .map_err(|e| CmdError::Usage(format!("--criterion[{i}] not valid JSON: {e}")))?;
498 out.push(one);
499 }
500 Ok(out)
501}
502
503fn parse_iso_opt(
504 s: Option<&str>,
505 flag: &str,
506) -> Result<Option<chrono::DateTime<chrono::Utc>>, CmdError> {
507 match s {
508 None => Ok(None),
509 Some(raw) => chrono::DateTime::parse_from_rfc3339(raw)
510 .map(|d| Some(d.with_timezone(&chrono::Utc)))
511 .map_err(|e| CmdError::Usage(format!("{flag} not a valid RFC3339 timestamp: {e}"))),
512 }
513}
514
515#[cfg(test)]
516mod tests {
517 use super::*;
518 use crate::Network;
519
520 #[test]
521 fn validate_override_rejects_without_opt_in() {
522 let err = validate_override_rpc_url("https://mallory.example", Network::Mainnet, false)
523 .expect_err("override without opt-in must be refused");
524 match err {
525 CmdError::Usage(msg) => {
526 assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
527 }
528 other => panic!("expected Usage, got {other:?}"),
529 }
530 }
531
532 #[test]
533 fn validate_override_accepts_with_opt_in() {
534 validate_override_rpc_url("https://my-node.example", Network::Testnet, true)
535 .expect("opt-in bypasses the guard");
536 }
537
538 #[test]
539 fn validate_override_rejects_plain_http_on_mainnet() {
540 let err = validate_override_rpc_url("http://my-node.example", Network::Mainnet, true)
541 .expect_err("plain-http on mainnet is always refused (except loopback)");
542 assert!(matches!(err, CmdError::Usage(msg) if msg.contains("plain-HTTP")));
543 }
544
545 #[test]
546 fn validate_override_allows_plain_http_loopback_on_mainnet() {
547 validate_override_rpc_url("http://127.0.0.1:8545", Network::Mainnet, true)
548 .expect("loopback bypasses mainnet-HTTPS check");
549 validate_override_rpc_url("http://localhost:8545", Network::Mainnet, true)
550 .expect("loopback bypasses mainnet-HTTPS check");
551 }
552
553 #[test]
554 fn validate_override_allows_plain_http_on_testnet() {
555 validate_override_rpc_url("http://my-testnet.example", Network::Testnet, true)
556 .expect("testnet does not enforce HTTPS");
557 }
558
559 #[test]
560 fn pickup_hours_conversion_follows_api_contract() {
561 let err = pickup_hours_to_wire(3).expect_err("3 is outside the contract set");
565 assert!(matches!(err, CmdError::Validation { .. }));
566 let wire = pickup_hours_to_wire(24).expect("24 is contract-valid");
568 assert_eq!(i64::from(wire), 24);
569 }
570
571 #[test]
572 fn network_name_matches_config_map_keys() {
573 assert_eq!(Network::Mainnet.as_str(), "mainnet");
576 assert_eq!(Network::Testnet.as_str(), "testnet");
577 }
578}