session

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package session orchestrates AGH session lifecycle around ACP-backed agents.

Index

Constants

View Source
const (
	RepairSeverityInfo    = "info"
	RepairSeverityWarning = "warning"
	RepairSeverityError   = "error"

	RepairIssueSequenceGap                = "event_sequence_gap"
	RepairIssueSequenceDuplicate          = "event_sequence_duplicate"
	RepairIssueSequenceRegression         = "event_sequence_regression"
	RepairIssueInvalidEventJSON           = "invalid_event_json"
	RepairIssueEventTypeMismatch          = "event_type_mismatch"
	RepairIssueNoRepairableTurn           = "no_repairable_turn"
	RepairIssueSessionNotStopped          = "session_not_stopped"
	RepairIssueStopReasonRequiresForce    = "stop_reason_requires_force"
	RepairIssueDanglingToolCallMissingID  = "dangling_tool_call_missing_id"
	RepairIssueTerminalEventAlreadyExists = "terminal_event_already_exists"

	RepairActionAppendInterruptedToolResult = "append_interrupted_tool_result"
	RepairActionAppendTerminalError         = "append_terminal_error"
)
View Source
const (
	// DefaultSpawnMaxChildren is the MVP per-parent active child cap.
	DefaultSpawnMaxChildren = 5
	// DefaultSpawnMaxDepth is the MVP maximum child depth under a root session.
	DefaultSpawnMaxDepth = 1
	// DefaultSpawnRole is used when an agent omits the advisory child role.
	DefaultSpawnRole = "worker"
	// SpawnRoleMemoryExtractor marks daemon-owned extractor children.
	SpawnRoleMemoryExtractor = "memory-extractor"
)
View Source
const (
	// DefaultLivenessStallAfter defines how long a session may go without ACP
	// activity before recovery marks it stalled.
	DefaultLivenessStallAfter = 2 * time.Minute
)
View Source
const (
	// EventTypeSessionStopped is emitted when a session transitions to the stopped state.
	EventTypeSessionStopped = "session_stopped"
)

Variables

View Source
var (
	// ErrSessionNotFound reports that the requested active session does not exist.
	ErrSessionNotFound = errors.New("session: session not found")
	// ErrSessionNotActive reports that a known session cannot accept live approvals or prompts.
	ErrSessionNotActive = errors.New("session: session is not active")
	// ErrPendingPermissionNotFound reports that no waiting permission matched the approval request.
	ErrPendingPermissionNotFound = errors.New("session: pending permission not found")
	// ErrPendingPermissionConflict reports that the approval request matched multiple pending permissions.
	ErrPendingPermissionConflict = errors.New("session: pending permission lookup is ambiguous")
	// ErrInvalidPermissionDecision reports an approval decision unsupported by the pending provider request.
	ErrInvalidPermissionDecision = errors.New("session: invalid permission decision")
	// ErrInvalidRuntimeOverride reports that a session runtime override is invalid.
	ErrInvalidRuntimeOverride = errors.New("session: invalid runtime override")
)
View Source
var (
	// ErrInvalidStateTransition reports that a session state transition is not allowed.
	ErrInvalidStateTransition = errors.New("session: invalid state transition")
	// ErrPromptInProgress reports that the session already has prompt setup or execution in flight.
	ErrPromptInProgress = errors.New("session: prompt already in progress")
	// ErrPromptNotInProgress reports that an operation requires an active prompt turn.
	ErrPromptNotInProgress = errors.New("session: prompt is not in progress")
)
View Source
var (
	// ErrSoulRefreshConflict reports that a Soul refresh cannot run because
	// another session-scoped operation or an active task run is in progress.
	ErrSoulRefreshConflict = errors.New("session: soul refresh conflict")
	// ErrSoulRefreshDigestConflict reports a stale body-level expected digest.
	ErrSoulRefreshDigestConflict = errors.New("session: soul refresh expected digest conflict")
)
View Source
var (
	// ErrSpawnValidation reports a structurally invalid spawn request.
	ErrSpawnValidation = errors.New("session: spawn validation failed")
	// ErrSpawnPermissionDenied reports a failed permission narrowing check.
	ErrSpawnPermissionDenied = errors.New("session: spawn permission denied")
	// ErrSpawnLimitExceeded reports a depth, child, or workspace cap violation.
	ErrSpawnLimitExceeded = errors.New("session: spawn limit exceeded")
)
View Source
var ErrScopedInterruptNotFound = toolruntime.ErrProcessNotFound

ErrScopedInterruptNotFound reports that no registered tool process matched a scoped interrupt.

View Source
var SupportedReasoningEfforts = []string{"minimal", "low", "medium", runtimeOverridesHighKey, "xhigh"}

SupportedReasoningEfforts is the canonical ordered enum accepted by session creation.

Functions

func AnnotateUnpersistedRecovery

func AnnotateUnpersistedRecovery(meta store.SessionMeta, err error) store.SessionMeta

AnnotateUnpersistedRecovery appends persistence failure detail to the recovered stopped-state metadata returned to callers when the synthetic crash classification could not be durably written.

func AttachableForInfo

func AttachableForInfo(info *Info, now time.Time) bool

AttachableForInfo computes whether a session snapshot is eligible for an explicit attach without consulting UI state or spawning a new runtime.

func ClassifyInactiveMetaForRecovery

func ClassifyInactiveMetaForRecovery(now time.Time, meta store.SessionMeta) (store.SessionMeta, bool)

ClassifyInactiveMetaForRecovery rewrites non-terminal persisted session metadata into a stopped view that captures the best available supervision evidence after daemon interruption.

func IsSupportedReasoningEffort

func IsSupportedReasoningEffort(value string) bool

IsSupportedReasoningEffort reports whether value is an accepted reasoning effort.

func RepairLegacyProvider

