rpi-cli 0.9.1

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Session switching, import, fork, sharing, and transcript history rendering.

use super::*;

/// `/share`: mirror the TS intent (share the session). With the `gh` CLI on
/// PATH, create a gist of the exported markdown; otherwise fall back to the
/// clipboard (best-effort) and note the local path.
pub(super) async fn share_session(harness: &AgentHarness, chat: &Arc<Container>) {
    use std::process::Stdio;

    // Reuse the export builder for the transcript text.
    let tree = harness.session().view("main");
    let entries = match tree
        .find_entries(&EntryQuery {
            entry_type: None,
            custom_type: None,
            // Exports append entries top-to-bottom, so use chronological order
            // instead of the session query default (newest-first).
            order: Some(EntryOrder::OldestFirst),
            limit: None,
            cursor: None,
        })
        .await
    {
        Ok(e) => e,
        Err(e) => {
            add_error_message(chat, &format!("Could not read session: {e}"));
            return;
        }
    };
    let mut md = String::from("# Session\n\n");
    for e in entries {
        let Entry::Message(me) = e else { continue };
        match &me.message {
            AgentMessage::User(u) => {
                md.push_str(&format!("## User\n\n{}\n\n", user_message_text(u)));
            }
            AgentMessage::Assistant(a) => {
                let text = assistant_text(a);
                if !text.is_empty() {
                    md.push_str(&format!("## Assistant\n\n{}\n\n", text));
                }
            }
            _ => {}
        }
    }

    // `gh gist create` — stdin-piped, best-effort; only when gh exists.
    let gh = std::process::Command::new("gh")
        .arg("gist")
        .arg("create")
        .arg("--filename")
        .arg("session.md")
        .arg("-")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn();
    if let Ok(mut child) = gh {
        use std::io::Write;
        if let Some(mut stdin) = child.stdin.take() {
            let _ = stdin.write_all(md.as_bytes());
            let _ = stdin.flush();
        }
        let out = child.wait_with_output().ok();
        if let Some(out) = out {
            if out.status.success() {
                let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
                add_note_message(chat, &format!("Shared session: {url}"));
                return;
            }
        }
        add_note_message(chat, "gh gist failed — falling back to the clipboard.");
    } else {
        add_note_message(chat, "gh CLI not found — falling back to the clipboard.");
    }
    // Clipboard fallback (or transcript echo when the clipboard feature is off).
    if copy_to_clipboard(&md) {
        add_note_message(chat, "Session transcript copied to the clipboard.");
    } else {
        add_note_message(
            chat,
            "Clipboard unavailable — use /export to write the transcript to a file.",
        );
    }
}

// Session export is driven through the product-layer `AgentSession`
// (`crate::agent_session`), which owns format selection + default filenames —
// the TUI loop calls `AgentSession::export*` directly, so there is no separate
// helper here.

