Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504package loginservice
import ( "bytes" "context" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "runtime" "slices" "strconv" "strings" "time")
const daemonMarker = "# albedo daemon service v1\n"
type DaemonUnit struct { path, name, home string declarative bool}
func ForDaemon(home string) (DaemonUnit, error) { service, err := For("daemon", home) if err != nil { return DaemonUnit{}, err } return DaemonUnit{path: service.path, name: service.name, home: home}, nil}
type ServiceFileKind string
const ( AbsentFile ServiceFileKind = "absent" OwnedFile ServiceFileKind = "owned" ForeignFile ServiceFileKind = "foreign" // DeclaredFile means a file exists under the stable declarative name. Its // content is never read: the loaded registration is what the CLI controls. DeclaredFile ServiceFileKind = "declared")
type Definition struct { Environment map[string]string Executable string}
type Observation struct { // Launchd.Definition is the loaded registration; drift compares it with Definition. Launchd *LaunchdObservation Properties map[string]string Info os.FileInfo // Definition is parsed from an owned service file; for a declarative unit // it is the loaded definition, so file-versus-loaded drift never applies. Definition Definition LoadedDefinition Definition File ServiceFileKind Problem string Data []byte Available bool}
func (s DaemonUnit) Name() string { return s.name }func (s DaemonUnit) Path() string { return s.path }
func (s DaemonUnit) Run(ctx context.Context, verb string) error { if runtime.GOOS == "darwin" { return errors.New("systemd operations are unavailable under launchd") } budget := 15 * time.Second if verb == "stop" { budget = 60 * time.Second } _, err := s.command(ctx, budget, verb, s.name) return err}
func (s DaemonUnit) Reload(ctx context.Context) error { if runtime.GOOS == "darwin" { return errors.New("systemd operations are unavailable under launchd") } _, err := s.command(ctx, 15*time.Second, "daemon-reload") return err}
func (s DaemonUnit) command(ctx context.Context, budget time.Duration, args ...string) (string, error) { name := os.Getenv("ALBEDO_SYSTEMCTL") if name == "" { name = "systemctl" } ctx, cancel := context.WithTimeout(ctx, budget) defer cancel() output, err := exec.CommandContext(ctx, name, append([]string{"--user"}, args...)...).CombinedOutput() if err != nil { return "", fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(output))) } return string(output), nil}
const properties = "LoadState,ActiveState,SubState,MainPID,InvocationID,Job,FragmentPath,DropInPaths,TriggeredBy,ExecStart,ExecCondition,ExecStartPre,ExecStartPost,ExecStop,ExecStopPost,Environment,EnvironmentFiles,KillMode,Restart,RestartUSec,RestartPreventExitStatus,RestartForceExitStatus,NeedDaemonReload,Type,ExitType,RemainAfterExit,KillSignal,SendSIGHUP,SendSIGKILL,FinalKillSignal,TimeoutStopUSec,TimeoutStopFailureMode,StartLimitIntervalUSec,StartLimitBurst,StandardOutput,StandardError,UnitFileState,Result,NRestarts,ExecMainStatus"
func (s DaemonUnit) observe(ctx context.Context) (Observation, error) { if runtime.GOOS == "darwin" { return s.observeLaunchd(ctx) } observation := Observation{File: AbsentFile, Properties: map[string]string{}} if runtime.GOOS != "linux" { return observation, nil } info, err := os.Lstat(s.path) if err == nil { observation.Info = info switch { case s.declarative: observation.File = DeclaredFile case info.Mode().IsRegular(): observation.File = ForeignFile observation.Data, err = readServiceFile(s.path) if err != nil { return observation, err } if bytes.HasPrefix(observation.Data, []byte(daemonMarker)) { observation.File = OwnedFile if observation.Definition, err = s.parseDefinition(observation.Data); err != nil { observation.Problem = err.Error() } } default: observation.File = ForeignFile } } else if !errors.Is(err, os.ErrNotExist) { return observation, err } name := os.Getenv("ALBEDO_SYSTEMCTL") if name == "" { name = "systemctl" } if _, err = exec.LookPath(name); (errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist)) && observation.File == AbsentFile { return observation, nil } if observation.File == AbsentFile && os.Getenv("ALBEDO_SYSTEMCTL") == "" { if _, bootErr := os.Stat("/run/systemd/system"); errors.Is(bootErr, os.ErrNotExist) { return observation, nil } } output, err := s.command(ctx, 15*time.Second, "show", s.name, "--all", "--property="+properties) if err != nil { return observation, err } observation.Available = true for line := range strings.SplitSeq(output, "\n") { key, value, ok := strings.Cut(line, "=") if ok { observation.Properties[key] = value } } if observation.Properties["LoadState"] == "" { return observation, errors.New("systemctl returned no unit load state") } if (observation.File == OwnedFile || observation.File == DeclaredFile) && observation.Problem == "" && observation.Properties["LoadState"] == "loaded" { observation.LoadedDefinition, observation.Problem = s.loadedContract(observation) if s.declarative && observation.Problem == "" { observation.Definition = observation.LoadedDefinition } } return observation, nil}
const serviceFileLimit = 64 * 1024
func readServiceFile(path string) ([]byte, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() data, err := io.ReadAll(io.LimitReader(file, serviceFileLimit+1)) if err != nil { return nil, err } if len(data) > serviceFileLimit { return nil, fmt.Errorf("service file exceeds 64 KiB: %s", path) } return data, nil}
func (s DaemonUnit) Render(definition Definition) ([]byte, error) { if runtime.GOOS == "darwin" { return s.renderLaunchd(definition) } if !filepath.IsAbs(definition.Executable) || strings.ContainsAny(definition.Executable, "\x00\n\r;{}") { return nil, errors.New("service requires an absolute executable path without control characters or semicolons/braces") } if definition.Environment["ALBEDO_HOME"] != s.home { return nil, errors.New("service home does not match") } var data strings.Builder fmt.Fprintf(&data, "%s[Unit]\nDescription=albedo daemon\nStartLimitIntervalSec=60\nStartLimitBurst=5\n\n[Service]\nType=exec\nExecStart=:%s daemon --serve\n", daemonMarker, unitQuote(definition.Executable)) keys := make([]string, 0, len(definition.Environment)) for key := range definition.Environment { keys = append(keys, key) } slices.Sort(keys) for _, key := range keys { if key != "ALBEDO_HOME" && key != "PATH" && key != "ALBEDO_DAEMON" && key != "ALBEDO_ROOT" { return nil, fmt.Errorf("unsupported service environment key %s", key) } if strings.ContainsAny(definition.Environment[key], "\x00\n\r") { return nil, fmt.Errorf("invalid service environment value for %s", key) } fmt.Fprintln(&data, "Environment="+unitQuote(key+"="+definition.Environment[key])) } fmt.Fprintf(&data, "KillMode=process\nRestart=on-failure\nRestartSec=3\nRestartPreventExitStatus=75\nTimeoutStopSec=45\nStandardOutput=%s\nStandardError=%s\n\n[Install]\nWantedBy=default.target\n", strings.ReplaceAll("append:"+filepath.Join(s.home, "daemon.log"), "%", "%%"), strings.ReplaceAll("append:"+filepath.Join(s.home, "daemon.log"), "%", "%%")) return []byte(data.String()), nil}
func (s DaemonUnit) Capture() (Definition, error) { executable, err := Executable() if err != nil { return Definition{}, err } definition := Definition{Executable: executable, Environment: map[string]string{"ALBEDO_HOME": s.home}} for _, key := range []string{"PATH", "ALBEDO_DAEMON", "ALBEDO_ROOT"} { value := os.Getenv(key) if value != "" && (key != "ALBEDO_DAEMON" || !strings.HasPrefix(value, "/nix/store/")) { definition.Environment[key] = value } } return definition, nil}
func (s DaemonUnit) parseDefinition(data []byte) (Definition, error) { definition := Definition{Environment: map[string]string{}} for line := range strings.SplitSeq(string(data), "\n") { if value, ok := strings.CutPrefix(line, "Environment="); ok { assignment, err := strconv.Unquote(value) if err != nil { return definition, errors.New("unrecognized unit environment") } key, value, ok := strings.Cut(strings.ReplaceAll(assignment, "%%", "%"), "=") if !ok { return definition, errors.New("invalid unit environment") } definition.Environment[key] = value } if value, ok := strings.CutPrefix(line, "ExecStart=:"); ok { value, ok = strings.CutSuffix(value, " daemon --serve") if !ok { return definition, errors.New("unrecognized unit command") } executable, err := strconv.Unquote(value) if err != nil { return definition, errors.New("unrecognized unit executable") } definition.Executable = strings.ReplaceAll(executable, "%%", "%") } } expected, err := s.Render(definition) if err != nil { return definition, err } if !bytes.Equal(data, expected) { return definition, errors.New("unit contains edits outside the generated service format") } return definition, nil}
func (s DaemonUnit) loadedContract(observation Observation) (Definition, string) { p := observation.Properties expected := []struct{ key, value string }{ {"FragmentPath", s.path}, {"TriggeredBy", ""}, {"ExecCondition", ""}, {"ExecStartPre", ""}, {"ExecStartPost", ""}, {"ExecStop", ""}, {"ExecStopPost", ""}, {"EnvironmentFiles", ""}, {"Type", "exec"}, {"RemainAfterExit", "no"}, {"KillMode", "process"}, {"Restart", "on-failure"}, {"RestartForceExitStatus", ""}, {"KillSignal", "15"}, {"SendSIGHUP", "no"}, {"SendSIGKILL", "yes"}, {"FinalKillSignal", "9"}, {"TimeoutStopUSec", "45s"}, {"RestartUSec", "3s"}, {"StartLimitIntervalUSec", "1min"}, {"StartLimitBurst", "5"}, {"StandardOutput", "append"}, {"StandardError", "append"}, } for _, property := range expected { if p[property.key] != property.value { return Definition{}, "unsupported loaded property " + property.key } } if !allowedDaemonDropIns(p["DropInPaths"]) { return Definition{}, "unsupported loaded property DropInPaths" } stopFailureMode := "terminate" if p["DropInPaths"] != "" { stopFailureMode = "abort" } if p["TimeoutStopFailureMode"] != stopFailureMode { return Definition{}, "unsupported loaded property TimeoutStopFailureMode" } // Before systemd 250, services always followed the main process. if p["ExitType"] != "" && p["ExitType"] != "main" { return Definition{}, "unsupported loaded property ExitType" } if p["RestartPreventExitStatus"] != "75" { return Definition{}, "unsupported loaded property RestartPreventExitStatus" } loaded := Definition{} command, ok := strings.CutPrefix(p["ExecStart"], "{ path=") if !ok { return Definition{}, "unsupported loaded property ExecStart" } loaded.Executable, _, ok = strings.Cut(command, " ; argv[]=") if !ok { return Definition{}, "unsupported loaded property ExecStart" } prefix := "{ path=" + loaded.Executable + " ; argv[]=" + loaded.Executable + " daemon --serve ; " if !strings.HasPrefix(p["ExecStart"], prefix) || strings.Count(p["ExecStart"], "{ path=") != 1 { return Definition{}, "unsupported loaded property ExecStart" } environment, err := splitWords(p["Environment"]) if err != nil { return Definition{}, "unrecognized loaded Environment" } actualEnvironment := make(map[string]string, len(environment)) for _, entry := range environment { key, value, ok := strings.Cut(entry, "=") if _, duplicate := actualEnvironment[key]; !ok || duplicate { return Definition{}, "unsupported loaded Environment" } actualEnvironment[key] = value } loaded.Environment = actualEnvironment if _, err = s.Render(loaded); err != nil { return Definition{}, "unsupported loaded Environment or executable" } return loaded, ""}
var ErrServiceFileNotOwned = errors.New("service file is not owned by albedo")
func (observation Observation) FileOwnershipError() error { if observation.File == DeclaredFile { return fmt.Errorf("%w; manage it through its declaration owner, such as home-manager", ErrServiceFileNotOwned) } if observation.Problem != "" { return fmt.Errorf("%w: %s", ErrServiceFileNotOwned, observation.Problem) } return ErrServiceFileNotOwned}
// CheckFileOwnership is read-only and runs before launcher.lock can be created.// Only absent files and this CLI's exact regular generated files permit installation.func (s DaemonUnit) CheckFileOwnership() error { if other, exists := s.companion(); exists { if _, err := os.Lstat(other.path); err == nil || !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("%w: another daemon service file exists at %s; inspect with albedo daemon status", ErrServiceFileNotOwned, other.path) } } if s.declarative { return Observation{File: DeclaredFile}.FileOwnershipError() } info, err := os.Lstat(s.path) switch { case errors.Is(err, os.ErrNotExist): return nil case err != nil: return fmt.Errorf("%w: %w", ErrServiceFileNotOwned, err) case info.Mode()&os.ModeSymlink != 0: return fmt.Errorf("%w: generated service file is a symlink", ErrServiceFileNotOwned) case !info.Mode().IsRegular(): return fmt.Errorf("%w: service file is not a regular file", ErrServiceFileNotOwned) } data, err := readServiceFile(s.path) if err != nil { return fmt.Errorf("%w: %w", ErrServiceFileNotOwned, err) } if strings.HasSuffix(s.path, ".plist") { _, err = s.parseLaunchdDefinition(data) } else { _, err = s.parseDefinition(data) } if err != nil { return fmt.Errorf("%w: %w", ErrServiceFileNotOwned, err) } return nil}
func allowedDaemonDropIns(value string) bool { if value == "" { return true } const vendorPath = "/usr/lib/systemd/user/service.d/10-timeout-abort.conf" if value != vendorPath { return false } data, err := os.ReadFile(vendorPath) if err != nil { return false } var directives []string for line := range strings.SplitSeq(string(data), "\n") { line = strings.TrimSpace(line) if line != "" && !strings.HasPrefix(line, "#") && !strings.HasPrefix(line, ";") { directives = append(directives, line) } } return slices.Equal(directives, []string{"[Service]", "TimeoutStopFailureMode=abort"})}
func splitWords(input string) ([]string, error) { var words []string for input = strings.TrimSpace(input); input != ""; input = strings.TrimSpace(input) { if input[0] != '"' { index := strings.IndexAny(input, " \t") if index < 0 { words = append(words, input) break } words = append(words, input[:index]) input = input[index:] continue } end := 1 for end < len(input) { if input[end] == '\\' { end += 2 continue } if input[end] == '"' { break } end++ } if end >= len(input) { return nil, errors.New("unterminated quoted word") } word, err := strconv.Unquote(strings.NewReplacer(`\$`, `$`, "\\`", "`").Replace(input[:end+1])) if err != nil { return nil, err } words = append(words, word) input = input[end+1:] } return words, nil}
func (s DaemonUnit) Publish(data []byte) (os.FileInfo, error) { directory := filepath.Dir(s.path) if err := os.MkdirAll(directory, 0700); err != nil { return nil, err } file, err := os.CreateTemp(directory, ".albedo-unit-*") if err != nil { return nil, err } defer os.Remove(file.Name()) if err = file.Chmod(0600); err == nil { _, err = file.Write(data) } if err == nil { err = file.Sync() } closeErr := file.Close() if err == nil { err = closeErr } if err != nil { return nil, err } if err = os.Rename(file.Name(), s.path); err != nil { return nil, err } dir, err := os.Open(directory) if err != nil { return nil, err } defer dir.Close() if err = dir.Sync(); err != nil { return nil, err } return os.Lstat(s.path)}
func (s DaemonUnit) Unchanged(info os.FileInfo, data []byte) bool { current, err := os.Lstat(s.path) if err != nil || !current.Mode().IsRegular() || !os.SameFile(info, current) { return false } bytesNow, err := os.ReadFile(s.path) return err == nil && bytes.Equal(data, bytesNow)}