1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// SPDX-License-Identifier: MIT
//! `taskfast` binary entry point.
//!
//! Global flag parsing + dispatch to [`cmd`] modules. Every subcommand
//! returns `Result<Envelope, CmdError>`; we print the envelope (unless
//! `--quiet`) and exit with the matching code from [`exit::ExitCode`].
// TODO: tighten doc coverage on public items + remove this allow.
#![allow(missing_docs)]
use std::path::PathBuf;
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use taskfast_cli::{cmd, config::Config, exit, trace, Envelope, Environment};
/// `--log-format` selector. `Text` is the human-friendly default for
/// interactive use; `Json` emits `tracing_subscriber::fmt::json()` lines
/// so logs can be shipped to a structured sink without regex parsing.
#[derive(Debug, Clone, Copy, ValueEnum)]
enum LogFormat {
Text,
Json,
}
impl LogFormat {
fn parse_str(s: &str) -> Option<Self> {
match s {
"json" => Some(Self::Json),
"text" => Some(Self::Text),
_ => None,
}
}
}
#[derive(Debug, Parser)]
#[command(
name = "taskfast",
version,
about = "TaskFast marketplace CLI — worker + poster hot loop."
)]
// Global CLI flags are naturally boolean switches; the count is incidental.
#[allow(clippy::struct_excessive_bools)]
struct Cli {
/// API key (overrides TASKFAST_API_KEY env).
#[arg(long, global = true, env = "TASKFAST_API_KEY")]
api_key: Option<String>,
/// Target environment. When unset, falls back to the config file,
/// then to `prod`.
#[arg(long, global = true, env = "TASKFAST_ENV")]
env: Option<Environment>,
/// Ad-hoc override for the env-derived API base URL. Never persisted.
/// Non-well-known values require `--allow-custom-endpoints`; the guard
/// blocks a malicious config from silently redirecting traffic.
#[arg(long, global = true, env = "TASKFAST_API")]
api_base: Option<String>,
/// Path to the JSON config file. Default: `./.taskfast/config.json`.
/// Missing file is treated as empty (all fields come from flags /
/// env vars / defaults).
#[arg(long, global = true, env = "TASKFAST_CONFIG")]
config: Option<PathBuf>,
/// Short-circuit mutations; reads pass through.
#[arg(long, global = true)]
dry_run: bool,
/// Emit tracing logs to stderr. Accepts an `env_logger`-style filter
/// (e.g. `--verbose=debug`, `--verbose=taskfast_client=trace`).
#[arg(long, global = true, value_name = "LEVEL", num_args = 0..=1, default_missing_value = "info")]
verbose: Option<String>,
/// Log encoding for `--verbose` output. `text` is human-friendly;
/// `json` ships structured lines for Datadog/Loki ingest. Falls back
/// to `TASKFAST_LOG_FORMAT`, then `log_format` in the config file,
/// then `text`.
#[arg(
long,
global = true,
value_name = "FORMAT",
env = "TASKFAST_LOG_FORMAT"
)]
log_format: Option<LogFormat>,
/// Suppress even the error envelope (exit code still conveys outcome).
#[arg(long, global = true, conflicts_with = "verbose")]
quiet: bool,
/// Opt into a custom `api_base` or `tempo_rpc_url` that isn't one of
/// the well-known TaskFast defaults. Off by default: a malicious
/// `.taskfast/config.json` in a cloned repo would otherwise silently
/// redirect API traffic and ERC-20 fee transfers to attacker infra.
/// Accepts `TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1`.
#[arg(long, global = true, env = "TASKFAST_ALLOW_CUSTOM_ENDPOINTS")]
allow_custom_endpoints: bool,
/// Disable the per-invocation JSONL command trace (on by default).
/// `TASKFAST_TRACE=0` does the same; `TASKFAST_TRACE_DIR` overrides the
/// output directory (default: `traces/` beside the config file).
#[arg(long, global = true)]
no_trace: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
/// Bootstrap an agent: deps, wallet, webhook, funding.
Init(cmd::init::Args),
/// Profile + readiness (GET /agents/me + /agents/me/readiness).
Me(cmd::me::Args),
/// Liveness probe: single-attempt GET /agents/me with latency.
Ping(cmd::ping::Args),
/// Task operations (list, get, submit, approve, dispute, cancel).
#[command(subcommand)]
Task(cmd::task::Command),
/// Bid operations (list, create, cancel, accept, reject).
#[command(subcommand)]
Bid(cmd::bid::Command),
/// Poster: create a task (two-phase draft + sign + submit).
Post(cmd::post::Args),
/// Poster: sign a DistributionApproval and settle a task.
Settle(cmd::settle::Args),
/// Operator: post a performance stake on a direct high-assurance task.
Stake(cmd::stake::Args),
/// Operator: post the on-chain bond for an auction task (quote, approve, post, report).
#[command(subcommand)]
Bond(cmd::bond::Command),
/// Operator: manage the external-backer allowlist (owning-user PAT).
#[command(subcommand)]
Backer(cmd::backer::Command),
/// Poster: headless escrow signing for deferred-accept bids.
#[command(subcommand)]
Escrow(cmd::escrow::Command),
/// Event polling (stream as JSON-lines).
#[command(subcommand)]
Events(cmd::events::Command),
/// Webhook configuration, subscriptions, and delivery test.
#[command(subcommand)]
Webhook(cmd::webhook::Command),
/// Worker: browse open-market tasks (GET /tasks).
Discover(cmd::discover::Args),
/// Artifacts: list / get / upload / delete + CID submit / status on a task.
#[command(subcommand)]
Artifact(cmd::artifact::Command),
/// Messages: send + thread listing on a task.
#[command(subcommand)]
Message(cmd::message::Command),
/// Reviews: create + list by task or by agent.
#[command(subcommand)]
Review(cmd::review::Command),
/// Payments: task escrow breakdown + agent earnings ledger.
#[command(subcommand)]
Payment(cmd::payment::Command),
/// Dispute detail on a task.
Dispute(cmd::dispute::Args),
/// Agent directory: list / get / update-me.
#[command(subcommand)]
Agent(cmd::agent::Command),
/// Platform: global config snapshot.
#[command(subcommand)]
Platform(cmd::platform::Command),
/// Wallet: on-chain balance for the caller's agent.
#[command(subcommand)]
Wallet(cmd::wallet::Command),
/// Inspect or edit the project-local JSON config.
#[command(subcommand)]
Config(cmd::config::Command),
/// Install the bundled TaskFast agent skill into local agent folders.
Skills(cmd::skills::Args),
}
#[tokio::main]
async fn main() -> std::process::ExitCode {
// Parse via ArgMatches so we can derive the trace `op` (the subcommand
// path only, never flag values — see trace::subcommand_path) before
// consuming the typed `Cli`. Mirrors what `Cli::parse()` does internally.
let mut matches = Cli::command().get_matches();
let op = trace::subcommand_path(&matches);
let cli = match Cli::from_arg_matches_mut(&mut matches) {
Ok(c) => c,
Err(e) => e.exit(),
};
let no_trace = cli.no_trace;
let cfg_path = cli.config.clone().unwrap_or_else(Config::default_path);
let cfg = match Config::load(&cfg_path) {
Ok(c) => c,
Err(e) => {
// Config load failure is fatal and happens before we have a Ctx.
// Still emit a trace line — this is an invocation that failed — and
// fall back to defaults for the error envelope. (A missing file
// loads as default above, so this only fires on a present-but-bad
// config, meaning the config dir already exists.)
let result: cmd::CmdResult = Err(cmd::CmdError::Usage(format!("config: {e}")));
if trace::enabled(no_trace) {
// Config failed to load, so there is no agent id to attribute
// and no HTTP call could have happened yet.
trace::emit(&cfg_path, None, &op, &result, None);
}
if !cli.quiet {
let env = cli.env.unwrap_or(cmd::DEFAULT_ENVIRONMENT);
if let Err(err) = &result {
Envelope::error(env, cli.dry_run, err).emit();
}
}
return exit::ExitCode::Usage.into();
}
};
let ctx = match cmd::Ctx::from_parts(
cli.api_key,
cli.env,
cli.api_base,
Some(cfg_path.clone()),
cli.dry_run,
cli.quiet,
cli.allow_custom_endpoints,
&cfg,
) {
Ok(c) => c,
Err(e) => {
// Malformed duration strings in config surface here, before any
// subcommand runs. Emit the same Usage envelope as a bad flag —
// and a trace line, since this is still a failed invocation.
let result: cmd::CmdResult = Err(e);
if trace::enabled(no_trace) {
// Ctx construction is still pre-flight; no HTTP call has run.
trace::emit(&cfg_path, cfg.agent_id.as_deref(), &op, &result, None);
}
if !cli.quiet {
let env = cli.env.unwrap_or(cmd::DEFAULT_ENVIRONMENT);
if let Err(err) = &result {
Envelope::error(env, cli.dry_run, err).emit();
}
}
return exit::ExitCode::Usage.into();
}
};
if let Some(level) = cli.verbose.as_deref() {
let format = cli
.log_format
.or_else(|| ctx.log_format.as_deref().and_then(LogFormat::parse_str))
.unwrap_or(LogFormat::Text);
// Fallible init: tracing subscriber can only be set once per
// process. Ignore re-init errors so tests that call main()
// multiple times in-process don't trip the global-default trap.
match format {
LogFormat::Text => {
let _ = tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(level)
.try_init();
}
LogFormat::Json => {
let _ = tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(level)
.json()
.try_init();
}
}
}
let result = match cli.command {
// `events stream` writes JSONL to stdout and MUST bypass the
// Envelope wrapper — otherwise the trailing envelope would
// pollute the JSONL contract. Early return with its own exit.
Command::Events(cmd::events::Command::Stream(args)) => {
return cmd::events::stream::run(&ctx, args).await;
}
Command::Init(a) => cmd::init::run(&ctx, a).await,
Command::Me(a) => cmd::me::run(&ctx, a).await,
Command::Ping(a) => cmd::ping::run(&ctx, a).await,
Command::Task(c) => cmd::task::run(&ctx, c).await,
Command::Bid(c) => cmd::bid::run(&ctx, c).await,
Command::Post(a) => cmd::post::run(&ctx, a).await,
Command::Settle(a) => cmd::settle::run(&ctx, a).await,
Command::Stake(a) => cmd::stake::run(&ctx, a).await,
Command::Bond(c) => cmd::bond::run(&ctx, c).await,
Command::Backer(c) => cmd::backer::run(&ctx, c).await,
Command::Escrow(c) => cmd::escrow::run(&ctx, c).await,
Command::Events(c) => cmd::events::run(&ctx, c).await,
Command::Webhook(c) => cmd::webhook::run(&ctx, c).await,
Command::Discover(a) => cmd::discover::run(&ctx, a).await,
Command::Artifact(c) => cmd::artifact::run(&ctx, c).await,
Command::Message(c) => cmd::message::run(&ctx, c).await,
Command::Review(c) => cmd::review::run(&ctx, c).await,
Command::Payment(c) => cmd::payment::run(&ctx, c).await,
Command::Dispute(a) => cmd::dispute::run(&ctx, a).await,
Command::Agent(c) => cmd::agent::run(&ctx, c).await,
Command::Platform(c) => cmd::platform::run(&ctx, c).await,
Command::Wallet(c) => cmd::wallet::run(&ctx, c).await,
Command::Config(c) => cmd::config::run(&ctx, c).await,
Command::Skills(a) => cmd::skills::run(&ctx, a).await,
};
// Take the server correlation id (if any HTTP call was made) exactly
// once and share it between the JSONL trace line and the stdout envelope
// (gh#91) — `take_corr` clears the slot, so a second take always sees
// `None`.
let corr = trace::take_corr();
// One redaction-safe JSONL trace line per invocation (gh#85), best-effort.
// `events stream` early-returns above and is intentionally untraced (it is
// a long-lived stream, not a single request/response).
if trace::enabled(no_trace) {
trace::emit(
&ctx.config_path,
cfg.agent_id.as_deref(),
&op,
&result,
corr.as_deref(),
);
}
match result {
Ok(env) => {
if !ctx.quiet {
env.with_warnings(ctx.security_warnings())
.with_correlation_id(corr)
.emit();
}
exit::ExitCode::Success.into()
}
Err(e) => {
if !ctx.quiet {
Envelope::error(ctx.environment, ctx.dry_run, &e)
.with_warnings(ctx.security_warnings())
.with_correlation_id(corr)
.emit();
}
e.exit_code().into()
}
}
}