/// Fork the current session into a new JSONL session and switch to it (TS
/// `/fork` — a copy of the transcript in a fresh file; the fork is a new
/// session the user continues in). Uses the repo's `fork_typed`, then swaps
/// the harness backing and renders the (empty-ish) fork transcript.
/// Hot-switch the harness to another saved session: abort any in-flight run,
/// open the target session file, swap the durable backing, and re-render the
/// transcript from the new history (mirrors pi's `/session` resume-in-place).
/// Shared by the `/session` selector, `/import`, and `/fork`. The current
/// model/footer stay put (v1 doesn't replay the session's ModelChange entries).
pub(super) async fn switch_to_session(
    harness: &AgentHarness,
    lane: &Arc<dyn AgentLane>,
    id: &str,
    cwd: &std::path::Path,
    chat: &Arc<Container>,
    state: &Arc<TuiState>,
    tool_context: &rpi_extensions::ToolCallContext,
) -> bool {
    if *state.status.lock().unwrap() == RunStatus::Working {
        state.set_status(RunStatus::Aborting);
        let _ = lane.abort().await;
    }
    if let Err(error) = lane.wait_for_idle().await {
        add_error_message(chat, &format!("Could not switch session: {error}"));
        return false;
    }
    // Same late-result race as `/new`: a running user `!command` finishes into
    // the live lane, which would be the NEW session after this swap.
    if state.user_bash_running() {
        add_note_message(
            chat,
            "Wait for the !command to finish before switching sessions, or press Esc to cancel it.",
        );
        return false;
    }
    let cwd_str = cwd.to_string_lossy().to_string();
    match crate::session::open_session_by_id_in_dir(id, &cwd_str, &state.session_dir).await {
        Ok(new_session) => {
            // Route through the funnel so the plugin channels follow the swap;
            // a bare `set_session` would leave every plugin naming the session
            // it was serving before this call.
            if let Err(error) =
                crate::session::set_active_session(harness, new_session, Some(tool_context)).await
            {
                add_error_message(chat, &format!("Could not switch session: {error}"));
                state.set_status(RunStatus::Idle);
                return false;
            }
            chat.clear();
            state.reset_session_state();
            let (tools, skills, context_files) = current_capabilities(harness, lane).await;
            add_welcome_message_with_capabilities(chat, &tools, &skills, &context_files);
            render_session_history(
                harness,
                chat,
                state.markdown_transformer(),
                Some(state.extension_session.clone()),
                state.images_visible(),
                None,
            )
            .await;
            state.set_status(RunStatus::Idle);
            add_note_message(chat, &format!("Switched to session {id}."));
            true
        }
        Err(e) => {
            state.set_status(RunStatus::Idle);
            add_error_message(chat, &format!("Could not open session {id}: {e}"));
            false
        }
    }
}

/// `/import <path>`: validate and save a session in the selected repository,
/// then activate it through the same funnel as other session switches.
pub(super) async fn import_session(
    harness: &AgentHarness,
    lane: &Arc<dyn AgentLane>,
    path: &str,
    cwd: &std::path::Path,
    chat: &Arc<Container>,
    state: &Arc<TuiState>,
    tool_context: &rpi_extensions::ToolCallContext,
) {
    use std::path::Path as FsPath;

    let src = FsPath::new(path);
    if !src.is_file() {
        add_error_message(chat, &format!("Import source not found: {path}"));
        return;
    }
    let Some(fname) = src.file_name().and_then(|f| f.to_str()) else {
        add_error_message(chat, "Import source has no file name.");
        return;
    };
    if !fname.ends_with(".jsonl") {
        add_error_message(chat, "Import source must be a .jsonl session file.");
        return;
    }
    if *state.status.lock().unwrap() == RunStatus::Working {
        state.set_status(RunStatus::Aborting);
        let _ = lane.abort().await;
    }
    if let Err(error) = lane.wait_for_idle().await {
        add_error_message(chat, &format!("Could not import session: {error}"));
        return;
    }
    // Same late-result race as `/new`: a running user `!command` finishes into
    // the live lane, which would be the NEW session after this swap.
    if state.user_bash_running() {
        add_note_message(
            chat,
            "Wait for the !command to finish before importing a session, or press Esc to cancel it.",
        );
        return;
    }
    let result =
        crate::session::import_session_file(src, &cwd.to_string_lossy(), &state.session_dir).await;
    let new_session = match result {
        Ok(session) => session,
        Err(error) => {
            state.set_status(RunStatus::Idle);
            add_error_message(chat, &format!("Could not import session: {error}"));
            return;
        }
    };
    if let Err(error) =
        crate::session::set_active_session(harness, new_session, Some(tool_context)).await
    {
        state.set_status(RunStatus::Idle);
        add_error_message(chat, &format!("Could not import session: {error}"));
        return;
    }
    chat.clear();
    state.reset_session_state();
    let (tools, skills, context_files) = current_capabilities(harness, lane).await;
    add_welcome_message_with_capabilities(chat, &tools, &skills, &context_files);
    render_session_history(
        harness,
        chat,
        state.markdown_transformer(),
        Some(state.extension_session.clone()),
        state.images_visible(),
        None,
    )
    .await;
    state.set_status(RunStatus::Idle);
    add_note_message(chat, &format!("Imported session from {path}"));
}

