chat: broker OpenCode v2 chat over the owned serve SSE endpoint

The installed OpenCode 2.0.20 exposes the authenticated SSE event firehose at
/api/event and the /api HTTP surface, but Detect selects backend "v2" and Open
returned no owned process/URL, so chat stayed disabled and every chat_* request
was answered with "chat is not configured on this server".

Add opencode.OpenStream/OpenChat: for either backend they start the single owned
opencode serve process, discover the loopback URL and verify the backend health
contract (/api/info for v2, /global/health for v1). main and the live test share
OpenChat so the selection cannot drift. Chat now streams real incremental
session.text.delta/session.reasoning.delta frames via the existing
Connection.EventStream + NormalizeChatEvent, with no polling and no fake
streaming.

- Authenticate the owned endpoint with the per-backend user (opencode for v2,
  pipelines for v1); the v2 server ignores OPENCODE_SERVER_USERNAME.
- Send the V2 prompt shape {"text":...}, which the v1 translation also accepts.
- Skip firehose event types the adapter does not surface before decoding their
  data, so session.instructions.updated (delta is an object) no longer fails the
  stream.

Unit tests cover the per-backend user, the prompt shape/auth, the captured real
V2 event shapes and the selection guards. An opt-in live test drives
chat_sessions/chat_messages/a completed chat_prompt/an interrupted chat_prompt
against the installed OpenCode. Update the packaged operations reference with the
realized capability, dated evidence and deployment state.

