Files
pipelines/internal/server/chat.go
T
alan e42f9cc031 Send mid-turn chat prompts to the harness and queue the rest durably on the server
Claude Code (stream-json stdin) and Codex (turn/steer pinned to the active
turn) receive a prompt sent while a turn runs immediately. Other harnesses
(OpenCode) get a durable chat_prompt_queue row owned by the session: it
survives the last client detaching and a server restart, is delivered in
order when the turn ends with or without a client, and is deduplicated by
operation id. chat_subscribe carries the queue, chat_queue frames report
delivered/removed/failed changes, and chat_unqueue removes a waiting prompt.
2026-11-01 18:30:20 +00:00

236 lines
11 KiB
Go

package server
import (
"context"
"crypto/rand"
"encoding/hex"
"git.a-wan.net/alan/pipelines/internal/opencode"
"regexp"
"strconv"
"sync/atomic"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatBroker is the server-side OpenCode chat seam. *opencode.Chat implements
// it; tests substitute a scripted broker. Keeping it an interface means the
// /connect handler never builds a second OpenCode transport.
type chatBroker interface {
Prompt(ctx context.Context, sessionID, text string) error
// Stream subscribes to the session's OpenCode event stream. ready is called
// once the subscription is attached, before any frame is read, so the caller
// can order the prompt after the subscription.
Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error
Interrupt(ctx context.Context, sessionID string) error
Messages(ctx context.Context, sessionID string, limit int, cursor string) (protocol.ChatHistoryPage, error)
// Sessions lists the endpoint's OpenCode sessions so the handler can
// restrict them to the operator's own recorded sessions.
Sessions(ctx context.Context) ([]protocol.ChatSession, error)
// Create creates one OpenCode session in the given directory and returns it.
Create(ctx context.Context, title, directory string) (protocol.ChatSession, error)
// ActivateSkill explicitly attaches a registered OpenCode skill before a chat can receive its first prompt.
ActivateSkill(ctx context.Context, sessionID, skill string) error
// Session returns the endpoint's own record of one existing session so an
// adopted session carries the endpoint's directory and title; found is false
// when the endpoint does not list sessionID.
Session(ctx context.Context, sessionID string) (protocol.ChatSession, bool, error)
// Permissions lists the session's pending OpenCode approval requests so the
// handler can push chat_permission frames.
Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error)
// Shells returns only shell operations whose ownership is authoritatively
// verified for sessionID. It is the reconnect/readback source.
Shells(ctx context.Context, sessionID string) ([]protocol.ChatShell, error)
Reply(ctx context.Context, request protocol.ChatReplyRequest) error
}
type chatPromptWithMessageID interface {
PromptWithMessageID(context.Context, string, string, string) error
}
// chatPromptWithFiles is implemented by a broker that can hand local files to
// the agent with a prompt. The server writes browser attachment bytes to private
// temporary files first; a browser URI is not readable by the agent service.
type chatPromptWithFiles interface {
PromptWithMessageIDFiles(context.Context, string, string, string, []opencode.PromptFile) error
}
// chatInstructioner is the optional preloaded-behavior surface. OpenCode
// implements session instruction entries; a harness without them still creates
// the chat without instructions.
type chatInstructioner interface {
SetInstruction(ctx context.Context, sessionID, key string, value any) error
}
// chatModeler is the optional model-selection surface. OpenCode implements it;
// a harness without a model switch reports that clearly rather than pretending.
type chatModeler interface {
Models(ctx context.Context, sessionID string) ([]protocol.ChatModel, error)
SwitchModel(ctx context.Context, sessionID, provider, model string) error
}
// chatAnswerer is the optional form-answer surface. Test brokers and older
// backends need not implement it; a broker that does not answers chat_answer
// with a clear error rather than pretending the question was delivered.
type chatAnswerer interface {
Answer(context.Context, protocol.ChatAnswerRequest) error
}
type chatFormReader interface {
Forms(context.Context, string) ([]protocol.ChatForm, error)
}
type chatShellOutputReader interface {
ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error)
}
// chatShellReleaser is implemented by brokers that retain verified shell ids for
// attributing exit events. The hub calls it only after the last observer leaves
// a room; a later attach obtains a fresh authoritative snapshot.
// This is a bounded local-cache operation: it must not perform I/O or call the
// hub, which serializes it with room replacement under its mutex.
type chatShellReleaser interface {
ReleaseShells(sessionID string)
}
// chatTurnReporter is implemented by a broker that knows, without I/O, whether
// a session's turn is in flight in the harness itself. The hub's room forgets a
// turn when its last client leaves (a page reload), and a harness such as Claude
// Code does not replay a step-started frame to a new stream, so chat_subscribe
// asks the broker before deciding whether to replay the live marker.
type chatTurnReporter interface {
TurnRunning(sessionID string) bool
}
// operatorRegistry is the server-side operator-session seam. *pipeline.Store
// satisfies it. It is a table of its own, separate from the pipeline stage
// ownership (SessionOwner/run_session_owners) that settles a run: chat_sessions
// lists operator sessions only and never consults stage ownership.
type operatorRegistry interface {
BeginChatCreate(ctx context.Context, requestID, title, directory string) (pipeline.ChatCreateBootstrap, error)
SetChatCreateSession(ctx context.Context, requestID, sessionID string) error
AdvanceChatCreate(ctx context.Context, requestID, from, to string) error
RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error
// RecordVerificationSession records a chat created for automated verification:
// a real, closable row that OperatorSessions never lists.
RecordVerificationSession(ctx context.Context, sessionID, directory, title, tag string) error
TouchOperatorSession(ctx context.Context, sessionID string) error
OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error)
OperatorDirectories(ctx context.Context, limit int) ([]string, error)
// OperatorSession returns one recorded operator session by id (found false
// when the id is not an operator session), so chat_close/chat_reopen can echo
// the updated row and refuse a session that is not theirs.
OperatorSession(ctx context.Context, sessionID string) (pipeline.OperatorSession, bool, error)
// CloseOperatorSession records the closed state; ReopenOperatorSession clears
// it. Neither deletes anything, and neither touches a pipeline-owned run
// session (which has no operator_sessions row).
CloseOperatorSession(ctx context.Context, sessionID string) error
ReopenOperatorSession(ctx context.Context, sessionID string) error
SetOperatorSessionStar(ctx context.Context, sessionID string, starred bool) error
SetOperatorSessionTitle(ctx context.Context, sessionID, title string) error
SetOperatorSessionBackend(ctx context.Context, sessionID, backend string) error
}
// validChatSessionID accepts the opaque id shapes of the supported harnesses
// (OpenCode ses_…, Codex/Claude UUIDs). The owning adapter still validates the
// exact shape before any provider call; this only rejects clearly unsafe ids.
var chatSessionIDPattern = regexp.MustCompile(`^(?:ses_[A-Za-z0-9_]+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$`)
func validChatSessionID(id string) bool {
return len(id) <= 200 && chatSessionIDPattern.MatchString(id)
}
var chatTokenSequence atomic.Uint64
// chatClientToken returns an unguessable per-connection identity. Its only role
// is to key a connection's chat-room subscriptions and to exclude the sender from
// its own fan-out; it carries no ownership. A fresh token per connection means a
// reconnected client is a new identity and simply reattaches.
func chatClientToken() string {
var b [8]byte
if _, err := rand.Read(b[:]); err != nil {
return "conn-fallback-" + strconv.FormatUint(chatTokenSequence.Add(1), 10)
}
return "conn-" + hex.EncodeToString(b[:])
}
// handleChat dispatches one chat_* request. It returns true when the request was
// a chat type and has been fully answered (the caller must not fall through to
// the generic response). Frames are pushed after the ack, each through the
// connection-scoped write function so the read loop and the stream goroutine
// never interleave partial websocket writes.
func handleChat(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) bool {
switch request.Type {
case protocol.ChatPrompt:
handleChatPrompt(ctx, request, broker, hub, registry, clientID, write)
return true
case protocol.ChatSubscribe:
handleChatSubscribe(request, broker, hub, clientID, write)
return true
case protocol.ChatUnqueue:
handleChatUnqueue(ctx, request, hub, write)
return true
case protocol.ChatMessages:
handleChatMessages(ctx, request, broker, hub, write)
return true
case protocol.ChatInterrupt:
handleChatSimple(ctx, request, broker, hub, write)
return true
case protocol.ChatReply:
handleChatSimple(ctx, request, broker, hub, write)
return true
case protocol.ChatAnswer:
handleChatAnswer(ctx, request, broker, write)
return true
case protocol.ChatSessions:
handleChatSessions(ctx, request, broker, hub, registry, write)
return true
case protocol.ChatCreate:
handleChatCreate(ctx, request, broker, registry, write)
return true
case protocol.ChatAdopt:
handleChatAdopt(ctx, request, broker, registry, write)
return true
case protocol.ChatDirectories:
handleChatDirectories(ctx, request, registry, write)
return true
case protocol.ChatClose:
handleChatClose(ctx, request, broker, hub, registry, write)
return true
case protocol.ChatReopen:
handleChatReopen(ctx, request, registry, write)
return true
case protocol.ChatStar:
handleChatStar(ctx, request, registry, write)
return true
case protocol.ChatRename:
handleChatRename(ctx, request, registry, write)
return true
case protocol.ChatBackends:
handleChatBackends(request, broker, write)
return true
case protocol.ChatModels:
handleChatModels(ctx, request, broker, write)
return true
case protocol.ChatModelSelect:
handleChatModelSwitch(ctx, request, broker, write)
return true
case protocol.ChatModes:
handleChatModes(ctx, request, broker, write)
return true
case protocol.ChatModeSelect:
handleChatModeSwitch(ctx, request, broker, write)
return true
case protocol.ChatShells:
handleChatShells(ctx, request, broker, registry, write)
return true
case protocol.ChatShellOutput:
handleChatShellOutput(ctx, request, broker, registry, write)
return true
case protocol.ChatAttachmentImage:
handleChatAttachmentImage(request, broker, write)
return true
}
return false
}