app

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultGlobalPolicy

func DefaultGlobalPolicy() domain.PolicyMetadata

DefaultGlobalPolicy returns the baseline global policy merged during Manager.BeginTurn when the executor has no operator-specific policy wiring.

func DigestJSONFields

func DigestJSONFields(raw string, pol domain.PolicyMetadata) string

DigestJSONFields returns a structural digest of JSON without echoing full payloads.

func FingerprintResumeToken

func FingerprintResumeToken(key []byte, tok domain.ResumeToken, m EntropyMaterial) domain.TokenFingerprint

FingerprintResumeToken computes the stored fingerprint for an existing raw token (tests, resume validation).

func RawAuditAllowed

func RawAuditAllowed(pol domain.PolicyMetadata) bool

RawAuditAllowed reports whether session policy permits embedding raw payloads in audit records.

func RedactCorrelationJSON

func RedactCorrelationJSON(raw string, pol domain.PolicyMetadata) string

RedactCorrelationJSON applies correlation redaction for operator-visible JSON strings.

Types

type BeginInput

type BeginInput struct {
	Now     time.Time
	TraceID string

	Session            SessionWire
	Principal          domain.PrincipalRef
	Workspace          domain.WorkspaceRef
	GlobalPolicy       domain.PolicyMetadata
	ClientHints        domain.ClientHints
	FirstMessageDigest string

	// WorkspaceMatchRequired rejects the turn when a workspace id is required but missing on the request.
	WorkspaceMatchRequired bool
}

BeginInput is the secure-session gate input for one client-visible turn.

type BeginResult

type BeginResult struct {
	Record          domain.Record
	TurnID          domain.TurnID
	IsNew           bool
	Response        ResponseMetadata
	EffectivePolicy domain.PolicyMetadata
}

BeginResult is the validated secure-session context for routing and continuity.

type ClientInputLine

type ClientInputLine struct {
	Role    string
	Ordinal int
	Parts   []string // part kinds in order (text, tool_result, …)
}

ClientInputLine is one ordered accepted client message line after hooks (canonical roles).

type ClientTurnRecordInput

type ClientTurnRecordInput struct {
	Now       time.Time
	TraceID   string
	SessionID domain.SessionID
	TurnID    domain.TurnID
	Policy    domain.PolicyMetadata
	Lines     []ClientInputLine
}

ClientTurnRecordInput captures accepted client input for one gated turn.

type EntropyMaterial

type EntropyMaterial struct {
	PrincipalID        string
	AgentDigest        string
	FirstMessageDigest string
}

EntropyMaterial carries optional domain-separation inputs for resume fingerprints. Uniqueness of session ids and resume tokens does not depend on these fields.

type GateRecording

type GateRecording interface {
	RecordClientTurnAfterGate(ctx context.Context, in ClientTurnRecordInput) error
	RecordPostHookStreamEvent(ctx context.Context, in StreamEventRecordInput) error
}

GateRecording is the secure-session recorder port used by the runtime after gate success and for post-hook canonical stream events (transcript, usage, activity, audit).

type Generator

type Generator interface {
	NewSessionID(ctx context.Context, material EntropyMaterial) (domain.SessionID, error)
	NewResumeToken(ctx context.Context, material EntropyMaterial) (domain.ResumeToken, domain.TokenFingerprint, error)
}

Generator issues proxy-owned session ids and resume bearer tokens.

type LineageALeg

type LineageALeg struct {
	ALegID                string
	ContinuityKey         string
	WeightedFirstConsumed bool
}

LineageALeg is the minimal A-leg view the secure-session manager needs from B2BUA lineage.

type LineageStore

type LineageStore interface {
	CreateALeg(ctx context.Context, continuityKey string) (LineageALeg, error)
	FetchALeg(ctx context.Context, aLegID string) (LineageALeg, error)
	SetWeightedFirstConsumed(ctx context.Context, aLegID string, consumed bool) error
}

LineageStore is an app-owned port over A-leg allocation and routing flags. Implementations live under securesession/adapters (e.g. b2bualineage).

type Manager

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

Manager enforces secure-session policy for BeginTurn and records turn outcomes.

func NewManager

func NewManager(store Store, gen Generator, lineage LineageStore, cfg ManagerConfig) (*Manager, error)

NewManager constructs a Manager. store, gen, and lineage must be non-nil; cfg.FingerprintKey must be non-empty.

func (*Manager) AssertActive

func (m *Manager) AssertActive(ctx context.Context, id domain.SessionID) error

AssertActive loads the session and returns ErrSessionQuarantined when status is quarantined. Phase 1 implements the status check when stores persist Status; unimplemented quarantine leaves sessions active so existing BeginTurn behavior is unchanged.

func (*Manager) BeginTurn

func (m *Manager) BeginTurn(ctx context.Context, in BeginInput) (BeginResult, error)

BeginTurn authorizes a new or resumed session turn and returns validated proxy-owned state.

