Skip to content

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

Go

fix(daemon): recover in-turn when a resumed session cannot resolve provider auth (#6798)

Multica Eve0c69f1f95fd8
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index c2c994e1f7..45f0e3490f 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -6713,6 +6713,35 @@ func shouldRetryWithFreshSession(result agent.Result, priorSessionID string, too
if taskfailure.UnresumableHistory(result.Error) {
return true
}
+ // Third form of positive evidence, and the same shape of argument: the
+ // resume was not refused — the runtime happily rebuilt the session — but
+ // the provider identity it rebuilt can no longer resolve its own
+ // credentials, so the turn dies with "Could not resolve authentication
+ // method" (GH #6777). The credentials are fine; only the session's copy of
+ // the provider is broken, which is precisely what a fresh session
+ // re-resolves from current config.
+ //
+ // This is the exception the Result.ResumeRejected doc calls out: adapters
+ // must NOT flag auth errors, because a genuine credential failure keeps the
+ // session so the platform's own retry can continue the conversation. The
+ // distinction is resume-vs-fresh, not the error text — and priorSessionID
+ // above already establishes that this run WAS a resume. On a cold run the
+ // same error means the config really is wrong and this gate never sees it.
+ //
+ // Deciding here rather than in each ACP adapter is what makes it correct
+ // for every step of the ACP lifecycle: the failure surfaces at
+ // session/resume, at session/set_model (a resumed session whose persisted
+ // provider was normalised gets a redundant set_model that re-routes to the
+ // wrong provider — MUL-5029) or at session/prompt, and only two of those
+ // three carry any resume-failure signal today. The final error text carries
+ // the phrase on all three.
+ //
+ // Worst case, the config genuinely is broken: the fresh attempt fails the
+ // same way, the user sees the same error once, and the single-retry budget
+ // bounds the cost. That is the same trade the branch above already makes.
+ if taskfailure.AuthMethodUnresolved(result.Error) {
+ return true
+ }
// Everything below is a bounded compatibility path for the backends that
// cannot answer question 1 at all. For every other backend a false
// ResumeRejected is a real answer — it checked and this was not a
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 368106cf3b..3fd5ab8120 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -24,6 +24,7 @@ import (
"github.com/multica-ai/multica/server/internal/daemon/execenv"
"github.com/multica-ai/multica/server/internal/daemon/repocache"
"github.com/multica-ai/multica/server/pkg/agent"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
"github.com/pelletier/go-toml/v2"
)
@@ -2370,6 +2371,83 @@ func TestExecuteAndDrain_NetworkFailureKeepsResumeSession(t *testing.T) {
}
}
+// TestExecuteAndDrain_AuthResolutionOnResumeRecoversInTurn is the GH #6777
+// regression, driven through the same two-attempt sequence the daemon runs.
+//
+// The reported symptom was a Chat that alternated success / failure forever:
+// turn 1 opened a session and worked; turn 2 resumed it and died with the
+// provider's auth-resolution error; the server-side resume guards then
+// blacklisted that session so turn 3 started fresh and worked again, and so on.
+// Server-side blacklisting alone can only produce that alternation — curing the
+// FAILING turn needs the in-turn fresh retry, which never fired because nothing
+// identified the error as fatal-to-resume. This asserts the whole recovery:
+// the gate opens on attempt 1, and a cold attempt 2 succeeds with its own
+// session id.
+func TestExecuteAndDrain_AuthResolutionOnResumeRecoversInTurn(t *testing.T) {
+ t.Parallel()
+
+ d := newTestDaemon(t)
+
+ const authErr = `hermes provider error: "Could not resolve authentication method. Expected either api_key or auth_token to be set. Or for one of the X-Api-Key or Authorization headers to be explicitly omitted"`
+
+ fb := &fakeBackend{
+ results: []agent.Result{
+ // Attempt 1: resumed session, provider identity unusable.
+ {Status: "failed", Error: authErr, SessionID: "ses_resumed"},
+ // Attempt 2: cold session re-resolves the provider from config.
+ {Status: "completed", Output: "hello", SessionID: "ses_fresh"},
+ },
+ }
+
+ opts := agent.ExecOptions{ResumeSessionID: "ses_resumed"}
+ result, tools, err := d.executeAndDrain(context.Background(), fb, "p", opts, slog.Default(), "t", "", new(atomic.Int32))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The adapter must NOT claim the resume was rejected — nothing rejected it,
+ // and Result.ResumeRejected is documented as excluding auth failures. The
+ // recovery has to come from the gate instead.
+ if result.ResumeRejected {
+ t.Fatal("an auth-resolution failure must not be reported as a rejected resume")
+ }
+ if !shouldRetryWithFreshSession(result, opts.ResumeSessionID, tools, "hermes") {
+ t.Fatal("a resumed session that cannot resolve auth must retry once from a fresh session; without this the failing turn is never cured and the user sees alternating failures")
+ }
+
+ // What runTask does on that verdict: retire the prior session and re-run
+ // cold. Mirrored here so the sequence — not just the predicate — is pinned.
+ retired := opts.ResumeSessionID
+ freshOpts := opts
+ freshOpts.ResumeSessionID = ""
+ retry, retryTools, err := d.executeAndDrain(context.Background(), fb, "p", freshOpts, slog.Default(), "t", "", new(atomic.Int32))
+ if err != nil {
+ t.Fatal(err)
+ }
+ final, _ := reconcileFreshRetryResult(result, result.Usage, tools, retry, retryTools, nil)
+
+ if final.Status != "completed" {
+ t.Fatalf("status = %q, want completed — the user's message must succeed on this turn", final.Status)
+ }
+ if final.SessionID != "ses_fresh" {
+ t.Fatalf("session id = %q, want ses_fresh so the next turn resumes the working session", final.SessionID)
+ }
+ if final.SessionID == retired {
+ t.Fatal("the dead session must not become the resume pointer again")
+ }
+ if int(fb.idx.Load()) != 2 {
+ t.Fatalf("expected exactly 2 attempts (one retry, not a loop), got %d", fb.idx.Load())
+ }
+ if fb.calls[1].ResumeSessionID != "" {
+ t.Fatalf("retry asked to resume %q; it must be a cold start", fb.calls[1].ResumeSessionID)
+ }
+ // The server-side half of the fix still has to hold: even though this turn
+ // recovered, the failed attempt's error must keep that session out of every
+ // later resume lookup.
+ if !taskfailure.AuthMethodUnresolved(result.Error) {
+ t.Fatal("the failed attempt's error must still be recognised so ResumeUnsafeFailure and the resume queries retire the dead session")
+ }
+}
+
func TestShouldRetryWithFreshSession(t *testing.T) {
t.Parallel()
@@ -2652,6 +2730,89 @@ func TestShouldRetryWithFreshSession(t *testing.T) {
provider: "codex",
want: false,
},
+ {
+ // GH #6777: the alternating Chat failure. Hermes rebuilds the
+ // resumed session but persists a normalised provider identity that
+ // can no longer resolve its credentials, so the turn dies with the
+ // SDK's auth-resolution message. Nothing rejected the resume, so
+ // ResumeRejected is false and correctly so — the adapter cannot
+ // tell this from a bad credential. Only this gate knows the run was
+ // a resume, and a fresh session re-resolves the provider from
+ // current config.
+ name: "hermes resumed session that cannot resolve auth retries",
+ result: agent.Result{
+ Status: "failed",
+ Error: `hermes provider error: "Could not resolve authentication method. Expected either api_key or auth_token to be set. Or for one of the X-Api-Key or Authorization headers to be explicitly omitted"`,
+ SessionID: "ses_resumed",
+ },
+ priorSessionID: "ses_resumed",
+ provider: "hermes",
+ want: true,
+ },
+ {
+ // The same failure surfacing one ACP step earlier: a resumed
+ // session whose persisted provider was flattened gets a
+ // non-redundant session/set_model, which re-runs provider
+ // auto-detection and mis-routes (MUL-5029). The adapter wraps the
+ // message instead of replacing it, which is why matching the
+ // phrase here covers all three lifecycle steps at once.
+ name: "hermes set_model auth-resolution failure on resume retries",
+ result: agent.Result{
+ Status: "failed",
+ Error: `hermes could not switch to model "custom:deepseek-v4-pro": session/set_model: Could not resolve authentication method. Expected either api_key or auth_token to be set.`,
+ SessionID: "ses_resumed",
+ },
+ priorSessionID: "ses_resumed",
+ provider: "hermes",
+ want: true,
+ },
+ {
+ // The tools gate is untouched by the new evidence, exactly as for
+ // the poisoned-history branch above: a turn that already acted is
+ // never replayed. Its session is still retired at report time by
+ // ResumeUnsafeFailure's matching text guard.
+ name: "hermes auth-resolution failure after a tool ran never retries",
+ result: agent.Result{
+ Status: "failed",
+ Error: `hermes provider error: "Could not resolve authentication method. Expected either api_key or auth_token to be set."`,
+ SessionID: "ses_resumed",
+ },
+ priorSessionID: "ses_resumed",
+ tools: 1,
+ provider: "hermes",
+ want: false,
+ },
+ {
+ // The load-bearing scope limit: on a COLD run the same message
+ // means the agent's provider config really is incomplete. There is
+ // no session to blame and no fresh session to fall back to, so the
+ // error must reach the user instead of burning a second run. The
+ // priorSessionID gate is what encodes that distinction.
+ name: "cold run that cannot resolve auth does not retry",
+ result: agent.Result{
+ Status: "failed",
+ Error: `hermes provider error: "Could not resolve authentication method. Expected either api_key or auth_token to be set."`,
+ },
+ priorSessionID: "",
+ provider: "hermes",
+ want: false,
+ },
+ {
+ // Narrowness guard, mirroring the SQL side's auth-adjacent test: a
+ // rejected credential is about the credential, not the session's
+ // copy of the provider, and a fresh session replays it verbatim.
+ // Widening the phrase to any authentication-shaped error would
+ // discard healthy conversation pointers on every such failure.
+ name: "hermes rejected credential on resume keeps the session",
+ result: agent.Result{
+ Status: "failed",
+ Error: `hermes provider error: "401 authentication_error: invalid x-api-key"`,
+ SessionID: "ses_resumed",
+ },
+ priorSessionID: "ses_resumed",
+ provider: "hermes",
+ want: false,
+ },
}
for _, tt := range tests {
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 337632c47b..298da16c36 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -4275,7 +4275,11 @@ func ResumeUnsafeFailure(failureReason, errorText string) bool {
// reason-independent text guard is the load-bearing protection for both new
// and already persisted rows. Keep it in sync with the GetLastTaskSession /
// GetLastChatTaskSession resume queries.
- if strings.Contains(lower, "could not resolve authentication method") {
+ //
+ // The phrase itself lives in taskfailure.AuthMethodUnresolved, shared with
+ // the daemon's in-turn fresh-session retry gate so the two layers cannot
+ // disagree about which errors mean "this session can never be resumed".
+ if taskfailure.AuthMethodUnresolved(errorText) {
return true
}
// Same defense-in-depth for the provider-agnostic empty-message shape:
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 466e4f65e6..2c92e64f5b 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -209,6 +209,14 @@ type Result struct {
// network drops, rate limits, quota, provider 5xx, or auth errors. Those
// keep the session pointer so the platform's own retry can resume the
// truncated conversation (see retryableReasons in internal/service/task.go).
+ //
+ // The auth exclusion above stands even for the one auth error a fresh
+ // session DOES cure — a resumed session whose persisted provider identity
+ // can no longer resolve its credentials (GH #6777). An adapter cannot tell
+ // that apart from a genuinely bad credential by looking at the error, so
+ // the judgement is made once, provider-agnostically, in
+ // shouldRetryWithFreshSession, where "was this run a resume?" is already
+ // known. Do not encode it here.
ResumeRejected bool
// codexInitializeRetrySafe is provider-internal evidence that an
// initialize timeout happened before semantic activity and after the
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index c100954e0a..80b382571f 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -3373,6 +3373,9 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
-- the only thing that keeps a wedged issue from resuming the same dead
-- session on its next trigger — there is no daemon upgrade to wait for.
-- Keep in sync with ResumeUnsafeFailure and GetLastChatTaskSession.
+ -- The phrase itself lives in taskfailure.AuthMethodUnresolved, which the
+ -- daemon's in-turn fresh-session retry reads (GH #6777). This guard stays
+ -- because it is the only protection for rows an older daemon wrote.
AND NOT (COALESCE(error, '') ILIKE '%could not resolve authentication method%')
AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 884235f1e8..9a188dff52 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -879,6 +879,9 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
-- text guard keeps the dead session from being replayed. This and
-- GetLastTaskSession must move together.
-- Keep in sync with ResumeUnsafeFailure and GetLastTaskSession.
+ -- The phrase itself lives in taskfailure.AuthMethodUnresolved, which the
+ -- daemon's in-turn fresh-session retry reads (GH #6777). This guard stays
+ -- because it is the only protection for rows an older daemon wrote.
AND NOT (COALESCE(error, '') ILIKE '%could not resolve authentication method%')
AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 649dcfce41..1872a49048 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -934,6 +934,9 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
-- the only thing that keeps a wedged issue from resuming the same dead
-- session on its next trigger — there is no daemon upgrade to wait for.
-- Keep in sync with ResumeUnsafeFailure and GetLastChatTaskSession.
+ -- The phrase itself lives in taskfailure.AuthMethodUnresolved, which the
+ -- daemon's in-turn fresh-session retry reads (GH #6777). This guard stays
+ -- because it is the only protection for rows an older daemon wrote.
AND NOT (COALESCE(error, '') ILIKE '%could not resolve authentication method%')
AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index edef4a6eb7..4a98ea7c40 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -1043,6 +1043,9 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
-- text guard keeps the dead session from being replayed. This and
-- GetLastTaskSession must move together.
-- Keep in sync with ResumeUnsafeFailure and GetLastTaskSession.
+ -- The phrase itself lives in taskfailure.AuthMethodUnresolved, which the
+ -- daemon's in-turn fresh-session retry reads (GH #6777). This guard stays
+ -- because it is the only protection for rows an older daemon wrote.
AND NOT (COALESCE(error, '') ILIKE '%could not resolve authentication method%')
AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
diff --git a/server/pkg/taskfailure/resume.go b/server/pkg/taskfailure/resume.go
index 9cbb6d4e8f..59d7a82487 100644
--- a/server/pkg/taskfailure/resume.go
+++ b/server/pkg/taskfailure/resume.go
@@ -1,6 +1,9 @@
package taskfailure
-import "regexp"
+import (
+ "regexp"
+ "strings"
+)
// UnresumableHistory reports whether an agent error means the conversation
// history itself can no longer be sent to the provider: a message already
@@ -39,6 +42,39 @@ func UnresumableHistory(errText string) bool {
return emptyContentRe.MatchString(errText) && historyMessageLocatorRe.MatchString(errText)
}
+// AuthMethodUnresolved reports whether an agent error is the provider
+// SDK refusing to resolve its own credentials — no api_key, no auth_token, and
+// no explicitly-omitted auth header. On a RESUMED session this is
+// deterministic rather than transient: the credential-bearing provider
+// identity lives in the session state the runtime rebuilt, so replaying the
+// same session reproduces the same error forever. A fresh session re-resolves
+// the provider from current config and succeeds (GH #6777).
+//
+// Deliberately the exact provider phrase and nothing looser. Every other
+// authentication-shaped error — an expired token, a revoked key, a 401 — is
+// about the credential itself and is NOT cured by a new session, so widening
+// this would discard healthy conversation pointers on failures a retry cannot
+// fix. Classify leaves this text as agent_error.unknown (resume-safe), which
+// is why the guard has to key on the text rather than the reason.
+//
+// This is the single source of truth for the phrase. Keep it in sync with the
+// GetLastTaskSession / GetLastChatTaskSession resume queries (pkg/db/queries),
+// which apply the same guard server-side so rows written by a daemon too old
+// to carry the in-turn retry are still excluded from resume.
+func AuthMethodUnresolved(errText string) bool {
+ if errText == "" {
+ return false
+ }
+ return strings.Contains(strings.ToLower(errText), authMethodUnresolvedPhrase)
+}
+
+// authMethodUnresolvedPhrase is the lowercase provider phrase
+// AuthMethodUnresolved matches. It appears verbatim in the runtime's error
+// however the failure reached us — session/resume, session/set_model or
+// session/prompt — because every ACP adapter wraps the underlying message
+// with %v rather than replacing it.
+const authMethodUnresolvedPhrase = "could not resolve authentication method"
+
// emptyContentRe matches the provider's complaint that a content field is
// empty, in the wordings observed across providers.
var emptyContentRe = regexp.MustCompile(`(?i)must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty`)
diff --git a/server/pkg/taskfailure/resume_test.go b/server/pkg/taskfailure/resume_test.go
index 35d69b8dfa..112e6f394b 100644
--- a/server/pkg/taskfailure/resume_test.go
+++ b/server/pkg/taskfailure/resume_test.go
@@ -144,3 +144,93 @@ func TestUnresumableHistoryIsStatusAndProviderAgnostic(t *testing.T) {
}
}
}
+
+// TestAuthMethodUnresolved pins the GH #6777 predicate. The positives are the
+// provider phrase as it reaches us through each ACP lifecycle step; the
+// negatives are every other authentication-shaped failure, which a fresh
+// session cannot cure and which must therefore keep its session pointer.
+func TestAuthMethodUnresolved(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ errMsg string
+ want bool
+ }{
+ {
+ // Verbatim from the reporter, as the ACP provider-error sniffer
+ // wraps it (GH #6777).
+ name: "gh6777 sniffer-wrapped provider error",
+ errMsg: `hermes provider error: "Could not resolve authentication method. Expected either api_key or auth_token to be set. Or for one of the X-Api-Key or Authorization headers to be explicitly omitted"`,
+ want: true,
+ },
+ {
+ // Same failure one step earlier: the adapter wraps the runtime
+ // message with %v instead of replacing it, so the phrase survives.
+ name: "set_model wrapper keeps the phrase",
+ errMsg: `hermes could not switch to model "custom:deepseek-v4-pro": session/set_model: Could not resolve authentication method. Expected either api_key or auth_token to be set.`,
+ want: true,
+ },
+ {
+ name: "case differences do not matter",
+ errMsg: "COULD NOT RESOLVE AUTHENTICATION METHOD",
+ want: true,
+ },
+ {
+ name: "empty error",
+ errMsg: "",
+ want: false,
+ },
+
+ // --- Negatives: authentication-shaped, but not session-shaped. A new
+ // session replays these verbatim, so matching them would cost a wasted
+ // run AND the conversation pointer. ---
+ {
+ name: "rejected api key",
+ errMsg: `hermes provider error: "401 authentication_error: invalid x-api-key"`,
+ want: false,
+ },
+ {
+ name: "revoked oauth token",
+ errMsg: "OAuth access token has been revoked",
+ want: false,
+ },
+ {
+ name: "missing credential env var",
+ errMsg: "missing environment variable: ANTHROPIC_API_KEY",
+ want: false,
+ },
+ {
+ // Talks about resolving and about auth, but is a DNS failure.
+ name: "unresolved host is not unresolved auth",
+ errMsg: "dial tcp: lookup auth.example.com: no such host",
+ want: false,
+ },
+ }
+
+ for _, tt := range cases {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ if got := AuthMethodUnresolved(tt.errMsg); got != tt.want {
+ t.Errorf("AuthMethodUnresolved(%q) = %v, want %v", tt.errMsg, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestAuthMethodUnresolvedMatchesResumeQueryGuard asserts the Go predicate and
+// the SQL guard in GetLastTaskSession / GetLastChatTaskSession agree on the
+// phrase. They are two independent implementations of the same rule — the
+// daemon's in-turn retry reads this one, and rows written by a daemon too old
+// to have it are caught by the SQL one — so a drift would leave one layer
+// resuming a session the other considers dead.
+func TestAuthMethodUnresolvedMatchesResumeQueryGuard(t *testing.T) {
+ t.Parallel()
+
+ // The ILIKE pattern the queries apply, minus the wildcards.
+ const sqlGuardPhrase = "could not resolve authentication method"
+
+ if !AuthMethodUnresolved("prefix " + sqlGuardPhrase + " suffix") {
+ t.Fatalf("predicate does not match the SQL guard phrase %q — pkg/db/queries and pkg/taskfailure have drifted", sqlGuardPhrase)
+ }
+}