Files
pipelines/internal/installation/service.go
T
alan 1f75e4797e Broker chat from an operator's own OpenCode endpoint and adopt existing sessions
Add an opt-in way to broker chat from an operator-supplied OpenCode service
instead of the instance the server spawns for itself, and a way to adopt a
session that already exists on that endpoint so it appears in chat_sessions and
can be continued from the app.

- Endpoint selection: the `-opencode-endpoint` server flag (defaulting to
  `PIPELINES_OPENCODE_ENDPOINT`) opts in; precedence is explicit flag >
  explicit environment > the endpoint recorded on a previous run, with the
  spawned instance as the default. opencode.OpenEndpoint validates the
  reference once (http(s), host, no userinfo/query/fragment/path), detects the
  backend from its own /api/info (v2) or /global/health (v1) contract, and
  requires a streamable text/event-stream event path. It owns no process
  (Close is a no-op) and never calls startServe; every failure names the
  endpoint and disables chat rather than silently falling back. An
  authenticated endpoint takes an optional password only through the private
  file PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE, with
  PIPELINES_OPENCODE_ENDPOINT_USERNAME overriding the detected default.
- Persistence: the validated choice is recorded in an additive single-row
  server_settings table so a restart with no flag/environment reuses it; an
  unreachable recorded endpoint disables chat with a clear message and no
  fallback.
- chat_adopt: a new protocol request (ChatAdoptRequest) with handleChatAdopt in
  internal/server/chat.go. It refuses a nil broker/registry/payload and a
  blank or foreign-shaped id before any endpoint call, reads the endpoint via
  the shared Chat.Session (which reuses Sessions/decodeChatSessions), records
  through the existing RecordOperatorSession with the endpoint's directory and
  title verbatim, and echoes the adopted session plus its registry row like
  chat_create. A missing id is refused naming the id and records nothing; an
  endpoint record with an empty directory is refused rather than substituting
  the server's working directory or home.
- CLI: `pipelines chat-adopt <session-id> [--json]` (usage, notes, help
  inventory, dispatch) with docs/cli.md updated under Chat sessions.
- Autostart preserves the endpoint variables (and the password-file reference,
  never an inline secret) via serviceEnvironmentKeys.

Checks before committing:
- Package location: the change is user-facing chat behaviour, so the packaged
  authoring skill reference internal/author/skill/references/operations.md is
  updated in the same change (Brokered OpenCode chat section) with a dated
  verification-evidence entry and the not-deployed state. No new reference file
  is added, so internal/author/install.go's managed inventory is unchanged.
- Packaged templates: this repository packages no template set for this
  behaviour and none references the chat endpoint, so no template needs
  updating.
- Verification: `go build ./...`, `go vet` on the touched packages, `gofmt -l`
  clean and `go test ./...` all pass. The unit tests cover the endpoint
  validation/precedence, the adopt happy path and refusals, the recorded
  endpoint round-trip, the protocol round-trip and the CLI dispatch. The live
  scratch-server check against the operator's real endpoint was not run in this
  change.

Nothing unrelated is staged; docs left stale (README and other shared documents)
are not edited here and are for a single folding writer.
2026-10-17 20:14:11 +01:00

302 lines
9.8 KiB
Go

