rho-coding-agent 0.26.0

A lightweight agent harness inspired by Pi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! Render saved sessions as self-contained HTML transcripts.
//!
//! Consumes [`SessionExport`] data from the session store and produces a
//! single HTML file with embedded styles: user prompts as plain text,
//! assistant text as rendered markdown, and tool calls paired with their
//! outputs in collapsible blocks.

use std::{
    collections::{HashMap, HashSet},
    fmt::Write as _,
    fs,
    io::Write as _,
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

use crate::{
    model::{ContentBlock, ImageContent, Message},
    session::{ExportedMessage, Session, SessionExport},
    tool::{ToolCall, ToolResult},
};

#[cfg(test)]
#[path = "export_tests.rs"]
mod tests;

/// Tool outputs at most this many lines render expanded; longer ones start
/// collapsed so the transcript stays skimmable.
const TOOL_OUTPUT_EXPANDED_MAX_LINES: usize = 24;
const TOOL_ARGUMENT_PREVIEW_MAX_CHARS: usize = 80;

/// Load the session matching `id_prefix`, render it, and write the HTML file.
///
/// `path_arg` is the raw `/export` argument: empty selects a default file name
/// in `cwd`, a directory receives the default file name, and anything else is
/// used as the output file path (relative paths resolve against `cwd`).
pub fn write_session_html(cwd: &Path, id_prefix: &str, path_arg: &str) -> anyhow::Result<PathBuf> {
    let export = Session::export_by_id(cwd, id_prefix)?;
    write_export_html(cwd, path_arg, &export)
}

pub(crate) fn write_export_html(
    cwd: &Path,
    path_arg: &str,
    export: &SessionExport,
) -> anyhow::Result<PathBuf> {
    let path = resolve_output_path(cwd, path_arg, &export.id);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let rendered = render_html(export);
    let mut options = fs::OpenOptions::new();
    options.create(true).write(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut file = options.open(&path)?;
    set_private_file_permissions(&file)?;
    file.write_all(rendered.as_bytes())?;
    Ok(path)
}

fn set_private_file_permissions(file: &fs::File) -> anyhow::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        file.set_permissions(fs::Permissions::from_mode(0o600))?;
    }
    #[cfg(not(unix))]
    {
        let _ = file;
    }
    Ok(())
}

pub(crate) fn resolve_output_path(cwd: &Path, path_arg: &str, session_id: &str) -> PathBuf {
    let short_id: String = session_id.chars().take(8).collect();
    let default_name = format!("rho-session-{short_id}.html");
    let path_arg = path_arg.trim();
    if path_arg.is_empty() {
        return cwd.join(default_name);
    }
    let path = PathBuf::from(path_arg);
    let path = if path.is_absolute() {
        path
    } else {
        cwd.join(path)
    };
    if path.is_dir() {
        path.join(default_name)
    } else {
        path
    }
}

pub(crate) fn render_html(export: &SessionExport) -> String {
    let title = export.title.as_deref().unwrap_or("rho session");
    let mut html = String::new();
    html.push_str("<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n");
    html.push_str("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n");
    let _ = writeln!(html, "<title>{}</title>", escape_html(title));
    html.push_str("<style>\n");
    html.push_str(STYLE);
    html.push_str("</style>\n</head>\n<body>\n");
    push_header(&mut html, export, title);
    html.push_str("<main>\n");
    push_messages(&mut html, &export.messages);
    html.push_str("</main>\n<script>\n");
    html.push_str(SCRIPT);
    html.push_str("</script>\n</body>\n</html>\n");
    html
}

fn push_header(html: &mut String, export: &SessionExport, title: &str) {
    html.push_str("<header>\n");
    html.push_str(
        "<p class=\"brand\"><span class=\"brand-mark\">ρ</span> session transcript</p>\n",
    );
    let _ = writeln!(html, "<h1>{}</h1>", escape_html(title));
    html.push_str("<dl class=\"meta\">\n");
    push_meta_row(html, "session", &export.id);
    // Transcripts are meant to be shared; the workspace directory name
    // identifies the project without leaking the local filesystem layout.
    let project = export.cwd.file_name().map_or_else(
        || export.cwd.display().to_string(),
        |name| name.to_string_lossy().into_owned(),
    );
    push_meta_row(html, "project", &project);
    push_meta_row(html, "created", &format_datetime(export.created_at));
    push_meta_row(html, "updated", &format_datetime(export.updated_at));
    push_meta_row(html, "messages", &export.messages.len().to_string());
    let exported = format!(
        "{} by rho v{}",
        format_datetime(now_unix_secs()),
        env!("CARGO_PKG_VERSION")
    );
    push_meta_row(html, "exported", &exported);
    html.push_str("</dl>\n</header>\n");
}

