session

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 51 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

Overview

Package session manages user-facing chat threads, session metadata, persistent per-session file change journals, per-session tool containers and permission gates, and the chronological session timeline stored in SQLite, resolving workspace agents, system prompts, and language models per session and executing conversational turns through github.com/masterkeysrd/tasksmith/internal/daemon/harness.Harness.

Strict Dependency Injection

As an internal application subsystem, New requires required runtime dependencies on Config to be explicitly provided:

Separation of Session Timeline and Graph Checkpoints

TaskSmith maintains a strict separation between two persistence layers:

  1. The `timeline` table managed by github.com/masterkeysrd/tasksmith/internal/daemon/timeline.Store records the complete, append-only chronological log of session events (sorted chronologically by UUIDv7 `id ASC` via Session.Timeline), including user turns, intermediate tool-calling assistant messages, tool execution results, final assistant replies, model/agent transitions, permission mode updates, and permission decisions. github.com/masterkeysrd/tasksmith/internal/daemon/timeline.Timeline.Messages queries the message subset of the timeline for UI transcript callers.
  2. The `checkpoints` table managed by github.com/masterkeysrd/tasksmith/internal/daemon/harness.Harness stores the Loom workflow graph execution state sent to the LLM.

Appending an entry internally (for example, a UI-only system notice or mode change) records the entry in the session timeline and publishes an [EventEntryAdded] event without mutating or polluting the underlying harness graph checkpoint for that session.

All-or-Nothing Permission Resolution

When a turn pauses at `ToolsNode` awaiting user approval for one or more tool calls, Session.Send publishes [EventPermissionRequested] and returns `(nil, nil)`. Callers inspect unresolved permissions via [Session.PendingPermissions] and submit individual decisions via [Session.RespondPermission]. Partial decisions are buffered in memory per session without invoking the workflow graph until every pending permission for the turn has been resolved, at which point [Session.RespondPermission] resumes the harness graph with the complete decision set. Calling Session.Send with a new user message while permissions are pending discards any buffered partial decisions and cancels the pending tool calls in chronological order.

Persistent Per-Session Journal

Session.Journal returns a persistent github.com/masterkeysrd/tasksmith/internal/daemon/journal.Journal implementing github.com/masterkeysrd/tasksmith/internal/daemon/std.FileTracker with SQLite metadata paired with content-addressable snapshots in `<sessionDir>/blobs/<sha256>`. This enables on-demand unified diff generation (github.com/masterkeysrd/tasksmith/internal/daemon/journal.Journal.DiffEntry), point-in-time recovery (github.com/masterkeysrd/tasksmith/internal/daemon/journal.Journal.RecoverAt), and conflict-aware 3-way baseline reversion (github.com/masterkeysrd/tasksmith/internal/daemon/journal.Journal.RevertToBaseline).

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidConfig        = errors.New("session: invalid configuration")
	ErrSessionNotFound      = errors.New("session: session not found")
	ErrEmptySessionID       = errors.New("session: session ID must not be empty")
	ErrNilMessage           = errors.New("session: message must not be nil")
	ErrJournalNotFound      = journal.ErrNotFound
	ErrEntryNotFound        = journal.ErrEntryNotFound
	ErrBlobNotFound         = journal.ErrBlobNotFound
	ErrRevertConflict       = journal.ErrRevertConflict
	ErrNoPendingPermissions = errors.New("session: no pending permissions")
	ErrPermissionNotFound   = errors.New("session: permission request not found")
	ErrInvalidDecision      = errors.New("session: invalid permission decision")
	ErrNoPendingQuestions   = errors.New("session: no pending questions")
	ErrQuestionNotFound     = errors.New("session: question request not found")
	ErrInvalidQuestion      = errors.New("session: invalid question response")
	ErrNoPendingPlanReviews = errors.New("session: no pending plan reviews")
	ErrPlanReviewNotFound   = errors.New("session: plan review request not found")
	ErrInvalidPlanReview    = errors.New("session: invalid plan review decision")
	ErrInvalidSessionID     = errors.New("session: session ID must be a canonical lowercase UUIDv7")
	ErrSessionConflict      = errors.New("session: session already exists with different parameters")
	ErrSessionRunning       = errors.New("session: session already has an active turn")
	ErrEmptyMessage         = errors.New("session: message content must not be empty")
	ErrUnknownCommand       = errors.New("session: unknown slash command")
	ErrCapabilityMismatch   = errors.New("session: model lacks required session capabilities")
)

Sentinel errors returned by the session package.

Functions

func FromAPIBlock

func FromAPIBlock(b api.Block) (message.Block, bool)

FromAPIBlock converts a single api.Block into an internal message.Block. The boolean reports whether the block was successfully converted.

func Migrate

