Skip to content

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

Go

feat(agent): surface agent CLI stderr tail in failure messages (#1674)

songlei6f04a6d26b93
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index d4d5941feb..82cdd4e25a 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -83,7 +83,13 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
stdin = nil
}
}
- cmd.Stderr = newLogWriter(b.cfg.Logger, "[claude:stderr] ")
+ // Capture stderr into both the daemon log (as before) and a bounded tail
+ // buffer so we can include the last few KB in Result.Error when claude
+ // exits unexpectedly. Without the tail, an exit-code-only failure looks
+ // like "claude exited with error: exit status 3" — which is useless for
+ // root-causing V8 aborts, Bun panics, or any other CLI-side crash.
+ stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[claude:stderr] "), agentStderrTailBytes)
+ cmd.Stderr = stderrBuf
if err := cmd.Start(); err != nil {
closeStdin()
@@ -188,6 +194,15 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
finalError = fmt.Sprintf("claude exited with error: %v", exitErr)
}
+ // cmd.Wait() has returned — os/exec's stderr copy goroutine has
+ // observed every byte claude wrote to stderr before exiting, so
+ // stderrBuf.Tail() is safe to sample now. Attach the tail to any
+ // non-empty failure message; callers upstream surface this as the
+ // task's error field, which is the only place users see it.
+ if finalError != "" {
+ finalError = withAgentStderr(finalError, "claude", stderrBuf.Tail())
+ }
+
b.cfg.Logger.Info("claude finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed")
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 0ad4b24cf9..d430bd89ea 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -5,7 +5,6 @@ import (
"context"
"encoding/json"
"fmt"
- "io"
"log/slog"
"os"
"os/exec"
@@ -24,59 +23,10 @@ var codexBlockedArgs = map[string]blockedArgMode{
// codexStderrTailBytes bounds the stderr tail captured for inclusion in
// error messages when codex exits before the JSON-RPC handshake (e.g. the
// user supplied a custom_args flag that the `app-server` subcommand
-// rejects). Large enough to contain typical CLI error lines, small enough
-// to stay sensible inside a task-level Result.Error string.
+// rejects). Kept as its own constant so bumping codex independently of
+// other agents stays easy if codex starts shipping longer failure traces.
const codexStderrTailBytes = 2048
-// stderrTail forwards writes to an inner writer (typically the daemon's
-// log) while also retaining a bounded tail of the bytes written. Consumers
-// call Tail() to include that context in error messages when the codex
-// process exits before we can read a structured JSON-RPC error — otherwise
-// all the user sees is "codex process exited", with the real reason stuck
-// in daemon logs.
-type stderrTail struct {
- inner io.Writer
- max int
-
- mu sync.Mutex
- buf []byte
-}
-
-func newStderrTail(inner io.Writer, max int) *stderrTail {
- return &stderrTail{inner: inner, max: max}
-}
-
-func (s *stderrTail) Write(p []byte) (int, error) {
- if _, err := s.inner.Write(p); err != nil {
- return 0, err
- }
- s.mu.Lock()
- s.buf = append(s.buf, p...)
- if len(s.buf) > s.max {
- s.buf = s.buf[len(s.buf)-s.max:]
- }
- s.mu.Unlock()
- return len(p), nil
-}
-
-// Tail returns the captured stderr with leading/trailing whitespace
-// trimmed; empty string means nothing was written or everything was
-// whitespace.
-func (s *stderrTail) Tail() string {
- s.mu.Lock()
- defer s.mu.Unlock()
- return strings.TrimSpace(string(s.buf))
-}
-
-// withCodexStderr appends a stderr tail hint to an error message when
-// non-empty, otherwise returns msg unchanged.
-func withCodexStderr(msg, tail string) string {
- if tail == "" {
- return msg
- }
- return msg + "; codex stderr: " + tail
-}
-
// codexBackend implements Backend by spawning `codex app-server --listen stdio://`
// and communicating via JSON-RPC 2.0 over stdin/stdout.
type codexBackend struct {
@@ -218,7 +168,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
if err != nil {
drainAndWait() // flush os/exec stderr goroutine before sampling Tail
finalStatus = "failed"
- finalError = withCodexStderr(fmt.Sprintf("codex initialize failed: %v", err), stderrBuf.Tail())
+ finalError = withAgentStderr(fmt.Sprintf("codex initialize failed: %v", err), "codex", stderrBuf.Tail())
resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
return
}
@@ -231,7 +181,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
if err != nil {
drainAndWait() // flush os/exec stderr goroutine before sampling Tail
finalStatus = "failed"
- finalError = withCodexStderr(err.Error(), stderrBuf.Tail())
+ finalError = withAgentStderr(err.Error(), "codex", stderrBuf.Tail())
resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
return
}
@@ -252,7 +202,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
if err != nil {
drainAndWait() // flush os/exec stderr goroutine before sampling Tail
finalStatus = "failed"
- finalError = withCodexStderr(fmt.Sprintf("codex turn/start failed: %v", err), stderrBuf.Tail())
+ finalError = withAgentStderr(fmt.Sprintf("codex turn/start failed: %v", err), "codex", stderrBuf.Tail())
resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
return
}
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index f379c7fa38..686889df90 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -1011,13 +1011,13 @@ func TestCodexExecuteSurfacesStderrWhenChildExitsEarly(t *testing.T) {
}
}
-func TestWithCodexStderrAppendsHint(t *testing.T) {
+func TestWithAgentStderrAppendsHint(t *testing.T) {
t.Parallel()
- if got := withCodexStderr("codex initialize failed: process exited", ""); got != "codex initialize failed: process exited" {
+ if got := withAgentStderr("codex initialize failed: process exited", "codex", ""); got != "codex initialize failed: process exited" {
t.Errorf("empty tail should not modify msg, got %q", got)
}
- msg := withCodexStderr("codex initialize failed: process exited", "unexpected argument '-m' found")
+ msg := withAgentStderr("codex initialize failed: process exited", "codex", "unexpected argument '-m' found")
want := "codex initialize failed: process exited; codex stderr: unexpected argument '-m' found"
if msg != want {
t.Errorf("got %q, want %q", msg, want)
diff --git a/server/pkg/agent/stderr_tail.go b/server/pkg/agent/stderr_tail.go
new file mode 100644
index 0000000000..b123922920
--- /dev/null
+++ b/server/pkg/agent/stderr_tail.go
@@ -0,0 +1,72 @@
+package agent
+
+import (
+ "io"
+ "strings"
+ "sync"
+)
+
+// agentStderrTailBytes bounds the stderr tail captured for inclusion in
+// error messages when an agent CLI exits before emitting a structured
+// error (e.g. V8 abort on Windows, Bun panic, OOM). Large enough to
+// contain typical CLI error lines, small enough to stay sensible inside
+// a task-level Result.Error string.
+const agentStderrTailBytes = 2048
+
+// stderrTail forwards writes to an inner writer (typically the daemon's
+// log) while also retaining a bounded tail of the bytes written. Consumers
+// call Tail() to include that context in error messages when the agent
+// process exits before it emits a structured error — otherwise all the
+// user sees is "exit status N", with the real reason stuck in daemon logs.
+//
+// All backends that supervise a child CLI process should wire their
+// cmd.Stderr through this type, and on failure include Tail() in
+// Result.Error via withAgentStderr. That makes root-causing CLI crashes
+// possible without having to crawl the daemon host's log files.
+type stderrTail struct {
+ inner io.Writer
+ max int
+
+ mu sync.Mutex
+ buf []byte
+}
+
+func newStderrTail(inner io.Writer, max int) *stderrTail {
+ if max <= 0 {
+ max = agentStderrTailBytes
+ }
+ return &stderrTail{inner: inner, max: max}
+}
+
+func (s *stderrTail) Write(p []byte) (int, error) {
+ if _, err := s.inner.Write(p); err != nil {
+ return 0, err
+ }
+ s.mu.Lock()
+ s.buf = append(s.buf, p...)
+ if len(s.buf) > s.max {
+ s.buf = s.buf[len(s.buf)-s.max:]
+ }
+ s.mu.Unlock()
+ return len(p), nil
+}
+
+// Tail returns the captured stderr with leading/trailing whitespace
+// trimmed; empty string means nothing was written or everything was
+// whitespace.
+func (s *stderrTail) Tail() string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return strings.TrimSpace(string(s.buf))
+}
+
+// withAgentStderr appends a stderr tail hint to an error message when
+// non-empty, otherwise returns msg unchanged. The tail is prefixed with a
+// short label so the composed string stays readable even when the original
+// msg is already verbose.
+func withAgentStderr(msg, label, tail string) string {
+ if tail == "" {
+ return msg
+ }
+ return msg + "; " + label + " stderr: " + tail
+}