fix(opencode): read V2 session exports directly from authenticated API

This commit is contained in:
2026-10-20 20:40:57 +01:00
parent 074b5bb087
commit 1b8d0f2a75
7 changed files with 339 additions and 37 deletions
+70 -21
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"time"
@@ -21,29 +22,53 @@ var ErrEmptySessionExport = errors.New("session recorded but native export conta
var errTransientExport = errors.New("native session export temporarily unavailable")
var errSessionIdentity = errors.New("native export session identity mismatch")
// nativeExportResult is one bounded `opencode export` readback. envelope is the
// stdout prefix the CLI wrote, capped at the caller's limit; truncated is true
// when the CLI wrote more than the cap, so the prefix is not valid whole JSON.
// nativeExportResult is one bounded native export readback. envelope is capped
// at the caller's limit; truncated explicitly distinguishes a size-limited
// prefix from complete JSON.
type nativeExportResult struct {
envelope []byte
truncated bool
}
// exportNative runs the read-only session export CLI once with stdout capped at
// limit bytes. It is the single export invocation shared by Connection.Messages
// and ExportSession; the returned envelope is validated by the one
// validNativeExport check both call. The subcommand follows the backend's
// published interface: the native v1 CLI exposes top-level `export <id>`, while
// the installed v2 CLI exposes it as `session export <id>`. It never writes to,
// resumes or mutates the session, and it does not wait for session idleness.
func exportNative(ctx context.Context, executable, directory, backend, id string, limit int) (nativeExportResult, error) {
// exportNative reads the existing V2 endpoint directly (CLI stdout silently
// cuts large exports at 256 KiB), retaining the top-level export CLI for V1.
// It never starts a backend, resumes a session, pairs, or mutates stored data.
func exportNative(ctx context.Context, executable, directory, backend, id string, limit int, connections ...*Connection) (nativeExportResult, error) {
if !sessionID.MatchString(id) {
return nativeExportResult{}, fmt.Errorf("invalid session ID")
}
args := []string{"export", id}
if backend == "v2" {
args = []string{"session", "export", id}
var c *Connection
if len(connections) > 0 {
c = connections[0]
} else {
var err error
c, err = sessionExportConnection(directory)
if err != nil {
return nativeExportResult{}, err
}
}
if c == nil || c.URL == "" || c.Backend != "v2" {
return nativeExportResult{}, fmt.Errorf("session export requires the existing V2 endpoint")
}
body, err := c.HistoryNative(ctx, "/api/experimental/session/"+id+"/export?sanitize=false")
if err != nil {
if c.LastHTTPStatus == 429 || c.LastHTTPStatus == 503 {
err = errors.Join(errTransientExport, err)
}
return nativeExportResult{}, err
}
defer body.Close()
data, err := io.ReadAll(io.LimitReader(body, int64(limit)+1))
if err != nil {
return nativeExportResult{}, fmt.Errorf("session export response interrupted")
}
if len(data) > limit {
return nativeExportResult{envelope: data[:limit], truncated: true}, nil
}
return nativeExportResult{envelope: data}, nil
}
args := []string{"export", id}
cmd := CommandContext(ctx, executable, args...)
cmd.Dir = directory
stdout := &boundedOutput{limit: limit}
@@ -126,6 +151,7 @@ type ExportedPart struct {
// ExportedMessage is one decoded turn. Every role is kept, not only
// user/assistant, so the export is the session the harness stored.
type ExportedMessage struct {
Raw json.RawMessage
ID string
Role string
Model string
@@ -153,12 +179,15 @@ type ExportedSession struct {
// writes, no resumption and no idleness wait. Empty readbacks and explicitly
// temporary failures get at most three attempts within the caller's deadline;
// wrong identity and permanent failures never retry.
func ExportSession(ctx context.Context, executable, directory, backend, id string) (ExportedSession, error) {
// An optional existing connection pins V2 readback to the caller's exact
// endpoint/auth context. Otherwise only configured endpoint/private local
// service state is read; there is no CLI/service-start fallback.
func ExportSession(ctx context.Context, executable, directory, backend, id string, connections ...*Connection) (ExportedSession, error) {
if !sessionID.MatchString(id) {
return ExportedSession{}, fmt.Errorf("invalid session ID")
}
for attempt := 0; attempt < 3; attempt++ {
session, err := exportSessionOnce(ctx, executable, directory, backend, id)
session, err := exportSessionOnce(ctx, executable, directory, backend, id, connections...)
session.Attempts = attempt + 1
if err == nil {
return session, nil
@@ -181,9 +210,9 @@ func ExportSession(ctx context.Context, executable, directory, backend, id strin
panic("unreachable")
}
func exportSessionOnce(ctx context.Context, executable, directory, backend, id string) (ExportedSession, error) {
func exportSessionOnce(ctx context.Context, executable, directory, backend, id string, connections ...*Connection) (ExportedSession, error) {
session := ExportedSession{ID: id, Backend: backend}
exported, err := exportNative(ctx, executable, directory, backend, id, MaxSessionExport)
exported, err := exportNative(ctx, executable, directory, backend, id, MaxSessionExport, connections...)
if err != nil {
return session, fmt.Errorf("native session export failed: %w", err)
}
@@ -193,9 +222,7 @@ func exportSessionOnce(ctx context.Context, executable, directory, backend, id s
return session, err
}
session.Messages, session.Truncated = exportedMessages(records), true
if len(session.Messages) == 0 {
return session, ErrEmptySessionExport
}
// Even a cut inside the first turn is partial evidence, never settling.
return session, nil
}
messages, ok := validNativeExport(exported.envelope, id)
@@ -214,7 +241,7 @@ func exportSessionOnce(ctx context.Context, executable, directory, backend, id s
if identity != "" && identity != id {
return session, errSessionIdentity
}
if identity == id && errors.As(err, &syntax) && strings.Contains(syntax.Error(), "unexpected end") {
if backend != "v2" && len(exported.envelope) != 262144 && identity == id && errors.As(err, &syntax) && strings.Contains(syntax.Error(), "unexpected end") {
return session, errTransientExport
}
return session, fmt.Errorf("native export returned invalid session evidence")
@@ -273,6 +300,7 @@ func exportedMessages(records []nativeChatMessage) []ExportedMessage {
messages := make([]ExportedMessage, 0, len(records))
for _, record := range records {
message := ExportedMessage{
Raw: record.Raw,
ID: record.messageID(),
Role: record.role(),
Model: record.modelID(),
@@ -290,6 +318,18 @@ func exportedMessages(records []nativeChatMessage) []ExportedMessage {
if len(message.Parts) == 0 && message.Role == protocol.ChatRoleUser && record.Text != "" {
message.Parts = append(message.Parts, ExportedPart{Type: protocol.ChatPartText, Text: record.Text})
}
var fields map[string]json.RawMessage
_ = json.Unmarshal(record.Raw, &fields)
var files []json.RawMessage
_ = json.Unmarshal(fields["files"], &files)
for _, file := range files {
message.Parts = append(message.Parts, ExportedPart{Type: "file", Raw: file})
}
// Non-chat events (system, selection, compaction, etc.) must retain
// their real payload even when they have no text/content array.
if len(message.Parts) == 0 {
message.Parts = append(message.Parts, ExportedPart{Type: record.role(), Raw: record.Raw})
}
messages = append(messages, message)
}
return messages
@@ -300,6 +340,10 @@ func exportedMessages(records []nativeChatMessage) []ExportedMessage {
// info.id is an error so an unrelated session is never exported.
func decodeExportPrefix(data []byte, wantID string) ([]nativeChatMessage, bool, error) {
decoder := json.NewDecoder(bytes.NewReader(data))
return decodeExportPrefixObject(decoder, wantID)
}
func decodeExportPrefixObject(decoder *json.Decoder, wantID string) ([]nativeChatMessage, bool, error) {
open, err := decoder.Token()
if err != nil {
return nil, false, fmt.Errorf("native export returned invalid session evidence")
@@ -323,6 +367,11 @@ func decodeExportPrefix(data []byte, wantID string) ([]nativeChatMessage, bool,
}
key, _ := keyToken.(string)
switch key {
case "data":
if sawIdentity || sawMessages {
return nil, false, fmt.Errorf("ambiguous native export envelope")
}
return decodeExportPrefixObject(decoder, wantID)
case "info":
var info struct {
ID string `json:"id"`