package thin import ( "context" "errors" "io/fs" "os" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" ) // A Mac worker's own Claude connections (Mac runners spec §8.5; slice F // task 11). The worker opens Conns over its own accounts root (the one // its home guard checks), seals to its own enrolment key, and says its // connections and seal key in hello only once the welcome says 37. Only // Claude token connections live on a Mac, pasted or made by its own // sign-in (maccreds.go); every store and use passes the Mac's guards. // // The credential hold (D1): from the moment an attempt starts until its // files are gone and the Keychain is clean, the Mac counts as holding a // model credential. Every source of it is on disk (the attempt rows, the // bindings, the accounts root, the Keychain records), so it holds across // a restart; one that cannot be read holds. // workerConns is a Mac worker's own Claude connections. type workerConns struct { conns *Conns connector *Connector // claude is the worker's Claude options: the Mac's check, auth // status and guards. claude ClaudeOptions sealKey string mac *macCreds } // openWorkerConns opens a Mac worker's connections over state, for the // runner bearer names, with m its credential operations. notify sends // what is queued; changed asks for a hello soon. func openWorkerConns(c runner.Config, o Options, state *State, bearer runnerproto.RunnerCredential, m *macCreds, notify, changed func()) *workerConns { w := &workerConns{mac: m, claude: o.Claude} if p := w.claude.Profile; p != nil && p.Version == "" { named := *p named.Version = o.Version w.claude.Profile = &named } // On a Mac the CLI's auth status is the darwin one, token by // descriptor, in its turn and behind the guards: never Linux's, which // puts the token in an environment outside any turn. w.claude.Runner, w.claude.State, w.claude.Logger, w.claude.Mac, w.claude.Refresh = c, state, o.Logger, m, m.authStatus // The Mac's turn before the home's lock, as every step and check takes // them: the refresh's auth status needs the turn (CI fix, wave 3). conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: m.authStatus, LockWait: w.claude.LockWait, Changed: changed, Turn: m.checkTurn} conns.Verify = func(ctx context.Context, b runner.AccountBinding) error { res, err := w.claude.CheckToken(ctx, b) if res.Seen != nil && !errors.Is(err, provider.ErrLoginRequired) { if res.Seen.Limited { conns.Limit(b.ID, *res.Seen) } else { conns.Observe(b.ID, *res.Seen, "") } } if rerr := state.ReportCheck(context.Background(), res.Rows); rerr != nil && o.Logger != nil { o.Logger.Warn("token check usage", "err", sanitize(rerr)) } if changed != nil { changed() } return err } w.conns = conns // The Mac's checks read this hold before any runs outside the // sandbox (macChecks.unsandboxedAllowed, D1). m.held = w.held w.connector = &Connector{Runner: c, State: state, Conns: conns, Root: m.paths.AccountsRoot, Owners: withPerson(coordinatorPersons(c)(), bearer.Person), Notify: notify, Logger: o.Logger, Limit: o.ConnectLimit, RunnerID: bearer.RunnerID, Mac: m} if key, err := runner.ReadMachineKey(c.StateDir); err == nil { if keys, err := sealbox.FromEd25519(key); err == nil { w.connector.Seal, w.sealKey = &keys, keys.PublicString() } clear(key) } else if o.Logger != nil { o.Logger.Warn("no seal key: Claude cannot be added to this Mac", "err", sanitize(err)) } return w } // start recovers what a previous process left (connector.go's Start: // attempts, owed sign-outs, the Keychain watches). func (w *workerConns) start(ctx context.Context) error { return w.connector.Start(ctx) } // hello puts the worker's connections, seal key and credential hold in // h, only at ProtocolMacEngineering: below it (and before any welcome, // spoken 0) a worker says none. func (w *workerConns) hello(spoken int, h *wire.Hello) { if spoken < wire.ProtocolMacEngineering { return } // After the welcome, and only then, this is the whole inventory: the // instance may release a hold on it. h.Connections, h.SealKey, h.Inventory = w.conns.Held(), w.sealKey, true if h.Capabilities == nil { return } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := *h.Capabilities c.ModelHold = w.held(ctx) if items := w.mac.keychain.Residue(); len(items) > 0 { c.ModelHold, c.HoldingItems = true, items[:min(len(items), wire.MaxHoldingItems)] } h.Capabilities = &c } // held is the worker's credential hold now. func (w *workerConns) held(ctx context.Context) bool { return w.connector.credentialHeld(ctx) } // credentialHeld: this runner holds, or may hold, a model credential: an // attempt running or a sign-out owed, a binding, anything in the // accounts root, or (on a Mac) a Keychain record (an item left, or a // launch not yet proven ended). A source that cannot be read holds. func (c *Connector) credentialHeld(ctx context.Context) bool { var n int if err := c.State.db.QueryRowContext(ctx, "SELECT (SELECT count(*) FROM connect_attempts WHERE state='running') + (SELECT count(*) FROM connect_cleanups)").Scan(&n); err != nil || n > 0 { return true } if bs, err := runner.LoadBindings(c.Runner.AccountBindingsPath); err != nil || len(bs) > 0 { return true } if entries, err := os.ReadDir(c.Root); err != nil && !errors.Is(err, fs.ErrNotExist) || len(entries) > 0 { return true } if c.Mac != nil { if c.Mac.Held() { return true } if left, err := c.Mac.keychain.Unproven(); err != nil || len(left) > 0 { return true } } return false } // macTakes: a Mac keeps only Claude, by a pasted token or its own // sign-in (Mac runners spec §8.5: Codex is slice G, metered and endpoint // connections stay on the primary). func macTakes(cmd wire.ConnectCommand) bool { return cmd.Provider == wire.ProviderClaude && (cmd.Kind == wire.KindToken || cmd.Kind == wire.KindSubscription || cmd.Kind == "") }