session

package
v0.31.27 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultKeepRecentMessages = 20
	MinKeepRecentMessages     = 5
	MaxKeepRecentMessages     = 200
	DefaultKeepRecentTokens   = 12000
	MinKeepRecentTokens       = 1
	MaxKeepRecentTokens       = 64000
	DefaultKeepRecentFraction = 0.30
	MinKeepRecentFraction     = 0.05
	MaxKeepRecentFraction     = 0.90
)
View Source
const (
	PlanStatusDrafting  = "drafting"
	PlanStatusProposed  = "proposed"
	PlanStatusExecuting = "executing"
	PlanStatusPaused    = "paused"
	PlanStatusCompleted = "completed"
	PlanStatusAborted   = "aborted"
)

Plan status constants — enumerate the states a plan can be in.

View Source
const (
	// TasksInjectionHeader marks task state that was deliberately reinserted
	// after context compression so later compactions can replace stale copies.
	TasksInjectionHeader = "## Active Plan (preserved across compression)"
)

Variables

This section is empty.

Functions

func AppendMessage

func AppendMessage(path string, msg Message) error

AppendMessage appends a single message as one JSON line to the JSONL file at path.

func ArchiveSummary added in v0.20.0

func ArchiveSummary(st SessionTasks) string

ArchiveSummary returns a human-readable summary of the plan and tasks for memory archival.

func BuildCompactionSummary

func BuildCompactionSummary(messages []Message) string

func BuildCompactionSummaryWithOptions added in v0.10.2

func BuildCompactionSummaryWithOptions(messages []Message, opts CompactionSummaryOptions) string

func EstimateMessageTokenCost added in v0.27.0

func EstimateMessageTokenCost(msg Message) int

EstimateMessageTokenCost is the exported wrapper for single-message token estimation.

func EstimateTokens

func EstimateTokens(messages []Message) int

func FormatTasksForInjection added in v0.20.0

func FormatTasksForInjection(st SessionTasks) string

FormatTasksForInjection renders active tasks for system prompt injection after context compression. Only includes pending and in_progress tasks.

func IsTasksInjectionMessage added in v0.31.16

func IsTasksInjectionMessage(msg Message) bool

IsTasksInjectionMessage reports whether msg is a previously injected active plan block. Compaction replaces these blocks with fresh task state.

func NextTaskID added in v0.20.0

func NextTaskID(tasks []Task) string

NextTaskID returns the next sequential task ID based on existing tasks.

func NowRFC3339 added in v0.20.0

func NowRFC3339() string

NowRFC3339 returns current time in RFC3339 format.

func RewriteMessages

func RewriteMessages(path string, messages []Message) error

RewriteMessages replaces the transcript contents with the provided messages.

func TaskSummary added in v0.20.0

func TaskSummary(tasks []Task) map[string]int

TaskSummary returns a compact summary of task statuses.

func ValidPlanStatus added in v0.31.10

func ValidPlanStatus(s string) bool

ValidPlanStatus reports whether s is a recognized plan status.

func ValidTaskStatus added in v0.20.0

func ValidTaskStatus(status string) bool

ValidTaskStatus checks if a status string is valid.

Types

type CompactOptions

type CompactOptions struct {
	BeforeRewrite       func(summary string, compactedCount int, originalCount int) error
	SummaryBuilder      func(messages []Message, previousContext string) (string, error)
	PostSummaryMessages []Message
	KeepRecentTokens    int
	KeepRecentFraction  float64
	SummaryInstructions string
	// PreloadedMessages supplies already-read messages to avoid a second ReadMessages
	// call on the same path. When set, ReadMessages is skipped, preventing a
	// reentrant-lock deadlock when the caller already holds the path lock.
	PreloadedMessages []Message
}

CompactOptions configures CompactTranscriptWithOptions.

