diff --git a/internal/runtime/executor/claude_executor.go b/internal/runtime/executor/claude_executor.go index a6be4b33e4..4deffd6a25 100644 --- a/internal/runtime/executor/claude_executor.go +++ b/internal/runtime/executor/claude_executor.go @@ -14,6 +14,7 @@ import ( "github.com/MoeForge/moego/ojson" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" sigcompat "github.com/router-for-me/CLIProxyAPI/v8/internal/signature" "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" @@ -38,6 +39,7 @@ type ClaudeExecutor struct { // constructors allocate it so copies made per request reuse one store. oauthToolAliases *claudeOAuthToolAliasStore threadBetas *helps.ClaudeThreadBetaStore + advisorOwners *helps.ClaudeAdvisorOwnerStore } type claudeOAuthCancellationError struct { @@ -396,7 +398,51 @@ func stripTranslatedDefaultMaxTokens(from sdktranslator.Format, originalPayload, } func NewClaudeExecutor(cfg *config.Config) *ClaudeExecutor { - return &ClaudeExecutor{cfg: cfg, oauthToolAliases: &claudeOAuthToolAliasStore{}, threadBetas: &helps.ClaudeThreadBetaStore{}} + return &ClaudeExecutor{ + cfg: cfg, + oauthToolAliases: &claudeOAuthToolAliasStore{}, + threadBetas: &helps.ClaudeThreadBetaStore{}, + advisorOwners: helps.NewClaudeAdvisorOwnerStore(), + } +} + +func (e *ClaudeExecutor) claudeAdvisorOwnerStore() *helps.ClaudeAdvisorOwnerStore { + claudeOAuthToolAliasStoreInitMu.Lock() + defer claudeOAuthToolAliasStoreInitMu.Unlock() + if e.advisorOwners == nil { + e.advisorOwners = helps.NewClaudeAdvisorOwnerStore() + } + return e.advisorOwners +} + +func claudeAdvisorCredentialOwner(auth *cliproxyauth.Auth, apiKey string) string { + if identity := claudeDiagnosticsCredentialIdentity(auth); identity != "" { + return identity + } + if key := strings.TrimSpace(apiKey); key != "" { + return "key:" + kvstore.HashKeyPart(key) + } + return "" +} + +func (e *ClaudeExecutor) stripForeignClaudeAdvisorBlocksDoc(ctx context.Context, auth *cliproxyauth.Auth, apiKey string, doc *ojson.Doc) *helps.ClaudeAdvisorRequestState { + if e == nil || doc == nil { + return nil + } + owner := claudeAdvisorCredentialOwner(auth, apiKey) + if owner == "" { + return nil + } + scope := e.upstreamRequestLogProvider() + state, stripped := e.claudeAdvisorOwnerStore().StripForeignAdvisorBlocksDoc(ctx, doc, scope, owner) + if stripped > 0 { + helps.LogWithRequestID(ctx).WithFields(log.Fields{ + "component": "advisor_sanitizer", + "executor": scope, + "stripped_blocks": stripped, + }).Debug("claude executor: stripped foreign advisor blocks before upstream") + } + return state } func (e *ClaudeExecutor) prepareClaudeThreadBetas(ctx context.Context, request *http.Request, auth *cliproxyauth.Auth, body []byte, extraBetas []string, payloadBetasConfigured bool, incomingHeaders http.Header, uncloak bool, metadataSets ...map[string]any) (*helps.ClaudeThreadBetaRequest, error) { diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index 5bd2e31f4a..9390136b20 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -101,6 +101,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r if rebuildMidSystemMessageEnabled(e.cfg, auth) { rebuildMidSystemMessagesToTopLevelDoc(doc) } + advisorState := e.stripForeignClaudeAdvisorBlocksDoc(ctx, auth, apiKey, doc) // Apply cloaking (system prompt injection, fake user ID, sensitive word obfuscation) // based on client type and configuration. @@ -262,6 +263,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r bodyForUpstream := doc.Bytes() body = bodyForUpstream bodyForTranslation := bodyForUpstream + advisorState.FilterUnknownIDsFromFinalBody(bodyForUpstream) if cchSigning { bodyForUpstream, err = signAnthropicMessagesBody(bodyForUpstream) if err != nil { @@ -439,6 +441,12 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r return resp, errRefusal } } + advisorState.RecordAccepted() + if upstreamStream { + advisorState.RecordResponseSSE(data) + } else { + advisorState.RecordResponseJSON(data) + } data = e.restoreResponseModel(data, req.Model) helps.RecordClaudeWebSearchResultsContext(ctx, webSearchSessionKey, data, webSearchTTL, webSearchLimit) cacheClaudeThinkingReplayResponse(ctx, replayScope, data) diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index 4de4be93db..cb63d6d637 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -106,6 +106,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if rebuildMidSystemMessageEnabled(e.cfg, auth) { rebuildMidSystemMessagesToTopLevelDoc(doc) } + advisorState := e.stripForeignClaudeAdvisorBlocksDoc(ctx, auth, apiKey, doc) // Apply cloaking (system prompt injection, fake user ID, sensitive word obfuscation) // based on client type and configuration. @@ -256,6 +257,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A bodyForUpstream := doc.Bytes() body = bodyForUpstream bodyForTranslation := bodyForUpstream + advisorState.FilterUnknownIDsFromFinalBody(bodyForUpstream) if cchSigning { bodyForUpstream, err = signAnthropicMessagesBody(bodyForUpstream) if err != nil { @@ -434,6 +436,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return } line = e.restoreResponseModel(restoredLine, req.Model) + advisorState.ObserveSSELine(line) event.Write(line) event.WriteByte('\n') if len(bytes.TrimSpace(line)) == 0 { @@ -506,6 +509,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return } line = e.restoreResponseModel(restoredLine, req.Model) + advisorState.ObserveSSELine(line) helps.RecordClaudeWebSearchResultsContext(ctx, webSearchSessionKey, line, webSearchTTL, webSearchLimit) chunks := sdktranslator.TranslateStream( ctx, diff --git a/internal/runtime/executor/claude_executor_tokens.go b/internal/runtime/executor/claude_executor_tokens.go index 9a872bc5df..fe94084802 100644 --- a/internal/runtime/executor/claude_executor_tokens.go +++ b/internal/runtime/executor/claude_executor_tokens.go @@ -196,6 +196,7 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy if rebuildMidSystemMessageEnabled(e.cfg, auth) { rebuildMidSystemMessagesToTopLevelDoc(doc) } + _ = e.stripForeignClaudeAdvisorBlocksDoc(ctx, auth, apiKey, doc) directAnthropic := isAnthropicUpstreamBase(baseURL) // Claude Code's count_tokens carries only model, messages and tools, so the diff --git a/internal/runtime/executor/claude_issue7638_test.go b/internal/runtime/executor/claude_issue7638_test.go new file mode 100644 index 0000000000..199b169892 --- /dev/null +++ b/internal/runtime/executor/claude_issue7638_test.go @@ -0,0 +1,769 @@ +package executor + +import ( + "context" + "fmt" + "io" + "net/http" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func claudeIssue7638OAuthAuth(id, token, accountUUID string) *cliproxyauth.Auth { + return &cliproxyauth.Auth{ + ID: id, + Provider: "claude", + Status: cliproxyauth.StatusActive, + Metadata: map[string]any{ + "access_token": token, + "account_uuid": accountUUID, + }, + } +} + +func claudeIssue7638JSONResponse(req *http.Request, body string) *http.Response { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + } +} + +func claudeIssue7638SSEResponse(req *http.Request, events string) *http.Response { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(events)), + Request: req, + } +} + +func claudeIssue7638AdvisorMintJSON(id, text string) string { + return fmt.Sprintf(`{ + "id": "msg_%s", + "type": "message", + "role": "assistant", + "model": "claude-opus-5-5", + "content": [ + {"type": "server_tool_use", "id": %q, "name": "advisor", "input": {}}, + {"type": "advisor_tool_result", "tool_use_id": %q, "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_%s"}}, + {"type": "text", "text": %q} + ], + "stop_reason": "end_turn", + "usage": {"input_tokens": 10, "output_tokens": 20} + }`, id, id, id, id, text) +} + +func claudeIssue7638AdvisorMintSSE(id, text string) string { + return fmt.Sprintf( + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_%s\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-opus-5-5\",\"content\":[],\"stop_reason\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0}}}\n\n"+ + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"server_tool_use\",\"id\":%q,\"name\":\"advisor\",\"input\":{}}}\n\n"+ + "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n"+ + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"advisor_tool_result\",\"tool_use_id\":%q,\"content\":{\"type\":\"advisor_redacted_result\",\"encrypted_content\":\"enc_%s\"}}}\n\n"+ + "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":1}\n\n"+ + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":2,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n"+ + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":2,\"delta\":{\"type\":\"text_delta\",\"text\":%q}}\n\n"+ + "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":2}\n\n"+ + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":20}}\n\n"+ + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + id, id, id, id, text, + ) +} + +func TestClaudeIssue7638_ExecuteStripsForeignAdvisorBlocksAndPreservesOwn(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + var captured [][]byte + callIdx := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, _ := io.ReadAll(req.Body) + captured = append(captured, body) + callIdx++ + switch callIdx { + case 1: + return claudeIssue7638JSONResponse(req, claudeIssue7638AdvisorMintJSON("srvtoolu_adv_a", "from A")), nil + case 2: + return claudeIssue7638JSONResponse(req, claudeIssue7638AdvisorMintJSON("srvtoolu_adv_b", "from B")), nil + default: + return claudeIssue7638JSONResponse(req, `{"id":"msg_3","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"done"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`), nil + } + }) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + exec := NewClaudeExecutor(&config.Config{}) + authA := claudeIssue7638OAuthAuth("cred-a", "sk-ant-oat-a", "11111111-1111-4111-8111-111111111111") + authB := claudeIssue7638OAuthAuth("cred-b", "sk-ant-oat-b", "22222222-2222-4222-8222-222222222222") + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude} + + // Turn 1 on A: mints srvtoolu_adv_a. + turn1 := []byte(`{"model":"claude-opus-5-5","max_tokens":256,"messages":[{"role":"user","content":"turn 1"}]}`) + if _, err := exec.Execute(ctx, authA, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: turn1}, opts); err != nil { + t.Fatalf("turn 1 Execute() error = %v", err) + } + + // Turn 2 on B: replays A's advisor blocks (must be stripped) and mints srvtoolu_adv_b. + turn2 := []byte(`{ + "model": "claude-opus-5-5", + "max_tokens": 256, + "messages": [ + {"role": "user", "content": "turn 1"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_adv_a", "name": "advisor", "input": {}}, + {"type": "advisor_tool_result", "tool_use_id": "srvtoolu_adv_a", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_a"}}, + {"type": "text", "text": "from A"} + ] + }, + {"role": "user", "content": "turn 2"} + ] + }`) + if _, err := exec.Execute(ctx, authB, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: turn2}, opts); err != nil { + t.Fatalf("turn 2 Execute() error = %v", err) + } + + if strings.Contains(string(captured[1]), "srvtoolu_adv_a") { + t.Fatalf("turn 2 sent foreign advisor block srvtoolu_adv_a to cred-b: %s", captured[1]) + } + if !strings.Contains(string(captured[1]), "from A") { + t.Fatalf("turn 2 dropped non-advisor text block: %s", captured[1]) + } + + // Turn 3 on B: replays both A's (foreign) and B's (own) advisor blocks. + turn3 := []byte(`{ + "model": "claude-opus-5-5", + "max_tokens": 256, + "messages": [ + {"role": "user", "content": "turn 1"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_adv_a", "name": "advisor", "input": {}}, + {"type": "advisor_tool_result", "tool_use_id": "srvtoolu_adv_a", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_a"}}, + {"type": "text", "text": "from A"} + ] + }, + {"role": "user", "content": "turn 2"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_adv_b", "name": "advisor", "input": {}}, + {"type": "advisor_tool_result", "tool_use_id": "srvtoolu_adv_b", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_b"}}, + {"type": "text", "text": "from B"} + ] + }, + {"role": "user", "content": "turn 3"} + ] + }`) + if _, err := exec.Execute(ctx, authB, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: turn3}, opts); err != nil { + t.Fatalf("turn 3 Execute() error = %v", err) + } + + if strings.Contains(string(captured[2]), "srvtoolu_adv_a") { + t.Fatalf("turn 3 sent foreign advisor block srvtoolu_adv_a to cred-b: %s", captured[2]) + } + if !strings.Contains(string(captured[2]), "srvtoolu_adv_b") { + t.Fatalf("turn 3 stripped cred-b's own advisor block srvtoolu_adv_b: %s", captured[2]) + } +} + +func TestClaudeIssue7638_ExecuteStreamTracksMintedAdvisorAndStripsOnRebind(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + var captured [][]byte + callIdx := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, _ := io.ReadAll(req.Body) + captured = append(captured, body) + callIdx++ + if callIdx == 1 { + return claudeIssue7638SSEResponse(req, claudeIssue7638AdvisorMintSSE("srvtoolu_stream_a", "stream from A")), nil + } + return claudeIssue7638SSEResponse(req, + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_s2\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-opus-5-5\",\"content\":[],\"stop_reason\":null,\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n"+ + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n"+ + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\n"+ + "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n"+ + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":1}}\n\n"+ + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + ), nil + }) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + exec := NewClaudeExecutor(&config.Config{}) + authA := claudeIssue7638OAuthAuth("cred-stream-a", "sk-ant-oat-sa", "11111111-1111-4111-8111-111111111112") + authB := claudeIssue7638OAuthAuth("cred-stream-b", "sk-ant-oat-sb", "22222222-2222-4222-8222-222222222223") + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Stream: true} + + // Turn 1 streaming on A: mints srvtoolu_stream_a. + res1, err := exec.ExecuteStream(ctx, authA, cliproxyexecutor.Request{ + Model: "claude-opus-5-5", + Payload: []byte(`{"model":"claude-opus-5-5","max_tokens":256,"stream":true,"messages":[{"role":"user","content":"turn 1"}]}`), + }, opts) + if err != nil { + t.Fatalf("turn 1 ExecuteStream() error = %v", err) + } + for chunk := range res1.Chunks { + if chunk.Err != nil { + t.Fatalf("turn 1 chunk error = %v", chunk.Err) + } + } + + // Turn 2 streaming on B: foreign advisor turns (containing ONLY advisor blocks) must be dropped completely. + turn2 := []byte(`{ + "model": "claude-opus-5-5", + "max_tokens": 256, + "stream": true, + "messages": [ + {"role": "user", "content": "turn 1"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_stream_a", "name": "advisor", "input": {}} + ] + }, + { + "role": "user", + "content": [ + {"type": "advisor_tool_result", "tool_use_id": "srvtoolu_stream_a", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_sa"}} + ] + }, + {"role": "assistant", "content": "stream from A"}, + {"role": "user", "content": "turn 2"} + ] + }`) + res2, err := exec.ExecuteStream(ctx, authB, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: turn2}, opts) + if err != nil { + t.Fatalf("turn 2 ExecuteStream() error = %v", err) + } + for chunk := range res2.Chunks { + if chunk.Err != nil { + t.Fatalf("turn 2 chunk error = %v", chunk.Err) + } + } + + if strings.Contains(string(captured[1]), "srvtoolu_stream_a") { + t.Fatalf("turn 2 stream sent foreign advisor block to cred-stream-b: %s", captured[1]) + } + // The two advisor-only turns must be dropped rather than leaving empty content arrays. + for _, msg := range ojson.GetBytes(captured[1], "messages").Array() { + content := msg.Get("content") + if content.IsArray() && len(content.Array()) == 0 { + t.Fatalf("turn 2 stream left empty content array in messages: %s", captured[1]) + } + } +} + +func TestClaudeIssue7638_InRequestFailover429StripsForeignAdvisorOnRetry(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + var mu sync.Mutex + var attempts []struct { + authHeader string + body []byte + } + turn := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, _ := io.ReadAll(req.Body) + authHeader := req.Header.Get("Authorization") + mu.Lock() + attempts = append(attempts, struct { + authHeader string + body []byte + }{authHeader: authHeader, body: body}) + turn++ + cur := turn + mu.Unlock() + switch cur { + case 1: + // Turn 1 on A mints srvtoolu_failover. + return claudeIssue7638JSONResponse(req, claudeIssue7638AdvisorMintJSON("srvtoolu_failover", "advice")), nil + case 2: + // Turn 2 first lands on A, which returns 429 to trigger in-request failover to B. + return &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"type":"error","error":{"type":"rate_limit_error","message":"rate limited"}}`)), + Request: req, + }, nil + default: + // Retry on B must receive cleaned body without srvtoolu_failover. + if strings.Contains(string(body), "srvtoolu_failover") { + return &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"type":"error","error":{"type":"invalid_request_error","message":"Advisor tool result content could not be processed."}}`)), + Request: req, + }, nil + } + return claudeIssue7638JSONResponse(req, `{"id":"msg_ok","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"recovered"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`), nil + } + }) + + manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil) + manager.SetRetryConfig(2, 0, 0) + manager.RegisterExecutor(NewClaudeExecutor(&config.Config{})) + authA := claudeIssue7638OAuthAuth("cred-issue7638-a", "sk-ant-oat-a", "11111111-1111-4111-8111-111111111111") + authB := claudeIssue7638OAuthAuth("cred-issue7638-b", "sk-ant-oat-b", "22222222-2222-4222-8222-222222222222") + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authA.ID, "claude", []*registry.ModelInfo{{ID: "claude-opus-5-5"}}) + reg.RegisterClient(authB.ID, "claude", []*registry.ModelInfo{{ID: "claude-opus-5-5"}}) + t.Cleanup(func() { + reg.UnregisterClient(authA.ID) + reg.UnregisterClient(authB.ID) + }) + if _, err := manager.Register(context.Background(), authA); err != nil { + t.Fatal(err) + } + if _, err := manager.Register(context.Background(), authB); err != nil { + t.Fatal(err) + } + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude} + + // Turn 1: A serves and mints srvtoolu_failover. + if _, err := manager.Execute(ctx, []string{"claude"}, cliproxyexecutor.Request{ + Model: "claude-opus-5-5", + Payload: []byte(`{"model":"claude-opus-5-5","max_tokens":256,"messages":[{"role":"user","content":"turn 1"}]}`), + }, opts); err != nil { + t.Fatalf("turn 1 manager.Execute() error = %v", err) + } + + // Turn 2: A returns 429 -> Manager fails over to B -> B must succeed with stripped body. + turn2 := []byte(`{ + "model": "claude-opus-5-5", + "max_tokens": 256, + "messages": [ + {"role": "user", "content": "turn 1"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_failover", "name": "advisor", "input": {}}, + {"type": "advisor_tool_result", "tool_use_id": "srvtoolu_failover", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_f"}}, + {"type": "text", "text": "advice"} + ] + }, + {"role": "user", "content": "turn 2"} + ] + }`) + if _, err := manager.Execute(ctx, []string{"claude"}, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: turn2}, opts); err != nil { + t.Fatalf("turn 2 failover manager.Execute() error = %v", err) + } + + mu.Lock() + defer mu.Unlock() + if len(attempts) != 3 { + t.Fatalf("expected 3 upstream attempts (turn1-A, turn2-A-429, turn2-B-200), got %d", len(attempts)) + } + if !strings.Contains(string(attempts[1].body), "srvtoolu_failover") { + t.Fatalf("attempt on original owner A unexpectedly stripped its own advisor block: %s", attempts[1].body) + } + if strings.Contains(string(attempts[2].body), "srvtoolu_failover") { + t.Fatalf("failover attempt on B still contained foreign advisor block: %s", attempts[2].body) + } +} + +func TestClaudeIssue7638_CountTokensAndKVPersistenceAcrossRestart(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + kvPath := filepath.Join(t.TempDir(), "kv.db") + if errCfg := kvstore.ConfigureLocal(true, kvPath); errCfg != nil { + t.Fatal(errCfg) + } + t.Cleanup(func() { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Error(errShutdown) + } + }) + + var captured [][]byte + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, _ := io.ReadAll(req.Body) + captured = append(captured, body) + if strings.Contains(req.URL.Path, "count_tokens") { + return claudeIssue7638JSONResponse(req, `{"input_tokens":42}`), nil + } + return claudeIssue7638JSONResponse(req, claudeIssue7638AdvisorMintJSON("srvtoolu_persist", "persisted")), nil + }) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + authA := claudeIssue7638OAuthAuth("cred-persist-a", "sk-ant-oat-pa", "11111111-1111-4111-8111-111111111113") + authB := claudeIssue7638OAuthAuth("cred-persist-b", "sk-ant-oat-pb", "22222222-2222-4222-8222-222222222224") + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude} + + exec1 := NewClaudeExecutor(&config.Config{}) + if _, err := exec1.Execute(ctx, authA, cliproxyexecutor.Request{ + Model: "claude-opus-5-5", + Payload: []byte(`{"model":"claude-opus-5-5","max_tokens":256,"messages":[{"role":"user","content":"turn 1"}]}`), + }, opts); err != nil { + t.Fatalf("exec1.Execute() error = %v", err) + } + + // Simulate proxy restart: close & reopen KV store and allocate a brand-new ClaudeExecutor. + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + if errCfg := kvstore.ConfigureLocal(true, kvPath); errCfg != nil { + t.Fatal(errCfg) + } + exec2 := NewClaudeExecutor(&config.Config{}) + + replayPayload := []byte(`{ + "model": "claude-opus-5-5", + "max_tokens": 256, + "messages": [ + {"role": "user", "content": "turn 1"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_persist", "name": "advisor", "input": {}}, + {"type": "advisor_tool_result", "tool_use_id": "srvtoolu_persist", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_p"}}, + {"type": "text", "text": "persisted"} + ] + }, + {"role": "user", "content": "turn 2"} + ] + }`) + + if _, err := exec2.CountTokens(ctx, authB, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: replayPayload}, opts); err != nil { + t.Fatalf("exec2.CountTokens() error = %v", err) + } + if strings.Contains(string(captured[1]), "srvtoolu_persist") { + t.Fatalf("post-restart CountTokens on cred-persist-b still contained foreign advisor block: %s", captured[1]) + } + + if _, err := exec2.Execute(ctx, authB, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: replayPayload}, opts); err != nil { + t.Fatalf("exec2.Execute() error = %v", err) + } + if strings.Contains(string(captured[2]), "srvtoolu_persist") { + t.Fatalf("post-restart Execute on cred-persist-b still contained foreign advisor block: %s", captured[2]) + } +} + +func TestClaudeIssue7638_AllAdvisorBlockShapesAndRequestFallbackLearning(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + var captured [][]byte + callIdx := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, _ := io.ReadAll(req.Body) + captured = append(captured, body) + callIdx++ + if callIdx == 1 { + // Failed 400 on B must NOT record B as the owner of srvtoolu_pre. + return &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"type":"error","error":{"type":"invalid_request_error","message":"Advisor tool result content could not be processed."}}`)), + Request: req, + }, nil + } + return claudeIssue7638JSONResponse(req, `{"id":"msg_ok","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`), nil + }) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + exec := NewClaudeExecutor(&config.Config{}) + authA := claudeIssue7638OAuthAuth("cred-shape-a", "sk-ant-oat-sha", "11111111-1111-4111-8111-111111111114") + authB := claudeIssue7638OAuthAuth("cred-shape-b", "sk-ant-oat-shb", "22222222-2222-4222-8222-222222222225") + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude} + + payload := []byte(`{ + "model": "claude-opus-5-5", + "max_tokens": 256, + "messages": [ + {"role": "user", "content": "start"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_pre", "name": "advisor", "input": {}}, + {"type": "server_tool_use", "id": "srvtoolu_ws", "name": "web_search", "input": {"query": "go"}}, + {"type": "tool_use", "id": "toolu_mix", "name": "custom_tool", "input": {}} + ] + }, + { + "role": "user", + "content": [ + {"type": "advisor_redacted_result", "tool_use_id": "srvtoolu_pre", "encrypted_content": "enc_redacted"}, + {"type": "tool_result", "tool_use_id": "srvtoolu_pre", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_obj"}}, + { + "type": "tool_result", + "tool_use_id": "toolu_mix", + "content": [ + {"type": "text", "text": "keep tool output"}, + {"type": "advisor_redacted_result", "encrypted_content": "enc_mixed"} + ] + } + ] + }, + {"role": "user", "content": "next"} + ] + }`) + + // Call 1: B fails with 400 -> must NOT claim ownership of srvtoolu_pre or toolu_mix. + if _, err := exec.Execute(ctx, authB, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: payload}, opts); err == nil { + t.Fatal("expected 400 error on first attempt") + } + + // Call 2: A succeeds with 200 -> A learns ownership of srvtoolu_pre and toolu_mix via 2xx request fallback. + if _, err := exec.Execute(ctx, authA, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: payload}, opts); err != nil { + t.Fatalf("A Execute() error = %v", err) + } + + // Call 3: B retries -> foreign advisor blocks stripped; web_search and non-advisor tool_result text kept! + if _, err := exec.Execute(ctx, authB, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: payload}, opts); err != nil { + t.Fatalf("B Execute() error = %v", err) + } + + bodyB := string(captured[2]) + if strings.Contains(bodyB, "srvtoolu_pre") || strings.Contains(bodyB, "enc_redacted") || strings.Contains(bodyB, "enc_obj") || strings.Contains(bodyB, "enc_mixed") { + t.Fatalf("B still received foreign advisor blocks: %s", bodyB) + } + if !strings.Contains(bodyB, "srvtoolu_ws") { + t.Fatalf("non-advisor web_search server_tool_use was wrongly stripped: %s", bodyB) + } + if !strings.Contains(bodyB, "toolu_mix") || !strings.Contains(bodyB, "keep tool output") { + t.Fatalf("mixed tool_result non-advisor text was wrongly stripped: %s", bodyB) + } +} +func TestClaudeIssue7638_ForAPIKeyAndWithConfigShareAdvisorOwnerStore(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + var captured [][]byte + callIdx := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, _ := io.ReadAll(req.Body) + captured = append(captured, body) + callIdx++ + if callIdx == 1 { + return claudeIssue7638JSONResponse(req, claudeIssue7638AdvisorMintJSON("srvtoolu_shared", "from A")), nil + } + return claudeIssue7638JSONResponse(req, `{"id":"msg_2","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`), nil + }) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + base := NewClaudeExecutor(&config.Config{}) + copyA := base.ForAPIKey().(*ClaudeExecutor) + copyB := base.WithConfig(&config.Config{}) + authA := claudeIssue7638OAuthAuth("cred-share-a", "sk-ant-oat-sha1", "11111111-1111-4111-8111-111111111115") + authB := claudeIssue7638OAuthAuth("cred-share-b", "sk-ant-oat-shb1", "22222222-2222-4222-8222-222222222226") + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude} + + if _, err := copyA.Execute(ctx, authA, cliproxyexecutor.Request{ + Model: "claude-opus-5-5", + Payload: []byte(`{"model":"claude-opus-5-5","max_tokens":256,"messages":[{"role":"user","content":"turn 1"}]}`), + }, opts); err != nil { + t.Fatalf("copyA.Execute() error = %v", err) + } + + replay := []byte(`{ + "model": "claude-opus-5-5", + "max_tokens": 256, + "messages": [ + {"role": "user", "content": "turn 1"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_shared", "name": "advisor", "input": {}}, + {"type": "advisor_tool_result", "tool_use_id": "srvtoolu_shared", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_s"}}, + {"type": "text", "text": "from A"} + ] + }, + {"role": "user", "content": "turn 2"} + ] + }`) + if _, err := copyB.Execute(ctx, authB, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: replay}, opts); err != nil { + t.Fatalf("copyB.Execute() error = %v", err) + } + if strings.Contains(string(captured[1]), "srvtoolu_shared") { + t.Fatalf("WithConfig/ForAPIKey copies did not share advisor owner store: %s", captured[1]) + } +} + +func TestClaudeIssue7638_PayloadRuleRemainsFinalSemanticBarrier(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + var captured [][]byte + callIdx := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, _ := io.ReadAll(req.Body) + captured = append(captured, body) + callIdx++ + if callIdx == 1 { + return claudeIssue7638JSONResponse(req, claudeIssue7638AdvisorMintJSON("srvtoolu_barrier", "from A")), nil + } + return claudeIssue7638JSONResponse(req, `{"id":"msg_2","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`), nil + }) + + cfg := &config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "claude-opus-5-5", Protocol: "claude"}}, + Params: map[string]any{"max_tokens": 999}, + }, + }, + }, + } + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + exec := NewClaudeExecutor(cfg) + authA := claudeIssue7638OAuthAuth("cred-bar-a", "sk-ant-oat-ba", "11111111-1111-4111-8111-111111111116") + authB := claudeIssue7638OAuthAuth("cred-bar-b", "sk-ant-oat-bb", "22222222-2222-4222-8222-222222222227") + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude} + + if _, err := exec.Execute(ctx, authA, cliproxyexecutor.Request{ + Model: "claude-opus-5-5", + Payload: []byte(`{"model":"claude-opus-5-5","max_tokens":256,"messages":[{"role":"user","content":"turn 1"}]}`), + }, opts); err != nil { + t.Fatalf("turn 1 error = %v", err) + } + + replay := []byte(`{ + "model": "claude-opus-5-5", + "max_tokens": 256, + "messages": [ + {"role": "user", "content": "turn 1"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_barrier", "name": "advisor", "input": {}}, + {"type": "advisor_tool_result", "tool_use_id": "srvtoolu_barrier", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_b"}}, + {"type": "text", "text": "from A"} + ] + }, + {"role": "user", "content": "turn 2"} + ] + }`) + if _, err := exec.Execute(ctx, authB, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: replay}, opts); err != nil { + t.Fatalf("turn 2 error = %v", err) + } + if strings.Contains(string(captured[1]), "srvtoolu_barrier") { + t.Fatalf("foreign advisor block was not stripped: %s", captured[1]) + } + if got := ojson.GetBytes(captured[1], "max_tokens").Int(); got != 999 { + t.Fatalf("payload override max_tokens = %d, want 999: %s", got, captured[1]) + } +} + +func TestClaudeIssue7638_PayloadRuleRemovingUnknownAdvisorDoesNotClaimOwner(t *testing.T) { + for _, stream := range []bool{false, true} { + mode := "Execute" + if stream { + mode = "ExecuteStream" + } + t.Run(mode, func(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + var captured [][]byte + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, _ := io.ReadAll(req.Body) + captured = append(captured, body) + if stream { + return claudeIssue7638SSEResponse(req, + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_f\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-opus-5-5\",\"content\":[],\"stop_reason\":null,\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n"+ + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n"+ + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\n"+ + "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n"+ + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":1}}\n\n"+ + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + ), nil + } + return claudeIssue7638JSONResponse(req, `{"id":"msg_f","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`), nil + }) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + authA := claudeIssue7638OAuthAuth("cred-filt-a", "sk-ant-oat-fa", "11111111-1111-4111-8111-111111111117") + authB := claudeIssue7638OAuthAuth("cred-filt-b", "sk-ant-oat-fb", "22222222-2222-4222-8222-222222222228") + + // Override replaces messages so srvtoolu_filtered never reaches upstream B. + overrideCfg := &config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "claude-opus-5-5", Protocol: "claude"}}, + Params: map[string]any{ + "messages": []any{map[string]any{"role": "user", "content": "sanitized by rule"}}, + }, + }, + }, + }, + } + exec := NewClaudeExecutor(overrideCfg) + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Stream: stream} + + streamField := "" + if stream { + streamField = `"stream":true,` + } + payload := []byte(fmt.Sprintf(`{ + "model": "claude-opus-5-5", + "max_tokens": 256, + %s + "messages": [ + {"role": "user", "content": "turn 1"}, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_filtered", "name": "advisor", "input": {}}, + {"type": "advisor_tool_result", "tool_use_id": "srvtoolu_filtered", "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_filt"}}, + {"type": "text", "text": "from A"} + ] + }, + {"role": "user", "content": "turn 2"} + ] + }`, streamField)) + + runReq := func(e *ClaudeExecutor, auth *cliproxyauth.Auth) { + if stream { + res, err := e.ExecuteStream(ctx, auth, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: payload}, opts) + if err != nil { + t.Fatalf("ExecuteStream() error = %v", err) + } + for chunk := range res.Chunks { + if chunk.Err != nil { + t.Fatalf("ExecuteStream() chunk error = %v", chunk.Err) + } + } + return + } + if _, err := e.Execute(ctx, auth, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: payload}, opts); err != nil { + t.Fatalf("Execute() error = %v", err) + } + } + + // Call 1 on B with payload rule removing srvtoolu_filtered: B succeeds, + // but MUST NOT claim ownership of srvtoolu_filtered. + runReq(exec, authB) + if strings.Contains(string(captured[0]), "srvtoolu_filtered") { + t.Fatalf("expected payload rule to remove srvtoolu_filtered before upstream B: %s", captured[0]) + } + + // Call 2 on A without the payload rule (sharing the same store via WithConfig): + // srvtoolu_filtered must NOT be stripped for A! + plainExec := exec.WithConfig(&config.Config{}) + runReq(plainExec, authA) + if !strings.Contains(string(captured[1]), "srvtoolu_filtered") { + t.Fatalf("cred-filt-a had srvtoolu_filtered stripped because cred-filt-b falsely claimed ownership after payload removal: %s", captured[1]) + } + }) + } +} diff --git a/internal/runtime/executor/helps/claude_advisor_state.go b/internal/runtime/executor/helps/claude_advisor_state.go new file mode 100644 index 0000000000..1f6c45d859 --- /dev/null +++ b/internal/runtime/executor/helps/claude_advisor_state.go @@ -0,0 +1,548 @@ +package helps + +import ( + "bytes" + "container/list" + "context" + "fmt" + "strings" + "sync" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" + log "github.com/sirupsen/logrus" +) + +const ( + // ClaudeAdvisorOwnerTTL bounds cached advisor block credential ownership. + ClaudeAdvisorOwnerTTL = 24 * time.Hour + claudeAdvisorOwnerLimit = 4096 + claudeAdvisorKVRefreshInterval = time.Hour +) + +type claudeAdvisorOwnerEntry struct { + key string + owner string + expiresAt time.Time + kvRefreshedAt time.Time + elem *list.Element +} + +// ClaudeAdvisorOwnerStore tracks which Claude credential minted each advisor +// tool_use_id so foreign encrypted advisor blocks can be stripped when a +// conversation moves to a different credential. +type ClaudeAdvisorOwnerStore struct { + mu sync.Mutex + entries map[string]*claudeAdvisorOwnerEntry + order *list.List + nowFunc func() time.Time +} + +// NewClaudeAdvisorOwnerStore allocates a bounded in-memory advisor owner store +// backed by best-effort KV persistence when configured. +func NewClaudeAdvisorOwnerStore() *ClaudeAdvisorOwnerStore { + return &ClaudeAdvisorOwnerStore{ + entries: make(map[string]*claudeAdvisorOwnerEntry), + order: list.New(), + } +} + +func (s *ClaudeAdvisorOwnerStore) now() time.Time { + if s != nil && s.nowFunc != nil { + return s.nowFunc() + } + return time.Now() +} + +func claudeAdvisorOwnerKVKey(scope, toolUseID string) string { + return "claude:advisor-auth:v1:" + kvstore.HashKeyPart(scope) + ":" + kvstore.HashKeyPart(toolUseID) +} + +func (s *ClaudeAdvisorOwnerStore) initLocked() { + if s.entries == nil { + s.entries = make(map[string]*claudeAdvisorOwnerEntry) + } + if s.order == nil { + s.order = list.New() + } +} + +func (s *ClaudeAdvisorOwnerStore) hasLiveLocalOwner(key string, now time.Time) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.entries == nil { + return false + } + entry, exists := s.entries[key] + return exists && now.Before(entry.expiresAt) +} + +func (s *ClaudeAdvisorOwnerStore) cacheOwner(key, owner string, now time.Time, kvSynced bool) bool { + s.mu.Lock() + defer s.mu.Unlock() + s.initLocked() + if entry, exists := s.entries[key]; exists { + if now.Before(entry.expiresAt) { + return false + } + entry.owner = strings.Clone(owner) + entry.expiresAt = now.Add(ClaudeAdvisorOwnerTTL) + if kvSynced { + entry.kvRefreshedAt = now + } else { + entry.kvRefreshedAt = time.Time{} + } + s.order.MoveToBack(entry.elem) + return true + } + entry := &claudeAdvisorOwnerEntry{ + key: key, + owner: strings.Clone(owner), + expiresAt: now.Add(ClaudeAdvisorOwnerTTL), + } + if kvSynced { + entry.kvRefreshedAt = now + } + entry.elem = s.order.PushBack(entry) + s.entries[key] = entry + for s.order.Len() > claudeAdvisorOwnerLimit { + front := s.order.Front() + if front == nil { + break + } + oldest := front.Value.(*claudeAdvisorOwnerEntry) + s.order.Remove(front) + delete(s.entries, oldest.key) + } + return true +} + +// Lookup returns the recorded owning credential identity for toolUseID and +// slides the retention window forward for active sessions. +func (s *ClaudeAdvisorOwnerStore) Lookup(ctx context.Context, scope, toolUseID string) (string, bool) { + if s == nil || scope == "" || toolUseID == "" { + return "", false + } + key := claudeAdvisorOwnerKVKey(scope, toolUseID) + now := s.now() + s.mu.Lock() + if s.entries != nil { + if entry, found := s.entries[key]; found { + if now.Before(entry.expiresAt) { + entry.expiresAt = now.Add(ClaudeAdvisorOwnerTTL) + if s.order != nil && entry.elem != nil { + s.order.MoveToBack(entry.elem) + } + shouldRefreshKV := entry.kvRefreshedAt.IsZero() || now.Sub(entry.kvRefreshedAt) >= claudeAdvisorKVRefreshInterval + if shouldRefreshKV { + entry.kvRefreshedAt = now + } + owner := entry.owner + s.mu.Unlock() + if shouldRefreshKV { + kvstore.KVExpireBestEffort(context.Background(), key, ClaudeAdvisorOwnerTTL) + } + return owner, true + } + if s.order != nil && entry.elem != nil { + s.order.Remove(entry.elem) + } + delete(s.entries, key) + } + } + s.mu.Unlock() + + client, kvMode, errClient := kvstore.CurrentKVClient() + if !kvMode || errClient != nil || client == nil { + return "", false + } + if ctx == nil { + ctx = context.Background() + } + raw, foundKV, errGet := client.KVGet(ctx, key) + if errGet != nil || !foundKV { + return "", false + } + owner := strings.TrimSpace(string(raw)) + if owner == "" { + return "", false + } + s.cacheOwner(key, owner, now, true) + kvstore.KVExpireBestEffort(context.Background(), key, ClaudeAdvisorOwnerTTL) + return owner, true +} + +// Remember records owner for toolUseID using first-writer-wins semantics across +// both local memory and the shared KV store when configured. +func (s *ClaudeAdvisorOwnerStore) Remember(scope, toolUseID, owner string) { + if s == nil || scope == "" || toolUseID == "" || owner == "" { + return + } + key := claudeAdvisorOwnerKVKey(scope, toolUseID) + now := s.now() + if s.hasLiveLocalOwner(key, now) { + return + } + + winningOwner := owner + kvSynced := false + client, kvMode, errClient := kvstore.CurrentKVClient() + if kvMode && errClient == nil && client != nil { + written, errSet := client.KVSetNX(context.Background(), key, []byte(owner), ClaudeAdvisorOwnerTTL) + if errSet != nil { + log.Errorf("claude advisor owner kv setnx failed: %v", errSet) + } else if written { + kvSynced = true + } else { + // Another writer already claimed this tool_use_id in shared KV; adopt + // the authoritative winner so local memory stays consistent, and never + // cache the losing local candidate if the follow-up read fails. + raw, foundKV, errGet := client.KVGet(context.Background(), key) + if errGet != nil { + log.Errorf("claude advisor owner kv get after conflict failed: %v", errGet) + return + } + if !foundKV { + return + } + existing := strings.TrimSpace(string(raw)) + if existing == "" { + return + } + winningOwner = existing + kvSynced = true + } + } + s.cacheOwner(key, winningOwner, now, kvSynced) +} + +// ClaudeAdvisorRequestState carries per-request advisor ownership context so +// unknown request IDs and newly minted response IDs are recorded only after +// upstream acceptance. +type ClaudeAdvisorRequestState struct { + store *ClaudeAdvisorOwnerStore + scope string + owner string + unknownIDs []string + accepted bool +} + +// FilterUnknownIDsFromFinalBody performs a read-only check against the final +// outbound request payload (after user payload rules) and drops any unknown +// advisor IDs that are no longer present in body.messages. +func (r *ClaudeAdvisorRequestState) FilterUnknownIDsFromFinalBody(body []byte) { + if r == nil || len(r.unknownIDs) == 0 { + return + } + messages := ojson.GetBytesNoCopy(body, "messages") + if !messages.IsArray() { + r.unknownIDs = nil + return + } + present := make(map[string]struct{}, len(r.unknownIDs)) + for _, msg := range messages.Array() { + content := msg.Get("content") + if content.IsArray() { + for _, block := range content.Array() { + if id := claudeAdvisorBlockID(block); id != "" { + present[id] = struct{}{} + } + } + } else if content.IsObject() { + blockType := content.Get("type").String() + if blockType == "advisor_tool_result" || blockType == "advisor_redacted_result" { + if id := strings.TrimSpace(content.Get("tool_use_id").String()); id != "" { + present[id] = struct{}{} + } + } + } + } + filtered := r.unknownIDs[:0] + for _, id := range r.unknownIDs { + if _, ok := present[id]; ok { + filtered = append(filtered, id) + } + } + r.unknownIDs = filtered +} + +// RecordAccepted commits ownership of any previously unknown advisor IDs seen +// in the request after the upstream credential accepted the request. +func (r *ClaudeAdvisorRequestState) RecordAccepted() { + if r == nil || r.store == nil || r.accepted { + return + } + r.accepted = true + for _, id := range r.unknownIDs { + r.store.Remember(r.scope, id, r.owner) + } +} + +// RecordResponseJSON records advisor blocks minted in a non-streaming Claude +// Messages JSON response. +func (r *ClaudeAdvisorRequestState) RecordResponseJSON(data []byte) { + if r == nil || r.store == nil || len(data) == 0 { + return + } + content := ojson.GetBytesNoCopy(data, "content") + if !content.IsArray() { + return + } + for _, block := range content.Array() { + if id := claudeAdvisorBlockID(block); id != "" { + r.store.Remember(r.scope, id, r.owner) + } + } +} + +// ObserveSSELine inspects one SSE line from a Claude stream, committing +// request-side unknown advisor IDs on message_start and recording newly minted +// advisor blocks on content_block_start. +func (r *ClaudeAdvisorRequestState) ObserveSSELine(line []byte) { + if r == nil || r.store == nil || len(line) == 0 { + return + } + trimmed := bytes.TrimSpace(line) + if !bytes.HasPrefix(trimmed, []byte("data:")) { + return + } + payload := bytes.TrimSpace(trimmed[len("data:"):]) + if len(payload) == 0 || bytes.Equal(payload, []byte("[DONE]")) { + return + } + if !bytes.Contains(payload, []byte("content_block_start")) && !bytes.Contains(payload, []byte("message_start")) { + return + } + if !ojson.ValidBytes(payload) { + return + } + root := ojson.ParseBytes(payload) + switch root.Get("type").String() { + case "message_start": + r.RecordAccepted() + case "content_block_start": + if id := claudeAdvisorBlockID(root.Get("content_block")); id != "" { + r.store.Remember(r.scope, id, r.owner) + } + } +} + +// RecordResponseSSE records advisor blocks minted across a buffered Claude SSE +// response body. +func (r *ClaudeAdvisorRequestState) RecordResponseSSE(data []byte) { + if r == nil || r.store == nil || len(data) == 0 { + return + } + for _, line := range bytes.Split(data, []byte("\n")) { + r.ObserveSSELine(line) + } +} + +// StripForeignAdvisorBlocksDoc removes advisor state blocks owned by another +// credential from doc.messages in place and returns per-request tracking state +// along with the number of stripped blocks. +func (s *ClaudeAdvisorOwnerStore) StripForeignAdvisorBlocksDoc(ctx context.Context, doc *ojson.Doc, scope, owner string) (*ClaudeAdvisorRequestState, int) { + if s == nil || doc == nil || scope == "" || owner == "" { + return nil, 0 + } + state := &ClaudeAdvisorRequestState{ + store: s, + scope: scope, + owner: owner, + } + messages := doc.Get("messages") + if !messages.IsArray() || !claudeMessagesContainAdvisorState(messages) { + return state, 0 + } + + messageResults := messages.Array() + ordinaryToolUseIDs := make(map[string]struct{}) + for _, msg := range messageResults { + content := msg.Get("content") + if !content.IsArray() { + continue + } + for _, block := range content.Array() { + if block.Get("type").String() == "tool_use" { + if id := strings.TrimSpace(block.Get("id").String()); id != "" { + ordinaryToolUseIDs[id] = struct{}{} + } + } + } + } + + resolvedOwners := make(map[string]string) + unknownSeen := make(map[string]struct{}) + isForeign := func(id string) bool { + if id == "" { + return false + } + recorded, checked := resolvedOwners[id] + if !checked { + if foundOwner, ok := s.Lookup(ctx, scope, id); ok { + recorded = foundOwner + } + resolvedOwners[id] = recorded + } + if recorded == "" { + if _, seen := unknownSeen[id]; !seen { + unknownSeen[id] = struct{}{} + state.unknownIDs = append(state.unknownIDs, strings.Clone(id)) + } + return false + } + return recorded != owner + } + + strippedBlocks := 0 + var droppedMessages []int + + for i, msg := range messageResults { + content := msg.Get("content") + if content.IsArray() { + contentResults := content.Array() + var droppedParts []int + + for j, block := range contentResults { + blockType := block.Get("type").String() + switch blockType { + case "server_tool_use": + if block.Get("name").String() != "advisor" { + continue + } + if isForeign(strings.TrimSpace(block.Get("id").String())) { + droppedParts = append(droppedParts, j) + strippedBlocks++ + } + case "advisor_tool_result", "advisor_redacted_result": + if isForeign(strings.TrimSpace(block.Get("tool_use_id").String())) { + droppedParts = append(droppedParts, j) + strippedBlocks++ + } + case "tool_result": + inner := block.Get("content") + if inner.IsObject() && inner.Get("type").String() == "advisor_redacted_result" { + id := strings.TrimSpace(block.Get("tool_use_id").String()) + if isForeign(id) { + if _, isOrdinary := ordinaryToolUseIDs[id]; isOrdinary { + _ = doc.Set(fmt.Sprintf("messages.%d.content.%d.content", i, j), "") + } else { + droppedParts = append(droppedParts, j) + } + strippedBlocks++ + } + } else if inner.IsArray() { + innerItems := inner.Array() + var advisorSubIndices []int + for subIdx, sub := range innerItems { + if sub.Get("type").String() == "advisor_redacted_result" { + advisorSubIndices = append(advisorSubIndices, subIdx) + } + } + if len(advisorSubIndices) == 0 { + continue + } + id := strings.TrimSpace(block.Get("tool_use_id").String()) + if !isForeign(id) { + continue + } + _, isOrdinary := ordinaryToolUseIDs[id] + if !isOrdinary { + // The paired server_tool_use(name="advisor") is dropped in the + // same pass, so drop the entire tool_result to avoid a dangling + // tool_use_id reference. + droppedParts = append(droppedParts, j) + strippedBlocks++ + } else if len(advisorSubIndices) < len(innerItems) { + for k := len(advisorSubIndices) - 1; k >= 0; k-- { + _ = doc.Delete(fmt.Sprintf("messages.%d.content.%d.content.%d", i, j, advisorSubIndices[k])) + } + strippedBlocks += len(advisorSubIndices) + } else { + _ = doc.Set(fmt.Sprintf("messages.%d.content.%d.content", i, j), "") + strippedBlocks += len(advisorSubIndices) + } + } + } + } + + if len(droppedParts) > 0 { + if len(droppedParts) == len(contentResults) { + droppedMessages = append(droppedMessages, i) + continue + } + for k := len(droppedParts) - 1; k >= 0; k-- { + _ = doc.Delete(fmt.Sprintf("messages.%d.content.%d", i, droppedParts[k])) + } + } + } else if content.IsObject() { + blockType := content.Get("type").String() + if blockType == "advisor_tool_result" || blockType == "advisor_redacted_result" { + if isForeign(strings.TrimSpace(content.Get("tool_use_id").String())) { + droppedMessages = append(droppedMessages, i) + strippedBlocks++ + } + } + } + } + + for k := len(droppedMessages) - 1; k >= 0; k-- { + _ = doc.Delete(fmt.Sprintf("messages.%d", droppedMessages[k])) + } + return state, strippedBlocks +} + +func claudeAdvisorBlockID(block ojson.Result) string { + if !block.IsObject() { + return "" + } + switch block.Get("type").String() { + case "server_tool_use": + if block.Get("name").String() == "advisor" { + return strings.TrimSpace(block.Get("id").String()) + } + case "advisor_tool_result", "advisor_redacted_result": + return strings.TrimSpace(block.Get("tool_use_id").String()) + case "tool_result": + if claudeToolResultContainsAdvisorRedacted(block.Get("content")) { + return strings.TrimSpace(block.Get("tool_use_id").String()) + } + } + return "" +} + +func claudeToolResultContainsAdvisorRedacted(inner ojson.Result) bool { + if inner.IsObject() { + return inner.Get("type").String() == "advisor_redacted_result" + } + if inner.IsArray() { + for _, sub := range inner.Array() { + if sub.Get("type").String() == "advisor_redacted_result" { + return true + } + } + } + return false +} + +func claudeMessagesContainAdvisorState(messages ojson.Result) bool { + for _, msg := range messages.Array() { + content := msg.Get("content") + if content.IsArray() { + for _, block := range content.Array() { + if claudeAdvisorBlockID(block) != "" { + return true + } + } + } else if content.IsObject() { + blockType := content.Get("type").String() + if blockType == "advisor_tool_result" || blockType == "advisor_redacted_result" { + if strings.TrimSpace(content.Get("tool_use_id").String()) != "" { + return true + } + } + } + } + return false +} diff --git a/internal/runtime/executor/helps/claude_advisor_state_test.go b/internal/runtime/executor/helps/claude_advisor_state_test.go new file mode 100644 index 0000000000..f8598ae906 --- /dev/null +++ b/internal/runtime/executor/helps/claude_advisor_state_test.go @@ -0,0 +1,265 @@ +package helps + +import ( + "context" + "errors" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" +) + +func TestClaudeAdvisorOwnerStore_FirstWriterWinsSlidingTTLAndBounds(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + now := time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC) + store := NewClaudeAdvisorOwnerStore() + store.nowFunc = func() time.Time { return now } + + // First writer wins while entry is still live. + store.Remember("claude", "srvtoolu_1", "id:cred-a") + store.Remember("claude", "srvtoolu_1", "id:cred-b") + owner, ok := store.Lookup(context.Background(), "claude", "srvtoolu_1") + if !ok || owner != "id:cred-a" { + t.Fatalf("Lookup() = (%q, %v), want (id:cred-a, true)", owner, ok) + } + + // Scope isolation. + if foreignOwner, found := store.Lookup(context.Background(), "other-provider", "srvtoolu_1"); found { + t.Fatalf("Lookup() crossed scopes: (%q, %v)", foreignOwner, found) + } + + // Active session sliding TTL: hitting Lookup at +20h keeps the entry alive past + // the original 24h mark (at +30h total). + now = now.Add(20 * time.Hour) + owner, ok = store.Lookup(context.Background(), "claude", "srvtoolu_1") + if !ok || owner != "id:cred-a" { + t.Fatalf("active Lookup() at +20h = (%q, %v), want (id:cred-a, true)", owner, ok) + } + now = now.Add(10 * time.Hour) // 30h since initial registration, 10h since last hit + owner, ok = store.Lookup(context.Background(), "claude", "srvtoolu_1") + if !ok || owner != "id:cred-a" { + t.Fatalf("active Lookup() at +30h (10h idle) = (%q, %v), want (id:cred-a, true)", owner, ok) + } + + // Idle entry expires once untouched for >24h. + now = now.Add(ClaudeAdvisorOwnerTTL + time.Second) + if expiredOwner, found := store.Lookup(context.Background(), "claude", "srvtoolu_1"); found { + t.Fatalf("expired entry remained live: (%q, %v)", expiredOwner, found) + } + + // Re-inserting an expired key keeps order length accurate. + store.Remember("claude", "srvtoolu_1", "id:cred-b") + owner, ok = store.Lookup(context.Background(), "claude", "srvtoolu_1") + if !ok || owner != "id:cred-b" { + t.Fatalf("refreshed Lookup() = (%q, %v), want (id:cred-b, true)", owner, ok) + } + if store.order.Len() != 1 { + t.Fatalf("order len = %d after refresh, want 1", store.order.Len()) + } + + // Bounded LRU eviction: exceeding claudeAdvisorOwnerLimit evicts the oldest idle entry. + for i := 0; i <= claudeAdvisorOwnerLimit; i++ { + store.Remember("claude", "srvtoolu_bound_"+strconv.Itoa(i), "id:cred-a") + } + if _, found := store.Lookup(context.Background(), "claude", "srvtoolu_1"); found { + t.Fatal("oldest entry was not evicted when exceeding store limit") + } + if got, found := store.Lookup(context.Background(), "claude", "srvtoolu_bound_"+strconv.Itoa(claudeAdvisorOwnerLimit)); !found || got != "id:cred-a" { + t.Fatalf("newest entry lost: (%q, %v)", got, found) + } +} + +func TestClaudeAdvisorOwnerStore_SharedKVFirstWriterConsistency(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + kvPath := filepath.Join(t.TempDir(), "kv.db") + if errCfg := kvstore.ConfigureLocal(true, kvPath); errCfg != nil { + t.Fatal(errCfg) + } + t.Cleanup(func() { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Error(errShutdown) + } + }) + + store1 := NewClaudeAdvisorOwnerStore() + store2 := NewClaudeAdvisorOwnerStore() + + // store1 claims ownership first in shared KV; store2 attempts a conflicting claim. + store1.Remember("claude", "srvtoolu_shared_kv", "id:cred-a") + store2.Remember("claude", "srvtoolu_shared_kv", "id:cred-b") + + owner1, ok1 := store1.Lookup(context.Background(), "claude", "srvtoolu_shared_kv") + owner2, ok2 := store2.Lookup(context.Background(), "claude", "srvtoolu_shared_kv") + if !ok1 || owner1 != "id:cred-a" { + t.Fatalf("store1 Lookup() = (%q, %v), want (id:cred-a, true)", owner1, ok1) + } + if !ok2 || owner2 != "id:cred-a" { + t.Fatalf("store2 Lookup() = (%q, %v), want authoritative KV winner (id:cred-a, true)", owner2, ok2) + } + + // Active Lookup past the KV refresh interval must renew the backing KV TTL. + now := time.Now() + store1.nowFunc = func() time.Time { return now } + client, kvMode, errClient := kvstore.CurrentKVClient() + if !kvMode || errClient != nil || client == nil { + t.Fatalf("CurrentKVClient() = (%v, %v, %v), want active local KV", client, kvMode, errClient) + } + key := claudeAdvisorOwnerKVKey("claude", "srvtoolu_shared_kv") + if _, errExp := client.KVExpire(context.Background(), key, 30*time.Second); errExp != nil { + t.Fatalf("KVExpire() error = %v", errExp) + } + now = now.Add(2 * time.Hour) + if got, found := store1.Lookup(context.Background(), "claude", "srvtoolu_shared_kv"); !found || got != "id:cred-a" { + t.Fatalf("active Lookup() = (%q, %v), want (id:cred-a, true)", got, found) + } + remaining, hasTTL, errTTL := client.KVTTL(context.Background(), key) + if errTTL != nil || !hasTTL || remaining < 23*time.Hour { + t.Fatalf("backing KV TTL after active Lookup = (%v, hasTTL=%v, err=%v), want >= 23h", remaining, hasTTL, errTTL) + } +} + +type stubConflictAdvisorKVClient struct { + kvstore.KVClient + getErr error + getVal []byte + getFound bool + setNXDone bool +} + +func (c *stubConflictAdvisorKVClient) KVSetNX(_ context.Context, _ string, _ []byte, _ time.Duration) (bool, error) { + c.setNXDone = true + return false, nil +} + +func (c *stubConflictAdvisorKVClient) KVGet(_ context.Context, _ string) ([]byte, bool, error) { + if c.getErr != nil { + return nil, false, c.getErr + } + return c.getVal, c.getFound, nil +} + +func (c *stubConflictAdvisorKVClient) KVExpire(_ context.Context, _ string, _ time.Duration) (bool, error) { + return true, nil +} + +func TestClaudeAdvisorOwnerStore_KVConflictReadErrorDoesNotCacheLoser(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + stub := &stubConflictAdvisorKVClient{getErr: errors.New("transient kv read failure")} + kvstore.RegisterHomeProvider(func() (kvstore.KVClient, bool, error) { + return stub, true, nil + }) + t.Cleanup(func() { + kvstore.RegisterHomeProvider(nil) + }) + + store := NewClaudeAdvisorOwnerStore() + // KVSetNX returns false (lost conflict) and follow-up KVGet fails -> losing + // candidate "id:cred-b" must NOT be cached locally. + store.Remember("claude", "srvtoolu_conflict_err", "id:cred-b") + if !stub.setNXDone { + t.Fatal("expected KVSetNX to be called") + } + + // Once KV recovers, Lookup must fetch the true winner "id:cred-a" rather than + // returning the losing candidate "id:cred-b". + stub.getErr = nil + stub.getVal = []byte("id:cred-a") + stub.getFound = true + owner, ok := store.Lookup(context.Background(), "claude", "srvtoolu_conflict_err") + if !ok || owner != "id:cred-a" { + t.Fatalf("Lookup() after conflict read recovery = (%q, %v), want (id:cred-a, true)", owner, ok) + } +} + +func TestStripForeignAdvisorBlocksDoc_EdgeCases(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + store := NewClaudeAdvisorOwnerStore() + store.Remember("claude", "toolu_ord", "id:cred-a") + store.Remember("claude", "srvtoolu_obj", "id:cred-a") + store.Remember("claude", "srvtoolu_mixed_srv", "id:cred-a") + + doc := ojson.NewDocString(`{ + "messages": [ + {"role": "user", "content": "hi"}, + { + "role": "assistant", + "content": [ + {"type": "tool_use", "id": "toolu_ord", "name": "normal_tool", "input": {}} + ] + }, + { + "role": "user", + "content": [ + { + "type": "tool_result", + "tool_use_id": "toolu_ord", + "content": [ + {"type": "advisor_redacted_result", "encrypted_content": "enc_ord"} + ] + } + ] + }, + { + "role": "assistant", + "content": [ + {"type": "server_tool_use", "id": "srvtoolu_mixed_srv", "name": "advisor", "input": {}} + ] + }, + { + "role": "user", + "content": [ + { + "type": "tool_result", + "tool_use_id": "srvtoolu_mixed_srv", + "content": [ + {"type": "text", "text": "wrapper text"}, + {"type": "advisor_redacted_result", "encrypted_content": "enc_mixed_srv"} + ] + } + ] + }, + { + "role": "user", + "content": { + "type": "advisor_tool_result", + "tool_use_id": "srvtoolu_obj", + "content": {"type": "advisor_redacted_result", "encrypted_content": "enc_obj"} + } + }, + {"role": "user", "content": "final"} + ] + }`) + + _, stripped := store.StripForeignAdvisorBlocksDoc(context.Background(), doc, "claude", "id:cred-b") + if stripped != 4 { + t.Fatalf("stripped = %d, want 4", stripped) + } + out := doc.String() + if strings.Contains(out, "enc_ord") || strings.Contains(out, "enc_obj") || strings.Contains(out, "srvtoolu_obj") || strings.Contains(out, "srvtoolu_mixed_srv") || strings.Contains(out, "enc_mixed_srv") { + t.Fatalf("foreign advisor content or dangling server_tool_use tool_result remained: %s", out) + } + // Ordinary tool_use must keep its paired tool_result with cleared content instead of orphaning it. + if got := doc.Get("messages.2.content.0.type").String(); got != "tool_result" { + t.Fatalf("messages.2.content.0.type = %q, want tool_result: %s", got, out) + } + if got := doc.Get("messages.2.content.0.content").String(); got != "" { + t.Fatalf("messages.2.content.0.content = %q, want empty string: %s", got, out) + } + // Both advisor-only turns (server_tool_use + mixed tool_result for dropped server_tool_use) + // and the object-content advisor message must be dropped completely. + if got := doc.Get("messages.#").Int(); got != 4 { + t.Fatalf("messages count = %d, want 4: %s", got, out) + } +}