Files
pipelines/internal/opencode/chat.go
T
alan 06001697c8 Add per-chat thinking levels for Codex, Claude Code and OpenCode
Codex: model/list supportedReasoningEfforts per model, turn/start effort,
thread reasoningEffort as the current level. Claude Code: initialize
supportedEffortLevels, apply_flag_settings effortLevel at the next turn
start. OpenCode v2: model variants via the session model endpoint.
chat_effort sets a level; rows and chat_models carry the levels; Codex and
Claude levels persist in operator_sessions.chat_effort and are re-applied
before every turn.
2026-11-09 20:07:41 +00:00

1993 lines
73 KiB
Go

package opencode
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"sort"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// ErrPermissionUnsupported reports that the connected OpenCode backend does not
// expose the brokered approval surface. The native v1 serve translation returns
// it; callers treat it as a documented limitation rather than an operational
// failure, so a chat prompt does not emit a permission error frame on a backend
// that cannot answer one.
var ErrPermissionUnsupported = errors.New("OpenCode permission approval is not implemented for the native serve backend")
// 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 and session-id shape of Connection, with its normal 64 KiB / 1 MiB
// call guards. History alone streams/project tool details before decoding; it
// does not introduce a total-history cap or a second credential path.
type Chat struct {
conn *Connection
shellMu sync.Mutex
shells map[string]*ChatStreamState
// shellOwners retains ownership from the last authoritative global shell
// listing so a shell known to belong to another session is rejected before
// its detail or output endpoint is queried.
shellOwners map[string]string
// mu serializes the adapter's HTTP calls. Connection records its last
// operation and status on the shared connection, so two calls must not
// overlap; the permission poller runs alongside the read loop's
// prompt/interrupt/reply calls.
mu sync.Mutex
usageMu sync.Mutex
usageModels map[string]usageModelCache
modeMu sync.Mutex
agents map[string]string
modelMu sync.Mutex
sessionModels map[string]sessionModelCache
// catalog caches /api/model for thinking levels (efforts.go).
catalogMu sync.Mutex
catalog []protocol.ChatModel
catalogAt time.Time
}
// 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) }
// ValidShellID accepts only the provider's opaque shell-id alphabet. Keeping
// this check shared by the websocket boundary and provider adapter ensures an
// invalid id is rejected before either network call or path construction.
func ValidShellID(id string) bool {
if len(id) <= 3 || len(id) > 128 || !strings.HasPrefix(id, "sh_") {
return false
}
for _, c := range id[3:] {
if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_' && c != '-' {
return false
}
}
return true
}
// call serializes the adapter's HTTP calls and forwards them through the shared
// Connection, so no second transport is introduced and Connection's recorded
// last operation/status is never written by two goroutines at once.
func (c *Chat) call(ctx context.Context, method, path string, body any) ([]byte, error) {
c.mu.Lock()
defer c.mu.Unlock()
return c.conn.Call(ctx, method, path, body)
}
// 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 {
return c.PromptWithMessageID(ctx, id, text, "")
}
// PromptFile is one local file handed to OpenCode with a prompt. URI is the
// file:// URL the server wrote; Name is the browser's display name.
type PromptFile struct {
URI string
Name string
preparedURI string
}
// NewPreparedPromptFile marks a file written by the server attachment store.
// Only trusted server-side upload preparation should call this constructor;
// browser-provided paths must never be marked as prepared.
func NewPreparedPromptFile(uri, name string) PromptFile {
return PromptFile{URI: uri, Name: name, preparedURI: uri}
}
// ServerPrepared reports whether URI is the unchanged server-prepared reference.
func (f PromptFile) ServerPrepared() bool { return f.URI != "" && f.URI == f.preparedURI }
// PromptWithMessageID forwards the caller's canonical message id to OpenCode.
// OpenCode persists this id in history, which is the only safe bridge between
// the live user echo and an authoritative history page.
func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID string) error {
return c.PromptWithMessageIDFiles(ctx, id, text, messageID, nil)
}
// PromptWithMessageIDFiles is PromptWithMessageID with local file attachments.
// The V2 prompt body accepts a `files` array of {uri,name}; the server writes
// browser bytes to a private temporary file first, because a browser's own file
// reference is not readable by an OpenCode service on another machine.
func (c *Chat) PromptWithMessageIDFiles(ctx context.Context, id, text, messageID string, files []PromptFile) error {
if !sessionID.MatchString(id) {
return fmt.Errorf("invalid OpenCode session id")
}
if strings.TrimSpace(text) == "" {
return fmt.Errorf("empty chat prompt")
}
// The V2 prompt body is {"text": ...}; the native serve translation accepts
// the same "text" field, so one shape works on both backends without a
// second request format.
body := map[string]any{"text": text}
if messageID != "" {
body["id"] = messageID
}
if agent := c.agentFor(id); agent != "" {
body["agent"] = agent
}
if len(files) > 0 {
attachments := make([]map[string]string, 0, len(files))
for _, file := range files {
if strings.TrimSpace(file.URI) == "" {
continue
}
item := map[string]string{"uri": file.URI}
if name := strings.TrimSpace(file.Name); name != "" {
item["name"] = name
}
attachments = append(attachments, item)
}
if len(attachments) > 0 {
body["files"] = attachments
}
}
if evidence, err := c.call(ctx, "post", "/api/session/"+id+"/prompt", 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
}
// 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"`
Variants []struct {
ID string `json:"id"`
} `json:"variants"`
} `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
}
model := protocol.ChatModel{ID: id, Provider: provider, Name: name}
for _, variant := range item.Variants {
if variant.ID != "" && !protocol.HasChatEffort(model.Efforts, variant.ID) {
model.Efforts = append(model.Efforts, protocol.ChatEffort{ID: variant.ID, Name: protocol.ChatEffortName(variant.ID)})
}
}
models = append(models, model)
}
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
}
c.modelMu.Lock()
delete(c.sessionModels, id)
c.modelMu.Unlock()
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.
func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
if !sessionID.MatchString(request.SessionID) {
return fmt.Errorf("invalid OpenCode session id")
}
if strings.TrimSpace(request.FormID) == "" {
return fmt.Errorf("a form id is required")
}
if request.Action == "cancel" {
_, err := c.call(ctx, "delete", "/api/session/"+request.SessionID+"/form/"+url.PathEscape(request.FormID), nil)
return err
}
if request.Action != "" && request.Action != "accept" {
return fmt.Errorf("unsupported OpenCode form action")
}
body := map[string]any{"answer": request.Answers}
if request.Answers == nil {
body["answer"] = map[string]any{}
}
if _, err := c.call(ctx, "post", "/api/session/"+request.SessionID+"/form/"+url.PathEscape(request.FormID)+"/reply", 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.call(ctx, "post", "/api/session/"+id+"/interrupt", map[string]any{}); err != nil {
return err
}
return nil
}
// Detach is the server-restart shutdown (chatShutdownDetacher). Sessions, turns, questions,
// permissions and shells live in the OpenCode service, not in this adapter, so
// there is nothing to stop: the connection's owner decides whether the service
// itself outlives the server (an attached endpoint and the detached owned chat
// service do; a V1 serve child does not).
func (c *Chat) Detach() {}
// 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, cursor string) (protocol.ChatHistoryPage, error) {
if !sessionID.MatchString(id) {
return protocol.ChatHistoryPage{}, fmt.Errorf("invalid OpenCode session id")
}
var data []byte
var err error
c.mu.Lock()
defer c.mu.Unlock()
var reader io.Reader
if c.conn.Backend == "v1" {
var body io.ReadCloser
body, err = c.conn.HistoryNative(ctx, "/session/"+id+"/message")
if err == nil {
defer body.Close()
reader = body
} else if c.conn.LastHTTPStatus == 400 {
// Preserve the existing OutputFormat/read-only export recovery on
// native serve. Ordinary history is streamed, never Call-buffered.
data, err = c.conn.Messages(ctx, id)
reader = bytes.NewReader(data)
}
} else {
if limit <= 0 {
limit = 100 // bounded newest-page request, including legacy clients
}
path := "/api/session/" + id + "/message"
values := make([]string, 0, 2)
if limit > 0 {
values = append(values, fmt.Sprintf("limit=%d", limit))
}
if cursor != "" {
values = append(values, "cursor="+url.QueryEscape(cursor))
}
if len(values) > 0 {
path += "?" + strings.Join(values, "&")
}
var body io.ReadCloser
body, err = c.conn.HistoryNative(ctx, path)
if err == nil {
defer body.Close()
reader = body
}
}
if err != nil {
return protocol.ChatHistoryPage{}, err
}
messages, next, descending, err := decodeChatHistoryPage(ctx, id, reader)
if err != nil {
return protocol.ChatHistoryPage{}, err
}
// The verified API returns newest first. The transcript is chronological.
if descending {
for left, right := 0, len(messages)-1; left < right; left, right = left+1, right-1 {
messages[left], messages[right] = messages[right], messages[left]
}
}
return protocol.ChatHistoryPage{Messages: messages, NextCursor: next, HasMore: next != ""}, nil
}
// Sessions lists the OpenCode sessions on the endpoint. On the V2 HTTP API that
// is GET /api/session; the native v1 serve translation maps it to GET /session.
// It reads the list unscoped by the connection's directory (see
// Connection.SessionList): the V2 list is otherwise restricted to the
// connection's own directory, while an operator session may live in any
// directory, and the caller is responsible for restricting the result to the
// operator's recorded sessions. It decodes the verified {"data":[...]} envelope
// (tolerating a bare array like chatMessageRecords), lifts the nested
// location.directory and time{created,updated} into protocol.ChatSession, drops
// records without a valid session id, and orders newest-updated first so the list
// is deterministic.
func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
c.mu.Lock()
data, err := c.conn.SessionList(ctx)
c.mu.Unlock()
if err != nil {
return nil, err
}
return decodeChatSessions(data)
}
// Automations reads the documented OpenCode experimental schedule surface. The
// endpoint is session-scoped by query parameter; the decoder still requires an
// exact sessionID match before counting anything. The older serve backend has
// no schedule API, so it reports unavailable without making a guessed request.
func (c *Chat) Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error) {
info := protocol.ChatAutomationInfo{SessionID: sessionID, Provider: "opencode"}
if !ValidSessionID(sessionID) {
return info, fmt.Errorf("invalid OpenCode session id")
}
if c == nil || c.conn == nil || c.conn.Backend == "v1" {
info.Status = protocol.ChatAutomationUnavailable
info.Reason = "this OpenCode backend does not expose the experimental schedule read API"
return info, nil
}
readCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
data, err := c.call(readCtx, "get", "/api/experimental/schedule?sessionID="+url.QueryEscape(sessionID), nil)
if err != nil {
if strings.Contains(err.Error(), "HTTP 404") || strings.Contains(err.Error(), "HTTP 405") {
info.Status = protocol.ChatAutomationUnavailable
info.Reason = "this OpenCode endpoint does not expose the experimental schedule read API"
return info, nil
}
return info, err
}
entries, err := decodeScheduleInfos(data)
if err != nil {
return info, err
}
count := 0
for _, entry := range entries {
if entry.SessionID == sessionID && entry.Status == "active" {
count++
}
}
info.Status = protocol.ChatAutomationSupported
info.ActiveCount = &count
return info, nil
}
type scheduleInfo struct {
SessionID string `json:"sessionID"`
Status string `json:"status"`
}
// decodeScheduleInfos accepts the documented array and the API's common data
// envelope, but rejects null/malformed bodies so a bad response never becomes a
// false empty count.
func decodeScheduleInfos(data []byte) ([]scheduleInfo, error) {
var entries []scheduleInfo
if err := json.Unmarshal(data, &entries); err == nil && entries != nil {
if err := validateScheduleInfos(entries); err != nil {
return nil, err
}
return entries, nil
}
var envelope struct {
Data []scheduleInfo `json:"data"`
}
if err := json.Unmarshal(data, &envelope); err != nil || envelope.Data == nil {
return nil, fmt.Errorf("invalid OpenCode schedule response")
}
if err := validateScheduleInfos(envelope.Data); err != nil {
return nil, err
}
return envelope.Data, nil
}
func validateScheduleInfos(entries []scheduleInfo) error {
for _, entry := range entries {
if entry.SessionID == "" || entry.Status == "" {
return fmt.Errorf("invalid OpenCode schedule response")
}
}
return nil
}
// Create creates one OpenCode session in the given directory, mirroring the
// verified V2 shape POST /api/session {"title":...,"location":{"directory":...}}.
// It deliberately sends no model or permission override here: the endpoint's own
// defaults apply, exactly as the live check creates a session. The created
// session is returned with its directory lifted from location.directory.
// ActivateSkill uses the V2 experimental session skill endpoint. resume=false
// records the skill without starting an artificial turn; the first operator prompt
// is therefore the first model turn and receives the manager instructions.
func (c *Chat) ActivateSkill(ctx context.Context, id, skill string) error {
if !sessionID.MatchString(id) {
return fmt.Errorf("invalid OpenCode session id")
}
if strings.TrimSpace(skill) == "" {
return fmt.Errorf("empty OpenCode skill id")
}
_, err := c.call(ctx, "post", "/api/experimental/session/"+id+"/skill", map[string]any{"id": skill, "resume": false})
return err
}
func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
body := struct {
Title string `json:"title"`
Location struct {
Directory string `json:"directory"`
} `json:"location"`
}{Title: title}
body.Location.Directory = directory
data, err := c.call(ctx, "post", "/api/session", body)
if err != nil {
return protocol.ChatSession{}, err
}
return decodeChatSession(data)
}
// Session returns the endpoint's own record of one session so a caller can adopt
// an existing session with the directory and title the endpoint reports, never a
// guessed directory. found is false when the endpoint does not list id. It
// reuses Sessions/decodeChatSessions, so no second session decoder or endpoint is
// introduced; it performs at most one bounded endpoint read.
func (c *Chat) Session(ctx context.Context, id string) (protocol.ChatSession, bool, error) {
if !ValidSessionID(id) {
return protocol.ChatSession{}, false, fmt.Errorf("invalid OpenCode session id")
}
sessions, err := c.Sessions(ctx)
if err != nil {
return protocol.ChatSession{}, false, err
}
for _, session := range sessions {
if session.ID == id {
return session, true, nil
}
}
return protocol.ChatSession{}, false, nil
}
// 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.call(ctx, "post", path, body); err != nil {
return err
}
return nil
}
// Permissions lists the session's pending OpenCode approval requests, mirroring
// GET /api/session/{id}/permission. The location-wide endpoint can silently
// miss chats in another directory. Results are still filtered to sessionID;
// a malformed response is an error, never an empty
// success. It reuses Connection.Call so the request keeps the shared bounds,
// auth and translation, and reuses ValidSessionID for the same rejection the
// other chat calls apply.
func (c *Chat) Permissions(ctx context.Context, id string) ([]protocol.ChatPermissionFrame, error) {
if !sessionID.MatchString(id) {
return nil, fmt.Errorf("invalid OpenCode session id")
}
data, err := c.call(ctx, "get", "/api/session/"+id+"/permission", nil)
if err != nil {
return nil, err
}
return decodeChatPermissions(id, data)
}
// nativeChatPermission is one pending approval request matching the V2
// Permission.Request schema verified against the service's /openapi.json: id,
// sessionID, action and resources are required; save, metadata, source and
// message are optional, so the decoder tolerates any of them being absent.
type nativeChatPermission struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Action string `json:"action"`
Resources []string `json:"resources"`
Save []string `json:"save"`
Metadata map[string]any `json:"metadata"`
Source *nativeChatPermissionSource `json:"source"`
Message string `json:"message"`
}
// nativeChatPermissionSource is the incoming Permission.Source union; its single
// (tool) member carries type plus the message id and call id (the protocol frame
// renames messageID to message_id).
type nativeChatPermissionSource struct {
Type string `json:"type"`
MessageID string `json:"messageID"`
ID string `json:"id"`
}
// chatEnvelope unwraps the {"data":[...]} envelope the V2 HTTP API returns and
// reports whether the body was that envelope with a non-nil data array; a bare
// array or a malformed body returns ok=false. It is the single envelope rule the
// message and permission decoders share instead of each re-deriving it.
func chatEnvelope[T any](data []byte) ([]T, bool) {
var response struct {
Data []T `json:"data"`
}
if err := json.Unmarshal(data, &response); err != nil || response.Data == nil {
return nil, false
}
return response.Data, true
}
// chatPermissionRecords reads the {"data":[...]} envelope the V2 endpoint
// returns. An unparseable body or a missing data array is an error, never an
// empty list.
func chatPermissionRecords(data []byte) ([]nativeChatPermission, error) {
records, ok := chatEnvelope[nativeChatPermission](data)
if !ok {
return nil, fmt.Errorf("invalid OpenCode permission response")
}
return records, nil
}
// decodeChatPermissions maps the pending-request list onto protocol frames,
// keeping only the requested session's requests (a request with no id cannot be
// answered and is dropped).
func decodeChatPermissions(sessionID string, data []byte) ([]protocol.ChatPermissionFrame, error) {
records, err := chatPermissionRecords(data)
if err != nil {
return nil, err
}
frames := make([]protocol.ChatPermissionFrame, 0, len(records))
for _, record := range records {
if record.SessionID != sessionID || record.ID == "" {
continue
}
frame := protocol.ChatPermissionFrame{
SessionID: sessionID,
RequestID: record.ID,
Action: record.Action,
Resources: record.Resources,
Save: record.Save,
Metadata: record.Metadata,
Message: record.Message,
}
if record.Source != nil {
frame.Source = &protocol.ChatPermissionSource{Type: record.Source.Type, MessageID: record.Source.MessageID, ID: record.Source.ID}
}
frames = append(frames, frame)
}
return frames, nil
}
// Shells reads the endpoint's authoritative shell list and returns only running
// operations whose metadata explicitly names sessionID. The shell API is global;
// filtering locally avoids guessing an unsupported query filter and never assigns
// ownership from a shared working directory. A successful read also seeds the
// stream state used to attribute later shell.exited events, which carry no session.
func (c *Chat) Shells(ctx context.Context, sessionID string) ([]protocol.ChatShell, error) {
if !ValidSessionID(sessionID) {
return nil, fmt.Errorf("invalid OpenCode session id")
}
state, err := c.streamStateContext(ctx, sessionID)
if err != nil {
return nil, err
}
// One read per state; waiting and I/O never hold the event-state mutex.
state.mu.Lock()
if state.readGate == nil {
state.readGate = make(chan struct{}, 1)
}
gate := state.readGate
state.mu.Unlock()
select {
case gate <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
defer func() { <-gate }()
state.mu.Lock()
state.readback = &ShellSnapshot{}
state.mu.Unlock()
defer func() { state.mu.Lock(); state.readback = nil; state.mu.Unlock() }()
data, err := c.call(ctx, "get", "/api/shell", nil)
if err != nil {
return nil, err
}
var response struct {
Data []chatShellInfo `json:"data"`
}
if err := json.Unmarshal(data, &response); err != nil || response.Data == nil {
if err := json.Unmarshal(data, &response.Data); err != nil {
return nil, fmt.Errorf("invalid OpenCode shell response")
}
}
c.shellMu.Lock()
if c.shellOwners == nil {
c.shellOwners = make(map[string]string)
}
for _, info := range response.Data {
if ValidShellID(info.ID) && ValidSessionID(info.shellSessionID()) {
c.shellOwners[info.ID] = info.shellSessionID()
}
}
c.shellMu.Unlock()
out := make([]protocol.ChatShell, 0, len(response.Data))
for _, info := range response.Data {
if info.ID == "" || info.shellSessionID() != sessionID || (info.Status != "" && info.Status != protocol.ChatShellRunning && info.Status != protocol.ChatShellExited) {
continue
}
status := info.Status
if status == "" {
status = protocol.ChatShellRunning
}
out = append(out, protocol.ChatShell{ID: info.ID, Status: status, Command: info.Command})
}
state.mu.Lock()
defer state.mu.Unlock()
out, err = state.readback.Merge(out)
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
ids := make([]string, 0, len(out))
for _, shell := range out {
ids = append(ids, shell.ID)
}
state.replaceShellsLocked(ids)
return out, nil
}
// ShellOutput validates explicit session metadata from the authoritative detail
// record before reading the selected bounded output page. A shared directory is
// never ownership evidence.
func (c *Chat) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
if !ValidSessionID(query.SessionID) || !ValidShellID(query.ShellID) || query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
return protocol.ChatShellOutputPage{}, fmt.Errorf("invalid shell output query")
}
c.shellMu.Lock()
owner := c.shellOwners[query.ShellID]
c.shellMu.Unlock()
if owner != "" && owner != query.SessionID {
return protocol.ChatShellOutputPage{}, fmt.Errorf("shell is not available for this session")
}
data, err := c.call(ctx, "get", "/api/shell/"+query.ShellID, nil)
if err != nil {
if c.conn.LastHTTPStatus == 404 {
return protocol.ChatShellOutputPage{Unavailable: true}, nil
}
return protocol.ChatShellOutputPage{}, err
}
var detail struct {
Data chatShellInfo `json:"data"`
}
if err := json.Unmarshal(data, &detail); err != nil || detail.Data.ID != query.ShellID || detail.Data.shellSessionID() != query.SessionID || (detail.Data.Status != "" && detail.Data.Status != protocol.ChatShellRunning && detail.Data.Status != protocol.ChatShellExited) {
return protocol.ChatShellOutputPage{}, fmt.Errorf("shell is not available for this session")
}
shell := protocol.ChatShell{ID: detail.Data.ID, Status: detail.Data.Status, Command: detail.Data.Command, Exit: detail.Data.Exit}
if shell.Status == "" {
shell.Status = protocol.ChatShellRunning
}
path := fmt.Sprintf("/api/shell/%s/output?cursor=%d&limit=%d", query.ShellID, query.Cursor, query.Limit)
data, err = c.call(ctx, "get", path, nil)
if err != nil {
if c.conn.LastHTTPStatus == 404 {
return protocol.ChatShellOutputPage{Shell: shell, Unavailable: true}, nil
}
return protocol.ChatShellOutputPage{}, err
}
var response struct {
Data *struct {
Output *string `json:"output"`
Cursor *int64 `json:"cursor"`
Size *int64 `json:"size"`
Truncated *bool `json:"truncated"`
} `json:"data"`
}
if err := json.Unmarshal(data, &response); err != nil || response.Data == nil || response.Data.Output == nil || response.Data.Cursor == nil || response.Data.Size == nil || response.Data.Truncated == nil || len(*response.Data.Output) > query.Limit || *response.Data.Cursor < query.Cursor || *response.Data.Cursor > protocol.ChatShellOutputMaxCursor || *response.Data.Size < *response.Data.Cursor || *response.Data.Size > protocol.ChatShellOutputMaxCursor || *response.Data.Cursor-query.Cursor != int64(len(*response.Data.Output)) {
return protocol.ChatShellOutputPage{}, fmt.Errorf("invalid OpenCode shell output response")
}
return protocol.ChatShellOutputPage{Shell: shell, Output: *response.Data.Output, Cursor: *response.Data.Cursor, Size: *response.Data.Size, Truncated: *response.Data.Truncated}, nil
}
// streamState returns the session's retained, verified shell identities. It is
// deliberately kept across stream replacement so an exit after reconnect remains
// attributable; Shells reconciles its contents from authoritative readback on
// each attach rather than replacing the pointer a live scanner is using.
func (c *Chat) streamState(sessionID string) *ChatStreamState {
state, _ := c.streamStateContext(context.Background(), sessionID)
return state
}
func (c *Chat) streamStateContext(ctx context.Context, sessionID string) (*ChatStreamState, error) {
c.shellMu.Lock()
defer c.shellMu.Unlock()
if err := ctx.Err(); err != nil {
return nil, err
}
if c.shells == nil {
c.shells = map[string]*ChatStreamState{}
}
state := c.shells[sessionID]
if state == nil {
state = &ChatStreamState{}
c.shells[sessionID] = state
}
return state, nil
}
// ReleaseShells discards verified shell identities after the last room observer
// disconnects. A future attach calls Shells for a fresh authoritative snapshot,
// so this bounds state without attributing a foreign shell during the gap.
func (c *Chat) ReleaseShells(sessionID string) {
if sessionID == "" {
return
}
c.shellMu.Lock()
delete(c.shells, sessionID)
c.shellMu.Unlock()
}
// 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")
}
// Pin state before opening/announcing the stream so a canceled scanner
// cannot acquire a replacement room's identity map.
state, err := c.streamStateContext(ctx, id)
if err != nil {
return err
}
body, err := c.conn.EventStream(ctx)
if err != nil {
return err
}
defer body.Close()
defer func() {
state.mu.Lock()
state.Compaction = nil
state.mu.Unlock()
}()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var delivery sync.Mutex
usageReadbackAvailable := false // protected by delivery, fallback for older API builds
var pendingUsage *protocol.ChatUsage // latest cumulative event, never a sum
state.mu.Lock()
busy := state.Active
state.mu.Unlock()
setBusy := func(value bool) {
busy = value
state.mu.Lock()
state.Active = value
state.usageDirty = true
if !value {
state.Compaction = nil
}
state.mu.Unlock()
}
deliver := func(frame protocol.ChatEventFrame) error {
// Native usage is cumulative but lacks context/model/timing. Coalesce it
// into one complete readback; never erase richer metrics with a partial
// usage event or issue HTTP reads for every token delta.
if frame.Kind == protocol.ChatEventUsage {
state.mu.Lock()
state.usageDirty = true
state.mu.Unlock()
delivery.Lock()
defer delivery.Unlock()
if usageReadbackAvailable {
pendingUsage = frame.Usage
return nil
}
return emit(frame)
}
delivery.Lock()
defer delivery.Unlock()
if frame.Kind == protocol.ChatEventStep || frame.Kind == protocol.ChatEventText || frame.Kind == protocol.ChatEventTool || frame.Kind == protocol.ChatEventReasoning || (frame.Compaction != nil && frame.Compaction.Status == "running") {
setBusy(true)
}
return emit(frame)
}
// Recover a compaction already underway before this SSE attachment. The
// event body is already open, so any concurrent terminal event follows this
// snapshot in the scanner, rather than being lost between read and subscribe.
if compaction := c.readCompaction(ctx, id); compaction != nil {
state.mu.Lock()
state.Compaction = compaction
state.mu.Unlock()
if err := deliver(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventCompaction, Compaction: compaction}); err != nil {
return err
}
}
// V2 /api/session/active describes foreground drains, not individual
// provider steps. Poll it even after reconnect: a busy drain may have
// started before this SSE subscription. Failed readbacks never imply idle.
watchDone := make(chan struct{})
go func() {
defer close(watchDone)
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
}
delivery.Lock()
readCtx, readCancel := context.WithTimeout(ctx, 5*time.Second)
data, err := c.call(readCtx, "get", "/api/session/active", nil)
readCancel()
var emitErr error
var response struct {
Data *map[string]json.RawMessage `json:"data"`
}
if err == nil && json.Unmarshal(data, &response) == nil && response.Data != nil {
_, active := (*response.Data)[id]
if active && !busy {
setBusy(true)
emitErr = emit(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted}})
} else if !active && busy {
setBusy(false)
emitErr = emit(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}})
}
}
delivery.Unlock()
if emitErr != nil {
cancel()
_ = body.Close()
return
}
}
}()
defer func() { cancel(); <-watchDone }()
usageRefreshGate := make(chan struct{}, 1)
refreshUsage := func() error {
if c.conn.Backend == "v1" {
return nil
}
select {
case usageRefreshGate <- struct{}{}:
defer func() { <-usageRefreshGate }()
default:
return nil
}
readCtx, readCancel := context.WithTimeout(ctx, 5*time.Second)
usage, err := c.Usage(readCtx, id)
readCancel()
if err != nil {
// A failed enrichment read must not lose authoritative native totals.
delivery.Lock()
defer delivery.Unlock()
usageReadbackAvailable = false
if pendingUsage != nil {
usage := pendingUsage
pendingUsage = nil
return emit(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventUsage, Usage: usage})
}
return nil // unavailable metrics must not break chat
}
delivery.Lock()
defer delivery.Unlock()
usageReadbackAvailable = true
pendingUsage = nil
return emit(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventUsage, Usage: usage})
}
if err := refreshUsage(); err != nil {
return err
}
usageDone := make(chan struct{})
go func() {
defer close(usageDone)
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
}
state.mu.Lock()
refresh := state.usageDirty || state.Active
state.usageDirty = false
state.mu.Unlock()
if refresh {
if err := refreshUsage(); err != nil {
cancel()
_ = body.Close()
return
}
}
}
}()
defer func() { cancel(); <-usageDone }()
if ready != nil {
ready()
}
err = c.scanChatEventsWithState(ctx, body, id, state, deliver)
if ctx.Err() == nil {
state.mu.Lock()
dirty := state.usageDirty
state.mu.Unlock()
if dirty {
if refreshErr := refreshUsage(); refreshErr != nil {
return refreshErr
}
}
}
return err
}
// 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 (c *Chat) scanChatEvents(ctx context.Context, body io.Reader, sessionID string, emit func(protocol.ChatEventFrame) error) error {
return c.scanChatEventsWithState(ctx, body, sessionID, c.streamState(sessionID), emit)
}
func (c *Chat) scanChatEventsWithState(ctx context.Context, body io.Reader, sessionID string, state *ChatStreamState, emit func(protocol.ChatEventFrame) error) error {
scanner := bufio.NewScanner(body)
scanner.Buffer(make([]byte, 0, 64<<10), MaxResponse)
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
}
var usageTrigger struct {
Type string `json:"type"`
Data struct {
SessionID string `json:"sessionID"`
} `json:"data"`
}
if json.Unmarshal(payload, &usageTrigger) == nil && usageTrigger.Data.SessionID == sessionID {
switch usageTrigger.Type {
case "session.usage.updated", "session.step.ended", "session.step.failed", "session.compaction.ended", "session.compaction.failed", "session.model.selected", "session.moved", "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
state.mu.Lock()
state.usageDirty = true
state.mu.Unlock()
}
}
frame, ok, err := NormalizeChatEvent(payload, sessionID, state)
if err != nil {
return err
}
if !ok {
continue
}
if frame.MessageID != "" {
state.setLastMessageID(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()
}
// isChatEventType reports whether t is an event type NormalizeChatEvent
// surfaces. Unknown types are skipped before their data is decoded, so an
// unrelated event whose fields share a name with chatEvent but carry a different
// JSON shape cannot fail the stream.
func isChatEventType(t string) bool {
switch t {
case "session.text.delta", "session.reasoning.delta",
"session.step.started", "session.step.streamed", "session.step.ended",
"session.usage.updated",
"session.compaction.started", "session.compaction.ended", "session.compaction.failed",
"session.tool.input.started", "session.tool.input.ended",
"session.tool.called", "session.tool.progress",
"session.tool.success", "session.tool.failed",
"form.created", "form.replied", "form.cancelled",
"shell.created", "shell.exited":
return true
}
return false
}
// chatFormPayload is the form object nested under form.created. The question
// tool uses metadata.kind == "question"; other forms are surfaced with their own
// kind so the client can decide whether to render them as a question.
type chatFormPayload struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Title string `json:"title"`
Metadata map[string]any `json:"metadata"`
Fields []chatFormField `json:"fields"`
}
// Forms recovers pending questions even when their creation event preceded the
// browser connection or the Pipelines process. Session ownership is explicit.
func (c *Chat) Forms(ctx context.Context, id string) ([]protocol.ChatForm, error) {
if !ValidSessionID(id) {
return nil, fmt.Errorf("invalid OpenCode session id")
}
data, err := c.call(ctx, "get", "/api/session/"+id+"/form", nil)
if err != nil {
return nil, err
}
forms, ok := chatEnvelope[chatFormPayload](data)
if !ok {
return nil, fmt.Errorf("invalid OpenCode form response")
}
result := make([]protocol.ChatForm, 0, len(forms))
for _, form := range forms {
if form.ID == "" || form.SessionID != id {
continue
}
frame, valid, err := normalizeFormEvent("form.created", chatEvent{Form: &form}, id, nil)
if err != nil {
return nil, err
}
if valid {
result = append(result, *frame.Form)
}
}
return result, nil
}
type chatFormField struct {
Key string `json:"key"`
Title string `json:"title"`
Description string `json:"description"`
Type string `json:"type"`
Options []chatFormOption `json:"options"`
Custom bool `json:"custom"`
Required bool `json:"required"`
URL string `json:"url"`
Default any `json:"default"`
Minimum any `json:"minimum"`
Maximum any `json:"maximum"`
MinLength *int `json:"minLength"`
MaxLength *int `json:"maxLength"`
MinItems *int `json:"minItems"`
MaxItems *int `json:"maxItems"`
Format string `json:"format"`
Pattern string `json:"pattern"`
Placeholder string `json:"placeholder"`
Hidden bool `json:"hidden"`
When []protocol.ChatFormWhen `json:"when"`
}
type chatFormOption struct {
Value string `json:"value"`
Label string `json:"label"`
Description string `json:"description"`
}
// 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"`
Text string `json:"text"`
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"`
// The shell family. shell.created nests the started command under info;
// shell.exited carries the id, the final status and the exit code at the top
// level. Exit is a pointer so an exit of 0 is distinguishable from absent.
Status string `json:"status"`
Exit *int `json:"exit"`
Info *chatShellInfo `json:"info"`
// Form is the nested form.created payload; FormID is the bare id on
// form.replied/form.cancelled.
Form *chatFormPayload `json:"form"`
}
// chatShellInfo is the Shell.Info envelope a shell.created event nests under
// "info". The session that started the shell is reported in metadata.sessionID
// (the agent's shell tool sets it); only the fields the protocol surfaces are
// read, and the shell's cwd/file are deliberately not carried so no path or
// credential leaks into a frame.
type chatShellInfo struct {
ID string `json:"id"`
Status string `json:"status"`
Command string `json:"command"`
Exit *int `json:"exit"`
Metadata map[string]any `json:"metadata"`
}
// shellSessionID reads the session that started a shell from the created event's
// metadata, or "" when the event carries none. The agent's shell tool sets
// metadata.sessionID; a shell started by anything else is unattributed and is
// ignored, so a shell that cannot be shown to belong to this session never
// becomes one of its frames.
func (i *chatShellInfo) shellSessionID() string {
if i == nil || i.Metadata == nil {
return ""
}
id, _ := i.Metadata["sessionID"].(string)
return id
}
// ChatStreamState is the per-session memory one event stream folds across its
// frames, so a frame that omits context can still be attributed. It is the
// single state NormalizeChatEvent reads and writes; a caller that maps a lone
// event passes an empty state (or nil when it needs no attribution).
//
// - LastMessageID is the most recent assistant message id, so a later tool or
// step event that omits it still attributes every frame to a stable message.
// - Shells holds the ids of the shells this session has started and not yet
// seen exit. shell.exited carries no session id, so the id remembered here is
// what attributes the exit to its session: another session's shell is an
// unknown id and is ignored.
// - Forms maps a pending form id to its session, so form.replied/cancelled
// (which carry no session) can be attributed to the right chat.
type ChatStreamState struct {
Compaction *protocol.ChatCompaction
mu sync.Mutex
Active bool // last observed foreground drain, retained across SSE reconnects
LastMessageID string
Shells map[string]struct{}
Forms map[string]string
readGate chan struct{}
readback *ShellSnapshot
usageDirty bool
}
func (s *ChatStreamState) lastMessageID() string {
if s == nil {
return ""
}
s.mu.Lock()
defer s.mu.Unlock()
return s.LastMessageID
}
func (s *ChatStreamState) setLastMessageID(id string) {
if s == nil || id == "" {
return
}
s.mu.Lock()
s.LastMessageID = id
s.mu.Unlock()
}
// knowsShell reports whether id is a shell this stream has already surfaced for
// the session, and so is one this stream may now report the exit of.
func (s *ChatStreamState) knowsShell(id string) bool {
if s == nil || id == "" {
return false
}
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.Shells[id]
return ok
}
// markShell remembers id as a shell of this session.
func (s *ChatStreamState) markShell(id string) {
if s == nil || id == "" {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.Shells == nil {
s.Shells = map[string]struct{}{}
}
s.Shells[id] = struct{}{}
}
// forgetShell drops id once its exit has been surfaced.
func (s *ChatStreamState) forgetShell(id string) {
if s == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.Shells == nil {
return
}
delete(s.Shells, id)
}
// replaceShells applies one authoritative running-shell snapshot without
// replacing the state object an already attached event scanner owns.
func (s *ChatStreamState) replaceShells(ids []string) {
if s == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
s.replaceShellsLocked(ids)
}
func (s *ChatStreamState) replaceShellsLocked(ids []string) {
s.Shells = make(map[string]struct{}, len(ids))
for _, id := range ids {
if id != "" {
s.Shells[id] = struct{}{}
}
}
}
// NormalizeChatEvent maps one OpenCode firehose `data:` payload to a
// protocol.ChatEventFrame, folding the small per-session context ([stream]) it
// needs across frames. 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.
// stream may be nil when the caller maps a lone event and needs no attribution;
// a nil stream simply means no inherited message id and no remembered shell.
func NormalizeChatEvent(payload []byte, sessionID string, stream *ChatStreamState) (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
}
// Only decode the data of event types this adapter surfaces. The firehose
// also carries unrelated session events whose fields collide with chatEvent
// but have a different JSON shape (session.instructions.updated carries
// "delta" as an object), so decoding every event would fail the stream on an
// event that is not a chat frame at all.
if !isChatEventType(outer.Type) {
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)
}
// The shell events are location-scoped, not session-scoped: the session that
// started a shell is reported in the created event's metadata, and the exit
// names no session at all, so it is attributed through the ids this stream
// already surfaced. They are mapped before the session check the other events
// use, which their absent data.sessionID could never pass.
if outer.Type == "shell.created" || outer.Type == "shell.exited" {
return normalizeShellEvent(outer.Type, data, sessionID, stream)
}
if strings.HasPrefix(outer.Type, "form.") {
return normalizeFormEvent(outer.Type, data, sessionID, stream)
}
if data.SessionID != sessionID {
return protocol.ChatEventFrame{}, false, nil
}
// Verified V2 SessionEvent.Compaction schema (upstream 3fdb13bc):
// only sessionID is shared across started/ended/failed; no message id.
if strings.HasPrefix(outer.Type, "session.compaction.") {
status := "running"
if outer.Type == "session.compaction.ended" {
status = "completed"
}
if outer.Type == "session.compaction.failed" {
status = "failed"
}
compaction := &protocol.ChatCompaction{Status: status}
if stream != nil {
stream.mu.Lock()
stream.Compaction = nil
if status == "running" {
stream.Compaction = compaction
}
stream.mu.Unlock()
}
return protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventCompaction, Compaction: compaction}, true, nil
}
messageID := data.MessageID
if messageID == "" {
messageID = data.MessageIDAlt
}
if messageID == "" && stream != nil {
messageID = stream.lastMessageID()
}
// Usage is session state; native V2 UsageUpdated has no message id. Other
// message frames still require a stable id for transcript attribution.
if messageID == "" && outer.Type != "session.usage.updated" {
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: protocol.ChatDeltaPartID(messageID, protocol.ChatPartText, data.Ordinal)}
case outer.Type == "session.reasoning.delta":
frame.Kind = protocol.ChatEventReasoning
frame.Delta = data.Delta
frame.Part = &protocol.ChatPart{Type: protocol.ChatPartReasoning, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartReasoning, 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), Intermediate: outer.Type == "session.step.ended"}
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: toolInput(data), 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
frame.Usage = decodeUsageSnapshot(outer.Data)
default:
return protocol.ChatEventFrame{}, false, nil
}
return frame, true, nil
}
// normalizeFormEvent maps one form.created / form.replied / form.cancelled
// payload onto a ChatEventForm frame. Form.created carries its own session; the
// terminal events carry only an id, so the stream remembers which session owns
// each pending form. A form from another session is ignored, and an unknown
// terminal id is another session's form rather than a malformed frame.
func normalizeFormEvent(eventType string, data chatEvent, sessionID string, stream *ChatStreamState) (protocol.ChatEventFrame, bool, error) {
if eventType == "form.created" {
form := data.Form
if form == nil || form.ID == "" {
return protocol.ChatEventFrame{}, false, fmt.Errorf("malformed OpenCode form.created event")
}
if form.SessionID != "" && form.SessionID != sessionID {
return protocol.ChatEventFrame{}, false, nil
}
kind := ""
if form.Metadata != nil {
kind, _ = form.Metadata["kind"].(string)
}
frame := protocol.ChatForm{
ID: form.ID,
SessionID: sessionID,
Title: form.Title,
Kind: kind,
Actions: []string{"accept", "cancel"},
}
for _, field := range form.Fields {
out := protocol.ChatFormField{
Key: field.Key,
Title: field.Title,
Description: field.Description,
Type: field.Type,
Custom: field.Custom,
Required: field.Required,
URL: field.URL, Default: field.Default, Minimum: field.Minimum, Maximum: field.Maximum,
MinLength: field.MinLength, MaxLength: field.MaxLength, MinItems: field.MinItems, MaxItems: field.MaxItems,
Format: field.Format, Pattern: field.Pattern, Placeholder: field.Placeholder, Hidden: field.Hidden, When: field.When,
}
for _, option := range field.Options {
value := option.Value
if value == "" {
value = option.Label
}
out.Options = append(out.Options, protocol.ChatFormOption{
Value: value, Label: option.Label, Description: option.Description,
})
}
frame.Fields = append(frame.Fields, out)
}
if stream != nil {
stream.mu.Lock()
if stream.Forms == nil {
stream.Forms = map[string]string{}
}
stream.Forms[form.ID] = sessionID
stream.mu.Unlock()
}
return protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventForm, Form: &frame}, true, nil
}
id := data.ID
if id == "" && data.Form != nil {
id = data.Form.ID
}
if id == "" {
return protocol.ChatEventFrame{}, false, fmt.Errorf("malformed OpenCode %s event", eventType)
}
if stream == nil {
return protocol.ChatEventFrame{}, false, nil
}
stream.mu.Lock()
owner, known := stream.Forms[id]
if known && owner == sessionID {
delete(stream.Forms, id)
}
stream.mu.Unlock()
if !known || owner != sessionID {
return protocol.ChatEventFrame{}, false, nil
}
form := &protocol.ChatForm{ID: id, SessionID: sessionID}
if eventType == "form.cancelled" {
form.Cancelled = true
} else {
form.Resolved = true
}
return protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventForm, Form: form}, true, nil
}
// normalizeShellEvent maps one shell.created/shell.exited payload onto a
// protocol.ChatEventShell frame. A shell belongs to the session whose id the
// created event carries in info.metadata.sessionID, so a shell started by any
// other session is ignored (ok=false) rather than shown in this session. The
// exit event carries no session at all, so it is emitted only for a shell id
// this stream already surfaced for the session; any other id is another
// session's and is ignored. An event that carries no shell id at all cannot be
// keyed by the client and is malformed, so it fails the stream instead of
// producing a frame the client cannot attribute.
func normalizeShellEvent(eventType string, data chatEvent, sessionID string, stream *ChatStreamState) (protocol.ChatEventFrame, bool, error) {
if eventType == "shell.created" {
if data.Info == nil || data.Info.ID == "" {
return protocol.ChatEventFrame{}, false, fmt.Errorf("malformed OpenCode shell.created event")
}
if data.Info.shellSessionID() != sessionID {
return protocol.ChatEventFrame{}, false, nil
}
status := data.Info.Status
if status == "" {
status = protocol.ChatShellRunning
}
shell := &protocol.ChatShell{ID: data.Info.ID, Status: status, Command: data.Info.Command}
if stream != nil {
stream.mu.Lock()
stream.readback.Record(shell)
if stream.Shells == nil {
stream.Shells = map[string]struct{}{}
}
if status == protocol.ChatShellRunning && len(stream.Shells) < chatShellIdentityLimit {
stream.Shells[shell.ID] = struct{}{}
}
stream.mu.Unlock()
}
return protocol.ChatEventFrame{
SessionID: sessionID,
Kind: protocol.ChatEventShell,
Shell: shell,
}, true, nil
}
if data.ID == "" {
return protocol.ChatEventFrame{}, false, fmt.Errorf("malformed OpenCode shell.exited event")
}
if stream == nil {
return protocol.ChatEventFrame{}, false, nil
}
stream.mu.Lock()
stream.readback.Record(&protocol.ChatShell{ID: data.ID, Status: protocol.ChatShellExited})
_, known := stream.Shells[data.ID]
delete(stream.Shells, data.ID)
stream.mu.Unlock()
if !known {
return protocol.ChatEventFrame{}, false, nil
}
status := data.Status
if status == "" {
status = protocol.ChatShellExited
}
return protocol.ChatEventFrame{
SessionID: sessionID,
Kind: protocol.ChatEventShell,
Shell: &protocol.ChatShell{ID: data.ID, Status: status, Exit: data.Exit},
}, true, nil
}
// toolInput picks a tool call's arguments from whichever frame carries them:
// session.tool.called carries the parsed `input` object, session.tool.input.ended
// carries the same arguments as a `text` JSON string, and progress/success carry
// neither. Text that already parses as JSON is kept as that value (so an object
// pretty-prints); a partial string is carried as a JSON string so the frame stays
// valid and the client can show it while streaming. It returns nil when the frame
// carries no arguments, so the consumer retains what it already learned.
func toolInput(data chatEvent) json.RawMessage {
if len(data.Input) > 0 && string(data.Input) != "null" {
return data.Input
}
text := strings.TrimSpace(data.Text)
if text == "" {
return nil
}
if json.Valid([]byte(text)) {
return json.RawMessage(text)
}
encoded, err := json.Marshal(text)
if err != nil {
return nil
}
return encoded
}
// 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
}
// nativeChatMessage is one stored turn. The two surfaces return different
// envelopes for the same session and both decode into this one struct, so the
// mapping below reads whichever fields a record populated:
//
// - the V2 HTTP API (GET /api/session/{id}/message) puts id/type/agent/model,
// the timing and the parts array at the message top level, with the parts
// under "content" and a user turn's text as a bare string;
// - the native serve readback nests the same fields under "info" (role as
// "role", model as "modelID", timing as "created") with the parts under
// "parts".
type nativeChatMessage struct {
Raw json.RawMessage `json:"-"`
ID string `json:"id"`
Type string `json:"type"`
Agent string `json:"agent"`
Model nativeChatModel `json:"model"`
Time *protocol.ChatTime `json:"time"`
Text string `json:"text"`
Content []nativeChatPart `json:"content"`
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 []nativeChatPart `json:"parts"`
// Files are the V2 user turn's attached files. They live on the message
// envelope (not in Parts), with an inline data field the history mapper must
// not expose.
Files []nativeChatFile `json:"files"`
}
type nativeChatFile struct {
Data string `json:"data"`
Mime string `json:"mime"`
Name string `json:"name"`
Source struct {
Type string `json:"type"`
URI string `json:"uri"`
} `json:"source"`
}
// 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"`
ProviderID string `json:"providerID"`
// Variant is the session model's chosen variant (its thinking level).
Variant string `json:"variant"`
}
// nativeChatPart is one content element shared by both message envelopes. Raw
// keeps the element's original JSON so the session exporter can render an
// unrecognised part type (file, patch, step, ...) instead of dropping it; it is
// ignored when a part is re-encoded.
type nativeChatPart struct {
Type string `json:"type"`
ID string `json:"id"`
Text string `json:"text"`
Name string `json:"name"`
URI string `json:"uri"`
Mime string `json:"mime"`
Executed bool `json:"executed"`
State *protocol.ChatToolState `json:"state"`
Time *protocol.ChatTime `json:"time"`
Raw json.RawMessage `json:"-"`
}
// UnmarshalJSON decodes one content part and retains its raw JSON alongside the
// decoded fields, so a part type the decoder does not model is still available
// verbatim to the session exporter.
func (p *nativeChatPart) UnmarshalJSON(data []byte) error {
type part nativeChatPart
var decoded part
if err := json.Unmarshal(data, &decoded); err != nil {
return err
}
*p = nativeChatPart(decoded)
p.Raw = append(p.Raw[:0], data...)
return nil
}
// role, parts and the accessor methods below read the V2 top-level fields first
// and fall back to the native serve "info"/"parts" fields, so one record maps
// regardless of which surface produced it.
func (m nativeChatMessage) role() string {
if m.Info.Role != "" {
return m.Info.Role
}
return m.Type
}
func (m nativeChatMessage) messageID() string {
if m.Info.ID != "" {
return m.Info.ID
}
return m.ID
}
func (m nativeChatMessage) modelID() string {
if m.Info.ModelID != "" {
return m.Info.ModelID
}
return m.Model.ID
}
func (m nativeChatMessage) agent() string {
if m.Info.Agent != "" {
return m.Info.Agent
}
return m.Agent
}
func (m nativeChatMessage) createdAt() int64 {
if m.Info.CreatedAt != 0 {
return m.Info.CreatedAt
}
if m.Time != nil {
return m.Time.Created
}
return 0
}
func (m nativeChatMessage) contentParts() []nativeChatPart {
if m.Parts != nil {
return m.Parts
}
return m.Content
}
// 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) {
if records, ok := chatEnvelope[nativeChatMessage](data); ok {
return records, 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
}
return mapChatMessages(sessionID, records), nil
}
func mapChatMessages(sessionID string, records []nativeChatMessage) []protocol.ChatMessage {
messages := make([]protocol.ChatMessage, 0, len(records))
for _, record := range records {
role := record.role()
if role != protocol.ChatRoleUser && role != protocol.ChatRoleAssistant {
continue
}
out := protocol.ChatMessage{ID: record.messageID(), SessionID: sessionID, Role: role, Model: record.modelID(), Agent: record.agent(), CreatedAt: record.createdAt()}
for _, part := range record.contentParts() {
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})
case protocol.ChatPartFile:
if part.URI == "" && part.Name == "" {
continue
}
out.Parts = append(out.Parts, protocol.ChatPart{Type: protocol.ChatPartFile, Name: part.Name, URI: part.URI, Mime: part.Mime})
}
}
// A V2 user turn carries its prompt text as a message-level string rather
// than a content array, so surface it as the turn's single text part.
if len(out.Parts) == 0 && role == protocol.ChatRoleUser && record.Text != "" {
out.Parts = append(out.Parts, protocol.ChatPart{Type: protocol.ChatPartText, Text: record.Text})
}
// Attached files are top-level on the user envelope. Keep their name,
// MIME and file URI for the transcript; never copy the base64 data into
// history.
for _, file := range record.Files {
uri := file.Source.URI
if uri == "" {
continue
}
out.Parts = append(out.Parts, protocol.ChatPart{
Type: protocol.ChatPartFile,
Name: file.Name,
URI: uri,
Mime: file.Mime,
})
}
messages = append(messages, out)
}
return messages
}
// decodeChatHistoryPage reads the V2 cursor envelope while retaining the older
// bare-array decoder for native serve. Tool output is intentionally previewed:
// one command's unbounded stdout must not make the entire transcript or its final
// answer unavailable over the websocket.
func decodeChatHistoryPage(ctx context.Context, sessionID string, reader io.Reader) ([]protocol.ChatMessage, string, bool, error) {
return readHistoryPage(ctx, sessionID, reader)
}
const historyToolPreviewBytes = 64 << 10
// nativeChatSession is one listed session in the verified V2 shape
// ({id,title,agent,model,cost,tokens,outcome,time,title,location.directory,
// parentID,permissions}); only the fields the protocol surfaces are read. The
// native v1 serve readback of the same list is not covered by the research, so
// its records decode through the same tolerant envelope but any additional
// nesting is not asserted.
type nativeChatSession struct {
ID string `json:"id"`
Title string `json:"title"`
Agent string `json:"agent"`
Model nativeChatModel `json:"model"`
ParentID string `json:"parentID"`
Location struct {
Directory string `json:"directory"`
} `json:"location"`
Time struct {
Created int64 `json:"created"`
Updated int64 `json:"updated"`
} `json:"time"`
}
// chatSessionRecords accepts both session-list envelopes: the V2 HTTP API wraps
// them in {"data":[...]} while the native serve readback returns a bare array.
// An unrecognised body is an error, never an empty list.
func chatSessionRecords(data []byte) ([]nativeChatSession, error) {
if records, ok := chatEnvelope[nativeChatSession](data); ok {
return records, nil
}
var records []nativeChatSession
if err := json.Unmarshal(data, &records); err != nil {
return nil, fmt.Errorf("invalid OpenCode session response")
}
return records, nil
}
// chatSessionRecord reads one created session, accepting the {"data":{...}}
// envelope the V2 API returns and tolerating a bare object. An unrecognised body
// is an error, never an empty session.
func chatSessionRecord(data []byte) (nativeChatSession, error) {
var response struct {
Data *nativeChatSession `json:"data"`
}
if err := json.Unmarshal(data, &response); err == nil && response.Data != nil {
return *response.Data, nil
}
var record nativeChatSession
if err := json.Unmarshal(data, &record); err != nil || record.ID == "" {
return nativeChatSession{}, fmt.Errorf("invalid OpenCode session response")
}
return record, nil
}
// chatSessionFields lifts the nested location.directory and time{created,updated}
// of one native session record onto protocol.ChatSession. It is the single field
// 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,
ModelProvider: record.Model.ProviderID,
Effort: record.Model.Variant,
Directory: record.Location.Directory,
ParentID: record.ParentID,
CreatedAt: record.Time.Created,
UpdatedAt: record.Time.Updated,
}
}
// decodeChatSessions maps the listed sessions onto protocol.ChatSession, dropping
// every record whose id is not a valid OpenCode session id (an empty or foreign
// id cannot be addressed) and ordering by UpdatedAt then id so the result is
// deterministic.
func decodeChatSessions(data []byte) ([]protocol.ChatSession, error) {
records, err := chatSessionRecords(data)
if err != nil {
return nil, err
}
sessions := make([]protocol.ChatSession, 0, len(records))
for _, record := range records {
if !sessionID.MatchString(record.ID) {
continue
}
sessions = append(sessions, chatSessionFields(record))
}
sort.SliceStable(sessions, func(i, j int) bool {
if sessions[i].UpdatedAt != sessions[j].UpdatedAt {
return sessions[i].UpdatedAt > sessions[j].UpdatedAt
}
return sessions[i].ID < sessions[j].ID
})
return sessions, nil
}
// decodeChatSession maps one created session, rejecting an empty or foreign id
// (an unaddressable session is an error, never a silent success).
func decodeChatSession(data []byte) (protocol.ChatSession, error) {
record, err := chatSessionRecord(data)
if err != nil {
return protocol.ChatSession{}, err
}
if !sessionID.MatchString(record.ID) {
return protocol.ChatSession{}, fmt.Errorf("invalid OpenCode session response")
}
return chatSessionFields(record), nil
}
// ProbeTurn reports whether OpenCode is running a turn for the session, read
// from the same /api/session/active list Stream polls. The server uses it once
// at start to resume observing turns a previous process left running. A failed
// read is an error, never "idle".
func (c *Chat) ProbeTurn(ctx context.Context, id string) (bool, error) {
if !sessionID.MatchString(id) {
return false, fmt.Errorf("invalid OpenCode session id")
}
data, err := c.call(ctx, "get", "/api/session/active", nil)
if err != nil {
return false, err
}
var response struct {
Data *map[string]json.RawMessage `json:"data"`
}
if err := json.Unmarshal(data, &response); err != nil || response.Data == nil {
return false, fmt.Errorf("invalid OpenCode active-session readback")
}
_, active := (*response.Data)[id]
return active, nil
}