Skip to main content

rpi_cli/
extensions_actions.rs

1//! B5a — the `RuntimeActionHost` impl over the harness, lived in `rpi-cli`
2//! (NOT `rpi-harness`) so `rpi-extensions` stays a leaf in the crate DAG. The
3//! trait is defined in `rpi-extensions` (JSON + primitives only); this is the
4//! host side that bridges the 16 [`RuntimeActionId`] actions to the harness.
5//!
6//! 10 ops delegate to `harness.lane("main")` (the `AgentLane` surface backs
7//! `prompt_message`/`prompt_text`/`get_active_tools`/`set_active_tools`/
8//! `set_model`/`get_thinking_level`/`set_thinking_level`/`compact`/
9//! `navigate_tree`). Run-ops serialize via `acquire_run`'s `active_run` guard —
10//! a concurrent plugin invocation surfaces `lane_busy` as the harness error
11//! string, the right behavior (a plugin can't re-enter an active run).
12//!
13//! 6 non-lane ops:
14//! - `append_entry` → the harness's boundary-aware message writer, or raw
15//!   extension data on the session; `set_session_name` → `set_name`.
16//! - `get_system_prompt` → `AgentHarness::get_system_prompt` (B5a accessor).
17//! - `new_session`/`fork`/`switch_session` → reuse `crate::session`'s
18//!   create/fork/open helpers + `harness.set_session`.
19//! - `reload` → handled by `ActionBridge.reload` (B5d); the host impl is the
20//!   "not configured" fallback for bridges without a callback.
21//!
22//! ## Construction ordering (the load-bearing wrinkle)
23//!
24//! Extensions load **before** the harness is created (extensions provide the
25//! tools the harness is built with), but the plugin stores the
26//! `ActionBridge`'s `user_data` pointer during `register` and that pointer
27//! must remain valid for the whole session. So the host cannot hold the
28//! `AgentHarness` directly — it holds an [`Arc<OnceLock<WeakAgentHarness>>`]
29//! that is **empty at register time** and **filled once** by
30//! [`HarnessActionHost::set_harness`] immediately after `AgentHarness::create`
31//! succeeds. Each action upgrades that weak binding for its duration; the host
32//! must not keep tools/providers alive via adapter -> keepalive -> bridge -> host.
33//! Before construction or after final harness release, actions fail explicitly.
34//! The bridge's opaque handle stays stable without retaining the harness.
35//!
36//! The impl needs the model `catalog` for `set_model(id)` (the lane wants a
37//! `Model`, not an id) and the `cwd` for session create/fork/switch. Both are
38//! held by `rpi-cli` at build time and moved into the host.
39
40use std::collections::BTreeMap;
41use std::path::PathBuf;
42use std::sync::{Arc, OnceLock, RwLock};
43
44use rpi_ai::types::ThinkingLevel;
45use rpi_extensions::RuntimeActionHost;
46use rpi_harness::agent_harness::{
47    AgentHarness, HarnessRunOutcome, NavigationOutcome, SendMessageResult, WeakAgentHarness,
48};
49use rpi_harness::session::session::Session;
50use rpi_harness::types::SendMessageOptions;
51use tokio::runtime::Handle;
52
53use crate::session::{default_session_dir, open_session_by_id_in_dir};
54
55mod independent_runs;
56pub(crate) use independent_runs::observations::{
57    capabilities as child_observation_capabilities, COMMANDS as CHILD_OBSERVATION_COMMANDS,
58};
59
60/// Merge built-in / extension / prompt-template commands into the
61/// `ListCommands` payload.
62///
63/// It is one function because it is the single source of truth for the shape:
64///
65/// * Built-in commands live in the TUI's `CommandRegistry`, not the plugin
66///   registry. Reporting only the extension half leaves a remote client without
67///   the most common entries (`/help`, `/model`, …).
68/// * Prompt templates live in **neither**: the TUI merges them into autocomplete
69///   separately (`build_builtin_registry` explicitly says so). They have to be
70///   read from the harness resources, or a remote `/` completion list is
71///   permanently shorter than the terminal's — same host, two command tables.
72/// * Precedence is built-in > extension > prompt, matching the TUI (built-ins
73///   register first and cannot be shadowed; a template sharing a built-in name
74///   is unreachable there too).
75/// * Extension and template names may omit the leading `/`, so normalize.
76///
77/// Built-in **aliases and hidden commands** win dispatch in the TUI without
78/// appearing as suggestions. Reserving them here keeps an extension that
79/// registers the same name from being advertised as `source:"extension"` when
80/// the built-in is what actually runs.
81fn merge_command_list_reserved(
82    builtin: Vec<(String, String)>,
83    extension: Vec<(String, String)>,
84    templates: Vec<(String, String)>,
85    reserved: Vec<String>,
86) -> Vec<serde_json::Value> {
87    // Reserved names must block *later* sources without blocking the built-ins
88    // themselves: a visible built-in canonical name is both the reservation and
89    // a real entry, so seeding `seen` with it would drop every built-in from the
90    // listing. Keep the reservation set separate and consult it only for
91    // non-builtin sources; collisions among the sources still fall to `seen`.
92    let mut reserved_names = std::collections::BTreeSet::new();
93    for name in reserved {
94        let name = if !name.starts_with('/') {
95            format!("/{name}")
96        } else {
97            name
98        };
99        reserved_names.insert(name);
100    }
101    let mut seen = std::collections::BTreeSet::new();
102    let mut out: Vec<serde_json::Value> = Vec::new();
103    for (source, commands) in [
104        ("builtin", builtin),
105        ("extension", extension),
106        ("prompt", templates),
107    ] {
108        for (name, description) in commands {
109            let name = if source != "builtin" && !name.starts_with('/') {
110                format!("/{name}")
111            } else {
112                name
113            };
114            if source != "builtin" && reserved_names.contains(&name) {
115                continue;
116            }
117            if !seen.insert(name.clone()) {
118                continue;
119            }
120            out.push(serde_json::json!({
121                "name": name,
122                "description": description,
123                "source": source,
124            }));
125        }
126    }
127    out
128}
129
130/// The `RuntimeActionHost` impl over an `AgentHarness`. Built once per session
131/// in [`crate::session::build`] — constructed **empty** before extension load
132/// (the harness doesn't exist yet), then filled via [`set_harness`](Self::set_harness)
133/// once `AgentHarness::create` succeeds. Carried inside the [`ActionBridge`] as
134/// `Arc<dyn RuntimeActionHost>`.
135///
136/// `runtime` is captured at build time so the bridge can spawn dispatch from
137/// any thread; the impl's async methods run ON that runtime (they are spawned
138/// by the trampoline), so they may freely await.
139pub struct HarnessActionHost {
140    /// Weak binding filled after construction. Each operation upgrades it;
141    /// before construction or after final owner release it returns an error.
142    harness: Arc<OnceLock<WeakAgentHarness>>,
143    /// The auth-filtered catalog (the same list the TUI `/model` selector
144    /// shows). `set_model(id)` resolves an id against this.
145    catalog: RwLock<Vec<rpi_ai::Model>>,
146    /// The session cwd — `new_session`/`fork`/`switch_session` need it to
147    /// locate the session dir.
148    cwd: PathBuf,
149    session_dir: PathBuf,
150    ephemeral_sessions_only: bool,
151    publish_process_identity: bool,
152    /// Host-owned startup choice, independent of model tools and plugin flags.
153    /// Immutable after construction, including while the registry is published.
154    native_durable: bool,
155    /// Parsed unknown long flags retained for extension consumption.
156    cli_flags: BTreeMap<String, serde_json::Value>,
157    /// The session's plugin-tool context (`cwd` + session id). The session
158    /// runtime actions (`new_session`/`fork`/`switch_session`) swap the session
159    /// the harness serves, and must republish the id here too — a plugin whose
160    /// tool state keyed off the old id would otherwise keep serving the session
161    /// it named before the swap.
162    tool_context: rpi_extensions::ToolCallContext,
163    independent_runs: independent_runs::IndependentRuns,
164    side_questions: crate::side_questions::SideQuestions,
165    #[allow(dead_code)]
166    runtime: Handle,
167    /// Loaded extension registry, set once the session's extensions are in.
168    ///
169    /// Needed by `ListCommands`: the plugin ABI had no way to enumerate slash
170    /// commands, so a remote UI could not offer completion. `None` before the
171    /// registry is published (and in tests that never load extensions) — the
172    /// action then answers with an empty list rather than failing, matching
173    /// the "no commands registered" case.
174    registry: std::sync::RwLock<Option<std::sync::Arc<rpi_extensions::RegistrySnapshot>>>,
175}
176
177impl HarnessActionHost {
178    /// Build an **empty** host (no harness yet). The `runtime` is the handle
179    /// the bridge captured (kept only so the impl can name it for future
180    /// direct-spawn needs; the trampoline already spawns on the bridge's
181    /// runtime). Call [`set_harness`](Self::set_harness) once the harness is
182    /// created. Returns `(host, harness_cell)` where `harness_cell` is the
183    /// shared `OnceLock` the caller fills.
184    pub fn new_empty(
185        catalog: Vec<rpi_ai::Model>,
186        cwd: PathBuf,
187        runtime: Handle,
188        cli_flags: BTreeMap<String, serde_json::Value>,
189        tool_context: rpi_extensions::ToolCallContext,
190    ) -> (Self, Arc<OnceLock<WeakAgentHarness>>) {
191        let harness = Arc::new(OnceLock::new());
192        (
193            Self {
194                harness: Arc::clone(&harness),
195                catalog: RwLock::new(catalog),
196                session_dir: default_session_dir(&cwd),
197                ephemeral_sessions_only: false,
198                publish_process_identity: true,
199                native_durable: false,
200                cwd,
201                cli_flags,
202                tool_context,
203                independent_runs: independent_runs::IndependentRuns::default(),
204                side_questions: crate::side_questions::SideQuestions::default(),
205                runtime,
206                registry: std::sync::RwLock::new(None),
207            },
208            harness,
209        )
210    }
211
212    // Final retirement only, never a per-run/session-switch cancellation.
213    // This is the native auxiliary domain, NOT an OS process cleanup receipt.
214    #[allow(dead_code)] // Default CLI Host factory is not wired yet.
215    pub(crate) fn begin_auxiliary_shutdown(&self) {
216        self.independent_runs.begin_shutdown();
217        self.side_questions.begin_shutdown();
218    }
219
220    #[allow(dead_code)]
221    pub(crate) async fn wait_auxiliary_shutdown(&self) -> Result<(), String> {
222        let (children, questions) = tokio::join!(
223            self.independent_runs.wait_shutdown(),
224            self.side_questions.wait_shutdown(),
225        );
226        children.and(questions)
227    }
228
229    pub fn set_catalog(&self, catalog: Vec<rpi_ai::Model>) {
230        *self
231            .catalog
232            .write()
233            .unwrap_or_else(|error| error.into_inner()) = catalog;
234    }
235
236    pub(crate) fn with_ephemeral_sessions_only(mut self, enabled: bool) -> Self {
237        self.ephemeral_sessions_only = enabled;
238        self
239    }
240    pub(crate) fn with_process_identity(mut self, publish: bool) -> Self {
241        self.publish_process_identity = publish;
242        self
243    }
244    pub(crate) fn with_native_durable(mut self, enabled: bool) -> Self {
245        self.native_durable = enabled;
246        self
247    }
248    fn allow_saved_sessions(&self) -> Result<(), String> {
249        if self.ephemeral_sessions_only {
250            Err("--mini does not support saved sessions".into())
251        } else {
252            Ok(())
253        }
254    }
255
256    pub(crate) fn with_session_dir(mut self, session_dir: PathBuf) -> Self {
257        self.session_dir = session_dir;
258        self
259    }
260
261    /// Publish the loaded extension registry so `ListCommands` can answer.
262    ///
263    /// `None` publishes "no extensions". A reload that ends with zero plugins
264    /// must publish that too: otherwise the previous snapshot stays cached and
265    /// removed extensions keep advertising their commands.
266    pub(crate) fn publish_registry_impl(
267        &self,
268        snapshot: Option<std::sync::Arc<rpi_extensions::RegistrySnapshot>>,
269    ) {
270        if let Ok(mut slot) = self.registry.write() {
271            *slot = snapshot;
272        }
273    }
274
275    fn registry_snapshot(&self) -> Option<std::sync::Arc<rpi_extensions::RegistrySnapshot>> {
276        self.registry.read().ok().and_then(|slot| slot.clone())
277    }
278
279    /// Fill the harness cell. Call exactly once, immediately after
280    /// `AgentHarness::create` succeeds. Returns the host (for fluent chaining)
281    /// — the caller already holds the `Arc<dyn RuntimeActionHost>` from
282    /// construction; this just populates the cell that host reads.
283    pub fn set_harness(cell: &Arc<OnceLock<WeakAgentHarness>>, harness: Arc<AgentHarness>) {
284        let _ = cell.set(harness.downgrade());
285    }
286
287    /// Pin the harness only for this action. The binding itself must not retain
288    /// tools/providers through the plugin -> keepalive -> host reference cycle.
289    fn harness(&self) -> Result<AgentHarness, String> {
290        self.harness
291            .get()
292            .ok_or_else(|| "runtime action invoked before harness was built".to_string())?
293            .upgrade()
294            .ok_or_else(|| "runtime action invoked after harness was dropped".to_string())
295    }
296
297    /// Resolve `id` (case-insensitive exact, then substring) against the
298    /// catalog. Mirrors the resolver's exact-id-first fallback.
299    fn resolve_model(&self, id: &str) -> Option<rpi_ai::Model> {
300        let catalog = self.catalog.read().ok()?;
301        catalog
302            .iter()
303            .find(|m| m.id.eq_ignore_ascii_case(id))
304            .cloned()
305            .or_else(|| {
306                catalog
307                    .iter()
308                    .find(|m| m.id.to_ascii_lowercase().contains(&id.to_ascii_lowercase()))
309                    .cloned()
310            })
311    }
312}
313
314/// Serialize reclaimed queue entries for the ABI boundary.
315///
316/// Each entry is `{"text": "…", "images": [{mediaType, data}]}` — text and its
317/// own attachments **together**. A flat `images` side list would lose the
318/// pairing as soon as two queued messages carry different pictures: a restore
319/// would attach image B next to text A, or attach the picture to whichever
320/// entry happened to be first.
321pub(crate) fn queued_message_payloads(
322    messages: &[rpi_agent::AgentMessage],
323) -> Vec<serde_json::Value> {
324    messages
325        .iter()
326        .map(|message| {
327            let (text, images) = match message {
328                rpi_agent::AgentMessage::User(user) => match &user.content {
329                    rpi_ai::types::UserContent::Text(text) => (text.clone(), Vec::new()),
330                    rpi_ai::types::UserContent::Blocks(blocks) => {
331                        let text = blocks
332                            .iter()
333                            .filter_map(|block| match block {
334                                rpi_ai::types::Content::Text(text) => Some(text.text.as_str()),
335                                _ => None,
336                            })
337                            .collect::<Vec<_>>()
338                            .join("\n");
339                        let collected: Vec<_> = blocks
340                            .iter()
341                            .filter_map(|block| match block {
342                                rpi_ai::types::Content::Image(image) => Some(image.clone()),
343                                _ => None,
344                            })
345                            .collect();
346                        (text, image_payloads(&collected))
347                    }
348                },
349                _ => (String::new(), Vec::new()),
350            };
351            serde_json::json!({ "text": text, "images": images })
352        })
353        .filter(|entry| {
354            entry["text"].as_str().is_some_and(|t| !t.trim().is_empty())
355                || entry["images"].as_array().is_some_and(|i| !i.is_empty())
356        })
357        .collect()
358}
359
360/// Serialize image attachments as `{mediaType, data}`.
361fn image_payloads(images: &[rpi_ai::types::ImageContent]) -> Vec<serde_json::Value> {
362    images
363        .iter()
364        .map(|image| {
365            serde_json::json!({
366                "mediaType": image.mime_type,
367                "data": image.data,
368            })
369        })
370        .collect()
371}
372
373/// Helper: pull a string field `key` from `args` (object), or return `msg`.
374fn arg_str(args: &serde_json::Value, key: &str) -> Result<String, String> {
375    args.get(key)
376        .and_then(|v| v.as_str())
377        .map(|s| s.to_string())
378        .ok_or_else(|| format!("missing string field `{key}` in action args"))
379}
380
381/// Helper: pull an optional string field.
382fn arg_str_opt(args: &serde_json::Value, key: &str) -> Option<String> {
383    args.get(key)
384        .and_then(|v| v.as_str())
385        .map(|s| s.to_string())
386}
387
388/// Helper: pull a bool field (default `false`).
389fn arg_bool(args: &serde_json::Value, key: &str) -> bool {
390    args.get(key).and_then(|v| v.as_bool()).unwrap_or(false)
391}
392
393/// Helper: pull a string array field.
394fn arg_str_array(args: &serde_json::Value, key: &str) -> Result<Vec<String>, String> {
395    args.get(key)
396        .and_then(|v| v.as_array())
397        .map(|arr| {
398            arr.iter()
399                .filter_map(|v| v.as_str().map(|s| s.to_string()))
400                .collect()
401        })
402        .ok_or_else(|| format!("missing string-array field `{key}` in action args"))
403}
404
405/// Render a `HarnessRunOutcome` as JSON for the plugin. Only the terminal
406/// status + leaf id cross (the final message text is folded to a string; full
407/// assistant content is too rich for a v1 action result).
408pub(crate) fn run_outcome_json(outcome: HarnessRunOutcome) -> serde_json::Value {
409    match outcome {
410        HarnessRunOutcome::Completed {
411            leaf_id,
412            final_entry_id,
413            final_message,
414        } => {
415            serde_json::json!({
416                "status": "completed",
417                "leafId": leaf_id,
418                "finalEntryId": final_entry_id,
419                "text": assistant_text(&final_message),
420            })
421        }
422        HarnessRunOutcome::Aborted {
423            leaf_id,
424            final_entry_id,
425            final_message,
426        } => {
427            serde_json::json!({
428                "status": "aborted",
429                "leafId": leaf_id,
430                "finalEntryId": final_entry_id,
431                "text": assistant_text(&final_message),
432            })
433        }
434        HarnessRunOutcome::Failed {
435            leaf_id,
436            error,
437            final_entry_id,
438            final_message,
439        } => {
440            serde_json::json!({
441                "status": "failed",
442                "leafId": leaf_id,
443                "error": format!("{error:?}"),
444                "finalEntryId": final_entry_id,
445                "text": final_message.map(|m| assistant_text(&m)).unwrap_or_default(),
446            })
447        }
448        HarnessRunOutcome::Suspended {
449            leaf_id,
450            final_entry_id,
451            ..
452        } => {
453            serde_json::json!({
454                "status": "suspended",
455                "leafId": leaf_id,
456                "finalEntryId": final_entry_id,
457            })
458        }
459    }
460}
461
462/// Accept the SDK's flat action args and Pi-style nested options. Reject mixed
463/// forms instead of silently choosing one set of scheduling instructions.
464fn send_message_options(args: &serde_json::Value) -> Result<SendMessageOptions, String> {
465    let flat = args.get("triggerTurn").is_some() || args.get("deliverAs").is_some();
466    let value = if let Some(options) = args.get("options").filter(|value| !value.is_null()) {
467        if !options.is_object() {
468            return Err("send_message options must be an object".into());
469        }
470        if flat {
471            return Err(
472                "put triggerTurn/deliverAs either in options or at the top level, not both".into(),
473            );
474        }
475        options.clone()
476    } else {
477        let mut fields = serde_json::Map::new();
478        for key in ["triggerTurn", "deliverAs"] {
479            if let Some(value) = args.get(key) {
480                fields.insert(key.into(), value.clone());
481            }
482        }
483        serde_json::Value::Object(fields)
484    };
485    serde_json::from_value(value).map_err(|error| format!("invalid send_message options: {error}"))
486}
487
488fn send_message_input(args: &serde_json::Value) -> Result<rpi_agent::AgentMessage, String> {
489    let timestamp = std::time::SystemTime::now()
490        .duration_since(std::time::UNIX_EPOCH)
491        .unwrap_or_default()
492        .as_millis()
493        .min(i64::MAX as u128) as i64;
494    if let Some(message) = args.get("message") {
495        if message.get("kind").is_some() {
496            return serde_json::from_value(message.clone())
497                .map_err(|error| format!("invalid message: {error}"));
498        }
499        // Pi's custom message input does not include the stored AgentMessage
500        // discriminator. Preserve customType/display/details via its constructor.
501        #[derive(serde::Deserialize)]
502        #[serde(rename_all = "camelCase")]
503        struct CustomInput {
504            custom_type: String,
505            #[serde(default)]
506            content: Option<rpi_ai::types::UserContent>,
507            #[serde(default)]
508            display: bool,
509            #[serde(default)]
510            details: Option<serde_json::Value>,
511        }
512        let input: CustomInput = serde_json::from_value(message.clone())
513            .map_err(|error| format!("invalid custom message: {error}"))?;
514        return Ok(rpi_harness::messages::create_custom_message(
515            &input.custom_type,
516            input
517                .content
518                .unwrap_or(rpi_ai::types::UserContent::Blocks(Vec::new())),
519            input.display,
520            input.details,
521            timestamp,
522        ));
523    }
524    let text =
525        arg_str(args, "text").map_err(|_| "missing `message` or `text` field".to_string())?;
526    Ok(rpi_agent::AgentMessage::User(
527        rpi_ai::types::UserMessage::new(text, timestamp),
528    ))
529}
530
531fn send_message_result(result: SendMessageResult) -> serde_json::Value {
532    match result {
533        SendMessageResult::Appended { entry_id } => {
534            serde_json::json!({"status":"appended", "entryId":entry_id})
535        }
536        SendMessageResult::Queued { entry_id, queue } => {
537            if queue == rpi_harness::session::types::QueueKind::Context {
538                return serde_json::json!({"status":"queued", "entryId":entry_id, "queue":"context"});
539            }
540            let delivery = match queue {
541                rpi_harness::session::types::QueueKind::NextRun => "nextTurn",
542                _ => queue.as_str(),
543            };
544            serde_json::json!({"status":"queued", "entryId":entry_id, "deliverAs":delivery})
545        }
546        SendMessageResult::Run(run) => run_outcome_json(run.outcome),
547    }
548}
549
550/// Extract the concatenated text from an assistant message (the `text` blocks).
551pub(crate) fn assistant_text(msg: &rpi_ai::types::AssistantMessage) -> String {
552    msg.content
553        .iter()
554        .filter_map(|b| match b {
555            rpi_ai::types::Content::Text(t) => Some(t.text.as_str()),
556            _ => None,
557        })
558        .collect::<Vec<_>>()
559        .join("")
560}
561
562#[async_trait::async_trait]
563impl RuntimeActionHost for HarnessActionHost {
564    fn cancel_side_questions(&self, owner: u64) {
565        self.side_questions.cancel_owner(owner);
566    }
567    fn side_question_revision(&self) -> u64 {
568        self.side_questions.revision()
569    }
570    fn side_question_views(&self) -> Vec<serde_json::Value> {
571        self.side_questions.views()
572    }
573    async fn side_question_ui(
574        &self,
575        owner: u64,
576        thread_id: String,
577        args: serde_json::Value,
578    ) -> Result<serde_json::Value, String> {
579        self.side_questions
580            .ui_handle(&self.harness()?, owner, thread_id, args)
581            .await
582    }
583    async fn side_question(
584        &self,
585        owner: u64,
586        args: serde_json::Value,
587        sink: rpi_extensions::SideQuestionSink,
588    ) -> Result<serde_json::Value, String> {
589        self.side_questions
590            .handle(&self.harness()?, owner, args, sink)
591            .await
592    }
593
594    fn cancel_child_agents(&self, owner: u64) {
595        self.independent_runs.cancel_owner(owner);
596    }
597    fn child_agent_roster(&self) -> Vec<serde_json::Value> {
598        self.independent_runs.roster()
599    }
600    fn stop_child_agent(&self, child_id: &str) -> Result<serde_json::Value, String> {
601        self.independent_runs.stop(child_id)
602    }
603
604    fn supports_child_observations(&self) -> bool {
605        true
606    }
607
608    fn child_observations(
609        &self,
610        parent: &str,
611        request: serde_json::Value,
612    ) -> Result<serde_json::Value, String> {
613        self.independent_runs.query_observations(parent, request)
614    }
615    fn replace_model_catalog(&self, models: Vec<rpi_ai::Model>) {
616        self.set_catalog(models);
617    }
618    async fn list_commands(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
619        let builtin = crate::interactive_tui::build_builtin_commands_for_abi(self.native_durable);
620        let extension: Vec<(String, String)> = self
621            .registry_snapshot()
622            .as_deref()
623            .map(|snapshot| {
624                snapshot
625                    .commands()
626                    .iter()
627                    .map(|c| (c.name.clone(), c.description.clone()))
628                    .collect()
629            })
630            .unwrap_or_default();
631        // Prompt templates are harness resources, not registry entries — see
632        // `merge_command_list`. A missing/closed harness yields no templates
633        // rather than an error: "none discovered" is a real answer, and `/`
634        // completion must still work for the commands that do exist.
635        let templates: Vec<(String, String)> = match self.harness() {
636            Ok(harness) => match harness.get_resources().await {
637                Ok(resources) => resources
638                    .prompt_templates
639                    .unwrap_or_default()
640                    .into_iter()
641                    .map(|template| {
642                        (
643                            template.name,
644                            template
645                                .description
646                                .unwrap_or_else(|| "Expand prompt template".to_string()),
647                        )
648                    })
649                    .collect(),
650                Err(_) => Vec::new(),
651            },
652            Err(_) => Vec::new(),
653        };
654        Ok(serde_json::json!({
655            "commands": merge_command_list_reserved(
656                builtin,
657                extension,
658                templates,
659                crate::interactive_tui::builtin_reserved_names(self.native_durable),
660            )
661        }))
662    }
663
664    fn publish_registry(&self, snapshot: std::sync::Arc<rpi_extensions::RegistrySnapshot>) {
665        self.publish_registry_impl(Some(snapshot));
666    }
667
668    fn publish_registry_opt(
669        &self,
670        snapshot: Option<std::sync::Arc<rpi_extensions::RegistrySnapshot>>,
671    ) {
672        self.publish_registry_impl(snapshot);
673    }
674
675    async fn abort(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
676        // The harness reclaims the queue and cancels the run under one write
677        // gate, so there is no `clear_queue()` + `abort()` window in which a
678        // message could be both drained into the transcript and handed back.
679        //
680        // Why this matters: the agent loop drains the steering queue on abort
681        // and emits those messages as transcript content. Native-pi's TUI
682        // avoids the resulting "ghost message" by calling `clearQueue()` first
683        // ("a cancel never silently swallows messages the user staged while the
684        // run was in flight"). A plugin has no editor to restore into, so it
685        // hands them back to its caller instead.
686        // `abort_reclaiming(true)`: one call cancels **and** reclaims under the
687        // harness's write gate, so the idle case is atomic too. A separate
688        // `clear_queue()` afterwards would let a new run start and drain the
689        // queue in between — the caller would then report "nothing was queued"
690        // for messages that were in fact consumed.
691        let harness = self.harness()?;
692        let result = harness
693            .abort_reclaiming(true)
694            .await
695            .map_err(|error| error.to_string())?;
696        Ok(serde_json::json!({
697            // Empty run id = the lane was already idle. The queue is still
698            // handed back: a stop button must be idempotent, and messages can
699            // land as a run settles.
700            "aborted": !result.run_id.is_empty(),
701            "runId": if result.run_id.is_empty() {
702                serde_json::Value::Null
703            } else {
704                serde_json::json!(result.run_id)
705            },
706            "steer": queued_message_payloads(&result.steer),
707            "followUp": queued_message_payloads(&result.follow_up),
708        }))
709    }
710
711    fn stop_round(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
712        self.harness()?.request_stop_round();
713        Ok(serde_json::json!({ "requested": true }))
714    }
715
716    async fn get_execution_context(
717        &self,
718        _args: serde_json::Value,
719    ) -> Result<serde_json::Value, String> {
720        let harness = self.harness()?;
721        let mut context = harness.execution_context().map_err(|e| e.to_string())?;
722        if let Some(serde_json::Value::Object(child)) =
723            rpi_agent::tool_execution_scope::public_execution_context()
724        {
725            context
726                .as_object_mut()
727                .expect("execution context is an object")
728                .extend(child);
729        }
730        context["cwd"] = serde_json::json!(self.cwd);
731        context["sessionId"] = serde_json::json!(harness.session().storage().metadata().id);
732        Ok(context)
733    }
734
735    async fn independent_run(
736        &self,
737        owner: u64,
738        args: serde_json::Value,
739    ) -> Result<serde_json::Value, String> {
740        self.independent_run_for_tool(owner, args, None).await
741    }
742
743    async fn independent_run_for_tool(
744        &self,
745        owner: u64,
746        args: serde_json::Value,
747        tool_call_id: Option<String>,
748    ) -> Result<serde_json::Value, String> {
749        if rpi_agent::tool_execution_scope::is_child_execution() {
750            return Err("nested independent runs are not allowed".into());
751        }
752        if args.get("op").and_then(serde_json::Value::as_str) == Some("start") {
753            self.independent_runs
754                .start_run(&self.harness()?, owner, &args, tool_call_id)
755                .await
756        } else {
757            // Reclamation must remain possible after the parent was dropped.
758            self.independent_runs.handle_run(owner, &args)
759        }
760    }
761
762    async fn get_cli_flag(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
763        let name = arg_str(&args, "name")?;
764        Ok(serde_json::json!({
765            "value": self.cli_flags.get(&name).cloned().unwrap_or(serde_json::Value::Null)
766        }))
767    }
768
769    async fn send_message(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
770        let options = send_message_options(&args)?;
771        let message = send_message_input(&args)?;
772        let lane = self.harness()?.lane("main");
773        let result = lane
774            .send_message(message, options)
775            .await
776            .map_err(|e| e.to_string())?;
777        Ok(send_message_result(result))
778    }
779
780    async fn send_user_message(
781        &self,
782        args: serde_json::Value,
783    ) -> Result<serde_json::Value, String> {
784        let text = arg_str(&args, "text")?;
785        let lane = self.harness()?.lane("main");
786        // Honor the same scheduling instructions `SendMessage` accepts.
787        //
788        // The action used to call `prompt_text` directly, which ignored
789        // `deliverAs` entirely. Two consequences:
790        //
791        // 1. A message sent while a run is in flight was rejected with
792        //    "lane busy" instead of being queued — and because this action
793        //    blocks for the whole run, callers that fire-and-forget (a bridge,
794        //    a remote UI) never saw the error. The message silently vanished.
795        // 2. `steer` / `followUp` / `nextTurn` were all delivered as "start a
796        //    new prompt", so a client could not express them at all.
797        //
798        // `send_message` with `triggerTurn: Some(true)` keeps the idle behavior
799        // (start a run) while giving an active run the queueing semantics the
800        // delivery mode asks for.
801        let mut options = send_message_options(&args)?;
802        if options.trigger_turn.is_none() {
803            options.trigger_turn = Some(true);
804        }
805        let message = rpi_agent::AgentMessage::User(rpi_ai::types::UserMessage::new(
806            text,
807            std::time::SystemTime::now()
808                .duration_since(std::time::UNIX_EPOCH)
809                .unwrap_or_default()
810                .as_millis()
811                .min(i64::MAX as u128) as i64,
812        ));
813        let result = lane
814            .send_message(message, options)
815            .await
816            .map_err(|e| e.to_string())?;
817        Ok(send_message_result(result))
818    }
819
820    async fn append_entry(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
821        // `{"message": <AgentMessage json>}` appends a message entry; OR
822        // `{"customType": "...", "data": {...}}` appends a custom entry. No run
823        // is driven. Messages use the harness boundary writer, whose entry id
824        // may be reserved until the current turn settles. Custom data stays out
825        // of model context unless a caller explicitly configures a projector.
826        if let Some(expected) = args.get("expected") {
827            let guard = serde_json::from_value(expected.clone())
828                .map_err(|error| format!("invalid AppendEntry expected guard: {error}"))?;
829            let entry = if let Some(custom_type) = arg_str_opt(&args, "customType") {
830                if args.get("message").is_some() || args.get("outboxKey").is_some() {
831                    return Err("scoped custom entry cannot include message/outboxKey".into());
832                }
833                crate::resource_selection::validate_public_entry(&custom_type, args.get("data"))?;
834                rpi_harness::agent_harness::ScopedEntry::Custom {
835                    custom_type,
836                    data: args.get("data").cloned(),
837                }
838            } else {
839                let message =
840                    serde_json::from_value(args.get("message").cloned().ok_or("missing message")?)
841                        .map_err(|error| format!("invalid message: {error}"))?;
842                let key = arg_str(&args, "outboxKey")?;
843                rpi_harness::agent_harness::ScopedEntry::Notice { message, key }
844            };
845            let id = self
846                .harness()?
847                .append_scoped_entry(&guard, entry)
848                .await
849                .map_err(|error| error.to_string())?;
850            return Ok(serde_json::json!({"entryId":id, "scoped":true}));
851        }
852        if args.get("outboxKey").is_some() {
853            return Err("outboxKey requires an expected guard".into());
854        }
855        if let Some(custom_type) = arg_str_opt(&args, "customType") {
856            crate::resource_selection::validate_public_entry(&custom_type, args.get("data"))?;
857            let data = args.get("data").cloned();
858            let id = self
859                .harness()?
860                .append_custom_entry(&custom_type, data)
861                .await
862                .map_err(|e| e.to_string())?;
863            return Ok(serde_json::json!({ "entryId": id }));
864        }
865        let msg = args
866            .get("message")
867            .ok_or_else(|| "missing `message` or `customType` field".to_string())?;
868        let message: rpi_agent::AgentMessage =
869            serde_json::from_value(msg.clone()).map_err(|e| format!("invalid message: {e}"))?;
870        let id = self
871            .harness()?
872            .append_message(message)
873            .await
874            .map_err(|e| e.to_string())?;
875        Ok(serde_json::json!({ "entryId": id }))
876    }
877
878    async fn get_session_branch(
879        &self,
880        args: serde_json::Value,
881    ) -> Result<serde_json::Value, String> {
882        let request = crate::modes::branch_entry_query(&args)?;
883        let (entries, session_id, leaf_id) =
884            crate::modes::branch_snapshot(&self.harness()?, &request).await?;
885        let entries = entries
886            .iter()
887            .map(serde_json::to_value)
888            .collect::<Result<Vec<_>, _>>()
889            .map_err(|e| format!("serialize session branch: {e}"))?;
890        Ok(serde_json::json!({
891            "entries": entries,
892            "count": entries.len(),
893            "filtered": true,
894            "sessionId": session_id,
895            "leafId": leaf_id,
896            "scopedAppend": true,
897        }))
898    }
899
900    async fn set_session_name(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
901        let name = arg_str(&args, "name")?;
902        self.harness()?
903            .session()
904            .set_name(Some(&name))
905            .await
906            .map_err(|e| e.to_string())?;
907        Ok(serde_json::Value::Null)
908    }
909
910    async fn get_active_tools(
911        &self,
912        _args: serde_json::Value,
913    ) -> Result<serde_json::Value, String> {
914        let lane = self.harness()?.lane("main");
915        let tools = lane.get_active_tools().await.map_err(|e| e.to_string())?;
916        Ok(serde_json::json!({ "tools": tools }))
917    }
918
919    async fn set_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
920        let tools = arg_str_array(&args, "tools")?;
921        let lane = self.harness()?.lane("main");
922        lane.set_active_tools(tools)
923            .await
924            .map_err(|e| e.to_string())?;
925        Ok(serde_json::Value::Null)
926    }
927
928    async fn set_model(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
929        let id = arg_str(&args, "model")?;
930        let model = self
931            .resolve_model(&id)
932            .ok_or_else(|| format!("model `{id}` not in catalog"))?;
933        let lane = self.harness()?.lane("main");
934        lane.set_model(model.clone())
935            .await
936            .map_err(|e| e.to_string())?;
937        Ok(serde_json::json!({ "model": model.id }))
938    }
939
940    async fn get_thinking_level(
941        &self,
942        _args: serde_json::Value,
943    ) -> Result<serde_json::Value, String> {
944        let lane = self.harness()?.lane("main");
945        let level = lane.get_thinking_level().await.map_err(|e| e.to_string())?;
946        Ok(serde_json::json!({ "level": level }))
947    }
948
949    async fn set_thinking_level(
950        &self,
951        args: serde_json::Value,
952    ) -> Result<serde_json::Value, String> {
953        let level_val = args
954            .get("level")
955            .ok_or_else(|| "missing `level` field".to_string())?;
956        let level: ThinkingLevel = if let Some(s) = level_val.as_str() {
957            serde_json::from_value(serde_json::Value::String(s.to_string()))
958                .map_err(|e| format!("invalid thinking level `{s}`: {e}"))?
959        } else {
960            serde_json::from_value(level_val.clone())
961                .map_err(|e| format!("invalid thinking level: {e}"))?
962        };
963        let lane = self.harness()?.lane("main");
964        lane.set_thinking_level(level)
965            .await
966            .map_err(|e| e.to_string())?;
967        Ok(serde_json::Value::Null)
968    }
969
970    async fn compact(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
971        let custom = arg_str_opt(&args, "customInstructions");
972        let lane = self.harness()?.lane("main");
973        let result = lane
974            .compact(custom.as_deref())
975            .await
976            .map_err(|e| e.to_string())?;
977        Ok(
978            serde_json::json!({ "runId": result.run_id, "outcome": format!("{:?}", result.outcome) }),
979        )
980    }
981
982    async fn get_system_prompt(
983        &self,
984        _args: serde_json::Value,
985    ) -> Result<serde_json::Value, String> {
986        let prompt = self
987            .harness()?
988            .get_system_prompt()
989            .await
990            .map_err(|e| e.to_string())?;
991        Ok(serde_json::json!({ "prompt": prompt }))
992    }
993
994    async fn new_session(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
995        let harness = self.harness()?;
996        let session = if self.ephemeral_sessions_only {
997            crate::session::ephemeral_session()
998        } else {
999            let cwd_str = self.cwd.to_string_lossy();
1000            let dir = &self.session_dir;
1001            std::fs::create_dir_all(dir)
1002                .map_err(|e| format!("create session dir {}: {e}", dir.display()))?;
1003            crate::session::create_jsonl_session(dir, &cwd_str)
1004                .await
1005                .map_err(|e| format!("create session: {e}"))?
1006        };
1007        let id = session.storage().metadata().id.clone();
1008        crate::session::set_active_session_with_identity(
1009            &harness,
1010            session,
1011            Some(&self.tool_context),
1012            self.publish_process_identity,
1013        )
1014        .await?;
1015        Ok(serde_json::json!({ "sessionId": id }))
1016    }
1017
1018    async fn fork(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
1019        self.allow_saved_sessions()?;
1020        let harness = self.harness()?;
1021        let cwd_str = self.cwd.to_string_lossy().to_string();
1022        let new_session =
1023            crate::session::fork_session_storage(&harness, &cwd_str, &self.session_dir)
1024                .await
1025                .map_err(|e| format!("fork session: {e}"))?;
1026        let id = new_session.storage().metadata().id.clone();
1027        crate::session::set_active_session_with_identity(
1028            &harness,
1029            new_session,
1030            Some(&self.tool_context),
1031            self.publish_process_identity,
1032        )
1033        .await?;
1034        Ok(serde_json::json!({ "sessionId": id }))
1035    }
1036
1037    async fn navigate_tree(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
1038        let target_id = arg_str_opt(&args, "targetId");
1039        let summarize = arg_bool(&args, "summarize");
1040        let custom = arg_str_opt(&args, "customInstructions");
1041        let label = arg_str_opt(&args, "label");
1042        let lane = self.harness()?.lane("main");
1043        let result = lane
1044            .navigate_tree(
1045                target_id.as_deref(),
1046                summarize,
1047                custom.as_deref(),
1048                label.as_deref(),
1049            )
1050            .await
1051            .map_err(|e| e.to_string())?;
1052        let status = match &result.outcome {
1053            NavigationOutcome::Completed { .. } => "completed",
1054            NavigationOutcome::Declined { .. } => "declined",
1055            NavigationOutcome::Aborted { .. } => "aborted",
1056            NavigationOutcome::Failed { .. } => "failed",
1057        };
1058        Ok(serde_json::json!({ "runId": result.run_id, "status": status }))
1059    }
1060
1061    async fn switch_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
1062        self.allow_saved_sessions()?;
1063        let harness = self.harness()?;
1064        let id = arg_str(&args, "id")?;
1065        let cwd_str = self.cwd.to_string_lossy().to_string();
1066        let new_session: Session = open_session_by_id_in_dir(&id, &cwd_str, &self.session_dir)
1067            .await
1068            .map(|restored| restored.session)
1069            .map_err(|e| e.to_string())?;
1070        let new_id = new_session.storage().metadata().id.clone();
1071        crate::session::set_active_session_with_identity(
1072            &harness,
1073            new_session,
1074            Some(&self.tool_context),
1075            self.publish_process_identity,
1076        )
1077        .await?;
1078        Ok(serde_json::json!({ "sessionId": new_id }))
1079    }
1080
1081    async fn reload(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
1082        // Reached only when `ActionBridge.reload` is `None` (no /reload wired).
1083        // B5d wires the reload callback at the bridge layer; this host impl is
1084        // the "not configured" fallback.
1085        Err("reload not configured (no /reload callback on this bridge)".to_string())
1086    }
1087}
1088
1089#[cfg(test)]
1090mod lifetime_tests;
1091
1092#[cfg(test)]
1093mod send_message_tests {
1094    use super::*;
1095    use rpi_harness::types::MessageDelivery;
1096
1097    #[test]
1098    fn options_accept_flat_and_nested_forms_with_pi_defaults() {
1099        assert_eq!(
1100            send_message_options(&serde_json::json!({"text":"context"})).unwrap(),
1101            SendMessageOptions::default()
1102        );
1103        let expected = SendMessageOptions {
1104            trigger_turn: Some(false),
1105            deliver_as: MessageDelivery::FollowUp,
1106        };
1107        for args in [
1108            serde_json::json!({"text":"context", "triggerTurn":false, "deliverAs":"followUp"}),
1109            serde_json::json!({"text":"context", "options":{"triggerTurn":false, "deliverAs":"followUp"}}),
1110        ] {
1111            assert_eq!(send_message_options(&args).unwrap(), expected);
1112        }
1113    }
1114
1115    #[test]
1116    fn options_reject_invalid_or_ambiguous_scheduling_instructions() {
1117        for args in [
1118            serde_json::json!({"triggerTurn":"false"}),
1119            serde_json::json!({"deliverAs":"follow-up"}),
1120            serde_json::json!({"options":{"typo":true}}),
1121            serde_json::json!({"options":[], "text":"context"}),
1122            serde_json::json!({"options":{"triggerTurn":true}, "triggerTurn":false}),
1123        ] {
1124            assert!(send_message_options(&args).is_err(), "{args}");
1125        }
1126    }
1127
1128    #[test]
1129    fn pi_custom_input_preserves_content_and_display_metadata() {
1130        let message = send_message_input(&serde_json::json!({"message":{
1131            "customType":"goal", "content":"goal state", "display":true, "details":{"step":2}
1132        }}))
1133        .unwrap();
1134        let rpi_agent::AgentMessage::Custom(custom) = &message else {
1135            panic!("custom")
1136        };
1137        assert_eq!(
1138            custom.content,
1139            vec![rpi_ai::types::Content::text("goal state")]
1140        );
1141        let data = rpi_harness::messages::custom_data(&message).unwrap();
1142        assert_eq!(data.custom_type, "goal");
1143        assert!(data.display);
1144        assert_eq!(data.details, Some(serde_json::json!({"step":2})));
1145        // The existing stored AgentMessage input remains supported.
1146        let stored = serde_json::to_value(&message).unwrap();
1147        assert_eq!(
1148            send_message_input(&serde_json::json!({"message":stored})).unwrap(),
1149            message
1150        );
1151    }
1152
1153    #[test]
1154    fn missing_custom_content_is_empty_and_queued_results_use_pi_delivery_names() {
1155        let message = send_message_input(
1156            &serde_json::json!({"message":{"customType":"goal", "content":null}}),
1157        )
1158        .unwrap();
1159        assert!(
1160            matches!(message, rpi_agent::AgentMessage::Custom(custom) if custom.content.is_empty())
1161        );
1162        assert_eq!(
1163            send_message_result(SendMessageResult::Queued {
1164                entry_id: "reserved".into(),
1165                queue: rpi_harness::session::types::QueueKind::NextRun,
1166            }),
1167            serde_json::json!({"status":"queued", "entryId":"reserved", "deliverAs":"nextTurn"})
1168        );
1169    }
1170}
1171
1172#[cfg(test)]
1173#[path = "extensions_actions/native_durable_inventory_tests.rs"]
1174mod native_durable_inventory_tests;
1175
1176#[cfg(test)]
1177mod list_commands_tests {
1178    use super::merge_command_list_reserved;
1179
1180    /// Reserving names must not delete the built-ins from the listing.
1181    ///
1182    /// The reservation set contains every built-in canonical name, so seeding
1183    /// the dedupe set with it silently dropped all of them: the real listing
1184    /// went from 32 built-ins to 0, leaving only extension entries.
1185    #[test]
1186    fn reserved_names_do_not_remove_the_builtins_themselves() {
1187        let builtin = vec![
1188            ("/help".to_string(), "help".to_string()),
1189            ("/model".to_string(), "model".to_string()),
1190        ];
1191        let out = merge_command_list_reserved(
1192            builtin,
1193            vec![("deploy".into(), "deploy".into())],
1194            vec![],
1195            // Every built-in name is reserved (as in production), plus an alias
1196            // and a hidden command that are not listed.
1197            vec![
1198                "/help".to_string(),
1199                "/model".to_string(),
1200                "/q".to_string(),
1201                "/context".to_string(),
1202            ],
1203        );
1204        assert_eq!(names(&out), vec!["/help", "/model", "/deploy"]);
1205        assert_eq!(out[0]["source"], "builtin");
1206        assert_eq!(out[1]["source"], "builtin");
1207        assert_eq!(out[2]["source"], "extension");
1208    }
1209
1210    /// A built-in alias or hidden built-in wins TUI dispatch without showing up
1211    /// as a suggestion, so an extension registering the same name must not be
1212    /// advertised as `source:"extension"`.
1213    #[test]
1214    fn reserved_builtin_aliases_hide_colliding_extension_entries() {
1215        let out = merge_command_list_reserved(
1216            vec![("/help".into(), "help".into())],
1217            vec![
1218                ("q".into(), "quit".into()),
1219                ("context".into(), "context".into()),
1220                ("deploy".into(), "deploy".into()),
1221            ],
1222            vec![],
1223            vec!["/q".into(), "/context".into()],
1224        );
1225        // `/q` and `/context` are unreachable, `/deploy` is not a built-in.
1226        assert_eq!(names(&out), vec!["/help", "/deploy"]);
1227        assert_eq!(out[1]["source"], "extension");
1228    }
1229
1230    fn names(v: &[serde_json::Value]) -> Vec<&str> {
1231        v.iter().map(|c| c["name"].as_str().unwrap()).collect()
1232    }
1233
1234    #[test]
1235    fn builtin_wins_over_a_same_named_extension_command() {
1236        let out = merge_command_list_reserved(
1237            vec![("/model".into(), "built-in".into())],
1238            vec![("/model".into(), "extension".into())],
1239            vec![],
1240            Vec::new(),
1241        );
1242        assert_eq!(names(&out), vec!["/model"]);
1243        assert_eq!(out[0]["source"], "builtin");
1244        assert_eq!(out[0]["description"], "built-in");
1245    }
1246
1247    #[test]
1248    fn extension_and_template_names_get_a_leading_slash() {
1249        let out = merge_command_list_reserved(
1250            vec![],
1251            vec![("deploy".into(), "deploy".into())],
1252            vec![("review".into(), "review".into())],
1253            Vec::new(),
1254        );
1255        assert_eq!(names(&out), vec!["/deploy", "/review"]);
1256        assert_eq!(out[0]["source"], "extension");
1257        assert_eq!(out[1]["source"], "prompt");
1258    }
1259
1260    /// Prompt templates live in neither the built-in registry nor the extension
1261    /// registry, so `ListCommands` has to merge them itself — otherwise a remote
1262    /// `/` completion list is permanently shorter than the terminal's.
1263    #[test]
1264    fn prompt_templates_are_listed_with_their_own_source() {
1265        let out = merge_command_list_reserved(
1266            vec![("/help".into(), "help".into())],
1267            vec![],
1268            vec![("review".into(), "review a diff".into())],
1269            Vec::new(),
1270        );
1271        assert_eq!(names(&out), vec!["/help", "/review"]);
1272        assert_eq!(out[1]["source"], "prompt");
1273        assert_eq!(out[1]["description"], "review a diff");
1274    }
1275
1276    /// A template sharing a built-in name is unreachable in the TUI too, so it
1277    /// must not be reported twice (or as `prompt`).
1278    #[test]
1279    fn a_builtin_name_is_not_reported_as_a_template() {
1280        let out = merge_command_list_reserved(
1281            vec![("/review".into(), "built-in".into())],
1282            vec![],
1283            vec![("review".into(), "template".into())],
1284            Vec::new(),
1285        );
1286        assert_eq!(names(&out), vec!["/review"]);
1287        assert_eq!(out[0]["source"], "builtin");
1288    }
1289
1290    #[test]
1291    fn no_commands_is_an_empty_list_not_an_error() {
1292        assert!(merge_command_list_reserved(vec![], vec![], vec![], Vec::new()).is_empty());
1293    }
1294}