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:
+113
-9
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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"`
|
||||
|
||||
Reference in New Issue
Block a user