schedule

package
v0.52.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package schedule stores conversation-scoped scheduled prompts and fires them back into the conversation they were created in.

Why a relay needs this at all

Host-level cron (and its friendlier cousins) can already run a command at a time. What it cannot do is deliver into a CONVERSATION: a scheduled prompt here re-enters the same conv the schedule was created from, so the agent answering it has the topic's whole history, and its answer streams into that topic through the relay's ordinary path. That context is the entire reason this exists, and it is why "just shell out to cron" is the wrong layer. Host chores stay in host cron; only conversation-scoped work belongs here.

Shape

A Store owns a JSON file, a tick loop, and a Fire callback supplied by the relay. Fire is called SYNCHRONOUSLY for the whole turn the scheduled prompt starts — it must not return until that turn is over — because that is what lets the store know which schedule a call to Add or Retime made during the turn belongs to.

Runaway control

A scheduled prompt costs real money every time it fires, but the agent, not a heuristic, judges when a wait is done: it unschedules. The store only bounds what the operator configures:

  • Every item has a budget: Until (default 24h after arming, at most MaxUntil) and MaxFires (default DefaultMaxFires). The item is removed when either is spent.
  • A scheduled turn may re-time and re-budget its own item (Retime; an ETA moved out) and add one-shots (Add) that inherit the parent's remaining budget; it may not start a new repeat.
  • Fire reports whether the turn was silent. Each silent fire doubles the next interval, up to Config.MaxBackoff; a non-silent fire or a re-time resets it. Config.SilentLimit, off by default, stops an item after that many silent fires in a row.
  • When the store stops an item it fires one more turn that tells the agent (Item.Stop, InformText). That turn may arm a repeat with a fresh budget; Config.MaxRearms caps how often a chain does so.
  • MaxPerConv and MaxTotal cap how many items can be armed at once, and MinInterval floors a repeat.

Attribution starts when Fire is CALLED, not when the turn it starts begins, so a relay that makes Fire queue behind a human turn will treat that human turn as scheduled. That over-restricts rather than under-restricts, which is the direction a safety bound should err in.

None of that removes the need for a human to be able to LOOK: List is what the relay's `!schedules` command renders, and Remove is what kills one.

Index

Constants

View Source
const (
	DefaultMaxPerConv  = 10
	DefaultMaxTotal    = 100
	DefaultMinInterval = time.Minute
	DefaultTick        = time.Second
	// DefaultUntil is how long a budget lasts when the caller names no
	// deadline.
	DefaultUntil = 24 * time.Hour
	// MaxUntil is the furthest deadline any budget may have.
	MaxUntil = 7 * 24 * time.Hour
	// DefaultMaxFires is how many fires a budget allows when the caller
	// names no count.
	DefaultMaxFires = 20
	// DefaultMaxBackoff is Config.MaxBackoff when the relay sets none.
	DefaultMaxBackoff = 6 * time.Hour

	// MaxTextLen bounds one scheduled prompt. A schedule is stored
	// and replayed unattended; an unbounded blob is a way to make every
	// future turn expensive by accident.
	MaxTextLen = 4000
)

Defaults for Config. Every one of these is a safety bound, not a tuning knob; raise them deliberately.

Variables

View Source
var ErrGone = errors.New("schedule: conversation is gone")

ErrGone is returned by a Fire callback whose conversation no longer exists — retired with `!new`, or in a channel the relay has stopped serving. The item is removed rather than retried: a schedule for a conversation nobody can reach is pure cost.

Functions

func InformText added in v0.52.0

func InformText(it Item, why Stop) string

InformText is the prompt of the turn that tells the agent its schedule stopped. The agent decides what happens next: arm a new schedule (this turn may, with a fresh budget) or be done.

Types

type Budget added in v0.51.0

type Budget struct {
	Until    time.Time
	MaxFires int
}

Budget bounds one item. Zero fields mean the store's defaults.

type Config

type Config struct {
	// Path is the JSON file the store persists to. Required.
	Path string
	// Fire delivers one due item into its conversation. It MUST block
	// for the whole turn the prompt starts; see the package doc.
	// Returning ErrGone removes the item. Required.
	Fire func(ctx context.Context, it Item) (Result, error)
	// Stopped, when set, is told about every item the store removes on
	// its own (budget spent, silent streak). It is called without the
	// store's lock held. The agent itself is told through a
	// stop-informed fire (see MaxRearms), not through Stopped.
	Stopped func(it Item, why Stop)

	// MaxPerConv, MaxTotal and MinInterval bound runaway scheduling;
	// zero means the corresponding Default above.
	MaxPerConv  int
	MaxTotal    int
	MinInterval time.Duration
	// DefaultUntil and DefaultMaxFires are a fresh budget's defaults;
	// zero means the package defaults. DefaultUntil is capped at
	// MaxUntil.
	DefaultUntil    time.Duration
	DefaultMaxFires int
	// SilentLimit, when positive, stops an item after that many
	// silent fires in a row (StopSilent); the agent is then informed.
	// Zero or negative disables it.
	SilentLimit int
	// MaxBackoff caps how far silent fires stretch a repeat's interval
	// (doubling once per silent fire). Zero means DefaultMaxBackoff;
	// negative disables backoff, so a repeat always fires every Every.
	MaxBackoff time.Duration
	// MaxRearms caps stop-informed turns per chain. When the store
	// stops an item it fires one more turn in its conversation whose
	// Item has Stop set and Text = InformText, so the agent can arm a
	// new schedule (with a fresh budget) or be done. Zero means no cap;
	// a positive N skips the informed turn once a chain has been
	// re-armed N times; negative never informs.
	MaxRearms int

	// Tick is how often the loop looks for due items. Zero means
	// DefaultTick. Ignored when Ticks is set.
	Tick time.Duration
	// Ticks, when non-nil, replaces the internal ticker. Tests drive
	// it by hand so no test ever waits on a wall clock.
	Ticks <-chan time.Time

	// Now is the clock. Defaults to time.Now.
	Now func() time.Time
	// Logf receives operational messages.
	Logf func(format string, args ...any)
}

