Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8186: treat process exit as terminal signal on OpenCode 2.x (#9463)

Multica Eve76dfd4a58b7b
diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.go
index 16ea983470..f647f19040 100644
--- a/server/pkg/agent/opencode.go
+++ b/server/pkg/agent/opencode.go
@@ -481,6 +481,10 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
stepProducedOutput := false // current step emitted text, a tool call, or reported usage
lastStepVoid := false // the most recently closed step produced nothing at all
+ // exitIsTerminal: on 2.x the process outcome, not step bracketing, is the
+ // terminal signal. See the EOF check below for why.
+ exitIsTerminal := opencodeUsesV2Contract(b.cfg)
+
scanner := newAgentStreamScanner(r)
for scanner.Scan() {
@@ -506,10 +510,20 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
b.handleTextEvent(event, ch, &output)
if event.Part.Text != "" {
stepProducedOutput = true
+ // On 2.x the step this text belongs to may never close, so the
+ // void-step guard would otherwise keep judging the run by an
+ // earlier empty step it already recovered from. 1.x still waits
+ // for that step's step_finish to clear the flag.
+ if exitIsTerminal {
+ lastStepVoid = false
+ }
}
case "tool_use":
b.handleToolUseEvent(event, ch)
stepProducedOutput = true
+ if exitIsTerminal {
+ lastStepVoid = false // same recovery rule as text above
+ }
if event.Part.Metadata == nil || !event.Part.Metadata.ProviderExecuted {
stepHasContinuationTool = true
}
@@ -564,14 +578,30 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
// all means the run did not finish: its provider stream died and
// `opencode run` exited without emitting an error event. Fail closed on
// that structural evidence rather than reporting a false-green completion.
+ //
+ // OpenCode 2.x changes which of these shapes are evidence. Its CLI stops
+ // consuming step events as soon as the session settles, so the final step's
+ // step_finish is routinely never written (GH #8892, #9456): a completed
+ // text-only turn arrives as `step_start, text` → EOF, and a tool turn can
+ // end as `…, step_finish(tool-calls), text` → EOF with no new step_start.
+ // At the same time 2.x no longer exits quietly on a dead provider stream: a
+ // reset, truncated or empty stream surfaces an `error` event and a non-zero
+ // exit. So on 2.x the process outcome is the terminal signal — the caller
+ // already fails a non-zero exit, a cancellation/timeout and a failed prompt
+ // write, and error events / scanner errors fail it here. Only the two
+ // step-bracketing guards are waived; the void-step guard still applies,
+ // because a step that actually closed with nothing in it is no less dead
+ // on 2.x — unless later text or a tool call shows the run recovered from
+ // it (cleared in the loop above). 1.x and custom runtimes keep every guard
+ // unchanged.
noTerminalSignal := false
if finalStatus == "completed" {
switch {
- case openStep:
+ case openStep && !exitIsTerminal:
finalStatus = "failed"
finalError = "opencode stream ended without a terminal signal (step still open at EOF)"
noTerminalSignal = true
- case awaitingContinuation:
+ case awaitingContinuation && !exitIsTerminal:
finalStatus = "failed"
finalError = "opencode stream ended without a terminal signal (last step required a continuation that never started)"
noTerminalSignal = true
@@ -583,13 +613,17 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
}
return eventResult{
- status: finalStatus,
- errMsg: finalError,
- output: output.String(),
- sessionID: sessionID,
- usage: usage,
- noTerminalSignal: noTerminalSignal,
- sawTerminalSignal: sawStepFinish && !noTerminalSignal,
+ status: finalStatus,
+ errMsg: finalError,
+ output: output.String(),
+ sessionID: sessionID,
+ usage: usage,
+ noTerminalSignal: noTerminalSignal,
+ // On 2.x a step_finish proves only that an intermediate step closed —
+ // the final one routinely never reports — so the stream never carries
+ // positive proof of completion there, and a failed prompt write must
+ // keep failing the run (Execute keys that on this field).
+ sawTerminalSignal: sawStepFinish && !noTerminalSignal && !exitIsTerminal,
}
}
@@ -829,9 +863,16 @@ type opencodeToolState struct {
}
// opencodeError represents an error event from opencode.
+//
+// 1.x reports `{"name": …, "data": {"message": …}}`; 2.x reports a flat
+// `{"type": "provider.invalid-output", "message": …}`. Both are decoded so a
+// 2.x failure surfaces its real cause instead of "unknown opencode error".
type opencodeError struct {
Name string `json:"name,omitempty"`
Data *opencodeErrData `json:"data,omitempty"`
+ // 2.x shape.
+ Type string `json:"type,omitempty"`
+ Msg string `json:"message,omitempty"`
}
// Message returns the human-readable error message.
@@ -839,10 +880,16 @@ func (e *opencodeError) Message() string {
if e.Data != nil && e.Data.Message != "" {
return e.Data.Message
}
+ if e.Msg != "" {
+ if e.Type != "" {
+ return e.Type + ": " + e.Msg
+ }
+ return e.Msg
+ }
if e.Name != "" {
return e.Name
}
- return ""
+ return e.Type
}
type opencodeErrData struct {
diff --git a/server/pkg/agent/opencode_v2_terminal_test.go b/server/pkg/agent/opencode_v2_terminal_test.go
new file mode 100644
index 0000000000..627e3f7c16
--- /dev/null
+++ b/server/pkg/agent/opencode_v2_terminal_test.go
@@ -0,0 +1,202 @@
+package agent
+
+import (
+ "log/slog"
+ "strings"
+ "testing"
+)
+
+// Stream shapes observed from real OpenCode 2.x runs (GH #8892, #9456, and the
+// captures in #8897 / #9437). 2.x stops consuming step events once the session
+// settles, so the final step_finish is routinely missing even though the turn
+// completed and the CLI exits 0. On 2.x the process outcome is the terminal
+// signal; these tests pin the stream half of that contract.
+const (
+ v2TermStepStart = `{"type":"step_start","sessionID":"ses_v2","part":{"type":"step-start"}}`
+ v2TermText = `{"type":"text","sessionID":"ses_v2","part":{"type":"text","text":"DONE","time":{"start":1,"end":2}}}`
+ v2TermToolUse = `{"type":"tool_use","sessionID":"ses_v2","part":{"type":"tool","tool":"write","callID":"call_1","state":{"status":"completed","input":{"path":"probe.txt"},"output":"ok"}}}`
+ v2TermStepFinishTools = `{"type":"step_finish","sessionID":"ses_v2","part":{"type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":10585,"output":69,"reasoning":0,"cache":{"read":0,"write":0}}}}`
+ v2TermStepFinishVoid = `{"type":"step_finish","sessionID":"ses_v2","part":{"type":"step-finish","reason":"unknown","cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}}}}`
+ v2TermErrorInvalidOut = `{"type":"error","sessionID":"ses_v2","error":{"type":"provider.invalid-output","message":"stream ended without finish_reason"}}`
+ v2TermErrorTypeOnly = `{"type":"error","sessionID":"ses_v2","error":{"type":"provider.invalid-output"}}`
+ v1TermErrorNameAndData = `{"type":"error","sessionID":"ses_v1","error":{"name":"APIError","data":{"message":"rate limited"}}}`
+)
+
+func v2TermConfig() Config {
+ return Config{Logger: slog.Default(), BuiltinRuntime: true, CLIVersion: "opencode v2.1.3"}
+}
+
+func runV2TermStream(t *testing.T, cfg Config, lines ...string) eventResult {
+ t.Helper()
+ b := &opencodeBackend{cfg: cfg}
+ ch := make(chan Message, 256)
+ defer close(ch)
+ return b.processEvents(strings.NewReader(strings.Join(lines, "\n")), ch)
+}
+
+// TestOpencodeV2MissingFinalStepFinishCompletes covers every real 2.x shape
+// that ends without a closing step_finish. None of them may fail on their own.
+func TestOpencodeV2MissingFinalStepFinishCompletes(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ lines []string
+ wantInput int64
+ }{
+ {"text-only step left open", []string{v2TermStepStart, v2TermText}, 0},
+ {"bare text without step_start", []string{v2TermText}, 0},
+ {"tool step closed then text without new step_start",
+ []string{v2TermStepStart, v2TermToolUse, v2TermStepFinishTools, v2TermText}, 10585},
+ {"tool step closed then final text step left open",
+ []string{v2TermStepStart, v2TermToolUse, v2TermStepFinishTools, v2TermStepStart, v2TermText}, 10585},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ res := runV2TermStream(t, v2TermConfig(), tc.lines...)
+ if res.status != "completed" {
+ t.Fatalf("status = %q (err %q), want completed", res.status, res.errMsg)
+ }
+ if res.output != "DONE" {
+ t.Fatalf("output = %q, want the streamed reply preserved", res.output)
+ }
+ if res.noTerminalSignal {
+ t.Fatal("noTerminalSignal = true, want false: on 2.x the process exit is the terminal signal")
+ }
+ // Usage from step_finish events that did arrive is still counted, once.
+ if res.usage.InputTokens != tc.wantInput {
+ t.Fatalf("input tokens = %d, want %d", res.usage.InputTokens, tc.wantInput)
+ }
+ })
+ }
+}
+
+// TestOpencodeV2StillFailsClosed pins what the 2.x relaxation must not cover.
+func TestOpencodeV2StillFailsClosed(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ lines []string
+ wantErr string
+ }{
+ {"error event", []string{v2TermStepStart, v2TermText, v2TermErrorInvalidOut},
+ "provider.invalid-output: stream ended without finish_reason"},
+ {"error event with type only", []string{v2TermStepStart, v2TermErrorTypeOnly},
+ "provider.invalid-output"},
+ {"closed void step", []string{v2TermStepStart, v2TermStepFinishVoid}, "empty step"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ res := runV2TermStream(t, v2TermConfig(), tc.lines...)
+ if res.status != "failed" {
+ t.Fatalf("status = %q, want failed", res.status)
+ }
+ if !strings.Contains(res.errMsg, tc.wantErr) {
+ t.Fatalf("errMsg = %q, want it to contain %q", res.errMsg, tc.wantErr)
+ }
+ if res.sawTerminalSignal {
+ t.Fatal("sawTerminalSignal = true on a failed run")
+ }
+ })
+ }
+}
+
+// TestOpencodeV1AndCustomKeepStepBracketing guards that only built-in 2.x
+// runtimes get the relaxation: 1.x and custom runtimes still fail the same
+// shapes closed (#5233).
+func TestOpencodeV1AndCustomKeepStepBracketing(t *testing.T) {
+ t.Parallel()
+
+ cfgs := map[string]Config{
+ "builtin 1.x": {Logger: slog.Default(), BuiltinRuntime: true, CLIVersion: "1.18.32"},
+ "custom 2.x": {Logger: slog.Default(), BuiltinRuntime: false, CLIVersion: "opencode v2.1.3"},
+ "unknown version": {Logger: slog.Default(), BuiltinRuntime: true},
+ }
+ shapes := map[string][]string{
+ "open step": {v2TermStepStart, v2TermText},
+ "continuation not seen": {v2TermStepStart, v2TermToolUse, v2TermStepFinishTools, v2TermText},
+ }
+ for cfgName, cfg := range cfgs {
+ for shapeName, lines := range shapes {
+ cfg, lines := cfg, lines
+ t.Run(cfgName+"/"+shapeName, func(t *testing.T) {
+ t.Parallel()
+ res := runV2TermStream(t, cfg, lines...)
+ if res.status != "failed" || !res.noTerminalSignal {
+ t.Fatalf("status = %q noTerminalSignal = %v, want failed closed", res.status, res.noTerminalSignal)
+ }
+ if !strings.Contains(res.errMsg, "terminal signal") {
+ t.Fatalf("errMsg = %q, want the terminal-signal diagnosis", res.errMsg)
+ }
+ })
+ }
+ }
+}
+
+// TestOpencodeErrorMessageShapes pins decoding of both majors' error payloads.
+func TestOpencodeErrorMessageShapes(t *testing.T) {
+ t.Parallel()
+
+ res := runV2TermStream(t, Config{Logger: slog.Default()}, v1TermErrorNameAndData)
+ if res.status != "failed" || res.errMsg != "rate limited" {
+ t.Fatalf("1.x error: status = %q errMsg = %q, want failed / rate limited", res.status, res.errMsg)
+ }
+}
+
+// TestOpencodeV2RecoveredVoidStepCompletes: a void step the run recovers from
+// must not fail a 2.x run just because the recovering step never reports its
+// step_finish (review on #9463). Mirrors the 1.x
+// TestOpencodeProcessEventsEmptyStepMidRunRecovers for the 2.x stream shape.
+func TestOpencodeV2RecoveredVoidStepCompletes(t *testing.T) {
+ t.Parallel()
+
+ cases := map[string][]string{
+ "new step_start then text": {v2TermStepStart, v2TermStepFinishVoid, v2TermStepStart, v2TermText},
+ "bare text after void": {v2TermStepStart, v2TermStepFinishVoid, v2TermText},
+ "tool after void": {v2TermStepStart, v2TermStepFinishVoid, v2TermStepStart, v2TermToolUse},
+ }
+ for name, lines := range cases {
+ lines := lines
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+ res := runV2TermStream(t, v2TermConfig(), lines...)
+ if res.status != "completed" {
+ t.Fatalf("status = %q (err %q), want completed after recovery", res.status, res.errMsg)
+ }
+ })
+ }
+
+ // A void step that is still the last thing the stream saw keeps failing,
+ // even after an open step_start with nothing in it.
+ res := runV2TermStream(t, v2TermConfig(), v2TermStepStart, v2TermStepFinishVoid, v2TermStepStart)
+ if res.status != "failed" || !strings.Contains(res.errMsg, "empty step") {
+ t.Fatalf("void then empty open step: status = %q errMsg = %q, want empty-step failure", res.status, res.errMsg)
+ }
+}
+
+// TestOpencodeV1VoidStepThenBareTextStillFails pins that the recovery rule is
+// 2.x-only: on 1.x a recovering step must still close with step_finish.
+func TestOpencodeV1VoidStepThenBareTextStillFails(t *testing.T) {
+ t.Parallel()
+
+ cfg := Config{Logger: slog.Default(), BuiltinRuntime: true, CLIVersion: "1.18.32"}
+ res := runV2TermStream(t, cfg, v2TermStepStart, v2TermStepFinishVoid, v2TermText)
+ if res.status != "failed" || !strings.Contains(res.errMsg, "empty step") {
+ t.Fatalf("status = %q errMsg = %q, want 1.x empty-step failure unchanged", res.status, res.errMsg)
+ }
+}
+
+// TestOpencodeV2NeverClaimsStreamLevelCompletion: on 2.x an intermediate
+// step_finish is not proof the run finished, so sawTerminalSignal stays false
+// and Execute keeps failing a broken prompt write.
+func TestOpencodeV2NeverClaimsStreamLevelCompletion(t *testing.T) {
+ t.Parallel()
+
+ res := runV2TermStream(t, v2TermConfig(), v2TermStepStart, v2TermToolUse, v2TermStepFinishTools, v2TermText)
+ if res.status != "completed" || res.sawTerminalSignal {
+ t.Fatalf("status = %q sawTerminalSignal = %v, want completed without stream-level proof", res.status, res.sawTerminalSignal)
+ }
+}
diff --git a/server/pkg/agent/opencode_v2_terminal_unix_test.go b/server/pkg/agent/opencode_v2_terminal_unix_test.go
new file mode 100644
index 0000000000..4d6c21f460
--- /dev/null
+++ b/server/pkg/agent/opencode_v2_terminal_unix_test.go
@@ -0,0 +1,119 @@
+//go:build !windows
+
+package agent
+
+import (
+ "context"
+ "log/slog"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestOpencodeV2ExecuteExitIsTerminal drives the real Execute path against a
+// fake 2.x CLI: the stream half (processEvents) waives the missing final
+// step_finish, and the process half must still decide the outcome.
+func TestOpencodeV2ExecuteExitIsTerminal(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ lines []string
+ exitCode int
+ wantStatus string
+ wantErr string
+ }{
+ {"open text step, exit 0", []string{v2TermStepStart, v2TermText}, 0, "completed", ""},
+ {"tool then bare text, exit 0",
+ []string{v2TermStepStart, v2TermToolUse, v2TermStepFinishTools, v2TermText}, 0, "completed", ""},
+ {"error event, exit 1", []string{v2TermStepStart, v2TermText, v2TermErrorInvalidOut}, 1, "failed",
+ "provider.invalid-output"},
+ {"open step, no error, exit 1", []string{v2TermStepStart, v2TermText}, 1, "failed", "exited with error"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ var script strings.Builder
+ script.WriteString("#!/bin/sh\ncat > /dev/null\n")
+ for _, l := range tc.lines {
+ script.WriteString("printf '%s\\n' '" + l + "'\n")
+ }
+ script.WriteString("exit " + string(rune('0'+tc.exitCode)) + "\n")
+
+ fakePath := filepath.Join(t.TempDir(), "opencode")
+ writeTestExecutable(t, fakePath, []byte(script.String()))
+
+ backend, err := New("opencode", Config{
+ ExecutablePath: fakePath,
+ CLIVersion: "opencode v2.1.3",
+ BuiltinRuntime: true,
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new opencode backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt", ExecOptions{Cwd: t.TempDir(), Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ res := <-session.Result
+
+ if res.Status != tc.wantStatus {
+ t.Fatalf("status = %q (err %q), want %q", res.Status, res.Error, tc.wantStatus)
+ }
+ if !strings.Contains(res.Error, tc.wantErr) {
+ t.Fatalf("error = %q, want it to contain %q", res.Error, tc.wantErr)
+ }
+ if tc.wantStatus == "completed" && res.Output != "DONE" {
+ t.Fatalf("output = %q, want DONE", res.Output)
+ }
+ })
+ }
+}
+
+// TestOpencodeV2BrokenPromptWriteFails: a 2.x CLI that closes stdin before the
+// prompt is delivered, then streams a tool step plus final text and exits 0,
+// must fail on the prompt write (review on #9463). The prompt is far larger
+// than the pipe buffer so the write cannot complete.
+func TestOpencodeV2BrokenPromptWriteFails(t *testing.T) {
+ t.Parallel()
+
+ var script strings.Builder
+ script.WriteString("#!/bin/sh\nexec 0<&-\n")
+ for _, l := range []string{v2TermStepStart, v2TermToolUse, v2TermStepFinishTools, v2TermText} {
+ script.WriteString("printf '%s\\n' '" + l + "'\n")
+ }
+ script.WriteString("exit 0\n")
+ fakePath := filepath.Join(t.TempDir(), "opencode")
+ writeTestExecutable(t, fakePath, []byte(script.String()))
+
+ cfg := v2TermConfig()
+ cfg.ExecutablePath = fakePath
+ backend, err := New("opencode", cfg)
+ if err != nil {
+ t.Fatalf("new opencode backend: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, strings.Repeat("undelivered prompt\n", 100000), ExecOptions{Cwd: t.TempDir(), Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ res := <-session.Result
+ if res.Status != "failed" || !strings.Contains(res.Error, "prompt write failed") {
+ t.Fatalf("status = %q error = %q, want failed prompt delivery", res.Status, res.Error)
+ }
+}