Files
pipelines/cmd/pipelines-server/main.go
T
alan 0ba1204895 chat: attach to the operator's own OpenCode by pairing, fall back honestly
Brokered chat accepted an operator-supplied endpoint (-opencode-endpoint /
PIPELINES_OPENCODE_ENDPOINT) but failed closed against the operator's running
V2 service: that API authenticates every request with HTTP Basic auth (fixed
user "opencode" plus a password), the broker had no credential, so the health
probe answered 401 and startup logged "OpenCode endpoint ... is unreachable or
is not an OpenCode service", disabling chat entirely.

Established from the installed binary (opencode v2.0.20), not from docs:
`opencode --help` advertises `api`, `pair`, `serve`, `service` and `auth`;
`GET /api/info` is unauthenticated-401 with www-authenticate Basic realm
"Secure Area"; Basic auth user `opencode` with the password from
~/.local/state/opencode/service.json answers 200; `POST /api/pair` returns a
code and `GET /auth/connect/{code}` returns a token that is then accepted as
the Basic password.

- internal/opencode/pair.go (new): PairEndpoint does the pair exchange over the
  shared nativeRequest transport (same auth, bounds and JSON checks);
  ReadServiceCredential reads the operator's local service password under the
  private-file rule; OpenEndpointAttached resolves the credential in precedence
  order - explicit password file, a paired token stored by an earlier run, then
  a fresh pairing bootstrapped by the local service credential - stores the
  token owner-only and re-pairs once when a stored token is refused (401).
- internal/opencode/endpoint.go: OpenEndpoint wraps probeEndpoint, which returns
  the connection even on failure; Connection.unauthorized (set on HTTP 401 by
  the request paths, cleared per probe) distinguishes an authentication refusal
  from any other refusal.
- cmd/pipelines-server/main.go: the endpoint attach uses OpenEndpointAttached
  with the paired-credential file beside the pipeline database. An endpoint that
  cannot be attached logs a line naming it and falls back to the server's own
  OpenCode instance instead of leaving chat refused.
- internal/protocol/status.go, internal/server/websocket.go: get_status gains an
  opencode object (health = endpoint | fallback | spawned | unavailable, plus
  the endpoint url), the honest status evidence for the fallback. No credential
  is ever placed there.
- Tests: internal/opencode/pair_test.go, internal/protocol/status_test.go and a
  TestStatusReportsOpenCodeAttachment case in internal/server/status_test.go.

Repository checks: go build ./..., go vet ./... and gofmt -l . clean;
go test ./internal/... ./cmd/... green.

Packaged templates and skill references: the repository has no template tree
that mentions the OpenCode endpoint, and no packaged reference file is added, so
internal/author/install.go's managed inventory is unchanged. The packaged
authoring reference internal/author/skill/references/operations.md (the endpoint
paragraph around line 289, the "clear refusal and no fallback" wording and the
password-file/username-only credential story, and the missing opencode status
field) is now stale; per the maintenance convention the item does not edit the
shared document and instead records the stale points, with the exact wording
they should take, in docs/notes/chat-persistence.md for the docs-fold writer.
2026-10-18 00:55:26 +01:00

139 lines
5.7 KiB
Go

