1use sha2::{Digest, Sha256};
3use std::collections::HashSet;
4use std::io::Read;
5use std::path::{Component, Path, PathBuf};
6use std::sync::{Mutex, OnceLock, Weak};
7
8use rpi_harness::agent_harness::AgentHarness;
9use rpi_harness::session::types::SessionStorage;
10use serde::{Deserialize, Serialize};
11use serde_json::{json, Value};
12
13use crate::args::{Args, Mode};
14mod fork;
15pub(crate) use fork::initial_values as fork_initial_values;
16pub(crate) use fork::initial_values_for_selection as fork_initial_values_for_selection;
17
18pub const MAX_SELECTION_BYTES: usize = 64 * 1024;
19pub const MAX_STATE_BYTES: usize = 256 * 1024;
20pub(crate) fn transition_capability() -> Value {
21 json!({"version":1, "startupFlag":"--resource-transition", "maxRequestBytes":MAX_SELECTION_BYTES,
22 "maxOperationIdBytes":128,"operationIdPattern":"^[A-Za-z0-9._-]{1,128}$",
23 "request":{"requiredFields":["version","operation_id","expected","target"],
24 "unknownFields":"reject","duplicateFields":"reject",
25 "expected":{"revision":"u64","fingerprint":"lowercase-sha256-or-null","unboundRevision":0},
26 "target":"complete-exact-selection-v1"},
27 "expected":"revision-and-fingerprint", "retry":"same-operation-current-binding", "legacyTarget":false})
28}
29
30pub(crate) const MAX_CAPABILITIES_BYTES: usize = 16 * 1024;
31pub(crate) fn capabilities() -> Value {
33 json!({"version":1,"type":"resource_capabilities","maxResponseBytes":MAX_CAPABILITIES_BYTES,
34 "host":{"name":crate::APP_NAME,"version":crate::VERSION},
35 "exactSelection":{"versions":[1],"startupFlag":"--resource-config","mode":"rpc",
36 "maxConfigBytes":MAX_SELECTION_BYTES,"maxSnapshotBytes":MAX_STATE_BYTES,
37 "stateCommand":"get_resource_state","toolModes":["default","only","none"],
38 "packageScopes":["project","global"],"ordinaryReopen":"immutable","hotApply":false},
39 "management":crate::resource_management::capabilities(),
40 "transition":transition_capability(),"savedSessionRead":crate::saved_session_read::capabilities(),"loadedFacts":false})
41}
42const SESSION_KEY: &str = "rpi.resource-selection.v1";
43
44pub(crate) fn validate_public_entry(custom_type: &str, data: Option<&Value>) -> Result<(), String> {
47 if custom_type == rpi_harness::session::values::VALUE_CUSTOM_TYPE
48 && data
49 .and_then(|d| d.get("key"))
50 .and_then(Value::as_str)
51 .is_some_and(|key| {
52 key.starts_with("rpi.resource-selection.")
53 || key.starts_with("rpi.resource-inventory.")
54 })
55 {
56 return Err(
57 "host-owned resource session values cannot be appended through public APIs".into(),
58 );
59 }
60 Ok(())
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
64#[serde(deny_unknown_fields)]
65pub struct ResourceSelection {
66 pub version: u32,
67 pub main_package: Option<MainPackage>,
68 #[serde(default)]
69 pub skills: Vec<PathBuf>,
70 #[serde(default)]
71 pub extensions: Vec<PathBuf>,
72 #[serde(default)]
73 pub instructions: Vec<PathBuf>,
74 pub tools: ToolSelection,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(deny_unknown_fields)]
79pub struct MainPackage {
80 pub name: String,
81 #[serde(
82 default,
83 skip_serializing_if = "crate::resource_management::Scope::is_project"
84 )]
85 pub scope: crate::resource_management::Scope,
86 #[serde(default)]
88 pub instructions: Vec<PathBuf>,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
92#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
93pub enum ToolSelection {
94 Default {},
95 Only { names: Vec<String> },
96 None {},
97}
98
99#[derive(Debug, Clone, Serialize)]
100pub struct ResolvedPackage {
101 pub name: String,
102 pub version: Option<String>,
103 pub source: String,
104 pub cargo_package: Option<String>,
105 pub root: PathBuf,
106}
107
108#[derive(Debug, Clone)]
109pub struct ResolvedSelection {
110 pub package: Option<ResolvedPackage>,
111 pub selection: ResourceSelection,
112 pub skills: Vec<PathBuf>,
113 pub extensions: Vec<PathBuf>,
114 pub instructions: Vec<(PathBuf, String, String)>,
115 pub transition: Option<ResourceTransition>,
116 validated_skills: Option<ValidatedSkills>,
117}
118
119#[derive(Debug, Clone)]
120pub(crate) struct ValidatedSkills {
121 pub skills: Vec<rpi_harness::types::Skill>,
122 inventory: Value,
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize)]
126#[serde(deny_unknown_fields)]
127pub struct ResourceTransition {
128 pub version: u32,
129 pub operation_id: String,
130 pub expected: ExpectedBinding,
131 pub target: ResourceSelection,
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
135#[serde(deny_unknown_fields)]
136pub struct ExpectedBinding {
137 pub revision: u64,
138 pub fingerprint: Option<String>,
139}
140
141impl ResourceTransition {
142 fn validate(&self) -> Result<(), String> {
143 if self.version != 1
144 || self.operation_id.is_empty()
145 || self.operation_id.len() > 128
146 || !self
147 .operation_id
148 .bytes()
149 .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
150 || (self.expected.revision == 0) != self.expected.fingerprint.is_none()
151 || self.expected.fingerprint.as_ref().is_some_and(|f| {
152 f.len() != 64
153 || !f
154 .bytes()
155 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
156 })
157 {
158 return Err(
159 "invalid resource transition version, operation ID or expected binding".into(),
160 );
161 }
162 Ok(())
163 }
164}
165
166fn contained(path: &Path, root: &Path) -> Result<PathBuf, String> {
167 let path = std::fs::canonicalize(path).map_err(|e| e.to_string())?;
168 if !path.starts_with(root) || path == root {
169 return Err(format!(
170 "package resource escapes canonical package root: {}",
171 path.display()
172 ));
173 }
174 Ok(path)
175}
176
177fn validate_package_tree(
180 path: &Path,
181 root: &Path,
182 visited: &mut HashSet<PathBuf>,
183) -> Result<(), String> {
184 let path = contained(path, root)?;
185 if path.is_dir() {
186 if !visited.insert(path.clone()) {
187 return Err("package resource directory cycle/alias".into());
188 }
189 for entry in std::fs::read_dir(path).map_err(|e| e.to_string())? {
190 validate_package_tree(&entry.map_err(|e| e.to_string())?.path(), root, visited)?;
191 }
192 }
193 Ok(())
194}
195
196fn read_limited(path: &Path) -> Result<Vec<u8>, String> {
197 let mut bytes = Vec::new();
198 std::fs::File::open(path)
199 .map_err(|e| format!("{}: {e}", path.display()))?
200 .take((MAX_SELECTION_BYTES + 1) as u64)
201 .read_to_end(&mut bytes)
202 .map_err(|e| e.to_string())?;
203 if bytes.len() > MAX_SELECTION_BYTES {
204 return Err(format!("resource input exceeds 64 KiB: {}", path.display()));
205 }
206 Ok(bytes)
207}
208fn fingerprint(path: &Path) -> Result<String, String> {
209 let mut reader = std::fs::File::open(path).map_err(|e| e.to_string())?;
210 let mut hash = Sha256::new();
211 let mut buf = [0; 8192];
212 loop {
213 let n = reader.read(&mut buf).map_err(|e| e.to_string())?;
214 if n == 0 {
215 break;
216 }
217 hash.update(&buf[..n]);
218 }
219 Ok(format!("{:x}", hash.finalize()))
220}
221
222fn file(path: &Path) -> Result<PathBuf, String> {
223 if !path.is_file() {
224 return Err(format!("missing resource file: {}", path.display()));
225 }
226 std::fs::canonicalize(path).map_err(|e| e.to_string())
227}
228fn unique_paths(paths: &[PathBuf]) -> Result<(), String> {
229 let mut seen = HashSet::new();
230 for path in paths {
231 if !seen.insert(path) {
232 return Err(format!("duplicate resource: {}", path.display()));
233 }
234 }
235 Ok(())
236}
237fn relative(path: &Path) -> Result<(), String> {
238 if path.as_os_str().is_empty()
239 || path
240 .components()
241 .any(|c| !matches!(c, Component::Normal(_)))
242 {
243 return Err(format!(
244 "expected a package-relative path: {}",
245 path.display()
246 ));
247 }
248 Ok(())
249}
250
251impl ResolvedSelection {
252 pub fn load(args: &Args, cwd: &Path, trusted: bool) -> Result<Option<Self>, String> {
253 Self::load_for(&crate::config::AgentHome::process(), args, cwd, trusted)
254 }
255
256 pub fn load_for(
257 home: &crate::config::AgentHome,
258 args: &Args,
259 cwd: &Path,
260 trusted: bool,
261 ) -> Result<Option<Self>, String> {
262 let Some(config) = args
263 .resource_transition
264 .as_ref()
265 .or(args.resource_config.as_ref())
266 else {
267 return Ok(None);
268 };
269 if let Some(error) = args.fork_cut_errors().first() {
270 return Err((*error).to_owned());
271 }
272 if (args.resource_config.is_some() && args.resource_transition.is_some())
273 || (args.resource_transition.is_some()
274 && (args.name.is_some()
275 || args.fork.is_some()
276 || args.no_session
277 || !args.messages.is_empty()))
278 || args.mode != Mode::Rpc
279 || args.dev_local_only
280 || args.project_only
281 || args.trust_override == Some(false)
282 || !trusted
283 || args.system_prompt.is_some()
284 || !args.append_system_prompt.is_empty()
285 || args.tools.is_some()
286 || args.exclude_tools.is_some()
287 || args.no_tools
288 || args.no_builtin_tools
289 || args.no_skills
290 || args.no_prompt_templates
291 || args.no_extensions
292 || args.no_context_files
293 || !args.skill.is_empty()
294 || !args.prompt_template.is_empty()
295 || !args.extension.is_empty()
296 || !args.extensions_dir.is_empty()
297 || !args.unknown_flags.is_empty()
298 {
299 return Err("--resource-config requires trusted --mode rpc and conflicts with resource/tool/prompt/discovery/dev flags and unknown extension flags".into());
300 }
301 let bytes = read_limited(&cwd.join(config))?;
302 let transition: Option<ResourceTransition> = if args.resource_transition.is_some() {
303 let request: ResourceTransition = serde_json::from_slice(&bytes)
304 .map_err(|e| format!("invalid resource transition: {e}"))?;
305 request.validate()?;
306 Some(request)
307 } else {
308 None
309 };
310 let selection: ResourceSelection = if let Some(request) = &transition {
311 request.target.clone()
312 } else {
313 serde_json::from_slice(&bytes).map_err(|e| format!("invalid resource config: {e}"))?
314 };
315 if selection.version != 1 {
316 return Err("unsupported resource config version".into());
317 }
318 if let ToolSelection::Only { names } = &selection.tools {
319 let mut seen = HashSet::new();
320 for name in names {
321 if name.is_empty() || !seen.insert(name) {
322 return Err("empty or duplicate tool name".into());
323 }
324 }
325 }
326 let mut skills = Vec::new();
327 let mut extensions = Vec::new();
328 let mut instructions = Vec::new();
329 let mut resolved_package = None;
330 if let Some(main) = &selection.main_package {
331 let native_root = main.scope.root(home, cwd)?;
332 let package = crate::packages::selected_package_at(&native_root, &main.name)?;
333 let packages_root =
334 std::fs::canonicalize(native_root.join("packages")).map_err(|e| e.to_string())?;
335 let root = std::fs::canonicalize(packages_root.join(&main.name))
336 .map_err(|e| format!("missing package directory: {e}"))?;
337 if !root.is_dir() || !root.starts_with(&packages_root) || root == packages_root {
338 return Err("package root escapes .rpi/packages".into());
339 }
340 let skill_dir = root.join("skills");
341 if skill_dir.exists() {
342 let skill_dir = contained(&skill_dir, &root)?;
343 validate_package_tree(&skill_dir, &root, &mut HashSet::new())?;
344 skills.push(skill_dir);
345 }
346 for artifact in &package.artifacts {
347 relative(Path::new(artifact))?;
348 extensions.push(contained(
349 &file(&root.join("extensions").join(artifact))?,
350 &root,
351 )?);
352 }
353 for instruction in &main.instructions {
354 relative(instruction)?;
355 let path = contained(&file(&root.join(instruction))?, &root)?;
356 instructions.push((path, format!("package:{}", main.name), String::new()));
357 }
358 resolved_package = Some(ResolvedPackage {
359 name: package.name,
360 version: if package.version.is_empty() {
361 None
362 } else {
363 Some(package.version)
364 },
365 source: package.source,
366 cargo_package: if package.cargo_package.is_empty() {
367 None
368 } else {
369 Some(package.cargo_package)
370 },
371 root,
372 });
373 }
374 let mut additions = Vec::new();
376 for skill in &selection.skills {
377 let path = cwd.join(skill);
378 if !path.exists() {
379 return Err(format!("missing skill: {}", path.display()));
380 }
381 additions.push(std::fs::canonicalize(path).map_err(|e| e.to_string())?);
382 }
383 additions.extend(skills);
384 skills = additions;
385 for extension in &selection.extensions {
386 extensions.push(file(&cwd.join(extension))?);
387 }
388 for instruction in &selection.instructions {
389 instructions.push((
390 file(&cwd.join(instruction))?,
391 "explicit".into(),
392 String::new(),
393 ));
394 }
395 unique_paths(&skills)?;
396 unique_paths(&extensions)?;
397 unique_paths(&instructions.iter().map(|i| i.0.clone()).collect::<Vec<_>>())?;
398 for extension in &extensions {
399 if extension.extension().and_then(|e| e.to_str())
400 != Some(std::env::consts::DLL_EXTENSION)
401 {
402 return Err(format!("not a native extension: {}", extension.display()));
403 }
404 }
405 for (path, _, text) in &mut instructions {
406 *text = String::from_utf8(read_limited(path)?)
407 .map_err(|e| format!("instruction {}: {e}", path.display()))?;
408 }
409 Ok(Some(Self {
410 package: resolved_package,
411 selection,
412 skills,
413 extensions,
414 instructions,
415 transition,
416 validated_skills: None,
417 }))
418 }
419
420 pub(crate) fn host_instructions(selection: ResourceSelection) -> Result<Self, String> {
423 if selection.version != 1
424 || selection.main_package.is_some()
425 || !selection.skills.is_empty()
426 || !selection.extensions.is_empty()
427 || selection.instructions.len() > 32
428 || matches!(selection.tools, ToolSelection::Default {})
429 {
430 return Err("unsupported Host instruction resource selection".into());
431 }
432 let mut instructions = Vec::new();
433 let mut total = 0usize;
434 for path in &selection.instructions {
435 if !path.is_absolute() {
436 return Err("Host instruction path must be absolute".into());
437 }
438 let path = file(path)?;
439 let text = String::from_utf8(read_limited(&path)?)
440 .map_err(|_| "Host instruction must be UTF-8")?;
441 total = total
442 .checked_add(text.len())
443 .ok_or("instruction size overflow")?;
444 if total > MAX_SELECTION_BYTES {
445 return Err("Host instructions exceed 64 KiB".into());
446 }
447 instructions.push((path, "explicit".into(), text));
448 }
449 unique_paths(&instructions.iter().map(|i| i.0.clone()).collect::<Vec<_>>())?;
450 Ok(Self {
451 selection,
452 package: None,
453 skills: Vec::new(),
454 extensions: Vec::new(),
455 instructions,
456 transition: None,
457 validated_skills: Some(ValidatedSkills {
458 skills: Vec::new(),
459 inventory: json!([]),
460 }),
461 })
462 }
463
464 pub(crate) async fn validate_skills(
467 &mut self,
468 env: &std::sync::Arc<dyn rpi_tools::ExecutionEnv>,
469 ) -> Result<(), String> {
470 let hashes = Mutex::new(std::collections::HashMap::new());
471 let observe = |path: &str, raw: &str| {
472 hashes.lock().unwrap().insert(
473 path.to_owned(),
474 format!("{:x}", Sha256::digest(raw.as_bytes())),
475 );
476 };
477 let mut skills = Vec::new();
478 let mut diagnostics = Vec::new();
479 for path in &self.skills {
480 let loaded = rpi_harness::skills::load_skills_with_source_observer(
481 env,
482 &[path.to_string_lossy().into_owned()],
483 &observe,
484 )
485 .await;
486 if loaded.skills.is_empty() {
487 return Err(format!(
488 "selected skill source loaded no Skills: {}",
489 path.display()
490 ));
491 }
492 skills.extend(loaded.skills);
493 diagnostics.extend(loaded.diagnostics);
494 }
495 let skills = crate::resource_dirs::dedupe_skills(skills, &mut diagnostics);
496 if !diagnostics.is_empty() {
497 return Err(format!("selected skill diagnostics: {diagnostics:?}"));
498 }
499 let hashes = hashes.into_inner().unwrap();
500 let inventory = json!(skills
501 .iter()
502 .map(|skill| json!({
503 "name": skill.name, "path": skill.file_path, "sha256": hashes[&skill.file_path]
504 }))
505 .collect::<Vec<_>>());
506 self.validated_skills = Some(ValidatedSkills { skills, inventory });
507 Ok(())
508 }
509
510 pub(crate) fn validated_skills(&self) -> Result<&ValidatedSkills, String> {
511 self.validated_skills
512 .as_ref()
513 .ok_or_else(|| "selected Skills were not preflight validated".into())
514 }
515
516 pub fn active_tools(&self, registered: &[String]) -> Result<Vec<String>, String> {
517 match &self.selection.tools {
518 ToolSelection::Default {} => Ok(registered.to_vec()),
519 ToolSelection::None {} => Ok(Vec::new()),
520 ToolSelection::Only { names } => {
521 for name in names {
522 if !registered.contains(name) {
523 return Err(format!("unknown selected tool: {name}"));
524 }
525 }
526 Ok(names.clone())
527 }
528 }
529 }
530
531 pub fn provenance(&self) -> Value {
532 json!(self.instructions.iter().map(|(path, source, text)| json!({"path": path, "source": source, "sha256": format!("{:x}",Sha256::digest(text.as_bytes()))})).collect::<Vec<_>>())
533 }
534}
535
536type Attachment = (Weak<dyn SessionStorage>, Value);
539fn states() -> &'static Mutex<Vec<Attachment>> {
540 static STATES: OnceLock<Mutex<Vec<Attachment>>> = OnceLock::new();
541 STATES.get_or_init(|| Mutex::new(Vec::new()))
542}
543pub(crate) fn attach(harness: &AgentHarness, state: Value) {
544 let mut states = states().lock().unwrap();
545 states.retain(|(storage, _)| storage.strong_count() > 0);
546 states.push((
547 std::sync::Arc::downgrade(&harness.session().storage()),
548 state,
549 ));
550}
551
552pub async fn get_resource_state(harness: &AgentHarness) -> Result<Value, String> {
553 let storage = harness.session().storage();
554 let state = states().lock().unwrap().iter().find_map(|(s, state)| {
555 s.upgrade()
556 .filter(|s| std::sync::Arc::ptr_eq(s, &storage))
557 .map(|_| state.clone())
558 });
559 let mut state = state.ok_or("get_resource_state requires --resource-config v1")?;
560 let metadata = harness
561 .session()
562 .get_metadata()
563 .await
564 .map_err(|e| e.to_string())?;
565 let resources = harness.get_resources().await.map_err(|e| e.to_string())?;
566 let registered: Vec<_> = harness
567 .get_tools()
568 .await
569 .map_err(|e| e.to_string())?
570 .iter()
571 .map(|t| t.tool.schema().name.clone())
572 .collect();
573 let execution = harness.execution_context().map_err(|e| e.to_string())?;
574 let active = execution["tools"].clone();
575 let read = active
576 .as_array()
577 .is_some_and(|names| names.iter().any(|n| n == "read"));
578 state["sessionId"] = json!(metadata.id);
579 let values = rpi_harness::session::SessionValues::load(harness.session())
580 .await
581 .map_err(|e| e.to_string())?;
582 if let Some(binding) = values.get(SESSION_KEY) {
583 validate_persisted_binding(binding)?;
584 }
585 state["binding"] = binding_state(&values);
586 state["transition"] = transition_capability();
587 state["registeredTools"] = json!(registered);
588 state["modelEffectiveTools"] = active;
589 state["loadedSkills"] = json!(resources.skills.unwrap_or_default().iter().map(|s| json!({
590 "name": s.name, "path": s.file_path, "modelVisible": read && !s.disable_model_invocation.unwrap_or(false)
591 })).collect::<Vec<_>>());
592 state["promptTemplates"] = json!(resources
593 .prompt_templates
594 .unwrap_or_default()
595 .iter()
596 .map(|t| &t.name)
597 .collect::<Vec<_>>());
598 if serde_json::to_vec(&state).map_err(|e| e.to_string())?.len() > MAX_STATE_BYTES {
599 return Err("resource snapshot exceeds 256 KiB".into());
600 }
601 Ok(state)
602}
603
604fn declaration(s: &ResolvedSelection) -> Value {
605 json!({"selection": s.selection, "package": s.package, "skills": s.skills, "extensions": s.extensions, "instructions": s.provenance()})
606}
607
608pub(crate) async fn bind_session(
609 session: &rpi_harness::session::Session,
610 selected: Option<&ResolvedSelection>,
611) -> Result<(), String> {
612 use rpi_harness::session::SessionValues;
613 let values = SessionValues::load(session)
614 .await
615 .map_err(|e| e.to_string())?;
616 validate_session_binding(&values, selected)
617}
618
619pub(crate) fn validate_session_binding(
621 values: &rpi_harness::session::SessionValues,
622 selected: Option<&ResolvedSelection>,
623) -> Result<(), String> {
624 if let Some(binding) = values.get(SESSION_KEY) {
625 validate_persisted_binding(binding)?;
626 }
627 if let Some(request) = selected.and_then(|s| s.transition.as_ref()) {
628 validate_transition(values, request)?;
629 if values
631 .get(SESSION_KEY)
632 .and_then(|v| v.get("operationId"))
633 .and_then(Value::as_str)
634 != Some(request.operation_id.as_str())
635 {
636 return Ok(());
637 }
638 }
639 match (values.get(SESSION_KEY), selected) {
640 (Some(old), Some(selected)) if old.get("declaration") == Some(&declaration(selected)) => {
641 let extensions = selected.extensions.iter().map(|path| Ok(json!({"path":path,"sha256":fingerprint(path)?})))
644 .collect::<Result<Vec<_>, String>>()?;
645 if old.pointer("/inventory/extensions") != Some(&json!(extensions)) {
646 return Err("session resource artifact inventory changed; restore original resources or use a new session".into());
647 }
648 if old.pointer("/inventory/skills") != Some(&selected.validated_skills()?.inventory) {
649 return Err("session resource Skill inventory changed; restore original resources or use a new session".into());
650 }
651 Ok(())
652 },
653 (Some(_), _) => Err("session resource selection differs or is missing; restart with the same declared selection or use a new session".into()),
654 (None, _) => Ok(()),
655 }
656}
657
658fn binding_fingerprint(binding: &Value) -> String {
660 format!(
661 "{:x}",
662 Sha256::digest(
663 serde_json::to_vec(&json!({
664 "declaration": binding["declaration"], "inventory": binding["inventory"]
665 }))
666 .expect("JSON binding")
667 )
668 )
669}
670
671fn valid_digest(value: &Value) -> bool {
672 value.as_str().is_some_and(|s| {
673 s.len() == 64
674 && s.bytes()
675 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
676 })
677}
678
679fn validate_persisted_binding(binding: &Value) -> Result<u64, String> {
681 let invalid = || "invalid persisted resource binding metadata".to_string();
682 let object = binding.as_object().ok_or_else(invalid)?;
683 if !object.get("declaration").is_some_and(Value::is_object)
684 || !object.get("inventory").is_some_and(Value::is_object)
685 || serde_json::to_vec(binding).map_err(|_| invalid())?.len() > MAX_STATE_BYTES
686 {
687 return Err(invalid());
688 }
689 let revision = match object.get("revision") {
690 None if !object.contains_key("operationId") && !object.contains_key("operations") => 1,
691 Some(value) => value.as_u64().filter(|r| *r > 0).ok_or_else(invalid)?,
692 None => return Err(invalid()),
693 };
694 let operations = match object.get("operations") {
695 Some(value) => Some(value.as_object().ok_or_else(invalid)?),
696 None => None,
697 };
698 let current = match object.get("operationId") {
699 Some(value) => Some(value.as_str().ok_or_else(invalid)?),
700 None => None,
701 };
702 let mut revisions = std::collections::HashSet::new();
703 if let Some(operations) = operations {
704 for (id, operation) in operations {
705 if id.is_empty()
706 || id.len() > 128
707 || !id
708 .bytes()
709 .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
710 {
711 return Err(invalid());
712 }
713 let op = operation.as_object().ok_or_else(invalid)?;
714 if op.len() != 4
715 || !valid_digest(&operation["target"])
716 || !valid_digest(&operation["fingerprint"])
717 {
718 return Err(invalid());
719 }
720 let expected: ExpectedBinding =
721 serde_json::from_value(operation["expected"].clone()).map_err(|_| invalid())?;
722 if (expected.revision == 0) != expected.fingerprint.is_none()
723 || expected
724 .fingerprint
725 .as_ref()
726 .is_some_and(|f| !valid_digest(&json!(f)))
727 {
728 return Err(invalid());
729 }
730 let result = operation["revision"].as_u64().ok_or_else(invalid)?;
731 if expected.revision.checked_add(1) != Some(result)
732 || result > revision
733 || !revisions.insert(result)
734 {
735 return Err(invalid());
736 }
737 if current == Some(id.as_str()) {
738 let target = format!(
739 "{:x}",
740 Sha256::digest(
741 serde_json::to_vec(&binding["declaration"]["selection"])
742 .map_err(|_| invalid())?
743 )
744 );
745 if result != revision
746 || operation["fingerprint"] != binding_fingerprint(binding)
747 || operation["target"] != target
748 {
749 return Err(invalid());
750 }
751 } else if result == revision {
752 return Err(invalid());
753 }
754 if let Some(previous) = operations
757 .values()
758 .find(|p| p["revision"].as_u64() == Some(expected.revision))
759 {
760 if previous["fingerprint"] != json!(expected.fingerprint) {
761 return Err(invalid());
762 }
763 }
764 }
765 }
766 if let Some(operations) = operations {
767 if !operations.is_empty() {
768 let first = *revisions.iter().min().ok_or_else(invalid)?;
769 if first > 2
770 || revision.checked_sub(first).and_then(|n| n.checked_add(1))
771 != Some(operations.len() as u64)
772 {
773 return Err(invalid());
774 }
775 }
776 }
777 match current {
778 Some(id) if !operations.is_some_and(|ops| ops.contains_key(id)) => return Err(invalid()),
779 None if operations.is_some_and(|ops| !ops.is_empty()) || revision != 1 => {
780 return Err(invalid())
781 }
782 _ => {}
783 }
784 Ok(revision)
785}
786
787pub(crate) fn saved_binding_state(
788 values: &rpi_harness::session::SessionValues,
789) -> Result<Value, String> {
790 if let Some(binding) = values.get(SESSION_KEY) {
791 validate_persisted_binding(binding)?;
792 }
793 Ok(binding_state(values))
794}
795pub(crate) fn binding_state(values: &rpi_harness::session::SessionValues) -> Value {
796 match values.get(SESSION_KEY) {
797 Some(binding) => match validate_persisted_binding(binding) {
798 Ok(revision) => json!({"revision": revision,
799 "fingerprint": binding_fingerprint(binding), "operationId": binding.get("operationId")}),
800 Err(error) => json!({"error": error}),
801 },
802 None => json!({"revision": 0, "fingerprint": null, "operationId": null}),
803 }
804}
805
806fn target_fingerprint(request: &ResourceTransition) -> String {
807 format!(
808 "{:x}",
809 Sha256::digest(serde_json::to_vec(&request.target).expect("typed target"))
810 )
811}
812
813fn validate_transition(
814 values: &rpi_harness::session::SessionValues,
815 request: &ResourceTransition,
816) -> Result<(), String> {
817 let old = values.get(SESSION_KEY);
818 if let Some(binding) = old {
819 validate_persisted_binding(binding)?;
820 }
821 let actual = binding_state(values);
822 if let Some(operation) = old
823 .and_then(|v| v.get("operations"))
824 .and_then(|v| v.get(&request.operation_id))
825 {
826 if operation["target"] != target_fingerprint(request)
827 || operation["expected"] != json!(request.expected)
828 || actual["operationId"] != request.operation_id
829 || operation["revision"] != actual["revision"]
830 || operation["fingerprint"] != actual["fingerprint"]
831 {
832 return Err("resource transition operation conflict or superseded retry".into());
833 }
834 return Ok(());
835 }
836 if actual["revision"] != request.expected.revision
837 || actual["fingerprint"] != json!(request.expected.fingerprint)
838 {
839 return Err("stale resource transition expected binding".into());
840 }
841 Ok(())
842}
843
844pub(crate) async fn bind_inventory(
847 harness: &AgentHarness,
848 selected: &ResolvedSelection,
849) -> Result<(), String> {
850 let resources = harness.get_resources().await.map_err(|e| e.to_string())?;
851 let mut skills = Vec::new();
852 for skill in resources.skills.unwrap_or_default() {
853 skills.push(json!({"name": skill.name, "path": skill.file_path, "sha256": fingerprint(Path::new(&skill.file_path))?}));
854 }
855 if json!(skills) != selected.validated_skills()?.inventory {
858 return Err("session resource Skill inventory changed after preflight".into());
859 }
860 let mut extensions = Vec::new();
861 for path in &selected.extensions {
862 extensions.push(json!({"path": path, "sha256": fingerprint(path)?}));
863 }
864 let tools: Vec<_> = harness
865 .get_tools()
866 .await
867 .map_err(|e| e.to_string())?
868 .iter()
869 .map(|t| json!(t.tool.schema()))
870 .collect();
871 let inventory = json!({"skills":skills, "extensions":extensions, "toolSchemasSha256":format!("{:x}",Sha256::digest(serde_json::to_vec(&tools).map_err(|e| e.to_string())?))});
872 bind_inventory_to_session(harness.session(), selected, inventory).await
873}
874
875pub(crate) fn validate_exact_inventory(
878 values: &rpi_harness::session::SessionValues,
879 selected: &ResolvedSelection,
880 inventory: &Value,
881) -> Result<(), String> {
882 validate_session_binding(values, Some(selected))?;
883 let candidate = json!({"declaration":declaration(selected),"inventory":inventory,"revision":1});
884 if serde_json::to_vec(&candidate)
885 .map_err(|e| e.to_string())?
886 .len()
887 > MAX_STATE_BYTES
888 {
889 return Err("resource binding exceeds 256 KiB".into());
890 }
891 if values
892 .get(SESSION_KEY)
893 .is_some_and(|old| old.get("inventory") != Some(inventory))
894 {
895 return Err("session resource inventory changed".into());
896 }
897 Ok(())
898}
899
900pub(crate) async fn bind_inventory_to_session(
903 session: &rpi_harness::session::Session,
904 selected: &ResolvedSelection,
905 inventory: Value,
906) -> Result<(), String> {
907 use rpi_harness::session::{SessionValueWriter, SessionValues};
908 let values = SessionValues::load(session)
909 .await
910 .map_err(|e| e.to_string())?;
911 validate_session_binding(&values, Some(selected))?;
912 let old = values.get(SESSION_KEY);
913 let retry = selected.transition.as_ref().is_some_and(|r| {
914 old.and_then(|v| v.get("operationId"))
915 .and_then(Value::as_str)
916 == Some(r.operation_id.as_str())
917 });
918 if let Some(old) = old.filter(|_| selected.transition.is_none() || retry) {
919 if old.get("inventory") != Some(&inventory)
920 || old.get("declaration") != Some(&declaration(selected))
921 {
922 return Err(
923 "session resource inventory changed; use original resources or a new session"
924 .into(),
925 );
926 }
927 } else {
928 let revision = binding_state(&values)["revision"]
930 .as_u64()
931 .unwrap()
932 .checked_add(1)
933 .ok_or("resource binding revision overflow")?;
934 let mut binding = json!({"declaration": declaration(selected), "inventory": inventory, "revision": revision});
935 if let Some(request) = &selected.transition {
936 let mut operations = old
937 .and_then(|v| v.get("operations"))
938 .cloned()
939 .unwrap_or(json!({}));
940 operations[&request.operation_id] = json!({"target": target_fingerprint(request), "expected": request.expected,
941 "revision": revision, "fingerprint": binding_fingerprint(&binding)});
942 binding["operations"] = operations;
943 binding["operationId"] = json!(request.operation_id);
944 }
945 if serde_json::to_vec(&binding)
946 .map_err(|e| e.to_string())?
947 .len()
948 > MAX_STATE_BYTES
949 {
950 return Err("resource binding/operation ledger exceeds 256 KiB".into());
951 }
952 SessionValueWriter::new(session.clone())
953 .set(SESSION_KEY, binding)
954 .await
955 .map_err(|e| e.to_string())?;
956 }
957 Ok(())
958}
959
960#[cfg(test)]
961mod tests {
962 use super::*;
963 #[test]
964 fn typed_schema_rejects_unknown_and_duplicate_fields_at_each_level() {
965 for input in [
966 r#"{"version":1,"tools":{"mode":"none","unexpected":1}}"#,
967 r#"{"version":1,"tools":{"mode":"default","names":[]}}"#,
968 r#"{"version":1,"main_package":{"name":"x","unexpected":1},"tools":{"mode":"none"}}"#,
969 r#"{"version":1,"version":1,"tools":{"mode":"none"}}"#,
970 r#"{"version":1,"tools":{"mode":"only","names":[],"unexpected":1}}"#,
971 ] {
972 assert!(
973 serde_json::from_str::<ResourceSelection>(input).is_err(),
974 "{input}"
975 );
976 }
977 for path in ["../outside.md", "./instruction.md", ""] {
978 assert!(relative(Path::new(path)).is_err());
979 }
980 }
981
982 #[test]
983 fn configuration_instruction_and_registry_reads_are_bounded() {
984 let temp = tempfile::tempdir().unwrap();
985 let root = temp.path();
986 let input = root.join("input.md");
987 std::fs::write(&input, vec![b'x'; MAX_SELECTION_BYTES]).unwrap();
988 assert_eq!(read_limited(&input).unwrap().len(), MAX_SELECTION_BYTES);
989 std::fs::write(&input, vec![b'x'; MAX_SELECTION_BYTES + 1]).unwrap();
990 assert!(read_limited(&input).unwrap_err().contains("exceeds 64 KiB"));
991 std::fs::create_dir(root.join(".rpi")).unwrap();
992 std::fs::write(
993 root.join(".rpi/packages.json"),
994 vec![b' '; MAX_STATE_BYTES + 1],
995 )
996 .unwrap();
997 assert!(crate::packages::selected_project_package(root, "valid")
998 .unwrap_err()
999 .contains("exceeds 256 KiB"));
1000 }
1001
1002 #[tokio::test]
1003 async fn real_storage_v1_reopen_and_complete_committed_retry_never_double_revision() {
1004 use rpi_harness::session::jsonl::{JsonlSessionStorage, JsonlV4Header};
1005 use rpi_harness::session::{Session, SessionValueWriter, SessionValues};
1006 let temp = tempfile::tempdir().unwrap();
1007 let path = temp.path().join("history.jsonl");
1008 let fs: std::sync::Arc<dyn rpi_tools::FileSystem> =
1009 std::sync::Arc::new(rpi_tools::OsExecutionEnv::with_cwd(temp.path().into()));
1010 let clock = std::sync::Arc::new(rpi_harness::session::memory::SystemClock);
1011 let ids = std::sync::Arc::new(rpi_harness::session::session::DefaultIdGenerator::new());
1012 let storage = JsonlSessionStorage::create(
1013 fs.clone(),
1014 path.to_str().unwrap(),
1015 JsonlV4Header::new(
1016 "binding-retry".into(),
1017 1,
1018 temp.path().to_string_lossy().into(),
1019 None,
1020 None,
1021 None,
1022 ),
1023 clock.clone(),
1024 ids.clone(),
1025 )
1026 .await
1027 .unwrap();
1028 let session = Session::new(std::sync::Arc::new(storage), None);
1029 let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
1030 session: session.clone(),
1031 ..Default::default()
1032 })
1033 .await
1034 .unwrap();
1035 let message = session
1036 .append_message(rpi_agent::message::AgentMessage::User(
1037 rpi_ai::types::UserMessage::new("preserved real message", 1),
1038 ))
1039 .await
1040 .unwrap();
1041 let mut selected = ResolvedSelection {
1042 package: None,
1043 selection: serde_json::from_value(json!({"version":1,"tools":{"mode":"none"}}))
1044 .unwrap(),
1045 skills: vec![],
1046 extensions: vec![],
1047 instructions: vec![],
1048 transition: None,
1049 validated_skills: None,
1050 };
1051 let env: std::sync::Arc<dyn rpi_tools::ExecutionEnv> =
1052 std::sync::Arc::new(rpi_tools::OsExecutionEnv::with_cwd(temp.path().into()));
1053 selected.validate_skills(&env).await.unwrap();
1054 bind_inventory(&harness, &selected).await.unwrap();
1055 let mut old = SessionValues::load(&session)
1058 .await
1059 .unwrap()
1060 .get(SESSION_KEY)
1061 .unwrap()
1062 .clone();
1063 old.as_object_mut().unwrap().remove("revision");
1064 let original = old.clone();
1065 for (field, value) in [
1066 ("revision", json!("corrupt")),
1067 ("revision", json!(null)),
1068 ("revision", json!(0)),
1069 ("operations", json!([])),
1070 ("operations", json!(1)),
1071 ("operationId", json!(7)),
1072 ("operations", json!({"bad":null})),
1073 (
1074 "operations",
1075 json!({"bad":{"target":"bad","expected":{"revision":0,"fingerprint":null},"revision":1,"fingerprint":"bad"}}),
1076 ),
1077 ] {
1078 let mut damaged = original.clone();
1079 damaged[field] = value;
1080 SessionValueWriter::new(session.clone())
1081 .set(SESSION_KEY, damaged)
1082 .await
1083 .unwrap();
1084 let before = std::fs::read(&path).unwrap();
1085 assert!(bind_session(&session, Some(&selected))
1086 .await
1087 .unwrap_err()
1088 .contains("invalid persisted"));
1089 assert!(bind_inventory(&harness, &selected).await.is_err());
1090 let facts = SessionValues::load(&session).await.unwrap();
1091 assert!(binding_state(&facts).get("error").is_some());
1092 assert_eq!(std::fs::read(&path).unwrap(), before);
1093 }
1094 SessionValueWriter::new(session.clone())
1095 .set(SESSION_KEY, original)
1096 .await
1097 .unwrap();
1098 let bytes = std::fs::read(&path).unwrap();
1099 bind_session(&session, Some(&selected)).await.unwrap();
1100 bind_inventory(&harness, &selected).await.unwrap();
1101 assert_eq!(std::fs::read(&path).unwrap(), bytes);
1102 let base = binding_state(&SessionValues::load(&session).await.unwrap());
1103 assert_eq!(base["revision"], 1);
1104 selected.selection.tools = ToolSelection::Only { names: vec![] };
1105 selected.transition = Some(ResourceTransition {
1106 version: 1,
1107 operation_id: "committed-with-lost-result".into(),
1108 expected: serde_json::from_value(
1109 json!({"revision":base["revision"],"fingerprint":base["fingerprint"]}),
1110 )
1111 .unwrap(),
1112 target: selected.selection.clone(),
1113 });
1114 bind_inventory(&harness, &selected).await.unwrap();
1115 drop(harness);
1116 drop(session);
1117 let committed = std::fs::read(&path).unwrap();
1118 let storage = JsonlSessionStorage::load_for_resource_transition(
1119 fs,
1120 path.to_str().unwrap(),
1121 clock,
1122 ids,
1123 )
1124 .await
1125 .unwrap();
1126 let session = Session::new(std::sync::Arc::new(storage), None);
1127 let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
1128 session: session.clone(),
1129 allow_existing_session: true,
1130 ..Default::default()
1131 })
1132 .await
1133 .unwrap();
1134 bind_session(&session, Some(&selected)).await.unwrap();
1137 bind_inventory(&harness, &selected).await.unwrap();
1138 assert_eq!(std::fs::read(&path).unwrap(), committed);
1139 let state = binding_state(&SessionValues::load(&session).await.unwrap());
1140 assert_eq!(state["revision"], 2);
1141 assert_eq!(state["operationId"], "committed-with-lost-result");
1142 assert!(session.get_entry(&message).await.unwrap().is_some());
1143 }
1144
1145 #[test]
1146 fn persisted_operation_associations_are_validated_in_full() {
1147 let selected = json!({"version":1,"tools":{"mode":"none"}});
1148 let target = format!(
1149 "{:x}",
1150 Sha256::digest(serde_json::to_vec(&selected).unwrap())
1151 );
1152 let mut binding = json!({"declaration":{"selection":selected},"inventory":{},"revision":2,"operationId":"one"});
1153 let fingerprint = binding_fingerprint(&binding);
1154 binding["operations"] = json!({"one":{"target":target,"expected":{"revision":1,"fingerprint":"a".repeat(64)},"revision":2,"fingerprint":fingerprint}});
1155 assert_eq!(validate_persisted_binding(&binding).unwrap(), 2);
1156 for (pointer, value) in [
1157 ("/operationId", json!("missing")),
1158 ("/operations/one/target", json!("b".repeat(64))),
1159 ("/operations/one/fingerprint", json!("b".repeat(64))),
1160 (
1161 "/operations/one/expected",
1162 json!({"revision":1,"fingerprint":null}),
1163 ),
1164 (
1165 "/operations/one/expected",
1166 json!({"revision":0,"fingerprint":"a".repeat(64)}),
1167 ),
1168 ("/operations/one/revision", json!(3)),
1169 ("/operations/one/expected/revision", json!("1")),
1170 ] {
1171 let mut damaged = binding.clone();
1172 *damaged.pointer_mut(pointer).unwrap() = value;
1173 assert!(validate_persisted_binding(&damaged).is_err(), "{pointer}");
1174 }
1175 let mut damaged = binding.clone();
1176 damaged["operations"]["older"] = json!({"target":"c".repeat(64),"expected":{"revision":0,"fingerprint":null},"revision":1,"fingerprint":"d".repeat(64)});
1177 assert!(validate_persisted_binding(&damaged).is_err());
1178 damaged["operations"]["one"]["expected"]["fingerprint"] = json!("d".repeat(64));
1179 assert!(validate_persisted_binding(&damaged).is_ok());
1180 }
1181
1182 #[tokio::test]
1183 async fn validated_skills_keep_parsed_content_and_exact_source_hash() {
1184 let temp = tempfile::tempdir().unwrap();
1185 let root = temp.path();
1186 std::fs::create_dir_all(root.join("review")).unwrap();
1187 let path = root.join("review/SKILL.md");
1188 let raw = "---\r\nname: review\r\ndescription: Review fixture\r\n---\r\nOriginal body\r\n";
1189 std::fs::write(&path, raw).unwrap();
1190 std::fs::write(
1191 root.join("resources.json"),
1192 r#"{"version":1,"skills":["review"],"tools":{"mode":"none"}}"#,
1193 )
1194 .unwrap();
1195 let args = Args {
1196 mode: Mode::Rpc,
1197 resource_config: Some("resources.json".into()),
1198 ..Default::default()
1199 };
1200 let mut selected = ResolvedSelection::load(&args, root, true).unwrap().unwrap();
1201 let env: std::sync::Arc<dyn rpi_tools::ExecutionEnv> =
1202 std::sync::Arc::new(rpi_tools::OsExecutionEnv::with_cwd(root.to_path_buf()));
1203 selected.validate_skills(&env).await.unwrap();
1204 let validated = selected.validated_skills().unwrap();
1205 assert_eq!(
1206 validated.inventory[0]["sha256"],
1207 format!("{:x}", Sha256::digest(raw.as_bytes()))
1208 );
1209 assert_eq!(validated.skills[0].name, "review");
1210 let content = validated.skills[0].content.clone();
1211 std::fs::write(&path, "---\nname: [\n---\nMalformed replacement").unwrap();
1214 assert_eq!(
1215 selected.validated_skills().unwrap().skills[0].content,
1216 content
1217 );
1218 assert_ne!(
1219 selected.validated_skills().unwrap().inventory[0]["sha256"],
1220 fingerprint(&path).unwrap()
1221 );
1222 }
1223
1224 #[tokio::test]
1225 async fn overlapping_skill_roots_fail_closed_without_validated_inventory() {
1226 let temp = tempfile::tempdir().unwrap();
1227 let root = temp.path();
1228 std::fs::create_dir(root.join("review")).unwrap();
1229 std::fs::write(
1230 root.join("review/SKILL.md"),
1231 "---\nname: review\ndescription: Review fixture\n---\nValid body\n",
1232 )
1233 .unwrap();
1234 std::fs::write(
1235 root.join("resources.json"),
1236 r#"{"version":1,"skills":["review","review/SKILL.md"],"tools":{"mode":"none"}}"#,
1237 )
1238 .unwrap();
1239 let args = Args {
1240 mode: Mode::Rpc,
1241 resource_config: Some("resources.json".into()),
1242 ..Default::default()
1243 };
1244 let mut selected = ResolvedSelection::load(&args, root, true).unwrap().unwrap();
1247 let env: std::sync::Arc<dyn rpi_tools::ExecutionEnv> =
1248 std::sync::Arc::new(rpi_tools::OsExecutionEnv::with_cwd(root.to_path_buf()));
1249 let error = selected.validate_skills(&env).await.unwrap_err();
1250 assert!(error.contains("selected skill diagnostics"), "{error}");
1251 assert!(error.contains("shadowed"), "{error}");
1252 assert!(error.contains("first-registration wins"), "{error}");
1253 assert!(selected.validated_skills().is_err());
1254 }
1255
1256 #[tokio::test]
1257 async fn snapshot_errors_without_exact_mode_and_when_oversized() {
1258 let harness = AgentHarness::create(Default::default()).await.unwrap();
1259 assert!(get_resource_state(&harness)
1260 .await
1261 .unwrap_err()
1262 .contains("requires --resource-config"));
1263 harness.seal_resources(vec![]).unwrap();
1264 attach(&harness, json!({"oversized": "x".repeat(MAX_STATE_BYTES)}));
1265 assert!(get_resource_state(&harness)
1266 .await
1267 .unwrap_err()
1268 .contains("exceeds 256 KiB"));
1269 }
1270}