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:
+113
-19
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user