chat: add model switching and preloaded instructions

Expose the OpenCode model list and session model switch over the chat protocol,
carry a per-session model provider on chat rows, and apply a preloaded behavior
brief as a durable session instruction entry when a chat is created.
This commit is contained in:
2026-10-20 14:58:20 +01:00
parent f982c0b712
commit 6bfe4c8921
12 changed files with 468 additions and 17 deletions
+20
View File
@@ -55,6 +55,20 @@ type chatPromptWithFiles interface {
PromptWithMessageIDFiles(context.Context, string, string, string, []opencode.PromptFile) error
}
// chatInstructioner is the optional preloaded-behavior surface. OpenCode
// implements session instruction entries; a harness without them still creates
// the chat without instructions.
type chatInstructioner interface {
SetInstruction(ctx context.Context, sessionID, key string, value any) error
}
// chatModeler is the optional model-selection surface. OpenCode implements it;
// a harness without a model switch reports that clearly rather than pretending.
type chatModeler interface {
Models(ctx context.Context, sessionID string) ([]protocol.ChatModel, error)
SwitchModel(ctx context.Context, sessionID, provider, model string) error
}
// chatAnswerer is the optional form-answer surface. Test brokers and older
// backends need not implement it; a broker that does not answers chat_answer
// with a clear error rather than pretending the question was delivered.
@@ -179,6 +193,12 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatBackends:
handleChatBackends(request, broker, write)
return true
case protocol.ChatModels:
handleChatModels(ctx, request, broker, write)
return true
case protocol.ChatModelSelect:
handleChatModelSwitch(ctx, request, broker, write)
return true
case protocol.ChatShells:
handleChatShells(ctx, request, broker, registry, write)
return true
+40
View File
@@ -151,6 +151,46 @@ func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, t
return m.PromptWithMessageID(ctx, sessionID, text, messageID)
}
// SetInstruction forwards one preloaded behavior instruction to the session's
// harness when it supports durable instruction entries.
func (m *chatManager) SetInstruction(ctx context.Context, sessionID, key string, value any) error {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return err
}
instr, ok := adapter.(chatInstructioner)
if !ok {
return errors.New("this chat harness does not support session instructions")
}
return instr.SetInstruction(ctx, sessionID, key, value)
}
// Models lists the models the session's harness offers for switching.
func (m *chatManager) Models(ctx context.Context, sessionID string) ([]protocol.ChatModel, error) {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return nil, err
}
modeler, ok := adapter.(chatModeler)
if !ok {
return nil, errors.New("this chat harness does not support changing models")
}
return modeler.Models(ctx, sessionID)
}
// SwitchModel changes the session's model for subsequent turns.
func (m *chatManager) SwitchModel(ctx context.Context, sessionID, provider, model string) error {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return err
}
modeler, ok := adapter.(chatModeler)
if !ok {
return errors.New("this chat harness does not support changing models")
}
return modeler.SwitchModel(ctx, sessionID, provider, model)
}
func (m *chatManager) Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
+13
View File
@@ -3,6 +3,7 @@ package server
import (
"context"
"errors"
"log"
"os"
"path/filepath"
"strings"
@@ -109,6 +110,7 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
operationID := ""
backend := "opencode"
ephemeral := false
instructions := ""
if request.ChatCreate != nil {
title = strings.TrimSpace(request.ChatCreate.Title)
directory = strings.TrimSpace(request.ChatCreate.Directory)
@@ -117,6 +119,7 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
backend = value
}
ephemeral = request.ChatCreate.Ephemeral
instructions = strings.TrimSpace(request.ChatCreate.Instructions)
}
// Legacy clients did not carry a durable create identity. Give each received
// request its own server-generated scope so their connection-local envelope
@@ -177,6 +180,16 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
// Reserve the activation before calling the external service. If the
// process dies after the call but before the success checkpoint, a retry
// must report the ambiguous operation rather than append the skill twice.
// Preload the web chat's behavior brief before the first turn. This is
// best effort: an older OpenCode build or another harness without the
// experimental instruction surface still gets a usable chat.
if instructions != "" {
if instr, ok := broker.(chatInstructioner); ok {
if err := instr.SetInstruction(ctx, session.ID, "pipelines.behavior", instructions); err != nil {
log.Printf("chat %s preload instructions: %v", session.ID, err)
}
}
}
if err := registry.AdvanceChatCreate(ctx, operationID, "created", "activating"); err != nil {
chatCreateConflictError(request, err, write)
return
+43
View File
@@ -105,6 +105,49 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
}
}
// handleChatModels lists the models a session's harness can switch to.
func handleChatModels(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
query := request.ChatQuery
if query == nil || !validChatSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
modeler, ok := broker.(chatModeler)
if !ok {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "this chat harness does not support changing models"})
return
}
models, err := modeler.Models(ctx, query.SessionID)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
_ = write(protocol.Message{Type: protocol.ChatModels, ID: request.ID, ChatModels: models})
}
// handleChatModelSwitch changes one session's model for subsequent turns.
func handleChatModelSwitch(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
body := request.ModelRequest
if body == nil || !validChatSessionID(body.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
if strings.TrimSpace(body.Provider) == "" || strings.TrimSpace(body.Model) == "" {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a model and provider are required"})
return
}
modeler, ok := broker.(chatModeler)
if !ok {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "this chat harness does not support changing models"})
return
}
if err := modeler.SwitchModel(ctx, body.SessionID, body.Provider, body.Model); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
_ = write(protocol.Message{Type: protocol.ChatModelSelect, ID: request.ID, ModelRequest: body})
}
// handleChatSubscribe attaches one connection to a session's shared stream so it
// receives every frame any client's turn produces, its own or another device's.
// It replays the session's still-pending approval requests, if the room holds
+61 -1
View File
@@ -48,6 +48,9 @@ type fakeChat struct {
replyRequest protocol.ChatReplyRequest
replyErr error
messageCalls int
models []protocol.ChatModel
modelSwitch string
modelSession string
messageSessionID string
messageLimit int
messageCursor string
@@ -86,6 +89,9 @@ type fakeChat struct {
activateSessionID string
activateSkill string
activateErr error
instructionSession string
instructionKey string
instructionValue any
sessionByIDCalls int
sessionByID string
sessionRecord protocol.ChatSession
@@ -109,6 +115,17 @@ func (f *fakeChat) Prompt(context.Context, string, string) error {
return nil
}
func (f *fakeChat) Models(context.Context, string) ([]protocol.ChatModel, error) {
return append([]protocol.ChatModel(nil), f.models...), nil
}
func (f *fakeChat) SwitchModel(_ context.Context, sessionID, provider, model string) error {
f.mu.Lock()
f.modelSession = sessionID
f.modelSwitch = provider + "/" + model
f.mu.Unlock()
return nil
}
func (f *fakeChat) PromptWithMessageIDFiles(ctx context.Context, sessionID, text, _ string, files []opencode.PromptFile) error {
f.mu.Lock()
f.promptFiles = append([]opencode.PromptFile(nil), files...)
@@ -280,6 +297,15 @@ func (f *fakeChat) ActivateSkill(_ context.Context, sessionID, skill string) err
return f.activateErr
}
func (f *fakeChat) SetInstruction(_ context.Context, sessionID, key string, value any) error {
f.mu.Lock()
defer f.mu.Unlock()
f.instructionSession = sessionID
f.instructionKey = key
f.instructionValue = value
return nil
}
func (f *fakeChat) Create(_ context.Context, title, directory string) (protocol.ChatSession, error) {
f.mu.Lock()
f.createCalls++
@@ -418,6 +444,34 @@ func readChatTurn(t *testing.T, ctx context.Context, conn *websocket.Conn) []pro
}
}
func TestChatModelsAndSwitch(t *testing.T) {
broker := scriptedChat()
broker.models = []protocol.ChatModel{{ID: "m1", Provider: "p1", Name: "Model One"}}
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatModels, ID: "r1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var reply protocol.Message
if err := wsjson.Read(ctx, conn, &reply); err != nil {
t.Fatal(err)
}
if reply.Type != protocol.ChatModels || len(reply.ChatModels) != 1 || reply.ChatModels[0].ID != "m1" {
t.Fatalf("models reply = %+v", reply)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatModelSelect, ID: "r2", ModelRequest: &protocol.ChatModelRequest{SessionID: "ses_1", Provider: "p1", Model: "m1"}}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(ctx, conn, &reply); err != nil {
t.Fatal(err)
}
if reply.Type != protocol.ChatModelSelect || reply.ModelRequest == nil || reply.ModelRequest.Model != "m1" {
t.Fatalf("switch reply = %+v", reply)
}
if broker.modelSession != "ses_1" || broker.modelSwitch != "p1/m1" {
t.Fatalf("switched %q %q", broker.modelSession, broker.modelSwitch)
}
}
func TestChatPromptWritesAttachmentAndForwardsLocalFile(t *testing.T) {
broker := scriptedChat()
ctx, _, conn := dialChat(t, broker)
@@ -1463,7 +1517,7 @@ func TestChatCreateRecordsOperatorSession(t *testing.T) {
broker.created = protocol.ChatSession{ID: "ses_new", Title: "demo"}
dir := t.TempDir()
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "c1", ChatCreate: &protocol.ChatCreateRequest{Title: "demo", Directory: dir}}); err != nil {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "c1", ChatCreate: &protocol.ChatCreateRequest{Title: "demo", Directory: dir, Instructions: "be careful"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
@@ -1488,6 +1542,12 @@ func TestChatCreateRecordsOperatorSession(t *testing.T) {
if activateCalls != 1 || activateSession != "ses_new" || activateSkill != "pipelines-manager" {
t.Fatalf("manager bootstrap = %d/%q/%q", activateCalls, activateSession, activateSkill)
}
broker.mu.Lock()
instructionSession, instructionKey, instructionValue := broker.instructionSession, broker.instructionKey, broker.instructionValue
broker.mu.Unlock()
if instructionSession != "ses_new" || instructionKey != "pipelines.behavior" || instructionValue != "be careful" {
t.Fatalf("preloaded instruction = %q/%q/%v", instructionSession, instructionKey, instructionValue)
}
recorded, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)