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