package main
import (
"context"
"errors"
"flag"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/paths"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/server"
"git.a-wan.net/alan/pipelines/internal/summarise"
)
func main() {
addr := flag.String("addr", "127.0.0.1:8080", "HTTP/WebSocket listen address")
// -opencode-endpoint opts in to brokering chat from an operator-supplied
// OpenCode service instead of the spawned default. Its default is the
// environment variable, so both are the same opt-in; the recorded choice (set
// by a previous run) is used when neither is present.
endpoint := flag.String("opencode-endpoint", os.Getenv(opencode.EndpointEnvKey), "Broker chat from this OpenCode endpoint instead of spawning one")
defaultDB, err := paths.Database()
if err != nil {
log.Fatal(err)
}
db := flag.String("db", defaultDB, "SQLite database path (honors XDG_DATA_HOME)")
flag.Parse()
if err := os.MkdirAll(filepath.Dir(*db), 0700); err != nil {
log.Fatal(err)
}
store, err := pipeline.Open(*db)
if err != nil {
log.Fatal(err)
}
defer store.Close()
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
artifactsRoot := filepath.Join(filepath.Dir(*db), "artifacts")
// Each new run gets a bounded one-line title from the configured default
// harness; the summariser falls back to the prompt's first line, so title
// generation never blocks or fails run creation.
options := server.Options{ArtifactsRoot: artifactsRoot, RunTitles: summarise.GenerateTitle, StepVerdicts: summarise.GenerateVerdictReason}
recorded := ""
if value, err := store.OpenCodeEndpoint(ctx); err != nil {
log.Printf("OpenCode endpoint setting unreadable: %v", err)
} else {
recorded = value
}
reference := opencode.ResolveEndpointRef(*endpoint, os.Getenv(opencode.EndpointEnvKey), recorded)
// Chat brokers OpenCode over one endpoint. When the operator configured an
// endpoint (flag, environment or a previously recorded choice) the broker
// attaches to it: it uses the password-file credential if one was supplied,
// otherwise it pairs once with the operator's local OpenCode service
// credential, stores the paired token owner-only beside the pipeline
// database and reuses it across restarts. An endpoint that cannot be
// attached is a log line and a status note, and chat then falls back to the
// server's own OpenCode instance rather than staying refused. Only a
// URL-bearing, SSE-capable connection enables chat; otherwise chat stays
// disabled and every chat_* request is answered with a protocol error naming
// the missing configuration rather than hanging.
openCodeStatus := protocol.ServiceStatus{Health: "unavailable"}
if reference != "" {
explicit, explicitErr := opencode.ReadEndpointCredentialFile(os.Getenv(opencode.EndpointPasswordFileEnvKey))
if explicitErr != nil {
log.Printf("OpenCode endpoint password file unreadable: %v", explicitErr)
}
// The pair bootstrap (the operator's local service credential) is only
// needed when no explicit password was supplied; a password-file setup
// therefore logs nothing here.
bootstrap := ""
if explicit == "" {
setting, _ := opencode.ServiceCredentialPath()
value, bootstrapErr := opencode.ReadServiceCredential(setting)
if bootstrapErr != nil {
log.Printf("OpenCode local service credential unreadable: %v", bootstrapErr)
}
bootstrap = value
}
credentialPath := filepath.Join(filepath.Dir(*db), "opencode-endpoint.json")
attach, attachErr := opencode.OpenEndpointAttached(ctx, reference, explicit, bootstrap, credentialPath)
if attachErr != nil {
log.Printf("OpenCode endpoint %s could not be attached (%v); falling back to the server's own OpenCode instance", reference, attachErr)
openCodeStatus = protocol.ServiceStatus{Health: "fallback", URL: reference}
} else {
options.Chat = opencode.NewChat(attach.Connection)
defer attach.Connection.Close()
openCodeStatus = protocol.ServiceStatus{Health: "endpoint", URL: reference}
if attach.Note != "" {
log.Printf("OpenCode endpoint %s: %s", reference, attach.Note)
}
if err := store.RecordOpenCodeEndpoint(ctx, reference); err != nil {
log.Printf("record OpenCode endpoint: %v", err)
}
}
}
if options.Chat == nil {
if conn, err := opencode.OpenChat(ctx, opencode.Executable(), ""); err != nil {
log.Printf("OpenCode chat unavailable: %v", err)
} else if conn.URL == "" {
conn.Close()
log.Printf("OpenCode chat unavailable: the connection exposes no streamable event endpoint")
} else {
options.Chat = opencode.NewChat(conn)
defer conn.Close()
if openCodeStatus.Health == "unavailable" {
openCodeStatus = protocol.ServiceStatus{Health: "spawned", URL: conn.URL}
}
}
}
// If neither the endpoint nor the spawned instance enabled chat, report that
// honestly rather than claiming the fallback is serving chat.
if options.Chat == nil && openCodeStatus.Health != "endpoint" {
openCodeStatus.Health = "unavailable"
}
options.OpenCodeStatus = openCodeStatus
srv := &http.Server{Addr: *addr, Handler: server.HandlerWithOptions(ctx, options, store), ReadHeaderTimeout: 5 * time.Second}
defer server.WaitRuns(srv.Handler)
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("shutdown: %v", err)
}
}()
log.Printf("listening on %s (WebSocket endpoint: /connect)", *addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}