In this note
  1. 01call and streamEvents share one execution core
  2. 02Event IDs answer different questions
  3. 03Streaming events can rebuild a message
  4. 04Permission ASK creates a real pause
  5. 05External execution uses a suspended result
  6. 06Interrupt is not the same as HITL pause
  7. 07AgentStateStore defines the recovery boundary
  8. 08A production review checklist
  9. 09Source files

An Agent becomes difficult to operate when one call lasts longer than one HTTP request. The model may stream text, request two tools, wait for approval, and continue several minutes later. A process may restart between those steps. If the runtime exposes only a final string, the application cannot tell whether the task finished, paused, or lost its place.

AgentScope Java 2.0 models an execution as an event stream backed by session state. The code below comes from commit d60414a6. The example is a deployment assistant that prepares a release, asks before publishing it, waits for an external deployment system, and then reports the result.

A recovery review asks what is persisted, what is only streamed, and what the next call must provide.

call and streamEvents share one execution core

ReActAgent routes both blocking and streaming APIs through buildAgentStream().

callInternal() consumes that stream, selects the last AgentResultEvent, and returns its Msg. streamEvents() exposes the same stream to the caller. Middleware around onAgent sees the same lifecycle in both modes, so a production service does not need separate policy code for the REST path and the SSE path.

The outer lifecycle is:

AgentStartEvent
    -> reasoning events
    -> tool events
    -> zero or more additional reasoning rounds
    -> AgentResultEvent
    -> AgentEndEvent

buildAgentStream() also runs the normal agent lifecycle, including the execution gate, hooks, tracing, and state handling. It installs an event sink in Reactor context so inner reasoning and acting code can publish events without receiving a UI callback through every method signature.

Cancellation is scoped to the subscription. When the subscriber cancels the Flux, sink.onCancel() disposes the lifecycle subscription. A blocking tool may still continue if its implementation does not respond to cancellation. Cancellation also does not create a durable resume point. Durable recovery depends on the state written before cancellation or interruption.

Event IDs answer different questions

The stream uses three identifiers:

  • replyId groups events produced by one reply stream.
  • blockId groups the start, delta, and end events for one text, thinking, or data block.
  • toolCallId connects a tool request with its result.

These IDs have different scopes. blockId is meaningful inside its reply. A tool call ID must remain stable when the tool moves from requested to approved, executed, or denied. A session ID belongs to runtime state and spans multiple calls.

The source also creates reply IDs at more than one layer. buildAgentStream() creates an ID for the outer Agent lifecycle. Model calls and acting streams create their own IDs for their event sequences. A consumer should therefore correlate events by event type and ID instead of treating the first reply ID as a session-wide trace ID.

A practical UI state model looks like this:

(replyId, blockId)       -> visible streaming block
(replyId, toolCallId)    -> tool status in this event sequence
(userId, sessionId)      -> durable Agent state slot

Mixing these scopes causes familiar bugs. A reconnecting client may attach new deltas to an old message, or a tool result may be displayed under the wrong call even though the backend state is correct.

Streaming events can rebuild a message

Model output arrives as block lifecycles. Text, thinking, and tool calls each produce start, delta, and end events. Inside ReActAgent, ModelCallBlockLifecycle makes sure the start event appears before the first delta and the end event appears when the model call closes.

The accumulator contract in ContentAccumulator is small: add a chunk, report whether content exists, build the aggregated block, and reset. Text concatenation and tool argument assembly can use different implementations while producing normal ContentBlock objects for the final message.

This supports two views of the same output:

incremental AgentEvent stream -> live interface and telemetry
final Msg                     -> conversation context and return value

Reconstructible events are not automatically a durable event log. The framework emits them, but an application that needs reconnect replay must store them with ordering information. AgentStateStore persists Agent state, not every event sent over SSE.

That distinction affects recovery design. Event storage lets a client redraw what already happened. Agent state lets the next call decide what work remains.

Permission ASK creates a real pause

Suppose the model requests publish_release. Permission evaluation returns ASK. The acting path marks the related ToolUseBlock as ASKING, emits RequireUserConfirmEvent, and then emits a RequestStopEvent with GenerateReason.PERMISSION_ASKING.

No approved tool runs in that branch. If the same model response also contained calls denied by policy, the Agent writes synthetic DENIED results for those calls before stopping. This prevents denied calls from appearing as unresolved work after resume.

The pause result contains the pending calls:

agent.streamEvents(message)
    .doOnNext(event -> {
        if (event instanceof RequireUserConfirmEvent confirm) {
            confirm.getToolCalls().forEach(toolCall ->
                showApproval(toolCall.getId(), toolCall.getName(), toolCall.getInput()));
        }
    })
    .blockLast();

