Stream brokered OpenCode chat replies over /connect

Add the server-side half of the brokered chat path (route B): the
opencode.Chat adapter forwards chat_prompt to POST
/api/session/{id}/prompt through the owned Connection.Call translation
and derives chat_event frames from the authenticated /api/event SSE
firehose (text and reasoning deltas, tool parts with their status
transitions, step and usage). Every pushed frame carries a stable
session and message id, with a last-message-id fallback so step/tool
events that omit the assistant message id stay attributable.

The /connect handler keeps per-session retained state (chatHub) capped at
1 MiB with least-recently-updated eviction at 128 turns, so a
reconnecting client re-syncs through chat_messages instead of replaying
deltas the OpenCode per-session log never resends. Prompt dispatch
subscribes before posting and buffers pre-ack frames to preserve order,
and cancels the stream on disconnect so no goroutine leaks. chat_sessions
and chat_create are declared but not yet brokered: they answer with an
explicit protocol error rather than the generic Pong.

Reuse the existing transport, validation and normalization; no second
OpenCode transport or credential path is introduced.

Tests: protocol golden round-trip, adapter normalization + v1/v2 Call
translation, and handler ack/stream/validation/resume/disconnect, plus a
real-adapter no-tool evidence harness.
This commit is contained in:
2026-10-16 04:09:14 +01:00
parent 9fa09e6ce8
commit b8b545accd
9 changed files with 1786 additions and 10 deletions
+25 -8
View File
@@ -5,6 +5,7 @@ import (
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/coder/websocket"
@@ -21,6 +22,10 @@ type Options struct {
// ArtifactsRoot overrides where stage artifacts live. Empty uses the store's
// directory (the database's parent), matching the data-directory default.
ArtifactsRoot string
// Chat brokers OpenCode chat traffic over /connect. Nil answers every
// chat_* request with a protocol error; a configured server passes an
// *opencode.Chat bound to the owned endpoint.
Chat chatBroker
}
// Handler serves the persistent connection with default options. Canceling ctx
@@ -34,6 +39,7 @@ func Handler(ctx context.Context, stores ...*pipeline.Store) http.Handler {
func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipeline.Store) http.Handler {
build := buildinfo.Current()
started := time.Now()
hub := newChatHub()
mux := http.NewServeMux()
var runs *runner
var runErr error
@@ -70,16 +76,27 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
}
defer conn.CloseNow()
conn.SetReadLimit(2 << 20)
// connCtx is canceled when this connection's read loop returns, so a
// chat subscription started for the client stops on disconnect. A single
// write mutex serializes the read loop's responses and the chat stream
// goroutine, which must never interleave partial websocket writes.
connCtx, connCancel := context.WithCancel(ctx)
defer connCancel()
var writeMu sync.Mutex
write := func(message protocol.Message) error {
writeMu.Lock()
defer writeMu.Unlock()
writeCtx, cancel := context.WithTimeout(connCtx, 5*time.Second)
defer cancel()
return wsjson.Write(writeCtx, conn, message)
}
if len(stores) > 0 {
items, err := stores[0].List(ctx)
if err != nil {
log.Printf("list pipelines: %v", err)
return
}
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err = wsjson.Write(writeCtx, conn, protocol.Message{Type: protocol.PipelineList, Pipelines: items, NotificationEndpoints: notificationEndpoints()})
cancel()
if err != nil {
if err := write(protocol.Message{Type: protocol.PipelineList, Pipelines: items, NotificationEndpoints: notificationEndpoints()}); err != nil {
return
}
}
@@ -89,6 +106,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
return
}
log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version)
if handleChat(connCtx, request, options.Chat, hub, write) {
continue
}
response := protocol.Message{Type: protocol.Pong, ID: request.ID}
if request.Type == protocol.List || request.Type == protocol.Submit {
response.NotificationEndpoints = notificationEndpoints()
@@ -196,10 +216,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
response.Error = "execution unavailable: " + runErr.Error()
}
}
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := wsjson.Write(writeCtx, conn, response)
cancel()
if err != nil {
if err := write(response); err != nil {
log.Printf("write response: %v", err)
return
}