Repository navigation
feat(core): support returnDirect tool result short-circuit - #2891
Conversation
3808802 to
64b2eb6
Compare
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
7817495 to
b9a1ad3
Compare
b9a1ad3 to
d5a76b7
Compare
jujn
left a comment
There was a problem hiding this comment.
还有两点:
- 目前外部工具恢复后不会应用 returnDirect。如果明确不支持可以在 javadoc 写清楚。
- agui 模块没有适配当前功能(不阻塞)。
| private Msg buildReturnDirectResultMsg( | ||
| List<Map.Entry<ToolUseBlock, ToolResultBlock>> pairs) { |
There was a problem hiding this comment.
ReActAgent 在执行 PostActing hook 之前就计算了 returnDirect,但最终消息在 buildReturnDirectResultMsg 里使用的是 successPairs 中的原始工具结果。即如果 hook 把结果改写,调用方拿到的仍是原始结果。但是我想,hook 相关组件不久后就移除了,所以不应强绑定 returnDirect 功能
There was a problem hiding this comment.
有意为之,测试 postActingRewriteDoesNotAffectReturnDirectResult 钉死了这个行为。hook 整包已 @deprecated(forRemoval),不为其补语义;要改写内容应该放在工具 converter 或 AgentTool 装饰器,两条路径都生效。已补 javadoc 说明边界,并加了丢弃改写时的 log.warn,redaction 场景不会静默失效。
| for (Map.Entry<ToolUseBlock, ToolResultBlock> pair : pairs) { | ||
| List<ContentBlock> output = pair.getValue().getOutput(); | ||
| if (output.isEmpty()) { | ||
| content.add(TextBlock.builder().text("(no output)").build()); | ||
| } else { | ||
| content.addAll(output); |
There was a problem hiding this comment.
多工具 direct 返回结果缺少 toolCallId / toolName 关联,调用方无法可靠地把结果映射回工具调用。
There was a problem hiding this comment.
保序没问题:并行执行走 mergeSequential,与完成先后无关,已补差速测试。但块映射不做:真模型总结出来的内容同样分不出哪段来自哪个工具,给收口消息加这个信息反而让调用方绑死在「本轮被短路」上——工具改回普通模式这段逻辑就失效了。需要按工具归属的消费方走事件流,ToolResult 事件本来就带 toolCallId;真出现只拿返回值还要块级溯源的场景,再按专用块类型补。
| for (Map.Entry<ToolUseBlock, ToolResultBlock> pair : pairs) { | ||
| List<ContentBlock> output = pair.getValue().getOutput(); | ||
| if (output.isEmpty()) { | ||
| content.add(TextBlock.builder().text("(no output)").build()); |
There was a problem hiding this comment.
空输出会被改写为 "(no output)",对于返回文本的工具可能造成误解。Spring AI tool 返回 null 时会写入空字符串。
There was a problem hiding this comment.
触发面比描述窄:零块输出只可能来自自定义 converter 返回空列表,默认转换和 MCP 都到不了这个分支。处理已调整:零块结果不进收口消息(与模型总结跳过无输出工具一致,事件流侧同样无投影),仅整批全零时垫一个 "(no output)" 保住 provider 对 assistant content 非空的要求。真拿到占位也能判别——generateReason 和 _tool_return_direct 标记都表明这是收口合成的。
工具侧的义务也写进了 javadoc:声明 returnDirect 就该保证成功结果有可呈现的内容。
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
First review of the returnDirect tool semantics (Spring AI-style loop short-circuit). The overall shape is sound: the batch rule is conservative (short-circuit only when the round has no suspended entries and every executed result is both SUCCESS and declared returnDirect), permission-denied and error results correctly feed back to the model instead of being presented as the answer, the placeholder keeps the tool_call → tool_result → assistant chain that providers demand, and the TOOL_RETURN_DIRECT metadata + GenerateReason give consumers a way to recognise the synthesized message. @Tool.returnDirect() / ToolBase.Builder / ReflectiveFunctionTool wiring is additive and the old protected ToolBase constructor still delegates with false, so no break for existing tools. ReActAgentReturnDirectTest is thorough — 600 lines covering single/mixed/all-direct batches, suspend, deny, error, [ERROR]-prefixed text, non-text output, empty output and the annotated path.
@jujn's CHANGES_REQUESTED stands and I am deliberately not repeating the four points already raised there (pre-hook decision vs. rewritten result, missing toolCallId/toolName association, "(no output)" wording, external-tool resume and the AG-UI gap). Two additions plus one streaming consequence below.
Findings
- [Warning]
ReActAgent.java:2812—.last()only propagates the final hook event's stop flag, so in a multi-tool batch astopAgent()on an earlier entry is swallowed and the turn returns a successful direct answer instead ofACTING_STOP_REQUESTED. - [Warning]
ReActAgent.java:2822— the direct result is built from pre-hook entries, soPostActingresult rewriting silently does not apply to exactly the results shown to the user verbatim; if that is intended (hooks are on their way out), one sentence in the@Tool.returnDirect()javadoc is enough. - [Info]
ReActAgent.java:3593— onstreamEventsthe payload is emitted both in the tool-result events and as the final result, so consumers that render both will show it twice; needs an explicit decision alongside the AG-UI adaptation.
Suggestions
takeUntil(PostActingEvent::isStopRequested) before .last() keeps the stop-authority rule uniform across the batch, and a two-tool test where the first hook stops would lock it in. A CI note: build (windows-latest) is failing on this head while ubuntu, License and Module Sync pass — worth ruling out the new code path before the next push.
Automated review by github-manager-bot
- [WARNING]
agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:2812
In a multi-tool batch .last() only carries the stop flag of the final hook event, so a stopAgent() raised on an earlier entry is lost — and the new returnDirect branch then ends the turn with a successful final answer instead of ACTING_STOP_REQUESTED.
The placeholder logic a few lines below (notifyPostActingHook, line 3526: if (returnDirect && !e.isStopRequested())) already evaluates the stop flag per entry, so the two decisions disagree: a stopped entry keeps its real tool result in context (no placeholder) while buildReturnDirectResultMsg still lifts that same result into the closing message that the caller receives.
Either aggregate the flag across the batch, or stop consuming early so the branch sees it:
return Flux.fromIterable(successPairs)
.concatMap(e -> notifyPostActingHook(e, returnDirect))
.takeUntil(PostActingEvent::isStopRequested) // any stop in the batch wins
.last()
.flatMap(event -> { ... });hitlStopTakesPriorityOverReturnDirect drives a single tool call, so it cannot catch this; a two-tool variant where the first hook stops would.
- [WARNING]
agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:2822
returnDirect is decided from successPairs and the closing message is built from those same pre-hook entries, so a PostActing hook that rewrites the result via setToolResult(...) has no effect on what the caller receives — postActingRewriteDoesNotAffectReturnDirectResult pins that behaviour, so it reads as intentional. The wrinkle is that a returnDirect result is the one path handed straight to the end user with no model pass in between, and result rewriting is the main thing that hook does today (redaction, truncation, substituting a safe message).
@jujn's point that the hook layer is going away anyway is probably the decisive argument, so the cheap resolution is one sentence in the @Tool.returnDirect() javadoc — "the tool result is returned verbatim; PostActing result rewrites do not apply" — so the next person does not try to redact a direct result through a hook and get a silent no-op.
- [INFO]
agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:3593
On the streamEvents path the tool's content has already been emitted through the ToolResult* events, and the same payload then leaves as the turn's final result via AgentResultEvent, so a client that renders both the tool output and the final answer shows it twice. Replacing the context entry with the placeholder removes the duplicate for the next model pass, not for the event stream.
This is the consumer-facing half of the AG-UI gap @jujn flagged as non-blocking, so it may just need an explicit decision: either suppress/placeholder the content in the direct path's tool-result events, or document that consumers must prefer the final result over tool output when _tool_return_direct is set.
…h model-style closing text events, hook-rewrite warning, zero-block placeholder refinement, javadoc and regression tests
第一点 1(外部工具恢复后不应用 returnDirect) 第二点 2(agui 模块未适配) |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Delta re-review of ebe401c3 (previous review was on 1e9a1489). The direction is right: closing the external-execution gap is what @jujn's CHANGES_REQUESTED asked for, the two paths really do converge on finalizeReturnDirect, the projection decision is now explicit and tested end-to-end through AG-UI, and AgentEvent.METADATA_GENERATE_REASON gives consumers a way to tell a substituted answer from a model-generated one. pairProvidedToolResults + the pendingBatch.size() == originalBatch.size() guard also encode the "whole batch, one resume" rule cleanly instead of leaking it into the caller.
Two things I would fix before this merges:
- [Warning] The
ExternalExecutionResultEventpublished on the resume path now carries the placeholder rather than the caller's real result, becauseplaceholderToolResultMsgsis applied beforevalidateAndAddToolResults(which both persists and publishes). No current test asserts that payload, so the regression is invisible in CI. - [Warning] The persisted placeholder keeps the caller's raw
ToolResultBlockstate while the short-circuit gate usesdetermineToolResultState(...), so an unset/RUNNINGstate can be recorded for a turn that ended successfully — the exact mismatch the in-framework path was fixed for.
Also re-raising the .last() stop-flag propagation point from the previous round, still unaddressed and now a one-line change; plus two nits on the synthesized projection.
Nice touch: externalAndInternalPathsAreIsomorphic and parallelSkewPreservesDeclarationOrder are the kinds of tests that make this semantics reviewable at all. Adding a payload assertion to the isomorphism test would make it catch the first issue automatically.
CLA signed. CI: ubuntu/windows build, License, Module Sync, codecov and validate all pass on this head.
Automated review by github-manager-bot
| && externalPairs.size() == pendingBatch.size() | ||
| && externalPairs.stream().allMatch(this::isReturnDirectToolCall); | ||
| validateAndAddToolResults( | ||
| returnDirectResume ? placeholderToolResultMsgs(msgs) : msgs, pendingIds); |
There was a problem hiding this comment.
validateAndAddToolResults publishes ExternalExecutionResultEvent(replyId, results) from the messages it was handed (line ~2248), and on this branch those messages have already been through placeholderToolResultMsgs. So whenever the returnDirect short-circuit fires, the event that exists to tell consumers what the external executor produced now carries the placeholder sentence ("Tool call completed. The result has been presented to the user as the final output of this turn.") instead of the real payload — before this commit it carried the caller's results verbatim.
The real content does still reach the turn (externalPairs is paired from the untouched providedResults, and publishReturnDirectTextEvents projects it), so nothing visible breaks in AG-UI — ExternalExecutionEventConverter suppresses that event entirely. But any other consumer of the durable event stream (audit / session mirror / A2A replay, anything reading getToolResults()) silently loses the external result on this path.
The new test checks the event's index (iStart > iExternalResult) and never its payload, which is exactly the gap:
int iExternalResult = indexOf(resumeEvents, ExternalExecutionResultEvent.class);
assertTrue(iExternalResult >= 0, "ExternalExecutionResultEvent must still be emitted");Suggested shape: keep the substitution scoped to what gets persisted, not to what gets validated/published — e.g. validate + publish from the original msgs, then state.contextMutable().addAll(returnDirectResume ? placeholderToolResultMsgs(msgs) : msgs), splitting the one call in two. And extend that test to assert ((ExternalExecutionResultEvent) resumeEvents.get(iExternalResult)).getToolResults().get(0) still contains "ext-result".
| if (!(block instanceof ToolResultBlock result)) { | ||
| return block; | ||
| } | ||
| return placeholderResultBlock(result.getId(), result.getName(), result.getState()); |
There was a problem hiding this comment.
The gate and the persisted row can disagree on state. returnDirectResume is decided by isReturnDirectToolCall, which normalizes through determineToolResultState(...) (null/RUNNING + no [ERROR] prefix → SUCCESS), but the placeholder written into context keeps result.getState() as the caller sent it. A caller that supplies a plain result without setting the state therefore ends the turn successfully while history shows a RUNNING (or null) tool_result — the same class of bug the FIX: determine the final state and update ToolResultBlock before adding to contextMutable() comment at line ~3571 exists for on the in-framework path.
The internal path is covered: buildReturnDirectPlaceholderMsg(toolUse, updatedResult) receives the already-normalized block. Passing the determined state here too keeps the two paths genuinely isomorphic:
return placeholderResultBlock(
result.getId(), result.getName(), determineToolResultState(result));externalResumeShortCircuitsReturnDirect asserts ToolResultState.SUCCESS, but its successResult(...) helper sets that state explicitly, so the un-normalized case is what the current suite misses.
| return Flux.fromIterable(successPairs) | ||
| .concatMap(this::notifyPostActingHook) | ||
| .concatMap(e -> notifyPostActingHook(e, returnDirect)) | ||
| .last() |
There was a problem hiding this comment.
Re-raising from the previous round because it is still open on this head and the refactor made it easier to fix: .last() only propagates the final hook event's stop flag, so in a multi-tool batch a stopAgent() raised on an earlier entry is swallowed and the turn still returns a successful TOOL_RETURN_DIRECT answer instead of ACTING_STOP_REQUESTED. Now that both paths funnel through finalizeReturnDirect, one operator covers the rule:
Flux.fromIterable(successPairs)
.concatMap(e -> notifyPostActingHook(e, returnDirect))
.takeUntil(PostActingEvent::isStopRequested)
.last()plus a two-tool test where the first hook stops. Not a blocker on its own — flagging so it does not get lost under the new external-resume work.
| for (TextBlock block : closingMsg.getContentBlocks(TextBlock.class)) { | ||
| String blockId = UUID.randomUUID().toString().replace("-", ""); | ||
| publishEvent(new TextBlockStartEvent(effectiveReplyId, blockId)); | ||
| publishEvent( |
There was a problem hiding this comment.
Two small notes on the synthesized projection:
- The whole
TextBlockis emitted as one delta. That is fine functionally, but it is the only place in the codebase where a text block reaches event consumers undivided, so a client that assumed bounded chunks (the model path chunks per SSE frame) sees one oversized frame for returnDirect turns. Chunking it the same way asModelCallBlockLifecyclewould keep the projection uniform. - Non-text results (image / data blocks) emit no text events at all, which is documented here, but it means an image-only returnDirect answer disappears from a text-only consumer with no signal. Worth one sentence in
Tool#returnDirect()javadoc: the flag currently implies "the result is the final answer and it is text".
…ResultEvent payload on the resume short-circuit, normalize the persisted placeholder state, and honor earlier PostActing stopAgent() in multi-tool batches
b0a3ccb to
56b2f84
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Delta re-review of 56b2f843 (previous review was on ebe401c3). All three findings from the last round are properly closed, and each one is pinned by a test rather than by a claim: ExternalExecutionResultEvent now publishes the caller's real results while only the persisted copy is placeholder-shaped, placeholderToolResultMsgs runs the state through determineToolResultState(...) so a short-circuited turn can't be recorded as RUNNING, the .last() stop-flag issue is addressed, and the @Tool javadoc now states the text-only projection rule instead of implying "empty output is the only gap". externalResumeNormalizesPlaceholderState is a good test to have — it asserts the reason (gate parity with the in-framework path), not just the value.
The takeUntil fix is the one place where the cure is worse than the disease: it cancels the concatMap, so every pair after the stopping tool loses its tool_result write and its PostActing hook, leaving a tool_use with no matching result in the persisted context — the inconsistency synthesizeErrorResultsForPendingToolCalls exists to prevent. Details and two possible shapes inline; the accompanying tc2 assertion would make it visible in CI either way.
Not blocking on anything else. CLA signed; CI green on this head (ubuntu + windows build, License, Module Sync, codecov, validate).
Automated review by github-manager-bot
| return Flux.fromIterable(successPairs) | ||
| .concatMap(this::notifyPostActingHook) | ||
| .concatMap(e -> notifyPostActingHook(e, returnDirect)) | ||
| .takeUntil(PostActingEvent::isStopRequested) |
There was a problem hiding this comment.
This fixes the swallowed-stop bug, but it introduces a new one: takeUntil completes the flux and cancels the concatMap, so for every pair after the stopping tool notifyPostActingHook is never subscribed. That method is the only place the pair's tool_result is appended (state.contextMutable().add(resultMsg)), while the assistant tool_use blocks were already written during reasoning — so a mid-batch stopAgent() persists a tool_use with no matching tool_result for the rest of the batch.
That is precisely the hazard documented on synthesizeErrorResultsForPendingToolCalls ("Without this, the next resumed run inherits an inconsistent context and providers may return an empty response"), except here it happens on the clean-stop path rather than on interrupt. The tools have already run by this point (successPairs comes out of runToolBatch), so their side effects are real but unrecorded, and their PostActing hooks silently never fire.
Two options that keep the stop semantics without losing the tail:
// (a) run every hook, then let the earliest stop win
return Flux.fromIterable(successPairs)
.concatMap(e -> notifyPostActingHook(e, returnDirect))
.collectList()
.flatMap(events -> {
PostActingEvent stop = events.stream()
.filter(PostActingEvent::isStopRequested)
.findFirst().orElse(null);
PostActingEvent event = stop != null ? stop : events.get(events.size() - 1);
...
});// (b) keep takeUntil, but patch the abandoned tail before returning
// (same shape as the interrupt reconciliation)
scope.synthesizeErrorResultsForPendingToolCalls();(a) is probably the behaviour the hook author expects; (b) is smaller but says "the remaining tools' hooks are skipped", which then deserves a comment on PostActingEvent/the @Tool javadoc rather than only here. Happy to look again either way — the takeUntil choice is defensible if it is explicit.
| } | ||
|
|
||
| @Test | ||
| void earlierPostActingStopWinsOverReturnDirect() { |
There was a problem hiding this comment.
Nice that the stop case is now covered — this test is what makes the fix reviewable. It pins tc1 (the stopping tool) but is silent about tc2, which is exactly the pair the cancellation drops, so CI stays green while the context loses a tool_result.
One extra assertion would turn this into a regression test for the tail as well:
assertNotNull("the non-stopping tool of the batch must still be recorded", findToolResultMsg(agent, "tc2"));If the answer is "skipping tc2 is intended", then please assert that instead (assertNull(...) plus a comment) — right now the test just doesn't say either way.
… PostActing hooks and persist verbatim past the earliest stopAgent()
Conflict resolutions: - ReActAgent.maybePatchPendingToolCalls: take upstream's shared MessageUtils.lastAssistantMessage(state.contextMutable()); fork's patchPendingToolCalls extraction was behaviour-equivalent and its findLastAssistantMsg() helper is deleted upstream. - AgentRunSandbox.shutdown: keep fork side. Upstream agentscope-ai#2302 (keep MCP channel open for non-owned sandboxes) is already covered — the fork replaced the MCP channel with the HTTP data plane and shutdown() is a deliberate no-op, with the isSandboxOwned() guard in destroyInstance(). - WorkspaceContextMiddleware.buildWorkspaceParagraph: combine both — upstream agentscope-ai#3020 effectiveWorkspace plus fork's RuntimeContext for the sandbox working directory. - Semantic fix: fork-only ToolRetryLater call site updated to the two-arg notifyPostActingHook(entry, false) introduced by agentscope-ai#2891. - AgentRunSandboxShutdownTest (added by agentscope-ai#2302) rewritten against the HTTP data plane / destroyInstance semantics. - Revision follows upstream at 2.0.4-SNAPSHOT.
feat(core): 支持
returnDirect工具语义摘要
returnDirect是工具调用的循环控制开关:工具执行成功后,结果不再交回模型推理,直接作为本轮最终输出返回调用方,对应 Spring AI 的@Tool(returnDirect = true)。false:结果喂回模型继续推理。true:跳过下一轮模型调用,结果直接返回。returnDirect=true且执行成功时才整体返回,否则喂回模型。多工具语义
一个 batch 产出多个结果时按整批决定去向:
TOOL_SUSPENDED挂起,returnDirect不生效。returnDirect=true且 state 为SUCCESS→ 返回TOOL_RETURN_DIRECT。实现
returnDirect 触发的本质,是把工具结果「搬进消息序列」充当本轮最终答案。结构上做两件事:
assistant消息,作为本轮最终输出写入 context 并返回,并打上TOOL_RETURN_DIRECT标记。messages是完整性的表达,必须维持tool call → tool result → assistant的闭环。原tool_result保留、内容换成占位句:Tool call completed. The result has been presented to the user as the final output of this turn.。占位句作为 tool result 承接 tool call 的「语言表达」,合成的 assistant「模拟 LLM」收口。这样既避免结果重复,也满足供应商「每个tool_use后必须紧跟tool_result」的要求。判定上同时校验工具声明与结果状态:仅当该轮所有结果均
returnDirect=true且SUCCESS才直接返回;suspended 挂起与 HITL 叫停优先于 returnDirect。兼容性
returnDirect=false),无破坏性变更。ToolBase位置构造器签名,内置工具无需改动。switch的少数消费方;GenerateReasonTest计数断言 11 → 12。