oino-resources 1.0.0

Resource loading for Oino: context files, skills, prompt templates, system prompt, project trust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Project trust (runtime §9.7).

use std::path::{Path, PathBuf};

use oino_settings::paths::{CONFIG_DIR_NAME, TRUST_FILE, canonicalize_or_self, lexical_normalize};
use oino_settings::storage::{FileLock, write_atomic};
use oino_settings::{JsonObject, ProjectTrustDefault};
use serde_json::Value;

/// Project-local entries under `.oino/` that require trust (the
/// `TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES`, without `mcp.json`: no MCP in core).
pub const PROTECTED_PROJECT_RESOURCES: [&str; 7] = [
    "settings.json",
    "extensions",
    "skills",
    "prompts",
    "themes",
    "SYSTEM.md",
    "APPEND_SYSTEM.md",
];

/// A saved trust decision: `Some(true|false)`, or `None` for "no decision".
pub type ProjectTrustDecision = Option<bool>;

/// A saved decision and the (canonical) directory it was saved for.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrustEntry {
    /// Canonical directory key in `trust.json`.
    pub path: PathBuf,
    /// Trusted or not.
    pub trusted: bool,
}

/// One edit of `trust.json` (`decision: None` deletes the key).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrustUpdate {
    /// Directory (canonicalised on write).
    pub path: PathBuf,
    /// New decision.
    pub decision: ProjectTrustDecision,
}

/// A selectable trust answer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrustOption {
    /// Label shown to the user.
    pub label: String,
    /// Whether choosing it trusts the project for this session.
    pub trusted: bool,
    /// Edits to save when chosen (empty = this session only).
    pub updates: Vec<TrustUpdate>,
    /// Directory whose decision is saved, if any.
    pub saved_path: Option<PathBuf>,
}

/// `trust.json` failure.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TrustStoreError {
    /// Unreadable or invalid JSON.
    #[error("Failed to read trust store {path}: {message}")]
    Read {
        /// Store path.
        path: PathBuf,
        /// Cause.
        message: String,
    },
    /// Top-level value is not an object.
    #[error("Invalid trust store {path}: expected an object")]
    NotAnObject {
        /// Store path.
        path: PathBuf,
    },
    /// A value is not `true`, `false` or `null`.
    #[error("Invalid trust store {path}: value for {key} must be true, false, or null")]
    InvalidValue {
        /// Store path.
        path: PathBuf,
        /// JSON-quoted key.
        key: String,
    },
    /// Lock or write failure.
    #[error("Failed to write trust store {path}: {message}")]
    Write {
        /// Store path.
        path: PathBuf,
        /// Cause.
        message: String,
    },
}

/// `<agent>/trust.json`: canonical directory → decision, locked access,
/// nearest-ancestor lookup.
#[derive(Clone, Debug)]
pub struct TrustStore {
    path: PathBuf,
}

fn normalize_dir(dir: &Path) -> PathBuf {
    let absolute =
        std::path::absolute(dir).map_or_else(|_| dir.to_path_buf(), |p| lexical_normalize(&p));
    canonicalize_or_self(&absolute)
}

impl TrustStore {
    /// The store in `agent_dir`.
    #[must_use]
    pub fn new(agent_dir: &Path) -> Self {
        Self {
            path: agent_dir.join(TRUST_FILE),
        }
    }

    /// Store file path.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Nearest saved decision for `cwd` or an ancestor.
    ///
    /// # Errors
    ///
    /// [`TrustStoreError`] for an unreadable or invalid store.
    pub fn get(&self, cwd: &Path) -> Result<ProjectTrustDecision, TrustStoreError> {
        Ok(self.get_entry(cwd)?.map(|entry| entry.trusted))
    }

    /// Nearest saved entry.
    ///
    /// # Errors
    ///
    /// See [`Self::get`].
    pub fn get_entry(&self, cwd: &Path) -> Result<Option<TrustEntry>, TrustStoreError> {
        let data = self.locked(|| self.read())?;
        let start = normalize_dir(cwd);
        Ok(start
            .ancestors()
            .find_map(|dir| match data.get(dir.to_string_lossy().as_ref()) {
                Some(Value::Bool(trusted)) => Some(TrustEntry {
                    path: dir.to_path_buf(),
                    trusted: *trusted,
                }),
                _ => None,
            }))
    }

    /// Save one decision.
    ///
    /// # Errors
    ///
    /// See [`Self::set_many`].
    pub fn set(&self, cwd: &Path, decision: ProjectTrustDecision) -> Result<(), TrustStoreError> {
        self.set_many(&[TrustUpdate {
            path: cwd.to_path_buf(),
            decision,
        }])
    }

