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 use taskfast_client::api::types::AgentProfileStatus;
598 match profile.status {
599 Some(AgentProfileStatus::Active) => Ok(()),
600 Some(other) => Err(CmdError::Validation {
601 code: "agent_not_active".into(),
602 message: format!("agent status is {other:?}; owner must reactivate"),
603 }),
604 None => Err(CmdError::Server(
605 "GET /agents/me returned no status field".into(),
606 )),
607 }
608}
609
610enum WalletOutcome {
612 AlreadyConfigured,
614 ByoRegistered { address: String },
616 Generated {
618 address: String,
619 keystore_path: PathBuf,
620 },
621 DryRunGenerated { address: String },
623 Skipped,
625}
626
627impl WalletOutcome {
628 fn address(&self) -> Option<&str> {
629 match self {
630 Self::ByoRegistered { address }
631 | Self::Generated { address, .. }
632 | Self::DryRunGenerated { address } => Some(address),
633 Self::AlreadyConfigured | Self::Skipped => None,
634 }
635 }
636
637 fn keystore_path(&self) -> Option<&Path> {
638 match self {
639 Self::Generated { keystore_path, .. } => Some(keystore_path),
640 _ => None,
641 }
642 }
643
644 fn tag(&self) -> &'static str {
645 match self {
646 Self::AlreadyConfigured => "already_configured",
647 Self::ByoRegistered { .. } => "byo_registered",
648 Self::Generated { .. } => "generated",
649 Self::DryRunGenerated { .. } => "dry_run_generated",
650 Self::Skipped => "skipped",
651 }
652 }
653}
654
655async fn provision_wallet(
656 client: &TaskFastClient,
657 args: &Args,
658 dry_run: bool,
659) -> Result<WalletOutcome, CmdError> {
660 if let Some(addr) = args.wallet_address.as_deref() {
661 if dry_run {
662 return Ok(WalletOutcome::Skipped);
663 }
664 wallet::register_wallet(client, addr)
665 .await
666 .map_err(CmdError::from)?;
667 return Ok(WalletOutcome::ByoRegistered {
668 address: addr.to_string(),
669 });
670 }
671 if !args.generate_wallet {
672 return Err(CmdError::Usage(
673 "pass --wallet-address <0x...> or --generate-wallet (or --skip-wallet to defer)".into(),
674 ));
675 }
676
677 let signer = wallet::generate_signer();
678 let address = format!("0x{}", hex::encode(signer.address().as_slice()));
679
680 if dry_run {
681 return Ok(WalletOutcome::DryRunGenerated { address });
684 }
685
686 let password = resolve_wallet_password(args)?;
687 let keystore_path = persist_keystore(&signer, args, &password)?;
688 wallet::register_wallet(client, &address)
689 .await
690 .map_err(CmdError::from)?;
691 Ok(WalletOutcome::Generated {
692 address,
693 keystore_path,
694 })
695}
696
697fn resolve_wallet_password(args: &Args) -> Result<String, CmdError> {
698 if let Some(pw) = args.inline_wallet_password.as_deref() {
701 if !pw.is_empty() {
702 return Ok(pw.to_string());
703 }
704 }
705 if let Ok(pw) = std::env::var("TASKFAST_WALLET_PASSWORD") {
706 if !pw.is_empty() {
707 return Ok(pw);
708 }
709 }
710 let path = args.wallet_password_file.as_deref().ok_or_else(|| {
711 CmdError::Usage(
712 "--generate-wallet requires --wallet-password-file or TASKFAST_WALLET_PASSWORD".into(),
713 )
714 })?;
715 let raw = std::fs::read_to_string(path).map_err(|e| {
716 CmdError::Usage(format!(
717 "cannot read wallet password file {}: {e}",
718 path.display()
719 ))
720 })?;
721 let trimmed = raw.trim_end_matches(['\n', '\r']);
722 if trimmed.is_empty() {
723 return Err(CmdError::Usage(format!(
724 "wallet password file {} is empty",
725 path.display()
726 )));
727 }
728 Ok(trimmed.to_string())
729}
730
731fn persist_keystore(
732 signer: &PrivateKeySigner,
733 args: &Args,
734 password: &str,
735) -> Result<PathBuf, CmdError> {
736 let path = match &args.keystore_path {
737 Some(p) => p.clone(),
738 None => keystore::default_keyfile_path(signer.address()).map_err(CmdError::from)?,
739 };
740 keystore::save_signer(signer, &path, password).map_err(CmdError::from)
741}
742
743enum FaucetOutcome {
748 Skipped { reason: &'static str },
749 Requested { drops: Vec<FaucetDrop> },
750 Failed { error: String },
751}
752
753async fn maybe_request_faucet(
754 args: &Args,
755 network: crate::Network,
756 wallet: &WalletOutcome,
757 dry_run: bool,
758) -> FaucetOutcome {
759 if dry_run {
760 return FaucetOutcome::Skipped { reason: "dry_run" };
761 }
762 if !args.fund {
763 return FaucetOutcome::Skipped {
764 reason: "fund_flag_not_set",
765 };
766 }
767 if !matches!(network, crate::Network::Testnet) {
768 return FaucetOutcome::Skipped { reason: "mainnet" };
769 }
770 let address = match wallet {
771 WalletOutcome::Generated { address, .. } => address.clone(),
772 WalletOutcome::ByoRegistered { address } => address.clone(),
773 _ => {
774 return FaucetOutcome::Skipped {
775 reason: "no_fresh_wallet",
776 };
777 }
778 };
779 let http = reqwest::Client::new();
780 match request_testnet_funds(&http, &address).await {
781 Ok(drops) => FaucetOutcome::Requested { drops },
782 Err(e) => FaucetOutcome::Failed {
783 error: e.to_string(),
784 },
785 }
786}
787
788fn parse_wei_hex(s: Option<&str>) -> Option<u128> {
791 let s = s?.trim();
792 let hex = s.strip_prefix("0x").unwrap_or(s);
793 if hex.is_empty() {
794 return None;
795 }
796 u128::from_str_radix(hex, 16).ok()
797}
798
799fn build_funding_warning(
805 faucet_error: Option<&str>,
806 balance_wei: Option<u128>,
807 address: &str,
808 rpc_url: Option<&str>,
809 funding_hint: Option<&str>,
810) -> Option<String> {
811 let zero_balance = balance_wei.is_some_and(|b| b == 0);
812 if faucet_error.is_none() && !zero_balance {
813 return None;
814 }
815 let mut lines = Vec::new();
816 match (faucet_error, zero_balance) {
817 (Some(err), _) => lines.push(format!(
818 "WARNING: testnet faucet funding failed (--fund): {err}"
819 )),
820 (None, true) => lines.push(format!(
821 "WARNING: wallet {address} balance is zero at the end of init"
822 )),
823 (None, false) => return None,
824 }
825 lines.push(
826 " the next on-chain command will fail until the wallet is funded. \
827 manual fallback:"
828 .to_string(),
829 );
830 if let Some(rpc) = rpc_url {
831 lines.push(format!(
832 " cast rpc tempo_fundAddress '[\"{address}\"]' --raw --rpc-url {rpc}"
833 ));
834 }
835 lines.push(" or fund at https://wallet.tempo.xyz".to_string());
836 if let Some(hint) = funding_hint {
837 lines.push(format!(" server funding hint: {hint}"));
838 }
839 Some(lines.join("\n"))
840}
841
842async fn warn_if_unfunded(
851 client: &TaskFastClient,
852 ctx: &Ctx,
853 wallet_address: Option<&str>,
854 faucet: &FaucetOutcome,
855 readiness: &AgentReadiness,
856) {
857 if ctx.dry_run {
858 return;
859 }
860 if !matches!(ctx.environment.network(), crate::Network::Testnet) {
861 return;
862 }
863 let Some(address) = wallet_address else {
864 return;
865 };
866 let faucet_error = match faucet {
867 FaucetOutcome::Failed { error } => Some(error.as_str()),
868 _ => None,
869 };
870 let balance_wei = match client.inner().get_wallet_balance().await {
871 Ok(resp) => parse_wei_hex(resp.into_inner().available_balance.as_deref()),
872 Err(e) => {
873 tracing::warn!(error = %e, "init: balance check unavailable; skipping zero-balance warning");
874 None
875 }
876 };
877 if build_funding_warning(
878 faucet_error,
879 balance_wei,
880 address,
881 None,
882 readiness.checks.funded.funding_hint.as_deref(),
883 )
884 .is_none()
885 {
886 return;
887 }
888 let rpc_url = client
891 .fetch_network_config()
892 .await
893 .ok()
894 .and_then(|cfg| cfg.entry(ctx.environment.network().as_str()).ok())
895 .map(|entry| entry.rpc_url.clone());
896 if let Some(warning) = build_funding_warning(
897 faucet_error,
898 balance_wei,
899 address,
900 rpc_url.as_deref(),
901 readiness.checks.funded.funding_hint.as_deref(),
902 ) {
903 eprintln!("{warning}");
904 }
905}
906
907#[cfg_attr(test, derive(Debug))]
912enum WebhookOutcome {
913 Skipped,
914 DryRun {
915 url: String,
916 events: Vec<String>,
917 secret_file: Option<PathBuf>,
918 },
919 Registered {
920 url: String,
921 secret_returned: bool,
922 secret_persisted: bool,
923 secret_file: Option<PathBuf>,
924 subscribed: Option<Vec<String>>,
925 },
926 Failed {
927 error: String,
928 },
929}
930
931fn resolve_webhook_events(args: &Args) -> Vec<String> {
939 if !args.webhook_events.is_empty() {
940 return args.webhook_events.clone();
941 }
942 if args.no_default_events {
943 return Vec::new();
944 }
945 crate::cmd::webhook::DEFAULT_WORKER_EVENTS
946 .iter()
947 .map(|s| (*s).to_string())
948 .collect()
949}
950
951async fn maybe_configure_webhook(
952 client: &TaskFastClient,
953 args: &Args,
954 dry_run: bool,
955) -> WebhookOutcome {
956 let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) else {
957 return WebhookOutcome::Skipped;
958 };
959 let events = resolve_webhook_events(args);
960 if dry_run {
961 return WebhookOutcome::DryRun {
962 url: url.to_string(),
963 events,
964 secret_file: args.webhook_secret_file.clone(),
965 };
966 }
967 let body = WebhookConfigRequest {
968 url: url.to_string(),
969 secret: None,
970 events: None,
971 };
972 let cfg = match webhooks::configure_webhook(client, &body).await {
973 Ok(c) => c,
974 Err(e) => {
975 return WebhookOutcome::Failed {
976 error: e.to_string(),
977 };
978 }
979 };
980 let secret_persisted = match (cfg.secret.as_deref(), args.webhook_secret_file.as_ref()) {
981 (Some(secret), Some(path)) => match persist_secret(path, secret) {
982 Ok(()) => true,
983 Err(e) => {
984 return WebhookOutcome::Failed {
985 error: e.to_string(),
986 };
987 }
988 },
989 _ => false,
990 };
991 let subscribed = if events.is_empty() {
992 None
993 } else {
994 match webhooks::update_subscriptions(client, events).await {
995 Ok(subs) => Some(subs.subscribed_event_types),
996 Err(e) => {
997 return WebhookOutcome::Failed {
998 error: e.to_string(),
999 };
1000 }
1001 }
1002 };
1003 WebhookOutcome::Registered {
1004 url: cfg.url,
1005 secret_returned: cfg.secret.is_some(),
1006 secret_persisted,
1007 secret_file: args.webhook_secret_file.clone(),
1008 subscribed,
1009 }
1010}
1011
1012fn build_envelope_data(
1013 cfg_path: &Path,
1014 config_written: bool,
1015 wallet: &WalletOutcome,
1016 agent: &AgentOutcome,
1017 readiness: &AgentReadiness,
1018 faucet: &FaucetOutcome,
1019 webhook: &WebhookOutcome,
1020 dry_run: bool,
1021) -> serde_json::Value {
1022 let mut wallet_obj = json!({
1023 "status": wallet.tag(),
1024 });
1025 if let Some(addr) = wallet.address() {
1026 wallet_obj["address"] = json!(addr);
1027 }
1028 if let Some(path) = wallet.keystore_path() {
1029 wallet_obj["keystore_path"] = json!(path.display().to_string());
1030 }
1031
1032 let mut cfg_obj = json!({
1033 "path": cfg_path.display().to_string(),
1034 "written": config_written,
1035 });
1036 if dry_run && !config_written {
1037 cfg_obj["would_write"] = json!(true);
1038 }
1039
1040 let faucet_obj = match faucet {
1041 FaucetOutcome::Skipped { reason } => {
1042 let mut o = json!({
1043 "status": "skipped",
1044 "reason": reason,
1045 });
1046 if *reason == "mainnet" {
1050 o["funding_hint"] = json!({
1051 "url": "https://wallet.tempo.xyz",
1052 "message": "Production wallets must be funded manually by the owning human at wallet.tempo.xyz before posting or settling.",
1053 });
1054 }
1055 o
1056 }
1057 FaucetOutcome::Requested { drops } => json!({
1058 "status": "requested",
1059 "drops": drops.iter().map(|d| json!({
1060 "token": d.token,
1061 "tx_hash": d.tx_hash,
1062 })).collect::<Vec<_>>(),
1063 }),
1064 FaucetOutcome::Failed { error } => json!({
1065 "status": "failed",
1066 "error": error,
1067 }),
1068 };
1069
1070 let webhook_obj = match webhook {
1071 WebhookOutcome::Skipped => json!({ "status": "skipped" }),
1072 WebhookOutcome::DryRun {
1073 url,
1074 events,
1075 secret_file,
1076 } => {
1077 let mut o = json!({
1078 "status": "would_register",
1079 "url": url,
1080 "events": events,
1081 });
1082 if let Some(p) = secret_file {
1083 o["secret_file"] = json!(p.display().to_string());
1084 }
1085 o
1086 }
1087 WebhookOutcome::Registered {
1088 url,
1089 secret_returned,
1090 secret_persisted,
1091 secret_file,
1092 subscribed,
1093 } => {
1094 let mut o = json!({
1095 "status": "registered",
1096 "url": url,
1097 "secret_returned": secret_returned,
1098 "secret_persisted": secret_persisted,
1099 });
1100 if let Some(p) = secret_file {
1101 o["secret_file"] = json!(p.display().to_string());
1102 }
1103 if let Some(subs) = subscribed {
1104 o["subscribed"] = json!(subs);
1105 }
1106 o
1107 }
1108 WebhookOutcome::Failed { error } => json!({
1109 "status": "failed",
1110 "error": error,
1111 }),
1112 };
1113
1114 let mut out = json!({
1115 "wallet": wallet_obj,
1116 "config_file": cfg_obj,
1117 "faucet": faucet_obj,
1118 "webhook": webhook_obj,
1119 "readiness": readiness,
1120 "ready_to_work": readiness.ready_to_work,
1121 });
1122 if let AgentOutcome::Minted(MintedAgent::Live { id, name, .. }) = agent {
1123 let mut a = json!({ "action": "minted" });
1124 if let Some(id) = id {
1125 a["id"] = json!(id);
1126 }
1127 if let Some(name) = name {
1128 a["name"] = json!(name);
1129 }
1130 out["agent"] = a;
1131 }
1132 out
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137 use super::*;
1138 use crate::Environment;
1139
1140 fn base_args() -> Args {
1141 Args {
1142 wallet_address: None,
1143 generate_wallet: false,
1144 wallet_password_file: None,
1145 keystore_path: None,
1146 skip_wallet: false,
1147 fund: false,
1148 human_api_key: None,
1149 agent_name: "taskfast-agent".into(),
1150 agent_description: "Headless agent registered via taskfast init".into(),
1151 agent_capabilities: Vec::new(),
1152 webhook_url: None,
1153 webhook_secret_file: None,
1154 webhook_events: Vec::new(),
1155 no_default_events: false,
1156 no_interactive: true,
1157 inline_wallet_password: None,
1158 }
1159 }
1160
1161 fn ctx_with_key(key: Option<&str>) -> Ctx {
1162 Ctx {
1163 api_key: key.map(String::from),
1164 environment: Environment::Local,
1165 api_base: None,
1166 config_path: PathBuf::from("/dev/null"),
1167 dry_run: false,
1168 quiet: true,
1169 ..Default::default()
1170 }
1171 }
1172
1173 fn cfg_with_key(key: Option<&str>) -> Config {
1174 Config {
1175 api_key: key.map(str::to_string),
1176 ..Config::default()
1177 }
1178 }
1179
1180 #[test]
1181 fn resolve_api_key_prefers_ctx_over_config() {
1182 let ctx = ctx_with_key(Some("from-flag"));
1183 let cfg = cfg_with_key(Some("from-file"));
1184 assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-flag");
1185 }
1186
1187 #[test]
1188 fn resolve_api_key_falls_back_to_config() {
1189 let ctx = ctx_with_key(None);
1190 let cfg = cfg_with_key(Some("from-file"));
1191 assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-file");
1192 }
1193
1194 #[test]
1195 fn resolve_api_key_empty_string_is_treated_as_absent() {
1196 let ctx = ctx_with_key(Some(""));
1197 let cfg = cfg_with_key(Some(""));
1198 match resolve_api_key(&ctx, &cfg) {
1199 Err(CmdError::MissingApiKey) => {}
1200 other => panic!("expected MissingApiKey, got {other:?}"),
1201 }
1202 }
1203
1204 #[test]
1205 fn provision_without_wallet_flag_errors_as_usage() {
1206 let args = base_args();
1210 assert!(args.wallet_address.is_none() && !args.generate_wallet);
1211 }
1214
1215 #[test]
1216 fn wallet_outcome_tag_is_stable() {
1217 assert_eq!(WalletOutcome::AlreadyConfigured.tag(), "already_configured");
1220 assert_eq!(
1221 WalletOutcome::ByoRegistered {
1222 address: "0x00".into()
1223 }
1224 .tag(),
1225 "byo_registered"
1226 );
1227 assert_eq!(
1228 WalletOutcome::Generated {
1229 address: "0x00".into(),
1230 keystore_path: PathBuf::from("/tmp/x")
1231 }
1232 .tag(),
1233 "generated"
1234 );
1235 assert_eq!(
1236 WalletOutcome::DryRunGenerated {
1237 address: "0x00".into()
1238 }
1239 .tag(),
1240 "dry_run_generated"
1241 );
1242 assert_eq!(WalletOutcome::Skipped.tag(), "skipped");
1243 }
1244
1245 #[test]
1246 fn resolve_webhook_events_uses_defaults_when_events_empty() {
1247 let args = Args {
1252 webhook_url: Some("https://h.example/x".into()),
1253 ..base_args()
1254 };
1255 let events = resolve_webhook_events(&args);
1256 assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1257 }
1258
1259 #[test]
1260 fn resolve_webhook_events_respects_no_default_events_opt_out() {
1261 let args = Args {
1263 webhook_url: Some("https://h.example/x".into()),
1264 no_default_events: true,
1265 ..base_args()
1266 };
1267 assert!(resolve_webhook_events(&args).is_empty());
1268 }
1269
1270 #[test]
1271 fn resolve_webhook_events_explicit_events_override_defaults() {
1272 let args = Args {
1274 webhook_url: Some("https://h.example/x".into()),
1275 webhook_events: vec!["task_assigned".into()],
1276 ..base_args()
1277 };
1278 assert_eq!(resolve_webhook_events(&args), vec!["task_assigned"]);
1279 }
1280
1281 #[test]
1282 fn resolve_webhook_events_explicit_events_win_over_no_default_events() {
1283 let args = Args {
1286 webhook_url: Some("https://h.example/x".into()),
1287 webhook_events: vec!["bid_accepted".into()],
1288 no_default_events: true,
1289 ..base_args()
1290 };
1291 assert_eq!(resolve_webhook_events(&args), vec!["bid_accepted"]);
1292 }
1293
1294 #[test]
1297 fn funding_warning_faucet_failure_lists_manual_fallback() {
1298 let w = build_funding_warning(
1299 Some("faucet returned status 405: method not allowed"),
1300 Some(0),
1301 "0xabc0000000000000000000000000000000000000",
1302 Some("https://rpc.testnet.example"),
1303 None,
1304 )
1305 .expect("faucet failure must warn");
1306 assert!(w.contains("faucet returned status 405"), "got: {w}");
1307 assert!(w.contains("0xabc0000000000000000000000000000000000000"));
1308 assert!(w.contains(
1309 "cast rpc tempo_fundAddress \
1310 '[\"0xabc0000000000000000000000000000000000000\"]' \
1311 --raw --rpc-url https://rpc.testnet.example"
1312 ));
1313 assert!(w.contains("https://wallet.tempo.xyz"));
1314 }
1315
1316 #[test]
1317 fn funding_warning_zero_balance_without_faucet_failure_still_warns() {
1318 let w = build_funding_warning(
1322 None,
1323 Some(0),
1324 "0xabc0000000000000000000000000000000000000",
1325 Some("https://rpc.testnet.example"),
1326 None,
1327 )
1328 .expect("zero balance must warn");
1329 assert!(w.contains("zero"), "got: {w}");
1330 assert!(w.contains("https://wallet.tempo.xyz"));
1331 }
1332
1333 #[test]
1334 fn funding_warning_silent_when_funded() {
1335 assert!(build_funding_warning(
1336 None,
1337 Some(42),
1338 "0xabc0000000000000000000000000000000000000",
1339 Some("https://rpc.testnet.example"),
1340 None,
1341 )
1342 .is_none());
1343 }
1344
1345 #[test]
1346 fn funding_warning_silent_when_balance_unknown_and_faucet_did_not_fail() {
1347 assert!(build_funding_warning(
1349 None,
1350 None,
1351 "0xabc0000000000000000000000000000000000000",
1352 Some("https://rpc.testnet.example"),
1353 None,
1354 )
1355 .is_none());
1356 }
1357
1358 #[test]
1359 fn funding_warning_without_rpc_url_omits_cast_line_keeps_web_fallback() {
1360 let w = build_funding_warning(
1361 Some("faucet http request failed"),
1362 Some(0),
1363 "0xabc0000000000000000000000000000000000000",
1364 None,
1365 None,
1366 )
1367 .expect("must still warn");
1368 assert!(!w.contains("cast rpc"), "got: {w}");
1369 assert!(w.contains("https://wallet.tempo.xyz"));
1370 }
1371
1372 #[test]
1373 fn funding_warning_surfaces_server_funding_hint() {
1374 let w = build_funding_warning(
1375 None,
1376 Some(0),
1377 "0xabc0000000000000000000000000000000000000",
1378 None,
1379 Some("https://wallet.tempo.xyz/topup"),
1380 )
1381 .expect("must warn");
1382 assert!(w.contains("https://wallet.tempo.xyz/topup"), "got: {w}");
1383 }
1384
1385 #[test]
1386 fn parse_wei_hex_handles_0x_zero_and_plain_hex_forms() {
1387 assert_eq!(parse_wei_hex(Some("0x0")), Some(0));
1388 assert_eq!(
1389 parse_wei_hex(Some(
1390 "0x000000000000000000000000000000000000000000000000000000000000000a"
1391 )),
1392 Some(10)
1393 );
1394 assert_eq!(parse_wei_hex(None), None);
1395 assert_eq!(parse_wei_hex(Some("0x")), None);
1396 }
1397
1398 #[tokio::test]
1399 async fn maybe_configure_webhook_dry_run_surfaces_default_events() {
1400 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1404 let args = Args {
1405 webhook_url: Some("https://h.example/x".into()),
1406 ..base_args()
1407 };
1408 let outcome = maybe_configure_webhook(&client, &args, true).await;
1409 match outcome {
1410 WebhookOutcome::DryRun { events, url, .. } => {
1411 assert_eq!(url, "https://h.example/x");
1412 assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1413 }
1414 other => panic!("expected DryRun, got {other:?}"),
1415 }
1416 }
1417
1418 #[tokio::test]
1419 async fn maybe_configure_webhook_dry_run_respects_no_default_events() {
1420 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1421 let args = Args {
1422 webhook_url: Some("https://h.example/x".into()),
1423 no_default_events: true,
1424 ..base_args()
1425 };
1426 let outcome = maybe_configure_webhook(&client, &args, true).await;
1427 match outcome {
1428 WebhookOutcome::DryRun { events, .. } => assert!(events.is_empty()),
1429 other => panic!("expected DryRun, got {other:?}"),
1430 }
1431 }
1432
1433 #[tokio::test]
1434 async fn maybe_configure_webhook_no_url_is_skipped() {
1435 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1438 let outcome = maybe_configure_webhook(&client, &base_args(), true).await;
1439 assert!(matches!(outcome, WebhookOutcome::Skipped));
1440 }
1441}