package opencode import ( "encoding/json" "fmt" "os" "path/filepath" "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) { path, err := ServiceCredentialPath() if err != nil { return nil, err } return serviceConnection(path, directory) } // serviceConnection reads only the existing CLI-managed service. Chat endpoint // overrides belong to a different transport and must never redirect stage work. func serviceConnection(path, directory string) (*Connection, error) { path, err := filepath.Abs(path) if err != nil { return nil, fmt.Errorf("invalid local OpenCode credential path") } if err := checkPrivateFile(path, serviceCredentialLimit); err != nil { return nil, fmt.Errorf("cannot read the local OpenCode service credential") } data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("cannot read the local OpenCode endpoint") } var state struct{ URL, Password string } if json.Unmarshal(data, &state) != nil || strings.TrimSpace(state.Password) == "" { return nil, fmt.Errorf("invalid local OpenCode endpoint") } base, err := NormalizeEndpointURL(state.URL) if err != nil { return nil, fmt.Errorf("invalid local OpenCode endpoint") } return &Connection{Backend: "v2", URL: base, Directory: directory, password: strings.TrimSpace(state.Password), credentialFile: path}, 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 }