1use std::path::{Path, PathBuf};
50
51use clap::Parser;
52use serde_json::json;
53
54use super::{CmdError, CmdResult, Ctx};
55use crate::config::Config;
56use crate::envelope::Envelope;
57
58use alloy_signer_local::PrivateKeySigner;
59use taskfast_agent::bootstrap::{create_agent_headless, get_readiness, validate_auth};
60use taskfast_agent::faucet::{request_testnet_funds, FaucetDrop};
61use taskfast_agent::keystore;
62use taskfast_agent::wallet;
63use taskfast_agent::webhooks;
64use taskfast_client::api::types::{AgentCreateRequest, AgentReadiness, WebhookConfigRequest};
65use taskfast_client::TaskFastClient;
66
67use super::webhook::persist_secret;
68
69const WALLET_STATUS_COMPLETE: &str = "complete";
73
74#[derive(Debug, Parser)]
75#[allow(clippy::struct_excessive_bools)]
79pub struct Args {
80 #[arg(long, conflicts_with = "generate_wallet")]
83 pub wallet_address: Option<String>,
84
85 #[arg(long)]
88 pub generate_wallet: bool,
89
90 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
95 pub wallet_password_file: Option<PathBuf>,
96
97 #[arg(long)]
100 pub keystore_path: Option<PathBuf>,
101
102 #[arg(long)]
105 pub skip_wallet: bool,
106
107 #[arg(long)]
113 pub fund: bool,
114
115 #[arg(long, env = "TASKFAST_HUMAN_API_KEY")]
121 pub human_api_key: Option<String>,
122
123 #[arg(long, default_value = "taskfast-agent")]
125 pub agent_name: String,
126
127 #[arg(long, default_value = "Headless agent registered via taskfast init")]
129 pub agent_description: String,
130
131 #[arg(long = "agent-capability", value_name = "CAP")]
135 pub agent_capabilities: Vec<String>,
136
137 #[arg(long)]
143 pub webhook_url: Option<String>,
144
145 #[arg(long)]
150 pub webhook_secret_file: Option<PathBuf>,
151
152 #[arg(long = "webhook-event", value_name = "EVENT")]
159 pub webhook_events: Vec<String>,
160
161 #[arg(long)]
166 pub no_default_events: bool,
167
168 #[arg(long, env = "TASKFAST_NO_INTERACTIVE")]
172 pub no_interactive: bool,
173
174 #[arg(skip)]
180 pub inline_wallet_password: Option<String>,
181}
182
183pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
184 let interactive = !args.no_interactive && crate::cmd::init_tui::is_interactive();
185 run_with_prompter(
186 ctx,
187 args,
188 &crate::cmd::init_tui::DialoguerPrompter,
189 interactive,
190 )
191 .await
192}
193
194pub async fn run_with_prompter<P: crate::cmd::init_tui::Prompter>(
199 ctx: &Ctx,
200 mut args: Args,
201 prompter: &P,
202 interactive: bool,
203) -> CmdResult {
204 let cfg_path = ctx.config_path.clone();
205
206 let mut cfg = Config::load(&cfg_path)?;
210
211 let (api_key, agent_outcome) = match resolve_api_key(ctx, &cfg) {
220 Ok(k) => (k, AgentOutcome::PreExisting),
221 Err(CmdError::MissingApiKey) => {
222 let pat = resolve_pat(ctx, &args, interactive, prompter).await?;
223 let minted = mint_agent(ctx, &args, &pat).await?;
224 match minted {
225 MintedAgent::DryRun { ref intent } => {
226 return Ok(Envelope::success(
227 ctx.environment,
228 ctx.dry_run,
229 build_dry_run_mint_envelope(&cfg_path, intent),
230 ));
231 }
232 MintedAgent::Live { ref api_key, .. } => {
233 (api_key.clone(), AgentOutcome::Minted(minted))
234 }
235 }
236 }
237 Err(e) => return Err(e),
238 };
239
240 if interactive
247 && matches!(agent_outcome, AgentOutcome::Minted(_))
248 && args.wallet_address.is_none()
249 && !args.generate_wallet
250 && !args.skip_wallet
251 {
252 apply_wallet_mode_prompt(&mut args, prompter)?;
253 }
254
255 let effective_ctx = Ctx {
256 api_key: Some(api_key.clone()),
257 ..ctx.clone()
258 };
259 let client = effective_ctx.client()?;
260
261 let profile = match validate_auth(&client).await {
266 Ok(p) => p,
267 Err(taskfast_client::Error::Auth(msg))
268 if matches!(agent_outcome, AgentOutcome::PreExisting) =>
269 {
270 return Err(CmdError::Auth(stale_key_hint(
271 &msg, &cfg_path, &cfg, ctx, &args,
272 )));
273 }
274 Err(e) => return Err(CmdError::from(e)),
275 };
276 assert_active(&profile)?;
277 if !ctx.dry_run {
282 super::enforce_server_network_invariant(&effective_ctx, &client).await?;
283 }
284 let readiness = get_readiness(&client).await.map_err(CmdError::from)?;
285
286 let wallet_outcome = if args.skip_wallet {
288 WalletOutcome::Skipped
289 } else if readiness.checks.wallet.status == WALLET_STATUS_COMPLETE
290 && args.wallet_address.is_none()
291 && !args.generate_wallet
292 {
293 WalletOutcome::AlreadyConfigured
296 } else {
297 provision_wallet(&client, &args, ctx.dry_run).await?
298 };
299
300 cfg.environment = Some(ctx.environment);
305 cfg.api_key = Some(api_key.clone());
306 if let Some(addr) = wallet_outcome.address() {
307 cfg.wallet_address = Some(addr.to_string());
308 }
309 if let Some(path) = wallet_outcome.keystore_path() {
310 cfg.keystore_path = Some(path.to_path_buf());
311 }
312 if let AgentOutcome::Minted(MintedAgent::Live { id: Some(id), .. }) = &agent_outcome {
313 cfg.agent_id = Some(id.clone());
314 }
315 if let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) {
316 cfg.webhook_url = Some(url.to_string());
317 }
318 if let Some(path) = args.webhook_secret_file.as_ref() {
319 cfg.webhook_secret_path = Some(path.clone());
320 }
321
322 let config_written = if ctx.dry_run {
323 false
324 } else {
325 cfg.save(&cfg_path)?;
326 true
327 };
328
329 let faucet_outcome = maybe_request_faucet(
341 &args,
342 ctx.environment.network(),
343 &wallet_outcome,
344 ctx.dry_run,
345 )
346 .await;
347
348 let webhook_outcome = maybe_configure_webhook(&client, &args, ctx.dry_run).await;
353
354 let final_readiness = get_readiness(&client).await.map_err(CmdError::from)?;
357
358 let data = build_envelope_data(
359 &cfg_path,
360 config_written,
361 &wallet_outcome,
362 &agent_outcome,
363 &final_readiness,
364 &faucet_outcome,
365 &webhook_outcome,
366 ctx.dry_run,
367 );
368 Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
369}
370
371enum AgentOutcome {
376 PreExisting,
377 Minted(MintedAgent),
378}
379
380enum MintedAgent {
384 Live {
385 api_key: String,
386 id: Option<String>,
387 name: Option<String>,
388 },
389 DryRun {
390 intent: MintIntent,
391 },
392}
393
394struct MintIntent {
395 name: String,
396 description: String,
397 capabilities: Vec<String>,
398}
399
400async fn resolve_pat<P: crate::cmd::init_tui::Prompter>(
405 ctx: &Ctx,
406 args: &Args,
407 interactive: bool,
408 prompter: &P,
409) -> Result<String, CmdError> {
410 if let Some(p) = args.human_api_key.as_deref().filter(|s| !s.is_empty()) {
411 return Ok(p.to_string());
412 }
413 if !interactive {
414 return Err(CmdError::MissingApiKey);
415 }
416 let accounts_url = crate::accounts_url(ctx.base_url());
417 let pat = prompter
418 .pat(&accounts_url)
419 .map_err(|e| CmdError::Usage(format!("PAT prompt failed: {e}")))?;
420 let pat_client = TaskFastClient::from_api_key(ctx.base_url(), &pat).map_err(CmdError::from)?;
424 let profile = pat_client.get_user_profile().await.ok().flatten();
425 eprintln!("{}", crate::cmd::init_tui::greeting(profile.as_ref()));
426 Ok(pat)
427}
428
429fn apply_wallet_mode_prompt<P: crate::cmd::init_tui::Prompter>(
433 args: &mut Args,
434 prompter: &P,
435) -> Result<(), CmdError> {
436 use crate::cmd::init_tui::WalletMode;
437 let mode = prompter
438 .wallet_mode()
439 .map_err(|e| CmdError::Usage(format!("wallet-mode prompt failed: {e}")))?;
440 match mode {
441 WalletMode::Byow => {
442 let addr = prompter
443 .wallet_address()
444 .map_err(|e| CmdError::Usage(format!("wallet-address prompt failed: {e}")))?;
445 args.wallet_address = Some(addr.trim().to_string());
446 }
447 WalletMode::Generate => {
448 args.generate_wallet = true;
449 let pw = prompter
450 .wallet_password()
451 .map_err(|e| CmdError::Usage(format!("password prompt failed: {e}")))?;
452 args.inline_wallet_password = Some(pw);
453 }
454 WalletMode::Skip => {
455 args.skip_wallet = true;
456 }
457 }
458 Ok(())
459}
460
461async fn mint_agent(ctx: &Ctx, args: &Args, pat: &str) -> Result<MintedAgent, CmdError> {
462 if pat.is_empty() {
463 return Err(CmdError::Usage("PAT is empty".into()));
464 }
465
466 let capabilities = if args.agent_capabilities.is_empty() {
467 vec!["general".to_string()]
468 } else {
469 args.agent_capabilities.clone()
470 };
471
472 if ctx.dry_run {
473 return Ok(MintedAgent::DryRun {
474 intent: MintIntent {
475 name: args.agent_name.clone(),
476 description: args.agent_description.clone(),
477 capabilities,
478 },
479 });
480 }
481
482 let pat_client = TaskFastClient::from_api_key(ctx.base_url(), pat).map_err(CmdError::from)?;
483 let body = AgentCreateRequest {
484 owner_id: None,
485 name: args.agent_name.clone(),
486 description: args.agent_description.clone(),
487 capabilities,
488 rate: None,
489 max_task_budget: None,
490 daily_spend_limit: None,
491 payout_method: None,
492 payment_method: None,
493 tempo_wallet_address: None,
494 };
495 let resp = create_agent_headless(&pat_client, &body)
496 .await
497 .map_err(CmdError::from)?;
498 let api_key = resp
499 .api_key
500 .clone()
501 .ok_or_else(|| CmdError::Server("POST /agents returned no api_key despite 201".into()))?;
502 Ok(MintedAgent::Live {
503 api_key,
504 id: resp.id.map(|u| u.to_string()),
505 name: resp.name.clone(),
506 })
507}
508
509fn build_dry_run_mint_envelope(cfg_path: &Path, intent: &MintIntent) -> serde_json::Value {
510 json!({
511 "agent": {
512 "action": "would_mint",
513 "name": intent.name,
514 "description": intent.description,
515 "capabilities": intent.capabilities,
516 },
517 "config_file": {
518 "path": cfg_path.display().to_string(),
519 "written": false,
520 "would_write": true,
521 },
522 "ready_to_work": false,
523 })
524}
525
526fn resolve_api_key(ctx: &Ctx, cfg: &Config) -> Result<String, CmdError> {
535 if let Some(k) = ctx.api_key.as_deref() {
536 if !k.is_empty() {
537 return Ok(k.to_string());
538 }
539 }
540 if let Some(k) = cfg.api_key.as_deref() {
541 if !k.is_empty() {
542 return Ok(k.to_string());
543 }
544 }
545 Err(CmdError::MissingApiKey)
546}
547
548fn stale_key_hint(msg: &str, cfg_path: &Path, cfg: &Config, ctx: &Ctx, args: &Args) -> String {
552 let source = if cfg.api_key.as_deref().is_some_and(|k| !k.is_empty()) {
553 format!("config file {}", cfg_path.display())
554 } else if ctx.api_key.is_some() {
555 "--api-key flag or TASKFAST_API_KEY env".to_string()
556 } else {
557 "unknown".to_string()
558 };
559 let had_pat = args.human_api_key.is_some();
560 let pat_note = if had_pat {
561 "\n note: --human-api-key was provided but ignored because an existing api_key was found; \
562 the PAT mints a new agent only when no api_key is resolvable."
563 } else {
564 ""
565 };
566 format!(
567 "{msg}\n hint: agent api_key rejected — likely stale (agent deleted or key rotated).\n \
568 source: {source}\n fix: delete {path} (and unset TASKFAST_API_KEY if set), then re-run \
569 `taskfast --env {env} init --human-api-key <tf_user_...>` to mint a fresh agent.{pat_note}",
570 path = cfg_path.display(),
571 env = ctx.environment.as_str(),
572 )
573}
574
575fn assert_active(profile: &taskfast_client::api::types::AgentProfile) -> Result<(), CmdError> {
576 use taskfast_client::api::types::AgentProfileStatus;
577 match profile.status {
578 Some(AgentProfileStatus::Active) => Ok(()),
579 Some(other) => Err(CmdError::Validation {
580 code: "agent_not_active".into(),
581 message: format!("agent status is {other:?}; owner must reactivate"),
582 }),
583 None => Err(CmdError::Server(
584 "GET /agents/me returned no status field".into(),
585 )),
586 }
587}
588
589enum WalletOutcome {
591 AlreadyConfigured,
593 ByoRegistered { address: String },
595 Generated {
597 address: String,
598 keystore_path: PathBuf,
599 },
600 DryRunGenerated { address: String },
602 Skipped,
604}
605
606impl WalletOutcome {
607 fn address(&self) -> Option<&str> {
608 match self {
609 Self::ByoRegistered { address }
610 | Self::Generated { address, .. }
611 | Self::DryRunGenerated { address } => Some(address),
612 Self::AlreadyConfigured | Self::Skipped => None,
613 }
614 }
615
616 fn keystore_path(&self) -> Option<&Path> {
617 match self {
618 Self::Generated { keystore_path, .. } => Some(keystore_path),
619 _ => None,
620 }
621 }
622
623 fn tag(&self) -> &'static str {
624 match self {
625 Self::AlreadyConfigured => "already_configured",
626 Self::ByoRegistered { .. } => "byo_registered",
627 Self::Generated { .. } => "generated",
628 Self::DryRunGenerated { .. } => "dry_run_generated",
629 Self::Skipped => "skipped",
630 }
631 }
632}
633
634async fn provision_wallet(
635 client: &TaskFastClient,
636 args: &Args,
637 dry_run: bool,
638) -> Result<WalletOutcome, CmdError> {
639 if let Some(addr) = args.wallet_address.as_deref() {
640 if dry_run {
641 return Ok(WalletOutcome::Skipped);
642 }
643 wallet::register_wallet(client, addr)
644 .await
645 .map_err(CmdError::from)?;
646 return Ok(WalletOutcome::ByoRegistered {
647 address: addr.to_string(),
648 });
649 }
650 if !args.generate_wallet {
651 return Err(CmdError::Usage(
652 "pass --wallet-address <0x...> or --generate-wallet (or --skip-wallet to defer)".into(),
653 ));
654 }
655
656 let signer = wallet::generate_signer();
657 let address = format!("0x{}", hex::encode(signer.address().as_slice()));
658
659 if dry_run {
660 return Ok(WalletOutcome::DryRunGenerated { address });
663 }
664
665 let password = resolve_wallet_password(args)?;
666 let keystore_path = persist_keystore(&signer, args, &password)?;
667 wallet::register_wallet(client, &address)
668 .await
669 .map_err(CmdError::from)?;
670 Ok(WalletOutcome::Generated {
671 address,
672 keystore_path,
673 })
674}
675
676fn resolve_wallet_password(args: &Args) -> Result<String, CmdError> {
677 if let Some(pw) = args.inline_wallet_password.as_deref() {
680 if !pw.is_empty() {
681 return Ok(pw.to_string());
682 }
683 }
684 if let Ok(pw) = std::env::var("TASKFAST_WALLET_PASSWORD") {
685 if !pw.is_empty() {
686 return Ok(pw);
687 }
688 }
689 let path = args.wallet_password_file.as_deref().ok_or_else(|| {
690 CmdError::Usage(
691 "--generate-wallet requires --wallet-password-file or TASKFAST_WALLET_PASSWORD".into(),
692 )
693 })?;
694 let raw = std::fs::read_to_string(path).map_err(|e| {
695 CmdError::Usage(format!(
696 "cannot read wallet password file {}: {e}",
697 path.display()
698 ))
699 })?;
700 let trimmed = raw.trim_end_matches(['\n', '\r']);
701 if trimmed.is_empty() {
702 return Err(CmdError::Usage(format!(
703 "wallet password file {} is empty",
704 path.display()
705 )));
706 }
707 Ok(trimmed.to_string())
708}
709
710fn persist_keystore(
711 signer: &PrivateKeySigner,
712 args: &Args,
713 password: &str,
714) -> Result<PathBuf, CmdError> {
715 let path = match &args.keystore_path {
716 Some(p) => p.clone(),
717 None => keystore::default_keyfile_path(signer.address()).map_err(CmdError::from)?,
718 };
719 keystore::save_signer(signer, &path, password).map_err(CmdError::from)
720}
721
722enum FaucetOutcome {
727 Skipped { reason: &'static str },
728 Requested { drops: Vec<FaucetDrop> },
729 Failed { error: String },
730}
731
732async fn maybe_request_faucet(
733 args: &Args,
734 network: crate::Network,
735 wallet: &WalletOutcome,
736 dry_run: bool,
737) -> FaucetOutcome {
738 if dry_run {
739 return FaucetOutcome::Skipped { reason: "dry_run" };
740 }
741 if !args.fund {
742 return FaucetOutcome::Skipped {
743 reason: "fund_flag_not_set",
744 };
745 }
746 if !matches!(network, crate::Network::Testnet) {
747 return FaucetOutcome::Skipped { reason: "mainnet" };
748 }
749 let address = match wallet {
750 WalletOutcome::Generated { address, .. } => address.clone(),
751 WalletOutcome::ByoRegistered { address } => address.clone(),
752 _ => {
753 return FaucetOutcome::Skipped {
754 reason: "no_fresh_wallet",
755 };
756 }
757 };
758 let http = reqwest::Client::new();
759 match request_testnet_funds(&http, &address).await {
760 Ok(drops) => FaucetOutcome::Requested { drops },
761 Err(e) => FaucetOutcome::Failed {
762 error: e.to_string(),
763 },
764 }
765}
766
767#[cfg_attr(test, derive(Debug))]
772enum WebhookOutcome {
773 Skipped,
774 DryRun {
775 url: String,
776 events: Vec<String>,
777 secret_file: Option<PathBuf>,
778 },
779 Registered {
780 url: String,
781 secret_returned: bool,
782 secret_persisted: bool,
783 secret_file: Option<PathBuf>,
784 subscribed: Option<Vec<String>>,
785 },
786 Failed {
787 error: String,
788 },
789}
790
791fn resolve_webhook_events(args: &Args) -> Vec<String> {
799 if !args.webhook_events.is_empty() {
800 return args.webhook_events.clone();
801 }
802 if args.no_default_events {
803 return Vec::new();
804 }
805 crate::cmd::webhook::DEFAULT_WORKER_EVENTS
806 .iter()
807 .map(|s| (*s).to_string())
808 .collect()
809}
810
811async fn maybe_configure_webhook(
812 client: &TaskFastClient,
813 args: &Args,
814 dry_run: bool,
815) -> WebhookOutcome {
816 let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) else {
817 return WebhookOutcome::Skipped;
818 };
819 let events = resolve_webhook_events(args);
820 if dry_run {
821 return WebhookOutcome::DryRun {
822 url: url.to_string(),
823 events,
824 secret_file: args.webhook_secret_file.clone(),
825 };
826 }
827 let body = WebhookConfigRequest {
828 url: url.to_string(),
829 secret: None,
830 events: None,
831 };
832 let cfg = match webhooks::configure_webhook(client, &body).await {
833 Ok(c) => c,
834 Err(e) => {
835 return WebhookOutcome::Failed {
836 error: e.to_string(),
837 };
838 }
839 };
840 let secret_persisted = match (cfg.secret.as_deref(), args.webhook_secret_file.as_ref()) {
841 (Some(secret), Some(path)) => match persist_secret(path, secret) {
842 Ok(()) => true,
843 Err(e) => {
844 return WebhookOutcome::Failed {
845 error: e.to_string(),
846 };
847 }
848 },
849 _ => false,
850 };
851 let subscribed = if events.is_empty() {
852 None
853 } else {
854 match webhooks::update_subscriptions(client, events).await {
855 Ok(subs) => Some(subs.subscribed_event_types),
856 Err(e) => {
857 return WebhookOutcome::Failed {
858 error: e.to_string(),
859 };
860 }
861 }
862 };
863 WebhookOutcome::Registered {
864 url: cfg.url,
865 secret_returned: cfg.secret.is_some(),
866 secret_persisted,
867 secret_file: args.webhook_secret_file.clone(),
868 subscribed,
869 }
870}
871
872fn build_envelope_data(
873 cfg_path: &Path,
874 config_written: bool,
875 wallet: &WalletOutcome,
876 agent: &AgentOutcome,
877 readiness: &AgentReadiness,
878 faucet: &FaucetOutcome,
879 webhook: &WebhookOutcome,
880 dry_run: bool,
881) -> serde_json::Value {
882 let mut wallet_obj = json!({
883 "status": wallet.tag(),
884 });
885 if let Some(addr) = wallet.address() {
886 wallet_obj["address"] = json!(addr);
887 }
888 if let Some(path) = wallet.keystore_path() {
889 wallet_obj["keystore_path"] = json!(path.display().to_string());
890 }
891
892 let mut cfg_obj = json!({
893 "path": cfg_path.display().to_string(),
894 "written": config_written,
895 });
896 if dry_run && !config_written {
897 cfg_obj["would_write"] = json!(true);
898 }
899
900 let faucet_obj = match faucet {
901 FaucetOutcome::Skipped { reason } => {
902 let mut o = json!({
903 "status": "skipped",
904 "reason": reason,
905 });
906 if *reason == "mainnet" {
910 o["funding_hint"] = json!({
911 "url": "https://wallet.tempo.xyz",
912 "message": "Production wallets must be funded manually by the owning human at wallet.tempo.xyz before posting or settling.",
913 });
914 }
915 o
916 }
917 FaucetOutcome::Requested { drops } => json!({
918 "status": "requested",
919 "drops": drops.iter().map(|d| json!({
920 "token": d.token,
921 "tx_hash": d.tx_hash,
922 })).collect::<Vec<_>>(),
923 }),
924 FaucetOutcome::Failed { error } => json!({
925 "status": "failed",
926 "error": error,
927 }),
928 };
929
930 let webhook_obj = match webhook {
931 WebhookOutcome::Skipped => json!({ "status": "skipped" }),
932 WebhookOutcome::DryRun {
933 url,
934 events,
935 secret_file,
936 } => {
937 let mut o = json!({
938 "status": "would_register",
939 "url": url,
940 "events": events,
941 });
942 if let Some(p) = secret_file {
943 o["secret_file"] = json!(p.display().to_string());
944 }
945 o
946 }
947 WebhookOutcome::Registered {
948 url,
949 secret_returned,
950 secret_persisted,
951 secret_file,
952 subscribed,
953 } => {
954 let mut o = json!({
955 "status": "registered",
956 "url": url,
957 "secret_returned": secret_returned,
958 "secret_persisted": secret_persisted,
959 });
960 if let Some(p) = secret_file {
961 o["secret_file"] = json!(p.display().to_string());
962 }
963 if let Some(subs) = subscribed {
964 o["subscribed"] = json!(subs);
965 }
966 o
967 }
968 WebhookOutcome::Failed { error } => json!({
969 "status": "failed",
970 "error": error,
971 }),
972 };
973
974 let mut out = json!({
975 "wallet": wallet_obj,
976 "config_file": cfg_obj,
977 "faucet": faucet_obj,
978 "webhook": webhook_obj,
979 "readiness": readiness,
980 "ready_to_work": readiness.ready_to_work,
981 });
982 if let AgentOutcome::Minted(MintedAgent::Live { id, name, .. }) = agent {
983 let mut a = json!({ "action": "minted" });
984 if let Some(id) = id {
985 a["id"] = json!(id);
986 }
987 if let Some(name) = name {
988 a["name"] = json!(name);
989 }
990 out["agent"] = a;
991 }
992 out
993}
994
995#[cfg(test)]
996mod tests {
997 use super::*;
998 use crate::Environment;
999
1000 fn base_args() -> Args {
1001 Args {
1002 wallet_address: None,
1003 generate_wallet: false,
1004 wallet_password_file: None,
1005 keystore_path: None,
1006 skip_wallet: false,
1007 fund: false,
1008 human_api_key: None,
1009 agent_name: "taskfast-agent".into(),
1010 agent_description: "Headless agent registered via taskfast init".into(),
1011 agent_capabilities: Vec::new(),
1012 webhook_url: None,
1013 webhook_secret_file: None,
1014 webhook_events: Vec::new(),
1015 no_default_events: false,
1016 no_interactive: true,
1017 inline_wallet_password: None,
1018 }
1019 }
1020
1021 fn ctx_with_key(key: Option<&str>) -> Ctx {
1022 Ctx {
1023 api_key: key.map(String::from),
1024 environment: Environment::Local,
1025 api_base: None,
1026 config_path: PathBuf::from("/dev/null"),
1027 dry_run: false,
1028 quiet: true,
1029 ..Default::default()
1030 }
1031 }
1032
1033 fn cfg_with_key(key: Option<&str>) -> Config {
1034 Config {
1035 api_key: key.map(str::to_string),
1036 ..Config::default()
1037 }
1038 }
1039
1040 #[test]
1041 fn resolve_api_key_prefers_ctx_over_config() {
1042 let ctx = ctx_with_key(Some("from-flag"));
1043 let cfg = cfg_with_key(Some("from-file"));
1044 assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-flag");
1045 }
1046
1047 #[test]
1048 fn resolve_api_key_falls_back_to_config() {
1049 let ctx = ctx_with_key(None);
1050 let cfg = cfg_with_key(Some("from-file"));
1051 assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-file");
1052 }
1053
1054 #[test]
1055 fn resolve_api_key_empty_string_is_treated_as_absent() {
1056 let ctx = ctx_with_key(Some(""));
1057 let cfg = cfg_with_key(Some(""));
1058 match resolve_api_key(&ctx, &cfg) {
1059 Err(CmdError::MissingApiKey) => {}
1060 other => panic!("expected MissingApiKey, got {other:?}"),
1061 }
1062 }
1063
1064 #[test]
1065 fn provision_without_wallet_flag_errors_as_usage() {
1066 let args = base_args();
1070 assert!(args.wallet_address.is_none() && !args.generate_wallet);
1071 }
1074
1075 #[test]
1076 fn wallet_outcome_tag_is_stable() {
1077 assert_eq!(WalletOutcome::AlreadyConfigured.tag(), "already_configured");
1080 assert_eq!(
1081 WalletOutcome::ByoRegistered {
1082 address: "0x00".into()
1083 }
1084 .tag(),
1085 "byo_registered"
1086 );
1087 assert_eq!(
1088 WalletOutcome::Generated {
1089 address: "0x00".into(),
1090 keystore_path: PathBuf::from("/tmp/x")
1091 }
1092 .tag(),
1093 "generated"
1094 );
1095 assert_eq!(
1096 WalletOutcome::DryRunGenerated {
1097 address: "0x00".into()
1098 }
1099 .tag(),
1100 "dry_run_generated"
1101 );
1102 assert_eq!(WalletOutcome::Skipped.tag(), "skipped");
1103 }
1104
1105 #[test]
1106 fn resolve_webhook_events_uses_defaults_when_events_empty() {
1107 let args = Args {
1112 webhook_url: Some("https://h.example/x".into()),
1113 ..base_args()
1114 };
1115 let events = resolve_webhook_events(&args);
1116 assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1117 }
1118
1119 #[test]
1120 fn resolve_webhook_events_respects_no_default_events_opt_out() {
1121 let args = Args {
1123 webhook_url: Some("https://h.example/x".into()),
1124 no_default_events: true,
1125 ..base_args()
1126 };
1127 assert!(resolve_webhook_events(&args).is_empty());
1128 }
1129
1130 #[test]
1131 fn resolve_webhook_events_explicit_events_override_defaults() {
1132 let args = Args {
1134 webhook_url: Some("https://h.example/x".into()),
1135 webhook_events: vec!["task_assigned".into()],
1136 ..base_args()
1137 };
1138 assert_eq!(resolve_webhook_events(&args), vec!["task_assigned"]);
1139 }
1140
1141 #[test]
1142 fn resolve_webhook_events_explicit_events_win_over_no_default_events() {
1143 let args = Args {
1146 webhook_url: Some("https://h.example/x".into()),
1147 webhook_events: vec!["bid_accepted".into()],
1148 no_default_events: true,
1149 ..base_args()
1150 };
1151 assert_eq!(resolve_webhook_events(&args), vec!["bid_accepted"]);
1152 }
1153
1154 #[tokio::test]
1155 async fn maybe_configure_webhook_dry_run_surfaces_default_events() {
1156 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1160 let args = Args {
1161 webhook_url: Some("https://h.example/x".into()),
1162 ..base_args()
1163 };
1164 let outcome = maybe_configure_webhook(&client, &args, true).await;
1165 match outcome {
1166 WebhookOutcome::DryRun { events, url, .. } => {
1167 assert_eq!(url, "https://h.example/x");
1168 assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
1169 }
1170 other => panic!("expected DryRun, got {other:?}"),
1171 }
1172 }
1173
1174 #[tokio::test]
1175 async fn maybe_configure_webhook_dry_run_respects_no_default_events() {
1176 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1177 let args = Args {
1178 webhook_url: Some("https://h.example/x".into()),
1179 no_default_events: true,
1180 ..base_args()
1181 };
1182 let outcome = maybe_configure_webhook(&client, &args, true).await;
1183 match outcome {
1184 WebhookOutcome::DryRun { events, .. } => assert!(events.is_empty()),
1185 other => panic!("expected DryRun, got {other:?}"),
1186 }
1187 }
1188
1189 #[tokio::test]
1190 async fn maybe_configure_webhook_no_url_is_skipped() {
1191 let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
1194 let outcome = maybe_configure_webhook(&client, &base_args(), true).await;
1195 assert!(matches!(outcome, WebhookOutcome::Skipped));
1196 }
1197}