Skip to main content

rpi_cli/host/
instruction_resources.rs

1//! Frozen instruction-only resources. Not an extension authority or loader.
2use super::ordinary::{BackendError, BackendResult};
3use crate::resource_selection::{self, ResolvedSelection, ResourceSelection, ToolSelection};
4use rpi_harness::{
5    session::{Session, SessionValues},
6    types::{AgentHarnessResources, HarnessTool},
7};
8use serde_json::{json, Value};
9use sha2::{Digest, Sha256};
10use std::collections::BTreeSet;
11
12/// Immutable, bounded explicit instruction snapshot. Construction performs only
13/// reads. This type cannot contain DLLs, package discovery or skill execution.
14/// A profile identifier is evidence of binding identity, never an authority grant.
15pub struct NativeInstructionResources {
16    selected: ResolvedSelection,
17    identity: String,
18}
19impl NativeInstructionResources {
20    pub fn freeze(selection: ResourceSelection) -> BackendResult<Self> {
21        let selected = ResolvedSelection::host_instructions(selection)
22            .map_err(|_| BackendError::Binding("invalid explicit instruction resources"))?;
23        if let ToolSelection::Only { names } = &selected.selection.tools {
24            let unique: BTreeSet<_> = names.iter().collect();
25            if unique.len() != names.len() || names.iter().any(|name| name.is_empty()) {
26                return Err(BackendError::Binding("invalid resource tool selection"));
27            }
28        }
29        let identity =
30            format!("instructions-v1:{:x}", Sha256::digest(serde_json::to_vec(
31            &json!({"selection":selected.selection,"instructions":selected.provenance()})
32        ).map_err(|_| BackendError::Binding("invalid resource identity"))?));
33        Ok(Self { selected, identity })
34    }
35    pub fn identity(&self) -> &str {
36        &self.identity
37    }
38    pub(super) fn validate_tools(&self, tools: &[String]) -> BackendResult<()> {
39        let matches = match &self.selected.selection.tools {
40            ToolSelection::Only { names } => names == tools,
41            ToolSelection::None {} => tools.is_empty(),
42            ToolSelection::Default {} => false,
43        };
44        if !matches {
45            return Err(BackendError::Binding(
46                "resource tools differ from exact Agent tools",
47            ));
48        }
49        Ok(())
50    }
51    pub(super) fn configure_parts(
52        &self,
53        prompt: &mut Option<String>,
54        provenance: &mut AgentHarnessResources,
55    ) {
56        let prompt = prompt.get_or_insert_with(String::new);
57        for (path, _, text) in &self.selected.instructions {
58            prompt.push_str("\n\n");
59            prompt.push_str(text);
60            provenance
61                .context_files
62                .push(path.to_string_lossy().into_owned());
63        }
64    }
65    fn inventory(&self, tools: &[HarnessTool]) -> Value {
66        let schemas: Vec<_> = tools.iter().map(|tool| json!(tool.tool.schema())).collect();
67        json!({"skills":[],"extensions":[],"toolSchemasSha256":format!("{:x}",
68            Sha256::digest(serde_json::to_vec(&schemas).expect("tool schemas serialize")))})
69    }
70    pub(super) fn validate(
71        &self,
72        values: &SessionValues,
73        tools: &[HarnessTool],
74    ) -> BackendResult<()> {
75        resource_selection::validate_exact_inventory(values, &self.selected, &self.inventory(tools))
76            .map_err(|_| {
77                BackendError::Binding("saved instruction resources or tool inventory changed")
78            })
79    }
80    /// Only called inside owned build, with the exact strict-committed Session,
81    /// before creating any Harness or publishing Live. Always sync on reopen,
82    /// including a binding left visible after a previous failed sync.
83    pub(super) async fn persist(
84        &self,
85        session: &Session,
86        tools: &[HarnessTool],
87    ) -> BackendResult<()> {
88        resource_selection::bind_inventory_to_session(
89            session,
90            &self.selected,
91            self.inventory(tools),
92        )
93        .await
94        .map_err(|_| BackendError::ResourcePersistence)?;
95        session.sync_history().await?;
96        Ok(())
97    }
98}