Skip to content

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

Rust

bash: bound `await bash()` with a degrade window (yield_after) (#3523)

Sebastian Müller29f2b3ca45a0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bd0ff662c0..6c98843f3c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -447,6 +447,29 @@ jobs:
python3 scripts/test_ci_test_shard_summary.py
python3 scripts/ci_test_shard_summary.py --total ${{ env.SHARD_COUNT }} --dir manifests
+ # The vendored runtime suite (prime-agent-runtime): the kernel-side Python
+ # (`bash()`, the repl protocol, the bounded-await contract) has no Rust test,
+ # so this is its only CI gate — CPython 3.11, the minimum the runtime
+ # supports and the version the kernel venv pins.
+ runtime:
+ name: runtime suite (python 3.11)
+ needs: trust
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ if: needs.trust.result == 'success' && needs.trust.outputs.allowed == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+ - name: Install uv
+ run: |
+ python3 -m pip install --user uv
+ echo "$HOME/.local/bin" >> "$GITHUB_PATH"
+ - name: Run the runtime suite (CPython 3.11)
+ run: |
+ cd prime-agent-runtime
+ uv run --python 3.11 python -m unittest discover -s test
+
# The Windows job set + the supply-chain deny gate:
#
# windows-cross — the cfg-hygiene cross-target gate, the CI mirror of
@@ -517,7 +540,18 @@ jobs:
# enforces.
trust-audit:
name: trust gate audit
- needs: [trust, changes, fmt, clippy-test, test-shard, test-summary, windows-cross, deny]
+ needs:
+ [
+ trust,
+ changes,
+ fmt,
+ clippy-test,
+ test-shard,
+ test-summary,
+ runtime,
+ windows-cross,
+ deny,
+ ]
if: always()
runs-on: ubuntu-24.04
timeout-minutes: 10
diff --git a/crates/pa-core/examples/kernel_bench.rs b/crates/pa-core/examples/kernel_bench.rs
index 9457fcea5c..9824ef2c16 100644
--- a/crates/pa-core/examples/kernel_bench.rs
+++ b/crates/pa-core/examples/kernel_bench.rs
@@ -84,6 +84,7 @@ fn manager_options(
}),
bootstrap_code: Some(pa_core::kernel::bootstrap::build_rlm_bootstrap_code(
&bench_python_skills(),
+ false,
)),
stderr_log_path: None,
}
diff --git a/crates/pa-core/src/kernel/bootstrap/mod.rs b/crates/pa-core/src/kernel/bootstrap/mod.rs
index 7fe34e4236..29a714b59b 100644
--- a/crates/pa-core/src/kernel/bootstrap/mod.rs
+++ b/crates/pa-core/src/kernel/bootstrap/mod.rs
@@ -184,7 +184,7 @@ async fn ensure_kernel_python_uncached(
let mut missing = Vec::new();
if !has_prime_agent_runtime(&python_str) {
missing.push(
- "a current prime-agent-runtime with callable rlm.spawn, rlm.create_session, rlm.host_request, rlm.progress_note, rlm.rename, and explicit harness CRUD methods".to_string(),
+ "a current prime-agent-runtime with callable rlm.spawn, rlm.create_session, rlm.host_request, rlm.progress_note, rlm.rename, rlm._set_completion_notices_wired, and explicit harness CRUD methods".to_string(),
);
}
if missing.is_empty() {
diff --git a/crates/pa-core/src/kernel/bootstrap/runtime_code.rs b/crates/pa-core/src/kernel/bootstrap/runtime_code.rs
index 03190f4d3c..b478cdd891 100644
--- a/crates/pa-core/src/kernel/bootstrap/runtime_code.rs
+++ b/crates/pa-core/src/kernel/bootstrap/runtime_code.rs
@@ -33,12 +33,23 @@ pub fn parse_unavailable_python_skills(stdout: &str) -> Option<UnavailablePython
const RLM_BOOTSTRAP_HEADER_CODE: &str =
"import asyncio\nimport os as _prime_agent_os\n\n_prime_agent_os.environ[\"NO_COLOR\"] = \"1\"";
-const RLM_BOOTSTRAP_RUNTIME_CODE: &str = r#"
+const RLM_BOOTSTRAP_RUNTIME_HEAD_CODE: &str = "
try:
import rlm as _prime_agent_rlm_module
rlm = _prime_agent_rlm_module.rlm
bash = _prime_agent_rlm_module.bash
import rlm.mcp as mcp
+";
+
+/// One line inside the bootstrap's try block, emitted only when the host
+/// registered the [`crate::kernel::shared::BASH_COMPLETED_REQUEST_TYPE`]
+/// handler: turns the runtime's bounded `await bash()` default on. Without
+/// the notice nothing wakes a cell that ended its turn on a degraded command,
+/// so daemonless sessions keep the unbounded await.
+const RLM_BOOTSTRAP_BASH_NOTICES_LINE_CODE: &str =
+ " _prime_agent_rlm_module._set_completion_notices_wired(True)\n";
+
+const RLM_BOOTSTRAP_RUNTIME_TAIL_CODE: &str = r#"
except Exception as _prime_agent_rlm_error:
_PRIME_AGENT_RLM_IMPORT_ERROR = str(_prime_agent_rlm_error)
@@ -68,15 +79,24 @@ except Exception as _prime_agent_rlm_error:
rlm = _PrimeAgentMissingRlm()
- def bash(command):
+ def bash(command, yield_after=None):
rlm._raise_missing()
"#;
/// The code the session injects right after kernel start/restore: binds the `rlm`, `bash`, and MCP
-/// surfaces, imports every Python skill.
+/// surfaces, imports every Python skill. `bash_notices_wired` emits the bounded-await toggle only
+/// when the host registers the bash completion notice.
#[must_use]
-pub fn build_rlm_bootstrap_code(python_skills: &[KernelPythonSkill]) -> String {
- let base_code = format!("{RLM_BOOTSTRAP_HEADER_CODE}\n\n{RLM_BOOTSTRAP_RUNTIME_CODE}");
+pub fn build_rlm_bootstrap_code(
+ python_skills: &[KernelPythonSkill],
+ bash_notices_wired: bool,
+) -> String {
+ let mut runtime_code = String::from(RLM_BOOTSTRAP_RUNTIME_HEAD_CODE);
+ if bash_notices_wired {
+ runtime_code.push_str(RLM_BOOTSTRAP_BASH_NOTICES_LINE_CODE);
+ }
+ runtime_code.push_str(RLM_BOOTSTRAP_RUNTIME_TAIL_CODE);
+ let base_code = format!("{RLM_BOOTSTRAP_HEADER_CODE}\n\n{runtime_code}");
// TS: `[...new Set(pythonSkills.map(...))]` — first-seen order, so the pre-import loop follows
// the session's skill discovery order.
let mut import_names: Vec<&str> = Vec::new();
@@ -180,11 +200,25 @@ mod tests {
#[test]
fn bootstrap_code_without_skills_binds_rlm() {
- let code = build_rlm_bootstrap_code(&[]);
+ let code = build_rlm_bootstrap_code(&[], false);
assert!(code.contains("import rlm as _prime_agent_rlm_module"));
assert!(!code.contains("_PrimeAgentUnavailableSkill"));
}
+ #[test]
+ fn bootstrap_turns_the_bounded_bash_default_on_only_with_notices() {
+ let daemonless = build_rlm_bootstrap_code(&[], false);
+ let noticed = build_rlm_bootstrap_code(&[], true);
+ assert!(
+ noticed.contains("_set_completion_notices_wired(True)"),
+ "the wired bootstrap must enable the bounded bash default: {noticed}"
+ );
+ assert!(
+ !daemonless.contains("_set_completion_notices_wired"),
+ "the daemonless bootstrap must not emit the toggle: {daemonless}"
+ );
+ }
+
#[test]
fn bootstrap_code_imports_skills() {
let skills = vec![KernelPythonSkill {
@@ -193,7 +227,7 @@ mod tests {
package_path: PathBuf::from("/pkg/edit"),
pyproject_path: PathBuf::from("/pkg/edit/pyproject.toml"),
}];
- let code = build_rlm_bootstrap_code(&skills);
+ let code = build_rlm_bootstrap_code(&skills, false);
assert!(code.contains(r#"for _prime_agent_skill_name in ["edit"]"#));
assert!(code.contains("_PrimeAgentUnavailableSkill"));
}
diff --git a/crates/pa-core/src/kernel/bootstrap/venv/probe.rs b/crates/pa-core/src/kernel/bootstrap/venv/probe.rs
index 2ed2c23687..8f4c1802de 100644
--- a/crates/pa-core/src/kernel/bootstrap/venv/probe.rs
+++ b/crates/pa-core/src/kernel/bootstrap/venv/probe.rs
@@ -28,7 +28,7 @@ fn run_quiet(command: &str, args: &[&str]) -> bool {
/// The runtime-ready assertion from the TS product: a current
/// prime-agent-runtime with the callable RLM surface, harness CRUD, bash
/// handles, and protocol version 3.
-const RUNTIME_READY_CHECK: &str = "import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ['create_memory', 'update_memory', 'delete_memory', 'create_skill', 'update_skill', 'delete_skill', 'create_subagent', 'update_subagent', 'delete_subagent', 'create_prompt_note', 'update_prompt_note', 'delete_prompt_note', 'record_refinement']; _mcp_discovery_methods = ['list_plugins', 'search_plugins', 'list_connections', 'search_tools', 'describe_tool']; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert all(callable(getattr(mcp, _m, None)) for _m in _mcp_discovery_methods), \"rlm.mcp is missing MCP discovery methods (list_plugins, search_plugins, list_connections, search_tools, describe_tool); the kernel venv needs a current prime-agent-runtime\"; assert callable(rlm.spawn); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm.spawn); assert inspect.signature(rlm.spawn).parameters['name'].default is inspect.Parameter.empty; assert not hasattr(rlm, 'run'); assert not hasattr(rlm.rlm, 'run'); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert callable(rlm.create_session); assert callable(rlm.rlm.create_session); assert callable(rlm.progress_note); assert callable(rlm.rlm.progress_note); assert callable(rlm.rename); assert callable(rlm.rlm.rename); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 3; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')";
+const RUNTIME_READY_CHECK: &str = "import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ['create_memory', 'update_memory', 'delete_memory', 'create_skill', 'update_skill', 'delete_skill', 'create_subagent', 'update_subagent', 'delete_subagent', 'create_prompt_note', 'update_prompt_note', 'delete_prompt_note', 'record_refinement']; _mcp_discovery_methods = ['list_plugins', 'search_plugins', 'list_connections', 'search_tools', 'describe_tool']; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert all(callable(getattr(mcp, _m, None)) for _m in _mcp_discovery_methods), \"rlm.mcp is missing MCP discovery methods (list_plugins, search_plugins, list_connections, search_tools, describe_tool); the kernel venv needs a current prime-agent-runtime\"; assert callable(rlm.spawn); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm.spawn); assert inspect.signature(rlm.spawn).parameters['name'].default is inspect.Parameter.empty; assert not hasattr(rlm, 'run'); assert not hasattr(rlm.rlm, 'run'); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert callable(rlm.create_session); assert callable(rlm.rlm.create_session); assert callable(rlm.progress_note); assert callable(rlm.rlm.progress_note); assert callable(rlm.rename); assert callable(rlm.rlm.rename); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert callable(rlm._set_completion_notices_wired); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 3; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')";
pub(crate) fn has_prime_agent_runtime(python: &str) -> bool {
run_quiet(python, &["-c", RUNTIME_READY_CHECK])
diff --git a/crates/pa-core/src/kernel/provisioner.rs b/crates/pa-core/src/kernel/provisioner.rs
index 0d7573e2bb..1fe444f3bc 100644
--- a/crates/pa-core/src/kernel/provisioner.rs
+++ b/crates/pa-core/src/kernel/provisioner.rs
@@ -18,7 +18,7 @@ use crate::kernel::manager::{KernelStartOptions, ReplKernelManager};
use crate::kernel::shared::ExecuteStatus;
use crate::kernel::shared::{
ExecuteOptions, HostRequestHandlers, KernelManagerOptions, KernelShutdownOptions,
- KernelSnapshotConfig, BOOTSTRAP_EXECUTION_TIMEOUT_MS,
+ KernelSnapshotConfig, BASH_COMPLETED_REQUEST_TYPE, BOOTSTRAP_EXECUTION_TIMEOUT_MS,
};
use crate::kernel::state_snapshot::RestoreResult;
use crate::kernel::state_snapshot::{manifest_path_in, snapshot_path_in};
@@ -1035,7 +1035,15 @@ async fn start_kernel_impl(
gate().await;
}
let snapshot_dir = options.snapshot_dir.clone();
- let bootstrap_code = build_rlm_bootstrap_code(&options.python_skills);
+ // The bounded-await default keys on the bash.completed host handler:
+ // one source of truth (the registry the daemon registers the notice in).
+ let bootstrap_code = build_rlm_bootstrap_code(
+ &options.python_skills,
+ options
+ .host_handlers
+ .get(BASH_COMPLETED_REQUEST_TYPE)
+ .is_some(),
+ );
let mut env = options.env.clone();
if let Some(shell_path) = &options.shell_path {
env.insert(
diff --git a/crates/pa-core/src/kernel/shared.rs b/crates/pa-core/src/kernel/shared.rs
index 302d007d3c..7cc425f94b 100644
--- a/crates/pa-core/src/kernel/shared.rs
+++ b/crates/pa-core/src/kernel/shared.rs
@@ -67,6 +67,11 @@ pub const AGENT_MESSAGE_DISPLAY_MIME: &str = "application/vnd.prime-agent.agent-
pub const BASH_ACTIVITY_DISPLAY_MIME: &str = "application/vnd.prime-agent.bash-activity+json";
/// One `bash()` call's command text (capped) and non-blank line count.
pub const BASH_COMMAND_DISPLAY_MIME: &str = "application/vnd.prime-agent.bash-command+json";
+/// The kernel host request that reports a background bash completion
+/// (the `[bash-done]` lane). The daemon registers the handler
+/// (`bash_notices`), and the provisioner keys the bounded-await bootstrap
+/// default on its presence.
+pub const BASH_COMPLETED_REQUEST_TYPE: &str = "bash.completed";
pub const EXECUTE_STATUS_OK: &str = "ok";
pub const EXECUTE_STATUS_ERROR: &str = "error";
diff --git a/crates/pa-core/src/prompts/layers/core.md b/crates/pa-core/src/prompts/layers/core.md
index 2b49c63a5c..6cee7a45eb 100644
--- a/crates/pa-core/src/prompts/layers/core.md
+++ b/crates/pa-core/src/prompts/layers/core.md
@@ -15,7 +15,7 @@ The harness often sends messages to the agent. These are user messages starting
- `.output() -> str`
- `.poll() -> BashResult | None`
- `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive
- - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing
+ - `await handle`: waits according to this session's bash completion contract; the handle remains awaitable after command completion
- `BashResult`
- `.exit_code: int`
- `.output: str`
diff --git a/crates/pa-core/src/prompts/layers/usage.md b/crates/pa-core/src/prompts/layers/usage.md
index 8273651870..9a101b7c1d 100644
--- a/crates/pa-core/src/prompts/layers/usage.md
+++ b/crates/pa-core/src/prompts/layers/usage.md
@@ -5,7 +5,7 @@ The following are mandatory rules, only to be overridden by clear user intent.
- Goals must only be created at a user's request.
- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.
- `bash("""...""")` should be used over `bash("...")` because it makes using quotation marks inside bash easy.
-- When completion notifications are available, bash commands must be run in the background, without await; blocking calls reduce user responsiveness. Collect results in a later `python_repl` call — the harness notifies when a command finishes. Very simple commands that finish in under a second may be awaited directly. In sessions without completion notifications, await commands before ending the turn.
+- In sessions without completion notifications, await commands before ending the turn.
- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables — both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).
- Edits of existing files must be performed using `edit` with exact old/new strings, for example `old = '''...'''; new = '''...'''; await edit(path="pkg/file.py", old_str=old, new_str=new)`; if the text contains triple double quotes ("""), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.
- Agents use Python for reading files and searching in them — it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.
@@ -13,7 +13,7 @@ The following are mandatory rules, only to be overridden by clear user intent.
- Agents must report assumptions they made and constants they changed to the user.
- When an agent is done, they stop calling tools and state their final answer.
- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.
-- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`. When completion notifications are available, they do not replace polling with a long blocking `await`: they await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.
+- Agents do not keep the turn open by polling with `time.sleep()`, shell `sleep`, or repeated awaits of a still-running handle; they end the turn and collect the result on the done notification.
- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.
- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.
- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.
diff --git a/crates/pa-core/src/prompts/system_prompt.rs b/crates/pa-core/src/prompts/system_prompt.rs
index b21c4fdde6..ba664f5705 100644
--- a/crates/pa-core/src/prompts/system_prompt.rs
+++ b/crates/pa-core/src/prompts/system_prompt.rs
@@ -310,6 +310,14 @@ fn session_role_section(options: &BuildSystemPromptOptions, has_ipython: bool) -
"This session has no Python REPL (`python_repl` tool): the programmatic tools described above are unavailable here."
.to_string(),
);
+ } else if !options.daemonless {
+ // The bounded-await runtime half runs only where the host registers
+ // the bash completion notice (the same sessions the daemonless flag
+ // excludes), so the contract renders only there.
+ lines.push(
+ "`await bash(cmd)` waits at most `yield_after` seconds (`bash(cmd, yield_after=...)`, default 10, max 300; `None` uses the default, not an unbounded wait). If the command is still running, it returns a snapshot: `r.running` is True, `r.exit_code` is None, `r.output` is the output so far, and `r.handle` is the live handle. A completed result has `r.running` False and an integer `r.exit_code`. The command keeps running after a snapshot; end the turn and collect the final result on the `[bash-done]` notification."
+ .to_string(),
+ );
}
if options.allow_recursion == Some(false) {
lines.push("Subagent spawning is disabled in this session.".to_string());
diff --git a/crates/pa-core/tests/kernel_capture_freshness.rs b/crates/pa-core/tests/kernel_capture_freshness.rs
index 9b8f7ce019..0ee7cf66fe 100644
--- a/crates/pa-core/tests/kernel_capture_freshness.rs
+++ b/crates/pa-core/tests/kernel_capture_freshness.rs
@@ -56,7 +56,7 @@ fn test_options(snapshot_dir: Option<&Path>) -> Option<KernelManagerOptions> {
max_variable_bytes: None,
debounce_ms: None,
}),
- bootstrap_code: Some(build_rlm_bootstrap_code(&[])),
+ bootstrap_code: Some(build_rlm_bootstrap_code(&[], false)),
stderr_log_path: None,
on_background_work_settled: None,
})
diff --git a/crates/pa-core/tests/kernel_lifecycle.rs b/crates/pa-core/tests/kernel_lifecycle.rs
index aef59df5ee..32fced5ac3 100644
--- a/crates/pa-core/tests/kernel_lifecycle.rs
+++ b/crates/pa-core/tests/kernel_lifecycle.rs
@@ -73,7 +73,7 @@ fn test_options(snapshot_dir: Option<&std::path::Path>) -> Option<KernelManagerO
debounce_ms: None,
}),
// The TS provisioner always runs the RLM bootstrap after start; tests match that contract.
- bootstrap_code: Some(build_rlm_bootstrap_code(&[])),
+ bootstrap_code: Some(build_rlm_bootstrap_code(&[], false)),
stderr_log_path: None,
})
}
@@ -199,7 +199,7 @@ async fn rlm_bootstrap_injects_the_kernel_surface() {
return;
};
let options = KernelManagerOptions {
- bootstrap_code: Some(build_rlm_bootstrap_code(&[])),
+ bootstrap_code: Some(build_rlm_bootstrap_code(&[], false)),
..base
};
let manager = started_manager(options).await;
@@ -246,7 +246,7 @@ async fn host_requests_round_trip_to_registered_handlers() {
};
let options = KernelManagerOptions {
host_handlers: handlers,
- bootstrap_code: Some(build_rlm_bootstrap_code(&[])),
+ bootstrap_code: Some(build_rlm_bootstrap_code(&[], false)),
..base
};
let manager = started_manager(options).await;
diff --git a/crates/pa-core/tests/kernel_restore_guards.rs b/crates/pa-core/tests/kernel_restore_guards.rs
index ea4b592916..f83bcaac1b 100644
--- a/crates/pa-core/tests/kernel_restore_guards.rs
+++ b/crates/pa-core/tests/kernel_restore_guards.rs
@@ -70,7 +70,7 @@ fn test_options(
max_variable_bytes: None,
debounce_ms,
}),
- bootstrap_code: Some(build_rlm_bootstrap_code(&[])),
+ bootstrap_code: Some(build_rlm_bootstrap_code(&[], false)),
stderr_log_path: None,
on_background_work_settled: None,
})
@@ -202,7 +202,7 @@ async fn post_restore_auto_snapshot_skips_until_a_real_cell_changes_the_namespac
let restore = reader.restore_state().await.expect("restore");
assert!(restore.restored.iter().any(|name| name == "restored_var"));
- let bootstrap_code = build_rlm_bootstrap_code(&[]);
+ let bootstrap_code = build_rlm_bootstrap_code(&[], false);
let bootstrap = reader
.execute(&bootstrap_code, ExecuteOptions::default())
.await
diff --git a/crates/pa-core/tests/kernel_teardown.rs b/crates/pa-core/tests/kernel_teardown.rs
index f12c6729eb..687e7a2267 100644
--- a/crates/pa-core/tests/kernel_teardown.rs
+++ b/crates/pa-core/tests/kernel_teardown.rs
@@ -159,7 +159,10 @@ fn test_options() -> Option<pa_core::kernel::shared::KernelManagerOptions> {
python_skills: Vec::new(),
on_background_work_settled: None,
snapshot: None,
- bootstrap_code: Some(pa_core::kernel::bootstrap::build_rlm_bootstrap_code(&[])),
+ bootstrap_code: Some(pa_core::kernel::bootstrap::build_rlm_bootstrap_code(
+ &[],
+ false,
+ )),
stderr_log_path: None,
})
}
diff --git a/crates/pa-core/tests/prompt_guards.rs b/crates/pa-core/tests/prompt_guards.rs
index 1147d018de..0af594c52c 100644
--- a/crates/pa-core/tests/prompt_guards.rs
+++ b/crates/pa-core/tests/prompt_guards.rs
@@ -284,7 +284,7 @@ fn all_string_literals(text: &str) -> Vec<String> {
/// Kernel-bound REPL names from the real bootstrap code (`rlm`, `bash`,
/// `mcp`), derived from `build_rlm_bootstrap_code`.
fn kernel_bound_names() -> BTreeSet<String> {
- let code = pa_core::kernel::bootstrap::build_rlm_bootstrap_code(&[]);
+ let code = pa_core::kernel::bootstrap::build_rlm_bootstrap_code(&[], false);
let mut names = BTreeSet::new();
for line in code.lines() {
let line = line.trim_start();
@@ -535,6 +535,38 @@ fn bundled_skills_match_the_ts_packaged_set() {
);
}
+/// The bounded-await contract renders only in daemon sessions: the
+/// runtime half (the degrade) exists only where the host registers the
+/// bash completion notice, so a daemonless prompt must carry no trace of it.
+#[test]
+fn bounded_await_contract_render_is_daemon_only() {
+ let mut options = BuildSystemPromptOptions {
+ cwd: "/w".to_string(),
+ messages_path: Some("/log.jsonl".to_string()),
+ skills: sorted_bundled_skills(),
+ selected_tools: Some(vec!["python_repl"]),
+ ..Default::default()
+ };
+ let daemon = system_prompt_breakdown(&options);
+ assert!(
+ daemon.assembled.contains("yield_after")
+ && daemon.assembled.contains("[bash-done]")
+ && daemon.assembled.contains("`r.running` is True")
+ && daemon.assembled.contains("`r.exit_code` is None"),
+ "the daemon session prompt must carry the bounded-await result contract"
+ );
+ options.daemonless = true;
+ let daemonless = system_prompt_breakdown(&options);
+ assert!(
+ !daemonless.assembled.contains("yield_after")
+ && !daemonless.assembled.contains("[bash-done]")
+ && !daemonless.assembled.contains("still-running snapshot")
+ && !daemonless.assembled.contains("about 10 seconds"),
+ "the daemonless session prompt must not leak the bounded-await contract: {0}",
+ daemonless.assembled
+ );
+}
+
/// The generic mcp skill loads through the normal markdown discovery and renders in the
/// `<available_skills>` inventory exactly like any other markdown skill: the `[skill name
/// location]`-style XML the TS `formatSkillsForPrompt` emits, without a `python_import` line.
diff --git a/crates/pa-daemon/src/bash_notices.rs b/crates/pa-daemon/src/bash_notices.rs
index 56da47973c..b1cfee61d3 100644
--- a/crates/pa-daemon/src/bash_notices.rs
+++ b/crates/pa-daemon/src/bash_notices.rs
@@ -6,7 +6,7 @@
use serde_json::Value;
-use pa_core::kernel::shared::{host_handler, HostRequestHandlers};
+use pa_core::kernel::shared::{host_handler, HostRequestHandlers, BASH_COMPLETED_REQUEST_TYPE};
use crate::agent_engine::AgentSessionEngine;
use crate::engine::{BashCompletionNotice, BashConsumedNotice};
@@ -56,7 +56,7 @@ impl AgentSessionEngine {
return;
};
handlers.register(
- "bash.completed",
+ BASH_COMPLETED_REQUEST_TYPE,
host_handler(move |payload| {
let completion = completion.clone();
Box::pin(async move {
diff --git a/crates/pa-daemon/tests/autobg_headless_e2e.rs b/crates/pa-daemon/tests/autobg_headless_e2e.rs
new file mode 100644
index 0000000000..6333ad4081
--- /dev/null
+++ b/crates/pa-daemon/tests/autobg_headless_e2e.rs
@@ -0,0 +1,431 @@
+//! Bounded bash await, headless e2e: a `python_repl` tool call that does a
+//! blocking `await bash(...)` keeps the turn moving instead of wedging it,
+//! with NO override — the kernel bootstrap's default wiring (the
+//! bash.completed host handler flips the runtime's bounded default on) is
+//! the thing under test.
+//!
+//! The mock provider scripts the turn: request 1 calls `python_repl` with a
+//! one-shot `await bash('sleep 13; echo ...')`. The await degrades at the
+//! 10s default: the tool result carries the still-running handle, and the
+//! turn settles while the command keeps running. Its `[bash-done ...]`
+//! notice then wakes the idle session. Everything is asserted by transcript
+//! event ORDER, not wall-clock caps.
+
+// 64-bit-only targets; the narrowing casts sit at bounded OS boundaries.
+#![allow(
+ clippy::cast_possible_truncation,
+ clippy::cast_possible_wrap,
+ clippy::cast_sign_loss,
+ clippy::cast_precision_loss
+)]
+// Fn length is a style gate, not correctness.
+#![allow(clippy::too_many_lines)]
+// API-shape opinions, not defects; the surfaces are deliberate.
+#![allow(
+ clippy::unnecessary_wraps,
+ clippy::zero_sized_map_values,
+ clippy::struct_excessive_bools,
+ clippy::struct_field_names
+)]
+#![cfg(unix)]
+
+use std::fmt::Write as _;
+use std::io::{BufRead, BufReader, Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::os::unix::net::UnixStream;
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::{Duration, Instant};
+
+use serde_json::{json, Value};
+
+struct Daemon {
+ child: Child,
+ #[allow(dead_code)]
+ socket: PathBuf,
+}
+
+impl Drop for Daemon {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+/// The kernel Python with prime-agent-runtime installed; `PA_E2E_KERNEL_PYTHON` overrides.
+fn kernel_python() -> Option<PathBuf> {
+ if let Some(explicit) = std::env::var_os("PA_E2E_KERNEL_PYTHON") {
+ let explicit = PathBuf::from(explicit);
+ assert!(
+ explicit.exists(),
+ "PA_E2E_KERNEL_PYTHON {} not found",
+ explicit.display()
+ );
+ return Some(explicit);
+ }
+ let candidate = PathBuf::from(std::env::var("HOME").map_or_else(
+ |_| "/home/ubuntu/.prime/agent/kernel-venv/bin/python".to_string(),
+ |home| format!("{home}/.prime/agent/kernel-venv/bin/python"),
+ ));
+ if candidate.exists() {
+ return Some(candidate);
+ }
+ eprintln!(
+ "kernel python {} not found; skipping bounded-await e2e",
+ candidate.display()
+ );
+ None
+}
+
+/// The sequential mock: one SSE answer per request in order.
+fn spawn_mock(next: &'static AtomicUsize) -> PathBuf {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock");
+ let url = format!(
+ "http://127.0.0.1:{}/v1",
+ listener.local_addr().unwrap().port()
+ );
+ std::thread::spawn(move || {
+ for stream in listener.incoming() {
+ let Ok(stream) = stream else { continue };
+ std::thread::spawn(move || {
+ let _ = serve(stream, next);
+ });
+ }
+ });
+ PathBuf::from(url)
+}
+
+fn chunk(delta: &Value, finish_reason: Option<&str>) -> String {
+ json!({
+ "id": "chatcmpl-bounded",
+ "object": "chat.completion.chunk",
+ "created": 1_750_000_000,
+ "model": "mock-1",
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],
+ })
+ .to_string()
+}
+
+fn serve(mut stream: TcpStream, next: &AtomicUsize) -> std::io::Result<()> {
+ let mut reader = BufReader::new(stream.try_clone()?);
+ let mut content_length = 0usize;
+ loop {
+ let mut line = String::new();
+ if reader.read_line(&mut line)? == 0 {
+ return Ok(());
+ }
+ if line == "\r\n" {
+ break;
+ }
+ let lower = line.to_ascii_lowercase();
+ if let Some(value) = lower.strip_prefix("content-length:") {
+ content_length = value.trim().parse().unwrap_or_default();
+ }
+ }
+ let mut body = vec![0u8; content_length];
+ if content_length > 0 {
+ reader.read_exact(&mut body)?;
+ }
+ // The scripted sequence: request 1 answers the python_repl tool call that
+ // runs the bounded one-shot await, request 2 ends the turn, every later
+ // request the woken reply.
+ let request = next.fetch_add(1, Ordering::SeqCst);
+ let mut payload = String::new();
+ let data = match request {
+ 0 => [
+ chunk(
+ &json!({
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [{
+ "index": 0,
+ "id": "call-bounded-1",
+ "type": "function",
+ "function": {
+ "name": "python_repl",
+ "arguments": "{\"code\": \"from rlm import bash\\nres = await bash('sleep 13; echo BOUNDED_AWAIT_E2E_DONE')\\nres\"}"
+ }
+ }]
+ }),
+ None,
+ ),
+ chunk(&json!({}), Some("tool_calls")),
+ ],
+ 1 => [
+ chunk(
+ &json!({"role": "assistant", "content": "turn complete"}),
+ None,
+ ),
+ chunk(&json!({}), Some("stop")),
+ ],
+ _ => [
+ chunk(
+ &json!({"role": "assistant", "content": "woken by the bash-done notice"}),
+ None,
+ ),
+ chunk(&json!({}), Some("stop")),
+ ],
+ };
+ for data in data {
+ write!(payload, "data: {data}\n\n").expect("write to String");
+ }
+ payload.push_str("data: [DONE]\n\n");
+ stream.write_all(
+ format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{payload}"
+ )
+ .as_bytes(),
+ )
+}
+
+struct Client {
+ reader: BufReader<UnixStream>,
+ writer: UnixStream,
+}
+
+impl Client {
+ fn connect(socket: &Path) -> Client {
+ let stream = UnixStream::connect(socket).expect("connect");
+ let writer = stream.try_clone().expect("clone");
+ let mut client = Client {
+ reader: BufReader::new(stream),
+ writer,
+ };
+ let hello = client.read_line();
+ assert_eq!(hello["type"], "daemon_hello");
+ client
+ }
+
+ fn read_line(&mut self) -> Value {
+ let mut line = String::new();
+ let deadline = Instant::now() + Duration::from_mins(2);
+ self.reader
+ .get_mut()
+ .set_read_timeout(Some(Duration::from_millis(100)))
+ .expect("timeout");
+ loop {
+ match self.reader.read_line(&mut line) {
+ Ok(0) => panic!("supervisor closed the connection"),
+ Ok(_) if line.trim().is_empty() => line.clear(),
+ Ok(_) => return serde_json::from_str(line.trim()).expect("parse line"),
+ Err(error) => {
+ assert!(
+ Instant::now() < deadline,
+ "timed out waiting for supervisor line: {error}"
+ );
+ }
+ }
+ }
+ }
+
+ fn request(&mut self, id: &str, command: &Value) -> Value {
+ let envelope = json!({
+ "type": "command",
+ "id": id,
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "command": command,
+ });
+ let mut line = serde_json::to_string(&envelope).expect("serialize");
+ line.push('\n');
+ self.writer
+ .write_all(line.as_bytes())
+ .unwrap_or_else(|error| panic!("write command {id}: {error}"));
+ let deadline = Instant::now() + Duration::from_mins(2);
+ loop {
+ assert!(Instant::now() < deadline, "no response for id {id}");
+ let line = self.read_line();
+ if line.get("id").and_then(Value::as_str) == Some(id) {
+ return line;
+ }
+ }
+ }
+
+ fn messages(&mut self, active_session_id: &str) -> String {
+ let response = self.request(
+ "gm",
+ &json!({ "type": "get_messages", "activeSessionId": active_session_id }),
+ );
+ assert_eq!(response["success"], true, "get_messages failed: {response}");
+ serde_json::to_string(&response["data"]).expect("messages json")
+ }
+}
+
+fn wait_until<T>(deadline: Duration, mut probe: impl FnMut() -> Option<T>) -> T {
+ let deadline = Instant::now() + deadline;
+ loop {
+ if let Some(value) = probe() {
+ return value;
+ }
+ assert!(Instant::now() < deadline, "condition never became true");
+ std::thread::sleep(Duration::from_millis(100));
+ }
+}
+
+#[allow(clippy::zombie_processes)]
+fn spawn_daemon(socket: &Path, agent_dir: &Path, kernel_python: Option<&Path>) -> Daemon {
+ std::fs::create_dir_all(agent_dir).expect("agent dir");
+ let mut command = Command::new(env!("CARGO_BIN_EXE_pa-daemon"));
+ command
+ .arg("supervisor")
+ .arg("--socket")
+ .arg(socket)
+ .arg("--agent-dir")
+ .arg(agent_dir)
+ .env_remove("PRIME_API_KEY")
+ .env("PRIME_AGENT_CODING_AGENT_DIR", agent_dir)
+ // A supervisor killed at teardown must not leak its session workers.
+ .env(
+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
+ "20000",
+ );
+ if let Some(kernel_python) = kernel_python {
+ command.env("PRIME_AGENT_KERNEL_PYTHON", kernel_python);
+ }
+ let child = command
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .expect("spawn pa-daemon supervisor");
+ let deadline = Instant::now() + Duration::from_secs(15);
+ while Instant::now() < deadline {
+ if socket.exists() {
+ return Daemon {
+ child,
+ socket: socket.to_path_buf(),
+ };
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ panic!("supervisor socket never appeared");
+}
+
+#[test]
+fn a_bounded_bash_await_degrades_and_the_notice_wakes_the_session() {
+ static NEXT: AtomicUsize = AtomicUsize::new(0);
+ let Some(kernel_python) = kernel_python() else {
+ return;
+ };
+ let root = tempfile::TempDir::new().expect("temp dir");
+ let dir = root.path().to_path_buf();
+ let agent_dir = dir.join("agent");
+ std::fs::create_dir_all(&agent_dir).expect("agent dir");
+ let socket = dir.join("daemon.sock");
+ let url = spawn_mock(&NEXT);
+ std::fs::write(
+ agent_dir.join("models.json"),
+ json!({
+ "providers": {
+ "prime-inference": {
+ "api": "openai-completions",
+ "baseUrl": url.to_string_lossy(),
+ "apiKey": "sk-bounded",
+ "models": [
+ {
+ "id": "mock-1",
+ "name": "Mock 1",
+ "api": "openai-completions",
+ "contextWindow": 128_000,
+ "maxTokens": 4096
+ }
+ ]
+ }
+ }
+ })
+ .to_string(),
+ )
+ .expect("write models.json");
+
+ let supervisor = spawn_daemon(&socket, &agent_dir, Some(&kernel_python));
+ let mut client = Client::connect(&socket);
+ let sessions = agent_dir.join("sessions");
+ std::fs::create_dir_all(&sessions).expect("sessions dir");
+ let created = client.request(
+ "c1",
+ &json!({
+ "type": "create",
+ "name": "bounded-await-lane",
+ "config": {
+ "cwd": dir.to_string_lossy(),
+ "sessionDir": sessions.to_string_lossy(),
+ "provider": "prime-inference",
+ "model": "mock-1",
+ },
+ }),
+ );
+ assert_eq!(created["success"], true, "create failed: {created}");
+ let active_id = created["data"]["id"]
+ .as_str()
+ .or_else(|| created["data"]["activeSessionId"].as_str())
+ .expect("active session id")
+ .to_string();
+
+ // THE TURN: the tool call awaits a 13s command with NO override; the
+ // default wiring must degrade the await and settle the turn while the
+ // command is still running.
+ let turn = client.request(
+ "p1",
+ &json!({
+ "type": "prompt_and_wait",
+ "activeSessionId": active_id,
+ "message": "run the blocking await and finish",
+ }),
+ );
+ assert_eq!(turn["success"], true, "turn failed: {turn}");
+
+ // Event ORDER, part 1 — the tool result shows the RUNNING snapshot (the
+ // degrade hint rides the same stderr lane) and the turn settled before
+ // the command finished: no completed-result repr anywhere yet.
+ let after_turn = client.messages(&active_id);
+ let snapshot = after_turn
+ .find("<BashSnapshot running pid=")
+ .expect("the tool result never showed the running snapshot");
+ let turn_end = after_turn
+ .find("turn complete")
+ .expect("the follow-up assistant reply never landed");
+ assert!(
+ snapshot < turn_end,
+ "the running-snapshot tool result must precede the turn's end: {after_turn}"
+ );
+ assert!(
+ !after_turn.contains("BashResult("),
+ "the await blocked to completion instead of degrading: {after_turn}"
+ );
+ assert!(
+ after_turn.contains("still running after"),
+ "the budgeted degrade hint never reached the tool result: {after_turn}"
+ );
+
+ // Event ORDER, part 2 — the command finishes past the turn, and its
+ // notice wakes the idle session: the woken reply can only follow the
+ // [bash-done] row that caused it.
+ let settled = wait_until(Duration::from_mins(1), || {
+ let messages = client.messages(&active_id);
+ (messages.contains("[bash-done pid:") && messages.contains("exit:0")).then_some(messages)
+ });
+ let notice = settled
+ .find("[bash-done pid:")
+ .expect("the bash-done notice never landed");
+ assert!(
+ notice > turn_end,
+ "the notice must land after the turn settled, not inside it: {settled}"
+ );
+ // The wake itself: the woken reply can only exist after the notice.
+ wait_until(Duration::from_mins(1), || {
+ let messages = client.messages(&active_id);
+ let woken_after_notice = messages
+ .find("woken by the bash-done notice")
+ .is_some_and(|at| at > notice);
+ woken_after_notice.then_some(messages)
+ });
+
+ // Teardown: stop the session through the live supervisor so the worker
+ // (and its kernel + the 13s sleeper) do not leak past the test.
+ client.request(
+ "k1",
+ &json!({ "type": "kill", "activeSessionId": active_id }),
+ );
+ drop(client);
+ drop(supervisor);
+}
diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.py
index 6f36acc24a..90e85f85fe 100644
--- a/prime-agent-runtime/src/rlm/__init__.py
+++ b/prime-agent-runtime/src/rlm/__init__.py
@@ -8,7 +8,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any
-from .bash import BashHandle, BashResult, bash
+from .bash import BashHandle, BashResult, BashSnapshot, bash, _set_completion_notices_wired
from .factory import (
FACTORY_HELP,
graph_factory,
diff --git a/prime-agent-runtime/src/rlm/bash.py b/prime-agent-runtime/src/rlm/bash.py
index 79e285f572..2c6297d0a0 100644
--- a/prime-agent-runtime/src/rlm/bash.py
+++ b/prime-agent-runtime/src/rlm/bash.py
@@ -19,7 +19,7 @@ import threading
import time
import uuid
from collections import deque
-from collections.abc import Callable, Generator
+from collections.abc import Awaitable, Callable, Generator
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, NoReturn, cast
@@ -57,6 +57,88 @@ _ASYNCIO_WRAPPER_CALLBACKS = {
("asyncio.tasks", "_release_waiter"),
}
+# Bounded awaits (yield_after): in sessions whose host registers the
+# bash.completed handler, an await past its bound degrades to returning the
+# live handle instead of blocking (the [bash-done] notice collects it). The
+# kernel bootstrap flips the flag from the host-handler registry — one source
+# of truth; the numbers stay here, never on the Rust side.
+_completion_notices_wired = False
+_DEFAULT_YIELD_AFTER_SECONDS = 10.0
+_MAX_YIELD_AFTER_SECONDS = 300.0
+
+
+def _set_completion_notices_wired(wired: bool) -> None:
+ """Record whether the host wires bash completion notices.
+
+ Called by the kernel bootstrap only when the `bash.completed` host handler
+ is registered. Sessions without the notice keep unbounded awaits: nothing
+ would wake a cell that ended its turn on a degraded command.
+ """
+ global _completion_notices_wired
+ _completion_notices_wired = wired
+
+
+def _effective_yield_after(yield_after: float | None) -> float | None:
+ """The bound every await of a handle uses; None means unbounded."""
+ if not _completion_notices_wired:
+ return None
+ if yield_after is None:
+ return _DEFAULT_YIELD_AFTER_SECONDS
+ return min(yield_after, _MAX_YIELD_AFTER_SECONDS)
+
+
+# One stderr hint per degrade, budgeted per kernel (nano-rlm's
+# MAX_LONG_RUN_NOTES shape): the first few degrades teach the contract, later
+# ones stay quiet.
+_MAX_DEGRADE_HINTS = 3
+_degrade_hints_written = 0
+
+
+def _note_degrade(handle: "BashHandle") -> None:
+ """Write the degrade hint to the awaiting cell's stderr, within budget."""
+ global _degrade_hints_written
+ if _degrade_hints_written >= _MAX_DEGRADE_HINTS:
+ return
+ _degrade_hints_written += 1
+ sys.stderr.write(
+ f"bash: still running after {handle._yield_after:g}s (pid {handle._pid}); "
+ "returned a snapshot: r.running is True, r.output is the output so "
+ "far, r.handle is the live handle. End the turn — a [bash-done] "
+ "notification arrives when it finishes.\n"
+ )
+
+
+async def _bounded_wait(
+ wait: Awaitable[BashResult], yield_after: float | None
+) -> BashResult | None:
+ """Await a command wait, abandoning it after `yield_after` seconds.
+
+ Returns None only on the degrade: the wait task keeps running (cancelling
+ an owned wait would kill the command — the degrade must not), and its
+ late result is consumed silently by the done callback.
+ """
+ if yield_after is None:
+ return await wait
+ wait_task = asyncio.ensure_future(wait)
+ try:
+ done, _pending = await asyncio.wait({wait_task}, timeout=yield_after)
+ except asyncio.CancelledError:
+ # An interrupt inside the window: the wait must observe the cancel
+ # (an owned await runs its kill dance in _wait_owned) before the
+ # CancelledError propagates.
+ wait_task.cancel()
+ while not wait_task.done():
+ try:
+ await asyncio.shield(wait_task)
+ except asyncio.CancelledError:
+ continue
+ raise
+ if wait_task in done:
+ return wait_task.result()
+ wait_task.add_done_callback(_consume_notice_task)
+ return None
+
+
_live_handles: set["BashHandle"] = set()
# Kernel-owned opaque IDs: retained results are bounded, never resolved by PID.
_activity_handles: dict[str, "BashHandle"] = {}
@@ -190,6 +272,38 @@ class BashResult:
output: str
duration: float
+ @property
+ def running(self) -> bool:
+ # The discriminator the prompt teaches: a finished result is never
+ # running (BashSnapshot.running is True). A property, not a field, so
+ # repr, equality, and positional construction stay unchanged.
+ return False
+
+
+@dataclass(frozen=True)
+class BashSnapshot:
+ """A degraded await's still-running snapshot (`BashHandle.__await__`).
+
+ `r.output`/`r.exit_code` read like a BashResult's — output so far and
+ None while running — and `r.running` is True; `r.handle` is the live
+ handle: collect the final result on the [bash-done] notification or with
+ `await r.handle`. The snapshot itself is not awaitable (that was #3076's
+ rejected wrapper shape).
+ """
+
+ output: str
+ exit_code: None
+ running: bool
+ duration: float
+ handle: "BashHandle"
+
+ def __repr__(self) -> str:
+ return (
+ f"<BashSnapshot running pid={self.handle._pid} "
+ f"after {self.duration:g}s: collect on the [bash-done] "
+ "notification or await .handle>"
+ )
+
class _BoundedBuffer:
"""First _HEAD_CAP bytes plus a rolling _TAIL_CAP-byte tail; the middle is dropped."""
@@ -249,8 +363,11 @@ class BashHandle:
handle; later awaits only wait and cancelling them leaves it running.
"""
- def __init__(self, command: str) -> None:
+ def __init__(self, command: str, yield_after: float | None = None) -> None:
self.command = command
+ # The bound every await of this handle uses (None = unbounded); the
+ # caller's effective value, resolved once in bash().
+ self._yield_after = yield_after
self._activity_id = secrets.token_hex(16)
completion_context = _current_cell_completion_context()
self._creating_cell_finished = completion_context[0] if completion_context else None
@@ -927,10 +1044,11 @@ class BashHandle:
if delivered:
_record_journal(self._pid, active=False)
- def __await__(self) -> Generator[Any, None, BashResult]:
+ def __await__(self) -> Generator[Any, None, BashResult | BashSnapshot]:
# A handle awaited before any other API use is a one-shot command tied
# to the await (kill-on-cancel); touching the handle API first marks it
- # as a deliberate background handle whose awaits only wait.
+ # as a deliberate background handle whose awaits only wait. Both paths
+ # wait at most the handle's bound, then degrade to this live handle.
try:
current_task = asyncio.current_task()
except RuntimeError:
@@ -940,18 +1058,43 @@ class BashHandle:
wait = self._wait_owned() if owned else self._wait()
self._released = True
completed = False
+ degraded = False
try:
- result = yield from wait.__await__()
- completed = True
- return result
+ result = yield from _bounded_wait(wait, self._yield_after).__await__()
+ if result is None:
+ degraded = True
+ else:
+ completed = True
finally:
- if (completed or owned) and (
- creating_cell_waited
- or _creating_cell_waits_for(self._creating_cell_task, current_task)
+ # A degraded await never completed: the [bash-done] notice must
+ # still fire, so it counts as neither awaited nor consumed.
+ if (
+ not degraded
+ and (completed or owned)
+ and (
+ creating_cell_waited
+ or _creating_cell_waits_for(self._creating_cell_task, current_task)
+ )
):
self._awaited_by_creating_cell = True
if completed:
self._note_result_consumed(current_task)
+ if degraded:
+ _note_degrade(self)
+ return self._degrade_snapshot()
+ return cast("BashResult", result)
+
+ def _degrade_snapshot(self) -> BashSnapshot:
+ """Read the internal buffer directly: the public readers count as a
+ result read, which would withdraw the [bash-done] notice the degrade
+ must keep alive."""
+ return BashSnapshot(
+ output=self._buffer.text(),
+ exit_code=None,
+ running=True,
+ duration=time.monotonic() - self._started,
+ handle=self,
+ )
def __reduce__(self) -> NoReturn:
# Reviving a handle would resurrect a stale pid and raw fd numbers: dill
@@ -964,11 +1107,19 @@ class BashHandle:
return f"<BashHandle pid={self._pid} {state} command={self.command!r}>"
-def bash(command: str) -> BashHandle:
+def bash(command: str, yield_after: float | None = None) -> BashHandle:
"""Start a shell command immediately; await the handle for the result.
`await bash(cmd)` is a one-shot: cancelling the await (e.g. an interrupt)
- kills the command's process group. `h = bash(cmd)` used as a background
+ kills the command's process group. In sessions whose host wires completion
+ notices (the kernel bootstrap turns the bounded default on), an await that
+ is still running after `yield_after` seconds instead DEGRADES: it returns a
+ BashSnapshot (r.running True, r.output the output so far, r.handle the live
+ handle) while the command keeps running, and its [bash-done] notification
+ arrives on completion. `yield_after=None` uses the session
+ default (10 seconds); explicit values must be positive and are clamped to
+ 300. In sessions without completion notices every await stays unbounded and
+ `yield_after` has no effect. `h = bash(cmd)` used as a background
handle (any .pid/.running/.output()/.tail()/.poll()/.kill() access before
the first await) survives cancellation; awaiting it only waits. Leak
containment is per-platform: process groups plus the orphan journal on
@@ -981,8 +1132,10 @@ def bash(command: str) -> BashHandle:
"""
if not isinstance(command, str) or not command:
raise TypeError("command must be a non-empty str")
+ if yield_after is not None and yield_after <= 0:
+ raise ValueError("yield_after must be a positive number of seconds")
_install_shutdown_hook()
- handle = BashHandle(command)
+ handle = BashHandle(command, _effective_yield_after(yield_after))
from . import repl
repl.emit(
diff --git a/prime-agent-runtime/test/test_agent_message_skill.py b/prime-agent-runtime/test/test_agent_message_skill.py
index d0351a85ed..e3aa631268 100644
--- a/prime-agent-runtime/test/test_agent_message_skill.py
+++ b/prime-agent-runtime/test/test_agent_message_skill.py
@@ -7,7 +7,7 @@ from pathlib import Path
from unittest.mock import AsyncMock, patch
-SKILL = Path(__file__).parents[2] / "packages/coding-agent/skills/agent-message/src/agent_message/__init__.py"
+SKILL = Path(__file__).parents[2] / "skills/agent-message/src/agent_message/__init__.py"
class AgentMessageSkillTest(unittest.TestCase):
diff --git a/prime-agent-runtime/test/test_bash.py b/prime-agent-runtime/test/test_bash.py
index 471f0bf5c5..e6149e1aad 100644
--- a/prime-agent-runtime/test/test_bash.py
+++ b/prime-agent-runtime/test/test_bash.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import io
import json
import os
import resource
@@ -536,8 +537,8 @@ class BashTest(unittest.IsolatedAsyncioTestCase):
pids: list[int] = []
original_init = bash_module.BashHandle.__init__
- def capturing_init(handle_self, command):
- original_init(handle_self, command)
+ def capturing_init(handle_self, command, *args, **kwargs):
+ original_init(handle_self, command, *args, **kwargs)
pids.append(handle_self._pid)
async def run_oneshot():
@@ -564,8 +565,8 @@ class BashTest(unittest.IsolatedAsyncioTestCase):
pids: list[int] = []
original_init = bash_module.BashHandle.__init__
- def capturing_init(handle_self, command):
- original_init(handle_self, command)
+ def capturing_init(handle_self, command, *args, **kwargs):
+ original_init(handle_self, command, *args, **kwargs)
pids.append(handle_self._pid)
async def run_oneshot():
@@ -639,8 +640,8 @@ class BashTest(unittest.IsolatedAsyncioTestCase):
pids: list[int] = []
original_init = bash_module.BashHandle.__init__
- def capturing_init(handle_self, command):
- original_init(handle_self, command)
+ def capturing_init(handle_self, command, *args, **kwargs):
+ original_init(handle_self, command, *args, **kwargs)
pids.append(handle_self._pid)
async def run_oneshot():
@@ -1275,17 +1276,11 @@ class BashTest(unittest.IsolatedAsyncioTestCase):
with mock.patch.object(bash_module.os, "killpg", side_effect=OSError):
self.assertFalse(bash_module._signal_group(1234567, signal.SIGKILL))
- async def test_journal_configured_but_unwritable_kills_child_and_raises(self):
+ async def test_journal_configured_but_unwritable_stays_best_effort(self):
+ # TS parity (#2524): a journal that cannot be written means the
+ # command runs untracked, never that the spawn dies.
with tempfile.TemporaryDirectory() as tmp:
marker = os.path.join(tmp, "marker")
- pids: list[int] = []
- real_popen = subprocess.Popen
-
- def capturing_popen(*args, **kwargs):
- proc = real_popen(*args, **kwargs)
- pids.append(proc.pid)
- return proc
-
with mock.patch.dict(
os.environ,
{
@@ -1293,14 +1288,9 @@ class BashTest(unittest.IsolatedAsyncioTestCase):
"PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
},
):
- with mock.patch.object(bash_module.subprocess, "Popen", capturing_popen):
- with self.assertRaises(RuntimeError):
- bash(f"touch {marker}")
- await _poll_group_dead(pids[0])
- await asyncio.sleep(0.2)
- self.assertFalse(os.path.exists(marker))
- with bash_module._live_lock:
- self.assertFalse(bash_module._live_handles)
+ result = await asyncio.wait_for(bash(f"touch {marker}"), timeout=5)
+ self.assertEqual(result.exit_code, 0)
+ self.assertTrue(os.path.exists(marker))
async def test_journal_bad_owner_pid_rejects(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -1315,7 +1305,10 @@ class BashTest(unittest.IsolatedAsyncioTestCase):
with self.assertRaises(RuntimeError):
bash("echo hi")
- async def test_missing_start_id_rejects_when_configured(self):
+ async def test_missing_start_id_records_identity_free(self):
+ # Identity-free records (no processStartId) are valid and still
+ # safely reaped on POSIX via the group-scoped kill: the spawn must
+ # not fail when the start id is unavailable.
with tempfile.TemporaryDirectory() as tmp:
journal = os.path.join(tmp, "journal.jsonl")
with mock.patch.dict(
@@ -1326,12 +1319,17 @@ class BashTest(unittest.IsolatedAsyncioTestCase):
},
):
with mock.patch.object(bash_module, "_process_start_id", return_value=None):
- with self.assertRaises(RuntimeError):
- bash("sleep 30")
+ result = await bash("echo ok")
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("ok", result.output)
+ with open(journal) as f:
+ record = json.loads(next(line for line in f if line.strip()))
+ self.assertNotIn("processStartId", record)
+ self.assertTrue(record["active"])
- async def test_journal_short_write_rejects_when_configured(self):
- # A partial os.write would leave a truncated JSON line the host
- # discards; enrollment must treat it as failure.
+ async def test_journal_short_write_stays_best_effort(self):
+ # A zero-write leaves no complete record (the host discards truncated
+ # lines) but enrollment still returns True: the command is alive.
with tempfile.TemporaryDirectory() as tmp:
journal = os.path.join(tmp, "journal.jsonl")
@@ -1346,7 +1344,8 @@ class BashTest(unittest.IsolatedAsyncioTestCase):
},
):
with mock.patch.object(bash_module.os, "write", short_write):
- self.assertFalse(bash_module._record_journal(os.getpid(), active=False))
+ self.assertTrue(bash_module._record_journal(os.getpid(), active=False))
+ self.assertEqual(os.path.getsize(journal), 0)
async def test_journal_partial_writes_complete_the_record(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -1379,6 +1378,92 @@ class BashTest(unittest.IsolatedAsyncioTestCase):
self.assertIn("ok", result.output)
+class BoundedAwaitTest(unittest.IsolatedAsyncioTestCase):
+ """The yield_after contract: with completion notices wired (the kernel
+ bootstrap call) an await degrades to the live handle past its bound;
+ without them every await stays unbounded (nothing wakes a collector)."""
+
+ def _wire_notices(self) -> None:
+ bash_module._set_completion_notices_wired(True)
+ self.addCleanup(bash_module._set_completion_notices_wired, False)
+ bash_module._degrade_hints_written = 0
+ self.addCleanup(setattr, bash_module, "_degrade_hints_written", 0)
+
+ async def test_wired_default_and_maximum_bounds(self):
+ self._wire_notices()
+ self.assertEqual(bash_module._effective_yield_after(None), 10.0)
+ self.assertEqual(bash_module._effective_yield_after(500), 300.0)
+ self.assertEqual(bash_module._effective_yield_after(0.25), 0.25)
+ bash_module._set_completion_notices_wired(False)
+ self.assertIsNone(bash_module._effective_yield_after(None))
+ self.assertIsNone(bash_module._effective_yield_after(0.25))
+
+ async def test_bounded_await_degrades_to_a_snapshot(self):
+ self._wire_notices()
+ handle = bash("sleep 0.5", yield_after=0.3)
+ returned = await handle
+ self.assertIsInstance(returned, bash_module.BashSnapshot)
+ self.assertIs(returned.handle, handle)
+ self.assertIsNone(returned.exit_code)
+ self.assertTrue(returned.running)
+ self.assertIsInstance(returned.output, str)
+ # The prompt's collect idiom: re-awaiting the live handle returns the
+ # final result once the command finishes inside the window.
+ result = await returned.handle
+ self.assertEqual(result.exit_code, 0)
+
+ async def test_bounded_await_returns_the_result_within_the_window(self):
+ self._wire_notices()
+ result = await bash("printf quick", yield_after=5)
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("quick", result.output)
+ self.assertIs(result.running, False)
+ with self.assertRaises(ValueError):
+ bash("echo no", yield_after=0)
+ with self.assertRaises(ValueError):
+ bash("echo no", yield_after=-1)
+
+ async def test_daemonless_await_ignores_the_bound(self):
+ # No completion notices wired: no wake-up exists to collect a
+ # degraded command, so the await stays unbounded and yield_after
+ # has no effect.
+ result = await bash("sleep 1", yield_after=0.2)
+ self.assertEqual(result.exit_code, 0)
+
+ async def test_cancelling_a_later_await_of_a_degraded_handle_only_waits(self):
+ self._wire_notices()
+ handle = bash("sleep 1.5", yield_after=0.3)
+ snapshot = await handle
+ self.assertIsInstance(snapshot, bash_module.BashSnapshot)
+
+ async def consume():
+ return await handle
+
+ task = asyncio.create_task(consume())
+ await asyncio.sleep(0.2)
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+ # The degrade released the handle: a cancelled later await stops
+ # waiting without killing the still-running command.
+ self.assertTrue(handle.running)
+ result = await asyncio.wait_for(handle._wait(), 10)
+ self.assertEqual(result.exit_code, 0)
+
+ async def test_degrade_hints_are_budgeted_to_the_first_three(self):
+ self._wire_notices()
+ handles = []
+ hints = io.StringIO()
+ with mock.patch.object(sys, "stderr", hints):
+ for _ in range(5):
+ handle = bash("sleep 3", yield_after=0.2)
+ handles.append(handle)
+ self.assertIsInstance(await handle, bash_module.BashSnapshot)
+ for handle in handles:
+ handle.kill(grace=0.1)
+ self.assertEqual(hints.getvalue().count("still running after"), 3)
+
+
async def _poll_group_dead(pgid: int, timeout: float = 5.0) -> None:
deadline = asyncio.get_running_loop().time() + timeout
while asyncio.get_running_loop().time() < deadline:
diff --git a/prime-agent-runtime/test/test_repl.py b/prime-agent-runtime/test/test_repl.py
index cce4c88470..a1bbe8e5a6 100644
--- a/prime-agent-runtime/test/test_repl.py
+++ b/prime-agent-runtime/test/test_repl.py
@@ -515,6 +515,28 @@ class ReplTest(unittest.TestCase):
time.sleep(1.6)
self.assertFalse(os.path.exists(marker))
+ def test_interrupted_await_inside_bounded_window_still_kills(self):
+ # The bounded wait observes an interrupt instead of abandoning on it:
+ # inside the window the owned await keeps its kill-on-cancel contract.
+ with tempfile.TemporaryDirectory() as tmp:
+ marker = os.path.join(tmp, "marker")
+ code = "\n".join(
+ [
+ "import rlm",
+ "rlm._set_completion_notices_wired(True)",
+ "from rlm import bash",
+ f"r = await bash('sleep 1.5 && touch {marker}', yield_after=3)",
+ ]
+ )
+ self.repl.send({"type": "execute", "id": "ibash-bounded", "code": code})
+ time.sleep(0.4)
+ self.repl.send({"type": "interrupt"})
+ events = self.repl.until_done("ibash-bounded")
+ self.assertEqual(one(events, "error")["ename"], "KeyboardInterrupt")
+ self.assertEqual(one(events, "done")["status"], "error")
+ time.sleep(1.6)
+ self.assertFalse(os.path.exists(marker))
+
def _interrupt_after_running(self, rid: str, code: str) -> list[dict]:
self.repl.send({"type": "execute", "id": rid, "code": code})
# Give the cell time to enter its blocking region before interrupting.
@@ -1154,6 +1176,34 @@ class ReplTest(unittest.TestCase):
inspected = self.repl.execute("bash-inspect", "handle.poll().output")
self.assertIn("detached", one(inspected, "result")["text"])
+ def test_degraded_await_in_creating_cell_still_sends_bash_completion(self):
+ # A bounded await that degrades inside the creating cell must count as
+ # neither awaited nor consumed, or the [bash-done] notice (the only
+ # wake-up) would never fire.
+ code = "\n".join(
+ [
+ "import rlm",
+ "rlm._set_completion_notices_wired(True)",
+ "from rlm import bash",
+ "handle = bash('sleep 0.6; printf degraded', yield_after=0.3)",
+ "await handle",
+ "handle.pid",
+ ]
+ )
+ events = self.repl.execute("bash-degrade", code)
+ pid = int(one(events, "result")["text"])
+ request = wait_for_host_request(self.repl, events)
+ self.assertEqual(
+ request["data"],
+ {
+ "type": "bash.completed",
+ "pid": pid,
+ "command": "sleep 0.6; printf degraded",
+ "exitCode": 0,
+ },
+ )
+ reply_ok(self.repl, request)
+
def test_result_read_after_notice_requests_one_withdrawal(self):
reads = (
("poll", "handle.poll().output"),