fn push_meta_row(html: &mut String, label: &str, value: &str) {
    let _ = writeln!(
        html,
        "<div><dt>{}</dt><dd>{}</dd></div>",
        escape_html(label),
        escape_html(value)
    );
}

fn push_messages(html: &mut String, messages: &[ExportedMessage]) {
    let mut results_by_id: HashMap<&str, &ToolResult> = HashMap::new();
    let mut called_ids: HashSet<&str> = HashSet::new();
    for entry in messages {
        match &entry.message {
            Message::ToolResult(result) => {
                results_by_id.entry(result.id.as_str()).or_insert(result);
            }
            Message::Assistant(blocks) => {
                for block in blocks {
                    if let ContentBlock::ToolCall(call) = block {
                        called_ids.insert(call.id.as_str());
                    }
                }
            }
            Message::System(_) | Message::User(_) => {}
        }
    }

    // Consecutive turns by the same speaker share one role head so the
    // transcript reads as exchanges, not a stack of identical blocks.
    let mut previous_role: Option<&str> = None;
    for entry in messages {
        match &entry.message {
            Message::System(text) => {
                push_system(html, text);
                previous_role = None;
            }
            Message::User(blocks) => {
                let continuation = previous_role == Some("user");
                push_user(html, entry.timestamp, blocks, continuation);
                previous_role = Some("user");
            }
            Message::Assistant(blocks) => {
                let continuation = previous_role == Some("assistant");
                push_assistant(html, entry.timestamp, blocks, &results_by_id, continuation);
                previous_role = Some("assistant");
            }
            // Rendered inline with the tool call that produced it; the
            // speaker run continues across it.
            Message::ToolResult(result) if called_ids.contains(result.id.as_str()) => {}
            Message::ToolResult(result) => {
                push_tool_call(html, None, Some(result));
                previous_role = None;
            }
        }
    }
}

fn push_system(html: &mut String, text: &str) {
    html.push_str("<details class=\"system\">\n<summary>System prompt</summary>\n");
    let _ = writeln!(html, "<pre>{}</pre>", escape_html(text));
    html.push_str("</details>\n");
}

fn push_user(
    html: &mut String,
    timestamp: Option<u64>,
    blocks: &[ContentBlock],
    continuation: bool,
) {
    let cont_class = if continuation { " cont" } else { "" };
    let _ = writeln!(html, "<section class=\"entry user{cont_class}\">");
    if !continuation {
        push_entry_head(html, "you", timestamp);
    }
    for block in blocks {
        match block {
            ContentBlock::Text(text) => {
                let _ = writeln!(html, "<div class=\"plain\">{}</div>", escape_html(text));
            }
            ContentBlock::Image(image) => push_image(html, image),
            // User messages never carry tool calls; keep the transcript
            // complete if one ever appears.
            ContentBlock::ToolCall(call) => push_tool_call(html, Some(call), None),
        }
    }
    html.push_str("</section>\n");
}

fn push_assistant(
    html: &mut String,
    timestamp: Option<u64>,
    blocks: &[ContentBlock],
    results_by_id: &HashMap<&str, &ToolResult>,
    continuation: bool,
) {
    let cont_class = if continuation { " cont" } else { "" };
    let _ = writeln!(html, "<section class=\"entry assistant{cont_class}\">");
    if !continuation {
        push_entry_head(html, "rho", timestamp);
    }
    for block in blocks {
        match block {
            ContentBlock::Text(text) => {
                let _ = writeln!(
                    html,
                    "<div class=\"markdown\">{}</div>",
                    markdown_to_html(text)
                );
            }
            ContentBlock::Image(image) => push_image(html, image),
            ContentBlock::ToolCall(call) => push_tool_call(
                html,
                Some(call),
                results_by_id.get(call.id.as_str()).copied(),
            ),
        }
    }
    html.push_str("</section>\n");
}

fn push_entry_head(html: &mut String, role: &str, timestamp: Option<u64>) {
    html.push_str("<div class=\"entry-head\">");
    let _ = write!(html, "<span class=\"role\">{}</span>", escape_html(role));
    if let Some(timestamp) = timestamp {
        let _ = write!(
            html,
            "<time title=\"{}\">{}</time>",
            escape_html(&format_datetime(timestamp)),
            escape_html(&format_clock(timestamp))
        );
    }
    html.push_str("</div>\n");
}

