agent

package
v2.3.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package agent implements the transport-neutral, read-only conversational RAG domain.

Index

Constants

View Source
const (
	AuditErrorInvalidMetadata = "audit_invalid_metadata"
	AuditErrorSinkUnavailable = "audit_sink_unavailable"
	AuditErrorSinkDelivery    = "audit_sink_delivery"
)
View Source
const (
	MaxQuestionBytes       = 8 * 1024
	MaxHistoryMessages     = 12
	MaxHistoryMessageBytes = 4 * 1024
	MaxHistoryBytes        = 24 * 1024
	MaxEvidencePerCorpus   = 8
	MaxContextBytes        = 32 * 1024
)
View Source
const (
	RoleUser      = "user"
	RoleAssistant = "assistant"
)
View Source
const (
	ConfidenceLow    = "low"
	ConfidenceMedium = "medium"
	ConfidenceHigh   = "high"

	DegradedMemoryUnavailable = "memory_unavailable"
	DegradedCodeUnavailable   = "code_unavailable"
	DegradedNoEvidence        = "no_authorized_evidence"
)
View Source
const HardMaxOutputTokens = 4096

Variables

View Source
var ErrUnknownLimitTier = errors.New("unknown agent limit tier")

Functions

func WithRequestTimeout

func WithRequestTimeout(parent context.Context, limits Limits, transport Transport) (context.Context, context.CancelFunc)

WithRequestTimeout derives the server-owned transport deadline while preserving an earlier upstream deadline and cancellation.

Types

type Answer

type Answer struct {
	Answer     string          `json:"answer"`
	Sources    []Source        `json:"sources"`
	Confidence Confidence      `json:"confidence"`
	Retrieval  RetrievalStatus `json:"retrieval"`
	Usage      CompletionUsage `json:"-"`
}

type AuditEvent

type AuditEvent struct {
	Phase         AuditPhase    `json:"phase"`
	CorrelationID string        `json:"correlation_id"`
	ActorID       string        `json:"actor_id"`
	TenantID      string        `json:"tenant_id"`
	WorkspaceID   string        `json:"workspace_id"`
	Project       string        `json:"project"`
	Transport     Transport     `json:"transport"`
	ResultClass   string        `json:"result_class"`
	Duration      time.Duration `json:"duration_ns"`
	InputTokens   int           `json:"input_tokens"`
	OutputTokens  int           `json:"output_tokens"`
	SourceCount   int           `json:"source_count"`
	Confidence    string        `json:"confidence,omitempty"`
	Degraded      []string      `json:"degraded,omitempty"`
}

AuditEvent is deliberately a closed, metadata-only schema. Conversational content, evidence, credentials, embeddings and provider destinations have no representable field here.

type AuditFailure

type AuditFailure struct {
	CorrelationID string        `json:"correlation_id"`
	Project       string        `json:"project"`
	ResultClass   string        `json:"result_class"`
	SourceCount   int           `json:"source_count"`
	Duration      time.Duration `json:"duration_ns"`
	ErrorClass    string        `json:"error_class"`
}

AuditFailure is the only outcome-delivery failure exposed to telemetry. It intentionally excludes the sink error and all request content.

type AuditPhase

type AuditPhase string
const (
	AuditPhaseAuthorization AuditPhase = "authorization"
	AuditPhaseOutcome       AuditPhase = "outcome"
)

type AuditSink

type AuditSink interface {
	Record(context.Context, AuditEvent) error
}

type AuditTelemetry

type AuditTelemetry interface {
	AuditDeliveryFailed(AuditFailure)
}

type Auditor

type Auditor struct {
	Sink      AuditSink
	Telemetry AuditTelemetry
}

func (Auditor) RecordAuthorization

func (a Auditor) RecordAuthorization(ctx context.Context, event AuditEvent) error

RecordAuthorization is the mandatory pre-provider audit. It fails closed.

func (Auditor) RecordOutcome

func (a Auditor) RecordOutcome(ctx context.Context, event AuditEvent)

RecordOutcome is best effort because a completed answer cannot be recalled. Delivery failure is reported using content-free telemetry only.

