Files
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

171 lines
6.9 KiB
Go

package opencode
import (
"context"
"encoding/json"
"fmt"
"net/url"
"os"
"strings"
"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
}
if err := checkPrivateFile(path, endpointPasswordFileLimit); err != nil {
switch {
case os.IsNotExist(err):
return "", fmt.Errorf("cannot read the OpenCode endpoint password file")
case strings.Contains(err.Error(), "another user"):
return "", fmt.Errorf("the OpenCode endpoint password file belongs to another user")
default:
return "", fmt.Errorf("invalid OpenCode endpoint password file")
}
}
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) {
conn, err := probeEndpoint(ctx, rawURL, password)
if err != nil {
return nil, err
}
return conn, nil
}
// probeEndpoint is the shared body of OpenEndpoint. Unlike OpenEndpoint it
// returns the connection even when the probe fails, so a caller that supplied a
// credential can tell an authentication refusal (Connection.unauthorized, set on
// HTTP 401) from any other refusal without a second probe or a second judgement
// of the endpoint contract. A caller that does not care discards the connection
// through OpenEndpoint.
func probeEndpoint(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{},
}
// A fresh probe judges this connection's credential only: any 401 recorded
// here belongs to the password supplied now, not to a connection reused
// across a re-pair.
conn.unauthorized = false
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 conn, 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 conn, 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
}