1f75e4797e
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.
105 lines
4.2 KiB
Go
105 lines
4.2 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/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}
|
|
// Chat brokers OpenCode over one endpoint. By default OpenChat detects the
|
|
// installed CLI and starts the single owned serve process for it: the native
|
|
// wire for v1, and the V2 API for the installed V2 CLI (which exposes the
|
|
// authenticated SSE firehose at /api/event). When the operator configured an
|
|
// endpoint (flag, environment or a previously recorded choice) chat is
|
|
// brokered from that endpoint instead: it is validated once, an unreachable or
|
|
// non-OpenCode endpoint is a clear refusal and never falls back to a spawned
|
|
// instance, and nothing is started locally. 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.
|
|
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)
|
|
if reference != "" {
|
|
password, err := opencode.ReadEndpointCredentialFile(os.Getenv(opencode.EndpointPasswordFileEnvKey))
|
|
if err != nil {
|
|
log.Printf("OpenCode chat unavailable: %v", err)
|
|
} else if conn, err := opencode.OpenEndpoint(ctx, reference, password); err != nil {
|
|
log.Printf("OpenCode chat unavailable: %v", err)
|
|
} else {
|
|
options.Chat = opencode.NewChat(conn)
|
|
defer conn.Close()
|
|
if err := store.RecordOpenCodeEndpoint(ctx, reference); err != nil {
|
|
log.Printf("record OpenCode endpoint: %v", err)
|
|
}
|
|
}
|
|
} else 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()
|
|
}
|
|
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)
|
|
}
|
|
}
|