-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathmain.rs
More file actions
7479 lines (6954 loc) · 255 KB
/
Copy pathmain.rs
File metadata and controls
7479 lines (6954 loc) · 255 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
//! OpenFang CLI — command-line interface for the OpenFang Agent OS.
//!
//! When a daemon is running (`openfang start`), the CLI talks to it over HTTP.
//! Otherwise, commands boot an in-process kernel (single-shot mode).
mod bundled_agents;
mod dotenv;
mod launcher;
mod mcp;
pub mod progress;
pub mod table;
mod templates;
mod tui;
mod ui;
use clap::{Parser, Subcommand};
use colored::Colorize;
use openfang_api::server::read_daemon_info;
use openfang_kernel::OpenFangKernel;
use openfang_types::agent::{AgentId, AgentManifest};
use std::io::{self, BufRead, Write};
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
#[cfg(windows)]
use std::sync::atomic::Ordering;
/// Global flag set by the Ctrl+C handler.
static CTRLC_PRESSED: AtomicBool = AtomicBool::new(false);
/// Install a Ctrl+C handler that force-exits the process.
/// On Windows/MINGW, the default handler doesn't reliably interrupt blocking
/// `read_line` calls, so we explicitly call `process::exit`.
fn install_ctrlc_handler() {
#[cfg(windows)]
{
extern "system" {
fn SetConsoleCtrlHandler(
handler: Option<unsafe extern "system" fn(u32) -> i32>,
add: i32,
) -> i32;
}
unsafe extern "system" fn handler(_ctrl_type: u32) -> i32 {
if CTRLC_PRESSED.swap(true, Ordering::SeqCst) {
// Second press: hard exit
std::process::exit(130);
}
// First press: print message and exit cleanly
let _ = std::io::Write::write_all(&mut std::io::stderr(), b"\nInterrupted.\n");
std::process::exit(0);
}
unsafe { SetConsoleCtrlHandler(Some(handler), 1) };
}
#[cfg(not(windows))]
{
// On Unix, the default SIGINT handler already interrupts read_line
// and terminates the process.
let _ = &CTRLC_PRESSED;
}
}
const AFTER_HELP: &str = "\
\x1b[1mHint:\x1b[0m Commands suffixed with [*] have subcommands. Run `<command> --help` for details.
\x1b[1;36mExamples:\x1b[0m
openfang init Initialize config and data directories
openfang start Start the kernel daemon
openfang tui Launch the interactive terminal dashboard
openfang chat Quick chat with the default agent
openfang agent new coder Spawn a new agent from a template
openfang models list Browse available LLM models
openfang add github Install the GitHub integration
openfang doctor Run diagnostic health checks
openfang channel setup Interactive channel setup wizard
openfang cron list List scheduled jobs
openfang uninstall Completely remove OpenFang from your system
\x1b[1;36mQuick Start:\x1b[0m
1. openfang init Set up config + API key
2. openfang start Launch the daemon
3. openfang chat Start chatting!
\x1b[1;36mMore:\x1b[0m
Docs: https://github.com/RightNow-AI/openfang
Dashboard: http://127.0.0.1:4200/ (when daemon is running)";
/// OpenFang — the open-source Agent Operating System.
#[derive(Parser)]
#[command(
name = "openfang",
version,
about = "\u{1F40D} OpenFang \u{2014} Open-source Agent Operating System",
long_about = "\u{1F40D} OpenFang \u{2014} Open-source Agent Operating System\n\n\
Deploy, manage, and orchestrate AI agents from your terminal.\n\
40 channels \u{00b7} 60 skills \u{00b7} 50+ models \u{00b7} infinite possibilities.",
after_help = AFTER_HELP,
)]
struct Cli {
/// Path to config file.
#[arg(long, global = true)]
config: Option<PathBuf>,
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand)]
enum Commands {
/// Initialize OpenFang (create ~/.openfang/ and default config).
Init {
/// Quick mode: no prompts, just write config + .env (for CI/scripts).
#[arg(long)]
quick: bool,
},
/// Start the OpenFang kernel daemon (API server + kernel).
Start {
/// Auto-approve all tool calls (no confirmation prompts).
#[arg(long)]
yolo: bool,
},
/// Stop the running daemon.
Stop,
/// Manage agents (new, list, chat, kill, spawn) [*].
#[command(subcommand)]
Agent(AgentCommands),
/// Manage workflows (list, create, run) [*].
#[command(subcommand)]
Workflow(WorkflowCommands),
/// Manage event triggers (list, create, delete) [*].
#[command(subcommand)]
Trigger(TriggerCommands),
/// Migrate from another agent framework to OpenFang.
Migrate(MigrateArgs),
/// Manage skills (install, list, search, create, remove) [*].
#[command(subcommand)]
Skill(SkillCommands),
/// Manage channel integrations (setup, test, enable, disable) [*].
#[command(subcommand)]
Channel(ChannelCommands),
/// Manage hands (list, activate, deactivate, info) [*].
#[command(subcommand)]
Hand(HandCommands),
/// Show or edit configuration (show, edit, get, set, keys) [*].
#[command(subcommand)]
Config(ConfigCommands),
/// Quick chat with the default agent.
Chat {
/// Optional agent name or ID to chat with.
agent: Option<String>,
},
/// Show kernel status.
Status {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Run diagnostic health checks.
Doctor {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
/// Attempt to auto-fix issues (create missing dirs/config).
#[arg(long)]
repair: bool,
},
/// Open the web dashboard in the default browser.
Dashboard,
/// Generate shell completion scripts.
Completion {
/// Shell to generate completions for.
#[arg(value_enum)]
shell: clap_complete::Shell,
},
/// Start MCP (Model Context Protocol) server over stdio.
Mcp,
/// Add an integration (one-click MCP server setup).
Add {
/// Integration name (e.g., "github", "slack", "notion").
name: String,
/// API key or token to store in the vault.
#[arg(long)]
key: Option<String>,
},
/// Remove an installed integration.
Remove {
/// Integration name.
name: String,
},
/// List or search integrations.
Integrations {
/// Search query (optional — lists all if omitted).
query: Option<String>,
},
/// Manage the credential vault (init, set, list, remove) [*].
#[command(subcommand)]
Vault(VaultCommands),
/// Scaffold a new skill or integration template.
New {
/// What to scaffold.
#[arg(value_enum)]
kind: ScaffoldKind,
},
/// Launch the interactive terminal dashboard.
Tui,
/// Browse models, aliases, and providers [*].
#[command(subcommand)]
Models(ModelsCommands),
/// Daemon control (start, stop, status) [*].
#[command(subcommand)]
Gateway(GatewayCommands),
/// Manage execution approvals (list, approve, reject) [*].
#[command(subcommand)]
Approvals(ApprovalsCommands),
/// Manage scheduled jobs (list, create, delete, enable, disable) [*].
#[command(subcommand)]
Cron(CronCommands),
/// List conversation sessions.
Sessions {
/// Optional agent name or ID to filter by.
agent: Option<String>,
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Tail the OpenFang log file.
Logs {
/// Number of lines to show.
#[arg(long, default_value = "50")]
lines: usize,
/// Follow log output in real time.
#[arg(long, short)]
follow: bool,
},
/// Quick daemon health check.
Health {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Dashboard authentication [*].
#[command(subcommand)]
Auth(AuthCommands),
/// Security tools and audit trail [*].
#[command(subcommand)]
Security(SecurityCommands),
/// Search and manage agent memory (KV store) [*].
#[command(subcommand)]
Memory(MemoryCommands),
/// Device pairing and token management [*].
#[command(subcommand)]
Devices(DevicesCommands),
/// Generate device pairing QR code.
Qr,
/// Webhook helpers and trigger management [*].
#[command(subcommand)]
Webhooks(WebhooksCommands),
/// Interactive onboarding wizard.
Onboard {
/// Quick non-interactive mode.
#[arg(long)]
quick: bool,
},
/// Quick non-interactive initialization.
Setup {
/// Quick mode (same as `init --quick`).
#[arg(long)]
quick: bool,
},
/// Interactive setup wizard for credentials and channels.
Configure,
/// Send a one-shot message to an agent.
Message {
/// Agent name or ID.
agent: String,
/// Message text.
text: String,
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// System info and version [*].
#[command(subcommand)]
System(SystemCommands),
/// Reset local config and state.
Reset {
/// Skip confirmation prompt.
#[arg(long)]
confirm: bool,
},
/// Completely uninstall OpenFang from your system.
Uninstall {
/// Skip confirmation prompt (also --yes).
#[arg(long, alias = "yes")]
confirm: bool,
/// Keep config files (config.toml, .env, secrets.env).
#[arg(long)]
keep_config: bool,
},
}
#[derive(Subcommand)]
enum VaultCommands {
/// Initialize the credential vault.
Init,
/// Store a credential in the vault.
Set {
/// Credential key (env var name).
key: String,
},
/// List all keys in the vault (values are hidden).
List,
/// Remove a credential from the vault.
Remove {
/// Credential key.
key: String,
},
}
#[derive(Clone, clap::ValueEnum)]
enum ScaffoldKind {
Skill,
Integration,
}
#[derive(clap::Args)]
struct MigrateArgs {
/// Source framework to migrate from.
#[arg(long, value_enum)]
from: MigrateSourceArg,
/// Path to the source workspace (auto-detected if not set).
#[arg(long)]
source_dir: Option<PathBuf>,
/// Dry run — show what would be imported without making changes.
#[arg(long)]
dry_run: bool,
}
#[derive(Clone, clap::ValueEnum)]
enum MigrateSourceArg {
Openclaw,
Langchain,
Autogpt,
}
#[derive(Subcommand)]
enum SkillCommands {
/// Install a skill from FangHub or a local directory.
Install {
/// Skill name, local path, or git URL.
source: String,
},
/// List installed skills.
List,
/// Remove an installed skill.
Remove {
/// Skill name.
name: String,
},
/// Search FangHub for skills.
Search {
/// Search query.
query: String,
},
/// Create a new skill scaffold.
Create,
}
#[derive(Subcommand)]
enum ChannelCommands {
/// List configured channels and their status.
List,
/// Interactive setup wizard for a channel.
Setup {
/// Channel name (telegram, discord, slack, whatsapp, etc.). Shows picker if omitted.
channel: Option<String>,
},
/// Test a channel by sending a test message.
Test {
/// Channel name.
channel: String,
},
/// Enable a channel.
Enable {
/// Channel name.
channel: String,
},
/// Disable a channel without removing its configuration.
Disable {
/// Channel name.
channel: String,
},
}
#[derive(Subcommand)]
enum HandCommands {
/// List all available hands.
List,
/// Show currently active hand instances.
Active,
/// Install a hand from a local directory containing HAND.toml.
Install {
/// Path to the hand directory (must contain HAND.toml).
path: String,
},
/// Activate a hand by ID.
Activate {
/// Hand ID (e.g. "clip", "lead", "researcher").
id: String,
/// Optional instance name. Required to run multiple instances of the same hand.
#[arg(long, short = 'n')]
name: Option<String>,
},
/// Deactivate an active hand instance.
Deactivate {
/// Hand ID.
id: String,
},
/// Show detailed info about a hand.
Info {
/// Hand ID.
id: String,
},
/// Check dependency status for a hand.
CheckDeps {
/// Hand ID.
id: String,
},
/// Install missing dependencies for a hand.
InstallDeps {
/// Hand ID.
id: String,
},
/// Pause a running hand instance.
Pause {
/// Instance ID (from `hand active`).
id: String,
},
/// Resume a paused hand instance.
Resume {
/// Instance ID (from `hand active`).
id: String,
},
/// Get, set, or list settings for an active hand instance.
///
/// With no flags, prints the current settings. Use `--set KEY=VAL`
/// (repeatable) to update values, `--unset KEY` to remove a value,
/// or `--get KEY` to print a single value.
Config {
/// Hand ID (e.g. "browser", "clip").
id: String,
/// Print a single setting value.
#[arg(long, value_name = "KEY", conflicts_with_all = ["set", "unset", "list"])]
get: Option<String>,
/// Set a setting value. Format: `KEY=VALUE`. May be repeated.
#[arg(long, value_name = "KEY=VALUE")]
set: Vec<String>,
/// Unset a setting key. May be repeated.
#[arg(long, value_name = "KEY")]
unset: Vec<String>,
/// List the current settings (default when no other flag is given).
#[arg(long)]
list: bool,
},
}
#[derive(Subcommand)]
enum ConfigCommands {
/// Show the current configuration.
Show,
/// Open the configuration file in your editor.
Edit,
/// Get a config value by dotted key path (e.g. "default_model.provider").
Get {
/// Dotted key path (e.g. "default_model.provider", "api_listen").
key: String,
},
/// Set a config value (warning: strips TOML comments).
Set {
/// Dotted key path.
key: String,
/// New value.
value: String,
},
/// Remove a config key (warning: strips TOML comments).
Unset {
/// Dotted key path to remove (e.g. "api.cors_origin").
key: String,
},
/// Save an API key to ~/.openfang/.env (prompts interactively).
SetKey {
/// Provider name (groq, anthropic, openai, gemini, deepseek, etc.).
provider: String,
},
/// Remove an API key from ~/.openfang/.env.
DeleteKey {
/// Provider name.
provider: String,
},
/// Test provider connectivity with the stored API key.
TestKey {
/// Provider name.
provider: String,
},
}
#[derive(Subcommand)]
enum AgentCommands {
/// Spawn a new agent from a template (interactive or by name).
New {
/// Template name (e.g., "coder", "assistant"). Interactive picker if omitted.
template: Option<String>,
},
/// Spawn a new agent from a manifest file.
Spawn {
/// Path to the agent manifest TOML file.
manifest: PathBuf,
},
/// List all running agents.
List {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Interactive chat with an agent.
Chat {
/// Agent ID (UUID).
agent_id: String,
},
/// Kill an agent.
Kill {
/// Agent ID (UUID).
agent_id: String,
},
/// Set an agent property (e.g., model).
Set {
/// Agent ID (UUID).
agent_id: String,
/// Field to set (model).
field: String,
/// New value.
value: String,
},
}
#[derive(Subcommand)]
enum WorkflowCommands {
/// List all registered workflows.
List,
/// Create a workflow from a JSON file.
Create {
/// Path to a JSON file describing the workflow.
file: PathBuf,
},
/// Get a workflow by ID.
Get {
/// Workflow ID (UUID).
workflow_id: String,
},
/// Update a workflow from a JSON file.
Update {
/// Workflow ID (UUID).
workflow_id: String,
/// Path to a JSON file with the updated workflow definition.
file: PathBuf,
},
/// Delete a workflow by ID.
Delete {
/// Workflow ID (UUID).
workflow_id: String,
},
/// Run a workflow by ID.
Run {
/// Workflow ID (UUID).
workflow_id: String,
/// Input text for the workflow.
input: String,
},
}
#[derive(Subcommand)]
enum TriggerCommands {
/// List all triggers (optionally filtered by agent).
List {
/// Optional agent ID to filter by.
#[arg(long)]
agent_id: Option<String>,
},
/// Create a trigger for an agent.
Create {
/// Agent ID (UUID) that owns the trigger.
agent_id: String,
/// Trigger pattern as JSON (e.g. '{"lifecycle":{}}' or '{"agent_spawned":{"name_pattern":"*"}}').
pattern_json: String,
/// Prompt template (use {{event}} placeholder).
#[arg(long, default_value = "Event: {{event}}")]
prompt: String,
/// Maximum number of times to fire (0 = unlimited).
#[arg(long, default_value = "0")]
max_fires: u64,
},
/// Delete a trigger by ID.
Delete {
/// Trigger ID (UUID).
trigger_id: String,
},
}
#[derive(Subcommand)]
enum ModelsCommands {
/// List available models (optionally filter by provider).
List {
/// Filter by provider name.
#[arg(long)]
provider: Option<String>,
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Show model aliases (shorthand names).
Aliases {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// List known LLM providers and their auth status.
Providers {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Set the default model for the daemon.
Set {
/// Model ID or alias (e.g. "gpt-4o", "claude-sonnet"). Interactive picker if omitted.
model: Option<String>,
},
}
#[derive(Subcommand)]
enum GatewayCommands {
/// Start the kernel daemon.
Start,
/// Stop the running daemon.
Stop,
/// Show daemon status.
Status {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
}
#[derive(Subcommand)]
enum ApprovalsCommands {
/// List pending approvals.
List {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Approve a pending request.
Approve {
/// Approval ID.
id: String,
},
/// Reject a pending request.
Reject {
/// Approval ID.
id: String,
},
}
#[derive(Subcommand)]
enum CronCommands {
/// List scheduled jobs.
List {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Create a new scheduled job.
Create {
/// Agent name or ID to run.
agent: String,
/// Cron expression (e.g. "0 */6 * * *").
spec: String,
/// Prompt to send when the job fires.
prompt: String,
/// Optional job name (auto-generated if omitted).
#[arg(long)]
name: Option<String>,
},
/// Delete a scheduled job.
Delete {
/// Job ID.
id: String,
},
/// Enable a disabled job.
Enable {
/// Job ID.
id: String,
},
/// Disable a job without deleting it.
Disable {
/// Job ID.
id: String,
},
}
#[derive(Subcommand)]
enum AuthCommands {
/// Generate an Argon2id password hash for dashboard authentication.
HashPassword,
}
#[derive(Subcommand)]
enum SecurityCommands {
/// Show security status summary.
Status {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Show recent audit trail entries.
Audit {
/// Maximum number of entries to show.
#[arg(long, default_value = "20")]
limit: usize,
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Verify audit trail integrity (Merkle chain).
Verify,
}
#[derive(Subcommand)]
enum MemoryCommands {
/// List KV pairs for an agent.
List {
/// Agent name or ID.
agent: String,
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Get a specific KV value.
Get {
/// Agent name or ID.
agent: String,
/// Key name.
key: String,
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Set a KV value.
Set {
/// Agent name or ID.
agent: String,
/// Key name.
key: String,
/// Value to store.
value: String,
},
/// Delete a KV pair.
Delete {
/// Agent name or ID.
agent: String,
/// Key name.
key: String,
},
}
#[derive(Subcommand)]
enum DevicesCommands {
/// List paired devices.
List {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Start a new device pairing flow.
Pair,
/// Remove a paired device.
Remove {
/// Device ID.
id: String,
},
}
#[derive(Subcommand)]
enum WebhooksCommands {
/// List configured webhooks.
List {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Create a new webhook trigger.
Create {
/// Agent name or ID.
agent: String,
/// Webhook callback URL.
url: String,
},
/// Delete a webhook.
Delete {
/// Webhook ID.
id: String,
},
/// Send a test payload to a webhook.
Test {
/// Webhook ID.
id: String,
},
}
#[derive(Subcommand)]
enum SystemCommands {
/// Show detailed system info.
Info {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
/// Show version information.
Version {
/// Output as JSON for scripting.
#[arg(long)]
json: bool,
},
}
fn config_log_level() -> String {
let config_path = if let Ok(home) = std::env::var("OPENFANG_HOME") {
std::path::PathBuf::from(home).join("config.toml")
} else {
dirs::home_dir()
.unwrap_or_else(std::env::temp_dir)
.join(".openfang")
.join("config.toml")
};
if let Ok(content) = std::fs::read_to_string(config_path) {
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with("log_level") {
if let Some(val) = trimmed.split('=').nth(1) {
let level = val.trim().trim_matches('"').trim_matches('\'');
if !level.is_empty() {
return level.to_string();
}
}
}
}
}
"info".to_string()
}
fn init_tracing_stderr() {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(config_log_level())),
)
.with_writer(std::io::stderr)
.init();
}
/// Get the OpenFang home directory, respecting OPENFANG_HOME env var.
fn cli_openfang_home() -> std::path::PathBuf {
if let Ok(home) = std::env::var("OPENFANG_HOME") {
return std::path::PathBuf::from(home);
}
dirs::home_dir()
.unwrap_or_else(std::env::temp_dir)
.join(".openfang")
}
/// Redirect tracing to a log file so it doesn't corrupt the ratatui TUI.
fn init_tracing_file() {
let log_dir = cli_openfang_home();
let _ = std::fs::create_dir_all(&log_dir);
let log_path = log_dir.join("tui.log");
match std::fs::File::create(&log_path) {
Ok(file) => {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(config_log_level())),
)
.with_writer(std::sync::Mutex::new(file))
.with_ansi(false)
.init();
}
Err(_) => {
// Fallback: suppress all output rather than corrupt the TUI
tracing_subscriber::fmt()
.with_max_level(tracing::Level::ERROR)
.with_writer(std::io::sink)
.init();
}
}
}
/// Write `msg` to stdout, silently exiting with code 0 on BrokenPipe.
/// Use this instead of `println!` for machine-readable (JSON) output that is
/// commonly piped into other tools.
fn write_stdout_safe(msg: &str) {
let out = std::io::stdout();
let mut lock = out.lock();
if let Err(e) = writeln!(lock, "{}", msg) {
if e.kind() == std::io::ErrorKind::BrokenPipe {
std::process::exit(0);
}
eprintln!("error: failed writing to stdout: {e}");
std::process::exit(1);
}
}
fn main() {
// Load ~/.openfang/.env into process environment (system env takes priority).
dotenv::load_dotenv();
let cli = Cli::parse();
// Determine if this invocation launches a ratatui TUI.
// TUI modes must NOT install the Ctrl+C handler (it calls process::exit
// which bypasses ratatui::restore and leaves the terminal in raw mode).
// TUI modes also need file-based tracing (stderr output corrupts the TUI).
let is_launcher = cli.command.is_none() && std::io::IsTerminal::is_terminal(&std::io::stdout());
let is_tui_mode = is_launcher
|| matches!(cli.command, Some(Commands::Tui))
|| matches!(cli.command, Some(Commands::Chat { .. }))
|| matches!(
cli.command,
Some(Commands::Agent(AgentCommands::Chat { .. }))
);
if is_tui_mode {
init_tracing_file();
} else {
// CLI subcommands: install Ctrl+C handler for clean interrupt of
// blocking read_line calls, and trace to stderr.
install_ctrlc_handler();
init_tracing_stderr();
}
match cli.command {
None => {
if !std::io::IsTerminal::is_terminal(&std::io::stdout()) {
// Piped: fall back to text help
use clap::CommandFactory;
Cli::command().print_help().unwrap();
println!();
return;
}
match launcher::run(cli.config.clone()) {
launcher::LauncherChoice::GetStarted => cmd_init(false),
launcher::LauncherChoice::Chat => cmd_quick_chat(cli.config, None),
launcher::LauncherChoice::Dashboard => cmd_dashboard(),
launcher::LauncherChoice::DesktopApp => launcher::launch_desktop_app(),
launcher::LauncherChoice::TerminalUI => tui::run(cli.config),
launcher::LauncherChoice::ShowHelp => {
use clap::CommandFactory;
Cli::command().print_help().unwrap();
println!();
}
launcher::LauncherChoice::Quit => {}
}
}
Some(Commands::Tui) => tui::run(cli.config),
Some(Commands::Init { quick }) => cmd_init(quick),
Some(Commands::Start { yolo }) => cmd_start(cli.config, yolo),
Some(Commands::Stop) => cmd_stop(),
Some(Commands::Agent(sub)) => match sub {
AgentCommands::New { template } => cmd_agent_new(cli.config, template),
AgentCommands::Spawn { manifest } => cmd_agent_spawn(cli.config, manifest),
AgentCommands::List { json } => cmd_agent_list(cli.config, json),
AgentCommands::Chat { agent_id } => cmd_agent_chat(cli.config, &agent_id),
AgentCommands::Kill { agent_id } => cmd_agent_kill(cli.config, &agent_id),
AgentCommands::Set {
agent_id,
field,
value,
} => cmd_agent_set(&agent_id, &field, &value),
},
Some(Commands::Workflow(sub)) => match sub {
WorkflowCommands::List => cmd_workflow_list(),
WorkflowCommands::Create { file } => cmd_workflow_create(file),
WorkflowCommands::Get { workflow_id } => cmd_workflow_get(&workflow_id),
WorkflowCommands::Update { workflow_id, file } => {
cmd_workflow_update(&workflow_id, file)
}
WorkflowCommands::Delete { workflow_id } => cmd_workflow_delete(&workflow_id),
WorkflowCommands::Run { workflow_id, input } => cmd_workflow_run(&workflow_id, &input),
},
Some(Commands::Trigger(sub)) => match sub {
TriggerCommands::List { agent_id } => cmd_trigger_list(agent_id.as_deref()),
TriggerCommands::Create {