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
- Variables
- func ConfigFile(configDir string) string
- func LockFile(dataDir string) string
- func Osascript(ctx context.Context, title, body string) error
- func Plist(s PlistSpec) []byte
- func PlistPATH(otagBin, path string, tmpDirs []string, fnmDefault string) (string, []string)
- func Probe(dataDir string) (running bool, pid int, err error)
- func ReadPlistEnv(path string) (map[string]string, error)
- func RotateLog(path string, max int64, fds ...int) (bool, error)
- type AgentStatus
- type Config
- type Daemon
- type Launchd
- type Lock
- type PlistSpec
- type QuotaCollector
Constants ¶
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.
const Label = "io.github.nesiler.otag"
Label is the launchd label of the daemon.
const LogMaxBytes = 10 << 20
LogMaxBytes is the size at which the launch agent's log is rotated.
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).
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.
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 ¶
var Actor = run.Actor{Name: "daemon", Source: "daemon"}
Actor is how the daemon appears in events.
var ProofTimeouts = map[string]time.Duration{ adapter.ChanToolContext: 2 * time.Minute, adapter.ChanPromptContext: 2 * time.Minute, adapter.ChanModSubmit: 3 * time.Minute, adapter.ChanAPIStart: 10 * time.Minute, adapter.ChanAPISteer: 10 * time.Minute, adapter.ChanLaunchPrompt: 10 * time.Minute, adapter.ChanStopBlock: 30 * time.Minute, }
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 ¶
ConfigFile is the daemon's config file in the config dir.
func Plist ¶
Plist renders the launch agent: `otag daemon --service`, restarted by launchd only when it fails, logging to LogPath.
func PlistPATH ¶
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 ReadPlistEnv ¶
ReadPlistEnv returns the EnvironmentVariables of an installed agent (as written by Plist).
func RotateLog ¶
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.
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 ¶
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.
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 ¶
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.
type Lock ¶
type Lock struct {
Path string
// contains filtered or unexported fields
}
Lock is the held single-instance lock (flock on <data>/daemon.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 ¶
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.