    /// Apply several edits under one lock; keys are written sorted with a trailing newline.
    ///
    /// # Errors
    ///
    /// [`TrustStoreError`] for an invalid existing store or a write failure.
    pub fn set_many(&self, updates: &[TrustUpdate]) -> Result<(), TrustStoreError> {
        self.locked(|| {
            let mut data = self.read()?;
            for update in updates {
                let key = normalize_dir(&update.path).to_string_lossy().into_owned();
                match update.decision {
                    Some(trusted) => {
                        data.insert(key, Value::Bool(trusted));
                    }
                    None => {
                        data.shift_remove(&key);
                    }
                }
            }
            let mut keys: Vec<&String> = data.keys().collect();
            keys.sort();
            let sorted: JsonObject = keys
                .into_iter()
                .map(|key| (key.clone(), data[key].clone()))
                .collect();
            let text = serde_json::to_string_pretty(&Value::Object(sorted)).map_err(|e| {
                TrustStoreError::Write {
                    path: self.path.clone(),
                    message: e.to_string(),
                }
            })?;
            write_atomic(&self.path, format!("{text}\n").as_bytes()).map_err(|e| {
                TrustStoreError::Write {
                    path: self.path.clone(),
                    message: e.to_string(),
                }
            })
        })
    }

    fn locked<T>(
        &self,
        f: impl FnOnce() -> Result<T, TrustStoreError>,
    ) -> Result<T, TrustStoreError> {
        let _lock = FileLock::acquire(&self.path).map_err(|e| TrustStoreError::Write {
            path: self.path.clone(),
            message: e.to_string(),
        })?;
        f()
    }

    fn read(&self) -> Result<JsonObject, TrustStoreError> {
        let content = match std::fs::read_to_string(&self.path) {
            Ok(content) => content,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return Ok(JsonObject::new());
            }
            Err(error) => {
                return Err(TrustStoreError::Read {
                    path: self.path.clone(),
                    message: error.to_string(),
                });
            }
        };
        let parsed: Value = serde_json::from_str(oino_settings::json::strip_bom(&content))
            .map_err(|error| TrustStoreError::Read {
                path: self.path.clone(),
                message: error.to_string(),
            })?;
        let Value::Object(data) = parsed else {
            return Err(TrustStoreError::NotAnObject {
                path: self.path.clone(),
            });
        };
        if let Some((key, _)) = data
            .iter()
            .find(|(_, value)| !matches!(value, Value::Bool(_) | Value::Null))
        {
            return Err(TrustStoreError::InvalidValue {
                path: self.path.clone(),
                key: Value::from(key.as_str()).to_string(),
            });
        }
        Ok(data)
    }
}

/// Protected entries under `<cwd>/.oino`, or an
/// `.agents/skills` dir in `cwd` or any ancestor other than `~/.agents/skills`.
#[must_use]
pub fn has_protected_resources(cwd: &Path, home: Option<&Path>) -> bool {
    let user_agents_skills = home.map(|home| normalize_dir(home).join(".agents").join("skills"));
    let start = normalize_dir(cwd);
    let config = start.join(CONFIG_DIR_NAME);
    if PROTECTED_PROJECT_RESOURCES
        .iter()
        .any(|entry| config.join(entry).exists())
    {
        return true;
    }
    start.ancestors().any(|dir| {
        let skills = dir.join(".agents").join("skills");
        Some(&skills) != user_agents_skills.as_ref() && skills.exists()
    })
}

/// Parent directory offered by "Trust parent folder".
#[must_use]
pub fn trust_parent_path(cwd: &Path) -> Option<PathBuf> {
    normalize_dir(cwd).parent().map(Path::to_path_buf)
}

/// Returns the project trust options.
#[must_use]
pub fn trust_options(cwd: &Path, include_session_only: bool) -> Vec<TrustOption> {
    let trust_path = normalize_dir(cwd);
    let mut options = vec![TrustOption {
        label: "Trust".to_owned(),
        trusted: true,
        updates: vec![TrustUpdate {
            path: trust_path.clone(),
            decision: Some(true),
        }],
        saved_path: Some(trust_path.clone()),
    }];
    if let Some(parent) = trust_parent_path(cwd) {
        options.push(TrustOption {
            label: format!("Trust parent folder ({})", parent.display()),
            trusted: true,
            updates: vec![
                TrustUpdate {
                    path: parent.clone(),
                    decision: Some(true),
                },
                TrustUpdate {
                    path: trust_path.clone(),
                    decision: None,
                },
            ],
            saved_path: Some(parent),
        });
    }
    if include_session_only {
        options.push(TrustOption {
            label: "Trust (this session only)".to_owned(),
            trusted: true,
            updates: Vec::new(),
            saved_path: None,
        });
    }
    options.push(TrustOption {
        label: "Do not trust".to_owned(),
        trusted: false,
        updates: vec![TrustUpdate {
            path: trust_path.clone(),
            decision: Some(false),
        }],
        saved_path: Some(trust_path),
    });
    if include_session_only {
        options.push(TrustOption {
            label: "Do not trust (this session only)".to_owned(),
            trusted: false,
            updates: Vec::new(),
            saved_path: None,
        });
    }
    options
}

/// Formats the project trust prompt (product strings substituted).
#[must_use]
pub fn trust_prompt(cwd: &Path) -> String {
    format!(
        "Trust project folder?\n{}\n\nThis allows Oino to load {CONFIG_DIR_NAME} settings and resources, install missing project packages, and execute project extensions.",
        cwd.display()
    )
}

/// A `project_trust` extension handler's answer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ExtensionTrustDecision {
    /// `trusted: "yes"`.
    pub trusted: bool,
    /// Save the decision to `trust.json`.
    pub remember: bool,
}

/// Inputs of [`resolve_project_trust`], in decision order.
#[derive(Clone, Debug)]
pub struct TrustRequest<'a> {
    /// Project directory.
    pub cwd: &'a Path,
    /// Home dir (to ignore `~/.agents/skills`).
    pub home: Option<&'a Path>,
    /// `-a` (`Some(true)`) / `-na` (`Some(false)`).
    pub cli_override: Option<bool>,
    /// Result of the `project_trust` extension event (emit it only when
    /// [`has_protected_resources`] is true).
    pub extension_decision: Option<ExtensionTrustDecision>,
    /// `defaultProjectTrust` from the global settings.
    pub default_trust: ProjectTrustDefault,
    /// Whether a UI can ask the user (interactive modes).
    pub has_ui: bool,
}

/// Why [`resolve_project_trust`] decided.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrustSource {
    /// CLI `-a` / `-na`.
    Cli,
    /// The project has no protected resources.
    NoProtectedResources,
    /// A `project_trust` extension handler.
    Extension,
    /// A saved decision in `trust.json`.
    Saved,
    /// `defaultProjectTrust` = `always` / `never`.
    Default,
    /// `ask` without a UI.
    NonInteractive,
}

/// Outcome of [`resolve_project_trust`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TrustResolution {
    /// Decided without asking.
    Decided {
        /// Trusted or not.
        trusted: bool,
        /// Deciding rule.
        source: TrustSource,
    },
    /// Ask the user with [`trust_prompt`] and these options; save the chosen option's
    /// `updates` with [`TrustStore::set_many`]; a dismissed prompt means untrusted.
    Ask {
        /// Options including the session-only ones.
        options: Vec<TrustOption>,
    },
}

/// Resolves project trust minus the UI: CLI → no protected resources → extension decision
/// (saved when `remember`) → nearest saved decision → `defaultProjectTrust` → ask (UI) or
/// untrusted.
///
/// # Errors
///
/// [`TrustStoreError`] when `trust.json` cannot be read or a remembered decision cannot be
/// written.
pub fn resolve_project_trust(
    request: &TrustRequest<'_>,
    store: &TrustStore,
) -> Result<TrustResolution, TrustStoreError> {
    let decided = |trusted, source| TrustResolution::Decided { trusted, source };
    if let Some(trusted) = request.cli_override {
        return Ok(decided(trusted, TrustSource::Cli));
    }
    if !has_protected_resources(request.cwd, request.home) {
        return Ok(decided(true, TrustSource::NoProtectedResources));
    }
    if let Some(extension) = request.extension_decision {
        if extension.remember {
            store.set(request.cwd, Some(extension.trusted))?;
        }
        return Ok(decided(extension.trusted, TrustSource::Extension));
    }
    if let Some(trusted) = store.get(request.cwd)? {
        return Ok(decided(trusted, TrustSource::Saved));
    }
    match request.default_trust {
        ProjectTrustDefault::Always => Ok(decided(true, TrustSource::Default)),
        ProjectTrustDefault::Never => Ok(decided(false, TrustSource::Default)),
        ProjectTrustDefault::Ask if !request.has_ui => {
            Ok(decided(false, TrustSource::NonInteractive))
        }
        ProjectTrustDefault::Ask => Ok(TrustResolution::Ask {
            options: trust_options(request.cwd, true),
        }),
    }
}