fn push_image(html: &mut String, image: &ImageContent) {
    let _ = writeln!(
        html,
        "<img class=\"attachment\" alt=\"attached image\" src=\"data:{};base64,{}\">",
        escape_html(&image.mime_type),
        escape_html(&image.data)
    );
}

fn push_tool_call(html: &mut String, call: Option<&ToolCall>, result: Option<&ToolResult>) {
    let (status_class, status_label) = match result {
        Some(result) if result.ok => ("ok", "ok"),
        Some(_) => ("err", "error"),
        None => ("pending", "no result"),
    };
    let output_lines = result.map_or(0, |result| result.content.lines().count());
    let open_attribute = if output_lines <= TOOL_OUTPUT_EXPANDED_MAX_LINES {
        " open"
    } else {
        ""
    };
    let name = call.map_or("tool result", |call| call.name.as_str());

    let _ = write!(html, "<details class=\"tool\"{open_attribute}>\n<summary>");
    let _ = write!(
        html,
        "<span class=\"tool-name\">{}</span>",
        escape_html(name)
    );
    if let Some(call) = call {
        let _ = write!(
            html,
            "<span class=\"tool-preview\">{}</span>",
            escape_html(&argument_preview(call))
        );
    }
    let _ = writeln!(
        html,
        "<span class=\"status {status_class}\">{status_label}</span></summary>"
    );
    html.push_str("<div class=\"tool-body\">\n");
    if let Some(call) = call {
        html.push_str("<div class=\"tool-section\">arguments</div>\n");
        let arguments = serde_json::to_string_pretty(&call.arguments)
            .unwrap_or_else(|_| call.arguments.to_string());
        let _ = writeln!(
            html,
            "<pre class=\"tool-args\">{}</pre>",
            escape_html(&arguments)
        );
    }
    if let Some(result) = result {
        html.push_str("<div class=\"tool-section\">output</div>\n");
        if result.content.is_empty() {
            html.push_str("<pre class=\"tool-output empty\">(no output)</pre>\n");
        } else {
            let _ = writeln!(
                html,
                "<pre class=\"tool-output\">{}</pre>",
                escape_html(&result.content)
            );
        }
    }
    html.push_str("</div>\n</details>\n");
}

/// Argument fields that make a good one-line summary, in priority order.
const PREVIEW_KEYS: [&str; 8] = [
    "command",
    "file_path",
    "path",
    "pattern",
    "query",
    "url",
    "description",
    "prompt",
];

fn argument_preview(call: &ToolCall) -> String {
    let picked = call.arguments.as_object().and_then(|fields| {
        PREVIEW_KEYS
            .iter()
            .find_map(|key| fields.get(*key).and_then(|value| value.as_str()))
            .or_else(|| {
                (fields.len() == 1)
                    .then(|| fields.values().next().and_then(|value| value.as_str()))
                    .flatten()
            })
    });
    let full = match picked {
        Some(text) => text.split_whitespace().collect::<Vec<_>>().join(" "),
        None => serde_json::to_string(&call.arguments).unwrap_or_default(),
    };
    let mut preview: String = full.chars().take(TOOL_ARGUMENT_PREVIEW_MAX_CHARS).collect();
    if preview.chars().count() < full.chars().count() {
        preview.push('');
    }
    preview
}

fn markdown_to_html(text: &str) -> String {
    use pulldown_cmark::{html, Event, Options, Parser};

    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TASKLISTS);
    let parser = Parser::new_ext(text, options).map(|event| match event {
        Event::Html(raw) | Event::InlineHtml(raw) => Event::Text(raw),
        event => event,
    });
    let mut rendered = String::new();
    html::push_html(&mut rendered, parser);
    rendered
}

fn escape_html(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&#39;"),
            _ => escaped.push(ch),
        }
    }
    escaped
}

fn format_datetime(unix_secs: u64) -> String {
    local_datetime(unix_secs).map_or_else(
        || unix_secs.to_string(),
        |time| time.format("%Y-%m-%d %H:%M:%S").to_string(),
    )
}

fn format_clock(unix_secs: u64) -> String {
    local_datetime(unix_secs).map_or_else(
        || unix_secs.to_string(),
        |time| time.format("%H:%M:%S").to_string(),
    )
}

fn local_datetime(unix_secs: u64) -> Option<chrono::DateTime<chrono::Local>> {
    let timestamp = i64::try_from(unix_secs).ok()?;
    Some(chrono::DateTime::from_timestamp(timestamp, 0)?.with_timezone(&chrono::Local))
}

fn now_unix_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .unwrap_or_default()
}

const STYLE: &str = r#"
:root {
  color-scheme: light dark;
  --bg: oklch(100% 0 0);
  --surface: oklch(96.5% 0.004 20);
  --well: oklch(93% 0.006 20);
  --ink: oklch(24% 0.012 20);
  --muted: oklch(50% 0.02 20);
  --line: oklch(90% 0.008 20);
  --brand: oklch(42% 0.125 18);
  --user-bg: oklch(96.6% 0.013 18);
  --ok: oklch(52% 0.12 150);
  --err: oklch(50% 0.17 27);
  --font-sans: ui-sans-serif, system-ui, "Segoe UI", Roboto, sans-serif;
  --font-mono: ui-monospace, "SF Mono", "Cascadia Code", Menlo, Consolas, monospace;
}
@media (prefers-color-scheme: dark) {
  :root {
    --bg: oklch(15.5% 0 0);
    --surface: oklch(20.5% 0 0);
    --well: oklch(12.5% 0 0);
    --ink: oklch(90% 0.006 20);
    --muted: oklch(67% 0.012 20);
    --line: oklch(28.5% 0 0);
    --brand: oklch(72% 0.1 18);
    --user-bg: oklch(23% 0.02 18);
    --ok: oklch(72% 0.13 150);
    --err: oklch(70% 0.15 27);
  }
}
* { box-sizing: border-box; }
::selection { background: color-mix(in oklab, var(--brand) 22%, var(--bg)); }
body {
  margin: 0 auto;
  padding: 2.75rem 1.25rem 5rem;
  max-width: 45rem;
  background: var(--bg);
  color: var(--ink);
  font: 16px/1.65 var(--font-sans);
}
header { margin-bottom: 2.75rem; }
header .brand {
  margin: 0 0 1rem;
  font: 500 0.8125rem/1 var(--font-mono);
  color: var(--brand);
}
header .brand-mark { font-size: 1.0625rem; margin-right: 0.125rem; }
header h1 {
  margin: 0 0 1.25rem;
  font-size: 1.75rem;
  font-weight: 700;
  line-height: 1.25;
  letter-spacing: -0.015em;
  text-wrap: balance;
}
dl.meta {
  margin: 0;
  padding: 0.875rem 0;
  border-block: 1px solid var(--line);
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(19rem, 1fr));
  gap: 0.375rem 2rem;
  font-size: 0.8125rem;
}
dl.meta div { display: flex; gap: 0.75rem; min-width: 0; align-items: baseline; }
dl.meta dt { color: var(--muted); flex: none; width: 5.25rem; }
dl.meta dd { margin: 0; overflow-wrap: anywhere; font: 0.75rem/1.6 var(--font-mono); }
.controls { display: flex; gap: 0.5rem; margin-top: 1rem; }
.controls button {
  font: 500 0.75rem/1 var(--font-mono);
  color: var(--muted);
  background: none;
  border: 1px solid var(--line);
  border-radius: 999px;
  padding: 0.4375rem 0.875rem;
  cursor: pointer;
  transition: color 0.15s, border-color 0.15s, background-color 0.15s;
}
.controls button:hover { color: var(--ink); border-color: var(--muted); }
.controls button:active { background: var(--surface); }
.controls button:focus-visible { outline: 2px solid var(--brand); outline-offset: 2px; }
main { display: flex; flex-direction: column; gap: 1.25rem; }
.entry.user {
  background: var(--user-bg);
  border-radius: 12px;
  padding: 0.875rem 1.125rem 1rem;
}
main > .entry.user:not(:first-child) { margin-top: 1.25rem; }
.entry.cont { margin-top: -0.5rem; }
.entry-head {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  gap: 1rem;
  margin-bottom: 0.375rem;
}
.entry-head .role { font: 600 0.75rem/1 var(--font-mono); }
.entry.user .role { color: var(--brand); }
.entry.assistant .role { color: var(--muted); }
.entry-head time { font: 0.6875rem/1 var(--font-mono); color: var(--muted); }
.plain { white-space: pre-wrap; overflow-wrap: anywhere; }
img.attachment {
  max-width: 100%;
  border: 1px solid var(--line);
  border-radius: 8px;
  margin: 0.5rem 0;
}
pre {
  background: var(--surface);
  border-radius: 8px;
  padding: 0.75rem 0.875rem;
  overflow-x: auto;
  font: 0.8125rem/1.55 var(--font-mono);
  white-space: pre-wrap;
  overflow-wrap: anywhere;
}
code {
  background: var(--surface);
  border-radius: 4px;
  padding: 0.125rem 0.3125rem;
  font: 0.875em var(--font-mono);
}
pre code { background: none; padding: 0; font: inherit; }
details.system, details.tool {
  background: var(--surface);
  border-radius: 10px;
  overflow: hidden;
}
details.tool { margin: 0.625rem 0; }
details.system > summary, details.tool > summary {
  cursor: pointer;
  list-style: none;
  display: flex;
  align-items: baseline;
  gap: 0.625rem;
  padding: 0.5625rem 0.875rem;
  font: 0.75rem/1.5 var(--font-mono);
  color: var(--muted);
  transition: background-color 0.15s ease-out;
}
details.system > summary::-webkit-details-marker,
details.tool > summary::-webkit-details-marker { display: none; }
details.system > summary:hover, details.tool > summary:hover { background: var(--well); }
details.system > summary:focus-visible, details.tool > summary:focus-visible {
  outline: 2px solid var(--brand);
  outline-offset: -2px;
}
details.system > summary::before, details.tool > summary::before {
  content: "";
  flex: none;
  align-self: center;
  width: 0.3125rem;
  height: 0.3125rem;
  border-right: 1.5px solid currentColor;
  border-bottom: 1.5px solid currentColor;
  transform: rotate(-45deg);
  transition: transform 0.15s ease-out;
}
details[open] > summary::before { transform: rotate(45deg); }
details.tool > summary .tool-name { font-weight: 600; color: var(--ink); }
details.tool > summary .tool-preview {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
details.tool > summary .status {
  flex: none;
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  font-size: 0.6875rem;
  font-weight: 600;
}
details.tool > summary .status::before {
  content: "";
  width: 0.375rem;
  height: 0.375rem;
  border-radius: 50%;
  background: currentColor;
}
.status.ok { color: var(--ok); }
.status.err { color: var(--err); }
.status.pending { color: var(--muted); }
.tool-body { padding: 0.25rem 0.875rem 0.75rem; border-top: 1px solid var(--line); }
.tool-body pre { background: var(--well); margin: 0; }
.tool-section {
  font: 600 0.6875rem/1 var(--font-mono);
  color: var(--muted);
  margin: 0.625rem 0 0.375rem;
}
.tool-output.empty { color: var(--muted); font-style: italic; }
details.system > pre { margin: 0 0.875rem 0.75rem; background: var(--well); }
.markdown > :first-child { margin-top: 0; }
.markdown > :last-child { margin-bottom: 0; }
.markdown h1, .markdown h2, .markdown h3 { margin: 1.5rem 0 0.5rem; line-height: 1.3; }
.markdown h1 { font-size: 1.25rem; }
.markdown h2 { font-size: 1.125rem; }
.markdown h3 { font-size: 1rem; }
.markdown blockquote {
  margin: 0.5rem 0;
  padding: 0.25rem 1rem;
  border-left: 1px solid var(--muted);
  color: var(--muted);
}
.markdown table { border-collapse: collapse; display: block; overflow-x: auto; }
.markdown th, .markdown td { border: 1px solid var(--line); padding: 0.375rem 0.75rem; }
.markdown th { background: var(--surface); }
.markdown a { color: var(--brand); text-underline-offset: 2px; }
.markdown hr { border: none; border-top: 1px solid var(--line); }
@media (prefers-reduced-motion: reduce) {
  * { transition: none !important; }
}
@media print {
  body { max-width: none; padding: 0; }
  .controls { display: none; }
  details.system, details.tool { break-inside: avoid; }
}
"#;

/// Injects the expand/collapse-all controls; without JavaScript the
/// transcript renders complete and the controls simply never appear.
const SCRIPT: &str = r#"
(function () {
  var tools = document.querySelectorAll("details.tool");
  if (tools.length === 0) return;
  var controls = document.createElement("div");
  controls.className = "controls";
  [["expand all", true], ["collapse all", false]].forEach(function (pair) {
    var button = document.createElement("button");
    button.type = "button";
    button.textContent = pair[0];
    button.addEventListener("click", function () {
      tools.forEach(function (tool) { tool.open = pair[1]; });
    });
    controls.appendChild(button);
  });
  document.querySelector("header").appendChild(controls);
})();
"#;