Repository navigation
Expand file tree
/
Copy pathmain.rs
More file actions
7422 lines (6734 loc) · 263 KB
/
Copy pathmain.rs
File metadata and controls
7422 lines (6734 loc) · 263 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`.
#![forbid(unsafe_code)]
use clap::{CommandFactory, Parser, Subcommand, ValueEnum, ValueHint};
use clap_complete::engine::ArgValueCompleter;
use clap_complete::env::CompleteEnv;
use miette::Result;
use openshell_cli::color::{self, ColorChoice, Colorize};
use std::collections::HashMap;
use std::io::Write;
use std::path::PathBuf;
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;
use openshell_core::proto::{GpuResourceRequirements, ServiceAuthorizationMode};
/// 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,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum GpuCliRequest {
DriverDefault,
Count(u32),
}
impl From<GpuCliRequest> for GpuResourceRequirements {
fn from(gpu: GpuCliRequest) -> Self {
match gpu {
GpuCliRequest::Count(count) => Self { count: Some(count) },
GpuCliRequest::DriverDefault => Self { count: None },
}
}
}
/// 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 {
// When a gateway name is explicitly provided (via flag or env var),
// trust it directly — don't require metadata to exist yet. This
// avoids a race condition where mTLS certs are stored under the
// real gateway name but the CLI falls back to using the raw
// endpoint URL (producing a mangled path like `https___...`).
let name = gateway_flag
.clone()
.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 register one with: openshell gateway add <endpoint>"
)
})?;
let metadata = load_gateway_metadata(&name).map_err(|_| {
miette::miette!(
"Unknown gateway '{name}'.\n\
Register it first: openshell gateway add <endpoint> --name {name}\n\
Or list available gateways: openshell gateway select"
)
})?;
Ok(GatewayContext {
name: metadata.name,
endpoint: metadata.gateway_endpoint,
})
}
fn parse_gpu_request(value: &str) -> std::result::Result<GpuCliRequest, String> {
if value.is_empty() {
return Ok(GpuCliRequest::DriverDefault);
}
let count = value
.parse::<u32>()
.map_err(|_| "GPU count must be a positive integer".to_string())?;
if count == 0 {
return Err("GPU count must be greater than 0".to_string());
}
Ok(GpuCliRequest::Count(count))
}
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 authentication token from local storage based on gateway auth mode.
///
/// Handles Cloudflare Access and OIDC auth modes by loading the stored token
/// and setting it on `TlsOptions`. For OIDC, automatically refreshes the token
/// if it's near expiry.
fn apply_auth(tls: &mut TlsOptions, gateway_name: &str) -> Result<()> {
if let Some(error) = apply_auth_with_status(tls, gateway_name) {
return Err(miette::miette!(error));
}
Ok(())
}
/// Apply stored authentication and return a user-facing preparation failure,
/// if the CLI already knows the credentials cannot be used.
fn apply_auth_with_status(tls: &mut TlsOptions, gateway_name: &str) -> Option<String> {
let meta = get_gateway_metadata(gateway_name)?;
match meta.auth_mode.as_deref() {
Some("cloudflare_jwt") => {
if let Some(token) = load_edge_token(gateway_name) {
tls.edge_token = Some(token);
None
} else {
Some(format!(
"edge credentials are missing; run `openshell gateway login {gateway_name}`"
))
}
}
Some("oidc") => {
let Some(bundle) = openshell_bootstrap::oidc_token::load_oidc_token(gateway_name)
else {
return Some(format!(
"OIDC credentials are missing; run `openshell gateway login {gateway_name}`"
));
};
if openshell_bootstrap::oidc_token::is_token_expired(&bundle) {
let insecure = std::env::var("OPENSHELL_GATEWAY_INSECURE")
.is_ok_and(|v| !v.is_empty() && v != "0" && v != "false");
// Try to refresh the token in-place using block_in_place
// so the async refresh can run within the sync apply_auth call.
match tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(
openshell_cli::oidc_auth::oidc_refresh_token(
&bundle,
meta.oidc_scopes.as_deref(),
insecure,
),
)
}) {
Ok(refreshed) => {
let _ = openshell_bootstrap::oidc_token::store_oidc_token(
gateway_name,
&refreshed,
);
tls.oidc_token = Some(refreshed.access_token);
None
}
Err(e) => {
tracing::warn!("OIDC token refresh failed: {e}");
if openshell_bootstrap::oidc_token::is_token_actually_expired(&bundle) {
Some(format!(
"OIDC token refresh failed: {e}\ncached OIDC token has expired; run `openshell gateway login {gateway_name}`"
))
} else {
tls.oidc_token = Some(bundle.access_token);
eprintln!(
"Warning: OIDC token refresh failed; continuing with the cached token: {e}"
);
None
}
}
}
} else {
tls.oidc_token = Some(bundle.access_token);
None
}
}
_ => None,
}
}
/// Resolve a sandbox name, falling back to the last-used sandbox for the
/// gateway and workspace.
///
/// When `name` is `None`, looks up the last sandbox recorded for the active
/// gateway and workspace. Prints a hint when falling back so the user knows
/// which sandbox was chosen.
fn resolve_sandbox_name(name: Option<String>, gateway: &str, workspace: &str) -> Result<String> {
if let Some(n) = name {
return Ok(n);
}
let last = load_last_sandbox(gateway, workspace).ok_or_else(|| {
miette::miette!(
"No sandbox name provided and no last-used sandbox.\n\
Specify a sandbox name or connect to one first: openshell 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
service: Expose sandbox services
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
profile: Browse and manage profiles
\x1b[1mGATEWAY COMMANDS\x1b[0m
gateway: Manage gateways
status: Show gateway status and information
whoami: Show the authenticated user identity
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 add http://127.0.0.1:8080 --local
$ 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 registry.example.com/agents/python:latest
$ 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 service my-sandbox --target-port 8000 --local 8000
$ openshell forward stop 8080
$ openshell forward list
";
const SERVICE_EXAMPLES: &str = "\x1b[1mALIAS\x1b[0m
svc
\x1b[1mEXAMPLES\x1b[0m
$ openshell service expose my-sandbox 8080
$ openshell service expose my-sandbox 8080 web
$ openshell service list
$ openshell service list my-sandbox
$ openshell service get my-sandbox web
$ openshell service delete my-sandbox web
";
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 update my-sandbox --add-endpoint api.github.com:443:read-only:rest:enforce
$ openshell policy update my-sandbox --add-endpoint realtime.example.com:443:read-write:websocket:enforce:websocket-credential-rewrite,allowed-ip=10.0.0.0/8
$ openshell policy update my-sandbox --rule-name github --binary /usr/bin/gh --add-allow 'api.github.com:443:GET:/repos/**'
$ openshell policy set --global --policy policy.yaml
$ openshell policy delete --global
$ openshell policy list my-sandbox
";
const SETTINGS_EXAMPLES: &str = "\x1b[1mEXAMPLES\x1b[0m
$ openshell settings get my-sandbox
$ openshell settings get --global
$ openshell settings set my-sandbox --key ocsf_json_enabled --value true
$ openshell settings set --global --key ocsf_json_enabled --value true
$ openshell settings delete --global --key ocsf_json_enabled
";
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 PROFILE_EXAMPLES: &str = "\x1b[1mEXAMPLES\x1b[0m
$ openshell profile list
$ openshell profile list --type provider -o json
$ openshell profile describe openai
$ openshell profile export openai
$ openshell profile import -f custom-api.yaml
";
const WORKSPACE_EXAMPLES: &str = "\x1b[1mALIAS\x1b[0m
ws
\x1b[1mEXAMPLES\x1b[0m
$ openshell workspace create --name staging
$ openshell workspace list
$ openshell workspace get staging
$ openshell workspace delete staging
";
const GATEWAY_EXAMPLES: &str = "\x1b[1mALIAS\x1b[0m
gw
\x1b[1mEXAMPLES\x1b[0m
$ openshell gateway add http://127.0.0.1:8080 --local
$ openshell gateway select my-gateway
$ openshell gateway info
$ openshell gateway remove my-gateway
";
const DOCTOR_HELP: &str = "\x1b[1mALIAS\x1b[0m
dr
\x1b[1mEXAMPLES\x1b[0m
$ openshell doctor check
";
/// `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>,
/// Skip TLS certificate verification for gateway connections.
#[arg(
long,
global = true,
env = "OPENSHELL_GATEWAY_INSECURE",
help_heading = "GATEWAY FLAGS"
)]
gateway_insecure: bool,
/// Workspace scope for resource operations.
#[arg(
long,
global = true,
env = "OPENSHELL_WORKSPACE",
default_value = "default",
help_heading = "GLOBAL FLAGS",
add = ArgValueCompleter::new(completers::complete_workspace_names)
)]
workspace: String,
/// Increase verbosity (-v, -vv, -vvv).
#[arg(short, long, action = clap::ArgAction::Count, global = true, help_heading = "GLOBAL FLAGS")]
verbose: u8,
/// When to colorize output. `auto` colorizes only when stdout is a terminal.
#[arg(
long,
global = true,
value_enum,
default_value_t = ColorChoice::Auto,
value_name = "WHEN",
env = "OPENSHELL_COLOR",
help_heading = "GLOBAL FLAGS"
)]
color: ColorChoice,
/// 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>,
},
/// Manage sandbox services.
#[command(alias = "svc", after_help = SERVICE_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Service {
#[command(subcommand)]
command: Option<ServiceCommands>,
},
/// 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>,
},
/// Browse and manage profiles.
#[command(after_help = PROFILE_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Profile {
#[command(subcommand)]
command: Option<ProfileCommands>,
},
/// Manage delegated identity credential records.
#[command(help_template = SUBCOMMAND_HELP_TEMPLATE)]
DelegatedCredential {
#[command(subcommand)]
command: Option<DelegatedCredentialCommands>,
},
/// Manage workspaces.
#[command(alias = "ws", after_help = WORKSPACE_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Workspace {
#[command(subcommand)]
command: Option<WorkspaceCommands>,
},
// ===================================================================
// GATEWAY COMMANDS
// ===================================================================
/// Manage gateways.
#[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 {
/// Output format.
#[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)]
output: OutputFormat,
},
/// Show the identity validated by the gateway.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Whoami {
/// Output format.
#[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)]
output: OutputFormat,
},
// ===================================================================
// DIAGNOSTIC COMMANDS
// ===================================================================
/// Diagnose gateway issues.
///
/// Check local prerequisites for gateway development.
#[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 <name> --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 name. Required in token mode.
#[arg(long)]
sandbox: 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, PartialEq, Eq, ValueEnum)]
enum OutputFormat {
Table,
Yaml,
Json,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
enum CliServiceAuthorizationMode {
#[default]
Strip,
BearerPassthrough,
}
impl From<CliServiceAuthorizationMode> for ServiceAuthorizationMode {
fn from(value: CliServiceAuthorizationMode) -> Self {
match value {
CliServiceAuthorizationMode::Strip => Self::Strip,
CliServiceAuthorizationMode::BearerPassthrough => Self::BearerPassthrough,
}
}
}
#[derive(Clone, Debug, ValueEnum)]
enum CliProviderRefreshStrategy {
Oauth2RefreshToken,
Oauth2ClientCredentials,
GoogleServiceAccountJwt,
AwsStsAssumeRole,
}
impl CliProviderRefreshStrategy {
fn as_str(&self) -> &'static str {
match self {
Self::Oauth2RefreshToken => "oauth2_refresh_token",
Self::Oauth2ClientCredentials => "oauth2_client_credentials",
Self::GoogleServiceAccountJwt => "google_service_account_jwt",
Self::AwsStsAssumeRole => "aws_sts_assume_role",
}
}
}
impl OutputFormat {
fn as_str(&self) -> &'static str {
match self {
Self::Table => "table",
Self::Yaml => "yaml",
Self::Json => "json",
}
}
}
#[derive(Clone, Debug, ValueEnum)]
enum PolicyGetOutput {
Table,
Json,
}
impl PolicyGetOutput {
fn as_str(&self) -> &'static str {
match self {
Self::Table => "table",
Self::Json => "json",
}
}
}
#[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,
}
}
}
#[derive(Subcommand, Debug)]
enum ProviderCommands {
/// Create a provider config.
#[command(group = clap::ArgGroup::new("cred_source").required(false).multiple(true).args(["from_existing", "credentials", "from_gcloud_adc", "runtime_credentials", "from_oidc_token"]), help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Create {
/// Provider name.
#[arg(long)]
name: String,
/// Provider type.
#[arg(long = "type")]
provider_type: String,
/// Labels to attach to the provider (KEY=VALUE, repeatable).
#[arg(long = "label", value_name = "KEY=VALUE")]
labels: Vec<String>,
/// Load provider credentials/config from existing local state.
#[arg(long, conflicts_with_all = ["credentials", "from_gcloud_adc", "runtime_credentials", "from_oidc_token"])]
from_existing: bool,
/// Provider credential pair (`KEY=VALUE`) or env lookup key (`KEY`).
#[arg(
long = "credential",
value_name = "KEY[=VALUE]",
conflicts_with_all = ["from_existing", "from_gcloud_adc", "runtime_credentials"]
)]
credentials: Vec<String>,
/// Configure credentials from gcloud Application Default Credentials
/// (`~/.config/gcloud/application_default_credentials.json`).
/// Valid for providers whose profile declares an ADC-compatible credential.
#[arg(long, group = "cred_source", conflicts_with_all = ["from_existing", "credentials", "runtime_credentials", "from_oidc_token"])]
from_gcloud_adc: bool,
/// Store the active gateway OIDC access token as the named provider credential.
#[arg(long, group = "cred_source", conflicts_with_all = ["from_existing", "from_gcloud_adc", "runtime_credentials"])]
from_oidc_token: bool,
/// Create a provider whose required credentials are resolved at runtime by the gateway/sandbox.
#[arg(long, conflicts_with_all = ["from_existing", "credentials", "from_gcloud_adc", "from_oidc_token"])]
runtime_credentials: bool,
/// Provider config key/value pair.
#[arg(long = "config", value_name = "KEY=VALUE")]
config: Vec<String>,
/// Use a platform-scoped (global) provider profile instead of
/// a workspace-scoped one.
#[arg(long)]
global_profile: bool,
},
/// Manage provider credential refresh.
#[command(subcommand, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Refresh(ProviderRefreshCommands),
/// 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 in this page.
#[arg(long, default_value_t = 100)]
page_size: i32,
/// Opaque continuation token from a previous page.
#[arg(long, default_value = "")]
page_token: String,
/// Filter providers by labels (e.g. env=dev,team=ml).
#[arg(long)]
label_selector: Option<String>,
/// Print only provider names, one per line.
#[arg(long, conflicts_with = "output")]
names: bool,
/// Output format.
#[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table, conflicts_with = "names")]
output: OutputFormat,
/// List providers across all workspaces (overrides --workspace).
#[arg(long)]
all_workspaces: bool,
},
/// List available provider profiles (alias for `profile list --type provider`).
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
ListProfiles {
/// Output format.
#[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)]
output: OutputFormat,
/// List platform-scoped profiles (ignores --workspace).
#[arg(long)]
global: bool,
},
/// Manage provider profiles (alias for `profile`).
#[command(subcommand, help_template = SUBCOMMAND_HELP_TEMPLATE)]
Profile(ProfileCommands),
/// 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_all = ["credentials", "from_oidc_token"])]
from_existing: bool,
/// Store the active gateway OIDC access token as the named provider credential.
#[arg(long, conflicts_with = "from_existing")]
from_oidc_token: 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>,
/// Credential expiry (`KEY=TIMESTAMP`). Accepts epoch milliseconds or RFC3339. A zero timestamp clears expiry.
#[arg(long = "credential-expires-at", value_name = "KEY=TIMESTAMP")]
credential_expires_at: Vec<String>,
#[command(flatten)]
readiness: ProviderReadinessArgs,
},