package installation
import (
"bytes"
"context"
"encoding/xml"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"git.a-wan.net/alan/pipelines/internal/paths"
)
const serviceMarker = "Managed by pipelines service"
const serviceLabel = "net.a-wan.pipelines"
type serviceDefinition struct {
Binary, Directory string
Args []string
Environment map[string]string
}
func xmlText(s string) string {
var b bytes.Buffer
_ = xml.EscapeText(&b, []byte(s))
return b.String()
}
func unitQuote(s string) string {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, "%", "%%").Replace(s) + `"`
}
func (d serviceDefinition) render(platform string) (string, error) {
for _, value := range append(append([]string{d.Binary, d.Directory}, d.Args...), envValues(d.Environment)...) {
if strings.ContainsAny(value, "\r\n\x00") {
return "", fmt.Errorf("service settings cannot contain line breaks or NUL")
}
}
if platform == "linux" {
var b strings.Builder
// WorkingDirectory is a path setting, not a shell-style argument list.
// Quotes become literal path characters and make an absolute path invalid.
fmt.Fprintf(&b, "# %s\n[Unit]\nDescription=Pipelines server\n\n[Service]\nType=simple\nWorkingDirectory=%s\nExecStart=%s", serviceMarker, strings.ReplaceAll(d.Directory, "%", "%%"), unitQuote(strings.ReplaceAll(d.Binary, "$", "$$")))
for _, arg := range d.Args {
fmt.Fprintf(&b, " %s", unitQuote(strings.ReplaceAll(arg, "$", "$$")))
}
b.WriteString("\nRestart=on-failure\nRestartSec=5\nUMask=0077\n")
for _, key := range serviceEnvironmentKeys {
if value, ok := d.Environment[key]; ok {
fmt.Fprintf(&b, "Environment=%s\n", unitQuote(key+"="+value))
}
}
b.WriteString("\n[Install]\nWantedBy=default.target\n")
return b.String(), nil
}
if platform == "darwin" {
var b strings.Builder
fmt.Fprintf(&b, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- %s -->\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>%s</string>\n<key>ProgramArguments</key><array>", serviceMarker, serviceLabel)
for _, arg := range append([]string{d.Binary}, d.Args...) {
fmt.Fprintf(&b, "<string>%s</string>", xmlText(arg))
}
fmt.Fprintf(&b, "</array>\n<key>WorkingDirectory</key><string>%s</string>\n<key>RunAtLoad</key><true/>\n<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n<key>ThrottleInterval</key><integer>5</integer>\n<key>Umask</key><integer>63</integer>\n<key>EnvironmentVariables</key><dict>", xmlText(d.Directory))
for _, key := range serviceEnvironmentKeys {
if value, ok := d.Environment[key]; ok {
fmt.Fprintf(&b, "<key>%s</key><string>%s</string>", key, xmlText(value))
}
}
b.WriteString("</dict>\n</dict></plist>\n")
return b.String(), nil
}
return "", fmt.Errorf("autostart is supported on Linux (systemd) and macOS (launchd)")
}
// Only explicitly supported settings are captured, never the complete environment
// or provider credentials. File-based notification credentials remain references.
var serviceEnvironmentKeys = []string{"PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_OPENCODE_ENDPOINT_USERNAME", "PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN_FILE"}
func envValues(env map[string]string) []string {
var values []string
for _, key := range serviceEnvironmentKeys {
if value, ok := env[key]; ok {
values = append(values, value)
}
}
return values
}
func serviceFile(platform string) (string, error) {
if platform == "linux" {
dir, err := os.UserConfigDir()
return filepath.Join(dir, "systemd", "user", "pipelines.service"), err
}
if platform == "darwin" {
home, err := os.UserHomeDir()
return filepath.Join(home, "Library", "LaunchAgents", serviceLabel+".plist"), err
}
return "", fmt.Errorf("autostart is supported on Linux (systemd) and macOS (launchd)")
}
func verifyServiceFile(path string) error {
info, err := os.Lstat(path)
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return fmt.Errorf("refusing to replace non-regular service file %s", path)
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
if !strings.Contains(string(data), serviceMarker) {
return fmt.Errorf("refusing to change unmanaged service file %s", path)
}
return nil
}
func writeServiceFile(path, content string) error {
if err := verifyServiceFile(path); err != nil && !os.IsNotExist(err) {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
f, err := os.CreateTemp(filepath.Dir(path), ".pipelines-service-*")
if err != nil {
return err
}
defer os.Remove(f.Name())
_, writeErr := io.WriteString(f, content)
closeErr := f.Close()
if writeErr != nil {
return writeErr
}
if closeErr != nil {
return closeErr
}
return os.Rename(f.Name(), path)
}
func ServerExecutable(executable string) (string, error) {
if server, err := exec.LookPath("pipelines-server"); err == nil {
return filepath.Abs(server)
}
resolved, err := filepath.EvalSymlinks(executable)
if err != nil {
return "", err
}
server := filepath.Join(filepath.Dir(resolved), "pipelines-server")
info, err := os.Stat(server)
if err != nil {
return "", err
}
if !info.Mode().IsRegular() || info.Mode().Perm()&0111 == 0 {
return "", fmt.Errorf("%s is not an executable server", server)
}
return server, nil
}
// ServiceCommand uses the OS service manager directly, without a second supervisor.
func ServiceCommand(ctx context.Context, executable string, args []string, out, stderr io.Writer) error {
help := "Usage: pipelines service enable [--db FILE] [--addr HOST:PORT] [--print]\n pipelines service disable | status\nAutostart is per-user, at login. enable starts the server now; --print only previews.\nRuns use the directory you invoke pipelines run from.\n"
if len(args) == 0 || args[0] == "--help" || args[0] == "help" {
_, err := io.WriteString(out, help)
return err
}
path, err := serviceFile(runtime.GOOS)
if err != nil {
return err
}
run := func(name string, args ...string) error {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Stdout = out
cmd.Stderr = stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s failed: %w", name, err)
}
return nil
}
domain := fmt.Sprintf("gui/%d", os.Getuid())
switch args[0] {
case "enable":
f := flag.NewFlagSet("service enable", flag.ContinueOnError)
f.SetOutput(stderr)
preview := f.Bool("print", false, "Preview service definition without writing or starting")
defaultDB, err := paths.Database()
if err != nil {
return err
}
db := f.String("db", defaultDB, "SQLite database file")
addr := f.String("addr", "127.0.0.1:8080", "Server listen address")
if err := f.Parse(args[1:]); err != nil {
if err == flag.ErrHelp {
return nil
}
return err
}
if len(f.Args()) != 0 {
return fmt.Errorf("service enable takes no positional arguments")
}
if os.Getenv("PIPELINES_NTFY_TOKEN") != "" {
return fmt.Errorf("use PIPELINES_NTFY_TOKEN_FILE for autostart; inline tokens are not saved")
}
binary, err := ServerExecutable(executable)
if err != nil {
return err
}
database, err := filepath.Abs(*db)
if err != nil {
return err
}
home, err := os.UserHomeDir()
if err != nil {
return err
}
d := serviceDefinition{Binary: binary, Directory: home, Args: []string{"-db", database, "-addr", *addr}, Environment: map[string]string{}}
for _, key := range serviceEnvironmentKeys {
if value, ok := os.LookupEnv(key); ok {
d.Environment[key] = value
}
}
for _, key := range []string{"PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_NTFY_TOKEN_FILE"} {
if value := d.Environment[key]; value != "" && (key != "PIPELINES_OPENCODE" || strings.ContainsRune(value, filepath.Separator)) {
absolute, err := filepath.Abs(value)
if err != nil {
return err
}
d.Environment[key] = absolute
}
}
content, err := d.render(runtime.GOOS)
if err != nil {
return err
}
if *preview {
_, err = io.WriteString(out, content)
return err
}
if err = writeServiceFile(path, content); err != nil {
return err
}
fmt.Fprintf(out, "Saved %s\n", path)
if runtime.GOOS == "linux" {
if err = run("systemctl", "--user", "daemon-reload"); err != nil {
return err
}
if err = run("systemctl", "--user", "enable", "pipelines.service"); err != nil {
return err
}
// Reconfiguration also needs to replace an already-running process.
return run("systemctl", "--user", "restart", "pipelines.service")
}
// bootout may fail when the service has not previously been loaded.
cmd := exec.CommandContext(ctx, "launchctl", "bootout", domain, path)
_ = cmd.Run()
if err = run("launchctl", "enable", domain+"/"+serviceLabel); err != nil {
return err
}
return run("launchctl", "bootstrap", domain, path)
case "disable":
if len(args) != 1 {
return fmt.Errorf("service disable takes no arguments")
}
if err = verifyServiceFile(path); err != nil {
return err
}
if runtime.GOOS == "linux" {
err = run("systemctl", "--user", "disable", "--now", "pipelines.service")
} else {
err = run("launchctl", "disable", domain+"/"+serviceLabel)
if err == nil {
err = run("launchctl", "bootout", domain, path)
}
}
if err != nil {
return err
}
if err = os.Remove(path); err != nil {
return err
}
if runtime.GOOS == "linux" {
return run("systemctl", "--user", "daemon-reload")
}
return nil
case "status":
if len(args) != 1 {
return fmt.Errorf("service status takes no arguments")
}
if runtime.GOOS == "linux" {
return run("systemctl", "--user", "status", "pipelines.service")
}
return run("launchctl", "print", domain+"/"+serviceLabel)
default:
return fmt.Errorf("unknown service command %q\n%s", args[0], help)
}
}