| 1 | package library |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/json" |
| 7 | "net/http" |
| 8 | "slices" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/equipo/identity" |
| 13 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 14 | "amadan.net/oficina/equipo/internal/equipo/planning" |
| 15 | "github.com/go-chi/chi/v5" |
| 16 | ) |
| 17 | |
| 18 | type Operations interface { |
| 19 | SpecialistFormProjects(context.Context, kernel.Actor, Specialist) ([]ProjectOption, error) |
| 20 | SpecialistWork(context.Context, kernel.Actor, string) (planning.SpecialistWorkView, error) |
| 21 | PlaybookOperations |
| 22 | SaveSpecialist(context.Context, kernel.Actor, Specialist) error |
| 23 | Specialist(context.Context, kernel.Actor, string) (Specialist, error) |
| 24 | CreateSpecialist(context.Context, kernel.Actor, SpecialistInput, kernel.Mutation) (Specialist, error) |
| 25 | UpdateSpecialist(context.Context, kernel.Actor, SpecialistInput, kernel.Mutation) (Specialist, error) |
| 26 | DeleteSpecialist(context.Context, kernel.Actor, string, kernel.Mutation) error |
| 27 | SpecialistTemplates(context.Context, kernel.Actor) ([]Template, error) |
| 28 | InstallSpecialistTemplate(context.Context, kernel.Actor, TemplateRef, kernel.Mutation) (Specialist, error) |
| 29 | SpecialistTemplateDiff(context.Context, kernel.Actor, string, TemplateRef) (TemplateDiff, error) |
| 30 | ApplySpecialistTemplate(context.Context, kernel.Actor, string, TemplateDiff, []string, kernel.Mutation) (Specialist, error) |
| 31 | } |
| 32 | type FieldDiff struct{ Key, CopyKey, Old, Current, Suggested string } |
| 33 | type ProjectOption struct { |
| 34 | ID int64 |
| 35 | Name string |
| 36 | Selected bool |
| 37 | } |
| 38 | type View struct { |
| 39 | PlaybookEditable bool |
| 40 | Work planning.SpecialistWorkView |
| 41 | PlaybookPage, Owner bool |
| 42 | Playbook Playbook |
| 43 | Playbooks []PlaybookView |
| 44 | Defaults []PlaybookDefault |
| 45 | PlaybookTemplates []Template |
| 46 | PlaybookSteps []PlaybookStepView |
| 47 | Specialists []Specialist |
| 48 | SuggestionID string |
| 49 | Specialist Specialist |
| 50 | Templates []Template |
| 51 | Icons []string |
| 52 | Models []ModelRef |
| 53 | Projects []ProjectOption |
| 54 | Diff TemplateDiff |
| 55 | Fields []FieldDiff |
| 56 | DiffJSON, RequestID string |
| 57 | } |
| 58 | type Handler struct { |
| 59 | LegacyForm func(http.ResponseWriter, *http.Request, ...string) (kernel.Actor, error) |
| 60 | Number func(*http.Request, string) (int64, error) |
| 61 | NotFound error |
| 62 | Store Operations |
| 63 | Actor func(*http.Request) (kernel.Actor, error) |
| 64 | Render func(http.ResponseWriter, *http.Request, string, View) |
| 65 | Failure func(http.ResponseWriter, *http.Request, error) |
| 66 | Invalid error |
| 67 | } |
| 68 | |
| 69 | func (h *Handler) Catalog(w http.ResponseWriter, r *http.Request) { |
| 70 | a, err := h.Actor(r) |
| 71 | if err != nil { |
| 72 | h.Failure(w, r, err) |
| 73 | return |
| 74 | } |
| 75 | rows, err := h.Store.SpecialistTemplates(r.Context(), a) |
| 76 | if err != nil { |
| 77 | h.Failure(w, r, err) |
| 78 | return |
| 79 | } |
| 80 | h.Render(w, r, "template_library", View{Templates: rows, RequestID: rand.Text()}) |
| 81 | } |
| 82 | func (h *Handler) Form(w http.ResponseWriter, r *http.Request) { |
| 83 | a, err := h.Actor(r) |
| 84 | if err != nil { |
| 85 | h.Failure(w, r, err) |
| 86 | return |
| 87 | } |
| 88 | row := Specialist{MaxConcurrent: 1, Icon: "plus"} |
| 89 | if key := chi.URLParam(r, "key"); key != "" { |
| 90 | row, err = h.Store.Specialist(r.Context(), a, key) |
| 91 | if err != nil { |
| 92 | h.Failure(w, r, err) |
| 93 | return |
| 94 | } |
| 95 | } |
| 96 | iconIDs := []string{"lightbulb", "pencil", "type", "code", "check-circle", "shield", "sliders", "plus"} |
| 97 | if !slices.Contains(iconIDs, row.Icon) { |
| 98 | iconIDs = append(iconIDs, row.Icon) |
| 99 | } |
| 100 | projects, err := h.Store.SpecialistFormProjects(r.Context(), a, row) |
| 101 | if err != nil { |
| 102 | h.Failure(w, r, err) |
| 103 | return |
| 104 | } |
| 105 | h.Render(w, r, "specialist_form", View{Specialist: row, Projects: projects, Icons: iconIDs, Models: append(slices.Clone(row.AllowedModels), ModelRef{}), RequestID: rand.Text()}) |
| 106 | } |
| 107 | func (h *Handler) form(w http.ResponseWriter, r *http.Request, allowed ...string) (kernel.Actor, kernel.Mutation, error) { |
| 108 | a, err := h.Actor(r) |
| 109 | if err != nil { |
| 110 | return a, kernel.Mutation{}, err |
| 111 | } |
| 112 | r.Body = http.MaxBytesReader(w, r.Body, 64<<10) |
| 113 | if r.ParseForm() != nil { |
| 114 | return a, kernel.Mutation{}, h.Invalid |
| 115 | } |
| 116 | for key, v := range r.PostForm { |
| 117 | modelField := false |
| 118 | if strings.HasPrefix(key, "model.") { |
| 119 | parts := strings.Split(key, ".") |
| 120 | if len(parts) == 3 { |
| 121 | n, e := strconv.Atoi(parts[1]) |
| 122 | modelField = e == nil && n >= 0 && n <= 100 && slices.Contains([]string{"provider", "family", "name"}, parts[2]) && slices.Contains(allowed, "models") |
| 123 | } |
| 124 | } |
| 125 | if (!slices.Contains(allowed, key) || key == "models") && !modelField || len(v) != 1 && key != "field" && key != "project" { |
| 126 | return a, kernel.Mutation{}, h.Invalid |
| 127 | } |
| 128 | } |
| 129 | revision := int64(0) |
| 130 | if v := r.PostForm.Get("revision"); v != "" { |
| 131 | revision, err = strconv.ParseInt(v, 10, 64) |
| 132 | if err != nil { |
| 133 | return a, kernel.Mutation{}, h.Invalid |
| 134 | } |
| 135 | } |
| 136 | m := kernel.Mutation{RequestID: r.PostForm.Get("request_id"), Revision: revision} |
| 137 | if !m.Valid() { |
| 138 | return a, m, h.Invalid |
| 139 | } |
| 140 | return a, m, nil |
| 141 | } |
| 142 | func (h *Handler) Save(w http.ResponseWriter, r *http.Request) { |
| 143 | a, m, err := h.form(w, r, "request_id", "revision", "name", "icon", "instructions", "max_concurrent", "models", "project") |
| 144 | if err != nil { |
| 145 | h.Failure(w, r, err) |
| 146 | return |
| 147 | } |
| 148 | max, err := strconv.Atoi(r.PostForm.Get("max_concurrent")) |
| 149 | if err != nil { |
| 150 | h.Failure(w, r, h.Invalid) |
| 151 | return |
| 152 | } |
| 153 | in := SpecialistInput{Key: chi.URLParam(r, "key"), Name: r.PostForm.Get("name"), Icon: r.PostForm.Get("icon"), Instructions: r.PostForm.Get("instructions"), MaxConcurrent: max} |
| 154 | for i := 0; i <= 100; i++ { |
| 155 | prefix := "model." + strconv.Itoa(i) + "." |
| 156 | model := ModelRef{r.PostForm.Get(prefix + "provider"), r.PostForm.Get(prefix + "family"), r.PostForm.Get(prefix + "name")} |
| 157 | if model != (ModelRef{}) { |
| 158 | in.AllowedModels = append(in.AllowedModels, model) |
| 159 | } |
| 160 | } |
| 161 | for _, v := range r.PostForm["project"] { |
| 162 | id, e := strconv.ParseInt(v, 10, 64) |
| 163 | if e != nil { |
| 164 | h.Failure(w, r, h.Invalid) |
| 165 | return |
| 166 | } |
| 167 | in.ProjectIDs = append(in.ProjectIDs, id) |
| 168 | } |
| 169 | var row Specialist |
| 170 | if in.Key == "" { |
| 171 | row, err = h.Store.CreateSpecialist(r.Context(), a, in, m) |
| 172 | } else { |
| 173 | row, err = h.Store.UpdateSpecialist(r.Context(), a, in, m) |
| 174 | } |
| 175 | if err != nil { |
| 176 | h.Failure(w, r, err) |
| 177 | return |
| 178 | } |
| 179 | http.Redirect(w, r, "/specialists/"+row.Key, http.StatusSeeOther) |
| 180 | } |
| 181 | func (h *Handler) Archive(w http.ResponseWriter, r *http.Request) { |
| 182 | a, m, err := h.form(w, r, "request_id", "revision") |
| 183 | if err == nil { |
| 184 | err = h.Store.DeleteSpecialist(r.Context(), a, chi.URLParam(r, "key"), m) |
| 185 | } |
| 186 | if err != nil { |
| 187 | h.Failure(w, r, err) |
| 188 | return |
| 189 | } |
| 190 | http.Redirect(w, r, "/work", http.StatusSeeOther) |
| 191 | } |
| 192 | func (h *Handler) Install(w http.ResponseWriter, r *http.Request) { |
| 193 | a, m, err := h.form(w, r, "request_id", "version") |
| 194 | if err != nil { |
| 195 | h.Failure(w, r, err) |
| 196 | return |
| 197 | } |
| 198 | version, err := strconv.ParseInt(r.PostForm.Get("version"), 10, 64) |
| 199 | if err != nil { |
| 200 | h.Failure(w, r, h.Invalid) |
| 201 | return |
| 202 | } |
| 203 | row, err := h.Store.InstallSpecialistTemplate(r.Context(), a, TemplateRef{chi.URLParam(r, "id"), version}, m) |
| 204 | if err != nil { |
| 205 | h.Failure(w, r, err) |
| 206 | return |
| 207 | } |
| 208 | http.Redirect(w, r, "/specialists/"+row.Key+"/edit", http.StatusSeeOther) |
| 209 | } |
| 210 | func (h *Handler) Diff(w http.ResponseWriter, r *http.Request) { |
| 211 | a, err := h.Actor(r) |
| 212 | if err != nil { |
| 213 | h.Failure(w, r, err) |
| 214 | return |
| 215 | } |
| 216 | key := chi.URLParam(r, "key") |
| 217 | row, err := h.Store.Specialist(r.Context(), a, key) |
| 218 | if err != nil { |
| 219 | h.Failure(w, r, err) |
| 220 | return |
| 221 | } |
| 222 | version := row.TemplateVersion |
| 223 | if v := r.URL.Query().Get("version"); v != "" { |
| 224 | version, err = strconv.ParseInt(v, 10, 64) |
| 225 | if err != nil { |
| 226 | h.Failure(w, r, h.Invalid) |
| 227 | return |
| 228 | } |
| 229 | } |
| 230 | diff, err := h.Store.SpecialistTemplateDiff(r.Context(), a, key, TemplateRef{row.TemplateID, version}) |
| 231 | if err != nil { |
| 232 | h.Failure(w, r, err) |
| 233 | return |
| 234 | } |
| 235 | view := View{Specialist: row, Diff: diff, RequestID: rand.Text()} |
| 236 | raw, _ := json.Marshal(diff) |
| 237 | view.DiffJSON = string(raw) |
| 238 | labels := map[string]string{"name": "specialists.name", "icon": "specialists.icon", "instructions": "specialists.instructions", "allowed_models": "specialists.models", "tools": "specialists.tools", "project_ids": "specialists.projects", "max_concurrent": "specialist.concurrent"} |
| 239 | for _, field := range []string{"name", "icon", "instructions", "allowed_models", "tools", "project_ids", "max_concurrent"} { |
| 240 | view.Fields = append(view.Fields, FieldDiff{field, labels[field], string(diff.Old[field]), string(diff.Current[field]), string(diff.Suggested[field])}) |
| 241 | } |
| 242 | h.Render(w, r, "template_diff", view) |
| 243 | } |
| 244 | func (h *Handler) Apply(w http.ResponseWriter, r *http.Request) { |
| 245 | a, m, err := h.form(w, r, "request_id", "revision", "diff", "field") |
| 246 | if err != nil { |
| 247 | h.Failure(w, r, err) |
| 248 | return |
| 249 | } |
| 250 | var diff TemplateDiff |
| 251 | if json.Unmarshal([]byte(r.PostForm.Get("diff")), &diff) != nil { |
| 252 | h.Failure(w, r, h.Invalid) |
| 253 | return |
| 254 | } |
| 255 | row, err := h.Store.ApplySpecialistTemplate(r.Context(), a, chi.URLParam(r, "key"), diff, r.PostForm["field"], m) |
| 256 | if err != nil { |
| 257 | h.Failure(w, r, err) |
| 258 | return |
| 259 | } |
| 260 | http.Redirect(w, r, "/specialists/"+row.Key, http.StatusSeeOther) |
| 261 | } |
| 262 | |
| 263 | func (h *Handler) Detail(w http.ResponseWriter, r *http.Request) { |
| 264 | a, err := h.Actor(r) |
| 265 | if err != nil { |
| 266 | h.Failure(w, r, err) |
| 267 | return |
| 268 | } |
| 269 | row, err := h.Store.Specialist(r.Context(), a, chi.URLParam(r, "key")) |
| 270 | if err != nil { |
| 271 | h.Failure(w, r, err) |
| 272 | return |
| 273 | } |
| 274 | work, err := h.Store.SpecialistWork(r.Context(), a, row.Key) |
| 275 | if err != nil { |
| 276 | h.Failure(w, r, err) |
| 277 | return |
| 278 | } |
| 279 | h.Render(w, r, "specialist", View{Specialist: row, Work: work, RequestID: rand.Text()}) |
| 280 | } |
| 281 | |
| 282 | func (h *Handler) Routes(r chi.Router) { |
| 283 | h.PlaybookRoutes(r) |
| 284 | r.Get("/specialists/{key}", h.Detail) |
| 285 | r.Get("/templates", h.Catalog) |
| 286 | r.Post("/templates/{id}/install", h.Install) |
| 287 | r.Get("/specialists/new", h.Form) |
| 288 | r.Post("/specialists", h.Save) |
| 289 | r.Get("/specialists/{key}/edit", h.Form) |
| 290 | r.Post("/specialists/{key}/edit", h.Save) |
| 291 | r.Post("/specialists/{key}/archive", h.Archive) |
| 292 | r.Get("/specialists/{key}/template-diff", h.Diff) |
| 293 | r.Post("/specialists/{key}/template-update", h.Apply) |
| 294 | r.Post("/specialists/{key}", h.SaveLegacy) |
| 295 | } |
| 296 | |
| 297 | func SessionActor(forbidden error) func(*http.Request) (kernel.Actor, error) { |
| 298 | return func(r *http.Request) (kernel.Actor, error) { |
| 299 | id, ok := identity.From(r) |
| 300 | if !ok { |
| 301 | return kernel.Actor{}, forbidden |
| 302 | } |
| 303 | return kernel.Actor{Address: id.Address}, nil |
| 304 | } |
| 305 | } |
| 306 | |