| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io/fs" |
| 7 | "os" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/runner" |
| 11 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 12 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 13 | "amadan.net/oficina/equipo/internal/sealbox" |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | ) |
| 16 | |
| 17 | // A Mac worker's own Claude connections (Mac runners spec §8.5; slice F |
| 18 | // task 11). The worker opens Conns over its own accounts root (the one |
| 19 | // its home guard checks), seals to its own enrolment key, and says its |
| 20 | // connections and seal key in hello only once the welcome says 37. Only |
| 21 | // Claude token connections live on a Mac, pasted or made by its own |
| 22 | // sign-in (maccreds.go); every store and use passes the Mac's guards. |
| 23 | // |
| 24 | // The credential hold (D1): from the moment an attempt starts until its |
| 25 | // files are gone and the Keychain is clean, the Mac counts as holding a |
| 26 | // model credential. Every source of it is on disk (the attempt rows, the |
| 27 | // bindings, the accounts root, the Keychain records), so it holds across |
| 28 | // a restart; one that cannot be read holds. |
| 29 | |
| 30 | // workerConns is a Mac worker's own Claude connections. |
| 31 | type workerConns struct { |
| 32 | conns *Conns |
| 33 | connector *Connector |
| 34 | // claude is the worker's Claude options: the Mac's check, auth |
| 35 | // status and guards. |
| 36 | claude ClaudeOptions |
| 37 | sealKey string |
| 38 | mac *macCreds |
| 39 | } |
| 40 | |
| 41 | // openWorkerConns opens a Mac worker's connections over state, for the |
| 42 | // runner bearer names, with m its credential operations. notify sends |
| 43 | // what is queued; changed asks for a hello soon. |
| 44 | func openWorkerConns(c runner.Config, o Options, state *State, bearer runnerproto.RunnerCredential, m *macCreds, notify, changed func()) *workerConns { |
| 45 | w := &workerConns{mac: m, claude: o.Claude} |
| 46 | if p := w.claude.Profile; p != nil && p.Version == "" { |
| 47 | named := *p |
| 48 | named.Version = o.Version |
| 49 | w.claude.Profile = &named |
| 50 | } |
| 51 | // On a Mac the CLI's auth status is the darwin one, token by |
| 52 | // descriptor, in its turn and behind the guards: never Linux's, which |
| 53 | // puts the token in an environment outside any turn. |
| 54 | w.claude.Runner, w.claude.State, w.claude.Logger, w.claude.Mac, w.claude.Refresh = c, state, o.Logger, m, m.authStatus |
| 55 | // The Mac's turn before the home's lock, as every step and check takes |
| 56 | // them: the refresh's auth status needs the turn (CI fix, wave 3). |
| 57 | conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: m.authStatus, LockWait: w.claude.LockWait, Changed: changed, |
| 58 | Turn: m.checkTurn} |
| 59 | conns.Verify = func(ctx context.Context, b runner.AccountBinding) error { |
| 60 | res, err := w.claude.CheckToken(ctx, b) |
| 61 | if res.Seen != nil && !errors.Is(err, provider.ErrLoginRequired) { |
| 62 | if res.Seen.Limited { |
| 63 | conns.Limit(b.ID, *res.Seen) |
| 64 | } else { |
| 65 | conns.Observe(b.ID, *res.Seen, "") |
| 66 | } |
| 67 | } |
| 68 | if rerr := state.ReportCheck(context.Background(), res.Rows); rerr != nil && o.Logger != nil { |
| 69 | o.Logger.Warn("token check usage", "err", sanitize(rerr)) |
| 70 | } |
| 71 | if changed != nil { |
| 72 | changed() |
| 73 | } |
| 74 | return err |
| 75 | } |
| 76 | w.conns = conns |
| 77 | // The Mac's checks read this hold before any runs outside the |
| 78 | // sandbox (macChecks.unsandboxedAllowed, D1). |
| 79 | m.held = w.held |
| 80 | 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} |
| 81 | if key, err := runner.ReadMachineKey(c.StateDir); err == nil { |
| 82 | if keys, err := sealbox.FromEd25519(key); err == nil { |
| 83 | w.connector.Seal, w.sealKey = &keys, keys.PublicString() |
| 84 | } |
| 85 | clear(key) |
| 86 | } else if o.Logger != nil { |
| 87 | o.Logger.Warn("no seal key: Claude cannot be added to this Mac", "err", sanitize(err)) |
| 88 | } |
| 89 | return w |
| 90 | } |
| 91 | |
| 92 | // start recovers what a previous process left (connector.go's Start: |
| 93 | // attempts, owed sign-outs, the Keychain watches). |
| 94 | func (w *workerConns) start(ctx context.Context) error { return w.connector.Start(ctx) } |
| 95 | |
| 96 | // hello puts the worker's connections, seal key and credential hold in |
| 97 | // h, only at ProtocolMacEngineering: below it (and before any welcome, |
| 98 | // spoken 0) a worker says none. |
| 99 | func (w *workerConns) hello(spoken int, h *wire.Hello) { |
| 100 | if spoken < wire.ProtocolMacEngineering { |
| 101 | return |
| 102 | } |
| 103 | // After the welcome, and only then, this is the whole inventory: the |
| 104 | // instance may release a hold on it. |
| 105 | h.Connections, h.SealKey, h.Inventory = w.conns.Held(), w.sealKey, true |
| 106 | if h.Capabilities == nil { |
| 107 | return |
| 108 | } |
| 109 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 110 | defer cancel() |
| 111 | c := *h.Capabilities |
| 112 | c.ModelHold = w.held(ctx) |
| 113 | if items := w.mac.keychain.Residue(); len(items) > 0 { |
| 114 | c.ModelHold, c.HoldingItems = true, items[:min(len(items), wire.MaxHoldingItems)] |
| 115 | } |
| 116 | h.Capabilities = &c |
| 117 | } |
| 118 | |
| 119 | // held is the worker's credential hold now. |
| 120 | func (w *workerConns) held(ctx context.Context) bool { return w.connector.credentialHeld(ctx) } |
| 121 | |
| 122 | // credentialHeld: this runner holds, or may hold, a model credential: an |
| 123 | // attempt running or a sign-out owed, a binding, anything in the |
| 124 | // accounts root, or (on a Mac) a Keychain record (an item left, or a |
| 125 | // launch not yet proven ended). A source that cannot be read holds. |
| 126 | func (c *Connector) credentialHeld(ctx context.Context) bool { |
| 127 | var n int |
| 128 | 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 { |
| 129 | return true |
| 130 | } |
| 131 | if bs, err := runner.LoadBindings(c.Runner.AccountBindingsPath); err != nil || len(bs) > 0 { |
| 132 | return true |
| 133 | } |
| 134 | if entries, err := os.ReadDir(c.Root); err != nil && !errors.Is(err, fs.ErrNotExist) || len(entries) > 0 { |
| 135 | return true |
| 136 | } |
| 137 | if c.Mac != nil { |
| 138 | if c.Mac.Held() { |
| 139 | return true |
| 140 | } |
| 141 | if left, err := c.Mac.keychain.Unproven(); err != nil || len(left) > 0 { |
| 142 | return true |
| 143 | } |
| 144 | } |
| 145 | return false |
| 146 | } |
| 147 | |
| 148 | // macTakes: a Mac keeps only Claude, by a pasted token or its own |
| 149 | // sign-in (Mac runners spec §8.5: Codex is slice G, metered and endpoint |
| 150 | // connections stay on the primary). |
| 151 | func macTakes(cmd wire.ConnectCommand) bool { |
| 152 | return cmd.Provider == wire.ProviderClaude && (cmd.Kind == wire.KindToken || cmd.Kind == wire.KindSubscription || cmd.Kind == "") |
| 153 | } |
| 154 | |