Skip to content

feat(core): add ON_FINAL_ANSWER middleware extension point — final-answer gate with certified delivery - #4213

Open
xzxiaoshan wants to merge 8 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/final-answer-gate
Open

xzxiaoshan wants to merge 8 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/final-answer-gate

Conversation

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

What this adds

A seventh middleware extension point: ON_FINAL_ANSWER. Any middleware that overrides the onFinalAnswer hook becomes a final-answer gate — consulted every time the agent is about to deliver an answer, with the last word on what actually ships.

Until now a middleware could observe and transform reasoning, but nothing could veto the final answer before it reached the caller. This closes that gap: PII redaction, compliance review, quality checks that send the agent back to work, or a fallback answer when the loop exhausts — all written as a middleware, with no agent subclassing and no wrapper code.

Writing a gate

A gate is just a MiddlewareBase that overrides one hook — no dedicated interface to implement:

public class ComplianceGate implements MiddlewareBase {

    private static final int MAX_RETRIES = 3;  // your policy, well below the framework fuse

    @Override
    public Mono<FinalAnswerDecision> onFinalAnswer(RuntimeContext ctx, FinalAnswerInput input) {
        // Retrying an exhausted summary rarely converges — swap in a fallback instead
        if (input.finishReason() == FinishReason.MAX_ITERATIONS) {
            return Mono.just(FinalAnswerDecision.accept(fallbackMessage()));
        }
        // Tool-direct output comes from your own tool code — let it through
        if (input.finishReason() == FinishReason.RETURN_DIRECT) {
            return Mono.just(FinalAnswerDecision.accept());
        }
        return Mono.fromCallable(() -> checker.check(textOf(input.candidate())))
                .subscribeOn(Schedulers.boundedElastic())
                .map(result -> {
                    if (result.passed()) {
                        return FinalAnswerDecision.accept();
                    }
                    if (input.retryCount() >= MAX_RETRIES) {
                        return FinalAnswerDecision.accept(fallbackMessage());
                    }
                    return FinalAnswerDecision.retry(reminder(result.issues()));
                });
    }
}

Three verdicts cover the space: accept() ships the candidate unchanged, accept(replacement) ships your rewrite instead (the session keeps the sanitized version), and retry(msgs) rejects the candidate — the model's own draft plus your feedback re-enters the context and reasoning runs again. An empty Mono counts as a plain accept.

The input carries the working draft, the retries already honored, cumulative token usage, and which exit produced the candidate (FINAL_ANSWER, MAX_ITERATIONS, RETURN_DIRECT). Interrupt-like exits — HITL suspension, acting stops — are not final answers and never reach the gate. The hook never receives the agent, so a stateless gate instance safely serves any number of agents and concurrent calls; cross-round state belongs in RuntimeContext attributes. Participation follows the same activePoints() contract as every extension point: auto-detected when you implement the hook (recommended to also declare EnumSet.of(ExtensionPoint.ON_FINAL_ANSWER) explicitly, as elsewhere).

Certified delivery — the trade-off, chosen not defaulted

ON_FINAL_ANSWER is a side-effect point: the moment any middleware participates there, the agent switches to certified delivery. Live TextBlock* / ThinkingBlock* events of every round are dropped from the public stream — dropped, not buffered, so nothing can leak on cancel or error. After the verdict, the certified message is projected in one burst, thinking first then text, each as a complete block lifecycle — clients assemble it exactly like a live stream. The projected content, call()'s return value, AgentResultEvent, and memory are the same message by construction; rejected candidates never reach the public stream.

Two notes for stream consumers: ModelCallEndEvent still fires live (usage only) and may precede the certified content — assemble text on TextBlockEnd / AgentResultEvent, never on ModelCallEnd. And the content-free final_answer.reviewing custom event is the intended hook for a "reviewing…" placeholder UI. Activation is never accidental: auto-detection lights up exactly the classes that factually implement the hook, and the only other path is an explicit declaration. Purely observational uses should stay on the event stream — a gate sacrifices real-time streaming for nothing.

Chains and safety rails