KeepRecent strategies are tried in priority order — the first non-zero option wins, lower options are ignored:

  1. KeepRecentFraction (if > 0): retain the most recent X% of total transcript tokens (clamped to MinKeepRecentFraction..MaxKeepRecentFraction).
  2. KeepRecentTokens (if > 0): retain a specific token budget (clamped to MinKeepRecentTokens..MaxKeepRecentTokens).
  3. keepRecent positional argument: retain a specific message count (clamped to MinKeepRecentMessages..MaxKeepRecentMessages, default DefaultKeepRecentMessages = 20).

Setting both KeepRecentFraction and KeepRecentTokens is supported but the fraction wins — set only the strategy you want.

type CompactResult

type CompactResult struct {
	Compacted      bool
	OriginalCount  int
	FinalCount     int
	CompactedCount int
	Summary        string
}

func CompactTranscript

func CompactTranscript(path string, keepRecent int, now time.Time) (CompactResult, error)

func CompactTranscriptWithOptions

func CompactTranscriptWithOptions(path string, keepRecent int, now time.Time, opts CompactOptions) (CompactResult, error)

type CompactionSummaryOptions added in v0.10.2

type CompactionSummaryOptions struct {
	FocusInstructions string
	PreviousContext   string
}

type HistorySnapshot

type HistorySnapshot struct {
	Messages       []Message
	Tokens         int
	CompactionUsed bool
}

HistorySnapshot captures the portion of transcript loaded into model context.

func LoadHistorySnapshot

func LoadHistorySnapshot(path string, maxTokens int) (HistorySnapshot, error)

LoadHistorySnapshot reads transcript history and returns the loaded messages together with token and compaction-boundary metadata.

type Message

type Message struct {
	Role       string    `json:"role"`
	Content    string    `json:"content"`
	Timestamp  time.Time `json:"timestamp"`
	ToolName   string    `json:"tool_name,omitempty"`
	ToolCallID string    `json:"tool_call_id,omitempty"`
	ToolArgs   string    `json:"tool_args,omitempty"`
}

Message represents a single chat message in a session transcript. Tool fields are optional (omitempty) for backward compatibility with existing transcripts.

func LoadHistory

func LoadHistory(path string, maxTokens int) ([]Message, error)

LoadHistory reads messages from a JSONL file, returning only the most recent messages that fit within the given token budget. Tokens are estimated as len(content)/4. Messages are returned in chronological order (oldest first). Returns an empty slice if the file does not exist.

func ReadMessages

func ReadMessages(path string) ([]Message, error)

ReadMessages reads all messages from a JSONL file. Returns an empty slice if the file does not exist or is empty.

type Plan added in v0.20.0

type Plan struct {
	Goal        string `json:"goal"`
	Constraints string `json:"constraints,omitempty"`
	CreatedAt   string `json:"created_at"`
	Status      string `json:"status,omitempty"`
	UpdatedAt   string `json:"updated_at,omitempty"`
}

Plan represents a high-level goal for the current session. At most one plan is active per session; setting a new plan archives the previous one.

Status follows a small state machine:

drafting ──plan_propose──► proposed ──plan_approve──► executing
   ▲                                                     │
   │                                                     │ plan_pause
   │                                                     ▼
   │                                                  paused
   │                                                     │
   │ user edit                       plan_resume         │
   └────────────────────                 ◄───────────────┘

executing ─(all tasks completed/cancelled)──► completed
any (except completed/aborted) ──plan_abort──► aborted

Empty Status (legacy plans saved before this field existed) is treated as "executing" on load so existing sessions keep their prior behavior.

type Session

type Session struct {
	ID                 string             `json:"id"`
	Title              string             `json:"title"`
	Kind               string             `json:"kind,omitempty"`
	Hidden             bool               `json:"hidden,omitempty"`
	ToolConfig         *SessionToolConfig `json:"tool_config,omitempty"`
	LastCompactionMode string             `json:"last_compaction_mode,omitempty"`
	PromptOverride     string             `json:"prompt_override,omitempty"`
	WorkDirs           []string           `json:"work_dirs,omitempty"`
	CurrentDir         string             `json:"current_dir,omitempty"`
	CreatedAt          time.Time          `json:"created_at"`
	UpdatedAt          time.Time          `json:"updated_at"`
}

type SessionTasks added in v0.20.0

