session

package
v0.5.0 Latest Latest
Warning

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

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

Documentation

Overview

Package session provides session management and persistence.

Index

Constants

View Source
const (
	StatusRunning  = "running"
	StatusComplete = "complete"
	StatusFailed   = "failed"
)

Status constants for sessions.

View Source
const (
	// LLM conversation events
	EventSystem    = "system"    // System message to LLM
	EventUser      = "user"      // User/prompt message to LLM
	EventAssistant = "assistant" // LLM response

	// Tool events
	EventToolCall   = "tool_call"   // Tool invocation started
	EventToolResult = "tool_result" // Tool completed

	// Goal events
	EventGoalStart = "goal_start"
	EventGoalEnd   = "goal_end"

	// Workflow events
	EventWorkflowStart = "workflow_start"
	EventWorkflowEnd   = "workflow_end"

	// Supervision events (four-phase execution)
	EventPhaseCommit    = "phase_commit"    // COMMIT phase - agent declares intent
	EventPhaseExecute   = "phase_execute"   // EXECUTE phase - do work
	EventPhaseReconcile = "phase_reconcile" // RECONCILE phase - static checks
	EventPhaseSupervise = "phase_supervise" // SUPERVISE phase - LLM judgment
	EventCheckpoint     = "checkpoint"      // Checkpoint saved

	// Security events
	EventSecurityBlock      = "security_block"      // Untrusted content registered
	EventSecurityStatic     = "security_static"     // Static/deterministic checks (patterns, entropy)
	EventSecurityTriage     = "security_triage"     // LLM triage for suspicious content
	EventSecuritySupervisor = "security_supervisor" // Full supervisor review
	EventSecurityDecision   = "security_decision"   // Final decision
	EventBashSecurity       = "bash_security"       // Bash command security check

	// Sub-agent events
	EventSubAgentStart = "subagent_start" // Sub-agent spawned
	EventSubAgentEnd   = "subagent_end"   // Sub-agent completed

	// Warning events (shown in yellow in replay)
	EventWarning = "warning"

	// Deprecated: use the descriptive names above
	EventSecurityTier1 = EventSecurityStatic
	EventSecurityTier2 = EventSecurityTriage
	EventSecurityTier3 = EventSecuritySupervisor
)

Event types for the session log - unified forensic events

View Source
const (
	RecordTypeHeader = "header" // Session metadata (first line)
	RecordTypeEvent  = "event"  // Individual event
	RecordTypeFooter = "footer" // Final state (last line, optional)
)

JSONL record types for streaming format

Variables

This section is empty.

Functions

func DetectFormat

func DetectFormat(path string) (string, error)

DetectFormat checks if a file is JSONL or legacy JSON format.

Types

type Event

type Event struct {
	// Core fields - always present
	SeqID     uint64    `json:"seq"`       // Monotonic sequence number for ordering
	Type      string    `json:"type"`      // Event type (see constants above)
	Timestamp time.Time `json:"timestamp"` // When this event occurred

	// Correlation - for linking related events
	CorrelationID string `json:"corr_id,omitempty"` // Links related events (e.g., tool_call -> security checks -> tool_result)
	ParentSeqID   uint64 `json:"parent,omitempty"`  // Parent event sequence ID (for nesting)

	// Agent context - for sub-agent attribution
	Agent     string `json:"agent,omitempty"`      // Agent name (for sub-agents)
	AgentRole string `json:"agent_role,omitempty"` // Agent role (for dynamic sub-agents)

	// Context - where in execution this happened
	Goal string `json:"goal,omitempty"` // Current goal name
	Step string `json:"step,omitempty"` // Current step (for workflow steps)

	// Content - the actual data
	Content string                 `json:"content,omitempty"` // Message content, tool result, etc.
	Tool    string                 `json:"tool,omitempty"`    // Tool name (for tool events)
	Args    map[string]interface{} `json:"args,omitempty"`    // Tool arguments (sanitized)

	// Outcome
	Success    *bool  `json:"success,omitempty"`     // nil = in progress, true = success, false = failure
	Error      string `json:"error,omitempty"`       // Error message if failed
	DurationMs int64  `json:"duration_ms,omitempty"` // Execution time (for *_end events)

	// Forensic metadata - structured data for analysis
	Meta *EventMeta `json:"meta,omitempty"`
}

Event represents a single entry in the session log. This is THE forensic record - all analysis tools read from here.

type EventMeta

