Skip to content

fix: truncated OpenCode Go completions stream after tools reports a generic agent failure - #140367

Merged
VACInc merged 3 commits into
mainfrom
fix/completions-incomplete-stream
Sep 6, 2026
Merged

VACInc merged 3 commits into
mainfrom
fix/completions-incomplete-stream

Conversation

@VACInc

@VACInc VACInc commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Related: #128368, #127538, #137887, #126404, #138645, #124176, #138204

Additional instructions

MUST: Keep Allow edits from maintainers enabled for this PR so maintainers
can help update the branch when needed.

What Problem This Solves

Fixes an issue where users sending a follow-up in a Telegram topic session would see a generic ⚠️ Agent run failed (model: opencode-go/glm-5.3). after the model had already run tools and delivered pre-tool commentary, when OpenCode Go's openai-completions SSE closed without finish_reason or [DONE].

The sibling user-visible copy The tool run finished, but no final summary was produced. I did not repeat any completed actions. is the intentional host fallback after settled tools when isolated finalization is empty. This incident never reached that path: the truncated stream was unclassified, and pre-tool commentary was treated as if the turn had already composed a final answer.

Why This Change Was Made

Classify the completions-transport producer string Stream ended without finish_reason as the same incomplete assistant-stream timeout already used for Mistral/Bedrock/Anthropic/Google/OpenAI Responses. After tools have settled, capture settled-turn finalization context for that failure even when commentary was delivered before the last tool result. Do not treat that commentary as a composed final answer. Do not classify the plugin lifecycle string opencode-go stream ended without a terminal event (different owner, corpus forbids it).

Without prior tools, the timeout classification lets replay-safe failover/retry use the same path as the sibling incomplete-stream producers. After tools (replay-unsafe), the host can attempt a tool-free summary instead of unclassified "Agent run failed". If that summary is also empty, the existing honest fallback remains.

User Impact

  • After a truncated OpenCode Go / openai-completions stream with settled tools, OpenClaw can still produce a tool-free summary, or the existing honest "no final summary" fallback, instead of a generic agent-run failure.
  • After a truncated completions stream without tools, failover/retry copy matches other incomplete assistant streams (timeout) instead of an unclassified failure.
  • Session model overrides that disable fallbacks still get the post-tool recovery path rather than a dead end.
  • Plugin-owned opencode-go stream ended without a terminal event behavior is unchanged.

Evidence

Live incident (redacted, 2026-09-06 UTC)

Telegram group topic session (chat IDs, user IDs, usernames, hostnames, and personal content omitted).

  • User follow-up after a device power cycle; session model override opencode-go/glm-5.3 disabled configured fallbacks.
  • API: openai-completions. Endpoint: https://opencode.ai/zen/go/v1/chat/completions.
  • First POST: HTTP 200 SSE (~2.6s). Tool call succeeded (operator-owned SSH/exec-style tool). Commentary and tool cards were delivered to the topic.
  • Second completions request: HTTP 200 SSE (~2.8s), then the stream closed ~32s later with no finish_reason and no [DONE].
  • Producer error: Stream ended without finish_reason.
  • failoverReason: null, providerRuntimeFailureKind: unclassified.
  • User-facing copy: ⚠️ Agent run failed (model: opencode-go/glm-5.3).
  • Transcript: empty assistant, stopReason: error, 0 tokens.

Why settled-turn recovery did not run:

  1. resolveSettledTurnFinalizationContext only treated isTransientNetworkError as eligible. Incomplete-stream text is not a network errno.
  2. Any non-empty assistantTexts omitted context. Pre-tool commentary ("checking post-reboot state…") filled that list even though no post-tool answer existed.

Same-topic observations (not claimed as the same root cause)

  • Minutes earlier, a different glm-5.3 cloud route returned HTTP 429 session usage limit (you have reached your session usage limit; account identifier redacted). Retries 1–9 then rate-limit user copy. Provider name was already log-redacted.
  • A prior reply on the same topic was aborted by a new inbound (Reply operation aborted by user).
  • Earlier the same day: restart recovery claim changed before agent adoption on the same topic (operational noise).
  • Overnight, the same group hit Session transcript keyed user is outside the current turn on openai/gpt-5.6-sol (separate defect).

Classification contract

Producer in packages/ai/src/transports/openai-completions-stream.ts still throws Stream ended without finish_reason (tests already expect that string). Classification is the owner fix.

