Files
pipelines/internal/opencode/endpoint.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

154 lines
6.1 KiB
Go

package opencode
import (
"context"
"encoding/json"
"fmt"
"net/url"
"os"
"strings"
"syscall"
"time"
)
// Environment keys for the operator-supplied OpenCode endpoint. The endpoint
// itself is opt-in: when none of the flag, these variables or the recorded
// setting is present the server keeps today's spawned default. The password is
// accepted only through a private file reference (never inline), mirroring the
// ntfy token-file rule; an optional username overrides the detected default.
const (
EndpointEnvKey = "PIPELINES_OPENCODE_ENDPOINT"
EndpointPasswordFileEnvKey = "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE"
EndpointUsernameEnvKey = "PIPELINES_OPENCODE_ENDPOINT_USERNAME"
)
// endpointProbeTimeout bounds each startup probe (health and SSE) so an
// unreachable endpoint fails fast instead of hanging server startup.
const endpointProbeTimeout = 5 * time.Second
// endpointPasswordFileLimit bounds the credential file read.
const endpointPasswordFileLimit = 4096
// ResolveEndpointRef picks the operator's OpenCode endpoint reference by
// precedence: explicit flag > explicit environment > the endpoint recorded on a
// previous run. An empty result means no endpoint is configured, so the caller
// keeps today's spawned-instance default. It is the single precedence resolver
// used by the server and its tests so the choice cannot drift.
func ResolveEndpointRef(flagValue, envValue, recorded string) string {
for _, value := range []string{flagValue, envValue, recorded} {
if value = strings.TrimSpace(value); value != "" {
return value
}
}
return ""
}
// NormalizeEndpointURL validates an operator-supplied endpoint the way the other
// endpoint references are validated: an http(s) URL with a non-empty host, no
// userinfo, no query, no fragment and an empty or "/" path. Anything else is a
// clear error naming the endpoint rather than a silently guessed base.
func NormalizeEndpointURL(raw string) (string, error) {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") ||
u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
return "", fmt.Errorf("invalid OpenCode endpoint %q: use an http(s) URL with a host and no credentials, query, fragment or path", raw)
}
return strings.TrimRight(u.String(), "/"), nil
}
// ReadEndpointCredentialFile reads the optional endpoint password from a private
// file reference, mirroring the ntfy token-file rule: a regular, single-owner
// 0600 file with a bounded read. An empty path yields no password, so an endpoint
// that authenticates with the default user only keeps working.
func ReadEndpointCredentialFile(path string) (string, error) {
if strings.TrimSpace(path) == "" {
return "", nil
}
info, err := os.Lstat(path)
if err != nil {
return "", fmt.Errorf("cannot read the OpenCode endpoint password file")
}
if !info.Mode().IsRegular() || info.Mode().Perm() != 0600 || info.Size() > endpointPasswordFileLimit {
return "", fmt.Errorf("invalid OpenCode endpoint password file")
}
if stat, ok := info.Sys().(*syscall.Stat_t); !ok || stat.Uid != uint32(os.Getuid()) {
return "", fmt.Errorf("the OpenCode endpoint password file belongs to another user")
}
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("cannot read the OpenCode endpoint password file")
}
return strings.TrimSpace(string(data)), nil
}
// OpenEndpoint opens an operator-supplied OpenCode endpoint without owning a
// process: the returned Connection has no owned process (Close is a no-op), so
// nothing local is ever spawned, and it is never used to reach a different
// instance. The endpoint reference is validated once here (URL shape, then the
// backend-specific health contract, then a streamable event path) and every
// failure names the endpoint; there is no fallback and no retry loop.
func OpenEndpoint(ctx context.Context, rawURL, password string) (*Connection, error) {
base, err := NormalizeEndpointURL(rawURL)
if err != nil {
return nil, err
}
conn := &Connection{
URL: base,
password: password,
username: strings.TrimSpace(os.Getenv(EndpointUsernameEnvKey)),
models: map[string]map[string]string{},
responses: map[string][]byte{},
}
probeCtx, cancel := context.WithTimeout(ctx, endpointProbeTimeout)
defer cancel()
switch {
case conn.probeHealth(probeCtx, "v2") == nil:
conn.Backend = "v2"
case conn.probeHealth(probeCtx, "v1") == nil:
conn.Backend = "v1"
default:
return nil, fmt.Errorf("OpenCode endpoint %s is unreachable or is not an OpenCode service", base)
}
// Require a streamable event endpoint before the endpoint is accepted: a
// healthy service without SSE cannot broker chat, so it is a clear refusal,
// never a silent fallback to another instance.
streamCtx, cancelStream := context.WithTimeout(ctx, endpointProbeTimeout)
defer cancelStream()
body, err := conn.EventStream(streamCtx)
if err != nil {
return nil, fmt.Errorf("OpenCode endpoint %s exposes no streamable event endpoint: %w", base, err)
}
body.Close()
return conn, nil
}
// probeHealth checks one backend family's readiness contract through the same
// authenticated request path the adapter uses, so a reachable but unauthorized
// endpoint is not mistaken for a healthy one. checkHealth and OpenEndpoint share
// it, so the endpoint contract is defined once.
func (c *Connection) probeHealth(ctx context.Context, backend string) error {
previous := c.Backend
c.Backend = backend
defer func() { c.Backend = previous }()
if backend == "v2" {
info, err := c.nativeRequest(ctx, "get", "/api/info", nil, "")
var result struct {
Version string `json:"version"`
URLs []string `json:"urls"`
}
if err != nil || json.Unmarshal(info, &result) != nil || result.Version == "" {
return fmt.Errorf("no V2 info contract")
}
return nil
}
health, err := c.nativeRequest(ctx, "get", "/global/health", nil, "")
var result struct {
Healthy bool `json:"healthy"`
Version string `json:"version"`
}
if err != nil || json.Unmarshal(health, &result) != nil || !result.Healthy || result.Version == "" {
return fmt.Errorf("no native health contract")
}
return nil
}