1use std::path::{Path, PathBuf};
59
60use clap::Parser;
61use serde_json::json;
62
63use super::{CmdError, CmdResult, Ctx};
64use crate::config::Config;
65use crate::envelope::Envelope;
66
67use alloy_signer_local::PrivateKeySigner;
68use taskfast_agent::bootstrap::{create_agent_headless, get_readiness, validate_auth};
69use taskfast_agent::faucet::{request_testnet_funds, FaucetDrop};
70use taskfast_agent::keystore;
71use taskfast_agent::wallet;
72use taskfast_client::api::types::{AgentCreateRequest, AgentReadiness};
73use taskfast_client::TaskFastClient;
74
75const WALLET_STATUS_COMPLETE: &str = "complete";
79
80#[derive(Debug, Parser)]
81#[allow(clippy::struct_excessive_bools)]
85pub struct Args {
86 #[arg(long, conflicts_with = "generate_wallet")]
89 pub wallet_address: Option<String>,
90
91 #[arg(long)]
94 pub generate_wallet: bool,
95
96 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
101 pub wallet_password_file: Option<PathBuf>,
102
103 #[arg(long)]
106 pub keystore_path: Option<PathBuf>,
107
108 #[arg(long)]
111 pub skip_wallet: bool,
112
113 #[arg(long)]
119 pub fund: bool,
120
121 #[arg(long, env = "TASKFAST_HUMAN_API_KEY")]
127 pub human_api_key: Option<String>,
128
129 #[arg(long, default_value = "taskfast-agent")]
131 pub agent_name: String,
132
133 #[arg(long, default_value = "Headless agent registered via taskfast init")]
135 pub agent_description: String,
136
137 #[arg(long = "agent-capability", value_name = "CAP")]
141 pub agent_capabilities: Vec<String>,
142
143 #[arg(long)]
149 pub webhook_url: Option<String>,
150
151 #[arg(long)]
156 pub webhook_secret_file: Option<PathBuf>,
157
158 #[arg(long = "webhook-event", value_name = "EVENT")]
165 pub webhook_events: Vec<String>,
166
167 #[arg(long)]
172 pub no_default_events: bool,
173
174 #[arg(long, env = "TASKFAST_NO_INTERACTIVE")]
178 pub no_interactive: bool,
179
180 #[arg(skip)]
186 pub inline_wallet_password: Option<String>,
187}
188
189pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
190 let interactive = !args.no_interactive && crate::cmd::init_tui::is_interactive();
191 run_with_prompter(
192 ctx,
193 args,
194 &crate::cmd::init_tui::DialoguerPrompter,
195 interactive,
196 )
197 .await
198}
199
200pub async fn run_with_prompter<P: crate::cmd::init_tui::Prompter>(
205 ctx: &Ctx,
206 mut args: Args,
207 prompter: &P,
208 interactive: bool,
209) -> CmdResult {
210 let cfg_path = ctx.config_path.clone();
211
212 let mut cfg = Config::load(&cfg_path)?;
216
217 let (api_key, agent_outcome) = match resolve_api_key(ctx, &cfg) {
226 Ok(k) => (k, AgentOutcome::PreExisting),
227 Err(CmdError::MissingApiKey) => {
228 let pat = resolve_pat(ctx, &args, interactive, prompter).await?;
229 let minted = mint_agent(ctx, &args, &pat).await?;
230 match minted {
231 MintedAgent::DryRun { ref intent } => {
232 return Ok(Envelope::success(
233 ctx.environment,
234 ctx.dry_run,
235 build_dry_run_mint_envelope(&cfg_path, intent),
236 ));
237 }
238 MintedAgent::Live { ref api_key, .. } => {
239 (api_key.clone(), AgentOutcome::Minted(minted))
240 }
241 }
242 }
243 Err(e) => return Err(e),
244 };
245
246 if interactive
253 && matches!(agent_outcome, AgentOutcome::Minted(_))
254 && args.wallet_address.is_none()
255 && !args.generate_wallet
256 && !args.skip_wallet
257 {
258 apply_wallet_mode_prompt(&mut args, prompter)?;
259 }
260
261 let effective_ctx = Ctx {
262 api_key: Some(api_key.clone()),
263 ..ctx.clone()
264 };
265 let client = effective_ctx.client()?;
266
267 let profile = match validate_auth(&client).await {
272 Ok(p) => p,
273 Err(taskfast_client::Error::Auth(msg))
274 if matches!(agent_outcome, AgentOutcome::PreExisting) =>
275 {
276 return Err(CmdError::Auth(stale_key_hint(
277 &msg, &cfg_path, &cfg, ctx, &args,
278 )));
279 }
280 Err(e) => return Err(CmdError::from(e)),
281 };
282 assert_active(&profile)?;
283 if !ctx.dry_run {
288 super::enforce_server_network_invariant(&effective_ctx, &client).await?;
289 }
290 let readiness = get_readiness(&client).await.map_err(CmdError::from)?;
291
292 let wallet_outcome = if args.skip_wallet {
294 WalletOutcome::Skipped
295 } else if readiness.checks.wallet.status == WALLET_STATUS_COMPLETE
296 && args.wallet_address.is_none()
297 && !args.generate_wallet
298 {
299 WalletOutcome::AlreadyConfigured
302 } else {
303 provision_wallet(&client, &args, ctx.dry_run).await?
304 };
305
306 cfg.environment = Some(ctx.environment);
311 cfg.api_key = Some(api_key.clone());
312 if let Some(addr) = wallet_outcome.address() {
313 cfg.wallet_address = Some(addr.to_string());
314 }
315 if let Some(path) = wallet_outcome.keystore_path() {
316 cfg.keystore_path = Some(path.to_path_buf());
317 }
318 if let AgentOutcome::Minted(MintedAgent::Live { id: Some(id), .. }) = &agent_outcome {
319 cfg.agent_id = Some(id.clone());
320 }
321 if let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) {
322 cfg.webhook_url = Some(url.to_string());
323 }
324 if let Some(path) = args.webhook_secret_file.as_ref() {
325 cfg.webhook_secret_path = Some(path.clone());
326 }
327
328 let config_written = if ctx.dry_run {
329 false
330 } else {
331 cfg.save(&cfg_path)?;
332 true
333 };
334
335 let faucet_outcome = maybe_request_faucet(
347 &args,
348 ctx.environment.network(),
349 &wallet_outcome,
350 ctx.dry_run,
351 )
352 .await;
353
354 let webhook_outcome = maybe_configure_webhook(&client, &args, ctx.dry_run).await;
359
360 let final_readiness = get_readiness(&client).await.map_err(CmdError::from)?;
363
364 warn_if_unfunded(
368 &client,
369 ctx,
370 cfg.wallet_address.as_deref(),
371 &faucet_outcome,
372 &final_readiness,
373 )
374 .await;
375
376 let data = build_envelope_data(
377 &cfg_path,
378 config_written,
379 &wallet_outcome,
380 &agent_outcome,
381 &final_readiness,
382 &faucet_outcome,
383 &webhook_outcome,
384 ctx.dry_run,
385 );
386 Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
387}
388
389enum AgentOutcome {
394 PreExisting,
395 Minted(MintedAgent),
396}
397
398enum MintedAgent {
402 Live {
403 api_key: String,
404 id: Option<String>,
405 name: Option<String>,
406 },
407 DryRun {
408 intent: MintIntent,
409 },
410}
411
412struct MintIntent {
413 name: String,
414 description: String,
415 capabilities: Vec<String>,
416}
417
418async fn resolve_pat<P: crate::cmd::init_tui::Prompter>(
423 ctx: &Ctx,
424 args: &Args,
425 interactive: bool,
426 prompter: &P,
427) -> Result<String, CmdError> {
428 if let Some(p) = args.human_api_key.as_deref().filter(|s| !s.is_empty()) {
429 return Ok(p.to_string());
430 }
431 if !interactive {
432 return Err(CmdError::MissingApiKey);
433 }
434 let accounts_url = crate::accounts_url(ctx.base_url());
435 let pat = prompter
436 .pat(&accounts_url)
437 .map_err(|e| CmdError::Usage(format!("PAT prompt failed: {e}")))?;
438 let pat_client = TaskFastClient::from_api_key(ctx.base_url(), &pat).map_err(CmdError::from)?;
442 let profile = pat_client.get_user_profile().await.ok().flatten();
443 eprintln!("{}", crate::cmd::init_tui::greeting(profile.as_ref()));
444 Ok(pat)
445}
446
447fn apply_wallet_mode_prompt<P: crate::cmd::init_tui::Prompter>(
451 args: &mut Args,
452 prompter: &P,
453) -> Result<(), CmdError> {
454 use crate::cmd::init_tui::WalletMode;
455 let mode = prompter
456 .wallet_mode()
457 .map_err(|e| CmdError::Usage(format!("wallet-mode prompt failed: {e}")))?;
458 match mode {
459 WalletMode::Byow => {
460 let addr = prompter
461 .wallet_address()
462 .map_err(|e| CmdError::Usage(format!("wallet-address prompt failed: {e}")))?;
463 args.wallet_address = Some(addr.trim().to_string());
464 }
465 WalletMode::Generate => {
466 args.generate_wallet = true;
467 let pw = prompter
468 .wallet_password()
469 .map_err(|e| CmdError::Usage(format!("password prompt failed: {e}")))?;
470 args.inline_wallet_password = Some(pw);
471 }
472 WalletMode::Skip => {
473 args.skip_wallet = true;
474 }
475 }
476 Ok(())
477}
478
479async fn mint_agent(ctx: &Ctx, args: &Args, pat: &str) -> Result<MintedAgent, CmdError> {
480 if pat.is_empty() {
481 return Err(CmdError::Usage("PAT is empty".into()));
482 }
483
484 let capabilities = if args.agent_capabilities.is_empty() {
485 vec!["general".to_string()]
486 } else {
487 args.agent_capabilities.clone()
488 };
489
490 if ctx.dry_run {
491 return Ok(MintedAgent::DryRun {
492 intent: MintIntent {
493 name: args.agent_name.clone(),
494 description: args.agent_description.clone(),
495 capabilities,
496 },
497 });
498 }
499
500 let pat_client = TaskFastClient::from_api_key(ctx.base_url(), pat).map_err(CmdError::from)?;
501 let body = AgentCreateRequest {
502 owner_id: None,
503 name: args.agent_name.clone(),
504 description: args.agent_description.clone(),
505 capabilities,
506 rate: None,
507 max_task_budget: None,
508 daily_spend_limit: None,
509 payout_method: None,
510 payment_method: None,
511 tempo_wallet_address: None,
512 };
513 let resp = create_agent_headless(&pat_client, &body)
514 .await
515 .map_err(CmdError::from)?;
516 let api_key = resp
517 .api_key
518 .clone()
519 .ok_or_else(|| CmdError::Server("POST /agents returned no api_key despite 201".into()))?;
520 Ok(MintedAgent::Live {
521 api_key,
522 id: resp.id.map(|u| u.to_string()),
523 name: resp.name.clone(),
524 })
525}
526
527fn build_dry_run_mint_envelope(cfg_path: &Path, intent: &MintIntent) -> serde_json::Value {
528 json!({
529 "agent": {
530 "action": "would_mint",
531 "name": intent.name,
532 "description": intent.description,
533 "capabilities": intent.capabilities,
534 },
535 "config_file": {
536 "path": cfg_path.display().to_string(),
537 "written": false,
538 "would_write": true,
539 },
540 "ready_to_work": false,
541 })
542}
543
544fn resolve_api_key(ctx: &Ctx, cfg: &Config) -> Result<String, CmdError> {
553 if let Some(k) = ctx.api_key.as_deref() {
554 if !k.is_empty() {
555 return Ok(k.to_string());
556 }
557 }
558 if let Some(k) = cfg.api_key.as_deref() {
559 if !k.is_empty() {
560 return Ok(k.to_string());
561 }
562 }
563 Err(CmdError::MissingApiKey)
564}
565
566fn stale_key_hint(msg: &str, cfg_path: &Path, cfg: &Config, ctx: &Ctx, args: &Args) -> String {
570 let source = if cfg.api_key.as_deref().is_some_and(|k| !k.is_empty()) {
571 format!("config file {}", cfg_path.display())
572 } else if ctx.api_key.is_some() {
573 "--api-key flag or TASKFAST_API_KEY env".to_string()
574 } else {
575 "unknown".to_string()
576 };
577 let had_pat = args.human_api_key.is_some();
578 let pat_note = if had_pat {
579 "\n note: --human-api-key was provided but ignored because an existing api_key was found; \
580 the PAT mints a new agent only when no api_key is resolvable."
581 } else {
582 ""
583 };
584 format!(
585 "{msg}\n hint: agent api_key rejected — likely stale (agent deleted or key rotated).\n \
586 source: {source}\n fix: delete {path} (and unset TASKFAST_API_KEY if set), then re-run \
587 `taskfast --env {env} init --human-api-key <tf_user_...>` to mint a fresh agent.{pat_note}",
588 path = cfg_path.display(),
589 env = ctx.environment.as_str(),
590 )
591}
592
593fn assert_active(profile: &taskfast_client::api::types::AgentProfile) -> Result<(), CmdError> {
594 match profile.status.as_deref() {
595 Some("active") => Ok(()),
596 Some(other) => Err(CmdError::Validation {
597 code: "agent_not_active".into(),
598 message: format!("agent status is {other}; owner must reactivate"),
599 }),
600 None => Err(CmdError::Server(
601 "GET /agents/me returned no status field".into(),
602 )),
603 }
604}
605
606enum WalletOutcome {
608 AlreadyConfigured,
610 ByoRegistered { address: String },
612 Generated {
614 address: String,
615 keystore_path: PathBuf,
616 },
617 DryRunGenerated { address: String },
619 Skipped,
621}
622
623impl WalletOutcome {
624 fn address(&self) -> Option<&str> {
625 match self {
626 Self::ByoRegistered { address }
627 | Self::Generated { address, .. }
628 | Self::DryRunGenerated { address } => Some(address),
629 Self::AlreadyConfigured | Self::Skipped => None,
630 }
631 }
632
633 fn keystore_path(&self) -> Option<&Path> {
634 match self {
635 Self::Generated { keystore_path, .. } => Some(keystore_path),
636 _ => None,
637 }
638 }
639
640 fn tag(&self) -> &'static str {
641 match self {
642 Self::AlreadyConfigured => "already_configured",
643 Self::ByoRegistered { .. } => "byo_registered",
644 Self::Generated { .. } => "generated",
645 Self::DryRunGenerated { .. } => "dry_run_generated",
646 Self::Skipped => "skipped",
647 }
648 }
649}
650
651async fn provision_wallet(
652 client: &TaskFastClient,
653 args: &Args,
654 dry_run: bool,
655) -> Result<WalletOutcome, CmdError> {
656 if let Some(addr) = args.wallet_address.as_deref() {
657 if dry_run {
658 return Ok(WalletOutcome::Skipped);
659 }
660 return match wallet::register_wallet(client, addr)
661 .await
662 .map_err(CmdError::from)?
663 {
664 wallet::WalletRegistration::Configured(_) => Ok(WalletOutcome::ByoRegistered {
665 address: addr.to_string(),
666 }),
667 wallet::WalletRegistration::AlreadyConfigured => Err(CmdError::Validation {
668 code: "wallet_already_configured".into(),
669 message: "agent already has a tempo wallet configured".into(),
670 }),
671 };
672 }
673 if !args.generate_wallet {
674 return Err(CmdError::Usage(
675 "pass --wallet-address <0x...> or --generate-wallet (or --skip-wallet to defer)".into(),
676 ));
677 }
678
679 let signer = wallet::generate_signer();
680 let address = format!("0x{}", hex::encode(signer.address().as_slice()));
681
682 if dry_run {
683 return Ok(WalletOutcome::DryRunGenerated { address });
686 }
687
688 let password = resolve_wallet_password(args)?;
689 let keystore_path = persist_keystore(&signer, args, &password)?;
690 match wallet::register_wallet(client, &address).await {
691 Ok(wallet::WalletRegistration::Configured(_)) => Ok(WalletOutcome::Generated {
692 address,
693 keystore_path,
694 }),
695 Ok(wallet::WalletRegistration::AlreadyConfigured) => {
696 let _ = std::fs::remove_file(&keystore_path);
697 Err(CmdError::Validation {
698 code: "wallet_already_configured".into(),
699 message: "agent already has a tempo wallet configured".into(),
700 })
701 }
702 Err(e) => {
703 let _ = std::fs::remove_file(&keystore_path);
704 Err(CmdError::from(e))
705 }
706 }
707}
708
709fn resolve_wallet_password(args: &Args) -> Result<zeroize::Zeroizing<String>, CmdError> {
710 super::wallet_args::resolve_password_with_inline_and_missing_hint(
711 args.inline_wallet_password.as_deref(),
712 args.wallet_password_file.as_deref(),
713 "--generate-wallet requires --wallet-password-file or TASKFAST_WALLET_PASSWORD",
714 )
715}
716
717fn persist_keystore(
718 signer: &PrivateKeySigner,
719 args: &Args,
720 password: &str,
721) -> Result<PathBuf, CmdError> {
722 let path = match &args.keystore_path {
723 Some(p) => p.clone(),
724 None => keystore::default_keyfile_path(signer.address()).map_err(CmdError::from)?,
725 };
726 keystore::save_signer(signer, &path, password).map_err(CmdError::from)
727}
728
729enum FaucetOutcome {
734 Skipped { reason: &'static str },
735 Requested { drops: Vec<FaucetDrop> },
736 Failed { error: String },
737}
738
739async fn maybe_request_faucet(
740 args: &Args,
741 network: crate::Network,
742 wallet: &WalletOutcome,
743 dry_run: bool,
744) -> FaucetOutcome {
745 if dry_run {
746 return FaucetOutcome::Skipped { reason: "dry_run" };
747 }
748 if !args.fund {
749 return FaucetOutcome::Skipped {
750 reason: "fund_flag_not_set",
751 };
752 }
753 if !matches!(network, crate::Network::Testnet) {
754 return FaucetOutcome::Skipped { reason: "mainnet" };
755 }
756 let address = match wallet {
757 WalletOutcome::Generated { address, .. } => address.clone(),
758 WalletOutcome::ByoRegistered { address } => address.clone(),
759 _ => {
760 return FaucetOutcome::Skipped {
761 reason: "no_fresh_wallet",
762 };
763 }
764 };
765 let http = reqwest::Client::new();
766 match request_testnet_funds(&http, &address).await {
767 Ok(drops) => FaucetOutcome::Requested { drops },
768 Err(e) => FaucetOutcome::Failed {
769 error: e.to_string(),
770 },
771 }
772}
773
774fn parse_wei_hex(s: Option<&str>) -> Option<u128> {
777 let s = s?.trim();
778 let hex = s.strip_prefix("0x").unwrap_or(s);
779 if hex.is_empty() {
780 return None;
781 }
782 u128::from_str_radix(hex, 16).ok()
783}
784
785fn build_funding_warning(
791 faucet_error: Option<&str>,
792 balance_wei: Option<u128>,
793 address: &str,
794 rpc_url: Option<&str>,
795 funding_hint: Option<&str>,
796) -> Option<String> {
797 let zero_balance = balance_wei.is_some_and(|b| b == 0);
798 if faucet_error.is_none() && !zero_balance {
799 return None;
800 }
801 let mut lines = Vec::new();
802 match (faucet_error, zero_balance) {
803 (Some(err), _) => lines.push(format!(
804 "WARNING: testnet faucet funding failed (--fund): {err}"
805 )),
806 (None, true) => lines.push(format!(
807 "WARNING: wallet {address} balance is zero at the end of init"
808 )),
809 (None, false) => return None,
810 }
811 lines.push(
812 " the next on-chain command will fail until the wallet is funded. \
813 manual fallback:"
814 .to_string(),
815 );
816 if let Some(rpc) = rpc_url {
817 lines.push(format!(
818 " cast rpc tempo_fundAddress '[\"{address}\"]' --raw --rpc-url {rpc}"
819 ));
820 }
821 lines.push(" or fund at https://wallet.tempo.xyz".to_string());
822 if let Some(hint) = funding_hint {
823 lines.push(format!(" server funding hint: {hint}"));
824 }
825 Some(lines.join("\n"))
826}
827
828async fn warn_if_unfunded(
837 client: &TaskFastClient,
838 ctx: &Ctx,
839 wallet_address: Option<&str>,
840 faucet: &FaucetOutcome,
841 readiness: &AgentReadiness,
842) {
843 if ctx.dry_run {
844 return;
845 }
846 if !matches!(ctx.environment.network(), crate::Network::Testnet) {
847 return;
848 }
849 let Some(address) = wallet_address else {
850 return;
851 };
852 let faucet_error = match faucet {
853 FaucetOutcome::Failed { error } => Some(error.as_str()),
854 _ => None,
855 };
856 let balance_wei = match client.inner().get_wallet_balance().await {
857 Ok(resp) => parse_wei_hex(resp.into_inner().available_balance.as_deref()),
858 Err(e) => {
859 tracing::warn!(error = %e, "init: balance check unavailable; skipping zero-balance warning");
860 None
861 }
862 };
863 if build_funding_warning(
864 faucet_error,
865 balance_wei,
866 address,
867 None,
868 readiness.checks.funded.funding_hint.as_deref(),
869 )
870 .is_none()
871 {
872 return;
873 }
874 let rpc_url = client
877 .fetch_network_config()
878 .await
879 .ok()
880 .and_then(|cfg| cfg.entry(ctx.environment.network().as_str()).ok())
881 .map(|entry| entry.rpc_url.clone());
882 if let Some(warning) = build_funding_warning(
883 faucet_error,
884 balance_wei,
885 address,
886 rpc_url.as_deref(),
887 readiness.checks.funded.funding_hint.as_deref(),
888 ) {
889 eprintln!("{warning}");
890 }
891}
892
893#[cfg_attr(test, derive(Debug))]
898enum WebhookOutcome {
899 Skipped,
900 DryRun {
901 url: String,
902 events: Vec<String>,
903 secret_file: Option<PathBuf>,
904 },
905 Registered {
906 url: String,
907 secret_returned: bool,
908 secret_persisted: bool,
909 secret_file: Option<PathBuf>,
910 subscribed: Option<Vec<String>>,
911 },
912 Failed {
913 error: String,
914 },
915}
916
917fn resolve_webhook_events(args: &Args) -> Vec<String> {
925 if !args.webhook_events.is_empty() {
926 return args.webhook_events.clone();
927 }
928 if args.no_default_events {
929 return Vec::new();
930 }
931 crate::cmd::webhook::DEFAULT_WORKER_EVENTS
932 .iter()
933 .map(|s| (*s).to_string())
934 .collect()
935}
936
937async fn maybe_configure_webhook(
938 client: &TaskFastClient,
939 args: &Args,
940 dry_run: bool,
941) -> WebhookOutcome {
942 let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) else {
943 return WebhookOutcome::Skipped;
944 };
945 let events = resolve_webhook_events(args);
946 if dry_run {
947 return WebhookOutcome::DryRun {
948 url: url.to_string(),
949 events,
950 secret_file: args.webhook_secret_file.clone(),
951 };
952 }
953 match crate::cmd::webhook::provision_webhook(
954 client,
955 url,
956 args.webhook_secret_file.as_deref(),
957 &events,
958 )
959 .await
960 {
961 Ok(outcome) => WebhookOutcome::Registered {
962 url: outcome.url,
963 secret_returned: outcome.secret_returned,
964 secret_persisted: outcome.secret_persisted,
965 secret_file: outcome.secret_file,
966 subscribed: outcome.subscribed,
967 },
968 Err(e) => WebhookOutcome::Failed {
969 error: e.to_string(),
970 },
971 }
972}
973
974fn build_envelope_data(
975 cfg_path: &Path,
976 config_written: bool,
977 wallet: &WalletOutcome,
978 agent: &AgentOutcome,
979 readiness: &AgentReadiness,
980 faucet: &FaucetOutcome,
981 webhook: &WebhookOutcome,
982 dry_run: bool,
983) -> serde_json::Value {
984 let mut wallet_obj = json!({
985 "status": wallet.tag(),
986 });
987 if let Some(addr) = wallet.address() {
988 wallet_obj["address"] = json!(addr);
989 }
990 if let Some(path) = wallet.keystore_path() {
991 wallet_obj["keystore_path"] = json!(path.display().to_string());
992 }
993
994 let mut cfg_obj = json!({
995 "path": cfg_path.display().to_string(),
996 "written": config_written,
997 });
998 if dry_run && !config_written {
999 cfg_obj["would_write"] = json!(true);
1000 }
1001
1002 let faucet_obj = match faucet {
1003 FaucetOutcome::Skipped { reason } => {
1004 let mut o = json!({
1005 "status": "skipped",
1006 "reason": reason,
1007 });
1008 if *reason == "mainnet" {
1012 o["funding_hint"] = json!({
1013 "url": "https://wallet.tempo.xyz",
1014 "message": "Production wallets must be funded manually by the owning human at wallet.tempo.xyz before posting or settling.",
1015 });
1016 }
1017 o
1018 }
1019 FaucetOutcome::Requested { drops } => json!({
1020 "status": "requested",
1021 "drops": drops.iter().map(|d| json!({
1022 "token": d.token,
1023 "tx_hash": d.tx_hash,
1024 })).collect::<Vec<_>>(),
1025 }),
1026 FaucetOutcome::Failed { error } => json!({
1027 "status": "failed",
1028 "error": error,
1029 }),
1030 };
1031
1032 let webhook_obj = match webhook {
1033 WebhookOutcome::Skipped => json!({ "status": "skipped" }),
1034 WebhookOutcome::DryRun {
1035 url,
1036 events,
1037 secret_file,
1038 } => {
1039 let mut o = json!({
1040 "status": "would_register",
1041 "url": url,
1042 "events": events,
1043 });
1044 if let Some(p) = secret_file {
1045 o["secret_file"] = json!(p.display().to_string());
1046 }
1047 o
1048 }
1049 WebhookOutcome::Registered {
1050 url,
1051 secret_returned,
1052 secret_persisted,
1053 secret_file,
1054 subscribed,
1055 } => {
1056 let mut o = json!({
1057 "status": "registered",
1058 "url": url,
1059 "secret_returned": secret_returned,
1060 "secret_persisted": secret_persisted,
1061 });
1062 if let Some(p) = secret_file {
1063 o["secret_file"] = json!(p.display().to_string());
1064 }
1065 if let Some(subs) = subscribed {
1066 o["subscribed"] = json!(subs);
1067 }
1068 o
1069 }
1070 WebhookOutcome::Failed { error } => json!({
1071 "status": "failed",
1072 "error": error,
1073 }),
1074 };
1075
1076 let mut out = json!({
1077 "wallet": wallet_obj,
1078 "config_file": cfg_obj,
1079 "faucet": faucet_obj,
1080 "webhook": webhook_obj,
1081 "readiness": readiness,
1082 "ready_to_work": readiness.ready_to_work,
1083 });
1084 if let AgentOutcome::Minted(MintedAgent::Live { id, name, .. }) = agent {
1085 let mut a = json!({ "action": "minted" });
1086 if let Some(id) = id {
1087 a["id"] = json!(id);
1088 }
1089 if let Some(name) = name {
1090 a["name"] = json!(name);
1091 }
1092 out["agent"] = a;
1093 }
1094 out
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099 use super::*;
1100 use crate::Environment;
1101
1102 fn base_args() -> Args {
1103 Args {
1104 wallet_address: None,
1105 generate_wallet: false,
1106 wallet_password_file: None,
1107 keystore_path: None,
1108 skip_wallet: false,
1109 fund: false,
1110 human_api_key: None,
1111 agent_name: "taskfast-agent".into(),
1112 agent_description: "Headless agent registered via taskfast init".into(),
1113 agent_capabilities: Vec::new(),
1114 webhook_url: None,
1115 webhook_secret_file: None,
1116 webhook_events: Vec::new(),
1117 no_default_events: false,
1118 no_interactive: true,
1119 inline_wallet_password: None,
1120 }
1121 }
1122
1123 fn ctx_with_key(key: Option<&str>) -> Ctx {
1124 Ctx {
1125 api_key: key.map(String::from),
1126 environment: Environment::Local,
1127 api_base: None,
1128 config_path: PathBuf::from("/dev/null"),
1129 dry_run: false,
1130 quiet: true,
1131 ..Default::default()
1132 }
1133 }
1134
1135 fn cfg_with_key(key: Option<&str>) -> Config {
1136 Config {
1137 api_key: key.map(str::to_string),
1138 ..Config::default()
1139 }
1140 }
1141
1142 #[test]
1143 fn resolve_api_key_prefers_ctx_over_config() {
1144 let ctx = ctx_with_key(Some("from-flag"));
1145 let cfg = cfg_with_key(Some("from-file"));
1146 assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-flag");
1147 }
1148
1149 #[test]
1150 fn resolve_api_key_falls_back_to_config() {
1151 let ctx = ctx_with_key(None);
1152 let cfg = cfg_with_key(Some("from-file"));
1153 assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-file");
1154 }
1155
1156 #[test]
1157 fn resolve_api_key_empty_string_is_treated_as_absent() {
1158 let ctx = ctx_with_key(Some(""));
1159 let cfg = cfg_with_key(Some(""));
1160 match resolve_api_key(&ctx, &cfg) {
1161 Err(CmdError::MissingApiKey) => {}
1162 other => panic!("expected MissingApiKey, got {other:?}"),
1163 }
1164 }
1165
1166 #[test]
1167 fn provision_without_wallet_flag_errors_as_usage() {
1168 let args = base_args();
1172 assert!(args.wallet_address.is_none() && !args.generate_wallet);
1173 }
1176
1177 #[test]
1178 fn wallet_outcome_tag_is_stable() {
1179 assert_eq!(WalletOutcome::AlreadyConfigured.tag(), "already_configured");
1182 assert_eq!(
1183 WalletOutcome::ByoRegistered {
1184 address: "0x00".into()
1185 }
1186 .tag(),
1187 "byo_registered"
1188 );
1189 assert_eq!(
1190 WalletOutcome::Generated {
1191 address: "0x00".into(),
1192 keystore_path: PathBuf::from("/tmp/x")
1193 }
1194 .tag(),
1195 "generated"
1196 );
1197 assert_eq!(
1198 WalletOutcome::DryRunGenerated {
1199 address: "0x00".into()
1200 }
1201 .tag(),
1202 "dry_run_generated"
1203 );
1204 assert_eq!(WalletOutcome::Skipped.tag(), "skipped");
1205 }
1206
1207 #[test]
1208 fn resolve_webhook_events_uses_defaults_when_events_empty() {
1209 let args = Args {
1214 webhook_url: Some("https://h.example/x".into()),
1215 ..base_args()
1216 };
1217 let events = resolve_webhook_events(&args);
1218 assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1219 }
1220
1221 #[test]
1222 fn resolve_webhook_events_respects_no_default_events_opt_out() {
1223 let args = Args {
1225 webhook_url: Some("https://h.example/x".into()),
1226 no_default_events: true,
1227 ..base_args()
1228 };
1229 assert!(resolve_webhook_events(&args).is_empty());
1230 }
1231
1232 #[test]
1233 fn resolve_webhook_events_explicit_events_override_defaults() {
1234 let args = Args {
1236 webhook_url: Some("https://h.example/x".into()),
1237 webhook_events: vec!["task_assigned".into()],
1238 ..base_args()
1239 };
1240 assert_eq!(resolve_webhook_events(&args), vec!["task_assigned"]);
1241 }
1242
1243 #[test]
1244 fn resolve_webhook_events_explicit_events_win_over_no_default_events() {
1245 let args = Args {
1248 webhook_url: Some("https://h.example/x".into()),
1249 webhook_events: vec!["bid_accepted".into()],
1250 no_default_events: true,
1251 ..base_args()
1252 };
1253 assert_eq!(resolve_webhook_events(&args), vec!["bid_accepted"]);
1254 }
1255
1256 #[test]
1259 fn funding_warning_faucet_failure_lists_manual_fallback() {
1260 let w = build_funding_warning(
1261 Some("faucet returned status 405: method not allowed"),
1262 Some(0),
1263 "0xabc0000000000000000000000000000000000000",
1264 Some("https://rpc.testnet.example"),
1265 None,
1266 )
1267 .expect("faucet failure must warn");
1268 assert!(w.contains("faucet returned status 405"), "got: {w}");
1269 assert!(w.contains("0xabc0000000000000000000000000000000000000"));
1270 assert!(w.contains(
1271 "cast rpc tempo_fundAddress \
1272 '[\"0xabc0000000000000000000000000000000000000\"]' \
1273 --raw --rpc-url https://rpc.testnet.example"
1274 ));
1275 assert!(w.contains("https://wallet.tempo.xyz"));
1276 }
1277
1278 #[test]
1279 fn funding_warning_zero_balance_without_faucet_failure_still_warns() {
1280 let w = build_funding_warning(
1284 None,
1285 Some(0),
1286 "0xabc0000000000000000000000000000000000000",
1287 Some("https://rpc.testnet.example"),
1288 None,
1289 )
1290 .expect("zero balance must warn");
1291 assert!(w.contains("zero"), "got: {w}");
1292 assert!(w.contains("https://wallet.tempo.xyz"));
1293 }
1294
1295 #[test]
1296 fn funding_warning_silent_when_funded() {
1297 assert!(build_funding_warning(
1298 None,
1299 Some(42),
1300 "0xabc0000000000000000000000000000000000000",
1301 Some("https://rpc.testnet.example"),
1302 None,
1303 )
1304 .is_none());
1305 }
1306
1307 #[test]
1308 fn funding_warning_silent_when_balance_unknown_and_faucet_did_not_fail() {
1309 assert!(build_funding_warning(
1311 None,
1312 None,
1313 "0xabc0000000000000000000000000000000000000",
1314 Some("https://rpc.testnet.example"),
1315 None,
1316 )
1317 .is_none());
1318 }
1319
1320 #[test]
1321 fn funding_warning_without_rpc_url_omits_cast_line_keeps_web_fallback() {
1322 let w = build_funding_warning(
1323 Some("faucet http request failed"),
1324 Some(0),
1325 "0xabc0000000000000000000000000000000000000",
1326 None,
1327 None,
1328 )
1329 .expect("must still warn");
1330 assert!(!w.contains("cast rpc"), "got: {w}");
1331 assert!(w.contains("https://wallet.tempo.xyz"));
1332 }
1333
1334 #[test]
1335 fn funding_warning_surfaces_server_funding_hint() {
1336 let w = build_funding_warning(
1337 None,
1338 Some(0),
1339 "0xabc0000000000000000000000000000000000000",
1340 None,
1341 Some("https://wallet.tempo.xyz/topup"),
1342 )
1343 .expect("must warn");
1344 assert!(w.contains("https://wallet.tempo.xyz/topup"), "got: {w}");
1345 }
1346
1347 #[test]
1348 fn parse_wei_hex_handles_0x_zero_and_plain_hex_forms() {
1349 assert_eq!(parse_wei_hex(Some("0x0")), Some(0));
1350 assert_eq!(
1351 parse_wei_hex(Some(
1352 "0x000000000000000000000000000000000000000000000000000000000000000a"
1353 )),
1354 Some(10)
1355 );
1356 assert_eq!(parse_wei_hex(None), None);
1357 assert_eq!(parse_wei_hex(Some("0x")), None);
1358 }
1359
1360 #[tokio::test]
1361 async fn maybe_configure_webhook_dry_run_surfaces_default_events() {
1362 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1366 let args = Args {
1367 webhook_url: Some("https://h.example/x".into()),
1368 ..base_args()
1369 };
1370 let outcome = maybe_configure_webhook(&client, &args, true).await;
1371 match outcome {
1372 WebhookOutcome::DryRun { events, url, .. } => {
1373 assert_eq!(url, "https://h.example/x");
1374 assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1375 }
1376 other => panic!("expected DryRun, got {other:?}"),
1377 }
1378 }
1379
1380 #[tokio::test]
1381 async fn maybe_configure_webhook_dry_run_respects_no_default_events() {
1382 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1383 let args = Args {
1384 webhook_url: Some("https://h.example/x".into()),
1385 no_default_events: true,
1386 ..base_args()
1387 };
1388 let outcome = maybe_configure_webhook(&client, &args, true).await;
1389 match outcome {
1390 WebhookOutcome::DryRun { events, .. } => assert!(events.is_empty()),
1391 other => panic!("expected DryRun, got {other:?}"),
1392 }
1393 }
1394
1395 #[tokio::test]
1396 async fn maybe_configure_webhook_no_url_is_skipped() {
1397 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1400 let outcome = maybe_configure_webhook(&client, &base_args(), true).await;
1401 assert!(matches!(outcome, WebhookOutcome::Skipped));
1402 }
1403}