monitor

package
v0.4.8 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package monitor owns daemon-native session monitors: durable-for-the-daemon watches that wake their owning agent session when a terminal exits, a terminal prints a pattern, or a timer elapses. Provider-internal background mechanisms (Claude Code Monitor/run_in_background, Codex background terminals) cannot start a Compozy turn, so the daemon owns the wake.

Index

Constants

View Source
const (
	UntilExit  = "exit"
	UntilMatch = "match"
)

Terminal wait conditions accepted by terminal monitors.

View Source
const (
	ReasonExit           = "exit"
	ReasonMatch          = "match"
	ReasonTimeout        = "timeout"
	ReasonStalled        = "stalled"
	ReasonTimerElapsed   = "timer_elapsed"
	ReasonTerminalFailed = "terminal_unavailable"
	// ReasonSessionStopped marks a monitor canceled because its owner was stopped on purpose.
	ReasonSessionStopped = "session_stopped"
	// ReasonOwnerPrefix prefixes the restart-eligibility reason that kept an owner from resuming.
	ReasonOwnerPrefix = "owner_"
)

Outcome reasons reported to the woken agent.

View Source
const (
	MaxDescriptionRunes    = 200
	MaxPatternRunes        = 512
	MaxActivePerSession    = 8
	MaxActivePerTerminal   = 4
	MaxActiveTotal         = 256
	DefaultTerminalTimeout = 30 * time.Minute
	MaxTerminalTimeout     = 6 * time.Hour
	MinTimerDelay          = 5 * time.Second
	MaxTimerDelay          = 24 * time.Hour
)

Bounds keep monitors cheap and prevent runaway wake loops.

Variables

View Source
var (
	// ErrInvalid reports a monitor spec that fails validation.
	ErrInvalid = errors.New("monitor: invalid spec")
	// ErrLimit reports that the owning session already has the maximum active monitors.
	ErrLimit = errors.New("monitor: active monitor limit reached")
	// ErrNotFound reports an unknown monitor id for the session.
	ErrNotFound = errors.New("monitor: not found")
	// ErrStopped reports that the service is shutting down.
	ErrStopped = errors.New("monitor: service stopped")
	// ErrSessionGone reports a permanent wake refusal: the owning session is stopped or removed.
	ErrSessionGone = errors.New("monitor: owning session is not active")
)
View Source
var ErrOwnerStopped = errors.New("monitor: owner was stopped on purpose")

ErrOwnerStopped reports that the owner was stopped on purpose (an operator or agent decision), so its monitors must not outlive that decision.

Functions

This section is empty.

Types

type Kind

type Kind string

Kind selects what a monitor watches.

const (
	// KindTerminal watches one integrated terminal for exit or an output match.
	KindTerminal Kind = "terminal"
	// KindTimer fires once after a delay.
	KindTimer Kind = "timer"
)

type Monitor

type Monitor struct {
	ID          string    `json:"monitor_id"`
	SessionID   string    `json:"session_id"`
	Kind        Kind      `json:"kind"`
	Description string    `json:"description"`
	TerminalID  string    `json:"terminal_id,omitempty"`
	Until       string    `json:"until,omitempty"`
	Pattern     string    `json:"pattern,omitempty"`
	Status      Status    `json:"status"`
	CreatedAt   time.Time `json:"created_at"`
	DeadlineAt  time.Time `json:"deadline_at"`
	FiredAt     time.Time `json:"fired_at,omitzero"`
	Reason      string    `json:"reason,omitempty"`
	ExitCode    *int      `json:"exit_code,omitempty"`
	// Reused marks a Create that returned an already-active identical terminal
	// monitor instead of registering a duplicate wake. It is not part of the wire shape.
	Reused bool `json:"-"`
}

Monitor is the observable state of one monitor.

type Notification

type Notification struct {
	Monitor Monitor
	Outcome Outcome
}

Notification is one fired monitor delivered to its owning session.

func (Notification) Message

func (n Notification) Message() string

Message renders the wake prompt the woken agent receives. It mirrors the provider conventions agents already follow for background-task wakes: an explicit not-user-input header, a structured block, then the next action.

type Option

type Option func(*Service)

Option configures a Service.

func WithClock

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

WithClock overrides the wall clock used for timestamps and retention.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the service logger.

func WithObserver

func WithObserver(observe func(ctx context.Context, sessionID string)) Option

WithObserver registers a callback for every change to a session's monitors: one starts, fires, is canceled, delivered, or abandoned. Calls run one at a time on a service-owned goroutine with a bounded context, never on the caller's path, and stop when the service shuts down. Changes that arrive while a session's refresh is still pending coalesce into that one call.

func WithOwners

func WithOwners(owners Owners) Option

WithOwners lets the service capture owner bindings and resume owners during recovery.

func WithStore

func WithStore(store Store) Option

WithStore makes monitors durable across daemon restarts.

type Outcome

type Outcome struct {
	Reason   string
	ExitCode *int
	// Output is untrusted terminal text; empty for timers.
	Output string
	// OutputLost marks a wake re-delivered after a restart: the terminal output it carried was not retained.
	OutputLost bool
}

Outcome is what a fired monitor observed.

type OwnerIneligibleError

type OwnerIneligibleError struct{ Reason string }

OwnerIneligibleError reports that a restart-stopped owner may not be resumed automatically. Reason is the session restart-eligibility reason.

func (*OwnerIneligibleError) Error

func (e *OwnerIneligibleError) Error() string

type Owners

