diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index 7f648c53..c37c0313 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -591,6 +591,17 @@ func (a *Application) Run(ctx context.Context) error { }) return nil }) + startBackground("audit_retention_cleanup", func(taskCtx context.Context) error { + a.runPeriodicTask(taskCtx, time.Hour, "audit_retention_cleanup", func(runCtx context.Context) error { + retentionDays := a.settings.Get().Config.Audit.RetentionDays + if retentionDays <= 0 { + retentionDays = 7 + } + _, err := a.audits.PurgeOutdated(runCtx, retentionDays) + return err + }) + return nil + }) startBackground("quota_recovery", func(taskCtx context.Context) error { a.quotaRecovery.Run(taskCtx) return nil diff --git a/backend/internal/application/audit/service.go b/backend/internal/application/audit/service.go index 4051fc13..81152301 100644 --- a/backend/internal/application/audit/service.go +++ b/backend/internal/application/audit/service.go @@ -405,6 +405,16 @@ func (s *Service) Get(ctx context.Context, id uint64) (auditdomain.Record, error return s.audits.Get(ctx, id) } +// PurgeOutdated 清理超过指定保留天数的历史审计记录。 +func (s *Service) PurgeOutdated(ctx context.Context, retentionDays int) (int64, error) { + if retentionDays <= 0 { + return 0, nil + } + cutoff := time.Now().UTC().AddDate(0, 0, -retentionDays) + return s.audits.PurgeOlderThan(ctx, cutoff) +} + + // CursorResult 表示按递减 ID 游标读取的一页审计记录。 type CursorResult struct { Items []auditdomain.Record diff --git a/backend/internal/application/gateway/image.go b/backend/internal/application/gateway/image.go index 45d00e98..005da545 100644 --- a/backend/internal/application/gateway/image.go +++ b/backend/internal/application/gateway/image.go @@ -303,7 +303,7 @@ func (s *Service) executeImage( effectiveQuotaMode := lease.QuotaMode accountID := credential.ID var once sync.Once - finalize := func(_ Usage, _ string, errorCode string) { + finalizeWithBody := func(_ Usage, _ string, errorCode string, responseBody string) { once.Do(func() { successful := auditRequestSucceeded(response.StatusCode, errorCode) lease.completeSelectorObservation(successful) @@ -312,6 +312,7 @@ func (s *Service) executeImage( record := auditBase record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode record.ErrorCode = errorCode + record.ResponseBody = responseBody record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC() applyAuditEgress(&record, egressTrace, route.Provider) if successful { @@ -356,8 +357,15 @@ func (s *Service) executeImage( } }) } + finalize := func(usage Usage, responseID string, errorCode string) { + finalizeWithBody(usage, responseID, errorCode, "") + } finalizationOwnsReservation = true - return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, Finalize: finalize}, nil + return &Result{ + StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, + Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, + Finalize: finalize, FinalizeWithBody: finalizeWithBody, + }, nil } // quotaFinalizationModes separates the immediate local consumption fence from diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 1652cf74..fd04898c 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -154,6 +154,7 @@ type Result struct { MarkFirstToken func() RecordStreamFailure func(StreamFailureDiagnostic) Finalize func(usage Usage, responseID, errorCode string) + FinalizeWithBody func(usage Usage, responseID, errorCode, responseBody string) } // StreamFailureDiagnostic safely projects a failure termination event returned in-stream after downstream 2xx headers. @@ -1061,7 +1062,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string handoffResponse := func(response *provider.Response, lease *accountLease, credential accountdomain.Credential, upstreamStartedAt time.Time) *Result { accountID := credential.ID var once sync.Once - finalize := func(usage Usage, responseID, errorCode string) { + finalizeWithBody := func(usage Usage, responseID, errorCode, responseBody string) { once.Do(func() { // HTTP 状态码保留线上真实值;流在 2xx 响应头之后失败时由 errorCode // 决定最终结果,避免把协议状态与业务结果混为一谈。 @@ -1114,7 +1115,27 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string } record.DurationMS = time.Since(startedAt).Milliseconds() record.ErrorCode = errorCode + record.ResponseBody = responseBody attempts := failureAttempts.snapshot() + if !successful && len(attempts) == 0 { + statusCode := response.StatusCode + failureAttempts.append(audit.Attempt{ + Source: audit.AttemptSourceUpstreamHTTP, + Stage: "response_stream", + AccountID: auditAccountID(credential.ID), + AccountName: credential.Name, + Method: http.MethodPost, + RequestPath: sanitizeRequestPath(path), + UpstreamURL: sanitizeUpstreamURL(response.UpstreamURL), + StartedAt: upstreamStartedAt.UTC(), + DurationMS: time.Since(upstreamStartedAt).Milliseconds(), + UpstreamStatusCode: &statusCode, + UpstreamStatus: response.Status, + ResponseHeaders: sanitizeDiagnosticHeaders(response.Header), + TransportError: errorCode, + }) + attempts = failureAttempts.snapshot() + } if !successful || len(attempts) > 0 { record.Attempts = attempts } @@ -1166,6 +1187,9 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string timing.finish(s.logger, outcome) }) } + finalize := func(usage Usage, responseID, errorCode string) { + finalizeWithBody(usage, responseID, errorCode, "") + } response.Body = &firstByteReadCloser{ReadCloser: response.Body, mark: timing.markFirstBody} recordStreamFailure := func(diagnostic StreamFailureDiagnostic) { failureAttempts.captureStreamFailure(credential, upstreamStartedAt, response, diagnostic) @@ -1175,7 +1199,12 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string markFirstToken = firstToken.mark } timingHandedOff = true - return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, MarkFirstToken: markFirstToken, RecordStreamFailure: recordStreamFailure, Finalize: finalize} + return &Result{ + StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, + Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, + MarkFirstToken: markFirstToken, RecordStreamFailure: recordStreamFailure, + Finalize: finalize, FinalizeWithBody: finalizeWithBody, + } } // fail_open retains at most one successful no-thinking stream. The account // lease is released immediately; the read pump applies upstream backpressure diff --git a/backend/internal/application/gateway/voice.go b/backend/internal/application/gateway/voice.go index bc5f2927..75aed96e 100644 --- a/backend/internal/application/gateway/voice.go +++ b/backend/internal/application/gateway/voice.go @@ -475,7 +475,7 @@ func (s *Service) executeVoice( } accountID := credential.ID var once sync.Once - finalize := func(_ Usage, _ string, errorCode string) { + finalizeWithBody := func(_ Usage, _ string, errorCode string, responseBody string) { once.Do(func() { successful := auditRequestSucceeded(response.StatusCode, errorCode) lease.completeSelectorObservation(successful) @@ -484,6 +484,7 @@ func (s *Service) executeVoice( record := auditBase record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode record.ErrorCode = errorCode + record.ResponseBody = responseBody record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC() applyAuditEgress(&record, egressTrace, route.Provider) if successful && completedPricing.CostInUSDTicks > 0 { @@ -517,7 +518,14 @@ func (s *Service) executeVoice( } }) } - return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, Finalize: finalize}, nil + finalize := func(usage Usage, responseID string, errorCode string) { + finalizeWithBody(usage, responseID, errorCode, "") + } + return &Result{ + StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, + Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, + Finalize: finalize, FinalizeWithBody: finalizeWithBody, + }, nil } func jsonVoiceResponse(status int, value any) *provider.Response { diff --git a/backend/internal/application/settings/service.go b/backend/internal/application/settings/service.go index 79249c6d..8ac8fa9b 100644 --- a/backend/internal/application/settings/service.go +++ b/backend/internal/application/settings/service.go @@ -119,10 +119,16 @@ type SegmentedSelectorConfig struct { // AuditConfig 是管理接口使用的审计可编辑输入。 type AuditConfig struct { - BufferSize int - BatchSize int - FlushInterval string - CommitDelayMS int + BufferSize int + BatchSize int + FlushInterval string + CommitDelayMS int + RetentionDays int + RetentionDaysProvided bool + RecordRequestBody bool + RecordRequestBodyProvided bool + RecordResponseBody bool + RecordResponseBodyProvided bool } // ClientKeyDefaultsConfig 是管理接口使用的密钥默认限制输入。 @@ -403,9 +409,14 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C if value.Audit.CommitDelay > 0 { commitDelay = value.Audit.CommitDelay } + retentionDays := base.Audit.RetentionDays + if value.Audit.RetentionDays > 0 { + retentionDays = value.Audit.RetentionDays + } base.Audit = config.AuditConfig{ BufferSize: value.Audit.BufferSize, BatchSize: value.Audit.BatchSize, FlushInterval: config.Duration(value.Audit.FlushInterval), - CommitDelay: config.Duration(commitDelay), + CommitDelay: config.Duration(commitDelay), RetentionDays: retentionDays, + RecordRequestBody: value.Audit.RecordRequestBody, RecordResponseBody: value.Audit.RecordResponseBody, LedgerMode: base.Audit.LedgerMode, LedgerFailureThreshold: base.Audit.LedgerFailureThreshold, LedgerUnhealthyGrace: base.Audit.LedgerUnhealthyGrace, LedgerQueueHighWatermarkPct: base.Audit.LedgerQueueHighWatermarkPct, } @@ -482,6 +493,7 @@ func toDomainConfig(value config.Config) settingsdomain.Config { }, Audit: settingsdomain.AuditConfig{ BufferSize: value.Audit.BufferSize, BatchSize: value.Audit.BatchSize, FlushInterval: value.Audit.FlushInterval.Value(), CommitDelay: value.Audit.CommitDelay.Value(), + RetentionDays: value.Audit.RetentionDays, RecordRequestBody: value.Audit.RecordRequestBody, RecordResponseBody: value.Audit.RecordResponseBody, }, ClientKeyDefaults: settingsdomain.ClientKeyDefaultsConfig{ RPMLimit: value.ClientKeyDefaults.RPMLimit, MaxConcurrent: value.ClientKeyDefaults.MaxConcurrent, @@ -574,6 +586,15 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config, if input.Audit.CommitDelayMS > 0 { next.Audit.CommitDelay = config.Duration(time.Duration(input.Audit.CommitDelayMS) * time.Millisecond) } + if input.Audit.RetentionDaysProvided { + next.Audit.RetentionDays = input.Audit.RetentionDays + } + if input.Audit.RecordRequestBodyProvided { + next.Audit.RecordRequestBody = input.Audit.RecordRequestBody + } + if input.Audit.RecordResponseBodyProvided { + next.Audit.RecordResponseBody = input.Audit.RecordResponseBody + } next.ClientKeyDefaults.RPMLimit = input.ClientKeyDefaults.RPMLimit next.ClientKeyDefaults.MaxConcurrent = input.ClientKeyDefaults.MaxConcurrent if input.AccountsProvided { @@ -711,6 +732,9 @@ func toEditable(cfg config.Config) EditableConfig { }, Audit: AuditConfig{ BufferSize: cfg.Audit.BufferSize, BatchSize: cfg.Audit.BatchSize, FlushInterval: cfg.Audit.FlushInterval.String(), CommitDelayMS: int(cfg.Audit.CommitDelay.Value() / time.Millisecond), + RetentionDays: cfg.Audit.RetentionDays, RetentionDaysProvided: true, + RecordRequestBody: cfg.Audit.RecordRequestBody, RecordRequestBodyProvided: true, + RecordResponseBody: cfg.Audit.RecordResponseBody, RecordResponseBodyProvided: true, }, ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: cfg.ClientKeyDefaults.RPMLimit, MaxConcurrent: cfg.ClientKeyDefaults.MaxConcurrent}, Accounts: AccountsConfig{ diff --git a/backend/internal/domain/audit/audit.go b/backend/internal/domain/audit/audit.go index ee850a2a..3c17f39b 100644 --- a/backend/internal/domain/audit/audit.go +++ b/backend/internal/domain/audit/audit.go @@ -115,6 +115,7 @@ type Record struct { RequestPath string RequestHeaders map[string][]string RequestBody string + ResponseBody string AttemptCount int Attempts []Attempt CreatedAt time.Time diff --git a/backend/internal/domain/settings/settings.go b/backend/internal/domain/settings/settings.go index 2a00befc..b699ea07 100644 --- a/backend/internal/domain/settings/settings.go +++ b/backend/internal/domain/settings/settings.go @@ -120,10 +120,13 @@ type SegmentedSelectorConfig struct { } type AuditConfig struct { - BufferSize int - BatchSize int - FlushInterval time.Duration - CommitDelay time.Duration + BufferSize int + BatchSize int + FlushInterval time.Duration + CommitDelay time.Duration + RetentionDays int + RecordRequestBody bool + RecordResponseBody bool } // ClientKeyDefaultsConfig 定义新建客户端密钥的默认限制。 diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index da19074f..e5f2265e 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -248,6 +248,9 @@ type AuditConfig struct { BatchSize int `yaml:"batchSize"` FlushInterval Duration `yaml:"flushInterval"` CommitDelay Duration `yaml:"commitDelay"` + RetentionDays int `yaml:"retentionDays"` + RecordRequestBody bool `yaml:"recordRequestBody"` + RecordResponseBody bool `yaml:"recordResponseBody"` LedgerMode string `yaml:"ledgerMode"` LedgerFailureThreshold int `yaml:"ledgerFailureThreshold"` LedgerUnhealthyGrace Duration `yaml:"ledgerUnhealthyGrace"` @@ -920,6 +923,7 @@ func defaultConfig() Config { }, Audit: AuditConfig{ BufferSize: 16384, BatchSize: 256, FlushInterval: Duration(250 * time.Millisecond), CommitDelay: Duration(5 * time.Millisecond), + RetentionDays: 7, RecordRequestBody: true, RecordResponseBody: true, LedgerMode: "enforce", LedgerFailureThreshold: 1, LedgerUnhealthyGrace: Duration(10 * time.Second), LedgerQueueHighWatermarkPct: 90, }, diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index c7339390..3025d282 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -376,6 +376,7 @@ func toAuditModels(value audit.Record) (requestAuditModel, []requestAuditAttempt RequestPath: truncate(value.RequestPath, 2048), RequestHeadersJSON: truncate(requestHeadersJSON, 65536), RequestBody: truncate(value.RequestBody, 16777216), + ResponseBody: truncate(value.ResponseBody, 16777216), AttemptCount: len(value.Attempts), CreatedAt: value.CreatedAt, } attempts := make([]requestAuditAttemptModel, 0, len(value.Attempts)) @@ -1058,3 +1059,18 @@ func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter } return query } + +func (r *AuditRepository) PurgeOlderThan(ctx context.Context, cutoff time.Time) (int64, error) { + var totalDeleted int64 + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + _ = tx.Exec("DELETE FROM request_audit_attempts WHERE audit_id IN (SELECT id FROM request_audits WHERE created_at < ?)", cutoff).Error + res := tx.Where("created_at < ?", cutoff).Delete(&requestAuditModel{}) + if res.Error != nil { + return res.Error + } + totalDeleted = res.RowsAffected + return nil + }) + return totalDeleted, err +} + diff --git a/backend/internal/infra/persistence/relational/mapping.go b/backend/internal/infra/persistence/relational/mapping.go index e33e8e65..0f0fc376 100644 --- a/backend/internal/infra/persistence/relational/mapping.go +++ b/backend/internal/infra/persistence/relational/mapping.go @@ -270,7 +270,7 @@ func toAuditDomain(value requestAuditModel) audit.Record { EstimatedCostInUSDTicks: value.EstimatedCostInUSDTicks, PricingModel: value.PricingModel, PricingVersion: value.PricingVersion, NumSourcesUsed: value.NumSourcesUsed, NumServerSideToolsUsed: value.NumServerSideToolsUsed, ContextInputTokens: value.ContextInputTokens, ContextOutputTokens: value.ContextOutputTokens, FirstTokenMS: value.FirstTokenMS, DurationMS: value.DurationMS, - ErrorCode: value.ErrorCode, RequestMethod: value.RequestMethod, RequestPath: value.RequestPath, RequestHeaders: requestHeaders, RequestBody: value.RequestBody, AttemptCount: value.AttemptCount, CreatedAt: value.CreatedAt, + ErrorCode: value.ErrorCode, RequestMethod: value.RequestMethod, RequestPath: value.RequestPath, RequestHeaders: requestHeaders, RequestBody: value.RequestBody, ResponseBody: value.ResponseBody, AttemptCount: value.AttemptCount, CreatedAt: value.CreatedAt, } } diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 90f402ba..4c275628 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -333,6 +333,7 @@ type requestAuditModel struct { RequestPath string `gorm:"type:text;not null;default:'';check:chk_request_audits_request_path,length(request_path) <= 2048"` RequestHeadersJSON string `gorm:"type:text;not null;default:'{}';check:chk_request_audits_request_headers,length(request_headers_json) <= 65536"` RequestBody string `gorm:"type:text;not null;default:'';check:chk_request_audits_request_body,length(request_body) <= 16777216"` + ResponseBody string `gorm:"type:text;not null;default:'';check:chk_request_audits_response_body,length(response_body) <= 16777216"` AttemptCount int `gorm:"not null;default:0;check:chk_request_audits_attempt_count,attempt_count >= 0"` CreatedAt time.Time `gorm:"not null"` } diff --git a/backend/internal/repository/audit.go b/backend/internal/repository/audit.go index d8e7bced..65e406af 100644 --- a/backend/internal/repository/audit.go +++ b/backend/internal/repository/audit.go @@ -17,6 +17,7 @@ type AuditRepository interface { Summarize(ctx context.Context, query AuditSummaryQuery) (audit.Summary, error) SumTokensByAccountsSince(ctx context.Context, accountIDs []uint64, since time.Time) (map[uint64]int64, error) SummarizeDegrade(ctx context.Context, query DegradeSummaryQuery) (DegradeSummaryResult, error) + PurgeOlderThan(ctx context.Context, cutoff time.Time) (int64, error) } type DegradeSummaryQuery struct { diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index 18fd2f62..7f6ff739 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -129,6 +129,7 @@ type auditResponse struct { RequestPath string `json:"requestPath,omitempty"` RequestHeaders map[string][]string `json:"requestHeaders,omitempty"` RequestBody string `json:"requestBody,omitempty"` + ResponseBody string `json:"responseBody,omitempty"` AttemptCount int `json:"attemptCount"` CreatedAt time.Time `json:"createdAt"` } @@ -498,6 +499,7 @@ func newAuditResponse(value auditdomain.Record) auditResponse { RequestPath: value.RequestPath, RequestHeaders: value.RequestHeaders, RequestBody: value.RequestBody, + ResponseBody: value.ResponseBody, AttemptCount: value.AttemptCount, CreatedAt: value.CreatedAt, } diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index d4508145..765c62a3 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1243,8 +1243,15 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st usage := gateway.Usage{} responseID := "" errorCode := "" + responseBody := "" defer result.Body.Close() - defer func() { result.Finalize(usage, responseID, errorCode) }() + defer func() { + if result.FinalizeWithBody != nil { + result.FinalizeWithBody(usage, responseID, errorCode, responseBody) + } else { + result.Finalize(usage, responseID, errorCode) + } + }() if isUpstreamCredentialStatus(result.StatusCode) { errorCode = "upstream_unavailable" clientCode := readCredentialErrorCode(result.StatusCode, result.Body) @@ -1272,13 +1279,13 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st var err error if stream { metadata, copyErr := copyStream(c.Writer, result.Body, protocol, result.MarkFirstToken) - usage, responseID, err = metadata.Usage, metadata.ResponseID, copyErr + usage, responseID, responseBody, err = metadata.Usage, metadata.ResponseID, metadata.ResponseBody, copyErr if metadata.StreamFailure != nil && result.RecordStreamFailure != nil { result.RecordStreamFailure(*metadata.StreamFailure) } } else { metadata, copyErr := copyJSON(c.Writer, result.Body, protocol) - usage, responseID, err = metadata.Usage, metadata.ResponseID, copyErr + usage, responseID, responseBody, err = metadata.Usage, metadata.ResponseID, metadata.ResponseBody, copyErr } if err != nil { switch { @@ -1304,6 +1311,7 @@ type responseMetadata struct { ResponseID string Model string SequenceNumber int64 + ResponseBody string StreamFailure *gateway.StreamFailureDiagnostic } @@ -1546,19 +1554,38 @@ func copyJSON(writer gin.ResponseWriter, source io.Reader, protocol streamProtoc if readErr != nil { if errors.Is(readErr, io.EOF) { if metadataComplete { - return normalizeMetadataUsage(extractMetadata(metadataBody), protocol), nil + meta := normalizeMetadataUsage(extractMetadata(metadataBody), protocol) + meta.ResponseBody = string(metadataBody) + return meta, nil } - return responseMetadata{}, nil + return responseMetadata{ResponseBody: string(metadataBody)}, nil } - return responseMetadata{}, readErr + return responseMetadata{ResponseBody: string(metadataBody)}, readErr } } } +type streamAccumulator struct { + chatContent strings.Builder + chatReasoning strings.Builder + chatRefusal strings.Builder + chatFinishReason string + chatSystemFingerprint string + anthropicThinking strings.Builder + anthropicText strings.Builder + anthropicStopReason string + responsesText strings.Builder + responsesReasoning strings.Builder + rawSSE strings.Builder +} + +const maxStreamAccumulatorBytes = 524288 // 512KB + type responseInspector struct { protocol streamProtocol pending []byte metadata responseMetadata + acc streamAccumulator onFirstToken func() firstTokenSeen bool firstTokenReady bool @@ -1592,6 +1619,10 @@ func (i *responseInspector) Inspect(chunk []byte) { continue } if bytes.HasPrefix(line, []byte("data:")) { + if i.acc.rawSSE.Len() < maxStreamAccumulatorBytes { + i.acc.rawSSE.Write(line) + i.acc.rawSSE.WriteByte('\n') + } value := bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:"))) if containsGeneratedDelta(value, i.protocol) { i.metadata.Usage.OutputObserved = true @@ -1599,6 +1630,7 @@ func (i *responseInspector) Inspect(chunk []byte) { i.observeFirstToken(value) i.observeTerminal(value) if !bytes.Equal(value, []byte("[DONE]")) { + i.accumulateStreamChunk(value) metadata := extractMetadata(value) if hasUsageMetadata(metadata.Usage) { if metadata.Usage.ResponseModel == "" { @@ -1624,6 +1656,194 @@ func (i *responseInspector) Inspect(chunk []byte) { } } +func (i *responseInspector) accumulateStreamChunk(data []byte) { + switch i.protocol { + case streamProtocolChat: + var chunk struct { + ID string `json:"id"` + Model string `json:"model"` + SystemFingerprint string `json:"system_fingerprint"` + Choices []struct { + Delta struct { + Content string `json:"content"` + Reasoning string `json:"reasoning"` + ReasoningContent string `json:"reasoning_content"` + ThinkingContent string `json:"thinking_content"` + Refusal string `json:"refusal"` + } `json:"delta"` + FinishReason string `json:"finish_reason"` + } `json:"choices"` + } + if json.Unmarshal(data, &chunk) == nil { + if chunk.SystemFingerprint != "" { + i.acc.chatSystemFingerprint = chunk.SystemFingerprint + } + for _, choice := range chunk.Choices { + if choice.Delta.Content != "" && i.acc.chatContent.Len() < maxStreamAccumulatorBytes { + i.acc.chatContent.WriteString(choice.Delta.Content) + } + reasoning := choice.Delta.ReasoningContent + if reasoning == "" { + reasoning = choice.Delta.Reasoning + } + if reasoning == "" { + reasoning = choice.Delta.ThinkingContent + } + if reasoning != "" && i.acc.chatReasoning.Len() < maxStreamAccumulatorBytes { + i.acc.chatReasoning.WriteString(reasoning) + } + if choice.Delta.Refusal != "" && i.acc.chatRefusal.Len() < maxStreamAccumulatorBytes { + i.acc.chatRefusal.WriteString(choice.Delta.Refusal) + } + if choice.FinishReason != "" { + i.acc.chatFinishReason = choice.FinishReason + } + } + } + case streamProtocolAnthropic: + var evt struct { + Type string `json:"type"` + Delta struct { + Type string `json:"type"` + Text string `json:"text"` + Thinking string `json:"thinking"` + StopReason string `json:"stop_reason"` + } `json:"delta"` + } + if json.Unmarshal(data, &evt) == nil { + if evt.Delta.Type == "text_delta" && evt.Delta.Text != "" && i.acc.anthropicText.Len() < maxStreamAccumulatorBytes { + i.acc.anthropicText.WriteString(evt.Delta.Text) + } + if evt.Delta.Type == "thinking_delta" && evt.Delta.Thinking != "" && i.acc.anthropicThinking.Len() < maxStreamAccumulatorBytes { + i.acc.anthropicThinking.WriteString(evt.Delta.Thinking) + } + if evt.Delta.StopReason != "" { + i.acc.anthropicStopReason = evt.Delta.StopReason + } + } + case streamProtocolResponses: + var evt struct { + Type string `json:"type"` + Delta string `json:"delta"` + } + if json.Unmarshal(data, &evt) == nil { + if (evt.Type == "response.output_text.delta" || evt.Type == "response.text.delta") && evt.Delta != "" && i.acc.responsesText.Len() < maxStreamAccumulatorBytes { + i.acc.responsesText.WriteString(evt.Delta) + } + if (evt.Type == "response.reasoning_text.delta" || evt.Type == "response.reasoning_summary_text.delta") && evt.Delta != "" && i.acc.responsesReasoning.Len() < maxStreamAccumulatorBytes { + i.acc.responsesReasoning.WriteString(evt.Delta) + } + } + } +} + +func (i *responseInspector) buildResponseBody() string { + switch i.protocol { + case streamProtocolChat: + if i.acc.chatContent.Len() > 0 || i.acc.chatReasoning.Len() > 0 || i.acc.chatFinishReason != "" { + msg := map[string]any{ + "role": "assistant", + "content": i.acc.chatContent.String(), + } + if i.acc.chatReasoning.Len() > 0 { + msg["reasoning_content"] = i.acc.chatReasoning.String() + } + if i.acc.chatRefusal.Len() > 0 { + msg["refusal"] = i.acc.chatRefusal.String() + } + finishReason := i.acc.chatFinishReason + if finishReason == "" { + finishReason = "stop" + } + resp := map[string]any{ + "id": i.metadata.ResponseID, + "object": "chat.completion", + "created": time.Now().Unix(), + "model": i.metadata.Model, + "choices": []map[string]any{ + { + "index": 0, + "message": msg, + "finish_reason": finishReason, + }, + }, + } + if i.acc.chatSystemFingerprint != "" { + resp["system_fingerprint"] = i.acc.chatSystemFingerprint + } + if i.metadata.Usage.TotalTokens > 0 || i.metadata.Usage.InputTokens > 0 || i.metadata.Usage.OutputTokens > 0 { + resp["usage"] = map[string]any{ + "prompt_tokens": i.metadata.Usage.InputTokens, + "completion_tokens": i.metadata.Usage.OutputTokens, + "total_tokens": i.metadata.Usage.TotalTokens, + } + } + if raw, err := json.MarshalIndent(resp, "", " "); err == nil { + return string(raw) + } + } + case streamProtocolAnthropic: + if i.acc.anthropicText.Len() > 0 || i.acc.anthropicThinking.Len() > 0 { + blocks := make([]map[string]any, 0, 2) + if i.acc.anthropicThinking.Len() > 0 { + blocks = append(blocks, map[string]any{ + "type": "thinking", + "thinking": i.acc.anthropicThinking.String(), + }) + } + if i.acc.anthropicText.Len() > 0 { + blocks = append(blocks, map[string]any{ + "type": "text", + "text": i.acc.anthropicText.String(), + }) + } + stopReason := i.acc.anthropicStopReason + if stopReason == "" { + stopReason = "end_turn" + } + resp := map[string]any{ + "id": i.metadata.ResponseID, + "type": "message", + "role": "assistant", + "content": blocks, + "model": i.metadata.Model, + "stop_reason": stopReason, + } + if i.metadata.Usage.TotalTokens > 0 || i.metadata.Usage.InputTokens > 0 || i.metadata.Usage.OutputTokens > 0 { + resp["usage"] = map[string]any{ + "input_tokens": i.metadata.Usage.InputTokens, + "output_tokens": i.metadata.Usage.OutputTokens, + } + } + if raw, err := json.MarshalIndent(resp, "", " "); err == nil { + return string(raw) + } + } + case streamProtocolResponses: + if i.acc.responsesText.Len() > 0 || i.acc.responsesReasoning.Len() > 0 { + resp := map[string]any{ + "id": i.metadata.ResponseID, + "object": "response", + "model": i.metadata.Model, + "output_text": i.acc.responsesText.String(), + } + if i.acc.responsesReasoning.Len() > 0 { + resp["reasoning_text"] = i.acc.responsesReasoning.String() + } + if raw, err := json.MarshalIndent(resp, "", " "); err == nil { + return string(raw) + } + } + } + return i.acc.rawSSE.String() +} + +func (i *responseInspector) Metadata() responseMetadata { + meta := normalizeMetadataUsage(i.metadata, i.protocol) + meta.ResponseBody = i.buildResponseBody() + return meta +} + func (i *responseInspector) observeReasoningStart() { if i.firstTokenSeen || i.firstTokenReady || i.onFirstToken == nil { return @@ -1740,10 +1960,6 @@ func containsGeneratedDelta(data []byte, protocol streamProtocol) bool { return false } -func (i *responseInspector) Metadata() responseMetadata { - return normalizeMetadataUsage(i.metadata, i.protocol) -} - func normalizeMetadataUsage(metadata responseMetadata, protocol streamProtocol) responseMetadata { if protocol != streamProtocolAnthropic { return metadata diff --git a/backend/internal/transport/http/settings/handler.go b/backend/internal/transport/http/settings/handler.go index 06849104..0f15adb7 100644 --- a/backend/internal/transport/http/settings/handler.go +++ b/backend/internal/transport/http/settings/handler.go @@ -116,10 +116,13 @@ type segmentedSelectorConfigDTO struct { } type auditConfigDTO struct { - BufferSize int `json:"bufferSize"` - BatchSize int `json:"batchSize"` - FlushInterval string `json:"flushInterval"` - CommitDelayMS int `json:"commitDelayMS"` + BufferSize int `json:"bufferSize"` + BatchSize int `json:"batchSize"` + FlushInterval string `json:"flushInterval"` + CommitDelayMS int `json:"commitDelayMS"` + RetentionDays *int `json:"retentionDays,omitempty"` + RecordRequestBody *bool `json:"recordRequestBody,omitempty"` + RecordResponseBody *bool `json:"recordResponseBody,omitempty"` } type clientKeyDefaultsConfigDTO struct { @@ -233,6 +236,12 @@ func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig { }, Audit: settingsapp.AuditConfig{ BufferSize: value.Audit.BufferSize, BatchSize: value.Audit.BatchSize, FlushInterval: value.Audit.FlushInterval, CommitDelayMS: value.Audit.CommitDelayMS, + RetentionDays: intValue(value.Audit.RetentionDays), + RetentionDaysProvided: value.Audit.RetentionDays != nil, + RecordRequestBody: boolValue(value.Audit.RecordRequestBody), + RecordRequestBodyProvided: value.Audit.RecordRequestBody != nil, + RecordResponseBody: boolValue(value.Audit.RecordResponseBody), + RecordResponseBodyProvided: value.Audit.RecordResponseBody != nil, }, ClientKeyDefaults: settingsapp.ClientKeyDefaultsConfig{ RPMLimit: value.ClientKeyDefaults.RPMLimit, MaxConcurrent: value.ClientKeyDefaults.MaxConcurrent, @@ -317,6 +326,9 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse { }, Audit: auditConfigDTO{ BufferSize: config.Audit.BufferSize, BatchSize: config.Audit.BatchSize, FlushInterval: config.Audit.FlushInterval, CommitDelayMS: config.Audit.CommitDelayMS, + RetentionDays: intPointer(config.Audit.RetentionDays), + RecordRequestBody: boolPointer(config.Audit.RecordRequestBody), + RecordResponseBody: boolPointer(config.Audit.RecordResponseBody), }, ClientKeyDefaults: clientKeyDefaultsConfigDTO{ RPMLimit: config.ClientKeyDefaults.RPMLimit, MaxConcurrent: config.ClientKeyDefaults.MaxConcurrent, @@ -357,6 +369,15 @@ func boolValue(value *bool) bool { return *value } +func intPointer(value int) *int { return &value } + +func intValue(value *int) int { + if value == nil { + return 0 + } + return *value +} + func stringSliceValue(value *[]string) []string { if value == nil { return nil @@ -368,3 +389,4 @@ func stringSlicePointer(value []string) *[]string { cloned := append([]string(nil), value...) return &cloned } + diff --git a/frontend/src/features/audits/request-audit-detail-dialog.tsx b/frontend/src/features/audits/request-audit-detail-dialog.tsx index 0688f948..fcc5c448 100644 --- a/frontend/src/features/audits/request-audit-detail-dialog.tsx +++ b/frontend/src/features/audits/request-audit-detail-dialog.tsx @@ -1,5 +1,6 @@ import { useQuery } from "@tanstack/react-query"; import { + Bot, Check, CheckCircle2, Code2, @@ -111,6 +112,10 @@ export function RequestAuditDetailDialog({ {t("audits.clientRequestBody")} + + + {t("audits.responseBodyTitle")} + {t("audits.upstreamDiagnostics")} @@ -131,6 +136,10 @@ export function RequestAuditDetailDialog({ + + + + @@ -412,6 +421,112 @@ function ClientRequestBodyPanel({ audit }: { audit: AuditDTO }) { ); } +function ResponseBodyPanel({ audit }: { audit: AuditDTO }) { + const { t } = useTranslation(); + const [copiedType, setCopiedType] = useState(null); + + const rawBody = audit.responseBody ?? ""; + + const { formattedJson, isJson, markdownBlock, byteSize } = useMemo(() => { + let formatted = rawBody; + let jsonValid = false; + if (rawBody) { + try { + const parsed = JSON.parse(rawBody); + formatted = JSON.stringify(parsed, null, 2); + jsonValid = true; + } catch { + formatted = rawBody; + jsonValid = false; + } + } + + const md = jsonValid ? "```json\n" + formatted + "\n```" : "```\n" + formatted + "\n```"; + const size = new Blob([rawBody]).size; + + return { + formattedJson: formatted, + isJson: jsonValid, + markdownBlock: md, + byteSize: size, + }; + }, [rawBody]); + + async function handleCopy(type: "raw" | "markdown") { + const textToCopy = type === "raw" ? formattedJson : markdownBlock; + const ok = await copyToClipboard(textToCopy); + if (ok) { + setCopiedType(type); + setTimeout(() => setCopiedType(null), 1800); + toast.success(t("common.copied")); + } else { + toast.error(t("common.copyFailed")); + } + } + + if (!rawBody) { + return } message={t("audits.noResponseBody")} />; + } + + return ( +
+
+
+ {audit.statusCode ? ( + = 400} /> + ) : null} + {byteSize > 0 ? ( + + {formatByteSize(byteSize)} + + ) : null} + {audit.streaming ? ( + + {t("audits.modeStreaming")} + + ) : null} + {audit.outputTokens > 0 ? ( + + {audit.outputTokens} tokens + + ) : null} +
+ +
+ + +
+
+ +
+
+          {formattedJson}
+        
+
+
+ ); +} + function UpstreamAttemptsPanel({ audit, attempts, diff --git a/frontend/src/features/audits/request-audits-api.ts b/frontend/src/features/audits/request-audits-api.ts index 91f2fdee..a569b521 100644 --- a/frontend/src/features/audits/request-audits-api.ts +++ b/frontend/src/features/audits/request-audits-api.ts @@ -70,6 +70,7 @@ export type AuditDTO = { requestPath?: string; requestHeaders?: Record; requestBody?: string; + responseBody?: string; attemptCount: number; createdAt: string; }; @@ -161,7 +162,7 @@ const auditValidator = hasShape({ durationMs: isNumber, errorCode: isOptional(isString), requestMethod: isOptional(isString), requestPath: isOptional(isString), requestHeaders: isOptional(isRecordOf(isArrayOf(isString))), - requestBody: isOptional(isString), attemptCount: isNumber, createdAt: isString, + requestBody: isOptional(isString), responseBody: isOptional(isString), attemptCount: isNumber, createdAt: isString, }); const auditAttemptValidator = hasShape({ id: isString, number: isNumber, source: isOneOf("upstream_http", "gateway_transport", "credential"), stage: isString, diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index a36847fc..c31c20bb 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -24,7 +24,7 @@ export type SettingsConfigDTO = { accountIsolatedConnections: boolean; segmentedSelector: { enabled: boolean; minCandidates: number; windowSize: number }; }; - audit: { bufferSize: number; batchSize: number; flushInterval: string; commitDelayMS: number }; + audit: { bufferSize: number; batchSize: number; flushInterval: string; commitDelayMS: number; retentionDays?: number; recordRequestBody?: boolean; recordResponseBody?: boolean }; clientKeyDefaults: { rpmLimit: number; maxConcurrent: number }; accounts: { markBuildForbiddenReauth: boolean; @@ -132,7 +132,10 @@ const settingsConfigValidator = hasShape({ accountIsolatedConnections: isOptional(isBoolean), segmentedSelector: isOptional(hasShape({ enabled: isBoolean, minCandidates: isNumber, windowSize: isNumber })), }), - audit: hasShape({ bufferSize: isNumber, batchSize: isNumber, flushInterval: isString, commitDelayMS: isOptional(isNumber) }), + audit: hasShape({ + bufferSize: isNumber, batchSize: isNumber, flushInterval: isString, commitDelayMS: isOptional(isNumber), + retentionDays: isOptional(isNumber), recordRequestBody: isOptional(isBoolean), recordResponseBody: isOptional(isBoolean), + }), clientKeyDefaults: hasShape({ rpmLimit: isNumber, maxConcurrent: isNumber }), // Older backends may omit accounts; withSettingsDefaults supplies a safe local default. accounts: isOptional(hasShape({ @@ -172,6 +175,9 @@ function withSettingsDefaults(snapshot: SettingsSnapshotDTO): SettingsSnapshotDT audit: { ...snapshot.config.audit, commitDelayMS: snapshot.config.audit.commitDelayMS ?? 5, + retentionDays: snapshot.config.audit.retentionDays ?? 7, + recordRequestBody: snapshot.config.audit.recordRequestBody ?? true, + recordResponseBody: snapshot.config.audit.recordResponseBody ?? true, }, routing: { ...snapshot.config.routing, diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index 96c03fdf..01b2db98 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -152,7 +152,15 @@ export const settingsSchema = z.object({ }), }).refine((value) => durationSeconds(value.cooldownMax) >= durationSeconds(value.cooldownBase), { path: ["cooldownMax"] }) .refine((value) => value.segmentedSelector.windowSize <= value.segmentedSelector.minCandidates, { path: ["segmentedSelector", "windowSize"] }), - audit: z.object({ bufferSize: positiveInteger.max(262_144), batchSize: positiveInteger.max(4_096), flushInterval: auditFlushDuration, commitDelayMS: positiveInteger.max(50) }) + audit: z.object({ + bufferSize: positiveInteger.max(262_144), + batchSize: positiveInteger.max(4_096), + flushInterval: auditFlushDuration, + commitDelayMS: positiveInteger.max(50), + retentionDays: z.number().int().min(0).max(365), + recordRequestBody: z.boolean(), + recordResponseBody: z.boolean(), + }) .refine((value) => value.batchSize <= value.bufferSize, { path: ["batchSize"] }), clientKeyDefaults: z.object({ rpmLimit: positiveInteger.max(100_000), maxConcurrent: positiveInteger.max(1_024) }), accounts: z.object({ @@ -209,7 +217,15 @@ export function toSettingsForm(config: SettingsConfigDTO): SettingsForm { accountIsolatedConnections: config.routing.accountIsolatedConnections, segmentedSelector: config.routing.segmentedSelector, }, - audit: { bufferSize: config.audit.bufferSize, batchSize: config.audit.batchSize, flushInterval: parseDuration(config.audit.flushInterval), commitDelayMS: config.audit.commitDelayMS }, + audit: { + bufferSize: config.audit.bufferSize, + batchSize: config.audit.batchSize, + flushInterval: parseDuration(config.audit.flushInterval), + commitDelayMS: config.audit.commitDelayMS, + retentionDays: config.audit.retentionDays ?? 7, + recordRequestBody: config.audit.recordRequestBody ?? true, + recordResponseBody: config.audit.recordResponseBody ?? true, + }, clientKeyDefaults: config.clientKeyDefaults, accounts: { markBuildForbiddenReauth: config.accounts.markBuildForbiddenReauth, @@ -252,7 +268,15 @@ export function toSettingsDTO(config: SettingsForm): SettingsConfigDTO { accountIsolatedConnections: config.routing.accountIsolatedConnections, segmentedSelector: config.routing.segmentedSelector, }, - audit: { bufferSize: config.audit.bufferSize, batchSize: config.audit.batchSize, flushInterval: formatDuration(config.audit.flushInterval), commitDelayMS: config.audit.commitDelayMS }, + audit: { + bufferSize: config.audit.bufferSize, + batchSize: config.audit.batchSize, + flushInterval: formatDuration(config.audit.flushInterval), + commitDelayMS: config.audit.commitDelayMS, + retentionDays: config.audit.retentionDays, + recordRequestBody: config.audit.recordRequestBody, + recordResponseBody: config.audit.recordResponseBody, + }, clientKeyDefaults: config.clientKeyDefaults, accounts: { markBuildForbiddenReauth: config.accounts.markBuildForbiddenReauth, diff --git a/frontend/src/features/settings/settings-page.tsx b/frontend/src/features/settings/settings-page.tsx index c88919d9..b9ac679f 100644 --- a/frontend/src/features/settings/settings-page.tsx +++ b/frontend/src/features/settings/settings-page.tsx @@ -85,6 +85,7 @@ export function SettingsPage() { {t("console.name")} {t("settings.groups.delivery")} {t("settings.groups.policies")} + {t("settings.audit.tabTitle")} {t("settings.accounts.title")} {t("updates.title")} @@ -341,15 +342,6 @@ export function SettingsPage() { - -
- - - } /> - -
-
-
@@ -358,6 +350,129 @@ export function SettingsPage() { + + +
+ + + + + + ( +
+ +
+ )} + /> +
+ + + ( +
+ +
+ )} + /> +
+
+
+ + +
+ + + + + + + + ( + + )} + /> + + + + +
+
+
+
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 96ab1312..ae7bad1d 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -944,8 +944,12 @@ const resources = { serverTools: "工具调用 {{count}} 次", detailTitle: "请求诊断与报文详情", requestOverview: "请求概览", - clientRequestBody: "完整报文", + clientRequestBody: "请求报文", clientRequest: "完整报文", + responseBodyTitle: "响应报文", + noResponseBody: "未捕获到服务端响应报文或未启用响应报文记录。", + copyResponseRaw: "复制响应报文", + modeStreaming: "SSE 流式", requestHeaders: "HTTP 请求头", requestBody: "请求体 (Body)", requestLine: "请求行", @@ -1007,7 +1011,7 @@ const resources = { restartRequired: "重启生效", invalidValue: "请输入有效值", durationUnit: "时长单位", - groups: { providers: "Provider 配置", delivery: "媒体与网络", policies: "运行策略", about: "关于" }, + groups: { providers: "Provider 配置", delivery: "媒体与网络", policies: "运行策略", audit: "日志设置", accounts: "账号维护", about: "关于" }, server: { title: "服务容量", maxConcurrentRequests: "API 请求并发上限", maxConcurrentRequestsHelp: "单实例同时处理的 /v1 请求数;调低不会中断进行中的请求。" }, provider: { title: "Grok Build", baseURL: "上游地址", baseURLHelp: "Grok Build 请求使用的主要上游端点。", fallbackBaseURL: "XAI 备用地址", fallbackBaseURLHelp: "自动路由至 XAI 或 Build 请求回退时使用的端点。", clientVersion: "客户端版本", clientVersionHelp: "随 Build 请求发送的版本;建议使用已完成兼容验证的版本。", clientIdentifier: "客户端标识", clientIdentifierHelp: "随请求发送的客户端身份标识,需与上游协议保持一致。", tokenAuth: "Token Auth", tokenAuthHelp: "随 Grok Build 请求发送的客户端协议标识,通常保持为 xai-grok-cli。", userAgent: "User-Agent", userAgentHelp: "用于 Grok Build 推理请求及其出口节点;直连 XAI 媒体请求按客户端版本使用官方 xai-grok-build User-Agent。", recommendedVersion: "推荐 {{version}}", syncRecommendedVersion: "同步最新版本", recommendedVersionApplied: "已是推荐版本", syncRecommendedVersionDescription: "使用已完成兼容验证的版本和 User-Agent 填充当前表单,保存后生效。" }, web: { title: "Grok Web", baseURL: "上游地址", baseURLHelp: "Grok Web API 与账号操作使用的基础端点。", statsigMode: "x-statsig 获取方式", statsigModeHelp: "选择固定配置或通过签名服务动态获取请求标识。", statsigManual: "手动填写", statsigURL: "URL 获取", statsigValue: "x-statsig-id", statsigValueHelp: "直接配置 Grok Web 请求使用的 x-statsig-id。", statsigConfigured: "已配置", statsigKeepConfigured: "留空保持当前配置", statsigValuePlaceholder: "粘贴 x-statsig-id", statsigSignerURL: "签名服务 URL", statsigSignerURLHelp: "按请求获取 x-statsig-id 的内部签名服务地址。", quotaTimeout: "额度请求超时", quotaTimeoutHelp: "查询账号额度与状态时允许等待上游响应的最长时间。", chatTimeout: "聊天超时", chatTimeoutHelp: "Grok Web 聊天请求完成前允许等待的最长时间。", streamIdleTimeout: "流式空闲超时", streamIdleTimeoutHelp: "上游文本聊天流连续无数据时允许等待的最长时间;不影响图片、视频和其他媒体请求。", imageTimeout: "图片超时", imageTimeoutHelp: "图片生成与编辑任务完成前允许等待的最长时间。", videoTimeout: "视频超时", videoTimeoutHelp: "视频生成任务完成前允许等待的最长时间。", mediaConcurrency: "媒体任务并发", mediaConcurrencyHelp: "单实例可同时执行的图片与视频任务数;修改后需重启。", recoveryBackoffBase: "额度恢复退避", recoveryBackoffBaseHelp: "额度恢复检查连续失败后的初始重试间隔。", recoveryBackoffMax: "额度恢复最大退避", recoveryBackoffMaxHelp: "额度恢复检查采用指数退避时允许达到的最大间隔。", allowNSFW: "允许 NSFW 图片", allowNSFWHelp: "允许 Grok Web 图片请求启用成人内容偏好。", clearanceMode: "Clearance 管理", clearanceModeHelp: "选择手动维护 Cloudflare 凭据,或由 FlareSolverr 按实际出口自动获取并定期刷新。", clearanceManual: "手动维护", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr 地址", flareSolverrURLHelp: "用于求解 Cloudflare Clearance 的内部 FlareSolverr 服务地址。", clearanceTimeout: "求解超时", clearanceTimeoutHelp: "等待单次 FlareSolverr 求解完成的最长时间。", clearanceRefresh: "刷新周期", clearanceRefreshHelp: "固定出口 Clearance 的定期刷新间隔;账号粘性代理会在实际请求中按账号独立维护。" }, @@ -1016,7 +1020,26 @@ const resources = { media: { title: "媒体存储", maxImageSize: "单张图片上限", maxImageSizeHelp: "单个图片文件允许写入本地媒体存储的最大大小。", maxTotalSize: "媒体存储上限", maxTotalSizeHelp: "本地图片与视频文件允许占用的总存储空间。", cleanupThresholdPercent: "自动清理阈值", cleanupThresholdPercentHelp: "存储使用率达到该比例后,系统按时间清理较早的媒体文件。", cleanupInterval: "容量检查间隔", cleanupIntervalHelp: "后台检查媒体存储使用量并触发清理的时间间隔。", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时回退到服务启动值,默认为 http://127.0.0.1:8000。" }, egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 地址。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" }, routing: { title: "路由策略", stickyTTL: "会话粘性时长", stickyTTLHelp: "同一会话优先复用已选账号的有效时长;到期后重新参与调度。", cooldownBase: "基础冷却时间", cooldownBaseHelp: "账号发生可恢复故障后首次进入冷却的时长。", cooldownMax: "最大冷却时间", cooldownMaxHelp: "连续故障触发指数退避时允许达到的最长冷却时间。", capacityWait: "账号满载等待", capacityWaitHelp: "全部候选账号并发已满时,切换或失败前等待容量释放的时间。", maxAttempts: "最大尝试次数", maxAttemptsHelp: "单次请求在可用账号之间切换并重试的最大次数,范围为 1–200。", videoMaxAttempts: "视频最大尝试次数", videoMaxAttemptsHelp: "仅作用于视频任务创建阶段的切号重试,可单独设置数值,或开启无限制。创建成功后的轮询不会换号。", preferFreeBuild: "Grok Build Free 账号优先", preferFreeBuildHelp: "启用后优先选择已确认可用的 Free 账号,其他路由条件保持不变。", accountIsolatedConnections: "按账号隔离上游连接", accountIsolatedConnectionsHelp: "开启后,不同账号使用各自的上游 TCP/HTTP 连接池,便于外部 L4 或按连接哈希的负载均衡器分散流量;同一账号仍可复用连接。适用于 Build / Web / Console 出站及 Web 转 Build。会增加连接数、TLS 握手、内存和文件描述符占用,建议仅在确有外部连接级负载均衡需求时开启。" }, - audit: { title: "请求审计", bufferSize: "队列容量", bufferSizeHelp: "审计记录进入持久化前可在内存队列中等待的最大数量。", batchSize: "批量写入数", batchSizeHelp: "每次数据库事务最多写入的审计记录数量。", flushInterval: "刷新间隔", flushIntervalHelp: "队列未达到批量写入数时,强制提交待处理审计记录的间隔。", commitDelay: "提交聚合等待(毫秒)", commitDelayHelp: "需要确认提交的请求进入原子批次前允许等待的最长时间。" }, + audit: { + title: "请求审计与日志设置", + tabTitle: "日志设置", + retentionTitle: "日志保留与报文策略", + retentionDays: "日志保留天数", + retentionDaysHelp: "自动清理超过指定天数的请求审计与上游失败诊断记录。设置为 0 表示永久保留,默认为 7 天。", + recordRequestBody: "记录客户端请求报文", + recordRequestBodyHelp: "记录客户端发送的完整 HTTP 请求头与 Body(包含文本与多模态数据,便于报文复现与排查)。", + recordResponseBody: "记录服务端响应报文", + recordResponseBodyHelp: "流式输出结束后自动聚合完整的响应报文(SSE / JSON),便于在审计中查看与复制。", + performanceTitle: "写入缓冲与性能", + bufferSize: "队列容量", + bufferSizeHelp: "审计记录进入持久化前可在内存队列中等待的最大数量。", + batchSize: "批量写入数", + batchSizeHelp: "每次数据库事务最多写入的审计记录数量。", + flushInterval: "刷新间隔", + flushIntervalHelp: "队列未达到批量写入数时,强制提交待处理审计记录的间隔。", + commitDelay: "提交聚合等待(毫秒)", + commitDelayHelp: "需要确认提交的请求进入原子批次前允许等待的最长时间。", + }, clientKeys: { title: "密钥默认限制", rpmLimit: "默认 RPM", rpmLimitHelp: "新建客户端密钥默认允许的每分钟请求数。", maxConcurrent: "默认并发数", maxConcurrentHelp: "新建客户端密钥默认允许同时执行的请求数。" }, accounts: { title: "账号维护", @@ -1721,8 +1744,12 @@ const resources = { serverTools: "Tool calls {{count}} times", detailTitle: "Request Diagnostics & Payload", requestOverview: "Overview", - clientRequestBody: "Full Request", + clientRequestBody: "Request Body", clientRequest: "Full Request", + responseBodyTitle: "Response Body", + noResponseBody: "No response body captured or response payload recording is disabled.", + copyResponseRaw: "Copy Response Body", + modeStreaming: "SSE Stream", requestHeaders: "HTTP Request Headers", requestBody: "Request Body", requestLine: "Request Line", @@ -1783,7 +1810,7 @@ const resources = { errorFrameCount_one: "{{count}} error frame", errorFrameCount_other: "{{count}} error frames", }, - settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Client protocol identifier sent with Grok Build requests; normally keep xai-grok-cli.", userAgent: "User-Agent", userAgentHelp: "Used by Grok Build inference requests and their egress nodes. Direct XAI media requests derive the official xai-grok-build User-Agent from the client version.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for raw text-chat streams; image, video, and other media requests are unaffected.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for a Grok Web video generation request to complete.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference.", clearanceMode: "Clearance management", clearanceModeHelp: "Maintain Cloudflare credentials manually or let FlareSolverr acquire and refresh them on the actual egress.", clearanceManual: "Manual", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr URL", flareSolverrURLHelp: "Internal FlareSolverr endpoint used to solve Cloudflare Clearance.", clearanceTimeout: "Solve timeout", clearanceTimeoutHelp: "Maximum time allowed for one FlareSolverr solve.", clearanceRefresh: "Refresh interval", clearanceRefreshHelp: "Periodic refresh interval for fixed egress; account-bound proxies are maintained independently during requests." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for text SSE only; media and non-streaming requests are unaffected." }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", importConcurrencyHelp: "Accounts initialized and synchronized concurrently after a batch import.", conversionConcurrency: "Account conversion concurrency", conversionConcurrencyHelp: "Cross-provider account conversions that may run concurrently.", syncConcurrency: "Data sync concurrency", syncConcurrencyHelp: "Quota, status, and capability synchronizations that may run concurrently.", refreshConcurrency: "Credential refresh concurrency", refreshConcurrencyHelp: "Account credential refreshes that may run concurrently.", randomDelay: "Maximum random delay (ms)", randomDelayHelp: "Maximum randomized delay before batch work starts to smooth upstream request bursts." }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxImageSizeHelp: "Largest individual image that may be written to local media storage.", maxTotalSize: "Media storage limit", maxTotalSizeHelp: "Total local storage available to image and video files.", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupThresholdPercentHelp: "Storage utilization that triggers removal of older media files.", cleanupInterval: "Capacity check interval", cleanupIntervalHelp: "Interval between background storage checks and cleanup evaluation.", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use the service startup value, which defaults to http://127.0.0.1:8000." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H.\nResin users can put {account} in the username to bind one lease per account.", proxyPool: "Proxy pool mode", proxyPoolHelp: "A request-level connection failure does not cool the entire shared node. Proxies containing {account} use this policy automatically.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed", refreshClearance: "Refresh Clearance", clearanceRefreshed: "Clearance refreshed", clearanceManaged: "Cloudflare cookies and User-Agent are managed by FlareSolverr; account-bound proxies are isolated per account." }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", stickyTTLHelp: "How long a session prefers its selected account before returning to normal scheduling.", cooldownBase: "Base cooldown", cooldownBaseHelp: "Initial cooldown applied after a recoverable account failure.", cooldownMax: "Maximum cooldown", cooldownMaxHelp: "Longest cooldown allowed when repeated failures trigger exponential backoff.", capacityWait: "Saturated account wait", capacityWaitHelp: "How long to wait for capacity before switching accounts or failing when all candidates are saturated.", maxAttempts: "Maximum attempts", maxAttemptsHelp: "Maximum account switches and retries allowed for one request, from 1 to 200.", videoMaxAttempts: "Video maximum attempts", videoMaxAttemptsHelp: "Create-phase account failover for video jobs only. Set a number or enable unlimited. Polling after create stays on the same account.", preferFreeBuild: "Prefer Grok Build Free accounts", preferFreeBuildHelp: "Prefer confirmed usable Free accounts without changing other routing eligibility rules.", accountIsolatedConnections: "Isolate upstream connections by account", accountIsolatedConnectionsHelp: "When enabled, each account uses its own upstream TCP/HTTP connection pool so external L4 or connection-hash load balancers can spread traffic; the same account still reuses connections. Applies to Build, Web, Console, and Web-to-Build traffic. This increases connections, TLS handshakes, memory, and file-descriptor usage, so enable it only when connection-level balancing is required." }, audit: { title: "Request audit", bufferSize: "Queue capacity", bufferSizeHelp: "Maximum audit records held in memory before persistence.", batchSize: "Batch size", batchSizeHelp: "Maximum audit records written in one database transaction.", flushInterval: "Flush interval", flushIntervalHelp: "Maximum time pending audit records wait before they are committed.", commitDelay: "Commit aggregation delay (ms)", commitDelayHelp: "Maximum time acknowledged writes wait to join an atomic batch before commit." }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", rpmLimitHelp: "Requests per minute assigned to newly created client keys.", maxConcurrent: "Default concurrency", maxConcurrentHelp: "Concurrent requests assigned to newly created client keys." }, accounts: { title: "Account maintenance", invalidationTitle: "Automatic interception", botRiskSchedulingTitle: "Bot-risk scheduling", excludeBuildBotFlaggedFromScheduling: "Exclude bot-risk Build accounts from scheduling", excludeBuildBotFlaggedFromSchedulingHelp: "When enabled, Grok Build accounts whose JWT bot_flag_source/bfs is 1 or 2 are removed from Build scheduling only. Linked Web/Console accounts keep their normal scheduling. Accounts remain in the pool for viewing and manual actions.", cleanupTitle: "Account cleanup", autoCleanReauthEnabled: "Automatic invalid-account cleanup", autoCleanReauthEnabledHelp: "Permanently deletes invalid accounts after the configured retention period. Accounts with active requests or video jobs are skipped.", autoCleanReauthInterval: "Cleanup interval", autoCleanReauthIntervalHelp: "How often to check for eligible accounts, from 1 minute to 1 hour.", autoCleanReauthMinAge: "Minimum retention", autoCleanReauthMinAgeHelp: "How long to retain an account after it is marked for reauthorization.", autoCleanIncludeDisabled: "Include disabled accounts", autoCleanIncludeDisabledHelp: "Includes disabled accounts that require reauthorization in automatic cleanup.", autoCleanEnableTitle: "Enable automatic cleanup?", autoCleanEnableDescription: "Eligible accounts will be permanently deleted and cannot be recovered. The first run starts after one full cleanup interval.", autoCleanIncludeDisabledTitle: "Include disabled accounts?", autoCleanIncludeDisabledDescription: "Disabled accounts that require reauthorization will also be permanently deleted. This action cannot be undone.", autoCleanConfirm: "Enable" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } }, + settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", audit: "Audit & Logs", accounts: "Account maintenance", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Client protocol identifier sent with Grok Build requests; normally keep xai-grok-cli.", userAgent: "User-Agent", userAgentHelp: "Used by Grok Build inference requests and their egress nodes. Direct XAI media requests derive the official xai-grok-build User-Agent from the client version.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for raw text-chat streams; image, video, and other media requests are unaffected.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for a Grok Web video generation request to complete.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference.", clearanceMode: "Clearance management", clearanceModeHelp: "Maintain Cloudflare credentials manually or let FlareSolverr acquire and refresh them on the actual egress.", clearanceManual: "Manual", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr URL", flareSolverrURLHelp: "Internal FlareSolverr endpoint used to solve Cloudflare Clearance.", clearanceTimeout: "Solve timeout", clearanceTimeoutHelp: "Maximum time allowed for one FlareSolverr solve.", clearanceRefresh: "Refresh interval", clearanceRefreshHelp: "Periodic refresh interval for fixed egress; account-bound proxies are maintained independently during requests." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for text SSE only; media and non-streaming requests are unaffected." }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", importConcurrencyHelp: "Accounts initialized and synchronized concurrently after a batch import.", conversionConcurrency: "Account conversion concurrency", conversionConcurrencyHelp: "Cross-provider account conversions that may run concurrently.", syncConcurrency: "Data sync concurrency", syncConcurrencyHelp: "Quota, status, and capability synchronizations that may run concurrently.", refreshConcurrency: "Credential refresh concurrency", refreshConcurrencyHelp: "Account credential refreshes that may run concurrently.", randomDelay: "Maximum random delay (ms)", randomDelayHelp: "Maximum randomized delay before batch work starts to smooth upstream request bursts." }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxImageSizeHelp: "Largest individual image that may be written to local media storage.", maxTotalSize: "Media storage limit", maxTotalSizeHelp: "Total local storage available to image and video files.", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupThresholdPercentHelp: "Storage utilization that triggers removal of older media files.", cleanupInterval: "Capacity check interval", cleanupIntervalHelp: "Interval between background storage checks and cleanup evaluation.", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use the service startup value, which defaults to http://127.0.0.1:8000." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H.\nResin users can put {account} in the username to bind one lease per account.", proxyPool: "Proxy pool mode", proxyPoolHelp: "A request-level connection failure does not cool the entire shared node. Proxies containing {account} use this policy automatically.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed", refreshClearance: "Refresh Clearance", clearanceRefreshed: "Clearance refreshed", clearanceManaged: "Cloudflare cookies and User-Agent are managed by FlareSolverr; account-bound proxies are isolated per account." }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", stickyTTLHelp: "How long a session prefers its selected account before returning to normal scheduling.", cooldownBase: "Base cooldown", cooldownBaseHelp: "Initial cooldown applied after a recoverable account failure.", cooldownMax: "Maximum cooldown", cooldownMaxHelp: "Longest cooldown allowed when repeated failures trigger exponential backoff.", capacityWait: "Saturated account wait", capacityWaitHelp: "How long to wait for capacity before switching accounts or failing when all candidates are saturated.", maxAttempts: "Maximum attempts", maxAttemptsHelp: "Maximum account switches and retries allowed for one request, from 1 to 200.", videoMaxAttempts: "Video maximum attempts", videoMaxAttemptsHelp: "Create-phase account failover for video jobs only. Set a number or enable unlimited. Polling after create stays on the same account.", preferFreeBuild: "Prefer Grok Build Free accounts", preferFreeBuildHelp: "Prefer confirmed usable Free accounts without changing other routing eligibility rules.", accountIsolatedConnections: "Isolate upstream connections by account", accountIsolatedConnectionsHelp: "When enabled, each account uses its own upstream TCP/HTTP connection pool so external L4 or connection-hash load balancers can spread traffic; the same account still reuses connections. Applies to Build, Web, Console, and Web-to-Build traffic. This increases connections, TLS handshakes, memory, and file-descriptor usage, so enable it only when connection-level balancing is required." }, audit: { title: "Request Audit & Logs", tabTitle: "Audit & Logs", retentionTitle: "Log Retention & Payload Policy", retentionDays: "Log retention days", retentionDaysHelp: "Automatically purges request audits and failure attempts older than the specified days. Set to 0 for indefinite retention, default is 7 days.", recordRequestBody: "Record client request payloads", recordRequestBodyHelp: "Captures complete HTTP headers and request bodies from client calls for diagnostic and replication purposes.", recordResponseBody: "Record server response payloads", recordResponseBodyHelp: "Reconstructs complete SSE stream responses and JSON bodies to view in request audit details.", performanceTitle: "Buffer & Performance", bufferSize: "Queue capacity", bufferSizeHelp: "Maximum audit records held in memory before persistence.", batchSize: "Batch size", batchSizeHelp: "Maximum audit records written in one database transaction.", flushInterval: "Flush interval", flushIntervalHelp: "Maximum time pending audit records wait before they are committed.", commitDelay: "Commit aggregation delay (ms)", commitDelayHelp: "Maximum time acknowledged writes wait to join an atomic batch before commit." }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", rpmLimitHelp: "Requests per minute assigned to newly created client keys.", maxConcurrent: "Default concurrency", maxConcurrentHelp: "Concurrent requests assigned to newly created client keys." }, accounts: { title: "Account maintenance", invalidationTitle: "Automatic interception", botRiskSchedulingTitle: "Bot-risk scheduling", excludeBuildBotFlaggedFromScheduling: "Exclude bot-risk Build accounts from scheduling", excludeBuildBotFlaggedFromSchedulingHelp: "When enabled, Grok Build accounts whose JWT bot_flag_source/bfs is 1 or 2 are removed from Build scheduling only. Linked Web/Console accounts keep their normal scheduling. Accounts remain in the pool for viewing and manual actions.", cleanupTitle: "Account cleanup", autoCleanReauthEnabled: "Automatic invalid-account cleanup", autoCleanReauthEnabledHelp: "Permanently deletes invalid accounts after the configured retention period. Accounts with active requests or video jobs are skipped.", autoCleanReauthInterval: "Cleanup interval", autoCleanReauthIntervalHelp: "How often to check for eligible accounts, from 1 minute to 1 hour.", autoCleanReauthMinAge: "Minimum retention", autoCleanReauthMinAgeHelp: "How long to retain an account after it is marked for reauthorization.", autoCleanIncludeDisabled: "Include disabled accounts", autoCleanIncludeDisabledHelp: "Includes disabled accounts that require reauthorization in automatic cleanup.", autoCleanEnableTitle: "Enable automatic cleanup?", autoCleanEnableDescription: "Eligible accounts will be permanently deleted and cannot be recovered. The first run starts after one full cleanup interval.", autoCleanIncludeDisabledTitle: "Include disabled accounts?", autoCleanIncludeDisabledDescription: "Disabled accounts that require reauthorization will also be permanently deleted. This action cannot be undone.", autoCleanConfirm: "Enable" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } }, egressProxyProfiles: { title: "Proxy address library", libraryTitle: "Proxy address library", libraryDescription: "Manage reusable proxy addresses in one place. Changes sync to every node using the address.", description: "Save proxy addresses that need to be reused across nodes.", add: "Add proxy address", addTitle: "Add proxy address", editTitle: "Edit proxy address", dialogDescription: "Changing the proxy address updates every bound node. Capacity and operational state remain isolated per node.", name: "Address name", endpoint: "Proxy address", nodes: "Used by", search: "Search address names", empty: "No proxy addresses", emptyLibrary: "The library is empty. Add an address to reuse it across nodes.", noMatches: "No matching proxy addresses", loadingSelection: "Loading selected address…", selectionUnavailable: "Proxy address #{{id}} is unavailable", saved: "Proxy address saved", deleted: "Proxy address deleted", deleteTitle: "Delete proxy address?", deleteDescription: "This deletes {{name}}. Addresses currently used by nodes cannot be deleted.", deleteBlocked: "Used by {{count}} nodes", assignment: "Proxy address source", assignmentHelp: "Select an address from the library to reuse it across Provider nodes. Health, capacity, User-Agent, and Clearance remain isolated per node.", independent: "Configure this node separately", managedByProfile: "Managed by the proxy address library", nodeCount: "{{count}} nodes", backToLibrary: "Back to address library", createFromPicker: "Add and use a proxy address", refreshNodes: "Refresh proxy nodes", reveal: "Reveal full proxy URL", hide: "Hide full proxy URL", revealUnavailable: "Only a saved proxy address can reveal its URL" }, settingsBuildTransport: { responseHeaderTimeout: "Response header timeout", responseHeaderTimeoutHelp: "Maximum time to wait for the first Grok Build response headers after the request body is sent.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum wait for useful generated content or tool progress. Keepalives and private control events do not extend the deadline." },