Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1312 lines (1134 loc) · 37.1 KB
/
Copy pathmain.go
File metadata and controls
1312 lines (1134 loc) · 37.1 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
package main
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss"
"github.com/dustin/go-humanize"
"github.com/mattn/go-isatty"
"github.com/leighmcculloch/silo/backend"
applecontainer "github.com/leighmcculloch/silo/backend/container"
"github.com/leighmcculloch/silo/backend/docker"
flybackend "github.com/leighmcculloch/silo/backend/fly"
namespacebackend "github.com/leighmcculloch/silo/backend/namespace"
"github.com/leighmcculloch/silo/cli"
"github.com/leighmcculloch/silo/config"
"github.com/leighmcculloch/silo/configshow"
"github.com/leighmcculloch/silo/run"
"github.com/leighmcculloch/silo/tilde"
"github.com/leighmcculloch/silo/tools"
"github.com/leighmcculloch/silo/tools/claudecode"
"github.com/leighmcculloch/silo/tools/cline"
"github.com/leighmcculloch/silo/tools/codexcli"
"github.com/leighmcculloch/silo/tools/copilotcli"
"github.com/leighmcculloch/silo/tools/kilocode"
"github.com/leighmcculloch/silo/tools/mistralvibe"
"github.com/leighmcculloch/silo/tools/opencode"
"github.com/leighmcculloch/silo/tools/paperclipai"
"github.com/leighmcculloch/silo/tools/pi"
"github.com/leighmcculloch/silo/tools/shell"
"github.com/spf13/cobra"
)
var (
version = "dev"
// supportedTools is the single source of truth for which tools silo
// supports. To add a tool: create tools/<name>/, define its Tool, and
// add it here. To remove a tool: delete from this slice.
supportedTools = []tools.Tool{
claudecode.Tool,
cline.Tool,
codexcli.Tool,
opencode.Tool,
paperclipai.Tool,
copilotcli.Tool,
mistralvibe.Tool,
kilocode.Tool,
pi.Tool,
}
)
// toolDefaults returns the default ToolConfig map derived from supportedTools.
func toolDefaults() map[string]config.ToolConfig {
return tools.DefaultToolConfigs(supportedTools)
}
// findTool returns the Tool definition for the given name, or nil if not found.
func findTool(name string) *tools.Tool {
for i := range supportedTools {
if supportedTools[i].Name == name {
return &supportedTools[i]
}
}
return nil
}
func main() {
os.Exit(runMain(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
}
// runMain is the main entry point that can be called by tests
func runMain(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
rootCmd := newRootCmd(stdout, stderr)
rootCmd.SetArgs(args)
rootCmd.SetIn(stdin)
rootCmd.SetOut(stdout)
rootCmd.SetErr(stderr)
if err := rootCmd.Execute(); err != nil {
if !hasQuietArg(args) && isStdoutTTY(stderr) {
cli.LogErrorTo(stderr, "%v", err)
}
return 1
}
return 0
}
func hasQuietArg(args []string) bool {
// Silo flags appear before the tool subcommand name; tool args appear
// after. Stop scanning once we hit a tool name so a tool's own -q is not
// misread as silo's --quiet.
toolNames := AvailableTools(supportedTools)
for _, arg := range args {
if slices.Contains(toolNames, arg) {
break
}
if arg == "--quiet" || arg == "-q" {
return true
}
if strings.HasPrefix(arg, "-") && !strings.HasPrefix(arg, "--") && strings.Contains(arg[1:], "q") {
return true
}
}
return false
}
func isStdoutTTY(stdout io.Writer) bool {
if f, ok := stdout.(*os.File); ok {
return isatty.IsTerminal(f.Fd())
}
return false
}
func boolFlag(cmd *cobra.Command, name string) bool {
if cmd == nil {
return false
}
if f := cmd.Flags().Lookup(name); f != nil {
if q, err := cmd.Flags().GetBool(name); err == nil && q {
return true
}
}
if root := cmd.Root(); root != nil && root != cmd {
if f := root.Flags().Lookup(name); f != nil {
if q, err := root.Flags().GetBool(name); err == nil && q {
return true
}
}
}
return false
}
func newRootCmd(stdout, stderr io.Writer) *cobra.Command {
rootCmd := &cobra.Command{
Use: "silo",
Short: "Run AI coding tools in isolated Docker containers",
Long: lipgloss.NewStyle().Foreground(lipgloss.Color("205")).Render(`
███████╗██╗██╗ ██████╗
██╔════╝██║██║ ██╔═══██╗
███████╗██║██║ ██║ ██║
╚════██║██║██║ ██║ ██║
███████║██║███████╗╚██████╔╝
╚══════╝╚═╝╚══════╝ ╚═════╝
`) + `
Run AI tools (Claude Code, Cline, Codex, OpenCode, Paperclip AI, Copilot, Mistral Vibe, Kilo Code, Pi Coding Agent) in isolated
Docker containers with proper security sandboxing.
The container is configured with:
• Your current directory mounted as the working directory
• Git identity from your host machine
• Tool-specific configuration directories
• API keys from configured key files
Configuration is loaded from (in order, merged):
1. ~/.config/silo/config.json (global)
2. .silo.json files from root to current directory (local)
`,
Example: ` # Interactive tool selection
silo
# Run a specific tool
silo claude
silo cline
silo codex
silo opencode
silo paperclipai
silo copilot
silo vibe
silo kilo
silo pi
# Silo flags go before the tool name; tool args go after
silo --backend docker claude --continue
silo claude --help
# --continue and --resume are passed through to the tool
silo --continue
silo --resume <session-id>`,
SilenceUsage: true,
SilenceErrors: true,
// Parse silo's root flags while traversing to a tool subcommand.
// Tool subcommands disable flag parsing so their args pass through
// unchanged; without this, root flags placed before the tool name
// (e.g. `silo --verbose pi`) would never be parsed.
TraverseChildren: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runSilo(cmd, args, stdout, stderr)
},
}
rootCmd.Flags().StringP("backend", "b", "", "Backend to use: docker, container, fly, namespace")
rootCmd.Flags().Bool("force-build", false, "Force rebuild of container image")
rootCmd.Flags().Bool("no-cache", false, "Disable build cache (implies --force-build)")
rootCmd.Flags().BoolP("verbose", "v", false, "Show detailed output instead of progress bar")
rootCmd.Flags().BoolP("quiet", "q", false, "Suppress silo logs and render only tool output")
rootCmd.Flags().Bool("no-tty", false, "Run without allocating a TTY; suitable for scripts and JSON output")
rootCmd.Flags().String("tool-version", "", "Pin a specific tool version (forces synchronous build)")
rootCmd.Flags().String("entrypoint", "", "Run a custom command instead of the tool (e.g. /bin/bash)")
rootCmd.Flags().Bool("continue", false, "Pass --continue through to the tool")
rootCmd.Flags().String("resume", "", "Pass --resume <id> through to the tool")
addMountFlags(rootCmd)
// Define command groups (order here determines display order in --help)
rootCmd.AddGroup(
&cobra.Group{ID: "tools", Title: "Tools:"},
&cobra.Group{ID: "container", Title: "Container Commands:"},
&cobra.Group{ID: "config", Title: "Configuration:"},
)
// Register each tool as a subcommand. Flag parsing is disabled so that
// every arg after the tool name is forwarded to the tool unchanged. Silo
// flags must be passed before the tool name (parsed by rootCmd).
for _, t := range supportedTools {
toolDef := t // capture loop variable
toolCmd := &cobra.Command{
Use: toolDef.Name + " [args...]",
Short: toolDef.Description,
GroupID: "tools",
Args: cobra.ArbitraryArgs,
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runTool(cmd, toolDef, args, stdout, stderr)
},
}
rootCmd.AddCommand(toolCmd)
}
configCmd := &cobra.Command{
Use: "config",
Short: "Configuration management commands",
GroupID: "config",
}
configShowCmd := &cobra.Command{
Use: "show",
Short: "Show the current merged configuration",
RunE: func(cmd *cobra.Command, args []string) error {
return configshow.Show(stdout, toolDefaults())
},
}
configPathsCmd := &cobra.Command{
Use: "paths",
Short: "Show all config file paths being merged",
RunE: func(cmd *cobra.Command, args []string) error {
return runConfigPaths(cmd, args, stdout)
},
}
configEditCmd := &cobra.Command{
Use: "edit",
Short: "Edit a config file in your editor",
RunE: func(cmd *cobra.Command, args []string) error {
return runConfigEdit(cmd, args, stdout, stderr)
},
}
configDefaultCmd := &cobra.Command{
Use: "default",
Short: "Show the default configuration",
RunE: func(cmd *cobra.Command, args []string) error {
return configshow.Default(stdout, toolDefaults())
},
}
configInitCmd := &cobra.Command{
Use: "init",
Short: "Create a sample configuration file",
Long: `Create a sample silo configuration file.
By default, an interactive prompt lets you choose between local and global config.
Use --local or --global to skip the prompt.`,
RunE: func(cmd *cobra.Command, args []string) error {
globalFlag, _ := cmd.Flags().GetBool("global")
localFlag, _ := cmd.Flags().GetBool("local")
return runInit(cmd, args, stderr, globalFlag, localFlag)
},
}
configInitCmd.Flags().BoolP("global", "g", false, fmt.Sprintf("Create global config (%s)", tilde.Path(filepath.Join(config.XDGConfigHome(), "silo", "silo.jsonc"))))
configInitCmd.Flags().BoolP("local", "l", false, "Create local config (silo.jsonc)")
configInitCmd.MarkFlagsMutuallyExclusive("global", "local")
configCmd.AddCommand(configShowCmd)
configCmd.AddCommand(configPathsCmd)
configCmd.AddCommand(configEditCmd)
configCmd.AddCommand(configDefaultCmd)
configCmd.AddCommand(configInitCmd)
rootCmd.AddCommand(configCmd)
logsCmd := &cobra.Command{
Use: "logs",
Short: "Browse build logs from previous runs",
GroupID: "config",
RunE: func(cmd *cobra.Command, args []string) error {
return runLogs(stdout, stderr)
},
}
rootCmd.AddCommand(logsCmd)
lsCmd := &cobra.Command{
Use: "ls",
Short: "List all silo-created containers",
GroupID: "container",
RunE: func(cmd *cobra.Command, args []string) error {
return runList(cmd, args, stdout, stderr)
},
}
lsCmd.Flags().StringP("backend", "b", "", "Backend to use: docker, container, fly, namespace (default: all)")
lsCmd.Flags().BoolP("quiet", "q", false, "Only display container names")
rootCmd.AddCommand(lsCmd)
rmCmd := &cobra.Command{
Use: "rm [container...]",
Short: "Remove silo containers",
GroupID: "container",
Args: cobra.ArbitraryArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runRemove(cmd, args, stderr)
},
}
rmCmd.Flags().StringP("backend", "b", "", "Backend to use: docker, container, fly, namespace (default: all)")
rmCmd.Flags().BoolP("force", "f", false, "Force removal of running containers")
rootCmd.AddCommand(rmCmd)
execCmd := &cobra.Command{
Use: "exec [container] [command] [args...]",
Short: "Run a command in a running silo container",
GroupID: "container",
Long: `Execute an arbitrary command inside a running silo container with an interactive TTY.`,
Example: ` # Run bash in a container
silo exec silo-myproject-1 /bin/bash
# Run a specific command
silo exec silo-myproject-1 ls -la /app`,
Args: cobra.MinimumNArgs(2),
ValidArgsFunction: completeContainerNames,
RunE: func(cmd *cobra.Command, args []string) error {
return runExec(cmd, args[0], args[1:], stderr)
},
}
execCmd.Flags().StringP("backend", "b", "", "Backend to use: docker, container, fly, namespace (default: all)")
rootCmd.AddCommand(execCmd)
shellCmd := &cobra.Command{
Use: "shell [container]",
Short: "Open a shell in a new or running silo container",
GroupID: "container",
Long: `Open an interactive /bin/bash shell in a silo container.
Without arguments, starts a new silo container with no tool installed
(base image only, with post-build and pre-run hooks applied) and opens
a bash shell inside it.
With a container name, opens a /bin/bash shell inside that running
container.`,
Example: ` # Start a new container and open a shell
silo shell
# Open a shell in a running container
silo shell silo-myproject-1`,
Args: cobra.MaximumNArgs(1),
ValidArgsFunction: completeContainerNames,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return runShell(cmd, stdout, stderr)
}
return runExec(cmd, args[0], shell.DefaultShellCommand(), stderr)
},
}
shellCmd.Flags().StringP("backend", "b", "", "Backend to use: docker, container, fly, namespace (default: all)")
shellCmd.Flags().Bool("force-build", false, "Force rebuild of container image (new container mode)")
shellCmd.Flags().Bool("no-cache", false, "Disable build cache (implies --force-build) (new container mode)")
shellCmd.Flags().BoolP("verbose", "v", false, "Show detailed output instead of progress bar (new container mode)")
shellCmd.Flags().BoolP("quiet", "q", false, "Suppress silo logs (new container mode)")
shellCmd.Flags().Bool("no-tty", false, "Run without allocating a TTY (new container mode)")
addMountFlags(shellCmd)
rootCmd.AddCommand(shellCmd)
reconnectCmd := &cobra.Command{
Use: "reconnect [container]",
Short: "Reconnect to a running silo container's tool session",
GroupID: "container",
Long: `Reconnect to a running silo container's tool session. Re-syncs files and reattaches to the running tool (e.g., claude, copilot).`,
Example: ` silo reconnect silo-1`,
Args: cobra.ExactArgs(1),
ValidArgsFunction: completeContainerNames,
RunE: func(cmd *cobra.Command, args []string) error {
return runReconnect(cmd, args[0], stderr)
},
}
reconnectCmd.Flags().StringP("backend", "b", "", "Backend to use: docker, container, fly, namespace (default: all)")
rootCmd.AddCommand(reconnectCmd)
// Hidden __build subcommand — used by background build launcher.
buildCmd := &cobra.Command{
Use: "__build",
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
dir, _ := cmd.Flags().GetString("dir")
return runBackgroundBuild(dir, stderr)
},
}
buildCmd.Flags().String("dir", "", "Build state directory")
rootCmd.AddCommand(buildCmd)
upgradeCmd := &cobra.Command{
Use: "upgrade",
Short: "Upgrade silo to the latest version",
RunE: func(cmd *cobra.Command, args []string) error {
return runUpgrade(stderr)
},
}
rootCmd.AddCommand(upgradeCmd)
rootCmd.Version = version
rootCmd.SetVersionTemplate("silo version {{.Version}}\n")
return rootCmd
}
func runSilo(cmd *cobra.Command, args []string, stdout, stderr io.Writer) error {
// Load configuration
cfg := config.LoadAll(toolDefaults())
noTTY := boolFlag(cmd, "no-tty") || !isStdoutTTY(stdout)
// Tool args come only from the pass-through flags --continue and --resume
// when invoking silo without an explicit tool subcommand.
toolArgs := passThroughToolArgs(cmd)
// Get cwd for repo matching
cwd, _ := os.Getwd()
// Determine tool (priority: repo config > global config > interactive)
var tool string
var err error
// Check repo-specific tool setting (applied in specificity order)
for _, m := range run.GetMatchingRepos(cfg, cwd) {
if m.Config.Tool != "" {
tool = m.Config.Tool
}
}
// Fall back to global config tool
if tool == "" && cfg.Tool != "" {
tool = cfg.Tool
}
// Interactive selection as last resort
if tool == "" {
if noTTY {
return fmt.Errorf("--no-tty requires an explicit tool or configured default tool")
}
tool, err = selectTool()
if err != nil {
return err
}
}
// Validate tool
validTools := AvailableTools(supportedTools)
if !slices.Contains(validTools, tool) {
return fmt.Errorf("invalid tool: %s (valid tools: %s)", tool, strings.Join(validTools, ", "))
}
// Find tool definition
toolDef := findTool(tool)
if toolDef == nil {
return fmt.Errorf("tool definition not found: %s", tool)
}
// Override backend from flag
if b, _ := cmd.Flags().GetString("backend"); b != "" {
cfg.Backend = b
}
// Get force-build flag
forceBuild, _ := cmd.Flags().GetBool("force-build")
// Get no-cache flag (implies force-build)
noCache, _ := cmd.Flags().GetBool("no-cache")
if noCache {
forceBuild = true
}
// Get verbose flag
verbose, _ := cmd.Flags().GetBool("verbose")
// Get quiet flag
quiet := boolFlag(cmd, "quiet")
// Get no-tty flag
noTTY = boolFlag(cmd, "no-tty")
// Auto-detect non-interactive environment
if !noTTY && !isStdoutTTY(stdout) {
noTTY = true
quiet = true
}
// Get tool-version flag
toolVersion, _ := cmd.Flags().GetString("tool-version")
// Get additional mount flags
extraMountsRW, extraMountsRO, err := extraMountsFromFlags(cmd)
if err != nil {
return err
}
// Run the tool
return run.Tool(run.Options{
ToolDef: *toolDef,
ToolArgs: toolArgs,
Config: cfg,
Dockerfile: Dockerfile(*toolDef),
ForceBuild: forceBuild,
NoCache: noCache,
Verbose: verbose,
Quiet: quiet,
NoTTY: noTTY,
ToolVersion: toolVersion,
ExtraMountsRW: extraMountsRW,
ExtraMountsRO: extraMountsRO,
Stdin: cmd.InOrStdin(),
Stdout: stdout,
Stderr: stderr,
})
}
func runTool(cmd *cobra.Command, toolDef tools.Tool, args []string, stdout, stderr io.Writer) error {
// Load configuration
cfg := config.LoadAll(toolDefaults())
// Silo flags live on the root command; the tool subcommand has flag
// parsing disabled so every arg here is a tool arg. Pass-through flags
// (--continue, --resume) are prepended.
root := cmd.Root()
toolArgs := append(passThroughToolArgs(root), args...)
// Override backend from flag
if b, _ := root.Flags().GetString("backend"); b != "" {
cfg.Backend = b
}
// Get force-build flag
forceBuild, _ := root.Flags().GetBool("force-build")
// Get no-cache flag (implies force-build)
noCache, _ := root.Flags().GetBool("no-cache")
if noCache {
forceBuild = true
}
// Get verbose flag
verbose, _ := root.Flags().GetBool("verbose")
// Get quiet flag
quiet, _ := root.Flags().GetBool("quiet")
// Get no-tty flag
noTTY, _ := root.Flags().GetBool("no-tty")
// Auto-detect non-interactive environment
if !noTTY && !isStdoutTTY(stdout) {
noTTY = true
quiet = true
}
// Get entrypoint flag
entrypoint, _ := root.Flags().GetString("entrypoint")
// Get tool-version flag
toolVersion, _ := root.Flags().GetString("tool-version")
// Get additional mount flags
extraMountsRW, extraMountsRO, err := extraMountsFromFlags(root)
if err != nil {
return err
}
// Run the tool
return run.Tool(run.Options{
ToolDef: toolDef,
ToolArgs: toolArgs,
Config: cfg,
Dockerfile: Dockerfile(toolDef),
ForceBuild: forceBuild,
NoCache: noCache,
Verbose: verbose,
Quiet: quiet,
NoTTY: noTTY,
Entrypoint: entrypoint,
ToolVersion: toolVersion,
ExtraMountsRW: extraMountsRW,
ExtraMountsRO: extraMountsRO,
Stdin: cmd.InOrStdin(),
Stdout: stdout,
Stderr: stderr,
})
}
// passThroughToolArgs returns args derived from silo's pass-through flags
// (--continue, --resume) that should be forwarded to the underlying tool.
func passThroughToolArgs(cmd *cobra.Command) []string {
root := cmd.Root()
var args []string
if c, _ := root.Flags().GetBool("continue"); c {
args = append(args, "--continue")
}
if r, _ := root.Flags().GetString("resume"); r != "" {
args = append(args, "--resume", r)
}
return args
}
func addMountFlags(cmd *cobra.Command) {
cmd.Flags().StringArrayP("mount", "m", nil, "Additional read-write path to mount into the container (repeatable)")
cmd.Flags().StringArray("mountro", nil, "Additional read-only path to mount into the container (repeatable)")
}
func extraMountsFromFlags(cmd *cobra.Command) (mountsRW, mountsRO []string, err error) {
mountsRW, err = cmd.Flags().GetStringArray("mount")
if err != nil {
return nil, nil, err
}
mountsRO, err = cmd.Flags().GetStringArray("mountro")
if err != nil {
return nil, nil, err
}
return mountsRW, mountsRO, nil
}
func selectTool() (string, error) {
names := AvailableTools(supportedTools)
var options []huh.Option[string]
for _, t := range names {
options = append(options, huh.NewOption(ToolDescription(supportedTools, t), t))
}
var selected string
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[string]().
Title("Select AI Tool").
Description("Choose which AI coding assistant to run").
Options(options...).
Value(&selected),
),
)
if err := form.Run(); err != nil {
return "", fmt.Errorf("selection cancelled")
}
return selected, nil
}
func runConfigPaths(_ *cobra.Command, _ []string, stdout io.Writer) error {
paths := config.GetConfigPaths()
for _, p := range paths {
if p.Exists {
fmt.Fprintln(stdout, p.Path)
}
}
return nil
}
func runConfigEdit(_ *cobra.Command, _ []string, _, stderr io.Writer) error {
paths := config.GetConfigPaths()
// Build options for the selector:
// - Always include global config (first path)
// - Only include local configs that exist
var options []huh.Option[string]
for i, p := range paths {
isGlobal := i == 0
if !isGlobal && !p.Exists {
continue
}
label := p.Path
if !p.Exists {
label += " (new)"
}
options = append(options, huh.NewOption(label, p.Path))
}
var selectedPath string
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[string]().
Title("Select Config to Edit").
Description("Configs are merged in order shown (later overrides earlier)").
Options(options...).
Value(&selectedPath),
),
)
if err := form.Run(); err != nil {
return fmt.Errorf("selection cancelled")
}
// Get editor from environment
editor := os.Getenv("EDITOR")
if editor == "" {
editor = os.Getenv("VISUAL")
}
if editor == "" {
editor = "vi"
}
// Ensure parent directory exists for new files
dir := filepath.Dir(selectedPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
// If file doesn't exist, pre-fill with template
if _, err := os.Stat(selectedPath); os.IsNotExist(err) {
if err := os.WriteFile(selectedPath, []byte(sampleConfig), 0644); err != nil {
return fmt.Errorf("failed to create config: %w", err)
}
}
// Open editor
cmd := exec.Command(editor, selectedPath)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("editor failed: %w", err)
}
return nil
}
func runInit(_ *cobra.Command, _ []string, stderr io.Writer, globalFlag, localFlag bool) error {
var configType string
// Determine config type from flags or interactive prompt
if globalFlag {
configType = "global"
} else if localFlag {
configType = "local"
} else {
// Interactive selection
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[string]().
Title("Create Configuration").
Description("Choose which configuration file to create").
Options(
huh.NewOption("Local (silo.jsonc in current directory)", "local"),
huh.NewOption(fmt.Sprintf("Global (%s)", tilde.Path(filepath.Join(config.XDGConfigHome(), "silo", "silo.jsonc"))), "global"),
).
Value(&configType),
),
)
if err := form.Run(); err != nil {
return fmt.Errorf("selection cancelled")
}
}
var configPath string
if configType == "global" {
configDir := filepath.Join(config.XDGConfigHome(), "silo")
if err := os.MkdirAll(configDir, 0755); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
configPath = filepath.Join(configDir, "silo.jsonc")
} else {
configPath = "silo.jsonc"
}
if _, err := os.Stat(configPath); err == nil {
return fmt.Errorf("config file already exists: %s", configPath)
}
if err := os.WriteFile(configPath, []byte(sampleConfig), 0644); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
cli.LogSuccessTo(stderr, "Created %s", configPath)
return nil
}
func runLogs(stdout, stderr io.Writer) error {
logDir := filepath.Join(config.XDGStateHomeDir(), "silo", "logs")
entries, err := os.ReadDir(logDir)
if err != nil {
return fmt.Errorf("no logs found (looked in %s)", tilde.Path(logDir))
}
// Filter to .log files and collect in reverse order (most recent first)
var logs []os.DirEntry
for i := len(entries) - 1; i >= 0; i-- {
if filepath.Ext(entries[i].Name()) == ".log" {
logs = append(logs, entries[i])
}
}
if len(logs) == 0 {
return fmt.Errorf("no logs found in %s", tilde.Path(logDir))
}
// Build options for the selector
var options []huh.Option[string]
for _, entry := range logs {
name := entry.Name()
path := filepath.Join(logDir, name)
info, _ := entry.Info()
label := name
if info != nil {
label = fmt.Sprintf("%s (%s)", name, humanize.Bytes(uint64(info.Size())))
}
options = append(options, huh.NewOption(label, path))
}
var selected string
for {
km := huh.NewDefaultKeyMap()
km.Quit = key.NewBinding(key.WithKeys("q", "ctrl+c"))
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[string]().
Title("Select Log").
Description(tilde.Path(logDir)).
Options(options...).
Value(&selected),
),
).WithKeyMap(km)
if err := form.Run(); err != nil {
return nil
}
// Open in less
cmd := exec.Command("less", selected)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Run()
}
}
func runRemove(cmd *cobra.Command, args []string, stderr io.Writer) error {
ctx := context.Background()
backendFlag, _ := cmd.Flags().GetString("backend")
force, _ := cmd.Flags().GetBool("force")
cfg := config.LoadAll(toolDefaults())
backends := removeBackends(backendFlag)
targetsByBackend, err := resolveRemoveTargets(ctx, cfg, backends, args, stderr)
if err != nil {
return err
}
for _, backendType := range backends {
toRemove := targetsByBackend[backendType]
if len(toRemove) == 0 {
continue
}
backendClient, err := createBackendByType(backendType, cfg)
if err != nil {
cli.LogWarningTo(stderr, "%s not available: %v", backendType, err)
continue
}
// Unless -f is passed, refuse to remove running containers.
if !force {
containers, listErr := backendClient.List(ctx)
if listErr == nil {
toRemove = filterRunningContainers(toRemove, containers, stderr)
}
}
if len(toRemove) == 0 {
backendClient.Close()
continue
}
removed, err := backendClient.Remove(ctx, toRemove)
backendClient.Close()
if err != nil {
cli.LogWarningTo(stderr, "failed to remove containers (%s): %v", backendType, err)
continue
}
for _, name := range removed {
cli.LogTo(stderr, "Removed %s (%s)", name, backendType)
}
}
return nil
}
func runExec(cmd *cobra.Command, name string, command []string, stderr io.Writer) error {
ctx := context.Background()
backendFlag, _ := cmd.Flags().GetString("backend")
cfg := config.LoadAll(toolDefaults())
var backends []string
if backendFlag != "" {
backends = []string{backendFlag}
} else {
backends = []string{"docker", "container", "fly", "namespace"}
}
for _, backendType := range backends {
backendClient, err := createBackendByType(backendType, cfg)
if err != nil {
continue
}
err = backendClient.Exec(ctx, name, command)
backendClient.Close()
if err == nil {
return nil
}
// If the error is "not found", try the next backend.
// If the error is something else (not running, exec failure), return it.
if !strings.Contains(err.Error(), "not found") {
return err
}
}
return fmt.Errorf("container %s not found", name)
}
// runShell starts a new silo container using the shell "tool" (base image
// only, no tool installed) and opens an interactive bash shell inside it.
func runShell(cmd *cobra.Command, stdout, stderr io.Writer) error {
cfg := config.LoadAll(toolDefaults())
if b, _ := cmd.Flags().GetString("backend"); b != "" {
cfg.Backend = b
}
forceBuild, _ := cmd.Flags().GetBool("force-build")
noCache, _ := cmd.Flags().GetBool("no-cache")
if noCache {
forceBuild = true
}
verbose, _ := cmd.Flags().GetBool("verbose")
quiet, _ := cmd.Flags().GetBool("quiet")
noTTY, _ := cmd.Flags().GetBool("no-tty")
if !noTTY && !isStdoutTTY(stdout) {
noTTY = true
quiet = true
}
extraMountsRW, extraMountsRO, err := extraMountsFromFlags(cmd)
if err != nil {
return err
}
return run.Tool(run.Options{
ToolDef: shell.Tool,
Config: cfg,
Dockerfile: Dockerfile(shell.Tool),
ForceBuild: forceBuild,
NoCache: noCache,
Verbose: verbose,
Quiet: quiet,
NoTTY: noTTY,
ExtraMountsRW: extraMountsRW,
ExtraMountsRO: extraMountsRO,
Stdin: cmd.InOrStdin(),
Stdout: stdout,
Stderr: stderr,
})
}
func runReconnect(cmd *cobra.Command, name string, stderr io.Writer) error {
ctx := context.Background()
backendFlag, _ := cmd.Flags().GetString("backend")
cfg := config.LoadAll(toolDefaults())
cwd, _ := os.Getwd()