Skip to content

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

Go

MUL-5154: fix(agent): surface Kimi provider API errors (#5785)

Rusty Raven2e424e06a1d9
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.go
index ed560210fc..c46f7a8b36 100644
--- a/server/pkg/agent/hermes.go
+++ b/server/pkg/agent/hermes.go
@@ -18,6 +18,8 @@ import (
"sync"
"sync/atomic"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
)
// hermesBlockedArgs are flags hardcoded by the daemon that must not be
@@ -715,6 +717,9 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
<-readerDone
<-stderrDone
}
+ // Flush any partial stderr line that arrived without a trailing '\n'
+ // before the pipe closed (P1 from multica#5785 review Aug 10).
+ providerErr.Finalize()
streamingCurrentTurn.Store(false)
finalOutput, providerErrorOutput := deliverable.result()
@@ -761,6 +766,17 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
sessionID = ""
resumeRejected = true
}
+ // A poisoned session history (400 "assistant must not be empty") is
+ // unresumable: every resume replays the identical body and reproduces
+ // the same 400. Signal the daemon to drop the old session so it can
+ // retry fresh via the tools==0 gate instead of re-submitting the broken
+ // transcript indefinitely. Guard on ResumeSessionID so a fresh run that
+ // somehow sees the same fingerprint is not misflagged. This is the
+ // positive backend signal; taskfailure.UnresumableHistory keys off the
+ // surfaced Result.Error string as the backend-agnostic path (#6083).
+ if finalStatus == "failed" && opts.ResumeSessionID != "" && providerErr.isPoisonedHistory() {
+ resumeRejected = true
+ }
// Build usage map.
u := c.accumulatedUsage()
@@ -2732,12 +2748,13 @@ func hermesToolNameFromTitle(title string, kind string) string {
// a successful retry following an early per-attempt warning would be
// wrongly marked as failed.
type acpProviderErrorSniffer struct {
- provider string
- mu sync.Mutex
- remains []byte // buffer for a partial trailing line across writes
- lines []string // captured error lines, bounded
- seen map[string]bool
- terminal bool // sticky: at least one line matched acpTerminalErrorRe
+ provider string
+ kimiStyle bool // true for kimi: enables provider.api_error line detection
+ mu sync.Mutex
+ remains []byte // buffer for a partial trailing line across writes
+ lines []string // captured error lines, bounded
+ seen map[string]bool
+ terminal bool // sticky: at least one line matched acpTerminalErrorRe
// echoJSON tracks an incomplete structured payload from a Python
// INFO/DEBUG root-logger record. The JSON scanner state is persisted
// across Write calls so only actual payload continuations are skipped.
@@ -2755,6 +2772,8 @@ var acpErrorHeaderRe = regexp.MustCompile(`(?:⚠️|❌|\[ERROR\]).*(?:BadReque
// acpErrorDetailRe pulls the most useful single-line messages out of
// the subsequent lines of the error block (the one whose "Error:" or
// "Details:" tag actually spells out what happened).
+// Branches keep \s* so "detail:value" (no space) and "Error: message"
+// (with space) are both matched.
var acpErrorDetailRe = regexp.MustCompile(`(?:Error:|detail:|Details:)\s*(.+)`)
// acpTerminalErrorRe matches markers that only appear when the
@@ -2765,6 +2784,25 @@ var acpErrorDetailRe = regexp.MustCompile(`(?:Error:|detail:|Details:)\s*(.+)`)
// warnings ("(attempt 1/3)") deliberately do NOT match this pattern.
var acpTerminalErrorRe = regexp.MustCompile(`(?:❌|\[ERROR\]|after \d+ retr|Non-retryable|BadRequestError|AuthenticationError)`)
+// kimiProviderApiErrorRe matches kimi-specific "provider.api_error:" lines
+// that do not use the emoji-prefixed format of the shared ACP backends.
+// Scoped to kimiStyle sniffers to avoid false-positive captures when
+// other backends echo provider.api_error text in tool output.
+var kimiProviderApiErrorRe = regexp.MustCompile(`provider\.api_error`)
+
+// kimiTerminalErrorRe classifies kimi client errors (400/401/403) as
+// terminal. 429 (rate-limit) and 408 (timeout) are intentionally excluded:
+// the kimi adapter retries those internally, and a run that ultimately
+// succeeds after retries must stay status=completed.
+var kimiTerminalErrorRe = regexp.MustCompile(`provider\.api_error: (?:400|401|403)`)
+
+// providerApiErrorStatusRe extracts the numeric status code from a kimi
+// "provider.api_error: NNN" line so messageLocked can forward it into the
+// formatted detail string, letting taskfailure.UnresumableHistory detect the
+// 400 fingerprint even when the human-readable detail text is on a separate
+// stderr line (Kimi's two-line format).
+var providerApiErrorStatusRe = regexp.MustCompile(`provider\.api_error: (\d+)`)
+
// acpAgentOutputTerminalRe matches the synthetic agent-text turn that
// hermes-style ACP adapters inject when they exhaust retries against
// the upstream LLM ("API call failed after 3 retries: HTTP 429..."),
@@ -2806,7 +2844,11 @@ const acpMaxErrorLineLen = 4096
// with the given provider name (e.g. "hermes", "kimi") so failure
// strings make it obvious which runtime produced the error.
func newACPProviderErrorSniffer(provider string) *acpProviderErrorSniffer {
- return &acpProviderErrorSniffer{provider: provider, seen: map[string]bool{}}
+ return &acpProviderErrorSniffer{
+ provider: provider,
+ kimiStyle: provider == "kimi",
+ seen: map[string]bool{},
+ }
}
// Write implements io.Writer so the sniffer can sit behind an
@@ -2863,10 +2905,11 @@ func (s *acpProviderErrorSniffer) Write(p []byte) (int, error) {
continue
}
}
- if !(acpErrorHeaderRe.MatchString(line) || acpErrorDetailRe.MatchString(line)) {
+ isKimiErr := s.kimiStyle && kimiProviderApiErrorRe.MatchString(line)
+ if !(acpErrorHeaderRe.MatchString(line) || acpErrorDetailRe.MatchString(line) || isKimiErr) {
continue
}
- if acpTerminalErrorRe.MatchString(line) {
+ if acpTerminalErrorRe.MatchString(line) || (s.kimiStyle && kimiTerminalErrorRe.MatchString(line)) {
s.terminal = true
}
if s.seen[line] {
@@ -2881,6 +2924,23 @@ func (s *acpProviderErrorSniffer) Write(p []byte) (int, error) {
return len(p), nil
}
+// Finalize must be called once after the process stderr pipe has been fully
+// drained (io.Copy returned). It flushes any partial last line that arrived
+// without a trailing newline so it is included in the terminal-error and
+// poisoned-history decisions. Without this, a process that exits after writing
+// "provider.api_error: 400 ..." without a trailing '\n' leaves the sniffer
+// with no captured error, causing the task to land as completed/empty.
+func (s *acpProviderErrorSniffer) Finalize() {
+ s.mu.Lock()
+ remaining := strings.TrimRight(string(s.remains), "\r")
+ s.remains = s.remains[:0]
+ s.mu.Unlock()
+ if remaining == "" {
+ return
+ }
+ _, _ = s.Write([]byte(remaining + "\n"))
+}
+
func (s *acpProviderErrorSniffer) startEchoJSON(payload string) {
payload = strings.TrimSpace(payload)
if payload == "" || (payload[0] != '{' && payload[0] != '[') {
@@ -2962,10 +3022,89 @@ func (s *acpProviderErrorSniffer) terminalMessage() string {
return s.messageLocked()
}
+// isPoisonedHistory reports whether the terminal error indicates a
+// permanently poisoned session history — the provider refused to replay the
+// transcript because a message it already contains has empty content. Resuming
+// the same session replays the identical body and reproduces the same
+// rejection, so the daemon must drop the session pointer and start fresh.
+//
+// This is the positive backend signal that sets Result.ResumeRejected. It
+// delegates to the exact predicate the daemon uses to retire the session
+// (taskfailure.UnresumableHistory) evaluated against the same surfaced message
+// (messageLocked) the daemon will classify. Sharing one predicate is
+// deliberate: the two must never disagree, or the backend would flag a
+// rejection the daemon then declines to act on (or vice versa). It also gives
+// the precision the reviewer asked for — UnresumableHistory requires BOTH an
+// emptiness complaint AND a history-message locator (role 'assistant', "message
+// at position", "messages[N]"), so an unrelated 400 such as "commit message
+// must not be empty" no longer trips ResumeRejected. messageLocked already
+// stitches Kimi's two-line stderr (status header + detail line) into a single
+// string, so the locator and the emptiness token are both visible here.
+func (s *acpProviderErrorSniffer) isPoisonedHistory() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if !s.terminal {
+ return false
+ }
+ return taskfailure.UnresumableHistory(s.messageLocked())
+}
+
// messageLocked is the lock-held implementation shared by message()
// and terminalMessage(). Caller must hold s.mu.
func (s *acpProviderErrorSniffer) messageLocked() string {
prefix := s.provider + " provider error: "
+
+ if s.kimiStyle {
+ // Find the LAST terminal provider.api_error line. Using the last one
+ // ensures a 429 (transient, internally retried) followed by a 400
+ // (definitive failure) always yields the 400 status tag rather than the
+ // earlier 429 "rate limit" noise. The loop does not break on the first
+ // match so a later terminal line always wins.
+ var apiErrTag string
+ apiErrLineIdx := -1
+ for i, line := range s.lines {
+ if kimiTerminalErrorRe.MatchString(line) {
+ if m := providerApiErrorStatusRe.FindStringSubmatch(line); m != nil {
+ apiErrTag = "provider.api_error: " + m[1] + " "
+ apiErrLineIdx = i
+ }
+ }
+ }
+
+ if apiErrLineIdx >= 0 {
+ // Scan for the detail belonging to the terminal line: start at
+ // apiErrLineIdx, not at 0. Starting at 0 would pair a preceding
+ // 429 "rate limit exceeded" detail with the 400 status tag, hiding
+ // the history locator from taskfailure.UnresumableHistory.
+ for i := apiErrLineIdx; i < len(s.lines); i++ {
+ line := s.lines[i]
+ if m := acpErrorDetailRe.FindStringSubmatch(line); m != nil {
+ detail := strings.TrimSpace(m[1])
+ if detail == "" {
+ continue
+ }
+ return acpTruncateError(prefix + apiErrTag + detail)
+ }
+ }
+ // Single-line format: "provider.api_error: 400 <detail>" where the
+ // detail text follows the status code on the same line but is not
+ // captured by acpErrorDetailRe (which requires Error:/detail:/Details:
+ // prefixes). Extract it directly from the header line.
+ headerLine := s.lines[apiErrLineIdx]
+ if loc := providerApiErrorStatusRe.FindStringIndex(headerLine); loc != nil {
+ after := strings.TrimLeft(headerLine[loc[1]:], " ")
+ if after != "" {
+ return acpTruncateError(prefix + apiErrTag + after)
+ }
+ }
+ // Nothing extractable beyond the status; surface the raw header.
+ return acpTruncateError(prefix + headerLine)
+ }
+ }
+
+ // Common path: non-kimi or kimi without a terminal provider.api_error line.
+ // Return the first detail tag, then fall back to the first header line.
for _, line := range s.lines {
if m := acpErrorDetailRe.FindStringSubmatch(line); m != nil {
detail := strings.TrimSpace(m[1])
@@ -2975,7 +3114,7 @@ func (s *acpProviderErrorSniffer) messageLocked() string {
}
}
for _, line := range s.lines {
- if acpErrorHeaderRe.MatchString(line) {
+ if acpErrorHeaderRe.MatchString(line) || (s.kimiStyle && kimiProviderApiErrorRe.MatchString(line)) {
return acpTruncateError(prefix + line)
}
}
diff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.go
index 83c09a8e46..b6129c7c00 100644
--- a/server/pkg/agent/hermes_test.go
+++ b/server/pkg/agent/hermes_test.go
@@ -2434,6 +2434,290 @@ func TestHermesProviderErrorSnifferTerminalNonRetryable(t *testing.T) {
}
}
+// TestACPProviderErrorSnifferKimiApiError covers the kimi-specific error
+// format that was previously invisible to the sniffer, causing tasks to
+// silently complete instead of failing (GitHub multica#5760):
+//
+// error: failed to run prompt: provider.api_error: 400 the message at
+// position 43 with role 'assistant' must not be empty
+//
+// The line has no emoji prefix and uses lowercase "error:", so the original
+// acpErrorHeaderRe / acpErrorDetailRe did not capture it. The fix adds
+// provider.api_error as an additional header match, recognises 4xx codes as
+// terminal, and extracts the error message after "provider.api_error: NNN ".
+func TestACPProviderErrorSnifferKimiApiError(t *testing.T) {
+ t.Parallel()
+
+ stderr := "error: failed to run prompt: provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty\n"
+ s := newACPProviderErrorSniffer("kimi")
+ if _, err := s.Write([]byte(stderr)); err != nil {
+ t.Fatalf("Write: %v", err)
+ }
+
+ msg := s.terminalMessage()
+ if msg == "" {
+ t.Fatal("expected a non-empty terminal message; sniffer did not recognise provider.api_error line")
+ }
+ if !strings.Contains(msg, "must not be empty") {
+ t.Errorf("expected error detail about empty assistant message, got %q", msg)
+ }
+ if !strings.Contains(msg, "kimi") {
+ t.Errorf("expected provider prefix 'kimi' in message, got %q", msg)
+ }
+
+ // promoteACPResultOnProviderError must flip completed→failed so resumed
+ // sessions with a permanently broken history surface as task failures.
+ finalStatus, finalError := promoteACPResultOnProviderError("completed", "", "", s)
+ if finalStatus != "failed" {
+ t.Errorf("status = %q, want %q", finalStatus, "failed")
+ }
+ if !strings.Contains(finalError, "must not be empty") {
+ t.Errorf("error = %q, want it to mention the empty assistant message", finalError)
+ }
+}
+
+// TestACPProviderErrorSnifferKimiApiError5xx verifies that a 5xx
+// provider.api_error (potentially transient) is captured but not classified
+// as terminal, so it only promotes to failed when output is also empty.
+func TestACPProviderErrorSnifferKimiApiError5xx(t *testing.T) {
+ t.Parallel()
+
+ stderr := "error: provider.api_error: 503 upstream temporarily unavailable\n"
+ s := newACPProviderErrorSniffer("kimi")
+ s.Write([]byte(stderr))
+
+ if s.terminalMessage() != "" {
+ t.Error("5xx provider.api_error should not be classified as terminal")
+ }
+ if s.message() == "" {
+ t.Error("5xx provider.api_error should still be captured as a non-terminal error")
+ }
+}
+
+// TestACPProviderErrorSnifferKimiRateLimitNotTerminal verifies that a
+// kimi-style 429 is captured for diagnostic purposes but is NOT marked
+// as terminal. The kimi adapter retries rate-limit errors internally;
+// a run that ultimately succeeds must stay status=completed regardless
+// of how many 429 warnings appeared on stderr during retries.
+func TestACPProviderErrorSnifferKimiRateLimitNotTerminal(t *testing.T) {
+ t.Parallel()
+
+ s := newACPProviderErrorSniffer("kimi")
+ s.Write([]byte("error: failed to run prompt: provider.api_error: 429 rate limit exceeded\n"))
+
+ if msg := s.terminalMessage(); msg != "" {
+ t.Errorf("429 should not be terminal, got %q", msg)
+ }
+ if msg := s.message(); msg == "" {
+ t.Error("429 should still be captured for diagnostics (message() must be non-empty)")
+ }
+
+ // promoteACPResultOnProviderError must leave status=completed when the
+ // adapter ultimately produced a real answer after internal retries.
+ finalStatus, _ := promoteACPResultOnProviderError("completed", "", "here is the answer", s)
+ if finalStatus != "completed" {
+ t.Errorf("status = %q, want completed: 429 + non-empty output must not be promoted to failed", finalStatus)
+ }
+}
+
+// TestACPProviderErrorSnifferPoisonedHistory verifies that the
+// "provider.api_error: 400 … must not be empty" pattern is detected as a
+// poisoned session so the backend can set ResumeRejected=true and the daemon
+// drops the broken session pointer instead of replaying the same bad history.
+func TestACPProviderErrorSnifferPoisonedHistory(t *testing.T) {
+ t.Parallel()
+
+ // Single-line format: 400 + role 'assistant' + must not be empty on the
+ // same line. This is the format emitted by some kimi-cli versions.
+ s := newACPProviderErrorSniffer("kimi")
+ s.Write([]byte("error: failed to run prompt: provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty\n"))
+ if !s.isPoisonedHistory() {
+ t.Fatal("single-line: expected isPoisonedHistory()=true for 400 assistant-empty error")
+ }
+
+ // Two-line format: kimi emits the status on the error header and the
+ // human-readable detail on a separate "detail:" line. isPoisonedHistory
+ // must detect this across lines, not only when both markers are on the
+ // same line.
+ s4 := newACPProviderErrorSniffer("kimi")
+ s4.Write([]byte("error: failed to run prompt: provider.api_error: 400\n"))
+ s4.Write([]byte("detail: messages[43].content: content must not be empty\n"))
+ if !s4.isPoisonedHistory() {
+ t.Fatal("two-line: expected isPoisonedHistory()=true when 400 and must-not-be-empty are on separate lines")
+ }
+
+ // A plain 400 with a different error message is terminal but not a
+ // poisoned history — the session may still be healthy.
+ s2 := newACPProviderErrorSniffer("kimi")
+ s2.Write([]byte("error: failed to run prompt: provider.api_error: 400 invalid model specified\n"))
+ if s2.isPoisonedHistory() {
+ t.Error("plain 400 without must-not-be-empty should not be classified as poisoned history")
+ }
+
+ // "must not be empty" on a detail line paired with a 429 header must
+ // not match — 429 is transient and not provider.api_error: 400.
+ s5 := newACPProviderErrorSniffer("kimi")
+ s5.Write([]byte("⚠️ API call failed after 3 retries: RateLimitError [HTTP 429]\n"))
+ s5.Write([]byte("detail: field must not be empty\n"))
+ if s5.isPoisonedHistory() {
+ t.Error("429 RateLimitError with must-not-be-empty detail should not be classified as poisoned history")
+ }
+}
+
+// TestACPProviderErrorSnifferMessageLockedPreservesAPIErrorStatus verifies
+// that messageLocked forwards the "provider.api_error: NNN" prefix into the
+// formatted output even when the human-readable detail arrives on a separate
+// stderr line. This is the contract classifyPoisonedError relies on.
+func TestACPProviderErrorSnifferMessageLockedPreservesAPIErrorStatus(t *testing.T) {
+ t.Parallel()
+
+ // Two-line format: status on header, detail on next line.
+ s := newACPProviderErrorSniffer("kimi")
+ s.Write([]byte("error: failed to run prompt: provider.api_error: 400\n"))
+ s.Write([]byte("detail: messages[43].content: content must not be empty\n"))
+ msg := s.terminalMessage()
+ if !strings.Contains(msg, "provider.api_error: 400") {
+ t.Errorf("two-line: terminalMessage() should include provider.api_error: 400, got %q", msg)
+ }
+ if !strings.Contains(msg, "must not be empty") {
+ t.Errorf("two-line: terminalMessage() should include the detail text, got %q", msg)
+ }
+
+ // Single-line format: status and detail on the same line.
+ s2 := newACPProviderErrorSniffer("kimi")
+ s2.Write([]byte("error: failed to run prompt: provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty\n"))
+ msg2 := s2.terminalMessage()
+ if !strings.Contains(msg2, "provider.api_error: 400") {
+ t.Errorf("single-line: terminalMessage() should include provider.api_error: 400, got %q", msg2)
+ }
+ if !strings.Contains(msg2, "must not be empty") {
+ t.Errorf("single-line: terminalMessage() should include the detail text, got %q", msg2)
+ }
+}
+
+// TestACPProviderErrorSnifferMixedRetry429Then400 verifies that when a kimi
+// adapter emits a transient 429 (internally retried) followed by a terminal
+// 400 (poisoned history), messageLocked pairs the 400 status tag with the
+// 400's own detail — not with the 429's "rate limit" text. This ensures that
+// taskfailure.UnresumableHistory can see the history locator in the final
+// surfaced error string (GitHub multica#5785 P1 from Aug 10 review).
+func TestACPProviderErrorSnifferMixedRetry429Then400(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ stderrSeq []string
+ wantIn string
+ wantNotIn string
+ }{
+ {
+ name: "single-line 400 after 429",
+ stderrSeq: []string{
+ "error: provider.api_error: 429 rate limit exceeded\n",
+ "error: provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty\n",
+ },
+ wantIn: "must not be empty",
+ wantNotIn: "rate limit",
+ },
+ {
+ name: "two-line 400 after 429",
+ stderrSeq: []string{
+ "error: provider.api_error: 429 rate limit exceeded\n",
+ "error: provider.api_error: 400\n",
+ "detail: messages[43].content: content must not be empty\n",
+ },
+ wantIn: "must not be empty",
+ wantNotIn: "rate limit",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ s := newACPProviderErrorSniffer("kimi")
+ for _, line := range tt.stderrSeq {
+ if _, err := s.Write([]byte(line)); err != nil {
+ t.Fatalf("Write: %v", err)
+ }
+ }
+ msg := s.terminalMessage()
+ if !strings.Contains(msg, "provider.api_error: 400") {
+ t.Errorf("expected provider.api_error: 400 in message, got %q", msg)
+ }
+ if !strings.Contains(msg, tt.wantIn) {
+ t.Errorf("expected %q in message, got %q", tt.wantIn, msg)
+ }
+ if strings.Contains(msg, tt.wantNotIn) {
+ t.Errorf("must not include %q (from 429) in message, got %q", tt.wantNotIn, msg)
+ }
+ if !s.isPoisonedHistory() {
+ t.Error("mixed 429→400 with assistant-empty detail must be classified as poisoned history")
+ }
+ })
+ }
+}
+
+// TestACPProviderErrorSnifferFinalizeFlushesPartialLine verifies that a
+// terminal error written to stderr WITHOUT a trailing newline is still detected
+// after Finalize() is called. Without Finalize(), a process that exits after
+// writing its last line without '\n' leaves the partial line in s.remains and
+// the sniffer reports no error, causing the task to land as completed/empty.
+func TestACPProviderErrorSnifferFinalizeFlushesPartialLine(t *testing.T) {
+ t.Parallel()
+
+ const line = "error: provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty"
+
+ s := newACPProviderErrorSniffer("kimi")
+ // Write without trailing newline — simulates a process that exits without '\n'.
+ if _, err := s.Write([]byte(line)); err != nil {
+ t.Fatalf("Write: %v", err)
+ }
+
+ if msg := s.terminalMessage(); msg != "" {
+ t.Errorf("before Finalize: expected empty terminalMessage (partial line still buffered), got %q", msg)
+ }
+
+ s.Finalize()
+
+ msg := s.terminalMessage()
+ if msg == "" {
+ t.Fatal("after Finalize: expected non-empty terminalMessage for error written without trailing newline")
+ }
+ if !strings.Contains(msg, "must not be empty") {
+ t.Errorf("after Finalize: expected 'must not be empty' in message, got %q", msg)
+ }
+ if !strings.Contains(msg, "provider.api_error: 400") {
+ t.Errorf("after Finalize: expected 'provider.api_error: 400' in message, got %q", msg)
+ }
+}
+
+// TestACPProviderErrorSnifferNonKimiIgnoresProviderApiError verifies that the
+// kimi-specific provider.api_error patterns are scoped to kimi only. Other ACP
+// backends (hermes, grok, kiro, qoder, qwenpaw, reasonix, traecli) must not
+// classify a provider.api_error line as terminal — tool output can legitimately
+// echo such lines when calling an underlying Kimi API, and a run with real
+// output must stay completed (GitHub multica#5785 P1 from Aug 10 review).
+func TestACPProviderErrorSnifferNonKimiIgnoresProviderApiError(t *testing.T) {
+ t.Parallel()
+
+ for _, provider := range []string{"hermes", "grok", "kiro", "qoder", "qwenpaw", "reasonix", "traecli"} {
+ t.Run(provider, func(t *testing.T) {
+ s := newACPProviderErrorSniffer(provider)
+ s.Write([]byte("provider.api_error: 400 assistant must not be empty\n"))
+
+ if msg := s.terminalMessage(); msg != "" {
+ t.Errorf("provider %q: provider.api_error in tool output must not be terminal, got %q", provider, msg)
+ }
+
+ // With real output the run must stay completed even if the sniffer
+ // captured the line via a non-terminal path.
+ status, _ := promoteACPResultOnProviderError("completed", "", "successful output", s)
+ if status != "completed" {
+ t.Errorf("provider %q: run with real output must stay completed, got %q", provider, status)
+ }
+ })
+ }
+}
+
// TestHermesBackendPromotesProviderErrorWithNonEmptyOutput pins the
// fix for GitHub multica#1952: a hermes run that hits a 429 (or any
// upstream provider error) must surface as Status=failed even though
@@ -2793,6 +3077,83 @@ func TestHermesBackendDoesNotPromoteOnTransientRetry(t *testing.T) {
}
}
+// fakeHermesACPPoisonedHistoryScript mimics a hermes-style adapter that emits
+// the "assistant message must not be empty" error in the Python [ERROR] log
+// format when asked to resume a session whose history is corrupted. This uses
+// the hermes-native stderr format (emoji-prefixed, after-N-retries), NOT the
+// bare kimi provider.api_error format — the kimi patterns are scoped to kimi.
+func fakeHermesACPPoisonedHistoryScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/resume"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_poison"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '%s\n' "2026-01-01 00:00:01 [ERROR] root: ❌ API call failed after 3 retries: BadRequestError the message at position 43 with role 'assistant' must not be empty" >&2
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+// TestHermesBackendPoisonedHistorySetsResumeRejected verifies the fix
+// for the kimi "assistant message must not be empty" scenario: when
+// the sniffer detects a 400 with the poisoned-history signal the
+// backend must set ResumeRejected=true so the daemon drops the broken
+// session and tries fresh (via the tools==0 gate) instead of
+// resuming the same corrupt history on every subsequent task.
+func TestHermesBackendPoisonedHistorySetsResumeRejected(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "hermes")
+ writeTestExecutable(t, fakePath, []byte(fakeHermesACPPoisonedHistoryScript()))
+
+ backend, err := New("hermes", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new hermes backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ ResumeSessionID: "ses_poison",
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed for poisoned history, got %q", result.Status)
+ }
+ if !result.ResumeRejected {
+ t.Error("expected ResumeRejected=true so the daemon clears the broken session")
+ }
+ if !strings.Contains(result.Error, "must not be empty") {
+ t.Errorf("expected error to mention the poisoned history detail, got %q", result.Error)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
// ── extractACPMcpCapabilities ──
func TestExtractACPMcpCapabilities(t *testing.T) {
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.go
index a6504a5b39..2ce75d1fca 100644
--- a/server/pkg/agent/kimi.go
+++ b/server/pkg/agent/kimi.go
@@ -442,6 +442,9 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
// Ensure the stderr copier has drained before consulting the
// provider-error sniffer; see hermes.go for the failure mode.
<-stderrDone
+ // Flush any partial stderr line that arrived without a trailing '\n'
+ // before the pipe closed (P1 from multica#5785 review Aug 10).
+ providerErr.Finalize()
streamingCurrentTurn.Store(false)
finalOutput, providerErrorOutput := deliverable.result()
@@ -455,6 +458,16 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
// deliverable, so a give-up turn that lands before a tool call
// stays visible.
finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)
+ // A poisoned session history (400 "assistant must not be empty") is
+ // unresumable — every resume replays the identical body and reproduces
+ // the same 400 — so signal the daemon to drop the session and retry
+ // fresh. Guard on ResumeSessionID: only a resume can inherit a poisoned
+ // history; a fresh run cannot reproduce it deterministically. This is
+ // the positive backend signal; taskfailure.UnresumableHistory keys off
+ // the surfaced Result.Error string as the backend-agnostic path (#6083).
+ if finalStatus == "failed" && opts.ResumeSessionID != "" && providerErr.isPoisonedHistory() {
+ resumeRejected = true
+ }
u := c.accumulatedUsage()
diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.go
index cac8a9f03f..03b9dd6a53 100644
--- a/server/pkg/agent/kimi_test.go
+++ b/server/pkg/agent/kimi_test.go
@@ -12,6 +12,8 @@ import (
"strings"
"testing"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
)
func TestNewReturnsKimiBackend(t *testing.T) {
@@ -695,6 +697,314 @@ func TestKimiFreshSessionIncludesMcpServers(t *testing.T) {
}
}
+// fakeKimiPoisonedHistoryScript mimics the kimi CLI when asked to resume a
+// session whose conversation history contains an empty assistant message. The
+// adapter emits the "provider.api_error: 400 … role 'assistant' must not be
+// empty" line to stderr and returns a completed (end_turn) JSON-RPC response —
+// matching the real kimi adapter behaviour that prompted MUL-5154.
+func fakeKimiPoisonedHistoryScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/resume"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_poison"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '%s\n' "error: failed to run prompt: provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty" >&2
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+// TestKimiBackendPoisonedHistorySetsResumeRejected verifies that when the kimi
+// backend receives the "assistant must not be empty" 400 error while resuming
+// a session, it sets ResumeRejected=true so the daemon clears the broken
+// session pointer and starts fresh on the next task.
+func TestKimiBackendPoisonedHistorySetsResumeRejected(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "kimi")
+ writeTestExecutable(t, fakePath, []byte(fakeKimiPoisonedHistoryScript()))
+
+ backend, err := New("kimi", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new kimi backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ ResumeSessionID: "ses_poison",
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed for poisoned history, got %q", result.Status)
+ }
+ if !result.ResumeRejected {
+ t.Error("expected ResumeRejected=true so the daemon clears the broken session")
+ }
+ if !strings.Contains(result.Error, "must not be empty") {
+ t.Errorf("expected error to mention the poisoned-history detail, got %q", result.Error)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
+// TestKimiBackendPoisonedHistoryFreshRunNoResumeRejected verifies that when
+// the same poisoned-history error occurs on a FRESH run (ResumeSessionID==""),
+// ResumeRejected must stay false. A fresh run cannot inherit a broken history,
+// so flagging it would incorrectly prevent the next task from resuming a good
+// session.
+func TestKimiBackendPoisonedHistoryFreshRunNoResumeRejected(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "kimi")
+ script := `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fresh"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '%s\n' "error: failed to run prompt: provider.api_error: 400 the message at position 1 with role 'assistant' must not be empty" >&2
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("kimi", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new kimi backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)
+ }
+ if result.ResumeRejected {
+ t.Error("ResumeRejected must be false on a fresh run (no ResumeSessionID)")
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
+// TestKimiBackendPoisonedHistoryTwoLineFormat verifies that the two-line kimi
+// stderr format (status on one line, detail on the next) is correctly detected
+// as a poisoned session. Both isPoisonedHistory and classifyPoisonedError must
+// fire even when "provider.api_error: 400" and "must not be empty" arrive on
+// separate lines.
+func TestKimiBackendPoisonedHistoryTwoLineFormat(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "kimi")
+ script := `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/resume"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_poison_2line"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '%s\n' "error: failed to run prompt: provider.api_error: 400" >&2
+ printf '%s\n' "detail: messages[43].content: content must not be empty" >&2
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("kimi", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new kimi backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ ResumeSessionID: "ses_poison_2line",
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if result.Status != "failed" {
+ t.Fatalf("two-line: expected status=failed, got %q (error=%q)", result.Status, result.Error)
+ }
+ if !result.ResumeRejected {
+ t.Error("two-line: expected ResumeRejected=true — isPoisonedHistory must detect across stderr lines")
+ }
+ if !strings.Contains(result.Error, "provider.api_error: 400") {
+ t.Errorf("two-line: expected error to contain provider.api_error: 400, got %q", result.Error)
+ }
+ if !strings.Contains(result.Error, "must not be empty") {
+ t.Errorf("two-line: expected error to contain must not be empty, got %q", result.Error)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
+// TestKimiPoisonedHistorySurfacedErrorIsUnresumable pins the cross-package
+// contract this PR exists to satisfy: the Result.Error string the kimi sniffer
+// surfaces must be recognized by taskfailure.UnresumableHistory, the daemon's
+// backend-agnostic predicate (#6083) that retires the session so a later issue
+// mention or chat cannot resume the poisoned transcript. isPoisonedHistory now
+// delegates to that same predicate, but the daemon classifies the surfaced
+// string independently of ResumeRejected — via shouldRetryWithFreshSession and
+// GetLastTaskSession / GetLastChatTaskSession — so the string itself must carry
+// the emptiness complaint and the message locator through the sniffer's
+// extraction, for both Kimi stderr shapes. A regression that only checked
+// ResumeRejected would not catch a messageLocked change that dropped the
+// locator and silently broke the daemon-side exclusion.
+func TestKimiPoisonedHistorySurfacedErrorIsUnresumable(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ script string
+ resumeID string
+ wantLocate string // a token the surfaced error must retain
+ }{
+ {
+ name: "single-line",
+ script: fakeKimiPoisonedHistoryScript(),
+ resumeID: "ses_poison",
+ wantLocate: "message at position",
+ },
+ {
+ name: "two-line",
+ script: `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/resume"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_poison_2line"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '%s\n' "error: failed to run prompt: provider.api_error: 400" >&2
+ printf '%s\n' "detail: messages[43].content: content must not be empty" >&2
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`,
+ resumeID: "ses_poison_2line",
+ wantLocate: "messages[43",
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "kimi")
+ writeTestExecutable(t, fakePath, []byte(tc.script))
+
+ backend, err := New("kimi", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new kimi backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ ResumeSessionID: tc.resumeID,
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if !strings.Contains(result.Error, tc.wantLocate) {
+ t.Errorf("surfaced error dropped the history locator %q: %q", tc.wantLocate, result.Error)
+ }
+ if !taskfailure.UnresumableHistory(result.Error) {
+ t.Errorf("taskfailure.UnresumableHistory(%q) = false; the daemon would not retire the poisoned session", result.Error)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+ })
+ }
+}
+
// TestKimiDrainsNotificationsAfterPromptResponse pins the trailing-notification
// drain. kimi ACP can emit a final session update just after the
// session/prompt response returns; closing stdin and cancelling the context at