Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(agent): deliver background task results to the active session

Steven Enamakel6bf1bd808518
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index 7d628a5915..49e50663d4 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@ -129,9 +129,7 @@ fn drain_schedule(event: &DomainEvent) -> Option<(String, Duration)> {
match background_completions::thread_for_session(session) {
Some(thread_id) => Some((thread_id, delay)),
None => {
- log::trace!(
- "[background_delivery] session has no delivery thread; not scheduling session={session}"
- );
+ log::trace!("[background_delivery] session has no delivery thread; not scheduling");
None
}
}
@@ -150,20 +148,19 @@ fn schedule_delivery(thread_id: String, delay: Duration) {
/// after [`RECOVERY_DELAY`], through the normal idle-gated path. Returns the
/// number of threads scheduled.
pub(crate) fn recover_on_boot(workspace_dir: &Path) -> usize {
+ // Scheduling needs a runtime; check before claiming so a later call retries.
+ if tokio::runtime::Handle::try_current().is_err() {
+ log::warn!(
+ "[background_delivery] no async runtime for boot recovery; will retry on the next call"
+ );
+ return 0;
+ }
// Once per workspace per process: the bootstrap workspace at startup, any
// other the first time a spawn opens it.
if !background_completions::claim_recovery(workspace_dir) {
return 0;
}
let threads = background_completions::recover_pending_threads(workspace_dir);
- let Ok(_runtime) = tokio::runtime::Handle::try_current() else {
- log::warn!(
- "[background_delivery] no async runtime at boot; {} thread(s) with undelivered \
- completions will deliver on their next subagent event",
- threads.len()
- );
- return 0;
- };
for thread_id in &threads {
log::info!(
"[background_delivery] scheduling redelivery of undelivered completions after restart \
@@ -270,6 +267,17 @@ async fn try_deliver_with<F, Fut, G, GFut>(
if let Some(batch) = claim_ready(&router, &thread_id) {
let task_ids: Vec<String> = batch.iter().map(|c| c.task_id.clone()).collect();
slot.hold(&task_ids);
+ // A user turn can start between the idle check inside `claim_ready` and
+ // the awaited turn below; re-check so a system turn is never streamed
+ // concurrently with it. Dropping the slot releases the lease (the claim
+ // already counted one attempt; this window is narrow).
+ if is_busy(&thread_id) {
+ log::debug!(
+ "[background_delivery] thread became busy after the claim; deferring \
+ thread_id={thread_id}"
+ );
+ return;
+ }
let notice = router.formatter().format_batch(&batch);
log::info!(
"[background_delivery] delivering {} batched background result(s) thread_id={thread_id}",
diff --git a/crates/openhuman-core/src/agent/orchestration/completion_notice.rs b/crates/openhuman-core/src/agent/orchestration/completion_notice.rs
index 20bbc16691..c65e23a9f2 100644
--- a/crates/openhuman-core/src/agent/orchestration/completion_notice.rs
+++ b/crates/openhuman-core/src/agent/orchestration/completion_notice.rs
@@ -20,7 +20,8 @@ const MAX_PERSISTED_ERROR_CHARS: usize = 500;
/// such instead of being dropped or mistaken for a success (#4896).
///
/// The harness record carries a [`CompletionStatus`]; the host's three-way
-/// outcome rides on it as `Success` / `Failed` / `Incomplete`.
+/// outcome rides on it as `Success` / `Failed` / `Incomplete` plus the
+/// [`AWAITING_INPUT_LABEL`] label.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum BackgroundAgentOutcome {
/// Ran to a usable result (or partial progress framed as such).
@@ -42,16 +43,25 @@ impl BackgroundAgentOutcome {
}
}
- /// The outcome a stored record renders as.
- pub(crate) fn from_status(status: CompletionStatus) -> Self {
- match status {
+ /// The outcome a stored record renders as. `Incomplete` is the harness's
+ /// word for several things (a timeout, an exhausted budget), so a record
+ /// counts as awaiting input only when the host labelled it so.
+ pub(crate) fn of(record: &CompletionRecord) -> Self {
+ match record.status {
CompletionStatus::Success => Self::Completed,
- CompletionStatus::Incomplete => Self::AwaitingInput,
- CompletionStatus::Failed | CompletionStatus::Cancelled => Self::Failed,
+ CompletionStatus::Incomplete if record.label.as_deref() == Some(AWAITING_INPUT_LABEL) => {
+ Self::AwaitingInput
+ }
+ CompletionStatus::Incomplete | CompletionStatus::Failed | CompletionStatus::Cancelled => {
+ Self::Failed
+ }
}
}
}
+/// The record label the host stamps on an awaiting-input pause.
+pub(crate) const AWAITING_INPUT_LABEL: &str = "awaiting_input";
+
/// Renders a batch of finished background sub-agents as the single
/// system-injected notice the parent agent reviews.
#[derive(Clone, Copy, Debug, Default)]
@@ -104,6 +114,16 @@ fn neutralize_envelope_markers(summary: &str) -> String {
.replace("<background_agent_", "&lt;background_agent_")
}
+/// Escape a value placed inside a quoted envelope attribute, so an identifier
+/// containing a quote or a tag cannot end the opening tag and forge markup.
+fn escape_attribute(value: &str) -> String {
+ value
+ .replace('&', "&amp;")
+ .replace('"', "&quot;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
+}
+
/// Render each result with its outcome-specific tag. Shared by the normal
/// delivery notice and by the undelivered fallback, so a result reads the same
/// either way and a failure is never dressed up as a completion.
@@ -112,7 +132,7 @@ fn render_results(records: &[CompletionRecord]) -> String {
for record in records {
// Distinct tag per terminal outcome so a failure / awaiting-input result
// is not presented as a normal completion (#4896).
- let (tag, empty_fallback) = match BackgroundAgentOutcome::from_status(record.status) {
+ let (tag, empty_fallback) = match BackgroundAgentOutcome::of(record) {
BackgroundAgentOutcome::Completed => {
("background_agent_result", "(no output reported)")
}
@@ -133,7 +153,9 @@ fn render_results(records: &[CompletionRecord]) -> String {
};
out.push_str(&format!(
"\n<{tag} id=\"{}\" agent=\"{}\">\n{}\n</{tag}>\n",
- record.task_id, record.agent_id, summary,
+ escape_attribute(&record.task_id),
+ escape_attribute(&record.agent_id),
+ summary,
));
}
out