Files
multica/server/internal/agenttmpl/loader.go
Naiyuan Qing 68edf57f64 feat(agents): agent template catalog + create-from-template endpoint
Server-side foundation for Phase 1 of the quick-create roadmap (see
docs/agent-quick-create-plan.md). Adds:

- server/internal/agenttmpl/ — embed-loaded catalog of curated agent
  templates. Each template ships pre-written instructions plus a list
  of skill URLs that get materialised into the workspace at create
  time. Validation runs at startup (init() panics on a malformed
  template) so a bad JSON ships as a deploy-time defect, not a
  runtime 500. Slug must equal the filename basename so the URL
  router is mirror-symmetric with the file layout.

- 11 starter templates covering Engineering / Writing / Building /
  Testing (code-reviewer, frontend-builder, planner, docs-writer,
  one-pager, html-slides, full-stack-engineer, …).

- Three new endpoints, all behind RequireWorkspaceMember:
    GET  /api/agent-templates           — picker list (no instructions)
    GET  /api/agent-templates/:slug     — detail with instructions
    POST /api/agents/from-template      — materialise + create

  Create flow:
    1. Auth + runtime authorization happen BEFORE the GitHub fan-out
       so a 403 never wastes 20s of upstream fetches.
    2. Pre-flight dedupe by cached_name reuses workspace skills
       without an HTTP fetch — second create-from-the-same-template
       drops from 20s to <100ms.
    3. Parallel fetch (30s per-URL timeout) for the remaining skills.
    4. Single transaction: every skill insert, the agent insert, and
       the agent_skill bindings. On any upstream fetch failure the TX
       rolls back and the API returns 422 with `failed_urls` so the
       UI can name the bad source(s).
    5. extra_skill_ids (user-supplied additions) are verified through
       GetSkillInWorkspace per id before attach, so a malicious client
       can't graft a skill from another workspace via UUID guessing.

- multica agent create --from-template <slug> CLI flag dispatches to
  the new endpoint with a 60s ceiling, matching `multica skill import`.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 16:45:04 +08:00

128 lines
3.5 KiB
Go

package agenttmpl
import (
"embed"
"encoding/json"
"fmt"
"io/fs"
"regexp"
"sort"
"strings"
)
//go:embed templates/*.json
var templateFS embed.FS
var slugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
// Registry is the in-memory store of loaded templates. It's read-only after
// construction — the only mutator is Load(), called once at server startup.
// Concurrent reads after that are safe without locking.
type Registry struct {
bySlug map[string]Template
order []string // slugs in deterministic load order, used by List()
}
// Load parses every *.json file under templates/ and returns a populated
// Registry. Any malformed template (bad JSON, missing required fields,
// slug/filename mismatch) aborts startup — we'd rather fail loudly at boot
// than serve a half-broken picker.
func Load() (*Registry, error) {
return loadFromFS(templateFS, "templates")
}
func loadFromFS(fsys fs.FS, dir string) (*Registry, error) {
entries, err := fs.ReadDir(fsys, dir)
if err != nil {
return nil, fmt.Errorf("agenttmpl: read templates dir: %w", err)
}
reg := &Registry{bySlug: make(map[string]Template)}
// Sort filenames so List() output is deterministic regardless of FS order.
names := make([]string, 0, len(entries))
for _, e := range entries {
if e.IsDir() {
continue
}
if !strings.HasSuffix(e.Name(), ".json") {
continue
}
names = append(names, e.Name())
}
sort.Strings(names)
for _, name := range names {
path := dir + "/" + name
data, err := fs.ReadFile(fsys, path)
if err != nil {
return nil, fmt.Errorf("agenttmpl: read %s: %w", path, err)
}
var t Template
if err := json.Unmarshal(data, &t); err != nil {
return nil, fmt.Errorf("agenttmpl: parse %s: %w", path, err)
}
if err := validate(t, name); err != nil {
return nil, fmt.Errorf("agenttmpl: %s: %w", path, err)
}
if _, dup := reg.bySlug[t.Slug]; dup {
return nil, fmt.Errorf("agenttmpl: duplicate slug %q (file %s)", t.Slug, path)
}
reg.bySlug[t.Slug] = t
reg.order = append(reg.order, t.Slug)
}
return reg, nil
}
// validate enforces the invariants that the rest of the handler / UI assume.
// Cheap to run at boot — every check pays for itself the first time someone
// adds a malformed template in a PR.
func validate(t Template, filename string) error {
if t.Slug == "" {
return fmt.Errorf("missing slug")
}
if !slugPattern.MatchString(t.Slug) {
return fmt.Errorf("slug %q must be lowercase kebab-case (a-z, 0-9, -)", t.Slug)
}
// Slug must equal the filename basename so URL routing matches file
// layout. Catches typos and lets `git mv` rename templates safely.
if filename != t.Slug+".json" {
return fmt.Errorf("slug %q does not match filename %q", t.Slug, filename)
}
if strings.TrimSpace(t.Name) == "" {
return fmt.Errorf("missing name")
}
if strings.TrimSpace(t.Instructions) == "" {
return fmt.Errorf("missing instructions")
}
if len(t.Skills) == 0 {
return fmt.Errorf("must declare at least one skill")
}
for i, s := range t.Skills {
if strings.TrimSpace(s.SourceURL) == "" {
return fmt.Errorf("skill[%d]: missing source_url", i)
}
}
return nil
}
// List returns all templates in deterministic load order.
func (r *Registry) List() []Template {
out := make([]Template, 0, len(r.order))
for _, slug := range r.order {
out = append(out, r.bySlug[slug])
}
return out
}
// Get returns the template with the given slug, or false if not found.
func (r *Registry) Get(slug string) (Template, bool) {
t, ok := r.bySlug[slug]
return t, ok
}