session

package
v1.40.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyCloudSyncChoice

func ApplyCloudSyncChoice(cfg *api.Config, line string) bool

ApplyCloudSyncChoice parses a raw answer line, updates cfg.CloudSync, and persists it. Extracted from PromptCloudSyncConsent so it can be unit-tested without touching stdin/stdout.

func CleanupOldSessions

func CleanupOldSessions() int

CleanupOldSessions removes expired sessions to prevent unbounded disk growth. Portable transcripts get a much longer grace period than legacy sessions, but they still expire: a lossless transcript is the largest thing this tool writes, and "retain forever" is not a bounded policy.

func CountTurns

func CountTurns(history []api.Message) int

CountTurns counts real user prompts. Tool results travel as user-role messages in the Anthropic wire format, and CLI backends contribute one entry per exposed tool call, so counting every user-role message reports a turn count several times the number of things the user actually typed.

func GenerateSessionID

func GenerateSessionID() string

GenerateSessionID creates a short random hex ID like Claude Code uses.

func IsValidSessionID

func IsValidSessionID(id string) bool

IsValidSessionID is the same validator used internally to gate filesystem access. Exported so callers (e.g. REPL /resume handlers) can validate user input *at the call site* and produce a clear error before LoadSession is reached. Validation is duplicated rather than relying on LoadSession's internal check so taint-tracking SAST tools see sanitization on the path from user input to LoadSession.

func MarshalRedacted

func MarshalRedacted(value any) ([]byte, error)

MarshalRedacted serializes portable content without mutating live history. Structured credential fields and recognized secrets in prose are removed.

func PromptCloudSyncConsent

func PromptCloudSyncConsent(cfg *api.Config, readLine func() (string, error)) bool

PromptCloudSyncConsent asks the user once whether they want sessions synced to the QualityMax cloud. The answer is persisted in cfg so the prompt never appears again. Returns true if the user opted in.

readLine must use the active readline instance (e.g. term.ReadConsent) so that it works correctly when readline already owns the terminal in raw mode.

func SanitizeSessionMessages

func SanitizeSessionMessages(messages []api.Message)

SanitizeSessionMessages fixes common corruption issues in saved sessions: - tool_use blocks missing Input field (causes Anthropic API 400 errors) - text blocks with extra Input field (causes "Extra inputs are not permitted") - tool_result blocks with nil Content

func SaveSession

func SaveSession(sessionID string, history []api.Message, projectID int, usage api.TokenUsage, model string, states ...api.ConversationState) error

SaveSession persists the current conversation to disk. Called after every message exchange for crash safety.

func StartQueueReader

func StartQueueReader(pq *PromptQueue, term *tui.Terminal, cancelFn func()) func() string

StartQueueReader starts a background goroutine that reads chars from stdin one at a time while the agent is processing. Each non-empty line (Enter-terminated) is pushed onto pq. If cancelFn is non-nil it is called when the user presses Enter, allowing the running agent to be interrupted so the queued prompt is processed next.

Display strategy: on the first printable keystroke, print a status line and an input prompt (" › "), then echo every subsequent character in real-time and handle backspace visually with \b \b. The spinner already pauses when userTyping is set, so spinner rewrites don't overwrite the input line. Concurrent streaming text may rarely interleave, but visible typing is far better UX than invisible.

The goroutine switches stdin to "half-raw" mode (ICANON+ECHO off, OPOST on) so we own echoing while leaving the agent's concurrent stdout stream intact. Returns a stop function that must be called before the next tui.ReadInput so stdin is never shared between two readers.

The stop function returns any partial line the user had typed but not yet Enter-terminated when the agent finished. If the agent's response races the user's typing (turn ends before Enter is pressed), the caller can recover the partial text rather than silently dropping it (QUA-577).

func SummaryFor

func SummaryFor(history []api.Message) string

sessionSummary builds a short human-readable summary from the conversation history to upload with cloud sessions. It takes the first user message as the topic and appends the turn count.

Types

type CloudSessionTracker

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

CloudSessionTracker manages the lifecycle of a cloud-tracked agent session. Zero value is ready to use — no initialisation needed.

func (*CloudSessionTracker) Complete

func (t *CloudSessionTracker) Complete(client *api.APIClient, totalTokens int, summary string, messages []api.Message)

Complete patches the cloud session as finished and uploads the full message history. No-op if Start was never called successfully (cloudID is empty) or client is nil.

func (*CloudSessionTracker) CompleteCurrent

func (t *CloudSessionTracker) CompleteCurrent(client *api.APIClient, totalTokens int, messages []api.Message)

CompleteCurrent finalizes the active cloud session using only the portion of the local history that belongs to its current project.

func (*CloudSessionTracker) Start

func (t *CloudSessionTracker) Start(client *api.APIClient, projectID int, model string)

Start opens a cloud session the first time it is called with a valid API client and non-zero project ID. Subsequent calls are no-ops (idempotent).

func (*CloudSessionTracker) StartWithHistory

func (t *CloudSessionTracker) StartWithHistory(
	client *api.APIClient, projectID int, model string, historyLength int, totalTokens int,
)

StartWithHistory opens a cloud session and records the point in the local conversation at which it began. This lets a single local REPL conversation move between projects without copying the earlier project's messages into the next cloud session.

func (*CloudSessionTracker) SwitchProject

func (t *CloudSessionTracker) SwitchProject(
	client *api.APIClient, projectID int, model string, totalTokens int, messages []api.Message,
) bool

SwitchProject finalizes the current cloud session and starts another one for projectID. Local history remains intact, but only messages entered after the switch belong to the new cloud session. It returns true when a tracked session was actually moved to a different project.

type PromptQueue

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

PromptQueue is a thread-safe FIFO for prompts submitted while the agent is already processing a previous request.

func (*PromptQueue) Clear

func (q *PromptQueue) Clear() int

Clear empties the queue and returns the number of items that were removed.

func (*PromptQueue) Len

func (q *PromptQueue) Len() int

func (*PromptQueue) Peek

func (q *PromptQueue) Peek() []string

func (*PromptQueue) Pop

func (q *PromptQueue) Pop() (string, bool)

func (*PromptQueue) Push

func (q *PromptQueue) Push(s string)

type Session

type Session struct {
	ID           string                `json:"id"`
	Conversation api.ConversationState `json:"conversation,omitempty"`
	CreatedAt    time.Time             `json:"created_at"`
	UpdatedAt    time.Time             `json:"updated_at"`
	ProjectID    int                   `json:"project_id,omitempty"`
	Model        string                `json:"model,omitempty"`
	Messages     []api.Message         `json:"messages"`
	Usage        api.TokenUsage        `json:"usage"`
	Turns        int                   `json:"turns"`
}

Session represents a saved conversation session.

func LoadLastSession

func LoadLastSession() (*Session, error)

LoadLastSession loads the most recently updated session.

func LoadSession

func LoadSession(id string) (*Session, error)

LoadSession loads a specific session by ID.

type SessionSummary

type SessionSummary struct {
	ID        string
	UpdatedAt time.Time
	Turns     int
	Tokens    int
	ProjectID int
	Model     string
}

SessionSummary is a lightweight session descriptor for listing.

func ListSessions

func ListSessions(limit int) ([]SessionSummary, error)

ListSessions returns recent sessions sorted by update time (newest first).

Jump to

Keyboard shortcuts

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