package server import ( "context" "errors" "strings" "time" "git.a-wan.net/alan/pipelines/internal/claude" "git.a-wan.net/alan/pipelines/internal/codex" "git.a-wan.net/alan/pipelines/internal/protocol" ) // chatExportLimit bounds an exported transcript. Older pages stop being read // once the newest history already fills it, and the file says so. const chatExportLimit = 8 << 20 // chatExportPageLimit bounds how many history pages one export reads. const chatExportPageLimit = 500 // chatNativeExporter is a harness that can hand back its own session file // cheaply (Claude Code's JSONL transcript). type chatNativeExporter interface { NativeExport(ctx context.Context, sessionID string) (protocol.ChatExportFile, error) } // NativeExport routes to the session's harness; only harnesses with a cheap // native file implement it. func (m *chatManager) NativeExport(ctx context.Context, sessionID string) (protocol.ChatExportFile, error) { adapter, err := m.brokerFor(ctx, sessionID) if err != nil { return protocol.ChatExportFile{}, err } exporter, ok := adapter.(chatNativeExporter) if !ok { return protocol.ChatExportFile{}, errors.New("this chat's harness has no native session export") } return exporter.NativeExport(ctx, sessionID) } // chatBackendName is the harness's display name. func chatBackendName(backend string) string { switch backend { case claude.Backend: return "Claude Code" case codex.Backend: return "Codex" case "", "opencode": return "OpenCode" default: return backend } } // chatResumeCommand is the terminal command that continues a session with the // harness's own CLI in its directory. Each form was checked against the CLI's // --help: `claude --resume ` (Claude Code 2.1), `codex resume ` (Codex // CLI 0.164) and `opencode --session ` (OpenCode 2.0). func chatResumeCommand(backend, sessionID, directory string) string { if !validChatSessionID(sessionID) { return "" } var command string switch backend { case claude.Backend: command = "claude --resume " + sessionID case codex.Backend: command = "codex resume " + sessionID case "", "opencode": command = "opencode --session " + sessionID default: return "" } if strings.TrimSpace(directory) == "" { return command } return "cd " + shellQuote(directory) + " && " + command } // chatNativeExportAvailable says chat_export format=native is offered. func chatNativeExportAvailable(backend string) bool { return backend == claude.Backend } // withChatHandoff fills the session's resume command and native export flag. func withChatHandoff(session protocol.ChatSession) protocol.ChatSession { session.ResumeCommand = chatResumeCommand(session.Backend, session.ID, session.Directory) session.NativeExport = chatNativeExportAvailable(session.Backend) return session } // shellQuote leaves a plain path as it is and single-quotes anything else. func shellQuote(value string) string { plain := value != "" for _, r := range value { if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("/._-+,:@%=", r)) { plain = false break } } if plain { return value } return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'" } // handleChatExport answers chat_export for one recorded operator session. func handleChatExport(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) { fail := func(message string) { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: message}) } if broker == nil { fail("chat is not configured on this server") return } if registry == nil { fail("operator session registry is not configured on this server") return } body := request.ChatExport if body == nil || !validChatSessionID(body.SessionID) { fail("a valid chat session id is required") return } format := strings.TrimSpace(body.Format) if format == "" { format = protocol.ChatExportMarkdown } switch format { case protocol.ChatExportMarkdown, protocol.ChatExportJSON, protocol.ChatExportNative: default: fail("chat export format must be markdown, json or native") return } row, found, err := registry.OperatorSession(ctx, body.SessionID) if err != nil { fail(err.Error()) return } if !found { fail("session " + body.SessionID + " is not an operator chat session") return } session := withChatHandoff(chatSessionFromOperator(row)) var file protocol.ChatExportFile if format == protocol.ChatExportNative { if !session.NativeExport { fail(chatBackendName(session.Backend) + " has no native session export") return } exporter, ok := broker.(chatNativeExporter) if !ok { fail("native session export is not available on this server") return } file, err = exporter.NativeExport(ctx, body.SessionID) if err != nil { fail(err.Error()) return } } else { messages, truncated, err := chatExportHistory(ctx, broker, body.SessionID) if err != nil { fail(err.Error()) return } transcript := chatExportTranscript{Session: session, Messages: messages, Truncated: truncated, ExportedAt: time.Now().UTC()} file, err = transcript.file(format) if err != nil { fail(err.Error()) return } } file.SessionID = body.SessionID file.Format = format _ = write(protocol.Message{Type: protocol.ChatExport, ID: request.ID, ChatExportFile: &file}) } // chatExportHistory reads the session's whole history, newest page first as // chat_messages serves it, and returns it oldest first. It stops reading older // pages once the bound is reached and reports that older turns were left out. func chatExportHistory(ctx context.Context, broker chatBroker, sessionID string) ([]protocol.ChatMessage, bool, error) { var pages [][]protocol.ChatMessage seen := map[string]bool{} size := 0 cursor := "" for page := 0; page < chatExportPageLimit; page++ { history, err := broker.Messages(ctx, sessionID, 100, cursor) if err != nil { return nil, false, err } kept := make([]protocol.ChatMessage, 0, len(history.Messages)) for _, message := range history.Messages { if message.ID != "" && seen[message.ID] { continue } seen[message.ID] = true kept = append(kept, message) size += chatMessageSize(message) } pages = append(pages, kept) next := history.NextCursor if next == "" || next == cursor { return flattenChatPages(pages), false, nil } if size >= chatExportLimit { return flattenChatPages(pages), true, nil } cursor = next } return flattenChatPages(pages), true, nil } func flattenChatPages(pages [][]protocol.ChatMessage) []protocol.ChatMessage { out := []protocol.ChatMessage{} for index := len(pages) - 1; index >= 0; index-- { out = append(out, pages[index]...) } return out } func chatMessageSize(message protocol.ChatMessage) int { size := 0 for _, part := range message.Parts { size += len(part.Text) + len(part.Name) + 64 } return size }