-
Notifications
You must be signed in to change notification settings - Fork 594
Expand file tree
/
Copy pathmain.rs
More file actions
3176 lines (2841 loc) · 113 KB
/
main.rs
File metadata and controls
3176 lines (2841 loc) · 113 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
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! `OpenShell` CLI - command-line interface for `OpenShell`.
use clap::{CommandFactory, Parser, Subcommand, ValueEnum, ValueHint};
use clap_complete::engine::ArgValueCompleter;
use clap_complete::env::CompleteEnv;
use miette::Result;
use owo_colors::OwoColorize;
use std::io::Write;
use openshell_bootstrap::{
edge_token::load_edge_token, get_gateway_metadata, list_gateways, load_active_gateway,
load_gateway_metadata, load_last_sandbox, save_last_sandbox,
};
use openshell_cli::completers;
use openshell_cli::run;
use openshell_cli::tls::TlsOptions;
/// Resolved gateway context: name + gateway endpoint.
struct GatewayContext {
/// The gateway name (used for TLS cert directory, metadata lookup, etc.).
name: String,
/// The gateway endpoint URL (e.g., `https://127.0.0.1` or `https://10.0.0.5`).
endpoint: String,
}
/// Resolve the gateway name to a [`GatewayContext`] with the gateway endpoint.
///
/// Resolution priority:
/// 1. `--gateway-endpoint` flag (direct URL, preserving metadata when available)
/// 2. `--gateway` flag (explicit name)
/// 3. `OPENSHELL_GATEWAY` environment variable
/// 4. Active gateway from `~/.config/openshell/active_gateway`
///
/// When `--gateway-endpoint` is provided, it is used directly as the endpoint.
/// If stored metadata can still identify the gateway, the stored gateway name
/// is preserved so auth and TLS materials continue to resolve correctly.
fn normalize_gateway_endpoint(endpoint: &str) -> &str {
endpoint.trim_end_matches('/')
}
fn find_gateway_by_endpoint(endpoint: &str) -> Option<String> {
let endpoint = normalize_gateway_endpoint(endpoint);
if let Some(active_name) = load_active_gateway()
&& let Ok(metadata) = load_gateway_metadata(&active_name)
&& normalize_gateway_endpoint(&metadata.gateway_endpoint) == endpoint
{
return Some(metadata.name);
}
list_gateways().ok()?.into_iter().find_map(|metadata| {
(normalize_gateway_endpoint(&metadata.gateway_endpoint) == endpoint)
.then_some(metadata.name)
})
}
fn resolve_gateway(
gateway_flag: &Option<String>,
gateway_endpoint: &Option<String>,
) -> Result<GatewayContext> {
if let Some(endpoint) = gateway_endpoint {
let name = gateway_flag
.clone()
.filter(|name| get_gateway_metadata(name).is_some())
.or_else(|| find_gateway_by_endpoint(endpoint))
.unwrap_or_else(|| endpoint.clone());
return Ok(GatewayContext {
name,
endpoint: endpoint.clone(),
});
}
let name = gateway_flag
.clone()
.or_else(|| {
std::env::var("OPENSHELL_GATEWAY")
.ok()
.filter(|v| !v.trim().is_empty())
})
.or_else(load_active_gateway)
.ok_or_else(|| {
miette::miette!(
"No active gateway.\n\
Set one with: openshell gateway select <name>\n\
Or deploy a new gateway: openshell gateway start"
)
})?;
let metadata = load_gateway_metadata(&name).map_err(|_| {
miette::miette!(
"Unknown gateway '{name}'.\n\
Deploy it first: openshell gateway start --name {name}\n\
Or list available gateways: openshell gateway select"
)
})?;
Ok(GatewayContext {
name: metadata.name,
endpoint: metadata.gateway_endpoint,
})
}
/// Resolve only the gateway name (without requiring metadata to exist).
///
/// Used by gateway commands that operate on a gateway by name but may not need
/// the gateway endpoint (e.g., `gateway start` creates the gateway).
fn resolve_gateway_name(gateway_flag: &Option<String>) -> Option<String> {
gateway_flag
.clone()
.or_else(|| {
std::env::var("OPENSHELL_GATEWAY")
.ok()
.filter(|v| !v.trim().is_empty())
})
.or_else(load_active_gateway)
}
/// Apply edge authentication token from local storage when the gateway uses edge auth.
///
/// When the resolved gateway has `auth_mode == "cloudflare_jwt"`, loads the
/// stored edge token from disk and sets it on the `TlsOptions`. The token is
/// always read from gateway metadata rather than supplied via a CLI flag.
fn apply_edge_auth(tls: &mut TlsOptions, gateway_name: &str) {
if let Some(meta) = get_gateway_metadata(gateway_name)
&& meta.auth_mode.as_deref() == Some("cloudflare_jwt")
&& let Some(token) = load_edge_token(gateway_name)
{
tls.edge_token = Some(token);
}
}
/// Resolve a sandbox name, falling back to the last-used sandbox for the gateway.
///
/// When `name` is `None`, looks up the last sandbox recorded for the active
/// gateway. Prints a hint when falling back so the user knows which sandbox
/// was chosen.
fn resolve_sandbox_name(name: Option<String>, gateway: &str) -> Result<String> {
if let Some(n) = name {
return Ok(n);
}
let last = load_last_sandbox(gateway).ok_or_else(|| {
miette::miette!(
"No sandbox name provided and no last-used sandbox.\n\
Specify a sandbox name or connect to one first: nav sandbox connect <name>"
)
})?;
eprintln!("{} Using sandbox '{}' (last used)", "→".bold(), last.bold(),);
Ok(last)
}
// Custom root help stays hand-authored so commands can be grouped into product
// areas without relying on clap's default subcommand listing. User-facing
// commands remain visible so shell completion can suggest them at the root.
const HELP_TEMPLATE: &str = "\
{about-with-newline}
\x1b[1mUSAGE\x1b[0m
openshell <command> <subcommand> [flags]
\x1b[1mSANDBOX COMMANDS\x1b[0m
sandbox: Manage sandboxes
forward: Manage port forwarding to a sandbox
logs: View sandbox logs
policy: Manage sandbox policy
settings: Manage sandbox and global settings
provider: Manage provider configuration
\x1b[1mGATEWAY COMMANDS\x1b[0m
gateway: Manage the gateway lifecycle
status: Show gateway status and information
inference: Manage inference configuration
doctor: Diagnose gateway issues
\x1b[1mADDITIONAL COMMANDS\x1b[0m
term: Launch the OpenShell interactive TUI
completions: Generate shell completions
ssh-proxy: SSH proxy (used by ProxyCommand)
help: Print this message or the help of the given subcommand(s)
\x1b[1mFLAGS\x1b[0m
{options}
\x1b[1mEXAMPLES\x1b[0m
$ openshell sandbox create
$ openshell gateway start
$ openshell logs my-sandbox
\x1b[1mLEARN MORE\x1b[0m
Use `openshell <command> --help` for more information about a command.
";
// Help template for subcommands (sandbox, gateway, etc.)
const SUBCOMMAND_HELP_TEMPLATE: &str = "\
{about-with-newline}
\x1b[1mUSAGE\x1b[0m
{usage}
\x1b[1mCOMMANDS\x1b[0m
{subcommands}
\x1b[1mFLAGS\x1b[0m
{options}
{after-help}";
// Help template for leaf commands (sandbox create, provider list, etc.)
const LEAF_HELP_TEMPLATE: &str = "\
{about-with-newline}
\x1b[1mUSAGE\x1b[0m
{usage}
{all-args}
{after-help}";
const SANDBOX_EXAMPLES: &str = "\x1b[1mALIAS\x1b[0m
sb
\x1b[1mEXAMPLES\x1b[0m
$ openshell sandbox create
$ openshell sandbox create --from python
$ openshell sandbox connect my-sandbox
$ openshell sandbox list
$ openshell sandbox delete my-sandbox
";
const FORWARD_EXAMPLES: &str = "\x1b[1mALIAS\x1b[0m
fwd
\x1b[1mEXAMPLES\x1b[0m
$ openshell forward start 8080
$ openshell forward start 3000 my-sandbox
$ openshell forward stop 8080
$ openshell forward list
";
const LOGS_EXAMPLES: &str = "\x1b[1mALIAS\x1b[0m
lg
\x1b[1mEXAMPLES\x1b[0m
$ openshell logs my-sandbox
$ openshell logs my-sandbox --tail
$ openshell logs --since 5m
$ openshell logs --source sandbox --level debug
";
const POLICY_EXAMPLES: &str = "\x1b[1mALIAS\x1b[0m
pol
\x1b[1mEXAMPLES\x1b[0m
$ openshell policy get my-sandbox
$ openshell policy set my-sandbox --policy policy.yaml
$ openshell policy set --global --policy policy.yaml
$ openshell policy delete --global
$ openshell policy list my-sandbox
$ openshell policy prove --policy policy.yaml --credentials creds.yaml
$ openshell policy prove --policy policy.yaml --credentials creds.yaml --compact
";
const SETTINGS_EXAMPLES: &str = "\x1b[1mEXAMPLES\x1b[0m
$ openshell settings get my-sandbox
$ openshell settings get --global
$ openshell settings set my-sandbox --key log_level --value debug
$ openshell settings set --global --key log_level --value warn
$ openshell settings set --global --key dummy_bool --value yes
$ openshell settings set --global --key dummy_int --value 42
$ openshell settings delete --global --key log_level
";
const PROVIDER_EXAMPLES: &str = "\x1b[1mEXAMPLES\x1b[0m
$ openshell provider create --name openai --type openai --credential OPENAI_API_KEY
$ openshell provider create --name anthropic --type anthropic --from-existing
$ openshell provider list
$ openshell provider get openai
$ openshell provider delete openai
";
const GATEWAY_EXAMPLES: &str = "\x1b[1mALIAS\x1b[0m
gw
\x1b[1mEXAMPLES\x1b[0m
$ openshell gateway start
$ openshell gateway start --name my-gateway --port 9090
$ openshell gateway stop
$ openshell gateway select my-gateway
$ openshell gateway info
";
const INFERENCE_EXAMPLES: &str = "\x1b[1mEXAMPLES\x1b[0m
$ openshell inference set --provider openai --model gpt-4
$ openshell inference get
$ openshell inference update --model gpt-4-turbo
";
const DOCTOR_HELP: &str = "\x1b[1mALIAS\x1b[0m
dr
\x1b[1mEXAMPLES\x1b[0m
$ openshell doctor check
$ openshell doctor logs --lines 100
$ openshell doctor exec -- kubectl get pods -A
$ openshell doctor llm.txt
\x1b[1mAI AGENT USAGE\x1b[0m
If you are a coding agent (LLM) diagnosing a gateway issue, run:
openshell doctor llm.txt
This prints a detailed diagnostic prompt with step-by-step instructions
for debugging gateway clusters using `openshell doctor logs` and
`openshell doctor exec`.
";
/// `OpenShell` CLI - agent execution and management.
#[derive(Parser, Debug)]
#[command(name = "openshell")]
#[command(author, version = openshell_core::VERSION, about, long_about = None)]
#[command(propagate_version = true)]
#[command(help_template = HELP_TEMPLATE)]
#[command(disable_help_subcommand = true)]
#[command(disable_help_flag = true, disable_version_flag = true)]
struct Cli {
/// Gateway name to operate on (resolved from stored metadata).
#[arg(
long,
short = 'g',
global = true,
env = "OPENSHELL_GATEWAY",
help_heading = "GATEWAY FLAGS",
add = ArgValueCompleter::new(completers::complete_gateway_names)
)]
gateway: Option<String>,
/// Gateway endpoint URL (e.g. <https://gateway.example.com>).
/// Connects directly without looking up gateway metadata.
#[arg(
long,
global = true,
env = "OPENSHELL_GATEWAY_ENDPOINT",
help_heading = "GATEWAY FLAGS"
)]
gateway_endpoint: Option<String>,
/// Increase verbosity (-v, -vv, -vvv).
#[arg(short, long, action = clap::ArgAction::Count, global = true, help_heading = "GLOBAL FLAGS")]
verbose: u8,
/// Print help.
#[arg(short = 'h', long, action = clap::ArgAction::Help, global = true, help_heading = "GLOBAL FLAGS")]
help: (),
/// Print version.
#[arg(short = 'V', long, action = clap::ArgAction::Version, global = true, help_heading = "GLOBAL FLAGS")]
version: (),
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand, Debug)]
enum Commands {
// ===================================================================
// SANDBOX COMMANDS
// ===================================================================
/// Manage sandboxes.
#[command(alias = "sb", after_help = SANDBOX_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Sandbox {
#[command(subcommand)]
command: Option<SandboxCommands>,
},
/// Manage port forwarding to a sandbox.
#[command(alias = "fwd", after_help = FORWARD_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Forward {
#[command(subcommand)]
command: Option<ForwardCommands>,
},
/// View sandbox logs.
#[command(alias = "lg", after_help = LOGS_EXAMPLES, help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Logs {
/// Sandbox name (defaults to last-used sandbox).
#[arg(add = ArgValueCompleter::new(completers::complete_sandbox_names))]
name: Option<String>,
/// Number of log lines to return.
#[arg(short, default_value_t = 200)]
n: u32,
/// Stream live logs.
#[arg(long)]
tail: bool,
/// Only show logs from this duration ago (e.g. 5m, 1h, 30s).
#[arg(long)]
since: Option<String>,
/// Filter by log source: "gateway", "sandbox", or "all" (default).
/// Can be specified multiple times: --source gateway --source sandbox
#[arg(long, default_value = "all")]
source: Vec<String>,
/// Minimum log level to display: error, warn, info (default), debug, trace.
#[arg(long, default_value = "")]
level: String,
},
/// Manage sandbox policy.
#[command(alias = "pol", after_help = POLICY_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Policy {
#[command(subcommand)]
command: Option<PolicyCommands>,
},
/// Manage sandbox and gateway settings.
#[command(after_help = SETTINGS_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Settings {
#[command(subcommand)]
command: Option<SettingsCommands>,
},
/// Manage network rules for a sandbox.
#[command(visible_alias = "rl", hide = true, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Rule {
#[command(subcommand)]
command: Option<DraftCommands>,
},
/// Manage provider configuration.
#[command(after_help = PROVIDER_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Provider {
#[command(subcommand)]
command: Option<ProviderCommands>,
},
// ===================================================================
// GATEWAY COMMANDS
// ===================================================================
/// Manage the gateway lifecycle.
#[command(alias = "gw", after_help = GATEWAY_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Gateway {
#[command(subcommand)]
command: Option<GatewayCommands>,
},
/// Show gateway status and information.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Status,
/// Manage inference configuration.
#[command(after_help = INFERENCE_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Inference {
#[command(subcommand)]
command: Option<InferenceCommands>,
},
// ===================================================================
// DIAGNOSTIC COMMANDS
// ===================================================================
/// Diagnose gateway issues.
///
/// Inspect logs, run commands inside the gateway container, and get
/// AI-assisted debugging guidance. If you are a coding agent, run
/// `openshell doctor llm.txt` for a full diagnostic prompt.
#[command(visible_alias = "dr", hide = true, after_help = DOCTOR_HELP, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Doctor {
#[command(subcommand)]
command: Option<DoctorCommands>,
},
// ===================================================================
// ADDITIONAL COMMANDS
// ===================================================================
/// Launch the `OpenShell` interactive TUI.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Term {
/// Color theme for the TUI: auto, dark, or light.
#[arg(long, default_value = "auto", env = "OPENSHELL_THEME")]
theme: openshell_tui::ThemeMode,
},
/// Generate shell completions.
#[command(after_long_help = COMPLETIONS_HELP, help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Completions {
/// Shell to generate completions for.
shell: CompletionShell,
},
/// SSH proxy (used by `ProxyCommand`).
///
/// Two mutually exclusive modes:
///
/// **Token mode** (used internally by `sandbox connect`):
/// `openshell ssh-proxy --gateway <url> --sandbox-id <id> --token <token>`
///
/// **Name mode** (for use in `~/.ssh/config`):
/// `openshell ssh-proxy --gateway <name> --name <sandbox-name>`
#[command(hide = true, help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
SshProxy {
/// Gateway URL (e.g., <https://gw.example.com:443/proxy/connect>).
/// Required in token mode. In name mode, can be a gateway name.
#[arg(long, short = 'g')]
gateway: Option<String>,
/// Sandbox id. Required in token mode.
#[arg(long)]
sandbox_id: Option<String>,
/// SSH session token. Required in token mode.
#[arg(long)]
token: Option<String>,
/// Gateway endpoint URL. Used in name mode. Deprecated: prefer --gateway.
#[arg(long)]
server: Option<String>,
/// Gateway name. Used with --name to resolve gateway from metadata.
#[arg(long)]
gateway_name: Option<String>,
/// Sandbox name. Used in name mode.
#[arg(long)]
name: Option<String>,
},
}
#[derive(Clone, Debug, ValueEnum)]
enum CompletionShell {
Bash,
Fish,
Zsh,
Powershell,
}
impl std::fmt::Display for CompletionShell {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Bash => write!(f, "bash"),
Self::Fish => write!(f, "fish"),
Self::Zsh => write!(f, "zsh"),
Self::Powershell => write!(f, "powershell"),
}
}
}
const COMPLETIONS_HELP: &str = "\
Generate shell completion scripts for OpenShell CLI.
Supported shells: bash, fish, zsh, powershell.
The script is output on stdout, allowing you to redirect the output to the file of your choosing.
The exact config file locations might vary based on your system. Make sure to restart your
shell before testing whether completions are working.
\x1b[1mBASH\x1b[0m
First, ensure that you install `bash-completion` using your package manager.
mkdir -p ~/.local/share/bash-completion/completions
openshell completions bash > ~/.local/share/bash-completion/completions/openshell
On macOS with Homebrew (install bash-completion first):
mkdir -p $(brew --prefix)/etc/bash_completion.d
openshell completions bash > $(brew --prefix)/etc/bash_completion.d/openshell.bash-completion
\x1b[1mFISH\x1b[0m
mkdir -p ~/.config/fish/completions
openshell completions fish > ~/.config/fish/completions/openshell.fish
\x1b[1mZSH\x1b[0m
mkdir -p ~/.zfunc
openshell completions zsh > ~/.zfunc/_openshell
Then add the following to your .zshrc before compinit:
fpath+=~/.zfunc
\x1b[1mPOWERSHELL\x1b[0m
openshell completions powershell >> $PROFILE
If no profile exists yet, create one first:
New-Item -Path $PROFILE -Type File -Force
";
fn normalize_completion_script(output: Vec<u8>, executable: &std::path::Path) -> Result<String> {
let script = String::from_utf8(output)
.map_err(|e| miette::miette!("generated completions were not valid UTF-8: {e}"))?;
Ok(script.replace(executable.to_string_lossy().as_ref(), "openshell"))
}
#[derive(Clone, Debug, ValueEnum)]
enum CliProviderType {
Claude,
Opencode,
Codex,
Generic,
Openai,
Anthropic,
Nvidia,
Gitlab,
Github,
Outlook,
}
#[derive(Clone, Debug, ValueEnum)]
enum CliEditor {
Vscode,
Cursor,
}
impl From<CliEditor> for openshell_cli::ssh::Editor {
fn from(value: CliEditor) -> Self {
match value {
CliEditor::Vscode => Self::Vscode,
CliEditor::Cursor => Self::Cursor,
}
}
}
impl CliProviderType {
fn as_str(&self) -> &'static str {
match self {
Self::Claude => "claude",
Self::Opencode => "opencode",
Self::Codex => "codex",
Self::Generic => "generic",
Self::Openai => "openai",
Self::Anthropic => "anthropic",
Self::Nvidia => "nvidia",
Self::Gitlab => "gitlab",
Self::Github => "github",
Self::Outlook => "outlook",
}
}
}
#[derive(Subcommand, Debug)]
enum ProviderCommands {
/// Create a provider config.
#[command(group = clap::ArgGroup::new("cred_source").required(true).args(["from_existing", "credentials"]), help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Create {
/// Provider name.
#[arg(long)]
name: String,
/// Provider type.
#[arg(long = "type", value_enum)]
provider_type: CliProviderType,
/// Load provider credentials/config from existing local state.
#[arg(long, conflicts_with = "credentials")]
from_existing: bool,
/// Provider credential pair (`KEY=VALUE`) or env lookup key (`KEY`).
#[arg(
long = "credential",
value_name = "KEY[=VALUE]",
conflicts_with = "from_existing"
)]
credentials: Vec<String>,
/// Provider config key/value pair.
#[arg(long = "config", value_name = "KEY=VALUE")]
config: Vec<String>,
},
/// Fetch a provider by name.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Get {
/// Provider name.
#[arg(add = ArgValueCompleter::new(completers::complete_provider_names))]
name: String,
},
/// List providers.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
List {
/// Maximum number of providers to return.
#[arg(long, default_value_t = 100)]
limit: u32,
/// Offset into the provider list.
#[arg(long, default_value_t = 0)]
offset: u32,
/// Print only provider names, one per line.
#[arg(long)]
names: bool,
},
/// Update an existing provider's credentials or config.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Update {
/// Provider name.
#[arg(add = ArgValueCompleter::new(completers::complete_provider_names))]
name: String,
/// Re-discover credentials from existing local state (e.g. env vars, config files).
#[arg(long, conflicts_with = "credentials")]
from_existing: bool,
/// Provider credential pair (`KEY=VALUE`) or env lookup key (`KEY`).
#[arg(
long = "credential",
value_name = "KEY[=VALUE]",
conflicts_with = "from_existing"
)]
credentials: Vec<String>,
/// Provider config key/value pair.
#[arg(long = "config", value_name = "KEY=VALUE")]
config: Vec<String>,
},
/// Delete providers by name.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Delete {
/// Provider names.
#[arg(required = true, num_args = 1.., value_name = "NAME", add = ArgValueCompleter::new(completers::complete_provider_names))]
names: Vec<String>,
},
}
// -----------------------------------------------------------------------
// Gateway commands (replaces the old `cluster` / `cluster admin` groups)
// -----------------------------------------------------------------------
#[derive(Subcommand, Debug)]
enum GatewayCommands {
/// Deploy/start the gateway.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Start {
/// Gateway name.
#[arg(long, default_value = "openshell", env = "OPENSHELL_GATEWAY")]
name: String,
/// SSH destination for remote deployment (e.g., user@hostname).
#[arg(long)]
remote: Option<String>,
/// Path to SSH private key for remote deployment.
#[arg(long, value_hint = ValueHint::FilePath)]
ssh_key: Option<String>,
/// Host port to map to the gateway (default: 8080).
#[arg(long, default_value_t = openshell_bootstrap::DEFAULT_GATEWAY_PORT)]
port: u16,
/// Override the gateway host written into cluster metadata.
///
/// By default, local clusters advertise 127.0.0.1. Set this when
/// the client cannot reach the Docker host at 127.0.0.1 — for
/// example in CI containers, WSL, or when Docker runs on a
/// remote host. Common values: `host.docker.internal`, a LAN IP,
/// or a hostname.
#[arg(long)]
gateway_host: Option<String>,
/// Destroy and recreate the gateway from scratch if one already exists.
///
/// Without this flag, an interactive prompt asks whether to recreate;
/// in non-interactive mode the existing gateway is reused silently.
#[arg(long)]
recreate: bool,
/// Listen on plaintext HTTP instead of mTLS.
///
/// Use when the gateway sits behind a reverse proxy (e.g., Cloudflare
/// Tunnel) that terminates TLS at the edge.
#[arg(long)]
plaintext: bool,
/// Disable gateway authentication (mTLS client certificate requirement).
///
/// The server still listens on TLS, but clients are not required to
/// present a certificate. Use when a reverse proxy (e.g., Cloudflare
/// Tunnel) terminates TLS and cannot forward client certs.
/// Ignored when --plaintext is set.
#[arg(long)]
disable_gateway_auth: bool,
/// Username for authenticating with the container image registry.
///
/// Defaults to `__token__` when `--registry-token` is set (the
/// standard convention for GHCR PAT-based auth). Only needed for
/// private registries — public GHCR repos pull without auth.
#[arg(long, env = "OPENSHELL_REGISTRY_USERNAME")]
registry_username: Option<String>,
/// Authentication token for pulling container images from the registry.
///
/// For GHCR, this is a GitHub personal access token (PAT) with
/// `read:packages` scope. Only needed for private registries —
/// public GHCR repos pull without auth. Used to pull the cluster
/// bootstrap image and passed into the k3s cluster so it can pull
/// server, sandbox, and community images at runtime.
#[arg(long, env = "OPENSHELL_REGISTRY_TOKEN")]
registry_token: Option<String>,
/// Enable NVIDIA GPU passthrough.
///
/// Passes all host GPUs into the cluster container and deploys the
/// NVIDIA k8s-device-plugin so Kubernetes workloads can request
/// `nvidia.com/gpu` resources. Requires NVIDIA drivers and the
/// NVIDIA Container Toolkit on the host.
#[arg(long)]
gpu: bool,
},
/// Stop the gateway (preserves state).
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Stop {
/// Gateway name (defaults to active gateway).
#[arg(long, env = "OPENSHELL_GATEWAY", add = ArgValueCompleter::new(completers::complete_gateway_names))]
name: Option<String>,
/// Override SSH destination (auto-resolved from gateway metadata).
#[arg(long)]
remote: Option<String>,
/// Path to SSH private key for remote gateway.
#[arg(long, value_hint = ValueHint::FilePath)]
ssh_key: Option<String>,
},
/// Destroy the gateway and its state.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Destroy {
/// Gateway name (defaults to active gateway).
#[arg(long, env = "OPENSHELL_GATEWAY", add = ArgValueCompleter::new(completers::complete_gateway_names))]
name: Option<String>,
/// Override SSH destination (auto-resolved from gateway metadata).
#[arg(long)]
remote: Option<String>,
/// Path to SSH private key for remote gateway.
#[arg(long, value_hint = ValueHint::FilePath)]
ssh_key: Option<String>,
},
/// Add an existing gateway.
///
/// Registers a gateway endpoint so it appears in `openshell gateway select`.
///
/// Without extra flags the gateway is treated as an edge-authenticated
/// (cloud) gateway and a browser is opened for authentication.
///
/// Pass `--remote <ssh-dest>` to register a remote mTLS gateway whose
/// Docker daemon is reachable over SSH. Pass `--local` to register a
/// local mTLS gateway running in Docker on this machine. In both cases
/// the CLI extracts mTLS certificates from the running container
/// automatically.
///
/// An `ssh://` endpoint (e.g., `ssh://user@host:8080`) is shorthand
/// for `--remote user@host` with the endpoint derived from the URL.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Add {
/// Gateway endpoint URL (e.g., `https://10.0.0.5:8080` or `ssh://user@host:8080`).
endpoint: String,
/// Gateway name (auto-derived from the endpoint hostname when omitted).
#[arg(long)]
name: Option<String>,
/// Register a remote mTLS gateway accessible via SSH.
#[arg(long, conflicts_with = "local")]
remote: Option<String>,
/// SSH private key for the remote host (used with `--remote` or `ssh://`).
#[arg(long, value_hint = ValueHint::FilePath)]
ssh_key: Option<String>,
/// Register a local mTLS gateway running in Docker on this machine.
#[arg(long, conflicts_with = "remote")]
local: bool,
},
/// Authenticate with an edge-authenticated gateway.
///
/// Opens a browser for the edge proxy's login flow and stores the
/// token locally. Use this to re-authenticate when a token expires.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Login {
/// Gateway name (defaults to the active gateway).
#[arg(add = ArgValueCompleter::new(completers::complete_gateway_names))]
name: Option<String>,
},
/// Select the active gateway.
///
/// When called without a name, opens an interactive chooser on a TTY and
/// lists available gateways in non-interactive mode.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Select {
/// Gateway name (omit to choose interactively or list in non-interactive mode).
#[arg(add = ArgValueCompleter::new(completers::complete_gateway_names))]
name: Option<String>,
},
/// Show gateway deployment details.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Info {
/// Gateway name (defaults to active gateway).
#[arg(long, env = "OPENSHELL_GATEWAY", add = ArgValueCompleter::new(completers::complete_gateway_names))]
name: Option<String>,
},
}
// -----------------------------------------------------------------------
// Inference commands
// -----------------------------------------------------------------------
#[derive(Subcommand, Debug)]
enum InferenceCommands {
/// Set gateway-level inference provider and model.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Set {
/// Provider name.
#[arg(long, add = ArgValueCompleter::new(completers::complete_provider_names))]
provider: String,
/// Model identifier to force for generation calls.
#[arg(long)]
model: String,
/// Configure the system inference route instead of the user-facing
/// route. System inference is used by platform functions (e.g. the
/// agent harness) and is not accessible to user code.
#[arg(long)]
system: bool,
/// Skip endpoint verification before saving the route.
#[arg(long)]
no_verify: bool,
},
/// Update gateway-level inference configuration (partial update).
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Update {
/// Provider name (unchanged if omitted).
#[arg(long, add = ArgValueCompleter::new(completers::complete_provider_names))]
provider: Option<String>,
/// Model identifier (unchanged if omitted).
#[arg(long)]
model: Option<String>,
/// Target the system inference route.
#[arg(long)]
system: bool,
/// Skip endpoint verification before saving the route.
#[arg(long)]
no_verify: bool,
},
/// Get gateway-level inference provider and model.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Get {
/// Show the system inference route instead of the user-facing route.
/// When omitted, both routes are displayed.
#[arg(long)]
system: bool,
},
}
// -----------------------------------------------------------------------
// Doctor (diagnostic) commands
// -----------------------------------------------------------------------
#[derive(Subcommand, Debug)]
enum DoctorCommands {
/// Fetch logs from the gateway container.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Logs {
/// Gateway name (defaults to active gateway).
#[arg(long, env = "OPENSHELL_GATEWAY")]
name: Option<String>,
/// Number of log lines to return (default: all).
#[arg(short, long)]
lines: Option<usize>,
/// Stream live logs (follow mode).
#[arg(long)]
tail: bool,
/// Override SSH destination for remote gateways.
#[arg(long)]
remote: Option<String>,
/// Path to SSH private key for remote gateways.
#[arg(long, value_hint = ValueHint::FilePath)]