Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

require local runtime sources during kernel bootstrap (#3661)

ktf22568b61222
diff --git a/crates/pa-core/src/kernel/bootstrap/mod.rs b/crates/pa-core/src/kernel/bootstrap/mod.rs
index 184087633e..25ba0f52ad 100644
--- a/crates/pa-core/src/kernel/bootstrap/mod.rs
+++ b/crates/pa-core/src/kernel/bootstrap/mod.rs
@@ -24,9 +24,7 @@ use venv::{
missing_python_skill_import_labels, missing_rlm_extra_import_labels, normalize_python_skills,
resolve_writable_kernel_venv_dir, sync_python_skills, BootstrapPythonSkill,
};
-pub use venv::{
- invalidate_runtime_probe_cache, kernel_venv_dir, kernel_venv_python, resolve_runtime_identity,
-};
+pub use venv::{invalidate_runtime_probe_cache, kernel_venv_dir, kernel_venv_python};
use venv::{kernel_base_ready, kernel_ready};
/// One Python skill the kernel should import at bootstrap.
@@ -101,7 +99,7 @@ impl EnsureKernelPythonOptions {
fn format_bootstrap_failure(error: &anyhow::Error) -> anyhow::Error {
let mut message = format!(
"Failed to set up the Python kernel runtime. {error:#}\n\
- First-time setup needs internet to install uv, Python, prime-agent-runtime, and default Python packages; once set up, prime-agent runs offline. \
+ First-time setup needs the bundled local runtime and internet to install uv, Python, and default Python packages; once set up, Prime Agent runs offline. \
An interrupted runtime upgrade needs network once more, so re-run this while online. \
Set PRIME_AGENT_KERNEL_PYTHON to a Python with a current prime-agent-runtime and default Python packages installed to skip auto-bootstrap."
);
@@ -230,7 +228,12 @@ async fn ensure_kernel_venv(
) -> anyhow::Result<PathBuf> {
let python = kernel_venv_python(&venv);
let python_str = python.to_string_lossy().to_string();
- let runtime_identity = resolve_runtime_identity();
+ // Validate the local source before probing any installed runtime or
+ // removing an existing venv. Missing payloads must fail closed.
+ let source_dir =
+ venv::require_runtime_source_dir().map_err(|error| format_bootstrap_failure(&error))?;
+ let runtime_identity =
+ venv::hash_runtime_source(&source_dir).map_err(|error| format_bootstrap_failure(&error))?;
if kernel_ready(&python_str, &venv, &runtime_identity, python_skills) {
return Ok(python);
}
@@ -246,6 +249,7 @@ async fn ensure_kernel_venv(
&uv,
&venv,
&python,
+ &source_dir,
&runtime_identity,
python_skills,
options,
@@ -260,7 +264,14 @@ async fn ensure_kernel_venv(
std::fs::remove_dir_all(&venv)
.with_context(|| format!("removing {}", venv.display()))?;
}
- bootstrap_venv(&venv, python_skills, options).await?;
+ bootstrap_venv(
+ &venv,
+ &source_dir,
+ &runtime_identity,
+ python_skills,
+ options,
+ )
+ .await?;
Ok(python)
}
.await;
diff --git a/crates/pa-core/src/kernel/bootstrap/venv.rs b/crates/pa-core/src/kernel/bootstrap/venv.rs
index d08bf97131..c5ff3a190d 100644
--- a/crates/pa-core/src/kernel/bootstrap/venv.rs
+++ b/crates/pa-core/src/kernel/bootstrap/venv.rs
@@ -38,8 +38,8 @@ pub(crate) use probe::{
has_prime_agent_runtime, missing_python_skill_import_labels, missing_rlm_extra_import_labels,
};
use probe::{has_prime_agent_runtime_memoized, installed_runtime_identity};
-pub use runtime_source::resolve_runtime_identity;
-use runtime_source::{collect_python_files, resolve_runtime_source_dir};
+use runtime_source::collect_python_files;
+pub(super) use runtime_source::{hash_runtime_source, require_runtime_source_dir};
pub(super) use runtime_source::{package_dir, packaged_runtime_dir};
#[cfg(test)]
use skills::{
@@ -58,7 +58,6 @@ use version::{
use version::{recorded_skills_cover, BOOTSTRAP_SCHEMA};
const PYTHON_VERSION: &str = "3.11";
-const RUNTIME_REQUIREMENT: &str = "prime-agent-runtime";
pub(crate) const BOOTSTRAP_LOCK_NAME: &str = ".bootstrap.lock";
pub(crate) const BOOTSTRAP_LOCK_RETRY_MS: u64 = 100;
pub(crate) const BOOTSTRAP_LOCK_STALE_WITHOUT_PID_MS: u64 = 30_000;
@@ -109,18 +108,14 @@ async fn run_async(command: &str, args: &[String]) -> anyhow::Result<()> {
pub(crate) async fn bootstrap_venv(
venv: &Path,
+ source_dir: &Path,
+ runtime_identity: &str,
python_skills: &[BootstrapPythonSkill],
options: &EnsureKernelPythonOptions,
) -> anyhow::Result<()> {
std::fs::create_dir_all(venv.parent().unwrap_or(Path::new("/")))?;
let uv = ensure_uv()?;
let python = kernel_venv_python(venv);
- let source_dir = resolve_runtime_source_dir();
- let runtime_requirement = source_dir.as_ref().map_or_else(
- || RUNTIME_REQUIREMENT.to_string(),
- |p| p.to_string_lossy().to_string(),
- );
- let runtime_identity = resolve_runtime_identity();
let venv_str = venv.to_string_lossy().to_string();
let python_str = python.to_string_lossy().to_string();
@@ -129,7 +124,7 @@ pub(crate) async fn bootstrap_venv(
"install".to_string(),
"--python".to_string(),
python_str,
- runtime_requirement,
+ source_dir.to_string_lossy().to_string(),
];
install_args.push(STATE_SNAPSHOT_REQUIREMENT.to_string());
for uv_arg in default_rlm_extra_uv_args() {
@@ -161,7 +156,8 @@ pub(crate) async fn bootstrap_venv(
&uv,
venv,
&python,
- &runtime_identity,
+ source_dir,
+ runtime_identity,
python_skills,
options,
)
@@ -174,6 +170,7 @@ pub(crate) async fn sync_python_skills(
uv: &str,
venv: &Path,
python: &Path,
+ source_dir: &Path,
runtime_identity: &str,
python_skills: &[BootstrapPythonSkill],
options: &EnsureKernelPythonOptions,
@@ -211,6 +208,9 @@ pub(crate) async fn sync_python_skills(
"install".to_string(),
"--python".to_string(),
python_str.clone(),
+ // Skills may depend on the runtime too. Keep their resolver
+ // pinned to the same local source, including per-skill retries.
+ source_dir.to_string_lossy().to_string(),
];
for skill in &missing {
install_args.push("--editable".to_string());
@@ -230,6 +230,7 @@ pub(crate) async fn sync_python_skills(
"install".to_string(),
"--python".to_string(),
python_str.clone(),
+ source_dir.to_string_lossy().to_string(),
"--editable".to_string(),
skill.package_path.clone(),
],
diff --git a/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs b/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs
index 7e92a924f2..7271a9d88d 100644
--- a/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs
+++ b/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs
@@ -2,7 +2,8 @@
//! sidecar layout, the source-checkout fallback, and the content identity
//! that invalidates an existing venv on any runtime change.
-use super::{expand_home, Digest, Path, PathBuf, RUNTIME_REQUIREMENT};
+use super::{expand_home, Digest, Path, PathBuf};
+use anyhow::Context;
/// Directory of the installed `prime-agent-runtime` sources. The Rust binary ships the same sidecar
/// layout the compiled TS executable uses.
@@ -21,55 +22,47 @@ pub(in crate::kernel::bootstrap) fn package_dir() -> PathBuf {
/// The packaged sidecar directory (the exe-adjacent layout): the TS `runtimeCandidateDirs`
/// bun-binary candidates.
pub(in crate::kernel::bootstrap) fn packaged_runtime_dir() -> Option<PathBuf> {
- let package = package_dir();
- [
- package.join("prime-agent-runtime"),
- package.join("dist").join("prime-agent-runtime"),
- ]
- .into_iter()
- .find(|candidate| candidate.join("pyproject.toml").exists())
+ resolve_runtime_source_dir(&package_dir(), None)
}
-fn runtime_candidate_dirs() -> Vec<PathBuf> {
- let mut candidates = packaged_runtime_dir().into_iter().collect::<Vec<_>>();
+fn resolve_runtime_source_dir(package: &Path, checkout: Option<&Path>) -> Option<PathBuf> {
+ let mut candidates = vec![
+ package.join("prime-agent-runtime"),
+ package.join("dist").join("prime-agent-runtime"),
+ ];
// Source checkouts keep the sidecar at the workspace root (TS resolves
// module-relative monorepo candidates the same way).
- if let Some(root) = crate::packages::source_checkout_root() {
+ if let Some(root) = checkout {
candidates.push(root.join("prime-agent-runtime"));
}
- candidates
-}
-
-pub(super) fn resolve_runtime_source_dir() -> Option<PathBuf> {
- runtime_candidate_dirs()
- .into_iter()
- .find(|candidate| candidate.join("pyproject.toml").exists())
+ candidates.into_iter().find_map(|candidate| {
+ // Always pass an absolute filesystem path to uv, including when
+ // PI_PACKAGE_DIR was relative. A manifest alone is not a runtime.
+ let candidate = candidate.canonicalize().ok()?;
+ if !["pyproject.toml", "src/rlm/__init__.py", "src/rlm/repl.py"]
+ .iter()
+ .all(|file| candidate.join(file).is_file())
+ {
+ return None;
+ }
+ let manifest = std::fs::read_to_string(candidate.join("pyproject.toml")).ok()?;
+ let manifest: toml::Value = toml::from_str(&manifest).ok()?;
+ (manifest.get("project")?.get("name")?.as_str()? == "prime-agent-runtime")
+ .then_some(candidate)
+ })
}
-/// Content identity of the runtime: a hash of every `rlm/*.py` file, the
-/// packaged machine library under `src/rlm/machines` (wheel package data:
-/// machine changes are runtime changes), and `pyproject.toml`, so any
-/// runtime change invalidates an existing venv. Falls back to the bare
-/// package name when the runtime resolves to a registry install (no local
-/// source).
-///
-/// # Panics
-///
-/// Panics when hashing the resolved local runtime source fails.
-#[must_use]
-pub fn resolve_runtime_identity() -> String {
- let Some(source_dir) = resolve_runtime_source_dir() else {
- return RUNTIME_REQUIREMENT.to_string();
- };
- hash_runtime_source(&source_dir).unwrap_or_else(|error| {
- panic!(
- "cannot hash runtime source at {}: {error}",
- source_dir.display()
- )
- })
+pub(in crate::kernel::bootstrap) fn require_runtime_source_dir() -> anyhow::Result<PathBuf> {
+ resolve_runtime_source_dir(&package_dir(), crate::packages::source_checkout_root()).context(
+ "Prime Agent requires a local prime-agent-runtime directory containing its pyproject.toml and src/rlm sources; reinstall Prime Agent with the runtime beside the binary, or set PI_PACKAGE_DIR to the complete trusted package directory. The runtime will not be downloaded from a package index.",
+ )
}
-fn hash_runtime_source(source_dir: &Path) -> anyhow::Result<String> {
+/// Hash the manifest, Python sources, and packaged machine library so any
+/// runtime change invalidates an existing venv.
+pub(in crate::kernel::bootstrap) fn hash_runtime_source(
+ source_dir: &Path,
+) -> anyhow::Result<String> {
let rlm_dir = source_dir.join("src").join("rlm");
let mut files = vec![source_dir.join("pyproject.toml")];
collect_python_files(&rlm_dir, &mut files)?;
@@ -130,17 +123,81 @@ mod tests {
"X = 1
",
)?;
+ std::fs::write(rlm.join("__init__.py"), "")?;
+ std::fs::write(rlm.join("repl.py"), "")?;
let machines = rlm.join("machines").join("review-sweep");
std::fs::create_dir_all(&machines)?;
std::fs::write(machines.join("MACHINE.md"), machine_body)?;
std::fs::write(
temp.join("pyproject.toml"),
- "[project]
-",
+ "[project]\nname = 'prime-agent-runtime'\n",
)?;
Ok(())
}
+ #[test]
+ fn missing_or_incomplete_runtime_sources_are_not_resolved() -> anyhow::Result<()> {
+ let temp = tempfile::tempdir()?;
+ let package = temp.path();
+ assert_eq!(resolve_runtime_source_dir(package, None), None);
+ let runtime = package.join("prime-agent-runtime");
+ runtime_fixture(&runtime, "machine")?;
+ for file in ["pyproject.toml", "src/rlm/__init__.py", "src/rlm/repl.py"] {
+ let path = runtime.join(file);
+ let contents = std::fs::read(&path)?;
+ std::fs::remove_file(&path)?;
+ assert_eq!(resolve_runtime_source_dir(package, None), None);
+ // A directory with the expected file name is also invalid.
+ std::fs::create_dir(&path)?;
+ assert_eq!(resolve_runtime_source_dir(package, None), None);
+ std::fs::remove_dir(&path)?;
+ std::fs::write(&path, contents)?;
+ }
+ for manifest in ["not toml", "[project]", "[project]\nname = 'other'"] {
+ std::fs::write(runtime.join("pyproject.toml"), manifest)?;
+ assert_eq!(resolve_runtime_source_dir(package, None), None);
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn packaged_dist_and_checkout_sources_resolve_to_absolute_paths() -> anyhow::Result<()> {
+ let temp = tempfile::tempdir()?;
+ let package = temp.path().join("package");
+ let checkout = temp.path().join("checkout");
+ let direct = package.join("prime-agent-runtime");
+ let dist = package.join("dist/prime-agent-runtime");
+ let source = checkout.join("prime-agent-runtime");
+ for runtime in [&source, &dist, &direct] {
+ runtime_fixture(runtime, "machine")?;
+ assert_eq!(
+ resolve_runtime_source_dir(&package, Some(&checkout)),
+ Some(runtime.canonicalize()?)
+ );
+ }
+ // An incomplete first candidate must not hide a valid dist payload.
+ std::fs::remove_file(direct.join("src/rlm/repl.py"))?;
+ assert_eq!(
+ resolve_runtime_source_dir(&package, Some(&checkout)),
+ Some(dist.canonicalize()?)
+ );
+ Ok(())
+ }
+
+ #[test]
+ fn relative_package_paths_are_never_returned_as_requirements() -> anyhow::Result<()> {
+ let cwd = std::env::current_dir()?;
+ let temp = tempfile::tempdir_in(&cwd)?;
+ let runtime = temp.path().join("prime-agent-runtime");
+ runtime_fixture(&runtime, "machine")?;
+ let relative = temp.path().strip_prefix(&cwd)?;
+ assert_eq!(
+ resolve_runtime_source_dir(relative, None),
+ Some(runtime.canonicalize()?)
+ );
+ Ok(())
+ }
+
#[test]
fn machine_library_changes_invalidate_the_runtime_identity() -> anyhow::Result<()> {
let temp = tempfile::tempdir()?;
diff --git a/crates/pa-core/src/kernel/bootstrap/venv/tests.rs b/crates/pa-core/src/kernel/bootstrap/venv/tests.rs
index e94f024487..86d794c99c 100644
--- a/crates/pa-core/src/kernel/bootstrap/venv/tests.rs
+++ b/crates/pa-core/src/kernel/bootstrap/venv/tests.rs
@@ -679,7 +679,7 @@ fn live_probe_memo_reprobes_when_installed_rlm_is_removed() {
std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap();
}
- let identity = resolve_runtime_identity();
+ let identity = hash_runtime_source(&require_runtime_source_dir().unwrap()).unwrap();
write_bootstrap_version(&fake, &identity, &[]).unwrap();
let probe_count = || {
@@ -981,6 +981,7 @@ async fn skill_sync_batches_missing_installs_into_one_uv_call() {
uv.to_str().unwrap(),
&venv,
dir.path().join("python").as_path(),
+ dir.path().join("prime-agent-runtime").as_path(),
"sha256:rt",
&skills,
&EnsureKernelPythonOptions::default(),
@@ -998,6 +999,7 @@ async fn skill_sync_batches_missing_installs_into_one_uv_call() {
"the installed skill is not reinstalled: {calls:?}"
);
assert_eq!(calls[0].matches("--editable").count(), 1);
+ assert!(calls[0].contains(dir.path().join("prime-agent-runtime").to_str().unwrap()));
let version = read_bootstrap_version(&venv).expect("version written");
assert_eq!(
version.python_skills.as_ref().map(Vec::len),
@@ -1034,6 +1036,7 @@ async fn skill_sync_falls_back_to_per_skill_installs_on_batch_failure() {
uv.to_str().unwrap(),
&venv,
dir.path().join("python").as_path(),
+ dir.path().join("prime-agent-runtime").as_path(),
"sha256:rt",
&skills,
&options,
@@ -1050,6 +1053,9 @@ async fn skill_sync_falls_back_to_per_skill_installs_on_batch_failure() {
calls[0].contains("edit") && calls[0].contains("broken"),
"the batch covers both skills: {calls:?}"
);
+ for call in &calls {
+ assert!(call.contains(dir.path().join("prime-agent-runtime").to_str().unwrap()));
+ }
let warnings = warnings.lock().unwrap();
assert!(
warnings.len() == 1 && warnings[0].contains("broken"),