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:
@@ -0,0 +1,355 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Chat is the brokered OpenCode chat adapter (route B in the research): the
|
||||
// Pipelines server owns the OpenCode endpoint and credentials and turns the v2
|
||||
// HTTP API into protocol.ChatEventFrame frames. It reuses the owned-endpoint
|
||||
// semantics, the session-id shape and the 64 KiB / 1 MiB bounds of Connection so
|
||||
// no second transport or credential path is introduced.
|
||||
type Chat struct {
|
||||
conn *Connection
|
||||
}
|
||||
|
||||
// NewChat brokers chat for one owned OpenCode endpoint. The connection must be
|
||||
// able to reach the /api HTTP surface: an owned serve connection (translated by
|
||||
// Connection.Call) or a connection that already carries the v2 API URL.
|
||||
func NewChat(conn *Connection) *Chat { return &Chat{conn: conn} }
|
||||
|
||||
// ValidSessionID reports whether id has the OpenCode session-id shape the
|
||||
// native adapter already accepts. It is the single validation shared by the
|
||||
// chat adapter and callers that must reject a request before any OpenCode call.
|
||||
func ValidSessionID(id string) bool { return sessionID.MatchString(id) }
|
||||
|
||||
// Prompt forwards one chat prompt through the existing Call translation
|
||||
// (authenticated, bounded, directory-scoped). The endpoint returns the inbox
|
||||
// envelope immediately; the reply arrives on Stream.
|
||||
func (c *Chat) Prompt(ctx context.Context, id, text string) error {
|
||||
if !sessionID.MatchString(id) {
|
||||
return fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return fmt.Errorf("empty chat prompt")
|
||||
}
|
||||
body := map[string]any{"parts": []map[string]string{{"type": "text", "text": text}}}
|
||||
if _, err := c.conn.Call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Interrupt aborts the session's active run, reusing the same translated surface.
|
||||
func (c *Chat) Interrupt(ctx context.Context, id string) error {
|
||||
if !sessionID.MatchString(id) {
|
||||
return fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
if _, err := c.conn.Call(ctx, "post", "/api/session/"+id+"/interrupt", map[string]any{}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Messages reads one session's stored turns. On the owned serve backend it
|
||||
// reuses Connection.Messages, including its read-only OutputFormat readback
|
||||
// fallback, instead of duplicating that path. It maps the verified assistant
|
||||
// content parts (text | reasoning | tool) onto protocol.ChatMessage.
|
||||
func (c *Chat) Messages(ctx context.Context, id string, limit int) ([]protocol.ChatMessage, error) {
|
||||
if !sessionID.MatchString(id) {
|
||||
return nil, fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
if c.conn.Backend == "v1" {
|
||||
data, err = c.conn.Messages(ctx, id)
|
||||
} else {
|
||||
path := "/api/session/" + id + "/message"
|
||||
if limit > 0 {
|
||||
path += fmt.Sprintf("?limit=%d", limit)
|
||||
}
|
||||
data, err = c.conn.Call(ctx, "get", path, nil)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decodeChatMessages(id, data)
|
||||
}
|
||||
|
||||
// Reply posts a permission decision, mirroring the documented endpoint.
|
||||
func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
|
||||
if !sessionID.MatchString(request.SessionID) {
|
||||
return fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
if request.RequestID == "" {
|
||||
return fmt.Errorf("missing permission request id")
|
||||
}
|
||||
decision := request.Decision
|
||||
if decision != protocol.ChatDecisionOnce && decision != protocol.ChatDecisionAlways && decision != protocol.ChatDecisionReject {
|
||||
return fmt.Errorf("invalid permission decision %q", decision)
|
||||
}
|
||||
body := map[string]any{"decision": decision}
|
||||
if request.Message != "" {
|
||||
body["message"] = request.Message
|
||||
}
|
||||
path := "/api/session/" + request.SessionID + "/permission/" + request.RequestID + "/reply"
|
||||
if _, err := c.conn.Call(ctx, "post", path, body); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stream subscribes to the OpenCode event firehose and invokes emit for every
|
||||
// frame belonging to sessionID. It reads one bounded SSE frame at a time and
|
||||
// never polls the per-session message log; the global firehose is the only
|
||||
// source of token-level deltas on this build. ready, when non-nil, is called
|
||||
// once the subscription is attached and before the first frame is read, so a
|
||||
// caller can post its prompt only after the stream is listening (the firehose
|
||||
// has no replay cursor). Canceling ctx cancels the subscription and returns
|
||||
// without leaking a connection.
|
||||
func (c *Chat) Stream(ctx context.Context, id string, ready func(), emit func(protocol.ChatEventFrame) error) error {
|
||||
if !sessionID.MatchString(id) {
|
||||
return fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
body, err := c.conn.EventStream(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer body.Close()
|
||||
if ready != nil {
|
||||
ready()
|
||||
}
|
||||
return scanChatEvents(ctx, body, id, emit)
|
||||
}
|
||||
|
||||
// scanChatEvents turns an SSE body into protocol frames, one bounded frame at a
|
||||
// time. Heartbeat comments, blank lines and unrelated event types are ignored;
|
||||
// malformed JSON fails the stream instead of producing a malformed frame. The
|
||||
// last assistant message id is retained so a later tool/step event that omits it
|
||||
// still attributes every frame to a stable message.
|
||||
func scanChatEvents(ctx context.Context, body io.Reader, sessionID string, emit func(protocol.ChatEventFrame) error) error {
|
||||
scanner := bufio.NewScanner(body)
|
||||
scanner.Buffer(make([]byte, 0, 64<<10), MaxResponse)
|
||||
lastMessageID := ""
|
||||
for scanner.Scan() {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
line := bytes.TrimSpace(scanner.Bytes())
|
||||
if !bytes.HasPrefix(line, []byte("data:")) {
|
||||
continue
|
||||
}
|
||||
payload := bytes.TrimSpace(line[len("data:"):])
|
||||
if len(payload) == 0 {
|
||||
continue
|
||||
}
|
||||
frame, ok, err := NormalizeChatEvent(payload, sessionID, &lastMessageID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if frame.MessageID != "" {
|
||||
lastMessageID = frame.MessageID
|
||||
}
|
||||
if err := emit(frame); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return fmt.Errorf("OpenCode event stream read failed")
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// 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.
|
||||
type chatEvent struct {
|
||||
SessionID string `json:"sessionID"`
|
||||
MessageID string `json:"assistantMessageID"`
|
||||
MessageIDAlt string `json:"messageID"`
|
||||
Delta string `json:"delta"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Input json.RawMessage `json:"input"`
|
||||
Content []protocol.ChatToolContent `json:"content"`
|
||||
Metadata map[string]any `json:"metadata"`
|
||||
Error *protocol.ChatError `json:"error"`
|
||||
Ordinal int `json:"ordinal"`
|
||||
Index int `json:"index"`
|
||||
Step int `json:"step"`
|
||||
InputTokens int `json:"inputTokens"`
|
||||
OutputTokens int `json:"outputTokens"`
|
||||
Cost float64 `json:"cost"`
|
||||
Tokens struct {
|
||||
Input int `json:"input"`
|
||||
Output int `json:"output"`
|
||||
} `json:"tokens"`
|
||||
}
|
||||
|
||||
// NormalizeChatEvent maps one OpenCode firehose `data:` payload to a
|
||||
// protocol.ChatEventFrame. ok is false for an event type this adapter does not
|
||||
// surface or one belonging to a different session, so the caller can skip it
|
||||
// without emitting a frame. Malformed JSON returns an error and never a frame.
|
||||
func NormalizeChatEvent(payload []byte, sessionID string, lastMessageID *string) (protocol.ChatEventFrame, bool, error) {
|
||||
var outer struct {
|
||||
Type string `json:"type"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &outer); err != nil {
|
||||
return protocol.ChatEventFrame{}, false, fmt.Errorf("malformed OpenCode event: %w", err)
|
||||
}
|
||||
if outer.Type == "" || len(outer.Data) == 0 {
|
||||
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)
|
||||
}
|
||||
if data.SessionID != sessionID {
|
||||
return protocol.ChatEventFrame{}, false, nil
|
||||
}
|
||||
messageID := data.MessageID
|
||||
if messageID == "" {
|
||||
messageID = data.MessageIDAlt
|
||||
}
|
||||
if messageID == "" && lastMessageID != nil {
|
||||
messageID = *lastMessageID
|
||||
}
|
||||
// Every pushed frame must carry a stable message id so the client can
|
||||
// attribute it; without one this is not a chat frame.
|
||||
if messageID == "" {
|
||||
return protocol.ChatEventFrame{}, false, nil
|
||||
}
|
||||
frame := protocol.ChatEventFrame{SessionID: sessionID, MessageID: messageID}
|
||||
switch {
|
||||
case outer.Type == "session.text.delta":
|
||||
frame.Kind = protocol.ChatEventText
|
||||
frame.Delta = data.Delta
|
||||
frame.Part = &protocol.ChatPart{Type: protocol.ChatPartText, ID: fmt.Sprintf("%s#%d", messageID, data.Ordinal)}
|
||||
case outer.Type == "session.reasoning.delta":
|
||||
frame.Kind = protocol.ChatEventReasoning
|
||||
frame.Delta = data.Delta
|
||||
frame.Part = &protocol.ChatPart{Type: protocol.ChatPartReasoning, ID: fmt.Sprintf("%s#%d", messageID, data.Ordinal)}
|
||||
case outer.Type == "session.step.started" || outer.Type == "session.step.streamed" || outer.Type == "session.step.ended":
|
||||
frame.Kind = protocol.ChatEventStep
|
||||
frame.Step = &protocol.ChatStep{Status: strings.TrimPrefix(outer.Type, "session.step."), Index: stepIndex(data)}
|
||||
case strings.HasPrefix(outer.Type, "session.tool."):
|
||||
status, ok := toolStatus(outer.Type)
|
||||
if !ok {
|
||||
return protocol.ChatEventFrame{}, false, nil
|
||||
}
|
||||
frame.Kind = protocol.ChatEventTool
|
||||
state := &protocol.ChatToolState{Status: status, Input: data.Input, Content: data.Content, Metadata: data.Metadata, Error: data.Error}
|
||||
frame.Part = &protocol.ChatPart{Type: protocol.ChatPartTool, ID: data.ID, Name: data.Name, State: state}
|
||||
case outer.Type == "session.usage.updated":
|
||||
frame.Kind = protocol.ChatEventUsage
|
||||
input, output := data.InputTokens, data.OutputTokens
|
||||
if data.Tokens.Input != 0 || data.Tokens.Output != 0 {
|
||||
input, output = data.Tokens.Input, data.Tokens.Output
|
||||
}
|
||||
frame.Usage = &protocol.ChatUsage{InputTokens: input, OutputTokens: output, Cost: data.Cost}
|
||||
default:
|
||||
return protocol.ChatEventFrame{}, false, nil
|
||||
}
|
||||
return frame, true, nil
|
||||
}
|
||||
|
||||
// toolStatus maps the verified tool event types onto the ToolState lifecycle.
|
||||
func toolStatus(eventType string) (string, bool) {
|
||||
switch eventType {
|
||||
case "session.tool.input.started", "session.tool.input.ended":
|
||||
return protocol.ChatToolStreaming, true
|
||||
case "session.tool.called", "session.tool.progress":
|
||||
return protocol.ChatToolRunning, true
|
||||
case "session.tool.success":
|
||||
return protocol.ChatToolCompleted, true
|
||||
case "session.tool.failed":
|
||||
return protocol.ChatToolError, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func stepIndex(data chatEvent) int {
|
||||
if data.Step > 0 {
|
||||
return data.Step
|
||||
}
|
||||
return data.Index
|
||||
}
|
||||
|
||||
// decodeChatMessages maps the native /message response onto the protocol chat
|
||||
// history shape. Assistant content parts are text, reasoning and tool; a user
|
||||
// turn is the prompt text. It never re-derives provider shapes.
|
||||
type nativeChatMessage struct {
|
||||
Info struct {
|
||||
ID string `json:"id"`
|
||||
Role string `json:"role"`
|
||||
ModelID string `json:"modelID"`
|
||||
Agent string `json:"agent"`
|
||||
CreatedAt int64 `json:"created"`
|
||||
} `json:"info"`
|
||||
Parts []struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
Text string `json:"text"`
|
||||
Name string `json:"name"`
|
||||
Executed bool `json:"executed"`
|
||||
State *protocol.ChatToolState `json:"state"`
|
||||
Time *protocol.ChatTime `json:"time"`
|
||||
} `json:"parts"`
|
||||
}
|
||||
|
||||
// chatMessageRecords accepts both message envelopes the two surfaces return:
|
||||
// the V2 HTTP API wraps them in {"data":[...]} while the native serve readback
|
||||
// returns a bare array. An unrecognised body is an error, never empty history.
|
||||
func chatMessageRecords(data []byte) ([]nativeChatMessage, error) {
|
||||
var response struct {
|
||||
Data []nativeChatMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &response); err == nil && response.Data != nil {
|
||||
return response.Data, nil
|
||||
}
|
||||
var records []nativeChatMessage
|
||||
if err := json.Unmarshal(data, &records); err != nil {
|
||||
return nil, fmt.Errorf("invalid OpenCode message response")
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func decodeChatMessages(sessionID string, data []byte) ([]protocol.ChatMessage, error) {
|
||||
records, err := chatMessageRecords(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
messages := make([]protocol.ChatMessage, 0, len(records))
|
||||
for _, message := range records {
|
||||
role := message.Info.Role
|
||||
if role != protocol.ChatRoleUser && role != protocol.ChatRoleAssistant {
|
||||
continue
|
||||
}
|
||||
out := protocol.ChatMessage{ID: message.Info.ID, SessionID: sessionID, Role: role, Model: message.Info.ModelID, Agent: message.Info.Agent, CreatedAt: message.Info.CreatedAt}
|
||||
for _, part := range message.Parts {
|
||||
switch part.Type {
|
||||
case protocol.ChatPartText, protocol.ChatPartReasoning:
|
||||
out.Parts = append(out.Parts, protocol.ChatPart{Type: part.Type, ID: part.ID, Text: part.Text})
|
||||
case protocol.ChatPartTool:
|
||||
out.Parts = append(out.Parts, protocol.ChatPart{Type: protocol.ChatPartTool, ID: part.ID, Name: part.Name, Executed: part.Executed, State: part.State, Time: part.Time})
|
||||
}
|
||||
}
|
||||
messages = append(messages, out)
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestNormalizeChatEvent(t *testing.T) {
|
||||
last := "msg_prev"
|
||||
cases := []struct {
|
||||
name string
|
||||
payload string
|
||||
last *string
|
||||
wantOK bool
|
||||
wantKind string
|
||||
wantMsg string
|
||||
wantDelta string
|
||||
wantStatus string
|
||||
wantStep string
|
||||
wantUsage *protocol.ChatUsage
|
||||
}{
|
||||
{name: "text delta", payload: `{"type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0,"delta":"hel"}}`, wantOK: true, wantKind: protocol.ChatEventText, wantMsg: "msg_1", wantDelta: "hel"},
|
||||
{name: "reasoning delta", payload: `{"type":"session.reasoning.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":1,"delta":"hmm"}}`, wantOK: true, wantKind: protocol.ChatEventReasoning, wantMsg: "msg_1", wantDelta: "hmm"},
|
||||
{name: "step ended", payload: `{"type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","step":2}}`, wantOK: true, wantKind: protocol.ChatEventStep, wantStep: protocol.ChatStepEnded},
|
||||
{name: "tool streaming", payload: `{"type":"session.tool.input.started","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","input":"{\"command\""}}`, wantOK: true, wantKind: protocol.ChatEventTool, wantStatus: protocol.ChatToolStreaming},
|
||||
{name: "tool running", payload: `{"type":"session.tool.called","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","input":{"command":"ls"}}}`, wantOK: true, wantKind: protocol.ChatEventTool, wantStatus: protocol.ChatToolRunning},
|
||||
{name: "tool completed", payload: `{"type":"session.tool.success","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","content":[{"type":"text","text":"ok"}]}}`, wantOK: true, wantKind: protocol.ChatEventTool, wantStatus: protocol.ChatToolCompleted},
|
||||
{name: "tool failed", payload: `{"type":"session.tool.failed","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","error":{"type":"tool","message":"boom"}}}`, wantOK: true, wantKind: protocol.ChatEventTool, wantStatus: protocol.ChatToolError},
|
||||
{name: "usage", payload: `{"type":"session.usage.updated","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","tokens":{"input":12,"output":34},"cost":0.001}}`, wantOK: true, wantKind: protocol.ChatEventUsage, wantUsage: &protocol.ChatUsage{InputTokens: 12, OutputTokens: 34, Cost: 0.001}},
|
||||
{name: "message id fallback", payload: `{"type":"session.step.started","data":{"sessionID":"ses_1","index":1}}`, last: &last, wantOK: true, wantKind: protocol.ChatEventStep, wantMsg: "msg_prev", wantStep: protocol.ChatStepStarted},
|
||||
{name: "foreign session skipped", payload: `{"type":"session.text.delta","data":{"sessionID":"ses_other","delta":"x"}}`, wantOK: false},
|
||||
{name: "unknown type skipped", payload: `{"type":"session.created","data":{"sessionID":"ses_1"}}`, wantOK: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
lastID := tc.last
|
||||
frame, ok, err := NormalizeChatEvent([]byte(tc.payload), "ses_1", lastID)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ok != tc.wantOK {
|
||||
t.Fatalf("ok = %v, want %v", ok, tc.wantOK)
|
||||
}
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if frame.SessionID != "ses_1" || frame.Kind != tc.wantKind {
|
||||
t.Fatalf("frame = %+v", frame)
|
||||
}
|
||||
if tc.wantMsg != "" && frame.MessageID != tc.wantMsg {
|
||||
t.Fatalf("messageID = %q, want %q", frame.MessageID, tc.wantMsg)
|
||||
}
|
||||
if tc.wantDelta != "" && frame.Delta != tc.wantDelta {
|
||||
t.Fatalf("delta = %q, want %q", frame.Delta, tc.wantDelta)
|
||||
}
|
||||
if tc.wantStatus != "" && (frame.Part == nil || frame.Part.State == nil || frame.Part.State.Status != tc.wantStatus) {
|
||||
t.Fatalf("tool state = %+v, want status %q", frame.Part, tc.wantStatus)
|
||||
}
|
||||
if tc.wantStep != "" && (frame.Step == nil || frame.Step.Status != tc.wantStep) {
|
||||
t.Fatalf("step = %+v, want %q", frame.Step, tc.wantStep)
|
||||
}
|
||||
if tc.wantUsage != nil && (frame.Usage == nil || *frame.Usage != *tc.wantUsage) {
|
||||
t.Fatalf("usage = %+v, want %+v", frame.Usage, tc.wantUsage)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeChatEventRejectsMalformedJSON(t *testing.T) {
|
||||
if _, _, err := NormalizeChatEvent([]byte(`{"type":`), "ses_1", nil); err == nil {
|
||||
t.Fatal("malformed event must return an error, not a frame")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatStreamFiltersFrames(t *testing.T) {
|
||||
var prompts atomic.Int32
|
||||
frames := []string{
|
||||
`{"id":"evt_1","type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","ordinal":0,"delta":"hello "}}`,
|
||||
`{"id":"evt_2","type":"session.text.delta","data":{"sessionID":"ses_other","assistantMessageID":"msg_x","ordinal":0,"delta":"ignore"}}`,
|
||||
`{"id":"evt_3","type":"session.tool.called","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","id":"call_1","name":"shell","input":{"command":"ls"}}}`,
|
||||
`{"id":"evt_4","type":"session.step.ended","data":{"sessionID":"ses_1","assistantMessageID":"msg_1","step":1}}`,
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/api/session/ses_1/prompt":
|
||||
prompts.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/api/event":
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
for _, frame := range frames {
|
||||
_, _ = w.Write([]byte("data: " + frame + "\n\n"))
|
||||
}
|
||||
default:
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
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
|
||||
err := chat.Stream(ctx, "ses_1", nil, func(frame protocol.ChatEventFrame) error {
|
||||
got = append(got, frame)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("stream: %v", err)
|
||||
}
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("got %d frames, want 3 (foreign session filtered): %+v", len(got), got)
|
||||
}
|
||||
if got[0].Kind != protocol.ChatEventText || got[0].Delta != "hello " || got[0].MessageID != "msg_1" || got[0].Part == nil || got[0].Part.ID == "" {
|
||||
t.Fatalf("text frame = %+v", got[0])
|
||||
}
|
||||
if got[1].Kind != protocol.ChatEventTool || got[1].Part == nil || got[1].Part.State == nil || got[1].Part.State.Status != protocol.ChatToolRunning {
|
||||
t.Fatalf("tool frame = %+v", got[1])
|
||||
}
|
||||
if got[2].Kind != protocol.ChatEventStep || got[2].Step == nil || got[2].Step.Status != protocol.ChatStepEnded {
|
||||
t.Fatalf("step frame = %+v", got[2])
|
||||
}
|
||||
for _, frame := range got {
|
||||
if frame.SessionID != "ses_1" || frame.MessageID == "" {
|
||||
t.Fatalf("frame missing stable ids: %+v", frame)
|
||||
}
|
||||
}
|
||||
|
||||
if err := chat.Prompt(ctx, "ses_1", "hello"); err != nil {
|
||||
t.Fatalf("prompt: %v", err)
|
||||
}
|
||||
if prompts.Load() != 1 {
|
||||
t.Fatalf("prompt posts = %d, want 1", prompts.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatRejectsInvalidSessionWithoutCalling(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
ctx := context.Background()
|
||||
if err := chat.Prompt(ctx, "not-a-session", "hi"); err == nil {
|
||||
t.Fatal("invalid session id must be rejected")
|
||||
}
|
||||
if err := chat.Stream(ctx, "", nil, func(protocol.ChatEventFrame) error { return nil }); err == nil {
|
||||
t.Fatal("empty session id must be rejected")
|
||||
}
|
||||
if err := chat.Interrupt(ctx, "bad id"); err == nil {
|
||||
t.Fatal("invalid interrupt session id must be rejected")
|
||||
}
|
||||
if calls.Load() != 0 {
|
||||
t.Fatalf("invalid requests reached the service: %d", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeChatMessages(t *testing.T) {
|
||||
raw := []byte(`{"data":[{"info":{"id":"msg_1","role":"assistant","modelID":"m","agent":"build","created":10},"parts":[{"type":"text","id":"p1","text":"hi"},{"type":"reasoning","id":"p2","text":"hmm"},{"type":"tool","id":"call_1","name":"shell","executed":true,"state":{"status":"completed","input":{"command":"ls"},"content":[{"type":"text","text":"ok"}]},"time":{"created":1,"ran":2,"completed":3}}]}]}`)
|
||||
messages, err := decodeChatMessages("ses_1", raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(messages) != 1 || messages[0].Role != protocol.ChatRoleAssistant || len(messages[0].Parts) != 3 {
|
||||
t.Fatalf("messages = %+v", messages)
|
||||
}
|
||||
tool := messages[0].Parts[2]
|
||||
if tool.Type != protocol.ChatPartTool || tool.Name != "shell" || tool.State == nil || tool.State.Status != protocol.ChatToolCompleted || tool.Time == nil {
|
||||
t.Fatalf("tool part = %+v", tool)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatStreamRejectsMalformedEvent(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: {\"type\":\"session.text.delta\",\"data\":{\"sessionID\":\"ses_1\"\n\n"))
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
emitted := 0
|
||||
err := chat.Stream(context.Background(), "ses_1", nil, func(protocol.ChatEventFrame) error {
|
||||
emitted++
|
||||
return nil
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("malformed event JSON must fail the stream")
|
||||
}
|
||||
if emitted != 0 {
|
||||
t.Fatalf("malformed event produced %d frames", emitted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatStreamRequiresEndpoint(t *testing.T) {
|
||||
chat := NewChat(&Connection{Backend: "v2"})
|
||||
err := chat.Stream(context.Background(), "ses_1", nil, func(protocol.ChatEventFrame) error { return nil })
|
||||
if err == nil || !strings.Contains(err.Error(), "event-stream endpoint") {
|
||||
t.Fatalf("expected endpoint error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeChatEventWithoutMessageID(t *testing.T) {
|
||||
for _, payload := range []string{
|
||||
`{"type":"session.text.delta","data":{"sessionID":"ses_1","ordinal":0,"delta":"x"}}`,
|
||||
`{"type":"session.tool.called","data":{"sessionID":"ses_1","id":"call_1","name":"shell","input":{"command":"ls"}}}`,
|
||||
`{"type":"session.usage.updated","data":{"sessionID":"ses_1","tokens":{"input":1,"output":2}}}`,
|
||||
} {
|
||||
if _, ok, err := NormalizeChatEvent([]byte(payload), "ses_1", nil); err != nil || ok {
|
||||
t.Fatalf("event without a message id produced a frame: ok=%v err=%v", ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatV1ConnectionDrivesThroughCall drives the adapter through a real
|
||||
// (serve-shaped) Connection so the /api -> native translation and the owned
|
||||
// endpoint are exercised, not a direct v2 URL shortcut.
|
||||
func TestChatV1ConnectionDrivesThroughCall(t *testing.T) {
|
||||
var sawPrompt, sawMessages bool
|
||||
var promptBody string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/session/ses_1/message":
|
||||
// Call must have translated /api/session/{id}/prompt to this path.
|
||||
sawPrompt = true
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
promptBody = string(body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"ok":true}`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/session/ses_1/message":
|
||||
sawMessages = true
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`[{"info":{"id":"msg_1","role":"assistant","modelID":"m","agent":"build","created":10},"parts":[{"type":"text","id":"p1","text":"hi"}]}]`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/event":
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: {\"type\":\"session.text.delta\",\"data\":{\"sessionID\":\"ses_1\",\"assistantMessageID\":\"msg_1\",\"ordinal\":0,\"delta\":\"hi\"}}\n\n"))
|
||||
default:
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
chat := NewChat(&Connection{Backend: "v1", URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}})
|
||||
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 !sawPrompt {
|
||||
t.Fatal("prompt was not translated to the native path")
|
||||
}
|
||||
// The translated body must carry the prompt text: the chat adapter sends the
|
||||
// V2 `parts` shape and the v1 translation has to preserve it, or the native
|
||||
// serve process receives an empty prompt.
|
||||
var sent struct {
|
||||
Parts []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
} `json:"parts"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(promptBody), &sent); err != nil {
|
||||
t.Fatalf("prompt body: %v (%s)", err, promptBody)
|
||||
}
|
||||
if len(sent.Parts) != 1 || sent.Parts[0].Type != protocol.ChatPartText || sent.Parts[0].Text != "hello" {
|
||||
t.Fatalf("prompt text not carried through the v1 translation: %s", promptBody)
|
||||
}
|
||||
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)
|
||||
}
|
||||
if len(got) != 1 || got[0].Kind != protocol.ChatEventText || got[0].MessageID != "msg_1" {
|
||||
t.Fatalf("stream frames = %+v", got)
|
||||
}
|
||||
messages, err := chat.Messages(ctx, "ses_1", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("messages: %v", err)
|
||||
}
|
||||
if !sawMessages || len(messages) != 1 || messages[0].ID != "msg_1" {
|
||||
t.Fatalf("messages = %+v", messages)
|
||||
}
|
||||
}
|
||||
@@ -277,3 +277,40 @@ func (c *Connection) Native(ctx context.Context, method, path string, body any)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// EventStream opens the authenticated SSE firehose for the connection's owned
|
||||
// endpoint using the same URL and credentials as Native, so chat never builds a
|
||||
// parallel HTTP client. The path follows the backend surface: the native serve
|
||||
// stream is /event, the V2 HTTP API is /api/event. The caller closes the body.
|
||||
func (c *Connection) EventStream(ctx context.Context) (io.ReadCloser, error) {
|
||||
if c == nil || c.URL == "" {
|
||||
return nil, fmt.Errorf("OpenCode chat requires an event-stream endpoint")
|
||||
}
|
||||
path := "/api/event"
|
||||
if c.Backend == "v1" {
|
||||
path = "/event"
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(c.URL, "/")+path, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Header.Set("Accept", "text/event-stream")
|
||||
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 event stream request failed")
|
||||
}
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
evidence, _ := io.ReadAll(io.LimitReader(response.Body, 16<<10))
|
||||
response.Body.Close()
|
||||
return nil, fmt.Errorf("OpenCode event stream failed (HTTP %d): %s", response.StatusCode, strings.TrimSpace(string(evidence)))
|
||||
}
|
||||
if !strings.HasPrefix(response.Header.Get("Content-Type"), "text/event-stream") {
|
||||
response.Body.Close()
|
||||
return nil, fmt.Errorf("OpenCode event stream returned a non-SSE response")
|
||||
}
|
||||
return response.Body, nil
|
||||
}
|
||||
|
||||
@@ -65,9 +65,14 @@ func messageText(data []byte) (string, error) {
|
||||
|
||||
// Call adapts the pipeline's existing V2 command contract to the native stable API.
|
||||
// Sessions still use the same account/database; only our loopback serve process is owned.
|
||||
// A connection whose backend already speaks the /api HTTP surface forwards the path
|
||||
// unchanged: only the v1 serve surface needs the /api -> native translation below.
|
||||
func (c *Connection) Call(ctx context.Context, method, path string, body any) ([]byte, error) {
|
||||
if c.Backend != "v1" {
|
||||
return nil, fmt.Errorf("native adapter requires the serve backend")
|
||||
if c.URL == "" {
|
||||
return nil, fmt.Errorf("native adapter requires the serve backend")
|
||||
}
|
||||
return c.Native(ctx, method, path, body)
|
||||
}
|
||||
if path == "/api/session" && method == "post" {
|
||||
data, _ := json.Marshal(body)
|
||||
@@ -152,6 +157,9 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
|
||||
Prompt string `json:"prompt"`
|
||||
Text string `json:"text"`
|
||||
Format json.RawMessage `json:"format"`
|
||||
Parts []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"parts"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &request); err != nil {
|
||||
return nil, err
|
||||
@@ -160,6 +168,17 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
|
||||
if text == "" {
|
||||
text = request.Text
|
||||
}
|
||||
// The brokered chat adapter sends the V2 prompt shape (a parts array);
|
||||
// accept it so the native translation carries the text unchanged instead
|
||||
// of posting an empty prompt.
|
||||
if text == "" {
|
||||
for _, part := range request.Parts {
|
||||
if part.Text != "" {
|
||||
text = part.Text
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
payload := map[string]any{"model": c.models[id], "parts": []map[string]string{{"type": "text", "text": text}}}
|
||||
if len(request.Format) > 0 {
|
||||
supported, err := c.supportsFormat(ctx, request.Format)
|
||||
|
||||
Reference in New Issue
Block a user