merge: bring dev into wait tool branch

This commit is contained in:
Goon committed 2026-05-19 09:18:29 +07:00
commit ed558e6f89
36 files changed
+1041 -73

No files matched your search

+10
View File
@@ -6,6 +6,10 @@ All notable changes to GoClaw are documented here. For full documentation, see [
### Added
- **Skill agent manage grants** — Adds per-agent skill edit/delete grants with
backend checks, HTTP/WS support, SQLite and PostgreSQL schema updates, and web
dashboard controls for granting and revoking manage access.
- **Packages Update Flow (Phase 2a: pip + npm)** — closes #900 (Phase 2a). Extends
Phase 1 update infrastructure to pip and npm package sources. `/v1/packages/updates`
now returns mixed-source results with an `availability: {github, pip, npm}` map.
@@ -77,6 +81,12 @@ All notable changes to GoClaw are documented here. For full documentation, see [
### Fixed
- **Skill grant tenant isolation.** Agent skill grants now validate both the
skill and agent tenant scope before insert, revoke, grant listing, or
can-manage checks. Visibility auto-promote/auto-demote updates are scoped to
the calling tenant or system skills so one tenant cannot mutate another
tenant's skill.
- **Agent provider switching.** Saving an agent after changing provider/model now
handles cleared ChatGPT OAuth routing config without writing SQL NULL into
NOT NULL JSON config columns.
+1 -1
View File
@@ -18,7 +18,7 @@ import (
// GOCLAW_PACKAGES_GITHUB_TOKEN optional PAT (boosts rate limit, enables private repos)
// GOCLAW_PACKAGES_MAX_ASSET_SIZE_MB default 200
// GOCLAW_PACKAGES_GITHUB_ALLOWED_ORGS comma-separated allowlist (empty = all allowed)
// GOCLAW_PACKAGES_GITHUB_BIN_DIR default /app/data/.runtime/bin
// GOCLAW_PACKAGES_GITHUB_BIN_DIR default {runtimeDir}/bin
// GOCLAW_PACKAGES_GITHUB_MANIFEST default {BIN_DIR}/../github-packages.json
func initGitHubInstaller() {
cfg := &skills.GitHubPackagesConfig{
+1 -1
View File
@@ -217,7 +217,7 @@ github:owner/repo[@tag]
```
Admin-only, SHA256-verified, ELF-validated, with a release-picker UI. Binaries
land in `/app/data/.runtime/bin/` (on `$PATH`). See
land in `{runtimeDir}/bin/` (on `$PATH`). See
[`docs/packages-github.md`](./packages-github.md) for syntax, configuration,
security posture, and troubleshooting (especially musl/glibc compatibility).
@@ -0,0 +1,43 @@
# Beta Skill Grants Tenant-Scope Hardening
**Date**: 2026-05-18 17:41
**Severity**: High
**Component**: Skills grants, tenant isolation, skill management UI/API
**Status**: Resolved
## What Happened
This beta ship started from PR #14, which added per-agent skill manage grants so an authorized agent can edit/delete skills even when `owner_id` no longer matches its current actor identity. The review caught the ugly part: the grant path could mutate skill visibility or grant records across tenant boundaries, and the UI/API exposed `owner_id` in skill responses where clients did not need it. Issue digitopvn/goclaw#15 tracks the hardening fallout.
## The Brutal Truth
This was a permission feature shipped close to a tenant-isolation fault line. That is always where mistakes hurt most. The exhausting part is that the baseline feature was useful, but the first version trusted grant inputs too much. A beta is exactly where this should be caught, but it still feels bad because cross-tenant mutation risk is not a cosmetic bug.
## Technical Details
- PG now validates grant scope before insert/update in `internal/store/pg/skills_grants.go:19` and `verifySkillGrantScope` rejects mismatched agent tenants as `agent not found`.
- SQLite mirrors the same check in `internal/store/sqlitestore/skills_grants.go:25`.
- Cleanup migration `migrations/000067_skill_agent_grants_scope_cleanup.up.sql:1` deletes `skill_agent_grants` rows where `sag.tenant_id <> a.tenant_id` or non-system skill tenant differs.
- `internal/store/skill_store.go:19` hides `OwnerID` with `json:"-"`, stopping owner IDs from leaking through skill responses/UI.
- Changelog updated under `CHANGELOG.md`.
## What We Tried
- Kept PR #14's per-agent `can_manage` model because it directly solves agent-owned skill maintenance without pretending `owner_id` is stable agent identity.
- Rejected UI-only filtering because it would not protect HTTP, WebSocket, import, or future callers.
- Added store-layer verification in both PG and SQLite because that is the point every grant mutation must cross.
## Root Cause Analysis
We shipped the first feature around ownership semantics without enforcing the tenant relationship at the same boundary as the write. The fundamental mistake was treating authorization and scope as already resolved by callers. In a multi-tenant system, that assumption is how one tenant ends up mutating another tenant's visibility state.
## Lessons Learned
Grant writes must prove both sides of the relationship: the skill and the agent. Do not rely on caller discipline. Also, response structs should not expose security-sensitive ownership fields just because the database row has them.
## Next Steps
- Owner: maintainers. Monitor digitopvn/goclaw#15 through beta.
- Owner: release lead. Verify beta users receive migration `000067` and no stale cross-tenant rows survive upgrade.
- Owner: reviewers. Treat future grant/import/export changes as tenant-scope sensitive by default.
- Tests/build are passing for this ship; keep PG, SQLite, and Web UI build checks required before promoting beyond beta.
+3 -3
View File
@@ -24,7 +24,7 @@ Examples:
4. Verifies SHA256 if the publisher ships `checksums.txt` / `SHA256SUMS`
5. Validates ELF magic bytes + 64-bit class + machine matches runtime arch
6. Extracts archive safely (tar.gz / zip / raw binary) with path-traversal + zip-bomb guards
7. Installs to `/app/data/.runtime/bin/` (prepended to `$PATH`)
7. Installs to `{runtimeDir}/bin/` (prepended to `$PATH`)
8. Persists a manifest for later listing + uninstall
## Usage
@@ -69,7 +69,7 @@ token in `config.json`.
| `GOCLAW_PACKAGES_GITHUB_TOKEN` | `""` | Optional PAT: rate 60/hr → 5000/hr + private repo access |
| `GOCLAW_PACKAGES_MAX_ASSET_SIZE_MB` | `200` | Applies to both download cap and 2× uncompressed cap |
| `GOCLAW_PACKAGES_GITHUB_ALLOWED_ORGS` | `""` | Comma-separated allowlist (empty = all orgs allowed) |
| `GOCLAW_PACKAGES_GITHUB_BIN_DIR` | `/app/data/.runtime/bin` | Where extracted binaries land |
| `GOCLAW_PACKAGES_GITHUB_BIN_DIR` | `{runtimeDir}/bin` | Where extracted binaries land |
| `GOCLAW_PACKAGES_GITHUB_MANIFEST` | `{bin_dir}/../github-packages.json` | Manifest path |
Token scopes:
@@ -133,7 +133,7 @@ the release. Do not force-install; report upstream.
## Limitations (Phase 1)
- Linux-only (Lite/Desktop editions not yet supported)
- Docker edition only (runtime dir `/app/data/.runtime/bin`)
- Docker and bare-metal gateway editions (default runtime dir resolves to `/app/data/.runtime/bin` in Docker or `/var/lib/goclaw/data/.runtime/bin` on bare-metal Linux)
- Installs all top-level executables in an archive (no interactive picker if
archive contains multiple binaries)
- No version history / rollback — re-installing replaces in place
+31
View File
@@ -6,6 +6,19 @@ Significant changes, features, and fixes in reverse chronological order.
## 2026-05-18
### Packages: GitHub installer runtime path
**Fixes**
- Fixed GitHub Releases package installs on bare-metal gateways by defaulting the GitHub binary directory to `{runtimeDir}/bin` instead of Docker-only `/app/data/.runtime/bin`.
- The fix covers installs such as `github:nextlevelbuilder/goclaw-cli@v0.4.1` on the VPS, where `/app` is not writable or present.
**Tests**
- Added default-path regression coverage and made Unix-socket apk helper tests skip cleanly on Windows environments that cannot bind Unix sockets.
---
### Tools: built-in wait delay
**Features**
@@ -56,6 +69,24 @@ Significant changes, features, and fixes in reverse chronological order.
## 2026-05-17
### Skills: agent manage grants
**Fixes**
- Added explicit per-agent skill manage grants so agents can edit/delete skills they were authorized to maintain even when `owner_id` no longer matches their current actor identity.
- Auto-granted manage permission to the creating/publishing agent for new managed skills.
**UI**
- Show custom skill owner IDs in the Skills table.
- Added Skills page controls to grant agent skill access and edit/delete permission.
**Tests**
- Added PG/SQLite grant coverage and verified Go builds plus Web UI build.
---
### Agents: provider switch save fix
**Fixes**
+2 -2
View File
@@ -17,7 +17,7 @@ import (
// skillOwnerGetter is an optional interface for stores that can return a skill's owner ID.
type skillOwnerGetter interface {
GetSkillOwnerID(id uuid.UUID) (string, bool)
GetSkillOwnerID(ctx context.Context, id uuid.UUID) (string, bool)
}
// SkillsMethods handles skills.list, skills.get, skills.update.
@@ -219,7 +219,7 @@ func (m *SkillsMethods) handleUpdate(ctx context.Context, client *gateway.Client
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrUnauthorized, i18n.T(locale, i18n.MsgPermissionDenied, "skills.update")))
return
}
if ownerID, found := ownerGetter.GetSkillOwnerID(skillID); found && ownerID != client.UserID() {
if ownerID, found := ownerGetter.GetSkillOwnerID(ctx, skillID); found && ownerID != client.UserID() {
client.SendResponse(protocol.NewErrorResponse(req.ID, protocol.ErrUnauthorized, i18n.T(locale, i18n.MsgPermissionDenied, "skills.update")))
return
}
+2 -1
View File
@@ -37,7 +37,7 @@ type SkillsHandler struct {
msgBus *bus.MessageBus
tenantCfgStore store.SkillTenantConfigStore
tenantStore store.TenantStore
db *sql.DB // for export/import direct queries
db *sql.DB // for export/import direct queries
uploadLocks sync.Map // per-slug mutex; bounded by validated slug set, entries are tiny (*sync.Mutex)
}
@@ -92,6 +92,7 @@ func (h *SkillsHandler) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("PUT /v1/skills/{id}", h.adminMiddleware(h.handleUpdate))
mux.HandleFunc("DELETE /v1/skills/{id}", h.adminMiddleware(h.handleDelete))
// Skill grants (admin+)
mux.HandleFunc("GET /v1/skills/{id}/grants/agent", h.adminMiddleware(h.handleListAgentGrants))
mux.HandleFunc("POST /v1/skills/{id}/grants/agent", h.adminMiddleware(h.handleGrantAgent))
mux.HandleFunc("DELETE /v1/skills/{id}/grants/agent/{agentID}", h.adminMiddleware(h.handleRevokeAgent))
mux.HandleFunc("POST /v1/skills/{id}/grants/user", h.adminMiddleware(h.handleGrantUser))
+30 -4
View File
@@ -33,6 +33,25 @@ func (h *SkillsHandler) handleListAgentSkills(w http.ResponseWriter, r *http.Req
writeJSON(w, http.StatusOK, map[string]any{"skills": skills})
}
func (h *SkillsHandler) handleListAgentGrants(w http.ResponseWriter, r *http.Request) {
locale := store.LocaleFromContext(r.Context())
idStr := r.PathValue("id")
skillID, err := uuid.Parse(idStr)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": i18n.T(locale, i18n.MsgInvalidID, "skill")})
return
}
grants, err := h.skills.ListAgentGrantsForSkill(r.Context(), skillID)
if err != nil {
slog.Error("failed to list skill agent grants", "skill_id", skillID, "error", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": i18n.T(locale, i18n.MsgFailedToList, "skill grants")})
return
}
writeJSON(w, http.StatusOK, map[string]any{"grants": grants})
}
func (h *SkillsHandler) handleGrantAgent(w http.ResponseWriter, r *http.Request) {
locale := store.LocaleFromContext(r.Context())
userID := store.UserIDFromContext(r.Context())
@@ -53,8 +72,9 @@ func (h *SkillsHandler) handleGrantAgent(w http.ResponseWriter, r *http.Request)
}
var req struct {
AgentID string `json:"agent_id"`
Version int `json:"version"`
AgentID string `json:"agent_id"`
Version int `json:"version"`
CanManage *bool `json:"can_manage"`
}
if !bindJSON(w, r, locale, &req) {
return
@@ -70,8 +90,14 @@ func (h *SkillsHandler) handleGrantAgent(w http.ResponseWriter, r *http.Request)
req.Version = 1
}
if err := h.skills.GrantToAgent(r.Context(), skillID, agentID, req.Version, userID); err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
var grantErr error
if req.CanManage == nil {
grantErr = h.skills.GrantToAgent(r.Context(), skillID, agentID, req.Version, userID)
} else {
grantErr = h.skills.GrantToAgent(r.Context(), skillID, agentID, req.Version, userID, *req.CanManage)
}
if grantErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": grantErr.Error()})
return
}
+7 -1
View File
@@ -528,7 +528,7 @@ func (s *skillManageStoreStub) StoreMissingDeps(_ context.Context, id uuid.UUID,
s.skills[id] = skill
return nil
}
func (s *skillManageStoreStub) GrantToAgent(context.Context, uuid.UUID, uuid.UUID, int, string) error {
func (s *skillManageStoreStub) GrantToAgent(context.Context, uuid.UUID, uuid.UUID, int, string, ...bool) error {
return nil
}
func (s *skillManageStoreStub) RevokeFromAgent(context.Context, uuid.UUID, uuid.UUID) error {
@@ -541,6 +541,12 @@ func (s *skillManageStoreStub) RevokeFromUser(context.Context, uuid.UUID, string
func (s *skillManageStoreStub) ListWithGrantStatus(context.Context, uuid.UUID) ([]store.SkillWithGrantStatus, error) {
return nil, nil
}
func (s *skillManageStoreStub) ListAgentGrantsForSkill(context.Context, uuid.UUID) ([]store.SkillAgentGrantInfo, error) {
return nil, nil
}
func (s *skillManageStoreStub) AgentCanManageSkill(context.Context, uuid.UUID, uuid.UUID) (bool, error) {
return false, nil
}
func (s *skillManageStoreStub) GetSkillFilePath(context.Context, uuid.UUID) (string, string, int, bool, bool) {
return "", "", 0, false, false
}
+4
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"net"
"runtime"
"strings"
"sync/atomic"
"testing"
@@ -42,6 +43,9 @@ func servePkgHelper(t *testing.T, sockPath, respJSON string) func() {
ln, err := net.Listen("unix", sockPath)
if err != nil {
if runtime.GOOS == "windows" {
t.Skipf("unix sockets are not available in this Windows test environment: %v", err)
}
t.Fatalf("servePkgHelper: listen %q: %v", sockPath, err)
}
+2 -2
View File
@@ -57,7 +57,7 @@ func ParseGitHubSpec(s string) (*GitHubSpec, error) {
// Token is sourced from env var only (never config.json plaintext).
type GitHubPackagesConfig struct {
Token string // optional GitHub personal access token
BinDir string // where to install binaries (default /app/data/.runtime/bin)
BinDir string // where to install binaries (default {runtimeDir}/bin)
ManifestPath string // manifest file path (default {BinDir}/../github-packages.json)
AllowedOrgs []string // lowercase list; empty = all allowed
MaxAssetSizeMB int // default 200
@@ -66,7 +66,7 @@ type GitHubPackagesConfig struct {
// Defaults fills in zero-valued fields.
func (c *GitHubPackagesConfig) Defaults() {
if c.BinDir == "" {
c.BinDir = "/app/data/.runtime/bin"
c.BinDir = filepath.Join(packageRuntimeDir(), "bin")
}
if c.ManifestPath == "" {
c.ManifestPath = filepath.Join(filepath.Dir(c.BinDir), "github-packages.json")
+15 -5
View File
@@ -2,17 +2,18 @@ package skills
import (
"errors"
"path/filepath"
"strings"
"testing"
)
func TestParseGitHubSpec(t *testing.T) {
cases := []struct {
in string
ok bool
owner string
repo string
tag string
in string
ok bool
owner string
repo string
tag string
}{
{"github:cli/cli@v2.45.0", true, "cli", "cli", "v2.45.0"},
{"github:cli/cli", true, "cli", "cli", ""},
@@ -123,11 +124,20 @@ func TestAllowedOrg(t *testing.T) {
}
func TestConfigDefaults(t *testing.T) {
runtimeDir := t.TempDir()
t.Setenv("RUNTIME_DIR", runtimeDir)
c := &GitHubPackagesConfig{}
c.Defaults()
if c.BinDir == "" || c.ManifestPath == "" || c.MaxAssetSizeMB != 200 {
t.Errorf("unexpected defaults: %+v", c)
}
if want := filepath.Join(runtimeDir, "bin"); c.BinDir != want {
t.Errorf("BinDir = %q, want %q", c.BinDir, want)
}
if want := filepath.Join(runtimeDir, "github-packages.json"); c.ManifestPath != want {
t.Errorf("ManifestPath = %q, want %q", c.ManifestPath, want)
}
if c.MaxAssetBytes() != 200*1024*1024 {
t.Errorf("MaxAssetBytes wrong: %d", c.MaxAssetBytes())
}
+2 -1
View File
@@ -4,6 +4,7 @@ import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
@@ -65,7 +66,7 @@ func CheckRuntimes() *RuntimeStatus {
// Check github-bin runtime directory (where GitHub-installed binaries live).
ghInfo := RuntimeInfo{Name: "github-bin"}
binDir := "/app/data/.runtime/bin"
binDir := filepath.Join(packageRuntimeDir(), "bin")
if gh := DefaultGitHubInstaller(); gh != nil && gh.Config != nil && gh.Config.BinDir != "" {
binDir = gh.Config.BinDir
}
+114 -24
View File
@@ -2,6 +2,7 @@ package pg
import (
"context"
"database/sql"
"fmt"
"log/slog"
"time"
@@ -14,38 +15,48 @@ import (
// GrantToAgent grants a skill to an agent with version pinning.
// Auto-promotes visibility from 'private' to 'internal' so the skill
// becomes accessible via ListAccessible for granted agents.
// Validates the agent belongs to the requesting tenant (prevents cross-tenant grant injection).
func (s *PGSkillStore) GrantToAgent(ctx context.Context, skillID, agentID uuid.UUID, version int, grantedBy string) error {
// Validates both the skill and agent belong to the requesting tenant.
func (s *PGSkillStore) GrantToAgent(ctx context.Context, skillID, agentID uuid.UUID, version int, grantedBy string, canManage ...bool) error {
if err := store.ValidateUserID(grantedBy); err != nil {
return err
}
tid := tenantIDForInsert(ctx)
// Verify agent belongs to the requesting tenant.
var agentTenantID uuid.UUID
if err := s.db.QueryRowContext(ctx,
"SELECT tenant_id FROM agents WHERE id = $1", agentID,
).Scan(&agentTenantID); err != nil {
return fmt.Errorf("agent not found")
}
if agentTenantID != tid {
return fmt.Errorf("agent not found")
if err := s.verifySkillGrantScope(ctx, skillID, agentID, tid); err != nil {
return err
}
_, err := s.db.ExecContext(ctx,
`INSERT INTO skill_agent_grants (id, skill_id, agent_id, pinned_version, granted_by, created_at, tenant_id)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (skill_id, agent_id) DO UPDATE SET pinned_version = EXCLUDED.pinned_version`,
store.GenNewID(), skillID, agentID, version, grantedBy, time.Now(), tid,
)
now := time.Now()
var err error
if len(canManage) > 0 {
_, err = s.db.ExecContext(ctx,
`INSERT INTO skill_agent_grants (id, skill_id, agent_id, pinned_version, granted_by, can_manage, created_at, tenant_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (skill_id, agent_id) DO UPDATE SET
pinned_version = EXCLUDED.pinned_version,
granted_by = EXCLUDED.granted_by,
can_manage = EXCLUDED.can_manage`,
store.GenNewID(), skillID, agentID, version, grantedBy, canManage[0], now, tid,
)
} else {
_, err = s.db.ExecContext(ctx,
`INSERT INTO skill_agent_grants (id, skill_id, agent_id, pinned_version, granted_by, created_at, tenant_id)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (skill_id, agent_id) DO UPDATE SET
pinned_version = EXCLUDED.pinned_version,
granted_by = EXCLUDED.granted_by`,
store.GenNewID(), skillID, agentID, version, grantedBy, now, tid,
)
}
if err != nil {
return err
}
// Auto-promote: private → internal (so ListAccessible query includes it for granted agents)
_, err = s.db.ExecContext(ctx,
`UPDATE skills SET visibility = 'internal', updated_at = NOW() WHERE id = $1 AND visibility = 'private'`,
skillID)
`UPDATE skills
SET visibility = 'internal', updated_at = NOW()
WHERE id = $1 AND visibility = 'private' AND (is_system = true OR tenant_id = $2)`,
skillID, tid)
if err != nil {
slog.Warn("skill_grants: failed to auto-promote visibility", "skill_id", skillID, "error", err)
// Non-fatal: grant was already created successfully
@@ -58,6 +69,10 @@ func (s *PGSkillStore) GrantToAgent(ctx context.Context, skillID, agentID uuid.U
// RevokeFromAgent revokes a skill grant from an agent.
// Auto-demotes visibility from 'internal' back to 'private' when no agent grants remain.
func (s *PGSkillStore) RevokeFromAgent(ctx context.Context, skillID, agentID uuid.UUID) error {
tid := tenantIDForInsert(ctx)
if err := s.verifySkillInGrantScope(ctx, skillID, tid); err != nil {
return err
}
tClause, tArgs, _, err := scopeClause(ctx, 3)
if err != nil {
return err
@@ -74,9 +89,9 @@ func (s *PGSkillStore) RevokeFromAgent(ctx context.Context, skillID, agentID uui
// avoiding a race window between COUNT and UPDATE.
_, err = s.db.ExecContext(ctx,
`UPDATE skills SET visibility = 'private', updated_at = NOW()
WHERE id = $1 AND visibility = 'internal'
WHERE id = $1 AND visibility = 'internal' AND (is_system = true OR tenant_id = $2)
AND NOT EXISTS (SELECT 1 FROM skill_agent_grants WHERE skill_id = $1)`,
skillID)
skillID, tid)
if err != nil {
slog.Warn("skill_grants: failed to auto-demote visibility", "skill_id", skillID, "error", err)
}
@@ -85,6 +100,37 @@ func (s *PGSkillStore) RevokeFromAgent(ctx context.Context, skillID, agentID uui
return nil
}
func (s *PGSkillStore) verifySkillGrantScope(ctx context.Context, skillID, agentID, tenantID uuid.UUID) error {
if err := s.verifySkillInGrantScope(ctx, skillID, tenantID); err != nil {
return err
}
var agentTenantID uuid.UUID
if err := s.db.QueryRowContext(ctx,
"SELECT tenant_id FROM agents WHERE id = $1", agentID,
).Scan(&agentTenantID); err != nil {
return fmt.Errorf("agent not found")
}
if agentTenantID != tenantID {
return fmt.Errorf("agent not found")
}
return nil
}
func (s *PGSkillStore) verifySkillInGrantScope(ctx context.Context, skillID, tenantID uuid.UUID) error {
var skillTenantID uuid.UUID
var isSystem bool
if err := s.db.QueryRowContext(ctx,
"SELECT tenant_id, is_system FROM skills WHERE id = $1", skillID,
).Scan(&skillTenantID, &isSystem); err != nil {
return fmt.Errorf("skill not found")
}
if !isSystem && skillTenantID != tenantID {
return fmt.Errorf("skill not found")
}
return nil
}
// ListAgentGrants returns all skill grants for an agent.
func (s *PGSkillStore) ListAgentGrants(ctx context.Context, agentID uuid.UUID) ([]SkillGrantInfo, error) {
tClause, tArgs, _, err := scopeClause(ctx, 2)
@@ -101,6 +147,47 @@ func (s *PGSkillStore) ListAgentGrants(ctx context.Context, agentID uuid.UUID) (
return result, nil
}
// ListAgentGrantsForSkill returns all agent grants for one skill.
func (s *PGSkillStore) ListAgentGrantsForSkill(ctx context.Context, skillID uuid.UUID) ([]store.SkillAgentGrantInfo, error) {
if err := s.verifySkillInGrantScope(ctx, skillID, tenantIDForInsert(ctx)); err != nil {
return nil, err
}
tClause, tArgs, _, err := scopeClause(ctx, 2)
if err != nil {
return nil, err
}
var result []store.SkillAgentGrantInfo
err = pkgSqlxDB.SelectContext(ctx, &result,
"SELECT agent_id, pinned_version, granted_by, can_manage FROM skill_agent_grants WHERE skill_id = $1"+tClause+" ORDER BY created_at DESC",
append([]any{skillID}, tArgs...)...)
if err != nil {
return nil, err
}
return result, nil
}
// AgentCanManageSkill reports whether an agent has explicit edit/delete rights for a skill.
func (s *PGSkillStore) AgentCanManageSkill(ctx context.Context, skillID, agentID uuid.UUID) (bool, error) {
if err := s.verifySkillInGrantScope(ctx, skillID, tenantIDForInsert(ctx)); err != nil {
return false, err
}
tClause, tArgs, _, err := scopeClause(ctx, 3)
if err != nil {
return false, err
}
var canManage bool
err = s.db.QueryRowContext(ctx,
"SELECT can_manage FROM skill_agent_grants WHERE skill_id = $1 AND agent_id = $2"+tClause,
append([]any{skillID, agentID}, tArgs...)...).Scan(&canManage)
if err == sql.ErrNoRows {
return false, nil
}
if err != nil {
return false, err
}
return canManage, nil
}
// GrantToUser grants a skill to a user (for internal visibility skills).
func (s *PGSkillStore) GrantToUser(ctx context.Context, skillID uuid.UUID, userID, grantedBy string) error {
if err := store.ValidateUserID(userID); err != nil {
@@ -210,16 +297,19 @@ func (s *PGSkillStore) ListWithGrantStatus(ctx context.Context, agentID uuid.UUI
return nil, err
}
tenantCond := ""
grantTenantCond := ""
if tc != "" {
tenantCond = fmt.Sprintf(" AND (s.is_system = true OR s.tenant_id = $%d)", 2)
grantTenantCond = fmt.Sprintf(" AND sag.tenant_id = $%d", 2)
}
rows, err := s.db.QueryContext(ctx,
`SELECT s.id, s.name, s.slug, COALESCE(s.description, ''), s.visibility, s.version,
(sag.id IS NOT NULL) AS granted,
COALESCE(sag.can_manage, false) AS can_manage,
sag.pinned_version,
s.is_system
FROM skills s
LEFT JOIN skill_agent_grants sag ON s.id = sag.skill_id AND sag.agent_id = $1
LEFT JOIN skill_agent_grants sag ON s.id = sag.skill_id AND sag.agent_id = $1`+grantTenantCond+`
WHERE s.status = 'active'`+tenantCond+`
ORDER BY s.name`, append([]any{agentID}, tcArgs...)...)
if err != nil {
@@ -230,7 +320,7 @@ func (s *PGSkillStore) ListWithGrantStatus(ctx context.Context, agentID uuid.UUI
var result []store.SkillWithGrantStatus
for rows.Next() {
var r store.SkillWithGrantStatus
if err := rows.Scan(&r.ID, &r.Name, &r.Slug, &r.Description, &r.Visibility, &r.Version, &r.Granted, &r.PinnedVer, &r.IsSystem); err != nil {
if err := rows.Scan(&r.ID, &r.Name, &r.Slug, &r.Description, &r.Visibility, &r.Version, &r.Granted, &r.CanManage, &r.PinnedVer, &r.IsSystem); err != nil {
slog.Warn("skill_grants: scan error in ListWithGrantStatus", "error", err)
continue
}
+13 -2
View File
@@ -16,7 +16,7 @@ type SkillInfo struct {
Source string `json:"source" db:"-"`
Description string `json:"description" db:"description"`
Visibility string `json:"visibility,omitempty" db:"visibility"`
OwnerID string `json:"owner_id,omitempty" db:"owner_id"`
OwnerID string `json:"-" db:"owner_id"`
Tags []string `json:"tags,omitempty" db:"tags"`
Version int `json:"version,omitempty" db:"version"`
IsSystem bool `json:"is_system,omitempty" db:"is_system"`
@@ -89,10 +89,19 @@ type SkillWithGrantStatus struct {
Visibility string `json:"visibility" db:"visibility"`
Version int `json:"version" db:"version"`
Granted bool `json:"granted" db:"granted"`
CanManage bool `json:"can_manage" db:"can_manage"`
PinnedVer *int `json:"pinned_version,omitempty" db:"pinned_version"`
IsSystem bool `json:"is_system" db:"is_system"`
}
// SkillAgentGrantInfo is a grant row for one skill across agents.
type SkillAgentGrantInfo struct {
AgentID uuid.UUID `json:"agent_id" db:"agent_id"`
PinnedVersion int `json:"pinned_version" db:"pinned_version"`
GrantedBy string `json:"granted_by" db:"granted_by"`
CanManage bool `json:"can_manage" db:"can_manage"`
}
// SkillManageStore extends SkillStore with CRUD, ownership, and grant operations
// needed by HTTP upload handlers and agent tools (skill_manage, publish_skill).
// Implemented by both PGSkillStore and SQLiteSkillStore.
@@ -119,11 +128,13 @@ type SkillManageStore interface {
ListSystemSkillDirs(ctx context.Context) map[string]string
StoreMissingDeps(ctx context.Context, id uuid.UUID, missing []string) error
// Grants
GrantToAgent(ctx context.Context, skillID, agentID uuid.UUID, version int, grantedBy string) error
GrantToAgent(ctx context.Context, skillID, agentID uuid.UUID, version int, grantedBy string, canManage ...bool) error
RevokeFromAgent(ctx context.Context, skillID, agentID uuid.UUID) error
GrantToUser(ctx context.Context, skillID uuid.UUID, userID, grantedBy string) error
RevokeFromUser(ctx context.Context, skillID uuid.UUID, userID string) error
ListWithGrantStatus(ctx context.Context, agentID uuid.UUID) ([]SkillWithGrantStatus, error)
ListAgentGrantsForSkill(ctx context.Context, skillID uuid.UUID) ([]SkillAgentGrantInfo, error)
AgentCanManageSkill(ctx context.Context, skillID, agentID uuid.UUID) (bool, error)
// Files
GetSkillFilePath(ctx context.Context, id uuid.UUID) (filePath string, slug string, version int, isSystem bool, ok bool)
}
+17 -1
View File
@@ -16,7 +16,7 @@ var schemaSQL string
// SchemaVersion is the current SQLite schema version.
// Bump this when adding new migration steps below.
const SchemaVersion = 34
const SchemaVersion = 36
// migrations maps version → SQL to apply when upgrading FROM that version.
// schema.sql always represents the LATEST full schema (for fresh DBs).
@@ -596,6 +596,20 @@ CREATE INDEX IF NOT EXISTS idx_ws_activity_retention ON workstation_activity(c
// Version 33 → 34: per-agent ordered provider/model fallback config.
33: `ALTER TABLE agents ADD COLUMN model_fallback TEXT NOT NULL DEFAULT '{}';`,
// Version 34 → 35: agent skill grants can optionally allow skill management.
34: `ALTER TABLE skill_agent_grants ADD COLUMN can_manage INTEGER NOT NULL DEFAULT 0;`,
// Version 35 → 36: remove legacy cross-tenant skill-agent grant rows.
35: `DELETE FROM skill_agent_grants
WHERE id IN (
SELECT sag.id
FROM skill_agent_grants sag
JOIN skills s ON sag.skill_id = s.id
JOIN agents a ON sag.agent_id = a.id
WHERE sag.tenant_id <> a.tenant_id
OR (s.is_system = 0 AND sag.tenant_id <> s.tenant_id)
);`,
// Version 23 → 24: vault_documents scope/ownership consistency triggers.
// Mirrors PG migration 000055 CHECK constraint; SQLite cannot add CHECK via
// ALTER TABLE so we use BEFORE INSERT + BEFORE UPDATE triggers instead.
@@ -975,6 +989,8 @@ func idempotentColumnMigration(version int) (string, string, bool) {
return "webhooks", "encrypted_secret", true
case 33:
return "agents", "model_fallback", true
case 34:
return "skill_agent_grants", "can_manage", true
default:
return "", "", false
}
+1
View File
@@ -408,6 +408,7 @@ CREATE TABLE IF NOT EXISTS skill_agent_grants (
agent_id TEXT NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
pinned_version INT NOT NULL,
granted_by VARCHAR(255) NOT NULL,
can_manage INTEGER NOT NULL DEFAULT 0,
tenant_id TEXT NOT NULL REFERENCES tenants(id),
created_at TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
UNIQUE(skill_id, agent_id)
+127 -14
View File
@@ -4,6 +4,8 @@ package sqlitestore
import (
"context"
"database/sql"
"fmt"
"log/slog"
"time"
@@ -20,27 +22,48 @@ type SkillGrantInfo struct {
}
// GrantToAgent grants a skill to an agent with version pinning.
func (s *SQLiteSkillStore) GrantToAgent(ctx context.Context, skillID, agentID uuid.UUID, version int, grantedBy string) error {
func (s *SQLiteSkillStore) GrantToAgent(ctx context.Context, skillID, agentID uuid.UUID, version int, grantedBy string, canManage ...bool) error {
if err := store.ValidateUserID(grantedBy); err != nil {
return err
}
// Upsert grant.
id := store.GenNewID()
_, err := s.db.ExecContext(ctx,
`INSERT INTO skill_agent_grants (id, skill_id, agent_id, pinned_version, granted_by, created_at, tenant_id)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (skill_id, agent_id) DO UPDATE SET pinned_version = excluded.pinned_version`,
id, skillID, agentID, version, grantedBy, time.Now().UTC(), tenantIDForInsert(ctx),
)
now := time.Now().UTC()
tid := tenantIDForInsert(ctx)
if err := s.verifySkillGrantScope(ctx, skillID, agentID, tid); err != nil {
return err
}
var err error
if len(canManage) > 0 {
_, err = s.db.ExecContext(ctx,
`INSERT INTO skill_agent_grants (id, skill_id, agent_id, pinned_version, granted_by, can_manage, created_at, tenant_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (skill_id, agent_id) DO UPDATE SET
pinned_version = excluded.pinned_version,
granted_by = excluded.granted_by,
can_manage = excluded.can_manage`,
id, skillID, agentID, version, grantedBy, canManage[0], now, tid,
)
} else {
_, err = s.db.ExecContext(ctx,
`INSERT INTO skill_agent_grants (id, skill_id, agent_id, pinned_version, granted_by, created_at, tenant_id)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (skill_id, agent_id) DO UPDATE SET
pinned_version = excluded.pinned_version,
granted_by = excluded.granted_by`,
id, skillID, agentID, version, grantedBy, now, tid,
)
}
if err != nil {
return err
}
// Auto-promote: private → internal.
_, err = s.db.ExecContext(ctx,
`UPDATE skills SET visibility = 'internal', updated_at = ? WHERE id = ? AND visibility = 'private'`,
time.Now().UTC(), skillID)
`UPDATE skills
SET visibility = 'internal', updated_at = ?
WHERE id = ? AND visibility = 'private' AND (is_system = 1 OR tenant_id = ?)`,
time.Now().UTC(), skillID, tid)
if err != nil {
slog.Warn("skill_grants: failed to auto-promote visibility", "skill_id", skillID, "error", err)
}
@@ -51,6 +74,10 @@ func (s *SQLiteSkillStore) GrantToAgent(ctx context.Context, skillID, agentID uu
// RevokeFromAgent revokes a skill grant from an agent.
func (s *SQLiteSkillStore) RevokeFromAgent(ctx context.Context, skillID, agentID uuid.UUID) error {
tid := tenantIDForInsert(ctx)
if err := s.verifySkillInGrantScope(ctx, skillID, tid); err != nil {
return err
}
tClause, tArgs, err := scopeClause(ctx)
if err != nil {
return err
@@ -65,9 +92,9 @@ func (s *SQLiteSkillStore) RevokeFromAgent(ctx context.Context, skillID, agentID
// Auto-demote: internal → private when no grants remain.
_, err = s.db.ExecContext(ctx,
`UPDATE skills SET visibility = 'private', updated_at = ?
WHERE id = ? AND visibility = 'internal'
WHERE id = ? AND visibility = 'internal' AND (is_system = 1 OR tenant_id = ?)
AND NOT EXISTS (SELECT 1 FROM skill_agent_grants WHERE skill_id = ?)`,
time.Now().UTC(), skillID, skillID)
time.Now().UTC(), skillID, tid, skillID)
if err != nil {
slog.Warn("skill_grants: failed to auto-demote visibility", "skill_id", skillID, "error", err)
}
@@ -76,6 +103,37 @@ func (s *SQLiteSkillStore) RevokeFromAgent(ctx context.Context, skillID, agentID
return nil
}
func (s *SQLiteSkillStore) verifySkillGrantScope(ctx context.Context, skillID, agentID, tenantID uuid.UUID) error {
if err := s.verifySkillInGrantScope(ctx, skillID, tenantID); err != nil {
return err
}
var agentTenantID uuid.UUID
if err := s.db.QueryRowContext(ctx,
"SELECT tenant_id FROM agents WHERE id = ?", agentID,
).Scan(&agentTenantID); err != nil {
return fmt.Errorf("agent not found")
}
if agentTenantID != tenantID {
return fmt.Errorf("agent not found")
}
return nil
}
func (s *SQLiteSkillStore) verifySkillInGrantScope(ctx context.Context, skillID, tenantID uuid.UUID) error {
var skillTenantID uuid.UUID
var isSystem bool
if err := s.db.QueryRowContext(ctx,
"SELECT tenant_id, is_system FROM skills WHERE id = ?", skillID,
).Scan(&skillTenantID, &isSystem); err != nil {
return fmt.Errorf("skill not found")
}
if !isSystem && skillTenantID != tenantID {
return fmt.Errorf("skill not found")
}
return nil
}
// ListAgentGrants returns all skill grants for an agent.
func (s *SQLiteSkillStore) ListAgentGrants(ctx context.Context, agentID uuid.UUID) ([]SkillGrantInfo, error) {
tClause, tArgs, err := scopeClause(ctx)
@@ -102,6 +160,57 @@ func (s *SQLiteSkillStore) ListAgentGrants(ctx context.Context, agentID uuid.UUI
return result, rows.Err()
}
// ListAgentGrantsForSkill returns all agent grants for one skill.
func (s *SQLiteSkillStore) ListAgentGrantsForSkill(ctx context.Context, skillID uuid.UUID) ([]store.SkillAgentGrantInfo, error) {
if err := s.verifySkillInGrantScope(ctx, skillID, tenantIDForInsert(ctx)); err != nil {
return nil, err
}
tClause, tArgs, err := scopeClause(ctx)
if err != nil {
return nil, err
}
rows, err := s.db.QueryContext(ctx,
"SELECT agent_id, pinned_version, granted_by, can_manage FROM skill_agent_grants WHERE skill_id = ?"+tClause+" ORDER BY created_at DESC",
append([]any{skillID}, tArgs...)...)
if err != nil {
return nil, err
}
defer rows.Close()
var result []store.SkillAgentGrantInfo
for rows.Next() {
var g store.SkillAgentGrantInfo
if err := rows.Scan(&g.AgentID, &g.PinnedVersion, &g.GrantedBy, &g.CanManage); err != nil {
slog.Warn("skill_grants: scan error in ListAgentGrantsForSkill", "error", err)
continue
}
result = append(result, g)
}
return result, rows.Err()
}
// AgentCanManageSkill reports whether an agent has explicit edit/delete rights for a skill.
func (s *SQLiteSkillStore) AgentCanManageSkill(ctx context.Context, skillID, agentID uuid.UUID) (bool, error) {
if err := s.verifySkillInGrantScope(ctx, skillID, tenantIDForInsert(ctx)); err != nil {
return false, err
}
tClause, tArgs, err := scopeClause(ctx)
if err != nil {
return false, err
}
var canManage bool
err = s.db.QueryRowContext(ctx,
"SELECT can_manage FROM skill_agent_grants WHERE skill_id = ? AND agent_id = ?"+tClause,
append([]any{skillID, agentID}, tArgs...)...).Scan(&canManage)
if err == sql.ErrNoRows {
return false, nil
}
if err != nil {
return false, err
}
return canManage, nil
}
// GrantToUser grants a skill to a user.
func (s *SQLiteSkillStore) GrantToUser(ctx context.Context, skillID uuid.UUID, userID, grantedBy string) error {
if err := store.ValidateUserID(userID); err != nil {
@@ -201,23 +310,27 @@ func (s *SQLiteSkillStore) ListWithGrantStatus(ctx context.Context, agentID uuid
return nil, err
}
tenantCond := ""
grantTenantCond := ""
if len(tArgs) > 0 {
tenantCond = " AND (s.is_system = 1 OR s.tenant_id = ?)"
grantTenantCond = " AND sag.tenant_id = ?"
}
_ = tClause
queryArgs := []any{agentID}
if len(tArgs) > 0 {
queryArgs = append(queryArgs, tArgs...)
queryArgs = append(queryArgs, tArgs...)
}
rows, err := s.db.QueryContext(ctx,
`SELECT s.id, s.name, s.slug, COALESCE(s.description, ''), s.visibility, s.version,
(sag.id IS NOT NULL) AS granted,
COALESCE(sag.can_manage, 0) AS can_manage,
sag.pinned_version,
s.is_system
FROM skills s
LEFT JOIN skill_agent_grants sag ON s.id = sag.skill_id AND sag.agent_id = ?
LEFT JOIN skill_agent_grants sag ON s.id = sag.skill_id AND sag.agent_id = ?`+grantTenantCond+`
WHERE s.status = 'active'`+tenantCond+`
ORDER BY s.name`, queryArgs...)
if err != nil {
@@ -229,7 +342,7 @@ func (s *SQLiteSkillStore) ListWithGrantStatus(ctx context.Context, agentID uuid
for rows.Next() {
var r store.SkillWithGrantStatus
if err := rows.Scan(&r.ID, &r.Name, &r.Slug, &r.Description, &r.Visibility,
&r.Version, &r.Granted, &r.PinnedVer, &r.IsSystem); err != nil {
&r.Version, &r.Granted, &r.CanManage, &r.PinnedVer, &r.IsSystem); err != nil {
slog.Warn("skill_grants: scan error in ListWithGrantStatus", "error", err)
continue
}
+137 -1
View File
@@ -4,10 +4,13 @@ package sqlitestore
import (
"context"
"database/sql"
"path/filepath"
"reflect"
"testing"
"github.com/google/uuid"
"github.com/nextlevelbuilder/goclaw/internal/store"
)
@@ -67,7 +70,119 @@ func TestSQLiteSkillStore_CreateSkillManaged_PersistsArchivedDependencyState(t *
}
}
func TestSQLiteSkillStore_GrantToAgentRejectsCrossTenantSkill(t *testing.T) {
_, skillStore, db := newTestSQLiteSkillStoreWithDB(t)
tenantA, agentA := seedSQLiteTenantAgent(t, db)
tenantB, _ := seedSQLiteTenantAgent(t, db)
ctxA := store.WithTenantID(context.Background(), tenantA)
ctxB := store.WithTenantID(context.Background(), tenantB)
skillID, err := skillStore.CreateSkillManaged(ctxB, store.SkillCreateParams{
Name: "Tenant B Skill",
Slug: "tenant-b-skill-" + tenantB.String()[:8],
OwnerID: "user-1",
Visibility: "private",
FilePath: filepath.Join(t.TempDir(), "tenant-b-skill", "1"),
})
if err != nil {
t.Fatalf("CreateSkillManaged error: %v", err)
}
if err := skillStore.GrantToAgent(ctxA, skillID, agentA, 1, "user-1", true); err == nil {
t.Fatal("GrantToAgent allowed tenant A to grant tenant B skill")
}
grants, err := skillStore.ListAgentGrantsForSkill(ctxB, skillID)
if err != nil {
t.Fatalf("ListAgentGrantsForSkill error: %v", err)
}
if len(grants) != 0 {
t.Fatalf("cross-tenant grant was inserted: %+v", grants)
}
got, ok := skillStore.GetSkillByID(ctxB, skillID)
if !ok {
t.Fatal("GetSkillByID returned !ok")
}
if got.Visibility != "private" {
t.Fatalf("cross-tenant grant changed visibility to %q, want private", got.Visibility)
}
}
func TestSQLiteSkillStore_RevokeFromAgentDoesNotDemoteCrossTenantSkill(t *testing.T) {
_, skillStore, db := newTestSQLiteSkillStoreWithDB(t)
tenantA, agentA := seedSQLiteTenantAgent(t, db)
tenantB, _ := seedSQLiteTenantAgent(t, db)
ctxA := store.WithTenantID(context.Background(), tenantA)
ctxB := store.WithTenantID(context.Background(), tenantB)
skillID, err := skillStore.CreateSkillManaged(ctxB, store.SkillCreateParams{
Name: "Tenant B Skill",
Slug: "tenant-b-revoke-skill-" + tenantB.String()[:8],
OwnerID: "user-1",
Visibility: "internal",
FilePath: filepath.Join(t.TempDir(), "tenant-b-revoke-skill", "1"),
})
if err != nil {
t.Fatalf("CreateSkillManaged error: %v", err)
}
if err := skillStore.RevokeFromAgent(ctxA, skillID, agentA); err == nil {
t.Fatal("RevokeFromAgent allowed tenant A to revoke tenant B skill")
}
got, ok := skillStore.GetSkillByID(ctxB, skillID)
if !ok {
t.Fatal("GetSkillByID returned !ok")
}
if got.Visibility != "internal" {
t.Fatalf("cross-tenant revoke demoted visibility to %q, want internal", got.Visibility)
}
}
func TestSQLiteSkillStore_ListWithGrantStatusIgnoresForeignTenantGrant(t *testing.T) {
_, skillStore, db := newTestSQLiteSkillStoreWithDB(t)
tenantA, _ := seedSQLiteTenantAgent(t, db)
tenantB, agentB := seedSQLiteTenantAgent(t, db)
ctxA := store.WithTenantID(context.Background(), tenantA)
skillID := uuid.New()
if _, err := db.Exec(
`INSERT INTO skills (id, name, slug, owner_id, visibility, version, status, file_path, is_system, tenant_id)
VALUES (?, 'System Skill', ?, 'system', 'internal', 1, 'active', ?, 1, ?)`,
skillID.String(), "system-grant-status-"+skillID.String()[:8], filepath.Join(t.TempDir(), "system-skill", "1"), store.MasterTenantID.String(),
); err != nil {
t.Fatalf("insert system skill: %v", err)
}
if _, err := db.Exec(
`INSERT INTO skill_agent_grants (id, skill_id, agent_id, pinned_version, granted_by, can_manage, tenant_id)
VALUES (?, ?, ?, 1, 'tenant-b-admin', 1, ?)`,
uuid.New().String(), skillID.String(), agentB.String(), tenantB.String(),
); err != nil {
t.Fatalf("insert foreign tenant grant: %v", err)
}
skills, err := skillStore.ListWithGrantStatus(ctxA, agentB)
if err != nil {
t.Fatalf("ListWithGrantStatus error: %v", err)
}
for _, skill := range skills {
if skill.ID == skillID {
if skill.Granted || skill.CanManage {
t.Fatalf("foreign tenant grant leaked into tenant A status: granted=%v canManage=%v", skill.Granted, skill.CanManage)
}
return
}
}
t.Fatalf("system skill %s not returned for tenant A", skillID)
}
func newTestSQLiteSkillStore(t *testing.T) (context.Context, *SQLiteSkillStore) {
ctx, skillStore, _ := newTestSQLiteSkillStoreWithDB(t)
return ctx, skillStore
}
func newTestSQLiteSkillStoreWithDB(t *testing.T) (context.Context, *SQLiteSkillStore, *sql.DB) {
t.Helper()
db, err := OpenDB(filepath.Join(t.TempDir(), "skills.db"))
@@ -79,5 +194,26 @@ func newTestSQLiteSkillStore(t *testing.T) (context.Context, *SQLiteSkillStore)
t.Fatalf("EnsureSchema error: %v", err)
}
return store.WithTenantID(context.Background(), store.MasterTenantID), NewSQLiteSkillStore(db, t.TempDir())
return store.WithTenantID(context.Background(), store.MasterTenantID), NewSQLiteSkillStore(db, t.TempDir()), db
}
func seedSQLiteTenantAgent(t *testing.T, db *sql.DB) (uuid.UUID, uuid.UUID) {
t.Helper()
tenantID := uuid.New()
agentID := uuid.New()
if _, err := db.Exec(
`INSERT INTO tenants (id, name, slug, status) VALUES (?, ?, ?, 'active')`,
tenantID.String(), "tenant-"+tenantID.String()[:8], "t"+tenantID.String()[:8],
); err != nil {
t.Fatalf("insert tenant: %v", err)
}
if _, err := db.Exec(
`INSERT INTO agents (id, tenant_id, agent_key, agent_type, status, provider, model, owner_id)
VALUES (?, ?, ?, 'predefined', 'active', 'test', 'test-model', 'user-1')`,
agentID.String(), tenantID.String(), "agent-"+agentID.String()[:8],
); err != nil {
t.Fatalf("insert agent: %v", err)
}
return tenantID, agentID
}
+1 -1
View File
@@ -170,7 +170,7 @@ func (t *PublishSkillTool) Execute(ctx context.Context, args map[string]any) *Re
// Auto-grant to calling agent (granted-by = owner, same as CreateSkillManaged)
agentID := store.AgentIDFromContext(ctx)
if agentID != uuid.Nil {
if err := t.skills.GrantToAgent(ctx, id, agentID, version, ownerID); err != nil {
if err := t.skills.GrantToAgent(ctx, id, agentID, version, ownerID, true); err != nil {
slog.Warn("publish_skill: auto-grant failed", "error", err)
}
}
+26 -3
View File
@@ -51,6 +51,29 @@ func isOwnerOfSkill(ctx context.Context, skills store.SkillManageStore, slug str
return ownerID == actorID || ownerID == userID || ownerID == senderID
}
func canManageSkill(ctx context.Context, skills store.SkillManageStore, info *store.SkillInfo) bool {
if isOwnerOfSkill(ctx, skills, info.Slug) {
return true
}
if info.ID == "" {
return false
}
skillID, err := uuid.Parse(info.ID)
if err != nil {
return false
}
agentID := store.AgentIDFromContext(ctx)
if agentID == uuid.Nil {
return false
}
ok, err := skills.AgentCanManageSkill(ctx, skillID, agentID)
if err != nil {
slog.Warn("skill_manage: manage grant check failed", "skill", info.Slug, "agent_id", agentID, "error", err)
return false
}
return ok
}
// tenantSkillsDir returns the skills-store directory scoped to the calling agent's tenant.
func (t *SkillManageTool) tenantSkillsDir(ctx context.Context) string {
tid := store.TenantIDFromContext(ctx)
@@ -211,7 +234,7 @@ func (t *SkillManageTool) executeCreate(ctx context.Context, args map[string]any
granted := false
agentID := store.AgentIDFromContext(ctx)
if agentID != uuid.Nil {
if err := t.skills.GrantToAgent(ctx, id, agentID, version, ownerID); err != nil {
if err := t.skills.GrantToAgent(ctx, id, agentID, version, ownerID, true); err != nil {
slog.Warn("skill_manage: auto-grant failed", "error", err)
} else {
granted = true
@@ -278,7 +301,7 @@ func (t *SkillManageTool) executePatch(ctx context.Context, args map[string]any)
// where DM owners got the raw channel sender)
// A DM user merged to "viettx" with Telegram ID "386246614" matches all
// three of their skills regardless of when they were created.
if !isOwnerOfSkill(ctx, t.skills, slug) {
if !canManageSkill(ctx, t.skills, info) {
return ErrorResult(fmt.Sprintf("cannot manage skill %q: you are not the owner", slug))
}
@@ -392,7 +415,7 @@ func (t *SkillManageTool) executeDelete(ctx context.Context, args map[string]any
// Ownership check: only the skill owner can delete.
// Same three-identity match as the patch flow above (#915).
if !isOwnerOfSkill(ctx, t.skills, slug) {
if !canManageSkill(ctx, t.skills, info) {
return ErrorResult(fmt.Sprintf("cannot manage skill %q: you are not the owner", slug))
}
+1 -1
View File
@@ -2,4 +2,4 @@ package upgrade
// RequiredSchemaVersion is the schema migration version this binary requires.
// Bump this whenever adding a new SQL migration file.
const RequiredSchemaVersion uint = 65
const RequiredSchemaVersion uint = 67
@@ -0,0 +1,2 @@
ALTER TABLE skill_agent_grants
DROP COLUMN IF EXISTS can_manage;
@@ -0,0 +1,2 @@
ALTER TABLE skill_agent_grants
ADD COLUMN IF NOT EXISTS can_manage BOOLEAN NOT NULL DEFAULT FALSE;
@@ -0,0 +1 @@
-- Irreversible cleanup migration.
@@ -0,0 +1,8 @@
DELETE FROM skill_agent_grants sag
USING skills s, agents a
WHERE sag.skill_id = s.id
AND sag.agent_id = a.id
AND (
sag.tenant_id <> a.tenant_id
OR (s.is_system = false AND sag.tenant_id <> s.tenant_id)
);
+129
View File
@@ -271,6 +271,9 @@ func TestStoreSkill_GrantToAgent(t *testing.T) {
if !g.Granted {
t.Error("expected Granted=true for granted skill")
}
if g.CanManage {
t.Error("expected CanManage=false by default")
}
found = true
break
}
@@ -295,6 +298,37 @@ func TestStoreSkill_GrantToAgent(t *testing.T) {
t.Error("granted skill not found in ListAccessible")
}
if err := s.GrantToAgent(ctx, skillID, agentID, 1, "test-owner", true); err != nil {
t.Fatalf("GrantToAgent can_manage: %v", err)
}
canManage, err := s.AgentCanManageSkill(ctx, skillID, agentID)
if err != nil {
t.Fatalf("AgentCanManageSkill: %v", err)
}
if !canManage {
t.Error("expected AgentCanManageSkill=true after manage grant")
}
if err := s.GrantToAgent(ctx, skillID, agentID, 1, "test-owner"); err != nil {
t.Fatalf("GrantToAgent preserve can_manage: %v", err)
}
canManage, err = s.AgentCanManageSkill(ctx, skillID, agentID)
if err != nil {
t.Fatalf("AgentCanManageSkill after preserve grant: %v", err)
}
if !canManage {
t.Error("expected omitted can_manage grant update to preserve existing manage permission")
}
if err := s.GrantToAgent(ctx, skillID, agentID, 1, "test-owner", false); err != nil {
t.Fatalf("GrantToAgent can_manage false: %v", err)
}
canManage, err = s.AgentCanManageSkill(ctx, skillID, agentID)
if err != nil {
t.Fatalf("AgentCanManageSkill after false grant: %v", err)
}
if canManage {
t.Error("expected explicit can_manage=false to revoke manage permission")
}
// Revoke
if err := s.RevokeFromAgent(ctx, skillID, agentID); err != nil {
t.Fatalf("RevokeFromAgent: %v", err)
@@ -312,6 +346,101 @@ func TestStoreSkill_GrantToAgent(t *testing.T) {
}
}
func TestStoreSkill_GrantToAgentRejectsCrossTenantSkill(t *testing.T) {
db := testDB(t)
tenantA, agentA := seedTenantAgent(t, db)
tenantB, _ := seedTenantAgent(t, db)
ctxA := tenantCtx(tenantA)
ctxB := tenantCtx(tenantB)
s := newSkillStore(t)
skillB := seedSkill(t, s, ctxB, "grant-cross-tenant-"+tenantB.String()[:8], "Tenant B Skill")
if err := s.GrantToAgent(ctxA, skillB, agentA, 1, "test-owner", true); err == nil {
t.Fatal("GrantToAgent allowed tenant A to grant tenant B skill")
}
grants, err := s.ListAgentGrantsForSkill(ctxB, skillB)
if err != nil {
t.Fatalf("ListAgentGrantsForSkill: %v", err)
}
if len(grants) != 0 {
t.Fatalf("cross-tenant grant was inserted: %+v", grants)
}
got, ok := s.GetSkillByID(ctxB, skillB)
if !ok {
t.Fatal("GetSkillByID for tenant B skill returned false")
}
if got.Visibility != "private" {
t.Fatalf("cross-tenant grant changed visibility to %q, want private", got.Visibility)
}
}
func TestStoreSkill_RevokeFromAgentDoesNotDemoteCrossTenantSkill(t *testing.T) {
db := testDB(t)
tenantA, agentA := seedTenantAgent(t, db)
tenantB, _ := seedTenantAgent(t, db)
ctxA := tenantCtx(tenantA)
ctxB := tenantCtx(tenantB)
s := newSkillStore(t)
skillB := seedSkill(t, s, ctxB, "revoke-cross-tenant-"+tenantB.String()[:8], "Tenant B Skill")
if err := s.UpdateSkill(ctxB, skillB, map[string]any{"visibility": "internal"}); err != nil {
t.Fatalf("UpdateSkill: %v", err)
}
if err := s.RevokeFromAgent(ctxA, skillB, agentA); err == nil {
t.Fatal("RevokeFromAgent allowed tenant A to revoke tenant B skill")
}
got, ok := s.GetSkillByID(ctxB, skillB)
if !ok {
t.Fatal("GetSkillByID for tenant B skill returned false")
}
if got.Visibility != "internal" {
t.Fatalf("cross-tenant revoke demoted visibility to %q, want internal", got.Visibility)
}
}
func TestStoreSkill_ListWithGrantStatusIgnoresForeignTenantGrant(t *testing.T) {
db := testDB(t)
tenantA, _ := seedTenantAgent(t, db)
tenantB, agentB := seedTenantAgent(t, db)
ctxA := tenantCtx(tenantA)
s := newSkillStore(t)
skillID := uuid.New()
if _, err := db.Exec(
`INSERT INTO skills (id, name, slug, owner_id, visibility, version, status, file_path, is_system, tenant_id)
VALUES ($1, 'System Skill', $2, 'system', 'internal', 1, 'active', $3, true, $4)`,
skillID, "system-grant-status-"+skillID.String()[:8], "/tmp/skills/system-skill/1", store.MasterTenantID,
); err != nil {
t.Fatalf("insert system skill: %v", err)
}
if _, err := db.Exec(
`INSERT INTO skill_agent_grants (id, skill_id, agent_id, pinned_version, granted_by, can_manage, tenant_id)
VALUES ($1, $2, $3, 1, 'tenant-b-admin', true, $4)`,
uuid.New(), skillID, agentB, tenantB,
); err != nil {
t.Fatalf("insert foreign tenant grant: %v", err)
}
skills, err := s.ListWithGrantStatus(ctxA, agentB)
if err != nil {
t.Fatalf("ListWithGrantStatus error: %v", err)
}
for _, skill := range skills {
if skill.ID == skillID {
if skill.Granted || skill.CanManage {
t.Fatalf("foreign tenant grant leaked into tenant A status: granted=%v canManage=%v", skill.Granted, skill.CanManage)
}
return
}
}
t.Fatalf("system skill %s not returned for tenant A", skillID)
}
func TestStoreSkill_TenantIsolation(t *testing.T) {
db := testDB(t)
tenantA, _ := seedTenantAgent(t, db)
+20
View File
@@ -11,11 +11,31 @@
"description": "Description",
"source": "Source",
"author": "Author",
"owner": "Owner",
"visibility": "Visibility",
"status": "Status",
"actions": "Actions"
},
"noDescription": "No description",
"owner": "Owner",
"unknownOwner": "Unknown",
"grants": {
"title": "Agent access for {{name}}",
"manage": "Manage agent access",
"current": "Current agent grants",
"none": "No agent grants yet.",
"add": "Add grant",
"update": "Update grant",
"grant": "Grant",
"save": "Save",
"revoke": "Revoke grant",
"selectAgent": "Select agent",
"allowManage": "Allow this agent to edit or delete the skill",
"canManage": "Can edit",
"loadFailed": "Failed to load grants",
"saveFailed": "Failed to save grant",
"revokeFailed": "Failed to revoke grant"
},
"visibility": {
"clickToCycle": "Click to change visibility"
},
+21 -1
View File
@@ -13,7 +13,8 @@
"author": "Tác giả",
"visibility": "Hiển thị",
"status": "Trạng thái",
"actions": "Thao tác"
"actions": "Thao tác",
"owner": "Chủ sở hữu"
},
"noDescription": "Không có mô tả",
"visibility": {
@@ -125,5 +126,24 @@
"rescanUpdated": "Đã cập nhật {{count}} skill",
"rescanNoChanges": "Tất cả skill đã cập nhật",
"rescanFailed": "Không thể quét lại dependencies"
},
"owner": "Chủ sở hữu",
"unknownOwner": "Không rõ",
"grants": {
"title": "Quyền agent cho {{name}}",
"manage": "Quản lý quyền agent",
"current": "Grant agent hiện tại",
"none": "Chưa có grant agent.",
"add": "Thêm grant",
"update": "Cập nhật grant",
"grant": "Grant",
"save": "Lưu",
"revoke": "Thu hồi grant",
"selectAgent": "Chọn agent",
"allowManage": "Cho phép agent này sửa hoặc xóa skill",
"canManage": "Được sửa",
"loadFailed": "Không thể tải grant",
"saveFailed": "Không thể lưu grant",
"revokeFailed": "Không thể thu hồi grant"
}
}
+21 -1
View File
@@ -13,7 +13,8 @@
"author": "作者",
"visibility": "可见性",
"status": "状态",
"actions": "操作"
"actions": "操作",
"owner": "所有者"
},
"noDescription": "暂无描述",
"visibility": {
@@ -125,5 +126,24 @@
"rescanUpdated": "已更新 {{count}} 个技能",
"rescanNoChanges": "所有技能已是最新",
"rescanFailed": "重新扫描依赖失败"
},
"owner": "所有者",
"unknownOwner": "未知",
"grants": {
"title": "{{name}} 的 Agent 权限",
"manage": "管理 Agent 权限",
"current": "当前 Agent 授权",
"none": "暂无 Agent 授权。",
"add": "添加授权",
"update": "更新授权",
"grant": "授权",
"save": "保存",
"revoke": "撤销授权",
"selectAgent": "选择 Agent",
"allowManage": "允许此 Agent 编辑或删除 Skill",
"canManage": "可编辑",
"loadFailed": "无法加载授权",
"saveFailed": "无法保存授权",
"revokeFailed": "无法撤销授权"
}
}
+30 -1
View File
@@ -7,7 +7,7 @@ import { queryKeys } from "@/lib/query-keys";
import { toast } from "@/stores/use-toast-store";
import i18next from "i18next";
import { userFriendlyError } from "@/lib/error-utils";
import type { SkillInfo, SkillFile, SkillVersions } from "@/types/skill";
import type { SkillInfo, SkillFile, SkillVersions, SkillAgentGrant } from "@/types/skill";
export type { SkillInfo, SkillFile, SkillVersions };
@@ -105,6 +105,34 @@ export function useSkills() {
[http, invalidate],
);
const listAgentGrants = useCallback(
async (id: string) => {
const res = await http.get<{ grants: SkillAgentGrant[] }>(`/v1/skills/${id}/grants/agent`);
return res.grants ?? [];
},
[http],
);
const grantSkillToAgent = useCallback(
async (id: string, agentId: string, version: number, canManage: boolean) => {
await http.post<{ ok: string }>(`/v1/skills/${id}/grants/agent`, {
agent_id: agentId,
version,
can_manage: canManage,
});
await invalidate();
},
[http, invalidate],
);
const revokeSkillFromAgent = useCallback(
async (id: string, agentId: string) => {
await http.delete<{ ok: string }>(`/v1/skills/${id}/grants/agent/${agentId}`);
await invalidate();
},
[http, invalidate],
);
const getSkillVersions = useCallback(
async (id: string) => {
return http.get<SkillVersions>(`/v1/skills/${id}/versions`);
@@ -220,6 +248,7 @@ export function useSkills() {
return {
skills, loading, refresh: invalidate, getSkill,
uploadSkill, updateSkill, deleteSkill,
listAgentGrants, grantSkillToAgent, revokeSkillFromAgent,
getSkillVersions, getSkillFiles, getSkillFileContent, rescanDeps, installDeps, installSingleDep, toggleSkill,
setTenantConfig, deleteTenantConfig,
};
@@ -0,0 +1,187 @@
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Plus, Trash2, ShieldCheck } from "lucide-react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useAgents } from "@/pages/agents/hooks/use-agents";
import type { SkillAgentGrant, SkillInfo } from "@/types/skill";
interface SkillAgentGrantsDialogProps {
skill: SkillInfo;
onClose: () => void;
onLoad: (skillId: string) => Promise<SkillAgentGrant[]>;
onGrant: (skillId: string, agentId: string, version: number, canManage: boolean) => Promise<void>;
onRevoke: (skillId: string, agentId: string) => Promise<void>;
}
export function SkillAgentGrantsDialog({
skill,
onClose,
onLoad,
onGrant,
onRevoke,
}: SkillAgentGrantsDialogProps) {
const { t } = useTranslation("skills");
const { agents } = useAgents();
const [grants, setGrants] = useState<SkillAgentGrant[]>([]);
const [agentId, setAgentId] = useState("");
const [canManage, setCanManage] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
if (!skill.id) return;
setLoading(true);
setError("");
onLoad(skill.id)
.then(setGrants)
.catch((err) => setError(err instanceof Error ? err.message : t("grants.loadFailed")))
.finally(() => setLoading(false));
}, [skill.id, onLoad, t]);
const agentNames = useMemo(() => {
const map = new Map<string, string>();
for (const agent of agents) map.set(agent.id, agent.display_name || agent.agent_key);
return map;
}, [agents]);
const selectedGrant = grants.find((grant) => grant.agent_id === agentId);
useEffect(() => {
setCanManage(selectedGrant?.can_manage ?? false);
}, [selectedGrant]);
const handleGrant = async () => {
if (!skill.id || !agentId) return;
setLoading(true);
setError("");
try {
await onGrant(skill.id, agentId, skill.version ?? 1, canManage);
setGrants((current) => {
const next: SkillAgentGrant = {
agent_id: agentId,
pinned_version: skill.version ?? 1,
granted_by: "",
can_manage: canManage,
};
if (current.some((grant) => grant.agent_id === agentId)) {
return current.map((grant) => (grant.agent_id === agentId ? next : grant));
}
return [...current, next];
});
setAgentId("");
setCanManage(false);
} catch (err) {
setError(err instanceof Error ? err.message : t("grants.saveFailed"));
} finally {
setLoading(false);
}
};
const handleRevoke = async (grant: SkillAgentGrant) => {
if (!skill.id) return;
setLoading(true);
setError("");
try {
await onRevoke(skill.id, grant.agent_id);
setGrants((current) => current.filter((item) => item.agent_id !== grant.agent_id));
if (agentId === grant.agent_id) setAgentId("");
} catch (err) {
setError(err instanceof Error ? err.message : t("grants.revokeFailed"));
} finally {
setLoading(false);
}
};
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-h-[85vh] flex flex-col sm:max-w-xl">
<DialogHeader>
<DialogTitle>{t("grants.title", { name: skill.name })}</DialogTitle>
</DialogHeader>
<div className="space-y-4 overflow-y-auto min-h-0 pr-1">
<div className="space-y-2">
<Label>{t("grants.current")}</Label>
{grants.length === 0 ? (
<p className="rounded-md border px-3 py-4 text-sm text-muted-foreground">{t("grants.none")}</p>
) : (
<div className="divide-y rounded-md border">
{grants.map((grant) => (
<div key={grant.agent_id} className="flex items-center justify-between gap-3 px-3 py-2.5">
<div className="min-w-0">
<p className="truncate text-sm font-medium">{agentNames.get(grant.agent_id) || grant.agent_id}</p>
<div className="mt-1 flex items-center gap-1.5">
<Badge variant="secondary" className="text-2xs">v{grant.pinned_version}</Badge>
{grant.can_manage && (
<Badge variant="outline" className="text-2xs border-emerald-500 text-emerald-600">
{t("grants.canManage")}
</Badge>
)}
</div>
</div>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
disabled={loading}
aria-label={t("grants.revoke")}
title={t("grants.revoke")}
onClick={() => handleRevoke(grant)}
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
))}
</div>
)}
</div>
<div className="space-y-3 rounded-md border p-3">
<Label>{selectedGrant ? t("grants.update") : t("grants.add")}</Label>
<Select value={agentId} onValueChange={setAgentId}>
<SelectTrigger>
<SelectValue placeholder={t("grants.selectAgent")} />
</SelectTrigger>
<SelectContent>
{agents.map((agent) => (
<SelectItem key={agent.id} value={agent.id}>
{agent.display_name || agent.agent_key}
</SelectItem>
))}
</SelectContent>
</Select>
<label className="flex items-center justify-between gap-3 rounded-md border px-3 py-2">
<span className="flex min-w-0 items-center gap-2 text-sm">
<ShieldCheck className="h-4 w-4 text-emerald-600" />
{t("grants.allowManage")}
</span>
<Switch checked={canManage} onCheckedChange={setCanManage} />
</label>
<Button size="sm" onClick={handleGrant} disabled={loading || !agentId} className="gap-1">
<Plus className="h-3.5 w-3.5" />
{selectedGrant ? t("grants.save") : t("grants.grant")}
</Button>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
</div>
</DialogContent>
</Dialog>
);
}
+8 -2
View File
@@ -1,5 +1,5 @@
import { useTranslation } from "react-i18next";
import { Zap, Pencil, Trash2 } from "lucide-react";
import { Zap, Pencil, Trash2, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
@@ -20,6 +20,7 @@ interface SkillTableRowProps {
toggling: string | null;
onView: (name: string) => void;
onEdit: (skill: SkillInfo) => void;
onManageGrants: (skill: SkillInfo) => void;
onDelete: (skill: SkillInfo) => void;
onToggle: (skill: SkillInfo, enabled: boolean) => void;
onCycleVisibility: (skill: SkillInfo) => void;
@@ -30,7 +31,7 @@ interface SkillTableRowProps {
/** Single row in the skills table with inline status, visibility, and action controls. */
export function SkillTableRow({
skill, tab, hasTenantScope, toggling,
onView, onEdit, onDelete, onToggle, onCycleVisibility,
onView, onEdit, onManageGrants, onDelete, onToggle, onCycleVisibility,
onSetTenantConfig, onDeleteTenantConfig,
}: SkillTableRowProps) {
const { t } = useTranslation("skills");
@@ -132,6 +133,11 @@ export function SkillTableRow({
<Button variant="ghost" size="sm" onClick={() => onEdit(skill)} className="gap-1">
<Pencil className="h-3.5 w-3.5" />
</Button>
{!skill.is_system && (
<Button variant="ghost" size="sm" onClick={() => onManageGrants(skill)} className="gap-1" title={t("grants.manage")}>
<Users className="h-3.5 w-3.5" />
</Button>
)}
{!skill.is_system && (
<Button
variant="ghost" size="sm"
+14
View File
@@ -12,6 +12,7 @@ import { cn } from "@/lib/utils";
import { useSkills, type SkillInfo } from "./hooks/use-skills";
import { SkillDetailDialog } from "./skill-detail-dialog";
import { SkillEditDialog } from "./skill-edit-dialog";
import { SkillAgentGrantsDialog } from "./skill-agent-grants-dialog";
const SkillUploadDialog = lazy(() =>
import("./skill-upload-dialog").then((m) => ({ default: m.SkillUploadDialog }))
@@ -32,6 +33,7 @@ export function SkillsPage() {
const { t } = useTranslation("skills");
const {
skills, loading, refresh, getSkill, uploadSkill, updateSkill, deleteSkill,
listAgentGrants, grantSkillToAgent, revokeSkillFromAgent,
getSkillVersions, getSkillFiles, getSkillFileContent, rescanDeps, installSingleDep, toggleSkill,
setTenantConfig, deleteTenantConfig,
} = useSkills();
@@ -45,6 +47,7 @@ export function SkillsPage() {
const [selectedSkill, setSelectedSkill] = useState<(SkillInfo & { content: string }) | null>(null);
const [uploadOpen, setUploadOpen] = useState(false);
const [editTarget, setEditTarget] = useState<SkillInfo | null>(null);
const [grantsTarget, setGrantsTarget] = useState<SkillInfo | null>(null);
const [deleteTarget, setDeleteTarget] = useState<SkillInfo | null>(null);
const [deleteLoading, setDeleteLoading] = useState(false);
const [rescanning, setRescanning] = useState(false);
@@ -180,6 +183,7 @@ export function SkillsPage() {
toggling={toggling}
onView={handleViewSkill}
onEdit={setEditTarget}
onManageGrants={setGrantsTarget}
onDelete={setDeleteTarget}
onToggle={handleToggle}
onCycleVisibility={handleCycleVisibility}
@@ -219,6 +223,16 @@ export function SkillsPage() {
/>
)}
{grantsTarget && (
<SkillAgentGrantsDialog
skill={grantsTarget}
onClose={() => setGrantsTarget(null)}
onLoad={listAgentGrants}
onGrant={grantSkillToAgent}
onRevoke={revokeSkillFromAgent}
/>
)}
<Suspense fallback={null}>
<SkillUploadDialog open={uploadOpen} onOpenChange={setUploadOpen} onUpload={(f) => uploadSkill(f)} />
</Suspense>
+8
View File
@@ -35,6 +35,14 @@ export interface SkillWithGrant {
visibility: string;
version: number;
granted: boolean;
can_manage?: boolean;
pinned_version?: number;
is_system: boolean;
}
export interface SkillAgentGrant {
agent_id: string;
pinned_version: number;
granted_by: string;
can_manage: boolean;
}