pub(super) async fn fork_session(
    harness: &AgentHarness,
    cwd: &std::path::Path,
    chat: &Arc<Container>,
    state: &Arc<TuiState>,
    tool_context: &rpi_extensions::ToolCallContext,
) {
    let lane = harness.lane("main");
    if *state.status.lock().unwrap() == RunStatus::Working {
        state.set_status(RunStatus::Aborting);
        let _ = lane.abort().await;
    }
    if let Err(error) = lane.wait_for_idle().await {
        add_error_message(chat, &format!("Could not fork session: {error}"));
        return;
    }
    // Same late-result race as `/new`: a running user `!command` finishes into
    // the live lane, which would be the NEW session after this swap.
    if state.user_bash_running() {
        add_note_message(
            chat,
            "Wait for the !command to finish before forking a session, or press Esc to cancel it.",
        );
        return;
    }
    let new_session = match crate::session::fork_session_storage(
        harness,
        &cwd.to_string_lossy(),
        &state.session_dir,
    )
    .await
    {
        Ok(session) => session,
        Err(error) => {
            state.set_status(RunStatus::Idle);
            add_error_message(chat, &format!("Could not fork session: {error}"));
            return;
        }
    };
    if let Err(error) =
        crate::session::set_active_session(harness, new_session, Some(tool_context)).await
    {
        state.set_status(RunStatus::Idle);
        add_error_message(chat, &format!("Could not fork session: {error}"));
        return;
    }
    chat.clear();
    state.reset_session_state();
    let (tools, skills, context_files) = current_capabilities(harness, &lane).await;
    add_welcome_message_with_capabilities(chat, &tools, &skills, &context_files);
    render_session_history(
        harness,
        chat,
        state.markdown_transformer(),
        Some(state.extension_session.clone()),
        state.images_visible(),
        None,
    )
    .await;
    state.set_status(RunStatus::Idle);
    add_note_message(chat, "Forked into a new session.");
}

/// `/new` (alias `/clear`): begin a fresh session.
///
/// Creates a new JSONL session file, swaps it onto the harness through the
/// shared [`crate::session::set_active_session`] funnel (so plugin channels
/// follow the swap), rebuilds the transcript with the session's REAL capability
/// snapshot, and drops every per-session counter in the footer.
///
/// The persistence policy of the run is honoured: when the current session is
/// ephemeral (`--no-session`), the fresh session is another in-memory one —
/// nothing may land on disk, and `/new` must never turn an explicit
/// no-persistence choice into persistent chat history.
///
/// The session being left behind is **not** deleted: its file stays on disk and
/// remains reachable through `/session`. Removing user data is not something
/// `/new` should do implicitly.
///
/// Returns `true` when the harness now serves a new session.
pub(super) async fn start_new_session(
    harness: &AgentHarness,
    lane: &Arc<dyn AgentLane>,
    cwd: &std::path::Path,
    chat: &Arc<Container>,
    state: &Arc<TuiState>,
    tool_context: &rpi_extensions::ToolCallContext,
) -> bool {
    if *state.status.lock().unwrap() == RunStatus::Working {
        state.set_status(RunStatus::Aborting);
        let _ = lane.abort().await;
    }
    if let Err(error) = lane.wait_for_idle().await {
        add_error_message(chat, &format!("Could not start a new session: {error}"));
        state.set_status(RunStatus::Idle);
        return false;
    }
    // A user `!command` writes its result through the live lane when it
    // finishes (`UserBashFinished`), with no originating-session identity.
    // Swapping the session underneath it would record that result in the NEW
    // conversation, so the switch waits for the shell run to finish. Merely
    // cancelling would not close the race: the completion is still coming.
    if state.user_bash_running() {
        add_note_message(
            chat,
            "Wait for the !command to finish before starting a new session, or press Esc to cancel it.",
        );
        return false;
    }
    let ephemeral = harness.session().storage().is_ephemeral();
    let new_session = if ephemeral {
        // `--no-session` chose no persistence; the fresh session honours that
        // choice instead of silently writing a JSONL file to disk.
        crate::session::ephemeral_session()
    } else {
        let dir = &state.session_dir;
        if let Err(error) = std::fs::create_dir_all(dir) {
            add_error_message(
                chat,
                &format!(
                    "Could not create session dir {}: {error} — check write permissions",
                    dir.display()
                ),
            );
            state.set_status(RunStatus::Idle);
            return false;
        }
        let cwd_str = cwd.to_string_lossy().to_string();
        match crate::session::create_jsonl_session(dir, &cwd_str).await {
            Ok(session) => session,
            Err(error) => {
                add_error_message(
                    chat,
                    &format!(
                        "Could not create session: {error} — the current session is still active"
                    ),
                );
                state.set_status(RunStatus::Idle);
                return false;
            }
        }
    };
    let new_id = new_session.storage().metadata().id.clone();
    // Route through the funnel so the plugin channels follow the swap; a bare
    // `set_session` would leave every plugin naming the session it was serving
    // before this call.
    if let Err(error) =
        crate::session::set_active_session(harness, new_session, Some(tool_context)).await
    {
        add_error_message(
            chat,
            &format!(
                "Could not start a new session: {error} — the previous session is still active"
            ),
        );
        state.set_status(RunStatus::Idle);
        return false;
    }
    state.reset_session_state();
    chat.clear();
    let (tools, skills, context_files) = current_capabilities(harness, lane).await;
    add_welcome_message_with_capabilities(chat, &tools, &skills, &context_files);
    render_session_history(
        harness,
        chat,
        state.markdown_transformer(),
        Some(state.extension_session.clone()),
        state.images_visible(),
        None,
    )
    .await;
    state.set_status(RunStatus::Idle);
    if ephemeral {
        add_note_message(chat, "Started a new ephemeral session (--no-session).");
    } else {
        add_note_message(chat, &format!("Started new session {new_id}."));
    }
    true
}