func (*Manager) FinishTurn

func (m *Manager) FinishTurn(ctx context.Context, sessionID domain.SessionID, turnID domain.TurnID, outcome TurnOutcome) error

FinishTurn records terminal turn outcome evidence (audit row).

func (*Manager) LoadByALegID

func (m *Manager) LoadByALegID(ctx context.Context, aLegID string) (domain.Record, error)

LoadByALegID returns the secure-session row owning a proxy A-leg.

func (*Manager) PreBackendMandatoryGates

func (m *Manager) PreBackendMandatoryGates(ctx context.Context, pol domain.PolicyMetadata) error

PreBackendMandatoryGates runs the same readiness checks as Manager.BeginTurn before opening a backend attempt.

func (*Manager) Quarantine

func (m *Manager) Quarantine(ctx context.Context, in domain.QuarantineInput) error

Quarantine transitions a session to the terminal quarantined status via Store.Quarantine. Phase 1 exposes the manager signature; store adapters may still return ErrQuarantineUnimplemented until Phase 5 implements durable/idempotent quarantine.

func (*Manager) RecordAttemptOpened

func (m *Manager) RecordAttemptOpened(ctx context.Context, trace domain.AttemptTrace) error

RecordAttemptOpened persists immutable B-leg open metadata for secure-session diagnostics.

func (*Manager) RecordAttemptOutcome

func (m *Manager) RecordAttemptOutcome(ctx context.Context, outcome domain.AttemptOutcome) error

RecordAttemptOutcome updates the latest terminal attempt outcome for secure-session diagnostics.

type ManagerConfig

type ManagerConfig struct {
	// ResumeWindow is inactivity-based resume limit; zero means unbounded.
	ResumeWindow time.Duration
	// StoreDurable is true when the secure-session store is durable (e.g. SQLite).
	StoreDurable bool
	// RequireDurableStore rejects BeginTurn when durable evidence is required but StoreDurable is false.
	RequireDurableStore bool
	// FingerprintKey fingerprints resume tokens (must match store configuration).
	FingerprintKey []byte
	// ObserveActivityTouch, when set, is called with wall time spent in last-activity [Store.TouchActivity] in BeginTurn.
	ObserveActivityTouch func(seconds float64)
	// ResumeFingerprintPrincipalOnly when true fingerprints resume tokens using only [PrincipalRef.ID]
	// as domain-separation material (HMAC still includes raw token bytes). Agent/client digest drift
	// does not invalidate resumes (see secure_session.resume_token_bind_principal_only).
	ResumeFingerprintPrincipalOnly bool
}

ManagerConfig configures Manager policy gates and crypto inputs.

type RandGenerator

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

RandGenerator creates opaque ids/tokens from crypto/rand and HMAC-SHA-256 fingerprints.

func NewRandGenerator

func NewRandGenerator(fpKey []byte) *RandGenerator

NewRandGenerator returns a generator that fingerprints resume tokens with fpKey. fpKey must be non-empty for production use; tests may use any fixed slice.

func (*RandGenerator) NewResumeToken

NewResumeToken returns a random bearer token and its stored fingerprint (never persist the token).

func (*RandGenerator) NewSessionID

func (g *RandGenerator) NewSessionID(ctx context.Context, material EntropyMaterial) (domain.SessionID, error)

NewSessionID returns a high-entropy opaque session id independent of material.

type Recorder

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

Recorder persists secure-session transcript, usage, activity, and audit via Store.

func NewRecorder

func NewRecorder(store Store) (*Recorder, error)

NewRecorder constructs a Recorder. store must be non-nil.

func (*Recorder) RecordClientTurnAfterGate

func (r *Recorder) RecordClientTurnAfterGate(ctx context.Context, in ClientTurnRecordInput) error

RecordClientTurnAfterGate appends accepted client input immediately after secure-session gate success.

func (*Recorder) RecordPostHookStreamEvent

func (r *Recorder) RecordPostHookStreamEvent(ctx context.Context, in StreamEventRecordInput) error

RecordPostHookStreamEvent records one post-hook canonical client-facing stream slice.

type ResponseMetadata

type ResponseMetadata struct {
	SessionID   string
	ResumeToken domain.ResumeToken
}

ResponseMetadata carries wire-safe session authority for new sessions only. Raw resume tokens must never be loaded from storage; they appear here only on create.

type SessionUsageRollup

type SessionUsageRollup interface {
	UsageTokenTotals(ctx context.Context, id domain.SessionID) (inputTokens, outputTokens int64, err error)
}

SessionUsageRollup is an optional extension implemented by stores that expose per-session token totals for operator diagnostics. Callers type-assert from Store when present.

type SessionWire

type SessionWire struct {
	ClientSessionID string
	ContinuityKey   string
	ALegID          string
	SessionID       string
	ResumeToken     string
}

