Files
devvm/internal/cli/root.go
T
w3cjandClaude Opus 5.5 aeea3135b2 feat(proxy): the proxy's broker and its child
A VM's proxy runs as two processes, as design.md's "The proxy's broker"
says: devvm _proxy, the broker, which keeps what only the host should
do, and devvm _proxy-child, which reads the VM's network and can be
confined by the follow-ups.

- wire.go: the protocol over one socketpair (close-on-exec from the
  start: SOCK_CLOEXEC on Linux, ForkLock elsewhere), length-prefixed JSON
  frames of at most 2 MiB, unknown fields refused, bytes as base64, one
  descriptor on a frame's first bytes (SCM_RIGHTS, MSG_CTRUNC breaks the
  rules), wire types for every secret (redact.Secret at once).
- broker.go: newBroker, the start (handshake: version 1 and each side's
  executable's SHA-256, within 4 s), the answers (value through lookups,
  kept 30 s or 5 min, a failure 5 s, dropped when the bindings change;
  file by number; link connected by the broker and passed as a
  descriptor; token exchanged by the broker), each by something in its
  own config, with caps 1/8/4/256; live: the lifeline closes the socket
  and kills the child 6 s later, SIGTERM stops it within a second, a
  child that ends ends the broker, a rule broken stops the child.
- child.go: the start (startOf), the child's server (newChildServer),
  the broker as hostSide over the socket (brokerClient), runChildOn;
  ready only after it reads the host's addresses (kept: the last good
  read), roots and time zone loaded first.
- process.go: Main(ctx, ...) and ChildMain; the child spawned with
  /proc/self/exe on Linux, PR_SET_PDEATHSIG from a locked thread
  (daemon.Cmd.DieWithThread), descriptors 3 and 4, and TZ, SSL_CERT_*
  and GODEBUG with updatemaxprocs=0 alone; run/proxy-child.pid and
  run/proxy.confined ("none" until the follow-ups); KeepLogs in the
  broker. ChildMain refuses to start unless descriptors 3 and 4 are a
  unix socket and an IP one (checkInherited): run by hand, without
  them, those numbers can be the Go runtime's own, which closing
  crashed it (signal_recv: inconsistent state).
- capture.go: a captured token request goes to the broker
  (captureToken, exchanger), so a login's real tokens never enter the
  child; an error reply passes up to 1 MiB, longer gets 502.
- watched.go: the child stats each changing file and asks the broker
  for it once it changed, keeping the stamp of what the broker read.
- rotate.go: proxy.log rotated by both through its descriptor, under a
  lock of a description of its own; OpenLog opens a log never through a
  link, one link, yours, replacing what a child left in its place.
- nixcache.go: the trim and its count through a safefile.Root, nar/
  only as a folder, links deleted as themselves; reads never through a
  link; the lock tried for 5 s (ErrNixLocked, nix_cache_locked).
- daemon: Cmd.Err, Files, Env, DieWithThread; Handle.Kill, Exit;
  WritePID.
- netpolicy: Proxy.Stop also stops a child that outlived its broker
  (run/proxy-child.pid, _proxy-child -for); proxy.log opened with
  OpenLog; a refused launch keeps a running VM only while both run.
  devvm network log and lock read the event log through safefile.
- vm, vmssh, vmlog: links.log and ports.log opened with OpenLog, read
  through safefile, trimmed only as a regular file with one link.
- backend: the build proxy's logs in a logs/ folder of their own.
- cli: _proxy-child; _proxy waits for its child on a signal
  (StopsItsOwn); the child reads none of devvm's folders (no
  makePrivate); ui.Files.
- Tests: FuzzBrokerFrames, the frames' rules, the handshake and the
  pair's end in synctest bubbles, the caps, the broker naming its own
  alone, the client over a real socketpair with a passed descriptor,
  ChildMain, TestInheritedSocket and proxy.txtar's child run by hand,
  the frozen 0.1.0 configs starting a broker and child,
  two writers rotating once, planted links, FIFOs and hard links; the
  testscript runner stops _proxy-child too; e2e: broker and child, their
  arguments, descriptors and environment, stop, SIGKILL either, planted
  files in the logs folder and the Nix cache, build proxies gone.
