Open and close each streamed model response with `ModelResponseStartEvent` and `ModelResponseEndEvent`
Stacked on #14402 (ModelResponseOrigin on part events), and it also merges #14426 (UI ends the open part on a restarted start), whose _end_open_part it reuses. Review the diff against model-response-origin. The #14426 merge also brought in the main commits that branch had merged, so the diff shows them for now; the PR's own changes are the commits on top. Once #14402 and #14426 merge, I'll merge origin/main in (a merge commit) so the diff is only this PR.
Step 6 of the stream attempts design: every streamed model response in an agent run is now opened by a ModelResponseStartEvent and closed by a ModelResponseEndEvent, so a consumer can render or store a whole response when it ends, and tell a response that completed from one that failed, was interrupted, or was superseded by a durable re-execution.
[!WARNING]
Compatibility impact: Existing code that matches AgentStreamEvent or ModelResponseStreamEvent exhaustively (a match ending in assert_never, or an isinstance chain that raises on an unknown event) may now fail on the new ModelResponseStartEvent and ModelResponseEndEvent. Vercel AI streams also get a finish-step/start-step between consecutive responses (see Compatibility below). Temporal Workflow Streams topics publish the new events too, so a stream_agent_events() subscriber on a release before 2.77, which can't skip unknown event kinds, ends its stream on the first one.
Why this can ship in a minor release: the version policy lists adding new "stream events" as not breaking, and asks consumers to code defensively against them. Subscribers on 2.77 and later skip event kinds they don't know (#14391). The Hatchet durable stream doesn't publish them yet, and the deprecated durable wrappers never dispatch them.
Migration: handle or ignore ModelResponseStartEvent and ModelResponseEndEvent wherever event streams are matched exhaustively. Until every Temporal topic subscriber runs 2.77 or later, leave the events off the topic with WorkflowStreamTopic(..., events=lambda e: not isinstance(e, ModelResponseStartEvent | ModelResponseEndEvent)).
The events
ModelResponseStartEvent(origin, model_name, provider_name, replaces=None)
ModelResponseEndEvent(origin, status: 'complete' | 'failed' | 'interrupted' | 'superseded', response, error=None)
Both are members of ModelResponseStreamEvent, next to the part events, and carry the ModelResponseOrigin from #14402. As on the part events, origin is left out of equality and repr().
- Who emits them: the agent stream (
AgentStream) and the durable model unit (BaseDurabilityCapability._model_request_stream_operation), neverStreamedResponse.__aiter__, soModel.request_stream()used directly sees no change. startcomes right before a response's first event, so it carries the model and provider names the stream knows by then. A stream with no events gets neither event. That keeps stand-in streams silent (a stream that failed to open, a hook that retried before calling its handler), and it keeps the legacyTemporalAgent/DBOSAgent/PrefectAgentwrappers deterministic. Their workflow-side stream is an event-lessCompletedStreamedResponse, and they dispatch every workflow-side event to the handler in a durable unit of its own, so boundaries there would add units an in-flight run's history doesn't have.endcarries the response as streamed. A response that stopped before it finished hasstate='interrupted', as the run records a partial response.complete: the stream finished (a laterModelRetrycan still reject it).failed: an error cut the stream short, whether the model's stream raised it or something around it did, like an exceeded usage limit. The end comes before the error propagates, witherroras'ExceptionType: message'(theModelRequestAttempt.errorformat). A start is left without an end only when the stream is torn down where nothing can be yielded anymore: the consumer stopping or an in-process cancel, the run'stimeout=, awrap_run_event_streamcapability raising, and durable cancellation or deadlines (TemporalTRY_CANCELorrequest_timeout, DBOS/Prefect cancellation). Douwe decided to document this rather than make up an end in workflow code;docs/agent.mdlists the cases. Temporal's defaultTRY_CANCELstays as is (Douwe chose opt-in on #14460), so the docs say a cancelled Temporal streaming response gets no end. #14460 (merged) made keeping the partial opt-in withWAIT_CANCELLATION_COMPLETED. The partial then reaches history as'interrupted', but the stream still gets no end, asdocs/agent.mdlists. An opt-in'interrupted'end for that case is a follow-up once this merges.interrupted:AgentStream.cancel(), or awrap_model_requesthook that stopped the stream to stream its own response.superseded: emitted by the successor durable execution (execution_attempt > 1) as its first event, for the previous execution's origin, withresponse=None.
replacesis the previous core attempt'sresponse_idwhenattempt > 1: aModelFallback/RetryModelRequestre-attempt, or awrap_model_requestreplacement. A durable re-execution of the same attempt doesn't set it.- Workflow side: the events are in
ModelResponseStreamEvent, soMODEL_RESPONSE_STREAM_EVENT_TYPESalready keeps the workflow-side copies away from handler dispatch and topic publishing. No new workflow commands.
Rollout (§7)
- In-process: always emitted. The version policy lists new stream events as non-breaking.
- Temporal topic: published by default, like any new event. They're published from the model activity, so in-flight workflows replay unchanged and no
workflow.patchedgate is needed. A subscriber before 2.77 can leave them off with the topic'seventsfilter. - Hatchet durable stream: never published, as Hatchet subscribers on 2.78 fail on an event kind they don't know and have no opt-in yet (follow-up #15926). The task's own
event_stream_handlergets them. - Durable end responses: a durable model unit's end event carries the
model_idthe run records (ModelRequestParams.response_model_id, on the Temporal and DBOS transports). Follow-ups: #15927 for the Hatchet, Render and Azure wires, and #15924 forworkspace_ref. - UI adapters:
- The base
UIEventStreamopens a new response turn on everyModelResponseStartEvent, so Vercel AI emitsstart-stepper response, and AG-UI mints a new message ID per response._turn_tostays for boundary-less streams (David's measurement on #7142). - On a non-
completeend it ends the open part (#14426's_end_open_part). Forfailedandinterruptedit also answers the tool calls that response streamed, with the same syntheticfailed/interruptedresults the error path uses, which is the synthetic-result option on #13260. Douwe decided on that option, so this closes #13260: the issue's repro, a hook that cancels a stream after a frontend tool call and returns a replacement, now getsTOOL_CALL_END+TOOL_CALL_RESULTin AG-UI andtool-input-available+tool-output-availablein Vercel AI. One limit: a UI fed from a Temporal Workflow Streams topic gets these answers only withresponse_boundaries=True, since the default topic doesn't publish the end.supersededonly ends the open part.
- The base
Harness StreamGuardrail
StreamGuardrail holds and screens part events, but the end event carries the whole response, so without a change the end would hand the caller what the guard replaced. The end's response is now released as screened: each screened part as the guard left it, and without a screened kind of part the guard never saw complete.
Compatibility
-
Exhaustive event matching: code that matches
ModelResponseStreamEventorAgentStreamEventexhaustively now sees two new event kinds,ModelResponseStartEventandModelResponseEndEvent, and must handle or ignore them. That covers amatchending inassert_neverand anisinstancechain that raises on an unknown event. Code that ignores unknown events is unaffected. docs/version-policy.md lists adding new "stream events" as not breaking. This is waived against v2.74.0 in.github/api-compatibility-waivers/61bc70c16b547c8ed6f1eaaddd5b42970ae5bb91f04e9796a418f3b655203c4b.json. -
Single-response runs: byte-identical; only retry/fallback/consecutive-response runs change. I ran the same script on
origin/mainand on this branch, encoding a text-only run and a tool round trip (a tool call, then a final text response) withVercelAIEventStreamandAGUIEventStream. After normalizing the random message IDs and timestamps, the SSE output is identical. The existing Vercel AI and AG-UI snapshot tests of those shapes pass unchanged. -
Bug fix for Vercel AI users (#12829): consecutive responses with no tool turn between them, like an output retry, used to share one step. Each response is now a step of its own, which is what the AI SDK expects:
before (main) after start start start-step start-step text-start text-start text-delta first text-delta first text-end text-end finish-step start-step text-start text-start text-delta second text-delta second text-end text-end message-metadata message-metadata finish-step finish-step finish finishPinned by
test_output_retry_streams_each_response_as_its_own_step. In AG-UI the second response gets its own message ID, as each model response already should. -
Vercel AI SDK v5, a tool call cut off by an error mid-stream: the response ends as failed, so its streamed call is now answered with
tool-output-errorafter thetool-input-availablethat main already sends. Before, the call was left announced but unanswered. AI SDK v6 is unchanged: it gets the singletool-input-errorfrom #14638. Pinned bytest_run_stream_error_closes_open_tool_call_v5. -
In-process event consumers see the two new event kinds, which the version policy lists as non-breaking. An exhaustive match over
AgentStreamEventor a snapshot of a run's events gains them. -
The
_special_tokensrestoration applies toend.responseas it does to the part events (test_streamed_response_end_carries_the_restored_text).
Not in this PR
ModelRequestStartEvent/ModelRequestEndEventfrom #7142: the design ships only the response half.run_stream_messages()from #7142: it becomes the §6 fold over these events in a later step.- Temporal
interruptedon a real cancel: that's #13731 (Phase 0 item 4). - Vercel
reset-stepand AG-UI's custom event for a superseded re-execution: Phase 0 item 2.
Tests
tests/test_model_response_boundaries.py: a plain run (start and end per response, each end equal to the response in history), aModelFallbackre-attempt (replacesset),AgentStream.cancel()(interruptedwith the partial), and an error after output (failed).tests/test_capability_hooks.py: awrap_model_requestreplacement mid-stream (interrupted, then a start withreplaces).tests/durable_exec/temporal/test_workflow_streams.py: a retried activity (the first execution'sfailedend, then the successor'ssupersededend and its own start), replayed withReplayer; and aneventsfilter keeping the boundaries off the topic while the activity's handler still gets them.tests/test_vercel_ai.pyandtests/test_ag_ui.py: snapshots of the chunk sequences for a replaced response whose tool call gets answered (#13260).- A usage limit exceeded mid-stream ends the response as
failedwith the partial (test_model_response_boundaries.py). tests/harness/guardrails/test_stream_guardrail.py: the end's response carries the redacted part.tests/durable_exec/test_durable_exec_compat.py: the new events round-trip through the durable JSON codec.- Existing event snapshots gain the two events. A test-only
inline-snapshothandler writesorigin=ANYfor them.
Credit
The response events, the UI wiring and the _turn_to measurement come from David Sanchez's (dsfaccini) #7142, rebuilt on the current design; his branch was three months and 23 conflicting files behind, so the commits are credited with a Co-authored-by trailer rather than merged. #5109 by yu2001-s explored the same boundaries first.
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
- PR title is fit for the release changelog.
🤖 Generated with Claude Code
Summary by cubic
Opens and closes each streamed model response in an agent run with ModelResponseStartEvent and ModelResponseEndEvent, so a consumer can render or store a whole response when it ends and tell a completed response from a failed, interrupted, or superseded one. Part of the stream attempts design (#14378), closes #7099 and #13260, and supersedes #7142.
The events
- Both sit in
ModelResponseStreamEventnext to the part events and carry theModelResponseOrigin. startprecedes a response's first event; a stream with no events gets neither, and a re-attempt'sstartsetsreplacesto the previous response id.endcarries the streamed response and astatus:complete,failed,interrupted, orsuperseded; acompleteend can carry an incomplete response when the stream was cut off.- Only the agent stream and the durable model unit inside an agent run emit them;
Model.request_stream()used directly is unchanged, and a durable unit stream outside a run emits neither. - A usage limit exceeded mid-stream ends the response
failedwith the partial. - UI adapters receive the end event's response with non-public tool parts hidden, matching what the part hooks show.
Rollout
- The events are always emitted in-process and published on Temporal topics by default; Hatchet's durable stream doesn't publish them yet (#15926), since its earlier subscribers can't decode the new kinds.
- The deprecated
TemporalAgent,DBOSAgent, andPrefectAgentdrop them from the workflow-side stream before handler dispatch, since they run one activity, step, or task per event and the new events would break replay of runs recorded before them. - A durable model unit's end event carries the
model_idthe run records, on the Temporal and DBOS transports, with the Temporal topic path now pinned by tests. - UI streams open a new response turn per
start, answer the tool calls a failed, interrupted, or rejected response streamed (#13260), and end the open part on a restarted start (#11734). Consecutive responses stream as separate Vercel steps, fixing #12829. - New
handle_model_response_startandhandle_model_response_endhooks let adapters forward the boundary events. StreamGuardrailscreens held tool calls when their response ends and releases the end's response as screened; a screened end loses itshistory_digestand provider details, and itserrorkeeps only the exception type.- An API-compatibility waiver against v2.78.0 exempts the union extension.
- Docs list the cases where a
startcan lack anendand say how to keep the events off a Temporal topic while some subscribers run a release before 2.77. - A tool call the run already executed is no longer answered again when a later response is rejected.