Skip to main content

taskfast_cli/cmd/
init.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast init` — the onboarding command.
3//!
4//! Replaces `init.sh`'s step 1-9 orchestration with a non-interactive,
5//! CLI-driven flow. Every input comes from a flag, an env var, or the
6//! existing [`Config`] file — there are no TTY prompts, because the
7//! caller is expected to be another agent/LLM.
8//!
9//! # Scope (this slice, am-yvc)
10//!
11//! * api_key: direct via `--api-key` / `TASKFAST_API_KEY` / config file.
12//! * validate: `GET /agents/me` — must be active.
13//! * readiness: `GET /agents/me/readiness` — informs wallet gate.
14//! * wallet: BYOW via `--wallet-address`, or generate + keystore with a
15//!   password sourced from `--wallet-password-file` / `TASKFAST_WALLET_PASSWORD`.
16//! * config file: load + write at `ctx.config_path` (default
17//!   `./.taskfast/config.json`, chmod 600 on unix).
18//! * final readiness assert.
19//!
20//! # Scope (am-z58 extension)
21//!
22//! * `--human-api-key` (+ optional agent-* fields): when no agent key is
23//!   available, POST /agents with the user PAT to mint one. The server
24//!   derives `owner_id` from the PAT, so the CLI never asks the caller for
25//!   it. The minted `api_key` is then used for the rest of the flow and
26//!   written to the config file. Under `--dry-run` the mint is skipped and the
27//!   envelope reports `agent.action = "would_mint"` — the rest of the flow
28//!   is also skipped because the real agent key never materialized.
29//!
30//! # Scope (am-iit extension)
31//!
32//! * Optional `--webhook-url` (+ `--webhook-secret-file`, repeat
33//!   `--webhook-event`) folds webhook registration into the init run:
34//!   PUT /agents/me/webhooks, persist the returned secret (chmod 600),
35//!   and optionally replace the subscription list. Skipped silently
36//!   when the URL isn't supplied so callers who prefer a separate
37//!   `taskfast webhook register` step still get the pre-am-iit flow.
38//!
39//! Deferred to separate beads so this slice stays reviewable:
40//! * `am-c74` — balance polling after faucet dispense.
41//!
42//! # `--dry-run` semantics
43//!
44//! Mutations short-circuit: no wallet POST, no config file write, no
45//! keystore write. A wallet is still generated (so the address is real)
46//! but its signer is dropped at the end of the function. Readiness and
47//! profile reads pass through.
48
49use 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
69/// Wallet status string emitted by the server when the agent hasn't
70/// registered one yet. `AgentReadinessChecks.wallet.status == "complete"`
71/// means it's already done.
72const WALLET_STATUS_COMPLETE: &str = "complete";
73
74#[derive(Debug, Parser)]
75// CLI surface: each flag is an independent user opt-in/out. Collapsing
76// them into a state machine or nested enum would make clap's derive
77// macro unergonomic without narrowing the actual accepted inputs.
78#[allow(clippy::struct_excessive_bools)]
79pub struct Args {
80    /// Wallet address to register (BYOW). Mutually exclusive with
81    /// `--generate-wallet`.
82    #[arg(long, conflicts_with = "generate_wallet")]
83    pub wallet_address: Option<String>,
84
85    /// Generate a fresh keypair, persist it via the keystore module, then
86    /// register the derived address with TaskFast.
87    #[arg(long)]
88    pub generate_wallet: bool,
89
90    /// Path to a file containing the keystore password. Required when
91    /// `--generate-wallet` is used without `TASKFAST_WALLET_PASSWORD` set.
92    /// Prefer a mode-0400 file over `--wallet-password` (which leaks via
93    /// process args).
94    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
95    pub wallet_password_file: Option<PathBuf>,
96
97    /// Explicit keystore path override. Default: XDG data dir +
98    /// `<address>.json`.
99    #[arg(long)]
100    pub keystore_path: Option<PathBuf>,
101
102    /// Skip wallet provisioning entirely. Useful for workers that never
103    /// settle (rare) or for rebuilding config state without touching chain.
104    #[arg(long)]
105    pub skip_wallet: bool,
106
107    /// Opt in to the testnet faucet for a freshly-generated wallet on
108    /// testnet environments (Staging / Local). Off by default so prod
109    /// scripts (and CI flows supplying funds out-of-band) never
110    /// accidentally hit the faucet. No-op on Prod — mainnet is never
111    /// auto-funded.
112    #[arg(long)]
113    pub fund: bool,
114
115    /// User PAT (`tf_user_*`) used to headlessly mint a fresh agent via
116    /// `POST /agents` when no agent API key is available. The server
117    /// derives the owning user from the PAT, so no owner UUID is required.
118    /// Ignored if an agent key is already resolvable (direct flag / env
119    /// var / config file).
120    #[arg(long, env = "TASKFAST_HUMAN_API_KEY")]
121    pub human_api_key: Option<String>,
122
123    /// Display name for the minted agent.
124    #[arg(long, default_value = "taskfast-agent")]
125    pub agent_name: String,
126
127    /// Description for the minted agent.
128    #[arg(long, default_value = "Headless agent registered via taskfast init")]
129    pub agent_description: String,
130
131    /// Capability tag for the minted agent (repeat to pass multiple). If
132    /// none are provided, defaults to `["general"]` so the request still
133    /// satisfies the non-empty-array convention most consumers expect.
134    #[arg(long = "agent-capability", value_name = "CAP")]
135    pub agent_capabilities: Vec<String>,
136
137    /// HTTPS URL to register for webhook event delivery. When supplied,
138    /// init PUTs `/agents/me/webhooks` after the wallet step and (if
139    /// the server returns one) persists the signing secret to
140    /// `--webhook-secret-file`. Omitting this flag leaves webhooks
141    /// untouched — `taskfast webhook register` can configure them later.
142    #[arg(long)]
143    pub webhook_url: Option<String>,
144
145    /// Path to persist the webhook signing secret (chmod 600 on unix).
146    /// The platform returns the secret exactly once at creation time
147    /// — a fresh re-register with an existing config returns `null`
148    /// and the existing file is left untouched.
149    #[arg(long)]
150    pub webhook_secret_file: Option<PathBuf>,
151
152    /// Event type to subscribe to after webhook registration. Repeat
153    /// for multiple. Ignored unless `--webhook-url` is also set. When
154    /// `--webhook-url` is supplied and this flag is omitted, init
155    /// auto-subscribes to the worker default set (same list as
156    /// `taskfast webhook subscribe --default-events`); pass
157    /// `--no-default-events` to opt out and register a URL-only endpoint.
158    #[arg(long = "webhook-event", value_name = "EVENT")]
159    pub webhook_events: Vec<String>,
160
161    /// Opt out of auto-subscribing to default worker events when
162    /// `--webhook-url` is set without any explicit `--webhook-event`.
163    /// Preserves the pre-existing behavior of registering a URL with
164    /// zero subscriptions (a deliberate URL-only push endpoint).
165    #[arg(long)]
166    pub no_default_events: bool,
167
168    /// Disable all TTY prompts even when stdin is a terminal. Use in
169    /// scripts or pipes where interactive fallback would stall. Env:
170    /// `TASKFAST_NO_INTERACTIVE=1`.
171    #[arg(long, env = "TASKFAST_NO_INTERACTIVE")]
172    pub no_interactive: bool,
173
174    /// Inline keystore password populated by the interactive wallet-
175    /// generate prompt. Never exposed as a CLI arg (would leak via
176    /// process args). Takes precedence over `--wallet-password-file`
177    /// when set, so the prompted value round-trips into the normal
178    /// password-resolution path.
179    #[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
194/// Same as [`run`] but with an injectable [`crate::cmd::init_tui::Prompter`] and an explicit
195/// `interactive` gate so tests can drive the TUI branches under
196/// `cargo test` (where neither stdin nor stdout is a TTY). Production
197/// callers should use [`run`].
198pub 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    // 1. Load any existing config so re-running init is idempotent. A
207    //    config-supplied api_key is layered under the CLI/env sources
208    //    Ctx already resolved (flag > env var > config).
209    let mut cfg = Config::load(&cfg_path)?;
210
211    // 1a. Resolve the agent API key. If none is available but the caller
212    //     supplied a user PAT, mint a fresh agent headlessly and use the
213    //     returned key. Under --dry-run we short-circuit before the POST
214    //     and return early — the rest of the flow depends on a real key.
215    //
216    //     Interactive fallback: when no key and no --human-api-key, and
217    //     we're attached to a TTY, prompt the human for their PAT and
218    //     greet them via /users/me before minting.
219    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    // 1b. Interactive wallet-mode prompt. Only fires when this run just
241    //     minted a fresh agent AND the human gave us zero wallet signal
242    //     on the command line. Re-init against an existing agent key is
243    //     treated as silent (preserves `init_idempotent_on_reinit`) so
244    //     humans re-running `taskfast init` to refresh state don't get
245    //     re-prompted about wallet setup they already completed.
246    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    // 2. Validate auth + fetch readiness.
262    //    On Auth failure with a PreExisting key, rewrite the error with a
263    //    remediation hint — the common cause is a stale api_key left over in
264    //    the config from a prior init run whose agent was deleted server-side.
265    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    // Cross-system invariant — fail-closed before any wallet/agent state
278    // is written if the deployment advertises a different (or additional)
279    // network than the env mandates. Skipped under --dry-run so a `taskfast
280    // init --dry-run` still succeeds against a fresh deployment.
281    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    // 3. Wallet provisioning.
287    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        // Nothing to do — server already has a wallet and caller isn't
294        // forcing a new one.
295        WalletOutcome::AlreadyConfigured
296    } else {
297        provision_wallet(&client, &args, ctx.dry_run).await?
298    };
299
300    // 4. Update the config in-memory (always — writing is gated by dry-run).
301    //    `api_base` and `network` are no longer persisted — both are derived
302    //    from `environment` at runtime via `Environment::api_base` /
303    //    `Environment::network`.
304    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    // 4b. Testnet funding. When a wallet was just generated on `--network
330    //     testnet`, hit the public Tempo moderato faucet. Fire-and-surface:
331    //     we report the faucet's tx hashes in the envelope but don't block
332    //     on confirmation here. Caller-side balance polling lives under
333    //     am-c74.
334    //
335    //     Mainnet is deliberately skipped — production wallets must be
336    //     funded by the owning human at `https://wallet.tempo.xyz`. The
337    //     envelope surfaces this with `status: "skipped", reason: "mainnet"`
338    //     plus a `funding_hint` so orchestrators can tell the human where
339    //     to go.
340    let faucet_outcome = maybe_request_faucet(
341        &args,
342        ctx.environment.network(),
343        &wallet_outcome,
344        ctx.dry_run,
345    )
346    .await;
347
348    // 4c. Optional webhook registration. Only runs when `--webhook-url`
349    //     is provided; otherwise the envelope reports `status: "skipped"`
350    //     so orchestrators can tell the step ran and found nothing to do
351    //     (vs. the CLI not supporting webhooks at all).
352    let webhook_outcome = maybe_configure_webhook(&client, &args, ctx.dry_run).await;
353
354    // 5. Final readiness check — surfaces any remaining gates (webhook,
355    //    funding) the caller still has to clear.
356    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
371/// Result of the agent-key resolution step. When the caller already had
372/// a key (flag / env var / config file), this is `PreExisting` and the
373/// envelope stays quiet about it. When a key was minted via
374/// `--human-api-key`, the envelope surfaces the minted agent's id/name.
375enum AgentOutcome {
376    PreExisting,
377    Minted(MintedAgent),
378}
379
380/// Live vs dry-run distinction for minting. Live carries the full
381/// response; dry-run carries just the would-have-called payload so the
382/// envelope can echo it back without touching the network.
383enum 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
400/// Resolve the PAT used to mint a fresh agent. Priority: `--human-api-key`
401/// (flag / env) → interactive prompt (when TTY-attached). Absent both,
402/// propagate the original [`CmdError::MissingApiKey`] so non-interactive
403/// callers see the same message they did before the TUI landed.
404async 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    // Greet via /users/me when available. 404 (endpoint not yet deployed)
421    // falls back to a neutral confirmation — we never block the flow on
422    // the greeting.
423    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
429/// Drive the interactive wallet-mode prompt and fold the result back
430/// into `args` so the existing `provision_wallet` branches see the same
431/// state they would have after flag parsing.
432fn 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
526/// Layered api_key resolution: Ctx (flag / env var / already-merged
527/// config value) wins, then the on-disk config, else
528/// [`CmdError::MissingApiKey`].
529///
530/// `Ctx::from_parts` already folds `cfg.api_key` into `ctx.api_key`, so
531/// by the time we get here the config lookup is a redundant last resort
532/// — kept for the test-driven path that constructs `Ctx` directly
533/// without going through `from_parts`.
534fn 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
548/// Build a remediation hint for the common "stale config" failure: the agent
549/// api_key stored in the config (or passed via flag/env) is rejected by the
550/// server. Lists the key's likely source and the minimum steps to recover.
551fn 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
589/// Side-effect summary the CLI envelope surfaces to orchestrators.
590enum WalletOutcome {
591    /// Server already had a wallet on file and the caller didn't override.
592    AlreadyConfigured,
593    /// BYOW path — caller supplied `--wallet-address`.
594    ByoRegistered { address: String },
595    /// Generated keypair, saved to keystore, registered with server.
596    Generated {
597        address: String,
598        keystore_path: PathBuf,
599    },
600    /// Dry-run generate — address is real but keystore wasn't written.
601    DryRunGenerated { address: String },
602    /// `--skip-wallet` or dry-run BYOW without register.
603    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 the address without resolving the password or persisting;
661        // caller just needs to see what *would* have been generated.
662        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    // Interactive prompt populates this; takes precedence so the prompted
678    // value isn't second-guessed by a stale env var from a prior shell.
679    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
722/// Envelope-friendly description of the faucet step. `Skipped` covers the
723/// common cases where no request was warranted (mainnet, BYOW, wallet
724/// already present, dry-run) — the reason is echoed so the caller can tell
725/// *why* we didn't hit the faucet.
726enum 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/// Outcome of the optional webhook step. `Skipped` is the default when
768/// `--webhook-url` wasn't passed; the remaining variants mirror the
769/// shell-script states (`registered`, `registered + subscribed`,
770/// `would_register`).
771#[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
791/// Resolve the final event subscription list for `taskfast init
792/// --webhook-url`. Precedence: explicit `--webhook-event` flags win
793/// outright; absent-events + `--no-default-events` yields an empty list
794/// (URL-only registration); absent-events + default path fans out to
795/// the 9-event worker default (`webhook::DEFAULT_WORKER_EVENTS`). Shared
796/// between the live subscription path and the `--dry-run` envelope so
797/// the preview never diverges from what would be pushed.
798fn 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            // On mainnet, point the caller at the human funding path so
907            // they don't assume the CLI "just handles it" like it does on
908            // testnet.
909            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        // We can't easily drive provision_wallet without a client, but we
1067        // can prove the flag-gate logic: with no flags set, the error is
1068        // Usage, not MissingApiKey.
1069        let args = base_args();
1070        assert!(args.wallet_address.is_none() && !args.generate_wallet);
1071        // The branch that returns Usage lives in provision_wallet — a
1072        // dedicated integration test drives the end-to-end path.
1073    }
1074
1075    #[test]
1076    fn wallet_outcome_tag_is_stable() {
1077        // Pinning the tag strings is intentional: orchestrators branch on
1078        // `data.wallet.status` so changes here are breaking.
1079        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        // URL set, no explicit events, no opt-out → auto-subscribe to
1108        // the 9-event worker default. Guards PLAN #11: raw `init
1109        // --webhook-url X` must not silently register a zero-event
1110        // endpoint.
1111        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        // Explicit opt-out preserves the legacy URL-only behavior.
1122        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        // Any `--webhook-event` wins: the defaults are NOT mixed in.
1133        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        // Safety: --no-default-events is an opt-out flag for the
1144        // auto-population path; explicit events should still flow.
1145        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        // Dry-run envelope must preview what the live path would push —
1157        // otherwise `init --webhook-url X --dry-run` silently differs
1158        // from the real call.
1159        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        // Regression guard: the auto-subscribe branch must not fire
1192        // when the URL is absent — init stays single-purpose.
1193        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}