- Review fixes: the lifeline closes the socket and starts the kill's
  timer before logging; every log lock (proxy.log's, the event log's
  rotation) is tried without blocking for 200 ms (flockWithin, which the
  Nix lock shares), then written without or the rotation skipped; a
  copied log's rotation streams at most twice its limit from a line's
  start (copyFrom, copyAtomic); a reply too long to send goes as
  too_long; kept token headers capped at 1 KiB; the child gives up on a
  request whose context ended, dropping its late reply and holding its
  slot until then; a write deadline on the start frame; errors reach the
  child as codes (not_found, refused, busy, too_long, failed), their
  text in the broker's log; FuzzFrameStreams, and FuzzBrokerFrames
  writes from a goroutine; nix_cache_locked links to How it works.
- Docs: processes, network, overview, design (with threat rows for the
  logs' locks and a log made huge), troubleshooting, the proxy's
  README, structure, testing; CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 22:04:32 -07:00

218 lines
8.0 KiB
Go

package cli
import (
"context"
"errors"
"slices"
"strings"
"github.com/spf13/cobra"
"github.com/devvmhq/devvm/internal/backend"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/proxy"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/ui"
)
// NewRoot returns the devvm command with every subcommand registered, each
// printing and asking through u, on the run's services (app). devvm
// itself is up: a shell in this folder's VM.
func NewRoot(u *ui.UI) *cobra.Command {
a := newApp(u)
uf := new(upFlags)
fl := new(ui.Flags)
root := &cobra.Command{
Use: "devvm",
Annotations: about{docs: "getting-started/commands", noJSON: "it opens a shell"}.annotations(),
Short: "Open a shell in this folder's VM, creating it first",
Long: "Open a shell in this folder's VM, at the same path, and create the VM first when the folder has none. " +
"devvm shows what a new VM gets, and in a terminal you can customize its toolchains, coding agents, layers, tier, ports and size, which --tools, --agents, --layers, --network, --ports, --cpus, --memory and --disk choose without asking. " +
"The VM mounts only this folder read-write, and with --clone it gets its own clone of the repo instead.",
Example: examples(
"devvm", "open this folder's VM, choosing what a new one gets",
"devvm --agents claude", "create the VM with Claude Code and the toolchains the folder needs",
"devvm --tools node --agents none --layers docker", "create the VM with node and the docker layer alone",
"devvm --clone", "create the VM with its own clone of this repo",
"devvm ls", "list every VM",
),
SilenceUsage: true,
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
f := *fl
f.PipedAnswers, f.PickOnPipe = a.testOverrides().PipedAnswers, a.testOverrides().PickOnPipe
u.SetFlags(f)
if a.testOverrides().LockOrder {
state.CheckLockOrder()
}
if wantsJSON(cmd) {
u.DataOnly() // stdout is the JSON's alone
}
// A proxy's child reads none of devvm's folders: it gets what it needs from its broker.
if cmd.Name() != proxy.ChildCommand {
makePrivate(a)
}
if !skipsLayout(cmd) {
if err := checkLayout(cmd.Context(), a); err != nil {
return ranError{err}
}
}
if !skipsRetention(cmd) {
autoRetain(cmd.Context(), a)
}
return nil
},
Args: noArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return up(cmd.Context(), a, uf)
},
SuggestionsMinimumDistance: msg.SuggestDistance,
}
root.SetOut(u.Stdout())
root.PersistentFlags().BoolVarP(&fl.Verbose, "verbose", "v", false, "show the output of the commands devvm runs instead of a status line")
root.PersistentFlags().BoolVar(&fl.NoInput, "no-input", false, "never ask, and fail where devvm would ask, naming the flag that answers it")
addUpFlags(root, a, uf)
addVersion(root)
root.AddCommand(newBuildCmd(a), newRebuildCmd(a), newImagesCmd(a), newGCCmd(a), newSpaceCmd(a), newLayerCmd(a), newSetupCmd(a), newAgentCmd(a), newMsgCmd(u),
newRestartCmd(a), newStopCmd(a), newUpdateCmd(a), newToolsCmd(a), newAdoptCmd(a), newHistoryCmd(a), newRmCmd(a), newLsCmd(a), newNetworkCmd(a), newHostCmd(a), newCodeCmd(a), newCursorCmd(a), newDesktopCmd(a), newSSHAgentCmd(a), newGitProtectCmd(a), newCloneCmd(a), newPortsCmd(a), newSizeCmd(a), newMountCacheCmd(a), newDoctorCmd(a), newLimactlCmd(a), newQEMUCmd(u), newProxyCmd(a), newProxyChildCmd(a), newForwarderCmd(a), newRefreshToolsCmd(a), newSecretCmd(a),
newLinkCmd(a), newGroupCmd(a), newLinksCmd(a), newRetentionCmd(a), newVersionCmd(u), newCompletionCmd(u), newUpgradeCmd(a), newPasteCmd(a))
addCompletions(root, a)
checkCommands(root)
addHelp(root, u.Logo)
addGroups(root)
addDocs(root)
return root
}
// makePrivate makes devvm's data and settings folders the user's alone on
// every run, whatever mode they had. Without a HOME there are no folders,
// and the command says so itself.
func makePrivate(a *app) {
d, err := a.dirs()
if err != nil {
return
}
if err := state.MakePrivate(d); err != nil {
a.u.Warn(msg.FoldersNotPrivate(d.Config, d.Data).Because(err))
}
}
// checkLayout checks the layout version of devvm's folders before the
// command runs (state.CheckLayout), and fails when a newer devvm changed
// them or a version file can't be read. Without a HOME there are no
// folders, and the command says so itself.
func checkLayout(ctx context.Context, a *app) error {
if d, err := a.dirs(); err == nil {
return failed(state.CheckLayout(ctx, d), msg.LayoutUnchecked)
}
return nil
}
// failure is a command's failure and what failed, the message for an
// error that isn't one: what failed returns, which execute shows.
type failure struct {
err error
what func(reason string) msg.M
}
func (f failure) Error() string { return f.err.Error() }
func (f failure) Unwrap() error { return f.err }
// failed is err as a command's failure, nil for nil, which its RunE
// returns: execute shows it as showFailure says, with what failed for an
// error that isn't a message.
func failed(err error, what func(reason string) msg.M) error {
if err == nil {
return nil
}
return failure{err, what}
}
// showFailure prints what a command's RunE returned: a question's
// refusal (msg.Refusal: the question, then what answers it), the run
// log's end and its message when the details are there (a
// backend.LoggedError), the message err is or carries, or else what
// failed (output_failed without failed's), err's text its reason. Once
// the run is interrupted it prints nothing, as the failure is the
// interrupt's.
func showFailure(u *ui.UI, err error) {
if r, ok := errors.AsType[*msg.Refusal](err); ok {
u.Refused(r)
return
}
if e, ok := errors.AsType[*backend.LoggedError](err); ok {
u.ErrorLogged(e.Msg)
return
}
if m, ok := errors.AsType[msg.M](err); ok {
u.Error(m)
return
}
what := msg.OutputFailed
if f, ok := errors.AsType[failure](err); ok {
what, err = f.what, f.err
}
reason := err.Error()
if c, ok := errors.AsType[*state.CorruptError](err); ok && c.Error() == reason {
// A file devvm can't read, unwrapped: its message as the UI
// shows messages, names in names mode.
reason = c.Shown(u.Text)
}
u.Error(what(reason).Because(err))
}
// skipsLayout reports whether cmd runs without checking the layout
// version: what reads none of devvm's folders (help, completion, the
// version, the messages, devvm upgrade, which a layout a newer devvm
// wrote is a reason to run), and devvm's own hidden commands, which a
// devvm that checked it runs.
func skipsLayout(cmd *cobra.Command) bool {
path := strings.Fields(cmd.CommandPath())
if len(path) < 2 {
return false
}
return strings.HasPrefix(path[1], "_") || slices.Contains([]string{"completion", "version", "upgrade", "help", "__complete", "__completeNoDesc"}, path[1])
}
// Execute runs devvm with args on u and returns its exit code: 0, 1 for a
// failure, usageCode for a usage error (a bad argument or flag, an
// unknown command), which is followed by usage_help, naming the
// command's own --help.
func Execute(ctx context.Context, u *ui.UI, args []string) int {
return execute(ctx, u, NewRoot(u), args) //nolint:contextcheck // the commands' functions run later, with cmd.Context(), which execute sets from ctx
}
// execute runs root with args, as Execute does.
func execute(ctx context.Context, u *ui.UI, root *cobra.Command, args []string) (code int) {
defer func() {
if p := recover(); p != nil {
w, ok := p.(wordPanic)
if !ok {
panic(p)
}
printUsage(u, root, w.err)
code = usageCode
}
}()
root.SetArgs(args)
cmd, err := root.ExecuteContextC(ctx)
if err == nil {
return 0
}
if cmd == nil {
cmd = root
}
if e, ok := errors.AsType[ranError](err); ok {
showFailure(u, e.err)
return 1
}
// Anything else is the parser's, before the command ran. A word that
// isn't a command is devvm's, whichever command (help) refused it.
e := usage(err)
if strings.HasPrefix(e.m.ID(), "no_command") {
cmd = root
}
printUsage(u, cmd, e)
return usageCode
}