func RepairLegacyProvider(
	ctx context.Context,
	metaPath string,
	meta store.SessionMeta,
	opts LegacyProviderRepairOptions,
) (store.SessionMeta, error)

RepairLegacyProvider resolves and persists the effective provider for a legacy inactive session exactly once before resume or reconcile continues.

func ValidatePermissionSubset

func ValidatePermissionSubset(parent store.SessionPermissionPolicy, child store.SessionPermissionPolicy) error

ValidatePermissionSubset fails closed unless every child permission atom is present in the corresponding known parent category.

func ValidateReasoningEffort

func ValidateReasoningEffort(value string) error

ValidateReasoningEffort validates one reasoning effort override.

Types

type ACPDriverAdapter

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

ACPDriverAdapter adapts the concrete ACP driver to the session-local interface.

func NewACPDriverAdapter

func NewACPDriverAdapter(driver *acp.Driver) *ACPDriverAdapter

NewACPDriverAdapter wraps the provided ACP driver for use by the session manager.

func (*ACPDriverAdapter) Cancel

func (a *ACPDriverAdapter) Cancel(ctx context.Context, proc *AgentProcess) error

Cancel lets higher layers stop prompt work without bypassing ACP-owned lifecycle handling.

func (*ACPDriverAdapter) Interrupt

func (a *ACPDriverAdapter) Interrupt(
	ctx context.Context,
	sessionID string,
	turnID string,
) (toolruntime.InterruptReport, error)

Interrupt signals only registered tool processes scoped to the session turn.

func (*ACPDriverAdapter) Prompt

func (a *ACPDriverAdapter) Prompt(
	ctx context.Context,
	proc *AgentProcess,
	req acp.PromptRequest,
) (<-chan acp.AgentEvent, error)

Prompt streams prompt events from the wrapped ACP runtime.

func (*ACPDriverAdapter) Start

Start launches a new ACP-backed runtime process.

func (*ACPDriverAdapter) Stop

func (a *ACPDriverAdapter) Stop(ctx context.Context, proc *AgentProcess) error

Stop stops the wrapped ACP runtime process.

type AgentArtifactResolver

type AgentArtifactResolver interface {
	ResolveAgentArtifacts(name string, resolved *workspacepkg.ResolvedWorkspace) (AgentArtifacts, error)
}

AgentArtifactResolver resolves agent provenance and sidecars when available.

type AgentArtifacts

type AgentArtifacts struct {
	Agent               aghconfig.AgentDef
	ResourceID          string
	OwnerKind           string
	OwnerID             string
	Scope               resources.ResourceScope
	PackageOwned        bool
	SoulSourcePath      string
	SoulBody            string
	HeartbeatSourcePath string
	HeartbeatBody       string
}

AgentArtifacts returns an agent definition and optional resource-backed authored-context sidecars.

type AgentDriver

type AgentDriver interface {
	Start(ctx context.Context, opts acp.StartOpts) (*AgentProcess, error)
	Prompt(ctx context.Context, proc *AgentProcess, req acp.PromptRequest) (<-chan acp.AgentEvent, error)
	Cancel(ctx context.Context, proc *AgentProcess) error
	Stop(ctx context.Context, proc *AgentProcess) error
}

AgentDriver defines the ACP functionality consumed by the session manager.

type AgentEventNotifier

type AgentEventNotifier interface {
	OnAgentEventForSession(ctx context.Context, session *Session, event any)
}

AgentEventNotifier is an optional notifier extension that receives the active session alongside streamed agent events.

type AgentHooks

AgentHooks groups agent start and stop lifecycle hook dispatch.

type AgentProcess

type AgentProcess struct {
	PID       int
	AgentName string
	Command   string
	Args      []string
	Cwd       string
	SessionID string
	Caps      acp.Caps
	StartedAt time.Time
	// contains filtered or unexported fields
}

AgentProcess is the session-owned handle for a running agent process.

func NewAgentProcess

func NewAgentProcess(opts AgentProcessOptions) *AgentProcess

NewAgentProcess constructs an AgentProcess for custom AgentDriver implementations.

func (*AgentProcess) ApprovePermission

func (p *AgentProcess) ApprovePermission(ctx context.Context, req acp.ApproveRequest) error

ApprovePermission resolves one pending interactive permission request.

func (*AgentProcess) CapsSnapshot

func (p *AgentProcess) CapsSnapshot() acp.Caps

CapsSnapshot returns the latest ACP capability/config snapshot for this process.

func (*AgentProcess) Done

func (p *AgentProcess) Done() <-chan struct{}

Done reports when the underlying runtime process exits.

func (*AgentProcess) HealthState

func (p *AgentProcess) HealthState() (subprocess.HealthState, bool)

HealthState returns the latest runtime health snapshot when the driver exposes subprocess health monitoring.

func (*AgentProcess) RequestPermission

RequestPermission asks the active runtime permission path for a tool approval decision.

func (*AgentProcess) Stderr

func (p *AgentProcess) Stderr() string

Stderr returns any captured stderr output for the runtime process.

func (*AgentProcess) ToolHost

func (p *AgentProcess) ToolHost() sandbox.ToolHost

ToolHost returns the sandbox-owned tool host when the process exposes one.

func (*AgentProcess) Wait

func (p *AgentProcess) Wait() error

Wait blocks until the runtime process exits and returns its terminal error state.

type AgentProcessOptions

type AgentProcessOptions struct {
	PID               int
	AgentName         string
	Command           string
	Args              []string
	Cwd               string
	SessionID         string
	Caps              acp.Caps
	StartedAt         time.Time
	Done              <-chan struct{}
	Wait              func() error
	Stderr            func() string
	HealthState       func() subprocess.HealthState
	ApprovePermission func(context.Context, acp.ApproveRequest) error
	RequestPermission func(context.Context, acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error)
	CapsSnapshot      func() acp.Caps
	ConfigureRuntime  func(func() TurnSource)
	ToolHost          sandbox.ToolHost
}

