| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "log/slog" |
| 7 | "net/http" |
| 8 | "strings" |
| 9 | "sync" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/equipo/assist" |
| 13 | "amadan.net/oficina/equipo/internal/equipo/chat" |
| 14 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 15 | "amadan.net/oficina/equipo/internal/equipo/push" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | "gorm.io/gorm" |
| 18 | ) |
| 19 | |
| 20 | // thinChat holds the thin v1 conversation core for one Store. |
| 21 | type thinChat struct { |
| 22 | once sync.Once |
| 23 | store *chat.Store |
| 24 | } |
| 25 | |
| 26 | // Chat returns the thin v1 conversation store. |
| 27 | func (s *Store) Chat() *chat.Store { |
| 28 | s.chat.once.Do(func() { |
| 29 | s.chat.store = chat.NewStore(s.db, chat.Authority{ |
| 30 | CurrentPerson: s.chatCurrentPerson, |
| 31 | Me: chatMe, |
| 32 | PrimaryRunner: func(tx *gorm.DB, person string) (string, error) { |
| 33 | if !s.chatExecution { |
| 34 | return "", nil |
| 35 | } |
| 36 | return primaryRunner(tx, person) |
| 37 | }, |
| 38 | CurrentRunner: func(tx *gorm.DB, p chat.RunnerPrincipal) error { |
| 39 | _, err := runnerPrincipalAt(tx, RunnerPrincipal{RunnerID: p.RunnerID, Person: p.Person, CredentialID: p.CredentialID}, time.Now()) |
| 40 | return err |
| 41 | }, |
| 42 | RunnerRole: runnerRole, |
| 43 | FinishRemoval: func(tx *gorm.DB, id string) error { |
| 44 | return revokeRunnerAt(tx, id, s.runnerClock.Now().UTC()) |
| 45 | }, |
| 46 | Audit: func(tx *gorm.DB, actor, kind, record string) error { |
| 47 | return appendAudit(tx, Actor{Address: actor}, kind, record) |
| 48 | }, |
| 49 | // A push goes only to a device credential still valid now; only |
| 50 | // a revoked one (or its person signed out everywhere) is gone. |
| 51 | PushDevice: func(tx *gorm.DB, person, credential string) error { |
| 52 | state, err := s.personDevices().PushState(tx, credential, person) |
| 53 | switch { |
| 54 | case err != nil: |
| 55 | return err |
| 56 | case state == personapi.PushGone: |
| 57 | return push.ErrGone |
| 58 | case state != personapi.PushCurrent: |
| 59 | return push.ErrNotCurrent |
| 60 | } |
| 61 | return nil |
| 62 | }, |
| 63 | ActivityLabel: activityLabel, |
| 64 | Copy: copyText, |
| 65 | Origin: s.chatOrigin, |
| 66 | AssistantHosts: lowered(s.chatAssistantHosts), |
| 67 | // Host tokens are sealed as device results are, with the |
| 68 | // instance key (read when used: it is set after the store). |
| 69 | Seal: func(domain string, v any) (string, error) { return s.personDevices().Seal(domain, v) }, |
| 70 | Open: func(domain, sealed string, v any) error { return s.personDevices().Open(domain, sealed, v) }, |
| 71 | TestPerson: func(address string) bool { |
| 72 | address = strings.ToLower(address) |
| 73 | for _, suffix := range s.chatTestPeople { |
| 74 | if strings.HasSuffix(address, suffix) { |
| 75 | return true |
| 76 | } |
| 77 | } |
| 78 | return false |
| 79 | }, |
| 80 | }, nil) |
| 81 | s.chat.store.SetOperations(s.assistRegistry(slog.Default())) |
| 82 | }) |
| 83 | return s.chat.store |
| 84 | } |
| 85 | |
| 86 | // assistRegistry is the Assistant's operations: Base's, at the host each |
| 87 | // person registered, then the team's (the hand-off), then, with |
| 88 | // oficina-connect configured, the Oficina apps. A look for something |
| 89 | // they do by a person not connected raises the connect card. |
| 90 | func (s *Store) assistRegistry(logger *slog.Logger) *assist.Registry { |
| 91 | c := s.chat.store |
| 92 | providers := []assist.Provider{assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider(), c.WebProvider()} |
| 93 | if s.oficina != nil { |
| 94 | s.oficina.SetAllowed(c.AllowedFor(wire.AbilityAppsRead)) |
| 95 | providers = append(providers, assist.NewOficinaProvider(oficinaProvider, s.oficina, nil, c.AllowedFor(wire.AbilityAppsRead))) |
| 96 | } |
| 97 | r := assist.NewRegistry(providers...) |
| 98 | r.OnUnconnected(func(ctx context.Context, person, provider string) bool { |
| 99 | if provider != oficinaProvider { |
| 100 | return false |
| 101 | } |
| 102 | // No connect card for a person who may not read their apps. |
| 103 | if err := c.Allowed(ctx, person, wire.AbilityAppsRead); err != nil { |
| 104 | return false |
| 105 | } |
| 106 | open, err := c.RaiseConnect(ctx, person, chat.ConnectCard{Provider: oficinaProvider, Question: copyText("assistant.connect.oficina"), Link: s.oficinaLink(ctx, person)}) |
| 107 | if err != nil { |
| 108 | logger.Warn(copyOficinaCardFailed, "err", err) |
| 109 | } |
| 110 | return open |
| 111 | }) |
| 112 | s.assist = r |
| 113 | return r |
| 114 | } |
| 115 | |
| 116 | func lowered(in []string) []string { |
| 117 | out := make([]string, 0, len(in)) |
| 118 | for _, v := range in { |
| 119 | out = append(out, strings.ToLower(strings.TrimSpace(v))) |
| 120 | } |
| 121 | return out |
| 122 | } |
| 123 | |
| 124 | // DrainStreams ends every person stream and tells runners to reconnect, |
| 125 | // for a process that received SIGTERM. |
| 126 | func (s *Store) DrainStreams() { s.Chat().Hub().Drain() } |
| 127 | |
| 128 | func (s *Store) chatCurrentPerson(ctx context.Context, tx *gorm.DB) error { |
| 129 | if id, ok := ctx.Value(agentIdentityKey{}).(agentIdentity); ok { |
| 130 | if err := id.current(ctx, tx); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | } |
| 134 | p, ok := personapi.PrincipalFrom(ctx) |
| 135 | if !ok || p.Address == "" { |
| 136 | return ErrForbidden |
| 137 | } |
| 138 | return s.currentPersonAPI(tx, ctx) |
| 139 | } |
| 140 | |
| 141 | func chatMe(tx *gorm.DB, address string) (wire.Me, error) { |
| 142 | m, err := currentRunnerMember(tx, address) |
| 143 | if err != nil { |
| 144 | return wire.Me{}, err |
| 145 | } |
| 146 | var t Team |
| 147 | if err = tx.First(&t).Error; err != nil { |
| 148 | return wire.Me{}, storeError(err) |
| 149 | } |
| 150 | role := string(m.Role) |
| 151 | return wire.Me{ID: m.Address, Address: m.Address, Role: role, Person: wire.Person{Address: m.Address, DisplayIdentity: m.Address, Active: m.Active, Role: role}, TeamID: t.ID, TeamName: t.Name, Revision: m.Revision}, nil |
| 152 | } |
| 153 | |
| 154 | // primaryRunner is the person's newest unrevoked primary runner, and only |
| 155 | // for an active owner: teammate execution stays denied in v1. Workers |
| 156 | // never serve the coordinator. A row from before roles (no role) counts as |
| 157 | // a primary, as migration 0054 marked them all. |
| 158 | func primaryRunner(tx *gorm.DB, person string) (string, error) { |
| 159 | var ids []string |
| 160 | err := tx.Raw(`SELECT r.id FROM runners r JOIN members m ON m.address = r.person |
| 161 | WHERE r.person = ? AND r.revoked_at IS NULL AND m.active = 1 AND m.role = ? |
| 162 | AND coalesce(r.role, '') IN ('primary', '') AND r.removing_at IS NULL |
| 163 | ORDER BY r.rowid DESC LIMIT 1`, normalizeAddress(person), string(RoleOwner)).Scan(&ids).Error |
| 164 | if err != nil { |
| 165 | return "", storeError(err) |
| 166 | } |
| 167 | if len(ids) == 0 { |
| 168 | return "", nil |
| 169 | } |
| 170 | return ids[0], nil |
| 171 | } |
| 172 | |
| 173 | // runnerRole is the runner's enrolled role; a row from before roles is a |
| 174 | // primary. |
| 175 | func runnerRole(tx *gorm.DB, id string) (string, error) { |
| 176 | var roles []string |
| 177 | if err := tx.Raw(`SELECT coalesce(role, '') FROM runners WHERE id = ?`, id).Scan(&roles).Error; err != nil { |
| 178 | return "", storeError(err) |
| 179 | } |
| 180 | if len(roles) == 1 && roles[0] == wire.RoleWorker { |
| 181 | return wire.RoleWorker, nil |
| 182 | } |
| 183 | return wire.RolePrimary, nil |
| 184 | } |
| 185 | |
| 186 | func (s *Store) chatHTTP(authenticate func(*http.Request) (personapi.PersonPrincipal, error), failure func(http.ResponseWriter, *http.Request, error)) *chat.HTTP { |
| 187 | h := &chat.HTTP{Store: s.Chat(), Authenticate: authenticate, Failure: failure, AuthenticateRunner: func(ctx context.Context, token string) (chat.RunnerPrincipal, error) { |
| 188 | p, err := s.AuthenticateRunner(ctx, token) |
| 189 | if err != nil { |
| 190 | return chat.RunnerPrincipal{}, err |
| 191 | } |
| 192 | return chat.RunnerPrincipal{RunnerID: p.RunnerID, Person: p.Person, CredentialID: p.CredentialID}, nil |
| 193 | }} |
| 194 | if s.oficina != nil { |
| 195 | h.OficinaConnect, h.OficinaFinish, h.OficinaCatchUp = s.oficinaConnect, s.oficinaFinish, s.oficinaCatchUp |
| 196 | } |
| 197 | return h |
| 198 | } |
| 199 | |
| 200 | // RunnerStreamHandler is GET /api/runner/stream. Refused runner frames |
| 201 | // (a research_file chunk from a late attempt, say) are logged to logger. |
| 202 | func (s *Store) RunnerStreamHandler(logger *slog.Logger) http.Handler { |
| 203 | h := s.chatHTTP(func(*http.Request) (personapi.PersonPrincipal, error) { |
| 204 | return personapi.PersonPrincipal{}, ErrForbidden |
| 205 | }, func(w http.ResponseWriter, r *http.Request, err error) { |
| 206 | personapi.WriteError(w, r, 403, "forbidden", nil) |
| 207 | }) |
| 208 | h.Logger = logger |
| 209 | return h.RunnerStream(s.Chat().Process()) |
| 210 | } |
| 211 | |
| 212 | // activityLabel formats only server-resolved subjects and catalog names. |
| 213 | // The full label is also the tooltip and accessible text; the browser |
| 214 | // shortens long quoted subjects on the visible line. |
| 215 | func activityLabel(a wire.Activity, turnKind, subject string) string { |
| 216 | tool := a.Tool |
| 217 | if tool == wire.ToolRequestAccess { |
| 218 | return copyText("access.title") |
| 219 | } |
| 220 | if a.Kind == wire.ActivityThink { |
| 221 | tool = "thinking" |
| 222 | } |
| 223 | label := copyText("chat.activity." + tool) |
| 224 | if a.Repo != "" && copyText("chat.activity."+tool+"_repo") != "" { |
| 225 | label = fmt.Sprintf(copyText("chat.activity."+tool+"_repo"), a.Repo) |
| 226 | } |
| 227 | if subject != "" && copyText("chat.activity."+tool+"_subject") != "" { |
| 228 | label = fmt.Sprintf(copyText("chat.activity."+tool+"_subject"), subject) |
| 229 | } |
| 230 | if label == "" { |
| 231 | label = copyText("chat.activity.other") |
| 232 | } |
| 233 | if turnKind == wire.TurnMoveIn || turnKind == wire.TurnExplore { |
| 234 | step := strings.TrimSuffix(label, "…") |
| 235 | step = strings.ToLower(step[:1]) + step[1:] |
| 236 | return fmt.Sprintf(copyText("chat.activity."+turnKind), step) |
| 237 | } |
| 238 | return label |
| 239 | } |
| 240 | |