type EventMeta struct {
	// Phase execution (supervision)
	Phase         string   `json:"phase,omitempty"`          // COMMIT, EXECUTE, RECONCILE, SUPERVISE
	Result        string   `json:"result,omitempty"`         // Phase result or verdict
	Commitment    string   `json:"commitment,omitempty"`     // Agent's declared intent (JSON)
	Confidence    string   `json:"confidence,omitempty"`     // high, medium, low
	Triggers      []string `json:"triggers,omitempty"`       // Reconcile triggers that fired
	Escalate      bool     `json:"escalate,omitempty"`       // Whether to escalate to SUPERVISE
	Verdict       string   `json:"verdict,omitempty"`        // CONTINUE, REORIENT, PAUSE
	Correction    string   `json:"correction,omitempty"`     // Supervisor correction text
	Guidance      string   `json:"guidance,omitempty"`       // Supervisor guidance (alias for correction)
	Human         bool     `json:"human,omitempty"`          // Human intervention required/occurred
	HumanRequired bool     `json:"human_required,omitempty"` // Alias for Human field

	// Supervisor identification
	SupervisorType string `json:"supervisor_type,omitempty"` // "execution" or "security"

	// Security
	BlockID       string      `json:"block_id,omitempty"`       // Content block ID (b0001, b0002, ...)
	RelatedBlocks []string    `json:"related_blocks,omitempty"` // All blocks whose content contributed to this action
	TaintLineage  []TaintNode `json:"taint_lineage,omitempty"`  // Taint dependency tree for security events
	Trust         string      `json:"trust,omitempty"`          // trusted, vetted, untrusted
	BlockType     string      `json:"block_type,omitempty"`     // instruction, data
	Source        string      `json:"source,omitempty"`         // Where content came from
	Entropy       float64     `json:"entropy,omitempty"`        // Shannon entropy (0.0-8.0)
	CheckName     string      `json:"check,omitempty"`          // static, triage, supervisor
	Pass          bool        `json:"pass,omitempty"`           // Check passed
	Flags         []string    `json:"flags,omitempty"`          // Security flags detected
	Suspicious    bool        `json:"suspicious,omitempty"`     // Triage result
	Action        string      `json:"action,omitempty"`         // allow, deny, modify
	Reason        string      `json:"reason,omitempty"`         // Decision reason
	CheckPath     string      `json:"check_path,omitempty"`     // Verification path (static, static→triage, static→triage→supervisor)
	SkipReason    string      `json:"skip_reason,omitempty"`    // Why escalation was skipped (e.g., "low_risk_tool", "no_untrusted_content", "triage_benign")
	XMLBlock      string      `json:"xml,omitempty"`            // Full XML block for forensic tools

	// Deprecated: use CheckName/CheckPath instead
	Tier     int    `json:"tier,omitempty"`      // 1=static, 2=triage, 3=supervisor
	Tiers    string `json:"tiers,omitempty"`     // Old tier path format
	TierPath string `json:"tier_path,omitempty"` // Alias for Tiers

	// Checkpoint
	CheckpointType string `json:"ckpt_type,omitempty"` // pre, post, reconcile, supervise
	CheckpointID   string `json:"ckpt_id,omitempty"`   // Checkpoint identifier

	// Sub-agent execution
	SubAgentName   string            `json:"subagent_name,omitempty"`   // Sub-agent identifier
	SubAgentRole   string            `json:"subagent_role,omitempty"`   // Sub-agent role (from AGENT definition)
	SubAgentModel  string            `json:"subagent_model,omitempty"`  // Model used by sub-agent
	SubAgentTask   string            `json:"subagent_task,omitempty"`   // Task given to sub-agent
	SubAgentOutput string            `json:"subagent_output,omitempty"` // Full output from sub-agent
	SubAgentInputs map[string]string `json:"subagent_inputs,omitempty"` // Inputs passed to sub-agent

	// LLM details
	Model     string `json:"model,omitempty"`      // Model used
	LatencyMs int64  `json:"latency_ms,omitempty"` // LLM call latency
	TokensIn  int    `json:"tokens_in,omitempty"`  // Input tokens
	TokensOut int    `json:"tokens_out,omitempty"` // Output tokens

	// Full LLM interaction (for forensic replay)
	Prompt   string `json:"prompt,omitempty"`   // Full prompt sent to LLM
	Response string `json:"response,omitempty"` // Full LLM response
	Thinking string `json:"thinking,omitempty"` // LLM thinking/reasoning (if available)
}

EventMeta contains detailed forensic information. Structured for easy querying by forensic tools.

type FileManager

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

FileManager wraps FileStore to implement SessionManager.

func (*FileManager) Create

func (m *FileManager) Create(workflowName string) (*Session, error)

Create creates a new session.

func (*FileManager) Get

func (m *FileManager) Get(id string) (*Session, error)

Get retrieves a session by ID.

func (*FileManager) Update

func (m *FileManager) Update(sess *Session) error

Update updates a session.

type FileStore

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

FileStore implements Store using the filesystem. New sessions use JSONL format; legacy JSON format is supported for reading. Uses append-only writes for efficient event streaming.

func NewFileStore

func NewFileStore(dir string) (*FileStore, error)

NewFileStore creates a new file-based store.

func (*FileStore) Load

func (s *FileStore) Load(id string) (*Session, error)