func Migrate(ctx context.Context, db *sql.DB) error

Migrate executes SQLite migrations for the session schema.

func Preview

Preview computes the resolved session configuration, model details, and diagnostics for a proposed session configuration without creating a session.

func SessionDir

func SessionDir(workspaceRoot, sessionID string) (string, error)

SessionDir returns the session data directory for the given workspace root and session ID.

func ToAPIBlock

func ToAPIBlock(b message.Block) (api.Block, bool)

ToAPIBlock converts a single internal message.Block into the public api.Block representation. The boolean reports whether the block type is supported by the public API.

func ToAPIMessage

func ToAPIMessage(msg message.Message) (*api.Message, error)

ToAPIMessage converts an internal message.Message into the public api.Message representation. It returns an error when a structured tool payload cannot be serialized.

func ToAPIQuestionResponse

func ToAPIQuestionResponse(r api.QuestionResponse, questions []api.Question) api.QuestionResponse

ToAPIQuestionResponse converts an internal api.QuestionResponse into the public api.QuestionResponse representation, attaching confirmation flags for confirm-typed questions.

func ToAPISession

func ToAPISession(sess *Session) api.Session

ToAPISession converts an internal Session into the public api.Session representation used for HTTP responses and published events.

func ToAPITimelineEntry

func ToAPITimelineEntry(entry timeline.Entry) (api.TimelineEntry, error)

ToAPITimelineEntry converts an internal timeline.Entry into the public api.TimelineEntry representation used by the API.

Types

type CapabilityMismatchError

type CapabilityMismatchError struct {
	Model             string
	MissingModalities []string
}

CapabilityMismatchError reports which active-context modalities would be dropped by switching a session to Model without Force.

func (*CapabilityMismatchError) Error

func (e *CapabilityMismatchError) Error() string

func (*CapabilityMismatchError) Unwrap

func (e *CapabilityMismatchError) Unwrap() error

type Config

type Config struct {
	ID       string
	Title    string
	ParentID string
	WorkDir  string
	Parent   *Session
	// CommandDelegated marks a child session spawned for a user-invoked
	// delegated slash command rather than an autonomous invoke_agent subagent.
	CommandDelegated bool
	Session          api.SessionConfig
	// InitialPermissions optionally seeds a new session's session-scoped
	// permission grants. It is used when forking so the branch keeps the
	// approvals the source session already earned.
	InitialPermissions api.Permissions
	DB                 *sql.DB
	Workspace          *workspace.Workspace
	Gateway            func() gateway.Gateway
	Catalog            func() *models.Catalog
	Permissions        permissions.Manager
	// SandboxSettings optionally carries the workspace's sandbox.json manager
	// (nil keeps the built-in defaults: DefaultMode backend and the built-in
	// policy floor only). It supplies the effective default backend, the
	// failIfUnavailable lock, and user path overrides layered over the
	// built-in security floor.
	SandboxSettings sandboxcfg.Manager
	Publisher       Publisher
	Logger          log.Interface
	Metrics         metrics.Service
	ReloadLock      *sync.RWMutex
	Context         context.Context
	WaitGroup       *sync.WaitGroup
	OnUpdate        func(ctx context.Context, s *Session) error
	// MCPCaller resolves the MCP runtime for this session's workspace, or nil when
	// no MCP manager is attached. It is a function rather than a value because a
	// workspace reload replaces the runtime's context while sessions stay alive, so
	// each rebuild of the session's tool container must resolve the current one.
	MCPCaller func() tools.MCPCaller
}

Config holds runtime dependencies and parameters for initializing a Session.

func (Config) Validate

func (c Config) Validate() error

Validate checks that all required configuration dependencies are non-nil.

type LatestFilter

type LatestFilter struct {
	// WorkDir restricts matching to top-level sessions with this WorkDir when
	// non-empty.
	WorkDir string
	// IncludeEmptyWorkDir also matches legacy top-level sessions whose WorkDir
	// is empty (used when querying from the workspace root).
	IncludeEmptyWorkDir bool
}

LatestFilter specifies optional scoping for Store.Latest.

type ListFilter

type ListFilter struct {
	ParentID *string
}

ListFilter specifies filtering criteria for listing sessions.

type Publisher

type Publisher interface {
	Publish(topic string, event broker.Event)
	DeleteTopic(topic string)
}

Publisher broadcasts real-time session events to a topic.

type Session