AgentProcessOptions defines the exported fields and lifecycle hooks needed to construct an AgentProcess.

type AgentResolver

type AgentResolver interface {
	ResolveAgent(name string, resolved *workspacepkg.ResolvedWorkspace) (aghconfig.AgentDef, error)
}

AgentResolver resolves agent definitions from the daemon-authoritative catalog.

type AuthoredContextHooks

type AuthoredContextHooks interface {
	DispatchSessionHealthUpdateAfter(
		context.Context,
		hookspkg.SessionHealthUpdateAfterPayload,
	) (hookspkg.SessionHealthUpdateAfterPayload, error)
}

AuthoredContextHooks groups Soul, Heartbeat, and session-health observation hook dispatch.

type Badge

type Badge string

Badge is the canonical user-facing session status token.

const (
	BadgeRunning        Badge = "running"
	BadgeIdle           Badge = "idle"
	BadgeUnhealthy      Badge = "unhealthy"
	BadgeHung           Badge = "hung"
	BadgeWaitingForAuth Badge = "waiting-for-auth"
	BadgeStopped        Badge = "stopped"
	BadgeFailed         Badge = "failed"
	BadgeUnknown        Badge = "unknown"
)

func BadgeForHealth

func BadgeForHealth(info *Info, health heartbeat.SessionHealth) Badge

BadgeForHealth computes a badge from an explicit health row, preserving session/failure precedence from the base session info when supplied.

func BadgeForInfo

func BadgeForInfo(info *Info) Badge

BadgeForInfo computes a badge from the session manager/catalog snapshot.

func CanonicalBadge

func CanonicalBadge(input BadgeInputs) Badge

CanonicalBadge collapses runtime state, health, and failure classification into the stable eight-token badge vocabulary used by API, CLI, and web clients.

type BadgeInputs

type BadgeInputs struct {
	State               State
	HealthState         heartbeat.SessionHealthState
	Health              heartbeat.SessionHealthStatus
	Failure             *store.SessionFailure
	PendingAuth         bool
	ActivePrompt        bool
	Stalled             bool
	IneligibilityReason string
}

BadgeInputs are the runtime-truth fields used to compute a session badge.

type BusyInputMode

type BusyInputMode string

BusyInputMode selects how a user-facing prompt behaves while a session is busy.

const (
	BusyInputModeQueue     BusyInputMode = "queue"
	BusyInputModeInterrupt BusyInputMode = "interrupt"
	BusyInputModeSteer     BusyInputMode = "steer"
)

type CompactionHooks

type CompactionHooks interface {
	DispatchContextPreCompact(
		context.Context,
		hookspkg.ContextPreCompactPayload,
	) (hookspkg.ContextPreCompactPayload, error)
	DispatchContextPostCompact(
		context.Context,
		hookspkg.ContextPostCompactPayload,
	) (hookspkg.ContextPostCompactPayload, error)
}

CompactionHooks groups context compaction hook dispatch.

type ConversationHooks

ConversationHooks groups turn/message hook dispatch used during prompt streaming.

type CreateOpts

type CreateOpts struct {
	AgentName        string
	Provider         string
	Model            string
	ReasoningEffort  string
	SandboxRef       string
	DisableSandbox   bool
	Permissions      aghconfig.PermissionMode
	Name             string
	Workspace        string
	WorkspacePath    string
	Channel          string
	PromptOverlay    string
	Type             Type
	Lineage          *store.SessionLineage
	ParentSoulDigest string
}

CreateOpts defines the inputs required to create a new session.

type EventHooks

EventHooks groups event-record persistence hook dispatch.

type EventRecorder

type EventRecorder = store.EventRecorder

EventRecorder is the per-session storage surface consumed by session/.

type HealthRecoveryResult

type HealthRecoveryResult struct {
	RefreshedActive int
	Recomputed      int
	MarkedStale     int64
}

HealthRecoveryResult summarizes one metadata-only restart recovery pass.

type HealthStore

type HealthStore interface {
	UpsertSessionHealth(ctx context.Context, health heartbeat.SessionHealth) (heartbeat.SessionHealth, error)
	GetSessionHealth(ctx context.Context, sessionID string) (heartbeat.SessionHealth, error)
	ListSessionHealth(ctx context.Context, query heartbeat.SessionHealthListQuery) ([]heartbeat.SessionHealth, error)
	ListSessionHealthRecoveryInputs(ctx context.Context, limit int) ([]heartbeat.SessionHealth, error)
	MarkSessionHealthStale(ctx context.Context, cutoff time.Time, updatedAt time.Time) (int64, error)
}

HealthStore is the durable store used by metadata-only session health.

type HookSet

type HookSet struct {
	Session         LifecycleHooks
	Sandbox         SandboxHooks
	Prompt          PromptHooks
	Events          EventHooks
	Agent           AgentHooks
	Conversation    ConversationHooks
	Tools           ToolHooks
	Compaction      CompactionHooks
	Spawn           SpawnHooks
	AuthoredContext AuthoredContextHooks
}

HookSet collects the grouped session hook domains. Nil groups are treated as no-op implementations so callers only provide the domains they exercise.

type HostedMCPLaunchRequest

type HostedMCPLaunchRequest struct {
	SessionID   string
	WorkspaceID string
	AgentName   string
}

HostedMCPLaunchRequest describes the session identity for a hosted MCP entry.

type HostedMCPLauncher

type HostedMCPLauncher interface {
	Launch(ctx context.Context, req HostedMCPLaunchRequest) (aghconfig.MCPServer, error)
	CancelLaunch(sessionID string)
	ReleaseSession(sessionID string)
}

HostedMCPLauncher mints and releases session-bound hosted MCP launch records.

type IDGenerator

type IDGenerator func() string