type CompletionClaim

type CompletionClaim struct {
	Text            string   `json:"text"`
	CitationHandles []string `json:"citation_handles"`
}

CompletionClaim is the provider's smallest factual output unit. A claim is eligible for the public answer only when at least one handle was issued for this request and resolves to authorized evidence.

type CompletionProvider

type CompletionProvider interface {
	Complete(context.Context, CompletionRequest) (CompletionResult, error)
}

CompletionProvider intentionally exposes no tools, URL, model or credentials.

type CompletionRequest

type CompletionRequest struct {
	SystemPrompt string
	UserPrompt   string
}

type CompletionResult

type CompletionResult struct {
	Claims       []CompletionClaim
	InputTokens  int
	OutputTokens int
}

func (CompletionResult) Usage

type CompletionUsage

type CompletionUsage struct {
	InputTokens  int
	OutputTokens int
}

type Confidence

type Confidence struct {
	Level string  `json:"level"`
	Score float64 `json:"score"`
}

type Error

type Error struct {
	Code ErrorCode
	Err  error
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorCode

type ErrorCode string
const (
	ErrorQuotaExceeded    ErrorCode = "quota_exceeded"
	ErrorAgentTimeout     ErrorCode = "agent_timeout"
	ErrorRequestCancelled ErrorCode = "request_cancelled"
	ErrorAuditUnavailable ErrorCode = "audit_unavailable"
)
const (
	ErrorInvalidRequest      ErrorCode = "invalid_request"
	ErrorInvalidHistoryRole  ErrorCode = "invalid_history_role"
	ErrorHistoryTooLarge     ErrorCode = "history_too_large"
	ErrorQuestionTooLarge    ErrorCode = "question_too_large"
	ErrorProviderUnavailable ErrorCode = "provider_unavailable"
)

func ContextErrorCode

func ContextErrorCode(err error) ErrorCode

type Evidence

type Evidence struct {
	Kind      EvidenceKind `json:"type"`
	Title     string       `json:"title"`
	Path      string       `json:"path,omitempty"`
	LineStart int          `json:"line_start,omitempty"`
	LineEnd   int          `json:"line_end,omitempty"`
	Content   string       `json:"-"`
	Score     float64      `json:"-"`
}

Evidence is trusted scope-wise by its adapter. Content is prompt-only and never returned.

type EvidenceKind

type EvidenceKind string
const (
	EvidenceMemory EvidenceKind = "memory"
	EvidenceCode   EvidenceKind = "code"
)

type LimitPolicy

type LimitPolicy struct {
	Tiers map[string]Limits
}

func DefaultLimitPolicy

func DefaultLimitPolicy() LimitPolicy

func (LimitPolicy) ForTier

func (p LimitPolicy) ForTier(tier LimitTier) (Limits, error)

type LimitTier

type LimitTier string
const (
	TierLimited  LimitTier = "limited"
	TierStandard LimitTier = "standard"
	TierElevated LimitTier = "elevated"
)

type Limits

type Limits struct {
	RequestsPerMinute   int
	TokensPerMinute     int
	MaxTenantConcurrent int
	DefaultOutputTokens int
	MaxOutputTokens     int
	JSONTimeout         time.Duration
	StreamTimeout       time.Duration
}

Limits are trusted server-side budgets. None of these values may be supplied by an agent request.

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type QuotaError

type QuotaError struct {
	RetryAfter time.Duration
}

QuotaError carries bounded retry metadata without exposing limiter keys or internal capacity state.

func (*QuotaError) Error

func (e *QuotaError) Error() string

type Request

type Request struct {
	Scope    Scope     `json:"-"`
	Question string    `json:"question"`
	History  []Message `json:"history,omitempty"`
}

type RetrievalResult

type RetrievalResult struct {
	Evidence []Evidence
	Trace    RetrievalTrace
}

RetrievalResult keeps evidence and its safe execution trace together.

type RetrievalStage

type RetrievalStage struct {
	Name   string
	Status string
	Count  int
}

RetrievalStage reports only safe pipeline state; it never carries query, content, internal identifiers, or authorization details.

type RetrievalStageStatus

type RetrievalStageStatus struct {
	Name   string `json:"name"`
	Status string `json:"status"`
	Count  int    `json:"count"`
}

RetrievalStageStatus is the public, content-free projection of one retrieval stage. Generation remains empty until a trusted corpus generation is carried by the retrieval port; transports must never synthesize one from request data or expose internal checksums.

type RetrievalStatus

type RetrievalStatus struct {
	Tier             string                 `json:"tier,omitempty"`
	Stages           []RetrievalStageStatus `json:"stages,omitempty"`
	RefinementCount  int                    `json:"refinement_count,omitempty"`
	Generation       string                 `json:"generation,omitempty"`
	Degraded         []string               `json:"degraded"`
	InvalidCitations int                    `json:"invalid_citations,omitempty"`
}

type RetrievalTier

type RetrievalTier string

RetrievalTier is the bounded route selected for one scoped read.

const (
	RetrievalTierDirectFactual       RetrievalTier = "direct_factual"
	RetrievalTierSemanticHybrid      RetrievalTier = "semantic_hybrid"
	RetrievalTierMultiHopGraph       RetrievalTier = "multi_hop_graph"
	RetrievalTierArchitecturalGlobal RetrievalTier = "architectural_global"
	DegradedDenseUnavailable                       = "dense_unavailable"
)

type RetrievalTrace

type RetrievalTrace struct {
	Tier     RetrievalTier
	Stages   []RetrievalStage
	Degraded []string
}

RetrievalTrace is transport-neutral metadata from the scoped retriever.

type Retriever

type Retriever interface {
	Retrieve(context.Context, Scope, string, int) ([]Evidence, error)
}

Retriever has no write method and receives scope resolved by the server.

type Scope

type Scope struct {
	TenantID    string `json:"-"`
	WorkspaceID string `json:"-"`
	Project     string `json:"project"`
}

type ScopedRetriever

type ScopedRetriever interface {
	RetrieveScoped(context.Context, Scope, string, int) (RetrievalResult, error)
}

ScopedRetriever is the single read-only retrieval port used by the agent. Server composition resolves tenant, workspace, and project authority before the implementation touches lexical, dense, or graph dependencies.

type Service

type Service struct {
	// contains filtered or unexported fields
}

func NewScopedService

func NewScopedService(retriever ScopedRetriever, completion CompletionProvider) *Service

NewScopedService composes the agent with one deep, scope-preserving retrieval module. NewService remains for local compatibility while server mode uses this constructor exclusively.

func NewService

func NewService(memory, code Retriever, completion CompletionProvider) *Service

func (*Service) Answer

func (s *Service) Answer(ctx context.Context, req Request) (Answer, error)

func (*Service) Stream

func (s *Service) Stream(ctx context.Context, req Request, callbacks StreamCallbacks) (Answer, error)

Stream shares retrieval, prompt construction, claim validation, citation resolution and final answer semantics with Answer while allowing validated claims to reach the caller progressively.

type Source

type Source struct {
	Handle    string       `json:"handle"`
	Type      EvidenceKind `json:"type"`
	Title     string       `json:"title"`
	Path      string       `json:"path,omitempty"`
	LineStart int          `json:"line_start,omitempty"`
	LineEnd   int          `json:"line_end,omitempty"`
}

type StreamCallbacks

type StreamCallbacks struct {
	Meta    func(RetrievalStatus) error
	Delta   func(string) error
	Sources func([]Source) error
}

StreamCallbacks is transport-neutral. Meta precedes every delta, Sources is emitted once after all claims have been validated, and the returned Answer is the canonical terminal representation shared with the JSON transport.

type StreamingCompletionProvider

type StreamingCompletionProvider interface {
	Stream(context.Context, CompletionRequest, func(CompletionClaim) error) (CompletionUsage, error)
}

StreamingCompletionProvider emits complete, provider-produced claims as soon as they can be parsed. Claims are still untrusted until Service resolves their handles against the evidence issued for the current request.

type Transport

type Transport string
const (
	TransportJSON   Transport = "json"
	TransportStream Transport = "stream"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL