Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

perf(server): resolve only the requested skill bundles (#7810)

Bohan Jiang8d7e6f6a0a6f
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index dc2b0d8f2e..5f655111ad 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -3448,7 +3448,22 @@ func (h *Handler) ResolveTaskSkillBundles(w http.ResponseWriter, r *http.Request
return
}
- bundles, _, err := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)
+ // Validate before reading: a malformed ref is rejected the same way it
+ // always was, now without paying for a load first.
+ wanted := make([]service.AgentSkillBundleRef, 0, len(req.Skills))
+ for _, ref := range req.Skills {
+ if ref.ID == "" || ref.Source == "" || ref.Hash == "" {
+ writeError(w, http.StatusBadRequest, "invalid skill ref")
+ return
+ }
+ wanted = append(wanted, service.AgentSkillBundleRef{ID: ref.ID, Source: ref.Source})
+ }
+
+ // Load ONLY what was asked for. The daemon resolves one skill per request,
+ // so serving these out of the agent's full bundle set meant reading and
+ // hashing every skill the agent has, once per request, to return one of
+ // them — quadratic in skill count across a cold dispatch.
+ allowed, err := h.TaskService.LoadRequestedAgentSkillBundles(r.Context(), task.AgentID, wanted)
if err != nil {
// 5xx, not a partial answer: the daemon's resolve retry can recover a
// transient read, and a bundle assembled from a failed read would pass
@@ -3458,18 +3473,10 @@ func (h *Handler) ResolveTaskSkillBundles(w http.ResponseWriter, r *http.Request
writeError(w, http.StatusInternalServerError, "failed to load skill bundles")
return
}
- allowed := make(map[string]service.AgentSkillData, len(bundles))
- for _, bundle := range bundles {
- allowed[bundle.Source+"\x00"+bundle.ID] = bundle
- }
resolved := make([]service.AgentSkillData, 0, len(req.Skills))
for _, ref := range req.Skills {
- if ref.ID == "" || ref.Source == "" || ref.Hash == "" {
- writeError(w, http.StatusBadRequest, "invalid skill ref")
- return
- }
- bundle, ok := allowed[ref.Source+"\x00"+ref.ID]
+ bundle, ok := allowed[service.AgentSkillBundleKey(ref.Source, ref.ID)]
if !ok {
writeError(w, http.StatusNotFound, "skill bundle not found")
return
diff --git a/server/internal/handler/daemon_skill_resolve_scope_test.go b/server/internal/handler/daemon_skill_resolve_scope_test.go
new file mode 100644
index 0000000000..8d169bc7bd
--- /dev/null
+++ b/server/internal/handler/daemon_skill_resolve_scope_test.go
@@ -0,0 +1,376 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/skillbundle"
+)
+
+// The daemon resolves one skill bundle per request (GH #4505), so what the
+// resolve endpoint loads per request is multiplied by the agent's skill count
+// across a cold dispatch. These tests pin that it loads only the refs it was
+// asked for, and that narrowing the read did not narrow what the agent is
+// allowed to see -- the junction predicate is now doing the authorization the
+// full-set lookup used to do.
+
+// Query markers include the trailing kind so they cannot match a sibling query
+// whose name shares a prefix (ListAgentSkills vs ListAgentSkillsByIDs).
+const (
+ queryFullAgentSkills = "-- name: ListAgentSkills :many"
+ queryScopedAgentSkills = "-- name: ListAgentSkillsByIDs :many"
+ querySkillFilesByIDs = "-- name: ListSkillFilesBySkillIDs :many"
+)
+
+var errInjectedScopedSkillRead = errors.New("injected scoped skill read failure")
+
+// skillQuerySpy passes every statement through to the real pool while
+// recording which skill reads ran and how many IDs each was given, so a test
+// can assert the request cost and not just the response body. failQuery fails
+// one chosen query.
+type skillQuerySpy struct {
+ inner db.DBTX
+ failQuery string
+
+ mu sync.Mutex
+ fullSkillCalls int
+ scopedSkillIDs []int
+ skillFileCallIDs []int
+}
+
+func (s *skillQuerySpy) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
+ return s.inner.Exec(ctx, sql, args...)
+}
+
+func (s *skillQuerySpy) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ return s.inner.QueryRow(ctx, sql, args...)
+}
+
+func (s *skillQuerySpy) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
+ switch {
+ case strings.Contains(sql, queryScopedAgentSkills):
+ s.record(&s.scopedSkillIDs, uuidArgLen(args, 1))
+ if s.failQuery == queryScopedAgentSkills {
+ return nil, errInjectedScopedSkillRead
+ }
+ case strings.Contains(sql, queryFullAgentSkills):
+ s.mu.Lock()
+ s.fullSkillCalls++
+ s.mu.Unlock()
+ case strings.Contains(sql, querySkillFilesByIDs):
+ s.record(&s.skillFileCallIDs, uuidArgLen(args, 0))
+ }
+ return s.inner.Query(ctx, sql, args...)
+}
+
+func (s *skillQuerySpy) record(into *[]int, n int) {
+ s.mu.Lock()
+ *into = append(*into, n)
+ s.mu.Unlock()
+}
+
+func (s *skillQuerySpy) snapshot() (fullCalls int, scoped, files []int) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.fullSkillCalls, append([]int(nil), s.scopedSkillIDs...), append([]int(nil), s.skillFileCallIDs...)
+}
+
+func uuidArgLen(args []any, i int) int {
+ if i >= len(args) {
+ return -1
+ }
+ ids, ok := args[i].([]pgtype.UUID)
+ if !ok {
+ return -1
+ }
+ return len(ids)
+}
+
+func newSpyHandler(t *testing.T, spy *skillQuerySpy) *Handler {
+ t.Helper()
+ return New(db.New(spy), testPool, testHandler.Hub, testHandler.Bus, testHandler.EmailService,
+ nil, nil, analytics.NoopClient{}, Config{})
+}
+
+// resolveScopeFixture creates a runtime, a dispatched task, and an agent
+// carrying one skill per name in skillNames (each with one supporting file).
+func resolveScopeFixture(t *testing.T, ctx context.Context, name string, skillNames ...string) (runtimeID, taskID string, skillIDs []string) {
+ t.Helper()
+
+ runtimeID = createClaimReclaimRuntime(t, ctx, name+" runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, name+" agent")
+
+ for _, skillName := range skillNames {
+ skillID := dbfx.Insert(t, "skill", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "name": skillName,
+ "description": "Resolve scope fixture",
+ "content": skillName + " content",
+ "config": testutil.Raw("'{}'::jsonb"),
+ "created_by": testUserID,
+ })
+ dbfx.InsertNoID(t, "skill_file", testutil.Cols{
+ "skill_id": skillID,
+ "path": "rules.md",
+ "content": skillName + " rules",
+ }, "skill_id = $1", skillID)
+ dbfx.InsertNoID(t, "agent_skill", testutil.Cols{
+ "agent_id": agentID,
+ "skill_id": skillID,
+ }, "skill_id = $1", skillID)
+ skillIDs = append(skillIDs, skillID)
+ }
+
+ taskID = dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "issue_id": issueID,
+ "status": "dispatched",
+ "dispatched_at": testutil.Raw("now()"),
+ })
+ return runtimeID, taskID, skillIDs
+}
+
+func resolveBundles(t *testing.T, h *Handler, runtimeID, taskID string, refs ...resolveSkillBundleRef) *testutil.Response {
+ t.Helper()
+ req := newDaemonTokenRequest("POST",
+ "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve",
+ resolveSkillBundlesRequest{Skills: refs}, testWorkspaceID, "resolve-scope-daemon")
+ req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
+ return testutil.Call(t, h.ResolveTaskSkillBundles, req)
+}
+
+func workspaceRef(skillID string) resolveSkillBundleRef {
+ return resolveSkillBundleRef{ID: skillID, Source: skillbundle.SourceWorkspace, Hash: "sha256:whatever"}
+}
+
+// TestResolveTaskSkillBundles_LoadsOnlyTheRequestedSkill is the point of the
+// change: an agent with three skills asks for one, and the server must read
+// and hash one. Before, every resolve request loaded the agent's entire skill
+// set to pick a single bundle out of it, so a cold dispatch of N skills cost N
+// full loads.
+func TestResolveTaskSkillBundles_LoadsOnlyTheRequestedSkill(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ spy := &skillQuerySpy{inner: testPool}
+ runtimeID, taskID, skillIDs := resolveScopeFixture(t, ctx, "resolvescope",
+ "resolvescope-alpha", "resolvescope-beta", "resolvescope-gamma")
+
+ var resp struct {
+ Bundles []service.AgentSkillData `json:"bundles"`
+ }
+ resolveBundles(t, newSpyHandler(t, spy), runtimeID, taskID, workspaceRef(skillIDs[1])).
+ Want(http.StatusOK).JSON(&resp)
+
+ if len(resp.Bundles) != 1 || resp.Bundles[0].ID != skillIDs[1] {
+ t.Fatalf("resolved %+v, want exactly the requested skill %s", resp.Bundles, skillIDs[1])
+ }
+ if len(resp.Bundles[0].Files) != 1 || resp.Bundles[0].Files[0].Content != "resolvescope-beta rules" {
+ t.Fatalf("resolved bundle lost its files: %+v", resp.Bundles[0].Files)
+ }
+ if resp.Bundles[0].Hash == "" {
+ t.Fatal("resolved bundle has no hash")
+ }
+
+ fullCalls, scoped, files := spy.snapshot()
+ if fullCalls != 0 {
+ t.Fatalf("the full ListAgentSkills ran %d times; resolve must not load the agent's whole skill set", fullCalls)
+ }
+ if len(scoped) != 1 || scoped[0] != 1 {
+ t.Fatalf("scoped skill query calls = %v, want exactly one call for one id", scoped)
+ }
+ if len(files) != 1 || files[0] != 1 {
+ t.Fatalf("skill file query calls = %v, want exactly one call for one id", files)
+ }
+}
+
+// TestResolveTaskSkillBundles_BuiltinRefTouchesNoWorkspaceQuery pins the other
+// half: built-ins live in the binary, so resolving one must not reach the
+// database at all.
+func TestResolveTaskSkillBundles_BuiltinRefTouchesNoWorkspaceQuery(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ spy := &skillQuerySpy{inner: testPool}
+ runtimeID, taskID, _ := resolveScopeFixture(t, ctx, "resolvebuiltin", "resolvebuiltin-alpha")
+
+ builtins := testHandler.TaskService.BuiltinSkills()
+ if len(builtins) == 0 {
+ t.Skip("no builtin skills embedded in this build")
+ }
+ want := builtins[0]
+
+ var resp struct {
+ Bundles []service.AgentSkillData `json:"bundles"`
+ }
+ resolveBundles(t, newSpyHandler(t, spy), runtimeID, taskID, resolveSkillBundleRef{
+ ID: service.BuiltinSkillID(want.Name),
+ Source: skillbundle.SourceBuiltin,
+ Hash: "sha256:whatever",
+ }).Want(http.StatusOK).JSON(&resp)
+
+ if len(resp.Bundles) != 1 || resp.Bundles[0].Name != want.Name || resp.Bundles[0].Content != want.Content {
+ t.Fatalf("resolved %+v, want builtin %q", resp.Bundles, want.Name)
+ }
+
+ fullCalls, scoped, files := spy.snapshot()
+ if fullCalls != 0 || len(scoped) != 0 || len(files) != 0 {
+ t.Fatalf("builtin resolve hit the database: full=%d scoped=%v files=%v", fullCalls, scoped, files)
+ }
+}
+
+// TestResolveTaskSkillBundles_KeepsRequestOrderAndDeduplicates: the scoped
+// query orders by name, so response order can no longer fall out of the load.
+// It must follow the request, and a repeated ref must not be loaded twice.
+func TestResolveTaskSkillBundles_KeepsRequestOrderAndDeduplicates(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ spy := &skillQuerySpy{inner: testPool}
+ // Named so the query's name ASC order is the reverse of the request order.
+ runtimeID, taskID, skillIDs := resolveScopeFixture(t, ctx, "resolveorder",
+ "resolveorder-zulu", "resolveorder-alpha")
+ zulu, alpha := skillIDs[0], skillIDs[1]
+
+ var resp struct {
+ Bundles []service.AgentSkillData `json:"bundles"`
+ }
+ resolveBundles(t, newSpyHandler(t, spy), runtimeID, taskID,
+ workspaceRef(zulu), workspaceRef(alpha), workspaceRef(zulu)).
+ Want(http.StatusOK).JSON(&resp)
+
+ got := []string{}
+ for _, bundle := range resp.Bundles {
+ got = append(got, bundle.ID)
+ }
+ want := []string{zulu, alpha, zulu}
+ if len(got) != len(want) {
+ t.Fatalf("resolved %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("resolved %v, want request order %v", got, want)
+ }
+ }
+
+ _, scoped, files := spy.snapshot()
+ if len(scoped) != 1 || scoped[0] != 2 {
+ t.Fatalf("scoped skill query calls = %v, want one call for 2 distinct ids (the repeated ref must not load twice)", scoped)
+ }
+ if len(files) != 1 || files[0] != 2 {
+ t.Fatalf("skill file query calls = %v, want one call for 2 ids", files)
+ }
+}
+
+// TestResolveTaskSkillBundles_RefusesSkillsTheAgentCannotSee is the reason the
+// narrowed read is safe: the old code authorized by membership in the agent's
+// full bundle set, and the new query has to reject exactly the same refs.
+func TestResolveTaskSkillBundles_RefusesSkillsTheAgentCannotSee(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ runtimeID, taskID, skillIDs := resolveScopeFixture(t, ctx, "resolvedeny", "resolvedeny-owned")
+ agentID := ""
+ dbfx.QueryRow(t, `SELECT agent_id::text FROM agent_task_queue WHERE id = $1`, taskID).Scan(&agentID)
+
+ // A workspace skill nobody assigned to this agent.
+ unassigned := dbfx.Insert(t, "skill", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "name": "resolvedeny-unassigned",
+ "description": "",
+ "content": "unassigned content",
+ "config": testutil.Raw("'{}'::jsonb"),
+ "created_by": testUserID,
+ })
+
+ // Assigned, but the assignment is disabled.
+ disabled := dbfx.Insert(t, "skill", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "name": "resolvedeny-disabled",
+ "description": "",
+ "content": "disabled content",
+ "config": testutil.Raw("'{}'::jsonb"),
+ "created_by": testUserID,
+ })
+ dbfx.InsertNoID(t, "agent_skill", testutil.Cols{
+ "agent_id": agentID,
+ "skill_id": disabled,
+ "enabled": false,
+ }, "skill_id = $1", disabled)
+
+ // A skill owned by a different workspace.
+ foreignWorkspace := dbfx.Insert(t, "workspace", testutil.Cols{
+ "name": "Resolve deny foreign",
+ "slug": "resolve-deny-foreign",
+ "description": "",
+ "issue_prefix": "RDF",
+ })
+ foreign := dbfx.Insert(t, "skill", testutil.Cols{
+ "workspace_id": foreignWorkspace,
+ "name": "resolvedeny-foreign",
+ "description": "",
+ "content": "foreign content",
+ "config": testutil.Raw("'{}'::jsonb"),
+ "created_by": testUserID,
+ })
+
+ tests := []struct {
+ name string
+ ref resolveSkillBundleRef
+ }{
+ {name: "skill not assigned to the agent", ref: workspaceRef(unassigned)},
+ {name: "assignment disabled", ref: workspaceRef(disabled)},
+ {name: "skill owned by another workspace", ref: workspaceRef(foreign)},
+ {name: "unparseable skill id", ref: workspaceRef("not-a-uuid")},
+ {name: "source with no server-side producer", ref: resolveSkillBundleRef{
+ ID: skillIDs[0], Source: skillbundle.SourcePlugin, Hash: "sha256:whatever",
+ }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ spy := &skillQuerySpy{inner: testPool}
+ resolveBundles(t, newSpyHandler(t, spy), runtimeID, taskID, tc.ref).Want(http.StatusNotFound)
+ })
+ }
+
+ // The agent's own skill still resolves, so the cases above are denials and
+ // not a fixture that could never resolve anything.
+ spy := &skillQuerySpy{inner: testPool}
+ resolveBundles(t, newSpyHandler(t, spy), runtimeID, taskID, workspaceRef(skillIDs[0])).Want(http.StatusOK)
+}
+
+// TestResolveTaskSkillBundles_ScopedReadFailureReturns500 extends the
+// fail-closed rule to the new query: a failed read must not answer 404, which
+// the daemon would treat as a permanent "this skill is gone" rather than
+// retrying.
+func TestResolveTaskSkillBundles_ScopedReadFailureReturns500(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ runtimeID, taskID, skillIDs := resolveScopeFixture(t, ctx, "resolvereadfail", "resolvereadfail-alpha")
+
+ spy := &skillQuerySpy{inner: testPool, failQuery: queryScopedAgentSkills}
+ resolveBundles(t, newSpyHandler(t, spy), runtimeID, taskID, workspaceRef(skillIDs[0])).
+ Want(http.StatusInternalServerError)
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 9a31da4ff6..778e10cf91 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -6342,14 +6342,21 @@ func (s *TaskService) LoadAgentSkills(ctx context.Context, agentID pgtype.UUID)
if len(skills) == 0 {
return nil, nil
}
+ return s.skillsWithFiles(ctx, skills)
+}
- // Load every skill's files in one round trip instead of one query per
- // skill (N+1 on the task-claim hot path). Group by skill_id in a single
- // linear pass — the query orders by skill_id, path.
+// skillsWithFiles loads the files of every given skill in ONE round trip
+// instead of one query per skill, and assembles the result in the order the
+// skills were given. Shared by the claim-time full load and the resolve-time
+// scoped load so the two cannot drift on skill order, per-skill file order, or
+// the nil (not empty) file list of a skill that has none.
+func (s *TaskService) skillsWithFiles(ctx context.Context, skills []db.Skill) ([]AgentSkillData, error) {
skillIDs := make([]pgtype.UUID, len(skills))
for i, sk := range skills {
skillIDs[i] = sk.ID
}
+ // Group by skill_id in a single linear pass — the query orders by
+ // skill_id, path.
files, err := s.Queries.ListSkillFilesBySkillIDs(ctx, skillIDs)
if err != nil {
return nil, fmt.Errorf("list skill files for %d skills: %w", len(skills), err)
@@ -6388,6 +6395,97 @@ func (s *TaskService) LoadAgentSkillBundles(ctx context.Context, agentID pgtype.
return bundles, refs, nil
}
+// BuiltinSkillID is the ref id a builtin skill is addressed by. Builtins have
+// no database row, so their identity is their name — this is the one place
+// that turns a name into that identity, for both the bundle builder that hands
+// the id out and the resolver that looks one back up.
+func BuiltinSkillID(name string) string { return "builtin:" + name }
+
+// AgentSkillBundleKey is the (source, id) identity a daemon skill ref resolves
+// by. Source is part of the key because a builtin and a workspace skill are
+// different bundles even when they share a name.
+func AgentSkillBundleKey(source, id string) string { return source + "\x00" + id }
+
+// AgentSkillBundleRef is one skill a daemon is asking to resolve.
+type AgentSkillBundleRef struct {
+ ID string
+ Source string
+}
+
+// LoadRequestedAgentSkillBundles returns bundles for EXACTLY the refs given,
+// keyed by AgentSkillBundleKey. A ref the agent cannot see is simply absent
+// from the map — the junction predicate in ListAgentSkillsByIDs is the
+// authorization, so "no row" and "not allowed" are the same answer and the
+// caller reports both as not-found.
+//
+// This exists because the daemon resolves one skill per request (GH #4505, so
+// each download gets its own size-scaled deadline and caches independently).
+// Serving those out of the agent's full bundle set made the server redo the
+// whole agent on every request: N requests, each reading and hashing all N
+// skills to return one. Loading only what was asked for makes that linear,
+// which is why the resolve path must not reuse LoadAgentSkillBundles.
+func (s *TaskService) LoadRequestedAgentSkillBundles(ctx context.Context, agentID pgtype.UUID, refs []AgentSkillBundleRef) (map[string]AgentSkillData, error) {
+ requestedIDs := make([]pgtype.UUID, 0, len(refs))
+ seenWorkspace := make(map[string]struct{}, len(refs))
+ wantBuiltin := make(map[string]struct{}, len(refs))
+ for _, ref := range refs {
+ switch ref.Source {
+ case skillbundle.SourceBuiltin:
+ wantBuiltin[ref.ID] = struct{}{}
+ case skillbundle.SourceWorkspace:
+ if _, ok := seenWorkspace[ref.ID]; ok {
+ continue
+ }
+ id, err := util.ParseUUID(ref.ID)
+ if err != nil {
+ // An unparseable id matches no row, which is the same outcome
+ // as an id the agent does not have. Skipping it keeps one
+ // malformed ref from failing the refs alongside it.
+ continue
+ }
+ seenWorkspace[ref.ID] = struct{}{}
+ requestedIDs = append(requestedIDs, id)
+ }
+ // Any other source has no server-side producer, so it resolves to
+ // nothing and the caller reports not-found.
+ }
+
+ var requested []AgentSkillData
+ if len(requestedIDs) > 0 {
+ skills, err := s.Queries.ListAgentSkillsByIDs(ctx, db.ListAgentSkillsByIDsParams{
+ AgentID: agentID,
+ SkillIds: requestedIDs,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("list agent skills by ids: %w", err)
+ }
+ if len(skills) > 0 {
+ // Same fail-closed rule as LoadAgentSkills: a failed file read
+ // would produce a bundle that hashes and validates like a complete
+ // one, so it must never be served.
+ loaded, err := s.skillsWithFiles(ctx, skills)
+ if err != nil {
+ return nil, err
+ }
+ requested = append(requested, loaded...)
+ }
+ }
+ if len(wantBuiltin) > 0 {
+ for _, builtin := range s.BuiltinSkills() {
+ if _, ok := wantBuiltin[BuiltinSkillID(builtin.Name)]; ok {
+ requested = append(requested, builtin)
+ }
+ }
+ }
+
+ bundles, _ := BuildAgentSkillBundles(requested)
+ resolved := make(map[string]AgentSkillData, len(bundles))
+ for _, bundle := range bundles {
+ resolved[AgentSkillBundleKey(bundle.Source, bundle.ID)] = bundle
+ }
+ return resolved, nil
+}
+
func BuildAgentSkillBundles(skills []AgentSkillData) ([]AgentSkillData, []AgentSkillRefData) {
bundles := make([]AgentSkillData, 0, len(skills))
refs := make([]AgentSkillRefData, 0, len(skills))
@@ -6402,7 +6500,7 @@ func BuildAgentSkillBundles(skills []AgentSkillData) ([]AgentSkillData, []AgentS
}
}
if id == "" && source == skillbundle.SourceBuiltin {
- id = "builtin:" + skill.Name
+ id = BuiltinSkillID(skill.Name)
}
skill.Source = source
skill.ID = id
diff --git a/server/pkg/db/generated/skill.sql.go b/server/pkg/db/generated/skill.sql.go
index ec5a9c7008..45d7bfec05 100644
--- a/server/pkg/db/generated/skill.sql.go
+++ b/server/pkg/db/generated/skill.sql.go
@@ -326,6 +326,57 @@ func (q *Queries) ListAgentSkills(ctx context.Context, agentID pgtype.UUID) ([]S
return items, nil
}
+const listAgentSkillsByIDs = `-- name: ListAgentSkillsByIDs :many
+SELECT s.id, s.workspace_id, s.name, s.description, s.content, s.config, s.created_by, s.created_at, s.updated_at, s.plugin_installation_id FROM skill s
+JOIN agent_skill ask ON ask.skill_id = s.id
+WHERE ask.agent_id = $1
+ AND ask.enabled = TRUE
+ AND s.id = ANY($2::uuid[])
+ORDER BY s.name ASC
+`
+
+type ListAgentSkillsByIDsParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ SkillIds []pgtype.UUID `json:"skill_ids"`
+}
+
+// Scoped variant of ListAgentSkills: the same junction predicate, narrowed to
+// a set of requested skill IDs. The skill-bundle resolve path asks for one
+// skill per request, so loading the agent's whole set there costs a full read
+// and hash of every skill on every request. The junction predicate is also the
+// authorization: an ID the agent does not have enabled simply returns no row,
+// which the caller reports as not-found.
+func (q *Queries) ListAgentSkillsByIDs(ctx context.Context, arg ListAgentSkillsByIDsParams) ([]Skill, error) {
+ rows, err := q.db.Query(ctx, listAgentSkillsByIDs, arg.AgentID, arg.SkillIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Skill{}
+ for rows.Next() {
+ var i Skill
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.Content,
+ &i.Config,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.PluginInstallationID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listAgentSkillsByWorkspace = `-- name: ListAgentSkillsByWorkspace :many
SELECT ask.agent_id, s.id, s.name, s.description, ask.enabled
FROM agent_skill ask
diff --git a/server/pkg/db/queries/skill.sql b/server/pkg/db/queries/skill.sql
index 70b632f980..a4d795073e 100644
--- a/server/pkg/db/queries/skill.sql
+++ b/server/pkg/db/queries/skill.sql
@@ -114,6 +114,20 @@ JOIN agent_skill ask ON ask.skill_id = s.id
WHERE ask.agent_id = $1 AND ask.enabled = TRUE
ORDER BY s.name ASC;
+-- name: ListAgentSkillsByIDs :many
+-- Scoped variant of ListAgentSkills: the same junction predicate, narrowed to
+-- a set of requested skill IDs. The skill-bundle resolve path asks for one
+-- skill per request, so loading the agent's whole set there costs a full read
+-- and hash of every skill on every request. The junction predicate is also the
+-- authorization: an ID the agent does not have enabled simply returns no row,
+-- which the caller reports as not-found.
+SELECT s.* FROM skill s
+JOIN agent_skill ask ON ask.skill_id = s.id
+WHERE ask.agent_id = $1
+ AND ask.enabled = TRUE
+ AND s.id = ANY(sqlc.arg('skill_ids')::uuid[])
+ORDER BY s.name ASC;
+
-- name: ListAgentSkillSummaries :many
-- Summary variant for the agent skills list endpoint — omits `content` for
-- the same reason as ListSkillSummariesByWorkspace.