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
- Variables
- type Kind
- type Monitor
- type Notification
- type Option
- type Outcome
- type OwnerIneligibleError
- type Owners
- type Record
- type Service
- func (s *Service) ActiveCounts(sessionIDs []string) map[string]int
- func (s *Service) Cancel(sessionID, id string) (Monitor, error)
- func (s *Service) CancelSession(sessionID string) int
- func (s *Service) Create(ctx context.Context, spec Spec) (Monitor, error)
- func (s *Service) List(sessionID string) []Monitor
- func (s *Service) Recover(ctx context.Context) error
- func (s *Service) Shutdown(ctx context.Context) error
- func (s *Service) SuspendSession(sessionID string) int
- type Spec
- type Status
- type Store
- type TerminalWatch
- type TerminalWatcher
- type Waker
Constants ¶
const ( UntilExit = "exit" UntilMatch = "match" )
Terminal wait conditions accepted by terminal monitors.
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.
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 ¶
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") )
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 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 ¶
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 WithObserver ¶
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 ¶
WithOwners lets the service capture owner bindings and resume owners during recovery.
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 ¶
ActiveCounts reports, per requested session, how many monitors still hold a slot (active or delivering). Sessions without one are omitted.
func (*Service) Cancel ¶
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 ¶
CancelSession stops every monitor of a stopped or removed session and drops its history; nothing it registered may wake a later incarnation.
func (*Service) List ¶
List returns the session's monitors, active first, newest first within each group.
func (*Service) Recover ¶
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) SuspendSession ¶
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 ¶
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.