daemon

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package daemon is otag's background service (`otag daemon`, run by launchd): every tick it runs the quota collectors, reaps runs whose pane died, stops stalled runs, reminds about unanswered questions, starts fallback runs on another profile after a usage limit or a harness that would not launch, and shows new notifications. Everything it does goes through the same transactions as the CLI, so it may be down at any time without losing state. See docs/DAEMON.md.

Index

Constants

View Source
const ExitTimeOut = 150

ExitTimeOut is how long launchd waits after SIGTERM before SIGKILL; longer than a tick (TickTimeout), so a fallback launch in progress is never cut in half.

View Source
const Label = "io.github.nesiler.otag"

Label is the launchd label of the daemon.

View Source
const LogMaxBytes = 10 << 20

LogMaxBytes is the size at which the launch agent's log is rotated.

View Source
const MessagesBudget = 5 * time.Second

MessagesBudget bounds the dispatch part of one tick, so the other loops stay responsive: no attempt starts with less than minSendBudget of it left, and each adapter call gets at most what is left (a hung harness server cannot hold the tick; a call cut short has an unknown outcome, like any send that never answered).

View Source
const ServiceFlag = "--service"

ServiceFlag is the `otag daemon` flag the launch agent passes: permanent startup problems (invalid config, schema too new, another daemon holds the lock) then exit 0, so launchd (KeepAlive SuccessfulExit=false) does not restart the daemon every 10 s, and the daemon rotates its own log.

View Source
const TickTimeout = 2 * time.Minute

TickTimeout bounds one tick (a fallback launch included). ExitTimeOut of the launch agent is longer, so launchd never kills the daemon in the middle of a tick.

Variables

View Source
var Actor = run.Actor{Name: "daemon", Source: "daemon"}

Actor is how the daemon appears in events.

ProofTimeouts: a delivery dispatched longer ago than this on the channel without a proof becomes outcome_unknown (never re-sent automatically). Hook context is proven as it is printed, a mod submit within seconds; a steer waits for a step boundary and a Stop block for the end of the continued turn.

Functions

func ConfigFile

func ConfigFile(configDir string) string

ConfigFile is the daemon's config file in the config dir.

func LockFile

func LockFile(dataDir string) string

LockFile is the single-instance lock in the data dir; it holds the daemon's pid.

func Osascript

func Osascript(ctx context.Context, title, body string) error

Osascript shows a macOS notification.

func Plist

func Plist(s PlistSpec) []byte

Plist renders the launch agent: `otag daemon --service`, restarted by launchd only when it fails, logging to LogPath.

func PlistPATH

func PlistPATH(otagBin, path string, tmpDirs []string, fnmDefault string) (string, []string)

