Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): retire a Claude session after a safeguards refusal (MUL-10116) (#11536)
Bohan Jiang29095c286607
diff --git a/apps/docs/content/docs/tasks.fr.mdx b/apps/docs/content/docs/tasks.fr.mdxindex d8acfff718..bf2f749bac 100644--- a/apps/docs/content/docs/tasks.fr.mdx+++ b/apps/docs/content/docs/tasks.fr.mdx@@ -110,7 +110,7 @@ Les motifs d'échec affichés dans le journal d'exécution et dans les [Statisti| `timeout` | Dépassement de la limite de durée d'exécution configurée pour le daemon | Réduisez le périmètre de la tâche, ou ajustez `agent_timeout` du daemon || `iteration_limit` | Plafond d'itérations d'une exécution atteint | Réduisez le périmètre de la tâche || `agent_blocked` | L'agent a signalé qu'il ne peut pas continuer | Fournissez ce que son commentaire demande |-| `api_invalid_request` | L'API de la plateforme a rejeté une requête invalide | Relancez ; signalez le problème s'il se reproduit |+| `api_invalid_request` | L'API du modèle a refusé cette conversation : la requête a été jugée invalide (par exemple une image illisible), ou le modèle a refusé de répondre | La prochaine exécution démarre automatiquement une nouvelle session. Si la même demande est refusée à chaque fois, reformulez-la ou changez de modèle || `codex_semantic_inactivity` | Codex n'a produit aucune sortie utile pendant trop longtemps et a été jugé bloqué | Relancez, ou ajustez le délai d'inactivité de Codex |</Tab>diff --git a/apps/docs/content/docs/tasks.ja.mdx b/apps/docs/content/docs/tasks.ja.mdxindex d0e5035c34..f1915cebc1 100644--- a/apps/docs/content/docs/tasks.ja.mdx+++ b/apps/docs/content/docs/tasks.ja.mdx@@ -110,7 +110,7 @@ import { RunLifecycleDemo } from "@/components/demos/run-lifecycle-demo";| `timeout` | デーモンに設定された実行時間の上限を超えた | タスクの範囲を狭めるか、デーモンの `agent_timeout` を調整する || `iteration_limit` | 実行の反復回数の上限に達した | タスクの範囲を狭める || `agent_blocked` | エージェントが続行できないと自ら報告した | エージェントがコメントで求めた情報を補う |-| `api_invalid_request` | プラットフォーム API が不正なリクエストを拒否した | リトライし、繰り返し発生する場合は問題を報告する |+| `api_invalid_request` | モデル API がこの会話を拒否した。リクエストが無効と判定された(画像を読み取れないなど)か、モデルが回答を拒否した | 次回の実行は自動的に新しいセッションで始まる。同じリクエストが拒否され続ける場合は、言い換えるかモデルを変更する || `codex_semantic_inactivity` | Codex が長時間有効な出力を出さず、停滞と判定された | リトライするか、Codex の停滞タイムアウトを調整する |</Tab>diff --git a/apps/docs/content/docs/tasks.ko.mdx b/apps/docs/content/docs/tasks.ko.mdxindex 2cfbaccc1d..bb34bf87c7 100644--- a/apps/docs/content/docs/tasks.ko.mdx+++ b/apps/docs/content/docs/tasks.ko.mdx@@ -110,7 +110,7 @@ import { RunLifecycleDemo } from "@/components/demos/run-lifecycle-demo";| `timeout` | 데몬에 설정된 실행 시간 상한을 초과함 | 태스크 범위를 줄이거나 데몬의 `agent_timeout` 조정 || `iteration_limit` | 실행 반복 횟수 상한에 도달함 | 태스크 범위 축소 || `agent_blocked` | 에이전트가 계속 진행할 수 없다고 직접 보고함 | 댓글의 설명에 따라 정보 보충 |-| `api_invalid_request` | 플랫폼 API가 잘못된 요청을 거부함 | 재시도하고 반복되면 문제 신고 |+| `api_invalid_request` | 모델 API가 이 대화를 거부함. 요청이 유효하지 않다고 판단되었거나(예: 읽을 수 없는 이미지) 모델이 응답을 거부함 | 다음 실행은 자동으로 새 세션에서 시작됨. 같은 요청이 계속 거부되면 표현을 바꾸거나 모델을 변경 || `codex_semantic_inactivity` | Codex가 오랫동안 유효한 출력을 내지 않아 멈춘 것으로 판단됨 | 재시도하거나 Codex 정체 timeout 조정 |</Tab>diff --git a/apps/docs/content/docs/tasks.mdx b/apps/docs/content/docs/tasks.mdxindex 62bb298236..cec09d20fd 100644--- a/apps/docs/content/docs/tasks.mdx+++ b/apps/docs/content/docs/tasks.mdx@@ -110,7 +110,7 @@ The failure reasons shown in the execution log and [Analytics](/analytics#errors| `timeout` | Exceeded the daemon's configured execution time limit | Narrow the issue scope, or adjust the daemon's `agent_timeout` || `iteration_limit` | Hit the iteration cap for a run | Narrow the issue scope || `agent_blocked` | The agent reported it cannot proceed | Provide what its comment asked for |-| `api_invalid_request` | The platform API rejected an invalid request | Retry; report the problem if it recurs |+| `api_invalid_request` | The model API refused this conversation: the request was rejected as invalid (for example an unreadable image), or the model declined to answer | The next run starts a fresh session automatically. If the same request keeps being refused, rephrase it or switch models || `codex_semantic_inactivity` | Codex produced no meaningful output for too long and was judged stalled | Retry, or adjust the Codex inactivity timeout |</Tab>diff --git a/apps/docs/content/docs/tasks.zh-Hant.mdx b/apps/docs/content/docs/tasks.zh-Hant.mdxindex cad93aee85..a80460188e 100644--- a/apps/docs/content/docs/tasks.zh-Hant.mdx+++ b/apps/docs/content/docs/tasks.zh-Hant.mdx@@ -110,7 +110,7 @@ AI 代理自身返回的錯誤通常不會自動重試。鑑權失效、額度| `timeout` | 超過守護程序配置的執行時長上限 | 縮小任務範圍,或調整守護程序的 `agent_timeout` || `iteration_limit` | 達到執行輪次上限 | 縮小任務範圍 || `agent_blocked` | AI 代理主動報告無法繼續 | 按它在評論中的說明補充資訊 |-| `api_invalid_request` | 平臺 API 拒絕了非法請求 | 重試;反覆出現時報告問題 |+| `api_invalid_request` | 模型 API 拒絕了這段對話:請求被判為無效(例如圖片無法讀取),或模型拒絕回答 | 下一次執行會自動開啟新會話。如果同樣的請求一直被拒,換個說法或換個模型 || `codex_semantic_inactivity` | Codex 長時間無有效輸出被判停滯 | 重試,或調整 Codex 停滯超時 |</Tab>diff --git a/apps/docs/content/docs/tasks.zh.mdx b/apps/docs/content/docs/tasks.zh.mdxindex f115ca3231..207de3607b 100644--- a/apps/docs/content/docs/tasks.zh.mdx+++ b/apps/docs/content/docs/tasks.zh.mdx@@ -110,7 +110,7 @@ import { RunLifecycleDemo } from "@/components/demos/run-lifecycle-demo";| `timeout` | 超过守护进程配置的执行时长上限 | 缩小任务范围,或调整守护进程的 `agent_timeout` || `iteration_limit` | 达到执行轮次上限 | 缩小任务范围 || `agent_blocked` | 智能体主动报告无法继续 | 按它在评论中的说明补充信息 |-| `api_invalid_request` | 平台 API 拒绝了非法请求 | 重试;反复出现时报告问题 |+| `api_invalid_request` | 模型 API 拒绝了这段对话:请求被判为无效(例如图片无法读取),或模型拒绝回答 | 下一次运行会自动开启新会话。如果同样的请求一直被拒,换个说法或换个模型 || `codex_semantic_inactivity` | Codex 长时间无有效输出被判停滞 | 重试,或调整 Codex 停滞超时 |</Tab>diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.goindex ec152e44fb..44a30eef6e 100644--- a/server/internal/daemon/poisoned.go+++ b/server/internal/daemon/poisoned.go@@ -156,6 +156,16 @@ func classifyPoisonedError(errMsg string) (string, bool) {strings.Contains(lowered, "image.source.base64.data") {return FailureReasonAPIInvalidRequest, true}+ // A Claude safeguards refusal stays in the transcript, so resuming the+ // session sends the refused message again and is refused again. The+ // Claude backend recognises the refusal from structured fields and+ // reports it under this fixed marker; see claudeRefusalFailure. It is+ // filed under api_invalid_request because that reason already means "the+ // model API will not accept this conversation" and is on every resume+ // blacklist, so the next task starts a fresh session.+ if strings.HasPrefix(errMsg, agent.ClaudeModelRefusalMarker) {+ return FailureReasonAPIInvalidRequest, true+ }// Both markers must be present: "400" alone is too generic (a tool// could surface a 400 from anywhere) and "invalid_request_error"// alone could in theory appear in non-poisoning contexts. Thediff --git a/server/internal/daemon/poisoned_test.go b/server/internal/daemon/poisoned_test.goindex 729bdebfa9..13dc6e2dad 100644--- a/server/internal/daemon/poisoned_test.go+++ b/server/internal/daemon/poisoned_test.go@@ -169,6 +169,28 @@ func TestClassifyPoisonedError(t *testing.T) {wantOK: true,wantReason: FailureReasonAPIInvalidRequest,},+ {+ // MUL-10116: the Claude backend's refusal marker, as reported for+ // the captured Claude Code 2.1.280 resume. Every resume of a+ // refused session is refused again, so it must be retired.+ name: "claude safeguards refusal",+ errMsg: agent.ClaudeModelRefusalMarker + ": the model declined this conversation, and resuming the session would send the refused message again (API Error: Opus 5.5's safeguards flagged this message (https://www.anthropic.com/legal/aup).)",+ wantOK: true,+ wantReason: FailureReasonAPIInvalidRequest,+ },+ {+ // Only the backend's marker counts. Claude Code's own copy, or an+ // agent quoting it, keeps the session: a false positive would+ // throw away a healthy conversation.+ name: "refusal prose without the marker",+ errMsg: "API Error: Opus 5.5's safeguards flagged this message (https://www.anthropic.com/legal/aup). Try rephrasing the request in a new session or change your model.",+ wantOK: false,+ },+ {+ name: "marker quoted mid-message",+ errMsg: "tool failed: grep output mentioned " + agent.ClaudeModelRefusalMarker,+ wantOK: false,+ },{name: "case insensitive",errMsg: `api error: 400 {"type":"INVALID_REQUEST_ERROR"}`,@@ -414,3 +436,17 @@ func TestClassifyResumeUnsafeTimeout(t *testing.T) {})}}++// MUL-10116: the error the Claude backend reports for a refusal has to end in a+// failure reason the server refuses to resume, or the next comment on the+// issue resumes the refused session and is refused again.+func TestClaudeRefusalErrorRetiresSession(t *testing.T) {+ errMsg := agent.ClaudeModelRefusalMarker + ": the model declined this conversation (API Error: Opus 5.5's safeguards flagged this message)"+ reason, ok := classifyPoisonedError(errMsg)+ if !ok {+ t.Fatalf("refusal error %q was not classified", errMsg)+ }+ if !service.ResumeUnsafeFailure(reason, errMsg) {+ t.Fatalf("failure_reason %q must be resume-unsafe", reason)+ }+}diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex effc4c4514..64e0885418 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -440,6 +440,7 @@ type claudeTurn struct {sawResult boolresultIsError boolterminalReasonError string+ sawRefusalNoFallback boolsessionID stringlastUsageResult *claudeSDKMessagelastRawModelUsage map[string]TokenUsage@@ -487,6 +488,12 @@ func (t *claudeTurn) handleMessage(msg claudeSDKMessage) {if msg.SessionID != "" {t.sessionID = msg.SessionID}+ // Only the main thread's refusal decides the turn. A subagent's+ // refusal is reported back to the main thread as a tool result, and+ // the main thread's own result says how the turn ended.+ if msg.Subtype == claudeSubtypeModelRefusalNoFallback && msg.ParentToolUseID == "" {+ t.sawRefusalNoFallback = true+ }sid := t.sessionIDt.mu.Unlock()trySend(t.msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sid})@@ -518,6 +525,9 @@ func (t *claudeTurn) handleMessage(msg claudeSDKMessage) {t.finalResultText = msg.ResultTextt.resultIsError = msg.IsErrort.terminalReasonError = claudeTerminalReasonFailure(msg.TerminalReason, msg.ResultText)+ if t.terminalReasonError == "" {+ t.terminalReasonError = claudeRefusalFailure(msg.StopReason, t.sawRefusalNoFallback, msg.IsError, msg.ResultText)+ }if msg.SessionID != "" {t.sessionID = msg.SessionID}@@ -1016,11 +1026,14 @@ type claudeSDKMessage struct {// TerminalReason is Claude Code's structured statement of why the turn// ended. Read separately from IsError because the CLI computes the two// independently — see claudeTerminalReasonFailure.- TerminalReason string `json:"terminal_reason,omitempty"`- DurationMs float64 `json:"duration_ms,omitempty"`- NumTurns int `json:"num_turns,omitempty"`- Usage *claudeUsage `json:"usage,omitempty"`- ModelUsage map[string]claudeResultModelUsage `json:"modelUsage,omitempty"`+ TerminalReason string `json:"terminal_reason,omitempty"`+ // StopReason is the API stop_reason of the turn's last model response.+ // Read only to recognise a safeguards refusal — see claudeRefusalFailure.+ StopReason string `json:"stop_reason,omitempty"`+ DurationMs float64 `json:"duration_ms,omitempty"`+ NumTurns int `json:"num_turns,omitempty"`+ Usage *claudeUsage `json:"usage,omitempty"`+ ModelUsage map[string]claudeResultModelUsage `json:"modelUsage,omitempty"`// log fieldsLog *claudeLogEntry `json:"log,omitempty"`@@ -1100,6 +1113,54 @@ func claudeTerminalReasonFailure(terminalReason, resultText string) string {return msg}+// ClaudeModelRefusalMarker prefixes the error claudeRefusalFailure reports. It+// is fixed Multica prose, so the daemon can recognise the failure without+// depending on Claude Code's refusal copy, which changes between releases+// (2.1.263 writes "can't help with this", 2.1.280 "safeguards flagged this+// message").+const ClaudeModelRefusalMarker = "claude ended the turn with stop_reason=refusal"++// claudeSubtypeModelRefusalNoFallback is the system event Claude Code emits on+// the main thread when the model refused the turn and no fallback model+// answered it.+const claudeSubtypeModelRefusalNoFallback = "model_refusal_no_fallback"++// claudeRefusalFailure turns a safeguards refusal into an error naming it, and+// returns "" for every other turn.+//+// A refusal poisons the session. Claude Code keeps the refused user message in+// the transcript, so every --resume sends it to the API again and is refused+// again, whatever the new prompt says. A fresh session with the same new+// prompt is answered. Reproduced against Claude Code 2.1.263 and 2.1.280; the+// resumed frames are fixtured in+// testdata/claude-code-2.1.280-refusal-resume.jsonl. Before this the failure+// classified as agent_error.unknown, which no resume blacklist covers, so the+// next comment on the issue resumed the same session and failed the same way.+//+// Two structured signals, either is enough:+//+// - stop_reason=refusal on the result frame. The CLI copies the last model+// response's stop_reason there, so it is "end_turn" when a fallback model+// answered after the primary refused (fixtured in+// testdata/claude-code-2.1.280-refusal-fallback-answered.jsonl).+// - the model_refusal_no_fallback system event, when the result is an error.+// It covers a result frame that does not carry stop_reason.+//+// The daemon maps ClaudeModelRefusalMarker to a resume-unsafe failure reason+// (classifyPoisonedError), which retires the session so the next task starts+// fresh. The CLI's own text rides along for the user.+func claudeRefusalFailure(stopReason string, sawRefusalNoFallback, isError bool, resultText string) string {+ if strings.TrimSpace(stopReason) != "refusal" && !(sawRefusalNoFallback && isError) {+ return ""+ }+ msg := ClaudeModelRefusalMarker ++ ": the model declined this conversation, and resuming the session would send the refused message again"+ if detail := strings.TrimSpace(resultText); detail != "" {+ msg += " (" + detail + ")"+ }+ return msg+}+func claudeResultUsage(msg claudeSDKMessage, fallbackModel string) map[string]TokenUsage {usage, _ := claudeResultUsageSince(msg, fallbackModel, nil)return usagediff --git a/server/pkg/agent/claude_refusal_test.go b/server/pkg/agent/claude_refusal_test.gonew file mode 100644index 0000000000..570b6bf60c--- /dev/null+++ b/server/pkg/agent/claude_refusal_test.go@@ -0,0 +1,205 @@+package agent++import (+ "os"+ "runtime"+ "strings"+ "testing"+)++// claudeRefusalResumeFixture is the stream-json Claude Code 2.1.280 writes when+// a session whose first message was refused is resumed with an unrelated+// prompt. Captured by running the real CLI with the daemon's flags against an+// endpoint that returns stop_reason=refusal (stop_details.category=null)+// whenever the refused message is in the request; the resume sends it again,+// so the new prompt is refused too. Only the init frame's local tool/skill+// inventory and absolute paths were stripped.+const claudeRefusalResumeFixture = "testdata/claude-code-2.1.280-refusal-resume.jsonl"++// claudeRefusalFallbackAnsweredFixture is the counterpart: the primary model+// refused (category=cyber), Claude Code retried on its fallback model, and the+// fallback answered. The turn emits model_refusal_fallback, not+// model_refusal_no_fallback, and the result carries stop_reason=end_turn.+const claudeRefusalFallbackAnsweredFixture = "testdata/claude-code-2.1.280-refusal-fallback-answered.jsonl"++func TestClaudeRefusalFailure(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ stopReason string+ sawNoFall bool+ isError bool+ resultText string+ wantFailure bool+ }{+ {+ name: "stop_reason refusal on an error result",+ stopReason: "refusal",+ isError: true,+ resultText: "API Error: Opus 5.5's safeguards flagged this message",+ wantFailure: true,+ },+ {+ name: "stop_reason refusal without is_error still fails",+ stopReason: "refusal",+ wantFailure: true,+ },+ {+ name: "no-fallback event on an error result without stop_reason",+ // A result frame that does not carry stop_reason still has the+ // system event the CLI emits before it.+ sawNoFall: true,+ isError: true,+ resultText: "API Error: claude-opus-5-5 can't help with this.",+ wantFailure: true,+ },+ {+ name: "no-fallback event on a successful result is left alone",+ // Never observed; if a later step of the turn recovered, the+ // result decides.+ sawNoFall: true,+ stopReason: "end_turn",+ resultText: "Done.",+ },+ {+ name: "fallback model answered",+ stopReason: "end_turn",+ resultText: "OK",+ },+ {+ name: "an ordinary API error is left to is_error",+ stopReason: "",+ isError: true,+ resultText: "API Error: 529 overloaded",+ },+ {+ name: "a normal answer that talks about refusals",+ stopReason: "end_turn",+ resultText: "The model returned stop_reason=refusal, so I added a fallback.",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got := claudeRefusalFailure(tc.stopReason, tc.sawNoFall, tc.isError, tc.resultText)+ if (got != "") != tc.wantFailure {+ t.Fatalf("claudeRefusalFailure(%q, %v, %v, %q) = %q, wantFailure=%v",+ tc.stopReason, tc.sawNoFall, tc.isError, tc.resultText, got, tc.wantFailure)+ }+ if !tc.wantFailure {+ return+ }+ if !strings.HasPrefix(got, ClaudeModelRefusalMarker) {+ t.Fatalf("error must start with the refusal marker, got %q", got)+ }+ if tc.resultText != "" && !strings.Contains(got, tc.resultText) {+ t.Fatalf("the CLI's own wording must survive for the user; got %q", got)+ }+ })+ }+}++// TestClaudeExecuteReportsCapturedRefusal replays the captured resume. The run+// was already reported as failed before this change; what changed is the error+// text, which now names the refusal so the daemon retires the session instead+// of filing it as agent_error.unknown and resuming it on the next comment.+func TestClaudeExecuteReportsCapturedRefusal(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ frames, err := os.ReadFile(claudeRefusalResumeFixture)+ if err != nil {+ t.Fatalf("read captured frames: %v", err)+ }+ const sessionID = "d2c9a8fb-96d0-477c-bb9e-9f3e2261fe34"+ result := runClaudeFixture(t, string(frames), sessionID)++ if result.Status != "failed" {+ t.Fatalf("expected status=failed, got %q (output %q)", result.Status, result.Output)+ }+ if result.Output != "" {+ t.Fatalf("a refused run must publish no answer, got %q", result.Output)+ }+ if !strings.HasPrefix(result.Error, ClaudeModelRefusalMarker) {+ t.Fatalf("error should start with %q, got %q", ClaudeModelRefusalMarker, result.Error)+ }+ if !strings.Contains(result.Error, "safeguards flagged this message") {+ t.Fatalf("error should keep Claude Code's explanation for the user, got %q", result.Error)+ }+ // The id is needed to record which session the failure retires. The resume+ // itself was accepted, so this is not a rejected resume.+ if result.SessionID != sessionID {+ t.Fatalf("expected session id %q, got %q", sessionID, result.SessionID)+ }+ if result.ResumeRejected {+ t.Fatal("a refused turn on a resumed session is not a rejected resume")+ }+}++// TestClaudeExecuteKeepsRefusalAnsweredByFallback guards the other direction:+// when Claude Code's fallback model answers after the primary refused, the run+// is a normal success and its session stays resumable.+func TestClaudeExecuteKeepsRefusalAnsweredByFallback(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ frames, err := os.ReadFile(claudeRefusalFallbackAnsweredFixture)+ if err != nil {+ t.Fatalf("read captured frames: %v", err)+ }+ result := runClaudeFixture(t, string(frames), "")++ if result.Status != "completed" {+ t.Fatalf("expected status=completed, got %q (error %q)", result.Status, result.Error)+ }+ if result.Output != "OK" {+ t.Fatalf("expected the fallback model's answer, got %q", result.Output)+ }+ if result.Error != "" {+ t.Fatalf("expected no error, got %q", result.Error)+ }+}++// A model_refusal_no_fallback event only counts on the main thread. When a+// subagent was refused and the main thread later failed for an unrelated+// reason, the failure keeps its own text and the session is not retired.+func TestClaudeExecuteIgnoresSubagentRefusalEvent(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ const rateLimited = "API Error: 429 rate_limit_error"+ result := func(parent string) string {+ event := `{"type":"system","subtype":"model_refusal_no_fallback","session_id":"sess-sub","content":""`+ if parent != "" {+ event += `,"parent_tool_use_id":"` + parent + `"`+ }+ event += "}"+ return `{"type":"system","subtype":"init","session_id":"sess-sub"}` + "\n" ++ event + "\n" ++ `{"type":"result","subtype":"success","is_error":true,"terminal_reason":"api_error","session_id":"sess-sub","result":"` + rateLimited + `"}` + "\n"+ }++ sub := runClaudeFixture(t, result("toolu_subagent"), "")+ if sub.Status != "failed" {+ t.Fatalf("expected status=failed, got %q", sub.Status)+ }+ if strings.HasPrefix(sub.Error, ClaudeModelRefusalMarker) {+ t.Fatalf("a subagent's refusal must not mark the turn as refused, got %q", sub.Error)+ }+ if !strings.Contains(sub.Error, rateLimited) {+ t.Fatalf("the main thread's own error must be reported, got %q", sub.Error)+ }++ main := runClaudeFixture(t, result(""), "")+ if !strings.HasPrefix(main.Error, ClaudeModelRefusalMarker) {+ t.Fatalf("a main-thread refusal event on an error result must mark the turn as refused, got %q", main.Error)+ }+}diff --git a/server/pkg/agent/testdata/claude-code-2.1.280-refusal-fallback-answered.jsonl b/server/pkg/agent/testdata/claude-code-2.1.280-refusal-fallback-answered.jsonlnew file mode 100644index 0000000000..e666929f89--- /dev/null+++ b/server/pkg/agent/testdata/claude-code-2.1.280-refusal-fallback-answered.jsonl@@ -0,0 +1,14 @@+{"type":"system","subtype":"init","session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","model":"claude-opus-5-5","permissionMode":"bypassPermissions","apiKeySource":"ANTHROPIC_API_KEY","claude_code_version":"2.1.280"}+{"type":"system","subtype":"status","status":"requesting","session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","uuid":"14b6523c-d656-4f44-9c50-ff73e0ffcf28"}+{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg_mock_refusal","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}},"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","parent_tool_use_id":null,"uuid":"c383eebc-f4f7-46e1-aef3-ba6056c4a534","ttft_ms":3}+{"type":"system","subtype":"model_refusal_fallback","trigger":"refusal","direction":"retry","scope":"session","original_model":"claude-opus-5-5","fallback_model":"claude-opus-4-8","request_id":"req_011CfixtureRefusal","api_refusal_category":"cyber","api_refusal_explanation":"This request was declined because it could enable cyber harm.","retracted_message_uuids":[],"refused_user_message_uuid":"d74cf970-a882-4c1b-94df-56daf74a50e6","content":"Opus 5.5's safeguards flagged this session. You may be seeing this for the first time on an Opus model: Opus 5.5 is more capable and has stronger safeguards as a result, which can sometimes flag non-cybersecurity work. We're improving these safeguards to reduce the amount of incorrectly flagged messages. Opus 4.8 is answering instead, or you can edit and retry with Opus 5.5. You can learn more: https://support.claude.com/en/articles/8106465\n\nDetails: `[cyber]`","session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","uuid":"96588336-cdb8-4243-9778-2a570d4c6e70"}+{"type":"stream_event","event":{"type":"message_delta","context_management":null,"delta":{"container":null,"stop_details":null,"stop_reason":"refusal","stop_sequence":null},"usage":{"output_tokens_details":{"thinking_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":10,"iterations":[],"output_tokens":0,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0}}},"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","parent_tool_use_id":null,"uuid":"85e46549-1194-4ada-916c-22407eb33319"}+{"type":"stream_event","event":{"type":"message_stop"},"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","parent_tool_use_id":null,"uuid":"0986c692-38d9-495b-84b3-b2ba884fc56a"}+{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg_mock_refusal","type":"message","role":"assistant","model":"claude-opus-4-8","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}},"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","parent_tool_use_id":null,"uuid":"5302ffc3-2ace-4d29-a444-ba3f02cff664","ttft_ms":3}+{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}},"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","parent_tool_use_id":null,"uuid":"c56f727b-f65a-4daa-9430-90b6bb14db5d"}+{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"OK"}},"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","parent_tool_use_id":null,"uuid":"853013a1-b38f-41fe-a9a1-c8a27c500487"}+{"type":"assistant","message":{"id":"msg_mock_refusal","type":"message","role":"assistant","model":"claude-opus-4-8","content":[{"type":"text","text":"OK"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0},"context_management":null},"parent_tool_use_id":null,"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","uuid":"d90be33e-fbb9-4d17-844b-f5061b257879","timestamp":"2026-11-25T04:08:33.534Z","request_id":"req_011CfixtureRefusal"}+{"type":"stream_event","event":{"type":"content_block_stop","index":0},"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","parent_tool_use_id":null,"uuid":"2acdf374-d929-4579-a368-cbe963bbe86f"}+{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":5}},"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","parent_tool_use_id":null,"uuid":"333b6cb3-d418-40f1-b424-7d0b08ce622b"}+{"type":"stream_event","event":{"type":"message_stop"},"session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","parent_tool_use_id":null,"uuid":"2f334680-dad6-427d-ac5c-2ecd2c08eb60"}+{"duration_api_ms":15,"stop_reason":"end_turn","session_id":"d870b023-c166-40ae-8f23-bb948f5da3b4","total_cost_usd":0.000215,"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":5,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"modelUsage":{"claude-opus-5-5":{"inputTokens":10,"outputTokens":0,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":4e-05,"contextWindow":200000,"maxOutputTokens":128000,"thinkingTokens":0,"canonicalModel":"claude-opus-5-5","provider":"firstParty","costBasis":"list"},"claude-opus-4-8":{"inputTokens":10,"outputTokens":5,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.000175,"contextWindow":200000,"maxOutputTokens":64000,"thinkingTokens":0,"canonicalModel":"claude-opus-4-8","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"is_error":false,"num_turns":1,"subtype":"success","api_error_status":null,"result":"OK","ttft_ms":31,"type":"result","duration_ms":44,"uuid":"e4fb74b5-f56c-4f16-927c-c2332acb946a","ttft_stream_ms":24,"time_to_request_ms":21,"first_content_frame_ms":31,"queued_turn_count":0,"result_index":0}diff --git a/server/pkg/agent/testdata/claude-code-2.1.280-refusal-resume.jsonl b/server/pkg/agent/testdata/claude-code-2.1.280-refusal-resume.jsonlnew file mode 100644index 0000000000..7ceae7932d--- /dev/null+++ b/server/pkg/agent/testdata/claude-code-2.1.280-refusal-resume.jsonl@@ -0,0 +1,8 @@+{"type":"system","subtype":"init","session_id":"d2c9a8fb-96d0-477c-bb9e-9f3e2261fe34","model":"claude-opus-5-5","permissionMode":"bypassPermissions","apiKeySource":"ANTHROPIC_API_KEY","claude_code_version":"2.1.280"}+{"type":"system","subtype":"status","status":"requesting","session_id":"d2c9a8fb-96d0-477c-bb9e-9f3e2261fe34","uuid":"3499a033-dbe9-49dd-8e9d-e4a5afda848f"}+{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg_mock_refusal","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}},"session_id":"d2c9a8fb-96d0-477c-bb9e-9f3e2261fe34","parent_tool_use_id":null,"uuid":"121e5572-c42c-491d-92dc-300fd272d054","ttft_ms":4}+{"type":"system","subtype":"model_refusal_no_fallback","uuid":"e26d7235-19e5-4d3b-b624-fb3a38c46d55","original_model":"claude-opus-5-5","request_id":"req_011CfixtureRefusal","api_refusal_category":null,"api_refusal_explanation":null,"refused_user_message_uuid":"000c0fae-349d-4c13-a593-6588242e78aa","content":"","session_id":"d2c9a8fb-96d0-477c-bb9e-9f3e2261fe34"}+{"type":"assistant","message":{"diagnostics":null,"id":"fb2fa590-ded4-4267-a72e-98fe5abfcaf9","container":null,"model":"<synthetic>","role":"assistant","stop_details":{"type":"refusal","category":null,"explanation":null},"stop_reason":"refusal","stop_sequence":"","type":"message","usage":{"output_tokens_details":null,"input_tokens":0,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":null,"cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":null,"iterations":null,"speed":null},"content":[{"type":"text","text":"API Error: Opus 5.5's safeguards flagged this message (https://www.anthropic.com/legal/aup). This sometimes happens with safe, normal conversations. Claude Code can't respond to this message with Opus 5.5.\n\nTry rephrasing the request in a new session or change your model.\n\nLearn more: https://support.claude.com/en/articles/8106465\n\nRequest ID: req_011CfixtureRefusal"}],"context_management":null},"parent_tool_use_id":null,"session_id":"d2c9a8fb-96d0-477c-bb9e-9f3e2261fe34","uuid":"4b7a10da-10ac-4396-bddb-f1e4edf3517a","timestamp":"2026-11-25T04:08:32.588Z","error":"invalid_request","request_id":"req_011CfixtureRefusal","is_api_error_message":true}+{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"refusal","stop_sequence":null,"stop_details":{"type":"refusal","category":null,"explanation":null}},"usage":{"output_tokens":0}},"session_id":"d2c9a8fb-96d0-477c-bb9e-9f3e2261fe34","parent_tool_use_id":null,"uuid":"22f47bbe-26aa-429e-a277-d46d3be270dc"}+{"type":"stream_event","event":{"type":"message_stop"},"session_id":"d2c9a8fb-96d0-477c-bb9e-9f3e2261fe34","parent_tool_use_id":null,"uuid":"34fd122e-e1d8-4406-b883-5adf200dde52"}+{"duration_api_ms":13,"stop_reason":"refusal","session_id":"d2c9a8fb-96d0-477c-bb9e-9f3e2261fe34","total_cost_usd":8e-05,"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"modelUsage":{"claude-opus-5-5":{"inputTokens":20,"outputTokens":0,"thinkingTokens":0,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":8e-05,"contextWindow":200000,"maxOutputTokens":128000,"canonicalModel":"claude-opus-5-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"api_error","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"is_error":true,"num_turns":1,"subtype":"success","api_error_status":null,"result":"API Error: Opus 5.5's safeguards flagged this message (https://www.anthropic.com/legal/aup). This sometimes happens with safe, normal conversations. Claude Code can't respond to this message with Opus 5.5.\n\nTry rephrasing the request in a new session or change your model.\n\nLearn more: https://support.claude.com/en/articles/8106465\n\nRequest ID: req_011CfixtureRefusal","type":"result","duration_ms":27,"uuid":"fab0c70b-e41a-49ff-b7d9-9f72070aae98","queued_turn_count":0,"result_index":0}