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:
- Config.DB: Active SQLite connection used for storing the `sessions` table, `timeline` entries, and harness checkpoints.
- Config.Workspace: Active github.com/masterkeysrd/tasksmith/internal/daemon/workspace.Workspace used to resolve session agents, default completion models, tool policies, and dynamic system prompts.
- Config.Gateway: Active github.com/masterkeysrd/tasksmith/internal/daemon/gateway.Gateway getter used to resolve concrete github.com/masterkeysrd/loom/llm.Model instances.
- Config.Publisher: Active Publisher used to broadcast real-time [EventEntryAdded], [EventChunk], [EventPermissionRequested], and [EventCompleted] notifications.
- Config.Logger: Structured github.com/masterkeysrd/tasksmith/internal/core/log.Interface scoped to the "session" component.
- Config.Permissions: Active github.com/masterkeysrd/tasksmith/internal/daemon/permissions.Manager used for per-session permission gates.
Separation of Session Timeline and Graph Checkpoints ¶
TaskSmith maintains a strict separation between two persistence layers:
- 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.
- 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 ¶
- Variables
- func FromAPIBlock(b api.Block) (message.Block, bool)
- func Migrate(ctx context.Context, db *sql.DB) error
- func Preview(ctx context.Context, ws *workspace.Workspace, catalog *models.Catalog, ...) (api.SessionConfig, models.Model, []api.SessionDiagnostic, bool, error)
- func SessionDir(workspaceRoot, sessionID string) (string, error)
- func ToAPIBlock(b message.Block) (api.Block, bool)
- func ToAPIMessage(msg message.Message) (*api.Message, error)
- func ToAPIQuestionResponse(r api.QuestionResponse, questions []api.Question) api.QuestionResponse
- func ToAPISession(sess *Session) api.Session
- func ToAPITimelineEntry(entry timeline.Entry) (api.TimelineEntry, error)
- type CapabilityMismatchError
- type Config
- type LatestFilter
- type ListFilter
- type Publisher
- type Session
- func (s *Session) AddChild(child *Session)
- func (s *Session) Cancel(ctx context.Context) error
- func (s *Session) CheckpointTo(ctx context.Context, store Store) error
- func (s *Session) Child(id string) (*Session, bool)
- func (s *Session) Children() []*Session
- func (s *Session) Clone() *Session
- func (s *Session) Close() error
- func (s *Session) CurrentMode() api.PermissionMode
- func (s *Session) Enqueue(msg message.Message)
- func (s *Session) EnterPlanMode(ctx context.Context) (bool, string, error)
- func (s *Session) ExitPlanMode(ctx context.Context, _ string, nextMode api.PermissionMode) (api.PermissionMode, error)
- func (s *Session) Fork(ctx context.Context, title string) (*Session, error)
- func (s *Session) GetFileIndex() (*std.FileIndex, error)
- func (s *Session) HasItems() bool
- func (s *Session) HasLeadingCommand() bool
- func (s *Session) InvokeSubagent(ctx context.Context, in api.InvokeAgentInput) (api.InvokeAgentOutput, error)
- func (s *Session) IsClosing() bool
- func (s *Session) IsCommandDelegated() bool
- func (s *Session) ManageSubagents(ctx context.Context, in api.ManageAgentsInput) (api.ManageAgentsOutput, error)
- func (s *Session) Matches(req api.CreateSessionRequest) error
- func (s *Session) Parent() *Session
- func (s *Session) PlansDir() string
- func (s *Session) PopCommand() (id, command string, ok bool)
- func (s *Session) PopMessages() []message.Message
- func (s *Session) Refresh(ctx context.Context)
- func (s *Session) RemoveChild(id string)
- func (s *Session) ResolvedModel() (models.Model, *api.ThinkingSetting, bool)
- func (s *Session) Send(ctx context.Context, req api.SendRequest) error
- func (s *Session) SetParent(parent *Session)
- func (s *Session) Update(ctx context.Context, req api.UpdateSessionRequest) error
- func (s *Session) UploadMedia(ctx context.Context, mimeType, filename string, data []byte) (*api.Media, error)
- func (s *Session) VisibleQueue() []api.QueueItem
- func (s *Session) Wait(ctx context.Context) error
- func (s *Session) Workspace() *workspace.Workspace
- type State
- type Store
Constants ¶
This section is empty.
Variables ¶
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 ¶
FromAPIBlock converts a single api.Block into an internal message.Block. The boolean reports whether the block was successfully converted.
func Preview ¶
func Preview(ctx context.Context, ws *workspace.Workspace, catalog *models.Catalog, config api.SessionConfig) (api.SessionConfig, models.Model, []api.SessionDiagnostic, bool, error)
Preview computes the resolved session configuration, model details, and diagnostics for a proposed session configuration without creating a session.
func SessionDir ¶
SessionDir returns the session data directory for the given workspace root and session ID.
func ToAPIBlock ¶
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 ¶
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 ¶
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 ¶
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.
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 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 (*Session) Cancel ¶
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 ¶
CheckpointTo persists a snapshot of the session to store.
func (*Session) Children ¶
Children returns a cloned list of the child sessions registered with this session.
func (*Session) Clone ¶
Clone returns a deep copy of the session and its exported execution state, synchronizing on the session's embedded mutex.
func (*Session) CurrentMode ¶
func (s *Session) CurrentMode() api.PermissionMode
CurrentMode returns the session's active permission mode.
func (*Session) Enqueue ¶
Enqueue adds a message to the session's execution queue or initiates an immediate turn if idle.
func (*Session) EnterPlanMode ¶
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 ¶
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 ¶
GetFileIndex returns the session's FileIndex, creating it lazily if needed.
func (*Session) HasLeadingCommand ¶
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) IsCommandDelegated ¶
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) PlansDir ¶
PlansDir returns the session-scoped safe plans directory (<session-dir>/plans).
func (*Session) PopCommand ¶
PopCommand pops and returns the leading command item if present.
func (*Session) PopMessages ¶
PopMessages pops and returns all leading messages up to the next command item.
func (*Session) Refresh ¶
Refresh recalculates session diagnostics and reconfigures the harness (e.g. after a workspace reload), publishing a SessionUpdatedEvent.
func (*Session) RemoveChild ¶
RemoveChild unregisters a child session by ID from this session.
func (*Session) ResolvedModel ¶
func (*Session) Send ¶
Send initiates an asynchronous conversational turn with a user message or resolves a pending permission decision.
func (*Session) Update ¶
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 ¶
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 ¶
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.