type Owners interface {
	Binding(ctx context.Context, sessionID string) (string, error)
	Resume(ctx context.Context, sessionID, binding string) error
}

Owners resolves the session that owns a monitor. Binding captures the owner's restart-eligibility snapshot while it is live; Resume makes a restart-stopped owner able to receive a wake, or returns ErrOwnerStopped, ErrSessionGone, or an *OwnerIneligibleError.

type Record

type Record struct {
	Monitor      Monitor
	WorkspaceID  string
	ProfileID    string
	Timeout      time.Duration
	OwnerBinding string
	// OwnerCheckFailedAt is when a recovering monitor's owner check first failed transiently; zero
	// otherwise. It anchors the retry horizon across restarts.
	OwnerCheckFailedAt time.Time
	Version            int64
}

Record is the durable form of one monitor. It carries the definition and lifecycle state needed to restore a watch after a daemon restart; terminal output is never stored. Version orders writes made without holding the service lock, so a stale write can never overwrite a newer one.

type Service

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

Service owns every live monitor and the goroutines that watch them. State is indexed by owning session; active monitors are capped per session, per terminal, and per daemon, and finished ones expire after finishedRetention.

func NewService

func NewService(ctx context.Context, terminals TerminalWatcher, waker Waker, opts ...Option) (*Service, error)

NewService builds a monitor service bound to a daemon lifetime context.

func (*Service) ActiveCounts

func (s *Service) ActiveCounts(sessionIDs []string) map[string]int

ActiveCounts reports, per requested session, how many monitors still hold a slot (active or delivering). Sessions without one are omitted.

func (*Service) Cancel

func (s *Service) Cancel(sessionID, id string) (Monitor, error)

Cancel stops one active or delivering monitor owned by sessionID without waking the session. The monitor is canceled in memory at once and can no longer wake; the call reports an error until the cancellation is durable, and the service keeps retrying the write in the background, so a failed write never depends on a later caller.

func (*Service) CancelSession

func (s *Service) CancelSession(sessionID string) int

CancelSession stops every monitor of a stopped or removed session and drops its history; nothing it registered may wake a later incarnation.

func (*Service) Create

func (s *Service) Create(ctx context.Context, spec Spec) (Monitor, error)

Create validates spec, starts watching, and returns the active monitor.

func (*Service) List

func (s *Service) List(sessionID string) []Monitor

List returns the session's monitors, active first, newest first within each group.

func (*Service) Recover

func (s *Service) Recover(ctx context.Context) error

Recover restores durable monitors after a daemon restart. It never reruns a command: a timer resumes on its original deadline, a monitor that had already fired is re-delivered under its stable message id, and a terminal that no longer exists fires terminal_unavailable. A monitor whose owner was stopped on purpose is canceled; one whose owner cannot be resumed is recorded as interrupted, visibly, without a wake.

func (*Service) Shutdown

func (s *Service) Shutdown(ctx context.Context) error

Shutdown cancels every monitor and waits for watcher goroutines.

func (*Service) SuspendSession

func (s *Service) SuspendSession(sessionID string) int

SuspendSession stops the in-memory watches of an owner the daemon is interrupting for a restart, keeping every monitor durable so Recover can restore it. Each monitor keeps the owner binding captured while the owner was live: a stopped session no longer carries a complete route, so a snapshot taken at stop time would be degraded.

type Spec

type Spec struct {
	WorkspaceID string
	ProfileID   string
	SessionID   string
	Kind        Kind
	Description string
	TerminalID  string
	Until       string
	Pattern     string
	// Timeout bounds terminal monitors; on expiry the monitor still fires with ReasonTimeout.
	Timeout time.Duration
	// Delay is the timer monitor duration.
	Delay time.Duration
}

Spec describes one monitor request from an agent session.

type Status

type Status string

Status is the lifecycle state of one monitor.

const (
	StatusActive Status = "active"
	// StatusDelivering means the monitor fired and its wake is retrying a transient refusal.
	StatusDelivering Status = "delivering"
	// StatusFired means the wake was admitted to the owning session's input queue.
	StatusFired    Status = "fired"
	StatusCanceled Status = "canceled"
	// StatusUndelivered means the monitor fired but its owning session could not be woken.
	StatusUndelivered Status = "undelivered"
	// StatusInterrupted means a daemon restart ended the watch and the owner could not be
	// resumed, so no wake was sent. Reason says why.
	StatusInterrupted Status = "interrupted"
)

type Store

type Store interface {
	// SaveMonitor upserts the record; a write whose Version is not newer than the stored one is ignored.
	SaveMonitor(ctx context.Context, record Record) error
	// LoadMonitors returns every persisted monitor.
	LoadMonitors(ctx context.Context) ([]Record, error)
	// PruneFinishedMonitors deletes finished monitors that fired before cutoff.
	PruneFinishedMonitors(ctx context.Context, cutoff time.Time) error
}

Store persists monitors so they survive a daemon restart.

type TerminalWatch

type TerminalWatch func(ctx context.Context) (Outcome, error)

TerminalWatch blocks until the watched terminal condition resolves or ctx ends.

type TerminalWatcher

type TerminalWatcher interface {
	WatchTerminal(ctx context.Context, spec Spec) (TerminalWatch, error)
}

TerminalWatcher resolves a terminal at creation time and returns the blocking watch.

type Waker

type Waker interface {
	WakeSession(ctx context.Context, notification Notification) error
}

Waker admits one fired monitor to its owning session. It returns as soon as the wake is queued; ErrSessionGone marks a permanent refusal, and any other error is retried as transient.

Jump to

Keyboard shortcuts

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