feat(agent): enhance agent sharing and selection features

- Updated the AgentSelector component to improve agent selection logic, ensuring accurate representation of selected agents.
- Introduced new AgentShareSettings component for managing agent sharing with organizations, including UI for selecting organizations and displaying shared agents.
- Enhanced API interactions for sharing agents, including new methods for listing and managing agent shares.
- Improved localization support for agent sharing features across multiple languages.
- Updated various components to reflect changes in agent capabilities and sharing status, enhancing user experience and clarity.

This update strengthens the agent management features, providing users with better tools for sharing and selecting agents within organizations.
This commit is contained in:
wizardchen
2026-02-04 20:12:29 +08:00
committed by lyingbug
parent faa4e9e7b5
commit dfaf862bc0
45 changed files with 3606 additions and 477 deletions
@@ -0,0 +1,156 @@
package repository
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
var (
ErrAgentShareNotFound = errors.New("agent share not found")
ErrAgentShareAlreadyExists = errors.New("agent already shared to this organization")
)
// agentShareRepository implements AgentShareRepository interface
type agentShareRepository struct {
db *gorm.DB
}
// NewAgentShareRepository creates a new agent share repository
func NewAgentShareRepository(db *gorm.DB) interfaces.AgentShareRepository {
return &agentShareRepository{db: db}
}
// Create creates a new agent share record
func (r *agentShareRepository) Create(ctx context.Context, share *types.AgentShare) error {
var count int64
r.db.WithContext(ctx).Model(&types.AgentShare{}).
Where("agent_id = ? AND source_tenant_id = ? AND organization_id = ? AND deleted_at IS NULL",
share.AgentID, share.SourceTenantID, share.OrganizationID).
Count(&count)
if count > 0 {
return ErrAgentShareAlreadyExists
}
return r.db.WithContext(ctx).Create(share).Error
}
// GetByID gets a share record by ID
func (r *agentShareRepository) GetByID(ctx context.Context, id string) (*types.AgentShare, error) {
var share types.AgentShare
err := r.db.WithContext(ctx).Where("id = ?", id).First(&share).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return &share, nil
}
// GetByAgentAndOrg gets a share record by agent ID and organization ID
func (r *agentShareRepository) GetByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error) {
var share types.AgentShare
err := r.db.WithContext(ctx).
Where("agent_id = ? AND organization_id = ?", agentID, orgID).
First(&share).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return &share, nil
}
// Update updates a share record
func (r *agentShareRepository) Update(ctx context.Context, share *types.AgentShare) error {
return r.db.WithContext(ctx).Model(&types.AgentShare{}).
Where("id = ?", share.ID).Updates(share).Error
}
// Delete soft deletes a share record
func (r *agentShareRepository) Delete(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.AgentShare{}).Error
}
// DeleteByAgentIDAndSourceTenant soft deletes all share records for an agent (id, tenant_id)
func (r *agentShareRepository) DeleteByAgentIDAndSourceTenant(ctx context.Context, agentID string, sourceTenantID uint64) error {
return r.db.WithContext(ctx).
Where("agent_id = ? AND source_tenant_id = ?", agentID, sourceTenantID).
Delete(&types.AgentShare{}).Error
}
// DeleteByOrganizationID soft deletes all share records for an organization
func (r *agentShareRepository) DeleteByOrganizationID(ctx context.Context, orgID string) error {
return r.db.WithContext(ctx).Where("organization_id = ?", orgID).Delete(&types.AgentShare{}).Error
}
// ListByAgent lists all share records for an agent
func (r *agentShareRepository) ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error) {
var shares []*types.AgentShare
err := r.db.WithContext(ctx).
Preload("Organization").
Where("agent_id = ?", agentID).
Order("created_at DESC").
Find(&shares).Error
if err != nil {
return nil, err
}
return shares, nil
}
// ListByOrganization lists all share records for an organization (excluding deleted agents)
func (r *agentShareRepository) ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error) {
var shares []*types.AgentShare
err := r.db.WithContext(ctx).
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
Preload("Agent").
Where("agent_shares.organization_id = ? AND agent_shares.deleted_at IS NULL", orgID).
Order("agent_shares.created_at DESC").
Find(&shares).Error
if err != nil {
return nil, err
}
return shares, nil
}
// ListSharedAgentsForUser lists all agents shared to organizations that the user belongs to
func (r *agentShareRepository) ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error) {
var shares []*types.AgentShare
err := r.db.WithContext(ctx).
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
Preload("Agent").
Preload("Organization").
Joins("JOIN organization_members ON organization_members.organization_id = agent_shares.organization_id").
Joins("JOIN organizations ON organizations.id = agent_shares.organization_id AND organizations.deleted_at IS NULL").
Where("organization_members.user_id = ?", userID).
Where("agent_shares.deleted_at IS NULL").
Order("agent_shares.created_at DESC").
Find(&shares).Error
if err != nil {
return nil, err
}
return shares, nil
}
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID. Single query.
func (r *agentShareRepository) GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error) {
var share types.AgentShare
err := r.db.WithContext(ctx).
Joins("JOIN organization_members ON organization_members.organization_id = agent_shares.organization_id").
Where("agent_shares.agent_id = ?", agentID).
Where("organization_members.user_id = ?", userID).
Where("agent_shares.source_tenant_id != ?", excludeTenantID).
Where("agent_shares.deleted_at IS NULL").
First(&share).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return &share, nil
}
+252
View File
@@ -0,0 +1,252 @@
package service
import (
"context"
"errors"
"fmt"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
var (
ErrAgentShareNotFound = errors.New("agent share not found")
ErrAgentSharePermission = errors.New("permission denied for this share operation")
ErrAgentNotFoundForShare = errors.New("agent not found")
ErrNotAgentOwner = errors.New("only agent owner can share")
ErrOrgRoleCannotShareAgent = errors.New("only editors and admins can share agents to this organization")
ErrAgentNotConfigured = errors.New("agent is not fully configured (missing required chat model or rerank model when using knowledge bases)")
)
// agentShareService implements AgentShareService interface
type agentShareService struct {
shareRepo interfaces.AgentShareRepository
orgRepo interfaces.OrganizationRepository
agentRepo interfaces.CustomAgentRepository
userRepo interfaces.UserRepository
}
// NewAgentShareService creates a new agent share service
func NewAgentShareService(
shareRepo interfaces.AgentShareRepository,
orgRepo interfaces.OrganizationRepository,
agentRepo interfaces.CustomAgentRepository,
userRepo interfaces.UserRepository,
) interfaces.AgentShareService {
return &agentShareService{
shareRepo: shareRepo,
orgRepo: orgRepo,
agentRepo: agentRepo,
userRepo: userRepo,
}
}
// ShareAgent shares an agent to an organization
func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error) {
logger.Infof(ctx, "Sharing agent %s to organization %s", agentID, orgID)
agent, err := s.agentRepo.GetAgentByID(ctx, agentID, tenantID)
if err != nil || agent == nil {
return nil, ErrAgentNotFoundForShare
}
if agent.TenantID != tenantID {
return nil, ErrNotAgentOwner
}
// Require agent to be fully configured before sharing (same rules as for conversation)
if agent.Config.ModelID == "" {
return nil, ErrAgentNotConfigured
}
usesKB := agent.Config.KBSelectionMode != "none" || len(agent.Config.KnowledgeBases) > 0
if usesKB && agent.Config.RerankModelID == "" {
return nil, ErrAgentNotConfigured
}
_, err = s.orgRepo.GetByID(ctx, orgID)
if err != nil {
if errors.Is(err, repository.ErrOrganizationNotFound) {
return nil, ErrOrgNotFound
}
return nil, err
}
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
if err != nil {
if errors.Is(err, repository.ErrOrgMemberNotFound) {
return nil, ErrUserNotInOrg
}
return nil, err
}
if !member.Role.HasPermission(types.OrgRoleEditor) {
return nil, ErrOrgRoleCannotShareAgent
}
// 智能体共享仅支持只读,不支持可编辑
permission = types.OrgRoleViewer
share := &types.AgentShare{
ID: uuid.New().String(),
AgentID: agentID,
OrganizationID: orgID,
SharedByUserID: userID,
SourceTenantID: tenantID,
Permission: permission,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if err := s.shareRepo.Create(ctx, share); err != nil {
if errors.Is(err, repository.ErrAgentShareAlreadyExists) {
existing, err := s.shareRepo.GetByAgentAndOrg(ctx, agentID, orgID)
if err != nil {
return nil, err
}
existing.Permission = types.OrgRoleViewer
existing.UpdatedAt = time.Now()
if err := s.shareRepo.Update(ctx, existing); err != nil {
return nil, err
}
return existing, nil
}
return nil, err
}
logger.Infof(ctx, "Agent %s shared successfully to organization %s", agentID, orgID)
return share, nil
}
// RemoveShare removes an agent share
func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, userID string) error {
share, err := s.shareRepo.GetByID(ctx, shareID)
if err != nil {
if errors.Is(err, repository.ErrAgentShareNotFound) {
return ErrAgentShareNotFound
}
return err
}
if share.SharedByUserID == userID {
return s.shareRepo.Delete(ctx, shareID)
}
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
if err == nil && member.Role == types.OrgRoleAdmin {
return s.shareRepo.Delete(ctx, shareID)
}
return ErrAgentSharePermission
}
// ListSharesByAgent lists all shares for an agent
func (s *agentShareService) ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error) {
return s.shareRepo.ListByAgent(ctx, agentID)
}
// ListSharesByOrganization lists all agent shares for an organization
func (s *agentShareService) ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error) {
return s.shareRepo.ListByOrganization(ctx, orgID)
}
// ListSharedAgents lists agents shared to the user through organizations, deduplicated by agent ID (keep highest permission)
func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error) {
shares, err := s.shareRepo.ListSharedAgentsForUser(ctx, userID)
if err != nil {
return nil, err
}
agentInfoMap := make(map[string]*types.SharedAgentInfo)
for _, share := range shares {
if share.SourceTenantID == currentTenantID {
continue
}
if share.Agent == nil {
continue
}
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
if err != nil {
continue
}
effectivePermission := share.Permission
if !member.Role.HasPermission(share.Permission) {
effectivePermission = member.Role
}
info := &types.SharedAgentInfo{
Agent: share.Agent,
ShareID: share.ID,
OrganizationID: share.OrganizationID,
OrgName: "",
Permission: effectivePermission,
SourceTenantID: share.SourceTenantID,
SharedAt: share.CreatedAt,
SharedByUserID: share.SharedByUserID,
}
if share.Organization != nil {
info.OrgName = share.Organization.Name
}
if share.SharedByUserID != "" {
if u, err := s.userRepo.GetUserByID(ctx, share.SharedByUserID); err == nil && u != nil {
info.SharedByUsername = u.Username
}
}
key := fmt.Sprintf("%s_%d", share.AgentID, share.SourceTenantID)
existing, exists := agentInfoMap[key]
if !exists {
agentInfoMap[key] = info
} else if effectivePermission.HasPermission(existing.Permission) && effectivePermission != existing.Permission {
agentInfoMap[key] = info
}
}
result := make([]*types.SharedAgentInfo, 0, len(agentInfoMap))
for _, info := range agentInfoMap {
result = append(result, info)
}
return result, nil
}
// GetSharedAgentForUser returns the shared agent by agentID if the user has access; source tenant is resolved from the user's share. One share lookup + one agent lookup.
func (s *agentShareService) GetSharedAgentForUser(ctx context.Context, userID string, currentTenantID uint64, agentID string) (*types.CustomAgent, error) {
if agentID == "" {
return nil, ErrAgentShareNotFound
}
share, err := s.shareRepo.GetShareByAgentIDForUser(ctx, userID, agentID, currentTenantID)
if err != nil {
if errors.Is(err, repository.ErrAgentShareNotFound) {
return nil, ErrAgentSharePermission
}
return nil, err
}
agent, err := s.agentRepo.GetAgentByID(ctx, agentID, share.SourceTenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFoundForShare
}
return nil, err
}
return agent, nil
}
// GetShare gets an agent share by ID
func (s *agentShareService) GetShare(ctx context.Context, shareID string) (*types.AgentShare, error) {
share, err := s.shareRepo.GetByID(ctx, shareID)
if err != nil {
if errors.Is(err, repository.ErrAgentShareNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return share, nil
}
// GetShareByAgentAndOrg gets an agent share by agent ID and organization ID
func (s *agentShareService) GetShareByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error) {
share, err := s.shareRepo.GetByAgentAndOrg(ctx, agentID, orgID)
if err != nil {
if errors.Is(err, repository.ErrAgentShareNotFound) {
return nil, ErrAgentShareNotFound
}
return nil, err
}
return share, nil
}
@@ -124,6 +124,22 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type
return agent, nil
}
// GetAgentByIDAndTenant retrieves an agent by ID and tenant (for shared agents; does not resolve built-in)
func (s *customAgentService) GetAgentByIDAndTenant(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) {
if id == "" {
logger.Error(ctx, "Agent ID is empty")
return nil, errors.New("agent ID cannot be empty")
}
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFound
}
return nil, err
}
return agent, nil
}
// ListAgents lists all agents for the current tenant (including built-in agents)
func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAgent, error) {
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
@@ -7585,6 +7585,14 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string,
return s.repo.SearchKnowledgeInScopes(ctx, scopes, keyword, offset, limit, fileTypes)
}
// SearchKnowledgeForScopes searches knowledge within the given scopes (e.g. for shared agent context).
func (s *knowledgeService) SearchKnowledgeForScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error) {
if len(scopes) == 0 {
return nil, false, nil
}
return s.repo.SearchKnowledgeInScopes(ctx, scopes, keyword, offset, limit, fileTypes)
}
// ProcessKnowledgeListDelete handles Asynq knowledge list delete tasks
func (s *knowledgeService) ProcessKnowledgeListDelete(ctx context.Context, t *asynq.Task) error {
var payload types.KnowledgeListDeletePayload
@@ -139,6 +139,23 @@ func (s *knowledgeBaseService) GetKnowledgeBaseByIDOnly(ctx context.Context, id
return kb, nil
}
// GetKnowledgeBasesByIDsOnly retrieves knowledge bases by IDs without tenant filter (batch).
func (s *knowledgeBaseService) GetKnowledgeBasesByIDsOnly(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error) {
if len(ids) == 0 {
return nil, nil
}
kbs, err := s.repo.GetKnowledgeBaseByIDs(ctx, ids)
if err != nil {
return nil, err
}
for _, kb := range kbs {
if kb != nil {
kb.EnsureDefaults()
}
}
return kbs, nil
}
// ListKnowledgeBases returns all knowledge bases for a tenant
func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
@@ -195,6 +212,59 @@ func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types
return kbs, nil
}
// ListKnowledgeBasesByTenantID returns all knowledge bases for the given tenant (e.g. for shared agent context).
func (s *knowledgeBaseService) ListKnowledgeBasesByTenantID(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBase, error) {
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
})
return nil, err
}
for _, kb := range kbs {
kb.EnsureDefaults()
switch kb.Type {
case types.KnowledgeBaseTypeDocument:
if cnt, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
kb.KnowledgeCount = cnt
}
case types.KnowledgeBaseTypeFAQ:
if cnt, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
kb.ChunkCount = cnt
}
}
if processingCount, err := s.kgRepo.CountKnowledgeByStatus(ctx, tenantID, kb.ID, []string{"pending", "processing"}); err == nil {
kb.IsProcessing = processingCount > 0
kb.ProcessingCount = processingCount
}
}
return kbs, nil
}
// FillKnowledgeBaseCounts fills KnowledgeCount, ChunkCount, IsProcessing, ProcessingCount for the given KB using kb.TenantID.
func (s *knowledgeBaseService) FillKnowledgeBaseCounts(ctx context.Context, kb *types.KnowledgeBase) error {
if kb == nil {
return nil
}
tenantID := kb.TenantID
kb.EnsureDefaults()
switch kb.Type {
case types.KnowledgeBaseTypeDocument:
if cnt, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
kb.KnowledgeCount = cnt
}
case types.KnowledgeBaseTypeFAQ:
if cnt, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
kb.ChunkCount = cnt
}
}
if processingCount, err := s.kgRepo.CountKnowledgeByStatus(ctx, tenantID, kb.ID, []string{"pending", "processing"}); err == nil {
kb.IsProcessing = processingCount > 0
kb.ProcessingCount = processingCount
}
return nil
}
// UpdateKnowledgeBase updates a knowledge base's properties
func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
id string,
+22 -7
View File
@@ -39,17 +39,24 @@ var (
// organizationService implements OrganizationService interface
type organizationService struct {
orgRepo interfaces.OrganizationRepository
userRepo interfaces.UserRepository
shareRepo interfaces.KBShareRepository
orgRepo interfaces.OrganizationRepository
userRepo interfaces.UserRepository
shareRepo interfaces.KBShareRepository
agentShareRepo interfaces.AgentShareRepository
}
// NewOrganizationService creates a new organization service
func NewOrganizationService(orgRepo interfaces.OrganizationRepository, userRepo interfaces.UserRepository, shareRepo interfaces.KBShareRepository) interfaces.OrganizationService {
func NewOrganizationService(
orgRepo interfaces.OrganizationRepository,
userRepo interfaces.UserRepository,
shareRepo interfaces.KBShareRepository,
agentShareRepo interfaces.AgentShareRepository,
) interfaces.OrganizationService {
return &organizationService{
orgRepo: orgRepo,
userRepo: userRepo,
shareRepo: shareRepo,
orgRepo: orgRepo,
userRepo: userRepo,
shareRepo: shareRepo,
agentShareRepo: agentShareRepo,
}
}
@@ -227,6 +234,7 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context,
}
memberCounts := make(map[string]int64)
shareCounts := make(map[string]int64)
agentShareCounts := make(map[string]int)
memberOrgIDs := make(map[string]bool)
for _, org := range orgs {
if mc, err := s.orgRepo.CountMembers(ctx, org.ID); err == nil {
@@ -234,6 +242,9 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context,
}
shares, _ := s.shareRepo.ListByOrganization(ctx, org.ID)
shareCounts[org.ID] = int64(len(shares))
if agentShares, err := s.agentShareRepo.ListByOrganization(ctx, org.ID); err == nil {
agentShareCounts[org.ID] = len(agentShares)
}
_, err := s.orgRepo.GetMember(ctx, org.ID, userID)
memberOrgIDs[org.ID] = (err == nil)
}
@@ -247,6 +258,7 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context,
MemberCount: int(memberCounts[org.ID]),
MemberLimit: org.MemberLimit,
ShareCount: int(shareCounts[org.ID]),
AgentShareCount: agentShareCounts[org.ID],
IsAlreadyMember: memberOrgIDs[org.ID],
RequireApproval: org.RequireApproval,
})
@@ -312,6 +324,9 @@ func (s *organizationService) DeleteOrganization(ctx context.Context, id string,
if err := s.shareRepo.DeleteByOrganizationID(ctx, id); err != nil {
logger.Warnf(ctx, "Failed to delete KB shares for organization %s: %v", id, err)
}
if err := s.agentShareRepo.DeleteByOrganizationID(ctx, id); err != nil {
logger.Warnf(ctx, "Failed to delete agent shares for organization %s: %v", id, err)
}
return s.orgRepo.Delete(ctx, id)
}
+69 -42
View File
@@ -577,8 +577,20 @@ func (s *sessionService) KnowledgeQA(
}
}
// Retrieval scope: when agent is set, use agent's tenant (own or shared); otherwise session tenant or context
retrievalTenantID := session.TenantID
if customAgent != nil && customAgent.TenantID != 0 {
retrievalTenantID = customAgent.TenantID
logger.Infof(ctx, "Using agent tenant %d for retrieval scope", retrievalTenantID)
} else if v := ctx.Value(types.TenantIDContextKey); v != nil {
if tid, ok := v.(uint64); ok && tid != 0 {
retrievalTenantID = tid
logger.Infof(ctx, "Using effective tenant %d for retrieval from context", retrievalTenantID)
}
}
// Build unified search targets (computed once, used throughout pipeline)
searchTargets, err := s.buildSearchTargets(ctx, session.TenantID, knowledgeBaseIDs, knowledgeIDs)
searchTargets, err := s.buildSearchTargets(ctx, retrievalTenantID, knowledgeBaseIDs, knowledgeIDs)
if err != nil {
logger.Warnf(ctx, "Failed to build search targets: %v", err)
}
@@ -614,7 +626,7 @@ func (s *sessionService) KnowledgeQA(
FallbackPrompt: fallbackPrompt,
EventBus: eventBus.AsEventBusInterface(), // NEW: For pipeline to emit events directly
WebSearchEnabled: webSearchEnabled,
TenantID: session.TenantID,
TenantID: retrievalTenantID, // Effective tenant for retrieval (shared agent = agent's tenant)
RewritePromptSystem: rewritePromptSystem,
RewritePromptUser: rewritePromptUser,
EnableRewrite: enableRewrite,
@@ -923,12 +935,12 @@ func (s *sessionService) configureSkillsFromAgent(
}
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs
// This is called once at the request entry point to avoid repeated queries later in the pipeline
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs.
// tenantID is the retrieval scope: session.TenantID or effective tenant from shared agent (set by handler).
// This is called once at the request entry point to avoid repeated queries later in the pipeline.
// Logic:
// - For each knowledgeBaseID: create a SearchTargetTypeKnowledgeBase target with correct TenantID
// - For each knowledgeID: find its knowledgeBaseID, if the KB is already in the list, skip (covered by full KB search)
// otherwise create a SearchTargetTypeKnowledge target grouped by KB
// - For each knowledgeBaseID: resolve actual TenantID (own, org-shared, or in retrieval-tenant scope for shared agent)
// - For each knowledgeID: find its knowledgeBaseID; if the KB is already in the list, skip; otherwise add SearchTargetTypeKnowledge
func (s *sessionService) buildSearchTargets(
ctx context.Context,
tenantID uint64,
@@ -943,34 +955,31 @@ func (s *sessionService) buildSearchTargets(
// Track which KBs are fully searched
fullKBSet := make(map[string]bool)
// First pass: process knowledge base IDs and get their tenant info
// First pass: batch-fetch KBs, then resolve tenant per ID (tenant scope already set by caller)
if len(knowledgeBaseIDs) > 0 {
// Get KB details to determine their actual tenant IDs (may include shared KBs)
kbs, _ := s.knowledgeBaseService.GetKnowledgeBasesByIDsOnly(ctx, knowledgeBaseIDs)
kbByID := make(map[string]*types.KnowledgeBase, len(kbs))
for _, kb := range kbs {
if kb != nil {
kbByID[kb.ID] = kb
}
}
userID, _ := ctx.Value(types.UserIDContextKey).(string)
for _, kbID := range knowledgeBaseIDs {
fullKBSet[kbID] = true
// Try to get KB info - first from current tenant, then from shared access
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
// May be a shared KB from another tenant - use kbShareService to check
if s.kbShareService != nil {
userID, _ := ctx.Value(types.UserIDContextKey).(string)
if userID != "" {
// Check if user has at least viewer permission on this KB
hasAccess, _ := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
if hasAccess {
// Get KB info without tenant filter
kbInfo, err := s.knowledgeBaseService.GetKnowledgeBaseByIDOnly(ctx, kbID)
if err == nil && kbInfo != nil {
kbTenantMap[kbID] = kbInfo.TenantID
}
}
}
kb := kbByID[kbID]
if kb == nil {
kbTenantMap[kbID] = tenantID
} else if kb.TenantID == tenantID {
kbTenantMap[kbID] = tenantID
} else if s.kbShareService != nil && userID != "" {
hasAccess, _ := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
if hasAccess {
kbTenantMap[kbID] = kb.TenantID
} else {
kbTenantMap[kbID] = tenantID
}
} else if kb != nil {
kbTenantMap[kbID] = kb.TenantID
}
// Default to current tenant if we couldn't determine the actual tenant
if kbTenantMap[kbID] == 0 {
} else {
kbTenantMap[kbID] = tenantID
}
targets = append(targets, &types.SearchTarget{
@@ -1215,26 +1224,44 @@ func (s *sessionService) AgentQA(
knowledgeIDs []string,
) error {
sessionID := session.ID
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
sessionJSON, err := json.Marshal(session)
if err != nil {
logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err)
return fmt.Errorf("failed to marshal session: %w", err)
}
logger.Infof(ctx, "Start agent-based question answering, session ID: %s, tenant ID: %d, query: %s, session: %s",
sessionID, tenantID, query, string(sessionJSON))
// Build effective agent configuration by merging session and tenant configs
// All config now comes from customAgent parameter
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
// customAgent is required for AgentQA
// customAgent is required for AgentQA (handler has already done permission check for shared agent)
if customAgent == nil {
logger.Warnf(ctx, "Custom agent not provided for session: %s", sessionID)
return errors.New("custom agent configuration is required for agent QA")
}
// Use agent's tenant for retrieval and tenant-scoped config (handler has validated access)
agentTenantID := customAgent.TenantID
if agentTenantID == 0 {
agentTenantID = session.TenantID
}
logger.Infof(ctx, "Start agent-based question answering, session ID: %s, agent tenant ID: %d, query: %s, session: %s",
sessionID, agentTenantID, query, string(sessionJSON))
var tenantInfo *types.Tenant
if v := ctx.Value(types.TenantInfoContextKey); v != nil {
tenantInfo, _ = v.(*types.Tenant)
}
// When agent belongs to another tenant (shared agent), use agent's tenant for KB/model scope; load tenantInfo if needed
if tenantInfo == nil || tenantInfo.ID != agentTenantID {
if s.tenantService != nil {
if agentTenant, err := s.tenantService.GetTenantByID(ctx, agentTenantID); err == nil && agentTenant != nil {
tenantInfo = agentTenant
logger.Infof(ctx, "Using agent tenant info for retrieval scope, tenant ID: %d", agentTenantID)
}
}
}
if tenantInfo == nil {
logger.Warnf(ctx, "Tenant info not available for agent tenant %d, proceeding with defaults", agentTenantID)
tenantInfo = &types.Tenant{ID: agentTenantID}
}
// Ensure defaults are set
customAgent.EnsureDefaults()
@@ -1317,8 +1344,8 @@ func (s *sessionService) AgentQA(
logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode")
}
// Build search targets for agent (pre-compute once to avoid repeated queries)
searchTargets, err := s.buildSearchTargets(ctx, tenantInfo.ID, agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs)
// Build search targets using agent's tenant (handler has validated access for shared agent)
searchTargets, err := s.buildSearchTargets(ctx, agentTenantID, agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs)
if err != nil {
logger.Warnf(ctx, "Failed to build search targets for agent: %v", err)
// Continue without search targets, the tool will handle empty targets
+2
View File
@@ -113,6 +113,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(repository.NewCustomAgentRepository))
must(container.Provide(repository.NewOrganizationRepository))
must(container.Provide(repository.NewKBShareRepository))
must(container.Provide(repository.NewAgentShareRepository))
must(container.Provide(service.NewWebSearchStateService))
// MCP manager for managing MCP client connections
@@ -125,6 +126,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewKnowledgeBaseService))
must(container.Provide(service.NewOrganizationService))
must(container.Provide(service.NewKBShareService)) // KBShareService must be registered before KnowledgeService and KnowledgeTagService
must(container.Provide(service.NewAgentShareService))
must(container.Provide(service.NewKnowledgeService))
must(container.Provide(service.NewChunkService))
must(container.Provide(service.NewKnowledgeTagService))
+154 -33
View File
@@ -9,8 +9,10 @@ import (
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
goerrors "errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
@@ -19,9 +21,10 @@ import (
// KnowledgeHandler processes HTTP requests related to knowledge resources
type KnowledgeHandler struct {
kgService interfaces.KnowledgeService
kbService interfaces.KnowledgeBaseService
kbShareService interfaces.KBShareService
kgService interfaces.KnowledgeService
kbService interfaces.KnowledgeBaseService
kbShareService interfaces.KBShareService
agentShareService interfaces.AgentShareService
}
// NewKnowledgeHandler creates a new knowledge handler instance
@@ -29,11 +32,13 @@ func NewKnowledgeHandler(
kgService interfaces.KnowledgeService,
kbService interfaces.KnowledgeBaseService,
kbShareService interfaces.KBShareService,
agentShareService interfaces.AgentShareService,
) *KnowledgeHandler {
return &KnowledgeHandler{
kgService: kgService,
kbService: kbService,
kbShareService: kbShareService,
kgService: kgService,
kbService: kbService,
kbShareService: kbShareService,
agentShareService: agentShareService,
}
}
@@ -157,18 +162,41 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k
}
// Shared KB: check organization permission
if !userExists || h.kbShareService == nil {
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
if userExists && h.kbShareService != nil {
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
if permErr == nil && isShared && permission.HasPermission(requiredPermission) {
effectiveTenantID := knowledge.TenantID
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID), nil
}
}
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
if permErr != nil || !isShared {
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
// Shared agent: request passes agent_id, verify user has that shared agent and the agent has access to this knowledge/KB
if userExists && h.agentShareService != nil && requiredPermission == types.OrgRoleViewer {
agentID := c.Query("agent_id")
if agentID != "" {
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), tenantID, agentID)
if err == nil && agent != nil {
if knowledge.TenantID != agent.TenantID {
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
}
mode := agent.Config.KBSelectionMode
if mode == "none" {
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
}
if mode == "all" {
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
}
if mode == "selected" {
for _, kbID := range agent.Config.KnowledgeBases {
if kbID == knowledge.KnowledgeBaseID {
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
}
}
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
}
}
}
}
if !permission.HasPermission(requiredPermission) {
return nil, ctx, errors.NewForbiddenError("Insufficient permission for this operation")
}
effectiveTenantID := knowledge.TenantID
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID), nil
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
}
// handleDuplicateKnowledgeError handles cases where duplicate knowledge is detected
@@ -680,20 +708,22 @@ func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) {
// GetKnowledgeBatchRequest defines parameters for batch knowledge retrieval
type GetKnowledgeBatchRequest struct {
IDs []string `form:"ids" binding:"required"` // List of knowledge IDs
KBID string `form:"kb_id"` // Optional: scope to this KB (validates access and uses effective tenant for shared KB)
IDs []string `form:"ids" binding:"required"` // List of knowledge IDs
KBID string `form:"kb_id"` // Optional: scope to this KB (validates access and uses effective tenant for shared KB)
AgentID string `form:"agent_id"` // Optional: when using a shared agent, use agent's tenant for retrieval (validates shared agent access)
}
// GetKnowledgeBatch godoc
// @Summary 批量获取知识
// @Description 根据ID列表批量获取知识条目。可选 kb_id:指定时按该知识库校验权限并用于共享知识库的租户解析
// @Description 根据ID列表批量获取知识条目。可选 kb_id:指定时按该知识库校验权限并用于共享知识库的租户解析;可选 agent_id:使用共享智能体时传此参数,后端按智能体所属租户查询(用于刷新后恢复共享知识库下的文件)
// @Tags 知识管理
// @Accept json
// @Produce json
// @Param ids query []string true "知识ID列表"
// @Param kb_id query string false "可选,知识库ID(用于共享知识库时指定范围)"
// @Success 200 {object} map[string]interface{} "知识列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Param ids query []string true "知识ID列表"
// @Param kb_id query string false "可选,知识库ID(用于共享知识库时指定范围)"
// @Param agent_id query string false "可选,共享智能体ID(用于按智能体租户批量拉取文件详情)"
// @Success 200 {object} map[string]interface{} "知识列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/batch [get]
@@ -715,6 +745,30 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
return
}
// Optional agent_id: when using shared agent, resolve agent and use its tenant for batch retrieval (so shared KB files can be loaded after refresh)
if agentID := secutils.SanitizeForLog(req.AgentID); agentID != "" && h.agentShareService != nil {
userIDVal, ok := c.Get(types.UserIDContextKey.String())
if !ok {
c.Error(errors.NewUnauthorizedError("Unauthorized"))
return
}
userID, _ := userIDVal.(string)
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
if currentTenantID == 0 {
c.Error(errors.NewUnauthorizedError("Unauthorized"))
return
}
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID)
if err != nil || agent == nil {
logger.Warnf(ctx, "GetKnowledgeBatch: invalid or inaccessible shared agent %s: %v", agentID, err)
c.Error(errors.NewForbiddenError("Invalid or inaccessible shared agent").WithDetails(err.Error()))
return
}
effectiveTenantID = agent.TenantID
logger.Infof(ctx, "Batch retrieving knowledge with agent_id, effective tenant ID: %d, IDs count: %d",
effectiveTenantID, len(req.IDs))
}
var knowledges []*types.Knowledge
var err error
@@ -733,9 +787,8 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
knowledges, err = h.kgService.GetKnowledgeBatch(ctx, effectiveTenantID, req.IDs)
} else {
// No kb_id provided: use GetKnowledgeBatchWithSharedAccess to support cross-tenant shared files
// This is needed when page is refreshed and frontend doesn't have kb_id mapping
logger.Infof(ctx, "Batch retrieving knowledge without kb_id (using shared access), tenant ID: %d, IDs count: %d",
// No kb_id: use GetKnowledgeBatchWithSharedAccess (or effectiveTenantID may already be set by agent_id for shared agent)
logger.Infof(ctx, "Batch retrieving knowledge without kb_id, effective tenant ID: %d, IDs count: %d",
effectiveTenantID, len(req.IDs))
knowledges, err = h.kgService.GetKnowledgeBatchWithSharedAccess(ctx, effectiveTenantID, req.IDs)
@@ -999,14 +1052,15 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
// SearchKnowledge godoc
// @Summary Search knowledge
// @Description Search knowledge files by keyword across all knowledge bases
// @Description Search knowledge files by keyword. When agent_id is set (shared agent), scope is the agent's configured knowledge bases.
// @Tags Knowledge
// @Accept json
// @Produce json
// @Param keyword query string false "Keyword to search"
// @Param offset query int false "Offset for pagination"
// @Param limit query int false "Limit for pagination (default 20)"
// @Param file_types query string false "Comma-separated file extensions to filter (e.g., csv,xlsx)"
// @Param keyword query string false "Keyword to search"
// @Param offset query int false "Offset for pagination"
// @Param limit query int false "Limit for pagination (default 20)"
// @Param file_types query string false "Comma-separated file extensions to filter (e.g., csv,xlsx)"
// @Param agent_id query string false "Shared agent ID (search within agent's KB scope)"
// @Success 200 {object} map[string]interface{} "Search results"
// @Failure 400 {object} errors.AppError "Invalid request"
// @Security Bearer
@@ -1021,7 +1075,6 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
// Parse file_types parameter (comma-separated)
var fileTypes []string
if fileTypesStr := c.Query("file_types"); fileTypesStr != "" {
for _, ft := range strings.Split(fileTypesStr, ",") {
@@ -1032,7 +1085,75 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
}
}
// Retrieve knowledge entries (own + shared KBs; empty keyword returns recent files)
agentID := c.Query("agent_id")
if agentID != "" {
userIDVal, ok := c.Get(types.UserIDContextKey.String())
if !ok {
c.Error(errors.NewUnauthorizedError("user ID not found"))
return
}
userID, _ := userIDVal.(string)
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
if currentTenantID == 0 {
c.Error(errors.NewUnauthorizedError("tenant ID not found"))
return
}
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID)
if err != nil {
if goerrors.Is(err, service.ErrAgentShareNotFound) || goerrors.Is(err, service.ErrAgentSharePermission) || goerrors.Is(err, service.ErrAgentNotFoundForShare) {
c.Error(errors.NewForbiddenError("no permission for this shared agent"))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to verify shared agent access").WithDetails(err.Error()))
return
}
sourceTenantID := agent.TenantID
mode := agent.Config.KBSelectionMode
if mode == "none" {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": []interface{}{},
"has_more": false,
})
return
}
var scopes []types.KnowledgeSearchScope
if mode == "selected" && len(agent.Config.KnowledgeBases) > 0 {
for _, kbID := range agent.Config.KnowledgeBases {
if kbID != "" {
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kbID})
}
}
}
if len(scopes) == 0 {
kbs, err := h.kbService.ListKnowledgeBasesByTenantID(ctx, sourceTenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to list knowledge bases").WithDetails(err.Error()))
return
}
for _, kb := range kbs {
if kb != nil && kb.Type == types.KnowledgeBaseTypeDocument {
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kb.ID})
}
}
}
knowledges, hasMore, err := h.kgService.SearchKnowledgeForScopes(ctx, scopes, keyword, offset, limit, fileTypes)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to search knowledge").WithDetails(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": knowledges,
"has_more": hasMore,
})
return
}
// Default: own + shared KBs
knowledges, hasMore, err := h.kgService.SearchKnowledge(ctx, keyword, offset, limit, fileTypes)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
+139 -42
View File
@@ -8,7 +8,9 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/errors"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -20,10 +22,11 @@ import (
// KnowledgeBaseHandler defines the HTTP handler for knowledge base operations
type KnowledgeBaseHandler struct {
service interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
kbShareService interfaces.KBShareService
asynqClient *asynq.Client
service interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
kbShareService interfaces.KBShareService
agentShareService interfaces.AgentShareService
asynqClient *asynq.Client
}
// NewKnowledgeBaseHandler creates a new knowledge base handler instance
@@ -31,13 +34,15 @@ func NewKnowledgeBaseHandler(
service interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
kbShareService interfaces.KBShareService,
agentShareService interfaces.AgentShareService,
asynqClient *asynq.Client,
) *KnowledgeBaseHandler {
return &KnowledgeBaseHandler{
service: service,
knowledgeService: knowledgeService,
kbShareService: kbShareService,
asynqClient: asynqClient,
service: service,
knowledgeService: knowledgeService,
kbShareService: kbShareService,
agentShareService: agentShareService,
asynqClient: asynqClient,
}
}
@@ -70,7 +75,7 @@ func (h *KnowledgeBaseHandler) HybridSearch(c *gin.Context) {
var req types.SearchParams
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
@@ -82,7 +87,7 @@ func (h *KnowledgeBaseHandler) HybridSearch(c *gin.Context) {
results, err := h.service.HybridSearch(ctx, id, req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
@@ -115,7 +120,7 @@ func (h *KnowledgeBaseHandler) CreateKnowledgeBase(c *gin.Context) {
var req types.KnowledgeBase
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
if err := validateExtractConfig(req.ExtractConfig); err != nil {
@@ -129,7 +134,7 @@ func (h *KnowledgeBaseHandler) CreateKnowledgeBase(c *gin.Context) {
kb, err := h.service.CreateKnowledgeBase(ctx, &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
@@ -152,7 +157,7 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
tenantID, exists := c.Get(types.TenantIDContextKey.String())
if !exists {
logger.Error(ctx, "Failed to get tenant ID")
return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized")
return nil, "", 0, "", apperrors.NewUnauthorizedError("Unauthorized")
}
// Get user ID from context (needed for shared KB permission check)
@@ -162,14 +167,14 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Knowledge base ID is empty")
return nil, "", 0, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
return nil, "", 0, "", apperrors.NewBadRequestError("Knowledge base ID cannot be empty")
}
// Verify tenant has permission to access this knowledge base
kb, err := h.service.GetKnowledgeBaseByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return nil, id, 0, "", errors.NewInternalServerError(err.Error())
return nil, id, 0, "", apperrors.NewInternalServerError(err.Error())
}
// Check 1: Verify tenant ownership (owner has full access)
@@ -192,6 +197,37 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
}
}
// Check 3: Shared agent — request has agent_id, verify user has that shared agent and the agent has access to this KB
if userExists && h.agentShareService != nil {
agentID := c.Query("agent_id")
if agentID != "" {
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
if currentTenantID != 0 {
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), currentTenantID, agentID)
if err == nil && agent != nil {
if kb.TenantID != agent.TenantID {
logger.Warnf(ctx, "Shared agent tenant mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID)
} else {
mode := agent.Config.KBSelectionMode
if mode == "none" {
// no-op, fall through to forbid
} else if mode == "all" {
logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=all)", userID.(string), id, agentID)
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
} else if mode == "selected" {
for _, allowedID := range agent.Config.KnowledgeBases {
if allowedID == id {
logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=selected)", userID.(string), id, agentID)
return kb, id, kb.TenantID, types.OrgRoleViewer, nil
}
}
}
}
}
}
}
}
// No permission: not owner and no shared access
logger.Warnf(
ctx,
@@ -199,16 +235,17 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
"request tenant ID: %d, knowledge base tenant ID: %d",
id, tenantID.(uint64), kb.TenantID,
)
return nil, id, 0, "", errors.NewForbiddenError("No permission to operate")
return nil, id, 0, "", apperrors.NewForbiddenError("No permission to operate")
}
// GetKnowledgeBase godoc
// @Summary 获取知识库详情
// @Description 根据ID获取知识库详情
// @Description 根据ID获取知识库详情。当使用共享智能体时,可传 agent_id 以校验该智能体是否有权访问该知识库。
// @Tags 知识库
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param id path string true "知识库ID"
// @Param agent_id query string false "共享智能体 ID(用于校验智能体是否有权访问该知识库)"
// @Success 200 {object} map[string]interface{} "知识库详情"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "知识库不存在"
@@ -222,6 +259,10 @@ func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
c.Error(err)
return
}
// Fill counts (knowledge_count, chunk_count, is_processing) so hover/detail shows correct numbers
if fillErr := h.service.FillKnowledgeBaseCounts(c.Request.Context(), kb); fillErr != nil {
logger.Warnf(c.Request.Context(), "Failed to fill KB counts for %s: %v", kb.ID, fillErr)
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": kb,
@@ -230,10 +271,11 @@ func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
// ListKnowledgeBases godoc
// @Summary 获取知识库列表
// @Description 获取当前租户的所有知识库
// @Description 获取当前租户的所有知识库;或当传入 agent_id(共享智能体)时,校验权限后返回该智能体配置的知识库范围(用于 @ 提及)
// @Tags 知识库
// @Accept json
// @Produce json
// @Param agent_id query string false "共享智能体 ID(传入时返回该智能体可用的知识库)"
// @Success 200 {object} map[string]interface{} "知识库列表"
// @Failure 500 {object} errors.AppError "服务器错误"
// @Security Bearer
@@ -242,11 +284,66 @@ func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
ctx := c.Request.Context()
agentID := c.Query("agent_id")
if agentID != "" {
userIDVal, ok := c.Get(types.UserIDContextKey.String())
if !ok {
c.Error(apperrors.NewUnauthorizedError("user ID not found"))
return
}
userID, _ := userIDVal.(string)
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
if currentTenantID == 0 {
c.Error(apperrors.NewUnauthorizedError("tenant ID not found"))
return
}
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID)
if err != nil {
if stderrors.Is(err, service.ErrAgentShareNotFound) || stderrors.Is(err, service.ErrAgentSharePermission) || stderrors.Is(err, service.ErrAgentNotFoundForShare) {
c.Error(apperrors.NewForbiddenError("no permission for this shared agent"))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
mode := agent.Config.KBSelectionMode
if mode == "none" {
c.JSON(http.StatusOK, gin.H{"success": true, "data": []interface{}{}})
return
}
sourceTenantID := agent.TenantID
kbs, err := h.service.ListKnowledgeBasesByTenantID(ctx, sourceTenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
if mode == "selected" && len(agent.Config.KnowledgeBases) > 0 {
allowed := make(map[string]bool)
for _, id := range agent.Config.KnowledgeBases {
allowed[id] = true
}
filtered := make([]*types.KnowledgeBase, 0, len(kbs))
for _, kb := range kbs {
if allowed[kb.ID] {
filtered = append(filtered, kb)
}
}
kbs = filtered
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": kbs,
})
return
}
// Get all knowledge bases for this tenant
kbs, err := h.service.ListKnowledgeBases(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
@@ -308,7 +405,7 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) {
// Only admin/editor can update knowledge base
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
c.Error(errors.NewForbiddenError("No permission to update knowledge base"))
c.Error(apperrors.NewForbiddenError("No permission to update knowledge base"))
return
}
@@ -316,7 +413,7 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) {
var req UpdateKnowledgeBaseRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
@@ -327,7 +424,7 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) {
kb, err := h.service.UpdateKnowledgeBase(ctx, id, req.Name, req.Description, req.Config)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
@@ -365,7 +462,7 @@ func (h *KnowledgeBaseHandler) DeleteKnowledgeBase(c *gin.Context) {
// Only owner (admin with matching tenant) can delete knowledge base
tenantID, _ := c.Get(types.TenantIDContextKey.String())
if kb.TenantID != tenantID.(uint64) || permission != types.OrgRoleAdmin {
c.Error(errors.NewForbiddenError("Only knowledge base owner can delete"))
c.Error(apperrors.NewForbiddenError("Only knowledge base owner can delete"))
return
}
@@ -375,7 +472,7 @@ func (h *KnowledgeBaseHandler) DeleteKnowledgeBase(c *gin.Context) {
// Delete the knowledge base
if err := h.service.DeleteKnowledgeBase(ctx, id); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
@@ -418,7 +515,7 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
var req CopyKnowledgeBaseRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
@@ -426,7 +523,7 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
tenantID, exists := c.Get(types.TenantIDContextKey.String())
if !exists {
logger.Error(ctx, "Failed to get tenant ID")
c.Error(errors.NewUnauthorizedError("Unauthorized"))
c.Error(apperrors.NewUnauthorizedError("Unauthorized"))
return
}
@@ -486,7 +583,7 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
payloadBytes, err := json.Marshal(payload)
if err != nil {
logger.Errorf(ctx, "Failed to marshal KB clone payload: %v", err)
c.Error(errors.NewInternalServerError("Failed to create task"))
c.Error(apperrors.NewInternalServerError("Failed to create task"))
return
}
@@ -496,7 +593,7 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
info, err := h.asynqClient.Enqueue(task)
if err != nil {
logger.Errorf(ctx, "Failed to enqueue KB clone task: %v", err)
c.Error(errors.NewInternalServerError("Failed to enqueue task"))
c.Error(apperrors.NewInternalServerError("Failed to enqueue task"))
return
}
@@ -548,7 +645,7 @@ func (h *KnowledgeBaseHandler) GetKBCloneProgress(c *gin.Context) {
taskID := c.Param("task_id")
if taskID == "" {
logger.Error(ctx, "Task ID is empty")
c.Error(errors.NewBadRequestError("Task ID cannot be empty"))
c.Error(apperrors.NewBadRequestError("Task ID cannot be empty"))
return
}
@@ -576,55 +673,55 @@ func validateExtractConfig(config *types.ExtractConfig) error {
}
// Validate text field
if config.Text == "" {
return errors.NewBadRequestError("text cannot be empty")
return apperrors.NewBadRequestError("text cannot be empty")
}
// Validate tags field
if len(config.Tags) == 0 {
return errors.NewBadRequestError("tags cannot be empty")
return apperrors.NewBadRequestError("tags cannot be empty")
}
for i, tag := range config.Tags {
if tag == "" {
return errors.NewBadRequestError("tag cannot be empty at index " + strconv.Itoa(i))
return apperrors.NewBadRequestError("tag cannot be empty at index " + strconv.Itoa(i))
}
}
// Validate nodes
if len(config.Nodes) == 0 {
return errors.NewBadRequestError("nodes cannot be empty")
return apperrors.NewBadRequestError("nodes cannot be empty")
}
nodeNames := make(map[string]bool)
for i, node := range config.Nodes {
if node.Name == "" {
return errors.NewBadRequestError("node name cannot be empty at index " + strconv.Itoa(i))
return apperrors.NewBadRequestError("node name cannot be empty at index " + strconv.Itoa(i))
}
// Check for duplicate node names
if nodeNames[node.Name] {
return errors.NewBadRequestError("duplicate node name: " + node.Name)
return apperrors.NewBadRequestError("duplicate node name: " + node.Name)
}
nodeNames[node.Name] = true
}
if len(config.Relations) == 0 {
return errors.NewBadRequestError("relations cannot be empty")
return apperrors.NewBadRequestError("relations cannot be empty")
}
// Validate relations
for i, relation := range config.Relations {
if relation.Node1 == "" {
return errors.NewBadRequestError("relation node1 cannot be empty at index " + strconv.Itoa(i))
return apperrors.NewBadRequestError("relation node1 cannot be empty at index " + strconv.Itoa(i))
}
if relation.Node2 == "" {
return errors.NewBadRequestError("relation node2 cannot be empty at index " + strconv.Itoa(i))
return apperrors.NewBadRequestError("relation node2 cannot be empty at index " + strconv.Itoa(i))
}
if relation.Type == "" {
return errors.NewBadRequestError("relation type cannot be empty at index " + strconv.Itoa(i))
return apperrors.NewBadRequestError("relation type cannot be empty at index " + strconv.Itoa(i))
}
// Check if referenced nodes exist
if !nodeNames[relation.Node1] {
return errors.NewBadRequestError("relation references non-existent node1: " + relation.Node1)
return apperrors.NewBadRequestError("relation references non-existent node1: " + relation.Node1)
}
if !nodeNames[relation.Node2] {
return errors.NewBadRequestError("relation references non-existent node2: " + relation.Node2)
return apperrors.NewBadRequestError("relation references non-existent node2: " + relation.Node2)
}
}
+164 -10
View File
@@ -18,27 +18,30 @@ import (
// OrganizationHandler implements HTTP request handlers for organization management
type OrganizationHandler struct {
orgService interfaces.OrganizationService
shareService interfaces.KBShareService
userService interfaces.UserService
knowledgeRepo interfaces.KnowledgeRepository
chunkRepo interfaces.ChunkRepository
orgService interfaces.OrganizationService
shareService interfaces.KBShareService
agentShareService interfaces.AgentShareService
userService interfaces.UserService
knowledgeRepo interfaces.KnowledgeRepository
chunkRepo interfaces.ChunkRepository
}
// NewOrganizationHandler creates a new organization handler
func NewOrganizationHandler(
orgService interfaces.OrganizationService,
shareService interfaces.KBShareService,
agentShareService interfaces.AgentShareService,
userService interfaces.UserService,
knowledgeRepo interfaces.KnowledgeRepository,
chunkRepo interfaces.ChunkRepository,
) *OrganizationHandler {
return &OrganizationHandler{
orgService: orgService,
shareService: shareService,
userService: userService,
knowledgeRepo: knowledgeRepo,
chunkRepo: chunkRepo,
orgService: orgService,
shareService: shareService,
agentShareService: agentShareService,
userService: userService,
knowledgeRepo: knowledgeRepo,
chunkRepo: chunkRepo,
}
}
@@ -392,6 +395,9 @@ func (h *OrganizationHandler) PreviewByInviteCode(c *gin.Context) {
// Get shared knowledge bases count
shares, _ := h.shareService.ListSharesByOrganization(ctx, org.ID)
shareCount := len(shares)
// Get shared agents count
agentShares, _ := h.agentShareService.ListSharesByOrganization(ctx, org.ID)
agentShareCount := len(agentShares)
// Check if user is already a member
_, memberErr := h.orgService.GetMember(ctx, org.ID, userID.(string))
@@ -406,6 +412,7 @@ func (h *OrganizationHandler) PreviewByInviteCode(c *gin.Context) {
"avatar": org.Avatar,
"member_count": memberCount,
"share_count": shareCount,
"agent_share_count": agentShareCount,
"is_already_member": isAlreadyMember,
"require_approval": org.RequireApproval,
"created_at": org.CreatedAt,
@@ -1102,6 +1109,149 @@ func (h *OrganizationHandler) ListSharedKnowledgeBases(c *gin.Context) {
})
}
// ShareAgent shares an agent to an organization
func (h *OrganizationHandler) ShareAgent(c *gin.Context) {
ctx := c.Request.Context()
agentID := c.Param("id")
userID, _ := c.Get(types.UserIDContextKey.String())
tenantID, _ := c.Get(types.TenantIDContextKey.String())
var req types.ShareKnowledgeBaseRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("Invalid request parameters").WithDetails(err.Error()))
return
}
share, err := h.agentShareService.ShareAgent(ctx, agentID, req.OrganizationID, userID.(string), tenantID.(uint64), req.Permission)
if err != nil {
logger.Errorf(ctx, "Failed to share agent: %v", err)
if errors.Is(err, service.ErrOrgRoleCannotShareAgent) {
c.Error(apperrors.NewForbiddenError("Only editors and admins can share agents to this organization"))
return
}
if errors.Is(err, service.ErrAgentNotConfigured) {
c.Error(apperrors.NewValidationError("Agent is not fully configured. Please set the chat model and, if using knowledge bases, the rerank model in agent settings."))
return
}
c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation"))
return
}
c.JSON(http.StatusCreated, gin.H{"success": true, "data": share})
}
// ListAgentShares lists all shares for an agent
func (h *OrganizationHandler) ListAgentShares(c *gin.Context) {
ctx := c.Request.Context()
agentID := c.Param("id")
shares, err := h.agentShareService.ListSharesByAgent(ctx, agentID)
if err != nil {
logger.Errorf(ctx, "Failed to list agent shares: %v", err)
c.Error(apperrors.NewInternalServerError("Failed to list shares"))
return
}
response := make([]types.AgentShareResponse, 0, len(shares))
for _, s := range shares {
resp := types.AgentShareResponse{
ID: s.ID, AgentID: s.AgentID, OrganizationID: s.OrganizationID,
SharedByUserID: s.SharedByUserID, SourceTenantID: s.SourceTenantID,
Permission: string(s.Permission), CreatedAt: s.CreatedAt,
}
if s.Organization != nil {
resp.OrganizationName = s.Organization.Name
}
response = append(response, resp)
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"shares": response, "total": len(response)}})
}
// RemoveAgentShare removes an agent share
func (h *OrganizationHandler) RemoveAgentShare(c *gin.Context) {
ctx := c.Request.Context()
shareID := c.Param("share_id")
userID, _ := c.Get(types.UserIDContextKey.String())
if err := h.agentShareService.RemoveShare(ctx, shareID, userID.(string)); err != nil {
logger.Errorf(ctx, "Failed to remove agent share: %v", err)
c.Error(apperrors.NewForbiddenError("Permission denied"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "message": "Share removed successfully"})
}
// ListOrgAgentShares lists all agents shared to an organization
func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) {
ctx := c.Request.Context()
orgID := c.Param("id")
userID, _ := c.Get(types.UserIDContextKey.String())
member, err := h.orgService.GetMember(ctx, orgID, userID.(string))
if err != nil {
c.Error(apperrors.NewForbiddenError("You are not a member of this organization"))
return
}
myRoleInOrg := member.Role
shares, err := h.agentShareService.ListSharesByOrganization(ctx, orgID)
if err != nil {
logger.Errorf(ctx, "Failed to list organization agent shares: %v", err)
c.Error(apperrors.NewInternalServerError("Failed to list shares"))
return
}
response := make([]types.AgentShareResponse, 0, len(shares))
for _, s := range shares {
effectivePerm := s.Permission
if !myRoleInOrg.HasPermission(s.Permission) {
effectivePerm = myRoleInOrg
}
resp := types.AgentShareResponse{
ID: s.ID, AgentID: s.AgentID, OrganizationID: s.OrganizationID,
SharedByUserID: s.SharedByUserID, SourceTenantID: s.SourceTenantID,
Permission: string(s.Permission), MyRoleInOrg: string(myRoleInOrg), MyPermission: string(effectivePerm), CreatedAt: s.CreatedAt,
}
if s.Agent != nil {
resp.AgentName = s.Agent.Name
resp.AgentAvatar = s.Agent.Avatar
cfg := &s.Agent.Config
if cfg.KBSelectionMode != "" {
resp.ScopeKB = cfg.KBSelectionMode
if cfg.KBSelectionMode == "selected" && len(cfg.KnowledgeBases) > 0 {
resp.ScopeKBCount = len(cfg.KnowledgeBases)
}
} else {
resp.ScopeKB = "none"
}
resp.ScopeWebSearch = cfg.WebSearchEnabled
if cfg.MCPSelectionMode != "" {
resp.ScopeMCP = cfg.MCPSelectionMode
if cfg.MCPSelectionMode == "selected" && len(cfg.MCPServices) > 0 {
resp.ScopeMCPCount = len(cfg.MCPServices)
}
} else {
resp.ScopeMCP = "none"
}
}
if s.Organization != nil {
resp.OrganizationName = s.Organization.Name
}
if u, err := h.userService.GetUserByID(ctx, s.SharedByUserID); err == nil && u != nil {
resp.SharedByUsername = u.Username
}
response = append(response, resp)
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"shares": response, "total": len(response)}})
}
// ListSharedAgents lists agents shared to the current user
func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) {
ctx := c.Request.Context()
userID, _ := c.Get(types.UserIDContextKey.String())
tenantID, _ := c.Get(types.TenantIDContextKey.String())
list, err := h.agentShareService.ListSharedAgents(ctx, userID.(string), tenantID.(uint64))
if err != nil {
logger.Errorf(ctx, "Failed to list shared agents: %v", err)
c.Error(apperrors.NewInternalServerError("Failed to list shared agents"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": list, "total": len(list)})
}
// toOrgResponse converts an organization to response format
func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Organization, currentUserID string) types.OrganizationResponse {
resp := types.OrganizationResponse{
@@ -1128,6 +1278,10 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga
if shares, err := h.shareService.ListSharesByOrganization(ctx, org.ID); err == nil {
resp.ShareCount = len(shares)
}
// Get shared agent count for this organization
if agentShares, err := h.agentShareService.ListSharesByOrganization(ctx, org.ID); err == nil {
resp.AgentShareCount = len(agentShares)
}
// Get current user's role in this organization
isAdmin := false
+6
View File
@@ -20,6 +20,8 @@ type Handler struct {
config *config.Config // Application configuration
knowledgebaseService interfaces.KnowledgeBaseService // Service for managing knowledge bases
customAgentService interfaces.CustomAgentService // Service for managing custom agents
tenantService interfaces.TenantService // Service for loading tenant (shared agent context)
agentShareService interfaces.AgentShareService // Service for resolving shared agents (KB scope in retrieval)
}
// NewHandler creates a new instance of Handler with all necessary dependencies
@@ -30,6 +32,8 @@ func NewHandler(
config *config.Config,
knowledgebaseService interfaces.KnowledgeBaseService,
customAgentService interfaces.CustomAgentService,
tenantService interfaces.TenantService,
agentShareService interfaces.AgentShareService,
) *Handler {
return &Handler{
sessionService: sessionService,
@@ -38,6 +42,8 @@ func NewHandler(
config: config,
knowledgebaseService: knowledgebaseService,
customAgentService: customAgentService,
tenantService: tenantService,
agentShareService: agentShareService,
}
}
+57 -28
View File
@@ -18,19 +18,20 @@ import (
// qaRequestContext holds all the common data needed for QA requests
type qaRequestContext struct {
ctx context.Context
c *gin.Context
sessionID string
requestID string
query string
session *types.Session
customAgent *types.CustomAgent
assistantMessage *types.Message
knowledgeBaseIDs []string
knowledgeIDs []string
summaryModelID string
webSearchEnabled bool
mentionedItems types.MentionedItems
ctx context.Context
c *gin.Context
sessionID string
requestID string
query string
session *types.Session
customAgent *types.CustomAgent
assistantMessage *types.Message
knowledgeBaseIDs []string
knowledgeIDs []string
summaryModelID string
webSearchEnabled bool
mentionedItems types.MentionedItems
effectiveTenantID uint64 // when using shared agent, tenant ID for model/KB/MCP resolution; 0 = use context tenant
}
// parseQARequest parses and validates a QA request, returns the request context
@@ -71,18 +72,36 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
return nil, nil, errors.NewNotFoundError("Session not found")
}
// Get custom agent if agent_id is provided
// Get custom agent if agent_id is provided. Backend resolves shared agent from share relation (no client-provided tenant).
var customAgent *types.CustomAgent
var effectiveTenantID uint64
if request.AgentID != "" {
logger.Infof(ctx, "Fetching custom agent, agent ID: %s", secutils.SanitizeForLog(request.AgentID))
agent, err := h.customAgentService.GetAgentByID(ctx, request.AgentID)
if err != nil {
logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
secutils.SanitizeForLog(request.AgentID), err)
logger.Infof(ctx, "Resolving agent, agent ID: %s", secutils.SanitizeForLog(request.AgentID))
userIDVal, _ := c.Get(types.UserIDContextKey.String())
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
if h.agentShareService != nil && userIDVal != nil && currentTenantID != 0 {
userID, _ := userIDVal.(string)
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, request.AgentID)
if err == nil && agent != nil {
effectiveTenantID = agent.TenantID
customAgent = agent
logger.Infof(ctx, "Using shared agent: ID=%s, Name=%s, effectiveTenantID=%d (retrieval scope)",
customAgent.ID, customAgent.Name, effectiveTenantID)
}
}
if customAgent == nil {
agent, err := h.customAgentService.GetAgentByID(ctx, request.AgentID)
if err == nil {
customAgent = agent
logger.Infof(ctx, "Using own agent: ID=%s, Name=%s, AgentMode=%s",
customAgent.ID, customAgent.Name, customAgent.Config.AgentMode)
} else {
logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
secutils.SanitizeForLog(request.AgentID), err)
}
} else {
customAgent = agent
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s",
customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode)
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s, effectiveTenantID=%d",
customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode, effectiveTenantID)
}
}
@@ -143,11 +162,12 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
RequestID: c.GetString(types.RequestIDContextKey.String()),
IsCompleted: false,
},
knowledgeBaseIDs: secutils.SanitizeForLogArray(kbIDs),
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
webSearchEnabled: request.WebSearchEnabled,
mentionedItems: convertMentionedItems(request.MentionedItems),
knowledgeBaseIDs: secutils.SanitizeForLogArray(kbIDs),
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
webSearchEnabled: request.WebSearchEnabled,
mentionedItems: convertMentionedItems(request.MentionedItems),
effectiveTenantID: effectiveTenantID,
}
return reqCtx, &request, nil
@@ -169,9 +189,18 @@ func (h *Handler) setupSSEStream(reqCtx *qaRequestContext, generateTitle bool) *
// Write initial agent_query event
h.writeAgentQueryEvent(reqCtx.ctx, reqCtx.sessionID, reqCtx.assistantMessage.ID)
// Base context for async work: when using shared agent, use source tenant for model/KB/MCP resolution
baseCtx := reqCtx.ctx
if reqCtx.effectiveTenantID != 0 && h.tenantService != nil {
if tenant, err := h.tenantService.GetTenantByID(reqCtx.ctx, reqCtx.effectiveTenantID); err == nil && tenant != nil {
baseCtx = context.WithValue(context.WithValue(reqCtx.ctx, types.TenantIDContextKey, reqCtx.effectiveTenantID), types.TenantInfoContextKey, tenant)
logger.Infof(reqCtx.ctx, "Using effective tenant %d for shared agent (model/KB/MCP)", reqCtx.effectiveTenantID)
}
}
// Create EventBus and cancellable context
eventBus := event.NewEventBus()
asyncCtx, cancel := context.WithCancel(logger.CloneContext(reqCtx.ctx))
asyncCtx, cancel := context.WithCancel(logger.CloneContext(baseCtx))
streamCtx := &sseStreamContext{
eventBus: eventBus,
+1 -1
View File
@@ -33,7 +33,7 @@ type CreateKnowledgeQARequest struct {
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
AgentID string `json:"agent_id"` // Selected custom agent ID for this request
AgentID string `json:"agent_id"` // Selected custom agent ID (backend resolves shared agent and its tenant from share relation)
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files
+12
View File
@@ -500,6 +500,8 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
orgs.PUT("/:id/join-requests/:request_id/review", orgHandler.ReviewJoinRequest)
// List knowledge bases shared to this organization
orgs.GET("/:id/shares", orgHandler.ListOrgShares)
// List agents shared to this organization
orgs.GET("/:id/agent-shares", orgHandler.ListOrgAgentShares)
}
// Knowledge base sharing routes (add to existing kb routes)
@@ -515,6 +517,16 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
kbShares.DELETE("/:share_id", orgHandler.RemoveShare)
}
// Agent sharing routes
agentShares := r.Group("/agents/:id/shares")
{
agentShares.POST("", orgHandler.ShareAgent)
agentShares.GET("", orgHandler.ListAgentShares)
agentShares.DELETE("/:share_id", orgHandler.RemoveAgentShare)
}
// Shared knowledge bases route
r.GET("/shared-knowledge-bases", orgHandler.ListSharedKnowledgeBases)
// Shared agents route
r.GET("/shared-agents", orgHandler.ListSharedAgents)
}
+4 -1
View File
@@ -19,7 +19,7 @@ type CustomAgentService interface {
// - Possible errors such as insufficient permissions, validation errors, etc.
CreateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error)
// GetAgentByID retrieves agent information by ID
// GetAgentByID retrieves agent information by ID (uses tenant from context)
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the agent
@@ -28,6 +28,9 @@ type CustomAgentService interface {
// - Possible errors such as not existing, insufficient permissions, etc.
GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error)
// GetAgentByIDAndTenant retrieves agent by ID and tenant (for shared agents; skips built-in resolution)
GetAgentByIDAndTenant(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error)
// ListAgents lists all agents under the current tenant (including built-in agents)
// Parameters:
// - ctx: Context information, containing tenant information
+2
View File
@@ -146,6 +146,8 @@ type KnowledgeService interface {
// SearchKnowledge searches knowledge items by keyword across the tenant.
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
// SearchKnowledgeForScopes searches knowledge within the given (tenant_id, kb_id) scopes (e.g. for shared agent context).
SearchKnowledgeForScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
}
// KnowledgeRepository defines the interface for knowledge repositories.
@@ -42,6 +42,12 @@ type KnowledgeBaseService interface {
// - Possible errors such as not existing, etc.
GetKnowledgeBaseByIDOnly(ctx context.Context, id string) (*types.KnowledgeBase, error)
// GetKnowledgeBasesByIDsOnly retrieves knowledge bases by IDs without tenant filter (batch).
GetKnowledgeBasesByIDsOnly(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error)
// FillKnowledgeBaseCounts fills KnowledgeCount, ChunkCount, IsProcessing, ProcessingCount for the given KB (uses kb.TenantID).
FillKnowledgeBaseCounts(ctx context.Context, kb *types.KnowledgeBase) error
// ListKnowledgeBases lists all knowledge bases under the current tenant
// Parameters:
// - ctx: Context information, containing tenant information
@@ -49,6 +55,8 @@ type KnowledgeBaseService interface {
// - List of knowledge base objects
// - Possible errors such as insufficient permissions, etc.
ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error)
// ListKnowledgeBasesByTenantID lists all knowledge bases for a specific tenant (e.g. for shared agent context).
ListKnowledgeBasesByTenantID(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBase, error)
// UpdateKnowledgeBase updates knowledge base information
// Parameters:
+29
View File
@@ -127,3 +127,32 @@ type KBShareRepository interface {
CountSharesByKnowledgeBaseID(ctx context.Context, kbID string) (int64, error)
CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error)
}
// AgentShareService defines the agent sharing service interface
type AgentShareService interface {
ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error)
RemoveShare(ctx context.Context, shareID string, userID string) error
ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error)
// GetSharedAgentForUser returns the shared agent by agentID if the user has access (source tenant is resolved from share); used to resolve KB scope for @ mention.
GetSharedAgentForUser(ctx context.Context, userID string, currentTenantID uint64, agentID string) (*types.CustomAgent, error)
GetShare(ctx context.Context, shareID string) (*types.AgentShare, error)
GetShareByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error)
}
// AgentShareRepository defines the agent sharing repository interface
type AgentShareRepository interface {
Create(ctx context.Context, share *types.AgentShare) error
GetByID(ctx context.Context, id string) (*types.AgentShare, error)
GetByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error)
Update(ctx context.Context, share *types.AgentShare) error
Delete(ctx context.Context, id string) error
DeleteByAgentIDAndSourceTenant(ctx context.Context, agentID string, sourceTenantID uint64) error
DeleteByOrganizationID(ctx context.Context, orgID string) error
ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error)
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID.
GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error)
}
+59
View File
@@ -210,6 +210,39 @@ type SharedKnowledgeBaseInfo struct {
SharedAt time.Time `json:"shared_at"`
}
// AgentShare represents a sharing record of an agent to an organization
type AgentShare struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
AgentID string `json:"agent_id" gorm:"type:varchar(36);not null;index"`
OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"`
SharedByUserID string `json:"shared_by_user_id" gorm:"type:varchar(36);not null"`
SourceTenantID uint64 `json:"source_tenant_id" gorm:"not null;index"`
Permission OrgMemberRole `json:"permission" gorm:"type:varchar(32);not null;default:'viewer'"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
Agent *CustomAgent `json:"agent,omitempty" gorm:"foreignKey:AgentID,SourceTenantID;references:ID,TenantID"`
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
}
// TableName returns the table name for GORM
func (AgentShare) TableName() string {
return "agent_shares"
}
// SharedAgentInfo represents a shared agent with additional sharing info
type SharedAgentInfo struct {
Agent *CustomAgent `json:"agent"`
ShareID string `json:"share_id"`
OrganizationID string `json:"organization_id"`
OrgName string `json:"org_name"`
Permission OrgMemberRole `json:"permission"`
SourceTenantID uint64 `json:"source_tenant_id"`
SharedAt time.Time `json:"shared_at"`
SharedByUserID string `json:"shared_by_user_id,omitempty"`
SharedByUsername string `json:"shared_by_username,omitempty"`
}
// ----------------------
// Request/Response Types
// ----------------------
@@ -302,6 +335,7 @@ type OrganizationResponse struct {
MemberLimit int `json:"member_limit"` // 0 = unlimited
MemberCount int `json:"member_count"`
ShareCount int `json:"share_count"` // 共享到该组织的知识库数量
AgentShareCount int `json:"agent_share_count"` // 共享到该组织的智能体数量
PendingJoinRequestCount int `json:"pending_join_request_count"` // 待审批加入申请数(仅管理员可见)
IsOwner bool `json:"is_owner"`
MyRole string `json:"my_role,omitempty"`
@@ -342,6 +376,30 @@ type KnowledgeBaseShareResponse struct {
RequireApproval bool `json:"require_approval"`
}
// AgentShareResponse represents an agent share record in API responses
type AgentShareResponse struct {
ID string `json:"id"`
AgentID string `json:"agent_id"`
AgentName string `json:"agent_name"`
OrganizationID string `json:"organization_id"`
OrganizationName string `json:"organization_name"`
SharedByUserID string `json:"shared_by_user_id"`
SharedByUsername string `json:"shared_by_username"`
SourceTenantID uint64 `json:"source_tenant_id"`
Permission string `json:"permission"`
MyRoleInOrg string `json:"my_role_in_org,omitempty"`
MyPermission string `json:"my_permission,omitempty"`
CreatedAt time.Time `json:"created_at"`
// Agent scope summary for list display (from agent config when available)
ScopeKB string `json:"scope_kb,omitempty"` // "all" | "selected" | "none"
ScopeKBCount int `json:"scope_kb_count,omitempty"` // when selected
ScopeWebSearch bool `json:"scope_web_search,omitempty"`
ScopeMCP string `json:"scope_mcp,omitempty"` // "all" | "selected" | "none"
ScopeMCPCount int `json:"scope_mcp_count,omitempty"` // when selected
// Agent avatar (emoji or icon name) for list display
AgentAvatar string `json:"agent_avatar,omitempty"`
}
// ListOrganizationsResponse represents the response for listing organizations
type ListOrganizationsResponse struct {
Organizations []OrganizationResponse `json:"organizations"`
@@ -357,6 +415,7 @@ type SearchableOrganizationItem struct {
MemberCount int `json:"member_count"`
MemberLimit int `json:"member_limit"` // 0 = unlimited
ShareCount int `json:"share_count"`
AgentShareCount int `json:"agent_share_count"` // 共享到该组织的智能体数量
IsAlreadyMember bool `json:"is_already_member"`
RequireApproval bool `json:"require_approval"`
}