| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "slices" |
| 6 | |
| 7 | "amadan.net/oficina/equipo/internal/wire" |
| 8 | "gorm.io/gorm" |
| 9 | ) |
| 10 | |
| 11 | // A Mac worker's own Claude connections (Mac runners spec §8.5; slice F |
| 12 | // task 11). A connection row names its runner, and every operation on it |
| 13 | // goes there: start, the sealed secret, cancel, sign out, check, and the |
| 14 | // preference to each runner holding one. Local ids repeat across |
| 15 | // runners, so a row is matched by (runner, local id), never by the local |
| 16 | // id alone. A worker's hello records that worker's connections only, and |
| 17 | // only from protocol 37 (wire.WithoutWorkerConnections). |
| 18 | // |
| 19 | // The credential hold (D1, spec §8.3 (4)): from the moment a connection |
| 20 | // on a Mac starts connecting, the instance holds that Mac as having a |
| 21 | // model credential (runners.credential_held_at), and lets go only once |
| 22 | // the Mac's own hello says nothing of one is left: no connection, no |
| 23 | // files, no Keychain item, no launch it could not prove ended, and |
| 24 | // nothing the Mac has not been told yet. Task 15 reads it (the D1 |
| 25 | // predicate) through macCredentialHeld. |
| 26 | |
| 27 | // ConnectionMachine is one of the person's runners as the Connections |
| 28 | // page groups connections by: its id, name, role and platform (OS), the |
| 29 | // protocol it speaks, whether it is online, being removed or tainted, |
| 30 | // and the seal key it published. |
| 31 | type ConnectionMachine struct { |
| 32 | ID, Label, Role, Platform string |
| 33 | Protocol int |
| 34 | Online, Removing, Tainted bool |
| 35 | SealKey string |
| 36 | } |
| 37 | |
| 38 | // TakesClaude: Claude can be added to m. Only a Mac worker that speaks |
| 39 | // ProtocolMacEngineering and published a seal key, and is neither being |
| 40 | // removed nor tainted (D2: a tainted runner takes no model connection). |
| 41 | // The main runner adds its own as it always has. |
| 42 | func TakesClaude(m ConnectionMachine) bool { |
| 43 | return m.Role == wire.RoleWorker && m.Platform == "darwin" && m.Protocol >= wire.ProtocolMacEngineering && m.SealKey != "" && !m.Removing && !m.Tainted |
| 44 | } |
| 45 | |
| 46 | // machineOf is r as a ConnectionMachine. |
| 47 | func machineOf(r runnerInfo) ConnectionMachine { |
| 48 | m := ConnectionMachine{ID: r.ID, Label: r.Label, Role: r.Role, Protocol: r.Protocol, Online: r.Online, Removing: r.Removing, Tainted: r.Tainted, SealKey: r.Hello.SealKey} |
| 49 | if r.Hello.Platform != nil { |
| 50 | m.Platform = r.Hello.Platform.OS |
| 51 | } |
| 52 | return m |
| 53 | } |
| 54 | |
| 55 | // UsageKey is how UsageToday and RowFacts name a connection's usage: its |
| 56 | // local id on the main runner (and for rows that predate the runner's |
| 57 | // id), its runner and local id on any other. |
| 58 | func UsageKey(primary, runner, local string) string { |
| 59 | if runner == "" || runner == primary { |
| 60 | return local |
| 61 | } |
| 62 | return runner + "/" + local |
| 63 | } |
| 64 | |
| 65 | // ConnectionMachines are the person's runners, the main runner first. |
| 66 | func (s *Store) ConnectionMachines(ctx context.Context, person string) (out []ConnectionMachine, err error) { |
| 67 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 68 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 69 | return err |
| 70 | } |
| 71 | t := &txn{s: s, db: tx} |
| 72 | primary, err := s.authority.PrimaryRunner(tx, person) |
| 73 | if err != nil { |
| 74 | return err |
| 75 | } |
| 76 | rs, err := t.runners(person) |
| 77 | if err != nil { |
| 78 | return err |
| 79 | } |
| 80 | for _, r := range rs { |
| 81 | out = append(out, machineOf(r)) |
| 82 | } |
| 83 | slices.SortStableFunc(out, func(a, b ConnectionMachine) int { |
| 84 | switch { |
| 85 | case a.ID == primary && b.ID != primary: |
| 86 | return -1 |
| 87 | case b.ID == primary && a.ID != primary: |
| 88 | return 1 |
| 89 | } |
| 90 | return 0 |
| 91 | }) |
| 92 | return nil |
| 93 | }) |
| 94 | return out, err |
| 95 | } |
| 96 | |
| 97 | // connectionMachine is the person's runner id as a ConnectionMachine |
| 98 | // (found false when it is none of theirs). |
| 99 | func (t *txn) connectionMachine(person, id string) (ConnectionMachine, bool, error) { |
| 100 | rs, err := t.runners(person) |
| 101 | if err != nil { |
| 102 | return ConnectionMachine{}, false, err |
| 103 | } |
| 104 | for _, r := range rs { |
| 105 | if r.ID == id { |
| 106 | return machineOf(r), true, nil |
| 107 | } |
| 108 | } |
| 109 | return ConnectionMachine{}, false, nil |
| 110 | } |
| 111 | |
| 112 | // connectionRunner is where a row's commands go: its runner, or the |
| 113 | // main runner for a row that names none. |
| 114 | func (t *txn) connectionRunner(r connectionRecord) (string, error) { |
| 115 | if r.RunnerID != "" { |
| 116 | return r.RunnerID, nil |
| 117 | } |
| 118 | return t.s.authority.PrimaryRunner(t.db, r.Person) |
| 119 | } |
| 120 | |
| 121 | // MacCredentialHeld reports whether the instance holds a runner as |
| 122 | // having a model credential. A lookup error is an error, never "no". |
| 123 | func (s *Store) MacCredentialHeld(ctx context.Context, runner string) (held bool, err error) { |
| 124 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 125 | held, err = (&txn{s: s, db: tx}).macCredentialHeld(runner) |
| 126 | return err |
| 127 | }) |
| 128 | return held, err |
| 129 | } |
| 130 | |
| 131 | // macCredentialHeld is the instance's credential hold on runner (task |
| 132 | // 15's unsandboxedAllowed reads it in its transaction). |
| 133 | func (t *txn) macCredentialHeld(runner string) (bool, error) { |
| 134 | var n int64 |
| 135 | err := t.db.Raw(`SELECT count(*) FROM runners WHERE id = ? AND credential_held_at IS NOT NULL`, runner).Scan(&n).Error |
| 136 | return n > 0, err |
| 137 | } |
| 138 | |
| 139 | // holdCredential sets the hold on runner, from now, if it is not set. |
| 140 | // Setting it withdraws any choice to run checks there outside the |
| 141 | // sandbox that a waiting attempt carries (D1, withdrawUnsandboxed). |
| 142 | func (t *txn) holdCredential(runner string) error { |
| 143 | res := t.db.Exec(`UPDATE runners SET credential_held_at = ? WHERE id = ? AND credential_held_at IS NULL`, t.now(), runner) |
| 144 | if res.Error != nil || res.RowsAffected == 0 { |
| 145 | return res.Error |
| 146 | } |
| 147 | return t.withdrawUnsandboxed(runner) |
| 148 | } |
| 149 | |
| 150 | // helloHold applies a worker's hello (protocol 37) to its credential |
| 151 | // hold. Anything of a credential it reports holds. Only the Mac's |
| 152 | // complete report (the inventory mark, after the welcome, with a valid |
| 153 | // capability report) may release it, and only when the instance has no |
| 154 | // attempt connecting there and no connect or secret frame the Mac has |
| 155 | // not taken. Any other hello changes nothing. |
| 156 | func (t *txn) helloHold(l Lease, h wire.Hello, handshake bool) error { |
| 157 | runner := l.Runner.RunnerID |
| 158 | c := cleanHello(h).Capabilities |
| 159 | if c != nil && (c.ModelHold || len(c.HoldingItems) > 0 || c.Unproven == wire.UnprovenCredential) || len(h.Connections) > 0 { |
| 160 | return t.holdCredential(runner) |
| 161 | } |
| 162 | if handshake || !h.Inventory || c == nil { |
| 163 | // Not the Mac's complete word: it changes nothing. |
| 164 | return nil |
| 165 | } |
| 166 | var connecting, untaken int64 |
| 167 | if err := t.db.Model(&connectionRecord{}).Where("runner_id = ? AND state = ?", runner, wire.ConnConnecting).Count(&connecting).Error; err != nil { |
| 168 | return err |
| 169 | } |
| 170 | if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind IN ? AND acked_at IS NULL", runner, []string{wire.FrameConnect, wire.FrameSecret}).Count(&untaken).Error; err != nil { |
| 171 | return err |
| 172 | } |
| 173 | if connecting+untaken > 0 { |
| 174 | return t.holdCredential(runner) |
| 175 | } |
| 176 | return t.db.Exec(`UPDATE runners SET credential_held_at = NULL WHERE id = ?`, runner).Error |
| 177 | } |
| 178 | |
| 179 | // workerHello records what a worker's hello says of its connections: |
| 180 | // below ProtocolMacEngineering nothing (its hello was read without them); |
| 181 | // from it, that worker's connections and its credential hold. Only the |
| 182 | // complete report (the inventory mark, after the welcome) signs a |
| 183 | // connection out or releases the hold: the hello before the welcome |
| 184 | // (handshake) never does, whatever it says. |
| 185 | func (t *txn) workerHello(l Lease, h wire.Hello, handshake bool) error { |
| 186 | if l.Role != wire.RoleWorker || l.Protocol < wire.ProtocolMacEngineering { |
| 187 | return nil |
| 188 | } |
| 189 | // Complete only when marked, after the welcome, and with a capability |
| 190 | // report the instance accepts: one with none, or one cleanHello |
| 191 | // drops, is not the Mac's whole word. |
| 192 | complete := h.Inventory && !handshake && cleanHello(h).Capabilities != nil |
| 193 | if err := t.helloConnections(l, h.Connections, complete); err != nil { |
| 194 | return err |
| 195 | } |
| 196 | return t.helloHold(l, h, handshake) |
| 197 | } |
| 198 | |
| 199 | // preferenceRunners are the runners a preference goes to: the main |
| 200 | // runner, and every other runner holding one of the person's |
| 201 | // connections (not signed out). |
| 202 | func (t *txn) preferenceRunners(person string) ([]string, error) { |
| 203 | primary, err := t.s.authority.PrimaryRunner(t.db, person) |
| 204 | if err != nil { |
| 205 | return nil, err |
| 206 | } |
| 207 | var others []string |
| 208 | if err := t.db.Model(&connectionRecord{}).Where("person = ? AND runner_id <> ? AND runner_id <> '' AND state <> ?", person, primary, wire.ConnSignedOut).Distinct("runner_id").Order("runner_id").Pluck("runner_id", &others).Error; err != nil { |
| 209 | return nil, err |
| 210 | } |
| 211 | return append([]string{primary}, others...), nil |
| 212 | } |
| 213 | |