type Session struct {
	// We embed [State] here so that Session supports state fields and locking
	// directly, but marshal it as a struct in JSON.
	//
	// State also provides a [sync.Mutex] which is used as lock for both
	// the Session and State.
	*State `json:"state"`

	ID          string                  `json:"id"`
	Title       string                  `json:"title"`
	Config      api.SessionConfig       `json:"config"`
	Diagnostics []api.SessionDiagnostic `json:"diagnostics,omitempty"`
	ParentID    string                  `json:"parent_id,omitempty"`
	// ForkedFrom records the session ID this thread was forked from. It is
	// provenance only: unlike ParentID it does not attach the fork to the
	// parent/child delegation tree, so forks stay top-level human threads.
	ForkedFrom string    `json:"forked_from,omitempty"`
	WorkDir    string    `json:"work_dir,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`

	Permissions api.Permissions            `json:"-"`
	PermManager permissions.SessionManager `json:"-"`

	Root    string          `json:"-"` // Path to <WorkspaceDir>/sessions/<id>
	Sandbox sandbox.Sandbox `json:"-"`

	Timeline  timeline.Timeline `json:"-"`
	Journal   journal.Journal   `json:"-"`
	Tools     tools.Container   `json:"-"`
	Tasks     tasks.Store       `json:"-"`
	Harness   harness.Harness   `json:"-"`
	Std       *std.Std          `json:"-"`
	FileIndex *std.FileIndex    `json:"-"`
	// contains filtered or unexported fields
}

Session represents a persistent user-facing chat thread and its runtime state.

func New

func New(ctx context.Context, cfg Config) (*Session, error)

New constructs and initializes a new Session.

func Open

func Open(ctx context.Context, dbSess *Session, cfg Config) (*Session, error)

Open restores and initializes an existing Session from persisted state.

func (*Session) AddChild

func (s *Session) AddChild(child *Session)

AddChild registers or updates a child session on this parent session.

func (*Session) Cancel

func (s *Session) Cancel(ctx context.Context) error

Cancel interrupts any active conversational turn executing on this session (and any user-invoked delegated slash-command child), leaving autonomous invoke_agent background subagents and background tasks running.

func (*Session) CheckpointTo

func (s *Session) CheckpointTo(ctx context.Context, store Store) error

CheckpointTo persists a snapshot of the session to store.

func (*Session) Child

func (s *Session) Child(id string) (*Session, bool)

Child looks up a child session by ID.

func (*Session) Children

func (s *Session) Children() []*Session

Children returns a cloned list of the child sessions registered with this session.

func (*Session) Clone

func (s *Session) Clone() *Session

Clone returns a deep copy of the session and its exported execution state, synchronizing on the session's embedded mutex.

func (*Session) Close

func (s *Session) Close() error

Close closes session-scoped runtime resources like the Sandbox.

func (*Session) CurrentMode

func (s *Session) CurrentMode() api.PermissionMode

CurrentMode returns the session's active permission mode.

func (*Session) Enqueue

func (s *Session) Enqueue(msg message.Message)

Enqueue adds a message to the session's execution queue or initiates an immediate turn if idle.

func (*Session) EnterPlanMode

func (s *Session) EnterPlanMode(ctx context.Context) (bool, string, error)

EnterPlanMode transitions the session into plan mode, emitting a timeline mode entry and session update if the mode changed.

func (*Session) ExitPlanMode

func (s *Session) ExitPlanMode(ctx context.Context, _ string, nextMode api.PermissionMode) (api.PermissionMode, error)

ExitPlanMode transitions the session out of plan mode into nextMode after user approval of a plan document.

func (*Session) Fork

func (s *Session) Fork(ctx context.Context, title string) (*Session, error)

Fork creates a new top-level session branching this session's conversation. The fork receives the parent's latest harness checkpoint (all state channels), a copy of the parent's timeline, and the same session config and sandbox backend. Pending permissions, pending questions, subagents, background tasks, queued input, and the file-change journal are deliberately not carried over: the fork is an independent branch that never mutates the parent, and file rollback stays owned by the thread that made the changes.

Forking requires an idle session: a mid-turn or waiting checkpoint could leave the fork's conversation ending on an unanswered tool call.

func (*Session) GetFileIndex

func (s *Session) GetFileIndex() (*std.FileIndex, error)

GetFileIndex returns the session's FileIndex, creating it lazily if needed.

func (*Session) HasItems

func (s *Session) HasItems() bool

HasItems reports whether the execution queue has pending items.

func (*Session) HasLeadingCommand

func (s *Session) HasLeadingCommand() bool

HasLeadingCommand reports whether the next pending item in the queue is a command.

func (*Session) InvokeSubagent

func (s *Session) InvokeSubagent(ctx context.Context, in api.InvokeAgentInput) (api.InvokeAgentOutput, error)

InvokeSubagent spawns a child subagent asynchronously in an isolated child session.

func (*Session) IsClosing

func (s *Session) IsClosing() bool

IsClosing reports whether Close has been called on the session.

func (*Session) IsCommandDelegated

func (s *Session) IsCommandDelegated() bool

