WIP preserve large chat history recovery
This commit is contained in:
+66
-14
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -25,8 +26,9 @@ var ErrPermissionUnsupported = errors.New("OpenCode permission approval is not i
|
||||
// Chat is the brokered OpenCode chat adapter (route B in the research): the
|
||||
// Pipelines server owns the OpenCode endpoint and credentials and turns the v2
|
||||
// HTTP API into protocol.ChatEventFrame frames. It reuses the owned-endpoint
|
||||
// semantics, the session-id shape and the 64 KiB / 1 MiB bounds of Connection so
|
||||
// no second transport or credential path is introduced.
|
||||
// semantics and session-id shape of Connection, with its normal 64 KiB / 1 MiB
|
||||
// call guards. History alone streams/project tool details before decoding; it
|
||||
// does not introduce a total-history cap or a second credential path.
|
||||
type Chat struct {
|
||||
conn *Connection
|
||||
// mu serializes the adapter's HTTP calls. Connection records its last
|
||||
@@ -90,27 +92,63 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error {
|
||||
// reuses Connection.Messages, including its read-only OutputFormat readback
|
||||
// fallback, instead of duplicating that path. It maps the verified assistant
|
||||
// content parts (text | reasoning | tool) onto protocol.ChatMessage.
|
||||
func (c *Chat) Messages(ctx context.Context, id string, limit int) ([]protocol.ChatMessage, error) {
|
||||
func (c *Chat) Messages(ctx context.Context, id string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
|
||||
if !sessionID.MatchString(id) {
|
||||
return nil, fmt.Errorf("invalid OpenCode session id")
|
||||
return protocol.ChatHistoryPage{}, fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
var reader io.Reader
|
||||
if c.conn.Backend == "v1" {
|
||||
data, err = c.conn.Messages(ctx, id)
|
||||
} else {
|
||||
path := "/api/session/" + id + "/message"
|
||||
if limit > 0 {
|
||||
path += fmt.Sprintf("?limit=%d", limit)
|
||||
var body io.ReadCloser
|
||||
body, err = c.conn.HistoryNative(ctx, "/session/"+id+"/message")
|
||||
if err == nil {
|
||||
defer body.Close()
|
||||
reader = body
|
||||
} else if c.conn.LastHTTPStatus == 400 {
|
||||
// Preserve the existing OutputFormat/read-only export recovery on
|
||||
// native serve. Ordinary history is streamed, never Call-buffered.
|
||||
data, err = c.conn.Messages(ctx, id)
|
||||
reader = bytes.NewReader(data)
|
||||
}
|
||||
} else {
|
||||
if limit <= 0 {
|
||||
limit = 100 // bounded newest-page request, including legacy clients
|
||||
}
|
||||
path := "/api/session/" + id + "/message"
|
||||
values := make([]string, 0, 2)
|
||||
if limit > 0 {
|
||||
values = append(values, fmt.Sprintf("limit=%d", limit))
|
||||
}
|
||||
if cursor != "" {
|
||||
values = append(values, "cursor="+url.QueryEscape(cursor))
|
||||
}
|
||||
if len(values) > 0 {
|
||||
path += "?" + strings.Join(values, "&")
|
||||
}
|
||||
var body io.ReadCloser
|
||||
body, err = c.conn.HistoryNative(ctx, path)
|
||||
if err == nil {
|
||||
defer body.Close()
|
||||
reader = body
|
||||
}
|
||||
data, err = c.conn.Call(ctx, "get", path, nil)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return protocol.ChatHistoryPage{}, err
|
||||
}
|
||||
return decodeChatMessages(id, data)
|
||||
messages, next, descending, err := decodeChatHistoryPage(ctx, id, reader)
|
||||
if err != nil {
|
||||
return protocol.ChatHistoryPage{}, err
|
||||
}
|
||||
// The verified API returns newest first. The transcript is chronological.
|
||||
if descending {
|
||||
for left, right := 0, len(messages)-1; left < right; left, right = left+1, right-1 {
|
||||
messages[left], messages[right] = messages[right], messages[left]
|
||||
}
|
||||
}
|
||||
return protocol.ChatHistoryPage{Messages: messages, NextCursor: next, HasMore: next != ""}, nil
|
||||
}
|
||||
|
||||
// Sessions lists the OpenCode sessions on the endpoint. On the V2 HTTP API that
|
||||
@@ -793,6 +831,10 @@ func decodeChatMessages(sessionID string, data []byte) ([]protocol.ChatMessage,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return mapChatMessages(sessionID, records), nil
|
||||
}
|
||||
|
||||
func mapChatMessages(sessionID string, records []nativeChatMessage) []protocol.ChatMessage {
|
||||
messages := make([]protocol.ChatMessage, 0, len(records))
|
||||
for _, record := range records {
|
||||
role := record.role()
|
||||
@@ -815,9 +857,19 @@ func decodeChatMessages(sessionID string, data []byte) ([]protocol.ChatMessage,
|
||||
}
|
||||
messages = append(messages, out)
|
||||
}
|
||||
return messages, nil
|
||||
return messages
|
||||
}
|
||||
|
||||
// decodeChatHistoryPage reads the V2 cursor envelope while retaining the older
|
||||
// bare-array decoder for native serve. Tool output is intentionally previewed:
|
||||
// one command's unbounded stdout must not make the entire transcript or its final
|
||||
// answer unavailable over the websocket.
|
||||
func decodeChatHistoryPage(ctx context.Context, sessionID string, reader io.Reader) ([]protocol.ChatMessage, string, bool, error) {
|
||||
return readHistoryPage(ctx, sessionID, reader)
|
||||
}
|
||||
|
||||
const historyToolPreviewBytes = 64 << 10
|
||||
|
||||
// nativeChatSession is one listed session in the verified V2 shape
|
||||
// ({id,title,agent,model,cost,tokens,outcome,time,title,location.directory,
|
||||
// parentID,permissions}); only the fields the protocol surfaces are read. The
|
||||
|
||||
Reference in New Issue
Block a user