77 lines
2.2 KiB
Go
77 lines
2.2 KiB
Go
package opencode
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os/exec"
|
|
"strings"
|
|
)
|
|
|
|
type boundedOutput struct {
|
|
bytes.Buffer
|
|
overflow bool
|
|
limit int
|
|
}
|
|
|
|
func (b *boundedOutput) Write(p []byte) (int, error) {
|
|
n := len(p)
|
|
remaining := b.limit - b.Len()
|
|
if n > remaining {
|
|
b.overflow = true
|
|
p = p[:remaining]
|
|
}
|
|
_, _ = b.Buffer.Write(p)
|
|
return n, nil
|
|
}
|
|
|
|
// Messages preserves old sessions with native OutputFormat readback failures:
|
|
// the CLI export reads the local stored data without that HTTP encoder. It does
|
|
// not regenerate, repair the database, delete history or change conversations.
|
|
func (c *Connection) Messages(ctx context.Context, id string) ([]byte, error) {
|
|
if !sessionID.MatchString(id) {
|
|
return nil, fmt.Errorf("invalid session ID")
|
|
}
|
|
c.MessageReadbackDiagnostic = ""
|
|
data, err := c.Native(ctx, "get", "/session/"+id+"/message", nil)
|
|
if err == nil {
|
|
return data, nil
|
|
}
|
|
if !strings.Contains(err.Error(), "HTTP 400") || !strings.Contains(string(data), "Expected OutputFormat") {
|
|
return data, err
|
|
}
|
|
if ctx.Err() != nil {
|
|
return data, ctx.Err()
|
|
}
|
|
executable := c.Executable
|
|
if executable == "" {
|
|
executable = Executable()
|
|
}
|
|
cmd := exec.CommandContext(ctx, executable, "export", id)
|
|
cmd.Dir = c.Directory
|
|
stdout, stderr := &boundedOutput{limit: MaxResponse}, &boundedOutput{limit: 8 << 10}
|
|
cmd.Stdout = stdout
|
|
cmd.Stderr = stderr
|
|
if exportErr := cmd.Run(); exportErr != nil {
|
|
if ctx.Err() != nil {
|
|
return data, ctx.Err()
|
|
}
|
|
return data, fmt.Errorf("%w; read-only native export fallback failed", err)
|
|
}
|
|
if stdout.overflow {
|
|
return data, fmt.Errorf("%w; native export exceeds 1 MiB evidence limit", err)
|
|
}
|
|
var exported struct {
|
|
Info struct {
|
|
ID string `json:"id"`
|
|
} `json:"info"`
|
|
Messages json.RawMessage `json:"messages"`
|
|
}
|
|
if json.Unmarshal(stdout.Bytes(), &exported) != nil || exported.Info.ID != id || len(exported.Messages) == 0 || exported.Messages[0] != '[' {
|
|
return data, fmt.Errorf("%w; native export returned invalid or mismatched session evidence", err)
|
|
}
|
|
c.MessageReadbackDiagnostic = "Native HTTP message readback rejected stored OutputFormat (HTTP 400); read-only CLI export recovered the original messages without modifying the session."
|
|
return exported.Messages, nil
|
|
}
|