Files
pipelines/internal/opencode/connection.go
T
alan 05ae530442 Make Pipelines Docker-only with OpenCode and Pi
Install current verified harness releases inside Docker, preserve persistent accounts and settings, and provide separate interactive and pipeline model defaults with terminal onboarding and fuzzy pickers.

Add Docker-aware authoring transport, Pi stage execution, bounded workflow controls, reliable final-result readback and usage settlement, and finite short-lived CLI pipe draining. Keep dated installation evidence and packaged authoring guidance consistent.

Verified with a real Docker installation, both harness stages and interactive authors, the built-in plan/implement/review starter, independent host race/vet checks, installer tests, and packaged skill tests. Generated release receipts stay ignored in clean checkouts.
2026-10-11 23:00:25 +01:00

280 lines
8.3 KiB
Go

// Package opencode adapts the two published OpenCode API families without installing a CLI.
package opencode
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"syscall"
"time"
)
const MaxRequest = 64 << 10
const MaxResponse = 1 << 20
type Connection struct {
Backend, Executable, Directory string
URL string
password string
process *exec.Cmd
done chan error
models map[string]map[string]string
responses map[string][]byte
formatChecked bool
formatSupported bool
FormatProbe *FormatProbe
LastHTTPStatus int
LastHTTPOperation string
MessageReadbackDiagnostic string
}
// Reference records only our ephemeral loopback service credentials, never provider auth.
// The private file lets crash recovery abort the same owned service, not a new instance.
func (c *Connection) Reference() (string, error) {
cache, err := os.UserCacheDir()
if err != nil {
return "", err
}
dir := filepath.Join(cache, "pipelines", "private")
if err = os.MkdirAll(dir, 0700); err != nil {
return "", err
}
f, err := os.CreateTemp(dir, "opencode-connection-*.json")
if err != nil {
return "", err
}
data, _ := json.Marshal(map[string]string{"url": c.URL, "password": c.password, "directory": c.Directory})
_, writeErr := f.Write(data)
closeErr := f.Close()
if writeErr != nil {
return "", writeErr
}
if closeErr != nil {
return "", closeErr
}
return f.Name(), nil
}
func FromReference(path string) (*Connection, error) {
info, err := os.Lstat(path)
if err != nil {
return nil, err
}
if !info.Mode().IsRegular() || info.Mode().Perm() != 0600 || info.Size() > MaxRequest {
return nil, fmt.Errorf("invalid private OpenCode connection reference")
}
if stat, ok := info.Sys().(*syscall.Stat_t); !ok || stat.Uid != uint32(os.Getuid()) {
return nil, fmt.Errorf("OpenCode reference belongs to another user")
}
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var reference struct{ URL, Password, Directory string }
if err = json.Unmarshal(data, &reference); err != nil {
return nil, err
}
u, err := url.Parse(reference.URL)
if err != nil || u.Scheme != "http" || u.Hostname() != "127.0.0.1" || u.Port() == "" || u.Path != "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || len(reference.Password) != 64 {
return nil, fmt.Errorf("invalid owned OpenCode service endpoint")
}
return &Connection{Backend: "v1", URL: reference.URL, password: reference.Password, Directory: reference.Directory}, nil
}
func Executable() string {
if path := os.Getenv("PIPELINES_OPENCODE"); path != "" {
return path
}
return "opencode"
}
// Detect checks the advertised command interface, not an assumed release number.
func Detect(ctx context.Context, executable string) (string, error) {
cmd := CommandContext(ctx, executable, "--help")
data, err := cmd.CombinedOutput()
if err != nil {
// Preserve the caller's cancellation/deadline identity; a parent that
// exits 0 while a descendant still holds the combined-output pipe is
// never parsed from its partial stdout.
if ctx.Err() != nil {
return "", ctx.Err()
}
return "", fmt.Errorf("cannot run the selected OpenCode CLI: %w", err)
}
if regexp.MustCompile(`(?m)^\s*(?:opencode\s+)?api\s`).Match(data) {
return "v2", nil
}
if regexp.MustCompile(`(?m)^\s*(?:opencode\s+)?serve\s`).Match(data) {
return "v1", nil
}
return "", fmt.Errorf("selected OpenCode CLI advertises neither api nor serve")
}
func Open(ctx context.Context, executable, directory, backend string) (*Connection, error) {
if executable == "" {
executable = Executable()
}
if directory == "" {
var err error
directory, err = os.Getwd()
if err != nil {
return nil, err
}
}
if backend == "" {
var err error
backend, err = Detect(ctx, executable)
if err != nil {
return nil, err
}
}
c := &Connection{Backend: backend, Executable: executable, Directory: directory, models: map[string]map[string]string{}, responses: map[string][]byte{}}
if backend == "v2" {
return c, nil
}
if backend != "v1" {
return nil, fmt.Errorf("unknown OpenCode backend %q", backend)
}
secret := make([]byte, 32)
if _, err := rand.Read(secret); err != nil {
return nil, err
}
c.password = hex.EncodeToString(secret)
c.process = exec.Command(executable, "serve", "--hostname", "127.0.0.1", "--port", "0")
c.process.Dir = directory
for _, entry := range os.Environ() {
if !strings.HasPrefix(entry, "OPENCODE_SERVER_PASSWORD=") && !strings.HasPrefix(entry, "OPENCODE_SERVER_USERNAME=") {
c.process.Env = append(c.process.Env, entry)
}
}
c.process.Env = append(c.process.Env, "OPENCODE_SERVER_PASSWORD="+c.password, "OPENCODE_SERVER_USERNAME=pipelines")
stdout, err := c.process.StdoutPipe()
if err != nil {
return nil, err
}
c.process.Stderr = io.Discard
if err = c.process.Start(); err != nil {
return nil, err
}
c.done = make(chan error, 1)
go func() { c.done <- c.process.Wait() }()
address := make(chan string, 1)
go func() {
scanner := bufio.NewScanner(stdout)
pattern := regexp.MustCompile(`http://127\.0\.0\.1:[0-9]+`)
sent := false
for scanner.Scan() {
if !sent {
if found := pattern.FindString(scanner.Text()); found != "" {
address <- found
sent = true
}
}
}
}()
startup, stop := context.WithTimeout(ctx, 20*time.Second)
defer stop()
select {
case c.URL = <-address:
case <-c.done:
c.process = nil
return nil, fmt.Errorf("OpenCode serve exited before becoming ready")
case <-startup.Done():
c.Close()
return nil, fmt.Errorf("OpenCode serve startup: %w", startup.Err())
}
health, err := c.Native(startup, "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 == "" {
c.Close()
return nil, fmt.Errorf("OpenCode serve did not return the expected native health contract")
}
return c, nil
}
func (c *Connection) Close() {
if c.process == nil {
return
}
_ = c.process.Process.Signal(syscall.SIGTERM)
select {
case <-c.done:
case <-time.After(5 * time.Second):
_ = c.process.Process.Kill()
<-c.done
}
c.process = nil
}
func (c *Connection) Native(ctx context.Context, method, path string, body any) ([]byte, error) {
c.LastHTTPStatus = 0
c.LastHTTPOperation = strings.ToUpper(method) + " " + path
u, err := url.Parse(c.URL + path)
if err != nil {
return nil, err
}
query := u.Query()
query.Set("directory", c.Directory)
u.RawQuery = query.Encode()
var data []byte
if body != nil {
data, err = json.Marshal(body)
if err != nil {
return nil, err
}
if len(data) > MaxRequest {
return nil, fmt.Errorf("OpenCode request exceeds 64 KiB")
}
}
request, err := http.NewRequestWithContext(ctx, strings.ToUpper(method), u.String(), bytes.NewReader(data))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
request.SetBasicAuth("pipelines", c.password)
response, err := http.DefaultClient.Do(request)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, fmt.Errorf("OpenCode native API request failed")
}
defer response.Body.Close()
c.LastHTTPStatus = response.StatusCode
if response.StatusCode < 200 || response.StatusCode >= 300 {
// The stage adapter stores bounded, redacted failure evidence separately;
// the public error string remains free of provider bodies and credentials.
evidence, _ := io.ReadAll(io.LimitReader(response.Body, 16<<10))
return evidence, fmt.Errorf("OpenCode %s %s failed (HTTP %d)", method, path, response.StatusCode)
}
if !strings.HasPrefix(response.Header.Get("Content-Type"), "application/json") {
return nil, fmt.Errorf("OpenCode %s %s returned a non-JSON API response", method, path)
}
data, err = io.ReadAll(io.LimitReader(response.Body, MaxResponse+1))
if err != nil {
return nil, err
}
if len(data) > MaxResponse {
return nil, fmt.Errorf("OpenCode response exceeds 1 MiB")
}
if !json.Valid(data) {
return nil, fmt.Errorf("OpenCode returned invalid JSON")
}
return data, nil
}