Checks before commit: the packaged authoring reference
internal/author/skill/references/operations.md is updated in this change; no new
reference file was added, so internal/author/install.go's managed inventory is
unchanged and the internal/author tests pass. No packaged template describes the
brokered chat surface, and neither README.md nor the topic docs under docs/ (nor
web/) document it, so none of them needed updating.
This commit is contained in:
2026-10-17 01:48:07 +01:00
parent 515059674d
commit 30c1ed442e
6 changed files with 586 additions and 48 deletions
+29 -1
View File
@@ -65,7 +65,10 @@ func (c *Chat) Prompt(ctx context.Context, id, text string) error {
if strings.TrimSpace(text) == "" {
return fmt.Errorf("empty chat prompt")
}
body := map[string]any{"parts": []map[string]string{{"type": "text", "text": text}}}
// The V2 prompt body is {"text": ...}; the native serve translation accepts
// the same "text" field, so one shape works on both backends without a
// second request format.
body := map[string]any{"text": text}
if _, err := c.call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil {
return err
}
@@ -312,6 +315,23 @@ func scanChatEvents(ctx context.Context, body io.Reader, sessionID string, emit
return ctx.Err()
}
// isChatEventType reports whether t is an event type NormalizeChatEvent
// surfaces. Unknown types are skipped before their data is decoded, so an
// unrelated event whose fields share a name with chatEvent but carry a different
// JSON shape cannot fail the stream.
func isChatEventType(t string) bool {
switch t {
case "session.text.delta", "session.reasoning.delta",
"session.step.started", "session.step.streamed", "session.step.ended",
"session.usage.updated",
"session.tool.input.started", "session.tool.input.ended",
"session.tool.called", "session.tool.progress",
"session.tool.success", "session.tool.failed":
return true
}
return false
}
// chatEvent is the subset of the verified firehose envelope this adapter reads:
// {"type":"session.text.delta","data":{...}}. Fields absent from a given event
// stay zero so one struct covers every type.
@@ -353,6 +373,14 @@ func NormalizeChatEvent(payload []byte, sessionID string, lastMessageID *string)
if outer.Type == "" || len(outer.Data) == 0 {
return protocol.ChatEventFrame{}, false, nil
}
// Only decode the data of event types this adapter surfaces. The firehose
// also carries unrelated session events whose fields collide with chatEvent
// but have a different JSON shape (session.instructions.updated carries
// "delta" as an object), so decoding every event would fail the stream on an
// event that is not a chat frame at all.
if !isChatEventType(outer.Type) {
return protocol.ChatEventFrame{}, false, nil
}
var data chatEvent
if err := json.Unmarshal(outer.Data, &data); err != nil {
return protocol.ChatEventFrame{}, false, fmt.Errorf("malformed OpenCode event data: %w", err)
+140
View File
@@ -0,0 +1,140 @@
package opencode
import (
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// TestConnectionServerUser pins the owned serve basic-auth user per backend: the
// native serve authenticates "pipelines", the V2 API server authenticates
// "opencode" (verified against the installed 2.0.20 binary, which ignores
// OPENCODE_SERVER_USERNAME). A wrong user is an unauthenticated endpoint, so it
// is asserted rather than assumed.
func TestConnectionServerUser(t *testing.T) {
if got := (&Connection{Backend: "v1"}).serverUser(); got != "pipelines" {
t.Fatalf("v1 server user = %q, want pipelines", got)
}
if got := (&Connection{Backend: "v2"}).serverUser(); got != "opencode" {
t.Fatalf("v2 server user = %q, want opencode", got)
}
}
// TestChatV2PromptShapeAndAuth pins the outbound V2 prompt: a single "text"
// field (the installed service's PromptInput schema requires "text" and rejects
// a bare "parts" array) sent with the "opencode" basic-auth user. The same body
// also drives the v1 translation, so no second request format exists.
func TestChatV2PromptShapeAndAuth(t *testing.T) {
type request struct {
method, path, user, pass, body string
}
var got request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data := make([]byte, r.ContentLength)
_, _ = r.Body.Read(data)
user, pass, _ := r.BasicAuth()
got = request{method: r.Method, path: r.URL.Path, user: user, pass: pass, body: string(data)}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL, password: "deadbeef"})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := chat.Prompt(ctx, "ses_1", "hello"); err != nil {
t.Fatalf("prompt: %v", err)
}
if got.method != http.MethodPost || got.path != "/api/session/ses_1/prompt" {
t.Fatalf("prompt request = %+v", got)
}
if got.body != `{"text":"hello"}` {
t.Fatalf("prompt body = %q, want the V2 text shape", got.body)
}
if got.user != "opencode" || got.pass != "deadbeef" {
t.Fatalf("prompt auth = %q/%q, want opencode/deadbeef", got.user, got.pass)
}
}
// TestChatStreamRealV2Shapes replays the exact event frames the installed 2.0.20
// service emitted on /api/event during a live turn (captured, not documented):
// a step start, token text delta, usage and a step end whose data carries no
// step index. It asserts the existing firehose mapper surfaces them with stable
// session/message ids and that the usage frame inherits the retained message id.
func TestChatStreamRealV2Shapes(t *testing.T) {
frames := []string{
`{"id":"evt_0","created":0,"type":"session.instructions.updated","data":{"sessionID":"ses_1","delta":{"core/instructions":"abc","core/date":"def"}}}`,
`{"id":"evt_1","created":1,"type":"session.step.started","data":{"sessionID":"ses_1","agent":"build","model":{"id":"deepseek-v4.1-flash","providerID":"opencode-go","variant":"default"},"assistantMessageID":"msg_1","started":1}}`,
`{"id":"evt_2","created":2,"type":"session.text.started","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0}}`,
`{"id":"evt_3","created":3,"type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0,"delta":"Where granite meets"}}`,
`{"id":"evt_4","created":4,"type":"session.usage.updated","data":{"sessionID":"ses_1","cost":0.0005,"tokens":{"input":94,"output":304}}}`,
`{"id":"evt_5","created":5,"type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","finish":"stop","tokens":{"input":94,"output":304},"cost":0.0005}}`,
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/event" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
w.Header().Set("Content-Type", "text/event-stream")
for _, frame := range frames {
_, _ = w.Write([]byte("data: " + frame + "\n\n"))
}
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var got []protocol.ChatEventFrame
if err := chat.Stream(ctx, "ses_1", nil, func(frame protocol.ChatEventFrame) error {
got = append(got, frame)
return nil
}); err != nil {
t.Fatalf("stream: %v", err)
}
// text.started carries no delta and is skipped; the four remaining frames
// (step start, text delta, usage, step end) must all surface.
if len(got) != 4 {
t.Fatalf("frames = %d, want 4: %+v", len(got), got)
}
for _, frame := range got {
if frame.SessionID != "ses_1" || frame.MessageID != "msg_1" {
t.Fatalf("frame missing stable ids: %+v", frame)
}
}
if got[0].Kind != protocol.ChatEventStep || got[0].Step == nil || got[0].Step.Status != protocol.ChatStepStarted {
t.Fatalf("step start frame = %+v", got[0])
}
if got[1].Kind != protocol.ChatEventText || got[1].Delta != "Where granite meets" {
t.Fatalf("text frame = %+v", got[1])
}
if got[2].Kind != protocol.ChatEventUsage || got[2].Usage == nil || got[2].Usage.InputTokens != 94 || got[2].Usage.OutputTokens != 304 {
t.Fatalf("usage frame = %+v", got[2])
}
if got[3].Kind != protocol.ChatEventStep || got[3].Step == nil || got[3].Step.Status != protocol.ChatStepEnded {
t.Fatalf("step end frame = %+v", got[3])
}
}
// TestOpenStreamRejectsUnknownBackend pins that the shared construction path
// validates the backend before any process is started, so OpenStream never
// launches a serve for an unknown backend.
func TestOpenStreamRejectsUnknownBackend(t *testing.T) {
if _, err := OpenStream(context.Background(), "opencode", t.TempDir(), "v3"); err == nil {
t.Fatal("an unknown backend must be rejected")
}
}
// TestOpenChatRejectsUnrunnableCLI pins that OpenChat surfaces detection failure
// (an executable that cannot run) instead of opening a half-configured endpoint.
func TestOpenChatRejectsUnrunnableCLI(t *testing.T) {
missing := filepath.Join(t.TempDir(), "no-such-opencode")
if _, err := OpenChat(context.Background(), missing, ""); err == nil {
t.Fatal("a missing CLI must fail detection, not open an endpoint")
}
}
+113 -19
View File
@@ -123,6 +123,59 @@ func Detect(ctx context.Context, executable string) (string, error) {
}
func Open(ctx context.Context, executable, directory, backend string) (*Connection, error) {
c, err := newConnection(ctx, executable, directory, backend)
if err != nil {
return nil, err
}
// The V2 CLI talks to its own managed service, so stages reach it through the
// `api` subcommand and Open returns no owned process for them. Only
// OpenStream (brokered chat) opens the owned V2 endpoint.
if c.Backend == "v2" {
return c, nil
}
if err := c.startServe(ctx); err != nil {
return nil, err
}
return c, nil
}
// OpenStream opens the single owned `opencode serve` endpoint for either backend
// so a caller that needs a URL-bearing, SSE-capable connection (brokered chat)
// gets one on the installed V2 CLI too. The V2 server exposes the authenticated
// SSE event firehose at /api/event and the /api HTTP surface; the native serve
// exposes /event and the translated /api surface. Stage generation keeps using
// Open (the unstarted V2 connection plus its `api` subcommand), so this starts
// no process for it and there is never a second transport.
func OpenStream(ctx context.Context, executable, directory, backend string) (*Connection, error) {
c, err := newConnection(ctx, executable, directory, backend)
if err != nil {
return nil, err
}
if err := c.startServe(ctx); err != nil {
return nil, err
}
return c, nil
}
// OpenChat detects the installed backend and opens the owned, URL-bearing
// connection the brokered chat adapter streams from. main and the chat live test
// call this one selection function so their Detect/Open logic cannot drift.
func OpenChat(ctx context.Context, executable, directory string) (*Connection, error) {
if executable == "" {
executable = Executable()
}
backend, err := Detect(ctx, executable)
if err != nil {
return nil, err
}
return OpenStream(ctx, executable, directory, backend)
}
// newConnection resolves the executable/directory defaults, detects the backend
// when it is empty, and returns the bare, not-yet-opened connection. It is the
// shared construction path for Open and OpenStream so backend validation lives
// once.
func newConnection(ctx context.Context, executable, directory, backend string) (*Connection, error) {
if executable == "" {
executable = Executable()
}
@@ -140,33 +193,51 @@ func Open(ctx context.Context, executable, directory, backend string) (*Connecti
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" {
if backend != "v1" && backend != "v2" {
return nil, fmt.Errorf("unknown OpenCode backend %q", backend)
}
return &Connection{Backend: backend, Executable: executable, Directory: directory, models: map[string]map[string]string{}, responses: map[string][]byte{}}, nil
}
// serverUser is the HTTP basic-auth username the owned serve process expects.
// The native serve authenticates the fixed "pipelines" user; the V2 API server
// authenticates the fixed "opencode" user regardless of
// OPENCODE_SERVER_USERNAME, verified against the installed 2.0.20 binary.
func (c *Connection) serverUser() string {
if c.Backend == "v2" {
return "opencode"
}
return "pipelines"
}
// startServe launches one owned `opencode serve` process on loopback, injects the
// ephemeral password, discovers the URL and verifies the backend-specific health
// contract. Close terminates it. It is idempotent so a connection only ever owns
// one process.
func (c *Connection) startServe(ctx context.Context) error {
if c.process != nil {
return nil
}
secret := make([]byte, 32)
if _, err := rand.Read(secret); err != nil {
return nil, err
return err
}
c.password = hex.EncodeToString(secret)
c.process = exec.Command(executable, "serve", "--hostname", "127.0.0.1", "--port", "0")
c.process.Dir = directory
c.process = exec.Command(c.Executable, "serve", "--hostname", "127.0.0.1", "--port", "0")
c.process.Dir = c.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")
c.process.Env = append(c.process.Env, "OPENCODE_SERVER_PASSWORD="+c.password, "OPENCODE_SERVER_USERNAME="+c.serverUser())
stdout, err := c.process.StdoutPipe()
if err != nil {
return nil, err
return err
}
c.process.Stderr = io.Discard
if err = c.process.Start(); err != nil {
return nil, err
return err
}
c.done = make(chan error, 1)
go func() { c.done <- c.process.Wait() }()
@@ -190,21 +261,44 @@ func Open(ctx context.Context, executable, directory, backend string) (*Connecti
case c.URL = <-address:
case <-c.done:
c.process = nil
return nil, fmt.Errorf("OpenCode serve exited before becoming ready")
return fmt.Errorf("OpenCode serve exited before becoming ready")
case <-startup.Done():
c.Close()
return nil, fmt.Errorf("OpenCode serve startup: %w", startup.Err())
return fmt.Errorf("OpenCode serve startup: %w", startup.Err())
}
health, err := c.Native(startup, "get", "/global/health", nil)
if err := c.checkHealth(startup); err != nil {
c.Close()
return err
}
return nil
}
// checkHealth verifies the backend-specific readiness contract after the serve
// process prints its URL: the native serve answers /global/health, the V2 API
// server answers /api/info. Both use the same owned credentials the rest of the
// adapter uses, so a reachable but unauthorized endpoint is not mistaken for a
// healthy one.
func (c *Connection) checkHealth(ctx context.Context) error {
if c.Backend == "v2" {
info, err := c.Native(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("OpenCode serve did not return the expected V2 info contract")
}
return nil
}
health, err := c.Native(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 == "" {
c.Close()
return nil, fmt.Errorf("OpenCode serve did not return the expected native health contract")
return fmt.Errorf("OpenCode serve did not return the expected native health contract")
}
return c, nil
return nil
}
func (c *Connection) Close() {
@@ -246,7 +340,7 @@ func (c *Connection) Native(ctx context.Context, method, path string, body any)
return nil, err
}
request.Header.Set("Content-Type", "application/json")
request.SetBasicAuth("pipelines", c.password)
request.SetBasicAuth(c.serverUser(), c.password)
response, err := http.DefaultClient.Do(request)
if err != nil {
if ctx.Err() != nil {
@@ -300,7 +394,7 @@ func (c *Connection) EventStream(ctx context.Context) (io.ReadCloser, error) {
return nil, err
}
request.Header.Set("Accept", "text/event-stream")
request.SetBasicAuth("pipelines", c.password)
request.SetBasicAuth(c.serverUser(), c.password)
response, err := http.DefaultClient.Do(request)
if err != nil {
if ctx.Err() != nil {