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
+113 -9
View File
@@ -145,6 +145,108 @@ func (c *Chat) PromptWithMessageIDFiles(ctx context.Context, id, text, messageID
return nil
}
// Models lists the models the connected endpoint offers for this chat. The
// endpoint returns providers/models for the connection's directory; only enabled,
// non-deprecated entries are exposed, because the picker is a choice the operator
// can actually apply.
func (c *Chat) Models(ctx context.Context, _ string) ([]protocol.ChatModel, error) {
data, err := c.call(ctx, "get", "/api/model", nil)
if err != nil {
return nil, err
}
var envelope struct {
Data []struct {
ModelID string `json:"modelID"`
ProviderID string `json:"providerID"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Status string `json:"status"`
} `json:"data"`
}
if err := json.Unmarshal(data, &envelope); err != nil {
return nil, fmt.Errorf("invalid OpenCode model response")
}
models := make([]protocol.ChatModel, 0, len(envelope.Data))
seen := map[string]bool{}
for _, item := range envelope.Data {
id := strings.TrimSpace(item.ModelID)
provider := strings.TrimSpace(item.ProviderID)
if id == "" || provider == "" || !item.Enabled || strings.EqualFold(item.Status, "deprecated") {
continue
}
key := provider + "\x00" + id
if seen[key] {
continue
}
seen[key] = true
name := strings.TrimSpace(item.Name)
if name == "" {
name = id
}
models = append(models, protocol.ChatModel{ID: id, Provider: provider, Name: name})
}
sort.Slice(models, func(i, j int) bool {
if models[i].Provider != models[j].Provider {
return models[i].Provider < models[j].Provider
}
return strings.ToLower(models[i].Name) < strings.ToLower(models[j].Name)
})
return models, nil
}
// SwitchModel changes the model used by subsequent provider turns. A running
// turn keeps the model it started with; the next prompt uses the new one.
func (c *Chat) SwitchModel(ctx context.Context, id, provider, model string) error {
if !sessionID.MatchString(id) {
return fmt.Errorf("invalid OpenCode session id")
}
provider = strings.TrimSpace(provider)
model = strings.TrimSpace(model)
if provider == "" || model == "" {
return fmt.Errorf("a model and provider are required")
}
body := map[string]any{"model": map[string]string{"id": model, "providerID": provider}}
if evidence, err := c.call(ctx, "post", "/api/session/"+id+"/model", body); err != nil {
if reason := strings.TrimSpace(string(evidence)); reason != "" {
if len(reason) > 300 {
reason = reason[:300]
}
return fmt.Errorf("%w: %s", err, reason)
}
return err
}
return nil
}
// SetInstruction attaches or replaces one durable session instruction entry.
// The experimental instruction surface announces changes at the next step
// boundary, which is exactly what a preloaded behavior brief needs.
func (c *Chat) SetInstruction(ctx context.Context, id, key string, value any) error {
if !sessionID.MatchString(id) {
return fmt.Errorf("invalid OpenCode session id")
}
if key == "" || len(key) > 64 {
return fmt.Errorf("an instruction key is required")
}
for _, r := range key {
if (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '.' && r != '_' && r != '-' {
return fmt.Errorf("invalid instruction key")
}
}
path := "/api/experimental/session/" + id + "/instructions/entries/" + url.PathEscape(key)
body := map[string]any{"value": value}
if evidence, err := c.call(ctx, "put", path, body); err != nil {
if reason := strings.TrimSpace(string(evidence)); reason != "" {
if len(reason) > 300 {
reason = reason[:300]
}
return fmt.Errorf("%w: %s", err, reason)
}
return err
}
return nil
}
// Answer replies to one OpenCode form. The agent's question tool pauses inside a
// form.created event; replying lets the same turn continue. The answer object is
// keyed by the form field keys, exactly as the OpenCode CLI sends it.
@@ -1214,7 +1316,8 @@ type nativeChatFile struct {
// nativeChatModel is the nested Model.Ref a V2 turn carries ({id, providerID,
// variant}); only the model id is surfaced in the protocol message.
type nativeChatModel struct {
ID string `json:"id"`
ID string `json:"id"`
ProviderID string `json:"providerID"`
}
// nativeChatPart is one content element shared by both message envelopes. Raw
@@ -1432,14 +1535,15 @@ func chatSessionRecord(data []byte) (nativeChatSession, error) {
// mapping shared by the list decoder and Create, so the two cannot drift.
func chatSessionFields(record nativeChatSession) protocol.ChatSession {
return protocol.ChatSession{
ID: record.ID,
Title: record.Title,
Agent: record.Agent,
Model: record.Model.ID,
Directory: record.Location.Directory,
ParentID: record.ParentID,
CreatedAt: record.Time.Created,
UpdatedAt: record.Time.Updated,
ID: record.ID,
Title: record.Title,
Agent: record.Agent,
Model: record.Model.ID,
ModelProvider: record.Model.ProviderID,
Directory: record.Location.Directory,
ParentID: record.ParentID,
CreatedAt: record.Time.Created,
UpdatedAt: record.Time.Updated,
}
}
+78
View File
@@ -83,6 +83,84 @@ func TestChatV2PromptWithMessageID(t *testing.T) {
}
}
func TestChatSetInstructionShape(t *testing.T) {
var path string
var body map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
if r.Method != http.MethodPut {
t.Errorf("method = %s", r.Method)
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatal(err)
}
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if err := chat.SetInstruction(context.Background(), "ses_1", "pipelines.behavior", "be careful"); err != nil {
t.Fatal(err)
}
if path != "/api/experimental/session/ses_1/instructions/entries/pipelines.behavior" {
t.Fatalf("path = %q", path)
}
if body["value"] != "be careful" {
t.Fatalf("body = %+v", body)
}
}
func TestChatModelsListsEnabledModels(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/model" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[
{"modelID":"b-model","providerID":"prov-b","name":"B Model","enabled":true,"status":"active"},
{"modelID":"a-model","providerID":"prov-a","name":"A Model","enabled":true,"status":"active"},
{"modelID":"off","providerID":"prov-a","name":"Off","enabled":false,"status":"active"},
{"modelID":"old","providerID":"prov-a","name":"Old","enabled":true,"status":"deprecated"}
]}`))
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
models, err := chat.Models(context.Background(), "ses_1")
if err != nil {
t.Fatal(err)
}
if len(models) != 2 || models[0].Provider != "prov-a" || models[0].ID != "a-model" || models[1].ID != "b-model" {
t.Fatalf("models = %+v", models)
}
}
func TestChatSwitchModelShape(t *testing.T) {
var body struct {
Model struct {
ID string `json:"id"`
ProviderID string `json:"providerID"`
} `json:"model"`
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/api/session/ses_1/model" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
return
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatal(err)
}
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
if err := chat.SwitchModel(context.Background(), "ses_1", "opencode-go", "deepseek-v4.1-flash"); err != nil {
t.Fatal(err)
}
if body.Model.ID != "deepseek-v4.1-flash" || body.Model.ProviderID != "opencode-go" {
t.Fatalf("model body = %+v", body)
}
}
func TestChatV2PromptWithFiles(t *testing.T) {
var body struct {
Text string `json:"text"`
+31 -6
View File
@@ -46,6 +46,11 @@ const (
// ChatBackends lists the installed chat harnesses the server can create a
// session on. The reply is a bounded array of backend names.
ChatBackends = "chat_backends"
// ChatModels lists the models the chat's harness can switch to; its request
// body is ChatQuery (the session id).
ChatModels = "chat_models"
// ChatModelSelect switches one session's model for subsequent turns.
ChatModelSelect = "chat_model"
// ChatStar records the operator's star on the server, so every browser and
// device shows the same starred group. It takes a ChatQuery with SessionID
// and Starred, and echoes the updated session like close/reopen.
@@ -154,6 +159,21 @@ const (
ChatRoleAssistant = "assistant"
)
// ChatModel is one model the current chat harness can switch to. ID is the
// provider's model id, Provider its provider id, Name the harness's display name.
type ChatModel struct {
ID string `json:"id"`
Provider string `json:"provider"`
Name string `json:"name,omitempty"`
}
// ChatModelRequest switches the model for one session's subsequent turns.
type ChatModelRequest struct {
SessionID string `json:"session_id"`
Provider string `json:"provider"`
Model string `json:"model"`
}
// 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.
@@ -161,12 +181,13 @@ type ChatSession struct {
ID string `json:"id"`
// Backend names the harness that owns this session: opencode, codex or
// claude. Empty on older peers and for legacy OpenCode rows.
Backend string `json:"backend,omitempty"`
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"`
Backend string `json:"backend,omitempty"`
Title string `json:"title,omitempty"`
Agent string `json:"agent,omitempty"`
Model string `json:"model,omitempty"`
ModelProvider string `json:"model_provider,omitempty"`
Directory string `json:"directory,omitempty"`
ParentID string `json:"parent_id,omitempty"`
// Tag marks the session kind. The only stored value is "operator" (a chat
// the person created); pipeline stage sessions are never tagged and are never
// listed by chat_sessions. Additive/omitempty so older peers ignore it.
@@ -216,6 +237,10 @@ type ChatCreateRequest struct {
// preserving older clients and the default.
Backend string `json:"backend,omitempty"`
OperationID string `json:"operation_id,omitempty"`
// Instructions preloads the session's durable behavior instruction, when the
// harness supports session instruction entries (OpenCode does). Best effort:
// a harness without the surface still creates the chat.
Instructions string `json:"instructions,omitempty"`
// Ephemeral creates a chat for automated verification: the session is created,
// bootstrapped and usable exactly like a normal one, but no operator-registry
// row is written, so it can never appear in chat_sessions. It exists because a
+4
View File
@@ -194,6 +194,10 @@ type Message struct {
// ChatBackends is the chat_backends reply: the installed harnesses a new
// chat can use.
ChatBackends []string `json:"chat_backends,omitempty"`
// ChatModels is the chat_models reply: models the session's harness offers.
ChatModels []ChatModel `json:"chat_models,omitempty"`
// ModelRequest is the chat_model body and echoed selection.
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
// ChatSubscribe attaches this connection to one session's shared stream; the
// body names the session like ChatQuery. A chat_prompt response sets
// ChatQueued when the prompt had to wait for an in-flight turn and was
+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)
+7
View File
@@ -64,6 +64,11 @@ export const Protocol = Object.freeze({
CHAT_STAR: "chat_star",
CHAT_RENAME: "chat_rename",
CHAT_BACKENDS: "chat_backends",
// Model selection for one chat. `chat_models` uses the usual `chat_query`
// session body and replies in `chat_models`; `chat_model` carries
// `{session_id,provider,model}` in `chat_model` and echoes it.
CHAT_MODELS: "chat_models",
CHAT_MODEL: "chat_model",
// The shared live stream (C5). `chat_subscribe` attaches this connection to one
// session's stream (body: the session id); the server then pushes `chat_event`
// frames without a matching request id, so every client watching a session sees
@@ -119,6 +124,8 @@ export const ChatKeys = Object.freeze({
ANSWER: "chat_answer",
RENAME: "chat_rename",
BACKENDS: "chat_backends",
MODELS: "chat_models",
MODEL: "chat_model",
// The composer's payloads (C8/C9). `chat_interrupt` deliberately has no key of
// its own: its body is the same `chat_query` the other session-scoped commands
// carry (internal/protocol/chat.go ChatQuery, Chat.kt interruptRequest), so a
+28 -1
View File
@@ -262,6 +262,32 @@ export class PipelinesRepository {
return (await this.#client.call({ type: Protocol.CHAT_BACKENDS }))[ChatKeys.BACKENDS] ?? ["opencode"];
}
/** The models the session's harness offers for switching. */
async chatModels(sessionId) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
const response = await this.#client.call({
type: Protocol.CHAT_MODELS,
[ChatKeys.QUERY]: { session_id: sessionId },
});
return response[ChatKeys.MODELS] ?? [];
}
/** Switch one session's model for subsequent turns. */
async switchChatModel(sessionId, provider, model) {
const session = String(sessionId ?? "").trim();
const providerId = String(provider ?? "").trim();
const modelId = String(model ?? "").trim();
if (session === "") throw new ProtocolError("Select a chat session first.");
if (providerId === "" || modelId === "") throw new ProtocolError("Choose a model first.");
const response = await this.#client.call({
type: Protocol.CHAT_MODEL,
[ChatKeys.MODEL]: { session_id: session, provider: providerId, model: modelId },
});
return response[ChatKeys.MODEL] ?? { session_id: session, provider: providerId, model: modelId };
}
/**
* Loads a bounded chronological history page. `cursor` is the opaque
* continuation the server returned as `next_cursor`; it is passed back
@@ -497,7 +523,7 @@ export class PipelinesRepository {
* `chat_sessions` for the operator. Automated checks that drive this real page
* set it, so a run can never leave a stray "New chat" in the operator's list.
*/
async chatCreate(title, directory, operationId = newChatOperationId(), { backend = "opencode", ephemeral = false } = {}) {
async chatCreate(title, directory, operationId = newChatOperationId(), { backend = "opencode", ephemeral = false, instructions = "" } = {}) {
const response = await this.#client.call({
type: Protocol.CHAT_CREATE,
[ChatKeys.CREATE]: {
@@ -506,6 +532,7 @@ export class PipelinesRepository {
operation_id: operationId,
...(backend && backend !== "opencode" ? { backend } : {}),
...(ephemeral ? { ephemeral: true } : {}),
...(String(instructions ?? "").trim() !== "" ? { instructions: String(instructions).trim() } : {}),
},
});
const session = response[ChatKeys.SESSION];
+30
View File
@@ -367,6 +367,29 @@ test("chatPrompt includes files when present and reads chat_queued", async () =>
assert.equal(queued, true);
});
test("chatModels and switchChatModel use the session-scoped wire shapes", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => {
if (frame.type === "chat_models") {
return { id: frame.id, type: "chat_models", chat_models: [{ id: "m1", provider: "p1", name: "Model One" }] };
}
return { id: frame.id, type: "chat_model", chat_model: frame.chat_model };
};
const models = await repo.chatModels("s1");
assert.deepEqual(lastFrame(ws), {
type: "chat_models",
chat_query: { session_id: "s1" },
});
assert.deepEqual(models, [{ id: "m1", provider: "p1", name: "Model One" }]);
const selected = await repo.switchChatModel("s1", "p1", "m1");
assert.deepEqual(lastFrame(ws), {
type: "chat_model",
chat_model: { session_id: "s1", provider: "p1", model: "m1" },
});
assert.equal(selected.model, "m1");
});
test("chatPrompt sends browser attachment bytes with their name and mime", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_prompt" });
@@ -441,6 +464,13 @@ test("chatCreate sends title/directory/operation_id and returns chat_session", a
assert.deepEqual(session, created);
});
test("chatCreate sends a preloaded behavior brief when provided", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_create", chat_session: { id: "s1" } });
await repo.chatCreate("New chat", "/repo", "op-5", { instructions: "be careful" });
assert.equal(lastFrame(ws).chat_create.instructions, "be careful");
});
test("chatCreate throws when the reply carries no chat_session", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_create" });