Open and close each streamed model response with `ModelResponseStartEvent` and `ModelResponseEndEvent`

DO
11h ago
+3532-166

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), never StreamedResponse.__aiter__, so Model.request_stream() used directly sees no change.
  • start comes 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 legacy TemporalAgent/DBOSAgent/PrefectAgent wrappers deterministic. Their workflow-side stream is an event-less CompletedStreamedResponse, 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.
  • end carries the response as streamed. A response that stopped before it finished has state='interrupted', as the run records a partial response.
    • complete: the stream finished (a later ModelRetry can 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, with error as 'ExceptionType: message' (the ModelRequestAttempt.error format). 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's timeout=, a wrap_run_event_stream capability raising, and durable cancellation or deadlines (Temporal TRY_CANCEL or request_timeout, DBOS/Prefect cancellation). Douwe decided to document this rather than make up an end in workflow code; docs/agent.md lists the cases. Temporal's default TRY_CANCEL stays 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 with WAIT_CANCELLATION_COMPLETED. The partial then reaches history as 'interrupted', but the stream still gets no end, as docs/agent.md lists. An opt-in 'interrupted' end for that case is a follow-up once this merges.
    • interrupted: AgentStream.cancel(), or a wrap_model_request hook 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, with response=None.
  • replaces is the previous core attempt's response_id when attempt > 1: a ModelFallback / RetryModelRequest re-attempt, or a wrap_model_request replacement. A durable re-execution of the same attempt doesn't set it.
  • Workflow side: the events are in ModelResponseStreamEvent, so MODEL_RESPONSE_STREAM_EVENT_TYPES already 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.patched gate is needed. A subscriber before 2.77 can leave them off with the topic's events filter.
  • 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_handler gets them.
  • Durable end responses: a durable model unit's end event carries the model_id the run records (ModelRequestParams.response_model_id, on the Temporal and DBOS transports). Follow-ups: #15927 for the Hatchet, Render and Azure wires, and #15924 for workspace_ref.
  • UI adapters:
    • The base UIEventStream opens a new response turn on every ModelResponseStartEvent, so Vercel AI emits start-step per response, and AG-UI mints a new message ID per response. _turn_to stays for boundary-less streams (David's measurement on #7142).
    • On a non-complete end it ends the open part (#14426's _end_open_part). For failed and interrupted it also answers the tool calls that response streamed, with the same synthetic failed / interrupted results 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 gets TOOL_CALL_END + TOOL_CALL_RESULT in AG-UI and tool-input-available + tool-output-available in Vercel AI. One limit: a UI fed from a Temporal Workflow Streams topic gets these answers only with response_boundaries=True, since the default topic doesn't publish the end. superseded only ends the open part.

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 ModelResponseStreamEvent or AgentStreamEvent exhaustively now sees two new event kinds, ModelResponseStartEvent and ModelResponseEndEvent, and must handle or ignore them. That covers a match ending in assert_never and an isinstance chain 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/main and on this branch, encoding a text-only run and a tool round trip (a tool call, then a final text response) with VercelAIEventStream and AGUIEventStream. 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               finish
    

    Pinned 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-error after the tool-input-available that main already sends. Before, the call was left announced but unanswered. AI SDK v6 is unchanged: it gets the single tool-input-error from #14638. Pinned by test_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 AgentStreamEvent or a snapshot of a run's events gains them.

  • The _special_tokens restoration applies to end.response as it does to the part events (test_streamed_response_end_carries_the_restored_text).

Not in this PR

  • ModelRequestStartEvent / ModelRequestEndEvent from #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 interrupted on a real cancel: that's #13731 (Phase 0 item 4).
  • Vercel reset-step and 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), a ModelFallback re-attempt (replaces set), AgentStream.cancel() (interrupted with the partial), and an error after output (failed).
  • tests/test_capability_hooks.py: a wrap_model_request replacement mid-stream (interrupted, then a start with replaces).
  • tests/durable_exec/temporal/test_workflow_streams.py: a retried activity (the first execution's failed end, then the successor's superseded end and its own start), replayed with Replayer; and an events filter keeping the boundaries off the topic while the activity's handler still gets them.
  • tests/test_vercel_ai.py and tests/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 failed with 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-snapshot handler writes origin=ANY for 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 ModelResponseStreamEvent next to the part events and carry the ModelResponseOrigin.
  • start precedes a response's first event; a stream with no events gets neither, and a re-attempt's start sets replaces to the previous response id.
  • end carries the streamed response and a status: complete, failed, interrupted, or superseded; a complete end 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 failed with 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, and PrefectAgent drop 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_id the 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_start and handle_model_response_end hooks let adapters forward the boundary events.
  • StreamGuardrail screens held tool calls when their response ends and releases the end's response as screened; a screened end loses its history_digest and provider details, and its error keeps only the exception type.
  • An API-compatibility waiver against v2.78.0 exempts the union extension.
  • Docs list the cases where a start can lack an end and 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.