oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "amadan.net/oficina/equipo/internal/runner/provider/pi"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "io/fs"
12 "log/slog"
13 "net/netip"
14 "os"
15 "path/filepath"
16 "runtime"
17 "slices"
18 "strings"
19
20 "golang.org/x/sys/unix"
21 "sync"
22 "sync/atomic"
23 "time"
24
25 "amadan.net/oficina/equipo/internal/runner"
26 "amadan.net/oficina/equipo/internal/runner/containment"
27 "amadan.net/oficina/equipo/internal/runner/mac"
28 "amadan.net/oficina/equipo/internal/runner/metered"
29 "amadan.net/oficina/equipo/internal/runner/provider"
30 "amadan.net/oficina/equipo/internal/runner/webread"
31 "amadan.net/oficina/equipo/internal/runnerproto"
32 "amadan.net/oficina/equipo/internal/sealbox"
33 "amadan.net/oficina/equipo/internal/wire"
34)
35
36// ExitSuperseded is the process exit status after losing the lease; the
37// unit must not restart on it, or two processes would take turns.
38const ExitSuperseded = 3
39
40// Options are the thin runner's settings beyond runner.Config.
41type Options struct {
42 Version string
43 Claude ClaudeOptions
44 // Codex configures Codex coordinator sessions (pinned digests).
45 Codex CodexOptions
46 // Pi, in tests, is a fake Pi's install and digests; empty, the
47 // runner's own (EQUIPO_PI_ROOT, the committed pins).
48 Pi PiOptions
49 // OpenCode, in tests, is a fake OpenCode's install and digests;
50 // empty, the runner's own (EQUIPO_OPENCODE_ROOT, the committed pins).
51 OpenCode OpenCodeOptions
52 Logger *slog.Logger
53 // Connected observes the stream for tests.
54 Connected func(bool)
55 // Forge overrides the credential-file forge (tests use local repos).
56 Forge Forge
57 // IndexPace spaces the context index's fetches (default 4s).
58 IndexPace time.Duration
59 // NoCreate turns repository creation off (EQUIPO_RUNNER_CREATE_REPOS=0).
60 NoCreate bool
61 // Home is the namespace for new work that fits no related namespace
62 // (EQUIPO_RUNNER_HOME_NAMESPACE). It must also be in CreateIn.
63 Home string
64 // NoMoveIn turns automatic moving in and exploring off
65 // (EQUIPO_RUNNER_MOVE_IN=0).
66 NoMoveIn bool
67 // MaxStep bounds one Engineering step (EQUIPO_RUNNER_MAX_STEP, 5 to 60
68 // minutes; default 20) and the local checks gate; StepNote is appended
69 // to its prompt (tests steer the fake CLI with it).
70 MaxStep time.Duration
71 StepNote string
72 // KeptRetention bounds an unused kept step session (default
73 // KeptSessionRetention).
74 KeptRetention time.Duration
75 // MergeEvery spaces the merge checks of watched task branches
76 // (default: the minute reach check's pace).
77 MergeEvery time.Duration
78 // Protocol caps the runner stream protocol offered (tests: 1 acts as
79 // a slice 4 runner); 0 is the current one.
80 Protocol int
81 // FakePlatform (EQUIPO_FAKE_PLATFORM=darwin/arm64) starts the test
82 // build's fake Mac worker; any other build refuses it. FakeBin is put
83 // first on its gates' PATH (the fake xcodebuild).
84 FakePlatform, FakeBin string
85 // Getenv is the environment the runner was started with, its env
86 // file (--env-file) included; nil is the process's.
87 Getenv func(string) string
88 // FakeSandbox is what the fake worker says confined its checks
89 // (EQUIPO_FAKE_SANDBOX): none unless a scenario plays a Mac whose
90 // probe P2 denied (seatbelt). Test build only, like the fake itself.
91 FakeSandbox string
92 // AccountsRoot holds the homes of connections added from the app
93 // (EQUIPO_ACCOUNTS_ROOT; default ~/.local/share/equipo/accounts).
94 AccountsRoot string
95 // ConnectLimit bounds a connection attempt (default ConnectLimit).
96 ConnectLimit time.Duration
97 // ResearchFetch stands in for the Research fetch phase's sandboxed
98 // fetcher, and ResearchAddresses for this machine's interface
99 // addresses (the hello's and every Research step's): tests only, so
100 // no test reaches the network. nil: the real ones. Never read from
101 // the environment.
102 ResearchFetch func(context.Context, webread.LaunchConfig, webread.Plan) error
103 ResearchAddresses func() ([]netip.Addr, error)
104 // ReadCodexLimits stands in for the Codex reading probe's app-server
105 // read (tests); nil: provider.ReadCodexLimits with the pinned CLI.
106 ReadCodexLimits func(context.Context, provider.Binding) (provider.Identity, json.RawMessage, error)
107}
108
109// OptionsFromEnv reads the runner's optional thin settings.
110func OptionsFromEnv(getenv func(string) string) Options {
111 return Options{Getenv: getenv, FakePlatform: getenv("EQUIPO_FAKE_PLATFORM"), FakeBin: getenv("EQUIPO_FAKE_BIN"), FakeSandbox: getenv("EQUIPO_FAKE_SANDBOX"), NoCreate: getenv("EQUIPO_RUNNER_CREATE_REPOS") == "0", Home: getenv("EQUIPO_RUNNER_HOME_NAMESPACE"), NoMoveIn: getenv("EQUIPO_RUNNER_MOVE_IN") == "0", IndexPace: 4 * time.Second, AccountsRoot: getenv("EQUIPO_ACCOUNTS_ROOT"), MaxStep: maxStepFrom(getenv("EQUIPO_RUNNER_MAX_STEP")), Claude: ClaudeOptions{Profile: AnthropicProfile()}}
112}
113
114// Bounds of EQUIPO_RUNNER_MAX_STEP: under the stall sweep's 90 minutes
115// with room for the push, and long enough for a step to do anything.
116const (
117 minMaxStep = 5 * time.Minute
118 maxMaxStep = 60 * time.Minute
119)
120
121// maxStepFrom reads EQUIPO_RUNNER_MAX_STEP, a Go duration of 5 to 60
122// minutes; anything else (or nothing) is the default.
123func maxStepFrom(value string) time.Duration {
124 d, err := time.ParseDuration(value)
125 if err != nil || d < minMaxStep || d > maxMaxStep {
126 return DefaultMaxStep
127 }
128 return d
129}
130
131// SessionRoot is where durable coordinator transcripts live by default:
132// beside the state directory, never inside a runtime or credential home.
133func SessionRoot(c runner.Config) string { return filepath.Join(filepath.Dir(c.StateDir), "sessions") }
134
135// Run serves the instance until ctx ends or a newer generation takes over.
136func Run(ctx context.Context, c runner.Config, o Options) error {
137 if err := c.Validate(); err != nil {
138 return err
139 }
140 if p := o.Claude.Profile; p != nil && p.Version == "" {
141 // The profile read names the runner by its build.
142 named := *p
143 named.Version = o.Version
144 o.Claude.Profile = &named
145 }
146 if o.FakePlatform != "" {
147 if fake == nil {
148 return ErrNotTestBuild
149 }
150 platform, ok := fake.platform(o.FakePlatform)
151 if !ok {
152 return ErrNotTestBuild
153 }
154 if o.Logger != nil {
155 o.Logger.Warn("test build: the fake Mac worker runs checks in a process group without a sandbox", "build", fake.marker())
156 }
157 w, err := fake.setup(ctx, &c, o)
158 if err != nil {
159 return err
160 }
161 return runWorker(ctx, c, o, platform, w)
162 }
163 if runtime.GOOS == "darwin" {
164 return runMac(ctx, c, o)
165 }
166 // Ownership first: the state lock, then the scratch and workspace
167 // roots. Only then may recovery touch namespaces or scratch.
168 var manager *containment.Manager
169 release, err := startup(ctx, c, o.Logger, func(ctx context.Context) error {
170 var err error
171 manager, err = containment.New(containment.Config{Binary: c.Bwrap(), RunnerBinary: c.Executable, ScratchRoot: c.ScratchRoot, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}, {Provider: "codex"}}})
172 if err != nil {
173 return err
174 }
175 // Namespaces of a previous process died with it (--die-with-parent);
176 // verify each exit and release its record and scratch.
177 if records, err := manager.Records(ctx); err == nil {
178 for _, r := range records {
179 _ = manager.Forget(ctx, r)
180 }
181 }
182 return nil
183 })
184 if err != nil {
185 return err
186 }
187 defer release()
188 creds, state, err := openRunner(ctx, c, o.Logger)
189 if err != nil {
190 return err
191 }
192 defer state.Close()
193 o.Claude.Runner, o.Claude.Manager, o.Claude.State, o.Claude.Logger = c, manager, state, o.Logger
194 if o.Claude.SessionRoot == "" {
195 o.Claude.SessionRoot = SessionRoot(c)
196 }
197 if err = os.MkdirAll(o.Claude.SessionRoot, 0700); err != nil {
198 return err
199 }
200 o.Claude.defaults()
201
202 ctx, cancel := context.WithCancel(ctx)
203 defer cancel()
204 platform := hostPlatform()
205 // Previews: loaded once; the capability says whether this runner can
206 // publish them (the instance shows "previews aren't set up" when not).
207 preview := previewOptions(c, o.Logger)
208 // A paired CARLOS devbox wins over Carloku temporary sites.
209 devbox := ProbeDevbox(c, o.Logger, nil)
210 // Merged websites publish to their confirmed places through carlos.
211 site := ProbeSite(c, o.Logger)
212 // The page renderer (Linux amd64 only): checked in the background, so
213 // the connect never waits on its fixture render; a change of its
214 // health goes out in the next hello.
215 renderer := rendererHealth(c, platform.OS, platform.Arch, linkedRendererPin(), o.Logger)
216 caps := &Capabilities{Probe: linuxCapabilities(c, PreviewHostOf(devbox, preview), site, o.ResearchAddresses, renderer), Logger: o.Logger}
217 link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: platform.OS == "darwin", Role: enrolledRole(c, creds.Bearer.Role)}
218 if renderer != nil {
219 renderer.Changed = func() { caps.Stale(); link.HelloSoon() }
220 }
221 renderer.Start(ctx)
222 link.Files = &Files{State: state, SessionRoot: o.Claude.SessionRoot, Logger: o.Logger}
223 // Attachments stay bounded whether or not anything arrives.
224 go link.Files.Run(ctx, 10*time.Minute)
225 fg := o.Forge
226 if fg == nil {
227 ff := NewFileForge(c.AmadanCredentialPath, c.StateDir, !o.NoCreate).(*fileForge)
228 ff.accessTargets = state.accessReadTargets
229 // Each repository it created must have a credential its merges
230 // can use; say which do not, before a merge finds out.
231 ff.checkCreated(ctx, o.Logger)
232 fg, err = NewForges(ff)
233 if err != nil {
234 return err
235 }
236 } else if ff, ok := fg.(*fileForge); ok {
237 ff.accessTargets = state.accessReadTargets
238 }
239
240 clones := &Clones{Root: c.WorkspaceRoot, Git: c.GitPath, Forge: fg}
241 index := &Index{Forge: fg, Clones: clones, Path: filepath.Join(c.StateDir, "catalog.json"), Logger: o.Logger, Changed: link.HelloSoon, Pace: o.IndexPace}
242 tools := &bridge{State: state, Link: link, Forge: fg, Clones: clones, Index: index, Logger: o.Logger, SessionRoot: o.Claude.SessionRoot, Activity: link.Activity}
243 o.Claude.Tools, o.Claude.Catalog = tools.Reply, func() []wire.RepoInfo { return index.AccessCatalog(ctx, state) }
244 o.Claude.Protocol = link.LastProtocol
245 conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: o.Claude.Refresh, LockWait: o.Claude.LockWait}
246 conns.ClaudeUsage = o.Claude.Profile
247 conns.ClaudeStatus = func(ctx context.Context, b provider.Binding) (provider.Identity, string, error) {
248 return provider.ReadClaudeStatus(ctx, b, provider.LoginOptions{ClaudePath: c.ClaudePath})
249 }
250 // A Codex reading older than fifteen minutes is refreshed without a
251 // model turn before the scheduler decides. Claude usage is read by
252 // the hourly check and Check again.
253 conns.Reading = CodexReading(c, o.ReadCodexLimits, o.Claude.LockWait)
254 // A token check is a real request; its usage counts like any other,
255 // and the rate limit the provider reported on it is recorded as a
256 // turn's is: headroom, or limited until its reset. Not for a refused
257 // token, which is no connection.
258 conns.Verify = func(ctx context.Context, b runner.AccountBinding) error {
259 res, err := o.Claude.CheckToken(ctx, b)
260 if res.Seen != nil && !errors.Is(err, provider.ErrLoginRequired) {
261 if res.Seen.Limited {
262 conns.Limit(b.ID, *res.Seen)
263 } else {
264 conns.Observe(b.ID, *res.Seen, "")
265 }
266 }
267 if rerr := state.ReportCheck(context.Background(), res.Rows); rerr != nil && o.Logger != nil {
268 o.Logger.Warn("token check usage", "err", sanitize(rerr))
269 }
270 if res.Seen != nil || res.Named {
271 // The headroom, or the account its profile named, goes with
272 // the next hello, not the next beat.
273 link.HelloSoon()
274 } else {
275 link.Notify()
276 }
277 return err
278 }
279 engine := &Engine{State: state, Conns: conns, Logger: o.Logger, Emit: link.Delta, Act: link.Activity, Notify: link.Notify, Authorize: link.Confirm, Open: func(person, lane string, b runner.AccountBinding) (Coordinator, error) {
280 return openLane(o.Claude, o.Codex, person, lane, b)
281 }, Glance: func(person string, b runner.AccountBinding) (Glancer, error) {
282 return OpenGlance(o.Claude, o.Codex, person, b)
283 }, SendGlance: link.Glance, Glances: link.Glances, OpenLookup: func(person string, b runner.AccountBinding) (Glancer, string, error) {
284 return OpenLookup(o.Claude, o.Codex, person, b)
285 }}
286 var wakeSteps atomic.Pointer[func()]
287 conns.Changed = func() {
288 engine.ConnectionsChanged()
289 link.HelloSoon()
290 if wake := wakeSteps.Load(); wake != nil {
291 (*wake)()
292 }
293 }
294 link.Engine = engine
295 if o.AccountsRoot == "" {
296 o.AccountsRoot = DefaultAccountsRoot()
297 }
298 connector := &Connector{Runner: c, State: state, Conns: conns, Root: o.AccountsRoot, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), Notify: link.Notify, Logger: o.Logger, Limit: o.ConnectLimit, RunnerID: creds.Bearer.RunnerID, Manager: manager}
299 // The metered guard (connectors spec S1). Its slots are reconciled
300 // before anything is admitted: a slot whose attempt's namespace is
301 // proven gone is released with its charge, or with the spend unknown.
302 conns.Meter = &metered.Meter{DB: state.db, Gone: connector.namespaceGone, Changed: func() { conns.changed() }}
303 // A model's first use in a step is probed by the Connector, which
304 // holds the provider clients (§16.4).
305 conns.Prober = connector.probeModel
306 if err = conns.Meter.Recover(ctx); err != nil && o.Logger != nil {
307 o.Logger.Warn("metered recovery", "err", sanitize(err))
308 }
309 // The seal key: the X25519 form of the enrolment key the owner
310 // approved; secrets for token connections are sealed to it.
311 sealKey := ""
312 if key, err := runner.ReadMachineKey(c.StateDir); err == nil {
313 if keys, err := sealbox.FromEd25519(key); err == nil {
314 connector.Seal, sealKey = &keys, keys.PublicString()
315 }
316 clear(key)
317 } else if o.Logger != nil {
318 o.Logger.Warn("no seal key: token connections cannot be added", "err", sanitize(err))
319 }
320 if err = connector.Start(ctx); err != nil {
321 return err
322 }
323 link.Connector = connector
324 // Token connections made before the profile read existed are read
325 // once now (profile.go), beside hello and the checks, never before.
326 go o.Claude.readProfilesAtStart(ctx, conns, link.HelloSoon)
327 createIn := &namespaces{}
328 recheck := make(chan struct{}, 1)
329 link.Recheck = func() {
330 select {
331 case recheck <- struct{}{}:
332 default:
333 }
334 }
335 go createIn.loop(ctx, fg, link, index, recheck)
336 var settle *settler
337 if !o.NoMoveIn {
338 settle = &settler{State: state, Link: link, Index: index, SessionRoot: o.Claude.SessionRoot, Persons: coordinatorPersons(c), Logger: o.Logger}
339 index.Refreshed = func() { settle.Check(ctx) }
340 }
341 engine.ResetDesk = func(person string) error {
342 if err := resetConversation(ctx, state, o.Claude.SessionRoot, person); err != nil {
343 return err
344 }
345 if settle != nil {
346 settle.forget(person)
347 go settle.Check(ctx)
348 }
349 link.Notify()
350 return nil
351 }
352 if af, ok := fg.(AccessForge); ok {
353 link.Access = &AccessEngine{State: state, Forge: af, Authorize: link.ConfirmAccess, Refresh: func() { index.Kick(); link.HelloSoon() }, Notify: link.Notify, Logger: o.Logger}
354 accessDone := make(chan struct{})
355 go func() { defer close(accessDone); link.Access.Run(ctx) }()
356 defer func() { cancel(); <-accessDone }()
357 }
358 go index.Loop(ctx)
359 link.Hello = func() wire.Hello {
360 repos := fg.Repos()
361 if repos == nil {
362 repos = []string{}
363 }
364 in := createIn.get()
365 home := ""
366 if slices.Contains(in, o.Home) {
367 home = o.Home
368 }
369 catalog := index.AccessCatalog(ctx, state)
370 if catalog == nil {
371 catalog = []wire.RepoInfo{}
372 }
373 report := caps.Get(ctx)
374 return wire.Hello{Repos: repos, CreateIn: in, Home: home, Agent: fg.Agent(), Catalog: catalog, Connections: conns.Held(), Versions: map[string]string{"runner": o.Version, "claude": provider.ClaudeVersion}, SealKey: sealKey,
375 Platform: &platform, Label: c.MachineLabel, Sandbox: wire.SandboxBubblewrap, Capabilities: &report}
376 }
377 if err = engine.Start(ctx); err != nil {
378 return err
379 }
380 engineer := &Engineer{DiffSecrets: []string{creds.Bearer.Token}, O: o.Claude, Codex: o.Codex, Pi: piOptions(c, o.Pi), OpenCode: opencodeOptions(c, o.OpenCode), Clones: clones, Forge: fg, CI: hostedCIOf(fg), Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPreview: link.ConfirmPreview, ConfirmRender: link.ConfirmRender, Preview: preview, Devbox: devbox, Site: site, ConfirmPublish: link.ConfirmPublish, ConfirmMint: link.ConfirmMint, SiteChanged: func() { caps.Stale(); link.HelloSoon() }, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Spoken: func() int { p, _ := link.Spoken(); return p }, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel, Merged: func(string) { index.Kick() }}
381 engineer.Renderer = renderer
382 link.Forget = engineer.RemoveKept
383 link.TaskEnded = engineer.PreviewTaskEnded
384 // A Research step that met an address outside the confirmed inventory
385 // has the next hello say what is here now.
386 engineer.ResearchAddresses = func() { caps.Stale(); link.HelloSoon() }
387 engineer.rh.launch, engineer.rh.addrs = o.ResearchFetch, o.ResearchAddresses
388 if devbox != nil {
389 // The domain, once a share tells it, goes out in the next hello.
390 devbox.Learnt = link.HelloSoon
391 }
392 merges := &MergeWatch{State: state, Clones: clones, Git: c.GitPath, Notify: link.Notify, Logger: o.Logger, Every: o.MergeEvery}
393 if merges.Every <= 0 {
394 merges.Every = reachEvery + 5*time.Second
395 }
396 link.Synced = func() {
397 merges.Kick()
398 // Each sync (start, reconnect, and so a new rule's first start)
399 // warms the Assistant lanes in use, where the instance has them.
400 if proto, _ := link.Spoken(); proto >= wire.ProtocolAssistant {
401 engine.WarmAssistants()
402 }
403 }
404 go merges.Loop(ctx)
405 if engineer.MaxStep == 0 {
406 engineer.MaxStep = DefaultMaxStep
407 }
408 tags := func() []string { return caps.Get(ctx).Tags }
409 steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, engineer.Exec), Ask: engineer.ask, Notify: link.Notify, Logger: o.Logger, Sweep: func(ctx context.Context) {
410 engineer.Sweep(ctx, state)
411 engineer.sweepKept(ctx, state)
412 engineer.SweepPublications(ctx, state)
413 }, Verify: func(ctx context.Context, id string) bool { return verifiedExit(ctx, manager, id) }, TerminationKind: wire.TerminationNamespace}
414 link.Steps = steps
415 relay := &Relay{State: state, Engine: engineer, Notify: link.Notify, Logger: o.Logger}
416 link.Relay = relay
417 go relay.Loop(ctx)
418 // A change of a connection's standing also looks again at questions
419 // held by the metered guard.
420 steps.Meter = conns.Meter
421 // A question on a step's kept Pi session runs through the guard on
422 // its own connection (connectors spec §7, Ask).
423 steps.MeteredAsk = engineer.askPi
424 wake := steps.MeteredChanged
425 wakeSteps.Store(&wake)
426 // A new reading wakes the steps the scheduler holds.
427 conns.Readings = steps.MeteredChanged
428 if err = steps.Start(ctx); err != nil {
429 return err
430 }
431 go conns.Loop(ctx)
432 err = link.Run(ctx)
433 if errors.Is(err, ErrSuperseded) {
434 cancel()
435 engine.Wait()
436 steps.Wait()
437 _ = state.Supersede(context.Background())
438 return err
439 }
440 cancel()
441 engine.Wait()
442 steps.Wait()
443 if ctx.Err() != nil && !errors.Is(err, ErrRevoked) {
444 return nil
445 }
446 return err
447}
448
449// resetConversation clears the person's own conversation once its
450// coordinator process is closed: the main desk and the main lane's
451// session go, and the instance hears the notebook is empty.
452func resetConversation(ctx context.Context, state *State, sessionRoot, person string) error {
453 desk, err := OpenDesk(sessionRoot, person)
454 if err == nil {
455 err = desk.Clear()
456 }
457 if err == nil {
458 err = state.deleteSession(ctx, person, wire.LaneCoordinator)
459 }
460 if err == nil {
461 err = state.SendNotebook(ctx, wire.NotebookReport{Person: person})
462 }
463 return err
464}
465
466// namespaces caches where the agent may create repositories, refreshed in
467// the background so a hello never waits on the hub.
468type namespaces struct {
469 mu sync.Mutex
470 ns []string
471}
472
473func (n *namespaces) get() []string {
474 n.mu.Lock()
475 defer n.mu.Unlock()
476 return append([]string{}, n.ns...)
477}
478
479// loop watches what the agent may create in and what it reaches: a
480// cheap conditional check about once a minute, and at once when a
481// person acts on a grant card (recheck). A change in reach is sent in a
482// hello and refreshes the index for the new repositories only.
483func (n *namespaces) loop(ctx context.Context, f Forge, link *Link, index *Index, recheck <-chan struct{}) {
484 var reach []string
485 for {
486 rctx, cancel := context.WithTimeout(ctx, 40*time.Second)
487 ns := f.CreateIn(rctx)
488 now := f.Reachable(rctx)
489 cancel()
490 n.mu.Lock()
491 changed := !slices.Equal(ns, n.ns)
492 n.ns = ns
493 n.mu.Unlock()
494 moved := reach != nil && !slices.Equal(now, reach)
495 reach = now
496 if changed || moved {
497 link.HelloSoon()
498 }
499 if moved && index != nil {
500 index.Kick()
501 }
502 select {
503 case <-ctx.Done():
504 return
505 case <-time.After(reachEvery + 5*time.Second):
506 case <-recheck:
507 f.Recheck()
508 }
509 }
510}
511
512// ErrRootShared means a scratch or workspace root belongs to another
513// runner's state directory, or another runner holds it now.
514var ErrRootShared = errors.New("runner root shared with another runner")
515
516const ownerFile = ".equipo-root-owner"
517
518// startup orders what a runner may touch: its state lock, then exclusive
519// ownership of its scratch and workspace roots, then recovery of what its
520// own dead processes left (namespaces, then credential copies and other
521// scratch). A runner refused its roots recovers and deletes nothing.
522func startup(ctx context.Context, c runner.Config, log *slog.Logger, recover func(context.Context) error) (func(), error) {
523 done := startPhase(log, "state_lock")
524 lock, err := runner.LockState(c.StateDir)
525 done(err)
526 if err != nil {
527 return nil, err
528 }
529 done = startPhase(log, "claim_roots")
530 roots, err := claimRoots(c)
531 done(err)
532 if err != nil {
533 lock.Close()
534 return nil, err
535 }
536 release := func() { roots(); lock.Close() }
537 done = startPhase(log, "sweep")
538 if err = recover(ctx); err == nil {
539 err = sweepOrphans(c)
540 }
541 done(err)
542 if err != nil {
543 release()
544 return nil, err
545 }
546 return release, nil
547}
548
549// openRunner reads the runner's credential and opens its state, each a
550// logged startup phase. Nothing of the credential is logged.
551func openRunner(ctx context.Context, c runner.Config, log *slog.Logger) (runnerproto.CredentialRotation, *State, error) {
552 done := startPhase(log, "credentials")
553 creds, err := runner.ReadCredentials(filepath.Join(c.StateDir, "credentials.json"))
554 done(credentialLogError(err))
555 if err != nil {
556 return creds, nil, err
557 }
558 done = startPhase(log, "open_state")
559 state, err := OpenState(ctx, c.StateDir)
560 done(err)
561 return creds, state, err
562}
563
564// credentialLogError is a credential read failure as it may be logged: a
565// path, policy or identity error as it is; anything the decoder said
566// about the file's content only by its type.
567func credentialLogError(err error) error {
568 var path *fs.PathError
569 if err == nil || errors.As(err, &path) || errors.Is(err, provider.ErrPolicy) || errors.Is(err, provider.ErrIdentity) {
570 return err
571 }
572 return fmt.Errorf("unreadable credential file (%T)", err)
573}
574
575// startPhase logs a startup phase's start; the function it returns logs
576// its end, how long it took and its error. A silent hang at start is
577// pinned to the phase that started and never ended.
578func startPhase(log *slog.Logger, phase string) func(error) {
579 if log == nil {
580 return func(error) {}
581 }
582 start := time.Now()
583 log.Info("startup phase", "phase", phase)
584 return func(err error) {
585 if err != nil {
586 log.Warn("startup phase failed", "phase", phase, "took", took(start), "err", err.Error())
587 return
588 }
589 log.Info("startup phase done", "phase", phase, "took", took(start))
590 }
591}
592
593// took is the time since start, rounded for a log line.
594func took(start time.Time) time.Duration {
595 d := time.Since(start)
596 if d >= time.Second {
597 return d.Round(time.Millisecond)
598 }
599 return d.Round(time.Microsecond)
600}
601
602// prepareRoots claims the roots and sweeps orphans.
603func prepareRoots(c runner.Config) (func(), error) {
604 release, err := claimRoots(c)
605 if err != nil {
606 return nil, err
607 }
608 if err = sweepOrphans(c); err != nil {
609 release()
610 return nil, err
611 }
612 return release, nil
613}
614
615// claimRoots takes exclusive ownership of the scratch and workspace roots
616// for this state directory: an owner record naming it, and a lock held for
617// the life of the process.
618func claimRoots(c runner.Config) (func(), error) {
619 var locks []*os.File
620 release := func() {
621 for _, f := range locks {
622 f.Close()
623 }
624 }
625 for _, root := range []string{c.ScratchRoot, c.WorkspaceRoot} {
626 if err := os.MkdirAll(root, 0700); err != nil {
627 release()
628 return nil, err
629 }
630 f, err := os.OpenFile(filepath.Join(root, ownerFile+".lock"), os.O_CREATE|os.O_RDWR, 0600)
631 if err != nil {
632 release()
633 return nil, err
634 }
635 locks = append(locks, f)
636 if unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB) != nil {
637 release()
638 return nil, ErrRootShared
639 }
640 owner := filepath.Join(root, ownerFile)
641 raw, err := os.ReadFile(owner)
642 switch {
643 case errors.Is(err, os.ErrNotExist):
644 err = os.WriteFile(owner, []byte(c.StateDir+"\n"), 0600)
645 case err == nil && strings.TrimSpace(string(raw)) != c.StateDir:
646 err = ErrRootShared
647 }
648 if err != nil {
649 release()
650 return nil, err
651 }
652 }
653 return release, nil
654}
655
656// sweepOrphans removes what coordinator processes create, by owner prefix,
657// without following links.
658func sweepOrphans(c runner.Config) error {
659 for dir, prefixes := range map[string][]string{
660 filepath.Join(c.ScratchRoot, "homes"): {"account-", "config-"},
661 c.ScratchRoot: {"policy-"},
662 c.WorkspaceRoot: {"converse-", "step-"},
663 c.StateDir: {"coord-tool-"},
664 macToolRoot(c): {macToolDirPrefix},
665 } {
666 entries, err := os.ReadDir(dir)
667 if errors.Is(err, os.ErrNotExist) {
668 continue
669 }
670 if err != nil {
671 return err
672 }
673 for _, e := range entries {
674 for _, prefix := range prefixes {
675 if strings.HasPrefix(e.Name(), prefix) && e.Type().IsDir() {
676 if err := os.RemoveAll(filepath.Join(dir, e.Name())); err != nil {
677 return err
678 }
679 }
680 }
681 }
682 }
683 return nil
684}
685
686// verifiedExit reports whether a namespace's exit is verified: its record
687// is gone (released only after proof) or is released now with its proof.
688func verifiedExit(ctx context.Context, m *containment.Manager, id string) bool {
689 records, err := m.Records(ctx)
690 if err != nil {
691 return false
692 }
693 if _, unrecorded := unrecordedKey(id); id == "" || unrecorded {
694 // No namespace recorded for the attempt: verified only when none
695 // of this runner's namespaces remains.
696 return len(records) == 0
697 }
698 for _, r := range records {
699 if r.ID == id {
700 return m.Forget(ctx, r) == nil
701 }
702 }
703 return true
704}
705
706// enrolledRole is the role the runner was enrolled with: kept at
707// enrolment, or named by its credential; "" when it predates roles.
708func enrolledRole(c runner.Config, credential string) string {
709 if role := runner.ReadRole(c.StateDir); role != "" {
710 return role
711 }
712 if credential == wire.RoleWorker {
713 return wire.RoleWorker
714 }
715 return ""
716}
717
718// ErrNotTestBuild refuses EQUIPO_FAKE_PLATFORM outside the test build:
719// no release binary runs the unsandboxed fake worker.
720var ErrNotTestBuild = errors.New("EQUIPO_FAKE_PLATFORM: this runner is not a test build")
721
722// workerSetup is what differs between workers: the capability report,
723// the gate, how a gate is found in a tree, what must be ready before
724// judging, and what runs once the worker holds its roots.
725type workerSetup struct {
726 probe func(context.Context) wire.Capabilities
727 gate GateRunner
728 find func(dir string) (gate, string, bool)
729 ready func(context.Context) error
730 // started runs after startup with a function that refreshes the
731 // capability report; welcomed sees each welcome.
732 started func(ctx context.Context, refresh func())
733 welcomed func(wire.Welcome, *Worker, context.CancelCauseFunc)
734 // creds is a Mac's credential operations (maccreds.go): with them the
735 // worker holds Claude connections of its own (nil: none).
736 creds *macCreds
737 // engineering is a Mac's Engineering pieces (with creds; runWorker
738 // adds what needs the runner's state: its status, secrets, scanner).
739 engineering *WorkerEngineering
740 // fprobes are a Mac's F probes, bound to the worker once it has its
741 // Engineering pieces and connections.
742 fprobes *macEngineering
743}
744
745// workerRecord is the process record Verify settles: an attempt that
746// recorded no group is settled by its marker alone. An empty record is
747// never an ended attempt.
748func workerRecord(id string) string {
749 if key, ok := unrecordedKey(id); ok {
750 return mac.RecordID(0, attemptMarker(key))
751 }
752 return id
753}
754
755// attemptMarker is the EQUIPO_ATTEMPT value of a worker's attempt.
756func attemptMarker(key string) string {
757 sum := sha256.Sum256([]byte(key))
758 return "checks/" + hex.EncodeToString(sum[:8])
759}
760
761// ErrUpdated ends a worker that replaced its binary with the instance's
762// release: the service manager starts the new one.
763var ErrUpdated = errors.New("runner updated to the instance's release")
764
765// runWorker serves the instance as a worker: it runs the steps placed on
766// it and nothing else (no coordinator, no clone, no forge credential).
767func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Platform, w workerSetup) error {
768 release, err := startup(ctx, c, o.Logger, func(context.Context) error { return nil })
769 if err != nil {
770 return err
771 }
772 defer release()
773 creds, state, err := openRunner(ctx, c, o.Logger)
774 if err != nil {
775 return err
776 }
777 defer state.Close()
778 ctx, cancel := context.WithCancelCause(ctx)
779 defer cancel(nil)
780 caps := &Capabilities{Probe: w.probe, Logger: o.Logger}
781 link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: true, Role: enrolledRole(c, creds.Bearer.Role)}
782 // A Mac's own Claude connections (slice F task 11): said in hello
783 // only once the welcome says 37.
784 var own *workerConns
785 if w.creds != nil {
786 // A connection that changes can change the Engineering status: the
787 // report is gathered again, and the probes look.
788 own = openWorkerConns(c, o, state, creds.Bearer, w.creds, link.Notify, func() {
789 caps.Stale()
790 link.HelloSoon()
791 if w.fprobes != nil {
792 w.fprobes.soon()
793 }
794 })
795 }
796 link.Hello = func() wire.Hello {
797 report := caps.Get(ctx)
798 h := wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": o.Version}, Platform: &platform, Label: c.MachineLabel, Sandbox: w.gate.Sandbox(), Capabilities: &report}
799 spoken, _ := link.Spoken()
800 if own != nil {
801 own.hello(spoken, &h)
802 }
803 if spoken < wire.ProtocolMacEngineering {
804 // Before a welcome says 37 (and below it) none of slice F's
805 // report either: an older instance refuses a hello it cannot
806 // read, and a worker it refuses takes it for protocol 1 and
807 // stops (M9g). The welcome at 37 asks for the whole report.
808 wire.WithoutMacEngineering(&h)
809 }
810 return h
811 }
812 // Its owners include the person it is enrolled for, as on the primary:
813 // before their first connection here they have no binding.
814 engineer := &Engineer{O: o.Claude, Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Host: c.MachineLabel, Note: o.StepNote, Retention: o.KeptRetention,
815 Spoken: func() int { p, _ := link.Spoken(); return p }, Delta: link.Delta, Activity: link.Activity}
816 engineer.O.Runner, engineer.O.State, engineer.O.Logger = c, state, o.Logger
817 if own != nil {
818 // Engineering on a Mac picks among the worker's own connections.
819 engineer.O = own.claude
820 engineer.Conns, engineer.Healthy = own.conns, own.conns.Usable
821 }
822 if engineer.O.SessionRoot == "" {
823 engineer.O.SessionRoot = SessionRoot(c)
824 }
825 worker := &Worker{State: state, Engine: engineer, Gate: w.gate, MaxStep: o.MaxStep, StepRoot: filepath.Join(c.ScratchRoot, "worker-steps"), Find: w.find, Ready: w.ready}
826 if w.engineering != nil && w.creds != nil && own != nil {
827 eng := *w.engineering
828 eng.Creds = w.creds
829 if eng.Leaks == nil {
830 eng.Leaks = engineer.workerLeaks
831 }
832 // The status the capability report says now: until every part of
833 // it is ready (task 14 composes it), no Engineering runs here.
834 eng.Status = func(ctx context.Context) *wire.EngineeringStatus { return caps.Get(ctx).Engineering }
835 if w.fprobes != nil {
836 // A Mac decides afresh at each use: the inputs now, the
837 // results' age now (never the hour-old report).
838 eng.Status = w.fprobes.statusNow
839 }
840 eng.Secrets = func(context.Context) ([]string, error) { return workerSecrets(c, creds.Bearer.Token) }
841 worker.Eng = &eng
842 if w.fprobes != nil {
843 w.fprobes.bind(worker, own.conns, caps.Get)
844 }
845 }
846 // The worker's relay answers the instance's send_pack for its
847 // committed candidates, from its store; forget_task releases them.
848 relay := &Relay{State: state, Engine: engineer, Worker: worker, Notify: link.Notify, Logger: o.Logger}
849 link.Relay = relay
850 link.Forget = func(dirs []string) { worker.forget(context.WithoutCancel(ctx), dirs) }
851 link.Welcomed = func(welcome wire.Welcome) {
852 if w.welcomed != nil {
853 w.welcomed(welcome, worker, cancel)
854 }
855 if own != nil {
856 // The first hello said no connections and none of slice F's
857 // report: the next says them.
858 link.HelloSoon()
859 }
860 }
861 if own != nil {
862 if err := own.start(ctx); err != nil {
863 return err
864 }
865 link.Connector = own.connector
866 go own.claude.readProfilesAtStart(ctx, own.conns, link.HelloSoon)
867 go own.conns.Loop(ctx)
868 }
869 if w.started != nil {
870 w.started(ctx, func() { caps.Stale(); link.HelloSoon() })
871 }
872 tags := func() []string { return caps.Get(ctx).Tags }
873 // Questions about the Engineering it ran are answered here, from the
874 // sessions it kept (worker_ask.go).
875 steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, worker.Exec), Ask: worker.ask, Notify: link.Notify, Logger: o.Logger,
876 Sweep: worker.sweep,
877 Verify: func(_ context.Context, id string) bool { return w.gate.Verify(workerRecord(id)) }, TerminationKind: wire.TerminationProcessGroup,
878 Acknowledge: func(_ context.Context, id string) { acknowledge(w.gate, workerRecord(id)) }}
879 link.Steps = steps
880 if err := steps.Start(ctx); err != nil {
881 return err
882 }
883 go relay.Loop(ctx)
884 err = link.Run(ctx)
885 updated := errors.Is(context.Cause(ctx), ErrUpdated)
886 cancel(nil)
887 steps.Wait()
888 if updated {
889 return ErrUpdated
890 }
891 if errors.Is(err, ErrSuperseded) {
892 _ = state.Supersede(context.Background())
893 return err
894 }
895 if ctx.Err() != nil && !errors.Is(err, ErrRevoked) {
896 return nil
897 }
898 return err
899}
900
901// piOptions is the runner's Pi: the install at EQUIPO_PI_ROOT, held to
902// this platform's committed pins unless a test pins its fake's.
903func piOptions(c runner.Config, test PiOptions) PiOptions {
904 if test.Install.Node != "" {
905 return test
906 }
907 if c.PiRoot == "" {
908 return PiOptions{}
909 }
910 node, tree := pi.Paths(c.PiRoot)
911 return PiOptions{Install: pi.Install{Node: node, Tree: tree}}
912}
913