Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/llm/src/protocols/openai-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,10 @@ const NO_EVENTS: StepResult["1"] = []
// `finish` event; `response.failed` is a hard failure that emits a
// `provider-error`. All three end the stream — kept in one set so `step` and
// the protocol's `terminal` predicate stay in sync.
const TERMINAL_TYPES = new Set(["response.completed", "response.incomplete", "response.failed"])
// `error` is terminal too: the provider emits it as the last event before
// closing a failed stream, and treating EOF after it as truncation would mask
// the real provider error (#407).
const TERMINAL_TYPES = new Set(["response.completed", "response.incomplete", "response.failed", "error"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Adding error to the terminal set stops reading at the first error event, so anything the provider sends afterwards is dropped

TERMINAL_TYPES drives Stream.takeUntil (src/route/client.ts:294), so with error in the set the client now cancels the provider stream at the first error event instead of draining it to EOF. Events after it are never parsed — for example a response.failed that follows an error carries the failure details under response.error (src/protocols/openai-responses.ts:900), and the user would no longer see them because the stream was already halted.

If the intent is only to stop the truncation error from masking a provider error, consider tracking "the provider reported an error" separately from "stop reading" rather than mixing it with the completion sentinels. Also note the comment above still says "All three end the stream" while the set now holds four types.


const onOutputTextDelta = (state: ParserState, event: OpenAIResponsesEvent): StepResult => {
if (!event.delta) return [state, NO_EVENTS]
Expand Down
20 changes: 20 additions & 0 deletions packages/llm/src/route/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,19 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
}),
streamPrepared: (prepared: Prepared, request: LLMRequest, runtime: TransportRuntime) => {
const route = `${request.model.provider}/${request.model.route.id}`
// Tracks whether a protocol-terminal event was seen, so a clean EOF
// without one (proxy/gateway truncation) fails into the retry pipeline
// instead of completing silently and looping generation (#407).
let sawTerminal = false

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: sawTerminal is allocated outside the stream, so re-running the same stream value skips the check

streamPrepared returns a Stream value, but the flag is created when the value is built rather than when the stream is executed. LLMClient.stream re-invokes streamPrepared per run (src/route/client.ts:394), so the main path is fine, but Route.streamPrepared is public API: a caller that keeps the stream and runs it twice gets a second run where sawTerminal is already true from the first run, and the truncation failure is silently skipped.

Move the flag inside the stream (for example Stream.unwrap(Effect.sync(() => { let sawTerminal = false; return ... }))) so every execution gets fresh state.

const events = routeInput.transport
.frames(prepared, request, runtime)
.pipe(
Stream.mapEffect(decodeEvent(route)),
Stream.tap((event) =>
Effect.sync(() => {
if (protocol.stream.terminal?.(event)) sawTerminal = true
}),
),
protocol.stream.terminal ? Stream.takeUntil(protocol.stream.terminal) : (stream) => stream,
)
return events.pipe(
Expand All @@ -291,6 +300,17 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
protocol.stream.onHalt ? { onHalt: protocol.stream.onHalt } : undefined,
),
Stream.catchCause((cause) => Stream.fail(streamError(route, `Failed to read ${route} stream`, cause))),
(stream) =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The EOF check ignores stream.onHalt, so a protocol that flushes its terminal event at EOF would emit a finish and then fail

Protocol.stream.onHalt is the documented way to flush the final event when the framed stream ends (src/route/protocol.ts:62); openai-chat (src/protocols/openai-chat.ts:491) and gemini (src/protocols/gemini.ts:496) both rely on it. The new check only looks for a terminal event, so a protocol declaring both terminal and onHalt would emit a valid finish through onHalt at EOF and then immediately fail with "Provider stream ended without a terminal finish event" — the same stream both completes and fails.

No protocol has both today, but the contract offers the two mechanisms independently and openai-chat/gemini are one predicate away. Gate the check on the protocol having no onHalt flush, or track a parser-level "finish emitted" signal instead.

Stream.concat(
stream,
Stream.fromEffect(
Effect.suspend(() =>
protocol.stream.terminal === undefined || sawTerminal

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: The terminal === undefined guard leaves the #407 failure mode in place for every other protocol

The new EOF check only runs for protocols that declare a stream.terminal predicate, and today that is only openai-responses (src/protocols/openai-responses.ts:978). anthropic-messages declares neither terminal nor onHalt (src/protocols/anthropic-messages.ts:838-842) and emits its terminal finish only when the message_delta event arrives (src/protocols/anthropic-messages.ts:819), so a truncated Anthropic stream still ends cleanly with no finish event.

That is the exact #407 loop, and the native runtime supports Anthropic (packages/opencode/src/session/llm/native-runtime.ts:55 allows the anthropic provider): packages/opencode/src/session/prompt.ts:1777 derives finished from handle.message.finish, so a stream that ends without a finish event leaves the assistant message unfinished and the run loop starts another generation, over and over, until the user interrupts.

Please make the "response completed" signal part of the contract for every protocol (add a terminal predicate to anthropic-messages, and treat openai-chat/gemini, which flush their finish through onHalt, as completed too), or key the check off a parser-level "finish emitted" signal instead of the presence of a terminal predicate, so every native route gets truncation protection.

? Effect.void
: ProviderShared.eventError(route, "Provider stream ended without a terminal finish event"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: The truncation failure is a non-retryable InvalidProviderOutput, so it never reaches the session retry pipeline

ProviderShared.eventError builds an InvalidProviderOutputReason (src/schema/errors.ts:134), whose retryable getter is false (src/schema/errors.ts:143), and the message Provider stream ended without a terminal finish event matches none of the session's RETRYABLE_MESSAGE_PATTERNS (packages/opencode/src/session/retry.ts:34). The native path surfaces the failure through MessageV2.fromError, which maps a plain Error to NamedError.Unknown (packages/opencode/src/session/message-v2.ts:705), so SessionRetry.retryable returns undefined and Effect.retry (packages/opencode/src/session/processor.ts:745) gives up after the first attempt.

The turn does stop instead of regenerating, which is the main point of the fix, but the claim in the PR description that the failure "feeds the session retry pipeline and, once retries are exhausted, halts the turn" does not hold: a transient gateway truncation — the most likely cause — is never retried. Either classify the failure as retryable and have the session honour LLMError.retryable, or use a reason/message the session already treats as retryable.

),
).pipe(Stream.drain),
),
)
},
} satisfies Route<Body, Prepared>
Expand Down
30 changes: 30 additions & 0 deletions packages/llm/test/provider/openai-responses.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,36 @@ describe("OpenAI Responses route", () => {
}),
)

