oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "log/slog"
10 "net/url"
11 "os"
12 "os/signal"
13 "syscall"
14
15 "amadan.net/oficina/equipo/internal/equipo"
16 "amadan.net/oficina/equipo/internal/release"
17 "amadan.net/oficina/equipo/internal/runner"
18 "amadan.net/oficina/equipo/internal/runner/mac"
19 "amadan.net/oficina/equipo/internal/runner/mac/fprobe"
20 "amadan.net/oficina/equipo/internal/runner/provider"
21 "amadan.net/oficina/equipo/internal/runner/render"
22 runnersetup "amadan.net/oficina/equipo/internal/runner/setup"
23 "amadan.net/oficina/equipo/internal/runner/thin"
24 "amadan.net/oficina/equipo/internal/runner/webread"
25 "amadan.net/oficina/equipo/internal/wire"
26 "amadan.net/rastrillo/rastrillo"
27)
28
29func run(ctx context.Context, args []string, input io.Reader, output, errorOutput io.Writer, getenv func(string) string) int {
30 fail := func(err error) int {
31 code, variable := runner.Diagnostic(err)
32 _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, code, variable)
33 return 1
34 }
35 // The Research fetcher, started by the runner under bubblewrap: it
36 // needs no configuration and reads its plan on stdin.
37 if len(args) > 0 && args[0] == "webread" {
38 return webread.Main(args[1:], input, errorOutput)
39 }
40 // The page renderer's sandbox, its first process: started by the
41 // runner under bubblewrap with no environment and no configuration.
42 if len(args) > 0 && args[0] == render.Subcommand {
43 return render.SandboxMain(args[1:], errorOutput)
44 }
45 // And the step before it, which closes what the runner's process
46 // should not pass on and executes bubblewrap.
47 if len(args) > 0 && args[0] == render.ExecSubcommand {
48 return render.ExecMain(args[1:])
49 }
50 // A Mac's MCP tool endpoint, started by the CLI: before anything
51 // reads the environment or a configuration.
52 if len(args) > 0 && args[0] == provider.DarwinToolProxyCommand {
53 if code, ok := toolProxy(ctx, args[1:], input, output); ok {
54 return code
55 }
56 }
57 if len(args) > 0 && args[0] == "account" {
58 return accountLogin(ctx, args[1:], input, output, errorOutput, getenv)
59 }
60 if len(args) > 0 && args[0] == "install" {
61 if goos() == "darwin" {
62 return installMac(ctx, args[1:], realMacInstallHost(), output, errorOutput)
63 }
64 return installRunner(ctx, args[1:], input, output, errorOutput, getenv)
65 }
66 // A Mac's launchd agent passes its environment as a file (launchd has
67 // no EnvironmentFile): run --env-file <path>, probe --env-file <path>.
68 args, envFile, ok := cutEnvFile(args)
69 if !ok {
70 return fail(nil)
71 }
72 if envFile != "" {
73 values, err := runnersetup.ReadEnvFile(envFile)
74 if err != nil {
75 return fail(err)
76 }
77 base := getenv
78 getenv = func(k string) string {
79 if v, ok := values[k]; ok {
80 return v
81 }
82 return base(k)
83 }
84 }
85 if len(args) == 2 && args[0] == "login" {
86 cfg, err := runner.LoadConfig(getenv)
87 if err != nil {
88 return fail(err)
89 }
90 if err = thin.Login(ctx, cfg, args[1], thin.LoginOptions{Input: input, Output: output}); err != nil {
91 return fail(err)
92 }
93 return 0
94 }
95 if len(args) > 0 && args[0] == "verify-install-manifest" {
96 return installManifest(args[1:], output)
97 }
98 if len(args) > 0 && args[0] == "install-pi" {
99 return installPi(ctx, args[1:], output, errorOutput)
100 }
101 // The page renderer beside this runner (Linux amd64), from the
102 // release's renderer.tar.gz: the production scripts run it.
103 if len(args) > 0 && args[0] == "install-renderer" {
104 return installRendererCommand(args[1:], output, errorOutput)
105 }
106 // The page renderer linked into this build, for the release tooling
107 // (scripts/publish-renderer.sh): a -trimpath build keeps no -ldflags
108 // in its build information, so only the runner itself can say.
109 if len(args) > 0 && args[0] == "renderer-asset" {
110 return rendererAssetCommand(args[1:], output, errorOutput)
111 }
112 if len(args) > 0 && args[0] == "install-opencode" {
113 return installOpenCode(ctx, args[1:], output, errorOutput)
114 }
115 if len(args) != 1 {
116 return fail(nil)
117 }
118 if args[0] == "version" {
119 if json.NewEncoder(output).Encode(struct {
120 Version string `json:"version"`
121 Manifest release.Manifest `json:"manifest"`
122 }{rastrillo.BuildVersion, release.BuildManifest()}) != nil {
123 return fail(nil)
124 }
125 return 0
126 }
127 if args[0] == "tool" {
128 if runner.ServeTools(ctx, input, output, getenv("EQUIPO_TOOL_SOCKET"), getenv("EQUIPO_TOOL_CAPABILITY_FILE")) != nil {
129 _, _ = io.WriteString(errorOutput, equipo.CopyToolRejected+"\n")
130 return 1
131 }
132 return 0
133 }
134 if args[0] != "run" && args[0] != "enrol" && args[0] != "preflight" && args[0] != "reset" && args[0] != "probe" && args[0] != "verify-installed" {
135 return fail(nil)
136 }
137 cfg, err := runner.LoadConfig(getenv)
138 if err != nil {
139 return fail(err)
140 }
141 cfg.Copy = equipo.RunnerToolCopy()
142 cfg.Report = func(code string) {
143 if code == "runner.waiting_accounts" {
144 _, _ = fmt.Fprintln(errorOutput, equipo.RunnerText(code))
145 return
146 }
147 _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, code, "-")
148 }
149 switch args[0] {
150 case "enrol":
151 err = enrolAlone(ctx, cfg, output, runner.Enrol)
152 if errors.Is(err, errInstallBusy) {
153 _, _ = fmt.Fprintln(errorOutput, equipo.RunnerSetupCopy("runner.install.busy"))
154 return 1
155 }
156 case "reset":
157 err = runner.Reset(ctx, cfg)
158 case "run":
159 opts := thin.OptionsFromEnv(getenv)
160 opts.Version, opts.Logger = rastrillo.BuildVersion, slog.New(slog.NewTextHandler(errorOutput, logOptions(getenv)))
161 logStart(opts.Logger, cfg, opts.Version, envFile)
162 err = thin.Run(ctx, cfg, opts)
163 if errors.Is(err, thin.ErrSuperseded) {
164 _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, "runner.superseded", "-")
165 return supersededExit(goos())
166 }
167 if errors.Is(err, thin.ErrUpdated) {
168 return mac.ExitUpdated
169 }
170 case "probe":
171 // The Mac's self-probes, on demand; the running worker picks the
172 // report up and sends it. Paul never needs this.
173 if goos() != "darwin" {
174 _, _ = fmt.Fprintln(errorOutput, equipo.RunnerSetupCopy("runner.mac.platform"))
175 return 1
176 }
177 opts := thin.OptionsFromEnv(getenv)
178 opts.Version = rastrillo.BuildVersion
179 var report mac.Report
180 report, err = thin.RunProbes(ctx, cfg, opts)
181 if err == nil {
182 err = json.NewEncoder(output).Encode(report.Probes)
183 }
184 case "verify-installed":
185 err = verifyInstalled(release.BuildManifest(), cfg)
186 // What differs, for the operator whose script stopped here (a
187 // renderer's diagnostic names the entry).
188 if err != nil {
189 _, _ = fmt.Fprintln(errorOutput, "verify-installed:", err)
190 }
191 case "preflight":
192 var reports any
193 reports, err = runner.Preflight(ctx, cfg)
194 if err == nil {
195 err = json.NewEncoder(output).Encode(reports)
196 }
197 }
198 if err != nil && !errors.Is(err, context.Canceled) {
199 return fail(err)
200 }
201 return 0
202}
203func main() {
204 if len(os.Args) == 2 && os.Args[1] == "__install_probe" {
205 os.Exit(runnersetup.InstallProbeMain(os.Stdin, os.Stdout))
206 }
207 if len(os.Args) > 1 && os.Args[1] == "__namespace" {
208 os.Exit(namespace(os.Args[2:]))
209 }
210 if len(os.Args) > 1 && os.Args[1] == "__fprobe" {
211 // The Mac probes' direct kernel reader (mac/fprobe), run inside
212 // Claude's sandbox by a probe script and by P2's fixture.
213 os.Exit(fprobe.HelperMain(os.Args[2:], os.Stdout))
214 }
215 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
216 code := run(ctx, os.Args[1:], os.Stdin, os.Stdout, os.Stderr, os.Getenv)
217 stop()
218 os.Exit(code)
219}
220
221// logStart is the runner's first line: what starts, where it connects
222// (the origin's host only) and from which env file. No credential.
223// logOptions is the runner's log level: info, or debug with
224// EQUIPO_RUNNER_LOG_LEVEL=debug (an Assistant turn's phases, for one).
225func logOptions(getenv func(string) string) *slog.HandlerOptions {
226 if getenv("EQUIPO_RUNNER_LOG_LEVEL") == "debug" {
227 return &slog.HandlerOptions{Level: slog.LevelDebug}
228 }
229 return &slog.HandlerOptions{Level: slog.LevelInfo}
230}
231
232func logStart(log *slog.Logger, cfg runner.Config, version, envFile string) {
233 role := wire.RolePrimary
234 if cfg.WorkerOnly || runner.ReadRole(cfg.StateDir) == wire.RoleWorker {
235 role = wire.RoleWorker
236 }
237 host := ""
238 if u, err := url.Parse(cfg.Origin); err == nil {
239 host = u.Host
240 }
241 attrs := []any{"version", version, "os", goos(), "arch", goarch(), "role", role, "origin", host, "label", cfg.MachineLabel}
242 if envFile != "" {
243 attrs = append(attrs, "env_file", envFile)
244 }
245 log.Info("runner starting", attrs...)
246}
247
248// supersededExit: systemd must not restart a runner that lost its lease
249// (RestartPreventExitStatus=3); launchd restarts any non-zero exit
250// (KeepAlive SuccessfulExit false), so on a Mac it is 0.
251func supersededExit(goos string) int {
252 if goos == "darwin" {
253 return 0
254 }
255 return thin.ExitSuperseded
256}
257
258// cutEnvFile takes "--env-file <path>" out of the arguments of run and
259// probe. ok is false when it is malformed or given to another verb.
260func cutEnvFile(args []string) (rest []string, file string, ok bool) {
261 for i := 0; i < len(args); i++ {
262 if args[i] != "--env-file" {
263 rest = append(rest, args[i])
264 continue
265 }
266 if file != "" || i+1 >= len(args) || len(rest) != 1 || (rest[0] != "run" && rest[0] != "probe") {
267 return nil, "", false
268 }
269 file = args[i+1]
270 i++
271 }
272 return rest, file, true
273}
274