Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🌐 chore: translate non-English comments to English in packages/openapi (#13184)

LobeHub Bot991de25b9757
diff --git a/packages/openapi/src/routes/message-translations.route.ts b/packages/openapi/src/routes/message-translations.route.ts
index 3a9aeb6a2af..9fef6a100c7 100644
--- a/packages/openapi/src/routes/message-translations.route.ts
+++ b/packages/openapi/src/routes/message-translations.route.ts
@@ -12,10 +12,10 @@ import {
MessageTranslateTriggerRequestSchema,
} from '../types/message-translations.type';
-// Message Translate 相关路由
+// Message Translate related routes
const MessageTranslationRoutes = new Hono();
-// POST /api/v1/message-translates - 翻译指定消息
+// POST /api/v1/message-translates - Translate specified message
MessageTranslationRoutes.post(
'/:messageId',
requireAuth,
@@ -35,7 +35,7 @@ MessageTranslationRoutes.post(
},
);
-// GET /api/v1/message-translates - 获取指定消息的翻译信息
+// GET /api/v1/message-translates - Get translation info for specified message
MessageTranslationRoutes.get(
'/:messageId',
requireAuth,
@@ -54,7 +54,7 @@ MessageTranslationRoutes.get(
},
);
-// PUT /api/v1/message-translates/:messageId - 更新消息翻译信息
+// PUT /api/v1/message-translates/:messageId - Update message translation info
MessageTranslationRoutes.patch(
'/:messageId',
requireAuth,
@@ -74,7 +74,7 @@ MessageTranslationRoutes.patch(
},
);
-// DELETE /api/v1/message-translates/:messageId - 删除消息翻译信息
+// DELETE /api/v1/message-translates/:messageId - Delete message translation info
MessageTranslationRoutes.delete(
'/:messageId',
requireAuth,
diff --git a/packages/openapi/src/services/agent-group.service.ts b/packages/openapi/src/services/agent-group.service.ts
index a37c320563f..b7bf7b7e34f 100644
--- a/packages/openapi/src/services/agent-group.service.ts
+++ b/packages/openapi/src/services/agent-group.service.ts
@@ -14,8 +14,8 @@ import type {
} from '../types/agent-group.type';
/**
- * AgentGroup 服务实现类
- * 处理助理分类相关的业务逻辑
+ * AgentGroup service implementation class
+ * Handles business logic related to agent group categories
*/
export class AgentGroupService extends BaseService {
private sessionGroupModel: SessionGroupModel;
@@ -26,20 +26,20 @@ export class AgentGroupService extends BaseService {
}
/**
- * 获取助理分类列表
- * @returns 助理分类列表
+ * Get agent group list
+ * @returns Agent group list
*/
async getAgentGroups(): ServiceResult<AgentGroupListResponse> {
- this.log('info', '获取助理分类列表');
+ this.log('info', 'Getting agent group list');
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('AGENT_READ');
if (!permissionResult.isPermitted) {
throw this.createAuthorizationError(permissionResult.message || '无权访问助理分类列表');
}
- // 构建查询条件
+ // Build query conditions
const conditions = [];
if (permissionResult.condition?.userId) {
@@ -51,7 +51,7 @@ export class AgentGroupService extends BaseService {
where: and(...conditions),
});
- this.log('info', `查询到 ${agentGroupList.length} 个助理分类`);
+ this.log('info', `Found ${agentGroupList.length} agent groups`);
return agentGroupList;
} catch (error) {
@@ -60,21 +60,21 @@ export class AgentGroupService extends BaseService {
}
/**
- * 根据 ID 获取助理分类详情
- * @param groupId 助理分类 ID
- * @returns 助理分类详情
+ * Get agent group detail by ID
+ * @param groupId Agent group ID
+ * @returns Agent group detail
*/
async getAgentGroupById(groupId: string): ServiceResult<AgentGroupListResponse[0] | null> {
try {
- this.log('info', '根据 ID 获取助理分类详情', { groupId });
+ this.log('info', 'Getting agent group detail by ID', { groupId });
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('AGENT_READ');
if (!permissionResult.isPermitted) {
throw this.createAuthorizationError(permissionResult.message || '无权访问此助理分类');
}
- // 构建查询条件
+ // Build query conditions
const conditions = [eq(sessionGroups.id, groupId)];
if (permissionResult.condition?.userId) {
@@ -86,7 +86,7 @@ export class AgentGroupService extends BaseService {
});
if (!agentGroup) {
- this.log('warn', '助理分类不存在', { groupId });
+ this.log('warn', 'Agent group not found', { groupId });
return null;
}
@@ -97,15 +97,15 @@ export class AgentGroupService extends BaseService {
}
/**
- * 创建助理分类
- * @param request 创建请求参数
- * @returns 创建完成的助理分类 ID
+ * Create agent group
+ * @param request Create request parameters
+ * @returns ID of the created agent group
*/
async createAgentGroup(request: CreateAgentGroupRequest): ServiceResult<string> {
- this.log('info', '创建助理分类', { name: request.name, sort: request.sort });
+ this.log('info', 'Creating agent group', { name: request.name, sort: request.sort });
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('AGENT_CREATE');
if (!permissionResult.isPermitted) {
throw this.createAuthorizationError(permissionResult.message || '无权创建助理分类');
@@ -124,7 +124,7 @@ export class AgentGroupService extends BaseService {
throw this.createBusinessError('助理分类创建失败');
}
- this.log('info', '助理分类创建成功', { id: result.id, name: request.name });
+ this.log('info', 'Agent group created successfully', { id: result.id, name: request.name });
return result.id;
} catch (error) {
this.handleServiceError(error, '创建助理分类');
@@ -132,15 +132,15 @@ export class AgentGroupService extends BaseService {
}
/**
- * 更新助理分类
- * @param request 更新请求参数
- * @returns 更新结果
+ * Update agent group
+ * @param request Update request parameters
+ * @returns Update result
*/
async updateAgentGroup(request: UpdateAgentGroupRequest): ServiceResult<void> {
- this.log('info', '更新助理分类', { id: request.id, name: request.name });
+ this.log('info', 'Updating agent group', { id: request.id, name: request.name });
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('AGENT_UPDATE');
if (!permissionResult.isPermitted) {
throw this.createAuthorizationError(permissionResult.message || '无权更新助理分类');
@@ -148,7 +148,7 @@ export class AgentGroupService extends BaseService {
const { id, ...updateData } = request;
- // 检查助理分类是否存在
+ // Check if agent group exists
const existingGroup = await this.sessionGroupModel.findById(id);
if (!existingGroup) {
throw this.createBusinessError(`助理分类 ID "${id}" 不存在`);
@@ -159,43 +159,43 @@ export class AgentGroupService extends BaseService {
.set({ ...updateData, updatedAt: new Date() })
.where(and(eq(sessionGroups.id, id), eq(sessionGroups.userId, this.userId)));
- this.log('info', '助理分类更新成功', { id });
+ this.log('info', 'Agent group updated successfully', { id });
} catch (error) {
this.handleServiceError(error, '更新助理分类');
}
}
/**
- * 删除助理分类
- * @param request 删除请求参数
- * @returns 删除结果
+ * Delete agent group
+ * @param request Delete request parameters
+ * @returns Deletion result
*/
async deleteAgentGroup(request: DeleteAgentGroupRequest): ServiceResult<void> {
- this.log('info', '删除助理分类', { id: request.id });
+ this.log('info', 'Deleting agent group', { id: request.id });
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('AGENT_DELETE');
if (!permissionResult.isPermitted) {
throw this.createAuthorizationError(permissionResult.message || '无权删除助理分类');
}
- // 检查助理分类是否存在
+ // Check if agent group exists
const existingGroup = await this.sessionGroupModel.findById(request.id);
if (!existingGroup) {
throw this.createBusinessError(`助理分类 ID "${request.id}" 不存在`);
}
- // 构建查询条件
+ // Build query conditions
const conditions = [eq(sessionGroups.id, request.id)];
if (permissionResult.condition?.userId) {
conditions.push(eq(sessionGroups.userId, permissionResult.condition.userId));
}
- // 删除助理分类,分类内助理的 sessionGroupId 会通过数据库外键约束自动设为 null
+ // Delete agent group; the sessionGroupId of agents in the group will be automatically set to null via database foreign key constraint
await this.db.delete(sessionGroups).where(and(...conditions));
- this.log('info', '助理分类删除成功', { id: request.id });
+ this.log('info', 'Agent group deleted successfully', { id: request.id });
} catch (error) {
this.handleServiceError(error, '删除助理分类');
}
diff --git a/packages/openapi/src/services/file.service.ts b/packages/openapi/src/services/file.service.ts
index 81f19860a52..a3fb704ad27 100644
--- a/packages/openapi/src/services/file.service.ts
+++ b/packages/openapi/src/services/file.service.ts
@@ -56,8 +56,8 @@ import type {
} from '../types/knowledge-base.type';
/**
- * 文件上传服务类
- * 专门处理服务端模式的文件上传和管理功能
+ * File upload service class
+ * Handles file upload and management functionality in server mode
*/
export class FileUploadService extends BaseService {
private fileModel: FileModel;
@@ -68,8 +68,8 @@ export class FileUploadService extends BaseService {
private chunkModel: ChunkModel;
private asyncTaskModel: AsyncTaskModel;
private knowledgeBaseModel: KnowledgeBaseModel;
- // 延迟引入 ChunkService,避免循环依赖开销
- // 注意:ChunkService 仅在服务端环境可用
+ // Lazy import ChunkService to avoid circular dependency overhead
+ // Note: ChunkService is only available in server-side environments
constructor(db: LobeChatDatabase, userId: string) {
super(db, userId);
@@ -84,25 +84,25 @@ export class FileUploadService extends BaseService {
}
/**
- * 确保获取完整URL,避免重复拼接
- * 检查URL是否已经是完整URL,如果不是则生成完整URL
+ * Ensure a full URL is obtained, avoiding duplicate concatenation
+ * Checks whether the URL is already a full URL; if not, generates the full URL
*/
private async ensureFullUrl(url?: string): Promise<string> {
if (!url) {
return '';
}
- // 检查URL是否已经是完整URL(向后兼容历史数据)
+ // Check if URL is already a full URL (backward compatible with historical data)
if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
- return url; // 已经是完整URL,直接返回
+ return url; // Already a full URL, return directly
} else {
- // 相对路径,生成完整URL
+ // Relative path, generate full URL
return await this.coreFileService.getFullFileUrl(url);
}
}
/**
- * 转换为上传响应格式
+ * Convert to upload response format
*/
private async convertToResponse(file: FileItem): Promise<FileDetailResponse['file']> {
const fullUrl = await this.ensureFullUrl(file.url);
@@ -114,7 +114,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 校验知识库归属(仅允许当前用户的知识库)
+ * Validate knowledge base ownership (only allows the current user's knowledge bases)
*/
private async assertOwnedKnowledgeBase(
knowledgeBaseId: string,
@@ -139,7 +139,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 批量文件上传
+ * Batch file upload
*/
async uploadFiles(request: BatchFileUploadRequest): Promise<BatchFileUploadResponse> {
try {
@@ -190,21 +190,21 @@ export class FileUploadService extends BaseService {
}
/**
- * 获取文件列表,支持三种场景:
- * 1. 获取当前用户的文件(默认)
- * 2. 获取指定用户的文件(需要 ALL 权限,或目标用户是自己)
- * 3. 获取系统中所有用户的文件(需要 ALL 权限,queryAll=true)
+ * Get file list, supporting three scenarios:
+ * 1. Get files for the current user (default)
+ * 2. Get files for a specified user (requires ALL permission, or target user is self)
+ * 3. Get files for all users in the system (requires ALL permission, queryAll=true)
*/
async getFileList(request: FileListQuery): Promise<FileListResponse> {
try {
- // 检查是否有全局权限
+ // Check whether global permission is available
const hasGlobalPermission = await this.hasGlobalPermission('FILE_READ');
- // 根据请求参数决定权限校验的资源范围
- // 1. queryAll=true 时,使用 ALL_SCOPE 查询全量数据
- // 2. 指定 userId 时,查询指定用户的数据
- // 3. 如果查询知识库文件且有全局权限,使用 ALL_SCOPE 以获取所有文件
- // 4. 否则查询当前用户的数据
+ // Determine resource scope for permission check based on request parameters
+ // 1. When queryAll=true, use ALL_SCOPE to query all data
+ // 2. When userId is specified, query data for that user
+ // 3. If querying knowledge base files and global permission exists, use ALL_SCOPE to get all files
+ // 4. Otherwise query current user's data
let resourceInfo: { targetUserId: string } | typeof ALL_SCOPE | undefined;
if (request.queryAll) {
@@ -212,7 +212,7 @@ export class FileUploadService extends BaseService {
} else if (request.userId) {
resourceInfo = { targetUserId: request.userId };
} else if (request.knowledgeBaseId && hasGlobalPermission) {
- // 查询知识库文件时,如果有全局权限,可查询所有文件
+ // When querying knowledge base files, if global permission exists, can query all files
resourceInfo = ALL_SCOPE;
}
@@ -228,15 +228,15 @@ export class FileUploadService extends BaseService {
queryAll: request.queryAll,
});
- // 计算分页参数
+ // Calculate pagination parameters
const { limit, offset } = processPaginationConditions(request);
- // 构建查询条件
+ // Build query conditions
const { knowledgeBaseId } = request;
- // 如果指定了知识库ID,使用 JOIN 查询
+ // If knowledge base ID is specified, use JOIN query
if (knowledgeBaseId) {
- // 构建查询条件
+ // Build query conditions
const whereConditions = [
eq(knowledgeBaseFiles.knowledgeBaseId, knowledgeBaseId),
...this.buildFileWhereConditions(request, permissionResult),
@@ -244,7 +244,7 @@ export class FileUploadService extends BaseService {
const whereClause = and(...whereConditions);
- // 使用 JOIN 查询知识库关联的文件
+ // Use JOIN query for knowledge base associated files
const baseQuery = this.db
.select({ file: files })
.from(knowledgeBaseFiles)
@@ -269,7 +269,7 @@ export class FileUploadService extends BaseService {
const filesResult: FileItem[] = records.map((row) => row.file);
const total = totalResult[0]?.count || 0;
- // 构建响应 (JOIN查询需要手动获取关联数据)
+ // Build response (JOIN query requires manually fetching associated data)
const responseFiles = await this.buildFileListResponse(
filesResult,
true,
@@ -289,11 +289,11 @@ export class FileUploadService extends BaseService {
};
}
- // 未指定知识库ID,使用关系查询(自动 join user 和 knowledgeBases)
+ // No knowledge base ID specified, use relational query (auto join user and knowledgeBases)
const whereConditions = this.buildFileWhereConditions(request, permissionResult);
const whereClause = and(...whereConditions);
- // 当前 files 关系未定义 user/knowledgeBases,采用基础查询并手动补齐关联数据
+ // Current files relation does not define user/knowledgeBases, use basic query and manually supplement associated data
const queryOptions = {
limit,
offset,
@@ -311,7 +311,7 @@ export class FileUploadService extends BaseService {
const total = totalResult[0]?.count || 0;
- // 构建响应 (关系查询已包含 user 和 knowledgeBases)
+ // Build response (relational query already includes user and knowledgeBases)
const responseFiles = await this.buildFileListResponse(
filesResult,
true,
@@ -334,22 +334,22 @@ export class FileUploadService extends BaseService {
}
/**
- * 获取指定知识库下的文件列表
- * 复用 getFileList 的查询逻辑,但使用 KNOWLEDGE_BASE_READ 权限
+ * Get file list for a specified knowledge base
+ * Reuses getFileList query logic but uses KNOWLEDGE_BASE_READ permission
*/
async getKnowledgeBaseFileList(
knowledgeBaseId: string,
request: KnowledgeBaseFileListQuery,
): Promise<FileListResponse> {
try {
- // 权限校验(知识库读取权限)
+ // Permission check (knowledge base read permission)
const permissionResult = await this.resolveOperationPermission('KNOWLEDGE_BASE_READ');
if (!permissionResult.isPermitted) {
throw this.createAuthorizationError(permissionResult.message || '无权访问知识库文件列表');
}
- // 校验知识库访问权限与存在性
+ // Validate knowledge base access permission and existence
const knowledgeBase = await this.knowledgeBaseModel.findById(knowledgeBaseId);
if (!knowledgeBase) {
throw this.createNotFoundError('Knowledge base not found or access denied');
@@ -360,7 +360,7 @@ export class FileUploadService extends BaseService {
request,
});
- // 复用 getFileList 的查询逻辑
+ // Reuse getFileList query logic
const fileListQuery: FileListQuery = {
...request,
knowledgeBaseId,
@@ -381,7 +381,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 批量创建知识库与文件的关联
+ * Batch create associations between knowledge bases and files
*/
async addFilesToKnowledgeBase(
knowledgeBaseId: string,
@@ -428,7 +428,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 批量移除知识库与文件的关联
+ * Batch remove associations between knowledge bases and files
*/
async removeFilesFromKnowledgeBase(
knowledgeBaseId: string,
@@ -474,7 +474,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 批量移动文件到另一个知识库
+ * Batch move files to another knowledge base
*/
async moveFilesBetweenKnowledgeBases(
sourceKnowledgeBaseId: string,
@@ -485,11 +485,11 @@ export class FileUploadService extends BaseService {
throw this.createValidationError('目标知识库不能与源知识库相同');
}
- // 校验知识库归属
+ // Validate knowledge base ownership
await this.assertOwnedKnowledgeBase(sourceKnowledgeBaseId, 'KNOWLEDGE_BASE_UPDATE');
await this.assertOwnedKnowledgeBase(request.targetKnowledgeBaseId, 'KNOWLEDGE_BASE_UPDATE');
- // 校验文件归属
+ // Validate file ownership
const uniqueFileIds = Array.from(new Set(request.fileIds));
const ownedFiles = await this.db.query.files.findMany({
@@ -543,11 +543,11 @@ export class FileUploadService extends BaseService {
}
/**
- * 获取文件详情
+ * Get file detail
*/
async getFileDetail(fileId: string): Promise<FileDetailResponse> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('FILE_READ', {
targetFileId: fileId,
});
@@ -558,13 +558,13 @@ export class FileUploadService extends BaseService {
const file = await this.findFileByIdWithPermission(fileId, permissionResult);
- // 检查是否为图片文件
+ // Check if the file is an image
const isImage = file.fileType.startsWith('image/');
const convertedFile = await this.convertToResponse(file);
if (!isImage) {
- // 非图片文件:获取解析结果
+ // Non-image file: get parse result
try {
const parseResult = await this.parseFile(fileId, { skipExist: true });
@@ -573,7 +573,7 @@ export class FileUploadService extends BaseService {
parsed: parseResult,
};
} catch (parseError) {
- // 如果解析失败,仍然返回文件详情,但不包含解析结果
+ // If parsing fails, still return file details without parse result
this.log('warn', 'Failed to parse file content', {
error: parseError,
fileId,
@@ -601,11 +601,11 @@ export class FileUploadService extends BaseService {
}
/**
- * 获取文件预签名访问URL
+ * Get file pre-signed access URL
*/
async getFileUrl(fileId: string, options: FileUrlRequest = {}): Promise<FileUrlResponse> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('FILE_READ', {
targetFileId: fileId,
});
@@ -616,13 +616,13 @@ export class FileUploadService extends BaseService {
const file = await this.findFileByIdWithPermission(fileId, permissionResult);
- // 设置过期时间(默认1小时)
+ // Set expiry time (default 1 hour)
const expiresIn = options.expiresIn || 3600;
- // 使用S3服务生成预签名URL
+ // Use S3 service to generate pre-signed URL
const signedUrl = await this.s3Service.createPreSignedUrlForPreview(file.url, expiresIn);
- // 计算过期时间戳
+ // Calculate expiry timestamp
const expiresAt = new Date(Date.now() + expiresIn * 1000).toISOString();
this.log('info', 'File URL generated successfully', {
@@ -644,7 +644,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 文件上传
+ * File upload
*/
async uploadFile(file: File, options: PublicFileUploadRequest = {}): Promise<FileDetailResponse> {
try {
@@ -661,15 +661,15 @@ export class FileUploadService extends BaseService {
type: file.type,
});
- // 1. 验证文件
+ // 1. Validate file
await this.validateFile(file, options.skipCheckFileType);
- // 2. 计算文件哈希
+ // 2. Calculate file hash
const fileArrayBuffer = await file.arrayBuffer();
const hash = sha256(fileArrayBuffer);
const resolvedSessionId = await this.resolveSessionId(options);
- // 3. 检查文件是否已存在(去重逻辑)
+ // 3. Check if file already exists (deduplication logic)
if (!options.skipDeduplication) {
const existingFileCheck = await this.fileModel.checkHash(hash);
@@ -680,17 +680,17 @@ export class FileUploadService extends BaseService {
name: file.name,
});
- // 检查当前用户是否已经有这个文件的记录
+ // Check if the current user already has a record for this file
const existingUserFile = await this.findExistingUserFile(hash);
if (existingUserFile) {
- // 用户已有此文件记录,直接返回
+ // User already has this file record, return directly
this.log('info', 'User already has this public file record', {
fileId: existingUserFile.id,
name: existingUserFile.name,
});
- // 如果提供了 sessionId(支持 agentId 解析),创建文件和会话的关联关系
+ // If sessionId is provided (supports agentId resolution), create file-session association
if (resolvedSessionId) {
await this.createFileSessionRelation(existingUserFile.id, resolvedSessionId);
this.log('info', 'Existing public file associated with session', {
@@ -701,7 +701,7 @@ export class FileUploadService extends BaseService {
return await this.getFileDetail(existingUserFile.id);
} else {
- // 文件在全局表中存在,但用户没有记录,创建用户文件记录
+ // File exists in global table but user has no record, create user file record
this.log('info', 'Public file exists globally, creating user file record', {
hash,
name: file.name,
@@ -721,9 +721,9 @@ export class FileUploadService extends BaseService {
userId: this.userId,
};
- const createResult = await this.fileModel.create(fileRecord, false); // 不插入全局表,因为已存在
+ const createResult = await this.fileModel.create(fileRecord, false); // Skip inserting into global table since it already exists
- // 如果提供了 sessionId(支持 agentId 解析),创建文件和会话的关联关系
+ // If sessionId is provided (supports agentId resolution), create file-session association
if (resolvedSessionId) {
await this.createFileSessionRelation(createResult.id, resolvedSessionId);
this.log('info', 'Deduplicated public file associated with session', {
@@ -745,14 +745,14 @@ export class FileUploadService extends BaseService {
}
}
- // 4. 文件不存在,正常上传流程
+ // 4. File does not exist, proceed with normal upload flow
const metadata = this.generateFileMetadata(file, options.directory);
- // 5. 上传到 S3
+ // 5. Upload to S3
const fileBuffer = Buffer.from(fileArrayBuffer);
await this.s3Service.uploadBuffer(metadata.path, fileBuffer, file.type);
- // 7. 保存文件记录到数据库
+ // 7. Save file record to database
const fileRecord = {
chunkTaskId: null,
clientId: null,
@@ -769,7 +769,7 @@ export class FileUploadService extends BaseService {
const createResult = await this.fileModel.create(fileRecord, true);
- // 如果提供了 sessionId(支持 agentId 解析),创建文件和会话的关联关系
+ // If sessionId is provided (supports agentId resolution), create file-session association
if (resolvedSessionId) {
await this.createFileSessionRelation(createResult.id, resolvedSessionId);
this.log('info', 'Public file associated with session', {
@@ -785,14 +785,14 @@ export class FileUploadService extends BaseService {
}
/**
- * 解析文件内容
+ * Parse file content
*/
async parseFile(
fileId: string,
options: Partial<FileParseRequest> = {},
): Promise<FileParseResponse> {
try {
- // 1. 权限校验
+ // 1. Permission check
const permissionResult = await this.resolveOperationPermission('FILE_READ', {
targetFileId: fileId,
});
@@ -801,17 +801,17 @@ export class FileUploadService extends BaseService {
throw this.createAuthorizationError(permissionResult.message || '无权访问此文件');
}
- // 2. 查询文件
+ // 2. Query file
const file = await this.findFileByIdWithPermission(fileId, permissionResult);
- // 3. 检查文件类型是否支持解析
+ // 3. Check if file type supports parsing
if (isChunkingUnsupported(file.fileType)) {
throw this.createBusinessError(
`File type '${file.fileType}' does not support content parsing`,
);
}
- // 4. 检查是否已经解析过(如果不跳过已存在的)
+ // 4. Check if file has already been parsed (if not skipping existing)
if (!options.skipExist) {
const existingDocument = await this.documentModel.findByFileId(fileId);
if (existingDocument) {
@@ -842,7 +842,7 @@ export class FileUploadService extends BaseService {
});
try {
- // 5. 使用 DocumentService 解析文件
+ // 5. Use DocumentService to parse file
const document = await this.documentService.parseFile(fileId);
this.log('info', 'File parsed successfully', {
@@ -852,7 +852,7 @@ export class FileUploadService extends BaseService {
totalCharCount: document.totalCharCount,
});
- // 6. 返回解析结果
+ // 6. Return parse result
return {
content: document.content || '',
fileId,
@@ -877,7 +877,7 @@ export class FileUploadService extends BaseService {
name: file.name,
});
- // 返回失败结果
+ // Return failure result
return {
content: '',
error: errorMessage,
@@ -894,14 +894,14 @@ export class FileUploadService extends BaseService {
}
/**
- * 创建分块任务(可选自动触发嵌入)
+ * Create chunking task (optionally auto-trigger embedding)
*/
async createChunkTask(
fileId: string,
req: Partial<FileChunkRequest> = {},
): Promise<FileChunkResponse> {
try {
- // 权限:更新文件即可
+ // Permission: file update is sufficient
const permissionResult = await this.resolveOperationPermission('FILE_UPDATE', {
targetFileId: fileId,
});
@@ -915,7 +915,7 @@ export class FileUploadService extends BaseService {
throw this.createBusinessError(`File type '${file.fileType}' does not support chunking`);
}
- // 触发分块异步任务
+ // Trigger async chunking task
const { ChunkService } = await import('@/server/services/chunk');
const chunkService = new ChunkService(this.db, this.userId);
@@ -946,11 +946,11 @@ export class FileUploadService extends BaseService {
}
/**
- * 查询文件分块与嵌入任务状态
+ * Query file chunking and embedding task status
*/
async getFileChunkStatus(fileId: string) {
try {
- // 权限:读取文件即可
+ // Permission: file read is sufficient
const permissionResult = await this.resolveOperationPermission('FILE_READ', {
targetFileId: fileId,
});
@@ -983,11 +983,11 @@ export class FileUploadService extends BaseService {
}
/**
- * 删除文件
+ * Delete file
*/
async deleteFile(fileId: string): Promise<void> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('FILE_DELETE', {
targetFileId: fileId,
});
@@ -998,10 +998,10 @@ export class FileUploadService extends BaseService {
const file = await this.findFileByIdWithPermission(fileId, permissionResult);
- // 删除S3文件
+ // Delete S3 file
await this.coreFileService.deleteFile(file.url);
- // 删除数据库记录及关联 chunks / global_files
+ // Delete database record and associated chunks / global_files
await this.fileModel.delete(fileId);
this.log('info', 'File deleted successfully', { fileId, key: file.url });
@@ -1013,10 +1013,10 @@ export class FileUploadService extends BaseService {
}
/**
- * 验证文件
+ * Validate file
*/
private async validateFile(file: File, skipCheckFileType = false): Promise<void> {
- // 文件大小限制 (100MB)
+ // File size limit (100MB)
const maxSize = 100 * 1024 * 1024;
if (file.size > maxSize) {
throw this.createBusinessError(
@@ -1024,12 +1024,12 @@ export class FileUploadService extends BaseService {
);
}
- // 文件名长度限制
+ // Filename length limit
if (file.name.length > 255) {
throw this.createBusinessError('Filename is too long (max 255 characters)');
}
- // 检查文件类型(如果未跳过检查)
+ // Check file type (if check is not skipped)
if (!skipCheckFileType) {
const allowedTypes = [
'image/',
@@ -1048,7 +1048,7 @@ export class FileUploadService extends BaseService {
'application/json',
];
- // 基于文件扩展名的额外验证(用于处理 application/octet-stream 等通用类型)
+ // Additional validation based on file extension (for handling generic types like application/octet-stream)
const allowedExtensions = [
'.yaml',
'.yml',
@@ -1090,7 +1090,7 @@ export class FileUploadService extends BaseService {
const fileExtension = file.name.toLowerCase().slice(Math.max(0, file.name.lastIndexOf('.')));
const isExtensionAllowed = allowedExtensions.includes(fileExtension);
- // 如果文件类型不被允许,但扩展名是允许的(处理 application/octet-stream 等情况)
+ // If file type is not allowed but extension is allowed (handles application/octet-stream cases)
if (!isAllowed && !isExtensionAllowed) {
throw this.createBusinessError(`File type '${file.type}' is not supported`);
}
@@ -1098,7 +1098,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 生成文件元数据
+ * Generate file metadata
*/
private generateFileMetadata(file: File, directory?: string): FileMetadata {
const now = new Date();
@@ -1116,7 +1116,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 解析上传请求中的 sessionId(agentId 优先,sessionId 兼容)
+ * Resolve sessionId from upload request (agentId takes priority, sessionId as fallback)
*/
private async resolveSessionId(options: PublicFileUploadRequest): Promise<string | undefined> {
if (!options.agentId) {
@@ -1143,7 +1143,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 创建文件和会话的关联关系
+ * Create file-session association
*/
private async createFileSessionRelation(fileId: string, sessionId: string): Promise<void> {
try {
@@ -1167,7 +1167,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 批量获取文件详情和内容
+ * Batch retrieve file details and content
*/
async handleQueries(request: BatchGetFilesRequest): Promise<BatchGetFilesResponse> {
try {
@@ -1179,10 +1179,10 @@ export class FileUploadService extends BaseService {
const files: BatchGetFilesResponse['files'] = [];
const failed: BatchGetFilesResponse['failed'] = [];
- // 并行处理所有文件
+ // Process all files in parallel
const promises = request.fileIds.map(async (fileId) => {
try {
- // 获取文件详情
+ // Get file detail
const fileDetail = await this.getFileDetail(fileId);
files.push(fileDetail);
@@ -1199,7 +1199,7 @@ export class FileUploadService extends BaseService {
}
});
- // 等待所有异步操作完成
+ // Wait for all async operations to complete
await Promise.all(promises);
const result: BatchGetFilesResponse = {
@@ -1222,7 +1222,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 查找用户是否已有指定哈希的文件记录
+ * Find whether the user already has a file record for the specified hash
*/
private async findExistingUserFile(hash: string): Promise<FileItem | null> {
try {
@@ -1237,7 +1237,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 构建文件查询的 WHERE 条件
+ * Build WHERE conditions for file queries
*/
private buildFileWhereConditions(
request: FileListQuery,
@@ -1250,22 +1250,22 @@ export class FileUploadService extends BaseService {
const { keyword, fileType, updatedAtStart, updatedAtEnd } = request;
const conditions = [];
- // 权限条件
+ // Permission conditions
if (permissionResult?.condition?.userId) {
conditions.push(eq(files.userId, permissionResult.condition.userId));
}
- // 关键词搜索
+ // Keyword search
if (keyword) {
conditions.push(ilike(files.name, `%${keyword}%`));
}
- // 文件类型过滤
+ // File type filter
if (fileType) {
conditions.push(ilike(files.fileType, `${fileType}%`));
}
- // 更新时间区间
+ // Updated time range
if (updatedAtStart) {
conditions.push(gte(files.updatedAt, new Date(updatedAtStart)));
}
@@ -1303,10 +1303,10 @@ export class FileUploadService extends BaseService {
}
/**
- * 批量获取文件关联数据并构建响应
- * @param filesResult 文件列表(FileItem 或带关系的文件对象)
- * @param needsManualRelationFetch 是否需要手动获取关联数据(JOIN查询时需要)
- * @param hasGlobalPermission 是否有全局权限(决定是否显示所有关联用户)
+ * Batch fetch file associated data and build response
+ * @param filesResult File list (FileItem or file objects with relations)
+ * @param needsManualRelationFetch Whether to manually fetch associated data (required for JOIN queries)
+ * @param hasGlobalPermission Whether global permission is available (determines whether to show all associated users)
*/
private async buildFileListResponse(
filesResult: (FileItem & {
@@ -1318,7 +1318,7 @@ export class FileUploadService extends BaseService {
): Promise<FileDetailResponse['file'][]> {
if (filesResult.length === 0) return [];
- // 1. 按 fileHash 去重(相同 hash 的文件只保留第一个)
+ // 1. Deduplicate by fileHash (only keep the first file with the same hash)
const uniqueFilesByHash = new Map<string, (typeof filesResult)[0]>();
for (const file of filesResult) {
const key = file.fileHash || file.id;
@@ -1331,7 +1331,7 @@ export class FileUploadService extends BaseService {
const fileIds = dedupedFiles.map((file) => file.id);
const fileHashes = dedupedFiles.map((file) => file.fileHash).filter(Boolean) as string[];
- // 批量查询分块、任务状态
+ // Batch query chunk counts and task statuses
const [chunkCounts, chunkTasks, embeddingTasks] = await Promise.all([
this.chunkModel.countByFileIds(fileIds),
this.asyncTaskModel.findByIds(
@@ -1344,21 +1344,21 @@ export class FileUploadService extends BaseService {
),
]);
- // 2. 查询所有相同 hash 的文件对应的用户
- // 只有全局权限时才查询所有用户,否则只返回当前文件的用户
+ // 2. Query users associated with all files having the same hash
+ // Only query all users when global permission is available; otherwise only return the current file's user
const hashUsersMap = new Map<string, any[]>();
if (hasGlobalPermission && fileHashes.length > 0) {
- // 查询所有相同 hash 的文件
+ // Query all files with the same hash
const allFilesWithSameHash = await this.db.query.files.findMany({
columns: { fileHash: true, userId: true },
where: inArray(files.fileHash, fileHashes),
});
- // 收集所有用户 ID
+ // Collect all user IDs
const allUserIds = [...new Set(allFilesWithSameHash.map((f) => f.userId))];
- // 查询用户信息
+ // Query user info
const allUsers =
allUserIds.length > 0
? await this.db.query.users.findMany({
@@ -1367,7 +1367,7 @@ export class FileUploadService extends BaseService {
})
: [];
- // 构建 hash -> users 映射
+ // Build hash -> users mapping
for (const file of allFilesWithSameHash) {
if (!file.fileHash) continue;
const user = allUsers.find((u) => u.id === file.userId);
@@ -1375,7 +1375,7 @@ export class FileUploadService extends BaseService {
if (!hashUsersMap.has(file.fileHash)) {
hashUsersMap.set(file.fileHash, []);
}
- // 避免重复添加同一用户
+ // Avoid adding the same user twice
const existingUsers = hashUsersMap.get(file.fileHash)!;
if (!existingUsers.some((u) => u.id === user.id)) {
existingUsers.push(user);
@@ -1384,7 +1384,7 @@ export class FileUploadService extends BaseService {
}
}
- // 如果是 JOIN 查询,需要单独查询知识库和用户信息
+ // For JOIN queries, need to separately query knowledge base and user info
let fileKnowledgeBases: any[] = [];
let usersData: any[] = [];
@@ -1418,7 +1418,7 @@ export class FileUploadService extends BaseService {
]);
}
- // 构建响应数据
+ // Build response data
return Promise.all(
dedupedFiles.map(async (file) => {
const base = await this.convertToResponse(file);
@@ -1431,7 +1431,7 @@ export class FileUploadService extends BaseService {
? embeddingTasks.find((task) => task.id === file.embeddingTaskId)
: null;
- // 获取知识库信息
+ // Get knowledge base info
const knowledgeBases = needsManualRelationFetch
? fileKnowledgeBases
.filter((kb) => kb.fileId === file.id)
@@ -1443,14 +1443,14 @@ export class FileUploadService extends BaseService {
}))
: file.knowledgeBases?.map((kb) => kb.knowledgeBase) || [];
- // 获取用户信息
+ // Get user info
let fileUsers = [];
if (hasGlobalPermission && file.fileHash && hashUsersMap.has(file.fileHash)) {
- // 全局权限:返回所有关联该 hash 的用户
+ // Global permission: return all users associated with this hash
fileUsers = hashUsersMap.get(file.fileHash) || [];
} else {
- // 非全局权限:只返回当前文件的用户
+ // Non-global permission: only return the current file's user
const currentUser = needsManualRelationFetch
? usersData.find((u) => u.id === file.userId) || null
: file.user || null;
@@ -1492,7 +1492,7 @@ export class FileUploadService extends BaseService {
}
/**
- * 更新文件
+ * Update file
* PATCH /files/:id
*/
async updateFile(
@@ -1500,7 +1500,7 @@ export class FileUploadService extends BaseService {
updateData: { knowledgeBaseId?: string | null },
): Promise<FileDetailResponse> {
try {
- // 1. 权限校验
+ // 1. Permission check
const permissionResult = await this.resolveOperationPermission('FILE_UPDATE', {
targetFileId: fileId,
});
@@ -1508,13 +1508,13 @@ export class FileUploadService extends BaseService {
throw this.createAuthorizationError(permissionResult.message || '无权更新文件');
}
- // 2. 查询文件
+ // 2. Query file
const file = await this.findFileByIdWithPermission(fileId, permissionResult);
- // 3. 处理知识库关联
+ // 3. Handle knowledge base association
if ('knowledgeBaseId' in updateData) {
await this.db.transaction(async (trx) => {
- // 删除现有的知识库关联(对于全局权限用户,使用文件的实际 userId)
+ // Delete existing knowledge base association (for global permission users, use the file's actual userId)
const targetUserId = file.userId;
await trx
.delete(knowledgeBaseFiles)
@@ -1525,9 +1525,9 @@ export class FileUploadService extends BaseService {
),
);
- // 如果提供了新的知识库ID,创建新的关联
+ // If a new knowledge base ID is provided, create a new association
if (updateData.knowledgeBaseId) {
- // 验证知识库是否存在且用户有权访问
+ // Validate that the knowledge base exists and the user has access
const knowledgeBase = await this.knowledgeBaseModel.findById(
updateData.knowledgeBaseId,
);
@@ -1545,7 +1545,7 @@ export class FileUploadService extends BaseService {
});
}
- // 4. 获取更新后的文件详情
+ // 4. Get updated file detail
const updatedFile = await this.getFileDetail(fileId);
return updatedFile;
diff --git a/packages/openapi/src/services/knowledge-base.service.ts b/packages/openapi/src/services/knowledge-base.service.ts
index 43ce3072a2a..12e57d67f95 100644
--- a/packages/openapi/src/services/knowledge-base.service.ts
+++ b/packages/openapi/src/services/knowledge-base.service.ts
@@ -20,8 +20,8 @@ import type {
} from '../types/knowledge-base.type';
/**
- * 知识库服务类
- * 处理知识库的增删改查功能
+ * Knowledge base service class
+ * Handles CRUD operations for knowledge bases
*/
export class KnowledgeBaseService extends BaseService {
private knowledgeBaseModel: KnowledgeBaseModel;
@@ -32,11 +32,11 @@ export class KnowledgeBaseService extends BaseService {
}
/**
- * 获取知识库列表
+ * Get knowledge base list
*/
async getKnowledgeBaseList(request: KnowledgeBaseListQuery): Promise<KnowledgeBaseListResponse> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('KNOWLEDGE_BASE_READ');
if (!permissionResult.isPermitted) {
@@ -45,7 +45,7 @@ export class KnowledgeBaseService extends BaseService {
this.log('info', 'Getting knowledge base list', request);
- // 计算分页参数与查询条件
+ // Calculate pagination parameters and query conditions
const { limit, offset } = processPaginationConditions(request);
const { keyword } = request;
@@ -74,7 +74,7 @@ export class KnowledgeBaseService extends BaseService {
const total = totalResult[0]?.count || 0;
- // 添加访问类型
+ // Add access type
const knowledgeBasesWithAuthorization = items.map((item) => {
const accessType: KnowledgeBaseAccessType = 'owner';
@@ -99,11 +99,11 @@ export class KnowledgeBaseService extends BaseService {
}
/**
- * 获取知识库详情
+ * Get knowledge base detail
*/
async getKnowledgeBaseDetail(id: string): Promise<KnowledgeBaseDetailResponse> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('KNOWLEDGE_BASE_READ');
if (!permissionResult.isPermitted) {
@@ -112,7 +112,7 @@ export class KnowledgeBaseService extends BaseService {
this.log('info', 'Getting knowledge base detail', { id });
- // 使用模型的 findById 方法,它包含了访问权限和启用状态的检查
+ // Use the model's findById method, which includes access permission and enabled status checks
const knowledgeBase = await this.knowledgeBaseModel.findById(id);
if (!knowledgeBase) {
@@ -130,13 +130,13 @@ export class KnowledgeBaseService extends BaseService {
}
/**
- * 创建知识库
+ * Create knowledge base
*/
async createKnowledgeBase(
request: CreateKnowledgeBaseRequest,
): Promise<CreateKnowledgeBaseResponse> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('KNOWLEDGE_BASE_CREATE');
if (!permissionResult.isPermitted) {
@@ -147,7 +147,7 @@ export class KnowledgeBaseService extends BaseService {
name: request.name,
});
- // 创建知识库
+ // Create knowledge base
const createData: Parameters<KnowledgeBaseModel['create']>[0] = {
name: request.name,
};
@@ -171,14 +171,14 @@ export class KnowledgeBaseService extends BaseService {
}
/**
- * 更新知识库
+ * Update knowledge base
*/
async updateKnowledgeBase(
id: string,
request: UpdateKnowledgeBaseRequest,
): Promise<KnowledgeBaseDetailResponse> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('KNOWLEDGE_BASE_UPDATE');
if (!permissionResult.isPermitted) {
@@ -187,7 +187,7 @@ export class KnowledgeBaseService extends BaseService {
this.log('info', 'Updating knowledge base', { id, request });
- // 检查知识库是否存在且属于当前用户
+ // Check if knowledge base exists and belongs to the current user
const existingKb = await this.db.query.knowledgeBases.findFirst({
where: and(eq(knowledgeBases.id, id), eq(knowledgeBases.userId, this.userId)),
});
@@ -196,10 +196,10 @@ export class KnowledgeBaseService extends BaseService {
throw this.createNotFoundError('Knowledge base not found or access denied');
}
- // 更新知识库
+ // Update knowledge base
await this.knowledgeBaseModel.update(id, request);
- // 获取更新后的知识库信息
+ // Get updated knowledge base info
const updatedKb = await this.db.query.knowledgeBases.findFirst({
where: eq(knowledgeBases.id, id),
});
@@ -215,11 +215,11 @@ export class KnowledgeBaseService extends BaseService {
}
/**
- * 删除知识库
+ * Delete knowledge base
*/
async deleteKnowledgeBase(id: string): Promise<DeleteKnowledgeBaseResponse> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('KNOWLEDGE_BASE_DELETE');
if (!permissionResult.isPermitted) {
@@ -228,7 +228,7 @@ export class KnowledgeBaseService extends BaseService {
this.log('info', 'Deleting knowledge base', { id });
- // 检查知识库是否存在且属于当前用户
+ // Check if knowledge base exists and belongs to the current user
const existingKb = await this.db.query.knowledgeBases.findFirst({
where: and(eq(knowledgeBases.id, id), eq(knowledgeBases.userId, this.userId)),
});
@@ -237,7 +237,7 @@ export class KnowledgeBaseService extends BaseService {
throw this.createNotFoundError('Knowledge base not found or access denied');
}
- // 删除知识库
+ // Delete knowledge base
await this.knowledgeBaseModel.delete(id);
this.log('info', 'Knowledge base deleted successfully', { id });
diff --git a/packages/openapi/src/services/message-translations.service.ts b/packages/openapi/src/services/message-translations.service.ts
index d259e74ce3d..b1889085156 100644
--- a/packages/openapi/src/services/message-translations.service.ts
+++ b/packages/openapi/src/services/message-translations.service.ts
@@ -21,12 +21,12 @@ export class MessageTranslateService extends BaseService {
}
/**
- * 根据消息ID获取翻译信息
- * @param messageId 消息ID
- * @returns 翻译信息
+ * Get translation info by message ID
+ * @param messageId Message ID
+ * @returns Translation info
*/
async getTranslateByMessageId(messageId: string): ServiceResult<MessageTranslateResponse | null> {
- // 权限检查已在路由层完成 (MESSAGE_READ + TRANSLATION_READ)
+ // Permission check is already done in the route layer (MESSAGE_READ + TRANSLATION_READ)
this.log('info', '根据消息ID获取翻译信息', { messageId, userId: this.userId });
@@ -57,14 +57,14 @@ export class MessageTranslateService extends BaseService {
}
/**
- * 创建或更新消息翻译
- * @param translateData 翻译数据
- * @returns 翻译结果
+ * Create or update message translation
+ * @param translateData Translation data
+ * @returns Translation result
*/
async translateMessage(
translateData: MessageTranslateTriggerRequest,
): ServiceResult<Partial<MessageTranslateItem>> {
- // 权限检查已在路由层完成 (MESSAGE_READ + TRANSLATION_CREATE)
+ // Permission check is already done in the route layer (MESSAGE_READ + TRANSLATION_CREATE)
this.log('info', '开始翻译消息', {
...translateData,
@@ -72,7 +72,7 @@ export class MessageTranslateService extends BaseService {
});
try {
- // 首先获取原始消息内容和 sessionId
+ // First fetch the original message content and sessionId
const messageInfo = await this.db.query.messages.findFirst({
where: eq(messages.id, translateData.messageId),
});
@@ -83,7 +83,7 @@ export class MessageTranslateService extends BaseService {
this.log('info', '原始消息内容', { originalMessage: messageInfo.content });
- // 使用ChatService进行翻译,传递 sessionId 以使用正确的模型配置
+ // Use ChatService for translation, passing sessionId to use the correct model configuration
const chatService = new ChatService(this.db, this.userId);
const translatedContent = await chatService.translate({
...translateData,
@@ -91,7 +91,7 @@ export class MessageTranslateService extends BaseService {
text: removeSystemContext(messageInfo.content),
});
- // 使用 updateTranslateInfo 来更新翻译内容
+ // Use updateTranslateInfo to update translation content
return this.updateTranslateInfo({
from: translateData.from,
messageId: translateData.messageId,
@@ -104,17 +104,17 @@ export class MessageTranslateService extends BaseService {
}
/**
- * 更新消息翻译信息
- * @param data 翻译信息更新数据
- * @returns 更新后的翻译结果
+ * Update message translation info
+ * @param data Translation info update data
+ * @returns Updated translation result
*/
async updateTranslateInfo(
data: MessageTranslateInfoUpdate,
): ServiceResult<Partial<MessageTranslateItem>> {
- // 权限检查已在路由层完成 (MESSAGE_UPDATE + TRANSLATION_UPDATE)
+ // Permission check is already done in the route layer (MESSAGE_UPDATE + TRANSLATION_UPDATE)
try {
- // 检查消息是否存在
+ // Check if message exists
const messageInfo = await this.db.query.messages.findFirst({
where: eq(messages.id, data.messageId),
});
@@ -122,7 +122,7 @@ export class MessageTranslateService extends BaseService {
throw this.createCommonError('未找到要更新翻译信息的消息');
}
- // 更新翻译信息和内容
+ // Update translation info and content
await this.db
.insert(messageTranslates)
.values({
@@ -156,17 +156,17 @@ export class MessageTranslateService extends BaseService {
}
/**
- * 删除指定消息的翻译信息
- * @param messageId 消息ID
- * @returns 删除结果
+ * Delete translation info for the specified message
+ * @param messageId Message ID
+ * @returns Deletion result
*/
async deleteTranslateByMessageId(
messageId: string,
): ServiceResult<{ deleted: boolean; messageId: string }> {
- // 权限检查已在路由层完成 (TRANSLATION_DELETE)
+ // Permission check is already done in the route layer (TRANSLATION_DELETE)
try {
- // 检查翻译消息是否存在
+ // Check if the translation message exists
const originalTranslation = await this.db.query.messageTranslates.findFirst({
where: eq(messageTranslates.id, messageId),
});
diff --git a/packages/openapi/src/services/topic.service.ts b/packages/openapi/src/services/topic.service.ts
index 8e0fa567cc9..f326d28cbc3 100644
--- a/packages/openapi/src/services/topic.service.ts
+++ b/packages/openapi/src/services/topic.service.ts
@@ -20,32 +20,32 @@ export class TopicService extends BaseService {
}
/**
- * 获取话题列表(支持按 agent/group 过滤)
- * @param request 查询参数
- * @returns 话题列表
+ * Get topic list (supports filtering by agent/group)
+ * @param request Query parameters
+ * @returns Topic list
*/
async getTopics(request: TopicListQuery): Promise<TopicListResponse> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('TOPIC_READ');
if (!permissionResult.isPermitted) {
throw this.createAuthorizationError(permissionResult.message || '没有权限访问话题列表');
}
- // 构建查询条件
+ // Build query conditions
const conditions = [];
- // 添加权限相关的查询条件
+ // Add permission-related query conditions
if (permissionResult?.condition?.userId) {
conditions.push(eq(topics.userId, permissionResult.condition.userId));
}
- // 优先按 groupId 过滤
+ // Filter by groupId first
if (request.groupId) {
conditions.push(eq(topics.groupId, request.groupId));
} else if (request.agentId) {
- // 通过 agentId 反查 sessionId,再按 sessionId 过滤
+ // Reverse-lookup sessionId from agentId, then filter by sessionId
const [relation] = await this.db
.select({ sessionId: agentsToSessions.sessionId })
.from(agentsToSessions)
@@ -55,31 +55,31 @@ export class TopicService extends BaseService {
if (relation) {
conditions.push(eq(topics.sessionId, relation.sessionId));
} else {
- // agentId 不存在对应 session,直接返回空
+ // No session found for agentId, return empty directly
return { topics: [], total: 0 };
}
} else if (request.isInbox) {
- // inbox:sessionId 为 null 且 groupId 为 null 且 agentId 为 null
+ // inbox: sessionId is null, groupId is null, and agentId is null
conditions.push(isNull(topics.sessionId));
conditions.push(isNull(topics.groupId));
conditions.push(isNull(topics.agentId));
}
- // 排除指定触发来源的话题
+ // Exclude topics with specified trigger sources
if (request.excludeTriggers && request.excludeTriggers.length > 0) {
conditions.push(notInArray(topics.trigger, request.excludeTriggers));
}
- // 如果有关键词,添加标题的模糊搜索条件
+ // If keyword is provided, add fuzzy search condition on title
if (request.keyword) {
conditions.push(ilike(topics.title, `%${request.keyword}%`));
}
- // 统一查询路径与并发计数/列表
+ // Unified query path with concurrent count/list
const { limit, offset } = processPaginationConditions(request);
const whereExpr = conditions.length ? and(...conditions) : undefined;
- // 构建列表查询基础
+ // Build base list query
const baseListQuery = this.db
.select({
messageCount: count(messages.id),
@@ -93,10 +93,10 @@ export class TopicService extends BaseService {
.orderBy(desc(topics.favorite), desc(topics.createdAt))
.where(whereExpr);
- // 分页参数
+ // Pagination parameters
const listQuery = limit ? baseListQuery.limit(limit).offset(offset!) : baseListQuery;
- // 构建计数查询
+ // Build count query
const countQuery = this.db.select({ count: count() }).from(topics).where(whereExpr);
const [result, [countResult]] = await Promise.all([listQuery, countQuery]);
@@ -116,7 +116,7 @@ export class TopicService extends BaseService {
async getTopicById(topicId: string): Promise<TopicResponse> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('TOPIC_READ', {
targetTopicId: topicId,
});
@@ -125,10 +125,10 @@ export class TopicService extends BaseService {
throw this.createAuthorizationError(permissionResult.message || '没有权限访问该话题');
}
- // 构建查询条件
+ // Build query conditions
const whereConditions = [eq(topics.id, topicId)];
- // 应用权限条件
+ // Apply permission conditions
if (permissionResult.condition?.userId) {
whereConditions.push(eq(topics.userId, permissionResult.condition.userId));
}
@@ -161,15 +161,15 @@ export class TopicService extends BaseService {
}
/**
- * 创建新的话题
- * @param payload 创建参数
- * @returns 创建的话题信息
+ * Create a new topic
+ * @param payload Create parameters
+ * @returns Created topic info
*/
async createTopic(payload: TopicCreateRequest): Promise<TopicResponse> {
try {
const { agentId, groupId, title, favorite, clientId } = payload;
- // agentId 时反查 sessionId
+ // When agentId is provided, reverse-lookup sessionId
let effectiveSessionId: string | null = null;
if (!effectiveSessionId && agentId) {
@@ -212,14 +212,14 @@ export class TopicService extends BaseService {
}
/**
- * 更新话题
- * @param topicId 话题ID
- * @param title 话题标题
- * @returns 更新后的话题信息
+ * Update topic
+ * @param topicId Topic ID
+ * @param title Topic title
+ * @returns Updated topic info
*/
async updateTopic(topicId: string, payload: TopicUpdateRequest): Promise<Partial<TopicResponse>> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('TOPIC_UPDATE', {
targetTopicId: topicId,
});
@@ -228,10 +228,10 @@ export class TopicService extends BaseService {
throw this.createAuthorizationError(permissionResult.message || '没有权限更新该话题');
}
- // 构建查询条件检查话题是否存在
+ // Build query conditions to check if topic exists
const whereConditions = [eq(topics.id, topicId)];
- // 应用权限条件
+ // Apply permission conditions
if (permissionResult.condition?.userId) {
whereConditions.push(eq(topics.userId, permissionResult.condition.userId));
}
@@ -253,12 +253,12 @@ export class TopicService extends BaseService {
}
/**
- * 删除话题
- * @param topicId 话题ID
+ * Delete topic
+ * @param topicId Topic ID
*/
async deleteTopic(topicId: string): Promise<void> {
try {
- // 权限校验
+ // Permission check
const permissionResult = await this.resolveOperationPermission('TOPIC_DELETE', {
targetTopicId: topicId,
});
@@ -267,10 +267,10 @@ export class TopicService extends BaseService {
throw this.createAuthorizationError(permissionResult.message || '没有权限删除该话题');
}
- // 构建查询条件检查话题是否存在
+ // Build query conditions to check if topic exists
const whereConditions = [eq(topics.id, topicId)];
- // 应用权限条件
+ // Apply permission conditions
if (permissionResult.condition?.userId) {
whereConditions.push(eq(topics.userId, permissionResult.condition.userId));
}
@@ -284,7 +284,7 @@ export class TopicService extends BaseService {
throw this.createNotFoundError('话题不存在');
}
- this.log('info', '话题删除成功', { topicId });
+ this.log('info', 'Topic deleted successfully', { topicId });
} catch (error) {
return this.handleServiceError(error, '删除话题');
}
diff --git a/packages/openapi/src/types/file.type.ts b/packages/openapi/src/types/file.type.ts
index 08b44b076a9..e3c40bd3c92 100644
--- a/packages/openapi/src/types/file.type.ts
+++ b/packages/openapi/src/types/file.type.ts
@@ -8,29 +8,29 @@ import { PaginationQuerySchema } from './common.type';
// ==================== File Upload Types ====================
/**
- * 文件上传请求类型
+ * File upload request type
*/
export interface FileUploadRequest {
- /** Agent ID(可选,优先于 sessionId) */
+ /** Agent ID (optional, takes priority over sessionId) */
agentId?: string;
- /** 文件目录(可选) */
+ /** File directory (optional) */
directory?: string;
- /** 文件对象 */
+ /** File object */
file: File;
- /** 知识库ID(可选) */
+ /** Knowledge base ID (optional) */
knowledgeBaseId?: string;
- /** 自定义路径(可选) */
+ /** Custom path (optional) */
pathname?: string;
- /** 会话ID(可选) */
+ /** Session ID (optional) */
sessionId?: string;
- /** 是否跳过文件类型检查 */
+ /** Whether to skip file type check */
skipCheckFileType?: boolean;
- /** 是否跳过去重检查 */
+ /** Whether to skip deduplication check */
skipDeduplication?: boolean;
}
/**
- * 文件详情类型
+ * File detail response type
*/
export interface FileDetailResponse {
file: FileListItem;
@@ -38,40 +38,40 @@ export interface FileDetailResponse {
}
/**
- * 公共文件上传请求类型
+ * Public file upload request type
*/
export interface PublicFileUploadRequest {
- /** Agent ID(可选,优先于 sessionId) */
+ /** Agent ID (optional, takes priority over sessionId) */
agentId?: string;
- /** 文件目录(可选) */
+ /** File directory (optional) */
directory?: string;
- /** 知识库ID(可选) */
+ /** Knowledge base ID (optional) */
knowledgeBaseId?: string;
- /** 会话ID(可选) */
+ /** Session ID (optional) */
sessionId?: string;
- /** 是否跳过文件类型检查 */
+ /** Whether to skip file type check */
skipCheckFileType?: boolean;
- /** 是否跳过去重检查 */
+ /** Whether to skip deduplication check */
skipDeduplication?: boolean;
}
// ==================== File Management Types ====================
/**
- * 文件列表查询参数
+ * File list query parameters
*/
export interface FileListQuery extends IPaginationQuery {
- /** 文件类型过滤 */
+ /** File type filter */
fileType?: string;
- /** 知识库ID过滤 */
+ /** Knowledge base ID filter */
knowledgeBaseId?: string;
- /** 是否查询全量数据(需要 ALL 权限) */
+ /** Whether to query all data (requires ALL permission) */
queryAll?: boolean;
- /** 更新时间结束 */
+ /** Updated time end */
updatedAtEnd?: string;
- /** 更新时间起始 */
+ /** Updated time start */
updatedAtStart?: string;
- /** 用户ID */
+ /** User ID */
userId?: string;
}
@@ -89,22 +89,22 @@ export const FileListQuerySchema = PaginationQuerySchema.extend({
});
/**
- * 文件列表响应类型
+ * File list response type
*/
export type FileListResponse = PaginationQueryResponse<{
- /** 文件列表 */
+ /** File list */
files: FileDetailResponse['file'][];
- /** 文件总大小 */
+ /** Total file size */
totalSize?: string;
}>;
// ==================== File URL Types ====================
/**
- * 获取文件URL请求类型
+ * File URL request type
*/
export interface FileUrlRequest {
- /** 过期时间(秒),默认为系统配置值 */
+ /** Expiry time (seconds), defaults to system configured value */
expiresIn?: number;
}
@@ -117,53 +117,53 @@ export const FileUrlRequestSchema = z.object({
});
/**
- * 获取文件URL响应类型
+ * File URL response type
*/
export interface FileUrlResponse {
- /** URL过期时间戳 */
+ /** URL expiry timestamp */
expiresAt: string;
- /** URL过期时间(秒) */
+ /** URL expiry time (seconds) */
expiresIn: number;
- /** 文件ID */
+ /** File ID */
fileId: string;
- /** 文件名 */
+ /** Filename */
name: string;
- /** 预签名访问URL */
+ /** Pre-signed access URL */
url: string;
}
// ==================== Batch Operations ====================
/**
- * 批量文件上传请求类型
+ * Batch file upload request type
*/
export interface BatchFileUploadRequest {
- /** Agent ID(可选,优先于 sessionId) */
+ /** Agent ID (optional, takes priority over sessionId) */
agentId?: string;
- /** 上传目录(可选) */
+ /** Upload directory (optional) */
directory?: string;
- /** 文件列表 */
+ /** File list */
files: File[];
- /** 知识库ID(可选) */
+ /** Knowledge base ID (optional) */
knowledgeBaseId?: string;
- /** 会话ID(可选) */
+ /** Session ID (optional) */
sessionId?: string;
- /** 是否跳过文件类型检查 */
+ /** Whether to skip file type check */
skipCheckFileType?: boolean;
}
/**
- * 批量文件上传响应类型
+ * Batch file upload response type
*/
export interface BatchFileUploadResponse {
- /** 失败的文件及错误信息 */
+ /** Failed files and error messages */
failed: Array<{
error: string;
name: string;
}>;
- /** 成功上传的文件 */
+ /** Successfully uploaded files */
successful: FileDetailResponse[];
- /** 总计数量 */
+ /** Total count */
summary: {
failed: number;
successful: number;
@@ -172,10 +172,10 @@ export interface BatchFileUploadResponse {
}
/**
- * 批量获取文件请求类型
+ * Batch get files request type
*/
export interface BatchGetFilesRequest {
- /** 文件ID列表 */
+ /** File ID list */
fileIds: string[];
}
@@ -184,31 +184,31 @@ export const BatchGetFilesRequestSchema = z.object({
});
/**
- * 批量获取文件响应类型
+ * Batch get files response type
*/
export interface BatchGetFilesResponse {
- /** 失败的文件及错误信息 */
+ /** Failed files and error messages */
failed: Array<{
error: string;
fileId: string;
}>;
- /** 文件列表 */
+ /** File list */
files: Array<FileDetailResponse>;
- /** 成功获取的文件数 */
+ /** Number of successfully retrieved files */
success: number;
- /** 请求总数 */
+ /** Total number of requests */
total: number;
}
// ==================== File Parsing Types ====================
/**
- * 文件解析请求类型
+ * File parse request type
*/
export interface FileParseRequest {
- /** 文件ID */
+ /** File ID */
fileId: string;
- /** 是否跳过已存在的解析结果 */
+ /** Whether to skip existing parse results */
skipExist?: boolean;
}
@@ -221,45 +221,45 @@ export const FileParseRequestSchema = z.object({
});
/**
- * 文件解析响应类型
+ * File parse response type
*/
export interface FileParseResponse {
- /** 解析后的文本内容 */
+ /** Parsed text content */
content?: string;
- /** 解析错误信息 */
+ /** Parse error message */
error?: string;
- /** 文件ID */
+ /** File ID */
fileId: string;
- /** 文件类型 */
+ /** File type */
fileType: string;
- /** 文档元数据 */
+ /** Document metadata */
metadata?: {
- /** 页数 */
+ /** Number of pages */
pages?: number;
- /** 文档标题 */
+ /** Document title */
title?: string;
- /** 字符总数 */
+ /** Total character count */
totalCharCount?: number;
- /** 行总数 */
+ /** Total line count */
totalLineCount?: number;
};
- /** 文件名 */
+ /** Filename */
name: string;
- /** 解析时间 */
+ /** Parse time */
parsedAt?: string;
- /** 解析状态 */
+ /** Parse status */
parseStatus: 'completed' | 'failed';
}
// ==================== File Chunking Types ====================
/**
- * 文件分块任务请求
+ * File chunking task request
*/
export interface FileChunkRequest {
- /** 是否在分块成功后自动触发嵌入任务(可覆盖服务端默认开关) */
+ /** Whether to automatically trigger embedding task after chunking succeeds (can override server default) */
autoEmbedding?: boolean;
- /** 是否跳过已存在分块任务(或已存在的分块结果) */
+ /** Whether to skip existing chunking tasks (or existing chunked results) */
skipExist?: boolean;
}
@@ -269,21 +269,21 @@ export const FileChunkRequestSchema = z.object({
});
/**
- * 文件分块任务响应
+ * File chunking task response
*/
export interface FileChunkResponse {
- /** 分块异步任务ID */
+ /** Chunk async task ID */
chunkTaskId?: string | null;
- /** 嵌入异步任务ID(仅当 autoEmbedding=true 时存在) */
+ /** Embedding async task ID (only present when autoEmbedding=true) */
embeddingTaskId?: string | null;
fileId: string;
message?: string;
- /** 是否已触发 */
+ /** Whether it has been triggered */
success: boolean;
}
/**
- * 文件关联用户信息
+ * File associated user info
*/
export interface FileUserItem {
avatar?: string | null;
@@ -294,62 +294,62 @@ export interface FileUserItem {
}
/**
- * 文件列表项(包含可选的分块状态信息)
+ * File list item (includes optional chunking status info)
*/
export interface FileListItem extends Partial<FileItem> {
- /** 分块任务信息(包含基础异步任务信息与分块数量) */
+ /** Chunking task info (includes basic async task info and chunk count) */
chunking?: FileAsyncTaskResponse | null;
- /** 嵌入任务信息(包含基础异步任务信息) */
+ /** Embedding task info (includes basic async task info) */
embedding?: FileAsyncTaskResponse | null;
- /** 关联的知识库列表 */
+ /** Associated knowledge base list */
knowledgeBases?: Array<KnowledgeBaseItem>;
- /** 关联的用户列表(相同 fileHash 的所有用户) */
+ /** Associated user list (all users with the same fileHash) */
users?: Array<FileUserItem>;
}
/**
- * 异步任务错误信息
+ * Async task error info
*/
export interface AsyncTaskErrorResponse {
- /** 错误详情 */
+ /** Error details */
body: {
detail: string;
};
- /** 错误名称 */
+ /** Error name */
name: string;
}
/**
- * 文件相关异步任务基础信息(用于列表中的 chunking/embedding 字段)
+ * File async task basic info (used for chunking/embedding fields in the list)
*/
export interface FileAsyncTaskResponse {
- /** 分块数量(仅 chunking 任务会返回) */
+ /** Chunk count (only returned by chunking tasks) */
count?: number | null;
- /** 异步任务错误信息 */
+ /** Async task error info */
error?: AsyncTaskErrorResponse | null;
- /** 异步任务 ID */
+ /** Async task ID */
id?: string;
- /** 异步任务状态 */
+ /** Async task status */
status?: 'pending' | 'processing' | 'success' | 'error' | null;
- /** 异步任务类型 */
+ /** Async task type */
type?: 'chunk' | 'embedding' | 'image_generation';
}
/**
- * 文件分块状态响应
+ * File chunking status response
*/
export interface FileChunkStatusResponse {
- /** 分块数量 */
+ /** Chunk count */
chunkCount: number | null;
- /** 分块任务错误信息 */
+ /** Chunking task error info */
chunkingError?: AsyncTaskErrorResponse | null;
- /** 分块任务状态 */
+ /** Chunking task status */
chunkingStatus?: 'pending' | 'processing' | 'success' | 'error' | null;
- /** 嵌入任务错误信息 */
+ /** Embedding task error info */
embeddingError?: AsyncTaskErrorResponse | null;
- /** 嵌入任务状态 */
+ /** Embedding task status */
embeddingStatus?: 'pending' | 'processing' | 'success' | 'error' | null;
- /** 嵌入任务是否已完成 */
+ /** Whether the embedding task has completed */
finishEmbedding?: boolean;
}
@@ -362,10 +362,10 @@ export const FileIdParamSchema = z.object({
// ==================== File Update Types ====================
/**
- * 文件更新请求类型
+ * File update request type
*/
export interface UpdateFileRequest {
- /** 知识库ID(可选) */
+ /** Knowledge base ID (optional) */
knowledgeBaseId?: string | null;
}
diff --git a/packages/openapi/src/types/knowledge-base.type.ts b/packages/openapi/src/types/knowledge-base.type.ts
index f60c7120863..dbdc6fed7fd 100644
--- a/packages/openapi/src/types/knowledge-base.type.ts
+++ b/packages/openapi/src/types/knowledge-base.type.ts
@@ -8,19 +8,19 @@ import { PaginationQuerySchema } from './common.type';
// ==================== Knowledge Base Query Types ====================
/**
- * 知识库列表查询参数
+ * Knowledge base list query parameters
*/
export interface KnowledgeBaseListQuery extends IPaginationQuery {
- // 继承自 IPaginationQuery: keyword, page, pageSize
+ // Inherited from IPaginationQuery: keyword, page, pageSize
}
export const KnowledgeBaseListQuerySchema = PaginationQuerySchema;
/**
- * 知识库文件列表查询参数
+ * Knowledge base file list query parameters
*/
export interface KnowledgeBaseFileListQuery extends IPaginationQuery {
- /** 文件类型过滤 */
+ /** File type filter */
fileType?: string;
}
@@ -29,10 +29,10 @@ export const KnowledgeBaseFileListQuerySchema = PaginationQuerySchema.extend({
});
/**
- * 知识库文件批量操作请求
+ * Knowledge base file batch operation request
*/
export interface KnowledgeBaseFileBatchRequest {
- /** 文件 ID 列表 */
+ /** File ID list */
fileIds: string[];
}
@@ -41,10 +41,10 @@ export const KnowledgeBaseFileBatchSchema = z.object({
});
/**
- * 知识库文件移动请求
+ * Knowledge base file move request
*/
export interface MoveKnowledgeBaseFilesRequest extends KnowledgeBaseFileBatchRequest {
- /** 目标知识库 ID */
+ /** Target knowledge base ID */
targetKnowledgeBaseId: string;
}
@@ -53,64 +53,64 @@ export const MoveKnowledgeBaseFilesSchema = KnowledgeBaseFileBatchSchema.extend(
});
/**
- * 知识库文件批量操作结果
+ * Knowledge base file batch operation result
*/
export interface KnowledgeBaseFileOperationResult {
- /** 失败的文件及原因 */
+ /** Failed files and reasons */
failed: Array<{
fileId: string;
reason: string;
}>;
- /** 操作成功的文件 ID 列表 */
+ /** List of successfully operated file IDs */
successed: string[];
}
/**
- * 知识库文件移动结果
+ * Knowledge base file move result
*/
export interface MoveKnowledgeBaseFilesResponse {
- /** 失败的文件及原因 */
+ /** Failed files and reasons */
failed: Array<{
fileId: string;
reason: string;
}>;
- /** 成功移动的文件 ID 列表 */
+ /** List of successfully moved file IDs */
successed: string[];
}
/**
- * 知识库列表响应类型
+ * Knowledge base list response type
*/
export type KnowledgeBaseAccessType = 'owner' | 'userGrant' | 'roleGrant' | 'public';
export interface KnowledgeBaseListItem extends KnowledgeBaseItem {
- /** 当前用户对该知识库的访问来源类型 */
+ /** The access source type for the current user on this knowledge base */
accessType?: KnowledgeBaseAccessType;
}
export type KnowledgeBaseListResponse = PaginationQueryResponse<{
- /** 知识库列表 */
+ /** Knowledge base list */
knowledgeBases: KnowledgeBaseListItem[];
}>;
// ==================== Knowledge Base Management Types ====================
/**
- * 知识库ID参数
+ * Knowledge base ID parameter
*/
export const KnowledgeBaseIdParamSchema = z.object({
id: z.string().min(1, '知识库 ID 不能为空'),
});
/**
- * 创建知识库请求类型
+ * Create knowledge base request type
*/
export interface CreateKnowledgeBaseRequest {
- /** 知识库头像 */
+ /** Knowledge base avatar */
avatar?: string;
- /** 知识库描述 */
+ /** Knowledge base description */
description?: string;
- /** 知识库名称 */
+ /** Knowledge base name */
name: string;
}
@@ -121,22 +121,22 @@ export const CreateKnowledgeBaseSchema = z.object({
});
/**
- * 创建知识库响应类型
+ * Create knowledge base response type
*/
export interface CreateKnowledgeBaseResponse {
- /** 知识库信息 */
+ /** Knowledge base info */
knowledgeBase: KnowledgeBaseItem;
}
/**
- * 更新知识库请求类型
+ * Update knowledge base request type
*/
export interface UpdateKnowledgeBaseRequest {
- /** 知识库头像 */
+ /** Knowledge base avatar */
avatar?: string;
- /** 知识库描述 */
+ /** Knowledge base description */
description?: string;
- /** 知识库名称 */
+ /** Knowledge base name */
name?: string;
}
@@ -147,19 +147,19 @@ export const UpdateKnowledgeBaseSchema = z.object({
});
/**
- * 知识库详情响应类型
+ * Knowledge base detail response type
*/
export interface KnowledgeBaseDetailResponse {
- /** 知识库信息 */
+ /** Knowledge base info */
knowledgeBase: KnowledgeBaseItem;
}
/**
- * 删除知识库响应类型
+ * Delete knowledge base response type
*/
export interface DeleteKnowledgeBaseResponse {
- /** 响应消息 */
+ /** Response message */
message?: string;
- /** 是否删除成功 */
+ /** Whether the deletion was successful */
success: boolean;
}
diff --git a/packages/openapi/src/types/message.type.ts b/packages/openapi/src/types/message.type.ts
index b3a75017caa..a12e92e33a8 100644
--- a/packages/openapi/src/types/message.type.ts
+++ b/packages/openapi/src/types/message.type.ts
@@ -17,7 +17,7 @@ export const MessagesQueryByTopicRequestSchema = z.object({
});
/**
- * 消息数量统计查询参数
+ * Message count statistics query parameters
*/
export interface MessagesCountQuery {
topicIds?: string[];
@@ -25,9 +25,9 @@ export interface MessagesCountQuery {
}
export const MessagesCountQuerySchema = z.object({
- // 按话题ID数组统计 (comma-separated string, e.g., "topic1,topic2,topic3")
+ // Count by topic ID array (comma-separated string, e.g., "topic1,topic2,topic3")
topicIds: z.string().nullish(),
- // 按用户ID统计 (仅管理员)
+ // Count by user ID (admin only)
userId: z.string().nullish(),
});
@@ -50,7 +50,7 @@ export const CountByUserRequestSchema = z.object({
// ==================== Message List Query Types ====================
/**
- * 消息列表查询参数
+ * Message list query parameters
*/
export interface MessagesListQuery extends IPaginationQuery {
role?: 'user' | 'system' | 'assistant' | 'tool';
@@ -60,7 +60,7 @@ export interface MessagesListQuery extends IPaginationQuery {
export const MessagesListQuerySchema = z
.object({
- // 过滤参数
+ // Filter parameters
topicId: z.string().nullish(),
userId: z.string().nullish(),
role: z.enum(['user', 'system', 'assistant', 'tool']).nullish(),
@@ -88,22 +88,22 @@ export const SearchMessagesByKeywordRequestSchema = z.object({
export interface MessagesCreateRequest {
agentId?: string | null;
- // 客户端标识
+ // Client identifier
clientId?: string;
content: string;
- // 状态
+ // Status
favorite?: boolean;
- // 文件关联
+ // File association
files?: string[];
- // 扩展数据
+ // Extended data
metadata?: any;
- // AI相关字段
+ // AI-related fields
model?: string;
observationId?: string | null;
- // 消息关联
+ // Message association
parentId?: string | null;
provider?: string;
@@ -117,7 +117,7 @@ export interface MessagesCreateRequest {
topicId: string | null;
- // 追踪标识
+ // Tracking identifier
traceId?: string | null;
}
@@ -125,36 +125,36 @@ export const MessagesCreateRequestSchema = z.object({
content: z.string().min(1, '消息内容不能为空'),
role: z.enum(['user', 'system', 'assistant', 'tool'], { required_error: '角色类型无效' }),
- // AI相关字段
- model: z.string().nullish(), // 使用的模型
- provider: z.string().nullish(), // 提供商
+ // AI-related fields
+ model: z.string().nullish(), // Model used
+ provider: z.string().nullish(), // Provider
topicId: z.string().nullable().nullish(),
threadId: z.string().nullable().nullish(),
- // 消息关联
- parentId: z.string().nullable().nullish(), // 父消息ID
- quotaId: z.string().nullable().nullish(), // 引用消息ID
- agentId: z.string().nullable().nullish(), // 关联的Agent ID
+ // Message association
+ parentId: z.string().nullable().nullish(), // Parent message ID
+ quotaId: z.string().nullable().nullish(), // Quoted message ID
+ agentId: z.string().nullable().nullish(), // Associated Agent ID
- // 客户端标识
- clientId: z.string().nullish(), // 客户端ID,用于跨设备同步
+ // Client identifier
+ clientId: z.string().nullish(), // Client ID, used for cross-device sync
- // 扩展数据
- metadata: z.any().nullish(), // 元数据
- reasoning: z.any().nullish(), // 推理过程
- search: z.any().nullish(), // 搜索结果
- tools: z.any().nullish(), // 工具调用
+ // Extended data
+ metadata: z.any().nullish(), // Metadata
+ reasoning: z.any().nullish(), // Reasoning process
+ search: z.any().nullish(), // Search results
+ tools: z.any().nullish(), // Tool calls
- // 追踪标识
- traceId: z.string().nullable().nullish(), // 追踪ID
- observationId: z.string().nullable().nullish(), // 观测ID
+ // Tracking identifier
+ traceId: z.string().nullable().nullish(), // Trace ID
+ observationId: z.string().nullable().nullish(), // Observation ID
- // 文件关联
- files: z.array(z.string()).nullish(), // 文件ID数组
+ // File association
+ files: z.array(z.string()).nullish(), // File ID array
- // 状态
- favorite: z.boolean().nullish().default(false), // 是否收藏
+ // Status
+ favorite: z.boolean().nullish().default(false), // Whether favorited
});
export const MessagesCreateWithReplyRequestSchema = MessagesCreateRequestSchema.extend({
@@ -199,14 +199,14 @@ export interface MessageIdParam {
id: string;
}
-// 从数据库联表查询出来的消息类型,包含关联的 session 和 topic 信息
+// Message type queried from database join, includes associated session and topic info
export interface MessageResponseFromDatabase extends DBMessageItem {
filesToMessages: { file: FileItem; messageId: string }[] | null;
session: SessionItem | null;
topic: TopicItem | null;
}
-// 消息查询时的返回类型,包含关联的 session 和 topic 信息
+// Return type for message query, includes associated session and topic info
export interface MessageResponse extends Omit<MessageResponseFromDatabase, 'filesToMessages'> {
files: FileItem[] | null;
}
diff --git a/packages/openapi/src/types/user.type.ts b/packages/openapi/src/types/user.type.ts
index 44ff3518738..a98ff98190d 100644
--- a/packages/openapi/src/types/user.type.ts
+++ b/packages/openapi/src/types/user.type.ts
@@ -7,7 +7,7 @@ import type { IPaginationQuery, PaginationQueryResponse } from './common.type';
// ==================== User Base Types ====================
/**
- * 获取用户列表请求参数(可选分页)
+ * Get user list request parameters (optional pagination)
*/
export interface GetUsersRequest {
page?: number;
@@ -15,7 +15,7 @@ export interface GetUsersRequest {
}
/**
- * 扩展的用户信息类型,包含角色信息
+ * Extended user info type including role information
*/
export type UserWithRoles = UserItem & {
messageCount?: number;
@@ -25,7 +25,7 @@ export type UserWithRoles = UserItem & {
// ==================== User CRUD Types ====================
/**
- * 创建用户请求参数
+ * Create user request parameters
*/
export interface CreateUserRequest {
avatar?: string;
@@ -52,7 +52,7 @@ export const CreateUserRequestSchema = z.object({
});
/**
- * 更新用户请求参数
+ * Update user request parameters
*/
export interface UpdateUserRequest {
avatar?: string;
@@ -68,7 +68,7 @@ export interface UpdateUserRequest {
}
/**
- * 更新用户请求验证Schema
+ * Update user request validation schema
*/
export const UpdateUserRequestSchema = z.object({
avatar: z.string().nullish(),
@@ -96,10 +96,10 @@ export type UserListResponse = PaginationQueryResponse<{
// ==================== User Role Management Types ====================
/**
- * 单个添加角色的请求
+ * Request for adding a single role
*/
export interface AddRoleRequest {
- expiresAt?: string; // ISO 8601 格式的过期时间
+ expiresAt?: string; // Expiry time in ISO 8601 format
roleId: string;
}
@@ -109,11 +109,11 @@ export const AddRoleRequestSchema = z.object({
});
/**
- * 更新用户角色的请求参数
+ * Update user roles request parameters
*/
export interface UpdateUserRolesRequest {
- addRoles?: AddRoleRequest[]; // 要添加的角色
- removeRoles?: string[]; // 要移除的角色ID
+ addRoles?: AddRoleRequest[]; // Roles to add
+ removeRoles?: string[]; // Role IDs to remove
}
export const UpdateUserRolesRequestSchema = z
@@ -123,7 +123,7 @@ export const UpdateUserRolesRequestSchema = z
})
.refine(
(data) => {
- // 至少要有一个操作(添加或移除)
+ // At least one operation (add or remove) must be specified
return (
(data.addRoles && data.addRoles.length > 0) ||
(data.removeRoles && data.removeRoles.length > 0)
@@ -135,7 +135,7 @@ export const UpdateUserRolesRequestSchema = z
)
.refine(
(data) => {
- // 检查添加和移除的角色之间不能有重复
+ // Check that there are no overlapping roles between add and remove lists
if (!data.addRoles || !data.removeRoles) return true;
const addRoleIds = data.addRoles.map((r) => r.roleId);
@@ -150,14 +150,14 @@ export const UpdateUserRolesRequestSchema = z
);
/**
- * 用户角色详情,包含角色信息和关联信息
+ * User role detail, including role info and association info
*/
export interface UserRoleDetail extends UserRoleItem {
role: RoleItem;
}
/**
- * 用户角色操作响应
+ * User role operation response
*/
export type UserRolesResponse = {
expiresAt?: Date | null;
@@ -167,7 +167,7 @@ export type UserRolesResponse = {
}[];
/**
- * 用户角色操作结果
+ * User role operation result
*/
export interface UserRoleOperationResult {
added: number;