The next call must send ConfirmResult objects under Msg.METADATA_CONFIRM_RESULTS. The Agent checks its saved context for calls in ASKING state. If they exist and the new call contains no confirmation, it fails with an explanatory exception instead of silently starting another reasoning round.

An approved result may carry a modified ToolUseBlock. applyConfirmResults() replaces the pending block and changes its state to ALLOWED. A rejection writes a ToolResultBlock with state DENIED, which the model can see in the next reasoning step.

This is application-level continuation. The JVM stack is not suspended. The first call returns after persisting pending work. A later call loads the state, recognizes the pending tool IDs, applies confirmation, and enters resumeAgent().

External execution uses a suspended result

Some tools must run outside the Agent process. A payment provider, deployment controller, or operator console may own the actual side effect. A tool marked externalTool=true is not invoked locally by ToolExecutor. The executor returns a suspended ToolResultBlock. ReActAgent then builds a message containing the tool request and pending result, with GenerateReason.TOOL_SUSPENDED.

The source tree declares RequireExternalExecutionEvent and ExternalExecutionResultEvent, and the documentation describes them. In the inspected commit, the runtime execution path does not construct either event class. A consumer should use the suspended result and GenerateReason.TOOL_SUSPENDED as the verified contract, or add and test an adapter before depending on the dedicated event types.

The external system performs the operation and returns ToolResultBlock values on a later call. Their IDs must match the pending tool call IDs. The Agent validates and adds those results, then resumes reasoning when no pending calls remain.

Permission approval and external execution solve separate problems:

  • Approval decides whether an operation may run.
  • External execution decides where it runs and who supplies the result.

A tool can require both. Approval should happen before an external system receives a request. The external result should include a stable operation ID so the application can reject duplicates or safely return the first result after a retry.

Interrupt is not the same as HITL pause

InterruptControl holds a flag, an interrupt source, and an optional user message for one session. ReActAgent.interrupt(userId, sessionId) raises that flag. Reasoning start, acting start, and streaming chunks are checkpoints where execution can notice it.

The control object is transient and is excluded from serialized AgentState. The interrupt signal therefore belongs to the current process. It cannot be used as a cross-process cancellation message after a worker has crashed.

State written around the interruption can still survive. Partial reasoning may be kept or discarded according to shutdown policy, and the conversation context is saved through the normal state lifecycle. A later call works from that saved context. It does not resume the old Java stack or Reactor subscription.

This gives three different behaviors:

| Mechanism | What stops | Durable input for continuation | |---|---|---| | Permission ASK | Tool execution before approval | ToolUseBlock in ASKING state plus ConfirmResult | | External execution | Local execution of an external tool | Pending tool call plus matching ToolResultBlock | | Interrupt | Current in-process execution at a checkpoint | Saved Agent context, if it was persisted |

Treating all three as a generic paused boolean loses the information needed to resume safely.

AgentStateStore defines the recovery boundary

AgentState contains the conversation buffer, summary, reply position, current iteration, permission context, tool context, task context, and plan-mode context. A configured AgentStateStore saves that state under (userId, sessionId).

At the start of a call, activateSlotForContext() resolves the slot. When a store is configured, it reloads the state on every call instead of trusting a JVM cache. This supports deployments where the next request reaches another replica. Calls for the same slot pass through the execution gate, while different sessions can run independently.

The storage abstraction does not make tool side effects transactional with Agent state. A deployment may succeed, then the worker may fail before it saves the result. The next call can see a pending tool and try again. Each side-effecting tool still needs an idempotency key or a status lookup in the system that owns the operation.

For the deployment assistant, the durable contract should be:

toolCallId -> deployment operation id
operation id -> external deployment status
(userId, sessionId) -> AgentState
event sequence -> optional replay store for the client

The Agent state tells the workflow what it intended to do. The deployment system remains the authority on whether the deployment actually happened.

A production review checklist

Before calling an Agent recoverable, test the points where state changes ownership:

  1. Disconnect an SSE client during a text block, reconnect, and replay stored events without duplicating text.
  2. Stop after RequireUserConfirmEvent, start a new process, and approve the pending call using the same (userId, sessionId).
  3. Submit the same approval twice and verify that the tool side effect occurs once.
  4. Return an external result with an unknown tool call ID and confirm that the Agent rejects it.
  5. Interrupt during reasoning and tool execution, then inspect which partial messages were saved.
  6. Run two requests for the same session and verify their order. Run different sessions and verify that they do not share state.

These checks separate a demo that looks smooth from a service that can recover. The output should be a documented continuation contract: identifiers, persisted fields, duplicate handling, and the actor responsible for each retry.

Source files