IDGenerator returns unique identifiers for sessions and prompt turns.

type Info

type Info struct {
	ID               string
	Name             string
	AgentName        string
	Provider         string
	Model            string
	ReasoningEffort  string
	WorkspaceID      string
	Workspace        string
	Channel          string
	Type             Type
	Lineage          *store.SessionLineage
	State            State
	StopReason       store.StopReason
	StopDetail       string
	Failure          *store.SessionFailure
	ACPSessionID     string
	ACPCaps          acp.Caps
	Liveness         *store.SessionLivenessMeta
	Sandbox          *store.SessionSandboxMeta
	SoulSnapshotID   string
	SoulDigest       string
	ParentSoulDigest string
	AttachedTo       string
	AttachExpiresAt  *time.Time
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

Info is the external read model returned by session list/get operations.

type InputQueueSummary

type InputQueueSummary struct {
	QueueGeneration int64
	PendingInputs   int
}

InputQueueSummary is the session package projection of durable busy-input queue state.

type LedgerMaterializer

type LedgerMaterializer interface {
	MaterializeSessionLedger(ctx context.Context, record store.SessionLedgerRecord) error
	DiscardSessionLedger(ctx context.Context, record store.SessionLedgerRecord) error
}

LedgerMaterializer is the thin session-end seam for forensic ledger projection.

type LegacyProviderRepairOptions

type LegacyProviderRepairOptions struct {
	Now               func() time.Time
	Logger            *slog.Logger
	WorkspaceResolver workspacepkg.RuntimeResolver
	AgentResolver     AgentResolver
}

LegacyProviderRepairOptions supplies the dependencies used to repair legacy session metadata that predates persisted provider state.

type LifecycleHooks

LifecycleHooks groups create/resume/stop session lifecycle hook dispatch.

type MCPResolver

type MCPResolver interface {
	Resolve(skills []*skillspkg.Skill) []aghconfig.MCPServer
}

MCPResolver resolves skill-declared MCP servers into runtime config entries.

type Manager

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

Manager owns active session lifecycle and runtime orchestration.

func NewManager

func NewManager(opts ...Option) (*Manager, error)

NewManager constructs a session manager with sensible defaults.

func (*Manager) ApprovePermission

func (m *Manager) ApprovePermission(ctx context.Context, id string, req acp.ApproveRequest) error

ApprovePermission resolves one pending interactive permission request for an active session.

func (*Manager) CancelPrompt

func (m *Manager) CancelPrompt(ctx context.Context, id string) error

CancelPrompt cancels prompt setup/execution for a known session.

func (*Manager) CancelQueuedPrompt

func (m *Manager) CancelQueuedPrompt(ctx context.Context, id string, queueEntryID string) (SendPromptResult, error)

CancelQueuedPrompt cancels one pending busy-input queue entry.

func (*Manager) ClearConversation

func (m *Manager) ClearConversation(ctx context.Context, id string) (_ *Session, err error)

ClearConversation resets the persisted transcript and ACP conversation context for an existing session while preserving the same session id. The session is restarted on a fresh event store so subsequent prompts start from a clean conversation.

func (*Manager) Create

func (m *Manager) Create(ctx context.Context, opts CreateOpts) (_ *Session, err error)

Create resolves an agent definition, opens the session store, and starts a new runtime session.

func (*Manager) Delete

func (m *Manager) Delete(ctx context.Context, id string) error

Delete removes one session from active runtime state and persisted history.

func (*Manager) Events

func (m *Manager) Events(
	ctx context.Context,
	id string,
	query store.EventQuery,
) (events []store.SessionEvent, err error)

Events returns persisted session events for active or stopped sessions.

func (*Manager) ExecSandbox

func (m *Manager) ExecSandbox(ctx context.Context, req SandboxExecRequest) (SandboxExecResult, error)

ExecSandbox runs a command through the active session's sandbox tool host.

func (*Manager) Get

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

Get returns the active in-memory session by id.

func (*Manager) GetSessionHealth

func (m *Manager) GetSessionHealth(ctx context.Context, id string) (heartbeat.SessionHealth, error)

GetSessionHealth returns a route-ready metadata-only health read model.

func (*Manager) History

func (m *Manager) History(
	ctx context.Context,
	id string,
	query store.EventQuery,
) (history []store.TurnHistory, err error)

History returns turn-grouped persisted session events for active or stopped sessions.

func (*Manager) InputQueueSummary

func (m *Manager) InputQueueSummary(ctx context.Context, id string) (InputQueueSummary, error)

InputQueueSummary returns the durable busy-input state for one session.

func (*Manager) InterruptPrompt

func (m *Manager) InterruptPrompt(ctx context.Context, id string) (SendPromptResult, error)

InterruptPrompt cancels the active user/session turn and fences stale queued input.

func (*Manager) IsPrompting

func (m *Manager) IsPrompting(id string) bool

IsPrompting reports whether the target session currently has an in-flight prompt setup or active turn.

func (*Manager) List

func (m *Manager) List() []*Info

List returns active in-memory sessions in stable order.

func (*Manager) ListAll

func (m *Manager) ListAll(ctx context.Context) ([]*Info, error)

ListAll returns active and stopped sessions discovered from on-disk metadata.

func (*Manager) ListSessionHealth

func (m *Manager) ListSessionHealth(
	ctx context.Context,
	query heartbeat.SessionHealthListQuery,
) ([]heartbeat.SessionHealth, error)

ListSessionHealth refreshes active rows, marks stale rows, and returns persisted health.

func (*Manager) Prompt

func (m *Manager) Prompt(ctx context.Context, id string, msg string) (<-chan acp.AgentEvent, error)

Prompt sends one prompt turn to an active session and mirrors the runtime stream into storage and observers.

func (*Manager) PromptNetwork

func (m *Manager) PromptNetwork(
	ctx context.Context,
	id string,
	msg string,
	meta ...acp.PromptNetworkMeta,
) (<-chan acp.AgentEvent, error)

PromptNetwork sends one network-originated prompt turn to an active session.

func (*Manager) PromptSynthetic

func (m *Manager) PromptSynthetic(
	ctx context.Context,
	id string,
	opts SyntheticPromptOpts,
) (<-chan acp.AgentEvent, error)

PromptSynthetic submits one daemon-owned synthetic prompt turn.

func (*Manager) PromptWithOpts

func (m *Manager) PromptWithOpts(ctx context.Context, id string, opts PromptOpts) (<-chan acp.AgentEvent, error)

PromptWithOpts sends one prompt turn with daemon-local provenance metadata.

func (*Manager) RecoverSessionHealth

func (m *Manager) RecoverSessionHealth(ctx context.Context) (HealthRecoveryResult, error)

RecoverSessionHealth recomputes persisted rows after daemon restart before wake decisions run.

func (*Manager) RefreshSoul

func (m *Manager) RefreshSoul(ctx context.Context, id string) (SoulRefreshResult, error)

RefreshSoul explicitly refreshes the session's resolved Soul snapshot.

func (*Manager) RefreshSoulWithExpectedDigest

func (m *Manager) RefreshSoulWithExpectedDigest(
	ctx context.Context,
	id string,
	expectedDigest string,
) (SoulRefreshResult, error)

RefreshSoulWithExpectedDigest explicitly refreshes a session Soul snapshot after service-owned CAS.

func (*Manager) RepairSession

func (m *Manager) RepairSession(
	ctx context.Context,
	opts RepairOpts,
) (result *RepairResult, err error)

RepairSession inspects one persisted session transcript and, when safe, appends terminal repair events for an interrupted final prompt turn.

func (*Manager) RequestPermission

func (m *Manager) RequestPermission(
	ctx context.Context,
	id string,
	req acp.RequestPermissionRequest,
) (acp.RequestPermissionResponse, error)

RequestPermission asks an active session's permission path for a tool-call decision.

func (*Manager) RequestStopWithCause

func (m *Manager) RequestStopWithCause(ctx context.Context, id string, cause StopCause, detail string) error

RequestStopWithCause marks a session as stopping and sends the cooperative ACP cancel signal without forcing process termination.

func (*Manager) Resume

func (m *Manager) Resume(ctx context.Context, id string) (_ *Session, err error)

Resume restarts a stopped session from its persisted metadata and event history.

func (*Manager) SendPrompt

func (m *Manager) SendPrompt(ctx context.Context, id string, opts SendPromptOpts) (SendPromptResult, error)

SendPrompt submits a user-facing prompt and applies busy-input policy when a turn is active.

func (*Manager) SetNetworkPeerLifecycle

func (m *Manager) SetNetworkPeerLifecycle(lifecycle NetworkPeerLifecycle)

SetNetworkPeerLifecycle installs the late-bound network join/leave callbacks used after session activation and before final stop cleanup.

func (*Manager) SetTurnEndNotifier

func (m *Manager) SetTurnEndNotifier(fn TurnEndNotifier)

SetTurnEndNotifier installs a post-construction callback invoked after each prompt turn finishes.

func (*Manager) Spawn

func (m *Manager) Spawn(ctx context.Context, opts SpawnOpts) (*Session, error)

Spawn creates a bounded child session after enforcing lineage, TTL, caps, workspace bounds, and permission narrowing.

func (*Manager) Status

func (m *Manager) Status(ctx context.Context, id string) (*Info, error)

Status returns the current session status from memory or on-disk metadata.

func (*Manager) SteerPrompt

func (m *Manager) SteerPrompt(ctx context.Context, id string, msg string) (SendPromptResult, error)

SteerPrompt stages guidance for the active turn, falling back to queue dispatch if no tool boundary arrives.

func (*Manager) Stop

func (m *Manager) Stop(ctx context.Context, id string) error

Stop stops an active session and persists the stopped state to disk.

func (*Manager) StopWithCause

func (m *Manager) StopWithCause(ctx context.Context, id string, cause StopCause, detail string) error

StopWithCause stops a session while preserving the explicit stop initiator.

func (*Manager) TouchSessionPresence

func (m *Manager) TouchSessionPresence(ctx context.Context, id string) (heartbeat.SessionHealth, error)

TouchSessionPresence records an idle metadata-only presence touch for an attachable session.

func (*Manager) Transcript

func (m *Manager) Transcript(ctx context.Context, id string) ([]transcript.UIMessage, error)

Transcript returns a canonical AI SDK replay transcript for the requested session.

func (*Manager) WaitForFinalizations

func (m *Manager) WaitForFinalizations(ctx context.Context) error

WaitForFinalizations blocks until all in-flight finalization routines finish.

func (*Manager) WaitForPromptDrains

func (m *Manager) WaitForPromptDrains(ctx context.Context) error

WaitForPromptDrains blocks until active prompt pump goroutines finish.

func (*Manager) WithSoulClaimLock

func (m *Manager) WithSoulClaimLock(ctx context.Context, sessionID string, fn func() error) error

WithSoulClaimLock runs fn while holding the session Soul lock used by refresh.

type NetworkPeerCapability

type NetworkPeerCapability struct {
	ID                string
	Summary           string
	Outcome           string
	Version           string
	Digest            string
	ContextNeeded     []string
	ArtifactsExpected []string
	ExecutionOutline  []string
	Constraints       []string
	Examples          []string
	Requirements      []string
}

NetworkPeerCapability is the runtime-owned capability projection shared with the network join lifecycle for brief and rich discovery.

type NetworkPeerJoin

type NetworkPeerJoin struct {
	SessionID    string
	PeerID       string
	WorkspaceID  string
	DisplayName  string
	Channel      string
	Capabilities []NetworkPeerCapability
}

NetworkPeerJoin describes one daemon-local peer registration request for the late-bound network lifecycle.

type NetworkPeerLifecycle

type NetworkPeerLifecycle interface {
	JoinChannel(ctx context.Context, join NetworkPeerJoin) error
	LeaveChannel(ctx context.Context, sessionID string) error
}

NetworkPeerLifecycle is the late-bound network join/leave surface consumed by the session manager without importing the network package.

type Notifier

type Notifier interface {
	OnSessionCreated(ctx context.Context, session *Session)
	OnSessionStopped(ctx context.Context, session *Session)
	OnAgentEvent(ctx context.Context, sessionID string, event any)
}

Notifier fans out session lifecycle and prompt events to downstream observers.

type Option

type Option func(*Manager)

Option customizes the session manager.

func WithAgentResolver

func WithAgentResolver(resolver AgentResolver) Option

WithAgentResolver injects the daemon-authoritative agent definition resolver.

func WithDriver

func WithDriver(driver AgentDriver) Option

WithDriver injects the runtime driver used for session lifecycle operations.

func WithHomePaths

func WithHomePaths(homePaths aghconfig.HomePaths) Option

WithHomePaths overrides the resolved AGH home directory layout.

func WithHookSet

func WithHookSet(hooks HookSet) Option

WithHookSet injects the grouped hook dispatch surface used by the session manager for lifecycle and runtime hook points.

func WithHostedMCPLauncher

func WithHostedMCPLauncher(launcher HostedMCPLauncher) Option

WithHostedMCPLauncher injects the session-bound AGH-hosted MCP launcher.

func WithLedgerMaterializer

func WithLedgerMaterializer(materializer LedgerMaterializer) Option

WithLedgerMaterializer injects the forensic session-ledger materializer.

func WithLifecycleContext

func WithLifecycleContext(ctx context.Context) Option

WithLifecycleContext injects the daemon-owned lifecycle context used by background goroutines.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger injects the logger used by the session manager.

func WithMCPResolver

func WithMCPResolver(resolver MCPResolver) Option

WithMCPResolver injects the skill MCP resolver used during session start.

func WithNotifier

func WithNotifier(notifier Notifier) Option

WithNotifier injects the async notification fan-out implementation.

func WithNow

func WithNow(now func() time.Time) Option

WithNow overrides the manager clock, mainly for tests.

func WithPromptAssembler

func WithPromptAssembler(assembler PromptAssembler) Option

WithPromptAssembler injects prompt assembly for session startup.

func WithPromptBufferSize

func WithPromptBufferSize(size int) Option

WithPromptBufferSize overrides the size of the returned prompt event buffer.

func WithPromptInputAugmenter

func WithPromptInputAugmenter(augmenter PromptInputAugmenter) Option

WithPromptInputAugmenter injects a bounded pre-dispatch message augmenter.

func WithProviderSecretResolver

func WithProviderSecretResolver(resolver ProviderSecretResolver) Option

WithProviderSecretResolver injects the launch-time provider secret resolver.

func WithQueryStore

func WithQueryStore(opener StoreOpener) Option

WithQueryStore injects the opener used for stopped-session transcript/event reads. Production uses a read-only no-create opener so stale viewers cannot recreate events.db during clear/delete races.

func WithSandboxIDGenerator

func WithSandboxIDGenerator(generator IDGenerator) Option

WithSandboxIDGenerator overrides sandbox id allocation.

func WithSandboxRegistry

func WithSandboxRegistry(registry *sandbox.Registry) Option

WithSandboxRegistry injects the runtime sandbox provider registry.

func WithSessionBusyInputConfig

func WithSessionBusyInputConfig(config aghconfig.SessionBusyInputConfig) Option

WithSessionBusyInputConfig overrides busy-input queue behavior.

func WithSessionHealthConfig

func WithSessionHealthConfig(config aghconfig.HeartbeatConfig) Option

WithSessionHealthConfig injects Agent Heartbeat bounds used by session health.

func WithSessionHealthStore

func WithSessionHealthStore(store HealthStore) Option

WithSessionHealthStore injects durable metadata-only session health storage.

func WithSessionIDGenerator

func WithSessionIDGenerator(generator IDGenerator) Option

WithSessionIDGenerator overrides session id allocation.

func WithSessionInputQueueStore

func WithSessionInputQueueStore(queueStore store.SessionInputQueueStore) Option

WithSessionInputQueueStore injects durable busy-input queue storage.

func WithSessionSupervision

func WithSessionSupervision(config aghconfig.SessionSupervisionConfig) Option

WithSessionSupervision overrides runtime activity supervision settings.

func WithSkillRegistry

func WithSkillRegistry(registry SkillRegistry) Option

WithSkillRegistry injects the active-skill registry used during session start.

func WithSoulRunActivityChecker

func WithSoulRunActivityChecker(checker SoulRunActivityChecker) Option

WithSoulRunActivityChecker injects the active-run predicate used by Soul refresh.

func WithSoulSnapshotStore

func WithSoulSnapshotStore(store SoulSnapshotStore) Option

WithSoulSnapshotStore injects durable Soul snapshot/session provenance storage.

func WithStartupPromptOverlay

func WithStartupPromptOverlay(overlay StartupPromptOverlay) Option

WithStartupPromptOverlay injects a daemon-owned startup prompt overlay.

func WithStore

func WithStore(opener StoreOpener) Option

WithStore injects the opener used to create per-session event recorders.

func WithTurnIDGenerator

func WithTurnIDGenerator(generator IDGenerator) Option

WithTurnIDGenerator overrides prompt turn id allocation.

func WithWorkspaceResolver

func WithWorkspaceResolver(resolver workspacepkg.RuntimeResolver) Option

WithWorkspaceResolver injects workspace resolution for create/resume flows.

type PromptAssembler

type PromptAssembler interface {
	Assemble(ctx context.Context, agent aghconfig.AgentDef, workspace *workspacepkg.ResolvedWorkspace) (string, error)
}

PromptAssembler assembles the prompt context for a new session start.

type PromptHooks

type PromptHooks interface {
	DispatchInputPreSubmit(context.Context, hookspkg.InputPreSubmitPayload) (hookspkg.InputPreSubmitPayload, error)
	DispatchPromptPostAssemble(context.Context, hookspkg.PromptPayload) (hookspkg.PromptPayload, error)
}

PromptHooks groups prompt assembly and user-input hook dispatch.

type PromptInputAugmenter

type PromptInputAugmenter func(ctx context.Context, session *Session, message string) (string, error)

PromptInputAugmenter can add bounded daemon-local context before prompt dispatch.

type PromptOpts

type PromptOpts struct {
	Message         string
	TurnSource      TurnSource
	PromptMeta      acp.PromptMeta
	DeliveryContext context.Context
}

PromptOpts carries per-turn metadata through the session prompt pipeline.

type PromptProvider

type PromptProvider interface {
	PromptSection(ctx context.Context, workspace *workspacepkg.ResolvedWorkspace) (string, error)
}

PromptProvider returns one workspace-scoped prompt section for composed system-prompt assembly.

type ProviderSecretResolver

type ProviderSecretResolver interface {
	ResolveRef(ctx context.Context, ref string) (string, error)
}

ProviderSecretResolver resolves provider-bound secret refs at launch time.

type RepairAction

type RepairAction struct {
	Code       string
	TurnID     string
	EventID    string
	ToolCallID string
	ToolName   string
	Persisted  bool
}

RepairAction is one append-only mutation planned or persisted by repair.

type RepairIssue

type RepairIssue struct {
	Code     string
	Severity string
	TurnID   string
	EventID  string
	Detail   string
}

RepairIssue is one non-mutating diagnostic discovered during repair.

type RepairOpts

type RepairOpts struct {
	SessionID string
	DryRun    bool
	Force     bool
}

RepairOpts controls one persisted session repair pass.

type RepairResult

type RepairResult struct {
	SessionID string
	Issues    []RepairIssue
	Actions   []RepairAction
	Persisted bool
}

RepairResult describes the detected inconsistencies and append-only repair events planned or persisted for a session.

type SandboxExecRequest

type SandboxExecRequest struct {
	SessionID string
	Command   string
	Timeout   time.Duration
}

SandboxExecRequest describes one command execution inside a session sandbox.

type SandboxExecResult

type SandboxExecResult struct {
	ExitCode int
	Stdout   string
	Stderr   string
}

SandboxExecResult reports the terminal execution result.

type SandboxHooks

SandboxHooks groups execution-sandbox lifecycle hook dispatch.

type SandboxLifecycleEvent

type SandboxLifecycleEvent struct {
	Name        string
	Span        string
	SessionID   string
	WorkspaceID string
	SandboxID   string
	Backend     string
	Profile     string
	InstanceID  string
	Reason      string
	Duration    time.Duration
	ErrorKind   string
	Error       string
	Timestamp   time.Time
}

SandboxLifecycleEvent reports provider lifecycle timing to optional observers.

type SandboxLifecycleNotifier

type SandboxLifecycleNotifier interface {
	OnSandboxLifecycleEvent(context.Context, SandboxLifecycleEvent)
}

SandboxLifecycleNotifier is an optional notifier extension for sandbox lifecycle spans.

type ScopedInterrupter

type ScopedInterrupter interface {
	Interrupt(ctx context.Context, sessionID string, turnID string) (toolruntime.InterruptReport, error)
}

ScopedInterrupter is the optional process-scoped interrupt surface for drivers.

type SendPromptOpts

type SendPromptOpts struct {
	Message         string
	Mode            BusyInputMode
	DeliveryContext context.Context
}

SendPromptOpts carries one user-facing prompt plus optional busy-input mode.

type SendPromptResult

type SendPromptResult struct {
	Status                     string
	Mode                       BusyInputMode
	Events                     <-chan acp.AgentEvent
	QueueEntryID               string
	QueuePosition              int
	QueueGeneration            int64
	EstimatedSendAt            *time.Time
	PreviousTurnID             string
	NewTurnID                  string
	Interrupted                bool
	Staged                     bool
	Queued                     bool
	CanceledQueuedEntries      int
	FallbackModeIfNoToolResult string
}

SendPromptResult reports whether input streamed immediately or was staged.

type Session

type Session struct {
	ID                   string
	Name                 string
	AgentName            string
	Provider             string
	Model                string
	ReasoningEffort      string
	EffectivePermissions string
	WorkspaceID          string
	Workspace            string
	Channel              string
	Type                 Type
	Lineage              *store.SessionLineage
	State                State

	ACPSessionID     string
	ACPCaps          acp.Caps
	Liveness         *store.SessionLivenessMeta
	Sandbox          *store.SessionSandboxMeta
	SoulSnapshotID   string
	SoulDigest       string
	ParentSoulDigest string
	AttachedTo       string
	AttachExpiresAt  *time.Time
	CreatedAt        time.Time
	UpdatedAt        time.Time
	// contains filtered or unexported fields
}

Session is the in-memory runtime representation of one active or stopping session.

func (*Session) ApprovePermission

func (s *Session) ApprovePermission(ctx context.Context, req acp.ApproveRequest) error

ApprovePermission resolves one pending permission request for an active session.

func (*Session) CurrentPromptMeta

func (s *Session) CurrentPromptMeta() acp.PromptMeta

CurrentPromptMeta reports the normalized metadata for the currently active prompt turn.

func (*Session) CurrentTurnID

func (s *Session) CurrentTurnID() string

CurrentTurnID reports the active prompt turn identifier.

func (*Session) CurrentTurnSource

func (s *Session) CurrentTurnSource() TurnSource

CurrentTurnSource reports the provenance of the currently active prompt turn.

func (*Session) DBPath

func (s *Session) DBPath() string

DBPath reports the on-disk per-session event database path.

func (*Session) Info

func (s *Session) Info() *Info

Info returns a consistent snapshot of the current session state.

func (*Session) IsPrompting

func (s *Session) IsPrompting() bool

IsPrompting reports whether the session currently has prompt setup or turn execution in flight.

func (*Session) Meta

func (s *Session) Meta() store.SessionMeta

Meta returns the current metadata snapshot for persistence.

func (*Session) MetaPath

func (s *Session) MetaPath() string

MetaPath reports the on-disk metadata file path.

func (*Session) RequestPermission

RequestPermission asks the active session process for a permission decision.

func (*Session) SessionDir

func (s *Session) SessionDir() string

SessionDir reports the on-disk session directory path.

type SkillRegistry

type SkillRegistry interface {
	ForWorkspace(ctx context.Context, resolved *workspacepkg.ResolvedWorkspace) ([]*skillspkg.Skill, error)
	ForAgent(
		ctx context.Context,
		resolved *workspacepkg.ResolvedWorkspace,
		agentName string,
	) ([]*skillspkg.Skill, error)
}

SkillRegistry resolves the active skill set for a workspace during session start.

type SoulRefreshResult

type SoulRefreshResult struct {
	SessionID        string
	AgentName        string
	SoulSnapshotID   string
	SoulDigest       string
	ParentSoulDigest string
	Snapshot         *soul.Snapshot
	Soul             *soul.ResolvedSoul
	ConfigProvenance soul.ConfigProvenance
	RefreshedAt      time.Time
}

SoulRefreshResult is the internal result returned after a session Soul refresh.

type SoulRunActivityChecker

type SoulRunActivityChecker interface {
	HasActiveRunForSession(ctx context.Context, sessionID string, now time.Time) (bool, error)
}

SoulRunActivityChecker reports whether a session currently owns an active run.

type SoulSnapshotStore

type SoulSnapshotStore interface {
	UpsertSoulSnapshot(ctx context.Context, snapshot soul.Snapshot) (soul.Snapshot, error)
	GetSoulSnapshot(ctx context.Context, id string) (soul.Snapshot, error)
	UpdateSessionSoulSnapshot(ctx context.Context, update store.SessionSoulSnapshotUpdate) error
}

SoulSnapshotStore is the durable storage needed by session Soul integration.

type SpawnHooks

SpawnHooks groups safe child-session spawn hook dispatch.

type SpawnOpts

type SpawnOpts struct {
	ParentSessionID    string
	AgentName          string
	Provider           string
	Model              string
	Name               string
	Workspace          string
	WorkspacePath      string
	Channel            string
	PromptOverlay      string
	SpawnRole          string
	TTL                time.Duration
	AutoStopOnParent   bool
	PermissionPolicy   store.SessionPermissionPolicy
	IdempotencyKey     string
	AllowStoppedParent bool
}

SpawnOpts defines the safe child-session creation request accepted by the manager.

type StartupPromptAssembler

type StartupPromptAssembler interface {
	AssembleStartup(
		ctx context.Context,
		startup StartupPromptContext,
		agent aghconfig.AgentDef,
		workspace *workspacepkg.ResolvedWorkspace,
	) (string, error)
}

StartupPromptAssembler optionally extends PromptAssembler with durable startup context so daemon-owned assemblers can select sections before the final system prompt is concatenated.

type StartupPromptContext

type StartupPromptContext struct {
	SessionID    string
	SessionName  string
	AgentName    string
	Provider     string
	WorkspaceID  string
	Workspace    string
	Channel      string
	SessionType  Type
	SoulSnapshot *soul.Snapshot
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

StartupPromptContext carries the durable session metadata available during startup prompt assembly and overlay selection.

type StartupPromptOverlay

type StartupPromptOverlay interface {
	Apply(ctx context.Context, startup StartupPromptContext, prompt string) (string, error)
}

StartupPromptOverlay applies daemon-owned startup prompt overlays after the base assembler has produced the startup prompt.

type State

type State string

State is the lifecycle state of a managed runtime session.

const (
	StateStarting State = "starting"
	StateActive   State = "active"
	StateStopping State = "stopping"
	StateStopped  State = "stopped"
)

type StopCause

type StopCause int

StopCause records why a session stop was initiated.

const (
	CauseNone StopCause = iota
	CauseCompleted
	CauseFailed
	CauseUserRequested
	CauseShutdown
	CauseHookDenied
	CauseProcessExited
	CauseTimeout
	CauseClearConversation
)

type StoreOpener

type StoreOpener func(ctx context.Context, sessionID string, path string) (EventRecorder, error)

StoreOpener opens the per-session events store for a session directory.

type SyntheticPromptOpts

type SyntheticPromptOpts struct {
	Message                 string
	Metadata                acp.PromptSyntheticMeta
	TurnID                  string
	SkipIfBusy              bool
	InterruptIfAgentWaiting bool
}

SyntheticPromptOpts carries daemon-owned synthetic prompt input plus wake-up metadata required for persistence and later reentry handling.

type ToolHooks

ToolHooks groups provider-native tool execution hook dispatch.

type TurnEndNotifier

type TurnEndNotifier func(sessionID string)

TurnEndNotifier is invoked once after a prompt turn finishes dispatching.

type TurnSource

type TurnSource string

TurnSource classifies the origin of a prompt turn inside the daemon runtime.

type Type

type Type string

Type identifies why a session was created.

const (
	SessionTypeUser        Type = "user"
	SessionTypeDream       Type = "dream"
	SessionTypeSystem      Type = "system"
	SessionTypeCoordinator Type = "coordinator"
	SessionTypeSpawned     Type = "spawned"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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