Multiple gates stack, consulted sequentially in order() (higher first). Each receives the current working draft — the chain head sees the model's original, later gates see their predecessors' replacements. Vetoes do not short-circuit: every gate is consulted, all feedback of a round is merged in chain order, and a round with multiple vetoes counts as a single retry. That retry writes the model's original draft (never a gate's rewrite) plus the merged feedback to memory, then re-enters reasoning with maxIters suspended — the retry fuse is the only bound on that path.

The rails: at most 10 retries per call, not configurable — the 11th veto fails the whole call closed (an error, zero delivery, the rejected draft still reaching the session-recording audit). A gate that throws fails the call, never a silent pass. Graceful exhaustion is the gate's own job, via input.retryCount(). Replacements stay within the exit's contract: at MAX_ITERATIONS and RETURN_DIRECT the framework re-stamps the exit's GenerateReason onto them, and native structured output is validated inside the accept path — a replacement that would break the exit's JSON contract fails closed instead of shipping garbage. An interrupt issued while a gate deliberates is honored at the verdict boundary, before anything ships.

Compatibility

Agents without a gate are unchanged — live token streaming stays, no gate events appear. MiddlewareBase gained only an enum constant and a default method (source- and binary-compatible); the engine driving all of this is package-private and holds no agent reference, only a per-call execution handle. FinalAnswerFilterMiddleware keeps its role for gate-free agents that only want a clean stream — its javadoc now spells out the division of labor.

Also included: a small fix to JsonFileAgentStateStore — an existing symlinked root directory is now accepted instead of failing Files.createDirectories (root-caused while running this branch's module suite on Windows; the affected test now passes deterministically).

Events and docs

Three markers on the CUSTOM channel: final_answer.reviewing (public stream placeholder while a gate deliberates), final_answer.retry (retry count and exit, never text), and final_answer.rejected (the rejected draft's text — session-recording audit only, never the public stream).

The middleware pages in docs/v2 are updated in English and Chinese.

…wer gate)

A middleware that overrides the new onFinalAnswer hook becomes a final-answer
gate: consulted at every final-answer exit (normal finish, the forced summary
after maxIters, the returnDirect short-circuit), it has the last word on what
gets delivered.

- Verdicts: accept() ships unchanged; accept(replacement) ships the rewrite and
  is memorized as the chain's output; retry(msgs) rejects the candidate - the
  model's original draft plus merged feedback re-enters reasoning. An empty
  Mono counts as a plain accept.
- Certified delivery: while a gate participates, live TextBlock*/ThinkingBlock*
  events are dropped (not buffered), and only the chain-certified message is
  projected post-verdict - thinking first, then text. The projected content,
  call()'s return, AgentResultEvent, and memory are the same message by
  construction.
- Chain semantics: gates run in order() (higher first), the working draft feeds
  forward, vetoes never short-circuit, and one round with multiple vetoes
  counts as a single retry; the retry re-enters reasoning with maxIters
  suspended.
- Safety rails: retry fuse of 10 per call (the 11th veto fails the whole call
  closed, the rejected draft still reaching the session-recording audit); gate
  errors fail the call; replacements keep the exit's contract (GenerateReason
  re-stamped at MAX_ITERATIONS/RETURN_DIRECT; native structured output is
  validated inside the accept path, a contract-breaking replacement fails
  closed).
- New public value types FinalAnswerInput, FinalAnswerDecision, FinishReason;
  package-private FinalAnswerGateEngine drives consultation, retry re-entry,
  audit, and projection, holding no agent reference.
- Content-free events: final_answer.reviewing (public-stream placeholder),
  final_answer.retry (retry count and exit, never text), final_answer.rejected
  (rejected draft text - session-recording audit only).
- Compatibility: MiddlewareBase gains one enum constant and one default method;
  agents without a gate are unchanged. FinalAnswerFilterMiddleware keeps its
  role for gate-free agents. docs/v2 middleware pages updated (EN/ZH).
- Also fix JsonFileAgentStateStore: accept an existing symlinked root instead
  of failing Files.createDirectories (root-caused while running this branch's
  module suite on Windows; the affected test now passes deterministically).
@mintlify

mintlify Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit a19ec7d.

Approve preview

Merge main (5525ac1) into the final-answer-gate branch and resolve:

- MiddlewareBase: keep both new extension points — ON_FINAL_ANSWER
  (this branch) and ON_AGENT_FINISH (main, durable runtime agentscope-ai#4154);
  both default methods kept; class javadoc lists onAgentFinish and
  states no hard hook counts (the enum is next to it).
- ReActAgent: adopt main's durable-runtime shape and rebase the gate
  onto it — settleSession stays deleted (durable host owns
  continuation); finalizeReturnDirect keeps its gated Mono signature;
  publishEvent keeps main's recordEvent/emitEvent split but stays
  package-private for the gate engine; reasoning keeps the host
  boundary wrapper; terminal reasoning messages still land only after
  the gate verdict, with main's reasoningCompleted() position
  bookkeeping preserved.
- FinalAnswerGateEngine + gate test: port the rejected-draft audit from
  the removed SessionRecorder to InvocationRecorder (journal event
  extension/final_answer.rejected).
- docs/v2 EN/ZH middleware pages: follow main's trimmed structure
  (activePoints/onAgentStateReady prose sections removed there) and
  layer the onFinalAnswer content on top. Counts follow the code, not
  main's docs: every ExtensionPoint constant is documented — 8 hooks,
  four types (Notification restored with onAgentStateReady +
  onAgentFinish), aligned tables/diagrams/wording in both languages.

Verified: mvn -pl agentscope-core -am test for
ReActAgentFinalAnswerGateTest (51), AgentExecutionHostTest (13),
InvocationIdentityTest (9), StructuredMixedBatchAuditTest (7) — all
pass; spotless:check clean; docs npm test 20/20 and build validation
pass.
- withhold returnDirect-bound tool batch content and defer external
  result events past the gate verdict (certified-delivery leak)
- mark gate-raised errors at the native structured exit so the
  synthetic-tool fallback rethrows instead of re-running the model
- re-certify fallback structured completion recursively across gate
  retries; validate replacements against the schema (fail closed)
- pass the real completion iteration at the returnDirect-resume and
  fallback-completion exits (durable position regression)
- trip the retry fuse only after the whole gate chain is consulted
- move middleware docs from v2 (published 2.0.4 snapshot) to dev EN/ZH
@xzxiaoshan

Copy link
Copy Markdown
Collaborator Author

A round of optimization was performed, optimizing and fixing the following content.

Fixed

  1. returnDirect content leak — a returnDirect tool's output is the final-answer candidate, yet its content events streamed live during execution, and the external-resume ExternalExecutionResultEvent was published before the verdict, violating the "rejected candidates never reach the public stream" promise. Now decided upfront by declaration: with a gate active, an all-returnDirect batch emits only lifecycle events (Start/End) and the content ships post-verdict via the existing projection; an external-resume result event is deferred until the original result is accepted — never on reject or replace. A failed returnDirect batch feeding the model no longer streams its output (the result still reaches the model context and the journal audit).

  2. Native structured output swallowing gate errors — a gate error was caught by the synthetic-tool fallback, which re-ran the model; if the second round passed, the call succeeded — violating fail-closed. Gate-raised failures (consultation, fuse, retry re-entry) are now marked and rethrown before the fallback; model output parse/validation failures keep the existing fallback behavior.

  3. Fallback structured output breaking the typed contract after a retry — this ran one level deeper than reported: a gate retry's re-entry terminal returns directly as the gate's own value, bypassing the completion exit's extraction and re-certification entirely, so a plain-text round could come back as the WeatherResponse.class result (the old test actually pinned that behavior). A retry round now re-forces generate_response, and the re-entered terminal is re-certified recursively by the same rules; replacements are validated against the schema and fail closed when invalid.

  4. Hardcoded iteration 0 in two exits (external returnDirect resume, fallback completion) — a gate retry wrote the durable journal position backwards. Both now pass the real iteration.

  5. Fuse short-circuiting the gate chain — the 11th veto errored mid-chain, so later gates were never consulted in that round, contradicting the "every gate is consulted" promise in three places. The check now runs after the whole chain has been consulted.

Checked, not changed

  • Server tool events: server tools are not in the local toolkit and have no returnDirect path; their results are intermediate content, not final candidates — they stay on the progress channel.
  • allOf implicit activation: since feat(core): explicit activePoints() declarations win; undeclared middlewares are auto-detected #3579 the default is inferred from the hooks a class actually implements — a middleware that doesn't implement onFinalAnswer never lights the point up. The premise no longer holds in the current code.

Docs: the middleware.md changes were reverted from v2 (the published 2.0.4 snapshot) and the feature documentation now lives in dev, EN and ZH. The original diff had also leaked onAgentStateReady / onAgentFinish — neither shipped in 2.0.4 — into the stable docs; reverted as well.

One known edge left open: native structured output + maxIters summary exit + a gate error — the summary path unwraps the gate-error marker before the fallback check, so the fallback still triggers there (pre-existing behavior, very narrow trigger). Can follow up separately if needed.

Both scenarios ride fixed one-second broker redelivery windows and
lease-rediscovery chains that stack serially; a shared ubuntu runner
adds scheduling delay on every hop, so the 5s/10s budgets expired
while convergence was still in progress (observed on this PR and on
unrelated builds, cf. agentscope-ai#4176). Convergence stays the assertion — only
the deadline widens:

- RocketMqExecutionTest: shared 10s wait -> named 30s budget
- AgentScopeAdapterTest: host-rebuild/recovery awaits 5s -> 30s
Merge main (decbe55, 41 commits) into the final-answer-gate branch and
resolve:

- AgentScopeAdapterTest / RocketMqExecutionTest (content conflicts):
  both sides widened the same await budgets for loaded CI runners —
  this branch (bfb7e33) with literals, main (agentscope-ai#4274) with the named
  TURN_DEADLINE / AWAIT_DEADLINE_SECONDS constants and waitUntil,
  covering every site this branch touched with equal or wider budgets.
  Take main's version of both files; they are now identical to main,
  which supersedes this branch's deflake.
- ReActAgent (auto-merged): main's only change (agentscope-ai#2919) adds structured-
  output call/streamEvents overloads that delegate to doCall, so they
  run through the same gated exits. The merged file is main plus this
  branch's feature delta, verified line by line.

Verified: mvn -T1C clean test-compile over the whole reactor (114
modules, spotless:check clean); core and harness full suites (3573 and
1918 tests, 0 failures), including ReActAgentFinalAnswerGateTest (58)
and main's new ReActAgentStreamEventsStructuredOutputTest (7); core
package with javadoc doclint; RocketMqExecutionTest 5/5; docs npm test
20/20 and build validation.

Not introduced here — reproduced identically on main and on the
pre-merge branch head on this Windows machine:
AgentScopeAdapterTest
nativeHarnessWorkspaceForkCopiesPrivateFilesWithoutSharingSubsequentWrites
and realHarnessMemoryFinalizationReplaysRecordedSummaryAfterRestart fail
(39/41 pass); `mint broken-links` reports the same 2750 internal links
on main.
Merge main (a067f5c, 1 commit) into the final-answer-gate branch and resolve:

- ReActAgent.runPostReasoningPipeline (content conflict): main's agentscope-ai#4218 replaces
  reasoningCompleted(iter) with reasoningApplied(iter, answer) — once a round's
  result is in memory, a resumed (handed-off) model call is checkpointed with
  "model_result_applied" and its terminal answer preserved for re-entry — while
  this branch lands a terminal candidate only after the gate verdict. Keep
  main's deferred per-branch bookkeeping without its unconditional memory
  write, and drop this branch's eager reasoningCompleted(iter): it ran before
  the terminal branch and cleared the pending call, which would have silently
  disabled both of main's new effects for every agent.
- FinalAnswerGateEngine: the loop's terminal exit now hands its bookkeeping to
  the gate (new overload taking this::reasoningApplied), which reports each
  round once its outcome is in memory — the landed (certified) message after
  the memory write and before the projection on accept; nothing on a veto,
  before the retry re-entry. Reporting the pre-verdict candidate preserved a
  draft the gate had replaced or rejected as the call's answer; skipping the
  veto report left the retry round rejected with "Cannot call the model while
  waiting for <call>"; reporting after gate() returned re-applied a stale
  iteration. The plain three-argument gate(...) lost its only caller and is
  folded into the transform form.
- New ReActAgentFinalAnswerGateHandoffTest (5 cases) over a handed-off model
  call: the replacement is what lands and ships on resume; a run lost after
  landing re-enters with the preserved certified answer, without a model call
  or another consultation; a veto releases the call for the retry round (plain
  and native structured-output exits); a rejected draft is never the preserved
  answer. The last four cases were checked to fail under the wrong resolutions
  above; the first pins the happy path.

Known gap, not addressed here: the per-call retry fuse does not bound a Turn
whose gate retries run over handed-off model calls. Every resume is a new call
with retryCount 0, so a gate that keeps vetoing re-dispatches the model without
limit instead of failing closed after 10 retries. Settling the budget per Turn
needs a durable design decision.

Verified: mvn -T1C clean test-compile over the whole reactor (114 modules,
spotless:check clean); core and harness full suites (3586 and 1918 tests, 0
failures, 0 errors), including ReActAgentFinalAnswerGateHandoffTest (5),
ReActAgentFinalAnswerGateTest (58) and main's ReActAgentFailoverBoundaryTest
(11).

Not introduced here — the failing set of the durable adapter closure is a
subset of pure main's, reproduced on a067f5c (exported with git archive) on
this Windows machine: the durable adapter module (AgentScopeAdapterTest 4 of
49, ModelWorkerTest 3, ProcessRecoveryTest 2,
HarnessExternalToolProcessRecoveryTest 1) and the sandbox module (13).
Merge main (9cfeaad, 31 commits) into the final-answer-gate branch and
resolve:

- MiddlewareBase (4 content conflicts): main's agentscope-ai#4399 adds the ON_AGENT_EVENT
  point and its onAgentEvent hook; this branch adds ON_FINAL_ANSWER and
  onFinalAnswer. Keep both. The enum keeps main's relative order with this
  branch's constant placed after ON_AGENT_EVENT, and the class javadoc lists
  both hooks, combining main's "notification hooks default to a no-op" with
  this branch's onAgentFinish and onFinalAnswer defaults.
- ReActAgent.ToolResultCallback (2 content conflicts): main passes the
  batch's resultHolder so a resolved result reaches middleware before its
  events; this branch passes withholdCandidateContent, which withholds the
  content events of a returnDirect-bound batch while a gate is active. The
  constructor takes both: onResult publishes the result fact and keeps
  withholding the content events.
- docs/dev middleware.md, EN and ZH (10 content conflicts each): combine
  main's onAgentEvent rows, notification ordering and recordEvent diagram
  lines with this branch's onFinalAnswer rows, gate ordering and lifecycle
  diagrams. Both sides had rewritten the stale "default is active
  everywhere" activePoints() wording; take main's. The hook counts read 9.
- onAgentEvent under a gate (auto-merged, no code change): the observer loop
  runs inside recordEvent, downstream of the gate's public-stream guard, so
  withheld live text and thinking never reach observers, while the certified
  projection does. Established by reading the merged code, not by a test.

Verified: mvn -B -T1C clean verify over the whole reactor (114 modules,
BUILD SUCCESS), run with -Dmaven.test.failure.ignore=true so that a failing
module does not skip its downstream modules: spotless:check on all 114
modules, 14092 tests, 28 failing testcases in 7 modules, none in a module
this branch touches. Re-running those 11 test classes in isolation yields
the same 24 failing testcases on this tree and on pure main (9cfeaad,
exported with git archive): the durable adapter module
(AgentScopeAdapterTest 2, ModelWorkerTest 2, ProcessRecoveryTest 2), the
durable sandbox extension (13), the sandbox examples (SandboxRoundTripTest
3, ToolInSandboxExampleTest 1) and RocketMqExecutionTest (1). The remaining
4 (GitLabOutboundClientTest 1, LocalSandboxClientTest 2,
CommandExecutorTest 1) pass in isolation on both trees and failed only
under full-reactor load. Core (3660) and harness (2330) suites: 0 failures,
0 errors, including ReActAgentFinalAnswerGateTest (58) and
ReActAgentFinalAnswerGateHandoffTest (5). docs npm test 20/20 and build
validation pass; mint broken-links still reports every internal link as
broken on this machine (2754), and the merged docs add no site links over
main.

Apart from the resolutions above, the merged tree differs from main by this
branch's pre-merge delta: the same 15 files. The 11 files main did not touch
are byte-identical to the pre-merge branch, and ReActAgent carries the same
changed lines except the constructor.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant