| 1 | //! Structured JSON rendering of a conversation export. |
| 2 | //! |
| 3 | //! The document is built from the same sanitized projection as the Markdown |
| 4 | //! and HTML renderings and is lossless about message roles and block kinds: |
| 5 | //! a tool result keeps the `user` role it travels under, and omitted content |
| 6 | //! is flagged instead of dropped. Payload values pass through the shared JSON |
| 7 | //! redactor; the envelope is written by this module and is not redacted by |
| 8 | //! key. Workspace restore points are not part of the document. |
| 9 | |
| 10 | use std::collections::HashMap; |
| 11 | |
| 12 | use codewhale_command_contract::facets::{ |
| 13 | ConversationExportProjection, ExportBlock, ExportMessage, ExportTurnOutcome, HistoryEntry, |
| 14 | TranscriptProjection, |
| 15 | }; |
| 16 | use codewhale_sanitize::sanitize::{ |
| 17 | is_internal_role, redact_json, redact_url_for_display, sanitize_text, |
| 18 | }; |
| 19 | use serde_json::{Value, json}; |
| 20 | |
| 21 | use super::export::{OMISSION_NOTE, format_export_time, tool_names}; |
| 22 | |
| 23 | const FORMAT_NAME: &str = "codewhale-conversation-export"; |
| 24 | const FORMAT_VERSION: u32 = 1; |
| 25 | |
| 26 | pub(super) fn render(projection: ConversationExportProjection) -> String { |
| 27 | let ConversationExportProjection { |
| 28 | metadata, |
| 29 | transcript, |
| 30 | restore_points: _, |
| 31 | turn_outcomes, |
| 32 | } = projection; |
| 33 | let names = tool_names(&transcript); |
| 34 | let (transcript_kind, messages) = match transcript { |
| 35 | TranscriptProjection::Authoritative(messages) => ( |
| 36 | "authoritative", |
| 37 | messages |
| 38 | .into_iter() |
| 39 | .enumerate() |
| 40 | .map(|(index, message)| message_json(index + 1, message, &names)) |
| 41 | .collect::<Vec<_>>(), |
| 42 | ), |
| 43 | TranscriptProjection::HistoryFallback(entries) => ( |
| 44 | "history_fallback", |
| 45 | entries |
| 46 | .into_iter() |
| 47 | .enumerate() |
| 48 | .map(|(index, entry)| entry_json(index + 1, entry)) |
| 49 | .collect::<Vec<_>>(), |
| 50 | ), |
| 51 | }; |
| 52 | let turn_outcomes: Vec<Value> = turn_outcomes.into_iter().map(turn_outcome_json).collect(); |
| 53 | let mut document = json!({ |
| 54 | "format": FORMAT_NAME, |
| 55 | "format_version": FORMAT_VERSION, |
| 56 | "generator": { |
| 57 | "name": "codewhale", |
| 58 | "version": env!("CARGO_PKG_VERSION"), |
| 59 | }, |
| 60 | "exported_at": format_export_time(metadata.exported_at_unix), |
| 61 | "session": { |
| 62 | "label": sanitize_text(&metadata.session_label), |
| 63 | "title": metadata.title.as_deref().map(sanitize_text), |
| 64 | "provider": sanitize_text(&metadata.provider), |
| 65 | "model": sanitize_text(&metadata.model), |
| 66 | "mode": sanitize_text(&metadata.mode), |
| 67 | "workspace": sanitize_text(&metadata.workspace_name), |
| 68 | "message_count": metadata.message_count, |
| 69 | }, |
| 70 | "transcript": transcript_kind, |
| 71 | "notice": OMISSION_NOTE, |
| 72 | "messages": messages, |
| 73 | }); |
| 74 | if !turn_outcomes.is_empty() { |
| 75 | document["turn_outcomes"] = Value::Array(turn_outcomes); |
| 76 | } |
| 77 | serde_json::to_string_pretty(&document).unwrap_or_else(|_| "{}".to_string()) |
| 78 | } |
| 79 | |
| 80 | fn turn_outcome_json(outcome: ExportTurnOutcome) -> Value { |
| 81 | let status = sanitize_text(&outcome.status); |
| 82 | let status = if status.trim().is_empty() { |
| 83 | "failed".to_string() |
| 84 | } else { |
| 85 | status |
| 86 | }; |
| 87 | let mut value = json!({ |
| 88 | "status": status, |
| 89 | "ended_at": format_export_time(outcome.ended_at_unix), |
| 90 | "after_message_count": outcome.after_message_count, |
| 91 | "error": sanitize_text(&outcome.error), |
| 92 | }); |
| 93 | if let Some(code) = outcome |
| 94 | .code |
| 95 | .as_deref() |
| 96 | .map(sanitize_text) |
| 97 | .filter(|code| !code.trim().is_empty()) |
| 98 | { |
| 99 | value["code"] = Value::String(code); |
| 100 | } |
| 101 | value |
| 102 | } |
| 103 | |
| 104 | fn message_json(index: usize, message: ExportMessage, names: &HashMap<String, String>) -> Value { |
| 105 | let role = sanitize_text(&message.role); |
| 106 | if is_internal_role(&message.role) { |
| 107 | return json!({ "index": index, "role": role, "omitted": true, "blocks": [] }); |
| 108 | } |
| 109 | let blocks: Vec<Value> = message |
| 110 | .blocks |
| 111 | .into_iter() |
| 112 | .map(|block| block_json(block, names)) |
| 113 | .collect(); |
| 114 | json!({ "index": index, "role": role, "blocks": blocks }) |
| 115 | } |
| 116 | |
| 117 | fn entry_json(index: usize, entry: HistoryEntry) -> Value { |
| 118 | let (role, text) = match entry { |
| 119 | HistoryEntry::Sanitized { role, body } => (role, sanitize_text(&body)), |
| 120 | HistoryEntry::Literal { role, body } => (role, body), |
| 121 | }; |
| 122 | json!({ |
| 123 | "index": index, |
| 124 | "role": sanitize_text(&role), |
| 125 | "blocks": [{ "type": "text", "text": text }], |
| 126 | }) |
| 127 | } |
| 128 | |
| 129 | fn block_json(block: ExportBlock, names: &HashMap<String, String>) -> Value { |
| 130 | match block { |
| 131 | ExportBlock::Text { text } => json!({ "type": "text", "text": sanitize_text(&text) }), |
| 132 | ExportBlock::ImageReference { url } => json!({ |
| 133 | "type": "image", |
| 134 | "url": sanitize_text(&redact_url_for_display(&url)), |
| 135 | }), |
| 136 | ExportBlock::ImageOmitted => json!({ "type": "image", "omitted": true }), |
| 137 | ExportBlock::InternalReasoning => json!({ "type": "reasoning", "omitted": true }), |
| 138 | ExportBlock::ToolCall { |
| 139 | id, |
| 140 | name, |
| 141 | caller, |
| 142 | input, |
| 143 | } => { |
| 144 | let mut value = json!({ |
| 145 | "type": "tool_use", |
| 146 | "id": sanitize_text(&id), |
| 147 | "name": sanitize_text(&name), |
| 148 | "input": redacted(input), |
| 149 | }); |
| 150 | if let Some(caller) = caller { |
| 151 | value["caller"] = json!({ |
| 152 | "type": sanitize_text(&caller.caller_type), |
| 153 | "tool_id": caller.tool_id.as_deref().map(sanitize_text), |
| 154 | }); |
| 155 | } |
| 156 | value |
| 157 | } |
| 158 | ExportBlock::ToolResult { |
| 159 | tool_use_id, |
| 160 | content, |
| 161 | is_error, |
| 162 | structured, |
| 163 | } => { |
| 164 | let mut value = json!({ |
| 165 | "type": "tool_result", |
| 166 | "tool_use_id": sanitize_text(&tool_use_id), |
| 167 | "is_error": is_error, |
| 168 | "content": sanitize_text(&content), |
| 169 | }); |
| 170 | if let Some(name) = names.get(&tool_use_id) { |
| 171 | value["name"] = Value::String(sanitize_text(name)); |
| 172 | } |
| 173 | if let Some(structured) = structured { |
| 174 | value["structured"] = redacted(structured); |
| 175 | } |
| 176 | value |
| 177 | } |
| 178 | ExportBlock::ServerToolCall { id, name, input } => json!({ |
| 179 | "type": "server_tool_use", |
| 180 | "id": sanitize_text(&id), |
| 181 | "name": sanitize_text(&name), |
| 182 | "input": redacted(input), |
| 183 | }), |
| 184 | ExportBlock::ToolSearchResult { |
| 185 | tool_use_id, |
| 186 | content, |
| 187 | } => json!({ |
| 188 | "type": "tool_search_result", |
| 189 | "tool_use_id": sanitize_text(&tool_use_id), |
| 190 | "content": redacted(content), |
| 191 | }), |
| 192 | ExportBlock::CodeExecutionResult { |
| 193 | tool_use_id, |
| 194 | content, |
| 195 | } => json!({ |
| 196 | "type": "code_execution_result", |
| 197 | "tool_use_id": sanitize_text(&tool_use_id), |
| 198 | "content": redacted(content), |
| 199 | }), |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | fn redacted(mut value: Value) -> Value { |
| 204 | redact_json(&mut value, None); |
| 205 | value |
| 206 | } |
| 207 |