Răsfoiți Sursa

fix(agent): 修复分析运行时与子代理测试发现的五处缺陷

- 工作区产物登记(BUG-1):execute_python 交付物目录对齐——
  outputs/ 与 work/outputs/ 双路径登记,prepare 预建 work/outputs;
  修复模型按工具描述写 ./outputs 后产物永不登记的问题
- 子代理记忆隔离(BUG-2):子代理构建禁用 memory 工具与钩子,
  一次性实例不再读到前实例 memory_save 的内容
- 停止生成死锁(BUG-3):对话流改用框架 AgentRun 执行句柄,
  停止时 cancel() 直接触发 RunControl 取消,立即掐断模型调用与工具链
  (原先僵尸流可跑十几分钟且会话闸门不释放);取消落库走中断样式并与
  doOnCancel CAS 去重;流入口单订阅守卫防异步超时重派发重跑
- 同步 spawn 后上下文丢失(BUG-4):完成回调重建 CaseContextHolder
  作用域;execute_python 显式从 RuntimeContext 取案件 ID
- 意图识别(BUG-5/O1/O7):提示词统一二分类口径并明确执行指令不算闲聊;
  调用加超时(默认 60s,此前从未生效,卡住会无限阻塞对话流);
  意图结果空字段归一化,修复 entities 缺失触发 NPE 打断整条流
- 其他:子代理系统提示说明工具构成;前端发送被拒时回填输入框原文
cc 2 săptămâni în urmă
părinte
comite
d4f09741b3

+ 13 - 0
ai-electron/frontend/src/ai/components/ChatComposer.vue

@@ -189,6 +189,19 @@
   const userStore = useUserStore();
   const userStore = useUserStore();
   const chatStore = useChatStreamStore();
   const chatStore = useChatStreamStore();
 
 
