| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "slices" |
| 7 | "strings" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/wire" |
| 10 | ) |
| 11 | |
| 12 | func (t *txn) requestAccess(r turnRecord, in wire.AccessRequest) (wire.ToolResult, error) { |
| 13 | in.Target = strings.TrimPrefix(strings.TrimSpace(in.Target), "amadan.net/") |
| 14 | if in.Role == "" { |
| 15 | in.Role = "agent" |
| 16 | } |
| 17 | reason, ok := cleanText(in.Reason, 1000) |
| 18 | if !ok || !wire.ValidAccessReason(reason) || !wire.ValidAccessTarget(in.Target) || !wire.AccessRole(in.Role) || in.ApprovalOpened || in.State != "" || in.RequestID != "" || in.ApproveURL != "" || in.Expires != 0 || r.Kind != wire.TurnPerson { |
| 19 | return refused("invalid", toolBadInput), nil |
| 20 | } |
| 21 | id, err := t.s.authority.PrimaryRunner(t.db, r.Person) |
| 22 | if err != nil { |
| 23 | return wire.ToolResult{}, err |
| 24 | } |
| 25 | var runner runnerSessionRecord |
| 26 | if err := t.db.First(&runner, "runner_id = ?", id).Error; err != nil { |
| 27 | return wire.ToolResult{}, err |
| 28 | } |
| 29 | if runner.Protocol < wire.ProtocolAccess { |
| 30 | return refused("runner_too_old", toolJobsTooOld), nil |
| 31 | } |
| 32 | var messages []messageRecord |
| 33 | if err := t.db.Where("person = ? AND turn_id = ? AND role = ?", r.Person, r.ID, wire.RolePerson).Order("seq").Find(&messages).Error; err != nil { |
| 34 | return wire.ToolResult{}, err |
| 35 | } |
| 36 | if len(messages) == 0 { |
| 37 | return refused("not_asked", toolBadInput), nil |
| 38 | } |
| 39 | if !strings.Contains(in.Target, "/") { |
| 40 | targets := []string{} |
| 41 | explicit := false |
| 42 | for _, m := range messages { |
| 43 | for _, word := range strings.Fields(m.Text) { |
| 44 | word = strings.TrimPrefix(strings.Trim(word, ".,?!\"'`()[]"), "amadan.net/") |
| 45 | if strings.HasPrefix(word, in.Target+"/") && wire.ValidAccessTarget(word) && !slices.Contains(targets, word) { |
| 46 | targets = append(targets, word) |
| 47 | } |
| 48 | } |
| 49 | lower := strings.ToLower(m.Text) |
| 50 | if m.Origin == originComposer && !uncertainPlacement(lower) && (strings.Contains(lower, "whole "+strings.ToLower(in.Target)+" namespace") || strings.Contains(lower, "whole namespace "+strings.ToLower(in.Target)) || strings.Contains(lower, "entire "+strings.ToLower(in.Target)+" namespace") || strings.Contains(lower, "entire namespace "+strings.ToLower(in.Target))) { |
| 51 | explicit = true |
| 52 | } |
| 53 | } |
| 54 | if len(targets) == 1 && !explicit { |
| 55 | in.Target = targets[0] |
| 56 | } else if !explicit { |
| 57 | return refused("narrow_target", "Name the single repository. A namespace needs the person's explicit request for that namespace."), nil |
| 58 | } |
| 59 | } |
| 60 | // Never for what the agent already reaches (#48): a repository on its |
| 61 | // list, or a namespace it already holds. |
| 62 | h, err := t.hello(r.Person) |
| 63 | if err != nil { |
| 64 | return wire.ToolResult{}, err |
| 65 | } |
| 66 | target := strings.ToLower(in.Target) |
| 67 | if has(h, target, in.Role) { |
| 68 | return refused("already_reached", fmt.Sprintf(toolAlreadyReached, in.Target)), nil |
| 69 | } |
| 70 | if ns, _, ok := strings.Cut(target, "/"); ok { |
| 71 | if slices.Contains(h.CreateIn, ns) && !reaches(h, target) { |
| 72 | return refused("no_such_repository", fmt.Sprintf(toolNoSuchRepository, in.Target, ns)), nil |
| 73 | } |
| 74 | // In a namespace Equipo knows nothing of, only the person's own |
| 75 | // words this turn say the repository is real (review R1). |
| 76 | if !knownNamespace(h, ns) && !namedIn(messages, target) { |
| 77 | return refused("not_named", fmt.Sprintf(toolNotNamed, in.Target)), nil |
| 78 | } |
| 79 | } |
| 80 | var old []cardRecord |
| 81 | if err := t.db.Where("person = ? AND kind = ? AND coalesce(access, '') <> '' AND (turn_id = ? OR state = ?)", r.Person, wire.CardAccess, r.ID, wire.CardOpen).Find(&old).Error; err != nil { |
| 82 | return wire.ToolResult{}, err |
| 83 | } |
| 84 | for _, c := range old { |
| 85 | var a wire.AccessRequest |
| 86 | if json.Unmarshal([]byte(c.Access), &a) != nil { |
| 87 | return wire.ToolResult{}, ErrInvalid |
| 88 | } |
| 89 | if c.TurnID == r.ID || a.Target == in.Target && c.State == wire.CardOpen { |
| 90 | return refused("already_asked", "An access card already exists. Wait for the person; never retry on your own."), nil |
| 91 | } |
| 92 | } |
| 93 | in.Reason, in.State = reason, "confirmation" |
| 94 | raw, _ := json.Marshal(in) |
| 95 | now := t.now() |
| 96 | // Replace only the explanatory find card in this same turn, and only |
| 97 | // while it is open: a resolved card never takes a confirmation. |
| 98 | var c cardRecord |
| 99 | if err := t.db.Where("person = ? AND turn_id = ? AND kind = ? AND state = ? AND coalesce(access, '') = ''", r.Person, r.ID, wire.CardAccess, wire.CardOpen).Find(&c).Error; err != nil { |
| 100 | return wire.ToolResult{}, err |
| 101 | } |
| 102 | fresh := c.ID == "" |
| 103 | if fresh { |
| 104 | c = cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardAccess, State: wire.CardOpen, TurnID: r.ID, Options: "[]", Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane} |
| 105 | } |
| 106 | key := "access.confirm" |
| 107 | if !strings.Contains(in.Target, "/") { |
| 108 | key = "access.confirm_namespace" |
| 109 | } |
| 110 | c.Access, c.Name, c.Question = string(raw), in.Target, fmt.Sprintf(t.s.authority.Copy(key), in.Target) |
| 111 | if fresh { |
| 112 | if err := t.db.Create(&c).Error; err != nil { |
| 113 | return wire.ToolResult{}, err |
| 114 | } |
| 115 | } else if err := t.saveCard(&c); err != nil { |
| 116 | return wire.ToolResult{}, err |
| 117 | } |
| 118 | if err := t.s.authority.Audit(t.db, r.Person, "access.proposed", c.ID); err != nil { |
| 119 | return wire.ToolResult{}, err |
| 120 | } |
| 121 | return wire.ToolResult{Code: "asked", Text: toolAsked}, t.cardEvent(c) |
| 122 | } |
| 123 | |
| 124 | func (t *txn) confirmAccess(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 125 | current, err := t.cardView(c) |
| 126 | if err != nil { |
| 127 | return wire.Card{}, wire.Card{}, err |
| 128 | } |
| 129 | var a wire.AccessRequest |
| 130 | if err := json.Unmarshal([]byte(c.Access), &a); err != nil { |
| 131 | return wire.Card{}, current, err |
| 132 | } |
| 133 | if c.State == wire.CardOpen && c.Revision == in.Revision && a.State == "pending" && in.Choice == "open_access" && wire.AccessURL(a.ApproveURL, a.RequestID) { |
| 134 | a.ApprovalOpened = true |
| 135 | if err := t.s.authority.Audit(t.db, person, "access.approval_opened", c.ID); err != nil { |
| 136 | return wire.Card{}, current, err |
| 137 | } |
| 138 | raw, _ := json.Marshal(a) |
| 139 | c.Access = string(raw) |
| 140 | if err := t.saveCard(&c); err != nil { |
| 141 | return wire.Card{}, current, err |
| 142 | } |
| 143 | out, err := t.cardView(c) |
| 144 | return out, wire.Card{}, err |
| 145 | } |
| 146 | if c.State != wire.CardOpen || c.Revision != in.Revision || a.State != "confirmation" { |
| 147 | return wire.Card{}, current, ErrCardConflict |
| 148 | } |
| 149 | if in.Choice != "confirm" { |
| 150 | return wire.Card{}, current, ErrInvalid |
| 151 | } |
| 152 | id, err := t.s.authority.PrimaryRunner(t.db, person) |
| 153 | if err != nil { |
| 154 | return wire.Card{}, current, err |
| 155 | } |
| 156 | var runner runnerSessionRecord |
| 157 | if err := t.db.First(&runner, "runner_id = ?", id).Error; err != nil { |
| 158 | return wire.Card{}, current, err |
| 159 | } |
| 160 | if runner.Protocol < wire.ProtocolAccess { |
| 161 | return wire.Card{}, current, ErrConflict |
| 162 | } |
| 163 | a.State = "filing" |
| 164 | raw, _ := json.Marshal(a) |
| 165 | c.Access = string(raw) |
| 166 | if err := t.saveCard(&c); err != nil { |
| 167 | return wire.Card{}, current, err |
| 168 | } |
| 169 | if err := t.s.authority.Audit(t.db, person, "access.confirmed", c.ID); err != nil { |
| 170 | return wire.Card{}, current, err |
| 171 | } |
| 172 | if err := t.command(person, wire.FrameRequestAccess, wire.AccessCommand{CardID: c.ID, Person: person, Target: a.Target, Role: a.Role, Reason: a.Reason, Confirmed: true}); err != nil { |
| 173 | return wire.Card{}, current, err |
| 174 | } |
| 175 | out, err := t.cardView(c) |
| 176 | return out, wire.Card{}, err |
| 177 | } |
| 178 | |
| 179 | func (t *txn) accessReport(l Lease, v *wire.AccessReport) error { |
| 180 | if v.Person != l.Runner.Person || l.Protocol < wire.ProtocolAccess { |
| 181 | return ErrForbidden |
| 182 | } |
| 183 | primary, err := t.s.authority.PrimaryRunner(t.db, v.Person) |
| 184 | if err != nil { |
| 185 | return err |
| 186 | } |
| 187 | if primary != l.Runner.RunnerID { |
| 188 | return ErrForbidden |
| 189 | } |
| 190 | var c cardRecord |
| 191 | if err := t.db.Where("id = ? AND person = ? AND kind = ?", v.CardID, v.Person, wire.CardAccess).First(&c).Error; err != nil { |
| 192 | return err |
| 193 | } |
| 194 | var a wire.AccessRequest |
| 195 | if json.Unmarshal([]byte(c.Access), &a) != nil { |
| 196 | return ErrInvalid |
| 197 | } |
| 198 | if a.State == "confirmation" { |
| 199 | return ErrForbidden |
| 200 | } |
| 201 | if wire.AccessFinal(a.State) && !(a.State == "expired" && (v.State == "approved" || v.State == "pending")) { |
| 202 | return nil |
| 203 | } |
| 204 | if v.State != "pending" && !wire.AccessFinal(v.State) || len(v.RequestID) > 200 || v.ApproveURL != "" && !wire.AccessURL(v.ApproveURL, v.RequestID) { |
| 205 | return ErrInvalid |
| 206 | } |
| 207 | if (v.State == "pending" || v.State == "approved") && (v.RequestID == "" || !wire.AccessURL(v.ApproveURL, v.RequestID)) { |
| 208 | return ErrInvalid |
| 209 | } |
| 210 | if a.RequestID != "" && a.RequestID != v.RequestID { |
| 211 | return ErrInvalid |
| 212 | } |
| 213 | if a.State == "expired" && (v.State == "approved" || v.State == "pending") { |
| 214 | c.State = wire.CardOpen |
| 215 | } |
| 216 | a.State, a.RequestID = v.State, v.RequestID |
| 217 | if v.ApproveURL != "" { |
| 218 | a.ApproveURL = v.ApproveURL |
| 219 | } |
| 220 | if v.Expires != 0 { |
| 221 | a.Expires = v.Expires |
| 222 | } |
| 223 | raw, _ := json.Marshal(a) |
| 224 | c.Access = string(raw) |
| 225 | if wire.AccessFinal(a.State) && a.State != "approved" { |
| 226 | c.State = wire.CardResolved |
| 227 | } |
| 228 | if err := t.saveCard(&c); err != nil { |
| 229 | return err |
| 230 | } |
| 231 | if err := t.s.authority.Audit(t.db, v.Person, "access."+a.State, c.ID); err != nil { |
| 232 | return err |
| 233 | } |
| 234 | if a.State == "approved" { |
| 235 | h, err := t.hello(v.Person) |
| 236 | if err != nil { |
| 237 | return err |
| 238 | } |
| 239 | return t.resolveAccess(v.Person, h) |
| 240 | } |
| 241 | return nil |
| 242 | } |
| 243 | |
| 244 | func (t *txn) continueAccess(c cardRecord, h wire.Hello) error { |
| 245 | var a wire.AccessRequest |
| 246 | if json.Unmarshal([]byte(c.Access), &a) != nil { |
| 247 | return ErrInvalid |
| 248 | } |
| 249 | if a.State != "approved" || strings.Contains(a.Target, "/") && !slices.ContainsFunc(h.Catalog, func(e wire.RepoInfo) bool { return intended(e.Repo, a.Target) }) { |
| 250 | return nil |
| 251 | } |
| 252 | c.State = wire.CardResolved |
| 253 | if err := t.saveCard(&c); err != nil { |
| 254 | return err |
| 255 | } |
| 256 | var messages []messageRecord |
| 257 | if err := t.db.Where("person = ? AND turn_id = ? AND role = ?", c.Person, c.TurnID, wire.RolePerson).Order("seq").Find(&messages).Error; err != nil { |
| 258 | return err |
| 259 | } |
| 260 | words := []string{} |
| 261 | for _, m := range messages { |
| 262 | words = append(words, m.Text) |
| 263 | } |
| 264 | _, _, err := t.send(c.Lane, c.Person, "access-approved:"+c.ID, fmt.Sprintf(t.s.authority.Copy("access.continue"), a.Target, strings.Join(words, "\n")), nil, func(m messageRecord) error { |
| 265 | return t.db.Create(&cardThreadRecord{ID: newID("ct_"), Person: c.Person, CardID: c.ID, TurnID: m.TurnID, MessageID: m.ID, CreatedAt: t.now()}).Error |
| 266 | }) |
| 267 | return err |
| 268 | } |
| 269 | |
| 270 | // personNamed reports whether the person's own words this turn name target |
| 271 | // (AccessTarget's spelling), not text the model or Equipo wrote. |
| 272 | func (t *txn) personNamed(r turnRecord, target string) (bool, error) { |
| 273 | var messages []messageRecord |
| 274 | if err := t.db.Where("person = ? AND turn_id = ? AND role = ?", r.Person, r.ID, wire.RolePerson).Order("seq").Find(&messages).Error; err != nil { |
| 275 | return false, err |
| 276 | } |
| 277 | return namedIn(messages, target), nil |
| 278 | } |
| 279 | |
| 280 | // namedIn reports whether one of the person's composed messages names |
| 281 | // target as a word of its own, spelled any way AccessTarget accepts. |
| 282 | func namedIn(messages []messageRecord, target string) bool { |
| 283 | for _, m := range messages { |
| 284 | if m.Origin != originComposer { |
| 285 | continue |
| 286 | } |
| 287 | for _, word := range strings.Fields(m.Text) { |
| 288 | if AccessTarget(strings.Trim(word, ".,;:!?\"'`()[]<>")) == target { |
| 289 | return true |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | return false |
| 294 | } |
| 295 | |
| 296 | // has reports whether the agent already has the access a request asks |
| 297 | // for (review S1). Write work (role agent or runner) needs a repository on |
| 298 | // the runner's list; a repository it only reads is in the catalog alone, |
| 299 | // which is enough for reading. A namespace counts only held whole. |
| 300 | func has(h wire.Hello, target, role string) bool { |
| 301 | if !strings.Contains(target, "/") { |
| 302 | // A namespace is held whole only where the agent may create; |
| 303 | // reading one repository there is not reading the namespace |
| 304 | // (review RN2). |
| 305 | return slices.Contains(h.CreateIn, target) |
| 306 | } |
| 307 | if role == "reader" { |
| 308 | return reaches(h, target) |
| 309 | } |
| 310 | return slices.ContainsFunc(h.Repos, func(repo string) bool { return strings.EqualFold(ProjectName(repo), target) }) |
| 311 | } |
| 312 | |