/// Render the restored session's prior transcript (user + assistant messages)
/// into the chat container. Called at TUI startup for `--continue`/`--resume`/
/// `--session` launches; a no-op for fresh sessions (no entries). Best-effort:
/// any session read failure just starts with an empty transcript.
///
/// `transformer` is the live assistant-markdown transformer (B5e); `None` is
/// the identity path. Each restored assistant component installs it so replayed
/// history renders through the same `register_markdown_transformer` handlers
/// the live stream does.
///
/// `footer` is the footer whose per-session counters the replayed usage belongs
/// to. It is `None` at startup, where the footer has not been built yet.
pub(super) async fn render_session_history(
    harness: &AgentHarness,
    chat: &Arc<Container>,
    transformer: Option<MarkdownTransformer>,
    extension_session: Option<crate::session::ExtensionSessionCell>,
    show_images: bool,
    footer: Option<&rpi_tui::FooterComponent>,
) {
    // Folding the replayed usage back into `footer` is a follow-up change; the
    // parameter is threaded through now so that change does not have to touch
    // every call site again.
    let _ = footer;
    let tree = harness.session().view("main");
    let entries = match tree
        .find_entries(&EntryQuery {
            entry_type: None,
            custom_type: None,
            // Session queries default to newest-first for selectors and
            // pagination. The transcript appends children top-to-bottom, so
            // restored history must explicitly be chronological.
            order: Some(EntryOrder::OldestFirst),
            limit: None,
            cursor: None,
        })
        .await
    {
        Ok(e) => e,
        Err(_) => return,
    };
    let mut rendered_any = false;
    for e in entries {
        match e {
            Entry::Message(me) => match &me.message {
                AgentMessage::User(u) => {
                    add_user_message(chat, &user_message_text(u));
                    add_user_images(chat, u, show_images);
                    rendered_any = true;
                }
                AgentMessage::Assistant(a) => {
                    let comp = Arc::new(AssistantMessageComponent::new(
                        AssistantMessageOptions::default(),
                    ));
                    comp.set_show_images(show_images);
                    comp.set_trailing_spacing(1);
                    if let Some(t) = &transformer {
                        comp.set_markdown_transformer(Some(t.clone()));
                    }
                    comp.update_blocks(&assistant_blocks(a));
                    chat.add_child(comp);
                    // The component adds spacing only when it has visible content.
                    if let Some(text) = extension_usage_text(extension_session.as_ref(), &a.usage) {
                        add_note_message(chat, &text);
                    }
                    if let Some(error) = assistant_error_text(a) {
                        add_error_message(chat, &error);
                    }
                    rendered_any = true;
                }
                AgentMessage::ToolResult(result) => {
                    if matches!(
                        result.tool_name.as_str(),
                        "plan_mode_start" | "plan_mode_complete"
                    ) && !result.is_error
                        && crate::transcript_view::update_plan_panel(
                            chat,
                            &serde_json::json!({"details":result.details}),
                        )
                    {
                        rendered_any = true;
                        continue;
                    }
                    if result.tool_name == "todo"
                        && !result.is_error
                        && crate::transcript_view::update_todo_list(
                            chat,
                            &serde_json::json!({
                                "content": result.content, "details": result.details,
                            }),
                        )
                    {
                        rendered_any = true;
                        continue;
                    }
                    // Tool results are persisted as separate message entries,
                    // not as part of the assistant text. Restore them as
                    // completed tool panels so resumed sessions show the
                    // command output as well as the user's prompts.
                    let comp = Arc::new(ToolExecutionComponent::new(&result.tool_name, ""));
                    comp.set_result(&tool_result_message_text(result), result.is_error);
                    if tool_result_requests_markdown(result.details.as_ref()) {
                        comp.set_result_markdown(true);
                    }
                    chat.add_child(comp);
                    for block in &result.content {
                        if let rpi_ai::types::Content::Image(image) = block {
                            add_image_preview(chat, image, show_images);
                        }
                    }
                    chat.add_child(Arc::new(Spacer::new(1)));
                    rendered_any = true;
                }
                AgentMessage::Custom(custom) => {
                    if let Some(session) = &extension_session {
                        if let Some(component) = extension_message_component(
                            session,
                            &custom.role,
                            &serde_json::json!({
                                "customType": custom.role,
                                "content": custom.content,
                                "details": custom.data,
                            }),
                            transformer.clone(),
                        ) {
                            chat.add_child(component);
                            chat.add_child(Arc::new(Spacer::new(1)));
                            rendered_any = true;
                            continue;
                        }
                    }
                    add_note_message(chat, &custom_message_fallback(custom));
                    rendered_any = true;
                }
            },
            Entry::Compaction(compaction) => {
                add_note_message(
                    chat,
                    &format!(
                        "Compacted {} tokens: {}",
                        compaction.tokens_before, compaction.summary
                    ),
                );
                rendered_any = true;
            }
            Entry::BranchSummary(summary) => {
                add_note_message(chat, &format!("Branch summary: {}", summary.summary));
                rendered_any = true;
            }
            Entry::Custom(custom) => {
                if custom.custom_type == "plan-mode" {
                    let mut details = custom.data.clone().unwrap_or(serde_json::Value::Null);
                    if let Some(fields) = details.as_object_mut() {
                        fields.insert("kind".into(), serde_json::json!("plan"));
                    }
                    if crate::transcript_view::update_plan_panel(
                        chat,
                        &serde_json::json!({"details":details}),
                    ) {
                        rendered_any = true;
                        continue;
                    }
                }
                let rendered = extension_session.as_ref().and_then(|session| {
                    extension_entry_component(session, &custom.custom_type, custom.data.clone())
                });
                if let Some(component) = rendered {
                    chat.add_child(component);
                    chat.add_child(Arc::new(Spacer::new(1)));
                    rendered_any = true;
                } else if let Some(text) =
                    custom_entry_display_text(&custom.custom_type, custom.data.as_ref())
                {
                    add_note_message(chat, &text);
                    rendered_any = true;
                }
            }
            Entry::ModelChange(change) => {
                add_note_message(
                    chat,
                    &format!("Model changed to {}:{}", change.provider, change.model_id),
                );
                rendered_any = true;
            }
            Entry::ThinkingLevel(change) => {
                add_note_message(
                    chat,
                    &format!("Thinking level: {:?}", change.thinking_level),
                );
                rendered_any = true;
            }
            Entry::ActiveTools(change) => {
                add_note_message(
                    chat,
                    &format!("Active tools: {}", change.active_tool_names.join(", ")),
                );
                rendered_any = true;
            }
        }
    }
    if rendered_any {
        // No trailing spacer here — each entry already adds its own trailing
        // Spacer(1), so an extra would double the bottom gap.
    }
}

