-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathmain.rs
More file actions
3633 lines (3297 loc) Ā· 131 KB
/
main.rs
File metadata and controls
3633 lines (3297 loc) Ā· 131 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![recursion_limit = "256"]
#![warn(clippy::all, clippy::pedantic)]
#![allow(
clippy::assigning_clones,
clippy::bool_to_int_with_if,
clippy::case_sensitive_file_extension_comparisons,
clippy::cast_possible_wrap,
clippy::doc_markdown,
clippy::field_reassign_with_default,
clippy::float_cmp,
clippy::implicit_clone,
clippy::items_after_statements,
clippy::map_unwrap_or,
clippy::manual_let_else,
clippy::missing_errors_doc,
clippy::missing_panics_doc,
clippy::module_name_repetitions,
clippy::needless_pass_by_value,
clippy::needless_raw_string_hashes,
clippy::redundant_closure_for_method_calls,
clippy::similar_names,
clippy::single_match_else,
clippy::struct_field_names,
clippy::too_many_lines,
clippy::uninlined_format_args,
clippy::unused_self,
clippy::cast_precision_loss,
clippy::unnecessary_cast,
clippy::unnecessary_lazy_evaluations,
clippy::unnecessary_literal_bound,
clippy::unnecessary_map_or,
clippy::unnecessary_wraps,
dead_code,
unused_variables,
unused_imports
)]
use anyhow::{Context, Result, bail};
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use dialoguer::{Password, Select};
use serde::{Deserialize, Serialize};
use std::io::{IsTerminal, Write};
use std::path::PathBuf;
use tracing::{info, warn};
use tracing_subscriber::{EnvFilter, fmt};
fn parse_temperature(s: &str) -> std::result::Result<f64, String> {
let t: f64 = s.parse().map_err(|e| format!("{e}"))?;
config::schema::validate_temperature(t)
}
fn print_no_command_help() -> Result<()> {
println!("No command provided.");
println!("Try `zeroclaw onboard` to initialize your workspace.");
println!();
let mut cmd = Cli::command();
cmd.print_help()?;
println!();
#[cfg(windows)]
pause_after_no_command_help();
Ok(())
}
#[cfg(windows)]
fn pause_after_no_command_help() {
println!();
print!("Press Enter to exit...");
let _ = std::io::stdout().flush();
let mut line = String::new();
let _ = std::io::stdin().read_line(&mut line);
}
#[cfg(feature = "agent-runtime")]
mod agent;
#[cfg(feature = "agent-runtime")]
mod approval;
#[cfg(feature = "agent-runtime")]
mod auth;
#[cfg(feature = "agent-runtime")]
mod channels;
#[cfg(feature = "agent-runtime")]
mod cli_input;
mod commands;
#[cfg(feature = "agent-runtime")]
mod rag {
pub use zeroclaw::rag::*;
}
mod config;
#[cfg(feature = "agent-runtime")]
mod cost;
#[cfg(feature = "agent-runtime")]
mod cron;
#[cfg(feature = "agent-runtime")]
mod daemon;
#[cfg(feature = "agent-runtime")]
mod doctor;
#[cfg(feature = "gateway")]
mod gateway;
#[cfg(feature = "agent-runtime")]
mod hardware;
#[cfg(feature = "agent-runtime")]
mod health;
#[cfg(feature = "agent-runtime")]
mod heartbeat;
#[cfg(feature = "agent-runtime")]
mod hooks;
#[cfg(feature = "agent-runtime")]
mod i18n;
#[cfg(feature = "agent-runtime")]
mod identity;
#[cfg(feature = "agent-runtime")]
mod integrations;
mod memory;
#[cfg(feature = "agent-runtime")]
mod migration;
#[cfg(feature = "agent-runtime")]
mod multimodal;
#[cfg(feature = "agent-runtime")]
mod observability;
#[cfg(feature = "agent-runtime")]
mod onboard;
#[cfg(feature = "agent-runtime")]
mod peripherals;
#[cfg(feature = "agent-runtime")]
mod platform;
#[cfg(feature = "plugins-wasm")]
mod plugins;
mod providers;
#[cfg(feature = "agent-runtime")]
mod security;
#[cfg(feature = "agent-runtime")]
mod service;
#[cfg(feature = "agent-runtime")]
mod skillforge;
#[cfg(feature = "agent-runtime")]
mod skills;
#[cfg(feature = "agent-runtime")]
mod sop;
#[cfg(feature = "agent-runtime")]
mod tools;
#[cfg(feature = "agent-runtime")]
mod trust;
#[cfg(feature = "tui-onboarding")]
mod tui;
#[cfg(feature = "agent-runtime")]
mod tunnel;
#[cfg(feature = "agent-runtime")]
mod util;
#[cfg(feature = "agent-runtime")]
mod verifiable_intent;
use config::Config;
// Re-export so binary modules can use crate::<CommandEnum> while keeping a single source of truth.
pub use zeroclaw::{
ChannelCommands, CronCommands, GatewayCommands, HardwareCommands, IntegrationCommands,
MigrateCommands, PeripheralCommands, ServiceCommands, SkillCommands, SopCommands,
};
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum CompletionShell {
#[value(name = "bash")]
Bash,
#[value(name = "fish")]
Fish,
#[value(name = "zsh")]
Zsh,
#[value(name = "powershell")]
PowerShell,
#[value(name = "elvish")]
Elvish,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum EstopLevelArg {
#[value(name = "kill-all")]
KillAll,
#[value(name = "network-kill")]
NetworkKill,
#[value(name = "domain-block")]
DomainBlock,
#[value(name = "tool-freeze")]
ToolFreeze,
}
/// `ZeroClaw` - Zero overhead. Zero compromise. 100% Rust.
#[derive(Parser, Debug)]
#[command(name = "zeroclaw")]
#[command(author = "theonlyhennygod")]
#[command(version)]
#[command(about = "The fastest, smallest AI assistant.", long_about = None)]
struct Cli {
#[arg(long, global = true)]
config_dir: Option<String>,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Initialize your workspace and configuration
Onboard {
/// Overwrite existing config without confirmation
#[arg(long)]
force: bool,
/// Reinitialize from scratch (backup and reset all configuration)
#[arg(long)]
reinit: bool,
/// Reconfigure channels only (fast repair flow)
#[arg(long)]
channels_only: bool,
/// API key for provider configuration
#[arg(long)]
api_key: Option<String>,
/// Provider name (used in quick mode, default: openrouter)
#[arg(long)]
provider: Option<String>,
/// Model ID override (used in quick mode)
#[arg(long)]
model: Option<String>,
/// Memory backend (sqlite, lucid, markdown, none) - used in quick mode, default: sqlite
#[arg(long)]
memory: Option<String>,
/// Skip interactive prompts and use quick setup with defaults
#[arg(long)]
quick: bool,
/// Use the ratatui-based TUI onboarding wizard
#[arg(long)]
tui: bool,
},
/// Start the AI agent loop
#[command(long_about = "\
Start the AI agent loop.
Launches an interactive chat session with the configured AI provider. \
Use --message for single-shot queries without entering interactive mode.
Examples:
zeroclaw agent # interactive session
zeroclaw agent -m \"Summarize today's logs\" # single message
zeroclaw agent -p anthropic --model claude-sonnet-4-20250514
zeroclaw agent --peripheral nucleo-f401re:/dev/ttyACM0")]
Agent {
/// Single message mode (don't enter interactive mode)
#[arg(short, long)]
message: Option<String>,
/// Load and save interactive session state in this JSON file
#[arg(long)]
session_state_file: Option<PathBuf>,
/// Provider to use (openrouter, anthropic, openai, openai-codex)
#[arg(short, long)]
provider: Option<String>,
/// Model to use
#[arg(long)]
model: Option<String>,
/// Temperature (0.0 - 2.0, defaults to config default_temperature)
#[arg(short, long, value_parser = parse_temperature)]
temperature: Option<f64>,
/// Attach a peripheral (board:path, e.g. nucleo-f401re:/dev/ttyACM0)
#[arg(long)]
peripheral: Vec<String>,
},
/// Start/manage the gateway server (webhooks, websockets)
#[command(long_about = "\
Manage the gateway server (webhooks, websockets).
Start, restart, or inspect the HTTP/WebSocket gateway that accepts \
incoming webhook events and WebSocket connections.
Examples:
zeroclaw gateway start # start gateway
zeroclaw gateway restart # restart gateway
zeroclaw gateway get-paircode # show pairing code")]
Gateway {
#[command(subcommand)]
gateway_command: Option<zeroclaw::GatewayCommands>,
},
/// Start ACP (Agent Control Protocol) server over stdio
#[command(long_about = "\
Start the ACP server (JSON-RPC 2.0 over stdio).
Launches a JSON-RPC 2.0 server on stdin/stdout for IDE and tool \
integration. Supports session management and streaming agent \
responses as notifications.
Methods: initialize, session/new, session/prompt, session/stop.
Examples:
zeroclaw acp # start ACP server
zeroclaw acp --max-sessions 5 # limit concurrent sessions")]
Acp {
/// Maximum concurrent sessions (default: 10)
#[arg(long)]
max_sessions: Option<usize>,
/// Session inactivity timeout in seconds (default: 3600)
#[arg(long)]
session_timeout: Option<u64>,
},
/// Start long-running autonomous runtime (gateway + channels + heartbeat + scheduler)
#[command(long_about = "\
Start the long-running autonomous daemon.
Launches the full ZeroClaw runtime: gateway server, all configured \
channels (Telegram, Discord, Slack, etc.), heartbeat monitor, and \
the cron scheduler. This is the recommended way to run ZeroClaw in \
production or as an always-on assistant.
Use 'zeroclaw service install' to register the daemon as an OS \
service (systemd/launchd) for auto-start on boot.
Examples:
zeroclaw daemon # use config defaults
zeroclaw daemon -p 9090 # gateway on port 9090
zeroclaw daemon --host 127.0.0.1 # localhost only")]
Daemon {
/// Port to listen on (use 0 for random available port); defaults to config gateway.port
#[arg(short, long)]
port: Option<u16>,
/// Host to bind to; defaults to config gateway.host
#[arg(long)]
host: Option<String>,
},
/// Manage OS service lifecycle (launchd/systemd user service)
Service {
/// Init system to use: auto (detect), systemd, or openrc
#[arg(long, default_value = "auto", value_parser = ["auto", "systemd", "openrc"])]
service_init: String,
#[command(subcommand)]
service_command: ServiceCommands,
},
/// Run diagnostics for daemon/scheduler/channel freshness
Doctor {
#[command(subcommand)]
doctor_command: Option<DoctorCommands>,
},
/// Show system status (full details)
Status {
/// Output format: "exit-code" exits 0 if healthy, 1 otherwise (for Docker HEALTHCHECK)
#[arg(long)]
format: Option<String>,
},
/// Engage, inspect, and resume emergency-stop states.
///
/// Examples:
/// - `zeroclaw estop`
/// - `zeroclaw estop --level network-kill`
/// - `zeroclaw estop --level domain-block --domain "*.chase.com"`
/// - `zeroclaw estop --level tool-freeze --tool shell --tool browser`
/// - `zeroclaw estop status`
/// - `zeroclaw estop resume --network`
/// - `zeroclaw estop resume --domain "*.chase.com"`
/// - `zeroclaw estop resume --tool shell`
Estop {
#[command(subcommand)]
estop_command: Option<EstopSubcommands>,
/// Level used when engaging estop from `zeroclaw estop`.
#[arg(long, value_enum)]
level: Option<EstopLevelArg>,
/// Domain pattern(s) for `domain-block` (repeatable).
#[arg(long = "domain")]
domains: Vec<String>,
/// Tool name(s) for `tool-freeze` (repeatable).
#[arg(long = "tool")]
tools: Vec<String>,
},
/// Configure and manage scheduled tasks
#[command(long_about = "\
Configure and manage scheduled tasks.
Schedule recurring, one-shot, or interval-based tasks using cron \
expressions, RFC 3339 timestamps, durations, or fixed intervals.
Cron expressions use the standard 5-field format: \
'min hour day month weekday'. Timezones default to UTC; \
override with --tz and an IANA timezone name.
Examples:
zeroclaw cron list
zeroclaw cron add '0 9 * * 1-5' 'Good morning' --tz America/New_York --agent
zeroclaw cron add '*/30 * * * *' 'Check system health' --agent
zeroclaw cron add '*/5 * * * *' 'echo ok'
zeroclaw cron add-at 2025-01-15T14:00:00Z 'Send reminder' --agent
zeroclaw cron add-every 60000 'Ping heartbeat'
zeroclaw cron once 30m 'Run backup in 30 minutes' --agent
zeroclaw cron pause <task-id>
zeroclaw cron update <task-id> --expression '0 8 * * *' --tz Europe/London")]
Cron {
#[command(subcommand)]
cron_command: CronCommands,
},
/// Manage provider model catalogs
Models {
#[command(subcommand)]
model_command: ModelCommands,
},
/// List supported AI providers
Providers,
/// Manage channels (telegram, discord, slack)
#[command(long_about = "\
Manage communication channels.
Add, remove, list, send, and health-check channels that connect ZeroClaw \
to messaging platforms. Supported channel types: telegram, discord, \
slack, whatsapp, matrix, imessage, email.
Examples:
zeroclaw channel list
zeroclaw channel doctor
zeroclaw channel add telegram '{\"bot_token\":\"...\",\"name\":\"my-bot\"}'
zeroclaw channel remove my-bot
zeroclaw channel bind-telegram zeroclaw_user
zeroclaw channel send 'Alert!' --channel-id telegram --recipient 123456789")]
Channel {
#[command(subcommand)]
channel_command: ChannelCommands,
},
/// Browse 50+ integrations
Integrations {
#[command(subcommand)]
integration_command: IntegrationCommands,
},
/// Manage skills (user-defined capabilities)
Skills {
#[command(subcommand)]
skill_command: SkillCommands,
},
/// Manage standard operating procedures (SOPs)
Sop {
#[command(subcommand)]
sop_command: SopCommands,
},
/// Migrate data from other agent runtimes
Migrate {
#[command(subcommand)]
migrate_command: MigrateCommands,
},
/// Manage provider subscription authentication profiles
Auth {
#[command(subcommand)]
auth_command: AuthCommands,
},
/// Discover and introspect USB hardware
#[command(long_about = "\
Discover and introspect USB hardware.
Enumerate connected USB devices, identify known development boards \
(STM32 Nucleo, Arduino, ESP32), and retrieve chip information via \
probe-rs / ST-Link.
Examples:
zeroclaw hardware discover
zeroclaw hardware introspect /dev/ttyACM0
zeroclaw hardware info --chip STM32F401RETx")]
Hardware {
#[command(subcommand)]
hardware_command: zeroclaw::HardwareCommands,
},
/// Manage hardware peripherals (STM32, RPi GPIO, etc.)
#[command(long_about = "\
Manage hardware peripherals.
Add, list, flash, and configure hardware boards that expose tools \
to the agent (GPIO, sensors, actuators). Supported boards: \
nucleo-f401re, rpi-gpio, esp32, arduino-uno.
Examples:
zeroclaw peripheral list
zeroclaw peripheral add nucleo-f401re /dev/ttyACM0
zeroclaw peripheral add rpi-gpio native
zeroclaw peripheral flash --port /dev/cu.usbmodem12345
zeroclaw peripheral flash-nucleo")]
Peripheral {
#[command(subcommand)]
peripheral_command: zeroclaw::PeripheralCommands,
},
/// Manage agent memory (list, get, stats, clear)
#[command(long_about = "\
Manage agent memory entries.
List, inspect, and clear memory entries stored by the agent. \
Supports filtering by category and session, pagination, and \
batch clearing with confirmation.
Examples:
zeroclaw memory stats
zeroclaw memory list
zeroclaw memory list --category core --limit 10
zeroclaw memory get <key>
zeroclaw memory clear --category conversation --yes")]
Memory {
#[command(subcommand)]
memory_command: MemoryCommands,
},
/// Manage configuration
#[command(long_about = "\
Manage ZeroClaw configuration.
View, set, or initialize config properties by dotted path. \
Use 'schema' to dump the full JSON Schema for the config file.
Properties are addressed by dotted path (e.g. channels.matrix.mention-only).
Secret fields (API keys, tokens) automatically use masked input.
Enum fields offer interactive selection when value is omitted.
Examples:
zeroclaw config list # list all properties
zeroclaw config list --secrets # list only secrets
zeroclaw config list --filter channels.matrix # filter by prefix
zeroclaw config get channels.matrix.mention-only # get a value
zeroclaw config set channels.matrix.mention-only true # set a value
zeroclaw config set channels.matrix.access-token # secret: masked input
zeroclaw config set channels.matrix.stream-mode # enum: interactive select
zeroclaw config init channels.matrix # init section with defaults
zeroclaw config schema # print JSON Schema to stdout
zeroclaw config schema > schema.json
Property path tab completion is included automatically in `zeroclaw completions <shell>`.")]
Config {
#[command(subcommand)]
config_command: ConfigCommands,
},
/// Check for and apply updates
#[command(long_about = "\
Check for and apply ZeroClaw updates.
By default, downloads and installs the latest release with a \
6-phase pipeline: preflight, download, backup, validate, swap, \
and smoke test. Automatic rollback on failure.
Use --check to only check for updates without installing.
Use --force to skip the confirmation prompt.
Use --version to target a specific release instead of latest.
Examples:
zeroclaw update # download and install latest
zeroclaw update --check # check only, don't install
zeroclaw update --force # install without confirmation
zeroclaw update --version 0.6.0 # install specific version")]
Update {
/// Only check for updates, don't install
#[arg(long)]
check: bool,
/// Skip confirmation prompt
#[arg(long)]
force: bool,
/// Target version (default: latest)
#[arg(long)]
version: Option<String>,
},
/// Run diagnostic self-tests
#[command(long_about = "\
Run diagnostic self-tests to verify the ZeroClaw installation.
By default, runs the full test suite including network checks \
(gateway health, memory round-trip). Use --quick to skip network \
checks for faster offline validation.
Examples:
zeroclaw self-test # full suite
zeroclaw self-test --quick # quick checks only (no network)")]
SelfTest {
/// Run quick checks only (no network)
#[arg(long)]
quick: bool,
},
/// Generate shell completion script to stdout
#[command(long_about = "\
Generate shell completion scripts for `zeroclaw`.
The script is printed to stdout so it can be sourced directly:
Examples:
source <(zeroclaw completions bash)
zeroclaw completions zsh > ~/.zfunc/_zeroclaw
zeroclaw completions fish > ~/.config/fish/completions/zeroclaw.fish")]
Completions {
/// Target shell
#[arg(value_enum)]
shell: CompletionShell,
},
/// Launch or install the companion desktop app
#[command(long_about = "\
Launch the ZeroClaw companion desktop app.
The companion app is a lightweight menu bar / system tray application \
that connects to the same gateway as the CLI. It provides quick access \
to the dashboard, status monitoring, and device pairing.
Use --install to download the pre-built companion app for your platform.
Examples:
zeroclaw desktop # launch the companion app
zeroclaw desktop --install # download and install it")]
Desktop {
/// Download and install the companion app
#[arg(long)]
install: bool,
},
/// Deprecated: use `zeroclaw config` instead
#[command(hide = true)]
Props {
#[command(subcommand)]
props_command: DeprecatedPropsCommands,
},
/// Manage WASM plugins
#[cfg(feature = "plugins-wasm")]
Plugin {
#[command(subcommand)]
plugin_command: PluginCommands,
},
}
/// Stub enum that mirrors the old `props` subcommands so clap can still parse
/// `zeroclaw props <anything>` and print a deprecation message.
#[derive(Subcommand, Debug)]
enum DeprecatedPropsCommands {
#[command(external_subcommand)]
Any(Vec<String>),
}
#[cfg(feature = "plugins-wasm")]
#[derive(Subcommand, Debug)]
enum PluginCommands {
/// List installed plugins
List,
/// Install a plugin from a directory or URL
Install {
/// Path to plugin directory or manifest
source: String,
},
/// Remove an installed plugin
Remove {
/// Plugin name
name: String,
},
/// Show information about a plugin
Info {
/// Plugin name
name: String,
},
}
#[derive(Subcommand, Debug)]
enum ConfigCommands {
/// Dump the full configuration JSON Schema to stdout
Schema,
/// List all config properties with current values
List {
/// Filter by path prefix (e.g. "channels.telegram")
#[arg(short, long)]
filter: Option<String>,
/// Show only secret (encrypted) fields
#[arg(long)]
secrets: bool,
},
/// Get a config property value
Get {
/// Property path (e.g. channels.telegram.mention-only)
path: String,
},
/// Set a config property (secret fields auto-prompt for masked input)
Set {
/// Property path
path: String,
/// New value (omit for secret fields to get masked input)
value: Option<String>,
/// Skip interactive prompts ā require value on command line, accept raw strings for enums
#[arg(long)]
no_interactive: bool,
},
/// Initialize unconfigured sections with defaults (enabled=false)
Init {
/// Section prefix (e.g. channels.matrix). Omit to init all.
section: Option<String>,
},
/// Migrate config.toml to the current schema version on disk (preserves comments)
Migrate,
/// Print matching property paths for shell completion (hidden)
#[command(hide = true)]
Complete {
/// Partial path to complete
partial: Option<String>,
},
}
#[derive(Subcommand, Debug)]
enum EstopSubcommands {
/// Print current estop status.
Status,
/// Resume from an engaged estop level.
Resume {
/// Resume only network kill.
#[arg(long)]
network: bool,
/// Resume one or more blocked domain patterns.
#[arg(long = "domain")]
domains: Vec<String>,
/// Resume one or more frozen tools.
#[arg(long = "tool")]
tools: Vec<String>,
/// OTP code. If omitted and OTP is required, a prompt is shown.
#[arg(long)]
otp: Option<String>,
},
}
#[derive(Subcommand, Debug)]
enum AuthCommands {
/// Login with OAuth (OpenAI Codex or Gemini)
Login {
/// Provider (`openai-codex` or `gemini`)
#[arg(long)]
provider: String,
/// Profile name (default: default)
#[arg(long, default_value = "default")]
profile: String,
/// Use OAuth device-code flow
#[arg(long)]
device_code: bool,
/// Import an existing auth.json file instead of starting a new login flow.
/// Currently supports only `openai-codex`; Codex defaults to `~/.codex/auth.json`.
#[arg(long, value_name = "PATH", conflicts_with = "device_code")]
import: Option<PathBuf>,
},
/// Complete OAuth by pasting redirect URL or auth code
PasteRedirect {
/// Provider (`openai-codex`)
#[arg(long)]
provider: String,
/// Profile name (default: default)
#[arg(long, default_value = "default")]
profile: String,
/// Full redirect URL or raw OAuth code
#[arg(long)]
input: Option<String>,
},
/// Paste setup token / auth token (for Anthropic subscription auth)
PasteToken {
/// Provider (`anthropic`)
#[arg(long)]
provider: String,
/// Profile name (default: default)
#[arg(long, default_value = "default")]
profile: String,
/// Token value (if omitted, read interactively)
#[arg(long)]
token: Option<String>,
/// Auth kind override (`authorization` or `api-key`)
#[arg(long)]
auth_kind: Option<String>,
},
/// Alias for `paste-token` (interactive by default)
SetupToken {
/// Provider (`anthropic`)
#[arg(long)]
provider: String,
/// Profile name (default: default)
#[arg(long, default_value = "default")]
profile: String,
},
/// Refresh OpenAI Codex access token using refresh token
Refresh {
/// Provider (`openai-codex`)
#[arg(long)]
provider: String,
/// Profile name or profile id
#[arg(long)]
profile: Option<String>,
},
/// Remove auth profile
Logout {
/// Provider
#[arg(long)]
provider: String,
/// Profile name (default: default)
#[arg(long, default_value = "default")]
profile: String,
},
/// Set active profile for a provider
Use {
/// Provider
#[arg(long)]
provider: String,
/// Profile name or full profile id
#[arg(long)]
profile: String,
},
/// List auth profiles
List,
/// Show auth status with active profile and token expiry info
Status,
}
#[derive(Subcommand, Debug)]
enum ModelCommands {
/// Refresh and cache provider models
Refresh {
/// Provider name (defaults to configured default provider)
#[arg(long)]
provider: Option<String>,
/// Refresh all providers that support live model discovery
#[arg(long)]
all: bool,
/// Force live refresh and ignore fresh cache
#[arg(long)]
force: bool,
},
/// List cached models for a provider
List {
/// Provider name (defaults to configured default provider)
#[arg(long)]
provider: Option<String>,
},
/// Set the default model in config
Set {
/// Model name to set as default
model: String,
},
/// Show current model configuration and cache status
Status,
}
#[derive(Subcommand, Debug)]
enum DoctorCommands {
/// Probe model catalogs across providers and report availability
Models {
/// Probe a specific provider only (default: all known providers)
#[arg(long)]
provider: Option<String>,
/// Prefer cached catalogs when available (skip forced live refresh)
#[arg(long)]
use_cache: bool,
},
/// Query runtime trace events (tool diagnostics and model replies)
Traces {
/// Show a specific trace event by id
#[arg(long)]
id: Option<String>,
/// Filter list output by event type
#[arg(long)]
event: Option<String>,
/// Case-insensitive text match across message/payload
#[arg(long)]
contains: Option<String>,
/// Maximum number of events to display
#[arg(long, default_value = "20")]
limit: usize,
},
}
#[derive(Subcommand, Debug)]
enum MemoryCommands {
/// List memory entries with optional filters
List {
#[arg(long)]
category: Option<String>,
#[arg(long)]
session: Option<String>,
#[arg(long, default_value = "50")]
limit: usize,
#[arg(long, default_value = "0")]
offset: usize,
},
/// Get a specific memory entry by key
Get { key: String },
/// Show memory backend statistics and health
Stats,
/// Clear memories by category, by key, or clear all
Clear {
/// Delete a single entry by key (supports prefix match)
#[arg(long)]
key: Option<String>,
#[arg(long)]
category: Option<String>,
/// Skip confirmation prompt
#[arg(long)]
yes: bool,
},
}
#[tokio::main]
#[allow(clippy::too_many_lines)]
async fn main() -> Result<()> {
// Install default crypto provider for Rustls TLS.
// This prevents the error: "could not automatically determine the process-level CryptoProvider"
// when both aws-lc-rs and ring features are available (or neither is explicitly selected).
#[cfg(feature = "agent-runtime")]
if let Err(e) = rustls::crypto::ring::default_provider().install_default() {
eprintln!("Warning: Failed to install default crypto provider: {e:?}");
}
if std::env::args_os().len() <= 1 {
return print_no_command_help();
}
let cli = Cli::parse();
if let Some(config_dir) = &cli.config_dir {
if config_dir.trim().is_empty() {
bail!("--config-dir cannot be empty");
}
// SAFETY: called early in main before any threads are spawned.
unsafe { std::env::set_var("ZEROCLAW_CONFIG_DIR", config_dir) };
}
// Completions must remain stdout-only and should not load config or initialize logging.
// This avoids warnings/log lines corrupting sourced completion scripts.
if let Commands::Completions { shell } = &cli.command {
let mut stdout = std::io::stdout().lock();
write_shell_completion(*shell, &mut stdout)?;
return Ok(());
}
// Initialize logging - respects RUST_LOG env var, defaults to INFO.
// matrix_sdk crates are suppressed to warn because they are extremely
// noisy at info level. To restore SDK-level output for Matrix debugging:
// RUST_LOG=info,matrix_sdk=info,matrix_sdk_base=info,matrix_sdk_crypto=info
let subscriber = fmt::Subscriber::builder()
.with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| {
EnvFilter::new("info,matrix_sdk=warn,matrix_sdk_base=warn,matrix_sdk_crypto=warn")
}))
.finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
// Onboard auto-detects the environment: if stdin/stdout are a TTY and no
// provider flags were given, it runs the full interactive wizard; otherwise
// it runs the quick (scriptable) setup. Use --quick to force quick setup,
// or set ZEROCLAW_INTERACTIVE=1 to force interactive mode when TTY
// detection fails. This means `curl ⦠| bash` and
// `zeroclaw onboard --api-key ā¦` both take the fast path, while a bare
// `zeroclaw onboard` in a terminal launches the wizard.
#[cfg(feature = "agent-runtime")]
if let Commands::Onboard {
force,
reinit,
channels_only,
api_key,
provider,
model,
memory,
quick,
tui: use_tui,
} = &cli.command
{
let force = *force;
let reinit = *reinit;
let channels_only = *channels_only;
let api_key = api_key.clone();