Skip to main content

rpi_cli/host/
profile.rs

1//! Explicit native Agent profiles for the foreground daemon.
2//!
3//! A profile is a private, absolute JSON file. It contains the Agent identity,
4//! workspace/session reference, a closed provider configuration (including any
5//! inline credential values), the exact tool environment, shell path and the
6//! trusted tool allowlist. Nothing falls back to CLI settings, process
7//! environment, ambient credentials or plugin discovery.
8//!
9//! This module only parses and validates. Persistent profiles selected for
10//! startup create/reopen a Session; explicit Mini profiles cannot reference one.
11//! Dynamically available profiles are frozen configuration, not implicit startup
12//! or execution. Mini daemon execution additionally requires separate private
13//! authority; parsing a profile alone never enables it.
14
15use super::{
16    bindings::{NativeBindingProfile, NativeToolPolicy},
17    ordinary::{BackendError, BackendResult, OrdinaryLimits},
18    AgentId, AgentMode, AgentSpec, ExecutionMode, LaunchSpec, ModelRef, SessionRef,
19    TimeoutOverrides,
20};
21use rpi_harness::types::AgentHarnessStreamOptions;
22use serde::Deserialize;
23#[cfg(any(unix, test))]
24use std::path::Path;
25use std::{
26    collections::{BTreeMap, BTreeSet},
27    path::PathBuf,
28    time::Duration,
29};
30
31/// Absolute profile byte budget. The document can contain provider credentials,
32/// so callers must read it through the private-file loader.
33pub const MAX_PROFILE_BYTES: u64 = 256 * 1024;
34const DEFAULT_MAX_INPUT_BYTES: usize = 8 * 1024 * 1024;
35const MAX_INPUT_BYTES: usize = 64 * 1024 * 1024;
36const MAX_STREAM_TIMEOUT_MS: u64 = 3_600_000;
37
38/// A validated native Agent input; its name does not imply automatic startup.
39pub struct HostStartupAgent {
40    pub spec: AgentSpec,
41    pub profile: NativeBindingProfile,
42    pub limits: OrdinaryLimits,
43}
44
45/// One private daemon Agent profile document (startup or dynamic-only).
46#[derive(Deserialize)]
47#[serde(deny_unknown_fields, rename_all = "camelCase")]
48pub struct AgentProfileFile {
49    agent: ProfileAgent,
50    runtime: rpi_runtime::config::ModelsConfig,
51    #[serde(default)]
52    provider_values: BTreeMap<String, String>,
53    tool_environment: BTreeMap<String, String>,
54    shell: PathBuf,
55    #[serde(default)]
56    approved_tools: Vec<String>,
57    #[serde(default)]
58    thinking: rpi_ai::ThinkingLevel,
59    #[serde(default)]
60    timeout_ms: Option<u64>,
61    #[serde(default)]
62    max_input_bytes: Option<usize>,
63    /// Exact v1 declaration; instructions/tools alone need no native grant.
64    /// Explicit extensions additionally require exact nativeHooks approval.
65    #[serde(default)]
66    resources: Option<crate::resource_selection::ResourceSelection>,
67    #[serde(default)]
68    native_hooks: Option<super::NativeHookConfig>,
69}
70
71#[derive(Deserialize)]
72#[serde(deny_unknown_fields, rename_all = "camelCase")]
73struct ProfileAgent {
74    id: AgentId,
75    name: String,
76    cwd: PathBuf,
77    #[serde(default = "persistent_mode")]
78    mode: AgentMode,
79    #[serde(default)]
80    session: Option<ProfileSession>,
81    model: ProfileModel,
82    #[serde(default)]
83    tools: Vec<String>,
84}
85
86#[derive(Deserialize)]
87#[serde(deny_unknown_fields, rename_all = "camelCase")]
88struct ProfileSession {
89    id: String,
90    path: PathBuf,
91}
92
93#[derive(Deserialize)]
94#[serde(deny_unknown_fields, rename_all = "camelCase")]
95struct ProfileModel {
96    provider: String,
97    model: String,
98}
99
100fn persistent_mode() -> AgentMode {
101    AgentMode::Persistent
102}
103
104fn bounded_text(value: &str, limit: usize) -> bool {
105    !value.is_empty()
106        && value.chars().count() <= limit
107        && !value.chars().any(char::is_control)
108        && value.trim() == value
109}
110
111impl AgentProfileFile {
112    /// Validate the document and produce the exact AgentSpec/native binding the
113    /// daemon will use. Rejections are fixed diagnostics without secret values.
114    pub fn into_startup(self) -> BackendResult<HostStartupAgent> {
115        if !bounded_text(&self.agent.name, 128) {
116            return Err(BackendError::Binding("profile Agent name is invalid"));
117        }
118        if !self.agent.cwd.is_absolute() {
119            return Err(BackendError::Binding("profile workspace must be absolute"));
120        }
121        let session = match (self.agent.mode, self.agent.session) {
122            (AgentMode::Persistent, Some(session)) => {
123                if !bounded_text(&session.id, 512) {
124                    return Err(BackendError::Binding("profile Session id is invalid"));
125                }
126                if !session.path.is_absolute() {
127                    return Err(BackendError::Binding(
128                        "profile Session path must be absolute",
129                    ));
130                }
131                Some(SessionRef {
132                    id: session.id,
133                    path: session.path,
134                })
135            }
136            (AgentMode::Persistent, None) => {
137                return Err(BackendError::Binding(
138                    "persistent profile requires a Session",
139                ))
140            }
141            (AgentMode::Mini, Some(_)) => {
142                return Err(BackendError::Binding(
143                    "mini profile must not reference a Session",
144                ))
145            }
146            (AgentMode::Mini, None) => None,
147        };
148        if !bounded_text(&self.agent.model.provider, 128)
149            || !bounded_text(&self.agent.model.model, 256)
150        {
151            return Err(BackendError::Binding("profile model reference is invalid"));
152        }
153        if self.runtime.providers.is_empty() {
154            return Err(BackendError::Binding(
155                "profile has no runtime provider configuration",
156            ));
157        }
158        let approved: BTreeSet<String> = self.approved_tools.into_iter().collect();
159        if self.agent.tools.iter().any(|tool| !approved.contains(tool)) {
160            return Err(BackendError::Binding(
161                "profile requests a tool that is not preapproved",
162            ));
163        }
164        let max_input_bytes = self.max_input_bytes.unwrap_or(DEFAULT_MAX_INPUT_BYTES);
165        if max_input_bytes == 0
166            || max_input_bytes > MAX_INPUT_BYTES
167            || (self.agent.mode == AgentMode::Mini && max_input_bytes > DEFAULT_MAX_INPUT_BYTES)
168        {
169            return Err(BackendError::Binding("profile input budget is invalid"));
170        }
171        let timeout = match self.timeout_ms {
172            Some(ms) if ms == 0 || ms > MAX_STREAM_TIMEOUT_MS => {
173                return Err(BackendError::Binding("profile stream timeout is invalid"))
174            }
175            Some(ms) => Some(Duration::from_millis(ms)),
176            None => None,
177        };
178        if self.shell.as_os_str().is_empty() || !self.shell.is_absolute() {
179            return Err(BackendError::Binding("profile shell path must be absolute"));
180        }
181        let instruction_resources = match (self.resources, self.native_hooks) {
182            (None, None) => None,
183            (Some(selection), hooks) => Some(std::sync::Arc::new(
184                super::NativeBindingResources::freeze(selection, hooks)?,
185            )),
186            (None, Some(_)) => {
187                return Err(BackendError::Binding(
188                    "native hooks require exact resources",
189                ))
190            }
191        };
192        if let Some(resources) = &instruction_resources {
193            resources.validate_tools(&self.agent.tools)?;
194        }
195        let spec = AgentSpec {
196            id: self.agent.id,
197            name: self.agent.name,
198            parent_id: None,
199            mode: self.agent.mode,
200            execution: ExecutionMode::InProcess,
201            session,
202            launch: LaunchSpec {
203                cwd: self.agent.cwd,
204                model: Some(ModelRef {
205                    provider: self.agent.model.provider,
206                    model: self.agent.model.model,
207                }),
208                tools: self.agent.tools,
209                resource_profile: instruction_resources
210                    .as_ref()
211                    .map(|r| r.identity().to_owned()),
212            },
213            timeouts: TimeoutOverrides::default(),
214        };
215        let profile = NativeBindingProfile {
216            runtime: rpi_runtime::RuntimeConfig {
217                models: self.runtime,
218                credentials: Default::default(),
219                settings: Default::default(),
220            },
221            provider_values: self.provider_values,
222            tool_environment: self.tool_environment,
223            shell_path: self.shell,
224            tools: NativeToolPolicy::Preapproved(approved),
225            thinking: self.thinking,
226            stream_options: AgentHarnessStreamOptions {
227                timeout,
228                ..Default::default()
229            },
230            instruction_resources,
231        };
232        Ok(HostStartupAgent {
233            spec,
234            profile,
235            limits: OrdinaryLimits { max_input_bytes },
236        })
237    }
238}
239
240/// Canonical workspace and Session paths used when creating a new Session.
241/// Existing Session files are left for the ordinary strict restore to verify.
242#[cfg(any(unix, test))]
243pub fn canonical_workspace(spec: &AgentSpec) -> BackendResult<PathBuf> {
244    std::fs::canonicalize(&spec.launch.cwd)
245        .map_err(|_| BackendError::Binding("profile workspace is unavailable"))
246}
247
248#[cfg(any(unix, test))]
249pub fn session_parent(path: &Path) -> BackendResult<PathBuf> {
250    let parent = path
251        .parent()
252        .ok_or(BackendError::Binding("profile Session path has no parent"))?;
253    if !parent.is_dir() {
254        return Err(BackendError::Binding(
255            "profile Session parent directory is unavailable",
256        ));
257    }
258    Ok(parent.to_path_buf())
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use serde_json::json;
265
266    fn base(workspace: &Path) -> serde_json::Value {
267        json!({
268            "agent": {
269                "id": "11111111-1111-4111-8111-111111111111",
270                "name": "profile-agent",
271                "cwd": workspace.to_string_lossy(),
272                "session": {"id": "profile-session", "path": workspace.join("s.jsonl").to_string_lossy()},
273                "model": {"provider": "fixture", "model": "host-fixture"},
274                "tools": ["read"]
275            },
276            "runtime": {"providers": {"fixture": {
277                "api": "openai-completions",
278                "baseUrl": "http://127.0.0.1:9/v1",
279                "apiKey": "$PROFILE_KEY",
280                "models": [{"id": "host-fixture", "contextWindow": 32768, "maxTokens": 1024}]
281            }}},
282            "providerValues": {"PROFILE_KEY": "private-key"},
283            "toolEnvironment": {"HOME": workspace.to_string_lossy(), "PATH": "/usr/bin:/bin"},
284            "shell": "/bin/sh",
285            "approvedTools": ["read"],
286            "thinking": "off",
287            "timeoutMs": 1000
288        })
289    }
290
291    fn parse(value: serde_json::Value) -> Result<HostStartupAgent, BackendError> {
292        serde_json::from_value::<AgentProfileFile>(value)
293            .map_err(|_| BackendError::Binding("invalid Agent profile"))
294            .and_then(AgentProfileFile::into_startup)
295    }
296
297    #[test]
298    fn explicit_profile_builds_a_closed_ordinary_spec() {
299        let workspace = tempfile::tempdir().unwrap();
300        let startup = parse(base(workspace.path())).unwrap();
301        assert_eq!(startup.spec.name, "profile-agent");
302        assert_eq!(startup.spec.mode, AgentMode::Persistent);
303        assert_eq!(startup.spec.execution, ExecutionMode::InProcess);
304        assert_eq!(startup.spec.launch.tools, vec!["read".to_string()]);
305        assert_eq!(
306            startup.spec.launch.model.as_ref().unwrap().provider,
307            "fixture"
308        );
309        assert_eq!(startup.limits.max_input_bytes, DEFAULT_MAX_INPUT_BYTES);
310        assert_eq!(
311            startup.profile.stream_options.timeout,
312            Some(Duration::from_millis(1000))
313        );
314        assert!(matches!(
315            startup.profile.tools,
316            NativeToolPolicy::Preapproved(ref tools) if tools.contains("read")
317        ));
318    }
319
320    #[test]
321    fn explicit_modes_enforce_session_identity_without_creating_files() {
322        let workspace = tempfile::tempdir().unwrap();
323        let mut value = base(workspace.path());
324        value["agent"]["mode"] = json!("persistent");
325        assert!(parse(value.clone()).unwrap().spec.session.is_some());
326        value["agent"].as_object_mut().unwrap().remove("session");
327        assert!(parse(value.clone()).is_err());
328        value["agent"].as_object_mut().unwrap().remove("mode");
329        assert!(
330            parse(value.clone()).is_err(),
331            "legacy profiles still require a Session"
332        );
333        value["agent"]["mode"] = json!("mini");
334        let mini = parse(value.clone()).unwrap();
335        assert_eq!(mini.spec.mode, AgentMode::Mini);
336        assert!(mini.spec.session.is_none());
337        mini.spec.validate().unwrap();
338        value["agent"]["session"] = serde_json::Value::Null;
339        assert!(parse(value.clone()).unwrap().spec.session.is_none());
340        value["agent"]["session"] = base(workspace.path())["agent"]["session"].clone();
341        assert!(
342            parse(value.clone()).is_err(),
343            "mini must not ignore a Session reference"
344        );
345        for mode in [json!("unknown"), json!("Mini"), json!(null), json!(true)] {
346            value["agent"]["mode"] = mode;
347            assert!(parse(value.clone()).is_err());
348        }
349        assert_eq!(std::fs::read_dir(workspace.path()).unwrap().count(), 0);
350    }
351
352    #[test]
353    fn profile_rejects_relative_paths_unapproved_tools_and_unknown_fields() {
354        let workspace = tempfile::tempdir().unwrap();
355        for (mutate, expected) in [
356            (
357                Box::new(|value: &mut serde_json::Value| {
358                    value["agent"]["cwd"] = json!("relative/workspace");
359                }) as Box<dyn Fn(&mut serde_json::Value)>,
360                "workspace must be absolute",
361            ),
362            (
363                Box::new(|value: &mut serde_json::Value| {
364                    value["agent"]["session"]["path"] = json!("relative.jsonl");
365                }),
366                "Session path must be absolute",
367            ),
368            (
369                Box::new(|value: &mut serde_json::Value| {
370                    value["agent"]["tools"] = json!(["bash"]);
371                }),
372                "not preapproved",
373            ),
374            (
375                Box::new(|value: &mut serde_json::Value| {
376                    value["approvedTools"] = json!([]);
377                }),
378                "not preapproved",
379            ),
380            (
381                Box::new(|value: &mut serde_json::Value| {
382                    value["shell"] = json!("sh");
383                }),
384                "shell path must be absolute",
385            ),
386            (
387                Box::new(|value: &mut serde_json::Value| {
388                    value["timeoutMs"] = json!(0);
389                }),
390                "stream timeout is invalid",
391            ),
392            (
393                Box::new(|value: &mut serde_json::Value| {
394                    value["maxInputBytes"] = json!(0);
395                }),
396                "input budget is invalid",
397            ),
398            (
399                Box::new(|value: &mut serde_json::Value| {
400                    value["runtime"] = json!({"providers": {}});
401                }),
402                "no runtime provider configuration",
403            ),
404        ] {
405            let mut value = base(workspace.path());
406            mutate(&mut value);
407            let error = parse(value).err().expect("profile must be rejected");
408            assert!(error.to_string().contains(expected), "{error}");
409        }
410        let mut unknown = base(workspace.path());
411        unknown["ambientSettings"] = json!(true);
412        assert!(serde_json::from_value::<AgentProfileFile>(unknown).is_err());
413    }
414
415    #[test]
416    fn instruction_profiles_freeze_content_and_reject_unsupported_authority() {
417        let workspace = tempfile::tempdir().unwrap();
418        let path = workspace.path().join("instruction.md");
419        std::fs::write(&path, "frozen {{placeholder}}").unwrap();
420        let mut value = base(workspace.path());
421        value["resources"] =
422            json!({"version":1,"tools":{"mode":"only","names":["read"]},"instructions":[path]});
423        let startup = parse(value.clone()).unwrap();
424        let frozen = startup.spec.launch.resource_profile.clone().unwrap();
425        assert_eq!(
426            frozen,
427            startup
428                .profile
429                .instruction_resources
430                .as_ref()
431                .unwrap()
432                .identity()
433        );
434        std::fs::write(&path, "replacement").unwrap();
435        assert_ne!(
436            frozen,
437            parse(value.clone())
438                .unwrap()
439                .spec
440                .launch
441                .resource_profile
442                .unwrap()
443        );
444        // Existing owned snapshots never re-read a changed source file.
445        assert_eq!(
446            frozen,
447            startup
448                .profile
449                .instruction_resources
450                .as_ref()
451                .unwrap()
452                .identity()
453        );
454        for resources in [
455            json!({"version":2,"tools":{"mode":"only","names":["read"]}}),
456            json!({"version":1,"tools":{"mode":"default"}}),
457            json!({"version":1,"tools":{"mode":"none"}}),
458            json!({"version":1,"tools":{"mode":"only","names":["read","read"]}}),
459            json!({"version":1,"tools":{"mode":"only","names":["bash"]}}),
460            json!({"version":1,"tools":{"mode":"only","names":["read"]},"instructions":["relative.md"]}),
461            json!({"version":1,"tools":{"mode":"only","names":["read"]},"instructions":[path,path]}),
462            json!({"version":1,"tools":{"mode":"only","names":["read"]},"extensions":[path]}),
463            json!({"version":1,"tools":{"mode":"only","names":["read"]},"skills":[workspace.path()]}),
464            json!({"version":1,"tools":{"mode":"only","names":["read"]},"main_package":{"name":"ambient"}}),
465        ] {
466            value["resources"] = resources;
467            assert!(
468                parse(value.clone()).is_err(),
469                "unsupported resource accepted"
470            );
471        }
472        value["resources"] =
473            json!({"version":1,"tools":{"mode":"only","names":["read"]},"instructions":[path]});
474        std::fs::write(&path, vec![0xff]).unwrap();
475        assert!(parse(value.clone()).is_err());
476        std::fs::write(&path, "x".repeat(64 * 1024 + 1)).unwrap();
477        assert!(parse(value).is_err());
478        assert!(!workspace.path().join("s.jsonl").exists());
479    }
480
481    #[test]
482    fn profile_requires_an_absolute_home_in_the_closed_tool_environment() {
483        let workspace = tempfile::tempdir().unwrap();
484        let mut value = base(workspace.path());
485        value["toolEnvironment"] = json!({"PATH": "/usr/bin:/bin"});
486        // Parsing succeeds; bind is what enforces the explicit HOME baseline.
487        let startup = parse(value).unwrap();
488        let runtime = tokio::runtime::Builder::new_current_thread()
489            .enable_all()
490            .build()
491            .unwrap();
492        let error = runtime
493            .block_on(startup.profile.bind(startup.spec))
494            .err()
495            .expect("missing HOME must be rejected");
496        assert!(error.to_string().contains("tool environment"), "{error}");
497    }
498
499    #[test]
500    fn session_parent_and_workspace_checks_are_explicit() {
501        let workspace = tempfile::tempdir().unwrap();
502        let startup = parse(base(workspace.path())).unwrap();
503        assert_eq!(
504            canonical_workspace(&startup.spec).unwrap(),
505            workspace.path().canonicalize().unwrap()
506        );
507        assert_eq!(
508            session_parent(&startup.spec.session.as_ref().unwrap().path).unwrap(),
509            workspace.path()
510        );
511        let mut missing = startup.spec.clone();
512        missing.launch.cwd = workspace.path().join("absent");
513        assert!(canonical_workspace(&missing).is_err());
514    }
515}