Config configures a Store.

type Item

type Item struct {
	// ID is short, opaque and unique across the store. It is what a
	// human types into `!unschedule`.
	ID string `json:"id"`
	// Conv is the relay's opaque conversation token, exactly as the
	// command broker uses it. The store never parses it.
	Conv string `json:"conv"`
	// Text is the prompt injected into the conversation on fire.
	Text string `json:"text"`
	// At is when it next fires (UTC).
	At time.Time `json:"at"`
	// Every, when non-zero, is the base repeat interval.
	Every time.Duration `json:"every,omitempty"`
	// Fires counts claimed fires, so a human can see a repeat working.
	Fires int `json:"fires,omitempty"`
	// Until is the budget's deadline (UTC): no fire happens after it.
	Until time.Time `json:"until"`
	// MaxFires is the budget's fire count: the item is removed once
	// Fires reaches it.
	MaxFires int `json:"max_fires"`
	// Silent is the current run of silent fires.
	Silent int `json:"silent,omitempty"`
	// Created is when the item was armed (UTC).
	Created time.Time `json:"created"`
	// Rearms counts how many stop-informed turns this chain has gone
	// through: an item armed in such a turn has the stopped item's
	// Rearms plus one, and a one-shot child inherits its parent's.
	Rearms int `json:"rearms,omitempty"`
	// Stop is set only on the item handed to Config.Fire for a
	// stop-informed turn (its Text is then InformText); never stored.
	Stop Stop `json:"-"`
}

Item is one armed schedule. It is the type both front ends speak — the relay's `!schedules` listing and the agent's list_schedules tool — so there is exactly one shape and nothing to drift.

func (Item) FiresLeft added in v0.51.0

func (i Item) FiresLeft() int

FiresLeft is how many fires the budget still allows.

func (Item) Interval added in v0.51.0

func (i Item) Interval(maxBackoff time.Duration) time.Duration

Interval is the gap before the next repeat: Every doubled once per silent fire in the current streak, capped at maxBackoff (or Every, when that is larger). maxBackoff <= 0 means no backoff. Zero for a one-shot.

func (Item) MarshalJSON

func (i Item) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Item) UnmarshalJSON

func (i *Item) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Result added in v0.51.0

type Result struct {
	// Silent is true when the turn had nothing worth posting (a
	// heartbeat, an explicit silent marker).
	Silent bool
}

Result is what a Fire callback reports about the turn it ran.

type Stop added in v0.51.0

type Stop string

Stop says why the store removed an item on its own.

const (
	// StopSilent: Config.SilentLimit silent fires in a row.
	StopSilent Stop = "silent"
	// StopFires: MaxFires spent.
	StopFires Stop = "fires"
	// StopUntil: the deadline passed.
	StopUntil Stop = "until"
)

Reasons passed to Config.Stopped and set on a stop-informed Item.

type Store

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

Store is the persisted set of armed schedules. Safe for concurrent use.

func Open

func Open(cfg Config) (*Store, error)

Open loads the store at cfg.Path, creating an empty one when the file does not exist. A corrupt file is an error, not a silent reset: an operator must see that armed work was lost. An older file is migrated and rewritten in the current format.

func (*Store) Add

func (s *Store) Add(conv, text string, at time.Time, every time.Duration, b Budget) (Item, error)

Add arms a new schedule for conv.

Called from a turn a schedule started (in the same conversation), Add only arms a one-shot, and that one-shot inherits the parent's remaining budget; b can only tighten it. Called from any other turn it arms a fresh budget from b.

func (*Store) List

func (s *Store) List(conv string) []Item

List returns the armed items for conv, soonest first. An empty conv lists every conversation's, which is what an operator wants.

func (*Store) Rekey added in v0.43.0

func (s *Store) Rekey(from, to string) (int, error)

Rekey moves every item armed for conversation from to conversation to, and returns how many it moved.

A relay whose conversation token can change — zulip-acp keys a conversation by its topic, and a topic can be renamed — calls it when the token changes. Without it, every item armed for the old token fires into a conversation that no longer exists and is dropped as gone.

The fires that run in from right now move too, so a schedule that a running scheduled turn arms after the move is still attributed to its parent. A move is not an arm: MaxPerConv is not checked, so nothing armed is lost when two conversations become one.

from == to, or an empty token, is a no-op.

func (*Store) Remove

func (s *Store) Remove(conv, id string) error

Remove disarms an item. conv scopes the lookup: a conversation can only ever cancel its own schedules, which matters because the id is short and a caller could otherwise guess into another conversation. An empty conv removes by id regardless of owner (operator scope).

func (*Store) Retime added in v0.51.0

func (s *Store) Retime(conv, id string, at time.Time, every time.Duration, b Budget) (Item, error)

Retime moves an armed item to at and sets its repeat to every.

Called from a turn a schedule started, it may only touch that schedule (or a one-shot the same turn armed), keeps the budget, and b must be zero. Called from any other turn it arms a fresh budget from b and clears the silent streak.

func (*Store) Run

func (s *Store) Run(ctx context.Context)

Run drives the fire loop until ctx is done. It returns once every in-flight fire has finished, so a relay can shut down cleanly.

Jump to

Keyboard shortcuts

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