agentscope-java icon indicating copy to clipboard operation
agentscope-java copied to clipboard

AguiAgentAdapter 对外部工具(SchemaOnlyTool / TOOL_SUSPENDED)未正确映射 AG-UI interrupt 语义,导致 CopilotKit 前端 HITL 无法弹出确认 UI

Open likebean opened this issue 4 months ago • 1 comments

问题描述

在使用 AG-UI + CopilotKit useHumanInTheLoop 做前端审批(Human-in-the-Loop)时,发现 AguiAgentAdapter 对 外部工具挂起(SchemaOnlyTool → ToolSuspendException → ToolResultBlock.isSuspended())的处理与 AG-UI 协议语义不一致,导致前端框架误判 tool 已执行完成,HITL 交互被跳过。

场景

  1. 前端通过 CopilotKit 注册纯前端工具(如 request_approval),每次 runAgent 时在 tools[] 中带给后端
  2. 后端 AguiAgentAdapter.injectFrontendTools() 将其注册为 SchemaOnlyTool
  3. 模型调用 request_approval 后,core 正确挂起(GenerateReason.TOOL_SUSPENDED)
  4. 期望:前端弹出「同意 / 拒绝」对话框,用户操作后再 runAgent 带回 role=tool 的真实结果
  5. 实际:前端直接显示 tool 已完成,且 UI 误判为「已拒绝」

实际 AG-UI 事件流(有问题)

RUN_STARTED
TOOL_CALL_START   (request_approval)
TOOL_CALL_ARGS
TOOL_CALL_END
TOOL_CALL_RESULT  content: "[Awaiting external execution]"   ← 不应作为最终结果发出
RUN_FINISHED      outcome: null / success                    ← 未表达 interrupt

期望 AG-UI 事件流

根据 AG-UI 协议(RunFinishedInterruptOutcome + Interrupt,以及 RunAgentInput.resume),外部工具挂起时应为:

RUN_STARTED
TOOL_CALL_START
TOOL_CALL_ARGS
TOOL_CALL_END
(不发 TOOL_CALL_RESULT)
RUN_FINISHED
  outcome: { type: "interrupt", interrupts: [{ toolCallId, reason, ... }] }

说明:RUN_FINISHED 表示 本轮 HTTP/SSE run 结束,不代表业务任务完成;挂起场景应通过 outcome=interrupt 表达「待用户恢复」。


根因分析

AguiAgentAdapter.convertEvent() 在处理 TOOL_RESULT 时,未区分普通结果与挂起结果,一律发出 ToolCallResult:

// AguiAgentAdapter.java ~352-386
} else if (type == EventType.TOOL_RESULT && event.isLast()) {
    ...
    String result = extractToolResultText(toolResult);
    ...
    events.add(new AguiEvent.ToolCallResult(..., result, "tool", ...));
}

而 ToolResultBlock 对挂起结果已有明确标记:

// ToolResultBlock.java
public boolean isSuspended() {
    return Boolean.TRUE.equals(metadata.get(METADATA_SUSPENDED));
}
// suspended() 默认 content: "[Awaiting external execution]"

finishRun() 也始终发普通 RunFinished,未使用已有的 RunFinishedInterruptOutcome:

// AguiAgentAdapter.java ~425-426
events.add(new AguiEvent.RunFinished(state.threadId, state.runId));

协议侧 AguiEvent 已定义 Interrupt / RunFinishedInterruptOutcome,测试用例也有覆盖,但 Adapter 未在 TOOL_SUSPENDED 路径上接入。

对 CopilotKit 的影响

CopilotKit 在 processAgentResult 中的逻辑是:若 newMessages 里 已存在 对应 toolCallId 的 role=tool 消息,则 不再执行 前端 useHumanInTheLoop handler。

后端发出的占位 TOOL_CALL_RESULT 会被当成「tool 已执行完」,从而跳过 HITL UI。占位内容 "[Awaiting external execution]" 也无法被解析为 { approved: boolean },前端 UI 容易误判为拒绝。


复现步骤(简化)

  1. Spring Boot 集成 agentscope-agui-spring-boot-starter,注册 Agent
  2. 前端 CopilotKit + useHumanInTheLoop({ name: "request_approval", ... })
  3. 用户发送:「请调用 request_approval 向我申请审批」
  4. 观察 AG-UI SSE:会出现 TOOL_CALL_RESULT: "[Awaiting external execution]" + 普通 RUN_FINISHED
  5. 前端不出现审批对话框,或直接进入 Complete 态

建议修复方向

在 AguiAgentAdapter 中,当 toolResult.isSuspended() 时:

  1. 不要 emit ToolCallResult(占位文案不应作为最终 tool 结果)
  2. 在 finishRun() 或挂起检测点 emit:
    new AguiEvent.RunFinished(
        threadId, runId, null,
        new AguiEvent.RunFinishedInterruptOutcome(List.of(
            new AguiEvent.Interrupt(
                interruptId, "tool_suspended", message, toolCallId, ...))))
    
  3. 文档中说明:客户端收到 interrupt 后,应通过 RunAgentInput.resume 或等价机制带回真实 tool 结果,再触发下一轮 run

想确认的问题

  1. 上述「挂起时不发 TOOL_CALL_RESULT,改发 RUN_FINISHED + interrupt」是否为 AG-UI 协议的推荐做法?
  2. 对 CopilotKit 类前端(不走 resume,而是在浏览器本地执行 handler 后再 runAgent),官方是否有推荐的集成模式?
  3. 是否计划在 AguiAgentAdapter 中正式支持 TOOL_SUSPENDED → interrupt 的映射?如有 roadmap 或 workaround,希望能指引一下。

环境信息

  • agentscope-extensions-agui(AguiAgentAdapter)
  • agentscope-core(SchemaOnlyTool / ToolResultBlock.isSuspended())
  • 前端:CopilotKit @copilotkit/react-core + @ag-ui/client HttpAgent
  • 集成方式:injectFrontendTools + 前端 useHumanInTheLoop

likebean avatar Jul 06 '26 10:07 likebean

Additional Core-level evidence from the native streamEvents() path (observed against e3a412ed2cc944e401da861c8d5e464b967724e9):

  • RequireExternalExecutionEvent and ExternalExecutionResultEvent are defined and registered as event subtypes, but Core/Harness production source has no construction/emission site for either event.
  • The coarse continuation itself works: a SchemaOnlyTool produces GenerateReason.TOOL_SUSPENDED; a subsequent call() carrying matching ToolResultBlock id/name resumes reasoning.
  • The same continuation also works after rebuilding the agent with the same persisted (userId, sessionId) state, so pending validation/state ownership is already correctly in Core.
  • The typed event stream does not expose a stable request event on suspension or a result event after supplied external results. Product adapters therefore cannot obtain a reliable one-shot ingress/interrupt identity without inspecting coarse messages or synthesizing runtime facts.

This suggests the native fix should start in Core, not only in AguiAgentAdapter:

  1. emit RequireExternalExecutionEvent(replyId, pending ToolUseBlocks) and a typed stop/interrupt boundary when the turn returns TOOL_SUSPENDED;
  2. emit ExternalExecutionResultEvent(replyId, accepted ToolResultBlocks) after Core validates and appends supplied results;
  3. preserve the same identities through persisted-state rebuild/restart;
  4. let AG-UI map those native events to its interrupt/resume protocol without treating the suspended placeholder as a terminal result.

Acceptance should cover same-instance resume, fresh-agent/state-store resume, duplicate/mismatched result rejection, and exactly-once request/result event emission. A product host should not need its own pending-execution store or synthesize these events.

richuV avatar Jul 11 '26 23:07 richuV