SessionWire carries session identifiers from the orchestration boundary into Manager.BeginTurn. Fields align with github.com/matdev83/go-llm-interactive-proxy/pkg/lipapi.SessionRef without importing lipapi.

type Store

type Store interface {
	Create(ctx context.Context, rec domain.CreateRecord) (domain.Record, error)
	LoadByID(ctx context.Context, id domain.SessionID) (domain.Record, error)
	LoadByResumeFingerprint(ctx context.Context, fp domain.TokenFingerprint) (domain.Record, error)
	LoadByALegID(ctx context.Context, aLegID string) (domain.Record, error)
	TouchActivity(ctx context.Context, id domain.SessionID, at time.Time, source domain.ActivitySource) error
	AppendAttemptTrace(ctx context.Context, trace domain.AttemptTrace) error
	UpdateAttemptOutcome(ctx context.Context, outcome domain.AttemptOutcome) error
	// AppendTranscript appends a row; durable implementations allocate the next seq in the same
	// transaction as the insert (item.Seq is ignored there). NextTranscriptSeq remains a best-effort preview.
	AppendTranscript(ctx context.Context, item domain.TranscriptItem) error
	// NextTranscriptSeq returns the next monotonic sequence number for a new transcript row for the session.
	NextTranscriptSeq(ctx context.Context, id domain.SessionID) (int64, error)
	AddUsage(ctx context.Context, delta domain.UsageDelta) error
	// NextAuditSeq returns the next monotonic sequence number for a new audit entry for the session.
	NextAuditSeq(ctx context.Context, id domain.SessionID) (int64, error)
	// AppendAudit appends a row; durable implementations allocate the next seq in the same transaction
	// as the insert (item.Seq is ignored there). NextAuditSeq remains a best-effort preview.
	AppendAudit(ctx context.Context, item domain.AuditItem) error
	Audit(ctx context.Context, id domain.SessionID, opts domain.ReadOptions) ([]domain.AuditItem, error)
	Summary(ctx context.Context, query domain.SummaryQuery) ([]domain.Summary, error)
	Transcript(ctx context.Context, id domain.SessionID, opts domain.ReadOptions) ([]domain.TranscriptItem, error)
	// ListAttemptEvidence returns chronological B-leg attempts for operator diagnostics (bounded by opts.Limit, default 100).
	ListAttemptEvidence(ctx context.Context, id domain.SessionID, opts domain.ReadOptions) ([]domain.AttemptEvidence, error)
	CheckReadiness(ctx context.Context, policy domain.PolicyMetadata) error
	// Quarantine performs an atomic, idempotent transition to SessionStatusQuarantined.
	// Durable implementations update status and append a minimal session audit row in one transaction.
	// A second identical quarantine must succeed without duplicating terminal state.
	Quarantine(ctx context.Context, in domain.QuarantineInput) error
}

Store persists secure-session rows, indexes, transcripts, usage, audit, and readiness checks. Adapters implement this port; the interface stays consumer-owned in package app.

type StreamEventRecordInput

type StreamEventRecordInput struct {
	Now       time.Time
	TraceID   string
	SessionID domain.SessionID
	TurnID    domain.TurnID
	BLegID    string
	BackendID string
	Policy    domain.PolicyMetadata

	EventKind string
	// EventPayloadJSON is a redacted JSON snapshot of the canonical event (never raw resume tokens).
	EventPayloadJSON string

	IsUsageEvent bool
	InputTokens  int64
	OutputTokens int64

	CacheReadTokens          int64
	CacheWriteTokens         int64
	NonCachedInputTokens     int64
	ReasoningTokens          int64
	NonReasoningOutputTokens int64
	TotalTokens              int64
	CostNanoUnits            int64
	CostMinorUnits           int64
	Currency                 string
	CostSource               string
	RawUsageJSON             string
	BillingUnavailable       bool

	RequestStartedAt         time.Time
	FirstRemoteEventAt       time.Time
	FirstMeaningfulTokenAt   time.Time
	RemoteCompletedAt        time.Time
	ProxyCompletedAt         time.Time
	TTFTMillis               int64
	RemoteDurationMillis     int64
	CompletionDurationMillis int64
	CompletionTPSMilli       int64

	// ProviderCorrelationJSON holds non-authoritative provider correlation (never session authority).
	ProviderCorrelationJSON string
}

StreamEventRecordInput is a post-hook canonical stream slice for recording.

type TurnOutcome

type TurnOutcome struct {
	Kind TurnOutcomeKind
}

TurnOutcome is input to Manager.FinishTurn for durable evidence.

type TurnOutcomeKind

type TurnOutcomeKind int

TurnOutcomeKind classifies how a turn ended for audit and diagnostics.

const (
	TurnOutcomeUnknown TurnOutcomeKind = iota
	TurnOutcomeSuccess
	TurnOutcomePreOutputDenied
	TurnOutcomeSurfacedFailure
	TurnOutcomePostOutputRecorderFailure
)

Jump to

Keyboard shortcuts

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