diff --git a/internal/runtime/executor/claude_executor_cloaking.go b/internal/runtime/executor/claude_executor_cloaking.go index 154479386e..fca58ba6f5 100644 --- a/internal/runtime/executor/claude_executor_cloaking.go +++ b/internal/runtime/executor/claude_executor_cloaking.go @@ -148,20 +148,44 @@ func computeFingerprint(messageText, version string) string { // generateBillingHeader creates the x-anthropic-billing-header text block that // Claude Code prepends to its system prompt. cch is present only on signed paths. -func generateBillingHeader(cchSigning bool, version, messageText, entrypoint, workload string) string { +func generateBillingHeader(cchSigning bool, version, messageText, entrypoint, workload string, isSubagent bool, prevReq, promptID string) string { if entrypoint == "" { entrypoint = "cli" } buildHash := computeFingerprint(messageText, version) - workloadPart := "" - if workload != "" { - workloadPart = fmt.Sprintf(" cc_workload=%s;", workload) - } + var b strings.Builder + b.WriteString("x-anthropic-billing-header: cc_version=") + b.WriteString(version) + b.WriteByte('.') + b.WriteString(buildHash) + b.WriteString("; cc_entrypoint=") + b.WriteString(entrypoint) + b.WriteByte(';') if cchSigning { - return fmt.Sprintf("x-anthropic-billing-header: cc_version=%s.%s; cc_entrypoint=%s; cch=00000;%s", version, buildHash, entrypoint, workloadPart) + b.WriteString(" cch=00000;") } - return fmt.Sprintf("x-anthropic-billing-header: cc_version=%s.%s; cc_entrypoint=%s;%s", version, buildHash, entrypoint, workloadPart) + if workload != "" { + b.WriteString(" cc_workload=") + b.WriteString(workload) + b.WriteByte(';') + } + if isSubagent { + b.WriteString(" cc_is_subagent=true;") + } + if cchSigning { + if prevReq != "" { + b.WriteString(" cc_prev_req=") + b.WriteString(prevReq) + b.WriteByte(';') + } + if promptID != "" { + b.WriteString(" cc_prompt_id=") + b.WriteString(promptID) + b.WriteByte(';') + } + } + return b.String() } func claudeBillingFingerprintMessageText(payload []byte) string { @@ -191,12 +215,28 @@ func claudeBillingFingerprintMessageText(payload []byte) string { } func claudeCCHFallbackBillingHeader(ctx context.Context, cfg *config.Config, payload []byte, entrypoint string) string { + isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(payload) + prevReq, promptID := helps.ExtractClaudeBillingTags(payload) + if !isProbeOrHelper { + continuityCtx := helps.ClaudeContinuityContextFromContext(ctx) + if prevReq == "" && continuityCtx != nil { + prevReq = continuityCtx.PreviousRequestID + } + if promptID == "" && continuityCtx != nil { + promptID = continuityCtx.PromptID + } + } + incomingHeaders := resolveIncomingClaudeHeaders(ctx, helps.IncomingHeadersFromContext(ctx)) + isSubagent := helps.IsClaudeSubagentRequest(incomingHeaders, payload) return generateBillingHeader( true, helps.DefaultClaudeVersion(cfg), claudeBillingFingerprintMessageText(payload), entrypoint, getWorkloadFromContext(ctx), + isSubagent, + prevReq, + promptID, ) } @@ -212,14 +252,22 @@ func checkSystemInstructionsWithMode(payload []byte, strictMode bool) []byte { // Claude models give it operator-level authority without changing the cached // top-level prefix. func checkSystemInstructionsWithSigningMode(payload []byte, strictMode bool, cchSigning bool, version, entrypoint, workload string) []byte { - return checkSystemInstructionsWithSigningModeAt(payload, strictMode, cchSigning, version, entrypoint, workload, time.Now()) + return checkSystemInstructionsWithSigningModeAt(payload, strictMode, cchSigning, version, entrypoint, workload, time.Now(), false, "", "") } -func checkSystemInstructionsWithSigningModeAt(payload []byte, strictMode bool, cchSigning bool, version, entrypoint, workload string, now time.Time) []byte { +func checkSystemInstructionsWithSigningModeAt( + payload []byte, + strictMode bool, + cchSigning bool, + version, entrypoint, workload string, + now time.Time, + isSubagent bool, + prevReq, promptID string, +) []byte { system := gjson.GetBytes(payload, "system") messageText := claudeBillingFingerprintMessageText(payload) - billingText := generateBillingHeader(cchSigning, version, messageText, entrypoint, workload) + billingText := generateBillingHeader(cchSigning, version, messageText, entrypoint, workload, isSubagent, prevReq, promptID) billingBlock := buildTextBlock(billingText, nil) agentBlock := buildTextBlock(claudeCodeCLIIdentity, &claudeCodeCacheControl) payload, _ = sjson.SetRawBytes(payload, "system", []byte("["+billingBlock+","+agentBlock+"]")) @@ -1026,7 +1074,59 @@ func applyCloaking( billingVersion := helps.DefaultClaudeVersion(cfg) workload := getWorkloadFromContext(ctx) - payload = checkSystemInstructionsWithSigningModeAt(payload, settings.strictMode, cchSigning, billingVersion, "cli", workload, claudeCodeCurrentTime(cfg, auth)) + + isSubagent := false + prevReq := "" + promptID := "" + if !helps.IsClaudeProbeOrHelperRequest(payload) { + incomingHeaders := resolveIncomingClaudeHeaders(ctx, helps.IncomingHeadersFromContext(ctx)) + isSubagent = helps.IsClaudeSubagentRequest(incomingHeaders, payload) + existingPrevReq, existingPromptID := helps.ExtractClaudeBillingTags(payload) + + sessionID := helps.ClaudeSessionIDFromContext(ctx) + if sessionID == "" && auth != nil { + sessionID = helps.ClaudeAgentSessionUUIDForRequest(incomingHeaders, payload, payload, confirmedClaudeCode) + } + + if sessionID != "" && auth != nil { + credIdentity := claudeDiagnosticsCredentialIdentity(auth) + isNewTurn := helps.IsClaudeNewPromptTurn(payload) + continuityKey, seq, prevMsgID, storedPrevReq, storedPromptID := helps.BeginClaudeContinuity(credIdentity, sessionID, isNewTurn, existingPromptID) + + if existingPromptID != "" { + promptID = existingPromptID + } else { + promptID = storedPromptID + } + if storedPrevReq != "" { + prevReq = storedPrevReq + } else { + prevReq = existingPrevReq + } + + if continuityCtx := helps.ClaudeContinuityContextFromContext(ctx); continuityCtx != nil { + continuityCtx.Key = continuityKey + continuityCtx.Sequence = seq + continuityCtx.PreviousMessageID = prevMsgID + continuityCtx.PreviousRequestID = prevReq + continuityCtx.PromptID = promptID + continuityCtx.Initialized = true + } + } + } + + payload = checkSystemInstructionsWithSigningModeAt( + payload, + settings.strictMode, + cchSigning, + billingVersion, + "cli", + workload, + claudeCodeCurrentTime(cfg, auth), + isSubagent, + prevReq, + promptID, + ) // Claude-Code-CLI fingerprint identity (real OAuth or fingerprint-profile=claude-code-cli) // is applied later through the shared ApplyClaudeCredentialMetadata path. diff --git a/internal/runtime/executor/claude_executor_diagnostics.go b/internal/runtime/executor/claude_executor_diagnostics.go index cc81ccb171..81910bcd8b 100644 --- a/internal/runtime/executor/claude_executor_diagnostics.go +++ b/internal/runtime/executor/claude_executor_diagnostics.go @@ -14,13 +14,22 @@ import ( type claudeDiagnosticsRequestState struct { key string sequence uint64 + promptID string } func injectClaudeDiagnostics(body []byte, auth *cliproxyauth.Auth, sessionID string) ([]byte, claudeDiagnosticsRequestState) { - key, sequence, previousMessageID := helps.BeginClaudeDiagnostics(claudeDiagnosticsCredentialIdentity(auth), sessionID) + key, sequence, previousMessageID, _, promptID := helps.BeginClaudeContinuity(claudeDiagnosticsCredentialIdentity(auth), sessionID, false, "") + return injectClaudeDiagnosticsWithState(body, key, sequence, previousMessageID, promptID) +} + +func injectClaudeDiagnosticsWithState(body []byte, key string, sequence uint64, previousMessageID string, promptIDs ...string) ([]byte, claudeDiagnosticsRequestState) { if key == "" { return body, claudeDiagnosticsRequestState{} } + promptID := "" + if len(promptIDs) > 0 { + promptID = promptIDs[0] + } value := `{"previous_message_id":null}` if previousMessageID != "" { value = `{"previous_message_id":` + marshalJSONStringWithoutHTMLEscape(previousMessageID) + `}` @@ -29,7 +38,7 @@ func injectClaudeDiagnostics(body []byte, auth *cliproxyauth.Auth, sessionID str if diagnostics := gjson.GetBytes(body, "diagnostics"); diagnostics.Exists() { updated, errSet := sjson.SetRawBytes(body, "diagnostics", []byte(value)) if errSet == nil { - return updated, claudeDiagnosticsRequestState{key: key, sequence: sequence} + return updated, claudeDiagnosticsRequestState{key: key, sequence: sequence, promptID: promptID} } } if contextManagement := gjson.GetBytes(body, "context_management"); contextManagement.Exists() { @@ -41,14 +50,22 @@ func injectClaudeDiagnostics(body []byte, auth *cliproxyauth.Auth, sessionID str updated = append(updated, `,"diagnostics":`...) updated = append(updated, value...) updated = append(updated, body[insertAt:]...) - return updated, claudeDiagnosticsRequestState{key: key, sequence: sequence} + return updated, claudeDiagnosticsRequestState{key: key, sequence: sequence, promptID: promptID} } } updated, errSet := sjson.SetRawBytes(body, "diagnostics", []byte(value)) if errSet != nil { return body, claudeDiagnosticsRequestState{} } - return updated, claudeDiagnosticsRequestState{key: key, sequence: sequence} + return updated, claudeDiagnosticsRequestState{key: key, sequence: sequence, promptID: promptID} +} + +func commitClaudeContinuity(state claudeDiagnosticsRequestState, messageID, requestID string) { + helps.CommitClaudeContinuity(state.key, state.sequence, messageID, requestID, state.promptID) +} + +func commitClaudeDiagnostics(state claudeDiagnosticsRequestState, messageID string) { + commitClaudeContinuity(state, messageID, "") } func claudeDiagnosticsCredentialIdentity(auth *cliproxyauth.Auth) string { @@ -71,10 +88,6 @@ func claudeDiagnosticsCredentialIdentity(auth *cliproxyauth.Auth) string { return "" } -func commitClaudeDiagnostics(state claudeDiagnosticsRequestState, messageID string) { - helps.CommitClaudeDiagnostics(state.key, state.sequence, messageID) -} - func claudeMessageIDFromResponse(data []byte) string { return strings.TrimSpace(gjson.GetBytes(data, "id").String()) } diff --git a/internal/runtime/executor/claude_executor_diagnostics_test.go b/internal/runtime/executor/claude_executor_diagnostics_test.go index 891a9c1b89..b58fb78278 100644 --- a/internal/runtime/executor/claude_executor_diagnostics_test.go +++ b/internal/runtime/executor/claude_executor_diagnostics_test.go @@ -3,6 +3,7 @@ package executor import ( "bytes" "context" + "fmt" "io" "net/http" "strings" @@ -109,3 +110,157 @@ func TestClaudeMessageIDFromSSECommitsOnlyCompletedMessage(t *testing.T) { t.Fatalf("incomplete SSE message ID = %q, want empty", got) } } + +func TestClaudeExecutorContinuityAdvancesRequestIDAndPromptIDInBillingHeader(t *testing.T) { + var capturedBillingHeaders []string + call := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, errRead := io.ReadAll(req.Body) + if errRead != nil { + t.Fatal(errRead) + } + billing := gjson.GetBytes(body, "system.0.text").String() + capturedBillingHeaders = append(capturedBillingHeaders, billing) + call++ + response := `{"id":"msg_turn_` + string(rune('0'+call)) + `","type":"message","model":"claude-sonnet-5","role":"assistant","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":1,"output_tokens":1}}` + header := http.Header{ + "Content-Type": []string{"application/json"}, + "request-id": []string{fmt.Sprintf("req_upstream_turn_%d", call)}, + } + return &http.Response{StatusCode: http.StatusOK, Header: header, Body: io.NopCloser(strings.NewReader(response)), Request: req}, nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + deviceIDs := []string{"0000000000000000000000000000000000000000000000000000000000000000"} + testID := uuid.NewString() + auth := &cliproxyauth.Auth{ + ID: "continuity-test-" + testID, + Attributes: map[string]string{"api_key": "sk-ant-oat-continuity-test"}, + Metadata: map[string]any{ + "account_uuid": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + claudeauth.ClaudeDeviceIDsMetadataKey: deviceIDs, + }, + } + executor := NewClaudeExecutor(&config.Config{}) + options := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + Metadata: map[string]any{cliproxyexecutor.ExecutionSessionMetadataKey: "continuity-conv-" + testID}, + } + + // Turn 1: User prompt + req1 := cliproxyexecutor.Request{Model: "claude-sonnet-5", Payload: []byte(`{"model":"claude-sonnet-5","messages":[{"role":"user","content":"turn 1 prompt"}],"max_tokens":100}`)} + if _, err := executor.Execute(ctx, auth, req1, options); err != nil { + t.Fatalf("turn 1 failed: %v", err) + } + + // Turn 2: User prompt in same conversation + req2 := cliproxyexecutor.Request{Model: "claude-sonnet-5", Payload: []byte(`{"model":"claude-sonnet-5","messages":[{"role":"user","content":"turn 1 prompt"},{"role":"assistant","content":"ok"},{"role":"user","content":"turn 2 prompt"}],"max_tokens":100}`)} + if _, err := executor.Execute(ctx, auth, req2, options); err != nil { + t.Fatalf("turn 2 failed: %v", err) + } + + // Turn 2.1: Tool result continuation within turn 2 + req2Tool := cliproxyexecutor.Request{Model: "claude-sonnet-5", Payload: []byte(`{"model":"claude-sonnet-5","messages":[{"role":"user","content":"turn 1 prompt"},{"role":"assistant","content":"ok"},{"role":"user","content":"turn 2 prompt"},{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"bash","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"tool output"}]}],"max_tokens":100}`)} + if _, err := executor.Execute(ctx, auth, req2Tool, options); err != nil { + t.Fatalf("turn 2.1 tool failed: %v", err) + } + + // Turn 3: Probe request (max_tokens: 1) + reqProbe := cliproxyexecutor.Request{Model: "claude-sonnet-5", Payload: []byte(`{"model":"claude-sonnet-5","messages":[{"role":"user","content":"probe"}],"max_tokens":1}`)} + if _, err := executor.Execute(ctx, auth, reqProbe, options); err != nil { + t.Fatalf("probe failed: %v", err) + } + + // Turn 4: Subagent request (carrying X-Claude-Code-Agent-Id) + subagentOptions := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + Headers: http.Header{"X-Claude-Code-Agent-Id": []string{"subagent-worker-1"}}, + Metadata: map[string]any{cliproxyexecutor.ExecutionSessionMetadataKey: "continuity-subagent-" + testID}, + } + reqSubagent := cliproxyexecutor.Request{Model: "claude-sonnet-5", Payload: []byte(`{"model":"claude-sonnet-5","messages":[{"role":"user","content":"subagent prompt"}],"max_tokens":100}`)} + if _, err := executor.Execute(ctx, auth, reqSubagent, subagentOptions); err != nil { + t.Fatalf("subagent failed: %v", err) + } + + // Turn 5: Resumed main session user prompt after probe (must chain from turn 2.1, NOT from probe turn 3) + req5 := cliproxyexecutor.Request{Model: "claude-sonnet-5", Payload: []byte(`{"model":"claude-sonnet-5","messages":[{"role":"user","content":"turn 5 prompt"}],"max_tokens":100}`)} + if _, err := executor.Execute(ctx, auth, req5, options); err != nil { + t.Fatalf("turn 5 failed: %v", err) + } + + if len(capturedBillingHeaders) != 6 { + t.Fatalf("captured %d billing headers, want 6", len(capturedBillingHeaders)) + } + + // Verify Turn 1: + h1 := capturedBillingHeaders[0] + if !strings.Contains(h1, "cc_version=2.1.258.") || !strings.Contains(h1, "cc_entrypoint=cli;") || !strings.Contains(h1, "cch=") { + t.Fatalf("h1 invalid: %s", h1) + } + if strings.Contains(h1, "cc_prev_req=") { + t.Fatalf("h1 must not contain cc_prev_req: %s", h1) + } + if !strings.Contains(h1, "cc_prompt_id=") { + t.Fatalf("h1 must contain cc_prompt_id: %s", h1) + } + prompt1 := extractTag(h1, "cc_prompt_id=") + + // Verify Turn 2: + h2 := capturedBillingHeaders[1] + if !strings.Contains(h2, "cc_prev_req=req_upstream_turn_1;") { + t.Fatalf("h2 must contain cc_prev_req=req_upstream_turn_1;, got: %s", h2) + } + if !strings.Contains(h2, "cc_prompt_id=") { + t.Fatalf("h2 must contain cc_prompt_id: %s", h2) + } + prompt2 := extractTag(h2, "cc_prompt_id=") + if prompt2 == prompt1 { + t.Fatalf("h2 promptID (%s) must differ from h1 promptID (%s)", prompt2, prompt1) + } + + // Verify Turn 2.1 (tool continuation): + h2Tool := capturedBillingHeaders[2] + if !strings.Contains(h2Tool, "cc_prev_req=req_upstream_turn_2;") { + t.Fatalf("h2Tool must contain cc_prev_req=req_upstream_turn_2;, got: %s", h2Tool) + } + prompt2Tool := extractTag(h2Tool, "cc_prompt_id=") + if prompt2Tool != prompt2 { + t.Fatalf("h2Tool promptID (%s) must match turn 2 promptID (%s)", prompt2Tool, prompt2) + } + + // Verify Turn 3 (probe with max_tokens: 1): + hProbe := capturedBillingHeaders[3] + if strings.Contains(hProbe, "cc_prev_req=") || strings.Contains(hProbe, "cc_prompt_id=") { + t.Fatalf("probe must not contain cc_prev_req or cc_prompt_id: %s", hProbe) + } + + // Verify Turn 4 (subagent): + hSubagent := capturedBillingHeaders[4] + if !strings.Contains(hSubagent, "cc_is_subagent=true;") { + t.Fatalf("hSubagent must contain cc_is_subagent=true;, got: %s", hSubagent) + } + if !strings.Contains(hSubagent, "cc_prompt_id=") { + t.Fatalf("hSubagent must contain cc_prompt_id: %s", hSubagent) + } + + // Verify Turn 5 (main turn after probe): + // Must chain to turn 2.1's response (req_upstream_turn_3), bypassing probe turn 3 (req_upstream_turn_4)! + h5 := capturedBillingHeaders[5] + if !strings.Contains(h5, "cc_prev_req=req_upstream_turn_3;") { + t.Fatalf("h5 must contain cc_prev_req=req_upstream_turn_3; (bypassing probe turn 4), got: %s", h5) + } + if !strings.Contains(h5, "cc_prompt_id=") { + t.Fatalf("h5 must contain cc_prompt_id: %s", h5) + } +} + +func extractTag(header, prefix string) string { + idx := strings.Index(header, prefix) + if idx < 0 { + return "" + } + val := header[idx+len(prefix):] + if end := strings.IndexByte(val, ';'); end >= 0 { + val = val[:end] + } + return val +} diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index 372b432dbe..69d368ed69 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -62,6 +62,14 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r if fp.ProfileClaudeCodeCLI { claudeSessionID = helps.ClaudeAgentSessionUUIDForRequest(incomingHeaders, originalPayload, req.Payload, confirmedClaudeCode, opts.Metadata, req.Metadata) } + + continuityCtx := &helps.ClaudeContinuityContext{} + ctx = helps.WithClaudeContinuityContext(ctx, continuityCtx) + ctx = helps.WithIncomingHeaders(ctx, incomingHeaders) + if claudeSessionID != "" { + ctx = helps.WithClaudeSessionID(ctx, claudeSessionID) + } + originalTranslated := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, upstreamStream, helps.APIKeyModelIsCompat(req)) body := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, upstreamStream, helps.APIKeyModelIsCompat(req)) body = helps.SetStringIfDifferent(body, "model", upstreamModel) @@ -94,14 +102,26 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r // Only the Messages endpoint on Anthropic itself was captured; count_tokens // keeps its own shape and other gateways never see this field. diagnosticsState := claudeDiagnosticsRequestState{} + isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(body) + if continuityCtx.Initialized { + diagnosticsState = claudeDiagnosticsRequestState{ + key: continuityCtx.Key, + sequence: continuityCtx.Sequence, + promptID: continuityCtx.PromptID, + } + } contextManagementState := claudeCodeContextManagementState{ eligible: cloaked && isAnthropicUpstreamBase(baseURL), callerOwned: gjson.GetBytes(body, "context_management").Exists(), } if contextManagementState.eligible { body, contextManagementState.automaticallyInjected = injectClaudeCodeContextManagement(body) - if fp.InjectDiagnostics { - body, diagnosticsState = injectClaudeDiagnostics(body, auth, claudeSessionID) + if fp.InjectDiagnostics && !isProbeOrHelper { + if continuityCtx.Initialized { + body, diagnosticsState = injectClaudeDiagnosticsWithState(body, continuityCtx.Key, continuityCtx.Sequence, continuityCtx.PreviousMessageID, continuityCtx.PromptID) + } else { + body, diagnosticsState = injectClaudeDiagnostics(body, auth, claudeSessionID) + } } } @@ -291,7 +311,9 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r helps.RecordAPIResponseError(ctx, e.cfg, errValidate) return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, errValidate) } - commitClaudeDiagnostics(diagnosticsState, claudeMessageIDFromSSE(data)) + if msgID := claudeMessageIDFromSSE(data); msgID != "" { + commitClaudeContinuity(diagnosticsState, msgID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) + } lines := bytes.Split(data, []byte("\n")) for i, line := range lines { if detail, ok := helps.ParseClaudeStreamUsage(line); ok { @@ -307,7 +329,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r } data = bytes.Join(lines, []byte("\n")) } else { - commitClaudeDiagnostics(diagnosticsState, claudeMessageIDFromResponse(data)) + commitClaudeContinuity(diagnosticsState, claudeMessageIDFromResponse(data), helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) reporter.Publish(ctx, helps.ParseClaudeUsage(data)) var errRestore error data, errRestore = restoreClaudeOAuthToolNamesFromResponse(data, oauthToolNamesReverseMap) diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index 865b3bdad4..cf9ccd6dfb 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -65,6 +65,14 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if fp.ProfileClaudeCodeCLI { claudeSessionID = helps.ClaudeAgentSessionUUIDForRequest(incomingHeaders, originalPayload, req.Payload, confirmedClaudeCode, opts.Metadata, req.Metadata) } + + continuityCtx := &helps.ClaudeContinuityContext{} + ctx = helps.WithClaudeContinuityContext(ctx, continuityCtx) + ctx = helps.WithIncomingHeaders(ctx, incomingHeaders) + if claudeSessionID != "" { + ctx = helps.WithClaudeSessionID(ctx, claudeSessionID) + } + originalTranslated := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, true, helps.APIKeyModelIsCompat(req)) body := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, true, helps.APIKeyModelIsCompat(req)) body = helps.SetStringIfDifferent(body, "model", upstreamModel) @@ -97,14 +105,26 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A // Only the Messages endpoint on Anthropic itself was captured; count_tokens // keeps its own shape and other gateways never see this field. diagnosticsState := claudeDiagnosticsRequestState{} + isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(body) + if continuityCtx.Initialized { + diagnosticsState = claudeDiagnosticsRequestState{ + key: continuityCtx.Key, + sequence: continuityCtx.Sequence, + promptID: continuityCtx.PromptID, + } + } contextManagementState := claudeCodeContextManagementState{ eligible: cloaked && isAnthropicUpstreamBase(baseURL), callerOwned: gjson.GetBytes(body, "context_management").Exists(), } if contextManagementState.eligible { body, contextManagementState.automaticallyInjected = injectClaudeCodeContextManagement(body) - if fp.InjectDiagnostics { - body, diagnosticsState = injectClaudeDiagnostics(body, auth, claudeSessionID) + if fp.InjectDiagnostics && !isProbeOrHelper { + if continuityCtx.Initialized { + body, diagnosticsState = injectClaudeDiagnosticsWithState(body, continuityCtx.Key, continuityCtx.Sequence, continuityCtx.PreviousMessageID, continuityCtx.PromptID) + } else { + body, diagnosticsState = injectClaudeDiagnostics(body, auth, claudeSessionID) + } } } @@ -356,7 +376,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return } if upstreamCompleted { - commitClaudeDiagnostics(diagnosticsState, upstreamMessageID) + commitClaudeContinuity(diagnosticsState, upstreamMessageID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) } return } @@ -418,7 +438,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return } if upstreamCompleted { - commitClaudeDiagnostics(diagnosticsState, upstreamMessageID) + commitClaudeContinuity(diagnosticsState, upstreamMessageID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) } }() result := &cliproxyexecutor.StreamResult{Headers: httpResp.Header.Clone(), Chunks: out} diff --git a/internal/runtime/executor/helps/claude_code_session.go b/internal/runtime/executor/helps/claude_code_session.go index ea70390447..ba07b21397 100644 --- a/internal/runtime/executor/helps/claude_code_session.go +++ b/internal/runtime/executor/helps/claude_code_session.go @@ -61,6 +61,24 @@ func HeaderValueCaseInsensitive(headers http.Header, name string) string { return headerValueCaseInsensitive(headers, name) } +// HeaderValuesCaseInsensitive returns all non-empty header values matching name case-insensitively. +func HeaderValuesCaseInsensitive(headers http.Header, name string) []string { + if headers == nil { + return nil + } + var result []string + for key, values := range headers { + if strings.EqualFold(key, name) { + for _, value := range values { + if trimmed := strings.TrimSpace(value); trimmed != "" { + result = append(result, trimmed) + } + } + } + } + return result +} + func headerValueCaseInsensitive(headers http.Header, name string) string { if headers == nil { return "" diff --git a/internal/runtime/executor/helps/claude_diagnostics.go b/internal/runtime/executor/helps/claude_diagnostics.go index d1d0a99e0f..0da34549bc 100644 --- a/internal/runtime/executor/helps/claude_diagnostics.go +++ b/internal/runtime/executor/helps/claude_diagnostics.go @@ -1,12 +1,19 @@ package helps import ( + "context" "crypto/sha256" "encoding/hex" + "net/http" + "regexp" "sort" "strings" "sync" "time" + + "github.com/google/uuid" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) const ( @@ -16,8 +23,90 @@ const ( claudeDiagnosticsEvictBatchSize = 256 ) +var ( + claudeRequestIDPattern = regexp.MustCompile(`^req_[A-Za-z0-9_-]{1,36}$`) + claudePromptIDPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) +) + +type claudeContextKey string + +const ( + claudeSessionIDContextKey claudeContextKey = "cpa_claude_session_id" + claudeContinuityContextKey claudeContextKey = "cpa_claude_continuity_ctx" + claudeIncomingHeadersContextKey claudeContextKey = "cpa_claude_incoming_headers" +) + +// WithIncomingHeaders attaches incoming HTTP headers to ctx. +func WithIncomingHeaders(ctx context.Context, headers http.Header) context.Context { + if headers == nil { + return ctx + } + return context.WithValue(ctx, claudeIncomingHeadersContextKey, headers) +} + +// IncomingHeadersFromContext retrieves incoming HTTP headers from ctx, if present. +func IncomingHeadersFromContext(ctx context.Context) http.Header { + if ctx == nil { + return nil + } + if h, ok := ctx.Value(claudeIncomingHeadersContextKey).(http.Header); ok { + return h + } + return nil +} + +// ClaudeContinuityContext holds request-scoped continuity state across cloaking and execution. +type ClaudeContinuityContext struct { + Key string + Sequence uint64 + PreviousMessageID string + PreviousRequestID string + PromptID string + Initialized bool +} + +// WithClaudeSessionID attaches a known Claude session ID to ctx. +func WithClaudeSessionID(ctx context.Context, sessionID string) context.Context { + if sessionID == "" { + return ctx + } + return context.WithValue(ctx, claudeSessionIDContextKey, sessionID) +} + +// ClaudeSessionIDFromContext retrieves the Claude session ID from ctx, if present. +func ClaudeSessionIDFromContext(ctx context.Context) string { + if ctx == nil { + return "" + } + if val, ok := ctx.Value(claudeSessionIDContextKey).(string); ok { + return val + } + return "" +} + +// WithClaudeContinuityContext attaches a mutable ClaudeContinuityContext to ctx. +func WithClaudeContinuityContext(ctx context.Context, cc *ClaudeContinuityContext) context.Context { + if cc == nil { + return ctx + } + return context.WithValue(ctx, claudeContinuityContextKey, cc) +} + +// ClaudeContinuityContextFromContext retrieves the ClaudeContinuityContext from ctx, if present. +func ClaudeContinuityContextFromContext(ctx context.Context) *ClaudeContinuityContext { + if ctx == nil { + return nil + } + if cc, ok := ctx.Value(claudeContinuityContextKey).(*ClaudeContinuityContext); ok { + return cc + } + return nil +} + type claudeDiagnosticsEntry struct { previousMessageID string + previousRequestID string + promptID string minimumSequence uint64 committedSequence uint64 lastAccess uint64 @@ -32,16 +121,26 @@ var claudeDiagnosticsState = struct { nextAccess uint64 }{entries: make(map[string]claudeDiagnosticsEntry)} -// BeginClaudeDiagnostics starts one request generation for a stable credential -// identity and Claude conversation. It returns the last successfully completed -// upstream message ID, if any. Only a SHA-256 digest of the credential identity -// and session is retained as the cache key, so access-token rotation does not -// interrupt continuity. -func BeginClaudeDiagnostics(credentialIdentity, sessionID string) (key string, sequence uint64, previousMessageID string) { +// IsValidClaudePromptID verifies whether an explicit prompt ID adheres to strict RFC 4122 UUIDv4 semantics. +func IsValidClaudePromptID(id string) bool { + id = strings.TrimSpace(id) + if !claudePromptIDPattern.MatchString(id) { + return false + } + parsed, err := uuid.Parse(id) + return err == nil && parsed.Version() == 4 && parsed.Variant() == uuid.RFC4122 +} + +// BeginClaudeContinuity starts one request generation for a stable credential +// identity and Claude conversation. It tracks the previous upstream message ID, +// previous upstream request ID (cc_prev_req), and active prompt ID (cc_prompt_id). +// If explicitPromptID is provided and valid, it is adopted. Otherwise if isNewPromptTurn +// is true (or if no prompt ID exists), a fresh UUIDv4 is generated. +func BeginClaudeContinuity(credentialIdentity, sessionID string, isNewPromptTurn bool, explicitPromptID string) (key string, sequence uint64, previousMessageID, previousRequestID, promptID string) { credentialIdentity = strings.TrimSpace(credentialIdentity) sessionID = strings.TrimSpace(sessionID) if credentialIdentity == "" || sessionID == "" { - return "", 0, "" + return "", 0, "", "", "" } digest := sha256.Sum256([]byte(credentialIdentity + "\x00" + sessionID)) key = hex.EncodeToString(digest[:]) @@ -62,19 +161,39 @@ func BeginClaudeDiagnostics(credentialIdentity, sessionID string) (key string, s if newGeneration { entry = claudeDiagnosticsEntry{minimumSequence: sequence} } + + activePromptID := entry.promptID + explicitPromptID = strings.TrimSpace(explicitPromptID) + if explicitPromptID != "" && IsValidClaudePromptID(explicitPromptID) { + activePromptID = strings.ToLower(explicitPromptID) + } else if isNewPromptTurn || activePromptID == "" { + activePromptID = uuid.NewString() + } + claudeDiagnosticsState.nextAccess++ entry.lastAccess = claudeDiagnosticsState.nextAccess entry.expiresAt = now.Add(claudeDiagnosticsTTL) claudeDiagnosticsState.entries[key] = entry - return key, sequence, entry.previousMessageID + return key, sequence, entry.previousMessageID, entry.previousRequestID, activePromptID } -// CommitClaudeDiagnostics advances continuity only after a response completes. -// A response from an older concurrently-started request cannot overwrite a -// newer committed generation, including after TTL expiry or capacity eviction. -func CommitClaudeDiagnostics(key string, sequence uint64, messageID string) { +// BeginClaudeDiagnostics starts one request generation for a stable credential +// identity and Claude conversation. It returns the last successfully completed +// upstream message ID, if any. Only a SHA-256 digest of the credential identity +// and session is retained as the cache key, so access-token rotation does not +// interrupt continuity. +func BeginClaudeDiagnostics(credentialIdentity, sessionID string) (key string, sequence uint64, previousMessageID string) { + key, sequence, prevMsg, _, _ := BeginClaudeContinuity(credentialIdentity, sessionID, false, "") + return key, sequence, prevMsg +} + +// CommitClaudeContinuity advances continuity only after a response completes. +// It commits the upstream message ID (msg_01...), request ID (req_01...), and prompt ID (cc_prompt_id). +// A non-empty messageID is required so incomplete/truncated streams do not advance sequence. +func CommitClaudeContinuity(key string, sequence uint64, messageID, requestID string, promptIDs ...string) { key = strings.TrimSpace(key) messageID = strings.TrimSpace(messageID) + requestID = strings.TrimSpace(requestID) if key == "" || sequence == 0 || messageID == "" { return } @@ -83,17 +202,34 @@ func CommitClaudeDiagnostics(key string, sequence uint64, messageID string) { claudeDiagnosticsState.Lock() defer claudeDiagnosticsState.Unlock() entry, ok := claudeDiagnosticsState.entries[key] - if !ok || sequence < entry.minimumSequence || sequence < entry.committedSequence { + if !ok || (!entry.expiresAt.IsZero() && now.After(entry.expiresAt)) || sequence < entry.minimumSequence || sequence < entry.committedSequence { return } claudeDiagnosticsState.nextAccess++ entry.previousMessageID = messageID + if requestID != "" && claudeRequestIDPattern.MatchString(requestID) { + entry.previousRequestID = requestID + } else { + entry.previousRequestID = "" + } + if len(promptIDs) > 0 { + if pID := strings.TrimSpace(promptIDs[0]); pID != "" && IsValidClaudePromptID(pID) { + entry.promptID = strings.ToLower(pID) + } + } entry.committedSequence = sequence entry.lastAccess = claudeDiagnosticsState.nextAccess entry.expiresAt = now.Add(claudeDiagnosticsTTL) claudeDiagnosticsState.entries[key] = entry } +// CommitClaudeDiagnostics advances continuity only after a response completes. +// A response from an older concurrently-started request cannot overwrite a +// newer committed generation, including after TTL expiry or capacity eviction. +func CommitClaudeDiagnostics(key string, sequence uint64, messageID string) { + CommitClaudeContinuity(key, sequence, messageID, "") +} + func cleanupClaudeDiagnosticsLocked(now time.Time) { if !claudeDiagnosticsState.lastCleanup.IsZero() && now.Sub(claudeDiagnosticsState.lastCleanup) < claudeDiagnosticsCleanupPeriod { return @@ -127,6 +263,11 @@ func evictClaudeDiagnosticsLocked() { } } +// ResetClaudeDiagnosticsForTest resets in-memory continuity state for test isolation. +func ResetClaudeDiagnosticsForTest() { + resetClaudeDiagnosticsForTest() +} + func resetClaudeDiagnosticsForTest() { claudeDiagnosticsState.Lock() defer claudeDiagnosticsState.Unlock() @@ -135,3 +276,286 @@ func resetClaudeDiagnosticsForTest() { claudeDiagnosticsState.nextSequence = 0 claudeDiagnosticsState.nextAccess = 0 } + +// IsClaudeNewPromptTurn inspects the request messages to determine whether +// this request starts a new user prompt turn (requiring a new cc_prompt_id) +// versus a tool continuation step (which reuses the current cc_prompt_id). +func IsClaudeNewPromptTurn(body []byte) bool { + if IsClaudeProbeOrHelperRequest(body) { + return false + } + messages := gjson.GetBytes(body, "messages") + if !messages.IsArray() { + return true + } + arr := messages.Array() + if len(arr) == 0 { + return true + } + lastMsg := arr[len(arr)-1] + if lastMsg.Get("role").String() != "user" { + return false + } + content := lastMsg.Get("content") + if content.IsArray() { + // If any element is a tool_result, this is a tool continuation turn. + for _, part := range content.Array() { + if part.Get("type").String() == "tool_result" { + return false + } + } + } + return true +} + +var ( + claudePrevReqBillingPattern = regexp.MustCompile(`\s*cc_prev_req=[^;]+;`) + claudePromptIDBillingPattern = regexp.MustCompile(`\s*cc_prompt_id=[^;]+;`) +) + +func isClaudeProbeRequest(body []byte) bool { + maxTokens := gjson.GetBytes(body, "max_tokens") + if !maxTokens.Exists() || maxTokens.Int() != 1 { + return false + } + tools := gjson.GetBytes(body, "tools") + if tools.Exists() && len(tools.Array()) > 0 { + return false + } + messages := gjson.GetBytes(body, "messages") + if !messages.Exists() || !messages.IsArray() || len(messages.Array()) == 0 { + return true // headless preflight probe without messages + } + arr := messages.Array() + if len(arr) != 1 { + return false + } + firstMsg := arr[0] + if firstMsg.Get("role").String() != "user" { + return false + } + content := firstMsg.Get("content") + if content.Type == gjson.String { + str := strings.TrimSpace(content.String()) + return str == "quota" || str == "test" || str == "." || str == "probe" + } + if content.IsArray() { + nonReminderCount := 0 + matched := false + for _, part := range content.Array() { + t := strings.TrimSpace(part.Get("text").String()) + if strings.Contains(t, "") { + continue + } + nonReminderCount++ + if t == "quota" || t == "test" || t == "." || t == "probe" || (t == "Hi" && part.Get("cache_control").Exists()) { + matched = true + } + } + return nonReminderCount == 1 && matched + } + return false +} + +func isClaudeTitleHelperInstruction(body []byte) bool { + matchesTitlePrompt := func(t string) bool { + return strings.Contains(t, "Return a short title") || + strings.Contains(t, "naming a coding session") || + strings.Contains(t, "Write the title in the predominant language") || + strings.Contains(t, "") + } + system := gjson.GetBytes(body, "system") + if system.IsArray() { + for _, part := range system.Array() { + if matchesTitlePrompt(part.Get("text").String()) { + return true + } + } + } else if matchesTitlePrompt(system.String()) { + return true + } + messages := gjson.GetBytes(body, "messages") + if messages.IsArray() { + for _, msg := range messages.Array() { + content := msg.Get("content") + if content.IsArray() { + for _, part := range content.Array() { + if matchesTitlePrompt(part.Get("text").String()) { + return true + } + } + } else if matchesTitlePrompt(content.String()) { + return true + } + } + } + return false +} + +func isClaudeTitleHelperRequest(body []byte) bool { + props := gjson.GetBytes(body, "output_config.format.schema.properties") + if props.Exists() { + if props.Get("title").Exists() && len(props.Map()) == 1 { + return isClaudeTitleHelperInstruction(body) + } + return false + } + + // When structured output schema is absent, it can only be an internal helper + // if a system-role block (either in system or in messages) contains the title instruction. + // Ordinary user messages ("role": "user") without a title schema are never internal helpers. + matchesSystemTitleInstruction := func(t string) bool { + return strings.Contains(t, "naming a coding session") || + strings.Contains(t, "Return a short title") || + strings.Contains(t, "Write the title in the predominant language") + } + system := gjson.GetBytes(body, "system") + if system.IsArray() { + for _, part := range system.Array() { + if matchesSystemTitleInstruction(part.Get("text").String()) { + return true + } + } + } else if matchesSystemTitleInstruction(system.String()) { + return true + } + + messages := gjson.GetBytes(body, "messages") + if messages.IsArray() { + for _, msg := range messages.Array() { + if msg.Get("role").String() == "system" { + content := msg.Get("content") + if content.IsArray() { + for _, part := range content.Array() { + if matchesSystemTitleInstruction(part.Get("text").String()) { + return true + } + } + } else if matchesSystemTitleInstruction(content.String()) { + return true + } + } + } + } + return false +} + +// IsClaudeProbeOrHelperRequest reports whether the request is a minimal +// probe/preflight (max_tokens: 1) or an automated title generation helper, +// which in native Claude Code do not emit cc_prompt_id or cc_prev_req. +func IsClaudeProbeOrHelperRequest(body []byte) bool { + return isClaudeProbeRequest(body) || isClaudeTitleHelperRequest(body) +} + +// IsClaudeSubagentRequest reports whether the incoming request originates from +// or represents a Claude Code subagent. +func IsClaudeSubagentRequest(headers http.Header, body []byte) bool { + if val := HeaderValueCaseInsensitive(headers, "X-Claude-Code-Agent-Id"); val != "" { + return true + } + if val := HeaderValueCaseInsensitive(headers, "X-Claude-Code-Parent-Agent-Id"); val != "" { + return true + } + if gjson.GetBytes(body, "metadata.user_id.parent_session_id").Exists() { + return true + } + if userID := gjson.GetBytes(body, "metadata.user_id").String(); userID != "" { + if strings.Contains(userID, `"parent_session_id"`) { + return true + } + } + // Only inspect system[0].text or billing header for cc_is_subagent, never raw user message content + system := gjson.GetBytes(body, "system") + if system.IsArray() && len(system.Array()) > 0 { + if strings.Contains(system.Array()[0].Get("text").String(), "cc_is_subagent=true") { + return true + } + } else if system.Type == gjson.String && strings.Contains(system.String(), "cc_is_subagent=true") { + return true + } + return false +} + +// StripClaudeBillingTags removes cc_prev_req and cc_prompt_id from the billing header in body. +func StripClaudeBillingTags(body []byte) []byte { + system := gjson.GetBytes(body, "system") + if !system.IsArray() || len(system.Array()) == 0 { + return body + } + billingText := system.Array()[0].Get("text").String() + if !strings.HasPrefix(billingText, "x-anthropic-billing-header:") { + return body + } + cleaned := claudePrevReqBillingPattern.ReplaceAllString(billingText, "") + cleaned = claudePromptIDBillingPattern.ReplaceAllString(cleaned, "") + if cleaned != billingText { + updated, err := sjson.SetBytes(body, "system.0.text", cleaned) + if err == nil { + return updated + } + } + return body +} + +// InjectClaudeBillingTags appends cc_prev_req and cc_prompt_id to the billing header in body if present. +func InjectClaudeBillingTags(body []byte, prevReq, promptID string) []byte { + system := gjson.GetBytes(body, "system") + if !system.IsArray() || len(system.Array()) == 0 { + return body + } + billingText := system.Array()[0].Get("text").String() + if !strings.HasPrefix(billingText, "x-anthropic-billing-header:") { + return body + } + cleaned := claudePrevReqBillingPattern.ReplaceAllString(billingText, "") + cleaned = claudePromptIDBillingPattern.ReplaceAllString(cleaned, "") + cleaned = strings.TrimSpace(cleaned) + if !strings.HasSuffix(cleaned, ";") { + cleaned += ";" + } + if prevReq != "" { + cleaned += " cc_prev_req=" + prevReq + ";" + } + if promptID != "" { + cleaned += " cc_prompt_id=" + promptID + ";" + } + updated, err := sjson.SetBytes(body, "system.0.text", cleaned) + if err == nil { + return updated + } + return body +} + +// ExtractClaudeBillingTags extracts existing cc_prev_req and cc_prompt_id values +// from a billing header in system text, if present. +func ExtractClaudeBillingTags(body []byte) (prevReq, promptID string) { + system := gjson.GetBytes(body, "system") + var billingText string + if system.IsArray() && len(system.Array()) > 0 { + billingText = system.Array()[0].Get("text").String() + } else if system.Type == gjson.String { + billingText = system.String() + } + if billingText == "" || !strings.HasPrefix(billingText, "x-anthropic-billing-header:") { + return "", "" + } + if idx := strings.Index(billingText, "cc_prev_req="); idx >= 0 { + val := billingText[idx+len("cc_prev_req="):] + if end := strings.IndexByte(val, ';'); end >= 0 { + val = val[:end] + } + if claudeRequestIDPattern.MatchString(val) { + prevReq = val + } + } + if idx := strings.Index(billingText, "cc_prompt_id="); idx >= 0 { + val := billingText[idx+len("cc_prompt_id="):] + if end := strings.IndexByte(val, ';'); end >= 0 { + val = val[:end] + } + if IsValidClaudePromptID(val) { + promptID = strings.ToLower(val) + } + } + return prevReq, promptID +} diff --git a/internal/runtime/executor/helps/claude_diagnostics_test.go b/internal/runtime/executor/helps/claude_diagnostics_test.go index 09a0e07539..073faacb35 100644 --- a/internal/runtime/executor/helps/claude_diagnostics_test.go +++ b/internal/runtime/executor/helps/claude_diagnostics_test.go @@ -2,8 +2,11 @@ package helps import ( "fmt" + "net/http" "testing" "time" + + "github.com/google/uuid" ) func TestClaudeDiagnosticsTracksCompletedMessagePerCredentialSession(t *testing.T) { @@ -100,3 +103,236 @@ func TestClaudeDiagnosticsRejectsLateOlderCommit(t *testing.T) { t.Fatalf("previous message = %q, want newer completed generation", previous) } } + +func TestClaudeContinuityTracksRequestIDAndPromptID(t *testing.T) { + resetClaudeDiagnosticsForTest() + defer resetClaudeDiagnosticsForTest() + + // Turn 1: New prompt turn + key, seq1, prevMsg, prevReq, prompt1 := BeginClaudeContinuity("cred-1", "sess-1", true, "") + if prevMsg != "" || prevReq != "" || prompt1 == "" { + t.Fatalf("turn 1 = prevMsg:%q prevReq:%q prompt:%q, want empty prevs and fresh prompt", prevMsg, prevReq, prompt1) + } + CommitClaudeContinuity(key, seq1, "msg_01aaa", "req_01bbb", prompt1) + + // Turn 1.1: Tool continuation turn (not new prompt) + _, seq2, prevMsg, prevReq, prompt2 := BeginClaudeContinuity("cred-1", "sess-1", false, "") + if prevMsg != "msg_01aaa" || prevReq != "req_01bbb" { + t.Fatalf("turn 1.1 = prevMsg:%q prevReq:%q, want msg_01aaa / req_01bbb", prevMsg, prevReq) + } + if prompt2 != prompt1 { + t.Fatalf("turn 1.1 prompt = %q, want same prompt %q as turn 1", prompt2, prompt1) + } + CommitClaudeContinuity(key, seq2, "msg_01ccc", "req_01ddd", prompt2) + + // Turn 2: New prompt turn + _, _, prevMsg, prevReq, prompt3 := BeginClaudeContinuity("cred-1", "sess-1", true, "") + if prevMsg != "msg_01ccc" || prevReq != "req_01ddd" { + t.Fatalf("turn 2 = prevMsg:%q prevReq:%q, want msg_01ccc / req_01ddd", prevMsg, prevReq) + } + if prompt3 == prompt1 { + t.Fatalf("turn 2 prompt = %q, want new prompt different from %q", prompt3, prompt1) + } +} + +func TestClaudeContinuityHelperPredicates(t *testing.T) { + probeBody := []byte(`{"model":"claude-fable-5-1","max_tokens":1,"messages":[{"role":"user","content":[{"type":"text","text":"Hi","cache_control":{"type":"ephemeral"}}]}]}`) + if !IsClaudeProbeOrHelperRequest(probeBody) { + t.Fatal("IsClaudeProbeOrHelperRequest(fable probe) = false, want true") + } + + quotaProbeBody := []byte(`{"model":"claude-haiku-4-5-20251001","max_tokens":1,"messages":[{"role":"user","content":"quota"}]}`) + if !IsClaudeProbeOrHelperRequest(quotaProbeBody) { + t.Fatal("IsClaudeProbeOrHelperRequest(quota probe) = false, want true") + } + + ordinaryHiMaxTokens1 := []byte(`{"model":"claude-fable-5-1","max_tokens":1,"messages":[{"role":"user","content":"Hi"}]}`) + if IsClaudeProbeOrHelperRequest(ordinaryHiMaxTokens1) { + t.Fatal("IsClaudeProbeOrHelperRequest(ordinary Hi max_tokens=1) = true, want false") + } + + multiTurnMaxTokens1 := []byte(`{"model":"claude-sonnet-5","max_tokens":1,"messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":"what is 1+1?"}]}`) + if IsClaudeProbeOrHelperRequest(multiTurnMaxTokens1) { + t.Fatal("IsClaudeProbeOrHelperRequest(multi-turn max_tokens=1) = true, want false") + } + + withToolsMaxTokens1 := []byte(`{"model":"claude-sonnet-5","max_tokens":1,"messages":[{"role":"user","content":"Hi"}],"tools":[{"name":"t1","description":"tool"}]}`) + if IsClaudeProbeOrHelperRequest(withToolsMaxTokens1) { + t.Fatal("IsClaudeProbeOrHelperRequest(tools max_tokens=1) = true, want false") + } + + titleBody := []byte(`{"model":"claude-haiku-4-5-20251001","output_config":{"format":{"schema":{"properties":{"title":{"type":"string"}}}}},"messages":[{"role":"user","content":"Return a short title summarizing this conversation"}]}`) + if !IsClaudeProbeOrHelperRequest(titleBody) { + t.Fatal("IsClaudeProbeOrHelperRequest(title helper) = false, want true") + } + + ordinaryTitleSchema := []byte(`{"model":"claude-haiku-4-5-20251001","output_config":{"format":{"schema":{"properties":{"title":{"type":"string"}}}}},"messages":[{"role":"user","content":"what is the title of the book?"}]}`) + if IsClaudeProbeOrHelperRequest(ordinaryTitleSchema) { + t.Fatal("IsClaudeProbeOrHelperRequest(ordinary title schema) = true, want false") + } + + relocatedTitleBody := []byte(`{"model":"claude-sonnet-5","system":[{"type":"text","text":"cli-identity"}],"messages":[{"role":"system","content":"Return a short title summarizing this conversation"}]}`) + if !IsClaudeProbeOrHelperRequest(relocatedTitleBody) { + t.Fatal("IsClaudeProbeOrHelperRequest(relocated title system in messages) = false, want true") + } + + toolResultBody := []byte(`{"model":"claude-sonnet-5","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":[{"type":"tool_use","id":"t1"}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"ok"}]}]}`) + if IsClaudeNewPromptTurn(toolResultBody) { + t.Fatal("IsClaudeNewPromptTurn(tool_result) = true, want false") + } + + newPromptBody := []byte(`{"model":"claude-sonnet-5","messages":[{"role":"user","content":"explain sorting"}]}`) + if !IsClaudeNewPromptTurn(newPromptBody) { + t.Fatal("IsClaudeNewPromptTurn(user text) = false, want true") + } + + subagentHeader := http.Header{"X-Claude-Code-Agent-Id": []string{"sub-1"}} + if !IsClaudeSubagentRequest(subagentHeader, []byte(`{}`)) { + t.Fatal("IsClaudeSubagentRequest(agent header) = false, want true") + } + + subagentMetaBody := []byte(`{"metadata":{"user_id":"{\"device_id\":\"dev\",\"session_id\":\"sess\",\"parent_session_id\":\"parent-1\"}"}}`) + if !IsClaudeSubagentRequest(nil, subagentMetaBody) { + t.Fatal("IsClaudeSubagentRequest(parent_session_id) = false, want true") + } + + billingSystemBody := []byte(`{"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.258.1e2; cc_entrypoint=cli; cch=00000; cc_prev_req=req_01abc; cc_prompt_id=3c6489dc-badc-42b2-bd28-49f8ebabfedd;"}]}`) + prevReq, promptID := ExtractClaudeBillingTags(billingSystemBody) + if prevReq != "req_01abc" || promptID != "3c6489dc-badc-42b2-bd28-49f8ebabfedd" { + t.Fatalf("ExtractClaudeBillingTags = %q, %q; want req_01abc, 3c6489dc-badc-42b2-bd28-49f8ebabfedd", prevReq, promptID) + } +} + +func TestIsValidClaudePromptID(t *testing.T) { + v4 := uuid.NewString() + if !IsValidClaudePromptID(v4) { + t.Fatalf("IsValidClaudePromptID(%q) = false, want true", v4) + } + + // UUIDv1 should be rejected + v1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8" + if IsValidClaudePromptID(v1) { + t.Fatalf("IsValidClaudePromptID(v1 %q) = true, want false", v1) + } + + // UUIDv4 with non-RFC4122 variant (variant bits 0xxx instead of 10xx, e.g. '0' instead of '8','9','a','b') + nonRFC4122 := "3c6489dc-badc-42b2-0d28-49f8ebabfedd" + if IsValidClaudePromptID(nonRFC4122) { + t.Fatalf("IsValidClaudePromptID(non-RFC4122 variant %q) = true, want false", nonRFC4122) + } + + // All zeros UUID should be rejected (version 0) + allZeros := "00000000-0000-0000-0000-000000000000" + if IsValidClaudePromptID(allZeros) { + t.Fatalf("IsValidClaudePromptID(all zeros %q) = true, want false", allZeros) + } + + // Invalid format strings + for _, invalid := range []string{"", "not-a-uuid", "12345", "3c6489dc-badc-42b2-bd28-49f8ebabfedd-extra"} { + if IsValidClaudePromptID(invalid) { + t.Fatalf("IsValidClaudePromptID(%q) = true, want false", invalid) + } + } +} + +func TestClaudeContinuityConcurrentOverlappingPromptID(t *testing.T) { + resetClaudeDiagnosticsForTest() + defer resetClaudeDiagnosticsForTest() + + // Turn 1 starts (in-flight, not committed) + key, seq1, _, _, prompt1 := BeginClaudeContinuity("cred-1", "sess-1", true, "") + + // Turn 2 starts concurrently before Turn 1 commits + _, seq2, _, _, prompt2 := BeginClaudeContinuity("cred-1", "sess-1", true, "") + if prompt1 == prompt2 { + t.Fatalf("turn 1 and turn 2 got same prompt %q, want distinct", prompt1) + } + + // Turn 1 completes upstream and commits + CommitClaudeContinuity(key, seq1, "msg_01aaa", "req_01bbb", prompt1) + + // Turn 1.1 tool continuation starts (not new turn) + _, _, prevMsg, prevReq, prompt11 := BeginClaudeContinuity("cred-1", "sess-1", false, "") + if prevMsg != "msg_01aaa" || prevReq != "req_01bbb" { + t.Fatalf("turn 1.1 prevMsg=%q prevReq=%q, want msg_01aaa / req_01bbb", prevMsg, prevReq) + } + if prompt11 != prompt1 { + t.Fatalf("turn 1.1 prompt=%q, want committed turn 1 prompt %q, not overwritten by uncommitted turn 2 (%q)", prompt11, prompt1, prompt2) + } + + // Turn 2 completes upstream and commits + CommitClaudeContinuity(key, seq2, "msg_01ccc", "req_01ddd", prompt2) + + // Turn 2.1 tool continuation starts + _, _, prevMsg2, prevReq2, prompt21 := BeginClaudeContinuity("cred-1", "sess-1", false, "") + if prevMsg2 != "msg_01ccc" || prevReq2 != "req_01ddd" { + t.Fatalf("turn 2.1 prevMsg=%q prevReq=%q, want msg_01ccc / req_01ddd", prevMsg2, prevReq2) + } + if prompt21 != prompt2 { + t.Fatalf("turn 2.1 prompt=%q, want committed turn 2 prompt %q", prompt21, prompt2) + } +} + +func TestClaudeContinuityClearsStaleRequestID(t *testing.T) { + resetClaudeDiagnosticsForTest() + defer resetClaudeDiagnosticsForTest() + + // Turn 1: has valid request-id + key, seq1, _, _, p1 := BeginClaudeContinuity("cred-1", "sess-1", true, "") + CommitClaudeContinuity(key, seq1, "msg_01aaa", "req_01bbb", p1) + + // Turn 1.1: verify prevReq is req_01bbb + _, seq2, _, prevReq1, p2 := BeginClaudeContinuity("cred-1", "sess-1", false, "") + if prevReq1 != "req_01bbb" { + t.Fatalf("turn 1.1 prevReq = %q, want req_01bbb", prevReq1) + } + + // Turn 1.1 finishes, but upstream returned no request-id + CommitClaudeContinuity(key, seq2, "msg_01ccc", "", p2) + + // Turn 2: verify prevReq is empty, NOT stale req_01bbb + _, _, prevMsg, prevReq2, _ := BeginClaudeContinuity("cred-1", "sess-1", true, "") + if prevMsg != "msg_01ccc" { + t.Fatalf("turn 2 prevMsg = %q, want msg_01ccc", prevMsg) + } + if prevReq2 != "" { + t.Fatalf("turn 2 prevReq = %q, want empty (must not retain stale request-id from prior turn)", prevReq2) + } +} + +func TestIsClaudeProbeRequest_MultiContentBlocksNotAProbe(t *testing.T) { + // A request with max_tokens: 1 and multiple content blocks where one happens to be "quota" + // but another is a regular prompt must NOT be treated as a probe. + payload := []byte(`{ + "model": "claude-sonnet-5", + "max_tokens": 1, + "messages": [{ + "role": "user", + "content": [ + {"type": "text", "text": "quota"}, + {"type": "text", "text": "Please write an analysis of the codebase."} + ] + }] + }`) + if IsClaudeProbeOrHelperRequest(payload) { + t.Fatal("multi-content user prompt with non-quota text must not be classified as a probe") + } +} + +func TestIsClaudeProbeRequest_SingleContentBlockWithReminderIsProbe(t *testing.T) { + // A probe request with a system-reminder block and a single quota block IS a probe. + payload := []byte(`{ + "model": "claude-sonnet-5", + "max_tokens": 1, + "messages": [{ + "role": "user", + "content": [ + {"type": "text", "text": "some reminder"}, + {"type": "text", "text": "quota"} + ] + }] + }`) + if !IsClaudeProbeOrHelperRequest(payload) { + t.Fatal("probe with system reminder and single quota block must be classified as a probe") + } +} diff --git a/internal/runtime/executor/helps/cloak_obfuscate.go b/internal/runtime/executor/helps/cloak_obfuscate.go index b35780374f..e8304955a0 100644 --- a/internal/runtime/executor/helps/cloak_obfuscate.go +++ b/internal/runtime/executor/helps/cloak_obfuscate.go @@ -147,6 +147,9 @@ func obfuscateSystemBlocks(payload []byte, matcher *SensitiveWordMatcher) []byte system.ForEach(func(key, value gjson.Result) bool { if value.Get("type").String() == "text" { text := value.Get("text").String() + if strings.HasPrefix(text, "x-anthropic-billing-header:") { + return true + } obfuscated := matcher.obfuscateText(text) if obfuscated != text { path := "system." + key.String() + ".text" @@ -161,9 +164,11 @@ func obfuscateSystemBlocks(payload []byte, matcher *SensitiveWordMatcher) []byte } } else if system.Type == gjson.String { text := system.String() - obfuscated := matcher.obfuscateText(text) - if obfuscated != text { - payload, _ = sjson.SetBytes(payload, "system", obfuscated) + if !strings.HasPrefix(text, "x-anthropic-billing-header:") { + obfuscated := matcher.obfuscateText(text) + if obfuscated != text { + payload, _ = sjson.SetBytes(payload, "system", obfuscated) + } } }