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:
+154
-33
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user