Skip to content

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

chore: files changed crates/openhuman-core/src/channels/runtime/dispatch/native_runner.rs,crates/ope

Steven Enamakel3724d87b2933
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/native_runner.rs b/crates/openhuman-core/src/channels/runtime/dispatch/native_runner.rs
index ce4d384354..e51a5a0cd0 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/native_runner.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/native_runner.rs
@@ -9,9 +9,9 @@ use async_trait::async_trait;
use tinyagents_harness::{
run_queue::RunQueue,
turn_runner::{
- EventSink, FailureClassifier, IngressDecision, IngressPolicy, IngressStage,
- QueueDisposition, ReplyStore, ScopeKey, Summarizer, TerminalEvent, TurnHost, TurnRequest,
- TurnResult, TurnRunner, TurnRunnerConfig, TurnSession, TurnSignal,
+ EventSink, FailureClassification, FailureClassifier, IngressDecision, IngressPolicy,
+ IngressStage, QueueDisposition, ReplyStore, ScopeKey, Summarizer, TerminalEvent, TurnHost,
+ TurnRequest, TurnResult, TurnRunner, TurnRunnerConfig, TurnSession, TurnSignal,
},
CancellationToken,
};
@@ -43,6 +43,8 @@ struct NativeSlot {
progress_failed: bool,
waiting_for_delivery: bool,
delivery_succeeded: Option<bool>,
+ #[cfg(test)]
+ failure_message: Option<String>,
}
#[derive(Default)]
@@ -320,6 +322,23 @@ struct NativeEvents {
shared: Arc<NativeShared>,
}
+fn render_classified_native_failure(
+ config: Option<&crate::config::Config>,
+ fallback: &str,
+ classification: &FailureClassification,
+) -> String {
+ config.map_or_else(
+ || fallback.to_owned(),
+ |config| {
+ config.render_native_channel_failure(
+ fallback,
+ classification.copy_key.as_deref(),
+ classification.copy_params.as_ref(),
+ )
+ },
+ )
+}
+
#[async_trait]
impl EventSink<QueuedPayload> for NativeEvents {
async fn progress(
@@ -384,6 +403,47 @@ impl EventSink<QueuedPayload> for NativeEvents {
};
self.shared.record_delivery(&request.request_id, delivered);
}
+
+ async fn classified_failure(
+ &self,
+ request: &TurnRequest<QueuedPayload>,
+ event: TerminalEvent,
+ classification: FailureClassification,
+ ) {
+ let event = match event {
+ TerminalEvent::Failed {
+ request_id,
+ message,
+ class,
+ error,
+ } => {
+ let fallback = if classification.message.is_empty() {
+ message
+ } else {
+ classification.message.clone()
+ };
+ let config = if let Some(ctx) = request.payload.ctx.as_ref() {
+ ctx.load_config().await.ok()
+ } else {
+ None
+ };
+ let localized =
+ render_classified_native_failure(config.as_ref(), &fallback, &classification);
+ #[cfg(test)]
+ self.shared.with(&request.request_id, |slot| {
+ slot.failure_message = Some(localized.clone());
+ });
+ TerminalEvent::Failed {
+ request_id,
+ message: localized,
+ class,
+ error,
+ }
+ }
+ other => other,
+ };
+ self.terminal(request, event).await;
+ }
}
struct NativeFailures;
@@ -393,6 +453,16 @@ impl FailureClassifier for NativeFailures {
let classified = crate::web_chat::classify_inference_error(error);
(classified.error_type.to_owned(), classified.message)
}
+
+ fn classify_failure(&self, error: &str) -> FailureClassification {
+ let classified = crate::web_chat::classify_inference_error(error);
+ FailureClassification {
+ class: classified.error_type.to_owned(),
+ message: classified.message,
+ copy_key: Some(classified.copy_key.to_owned()),
+ copy_params: classified.copy_params,
+ }
+ }
}
struct NativeSummarizer;
@@ -413,10 +483,17 @@ impl Summarizer<QueuedPayload> for NativeSummarizer {
let deadline = request.deadline.unwrap_or_default();
crate::web_chat::turn_timeout_error_message(deadline.as_secs())
};
- let (failure_type, message) = NativeFailures.classify(&error);
+ let classified = NativeFailures.classify_failure(&error);
+ let config = if let Some(ctx) = request.payload.ctx.as_ref() {
+ ctx.load_config().await.ok()
+ } else {
+ None
+ };
+ let message =
+ render_classified_native_failure(config.as_ref(), &classified.message, &classified);
Some(TurnResult {
reply: message,
- data: serde_json::json!({"failure_type": failure_type}),
+ data: serde_json::json!({"failure_type": classified.class}),
})
}
}
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/native_runner_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/native_runner_tests.rs
index bc67e43668..a52aafca53 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/native_runner_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/native_runner_tests.rs
@@ -1,5 +1,129 @@
use super::*;
+#[test]
+fn native_failure_classifier_preserves_localizable_error_metadata() {
+ let failure = NativeFailures.classify_failure("429 Too Many Requests: Retry-After: 12");
+
+ assert_eq!(failure.class, "rate_limited");
+ assert_eq!(failure.copy_key.as_deref(), Some("chat_error.rate_limited"));
+ assert_eq!(
+ failure
+ .copy_params
+ .as_ref()
+ .and_then(|params| params.get("retry_after_secs")),
+ Some(&serde_json::json!(12))
+ );
+}
+
+#[test]
+fn native_failure_event_copy_uses_configured_locale_and_keeps_queued_context() {
+ let mut config = crate::config::Config::default();
+ config.channels_locale = Some("zh-CN".to_owned());
+ let failure = FailureClassification {
+ class: "rate_limited".to_owned(),
+ message: "queued turn was not run: Your AI provider is rate-limiting requests. Retry in 12 seconds.".to_owned(),
+ copy_key: Some("chat_error.rate_limited".to_owned()),
+ copy_params: Some(serde_json::json!({"retry_after_secs": 12})),
+ };
+
+ let rendered = render_classified_native_failure(Some(&config), &failure.message, &failure);
+
+ assert!(rendered.starts_with("queued turn was not run: "));
+ assert!(rendered.contains("你的 AI 提供商"));
+ assert!(rendered.contains("12"));
+ assert!(!rendered.contains("Your AI provider"));
+}
+
+#[tokio::test]
+async fn native_sink_uses_dispatch_locale_and_rejects_unknown_copy_metadata() {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};
+
+ async fn delivered_message(
+ config: crate::config::Config,
+ request_id: &str,
+ failure: FailureClassification,
+ ) -> String {
+ let profile = format!("native-locale-{request_id}");
+ let core = CoreContext::for_test(DomainSet::full(), None).derive_with(
+ ContextOverlay::new(config, DomainSet::full(), Default::default())
+ .profile(profile.clone()),
+ );
+ let dispatch = DispatchCtx::new(core);
+ let shared = Arc::new(NativeShared::default());
+ shared.begin_delivery_wait(request_id);
+ let request = TurnRequest {
+ scope: ScopeKey {
+ agent_id: "orchestrator".into(),
+ profile_id: Some(profile),
+ },
+ thread_id: format!("thread-{request_id}"),
+ request_id: request_id.into(),
+ text: "hello".into(),
+ payload: QueuedPayload {
+ ctx: Some(dispatch),
+ ..Default::default()
+ },
+ host_authored: false,
+ disposition: QueueDisposition::Followup,
+ deadline: None,
+ idle_timeout: None,
+ };
+ NativeEvents {
+ shared: Arc::clone(&shared),
+ }
+ .classified_failure(
+ &request,
+ TerminalEvent::Failed {
+ request_id: request_id.into(),
+ message: "stale message".into(),
+ class: failure.class.clone(),
+ error: "classifier input".into(),
+ },
+ failure,
+ )
+ .await;
+ shared
+ .with(request_id, |slot| slot.failure_message.clone())
+ .expect("native sink captures its rendered terminal copy")
+ }
+
+ let mut spanish = crate::config::Config::default();
+ spanish.channels_locale = Some("es".into());
+ let translated = delivered_message(
+ spanish,
+ "spanish",
+ FailureClassification {
+ class: "rate_limited".into(),
+ message: "queued turn was not run: English rate limit copy".into(),
+ copy_key: Some("chat_error.rate_limited".into()),
+ copy_params: Some(serde_json::json!({"retry_after_secs": 12})),
+ },
+ )
+ .await;
+ assert!(translated.starts_with("queued turn was not run: "));
+ assert!(translated.contains("Tu proveedor de IA"));
+ assert!(translated.contains("12"));
+ assert!(!translated.contains("English rate limit copy"));
+
+ let mut unsupported = crate::config::Config::default();
+ unsupported.channels_locale = Some("ar-EG".into());
+ let fallback = delivered_message(
+ unsupported,
+ "fallback",
+ FailureClassification {
+ class: "future_class".into(),
+ message: "safe English fallback".into(),
+ copy_key: Some("chat_error.unrecognized".into()),
+ copy_params: Some(serde_json::json!({
+ "retry_after_secs": {"unexpected": "secret"},
+ "detail": ["untrusted"]
+ })),
+ },
+ )
+ .await;
+ assert_eq!(fallback, "safe English fallback");
+}
+
#[tokio::test]
async fn queued_terminal_delivery_does_not_leave_a_completion_entry() {
let shared = NativeShared::default();
diff --git a/crates/openhuman-core/src/inference/failure_copy/localized.rs b/crates/openhuman-core/src/inference/failure_copy/localized.rs
index 72dbf60f7b..a25c774104 100644
--- a/crates/openhuman-core/src/inference/failure_copy/localized.rs
+++ b/crates/openhuman-core/src/inference/failure_copy/localized.rs
@@ -2,6 +2,8 @@
use serde_json::Value;
+use super::chat_error_catalog;
+
const QUEUED_FAILURE_PREFIX: &str = "queued turn was not run: ";
pub(crate) fn supported_channel_locale(locale: Option<&str>) -> Option<&'static str> {
diff --git a/crates/openhuman-core/src/web_chat/turn_events.rs b/crates/openhuman-core/src/web_chat/turn_events.rs
index 5f04c1a24f..17c3d1bda5 100644
--- a/crates/openhuman-core/src/web_chat/turn_events.rs
+++ b/crates/openhuman-core/src/web_chat/turn_events.rs
@@ -13,7 +13,8 @@ use std::time::Duration;
use async_trait::async_trait;
use tinyagents_harness::progress::AgentProgress;
use tinyagents_harness::turn_runner::{
- EventSink, FailureClassifier, ReplyStore, Summarizer, TerminalEvent, TurnRequest, TurnResult,
+ EventSink, FailureClassification, FailureClassifier, ReplyStore, Summarizer, TerminalEvent,
+ TurnRequest, TurnResult,
};
use tinychannels_bus::web as bus_web;
@@ -102,6 +103,16 @@ impl FailureClassifier for WebFailures {
let classified = classify_inference_error(&host_error(error, None));
(classified.error_type.to_owned(), classified.message)
}
+
+ fn classify_failure(&self, error: &str) -> FailureClassification {
+ let classified = classify_inference_error(&host_error(error, None));
+ FailureClassification {
+ class: classified.error_type.to_owned(),
+ message: classified.message,
+ copy_key: Some(classified.copy_key.to_owned()),
+ copy_params: classified.copy_params,
+ }
+ }
}
/// Stores the reply a turn finished with before it is announced (#6034): once
@@ -278,7 +289,13 @@ impl WebEvents {
}
}
- async fn failed(&self, request: &TurnRequest<QueuedPayload>, surface: &Surface, error: &str) {
+ async fn failed(
+ &self,
+ request: &TurnRequest<QueuedPayload>,
+ surface: &Surface,
+ error: &str,
+ structured: Option<&FailureClassification>,
+ ) {
#[cfg(test)]
super::ops::set_last_run_chat_task_error_for_test(Some(error)).await;
let parallel =
@@ -300,7 +317,7 @@ impl WebEvents {
let classified = classify_inference_error(&raw);
report_failure(&detailed, &classified, parallel, request);
surface
- .event(chat_error_event(surface.context(), classified))
+ .event(chat_error_event(surface.context(), classified, structured))
.await;
}
@@ -394,18 +411,28 @@ fn report_failure(
fn chat_error_event(
context: bus_web::WebEventContext,
classified: ClassifiedError,
+ structured: Option<&FailureClassification>,
) -> bus_web::WebChannelEvent {
bus_web::WebChannelEvent::ChatError {
context,
- message: Some(classified.message),
+ message: Some(
+ structured
+ .map(|failure| failure.message.clone())
+ .unwrap_or(classified.message),
+ ),
error_type: Some(classified.error_type.to_owned()),
error_source: Some(classified.source.to_owned()),
error_retryable: Some(classified.retryable),
error_retry_after_ms: classified.retry_after_ms,
error_provider: classified.provider,
error_fallback_available: classified.fallback_available,
- copy_key: Some(classified.copy_key.to_owned()),
- copy_params: classified.copy_params,
+ copy_key: structured.map_or_else(
+ || Some(classified.copy_key.to_owned()),
+ |failure| failure.copy_key.clone(),
+ ),
+ copy_params: structured.map_or(classified.copy_params, |failure| {
+ failure.copy_params.clone()
+ }),
guardrail: None,
}
}
@@ -422,47 +449,18 @@ impl EventSink<QueuedPayload> for WebEvents {
}
async fn terminal(&self, request: &TurnRequest<QueuedPayload>, event: TerminalEvent) {
- let slot = self.shared.take(&request.request_id);
- // A message that waited in a run queue and never started was never
- // announced as a turn, so its being dropped is silent too.
- let never_started = self.shared.was_queued(&request.request_id);
- let (projection, done, note, _session_lease, _profile_turn) = match slot {
- Some(slot) => (
- slot.projection,
- slot.result,
- slot.cancel,
- slot.session_lease,
- slot.profile_turn,
- ),
- None => (None, None, None, None, None),
- };
- if never_started && !matches!(event, TerminalEvent::Completed { .. }) {
- log::debug!(
- "[web-channel] queued message dropped before it started thread_id={} request_id={}",
- request.thread_id,
- request.request_id
- );
- return;
- }
- if let Some(surface) = self.surface_of(request, &projection).await {
- match event {
- TerminalEvent::Completed { .. } => self.completed(request, &surface, done).await,
- TerminalEvent::Failed { error, .. } => {
- self.failed(request, &surface, &error).await;
- }
- TerminalEvent::Cancelled { .. } => {
- self.cancelled(request, &surface, note.unwrap_or_default())
- .await;
- }
- }
- }
- // The projection's trace export is best-effort I/O and must not hold
- // up terminal delivery.
- if let (Some(projection), Some(ctx)) = (projection, request.payload.ctx.clone()) {
- ctx.spawn(async move {
- projection.lock().await.finish().await;
- });
- }
+ self.terminal_with_classification(request, event, None)
+ .await;
+ }
+
+ async fn classified_failure(
+ &self,
+ request: &TurnRequest<QueuedPayload>,
+ event: TerminalEvent,
+ classification: FailureClassification,
+ ) {
+ self.terminal_with_classification(request, event, Some(classification))
+ .await;
}
async fn collected(
@@ -511,6 +509,58 @@ impl EventSink<QueuedPayload> for WebEvents {
}
}
+impl WebEvents {
+ async fn terminal_with_classification(
+ &self,
+ request: &TurnRequest<QueuedPayload>,
+ event: TerminalEvent,
+ classification: Option<FailureClassification>,
+ ) {
+ let slot = self.shared.take(&request.request_id);
+ // A message that waited in a run queue and never started was never
+ // announced as a turn, so its being dropped is silent too.
+ let never_started = self.shared.was_queued(&request.request_id);
+ let (projection, done, note, _session_lease, _profile_turn) = match slot {
+ Some(slot) => (
+ slot.projection,
+ slot.result,
+ slot.cancel,
+ slot.session_lease,
+ slot.profile_turn,
+ ),
+ None => (None, None, None, None, None),
+ };
+ if never_started && !matches!(event, TerminalEvent::Completed { .. }) {
+ log::debug!(
+ "[web-channel] queued message dropped before it started thread_id={} request_id={}",
+ request.thread_id,
+ request.request_id
+ );
+ return;
+ }
+ if let Some(surface) = self.surface_of(request, &projection).await {
+ match event {
+ TerminalEvent::Completed { .. } => self.completed(request, &surface, done).await,
+ TerminalEvent::Failed { error, .. } => {
+ self.failed(request, &surface, &error, classification.as_ref())
+ .await;
+ }
+ TerminalEvent::Cancelled { .. } => {
+ self.cancelled(request, &surface, note.unwrap_or_default())
+ .await;
+ }
+ }
+ }
+ // The projection's trace export is best-effort I/O and must not hold
+ // up terminal delivery.
+ if let (Some(projection), Some(ctx)) = (projection, request.payload.ctx.clone()) {
+ ctx.spawn(async move {
+ projection.lock().await.finish().await;
+ });
+ }
+ }
+}
+
#[cfg(test)]
#[path = "turn_events_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/web_chat/turn_events_tests.rs b/crates/openhuman-core/src/web_chat/turn_events_tests.rs
index 22bf33ab71..f94b2cff49 100644
--- a/crates/openhuman-core/src/web_chat/turn_events_tests.rs
+++ b/crates/openhuman-core/src/web_chat/turn_events_tests.rs
@@ -73,6 +73,20 @@ fn the_runners_guard_failures_classify_as_a_graceful_turn_timeout() {
assert_ne!(class, "turn_timeout");
}
+#[test]
+fn web_runner_classifier_keeps_structured_copy_metadata() {
+ let failure = WebFailures.classify_failure("429 Too Many Requests: Retry-After: 12");
+ assert_eq!(failure.class, "rate_limited");
+ assert_eq!(failure.copy_key.as_deref(), Some("chat_error.rate_limited"));
+ assert_eq!(
+ failure
+ .copy_params
+ .as_ref()
+ .and_then(|params| params.get("retry_after_secs")),
+ Some(&serde_json::json!(12))
+ );
+}
+
#[test]
fn a_guard_failure_reports_the_window_that_fired() {
let req = request("window", QueueDisposition::Interrupt);
@@ -137,6 +151,38 @@ async fn a_failed_turn_announces_a_classified_chat_error() {
} if error_type == "turn_timeout"));
}
+#[tokio::test]
+async fn classified_failure_event_preserves_runner_copy_and_queued_prefix() {
+ let mut rx = crate::web_chat::subscribe_web_channel_events();
+ let (_shared, sink) = events();
+ let req = request("events-structured-failure", QueueDisposition::Followup);
+ let classification = FailureClassification {
+ class: "auth_error".into(),
+ message: "queued turn was not run: localized by the runner".into(),
+ copy_key: Some("chat_error.auth_error".into()),
+ copy_params: Some(serde_json::json!({"detail": "sanitized detail"})),
+ };
+
+ sink.classified_failure(
+ &req,
+ TerminalEvent::Failed {
+ request_id: req.request_id.clone(),
+ message: "stale classifier message".into(),
+ class: "rate_limited".into(),
+ error: "429 Too Many Requests: Retry-After: 12".into(),
+ },
+ classification,
+ )
+ .await;
+
+ let error = events_for(&mut rx, &req.request_id, 1).await.remove(0);
+ assert!(matches!(error.wire_event(), WebChannelEvent::ChatError {
+ message: Some(message), copy_key: Some(copy_key), copy_params: Some(params), ..
+ } if message == "queued turn was not run: localized by the runner"
+ && copy_key == "chat_error.auth_error"
+ && params["detail"] == "sanitized detail"));
+}
+
#[tokio::test]
async fn a_stopped_turn_announces_cancelled_to_the_client_that_stopped_it() {
let mut rx = crate::web_chat::subscribe_web_channel_events();
diff --git a/scripts/generate-rust-chat-error-catalog.ts b/scripts/generate-rust-chat-error-catalog.ts
index 3f5a0a204b..f81ccd4734 100644
--- a/scripts/generate-rust-chat-error-catalog.ts
+++ b/scripts/generate-rust-chat-error-catalog.ts
@@ -2,6 +2,7 @@
/** Generate the Rust chat-error catalog from the canonical frontend i18n maps. */
import { readFile, writeFile } from "node:fs/promises";
+import { execFileSync } from "node:child_process";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
@@ -84,13 +85,17 @@ async function renderCatalog(): Promise<string> {
` (${rustString(locale)}, ${rustString(key)}) => Some(${rustString(translated)}),`,
)
.join("\n");
- return `// Generated by scripts/generate-rust-chat-error-catalog.ts; do not edit.\n\
+ const source = `// Generated by scripts/generate-rust-chat-error-catalog.ts; do not edit.\n\
pub const SUPPORTED_LOCALES: &[&str] = &[\n${localeRows}\n];\n\
pub fn translation(locale: &str, key: &str) -> Option<&'static str> {\n\
match (locale, key) {\n${translationRows}\n\
_ => None,\n\
}\n\
}\n`;
+ return execFileSync("rustfmt", ["--edition", "2021", "--emit", "stdout"], {
+ input: source,
+ encoding: "utf8",
+ });
}
async function main() {