it.effect("fails the stream when EOF arrives without a terminal event", () =>
Effect.gen(function* () {
const body = sseEvents(
{ type: "response.output_text.delta", item_id: "msg_1", delta: "Hello" },
{ type: "response.output_text.delta", item_id: "msg_1", delta: "!" },
)
const error = yield* LLMClient.stream(request).pipe(
Stream.runCollect,
Effect.flip,
Effect.provide(fixedResponse(body)),
)

expect(error.message).toContain("Provider stream ended without a terminal finish event")
}),
)

it.effect("streams cleanly when a terminal event closes the response", () =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Nothing pins the new error-as-terminal behaviour at the stream level

The error classification is the protocol correction this PR makes, but it is only covered indirectly: the existing provider-error cases go through LLMClient.generate, which fails if the stream errors, so they would catch a revert of the set. No test asserts the new contract directly — that a stream ending with an error event completes without the truncation failure and surfaces the provider error.

A case next to these two would lock it in:

it.effect("does not report truncation when the provider ends with an error event", () =>
  Effect.gen(function* () {
    const events = Array.from(
      yield* LLMClient.stream(request).pipe(
        Stream.runCollect,
        Effect.provide(fixedResponse(sseEvents({ type: "error", code: "rate_limit_exceeded", message: "Slow down" }))),
      ),
    )

    expect(events[events.length - 1]).toMatchObject({ type: "provider-error" })
  }),
)

Also, the new EOF test asserts only a message substring; asserting the failure reason as well would keep the classification from drifting.

Effect.gen(function* () {
const body = sseEvents(
{ type: "response.output_text.delta", item_id: "msg_1", delta: "Hello" },
{ type: "response.completed", response: { id: "resp_1" } },
)
const events = Array.from(
yield* LLMClient.stream(request).pipe(Stream.runCollect, Effect.provide(fixedResponse(body))),
)

expect(events[events.length - 1]).toMatchObject({ type: "finish", reason: "stop" })
}),
)

it.effect("parses reasoning summary stream fixtures", () =>
Effect.gen(function* () {
const body = sseEvents(
Expand Down
Loading