monitor

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 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"
)

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")
)

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"`
}

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.

type Outcome

type Outcome struct {
	Reason   string
	ExitCode *int
	// Output is untrusted terminal text; empty for timers.
	Output string
}

Outcome is what a fired monitor observed.

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.

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) Shutdown

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

Shutdown cancels every monitor and waits for watcher goroutines.

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"
)

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