package opencode import ( "bytes" "context" "encoding/json" "errors" "fmt" "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 := 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() } // Keep the original HTTP-400/OutputFormat evidence identity while also // preserving exec.ErrWaitDelay from a descendant-held output pipe. return data, errors.Join(err, fmt.Errorf("read-only native export fallback failed: %w", exportErr)) } 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 }