package main import ( "context" "encoding/json" "errors" "fmt" "io" "log/slog" "net/url" "os" "os/signal" "syscall" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/mac/fprobe" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/render" runnersetup "amadan.net/oficina/equipo/internal/runner/setup" "amadan.net/oficina/equipo/internal/runner/thin" "amadan.net/oficina/equipo/internal/runner/webread" "amadan.net/oficina/equipo/internal/wire" "amadan.net/rastrillo/rastrillo" ) func run(ctx context.Context, args []string, input io.Reader, output, errorOutput io.Writer, getenv func(string) string) int { fail := func(err error) int { code, variable := runner.Diagnostic(err) _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, code, variable) return 1 } // The Research fetcher, started by the runner under bubblewrap: it // needs no configuration and reads its plan on stdin. if len(args) > 0 && args[0] == "webread" { return webread.Main(args[1:], input, errorOutput) } // The page renderer's sandbox, its first process: started by the // runner under bubblewrap with no environment and no configuration. if len(args) > 0 && args[0] == render.Subcommand { return render.SandboxMain(args[1:], errorOutput) } // And the step before it, which closes what the runner's process // should not pass on and executes bubblewrap. if len(args) > 0 && args[0] == render.ExecSubcommand { return render.ExecMain(args[1:]) } // A Mac's MCP tool endpoint, started by the CLI: before anything // reads the environment or a configuration. if len(args) > 0 && args[0] == provider.DarwinToolProxyCommand { if code, ok := toolProxy(ctx, args[1:], input, output); ok { return code } } if len(args) > 0 && args[0] == "account" { return accountLogin(ctx, args[1:], input, output, errorOutput, getenv) } if len(args) > 0 && args[0] == "install" { if goos() == "darwin" { return installMac(ctx, args[1:], realMacInstallHost(), output, errorOutput) } return installRunner(ctx, args[1:], input, output, errorOutput, getenv) } // A Mac's launchd agent passes its environment as a file (launchd has // no EnvironmentFile): run --env-file , probe --env-file . args, envFile, ok := cutEnvFile(args) if !ok { return fail(nil) } if envFile != "" { values, err := runnersetup.ReadEnvFile(envFile) if err != nil { return fail(err) } base := getenv getenv = func(k string) string { if v, ok := values[k]; ok { return v } return base(k) } } if len(args) == 2 && args[0] == "login" { cfg, err := runner.LoadConfig(getenv) if err != nil { return fail(err) } if err = thin.Login(ctx, cfg, args[1], thin.LoginOptions{Input: input, Output: output}); err != nil { return fail(err) } return 0 } if len(args) > 0 && args[0] == "verify-install-manifest" { return installManifest(args[1:], output) } if len(args) > 0 && args[0] == "install-pi" { return installPi(ctx, args[1:], output, errorOutput) } // The page renderer beside this runner (Linux amd64), from the // release's renderer.tar.gz: the production scripts run it. if len(args) > 0 && args[0] == "install-renderer" { return installRendererCommand(args[1:], output, errorOutput) } // The page renderer linked into this build, for the release tooling // (scripts/publish-renderer.sh): a -trimpath build keeps no -ldflags // in its build information, so only the runner itself can say. if len(args) > 0 && args[0] == "renderer-asset" { return rendererAssetCommand(args[1:], output, errorOutput) } if len(args) > 0 && args[0] == "install-opencode" { return installOpenCode(ctx, args[1:], output, errorOutput) } if len(args) != 1 { return fail(nil) } if args[0] == "version" { if json.NewEncoder(output).Encode(struct { Version string `json:"version"` Manifest release.Manifest `json:"manifest"` }{rastrillo.BuildVersion, release.BuildManifest()}) != nil { return fail(nil) } return 0 } if args[0] == "tool" { if runner.ServeTools(ctx, input, output, getenv("EQUIPO_TOOL_SOCKET"), getenv("EQUIPO_TOOL_CAPABILITY_FILE")) != nil { _, _ = io.WriteString(errorOutput, equipo.CopyToolRejected+"\n") return 1 } return 0 } if args[0] != "run" && args[0] != "enrol" && args[0] != "preflight" && args[0] != "reset" && args[0] != "probe" && args[0] != "verify-installed" { return fail(nil) } cfg, err := runner.LoadConfig(getenv) if err != nil { return fail(err) } cfg.Copy = equipo.RunnerToolCopy() cfg.Report = func(code string) { if code == "runner.waiting_accounts" { _, _ = fmt.Fprintln(errorOutput, equipo.RunnerText(code)) return } _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, code, "-") } switch args[0] { case "enrol": err = enrolAlone(ctx, cfg, output, runner.Enrol) if errors.Is(err, errInstallBusy) { _, _ = fmt.Fprintln(errorOutput, equipo.RunnerSetupCopy("runner.install.busy")) return 1 } case "reset": err = runner.Reset(ctx, cfg) case "run": opts := thin.OptionsFromEnv(getenv) opts.Version, opts.Logger = rastrillo.BuildVersion, slog.New(slog.NewTextHandler(errorOutput, logOptions(getenv))) logStart(opts.Logger, cfg, opts.Version, envFile) err = thin.Run(ctx, cfg, opts) if errors.Is(err, thin.ErrSuperseded) { _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, "runner.superseded", "-") return supersededExit(goos()) } if errors.Is(err, thin.ErrUpdated) { return mac.ExitUpdated } case "probe": // The Mac's self-probes, on demand; the running worker picks the // report up and sends it. Paul never needs this. if goos() != "darwin" { _, _ = fmt.Fprintln(errorOutput, equipo.RunnerSetupCopy("runner.mac.platform")) return 1 } opts := thin.OptionsFromEnv(getenv) opts.Version = rastrillo.BuildVersion var report mac.Report report, err = thin.RunProbes(ctx, cfg, opts) if err == nil { err = json.NewEncoder(output).Encode(report.Probes) } case "verify-installed": err = verifyInstalled(release.BuildManifest(), cfg) // What differs, for the operator whose script stopped here (a // renderer's diagnostic names the entry). if err != nil { _, _ = fmt.Fprintln(errorOutput, "verify-installed:", err) } case "preflight": var reports any reports, err = runner.Preflight(ctx, cfg) if err == nil { err = json.NewEncoder(output).Encode(reports) } } if err != nil && !errors.Is(err, context.Canceled) { return fail(err) } return 0 } func main() { if len(os.Args) == 2 && os.Args[1] == "__install_probe" { os.Exit(runnersetup.InstallProbeMain(os.Stdin, os.Stdout)) } if len(os.Args) > 1 && os.Args[1] == "__namespace" { os.Exit(namespace(os.Args[2:])) } if len(os.Args) > 1 && os.Args[1] == "__fprobe" { // The Mac probes' direct kernel reader (mac/fprobe), run inside // Claude's sandbox by a probe script and by P2's fixture. os.Exit(fprobe.HelperMain(os.Args[2:], os.Stdout)) } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) code := run(ctx, os.Args[1:], os.Stdin, os.Stdout, os.Stderr, os.Getenv) stop() os.Exit(code) } // logStart is the runner's first line: what starts, where it connects // (the origin's host only) and from which env file. No credential. // logOptions is the runner's log level: info, or debug with // EQUIPO_RUNNER_LOG_LEVEL=debug (an Assistant turn's phases, for one). func logOptions(getenv func(string) string) *slog.HandlerOptions { if getenv("EQUIPO_RUNNER_LOG_LEVEL") == "debug" { return &slog.HandlerOptions{Level: slog.LevelDebug} } return &slog.HandlerOptions{Level: slog.LevelInfo} } func logStart(log *slog.Logger, cfg runner.Config, version, envFile string) { role := wire.RolePrimary if cfg.WorkerOnly || runner.ReadRole(cfg.StateDir) == wire.RoleWorker { role = wire.RoleWorker } host := "" if u, err := url.Parse(cfg.Origin); err == nil { host = u.Host } attrs := []any{"version", version, "os", goos(), "arch", goarch(), "role", role, "origin", host, "label", cfg.MachineLabel} if envFile != "" { attrs = append(attrs, "env_file", envFile) } log.Info("runner starting", attrs...) } // supersededExit: systemd must not restart a runner that lost its lease // (RestartPreventExitStatus=3); launchd restarts any non-zero exit // (KeepAlive SuccessfulExit false), so on a Mac it is 0. func supersededExit(goos string) int { if goos == "darwin" { return 0 } return thin.ExitSuperseded } // cutEnvFile takes "--env-file " out of the arguments of run and // probe. ok is false when it is malformed or given to another verb. func cutEnvFile(args []string) (rest []string, file string, ok bool) { for i := 0; i < len(args); i++ { if args[i] != "--env-file" { rest = append(rest, args[i]) continue } if file != "" || i+1 >= len(args) || len(rest) != 1 || (rest[0] != "run" && rest[0] != "probe") { return nil, "", false } file = args[i+1] i++ } return rest, file, true }