Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): scope Hermes provider-error sniffer to real error boundaries (#5864)
YikaJ26911108675e
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex 0367dc2d9b..c6658e459b 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -2191,6 +2191,13 @@ type acpProviderErrorSniffer struct {lines []string // captured error lines, boundedseen map[string]boolterminal 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.+ echoJSON bool+ echoDepth int+ echoInString bool+ echoEscaped bool}// acpErrorHeaderRe matches the first line of an API-error block.@@ -2221,6 +2228,33 @@ var acpAgentOutputTerminalRe = regexp.MustCompile(`API call failed after \d+ retconst acpMaxErrorLines = 8+// acpLogRecordPrefixRe matches the start of a Python `logging` record that+// Hermes writes to stderr: "YYYY-MM-DD HH:MM:SS[,mmm] [LEVEL] logger: ...".+// Capture groups are level, logger, and payload. Matching every logger is+// important because a non-root ERROR record also ends a preceding root INFO+// record and must remain visible to the provider-error matchers.+var acpLogRecordPrefixRe = regexp.MustCompile(+ `^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(?:,[0-9]+)? \[([A-Z]+)\] ([A-Za-z0-9_.-]+):\s*(.*)$`,+)++// acpEchoLogLevels are the Python root-logger levels Hermes uses purely to+// echo conversation and tool data to stderr. Those records are arbitrary+// payload, never a provider error, even when they embed strings such as+// "❌", "Error:", "HTTP 429", or "API call failed". ERROR / WARNING /+// CRITICAL records are real diagnostics and must still be matched.+var acpEchoLogLevels = map[string]bool{"INFO": true, "DEBUG": true}++// acpMaxErrorLineLen bounds the length of the persisted provider-error+// summary. Genuine ACP provider-error lines are short (an error header plus+// a one-line "Error: ..." detail — see TestHermesProviderErrorSniffer, ~150+// bytes), but an oversized echo that slips past the log-record filter could+// otherwise store tens of KB. This bound is applied only when BUILDING the+// stored message, never as a precondition for *classifying* a line as an+// error: a real provider failure whose single line happens to exceed this+// length must still fail the run, not be silently dropped (GitHub+// multica#5862 — do not gate matching on length).+const acpMaxErrorLineLen = 4096+// newACPProviderErrorSniffer returns a sniffer that tags its messages// with the given provider name (e.g. "hermes", "kimi") so failure// strings make it obvious which runtime produced the error.@@ -2246,11 +2280,42 @@ func (s *acpProviderErrorSniffer) Write(p []byte) (int, error) {complete = string(data[:nl])s.remains = append(s.remains[:0], data[nl+1:]...)- for _, line := range strings.Split(complete, "\n") {- line = strings.TrimSpace(line)+ for _, rawLine := range strings.Split(complete, "\n") {+ rawLine = strings.TrimSuffix(rawLine, "\r")+ line := strings.TrimSpace(rawLine)if line == "" {continue}+ // INFO/DEBUG root records are conversation/tool echoes and never+ // reach the error matchers. When their payload is structured JSON,+ // track brace depth across physical lines and skip only until that+ // JSON closes. A complete single-line echo therefore cannot hide a+ // following bare provider error. Any Python logger prefix also+ // starts a new record, so non-root ERROR diagnostics remain visible+ // (GitHub multica#5862).+ if m := acpLogRecordPrefixRe.FindStringSubmatch(line); m != nil {+ s.resetEchoJSON()+ if acpEchoLogLevels[m[1]] && m[2] == "root" {+ s.startEchoJSON(m[3])+ continue+ }+ } else if s.echoJSON {+ // A strong, unindented provider-error header is a new bare+ // error block even if a malformed echo never closed. Indented+ // error-looking text remains part of the structured echo. This+ // also applies when the echo was truncated inside a JSON string:+ // an unescaped physical newline is not valid inside that string.+ indented := rawLine[0] == ' ' || rawLine[0] == '\t'+ bareError := strings.HasPrefix(line, "⚠️") ||+ strings.HasPrefix(line, "❌") ||+ strings.HasPrefix(line, "[ERROR]")+ if !indented && bareError && acpErrorHeaderRe.MatchString(line) {+ s.resetEchoJSON()+ } else {+ s.consumeEchoJSON(rawLine)+ continue+ }+ }if !(acpErrorHeaderRe.MatchString(line) || acpErrorDetailRe.MatchString(line)) {continue}@@ -2269,6 +2334,55 @@ func (s *acpProviderErrorSniffer) Write(p []byte) (int, error) {return len(p), nil}+func (s *acpProviderErrorSniffer) startEchoJSON(payload string) {+ payload = strings.TrimSpace(payload)+ if payload == "" || (payload[0] != '{' && payload[0] != '[') {+ return+ }+ s.echoJSON = true+ s.consumeEchoJSON(payload)+}++// consumeEchoJSON tracks only structural JSON bytes. It avoids buffering+// arbitrary conversation/tool payloads while still recognizing their exact+// multi-line boundary, including braces inside quoted strings.+func (s *acpProviderErrorSniffer) consumeEchoJSON(fragment string) {+ for i := 0; i < len(fragment); i++ {+ switch {+ case s.echoEscaped:+ s.echoEscaped = false+ case s.echoInString:+ switch fragment[i] {+ case '\\':+ s.echoEscaped = true+ case '"':+ s.echoInString = false+ }+ default:+ switch fragment[i] {+ case '"':+ s.echoInString = true+ case '{', '[':+ s.echoDepth+++ case '}', ']':+ if s.echoDepth > 0 {+ s.echoDepth--+ }+ }+ }+ }+ if s.echoDepth == 0 {+ s.resetEchoJSON()+ }+}++func (s *acpProviderErrorSniffer) resetEchoJSON() {+ s.echoJSON = false+ s.echoDepth = 0+ s.echoInString = false+ s.echoEscaped = false+}+// message returns a single-line summary suitable for the task// error field. Prefers the most specific "Error:" / "detail:"// fragment; falls back to the first captured header line; empty@@ -2309,18 +2423,29 @@ func (s *acpProviderErrorSniffer) messageLocked() string {if m := acpErrorDetailRe.FindStringSubmatch(line); m != nil {detail := strings.TrimSpace(m[1])if detail != "" {- return prefix + detail+ return acpTruncateError(prefix + detail)}}}for _, line := range s.lines {if acpErrorHeaderRe.MatchString(line) {- return prefix + line+ return acpTruncateError(prefix + line)}}return ""}+// acpTruncateError bounds a persisted provider-error summary to+// acpMaxErrorLineLen bytes on a valid UTF-8 boundary, marking any cut.+// Classification already happened by the time this runs; it only limits+// how much of an oversized message is stored, never whether a run fails.+func acpTruncateError(msg string) string {+ if len(msg) <= acpMaxErrorLineLen {+ return msg+ }+ return strings.ToValidUTF8(msg[:acpMaxErrorLineLen], "") + "…(truncated)"+}+// promoteACPResultOnProviderError flips finalStatus to "failed" if// either (a) the stderr sniffer captured a terminal-failure marker,// (b) the adapter injected a synthetic "API call failed after Ndiff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.goindex c92b380dfe..d8b3769953 100644--- a/server/pkg/agent/hermes_test.go+++ b/server/pkg/agent/hermes_test.go@@ -1845,6 +1845,242 @@ func TestHermesProviderErrorSnifferBoundedBuffer(t *testing.T) {}}+// TestHermesProviderErrorSnifferIgnoresEchoedInfoRecords guards pollution+// failures from GitHub multica#5862.+//+// Pollution failure ≠ real provider failure:+// - real failure: Hermes/provider crashes; no successful final reply.+// - pollution failure: Hermes already produced a correct final reply /+// completed the requested work, then Multica suddenly flips the same+// run to failed because an `[INFO] root:` conversation/tool echo on+// stderr embedded error-looking tokens (Error:, KeyError:, ❌, ...).+//+// These fixtures model the pollution class. The sniffer must ignore the+// full INFO record, and a completed run with a successful final reply+// must stay completed.+func TestHermesProviderErrorSnifferIgnoresEchoedInfoRecords(t *testing.T) {+ t.Parallel()++ oversizedDoc := `2026-07-24 10:08:59 [INFO] root: {"message":{"role":"tool","content":"` ++ "# ❌ Deprecated approach: do not use this query. " ++ strings.Repeat("reference documentation body ... ", 500) ++ `The parser may return KeyError: 'series'; inspect the response shape first."}}`++ tests := []struct {+ name string+ line string+ }{+ {+ name: "oversized documentation payload",+ line: oversizedDoc,+ },+ {+ name: "short tool result payload",+ line: `2026-07-24 10:09:00 [INFO] root: {"message":{"role":"tool","content":"# ❌ Deprecated example. KeyError: 'series' means the optional field is absent."}}`,+ },+ {+ name: "short llm call payload",+ line: `2026-07-24 10:09:01 [INFO] root: {"type":"llm_call","finish_reason":"tool_calls","arguments":"print(f\"Error: {err}\")","reasoning_content":"❌ This sample is intentionally invalid."}`,+ },+ {+ name: "provider-looking text inside info payload",+ line: `2026-07-24 10:09:02 [INFO] root: {"message":{"role":"tool","content":"Troubleshooting example: ❌ API call failed after 3 retries: HTTP 429. This is quoted documentation, not the current run."}}`,+ },+ }++ if len(oversizedDoc) < acpMaxErrorLineLen {+ t.Fatalf("oversized fixture is %d bytes, below the cap %d", len(oversizedDoc), acpMaxErrorLineLen)+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ s := newACPProviderErrorSniffer("hermes")+ if _, err := s.Write([]byte(tt.line + "\n")); err != nil {+ t.Fatalf("Write: %v", err)+ }+ if msg := s.message(); msg != "" {+ t.Errorf("echoed INFO record must not be captured, got %d bytes: %q", len(msg), firstNRunes(msg, 100))+ }+ if msg := s.terminalMessage(); msg != "" {+ t.Errorf("echoed INFO record must not set terminal failure, got %d bytes: %q", len(msg), firstNRunes(msg, 100))+ }++ // Simulate the observed pollution timing: a successful final+ // reply already exists, then promotion consults the sniffer.+ successfulFinalReply := "Done. The requested work completed successfully."+ status, errStr := promoteACPResultOnProviderError("completed", "", successfulFinalReply, s)+ if status != "completed" {+ t.Errorf("pollution: successful final reply was present, but status flipped to %q (error=%q)", status, firstNRunes(errStr, 100))+ }+ })+ }+}++// TestHermesProviderErrorSnifferStillCapturesErrorRootRecords is the+// control for real failures: genuine `[ERROR] root:` provider records+// must still be terminal. Pollution handling must not swallow those.+func TestHermesProviderErrorSnifferStillCapturesErrorRootRecords(t *testing.T) {+ t.Parallel()++ s := newACPProviderErrorSniffer("hermes")+ line := `2026-07-24 10:09:03 [ERROR] root: ❌ API call failed after 3 retries: HTTP 429 rate limit exceeded`+ if _, err := s.Write([]byte(line + "\n")); err != nil {+ t.Fatalf("Write: %v", err)+ }++ msg := s.terminalMessage()+ if !strings.Contains(msg, "HTTP 429") {+ t.Fatalf("real error: expected genuine ERROR root record to remain terminal, got %q", msg)+ }+}++// TestHermesProviderErrorSnifferIgnoresMultiLineInfoRecords guards the+// second pollution shape from GitHub multica#5862. Hermes echoes a+// conversation/tool record whose JSON spans several physical lines: only+// the first line carries the `[INFO] root:` prefix, the continuation lines+// do not, yet they may embed both a capture token (`Error:`) and a terminal+// token (`❌`) on the same physical line. The whole record must be skipped,+// so a completed run with a successful final reply stays completed.+func TestHermesProviderErrorSnifferIgnoresMultiLineInfoRecords(t *testing.T) {+ t.Parallel()++ record := "2026-07-24 10:09:00 [INFO] root: {\n" ++ " \"message\": {\"role\": \"tool\", \"content\": \"❌ Error: KeyError 'series' is quoted documentation, not a provider failure\"}\n" ++ "}\n"++ s := newACPProviderErrorSniffer("hermes")+ for _, physicalLine := range strings.SplitAfter(record, "\n") {+ if physicalLine == "" {+ continue+ }+ if _, err := s.Write([]byte(physicalLine)); err != nil {+ t.Fatalf("Write: %v", err)+ }+ }+ if msg := s.message(); msg != "" {+ t.Errorf("multi-line INFO echo must not be captured, got %q", firstNRunes(msg, 120))+ }+ if msg := s.terminalMessage(); msg != "" {+ t.Errorf("multi-line INFO echo must not be terminal, got %q", firstNRunes(msg, 120))+ }+ status, errStr := promoteACPResultOnProviderError("completed", "", "Done. The requested work completed successfully.", s)+ if status != "completed" {+ t.Errorf("multi-line INFO echo flipped a completed run to %q (error=%q)", status, firstNRunes(errStr, 120))+ }+}++// TestHermesProviderErrorSnifferErrorRecordAfterInfoRecord is the control+// for the multi-line skip: a genuine `[ERROR] root:` record that FOLLOWS a+// multi-line INFO echo must still be terminal. The error record's own+// prefix ends the skipped INFO record, so real failures are not swallowed.+func TestHermesProviderErrorSnifferErrorRecordAfterInfoRecord(t *testing.T) {+ t.Parallel()++ stream := "2026-07-24 10:09:00 [INFO] root: {\n" ++ " \"content\": \"❌ Error: harmless echoed documentation\"\n" ++ "}\n" ++ "2026-07-24 10:09:05 [ERROR] root: ❌ API call failed after 3 retries: HTTP 429 rate limit exceeded\n"++ s := newACPProviderErrorSniffer("hermes")+ if _, err := s.Write([]byte(stream)); err != nil {+ t.Fatalf("Write: %v", err)+ }+ msg := s.terminalMessage()+ if !strings.Contains(msg, "HTTP 429") {+ t.Fatalf("real ERROR record after an INFO echo must stay terminal, got %q", msg)+ }+}++// TestHermesProviderErrorSnifferRealErrorsAfterSingleLineInfo guards record+// boundaries around INFO echoes. A complete single-line INFO record must not+// make a following bare provider-error block or a non-root logger record look+// like an INFO continuation.+func TestHermesProviderErrorSnifferRealErrorsAfterSingleLineInfo(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ stream string+ }{+ {+ name: "bare provider error",+ stream: "2026-07-24 10:09:00 [INFO] root: {\"message\":\"ordinary echo with an unmatched { in quoted text\"}\n" ++ "❌ API call failed after 3 retries: RateLimitError [HTTP 429]\n" ++ "📝 Error: HTTP 429 rate limit exceeded\n",+ },+ {+ name: "non-root error logger",+ stream: "2026-07-24 10:09:00 [INFO] root: {\"message\":\"ordinary echo\"}\n" ++ "2026-07-24 10:09:01 [ERROR] acp_adapter.server: ❌ API call failed after 3 retries: HTTP 429 rate limit exceeded\n",+ },+ {+ name: "bare provider error after echo truncated inside string",+ stream: "2026-07-24 10:09:00 [INFO] root: {\"message\":\"truncated echo\n" ++ "❌ API call failed after 3 retries: RateLimitError [HTTP 429]\n" ++ "📝 Error: HTTP 429 rate limit exceeded\n",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ s := newACPProviderErrorSniffer("hermes")+ if _, err := s.Write([]byte(tt.stream)); err != nil {+ t.Fatalf("Write: %v", err)+ }+ if msg := s.terminalMessage(); !strings.Contains(msg, "HTTP 429") {+ t.Fatalf("real provider error after a single-line INFO record was swallowed, got %q", msg)+ }+ })+ }+}++// TestHermesProviderErrorSnifferLongRealErrorStillFails guards the #1952+// regression: a genuine provider failure emitted as one long line (well+// over acpMaxErrorLineLen) with no successful output must still fail the+// run. Length must never decide whether a line is an error. The shared+// sniffer backs hermes/kimi/kiro/qoder/grok/traecli, so verify the+// non-Hermes callers too, and confirm the persisted message stays bounded.+func TestHermesProviderErrorSnifferLongRealErrorStillFails(t *testing.T) {+ t.Parallel()++ longReal := "❌ API call failed after 3 retries: BadRequestError [HTTP 400] " ++ "Error: HTTP 400: Error code: 400 - {'detail': \"" ++ strings.Repeat("the requested model is not supported for this account; ", 200) ++ "\"}"+ if len(longReal) <= acpMaxErrorLineLen {+ t.Fatalf("fixture is %d bytes, must exceed the cap %d to exercise the path", len(longReal), acpMaxErrorLineLen)+ }++ for _, provider := range []string{"hermes", "kimi", "kiro", "qoder", "grok", "traecli"} {+ t.Run(provider, func(t *testing.T) {+ s := newACPProviderErrorSniffer(provider)+ if _, err := s.Write([]byte(longReal + "\n")); err != nil {+ t.Fatalf("Write: %v", err)+ }+ // Empty output: no successful reply to fall back on (#1952).+ status, errStr := promoteACPResultOnProviderError("completed", "", "", s)+ if status != "failed" {+ t.Fatalf("long real provider error was dropped; run stayed %q instead of failed", status)+ }+ if errStr == "" {+ t.Fatal("failed run must carry a non-empty provider-error message")+ }+ if len(errStr) > acpMaxErrorLineLen+len("…(truncated)") {+ t.Errorf("persisted error not bounded: %d bytes", len(errStr))+ }+ })+ }+}++// firstNRunes returns at most n runes of s, for bounded error output.+func firstNRunes(s string, n int) string {+ r := []rune(s)+ if len(r) <= n {+ return s+ }+ return string(r[:n]) + "…"+}+func fakeHermesACPUsageWithDefaultModelScript() string {return `#!/bin/shwhile IFS= read -r line; do