| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "sync" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/runner/checks" |
| 12 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 13 | "amadan.net/oficina/equipo/internal/runner/forge" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| 17 | "amadan.net/oficina/equipo/internal/runner/provider/codex" |
| 18 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 19 | ) |
| 20 | |
| 21 | type Runtime struct { |
| 22 | preflightCache map[string]string |
| 23 | lastReports []runnerproto.ConnectionReport |
| 24 | namespaces *containment.Manager |
| 25 | launchers map[string]provider.Launcher |
| 26 | host provider.ProcessHost |
| 27 | cfg Config |
| 28 | lock *os.File |
| 29 | journal *Journal |
| 30 | api *HTTPInstance |
| 31 | service *Service |
| 32 | sandbox *checks.CodexSandbox |
| 33 | mu sync.Mutex |
| 34 | current *RunClaim |
| 35 | } |
| 36 | |
| 37 | func openRuntime(ctx context.Context, c Config) (r *Runtime, err error) { |
| 38 | if err = c.validate(); err != nil { |
| 39 | return nil, err |
| 40 | } |
| 41 | variable := "EQUIPO_RUNNER_STATE_DIR" |
| 42 | r = &Runtime{cfg: c} |
| 43 | defer func() { |
| 44 | if err != nil { |
| 45 | err = diagnosticAt(err, variable) |
| 46 | r.Close() |
| 47 | } |
| 48 | }() |
| 49 | r.lock, err = lockState(c.StateDir) |
| 50 | if err != nil { |
| 51 | return r, err |
| 52 | } |
| 53 | credentials, err := readCredentials(filepath.Join(c.StateDir, "credentials.json")) |
| 54 | if err != nil { |
| 55 | return r, err |
| 56 | } |
| 57 | variable = "EQUIPO_ACCOUNT_BINDINGS_PATH" |
| 58 | bs, err := loadDirectBindings(c.AccountBindingsPath) |
| 59 | if err != nil { |
| 60 | return r, err |
| 61 | } |
| 62 | for _, dir := range []struct{ name, path string }{{"EQUIPO_SCRATCH_ROOT", c.ScratchRoot}, {"EQUIPO_WORKSPACE_ROOT", c.WorkspaceRoot}} { |
| 63 | variable = dir.name |
| 64 | if err = os.MkdirAll(dir.path, 0700); err != nil { |
| 65 | return r, err |
| 66 | } |
| 67 | } |
| 68 | if err = forge.SweepDescriptions(c.ScratchRoot); err != nil { |
| 69 | return r, err |
| 70 | } |
| 71 | variable = "EQUIPO_RUNNER_STATE_DIR" |
| 72 | r.journal, err = OpenJournal(ctx, filepath.Join(c.StateDir, "journal.db")) |
| 73 | if err != nil { |
| 74 | return r, err |
| 75 | } |
| 76 | variable = "EQUIPO_ORIGIN" |
| 77 | r.api, err = NewHTTPInstance(c.Origin+"/api/runner/v2", r.journal, credentials.Bearer) |
| 78 | if err == nil { |
| 79 | r.api.repositories = (forge.FileCredentials{Path: c.AmadanCredentialPath}).RepositoryNames |
| 80 | } |
| 81 | if err != nil { |
| 82 | return r, err |
| 83 | } |
| 84 | for id, token := range credentials.CleanupTokens { |
| 85 | r.api.cleanup[id] = token |
| 86 | } |
| 87 | variable = "EQUIPO_SCRATCH_ROOT" |
| 88 | r.namespaces, err = containment.New(containment.Config{Binary: c.bwrap(), RunnerBinary: c.Executable, ScratchRoot: c.ScratchRoot, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}, {Provider: "codex"}}}) |
| 89 | if err != nil { |
| 90 | return r, err |
| 91 | } |
| 92 | if _, err = r.journal.ReconcileDirect(ctx, r.namespaces); err != nil { |
| 93 | return r, err |
| 94 | } |
| 95 | r.host = NewDirectHost(r.journal, r.namespaces) |
| 96 | captures := NewCaptureFactory(r.journal) |
| 97 | claudeLauncher, err := claude.New(r.host, captures) |
| 98 | if err != nil { |
| 99 | return r, err |
| 100 | } |
| 101 | codexLauncher, err := codex.New(r.host, captures) |
| 102 | if err != nil { |
| 103 | return r, err |
| 104 | } |
| 105 | r.launchers = map[string]provider.Launcher{"claude": claudeLauncher, "codex": codexLauncher} |
| 106 | variable = "EQUIPO_CODEX_PATH" |
| 107 | r.sandbox, err = checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: c.CodexPath, ScratchRoot: c.ScratchRoot, GoRoot: c.GoRoot, GoBinary: c.GoBinary, Protected: c.securityPaths(bs), Host: r.host, RunnerBinary: c.Executable, Bwrap: c.bwrap(), ModuleCache: c.moduleCache()}) |
| 108 | if err != nil { |
| 109 | return r, err |
| 110 | } |
| 111 | |
| 112 | return r, nil |
| 113 | } |
| 114 | func (r *Runtime) Close() error { |
| 115 | if r == nil { |
| 116 | return nil |
| 117 | } |
| 118 | var err error |
| 119 | if r.namespaces != nil { |
| 120 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 121 | records, e := r.namespaces.Records(ctx) |
| 122 | err = errors.Join(err, e) |
| 123 | for _, record := range records { |
| 124 | if _, e = r.namespaces.Stop(ctx, record.ID); e != nil { |
| 125 | // Failed construction may contain an unrelated record. Never claim it. |
| 126 | if r.journal == nil || r.journal.validateDirectRecord(ctx, record) != nil { |
| 127 | continue |
| 128 | } |
| 129 | _, e = r.namespaces.Recover(ctx, record) |
| 130 | } |
| 131 | err = errors.Join(err, e) |
| 132 | } |
| 133 | cancel() |
| 134 | if err != nil { |
| 135 | return err |
| 136 | } |
| 137 | r.namespaces = nil |
| 138 | } |
| 139 | if r.service != nil && r.service.Supervisor.activeRelease != nil { |
| 140 | if e := r.service.Supervisor.activeRelease(); e != nil { |
| 141 | return e |
| 142 | } |
| 143 | r.service.Supervisor.activeRelease = nil |
| 144 | } |
| 145 | if r.service != nil && r.service.Coordinator != nil && r.service.Coordinator.release != nil { |
| 146 | if e := r.service.Coordinator.release(); e != nil { |
| 147 | return e |
| 148 | } |
| 149 | r.service.Coordinator.release = nil |
| 150 | } |
| 151 | if r.journal != nil { |
| 152 | r.journal.captureMu.Lock() |
| 153 | err = errors.Join(err, r.journal.Close()) |
| 154 | r.journal.captureMu.Unlock() |
| 155 | r.journal = nil |
| 156 | } |
| 157 | if r.lock != nil { |
| 158 | err = errors.Join(err, r.lock.Close()) |
| 159 | r.lock = nil |
| 160 | } |
| 161 | return err |
| 162 | } |
| 163 | func (r *Runtime) binding(s provider.Selection) (AccountBinding, []AccountBinding, error) { |
| 164 | bs, err := loadDirectBindings(r.cfg.AccountBindingsPath) |
| 165 | if err != nil { |
| 166 | return AccountBinding{}, nil, err |
| 167 | } |
| 168 | var selected *AccountBinding |
| 169 | for i, b := range bs { |
| 170 | if b.Provider == s.Provider && b.Family == s.Family && b.Model == s.Model && b.AccountID == s.AccountID { |
| 171 | if selected != nil { |
| 172 | return AccountBinding{}, nil, provider.ErrIdentity |
| 173 | } |
| 174 | selected = &bs[i] |
| 175 | } |
| 176 | } |
| 177 | if selected == nil { |
| 178 | return AccountBinding{}, nil, provider.ErrIdentity |
| 179 | } |
| 180 | return *selected, bs, nil |
| 181 | } |
| 182 | func (r *Runtime) policy(_ context.Context, s provider.Selection) (provider.ReadPolicy, error) { |
| 183 | b, bs, err := r.binding(s) |
| 184 | if err != nil { |
| 185 | return provider.ReadPolicy{}, err |
| 186 | } |
| 187 | return bindingPolicy(r.cfg, bs, b) |
| 188 | } |
| 189 | func Preflight(ctx context.Context, c Config) ([]runnerproto.ConnectionReport, error) { |
| 190 | r, err := openRuntime(ctx, c) |
| 191 | if err != nil { |
| 192 | return nil, err |
| 193 | } |
| 194 | defer r.Close() |
| 195 | return r.discoverNamespaces(ctx) |
| 196 | } |
| 197 | func Run(ctx context.Context, c Config) error { |
| 198 | r, err := openRuntime(ctx, c) |
| 199 | if err != nil { |
| 200 | return err |
| 201 | } |
| 202 | defer r.Close() |
| 203 | if err = r.wire(ctx); err != nil { |
| 204 | return err |
| 205 | } |
| 206 | return r.service.Run(ctx) |
| 207 | } |
| 208 | func (r *Runtime) Poll(ctx context.Context) ([]runnerproto.Assignment, error) { |
| 209 | r.mu.Lock() |
| 210 | r.current = nil |
| 211 | r.mu.Unlock() |
| 212 | for { |
| 213 | reports, err := r.discoverNamespaces(ctx) |
| 214 | if err != nil { |
| 215 | return nil, err |
| 216 | } |
| 217 | if len(reports) == 0 && r.cfg.Report != nil { |
| 218 | r.cfg.Report("runner.waiting_accounts") |
| 219 | } |
| 220 | if err = r.api.Heartbeat(ctx, reports); err != nil { |
| 221 | return nil, err |
| 222 | } |
| 223 | r.mu.Lock() |
| 224 | r.lastReports = append([]runnerproto.ConnectionReport(nil), reports...) |
| 225 | r.mu.Unlock() |
| 226 | if len(reports) > 0 { |
| 227 | break |
| 228 | } |
| 229 | if err := waitService(ctx, 5*time.Second); err != nil { |
| 230 | return nil, err |
| 231 | } |
| 232 | } |
| 233 | return r.api.Poll(ctx) |
| 234 | } |
| 235 | func (r *Runtime) Claim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| 236 | if q.Version != runnerproto.DirectVersion { |
| 237 | return runnerproto.ClaimResponse{}, provider.ErrVersion |
| 238 | } |
| 239 | reports, err := r.discoverNamespaces(ctx) |
| 240 | if err != nil { |
| 241 | return runnerproto.ClaimResponse{}, err |
| 242 | } |
| 243 | if err = r.api.Heartbeat(ctx, reports); err != nil { |
| 244 | return runnerproto.ClaimResponse{}, err |
| 245 | } |
| 246 | r.mu.Lock() |
| 247 | r.lastReports = append([]runnerproto.ConnectionReport(nil), reports...) |
| 248 | r.mu.Unlock() |
| 249 | return r.api.Claim(ctx, q) |
| 250 | } |
| 251 | |
| 252 | func (r *Runtime) RecoverClaim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| 253 | return r.api.RecoverClaim(ctx, q) |
| 254 | } |
| 255 | |
| 256 | func (r *Runtime) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error { |
| 257 | if op == "validate" || op == "admit" { |
| 258 | if err := r.verifyRelease(); err != nil { |
| 259 | return provider.ErrPolicy |
| 260 | } |
| 261 | } |
| 262 | if op == "renew" { |
| 263 | r.mu.Lock() |
| 264 | reports := append([]runnerproto.ConnectionReport(nil), r.lastReports...) |
| 265 | r.mu.Unlock() |
| 266 | if len(reports) == 0 { |
| 267 | return provider.ErrPreflightRequired |
| 268 | } |
| 269 | // A held account lease cannot be reopened for a heartbeat. Dispatch and |
| 270 | // the workflow's current callback still revalidate the selected account. |
| 271 | if err := r.api.Heartbeat(ctx, reports); err != nil { |
| 272 | return err |
| 273 | } |
| 274 | } |
| 275 | return r.api.Call(ctx, op, q, out) |
| 276 | } |
| 277 | |