feat: 新增 agentfx 任务深链与研判报告入库流程
支持 goPath=agentfx 的 iframe 嵌入问答、内置研判助手种子与报告导入协助卡,并完善深度研究流式报告能力。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
6e9e89a6cb
commit
52b9cbf707
34 files changed
+4488
-392
No files matched your search
@@ -83,3 +83,22 @@ export async function updateTaskReport(
|
||||
});
|
||||
return readResponse(res, "update task report");
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入并整体替换一个任务的完整 `data` 数组(agentfx 智能体「入库」用)。
|
||||
* 任务必须已存在于 TaskCOP 任务表(否则 404);文件内旧的 taskId 会被路径 id 覆盖。
|
||||
*/
|
||||
export async function importTaskReport(
|
||||
taskId: TaskReportTaskId,
|
||||
data: TaskReportRecordDraft[],
|
||||
): Promise<TaskReportResponse> {
|
||||
const url = `${getBackendBaseURL()}/api/task-reports/import/by-task/${encodeURIComponent(
|
||||
String(taskId),
|
||||
)}`;
|
||||
const res = await apiFetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ data }),
|
||||
});
|
||||
return readResponse(res, "import task report");
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* 「agentfx」任务工作区:复制自 [[TaskFxWorkspace]] 的 3qfx lite 精简版,供新系统
|
||||
* iframe 嵌入(goPath=agentfx 深链,见 [[agentfx-deeplink]])。单独复制一份,后续按新系统
|
||||
* 需求改动互不影响 3qfx / rwfx / xdfx。
|
||||
*
|
||||
* 与 3qfx lite 版的差异:
|
||||
* - 任务详情来自本系统 Gateway 的 cop-task-detail(登录深链时已整包暂存到
|
||||
* sessionStorage 的 login.copTaskDetail,这里只读)。
|
||||
* - 业务映射用 AFX 行(「配置管理」里配置要用的智能体)。
|
||||
* - 无底部「快捷跳转」栏(TaskJumpBar):新系统嵌入 URL 带 hideJump=1 本就不渲染,
|
||||
* 且跳转按钮体系(task-buttons)暂未配置 agentfx 业务。
|
||||
*
|
||||
* 结构与 3qfx 一致:左侧 = 当前任务卡片 + 任务对话列表(按 taskId + agentId 隔离的 1:N)+
|
||||
* 「新建对话」;右侧 = <Outlet/> 渲染选中的对话(AgentChatPage taskBind:新建对话直接带
|
||||
* 开场信息自动发出)。进入 chats 索引:有历史 → 跳最新;无历史 → 跳 new 并自动开始。
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { Outlet, useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
import { Loader2, MessageSquare, PlusSquare } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { readTaskContext } from "@/core/auth/task-purpose";
|
||||
import { readCopTaskDetail } from "@/core/auth/task-deeplink";
|
||||
import { useTaskThreads } from "@/core/threads/use-task-threads";
|
||||
import { titleOfThread } from "@/core/threads/utils";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
import AgentChatPage from "@/pages/AgentChatPage";
|
||||
import { ChatRuntime } from "@/pages/WorkspaceRoutes";
|
||||
|
||||
/** 左列表顶部的业务名标识(3qfx 显示「三情分析」,agentfx 用固定名)。 */
|
||||
const AGENTFX_BUSINESS_NAME = "智能体分析";
|
||||
|
||||
function useChatsBase(taskBase: string): { taskId: string; agentId: string; chatsBase: string } {
|
||||
const { agent_id } = useParams<{ agent_id: string }>();
|
||||
const agentId = agent_id ?? "";
|
||||
const ctx = readTaskContext();
|
||||
const detail = readCopTaskDetail();
|
||||
const fallbackTaskId = detail?.id == null ? "" : String(detail.id).trim();
|
||||
// task context 偶发丢失但任务详情仍在 sessionStorage 时,回退到详情里的 taskId,
|
||||
// 避免左侧对话列表失效成「空任务态」(与 3qfx 相同的自恢复策略)。
|
||||
const taskId = ctx?.taskId ?? fallbackTaskId;
|
||||
return { taskId, agentId, chatsBase: `${taskBase}/agent/${agentId}/chats` };
|
||||
}
|
||||
|
||||
/**
|
||||
* 左侧顶部「当前任务」卡片:展示登录深链查询出的任务名称 + 简介(暂存在 sessionStorage 的
|
||||
* copTaskDetail)。无任务详情时不渲染。
|
||||
*/
|
||||
function TaskDetailHeader() {
|
||||
const detail = useMemo(() => readCopTaskDetail(), []);
|
||||
const name = desensitize((detail?.taskName ?? "").trim());
|
||||
const brief = desensitize(((detail?.overview ?? "").trim() || (detail?.taskContent ?? "").trim()));
|
||||
if (!name && !brief) return null;
|
||||
return (
|
||||
<div className="mb-3 rounded-md border border-[var(--card-border)] bg-background/70 p-2.5 shadow-sm dark:border-[#2b8ffe]/40 dark:bg-[#0b2546]/70">
|
||||
<div className="text-muted-foreground mb-1 text-[11px] font-medium">当前任务</div>
|
||||
{name && (
|
||||
<div
|
||||
className="text-foreground line-clamp-2 text-sm font-semibold leading-snug"
|
||||
title={name}
|
||||
>
|
||||
{name}
|
||||
</div>
|
||||
)}
|
||||
{brief && (
|
||||
<div
|
||||
className="text-muted-foreground mt-1 line-clamp-3 text-xs leading-relaxed"
|
||||
title={brief}
|
||||
>
|
||||
{brief}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 从路由路径里解析当前打开的会话 id(布局组件读不到子路由的 :thread_id,故从 path 取)。 */
|
||||
function parseThreadId(pathname: string, chatsBase: string): string | null {
|
||||
if (!pathname.startsWith(chatsBase)) return null;
|
||||
const seg = pathname.slice(chatsBase.length).replace(/^\/+/, "").split("/")[0];
|
||||
return seg && seg !== "new" ? seg : null;
|
||||
}
|
||||
|
||||
/** 左侧任务对话列表:顶部「当前任务」卡片 +「新建对话」;下方对话列表(1:N)。 */
|
||||
function TaskConversationsList({
|
||||
taskId,
|
||||
agentId,
|
||||
chatsBase,
|
||||
}: {
|
||||
taskId: string;
|
||||
agentId: string;
|
||||
chatsBase: string;
|
||||
}) {
|
||||
const { pathname } = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { threads, isLoading } = useTaskThreads(taskId, agentId);
|
||||
const currentThreadId = useMemo(() => parseThreadId(pathname, chatsBase), [pathname, chatsBase]);
|
||||
|
||||
return (
|
||||
<div className="bg-background/85 border-border/70 flex w-64 shrink-0 flex-col border-r shadow-[12px_0_30px_-30px_rgba(15,23,42,0.45)] backdrop-blur-xl dark:border-[#1b477e]/70 dark:bg-[#061b35]/82">
|
||||
<div className="border-border/70 border-b p-3 dark:border-[#1b477e]/70">
|
||||
{/* 左上角标明当前是哪个分析页面 */}
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<span className="h-4 w-1 rounded-full bg-[var(--color-main)]" />
|
||||
<span className="text-foreground text-sm font-semibold tracking-wide">
|
||||
{AGENTFX_BUSINESS_NAME}
|
||||
</span>
|
||||
</div>
|
||||
<TaskDetailHeader />
|
||||
<div className="mb-2 flex items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<div className="text-foreground text-sm font-semibold">任务对话</div>
|
||||
<div className="text-muted-foreground mt-0.5 text-xs tabular-nums">
|
||||
{isLoading ? "同步中" : `${threads.length} 个会话`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-9 w-full bg-[var(--color-main)] text-white shadow-sm hover:bg-[var(--brand-950)]"
|
||||
onClick={() => navigate(`${chatsBase}/new`)}
|
||||
>
|
||||
<PlusSquare className="h-4 w-4" /> 新建对话
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-2">
|
||||
{isLoading ? (
|
||||
<div className="text-muted-foreground rounded-md border border-dashed p-3 text-center text-sm dark:border-[#1b477e]/60">
|
||||
加载中…
|
||||
</div>
|
||||
) : threads.length === 0 ? (
|
||||
<div className="text-muted-foreground rounded-md border border-dashed p-3 text-center text-sm dark:border-[#1b477e]/60">
|
||||
暂无对话
|
||||
</div>
|
||||
) : (
|
||||
threads.map((thread) => (
|
||||
<button
|
||||
key={thread.thread_id}
|
||||
onClick={() => navigate(`${chatsBase}/${thread.thread_id}`)}
|
||||
className={cn(
|
||||
"group relative flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm transition-colors",
|
||||
"hover:bg-[var(--bg-color)] dark:hover:bg-[#0d2a4d]/85",
|
||||
thread.thread_id === currentThreadId &&
|
||||
"bg-[var(--bg-color)] font-medium text-[var(--color-main)] shadow-sm dark:bg-[#0d2a4d] dark:text-[#9fe3ff]",
|
||||
)}
|
||||
title={desensitize(titleOfThread(thread, "新对话"))}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"absolute inset-y-2 left-0 w-0.5 rounded-full bg-transparent transition-colors",
|
||||
thread.thread_id === currentThreadId && "bg-[var(--color-main)] dark:bg-[#64cdf5]",
|
||||
)}
|
||||
/>
|
||||
<MessageSquare className="text-muted-foreground group-hover:text-foreground h-3.5 w-3.5 shrink-0" />
|
||||
<span className="truncate">{desensitize(titleOfThread(thread, "新对话"))}</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** agentfx 任务工作区布局:左列表 + 右 Outlet。 */
|
||||
export function AgentFxWorkspace({ taskBase }: { taskBase: string }) {
|
||||
const { taskId, agentId, chatsBase } = useChatsBase(taskBase);
|
||||
return (
|
||||
<div className="flex size-full min-h-0 flex-col overflow-hidden">
|
||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||
<TaskConversationsList taskId={taskId} agentId={agentId} chatsBase={chatsBase} />
|
||||
<div className="relative min-h-0 min-w-0 flex-1">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** chats 索引:有历史对话 → 跳最新;否则 → 跳 new 并打 taskAutoStart 标记(自动发开场词)。 */
|
||||
export function AgentFxIndexResolver({ taskBase }: { taskBase: string }) {
|
||||
const { taskId, agentId, chatsBase } = useChatsBase(taskBase);
|
||||
const navigate = useNavigate();
|
||||
const { isLoading, hasThreads, latestThreadId } = useTaskThreads(taskId, agentId);
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoading) return;
|
||||
if (hasThreads && latestThreadId) {
|
||||
navigate(`${chatsBase}/${latestThreadId}`, { replace: true });
|
||||
} else {
|
||||
navigate(`${chatsBase}/new`, { replace: true, state: { taskAutoStart: true } });
|
||||
}
|
||||
}, [isLoading, hasThreads, latestThreadId, chatsBase, navigate]);
|
||||
|
||||
return (
|
||||
<div className="text-muted-foreground flex size-full items-center justify-center">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 右侧对话宿主:AgentChatPage taskBind → 仅 1:N 绑定,新建对话自动发出任务开场信息。 */
|
||||
export function AgentFxChat({ taskBase }: { taskBase: string }) {
|
||||
const { agent_id } = useParams<{ agent_id: string }>();
|
||||
return (
|
||||
<ChatRuntime>
|
||||
<AgentChatPage chatBasePath={`${taskBase}/agent/${agent_id}/chats`} taskBind />
|
||||
</ChatRuntime>
|
||||
);
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* agentfx「入库」用户协助卡片:任务研判报告智能体生成 report.md + task-reports.json
|
||||
* 并给出总结后,由 AgentChatPage(taskBind)注入到消息流尾部渲染本卡。
|
||||
*
|
||||
* 「开始入库」:读取沙箱产物 task-reports.json → 按 14 类结构校验(与后端
|
||||
* task-report-import 技能同规则)→ POST /api/task-reports/import/by-task/{taskId}
|
||||
* 整体替换任务详情。「暂不入库」仅收起卡片(用户之后可让智能体走技能入库)。
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { CheckCircle2, Database, Loader2, TriangleAlert } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { loadArtifactContent } from "@/core/artifacts/loader";
|
||||
import { importTaskReport } from "@/strategy-components/api/task-reports";
|
||||
import {
|
||||
AGENTFX_REPORT_JSON_OUTPUT_PATH,
|
||||
notifyTaskReportSaved,
|
||||
validateAgentfxReportText,
|
||||
type AgentfxReportValidation,
|
||||
} from "@/strategy-components/lib/agentfx-report-schema";
|
||||
|
||||
type Phase = "loading" | "ready" | "importing" | "done" | "error";
|
||||
|
||||
export function TaskReportImportCard({
|
||||
taskId,
|
||||
threadId,
|
||||
jsonPath = AGENTFX_REPORT_JSON_OUTPUT_PATH,
|
||||
onImported,
|
||||
onDismiss,
|
||||
}: {
|
||||
taskId: string;
|
||||
threadId: string;
|
||||
/** 沙箱产物路径(默认智能体 SOUL 约定的 task-reports.json)。 */
|
||||
jsonPath?: string;
|
||||
/** 入库成功回调(宿主据此刷新任务详情状态、收起卡片)。 */
|
||||
onImported?: () => void;
|
||||
/** 「暂不入库」回调(宿主收起卡片)。 */
|
||||
onDismiss?: () => void;
|
||||
}) {
|
||||
const [phase, setPhase] = useState<Phase>("loading");
|
||||
const [validation, setValidation] = useState<AgentfxReportValidation | null>(null);
|
||||
const [errorMsg, setErrorMsg] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setPhase("loading");
|
||||
void loadArtifactContent({ filepath: jsonPath, threadId })
|
||||
.then(({ content }) => {
|
||||
if (!alive) return;
|
||||
if (!content) {
|
||||
setErrorMsg("读取报告 JSON 失败(文件为空或不存在)");
|
||||
setPhase("error");
|
||||
return;
|
||||
}
|
||||
setValidation(validateAgentfxReportText(content, { sessionId: threadId }));
|
||||
setPhase("ready");
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!alive) return;
|
||||
setErrorMsg(error instanceof Error ? error.message : "读取报告 JSON 失败");
|
||||
setPhase("error");
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [jsonPath, threadId]);
|
||||
|
||||
const handleImport = useCallback(async () => {
|
||||
if (!validation || !validation.ok) return;
|
||||
setPhase("importing");
|
||||
try {
|
||||
const response = await importTaskReport(taskId, validation.records);
|
||||
const count = response.data?.length ?? 0;
|
||||
setPhase("done");
|
||||
toast.success(`入库成功:已写入 ${count} 条任务详情`);
|
||||
// iframe 嵌入场景:通知外部宿主系统任务详情已保存。
|
||||
notifyTaskReportSaved(taskId);
|
||||
onImported?.();
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "入库失败";
|
||||
setErrorMsg(message);
|
||||
setPhase("error");
|
||||
toast.error(`入库失败:${message}`);
|
||||
}
|
||||
}, [onImported, taskId, validation]);
|
||||
|
||||
return (
|
||||
<div className="border-border/70 bg-background/85 mx-auto w-full max-w-[760px] rounded-xl border p-4 shadow-sm backdrop-blur-xl dark:border-[#1b477e]/70 dark:bg-[#061b35]/82">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="bg-[var(--color-main)]/10 text-[var(--color-main)] mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
||||
<Database className="h-4.5 w-4.5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-foreground text-sm font-semibold">研判报告已生成,是否入库?</div>
|
||||
<div className="text-muted-foreground mt-1 text-xs leading-relaxed">
|
||||
入库会把结构化结果(任务详情,14 个分类)整体写入任务
|
||||
<span className="text-foreground mx-1 font-medium">{taskId}</span>
|
||||
,已有详情会被覆盖;报告文件(report.md / task-reports.json)保留在沙箱中。
|
||||
</div>
|
||||
|
||||
{phase === "loading" && (
|
||||
<div className="text-muted-foreground mt-3 flex items-center gap-1.5 text-xs">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" /> 正在校验报告 JSON…
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "ready" && validation && (
|
||||
<div className="mt-3 space-y-1.5 text-xs">
|
||||
{validation.ok ? (
|
||||
<div className="text-muted-foreground flex items-center gap-1.5">
|
||||
<CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
|
||||
校验通过:{validation.presentCategories.length} / 14 个分类
|
||||
{validation.missingCategories.length > 0 && (
|
||||
<span>(缺少:{validation.missingCategories.join("、")})</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground flex items-start gap-1.5">
|
||||
<TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500" />
|
||||
<span>
|
||||
{validation.records.length > 0
|
||||
? `校验发现 ${validation.errors.length} 处问题,可导入 ${validation.records.length} 条合法记录:`
|
||||
: "校验未通过:"}
|
||||
{validation.errors.slice(0, 3).join(";")}
|
||||
{validation.errors.length > 3 && ` 等 ${validation.errors.length} 处`}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "error" && (
|
||||
<div className="text-muted-foreground mt-3 flex items-start gap-1.5 text-xs">
|
||||
<TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500" />
|
||||
<span>{errorMsg || "发生错误"}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "done" && (
|
||||
<div className="text-muted-foreground mt-3 flex items-center gap-1.5 text-xs">
|
||||
<CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" /> 已入库;可在任务管理侧查看任务详情。
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(phase === "ready" || phase === "error") && (
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-8 bg-[var(--color-main)] text-white shadow-sm hover:bg-[var(--brand-950)]"
|
||||
disabled={phase !== "ready" || !validation?.ok}
|
||||
onClick={() => void handleImport()}
|
||||
>
|
||||
<Database className="h-3.5 w-3.5" /> 开始入库
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" className="h-8" onClick={onDismiss}>
|
||||
暂不入库
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "importing" && (
|
||||
<div className="text-muted-foreground mt-3 flex items-center gap-1.5 text-xs">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" /> 正在入库…
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* agentfx「任务研判报告」的结构校验(前端版)。
|
||||
*
|
||||
* 与后端技能脚本 `task-report-import/scripts/task_report_import.py` 保持同一套规则:
|
||||
* 14 个固定 `categoryType`、`contentJson` 必须是合法 JSON(对象自动序列化为字符串)。
|
||||
* 协助卡点「开始入库」时先用它把智能体生成的 `task-reports.json`(沙箱产物)校验成
|
||||
* 与导入示例一致的结构,再 POST 到 `/api/task-reports/import/by-task/{taskId}`。
|
||||
*/
|
||||
|
||||
import type { TaskReportRecordDraft } from "@/strategy-components/api/task-reports";
|
||||
|
||||
/** 智能体(SOUL.md 约定)写出的两份沙箱产物路径。 */
|
||||
export const AGENTFX_REPORT_MD_OUTPUT_PATH = "/mnt/user-data/outputs/report.md";
|
||||
export const AGENTFX_REPORT_JSON_OUTPUT_PATH = "/mnt/user-data/outputs/task-reports.json";
|
||||
|
||||
/** 14 个固定分类(与任务详情导入示例一致,均带 “ JSON” 后缀)。 */
|
||||
export const AGENTFX_REPORT_CATEGORY_TYPES: readonly string[] = [
|
||||
"信息环境 JSON",
|
||||
"人文环境 JSON",
|
||||
"敌情关键事件 JSON",
|
||||
"敌情对手叙事 JSON",
|
||||
"敌情目标 JSON",
|
||||
"我情口径 JSON",
|
||||
"我情叙事 JSON",
|
||||
"我情上级要求 JSON",
|
||||
"条件与限制 JSON",
|
||||
"优劣势分析 JSON",
|
||||
"风险及应对 JSON",
|
||||
"行动方案 JSON",
|
||||
"处置建议 JSON",
|
||||
"决心建议 JSON",
|
||||
];
|
||||
|
||||
export interface AgentfxReportValidation {
|
||||
/** 至少有一条合法记录且无校验错误。 */
|
||||
ok: boolean;
|
||||
/** 可直接交给 importTaskReport 的记录(id/时间由后端自动补齐)。 */
|
||||
records: TaskReportRecordDraft[];
|
||||
presentCategories: string[];
|
||||
missingCategories: string[];
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 入库成功后通知外部宿主系统(iframe 嵌入场景):向 window.top 广播
|
||||
* ``{source: "magent-web", type: "task-report:saved", taskId}``。卡片入库与
|
||||
* 技能入库两条路径成功后都会调用;未嵌入时 window.top 即自身,无人监听则自然空操作。
|
||||
*/
|
||||
export function notifyTaskReportSaved(taskId: string | number): void {
|
||||
try {
|
||||
window.top?.postMessage(
|
||||
{
|
||||
source: "magent-web",
|
||||
type: "task-report:saved",
|
||||
taskId: String(taskId),
|
||||
},
|
||||
"*",
|
||||
);
|
||||
} catch {
|
||||
/* 跨域受限环境访问 window.top 异常时静默忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
function stringifyContent(value: unknown): string | null {
|
||||
if (typeof value === "string") {
|
||||
if (!value.trim()) return null;
|
||||
try {
|
||||
// 归一化:parse 后重新序列化,把模型可能写的 \uXXXX 转义还原为汉字原文
|
||||
// (JSON.stringify 不会 ASCII 转义非 ASCII 字符)。
|
||||
return JSON.stringify(JSON.parse(value));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (value !== null && typeof value === "object") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验智能体生成的报告 JSON 文本:接受裸数组或 `{data|records: [...]}` 信封;
|
||||
* 每条记录必须有合法 `categoryType`(14 类之一)与可解析的 `contentJson`。
|
||||
*/
|
||||
export function validateAgentfxReportText(
|
||||
raw: string,
|
||||
options?: { sessionId?: string },
|
||||
): AgentfxReportValidation {
|
||||
const result: AgentfxReportValidation = {
|
||||
ok: false,
|
||||
records: [],
|
||||
presentCategories: [],
|
||||
missingCategories: [],
|
||||
errors: [],
|
||||
};
|
||||
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = JSON.parse(raw);
|
||||
} catch {
|
||||
result.errors.push("报告文件不是合法 JSON");
|
||||
return result;
|
||||
}
|
||||
|
||||
let rawRecords: unknown[] | null = null;
|
||||
if (Array.isArray(payload)) {
|
||||
rawRecords = payload;
|
||||
} else if (payload && typeof payload === "object") {
|
||||
const envelope = payload as { data?: unknown; records?: unknown };
|
||||
if (Array.isArray(envelope.data)) rawRecords = envelope.data;
|
||||
else if (Array.isArray(envelope.records)) rawRecords = envelope.records;
|
||||
}
|
||||
if (!rawRecords) {
|
||||
result.errors.push("JSON 必须是数组,或包含 data/records 数组的对象");
|
||||
return result;
|
||||
}
|
||||
|
||||
const present = new Set<string>();
|
||||
rawRecords.forEach((item, index) => {
|
||||
const label = `第 ${index + 1} 条`;
|
||||
if (!item || typeof item !== "object" || Array.isArray(item)) {
|
||||
result.errors.push(`${label}不是对象`);
|
||||
return;
|
||||
}
|
||||
const record = item as Record<string, unknown>;
|
||||
const category = String(record.categoryType ?? record.category_type ?? "").trim();
|
||||
if (!AGENTFX_REPORT_CATEGORY_TYPES.includes(category)) {
|
||||
result.errors.push(`${label} categoryType 非法:${category || "(空)"}`);
|
||||
return;
|
||||
}
|
||||
const content = stringifyContent(
|
||||
"contentJson" in record ? record.contentJson : record.content_json,
|
||||
);
|
||||
if (content === null) {
|
||||
result.errors.push(`${label}(${category})contentJson 缺失或不是合法 JSON`);
|
||||
return;
|
||||
}
|
||||
present.add(category);
|
||||
result.records.push({
|
||||
contentJson: content,
|
||||
categoryType: category,
|
||||
sessionId: options?.sessionId ?? "",
|
||||
});
|
||||
});
|
||||
|
||||
result.presentCategories = [...present];
|
||||
result.missingCategories = AGENTFX_REPORT_CATEGORY_TYPES.filter((c) => !present.has(c));
|
||||
result.ok = result.records.length > 0 && result.errors.length === 0;
|
||||
return result;
|
||||
}
|
||||
Reference in new issue
Block a user