Split chat/model/run files by concern (pure move)
Pure move: split the three multi-feature server files into per-concern files, with no behaviour change - same package, same exported and unexported identifiers, same call graph, same tests. - internal/server/chat.go -> chat.go (broker seam, client token, dispatcher), chat_hub.go, chat_claims.go, chat_permissions.go, chat_sessions.go, chat_stream.go, chat_commands.go - internal/stage/model.go -> model.go, model_run.go, model_failure.go, model_validation.go - internal/pipeline/runs.go -> runs.go (read side), runs_schema.go, runs_create.go, runs_mutate.go, runs_sessions.go Checked before committing: - Packaged templates and internal/author/skill/references: neither refers to internal/server/chat.go, internal/stage/model.go or internal/pipeline/runs.go, so nothing there needed updating (the change is a move with no behaviour change). - gofmt -l on the three packages: clean. go build ./..., go vet ./... and go test ./... pass. go.mod/go.sum unchanged. - No test, docs, android/, install or Docker files touched. Known stale path pointers deliberately left to the single docs writer (shared docs) and out of scope (android/): docs/chat-verification.md and android/README.md name the old file paths.
This commit is contained in:
@@ -4,15 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
@@ -54,32 +46,6 @@ type operatorRegistry interface {
|
||||
OperatorDirectories(ctx context.Context, limit int) ([]string, error)
|
||||
}
|
||||
|
||||
// chatPermissionPollInterval is the fixed interval between permission polls: one
|
||||
// GET per poll through the shared Connection bounds, never a busy loop. The first
|
||||
// poll runs immediately so a request pending when the prompt is sent is surfaced
|
||||
// without waiting a full interval.
|
||||
const chatPermissionPollInterval = 2 * time.Second
|
||||
|
||||
// chatPermissionRetainedLimit bounds the dedup set of already-pushed permission
|
||||
// request ids one session retains, so a long turn cannot grow it without limit.
|
||||
const chatPermissionRetainedLimit = 256
|
||||
|
||||
// chatRetainedLimit bounds the state one session may retain so a stalled reader
|
||||
// or a runaway turn cannot grow memory without limit. It matches the OpenCode
|
||||
// response bound (1 MiB).
|
||||
const chatRetainedLimit = opencode.MaxResponse
|
||||
|
||||
// chatMaxTurns bounds how many sessions retain turn state. A long-lived server
|
||||
// cannot accumulate state for every session ever prompted, so the
|
||||
// least-recently-updated turn is evicted once the cap is exceeded.
|
||||
const chatMaxTurns = 128
|
||||
|
||||
// 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
|
||||
|
||||
// chatClientToken returns an unguessable per-connection identity. It attributes
|
||||
// a session claim so two clients on the same server cannot silently write the
|
||||
// same conversation; a fresh token per connection means a reconnected client is
|
||||
@@ -92,367 +58,6 @@ func chatClientToken() string {
|
||||
return "conn-" + hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// chatHub retains the accumulated turn state per session, independently of any
|
||||
// single connection, so a reconnecting client can re-sync what it missed. State
|
||||
// is keyed by session and then by message id (a session holds many turns), and
|
||||
// is capped at chatRetainedLimit.
|
||||
type chatHub struct {
|
||||
mu sync.Mutex
|
||||
turns map[string]*chatTurn
|
||||
now func() time.Time
|
||||
// claims maps a session to the client currently writing it so a second
|
||||
// client is rejected; claimOrder bounds the map like chatMaxTurns.
|
||||
claims map[string]string
|
||||
claimOrder []string
|
||||
}
|
||||
|
||||
// chatPart is the retained form of one part. Text and reasoning deltas append to
|
||||
// text (amortized O(1)); a tool frame replaces part outright.
|
||||
type chatPart struct {
|
||||
part protocol.ChatPart
|
||||
text []byte
|
||||
}
|
||||
|
||||
// chatMessage is one retained assistant turn. Its parts keep the exact ids the
|
||||
// supporting chat_event frames carried, so a resume preserves attribution.
|
||||
type chatMessage struct {
|
||||
id string
|
||||
order []string
|
||||
parts map[string]*chatPart
|
||||
}
|
||||
|
||||
type chatTurn struct {
|
||||
sessionID string
|
||||
order []string
|
||||
messages map[string]*chatMessage
|
||||
step *protocol.ChatStep
|
||||
usage *protocol.ChatUsage
|
||||
size int
|
||||
overflow bool
|
||||
updated time.Time
|
||||
// permissions holds the request ids already pushed to the client so a
|
||||
// repeated poll cannot push the same pending request twice; permissionOrder
|
||||
// bounds it to chatPermissionRetainedLimit.
|
||||
permissions map[string]struct{}
|
||||
permissionOrder []string
|
||||
}
|
||||
|
||||
func newChatHub() *chatHub {
|
||||
return &chatHub{turns: map[string]*chatTurn{}, now: time.Now}
|
||||
}
|
||||
|
||||
func (h *chatHub) clock() time.Time {
|
||||
if h.now != nil {
|
||||
return h.now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// apply folds one pushed frame into the retained state. Text and reasoning
|
||||
// deltas append to their message's part; a tool frame upserts the full part
|
||||
// (accounting for its whole size) so the latest lifecycle status, input,
|
||||
// content, metadata, error and time are retained under the frame's message id.
|
||||
// Step and usage frames update the session's latest progress.
|
||||
func (h *chatHub) apply(frame protocol.ChatEventFrame) {
|
||||
if frame.SessionID == "" {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turnLocked(frame.SessionID)
|
||||
switch frame.Kind {
|
||||
case protocol.ChatEventStep:
|
||||
turn.step = frame.Step
|
||||
return
|
||||
case protocol.ChatEventUsage:
|
||||
turn.usage = frame.Usage
|
||||
return
|
||||
}
|
||||
if frame.MessageID == "" {
|
||||
return
|
||||
}
|
||||
message := turn.messages[frame.MessageID]
|
||||
if message == nil {
|
||||
message = &chatMessage{id: frame.MessageID, parts: map[string]*chatPart{}}
|
||||
turn.order = append(turn.order, frame.MessageID)
|
||||
turn.messages[frame.MessageID] = message
|
||||
}
|
||||
switch frame.Kind {
|
||||
case protocol.ChatEventText, protocol.ChatEventReasoning:
|
||||
id := ""
|
||||
if frame.Part != nil {
|
||||
id = frame.Part.ID
|
||||
}
|
||||
if id == "" || frame.Delta == "" {
|
||||
return
|
||||
}
|
||||
if !turn.retain(len(frame.Delta)) {
|
||||
return
|
||||
}
|
||||
part, ok := message.parts[id]
|
||||
if !ok {
|
||||
part = &chatPart{part: protocol.ChatPart{Type: frame.Kind, ID: id}}
|
||||
message.order = append(message.order, id)
|
||||
message.parts[id] = part
|
||||
}
|
||||
part.text = append(part.text, frame.Delta...)
|
||||
case protocol.ChatEventTool:
|
||||
if frame.Part == nil || frame.Part.ID == "" || turn.overflow {
|
||||
return
|
||||
}
|
||||
// The tool part is retained whole, so size the complete part (input,
|
||||
// content, metadata, error and time) and charge the difference against
|
||||
// the cap on every upsert, not just the first-seen name.
|
||||
incoming := chatPartBytes(frame.Part)
|
||||
part, ok := message.parts[frame.Part.ID]
|
||||
if !ok {
|
||||
if !turn.retain(incoming) {
|
||||
return
|
||||
}
|
||||
part = &chatPart{}
|
||||
message.order = append(message.order, frame.Part.ID)
|
||||
message.parts[frame.Part.ID] = part
|
||||
} else if previous := chatPartBytes(&part.part); incoming > previous {
|
||||
if !turn.retain(incoming - previous) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
turn.shrink(previous - incoming)
|
||||
}
|
||||
part.part = *frame.Part
|
||||
}
|
||||
}
|
||||
|
||||
// chatPartBytes estimates the retained size of a part so the per-session cap
|
||||
// accounts for its whole state instead of only the first-seen name. It walks the
|
||||
// fields rather than re-marshalling, so the cost matches the bytes it stores.
|
||||
func chatPartBytes(part *protocol.ChatPart) int {
|
||||
if part == nil {
|
||||
return 0
|
||||
}
|
||||
n := len(part.Type) + len(part.ID) + len(part.Name)
|
||||
if part.State == nil {
|
||||
return n
|
||||
}
|
||||
n += len(part.State.Status) + len(part.State.Input)
|
||||
for _, content := range part.State.Content {
|
||||
n += len(content.Type) + len(content.Text) + len(content.URI) + len(content.Mime) + len(content.Name)
|
||||
}
|
||||
if part.State.Error != nil {
|
||||
n += len(part.State.Error.Type) + len(part.State.Error.Message)
|
||||
}
|
||||
for key, value := range part.State.Metadata {
|
||||
n += len(key)
|
||||
if text, ok := value.(string); ok {
|
||||
n += len(text)
|
||||
} else {
|
||||
n += 8
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// evictLocked drops the least-recently-updated turn when the session cap is
|
||||
// reached, keeping retained memory bounded across session churn.
|
||||
func (h *chatHub) evictLocked() {
|
||||
if len(h.turns) < chatMaxTurns {
|
||||
return
|
||||
}
|
||||
oldestID := ""
|
||||
var oldest time.Time
|
||||
for id, turn := range h.turns {
|
||||
if oldestID == "" || turn.updated.Before(oldest) {
|
||||
oldestID, oldest = id, turn.updated
|
||||
}
|
||||
}
|
||||
if oldestID != "" {
|
||||
delete(h.turns, oldestID)
|
||||
}
|
||||
}
|
||||
|
||||
// claim reserves sessionID for clientID. It reports true when the session is
|
||||
// free or already held by the same client (so a client may re-prompt its own
|
||||
// session) and false when another client holds it. The claim map is bounded by
|
||||
// chatMaxTurns with oldest-eviction so a stuck client cannot grow it without
|
||||
// limit.
|
||||
func (h *chatHub) claim(sessionID, clientID string) bool {
|
||||
if sessionID == "" || clientID == "" {
|
||||
return false
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.claims == nil {
|
||||
h.claims = map[string]string{}
|
||||
}
|
||||
if holder, ok := h.claims[sessionID]; ok {
|
||||
return holder == clientID
|
||||
}
|
||||
h.evictClaimsLocked()
|
||||
h.claims[sessionID] = clientID
|
||||
h.claimOrder = append(h.claimOrder, sessionID)
|
||||
return true
|
||||
}
|
||||
|
||||
// release drops the same client's claim on sessionID; a claim held by a
|
||||
// different client is left untouched so a stale release cannot free a live one.
|
||||
func (h *chatHub) release(sessionID, clientID string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if holder, ok := h.claims[sessionID]; !ok || holder != clientID {
|
||||
return
|
||||
}
|
||||
delete(h.claims, sessionID)
|
||||
for i, id := range h.claimOrder {
|
||||
if id == sessionID {
|
||||
h.claimOrder = append(h.claimOrder[:i], h.claimOrder[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// busyForOther reports whether another client currently holds sessionID.
|
||||
func (h *chatHub) busyForOther(sessionID, clientID string) bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
holder, ok := h.claims[sessionID]
|
||||
return ok && holder != clientID
|
||||
}
|
||||
|
||||
// evictClaimsLocked drops the oldest claim when the cap is reached, keeping the
|
||||
// claim map bounded like the retained turns. Callers must hold h.mu.
|
||||
func (h *chatHub) evictClaimsLocked() {
|
||||
if len(h.claims) < chatMaxTurns {
|
||||
return
|
||||
}
|
||||
for len(h.claimOrder) > 0 {
|
||||
oldest := h.claimOrder[0]
|
||||
h.claimOrder = h.claimOrder[1:]
|
||||
if _, ok := h.claims[oldest]; ok {
|
||||
delete(h.claims, oldest)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// turnLocked returns the session's retained turn, creating it (and evicting the
|
||||
// least-recently-updated turn first when the cap is reached) and refreshing its
|
||||
// update time. It is the shared turn-initialization path for apply and
|
||||
// seenPermission, so the two cannot drift. Callers must hold h.mu.
|
||||
func (h *chatHub) turnLocked(sessionID string) *chatTurn {
|
||||
turn := h.turns[sessionID]
|
||||
if turn == nil {
|
||||
h.evictLocked()
|
||||
turn = &chatTurn{sessionID: sessionID, messages: map[string]*chatMessage{}}
|
||||
h.turns[sessionID] = turn
|
||||
}
|
||||
turn.updated = h.clock()
|
||||
return turn
|
||||
}
|
||||
|
||||
// retain records n more bytes and reports whether the turn is still within the
|
||||
// bound. The first overflow records one diagnostic and then drops further state
|
||||
// instead of growing without limit.
|
||||
func (t *chatTurn) retain(n int) bool {
|
||||
if t.overflow {
|
||||
return false
|
||||
}
|
||||
if t.size+n > chatRetainedLimit {
|
||||
t.overflow = true
|
||||
log.Printf("chat session %s retained state exceeds %d bytes; dropping further state", t.sessionID, chatRetainedLimit)
|
||||
return false
|
||||
}
|
||||
t.size += n
|
||||
return true
|
||||
}
|
||||
|
||||
// shrink releases n bytes when a tool upsert replaces a larger retained part.
|
||||
func (t *chatTurn) shrink(n int) {
|
||||
t.size -= n
|
||||
if t.size < 0 {
|
||||
t.size = 0
|
||||
}
|
||||
}
|
||||
|
||||
// snapshot returns the accumulated session as one assistant message per
|
||||
// retained message id, with the same stable part ids, or nil when nothing is
|
||||
// retained. It is the resume source: a reconnecting client re-syncs the whole
|
||||
// session once instead of replaying deltas, and each turn keeps its own id.
|
||||
func (h *chatHub) snapshot(sessionID string) []protocol.ChatMessage {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turns[sessionID]
|
||||
if turn == nil {
|
||||
return nil
|
||||
}
|
||||
turn.updated = h.clock()
|
||||
var messages []protocol.ChatMessage
|
||||
for _, id := range turn.order {
|
||||
message := turn.messages[id]
|
||||
if message == nil || len(message.order) == 0 {
|
||||
continue
|
||||
}
|
||||
out := protocol.ChatMessage{ID: id, SessionID: sessionID, Role: protocol.ChatRoleAssistant}
|
||||
for _, partID := range message.order {
|
||||
if part, ok := message.parts[partID]; ok {
|
||||
piece := part.part
|
||||
piece.Text = string(part.text)
|
||||
out.Parts = append(out.Parts, piece)
|
||||
}
|
||||
}
|
||||
messages = append(messages, out)
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
// seenPermission records requestID as pushed for the session and reports whether
|
||||
// it is newly seen (true) or a duplicate (false). The retained ids are bounded:
|
||||
// the oldest is dropped once the session exceeds chatPermissionRetainedLimit, so
|
||||
// the same pending request is pushed at most once while the state stays bounded.
|
||||
func (h *chatHub) seenPermission(sessionID, requestID string) bool {
|
||||
if sessionID == "" || requestID == "" {
|
||||
return false
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turnLocked(sessionID)
|
||||
if turn.permissions == nil {
|
||||
turn.permissions = map[string]struct{}{}
|
||||
}
|
||||
if _, ok := turn.permissions[requestID]; ok {
|
||||
return false
|
||||
}
|
||||
turn.permissions[requestID] = struct{}{}
|
||||
turn.permissionOrder = append(turn.permissionOrder, requestID)
|
||||
if len(turn.permissionOrder) > chatPermissionRetainedLimit {
|
||||
oldest := turn.permissionOrder[0]
|
||||
turn.permissionOrder = turn.permissionOrder[1:]
|
||||
delete(turn.permissions, oldest)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// forgetPermission releases a request id reserved by seenPermission when its
|
||||
// frame could not be written, so a later poll re-pushes it instead of the id
|
||||
// staying "seen" while the phone never received the request.
|
||||
func (h *chatHub) forgetPermission(sessionID, requestID string) {
|
||||
if sessionID == "" || requestID == "" {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turns[sessionID]
|
||||
if turn == nil {
|
||||
return
|
||||
}
|
||||
delete(turn.permissions, requestID)
|
||||
for i, id := range turn.permissionOrder {
|
||||
if id == requestID {
|
||||
turn.permissionOrder = append(turn.permissionOrder[:i], turn.permissionOrder[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -487,498 +92,3 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// handleChatSessions answers chat_sessions with the operator's own sessions,
|
||||
// marking any another client currently holds as Busy. 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.
|
||||
func handleChatSessions(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, 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.CreatedAt = operator.CreatedAt
|
||||
session.UpdatedAt = operator.UpdatedAt
|
||||
session.Busy = hub.busyForOther(operator.ID, clientID)
|
||||
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.
|
||||
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 := ""
|
||||
if request.ChatCreate != nil {
|
||||
title = strings.TrimSpace(request.ChatCreate.Title)
|
||||
directory = strings.TrimSpace(request.ChatCreate.Directory)
|
||||
}
|
||||
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
|
||||
}
|
||||
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.RecordOperatorSession(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
|
||||
}
|
||||
session.Directory = resolved
|
||||
session.Tag = protocol.ChatSessionTagOperator
|
||||
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.
|
||||
response.ChatSessions = []protocol.ChatSession{session}
|
||||
_ = write(response)
|
||||
}
|
||||
|
||||
// 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 !opencode.ValidSessionID(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
|
||||
}
|
||||
|
||||
func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, 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
|
||||
}
|
||||
prompt := request.ChatPrompt
|
||||
if prompt == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat prompt payload is required"})
|
||||
return
|
||||
}
|
||||
if !opencode.ValidSessionID(prompt.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(prompt.Text) == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a nonempty chat prompt is required"})
|
||||
return
|
||||
}
|
||||
// Reject an oversized prompt before any OpenCode call; the bound matches the
|
||||
// OpenCode request limit.
|
||||
if len(prompt.Text) > opencode.MaxRequest {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat prompt exceeds 64 KiB"})
|
||||
return
|
||||
}
|
||||
// Claim the session before subscribing or prompting: a second client must be
|
||||
// rejected here, before any broker call, so two clients cannot silently write
|
||||
// the same conversation. The same client may re-prompt its own session.
|
||||
sessionID := prompt.SessionID
|
||||
if !hub.claim(sessionID, clientID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is busy with another client"})
|
||||
return
|
||||
}
|
||||
|
||||
// Subscribe to the OpenCode firehose before posting the prompt: the stream
|
||||
// has no replay cursor (research 2.4), so a delta emitted between the POST
|
||||
// and the subscription would otherwise be lost. Frames that arrive before the
|
||||
// ack is written are buffered and flushed in order after it.
|
||||
streamCtx, streamCancel := context.WithCancel(ctx)
|
||||
attached := make(chan struct{})
|
||||
var attachOnce sync.Once
|
||||
streamResult := make(chan error, 1)
|
||||
var bufferMu sync.Mutex
|
||||
buffering := true
|
||||
var buffered []protocol.ChatEventFrame
|
||||
go func() {
|
||||
streamResult <- broker.Stream(streamCtx, sessionID, func() {
|
||||
attachOnce.Do(func() { close(attached) })
|
||||
}, func(frame protocol.ChatEventFrame) error {
|
||||
bufferMu.Lock()
|
||||
if buffering {
|
||||
buffered = append(buffered, frame)
|
||||
bufferMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
bufferMu.Unlock()
|
||||
hub.apply(frame)
|
||||
return write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame})
|
||||
})
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-attached:
|
||||
case err := <-streamResult:
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat stream: " + err.Error()})
|
||||
}
|
||||
return
|
||||
case <-ctx.Done():
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
return
|
||||
}
|
||||
|
||||
if err := broker.Prompt(ctx, sessionID, prompt.Text); err != nil {
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
// Recency is one UPDATE: it moves the operator session to the front of
|
||||
// chat_sessions. A session id that is not an operator session updates no row
|
||||
// and is not an error, so pipeline stage prompts are unaffected.
|
||||
if registry != nil {
|
||||
if err := registry.TouchOperatorSession(ctx, sessionID); err != nil {
|
||||
log.Printf("touch operator session %s: %v", sessionID, err)
|
||||
}
|
||||
}
|
||||
// Acknowledge the accepted prompt with the echoed request id, then stream the
|
||||
// reply. The prompt is sent exactly once and never re-sent on resume.
|
||||
if err := write(protocol.Message{Type: protocol.ChatPrompt, ID: request.ID}); err != nil {
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
return
|
||||
}
|
||||
// Flush frames buffered while the prompt was accepted, then resume live
|
||||
// delivery. Holding bufferMu preserves order: the stream goroutine either
|
||||
// buffered before this flush or waits and writes after it.
|
||||
bufferMu.Lock()
|
||||
buffering = false
|
||||
pending := buffered
|
||||
buffered = nil
|
||||
for _, frame := range pending {
|
||||
hub.apply(frame)
|
||||
if err := write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}); err != nil {
|
||||
bufferMu.Unlock()
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
return
|
||||
}
|
||||
}
|
||||
bufferMu.Unlock()
|
||||
go drainChatStream(ctx, streamResult, streamCancel, hub, sessionID, clientID, write)
|
||||
// Poll for pending approval requests alongside the event stream, sharing
|
||||
// streamCtx so the poller stops when the stream ends or the client
|
||||
// disconnects. The first poll runs immediately.
|
||||
go pollChatPermissions(streamCtx, broker, hub, sessionID, write)
|
||||
}
|
||||
|
||||
// pollChatPermissions polls the broker's pending-approval list on a fixed
|
||||
// interval, sharing the chat subscription's context so it stops on disconnect or
|
||||
// when the turn's stream ends. The hub dedups the request ids, so each pending
|
||||
// request is pushed at most once; a poll failure is surfaced once through the
|
||||
// same write closure instead of staying silent. A backend that does not expose
|
||||
// the approval surface (opencode.ErrPermissionUnsupported) stops the poller
|
||||
// quietly, so the documented limitation is not reported as a per-prompt error.
|
||||
func pollChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) {
|
||||
ticker := time.NewTicker(chatPermissionPollInterval)
|
||||
defer ticker.Stop()
|
||||
reported := false
|
||||
for {
|
||||
if err := pushChatPermissions(ctx, broker, hub, sessionID, write); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, opencode.ErrPermissionUnsupported) {
|
||||
log.Printf("chat permission poll session=%s: %v", sessionID, err)
|
||||
return
|
||||
}
|
||||
if reported {
|
||||
log.Printf("chat permission poll session=%s: %v", sessionID, err)
|
||||
} else {
|
||||
reported = true
|
||||
_ = write(protocol.Message{Type: protocol.Error, Error: "chat permission poll: " + err.Error()})
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pushChatPermissions performs one poll and writes a chat_permission frame for
|
||||
// every newly seen request of the session, through the same connection-scoped
|
||||
// write closure as the chat stream. It never re-pushes a request id, and releases
|
||||
// the reservation on a write failure so the frame is not silently dropped.
|
||||
func pushChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) error {
|
||||
pending, err := broker.Permissions(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, request := range pending {
|
||||
if request.SessionID != sessionID || request.RequestID == "" {
|
||||
continue
|
||||
}
|
||||
if !hub.seenPermission(sessionID, request.RequestID) {
|
||||
continue
|
||||
}
|
||||
frame := request
|
||||
if err := write(protocol.Message{Type: protocol.ChatPermission, ChatPermission: &frame}); err != nil {
|
||||
hub.forgetPermission(sessionID, request.RequestID)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// drainChatStream reports the terminal error of a chat subscription and releases
|
||||
// its context and the session claim once the stream has ended, so a later client
|
||||
// is no longer blocked and nothing leaks.
|
||||
func drainChatStream(ctx context.Context, result <-chan error, cancel context.CancelFunc, hub *chatHub, sessionID, clientID string, write func(protocol.Message) error) {
|
||||
defer cancel()
|
||||
defer hub.release(sessionID, clientID)
|
||||
if err := <-result; err != nil && ctx.Err() == nil {
|
||||
log.Printf("chat stream session=%s: %v", sessionID, err)
|
||||
_ = write(protocol.Message{Type: protocol.Error, Error: "chat stream: " + err.Error()})
|
||||
}
|
||||
}
|
||||
|
||||
func handleChatMessages(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, write func(protocol.Message) error) {
|
||||
query := request.ChatQuery
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
response := protocol.Message{Type: protocol.ChatMessages, ID: request.ID}
|
||||
// Resume from retained server state first: a reconnecting client gets the
|
||||
// accumulated turns with the same stable ids without re-reading OpenCode.
|
||||
if messages := hub.snapshot(query.SessionID); len(messages) > 0 {
|
||||
response.ChatMessages = messages
|
||||
_ = write(response)
|
||||
return
|
||||
}
|
||||
if broker == nil {
|
||||
_ = write(response)
|
||||
return
|
||||
}
|
||||
messages, err := broker.Messages(ctx, query.SessionID, query.Limit)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
response.ChatMessages = messages
|
||||
_ = write(response)
|
||||
}
|
||||
|
||||
func handleChatSimple(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, 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 request.Type == protocol.ChatInterrupt {
|
||||
query := request.ChatQuery
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
if err := broker.Interrupt(ctx, query.SessionID); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatInterrupt, ID: request.ID})
|
||||
return
|
||||
}
|
||||
reply := request.ChatReply
|
||||
if reply == nil || !opencode.ValidSessionID(reply.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(reply.RequestID) == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a permission request id is required"})
|
||||
return
|
||||
}
|
||||
switch reply.Decision {
|
||||
case protocol.ChatDecisionOnce, protocol.ChatDecisionAlways, protocol.ChatDecisionReject:
|
||||
default:
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid permission decision is required"})
|
||||
return
|
||||
}
|
||||
if err := broker.Reply(ctx, *reply); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatReply, ID: request.ID})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package server
|
||||
|
||||
// claim reserves sessionID for clientID. It reports true when the session is
|
||||
// free or already held by the same client (so a client may re-prompt its own
|
||||
// session) and false when another client holds it. The claim map is bounded by
|
||||
// chatMaxTurns with oldest-eviction so a stuck client cannot grow it without
|
||||
// limit.
|
||||
func (h *chatHub) claim(sessionID, clientID string) bool {
|
||||
if sessionID == "" || clientID == "" {
|
||||
return false
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.claims == nil {
|
||||
h.claims = map[string]string{}
|
||||
}
|
||||
if holder, ok := h.claims[sessionID]; ok {
|
||||
return holder == clientID
|
||||
}
|
||||
h.evictClaimsLocked()
|
||||
h.claims[sessionID] = clientID
|
||||
h.claimOrder = append(h.claimOrder, sessionID)
|
||||
return true
|
||||
}
|
||||
|
||||
// release drops the same client's claim on sessionID; a claim held by a
|
||||
// different client is left untouched so a stale release cannot free a live one.
|
||||
func (h *chatHub) release(sessionID, clientID string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if holder, ok := h.claims[sessionID]; !ok || holder != clientID {
|
||||
return
|
||||
}
|
||||
delete(h.claims, sessionID)
|
||||
for i, id := range h.claimOrder {
|
||||
if id == sessionID {
|
||||
h.claimOrder = append(h.claimOrder[:i], h.claimOrder[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// busyForOther reports whether another client currently holds sessionID.
|
||||
func (h *chatHub) busyForOther(sessionID, clientID string) bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
holder, ok := h.claims[sessionID]
|
||||
return ok && holder != clientID
|
||||
}
|
||||
|
||||
// evictClaimsLocked drops the oldest claim when the cap is reached, keeping the
|
||||
// claim map bounded like the retained turns. Callers must hold h.mu.
|
||||
func (h *chatHub) evictClaimsLocked() {
|
||||
if len(h.claims) < chatMaxTurns {
|
||||
return
|
||||
}
|
||||
for len(h.claimOrder) > 0 {
|
||||
oldest := h.claimOrder[0]
|
||||
h.claimOrder = h.claimOrder[1:]
|
||||
if _, ok := h.claims[oldest]; ok {
|
||||
delete(h.claims, oldest)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func handleChatMessages(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, write func(protocol.Message) error) {
|
||||
query := request.ChatQuery
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
response := protocol.Message{Type: protocol.ChatMessages, ID: request.ID}
|
||||
// Resume from retained server state first: a reconnecting client gets the
|
||||
// accumulated turns with the same stable ids without re-reading OpenCode.
|
||||
if messages := hub.snapshot(query.SessionID); len(messages) > 0 {
|
||||
response.ChatMessages = messages
|
||||
_ = write(response)
|
||||
return
|
||||
}
|
||||
if broker == nil {
|
||||
_ = write(response)
|
||||
return
|
||||
}
|
||||
messages, err := broker.Messages(ctx, query.SessionID, query.Limit)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
response.ChatMessages = messages
|
||||
_ = write(response)
|
||||
}
|
||||
|
||||
func handleChatSimple(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, 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 request.Type == protocol.ChatInterrupt {
|
||||
query := request.ChatQuery
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
if err := broker.Interrupt(ctx, query.SessionID); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatInterrupt, ID: request.ID})
|
||||
return
|
||||
}
|
||||
reply := request.ChatReply
|
||||
if reply == nil || !opencode.ValidSessionID(reply.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(reply.RequestID) == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a permission request id is required"})
|
||||
return
|
||||
}
|
||||
switch reply.Decision {
|
||||
case protocol.ChatDecisionOnce, protocol.ChatDecisionAlways, protocol.ChatDecisionReject:
|
||||
default:
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid permission decision is required"})
|
||||
return
|
||||
}
|
||||
if err := broker.Reply(ctx, *reply); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatReply, ID: request.ID})
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatRetainedLimit bounds the state one session may retain so a stalled reader
|
||||
// or a runaway turn cannot grow memory without limit. It matches the OpenCode
|
||||
// response bound (1 MiB).
|
||||
const chatRetainedLimit = opencode.MaxResponse
|
||||
|
||||
// chatMaxTurns bounds how many sessions retain turn state. A long-lived server
|
||||
// cannot accumulate state for every session ever prompted, so the
|
||||
// least-recently-updated turn is evicted once the cap is exceeded.
|
||||
const chatMaxTurns = 128
|
||||
|
||||
// chatHub retains the accumulated turn state per session, independently of any
|
||||
// single connection, so a reconnecting client can re-sync what it missed. State
|
||||
// is keyed by session and then by message id (a session holds many turns), and
|
||||
// is capped at chatRetainedLimit.
|
||||
type chatHub struct {
|
||||
mu sync.Mutex
|
||||
turns map[string]*chatTurn
|
||||
now func() time.Time
|
||||
// claims maps a session to the client currently writing it so a second
|
||||
// client is rejected; claimOrder bounds the map like chatMaxTurns.
|
||||
claims map[string]string
|
||||
claimOrder []string
|
||||
}
|
||||
|
||||
// chatPart is the retained form of one part. Text and reasoning deltas append to
|
||||
// text (amortized O(1)); a tool frame replaces part outright.
|
||||
type chatPart struct {
|
||||
part protocol.ChatPart
|
||||
text []byte
|
||||
}
|
||||
|
||||
// chatMessage is one retained assistant turn. Its parts keep the exact ids the
|
||||
// supporting chat_event frames carried, so a resume preserves attribution.
|
||||
type chatMessage struct {
|
||||
id string
|
||||
order []string
|
||||
parts map[string]*chatPart
|
||||
}
|
||||
|
||||
type chatTurn struct {
|
||||
sessionID string
|
||||
order []string
|
||||
messages map[string]*chatMessage
|
||||
step *protocol.ChatStep
|
||||
usage *protocol.ChatUsage
|
||||
size int
|
||||
overflow bool
|
||||
updated time.Time
|
||||
// permissions holds the request ids already pushed to the client so a
|
||||
// repeated poll cannot push the same pending request twice; permissionOrder
|
||||
// bounds it to chatPermissionRetainedLimit.
|
||||
permissions map[string]struct{}
|
||||
permissionOrder []string
|
||||
}
|
||||
|
||||
func newChatHub() *chatHub {
|
||||
return &chatHub{turns: map[string]*chatTurn{}, now: time.Now}
|
||||
}
|
||||
|
||||
func (h *chatHub) clock() time.Time {
|
||||
if h.now != nil {
|
||||
return h.now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// apply folds one pushed frame into the retained state. Text and reasoning
|
||||
// deltas append to their message's part; a tool frame upserts the full part
|
||||
// (accounting for its whole size) so the latest lifecycle status, input,
|
||||
// content, metadata, error and time are retained under the frame's message id.
|
||||
// Step and usage frames update the session's latest progress.
|
||||
func (h *chatHub) apply(frame protocol.ChatEventFrame) {
|
||||
if frame.SessionID == "" {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turnLocked(frame.SessionID)
|
||||
switch frame.Kind {
|
||||
case protocol.ChatEventStep:
|
||||
turn.step = frame.Step
|
||||
return
|
||||
case protocol.ChatEventUsage:
|
||||
turn.usage = frame.Usage
|
||||
return
|
||||
}
|
||||
if frame.MessageID == "" {
|
||||
return
|
||||
}
|
||||
message := turn.messages[frame.MessageID]
|
||||
if message == nil {
|
||||
message = &chatMessage{id: frame.MessageID, parts: map[string]*chatPart{}}
|
||||
turn.order = append(turn.order, frame.MessageID)
|
||||
turn.messages[frame.MessageID] = message
|
||||
}
|
||||
switch frame.Kind {
|
||||
case protocol.ChatEventText, protocol.ChatEventReasoning:
|
||||
id := ""
|
||||
if frame.Part != nil {
|
||||
id = frame.Part.ID
|
||||
}
|
||||
if id == "" || frame.Delta == "" {
|
||||
return
|
||||
}
|
||||
if !turn.retain(len(frame.Delta)) {
|
||||
return
|
||||
}
|
||||
part, ok := message.parts[id]
|
||||
if !ok {
|
||||
part = &chatPart{part: protocol.ChatPart{Type: frame.Kind, ID: id}}
|
||||
message.order = append(message.order, id)
|
||||
message.parts[id] = part
|
||||
}
|
||||
part.text = append(part.text, frame.Delta...)
|
||||
case protocol.ChatEventTool:
|
||||
if frame.Part == nil || frame.Part.ID == "" || turn.overflow {
|
||||
return
|
||||
}
|
||||
// The tool part is retained whole, so size the complete part (input,
|
||||
// content, metadata, error and time) and charge the difference against
|
||||
// the cap on every upsert, not just the first-seen name.
|
||||
incoming := chatPartBytes(frame.Part)
|
||||
part, ok := message.parts[frame.Part.ID]
|
||||
if !ok {
|
||||
if !turn.retain(incoming) {
|
||||
return
|
||||
}
|
||||
part = &chatPart{}
|
||||
message.order = append(message.order, frame.Part.ID)
|
||||
message.parts[frame.Part.ID] = part
|
||||
} else if previous := chatPartBytes(&part.part); incoming > previous {
|
||||
if !turn.retain(incoming - previous) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
turn.shrink(previous - incoming)
|
||||
}
|
||||
part.part = *frame.Part
|
||||
}
|
||||
}
|
||||
|
||||
// chatPartBytes estimates the retained size of a part so the per-session cap
|
||||
// accounts for its whole state instead of only the first-seen name. It walks the
|
||||
// fields rather than re-marshalling, so the cost matches the bytes it stores.
|
||||
func chatPartBytes(part *protocol.ChatPart) int {
|
||||
if part == nil {
|
||||
return 0
|
||||
}
|
||||
n := len(part.Type) + len(part.ID) + len(part.Name)
|
||||
if part.State == nil {
|
||||
return n
|
||||
}
|
||||
n += len(part.State.Status) + len(part.State.Input)
|
||||
for _, content := range part.State.Content {
|
||||
n += len(content.Type) + len(content.Text) + len(content.URI) + len(content.Mime) + len(content.Name)
|
||||
}
|
||||
if part.State.Error != nil {
|
||||
n += len(part.State.Error.Type) + len(part.State.Error.Message)
|
||||
}
|
||||
for key, value := range part.State.Metadata {
|
||||
n += len(key)
|
||||
if text, ok := value.(string); ok {
|
||||
n += len(text)
|
||||
} else {
|
||||
n += 8
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// evictLocked drops the least-recently-updated turn when the session cap is
|
||||
// reached, keeping retained memory bounded across session churn.
|
||||
func (h *chatHub) evictLocked() {
|
||||
if len(h.turns) < chatMaxTurns {
|
||||
return
|
||||
}
|
||||
oldestID := ""
|
||||
var oldest time.Time
|
||||
for id, turn := range h.turns {
|
||||
if oldestID == "" || turn.updated.Before(oldest) {
|
||||
oldestID, oldest = id, turn.updated
|
||||
}
|
||||
}
|
||||
if oldestID != "" {
|
||||
delete(h.turns, oldestID)
|
||||
}
|
||||
}
|
||||
|
||||
// turnLocked returns the session's retained turn, creating it (and evicting the
|
||||
// least-recently-updated turn first when the cap is reached) and refreshing its
|
||||
// update time. It is the shared turn-initialization path for apply and
|
||||
// seenPermission, so the two cannot drift. Callers must hold h.mu.
|
||||
func (h *chatHub) turnLocked(sessionID string) *chatTurn {
|
||||
turn := h.turns[sessionID]
|
||||
if turn == nil {
|
||||
h.evictLocked()
|
||||
turn = &chatTurn{sessionID: sessionID, messages: map[string]*chatMessage{}}
|
||||
h.turns[sessionID] = turn
|
||||
}
|
||||
turn.updated = h.clock()
|
||||
return turn
|
||||
}
|
||||
|
||||
// retain records n more bytes and reports whether the turn is still within the
|
||||
// bound. The first overflow records one diagnostic and then drops further state
|
||||
// instead of growing without limit.
|
||||
func (t *chatTurn) retain(n int) bool {
|
||||
if t.overflow {
|
||||
return false
|
||||
}
|
||||
if t.size+n > chatRetainedLimit {
|
||||
t.overflow = true
|
||||
log.Printf("chat session %s retained state exceeds %d bytes; dropping further state", t.sessionID, chatRetainedLimit)
|
||||
return false
|
||||
}
|
||||
t.size += n
|
||||
return true
|
||||
}
|
||||
|
||||
// shrink releases n bytes when a tool upsert replaces a larger retained part.
|
||||
func (t *chatTurn) shrink(n int) {
|
||||
t.size -= n
|
||||
if t.size < 0 {
|
||||
t.size = 0
|
||||
}
|
||||
}
|
||||
|
||||
// snapshot returns the accumulated session as one assistant message per
|
||||
// retained message id, with the same stable part ids, or nil when nothing is
|
||||
// retained. It is the resume source: a reconnecting client re-syncs the whole
|
||||
// session once instead of replaying deltas, and each turn keeps its own id.
|
||||
func (h *chatHub) snapshot(sessionID string) []protocol.ChatMessage {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turns[sessionID]
|
||||
if turn == nil {
|
||||
return nil
|
||||
}
|
||||
turn.updated = h.clock()
|
||||
var messages []protocol.ChatMessage
|
||||
for _, id := range turn.order {
|
||||
message := turn.messages[id]
|
||||
if message == nil || len(message.order) == 0 {
|
||||
continue
|
||||
}
|
||||
out := protocol.ChatMessage{ID: id, SessionID: sessionID, Role: protocol.ChatRoleAssistant}
|
||||
for _, partID := range message.order {
|
||||
if part, ok := message.parts[partID]; ok {
|
||||
piece := part.part
|
||||
piece.Text = string(part.text)
|
||||
out.Parts = append(out.Parts, piece)
|
||||
}
|
||||
}
|
||||
messages = append(messages, out)
|
||||
}
|
||||
return messages
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package server
|
||||
|
||||
// chatPermissionRetainedLimit bounds the dedup set of already-pushed permission
|
||||
// request ids one session retains, so a long turn cannot grow it without limit.
|
||||
const chatPermissionRetainedLimit = 256
|
||||
|
||||
// seenPermission records requestID as pushed for the session and reports whether
|
||||
// it is newly seen (true) or a duplicate (false). The retained ids are bounded:
|
||||
// the oldest is dropped once the session exceeds chatPermissionRetainedLimit, so
|
||||
// the same pending request is pushed at most once while the state stays bounded.
|
||||
func (h *chatHub) seenPermission(sessionID, requestID string) bool {
|
||||
if sessionID == "" || requestID == "" {
|
||||
return false
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turnLocked(sessionID)
|
||||
if turn.permissions == nil {
|
||||
turn.permissions = map[string]struct{}{}
|
||||
}
|
||||
if _, ok := turn.permissions[requestID]; ok {
|
||||
return false
|
||||
}
|
||||
turn.permissions[requestID] = struct{}{}
|
||||
turn.permissionOrder = append(turn.permissionOrder, requestID)
|
||||
if len(turn.permissionOrder) > chatPermissionRetainedLimit {
|
||||
oldest := turn.permissionOrder[0]
|
||||
turn.permissionOrder = turn.permissionOrder[1:]
|
||||
delete(turn.permissions, oldest)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// forgetPermission releases a request id reserved by seenPermission when its
|
||||
// frame could not be written, so a later poll re-pushes it instead of the id
|
||||
// staying "seen" while the phone never received the request.
|
||||
func (h *chatHub) forgetPermission(sessionID, requestID string) {
|
||||
if sessionID == "" || requestID == "" {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
turn := h.turns[sessionID]
|
||||
if turn == nil {
|
||||
return
|
||||
}
|
||||
delete(turn.permissions, requestID)
|
||||
for i, id := range turn.permissionOrder {
|
||||
if id == requestID {
|
||||
turn.permissionOrder = append(turn.permissionOrder[:i], turn.permissionOrder[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"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,
|
||||
// marking any another client currently holds as Busy. 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.
|
||||
func handleChatSessions(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, 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.CreatedAt = operator.CreatedAt
|
||||
session.UpdatedAt = operator.UpdatedAt
|
||||
session.Busy = hub.busyForOther(operator.ID, clientID)
|
||||
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.
|
||||
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 := ""
|
||||
if request.ChatCreate != nil {
|
||||
title = strings.TrimSpace(request.ChatCreate.Title)
|
||||
directory = strings.TrimSpace(request.ChatCreate.Directory)
|
||||
}
|
||||
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
|
||||
}
|
||||
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.RecordOperatorSession(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
|
||||
}
|
||||
session.Directory = resolved
|
||||
session.Tag = protocol.ChatSessionTagOperator
|
||||
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.
|
||||
response.ChatSessions = []protocol.ChatSession{session}
|
||||
_ = write(response)
|
||||
}
|
||||
|
||||
// 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 !opencode.ValidSessionID(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
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatPermissionPollInterval is the fixed interval between permission polls: one
|
||||
// GET per poll through the shared Connection bounds, never a busy loop. The first
|
||||
// poll runs immediately so a request pending when the prompt is sent is surfaced
|
||||
// without waiting a full interval.
|
||||
const chatPermissionPollInterval = 2 * time.Second
|
||||
|
||||
func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, 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
|
||||
}
|
||||
prompt := request.ChatPrompt
|
||||
if prompt == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat prompt payload is required"})
|
||||
return
|
||||
}
|
||||
if !opencode.ValidSessionID(prompt.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(prompt.Text) == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a nonempty chat prompt is required"})
|
||||
return
|
||||
}
|
||||
// Reject an oversized prompt before any OpenCode call; the bound matches the
|
||||
// OpenCode request limit.
|
||||
if len(prompt.Text) > opencode.MaxRequest {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat prompt exceeds 64 KiB"})
|
||||
return
|
||||
}
|
||||
// Claim the session before subscribing or prompting: a second client must be
|
||||
// rejected here, before any broker call, so two clients cannot silently write
|
||||
// the same conversation. The same client may re-prompt its own session.
|
||||
sessionID := prompt.SessionID
|
||||
if !hub.claim(sessionID, clientID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is busy with another client"})
|
||||
return
|
||||
}
|
||||
|
||||
// Subscribe to the OpenCode firehose before posting the prompt: the stream
|
||||
// has no replay cursor (research 2.4), so a delta emitted between the POST
|
||||
// and the subscription would otherwise be lost. Frames that arrive before the
|
||||
// ack is written are buffered and flushed in order after it.
|
||||
streamCtx, streamCancel := context.WithCancel(ctx)
|
||||
attached := make(chan struct{})
|
||||
var attachOnce sync.Once
|
||||
streamResult := make(chan error, 1)
|
||||
var bufferMu sync.Mutex
|
||||
buffering := true
|
||||
var buffered []protocol.ChatEventFrame
|
||||
go func() {
|
||||
streamResult <- broker.Stream(streamCtx, sessionID, func() {
|
||||
attachOnce.Do(func() { close(attached) })
|
||||
}, func(frame protocol.ChatEventFrame) error {
|
||||
bufferMu.Lock()
|
||||
if buffering {
|
||||
buffered = append(buffered, frame)
|
||||
bufferMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
bufferMu.Unlock()
|
||||
hub.apply(frame)
|
||||
return write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame})
|
||||
})
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-attached:
|
||||
case err := <-streamResult:
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat stream: " + err.Error()})
|
||||
}
|
||||
return
|
||||
case <-ctx.Done():
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
return
|
||||
}
|
||||
|
||||
if err := broker.Prompt(ctx, sessionID, prompt.Text); err != nil {
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
// Recency is one UPDATE: it moves the operator session to the front of
|
||||
// chat_sessions. A session id that is not an operator session updates no row
|
||||
// and is not an error, so pipeline stage prompts are unaffected.
|
||||
if registry != nil {
|
||||
if err := registry.TouchOperatorSession(ctx, sessionID); err != nil {
|
||||
log.Printf("touch operator session %s: %v", sessionID, err)
|
||||
}
|
||||
}
|
||||
// Acknowledge the accepted prompt with the echoed request id, then stream the
|
||||
// reply. The prompt is sent exactly once and never re-sent on resume.
|
||||
if err := write(protocol.Message{Type: protocol.ChatPrompt, ID: request.ID}); err != nil {
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
return
|
||||
}
|
||||
// Flush frames buffered while the prompt was accepted, then resume live
|
||||
// delivery. Holding bufferMu preserves order: the stream goroutine either
|
||||
// buffered before this flush or waits and writes after it.
|
||||
bufferMu.Lock()
|
||||
buffering = false
|
||||
pending := buffered
|
||||
buffered = nil
|
||||
for _, frame := range pending {
|
||||
hub.apply(frame)
|
||||
if err := write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}); err != nil {
|
||||
bufferMu.Unlock()
|
||||
streamCancel()
|
||||
hub.release(sessionID, clientID)
|
||||
return
|
||||
}
|
||||
}
|
||||
bufferMu.Unlock()
|
||||
go drainChatStream(ctx, streamResult, streamCancel, hub, sessionID, clientID, write)
|
||||
// Poll for pending approval requests alongside the event stream, sharing
|
||||
// streamCtx so the poller stops when the stream ends or the client
|
||||
// disconnects. The first poll runs immediately.
|
||||
go pollChatPermissions(streamCtx, broker, hub, sessionID, write)
|
||||
}
|
||||
|
||||
// pollChatPermissions polls the broker's pending-approval list on a fixed
|
||||
// interval, sharing the chat subscription's context so it stops on disconnect or
|
||||
// when the turn's stream ends. The hub dedups the request ids, so each pending
|
||||
// request is pushed at most once; a poll failure is surfaced once through the
|
||||
// same write closure instead of staying silent. A backend that does not expose
|
||||
// the approval surface (opencode.ErrPermissionUnsupported) stops the poller
|
||||
// quietly, so the documented limitation is not reported as a per-prompt error.
|
||||
func pollChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) {
|
||||
ticker := time.NewTicker(chatPermissionPollInterval)
|
||||
defer ticker.Stop()
|
||||
reported := false
|
||||
for {
|
||||
if err := pushChatPermissions(ctx, broker, hub, sessionID, write); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, opencode.ErrPermissionUnsupported) {
|
||||
log.Printf("chat permission poll session=%s: %v", sessionID, err)
|
||||
return
|
||||
}
|
||||
if reported {
|
||||
log.Printf("chat permission poll session=%s: %v", sessionID, err)
|
||||
} else {
|
||||
reported = true
|
||||
_ = write(protocol.Message{Type: protocol.Error, Error: "chat permission poll: " + err.Error()})
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pushChatPermissions performs one poll and writes a chat_permission frame for
|
||||
// every newly seen request of the session, through the same connection-scoped
|
||||
// write closure as the chat stream. It never re-pushes a request id, and releases
|
||||
// the reservation on a write failure so the frame is not silently dropped.
|
||||
func pushChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, sessionID string, write func(protocol.Message) error) error {
|
||||
pending, err := broker.Permissions(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, request := range pending {
|
||||
if request.SessionID != sessionID || request.RequestID == "" {
|
||||
continue
|
||||
}
|
||||
if !hub.seenPermission(sessionID, request.RequestID) {
|
||||
continue
|
||||
}
|
||||
frame := request
|
||||
if err := write(protocol.Message{Type: protocol.ChatPermission, ChatPermission: &frame}); err != nil {
|
||||
hub.forgetPermission(sessionID, request.RequestID)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// drainChatStream reports the terminal error of a chat subscription and releases
|
||||
// its context and the session claim once the stream has ended, so a later client
|
||||
// is no longer blocked and nothing leaks.
|
||||
func drainChatStream(ctx context.Context, result <-chan error, cancel context.CancelFunc, hub *chatHub, sessionID, clientID string, write func(protocol.Message) error) {
|
||||
defer cancel()
|
||||
defer hub.release(sessionID, clientID)
|
||||
if err := <-result; err != nil && ctx.Err() == nil {
|
||||
log.Printf("chat stream session=%s: %v", sessionID, err)
|
||||
_ = write(protocol.Message{Type: protocol.Error, Error: "chat stream: " + err.Error()})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user