Load reads a session from disk. Supports both JSONL (new) and JSON (legacy) formats.

func (*FileStore) Save

func (s *FileStore) Save(sess *Session) error

Save persists a session to disk using append-only writes. On first call, writes header. On subsequent calls, appends new events only. Always appends footer (loader takes the last footer).

type JSONLRecord

type JSONLRecord struct {
	RecordType string `json:"_type"` // header, event, footer

	// Header fields (when _type == "header")
	ID           string            `json:"id,omitempty"`
	WorkflowName string            `json:"workflow_name,omitempty"`
	Inputs       map[string]string `json:"inputs,omitempty"`
	CreatedAt    time.Time         `json:"created_at,omitempty"`

	// Event fields (when _type == "event") - embedded Event
	*Event `json:",omitempty"`

	// Footer fields (when _type == "footer")
	Status    string                 `json:"status,omitempty"`
	Result    string                 `json:"result,omitempty"`
	Error     string                 `json:"error,omitempty"`
	Outputs   map[string]string      `json:"outputs,omitempty"`
	State     map[string]interface{} `json:"state,omitempty"`
	UpdatedAt time.Time              `json:"updated_at,omitempty"`
}

JSONLRecord is a wrapper for JSONL lines with type discrimination.

type Manager

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

Manager manages sessions.

func NewManager

func NewManager(store Store) *Manager

NewManager creates a new session manager.

func (*Manager) AddEvent

func (m *Manager) AddEvent(id string, event Event) error

AddEvent adds an event to a session.

func (*Manager) Create

func (m *Manager) Create(workflowName string, inputs map[string]string) (*Session, error)

Create creates a new session.

func (*Manager) Get

func (m *Manager) Get(id string) (*Session, error)

Get retrieves a session by ID.

func (*Manager) Update

func (m *Manager) Update(sess *Session) error

Update saves changes to a session.

type Message

type Message struct {
	Role      string    `json:"role"` // user, assistant, tool
	Content   string    `json:"content"`
	Goal      string    `json:"goal"`
	Agent     string    `json:"agent,omitempty"`
	Timestamp time.Time `json:"timestamp"`
}

Message represents an LLM message (kept for backwards compatibility).

type Session

type Session struct {
	ID           string                 `json:"id"`
	WorkflowName string                 `json:"workflow_name"`
	Inputs       map[string]string      `json:"inputs"`
	State        map[string]interface{} `json:"state"`
	Outputs      map[string]string      `json:"outputs"`
	Status       string                 `json:"status"`
	Result       string                 `json:"result,omitempty"`
	Error        string                 `json:"error,omitempty"`
	Events       []Event                `json:"events"`
	CreatedAt    time.Time              `json:"created_at"`
	UpdatedAt    time.Time              `json:"updated_at"`
	// contains filtered or unexported fields
}

Session represents a workflow execution session.

func (*Session) AddEvent

func (s *Session) AddEvent(event Event) uint64

AddEvent adds a new event to the session with automatic sequencing.

func (*Session) CurrentSeqID

func (s *Session) CurrentSeqID() uint64

CurrentSeqID returns the current (last used) sequence ID without incrementing. Returns 0 if no events have been added yet.

func (*Session) StartCorrelation

func (s *Session) StartCorrelation() string

StartCorrelation generates a new correlation ID for linking related events.

type SessionManager

type SessionManager interface {
	Create(workflowName string) (*Session, error)
	Update(sess *Session) error
	Get(id string) (*Session, error)
}

SessionManager is the interface for session management operations.

func NewFileManager

func NewFileManager(dir string) SessionManager

NewFileManager creates a new file-based session manager.

type Store

type Store interface {
	Save(sess *Session) error
	Load(id string) (*Session, error)
}

Store is the interface for session persistence.

type TaintNode

type TaintNode struct {
	BlockID   string      `json:"block_id"`             // Block identifier (b0001, etc.)
	Trust     string      `json:"trust"`                // trusted, vetted, untrusted
	Source    string      `json:"source"`               // Where content came from
	EventSeq  uint64      `json:"event_seq,omitempty"`  // Event sequence when block was created
	Depth     int         `json:"depth,omitempty"`      // Depth in the taint tree (0 = root)
	TaintedBy []TaintNode `json:"tainted_by,omitempty"` // Parent blocks that influenced this block
}

TaintNode represents a node in the taint dependency tree. Each node describes a content block and its relationship to the security event.

type ToolCall

type ToolCall struct {
	ID        string                 `json:"id"`
	Name      string                 `json:"name"`
	Args      map[string]interface{} `json:"args"`
	Result    interface{}            `json:"result"`
	Error     string                 `json:"error,omitempty"`
	Duration  time.Duration          `json:"duration"`
	Goal      string                 `json:"goal"`
	Timestamp time.Time              `json:"timestamp"`
}

ToolCall represents a tool invocation (kept for backwards compatibility).

Jump to

Keyboard shortcuts

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