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.
This commit is contained in:
@@ -0,0 +1,765 @@
|
||||
// Package codex brokers an operator chat through the Codex App Server.
|
||||
//
|
||||
// Codex exposes threads, turns and items over JSON-RPC. The App Server is
|
||||
// normally reached over a Unix WebSocket socket (the desktop app and the CLI use
|
||||
// the same control socket). This adapter owns one client connection and mirrors
|
||||
// the protocol into the Pipelines chat frames; it never starts a second Codex
|
||||
// daemon or changes the operator's Codex configuration.
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
// Backend is the wire value stored in the operator-session registry.
|
||||
const Backend = "codex"
|
||||
|
||||
// DefaultSocketPath is the Codex desktop app-server control socket.
|
||||
func DefaultSocketPath() string {
|
||||
home := os.Getenv("CODEX_HOME")
|
||||
if home == "" {
|
||||
userHome, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
home = filepath.Join(userHome, ".codex")
|
||||
}
|
||||
return filepath.Join(home, "app-server-control", "app-server-control.sock")
|
||||
}
|
||||
|
||||
// Chat is one owned App Server connection.
|
||||
type Chat struct {
|
||||
conn *websocket.Conn
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
writeMu sync.Mutex
|
||||
nextID int64
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]chan rpcResponse
|
||||
subs map[string]map[chan protocol.ChatEventFrame]struct{}
|
||||
forms map[string]pendingForm
|
||||
turns map[string]string
|
||||
emitted map[string]bool
|
||||
closed bool
|
||||
}
|
||||
|
||||
type pendingForm struct {
|
||||
requestID json.RawMessage
|
||||
threadID string
|
||||
form protocol.ChatForm
|
||||
}
|
||||
|
||||
type rpcResponse struct {
|
||||
Result json.RawMessage
|
||||
Error *rpcError
|
||||
}
|
||||
|
||||
type rpcError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type rpcMessage struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
Error *rpcError `json:"error"`
|
||||
}
|
||||
|
||||
// Open connects to the app-server socket and performs the initialize handshake.
|
||||
func Open(ctx context.Context) (*Chat, error) {
|
||||
socket := DefaultSocketPath()
|
||||
if socket == "" {
|
||||
return nil, errors.New("Codex home is unavailable")
|
||||
}
|
||||
transport := &http.Transport{
|
||||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
|
||||
},
|
||||
}
|
||||
client := &http.Client{Transport: transport}
|
||||
conn, _, err := websocket.Dial(ctx, "ws://localhost/", &websocket.DialOptions{HTTPClient: client})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect Codex app-server: %w", err)
|
||||
}
|
||||
conn.SetReadLimit(16 << 20)
|
||||
child, cancel := context.WithCancel(ctx)
|
||||
c := &Chat{
|
||||
conn: conn, ctx: child, cancel: cancel,
|
||||
pending: map[string]chan rpcResponse{},
|
||||
subs: map[string]map[chan protocol.ChatEventFrame]struct{}{},
|
||||
forms: map[string]pendingForm{},
|
||||
turns: map[string]string{},
|
||||
emitted: map[string]bool{},
|
||||
}
|
||||
go c.readLoop()
|
||||
initCtx, initCancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer initCancel()
|
||||
if _, err := c.call(initCtx, "initialize", map[string]any{
|
||||
"clientInfo": map[string]any{"name": "pipelines", "title": "Pipelines", "version": "0.1"},
|
||||
}); err != nil {
|
||||
c.Close()
|
||||
return nil, fmt.Errorf("initialize Codex app-server: %w", err)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Available reports whether the app-server control socket exists.
|
||||
func Available() bool {
|
||||
path := DefaultSocketPath()
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && info.Mode()&os.ModeSocket != 0
|
||||
}
|
||||
|
||||
// Close shuts the owned client connection down.
|
||||
func (c *Chat) Close() {
|
||||
c.mu.Lock()
|
||||
if c.closed {
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
c.closed = true
|
||||
c.mu.Unlock()
|
||||
c.cancel()
|
||||
_ = c.conn.Close(websocket.StatusNormalClosure, "")
|
||||
}
|
||||
|
||||
func (c *Chat) readLoop() {
|
||||
for {
|
||||
_, data, err := c.conn.Read(c.ctx)
|
||||
if err != nil {
|
||||
c.failPending(err)
|
||||
return
|
||||
}
|
||||
var msg rpcMessage
|
||||
if err := json.Unmarshal(data, &msg); err != nil {
|
||||
continue
|
||||
}
|
||||
if len(msg.ID) > 0 && msg.Method != "" {
|
||||
c.handleServerRequest(msg)
|
||||
continue
|
||||
}
|
||||
if len(msg.ID) > 0 {
|
||||
key := string(msg.ID)
|
||||
c.mu.Lock()
|
||||
ch := c.pending[key]
|
||||
delete(c.pending, key)
|
||||
c.mu.Unlock()
|
||||
if ch != nil {
|
||||
ch <- rpcResponse{Result: msg.Result, Error: msg.Error}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if msg.Method != "" {
|
||||
c.handleNotification(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) failPending(err error) {
|
||||
c.mu.Lock()
|
||||
pending := c.pending
|
||||
c.pending = map[string]chan rpcResponse{}
|
||||
subs := c.subs
|
||||
c.subs = map[string]map[chan protocol.ChatEventFrame]struct{}{}
|
||||
c.mu.Unlock()
|
||||
for _, ch := range pending {
|
||||
ch <- rpcResponse{Error: &rpcError{Message: err.Error()}}
|
||||
}
|
||||
for _, set := range subs {
|
||||
for ch := range set {
|
||||
close(ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) call(ctx context.Context, method string, params any) (json.RawMessage, error) {
|
||||
c.mu.Lock()
|
||||
if c.closed {
|
||||
c.mu.Unlock()
|
||||
return nil, errors.New("Codex connection is closed")
|
||||
}
|
||||
c.nextID++
|
||||
id := c.nextID
|
||||
ch := make(chan rpcResponse, 1)
|
||||
c.pending[strconv.FormatInt(id, 10)] = ch
|
||||
c.mu.Unlock()
|
||||
|
||||
payload := map[string]any{"id": id, "method": method}
|
||||
if params != nil {
|
||||
payload["params"] = params
|
||||
}
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.writeMu.Lock()
|
||||
err = c.conn.Write(ctx, websocket.MessageText, data)
|
||||
c.writeMu.Unlock()
|
||||
if err != nil {
|
||||
c.mu.Lock()
|
||||
delete(c.pending, strconv.FormatInt(id, 10))
|
||||
c.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
c.mu.Lock()
|
||||
delete(c.pending, strconv.FormatInt(id, 10))
|
||||
c.mu.Unlock()
|
||||
return nil, ctx.Err()
|
||||
case resp := <-ch:
|
||||
if resp.Error != nil {
|
||||
return nil, errors.New(resp.Error.Message)
|
||||
}
|
||||
return resp.Result, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) respond(id json.RawMessage, result any) {
|
||||
payload := map[string]any{"id": id, "result": result}
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.writeMu.Lock()
|
||||
_ = c.conn.Write(c.ctx, websocket.MessageText, data)
|
||||
c.writeMu.Unlock()
|
||||
}
|
||||
|
||||
func (c *Chat) emit(frame protocol.ChatEventFrame) {
|
||||
c.mu.Lock()
|
||||
set := c.subs[frame.SessionID]
|
||||
var targets []chan protocol.ChatEventFrame
|
||||
for ch := range set {
|
||||
targets = append(targets, ch)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
for _, ch := range targets {
|
||||
select {
|
||||
case ch <- frame:
|
||||
default:
|
||||
// A slow client must not block the shared Codex connection. The hub
|
||||
// will repair from history on its next subscription.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) subscribe(id string) chan protocol.ChatEventFrame {
|
||||
ch := make(chan protocol.ChatEventFrame, 256)
|
||||
c.mu.Lock()
|
||||
if c.subs[id] == nil {
|
||||
c.subs[id] = map[chan protocol.ChatEventFrame]struct{}{}
|
||||
}
|
||||
c.subs[id][ch] = struct{}{}
|
||||
c.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (c *Chat) unsubscribe(id string, ch chan protocol.ChatEventFrame) {
|
||||
c.mu.Lock()
|
||||
if set := c.subs[id]; set != nil {
|
||||
delete(set, ch)
|
||||
if len(set) == 0 {
|
||||
delete(c.subs, id)
|
||||
}
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// Stream exposes one thread's notifications as chat frames.
|
||||
func (c *Chat) Stream(ctx context.Context, id string, ready func(), emit func(protocol.ChatEventFrame) error) error {
|
||||
ch := c.subscribe(id)
|
||||
defer c.unsubscribe(id, ch)
|
||||
if ready != nil {
|
||||
ready()
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case frame, ok := <-ch:
|
||||
if !ok {
|
||||
return errors.New("Codex connection closed")
|
||||
}
|
||||
if err := emit(frame); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prompt starts one turn. The user turn is already broadcast by the server, so
|
||||
// the adapter only forwards the assistant's items.
|
||||
func (c *Chat) Prompt(ctx context.Context, id, text string) error {
|
||||
return c.PromptWithMessageID(ctx, id, text, "")
|
||||
}
|
||||
|
||||
// PromptWithMessageID carries the client's native user-message id so the
|
||||
// optimistic browser bubble and the authoritative history item can reconcile.
|
||||
func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID string) error {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return errors.New("empty chat prompt")
|
||||
}
|
||||
params := map[string]any{
|
||||
"threadId": id,
|
||||
"input": []any{map[string]any{"type": "text", "text": text}},
|
||||
}
|
||||
if messageID != "" {
|
||||
params["clientUserMessageId"] = messageID
|
||||
}
|
||||
_, err := c.call(ctx, "turn/start", params)
|
||||
return err
|
||||
}
|
||||
|
||||
// Permissions is empty: Codex approvals are disabled on threads this adapter
|
||||
// creates (approvalPolicy never), and questions arrive as requestUserInput.
|
||||
func (c *Chat) Permissions(context.Context, string) ([]protocol.ChatPermissionFrame, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Shells is empty: Codex background terminals are not exposed through the chat
|
||||
// surface yet.
|
||||
func (c *Chat) Shells(context.Context, string) ([]protocol.ChatShell, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Reply is unused because Codex approvals are not created for these threads.
|
||||
func (c *Chat) Reply(context.Context, protocol.ChatReplyRequest) error {
|
||||
return errors.New("Codex approvals are not enabled for this chat backend")
|
||||
}
|
||||
|
||||
// ActivateSkill is an OpenCode-only chat concept.
|
||||
func (c *Chat) ActivateSkill(context.Context, string, string) error {
|
||||
return errors.New("Codex chat has no out-of-band skill activation")
|
||||
}
|
||||
|
||||
// Interrupt cancels the thread's active turn.
|
||||
func (c *Chat) Interrupt(ctx context.Context, id string) error {
|
||||
c.mu.Lock()
|
||||
turn := c.turns[id]
|
||||
c.mu.Unlock()
|
||||
if turn == "" {
|
||||
return nil
|
||||
}
|
||||
_, err := c.call(ctx, "turn/interrupt", map[string]any{"threadId": id, "turnId": turn})
|
||||
return err
|
||||
}
|
||||
|
||||
// Create starts one Codex thread in directory.
|
||||
func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
|
||||
if strings.TrimSpace(directory) == "" {
|
||||
return protocol.ChatSession{}, errors.New("a directory is required")
|
||||
}
|
||||
raw, err := c.call(ctx, "thread/start", map[string]any{
|
||||
"cwd": directory,
|
||||
"approvalPolicy": "never",
|
||||
"sandbox": "workspace-write",
|
||||
})
|
||||
if err != nil {
|
||||
return protocol.ChatSession{}, err
|
||||
}
|
||||
var result struct {
|
||||
Thread thread `json:"thread"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return protocol.ChatSession{}, err
|
||||
}
|
||||
session := result.Thread.chatSession()
|
||||
session.Backend = Backend
|
||||
if strings.TrimSpace(title) != "" {
|
||||
session.Title = strings.TrimSpace(title)
|
||||
}
|
||||
if title != "" {
|
||||
_, _ = c.call(ctx, "thread/name/set", map[string]any{"threadId": session.ID, "name": title})
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// Session returns one thread's current record.
|
||||
func (c *Chat) Session(ctx context.Context, id string) (protocol.ChatSession, bool, error) {
|
||||
raw, err := c.call(ctx, "thread/read", map[string]any{"threadId": id})
|
||||
if err != nil {
|
||||
return protocol.ChatSession{}, false, err
|
||||
}
|
||||
var result struct {
|
||||
Thread thread `json:"thread"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return protocol.ChatSession{}, false, err
|
||||
}
|
||||
if result.Thread.ID == "" {
|
||||
return protocol.ChatSession{}, false, nil
|
||||
}
|
||||
session := result.Thread.chatSession()
|
||||
session.Backend = Backend
|
||||
return session, true, nil
|
||||
}
|
||||
|
||||
// Sessions lists Codex threads (bounded) so the server can intersect them with
|
||||
// the operator registry.
|
||||
func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
|
||||
raw, err := c.call(ctx, "thread/list", map[string]any{"limit": 200})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var result struct {
|
||||
Data []thread `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sessions := make([]protocol.ChatSession, 0, len(result.Data))
|
||||
for _, t := range result.Data {
|
||||
session := t.chatSession()
|
||||
session.Backend = Backend
|
||||
sessions = append(sessions, session)
|
||||
}
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
// Messages reads a thread's turns and flattens them into chat messages.
|
||||
func (c *Chat) Messages(ctx context.Context, id string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
|
||||
_ = limit
|
||||
_ = cursor
|
||||
raw, err := c.call(ctx, "thread/read", map[string]any{"threadId": id, "includeTurns": true})
|
||||
if err != nil {
|
||||
return protocol.ChatHistoryPage{}, err
|
||||
}
|
||||
var result struct {
|
||||
Thread thread `json:"thread"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return protocol.ChatHistoryPage{}, err
|
||||
}
|
||||
messages := []protocol.ChatMessage{}
|
||||
for _, turn := range result.Thread.Turns {
|
||||
for _, item := range turn.Items {
|
||||
if msg, ok := item.chatMessage(id); ok {
|
||||
messages = append(messages, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
return protocol.ChatHistoryPage{Messages: messages}, nil
|
||||
}
|
||||
|
||||
// Answer replies to a pending requestUserInput request.
|
||||
func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
|
||||
c.mu.Lock()
|
||||
pending, ok := c.forms[request.FormID]
|
||||
if ok {
|
||||
delete(c.forms, request.FormID)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if !ok {
|
||||
return errors.New("the Codex question is no longer awaiting an answer")
|
||||
}
|
||||
answers := map[string]any{}
|
||||
for key, value := range request.Answers {
|
||||
switch v := value.(type) {
|
||||
case []any:
|
||||
answers[key] = map[string]any{"answers": v}
|
||||
case []string:
|
||||
answers[key] = map[string]any{"answers": v}
|
||||
case string:
|
||||
answers[key] = map[string]any{"answers": []string{v}}
|
||||
default:
|
||||
answers[key] = map[string]any{"answers": []string{fmt.Sprint(v)}}
|
||||
}
|
||||
}
|
||||
c.respond(pending.requestID, map[string]any{"answers": answers})
|
||||
c.emit(protocol.ChatEventFrame{
|
||||
SessionID: pending.threadID,
|
||||
Kind: protocol.ChatEventForm,
|
||||
Form: &protocol.ChatForm{ID: pending.form.ID, SessionID: pending.threadID, Resolved: true},
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Chat) handleServerRequest(msg rpcMessage) {
|
||||
switch msg.Method {
|
||||
case "item/tool/requestUserInput":
|
||||
var params struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
TurnID string `json:"turnId"`
|
||||
ItemID string `json:"itemId"`
|
||||
Questions []struct {
|
||||
ID string `json:"id"`
|
||||
Header string `json:"header"`
|
||||
Question string `json:"question"`
|
||||
IsOther bool `json:"isOther"`
|
||||
IsSecret bool `json:"isSecret"`
|
||||
Options []struct {
|
||||
Value string `json:"value"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
} `json:"options"`
|
||||
} `json:"questions"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Params, ¶ms); err != nil || params.ThreadID == "" || params.ItemID == "" {
|
||||
c.respond(msg.ID, map[string]any{"answers": map[string]any{}})
|
||||
return
|
||||
}
|
||||
form := protocol.ChatForm{
|
||||
ID: params.ItemID,
|
||||
SessionID: params.ThreadID,
|
||||
Title: "Question",
|
||||
Kind: "question",
|
||||
}
|
||||
for _, q := range params.Questions {
|
||||
field := protocol.ChatFormField{
|
||||
Key: q.ID, Title: q.Question, Description: q.Header,
|
||||
Type: "string", Custom: q.IsOther, Required: true,
|
||||
}
|
||||
for _, option := range q.Options {
|
||||
value := option.Value
|
||||
if value == "" {
|
||||
value = option.Label
|
||||
}
|
||||
field.Options = append(field.Options, protocol.ChatFormOption{
|
||||
Value: value, Label: option.Label, Description: option.Description,
|
||||
})
|
||||
}
|
||||
form.Fields = append(form.Fields, field)
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.forms[form.ID] = pendingForm{requestID: msg.ID, threadID: params.ThreadID, form: form}
|
||||
c.mu.Unlock()
|
||||
c.emit(protocol.ChatEventFrame{SessionID: params.ThreadID, Kind: protocol.ChatEventForm, Form: &form})
|
||||
case "item/commandExecution/requestApproval", "item/fileChange/requestApproval":
|
||||
// The thread is created with approvalPolicy never; if a provider still asks,
|
||||
// deny rather than leave the turn hanging.
|
||||
c.respond(msg.ID, map[string]any{"decision": "deny"})
|
||||
default:
|
||||
// Unknown server requests must not stall the shared connection.
|
||||
c.respond(msg.ID, map[string]any{})
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) handleNotification(msg rpcMessage) {
|
||||
var params struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
TurnID string `json:"turnId"`
|
||||
ItemID string `json:"itemId"`
|
||||
Delta string `json:"delta"`
|
||||
Item json.RawMessage `json:"item"`
|
||||
Turn struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
} `json:"turn"`
|
||||
Status struct {
|
||||
Type string `json:"type"`
|
||||
} `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Params, ¶ms); err != nil || params.ThreadID == "" {
|
||||
return
|
||||
}
|
||||
switch msg.Method {
|
||||
case "turn/started":
|
||||
c.mu.Lock()
|
||||
c.turns[params.ThreadID] = params.TurnID
|
||||
if c.turns[params.ThreadID] == "" {
|
||||
c.turns[params.ThreadID] = params.Turn.ID
|
||||
}
|
||||
c.mu.Unlock()
|
||||
c.emit(stepFrame(params.ThreadID, "started"))
|
||||
case "turn/completed":
|
||||
c.mu.Lock()
|
||||
delete(c.turns, params.ThreadID)
|
||||
c.mu.Unlock()
|
||||
c.emit(stepFrame(params.ThreadID, protocol.ChatStepEnded))
|
||||
case "item/started":
|
||||
c.handleItem(params.ThreadID, params.ItemID, params.Item, false)
|
||||
case "item/completed":
|
||||
c.handleItem(params.ThreadID, params.ItemID, params.Item, true)
|
||||
case "item/agentMessage/delta", "item/agentMessage/streaming":
|
||||
if params.ItemID != "" && params.Delta != "" {
|
||||
c.markEmitted(params.ItemID)
|
||||
c.emit(textFrame(params.ThreadID, params.ItemID, protocol.ChatEventText, params.Delta))
|
||||
}
|
||||
case "item/reasoning/delta":
|
||||
if params.ItemID != "" && params.Delta != "" {
|
||||
c.markEmitted(params.ItemID)
|
||||
c.emit(textFrame(params.ThreadID, params.ItemID, protocol.ChatEventReasoning, params.Delta))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) handleItem(threadID, itemID string, raw json.RawMessage, completed bool) {
|
||||
var item struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Status string `json:"status"`
|
||||
Command string `json:"command"`
|
||||
Query string `json:"query"`
|
||||
Name string `json:"name"`
|
||||
Input any `json:"input"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &item); err != nil {
|
||||
return
|
||||
}
|
||||
if item.ID == "" {
|
||||
item.ID = itemID
|
||||
}
|
||||
switch item.Type {
|
||||
case "agentMessage":
|
||||
if completed && item.Text != "" && !c.wasEmitted(item.ID) {
|
||||
c.emit(textFrame(threadID, item.ID, protocol.ChatEventText, item.Text))
|
||||
}
|
||||
case "reasoning":
|
||||
if completed && item.Text != "" && !c.wasEmitted(item.ID) {
|
||||
c.emit(textFrame(threadID, item.ID, protocol.ChatEventReasoning, item.Text))
|
||||
}
|
||||
case "commandExecution", "fileChange", "mcpToolCall", "webSearch":
|
||||
status := protocol.ChatToolRunning
|
||||
if completed {
|
||||
if strings.EqualFold(item.Status, "failed") || item.Error != "" {
|
||||
status = protocol.ChatToolError
|
||||
} else {
|
||||
status = protocol.ChatToolCompleted
|
||||
}
|
||||
}
|
||||
name := item.Type
|
||||
var input any
|
||||
switch item.Type {
|
||||
case "commandExecution":
|
||||
name = "shell"
|
||||
input = map[string]any{"command": item.Command}
|
||||
case "webSearch":
|
||||
name = "websearch"
|
||||
input = map[string]any{"query": item.Query}
|
||||
default:
|
||||
if item.Name != "" {
|
||||
name = item.Name
|
||||
}
|
||||
input = item.Input
|
||||
}
|
||||
encoded, _ := json.Marshal(input)
|
||||
state := &protocol.ChatToolState{Status: status, Input: encoded}
|
||||
if item.Text != "" {
|
||||
state.Content = []protocol.ChatToolContent{{Type: "text", Text: item.Text}}
|
||||
}
|
||||
if item.Error != "" {
|
||||
state.Error = &protocol.ChatError{Message: item.Error}
|
||||
}
|
||||
c.emit(protocol.ChatEventFrame{
|
||||
SessionID: threadID, MessageID: item.ID, Kind: protocol.ChatEventTool,
|
||||
Part: &protocol.ChatPart{Type: protocol.ChatPartTool, ID: item.ID, Name: name, State: state},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) markEmitted(id string) {
|
||||
c.mu.Lock()
|
||||
c.emitted[id] = true
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *Chat) wasEmitted(id string) bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.emitted[id]
|
||||
}
|
||||
|
||||
func textFrame(threadID, itemID, kind, delta string) protocol.ChatEventFrame {
|
||||
return protocol.ChatEventFrame{
|
||||
SessionID: threadID, MessageID: itemID, Kind: kind, Delta: delta,
|
||||
Part: &protocol.ChatPart{Type: kind, ID: protocol.ChatDeltaPartID(itemID, kind, 0)},
|
||||
}
|
||||
}
|
||||
|
||||
func stepFrame(threadID, status string) protocol.ChatEventFrame {
|
||||
return protocol.ChatEventFrame{
|
||||
SessionID: threadID, Kind: protocol.ChatEventStep,
|
||||
Step: &protocol.ChatStep{Status: status},
|
||||
}
|
||||
}
|
||||
|
||||
type thread struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Preview string `json:"preview"`
|
||||
Cwd string `json:"cwd"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
UpdatedAt int64 `json:"updatedAt"`
|
||||
Turns []turn `json:"turns"`
|
||||
}
|
||||
|
||||
type turn struct {
|
||||
Items []item `json:"items"`
|
||||
}
|
||||
|
||||
type item struct {
|
||||
ID string `json:"id"`
|
||||
ClientID string `json:"clientId"`
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Content json.RawMessage `json:"content"`
|
||||
Status string `json:"status"`
|
||||
Command string `json:"command"`
|
||||
Query string `json:"query"`
|
||||
Name string `json:"name"`
|
||||
Input any `json:"input"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func (t thread) chatSession() protocol.ChatSession {
|
||||
title := strings.TrimSpace(t.Name)
|
||||
if title == "" {
|
||||
title = strings.TrimSpace(t.Preview)
|
||||
}
|
||||
return protocol.ChatSession{
|
||||
ID: t.ID, Title: title, Directory: t.Cwd,
|
||||
CreatedAt: t.CreatedAt * 1000, UpdatedAt: t.UpdatedAt * 1000,
|
||||
}
|
||||
}
|
||||
|
||||
func (i item) chatMessage(sessionID string) (protocol.ChatMessage, bool) {
|
||||
msg := protocol.ChatMessage{ID: i.ID, SessionID: sessionID}
|
||||
switch i.Type {
|
||||
case "userMessage":
|
||||
msg.Role = protocol.ChatRoleUser
|
||||
if i.ClientID != "" {
|
||||
msg.ID = i.ClientID
|
||||
}
|
||||
var content []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
_ = json.Unmarshal(i.Content, &content)
|
||||
for _, part := range content {
|
||||
if part.Type == "text" && part.Text != "" {
|
||||
msg.Parts = append(msg.Parts, protocol.ChatPart{Type: protocol.ChatPartText, Text: part.Text})
|
||||
}
|
||||
}
|
||||
case "agentMessage":
|
||||
msg.Role = protocol.ChatRoleAssistant
|
||||
if i.Text != "" {
|
||||
msg.Parts = append(msg.Parts, protocol.ChatPart{Type: protocol.ChatPartText, Text: i.Text})
|
||||
}
|
||||
default:
|
||||
return protocol.ChatMessage{}, false
|
||||
}
|
||||
return msg, len(msg.Parts) > 0
|
||||
}
|
||||
@@ -23,6 +23,9 @@ type OperatorSession struct {
|
||||
Directory string
|
||||
Title string
|
||||
Tag string
|
||||
// Backend names the chat harness that owns the session: opencode, codex or
|
||||
// claude. Rows created before backends existed default to opencode.
|
||||
Backend string
|
||||
CreatedAt int64
|
||||
UpdatedAt int64
|
||||
// ClosedAt is the epoch-millisecond time the operator finished with the
|
||||
@@ -63,7 +66,7 @@ func (s *Store) initOperatorSessions() error {
|
||||
session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
|
||||
tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL,
|
||||
closed_at INTEGER NOT NULL DEFAULT 0, starred_at INTEGER NOT NULL DEFAULT 0,
|
||||
ephemeral INTEGER NOT NULL DEFAULT 0);
|
||||
backend TEXT NOT NULL DEFAULT 'opencode', ephemeral INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -144,6 +147,11 @@ func (s *Store) migrateOperatorSessions() error {
|
||||
if err := s.addColumnIfMissing("operator_sessions", "starred_at", "INTEGER NOT NULL DEFAULT 0"); err != nil {
|
||||
return err
|
||||
}
|
||||
// backend records which harness owns the session so a restart can route a
|
||||
// chat without guessing from its id. Existing rows are OpenCode.
|
||||
if err := s.addColumnIfMissing("operator_sessions", "backend", "TEXT NOT NULL DEFAULT 'opencode'"); err != nil {
|
||||
return err
|
||||
}
|
||||
// ephemeral marks a chat created for automated verification. It is hidden from
|
||||
// OperatorSessions but still a real row, so the session stays usable and
|
||||
// closable. Existing rows default to 0 (a normal, listed chat).
|
||||
@@ -221,6 +229,13 @@ func (s *Store) SetOperatorSessionTitle(ctx context.Context, sessionID, title st
|
||||
return err
|
||||
}
|
||||
|
||||
// SetOperatorSessionBackend records which harness owns a session. It is called
|
||||
// once after a create; the backend never changes for an existing session.
|
||||
func (s *Store) SetOperatorSessionBackend(ctx context.Context, sessionID, backend string) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET backend=? WHERE session_id=?", backend, sessionID)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetOperatorSessionStar records the shared star state in one UPDATE. A session
|
||||
// id that is not an operator session updates no row and is not an error, so a
|
||||
// pipeline-owned run session is never affected.
|
||||
@@ -238,9 +253,9 @@ func (s *Store) SetOperatorSessionStar(ctx context.Context, sessionID string, st
|
||||
// returned). It is one indexed lookup and never mutates the row.
|
||||
func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) {
|
||||
var session OperatorSession
|
||||
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at,starred_at
|
||||
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at
|
||||
FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
|
||||
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
|
||||
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return OperatorSession{}, false, nil
|
||||
}
|
||||
@@ -259,7 +274,7 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
|
||||
// operator can still see and reopen what they finished. It is one bounded
|
||||
// statement; recency is never mutated here.
|
||||
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at,starred_at
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at
|
||||
FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -268,7 +283,7 @@ FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at D
|
||||
sessions := []OperatorSession{}
|
||||
for rows.Next() {
|
||||
var session OperatorSession
|
||||
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
|
||||
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sessions = append(sessions, session)
|
||||
|
||||
@@ -43,6 +43,9 @@ const (
|
||||
// ChatRename records the operator's shared chat title on the server. Unlike
|
||||
// a local override, every browser and device then lists the same name.
|
||||
ChatRename = "chat_rename"
|
||||
// ChatBackends lists the installed chat harnesses the server can create a
|
||||
// session on. The reply is a bounded array of backend names.
|
||||
ChatBackends = "chat_backends"
|
||||
// ChatStar records the operator's star on the server, so every browser and
|
||||
// device shows the same starred group. It takes a ChatQuery with SessionID
|
||||
// and Starred, and echoes the updated session like close/reopen.
|
||||
@@ -154,7 +157,10 @@ const (
|
||||
// phone: the nested location.directory and time{created,updated} fields are
|
||||
// lifted to Directory, CreatedAt and UpdatedAt.
|
||||
type ChatSession struct {
|
||||
ID string `json:"id"`
|
||||
ID string `json:"id"`
|
||||
// Backend names the harness that owns this session: opencode, codex or
|
||||
// claude. Empty on older peers and for legacy OpenCode rows.
|
||||
Backend string `json:"backend,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Agent string `json:"agent,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
@@ -203,8 +209,11 @@ type ChatCloseResult struct {
|
||||
// correlation. Clients retrying a create across reconnects must retain it. The
|
||||
// response carries the created session in Message.ChatSession.
|
||||
type ChatCreateRequest struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Directory string `json:"directory,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Directory string `json:"directory,omitempty"`
|
||||
// Backend selects the chat harness for a new session. Empty means opencode,
|
||||
// preserving older clients and the default.
|
||||
Backend string `json:"backend,omitempty"`
|
||||
OperationID string `json:"operation_id,omitempty"`
|
||||
// Ephemeral creates a chat for automated verification: the session is created,
|
||||
// bootstrapped and usable exactly like a normal one, but no operator-registry
|
||||
|
||||
@@ -188,6 +188,9 @@ type Message struct {
|
||||
ChatAnswer *ChatAnswerRequest `json:"chat_answer,omitempty"`
|
||||
// ChatRename is the chat_rename body; the reply echoes the updated session.
|
||||
ChatRename *ChatRenameRequest `json:"chat_rename,omitempty"`
|
||||
// ChatBackends is the chat_backends reply: the installed harnesses a new
|
||||
// chat can use.
|
||||
ChatBackends []string `json:"chat_backends,omitempty"`
|
||||
// ChatSubscribe attaches this connection to one session's shared stream; the
|
||||
// body names the session like ChatQuery. A chat_prompt response sets
|
||||
// ChatQueued when the prompt had to wait for an in-flight turn and was
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
|
||||
@@ -92,6 +93,16 @@ type operatorRegistry interface {
|
||||
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
|
||||
@@ -157,6 +168,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatRename:
|
||||
handleChatRename(ctx, request, registry, write)
|
||||
return true
|
||||
case protocol.ChatBackends:
|
||||
handleChatBackends(request, broker, write)
|
||||
return true
|
||||
case protocol.ChatShells:
|
||||
handleChatShells(ctx, request, broker, registry, write)
|
||||
return true
|
||||
|
||||
@@ -3,7 +3,6 @@ package server
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
@@ -23,7 +22,7 @@ func handleChatAnswer(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat_answer payload is required"})
|
||||
return
|
||||
}
|
||||
if !opencode.ValidSessionID(answer.SessionID) {
|
||||
if !validChatSessionID(answer.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// handleChatBackends lists the installed chat harnesses. Older servers answer
|
||||
// with the empty field, which clients treat as OpenCode-only.
|
||||
func handleChatBackends(request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
|
||||
backends := []string{"opencode"}
|
||||
if lister, ok := broker.(interface{ Backends() []string }); ok {
|
||||
backends = lister.Backends()
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatBackends, ID: request.ID, ChatBackends: backends})
|
||||
}
|
||||
|
||||
// chatCreateBackend is the optional create-with-backend surface implemented by
|
||||
// the multi-harness manager. A single-broker installation keeps using Create.
|
||||
type chatCreateBackend interface {
|
||||
CreateBackend(ctx context.Context, title, directory, backend string) (protocol.ChatSession, error)
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
@@ -28,7 +27,7 @@ func handleChatClose(ctx context.Context, request protocol.Message, broker chatB
|
||||
return
|
||||
}
|
||||
query := request.ChatQuery
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
@@ -88,7 +87,7 @@ func handleChatReopen(ctx context.Context, request protocol.Message, registry op
|
||||
return
|
||||
}
|
||||
query := request.ChatQuery
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
@@ -135,6 +134,7 @@ func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSess
|
||||
Tag: session.Tag,
|
||||
CreatedAt: session.CreatedAt,
|
||||
UpdatedAt: session.UpdatedAt,
|
||||
Backend: session.Backend,
|
||||
}
|
||||
if session.ClosedAt > 0 {
|
||||
out.Closed = true
|
||||
|
||||
@@ -4,13 +4,12 @@ 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) {
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
@@ -39,7 +38,7 @@ func handleChatSimple(ctx context.Context, request protocol.Message, broker chat
|
||||
}
|
||||
if request.Type == protocol.ChatInterrupt {
|
||||
query := request.ChatQuery
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
@@ -51,7 +50,7 @@ func handleChatSimple(ctx context.Context, request protocol.Message, broker chat
|
||||
return
|
||||
}
|
||||
reply := request.ChatReply
|
||||
if reply == nil || !opencode.ValidSessionID(reply.SessionID) {
|
||||
if reply == nil || !validChatSessionID(reply.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/codex"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatManager routes one session to the harness that owns it. OpenCode remains
|
||||
// the default; Codex is attached when its app-server control socket exists.
|
||||
// The operator registry is the durable record of the backend, so a restart does
|
||||
// not have to guess from a session id.
|
||||
type chatManager struct {
|
||||
opencode chatBroker
|
||||
codex chatBroker
|
||||
registry operatorRegistry
|
||||
|
||||
mu sync.Mutex
|
||||
cache map[string]string // session id -> backend
|
||||
}
|
||||
|
||||
func NewChatManager(ctx context.Context, open chatBroker, registry operatorRegistry) *chatManager {
|
||||
m := &chatManager{opencode: open, registry: registry, cache: map[string]string{}}
|
||||
if codex.Available() {
|
||||
client, err := codex.Open(ctx)
|
||||
if err == nil {
|
||||
m.codex = client
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// Close releases the owned Codex client, if any.
|
||||
func (m *chatManager) Close() {
|
||||
if closer, ok := m.codex.(interface{ Close() }); ok {
|
||||
closer.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Backends lists the harnesses available for a new session.
|
||||
func (m *chatManager) Backends() []string {
|
||||
backends := []string{}
|
||||
if m.opencode != nil {
|
||||
backends = append(backends, "opencode")
|
||||
}
|
||||
if m.codex != nil {
|
||||
backends = append(backends, codex.Backend)
|
||||
}
|
||||
sort.Strings(backends)
|
||||
return backends
|
||||
}
|
||||
|
||||
func (m *chatManager) adapter(backend string) chatBroker {
|
||||
switch backend {
|
||||
case "", "opencode":
|
||||
return m.opencode
|
||||
case codex.Backend:
|
||||
return m.codex
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (m *chatManager) backendFor(ctx context.Context, sessionID string) string {
|
||||
m.mu.Lock()
|
||||
backend := m.cache[sessionID]
|
||||
m.mu.Unlock()
|
||||
if backend != "" {
|
||||
return backend
|
||||
}
|
||||
if m.registry != nil {
|
||||
if row, found, err := m.registry.OperatorSession(ctx, sessionID); err == nil && found && row.Backend != "" {
|
||||
m.mu.Lock()
|
||||
m.cache[sessionID] = row.Backend
|
||||
m.mu.Unlock()
|
||||
return row.Backend
|
||||
}
|
||||
}
|
||||
return "opencode"
|
||||
}
|
||||
|
||||
func (m *chatManager) brokerFor(ctx context.Context, sessionID string) (chatBroker, error) {
|
||||
backend := m.backendFor(ctx, sessionID)
|
||||
adapter := m.adapter(backend)
|
||||
if adapter == nil {
|
||||
return nil, errors.New("chat backend " + backend + " is not available")
|
||||
}
|
||||
return adapter, nil
|
||||
}
|
||||
|
||||
// CreateBackend creates a session on the requested harness. An empty backend
|
||||
// keeps the OpenCode default.
|
||||
func (m *chatManager) CreateBackend(ctx context.Context, title, directory, backend string) (protocol.ChatSession, error) {
|
||||
if backend == "" {
|
||||
backend = "opencode"
|
||||
}
|
||||
adapter := m.adapter(backend)
|
||||
if adapter == nil {
|
||||
return protocol.ChatSession{}, errors.New("chat backend " + backend + " is not available")
|
||||
}
|
||||
session, err := adapter.Create(ctx, title, directory)
|
||||
if err != nil {
|
||||
return protocol.ChatSession{}, err
|
||||
}
|
||||
session.Backend = backend
|
||||
m.mu.Lock()
|
||||
m.cache[session.ID] = backend
|
||||
m.mu.Unlock()
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (m *chatManager) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
|
||||
return m.CreateBackend(ctx, title, directory, "opencode")
|
||||
}
|
||||
|
||||
func (m *chatManager) Prompt(ctx context.Context, sessionID, text string) error {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return adapter.Prompt(ctx, sessionID, text)
|
||||
}
|
||||
|
||||
func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text, messageID string) error {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if withID, ok := adapter.(chatPromptWithMessageID); ok {
|
||||
return withID.PromptWithMessageID(ctx, sessionID, text, messageID)
|
||||
}
|
||||
return adapter.Prompt(ctx, sessionID, text)
|
||||
}
|
||||
|
||||
func (m *chatManager) Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return adapter.Stream(ctx, sessionID, ready, emit)
|
||||
}
|
||||
|
||||
func (m *chatManager) Interrupt(ctx context.Context, sessionID string) error {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return adapter.Interrupt(ctx, sessionID)
|
||||
}
|
||||
|
||||
func (m *chatManager) Messages(ctx context.Context, sessionID string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return protocol.ChatHistoryPage{}, err
|
||||
}
|
||||
return adapter.Messages(ctx, sessionID, limit, cursor)
|
||||
}
|
||||
|
||||
func (m *chatManager) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
|
||||
sessions := []protocol.ChatSession{}
|
||||
seen := map[string]bool{}
|
||||
for _, adapter := range []chatBroker{m.opencode, m.codex} {
|
||||
if adapter == nil {
|
||||
continue
|
||||
}
|
||||
list, err := adapter.Sessions(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, session := range list {
|
||||
if session.ID == "" || seen[session.ID] {
|
||||
continue
|
||||
}
|
||||
seen[session.ID] = true
|
||||
sessions = append(sessions, session)
|
||||
}
|
||||
}
|
||||
// A backend that cannot enumerate its own store still has registry rows.
|
||||
// Resolve those individually so an older/restarted backend never silently
|
||||
// drops a chat from the list.
|
||||
if m.registry != nil {
|
||||
if rows, err := m.registry.OperatorSessions(ctx); err == nil {
|
||||
for _, row := range rows {
|
||||
if seen[row.ID] || row.Backend == "" || row.Backend == "opencode" {
|
||||
continue
|
||||
}
|
||||
adapter := m.adapter(row.Backend)
|
||||
if adapter == nil {
|
||||
continue
|
||||
}
|
||||
if session, found, err := adapter.Session(ctx, row.ID); err == nil && found {
|
||||
seen[row.ID] = true
|
||||
sessions = append(sessions, session)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
func (m *chatManager) Session(ctx context.Context, sessionID string) (protocol.ChatSession, bool, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return protocol.ChatSession{}, false, err
|
||||
}
|
||||
return adapter.Session(ctx, sessionID)
|
||||
}
|
||||
|
||||
func (m *chatManager) Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if permissions, ok := adapter.(interface {
|
||||
Permissions(context.Context, string) ([]protocol.ChatPermissionFrame, error)
|
||||
}); ok {
|
||||
return permissions.Permissions(ctx, sessionID)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *chatManager) Shells(ctx context.Context, sessionID string) ([]protocol.ChatShell, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if shells, ok := adapter.(interface {
|
||||
Shells(context.Context, string) ([]protocol.ChatShell, error)
|
||||
}); ok {
|
||||
return shells.Shells(ctx, sessionID)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *chatManager) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
|
||||
adapter, err := m.brokerFor(ctx, request.SessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return adapter.Reply(ctx, request)
|
||||
}
|
||||
|
||||
func (m *chatManager) ActivateSkill(ctx context.Context, sessionID, skill string) error {
|
||||
// Skill bootstrap is an OpenCode chat concept. Other harnesses return from
|
||||
// create without a manager skill and must not fail the create.
|
||||
if m.backendFor(ctx, sessionID) != "opencode" {
|
||||
return nil
|
||||
}
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return adapter.ActivateSkill(ctx, sessionID, skill)
|
||||
}
|
||||
|
||||
func (m *chatManager) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
|
||||
adapter, err := m.brokerFor(ctx, request.SessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
answerer, ok := adapter.(chatAnswerer)
|
||||
if !ok {
|
||||
return errors.New("this chat backend cannot answer questions")
|
||||
}
|
||||
return answerer.Answer(ctx, request)
|
||||
}
|
||||
|
||||
func (m *chatManager) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
|
||||
adapter, err := m.brokerFor(ctx, query.SessionID)
|
||||
if err != nil {
|
||||
return protocol.ChatShellOutputPage{}, err
|
||||
}
|
||||
reader, ok := adapter.(chatShellOutputReader)
|
||||
if !ok {
|
||||
return protocol.ChatShellOutputPage{}, errors.New("this chat backend has no shell output")
|
||||
}
|
||||
return reader.ShellOutput(ctx, query)
|
||||
}
|
||||
|
||||
func (m *chatManager) ReleaseShells(sessionID string) {
|
||||
m.mu.Lock()
|
||||
backend := m.cache[sessionID]
|
||||
m.mu.Unlock()
|
||||
adapter := m.adapter(backend)
|
||||
if releaser, ok := adapter.(chatShellReleaser); ok {
|
||||
releaser.ReleaseShells(sessionID)
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
@@ -25,7 +24,7 @@ func handleChatRename(ctx context.Context, request protocol.Message, registry op
|
||||
return
|
||||
}
|
||||
rename := request.ChatRename
|
||||
if rename == nil || !opencode.ValidSessionID(rename.SessionID) {
|
||||
if rename == nil || !validChatSessionID(rename.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
@@ -72,6 +71,7 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
|
||||
}
|
||||
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
|
||||
@@ -107,11 +107,15 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
|
||||
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
|
||||
@@ -146,7 +150,15 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
|
||||
chatCreateConflictError(request, err, write)
|
||||
return
|
||||
}
|
||||
session, err = broker.Create(ctx, title, resolved)
|
||||
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
|
||||
@@ -199,6 +211,10 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = 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
|
||||
@@ -209,6 +225,7 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
|
||||
}
|
||||
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
|
||||
@@ -250,7 +267,7 @@ func handleChatAdopt(ctx context.Context, request protocol.Message, broker chatB
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(request.ChatAdopt.SessionID)
|
||||
if !opencode.ValidSessionID(id) {
|
||||
if !validChatSessionID(id) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func handleChatShells(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
||||
return
|
||||
}
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
@@ -50,7 +50,7 @@ func handleChatShellOutput(ctx context.Context, request protocol.Message, broker
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
||||
return
|
||||
}
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) || !validShellID(query.ShellID) || query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
|
||||
if query == nil || !validChatSessionID(query.SessionID) || !validShellID(query.ShellID) || query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid bounded shell output query is required"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package server
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
@@ -20,7 +19,7 @@ func handleChatStar(ctx context.Context, request protocol.Message, registry oper
|
||||
return
|
||||
}
|
||||
query := request.ChatQuery
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat prompt payload is required"})
|
||||
return
|
||||
}
|
||||
if !opencode.ValidSessionID(prompt.SessionID) {
|
||||
if !validChatSessionID(prompt.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
@@ -104,7 +104,7 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH
|
||||
// subscribeRequest and docs/cli.md both use it), not the chat_query body the
|
||||
// other session-scoped commands carry.
|
||||
query := request.ChatSubscribe
|
||||
if query == nil || !opencode.ValidSessionID(query.SessionID) {
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user