mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
feat(audit): add response body recording, stream reassembly, and audit log retention settings
This commit is contained in:
1 parent
9d841a2757
commit
86010fc55c
22 files changed
+694
-50
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -115,6 +115,7 @@ type Record struct {
|
||||
RequestPath string
|
||||
RequestHeaders map[string][]string
|
||||
RequestBody string
|
||||
ResponseBody string
|
||||
AttemptCount int
|
||||
Attempts []Attempt
|
||||
CreatedAt time.Time
|
||||
|
||||
@@ -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 定义新建客户端密钥的默认限制。
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Bot,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
Code2,
|
||||
@@ -111,6 +112,10 @@ export function RequestAuditDetailDialog({
|
||||
<Code2 className="size-3.5" />
|
||||
{t("audits.clientRequestBody")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="responseBody" className="gap-1.5 px-3 text-xs">
|
||||
<Bot className="size-3.5" />
|
||||
{t("audits.responseBodyTitle")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="attempts" className="gap-1.5 px-3 text-xs">
|
||||
<Server className="size-3.5" />
|
||||
{t("audits.upstreamDiagnostics")}
|
||||
@@ -131,6 +136,10 @@ export function RequestAuditDetailDialog({
|
||||
<ClientRequestBodyPanel audit={activeAudit} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="responseBody" className="min-h-0 flex-1 overflow-hidden p-4 focus-visible:outline-none">
|
||||
<ResponseBodyPanel audit={activeAudit} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="attempts" className="min-h-0 flex-1 overflow-hidden focus-visible:outline-none">
|
||||
<UpstreamAttemptsPanel audit={activeAudit} attempts={attempts} />
|
||||
</TabsContent>
|
||||
@@ -412,6 +421,112 @@ function ClientRequestBodyPanel({ audit }: { audit: AuditDTO }) {
|
||||
);
|
||||
}
|
||||
|
||||
function ResponseBodyPanel({ audit }: { audit: AuditDTO }) {
|
||||
const { t } = useTranslation();
|
||||
const [copiedType, setCopiedType] = useState<string | null>(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 <EmptyPanel icon={<FileText />} message={t("audits.noResponseBody")} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col overflow-hidden rounded-md border border-border/50 bg-muted/20">
|
||||
<div className="flex h-11 shrink-0 flex-wrap items-center justify-between gap-2 border-b border-border/40 bg-muted/40 px-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{audit.statusCode ? (
|
||||
<StatusBadge statusCode={audit.statusCode} failed={Boolean(audit.errorCode) || audit.statusCode >= 400} />
|
||||
) : null}
|
||||
{byteSize > 0 ? (
|
||||
<Badge variant="secondary" className="font-mono text-[10px]">
|
||||
{formatByteSize(byteSize)}
|
||||
</Badge>
|
||||
) : null}
|
||||
{audit.streaming ? (
|
||||
<Badge variant="outline" className="text-[10px] text-muted-foreground">
|
||||
{t("audits.modeStreaming")}
|
||||
</Badge>
|
||||
) : null}
|
||||
{audit.outputTokens > 0 ? (
|
||||
<Badge variant="outline" className="font-mono text-[10px] text-muted-foreground">
|
||||
{audit.outputTokens} tokens
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 gap-1 px-2 text-[11px] text-muted-foreground hover:text-foreground cursor-pointer"
|
||||
onClick={() => void handleCopy("raw")}
|
||||
title={t("audits.copyResponseRaw")}
|
||||
>
|
||||
{copiedType === "raw" ? <Check className="size-3.5 text-emerald-500" /> : <Copy className="size-3.5" />}
|
||||
{copiedType === "raw" ? t("common.copied") : isJson ? t("audits.copyJson") : t("common.copy")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 gap-1 px-2 text-[11px] text-muted-foreground hover:text-foreground cursor-pointer"
|
||||
onClick={() => void handleCopy("markdown")}
|
||||
title={t("audits.copyMarkdownCode")}
|
||||
>
|
||||
{copiedType === "markdown" ? <Check className="size-3.5 text-emerald-500" /> : <FileCode className="size-3.5" />}
|
||||
{copiedType === "markdown" ? t("common.copied") : t("audits.copyMarkdown")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-auto p-3">
|
||||
<pre className="font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-all select-text">
|
||||
{formattedJson}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UpstreamAttemptsPanel({
|
||||
audit,
|
||||
attempts,
|
||||
|
||||
@@ -70,6 +70,7 @@ export type AuditDTO = {
|
||||
requestPath?: string;
|
||||
requestHeaders?: Record<string, string[]>;
|
||||
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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -85,6 +85,7 @@ export function SettingsPage() {
|
||||
<TabsTrigger className="h-9 w-auto shrink-0 justify-start rounded-md px-3 text-xs data-[state=active]:font-medium lg:w-full" value="console">{t("console.name")}</TabsTrigger>
|
||||
<TabsTrigger className="h-9 w-auto shrink-0 justify-start rounded-md px-3 text-xs data-[state=active]:font-medium lg:w-full" value="delivery">{t("settings.groups.delivery")}</TabsTrigger>
|
||||
<TabsTrigger className="h-9 w-auto shrink-0 justify-start rounded-md px-3 text-xs data-[state=active]:font-medium lg:w-full" value="policies">{t("settings.groups.policies")}</TabsTrigger>
|
||||
<TabsTrigger className="h-9 w-auto shrink-0 justify-start rounded-md px-3 text-xs data-[state=active]:font-medium lg:w-full" value="audit">{t("settings.audit.tabTitle")}</TabsTrigger>
|
||||
<TabsTrigger className="h-9 w-auto shrink-0 justify-start rounded-md px-3 text-xs data-[state=active]:font-medium lg:w-full" value="accounts">{t("settings.accounts.title")}</TabsTrigger>
|
||||
<TabsTrigger className="h-9 w-auto shrink-0 justify-start rounded-md px-3 text-xs data-[state=active]:font-medium lg:w-full" value="about">{t("updates.title")}</TabsTrigger>
|
||||
</TabsList>
|
||||
@@ -341,15 +342,6 @@ export function SettingsPage() {
|
||||
</AlertDialog>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title={t("settings.audit.title")}>
|
||||
<div className="space-y-0">
|
||||
<SettingsField controlId="audit-buffer-size" label={t("settings.audit.bufferSize")} description={t("settings.audit.bufferSizeHelp")} badge={t("settings.restartRequired")} error={form.formState.errors.audit?.bufferSize?.message}><Input id="audit-buffer-size" type="number" min={1} max={262_144} {...form.register("audit.bufferSize", { valueAsNumber: true })} /></SettingsField>
|
||||
<SettingsField controlId="audit-batch-size" label={t("settings.audit.batchSize")} description={t("settings.audit.batchSizeHelp")} error={form.formState.errors.audit?.batchSize?.message}><Input id="audit-batch-size" type="number" min={1} max={4_096} {...form.register("audit.batchSize", { valueAsNumber: true })} /></SettingsField>
|
||||
<SettingsField controlId="audit-flush-interval" label={t("settings.audit.flushInterval")} description={t("settings.audit.flushIntervalHelp")} error={form.formState.errors.audit?.flushInterval?.message}><Controller control={form.control} name="audit.flushInterval" render={({ field }) => <DurationInput id="audit-flush-interval" value={field.value} onChange={field.onChange} />} /></SettingsField>
|
||||
<SettingsField controlId="audit-commit-delay" label={t("settings.audit.commitDelay")} description={t("settings.audit.commitDelayHelp")} error={form.formState.errors.audit?.commitDelayMS?.message}><Input id="audit-commit-delay" type="number" min={1} max={50} {...form.register("audit.commitDelayMS", { valueAsNumber: true })} /></SettingsField>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title={t("settings.clientKeys.title")}>
|
||||
<div className="space-y-0">
|
||||
<SettingsField controlId="client-key-default-rpm" label={t("settings.clientKeys.rpmLimit")} description={t("settings.clientKeys.rpmLimitHelp")} error={form.formState.errors.clientKeyDefaults?.rpmLimit?.message}><Input id="client-key-default-rpm" type="number" min={1} max={100_000} {...form.register("clientKeyDefaults.rpmLimit", { valueAsNumber: true })} /></SettingsField>
|
||||
@@ -358,6 +350,129 @@ export function SettingsPage() {
|
||||
</SettingsSection>
|
||||
</SettingsPane>
|
||||
|
||||
<SettingsPane value="audit">
|
||||
<SettingsSection title={t("settings.audit.retentionTitle")}>
|
||||
<div className="space-y-0">
|
||||
<SettingsField
|
||||
controlId="audit-retention-days"
|
||||
label={t("settings.audit.retentionDays")}
|
||||
description={t("settings.audit.retentionDaysHelp")}
|
||||
error={form.formState.errors.audit?.retentionDays?.message}
|
||||
>
|
||||
<Input
|
||||
id="audit-retention-days"
|
||||
type="number"
|
||||
min={0}
|
||||
max={365}
|
||||
{...form.register("audit.retentionDays", { valueAsNumber: true })}
|
||||
/>
|
||||
</SettingsField>
|
||||
|
||||
<SettingsField
|
||||
controlId="audit-record-request-body"
|
||||
label={t("settings.audit.recordRequestBody")}
|
||||
description={t("settings.audit.recordRequestBodyHelp")}
|
||||
>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="audit.recordRequestBody"
|
||||
render={({ field }) => (
|
||||
<div className="flex h-9 items-center">
|
||||
<Switch
|
||||
id="audit-record-request-body"
|
||||
checked={Boolean(field.value)}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</SettingsField>
|
||||
|
||||
<SettingsField
|
||||
controlId="audit-record-response-body"
|
||||
label={t("settings.audit.recordResponseBody")}
|
||||
description={t("settings.audit.recordResponseBodyHelp")}
|
||||
>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="audit.recordResponseBody"
|
||||
render={({ field }) => (
|
||||
<div className="flex h-9 items-center">
|
||||
<Switch
|
||||
id="audit-record-response-body"
|
||||
checked={Boolean(field.value)}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</SettingsField>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title={t("settings.audit.performanceTitle")}>
|
||||
<div className="space-y-0">
|
||||
<SettingsField
|
||||
controlId="audit-buffer-size"
|
||||
label={t("settings.audit.bufferSize")}
|
||||
description={t("settings.audit.bufferSizeHelp")}
|
||||
badge={t("settings.restartRequired")}
|
||||
error={form.formState.errors.audit?.bufferSize?.message}
|
||||
>
|
||||
<Input
|
||||
id="audit-buffer-size"
|
||||
type="number"
|
||||
min={1}
|
||||
max={262_144}
|
||||
{...form.register("audit.bufferSize", { valueAsNumber: true })}
|
||||
/>
|
||||
</SettingsField>
|
||||
<SettingsField
|
||||
controlId="audit-batch-size"
|
||||
label={t("settings.audit.batchSize")}
|
||||
description={t("settings.audit.batchSizeHelp")}
|
||||
error={form.formState.errors.audit?.batchSize?.message}
|
||||
>
|
||||
<Input
|
||||
id="audit-batch-size"
|
||||
type="number"
|
||||
min={1}
|
||||
max={4_096}
|
||||
{...form.register("audit.batchSize", { valueAsNumber: true })}
|
||||
/>
|
||||
</SettingsField>
|
||||
<SettingsField
|
||||
controlId="audit-flush-interval"
|
||||
label={t("settings.audit.flushInterval")}
|
||||
description={t("settings.audit.flushIntervalHelp")}
|
||||
error={form.formState.errors.audit?.flushInterval?.message}
|
||||
>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="audit.flushInterval"
|
||||
render={({ field }) => (
|
||||
<DurationInput id="audit-flush-interval" value={field.value} onChange={field.onChange} />
|
||||
)}
|
||||
/>
|
||||
</SettingsField>
|
||||
<SettingsField
|
||||
controlId="audit-commit-delay"
|
||||
label={t("settings.audit.commitDelay")}
|
||||
description={t("settings.audit.commitDelayHelp")}
|
||||
error={form.formState.errors.audit?.commitDelayMS?.message}
|
||||
>
|
||||
<Input
|
||||
id="audit-commit-delay"
|
||||
type="number"
|
||||
min={1}
|
||||
max={50}
|
||||
{...form.register("audit.commitDelayMS", { valueAsNumber: true })}
|
||||
/>
|
||||
</SettingsField>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
</SettingsPane>
|
||||
|
||||
<SettingsPane value="accounts">
|
||||
<SettingsSection title={t("settings.accounts.invalidationTitle")}>
|
||||
<div className="space-y-0">
|
||||
|
||||
@@ -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.", sLine truncated
|
||||
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-proLine truncated
|
||||
|
||||
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." },
|
||||
|
||||
Reference in new issue
Block a user