IsCommandDelegated reports whether this child session was spawned for a user-invoked delegated slash command rather than invoke_agent.

func (*Session) ManageSubagents

func (s *Session) ManageSubagents(ctx context.Context, in api.ManageAgentsInput) (api.ManageAgentsOutput, error)

ManageSubagents handles management operations (list, status, send, kill, models) on child subagent sessions and model discovery.

func (*Session) Matches

func (s *Session) Matches(req api.CreateSessionRequest) error

Matches returns nil if the session matches the parameters of req, or ErrSessionConflict if any parameter conflicts.

func (*Session) Parent

func (s *Session) Parent() *Session

Parent returns the parent session if this session is a delegated child.

func (*Session) PlansDir

func (s *Session) PlansDir() string

PlansDir returns the session-scoped safe plans directory (<session-dir>/plans).

func (*Session) PopCommand

func (s *Session) PopCommand() (id, command string, ok bool)

PopCommand pops and returns the leading command item if present.

func (*Session) PopMessages

func (s *Session) PopMessages() []message.Message

PopMessages pops and returns all leading messages up to the next command item.

func (*Session) Refresh

func (s *Session) Refresh(ctx context.Context)

Refresh recalculates session diagnostics and reconfigures the harness (e.g. after a workspace reload), publishing a SessionUpdatedEvent.

func (*Session) RemoveChild

func (s *Session) RemoveChild(id string)

RemoveChild unregisters a child session by ID from this session.

func (*Session) ResolvedModel

func (s *Session) ResolvedModel() (models.Model, *api.ThinkingSetting, bool)

func (*Session) Send

func (s *Session) Send(ctx context.Context, req api.SendRequest) error

Send initiates an asynchronous conversational turn with a user message or resolves a pending permission decision.

func (*Session) SetParent

func (s *Session) SetParent(parent *Session)

SetParent associates this session with a parent session.

func (*Session) Update

func (s *Session) Update(ctx context.Context, req api.UpdateSessionRequest) error

Update updates the session title or configuration, persisting changes and reconfiguring runtime harnesses.

func (*Session) UploadMedia

func (s *Session) UploadMedia(ctx context.Context, mimeType, filename string, data []byte) (*api.Media, error)

UploadMedia validates and stores raw media bytes into <session-dir>/media/<sha256> and returns the lightweight descriptor for subsequent Send requests.

func (*Session) VisibleQueue

func (s *Session) VisibleQueue() []api.QueueItem

func (*Session) Wait

func (s *Session) Wait(ctx context.Context) error

Wait blocks until an in-flight background turn completes or ctx cancels.

func (*Session) Workspace

func (s *Session) Workspace() *workspace.Workspace

Workspace returns the workspace configuration snapshot bound to this session.

type State

type State struct {
	sync.Mutex `json:"-"`

	Status             api.SessionStatus       `json:"status"`
	Running            bool                    `json:"running"`
	PendingPermissions []api.PermissionRequest `json:"pending_permissions,omitempty"`
	PendingQuestions   []api.QuestionRequest   `json:"pending_questions,omitempty"`
	PendingPlanReviews []api.PlanReviewRequest `json:"pending_plan_reviews,omitempty"`
	Tasks              []api.Task              `json:"tasks,omitempty"`
	Todos              []api.TodoItem          `json:"todos,omitempty"`
	Context            api.ContextState        `json:"context"`
	Error              string                  `json:"error,omitempty"`
	Activity           string                  `json:"activity,omitempty"`
	StartedAt          time.Time               `json:"started_at,omitzero"`
	FinishedAt         time.Time               `json:"finished_at,omitzero"`
	// contains filtered or unexported fields
}

State stores a session's live execution state and provides the sync.Mutex used to synchronize access to both Session and State.

func NewState

func NewState() *State

NewState constructs a new State initialized to api.StatusIdle.

func (*State) Clone

func (s *State) Clone() *State

Clone returns a copy of the exported state fields with [Status] defaulted to api.StatusIdle if empty. Caller must hold the state lock if s is shared.

type Store

type Store interface {
	Save(ctx context.Context, sess *Session) error
	Get(ctx context.Context, id string) (*Session, error)
	List(ctx context.Context, filter ListFilter) ([]*Session, error)
	// Latest returns the most recently updated top-level (non-subagent)
	// session matching filter, or ErrSessionNotFound when none exists.
	Latest(ctx context.Context, filter LatestFilter) (*Session, error)
	Delete(ctx context.Context, id string) error
}

Store persists session metadata in SQLite.

func NewStore

func NewStore(ctx context.Context, db *sql.DB) (Store, error)

NewStore initializes a SQLite-backed Store and runs schema migrations.

Jump to

Keyboard shortcuts

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