Files
pipelines/internal/server/chat_sessions.go
T
alan f7a3a49f94 chat: add the Codex backend
Store a chat's harness with its operator session, expose chat_backends and a
backend choice in New chat, and route each session through a manager. The Codex
adapter uses the App Server's Unix WebSocket for threads, turns, history,
questions and interrupt; OpenCode remains the default and Claude is not
advertised until its sidecar and login are wired.
2026-10-20 12:10:39 +01:00

373 lines
16 KiB
Go

package server
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// operatorDirectoryLimit bounds the chat_directories choices: the operator home
// plus recent operator-session directories, capped at this small fixed number so
// a long history is never returned. It matches the posture of the other small
// fixed list bounds.
const operatorDirectoryLimit = 8
// handleChatSessions answers chat_sessions with the operator's own sessions. The
// registry is the single source of truth for which sessions are listed and for
// their directory, tag, created/recency, so a pipeline stage session (recorded
// in run_steps, never in the operator registry) is always excluded and a session
// with no recorded tag is never listed. FAIL-CLOSED: when no registry is
// configured the result is empty, never the whole endpoint list. broker.Sessions
// is called at most once per request, and the registry once. A session is never
// marked Busy: any number of clients may watch and write one session.
func handleChatSessions(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
response := protocol.Message{Type: protocol.ChatSessions, ID: request.ID}
// No registry (no store and no injection): list nothing rather than the whole
// OpenCode machine.
if registry == nil {
_ = write(response)
return
}
operatorSessions, err := registry.OperatorSessions(ctx)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
// OperatorSessions is already most-recently-used first with a deterministic
// tie-break; keep that order and only include a registry session the broker
// still reports, so a session the operator deleted upstream is not listed.
registered := make(map[string]struct{}, len(operatorSessions))
for _, session := range operatorSessions {
if session.ID != "" {
registered[session.ID] = struct{}{}
}
}
sessions, err := broker.Sessions(ctx)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
present := make(map[string]protocol.ChatSession, len(sessions))
for _, session := range sessions {
if _, ok := registered[session.ID]; ok {
present[session.ID] = session
}
}
for _, operator := range operatorSessions {
session, ok := present[operator.ID]
if !ok {
continue
}
if operator.Title != "" {
session.Title = operator.Title
}
session.Directory = operator.Directory
session.Tag = operator.Tag
session.Backend = operator.Backend
session.CreatedAt = operator.CreatedAt
session.UpdatedAt = operator.UpdatedAt
// The closed state comes from the registry, so every client sees the same
// thing; a closed session stays in the list (the app groups it as history)
// rather than disappearing. A session is never marked Busy: any number of
// clients may watch and write one session.
session.Closed = operator.ClosedAt > 0
session.ClosedAt = operator.ClosedAt
session.Starred = operator.StarredAt > 0
session.StarredAt = operator.StarredAt
response.ChatSessions = append(response.ChatSessions, session)
}
_ = write(response)
}
// handleChatCreate creates one operator session in a resolved directory and
// records it in the operator registry: the OpenCode session id, the exact
// resolved directory, the title and the operator tag. A blank or omitted
// directory defaults to the operator's home, never the server's working
// directory. A registry write failure answers an error naming the created id, so
// an orphaned session is visible rather than silently reported as success. A
// request with Ephemeral set creates the session without any registry row, for
// automated verification that must never add a chat to the operator's list.
func handleChatCreate(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
title := ""
directory := ""
operationID := ""
backend := "opencode"
ephemeral := false
if request.ChatCreate != nil {
title = strings.TrimSpace(request.ChatCreate.Title)
directory = strings.TrimSpace(request.ChatCreate.Directory)
operationID = strings.TrimSpace(request.ChatCreate.OperationID)
if value := strings.TrimSpace(request.ChatCreate.Backend); value != "" {
backend = value
}
ephemeral = request.ChatCreate.Ephemeral
}
// Legacy clients did not carry a durable create identity. Give each received
// request its own server-generated scope so their connection-local envelope
// IDs (for example cli-1) cannot collide globally. Such requests cannot be
// retried exactly once across reconnects because they supplied no key.
if operationID == "" {
operationID = chatClientToken()
}
if title == "" {
title = "New chat"
}
resolved, err := resolveChatDirectory(directory)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
bootstrap, err := registry.BeginChatCreate(ctx, operationID, title, resolved)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
session := protocol.ChatSession{ID: bootstrap.SessionID, Title: title, Directory: resolved}
if session.ID == "" {
if bootstrap.State != "created" {
chatCreateBootstrapError(request, session.ID, bootstrap.State, write)
return
}
// The conditional transition is the durable reservation for the external
// Create call. A duplicate request that lost it must not create an orphan.
if err := registry.AdvanceChatCreate(ctx, operationID, "created", "creating"); err != nil {
chatCreateConflictError(request, err, write)
return
}
if creator, ok := broker.(chatCreateBackend); ok {
session, err = creator.CreateBackend(ctx, title, resolved, backend)
} else {
if backend != "opencode" {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat backend " + backend + " is not available"})
return
}
session, err = broker.Create(ctx, title, resolved)
}
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
if err := registry.SetChatCreateSession(ctx, operationID, session.ID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but durable bootstrap state could not be saved: " + err.Error()})
return
}
if err := registry.AdvanceChatCreate(ctx, operationID, "creating", "created"); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but durable bootstrap state could not advance: " + err.Error()})
return
}
bootstrap.State = "created"
}
if bootstrap.State == "created" {
// 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.
if err := registry.AdvanceChatCreate(ctx, operationID, "created", "activating"); err != nil {
chatCreateConflictError(request, err, write)
return
}
if err := broker.ActivateSkill(ctx, session.ID, "pipelines-manager"); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but manager bootstrap failed while activating pipelines-manager: " + err.Error()})
return
}
if err := registry.AdvanceChatCreate(ctx, operationID, "activating", "activated"); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " activated but durable bootstrap state could not be saved: " + err.Error()})
return
}
bootstrap.State = "activated"
}
if bootstrap.State == "creating" || bootstrap.State == "activating" || bootstrap.State == "recording" {
chatCreateBootstrapError(request, session.ID, bootstrap.State, write)
return
}
if bootstrap.State == "activated" {
if err := registry.AdvanceChatCreate(ctx, operationID, "activated", "recording"); err != nil {
chatCreateConflictError(request, err, write)
return
}
// An ephemeral (verification) create records a real but hidden row: the chat
// stays usable and closable, and chat_sessions never lists it. Everything
// else about the session — its id, skill activation and use — is identical.
record := registry.RecordOperatorSession
if ephemeral {
record = registry.RecordVerificationSession
}
if err := record(ctx, session.ID, resolved, title, protocol.ChatSessionTagOperator); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()})
return
}
if err := registry.SetOperatorSessionBackend(ctx, session.ID, backend); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was recorded but its backend could not be saved: " + err.Error()})
return
}
if err := registry.AdvanceChatCreate(ctx, operationID, "recording", "recorded"); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was recorded but durable bootstrap state could not be saved: " + err.Error()})
return
}
} else if bootstrap.State != "recorded" {
chatCreateBootstrapError(request, session.ID, bootstrap.State, write)
return
}
session.Directory = resolved
session.Tag = protocol.ChatSessionTagOperator
session.Backend = backend
response := protocol.Message{Type: protocol.ChatCreate, ID: request.ID, ChatSession: &session}
// The same registry row is echoed on the list field so a client can splice it
// into chat_sessions without a re-list. An ephemeral create has no listed row
// to splice, so that field stays empty and the client that asked for it opens
// the session from the echoed ChatSession instead.
if !ephemeral {
response.ChatSessions = []protocol.ChatSession{session}
}
_ = write(response)
}
func chatCreateConflictError(request protocol.Message, err error, write func(protocol.Message) error) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat_create bootstrap ownership/state conflict: " + err.Error()})
}
func chatCreateBootstrapError(request protocol.Message, sessionID, state string, write func(protocol.Message) error) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " has an unfinished manager bootstrap (" + state + "); it will not be repeated automatically"})
}
// handleChatAdopt records a session that already exists on the endpoint in the
// operator registry, using the endpoint's own directory and title verbatim, so
// it appears in chat_sessions and can be continued. It refuses a nil broker, a
// nil registry, a nil payload and an invalid/blank id before any broker call; an
// id the endpoint does not report is an error naming the id and records nothing;
// an endpoint record with an empty directory is refused rather than substituting
// the server's working directory or the operator home. The response echoes the
// adopted session and its registry row like chat_create.
func handleChatAdopt(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
if request.ChatAdopt == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat_adopt session id is required"})
return
}
id := strings.TrimSpace(request.ChatAdopt.SessionID)
if !validChatSessionID(id) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
session, found, err := broker.Session(ctx, id)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
if !found {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + id + " was not found on the OpenCode endpoint"})
return
}
directory := strings.TrimSpace(session.Directory)
if directory == "" {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + id + " has no directory on the OpenCode endpoint"})
return
}
if err := registry.RecordOperatorSession(ctx, session.ID, directory, session.Title, protocol.ChatSessionTagOperator); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was found but could not be recorded: " + err.Error()})
return
}
session.Directory = directory
session.Tag = protocol.ChatSessionTagOperator
response := protocol.Message{Type: protocol.ChatAdopt, ID: request.ID, ChatSession: &session}
// The same registry row is echoed on the list field so a client can splice it
// into chat_sessions without a re-list.
response.ChatSessions = []protocol.ChatSession{session}
_ = write(response)
}
// handleChatDirectories answers chat_directories with the operator's home first,
// then the directories of previous operator sessions most-recently-used first,
// deduplicated against the home directory and capped at operatorDirectoryLimit.
func handleChatDirectories(ctx context.Context, request protocol.Message, registry operatorRegistry, write func(protocol.Message) error) {
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
home, err := OperatorHomeDirectory()
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
directories := []string{home}
seen := map[string]struct{}{home: {}}
recent, err := registry.OperatorDirectories(ctx, operatorDirectoryLimit)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
for _, directory := range recent {
if len(directories) >= operatorDirectoryLimit {
break
}
if directory == "" {
continue
}
if _, ok := seen[directory]; ok {
continue
}
seen[directory] = struct{}{}
directories = append(directories, directory)
}
_ = write(protocol.Message{Type: protocol.ChatDirectories, ID: request.ID, ChatDirectories: directories})
}
// resolveChatDirectory resolves a chat_create directory to an absolute path: an
// omitted/empty value, "~" or a "~/..." value resolves to the operator's home
// (os.UserHomeDir) and never the server's working directory; any other value
// must be an absolute, existing directory, so a relative path cannot silently
// create a session relative to wherever the server was started.
func resolveChatDirectory(directory string) (string, error) {
directory = strings.TrimSpace(directory)
if directory == "" || directory == "~" || strings.HasPrefix(directory, "~/") {
return OperatorHomeDirectory()
}
if !filepath.IsAbs(directory) {
return "", errors.New("chat directory must be absolute or start with ~")
}
info, err := os.Stat(directory)
if err != nil {
return "", errors.New("chat directory " + directory + " is not available: " + err.Error())
}
if !info.IsDir() {
return "", errors.New("chat directory " + directory + " is not a directory")
}
return directory, nil
}
// OperatorHomeDirectory returns the operator's home directory, the default chat
// location. It is resolved through the standard library so it never falls back
// to the process working directory.
func OperatorHomeDirectory() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", errors.New("resolve operator home directory: " + err.Error())
}
if home == "" {
return "", errors.New("operator home directory is empty")
}
return home, nil
}