type SessionTasks struct {
	Plan  *Plan  `json:"plan,omitempty"`
	Tasks []Task `json:"tasks"`
}

SessionTasks holds the current plan and its associated tasks for a session.

func (SessionTasks) MarshalJSON added in v0.23.0

func (st SessionTasks) MarshalJSON() ([]byte, error)

MarshalJSON keeps the API contract stable by always emitting tasks as an array.

type SessionToolConfig added in v0.16.0

type SessionToolConfig struct {
	ToolsEnabled     []string `json:"tools_enabled,omitempty"`
	ToolsCustom      bool     `json:"tools_custom,omitempty"`
	ToolsDisabled    []string `json:"tools_disabled,omitempty"`
	ToolsAllowGroups []string `json:"tools_allow_groups,omitempty"`
	ToolsDenyGroups  []string `json:"tools_deny_groups,omitempty"`
	SkillsEnabled    []string `json:"skills_enabled,omitempty"`
	SkillsCustom     bool     `json:"skills_custom,omitempty"`
	MCPEnabled       []string `json:"mcp_enabled,omitempty"`
}

SessionToolConfig holds per-session tool/skill/MCP configuration. nil slices mean "inherit all from system defaults".

type Store

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

func NewStore

func NewStore(dir string) *Store

func (*Store) Create

func (s *Store) Create(title string) (Session, error)

func (*Store) CreateWithOptions

func (s *Store) CreateWithOptions(title string, kind string, hidden bool) (Session, error)

func (*Store) Delete

func (s *Store) Delete(id string) error

func (*Store) EnsureMain

func (s *Store) EnsureMain() (Session, error)

func (*Store) EnsureWorker

func (s *Store) EnsureWorker(projectID string) (Session, error)

func (*Store) Get

func (s *Store) Get(id string) (Session, error)

func (*Store) GetTasks added in v0.20.0

func (s *Store) GetTasks(sessionID string) (SessionTasks, error)

GetTasks reads the tasks file for a session. Returns empty SessionTasks if not found.

func (*Store) Latest

func (s *Store) Latest() (Session, error)

func (*Store) LatestAll

func (s *Store) LatestAll() (Session, error)

func (*Store) List

func (s *Store) List() ([]Session, error)

func (*Store) ListAll

func (s *Store) ListAll() ([]Session, error)

func (*Store) SaveTasks added in v0.20.0

func (s *Store) SaveTasks(sessionID string, tasks SessionTasks) error

SaveTasks writes the tasks file for a session.

func (*Store) SetCurrentDir added in v0.22.0

func (s *Store) SetCurrentDir(id string, dir string) error

SetCurrentDir updates only the current working directory for a session.

func (*Store) SetLastCompactionMode added in v0.25.0

func (s *Store) SetLastCompactionMode(id string, mode string) error

func (*Store) SetPromptOverride added in v0.16.0

func (s *Store) SetPromptOverride(id string, override string) error

SetPromptOverride updates the per-session prompt override.

func (*Store) SetTitle added in v0.15.0

func (s *Store) SetTitle(id string, title string) error

SetTitle renames a session.

func (*Store) SetToolConfig added in v0.16.0

func (s *Store) SetToolConfig(id string, config *SessionToolConfig) error

SetToolConfig updates the per-session tool configuration.

func (*Store) SetWorkDirs added in v0.22.0

func (s *Store) SetWorkDirs(id string, dirs []string, currentDir string) error

SetWorkDirs updates the per-session working directories and current directory.

func (*Store) Touch

func (s *Store) Touch(id string, updatedAt time.Time) error

func (*Store) TranscriptPath

func (s *Store) TranscriptPath(id string) string

func (*Store) WorkspaceDir

func (s *Store) WorkspaceDir() string

type Task added in v0.20.0

type Task struct {
	ID          string `json:"id"`
	Title       string `json:"title"`
	Status      string `json:"status"` // pending, in_progress, completed, cancelled
	Description string `json:"description,omitempty"`
}

Task represents a single work item linked to the session plan.

Jump to

Keyboard shortcuts

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