1. Y-Log 上报 optDetail 前缀 B1-CM助手 → CM助手-全量(全量替换 44 个前端文件 + 文档) 2. 知识库入库 nodeName 改为只取 md5(标题).md(去掉时间戳),同一篇 md 每次入库一致,避免重复记录 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
541 lines
17 KiB
TypeScript
541 lines
17 KiB
TypeScript
import { getBackendBaseURL } from "@/core/config";
|
|
import { apiFetch } from "@/core/api";
|
|
import { OptType, writeYLog } from "@/core/log/y-log";
|
|
|
|
import type {
|
|
Agent,
|
|
AgentSelectorResponse,
|
|
AgentSort,
|
|
CreateAgentRequest,
|
|
PaginatedAgents,
|
|
UpdateAgentRequest,
|
|
} from "./types";
|
|
|
|
const BACKEND_UNAVAILABLE_STATUSES = new Set([502, 503, 504]);
|
|
|
|
export class AgentNameCheckError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public readonly reason: "backend_unreachable" | "request_failed",
|
|
) {
|
|
super(message);
|
|
this.name = "AgentNameCheckError";
|
|
}
|
|
}
|
|
|
|
export interface ListAgentsParams {
|
|
search?: string;
|
|
tagIds?: string[];
|
|
/** Pagination scope. Omit for the legacy combined-visibility list.
|
|
* "builtin" = 内置智能体 (user_id IS NULL), admin only — backend 403s non-admins. */
|
|
scope?: "mine" | "square" | "builtin";
|
|
/** 1-based page index. Providing this (or scope) enables server-side pagination. */
|
|
page?: number;
|
|
pageSize?: number;
|
|
sort?: AgentSort;
|
|
/** Keep only agents published by this user id (the card's publisher). */
|
|
owner?: string;
|
|
/** Keep only agents filed under this publish square (发布广场). */
|
|
square?: string;
|
|
}
|
|
|
|
function buildAgentsQuery(params: ListAgentsParams): string {
|
|
const qs = new URLSearchParams();
|
|
if (params.search) qs.set("search", params.search);
|
|
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
|
|
if (params.scope) qs.set("scope", params.scope);
|
|
if (params.page != null) qs.set("page", String(params.page));
|
|
if (params.pageSize != null) qs.set("page_size", String(params.pageSize));
|
|
if (params.sort) qs.set("sort", params.sort);
|
|
if (params.owner) qs.set("owner", params.owner);
|
|
if (params.square) qs.set("square", params.square);
|
|
return qs.toString();
|
|
}
|
|
|
|
export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]> {
|
|
const query = buildAgentsQuery(params);
|
|
const res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
|
|
);
|
|
if (!res.ok) throw new Error(`Failed to load agents: ${res.statusText}`);
|
|
const data = (await res.json()) as { agents: Agent[] };
|
|
writeYLog({
|
|
optType: OptType.search,
|
|
optDetail: "CM助手-全量-智能体列表",
|
|
url: `/api/agents${query ? `?${query}` : ""}`,
|
|
reqParam: params,
|
|
returnParam: data.agents,
|
|
});
|
|
return data.agents;
|
|
}
|
|
|
|
/** Like {@link listAgents} but returns the pagination envelope (total/page). */
|
|
export async function listAgentsPaginated(
|
|
params: ListAgentsParams = {},
|
|
): Promise<PaginatedAgents> {
|
|
const query = buildAgentsQuery(params);
|
|
const res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
|
|
);
|
|
if (!res.ok) throw new Error(`Failed to load agents: ${res.statusText}`);
|
|
const data = (await res.json()) as {
|
|
agents: Agent[];
|
|
total?: number;
|
|
page?: number;
|
|
page_size?: number;
|
|
};
|
|
const result: PaginatedAgents = {
|
|
agents: data.agents,
|
|
total: data.total ?? data.agents.length,
|
|
page: data.page ?? params.page ?? 1,
|
|
pageSize: data.page_size ?? params.pageSize ?? data.agents.length,
|
|
};
|
|
writeYLog({
|
|
optType: OptType.search,
|
|
optDetail: "CM助手-全量-智能体列表",
|
|
url: `/api/agents${query ? `?${query}` : ""}`,
|
|
reqParam: params,
|
|
returnParam: result,
|
|
});
|
|
return result;
|
|
}
|
|
|
|
export async function listAllAgentsAdmin(): Promise<Agent[]> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents?admin=true`);
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(err.detail ?? `Failed to load agents: ${res.statusText}`);
|
|
}
|
|
const data = (await res.json()) as { agents: Agent[] };
|
|
writeYLog({
|
|
optType: OptType.search,
|
|
optDetail: "CM助手-全量-智能体列表",
|
|
url: `/api/agents?admin=true`,
|
|
returnParam: data.agents,
|
|
});
|
|
return data.agents;
|
|
}
|
|
|
|
export async function getAgent(id: string): Promise<Agent> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}`);
|
|
if (!res.ok) throw new Error(`Agent '${id}' not found`);
|
|
const agent = (await res.json()) as Agent;
|
|
writeYLog({
|
|
optType: OptType.view,
|
|
optDetail: "CM助手-全量-智能体-查看",
|
|
url: `/api/agents/${id}`,
|
|
reqParam: { id },
|
|
returnParam: agent,
|
|
});
|
|
return agent;
|
|
}
|
|
|
|
export async function createAgent(request: CreateAgentRequest): Promise<Agent> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(request),
|
|
});
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(err.detail ?? `Failed to create agent: ${res.statusText}`);
|
|
}
|
|
const created = (await res.json()) as Agent;
|
|
writeYLog({
|
|
optType: OptType.create,
|
|
optDetail: "CM助手-全量-智能体-新建",
|
|
url: `/api/agents`,
|
|
reqParam: request,
|
|
returnParam: created,
|
|
});
|
|
return created;
|
|
}
|
|
|
|
export async function updateAgent(
|
|
id: string,
|
|
request: UpdateAgentRequest,
|
|
): Promise<Agent> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}`, {
|
|
method: "PUT",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(request),
|
|
});
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(err.detail ?? `Failed to update agent: ${res.statusText}`);
|
|
}
|
|
const updated = (await res.json()) as Agent;
|
|
writeYLog({
|
|
optType: OptType.edit,
|
|
optDetail: "CM助手-全量-智能体-修改",
|
|
url: `/api/agents/${id}`,
|
|
reqParam: { id, ...request },
|
|
returnParam: updated,
|
|
});
|
|
return updated;
|
|
}
|
|
|
|
export async function deleteAgent(id: string): Promise<void> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}`, {
|
|
method: "DELETE",
|
|
});
|
|
if (!res.ok) throw new Error(`Failed to delete agent: ${res.statusText}`);
|
|
writeYLog({
|
|
optType: OptType.delete,
|
|
optDetail: "CM助手-全量-智能体-删除",
|
|
url: `/api/agents/${id}`,
|
|
reqParam: { id },
|
|
});
|
|
}
|
|
|
|
export async function getAgentSelector(): Promise<AgentSelectorResponse> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/selector`);
|
|
if (!res.ok) throw new Error(`Failed to load agent selector: ${res.statusText}`);
|
|
const selector = (await res.json()) as AgentSelectorResponse;
|
|
writeYLog({
|
|
optType: OptType.search,
|
|
optDetail: "CM助手-全量-智能体-选择器",
|
|
url: `/api/agents/selector`,
|
|
returnParam: selector,
|
|
});
|
|
return selector;
|
|
}
|
|
|
|
export async function favoriteAgent(id: string): Promise<void> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/favorite`, {
|
|
method: "POST",
|
|
});
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(err.detail ?? `Failed to favorite agent: ${res.statusText}`);
|
|
}
|
|
writeYLog({
|
|
optType: OptType.edit,
|
|
optDetail: "CM助手-全量-智能体-收藏",
|
|
url: `/api/agents/${id}/favorite`,
|
|
reqParam: { id },
|
|
});
|
|
}
|
|
|
|
export async function unfavoriteAgent(id: string): Promise<void> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/favorite`, {
|
|
method: "DELETE",
|
|
});
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(err.detail ?? `Failed to unfavorite agent: ${res.statusText}`);
|
|
}
|
|
writeYLog({
|
|
optType: OptType.edit,
|
|
optDetail: "CM助手-全量-智能体-取消收藏",
|
|
url: `/api/agents/${id}/favorite`,
|
|
reqParam: { id },
|
|
});
|
|
}
|
|
|
|
export async function pinAgent(id: string): Promise<void> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/pin`, {
|
|
method: "POST",
|
|
});
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(err.detail ?? `Failed to pin agent: ${res.statusText}`);
|
|
}
|
|
writeYLog({
|
|
optType: OptType.edit,
|
|
optDetail: "CM助手-全量-智能体-置顶",
|
|
url: `/api/agents/${id}/pin`,
|
|
reqParam: { id },
|
|
});
|
|
}
|
|
|
|
export async function unpinAgent(id: string): Promise<void> {
|
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/pin`, {
|
|
method: "DELETE",
|
|
});
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(err.detail ?? `Failed to unpin agent: ${res.statusText}`);
|
|
}
|
|
writeYLog({
|
|
optType: OptType.edit,
|
|
optDetail: "CM助手-全量-智能体-取消置顶",
|
|
url: `/api/agents/${id}/pin`,
|
|
reqParam: { id },
|
|
});
|
|
}
|
|
|
|
export async function reorderFeaturedAgents(agentIds: string[]): Promise<void> {
|
|
const res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/agents/featured/order`,
|
|
{
|
|
method: "PUT",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ agent_ids: agentIds }),
|
|
},
|
|
);
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(
|
|
err.detail ?? `Failed to reorder featured agents: ${res.statusText}`,
|
|
);
|
|
}
|
|
writeYLog({
|
|
optType: OptType.edit,
|
|
optDetail: "CM助手-全量-智能体-精选排序",
|
|
url: `/api/agents/featured/order`,
|
|
reqParam: { agent_ids: agentIds },
|
|
});
|
|
}
|
|
|
|
export async function listPrivateAgents(password: string): Promise<Agent[]> {
|
|
const res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/agents/private-square/list`,
|
|
{
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ password }),
|
|
},
|
|
);
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(
|
|
err.detail ?? `Failed to load private agents: ${res.statusText}`,
|
|
);
|
|
}
|
|
const data = (await res.json()) as { agents: Agent[] };
|
|
writeYLog({
|
|
optType: OptType.search,
|
|
optDetail: "CM助手-全量-私有广场智能体列表",
|
|
url: `/api/agents/private-square/list`,
|
|
returnParam: data.agents,
|
|
});
|
|
return data.agents;
|
|
}
|
|
|
|
export interface ListPrivateAgentsParams {
|
|
password: string;
|
|
search?: string;
|
|
tagIds?: string[];
|
|
page?: number;
|
|
pageSize?: number;
|
|
sort?: AgentSort;
|
|
/** Keep only agents published by this user id (the card's publisher). */
|
|
owner?: string;
|
|
}
|
|
|
|
/** Paginated private-square listing (password-gated). */
|
|
export async function listPrivateAgentsPaginated(
|
|
params: ListPrivateAgentsParams,
|
|
): Promise<PaginatedAgents> {
|
|
const res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/agents/private-square/list`,
|
|
{
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
password: params.password,
|
|
search: params.search || undefined,
|
|
tag_ids: params.tagIds && params.tagIds.length ? params.tagIds : undefined,
|
|
page: params.page,
|
|
page_size: params.pageSize,
|
|
sort: params.sort,
|
|
owner: params.owner || undefined,
|
|
}),
|
|
},
|
|
);
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(
|
|
err.detail ?? `Failed to load private agents: ${res.statusText}`,
|
|
);
|
|
}
|
|
const data = (await res.json()) as {
|
|
agents: Agent[];
|
|
total?: number;
|
|
page?: number;
|
|
page_size?: number;
|
|
};
|
|
const result: PaginatedAgents = {
|
|
agents: data.agents,
|
|
total: data.total ?? data.agents.length,
|
|
page: data.page ?? params.page ?? 1,
|
|
pageSize: data.page_size ?? params.pageSize ?? data.agents.length,
|
|
};
|
|
writeYLog({
|
|
optType: OptType.search,
|
|
optDetail: "CM助手-全量-私有广场智能体列表",
|
|
url: `/api/agents/private-square/list`,
|
|
reqParam: { ...params, password: undefined },
|
|
returnParam: result,
|
|
});
|
|
return result;
|
|
}
|
|
|
|
export async function setAgentPrivate(
|
|
id: string,
|
|
isPrivate: boolean,
|
|
): Promise<Agent> {
|
|
const res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/agents/${id}/private`,
|
|
{
|
|
method: "PUT",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ is_private: isPrivate }),
|
|
},
|
|
);
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(
|
|
err.detail ?? `Failed to update agent privacy: ${res.statusText}`,
|
|
);
|
|
}
|
|
const updated = (await res.json()) as Agent;
|
|
writeYLog({
|
|
optType: OptType.edit,
|
|
optDetail: "CM助手-全量-智能体-设置私有",
|
|
url: `/api/agents/${id}/private`,
|
|
reqParam: { id, is_private: isPrivate },
|
|
returnParam: updated,
|
|
});
|
|
return updated;
|
|
}
|
|
|
|
export async function setAgentFeatured(
|
|
id: string,
|
|
order: number | null,
|
|
): Promise<Agent> {
|
|
const res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/agents/${id}/featured`,
|
|
{
|
|
method: "PUT",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ order }),
|
|
},
|
|
);
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(
|
|
err.detail ?? `Failed to set featured: ${res.statusText}`,
|
|
);
|
|
}
|
|
const updated = (await res.json()) as Agent;
|
|
writeYLog({
|
|
optType: OptType.edit,
|
|
optDetail: "CM助手-全量-智能体-设置精选",
|
|
url: `/api/agents/${id}/featured`,
|
|
reqParam: { id, order },
|
|
returnParam: updated,
|
|
});
|
|
return updated;
|
|
}
|
|
|
|
export interface AgentSkillsSyncRemoval {
|
|
agent_id: string;
|
|
agent_name: string | null;
|
|
user_id: string | null;
|
|
removed_skills: string[];
|
|
}
|
|
|
|
export interface AgentSkillsSyncResult {
|
|
checked: number;
|
|
modified: number;
|
|
removals: AgentSkillsSyncRemoval[];
|
|
}
|
|
|
|
export async function adminSyncAgentSkills(): Promise<AgentSkillsSyncResult> {
|
|
const res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/agents/admin/sync-skills`,
|
|
{ method: "POST" },
|
|
);
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(err.detail ?? `Failed to sync agent skills: ${res.statusText}`);
|
|
}
|
|
const result = (await res.json()) as AgentSkillsSyncResult;
|
|
writeYLog({
|
|
optType: OptType.edit,
|
|
optDetail: "CM助手-全量-智能体-同步技能",
|
|
url: `/api/agents/admin/sync-skills`,
|
|
returnParam: result,
|
|
});
|
|
return result;
|
|
}
|
|
|
|
export interface KnowledgeIngestAttempt {
|
|
title_field: string;
|
|
status_code: number | null;
|
|
response_text: string;
|
|
success: boolean;
|
|
error: string | null;
|
|
}
|
|
|
|
export interface KnowledgeIngestPublishResult {
|
|
success: boolean;
|
|
template_name: string;
|
|
node_name: string;
|
|
batch_number: string;
|
|
attempts: KnowledgeIngestAttempt[];
|
|
}
|
|
|
|
/** 把一份 md 产物(标题 + 全文)发布到外部知识入库接口。后端会先按
|
|
* 「名称」字段映射发送,失败后用同一 nodeName 换「标题」字段重试一次。 */
|
|
export async function publishArtifactToKnowledge(request: {
|
|
agent_id: string;
|
|
title: string;
|
|
content: string;
|
|
}): Promise<KnowledgeIngestPublishResult> {
|
|
const res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/knowledge-ingest/publish`,
|
|
{
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(request),
|
|
},
|
|
);
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
throw new Error(err.detail ?? `发布入库失败: ${res.statusText}`);
|
|
}
|
|
const result = (await res.json()) as KnowledgeIngestPublishResult;
|
|
writeYLog({
|
|
optType: OptType.export,
|
|
optDetail: "CM助手-全量-智能体-产物发布入库",
|
|
url: `/api/knowledge-ingest/publish`,
|
|
reqParam: request,
|
|
returnParam: result,
|
|
});
|
|
return result;
|
|
}
|
|
|
|
export async function checkAgentName(
|
|
name: string,
|
|
): Promise<{ available: boolean; name: string }> {
|
|
let res: Response;
|
|
try {
|
|
res = await apiFetch(
|
|
`${getBackendBaseURL()}/api/agents/check?name=${encodeURIComponent(name)}`,
|
|
);
|
|
} catch {
|
|
throw new AgentNameCheckError(
|
|
"Could not reach the CM Assistant backend.",
|
|
"backend_unreachable",
|
|
);
|
|
}
|
|
|
|
if (!res.ok) {
|
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
|
if (BACKEND_UNAVAILABLE_STATUSES.has(res.status)) {
|
|
throw new AgentNameCheckError(
|
|
"Could not reach the CM Assistant backend.",
|
|
"backend_unreachable",
|
|
);
|
|
}
|
|
throw new AgentNameCheckError(
|
|
err.detail ?? `Failed to check agent name: ${res.statusText}`,
|
|
"request_failed",
|
|
);
|
|
}
|
|
return res.json() as Promise<{ available: boolean; name: string }>;
|
|
}
|