Add brokered OpenCode chat wire types
Add the internal/protocol types the phone needs to talk to OpenCode chat through the Pipelines server (route B): the chat_* request/response type constants (sessions, create, prompt, messages, interrupt, reply) and the server-pushed chat_event frame, plus the part/status/role/tool-state/decision constant sets and payload structs modelled on the verified OpenCode shapes - an assistant turn is a list of parts (text | reasoning | tool), and a tool part carries name, executed, state.status (streaming | running | completed | error), state.input, state.content, state.metadata, state.error and epoch-millisecond timings. Add eight optional omitempty chat fields to the shared Message envelope, so older peers ignore them, and a golden round-trip test covering every new type, an exact-JSON pin of a tool chat_event frame, envelope preservation and omitempty. go test ./internal/protocol/... passes.
This commit is contained in:
@@ -0,0 +1,211 @@
|
|||||||
|
package protocol
|
||||||
|
|
||||||
|
import "encoding/json"
|
||||||
|
|
||||||
|
// Chat requests and responses are brokered by the Pipelines server (route B in
|
||||||
|
// the OpenCode chat research): the phone keeps talking only to /connect and the
|
||||||
|
// server holds the OpenCode credentials, translating each type below to the
|
||||||
|
// native service. Like every other exchange, a client sends
|
||||||
|
// Message{Type: ChatXxx, ID: <opaque>} and the server echoes the ID on the
|
||||||
|
// response.
|
||||||
|
//
|
||||||
|
// The payloads mirror the verified OpenCode shapes: an assistant turn is a list
|
||||||
|
// of parts (text | reasoning | tool), and a tool part carries name, state.status,
|
||||||
|
// state.input, state.content, state.metadata, state.error and epoch-millisecond
|
||||||
|
// timings. Timings stay integer milliseconds rather than RFC3339 strings so the
|
||||||
|
// brokered values match the service exactly; all list fields are optional so
|
||||||
|
// older peers ignore them.
|
||||||
|
const (
|
||||||
|
ChatSessions = "chat_sessions"
|
||||||
|
ChatCreate = "chat_create"
|
||||||
|
ChatPrompt = "chat_prompt"
|
||||||
|
ChatMessages = "chat_messages"
|
||||||
|
ChatInterrupt = "chat_interrupt"
|
||||||
|
ChatReply = "chat_reply"
|
||||||
|
// ChatEvent is the server-pushed frame; it is the only type the server
|
||||||
|
// sends without a matching request.
|
||||||
|
ChatEvent = "chat_event"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Content part types carried by ChatPart.Type and ChatEvent.Kind.
|
||||||
|
const (
|
||||||
|
ChatPartText = "text"
|
||||||
|
ChatPartReasoning = "reasoning"
|
||||||
|
ChatPartTool = "tool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChatEvent.Kind values pushed on the chat_event stream. Step and usage carry
|
||||||
|
// no ChatPart; they report turn progress and the turn's totals.
|
||||||
|
const (
|
||||||
|
ChatEventText = ChatPartText
|
||||||
|
ChatEventReasoning = ChatPartReasoning
|
||||||
|
ChatEventTool = ChatPartTool
|
||||||
|
ChatEventStep = "step"
|
||||||
|
ChatEventUsage = "usage"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChatStep.Status values, mirroring the OpenCode session.step events.
|
||||||
|
const (
|
||||||
|
ChatStepStarted = "started"
|
||||||
|
ChatStepStreamed = "streamed"
|
||||||
|
ChatStepEnded = "ended"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChatToolState.Status values, mirroring OpenCode's ToolState union.
|
||||||
|
const (
|
||||||
|
ChatToolStreaming = "streaming"
|
||||||
|
ChatToolRunning = "running"
|
||||||
|
ChatToolCompleted = "completed"
|
||||||
|
ChatToolError = "error"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChatReplyRequest.Decision values, mirroring the OpenCode permission reply body.
|
||||||
|
const (
|
||||||
|
ChatDecisionOnce = "once"
|
||||||
|
ChatDecisionAlways = "always"
|
||||||
|
ChatDecisionReject = "reject"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChatMessage.Role values.
|
||||||
|
const (
|
||||||
|
ChatRoleUser = "user"
|
||||||
|
ChatRoleAssistant = "assistant"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChatSession is one createable/listed OpenCode session, flattened for the
|
||||||
|
// phone: the nested location.directory and time{created,updated} fields are
|
||||||
|
// lifted to Directory, CreatedAt and UpdatedAt.
|
||||||
|
type ChatSession struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title,omitempty"`
|
||||||
|
Agent string `json:"agent,omitempty"`
|
||||||
|
Model string `json:"model,omitempty"`
|
||||||
|
Directory string `json:"directory,omitempty"`
|
||||||
|
ParentID string `json:"parent_id,omitempty"`
|
||||||
|
CreatedAt int64 `json:"created_at,omitempty"`
|
||||||
|
UpdatedAt int64 `json:"updated_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatCreateRequest is the chat_create request body: a title and an optional
|
||||||
|
// working directory (the server's configured location when empty). The response
|
||||||
|
// carries the created session in Message.ChatSession.
|
||||||
|
type ChatCreateRequest struct {
|
||||||
|
Title string `json:"title,omitempty"`
|
||||||
|
Directory string `json:"directory,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatQuery is the session-scoped request body for chat_messages and
|
||||||
|
// chat_interrupt, which name their target session through it; Limit caps the
|
||||||
|
// returned history (server default when zero).
|
||||||
|
type ChatQuery struct {
|
||||||
|
SessionID string `json:"session_id"`
|
||||||
|
Limit int `json:"limit,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatPromptRequest is the chat_prompt request body: the text to send, with an
|
||||||
|
// optional model/agent override and attached file URIs. The matching response is
|
||||||
|
// the inbox envelope, which the server folds into a ChatMessage.
|
||||||
|
type ChatPromptRequest struct {
|
||||||
|
SessionID string `json:"session_id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Model string `json:"model,omitempty"`
|
||||||
|
Agent string `json:"agent,omitempty"`
|
||||||
|
Files []string `json:"files,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatMessage is one stored turn returned by chat_messages. A user turn is a
|
||||||
|
// single text part; an assistant turn holds the text, reasoning and tool parts
|
||||||
|
// the phone renders. Parts corresponds to the OpenCode content array.
|
||||||
|
type ChatMessage struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
SessionID string `json:"session_id"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
Model string `json:"model,omitempty"`
|
||||||
|
Agent string `json:"agent,omitempty"`
|
||||||
|
CreatedAt int64 `json:"created_at,omitempty"`
|
||||||
|
Parts []ChatPart `json:"parts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatPart is one element of a ChatMessage. Type selects the meaning: text and
|
||||||
|
// reasoning use Text and ID, tool uses ID, Name, Executed, State and Time.
|
||||||
|
type ChatPart struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
|
Text string `json:"text,omitempty"`
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
Executed bool `json:"executed,omitempty"`
|
||||||
|
State *ChatToolState `json:"state,omitempty"`
|
||||||
|
Time *ChatTime `json:"time,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatToolState is the lifecycle of a tool call. Input is a raw JSON value: a
|
||||||
|
// partial-JSON string while streaming, an object once running or completed.
|
||||||
|
// Content is the tool's textual/file result, Metadata its provider stats,
|
||||||
|
// Error the structured failure for status "error".
|
||||||
|
type ChatToolState struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
Input json.RawMessage `json:"input,omitempty"`
|
||||||
|
Content []ChatToolContent `json:"content,omitempty"`
|
||||||
|
Metadata map[string]any `json:"metadata,omitempty"`
|
||||||
|
Error *ChatError `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatToolContent is one returned tool result: either text or a file/uri pair
|
||||||
|
// (so a tool can return an image the phone renders).
|
||||||
|
type ChatToolContent struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Text string `json:"text,omitempty"`
|
||||||
|
URI string `json:"uri,omitempty"`
|
||||||
|
Mime string `json:"mime,omitempty"`
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatError is the structured error attached to a failed tool call.
|
||||||
|
type ChatError struct {
|
||||||
|
Type string `json:"type,omitempty"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatTime is the epoch-millisecond timing envelope of a tool call.
|
||||||
|
type ChatTime struct {
|
||||||
|
Created int64 `json:"created,omitempty"`
|
||||||
|
Ran int64 `json:"ran,omitempty"`
|
||||||
|
Completed int64 `json:"completed,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatEventFrame is the server-pushed chat_event frame. Kind selects the
|
||||||
|
// payload: text and reasoning carry an incremental Delta plus the target Part,
|
||||||
|
// tool carries a full Part with its state, step marks turn progress and usage
|
||||||
|
// reports the turn's totals.
|
||||||
|
type ChatEventFrame struct {
|
||||||
|
SessionID string `json:"session_id"`
|
||||||
|
MessageID string `json:"message_id,omitempty"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Delta string `json:"delta,omitempty"`
|
||||||
|
Part *ChatPart `json:"part,omitempty"`
|
||||||
|
Step *ChatStep `json:"step,omitempty"`
|
||||||
|
Usage *ChatUsage `json:"usage,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatStep is a progress marker for the current step of a turn.
|
||||||
|
type ChatStep struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
Index int `json:"index,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatUsage is the token and cost total of a turn.
|
||||||
|
type ChatUsage struct {
|
||||||
|
InputTokens int `json:"input_tokens,omitempty"`
|
||||||
|
OutputTokens int `json:"output_tokens,omitempty"`
|
||||||
|
Cost float64 `json:"cost,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatReplyRequest is the chat_reply request body: the phone's decision on a
|
||||||
|
// pending permission request, mirroring
|
||||||
|
// POST /api/session/{id}/permission/{requestID}/reply.
|
||||||
|
type ChatReplyRequest struct {
|
||||||
|
SessionID string `json:"session_id"`
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
Decision string `json:"decision"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package protocol
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// chatSamples covers every new chat type with a populated value, plus a text and
|
||||||
|
// a tool chat_event, so a round-trip loss in any field fails the test.
|
||||||
|
func chatSamples() []struct {
|
||||||
|
name string
|
||||||
|
value any
|
||||||
|
} {
|
||||||
|
return []struct {
|
||||||
|
name string
|
||||||
|
value any
|
||||||
|
}{
|
||||||
|
{"session", ChatSession{
|
||||||
|
ID: "ses_1", Title: "demo", Agent: "build", Model: "deepseek-v4.1-flash",
|
||||||
|
Directory: "/work", ParentID: "ses_0", CreatedAt: 1792112366711, UpdatedAt: 1792112367999,
|
||||||
|
}},
|
||||||
|
{"create", ChatCreateRequest{Title: "demo", Directory: "/work"}},
|
||||||
|
{"query", ChatQuery{SessionID: "ses_1", Limit: 50}},
|
||||||
|
{"prompt", ChatPromptRequest{SessionID: "ses_1", Text: "hello", Model: "m", Agent: "build", Files: []string{"file:///tmp/a.png"}}},
|
||||||
|
{"message", ChatMessage{
|
||||||
|
ID: "msg_1", SessionID: "ses_1", Role: ChatRoleAssistant, Model: "m", Agent: "build", CreatedAt: 1792112366711,
|
||||||
|
Parts: []ChatPart{
|
||||||
|
{Type: ChatPartText, ID: "p1", Text: "done"},
|
||||||
|
{Type: ChatPartReasoning, ID: "p2", Text: "thinking"},
|
||||||
|
{Type: ChatPartTool, ID: "call_1", Name: "shell", Executed: true,
|
||||||
|
State: &ChatToolState{
|
||||||
|
Status: ChatToolCompleted,
|
||||||
|
Input: json.RawMessage(`{"command":"ls"}`),
|
||||||
|
Content: []ChatToolContent{{Type: "text", Text: "app-debug.apk"}, {Type: "file", URI: "file:///tmp/x.png", Mime: "image/png", Name: "x.png"}},
|
||||||
|
Metadata: map[string]any{"exit": "0"},
|
||||||
|
},
|
||||||
|
Time: &ChatTime{Created: 1, Ran: 2, Completed: 3},
|
||||||
|
},
|
||||||
|
{Type: ChatPartTool, ID: "call_2", Name: "edit",
|
||||||
|
State: &ChatToolState{Status: ChatToolError, Input: json.RawMessage(`{}`), Error: &ChatError{Type: "tool", Message: "boom"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
{"event_text", ChatEventFrame{
|
||||||
|
SessionID: "ses_1", MessageID: "msg_1", Kind: ChatEventText, Delta: "hel",
|
||||||
|
Part: &ChatPart{Type: ChatPartText, ID: "p1"},
|
||||||
|
}},
|
||||||
|
{"event_tool", ChatEventFrame{
|
||||||
|
SessionID: "ses_1", MessageID: "msg_1", Kind: ChatEventTool,
|
||||||
|
Part: &ChatPart{Type: ChatPartTool, ID: "call_1", Name: "shell", Executed: true,
|
||||||
|
State: &ChatToolState{Status: ChatToolRunning, Input: json.RawMessage(`{"command":"ls"}`)},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
{"event_step", ChatEventFrame{SessionID: "ses_1", Kind: ChatEventStep, Step: &ChatStep{Status: ChatStepEnded, Index: 2}}},
|
||||||
|
{"event_usage", ChatEventFrame{SessionID: "ses_1", Kind: ChatEventUsage, Usage: &ChatUsage{InputTokens: 12, OutputTokens: 34, Cost: 0.001}}},
|
||||||
|
{"reply", ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: ChatDecisionOnce, Message: "ok"}},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChatTypesGoldenRoundTrip(t *testing.T) {
|
||||||
|
for _, sample := range chatSamples() {
|
||||||
|
encoded, err := json.Marshal(sample.value)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: marshal: %v", sample.name, err)
|
||||||
|
}
|
||||||
|
target := reflect.New(reflect.TypeOf(sample.value))
|
||||||
|
if err := json.Unmarshal(encoded, target.Interface()); err != nil {
|
||||||
|
t.Fatalf("%s: unmarshal: %v", sample.name, err)
|
||||||
|
}
|
||||||
|
decoded := target.Elem().Interface()
|
||||||
|
if !reflect.DeepEqual(decoded, sample.value) {
|
||||||
|
t.Fatalf("%s: fields lost\n got %+v\nwant %+v", sample.name, decoded, sample.value)
|
||||||
|
}
|
||||||
|
again, err := json.Marshal(decoded)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: re-marshal: %v", sample.name, err)
|
||||||
|
}
|
||||||
|
if string(again) != string(encoded) {
|
||||||
|
t.Fatalf("%s: wire shape not stable\n got %s\nwant %s", sample.name, again, encoded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestChatEventGoldenJSON pins the exact wire shape of a pushed frame so a JSON
|
||||||
|
// tag change cannot silently alter what the phone parses.
|
||||||
|
func TestChatEventGoldenJSON(t *testing.T) {
|
||||||
|
event := ChatEventFrame{
|
||||||
|
SessionID: "ses_1", MessageID: "msg_1", Kind: ChatEventTool,
|
||||||
|
Part: &ChatPart{Type: ChatPartTool, ID: "call_1", Name: "shell", Executed: true,
|
||||||
|
State: &ChatToolState{
|
||||||
|
Status: ChatToolStreaming,
|
||||||
|
Input: json.RawMessage(`"{\"command\":\"ls\""`),
|
||||||
|
Content: nil,
|
||||||
|
},
|
||||||
|
Time: &ChatTime{Created: 10, Ran: 11, Completed: 12},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(event)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := `{"session_id":"ses_1","message_id":"msg_1","kind":"tool","part":{"type":"tool","id":"call_1","name":"shell","executed":true,"state":{"status":"streaming","input":"{\"command\":\"ls\""},"time":{"created":10,"ran":11,"completed":12}}}`
|
||||||
|
if string(encoded) != want {
|
||||||
|
t.Fatalf("golden mismatch\n got %s\nwant %s", encoded, want)
|
||||||
|
}
|
||||||
|
var decoded ChatEventFrame
|
||||||
|
if err := json.Unmarshal([]byte(want), &decoded); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(decoded, event) {
|
||||||
|
t.Fatalf("golden did not decode back: %+v", decoded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChatEnvelopeRoundTrip(t *testing.T) {
|
||||||
|
session := ChatSession{ID: "ses_1", Title: "demo"}
|
||||||
|
message := Message{
|
||||||
|
Type: ChatSessions, ID: "r1",
|
||||||
|
ChatSessions: []ChatSession{session},
|
||||||
|
ChatSession: &session,
|
||||||
|
ChatCreate: &ChatCreateRequest{Title: "new"},
|
||||||
|
ChatQuery: &ChatQuery{SessionID: "ses_1", Limit: 10},
|
||||||
|
ChatPrompt: &ChatPromptRequest{SessionID: "ses_1", Text: "hi"},
|
||||||
|
ChatMessages: []ChatMessage{{ID: "msg_1", SessionID: "ses_1", Role: ChatRoleUser, Parts: []ChatPart{{Type: ChatPartText, Text: "hi"}}}},
|
||||||
|
ChatEvent: &ChatEventFrame{SessionID: "ses_1", Kind: ChatEventText, Delta: "hi"},
|
||||||
|
ChatReply: &ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: ChatDecisionReject},
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(message)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var decoded Message
|
||||||
|
if err := json.Unmarshal(encoded, &decoded); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if decoded.Type != ChatSessions || decoded.ID != "r1" {
|
||||||
|
t.Fatalf("envelope lost: %+v", decoded)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(decoded.ChatSessions, message.ChatSessions) ||
|
||||||
|
!reflect.DeepEqual(decoded.ChatSession, message.ChatSession) ||
|
||||||
|
!reflect.DeepEqual(decoded.ChatCreate, message.ChatCreate) ||
|
||||||
|
!reflect.DeepEqual(decoded.ChatQuery, message.ChatQuery) ||
|
||||||
|
!reflect.DeepEqual(decoded.ChatPrompt, message.ChatPrompt) ||
|
||||||
|
!reflect.DeepEqual(decoded.ChatMessages, message.ChatMessages) ||
|
||||||
|
!reflect.DeepEqual(decoded.ChatEvent, message.ChatEvent) ||
|
||||||
|
!reflect.DeepEqual(decoded.ChatReply, message.ChatReply) {
|
||||||
|
t.Fatalf("chat payloads lost: %+v", decoded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChatFieldsOmittedWhenUnused(t *testing.T) {
|
||||||
|
minimal, err := json.Marshal(Message{Type: List, ID: "r1"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, absent := range []string{"chat_sessions", "chat_session", "chat_create", "chat_query", "chat_prompt", "chat_messages", "chat_event", "chat_reply"} {
|
||||||
|
if strings.Contains(string(minimal), absent) {
|
||||||
|
t.Fatalf("absent %q must be omitted: %s", absent, minimal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -133,4 +133,14 @@ type Message struct {
|
|||||||
WritePaths []string `json:"write_paths,omitempty"`
|
WritePaths []string `json:"write_paths,omitempty"`
|
||||||
RequestKey string `json:"request_key,omitempty"`
|
RequestKey string `json:"request_key,omitempty"`
|
||||||
Workspace string `json:"workspace,omitempty"`
|
Workspace string `json:"workspace,omitempty"`
|
||||||
|
// Chat is the brokered OpenCode chat traffic (route B). See chat.go for the
|
||||||
|
// per-type payload structs and the wire shapes they mirror.
|
||||||
|
ChatSessions []ChatSession `json:"chat_sessions,omitempty"`
|
||||||
|
ChatSession *ChatSession `json:"chat_session,omitempty"`
|
||||||
|
ChatCreate *ChatCreateRequest `json:"chat_create,omitempty"`
|
||||||
|
ChatQuery *ChatQuery `json:"chat_query,omitempty"`
|
||||||
|
ChatPrompt *ChatPromptRequest `json:"chat_prompt,omitempty"`
|
||||||
|
ChatMessages []ChatMessage `json:"chat_messages,omitempty"`
|
||||||
|
ChatEvent *ChatEventFrame `json:"chat_event,omitempty"`
|
||||||
|
ChatReply *ChatReplyRequest `json:"chat_reply,omitempty"`
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user