Skip to main content

kernel/
config.rs

1//! Kernel configuration: the environment the kernel receives, its resource limits and the output budget.
2//! Ports of `kernelEnvironment`, `kernelResourceLimits` (kernel.ts) and `rlmOutputBudget` (output-truncation.ts).
3
4use crate::KernelError;
5use std::collections::HashSet;
6use std::ffi::OsStr;
7
8/// Names (ASCII case-insensitive) that mark a variable as a credential: kernel.ts `CREDENTIAL_NAME`.
9const CREDENTIAL_WORDS: &[&str] = &[
10    "APIKEY",
11    "API_KEY",
12    "ACCESSKEY",
13    "ACCESS_KEY",
14    "TOKEN",
15    "SECRET",
16    "PASSWORD",
17    "PASSWD",
18    "CREDENTIAL",
19    "PRIVATEKEY",
20    "PRIVATE_KEY",
21    "AUTH",
22    "COOKIE",
23    "SESSIONKEY",
24    "SESSION_KEY",
25    "WEBHOOK",
26];
27
28/// Environment for model-written Python: credentials and the session worker's control variables are removed so the
29/// kernel gets no ambient authority. `ULTRON_RLM_ENV_ALLOW` lists names (comma-separated) to pass through anyway.
30pub fn kernel_environment<K: AsRef<OsStr>, V: AsRef<OsStr>>(source: impl IntoIterator<Item = (K, V)>) -> Vec<(K, V)> {
31    let source: Vec<(K, V)> = source.into_iter().collect();
32    let allowed: HashSet<String> = source
33        .iter()
34        .find(|(name, _)| name.as_ref() == crate::env::RLM_ENV_ALLOW_ENV)
35        .map(|(_, value)| {
36            value
37                .as_ref()
38                .to_string_lossy()
39                .split(',')
40                .map(|name| jsrt::string::trim(name).to_string())
41                .filter(|name| !name.is_empty())
42                .collect()
43        })
44        .unwrap_or_default();
45    source
46        .into_iter()
47        .filter(|(name, _)| {
48            let name = name.as_ref().to_string_lossy();
49            let control = name.starts_with("PI_SESSION_WORKER_") || name.starts_with("ULTRON_SESSION_WORKER_");
50            let upper = name.to_ascii_uppercase();
51            let credential = CREDENTIAL_WORDS.iter().any(|word| upper.contains(word));
52            allowed.contains(name.as_ref()) || !(control || credential)
53        })
54        .collect()
55}
56
57/// Per-kernel resource limits; 0 disables one. Resource limits, not isolation.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct KernelResourceLimits {
60    /// RLIMIT_DATA in MiB for the kernel and, inherited, every process a cell spawns.
61    pub max_memory_mb: u64,
62    /// CPU time per cell.
63    pub max_cpu_seconds: u64,
64}
65
66const DEFAULT_KERNEL_LIMITS: KernelResourceLimits = KernelResourceLimits {
67    max_memory_mb: 4096,
68    max_cpu_seconds: 1800,
69};
70
71/// Explicit limits that take precedence over the environment.
72#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
73pub struct LimitOverrides {
74    pub max_memory_mb: Option<u64>,
75    pub max_cpu_seconds: Option<u64>,
76}
77
78/// Limits from `ULTRON_RLM_MAX_MEMORY_MB` and `ULTRON_RLM_MAX_CPU_SECONDS` (read through `lookup`), then overrides.
79/// A malformed value falls back to the default; a value over 2^53 - 1 is an error, as in TypeScript.
80pub fn kernel_resource_limits(
81    lookup: impl Fn(&str) -> Option<String>,
82    overrides: LimitOverrides,
83) -> Result<KernelResourceLimits, KernelError> {
84    let value = |name: &str, fallback: u64| -> Result<u64, ()> {
85        let Some(raw) = lookup(name) else {
86            return Ok(fallback);
87        };
88        let digits = jsrt::string::trim(&raw);
89        if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
90            return Ok(fallback);
91        }
92        match digits.parse::<u64>() {
93            Ok(number) if number <= jsrt::number::MAX_SAFE_INTEGER as u64 => Ok(number),
94            _ => Err(()),
95        }
96    };
97    let field = |name: &str, override_value: Option<u64>, env: &str, fallback: u64| {
98        let parsed = match override_value {
99            Some(number) if number <= jsrt::number::MAX_SAFE_INTEGER as u64 => Ok(number),
100            Some(_) => Err(()),
101            None => value(env, fallback),
102        };
103        parsed.map_err(|()| KernelError::new(format!("RLM {name} must be a non-negative integer")))
104    };
105    Ok(KernelResourceLimits {
106        max_memory_mb: field(
107            "maxMemoryMb",
108            overrides.max_memory_mb,
109            crate::env::RLM_MAX_MEMORY_MB_ENV,
110            DEFAULT_KERNEL_LIMITS.max_memory_mb,
111        )?,
112        max_cpu_seconds: field(
113            "maxCpuSeconds",
114            overrides.max_cpu_seconds,
115            crate::env::RLM_MAX_CPU_SECONDS_ENV,
116            DEFAULT_KERNEL_LIMITS.max_cpu_seconds,
117        )?,
118    })
119}
120
121const DEFAULT_RLM_OUTPUT_BYTES: u64 = 20_000;
122const MAX_RLM_OUTPUT_BYTES: u64 = 128 * 1024;
123
124/// The byte budget for one cell's captured stream: `ULTRON_RLM_OUTPUT_BYTES` (as JavaScript's `Number` reads it),
125/// else 20 KB, within 1 KB..128 KiB.
126pub fn rlm_output_budget(value: Option<&str>) -> u64 {
127    let raw = jsrt::string::trim(value.unwrap_or(""));
128    match Some(jsrt::number::parse(raw)).filter(|n| !n.is_nan()) {
129        Some(number) if number.fract() == 0.0 && number.is_finite() && number > 0.0 => {
130            number.clamp(1024.0, MAX_RLM_OUTPUT_BYTES as f64) as u64
131        }
132        _ => DEFAULT_RLM_OUTPUT_BYTES,
133    }
134}