PlistPATH joins otag's binary dir in front of path, dropping duplicates and entries that will not exist for long: relative ones (".", ""), fnm's per-shell `fnm_multishells` links (replaced by fnmDefault, fnm's default alias, when given and present) and directories under a temporary directory (tmpDirs). launchd gives agents only /usr/bin:/bin:/usr/sbin:/sbin, without tmux or the harnesses. It also returns the dropped entries.

func Probe

func Probe(dataDir string) (running bool, pid int, err error)

Probe reports whether a daemon holds the lock, and its pid.

func ReadPlistEnv

func ReadPlistEnv(path string) (map[string]string, error)

ReadPlistEnv returns the EnvironmentVariables of an installed agent (as written by Plist).

func RotateLog

func RotateLog(path string, max int64, fds ...int) (bool, error)

RotateLog keeps the daemon log bounded. launchd opens StandardOutPath/ StandardErrorPath itself and hands the daemon the descriptors, so when path is larger than max, RotateLog renames it to path.1 (replacing an older one), creates a new path (0600) and points fds (1 and 2 for the daemon) at it with dup2, so the logger and panics write to the new file. It reports whether it rotated.

Types

type AgentStatus

type AgentStatus struct {
	Installed bool   `json:"installed"`
	Loaded    bool   `json:"loaded"`
	Plist     string `json:"plist"`
}

AgentStatus describes the launch agent.

type Config

type Config struct {
	Tick              time.Duration            // loop interval; default 3s
	DeadGrace         time.Duration            // a pane must stay dead this long before the run is reaped; default 5s
	StallAfter        time.Duration            // running with no event this long = stalled; default 20m
	StallAfterHarness map[string]time.Duration // per-harness override of StallAfter
	// ToolStallAfter replaces the stall limit while a tool call runs (more tool starts
	// than ends in the current turn): a long command or build emits no events; default 45m.
	ToolStallAfter time.Duration
	// StallPaneActivity counts output of the run's pane (tmux window_activity) as a
	// heartbeat. Off by default: a TUI that animates a spinner would never stall.
	StallPaneActivity bool
	UnansweredAfter   time.Duration // waiting this long = one "unanswered" notification; default 10m
	// LaunchTimeout ends a queued or starting run that has no pane recorded after this
	// long (its launcher was killed) as launch_failed; default 5m.
	LaunchTimeout  time.Duration
	MaxAttempts    int           // runs per fallback chain before the task is blocked; default 3
	QuotaThreshold float64       // quota used_percent that makes a profile unavailable; default 90
	QuotaInterval  time.Duration // how often the quota collectors run; default 60s
	FallbackOn     []string      // ended reasons that start a fallback run; default quota, launch_failed
	DesktopNotify  bool          // show notifications with osascript; default true
	// EnvPassthrough names extra environment variables `otag daemon install` copies
	// into the launch agent (API keys for OpenCode {env:VAR}, ...); a trailing * is a
	// prefix match. Read at install time only.
	EnvPassthrough []string
	// RawPayloads stores hook payloads themselves (secrets redacted, long strings
	// clipped) for debugging; off, raw_hook_payloads keeps a compact extract of ids and
	// kinds only. Read by the hook bridge on every hook.
	RawPayloads bool
	// RawPayloadRetention deletes raw_hook_payloads rows older than this; 0 keeps
	// them. Default 7 days.
	RawPayloadRetention time.Duration

	// ParkAfter parks an idle run whose question has been unanswered this long (the
	// session closes, the answer resumes it); 0 = only `otag ask --park` parks. Default 30m.
	ParkAfter time.Duration
	// IdleAfter: a child or review run idle this long without an open question gets a
	// reminder (at most 2, then the human is told); 0 = off. Default 10m.
	IdleAfter time.Duration
}

Config is the daemon section of <config>/otag.toml. Every key is optional.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the defaults.

func LoadConfig

func LoadConfig(path string) (Config, []string, error)

LoadConfig reads the daemon section of path over the defaults; a missing file means defaults. Unknown keys under daemon are returned as warnings; other sections belong to other parts of otag.

type Daemon

type Daemon struct {
	DB         *db.DB
	Runs       *run.Manager
	Config     Config
	Collectors []QuotaCollector
	Now        func() time.Time                                    // default time.Now
	Desktop    func(ctx context.Context, title, body string) error // default osascript
	Log        *log.Logger                                         // default discards
	// Housekeeping, when set, runs after every tick of Run (log rotation).
	Housekeeping func()
	// contains filtered or unexported fields
}

Daemon runs the loops. Runs must use Actor{Name: "daemon", Source: "daemon"}.

func (*Daemon) Collect

func (d *Daemon) Collect(ctx context.Context)

Collect runs every quota collector when they are due: on the first call, then at most once per QuotaInterval. Errors are logged. Run calls it from its own goroutine; `otag daemon --once` calls it before its tick.

func (*Daemon) Run

func (d *Daemon) Run(ctx context.Context) error

Run ticks until ctx is cancelled. A tick in progress is finished (bounded) before Run returns, so a fallback launch is never cut in half by a shutdown. The quota collectors run in a goroutine of their own and are cancelled at shutdown.

func (*Daemon) Tick

func (d *Daemon) Tick(ctx context.Context)

Tick runs the run loops once (not the quota collectors, see Collect). Errors are logged; one failing loop does not stop the others.

type Launchd

type Launchd struct {
	Home      string // the agent goes to Home/Library/LaunchAgents
	Launchctl string // default "launchctl"
	UID       int
	// Wait bounds how long Install waits for a booted-out agent to disappear, and the
	// pause between bootstrap retries is derived from it; default 10s.
	Wait time.Duration
}

Launchd installs and removes the launch agent of one user.

func (Launchd) Install

func (l Launchd) Install(ctx context.Context, s PlistSpec) (string, error)

Install writes the agent (replacing an older one; 0600, it may hold passed-through variables), unloads an older instance and waits until it is gone, then loads the new one with `launchctl bootstrap gui/<uid>`, retrying while launchd still tears the old one down.

func (Launchd) PlistFile

func (l Launchd) PlistFile() string

PlistFile is the agent's path.

func (Launchd) Status

func (l Launchd) Status(ctx context.Context) AgentStatus

Status reports whether the agent file exists and launchd has it loaded.

func (Launchd) Uninstall

func (l Launchd) Uninstall(ctx context.Context) (removed bool, err error)

Uninstall unloads the agent (`launchctl bootout`) and removes its file. It is not an error when the agent is not loaded or not installed; any other bootout failure is.

type Lock

type Lock struct {
	Path string
	// contains filtered or unexported fields
}

Lock is the held single-instance lock (flock on <data>/daemon.lock).

func Acquire

func Acquire(dataDir string) (*Lock, error)

Acquire takes the lock or fails with CONFLICT when another daemon holds it. The file is kept on release (removing it would race with a starting daemon).

func (*Lock) Release

func (l *Lock) Release() error

Release drops the lock.

type PlistSpec

type PlistSpec struct {
	OtagBin string            // absolute path of the otag binary
	LogPath string            // stdout and stderr: <data>/daemon.log
	Env     map[string]string // EnvironmentVariables (PATH, OTAG_*, passed-through variables)
}

PlistSpec describes the launch agent.

type QuotaCollector

type QuotaCollector interface {
	Collect(ctx context.Context) error
}

QuotaCollector refreshes quota_snapshots and account/profile cooldowns (phase 3b). Run calls every collector from a goroutine of its own, on its first round and then at most once per Config.QuotaInterval, so a slow network or Keychain call never delays the pane and stall checks; an error is logged.

Jump to

Keyboard shortcuts

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