pub(super) fn invoke_extension_renderer(
    session: &crate::session::ExtensionSessionCell,
    kind: rpi_extensions::RegisteredRendererKind,
    payload: &serde_json::Value,
) -> Option<serde_json::Value> {
    let snapshot = session.lock().ok()?.snapshot_arc()?;
    let input = serde_json::to_string(payload).ok()?;
    for renderer in snapshot.renderers_of(kind) {
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut out = rpi_plugin_sdk::StbString::empty();
            let rc = (renderer.render_fn)(
                rpi_plugin_sdk::StbStringRef::from_str(&input),
                &mut out as *mut rpi_plugin_sdk::StbString,
                renderer.user_data,
            );
            // SAFETY: the callback transfers a live output to its producer.
            let out = unsafe {
                rpi_plugin_sdk::callbacks::OwnedString::from_raw(
                    out,
                    Some(renderer.plugin_free_string),
                )
            };

            if rc == 0 {
                Some(out.to_string_lossy())
            } else {
                None
            }
        }))
        .ok()
        .flatten();
        let Some(text) = outcome else { continue };
        if let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) {
            return Some(value);
        }
    }
    None
}

pub(super) fn extension_text_component(
    value: &serde_json::Value,
) -> Option<Arc<dyn rpi_tui::Component>> {
    if let Some(lines) = value.get("lines").and_then(|v| v.as_array()) {
        let text = lines
            .iter()
            .filter_map(|line| line.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        return Some(Arc::new(Text::new(text, 0, 0)));
    }
    let text = value.get("text").and_then(|v| v.as_str())?;
    if value.get("markdown").and_then(|v| v.as_bool()) == Some(true) {
        let component = Arc::new(AssistantMessageComponent::new(
            AssistantMessageOptions::default(),
        ));
        component.update_blocks(&[AssistantBlock::Text(text.to_string())]);
        Some(component)
    } else {
        Some(Arc::new(Text::new(text, 0, 0)))
    }
}

pub(super) fn extension_message_component(
    session: &crate::session::ExtensionSessionCell,
    custom_type: &str,
    payload: &serde_json::Value,
    transformer: Option<MarkdownTransformer>,
) -> Option<Arc<dyn rpi_tui::Component>> {
    let value = invoke_extension_renderer(
        session,
        rpi_extensions::RegisteredRendererKind::Message,
        payload,
    )?;
    if value.get("markdown").and_then(|v| v.as_bool()) == Some(true) {
        let text = value.get("text").and_then(|v| v.as_str())?;
        let component = Arc::new(AssistantMessageComponent::new(
            AssistantMessageOptions::default(),
        ));
        if let Some(transformer) = transformer {
            component.set_markdown_transformer(Some(transformer));
        }
        component.update_blocks(&[AssistantBlock::Text(text.to_string())]);
        return Some(component);
    }
    extension_text_component(&value)
        .or_else(|| Some(Arc::new(Text::new(format!("[{custom_type}]"), 0, 0))))
}

/// Render usage from a completed assistant message through the registered
/// message renderers. Hosts without a token-usage renderer return `None`.
pub(super) fn extension_usage_text(
    session: Option<&crate::session::ExtensionSessionCell>,
    usage: &rpi_ai::types::Usage,
) -> Option<String> {
    let session = session?;
    let payload = serde_json::json!({
        "customType": "token-usage",
        "usage": usage,
    });
    let value = invoke_extension_renderer(
        session,
        rpi_extensions::RegisteredRendererKind::Message,
        &payload,
    )?;
    value
        .get("text")
        .and_then(|value| value.as_str())
        .filter(|text| !text.trim().is_empty())
        .map(ToOwned::to_owned)
}

pub(super) fn extension_entry_component(
    session: &crate::session::ExtensionSessionCell,
    custom_type: &str,
    data: Option<serde_json::Value>,
) -> Option<Arc<dyn rpi_tui::Component>> {
    let payload = serde_json::json!({
        "customType": custom_type,
        "data": data,
    });
    let value = invoke_extension_renderer(
        session,
        rpi_extensions::RegisteredRendererKind::Entry,
        &payload,
    )?;
    extension_text_component(&value)
}

/// Project an assistant message's content into the provider-free
/// [`AssistantBlock`] list (text, thinking, and decoded image blocks, in
/// document order) the `AssistantMessageComponent` renders. Tool-call blocks
/// are rendered by their own components in the transcript.
/// Whether startup intentionally opened a session that already has history.
pub(super) fn launch_restores_history(args: &Args) -> bool {
    args.continue_session
        || args.resume
        || args.session.is_some()
        || args.session_id.is_some()
        || args.fork.is_some()
}

pub(super) fn custom_message_fallback(custom: &rpi_agent::CustomMessage) -> String {
    let content = custom
        .content
        .iter()
        .filter_map(|item| match item {
            Content::Text(text) => Some(text.text.as_str()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("\n");
    if content.is_empty() {
        format!("{}: {}", custom.role, custom.data)
    } else {
        format!("{}: {}", custom.role, content)
    }
}

/// Path to the enclosing repository's `.git/HEAD`, if any.
pub(super) fn find_git_head_path(cwd: &std::path::Path) -> Option<std::path::PathBuf> {
    let mut dir = Some(cwd);
    while let Some(current) = dir {
        let head = current.join(".git").join("HEAD");
        if head.exists() {
            return Some(head);
        }
        dir = current.parent();
    }
    None
}

/// Current git branch for `cwd`, or `None` outside a repository / on error.
/// Reads `.git/HEAD` directly (no `git` subprocess) so the footer can call it
/// cheaply at startup.
pub(super) fn git_branch_for(cwd: &std::path::Path) -> Option<String> {
    let mut dir = Some(cwd);
    while let Some(current) = dir {
        let head = current.join(".git").join("HEAD");
        if let Ok(contents) = std::fs::read_to_string(&head) {
            let trimmed = contents.trim();
            if let Some(reference) = trimmed.strip_prefix("ref: ") {
                let branch = reference
                    .rsplit('/')
                    .next()
                    .unwrap_or(reference)
                    .trim()
                    .to_string();
                if !branch.is_empty() {
                    return Some(branch);
                }
            }
            if !trimmed.is_empty() {
                return Some(trimmed.chars().take(7).collect());
            }
        }
        dir = current.parent();
    }
    None
}

/// The name displayed for a model id (last path segment / after the final
/// `:`), to keep the footer compact.
pub(super) fn short_model_name(id: &str) -> String {
    id.rsplit([':', '/'])
        .next()
        .filter(|s| !s.is_empty())
        .unwrap_or(id)
        .to_string()
}