+  // 发送被拒(如「该会话正在回复中」)时,store 会把原文退还到这里:
+  // 回填输入框,避免用户为发送失败重打一遍字
+  watch(
+    () => chatStore.draftRestore,
+    (text) => {
+      if (text) {
+        draft.value = text;
+        chatStore.draftRestore = null;
+        nextTick(() => inputRef.value?.focus?.());
+      }
+    },
+  );
+
   /* ---------------- 附件(选择即上传) ---------------- */
   /* ---------------- 附件(选择即上传) ---------------- */
 
 
   interface AttChip {
   interface AttChip {

+ 25 - 0
ai-electron/frontend/src/ai/store/chatStream.ts

@@ -203,6 +203,11 @@ export const useChatStreamStore = defineStore('ai-chat-stream', {
      * 刷新页面后从空开始,只保留父消息。
      * 刷新页面后从空开始,只保留父消息。
      */
      */
     tasks: [] as SubagentTask[],
     tasks: [] as SubagentTask[],
+    /**
+     * 发送被拒(如「该会话正在回复中」)时退还给输入框的原文。
+     * ChatComposer 消费后置回 null;输入框文本不再因发送失败而丢失。
+     */
+    draftRestore: null as string | null,
   }),
   }),
 
 
   getters: {
   getters: {
@@ -473,6 +478,11 @@ export const useChatStreamStore = defineStore('ai-chat-stream', {
 
 
       /** 记录模型/工具侧活动时间;有心跳也不代表模型在输出,二者分开统计 */
       /** 记录模型/工具侧活动时间;有心跳也不代表模型在输出,二者分开统计 */
       const markActivity = (kind: string) => {
       const markActivity = (kind: string) => {
+        // error/transport_error 是终止态而非“模型在输出”;其余事件都算收到过内容,
+        // 用于错误时判断要不要把用户输入退还给输入框
+        if (kind !== 'error' && kind !== 'transport_error') {
+          receivedAny = true;
+        }
         target.lastActivityAt = Date.now();
         target.lastActivityAt = Date.now();
         target.lastEventKind = kind;
         target.lastEventKind = kind;
       };
       };
@@ -482,6 +492,18 @@ export const useChatStreamStore = defineStore('ai-chat-stream', {
 
 
       /** 是否收到后端 done;用于识别“连接正常关闭但实际没跑完”的假完成 */
       /** 是否收到后端 done;用于识别“连接正常关闭但实际没跑完”的假完成 */
       let doneReceived = false;
       let doneReceived = false;
+      /** 是否收到过任何模型/工具内容;错误时据此决定是否退还输入框原文 */
+      let receivedAny = false;
+
+      /**
+       * 一个字都还没收到就失败(典型:会话被「正在回复中」拒绝):
+       * 把用户输入原文退还给输入框,避免用户重新打字。
+       */
+      const restoreDraftIfEmpty = () => {
+        if (!receivedAny && content && !this.draftRestore) {
+          this.draftRestore = content;
+        }
+      };
 
 
       /** 节流重扫富内容块 */
       /** 节流重扫富内容块 */
       const scheduleRescan = () => {
       const scheduleRescan = () => {
@@ -697,11 +719,13 @@ export const useChatStreamStore = defineStore('ai-chat-stream', {
               markActivity('error');
               markActivity('error');
               target.messageType = 'error';
               target.messageType = 'error';
               target.content = target.content || `⚠️ ${data.error || '请求失败'}`;
               target.content = target.content || `⚠️ ${data.error || '请求失败'}`;
+              restoreDraftIfEmpty();
             },
             },
             onTransportError: (err) => {
             onTransportError: (err) => {
               markActivity('transport_error');
               markActivity('transport_error');
               target.messageType = 'error';
               target.messageType = 'error';
               target.content = target.content || `⚠️ 网络异常:${(err as Error)?.message || err}`;
               target.content = target.content || `⚠️ 网络异常:${(err as Error)?.message || err}`;
+              restoreDraftIfEmpty();
             },
             },
           },
           },
           abortController.signal,
           abortController.signal,
@@ -711,6 +735,7 @@ export const useChatStreamStore = defineStore('ai-chat-stream', {
           markActivity('error');
           markActivity('error');
           target.messageType = 'error';
           target.messageType = 'error';
           target.content = target.content || `⚠️ ${err?.message || '请求失败'}`;
           target.content = target.content || `⚠️ ${err?.message || '请求失败'}`;
+          restoreDraftIfEmpty();
         }
         }
       } finally {
       } finally {
         // 连接被关闭但没有 done:不是正常完成,也不是后端显式 error 帧。
         // 连接被关闭但没有 done:不是正常完成,也不是后端显式 error 帧。

+ 34 - 14
ai-server/src/main/java/com/zsjz/ai/module/agent/analysis/AnalysisWorkspaceService.java

@@ -33,7 +33,9 @@ import java.util.stream.Stream;
  * <p>永久保留:不设 TTL、容量、单文件大小上限;仅案件删除或手工清理。
  * <p>永久保留:不设 TTL、容量、单文件大小上限;仅案件删除或手工清理。
  * 开关 {@code analysis.workspace.enabled} 默认关闭,关闭时 Python 仍走临时沙箱。
  * 开关 {@code analysis.workspace.enabled} 默认关闭,关闭时 Python 仍走临时沙箱。
  *
  *
- * <p>产物登记只认 {@code outputs/} 白名单扩展名;{@code work/} 中间文件不登记。
+ * <p>产物登记认两处(白名单扩展名):顶层 {@code outputs/} 与 cwd 相对路径
+ * {@code work/outputs/}(工具描述让模型把交付物写到 ./outputs,cwd=work,两个目录都要认领);
+ * {@code work/} 其余中间文件不登记。
  * 路径本身已含 {@code userId/sessionId},天然按用户/会话隔离。
  * 路径本身已含 {@code userId/sessionId},天然按用户/会话隔离。
  */
  */
 @Slf4j
 @Slf4j
@@ -69,11 +71,17 @@ public class AnalysisWorkspaceService {
         Files.createDirectories(work);
         Files.createDirectories(work);
         Files.createDirectories(outputs);
         Files.createDirectories(outputs);
         Files.createDirectories(runs);
         Files.createDirectories(runs);
+        // cwd 相对路径的交付物目录:工具描述让模型写 ./outputs(= work/outputs),
+        // 预建避免模型首次交付时因目录不存在而报错
+        Files.createDirectories(workOutputsDir(work));
         return new Workspace(root, work, outputs, runs);
         return new Workspace(root, work, outputs, runs);
     }
     }
 
 
     /**
     /**
-     * 登记本次执行新产生的 {@code outputs/} 文件(白名单扩展名 + 修改时间)。
+     * 登记本次执行新产生的交付物文件(白名单扩展名 + 修改时间)。
+     *
+     * <p>扫描两处:顶层 {@code outputs/} 与 cwd 相对路径 {@code work/outputs/}
+     * (工具描述让模型写 ./outputs,cwd=work),漏掉后者会导致交付物永远登记不到。
      *
      *
      * <p>{@code analysis.artifact.immediate=false} 时返回空列表,由回合末扫描兜底。
      * <p>{@code analysis.artifact.immediate=false} 时返回空列表,由回合末扫描兜底。
      */
      */
@@ -85,17 +93,9 @@ public class AnalysisWorkspaceService {
         int limit = Math.min(Math.max(1, properties.getArtifact().getMaxScanFiles()),
         int limit = Math.min(Math.max(1, properties.getArtifact().getMaxScanFiles()),
                 HARD_MAX_SCAN_FILES);
                 HARD_MAX_SCAN_FILES);
         List<Path> candidates = new ArrayList<>();
         List<Path> candidates = new ArrayList<>();
-        try (Stream<Path> files = Files.list(workspace.outputs())) {
-            files.filter(Files::isRegularFile)
-                    .filter(file -> !Files.isSymbolicLink(file))
-                    .filter(file -> ArtifactFileTypes.isSupported(file.getFileName().toString()))
-                    .filter(file -> modifiedMillis(file) >= threshold)
-                    .sorted(Comparator.comparingLong(AnalysisWorkspaceService::modifiedMillis))
-                    .forEach(candidates::add);
-        } catch (IOException e) {
-            log.info("扫描分析产物失败: outputs={}, error={}", workspace.outputs(), e.getMessage());
-            return List.of();
-        }
+        collectCandidates(workspace.outputs(), threshold, candidates);
+        collectCandidates(workOutputsDir(workspace.work()), threshold, candidates);
+        candidates.sort(Comparator.comparingLong(AnalysisWorkspaceService::modifiedMillis));
         if (candidates.size() > limit) {
         if (candidates.size() > limit) {
             candidates = new ArrayList<>(candidates.subList(candidates.size() - limit, candidates.size()));
             candidates = new ArrayList<>(candidates.subList(candidates.size() - limit, candidates.size()));
         }
         }
@@ -111,11 +111,31 @@ public class AnalysisWorkspaceService {
             }
             }
         }
         }
         if (!metas.isEmpty()) {
         if (!metas.isEmpty()) {
-            log.info("登记分析产物: outputs={}, count={}", workspace.outputs(), metas.size());
+            log.info("登记分析产物: outputs={}, workOutputs={}, count={}",
+                    workspace.outputs(), workOutputsDir(workspace.work()), metas.size());
         }
         }
         return metas;
         return metas;
     }
     }
 
 
+    private static Path workOutputsDir(Path work) {
+        return work.resolve("outputs");
+    }
+
+    private void collectCandidates(Path dir, long threshold, List<Path> candidates) {
+        if (dir == null || !Files.isDirectory(dir)) {
+            return;
+        }
+        try (Stream<Path> files = Files.list(dir)) {
+            files.filter(Files::isRegularFile)
+                    .filter(file -> !Files.isSymbolicLink(file))
+                    .filter(file -> ArtifactFileTypes.isSupported(file.getFileName().toString()))
+                    .filter(file -> modifiedMillis(file) >= threshold)
+                    .forEach(candidates::add);
+        } catch (IOException e) {
+            log.info("扫描分析产物失败: outputs={}, error={}", dir, e.getMessage());
+        }
+    }
+
     /**
     /**
      * 写运行记录 {@code runs/{execId}/meta.json}(永不参与产物登记)。
      * 写运行记录 {@code runs/{execId}/meta.json}(永不参与产物登记)。
      */
      */

+ 7 - 2
ai-server/src/main/java/com/zsjz/ai/module/agent/artifact/AgentArtifactScanner.java

@@ -164,6 +164,9 @@ public class AgentArtifactScanner {
      * <p>工作区开启且「即时登记」也开启时,Python 执行完已经登记过 outputs/,
      * <p>工作区开启且「即时登记」也开启时,Python 执行完已经登记过 outputs/,
      * {@link ArtifactService#isSourceRegistered} 会在 {@link #collect} 里跳过,不会重复;
      * {@link ArtifactService#isSourceRegistered} 会在 {@link #collect} 里跳过,不会重复;
      * 即时登记关闭时由本方法在回合末兜底。
      * 即时登记关闭时由本方法在回合末兜底。
+     *
+     * <p>扫描两处:顶层 {@code outputs/} 与 cwd 相对路径 {@code work/outputs/}
+     * (工具描述让模型把交付物写 ./outputs,cwd=work),与即时登记保持同一口径。
      */
      */
     private void collectAnalysisOutputs(Long caseId, Long userId, String sessionId,
     private void collectAnalysisOutputs(Long caseId, Long userId, String sessionId,
                                         long sinceMillis, Map<String, Candidate> out) {
                                         long sinceMillis, Map<String, Candidate> out) {
@@ -171,8 +174,10 @@ public class AgentArtifactScanner {
                 || userId == null || sessionId == null || sessionId.isBlank()) {
                 || userId == null || sessionId == null || sessionId.isBlank()) {
             return;
             return;
         }
         }
-        Path outputs = storageLayout.analysisOutputsDir(caseId, userId, sessionId);
-        collect(outputs, 2, sinceMillis, out);
+        collect(storageLayout.analysisOutputsDir(caseId, userId, sessionId), 2, sinceMillis, out);
+        Path workOutputs = storageLayout.analysisSessionDir(caseId, userId, sessionId)
+                .resolve("work").resolve("outputs");
+        collect(workOutputs, 2, sinceMillis, out);
     }
     }
 
 
     private void collect(Path root, int maxDepth, long sinceMillis, Map<String, Candidate> out) {
     private void collect(Path root, int maxDepth, long sinceMillis, Map<String, Candidate> out) {

+ 5 - 2
ai-server/src/main/java/com/zsjz/ai/module/agent/intent/IntentProperties.java

@@ -13,8 +13,11 @@ public class IntentProperties {
     /** 是否启用前置意图识别管道 */
     /** 是否启用前置意图识别管道 */
     private boolean enabled = true;
     private boolean enabled = true;
 
 
-    /** LLM 调用超时秒数(超时即降级为原始问题直发) */
-    private int timeoutSeconds = 5;
+    /**
+     * LLM 调用超时秒数(超时即取消订阅并降级为无意图上下文直发)。
+     * 默认 60s:实测 GLM-4.6 意图分类(含思维链)普遍 25~90s,5s/30s 会几乎必然超时降级。
+     */
+    private int timeoutSeconds = 60;
 
 
     /** 参与上下文增强的最近消息条数 */
     /** 参与上下文增强的最近消息条数 */
     private int historyTurns = 3;
     private int historyTurns = 3;

+ 23 - 2
ai-server/src/main/java/com/zsjz/ai/module/agent/intent/IntentService.java

@@ -19,6 +19,7 @@ import io.agentscope.core.tool.Toolkit;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 
 
+import java.time.Duration;
 import java.util.Collections;
 import java.util.Collections;
 import java.util.List;
 import java.util.List;
 import java.util.Map;
 import java.util.Map;
@@ -81,11 +82,31 @@ public class IntentService {
                              .build()) {
                              .build()) {
 
 
             Msg userMsg = new UserMessage(buildSystemPrompt(sessionId, question));
             Msg userMsg = new UserMessage(buildSystemPrompt(sessionId, question));
-            Msg response = agent.call(userMsg, IntentResult.class).block();
+            // 超时必须显式设置:block(Duration) 超时会取消订阅并中断底层 HTTP 调用;
+            // 之前裸 block() 没有超时——意图调用一旦卡住会无限阻塞整条对话流,
+            // 用户点「停止」后在途的意图调用也无法收敛
+            Msg response = agent.call(userMsg, IntentResult.class)
+                    .timeout(Duration.ofSeconds(etlProperties.getIntent().getTimeoutSeconds()))
+                    .block();
             if (response == null) {
             if (response == null) {
                 return null;
                 return null;
             }
             }
-            return response.getStructuredData(IntentResult.class);
+            IntentResult result = response.getStructuredData(IntentResult.class);
+            if (result == null) {
+                return null;
+            }
+            // 模型可能省略可选字段(尤其「执行指令」类输入常不给 entities):
+            // 缺失时归一化为默认值,避免下游 render/frame 直接 .isEmpty() NPE 打断整条流
+            if (result.getIntent() == null || result.getIntent().isBlank()) {
+                result.setIntent("《可能的数据分析请求》");
+            }
+            if (result.getEnhanced() == null) {
+                result.setEnhanced("");
+            }
+            if (result.getEntities() == null) {
+                result.setEntities(List.of());
+            }
+            return result;
         } catch (Exception e) {
         } catch (Exception e) {
             log.error("意图识别降级(fail-open): modelId={}, sessionId={}, error={}",
             log.error("意图识别降级(fail-open): modelId={}, sessionId={}, error={}",
                     modelId, sessionId, e.getMessage());
                     modelId, sessionId, e.getMessage());

+ 3 - 1
ai-server/src/main/java/com/zsjz/ai/module/agent/prompt/PromptAssembler.java

@@ -108,7 +108,9 @@ public final class PromptAssembler {
             - 不调用子代理(禁止嵌套)。
             - 不调用子代理(禁止嵌套)。
             - 最终消息必须包含:结论、证据/数字、产物路径(如果有)、风险/局限。
             - 最终消息必须包含:结论、证据/数字、产物路径(如果有)、风险/局限。
             - 不写面向用户的长文或客套话;父 Agent 会转述你的结论。
             - 不写面向用户的长文或客套话;父 Agent 会转述你的结论。
-            - 需要文件时优先写到当前工作目录;产物路径用绝对路径或相对数据根的路径说明清楚。""";
+            - 需要文件时优先写到当前工作目录;产物路径用绝对路径或相对数据根的路径说明清楚。
+            - 你的可用工具 = 档案声明的业务工具 + 框架常驻基础工具(文件读写、检索等);
+              不在此清单内的业务工具不可用,无需尝试,也不要据此判断「工具收窄未生效」。""";
 
 
     private PromptAssembler() {
     private PromptAssembler() {
     }
     }

+ 15 - 3
ai-server/src/main/java/com/zsjz/ai/module/agent/python/PythonExecutor.java

@@ -345,6 +345,18 @@ public class PythonExecutor {
      * 执行 Python,并记录执行归属(用户 + 会话),供产物扫描按归属认领。
      * 执行 Python,并记录执行归属(用户 + 会话),供产物扫描按归属认领。
      */
      */
     public PythonResult execute(String code, String userId, String sessionId) {
     public PythonResult execute(String code, String userId, String sessionId) {
+        return execute(code, userId, sessionId, null);
+    }
+
+    /**
+     * 执行 Python,并记录执行归属(用户 + 会话),供产物扫描按归属认领。
+     *
+     * <p>{@code explicitCaseId} 来自工具侧 {@code RuntimeContext}(SubagentContextKeys.CASE_ID):
+     *ScopedValue 绑定只在绑定线程内有效,子代理等外部长调用结束后,同批后续工具可能落在
+     * 无绑定的 Reactor 线程上,此时 {@link CaseContextHolder#get()} 拿不到案件——
+     * 调用方显式把案件 ID 从上下文传进来即可不再依赖线程绑定。
+     */
+    public PythonResult execute(String code, String userId, String sessionId, Long explicitCaseId) {
         long start = System.currentTimeMillis();
         long start = System.currentTimeMillis();
         if (!isAvailable()) {
         if (!isAvailable()) {
             return PythonResult.error("Python 执行环境不可用(未安装或缺少依赖:pip install pandas duckdb matplotlib)");
             return PythonResult.error("Python 执行环境不可用(未安装或缺少依赖:pip install pandas duckdb matplotlib)");
@@ -352,11 +364,11 @@ public class PythonExecutor {
         if (code == null || code.isBlank()) {
         if (code == null || code.isBlank()) {
             return PythonResult.error("Python 代码不能为空");
             return PythonResult.error("Python 代码不能为空");
         }
         }
-        // 只读 ThreadLocal:Agent 的流式链路跑在 Reactor 线程上,案件上下文由
-        // AgentToolRegistry 在工具调用收口处用 CaseContextHolder.runWith 显式绑定。
+        // 案件上下文:显式传入优先(随 RuntimeContext 流转,不依赖线程绑定),其次读
+        // CaseContextHolder(AgentToolRegistry 在工具调用收口处用 runWith 显式绑定的作用域值)。
         // 这里不能用 StateManager.getCaseId() —— 它取不到时返回哨兵 888888,
         // 这里不能用 StateManager.getCaseId() —— 它取不到时返回哨兵 888888,
         // 会导致 selectById(888888) 拿到 null 再 NPE,报错信息毫无指向性。
         // 会导致 selectById(888888) 拿到 null 再 NPE,报错信息毫无指向性。
-        Long workspaceId = CaseContextHolder.get();
+        Long workspaceId = explicitCaseId != null ? explicitCaseId : CaseContextHolder.get();
         if (workspaceId == null) {
         if (workspaceId == null) {
             return PythonResult.error("当前没有打开的案件,无法执行 Python 分析");
             return PythonResult.error("当前没有打开的案件,无法执行 Python 分析");
         }
         }

+ 5 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/service/AgentService.java

@@ -595,6 +595,11 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
         b.middleware(new PromptContextMiddleware(
         b.middleware(new PromptContextMiddleware(
                 caseInfo == null ? null : caseInfo.getName(), caseId, false));
                 caseInfo == null ? null : caseInfo.getName(), caseId, false));
         b.workspace(workspace);
         b.workspace(workspace);
+        // 子代理是一次性运行实例,不继承任何记忆:memory 目录按 (caseId,userId,父会话,alias)
+        // 共享,框架 memory_save/memory_search 会让后一个实例读到前一个实例存的口令等内容
+        // (测试 SA-11 失败根因)。work/ 中间文件共享是工作区设计,保持不变。
+        b.disableMemoryTools();
+        b.disableMemoryHooks();
         // 子会话不持久化:内存状态 + 关闭转录,任务结束释放
         // 子会话不持久化:内存状态 + 关闭转录,任务结束释放
         b.stateStore(new InMemoryAgentStateStore());
         b.stateStore(new InMemoryAgentStateStore());
         b.disableSessionPersistence();
         b.disableSessionPersistence();

+ 109 - 23
ai-server/src/main/java/com/zsjz/ai/module/agent/service/impl/AgentChatServiceImpl.java

@@ -34,6 +34,7 @@ import com.zsjz.ai.module.agent.vo.MessageVO;
 import com.zsjz.ai.module.agent.vo.SubagentTaskVO;
 import com.zsjz.ai.module.agent.vo.SubagentTaskVO;
 import com.zsjz.ai.module.graph.service.GraphService;
 import com.zsjz.ai.module.graph.service.GraphService;
 import com.zsjz.ai.common.model.graph.query.GraphQuery;
 import com.zsjz.ai.common.model.graph.query.GraphQuery;
+import io.agentscope.core.agent.AgentRun;
 import io.agentscope.core.agent.RuntimeContext;
 import io.agentscope.core.agent.RuntimeContext;
 import io.agentscope.core.event.*;
 import io.agentscope.core.event.*;
 import io.agentscope.core.message.Msg;
 import io.agentscope.core.message.Msg;
@@ -59,6 +60,7 @@ import java.time.LocalDate;
 import java.time.LocalDateTime;
 import java.time.LocalDateTime;
 import java.util.*;
 import java.util.*;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CancellationException;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.Semaphore;
@@ -466,7 +468,10 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
 
 
     @Override
     @Override
     public List<SubagentTaskVO> listSubagentTasks(Long sessionId) {
     public List<SubagentTaskVO> listSubagentTasks(Long sessionId) {
-        AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId));
+        // 任务接口用「404 不泄露」语义:未开案/案件不符与任务不存在同样返回 404,
+        // 不经由 requireSessionInOpenCase(那里未开案抛 400、案件不符抛 403 并回显 ID,
+        // 会向越权方泄露会话/案件的存在性与归属)。
+        AgentChatSession session = requireOwnedSessionForTasks(sessionId);
         Long userId = StpUtil.getLoginIdAsLong();
         Long userId = StpUtil.getLoginIdAsLong();
         String sid = String.valueOf(sessionId);
         String sid = String.valueOf(sessionId);
         return subagentTaskRegistry.list(userId, session.getCaseId(), sid).stream()
         return subagentTaskRegistry.list(userId, session.getCaseId(), sid).stream()
@@ -485,7 +490,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
 
 
     @Override
     @Override
     public void cancelSubagentTask(Long sessionId, String taskId) {
     public void cancelSubagentTask(Long sessionId, String taskId) {
-        AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId));
+        // 同 listSubagentTasks:404 不泄露语义(未开案/案件不符与任务不存在同响应)
+        AgentChatSession session = requireOwnedSessionForTasks(sessionId);
         Long userId = StpUtil.getLoginIdAsLong();
         Long userId = StpUtil.getLoginIdAsLong();
         String sid = String.valueOf(sessionId);
         String sid = String.valueOf(sessionId);
         // 必须先按 userId+caseId+sessionId 命中注册表,再查运行态;只凭 taskId 一律 404
         // 必须先按 userId+caseId+sessionId 命中注册表,再查运行态;只凭 taskId 一律 404
@@ -507,7 +513,11 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId));
         AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId));
         Long userId = StpUtil.getLoginIdAsLong();
         Long userId = StpUtil.getLoginIdAsLong();
         String sid = String.valueOf(sessionId);
         String sid = String.valueOf(sessionId);
-        // 先取消在途父流(用户在界面上点「停止」),再清理后台任务与并发许可
+        // 取消在途父流(用户在界面上点「停止」)。ActiveStream.cancel 会先对框架执行句柄
+        // (AgentRun,见 doStreamLocked)调用 cancel():直接触发 RunControl 取消,
+        // 立即掐断模型调用与工具链——单纯 dispose SSE 订阅拦不住在途运行(僵尸流实测可跑
+        // 十几分钟,期间会话闸门不释放、所有新消息被「正在回复中」拒绝)。
+        // 随后清理后台任务与并发许可。
         ActiveStream active = activeStreams.get(sessionId);
         ActiveStream active = activeStreams.get(sessionId);
         if (active != null) {
         if (active != null) {
             active.cancel();
             active.cancel();
@@ -529,24 +539,58 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         // 过程累积器随请求创建并下传:出错时错误消息要把「深度思考 + 工具调用 + 产物元数据」一并落库,
         // 过程累积器随请求创建并下传:出错时错误消息要把「深度思考 + 工具调用 + 产物元数据」一并落库,
         // 否则出错轮次刷新后只剩一行错误提示,本轮跑过的思考/工具/产物全部消失
         // 否则出错轮次刷新后只剩一行错误提示,本轮跑过的思考/工具/产物全部消失
         StreamProcess process = new StreamProcess();
         StreamProcess process = new StreamProcess();
-        return Flux.defer(() -> doStream(req, process, openCaseId))
-                .onErrorResume(ex -> {
-                    String errorMsg = ex.getMessage() != null ? ex.getMessage() : "未知错误";
-                    log.error("Chat stream error: sessionKey={}, ", req.getSessionKey(), ex);
-                    // 错误信息持久化:确保刷新后仍可见(含本轮已产生的过程数据)
-                    Long sessionId = parseSessionId(req.getSessionKey());
-                    if (sessionId != null) {
-                        // 出错前已生成的文件也登记为产物(帧已失败,事件只用于落库)
-                        appendGeneratedArtifactEvents(process.caseId, process.userId, process.agentRowId,
-                                String.valueOf(sessionId), process.turnStart, process, new ArrayList<>(),
-                                process.toolInputs, process.toolResults, process.toolNames);
-                        Mono.fromRunnable(() -> persistErrorMessage(sessionId, errorMsg, process))
+        // SSE 的 Spring MVC 异步派发在超时/断连后可能对同一 Flux 再订阅一次:
+        // 原流已终态(含用户停止),重订阅会重新走一遍 doStream(重复落库/重跑模型)。
+        // 这里按 AgentRun 的「单次订阅」语义,只允许第一个订阅者拿到真实流。
+        AtomicBoolean subscribed = new AtomicBoolean();
+        return Flux.defer(() -> {
+            if (!subscribed.compareAndSet(false, true)) {
+                return Flux.empty();
+            }
+            return doStream(req, process, openCaseId);
+        }).onErrorResume(ex -> {
+            boolean userStopped = ex instanceof CancellationException
+                    || ex.getCause() instanceof CancellationException;
+            Long sessionId = parseSessionId(req.getSessionKey());
+            if (userStopped) {
+                // 用户点「停止」触发的框架取消:走「中断」落库(与 doOnCancel 同一样式),
+                // 不发 error 帧——前端本地已显示「已停止生成」,连接也已断开。
+                // interruptPersisted 与 body.doOnCancel 共用:run.cancel 后 SSE 侧 dispose
+                // 可能仍在飞行,两条取消路径竞态时只落一条。
+                log.info("会话流被用户停止: sessionKey={}", req.getSessionKey());
+                if (sessionId != null && !process.resultPersisted.get()
+                        && process.interruptPersisted.compareAndSet(false, true)) {
+                    appendGeneratedArtifactEvents(process.caseId, process.userId, process.agentRowId,
+                            String.valueOf(sessionId), process.turnStart, process, new ArrayList<>(),
+                            process.toolInputs, process.toolResults, process.toolNames);
+                    String partialText = process.text.get().toString().trim();
+                    String toolEventsJson = buildToolEventsJson(process.toolInputs,
+                            process.toolResults, process.toolNames);
+                    String thinkingJson = buildThinkingMetadata(process.thinking.get().toString());
+                    if (!partialText.isEmpty() || !toolEventsJson.isEmpty()) {
+                        Mono.fromRunnable(() -> persistPartialMessage(sessionId, partialText,
+                                        toolEventsJson, thinkingJson))
                                 .subscribeOn(Schedulers.boundedElastic())
                                 .subscribeOn(Schedulers.boundedElastic())
                                 .subscribe();
                                 .subscribe();
                     }
                     }
-                    return Flux.just(sse("error",
-                            Map.of("type", "error", "error", errorMsg)));
-                });
+                }
+                return Flux.empty();
+            }
+            String errorMsg = ex.getMessage() != null ? ex.getMessage() : "未知错误";
+            log.error("Chat stream error: sessionKey={}, ", req.getSessionKey(), ex);
+            // 错误信息持久化:确保刷新后仍可见(含本轮已产生的过程数据)
+            if (sessionId != null) {
+                // 出错前已生成的文件也登记为产物(帧已失败,事件只用于落库)
+                appendGeneratedArtifactEvents(process.caseId, process.userId, process.agentRowId,
+                        String.valueOf(sessionId), process.turnStart, process, new ArrayList<>(),
+                        process.toolInputs, process.toolResults, process.toolNames);
+                Mono.fromRunnable(() -> persistErrorMessage(sessionId, errorMsg, process))
+                        .subscribeOn(Schedulers.boundedElastic())
+                        .subscribe();
+            }
+            return Flux.just(sse("error",
+                    Map.of("type", "error", "error", errorMsg)));
+        });
     }
     }
 
 
     /**
     /**
@@ -571,7 +615,7 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         ActiveStream active = new ActiveStream();
         ActiveStream active = new ActiveStream();
         activeStreams.put(sessionId, active);
         activeStreams.put(sessionId, active);
         try {
         try {
-            return doStreamLocked(sessionId, req, process, openCaseId)
+            return doStreamLocked(sessionId, req, process, openCaseId, active)
                     .doOnSubscribe(sub -> active.attach(sub::cancel))
                     .doOnSubscribe(sub -> active.attach(sub::cancel))
                     .doFinally(signal -> {
                     .doFinally(signal -> {
                         activeStreams.remove(sessionId, active);
                         activeStreams.remove(sessionId, active);
@@ -585,7 +629,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
     }
     }
 
 
     private Flux<ServerSentEvent<String>> doStreamLocked(Long sessionId, ChatRequestDTO req,
     private Flux<ServerSentEvent<String>> doStreamLocked(Long sessionId, ChatRequestDTO req,
-                                                         StreamProcess process, Long openCaseId) {
+                                                         StreamProcess process, Long openCaseId,
+                                                         ActiveStream active) {
         AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId), openCaseId);
         AgentChatSession session = requireSessionInOpenCase(requireSession(sessionId), openCaseId);
         // 本轮流的案件上下文:get_case_graph 的全量图谱补取要用它显式绑定,
         // 本轮流的案件上下文:get_case_graph 的全量图谱补取要用它显式绑定,
         // 因为 GraphService 的 @DS 路由只认 CaseContextHolder。
         // 因为 GraphService 的 @DS 路由只认 CaseContextHolder。
@@ -665,7 +710,13 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         process.userId = graphUserId;
         process.userId = graphUserId;
         process.agentRowId = agentRowId;
         process.agentRowId = agentRowId;
         process.turnStart = turnStart;
         process.turnStart = turnStart;
-        Flux<AgentEvent> events = agent.streamEvents(msgs, ctx);
+        // 用框架的一等执行句柄(AgentRun)而不是直接 streamEvents:
+        // stopSession 时对句柄 cancel() 会直接触发 RunControl.cancellation,
+        // guard(takeUntilOther) 立即掐断上游(含模型 HTTP 连接)——
+        // 单纯 dispose SSE 订阅实测拦不住在途运行(僵尸流可跑十几分钟)。
+        AgentRun<AgentEvent> run = agent.prepareRun(msgs, ctx);
+        active.attachRun(run);
+        Flux<AgentEvent> events = run.stream();
 
 
         long startMs = System.currentTimeMillis();
         long startMs = System.currentTimeMillis();
         String sessionKey = String.valueOf(sessionId);
         String sessionKey = String.valueOf(sessionId);
@@ -831,8 +882,9 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
             if (deletingSessions.contains(sessionId)) {
             if (deletingSessions.contains(sessionId)) {
                 return;
                 return;
             }
             }
-            // 用户主动中止:若 AgentResultEvent 尚未到达,保存已流式输出的部分内容
-            if (!resultPersisted.get()) {
+            // 用户主动中止:若 AgentResultEvent 尚未到达,保存已流式输出的部分内容。
+            // interruptPersisted 与 stream() onErrorResume 的取消分支共用,防止双写
+            if (!resultPersisted.get() && process.interruptPersisted.compareAndSet(false, true)) {
                 // 中断前已生成的文件也登记为产物(帧已取消,事件只用于落库)
                 // 中断前已生成的文件也登记为产物(帧已取消,事件只用于落库)
                 appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, sessionKey, turnStart,
                 appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, sessionKey, turnStart,
                         process, new ArrayList<>(), toolInputs, toolResults, toolNames);
                         process, new ArrayList<>(), toolInputs, toolResults, toolNames);
@@ -893,6 +945,24 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         return session;
         return session;
     }
     }
 
 
+    /**
+     * 子代理任务接口(列表/取消)专用守卫:404 不泄露语义。
+     *
+     * <p>未开案、会话不存在归属案件上下文或案件不符,一律 404「任务不存在或无权操作」,
+     * 不区分原因、不回显会话/案件 ID——与 registry 未命中时的响应完全一致,
+     * 越权方无法据此探测会话是否存在。区别于 {@link #requireSessionInOpenCase}
+     * (未开案抛 400、案件不符抛 403 并回显 ID,供正常用户排障)。
+     */
+    private AgentChatSession requireOwnedSessionForTasks(Long sessionId) {
+        AgentChatSession session = requireSession(sessionId);
+        Long openCaseId = CaseContextHolder.currentCaseId();
+        if (openCaseId == null || session.getCaseId() == null
+                || !openCaseId.equals(session.getCaseId())) {
+            throw new ServerException(404, "任务不存在或无权操作");
+        }
+        return session;
+    }
+
     /**
     /**
      * 将 AI 回复持久化为 assistant 消息。失败不影响流式输出。
      * 将 AI 回复持久化为 assistant 消息。失败不影响流式输出。
      *
      *
@@ -1652,6 +1722,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
      */
      */
     private static final class ActiveStream {
     private static final class ActiveStream {
         private final AtomicReference<Disposable> disposable = new AtomicReference<>();
         private final AtomicReference<Disposable> disposable = new AtomicReference<>();
+        /** 框架执行句柄:cancel() 直接触发 RunControl 取消,不依赖订阅 dispose 的传播 */
+        private volatile AgentRun<?> run;
         private volatile boolean cancelRequested;
         private volatile boolean cancelRequested;
 
 
         void attach(Disposable value) {
         void attach(Disposable value) {
@@ -1661,8 +1733,20 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
             }
             }
         }
         }
 
 
+        void attachRun(AgentRun<?> value) {
+            run = value;
+            if (cancelRequested) {
+                value.cancel();
+            }
+        }
+
         void cancel() {
         void cancel() {
             cancelRequested = true;
             cancelRequested = true;
+            // 先掐执行句柄(立即中断模型调用/工具链),再断 SSE 订阅
+            AgentRun<?> current = run;
+            if (current != null) {
+                current.cancel();
+            }
             Disposable value = disposable.get();
             Disposable value = disposable.get();
             if (value != null) {
             if (value != null) {
                 value.dispose();
                 value.dispose();
@@ -1685,6 +1769,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         final AtomicReference<StringBuilder> thinking = new AtomicReference<>(new StringBuilder());
         final AtomicReference<StringBuilder> thinking = new AtomicReference<>(new StringBuilder());
         /** 完整回答是否已落库(落库后出错不再重复携带过程数据) */
         /** 完整回答是否已落库(落库后出错不再重复携带过程数据) */
         final AtomicBoolean resultPersisted = new AtomicBoolean(false);
         final AtomicBoolean resultPersisted = new AtomicBoolean(false);
+        /** 中断消息是否已落库:停止时 doOnCancel 与 onErrorResume(取消) 可能竞态双触发,只落一条 */
+        final AtomicBoolean interruptPersisted = new AtomicBoolean(false);
         /** 生成文件是否已扫描登记(正常结束/中断/异常三条路径只扫一次) */
         /** 生成文件是否已扫描登记(正常结束/中断/异常三条路径只扫一次) */
         final AtomicBoolean artifactsScanned = new AtomicBoolean(false);
         final AtomicBoolean artifactsScanned = new AtomicBoolean(false);
         /** 本轮案件上下文:异常收尾路径也要用它扫描生成文件(可能跨线程读写) */
         /** 本轮案件上下文:异常收尾路径也要用它扫描生成文件(可能跨线程读写) */

+ 18 - 3
ai-server/src/main/java/com/zsjz/ai/module/agent/subagent/SubagentSpawnTool.java

@@ -1,5 +1,6 @@
 package com.zsjz.ai.module.agent.subagent;
 package com.zsjz.ai.module.agent.subagent;
 
 
+import com.zsjz.ai.common.context.CaseContextHolder;
 import com.zsjz.ai.module.agent.config.SubagentProperties;
 import com.zsjz.ai.module.agent.config.SubagentProperties;
 import io.agentscope.core.agent.Agent;
 import io.agentscope.core.agent.Agent;
 import io.agentscope.core.agent.RuntimeContext;
 import io.agentscope.core.agent.RuntimeContext;
@@ -154,6 +155,11 @@ public class SubagentSpawnTool {
                                           String parentSessionId, RuntimeContext parentCtx,
                                           String parentSessionId, RuntimeContext parentCtx,
                                           int timeoutSeconds) {
                                           int timeoutSeconds) {
         long start = System.currentTimeMillis();
         long start = System.currentTimeMillis();
+        // 子代理的完成回调跑在模型 HTTP 线程上(CompletableFuture.whenComplete),那里没有
+        // CaseContextHolder 绑定;不重绑的话,父链路后续同批工具(如 execute_python)经
+        // ReactorCaseContextConfig 调度钩子捕获到的是空上下文,报「当前没有打开的案件」。
+        Long scopeCaseId = caseId(parentCtx);
+        Long scopeUserId = userIdOf(parentCtx);
         return Mono.deferContextual(ctxView -> {
         return Mono.deferContextual(ctxView -> {
             CompletableFutureBridge bridge = new CompletableFutureBridge();
             CompletableFutureBridge bridge = new CompletableFutureBridge();
             AtomicBoolean timedOut = new AtomicBoolean(false);
             AtomicBoolean timedOut = new AtomicBoolean(false);
@@ -168,6 +174,7 @@ public class SubagentSpawnTool {
                 Disposable timer = Schedulers.parallel().schedule(() -> {
                 Disposable timer = Schedulers.parallel().schedule(() -> {
                     if (settled.compareAndSet(false, true)) {
                     if (settled.compareAndSet(false, true)) {
                         timedOut.set(true);
                         timedOut.set(true);
+                        // schedule 走调度钩子,定时任务已在案件作用域内执行
                         sink.success(timeoutPlaceholder());
                         sink.success(timeoutPlaceholder());
                     }
                     }
                 }, timeoutSeconds, TimeUnit.SECONDS);
                 }, timeoutSeconds, TimeUnit.SECONDS);
@@ -176,10 +183,18 @@ public class SubagentSpawnTool {
                         return;
                         return;
                     }
                     }
                     timer.dispose();
                     timer.dispose();
-                    if (error != null) {
-                        sink.error(error);
+                    // 在完成线程上重建案件作用域,父链路下游(flatMap 及之后的工具调用)才能续上
+                    Runnable emit = () -> {
+                        if (error != null) {
+                            sink.error(error);
+                        } else {
+                            sink.success(msg);
+                        }
+                    };
+                    if (scopeCaseId == null && scopeUserId == null) {
+                        emit.run();
                     } else {
                     } else {
-                        sink.success(msg);
+                        CaseContextHolder.runWith(scopeCaseId, scopeUserId, emit);
                     }
                     }
                 });
                 });
                 sink.onDispose(() -> {
                 sink.onDispose(() -> {

+ 22 - 1
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/PythonAnalysisTool.java

@@ -51,7 +51,8 @@ public class PythonAnalysisTool {
             PythonExecutor.PythonResult result = pythonExecutor.execute(
             PythonExecutor.PythonResult result = pythonExecutor.execute(
                     code,
                     code,
                     ctx == null ? null : ctx.getUserId(),
                     ctx == null ? null : ctx.getUserId(),
-                    ownerSessionId(ctx));
+                    ownerSessionId(ctx),
+                    caseIdOf(ctx));
 
 
             Map<String, Object> data = new LinkedHashMap<>();
             Map<String, Object> data = new LinkedHashMap<>();
             data.put("exitCode", result.exitCode());
             data.put("exitCode", result.exitCode());
@@ -110,6 +111,26 @@ public class PythonAnalysisTool {
         return ctx.getSessionId();
         return ctx.getSessionId();
     }
     }
 
 
+    /**
+     * 案件 ID:优先取随 {@link RuntimeContext} 流转的 {@link SubagentContextKeys#CASE_ID},
+     * 兜底读 {@code CaseContextHolder}(ScopedValue 绑定只在绑定线程内有效,
+     * 同批前置长调用结束后线程可能没有绑定,此时必须靠显式传递)。
+     */
+    private static Long caseIdOf(RuntimeContext ctx) {
+        if (ctx == null) {
+            return null;
+        }
+        Object caseId = ctx.get(SubagentContextKeys.CASE_ID);
+        if (caseId == null || String.valueOf(caseId).isBlank()) {
+            return com.zsjz.ai.common.context.CaseContextHolder.get();
+        }
+        try {
+            return Long.valueOf(String.valueOf(caseId));
+        } catch (NumberFormatException e) {
+            return com.zsjz.ai.common.context.CaseContextHolder.get();
+        }
+    }
+
     /**
     /**
      * 截断元数据:只在内联输出被截断时出现,避免正常结果多带字段。
      * 截断元数据:只在内联输出被截断时出现,避免正常结果多带字段。
      *
      *

+ 11 - 17
ai-server/src/main/resources/prompts/intent-recognition.txt

@@ -10,36 +10,30 @@
 
 
 # 分类标签
 # 分类标签
 
 
-`intent` 只能是以下5个值之一:
-
-- `data_query:数据查询/统计/聚合(需写 SQL 分析数据)`
-- `schema_explore:表结构探索(了解有哪些表/字段/含义)`
-- `etl_clean:数据清洗/转换/ETL 处理任务`
-- `visualization:图表/可视化需求`
-- `general_chat:通用问答/闲聊/与数据无关`
-
-必须逐字输出完整标签,包括开头的 `《` 和结尾的 `》`。不得省略书名号、改用其他括号、翻译标签或输出近义词。
+`intent` 只能是以下两个标签之一,必须逐字输出完整标签,包括开头的 `《` 和结尾的 `》`。不得省略书名号、改用其他括号、翻译标签或输出近义词。
 
 
 ## 《可能的数据分析请求》
 ## 《可能的数据分析请求》
 
 
-只要最新输入符合任一条件就使用:
+只要最新输入符合任一条件就使用(该标签的实际含义是「非闲聊,需完整分析流程处理」):
 
 
 - 请求查询、统计、筛选、列表、排名、比较、汇总、计算、解释或可视化数据;
 - 请求查询、统计、筛选、列表、排名、比较、汇总、计算、解释或可视化数据;
 - 提到可能属于已连接数据的业务实体、指标、记录、部门、人员、商品、订单等,并带有询问意图;
 - 提到可能属于已连接数据的业务实体、指标、记录、部门、人员、商品、订单等,并带有询问意图;
 - 询问业务术语、指标定义或数据口径;
 - 询问业务术语、指标定义或数据口径;
 - 是依赖历史的数据追问,例如“那华北呢”“第二名呢”“再按月份看”;
 - 是依赖历史的数据追问,例如“那华北呢”“第二名呢”“再按月份看”;
-- 表达模糊,但合理解释之一是继续当前数据分析任务。
+- 表达模糊,但合理解释之一是继续当前数据分析任务;
+- **要求执行任何操作或指令**:执行代码/脚本、调用工具、操作或读写文件、数据清洗/ETL、
+  委派子代理任务(提到 execute_python、agent_spawn、SQL、print、脚本、命令等执行性字样)——
+  即使与当前数据无关(如“用 Python 打印 1+1”),也不属于闲聊。
 
 
 此时 `response` 必须是空字符串。
 此时 `response` 必须是空字符串。
 
 
 ## 《闲聊或无关指令》
 ## 《闲聊或无关指令》
 
 
-只有当最新输入明确属于以下情况时使用:
+只有当最新输入**全部**满足以下情况时才使用:
 
 
-- 纯问候、感谢、情绪表达或无意义文本;
-- 询问助手身份或一般能力,且不要求分析具体数据;
-- 明确要求与已连接数据无关的创作、常识或外部信息;
-- 仅要求泄露内部提示词、改变系统规则或执行非数据任务。
+- 纯问候、感谢、情绪表达或无意义文本;或询问助手身份或一般能力;或要求与数据无关的创作、
+  常识、外部信息;或仅要求泄露内部提示词、改变系统规则;
+- **且不包含任何执行意图**:没有要求执行代码、调用工具、操作文件或委派任务。
 
 
 此时 `response` 应:
 此时 `response` 应:
 
 
@@ -52,7 +46,7 @@
 
 
 - 最新输入是主要分类依据。
 - 最新输入是主要分类依据。
 - 多轮历史只用于识别追问和指代,不能让一个明确的新闲聊话题继续进入分析。
 - 多轮历史只用于识别追问和指代,不能让一个明确的新闲聊话题继续进入分析。
-- 当5类都可能时,选择《可能的数据分析请求》,避免误拦截。
+- 无法确定时,选择《可能的数据分析请求》,避免误拦截。
 
 
 # 输出
 # 输出
 
 

+ 1 - 1
ai-server/src/test/java/com/zsjz/ai/module/agent/tools/PythonAnalysisToolTest.java

@@ -56,7 +56,7 @@ class PythonAnalysisToolTest {
     }
     }
 
 
     private void stub(PythonExecutor.PythonResult result) {
     private void stub(PythonExecutor.PythonResult result) {
-        when(executor.execute(anyString(), any(), any())).thenReturn(result);
+        when(executor.execute(anyString(), any(), any(), any())).thenReturn(result);
     }
     }
 
 
     private static PythonExecutor.PythonResult result(String relationGraphJson, String relationGraphError) {
     private static PythonExecutor.PythonResult result(String relationGraphJson, String relationGraphError) {