Files
pipelines/internal/opencode/export_endpoint.go
T

74 lines
2.1 KiB
Go

package opencode
import (
"encoding/json"
"fmt"
"os"
"strings"
)
// sessionExportConnection reads existing endpoint/auth configuration only. It
// never discovers by starting a CLI, serves a new backend, or pairs credentials.
// Callers already holding the exact connection should pass it to ExportSession.
func sessionExportConnection(directory string) (*Connection, error) {
endpoint := strings.TrimSpace(os.Getenv(EndpointEnvKey))
password, err := ReadEndpointCredentialFile(os.Getenv(EndpointPasswordFileEnvKey))
if err != nil {
return nil, err
}
if endpoint == "" || password == "" {
path, err := ServiceCredentialPath()
if err != nil {
return nil, err
}
credential, err := ReadServiceCredential(path)
if err != nil {
return nil, err
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("cannot read the local OpenCode endpoint")
}
var state struct {
URL string `json:"url"`
}
if json.Unmarshal(data, &state) != nil {
return nil, fmt.Errorf("invalid local OpenCode endpoint")
}
base, err := NormalizeEndpointURL(state.URL)
if err != nil {
return nil, fmt.Errorf("invalid local OpenCode endpoint")
}
if endpoint == "" {
endpoint = base
} else {
configured, err := NormalizeEndpointURL(endpoint)
if err != nil || configured != base {
return nil, fmt.Errorf("session export endpoint requires its own credential")
}
}
if password == "" {
password = credential
}
}
base, err := NormalizeEndpointURL(endpoint)
if err != nil {
return nil, err
}
return &Connection{Backend: "v2", URL: base, Directory: directory, password: password,
username: strings.TrimSpace(os.Getenv(EndpointUsernameEnvKey))}, nil
}
// UnmarshalJSON retains the complete stored turn, including unknown metadata
// and inline image attachments, independently of the chat UI projection.
func (m *nativeChatMessage) UnmarshalJSON(data []byte) error {
type message nativeChatMessage
var decoded message
if err := json.Unmarshal(data, &decoded); err != nil {
return err
}
*m = nativeChatMessage(decoded)
m.Raw = append(json.RawMessage(nil), data...)
return nil
}