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_agent::webhooks;
73use taskfast_client::api::types::{AgentCreateRequest, AgentReadiness, WebhookConfigRequest};
74use taskfast_client::TaskFastClient;
75
76use super::webhook::persist_secret;
77
78const WALLET_STATUS_COMPLETE: &str = "complete";
82
83#[derive(Debug, Parser)]
84#[allow(clippy::struct_excessive_bools)]
88pub struct Args {
89 #[arg(long, conflicts_with = "generate_wallet")]
92 pub wallet_address: Option<String>,
93
94 #[arg(long)]
97 pub generate_wallet: bool,
98
99 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
104 pub wallet_password_file: Option<PathBuf>,
105
106 #[arg(long)]
109 pub keystore_path: Option<PathBuf>,
110
111 #[arg(long)]
114 pub skip_wallet: bool,
115
116 #[arg(long)]
122 pub fund: bool,
123
124 #[arg(long, env = "TASKFAST_HUMAN_API_KEY")]
130 pub human_api_key: Option<String>,
131
132 #[arg(long, default_value = "taskfast-agent")]
134 pub agent_name: String,
135
136 #[arg(long, default_value = "Headless agent registered via taskfast init")]
138 pub agent_description: String,
139
140 #[arg(long = "agent-capability", value_name = "CAP")]
144 pub agent_capabilities: Vec<String>,
145
146 #[arg(long)]
152 pub webhook_url: Option<String>,
153
154 #[arg(long)]
159 pub webhook_secret_file: Option<PathBuf>,
160
161 #[arg(long = "webhook-event", value_name = "EVENT")]
168 pub webhook_events: Vec<String>,
169
170 #[arg(long)]
175 pub no_default_events: bool,
176
177 #[arg(long, env = "TASKFAST_NO_INTERACTIVE")]
181 pub no_interactive: bool,
182
183 #[arg(skip)]
189 pub inline_wallet_password: Option<String>,
190}
191
192pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
193 let interactive = !args.no_interactive && crate::cmd::init_tui::is_interactive();
194 run_with_prompter(
195 ctx,
196 args,
197 &crate::cmd::init_tui::DialoguerPrompter,
198 interactive,
199 )
200 .await
201}
202
203pub async fn run_with_prompter<P: crate::cmd::init_tui::Prompter>(
208 ctx: &Ctx,
209 mut args: Args,
210 prompter: &P,
211 interactive: bool,
212) -> CmdResult {
213 let cfg_path = ctx.config_path.clone();
214
215 let mut cfg = Config::load(&cfg_path)?;
219
220 let (api_key, agent_outcome) = match resolve_api_key(ctx, &cfg) {
229 Ok(k) => (k, AgentOutcome::PreExisting),
230 Err(CmdError::MissingApiKey) => {
231 let pat = resolve_pat(ctx, &args, interactive, prompter).await?;
232 let minted = mint_agent(ctx, &args, &pat).await?;
233 match minted {
234 MintedAgent::DryRun { ref intent } => {
235 return Ok(Envelope::success(
236 ctx.environment,
237 ctx.dry_run,
238 build_dry_run_mint_envelope(&cfg_path, intent),
239 ));
240 }
241 MintedAgent::Live { ref api_key, .. } => {
242 (api_key.clone(), AgentOutcome::Minted(minted))
243 }
244 }
245 }
246 Err(e) => return Err(e),
247 };
248
249 if interactive
256 && matches!(agent_outcome, AgentOutcome::Minted(_))
257 && args.wallet_address.is_none()
258 && !args.generate_wallet
259 && !args.skip_wallet
260 {
261 apply_wallet_mode_prompt(&mut args, prompter)?;
262 }
263
264 let effective_ctx = Ctx {
265 api_key: Some(api_key.clone()),
266 ..ctx.clone()
267 };
268 let client = effective_ctx.client()?;
269
270 let profile = match validate_auth(&client).await {
275 Ok(p) => p,
276 Err(taskfast_client::Error::Auth(msg))
277 if matches!(agent_outcome, AgentOutcome::PreExisting) =>
278 {
279 return Err(CmdError::Auth(stale_key_hint(
280 &msg, &cfg_path, &cfg, ctx, &args,
281 )));
282 }
283 Err(e) => return Err(CmdError::from(e)),
284 };
285 assert_active(&profile)?;
286 if !ctx.dry_run {
291 super::enforce_server_network_invariant(&effective_ctx, &client).await?;
292 }
293 let readiness = get_readiness(&client).await.map_err(CmdError::from)?;
294
295 let wallet_outcome = if args.skip_wallet {
297 WalletOutcome::Skipped
298 } else if readiness.checks.wallet.status == WALLET_STATUS_COMPLETE
299 && args.wallet_address.is_none()
300 && !args.generate_wallet
301 {
302 WalletOutcome::AlreadyConfigured
305 } else {
306 provision_wallet(&client, &args, ctx.dry_run).await?
307 };
308
309 cfg.environment = Some(ctx.environment);
314 cfg.api_key = Some(api_key.clone());
315 if let Some(addr) = wallet_outcome.address() {
316 cfg.wallet_address = Some(addr.to_string());
317 }
318 if let Some(path) = wallet_outcome.keystore_path() {
319 cfg.keystore_path = Some(path.to_path_buf());
320 }
321 if let AgentOutcome::Minted(MintedAgent::Live { id: Some(id), .. }) = &agent_outcome {
322 cfg.agent_id = Some(id.clone());
323 }
324 if let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) {
325 cfg.webhook_url = Some(url.to_string());
326 }
327 if let Some(path) = args.webhook_secret_file.as_ref() {
328 cfg.webhook_secret_path = Some(path.clone());
329 }
330
331 let config_written = if ctx.dry_run {
332 false
333 } else {
334 cfg.save(&cfg_path)?;
335 true
336 };
337
338 let faucet_outcome = maybe_request_faucet(
350 &args,
351 ctx.environment.network(),
352 &wallet_outcome,
353 ctx.dry_run,
354 )
355 .await;
356
357 let webhook_outcome = maybe_configure_webhook(&client, &args, ctx.dry_run).await;
362
363 let final_readiness = get_readiness(&client).await.map_err(CmdError::from)?;
366
367 warn_if_unfunded(
371 &client,
372 ctx,
373 cfg.wallet_address.as_deref(),
374 &faucet_outcome,
375 &final_readiness,
376 )
377 .await;
378
379 let data = build_envelope_data(
380 &cfg_path,
381 config_written,
382 &wallet_outcome,
383 &agent_outcome,
384 &final_readiness,
385 &faucet_outcome,
386 &webhook_outcome,
387 ctx.dry_run,
388 );
389 Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
390}
391
392enum AgentOutcome {
397 PreExisting,
398 Minted(MintedAgent),
399}
400
401enum MintedAgent {
405 Live {
406 api_key: String,
407 id: Option<String>,
408 name: Option<String>,
409 },
410 DryRun {
411 intent: MintIntent,
412 },
413}
414
415struct MintIntent {
416 name: String,
417 description: String,
418 capabilities: Vec<String>,
419}
420
421async fn resolve_pat<P: crate::cmd::init_tui::Prompter>(
426 ctx: &Ctx,
427 args: &Args,
428 interactive: bool,
429 prompter: &P,
430) -> Result<String, CmdError> {
431 if let Some(p) = args.human_api_key.as_deref().filter(|s| !s.is_empty()) {
432 return Ok(p.to_string());
433 }
434 if !interactive {
435 return Err(CmdError::MissingApiKey);
436 }
437 let accounts_url = crate::accounts_url(ctx.base_url());
438 let pat = prompter
439 .pat(&accounts_url)
440 .map_err(|e| CmdError::Usage(format!("PAT prompt failed: {e}")))?;
441 let pat_client = TaskFastClient::from_api_key(ctx.base_url(), &pat).map_err(CmdError::from)?;
445 let profile = pat_client.get_user_profile().await.ok().flatten();
446 eprintln!("{}", crate::cmd::init_tui::greeting(profile.as_ref()));
447 Ok(pat)
448}
449
450fn apply_wallet_mode_prompt<P: crate::cmd::init_tui::Prompter>(
454 args: &mut Args,
455 prompter: &P,
456) -> Result<(), CmdError> {
457 use crate::cmd::init_tui::WalletMode;
458 let mode = prompter
459 .wallet_mode()
460 .map_err(|e| CmdError::Usage(format!("wallet-mode prompt failed: {e}")))?;
461 match mode {
462 WalletMode::Byow => {
463 let addr = prompter
464 .wallet_address()
465 .map_err(|e| CmdError::Usage(format!("wallet-address prompt failed: {e}")))?;
466 args.wallet_address = Some(addr.trim().to_string());
467 }
468 WalletMode::Generate => {
469 args.generate_wallet = true;
470 let pw = prompter
471 .wallet_password()
472 .map_err(|e| CmdError::Usage(format!("password prompt failed: {e}")))?;
473 args.inline_wallet_password = Some(pw);
474 }
475 WalletMode::Skip => {
476 args.skip_wallet = true;
477 }
478 }
479 Ok(())
480}
481
482async fn mint_agent(ctx: &Ctx, args: &Args, pat: &str) -> Result<MintedAgent, CmdError> {
483 if pat.is_empty() {
484 return Err(CmdError::Usage("PAT is empty".into()));
485 }
486
487 let capabilities = if args.agent_capabilities.is_empty() {
488 vec!["general".to_string()]
489 } else {
490 args.agent_capabilities.clone()
491 };
492
493 if ctx.dry_run {
494 return Ok(MintedAgent::DryRun {
495 intent: MintIntent {
496 name: args.agent_name.clone(),
497 description: args.agent_description.clone(),
498 capabilities,
499 },
500 });
501 }
502
503 let pat_client = TaskFastClient::from_api_key(ctx.base_url(), pat).map_err(CmdError::from)?;
504 let body = AgentCreateRequest {
505 owner_id: None,
506 name: args.agent_name.clone(),
507 description: args.agent_description.clone(),
508 capabilities,
509 rate: None,
510 max_task_budget: None,
511 daily_spend_limit: None,
512 payout_method: None,
513 payment_method: None,
514 tempo_wallet_address: None,
515 };
516 let resp = create_agent_headless(&pat_client, &body)
517 .await
518 .map_err(CmdError::from)?;
519 let api_key = resp
520 .api_key
521 .clone()
522 .ok_or_else(|| CmdError::Server("POST /agents returned no api_key despite 201".into()))?;
523 Ok(MintedAgent::Live {
524 api_key,
525 id: resp.id.map(|u| u.to_string()),
526 name: resp.name.clone(),
527 })
528}
529
530fn build_dry_run_mint_envelope(cfg_path: &Path, intent: &MintIntent) -> serde_json::Value {
531 json!({
532 "agent": {
533 "action": "would_mint",
534 "name": intent.name,
535 "description": intent.description,
536 "capabilities": intent.capabilities,
537 },
538 "config_file": {
539 "path": cfg_path.display().to_string(),
540 "written": false,
541 "would_write": true,
542 },
543 "ready_to_work": false,
544 })
545}
546
547fn resolve_api_key(ctx: &Ctx, cfg: &Config) -> Result<String, CmdError> {
556 if let Some(k) = ctx.api_key.as_deref() {
557 if !k.is_empty() {
558 return Ok(k.to_string());
559 }
560 }
561 if let Some(k) = cfg.api_key.as_deref() {
562 if !k.is_empty() {
563 return Ok(k.to_string());
564 }
565 }
566 Err(CmdError::MissingApiKey)
567}
568
569fn stale_key_hint(msg: &str, cfg_path: &Path, cfg: &Config, ctx: &Ctx, args: &Args) -> String {
573 let source = if cfg.api_key.as_deref().is_some_and(|k| !k.is_empty()) {
574 format!("config file {}", cfg_path.display())
575 } else if ctx.api_key.is_some() {
576 "--api-key flag or TASKFAST_API_KEY env".to_string()
577 } else {
578 "unknown".to_string()
579 };
580 let had_pat = args.human_api_key.is_some();
581 let pat_note = if had_pat {
582 "\n note: --human-api-key was provided but ignored because an existing api_key was found; \
583 the PAT mints a new agent only when no api_key is resolvable."
584 } else {
585 ""
586 };
587 format!(
588 "{msg}\n hint: agent api_key rejected — likely stale (agent deleted or key rotated).\n \
589 source: {source}\n fix: delete {path} (and unset TASKFAST_API_KEY if set), then re-run \
590 `taskfast --env {env} init --human-api-key <tf_user_...>` to mint a fresh agent.{pat_note}",
591 path = cfg_path.display(),
592 env = ctx.environment.as_str(),
593 )
594}
595
596fn assert_active(profile: &taskfast_client::api::types::AgentProfile) -> Result<(), CmdError> {
597 match profile.status.as_deref() {
598 Some("active") => Ok(()),
599 Some(other) => Err(CmdError::Validation {
600 code: "agent_not_active".into(),
601 message: format!("agent status is {other}; owner must reactivate"),
602 }),
603 None => Err(CmdError::Server(
604 "GET /agents/me returned no status field".into(),
605 )),
606 }
607}
608
609enum WalletOutcome {
611 AlreadyConfigured,
613 ByoRegistered { address: String },
615 Generated {
617 address: String,
618 keystore_path: PathBuf,
619 },
620 DryRunGenerated { address: String },
622 Skipped,
624}
625
626impl WalletOutcome {
627 fn address(&self) -> Option<&str> {
628 match self {
629 Self::ByoRegistered { address }
630 | Self::Generated { address, .. }
631 | Self::DryRunGenerated { address } => Some(address),
632 Self::AlreadyConfigured | Self::Skipped => None,
633 }
634 }
635
636 fn keystore_path(&self) -> Option<&Path> {
637 match self {
638 Self::Generated { keystore_path, .. } => Some(keystore_path),
639 _ => None,
640 }
641 }
642
643 fn tag(&self) -> &'static str {
644 match self {
645 Self::AlreadyConfigured => "already_configured",
646 Self::ByoRegistered { .. } => "byo_registered",
647 Self::Generated { .. } => "generated",
648 Self::DryRunGenerated { .. } => "dry_run_generated",
649 Self::Skipped => "skipped",
650 }
651 }
652}
653
654async fn provision_wallet(
655 client: &TaskFastClient,
656 args: &Args,
657 dry_run: bool,
658) -> Result<WalletOutcome, CmdError> {
659 if let Some(addr) = args.wallet_address.as_deref() {
660 if dry_run {
661 return Ok(WalletOutcome::Skipped);
662 }
663 wallet::register_wallet(client, addr)
664 .await
665 .map_err(CmdError::from)?;
666 return Ok(WalletOutcome::ByoRegistered {
667 address: addr.to_string(),
668 });
669 }
670 if !args.generate_wallet {
671 return Err(CmdError::Usage(
672 "pass --wallet-address <0x...> or --generate-wallet (or --skip-wallet to defer)".into(),
673 ));
674 }
675
676 let signer = wallet::generate_signer();
677 let address = format!("0x{}", hex::encode(signer.address().as_slice()));
678
679 if dry_run {
680 return Ok(WalletOutcome::DryRunGenerated { address });
683 }
684
685 let password = resolve_wallet_password(args)?;
686 let keystore_path = persist_keystore(&signer, args, &password)?;
687 wallet::register_wallet(client, &address)
688 .await
689 .map_err(CmdError::from)?;
690 Ok(WalletOutcome::Generated {
691 address,
692 keystore_path,
693 })
694}
695
696fn resolve_wallet_password(args: &Args) -> Result<String, CmdError> {
697 if let Some(pw) = args.inline_wallet_password.as_deref() {
700 if !pw.is_empty() {
701 return Ok(pw.to_string());
702 }
703 }
704 if let Ok(pw) = std::env::var("TASKFAST_WALLET_PASSWORD") {
705 if !pw.is_empty() {
706 return Ok(pw);
707 }
708 }
709 let path = args.wallet_password_file.as_deref().ok_or_else(|| {
710 CmdError::Usage(
711 "--generate-wallet requires --wallet-password-file or TASKFAST_WALLET_PASSWORD".into(),
712 )
713 })?;
714 let raw = std::fs::read_to_string(path).map_err(|e| {
715 CmdError::Usage(format!(
716 "cannot read wallet password file {}: {e}",
717 path.display()
718 ))
719 })?;
720 let trimmed = raw.trim_end_matches(['\n', '\r']);
721 if trimmed.is_empty() {
722 return Err(CmdError::Usage(format!(
723 "wallet password file {} is empty",
724 path.display()
725 )));
726 }
727 Ok(trimmed.to_string())
728}
729
730fn persist_keystore(
731 signer: &PrivateKeySigner,
732 args: &Args,
733 password: &str,
734) -> Result<PathBuf, CmdError> {
735 let path = match &args.keystore_path {
736 Some(p) => p.clone(),
737 None => keystore::default_keyfile_path(signer.address()).map_err(CmdError::from)?,
738 };
739 keystore::save_signer(signer, &path, password).map_err(CmdError::from)
740}
741
742enum FaucetOutcome {
747 Skipped { reason: &'static str },
748 Requested { drops: Vec<FaucetDrop> },
749 Failed { error: String },
750}
751
752async fn maybe_request_faucet(
753 args: &Args,
754 network: crate::Network,
755 wallet: &WalletOutcome,
756 dry_run: bool,
757) -> FaucetOutcome {
758 if dry_run {
759 return FaucetOutcome::Skipped { reason: "dry_run" };
760 }
761 if !args.fund {
762 return FaucetOutcome::Skipped {
763 reason: "fund_flag_not_set",
764 };
765 }
766 if !matches!(network, crate::Network::Testnet) {
767 return FaucetOutcome::Skipped { reason: "mainnet" };
768 }
769 let address = match wallet {
770 WalletOutcome::Generated { address, .. } => address.clone(),
771 WalletOutcome::ByoRegistered { address } => address.clone(),
772 _ => {
773 return FaucetOutcome::Skipped {
774 reason: "no_fresh_wallet",
775 };
776 }
777 };
778 let http = reqwest::Client::new();
779 match request_testnet_funds(&http, &address).await {
780 Ok(drops) => FaucetOutcome::Requested { drops },
781 Err(e) => FaucetOutcome::Failed {
782 error: e.to_string(),
783 },
784 }
785}
786
787fn parse_wei_hex(s: Option<&str>) -> Option<u128> {
790 let s = s?.trim();
791 let hex = s.strip_prefix("0x").unwrap_or(s);
792 if hex.is_empty() {
793 return None;
794 }
795 u128::from_str_radix(hex, 16).ok()
796}
797
798fn build_funding_warning(
804 faucet_error: Option<&str>,
805 balance_wei: Option<u128>,
806 address: &str,
807 rpc_url: Option<&str>,
808 funding_hint: Option<&str>,
809) -> Option<String> {
810 let zero_balance = balance_wei.is_some_and(|b| b == 0);
811 if faucet_error.is_none() && !zero_balance {
812 return None;
813 }
814 let mut lines = Vec::new();
815 match (faucet_error, zero_balance) {
816 (Some(err), _) => lines.push(format!(
817 "WARNING: testnet faucet funding failed (--fund): {err}"
818 )),
819 (None, true) => lines.push(format!(
820 "WARNING: wallet {address} balance is zero at the end of init"
821 )),
822 (None, false) => return None,
823 }
824 lines.push(
825 " the next on-chain command will fail until the wallet is funded. \
826 manual fallback:"
827 .to_string(),
828 );
829 if let Some(rpc) = rpc_url {
830 lines.push(format!(
831 " cast rpc tempo_fundAddress '[\"{address}\"]' --raw --rpc-url {rpc}"
832 ));
833 }
834 lines.push(" or fund at https://wallet.tempo.xyz".to_string());
835 if let Some(hint) = funding_hint {
836 lines.push(format!(" server funding hint: {hint}"));
837 }
838 Some(lines.join("\n"))
839}
840
841async fn warn_if_unfunded(
850 client: &TaskFastClient,
851 ctx: &Ctx,
852 wallet_address: Option<&str>,
853 faucet: &FaucetOutcome,
854 readiness: &AgentReadiness,
855) {
856 if ctx.dry_run {
857 return;
858 }
859 if !matches!(ctx.environment.network(), crate::Network::Testnet) {
860 return;
861 }
862 let Some(address) = wallet_address else {
863 return;
864 };
865 let faucet_error = match faucet {
866 FaucetOutcome::Failed { error } => Some(error.as_str()),
867 _ => None,
868 };
869 let balance_wei = match client.inner().get_wallet_balance().await {
870 Ok(resp) => parse_wei_hex(resp.into_inner().available_balance.as_deref()),
871 Err(e) => {
872 tracing::warn!(error = %e, "init: balance check unavailable; skipping zero-balance warning");
873 None
874 }
875 };
876 if build_funding_warning(
877 faucet_error,
878 balance_wei,
879 address,
880 None,
881 readiness.checks.funded.funding_hint.as_deref(),
882 )
883 .is_none()
884 {
885 return;
886 }
887 let rpc_url = client
890 .fetch_network_config()
891 .await
892 .ok()
893 .and_then(|cfg| cfg.entry(ctx.environment.network().as_str()).ok())
894 .map(|entry| entry.rpc_url.clone());
895 if let Some(warning) = build_funding_warning(
896 faucet_error,
897 balance_wei,
898 address,
899 rpc_url.as_deref(),
900 readiness.checks.funded.funding_hint.as_deref(),
901 ) {
902 eprintln!("{warning}");
903 }
904}
905
906#[cfg_attr(test, derive(Debug))]
911enum WebhookOutcome {
912 Skipped,
913 DryRun {
914 url: String,
915 events: Vec<String>,
916 secret_file: Option<PathBuf>,
917 },
918 Registered {
919 url: String,
920 secret_returned: bool,
921 secret_persisted: bool,
922 secret_file: Option<PathBuf>,
923 subscribed: Option<Vec<String>>,
924 },
925 Failed {
926 error: String,
927 },
928}
929
930fn resolve_webhook_events(args: &Args) -> Vec<String> {
938 if !args.webhook_events.is_empty() {
939 return args.webhook_events.clone();
940 }
941 if args.no_default_events {
942 return Vec::new();
943 }
944 crate::cmd::webhook::DEFAULT_WORKER_EVENTS
945 .iter()
946 .map(|s| (*s).to_string())
947 .collect()
948}
949
950async fn maybe_configure_webhook(
951 client: &TaskFastClient,
952 args: &Args,
953 dry_run: bool,
954) -> WebhookOutcome {
955 let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) else {
956 return WebhookOutcome::Skipped;
957 };
958 let events = resolve_webhook_events(args);
959 if dry_run {
960 return WebhookOutcome::DryRun {
961 url: url.to_string(),
962 events,
963 secret_file: args.webhook_secret_file.clone(),
964 };
965 }
966 let body = WebhookConfigRequest {
967 url: url.to_string(),
968 secret: None,
969 events: None,
970 };
971 let cfg = match webhooks::configure_webhook(client, &body).await {
972 Ok(c) => c,
973 Err(e) => {
974 return WebhookOutcome::Failed {
975 error: e.to_string(),
976 };
977 }
978 };
979 let secret_persisted = match (cfg.secret.as_deref(), args.webhook_secret_file.as_ref()) {
980 (Some(secret), Some(path)) => match persist_secret(path, secret) {
981 Ok(()) => true,
982 Err(e) => {
983 return WebhookOutcome::Failed {
984 error: e.to_string(),
985 };
986 }
987 },
988 _ => false,
989 };
990 let subscribed = if events.is_empty() {
991 None
992 } else {
993 match webhooks::update_subscriptions(client, events).await {
994 Ok(subs) => Some(subs.subscribed_event_types),
995 Err(e) => {
996 return WebhookOutcome::Failed {
997 error: e.to_string(),
998 };
999 }
1000 }
1001 };
1002 WebhookOutcome::Registered {
1003 url: cfg.url,
1004 secret_returned: cfg.secret.is_some(),
1005 secret_persisted,
1006 secret_file: args.webhook_secret_file.clone(),
1007 subscribed,
1008 }
1009}
1010
1011fn build_envelope_data(
1012 cfg_path: &Path,
1013 config_written: bool,
1014 wallet: &WalletOutcome,
1015 agent: &AgentOutcome,
1016 readiness: &AgentReadiness,
1017 faucet: &FaucetOutcome,
1018 webhook: &WebhookOutcome,
1019 dry_run: bool,
1020) -> serde_json::Value {
1021 let mut wallet_obj = json!({
1022 "status": wallet.tag(),
1023 });
1024 if let Some(addr) = wallet.address() {
1025 wallet_obj["address"] = json!(addr);
1026 }
1027 if let Some(path) = wallet.keystore_path() {
1028 wallet_obj["keystore_path"] = json!(path.display().to_string());
1029 }
1030
1031 let mut cfg_obj = json!({
1032 "path": cfg_path.display().to_string(),
1033 "written": config_written,
1034 });
1035 if dry_run && !config_written {
1036 cfg_obj["would_write"] = json!(true);
1037 }
1038
1039 let faucet_obj = match faucet {
1040 FaucetOutcome::Skipped { reason } => {
1041 let mut o = json!({
1042 "status": "skipped",
1043 "reason": reason,
1044 });
1045 if *reason == "mainnet" {
1049 o["funding_hint"] = json!({
1050 "url": "https://wallet.tempo.xyz",
1051 "message": "Production wallets must be funded manually by the owning human at wallet.tempo.xyz before posting or settling.",
1052 });
1053 }
1054 o
1055 }
1056 FaucetOutcome::Requested { drops } => json!({
1057 "status": "requested",
1058 "drops": drops.iter().map(|d| json!({
1059 "token": d.token,
1060 "tx_hash": d.tx_hash,
1061 })).collect::<Vec<_>>(),
1062 }),
1063 FaucetOutcome::Failed { error } => json!({
1064 "status": "failed",
1065 "error": error,
1066 }),
1067 };
1068
1069 let webhook_obj = match webhook {
1070 WebhookOutcome::Skipped => json!({ "status": "skipped" }),
1071 WebhookOutcome::DryRun {
1072 url,
1073 events,
1074 secret_file,
1075 } => {
1076 let mut o = json!({
1077 "status": "would_register",
1078 "url": url,
1079 "events": events,
1080 });
1081 if let Some(p) = secret_file {
1082 o["secret_file"] = json!(p.display().to_string());
1083 }
1084 o
1085 }
1086 WebhookOutcome::Registered {
1087 url,
1088 secret_returned,
1089 secret_persisted,
1090 secret_file,
1091 subscribed,
1092 } => {
1093 let mut o = json!({
1094 "status": "registered",
1095 "url": url,
1096 "secret_returned": secret_returned,
1097 "secret_persisted": secret_persisted,
1098 });
1099 if let Some(p) = secret_file {
1100 o["secret_file"] = json!(p.display().to_string());
1101 }
1102 if let Some(subs) = subscribed {
1103 o["subscribed"] = json!(subs);
1104 }
1105 o
1106 }
1107 WebhookOutcome::Failed { error } => json!({
1108 "status": "failed",
1109 "error": error,
1110 }),
1111 };
1112
1113 let mut out = json!({
1114 "wallet": wallet_obj,
1115 "config_file": cfg_obj,
1116 "faucet": faucet_obj,
1117 "webhook": webhook_obj,
1118 "readiness": readiness,
1119 "ready_to_work": readiness.ready_to_work,
1120 });
1121 if let AgentOutcome::Minted(MintedAgent::Live { id, name, .. }) = agent {
1122 let mut a = json!({ "action": "minted" });
1123 if let Some(id) = id {
1124 a["id"] = json!(id);
1125 }
1126 if let Some(name) = name {
1127 a["name"] = json!(name);
1128 }
1129 out["agent"] = a;
1130 }
1131 out
1132}
1133
1134#[cfg(test)]
1135mod tests {
1136 use super::*;
1137 use crate::Environment;
1138
1139 fn base_args() -> Args {
1140 Args {
1141 wallet_address: None,
1142 generate_wallet: false,
1143 wallet_password_file: None,
1144 keystore_path: None,
1145 skip_wallet: false,
1146 fund: false,
1147 human_api_key: None,
1148 agent_name: "taskfast-agent".into(),
1149 agent_description: "Headless agent registered via taskfast init".into(),
1150 agent_capabilities: Vec::new(),
1151 webhook_url: None,
1152 webhook_secret_file: None,
1153 webhook_events: Vec::new(),
1154 no_default_events: false,
1155 no_interactive: true,
1156 inline_wallet_password: None,
1157 }
1158 }
1159
1160 fn ctx_with_key(key: Option<&str>) -> Ctx {
1161 Ctx {
1162 api_key: key.map(String::from),
1163 environment: Environment::Local,
1164 api_base: None,
1165 config_path: PathBuf::from("/dev/null"),
1166 dry_run: false,
1167 quiet: true,
1168 ..Default::default()
1169 }
1170 }
1171
1172 fn cfg_with_key(key: Option<&str>) -> Config {
1173 Config {
1174 api_key: key.map(str::to_string),
1175 ..Config::default()
1176 }
1177 }
1178
1179 #[test]
1180 fn resolve_api_key_prefers_ctx_over_config() {
1181 let ctx = ctx_with_key(Some("from-flag"));
1182 let cfg = cfg_with_key(Some("from-file"));
1183 assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-flag");
1184 }
1185
1186 #[test]
1187 fn resolve_api_key_falls_back_to_config() {
1188 let ctx = ctx_with_key(None);
1189 let cfg = cfg_with_key(Some("from-file"));
1190 assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-file");
1191 }
1192
1193 #[test]
1194 fn resolve_api_key_empty_string_is_treated_as_absent() {
1195 let ctx = ctx_with_key(Some(""));
1196 let cfg = cfg_with_key(Some(""));
1197 match resolve_api_key(&ctx, &cfg) {
1198 Err(CmdError::MissingApiKey) => {}
1199 other => panic!("expected MissingApiKey, got {other:?}"),
1200 }
1201 }
1202
1203 #[test]
1204 fn provision_without_wallet_flag_errors_as_usage() {
1205 let args = base_args();
1209 assert!(args.wallet_address.is_none() && !args.generate_wallet);
1210 }
1213
1214 #[test]
1215 fn wallet_outcome_tag_is_stable() {
1216 assert_eq!(WalletOutcome::AlreadyConfigured.tag(), "already_configured");
1219 assert_eq!(
1220 WalletOutcome::ByoRegistered {
1221 address: "0x00".into()
1222 }
1223 .tag(),
1224 "byo_registered"
1225 );
1226 assert_eq!(
1227 WalletOutcome::Generated {
1228 address: "0x00".into(),
1229 keystore_path: PathBuf::from("/tmp/x")
1230 }
1231 .tag(),
1232 "generated"
1233 );
1234 assert_eq!(
1235 WalletOutcome::DryRunGenerated {
1236 address: "0x00".into()
1237 }
1238 .tag(),
1239 "dry_run_generated"
1240 );
1241 assert_eq!(WalletOutcome::Skipped.tag(), "skipped");
1242 }
1243
1244 #[test]
1245 fn resolve_webhook_events_uses_defaults_when_events_empty() {
1246 let args = Args {
1251 webhook_url: Some("https://h.example/x".into()),
1252 ..base_args()
1253 };
1254 let events = resolve_webhook_events(&args);
1255 assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1256 }
1257
1258 #[test]
1259 fn resolve_webhook_events_respects_no_default_events_opt_out() {
1260 let args = Args {
1262 webhook_url: Some("https://h.example/x".into()),
1263 no_default_events: true,
1264 ..base_args()
1265 };
1266 assert!(resolve_webhook_events(&args).is_empty());
1267 }
1268
1269 #[test]
1270 fn resolve_webhook_events_explicit_events_override_defaults() {
1271 let args = Args {
1273 webhook_url: Some("https://h.example/x".into()),
1274 webhook_events: vec!["task_assigned".into()],
1275 ..base_args()
1276 };
1277 assert_eq!(resolve_webhook_events(&args), vec!["task_assigned"]);
1278 }
1279
1280 #[test]
1281 fn resolve_webhook_events_explicit_events_win_over_no_default_events() {
1282 let args = Args {
1285 webhook_url: Some("https://h.example/x".into()),
1286 webhook_events: vec!["bid_accepted".into()],
1287 no_default_events: true,
1288 ..base_args()
1289 };
1290 assert_eq!(resolve_webhook_events(&args), vec!["bid_accepted"]);
1291 }
1292
1293 #[test]
1296 fn funding_warning_faucet_failure_lists_manual_fallback() {
1297 let w = build_funding_warning(
1298 Some("faucet returned status 405: method not allowed"),
1299 Some(0),
1300 "0xabc0000000000000000000000000000000000000",
1301 Some("https://rpc.testnet.example"),
1302 None,
1303 )
1304 .expect("faucet failure must warn");
1305 assert!(w.contains("faucet returned status 405"), "got: {w}");
1306 assert!(w.contains("0xabc0000000000000000000000000000000000000"));
1307 assert!(w.contains(
1308 "cast rpc tempo_fundAddress \
1309 '[\"0xabc0000000000000000000000000000000000000\"]' \
1310 --raw --rpc-url https://rpc.testnet.example"
1311 ));
1312 assert!(w.contains("https://wallet.tempo.xyz"));
1313 }
1314
1315 #[test]
1316 fn funding_warning_zero_balance_without_faucet_failure_still_warns() {
1317 let w = build_funding_warning(
1321 None,
1322 Some(0),
1323 "0xabc0000000000000000000000000000000000000",
1324 Some("https://rpc.testnet.example"),
1325 None,
1326 )
1327 .expect("zero balance must warn");
1328 assert!(w.contains("zero"), "got: {w}");
1329 assert!(w.contains("https://wallet.tempo.xyz"));
1330 }
1331
1332 #[test]
1333 fn funding_warning_silent_when_funded() {
1334 assert!(build_funding_warning(
1335 None,
1336 Some(42),
1337 "0xabc0000000000000000000000000000000000000",
1338 Some("https://rpc.testnet.example"),
1339 None,
1340 )
1341 .is_none());
1342 }
1343
1344 #[test]
1345 fn funding_warning_silent_when_balance_unknown_and_faucet_did_not_fail() {
1346 assert!(build_funding_warning(
1348 None,
1349 None,
1350 "0xabc0000000000000000000000000000000000000",
1351 Some("https://rpc.testnet.example"),
1352 None,
1353 )
1354 .is_none());
1355 }
1356
1357 #[test]
1358 fn funding_warning_without_rpc_url_omits_cast_line_keeps_web_fallback() {
1359 let w = build_funding_warning(
1360 Some("faucet http request failed"),
1361 Some(0),
1362 "0xabc0000000000000000000000000000000000000",
1363 None,
1364 None,
1365 )
1366 .expect("must still warn");
1367 assert!(!w.contains("cast rpc"), "got: {w}");
1368 assert!(w.contains("https://wallet.tempo.xyz"));
1369 }
1370
1371 #[test]
1372 fn funding_warning_surfaces_server_funding_hint() {
1373 let w = build_funding_warning(
1374 None,
1375 Some(0),
1376 "0xabc0000000000000000000000000000000000000",
1377 None,
1378 Some("https://wallet.tempo.xyz/topup"),
1379 )
1380 .expect("must warn");
1381 assert!(w.contains("https://wallet.tempo.xyz/topup"), "got: {w}");
1382 }
1383
1384 #[test]
1385 fn parse_wei_hex_handles_0x_zero_and_plain_hex_forms() {
1386 assert_eq!(parse_wei_hex(Some("0x0")), Some(0));
1387 assert_eq!(
1388 parse_wei_hex(Some(
1389 "0x000000000000000000000000000000000000000000000000000000000000000a"
1390 )),
1391 Some(10)
1392 );
1393 assert_eq!(parse_wei_hex(None), None);
1394 assert_eq!(parse_wei_hex(Some("0x")), None);
1395 }
1396
1397 #[tokio::test]
1398 async fn maybe_configure_webhook_dry_run_surfaces_default_events() {
1399 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1403 let args = Args {
1404 webhook_url: Some("https://h.example/x".into()),
1405 ..base_args()
1406 };
1407 let outcome = maybe_configure_webhook(&client, &args, true).await;
1408 match outcome {
1409 WebhookOutcome::DryRun { events, url, .. } => {
1410 assert_eq!(url, "https://h.example/x");
1411 assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1412 }
1413 other => panic!("expected DryRun, got {other:?}"),
1414 }
1415 }
1416
1417 #[tokio::test]
1418 async fn maybe_configure_webhook_dry_run_respects_no_default_events() {
1419 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1420 let args = Args {
1421 webhook_url: Some("https://h.example/x".into()),
1422 no_default_events: true,
1423 ..base_args()
1424 };
1425 let outcome = maybe_configure_webhook(&client, &args, true).await;
1426 match outcome {
1427 WebhookOutcome::DryRun { events, .. } => assert!(events.is_empty()),
1428 other => panic!("expected DryRun, got {other:?}"),
1429 }
1430 }
1431
1432 #[tokio::test]
1433 async fn maybe_configure_webhook_no_url_is_skipped() {
1434 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1437 let outcome = maybe_configure_webhook(&client, &base_args(), true).await;
1438 assert!(matches!(outcome, WebhookOutcome::Skipped));
1439 }
1440}