Files
pipelines/internal/codex/shells.go
T

183 lines
5.3 KiB
Go

package codex
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"git.a-wan.net/alan/pipelines/internal/protocol"
"sort"
)
const commandOutputCap = 128 << 10
type commandSnapshot struct {
shell protocol.ChatShell
output string
size int64
order uint64
}
func codexShellID(thread, id string) string {
sum := sha256.Sum256([]byte(thread + "\x00" + id))
return "sh_codex_" + hex.EncodeToString(sum[:])
}
func commandRunning(i item) bool {
return i.Status == "inProgress" || i.Status == "running" || i.Status == ""
}
func (c *Chat) recordCommand(thread string, i item, emit bool) {
if i.ID == "" {
return
}
id := codexShellID(thread, i.ID)
c.mu.Lock()
if c.commands == nil {
c.commands = map[string]map[string]commandSnapshot{}
}
if c.commands[thread] == nil {
c.commands[thread] = map[string]commandSnapshot{}
}
old, exists := c.commands[thread][id]
// An older readback must not reopen a command whose exit we already saw.
if !emit && exists && old.shell.Status == protocol.ChatShellExited && commandRunning(i) {
c.mu.Unlock()
return
}
status := protocol.ChatShellExited
if commandRunning(i) {
status = protocol.ChatShellRunning
}
snapshot := old
snapshot.shell = protocol.ChatShell{ID: id, Command: i.Command, Status: status, Exit: i.ExitCode}
if snapshot.shell.Command == "" {
snapshot.shell.Command = old.shell.Command
}
if len(i.AggregatedOutput) > 0 && int64(len(i.AggregatedOutput)) >= old.size {
snapshot.output = i.AggregatedOutput
snapshot.size = int64(len(i.AggregatedOutput))
if len(snapshot.output) > commandOutputCap {
snapshot.output = snapshot.output[:commandOutputCap]
}
}
c.commandOrder++
snapshot.order = c.commandOrder
c.commands[thread][id] = snapshot
// Retain active commands plus a bounded recent exited/output cache. A lazy
// output read can recover older exits from the authoritative thread history.
for len(c.commands[thread]) > 128 {
key := ""
var order uint64
for candidate, value := range c.commands[thread] {
if value.shell.Status == protocol.ChatShellExited && (key == "" || value.order < order) {
key = candidate
order = value.order
}
}
if key == "" {
break
}
delete(c.commands[thread], key)
}
c.mu.Unlock()
if emit {
c.emit(protocol.ChatEventFrame{SessionID: thread, Kind: protocol.ChatEventShell, Shell: &snapshot.shell})
}
}
func (c *Chat) commandDelta(thread, id, delta string) {
if id == "" || delta == "" {
return
}
key := codexShellID(thread, id)
c.mu.Lock()
snapshot, ok := c.commands[thread][key]
if ok && snapshot.shell.Status == protocol.ChatShellRunning {
snapshot.size += int64(len(delta))
remaining := commandOutputCap - len(snapshot.output)
if remaining > 0 {
if len(delta) > remaining {
delta = delta[:remaining]
}
snapshot.output += delta
}
c.commands[thread][key] = snapshot
}
c.mu.Unlock()
}
// Shells uses the installed version's read-only thread API. It does not invent
// a background-terminal endpoint, resume a turn, or enable experimental flags.
func (c *Chat) Shells(ctx context.Context, id string) ([]protocol.ChatShell, error) {
c.mu.Lock()
before := c.commandOrder
c.mu.Unlock()
raw, err := c.call(ctx, "thread/read", map[string]any{"threadId": id, "includeTurns": true})
if err != nil {
return nil, err
}
var response struct {
Thread thread `json:"thread"`
}
if json.Unmarshal(raw, &response) != nil || response.Thread.ID != id {
return nil, errors.New("invalid Codex command readback")
}
seen := map[string]bool{}
for _, turn := range response.Thread.Turns {
for _, i := range turn.Items {
if i.Type == "commandExecution" {
seen[codexShellID(id, i.ID)] = true
c.recordCommand(id, i, false)
}
}
}
c.mu.Lock()
defer c.mu.Unlock()
result := []protocol.ChatShell{}
for key, snapshot := range c.commands[id] {
if !seen[key] && snapshot.order <= before {
delete(c.commands[id], key)
continue
}
if snapshot.shell.Status == protocol.ChatShellRunning {
result = append(result, snapshot.shell)
}
}
sort.Slice(result, func(i, j int) bool { return result[i].ID < result[j].ID })
return result, nil
}
func (c *Chat) ShellOutput(ctx context.Context, q protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
if q.Cursor < 0 || q.Cursor > protocol.ChatShellOutputMaxCursor || q.Limit <= 0 || q.Limit > protocol.ChatShellOutputLimit {
return protocol.ChatShellOutputPage{}, errors.New("invalid bounded Codex output query")
}
c.mu.Lock()
for thread, commands := range c.commands {
if _, known := commands[q.ShellID]; known && thread != q.SessionID {
c.mu.Unlock()
return protocol.ChatShellOutputPage{}, errors.New("command belongs to another thread")
}
}
c.mu.Unlock()
if _, err := c.Shells(ctx, q.SessionID); err != nil {
return protocol.ChatShellOutputPage{}, err
}
c.mu.Lock()
snapshot, ok := c.commands[q.SessionID][q.ShellID]
c.mu.Unlock()
if !ok {
return protocol.ChatShellOutputPage{Shell: protocol.ChatShell{ID: q.ShellID}, Unavailable: true}, nil
}
start := q.Cursor
if start > int64(len(snapshot.output)) {
start = int64(len(snapshot.output))
}
end := start + int64(q.Limit)
if end > int64(len(snapshot.output)) {
end = int64(len(snapshot.output))
}
return protocol.ChatShellOutputPage{Shell: snapshot.shell, Output: snapshot.output[start:end], Cursor: end, Size: snapshot.size, Truncated: end < snapshot.size}, nil
}