chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,462 @@
|
||||
import { get, post, put, del } from "../../utils/request";
|
||||
import type { AssistantAccessLevel } from "../assistant";
|
||||
|
||||
// 智能体配置
|
||||
// 智能推理下的智能体类型预设 ID
|
||||
// 'rag-qa' : 经典文档/FAQ 分块 RAG
|
||||
// 'wiki-qa' : Wiki 图谱导航问答
|
||||
// 'hybrid-rag-wiki': Wiki + 分块混合检索
|
||||
// 'custom' : 完全自定义(不应用预设)
|
||||
export type AgentType = 'rag-qa' | 'wiki-qa' | 'hybrid-rag-wiki' | 'data-analysis' | 'custom';
|
||||
|
||||
export interface QuestionSuggestionConfig {
|
||||
starters: {
|
||||
enabled: boolean;
|
||||
mode: 'curated' | 'knowledge' | 'hybrid';
|
||||
items: string[];
|
||||
count: number;
|
||||
};
|
||||
follow_ups: {
|
||||
enabled: boolean;
|
||||
mode: 'generated' | 'knowledge' | 'hybrid';
|
||||
count: number;
|
||||
model_id?: string;
|
||||
additional_instruction?: string;
|
||||
categories: Array<'clarify' | 'deepen' | 'action'>;
|
||||
max_context_turns: number;
|
||||
suppress_on_fallback: boolean;
|
||||
suppress_when_answer_asks_question: boolean;
|
||||
knowledge_fallback: boolean;
|
||||
allow_regenerate: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CustomAgentConfig {
|
||||
// ===== 基础设置 =====
|
||||
agent_mode?: 'quick-answer' | 'smart-reasoning'; // 运行模式:quick-answer=RAG模式, smart-reasoning=ReAct Agent模式
|
||||
// 智能推理模式下的类型预设,用于一键应用"系统提示词 + 工具 + KB 兼容性"组合
|
||||
// 仅在 agent_mode === 'smart-reasoning' 时生效;quick-answer 模式忽略
|
||||
agent_type?: AgentType;
|
||||
system_prompt?: string; // 统一系统提示词(使用 {{web_search_status}} 占位符动态控制行为)
|
||||
system_prompt_id?: string; // 引用的 prompt template ID(预设会填入此字段)
|
||||
context_template_id?: string; // Inherit the referenced context template when text is empty
|
||||
context_template?: string; // 上下文模板(普通模式)
|
||||
|
||||
// ===== 模型设置 =====
|
||||
model_id?: string;
|
||||
rerank_model_id?: string; // ReRank 模型 ID
|
||||
temperature?: number;
|
||||
max_completion_tokens?: number; // 0 = 跟随系统默认(快速问答 2048;智能推理 4096,绑沙箱可写文件时 24576)。大于 0 为自定义上限
|
||||
thinking?: boolean; // 是否启用思考模式(支持扩展思考的模型)
|
||||
// 思考强度:off | auto | minimal | low | medium | high | xhigh | max。
|
||||
// 为空时退回 thinking 布尔值(true == auto,false == off)。
|
||||
reasoning_effort?: string;
|
||||
citation_enabled?: boolean; // 是否在最终回答中输出知识库/网页来源引用(默认开启)
|
||||
|
||||
// ===== Agent模式设置 =====
|
||||
max_iterations?: number; // 最大迭代次数;-1 表示不限制
|
||||
llm_call_timeout?: number; // LLM调用超时时间(秒)
|
||||
allowed_tools?: string[] | null; // 允许的工具;null/未设置 = 后端默认工具,[] = 不使用内置工具
|
||||
reflection_enabled?: boolean; // 是否启用反思
|
||||
// MCP服务选择模式:all=全部启用的MCP服务, selected=指定服务, none=不使用MCP
|
||||
mcp_selection_mode?: 'all' | 'selected' | 'none';
|
||||
mcp_services?: string[]; // 选择的MCP服务ID列表
|
||||
// 对话中触发 OAuth 授权时的等待超时(秒):到点后自动跳过授权提示。
|
||||
// <=0 时使用服务端默认超时。仅对使用 OAuth 的 MCP 服务生效。
|
||||
mcp_auth_wait_timeout?: number;
|
||||
// 执行权限上限:修改数据的工具能否不经确认直接执行。未设置等同 auto_write。
|
||||
access_level?: AssistantAccessLevel;
|
||||
|
||||
// ===== Skills设置(仅Agent模式)=====
|
||||
// Skills选择模式:all=全部预装, selected=指定, none=不使用
|
||||
skills_selection_mode?: 'all' | 'selected' | 'none';
|
||||
selected_skills?: string[]; // 选择的Skill名称列表
|
||||
|
||||
// ===== 沙箱设置 =====
|
||||
// 该智能体的技能脚本运行在哪个沙箱配置上;为空表示不启用沙箱执行。
|
||||
// 指向逻辑配置而非某个具体版本,凭据轮换时无需重新指派每个智能体。
|
||||
sandbox_config_id?: string;
|
||||
|
||||
// ===== 知识库设置 =====
|
||||
// 知识库选择模式:all=全部知识库, selected=指定知识库, none=不使用知识库
|
||||
kb_selection_mode?: 'all' | 'selected' | 'none';
|
||||
knowledge_bases?: string[];
|
||||
// 是否仅在显式 @ 提及时检索知识库(默认: false)
|
||||
// true: 只有用户通过 @ 明确提及知识库/文档时才检索
|
||||
// false: 根据 kb_selection_mode 自动检索知识库
|
||||
retrieve_kb_only_when_mentioned?: boolean;
|
||||
|
||||
// ===== 图片上传/多模态设置 =====
|
||||
image_upload_enabled?: boolean; // 是否启用图片上传(默认: false)
|
||||
vlm_model_id?: string; // VLM模型ID(图片分析用)
|
||||
image_storage_provider?: string; // 图片存储提供商
|
||||
audio_upload_enabled?: boolean; // 是否启用音频上传/ASR转录(默认: false)
|
||||
asr_model_id?: string; // ASR模型ID(音频转录用)
|
||||
// 附件图片理解 / 扫描件 OCR 开关(默认: false,开启会增加解析耗时)
|
||||
attachment_image_understanding?: boolean;
|
||||
// 扫描件 OCR 最大页数(0 = 使用全局默认 ACADEMY_CHAT_ATTACHMENT_OCR_MAX_PAGES)
|
||||
attachment_ocr_max_pages?: number;
|
||||
// 单轮问答等待附件解析完成的最长时间(秒,0 = 使用全局默认 ACADEMY_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC)
|
||||
attachment_parse_wait_timeout_sec?: number;
|
||||
|
||||
// ===== 聊天附件解析引擎策略 =====
|
||||
// 按文件类型选择解析引擎;优先级:请求 parser_engine > 智能体规则 > 租户规则 > auto
|
||||
chat_parser_engine_rules?: { file_types: string[]; engine: string }[];
|
||||
|
||||
// ===== 文件类型限制 =====
|
||||
// 支持的文件类型(如 ["csv", "xlsx", "xls"])
|
||||
// 为空表示支持所有文件类型
|
||||
supported_file_types?: string[];
|
||||
|
||||
// ===== 网络搜索设置 =====
|
||||
web_search_enabled?: boolean;
|
||||
web_search_provider_id?: string;
|
||||
web_search_max_results?: number;
|
||||
|
||||
// ===== 多轮对话设置 =====
|
||||
multi_turn_enabled?: boolean; // 是否启用多轮对话
|
||||
history_turns?: number; // 保留历史轮数
|
||||
|
||||
// ===== 长期记忆 =====
|
||||
// 该智能体是否可以读取用户的长期记忆。
|
||||
// 缺省(旧数据)等同于 true:这是一个只能"关"的开关,空间设置关闭时
|
||||
// 这里打开也不会生效。
|
||||
memory_enabled?: boolean;
|
||||
|
||||
// ===== 检索策略设置 =====
|
||||
embedding_top_k?: number; // 向量召回TopK
|
||||
keyword_threshold?: number; // 关键词召回阈值
|
||||
vector_threshold?: number; // 向量召回阈值
|
||||
rerank_top_k?: number; // 重排TopK
|
||||
rerank_threshold?: number; // 重排阈值
|
||||
|
||||
// ===== 高级设置(主要用于普通模式)=====
|
||||
enable_query_expansion?: boolean; // 是否启用查询扩展
|
||||
enable_rewrite?: boolean; // 是否启用问题改写
|
||||
rewrite_prompt_system?: string; // 改写系统提示词
|
||||
rewrite_prompt_user?: string; // 改写用户提示词模板
|
||||
fallback_strategy?: 'fixed' | 'model'; // 兜底策略
|
||||
fallback_response?: string; // 固定兜底回复
|
||||
fallback_prompt?: string; // 兜底提示词(模型生成时)
|
||||
// 意图提示词:非检索意图(问候、闲聊等)时覆盖主系统提示词
|
||||
intent_prompts?: Record<string, string>;
|
||||
|
||||
// ===== 已废弃字段(保留兼容)=====
|
||||
welcome_message?: string;
|
||||
question_suggestions?: QuestionSuggestionConfig;
|
||||
}
|
||||
|
||||
// 智能体
|
||||
export interface CustomAgent {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
avatar?: string;
|
||||
is_builtin: boolean;
|
||||
tenant_id?: number;
|
||||
created_by?: string;
|
||||
// creator_name 由后端 list 接口批量回填,仅用于列表卡片来源徽章。
|
||||
creator_name?: string;
|
||||
config: CustomAgentConfig;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
// 创建智能体请求
|
||||
export interface CreateAgentRequest {
|
||||
name: string;
|
||||
description?: string;
|
||||
avatar?: string;
|
||||
config?: CustomAgentConfig;
|
||||
}
|
||||
|
||||
// 更新智能体请求
|
||||
export interface UpdateAgentRequest {
|
||||
name: string;
|
||||
description?: string;
|
||||
avatar?: string;
|
||||
config?: CustomAgentConfig;
|
||||
}
|
||||
|
||||
// 内置智能体 ID(常用的保留常量,便于代码引用)
|
||||
export const BUILTIN_QUICK_ANSWER_ID = 'builtin-quick-answer';
|
||||
export const BUILTIN_SMART_REASONING_ID = 'builtin-smart-reasoning';
|
||||
export const BUILTIN_TRAINING_COACH_ID = 'builtin-training-coach';
|
||||
export const BUILTIN_ACADEMY_ASSISTANT_ID = 'builtin-academy-assistant';
|
||||
|
||||
// AgentMode 常量
|
||||
export const AGENT_MODE_QUICK_ANSWER = 'quick-answer';
|
||||
export const AGENT_MODE_SMART_REASONING = 'smart-reasoning';
|
||||
|
||||
// Deprecated: Use BUILTIN_QUICK_ANSWER_ID instead
|
||||
export const BUILTIN_AGENT_NORMAL_ID = BUILTIN_QUICK_ANSWER_ID;
|
||||
// Deprecated: Use BUILTIN_SMART_REASONING_ID instead
|
||||
export const BUILTIN_AGENT_AGENT_ID = BUILTIN_SMART_REASONING_ID;
|
||||
|
||||
// 获取智能体列表(包括内置智能体)
|
||||
// disabled_own_agent_ids: 当前空间在对话下拉中停用的「我的」智能体 ID,仅影响本空间
|
||||
export function listAgents(params?: {
|
||||
/**
|
||||
* Optional creator filter; mirrors listKnowledgeBases. Built-in agents
|
||||
* (is_builtin=true) are always returned regardless of this filter so
|
||||
* the conversation dropdown never silently loses quick-answer /
|
||||
* smart-reasoning when a user picks "Created by me".
|
||||
*/
|
||||
creator?: 'all' | 'mine' | 'others';
|
||||
}) {
|
||||
const qs = params?.creator && params.creator !== 'all' ? `?creator=${params.creator}` : '';
|
||||
return get<{ data: CustomAgent[]; disabled_own_agent_ids?: string[] }>(`/api/v1/agents${qs}`);
|
||||
}
|
||||
|
||||
// 获取智能体详情
|
||||
export function getAgentById(id: string) {
|
||||
return get<{ data: CustomAgent }>(`/api/v1/agents/${id}`);
|
||||
}
|
||||
|
||||
// 创建智能体
|
||||
// 保存时后端对 allowed_tools 的处理说明(不阻止保存)
|
||||
export interface AllowedToolsWarnings {
|
||||
kept_unknown?: string[]; // 已保存、但当前版本没有的工具名,保留不动
|
||||
dropped?: string[]; // 由其他设置控制的工具,已从列表移除
|
||||
}
|
||||
|
||||
export function createAgent(data: CreateAgentRequest) {
|
||||
return post<{ data: CustomAgent; allowed_tools_warnings?: AllowedToolsWarnings }>('/api/v1/agents', data);
|
||||
}
|
||||
|
||||
// 更新智能体
|
||||
export function updateAgent(id: string, data: UpdateAgentRequest) {
|
||||
return put<{ data: CustomAgent; allowed_tools_warnings?: AllowedToolsWarnings }>(`/api/v1/agents/${id}`, data);
|
||||
}
|
||||
|
||||
// 删除智能体
|
||||
export function deleteAgent(id: string) {
|
||||
return del<{ success: boolean }>(`/api/v1/agents/${id}`);
|
||||
}
|
||||
|
||||
// 复制智能体
|
||||
export function copyAgent(id: string) {
|
||||
return post<{ data: CustomAgent }>(`/api/v1/agents/${id}/copy`);
|
||||
}
|
||||
|
||||
// 判断是否为内置智能体(通过 agent.is_builtin 字段或 ID 前缀判断)
|
||||
export function isBuiltinAgent(agentId: string): boolean {
|
||||
return agentId.startsWith('builtin-');
|
||||
}
|
||||
|
||||
// 占位符定义
|
||||
export interface PlaceholderDefinition {
|
||||
name: string;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
// 占位符响应
|
||||
export interface PlaceholdersResponse {
|
||||
all: PlaceholderDefinition[];
|
||||
system_prompt: PlaceholderDefinition[];
|
||||
agent_system_prompt: PlaceholderDefinition[];
|
||||
context_template: PlaceholderDefinition[];
|
||||
rewrite_system_prompt: PlaceholderDefinition[];
|
||||
rewrite_prompt: PlaceholderDefinition[];
|
||||
fallback_prompt: PlaceholderDefinition[];
|
||||
}
|
||||
|
||||
// 获取占位符定义
|
||||
export function getPlaceholders() {
|
||||
return get<{ data: PlaceholdersResponse }>('/api/v1/agents/placeholders');
|
||||
}
|
||||
|
||||
// ===== 智能体类型预设 =====
|
||||
|
||||
// 后端 kb_filter 结构(见 internal/types/agent_type_preset.go)
|
||||
export interface AgentTypeKBFilter {
|
||||
any_of?: string[]; // KB 至少拥有其一
|
||||
all_of?: string[]; // KB 必须全部拥有
|
||||
none_of?: string[]; // KB 必须全部不拥有
|
||||
}
|
||||
|
||||
// KB 能力标签(后端 types.KBCapabilities 的 JSON)
|
||||
export interface KBCapabilities {
|
||||
vector: boolean;
|
||||
keyword: boolean;
|
||||
wiki: boolean;
|
||||
graph: boolean;
|
||||
faq: boolean;
|
||||
}
|
||||
|
||||
// 预设的"自动填充"配置载荷:仅包含被预设覆盖的字段;其他字段不动
|
||||
export interface AgentTypePresetConfig {
|
||||
system_prompt_id?: string;
|
||||
temperature?: number;
|
||||
max_iterations?: number;
|
||||
allowed_tools?: string[];
|
||||
retain_retrieval_history?: boolean;
|
||||
faq_priority_enabled?: boolean;
|
||||
web_search_enabled?: boolean;
|
||||
supported_file_types?: string[];
|
||||
kb_selection_mode?: 'all' | 'selected' | 'none';
|
||||
}
|
||||
|
||||
export interface AgentTypePresetI18n {
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface AgentTypePreset {
|
||||
id: AgentType;
|
||||
i18n: Record<string, AgentTypePresetI18n>;
|
||||
config?: AgentTypePresetConfig; // 为空表示"自定义"类型(无预设)
|
||||
kb_filter?: AgentTypeKBFilter; // 为空表示所有 KB 可选
|
||||
}
|
||||
|
||||
// 拉取类型预设列表(编辑器用)
|
||||
export function getAgentTypePresets() {
|
||||
return get<{ data: AgentTypePreset[] }>('/api/v1/agents/type-presets');
|
||||
}
|
||||
|
||||
// 智能体可选工具目录(编辑器用,来自后端 AvailableToolDefinitions)
|
||||
export type AgentToolKBCapability = 'vector' | 'keyword' | 'wiki' | 'graph' | 'faq';
|
||||
|
||||
export interface AgentToolRequirement {
|
||||
any_of?: AgentToolKBCapability[];
|
||||
all_of?: AgentToolKBCapability[];
|
||||
}
|
||||
|
||||
export interface AgentToolDefinition {
|
||||
name: string;
|
||||
label: string;
|
||||
description: string;
|
||||
group: string;
|
||||
danger?: boolean;
|
||||
requirement: AgentToolRequirement;
|
||||
}
|
||||
|
||||
export interface AgentToolCatalog {
|
||||
tools: AgentToolDefinition[];
|
||||
// allowed_tools 未设置(null)时运行时使用的工具
|
||||
default_tools: string[];
|
||||
// 由智能体的其他设置决定是否注册的工具;写进 allowed_tools 不会注册
|
||||
switch_managed_tools: string[];
|
||||
}
|
||||
|
||||
export function getAgentTools() {
|
||||
return get<{ data: AgentToolCatalog }>('/api/v1/agents/tools');
|
||||
}
|
||||
|
||||
// ===== IM渠道 =====
|
||||
|
||||
export interface IMChannel {
|
||||
id: string;
|
||||
tenant_id?: number;
|
||||
agent_id: string;
|
||||
// 'lark' is Feishu's international edition; it shares Feishu's credentials and modes.
|
||||
platform: 'wecom' | 'feishu' | 'lark' | 'slack' | 'telegram' | 'dingtalk' | 'mattermost' | 'wechat' | 'qqbot' | 'yunzhijia';
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
mode: 'webhook' | 'websocket' | 'longpoll';
|
||||
output_mode: 'stream' | 'full';
|
||||
locale?: '' | 'zh-CN' | 'zh-TW' | 'en-US' | 'ko-KR' | 'ja-JP' | 'ru-RU';
|
||||
session_mode?: 'user' | 'thread';
|
||||
knowledge_base_id?: string;
|
||||
credentials: Record<string, any>;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export function listIMChannels(agentId: string) {
|
||||
return get<{ data: IMChannel[] }>(`/api/v1/agents/${agentId}/im-channels`);
|
||||
}
|
||||
|
||||
// Tenant-wide overview row. Credentials are intentionally omitted — use
|
||||
// listIMChannels(agentId) when you need to edit a specific channel.
|
||||
export interface IMChannelOverview {
|
||||
id: string;
|
||||
tenant_id: number;
|
||||
agent_id: string;
|
||||
agent_name: string; // localized built-in name when the agent is built-in
|
||||
platform: IMChannel['platform'];
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
mode: IMChannel['mode'];
|
||||
output_mode: IMChannel['output_mode'];
|
||||
locale?: IMChannel['locale'];
|
||||
session_mode?: IMChannel['session_mode'];
|
||||
bot_identity: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export function listAllIMChannels() {
|
||||
return get<{ data: IMChannelOverview[] }>('/api/v1/im-channels');
|
||||
}
|
||||
|
||||
export function createIMChannel(agentId: string, data: Partial<IMChannel>) {
|
||||
return post<{ data: IMChannel }>(`/api/v1/agents/${agentId}/im-channels`, data);
|
||||
}
|
||||
|
||||
export function updateIMChannel(id: string, data: Partial<IMChannel>) {
|
||||
return put<{ data: IMChannel }>(`/api/v1/im-channels/${id}`, data);
|
||||
}
|
||||
|
||||
export function deleteIMChannel(id: string) {
|
||||
return del<{ success: boolean }>(`/api/v1/im-channels/${id}`);
|
||||
}
|
||||
|
||||
export function toggleIMChannel(id: string) {
|
||||
return post<{ data: IMChannel }>(`/api/v1/im-channels/${id}/toggle`);
|
||||
}
|
||||
|
||||
// ===== 推荐问题 =====
|
||||
|
||||
// 推荐问题
|
||||
export interface SuggestedQuestion {
|
||||
question: string;
|
||||
source: 'faq' | 'document' | 'agent_config' | 'wiki';
|
||||
knowledge_base_id?: string;
|
||||
knowledge_id?: string;
|
||||
}
|
||||
|
||||
// 获取智能体推荐问题
|
||||
// 根据智能体关联的知识库范围返回推荐问题,用于前端对话面板快捷提问
|
||||
export function getSuggestedQuestions(
|
||||
agentId: string,
|
||||
params?: {
|
||||
knowledge_base_ids?: string[];
|
||||
knowledge_ids?: string[];
|
||||
tag_scopes?: Array<{ knowledge_base_id: string; tag_ids: string[] }>;
|
||||
limit?: number;
|
||||
}
|
||||
) {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.knowledge_base_ids?.length) query.set('knowledge_base_ids', params.knowledge_base_ids.join(','));
|
||||
if (params?.knowledge_ids?.length) query.set('knowledge_ids', params.knowledge_ids.join(','));
|
||||
if (params?.tag_scopes?.length) query.set('tag_scopes', JSON.stringify(params.tag_scopes));
|
||||
if (params?.limit) query.set('limit', String(params.limit));
|
||||
const qs = query.toString();
|
||||
return get<{ data: { questions: SuggestedQuestion[] } }>(`/api/v1/agents/${agentId}/suggested-questions${qs ? '?' + qs : ''}`);
|
||||
}
|
||||
// ===== WeChat QR Code Login =====
|
||||
|
||||
export interface WeChatQRCodeResult {
|
||||
qrcode_url: string;
|
||||
qrcode: string;
|
||||
}
|
||||
|
||||
export interface WeChatQRCodeStatus {
|
||||
status: 'wait' | 'scaned' | 'confirmed' | 'expired';
|
||||
credentials?: {
|
||||
bot_token: string;
|
||||
ilink_bot_id: string;
|
||||
ilink_user_id: string;
|
||||
};
|
||||
baseurl?: string;
|
||||
}
|
||||
|
||||
export function getWeChatQRCode() {
|
||||
return post<{ data: WeChatQRCodeResult }>('/api/v1/wechat/qrcode');
|
||||
}
|
||||
|
||||
export function pollWeChatQRCodeStatus(qrcode: string) {
|
||||
return post<{ data: WeChatQRCodeStatus }>('/api/v1/wechat/qrcode/status', { qrcode });
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { del, get } from '@/utils/request'
|
||||
|
||||
/**
|
||||
* One file in the artifact library: the latest version of a file a skill
|
||||
* generated in one of the caller's sessions. Download it through
|
||||
* downloadArtifact(session_id, message_id, index) from '@/api/chat', which
|
||||
* re-checks session ownership server side.
|
||||
*/
|
||||
export interface ArtifactLibraryItem {
|
||||
session_id: string
|
||||
session_title: string
|
||||
message_id: string
|
||||
index: number
|
||||
/** `resource://<handle>` when the deployment runs a resource catalog. */
|
||||
handle?: string
|
||||
file_name: string
|
||||
file_type: string
|
||||
file_size: number
|
||||
source_path: string
|
||||
created_at: string
|
||||
/** How many times this file was (re)generated in its session. */
|
||||
version_count: number
|
||||
}
|
||||
|
||||
export interface ArtifactLibraryParams {
|
||||
keyword?: string
|
||||
/** Extensions such as ".pdf"; empty means every type. */
|
||||
fileTypes?: string[]
|
||||
page?: number
|
||||
pageSize?: number
|
||||
}
|
||||
|
||||
export interface ArtifactLibraryPage {
|
||||
success: boolean
|
||||
data: ArtifactLibraryItem[]
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
}
|
||||
|
||||
export function listArtifactLibrary(params: ArtifactLibraryParams = {}) {
|
||||
const query: Record<string, string | number> = {}
|
||||
const keyword = params.keyword?.trim()
|
||||
if (keyword) query.keyword = keyword
|
||||
if (params.fileTypes?.length) query.file_types = params.fileTypes.join(',')
|
||||
if (params.page) query.page = params.page
|
||||
if (params.pageSize) query.page_size = params.pageSize
|
||||
return get<ArtifactLibraryPage>('/api/v1/artifacts', { params: query })
|
||||
}
|
||||
|
||||
export interface ArtifactDeleteResult {
|
||||
success: boolean
|
||||
data: { file_name: string; deleted: number }
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a file from the artifact library, along with every earlier version of
|
||||
* it in the same session — a library row is the file, not one regeneration of
|
||||
* it, so leaving the older versions behind would leave the row in place.
|
||||
*
|
||||
* The stored bytes are reclaimed unless something else still references them,
|
||||
* so this is not reversible. Callers confirm with the user first.
|
||||
*/
|
||||
export function deleteArtifactLibraryItem(item: ArtifactLibraryItem) {
|
||||
const query = new URLSearchParams({
|
||||
session_id: item.session_id,
|
||||
message_id: item.message_id,
|
||||
index: String(item.index),
|
||||
})
|
||||
return del<ArtifactDeleteResult>(`/api/v1/artifacts?${query.toString()}`)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { get, put } from '@/utils/request'
|
||||
|
||||
// Mirrors internal/types/assistant.go.
|
||||
export type AssistantAccessLevel = 'read_only' | 'confirm' | 'auto_write'
|
||||
|
||||
export const ASSISTANT_ACCESS_LEVELS: AssistantAccessLevel[] = ['read_only', 'confirm', 'auto_write']
|
||||
|
||||
export const DEFAULT_ASSISTANT_ACCESS_LEVEL: AssistantAccessLevel = 'confirm'
|
||||
|
||||
export const MAX_ASSISTANT_DISPLAY_NAME_LENGTH = 24
|
||||
|
||||
export interface AssistantConfig {
|
||||
/** Empty keeps the default name. */
|
||||
display_name: string
|
||||
/** The highest level a member may pick. */
|
||||
max_access_level: AssistantAccessLevel
|
||||
}
|
||||
|
||||
export function isAssistantAccessLevel(value: unknown): value is AssistantAccessLevel {
|
||||
return typeof value === 'string' && (ASSISTANT_ACCESS_LEVELS as string[]).includes(value)
|
||||
}
|
||||
|
||||
/** The level a run gets: the requested one, never above the ceiling. */
|
||||
export function capAssistantAccessLevel(
|
||||
requested: AssistantAccessLevel,
|
||||
ceiling: AssistantAccessLevel,
|
||||
): AssistantAccessLevel {
|
||||
const rank = (level: AssistantAccessLevel) => ASSISTANT_ACCESS_LEVELS.indexOf(level)
|
||||
return rank(requested) > rank(ceiling) ? ceiling : requested
|
||||
}
|
||||
|
||||
export function getTenantAssistantConfig() {
|
||||
return get<{ success: boolean; data: AssistantConfig }>('/api/v1/tenants/kv/assistant-config')
|
||||
}
|
||||
|
||||
export function updateTenantAssistantConfig(config: AssistantConfig) {
|
||||
return put<{ success: boolean; data: AssistantConfig }>('/api/v1/tenants/kv/assistant-config', config)
|
||||
}
|
||||
@@ -0,0 +1,587 @@
|
||||
import { post, get, put } from '@/utils/request'
|
||||
import i18n from '@/i18n'
|
||||
|
||||
const t = (key: string) => i18n.global.t(key)
|
||||
|
||||
// 用户登录接口
|
||||
export interface LoginRequest {
|
||||
email: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
success: boolean
|
||||
message?: string
|
||||
user?: {
|
||||
id: string
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string
|
||||
tenant_id: number
|
||||
can_access_all_tenants?: boolean
|
||||
is_system_admin?: boolean
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
tenant?: {
|
||||
id: number
|
||||
name: string
|
||||
description: string
|
||||
status: string
|
||||
business: string
|
||||
storage_quota: number
|
||||
storage_used: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
} | null
|
||||
// active_tenant mirrors `tenant` for endpoints that distinguish home
|
||||
// tenant from current tenant (e.g. /auth/register-by-invite). Only
|
||||
// one of `tenant` / `active_tenant` is populated by any given endpoint.
|
||||
active_tenant?: {
|
||||
id: number
|
||||
name: string
|
||||
description?: string
|
||||
status?: string
|
||||
business?: string
|
||||
storage_quota?: number
|
||||
storage_used?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
} | null
|
||||
memberships?: MembershipInfo[]
|
||||
token?: string
|
||||
refresh_token?: string
|
||||
}
|
||||
|
||||
export interface OIDCAuthURLResponse {
|
||||
success: boolean
|
||||
authorization_url?: string
|
||||
state?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface OIDCConfigResponse {
|
||||
success: boolean
|
||||
enabled: boolean
|
||||
provider_display_name?: string
|
||||
// password grant 表单直登是否可用(工号+密码,不跳 IdP 页)
|
||||
password_login_enabled?: boolean
|
||||
message?: string
|
||||
}
|
||||
|
||||
// 用户注册接口
|
||||
export interface RegisterRequest {
|
||||
username: string
|
||||
email: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface RegisterResponse {
|
||||
success: boolean
|
||||
message?: string
|
||||
data?: {
|
||||
user: {
|
||||
id: string
|
||||
username: string
|
||||
email: string
|
||||
}
|
||||
tenant: {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 用户偏好(与后端 types.UserPreferences 对齐,字段可选 = 没显式设置过)。
|
||||
// 新加 key 时记得:后端 service.UpdateUserPreferences 也要在 merge 分支里
|
||||
// 处理;前端调用方按需读 / 默认值降级。
|
||||
export interface UserPreferences {
|
||||
browser_search_instructions?: string | null
|
||||
// last_active_tenant_id 持久化「刷新 / 换设备 / 重新登录后回到上次的空间」
|
||||
// 偏好;后端在 Login / RefreshToken 时校验 membership 有效后才会沿用,
|
||||
// 否则回退到 home 并清掉这个字段。传 0 给 PATCH 表示「清除偏好」。
|
||||
last_active_tenant_id?: number | null
|
||||
// oidc_only_login 为 true 表示账号由 OIDC 自动开通且用户尚未设置已知密码。
|
||||
oidc_only_login?: boolean
|
||||
// gallery 记录图库的个人状态:搜索激活模式与逐字段开/关(按属性 ID)。
|
||||
// 每次变更整体覆盖该块;后端会校验 mode 与 status 取值。
|
||||
gallery?: {
|
||||
mode?: 'all' | 'custom'
|
||||
status?: Record<string, string>
|
||||
}
|
||||
}
|
||||
|
||||
// 用户信息接口
|
||||
export interface UserInfo {
|
||||
id: string
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string
|
||||
tenant_id: string
|
||||
can_access_all_tenants?: boolean
|
||||
preferences?: UserPreferences
|
||||
is_system_admin?: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 把后端返回的 user JSON 规范化成前端 UserInfo。
|
||||
*
|
||||
* 历史上有 4 处独立的 setUser 调用(Login、autoSetup、token rehydrate、
|
||||
* /auth/me 主动 refresh)各自手写字段白名单,每加一个 user 字段都要在
|
||||
* 4 处同步——否则该字段就被悄悄过滤掉。is_system_admin 上线时就因为
|
||||
* 漏拷一处而看不到「系统管理」入口;这个工厂存在的目的就是杜绝同类
|
||||
* 漏拷再发生。**新增 user 字段请只改这里**。
|
||||
*
|
||||
* fallbackTenantId 是 tenant_id 缺失时的兜底来源——
|
||||
* - autoSetup 响应顶层有 tenant.id,但 user 对象上没有 tenant_id
|
||||
* - /auth/me 偶发只返回 user 不带 tenant 时也走兜底
|
||||
* 调用方按需传入;不传则保持空字符串(与历史行为一致)。
|
||||
*
|
||||
* 字段读取统一走 `=== true` 而不是 `|| false`,对偶发非 boolean
|
||||
* 类型(后端某天传 1/0 或字符串)做严格收敛,避免把 truthy 字符串
|
||||
* 误判为权限通过。
|
||||
*/
|
||||
export function userInfoFromApi(
|
||||
u: any,
|
||||
fallbackTenantId?: string | number | null,
|
||||
): UserInfo {
|
||||
const rawTenantId =
|
||||
u?.tenant_id !== undefined && u?.tenant_id !== null && u.tenant_id !== ''
|
||||
? u.tenant_id
|
||||
: fallbackTenantId ?? ''
|
||||
const tid = Number(rawTenantId) > 0 ? rawTenantId : ''
|
||||
return {
|
||||
id: u?.id || '',
|
||||
username: u?.username || '',
|
||||
email: u?.email || '',
|
||||
avatar: u?.avatar,
|
||||
tenant_id: String(tid) || '',
|
||||
can_access_all_tenants: u?.can_access_all_tenants === true,
|
||||
is_system_admin: u?.is_system_admin === true,
|
||||
preferences: u?.preferences,
|
||||
created_at: u?.created_at || new Date().toISOString(),
|
||||
updated_at: u?.updated_at || new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
// 空间信息接口
|
||||
export interface TenantInfo {
|
||||
id: string
|
||||
name: string
|
||||
description?: string
|
||||
status?: string
|
||||
business?: string
|
||||
owner_id: string
|
||||
storage_quota?: number
|
||||
storage_used?: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
knowledge_bases?: KnowledgeBaseInfo[]
|
||||
}
|
||||
|
||||
// 知识库信息接口
|
||||
export interface KnowledgeBaseInfo {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
tenant_id: string
|
||||
// creator_id is the user id of whoever originally created the KB.
|
||||
// Set by PR 5 of the multi-tenant RBAC series; nullable for legacy
|
||||
// KBs created before that migration backfilled the column.
|
||||
creator_id?: string
|
||||
// creator_name 由后端 list 接口批量回填(username 优先,退化到 email),
|
||||
// 仅用于列表卡片来源徽章;缺失代表无法解析(已删除 / 老数据)。
|
||||
creator_name?: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
document_count?: number
|
||||
chunk_count?: number
|
||||
}
|
||||
|
||||
// 模型信息接口
|
||||
export interface ModelInfo {
|
||||
id: string
|
||||
name: string
|
||||
type: string
|
||||
source: string
|
||||
description?: string
|
||||
is_default?: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户登录
|
||||
*/
|
||||
export async function login(data: LoginRequest): Promise<LoginResponse> {
|
||||
try {
|
||||
const response = await post('/api/v1/auth/login', data)
|
||||
return response as unknown as LoginResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.loginFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工号密码直登(OIDC password grant):表单提交工号+密码,后端转发 IdP
|
||||
* token 端点校验(浏览器不接触 client_secret)。响应与本地登录同构
|
||||
* (token/user/tenant/memberships),复用登录持久化路径。
|
||||
*/
|
||||
export async function loginWithOIDCPassword(data: {
|
||||
username: string
|
||||
password: string
|
||||
}): Promise<LoginResponse> {
|
||||
try {
|
||||
const response = await post('/api/v1/auth/oidc/password', data)
|
||||
return response as unknown as LoginResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.loginFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 OIDC 登录跳转地址
|
||||
*/
|
||||
export async function getOIDCAuthorizationURL(redirectURI: string): Promise<OIDCAuthURLResponse> {
|
||||
try {
|
||||
const response = await get(`/api/v1/auth/oidc/url?redirect_uri=${encodeURIComponent(redirectURI)}`)
|
||||
return response as unknown as OIDCAuthURLResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.loginFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 OIDC 登录配置
|
||||
*/
|
||||
export async function getOIDCConfig(): Promise<OIDCConfigResponse> {
|
||||
try {
|
||||
const response = await get('/api/v1/auth/oidc/config')
|
||||
return response as unknown as OIDCConfigResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
enabled: false,
|
||||
message: error.message || t('error.auth.loginFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取认证配置(仅返回前端渲染需要的公开字段,例如注册模式)。
|
||||
*
|
||||
* 后端通过 `auth.registration_mode` 控制是否允许自助注册:
|
||||
* - "self_serve" 保留现有自助注册入口(默认)
|
||||
* - "invite_register" 仅持有效邀请链接可注册
|
||||
* - "invite_only" 禁止注册,已有账号仍可接受邀请
|
||||
*
|
||||
* 失败时隐藏注册入口,避免误展示不允许的注册流程。
|
||||
*/
|
||||
export interface AuthConfigResponse {
|
||||
success: boolean
|
||||
registration_mode: 'self_serve' | 'invite_register' | 'invite_only' | string
|
||||
complex_password_enabled: boolean
|
||||
}
|
||||
|
||||
export async function getAuthConfig(): Promise<AuthConfigResponse> {
|
||||
try {
|
||||
const response = await get('/api/v1/auth/config')
|
||||
return response as unknown as AuthConfigResponse
|
||||
} catch {
|
||||
return { success: false, registration_mode: '', complex_password_enabled: false }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户注册
|
||||
*/
|
||||
export async function register(data: RegisterRequest): Promise<RegisterResponse> {
|
||||
try {
|
||||
const response = await post('/api/v1/auth/register', data)
|
||||
return response as unknown as RegisterResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.registerFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lite 版自动初始化(创建默认用户/空间 + 签发令牌)
|
||||
*/
|
||||
let autoSetupPromise: Promise<LoginResponse> | null = null
|
||||
|
||||
export function autoSetup(): Promise<LoginResponse> {
|
||||
if (autoSetupPromise) return autoSetupPromise
|
||||
|
||||
const request = (async () => {
|
||||
try {
|
||||
const nativeApp = (window as any).go?.main?.App
|
||||
if (!nativeApp?.GetAutoSetupToken) return { success: false, message: 'Desktop authentication required' }
|
||||
const token = await nativeApp.GetAutoSetupToken()
|
||||
const response = await post('/api/v1/auth/auto-setup', {}, {
|
||||
headers: { 'X-Academy-Desktop-Token': token },
|
||||
})
|
||||
return response as unknown as LoginResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || 'Auto-setup unavailable'
|
||||
}
|
||||
}
|
||||
})()
|
||||
|
||||
autoSetupPromise = request
|
||||
void request.then(
|
||||
() => { if (autoSetupPromise === request) autoSetupPromise = null },
|
||||
() => { if (autoSetupPromise === request) autoSetupPromise = null },
|
||||
)
|
||||
return request
|
||||
}
|
||||
|
||||
/**
|
||||
* Membership row returned alongside /auth/me. Mirrors the LoginResponse
|
||||
* shape so the frontend can refresh `currentTenantRole` on every page
|
||||
* load — without it, role changes after login (e.g. an Owner demoting
|
||||
* us in a peer tenant) stay invisible until the user logs out and back
|
||||
* in.
|
||||
*/
|
||||
export interface MembershipInfo {
|
||||
tenant_id: number
|
||||
tenant_name?: string
|
||||
role: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户信息
|
||||
*/
|
||||
export interface AuthCapabilities {
|
||||
can_create_tenant: boolean
|
||||
auto_accept_invitation: boolean
|
||||
}
|
||||
|
||||
export async function getCurrentUser(): Promise<{ success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[]; tenant_required?: boolean; capabilities?: AuthCapabilities; preference_defaults?: { browser_search_instructions: string } }; message?: string }> {
|
||||
try {
|
||||
const response = await get('/api/v1/auth/me')
|
||||
return response as unknown as { success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[]; tenant_required?: boolean; capabilities?: AuthCapabilities; preference_defaults?: { browser_search_instructions: string } }; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.getUserFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新当前用户的偏好设置(PATCH 语义:只发要改的字段,后端只覆盖发了的 key,
|
||||
* 其它 key 保持不变)。后端会返回更新后的完整 preferences 对象。
|
||||
*/
|
||||
export async function updateMyPreferences(
|
||||
patch: Partial<UserPreferences>,
|
||||
): Promise<{ success: boolean; data?: UserPreferences; message?: string }> {
|
||||
try {
|
||||
const response = await put('/api/v1/auth/me/preferences', patch)
|
||||
return response as unknown as { success: boolean; data?: UserPreferences; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.updatePreferencesFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前空间信息
|
||||
*/
|
||||
export async function getCurrentTenant(): Promise<{ success: boolean; data?: TenantInfo; message?: string }> {
|
||||
try {
|
||||
const response = await get('/api/v1/auth/tenant')
|
||||
return response as unknown as { success: boolean; data?: TenantInfo; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.getTenantFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新Token
|
||||
*/
|
||||
export async function refreshToken(refreshToken: string): Promise<{ success: boolean; data?: { token: string; refreshToken: string }; message?: string }> {
|
||||
try {
|
||||
const response: any = await post('/api/v1/auth/refresh', { refreshToken })
|
||||
if (response && response.success) {
|
||||
if (response.access_token || response.refresh_token) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
token: response.access_token,
|
||||
refreshToken: response.refresh_token,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 其他情况直接返回原始消息
|
||||
return {
|
||||
success: false,
|
||||
message: response?.message || t('error.auth.refreshTokenFailed')
|
||||
}
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.refreshTokenFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户登出
|
||||
*/
|
||||
export async function logout(): Promise<{ success: boolean; message?: string }> {
|
||||
try {
|
||||
await post('/api/v1/auth/logout', {})
|
||||
return {
|
||||
success: true
|
||||
}
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.logoutFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface ChangePasswordRequest {
|
||||
old_password: string
|
||||
new_password: string
|
||||
}
|
||||
|
||||
/** Map change-password API failures to localized UI strings. */
|
||||
export function resolveChangePasswordError(error: any): string {
|
||||
const details =
|
||||
typeof error?.error?.details === 'string'
|
||||
? error.error.details
|
||||
: typeof error?.details === 'string'
|
||||
? error.details
|
||||
: ''
|
||||
switch (details) {
|
||||
case 'invalid_old_password':
|
||||
return t('userProfile.changePassword.failed')
|
||||
case 'password_policy':
|
||||
return t('userProfile.changePassword.policyFailed')
|
||||
case 'same_password':
|
||||
return t('userProfile.changePassword.sameAsCurrent')
|
||||
default:
|
||||
return error?.message || t('userProfile.changePassword.failed')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Self-service password rotation. On success the backend revokes every
|
||||
* outstanding session for the caller, so the client should clear local
|
||||
* auth state and send the user back to /login.
|
||||
*/
|
||||
export async function changePassword(
|
||||
data: ChangePasswordRequest,
|
||||
): Promise<{ success: boolean; message?: string }> {
|
||||
try {
|
||||
const response = await post('/api/v1/auth/change-password', data)
|
||||
return response as unknown as { success: boolean; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: resolveChangePasswordError(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证Token有效性
|
||||
*/
|
||||
export async function validateToken(): Promise<{ success: boolean; valid?: boolean; message?: string }> {
|
||||
try {
|
||||
const response = await get('/api/v1/auth/validate')
|
||||
return response as unknown as { success: boolean; valid?: boolean; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
valid: false,
|
||||
message: error.message || t('error.auth.validateTokenFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// ---- share-link registration --------------------------------------------
|
||||
|
||||
// InviteLookup is the public projection of a share-link row used by
|
||||
// /register?token=xxx — enough to render the registration page header
|
||||
// ("X invited you to Y") without leaking sensitive inviter fields.
|
||||
export interface InviteLookup {
|
||||
tenant_id: number
|
||||
tenant_name?: string
|
||||
role: string
|
||||
expires_at: string
|
||||
}
|
||||
|
||||
export interface InviteLookupResponse {
|
||||
success: boolean
|
||||
data?: InviteLookup
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface RegisterByInviteRequest {
|
||||
token: string
|
||||
email: string
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a share-link token (no auth) into the context the
|
||||
* registration page needs (tenant name, role, expiry). Returns 410
|
||||
* when the link is invalid / revoked / expired.
|
||||
*
|
||||
* Uses POST + body (rather than GET + path) so the plaintext token
|
||||
* never appears in access logs, browser history, or tracing spans.
|
||||
*/
|
||||
export async function getInvitationByToken(token: string): Promise<InviteLookupResponse> {
|
||||
try {
|
||||
const response = await post(`/api/v1/auth/invitations/lookup`, { token })
|
||||
return response as unknown as InviteLookupResponse
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || '' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete registration via a share-link token. The invitee supplies
|
||||
* their own email — the token is the authorisation, not an identity
|
||||
* lock.
|
||||
*/
|
||||
export async function registerByInvite(data: RegisterByInviteRequest): Promise<LoginResponse> {
|
||||
try {
|
||||
const response = await post('/api/v1/auth/register-by-invite', data)
|
||||
return response as unknown as LoginResponse
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || t('error.auth.registerFailed') }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
import type { AssistantAccessLevel } from '@/api/assistant'
|
||||
|
||||
// Shapes mirror internal/types/automation.go. Every endpoint works on the
|
||||
// caller's own automations; the server derives the owner from the request.
|
||||
|
||||
export type AutomationTriggerType = 'cron' | 'once'
|
||||
export type AutomationSessionMode = 'per_run' | 'persistent'
|
||||
export type AutomationMisfirePolicy = 'skip' | 'run_once'
|
||||
export type AutomationOverlapPolicy = 'skip' | 'queue'
|
||||
export type AutomationRunStatus =
|
||||
| 'queued'
|
||||
| 'running'
|
||||
| 'awaiting_approval'
|
||||
| 'succeeded'
|
||||
| 'failed'
|
||||
| 'cancelled'
|
||||
| 'skipped'
|
||||
| 'needs_attention'
|
||||
export type AutomationRunTrigger = 'schedule' | 'manual' | 'misfire'
|
||||
|
||||
export interface AutomationTrigger {
|
||||
type: AutomationTriggerType
|
||||
/** Five fields (minute first), six (seconds first) or a descriptor such as @daily. */
|
||||
expr?: string
|
||||
/** When a once trigger fires, RFC 3339. */
|
||||
at?: string
|
||||
/** IANA zone; empty means UTC. */
|
||||
timezone?: string
|
||||
}
|
||||
|
||||
export interface AutomationLimits {
|
||||
/** Execution time of one run, not counting approval waits. 0 uses the default. */
|
||||
max_duration_minutes?: number
|
||||
}
|
||||
|
||||
export interface Automation {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
enabled: boolean
|
||||
model_id: string
|
||||
instruction: string
|
||||
trigger: AutomationTrigger
|
||||
session_mode: AutomationSessionMode
|
||||
persistent_session_id: string
|
||||
carry_last_result: boolean
|
||||
misfire_policy: AutomationMisfirePolicy
|
||||
overlap_policy: AutomationOverlapPolicy
|
||||
access_level: AssistantAccessLevel
|
||||
approval_timeout_minutes: number
|
||||
limits: AutomationLimits
|
||||
notify_on_success: boolean
|
||||
next_run_at: string | null
|
||||
last_run_at: string | null
|
||||
last_success_at: string | null
|
||||
last_run_status: AutomationRunStatus | ''
|
||||
active_run_status?: 'queued' | 'running' | 'awaiting_approval' | ''
|
||||
consecutive_failures: number
|
||||
paused_reason: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/** Fields of a create or update; on update a field left out is kept. */
|
||||
export type AutomationInput = Partial<Pick<Automation,
|
||||
| 'name'
|
||||
| 'description'
|
||||
| 'model_id'
|
||||
| 'instruction'
|
||||
| 'trigger'
|
||||
| 'session_mode'
|
||||
| 'carry_last_result'
|
||||
| 'misfire_policy'
|
||||
| 'overlap_policy'
|
||||
| 'access_level'
|
||||
| 'approval_timeout_minutes'
|
||||
| 'limits'
|
||||
| 'notify_on_success'
|
||||
>>
|
||||
|
||||
export interface AutomationRun {
|
||||
id: string
|
||||
automation_id: string
|
||||
scheduled_at: string
|
||||
trigger_kind: AutomationRunTrigger
|
||||
status: AutomationRunStatus
|
||||
session_id: string
|
||||
user_message_id: string
|
||||
assistant_message_id: string
|
||||
pending_prompt_id: string
|
||||
cancel_requested: boolean
|
||||
answer: string
|
||||
error: string
|
||||
started_at: string | null
|
||||
finished_at: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface AutomationGrant {
|
||||
id: string
|
||||
grant_key: string
|
||||
label: string
|
||||
risk: string
|
||||
prompt_id: string
|
||||
created_at: string
|
||||
last_used_at: string | null
|
||||
/** Why the grant no longer applies, e.g. the agent changed. Empty while it does. */
|
||||
lapse?: string
|
||||
}
|
||||
|
||||
export interface AutomationGrantCandidate {
|
||||
prompt_id: string
|
||||
grant_key: string
|
||||
label: string
|
||||
risk: string
|
||||
tool: string
|
||||
service_name?: string
|
||||
asked_at: string
|
||||
}
|
||||
|
||||
const base = '/api/v1/automations'
|
||||
const enc = encodeURIComponent
|
||||
|
||||
export function listAutomations() {
|
||||
return get<{ success: boolean; data: Automation[] }>(base)
|
||||
}
|
||||
|
||||
export function getAutomation(id: string) {
|
||||
return get<{ success: boolean; data: Automation }>(`${base}/${enc(id)}`)
|
||||
}
|
||||
|
||||
export function getAutomationBySession(sessionId: string) {
|
||||
return get<{ success: boolean; data: Automation }>(`${base}/by-session/${enc(sessionId)}`)
|
||||
}
|
||||
|
||||
export function createAutomation(input: AutomationInput) {
|
||||
return post<{ success: boolean; data: Automation }>(base, input)
|
||||
}
|
||||
|
||||
export function updateAutomation(id: string, input: AutomationInput) {
|
||||
return put<{ success: boolean; data: Automation }>(`${base}/${enc(id)}`, input)
|
||||
}
|
||||
|
||||
export function deleteAutomation(id: string) {
|
||||
return del<{ success: boolean }>(`${base}/${enc(id)}`)
|
||||
}
|
||||
|
||||
export function pauseAutomation(id: string) {
|
||||
return post<{ success: boolean; data: Automation }>(`${base}/${enc(id)}/pause`, {})
|
||||
}
|
||||
|
||||
/** Schedule again from now and clear the failure count; missed runs are not caught up. */
|
||||
export function resumeAutomation(id: string) {
|
||||
return post<{ success: boolean; data: Automation }>(`${base}/${enc(id)}/resume`, {})
|
||||
}
|
||||
|
||||
export function runAutomationNow(id: string) {
|
||||
return post<{ success: boolean; data: AutomationRun }>(`${base}/${enc(id)}/run`, {})
|
||||
}
|
||||
|
||||
/** The next three times trigger fires, in UTC; rejects an invalid or too frequent trigger. */
|
||||
export function validateAutomationTrigger(trigger: AutomationTrigger) {
|
||||
return post<{ success: boolean; data: { next_runs: string[] } }>(`${base}/validate-trigger`, { trigger })
|
||||
}
|
||||
|
||||
export function listAutomationRuns(id: string, page = 1, pageSize = 20) {
|
||||
return get<{ success: boolean; data: AutomationRun[]; total: number }>(
|
||||
`${base}/${enc(id)}/runs?page=${page}&page_size=${pageSize}`,
|
||||
)
|
||||
}
|
||||
|
||||
export function cancelAutomationRun(runId: string) {
|
||||
return post<{ success: boolean; data: AutomationRun }>(`/api/v1/automation-runs/${enc(runId)}/cancel`, {})
|
||||
}
|
||||
|
||||
export function listAutomationGrants(id: string) {
|
||||
return get<{ success: boolean; data: AutomationGrant[] }>(`${base}/${enc(id)}/grants`)
|
||||
}
|
||||
|
||||
export function listAutomationGrantCandidates(id: string) {
|
||||
return get<{ success: boolean; data: AutomationGrantCandidate[] }>(`${base}/${enc(id)}/grant-candidates`)
|
||||
}
|
||||
|
||||
/** Let later runs make the call a past run asked approval for without asking. */
|
||||
export function addAutomationGrant(id: string, promptId: string) {
|
||||
return post<{ success: boolean; data: AutomationGrant }>(`${base}/${enc(id)}/grants`, { prompt_id: promptId })
|
||||
}
|
||||
|
||||
export function revokeAutomationGrant(grantId: string) {
|
||||
return del<{ success: boolean }>(`/api/v1/agent/grants/${enc(grantId)}`)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-app notifications.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type NotificationKind =
|
||||
| 'automation.succeeded'
|
||||
| 'automation.failed'
|
||||
| 'automation.awaiting_approval'
|
||||
| 'automation.paused'
|
||||
|
||||
export interface AppNotification {
|
||||
id: string
|
||||
kind: NotificationKind | string
|
||||
title: string
|
||||
body: string
|
||||
/** In-app route the notification opens. */
|
||||
link: string
|
||||
source_type: string
|
||||
source_id: string
|
||||
read_at: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface PendingNotification {
|
||||
id: string
|
||||
title: string
|
||||
kind: string
|
||||
link: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface NotificationPage {
|
||||
items: AppNotification[]
|
||||
pending: PendingNotification[]
|
||||
unread: number
|
||||
read_count: number
|
||||
next_cursor: string
|
||||
}
|
||||
|
||||
export function listNotifications(limit = 20, cursor = '') {
|
||||
return get<{ success: boolean; data: NotificationPage }>(
|
||||
`/api/v1/notifications?limit=${limit}${cursor ? `&cursor=${enc(cursor)}` : ''}`,
|
||||
)
|
||||
}
|
||||
|
||||
/** Removes read history only; live approvals and run records are unaffected. */
|
||||
export function clearReadNotifications() {
|
||||
return del<{ success: boolean }>('/api/v1/notifications/read')
|
||||
}
|
||||
|
||||
/** Mark history ids read; no ids marks all history. Pending work is separate. */
|
||||
export function markNotificationsRead(ids: string[] = []) {
|
||||
return post<{ success: boolean }>('/api/v1/notifications/read', { ids })
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { get, put, post } from '@/utils/request'
|
||||
|
||||
// ChatHistoryConfig represents the chat history KB configuration for a tenant.
|
||||
// knowledge_base_id is auto-managed by the backend; frontend only sets other fields.
|
||||
export interface ChatHistoryConfig {
|
||||
enabled: boolean
|
||||
embedding_model_id: string
|
||||
knowledge_base_id?: string // read-only, auto-managed
|
||||
}
|
||||
|
||||
// ChatHistoryKBStats represents statistics about the chat history knowledge base
|
||||
export interface ChatHistoryKBStats {
|
||||
enabled: boolean
|
||||
embedding_model_id?: string
|
||||
knowledge_base_id?: string
|
||||
knowledge_base_name?: string
|
||||
indexed_message_count: number
|
||||
has_indexed_messages: boolean
|
||||
}
|
||||
|
||||
// MessageSearchRequest defines search parameters for message search
|
||||
export interface MessageSearchRequest {
|
||||
query: string
|
||||
mode?: 'keyword' | 'vector' | 'hybrid'
|
||||
limit?: number
|
||||
session_ids?: string[]
|
||||
}
|
||||
|
||||
// MessageSearchGroupItem represents a merged Q&A pair in search results
|
||||
export interface MessageSearchGroupItem {
|
||||
request_id: string
|
||||
session_id: string
|
||||
session_title: string
|
||||
query_content: string
|
||||
answer_content: string
|
||||
score: number
|
||||
match_type: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
// MessageSearchResult represents the full search result
|
||||
export interface MessageSearchResult {
|
||||
items: MessageSearchGroupItem[]
|
||||
total: number
|
||||
}
|
||||
|
||||
// Get tenant chat history config via KV API
|
||||
export function getTenantChatHistoryConfig() {
|
||||
return get('/api/v1/tenants/kv/chat-history-config')
|
||||
}
|
||||
|
||||
// Update tenant chat history config via KV API
|
||||
export function updateTenantChatHistoryConfig(config: ChatHistoryConfig) {
|
||||
return put('/api/v1/tenants/kv/chat-history-config', config)
|
||||
}
|
||||
|
||||
// Get chat history KB statistics
|
||||
export function getChatHistoryKBStats() {
|
||||
return get('/api/v1/messages/chat-history-stats')
|
||||
}
|
||||
|
||||
// Search messages across all sessions (keyword + vector hybrid search)
|
||||
export function searchMessages(data: MessageSearchRequest) {
|
||||
return post('/api/v1/messages/search', data)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { get, post } from '../../utils/request'
|
||||
|
||||
/** States the UI and the model both see. `unknown` stays on the server. */
|
||||
export type BackgroundWorkState =
|
||||
| 'running'
|
||||
| 'succeeded'
|
||||
| 'failed'
|
||||
| 'cancelled'
|
||||
| 'lost'
|
||||
|
||||
/**
|
||||
* List rows from GET .../background-work.
|
||||
* The handler never fills parent_tool_call_id, so it is not part of this type.
|
||||
*/
|
||||
export interface BackgroundWorkItem {
|
||||
work_id: string
|
||||
kind: string
|
||||
title: string
|
||||
state: BackgroundWorkState
|
||||
started_at?: string
|
||||
finished_at?: string
|
||||
}
|
||||
|
||||
/** Byte windows on service.ShellJobPayload. */
|
||||
export interface ShellJobByteOffsets {
|
||||
stdout: number
|
||||
stderr: number
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON shape of service.ShellJobPayload, returned as detail `result`.
|
||||
* A user-facing read must not send run_id; the server keeps RunID empty so
|
||||
* the model's incremental cursor does not move.
|
||||
*/
|
||||
export interface ShellJobPayload {
|
||||
display_type: string
|
||||
work_id: string
|
||||
state: string
|
||||
session_id: string
|
||||
command: string
|
||||
work_dir: string
|
||||
exit_code?: number
|
||||
duration_ms: number
|
||||
started_at: string
|
||||
stdout: string
|
||||
stderr: string
|
||||
from_bytes: ShellJobByteOffsets
|
||||
total_bytes: ShellJobByteOffsets
|
||||
omitted_bytes: ShellJobByteOffsets
|
||||
truncated: boolean
|
||||
note?: string
|
||||
}
|
||||
|
||||
export interface BackgroundWorkDetail {
|
||||
work_id: string
|
||||
state: BackgroundWorkState
|
||||
title: string
|
||||
result: ShellJobPayload | null
|
||||
}
|
||||
|
||||
interface ApiData<T> {
|
||||
success?: boolean
|
||||
data?: T
|
||||
}
|
||||
|
||||
function sessionWorkPath(sessionId: string, workId?: string): string {
|
||||
const base = `/api/v1/sessions/${encodeURIComponent(sessionId)}/background-work`
|
||||
return workId === undefined ? base : `${base}/${encodeURIComponent(workId)}`
|
||||
}
|
||||
|
||||
export async function listBackgroundWork(
|
||||
sessionId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<BackgroundWorkItem[]> {
|
||||
const res = await get<ApiData<BackgroundWorkItem[]>>(sessionWorkPath(sessionId), signal ? { signal } : undefined)
|
||||
return Array.isArray(res?.data) ? res.data : []
|
||||
}
|
||||
|
||||
export async function getBackgroundWork(
|
||||
sessionId: string,
|
||||
workId: string,
|
||||
): Promise<BackgroundWorkDetail> {
|
||||
const res = await get<ApiData<BackgroundWorkDetail>>(sessionWorkPath(sessionId, workId))
|
||||
if (!res?.data) {
|
||||
throw new Error('background work not found')
|
||||
}
|
||||
return res.data
|
||||
}
|
||||
|
||||
const cancelInflight = new Map<string, Promise<{ work_id: string; state: string }>>()
|
||||
|
||||
export function cancelBackgroundWork(
|
||||
sessionId: string,
|
||||
workId: string,
|
||||
): Promise<{ work_id: string; state: string }> {
|
||||
const key = `${sessionId}\0${workId}`
|
||||
const pending = cancelInflight.get(key)
|
||||
if (pending) return pending
|
||||
const request = post<ApiData<{ work_id: string; state: string }>>(
|
||||
`${sessionWorkPath(sessionId, workId)}/cancel`,
|
||||
{},
|
||||
).then((res) => {
|
||||
if (!res?.data?.work_id) {
|
||||
throw new Error('background work not found')
|
||||
}
|
||||
return res.data
|
||||
}).finally(() => {
|
||||
if (cancelInflight.get(key) === request) cancelInflight.delete(key)
|
||||
})
|
||||
cancelInflight.set(key, request)
|
||||
return request
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { get, post, put, del, postChat, getDown } from "../../utils/request";
|
||||
|
||||
export type SessionKind = '' | 'assistant';
|
||||
|
||||
export interface SessionSummary {
|
||||
id: string;
|
||||
kind: SessionKind;
|
||||
title: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface CreateSessionRequest {
|
||||
title?: string;
|
||||
description?: string;
|
||||
project_dir?: string;
|
||||
kind?: SessionKind;
|
||||
}
|
||||
|
||||
export async function createSessions(data: CreateSessionRequest = {}) {
|
||||
return post("/api/v1/sessions", data);
|
||||
}
|
||||
|
||||
export async function getSessionsList(page: number, page_size: number, source?: string, kind?: SessionKind) {
|
||||
const params = new URLSearchParams({ page: String(page), page_size: String(page_size) });
|
||||
if (source) {
|
||||
params.set("source", source);
|
||||
}
|
||||
if (kind) params.set("kind", kind);
|
||||
return get(`/api/v1/sessions?${params.toString()}`);
|
||||
}
|
||||
|
||||
export async function pinSession(session_id: string) {
|
||||
return post(`/api/v1/sessions/${session_id}/pin`, {});
|
||||
}
|
||||
|
||||
export async function unpinSession(session_id: string) {
|
||||
return del(`/api/v1/sessions/${session_id}/pin`);
|
||||
}
|
||||
|
||||
export async function generateSessionsTitle(session_id: string, data: any) {
|
||||
return post(`/api/v1/sessions/${session_id}/generate_title`, data);
|
||||
}
|
||||
|
||||
export async function updateSession(session_id: string, data: { title: string; description?: string }) {
|
||||
return put(`/api/v1/sessions/${session_id}`, data);
|
||||
}
|
||||
|
||||
export async function forkSession(
|
||||
session_id: string,
|
||||
data: { message_id: string; title?: string },
|
||||
) {
|
||||
return post(`/api/v1/sessions/${session_id}/fork`, data, { timeout: 180000 });
|
||||
}
|
||||
|
||||
export async function rewindSession(
|
||||
session_id: string,
|
||||
data: { message_id: string },
|
||||
) {
|
||||
return post(`/api/v1/sessions/${session_id}/rewind`, data, { timeout: 180000 });
|
||||
}
|
||||
|
||||
export async function knowledgeChat(data: { session_id: string; query: string; }) {
|
||||
return postChat(`/api/v1/knowledge-chat/${data.session_id}`, { query: data.query, channel: "web" });
|
||||
}
|
||||
|
||||
// Agent chat with streaming support
|
||||
export async function agentChat(data: {
|
||||
session_id: string;
|
||||
query: string;
|
||||
knowledge_base_ids?: string[];
|
||||
agent_enabled: boolean;
|
||||
}) {
|
||||
return postChat(`/api/v1/agent-chat/${data.session_id}`, {
|
||||
query: data.query,
|
||||
knowledge_base_ids: data.knowledge_base_ids,
|
||||
agent_enabled: data.agent_enabled,
|
||||
channel: "web"
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMessageList(data: { session_id: string; limit: number, created_at: string }) {
|
||||
if (data.created_at) {
|
||||
return get(`/api/v1/messages/${data.session_id}/load?before_time=${encodeURIComponent(data.created_at)}&limit=${data.limit}`);
|
||||
} else {
|
||||
return get(`/api/v1/messages/${data.session_id}/load?limit=${data.limit}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function delSession(session_id: string) {
|
||||
return del(`/api/v1/sessions/${session_id}`);
|
||||
}
|
||||
|
||||
export async function batchDelSessions(ids: string[]) {
|
||||
return del(`/api/v1/sessions/batch`, { ids });
|
||||
}
|
||||
|
||||
export async function deleteAllSessions() {
|
||||
return del(`/api/v1/sessions/batch`, { delete_all: true });
|
||||
}
|
||||
|
||||
export async function getSession(session_id: string) {
|
||||
return get(`/api/v1/sessions/${session_id}`);
|
||||
}
|
||||
|
||||
export async function stopSession(session_id: string, message_id: string) {
|
||||
return post(`/api/v1/sessions/${session_id}/stop`, { message_id });
|
||||
}
|
||||
|
||||
export async function clearSessionMessages(session_id: string) {
|
||||
return del(`/api/v1/sessions/${session_id}/messages`);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Skill artifacts (files generated by skill scripts during agent turns)
|
||||
//
|
||||
// The backend keeps the physical storage path private and indexes each file by
|
||||
// its position (:index) in the owning assistant message. The list endpoints
|
||||
// return metadata only — clients must go through downloadArtifact to fetch
|
||||
// the actual bytes so ownership checks always run server-side.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ArtifactMeta {
|
||||
index: number;
|
||||
/**
|
||||
* `resource://<handle>` — the artifact's stable identity, and the destination
|
||||
* the answer body references. Empty when the deployment runs without a
|
||||
* resource catalog, in which case the body references files by name.
|
||||
*/
|
||||
handle?: string;
|
||||
file_name: string;
|
||||
file_type: string;
|
||||
file_size: number;
|
||||
source_path: string;
|
||||
mod_time: string;
|
||||
created_at: string;
|
||||
/**
|
||||
* Set when the user deleted the file. The entry stays in the list so the
|
||||
* artifacts after it keep their index — which is their download address —
|
||||
* so clients filter on this rather than on position.
|
||||
*/
|
||||
deleted_at?: string;
|
||||
}
|
||||
|
||||
// listMessageArtifacts returns the artifacts attached to a single assistant
|
||||
// message. Used by the drawer opened from the message action toolbar.
|
||||
export async function listMessageArtifacts(session_id: string, message_id: string) {
|
||||
return get(
|
||||
`/api/v1/sessions/${session_id}/messages/${message_id}/artifacts`,
|
||||
);
|
||||
}
|
||||
|
||||
// listSessionArtifacts returns every artifact recorded against the whole
|
||||
// session, in creation order. Powers "download everything generated in this
|
||||
// chat" drawers.
|
||||
export async function listSessionArtifacts(session_id: string) {
|
||||
return get(`/api/v1/sessions/${session_id}/artifacts`);
|
||||
}
|
||||
|
||||
// downloadArtifact streams a single artifact's bytes as a Blob so the caller
|
||||
// can trigger a browser download. A plain `<a href>` cannot be used because
|
||||
// axios attaches the Bearer token per request; issuing the download via
|
||||
// `getDown` keeps auth intact and lets the response be turned into an
|
||||
// object URL.
|
||||
export async function downloadArtifact(
|
||||
session_id: string,
|
||||
message_id: string,
|
||||
index: number,
|
||||
): Promise<Blob> {
|
||||
return getDown(
|
||||
`/api/v1/sessions/${session_id}/messages/${message_id}/artifacts/${index}/download`,
|
||||
);
|
||||
}
|
||||
|
||||
// deleteMessageArtifact removes a generated file from the session. The stored
|
||||
// bytes are reclaimed, so this is not reversible; callers confirm first.
|
||||
//
|
||||
// The in-chat panel lists every regeneration of a file as its own row, so it
|
||||
// deletes exactly the row the user clicked. The artifact library folds them
|
||||
// into one entry and passes all_versions.
|
||||
export async function deleteMessageArtifact(
|
||||
session_id: string,
|
||||
message_id: string,
|
||||
index: number,
|
||||
allVersions = false,
|
||||
) {
|
||||
const query = allVersions ? '?all_versions=true' : '';
|
||||
return del(
|
||||
`/api/v1/sessions/${session_id}/messages/${message_id}/artifacts/${index}${query}`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { del, get, post } from "../../utils/request";
|
||||
|
||||
export type SteerDelivery = 'inject' | 'after'
|
||||
|
||||
export type SteerQueueItem = {
|
||||
steer_id: string
|
||||
content: string
|
||||
delivery: SteerDelivery
|
||||
mentioned_items?: unknown[]
|
||||
promoting?: boolean
|
||||
awaitingIdleSend?: boolean
|
||||
// True while POST /steer is in flight. The stable client UUID is also the
|
||||
// durable server ID; disable actions until its queue entry exists.
|
||||
pending?: boolean
|
||||
failed?: boolean
|
||||
expected_assistant_message_id?: string
|
||||
client_id?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Append a message to a running agent turn.
|
||||
* Returns { success, status: 'queued' | 'already_injected' | 'new_run', steer_id?, delivery?, assistant_message_id? }.
|
||||
* - delivery 'after' (default): waits until the current run exits, then starts a follow-up turn.
|
||||
* - delivery 'inject': the running engine injects it at the next round boundary.
|
||||
* - 'new_run': no run is live; the caller should fall back to a normal send.
|
||||
* Lookup failures (503) reject rather than returning new_run — treating them
|
||||
* as idle would start a second turn on top of the one still generating.
|
||||
*/
|
||||
export async function steerSession(
|
||||
session_id: string,
|
||||
query: string,
|
||||
mentionedItems: any[] = [],
|
||||
delivery: SteerDelivery = 'after',
|
||||
expectedAssistantMessageId?: string,
|
||||
steerId?: string,
|
||||
) {
|
||||
return post(`/api/v1/sessions/${session_id}/steer`, {
|
||||
query,
|
||||
expected_assistant_message_id: expectedAssistantMessageId,
|
||||
steer_id: steerId,
|
||||
mentioned_items: mentionedItems,
|
||||
channel: 'web',
|
||||
delivery,
|
||||
});
|
||||
}
|
||||
|
||||
/** Flip a queued after-message to inject so the running turn reads it next. */
|
||||
export async function promoteSteerSession(session_id: string, steer_id: string) {
|
||||
return post(`/api/v1/sessions/${session_id}/steer/${steer_id}/inject`, {});
|
||||
}
|
||||
|
||||
/** Pending overlay items for the live run. Empty when nothing is generating. */
|
||||
export async function listSteerSession(session_id: string) {
|
||||
return get(`/api/v1/sessions/${session_id}/steer`);
|
||||
}
|
||||
|
||||
/** Drop a queued overlay item so it is neither injected nor sent as a follow-up. */
|
||||
export async function removeSteerSession(session_id: string, steer_id: string) {
|
||||
return del(`/api/v1/sessions/${session_id}/steer/${steer_id}`);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/** Current state of a delegated run, independent of its parent answer. */
|
||||
export interface CollaborationProgress {
|
||||
phase?: string
|
||||
tool_name?: string
|
||||
tool_call_id?: string
|
||||
iteration?: number
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface CollaborationTaskStatus {
|
||||
id: string
|
||||
name: string
|
||||
display_name?: string
|
||||
agent_id: string
|
||||
session_id: string
|
||||
run_id: string
|
||||
status: string
|
||||
progress?: CollaborationProgress | null
|
||||
prompt_id?: string
|
||||
latest_message?: string
|
||||
}
|
||||
|
||||
export interface CollaborationStatus {
|
||||
group_id: string
|
||||
revision: number
|
||||
tasks: CollaborationTaskStatus[]
|
||||
}
|
||||
|
||||
export interface CollaborationStatusStreamEvent {
|
||||
response_type: 'collaboration_status'
|
||||
/** Parent request identifier; child run identifiers live in tasks. */
|
||||
id: string
|
||||
assistant_message_id?: string
|
||||
data: CollaborationStatus
|
||||
}
|
||||
|
||||
export interface ProgressStreamEvent {
|
||||
response_type: 'progress'
|
||||
id: string
|
||||
assistant_message_id?: string
|
||||
/** Cumulative visible progress text for this event, safe to replay. */
|
||||
content: string
|
||||
done: boolean
|
||||
data: { event_id: string; iteration?: number }
|
||||
}
|
||||
|
||||
/** Persisted agent step fields used when rebuilding the visible timeline. */
|
||||
export interface AgentStepRecord extends Record<string, unknown> {
|
||||
iteration?: number
|
||||
thought?: string
|
||||
reasoning_content?: string
|
||||
progress?: string
|
||||
progress_event_id?: string
|
||||
}
|
||||
|
||||
export interface ChatHistoryMessage extends Record<string, unknown> {
|
||||
collaboration_status?: CollaborationStatus
|
||||
agent_steps?: AgentStepRecord[]
|
||||
}
|
||||
|
||||
/** An explicit protocol correction replaces only this answer segment. */
|
||||
export interface AnswerStreamMetadata {
|
||||
event_id: string
|
||||
replace?: boolean
|
||||
truncated?: boolean
|
||||
is_fallback?: boolean
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { after, before, test } from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createServer, type ViteDevServer } from 'vite'
|
||||
import { createSSRApp } from 'vue'
|
||||
import { renderToString } from 'vue/server-renderer'
|
||||
|
||||
let server: ViteDevServer
|
||||
let useStream: typeof import('./streame').useStream
|
||||
let transport: { requests: Array<{ url: string; options: { body: string } }> }
|
||||
const originalStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
|
||||
before(async () => {
|
||||
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: {
|
||||
getItem: (key: string) => key === 'academy_token' ? 'test-token' : null,
|
||||
} })
|
||||
const mocks: Record<string, string> = {
|
||||
'@microsoft/fetch-event-source': `export const requests = []; export async function fetchEventSource(url, options) { requests.push({url, options}); }`,
|
||||
'@/utils/index': `export const generateRandomString = () => 'test-request';`,
|
||||
'@/i18n': `export default { global: { t: key => key, locale: { value: 'zh-CN' } } };`,
|
||||
}
|
||||
server = await createServer({
|
||||
configFile: false,
|
||||
plugins: [{ name: 'stream-request-test', enforce: 'pre',
|
||||
resolveId(id) { if (id.startsWith('\0mock:')) return id },
|
||||
load(id) { if (id.startsWith('\0mock:')) return mocks[id.slice(6)] },
|
||||
}],
|
||||
optimizeDeps: { noDiscovery: true, entries: [] },
|
||||
resolve: { alias: [
|
||||
...Object.keys(mocks).map(find => ({ find, replacement: '\0mock:' + find })),
|
||||
{ find: '@', replacement: fileURLToPath(new URL('../../', import.meta.url)) },
|
||||
] },
|
||||
server: { middlewareMode: true, hmr: false }, appType: 'custom',
|
||||
})
|
||||
;({ useStream } = await server.ssrLoadModule('/src/api/chat/streame.ts'))
|
||||
transport = await server.ssrLoadModule('\0mock:@microsoft/fetch-event-source') as typeof transport
|
||||
})
|
||||
after(async () => {
|
||||
await server?.close()
|
||||
if (originalStorage) Object.defineProperty(globalThis, 'localStorage', originalStorage)
|
||||
else Reflect.deleteProperty(globalThis, 'localStorage')
|
||||
})
|
||||
|
||||
test('approval reattach identifies the resumed segment without changing ordinary replay', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
try {
|
||||
for (const pendingId of [undefined, 'pending/a+b']) {
|
||||
await stream.startStream({
|
||||
session_id: 'session', query: 'message', method: 'GET',
|
||||
url: '/api/v1/sessions/continue-stream', resume_pending_id: pendingId,
|
||||
})
|
||||
assert.equal(stream.error.value, null)
|
||||
const request = transport.requests.at(-1)!
|
||||
assert.equal(request.url, '/api/v1/sessions/continue-stream/session?message_id=message' +
|
||||
(pendingId ? '&resume_pending_id=pending%2Fa%2Bb' : ''))
|
||||
}
|
||||
} finally { stream.stopStream() }
|
||||
})
|
||||
|
||||
for (const effort of [undefined, '', 'off', 'auto', 'high', 'max']) {
|
||||
test(`SSE body carries only explicit reasoning overrides: ${effort}`, async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
try {
|
||||
await stream.startStream({
|
||||
session_id: 'session', query: 'question', method: 'POST', url: '/api/v1/agent-chat',
|
||||
reasoning_effort: effort,
|
||||
})
|
||||
assert.equal(stream.error.value, null)
|
||||
const body = JSON.parse(transport.requests.at(-1)!.options.body)
|
||||
assert.equal(body.reasoning_effort, effort || undefined)
|
||||
assert.equal(Object.hasOwn(body, 'reasoning_effort'), !!effort)
|
||||
} finally { stream.stopStream() }
|
||||
})
|
||||
}
|
||||
|
||||
for (const selected of [true, false, undefined]) {
|
||||
test(`SSE HTTP body preserves browser selection ${selected} alongside other tools`, async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
try {
|
||||
await stream.startStream({
|
||||
session_id: 'new-session', query: '查一下腾讯股价', method: 'POST', url: '/api/v1/agent-chat',
|
||||
agent_enabled: true, local_browser_enabled: selected, web_search_enabled: true,
|
||||
mcp_service_ids: ['mcp-1'], skill_names: ['report'],
|
||||
})
|
||||
assert.equal(stream.error.value, null)
|
||||
const request = transport.requests.at(-1)!
|
||||
assert.equal(request.url, '/api/v1/agent-chat/new-session')
|
||||
const body = JSON.parse(request.options.body)
|
||||
assert.equal(body.local_browser_enabled, selected)
|
||||
assert.equal(Object.hasOwn(body, 'local_browser_enabled'), selected !== undefined)
|
||||
assert.equal(body.web_search_enabled, true)
|
||||
assert.deepEqual(body.mcp_service_ids, ['mcp-1'])
|
||||
assert.deepEqual(body.skill_names, ['report'])
|
||||
assert.equal(stream.lastStreamRequest.value?.body?.local_browser_enabled, selected)
|
||||
} finally { stream.stopStream() }
|
||||
})
|
||||
}
|
||||
|
||||
test('SSE body carries an agent-only page context', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
try {
|
||||
await stream.startStream({
|
||||
session_id: 'session', query: 'Check', method: 'POST', url: '/api/v1/agent-chat',
|
||||
agent_enabled: true, page_context: { agent_id: 'agent-a' },
|
||||
})
|
||||
assert.equal(stream.error.value, null)
|
||||
const body = JSON.parse(transport.requests.at(-1)!.options.body)
|
||||
assert.deepEqual(body.page_context, { agent_id: 'agent-a' })
|
||||
assert.equal(body.assistant_scope, undefined)
|
||||
} finally { stream.stopStream() }
|
||||
})
|
||||
@@ -0,0 +1,380 @@
|
||||
import { fetchEventSource } from '@microsoft/fetch-event-source';
|
||||
import { ref, onUnmounted } from 'vue';
|
||||
import { generateRandomString } from '@/utils/index';
|
||||
import i18n from '@/i18n';
|
||||
import { getApiBaseUrl } from '@/utils/api-base';
|
||||
import type { AssistantAccessLevel } from '@/api/assistant';
|
||||
export type { CollaborationStatus, CollaborationTaskStatus, CollaborationProgress,
|
||||
CollaborationStatusStreamEvent, ProgressStreamEvent, AgentStepRecord, ChatHistoryMessage } from './streamTypes';
|
||||
import {
|
||||
sanitizeStreamRequestBody,
|
||||
type StreamRequestMeta,
|
||||
} from '@/utils/chatRequestDebug';
|
||||
import {
|
||||
StreamAuthError,
|
||||
isStreamAuthError,
|
||||
refreshAccessTokenShared,
|
||||
runStreamWithAuthRetry,
|
||||
} from '@/utils/authRefresh';
|
||||
|
||||
/** The Academy page the user has open; agent-chat only. */
|
||||
export interface PageContextPayload {
|
||||
page?: string
|
||||
section?: string
|
||||
agent_id?: string
|
||||
knowledge_base_id?: string
|
||||
knowledge_id?: string
|
||||
wiki_slug?: string
|
||||
wiki_issue_ids?: string[]
|
||||
model_id?: string
|
||||
mcp_service_id?: string
|
||||
session_id?: string
|
||||
message_id?: string
|
||||
/** The page's name as the sidebar shows it. */
|
||||
title?: string
|
||||
/** The dialog or drawer open over the page. */
|
||||
view?: string
|
||||
selection?: PageSelectionPayload
|
||||
}
|
||||
|
||||
export interface PageSelectionPayload {
|
||||
text: string
|
||||
field?: string
|
||||
ref?: string
|
||||
start_line?: number
|
||||
end_line?: number
|
||||
}
|
||||
|
||||
interface StreamOptions {
|
||||
// 请求方法 (默认POST)
|
||||
method?: 'GET' | 'POST'
|
||||
// 请求头
|
||||
headers?: Record<string, string>
|
||||
// 请求体自动序列化
|
||||
body?: Record<string, any>
|
||||
// 流式渲染间隔 (ms)
|
||||
chunkInterval?: number
|
||||
}
|
||||
|
||||
export function useStream() {
|
||||
// 响应式状态
|
||||
const output = ref('') // 显示内容
|
||||
const isStreaming = ref(false) // 流状态
|
||||
const isLoading = ref(false) // 初始加载
|
||||
const error = ref<string | null>(null)// 错误信息
|
||||
const lastStreamRequest = ref<StreamRequestMeta | null>(null)
|
||||
let controller = new AbortController()
|
||||
let streamGeneration = 0
|
||||
|
||||
// 流式渲染缓冲
|
||||
let buffer: string[] = []
|
||||
let renderTimer: number | null = null
|
||||
|
||||
// 启动流式请求
|
||||
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; agent_source_tenant_id?: string | number; web_search_enabled?: boolean; local_browser_enabled?: boolean; summary_model_id?: string; reasoning_effort?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; question_origin?: { knowledge_base_id: string; knowledge_id?: string }; page_context?: PageContextPayload; assistant_access?: AssistantAccessLevel; method: string; url: string; resume_pending_id?: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
|
||||
const myGeneration = ++streamGeneration
|
||||
const streamAbort = controller
|
||||
// 重置状态
|
||||
output.value = '';
|
||||
error.value = null;
|
||||
isStreaming.value = true;
|
||||
isLoading.value = true;
|
||||
|
||||
// 获取API配置
|
||||
const apiUrl = getApiBaseUrl();
|
||||
|
||||
const embedToken = params.embed_token;
|
||||
const token = embedToken || localStorage.getItem('academy_token');
|
||||
if (!token) {
|
||||
error.value = i18n.global.t('error.tokenNotFound');
|
||||
stopStream();
|
||||
return;
|
||||
}
|
||||
|
||||
// 跨空间访问请求头:只要 setSelectedTenant 写过激活空间,就附
|
||||
// X-Tenant-ID。早期版本会 short-circuit "selectedTenantId ===
|
||||
// defaultTenantId 时不附" 来减少 header 体积,但任何把 academy_tenant
|
||||
// 写成激活空间的代码(OIDC 同步 / UserMenu loadUserInfo / router
|
||||
// hydrate)都会让两者相等,使得后续流式请求悄悄丢 header、落到
|
||||
// home 空间上,导致 SSE 接口返回 404。直接附即可——后端
|
||||
// IsTenantAccessible 也允许 header 指向自家空间。
|
||||
const selectedTenantId = localStorage.getItem('academy_selected_tenant_id');
|
||||
const tenantIdHeader: string | null = selectedTenantId || null;
|
||||
|
||||
// TTFB instrumentation: record the moment we kick off the request so
|
||||
// we can compare it with the first answer chunk we receive from the
|
||||
// server. This makes it possible to correlate the frontend-observed
|
||||
// latency with the backend "TTFB:first_answer_chunk" log line by
|
||||
// matching on X-Request-ID.
|
||||
const sentAt = performance.now();
|
||||
const requestID = generateRandomString(12);
|
||||
let firstAnswerLogged = false;
|
||||
let receivedAssistantId = '';
|
||||
let receivedTerminal = false;
|
||||
let reconnectAttempts = 0;
|
||||
let streamMethod = params.method;
|
||||
// Never repeat an accepted POST: recovery attaches to its persisted message.
|
||||
const canReconnect = () => !embedToken && receivedAssistantId && !receivedTerminal &&
|
||||
(params.url === '/api/v1/agent-chat' || params.url === '/api/v1/sessions/continue-stream') &&
|
||||
myGeneration === streamGeneration && !streamAbort.signal.aborted;
|
||||
|
||||
|
||||
try {
|
||||
let url =
|
||||
params.method == "POST"
|
||||
? `${apiUrl}${params.url}/${params.session_id}`
|
||||
: `${apiUrl}${params.url}/${params.session_id}?message_id=${params.query}`;
|
||||
if (params.method === "GET" && params.resume_pending_id) {
|
||||
url += `&resume_pending_id=${encodeURIComponent(params.resume_pending_id)}`;
|
||||
}
|
||||
console.log(`[TTFB] request:start request_id=${requestID} url=${url} sent_at=${Date.now()}`);
|
||||
|
||||
// Prepare POST body with required fields for agent-chat
|
||||
// knowledge_base_ids array and agent_enabled can update Session's SessionAgentConfig
|
||||
const postBody: any = {
|
||||
query: params.query,
|
||||
agent_enabled: params.agent_enabled !== undefined ? params.agent_enabled : true
|
||||
};
|
||||
// Always include knowledge_base_ids for agent-chat (already validated above)
|
||||
if (params.knowledge_base_ids !== undefined && params.knowledge_base_ids.length > 0) {
|
||||
postBody.knowledge_base_ids = params.knowledge_base_ids;
|
||||
}
|
||||
// Include knowledge_ids if provided
|
||||
if (params.knowledge_ids !== undefined && params.knowledge_ids.length > 0) {
|
||||
postBody.knowledge_ids = params.knowledge_ids;
|
||||
}
|
||||
// Include agent_id if provided (backend resolves shared agent and tenant from share relation)
|
||||
if (params.agent_id) {
|
||||
postBody.agent_id = params.agent_id;
|
||||
}
|
||||
if (params.agent_source_tenant_id) {
|
||||
postBody.agent_source_tenant_id = Number(params.agent_source_tenant_id);
|
||||
}
|
||||
// Include web_search_enabled if provided
|
||||
if (params.web_search_enabled !== undefined) {
|
||||
postBody.web_search_enabled = params.web_search_enabled;
|
||||
}
|
||||
// Preserve the explicit browser choice when rebuilding the HTTP body.
|
||||
if (params.local_browser_enabled !== undefined) {
|
||||
postBody.local_browser_enabled = params.local_browser_enabled;
|
||||
}
|
||||
// Include summary_model_id if provided (for non-Agent mode)
|
||||
if (params.summary_model_id) {
|
||||
postBody.summary_model_id = params.summary_model_id;
|
||||
}
|
||||
// Omit inheritance so the agent's current default remains authoritative.
|
||||
if (params.reasoning_effort) {
|
||||
postBody.reasoning_effort = params.reasoning_effort;
|
||||
}
|
||||
// Include mcp_service_ids if provided (for Agent mode)
|
||||
if (params.mcp_service_ids !== undefined && params.mcp_service_ids.length > 0) {
|
||||
postBody.mcp_service_ids = params.mcp_service_ids;
|
||||
}
|
||||
if (params.skill_names !== undefined && params.skill_names.length > 0) {
|
||||
postBody.skill_names = params.skill_names;
|
||||
}
|
||||
if (params.tag_ids !== undefined && params.tag_ids.length > 0) {
|
||||
postBody.tag_ids = params.tag_ids;
|
||||
}
|
||||
// Include mentioned_items if provided (for displaying @mentions in chat)
|
||||
if (params.mentioned_items !== undefined && params.mentioned_items.length > 0) {
|
||||
postBody.mentioned_items = params.mentioned_items;
|
||||
}
|
||||
// Include images if provided (base64 data URIs for multimodal chat)
|
||||
if (params.images !== undefined && params.images.length > 0) {
|
||||
postBody.images = params.images;
|
||||
}
|
||||
// Include attachment_uploads if provided (documents, audio, etc.)
|
||||
if (params.attachment_uploads !== undefined && params.attachment_uploads.length > 0) {
|
||||
postBody.attachment_uploads = params.attachment_uploads;
|
||||
}
|
||||
if (params.attachment_ids !== undefined && params.attachment_ids.length > 0) {
|
||||
postBody.attachment_ids = params.attachment_ids;
|
||||
}
|
||||
if (params.suggestion_attribution) {
|
||||
postBody.suggestion_attribution = params.suggestion_attribution;
|
||||
}
|
||||
if (params.question_origin) {
|
||||
postBody.question_origin = params.question_origin;
|
||||
}
|
||||
if (params.page_context) {
|
||||
postBody.page_context = params.page_context;
|
||||
}
|
||||
if (params.assistant_access) {
|
||||
postBody.assistant_access = params.assistant_access;
|
||||
}
|
||||
postBody.channel = embedToken ? "embed" : "web";
|
||||
|
||||
lastStreamRequest.value = {
|
||||
requestId: requestID,
|
||||
url,
|
||||
method: params.method,
|
||||
body: params.method === 'POST' ? sanitizeStreamRequestBody(postBody) : null,
|
||||
sentAt: Date.now(),
|
||||
};
|
||||
|
||||
// Wrapped so an expired access token can be refreshed and the request
|
||||
// replayed once. Nothing has been streamed to the UI yet when the
|
||||
// handshake 401s, so the replay is invisible to the user.
|
||||
const runStream = async (authToken: string) => {
|
||||
const connection = new AbortController();
|
||||
const abortConnection = () => connection.abort();
|
||||
streamAbort.signal.addEventListener('abort', abortConnection, { once: true });
|
||||
let idleTimer: ReturnType<typeof setTimeout>;
|
||||
let rejectIdle: (reason: Error) => void;
|
||||
const idle = new Promise<never>((_, reject) => { rejectIdle = reject; });
|
||||
const armIdle = () => {
|
||||
clearTimeout(idleTimer);
|
||||
if (!canReconnect()) return;
|
||||
idleTimer = setTimeout(() => {
|
||||
rejectIdle(new Error('stream heartbeat timed out'));
|
||||
connection.abort();
|
||||
}, 30000);
|
||||
};
|
||||
armIdle();
|
||||
try {
|
||||
await Promise.race([idle, fetchEventSource(url, {
|
||||
method: streamMethod,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": embedToken ? `Embed ${embedToken}` : `Bearer ${authToken}`,
|
||||
"Accept-Language": i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN',
|
||||
"X-Request-ID": requestID,
|
||||
...(!embedToken && tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}),
|
||||
...(params.embed_session_sig ? { "X-Embed-Session": params.embed_session_sig } : {}),
|
||||
...(params.embed_visitor_id ? { "X-Embed-Visitor": params.embed_visitor_id } : {}),
|
||||
},
|
||||
body:
|
||||
streamMethod == "POST"
|
||||
? JSON.stringify(postBody)
|
||||
: null,
|
||||
signal: connection.signal,
|
||||
openWhenHidden: true,
|
||||
|
||||
onopen: async (res) => {
|
||||
// 401 is recoverable (refresh + replay); everything else is not.
|
||||
if (res.status === 401) throw new StreamAuthError(res.status);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
console.log(`[TTFB] response:headers request_id=${requestID} elapsed_ms=${(performance.now() - sentAt).toFixed(1)}`);
|
||||
if (myGeneration === streamGeneration) isLoading.value = false;
|
||||
},
|
||||
|
||||
onmessage: (ev) => {
|
||||
if (myGeneration !== streamGeneration) return
|
||||
const parsed = JSON.parse(ev.data);
|
||||
reconnectAttempts = 0;
|
||||
if (parsed?.response_type === 'agent_query' && typeof parsed.assistant_message_id === 'string') {
|
||||
receivedAssistantId = parsed.assistant_message_id;
|
||||
}
|
||||
if (['complete', 'stop', 'error'].includes(parsed?.response_type)) receivedTerminal = true;
|
||||
armIdle();
|
||||
if (parsed?.response_type === 'heartbeat') return;
|
||||
// Log first answer chunk for end-to-end TTFB measurement.
|
||||
// Filter by event type so non-answer events (references, tool
|
||||
// calls, etc.) don't count as the "first token" arrival.
|
||||
if (!firstAnswerLogged && (parsed?.response_type === 'answer' || parsed?.type === 'answer')) {
|
||||
firstAnswerLogged = true;
|
||||
console.log(`[TTFB] response:first_answer request_id=${requestID} elapsed_ms=${(performance.now() - sentAt).toFixed(1)}`);
|
||||
}
|
||||
buffer.push(parsed); // 数据存入缓冲
|
||||
// 执行自定义处理
|
||||
if (chunkHandler) {
|
||||
chunkHandler(parsed);
|
||||
}
|
||||
},
|
||||
|
||||
onerror: (err) => {
|
||||
if (isStreamAuthError(err)) throw err;
|
||||
throw new Error(`${i18n.global.t('error.streamFailed')}: ${err}`);
|
||||
},
|
||||
|
||||
onclose: () => {
|
||||
// A queued follow-up attaches via continue-stream while the previous
|
||||
// POST may still be open waiting for the session title. Both share one
|
||||
// controller, so only the current stream may stop it; otherwise the
|
||||
// old connection closing cuts the follow-up off mid-answer.
|
||||
if (canReconnect()) throw new Error('stream closed before the turn completed');
|
||||
if (myGeneration === streamGeneration) stopStream();
|
||||
},
|
||||
})]);
|
||||
} finally {
|
||||
clearTimeout(idleTimer!);
|
||||
streamAbort.signal.removeEventListener('abort', abortConnection);
|
||||
connection.abort();
|
||||
}
|
||||
};
|
||||
|
||||
while (myGeneration === streamGeneration && !streamAbort.signal.aborted) {
|
||||
try {
|
||||
await runStreamWithAuthRetry({
|
||||
run: runStream,
|
||||
initialToken: token,
|
||||
isEmbed: Boolean(embedToken),
|
||||
isCurrent: () => myGeneration === streamGeneration && !streamAbort.signal.aborted,
|
||||
refreshAccessToken: () => refreshAccessTokenShared({
|
||||
messages: {
|
||||
pleaseRelogin: i18n.global.t('error.pleaseRelogin'),
|
||||
tokenRefreshFailed: i18n.global.t('error.tokenRefreshFailed'),
|
||||
},
|
||||
}),
|
||||
reloginMessage: i18n.global.t('error.pleaseRelogin'),
|
||||
});
|
||||
break;
|
||||
} catch (err) {
|
||||
if (!canReconnect() || isStreamAuthError(err) || reconnectAttempts >= 8) throw err;
|
||||
reconnectAttempts++;
|
||||
// The server may still be restarting. A stop/new turn invalidates
|
||||
// this retry before it can attach or change visible state.
|
||||
await new Promise<void>((resolve) => {
|
||||
const done = () => {
|
||||
clearTimeout(timer);
|
||||
streamAbort.signal.removeEventListener('abort', done);
|
||||
resolve();
|
||||
};
|
||||
const timer = setTimeout(done, Math.min(1000 * 2 ** (reconnectAttempts - 1), 5000));
|
||||
streamAbort.signal.addEventListener('abort', done, { once: true });
|
||||
});
|
||||
if (myGeneration !== streamGeneration || streamAbort.signal.aborted) return;
|
||||
streamMethod = 'GET';
|
||||
url = `${apiUrl}/api/v1/sessions/continue-stream/${encodeURIComponent(params.session_id)}?message_id=${encodeURIComponent(receivedAssistantId)}`;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// A superseded stream failing must not surface as the current error or
|
||||
// abort the stream that replaced it (see onclose).
|
||||
if (myGeneration !== streamGeneration) return
|
||||
error.value = err instanceof Error ? err.message : String(err)
|
||||
stopStream()
|
||||
}
|
||||
}
|
||||
|
||||
let chunkHandler: ((data: any) => void) | null = null
|
||||
// 注册块处理器
|
||||
const onChunk = (handler: (data: any) => void) => {
|
||||
chunkHandler = handler
|
||||
}
|
||||
|
||||
|
||||
// 停止流
|
||||
const stopStream = () => {
|
||||
streamGeneration++
|
||||
controller.abort();
|
||||
controller = new AbortController(); // 重置控制器(如需重新发起)
|
||||
isStreaming.value = false;
|
||||
isLoading.value = false;
|
||||
}
|
||||
|
||||
// 组件卸载时自动清理
|
||||
onUnmounted(stopStream)
|
||||
|
||||
return {
|
||||
output, // 显示内容
|
||||
isStreaming, // 是否在流式传输中
|
||||
isLoading, // 初始连接状态
|
||||
error,
|
||||
lastStreamRequest,
|
||||
onChunk,
|
||||
startStream, // 启动流
|
||||
stopStream // 手动停止
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
// A queued follow-up attaches via continue-stream while the previous POST may
|
||||
// still be open (it waits up to 3s for the session title). An older stream
|
||||
// closing or failing must not cut off the stream that replaced it.
|
||||
import assert from 'node:assert/strict'
|
||||
import { after, before, test } from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createServer, type ViteDevServer } from 'vite'
|
||||
import { createSSRApp } from 'vue'
|
||||
import { renderToString } from 'vue/server-renderer'
|
||||
|
||||
type Call = {
|
||||
url: string
|
||||
options: { signal: AbortSignal, onmessage: (ev: { data: string }) => void, onclose: () => void }
|
||||
resolve: () => void
|
||||
reject: (err: unknown) => void
|
||||
}
|
||||
|
||||
let server: ViteDevServer
|
||||
let useStream: typeof import('./streame').useStream
|
||||
let transport: { calls: Call[] }
|
||||
const originalStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
|
||||
before(async () => {
|
||||
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: {
|
||||
getItem: (key: string) => key === 'academy_token' ? 'test-token' : null,
|
||||
} })
|
||||
// Each request stays pending until the test closes or fails it.
|
||||
const mocks: Record<string, string> = {
|
||||
'@microsoft/fetch-event-source': `export const calls = [];
|
||||
export function fetchEventSource(url, options) {
|
||||
return new Promise((resolve, reject) => { calls.push({ url, options, resolve, reject }) })
|
||||
}`,
|
||||
'@/utils/index': `export const generateRandomString = () => 'test-request';`,
|
||||
'@/i18n': `export default { global: { t: key => key, locale: { value: 'zh-CN' } } };`,
|
||||
}
|
||||
server = await createServer({
|
||||
configFile: false,
|
||||
plugins: [{ name: 'stream-overlap-test', enforce: 'pre',
|
||||
resolveId(id) { if (id.startsWith('\0mock:')) return id },
|
||||
load(id) { if (id.startsWith('\0mock:')) return mocks[id.slice(6)] },
|
||||
}],
|
||||
optimizeDeps: { noDiscovery: true, entries: [] },
|
||||
resolve: { alias: [
|
||||
...Object.keys(mocks).map(find => ({ find, replacement: '\0mock:' + find })),
|
||||
{ find: '@', replacement: fileURLToPath(new URL('../../', import.meta.url)) },
|
||||
] },
|
||||
// No file watching needed in tests (also avoids ENOSPC on hosts with few inotify watches).
|
||||
server: { middlewareMode: true, hmr: false, watch: null }, appType: 'custom',
|
||||
})
|
||||
;({ useStream } = await server.ssrLoadModule('/src/api/chat/streame.ts'))
|
||||
transport = await server.ssrLoadModule('\0mock:@microsoft/fetch-event-source') as typeof transport
|
||||
})
|
||||
after(async () => {
|
||||
await server?.close()
|
||||
if (originalStorage) Object.defineProperty(globalThis, 'localStorage', originalStorage)
|
||||
else Reflect.deleteProperty(globalThis, 'localStorage')
|
||||
})
|
||||
|
||||
async function nextCall(count: number): Promise<Call> {
|
||||
for (let i = 0; i < 100 && transport.calls.length < count; i++) await new Promise(r => setTimeout(r, 5))
|
||||
assert.equal(transport.calls.length, count, 'fetchEventSource was not called')
|
||||
return transport.calls[count - 1]
|
||||
}
|
||||
|
||||
async function overlapping() {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const chunks: unknown[] = []
|
||||
stream.onChunk(data => chunks.push(data))
|
||||
const base = transport.calls.length
|
||||
// First question: the POST stays open after its answer, waiting for the title.
|
||||
const first = stream.startStream({ session_id: 's', query: 'q1', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const a = await nextCall(base + 1)
|
||||
// The queued follow-up attaches while that POST is still open.
|
||||
const second = stream.startStream({ session_id: 's', query: 'assistant-2', method: 'GET', url: '/api/v1/sessions/continue-stream' })
|
||||
const b = await nextCall(base + 2)
|
||||
assert.match(b.url, /continue-stream\/s\?message_id=assistant-2$/)
|
||||
return { stream, chunks, a, b, first, second }
|
||||
}
|
||||
|
||||
test('an older stream closing does not cut the newer follow-up stream', async () => {
|
||||
const { stream, chunks, a, b, first, second } = await overlapping()
|
||||
a.options.onclose()
|
||||
a.resolve()
|
||||
await first
|
||||
assert.equal(b.options.signal.aborted, false, 'old onclose aborted the new stream')
|
||||
assert.equal(stream.isStreaming.value, true)
|
||||
b.options.onmessage({ data: JSON.stringify({ response_type: 'answer', id: 'r2', content: 'hi' }) })
|
||||
assert.equal(chunks.length, 1, 'new stream events were dropped after the old one closed')
|
||||
// The current stream closing still stops as before.
|
||||
b.options.onclose()
|
||||
b.resolve()
|
||||
await second
|
||||
assert.equal(stream.isStreaming.value, false)
|
||||
assert.equal(b.options.signal.aborted, true)
|
||||
assert.equal(stream.error.value, null)
|
||||
})
|
||||
|
||||
test('an older stream failing does not report an error or cut the newer stream', async () => {
|
||||
const { stream, chunks, a, b, first, second } = await overlapping()
|
||||
a.reject(new Error('old connection reset'))
|
||||
await first
|
||||
assert.equal(stream.error.value, null, 'old stream error leaked into the current one')
|
||||
assert.equal(b.options.signal.aborted, false)
|
||||
b.options.onmessage({ data: JSON.stringify({ response_type: 'complete', id: 'r2' }) })
|
||||
assert.equal(chunks.length, 1)
|
||||
b.options.onclose()
|
||||
b.resolve()
|
||||
await second
|
||||
})
|
||||
|
||||
test('the current stream failing still reports the error and stops', async () => {
|
||||
const { stream, a, b, first, second } = await overlapping()
|
||||
b.reject(new Error('current connection reset'))
|
||||
await second
|
||||
assert.match(String(stream.error.value), /current connection reset/)
|
||||
assert.equal(stream.isStreaming.value, false)
|
||||
assert.equal(b.options.signal.aborted, true)
|
||||
a.resolve()
|
||||
await first
|
||||
})
|
||||
|
||||
test('a disconnected accepted agent POST resumes by GET without executing the query twice', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const base = transport.calls.length
|
||||
const run = stream.startStream({ session_id: 'parent', query: 'spawn children', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = await nextCall(base + 1)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'answer-1' }) })
|
||||
post.reject(new Error('server restarted'))
|
||||
await new Promise(r => setTimeout(r, 1050))
|
||||
const resumed = await nextCall(base + 2)
|
||||
assert.match(resumed.url, /\/sessions\/continue-stream\/parent\?message_id=answer-1$/)
|
||||
assert.equal((resumed.options as any).method, 'GET')
|
||||
assert.equal((resumed.options as any).body, null)
|
||||
assert.equal(stream.isStreaming.value, true)
|
||||
assert.equal(stream.error.value, null)
|
||||
resumed.options.onmessage({ data: JSON.stringify({ response_type: 'complete', id: 'r1' }) })
|
||||
resumed.options.onclose()
|
||||
resumed.resolve()
|
||||
await run
|
||||
assert.equal(stream.isStreaming.value, false)
|
||||
})
|
||||
|
||||
test('stop during reconnect backoff prevents the old parent from attaching again', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const base = transport.calls.length
|
||||
const run = stream.startStream({ session_id: 'parent', query: 'spawn children', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = await nextCall(base + 1)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', assistant_message_id: 'answer-1' }) })
|
||||
post.reject(new Error('connection reset'))
|
||||
await new Promise(r => setTimeout(r, 20))
|
||||
stream.stopStream()
|
||||
await run
|
||||
await new Promise(r => setTimeout(r, 1050))
|
||||
assert.equal(transport.calls.length, base + 1)
|
||||
assert.equal(stream.isStreaming.value, false)
|
||||
assert.equal(stream.error.value, null)
|
||||
})
|
||||
|
||||
test('EOF without complete attaches to the original message rather than declaring completion', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const base = transport.calls.length
|
||||
const run = stream.startStream({ session_id: 'parent', query: 'work', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = await nextCall(base + 1)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', assistant_message_id: 'answer-1' }) })
|
||||
try { post.options.onclose(); assert.fail('an incomplete EOF must request recovery') }
|
||||
catch (error) { post.reject(error) }
|
||||
await new Promise(r => setTimeout(r, 1050))
|
||||
const resumed = await nextCall(base + 2)
|
||||
assert.equal((resumed.options as any).method, 'GET')
|
||||
resumed.options.onmessage({ data: JSON.stringify({ response_type: 'complete' }) })
|
||||
resumed.options.onclose()
|
||||
resumed.resolve()
|
||||
await run
|
||||
assert.equal(stream.error.value, null)
|
||||
})
|
||||
|
||||
test('a new stream supersedes an old reconnect without being stopped or receiving old output', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const base = transport.calls.length
|
||||
const first = stream.startStream({ session_id: 'parent', query: 'old', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = await nextCall(base + 1)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', assistant_message_id: 'old-answer' }) })
|
||||
post.reject(new Error('server restarted'))
|
||||
await new Promise(r => setTimeout(r, 20))
|
||||
const second = stream.startStream({ session_id: 'another-session', query: 'new', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const current = await nextCall(base + 2)
|
||||
await first
|
||||
assert.equal(transport.calls.length, base + 2)
|
||||
assert.equal(current.options.signal.aborted, false)
|
||||
assert.equal(stream.isStreaming.value, true)
|
||||
assert.equal(stream.error.value, null)
|
||||
current.options.onmessage({ data: JSON.stringify({ response_type: 'complete' }) })
|
||||
current.options.onclose()
|
||||
current.resolve()
|
||||
await second
|
||||
})
|
||||
|
||||
test('a silent broken proxy connection times out and resumes by GET; heartbeats stay out of chat', async (t) => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const chunks: unknown[] = []
|
||||
stream.onChunk(value => chunks.push(value))
|
||||
const base = transport.calls.length
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] })
|
||||
const run = stream.startStream({ session_id: 'parent', query: 'work', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = transport.calls[base]
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', assistant_message_id: 'answer-1' }) })
|
||||
t.mock.timers.tick(20000)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'heartbeat' }) })
|
||||
assert.equal(chunks.length, 1)
|
||||
t.mock.timers.tick(20000)
|
||||
assert.equal(post.options.signal.aborted, false)
|
||||
t.mock.timers.tick(10001)
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve()
|
||||
assert.equal(post.options.signal.aborted, true)
|
||||
t.mock.timers.tick(1000)
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve()
|
||||
const resumed = transport.calls[base + 1]
|
||||
assert.ok(resumed)
|
||||
assert.equal((resumed.options as any).method, 'GET')
|
||||
resumed.options.onmessage({ data: JSON.stringify({ response_type: 'complete' }) })
|
||||
resumed.options.onclose()
|
||||
resumed.resolve()
|
||||
await run
|
||||
assert.equal(stream.isStreaming.value, false)
|
||||
assert.equal(stream.error.value, null)
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { del, get, getDown, postUpload } from '@/utils/request';
|
||||
|
||||
export type TemporaryAttachmentStatus = 'uploaded' | 'processing' | 'ready' | 'failed';
|
||||
|
||||
export interface TemporaryAttachment {
|
||||
id: string;
|
||||
session_id: string;
|
||||
file_name: string;
|
||||
file_type: string;
|
||||
file_size: number;
|
||||
mime_type?: string;
|
||||
status: TemporaryAttachmentStatus;
|
||||
token_count: number;
|
||||
chunk_count: number;
|
||||
image_refs?: Array<{ original_ref?: string; url: string; mime_type?: string }>;
|
||||
error_message?: string;
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
interface AttachmentResponse {
|
||||
success: boolean;
|
||||
data: TemporaryAttachment;
|
||||
}
|
||||
|
||||
export function uploadTemporaryAttachment(
|
||||
sessionId: string,
|
||||
file: File,
|
||||
agentId?: string,
|
||||
agentSourceTenantId?: string,
|
||||
parserEngine?: string,
|
||||
onProgress?: (percent: number) => void,
|
||||
): Promise<AttachmentResponse> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (agentId) form.append('agent_id', agentId);
|
||||
if (agentSourceTenantId) form.append('agent_source_tenant_id', agentSourceTenantId);
|
||||
if (parserEngine) form.append('parser_engine', parserEngine);
|
||||
return postUpload(
|
||||
`/api/v1/sessions/${sessionId}/attachments`,
|
||||
form,
|
||||
(event) => {
|
||||
if (event.total) onProgress?.(Math.round((event.loaded * 100) / event.total));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function getTemporaryAttachment(sessionId: string, attachmentId: string): Promise<AttachmentResponse> {
|
||||
return get(`/api/v1/sessions/${sessionId}/attachments/${attachmentId}`);
|
||||
}
|
||||
|
||||
export function previewTemporaryAttachment(sessionId: string, attachmentId: string): Promise<Blob> {
|
||||
return getDown(`/api/v1/sessions/${sessionId}/attachments/${attachmentId}/preview`);
|
||||
}
|
||||
|
||||
export function deleteTemporaryAttachment(sessionId: string, attachmentId: string): Promise<void> {
|
||||
return del(`/api/v1/sessions/${sessionId}/attachments/${attachmentId}`);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Chunker debug / preview API. Single endpoint that runs the adaptive
|
||||
// chunker over a sample text without touching DB or embeddings. Used by
|
||||
// the KB editor debug panel.
|
||||
|
||||
import { post } from '../../utils/request'
|
||||
import type {
|
||||
PreviewChunkingRequest,
|
||||
PreviewChunkingResponse
|
||||
} from '../../types/chunker'
|
||||
|
||||
export function previewChunking(
|
||||
body: PreviewChunkingRequest
|
||||
): Promise<{ success: boolean; data: PreviewChunkingResponse }> {
|
||||
return post('/api/v1/chunker/preview', body)
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { get, post, put, del } from '../../utils/request'
|
||||
|
||||
// --- Types ---
|
||||
|
||||
export interface DataSource {
|
||||
id: string
|
||||
tenant_id: number
|
||||
knowledge_base_id: string
|
||||
name: string
|
||||
type: string
|
||||
config: any
|
||||
sync_schedule: string
|
||||
sync_mode: 'incremental' | 'full'
|
||||
status: 'active' | 'paused' | 'error'
|
||||
conflict_strategy: 'overwrite' | 'skip'
|
||||
sync_deletions: boolean
|
||||
last_sync_at: string | null
|
||||
last_sync_result: any
|
||||
error_message: string
|
||||
// Single-field "credentials" map from the main response — DataSource
|
||||
// credentials are a per-connector atomic set.
|
||||
credentials?: { credentials: { configured: boolean } }
|
||||
created_at: string
|
||||
updated_at: string
|
||||
latest_sync_log?: SyncLog
|
||||
}
|
||||
|
||||
/**
|
||||
* One user-facing failure sample. The backend sends a stable i18n `code`
|
||||
* (+ interpolation `params`) so the UI localises it to the viewer's language;
|
||||
* `message` is a fallback when no i18n key exists (old logs decode into it).
|
||||
*/
|
||||
export interface SyncItemError {
|
||||
title?: string
|
||||
code?: string
|
||||
params?: Record<string, string>
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface SyncResultDetail {
|
||||
total?: number
|
||||
created?: number
|
||||
updated?: number
|
||||
deleted?: number
|
||||
skipped?: number
|
||||
failed?: number
|
||||
/** Per-item failure samples (capped); localised in the sync-log drawer. */
|
||||
errors?: SyncItemError[]
|
||||
}
|
||||
|
||||
export interface SyncLog {
|
||||
id: string
|
||||
data_source_id: string
|
||||
status: 'running' | 'success' | 'partial' | 'failed' | 'canceled'
|
||||
started_at: string
|
||||
finished_at: string | null
|
||||
items_total: number
|
||||
items_created: number
|
||||
items_updated: number
|
||||
items_deleted: number
|
||||
items_skipped: number
|
||||
items_failed: number
|
||||
error_message: string
|
||||
result?: SyncResultDetail
|
||||
}
|
||||
|
||||
export interface ConnectorMeta {
|
||||
type: string
|
||||
name: string
|
||||
description: string
|
||||
icon: string
|
||||
priority: number
|
||||
auth_type: string
|
||||
capabilities: string[]
|
||||
}
|
||||
|
||||
export interface Resource {
|
||||
external_id: string
|
||||
name: string
|
||||
type: string
|
||||
description: string
|
||||
url: string
|
||||
parent_id?: string
|
||||
has_children?: boolean
|
||||
/** Connector-specific hints, e.g. Confluence Cloud's top-level-container limitation. */
|
||||
metadata?: Record<string, any>
|
||||
}
|
||||
|
||||
// --- API calls ---
|
||||
|
||||
export function getConnectorTypes() {
|
||||
return get('/api/v1/datasource/types')
|
||||
}
|
||||
|
||||
export function listDataSources(kbId: string) {
|
||||
return get(`/api/v1/datasource?kb_id=${encodeURIComponent(kbId)}`)
|
||||
}
|
||||
|
||||
export function getDataSource(id: string) {
|
||||
return get(`/api/v1/datasource/${id}`)
|
||||
}
|
||||
|
||||
export function createDataSource(data: Partial<DataSource>) {
|
||||
return post('/api/v1/datasource', data)
|
||||
}
|
||||
|
||||
export function updateDataSource(id: string, data: Partial<DataSource>) {
|
||||
return put(`/api/v1/datasource/${id}`, data)
|
||||
}
|
||||
|
||||
export function deleteDataSource(id: string) {
|
||||
return del(`/api/v1/datasource/${id}`)
|
||||
}
|
||||
|
||||
export function validateConnection(id: string) {
|
||||
return post(`/api/v1/datasource/${id}/validate`, {})
|
||||
}
|
||||
|
||||
// Validate credentials without persisting (during creation or credential replacement).
|
||||
export function validateCredentials(type: string, credentials: Record<string, any>) {
|
||||
return post('/api/v1/datasource/validate-credentials', { type, credentials })
|
||||
}
|
||||
|
||||
// listResources lists selectable resources for a data source. Pass parentId to
|
||||
// lazily load the direct children of a resource (e.g. expanding a Feishu wiki
|
||||
// space/node), which avoids traversing the whole tree up front.
|
||||
export function listResources(id: string, parentId?: string) {
|
||||
const query = parentId ? `?parent_id=${encodeURIComponent(parentId)}` : ''
|
||||
return get(`/api/v1/datasource/${id}/resources${query}`, { timeout: 120000 })
|
||||
}
|
||||
|
||||
// resolveResourceAncestors returns the ExternalIDs of every parent that must be
|
||||
// expanded to reveal the given (possibly deeply nested) selections in a lazily
|
||||
// loaded picker. Used when editing a data source to restore an existing selection.
|
||||
export function resolveResourceAncestors(id: string, resourceIds: string[]) {
|
||||
return post(`/api/v1/datasource/${id}/resource-ancestors`, { resource_ids: resourceIds }, { timeout: 120000 })
|
||||
}
|
||||
|
||||
export function triggerSync(id: string) {
|
||||
return post(`/api/v1/datasource/${id}/sync`, {})
|
||||
}
|
||||
|
||||
export function pauseDataSource(id: string) {
|
||||
return post(`/api/v1/datasource/${id}/pause`, {})
|
||||
}
|
||||
|
||||
export function resumeDataSource(id: string) {
|
||||
return post(`/api/v1/datasource/${id}/resume`, {})
|
||||
}
|
||||
|
||||
export function getSyncLogs(id: string, limit = 20, offset = 0) {
|
||||
return get(`/api/v1/datasource/${id}/logs?limit=${limit}&offset=${offset}`)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Data source credential subresource. Unlike the other three resources,
|
||||
// DataSource exposes a single logical field "credentials" because connector
|
||||
// auth is a per-connector atomic map. See internal/handler/dto/datasource.go.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
export interface DataSourceCredentialsResponse {
|
||||
fields: {
|
||||
credentials: { configured: boolean }
|
||||
}
|
||||
}
|
||||
|
||||
export async function putDataSourceCredentials(
|
||||
id: string,
|
||||
credentials: Record<string, unknown>,
|
||||
): Promise<DataSourceCredentialsResponse> {
|
||||
const response: any = await put(`/api/v1/datasource/${id}/credentials`, { credentials })
|
||||
return (response.data ?? response) as DataSourceCredentialsResponse
|
||||
}
|
||||
|
||||
export async function deleteDataSourceCredentials(id: string): Promise<void> {
|
||||
await del(`/api/v1/datasource/${id}/credentials/credentials`)
|
||||
}
|
||||
@@ -0,0 +1,790 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
import { resolveEmbedBaseUrl } from '@/utils/embedBaseUrl'
|
||||
|
||||
export interface EmbedChannel {
|
||||
id: string
|
||||
tenant_id: number
|
||||
agent_id: string
|
||||
name: string
|
||||
enabled: boolean
|
||||
allowed_origins: string[]
|
||||
welcome_message: string
|
||||
rate_limit_per_minute: number
|
||||
rate_limit_per_day?: number
|
||||
primary_color?: string
|
||||
page_title?: string
|
||||
header_title_mode?: HeaderTitleMode
|
||||
show_suggested_questions?: boolean
|
||||
widget_position?: WidgetPosition
|
||||
allow_web_search?: boolean
|
||||
allow_file_upload?: boolean
|
||||
default_locale?: string
|
||||
webhook_url?: string
|
||||
has_webhook_secret?: boolean
|
||||
publish_token?: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface EmbedChannelPublicConfig {
|
||||
channel_id: string
|
||||
name: string
|
||||
display_title?: string
|
||||
knowledge_base_ids?: string[]
|
||||
agent_id: string
|
||||
agent_name?: string
|
||||
agent_avatar?: string
|
||||
welcome_message: string
|
||||
primary_color?: string
|
||||
page_title?: string
|
||||
header_title_mode?: HeaderTitleMode
|
||||
show_suggested_questions?: boolean
|
||||
widget_position?: WidgetPosition
|
||||
allow_web_search?: boolean
|
||||
allow_file_upload?: boolean
|
||||
agent_web_search_enabled?: boolean
|
||||
agent_image_upload_enabled?: boolean
|
||||
default_locale?: string
|
||||
}
|
||||
|
||||
export type EmbedLocaleTag = 'zh-CN' | 'zh-TW' | 'en-US' | 'ko-KR' | 'ja-JP' | 'ru-RU' | ''
|
||||
|
||||
export interface EmbedChannelStats {
|
||||
session_count: number
|
||||
}
|
||||
|
||||
export type HeaderTitleMode = 'channel' | 'session'
|
||||
export type WidgetPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'
|
||||
|
||||
/** Prefix of short-lived embed session tokens minted by the backend. */
|
||||
export const EMBED_SESSION_TOKEN_PREFIX = 'ems_'
|
||||
|
||||
/** localStorage key prefix for persisted embed chat sessions (per channel). */
|
||||
export const EMBED_CHAT_SESSION_STORAGE_PREFIX = 'academy-embed-session:'
|
||||
|
||||
/** localStorage key prefix for anonymous embed visitor ids (per channel). */
|
||||
export const EMBED_VISITOR_STORAGE_PREFIX = 'academy-embed-visitor:'
|
||||
|
||||
export function embedVisitorStorageKey(channelId: string): string {
|
||||
return `${EMBED_VISITOR_STORAGE_PREFIX}${channelId}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成符合 UUID v4 格式的随机 ID。
|
||||
* 优先使用 crypto.randomUUID(),在不支持的浏览器中回退到 crypto.getRandomValues(),
|
||||
* 最终兜底使用 Math.random()。
|
||||
*/
|
||||
export function generateUUID(): string {
|
||||
// 优先使用原生 API(HTTPS 环境下可用)
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
|
||||
// 回退:使用 crypto.getRandomValues()
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
|
||||
const buf = new Uint8Array(16)
|
||||
crypto.getRandomValues(buf)
|
||||
// 设置 UUID v4 标志位
|
||||
buf[6] = (buf[6] & 0x0f) | 0x40
|
||||
buf[8] = (buf[8] & 0x3f) | 0x80
|
||||
const hex = Array.from(buf, (b) => b.toString(16).padStart(2, '0'))
|
||||
return [
|
||||
hex[0], hex[1], hex[2], hex[3], '-',
|
||||
hex[4], hex[5], '-',
|
||||
hex[6], hex[7], '-',
|
||||
hex[8], hex[9], '-',
|
||||
hex[10], hex[11], hex[12], hex[13], hex[14], hex[15],
|
||||
].join('')
|
||||
}
|
||||
|
||||
// 最终兜底:Math.random()(随机性较弱,仅保证格式正确)
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
||||
const r = (Math.random() * 16) | 0
|
||||
const v = c === 'x' ? r : (r & 0x3) | 0x8
|
||||
return v.toString(16)
|
||||
})
|
||||
}
|
||||
|
||||
/** Stable anonymous id for this browser on the given channel. */
|
||||
export function getOrCreateEmbedVisitorId(channelId: string): string {
|
||||
if (typeof localStorage === 'undefined' || !channelId) {
|
||||
return generateUUID()
|
||||
}
|
||||
const key = embedVisitorStorageKey(channelId)
|
||||
try {
|
||||
const existing = localStorage.getItem(key)?.trim()
|
||||
if (existing) return existing
|
||||
const id = generateUUID()
|
||||
localStorage.setItem(key, id)
|
||||
return id
|
||||
} catch {
|
||||
return generateUUID()
|
||||
}
|
||||
}
|
||||
|
||||
export function embedChatSessionStorageKey(channelId: string): string {
|
||||
return `${EMBED_CHAT_SESSION_STORAGE_PREFIX}${channelId}`
|
||||
}
|
||||
|
||||
/** Drop a persisted embed chat session so the next load starts fresh. */
|
||||
export function clearEmbedStoredChatSession(channelId: string): void {
|
||||
if (typeof localStorage === 'undefined') return
|
||||
try {
|
||||
localStorage.removeItem(embedChatSessionStorageKey(channelId))
|
||||
} catch {
|
||||
// localStorage may be unavailable in private mode.
|
||||
}
|
||||
}
|
||||
|
||||
/** Clear a stored chat session when it was created under a different agent binding. */
|
||||
export function clearEmbedStoredChatSessionIfAgentMismatch(channelId: string, agentId: string): void {
|
||||
if (typeof localStorage === 'undefined' || !channelId || !agentId) return
|
||||
try {
|
||||
const raw = localStorage.getItem(embedChatSessionStorageKey(channelId))
|
||||
if (!raw) return
|
||||
const parsed = JSON.parse(raw) as { agentId?: string }
|
||||
if (parsed?.agentId && parsed.agentId !== agentId) {
|
||||
localStorage.removeItem(embedChatSessionStorageKey(channelId))
|
||||
}
|
||||
} catch {
|
||||
// Malformed entry — remove so bootstrap can recover.
|
||||
localStorage.removeItem(embedChatSessionStorageKey(channelId))
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a token is already a short-lived session token (secure mode). */
|
||||
export function isEmbedSessionToken(token: string): boolean {
|
||||
return typeof token === 'string' && token.trim().startsWith(EMBED_SESSION_TOKEN_PREFIX)
|
||||
}
|
||||
|
||||
export async function listEmbedChannels(agentId: string) {
|
||||
return get<{ success: boolean; data: EmbedChannel[] }>(`/api/v1/agents/${agentId}/embed-channels`)
|
||||
}
|
||||
|
||||
export async function listAllEmbedChannels() {
|
||||
return get<{ success: boolean; data: EmbedChannel[] }>('/api/v1/embed-channels')
|
||||
}
|
||||
|
||||
export async function createEmbedChannel(agentId: string, data: Partial<EmbedChannel>) {
|
||||
return post<{ success: boolean; data: EmbedChannel }>(`/api/v1/agents/${agentId}/embed-channels`, data)
|
||||
}
|
||||
|
||||
export async function getEmbedChannel(channelId: string) {
|
||||
return get<{ success: boolean; data: EmbedChannel }>(`/api/v1/embed-channels/${channelId}`)
|
||||
}
|
||||
|
||||
export async function updateEmbedChannel(channelId: string, data: Partial<EmbedChannel>) {
|
||||
return put<{ success: boolean; data: EmbedChannel }>(`/api/v1/embed-channels/${channelId}`, data)
|
||||
}
|
||||
|
||||
export async function deleteEmbedChannel(channelId: string) {
|
||||
return del(`/api/v1/embed-channels/${channelId}`)
|
||||
}
|
||||
|
||||
export async function rotateEmbedToken(channelId: string) {
|
||||
return post<{ success: boolean; data: EmbedChannel }>(`/api/v1/embed-channels/${channelId}/rotate-token`, {})
|
||||
}
|
||||
|
||||
/** Short-lived session token for management UI preview (JWT auth, no publish token needed). */
|
||||
export async function getEmbedChannelStats(channelId: string) {
|
||||
return get<{ success: boolean; data: EmbedChannelStats }>(
|
||||
`/api/v1/embed-channels/${channelId}/stats`,
|
||||
)
|
||||
}
|
||||
|
||||
export async function issueEmbedPreviewSession(channelId: string) {
|
||||
return post<{ success: boolean; data: { session_token: string; expires_in: number } }>(
|
||||
`/api/v1/embed-channels/${channelId}/preview-session`,
|
||||
{},
|
||||
)
|
||||
}
|
||||
|
||||
export interface SuggestedQuestion {
|
||||
question: string
|
||||
source?: string
|
||||
}
|
||||
|
||||
export interface EmbedMessageSuggestionItem {
|
||||
id: string
|
||||
text: string
|
||||
category?: string
|
||||
source: string
|
||||
}
|
||||
|
||||
export interface EmbedMessageSuggestionSet {
|
||||
id: string
|
||||
status: 'generating' | 'ready' | 'suppressed' | 'failed'
|
||||
allow_regenerate: boolean
|
||||
questions: EmbedMessageSuggestionItem[]
|
||||
}
|
||||
|
||||
export async function getEmbedChunkById(channelId: string, token: string, chunkId: string) {
|
||||
return get<{ success: boolean; data: { content?: string } }>(
|
||||
`/api/v1/embed/${channelId}/chunks/${chunkId}`,
|
||||
{ headers: { Authorization: `Embed ${token}` } },
|
||||
)
|
||||
}
|
||||
|
||||
export async function getEmbedSuggestedQuestions(channelId: string, token: string, limit?: number) {
|
||||
// Omit limit to let the channel agent's configured starter count apply.
|
||||
const qs = typeof limit === 'number' && limit > 0 ? `?limit=${limit}` : ''
|
||||
return get<{ success: boolean; data: { questions: SuggestedQuestion[] } }>(
|
||||
`/api/v1/embed/${channelId}/suggested-questions${qs}`,
|
||||
{ headers: { Authorization: `Embed ${token}` } },
|
||||
)
|
||||
}
|
||||
|
||||
export async function ensureEmbedMessageSuggestions(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
messageId: string,
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
regenerate = false,
|
||||
) {
|
||||
return post<{ success: boolean; data: EmbedMessageSuggestionSet }>(
|
||||
`/api/v1/embed/${channelId}/sessions/${sessionId}/messages/${messageId}/suggestions`,
|
||||
{ regenerate },
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
}
|
||||
|
||||
export async function getEmbedMessageSuggestions(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
messageId: string,
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
) {
|
||||
return get<{ success: boolean; data: EmbedMessageSuggestionSet }>(
|
||||
`/api/v1/embed/${channelId}/sessions/${sessionId}/messages/${messageId}/suggestions`,
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
}
|
||||
|
||||
export async function recordEmbedMessageSuggestionEvent(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
suggestionSetId: string,
|
||||
eventType: 'impression' | 'click' | 'dismiss',
|
||||
questionId = '',
|
||||
) {
|
||||
return post(
|
||||
`/api/v1/embed/${channelId}/sessions/${sessionId}/suggestion-events`,
|
||||
{ suggestion_set_id: suggestionSetId, question_id: questionId, event_type: eventType },
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
}
|
||||
|
||||
export async function getEmbedConfig(channelId: string, token: string) {
|
||||
return get<{ success: boolean; data: EmbedChannelPublicConfig }>(
|
||||
`/api/v1/embed/${channelId}/config`,
|
||||
{ headers: { Authorization: `Embed ${token}` } },
|
||||
)
|
||||
}
|
||||
|
||||
export async function createEmbedSession(channelId: string, token: string) {
|
||||
return post<{ success: boolean; data: { id: string; sig: string } }>(
|
||||
`/api/v1/embed/${channelId}/sessions`,
|
||||
{},
|
||||
{ headers: { Authorization: `Embed ${token}` } },
|
||||
)
|
||||
}
|
||||
|
||||
export async function exchangeEmbedSession(channelId: string, publishToken: string) {
|
||||
return post<{ success: boolean; data: { session_token: string; expires_in: number } }>(
|
||||
`/api/v1/embed/${channelId}/exchange`,
|
||||
{},
|
||||
{ headers: { Authorization: `Embed ${publishToken}` } },
|
||||
)
|
||||
}
|
||||
|
||||
export async function stopEmbedSession(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
messageId: string,
|
||||
sessionSig: string,
|
||||
) {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Embed ${token}`,
|
||||
'X-Embed-Session': sessionSig,
|
||||
}
|
||||
return post(`/api/v1/embed/${channelId}/sessions/${sessionId}/stop`, { message_id: messageId }, { headers })
|
||||
}
|
||||
|
||||
function embedSessionHeaders(token: string, sessionSig: string, visitorId?: string): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Embed ${token}`,
|
||||
'X-Embed-Session': sessionSig,
|
||||
}
|
||||
const visitor = visitorId?.trim()
|
||||
if (visitor) headers['X-Embed-Visitor'] = visitor
|
||||
return headers
|
||||
}
|
||||
|
||||
export async function resolveEmbedMCPOAuth(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
pendingId: string,
|
||||
body: { service_id: string; decision?: 'authorize' | 'cancel' },
|
||||
): Promise<void> {
|
||||
await post(
|
||||
`/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}`,
|
||||
body,
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
}
|
||||
|
||||
export async function cancelEmbedMCPOAuth(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
pendingId: string,
|
||||
): Promise<void> {
|
||||
await post(
|
||||
`/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}/cancel`,
|
||||
{},
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
}
|
||||
|
||||
export async function getEmbedMCPOAuthAuthorizeURL(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
serviceId: string,
|
||||
body: { redirect_uri: string; frontend_redirect?: string },
|
||||
): Promise<{ authorizationUrl: string; authorizationAttempt: string }> {
|
||||
const response: any = await post(
|
||||
`/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-services/${encodeURIComponent(serviceId)}/oauth/authorize-url`,
|
||||
body,
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
const data = response.data ?? response
|
||||
return {
|
||||
authorizationUrl: data?.authorization_url ?? '',
|
||||
authorizationAttempt: data?.authorization_attempt ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
export async function getEmbedMCPOAuthStatus(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
serviceId: string,
|
||||
authorizationAttempt?: string,
|
||||
): Promise<boolean> {
|
||||
const query = authorizationAttempt
|
||||
? `?authorization_attempt=${encodeURIComponent(authorizationAttempt)}`
|
||||
: ''
|
||||
const response: any = await get(
|
||||
`/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-services/${encodeURIComponent(serviceId)}/oauth/status${query}`,
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
return Boolean((response.data ?? response)?.authorized)
|
||||
}
|
||||
|
||||
export async function resolveEmbedToolApproval(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
pendingId: string,
|
||||
body: { decision: 'approve' | 'reject'; modified_args?: Record<string, unknown>; reason?: string; allow_in_session?: boolean },
|
||||
): Promise<{ resumed: boolean }> {
|
||||
const res: any = await post(
|
||||
`/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/tool-approvals/${encodeURIComponent(pendingId)}`,
|
||||
body,
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
return { resumed: Boolean(res?.resumed) }
|
||||
}
|
||||
|
||||
export async function resolveEmbedAgentPrompt(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
promptId: string,
|
||||
kind: string,
|
||||
response: Record<string, unknown>,
|
||||
): Promise<{ resumed: boolean }> {
|
||||
const res: any = await post(
|
||||
`/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(promptId)}`,
|
||||
{ kind, response },
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
return { resumed: Boolean(res?.resumed) }
|
||||
}
|
||||
|
||||
export async function getEmbedMessageList(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
limit: number,
|
||||
beforeTime?: string,
|
||||
sig?: string,
|
||||
) {
|
||||
const params = new URLSearchParams({ limit: String(limit) })
|
||||
if (beforeTime) {
|
||||
params.set('before_time', beforeTime)
|
||||
}
|
||||
const headers: Record<string, string> = { Authorization: `Embed ${token}` }
|
||||
// Signed session handle — sent as a header so it never lands in URL/access logs.
|
||||
if (sig) headers['X-Embed-Session'] = sig
|
||||
return get<{ success: boolean; data: unknown[] }>(
|
||||
`/api/v1/embed/${channelId}/messages/${sessionId}/load?${params.toString()}`,
|
||||
{ headers },
|
||||
)
|
||||
}
|
||||
|
||||
const EMBED_MSG_SOURCE = 'academy-embed'
|
||||
const EMBED_HOST_SOURCE = 'academy-host'
|
||||
|
||||
// The exact parent origin, learned from the first trusted host message
|
||||
// (trust-on-first-use). Once known, every inbound/outbound message is pinned to
|
||||
// it so conversation content is never broadcast to an unexpected window.
|
||||
let verifiedParentOrigin = ''
|
||||
|
||||
function referrerParentOrigin(): string {
|
||||
if (window.parent === window) return ''
|
||||
try {
|
||||
if (document.referrer) {
|
||||
return new URL(document.referrer).origin
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed referrer
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** Best-known parent origin: verified handshake first, then referrer. */
|
||||
function knownParentOrigin(): string {
|
||||
return verifiedParentOrigin || referrerParentOrigin()
|
||||
}
|
||||
|
||||
function isTrustedParentMessage(event: MessageEvent): boolean {
|
||||
if (window.parent === window) return false
|
||||
if (event.source !== window.parent) return false
|
||||
if (!event.data || event.data.source !== EMBED_HOST_SOURCE) return false
|
||||
if (typeof event.origin !== 'string' || event.origin === 'null') return false
|
||||
const expected = knownParentOrigin()
|
||||
if (expected) {
|
||||
if (event.origin !== expected) return false
|
||||
} else {
|
||||
// First trusted handshake with no referrer hint: pin to this origin.
|
||||
verifiedParentOrigin = event.origin
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Post a message to the host page.
|
||||
* `sensitive` payloads (conversation content) are dropped when the parent
|
||||
* origin is unknown rather than broadcast to '*'. Non-sensitive handshake
|
||||
* messages (bootstrap_request/ready) may fall back to '*' so token handoff can
|
||||
* still bootstrap when the referrer is stripped.
|
||||
*/
|
||||
function postToParent(payload: Record<string, unknown>, opts?: { sensitive?: boolean }) {
|
||||
if (window.parent === window) return
|
||||
const target = knownParentOrigin()
|
||||
if (!target) {
|
||||
if (opts?.sensitive) return
|
||||
window.parent.postMessage({ source: EMBED_MSG_SOURCE, ...payload }, '*')
|
||||
return
|
||||
}
|
||||
window.parent.postMessage({ source: EMBED_MSG_SOURCE, ...payload }, target)
|
||||
}
|
||||
|
||||
/** Notify the parent page that the embed widget is ready. */
|
||||
export function postEmbedReady(channelId: string) {
|
||||
postToParent({ type: 'ready', channel_id: channelId })
|
||||
}
|
||||
|
||||
/** Request a publish token from the parent host page. */
|
||||
export function postEmbedBootstrapRequest(channelId: string) {
|
||||
postToParent({ type: 'bootstrap_request', channel_id: channelId })
|
||||
}
|
||||
|
||||
/** Notify the parent page when a user message is sent. */
|
||||
export function postEmbedMessageSent(channelId: string, sessionId: string, query: string) {
|
||||
postToParent(
|
||||
{
|
||||
type: 'message_sent',
|
||||
channel_id: channelId,
|
||||
session_id: sessionId,
|
||||
query,
|
||||
},
|
||||
{ sensitive: true },
|
||||
)
|
||||
}
|
||||
|
||||
/** Relay a chat event to the channel webhook (server-side, best-effort). */
|
||||
export function relayEmbedWebhookEvent(
|
||||
channelId: string,
|
||||
token: string,
|
||||
sessionId: string,
|
||||
sessionSig: string,
|
||||
body: { type: 'message_sent' | 'message_received'; query?: string; content?: string },
|
||||
) {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Embed ${token}`,
|
||||
'X-Embed-Session': sessionSig,
|
||||
}
|
||||
void post(
|
||||
`/api/v1/embed/${channelId}/sessions/${sessionId}/events`,
|
||||
{ type: body.type, session_id: sessionId, query: body.query, content: body.content },
|
||||
{ headers },
|
||||
).catch(() => {
|
||||
// Webhook relay must not block chat.
|
||||
})
|
||||
}
|
||||
|
||||
/** Notify the parent page when an assistant reply completes. */
|
||||
export function postEmbedMessageReceived(channelId: string, sessionId: string, content: string) {
|
||||
postToParent(
|
||||
{
|
||||
type: 'message_received',
|
||||
channel_id: channelId,
|
||||
session_id: sessionId,
|
||||
content,
|
||||
},
|
||||
{ sensitive: true },
|
||||
)
|
||||
}
|
||||
|
||||
export function parseEmbedTokenFromLocation(): string {
|
||||
const queryToken = new URLSearchParams(window.location.search).get('token')
|
||||
if (queryToken) return queryToken
|
||||
|
||||
const hash = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : ''
|
||||
if (!hash) return ''
|
||||
return new URLSearchParams(hash).get('token') || ''
|
||||
}
|
||||
|
||||
export function buildEmbedURL(
|
||||
channelId: string,
|
||||
token?: string,
|
||||
opts?: { locale?: string; refreshKey?: number; baseUrl?: string },
|
||||
) {
|
||||
const base = safeBaseUrl(opts?.baseUrl) || resolveEmbedBaseUrl()
|
||||
let path = `${base}/embed/${encodeURIComponent(channelId)}`
|
||||
const params = new URLSearchParams()
|
||||
if (opts?.locale?.trim()) params.set('locale', opts.locale.trim())
|
||||
if (opts?.refreshKey) params.set('r', String(opts.refreshKey))
|
||||
const qs = params.toString()
|
||||
if (qs) path += `?${qs}`
|
||||
if (token) path += `#token=${encodeURIComponent(token)}`
|
||||
return path
|
||||
}
|
||||
|
||||
/** Escape a value for safe interpolation inside an HTML double-quoted attribute. */
|
||||
function escapeHtmlAttr(value: string): string {
|
||||
return String(value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
}
|
||||
|
||||
/** Validate that a base URL is a well-formed http(s) origin; fall back otherwise. */
|
||||
function safeBaseUrl(raw?: string): string {
|
||||
const fallback = window.location.origin
|
||||
if (!raw) return fallback
|
||||
try {
|
||||
const u = new URL(raw, window.location.href)
|
||||
if (u.protocol !== 'http:' && u.protocol !== 'https:') return fallback
|
||||
return u.origin
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
export function buildEmbedSnippet(channelId: string, token?: string) {
|
||||
// A bare iframe has no token-handoff host, so the snippet must carry the
|
||||
// publish token in the URL hash, otherwise the embed page cannot bootstrap.
|
||||
const url = escapeHtmlAttr(buildEmbedURL(channelId, token))
|
||||
return `<iframe src="${url}" style="width:400px;height:600px;border:none;border-radius:12px" allow="clipboard-write"></iframe>`
|
||||
}
|
||||
|
||||
export function buildWidgetSnippet(
|
||||
channelId: string,
|
||||
token: string,
|
||||
opts?: { primaryColor?: string; title?: string; position?: WidgetPosition; baseUrl?: string },
|
||||
) {
|
||||
const base = safeBaseUrl(opts?.baseUrl)
|
||||
const position = opts?.position || 'bottom-right'
|
||||
const attrs = [
|
||||
`src="${escapeHtmlAttr(`${base}/academy-widget.js`)}"`,
|
||||
`data-channel="${escapeHtmlAttr(channelId)}"`,
|
||||
`data-token="${escapeHtmlAttr(token)}"`,
|
||||
`data-position="${escapeHtmlAttr(position)}"`,
|
||||
]
|
||||
if (opts?.primaryColor) attrs.push(`data-primary-color="${escapeHtmlAttr(opts.primaryColor)}"`)
|
||||
if (opts?.title) attrs.push(`data-title="${escapeHtmlAttr(opts.title)}"`)
|
||||
// Cross-origin embed: add data-sandbox="true" when using a dedicated embed subdomain.
|
||||
return `<script ${attrs.join('\n ')}></script>`
|
||||
}
|
||||
|
||||
/** Default placeholder for the integrator's own token-minting endpoint. */
|
||||
export const SECURE_TOKEN_ENDPOINT_PLACEHOLDER = 'https://your-backend.example.com/academy/embed-token'
|
||||
|
||||
/**
|
||||
* Secure-mode widget snippet: the page references an endpoint on the
|
||||
* integrator's own backend (data-token-endpoint) instead of carrying the
|
||||
* publish token. The publish token never reaches the browser.
|
||||
*/
|
||||
export function buildSecureWidgetSnippet(
|
||||
channelId: string,
|
||||
opts?: { primaryColor?: string; title?: string; position?: WidgetPosition; baseUrl?: string; tokenEndpoint?: string },
|
||||
) {
|
||||
const base = safeBaseUrl(opts?.baseUrl)
|
||||
const position = opts?.position || 'bottom-right'
|
||||
const endpoint = opts?.tokenEndpoint || SECURE_TOKEN_ENDPOINT_PLACEHOLDER
|
||||
const attrs = [
|
||||
`src="${escapeHtmlAttr(`${base}/academy-widget.js`)}"`,
|
||||
`data-channel="${escapeHtmlAttr(channelId)}"`,
|
||||
`data-token-endpoint="${escapeHtmlAttr(endpoint)}"`,
|
||||
`data-position="${escapeHtmlAttr(position)}"`,
|
||||
]
|
||||
if (opts?.primaryColor) attrs.push(`data-primary-color="${escapeHtmlAttr(opts.primaryColor)}"`)
|
||||
if (opts?.title) attrs.push(`data-title="${escapeHtmlAttr(opts.title)}"`)
|
||||
return `<script ${attrs.join('\n ')}></script>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-side reference (Node/Express) for the token-minting endpoint that
|
||||
* secure mode points at. The publish token stays on the server; the endpoint
|
||||
* exchanges it for a short-lived session token and returns that to the page.
|
||||
*/
|
||||
export function buildSecureServerNodeExample(channelId: string, opts?: { baseUrl?: string }) {
|
||||
const base = safeBaseUrl(opts?.baseUrl)
|
||||
const exchangeUrl = `${base}/api/v1/embed/${channelId}/exchange`
|
||||
return [
|
||||
`// Node/Express — keep ACADEMY_PUBLISH_TOKEN only on the server (env var).`,
|
||||
`app.get('/academy/embed-token', async (req, res) => {`,
|
||||
` // Only mint for logged-in visitors — e.g. session cookie or Bearer token.`,
|
||||
` const auth = req.headers.authorization || ''`,
|
||||
` const hasSession = Boolean(req.cookies?.session_id)`,
|
||||
` if (!hasSession && !auth.startsWith('Bearer ')) {`,
|
||||
` return res.status(401).json({ error: 'unauthorized' })`,
|
||||
` }`,
|
||||
` const r = await fetch('${exchangeUrl}', {`,
|
||||
` method: 'POST',`,
|
||||
` headers: {`,
|
||||
` Authorization: 'Embed ' + process.env.ACADEMY_PUBLISH_TOKEN,`,
|
||||
` Origin: 'https://your-site.example.com', // must match channel allowed_origins`,
|
||||
` },`,
|
||||
` })`,
|
||||
` const body = await r.json()`,
|
||||
` if (!body?.data?.session_token) return res.status(502).json({ error: 'mint failed' })`,
|
||||
` res.json({ token: body.data.session_token, expiresIn: body.data.expires_in })`,
|
||||
`})`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function buildSecureServerGoExample(channelId: string, opts?: { baseUrl?: string }) {
|
||||
const base = safeBaseUrl(opts?.baseUrl)
|
||||
const exchangeUrl = `${base}/api/v1/embed/${channelId}/exchange`
|
||||
return [
|
||||
`// Go net/http — keep ACADEMY_PUBLISH_TOKEN only on the server (env var).`,
|
||||
`func embedTokenHandler(w http.ResponseWriter, r *http.Request) {`,
|
||||
` if r.Header.Get("Authorization") == "" && r.Header.Get("Cookie") == "" {`,
|
||||
` http.Error(w, \`{"error":"unauthorized"}\`, http.StatusUnauthorized)`,
|
||||
` return`,
|
||||
` }`,
|
||||
` req, _ := http.NewRequest(http.MethodPost, "${exchangeUrl}", nil)`,
|
||||
` req.Header.Set("Authorization", "Embed "+os.Getenv("ACADEMY_PUBLISH_TOKEN"))`,
|
||||
` req.Header.Set("Origin", "https://your-site.example.com") // must match channel allowed_origins`,
|
||||
` resp, err := http.DefaultClient.Do(req)`,
|
||||
` if err != nil || resp.StatusCode >= 300 {`,
|
||||
` http.Error(w, \`{"error":"mint failed"}\`, http.StatusBadGateway)`,
|
||||
` return`,
|
||||
` }`,
|
||||
` defer resp.Body.Close()`,
|
||||
` var body struct { Data struct { SessionToken string \`json:"session_token"\` ExpiresIn int \`json:"expires_in"\` } \`json:"data"\` }`,
|
||||
` if json.NewDecoder(resp.Body).Decode(&body) != nil || body.Data.SessionToken == "" {`,
|
||||
` http.Error(w, \`{"error":"mint failed"}\`, http.StatusBadGateway)`,
|
||||
` return`,
|
||||
` }`,
|
||||
` w.Header().Set("Content-Type", "application/json")`,
|
||||
` json.NewEncoder(w).Encode(map[string]any{"token": body.Data.SessionToken, "expiresIn": body.Data.ExpiresIn})`,
|
||||
`}`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** @deprecated Use buildSecureServerNodeExample */
|
||||
export function buildSecureServerExample(channelId: string, opts?: { baseUrl?: string }) {
|
||||
return buildSecureServerNodeExample(channelId, opts)
|
||||
}
|
||||
|
||||
export function buildSecureServerExamples(channelId: string, opts?: { baseUrl?: string }) {
|
||||
return [
|
||||
buildSecureServerNodeExample(channelId, opts),
|
||||
'',
|
||||
buildSecureServerGoExample(channelId, opts),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** Listen for context injected by the parent page (embed host). */
|
||||
export function onEmbedHostContext(handler: (payload: Record<string, unknown>) => void) {
|
||||
const listener = (e: MessageEvent) => {
|
||||
if (!isTrustedParentMessage(e) || e.data.type !== 'set_context') return
|
||||
handler(e.data.payload || {})
|
||||
}
|
||||
window.addEventListener('message', listener)
|
||||
return () => window.removeEventListener('message', listener)
|
||||
}
|
||||
|
||||
/** Listen for a publish token provided by the parent host page. */
|
||||
export function onEmbedHostToken(handler: (token: string, channelId?: string) => void) {
|
||||
const listener = (e: MessageEvent) => {
|
||||
if (!isTrustedParentMessage(e) || e.data.type !== 'provide_token') return
|
||||
const token = String(e.data.token || '').trim()
|
||||
if (!token) return
|
||||
handler(token, e.data.channel_id)
|
||||
}
|
||||
window.addEventListener('message', listener)
|
||||
return () => window.removeEventListener('message', listener)
|
||||
}
|
||||
|
||||
/** Listen for locale changes from the parent host page. */
|
||||
export function onEmbedHostLocale(handler: (locale: string) => void) {
|
||||
const listener = (e: MessageEvent) => {
|
||||
if (!isTrustedParentMessage(e) || e.data.type !== 'set_locale') return
|
||||
const locale = String(e.data.payload?.locale || e.data.locale || '').trim()
|
||||
if (!locale) return
|
||||
handler(locale)
|
||||
}
|
||||
window.addEventListener('message', listener)
|
||||
return () => window.removeEventListener('message', listener)
|
||||
}
|
||||
|
||||
/** Listen for a pre-filled query from the parent host page. */
|
||||
export function onEmbedHostOpenWithQuery(handler: (query: string) => void) {
|
||||
const listener = (e: MessageEvent) => {
|
||||
if (!isTrustedParentMessage(e) || e.data.type !== 'open_with_query') return
|
||||
const query = String(e.data.payload?.query || e.data.query || '').trim()
|
||||
if (!query) return
|
||||
handler(query)
|
||||
}
|
||||
window.addEventListener('message', listener)
|
||||
return () => window.removeEventListener('message', listener)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { del, get, put } from '@/utils/request'
|
||||
|
||||
/**
|
||||
* Which value an execution would actually use for one variable.
|
||||
*
|
||||
* `unset` means nothing is stored anywhere, `workspace` means an admin filled
|
||||
* it in for everyone, `user` means the caller filled in their own — which wins
|
||||
* over the workspace one for this caller only.
|
||||
*/
|
||||
export type EnvVarSource = 'unset' | 'workspace' | 'user'
|
||||
|
||||
/**
|
||||
* One variable as its owner may see it. There is deliberately no value field:
|
||||
* the endpoint reports what is missing, never what is stored.
|
||||
*/
|
||||
export interface EnvVarView {
|
||||
name: string
|
||||
description?: string
|
||||
required?: boolean
|
||||
source: EnvVarSource
|
||||
/** Present only for the caller's own value; a workspace value has no per-variable timestamp. */
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
/** One skill's declared credentials. */
|
||||
export interface SkillEnvGroup {
|
||||
skill_id: string
|
||||
skill_name: string
|
||||
/** SKILL.md one-liner; not the instruction body. */
|
||||
description?: string
|
||||
vars: EnvVarView[]
|
||||
}
|
||||
|
||||
/**
|
||||
* One sandbox config: the caller's own config-wide variables, injected into
|
||||
* every execution on it, plus the credentials its skills declared.
|
||||
*/
|
||||
export interface ConfigEnvGroup {
|
||||
sandbox_config_id: string
|
||||
sandbox_config_name: string
|
||||
description?: string
|
||||
vars: EnvVarView[]
|
||||
skills: SkillEnvGroup[]
|
||||
}
|
||||
|
||||
export function listMyEnvVars(): Promise<{ data: ConfigEnvGroup[] }> {
|
||||
return get('/api/v1/me/env-vars') as unknown as Promise<{ data: ConfigEnvGroup[] }>
|
||||
}
|
||||
|
||||
export function setMySkillEnv(
|
||||
skillId: string,
|
||||
name: string,
|
||||
value: string,
|
||||
): Promise<{ success: boolean }> {
|
||||
return put('/api/v1/me/env-vars/skill', { skill_id: skillId, name, value }) as unknown as Promise<{
|
||||
success: boolean
|
||||
}>
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the caller's own value, after which the workspace value (if any)
|
||||
* applies again. The scope and name travel in a JSON body rather than the query
|
||||
* string, matching the PUT above.
|
||||
*/
|
||||
export function deleteMySkillEnv(skillId: string, name: string): Promise<{ success: boolean }> {
|
||||
return del('/api/v1/me/env-vars/skill', { skill_id: skillId, name }) as unknown as Promise<{
|
||||
success: boolean
|
||||
}>
|
||||
}
|
||||
|
||||
export function setMySandboxEnv(
|
||||
configId: string,
|
||||
name: string,
|
||||
value: string,
|
||||
): Promise<{ success: boolean }> {
|
||||
return put('/api/v1/me/env-vars/sandbox', {
|
||||
sandbox_config_id: configId,
|
||||
name,
|
||||
value,
|
||||
}) as unknown as Promise<{ success: boolean }>
|
||||
}
|
||||
|
||||
export function deleteMySandboxEnv(configId: string, name: string): Promise<{ success: boolean }> {
|
||||
return del('/api/v1/me/env-vars/sandbox', {
|
||||
sandbox_config_id: configId,
|
||||
name,
|
||||
}) as unknown as Promise<{ success: boolean }>
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { get, post } from '@/utils/request';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Image Gallery API
|
||||
//
|
||||
// The gallery lists every image asset inside a knowledge base. An "asset" is a
|
||||
// single rendered image projected from a chunk's `image_info` array (a document
|
||||
// chunk can carry several images). The backend de-duplicates, filters by
|
||||
// keyword / attribute / enabled state, sorts and paginates in the database, so
|
||||
// a page costs the same however many images the KB holds.
|
||||
//
|
||||
// What the gallery shows (filters, searchable fields, sort options) is NOT
|
||||
// hardcoded here: GET /knowledge-bases/:id/gallery-config returns the
|
||||
// self-describing contract (attribute sources, resolved per-attribute usage,
|
||||
// the caller's search activation state) and the UI renders from it. New
|
||||
// backend attributes therefore light up with no frontend change.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** One image projected from a chunk, as returned by the backend. */
|
||||
export interface ImageAsset {
|
||||
/** Stable id: "<chunkID>#<index-in-array>". */
|
||||
id: string;
|
||||
/** Owning chunk id. */
|
||||
chunk_id: string;
|
||||
/** Owning knowledge (document) id. */
|
||||
knowledge_id: string;
|
||||
/** Human-readable name of the source knowledge item (document title). */
|
||||
source_name: string;
|
||||
/** Owning chunk type; empty for images discovered on a text (document) chunk. */
|
||||
chunk_type: string;
|
||||
/** Rendered image URL. */
|
||||
url: string;
|
||||
/** Pre-transform source reference, when different. */
|
||||
original_url: string;
|
||||
/** Model-generated image description. */
|
||||
caption: string;
|
||||
/** Extracted OCR text, if any. */
|
||||
ocr_text: string;
|
||||
/** Observed attribute map keyed by source-local attribute name. */
|
||||
attrs: Record<string, unknown>;
|
||||
/** Mirrors the owning chunk's enabled flag. */
|
||||
is_enabled: boolean;
|
||||
/** Mirrors the owning chunk's index status. */
|
||||
status: number;
|
||||
/** Owning chunk creation time (ISO 8601). */
|
||||
created_at: string;
|
||||
/** Owning chunk last-update time (ISO 8601). */
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export type ImageSortOrder = 'asc' | 'desc';
|
||||
|
||||
/** Query parameters accepted by GET /knowledge-bases/:id/images. */
|
||||
export interface ImageListParams {
|
||||
/** Case-insensitive substring match against the union of searchIn fields. */
|
||||
keyword?: string;
|
||||
/**
|
||||
* Namespaced attribute ids to search ("builtin:caption"). Must be
|
||||
* in_searchfield=true in the contract; the backend drops anything else.
|
||||
* Omit to use the backend default (builtin caption + ocr_text).
|
||||
*/
|
||||
searchIn?: string[];
|
||||
/** Namespaced attribute id to sort by; must be in_sortfield=true. */
|
||||
sortBy?: string;
|
||||
sortOrder?: ImageSortOrder;
|
||||
/** Restrict to chunks with this enabled state. Omit to include both. */
|
||||
isEnabled?: boolean;
|
||||
/**
|
||||
* Source-document restriction: only images owned by these knowledge items
|
||||
* are listed. Sent in the POST body when present (the GET query-param
|
||||
* variant keeps a lower URL-length-driven cap).
|
||||
*/
|
||||
knowledgeIds?: string[];
|
||||
/**
|
||||
* Attribute filters keyed by namespaced attribute id. Values within one
|
||||
* attribute are OR-ed; attributes are AND-ed. Sent as one `attr_filters`
|
||||
* JSON query param.
|
||||
*/
|
||||
attrFilters?: Record<string, string[]>;
|
||||
/**
|
||||
* Per-value verdicts keyed by namespaced attribute id, each mapping a value
|
||||
* to "off" (hide images carrying it) or "on" (show them regardless). An
|
||||
* omitted value stays neutral. Sent as one `attr_rules` JSON query param;
|
||||
* "on" outranks "off" when both speak about the same image.
|
||||
*/
|
||||
attrRules?: Record<string, Record<string, string>>;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface ImageListResult {
|
||||
items: ImageAsset[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* List image assets for a knowledge base. Attribute references use the
|
||||
* namespaced ids from the gallery contract; the backend validates them
|
||||
* against the contract and silently drops ineligible ones.
|
||||
*
|
||||
* Requests carrying knowledge_ids go through POST /images with the filter as
|
||||
* a JSON body: URL length limits would otherwise cap the source picker's
|
||||
* select-all to a handful of documents.
|
||||
*/
|
||||
export async function listGalleryImages(
|
||||
kbId: string,
|
||||
params: ImageListParams = {},
|
||||
): Promise<ImageListResult> {
|
||||
if (params.knowledgeIds && params.knowledgeIds.length) {
|
||||
const res = await post<{
|
||||
success: boolean;
|
||||
data: ImageAsset[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}>(`/api/v1/knowledge-bases/${kbId}/images`, {
|
||||
keyword: params.keyword,
|
||||
search_in: params.searchIn,
|
||||
sort_by: params.sortBy,
|
||||
sort_order: params.sortOrder,
|
||||
is_enabled: params.isEnabled,
|
||||
knowledge_ids: params.knowledgeIds,
|
||||
attr_filters: params.attrFilters,
|
||||
attr_rules: params.attrRules,
|
||||
page: params.page,
|
||||
page_size: params.pageSize,
|
||||
});
|
||||
return {
|
||||
items: res.data,
|
||||
total: res.total,
|
||||
page: res.page,
|
||||
pageSize: res.page_size,
|
||||
};
|
||||
}
|
||||
|
||||
const query = new URLSearchParams();
|
||||
if (params.keyword) query.set('keyword', params.keyword);
|
||||
if (params.searchIn && params.searchIn.length) {
|
||||
query.set('search_in', params.searchIn.join(','));
|
||||
}
|
||||
if (params.sortBy) query.set('sort_by', params.sortBy);
|
||||
if (params.sortOrder) query.set('sort_order', params.sortOrder);
|
||||
if (typeof params.isEnabled === 'boolean') {
|
||||
query.set('is_enabled', String(params.isEnabled));
|
||||
}
|
||||
if (params.attrFilters && Object.keys(params.attrFilters).length) {
|
||||
query.set('attr_filters', JSON.stringify(params.attrFilters));
|
||||
}
|
||||
if (params.attrRules && Object.keys(params.attrRules).length) {
|
||||
query.set('attr_rules', JSON.stringify(params.attrRules));
|
||||
}
|
||||
if (params.page) query.set('page', String(params.page));
|
||||
if (params.pageSize) query.set('page_size', String(params.pageSize));
|
||||
|
||||
const qs = query.toString();
|
||||
const res = await get<{
|
||||
success: boolean;
|
||||
data: ImageAsset[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}>(`/api/v1/knowledge-bases/${kbId}/images${qs ? `?${qs}` : ''}`);
|
||||
|
||||
return {
|
||||
items: res.data,
|
||||
total: res.total,
|
||||
page: res.page,
|
||||
pageSize: res.page_size,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Gallery contract (GET /knowledge-bases/:id/gallery-config)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Resolved per-attribute usage flags after all config tiers merged. */
|
||||
export interface GalleryAttrUsage {
|
||||
in_filter: boolean;
|
||||
in_searchfield: boolean;
|
||||
in_sortfield: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* One attribute as the contract serves it: the source's declaration with
|
||||
* every config tier's overrides merged in. `id` is namespaced
|
||||
* ("<sourceID>:<name>"); `usage_from` names the highest tier that touched
|
||||
* the usage ("source" | "system" | "kb" | "user").
|
||||
*/
|
||||
/**
|
||||
* One allowed value of an attribute.
|
||||
*
|
||||
* Display text is deliberately split: `label` is the short name that fits a
|
||||
* filter checkbox, `description` is the sentence shown where there is room
|
||||
* (a tooltip). `value` stays the raw machine value — it is what gets
|
||||
* filtered and searched, and it is never localized.
|
||||
*/
|
||||
export interface GalleryAttrValue {
|
||||
value: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface GalleryResolvedAttr {
|
||||
id: string;
|
||||
source: string;
|
||||
/** Source-local attribute name, as stored in image_info attrs. */
|
||||
name: string;
|
||||
/** "text" | "date" | "extent" | "presence" | "keywords" */
|
||||
type: string;
|
||||
values?: GalleryAttrValue[];
|
||||
/** Short on-screen name; falls back to the attribute id when absent. */
|
||||
label: string;
|
||||
/** Sentence explaining the attribute; shown where there is room. */
|
||||
description?: string;
|
||||
usage: GalleryAttrUsage;
|
||||
usage_from: string;
|
||||
}
|
||||
|
||||
/** The self-describing contract the gallery UI renders from. */
|
||||
export interface GalleryConfig {
|
||||
/** Live source ids in priority order. */
|
||||
attribute_sources: string[];
|
||||
attributes: GalleryResolvedAttr[];
|
||||
/** Search activation mode: "all" (default) or "custom". */
|
||||
mode: 'all' | 'custom';
|
||||
/** Per-attribute search toggles ("on"/"off"); consulted in custom mode. */
|
||||
status: Record<string, string>;
|
||||
}
|
||||
|
||||
/** Fetch the gallery contract for a knowledge base. */
|
||||
export async function fetchGalleryConfig(kbId: string): Promise<GalleryConfig> {
|
||||
const res = await get<{ success: boolean; data: GalleryConfig }>(
|
||||
`/api/v1/knowledge-bases/${kbId}/gallery-config`,
|
||||
);
|
||||
return {
|
||||
attribute_sources: res.data.attribute_sources ?? [],
|
||||
attributes: res.data.attributes ?? [],
|
||||
mode: res.data.mode === 'custom' ? 'custom' : 'all',
|
||||
status: res.data.status ?? {},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,740 @@
|
||||
import { get, post, put } from '../../utils/request';
|
||||
import i18n from '@/i18n'
|
||||
import type { ModelCapabilities, ModelSpecOverride, ReasoningEffortLevel } from '../model'
|
||||
|
||||
const t = (key: string) => i18n.global.t(key)
|
||||
|
||||
// GET /initialization/config/:kbId exposes credential presence, not values.
|
||||
export interface ModelCredentialStatus {
|
||||
apiKey?: boolean;
|
||||
}
|
||||
|
||||
export interface COSCredentialStatus {
|
||||
secretId?: boolean;
|
||||
secretKey?: boolean;
|
||||
}
|
||||
|
||||
// 初始化配置数据类型
|
||||
export interface InitializationConfig {
|
||||
llm: {
|
||||
source: string;
|
||||
modelName: string;
|
||||
baseUrl?: string;
|
||||
/** @deprecated Use credentials.apiKey from GET responses */
|
||||
apiKey?: string;
|
||||
credentials?: ModelCredentialStatus;
|
||||
};
|
||||
embedding: {
|
||||
source: string;
|
||||
modelName: string;
|
||||
baseUrl?: string;
|
||||
/** @deprecated Use credentials.apiKey from GET responses */
|
||||
apiKey?: string;
|
||||
dimension?: number; // 添加embedding维度字段
|
||||
credentials?: ModelCredentialStatus;
|
||||
};
|
||||
rerank: {
|
||||
modelName: string;
|
||||
baseUrl: string;
|
||||
/** @deprecated Use credentials.apiKey from GET responses */
|
||||
apiKey?: string;
|
||||
enabled: boolean;
|
||||
credentials?: ModelCredentialStatus;
|
||||
};
|
||||
multimodal: {
|
||||
enabled: boolean;
|
||||
storageType: 'cos' | 'minio';
|
||||
vlm?: {
|
||||
modelName: string;
|
||||
baseUrl: string;
|
||||
/** @deprecated Use credentials.apiKey from GET responses */
|
||||
apiKey?: string;
|
||||
interfaceType?: string; // "ollama" or "openai"
|
||||
credentials?: ModelCredentialStatus;
|
||||
};
|
||||
cos?: {
|
||||
region: string;
|
||||
bucketName: string;
|
||||
appId: string;
|
||||
pathPrefix?: string;
|
||||
/** @deprecated Use credentials from GET responses */
|
||||
secretId?: string;
|
||||
/** @deprecated Use credentials from GET responses */
|
||||
secretKey?: string;
|
||||
credentials?: COSCredentialStatus;
|
||||
};
|
||||
minio?: {
|
||||
bucketName: string;
|
||||
pathPrefix?: string;
|
||||
};
|
||||
};
|
||||
documentSplitting: {
|
||||
chunkSize: number;
|
||||
chunkOverlap: number;
|
||||
separators: string[];
|
||||
// Adaptive chunking strategy. Empty / "legacy" = classic recursive splitter.
|
||||
// "auto" lets the backend profiler pick a tier; "heading" / "heuristic"
|
||||
// pin the tier explicitly. See backend chunker package for details.
|
||||
strategy?: string;
|
||||
// Cap chunk size in approx tokens. 0 = char-based budget only.
|
||||
tokenLimit?: number;
|
||||
// Language hints for heuristic patterns ("de", "en", "zh"). Empty = auto-detect.
|
||||
languages?: string[];
|
||||
};
|
||||
// Frontend-only hint for storage selection UI
|
||||
storageType?: 'cos' | 'minio';
|
||||
nodeExtract: {
|
||||
enabled: boolean,
|
||||
text: string,
|
||||
tags: string[],
|
||||
nodes: Node[],
|
||||
relations: Relation[]
|
||||
}
|
||||
}
|
||||
|
||||
// 下载任务状态类型
|
||||
export interface DownloadTask {
|
||||
id: string;
|
||||
modelName: string;
|
||||
status: 'pending' | 'downloading' | 'completed' | 'failed';
|
||||
progress: number;
|
||||
message: string;
|
||||
startTime: string;
|
||||
endTime?: string;
|
||||
}
|
||||
|
||||
// 简化版知识库配置更新接口(只传模型ID)
|
||||
export interface KBModelConfigRequest {
|
||||
llmModelId: string
|
||||
embeddingModelId: string
|
||||
vlm_config?: {
|
||||
enabled: boolean
|
||||
model_id?: string
|
||||
description_language?: string
|
||||
custom_instructions?: string
|
||||
}
|
||||
asr_config?: {
|
||||
enabled: boolean
|
||||
model_id?: string
|
||||
language?: string
|
||||
}
|
||||
documentSplitting: {
|
||||
chunkSize: number
|
||||
chunkOverlap: number
|
||||
separators: string[]
|
||||
parserEngineRules?: {
|
||||
file_types: string[]
|
||||
engine: string
|
||||
xlsx_first_row_as_header?: boolean
|
||||
}[]
|
||||
enableParentChild?: boolean
|
||||
parentChunkSize?: number
|
||||
childChunkSize?: number
|
||||
// Adaptive chunking strategy ("auto" | "heading" | "heuristic" | "legacy").
|
||||
// The backend uses pointer-based DTOs for these three fields:
|
||||
// - undefined / not set in payload → no change on server
|
||||
// - "" / 0 / [] explicitly sent → clears the value
|
||||
// Send the field whenever the user has opened the editor — even
|
||||
// empty values — so the user can always reset back to defaults.
|
||||
strategy?: string
|
||||
// Approximate token budget per chunk; 0 = char-based.
|
||||
tokenLimit?: number
|
||||
// Language hints for heuristic patterns. Empty array = auto-detect.
|
||||
languages?: string[]
|
||||
tableMetadataInstructions?: string
|
||||
}
|
||||
multimodal: {
|
||||
enabled: boolean
|
||||
}
|
||||
/** 存储引擎选择:"local" | "minio" | "cos" | "obs" 等,影响文档上传与文档内图片存储 */
|
||||
storageBackendId?: string
|
||||
storageProvider?: string
|
||||
nodeExtract: {
|
||||
enabled: boolean
|
||||
text: string
|
||||
tags: string[]
|
||||
nodes: Node[]
|
||||
relations: Relation[]
|
||||
customInstructions?: string
|
||||
}
|
||||
questionGeneration?: {
|
||||
enabled: boolean
|
||||
questionCount: number
|
||||
customInstructions?: string
|
||||
}
|
||||
}
|
||||
|
||||
export function updateKBConfig(kbId: string, config: KBModelConfigRequest): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('Starting KB config update (simplified)...', kbId, config);
|
||||
put(`/api/v1/initialization/config/${kbId}`, config)
|
||||
.then((response: any) => {
|
||||
console.log('KB config update completed', response);
|
||||
resolve(response);
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to update KB config:', error);
|
||||
reject(error.error || error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 根据知识库ID执行配置更新(旧版,保留兼容性)
|
||||
export function initializeSystemByKB(kbId: string, config: InitializationConfig): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('Starting KB config update...', kbId, config);
|
||||
post(`/api/v1/initialization/initialize/${kbId}`, config)
|
||||
.then((response: any) => {
|
||||
console.log('KB config update completed', response);
|
||||
resolve(response);
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to update KB config:', error);
|
||||
reject(error.error || error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 检查Ollama服务状态
|
||||
export function checkOllamaStatus(): Promise<{ available: boolean; version?: string; error?: string; baseUrl?: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
get('/api/v1/initialization/ollama/status')
|
||||
.then((response: any) => {
|
||||
resolve(response.data || { available: false });
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to check Ollama status:', error);
|
||||
resolve({ available: false, error: error.message || t('error.initialization.checkFailed') });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Ollama 模型详细信息接口
|
||||
export interface OllamaModelInfo {
|
||||
name: string;
|
||||
size: number;
|
||||
digest: string;
|
||||
modified_at: string;
|
||||
}
|
||||
|
||||
// 列出已安装的 Ollama 模型(详细信息)
|
||||
export function listOllamaModels(): Promise<OllamaModelInfo[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
get('/api/v1/initialization/ollama/models')
|
||||
.then((response: any) => {
|
||||
resolve((response.data && response.data.models) || []);
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to list Ollama models:', error);
|
||||
resolve([]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 检查Ollama模型状态
|
||||
export function checkOllamaModels(models: string[]): Promise<{ models: Record<string, boolean> }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/ollama/models/check', { models })
|
||||
.then((response: any) => {
|
||||
resolve(response.data || { models: {} });
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to check Ollama models:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 启动Ollama模型下载(异步)
|
||||
export function downloadOllamaModel(modelName: string): Promise<{ taskId: string; modelName: string; status: string; progress: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/ollama/models/download', { modelName })
|
||||
.then((response: any) => {
|
||||
resolve(response.data || { taskId: '', modelName, status: 'failed', progress: 0 });
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to start Ollama model download:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 查询下载进度
|
||||
export function getDownloadProgress(taskId: string): Promise<DownloadTask> {
|
||||
return new Promise((resolve, reject) => {
|
||||
get(`/api/v1/initialization/ollama/download/progress/${taskId}`)
|
||||
.then((response: any) => {
|
||||
resolve(response.data);
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to get download progress:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 获取所有下载任务
|
||||
export function listDownloadTasks(): Promise<DownloadTask[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
get('/api/v1/initialization/ollama/download/tasks')
|
||||
.then((response: any) => {
|
||||
resolve(response.data || []);
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to list download tasks:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export function getCurrentConfigByKB(kbId: string): Promise<InitializationConfig & { hasFiles: boolean }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
get(`/api/v1/initialization/config/${kbId}`)
|
||||
.then((response: any) => {
|
||||
resolve(response.data || {});
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to get KB config:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 所有"测试连接"接口共用的通用可选参数。
|
||||
// customHeaders / extraConfig / interfaceType 对应后端 ModelTestRequest 里的同名字段,
|
||||
// 会被透传给真正的模型装配流程,保证测试连接与生产调用走完全相同的路径。
|
||||
interface BaseModelTestPayload {
|
||||
spec?: ModelSpecOverride;
|
||||
customHeaders?: Record<string, string>;
|
||||
extraConfig?: Record<string, string>;
|
||||
interfaceType?: string;
|
||||
/** 第二段密钥(如 LKEAP Rerank 的腾讯云 SecretKey) */
|
||||
appSecret?: string;
|
||||
}
|
||||
|
||||
// 检查远程API模型
|
||||
export function checkRemoteModel(modelConfig: {
|
||||
modelName: string;
|
||||
baseUrl: string;
|
||||
apiKey?: string;
|
||||
provider?: string;
|
||||
// 编辑已存在模型时传 modelId,后端会自动从存储中带出 apiKey
|
||||
// (前端不再回显明文密钥,所以测试连接必须用这个回填路径)
|
||||
modelId?: string;
|
||||
} & BaseModelTestPayload): Promise<{
|
||||
available: boolean;
|
||||
message?: string;
|
||||
}> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/remote/check', modelConfig)
|
||||
.then((response: any) => {
|
||||
resolve(response.data || {});
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to check remote model:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 测试 Embedding 模型(本地/远程)是否可用
|
||||
export function testEmbeddingModel(modelConfig: {
|
||||
source: 'local' | 'remote';
|
||||
modelName: string;
|
||||
baseUrl?: string;
|
||||
apiKey?: string;
|
||||
dimension?: number;
|
||||
supportsDimensionOverride?: boolean;
|
||||
provider?: string;
|
||||
modelId?: string;
|
||||
} & BaseModelTestPayload): Promise<{ available: boolean; message?: string; dimension?: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/embedding/test', modelConfig)
|
||||
.then((response: any) => {
|
||||
resolve(response.data || {});
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to test Embedding model:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export function checkRerankModel(modelConfig: {
|
||||
modelName: string;
|
||||
baseUrl: string;
|
||||
apiKey?: string;
|
||||
provider?: string;
|
||||
modelId?: string;
|
||||
} & BaseModelTestPayload): Promise<{
|
||||
available: boolean;
|
||||
message?: string;
|
||||
}> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/rerank/check', modelConfig)
|
||||
.then((response: any) => {
|
||||
resolve(response.data || {});
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to check Rerank model:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 检查 ASR 模型连接(通过 /v1/audio/transcriptions 端点测试)
|
||||
export function checkASRModel(modelConfig: {
|
||||
modelName: string;
|
||||
baseUrl: string;
|
||||
apiKey?: string;
|
||||
provider?: string;
|
||||
modelId?: string;
|
||||
} & BaseModelTestPayload): Promise<{
|
||||
available: boolean;
|
||||
message?: string;
|
||||
}> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/asr/check', modelConfig)
|
||||
.then((response: any) => {
|
||||
resolve(response.data || {});
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to check ASR model:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function testMultimodalFunction(testData: {
|
||||
image: File;
|
||||
vlm_model: string;
|
||||
vlm_base_url: string;
|
||||
vlm_api_key?: string;
|
||||
vlm_interface_type?: string;
|
||||
storage_type?: 'cos' | 'minio';
|
||||
// COS optional fields (required only when storage_type === 'cos')
|
||||
cos_secret_id?: string;
|
||||
cos_secret_key?: string;
|
||||
cos_region?: string;
|
||||
cos_bucket_name?: string;
|
||||
cos_app_id?: string;
|
||||
cos_path_prefix?: string;
|
||||
// MinIO optional fields
|
||||
minio_bucket_name?: string;
|
||||
minio_path_prefix?: string;
|
||||
chunk_size: number;
|
||||
chunk_overlap: number;
|
||||
separators: string[];
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
caption?: string;
|
||||
ocr?: string;
|
||||
processing_time?: number;
|
||||
message?: string;
|
||||
}> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const formData = new FormData();
|
||||
formData.append('image', testData.image);
|
||||
formData.append('vlm_model', testData.vlm_model);
|
||||
formData.append('vlm_base_url', testData.vlm_base_url);
|
||||
if (testData.vlm_api_key) {
|
||||
formData.append('vlm_api_key', testData.vlm_api_key);
|
||||
}
|
||||
if (testData.vlm_interface_type) {
|
||||
formData.append('vlm_interface_type', testData.vlm_interface_type);
|
||||
}
|
||||
if (testData.storage_type) {
|
||||
formData.append('storage_type', testData.storage_type);
|
||||
}
|
||||
// Append COS fields only when storage_type is COS
|
||||
if (testData.storage_type === 'cos') {
|
||||
if (testData.cos_secret_id) formData.append('cos_secret_id', testData.cos_secret_id);
|
||||
if (testData.cos_secret_key) formData.append('cos_secret_key', testData.cos_secret_key);
|
||||
if (testData.cos_region) formData.append('cos_region', testData.cos_region);
|
||||
if (testData.cos_bucket_name) formData.append('cos_bucket_name', testData.cos_bucket_name);
|
||||
if (testData.cos_app_id) formData.append('cos_app_id', testData.cos_app_id);
|
||||
if (testData.cos_path_prefix) formData.append('cos_path_prefix', testData.cos_path_prefix);
|
||||
}
|
||||
// MinIO fields
|
||||
if (testData.minio_bucket_name) formData.append('minio_bucket_name', testData.minio_bucket_name);
|
||||
if (testData.minio_path_prefix) formData.append('minio_path_prefix', testData.minio_path_prefix);
|
||||
formData.append('chunk_size', testData.chunk_size.toString());
|
||||
formData.append('chunk_overlap', testData.chunk_overlap.toString());
|
||||
formData.append('separators', JSON.stringify(testData.separators));
|
||||
|
||||
// 获取鉴权Token
|
||||
const token = localStorage.getItem('academy_token');
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// 跨空间访问请求头:直接附,避免 short-circuit "selectedTenantId
|
||||
// === defaultTenantId 时不附" 在某些边角下让 header 静默丢失。
|
||||
// 与 utils/request.ts、api/chat/streame.ts 行为一致。
|
||||
const selectedTenantId = localStorage.getItem('academy_selected_tenant_id');
|
||||
if (selectedTenantId) {
|
||||
headers['X-Tenant-ID'] = selectedTenantId;
|
||||
}
|
||||
|
||||
// 使用原生fetch因为需要发送FormData
|
||||
fetch('/api/v1/initialization/multimodal/test', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then((data: any) => {
|
||||
if (data.success) {
|
||||
resolve(data.data || {});
|
||||
} else {
|
||||
resolve({ success: false, message: data.message || t('error.initialization.testFailed') });
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed multimodal test:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 文本内容关系提取接口
|
||||
export interface TextRelationExtractionRequest {
|
||||
text: string;
|
||||
tags: string[];
|
||||
model_id: string;
|
||||
}
|
||||
|
||||
export interface Node {
|
||||
name: string;
|
||||
attributes: string[];
|
||||
}
|
||||
|
||||
export interface Relation {
|
||||
node1: string;
|
||||
node2: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface TextRelationExtractionResponse {
|
||||
nodes: Node[];
|
||||
relations: Relation[];
|
||||
}
|
||||
|
||||
// 文本内容关系提取
|
||||
export function extractTextRelations(request: TextRelationExtractionRequest): Promise<TextRelationExtractionResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/extract/text-relation', request, { timeout: 60000 })
|
||||
.then((response: any) => {
|
||||
resolve(response.data || { nodes: [], relations: [] });
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to extract text relations:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export interface FabriTextRequest {
|
||||
tags: string[];
|
||||
model_id: string;
|
||||
}
|
||||
|
||||
export interface FabriTextResponse {
|
||||
text: string;
|
||||
}
|
||||
|
||||
// 文本内容生成
|
||||
export function fabriText(request: FabriTextRequest): Promise<FabriTextResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/extract/fabri-text', request)
|
||||
.then((response: any) => {
|
||||
resolve(response.data || { text: '' });
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to generate text:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export interface FabriTagRequest {
|
||||
}
|
||||
|
||||
export interface FabriTagResponse {
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
// 标签生成
|
||||
export function fabriTag(request: FabriTagRequest): Promise<FabriTagResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/extract/fabri-tag', request)
|
||||
.then((response: any) => {
|
||||
resolve(response.data || { tags: [] as string[] });
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to generate tags:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 厂商额外配置字段(Azure api_version、LKEAP secret_key 等)。
|
||||
// Mirrors internal/models/catalog.ExtraField.
|
||||
export interface ModelProviderExtraFieldOption {
|
||||
label: string;
|
||||
labels?: Record<string, string>;
|
||||
value: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames the primary credential input for vendors whose API does not take a
|
||||
* plain API key. LKEAP and Volcengine sign their rerank requests with a
|
||||
* CAM / IAM key pair, so the first field is a SecretId / Access Key ID.
|
||||
* The vendor declares the wording so the editor needs no vendor table.
|
||||
*/
|
||||
export interface ModelProviderCredentialLabel {
|
||||
label: string;
|
||||
labels?: Record<string, string>;
|
||||
placeholder?: string;
|
||||
placeholders?: Record<string, string>;
|
||||
hint?: string;
|
||||
hints?: Record<string, string>;
|
||||
// Backend model types ("KnowledgeQA", "Rerank", ...); empty = all.
|
||||
model_types?: string[];
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export interface ModelProviderExtraField {
|
||||
key: string;
|
||||
label: string;
|
||||
labels?: Record<string, string>;
|
||||
type: 'string' | 'number' | 'boolean' | 'select' | 'password' | string;
|
||||
required?: boolean;
|
||||
default?: string;
|
||||
placeholder?: string;
|
||||
placeholders?: Record<string, string>;
|
||||
options?: ModelProviderExtraFieldOption[];
|
||||
// Backend model types ("KnowledgeQA", "Embedding", "Rerank", "VLLM", "ASR"); empty = all.
|
||||
model_types?: string[];
|
||||
// Secret values are never echoed back; they are stored as the app_secret credential.
|
||||
secret?: boolean;
|
||||
}
|
||||
|
||||
// 厂商内置模型目录条目。Mirrors handler.ModelCatalogEntryDTO.
|
||||
export interface ModelCatalogEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
type: string;
|
||||
api?: string;
|
||||
reasoning?: boolean;
|
||||
input?: string[];
|
||||
context_window?: number;
|
||||
max_output_tokens?: number;
|
||||
dimension?: number;
|
||||
thinking_levels?: ReasoningEffortLevel[];
|
||||
cost?: Record<string, unknown>;
|
||||
// Vendor page these facts came from, for the "read the docs" link.
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export interface ModelProviderThinking {
|
||||
format: string;
|
||||
levels: ReasoningEffortLevel[];
|
||||
}
|
||||
|
||||
// 模型厂商信息类型。Mirrors handler.ModelProviderDTO — the frontend keeps no
|
||||
// vendor table of its own; everything rendered for a vendor comes from here.
|
||||
export interface ModelProviderOption {
|
||||
value: string; // provider 标识符
|
||||
label: string; // 显示名称(英文 / 默认)
|
||||
labels?: Record<string, string>; // 按 locale 的显示名称
|
||||
description: string; // 描述
|
||||
descriptions?: Record<string, string>;
|
||||
website?: string;
|
||||
icon?: string; // data:image/svg+xml;base64,... 可直接用于 <img src>
|
||||
api?: string;
|
||||
auth?: string;
|
||||
requiresAuth?: boolean;
|
||||
defaultUrls: Record<string, string>; // 按模型类型区分的默认 URL
|
||||
modelTypes: string[]; // 支持的模型类型
|
||||
extraFields?: ModelProviderExtraField[];
|
||||
credentialLabels?: ModelProviderCredentialLabel[];
|
||||
models?: ModelCatalogEntry[];
|
||||
thinking?: ModelProviderThinking;
|
||||
order?: number;
|
||||
}
|
||||
|
||||
// 获取模型厂商列表。
|
||||
//
|
||||
// 失败时 reject(不再吞成空数组):唯一的调用方 stores/modelProviders 需要
|
||||
// 区分「后端真的没有厂商」和「这次请求挂了」——把失败当成空列表缓存下来,
|
||||
// 会让厂商下拉在整个会话里一直空着,直到用户刷新页面。
|
||||
export function listModelProviders(modelType?: string): Promise<ModelProviderOption[]> {
|
||||
const url = modelType
|
||||
? `/api/v1/models/providers?model_type=${encodeURIComponent(modelType)}`
|
||||
: '/api/v1/models/providers';
|
||||
return get(url).then((response: any) => {
|
||||
const data = response?.data;
|
||||
// Reject rather than coerce: the store distinguishes "this vendor list
|
||||
// is genuinely empty" (cacheable) from "the request did not produce a
|
||||
// list" (retry on the next mount). Returning [] here would make a
|
||||
// malformed 200 look like the former and blank the vendor dropdown and
|
||||
// every card icon for the rest of the session.
|
||||
if (!Array.isArray(data)) {
|
||||
return Promise.reject(new Error('model providers response is not a list'));
|
||||
}
|
||||
return data as ModelProviderOption[];
|
||||
});
|
||||
}
|
||||
|
||||
export interface ResolveModelCatalogParams {
|
||||
spec?: ModelSpecOverride;
|
||||
provider: string;
|
||||
model?: string;
|
||||
base_url?: string;
|
||||
model_type?: string;
|
||||
api?: string;
|
||||
thinking_control?: string;
|
||||
remote_model_name?: string;
|
||||
// Vendor-declared non-secret extra fields (Azure api_version, ...) are
|
||||
// forwarded by key so the preview resolves the same request the runtime
|
||||
// will make. The backend only accepts keys the vendor declares.
|
||||
[extraField: string]: string | ModelSpecOverride | undefined;
|
||||
}
|
||||
|
||||
// 目录解析结果。Mirrors handler.ResolveModelCatalog response data.
|
||||
export interface ResolvedModelCatalog {
|
||||
provider: string;
|
||||
api: string;
|
||||
// base_url and url are only returned to callers who may configure
|
||||
// integrations; a viewer gets the capability answer without the endpoint.
|
||||
base_url?: string;
|
||||
// url is the endpoint the row will actually call, and only vendors that
|
||||
// compute their own URL report one (Azure, whose api_version picks
|
||||
// between the v1 data plane and the dated deployments path).
|
||||
url?: string;
|
||||
remote_model: string;
|
||||
cataloged: boolean;
|
||||
model: Record<string, unknown>;
|
||||
capabilities: ModelCapabilities;
|
||||
}
|
||||
|
||||
// 解析模型的有效接入配置(协议、思考等级、上下文窗口等),供编辑器实时展示。
|
||||
export function resolveModelCatalog(params: ResolveModelCatalogParams): Promise<ResolvedModelCatalog> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post(`/api/v1/models/catalog/resolve`, params)
|
||||
.then((response: any) => {
|
||||
if (response?.success && response?.data) {
|
||||
resolve(response.data as ResolvedModelCatalog);
|
||||
} else {
|
||||
reject(new Error(response?.message || 'resolve failed'));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
reject(error?.error || error);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,929 @@
|
||||
import { get, post, put, del, postUpload, getDown } from "../../utils/request";
|
||||
import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess';
|
||||
import type { AuditLog, AuditOutcome, ListAuditLogResponse } from '@/api/tenant/audit-log';
|
||||
import { buildListKnowledgeFilesQuery } from './knowledgeFileListQuery';
|
||||
|
||||
export { buildListKnowledgeFilesQuery } from './knowledgeFileListQuery';
|
||||
|
||||
export type KnowledgeBaseActivity = AuditLog;
|
||||
|
||||
export interface ListKnowledgeBaseActivityParams {
|
||||
after_id?: number;
|
||||
limit?: number;
|
||||
action?: string;
|
||||
outcome?: AuditOutcome;
|
||||
actor?: string;
|
||||
}
|
||||
|
||||
export async function listKnowledgeBaseActivity(
|
||||
id: string,
|
||||
params: ListKnowledgeBaseActivityParams = {},
|
||||
): Promise<ListAuditLogResponse> {
|
||||
const query = new URLSearchParams();
|
||||
if (params.after_id) query.set('after_id', String(params.after_id));
|
||||
if (params.limit) query.set('limit', String(params.limit));
|
||||
if (params.action) query.set('action', params.action);
|
||||
if (params.outcome) query.set('outcome', params.outcome);
|
||||
if (params.actor) query.set('actor', params.actor);
|
||||
const qs = query.toString();
|
||||
return (await get(`/api/v1/knowledge-bases/${id}/activity${qs ? `?${qs}` : ''}`)) as unknown as ListAuditLogResponse;
|
||||
}
|
||||
|
||||
// 知识库管理 API(列表、创建、获取、更新、删除、复制)
|
||||
export function listKnowledgeBases(params?: {
|
||||
agent_id?: string;
|
||||
agent_source_tenant_id?: string;
|
||||
/**
|
||||
* Optional creator filter. Server-side semantics:
|
||||
* - "mine" → only KBs whose creator_id matches the caller
|
||||
* - "others" → only KBs created by someone else in this tenant
|
||||
* - omitted/"all" → no filter
|
||||
* KBs predating the RBAC backfill (creator_id="") never match
|
||||
* mine/others — they fall out of both views by design.
|
||||
*/
|
||||
creator?: 'all' | 'mine' | 'others';
|
||||
}) {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.agent_id) query.set('agent_id', params.agent_id);
|
||||
if (params?.agent_source_tenant_id) query.set('agent_source_tenant_id', params.agent_source_tenant_id);
|
||||
if (params?.creator && params.creator !== 'all') query.set('creator', params.creator);
|
||||
const qs = query.toString();
|
||||
return get(qs ? `/api/v1/knowledge-bases?${qs}` : '/api/v1/knowledge-bases');
|
||||
}
|
||||
|
||||
// Read-only vector-store binding metadata enriched onto every KB
|
||||
// response (list, create, get, update, pin). Source carries where the
|
||||
// binding points; status reports whether that target is currently
|
||||
// reachable by the server.
|
||||
//
|
||||
// - source 'env' → KB uses the tenant's env-configured store
|
||||
// (RETRIEVE_DRIVER). vector_store_id is null and
|
||||
// vector_store_name is the localized "System
|
||||
// default" label; vector_store_engine_type still
|
||||
// reports the underlying engine (e.g. "postgres").
|
||||
// - source 'user' → KB is bound to a tenant-owned VectorStore.
|
||||
// vector_store_id / name / engine_type are real.
|
||||
// - source 'shared' → KB belongs to a different tenant and is
|
||||
// readable via cross-organization sharing. The
|
||||
// server strips vector_store_id and engine_type
|
||||
// to avoid leaking the owner tenant's store
|
||||
// inventory; only this source marker arrives.
|
||||
// - status 'unavailable' → the binding cannot be reached right now
|
||||
// (deleted row, registry miss, transient infra
|
||||
// failure). Operators recover via the global
|
||||
// Vector Stores settings page.
|
||||
// ---------------------------------------------------------------------------
|
||||
// Image attribute observation (route 3). Mirrors backend types in
|
||||
// internal/types/image_attrs.go. The backend registry is the single source of
|
||||
// truth; the frontend fetches it from GET /image-attrs/schema and renders the
|
||||
// attribute panel dynamically. The types/constants below mirror the v1 shape
|
||||
// so the UI still compiles and can render a fallback before the schema loads.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// One allowed value of an image attribute.
|
||||
//
|
||||
// Display text is split for the same reasons the gallery splits it: `label` is
|
||||
// what fits on a checkbox or a table cell, `description` is the sentence that
|
||||
// explains the value where there is room. `value` stays the raw machine value.
|
||||
export interface ImageAttrValue {
|
||||
value: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
// One observable image attribute, as returned by the schema endpoint. The
|
||||
// registry is authoritative for both the behaviour and the wording: label,
|
||||
// description and the per-value texts are what the settings panel shows to an
|
||||
// operator who does not read identifiers like "contain.text".
|
||||
export interface ImageAttrSpec {
|
||||
name: string;
|
||||
type: 'extent' | 'presence';
|
||||
values?: ImageAttrValue[];
|
||||
question: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
consumers?: string[];
|
||||
}
|
||||
|
||||
// One attribute match: attribute `prop` equals `is`.
|
||||
export interface ImageAttrCondition {
|
||||
prop: string;
|
||||
is: string;
|
||||
}
|
||||
|
||||
// The OCR clause of the attribute -> work policy: the attribute conditions that
|
||||
// turn OCR on. What to do about an image whose attributes were NOT observed is
|
||||
// not part of this table — it is a setting of the pipeline that schedules OCR
|
||||
// (its own ocr_on_unobserved), so an on_unobserved left here by an older client
|
||||
// is ignored rather than honoured from two places.
|
||||
export interface ImageOCRAction {
|
||||
on: ImageAttrCondition[];
|
||||
}
|
||||
|
||||
// The attribute -> work policy sent back to the API (snake_case JSON).
|
||||
export interface ImageActionsConfig {
|
||||
ocr: ImageOCRAction;
|
||||
}
|
||||
|
||||
// Canonical registry + built-in actions returned by GET /image-attrs/schema.
|
||||
export interface ImageAttrSchema {
|
||||
version: string;
|
||||
prompt: string;
|
||||
attributes: ImageAttrSpec[];
|
||||
default_actions: ImageActionsConfig;
|
||||
}
|
||||
|
||||
// Mirrors backend types.DefaultImageActions. The schema endpoint returns the
|
||||
// authoritative copy; this is the fallback used before the schema loads (e.g.
|
||||
// in create mode, where no knowledge base id exists yet to query).
|
||||
export const DEFAULT_IMAGE_ACTIONS: ImageActionsConfig = {
|
||||
ocr: {
|
||||
on: [
|
||||
{ prop: 'contain.text', is: 'block' },
|
||||
{ prop: 'contain.data_visual', is: 'true' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
// Display-only fallback used before a KB exists (create mode) so the panel can
|
||||
// render without a network call. It mirrors the registry for layout and wording
|
||||
// only; the endpoint response is authoritative whenever it loads.
|
||||
export const FALLBACK_IMAGE_ATTR_SCHEMA: ImageAttrSchema = {
|
||||
version: 'attrs/2',
|
||||
prompt: 'observe/1',
|
||||
attributes: [
|
||||
{
|
||||
name: 'contain.text',
|
||||
type: 'extent',
|
||||
values: [
|
||||
{ value: 'none', label: 'None', description: 'no text at all' },
|
||||
{ value: 'sparse', label: 'Sparse', description: 'a few words — a logo, a road sign, a single label' },
|
||||
{ value: 'block', label: 'Block', description: 'a block of body text — a screenshot, a table, a document page' },
|
||||
],
|
||||
question: '',
|
||||
label: 'Text in the image',
|
||||
description: 'How much body text the picture itself carries.',
|
||||
consumers: ['ocr'],
|
||||
},
|
||||
{
|
||||
name: 'contain.data_visual',
|
||||
type: 'presence',
|
||||
values: [
|
||||
{ value: 'true', label: 'Yes', description: 'a chart, graph or diagram with plotted values' },
|
||||
{ value: 'false', label: 'No', description: 'a photo, drawing, icon or decoration' },
|
||||
],
|
||||
question: '',
|
||||
label: 'Data visual',
|
||||
description: 'Whether the picture conveys data as a chart, graph, diagram or infographic.',
|
||||
consumers: ['ocr'],
|
||||
},
|
||||
],
|
||||
default_actions: DEFAULT_IMAGE_ACTIONS,
|
||||
};
|
||||
|
||||
// Mirrors backend types.MergeImageActions: a custom OCR.On replaces the default
|
||||
// OCR.On wholesale (the "on" list is a unit); anything else the custom table
|
||||
// does not mention keeps the default. The result is what the form seeds with and
|
||||
// what makes an empty custom table safe to open.
|
||||
export function mergeImageActions(
|
||||
custom?: ImageActionsConfig | null,
|
||||
): ImageActionsConfig {
|
||||
if (custom && custom.ocr && custom.ocr.on && custom.ocr.on.length > 0) {
|
||||
return { ocr: { on: custom.ocr.on } };
|
||||
}
|
||||
return { ocr: { on: DEFAULT_IMAGE_ACTIONS.ocr.on.map((c) => ({ ...c })) } };
|
||||
}
|
||||
|
||||
// Fetch the canonical image-attribute registry + default actions from the
|
||||
// backend. The registry drives the attribute panel; the default actions seed
|
||||
// the OCR-condition display.
|
||||
export async function fetchImageAttrSchema(kbId: string): Promise<ImageAttrSchema> {
|
||||
// The registry is global, not per-KB. The backend exposes it at a top-level
|
||||
// route, the same shape as the other read-only KB-editor helpers
|
||||
// (GET /api/v1/chunker/preview, GET /api/v1/system/parser-engines). kbId is
|
||||
// kept in the signature for callers that pass KB context.
|
||||
void kbId;
|
||||
const res = await get<{ success: boolean; data: ImageAttrSchema }>(
|
||||
`/api/v1/image-attrs/schema`,
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Mirrors backend types.ImageProcessingConfig (snake_case JSON). The UI edits
|
||||
// the attribute-observation switch, the pipeline pick and the image-vector
|
||||
// switch; saving sends the snapshot back with those fields updated so API-side
|
||||
// settings survive a UI edit.
|
||||
export interface ImageProcessingConfig {
|
||||
model_id?: string;
|
||||
image_actions?: ImageActionsConfig;
|
||||
image_attrs_enabled?: boolean;
|
||||
/** Which image pipeline runs for this base; empty means "follow the switch". */
|
||||
image_pipeline?: string;
|
||||
/**
|
||||
* Every setting the picked pipeline declares, each under that pipeline's slot
|
||||
* ("<pipeline>.<field key>"). The panel writes and reads this map, and it is
|
||||
* where the run reads those settings from too.
|
||||
*/
|
||||
image_pipeline_params?: Record<string, unknown>;
|
||||
// Index and recall images by their own vectors. Off unless the knowledge
|
||||
// base opts in, and only takes effect with an embedding model that takes
|
||||
// images.
|
||||
image_vector_enabled?: boolean;
|
||||
}
|
||||
|
||||
// Mirrors types.ImagePipelineSpec and types.ImageFieldDef.
|
||||
//
|
||||
// A field is private to the pipeline that declared it, which is why two
|
||||
// pipelines may both own a field called "enable_ocr". The knowledge base stores
|
||||
// them per pipeline rather than in one flat map, and the panel renders one
|
||||
// control per field without naming any pipeline.
|
||||
export interface ImagePipelineField {
|
||||
key: string;
|
||||
/**
|
||||
* 'note' carries no value: it is explanation text the pipeline declares
|
||||
* alongside the switches it explains.
|
||||
*/
|
||||
type: 'bool' | 'string' | 'enum' | 'note';
|
||||
label: string;
|
||||
description: string;
|
||||
default: unknown;
|
||||
options: string[] | null;
|
||||
/**
|
||||
* Which run of the panel the field belongs to: 'switch' (standing, shown
|
||||
* outright), 'advanced' or 'note' (both folded away). Absent or empty means
|
||||
* 'switch', so a pipeline only mentions the group for fields it folds.
|
||||
*/
|
||||
group?: 'switch' | 'advanced' | 'note';
|
||||
/** Whether this field turns an action on or off, as opposed to tuning one. */
|
||||
decides_action?: boolean;
|
||||
}
|
||||
|
||||
/** One condition the chosen pipeline places on its own tunables. The backend
|
||||
* owns the rules — including the wording each one triggers — so the panel never
|
||||
* decides on its own what a set of settings may or may not be. */
|
||||
export interface ImagePipelineRule {
|
||||
at_least_one: string[];
|
||||
/** i18n key of this rule's own message, translated at render time. */
|
||||
message_key: string;
|
||||
/** Which control to point at; defaults to the first of at_least_one. */
|
||||
field?: string;
|
||||
}
|
||||
|
||||
export interface ImagePipelineSpec {
|
||||
id: string;
|
||||
name: string;
|
||||
/** How the pipeline works, shown under the pick; i18n overlays on top. */
|
||||
description: string;
|
||||
fields: ImagePipelineField[];
|
||||
/** Conditions over those fields. Empty means the pipeline accepts any of it. */
|
||||
rules?: ImagePipelineRule[];
|
||||
}
|
||||
|
||||
export interface ImagePipelineViolation {
|
||||
message_key: string;
|
||||
field?: string;
|
||||
}
|
||||
|
||||
/** POST /api/v1/image-pipelines/validate: every rule of the named pipeline that
|
||||
* the given tunables break, translated by the caller rather than sent as prose.
|
||||
* `valid: true` means the backend found none. */
|
||||
export async function validateImagePipelines(
|
||||
pipelineId: string,
|
||||
params: Record<string, unknown>,
|
||||
): Promise<{ valid: boolean; violations: ImagePipelineViolation[] }> {
|
||||
const res = await post<{
|
||||
success: boolean;
|
||||
data: { valid: boolean; violations: ImagePipelineViolation[] };
|
||||
}>(`/api/v1/image-pipelines/validate`, { pipeline_id: pipelineId, params });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Fetch every registered image pipeline. The backend owns the list, so a
|
||||
// pipeline added there shows up here as an option with no frontend change. The
|
||||
// registry is global, not per-KB, hence the top-level route.
|
||||
export async function fetchImagePipelines(): Promise<ImagePipelineSpec[]> {
|
||||
const res = await get<{ success: boolean; data: ImagePipelineSpec[] }>(
|
||||
`/api/v1/image-pipelines`,
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export type VectorStoreSource = 'env' | 'user' | 'shared' | 'unavailable';
|
||||
export type VectorStoreStatus = 'available' | 'unavailable';
|
||||
|
||||
export interface KnowledgeBaseStoreView {
|
||||
vector_store_id?: string | null;
|
||||
vector_store_name?: string;
|
||||
vector_store_engine_type?: string;
|
||||
vector_store_source?: VectorStoreSource;
|
||||
vector_store_status?: VectorStoreStatus;
|
||||
}
|
||||
|
||||
export function createKnowledgeBase(data: {
|
||||
name: string;
|
||||
description?: string;
|
||||
type?: 'document' | 'faq';
|
||||
chunking_config?: any;
|
||||
image_processing_config?: ImageProcessingConfig;
|
||||
embedding_model_id?: string;
|
||||
summary_model_id?: string;
|
||||
auto_tag_config?: { enabled: boolean; model_id?: string; max_tags?: number; skip_if_tagged?: boolean };
|
||||
// Opt-in binding to a specific tenant-owned VectorStore. Omit (or
|
||||
// send undefined / empty string) to fall back to the env-configured
|
||||
// store. Immutable after creation — UpdateKnowledgeBase intentionally
|
||||
// does not accept this field.
|
||||
vector_store_id?: string;
|
||||
// Concrete tenant-owned storage instance. When omitted, the tenant default
|
||||
// backend is bound by the server at creation time.
|
||||
storage_backend_id?: string;
|
||||
vlm_config?: {
|
||||
enabled: boolean;
|
||||
model_id?: string;
|
||||
description_language?: string;
|
||||
custom_instructions?: string;
|
||||
};
|
||||
storage_provider_config?: { provider: string };
|
||||
storage_config?: any; // legacy, kept for backward compat (dual-write)
|
||||
asr_config?: {
|
||||
enabled: boolean;
|
||||
model_id?: string;
|
||||
language?: string;
|
||||
};
|
||||
extract_config?: any;
|
||||
faq_config?: { index_mode: string; question_index_mode?: string };
|
||||
wiki_config?: {
|
||||
synthesis_model_id?: string;
|
||||
max_pages_per_ingest?: number;
|
||||
extraction_granularity?: 'focused' | 'standard' | 'exhaustive';
|
||||
content_instructions?: string;
|
||||
extraction_instructions?: string;
|
||||
};
|
||||
indexing_strategy?: {
|
||||
vector_enabled: boolean;
|
||||
keyword_enabled: boolean;
|
||||
wiki_enabled: boolean;
|
||||
graph_enabled: boolean;
|
||||
};
|
||||
}) {
|
||||
return post(`/api/v1/knowledge-bases`, data);
|
||||
}
|
||||
|
||||
export function getKnowledgeBaseById(id: string, options?: { agent_id?: string; agent_source_tenant_id?: string }) {
|
||||
const query = new URLSearchParams();
|
||||
if (options?.agent_id) query.set('agent_id', options.agent_id);
|
||||
if (options?.agent_source_tenant_id) query.set('agent_source_tenant_id', options.agent_source_tenant_id);
|
||||
const qs = query.toString();
|
||||
return get(qs ? `/api/v1/knowledge-bases/${id}?${qs}` : `/api/v1/knowledge-bases/${id}`);
|
||||
}
|
||||
|
||||
export function updateKnowledgeBase(id: string, data: {
|
||||
name: string;
|
||||
description?: string;
|
||||
config?: {
|
||||
chunking_config?: any;
|
||||
image_processing_config?: ImageProcessingConfig;
|
||||
faq_config?: any;
|
||||
wiki_config?: {
|
||||
synthesis_model_id?: string;
|
||||
max_pages_per_ingest?: number;
|
||||
extraction_granularity?: 'focused' | 'standard' | 'exhaustive';
|
||||
content_instructions?: string;
|
||||
extraction_instructions?: string;
|
||||
};
|
||||
auto_tag_config?: { enabled: boolean; model_id?: string; max_tags?: number; skip_if_tagged?: boolean };
|
||||
profile_config?: KnowledgeBaseProfileConfig;
|
||||
indexing_strategy?: {
|
||||
vector_enabled: boolean;
|
||||
keyword_enabled: boolean;
|
||||
wiki_enabled: boolean;
|
||||
graph_enabled: boolean;
|
||||
};
|
||||
}
|
||||
}) {
|
||||
return put(`/api/v1/knowledge-bases/${id}`, data);
|
||||
}
|
||||
|
||||
/** Opt-in automatic generation of the knowledge-base description. */
|
||||
export interface KnowledgeBaseProfileConfig {
|
||||
enabled: boolean;
|
||||
model_id?: string;
|
||||
custom_instructions?: string;
|
||||
}
|
||||
|
||||
export interface KnowledgeBaseProfileNamedCount {
|
||||
name: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Machine-generated knowledge-base description. Derived from per-document
|
||||
* profiles; never overwrites the user-authored description.
|
||||
*/
|
||||
export interface KnowledgeBaseProfile {
|
||||
gist?: string;
|
||||
topics?: string[];
|
||||
typical_questions?: string[];
|
||||
stats?: {
|
||||
document_count: number;
|
||||
profiled_count: number;
|
||||
file_types?: KnowledgeBaseProfileNamedCount[];
|
||||
tags?: KnowledgeBaseProfileNamedCount[];
|
||||
raw_topics?: KnowledgeBaseProfileNamedCount[];
|
||||
doc_types?: KnowledgeBaseProfileNamedCount[];
|
||||
folders?: string[];
|
||||
earliest_at?: string;
|
||||
latest_at?: string;
|
||||
};
|
||||
aggregate_hash?: string;
|
||||
status?: 'ready' | 'empty' | 'failed' | string;
|
||||
error?: string;
|
||||
model_id?: string;
|
||||
generated_at?: string;
|
||||
}
|
||||
|
||||
/** Regenerates the AI description of a knowledge base synchronously. */
|
||||
export function generateKnowledgeBaseProfile(id: string) {
|
||||
return post(`/api/v1/knowledge-bases/${id}/profile/generate`, {});
|
||||
}
|
||||
|
||||
export function rebuildKBIndex(kbId: string) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/rebuild-index`, {});
|
||||
}
|
||||
|
||||
export function deleteKnowledgeBase(id: string) {
|
||||
return del(`/api/v1/knowledge-bases/${id}`);
|
||||
}
|
||||
|
||||
export function copyKnowledgeBase(data: { source_id: string; target_id?: string }) {
|
||||
return post(`/api/v1/knowledge-bases/copy`, data);
|
||||
}
|
||||
|
||||
export function duplicateKnowledgeBase(id: string) {
|
||||
return post(`/api/v1/knowledge-bases/${id}/duplicate`);
|
||||
}
|
||||
|
||||
// 获取可移动目标知识库列表(同类型、同Embedding模型)
|
||||
export function listMoveTargets(sourceKbId: string) {
|
||||
return get(`/api/v1/knowledge-bases/${sourceKbId}/move-targets`);
|
||||
}
|
||||
|
||||
// 移动知识到其他知识库
|
||||
export function moveKnowledge(data: {
|
||||
knowledge_ids: string[];
|
||||
source_kb_id: string;
|
||||
target_kb_id: string;
|
||||
mode: 'reuse_vectors' | 'reparse';
|
||||
}) {
|
||||
return post('/api/v1/knowledge/move', data);
|
||||
}
|
||||
|
||||
// 获取知识移动进度
|
||||
export function getKnowledgeMoveProgress(taskId: string) {
|
||||
return get(`/api/v1/knowledge/move/progress/${taskId}`);
|
||||
}
|
||||
|
||||
export function togglePinKnowledgeBase(id: string) {
|
||||
return put(`/api/v1/knowledge-bases/${id}/pin`);
|
||||
}
|
||||
|
||||
// 知识文件 API(基于具体知识库)
|
||||
// data.tag_ids: 可选,指定知识所属的多个标签 ID
|
||||
export function uploadKnowledgeFile(
|
||||
kbId: string,
|
||||
data: {
|
||||
file: File
|
||||
tag_ids?: string[]
|
||||
fileName?: string
|
||||
process_config?: KnowledgeProcessOverrides | string
|
||||
[key: string]: any
|
||||
} = { file: new File([], '') },
|
||||
onProgress?: (progressEvent: any) => void,
|
||||
config?: { signal?: AbortSignal },
|
||||
) {
|
||||
const formData = new FormData();
|
||||
Object.keys(data).forEach(key => {
|
||||
const value = data[key];
|
||||
if (value === undefined) return;
|
||||
if (key === 'tag_ids' && Array.isArray(value)) {
|
||||
formData.append(key, value.join(','));
|
||||
} else if (key === 'process_config' && value && typeof value !== 'string') {
|
||||
formData.append(key, JSON.stringify(value));
|
||||
} else {
|
||||
formData.append(key, value);
|
||||
}
|
||||
});
|
||||
return postUpload(`/api/v1/knowledge-bases/${kbId}/knowledge/file`, formData, onProgress, config);
|
||||
}
|
||||
|
||||
// 从URL创建知识
|
||||
// data.tag_ids: 可选,指定知识所属的多个标签 ID
|
||||
export function createKnowledgeFromURL(
|
||||
kbId: string,
|
||||
data: { url: string; enable_multimodel?: boolean; tag_ids?: string[]; process_config?: KnowledgeProcessOverrides },
|
||||
) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/knowledge/url`, data);
|
||||
}
|
||||
|
||||
// 手工创建知识
|
||||
// data.tag_ids: 可选,指定知识所属的标签 ID
|
||||
export function createManualKnowledge(
|
||||
kbId: string,
|
||||
data: {
|
||||
title: string
|
||||
content: string
|
||||
status: string
|
||||
tag_ids?: string[]
|
||||
process_config?: KnowledgeProcessOverrides
|
||||
},
|
||||
) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/knowledge/manual`, data);
|
||||
}
|
||||
|
||||
export type KnowledgeListSortField = 'updated_at' | 'created_at' | 'file_name';
|
||||
export type KnowledgeListSortOrder = 'asc' | 'desc';
|
||||
|
||||
export interface ListKnowledgeFilesParams {
|
||||
page: number;
|
||||
page_size: number;
|
||||
tag_ids?: string;
|
||||
keyword?: string;
|
||||
file_type?: string;
|
||||
parse_status?: string;
|
||||
source?: string;
|
||||
start_time?: string;
|
||||
end_time?: string;
|
||||
sort_by?: KnowledgeListSortField;
|
||||
sort_order?: KnowledgeListSortOrder;
|
||||
/**
|
||||
* 当前浏览的目录。空字符串表示知识库根目录;未定义时不按目录筛选。
|
||||
*/
|
||||
folder_path?: string;
|
||||
/** 是否同时包含 folder_path 下所有子目录中的文档。 */
|
||||
folder_recursive?: boolean;
|
||||
}
|
||||
|
||||
export function listKnowledgeFiles(kbId: string, params: ListKnowledgeFilesParams) {
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${buildListKnowledgeFilesQuery(params)}`);
|
||||
}
|
||||
|
||||
/** One node of the knowledge base folder tree. */
|
||||
export interface KnowledgeFolderNode {
|
||||
/** Canonical folder path, e.g. "docs/spec". */
|
||||
path: string;
|
||||
/** Last segment of the path, used as the row label. */
|
||||
name: string;
|
||||
/** Documents stored directly in this folder. */
|
||||
document_count: number;
|
||||
/** Documents in this folder plus every descendant folder. */
|
||||
total_count: number;
|
||||
children?: KnowledgeFolderNode[];
|
||||
}
|
||||
|
||||
export interface KnowledgeFolderTree {
|
||||
/** Documents that are not part of any uploaded folder. */
|
||||
root_document_count: number;
|
||||
/** Documents in the whole knowledge base. */
|
||||
total_document_count: number;
|
||||
folders: KnowledgeFolderNode[];
|
||||
}
|
||||
|
||||
export function listKnowledgeFolders(kbId: string) {
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/knowledge/folders`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-file documents under `folderPath` ('' = knowledge base top level). Folders
|
||||
* are derived from the stored paths, so a path that does not exist yet is
|
||||
* created by this call. Only the grouping changes; documents are not re-parsed.
|
||||
*/
|
||||
export function moveKnowledgeToFolder(kbId: string, ids: string[], folderPath: string) {
|
||||
return post('/api/v1/knowledge/folder', {
|
||||
kb_id: kbId,
|
||||
knowledge_ids: ids,
|
||||
folder_path: folderPath,
|
||||
});
|
||||
}
|
||||
|
||||
/** Rename or move a folder together with everything below it. */
|
||||
export function renameKnowledgeFolder(kbId: string, from: string, to: string) {
|
||||
return put(`/api/v1/knowledge-bases/${kbId}/knowledge/folders`, { from, to });
|
||||
}
|
||||
|
||||
export function getKnowledgeDetails(id: string, options?: { agent_id?: string; agent_source_tenant_id?: string }) {
|
||||
const query = new URLSearchParams();
|
||||
if (options?.agent_id) query.set('agent_id', options.agent_id);
|
||||
if (options?.agent_source_tenant_id) query.set('agent_source_tenant_id', options.agent_source_tenant_id);
|
||||
const qs = query.toString();
|
||||
return get(qs ? `/api/v1/knowledge/${id}?${qs}` : `/api/v1/knowledge/${id}`);
|
||||
}
|
||||
|
||||
export function updateManualKnowledge(
|
||||
id: string,
|
||||
data: { title: string; content: string; status: string; process_config?: KnowledgeProcessOverrides },
|
||||
) {
|
||||
return put(`/api/v1/knowledge/manual/${id}`, data);
|
||||
}
|
||||
|
||||
export function reparseKnowledge(id: string, data?: { process_config?: KnowledgeProcessOverrides }) {
|
||||
return post(`/api/v1/knowledge/${id}/reparse`, data);
|
||||
}
|
||||
|
||||
export function cancelKnowledgeParse(id: string) {
|
||||
return post(`/api/v1/knowledge/${id}/cancel-parse`);
|
||||
}
|
||||
|
||||
export function getKnowledgeSpans(id: string, attempt?: number) {
|
||||
const qs = attempt ? `?attempt=${attempt}` : '';
|
||||
return get(`/api/v1/knowledge/${id}/spans${qs}`);
|
||||
}
|
||||
|
||||
export function delKnowledgeDetails(id: string) {
|
||||
return del(`/api/v1/knowledge/${id}`);
|
||||
}
|
||||
|
||||
// 批量删除(同一知识库内)。后端会校验所有 id 隶属于 kb_id 且具有编辑权限。
|
||||
export function batchDeleteKnowledge(kbId: string, ids: string[]) {
|
||||
return post(`/api/v1/knowledge/batch-delete`, { kb_id: kbId, ids });
|
||||
}
|
||||
|
||||
export function downKnowledgeDetails(id: string) {
|
||||
return getDown(`/api/v1/knowledge/${id}/download`);
|
||||
}
|
||||
|
||||
// 使用已有登录和租户请求头下载 ZIP,不将凭据放入下载链接。
|
||||
export function batchDownloadKnowledge(kbId: string, ids: string[], signal?: AbortSignal): Promise<Blob> {
|
||||
return post<Blob>(`/api/v1/knowledge-bases/${encodeURIComponent(kbId)}/knowledge/batch-download`, { ids }, {
|
||||
responseType: 'blob',
|
||||
timeout: 300000,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
||||
export function previewKnowledgeFile(id: string) {
|
||||
return getDown(`/api/v1/knowledge/${id}/preview`);
|
||||
}
|
||||
|
||||
/** @param idsQueryString - query string with ids (e.g. ids=xxx&ids=yyy) */
|
||||
export function batchQueryKnowledge(idsQueryString: string, kbId?: string, agentId?: string, agentSourceTenantId?: string) {
|
||||
let qs = idsQueryString;
|
||||
if (kbId) qs += `&kb_id=${encodeURIComponent(kbId)}`;
|
||||
if (agentId) qs += `&agent_id=${encodeURIComponent(agentId)}`;
|
||||
if (agentSourceTenantId) qs += `&agent_source_tenant_id=${encodeURIComponent(agentSourceTenantId)}`;
|
||||
return get(`/api/v1/knowledge/batch?${qs}`);
|
||||
}
|
||||
|
||||
export const KNOWLEDGE_CHUNK_PAGE_SIZE = 25;
|
||||
|
||||
export function getKnowledgeDetailsCon(id: string, page: number) {
|
||||
return get(`/api/v1/chunks/${id}?page=${page}&page_size=${KNOWLEDGE_CHUNK_PAGE_SIZE}`);
|
||||
}
|
||||
|
||||
export interface ChunkEditPayload {
|
||||
content?: string;
|
||||
is_enabled?: boolean;
|
||||
expected_revision?: number;
|
||||
}
|
||||
|
||||
export function updateDocumentChunk(knowledgeId: string, chunkId: string, data: ChunkEditPayload) {
|
||||
return put(`/api/v1/chunks/${knowledgeId}/${chunkId}`, data);
|
||||
}
|
||||
|
||||
export function listChunkRevisions(knowledgeId: string, chunkId: string) {
|
||||
return get(`/api/v1/chunks/${knowledgeId}/${chunkId}/revisions`);
|
||||
}
|
||||
|
||||
export function revertDocumentChunk(knowledgeId: string, chunkId: string, revision: number, expectedRevision: number) {
|
||||
return post(`/api/v1/chunks/${knowledgeId}/${chunkId}/revert`, {
|
||||
revision,
|
||||
expected_revision: expectedRevision,
|
||||
});
|
||||
}
|
||||
|
||||
export function updateKnowledgeMetadata(knowledgeId: string, customMetadata: Record<string, unknown>) {
|
||||
return put(`/api/v1/knowledge/${knowledgeId}`, { custom_metadata: customMetadata });
|
||||
}
|
||||
|
||||
export function updateKnowledgeSummary(knowledgeId: string, description: string) {
|
||||
return put(`/api/v1/knowledge/${knowledgeId}`, { description });
|
||||
}
|
||||
|
||||
export function regenerateKnowledgeSummary(knowledgeId: string) {
|
||||
return post(`/api/v1/knowledge/${knowledgeId}/regenerate-summary`, {});
|
||||
}
|
||||
|
||||
// Get chunk by chunk_id only (new endpoint - to be added to backend)
|
||||
export function getChunkByIdOnly(chunkId: string) {
|
||||
return get(`/api/v1/chunks/by-id/${chunkId}`);
|
||||
}
|
||||
|
||||
// Delete a single generated question from a chunk by question ID
|
||||
export function deleteGeneratedQuestion(chunkId: string, questionId: string) {
|
||||
return del(`/api/v1/chunks/by-id/${chunkId}/questions`, { question_id: questionId });
|
||||
}
|
||||
|
||||
export function upsertGeneratedQuestion(chunkId: string, question: string, questionId?: string) {
|
||||
return put(`/api/v1/chunks/by-id/${chunkId}/questions`, {
|
||||
question_id: questionId || '',
|
||||
question,
|
||||
});
|
||||
}
|
||||
|
||||
export function regenerateGeneratedQuestions(chunkId: string) {
|
||||
return post(`/api/v1/chunks/by-id/${chunkId}/questions/regenerate`, {});
|
||||
}
|
||||
|
||||
export function listKnowledgeTags(
|
||||
kbId: string,
|
||||
params?: { page?: number; page_size?: number; keyword?: string },
|
||||
) {
|
||||
const query = buildQuery(params);
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/tags${query}`);
|
||||
}
|
||||
|
||||
export function createKnowledgeBaseTag(
|
||||
kbId: string,
|
||||
data: { name: string; color?: string; sort_order?: number },
|
||||
) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/tags`, data);
|
||||
}
|
||||
|
||||
export function updateKnowledgeBaseTag(
|
||||
kbId: string,
|
||||
tagId: string,
|
||||
data: { name?: string; color?: string; sort_order?: number },
|
||||
) {
|
||||
return put(`/api/v1/knowledge-bases/${kbId}/tags/${tagId}`, data);
|
||||
}
|
||||
|
||||
export function deleteKnowledgeBaseTag(kbId: string, tagSeqId: number, params?: { force?: boolean }) {
|
||||
const forceQuery = params?.force ? '?force=true' : '';
|
||||
return del(`/api/v1/knowledge-bases/${kbId}/tags/${tagSeqId}${forceQuery}`);
|
||||
}
|
||||
|
||||
export function updateKnowledgeTagBatch(data: { updates: Record<string, string[]> }) {
|
||||
return put(`/api/v1/knowledge/tags`, data);
|
||||
}
|
||||
|
||||
export function updateFAQEntryTagBatch(kbId: string, data: { updates: Record<number, number | null> }) {
|
||||
return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/tags`, data);
|
||||
}
|
||||
|
||||
const buildQuery = (params?: Record<string, any>) => {
|
||||
if (!params) return '';
|
||||
const query = new URLSearchParams();
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null || value === '') return;
|
||||
query.append(key, String(value));
|
||||
});
|
||||
const queryString = query.toString();
|
||||
return queryString ? `?${queryString}` : '';
|
||||
};
|
||||
|
||||
export function listFAQEntries(
|
||||
kbId: string,
|
||||
params?: {
|
||||
page?: number
|
||||
page_size?: number
|
||||
tag_id?: number
|
||||
tag_ids?: string
|
||||
keyword?: string
|
||||
is_enabled?: boolean
|
||||
},
|
||||
) {
|
||||
const query = buildQuery(params);
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/faq/entries${query}`);
|
||||
}
|
||||
|
||||
export function upsertFAQEntries(kbId: string, data: { entries: any[]; mode: 'append' | 'replace' }) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/faq/entries`, data);
|
||||
}
|
||||
|
||||
export function createFAQEntry(kbId: string, data: any) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/faq/entry`, data);
|
||||
}
|
||||
|
||||
export function updateFAQEntry(kbId: string, entryId: number, data: any) {
|
||||
return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/${entryId}`, data);
|
||||
}
|
||||
|
||||
// Unified batch update API - supports is_enabled, is_recommended, tag_id
|
||||
// Supports two modes:
|
||||
// 1. By entry ID: use by_id field
|
||||
// 2. By Tag: use by_tag field to apply the same update to all entries under a tag
|
||||
export interface FAQEntryFieldsUpdate {
|
||||
is_enabled?: boolean
|
||||
is_recommended?: boolean
|
||||
tag_id?: number | null
|
||||
}
|
||||
|
||||
export interface FAQEntryFieldsBatchRequest {
|
||||
by_id?: Record<number, FAQEntryFieldsUpdate>
|
||||
by_tag?: Record<number, FAQEntryFieldsUpdate>
|
||||
exclude_ids?: number[]
|
||||
}
|
||||
|
||||
export function updateFAQEntryFieldsBatch(kbId: string, data: FAQEntryFieldsBatchRequest) {
|
||||
return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/fields`, data);
|
||||
}
|
||||
|
||||
export function deleteFAQEntries(kbId: string, ids: number[]) {
|
||||
return del(`/api/v1/knowledge-bases/${kbId}/faq/entries`, { ids });
|
||||
}
|
||||
|
||||
export function searchFAQEntries(
|
||||
kbId: string,
|
||||
data: {
|
||||
query_text: string
|
||||
vector_threshold?: number
|
||||
match_count?: number
|
||||
}
|
||||
) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/faq/search`, data);
|
||||
}
|
||||
|
||||
// Export FAQ entries as CSV or JSON file
|
||||
export async function exportFAQEntries(kbId: string, format: 'csv' | 'json' = 'csv'): Promise<Blob> {
|
||||
const suffix = format === 'json' ? '?format=json' : ''
|
||||
const response = await getDown(`/api/v1/knowledge-bases/${kbId}/faq/entries/export${suffix}`)
|
||||
return response as unknown as Blob
|
||||
}
|
||||
|
||||
// FAQ Import Progress API
|
||||
export interface FAQBlockedEntry {
|
||||
index: number
|
||||
standard_question: string
|
||||
reason: string
|
||||
}
|
||||
|
||||
export interface FAQSuccessEntry {
|
||||
index: number
|
||||
seq_id: number
|
||||
tag_id?: number
|
||||
tag_name?: string
|
||||
standard_question: string
|
||||
}
|
||||
|
||||
export interface FAQImportProgress {
|
||||
task_id: string
|
||||
kb_id: string
|
||||
knowledge_id: string
|
||||
status: 'pending' | 'processing' | 'completed' | 'failed'
|
||||
progress: number
|
||||
total: number
|
||||
processed: number
|
||||
blocked: number
|
||||
blocked_entries?: FAQBlockedEntry[]
|
||||
success_entries?: FAQSuccessEntry[]
|
||||
message: string
|
||||
error: string
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
export function getFAQImportProgress(taskId: string) {
|
||||
return get(`/api/v1/faq/import/progress/${taskId}`);
|
||||
}
|
||||
|
||||
export function updateFAQImportResultDisplayStatus(knowledgeBaseId: string, displayStatus: 'open' | 'close') {
|
||||
return put(`/api/v1/knowledge-bases/${knowledgeBaseId}/faq/import/last-result/display`, {
|
||||
display_status: displayStatus
|
||||
});
|
||||
}
|
||||
|
||||
export function searchKnowledge(
|
||||
keyword: string,
|
||||
offset = 0,
|
||||
limit = 20,
|
||||
fileTypes?: string[],
|
||||
options?: { agent_id?: string; agent_source_tenant_id?: string; recent?: boolean }
|
||||
) {
|
||||
const query = new URLSearchParams();
|
||||
if (keyword) {
|
||||
query.set('keyword', keyword);
|
||||
}
|
||||
query.set('offset', String(offset));
|
||||
query.set('limit', String(limit));
|
||||
if (fileTypes && fileTypes.length > 0) {
|
||||
query.set('file_types', fileTypes.join(','));
|
||||
}
|
||||
if (options?.agent_id) query.set('agent_id', options.agent_id);
|
||||
if (options?.agent_source_tenant_id) query.set('agent_source_tenant_id', options.agent_source_tenant_id);
|
||||
if (options?.recent) query.set('recent', 'true');
|
||||
return get(`/api/v1/knowledge/search?${query.toString()}`);
|
||||
}
|
||||
|
||||
export function knowledgeSemanticSearch(data: {
|
||||
query: string;
|
||||
knowledge_base_ids?: string[];
|
||||
knowledge_ids?: string[];
|
||||
}) {
|
||||
return post('/api/v1/knowledge-search', data);
|
||||
}
|
||||
|
||||
export function batchReparseKnowledge(kbId: string, ids: string[], processConfig?: KnowledgeProcessOverrides) {
|
||||
return post(`/api/v1/knowledge/batch-reparse`, {
|
||||
kb_id: kbId,
|
||||
ids,
|
||||
process_config: processConfig,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { buildListKnowledgeFilesQuery } from './knowledgeFileListQuery';
|
||||
|
||||
test('知识文件列表请求会传递排序字段和方向', () => {
|
||||
const query = new URLSearchParams(buildListKnowledgeFilesQuery({
|
||||
page: 2,
|
||||
page_size: 35,
|
||||
sort_by: 'file_name',
|
||||
sort_order: 'asc',
|
||||
folder_path: '',
|
||||
}));
|
||||
|
||||
assert.equal(query.get('page'), '2');
|
||||
assert.equal(query.get('page_size'), '35');
|
||||
assert.equal(query.get('sort_by'), 'file_name');
|
||||
assert.equal(query.get('sort_order'), 'asc');
|
||||
assert.equal(query.get('folder_path'), '');
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ListKnowledgeFilesParams } from './index';
|
||||
|
||||
export function buildListKnowledgeFilesQuery(params: ListKnowledgeFilesParams): string {
|
||||
const query = new URLSearchParams();
|
||||
query.append('page', String(params.page));
|
||||
query.append('page_size', String(params.page_size));
|
||||
if (params.tag_ids) query.append('tag_ids', params.tag_ids);
|
||||
if (params.keyword) query.append('keyword', params.keyword);
|
||||
if (params.file_type) query.append('file_type', params.file_type);
|
||||
if (params.parse_status) query.append('parse_status', params.parse_status);
|
||||
if (params.source) query.append('source', params.source);
|
||||
if (params.start_time) query.append('start_time', params.start_time);
|
||||
if (params.end_time) query.append('end_time', params.end_time);
|
||||
if (params.sort_by) query.append('sort_by', params.sort_by);
|
||||
if (params.sort_order) query.append('sort_order', params.sort_order);
|
||||
if (params.folder_path !== undefined) {
|
||||
query.append('folder_path', params.folder_path);
|
||||
if (params.folder_recursive) query.append('folder_recursive', 'true');
|
||||
}
|
||||
return query.toString();
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
export type McpEndpointToolGroup = 'retrieve' | 'chat' | 'wiki' | 'ingest'
|
||||
|
||||
export interface McpEndpoint {
|
||||
id: string
|
||||
tenant_id: number
|
||||
name: string
|
||||
description: string
|
||||
enabled: boolean
|
||||
token_hint: string
|
||||
knowledge_base_ids: string[]
|
||||
tools: string[]
|
||||
default_agent_id: string
|
||||
rate_limit_per_minute: number
|
||||
/** Public path the MCP client connects to, relative to the server origin. */
|
||||
path: string
|
||||
last_used_at?: string | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
/** Only present on create / rotate responses; shown once. */
|
||||
token?: string
|
||||
}
|
||||
|
||||
export interface McpEndpointToolDefinition {
|
||||
name: string
|
||||
group: McpEndpointToolGroup
|
||||
destructive: boolean
|
||||
}
|
||||
|
||||
export interface McpEndpointToolCatalog {
|
||||
groups: McpEndpointToolGroup[]
|
||||
tools: McpEndpointToolDefinition[]
|
||||
default_tools: string[]
|
||||
}
|
||||
|
||||
export interface McpEndpointPayload {
|
||||
name?: string
|
||||
description?: string
|
||||
enabled?: boolean
|
||||
knowledge_base_ids?: string[]
|
||||
tools?: string[]
|
||||
default_agent_id?: string
|
||||
rate_limit_per_minute?: number
|
||||
}
|
||||
|
||||
interface Envelope<T> {
|
||||
success: boolean
|
||||
data: T
|
||||
}
|
||||
|
||||
export function listMcpEndpoints() {
|
||||
return get<Envelope<McpEndpoint[]>>('/api/v1/mcp-endpoints')
|
||||
}
|
||||
|
||||
export function getMcpEndpointToolCatalog() {
|
||||
return get<Envelope<McpEndpointToolCatalog>>('/api/v1/mcp-endpoints/tools')
|
||||
}
|
||||
|
||||
export function createMcpEndpoint(data: McpEndpointPayload) {
|
||||
return post<Envelope<McpEndpoint>>('/api/v1/mcp-endpoints', data)
|
||||
}
|
||||
|
||||
export function updateMcpEndpoint(id: string, data: McpEndpointPayload) {
|
||||
return put<Envelope<McpEndpoint>>(`/api/v1/mcp-endpoints/${id}`, data)
|
||||
}
|
||||
|
||||
export function deleteMcpEndpoint(id: string) {
|
||||
return del(`/api/v1/mcp-endpoints/${id}`)
|
||||
}
|
||||
|
||||
export function rotateMcpEndpointToken(id: string) {
|
||||
return post<Envelope<McpEndpoint>>(`/api/v1/mcp-endpoints/${id}/rotate-token`, {})
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
export interface MCPService {
|
||||
id: string
|
||||
tenant_id?: number
|
||||
name: string
|
||||
description: string
|
||||
usage_instructions?: string
|
||||
enabled: boolean
|
||||
transport_type: 'sse' | 'http-streamable' | 'stdio'
|
||||
url?: string // Optional: required for SSE/HTTP Streamable
|
||||
headers?: Record<string, string>
|
||||
auth_config?: {
|
||||
// Authentication strategy. Empty/absent means none. "oauth" enables the
|
||||
// per-user OAuth2 authorization-code flow (zero-config: discovery +
|
||||
// dynamic client registration).
|
||||
auth_type?: '' | 'api_key' | 'bearer' | 'oauth'
|
||||
// Secret fields (api_key, token) are NEVER returned by the server in
|
||||
// this shape — they live behind the /credentials subresource. The
|
||||
// optional-property typing remains so create-mode payloads can still
|
||||
// carry them in the initial POST body.
|
||||
api_key?: string
|
||||
// Header name carrying api_key when auth_type is "api_key". Non-secret;
|
||||
// empty defaults to "X-API-Key". Lets services expecting the key in a
|
||||
// different header (e.g. raw token in "Authorization") work.
|
||||
api_key_header?: string
|
||||
token?: string
|
||||
custom_headers?: Record<string, string>
|
||||
// OAuth-only, non-secret configuration.
|
||||
scopes?: string[]
|
||||
auth_server_metadata_url?: string
|
||||
// OAuth client registered with the authorization server ahead of time.
|
||||
// Empty means dynamic client registration. Non-secret.
|
||||
client_id?: string
|
||||
// Secret of client_id. Like api_key it is never returned; edits go
|
||||
// through the /credentials subresource.
|
||||
client_secret?: string
|
||||
}
|
||||
advanced_config?: {
|
||||
timeout?: number
|
||||
retry_count?: number
|
||||
retry_delay?: number
|
||||
}
|
||||
stdio_config?: {
|
||||
command: 'uvx' | 'npx' // Command: uvx or npx
|
||||
args: string[] // Command arguments array
|
||||
}
|
||||
env_vars?: Record<string, string> // Environment variables for stdio transport
|
||||
is_builtin?: boolean // Whether this is a builtin MCP service
|
||||
// Per-field "configured?" map embedded on the main response (server-side
|
||||
// dto.MCPServiceResponse.Credentials). Drives the CredentialResource card
|
||||
// without a follow-up GET. Absent for builtin services.
|
||||
credentials?: Record<McpCredentialField, CredentialFieldMetadata>
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
catalog?: {
|
||||
tool_count: number
|
||||
stale: boolean
|
||||
synced_at: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface MCPTool {
|
||||
name: string
|
||||
description: string
|
||||
inputSchema: Record<string, any>
|
||||
require_approval?: boolean
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export interface MCPToolApprovalRow {
|
||||
id: string
|
||||
tenant_id?: number
|
||||
service_id: string
|
||||
tool_name: string
|
||||
require_approval: boolean
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export interface MCPResource {
|
||||
uri: string
|
||||
name: string
|
||||
description?: string
|
||||
mimeType?: string
|
||||
}
|
||||
|
||||
export interface MCPTestResult {
|
||||
success: boolean
|
||||
message?: string
|
||||
description?: string
|
||||
// Set when the server requires OAuth (RFC 9728) but the service was not
|
||||
// configured for it — the UI guides the user to switch to OAuth 2.0.
|
||||
oauth_required?: boolean
|
||||
tools?: MCPTool[]
|
||||
resources?: MCPResource[]
|
||||
}
|
||||
|
||||
// List all MCP services
|
||||
/** Locates a shared agent's source workspace, same parameters as a chat request. */
|
||||
export interface MCPAgentScope {
|
||||
agentId?: string
|
||||
/** Set only for a shared agent; left empty for this workspace's own agents. */
|
||||
sourceTenantId?: string | number
|
||||
}
|
||||
|
||||
// Lists MCP services.
|
||||
//
|
||||
// With a shared agent, the result is the services THAT agent can be @mentioned
|
||||
// with: they live in its owner's workspace and none of their ids match anything
|
||||
// in the caller's. Those rows also carry a narrowed field set — no URL,
|
||||
// headers or credential metadata, which describe how the owner wired the
|
||||
// service up — since the picker needs nothing more.
|
||||
export async function listMCPServices(agent?: MCPAgentScope): Promise<MCPService[]> {
|
||||
const params: Record<string, string> = {}
|
||||
if (agent?.agentId && agent?.sourceTenantId) {
|
||||
params.agent_id = agent.agentId
|
||||
params.agent_source_tenant_id = String(agent.sourceTenantId)
|
||||
}
|
||||
const response: any = await get('/api/v1/mcp-services', { params })
|
||||
return response.data || []
|
||||
}
|
||||
|
||||
// Get a single MCP service by ID
|
||||
export async function getMCPService(id: string): Promise<MCPService> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${id}`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// Create a new MCP service
|
||||
export async function createMCPService(data: Partial<MCPService>): Promise<MCPService> {
|
||||
const response: any = await post('/api/v1/mcp-services', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// Update an existing MCP service
|
||||
export async function updateMCPService(id: string, data: Partial<MCPService>): Promise<MCPService> {
|
||||
const response: any = await put(`/api/v1/mcp-services/${id}`, data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// Delete an MCP service
|
||||
export async function deleteMCPService(id: string): Promise<void> {
|
||||
await del(`/api/v1/mcp-services/${id}`)
|
||||
}
|
||||
|
||||
// Test MCP service connection
|
||||
export async function testMCPService(id: string): Promise<MCPTestResult> {
|
||||
const response: any = await post(`/api/v1/mcp-services/${id}/test`, {})
|
||||
// 后端返回格式: { success: true, data: MCPTestResult }
|
||||
// response interceptor 已经返回了 data,所以 response 就是 { success: true, data: {...} }
|
||||
if (response && response.data) {
|
||||
return response.data
|
||||
}
|
||||
// 如果格式不对,尝试直接返回 response(可能是直接返回的数据)
|
||||
return response
|
||||
}
|
||||
|
||||
// Get tools from an MCP service
|
||||
export async function getMCPServiceTools(id: string): Promise<MCPTool[]> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${id}/tools`)
|
||||
return response.data || []
|
||||
}
|
||||
|
||||
// Get resources from an MCP service
|
||||
export async function getMCPServiceResources(id: string): Promise<MCPResource[]> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${id}/resources`)
|
||||
return response.data || []
|
||||
}
|
||||
|
||||
/** Persisted per-tool human-approval flags (issue #1173) */
|
||||
export async function getMCPToolApprovals(serviceId: string): Promise<MCPToolApprovalRow[]> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${serviceId}/tool-approvals`)
|
||||
return response.data || []
|
||||
}
|
||||
|
||||
export async function setMCPToolApproval(serviceId: string, toolName: string, requireApproval: boolean): Promise<void> {
|
||||
await put(`/api/v1/mcp-services/${serviceId}/tool-approvals/${encodeURIComponent(toolName)}`, {
|
||||
require_approval: requireApproval
|
||||
})
|
||||
}
|
||||
|
||||
export async function setMCPToolEnabled(serviceId: string, toolName: string, enabled: boolean): Promise<void> {
|
||||
await put(`/api/v1/mcp-services/${serviceId}/tool-approvals/${encodeURIComponent(toolName)}`, { enabled })
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Credential subresource (issue #988 follow-up).
|
||||
//
|
||||
// Secrets travel through a dedicated /credentials endpoint instead of the
|
||||
// main MCP PUT body. "Is this configured?" metadata is embedded on the main
|
||||
// MCPService response (MCPService.credentials), so there is no GET on this
|
||||
// endpoint — only PUT (write) and DELETE (clear). Both trigger an MCP
|
||||
// client reconnect server-side.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
export type McpCredentialField = 'api_key' | 'token' | 'client_secret'
|
||||
|
||||
export interface CredentialFieldMetadata {
|
||||
configured: boolean
|
||||
}
|
||||
|
||||
export interface McpCredentialsResponse {
|
||||
fields: Record<McpCredentialField, CredentialFieldMetadata>
|
||||
}
|
||||
|
||||
export async function putMCPCredentials(
|
||||
serviceId: string,
|
||||
body: Partial<Record<McpCredentialField, string>>
|
||||
): Promise<McpCredentialsResponse> {
|
||||
const response: any = await put(`/api/v1/mcp-services/${serviceId}/credentials`, body)
|
||||
return (response.data ?? response) as McpCredentialsResponse
|
||||
}
|
||||
|
||||
export async function deleteMCPCredentialField(
|
||||
serviceId: string,
|
||||
field: McpCredentialField
|
||||
): Promise<void> {
|
||||
await del(`/api/v1/mcp-services/${serviceId}/credentials/${field}`)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Per-user OAuth2 authorization-code flow.
|
||||
//
|
||||
// The user authorizes a service once; the backend stores their access/refresh
|
||||
// token (per tenant + user + service) and refreshes it transparently. The
|
||||
// callback is a public backend route that the third-party authorization
|
||||
// server redirects to.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
// Path of the public backend OAuth callback (registered outside /mcp-services
|
||||
// to avoid a route conflict, and allow-listed for no-auth in the backend).
|
||||
export const MCP_OAUTH_CALLBACK_PATH = '/api/v1/mcp-oauth/callback'
|
||||
|
||||
export interface MCPOAuthAuthorization {
|
||||
authorizationUrl: string
|
||||
authorizationAttempt: string
|
||||
}
|
||||
|
||||
export type MCPOAuthTokenState = 'authorized' | 'refreshable' | 'reauth_required' | 'pending'
|
||||
|
||||
export interface MCPOAuthStatus {
|
||||
authorized: boolean
|
||||
state: MCPOAuthTokenState
|
||||
refresh_available: boolean
|
||||
expires_at?: string
|
||||
}
|
||||
|
||||
// Begin authorization for the current user. The attempt id binds polling to
|
||||
// this popup, so an older stored token cannot be mistaken for fresh consent.
|
||||
export async function getMCPOAuthAuthorizeURL(
|
||||
serviceId: string,
|
||||
body: { redirect_uri: string; frontend_redirect?: string }
|
||||
): Promise<MCPOAuthAuthorization> {
|
||||
const response: any = await post(`/api/v1/mcp-services/${serviceId}/oauth/authorize-url`, body)
|
||||
const data = response.data ?? response
|
||||
return {
|
||||
authorizationUrl: data?.authorization_url ?? '',
|
||||
authorizationAttempt: data?.authorization_attempt ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
// Whether the current user has authorized this service.
|
||||
export async function getMCPOAuthStatus(
|
||||
serviceId: string,
|
||||
authorizationAttempt?: string,
|
||||
): Promise<boolean> {
|
||||
const query = authorizationAttempt
|
||||
? `?authorization_attempt=${encodeURIComponent(authorizationAttempt)}`
|
||||
: ''
|
||||
const response: any = await get(`/api/v1/mcp-services/${serviceId}/oauth/status${query}`)
|
||||
return Boolean((response.data ?? response)?.authorized)
|
||||
}
|
||||
|
||||
// Full lifecycle status for management surfaces. Expired access tokens with a
|
||||
// refresh token are "refreshable", not falsely presented as already usable.
|
||||
export async function getMCPOAuthAuthorizationStatus(serviceId: string): Promise<MCPOAuthStatus> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${serviceId}/oauth/status`)
|
||||
const data = response.data ?? response
|
||||
return {
|
||||
authorized: Boolean(data?.authorized),
|
||||
state: data?.state ?? 'reauth_required',
|
||||
refresh_available: Boolean(data?.refresh_available),
|
||||
expires_at: data?.expires_at,
|
||||
}
|
||||
}
|
||||
|
||||
// Revoke the current user's token (forces re-authorization).
|
||||
export async function revokeMCPOAuthToken(serviceId: string): Promise<void> {
|
||||
await del(`/api/v1/mcp-services/${serviceId}/oauth/token`)
|
||||
}
|
||||
|
||||
export async function resolveToolApproval(
|
||||
pendingId: string,
|
||||
body: { decision: 'approve' | 'reject'; modified_args?: Record<string, unknown>; reason?: string; allow_in_session?: boolean }
|
||||
): Promise<{ resumed: boolean }> {
|
||||
const res: any = await post(`/api/v1/agent/tool-approvals/${encodeURIComponent(pendingId)}`, body)
|
||||
// resumed: the run had been suspended and now continues on the server;
|
||||
// the client must re-attach to the message's stream.
|
||||
return { resumed: Boolean(res?.resumed) }
|
||||
}
|
||||
|
||||
// A remembered "allow for this conversation" approval.
|
||||
export interface AgentGrant {
|
||||
id: string
|
||||
scope: string
|
||||
scope_id: string
|
||||
grant_key: string
|
||||
label: string
|
||||
created_at: string
|
||||
last_used_at?: string
|
||||
}
|
||||
|
||||
// The current user's grants in a conversation, including those approved in
|
||||
// its delegated sub-tasks.
|
||||
export async function listAgentGrants(sessionId: string): Promise<AgentGrant[]> {
|
||||
const res: any = await get(`/api/v1/agent/grants?session_id=${encodeURIComponent(sessionId)}`)
|
||||
return Array.isArray(res?.data) ? res.data : []
|
||||
}
|
||||
|
||||
export async function revokeAgentGrant(id: string): Promise<void> {
|
||||
await del(`/api/v1/agent/grants/${encodeURIComponent(id)}`)
|
||||
}
|
||||
|
||||
// Answer a prompt the agent raised (ask_user, tool approval) with the kind's
|
||||
// response object.
|
||||
export async function resolveAgentPrompt(
|
||||
promptId: string,
|
||||
kind: string,
|
||||
response: Record<string, unknown>,
|
||||
): Promise<{ resumed: boolean }> {
|
||||
const res: any = await post(`/api/v1/agent/prompts/${encodeURIComponent(promptId)}`, { kind, response })
|
||||
return { resumed: Boolean(res?.resumed) }
|
||||
}
|
||||
|
||||
// Resume an agent run that paused on an in-conversation MCP OAuth prompt.
|
||||
// Call after the per-user authorization popup completes; the backend verifies
|
||||
// the token exists before unblocking the paused tool call.
|
||||
export async function resolveMCPOAuth(
|
||||
pendingId: string,
|
||||
body: { service_id: string; decision?: 'authorize' | 'cancel' }
|
||||
): Promise<void> {
|
||||
await post(`/api/v1/agent/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}`, body)
|
||||
}
|
||||
|
||||
export async function cancelMCPOAuth(pendingId: string): Promise<void> {
|
||||
await post(`/api/v1/agent/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}/cancel`, {})
|
||||
}
|
||||
|
||||
// Persisted directory: GET never opens an upstream MCP connection.
|
||||
export interface MCPMetadata {
|
||||
service_id: string
|
||||
tools: MCPTool[]
|
||||
instructions: string
|
||||
server_name: string
|
||||
server_version: string
|
||||
server_description: string
|
||||
synced_at: string
|
||||
stale: boolean
|
||||
}
|
||||
|
||||
export async function getMCPMetadata(id: string): Promise<MCPMetadata | null> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${id}/metadata`)
|
||||
return response.data ?? null
|
||||
}
|
||||
|
||||
export async function refreshMCPMetadata(id: string): Promise<MCPMetadata> {
|
||||
const response: any = await post(`/api/v1/mcp-services/${id}/metadata/refresh`, {})
|
||||
return response.data
|
||||
}
|
||||
|
||||
export async function generateMCPUsageInstructions(id: string, language: string): Promise<string> {
|
||||
const response: any = await post(`/api/v1/mcp-services/${id}/usage-instructions/generate`, { language }, { timeout: 65000 })
|
||||
return response.data.usage_instructions
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { get, put, post, del } from '@/utils/request'
|
||||
|
||||
// Kinds mirror internal/types/memory.go. profile and preference make up the
|
||||
// block injected on every turn; fact and task are pulled in only when the
|
||||
// current question matches them.
|
||||
export type MemoryKind = 'profile' | 'preference' | 'fact' | 'task' | 'interest'
|
||||
export type MemoryStatus = 'active' | 'superseded' | 'archived' | 'pending'
|
||||
export type MemoryOrigin = 'explicit' | 'extracted' | 'manual'
|
||||
|
||||
export interface MemoryItem {
|
||||
id: string
|
||||
kind: MemoryKind
|
||||
content: string
|
||||
topic: string
|
||||
importance: number
|
||||
origin: MemoryOrigin
|
||||
status: MemoryStatus
|
||||
source_session_id: string
|
||||
source_message_id: string
|
||||
valid_from: string
|
||||
invalid_at: string | null
|
||||
superseded_by: string
|
||||
last_used_at: string | null
|
||||
use_count: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
// MemorySettings is already merged server-side, so the UI never has to combine
|
||||
// a workspace switch with a personal one itself.
|
||||
export interface MemorySettings {
|
||||
workspace_enabled: boolean
|
||||
user_enabled: boolean
|
||||
effective: boolean
|
||||
write_mode: string
|
||||
item_count: number
|
||||
max_items: number
|
||||
}
|
||||
|
||||
export interface MemoryConfig {
|
||||
enabled: boolean
|
||||
write_mode: 'explicit_only' | 'auto'
|
||||
extract_model_id: string
|
||||
max_items: number
|
||||
/** Debounce before distillation runs, in seconds. */
|
||||
extract_delay_seconds: number
|
||||
/** Floor between two distillation runs for one person, in seconds. */
|
||||
extract_min_interval_seconds: number
|
||||
/** Workspace-specific rules appended to the distillation prompt. */
|
||||
extract_instructions: string
|
||||
/** How many conversations must touch a topic before it becomes an interest. */
|
||||
interest_threshold: number
|
||||
/** Whether memory may shape retrieval, not only the answer prompt. */
|
||||
retrieval_conditioning: boolean
|
||||
/** Model used to score memory against a question. Blank = lexical matching only. */
|
||||
embedding_model_id: string
|
||||
/** Whether recall also matches on meaning, not only on wording. */
|
||||
vector_recall: boolean
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Personal memory. Every endpoint operates on the caller's own memory space,
|
||||
// which the server derives from the request principal, so none of these take
|
||||
// an owner parameter.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function getMemorySettings() {
|
||||
return get<{ success: boolean; data: MemorySettings }>('/api/v1/memory/settings')
|
||||
}
|
||||
|
||||
export function updateMemoryEnabled(enabled: boolean) {
|
||||
return put<{ success: boolean; data: MemorySettings }>('/api/v1/memory/settings', { enabled })
|
||||
}
|
||||
|
||||
export function listMemoryItems(params: { status?: MemoryStatus; limit?: number; offset?: number } = {}) {
|
||||
const query = new URLSearchParams()
|
||||
if (params.status) query.set('status', params.status)
|
||||
if (params.limit != null) query.set('limit', String(params.limit))
|
||||
if (params.offset != null) query.set('offset', String(params.offset))
|
||||
const suffix = query.toString() ? `?${query.toString()}` : ''
|
||||
return get<{ success: boolean; data: MemoryItem[]; total: number }>(`/api/v1/memory/items${suffix}`)
|
||||
}
|
||||
|
||||
/** Accept a memory the system inferred, so it starts being used. */
|
||||
export function confirmMemoryItem(id: string) {
|
||||
return post<{ success: boolean; data: MemoryItem }>(`/api/v1/memory/items/${id}/confirm`, {})
|
||||
}
|
||||
|
||||
/** Decline an inference. The refusal is remembered, so it is not re-proposed. */
|
||||
export function rejectMemoryItem(id: string) {
|
||||
return post<{ success: boolean }>(`/api/v1/memory/items/${id}/reject`, {})
|
||||
}
|
||||
|
||||
export function createMemoryItem(payload: { kind: MemoryKind; content: string; importance?: number }) {
|
||||
return post<{ success: boolean; data: MemoryItem }>('/api/v1/memory/items', payload)
|
||||
}
|
||||
|
||||
export function updateMemoryItem(id: string, payload: { content: string; importance: number }) {
|
||||
return put<{ success: boolean; data: MemoryItem }>(
|
||||
`/api/v1/memory/items/${encodeURIComponent(id)}`,
|
||||
payload,
|
||||
)
|
||||
}
|
||||
|
||||
export function deleteMemoryItem(id: string) {
|
||||
return del<{ success: boolean }>(`/api/v1/memory/items/${encodeURIComponent(id)}`)
|
||||
}
|
||||
|
||||
export function clearMemoryItems() {
|
||||
return del<{ success: boolean; removed: number }>('/api/v1/memory/items')
|
||||
}
|
||||
|
||||
export function exportMemoryItems() {
|
||||
return get<{ success: boolean; total: number; data: MemoryItem[] }>('/api/v1/memory/export')
|
||||
}
|
||||
|
||||
/** Why a review changed nothing. Empty when it did change something. */
|
||||
export type MemoryConsolidationSkip =
|
||||
| 'too_few_items'
|
||||
| 'no_candidates'
|
||||
| 'model_unavailable'
|
||||
| 'model_declined'
|
||||
|
||||
export interface MemoryConsolidationResult {
|
||||
merged: number
|
||||
demoted: number
|
||||
expired: number
|
||||
reviewed: number
|
||||
candidates: number
|
||||
skipped?: MemoryConsolidationSkip
|
||||
}
|
||||
|
||||
/** Merge near-duplicates now, without waiting for the daily distillation pass. */
|
||||
export function consolidateMemory() {
|
||||
return post<{ success: boolean; data: MemoryConsolidationResult }>('/api/v1/memory/consolidate', {})
|
||||
}
|
||||
|
||||
export interface MemoryTopic {
|
||||
id: string
|
||||
topic: string
|
||||
aliases: string[]
|
||||
hits: number
|
||||
threshold: number
|
||||
last_seen_at: string
|
||||
}
|
||||
|
||||
export function listMemoryTopics(params: { limit?: number; offset?: number } = {}) {
|
||||
const query = new URLSearchParams()
|
||||
if (params.limit != null) query.set('limit', String(params.limit))
|
||||
if (params.offset != null) query.set('offset', String(params.offset))
|
||||
const suffix = query.toString() ? `?${query.toString()}` : ''
|
||||
return get<{ success: boolean; data: MemoryTopic[]; total: number }>(`/api/v1/memory/topics${suffix}`)
|
||||
}
|
||||
|
||||
/** Promote a counted topic into a long-term interest without waiting. */
|
||||
export function promoteMemoryTopic(id: string) {
|
||||
return post<{ success: boolean; data: MemoryItem }>(
|
||||
`/api/v1/memory/topics/${encodeURIComponent(id)}/promote`,
|
||||
{},
|
||||
)
|
||||
}
|
||||
|
||||
/** Stop tracking a topic. The refusal is remembered so it is not auto-promoted later. */
|
||||
export function deleteMemoryTopic(id: string) {
|
||||
return del<{ success: boolean }>(`/api/v1/memory/topics/${encodeURIComponent(id)}`)
|
||||
}
|
||||
|
||||
export interface MemoryDoc {
|
||||
id: string
|
||||
knowledge_id: string
|
||||
knowledge_base_id: string
|
||||
title: string
|
||||
hits: number
|
||||
last_used_at: string
|
||||
}
|
||||
|
||||
export function listMemoryDocuments(params: { limit?: number; offset?: number } = {}) {
|
||||
const query = new URLSearchParams()
|
||||
if (params.limit != null) query.set('limit', String(params.limit))
|
||||
if (params.offset != null) query.set('offset', String(params.offset))
|
||||
const suffix = query.toString() ? `?${query.toString()}` : ''
|
||||
return get<{ success: boolean; data: MemoryDoc[]; total: number }>(`/api/v1/memory/documents${suffix}`)
|
||||
}
|
||||
|
||||
/** Stop using one document as a personal retrieval signal. */
|
||||
export function deleteMemoryDocument(id: string) {
|
||||
return del<{ success: boolean }>(`/api/v1/memory/documents/${encodeURIComponent(id)}`)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Workspace configuration, stored on the tenant like the other KV configs.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function getTenantMemoryConfig() {
|
||||
return get<{ success: boolean; data: MemoryConfig }>('/api/v1/tenants/kv/memory-config')
|
||||
}
|
||||
|
||||
export function updateTenantMemoryConfig(config: MemoryConfig) {
|
||||
return put<{ success: boolean; data: MemoryConfig }>('/api/v1/tenants/kv/memory-config', config)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { get, post } from '@/utils/request'
|
||||
|
||||
export interface MessageSuggestionItem {
|
||||
id: string
|
||||
text: string
|
||||
category?: 'clarify' | 'deepen' | 'action'
|
||||
source: 'model' | 'faq' | 'document' | 'wiki' | string
|
||||
knowledge_base_ids?: string[]
|
||||
}
|
||||
|
||||
export interface MessageSuggestionSet {
|
||||
id: string
|
||||
session_id: string
|
||||
assistant_message_id: string
|
||||
status: 'generating' | 'ready' | 'suppressed' | 'failed'
|
||||
allow_regenerate: boolean
|
||||
suppression_reason?: string
|
||||
questions: MessageSuggestionItem[]
|
||||
generated_at?: string
|
||||
}
|
||||
|
||||
export function ensureMessageSuggestions(sessionId: string, messageId: string, regenerate = false) {
|
||||
return post<{ data: MessageSuggestionSet }>(
|
||||
`/api/v1/sessions/${sessionId}/messages/${messageId}/suggestions`,
|
||||
{ regenerate },
|
||||
)
|
||||
}
|
||||
|
||||
export function getMessageSuggestions(sessionId: string, messageId: string) {
|
||||
return get<{ data: MessageSuggestionSet }>(
|
||||
`/api/v1/sessions/${sessionId}/messages/${messageId}/suggestions`,
|
||||
)
|
||||
}
|
||||
|
||||
export function recordMessageSuggestionEvent(
|
||||
sessionId: string,
|
||||
suggestionSetId: string,
|
||||
eventType: 'impression' | 'click' | 'dismiss',
|
||||
questionId = '',
|
||||
) {
|
||||
return post(
|
||||
`/api/v1/sessions/${sessionId}/suggestion-events`,
|
||||
{ suggestion_set_id: suggestionSetId, question_id: questionId, event_type: eventType },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import { get, post, postUpload, put, del } from '../../utils/request';
|
||||
import i18n from '@/i18n'
|
||||
import { ModelInUseError, modelInUseErrorFromRequest } from './modelUsage'
|
||||
|
||||
export * from './modelUsage'
|
||||
|
||||
const t = (key: string) => i18n.global.t(key)
|
||||
|
||||
// Protocol-neutral thinking level. Mirrors internal/models/api.ReasoningEffort.
|
||||
export type ReasoningEffortLevel =
|
||||
| 'off'
|
||||
| 'auto'
|
||||
| 'minimal'
|
||||
| 'low'
|
||||
| 'medium'
|
||||
| 'high'
|
||||
| 'xhigh'
|
||||
| 'max'
|
||||
|
||||
// Catalog view of a saved chat/VLM model. Mirrors internal/models/catalog.Capabilities.
|
||||
// thinking_levels: empty array = the model cannot be asked to think.
|
||||
export interface ModelCapabilities {
|
||||
provider: string;
|
||||
api: string;
|
||||
cataloged: boolean;
|
||||
reasoning: boolean;
|
||||
thinking_levels: ReasoningEffortLevel[];
|
||||
thinking_format: string;
|
||||
input?: string[];
|
||||
context_window?: number;
|
||||
max_output_tokens?: number;
|
||||
max_tokens_field?: string;
|
||||
}
|
||||
|
||||
// Per-row override of a catalog entry. Mirrors internal/types.ModelSpecOverride.
|
||||
// compat is the flat, protocol-specific object defined in
|
||||
// internal/models/api/*_settings.go (free-form JSON).
|
||||
export interface ModelSpecOverride {
|
||||
api?: string;
|
||||
reasoning?: boolean;
|
||||
input?: string[];
|
||||
context_window?: number;
|
||||
max_output_tokens?: number;
|
||||
thinking_levels?: Record<string, string | null>;
|
||||
compat?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// 模型类型定义
|
||||
export interface ModelConfig {
|
||||
id?: string;
|
||||
tenant_id?: number;
|
||||
name: string;
|
||||
display_name?: string;
|
||||
type: 'KnowledgeQA' | 'Embedding' | 'Rerank' | 'VLLM' | 'ASR';
|
||||
source: 'local' | 'remote';
|
||||
description?: string;
|
||||
parameters: {
|
||||
base_url?: string;
|
||||
api_key?: string;
|
||||
provider?: string; // Provider identifier: openai, aliyun, zhipu, generic
|
||||
embedding_parameters?: {
|
||||
dimension?: number;
|
||||
truncate_prompt_tokens?: number;
|
||||
supports_dimension_override?: boolean;
|
||||
};
|
||||
interface_type?: 'ollama' | 'openai'; // VLLM专用
|
||||
parameter_size?: string; // Ollama模型参数大小 (e.g., "7B", "13B", "70B")
|
||||
extra_config?: Record<string, string>; // Provider-specific configuration
|
||||
// 自定义 HTTP 请求头(类似 Python OpenAI SDK 的 extra_headers),
|
||||
// 会在调用远程模型 API 时附加到每个请求上。Authorization、Content-Type 等保留头会被忽略。
|
||||
custom_headers?: Record<string, string>;
|
||||
supports_vision?: boolean; // Whether the model accepts image/multimodal input
|
||||
// 对话/VLM 的上下文窗口(token)。0 或不填表示使用后端默认 200000。
|
||||
context_window?: number;
|
||||
max_output_tokens?: number;
|
||||
// 后台任务(入库/富化)对该模型的并发上限,按模型 ID 全副本共享。
|
||||
// 0 或不填表示沿用全局默认(model.max_concurrency);仅对 chat/embedding/vllm 生效。
|
||||
max_concurrency?: number;
|
||||
app_id?: string;
|
||||
// Secret fields (api_key, app_secret) are never returned by the server in
|
||||
// this shape — they live behind the /credentials subresource. They are
|
||||
// kept on the type so create-mode payloads can still carry them in the
|
||||
// initial POST body.
|
||||
app_secret?: string;
|
||||
// Per-model catalog override (protocol, limits, protocol compat knobs).
|
||||
spec?: ModelSpecOverride;
|
||||
};
|
||||
// Catalog view (chat / VLM remote models only): protocol, thinking levels,
|
||||
// context window. Computed by the backend from provider + name + overrides.
|
||||
capabilities?: ModelCapabilities;
|
||||
is_default?: boolean;
|
||||
is_builtin?: boolean;
|
||||
status?: string;
|
||||
// Per-field configured? metadata from the main response. For builtin
|
||||
// models it is returned only to system administrators.
|
||||
credentials?: Record<ModelCredentialField, { configured: boolean }>;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
deleted_at?: string | null;
|
||||
}
|
||||
|
||||
// 复制模型。只提交展示名;name 与凭证由服务端从源模型复制。
|
||||
export function copyModelConfig(id: string, displayName: string): Promise<ModelConfig> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post(`/api/v1/models/${id}/copy`, { display_name: displayName })
|
||||
.then((response: any) => {
|
||||
if (response.success && response.data) {
|
||||
resolve(response.data);
|
||||
} else {
|
||||
reject(new Error(response.message || ''));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to copy model:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 创建模型
|
||||
export function createModel(data: ModelConfig): Promise<ModelConfig> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/models', data)
|
||||
.then((response: any) => {
|
||||
if (response.success && response.data) {
|
||||
resolve(response.data);
|
||||
} else {
|
||||
reject(new Error(response.message || t('error.model.createFailed')));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to create model:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 获取模型列表
|
||||
export function listModels(type?: string): Promise<ModelConfig[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = `/api/v1/models`;
|
||||
get(url)
|
||||
.then((response: any) => {
|
||||
if (response.success && response.data) {
|
||||
if (type) {
|
||||
response.data = response.data.filter((item: ModelConfig) => item.type === type);
|
||||
}
|
||||
resolve(response.data);
|
||||
} else {
|
||||
resolve([]);
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to list models:', error);
|
||||
// 抛出而非吞掉:调用方(含缓存层)才能区分「真失败」与「成功但无模型」,
|
||||
// 避免把一次瞬时失败的空结果缓存下来。各 UI 调用点均已 try/catch 兜底。
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 获取单个模型
|
||||
export function getModel(id: string): Promise<ModelConfig> {
|
||||
return new Promise((resolve, reject) => {
|
||||
get(`/api/v1/models/${id}`)
|
||||
.then((response: any) => {
|
||||
if (response.success && response.data) {
|
||||
resolve(response.data);
|
||||
} else {
|
||||
reject(new Error(response.message || t('error.model.getFailed')));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to get model:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 更新模型
|
||||
export function updateModel(id: string, data: Partial<ModelConfig>): Promise<ModelConfig> {
|
||||
return new Promise((resolve, reject) => {
|
||||
put(`/api/v1/models/${id}`, data)
|
||||
.then((response: any) => {
|
||||
if (response.success && response.data) {
|
||||
resolve(response.data);
|
||||
} else {
|
||||
reject(new Error(response.message || t('error.model.updateFailed')));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to update model:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 删除模型
|
||||
export function deleteModel(id: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
del(`/api/v1/models/${id}`)
|
||||
.then((response: any) => {
|
||||
if (response.success) {
|
||||
resolve();
|
||||
} else {
|
||||
const conflict = modelInUseErrorFromRequest(response)
|
||||
if (conflict) {
|
||||
reject(conflict)
|
||||
return
|
||||
}
|
||||
reject(new Error(response.message || t('error.model.deleteFailed')));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to delete model:', error);
|
||||
if (error instanceof ModelInUseError) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
const conflict = modelInUseErrorFromRequest(error)
|
||||
if (conflict) {
|
||||
reject(conflict)
|
||||
return
|
||||
}
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export interface ModelDebugOptions {
|
||||
system_prompt?: string
|
||||
temperature?: number
|
||||
top_p?: number
|
||||
max_tokens?: number
|
||||
thinking?: boolean
|
||||
// Graded thinking level; takes precedence over the boolean when set.
|
||||
reasoning_effort?: ReasoningEffortLevel | string
|
||||
// Embedding only: score `documents` (and the file) against `input` as a query.
|
||||
similarity?: boolean
|
||||
}
|
||||
|
||||
export interface ModelDebugResult {
|
||||
ok: boolean
|
||||
elapsed_ms: number
|
||||
request: Record<string, unknown>
|
||||
raw_response: unknown
|
||||
observations: Record<string, unknown>
|
||||
error?: string
|
||||
}
|
||||
|
||||
export async function debugModel(
|
||||
id: string,
|
||||
data: {
|
||||
input?: string
|
||||
documents?: string[]
|
||||
options?: ModelDebugOptions
|
||||
file?: File | null
|
||||
},
|
||||
): Promise<ModelDebugResult> {
|
||||
const form = new FormData()
|
||||
form.append('input', data.input || '')
|
||||
form.append('documents', JSON.stringify(data.documents || []))
|
||||
form.append('options', JSON.stringify(data.options || {}))
|
||||
if (data.file) form.append('file', data.file)
|
||||
const response: any = await postUpload(
|
||||
`/api/v1/models/${id}/debug`,
|
||||
form,
|
||||
undefined,
|
||||
{ timeout: 300000 },
|
||||
)
|
||||
if (response?.success && response?.data) return response.data
|
||||
throw new Error(response?.message || t('error.model.getFailed'))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Model credential subresource. See mcp-service.ts for the matching MCP API
|
||||
// shape and the design notes in internal/handler/dto/mcp.go.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
export type ModelCredentialField = 'api_key' | 'app_secret'
|
||||
|
||||
export interface ModelCredentialsResponse {
|
||||
fields: Record<ModelCredentialField, { configured: boolean }>
|
||||
}
|
||||
|
||||
export async function putModelCredentials(
|
||||
id: string,
|
||||
body: Partial<Record<ModelCredentialField, string>>,
|
||||
): Promise<ModelCredentialsResponse> {
|
||||
const response: any = await put(`/api/v1/models/${id}/credentials`, body)
|
||||
return (response.data ?? response) as ModelCredentialsResponse
|
||||
}
|
||||
|
||||
export async function deleteModelCredentialField(
|
||||
id: string,
|
||||
field: ModelCredentialField,
|
||||
): Promise<void> {
|
||||
await del(`/api/v1/models/${id}/credentials/${field}`)
|
||||
}
|
||||
|
||||
export interface InitializeAcademyCloudRequest {
|
||||
app_id: string
|
||||
app_secret: string
|
||||
}
|
||||
|
||||
// 仅保存 AcademyCloud 凭证,不自动创建模型
|
||||
export function saveAcademyCloudCredentials(data: InitializeAcademyCloudRequest): Promise<{ success: boolean; message: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/academycloud/credentials', data)
|
||||
.then((response: any) => {
|
||||
if (response.success) {
|
||||
resolve(response)
|
||||
} else {
|
||||
reject(new Error(response.message || response.error || '凭证保存失败'))
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to save AcademyCloud credentials:', error)
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export interface AcademyCloudStatusResult {
|
||||
has_models: boolean
|
||||
needs_reinit: boolean
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export function getAcademyCloudStatus(): Promise<AcademyCloudStatusResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
get('/api/v1/models/academycloud/status')
|
||||
.then((response: any) => {
|
||||
// status 接口直接返回对象,不包在 success/data 中
|
||||
if (response && typeof response.has_models === 'boolean') {
|
||||
resolve(response)
|
||||
} else if (response?.success && response?.data) {
|
||||
resolve(response.data)
|
||||
} else {
|
||||
resolve({ has_models: false, needs_reinit: false })
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
resolve({ has_models: false, needs_reinit: false })
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
MODEL_IN_USE_ERROR_CODE,
|
||||
ModelInUseError,
|
||||
modelInUseErrorFromRequest,
|
||||
modelUsageAgentSection,
|
||||
modelUsageBindingI18nKey,
|
||||
modelUsageKnowledgeBaseSection,
|
||||
modelUsageListTruncated,
|
||||
modelUsageResourceCount,
|
||||
modelUsageResourceRoute,
|
||||
parseModelUsageDetails,
|
||||
} from './modelUsage'
|
||||
|
||||
const details = {
|
||||
knowledge_bases: [
|
||||
{ id: 'kb-1', name: 'Product docs', bindings: ['vlm_model'] },
|
||||
{ id: 'kb-2', name: 'Engineering', bindings: ['vlm_model'] },
|
||||
],
|
||||
agents: [
|
||||
{ id: 'agent-1', name: 'Support', bindings: ['chat_model', 'follow_up_model'] },
|
||||
],
|
||||
long_term_memory: { bindings: ['extract_model'] },
|
||||
knowledge_base_total: 2,
|
||||
agent_total: 1,
|
||||
}
|
||||
|
||||
test('parses grouped model usage details without dropping multiple bindings', () => {
|
||||
assert.deepEqual(parseModelUsageDetails(details), details)
|
||||
})
|
||||
|
||||
test('fills missing totals from the listed collections', () => {
|
||||
const { knowledge_base_total, agent_total, ...withoutTotals } = details
|
||||
assert.deepEqual(parseModelUsageDetails(withoutTotals), details)
|
||||
assert.equal(knowledge_base_total, 2)
|
||||
assert.equal(agent_total, 1)
|
||||
})
|
||||
|
||||
test('keeps untruncated totals when the listed collections are capped', () => {
|
||||
const parsed = parseModelUsageDetails({
|
||||
...details,
|
||||
knowledge_base_total: 80,
|
||||
agent_total: 12,
|
||||
})
|
||||
assert.equal(parsed?.knowledge_base_total, 80)
|
||||
assert.equal(parsed?.agent_total, 12)
|
||||
assert.equal(modelUsageResourceCount(parsed!.knowledge_bases, parsed!.knowledge_base_total), 80)
|
||||
assert.equal(modelUsageListTruncated(parsed!.knowledge_bases, parsed!.knowledge_base_total), true)
|
||||
assert.equal(modelUsageListTruncated(parsed!.agents, parsed!.agent_total), true)
|
||||
})
|
||||
|
||||
test('recognizes only the dedicated model-in-use code with a valid payload', () => {
|
||||
const conflict = modelInUseErrorFromRequest({
|
||||
status: 400,
|
||||
success: false,
|
||||
error: {
|
||||
code: MODEL_IN_USE_ERROR_CODE,
|
||||
message: 'backwards-compatible server message',
|
||||
details,
|
||||
},
|
||||
})
|
||||
|
||||
assert.ok(conflict instanceof ModelInUseError)
|
||||
assert.deepEqual(conflict.details, details)
|
||||
assert.equal(modelInUseErrorFromRequest({ error: { code: 1000, details } }), null)
|
||||
})
|
||||
|
||||
test('rejects malformed details instead of guessing from the server message', () => {
|
||||
assert.equal(parseModelUsageDetails({ knowledge_bases: [], agents: [] }), null)
|
||||
assert.equal(parseModelUsageDetails({
|
||||
knowledge_bases: [],
|
||||
agents: [],
|
||||
long_term_memory: { bindings: [] },
|
||||
}), null)
|
||||
assert.equal(parseModelUsageDetails({
|
||||
knowledge_bases: [{ id: 'kb-1', name: 'Docs', bindings: [] }],
|
||||
agents: [],
|
||||
long_term_memory: { bindings: [] },
|
||||
}), null)
|
||||
assert.equal(parseModelUsageDetails({
|
||||
knowledge_bases: [{ id: 'kb-1', name: 'Docs', bindings: 'vlm_model' }],
|
||||
agents: [],
|
||||
long_term_memory: { bindings: [] },
|
||||
}), null)
|
||||
assert.equal(modelInUseErrorFromRequest({
|
||||
error: {
|
||||
code: MODEL_IN_USE_ERROR_CODE,
|
||||
message: 'model is used by 1 knowledge base(s)',
|
||||
details: null,
|
||||
},
|
||||
}), null)
|
||||
})
|
||||
|
||||
test('keeps navigation and localization stable for all resource kinds', () => {
|
||||
assert.deepEqual(
|
||||
modelUsageResourceRoute('knowledge_base', 'kb/with slash'),
|
||||
{ path: '/platform/knowledge-bases/kb%2Fwith%20slash' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
modelUsageResourceRoute('agent', 'agent-1'),
|
||||
{ path: '/platform/agents', query: { edit: 'agent-1', section: 'model' } },
|
||||
)
|
||||
assert.deepEqual(
|
||||
modelUsageResourceRoute('agent', 'agent-1', ['vlm_model']),
|
||||
{ path: '/platform/agents', query: { edit: 'agent-1', section: 'multimodal' } },
|
||||
)
|
||||
assert.deepEqual(
|
||||
modelUsageResourceRoute('agent', 'agent-1', ['follow_up_model']),
|
||||
{ path: '/platform/agents', query: { edit: 'agent-1', section: 'suggestions' } },
|
||||
)
|
||||
assert.equal(modelUsageBindingI18nKey('vlm_model'), 'modelSettings.usage.bindings.vlm_model')
|
||||
assert.equal(modelUsageBindingI18nKey('future_binding'), 'modelSettings.usage.bindings.unknown')
|
||||
})
|
||||
|
||||
test('maps knowledge-base bindings to the configuration section that owns them', () => {
|
||||
assert.equal(modelUsageKnowledgeBaseSection(['embedding_model']), 'models')
|
||||
assert.equal(modelUsageKnowledgeBaseSection(['summary_model']), 'models')
|
||||
assert.equal(modelUsageKnowledgeBaseSection(['wiki_synthesis_model']), 'models')
|
||||
assert.equal(modelUsageKnowledgeBaseSection(['auto_tag_model']), 'models')
|
||||
assert.equal(modelUsageKnowledgeBaseSection(['image_processing_model']), 'multimodal')
|
||||
assert.equal(modelUsageKnowledgeBaseSection(['vlm_model']), 'multimodal')
|
||||
assert.equal(modelUsageKnowledgeBaseSection(['asr_model']), 'asr')
|
||||
assert.equal(modelUsageKnowledgeBaseSection(['future_binding']), 'models')
|
||||
assert.equal(modelUsageKnowledgeBaseSection(['summary_model', 'vlm_model']), 'models')
|
||||
})
|
||||
|
||||
test('maps agent bindings to the configuration section that owns them', () => {
|
||||
assert.equal(modelUsageAgentSection(['chat_model']), 'model')
|
||||
assert.equal(modelUsageAgentSection(['rerank_model']), 'model')
|
||||
assert.equal(modelUsageAgentSection(['query_understand_model']), 'model')
|
||||
assert.equal(modelUsageAgentSection(['vlm_model']), 'multimodal')
|
||||
assert.equal(modelUsageAgentSection(['asr_model']), 'multimodal')
|
||||
assert.equal(modelUsageAgentSection(['follow_up_model']), 'suggestions')
|
||||
assert.equal(modelUsageAgentSection(['future_binding']), 'model')
|
||||
assert.equal(modelUsageAgentSection(['chat_model', 'vlm_model']), 'model')
|
||||
assert.equal(modelUsageAgentSection(['vlm_model', 'follow_up_model']), 'multimodal')
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
export const MODEL_IN_USE_ERROR_CODE = 2300
|
||||
|
||||
export const KNOWN_MODEL_USAGE_BINDINGS = [
|
||||
'embedding_model',
|
||||
'summary_model',
|
||||
'image_processing_model',
|
||||
'vlm_model',
|
||||
'asr_model',
|
||||
'wiki_synthesis_model',
|
||||
'auto_tag_model',
|
||||
'chat_model',
|
||||
'rerank_model',
|
||||
'query_understand_model',
|
||||
'follow_up_model',
|
||||
'extract_model',
|
||||
] as const
|
||||
|
||||
export type KnownModelUsageBinding = typeof KNOWN_MODEL_USAGE_BINDINGS[number]
|
||||
|
||||
export interface ModelUsageResource {
|
||||
id: string
|
||||
name: string
|
||||
bindings: string[]
|
||||
}
|
||||
|
||||
export interface ModelUsageDetails {
|
||||
knowledge_bases: ModelUsageResource[]
|
||||
agents: ModelUsageResource[]
|
||||
long_term_memory: {
|
||||
bindings: string[]
|
||||
}
|
||||
knowledge_base_total: number
|
||||
agent_total: number
|
||||
}
|
||||
|
||||
export class ModelInUseError extends Error {
|
||||
readonly details: ModelUsageDetails
|
||||
|
||||
constructor(details: ModelUsageDetails) {
|
||||
super('model is in use')
|
||||
this.name = 'ModelInUseError'
|
||||
this.details = details
|
||||
}
|
||||
}
|
||||
|
||||
type UnknownRecord = Record<string, unknown>
|
||||
|
||||
function isRecord(value: unknown): value is UnknownRecord {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function parseBindings(value: unknown): string[] | null {
|
||||
if (!Array.isArray(value) || value.some(binding => typeof binding !== 'string' || binding.trim() === '')) {
|
||||
return null
|
||||
}
|
||||
return [...value]
|
||||
}
|
||||
|
||||
function parseResources(value: unknown): ModelUsageResource[] | null {
|
||||
if (!Array.isArray(value)) return null
|
||||
|
||||
const resources: ModelUsageResource[] = []
|
||||
for (const item of value) {
|
||||
if (!isRecord(item) || typeof item.id !== 'string' || item.id.trim() === '' || typeof item.name !== 'string') {
|
||||
return null
|
||||
}
|
||||
const bindings = parseBindings(item.bindings)
|
||||
if (!bindings || bindings.length === 0) return null
|
||||
resources.push({ id: item.id, name: item.name, bindings })
|
||||
}
|
||||
return resources
|
||||
}
|
||||
|
||||
function parseTotal(value: unknown, listed: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value) && value >= listed) {
|
||||
return Math.floor(value)
|
||||
}
|
||||
return listed
|
||||
}
|
||||
|
||||
export function parseModelUsageDetails(value: unknown): ModelUsageDetails | null {
|
||||
if (!isRecord(value) || !isRecord(value.long_term_memory)) return null
|
||||
|
||||
const knowledgeBases = parseResources(value.knowledge_bases)
|
||||
const agents = parseResources(value.agents)
|
||||
const memoryBindings = parseBindings(value.long_term_memory.bindings)
|
||||
if (!knowledgeBases || !agents || !memoryBindings) return null
|
||||
|
||||
const details: ModelUsageDetails = {
|
||||
knowledge_bases: knowledgeBases,
|
||||
agents,
|
||||
long_term_memory: { bindings: memoryBindings },
|
||||
knowledge_base_total: parseTotal(value.knowledge_base_total, knowledgeBases.length),
|
||||
agent_total: parseTotal(value.agent_total, agents.length),
|
||||
}
|
||||
if (knowledgeBases.length === 0 && agents.length === 0 && memoryBindings.length === 0) {
|
||||
return null
|
||||
}
|
||||
return details
|
||||
}
|
||||
|
||||
export function modelInUseErrorFromRequest(error: unknown): ModelInUseError | null {
|
||||
if (!isRecord(error) || !isRecord(error.error) || error.error.code !== MODEL_IN_USE_ERROR_CODE) {
|
||||
return null
|
||||
}
|
||||
const details = parseModelUsageDetails(error.error.details)
|
||||
return details ? new ModelInUseError(details) : null
|
||||
}
|
||||
|
||||
const knownBindings = new Set<string>(KNOWN_MODEL_USAGE_BINDINGS)
|
||||
|
||||
export function modelUsageBindingI18nKey(binding: string): string {
|
||||
const key = knownBindings.has(binding) ? binding : 'unknown'
|
||||
return `modelSettings.usage.bindings.${key}`
|
||||
}
|
||||
|
||||
export function modelUsageResourceCount(resources: readonly ModelUsageResource[], total?: number): number {
|
||||
return typeof total === 'number' && Number.isFinite(total) && total >= resources.length
|
||||
? Math.floor(total)
|
||||
: resources.length
|
||||
}
|
||||
|
||||
export function modelUsageListTruncated(resources: readonly ModelUsageResource[], total?: number): boolean {
|
||||
return modelUsageResourceCount(resources, total) > resources.length
|
||||
}
|
||||
|
||||
export type ModelUsageResourceKind = 'knowledge_base' | 'agent'
|
||||
|
||||
export type KnowledgeBaseModelUsageSection = 'models' | 'multimodal' | 'asr'
|
||||
|
||||
export type AgentModelUsageSection = 'model' | 'multimodal' | 'suggestions'
|
||||
|
||||
const knowledgeBaseUsageSections: Partial<Record<KnownModelUsageBinding, KnowledgeBaseModelUsageSection>> = {
|
||||
embedding_model: 'models',
|
||||
summary_model: 'models',
|
||||
wiki_synthesis_model: 'models',
|
||||
auto_tag_model: 'models',
|
||||
image_processing_model: 'multimodal',
|
||||
vlm_model: 'multimodal',
|
||||
asr_model: 'asr',
|
||||
}
|
||||
|
||||
const agentUsageSections: Partial<Record<KnownModelUsageBinding, AgentModelUsageSection>> = {
|
||||
chat_model: 'model',
|
||||
rerank_model: 'model',
|
||||
query_understand_model: 'model',
|
||||
vlm_model: 'multimodal',
|
||||
asr_model: 'multimodal',
|
||||
follow_up_model: 'suggestions',
|
||||
}
|
||||
|
||||
export function modelUsageKnowledgeBaseSection(
|
||||
bindings: readonly string[],
|
||||
): KnowledgeBaseModelUsageSection {
|
||||
for (const binding of bindings) {
|
||||
const section = knowledgeBaseUsageSections[binding as KnownModelUsageBinding]
|
||||
if (section) return section
|
||||
}
|
||||
return 'models'
|
||||
}
|
||||
|
||||
export function modelUsageAgentSection(
|
||||
bindings: readonly string[],
|
||||
): AgentModelUsageSection {
|
||||
for (const binding of bindings) {
|
||||
const section = agentUsageSections[binding as KnownModelUsageBinding]
|
||||
if (section) return section
|
||||
}
|
||||
return 'model'
|
||||
}
|
||||
|
||||
export function modelUsageResourceRoute(
|
||||
kind: ModelUsageResourceKind,
|
||||
id: string,
|
||||
bindings: readonly string[] = [],
|
||||
) {
|
||||
if (kind === 'knowledge_base') {
|
||||
return { path: `/platform/knowledge-bases/${encodeURIComponent(id)}` }
|
||||
}
|
||||
return {
|
||||
path: '/platform/agents',
|
||||
query: { edit: id, section: modelUsageAgentSection(bindings) },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
// 组织中心(租户级共享组织架构)API 封装,对应后端 /api/v1/org/*(routes_org.go)。
|
||||
// 部门/员工档案归租户所有;业务模块(企业培训/图纸标注/物料检核...)通过
|
||||
// module_key 在 org_module_members 上绑定各自角色,组织数据只维护一份。
|
||||
// 响应解包沿用 api/training 导出的 unwrap(调用方 import { unwrap } from '@/api/training')。
|
||||
|
||||
// 注意必须带 /api/v1 前缀(与其他 api 模块一致);axios baseURL 为 '/',
|
||||
// 缺前缀时请求会落入前端 SPA 回退路由,返回 index.html 而非接口数据。
|
||||
const base = '/api/v1/org'
|
||||
|
||||
export type OrgModuleKey = string
|
||||
|
||||
/** 企业培训模块的 module_key(组织中心首个接入模块)。 */
|
||||
export const ORG_MODULE_TRAINING: OrgModuleKey = 'training'
|
||||
|
||||
export interface OrgDept {
|
||||
id: string
|
||||
tenant_id: number
|
||||
parent_id: string
|
||||
name: string
|
||||
code: string
|
||||
sort: number
|
||||
}
|
||||
|
||||
/** 模块绑定行(org_module_members):某模块在某员工上的角色/扩展属性。 */
|
||||
export interface OrgModuleMember {
|
||||
id: string
|
||||
tenant_id: number
|
||||
module_key: OrgModuleKey
|
||||
employee_id: string
|
||||
roles: string[]
|
||||
extra: Record<string, any>
|
||||
}
|
||||
|
||||
export interface OrgEmployee {
|
||||
id: string
|
||||
tenant_id: number
|
||||
user_id: string
|
||||
employee_no: string
|
||||
dept_id: string
|
||||
post: string
|
||||
lecturer_rate: number
|
||||
status: string
|
||||
/** 联查展示字段:用户姓名/部门名称/指定 module_key 的绑定角色 */
|
||||
user_name?: string
|
||||
dept_name?: string
|
||||
roles?: string[]
|
||||
}
|
||||
|
||||
export interface OrgListQuery {
|
||||
module_key?: string
|
||||
dept_id?: string
|
||||
keyword?: string
|
||||
page?: number
|
||||
page_size?: number
|
||||
}
|
||||
|
||||
export interface OrgPagedData<T> {
|
||||
items: T[]
|
||||
total: number
|
||||
}
|
||||
|
||||
// ---- 部门 ----
|
||||
|
||||
export const listDepts = () => get<{ success: boolean; data: OrgDept[] }>(`${base}/depts`)
|
||||
|
||||
/** 新增/修改部门:id 为空走新增,否则更新。 */
|
||||
export const saveDept = (payload: Partial<OrgDept>) =>
|
||||
post<{ success: boolean; data: OrgDept }>(`${base}/depts`, payload)
|
||||
|
||||
export const deleteDept = (id: string) => del<{ success: boolean }>(`${base}/depts/${enc(id)}`)
|
||||
|
||||
// ---- 员工档案 ----
|
||||
|
||||
export const listEmployees = (query?: OrgListQuery) =>
|
||||
get<{ success: boolean; data: OrgPagedData<OrgEmployee> }>(`${base}/employees`, { params: query })
|
||||
|
||||
export interface OrgPlatformUser {
|
||||
id: string
|
||||
username: string
|
||||
email: string
|
||||
/** 姓名(OIDC displayName claim),可能为空 */
|
||||
display_name?: string
|
||||
in_roster: boolean
|
||||
}
|
||||
|
||||
export const listPlatformUsers = () =>
|
||||
get<{ success: boolean; data: OrgPlatformUser[] }>(`${base}/platform-users`)
|
||||
|
||||
export interface OrgImportEmployee {
|
||||
user_id: string
|
||||
employee_no?: string
|
||||
dept_id: string
|
||||
post?: string
|
||||
status?: string
|
||||
}
|
||||
|
||||
/** 批量导入员工档案(部门必填,须为已维护部门)。 */
|
||||
export const importEmployees = (employees: OrgImportEmployee[]) =>
|
||||
post<{ success: boolean; data: { imported: number } }>(`${base}/employees/import`, { employees })
|
||||
|
||||
// ---- 模块角色绑定 ----
|
||||
|
||||
export const listModuleMembers = (moduleKey: OrgModuleKey) =>
|
||||
get<{ success: boolean; data: OrgModuleMember[] }>(
|
||||
`${base}/modules/${enc(moduleKey)}/members`,
|
||||
)
|
||||
|
||||
export const putModuleMember = (moduleKey: OrgModuleKey, employeeId: string, roles: string[]) =>
|
||||
put<{ success: boolean; data: OrgModuleMember }>(
|
||||
`${base}/modules/${enc(moduleKey)}/members/${enc(employeeId)}`,
|
||||
{ roles },
|
||||
)
|
||||
|
||||
// ---- 内部小工具 ----
|
||||
|
||||
function enc(value: string) {
|
||||
return encodeURIComponent(value)
|
||||
}
|
||||
@@ -0,0 +1,791 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
// Organization types
|
||||
export interface Organization {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
avatar?: string
|
||||
owner_id: string
|
||||
/**
|
||||
* Persisted owner tenant of the organization (Plan 3, migration 000046).
|
||||
* After Plan 3, member ownership is tenant-keyed: identifying the
|
||||
* "owner row" in the members list means matching member.tenant_id
|
||||
* against owner_tenant_id (NOT member.user_id against owner_id).
|
||||
* May be 0 on pre-000046 legacy rows; in that case fall back to
|
||||
* owner_id for display only.
|
||||
*/
|
||||
owner_tenant_id: number
|
||||
invite_code?: string
|
||||
invite_code_expires_at?: string | null
|
||||
invite_code_validity_days?: number
|
||||
require_approval?: boolean
|
||||
searchable?: boolean
|
||||
/** Max members; 0 = unlimited */
|
||||
member_limit?: number
|
||||
member_count?: number
|
||||
share_count?: number
|
||||
agent_share_count?: number
|
||||
pending_join_request_count?: number
|
||||
is_owner?: boolean
|
||||
my_role?: string
|
||||
has_pending_upgrade?: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* OrganizationMember represents one row in the organization's per-tenant
|
||||
* member list (Plan 3 / migration 000045). Each row is a (org, tenant)
|
||||
* tuple; the user fields describe the *representative* user attached to
|
||||
* that row for display/audit, not the member identity itself.
|
||||
*
|
||||
* - `tenant_id` + `tenant_name` are the canonical member identity.
|
||||
* - `representative_user_id` is the post-Plan-3 explicit alias; `user_id`
|
||||
* is kept for backward compatibility and points at the same value.
|
||||
* - Two users belonging to the *same* tenant produce a single row here
|
||||
* (UNIQUE(org_id, tenant_id)); the rep is the user who first brought
|
||||
* the tenant in.
|
||||
*/
|
||||
export interface OrganizationMember {
|
||||
id: string
|
||||
user_id: string
|
||||
representative_user_id?: string
|
||||
username: string
|
||||
/** Representative user's human-readable name (姓名); roster shows it as the primary label. */
|
||||
display_name?: string
|
||||
email: string
|
||||
avatar?: string
|
||||
role: 'admin' | 'editor' | 'viewer'
|
||||
tenant_id: number
|
||||
tenant_name?: string
|
||||
joined_at: string
|
||||
}
|
||||
|
||||
export interface KnowledgeBaseShare {
|
||||
id: string
|
||||
knowledge_base_id: string
|
||||
knowledge_base_name?: string
|
||||
knowledge_base_type?: string
|
||||
knowledge_count?: number
|
||||
chunk_count?: number
|
||||
organization_id: string
|
||||
organization_name?: string
|
||||
shared_by_user_id: string
|
||||
shared_by_username?: string
|
||||
source_tenant_id: number
|
||||
/** Share permission: what the space was granted (viewer/editor) */
|
||||
permission: 'admin' | 'editor' | 'viewer'
|
||||
/** Current user's role in this organization (admin/editor/viewer) */
|
||||
my_role_in_org?: 'admin' | 'editor' | 'viewer'
|
||||
/** Effective permission for current user = min(permission, my_role_in_org) */
|
||||
my_permission?: 'admin' | 'editor' | 'viewer'
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface SharedKnowledgeBase {
|
||||
knowledge_base: {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
type: string
|
||||
knowledge_count?: number
|
||||
chunk_count?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
share_id: string
|
||||
organization_id: string
|
||||
org_name: string
|
||||
permission: 'admin' | 'editor' | 'viewer'
|
||||
source_tenant_id: number
|
||||
shared_at: string
|
||||
}
|
||||
|
||||
/** When set, this KB is visible in the space via a shared agent (read-only, no direct KB share) */
|
||||
export interface SourceFromAgentInfo {
|
||||
agent_id: string
|
||||
agent_name: string
|
||||
/** "all" | "selected" | "none" — for showing agent's KB strategy in the drawer */
|
||||
kb_selection_mode?: string
|
||||
}
|
||||
|
||||
/** Item from GET /organizations/:id/shared-knowledge-bases (space-scoped list including mine and agent-carried) */
|
||||
export type OrganizationSharedKnowledgeBaseItem = SharedKnowledgeBase & {
|
||||
is_mine: boolean
|
||||
/** Present when the KB is from a shared agent's config (not directly shared to the space) */
|
||||
source_from_agent?: SourceFromAgentInfo
|
||||
}
|
||||
|
||||
export interface OrganizationPreview {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
avatar?: string
|
||||
member_count: number
|
||||
share_count: number
|
||||
agent_share_count?: number
|
||||
is_already_member: boolean
|
||||
require_approval: boolean
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/** Searchable (discoverable) organization item for join flow */
|
||||
export interface SearchableOrganizationItem {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
avatar?: string
|
||||
member_count: number
|
||||
member_limit: number // 0 = unlimited
|
||||
share_count: number
|
||||
agent_share_count?: number
|
||||
is_already_member: boolean
|
||||
require_approval: boolean
|
||||
}
|
||||
|
||||
// Request types
|
||||
export interface CreateOrganizationRequest {
|
||||
name: string
|
||||
description?: string
|
||||
avatar?: string
|
||||
invite_code_validity_days?: number // 0=never, 1, 7, 30; default 7
|
||||
member_limit?: number // 0=unlimited; default 50
|
||||
}
|
||||
|
||||
export interface UpdateOrganizationRequest {
|
||||
name?: string
|
||||
description?: string
|
||||
avatar?: string
|
||||
require_approval?: boolean
|
||||
searchable?: boolean
|
||||
invite_code_validity_days?: number // 0=never, 1, 7, 30
|
||||
member_limit?: number // 0=unlimited
|
||||
}
|
||||
|
||||
export interface UpdateMemberRoleRequest {
|
||||
role: 'admin' | 'editor' | 'viewer'
|
||||
}
|
||||
|
||||
export interface JoinOrganizationRequest {
|
||||
invite_code: string
|
||||
}
|
||||
|
||||
export interface ShareKnowledgeBaseRequest {
|
||||
organization_id: string
|
||||
permission: 'admin' | 'editor' | 'viewer'
|
||||
}
|
||||
|
||||
export interface UpdateSharePermissionRequest {
|
||||
permission: 'admin' | 'editor' | 'viewer'
|
||||
}
|
||||
|
||||
// Response types
|
||||
export interface ApiResponse<T> {
|
||||
success: boolean
|
||||
data?: T
|
||||
message?: string
|
||||
}
|
||||
|
||||
/** Per-org resource counts (included in list my organizations to avoid extra GET /me/resource-counts) */
|
||||
export interface ResourceCountsByOrg {
|
||||
knowledge_bases: { by_organization: Record<string, number> }
|
||||
agents: { by_organization: Record<string, number> }
|
||||
}
|
||||
|
||||
export interface ListOrganizationsResponse {
|
||||
organizations: Organization[]
|
||||
total: number
|
||||
resource_counts?: ResourceCountsByOrg
|
||||
}
|
||||
|
||||
export interface ListMembersResponse {
|
||||
members: OrganizationMember[]
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface JoinRequestResponse {
|
||||
id: string
|
||||
user_id: string
|
||||
username: string
|
||||
email: string
|
||||
message: string
|
||||
request_type: 'join' | 'upgrade' // 'join' for new member, 'upgrade' for role upgrade
|
||||
prev_role?: string // Previous role (only for upgrade requests)
|
||||
requested_role: string // Role applicant requested: admin, editor, viewer
|
||||
status: string
|
||||
created_at: string
|
||||
reviewed_at?: string
|
||||
}
|
||||
|
||||
export interface ListJoinRequestsResponse {
|
||||
requests: JoinRequestResponse[]
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface SubmitJoinRequestRequest {
|
||||
invite_code: string
|
||||
message?: string
|
||||
role?: 'admin' | 'editor' | 'viewer' // Optional: role applicant requests; default viewer
|
||||
}
|
||||
|
||||
export interface ReviewJoinRequestRequest {
|
||||
approved: boolean
|
||||
message?: string
|
||||
role?: 'admin' | 'editor' | 'viewer' // Optional: role to assign when approving; overrides applicant's requested role
|
||||
}
|
||||
|
||||
export interface RequestRoleUpgradeRequest {
|
||||
requested_role: 'admin' | 'editor' | 'viewer' // The role user wants to upgrade to
|
||||
message?: string // Optional message explaining the reason
|
||||
}
|
||||
|
||||
/**
|
||||
* InviteMemberRequest enrols a *tenant* into the organization (Plan 3).
|
||||
* - `tenant_id` is the preferred identity for the invitee.
|
||||
* - `representative_user_id` is optional metadata for the OTM row's
|
||||
* display/audit; when omitted the server picks a sensible default.
|
||||
* - `user_id` is kept for backward compatibility with pre-Plan-3 callers
|
||||
* (the server resolves the user's tenant if `tenant_id` is unset).
|
||||
*/
|
||||
export interface InviteMemberRequest {
|
||||
tenant_id?: number
|
||||
representative_user_id?: string
|
||||
user_id?: string
|
||||
role: 'admin' | 'editor' | 'viewer'
|
||||
}
|
||||
|
||||
export interface UserSearchResult {
|
||||
id: string
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* TenantInviteCandidate is one row in the search-tenants-for-invite picker.
|
||||
* The picker is tenant-centric; the representative_* fields describe the
|
||||
* user that caused the tenant to appear in the search (for display only).
|
||||
*/
|
||||
export interface TenantInviteCandidate {
|
||||
tenant_id: number
|
||||
tenant_name: string
|
||||
representative_user_id: string
|
||||
/** Matching user's human-readable name (姓名); the picker labels candidates by it. */
|
||||
representative_display_name?: string
|
||||
representative_username: string
|
||||
representative_email: string
|
||||
representative_avatar?: string
|
||||
/** True when the workspace already joined the org; the picker renders it disabled with an 已添加 tag. */
|
||||
is_member?: boolean
|
||||
}
|
||||
|
||||
export interface ListSharesResponse {
|
||||
shares: KnowledgeBaseShare[]
|
||||
total: number
|
||||
}
|
||||
|
||||
// Agent share types
|
||||
export interface AgentShareResponse {
|
||||
id: string
|
||||
agent_id: string
|
||||
agent_name?: string
|
||||
organization_id: string
|
||||
organization_name?: string
|
||||
shared_by_user_id: string
|
||||
shared_by_username?: string
|
||||
source_tenant_id: number
|
||||
permission: string
|
||||
my_role_in_org?: string
|
||||
my_permission?: string
|
||||
created_at: string
|
||||
/** Agent scope summary for list display */
|
||||
scope_kb?: string
|
||||
scope_kb_count?: number
|
||||
scope_web_search?: boolean
|
||||
scope_mcp?: string
|
||||
scope_mcp_count?: number
|
||||
/** Agent avatar (emoji) for list display */
|
||||
agent_avatar?: string
|
||||
}
|
||||
|
||||
export interface SharedAgentInfo {
|
||||
agent: { id: string; name: string; description?: string; [key: string]: any }
|
||||
share_id: string
|
||||
organization_id: string
|
||||
org_name: string
|
||||
permission: string
|
||||
source_tenant_id: number
|
||||
shared_at: string
|
||||
shared_by_user_id?: string
|
||||
shared_by_username?: string
|
||||
/** 由后端在源空间解析,不与当前空间的搜索引擎列表比较 */
|
||||
web_search_ready: boolean
|
||||
/** 当前用户是否已停用该共享智能体(仅影响本人对话下拉显示) */
|
||||
disabled_by_me?: boolean
|
||||
}
|
||||
|
||||
/** Item from GET /organizations/:id/shared-agents (space-scoped list including mine) */
|
||||
export type OrganizationSharedAgentItem = SharedAgentInfo & { is_mine: boolean }
|
||||
|
||||
export interface ListAgentSharesResponse {
|
||||
shares: AgentShareResponse[]
|
||||
total: number
|
||||
}
|
||||
|
||||
// Organization API functions
|
||||
|
||||
/**
|
||||
* Create a new organization
|
||||
*/
|
||||
export async function createOrganization(req: CreateOrganizationRequest): Promise<ApiResponse<Organization>> {
|
||||
try {
|
||||
const response = await post('/api/v1/organizations', req)
|
||||
return response as unknown as ApiResponse<Organization>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to create organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get organization by ID
|
||||
*/
|
||||
export async function getOrganization(id: string): Promise<ApiResponse<Organization>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${id}`)
|
||||
return response as unknown as ApiResponse<Organization>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to get organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List my organizations
|
||||
*/
|
||||
export async function listMyOrganizations(): Promise<ApiResponse<ListOrganizationsResponse>> {
|
||||
try {
|
||||
const response = await get('/api/v1/organizations')
|
||||
return response as unknown as ApiResponse<ListOrganizationsResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list organizations' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update organization
|
||||
*/
|
||||
export async function updateOrganization(id: string, req: UpdateOrganizationRequest): Promise<ApiResponse<Organization>> {
|
||||
try {
|
||||
const response = await put(`/api/v1/organizations/${id}`, req)
|
||||
return response as unknown as ApiResponse<Organization>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to update organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete organization
|
||||
*/
|
||||
export async function deleteOrganization(id: string): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await del(`/api/v1/organizations/${id}`)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to delete organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Join organization by invite code
|
||||
*/
|
||||
export async function joinOrganization(req: JoinOrganizationRequest): Promise<ApiResponse<Organization>> {
|
||||
try {
|
||||
const response = await post('/api/v1/organizations/join', req)
|
||||
return response as unknown as ApiResponse<Organization>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to join organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit a join request (for organizations that require approval).
|
||||
* Optional role: applicant's requested role (admin/editor/viewer); default viewer.
|
||||
*/
|
||||
export async function submitJoinRequest(req: SubmitJoinRequestRequest): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await post('/api/v1/organizations/join-request', req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to submit join request' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview organization by invite code (without joining)
|
||||
*/
|
||||
export async function previewOrganization(inviteCode: string): Promise<ApiResponse<OrganizationPreview>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/preview/${inviteCode}`)
|
||||
return response as unknown as ApiResponse<OrganizationPreview>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to preview organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search searchable (discoverable) organizations
|
||||
*/
|
||||
export async function searchSearchableOrganizations(
|
||||
q: string = '',
|
||||
limit: number = 20
|
||||
): Promise<ApiResponse<{ data: SearchableOrganizationItem[]; total: number }>> {
|
||||
try {
|
||||
const params = new URLSearchParams()
|
||||
if (q) params.set('q', q)
|
||||
params.set('limit', String(limit))
|
||||
const response = await get(`/api/v1/organizations/search?${params.toString()}`)
|
||||
const res = response as unknown as { success: boolean; data?: SearchableOrganizationItem[]; total?: number; message?: string }
|
||||
return {
|
||||
success: res.success,
|
||||
data: res.success ? { data: res.data || [], total: res.total ?? 0 } : undefined,
|
||||
message: res.message,
|
||||
}
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to search organizations' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Join a searchable organization by ID (no invite code)
|
||||
*/
|
||||
export async function joinOrganizationById(
|
||||
organizationId: string,
|
||||
message?: string,
|
||||
role?: 'admin' | 'editor' | 'viewer'
|
||||
): Promise<ApiResponse<Organization>> {
|
||||
try {
|
||||
const body: { organization_id: string; message?: string; role?: string } = { organization_id: organizationId }
|
||||
if (message) body.message = message
|
||||
if (role) body.role = role
|
||||
const response = await post('/api/v1/organizations/join-by-id', body)
|
||||
return response as unknown as ApiResponse<Organization>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to join organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Leave organization
|
||||
*/
|
||||
export async function leaveOrganization(id: string): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/organizations/${id}/leave`, {})
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to leave organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request role upgrade in an organization
|
||||
*/
|
||||
export async function requestRoleUpgrade(
|
||||
orgId: string,
|
||||
request: RequestRoleUpgradeRequest
|
||||
): Promise<ApiResponse<JoinRequestResponse>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/organizations/${orgId}/request-upgrade`, request)
|
||||
return response as unknown as ApiResponse<JoinRequestResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to submit upgrade request' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate new invite code
|
||||
*/
|
||||
export async function generateInviteCode(id: string): Promise<ApiResponse<{ invite_code: string }>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/organizations/${id}/invite-code`, {})
|
||||
return response as unknown as ApiResponse<{ invite_code: string }>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to generate invite code' }
|
||||
}
|
||||
}
|
||||
|
||||
// Member management
|
||||
|
||||
/**
|
||||
* List organization members
|
||||
*/
|
||||
export async function listMembers(orgId: string): Promise<ApiResponse<ListMembersResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/members`)
|
||||
return response as unknown as ApiResponse<ListMembersResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list members' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update member role (member is identified by tenant_id)
|
||||
*/
|
||||
export async function updateMemberRole(orgId: string, tenantId: number, req: UpdateMemberRoleRequest): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await put(`/api/v1/organizations/${orgId}/members/${tenantId}`, req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to update member role' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove member (member is identified by tenant_id)
|
||||
*/
|
||||
export async function removeMember(orgId: string, tenantId: number): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await del(`/api/v1/organizations/${orgId}/members/${tenantId}`)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to remove member' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List join requests (pending) for an organization (admin only)
|
||||
*/
|
||||
export async function listJoinRequests(orgId: string): Promise<ApiResponse<ListJoinRequestsResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/join-requests`)
|
||||
return response as unknown as ApiResponse<ListJoinRequestsResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list join requests' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Review join request (approve or reject) - admin only
|
||||
*/
|
||||
export async function reviewJoinRequest(orgId: string, requestId: string, req: ReviewJoinRequestRequest): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await put(`/api/v1/organizations/${orgId}/join-requests/${requestId}/review`, req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to review join request' }
|
||||
}
|
||||
}
|
||||
|
||||
// Knowledge base sharing
|
||||
|
||||
/**
|
||||
* Share knowledge base to organization
|
||||
*/
|
||||
export async function shareKnowledgeBase(kbId: string, req: ShareKnowledgeBaseRequest): Promise<ApiResponse<KnowledgeBaseShare>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/knowledge-bases/${kbId}/shares`, req)
|
||||
return response as unknown as ApiResponse<KnowledgeBaseShare>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to share knowledge base' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List shares for a knowledge base
|
||||
*/
|
||||
export async function listKBShares(kbId: string): Promise<ApiResponse<ListSharesResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/knowledge-bases/${kbId}/shares`)
|
||||
return response as unknown as ApiResponse<ListSharesResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list shares' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update share permission
|
||||
*/
|
||||
export async function updateSharePermission(kbId: string, shareId: string, req: UpdateSharePermissionRequest): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await put(`/api/v1/knowledge-bases/${kbId}/shares/${shareId}`, req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to update share permission' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove share
|
||||
*/
|
||||
export async function removeShare(kbId: string, shareId: string): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await del(`/api/v1/knowledge-bases/${kbId}/shares/${shareId}`)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to remove share' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List shared knowledge bases (shared to me through organizations)
|
||||
*/
|
||||
export async function listSharedKnowledgeBases(): Promise<ApiResponse<SharedKnowledgeBase[]>> {
|
||||
try {
|
||||
const response = await get('/api/v1/shared-knowledge-bases')
|
||||
return response as unknown as ApiResponse<SharedKnowledgeBase[]>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list shared knowledge bases' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List all knowledge bases in an organization (including those shared by current tenant), for list page when a space is selected.
|
||||
*/
|
||||
export async function listOrganizationSharedKnowledgeBases(orgId: string): Promise<ApiResponse<OrganizationSharedKnowledgeBaseItem[]>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/shared-knowledge-bases`)
|
||||
return response as unknown as ApiResponse<OrganizationSharedKnowledgeBaseItem[]>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list organization shared knowledge bases' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List knowledge bases shared to a specific organization
|
||||
*/
|
||||
export async function listOrgShares(orgId: string): Promise<ApiResponse<ListSharesResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/shares`)
|
||||
return response as unknown as ApiResponse<ListSharesResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list organization shares' }
|
||||
}
|
||||
}
|
||||
|
||||
// Agent sharing
|
||||
export async function shareAgent(agentId: string, req: ShareKnowledgeBaseRequest): Promise<ApiResponse<AgentShareResponse>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/agents/${agentId}/shares`, req)
|
||||
return response as unknown as ApiResponse<AgentShareResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to share agent' }
|
||||
}
|
||||
}
|
||||
|
||||
export async function listAgentShares(agentId: string): Promise<ApiResponse<ListAgentSharesResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/agents/${agentId}/shares`)
|
||||
return response as unknown as ApiResponse<ListAgentSharesResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list agent shares' }
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateAgentSharePermission(agentId: string, shareId: string, req: UpdateSharePermissionRequest): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await put(`/api/v1/agents/${agentId}/shares/${shareId}`, req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to update share permission' }
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeAgentShare(agentId: string, shareId: string): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await del(`/api/v1/agents/${agentId}/shares/${shareId}`)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to remove share' }
|
||||
}
|
||||
}
|
||||
|
||||
export async function listSharedAgents(): Promise<ApiResponse<SharedAgentInfo[]>> {
|
||||
try {
|
||||
const response = await get('/api/v1/shared-agents')
|
||||
return response as unknown as ApiResponse<SharedAgentInfo[]>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list shared agents' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List all agents in an organization (including those shared by current tenant), for list page when a space is selected.
|
||||
*/
|
||||
export async function listOrganizationSharedAgents(orgId: string): Promise<ApiResponse<OrganizationSharedAgentItem[]>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/shared-agents`)
|
||||
return response as unknown as ApiResponse<OrganizationSharedAgentItem[]>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list organization shared agents' }
|
||||
}
|
||||
}
|
||||
|
||||
/** 设置当前用户对某共享智能体的停用状态(仅影响本人对话下拉显示) */
|
||||
export async function setSharedAgentDisabledByMe(
|
||||
agentId: string,
|
||||
disabled: boolean
|
||||
): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await post('/api/v1/shared-agents/disabled', {
|
||||
agent_id: agentId,
|
||||
disabled
|
||||
})
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to update preference' }
|
||||
}
|
||||
}
|
||||
|
||||
export async function listOrgAgentShares(orgId: string): Promise<ApiResponse<ListAgentSharesResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/agent-shares`)
|
||||
return response as unknown as ApiResponse<ListAgentSharesResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list organization agent shares' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search candidate tenants for inviting to organization (excludes tenants
|
||||
* already in the org). Candidates match by member name (姓名), username, or
|
||||
* email; an exact numeric workspace ID also still resolves directly.
|
||||
*/
|
||||
export async function searchTenantsForInvite(
|
||||
orgId: string,
|
||||
query: string,
|
||||
limit: number = 10
|
||||
): Promise<ApiResponse<TenantInviteCandidate[]>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/search-tenants?q=${encodeURIComponent(query)}&limit=${limit}`)
|
||||
return response as unknown as ApiResponse<TenantInviteCandidate[]>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to search tenants' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use `searchTenantsForInvite`. Kept for callers that haven't
|
||||
* migrated yet; the backend serves the tenant-grouped shape from the
|
||||
* legacy `/search-users` path as well.
|
||||
*/
|
||||
export async function searchUsersForInvite(
|
||||
orgId: string,
|
||||
query: string,
|
||||
limit: number = 10
|
||||
): Promise<ApiResponse<TenantInviteCandidate[]>> {
|
||||
return searchTenantsForInvite(orgId, query, limit)
|
||||
}
|
||||
|
||||
/**
|
||||
* Invite a user to organization directly (admin only)
|
||||
*/
|
||||
export async function inviteMember(
|
||||
orgId: string,
|
||||
req: InviteMemberRequest
|
||||
): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/organizations/${orgId}/invite`, req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to invite member' }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { get, put } from '@/utils/request'
|
||||
|
||||
// RetrievalConfig represents the global retrieval/search configuration for a tenant.
|
||||
// Shared by knowledge search and message search.
|
||||
export interface RetrievalConfig {
|
||||
embedding_top_k: number
|
||||
vector_threshold: number
|
||||
keyword_threshold: number
|
||||
rerank_top_k: number
|
||||
rerank_threshold: number
|
||||
rerank_model_id: string
|
||||
rrf_k?: number
|
||||
rrf_vector_weight?: number
|
||||
rrf_keyword_weight?: number
|
||||
}
|
||||
|
||||
// Get tenant retrieval config via KV API
|
||||
export function getTenantRetrievalConfig() {
|
||||
return get('/api/v1/tenants/kv/retrieval-config')
|
||||
}
|
||||
|
||||
// Update tenant retrieval config via KV API
|
||||
export function updateTenantRetrievalConfig(config: RetrievalConfig) {
|
||||
return put('/api/v1/tenants/kv/retrieval-config', config)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { del, get, post, postUpload } from "../../utils/request";
|
||||
import type { ConfigSkillFileContent, ConfigSkillFileEntry } from "../system";
|
||||
|
||||
// Skill信息
|
||||
export interface SkillInfo {
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface SkillCatalogInstall {
|
||||
skill_id: string;
|
||||
sandbox_config_id: string;
|
||||
sandbox_config_name?: string;
|
||||
sandbox_type?: string;
|
||||
status: string;
|
||||
enabled: boolean;
|
||||
error?: string;
|
||||
version?: string;
|
||||
bundle_sha256?: string;
|
||||
// Present while a newer install is in flight or has failed and the sandbox
|
||||
// still runs the previous version.
|
||||
served?: { version?: string };
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface SkillCatalogItem {
|
||||
id: string;
|
||||
name: string;
|
||||
version?: string;
|
||||
description?: string;
|
||||
bundle_sha256?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
installations: SkillCatalogInstall[];
|
||||
}
|
||||
|
||||
export interface SkillCatalogRegisterResult {
|
||||
id: string;
|
||||
name: string;
|
||||
version?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/** Locates a shared agent's source workspace, same parameters as a chat request. */
|
||||
export interface AgentScope {
|
||||
agentId?: string;
|
||||
/** Set only for a shared agent; left empty for this workspace's own agents. */
|
||||
sourceTenantId?: string | number;
|
||||
}
|
||||
|
||||
// Lists the skills executable on the current sandbox config. Without a
|
||||
// sandboxConfigId, or when skills_available is false, the caller should hide or
|
||||
// disable the skills UI.
|
||||
//
|
||||
// Pass the agent for a shared one: its skills are installed on a sandbox config
|
||||
// in the OWNER's workspace, so looking them up in the caller's returns nothing.
|
||||
// The backend then reads the config off that agent and ignores sandboxConfigId.
|
||||
export function listSkills(sandboxConfigId?: string, agent?: AgentScope) {
|
||||
const params: Record<string, string> = {};
|
||||
if (sandboxConfigId) params.sandbox_config_id = sandboxConfigId;
|
||||
if (agent?.agentId && agent?.sourceTenantId) {
|
||||
params.agent_id = agent.agentId;
|
||||
params.agent_source_tenant_id = String(agent.sourceTenantId);
|
||||
}
|
||||
return get<{ data: SkillInfo[]; skills_available?: boolean }>('/api/v1/skills', { params });
|
||||
}
|
||||
|
||||
export function listSkillCatalog() {
|
||||
return get<{ data: SkillCatalogItem[] }>('/api/v1/skills/catalog');
|
||||
}
|
||||
|
||||
export function registerSkillCatalogFromSource(source: string) {
|
||||
return post<{ data: SkillCatalogRegisterResult }>('/api/v1/skills/catalog', { source }, {
|
||||
timeout: 2 * 60 * 1000,
|
||||
});
|
||||
}
|
||||
|
||||
export function registerSkillCatalogFromFile(
|
||||
file: File,
|
||||
onProgress?: (percent: number) => void,
|
||||
) {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return postUpload('/api/v1/skills/catalog', form, (e: any) => {
|
||||
if (e.total) onProgress?.(Math.round((e.loaded * 100) / e.total));
|
||||
}, { timeout: 5 * 60 * 1000 }) as Promise<{ data: SkillCatalogRegisterResult }>;
|
||||
}
|
||||
|
||||
export function installSkillCatalog(catalogId: string, sandboxConfigIds: string[]) {
|
||||
return post<{ data: { installs: Record<string, string>; errors?: Record<string, string> } }>(
|
||||
`/api/v1/skills/catalog/${catalogId}/install`,
|
||||
{ sandbox_config_ids: sandboxConfigIds },
|
||||
);
|
||||
}
|
||||
|
||||
export function deleteSkillCatalog(catalogId: string) {
|
||||
return del(`/api/v1/skills/catalog/${catalogId}`);
|
||||
}
|
||||
|
||||
export function listCatalogSkillFiles(catalogId: string) {
|
||||
return get<{ data: ConfigSkillFileEntry[] }>(`/api/v1/skills/catalog/${catalogId}/files`);
|
||||
}
|
||||
|
||||
export function getCatalogSkillFile(catalogId: string, path: string) {
|
||||
return get<{ data: ConfigSkillFileContent }>(`/api/v1/skills/catalog/${catalogId}/files/content`, {
|
||||
params: { path },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
export interface StorageBackendConfig {
|
||||
mode?: string
|
||||
endpoint?: string
|
||||
region?: string
|
||||
access_key_id?: string
|
||||
secret_access_key?: string
|
||||
bucket_name?: string
|
||||
path_prefix?: string
|
||||
app_id?: string
|
||||
use_ssl?: boolean
|
||||
force_path_style?: boolean
|
||||
use_temp_bucket?: boolean
|
||||
temp_bucket_name?: string
|
||||
temp_region?: string
|
||||
}
|
||||
|
||||
export interface StorageBackend {
|
||||
id: string
|
||||
tenant_id?: number
|
||||
name: string
|
||||
provider: string
|
||||
config: StorageBackendConfig
|
||||
source: 'user' | 'env'
|
||||
status: 'active' | 'disabled'
|
||||
legacy_alias?: boolean
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface StorageBackendListResponse {
|
||||
success: boolean
|
||||
data: StorageBackend[]
|
||||
default_storage_backend_id?: string | null
|
||||
}
|
||||
|
||||
export const listStorageBackends = (): Promise<StorageBackendListResponse> => get('/api/v1/storage-backends')
|
||||
export const listStorageBackendTypes = (): Promise<{ success: boolean; data: string[] }> => get('/api/v1/storage-backends/types')
|
||||
export const createStorageBackend = (data: Partial<StorageBackend>) => post('/api/v1/storage-backends', data)
|
||||
export const updateStorageBackend = (id: string, data: Partial<StorageBackend>) => put(`/api/v1/storage-backends/${id}`, data)
|
||||
export const deleteStorageBackend = (id: string) => del(`/api/v1/storage-backends/${id}`)
|
||||
export const setDefaultStorageBackend = (id: string) => put(`/api/v1/storage-backends/${id}/default`, {})
|
||||
export const testStorageBackend = (data: Partial<StorageBackend>) => post('/api/v1/storage-backends/test', data)
|
||||
export const testStorageBackendByID = (id: string) => post(`/api/v1/storage-backends/${id}/test`, {})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
||||
import { get, post, put } from '@/utils/request'
|
||||
|
||||
export interface CatalogModel {
|
||||
id: string
|
||||
type?: string
|
||||
match?: string
|
||||
name?: string
|
||||
context_window?: number
|
||||
max_output_tokens?: number
|
||||
reasoning?: boolean
|
||||
deprecated?: boolean
|
||||
[key: string]: unknown
|
||||
}
|
||||
export interface CatalogProvider {
|
||||
id: string
|
||||
name: string
|
||||
api: string
|
||||
model_types: string[]
|
||||
settings?: Record<string, unknown>
|
||||
models: CatalogModel[] | null
|
||||
// Levels each chat model offers once thinking is on, resolved server-side.
|
||||
model_thinking_levels?: Record<string, string[]>
|
||||
vendor_thinking_levels?: string[]
|
||||
}
|
||||
export interface CatalogOverlay { providers: Record<string, Record<string, any>> }
|
||||
export interface CatalogState {
|
||||
version: number
|
||||
baseline: string
|
||||
overlay: CatalogOverlay
|
||||
history: Array<{ version: number; overlay: CatalogOverlay; updated_by: string; updated_at: string }>
|
||||
builtin: CatalogProvider[]
|
||||
deployment: CatalogProvider[]
|
||||
effective: CatalogProvider[]
|
||||
deployment_error?: string
|
||||
sync_error?: string
|
||||
applied_version: number
|
||||
}
|
||||
// A check returns only the candidate; history and the lower layers are omitted.
|
||||
export type CatalogPreview = Omit<CatalogState, 'history' | 'builtin' | 'deployment'>
|
||||
export interface CatalogUpdate { version: number; baseline: string; overlay: CatalogOverlay }
|
||||
const root = '/api/v1/system/admin/model-catalog'
|
||||
export const getModelCatalog = () => get(root) as unknown as Promise<CatalogState>
|
||||
export const previewModelCatalog = (request: CatalogUpdate) => post(`${root}/preview`, request) as unknown as Promise<CatalogPreview>
|
||||
export const publishModelCatalog = (request: CatalogUpdate) => put(root, request) as unknown as Promise<CatalogState>
|
||||
@@ -0,0 +1,81 @@
|
||||
import { get } from '@/utils/request'
|
||||
|
||||
// AuditAction mirrors internal/types/audit_log.go's namespaced action
|
||||
// enum. The dot prefix (`rbac.`) is deliberate — future PRs will add
|
||||
// `kb.*` / `agent.*` namespaces without a schema change, and the
|
||||
// backend already treats this column as an opaque string. Keep this
|
||||
// list in sync with types/audit_log.go.
|
||||
export type AuditAction =
|
||||
| 'rbac.member_added'
|
||||
| 'rbac.member_removed'
|
||||
| 'rbac.member_role_changed'
|
||||
| 'rbac.member_left'
|
||||
| 'rbac.access_denied'
|
||||
| string // forward-compat: future namespaces shouldn't break the type
|
||||
|
||||
export type AuditOutcome = 'accepted' | 'success' | 'failed' | 'partial' | 'canceled' | 'denied'
|
||||
|
||||
// AuditLog mirrors internal/types/audit_log.go. `details` is the JSONB
|
||||
// blob — for role changes it carries `{"old_role":..., "new_role":...}`,
|
||||
// for access_denied it carries `{"required_role":...}`. We keep it as
|
||||
// an opaque record so future detail shapes don't need a frontend
|
||||
// breaking change.
|
||||
export interface AuditLog {
|
||||
id: number
|
||||
tenant_id: number
|
||||
actor_user_id: string
|
||||
actor_role: string
|
||||
action: AuditAction
|
||||
scope_type: string
|
||||
scope_id: string
|
||||
target_type: string
|
||||
target_id: string
|
||||
target_user_id: string
|
||||
request_path: string
|
||||
request_method: string
|
||||
outcome: AuditOutcome
|
||||
details: Record<string, unknown> | string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface ListAuditLogResponse {
|
||||
success: boolean
|
||||
data?: AuditLog[]
|
||||
next_cursor?: number
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface ListAuditLogParams {
|
||||
// Cursor: rows with id < after_id, newest first. Pass the
|
||||
// previous response's `next_cursor`. Omit on first page.
|
||||
after_id?: number
|
||||
// Page size, 1–100. Server defaults to 50 if omitted.
|
||||
limit?: number
|
||||
// Optional filters; backend matches on equality.
|
||||
action?: AuditAction
|
||||
outcome?: AuditOutcome
|
||||
actor?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* List the per-tenant audit log. Cursor-paginated by descending id.
|
||||
* Backend: GET /api/v1/tenants/:id/audit-log (Admin+).
|
||||
*
|
||||
* The first call should pass no cursor. Each subsequent page should
|
||||
* pass `after_id = previousResponse.next_cursor` until next_cursor
|
||||
* comes back as 0 (no older rows).
|
||||
*/
|
||||
export async function listAuditLog(
|
||||
tenantId: number,
|
||||
params: ListAuditLogParams = {},
|
||||
): Promise<ListAuditLogResponse> {
|
||||
const qs = new URLSearchParams()
|
||||
if (params.after_id) qs.append('after_id', String(params.after_id))
|
||||
if (params.limit) qs.append('limit', String(params.limit))
|
||||
if (params.action) qs.append('action', params.action)
|
||||
if (params.outcome) qs.append('outcome', params.outcome)
|
||||
if (params.actor) qs.append('actor', params.actor)
|
||||
const tail = qs.toString()
|
||||
const url = `/api/v1/tenants/${tenantId}/audit-log${tail ? '?' + tail : ''}`
|
||||
return (await get(url)) as unknown as ListAuditLogResponse
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import { del, get, post, put } from '@/utils/request'
|
||||
import i18n from '@/i18n'
|
||||
|
||||
const t = (key: string) => i18n.global.t(key)
|
||||
|
||||
// 空间信息接口
|
||||
export interface TenantInfo {
|
||||
id: number
|
||||
name: string
|
||||
description?: string
|
||||
status?: string
|
||||
business?: string
|
||||
storage_quota?: number
|
||||
storage_used?: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export type APIPrincipalMode = 'tenant' | 'direct_header' | 'signed_token'
|
||||
|
||||
export interface APIPrincipalConfig {
|
||||
mode: APIPrincipalMode
|
||||
direct_header_name: string
|
||||
signed_token_header_name: string
|
||||
require_direct_header: boolean
|
||||
// The server never returns the plaintext secret; only its presence.
|
||||
has_hmac_secret: boolean
|
||||
}
|
||||
|
||||
export interface UpdateAPIPrincipalConfigPayload {
|
||||
mode: APIPrincipalMode
|
||||
direct_header_name?: string
|
||||
signed_token_header_name?: string
|
||||
require_direct_header?: boolean
|
||||
hmac_secret?: string
|
||||
}
|
||||
|
||||
export interface CreateAPIPrincipalTestTokenPayload {
|
||||
external_user_id: string
|
||||
expires_in_seconds?: number
|
||||
}
|
||||
|
||||
export interface APIPrincipalTestToken {
|
||||
token: string
|
||||
header_name: string
|
||||
expires_in_seconds: number
|
||||
expires_at_unix: number
|
||||
external_user_id: string
|
||||
}
|
||||
|
||||
// Bounded per-key grants for non-full-access API keys.
|
||||
// - 'retrieve': read/search knowledge-base data within scope
|
||||
// - 'chat': run the conversation flow (sessions + agent listing + self identity)
|
||||
// - 'read_agents': list/read agents without chat or authoring
|
||||
// - 'ingest': write content into allowed knowledge bases (docs/chunks/FAQ/tags/wiki)
|
||||
// - 'manage_kbs': manage the KB lifecycle (create/copy/duplicate/update/delete + config)
|
||||
// - 'manage_agents': create/update/delete/copy agents
|
||||
// - 'message_history': search/read tenant chat-history metadata
|
||||
// - 'manage_models': manage tenant model definitions, checks, and credentials
|
||||
// - 'manage_mcp_services': manage MCP services, credentials, tool policies, and OAuth state
|
||||
// - 'manage_datasources': manage data-source connectors and sync jobs
|
||||
// - 'manage_channels': manage embed and IM channels
|
||||
// - 'manage_vector_stores': manage vector stores and parser/storage checks
|
||||
// - 'manage_web_search': manage web-search providers
|
||||
// - 'run_evaluations': run/read evaluation jobs
|
||||
// - 'manage_members': manage tenant members and invitations
|
||||
// - 'manage_spaces': manage organization/space collaboration
|
||||
// - 'manage_tenant_settings': read/update tenant integration settings (API principal mode, headers, tenant KV)
|
||||
export type TenantAPIKeyCapability =
|
||||
| 'retrieve'
|
||||
| 'chat'
|
||||
| 'read_agents'
|
||||
| 'ingest'
|
||||
| 'manage_kbs'
|
||||
| 'manage_agents'
|
||||
| 'message_history'
|
||||
| 'manage_models'
|
||||
| 'manage_mcp_services'
|
||||
| 'manage_datasources'
|
||||
| 'manage_channels'
|
||||
| 'manage_vector_stores'
|
||||
| 'manage_storage_backends'
|
||||
| 'manage_web_search'
|
||||
| 'run_evaluations'
|
||||
| 'manage_members'
|
||||
| 'manage_spaces'
|
||||
| 'manage_tenant_settings'
|
||||
| 'system_tenants_read'
|
||||
| 'system_tenants_manage'
|
||||
| 'system_settings_read'
|
||||
| 'system_settings_manage'
|
||||
| 'system_runtime_read'
|
||||
| 'system_runtime_manage'
|
||||
| 'system_audit_read'
|
||||
|
||||
export interface TenantAPIKey {
|
||||
id: number
|
||||
scope_type?: 'tenant' | 'platform'
|
||||
name: string
|
||||
api_key: string
|
||||
full_access: boolean
|
||||
knowledge_base_ids: string[] | null
|
||||
capabilities?: TenantAPIKeyCapability[]
|
||||
last_used_at?: string
|
||||
expires_at?: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface CreatedTenantAPIKey extends TenantAPIKey {
|
||||
token?: string
|
||||
}
|
||||
|
||||
export interface CreateTenantAPIKeyPayload {
|
||||
name: string
|
||||
full_access?: boolean
|
||||
knowledge_base_ids?: string[]
|
||||
capabilities?: TenantAPIKeyCapability[]
|
||||
expires_at_unix?: number
|
||||
}
|
||||
|
||||
export interface UpdateTenantAPIKeyPayload {
|
||||
name: string
|
||||
full_access: boolean
|
||||
knowledge_base_ids: string[]
|
||||
capabilities: TenantAPIKeyCapability[]
|
||||
expires_at_unix?: number
|
||||
}
|
||||
|
||||
// 搜索空间参数
|
||||
export interface SearchTenantsParams {
|
||||
keyword?: string
|
||||
tenant_id?: number
|
||||
page?: number
|
||||
page_size?: number
|
||||
}
|
||||
|
||||
// 搜索空间响应
|
||||
export interface SearchTenantsResponse {
|
||||
success: boolean
|
||||
data?: {
|
||||
items: TenantInfo[]
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有空间列表(需要跨空间访问权限)
|
||||
* @deprecated 建议使用 searchTenants 代替,支持分页和搜索
|
||||
*/
|
||||
export async function listAllTenants(): Promise<{ success: boolean; data?: { items: TenantInfo[] }; message?: string }> {
|
||||
try {
|
||||
const response = await get('/api/v1/tenants/all')
|
||||
return response as unknown as { success: boolean; data?: { items: TenantInfo[] }; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.listFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAPIPrincipalConfig(
|
||||
tenantId: number,
|
||||
): Promise<{ success: boolean; data?: APIPrincipalConfig; message?: string }> {
|
||||
try {
|
||||
const response = await get(`/api/v1/tenants/${tenantId}/api-principal-config`)
|
||||
return response as unknown as { success: boolean; data?: APIPrincipalConfig; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.getApiPrincipalConfigFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateAPIPrincipalConfig(
|
||||
tenantId: number,
|
||||
payload: UpdateAPIPrincipalConfigPayload,
|
||||
): Promise<{ success: boolean; data?: APIPrincipalConfig; message?: string }> {
|
||||
try {
|
||||
const response = await put(`/api/v1/tenants/${tenantId}/api-principal-config`, payload)
|
||||
return response as unknown as { success: boolean; data?: APIPrincipalConfig; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.updateApiPrincipalConfigFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function createAPIPrincipalTestToken(
|
||||
tenantId: number,
|
||||
payload: CreateAPIPrincipalTestTokenPayload,
|
||||
): Promise<{ success: boolean; data?: APIPrincipalTestToken; message?: string }> {
|
||||
try {
|
||||
const response = await post(`/api/v1/tenants/${tenantId}/api-principal-test-token`, payload)
|
||||
return response as unknown as { success: boolean; data?: APIPrincipalTestToken; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.createApiPrincipalTestTokenFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function listTenantAPIKeys(
|
||||
tenantId: number,
|
||||
): Promise<{ success: boolean; data?: TenantAPIKey[]; message?: string }> {
|
||||
try {
|
||||
const response = await get(`/api/v1/tenants/${tenantId}/api-keys`)
|
||||
return response as unknown as { success: boolean; data?: TenantAPIKey[]; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.listApiKeysFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function createTenantAPIKey(
|
||||
tenantId: number,
|
||||
payload: CreateTenantAPIKeyPayload,
|
||||
): Promise<{ success: boolean; data?: CreatedTenantAPIKey; message?: string }> {
|
||||
try {
|
||||
const response = await post(`/api/v1/tenants/${tenantId}/api-keys`, payload)
|
||||
return response as unknown as { success: boolean; data?: CreatedTenantAPIKey; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.createApiKeyFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 更新已创建租户 API Key 的授权范围和其他可配置属性。 */
|
||||
export async function updateTenantAPIKey(
|
||||
tenantId: number,
|
||||
keyId: number,
|
||||
payload: UpdateTenantAPIKeyPayload,
|
||||
): Promise<{ success: boolean; data?: TenantAPIKey; message?: string }> {
|
||||
try {
|
||||
const response = await put(`/api/v1/tenants/${tenantId}/api-keys/${keyId}`, payload)
|
||||
return response as unknown as { success: boolean; data?: TenantAPIKey; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('integrations.api.updateApiKeyScopeFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteTenantAPIKey(
|
||||
tenantId: number,
|
||||
keyId: number,
|
||||
): Promise<{ success: boolean; message?: string }> {
|
||||
try {
|
||||
const response = await del(`/api/v1/tenants/${tenantId}/api-keys/${keyId}`)
|
||||
return response as unknown as { success: boolean; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.deleteApiKeyFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新空间信息(目前暴露名称、描述两个字段的编辑入口)。
|
||||
* 后端 `PUT /tenants/:id` 用指针字段区分"未传"和"显式空串",未传的列不会
|
||||
* 被改动;这里也按需选择性传 `name` / `description`,互不影响。
|
||||
* 权限:owner(与 router.go 中的 g.Owner() 守卫保持一致)。
|
||||
*/
|
||||
export async function updateTenant(
|
||||
tenantId: number,
|
||||
payload: { name?: string; description?: string },
|
||||
): Promise<{ success: boolean; data?: TenantInfo; message?: string }> {
|
||||
try {
|
||||
const response = await put(`/api/v1/tenants/${tenantId}`, payload)
|
||||
return response as unknown as { success: boolean; data?: TenantInfo; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.updateFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除当前工作区。权限:owner。
|
||||
*/
|
||||
export async function deleteTenant(
|
||||
tenantId: number,
|
||||
): Promise<{ success: boolean; message?: string }> {
|
||||
try {
|
||||
const response = await del(`/api/v1/tenants/${tenantId}`)
|
||||
return response as unknown as { success: boolean; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.deleteFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建新工作区(任意已登录用户均可调用)。
|
||||
* 后端会自动把调用者写成新空间的 Owner,并填充默认 storage_quota
|
||||
* 等服务端字段;API Key 由用户在集成页手动创建。
|
||||
* 路由:POST /api/v1/tenants(router 上不挂 g.CrossTenant(),自助场景使用)。
|
||||
*/
|
||||
export async function createTenant(
|
||||
payload: { name: string; description?: string },
|
||||
): Promise<{ success: boolean; data?: TenantInfo; message?: string }> {
|
||||
try {
|
||||
const response = await post('/api/v1/tenants', payload)
|
||||
return response as unknown as { success: boolean; data?: TenantInfo; message?: string }
|
||||
} catch (error: any) {
|
||||
const code = error?.error?.code ?? error?.code
|
||||
return {
|
||||
success: false,
|
||||
message: code === 2005
|
||||
? t('tenant.create.disabled')
|
||||
: (error.message || t('error.tenant.createFailed')),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索空间(支持分页、关键词搜索和空间ID过滤)
|
||||
*/
|
||||
export async function searchTenants(params: SearchTenantsParams = {}): Promise<SearchTenantsResponse> {
|
||||
try {
|
||||
const queryParams = new URLSearchParams()
|
||||
if (params.keyword) {
|
||||
queryParams.append('keyword', params.keyword)
|
||||
}
|
||||
if (params.tenant_id) {
|
||||
queryParams.append('tenant_id', String(params.tenant_id))
|
||||
}
|
||||
if (params.page) {
|
||||
queryParams.append('page', String(params.page))
|
||||
}
|
||||
if (params.page_size) {
|
||||
queryParams.append('page_size', String(params.page_size))
|
||||
}
|
||||
|
||||
const queryString = queryParams.toString()
|
||||
const url = `/api/v1/tenants/search${queryString ? '?' + queryString : ''}`
|
||||
const response = await get(url)
|
||||
return response as unknown as SearchTenantsResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.searchFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import { get, post, del } from '@/utils/request'
|
||||
import type { TenantMember, TenantRole } from '@/api/tenant/members'
|
||||
|
||||
// TenantInvitationStatus mirrors internal/types/tenant_invitation.go's
|
||||
// five-state machine. pending is the only non-terminal state; the rest
|
||||
// are recorded for the audit trail.
|
||||
export type TenantInvitationStatus =
|
||||
| 'pending'
|
||||
| 'accepted'
|
||||
| 'declined'
|
||||
| 'revoked'
|
||||
| 'expired'
|
||||
|
||||
// TenantInvitation is the API projection of a tenant_invitations row,
|
||||
// hydrated with the inviter / invitee user fields and the tenant name
|
||||
// when the backend has them. Missing optional fields render as the
|
||||
// raw id in the UI rather than dropping the row.
|
||||
export interface TenantInvitation {
|
||||
id: number
|
||||
tenant_id: number
|
||||
tenant_name?: string
|
||||
invitee_user_id: string
|
||||
invitee_email?: string
|
||||
invitee_name?: string
|
||||
invited_by?: string | null
|
||||
inviter_email?: string
|
||||
inviter_name?: string
|
||||
role: TenantRole
|
||||
status: TenantInvitationStatus
|
||||
message?: string
|
||||
expires_at: string
|
||||
responded_at?: string | null
|
||||
created_at: string
|
||||
// invite_url is set on share-link rows that are still pending. The
|
||||
// backend re-emits it on every list/get so Owners can copy the
|
||||
// link on demand without "copy now or revoke" pressure.
|
||||
invite_url?: string
|
||||
// is_share_link distinguishes share-link rows (no specific invitee,
|
||||
// multi-use, copyable URL) from per-user invitations.
|
||||
is_share_link?: boolean
|
||||
// accepted_count counts how many users have completed registration
|
||||
// through this invitation. Surfaced in the management UI for
|
||||
// share-link rows ("已加入 N 人").
|
||||
accepted_count?: number
|
||||
}
|
||||
|
||||
export interface ListInvitationsResponse {
|
||||
success: boolean
|
||||
data?: {
|
||||
invitations: TenantInvitation[]
|
||||
total: number
|
||||
page?: number
|
||||
page_size?: number
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface ListTenantInvitationsParams {
|
||||
includeTerminal?: boolean
|
||||
page?: number
|
||||
page_size?: number
|
||||
}
|
||||
|
||||
function buildTenantInvitationsQuery(options: ListTenantInvitationsParams): string {
|
||||
const u = new URLSearchParams()
|
||||
if (options.includeTerminal) u.set('include_terminal', 'true')
|
||||
if (options.page != null && options.page > 0) u.set('page', String(options.page))
|
||||
if (options.page_size != null && options.page_size > 0) u.set('page_size', String(options.page_size))
|
||||
const qs = u.toString()
|
||||
return qs ? `?${qs}` : ''
|
||||
}
|
||||
|
||||
export interface CreateInvitationRequest {
|
||||
email: string
|
||||
role: TenantRole
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface CreateInvitationResponse {
|
||||
success: boolean
|
||||
// With tenant.auto_accept_invitation enabled the backend returns a
|
||||
// TenantMember (user_id set) instead of a pending TenantInvitation.
|
||||
data?: TenantInvitation | TenantMember
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface SimpleResponse {
|
||||
success: boolean
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface AcceptInvitationResponse {
|
||||
success: boolean
|
||||
data?: {
|
||||
membership: {
|
||||
tenant_id: number
|
||||
role: TenantRole
|
||||
status: string
|
||||
joined_at: string
|
||||
}
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
// AcceptInvitationByTokenResponse:已登录用户用 token 加入空间的响应(tenant_name 供前端展示)。
|
||||
export interface AcceptInvitationByTokenResponse {
|
||||
success: boolean
|
||||
data?: {
|
||||
membership: {
|
||||
tenant_id: number
|
||||
role: TenantRole
|
||||
status: string
|
||||
joined_at: string
|
||||
}
|
||||
tenant_name?: string
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface PendingCountResponse {
|
||||
success: boolean
|
||||
data?: { pending_count: number }
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* List invitations for a tenant. Defaults to pending only; pass
|
||||
* includeTerminal=true to also surface accepted/declined/revoked/
|
||||
* expired rows for the history view. Supports `page` / `page_size`.
|
||||
* Backend: GET /api/v1/tenants/:id/invitations (Viewer+).
|
||||
*/
|
||||
export async function listTenantInvitations(
|
||||
tenantId: number,
|
||||
options: ListTenantInvitationsParams = {},
|
||||
): Promise<ListInvitationsResponse> {
|
||||
const qs = buildTenantInvitationsQuery(options)
|
||||
return (await get(
|
||||
`/api/v1/tenants/${tenantId}/invitations${qs}`,
|
||||
)) as unknown as ListInvitationsResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a new invitation. The invitee will see it in /me/invitations
|
||||
* and must accept before they actually become a member.
|
||||
* Backend: POST /api/v1/tenants/:id/invitations (Owner+).
|
||||
*
|
||||
* 404 when the email is not a registered user (ask them to register).
|
||||
* 409 when an existing pending invitation already covers this pair, or
|
||||
* when the invitee is already an active member.
|
||||
*/
|
||||
export async function createInvitation(
|
||||
tenantId: number,
|
||||
body: CreateInvitationRequest,
|
||||
): Promise<CreateInvitationResponse> {
|
||||
return (await post(
|
||||
`/api/v1/tenants/${tenantId}/invitations`,
|
||||
body,
|
||||
)) as unknown as CreateInvitationResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke a still-pending invitation. Already-finalised rows return
|
||||
* 409; rows from another tenant render as 404 to avoid existence
|
||||
* leaks across tenants.
|
||||
* Backend: DELETE /api/v1/tenants/:id/invitations/:inv_id (Owner+).
|
||||
*/
|
||||
export async function revokeInvitation(
|
||||
tenantId: number,
|
||||
invId: number,
|
||||
): Promise<SimpleResponse> {
|
||||
return (await del(
|
||||
`/api/v1/tenants/${tenantId}/invitations/${invId}`,
|
||||
)) as unknown as SimpleResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* List MY invitations. Defaults to pending only — the inbox page
|
||||
* filters terminal rows by default; pass includeTerminal=true for a
|
||||
* history view if/when the UI grows one.
|
||||
* Backend: GET /api/v1/me/invitations (authenticated).
|
||||
*/
|
||||
export async function listMyInvitations(
|
||||
options: { includeTerminal?: boolean } = {},
|
||||
): Promise<ListInvitationsResponse> {
|
||||
const qs = options.includeTerminal ? '?include_terminal=true' : ''
|
||||
return (await get(`/api/v1/me/invitations${qs}`)) as unknown as ListInvitationsResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight pending-count endpoint used by the avatar-row badge
|
||||
* poller. Separate from the list endpoint so polling doesn't transfer
|
||||
* the full payload every cycle.
|
||||
* Backend: GET /api/v1/me/invitations/pending-count (authenticated).
|
||||
*/
|
||||
export async function getMyPendingInvitationCount(): Promise<PendingCountResponse> {
|
||||
return (await get(
|
||||
`/api/v1/me/invitations/pending-count`,
|
||||
)) as unknown as PendingCountResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept one of MY pending invitations. On success the backend also
|
||||
* creates the tenant_members row in the same flow; the caller should
|
||||
* then refresh memberships in the auth store.
|
||||
* Backend: POST /api/v1/me/invitations/:inv_id/accept (authenticated).
|
||||
*/
|
||||
export async function acceptInvitation(invId: number): Promise<AcceptInvitationResponse> {
|
||||
return (await post(
|
||||
`/api/v1/me/invitations/${invId}/accept`,
|
||||
)) as unknown as AcceptInvitationResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* 已登录用户用共享链接 token 加入空间(需鉴权,不创建新账号)。
|
||||
* 用于 invite_only 模式下的邀请链接流程:链接导向登录而非注册,登录后再兑换 token。
|
||||
* Backend: POST /api/v1/me/invitations/accept-by-token (authenticated).
|
||||
*/
|
||||
export async function acceptInvitationByToken(
|
||||
token: string,
|
||||
): Promise<AcceptInvitationByTokenResponse> {
|
||||
return (await post(
|
||||
`/api/v1/me/invitations/accept-by-token`,
|
||||
{ token },
|
||||
)) as unknown as AcceptInvitationByTokenResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Decline one of MY pending invitations.
|
||||
* Backend: POST /api/v1/me/invitations/:inv_id/decline (authenticated).
|
||||
*/
|
||||
export async function declineInvitation(invId: number): Promise<SimpleResponse> {
|
||||
return (await post(
|
||||
`/api/v1/me/invitations/${invId}/decline`,
|
||||
)) as unknown as SimpleResponse
|
||||
}
|
||||
|
||||
// ---- share-link API ----------------------------------------------------
|
||||
|
||||
export interface CreateInviteLinkRequest {
|
||||
role: TenantRole
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface CreateInviteLinkResponse {
|
||||
success: boolean
|
||||
data?: TenantInvitation
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a multi-use share-link invitation for the tenant. The
|
||||
* returned row carries `invite_url` (composed from the persisted
|
||||
* plaintext token) which the SPA copies into clipboards. The link
|
||||
* stays valid until expiry or revocation; revoking is the same DELETE
|
||||
* as a per-user invitation.
|
||||
*
|
||||
* Backend: POST /api/v1/tenants/:id/invite-links (Owner+).
|
||||
*/
|
||||
export async function createInviteLink(
|
||||
tenantId: number,
|
||||
body: CreateInviteLinkRequest,
|
||||
): Promise<CreateInviteLinkResponse> {
|
||||
return (await post(
|
||||
`/api/v1/tenants/${tenantId}/invite-links`,
|
||||
body,
|
||||
)) as unknown as CreateInviteLinkResponse
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
// TenantRole mirrors internal/types/tenant_member.go's four-role enum.
|
||||
// Keep the string values aligned with the Go constants.
|
||||
export type TenantRole = 'owner' | 'admin' | 'contributor' | 'viewer'
|
||||
|
||||
export type TenantMemberStatus = 'active' | 'invited' | 'suspended'
|
||||
|
||||
// TenantMember is the API projection of a (user, tenant) membership row,
|
||||
// already joined with the user's email/username/avatar by the backend.
|
||||
export interface TenantMember {
|
||||
user_id: string
|
||||
email: string
|
||||
username: string
|
||||
/** 姓名:来自 OIDC 可配置 claim(默认 nickname),本地/工号账号可能为空 */
|
||||
display_name?: string
|
||||
avatar?: string
|
||||
role: TenantRole
|
||||
status: TenantMemberStatus
|
||||
invited_by?: string | null
|
||||
joined_at: string
|
||||
}
|
||||
|
||||
export interface ListMembersResponse {
|
||||
success: boolean
|
||||
data?: {
|
||||
members: TenantMember[]
|
||||
total: number
|
||||
page?: number
|
||||
page_size?: number
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface ListMembersParams {
|
||||
page?: number
|
||||
page_size?: number
|
||||
/** 按邮箱/用户名筛选(服务端模糊匹配) */
|
||||
q?: string
|
||||
}
|
||||
|
||||
function buildMembersQuery(params: ListMembersParams | undefined): string {
|
||||
if (!params) return ''
|
||||
const u = new URLSearchParams()
|
||||
if (params.page != null && params.page > 0) u.set('page', String(params.page))
|
||||
if (params.page_size != null && params.page_size > 0) u.set('page_size', String(params.page_size))
|
||||
const q = params.q?.trim()
|
||||
if (q) u.set('q', q)
|
||||
const qs = u.toString()
|
||||
return qs ? `?${qs}` : ''
|
||||
}
|
||||
|
||||
export interface AddMemberRequest {
|
||||
email: string
|
||||
role: TenantRole
|
||||
}
|
||||
|
||||
export interface AddMemberResponse {
|
||||
success: boolean
|
||||
data?: TenantMember
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface SimpleResponse {
|
||||
success: boolean
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页列出空间成员。
|
||||
* Backend: GET /api/v1/tenants/:id/members (Viewer+)。查询参数:`q`、`page`、`page_size`。
|
||||
*/
|
||||
export async function listMembers(
|
||||
tenantId: number,
|
||||
params: ListMembersParams = {},
|
||||
): Promise<ListMembersResponse> {
|
||||
const qs = buildMembersQuery(params)
|
||||
return (await get(
|
||||
`/api/v1/tenants/${tenantId}/members${qs}`,
|
||||
)) as unknown as ListMembersResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历分页拉取空间的全部成员(每页最大 100,最多 500 页兜底)。
|
||||
* 用于「退出空间」等对全量成员的轻量校验;普通表格请直接使用 {@link listMembers} 分页接口。
|
||||
*/
|
||||
export async function fetchAllTenantMembers(tenantId: number): Promise<TenantMember[]> {
|
||||
const pageSize = 100
|
||||
let page = 1
|
||||
const out: TenantMember[] = []
|
||||
let total = Number.POSITIVE_INFINITY
|
||||
for (let guard = 0; guard < 500 && out.length < total; guard++) {
|
||||
const resp = await listMembers(tenantId, { page, page_size: pageSize })
|
||||
if (!resp.success || !resp.data) break
|
||||
total = resp.data.total
|
||||
const batch = resp.data.members || []
|
||||
if (batch.length === 0 && page >= 2) break
|
||||
out.push(...batch)
|
||||
if (batch.length < pageSize) break
|
||||
page++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Invite an existing user (by email) to the tenant with the given role.
|
||||
* Backend: POST /api/v1/tenants/:id/members (Owner+).
|
||||
*
|
||||
* Returns 404 when the email does not match any registered user — the
|
||||
* caller should ask the invitee to register first. PR 3 does not yet
|
||||
* support email-based invites for users who don't have an account.
|
||||
*/
|
||||
export async function addMember(
|
||||
tenantId: number,
|
||||
body: AddMemberRequest,
|
||||
): Promise<AddMemberResponse> {
|
||||
return (await post(`/api/v1/tenants/${tenantId}/members`, body)) as unknown as AddMemberResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Change an existing member's role.
|
||||
* Backend: PUT /api/v1/tenants/:id/members/:user_id (Owner+).
|
||||
*
|
||||
* Returns 409 when this would demote the last active Owner of the tenant.
|
||||
*/
|
||||
export async function updateMemberRole(
|
||||
tenantId: number,
|
||||
userId: string,
|
||||
role: TenantRole,
|
||||
): Promise<SimpleResponse> {
|
||||
return (await put(`/api/v1/tenants/${tenantId}/members/${userId}`, { role })) as unknown as SimpleResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a member from the tenant.
|
||||
* Backend: DELETE /api/v1/tenants/:id/members/:user_id (Owner+).
|
||||
*
|
||||
* Returns 409 when this would remove the last active Owner.
|
||||
*/
|
||||
export async function removeMember(
|
||||
tenantId: number,
|
||||
userId: string,
|
||||
): Promise<SimpleResponse> {
|
||||
return (await del(`/api/v1/tenants/${tenantId}/members/${userId}`)) as unknown as SimpleResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Quit the tenant on your own. Same last-Owner invariant as
|
||||
* removeMember, but does NOT require Owner+ — any active member can
|
||||
* call it.
|
||||
* Backend: POST /api/v1/tenants/:id/leave (Viewer+).
|
||||
*/
|
||||
export async function leaveTenant(tenantId: number): Promise<SimpleResponse> {
|
||||
return (await post(`/api/v1/tenants/${tenantId}/leave`)) as unknown as SimpleResponse
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,34 @@
|
||||
// API client for per-user starred resources (DB-backed; see migration
|
||||
// 000047 and internal/handler/user_resource_favorite.go).
|
||||
//
|
||||
// The backend authoritatively scopes favorites to the active (user, tenant)
|
||||
// pair from the auth context — these helpers therefore never pass user_id
|
||||
// or tenant_id, and a tenant switch automatically points reads at the
|
||||
// right namespace.
|
||||
|
||||
import { get, post, del } from '@/utils/request'
|
||||
|
||||
export type FavoriteResourceType = 'kb' | 'agent'
|
||||
|
||||
export interface FavoriteEntry {
|
||||
user_id: string
|
||||
tenant_id: number
|
||||
resource_type: FavoriteResourceType
|
||||
resource_id: string
|
||||
/** ISO timestamp from the server (created_at column). */
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export function listFavorites(type: FavoriteResourceType) {
|
||||
return get<{ success: boolean; data: FavoriteEntry[] }>(
|
||||
`/api/v1/user/favorites?type=${encodeURIComponent(type)}`
|
||||
)
|
||||
}
|
||||
|
||||
export function addFavorite(type: FavoriteResourceType, id: string) {
|
||||
return post('/api/v1/user/favorites', { type, id })
|
||||
}
|
||||
|
||||
export function removeFavorite(type: FavoriteResourceType, id: string) {
|
||||
return del(`/api/v1/user/favorites/${encodeURIComponent(type)}/${encodeURIComponent(id)}`)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
// ===== Types =====
|
||||
|
||||
export interface VectorStoreEntity {
|
||||
id?: string
|
||||
name: string
|
||||
engine_type: string
|
||||
connection_config: Record<string, any>
|
||||
index_config: Record<string, any>
|
||||
source: 'env' | 'user'
|
||||
readonly: boolean
|
||||
tenant_id?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface VectorStoreTypeInfo {
|
||||
type: string
|
||||
display_name: string
|
||||
connection_fields: FieldSchema[]
|
||||
index_fields: FieldSchema[]
|
||||
}
|
||||
|
||||
export interface FieldSchema {
|
||||
name: string
|
||||
type: 'string' | 'number' | 'boolean'
|
||||
required: boolean
|
||||
sensitive?: boolean
|
||||
description?: string
|
||||
default?: any
|
||||
// Inclusive bounds for number fields (omitempty on the backend). When
|
||||
// absent the UI falls back to per-field heuristics (isReplicaField).
|
||||
min?: number
|
||||
max?: number
|
||||
// Closed value set for string fields (e.g. knn_engine ∈ lucene|faiss).
|
||||
// When non-empty the UI renders a select instead of a free-text input.
|
||||
enum?: string[]
|
||||
// Marks a field that cannot change after store creation. Informational
|
||||
// for now (edit mode is fully read-only); kept for forward use.
|
||||
immutable?: boolean
|
||||
}
|
||||
|
||||
// ===== API Functions =====
|
||||
|
||||
export function listVectorStoreTypes(): Promise<VectorStoreTypeInfo[]> {
|
||||
return get('/api/v1/vector-stores/types').then((res: any) => {
|
||||
return res.success && res.data ? res.data : []
|
||||
})
|
||||
}
|
||||
|
||||
export function listVectorStores(): Promise<{ success: boolean; data: VectorStoreEntity[] }> {
|
||||
return get('/api/v1/vector-stores')
|
||||
}
|
||||
|
||||
export function createVectorStore(data: Partial<VectorStoreEntity>) {
|
||||
return post('/api/v1/vector-stores', data)
|
||||
}
|
||||
|
||||
export function updateVectorStore(id: string, data: Partial<VectorStoreEntity>) {
|
||||
return put(`/api/v1/vector-stores/${id}`, data)
|
||||
}
|
||||
|
||||
export function deleteVectorStore(id: string) {
|
||||
return del(`/api/v1/vector-stores/${id}`)
|
||||
}
|
||||
|
||||
export function testVectorStoreRaw(data: { engine_type: string; connection_config: any }): Promise<any> {
|
||||
return post('/api/v1/vector-stores/test', data)
|
||||
}
|
||||
|
||||
export function testVectorStoreById(id: string): Promise<any> {
|
||||
return post(`/api/v1/vector-stores/${id}/test`, {})
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
// WebSearchProviderEntity represents a configured web search provider instance
|
||||
export interface WebSearchProviderEntity {
|
||||
id?: string
|
||||
tenant_id?: number
|
||||
name: string
|
||||
provider: 'brave' | 'bing' | 'google' | 'duckduckgo' | 'tavily' | 'ollama' | 'baidu' | 'searxng' | 'keenable' | 'zhipu' | 'metaso' | 'exa' | 'bocha' | 'serply'
|
||||
description?: string
|
||||
parameters: {
|
||||
// api_key is never returned by the server in this shape; it lives behind
|
||||
// the /credentials subresource. Kept on the type so the initial create
|
||||
// POST can still include it.
|
||||
api_key?: string
|
||||
engine_id?: string
|
||||
base_url?: string
|
||||
proxy_url?: string
|
||||
extra_config?: Record<string, string>
|
||||
}
|
||||
is_default?: boolean
|
||||
// Per-field configured? metadata from the main response.
|
||||
credentials?: Record<WebSearchCredentialField, { configured: boolean }>
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
// WebSearchProviderTypeInfo describes metadata for a provider type
|
||||
export interface WebSearchProviderTypeInfo {
|
||||
id: string
|
||||
name: string
|
||||
requires_api_key: boolean
|
||||
// Keyless-by-default providers that still accept an optional key (e.g. Keenable).
|
||||
supports_optional_api_key?: boolean
|
||||
requires_engine_id?: boolean
|
||||
requires_base_url?: boolean
|
||||
supports_proxy?: boolean
|
||||
description?: string
|
||||
docs_url?: string
|
||||
config_fields?: WebSearchProviderConfigField[]
|
||||
}
|
||||
|
||||
export interface WebSearchProviderConfigField {
|
||||
key: string
|
||||
label: string
|
||||
label_key?: string
|
||||
type: 'select'
|
||||
required?: boolean
|
||||
default?: string
|
||||
description?: string
|
||||
description_key?: string
|
||||
options?: Array<{ label: string; label_key?: string; value: string }>
|
||||
}
|
||||
|
||||
// Create a new web search provider
|
||||
export function createWebSearchProvider(data: Partial<WebSearchProviderEntity>) {
|
||||
return post('/api/v1/web-search-providers', data)
|
||||
}
|
||||
|
||||
// List all web search providers for the current tenant
|
||||
export function listWebSearchProviders() {
|
||||
return get('/api/v1/web-search-providers')
|
||||
}
|
||||
|
||||
// Get a single web search provider by ID
|
||||
export function getWebSearchProvider(id: string) {
|
||||
return get(`/api/v1/web-search-providers/${id}`)
|
||||
}
|
||||
|
||||
// Update an existing web search provider
|
||||
export function updateWebSearchProvider(id: string, data: Partial<WebSearchProviderEntity>) {
|
||||
return put(`/api/v1/web-search-providers/${id}`, data)
|
||||
}
|
||||
|
||||
// Delete a web search provider
|
||||
export function deleteWebSearchProvider(id: string) {
|
||||
return del(`/api/v1/web-search-providers/${id}`)
|
||||
}
|
||||
|
||||
// Get available provider types (for dynamic form rendering)
|
||||
export function listWebSearchProviderTypes(): Promise<WebSearchProviderTypeInfo[]> {
|
||||
return get('/api/v1/web-search-providers/types').then((res: any) => {
|
||||
if (res.success && res.data) {
|
||||
return res.data
|
||||
}
|
||||
return []
|
||||
})
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Web search provider credential subresource.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
export type WebSearchCredentialField = 'api_key'
|
||||
|
||||
export interface WebSearchCredentialsResponse {
|
||||
fields: Record<WebSearchCredentialField, { configured: boolean }>
|
||||
}
|
||||
|
||||
export async function putWebSearchProviderCredentials(
|
||||
id: string,
|
||||
body: Partial<Record<WebSearchCredentialField, string>>,
|
||||
): Promise<WebSearchCredentialsResponse> {
|
||||
const response: any = await put(`/api/v1/web-search-providers/${id}/credentials`, body)
|
||||
return (response.data ?? response) as WebSearchCredentialsResponse
|
||||
}
|
||||
|
||||
export async function deleteWebSearchProviderCredentialField(
|
||||
id: string,
|
||||
field: WebSearchCredentialField,
|
||||
): Promise<void> {
|
||||
await del(`/api/v1/web-search-providers/${id}/credentials/${field}`)
|
||||
}
|
||||
|
||||
// Test a web search provider connection.
|
||||
// If id is provided, tests the existing saved provider.
|
||||
// If data is provided, tests with raw credentials (no persistence).
|
||||
export function testWebSearchProvider(id?: string, data?: { provider: string; parameters: any }): Promise<any> {
|
||||
if (id) {
|
||||
return post(`/api/v1/web-search-providers/${id}/test`, {})
|
||||
}
|
||||
return post('/api/v1/web-search-providers/test', data || {})
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { get, put } from '@/utils/request'
|
||||
|
||||
// WebSearchProviderConfig represents information about a web search provider type
|
||||
// Deprecated: Use WebSearchProviderTypeInfo from web-search-provider.ts instead
|
||||
export interface WebSearchProviderConfig {
|
||||
id: string
|
||||
name: string
|
||||
free: boolean
|
||||
requires_api_key: boolean
|
||||
description?: string
|
||||
api_url?: string
|
||||
}
|
||||
|
||||
// WebSearchConfig represents the web search configuration for a tenant
|
||||
export interface WebSearchConfig {
|
||||
// New: references a WebSearchProviderEntity by ID
|
||||
default_provider_id?: string
|
||||
// Deprecated: kept for backward compatibility
|
||||
provider?: string
|
||||
api_key?: string
|
||||
max_results: number
|
||||
include_date: boolean
|
||||
compression_method: string
|
||||
blacklist: string[]
|
||||
embedding_model_id?: string
|
||||
embedding_dimension?: number
|
||||
rerank_model_id?: string
|
||||
document_fragments?: number
|
||||
}
|
||||
|
||||
// Get web search provider types (available engines)
|
||||
export function getWebSearchProviders() {
|
||||
return get('/api/v1/web-search/providers')
|
||||
}
|
||||
|
||||
// Get tenant web search config via KV API
|
||||
export function getTenantWebSearchConfig() {
|
||||
return get('/api/v1/tenants/kv/web-search-config')
|
||||
}
|
||||
|
||||
// Update tenant web search config via KV API
|
||||
export function updateTenantWebSearchConfig(config: WebSearchConfig) {
|
||||
return put('/api/v1/tenants/kv/web-search-config', config)
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
import { get, post, put, del } from "../../utils/request";
|
||||
|
||||
// encodeSlugPath encodes each segment of a hierarchical wiki slug (e.g.
|
||||
// "foo/bar baz?") so the URL is safe while preserving the "/" separators
|
||||
// between segments. Using encodeURIComponent on the whole slug would also
|
||||
// escape the "/" and break hierarchical routing on the backend.
|
||||
function encodeSlugPath(slug: string): string {
|
||||
return slug.split("/").map(encodeURIComponent).join("/");
|
||||
}
|
||||
|
||||
// Wiki Page Types
|
||||
export interface WikiPage {
|
||||
id: string;
|
||||
tenant_id: number;
|
||||
knowledge_base_id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
page_type: string;
|
||||
status: string;
|
||||
content: string;
|
||||
summary: string;
|
||||
aliases: string[];
|
||||
parent_slug?: string;
|
||||
category_path?: string[];
|
||||
wiki_path?: string;
|
||||
depth?: number;
|
||||
sort_order?: number;
|
||||
source_refs: string[];
|
||||
in_links: string[];
|
||||
// Present on page detail responses; list and mutation responses omit it.
|
||||
in_link_titles?: Record<string, string>;
|
||||
out_links: string[];
|
||||
page_metadata: Record<string, any>;
|
||||
version: number;
|
||||
// Author kind of the current version: 'pipeline' | 'agent' | 'user' |
|
||||
// 'revert'. Empty/missing on legacy rows (treat as 'pipeline').
|
||||
last_edit_source?: string;
|
||||
last_editor_id?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface WikiPageListResponse {
|
||||
pages: WikiPage[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
export interface WikiFolder {
|
||||
id: string;
|
||||
tenant_id: number;
|
||||
knowledge_base_id: string;
|
||||
parent_id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
depth: number;
|
||||
sort_order: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface WikiFolderNode extends WikiFolder {
|
||||
page_count: number;
|
||||
has_children: boolean;
|
||||
}
|
||||
|
||||
export interface WikiFolderListResponse {
|
||||
parent_id: string;
|
||||
folders: WikiFolderNode[];
|
||||
}
|
||||
|
||||
export interface WikiGraphMeta {
|
||||
mode: 'overview' | 'ego' | string;
|
||||
total: number;
|
||||
returned: number;
|
||||
truncated: boolean;
|
||||
center?: string;
|
||||
depth?: number;
|
||||
familiar_count?: number;
|
||||
}
|
||||
|
||||
export interface WikiGraphData {
|
||||
nodes: { slug: string; title: string; page_type: string; link_count: number; familiar?: boolean }[];
|
||||
edges: { source: string; target: string }[];
|
||||
meta: WikiGraphMeta;
|
||||
}
|
||||
|
||||
export interface WikiStats {
|
||||
total_pages: number;
|
||||
pages_by_type: Record<string, number>;
|
||||
total_links: number;
|
||||
orphan_count: number;
|
||||
recent_updates: WikiPage[];
|
||||
pending_tasks: number;
|
||||
pending_issues: number;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export interface WikiPageIssue {
|
||||
id: string;
|
||||
tenant_id: number;
|
||||
knowledge_base_id: string;
|
||||
slug: string;
|
||||
issue_type: string;
|
||||
description: string;
|
||||
suspected_knowledge_ids: string[];
|
||||
status: string;
|
||||
reported_by: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
// Wiki API Functions
|
||||
export function listWikiPages(kbId: string, params?: {
|
||||
page_type?: string;
|
||||
status?: string;
|
||||
query?: string;
|
||||
category_path?: string;
|
||||
category_depth?: number;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
sort_by?: string;
|
||||
sort_order?: string;
|
||||
}) {
|
||||
const query = new URLSearchParams();
|
||||
if (params) {
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== '') {
|
||||
query.set(key, String(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
const qs = query.toString();
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/pages${qs ? '?' + qs : ''}`);
|
||||
}
|
||||
|
||||
// listWikiFolders returns the direct child folders of parentId ("" = root),
|
||||
// each enriched with a recursive page_count and a has_children flag so the tree
|
||||
// can render expand affordances and empty folders without a second request.
|
||||
// pageTypes scopes the view to a sidebar tab: only folders whose subtree holds
|
||||
// a page of those types (or are entirely empty) come back, and page_count is
|
||||
// counted within those types.
|
||||
export function listWikiFolders(kbId: string, parentId = '', pageTypes = '') {
|
||||
const query = new URLSearchParams();
|
||||
if (parentId) query.set('parent_id', parentId);
|
||||
if (pageTypes) query.set('page_types', pageTypes);
|
||||
const qs = query.toString();
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/folders${qs ? '?' + qs : ''}`);
|
||||
}
|
||||
|
||||
// createWikiFolder creates a new empty folder under parentId ("" = root).
|
||||
export function createWikiFolder(kbId: string, parentId: string, name: string) {
|
||||
return post(`/api/v1/knowledgebase/${kbId}/wiki/folders`, { parent_id: parentId, name });
|
||||
}
|
||||
|
||||
// updateWikiFolder renames and/or reparents a folder. Pass move_parent: true
|
||||
// (and parent_id) to reparent; omit it for a pure rename.
|
||||
export function updateWikiFolder(
|
||||
kbId: string,
|
||||
folderId: string,
|
||||
data: { name?: string; parent_id?: string; move_parent?: boolean },
|
||||
) {
|
||||
return put(`/api/v1/knowledgebase/${kbId}/wiki/folders/${folderId}`, data);
|
||||
}
|
||||
|
||||
// deleteWikiFolder removes an empty folder (no pages, no sub-folders).
|
||||
export function deleteWikiFolder(kbId: string, folderId: string) {
|
||||
return del(`/api/v1/knowledgebase/${kbId}/wiki/folders/${folderId}`);
|
||||
}
|
||||
|
||||
// moveWikiPage relocates a page into folderId ("" = root). The slug is sent in
|
||||
// the body because wiki slugs are hierarchical.
|
||||
export function moveWikiPage(kbId: string, slug: string, folderId: string) {
|
||||
return put(`/api/v1/knowledgebase/${kbId}/wiki/move-page`, { slug, folder_id: folderId });
|
||||
}
|
||||
|
||||
export function createWikiPage(kbId: string, data: Partial<WikiPage>) {
|
||||
return post(`/api/v1/knowledgebase/${kbId}/wiki/pages`, data);
|
||||
}
|
||||
|
||||
export function getWikiPage(kbId: string, slug: string) {
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/pages/${encodeSlugPath(slug)}`);
|
||||
}
|
||||
|
||||
// WikiPageUpdatePayload is a partial update: absent fields keep their stored
|
||||
// value. `version` is the optimistic-lock guard — send the version the page
|
||||
// had when the user started editing; the backend answers 409 (with
|
||||
// `current_version` in the body) when someone else edited in between.
|
||||
export interface WikiPageUpdatePayload {
|
||||
title?: string;
|
||||
content?: string;
|
||||
summary?: string;
|
||||
page_type?: string;
|
||||
status?: string;
|
||||
aliases?: string[];
|
||||
version?: number;
|
||||
}
|
||||
|
||||
export function updateWikiPage(kbId: string, slug: string, data: WikiPageUpdatePayload) {
|
||||
return put(`/api/v1/knowledgebase/${kbId}/wiki/pages/${encodeSlugPath(slug)}`, data);
|
||||
}
|
||||
|
||||
export function deleteWikiPage(kbId: string, slug: string) {
|
||||
return del(`/api/v1/knowledgebase/${kbId}/wiki/pages/${encodeSlugPath(slug)}`);
|
||||
}
|
||||
|
||||
// WikiPageRevision is one immutable snapshot of a superseded page version.
|
||||
// `content` is only populated when fetching a single revision.
|
||||
export interface WikiPageRevision {
|
||||
id: string;
|
||||
tenant_id: number;
|
||||
knowledge_base_id: string;
|
||||
page_id: string;
|
||||
slug: string;
|
||||
version: number;
|
||||
title: string;
|
||||
page_type: string;
|
||||
status: string;
|
||||
content?: string;
|
||||
summary: string;
|
||||
aliases: string[];
|
||||
edit_source: string;
|
||||
editor_id: string;
|
||||
edited_at: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface WikiRevisionListResponse {
|
||||
revisions: WikiPageRevision[];
|
||||
total: number;
|
||||
current_version: number;
|
||||
}
|
||||
|
||||
// listWikiRevisions returns the page's historical snapshots newest-first
|
||||
// (content omitted) plus the current version number. The current version has
|
||||
// no revision row — it is the page itself.
|
||||
export function listWikiRevisions(kbId: string, slug: string, params?: { limit?: number; offset?: number }) {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.limit !== undefined) query.set('limit', String(params.limit));
|
||||
if (params?.offset !== undefined) query.set('offset', String(params.offset));
|
||||
const qs = query.toString();
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/revisions/${encodeSlugPath(slug)}${qs ? '?' + qs : ''}`);
|
||||
}
|
||||
|
||||
// getWikiRevision returns one snapshot with full content.
|
||||
export function getWikiRevision(kbId: string, slug: string, version: number) {
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/revisions/${encodeSlugPath(slug)}?version=${version}`);
|
||||
}
|
||||
|
||||
// revertWikiPage rolls the page back to a stored revision. Applied as a
|
||||
// regular edit: the pre-revert state is snapshotted and version advances,
|
||||
// so a revert is itself revertable.
|
||||
export function revertWikiPage(kbId: string, slug: string, version: number) {
|
||||
return post(`/api/v1/knowledgebase/${kbId}/wiki/revert`, { slug, version });
|
||||
}
|
||||
|
||||
export interface WikiIndexEntryDTO {
|
||||
slug: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
parent_slug?: string;
|
||||
category_path?: string[];
|
||||
wiki_path?: string;
|
||||
depth?: number;
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
export interface WikiIndexGroup {
|
||||
type: string;
|
||||
total: number;
|
||||
items: WikiIndexEntryDTO[];
|
||||
next_cursor?: string;
|
||||
}
|
||||
|
||||
export interface WikiIndexResponse {
|
||||
intro: string;
|
||||
version: number;
|
||||
groups: WikiIndexGroup[];
|
||||
}
|
||||
|
||||
// getWikiIndex fetches the structured index view for a wiki KB. The
|
||||
// backend replaced the legacy "markdown blob of intro + directory" with
|
||||
// { intro, groups } so a 40k-page wiki no longer round-trips multiple
|
||||
// megabytes on every index open. Pass `types` to restrict which
|
||||
// page_type buckets come back; `limit` bounds the per-group window;
|
||||
// `cursor` resumes from a previous response.
|
||||
export function getWikiIndex(
|
||||
kbId: string,
|
||||
params?: { types?: string[]; limit?: number; cursor?: string },
|
||||
) {
|
||||
const query = new URLSearchParams();
|
||||
if (params) {
|
||||
if (params.types && params.types.length > 0) query.set('types', params.types.join(','));
|
||||
if (params.limit !== undefined) query.set('limit', String(params.limit));
|
||||
if (params.cursor) query.set('cursor', params.cursor);
|
||||
}
|
||||
const qs = query.toString();
|
||||
const suffix = qs ? `?${qs}` : '';
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/index${suffix}`);
|
||||
}
|
||||
|
||||
export interface WikiGraphQueryParams {
|
||||
mode?: 'overview' | 'ego';
|
||||
center?: string;
|
||||
depth?: number;
|
||||
types?: string[];
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
// getWikiGraph fetches a slice of the wiki link graph. Without params the
|
||||
// backend returns the top-500 most-connected pages (overview mode). Pass
|
||||
// `mode: 'ego', center: <slug>` to drill into a specific page's neighborhood.
|
||||
// For knowledge bases with tens of thousands of pages the overview cap is
|
||||
// what prevents the browser from choking on a 30MB payload / 100k SVG nodes.
|
||||
export function getWikiGraph(kbId: string, params?: WikiGraphQueryParams) {
|
||||
const query = new URLSearchParams();
|
||||
if (params) {
|
||||
if (params.mode) query.set('mode', params.mode);
|
||||
if (params.center) query.set('center', params.center);
|
||||
if (params.depth !== undefined) query.set('depth', String(params.depth));
|
||||
if (params.limit !== undefined) query.set('limit', String(params.limit));
|
||||
if (params.types && params.types.length > 0) {
|
||||
query.set('types', params.types.join(','));
|
||||
}
|
||||
}
|
||||
const qs = query.toString();
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/graph${qs ? '?' + qs : ''}`).then((res: any) => {
|
||||
// Older backends serialize an edgeless subgraph as `"edges": null`.
|
||||
const graph = res?.data || res;
|
||||
if (graph && typeof graph === 'object') {
|
||||
graph.nodes ??= [];
|
||||
graph.edges ??= [];
|
||||
}
|
||||
return res;
|
||||
});
|
||||
}
|
||||
|
||||
export function getWikiStats(kbId: string) {
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/stats`);
|
||||
}
|
||||
|
||||
export function searchWikiPages(kbId: string, q: string, limit?: number) {
|
||||
const params = new URLSearchParams({ q });
|
||||
if (limit) params.set('limit', String(limit));
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/search?${params.toString()}`);
|
||||
}
|
||||
|
||||
export function listWikiIssues(kbId: string, slug?: string, status?: string) {
|
||||
const params = new URLSearchParams();
|
||||
if (slug) params.set('slug', slug);
|
||||
if (status) params.set('status', status);
|
||||
return get(`/api/v1/knowledgebase/${kbId}/wiki/issues?${params.toString()}`);
|
||||
}
|
||||
|
||||
export function updateWikiIssueStatus(kbId: string, issueId: string, status: string) {
|
||||
return put(`/api/v1/knowledgebase/${kbId}/wiki/issues/${issueId}/status`, { status });
|
||||
}
|
||||
|
||||
export function rebuildWikiLinks(kbId: string) {
|
||||
return post(`/api/v1/knowledgebase/${kbId}/wiki/rebuild-links`, {});
|
||||
}
|
||||
Reference in new issue
Block a user