-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmain.rs
More file actions
2855 lines (2619 loc) · 114 KB
/
main.rs
File metadata and controls
2855 lines (2619 loc) · 114 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
use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand, ValueEnum};
use futures_util::{SinkExt, StreamExt};
use rustyclaw_core::args::CommonArgs;
use rustyclaw_core::commands::{CommandAction, CommandContext, handle_command};
use rustyclaw_core::config::Config;
use rustyclaw_core::gateway::{
ClientFrame, ClientFrameType, ClientPayload, ServerFrame, ServerFrameType, ServerPayload,
deserialize_frame, serialize_frame,
};
use rustyclaw_core::providers;
use rustyclaw_core::secrets::SecretsManager;
use rustyclaw_core::skills::SkillManager;
#[cfg(feature = "tui")]
use rustyclaw_tui::app::App;
#[cfg(feature = "tui")]
use rustyclaw_tui::onboard::run_onboard_wizard;
use std::path::PathBuf;
use tokio_tungstenite::tungstenite::Message;
use url::Url;
mod commands;
// ── Top-level CLI ───────────────────────────────────────────────────────────
#[derive(Debug, Parser)]
#[command(
name = "rustyclaw",
version,
about = "RustyClaw — lightweight agentic assistant",
long_about = "RustyClaw — a super-lightweight super-capable agentic tool with improved security.\n\n\
Run without a subcommand to launch the TUI."
)]
struct Cli {
#[command(flatten)]
common: CommonArgs,
#[command(subcommand)]
command: Option<Commands>,
}
// ── Subcommands (mirrors openclaw command tree) ─────────────────────────────
#[derive(Debug, Subcommand)]
enum Commands {
/// Initialise config + workspace (runs the wizard when wizard flags are present)
Setup(SetupArgs),
/// Interactive onboarding wizard — set up gateway, workspace, and skills
Onboard(OnboardArgs),
/// Import an existing OpenClaw installation into RustyClaw
Import(ImportArgs),
/// Interactive configuration wizard (models, gateway, skills)
Configure,
/// Config helpers: get / set / unset
#[command(subcommand)]
Config(ConfigCommands),
/// Health checks + quick fixes for gateway and configuration
Doctor(DoctorArgs),
/// Launch the terminal UI
#[command(alias = "ui")]
Tui(TuiArgs),
/// Send a one-shot message / slash-command
#[command(alias = "cmd", alias = "run", alias = "message")]
Command(CommandArgs),
/// Send a prompt to the model and print the response (headless mode)
#[command(alias = "chat", alias = "prompt")]
Ask(AskArgs),
/// Show system status (gateway, model, workspace)
Status(StatusArgs),
/// Gateway management (start / stop / restart / status)
#[command(subcommand)]
Gateway(GatewayCommands),
/// List / manage skills
#[command(subcommand)]
Skills(SkillsCommands),
/// Refresh the GitHub Copilot session token from OpenClaw
#[command(alias = "refresh")]
RefreshToken(RefreshTokenArgs),
/// ClawHub skill registry commands (search, install, publish, …)
#[command(name = "clawhub", alias = "hub", alias = "registry")]
ClawHub(ClawHubCommands),
}
// ── Setup ───────────────────────────────────────────────────────────────────
#[derive(Debug, Args, Default)]
struct SetupArgs {
/// Agent workspace directory (default: ~/.rustyclaw/workspace)
#[arg(long, value_name = "DIR")]
workspace: Option<String>,
/// Run the onboarding wizard
#[arg(long)]
wizard: bool,
/// Run wizard without prompts
#[arg(long)]
non_interactive: bool,
/// Wizard mode
#[arg(long, value_enum)]
mode: Option<OnboardMode>,
/// Remote gateway WebSocket URL
#[arg(long, value_name = "URL")]
remote_url: Option<String>,
/// Remote gateway token (optional)
#[arg(long, value_name = "TOKEN")]
remote_token: Option<String>,
}
// ── RefreshToken ────────────────────────────────────────────────────────────
#[derive(Debug, Args)]
struct RefreshTokenArgs {
/// Path to the OpenClaw directory (default: ~/.openclaw)
#[arg(long, value_name = "PATH")]
openclaw_dir: Option<String>,
/// Restart the gateway after refreshing
#[arg(long)]
restart: bool,
}
// ── Import ──────────────────────────────────────────────────────────────────
#[derive(Debug, Args)]
struct ImportArgs {
/// Path to the OpenClaw directory to import (default: ~/.openclaw)
#[arg(value_name = "PATH")]
source: Option<String>,
/// RustyClaw settings directory (default: ~/.rustyclaw)
#[arg(long, value_name = "DIR")]
target: Option<String>,
/// Overwrite existing files without prompting
#[arg(long)]
force: bool,
/// Dry run — show what would be imported without making changes
#[arg(long)]
dry_run: bool,
}
// ── Onboard ─────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, ValueEnum)]
enum OnboardMode {
Local,
Remote,
}
#[derive(Debug, Clone, ValueEnum)]
enum OnboardFlow {
Quickstart,
Advanced,
Manual,
}
#[derive(Debug, Clone, ValueEnum)]
enum GatewayAuthMode {
Token,
Password,
}
#[derive(Debug, Clone, ValueEnum, Default)]
enum GatewayBind {
#[default]
Loopback,
Lan,
Tailnet,
Auto,
Custom,
}
#[derive(Debug, Args, Default)]
#[command(after_help = "\
SECURITY NOTE:
API keys passed via CLI flags are visible in `ps aux` and process logs.
For scripted/automated setups, prefer environment variables:
ANTHROPIC_API_KEY=sk-xxx rustyclaw onboard
OPENROUTER_API_KEY=sk-xxx rustyclaw onboard
Or use the interactive wizard which prompts securely.
")]
struct OnboardArgs {
/// Agent workspace directory
#[arg(long, value_name = "DIR")]
workspace: Option<String>,
/// Reset config + credentials + sessions before wizard
#[arg(long)]
reset: bool,
/// Run without prompts
#[arg(long)]
non_interactive: bool,
/// Wizard mode
#[arg(long, value_enum)]
mode: Option<OnboardMode>,
/// Wizard flow
#[arg(long, value_enum)]
flow: Option<OnboardFlow>,
/// Auth provider choice (e.g. apiKey, openai-api-key, anthropic-api-key, …)
#[arg(long, value_name = "CHOICE")]
auth_choice: Option<String>,
/// Output JSON summary
#[arg(long)]
json: bool,
// ── Provider API-key flags (mirrors openclaw) ────────────────
// ⚠️ CLI flags are visible in `ps aux`. Prefer env vars for security:
// ANTHROPIC_API_KEY, OPENAI_API_KEY, OPENROUTER_API_KEY, etc.
/// Anthropic API key (prefer ANTHROPIC_API_KEY env var)
#[arg(long, value_name = "KEY", env = "ANTHROPIC_API_KEY", hide = true)]
anthropic_api_key: Option<String>,
/// OpenAI API key (prefer OPENAI_API_KEY env var)
#[arg(long, value_name = "KEY", env = "OPENAI_API_KEY", hide = true)]
openai_api_key: Option<String>,
/// OpenRouter API key (prefer OPENROUTER_API_KEY env var)
#[arg(long, value_name = "KEY", env = "OPENROUTER_API_KEY", hide = true)]
openrouter_api_key: Option<String>,
/// OpenCode Zen API key (prefer OPENCODE_API_KEY env var)
#[arg(long, value_name = "KEY", env = "OPENCODE_API_KEY", hide = true)]
opencode_api_key: Option<String>,
/// Gemini API key (prefer GEMINI_API_KEY env var)
#[arg(long, value_name = "KEY", env = "GEMINI_API_KEY", hide = true)]
gemini_api_key: Option<String>,
/// xAI API key (prefer XAI_API_KEY env var)
#[arg(long, value_name = "KEY", env = "XAI_API_KEY", hide = true)]
xai_api_key: Option<String>,
// ── Gateway flags (inline, mirrors openclaw) ────────────────
/// Gateway port
#[arg(long, value_name = "PORT")]
gateway_port: Option<u16>,
/// Gateway bind mode
#[arg(long, value_enum)]
gateway_bind: Option<GatewayBind>,
/// Gateway auth mode
#[arg(long, value_enum)]
gateway_auth: Option<GatewayAuthMode>,
/// Gateway token (token auth)
#[arg(long, value_name = "TOKEN")]
gateway_token: Option<String>,
/// Gateway password (password auth)
#[arg(long, value_name = "PASSWORD")]
gateway_password: Option<String>,
/// Remote gateway URL
#[arg(long, value_name = "URL")]
remote_url: Option<String>,
/// Remote gateway token
#[arg(long, value_name = "TOKEN")]
remote_token: Option<String>,
/// Skip skills setup
#[arg(long)]
skip_skills: bool,
/// Skip health check
#[arg(long)]
skip_health: bool,
}
// ── Config ──────────────────────────────────────────────────────────────────
#[derive(Debug, Subcommand)]
enum ConfigCommands {
/// Print a config value (dot path, e.g. model.provider)
Get {
/// Dot-separated config path
#[arg(value_name = "PATH")]
path: String,
},
/// Set a config value
Set {
/// Dot-separated config path
#[arg(value_name = "PATH")]
path: String,
/// Value to set
#[arg(value_name = "VALUE")]
value: String,
},
/// Remove a config value
Unset {
/// Dot-separated config path
#[arg(value_name = "PATH")]
path: String,
},
}
// ── Doctor ──────────────────────────────────────────────────────────────────
#[derive(Debug, Args, Default)]
struct DoctorArgs {
/// Accept defaults without prompting
#[arg(long)]
yes: bool,
/// Apply recommended repairs without prompting
#[arg(long)]
repair: bool,
/// Run without prompts (safe migrations only)
#[arg(long)]
non_interactive: bool,
/// Output JSON
#[arg(long)]
json: bool,
}
// ── TUI ─────────────────────────────────────────────────────────────────────
#[derive(Debug, Args, Default)]
struct TuiArgs {
/// Gateway WebSocket URL (overrides config)
#[arg(long = "url", value_name = "URL")]
url: Option<String>,
/// Gateway token
#[arg(long, value_name = "TOKEN")]
token: Option<String>,
/// Gateway password
#[arg(long, value_name = "PASSWORD")]
password: Option<String>,
/// Session key to resume
#[arg(long, value_name = "KEY")]
session: Option<String>,
/// Send an initial message instead of entering interactive mode
#[arg(long, value_name = "TEXT")]
message: Option<String>,
}
// ── Command / Message ───────────────────────────────────────────────────────
#[derive(Debug, Args)]
struct CommandArgs {
/// Command text to execute
#[arg(value_name = "COMMAND", trailing_var_arg = true)]
command: Vec<String>,
/// Gateway WebSocket URL (ws://…)
#[arg(
long = "gateway",
alias = "url",
alias = "ws",
value_name = "WS_URL",
env = "RUSTYCLAW_GATEWAY"
)]
gateway: Option<String>,
}
// ── Ask (headless mode) ─────────────────────────────────────────────────────
#[derive(Debug, Args)]
#[command(after_help = "\
EXAMPLES:
rustyclaw ask 'What is 2+2?'
echo 'Summarize this' | rustyclaw ask --stdin
rustyclaw ask --model anthropic/claude-haiku 'Quick question'
rustyclaw ask --no-tools 'Just chat, no actions'
")]
struct AskArgs {
/// Prompt text (can also be provided via --stdin)
#[arg(value_name = "PROMPT", trailing_var_arg = true)]
prompt: Vec<String>,
/// Read prompt from stdin
#[arg(long)]
stdin: bool,
/// Model to use (overrides default)
#[arg(long, short, value_name = "MODEL")]
model: Option<String>,
/// Disable tool use (pure chat mode)
#[arg(long)]
no_tools: bool,
/// Output raw JSON response
#[arg(long)]
json: bool,
/// System prompt override
#[arg(long, value_name = "PROMPT")]
system: Option<String>,
/// Gateway WebSocket URL (ws://…)
#[arg(
long = "gateway",
alias = "url",
alias = "ws",
value_name = "WS_URL",
env = "RUSTYCLAW_GATEWAY"
)]
gateway: Option<String>,
/// Maximum tokens in response
#[arg(long, value_name = "TOKENS")]
max_tokens: Option<u32>,
/// Temperature (0.0-2.0)
#[arg(long, value_name = "TEMP")]
temperature: Option<f32>,
}
// ── Status ──────────────────────────────────────────────────────────────────
#[derive(Debug, Args, Default)]
struct StatusArgs {
/// Output JSON
#[arg(long)]
json: bool,
/// Show all available information
#[arg(long)]
all: bool,
/// Include usage statistics
#[arg(long)]
usage: bool,
/// Verbose output
#[arg(long, short)]
verbose: bool,
}
// ── Gateway subcommands ─────────────────────────────────────────────────────
#[derive(Debug, Subcommand)]
enum GatewayCommands {
/// Start the gateway (daemon/background)
Start,
/// Stop a running gateway
Stop,
/// Restart the gateway
Restart,
/// Show gateway status
Status {
/// Output JSON
#[arg(long)]
json: bool,
},
/// Reload gateway configuration without restarting
Reload,
/// Run the gateway in the foreground (like `rustyclaw-gateway`)
Run(GatewayRunArgs),
}
#[derive(Debug, Args, Default)]
struct GatewayRunArgs {
/// Gateway port
#[arg(long, value_name = "PORT", default_value_t = 9001)]
port: u16,
/// Bind mode
#[arg(long, value_enum, default_value_t = GatewayBind::Loopback)]
bind: GatewayBind,
/// Auth token
#[arg(long, value_name = "TOKEN")]
token: Option<String>,
/// Auth mode
#[arg(long, value_enum)]
auth: Option<GatewayAuthMode>,
/// Auth password
#[arg(long, value_name = "PASSWORD")]
password: Option<String>,
/// Overwrite existing configuration
#[arg(long)]
force: bool,
/// Verbose logging
#[arg(long, short)]
verbose: bool,
}
// ── Skills subcommands ──────────────────────────────────────────────────────
#[derive(Debug, Subcommand)]
enum SkillsCommands {
/// List installed skills
List,
/// Show info about a skill
Info {
/// Skill name
#[arg(value_name = "NAME")]
name: String,
},
/// Check skills for issues
Check,
}
// ── ClawHub subcommands ─────────────────────────────────────────────────────
#[derive(Debug, Args)]
struct ClawHubCommands {
#[command(subcommand)]
command: Option<ClawHubSub>,
}
#[derive(Debug, Subcommand)]
enum ClawHubSub {
/// Authenticate with ClawHub
#[command(subcommand)]
Auth(ClawHubAuthCommands),
/// Search skills on ClawHub
Search {
/// Search query
#[arg(value_name = "QUERY", trailing_var_arg = true)]
query: Vec<String>,
},
/// Show trending / popular skills
Trending {
/// Filter by category
#[arg(value_name = "CATEGORY")]
category: Option<String>,
/// Max results to show
#[arg(long, short = 'n', default_value_t = 15)]
limit: usize,
},
/// List skill categories
Categories,
/// Show detailed info about a registry skill
Info {
/// Skill name
#[arg(value_name = "NAME")]
name: String,
},
/// Open ClawHub in your browser
Browse,
/// Show your ClawHub profile
Profile,
/// List your starred skills
Starred,
/// Star a skill
Star {
/// Skill name to star
#[arg(value_name = "NAME")]
name: String,
},
/// Unstar a skill
Unstar {
/// Skill name to unstar
#[arg(value_name = "NAME")]
name: String,
},
/// Install a skill from ClawHub
Install {
/// Skill name
#[arg(value_name = "NAME")]
name: String,
/// Version to install (default: latest)
#[arg(value_name = "VERSION")]
version: Option<String>,
},
/// Publish a local skill to ClawHub
Publish {
/// Skill name to publish
#[arg(value_name = "NAME")]
name: String,
},
}
#[derive(Debug, Subcommand)]
enum ClawHubAuthCommands {
/// Authenticate with an API token
Login {
/// API token from https://clawhub.ai/settings/tokens
#[arg(value_name = "TOKEN")]
token: String,
},
/// Show authentication status
Status,
/// Remove stored credentials
Logout,
}
// ═══════════════════════════════════════════════════════════════════════════
// Entrypoint
// ═══════════════════════════════════════════════════════════════════════════
#[tokio::main]
async fn main() -> Result<()> {
// Initialize structured logging from environment variables.
// Set RUSTYCLAW_LOG=debug or RUST_LOG=debug for verbose output.
rustyclaw_core::logging::init_from_env();
let cli = Cli::parse();
// Initialise colour output (respects --no-color / NO_COLOR).
rustyclaw_core::theme::init_color(cli.common.no_color);
let config_path = cli.common.config_path();
let mut config = Config::load(config_path)?;
cli.common.apply_overrides(&mut config);
match cli.command.unwrap_or(Commands::Tui(TuiArgs::default())) {
// ── Setup ───────────────────────────────────────────────
Commands::Setup(args) => {
// If any wizard-style flag is present, delegate to onboard.
let has_wizard_flags = args.wizard
|| args.non_interactive
|| args.mode.is_some()
|| args.remote_url.is_some()
|| args.remote_token.is_some();
if has_wizard_flags {
#[cfg(feature = "tui")]
{
let mut secrets = open_secrets(&config)?;
run_onboard_wizard(&mut config, &mut secrets, false, args.non_interactive)?;
// Optional agent setup step
let ws_dir = config.workspace_dir();
match rustyclaw_core::tools::agent_setup::exec_agent_setup(
&serde_json::json!({}),
&ws_dir,
) {
Ok(msg) => println!("{}", rustyclaw_core::theme::icon_ok(&msg)),
Err(e) => println!(
"{}",
rustyclaw_core::theme::icon_fail(&format!("Agent setup failed: {}", e))
),
}
}
#[cfg(not(feature = "tui"))]
{
eprintln!(
"Onboarding wizard is not available in this build. Build with --features tui to enable."
);
std::process::exit(1);
}
} else {
// Minimal setup: ensure directory skeleton + default config.
if let Some(ws) = args.workspace {
config.workspace_dir = Some(ws.into());
}
config.ensure_dirs()?;
config.save(None)?;
println!(
"{}",
rustyclaw_core::theme::icon_ok(&format!(
"Initialised config + workspace at {}",
rustyclaw_core::theme::info(&config.settings_dir.display().to_string())
))
);
// Optional agent setup step
let ws_dir = config.workspace_dir();
match rustyclaw_core::tools::agent_setup::exec_agent_setup(
&serde_json::json!({}),
&ws_dir,
) {
Ok(msg) => println!("{}", rustyclaw_core::theme::icon_ok(&msg)),
Err(e) => println!(
"{}",
rustyclaw_core::theme::icon_fail(&format!("Agent setup failed: {}", e))
),
}
}
}
// ── Onboard ─────────────────────────────────────────────
Commands::Onboard(_args) => {
#[cfg(feature = "tui")]
{
let mut secrets = open_secrets(&config)?;
run_onboard_wizard(&mut config, &mut secrets, _args.reset, _args.non_interactive)?;
// Optional agent setup step
let ws_dir = config.workspace_dir();
match rustyclaw_core::tools::agent_setup::exec_agent_setup(
&serde_json::json!({}),
&ws_dir,
) {
Ok(msg) => println!("{}", rustyclaw_core::theme::icon_ok(&msg)),
Err(e) => println!(
"{}",
rustyclaw_core::theme::icon_fail(&format!("Agent setup failed: {}", e))
),
}
}
#[cfg(not(feature = "tui"))]
{
eprintln!(
"Onboarding wizard is not available in this build. Build with --features tui to enable."
);
std::process::exit(1);
}
}
// ── Import ──────────────────────────────────────────────
Commands::Import(args) => {
run_import(&args, &mut config)?;
// Optional agent setup step
let ws_dir = config.workspace_dir();
match rustyclaw_core::tools::agent_setup::exec_agent_setup(
&serde_json::json!({}),
&ws_dir,
) {
Ok(msg) => println!("{}", rustyclaw_core::theme::icon_ok(&msg)),
Err(e) => println!(
"{}",
rustyclaw_core::theme::icon_fail(&format!("Agent setup failed: {}", e))
),
}
}
// ── RefreshToken ────────────────────────────────────────
Commands::RefreshToken(args) => {
run_refresh_token(&args, &mut config)?;
}
// ── Configure ───────────────────────────────────────────
Commands::Configure => {
#[cfg(feature = "tui")]
{
let mut secrets = open_secrets(&config)?;
run_onboard_wizard(&mut config, &mut secrets, false, false)?;
}
#[cfg(not(feature = "tui"))]
{
eprintln!(
"Configuration wizard is not available in this build. Build with --features tui to enable."
);
std::process::exit(1);
}
}
// ── Config get / set / unset ────────────────────────────
Commands::Config(sub) => match sub {
ConfigCommands::Get { path } => {
let value = config_get(&config, &path);
println!("{}", value);
}
ConfigCommands::Set { path, value } => {
config_set(&mut config, &path, &value)?;
config.save(None)?;
println!(
"{}",
rustyclaw_core::theme::icon_ok(&format!(
"Set {} = {}",
rustyclaw_core::theme::accent_bright(&path),
rustyclaw_core::theme::info(&value)
))
);
}
ConfigCommands::Unset { path } => {
config_unset(&mut config, &path)?;
config.save(None)?;
println!(
"{}",
rustyclaw_core::theme::icon_ok(&format!(
"Unset {}",
rustyclaw_core::theme::accent_bright(&path)
))
);
}
},
// ── Doctor ──────────────────────────────────────────────
Commands::Doctor(_args) => {
use rustyclaw_core::theme as t;
let sp = t::spinner("Running health checks…");
let checks = vec![
(
"Config file",
config.settings_dir.join("config.toml").exists(),
),
("Workspace dir", config.workspace_dir().exists()),
("Credentials dir", config.credentials_dir().exists()),
("SOUL.md", config.soul_path().exists()),
("Skills dir", config.skills_dir().exists()),
];
// Brief pause so the spinner is visible.
std::thread::sleep(std::time::Duration::from_millis(400));
sp.finish_and_clear();
let mut all_ok = true;
for (label, passed) in &checks {
if *passed {
println!(" {}", t::icon_ok(label));
} else {
println!(" {}", t::icon_fail(label));
all_ok = false;
}
}
println!();
if all_ok {
println!("{}", t::success("All checks passed."));
} else {
println!("{}", t::warn("Some checks failed."));
println!(
" Run {} or {} to fix.",
t::accent_bright("`rustyclaw setup`"),
t::accent_bright("`rustyclaw onboard`"),
);
}
}
// ── TUI ─────────────────────────────────────────────────
Commands::Tui(_args) => {
#[cfg(feature = "tui")]
{
// Apply TUI-specific overrides.
if let Some(url) = &_args.url {
config.gateway_url = Some(url.clone());
}
// The gateway owns the secrets vault. The TUI no longer needs
// a local vault password — it fetches secrets via gateway messages.
// A --password flag is forwarded to the gateway after connect if
// the vault is locked.
let mut app = App::new(config)?;
if let Some(pw) = _args.password {
app.set_deferred_vault_password(pw);
}
app.run().await?;
}
#[cfg(not(feature = "tui"))]
{
eprintln!(
"TUI is not available in this build. Build with --features tui to enable."
);
std::process::exit(1);
}
}
// ── Command / Message ───────────────────────────────────
Commands::Command(args) => {
let input = args.command.join(" ").trim().to_string();
if input.is_empty() {
anyhow::bail!("No command provided.");
}
if let Some(gateway_url) = args.gateway {
let response = send_command_via_gateway(&gateway_url, &input).await?;
println!("{}", response);
} else {
run_local_command(&mut config, &input)?;
}
}
// ── Ask (headless model interaction) ────────────────────
Commands::Ask(args) => {
handle_ask(&config, args).await?;
}
// ── Status ──────────────────────────────────────────────
Commands::Status(args) => {
print_status(&config, &args);
}
// ── Gateway sub-commands ────────────────────────────────
Commands::Gateway(sub) => {
match sub {
GatewayCommands::Start => {
let vault_password = extract_vault_password(&config);
let (port, bind) = commands::parse_gateway_defaults(&config);
commands::handle_start(&config, vault_password.as_deref(), port, bind)?;
}
GatewayCommands::Stop => {
commands::handle_stop(&config)?;
}
GatewayCommands::Restart => {
let vault_password = extract_vault_password(&config);
let (port, bind) = commands::parse_gateway_defaults(&config);
commands::handle_restart(&config, vault_password.as_deref(), port, bind)?;
}
GatewayCommands::Status { json } => {
commands::handle_status(&config, json);
}
GatewayCommands::Reload => {
use rustyclaw_core::theme as t;
let url = config
.gateway_url
.as_deref()
.unwrap_or("ws://127.0.0.1:9001");
let sp = t::spinner("Reloading gateway configuration\u{2026}");
match send_gateway_reload(url, config.totp_enabled).await {
Ok((provider, model)) => {
t::spinner_ok(
&sp,
&format!(
"Gateway reloaded: {} / {}",
t::info(&provider),
t::info(&model),
),
);
}
Err(e) => {
t::spinner_fail(&sp, &format!("Reload failed: {}", e));
}
}
}
GatewayCommands::Run(args) => {
let host = match args.bind {
GatewayBind::Loopback => "127.0.0.1",
GatewayBind::Lan => "0.0.0.0",
_ => "127.0.0.1",
};
commands::handle_run(config, host, args.port).await?;
}
}
}
// ── Skills sub-commands ─────────────────────────────────
Commands::Skills(sub) => {
// Use consolidated skills_dirs from config
let skills_dirs = config.skills_dirs();
let mut sm = SkillManager::with_dirs(skills_dirs);
sm.load_skills()?;
match sub {
SkillsCommands::List => {
use rustyclaw_core::theme as t;
let skills = sm.get_skills();
if skills.is_empty() {
println!("{}", t::muted("No skills installed."));
} else {
for s in skills {
if s.enabled {
println!(" {}", t::icon_ok(&t::accent_bright(&s.name)));
} else {
println!(" {}", t::icon_muted(&s.name));
}
}
}
}
SkillsCommands::Info { name } => {
println!(
"{}",
rustyclaw_core::theme::muted(&format!(
"Skill info for '{}' is not yet implemented.",
name
))
);
}
SkillsCommands::Check => {
println!(
"{}",
rustyclaw_core::theme::muted("Skill check is not yet implemented.")
);
}
}
}
// ── ClawHub sub-commands ────────────────────────────────
Commands::ClawHub(args) => {
use rustyclaw_core::theme as t;
// Use consolidated skills_dirs from config
let skills_dirs = config.skills_dirs();
let mut sm = SkillManager::with_dirs(skills_dirs);
sm.load_skills()?;
if let Some(url) = config.clawhub_url.as_deref() {
sm.set_registry(url, config.clawhub_token.clone());
} else if let Some(ref token) = config.clawhub_token {
let url = sm.registry_url().to_string();
sm.set_registry(&url, Some(token.clone()));
}
match args.command {
None => {
// No subcommand: show overview
println!("{}", t::accent_bright("ClawHub — Skill Registry"));
println!(" Registry: {}", t::info(sm.registry_url()));
match sm.auth_status() {
Ok(status) => println!(" Auth: {}", status),
Err(_) => println!(" Auth: {}", t::muted("unknown")),
}
println!();
println!(
" {} search <query> Search for skills",
t::muted("rustyclaw clawhub")
);
println!(
" {} trending [category] Browse trending skills",
t::muted("rustyclaw clawhub")
);
println!(
" {} categories List skill categories",
t::muted("rustyclaw clawhub")
);
println!(
" {} info <name> Show skill details",
t::muted("rustyclaw clawhub")
);
println!(
" {} browse Open ClawHub in browser",
t::muted("rustyclaw clawhub")
);
println!(
" {} auth login <token> Authenticate",
t::muted("rustyclaw clawhub")
);
println!(
" {} profile Show your profile",
t::muted("rustyclaw clawhub")
);
println!(