Pre-fix INCOMPLETE_ASSISTANT_STREAM_RE match results:

Message Old regex New regex
Stream ended without finish_reason no yes (timeout)
Mistral stream ended without a terminal finish reason yes yes
Bedrock stream ended before messageStop yes yes
opencode-go stream ended without a terminal event no no (intentional)

Local proof

  • Focused Vitest: attempt-result, settled-turn context (including incomplete-completions-stream capture), failover corpus (639), retry freeze. Exit 0.
  • node scripts/check-changed.mjs on the six touched files: exit 0 (core + coreTests), including tsgo and oxlint.
  • git diff --check: clean.
  • Autoreview (--mode local --base origin/main --max-priority P1) reported three P1s in src/cli/update-cli/* and src/commands/doctor-update.ts. Those files are not in this diff. Rejected as out of scope / wrong-patch hallucination.

Review follow-up (2026-09-06)

Runtime repair: af5690cec24d51b189229d7d5f086265eed3c67f; final head: 43b605dc99d6ba5520922a25f5d3ceb2ba666c44.

Addressed ClawSweeper’s P2: context capture and the synthetic terminal-provider-error gate now use the same commentary-aware classifier. Matching is restricted to the current user turn and exact whole commentary messages; prior-turn text and substring collisions cannot hide a composed answer. The tool-warning gate remains blank-text-only; settlement, cancellation, async work, delivered replies/media, explicit silence, refusals, and structured errors retain their existing guards.

Regression proof uses real attempt-result projection through terminal preparation and isolated finalization. Four cases failed before repair with not-attempted and pass afterward: thrown versus assistant-reported truncated streams, each with a returned summary or empty-finalizer honest fallback. Separate historical-text and current-commentary-substring regressions also failed before their repairs. Finalization requests keep tools disabled and retain the settled attempt.

Validation:

  • 774 focused tests passed: attempt-result (37), terminal-resolution (48), settled-turn-finalization (26), provider-error (19), stream-capture integration (5), and failover corpus (639).
  • node scripts/run-vitest.mjs on those six files; final affected scopes rerun after refinements.
  • Targeted node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json: 0 warnings/errors; formatting and git diff --check clean.
  • Conflict markers, max-lines and assertion-safety ratchets passed.
  • Fresh autoreview of the complete staged candidate through P2: scoped-clean, no accepted/actionable findings.
  • Follow-up production delta: -3 lines; tests/test support: +98 lines. No new config, schema, dependency or protocol surfaces.

Proof limitations: no new live Telegram/provider run. Testbox warmup was blocked by missing host authentication. Local full changed checks hit the pinned pnpm package-age restriction; standalone typechecking rejected shared dependency links. Neither safeguard was changed. Exact-head hosted CI subsequently passed on 43b605dc99d6ba5520922a25f5d3ceb2ba666c44: run 34055207990, including the required openclaw/ci-gate.

Related work (do not close as duplicates)

These overlap recovery, GLM, or truncated streams, but they do not own this completions finish_reason classification gap:

No existing open PR classifies Stream ended without finish_reason.

Test plan

  • Corpus classifies Stream ended without finish_reason as timeout and still leaves opencode-go stream ended without a terminal event unclassified
  • Settled-turn context is captured for that truncated stream after tools
  • Pre-tool commentary does not block recovery; unattributed or post-tool visible text still does
  • Auth/quota/policy and non-prompt sources still omit context
  • CI on final head 43b605dc99d6ba5520922a25f5d3ceb2ba666c44 (run 34055207990; required openclaw/ci-gate passed)

CI and review follow-up

ClawSweeper refreshed again at 19:38 UTC on September 6, 2026 for exact final head 43b605dc99d6ba5520922a25f5d3ceb2ba666c44: ready for maintainer review, no actionable findings, no before-merge items. The test-only optional-entry narrowing correction (toolAssistant?.role) fixes the TypeScript failure in earlier CI run 34054819853, job 101544853652. Its 26-test file passes after correction. Final-head CI run 34055207990 completed successfully, including required openclaw/ci-gate job 101546748326. PR remains open and unmerged for the maintainer.

Worked on by:

… failure

OpenCode Go openai-completions can close an SSE after settled tools without
finish_reason. Classify that as an incomplete assistant stream and keep
pre-tool commentary from blocking settled-turn recovery.
@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@VACInc
VACInc marked this pull request as ready for review September 6, 2026 18:33
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Sep 6, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 6, 2026
@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 6, 2026, 3:38 PM ET / 19:38 UTC.

ClawSweeper review

What this changes

Recognizes truncated completions streams as retryable failures and allows existing tool-free summary recovery when completed tools were preceded only by commentary.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: current main and v2026.9.2 still miss the completions-stream classification. The earlier finalization-gate finding is addressed, and no new blocking defect was found.

Priority: P1
Reviewed head: 43b605dc99d6ba5520922a25f5d3ceb2ba666c44

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level repair with meaningful regression coverage and no remaining actionable finding.
Proof confidence 🌊 off-meta tidepool Not applicable: The MEMBER-authored PR is exempt from the external-contributor proof gate. Its captured incident establishes the failure, while mocked finalization tests exercise the repaired owners; no after-fix real provider run is claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The MEMBER-authored PR is exempt from the external-contributor proof gate. Its captured incident establishes the failure, while mocked finalization tests exercise the repaired owners; no after-fix real provider run is claimed.
Evidence reviewed 10 items Current main still needs the repair: Current main accepts only transient network errors for settled-turn context and rejects all nonempty subscription text, including pre-tool commentary.
Latest release lacks the classification: The supplied latest release retains the pattern requiring 'without a terminal finish reason'; it does not match the completions producer's underscore form.
Authoritative transport contract: The repository-owned completions transport throws 'Stream ended without finish_reason' after cancellation checking when its terminal contract is unmet. This is the concrete producer behind the new classification; the changed behavior does not depend on the separate Codex implementation.
Findings None None.
Security None None.

How this fits together

The embedded agent runner turns provider responses and completed tool results into a final reply. Its recovery gates distinguish an unfinished answer from already-delivered output before requesting a tool-free summary.

flowchart TD
  A[Provider stream ends early] --> B[Classify incomplete response]
  B --> C{Tools completed?}
  C -->|No| D[Existing replay-safe retry policy]
  C -->|Yes| E[Check answer and settlement guards]
  E --> F[Tool-free finalization]
  F --> G[Summary or honest fallback]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +71, Tests +178. Total +249 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 5 82 11 +71
Tests 6 181 3 +178
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 263 14 +249

Review metrics

Metric Value Why it matters
Production and regression coverage Production net +62 lines; tests and test support net +187 lines Production growth implements a shared commentary classifier used by both recovery gates, with regression coverage for their combined behavior.

Technical review

Best possible solution:

Keep incomplete-stream handling in the shared classifier and reuse bounded, tool-free finalization while preserving existing settlement and delivery guards.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: an incomplete completions response emits an error that main does not classify, and pre-tool commentary independently blocks recovery context. No runtime reproduction was executed in this read-only review.

Is this the best way to solve the issue?

Yes. The patch repairs the existing classification and both recovery gates without replaying completed tools, adding settings, or changing the transport's terminal contract.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 62fca0de772f.

Labels

Label justifications:

  • P1: The reported live workflow loses its final answer after completed tools when a completions stream ends prematurely.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The MEMBER-authored PR is exempt from the external-contributor proof gate. Its captured incident establishes the failure, while mocked finalization tests exercise the repaired owners; no after-fix real provider run is claimed.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • VACInc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Heming Zeng: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-09-06T18:40:13.599Z sha 2ed2bcf :: needs changes before merge. :: [P2] Carry commentary-aware recovery through the finalization payload gate
  • reviewed 2026-09-06T19:30:24.887Z sha af5690c :: needs maintainer review before merge. :: none

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

Addressed the downstream finalization-gate finding in af5690c. Shared current-turn, exact-message commentary classification now reaches terminal preparation/finalization. Four full-path regressions and two attribution edge cases were reproduced failing before repair; 774 focused tests pass, targeted lint is clean, and fresh complete-candidate autoreview is scoped-clean through P2. PR Evidence now records commands, scope, production/test delta, and the remaining hosted-CI/environment limitations.

Please review only; do not merge.

@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 6, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 7, 2026
…eneric agent failure (openclaw#140367)

* fix: truncated completions streams after tools report a generic agent failure

OpenCode Go openai-completions can close an SSE after settled tools without
finish_reason. Classify that as an incomplete assistant stream and keep
pre-tool commentary from blocking settled-turn recovery.

* fix(agents): complete post-tool recovery after commentary

* test(agents): narrow optional finalization fixture entry

Worked on by:
- @VACInc

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: VACInc <[email protected]>
Co-authored-by: roboclaw-bot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants