Skip to content

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

merge: integrate local main into epic 8088 headless branch

Steven Enamakel448a0cf003bf
diff --cc Cargo.lock
index f65f69d9d9,e00726f0e9..cb37cb28c4
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -5562,10 -5549,12 +5551,12 @@@ dependencies =
"tinyinference-local",
"tinyinference-voice",
"tinymcp-bus",
+ "tinymemory-tools",
"tinysearch-bus",
+ "tinystoragedrivers",
"tinystoragedrivers-core",
- "tinytools",
- "tinytools-agent",
+ "tinytools 0.6.0",
+ "tinytools-agent 0.6.0",
"tinytools-std",
"tokio",
"tokio-stream",
@@@ -9233,9 -9235,13 +9254,13 @@@ dependencies =
"tinybus-module",
"tinyflows",
"tinyflows-bus",
+ "tinyflows-catalog",
+ "tinyflows-copilot",
"tinyflows-drivers",
+ "tinyflows-import",
"tinyflows-schedule",
"tinystoragedrivers-core",
- "tinytools",
++ "tinytools 0.6.0",
"tokio",
"tracing",
"uuid",
diff --cc Cargo.toml
index bf5ba95022,11fed53906..42cb97601c
--- a/Cargo.toml
+++ b/Cargo.toml
@@@ -43,8 -43,7 +43,8 @@@ repository = "https://github.com/tinyhu
openhuman-rpc = { path = "crates/openhuman-rpc", default-features = false }
openhuman-embed = { path = "crates/openhuman-embed", default-features = false }
openhuman-tinyhumans = { path = "crates/openhuman-tinyhumans", default-features = false }
- tinyagents-hooks = { path = "vendor/tinyagents/crates/tinyagents-hooks" }
+ tinyagents-hooks = { path = "vendor/tinyagents/crates/tinyagents-hooks", default-features = false }
+tinyagents-harness-tools = { path = "vendor/tinyagents/crates/tinyagents-harness-tools", default-features = false }
# Patches are workspace-root settings; Cargo ignores them in member manifests.
[patch."https://github.com/tinyhumansai/tinytools"]
diff --cc app/src/store/chatRuntimeSlice.ts
index 77ded06305,ca4b043d0e..24bb9460f5
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@@ -69,9 -69,27 +69,10 @@@ export function isActiveTimelineStatus(
return status === 'running' || status === 'awaiting_user';
}
-/**
- * Every `subagent:*` timeline row spawned by one `spawn_parallel_agents` tool
- * call — the workers sharing `subagent.parentCallId === parentCallId` (see
- * {@link SubagentActivity.parentCallId}) — in the order they were issued
- * (`seq`). Used by `ParallelAgentsCard` (`features/conversations/aui/
- * ParallelAgentsCard.tsx`) to render the vendored `SubagentList` above the
- * per-child `TaskCard` rows for a `spawn_parallel_agents` call.
- */
-export function selectSubagentChildrenByParentCallId(
- timeline: ToolTimelineEntry[],
- parentCallId: string
-): ToolTimelineEntry[] {
- return timeline
- .filter(entry => entry.subagent?.parentCallId === parentCallId)
- .sort((a, b) => a.seq - b.seq);
-}
-
/** Live progress of the running turn, as the socket handlers maintain it. */
export interface InferenceStatus {
- phase: 'thinking' | 'tool_use' | 'subagent';
+ /** `compacting`: summarizing earlier conversation before the next model call. */
+ phase: 'thinking' | 'compacting' | 'tool_use' | 'subagent';
iteration: number;
maxIterations: number;
activeTool?: string;
diff --cc crates/openhuman-app/Cargo.lock
index 92ccd7fc7b,c0833a9e95..a418025f85
--- a/crates/openhuman-app/Cargo.lock
+++ b/crates/openhuman-app/Cargo.lock
@@@ -6845,7 -6650,7 +6668,7 @@@ dependencies =
[[package]]
name = "tinychannels-bus"
--version = "0.1.36"
++version = "0.1.38"
dependencies = [
"anyhow",
"async-trait",
diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rs
index 7a28c0ca82,42dc14980c..104aa4ff5a
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rs
@@@ -104,66 -104,80 +104,82 @@@ pub fn upsert_running
let _guard = store_write_lock()
.lock()
.map_err(|_| "subagent session store lock poisoned".to_string())?;
+ if let Some(reuse) = reuse {
+ let selector = upsert.selector.clone();
+ let worker_thread_id = upsert.worker_thread_id.clone();
+ let display_name = upsert.display_name.clone();
+ let task_id = upsert.task_id.clone();
+ let lifecycle_key = upsert.lifecycle_key.clone();
+ let expected_task_id = reuse.current_task_id.clone();
+ let expected_lifecycle_key = reuse.lifecycle_key.clone();
+ if let Some(updated) =
+ store.update_session_if(&reuse.subagent_session_id, move |session, now| {
+ if session.status == DurableSubagentStatus::Closed
+ || session.current_task_id != expected_task_id
+ || session.lifecycle_key != expected_lifecycle_key
+ || !session.matches_selector(&selector)
+ {
+ return false;
+ }
+ session.parent_session = selector.parent_session.clone();
+ session.parent_thread_id = selector.parent_thread_id.clone();
+ session.worker_thread_id = worker_thread_id
+ .clone()
+ .or_else(|| session.worker_thread_id.clone());
+ session.display_name = display_name
+ .clone()
+ .or_else(|| session.display_name.clone());
+ session.current_task_id = Some(task_id.clone());
+ if let Some(lifecycle_key) = &lifecycle_key {
+ session.lifecycle_key = Some(lifecycle_key.clone());
+ }
++ session.parent_epoch = upsert.parent_epoch;
+ session.status = DurableSubagentStatus::Running;
+ session.reusable = true;
+ session.latest_error = None;
+ session.updated_at = now.clone();
+ session.last_used_at = now;
+ true
+ })?
+ {
+ return Ok(updated);
+ }
+ if store
+ .load()?
+ .iter()
+ .any(|session| session.subagent_session_id == reuse.subagent_session_id)
+ {
+ return Err("stale reusable sub-agent session changed during upsert".into());
+ }
+ }
let mut sessions = store.load()?;
let now = chrono::Utc::now().to_rfc3339();
- let session_id = reuse
- .map(|session| session.subagent_session_id.clone())
- .unwrap_or_else(|| format!("subsess-{}", uuid::Uuid::new_v4()));
+ let session_id = format!("subsess-{}", uuid::Uuid::new_v4());
- let mut session = if let Some(existing) = sessions
- .iter()
- .find(|session| session.subagent_session_id == session_id)
- .cloned()
- {
- if let Some(reuse) = reuse {
- if existing.status == DurableSubagentStatus::Closed
- || existing.current_task_id != reuse.current_task_id
- || existing.lifecycle_key != reuse.lifecycle_key
- {
- return Err("stale reusable sub-agent session changed during upsert".into());
- }
- }
- existing
- } else {
- DurableSubagentSession {
- subagent_session_id: session_id.clone(),
- parent_session: upsert.selector.parent_session.clone(),
- parent_thread_id: upsert.selector.parent_thread_id.clone(),
- worker_thread_id: upsert.worker_thread_id.clone(),
- agent_id: upsert.selector.agent_id.clone(),
- display_name: upsert.display_name.clone(),
- model: upsert.selector.model.clone(),
- sandbox_mode: upsert.selector.sandbox_mode.clone(),
- action_root: upsert.selector.action_root.clone(),
- task_key: upsert.selector.task_key.clone(),
- task_title: upsert.task_title.clone(),
- current_task_id: None,
- lifecycle_key: None,
- parent_epoch: None,
- status: DurableSubagentStatus::Running,
- reusable: true,
- latest_history: None,
- latest_error: None,
- created_at: now.clone(),
- updated_at: now.clone(),
- last_used_at: now.clone(),
- }
+ let session = DurableSubagentSession {
+ subagent_session_id: session_id.clone(),
+ parent_session: upsert.selector.parent_session.clone(),
+ parent_thread_id: upsert.selector.parent_thread_id.clone(),
+ worker_thread_id: upsert.worker_thread_id.clone(),
+ agent_id: upsert.selector.agent_id.clone(),
+ display_name: upsert.display_name.clone(),
+ model: upsert.selector.model.clone(),
+ sandbox_mode: upsert.selector.sandbox_mode.clone(),
+ action_root: upsert.selector.action_root.clone(),
+ task_key: upsert.selector.task_key.clone(),
+ task_title: upsert.task_title.clone(),
+ current_task_id: Some(upsert.task_id),
+ lifecycle_key: upsert.lifecycle_key,
++ parent_epoch: upsert.parent_epoch,
+ status: DurableSubagentStatus::Running,
+ reusable: true,
+ latest_history: None,
+ latest_error: None,
+ created_at: now.clone(),
+ updated_at: now.clone(),
+ last_used_at: now.clone(),
};
- session.parent_session = upsert.selector.parent_session;
- session.parent_thread_id = upsert.selector.parent_thread_id;
- session.worker_thread_id = upsert.worker_thread_id.or(session.worker_thread_id);
- session.display_name = upsert.display_name.or(session.display_name);
- session.current_task_id = Some(upsert.task_id);
- session.lifecycle_key = upsert.lifecycle_key.or(session.lifecycle_key);
- // This belongs to the new task, not the reusable session's previous run.
- session.parent_epoch = upsert.parent_epoch;
- session.status = DurableSubagentStatus::Running;
- session.reusable = true;
- session.latest_error = None;
- session.updated_at = now.clone();
- session.last_used_at = now;
-
sessions.retain(|existing| existing.subagent_session_id != session_id);
sessions.push(session.clone());
store.save(&sessions)?;
diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_driver_tests.rs
index 0000000000,32d4a13781..9ec8134bf1
mode 000000,100644..100644
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_driver_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_driver_tests.rs
@@@ -1,0 -1,115 +1,116 @@@
+ use super::*;
+
+ const FIXED_TIMESTAMP: &str = "2026-10-19T12:00:00.000Z";
+
+ fn session(updated_at: &str) -> DurableSubagentSession {
+ DurableSubagentSession {
+ subagent_session_id: "session-1".into(),
+ parent_session: "parent-1".into(),
+ parent_thread_id: Some("thread-1".into()),
++ parent_epoch: None,
+ worker_thread_id: Some("worker-1".into()),
+ agent_id: "researcher".into(),
+ display_name: None,
+ model: Some("model-1".into()),
+ sandbox_mode: "read_only".into(),
+ action_root: None,
+ task_key: "task-key".into(),
+ task_title: "Task title".into(),
+ current_task_id: Some("task-1".into()),
+ lifecycle_key: Some(tinyagents_orchestration::subagent::SubagentTaskKey {
+ root_run_id: "root-1".into(),
+ parent_run_id: "parent-run-1".into(),
+ thread_id: Some("thread-1".into()),
+ task_id: "task-1".into(),
+ }),
+ status: DurableSubagentStatus::Running,
+ reusable: true,
+ latest_history: None,
+ latest_error: None,
+ created_at: updated_at.into(),
+ updated_at: updated_at.into(),
+ last_used_at: updated_at.into(),
+ }
+ }
+
+ #[test]
+ fn observed_mutation_persists_when_the_timestamp_does_not_advance() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = SubagentSessionStore::new(dir.path().to_path_buf());
+ let observed = session(FIXED_TIMESTAMP);
+ store.save(std::slice::from_ref(&observed)).unwrap();
+
+ let updated = mutate_observed_session(&store, &observed, |current, _now| {
+ // This models the equal-millisecond case without sleeping or relying
+ // on clock scheduling: the requested field changes, but its persisted
+ // updated_at remains exactly the stored timestamp.
+ current.latest_error = Some("cancel reason".into());
+ })
+ .unwrap();
+
+ assert!(updated);
+ let persisted = store.load().unwrap().pop().unwrap();
+ assert_eq!(persisted.updated_at, FIXED_TIMESTAMP);
+ assert_eq!(persisted.latest_error.as_deref(), Some("cancel reason"));
+ }
+
+ fn change_parent(session: &mut DurableSubagentSession) {
+ session.parent_session = "replacement-parent".into();
+ }
+
+ fn change_thread(session: &mut DurableSubagentSession) {
+ session.parent_thread_id = Some("replacement-thread".into());
+ }
+
+ fn change_task(session: &mut DurableSubagentSession) {
+ session.current_task_id = Some("replacement-task".into());
+ }
+
+ fn change_lifecycle(session: &mut DurableSubagentSession) {
+ session.lifecycle_key.as_mut().unwrap().root_run_id = "replacement-root".into();
+ }
+
+ fn change_status(session: &mut DurableSubagentSession) {
+ session.status = DurableSubagentStatus::AwaitingUser;
+ }
+
+ #[test]
+ fn observed_mutation_rejects_a_stale_parent_thread_task_lifecycle_or_status() {
+ type SessionChange = fn(&mut DurableSubagentSession);
+ let changes: [(&str, SessionChange); 5] = [
+ ("parent", change_parent),
+ ("thread", change_thread),
+ ("task", change_task),
+ ("lifecycle", change_lifecycle),
+ ("status", change_status),
+ ];
+
+ for (field, change_current) in changes {
+ let dir = tempfile::tempdir().unwrap();
+ let store = SubagentSessionStore::new(dir.path().to_path_buf());
+ let observed = session(FIXED_TIMESTAMP);
+ let mut current = observed.clone();
+ change_current(&mut current);
+ store.save(std::slice::from_ref(&current)).unwrap();
+
+ let closure_called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let closure_marker = std::sync::Arc::clone(&closure_called);
+ let updated = mutate_observed_session(&store, &observed, move |session, _now| {
+ closure_marker.store(true, std::sync::atomic::Ordering::SeqCst);
+ session.latest_error = Some("stale mutation".into());
+ })
+ .unwrap();
+
+ assert!(!updated, "stale {field} must not update the current row");
+ assert!(
+ !closure_called.load(std::sync::atomic::Ordering::SeqCst),
+ "stale {field} must reject before mutation"
+ );
+ let persisted = store.load().unwrap().pop().unwrap();
+ assert_eq!(
+ serde_json::to_value(&persisted).unwrap(),
+ serde_json::to_value(&current).unwrap(),
+ "stale {field} must leave the current row unchanged"
+ );
+ }
+ }
diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_followup_tests.rs
index 0000000000,0000000000..e724a1e46c
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_followup_tests.rs
@@@ -1,0 -1,0 +1,108 @@@
++use super::*;
++
++#[test]
++fn list_for_parent_without_thread_id_does_not_filter_by_thread() {
++ let dir = tempfile::tempdir().unwrap();
++ let store = SubagentSessionStore::new(dir.path().to_path_buf());
++ let first = upsert_running(
++ &store,
++ SubagentSessionUpsert {
++ selector: selector("first"),
++ display_name: None,
++ task_title: "First".into(),
++ worker_thread_id: None,
++ task_id: "sub-1".into(),
++ lifecycle_key: None,
++ parent_epoch: None,
++ },
++ None,
++ )
++ .unwrap();
++
++ let mut second_selector = selector("second");
++ second_selector.parent_thread_id = Some("thread-b".into());
++ let second = upsert_running(
++ &store,
++ SubagentSessionUpsert {
++ selector: second_selector,
++ display_name: None,
++ task_title: "Second".into(),
++ worker_thread_id: None,
++ task_id: "sub-2".into(),
++ lifecycle_key: None,
++ parent_epoch: None,
++ },
++ None,
++ )
++ .unwrap();
++
++ let all = list_for_parent(&store, "parent-a", None).unwrap();
++ assert_eq!(all.len(), 2);
++ assert!(all
++ .iter()
++ .any(|session| session.subagent_session_id == first.subagent_session_id));
++ assert!(all
++ .iter()
++ .any(|session| session.subagent_session_id == second.subagent_session_id));
++
++ let thread_a = list_for_parent(&store, "parent-a", Some("thread-a")).unwrap();
++ assert_eq!(thread_a.len(), 1);
++ assert_eq!(thread_a[0].subagent_session_id, first.subagent_session_id);
++}
++
++#[test]
++fn missing_session_updates_return_errors() {
++ let dir = tempfile::tempdir().unwrap();
++ let store = SubagentSessionStore::new(dir.path().to_path_buf());
++ assert!(mark_finished(
++ &store,
++ "missing",
++ "sub-1",
++ &SubagentRunStatus::Completed,
++ vec![]
++ )
++ .is_err());
++ assert!(mark_failed(&store, "missing", "sub-1", "boom".into()).is_err());
++ assert!(!close(&store, "missing").unwrap());
++}
++
++#[test]
++fn legacy_session_with_toolkit_key_still_loads_and_reuses() {
++ // Sessions persisted before the `toolkit` spawn argument was retired
++ // carry a `toolkit` key. It must be ignored on load, and it must no
++ // longer take part in reuse matching.
++ let dir = tempfile::tempdir().unwrap();
++ let store = SubagentSessionStore::new(dir.path().to_path_buf());
++ let legacy = serde_json::json!([{
++ "subagentSessionId": "subsess-legacy",
++ "parentSession": "parent-a",
++ "parentThreadId": "thread-a",
++ "workerThreadId": null,
++ "agentId": "researcher",
++ "displayName": null,
++ "toolkit": "gmail",
++ "model": "oh-1",
++ "sandboxMode": "read_only",
++ "actionRoot": "/tmp/work",
++ "taskKey": "legacy-task",
++ "taskTitle": "Legacy task",
++ "currentTaskId": null,
++ "status": "idle",
++ "reusable": true,
++ "latestHistory": null,
++ "latestError": null,
++ "createdAt": "2026-01-01T00:00:00Z",
++ "updatedAt": "2026-01-01T00:00:00Z",
++ "lastUsedAt": "2026-01-01T00:00:00Z"
++ }]);
++ let parsed: Vec<DurableSubagentSession> =
++ serde_json::from_value(legacy).expect("legacy toolkit key is ignored");
++ store.save(&parsed).unwrap();
++
++ let sessions = store.load().expect("legacy toolkit key is ignored");
++ assert_eq!(sessions.len(), 1);
++ let reused = find_reusable(&store, &selector("legacy-task"))
++ .unwrap()
++ .expect("legacy session reuses without a toolkit match");
++ assert_eq!(reused.subagent_session_id, "subsess-legacy");
++}
diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_tests.rs
index ff2cbe4ee6,619a063eb1..8910511776
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_tests.rs
@@@ -623,108 -534,156 +629,55 @@@ fn closed_session_is_not_reusable()
}
#[test]
- fn list_for_parent_without_thread_id_does_not_filter_by_thread() {
- let dir = tempfile::tempdir().unwrap();
- let store = SubagentSessionStore::new(dir.path().to_path_buf());
- let first = upsert_running(
- &store,
- SubagentSessionUpsert {
- selector: selector("first"),
- display_name: None,
- task_title: "First".into(),
- worker_thread_id: None,
- task_id: "sub-1".into(),
- lifecycle_key: None,
- parent_epoch: None,
- },
- None,
- )
- .unwrap();
-
- let mut second_selector = selector("second");
- second_selector.parent_thread_id = Some("thread-b".into());
- let second = upsert_running(
- &store,
- SubagentSessionUpsert {
- selector: second_selector,
- display_name: None,
- task_title: "Second".into(),
- worker_thread_id: None,
- task_id: "sub-2".into(),
- lifecycle_key: None,
- parent_epoch: None,
- },
- None,
- )
- .unwrap();
-
- let all = list_for_parent(&store, "parent-a", None).unwrap();
- assert_eq!(all.len(), 2);
- assert!(all
- .iter()
- .any(|session| session.subagent_session_id == first.subagent_session_id));
- assert!(all
- .iter()
- .any(|session| session.subagent_session_id == second.subagent_session_id));
-
- let thread_a = list_for_parent(&store, "parent-a", Some("thread-a")).unwrap();
- assert_eq!(thread_a.len(), 1);
- assert_eq!(thread_a[0].subagent_session_id, first.subagent_session_id);
- }
+ fn an_equal_millisecond_live_close_persists_and_a_stale_snapshot_cannot_reopen_it() {
+ use crate::agent::orchestration::subagent_sessions::store_documents::{with_override, Docs};
+ use crate::storage::{MemoryStorage, Scope, StorageBackend};
+
+ let storage = MemoryStorage::new();
+ let docs = Docs::over(&storage.for_scope(&Scope::new("local").unwrap()).unwrap());
+ let store = SubagentSessionStore::new(std::env::temp_dir());
+ let original = with_override(docs.clone(), || {
+ upsert_running(
+ &store,
+ SubagentSessionUpsert {
+ selector: selector("equal-ms-close"),
++ parent_epoch: None,
+ display_name: None,
+ task_title: "Task".into(),
+ worker_thread_id: None,
+ task_id: "task-id".into(),
+ lifecycle_key: None,
+ },
+ None,
+ )
+ .unwrap()
+ });
+ let stale_snapshot = docs.load().unwrap();
+
+ with_override(docs.clone(), || {
+ store
+ .update_session(&original.subagent_session_id, |current, _now| {
+ current.status = DurableSubagentStatus::Closed;
+ current.reusable = false;
+ // Leave updated_at untouched to force an equal `_ms` live
+ // transition deterministically, without a sleep or clock shim.
+ })
+ .unwrap()
+ .expect("the session is updated");
- #[test]
- fn missing_session_updates_return_errors() {
- let dir = tempfile::tempdir().unwrap();
- let store = SubagentSessionStore::new(dir.path().to_path_buf());
- assert!(mark_finished(
- &store,
- "missing",
- "sub-1",
- &SubagentRunStatus::Completed,
- vec![]
- )
- .is_err());
- assert!(mark_failed(&store, "missing", "sub-1", "boom".into()).is_err());
- assert!(!close(&store, "missing").unwrap());
- }
+ // A whole-list snapshot at the same timestamp must not reopen it.
+ store.save(&stale_snapshot).unwrap();
+ });
- #[test]
- fn legacy_session_with_toolkit_key_still_loads_and_reuses() {
- // Sessions persisted before the `toolkit` spawn argument was retired
- // carry a `toolkit` key. It must be ignored on load, and it must no
- // longer take part in reuse matching.
- let dir = tempfile::tempdir().unwrap();
- let store = SubagentSessionStore::new(dir.path().to_path_buf());
- let legacy = serde_json::json!([{
- "subagentSessionId": "subsess-legacy",
- "parentSession": "parent-a",
- "parentThreadId": "thread-a",
- "workerThreadId": null,
- "agentId": "researcher",
- "displayName": null,
- "toolkit": "gmail",
- "model": "oh-1",
- "sandboxMode": "read_only",
- "actionRoot": "/tmp/work",
- "taskKey": "legacy-task",
- "taskTitle": "Legacy task",
- "currentTaskId": null,
- "status": "idle",
- "reusable": true,
- "latestHistory": null,
- "latestError": null,
- "createdAt": "2026-01-01T00:00:00Z",
- "updatedAt": "2026-01-01T00:00:00Z",
- "lastUsedAt": "2026-01-01T00:00:00Z"
- }]);
- let parsed: Vec<DurableSubagentSession> =
- serde_json::from_value(legacy).expect("legacy toolkit key is ignored");
- store.save(&parsed).unwrap();
-
- let sessions = store.load().expect("legacy toolkit key is ignored");
- assert_eq!(sessions.len(), 1);
- let reused = find_reusable(&store, &selector("legacy-task"))
+ let closed = docs
+ .load()
.unwrap()
- .expect("legacy session reuses without a toolkit match");
- assert_eq!(reused.subagent_session_id, "subsess-legacy");
+ .into_iter()
+ .find(|record| record.subagent_session_id == original.subagent_session_id)
+ .expect("session remains stored");
+ assert_eq!(closed.status, DurableSubagentStatus::Closed);
+ assert!(!closed.reusable);
}
+
-#[test]
-fn list_for_parent_without_thread_id_does_not_filter_by_thread() {
- let dir = tempfile::tempdir().unwrap();
- let store = SubagentSessionStore::new(dir.path().to_path_buf());
- let first = upsert_running(
- &store,
- SubagentSessionUpsert {
- selector: selector("first"),
- display_name: None,
- task_title: "First".into(),
- worker_thread_id: None,
- task_id: "sub-1".into(),
- lifecycle_key: None,
- },
- None,
- )
- .unwrap();
-
- let mut second_selector = selector("second");
- second_selector.parent_thread_id = Some("thread-b".into());
- let second = upsert_running(
- &store,
- SubagentSessionUpsert {
- selector: second_selector,
- display_name: None,
- task_title: "Second".into(),
- worker_thread_id: None,
- task_id: "sub-2".into(),
- lifecycle_key: None,
- },
- None,
- )
- .unwrap();
-
- let all = list_for_parent(&store, "parent-a", None).unwrap();
- assert_eq!(all.len(), 2);
- assert!(all
- .iter()
- .any(|session| session.subagent_session_id == first.subagent_session_id));
- assert!(all
- .iter()
- .any(|session| session.subagent_session_id == second.subagent_session_id));
-
- let thread_a = list_for_parent(&store, "parent-a", Some("thread-a")).unwrap();
- assert_eq!(thread_a.len(), 1);
- assert_eq!(thread_a[0].subagent_session_id, first.subagent_session_id);
-}
-
-#[test]
-fn missing_session_updates_return_errors() {
- let dir = tempfile::tempdir().unwrap();
- let store = SubagentSessionStore::new(dir.path().to_path_buf());
- assert!(mark_finished(
- &store,
- "missing",
- "sub-1",
- &SubagentRunStatus::Completed,
- vec![]
- )
- .is_err());
- assert!(mark_failed(&store, "missing", "sub-1", "boom".into()).is_err());
- assert!(!close(&store, "missing").unwrap());
-}
-
-#[test]
-fn legacy_session_with_toolkit_key_still_loads_and_reuses() {
- // Sessions persisted before the `toolkit` spawn argument was retired
- // carry a `toolkit` key. It must be ignored on load, and it must no
- // longer take part in reuse matching.
- let dir = tempfile::tempdir().unwrap();
- let store = SubagentSessionStore::new(dir.path().to_path_buf());
- let legacy = serde_json::json!([{
- "subagentSessionId": "subsess-legacy",
- "parentSession": "parent-a",
- "parentThreadId": "thread-a",
- "workerThreadId": null,
- "agentId": "researcher",
- "displayName": null,
- "toolkit": "gmail",
- "model": "oh-1",
- "sandboxMode": "read_only",
- "actionRoot": "/tmp/work",
- "taskKey": "legacy-task",
- "taskTitle": "Legacy task",
- "currentTaskId": null,
- "status": "idle",
- "reusable": true,
- "latestHistory": null,
- "latestError": null,
- "createdAt": "2026-01-01T00:00:00Z",
- "updatedAt": "2026-01-01T00:00:00Z",
- "lastUsedAt": "2026-01-01T00:00:00Z"
- }]);
- let parsed: Vec<DurableSubagentSession> =
- serde_json::from_value(legacy).expect("legacy toolkit key is ignored");
- store.save(&parsed).unwrap();
-
- let sessions = store.load().expect("legacy toolkit key is ignored");
- assert_eq!(sessions.len(), 1);
- let reused = find_reusable(&store, &selector("legacy-task"))
- .unwrap()
- .expect("legacy session reuses without a toolkit match");
- assert_eq!(reused.subagent_session_id, "subsess-legacy");
-}
++#[path = "ops_followup_tests.rs"]
++mod followup_tests;
diff --cc crates/openhuman-core/src/agent/orchestration/tools.rs
index 454e19d0f2,3fa665b6db..8818001cd1
--- a/crates/openhuman-core/src/agent/orchestration/tools.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools.rs
@@@ -1,13 -1,45 +1,15 @@@
-//! Declares OpenHuman's product orchestration surfaces over TinyAgents.
-//!
-//! Tools, by role:
-//! - **Spawn**: `spawn_subagent`, `spawn_async_subagent`,
-//! `spawn_parallel_agents`.
-//! - **Control**: `steer_subagent`, `continue_subagent`, `close_subagent`,
-//! `wait_subagent`, `wait` / `wait_loop`, `list_subagents`.
-//! - **Delegation**: `DelegateGraphTool`, `ArchetypeDelegationTool`,
-//! and `CollapsedDelegationTool` (`delegate_to`).
-//!
-//! TinyAgents owns generic control operations; the host control module keeps
-//! the product declarations and projections. Worker-thread persistence lives
-//! in `threads`.
-//!
-//! `agent::registration` assembles the delegation tools for the catalogue.
-//! Execution crosses the shared TinyAgents Jobs/Message and subagent driver
-//! ports while this module retains product-specific policies and envelopes.
+//! OpenHuman's single asynchronous sub-agent spawn surface.
-#[path = "tools/archetype_delegation_host.rs"]
-mod archetype_delegation;
#[path = "tools/awaiting_user.rs"]
pub(crate) mod awaiting_user;
-#[path = "tools/collapsed_delegation_host.rs"]
-mod collapsed_delegation;
-#[path = "tools/continue_subagent_host.rs"]
-mod continue_subagent;
-#[path = "tools/delegate_graph.rs"]
-mod delegate_graph;
-#[path = "tools/subagent_dispatch_host.rs"]
+#[path = "tools/dispatch_outcomes.rs"]
mod dispatch;
-#[path = "tools/spawn_async_subagent_surface.rs"]
-mod spawn_async_subagent;
-#[path = "tools/spawn_parallel_agents.rs"]
-mod spawn_parallel_agents;
#[path = "tools/spawn_subagent_surface.rs"]
mod spawn_subagent;
+ #[path = "tools/structured_payload.rs"]
+ pub(crate) mod structured_payload;
#[path = "tools/subagent_abort_report.rs"]
mod subagent_abort_report;
-#[path = "tools/subagent_control_surfaces.rs"]
-mod subagent_control_surfaces;
#[cfg(test)]
#[path = "tools/tools_e2e_tests.rs"]
mod tools_e2e_tests;
diff --cc crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs
index 170b1c00a5,7cbda01199..5dea7efdb0
--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs
@@@ -1,4 -1,35 +1,34 @@@
- //! Result helpers shared by the asynchronous spawn completion path.
+ //! Pure result mapping and framing for synchronous delegation dispatch.
+
-use super::DispatchMode;
+ use tinytools::ToolResult;
+
+ pub(super) fn awaiting_outcome_to_tool_result(
+ outcome: &crate::agent::subagent_host::SubagentRunOutcome,
+ question: &str,
+ checkpointed: bool,
+ ) -> ToolResult {
+ if !checkpointed {
+ let question_json = serde_json::to_string(question)
+ .unwrap_or_else(|_| "\"<unserializable question>\"".into());
+ return ToolResult::error(format!(
+ "The sub-agent `{}` paused to ask a question, but its state could not be saved and this delegation has no durable session to fall back on, so it cannot be resumed. Its progress is lost. Tell the user what it was asking — {} — and that the delegation has to be started again; do NOT call continue_subagent with task_id `{}`, there is nothing for it to resume.",
+ outcome.agent_id, question_json, outcome.task_id
+ ));
+ }
- ToolResult::success(super::super::awaiting_user::awaiting_user_envelope(
++ ToolResult::success(super::awaiting_user::awaiting_user_envelope(
+ &outcome.task_id,
+ &outcome.agent_id,
+ None,
+ question,
+ checkpointed,
+ ))
+ }
+
+ pub(super) fn format_subagent_failure(tool_name: &str, message: &str) -> String {
+ format!(
+ "{tool_name} failed and did not complete — no work was performed and no results were produced. Do NOT treat this as success or fabricate an output; report the failure to the user. Error: {message}"
+ )
+ }
pub(crate) fn is_unexecuted_tool_call_stub(output: &str) -> bool {
use tinytools_agent::dialect::{contains_tool_call_payload, strip_tool_calls_from_response};
@@@ -15,12 -48,35 +47,8 @@@
.any(char::is_alphanumeric)
}
- pub(crate) fn format_subagent_failure(tool: &str, error: &str) -> String {
- format!(
- "{tool} failed and did not complete. Do not treat this as success or fabricate output. Details: {error}"
- )
-const INLINE_RESULT_NOTE: &str = "\n\n[INLINE_RESULT] This delegation ran inline and is complete as returned — there is no sub-agent worker for it. Do NOT call wait_subagent, list_subagents or continue_subagent for this delegation.";
-const NO_WORKER_NOTE: &str = "\n\n[INLINE_RESULT] This delegation ran inline and registered no sub-agent worker, so there is nothing to collect: do NOT call wait_subagent, list_subagents or continue_subagent for it. Re-delegate with a corrected prompt instead.";
-
-pub(crate) fn with_inline_result_note(output: String, mode: DispatchMode) -> String {
- if mode == DispatchMode::Blocking {
- format!("{output}{INLINE_RESULT_NOTE}")
- } else {
- output
- }
-}
-
-pub(crate) fn incomplete_envelope(
- tool_name: &str,
- reason: &str,
- output: &str,
- mode: DispatchMode,
-) -> String {
- let envelope = format!(
- "[SUBAGENT_INCOMPLETE] the {tool_name} sub-agent {reason} and did not finish. Below is partial progress only — do NOT report it as done or re-run the identical delegation unchanged.\n\nPartial progress:\n{output}"
- );
- if mode == DispatchMode::Blocking {
- format!("{envelope}{NO_WORKER_NOTE}")
- } else {
- envelope
- }
--}
--
+ /// How a sub-agent handed back as `Incomplete { reason }` was stopped
+ /// (iteration cap or failure breaker), for its `SubagentCompleted` event.
pub(crate) fn incomplete_stop(
reason: &str,
failure_cause: Option<tinyagents_harness::no_progress::ClassifiedStopCause>,
diff --cc crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs
index 02d151b67f,bffb5d7cfb..ac197dc787
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs
@@@ -56,17 -54,7 +56,18 @@@ pub(super) fn make_completion
let result = result.map_err(anyhow::Error::msg);
match result {
Ok(outcome) => {
- match outcome.status {
+ let status = if matches!(outcome.status, SubagentRunStatus::Completed)
+ && super::super::dispatch::is_unexecuted_tool_call_stub(&outcome.output)
+ {
+ SubagentRunStatus::Incomplete {
+ reason: "returned an unexecuted tool call instead of a result"
+ .to_string(),
++ failure_cause: None,
+ }
+ } else {
+ outcome.status.clone()
+ };
+ match status.clone() {
SubagentRunStatus::Completed => {
if let Err(err) = subagent_sessions::mark_finished(
&background_store,
diff --cc crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_workspace_owner_tests.rs
index 0000000000,de81145a7c..44ae133c6a
mode 000000,100644..100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_workspace_owner_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_workspace_owner_tests.rs
@@@ -1,0 -1,409 +1,154 @@@
+ use super::*;
+
+ #[tokio::test]
-async fn driver_job_controls_are_isolated_by_workspace_with_shared_runtime_state() {
- use crate::agent::orchestration::subagent_sessions::{
- DurableSubagentSession, DurableSubagentStatus, SubagentSessionStore,
- };
- use crate::agent::subagent_host::{run_subagent_via_driver_tool, SubagentRunOptions};
++async fn generic_spawn_jobs_are_owned_by_their_workspace() {
++ use crate::agent::orchestration::subagent_sessions::SubagentSessionStore;
++ use crate::agent::tinyagents::host::OpenHumanRunContext;
+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
+ use crate::tools::toolpacks::ToolGroups;
- use tinyagents_harness::agent_loop::phases::execute_tool_batch;
- use tinyagents_orchestration::subagent::SubAgentJobRegistry;
- use tinyagents_runtime::turn_driver::SharedToolSet;
++ use tinyagents_harness::context::{RunConfig, RunContext};
++ use tinyagents_harness_tools::subagents::SubAgentJobRegistry;
+
- struct PausedModel {
- started: tokio::sync::mpsc::UnboundedSender<()>,
- release: Arc<tokio::sync::Notify>,
- }
-
- #[async_trait]
- impl ChatModel<()> for PausedModel {
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- let _ = self.started.send(());
- self.release.notified().await;
- Ok(ModelResponse::assistant("workspace child finished"))
- }
- }
++ const PROMPT_A: &str = "workspace-owner-child-a-canary";
++ const PROMPT_B: &str = "workspace-owner-child-b-canary";
+
+ let scratch = tempfile::tempdir().expect("workspace owner isolation fixture");
+ let workspace_a = scratch.path().join("workspace-a");
+ let workspace_b = scratch.path().join("workspace-b");
+ std::fs::create_dir_all(&workspace_a).expect("create workspace A");
+ std::fs::create_dir_all(&workspace_b).expect("create workspace B");
++
++ let model = Arc::new(ScriptedModel::new(vec![
++ (PROMPT_A, "workspace-a-child-result"),
++ (PROMPT_B, "workspace-b-child-result"),
++ ]));
+ let mut base_config = crate::config::Config::default();
+ base_config.workspace_dir = workspace_a.clone();
+ base_config.components.juice = false;
+ let base = CoreContext::for_test_with_config(DomainSet::full(), base_config.clone());
+ let definitions = Arc::new(AgentDefinitionRegistry::builtins_only());
- let mut config_a = base_config.clone();
- config_a.workspace_dir = workspace_a.clone();
- let mut config_b = base_config;
- config_b.workspace_dir = workspace_b.clone();
- let core_a = base.derive_with(
- ContextOverlay::new(config_a, DomainSet::full(), ToolGroups::none())
- .definitions(definitions.clone()),
- );
- let core_b = base.derive_with(
- ContextOverlay::new(config_b, DomainSet::full(), ToolGroups::none())
- .definitions(definitions),
- );
+
- let (started_tx, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
- let release = Arc::new(tokio::sync::Notify::new());
- let model: Arc<dyn ChatModel<()>> = Arc::new(PausedModel {
- started: started_tx,
- release: release.clone(),
- });
- let build_parent = |workspace: &std::path::Path, core: &Arc<CoreContext>| {
- let mut product_parent = parent_context(workspace, model.clone(), vec![]);
- product_parent.workspace_dir = workspace.to_path_buf();
- product_parent.session_id = "same-parent-session".into();
- let mut options = SubagentRunOptions::default();
- options.run_context.parent = Some(product_parent);
- options.task_id = Some("same-raw-task-id".into());
- options.thread_id = Some("same-parent-thread".into());
- options.run_context.thread_id = Some("same-parent-thread".into());
- options.run_context = options.run_context.with_core(Some(Arc::clone(core)));
- let run_id = workspace
- .file_name()
- .and_then(std::ffi::OsStr::to_str)
- .unwrap_or("workspace");
- let run = options.run_context.clone().into_tinyagents(
- tinyagents_harness::context::RunConfig::new(format!("parent-{run_id}"))
- .with_thread("same-parent-thread"),
- );
- (options, run)
++ let make_live = |workspace: &Path, core: &Arc<CoreContext>, run_id: &str| {
++ let mut parent = parent_context(workspace, model.clone(), vec![]);
++ parent.workspace_dir = workspace.to_path_buf();
++ parent.session_id = "shared-parent-session".into();
++ let mut host = OpenHumanRunContext::new()
++ .with_core(Some(Arc::clone(core)))
++ .with_parent(parent);
++ host.thread_id = Some("shared-parent-thread".into());
++ RunContext::new(
++ RunConfig::new(run_id).with_thread("shared-parent-thread"),
++ host,
++ )
+ };
- let (options_a, parent_a) = build_parent(&workspace_a, &core_a);
- let (options_b, parent_b) = build_parent(&workspace_b, &core_b);
- let parent_cancel_a = options_a.run_context.cancellation.clone();
- let parent_cancel_b = options_b.run_context.cancellation.clone();
- // Control aliases run in a fresh turn context, as they do after a parent
- // turn resumes. Keep the original parents intact for their spawned child
- // futures; RunContext is intentionally not Clone.
- let mut run_a = options_a.run_context.clone().into_tinyagents(
- tinyagents_harness::context::RunConfig::new("workspace-a-control")
- .with_thread("same-parent-thread"),
- );
- let mut run_b = options_b.run_context.clone().into_tinyagents(
- tinyagents_harness::context::RunConfig::new("workspace-b-control")
- .with_thread("same-parent-thread"),
- );
- let jobs_a =
- crate::core::runtime::slot_for::<SubAgentJobRegistry>(&parent_a.data.dispatch_ctx());
- let jobs_b =
- crate::core::runtime::slot_for::<SubAgentJobRegistry>(&parent_b.data.dispatch_ctx());
- assert!(
- Arc::ptr_eq(&jobs_a, &jobs_b),
- "the two workspace overlays must exercise one shared registry"
- );
- let key_a = tinyagents_orchestration::subagent::SubagentTaskKey::from_context(
- &parent_a,
- "same-raw-task-id",
- Some("same-parent-thread".into()),
- );
- let key_b = tinyagents_orchestration::subagent::SubagentTaskKey::from_context(
- &parent_b,
- "same-raw-task-id",
- Some("same-parent-thread".into()),
- );
+
- let mut definition_a = AgentDefinitionRegistry::builtins_only()
- .get("task_manager_agent")
- .expect("task manager definition")
- .clone();
- definition_a.id = "workspace-a-worker".into();
- definition_a.model = tinyagents_definition::ModelSpec::Inherit;
- let mut definition_b = definition_a.clone();
- definition_b.id = "workspace-b-worker".into();
- let mut child_a = tokio::spawn(async move {
- run_subagent_via_driver_tool(
- &parent_a,
- definition_a,
- "run in workspace A".into(),
- options_a,
++ let make_core = |workspace: &Path| {
++ let mut config = base_config.clone();
++ config.workspace_dir = workspace.to_path_buf();
++ base.derive_with(
++ ContextOverlay::new(config, DomainSet::full(), ToolGroups::none())
++ .definitions(Arc::clone(&definitions)),
+ )
- .await
- });
- let mut child_b = tokio::spawn(async move {
- run_subagent_via_driver_tool(
- &parent_b,
- definition_b,
- "run in workspace B".into(),
- options_b,
++ };
++ let core_a = make_core(&workspace_a);
++ let core_b = make_core(&workspace_b);
++ let live_a = make_live(&workspace_a, &core_a, "workspace-owner-parent-a");
++ let live_b = make_live(&workspace_b, &core_b, "workspace-owner-parent-b");
++
++ async fn spawn(live: &RunContext<OpenHumanRunContext>, prompt: &str) -> String {
++ let accepted = crate::core::runtime::CoreContext::scope(
++ live.data.dispatch_ctx().resolved().expect("live core context"),
++ Box::pin(SpawnSubagentTool::new().execute_with_live_parent_context(
++ json!({
++ "agent_id": "task_manager_agent",
++ "prompt": prompt,
++ "model": "test-model",
++ "task_key": "same task key in separate workspaces"
++ }),
++ None,
++ live.data.child(),
++ crate::agent::subagent_host::detached_subagent_parent(live, "workspace-child")
++ .expect("detached parent"),
++ )),
+ )
+ .await
- });
- let both_started = tokio::time::timeout(std::time::Duration::from_secs(5), async {
- for _ in 0..2 {
- tokio::select! {
- notification = started_rx.recv() => {
- notification.expect("model start notification");
- }
- result = &mut child_a => match result {
- Ok(Ok((outcome, output))) => panic!(
- "workspace A child returned before entering the gated model: {:?}, {output}",
- outcome.status,
- ),
- Ok(Err(error)) => panic!("workspace A child failed before model start: {error:?}"),
- Err(error) => panic!("workspace A child task panicked before model start: {error}"),
- },
- result = &mut child_b => match result {
- Ok(Ok((outcome, output))) => panic!(
- "workspace B child returned before entering the gated model: {:?}, {output}",
- outcome.status,
- ),
- Ok(Err(error)) => panic!("workspace B child failed before model start: {error:?}"),
- Err(error) => panic!("workspace B child task panicked before model start: {error}"),
- },
- }
- }
- })
- .await;
- if both_started.is_err() {
- let jobs = jobs_a
- .list()
- .into_iter()
- .map(|job| format!("{}:{}:{:?}", job.id, job.agent, job.status))
- .collect::<Vec<_>>();
- panic!(
- "both driver children enter the gated model; jobs={jobs:?}, child_finished=({}, {})",
- child_a.is_finished(),
- child_b.is_finished()
- );
++ .expect("generic spawn execution");
++ assert!(!accepted.is_error, "{}", accepted.output());
++ accepted
++ .output()
++ .split("[async_subagent_ref]\n")
++ .nth(1)
++ .and_then(|value| value.split("\n[/async_subagent_ref]").next())
++ .and_then(|value| serde_json::from_str::<serde_json::Value>(value).ok())
++ .and_then(|value| value["task_id"].as_str().map(str::to_owned))
++ .expect("accepted generic spawn contains its public task id")
+ }
+
- let job_a = jobs_a
- .list()
- .into_iter()
- .find(|job| job.agent == "workspace-a-worker")
- .expect("workspace A child is registered");
- let job_b = jobs_b
- .list()
- .into_iter()
- .find(|job| job.agent == "workspace-b-worker")
- .expect("workspace B child is registered");
- let id_a = job_a.id.as_str().to_owned();
- let id_b = job_b.id.as_str().to_owned();
- assert_ne!(
- id_a, id_b,
- "full lifecycle scope keeps raw-ID reuse distinct"
- );
++ let task_a = spawn(&live_a, PROMPT_A).await;
++ let task_b = spawn(&live_b, PROMPT_B).await;
++ assert_ne!(task_a, task_b, "workspace-scoped tasks remain distinct");
+
- let now = chrono::Utc::now().to_rfc3339();
- let save_running_session =
- |workspace: &std::path::Path,
- session_id: &str,
- task_key: tinyagents_orchestration::subagent::SubagentTaskKey| {
- SubagentSessionStore::new(workspace.to_path_buf()).save(&[DurableSubagentSession {
- subagent_session_id: session_id.to_owned(),
- parent_session: "same-parent-session".into(),
- parent_thread_id: Some("same-parent-thread".into()),
- worker_thread_id: None,
- agent_id: "task_manager_agent".into(),
- display_name: None,
- model: Some("test-model".into()),
- sandbox_mode: "workspace".into(),
- action_root: None,
- task_key: "same task in another workspace".into(),
- task_title: "Workspace scoped task".into(),
- current_task_id: Some("same-raw-task-id".into()),
- lifecycle_key: Some(task_key),
- status: DurableSubagentStatus::Running,
- reusable: true,
- latest_history: None,
- latest_error: None,
- created_at: now.clone(),
- updated_at: now.clone(),
- last_used_at: now.clone(),
- }])
- };
- save_running_session(&workspace_a, "workspace-a-session", key_a)
- .expect("persist A session for native close alias");
- save_running_session(&workspace_b, "workspace-b-session", key_b)
- .expect("persist B session for native close alias");
-
- let tools: SharedToolSet = Arc::new(vec![
- Box::new(crate::agent::orchestration::tools::ListSubagentsTool::new()),
- Box::new(crate::agent::orchestration::tools::WaitSubagentTool::new()),
- Box::new(crate::agent::orchestration::tools::SteerSubagentTool::new()),
- Box::new(crate::agent::orchestration::tools::CloseSubagentTool::new()),
- ]);
- let sets = vec![tools];
- let mut harness: tinyagents_harness::runtime::AgentHarness<
- (),
- crate::agent::tinyagents::host::OpenHumanRunContext,
- > = tinyagents_harness::runtime::AgentHarness::new();
- crate::agent::tinyagents::tool_registration::host_tool_set_builder(
- &sets,
- &None,
- true,
- &std::collections::HashSet::new(),
- )
- .register(&mut harness, None);
- let mut status_a = tinyagents_harness::events::HarnessRunStatus::new(
- run_a.run_id().clone(),
- tinyagents_harness::ComponentId::new("workspace-a-control"),
- );
- let mut status_b = tinyagents_harness::events::HarnessRunStatus::new(
- run_b.run_id().clone(),
- tinyagents_harness::ComponentId::new("workspace-b-control"),
- );
- let mut agent_run_a = tinyagents_harness::middleware::AgentRun::new();
- let mut agent_run_b = tinyagents_harness::middleware::AgentRun::new();
- let mut messages_a = Vec::new();
- let mut messages_b = Vec::new();
- let listed_a = execute_tool_batch(
- &harness,
- &(),
- &mut run_a,
- &mut agent_run_a,
- &mut status_a,
- &mut messages_a,
- vec![tinyinference_llm::tool::ToolCall::new(
- "workspace-a-list",
- "list_subagents",
- serde_json::json!({}),
- )],
- )
- .await
- .expect("native list alias works for A");
- assert!(listed_a.results[0].text().contains("workspace-a-session"));
++ let registry_a = CoreContext::sync_scope(Arc::clone(&core_a), || {
++ crate::core::runtime::slot_for::<SubAgentJobRegistry>(&live_a.data.dispatch_ctx())
++ });
++ let registry_b = CoreContext::sync_scope(Arc::clone(&core_b), || {
++ crate::core::runtime::slot_for::<SubAgentJobRegistry>(&live_b.data.dispatch_ctx())
++ });
+ assert!(
- !listed_a.results[0].text().contains("workspace-b-session"),
- "A must not see B's durable session: {}",
- listed_a.results[0].text()
++ Arc::ptr_eq(&registry_a, &registry_b),
++ "the fixture exercises one shared generic job registry"
+ );
- let listed_b = execute_tool_batch(
- &harness,
- &(),
- &mut run_b,
- &mut agent_run_b,
- &mut status_b,
- &mut messages_b,
- vec![tinyinference_llm::tool::ToolCall::new(
- "workspace-b-list",
- "list_subagents",
- serde_json::json!({}),
- )],
- )
- .await
- .expect("native list alias works for B");
- assert!(listed_b.results[0].text().contains("workspace-b-session"));
- assert!(!listed_b.results[0].text().contains("workspace-a-session"));
+
- let foreign_wait = execute_tool_batch(
- &harness,
- &(),
- &mut run_a,
- &mut agent_run_a,
- &mut status_a,
- &mut messages_a,
- vec![tinyinference_llm::tool::ToolCall::new(
- "workspace-a-wait-b",
- "wait_subagent",
- serde_json::json!({"task_id":id_b,"timeout_secs":1}),
- )],
- )
- .await
- .expect("foreign wait returns a recoverable selector denial");
- assert_eq!(foreign_wait.results.len(), 1);
- let foreign_wait_text = foreign_wait.results[0].text();
++ let load_row = |core: &Arc<CoreContext>, workspace: &Path, task_id: &str| {
++ CoreContext::sync_scope(Arc::clone(core), || {
++ SubagentSessionStore::new(workspace.to_path_buf())
++ .load()
++ .expect("read generic child session")
++ .into_iter()
++ .find(|row| row.current_task_id.as_deref() == Some(task_id))
++ .expect("generic child session is persisted")
++ })
++ };
++ let row_a = load_row(&core_a, &workspace_a, &task_a);
++ let row_b = load_row(&core_b, &workspace_b, &task_b);
++ let key_a = row_a.lifecycle_key.expect("A row has a lifecycle key");
++ let key_b = row_b.lifecycle_key.expect("B row has a lifecycle key");
++ let owner_a = crate::agent::tinyagents::tool_registration::subagent_owner_key(
++ &workspace_a,
++ "shared-parent-session",
++ Some("shared-parent-thread"),
++ );
++ let owner_b = crate::agent::tinyagents::tool_registration::subagent_owner_key(
++ &workspace_b,
++ "shared-parent-session",
++ Some("shared-parent-thread"),
++ );
++ let job_a = registry_a
++ .driver_job_for_key(&key_a, &owner_a)
++ .expect("workspace A owns its generic child job");
++ let job_b = registry_b
++ .driver_job_for_key(&key_b, &owner_b)
++ .expect("workspace B owns its generic child job");
++ assert_ne!(job_a, job_b);
+ assert!(
- foreign_wait_text.contains("selected subagent job or session is unavailable"),
- "A must receive a selector denial for B's generic job id, got: {foreign_wait_text}"
++ registry_a.driver_job_for_key(&key_a, &owner_b).is_none(),
++ "workspace B cannot resolve workspace A's generic child job"
+ );
- assert_eq!(
- jobs_b
- .get(&id_b)
- .expect("B child remains registered")
- .status,
- tinyagents_orchestration::subagent::SubAgentJobStatus::Running,
- "a foreign wait must not settle or mutate B's child"
- );
-
- let foreign_close = execute_tool_batch(
- &harness,
- &(),
- &mut run_a,
- &mut agent_run_a,
- &mut status_a,
- &mut messages_a,
- vec![tinyinference_llm::tool::ToolCall::new(
- "workspace-a-close-b",
- "close_subagent",
- serde_json::json!({"subagent_session_id":"workspace-b-session"}),
- )],
- )
- .await
- .expect("foreign close is a recoverable model-facing selector error");
- assert!(!foreign_close.results[0].text().contains("\"closed\":true"));
- let job_b = jobs_b.get(&id_b).expect("B's child remains registered");
- assert_eq!(
- job_b.status,
- tinyagents_orchestration::subagent::SubAgentJobStatus::Running
- );
-
- let owned_close = execute_tool_batch(
- &harness,
- &(),
- &mut run_b,
- &mut agent_run_b,
- &mut status_b,
- &mut messages_b,
- vec![tinyinference_llm::tool::ToolCall::new(
- "workspace-b-close-own",
- "close_subagent",
- serde_json::json!({"subagent_session_id":"workspace-b-session"}),
- )],
- )
- .await
- .expect("B can close its own durable child");
- assert_eq!(owned_close.results.len(), 1);
- assert_eq!(
- SubagentSessionStore::new(workspace_b.clone())
- .load()
- .unwrap()[0]
- .status,
- DurableSubagentStatus::Closed
- );
- release.notify_waiters();
- let result_a = tokio::time::timeout(std::time::Duration::from_secs(5), child_a)
- .await
- .expect("A child settles")
- .expect("A task join")
- .expect("A child succeeds");
- let result_b = tokio::time::timeout(std::time::Duration::from_secs(5), child_b)
++ assert!(
++ registry_b.driver_job_for_key(&key_b, &owner_a).is_none(),
++ "workspace A cannot resolve workspace B's generic child job"
++ );
++ for (registry, job_id, owner, expected_output) in [
++ (&registry_a, job_a, &owner_a, "workspace-a-child-result"),
++ (&registry_b, job_b, &owner_b, "workspace-b-child-result"),
++ ] {
++ let terminal = tokio::time::timeout(
++ std::time::Duration::from_secs(5),
++ registry.wait_owned(job_id.as_str(), owner),
++ )
+ .await
- .expect("B child settles")
- .expect("B task join");
- assert!(matches!(
- result_a.0.status,
- crate::agent::subagent_host::SubagentRunStatus::Completed
- ));
- match result_b {
- Ok((outcome, _)) => assert!(matches!(
- outcome.status,
- crate::agent::subagent_host::SubagentRunStatus::Cancelled
- )),
- Err(error) => assert_eq!(
- error.to_string(),
- "provider call failed: tinyagents harness run failed: run cancelled"
- ),
++ .expect("generic child reaches a terminal state")
++ .expect("owner can await its generic child");
++ assert_eq!(terminal.output.as_deref(), Some(expected_output));
+ }
- assert_eq!(
- jobs_b
- .get(&id_b)
- .expect("B driver job remains inspectable")
- .status,
- tinyagents_orchestration::subagent::SubAgentJobStatus::Cancelled,
- "the shared driver registry is authoritative for B's cancellation"
- );
- assert!(!parent_cancel_a.is_cancelled());
- assert!(!parent_cancel_b.is_cancelled());
+ }
diff --cc crates/openhuman-core/src/agent/session_host/driver.rs
index 3d5ac60bbc,8fe3c97424..7c26dc6dbb
--- a/crates/openhuman-core/src/agent/session_host/driver.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver.rs
@@@ -1,10 -1,11 +1,16 @@@
//! OpenHuman's model-and-harness implementation of the neutral session driver.
//!
-//! This adapter deliberately has no transcript, prefix, or generic history
-//! state. `tinyagents_runtime::Session` owns those and hands this type the
-//! complete immutable model history and tool declaration snapshot per call.
+//! This adapter holds no transcript, prefix, or generic history; its owning
+//! `tinyagents_runtime::Session` supplies the complete immutable history and tool snapshot per call.
mod grounded_close;
++mod helpers;
use crate::agent::tinyagents::SupplementalTrace;
++use helpers::{
++ append_synthesized_block, driver_cancelled_with_snapshot, driver_error,
++ driver_error_with_snapshot, driver_failure, ensure_snapshot_tools_are_executable,
++ repair_orphaned_tool_head,
++};
use std::{collections::HashSet, sync::Arc, time::Instant};
@@@ -521,230 -508,235 +527,6 @@@ impl SessionDriver<OpenHumanRunContext
}
}
--fn system_prefix_len(history: &[Message]) -> usize {
-- history
-- .iter()
-- .take_while(|message| matches!(message, Message::System(_)))
-- .count()
--}
--
--/// Drop `tool` messages that open the history right after the system prefix.
--/// Their assistant turn is gone (an old unpaired trim, #6721), and the provider
--/// rejects every request that carries them, so the thread can never recover
--/// without this. Later system rows (e.g. a steering nudge) are kept.
--fn repair_orphaned_tool_head(history: &mut Vec<Message>) {
-- let prefix_len = system_prefix_len(history);
-- let orphans =
-- tinyagents_harness::summarization::advance_past_orphan_tools(&history[prefix_len..], 0);
-- if orphans > 0 {
-- tracing::warn!(
-- orphans,
-- "[session_host::driver] repaired orphaned tool head: dropped {orphans} leading tool message(s)"
-- );
-- history.drain(prefix_len..prefix_len + orphans);
-- }
--}
--
--fn driver_error(error: impl std::fmt::Display) -> DriverFailure {
-- driver_failure(error)
--}
--
--fn driver_failure(error: impl std::fmt::Display) -> DriverFailure {
-- DriverFailure {
-- error: RuntimeError::Driver(error.to_string()),
-- partial: None,
-- outcome: None,
-- }
--}
--
--/// Refuse fresh declarations without a request-scoped executable source.
--/// Historical declarations may outlive their executors. The harness handles
--/// calls to those missing tools as recoverable errors; history never supplies
--/// an executor or bypasses the current tool policy.
--fn ensure_snapshot_tools_are_executable(
-- visible_tool_names: &HashSet<String>,
-- tools: &Arc<Vec<Box<dyn tinytools::Tool>>>,
-- synthesized_tools: &Arc<Vec<Box<dyn tinytools::Tool>>>,
-- recorded_tool_names: &HashSet<String>,
--) -> Result<(), DriverFailure> {
-- let executable_tool_names = tools
-- .iter()
-- .chain(synthesized_tools.iter())
-- .map(|tool| tool.name().to_string())
-- .collect::<HashSet<_>>();
-- let missing = visible_tool_names
-- .difference(&executable_tool_names)
-- .filter(|name| !recorded_tool_names.contains(*name))
-- .cloned()
-- .collect::<Vec<_>>();
-- if missing.is_empty() {
-- Ok(())
-- } else {
-- Err(driver_failure(format!(
-- "session tool snapshot declares non-executable tools: {}",
-- missing.join(", ")
-- )))
-- }
--}
--
--fn driver_error_with_snapshot(
-- error: anyhow::Error,
-- snapshot: &crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshotSink,
-- sidecar: &std::sync::Arc<
-- std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,
-- >,
-- elapsed: std::time::Duration,
--) -> DriverFailure {
-- // Classify from the typed harness error when the chain carries one, rather
-- // than matching on its rendered text.
- let dispatch_refusal = error.chain().find_map(|cause| {
- cause.downcast_ref::<crate::agent::tinyagents::budget::DispatchRefusal>()
- });
- sidecar
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .dispatch_refusal = dispatch_refusal.copied();
-- let typed = error
-- .chain()
-- .find_map(|cause| cause.downcast_ref::<tinyagents_harness::TinyAgentsError>());
-- let stalled = matches!(
-- typed,
-- Some(tinyagents_harness::TinyAgentsError::GenerationStalled)
-- );
-- let terminal = typed.map(|typed| {
-- tinyagents_harness::terminal::TerminalOutcome::from_error(
-- typed,
-- tinyagents_harness::terminal::TimeoutPhase::AfterTurn,
-- )
-- });
-- let error = error.to_string();
-- let guard = snapshot
-- .lock()
-- .unwrap_or_else(|poisoned| poisoned.into_inner());
-- record_snapshot_usage(&guard, sidecar, elapsed);
-- if guard.messages.is_empty() {
-- let mut failure = driver_failure(error);
-- failure.outcome = terminal;
-- return failure;
-- }
-- let accepted_end = guard.accepted_end();
-- let history = guard.messages[..accepted_end].to_vec();
-- let unanswered = crate::agent::tinyagents::middleware::turn_context::render_unanswered_steps(
-- &guard.messages[accepted_end..],
-- );
-- let display = if stalled {
-- // The model's streamed narration was stopped before it could repeat
-- // indefinitely. Preserve the completed tools as a useful, bounded
-- // partial rather than showing only the failed model's process text.
-- let results = crate::agent::session_host::turn_checkpoint::results_from_tool_outcomes(
-- &guard.tool_outcomes,
-- );
-- let evidence = crate::agent::session_host::turn_checkpoint::render_tool_results(
-- &results,
-- crate::agent::session_host::turn_checkpoint::CHECKPOINT_TOTAL_CHARS,
-- );
-- format!(
-- "I stopped a repetitive model response before it could finish. Here are the completed tool results I can report:\n{evidence}"
-- )
-- } else {
-- match unanswered {
-- Some(steps) => format!("The turn stopped before completion: {error}.\n\n{steps}"),
-- None => format!("The turn stopped before completion: {error}."),
-- }
-- };
-- DriverFailure {
-- error: RuntimeError::Driver(error),
-- partial: Some(DriverOutcome {
-- history,
-- output: None,
-- partial: Some(TranscriptPartial::new(display)),
-- interrupted: true,
-- outcome: terminal.clone(),
- tool_outcomes: guard.tool_outcomes.clone(),
-- }),
-- outcome: terminal,
-- }
--}
--
--/// A graph error or a Stop drops the harness's `AgentRun`, but its snapshot
--/// has already observed provider-accepted usage and completed tool outcomes.
--/// Copy those into the per-turn sidecar *before* producing the partial so
--/// runtime's single atomic append carries the same usage/failure truth as a
--/// successful turn. The partial history itself remains accepted-only.
--fn record_snapshot_usage(
-- guard: &crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshot,
-- sidecar: &std::sync::Arc<
-- std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,
-- >,
-- elapsed: std::time::Duration,
--) {
-- let mut observed = sidecar
-- .lock()
-- .unwrap_or_else(|poisoned| poisoned.into_inner());
-- observed.model_calls = guard.model_calls as usize;
-- observed.tool_calls = guard.tool_outcomes.len();
-- observed.input_tokens = guard.input_tokens;
-- observed.output_tokens = guard.output_tokens;
-- observed.cached_input_tokens = guard.cached_input_tokens;
-- observed.last_call_input_tokens = guard.last_call_input_tokens;
-- observed.last_call_output_tokens = guard.last_call_output_tokens;
-- // Each answered call was priced as it arrived (reported charge, else
-- // catalog estimate, else unknown); nothing is re-estimated here.
-- observed.cost = guard.cost;
-- observed.duration = Some(elapsed);
-- observed.tool_outcomes = guard.tool_outcomes.clone();
-- observed.resolved_route = guard.resolved_route.clone();
--}
--
--/// A stopped turn's partial (#7715): the prompt and the accepted rounds, or
--/// just the request before the first model call. No display partial: the
--/// turn_state mirror already records the streamed text.
--fn driver_cancelled_with_snapshot(
-- snapshot: &crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshotSink,
-- sidecar: &std::sync::Arc<
-- std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,
-- >,
-- elapsed: std::time::Duration,
-- request_history: Vec<Message>,
--) -> DriverFailure {
-- let guard = snapshot
-- .lock()
-- .unwrap_or_else(|poisoned| poisoned.into_inner());
-- record_snapshot_usage(&guard, sidecar, elapsed);
-- let history = if guard.messages.is_empty() {
-- request_history
-- } else {
-- guard.messages[..guard.accepted_end()].to_vec()
-- };
-- DriverFailure {
-- error: RuntimeError::Cancelled,
-- partial: Some(DriverOutcome {
-- history,
-- output: None,
-- partial: None,
-- interrupted: true,
-- outcome: None,
- tool_outcomes: guard.tool_outcomes.clone(),
-- }),
-- outcome: None,
-- }
--}
--
--/// Append the deterministic required-output block when `output` lacks it, and
--/// make that the durable final assistant row. Used when no model repair may
--/// run: a classified halt, or a turn out of time before the backstop.
--fn append_synthesized_block(
-- output: &mut String,
-- history: &mut Vec<Message>,
-- contract: &tinyagents_harness::config::RequiredOutput,
--) {
-- if tinyagents_harness::config::output_satisfies_contract(output, contract) {
-- return;
-- }
-- output.push_str("\n\n");
-- output.push_str(&tinyagents_harness::config::synthesize_block(contract));
-- if history
-- .last()
-- .is_some_and(|message| matches!(message, Message::Assistant(_)))
-- {
-- history.pop();
-- }
-- history.push(Message::assistant(output.clone()));
--}
--
#[cfg(test)]
#[path = "driver_tests.rs"]
mod tests;
diff --cc crates/openhuman-core/src/agent/session_host/driver/helpers.rs
index 0000000000,0000000000..182d8c0141
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/driver/helpers.rs
@@@ -1,0 -1,0 +1,232 @@@
++use super::*;
++
++pub(super) fn system_prefix_len(history: &[Message]) -> usize {
++ history
++ .iter()
++ .take_while(|message| matches!(message, Message::System(_)))
++ .count()
++}
++
++/// Drop `tool` messages that open the history right after the system prefix.
++/// Their assistant turn is gone (an old unpaired trim, #6721), and the provider
++/// rejects every request that carries them, so the thread can never recover
++/// without this. Later system rows (e.g. a steering nudge) are kept.
++pub(super) fn repair_orphaned_tool_head(history: &mut Vec<Message>) {
++ let prefix_len = system_prefix_len(history);
++ let orphans =
++ tinyagents_harness::summarization::advance_past_orphan_tools(&history[prefix_len..], 0);
++ if orphans > 0 {
++ tracing::warn!(
++ orphans,
++ "[session_host::driver] repaired orphaned tool head: dropped {orphans} leading tool message(s)"
++ );
++ history.drain(prefix_len..prefix_len + orphans);
++ }
++}
++
++pub(super) fn driver_error(error: impl std::fmt::Display) -> DriverFailure {
++ driver_failure(error)
++}
++
++pub(super) fn driver_failure(error: impl std::fmt::Display) -> DriverFailure {
++ DriverFailure {
++ error: RuntimeError::Driver(error.to_string()),
++ partial: None,
++ outcome: None,
++ }
++}
++
++/// Refuse fresh declarations without a request-scoped executable source.
++/// Historical declarations may outlive their executors. The harness handles
++/// calls to those missing tools as recoverable errors; history never supplies
++/// an executor or bypasses the current tool policy.
++pub(super) fn ensure_snapshot_tools_are_executable(
++ visible_tool_names: &HashSet<String>,
++ tools: &Arc<Vec<Box<dyn tinytools::Tool>>>,
++ synthesized_tools: &Arc<Vec<Box<dyn tinytools::Tool>>>,
++ recorded_tool_names: &HashSet<String>,
++) -> Result<(), DriverFailure> {
++ let executable_tool_names = tools
++ .iter()
++ .chain(synthesized_tools.iter())
++ .map(|tool| tool.name().to_string())
++ .collect::<HashSet<_>>();
++ let missing = visible_tool_names
++ .difference(&executable_tool_names)
++ .filter(|name| !recorded_tool_names.contains(*name))
++ .cloned()
++ .collect::<Vec<_>>();
++ if missing.is_empty() {
++ Ok(())
++ } else {
++ Err(driver_failure(format!(
++ "session tool snapshot declares non-executable tools: {}",
++ missing.join(", ")
++ )))
++ }
++}
++
++pub(super) fn driver_error_with_snapshot(
++ error: anyhow::Error,
++ snapshot: &crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshotSink,
++ sidecar: &std::sync::Arc<
++ std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,
++ >,
++ elapsed: std::time::Duration,
++) -> DriverFailure {
++ // Classify from the typed harness error when the chain carries one, rather
++ // than matching on its rendered text.
++ let dispatch_refusal = error.chain().find_map(|cause| {
++ cause.downcast_ref::<crate::agent::tinyagents::budget::DispatchRefusal>()
++ });
++ sidecar
++ .lock()
++ .unwrap_or_else(|poisoned| poisoned.into_inner())
++ .dispatch_refusal = dispatch_refusal.copied();
++ let typed = error
++ .chain()
++ .find_map(|cause| cause.downcast_ref::<tinyagents_harness::TinyAgentsError>());
++ let stalled = matches!(
++ typed,
++ Some(tinyagents_harness::TinyAgentsError::GenerationStalled)
++ );
++ let terminal = typed.map(|typed| {
++ tinyagents_harness::terminal::TerminalOutcome::from_error(
++ typed,
++ tinyagents_harness::terminal::TimeoutPhase::AfterTurn,
++ )
++ });
++ let error = error.to_string();
++ let guard = snapshot
++ .lock()
++ .unwrap_or_else(|poisoned| poisoned.into_inner());
++ record_snapshot_usage(&guard, sidecar, elapsed);
++ if guard.messages.is_empty() {
++ let mut failure = driver_failure(error);
++ failure.outcome = terminal;
++ return failure;
++ }
++ let accepted_end = guard.accepted_end();
++ let history = guard.messages[..accepted_end].to_vec();
++ let unanswered = crate::agent::tinyagents::middleware::turn_context::render_unanswered_steps(
++ &guard.messages[accepted_end..],
++ );
++ let display = if stalled {
++ // The model's streamed narration was stopped before it could repeat
++ // indefinitely. Preserve the completed tools as a useful, bounded
++ // partial rather than showing only the failed model's process text.
++ let results = crate::agent::session_host::turn_checkpoint::results_from_tool_outcomes(
++ &guard.tool_outcomes,
++ );
++ let evidence = crate::agent::session_host::turn_checkpoint::render_tool_results(
++ &results,
++ crate::agent::session_host::turn_checkpoint::CHECKPOINT_TOTAL_CHARS,
++ );
++ format!(
++ "I stopped a repetitive model response before it could finish. Here are the completed tool results I can report:\n{evidence}"
++ )
++ } else {
++ match unanswered {
++ Some(steps) => format!("The turn stopped before completion: {error}.\n\n{steps}"),
++ None => format!("The turn stopped before completion: {error}."),
++ }
++ };
++ DriverFailure {
++ error: RuntimeError::Driver(error),
++ partial: Some(DriverOutcome {
++ history,
++ output: None,
++ partial: Some(TranscriptPartial::new(display)),
++ interrupted: true,
++ outcome: terminal.clone(),
++ tool_outcomes: guard.tool_outcomes.clone(),
++ }),
++ outcome: terminal,
++ }
++}
++
++/// A graph error or a Stop drops the harness's `AgentRun`, but its snapshot
++/// has already observed provider-accepted usage and completed tool outcomes.
++/// Copy those into the per-turn sidecar *before* producing the partial so
++/// runtime's single atomic append carries the same usage/failure truth as a
++/// successful turn. The partial history itself remains accepted-only.
++pub(super) fn record_snapshot_usage(
++ guard: &crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshot,
++ sidecar: &std::sync::Arc<
++ std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,
++ >,
++ elapsed: std::time::Duration,
++) {
++ let mut observed = sidecar
++ .lock()
++ .unwrap_or_else(|poisoned| poisoned.into_inner());
++ observed.model_calls = guard.model_calls as usize;
++ observed.tool_calls = guard.tool_outcomes.len();
++ observed.input_tokens = guard.input_tokens;
++ observed.output_tokens = guard.output_tokens;
++ observed.cached_input_tokens = guard.cached_input_tokens;
++ observed.last_call_input_tokens = guard.last_call_input_tokens;
++ observed.last_call_output_tokens = guard.last_call_output_tokens;
++ // Each answered call was priced as it arrived (reported charge, else
++ // catalog estimate, else unknown); nothing is re-estimated here.
++ observed.cost = guard.cost;
++ observed.duration = Some(elapsed);
++ observed.tool_outcomes = guard.tool_outcomes.clone();
++ observed.resolved_route = guard.resolved_route.clone();
++}
++
++/// A stopped turn's partial (#7715): the prompt and the accepted rounds, or
++/// just the request before the first model call. No display partial: the
++/// turn_state mirror already records the streamed text.
++pub(super) fn driver_cancelled_with_snapshot(
++ snapshot: &crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshotSink,
++ sidecar: &std::sync::Arc<
++ std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,
++ >,
++ elapsed: std::time::Duration,
++ request_history: Vec<Message>,
++) -> DriverFailure {
++ let guard = snapshot
++ .lock()
++ .unwrap_or_else(|poisoned| poisoned.into_inner());
++ record_snapshot_usage(&guard, sidecar, elapsed);
++ let history = if guard.messages.is_empty() {
++ request_history
++ } else {
++ guard.messages[..guard.accepted_end()].to_vec()
++ };
++ DriverFailure {
++ error: RuntimeError::Cancelled,
++ partial: Some(DriverOutcome {
++ history,
++ output: None,
++ partial: None,
++ interrupted: true,
++ outcome: None,
++ tool_outcomes: guard.tool_outcomes.clone(),
++ }),
++ outcome: None,
++ }
++}
++
++/// Append the deterministic required-output block when `output` lacks it, and
++/// make that the durable final assistant row. Used when no model repair may
++/// run: a classified halt, or a turn out of time before the backstop.
++pub(super) fn append_synthesized_block(
++ output: &mut String,
++ history: &mut Vec<Message>,
++ contract: &tinyagents_harness::config::RequiredOutput,
++) {
++ if tinyagents_harness::config::output_satisfies_contract(output, contract) {
++ return;
++ }
++ output.push_str("\n\n");
++ output.push_str(&tinyagents_harness::config::synthesize_block(contract));
++ if history
++ .last()
++ .is_some_and(|message| matches!(message, Message::Assistant(_)))
++ {
++ history.pop();
++ }
++ history.push(Message::assistant(output.clone()));
++}
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs
index 11399eec91,1bf3127378..6085b859b4
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs
@@@ -92,6 -94,13 +94,13 @@@ impl OpenHumanTurnPrelude
}
pub(super) fn build_system_prompt_tiered(&self) -> Result<crate::agent::prompts::TieredPrompt> {
+ self.build_system_prompt_tiered_with_flow_archetype(None)
+ }
+
- pub(super) fn build_system_prompt_tiered_with_flow_archetype(
++ pub(crate) fn build_system_prompt_tiered_with_flow_archetype(
+ &self,
+ flow_archetype_text: Option<&str>,
+ ) -> Result<crate::agent::prompts::TieredPrompt> {
use crate::agent::prompts::{PromptContext, PromptTool};
let surface = self
.tool_surface
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session/prompt_surface.rs
index 6e6b9ceed2,da29985467..d4ffe581dd
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_surface.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_surface.rs
@@@ -3,17 -3,6 +3,24 @@@
use super::*;
impl OpenHumanSessionHost {
+ /// Render the prompt from the same current-turn prelude that prepares a
+ /// cold runtime turn. Callers must refresh the prompt surface first when
+ /// they need live integrations or synthesized tools.
+ pub fn render_current_turn_prompt(&self) -> Result<String> {
++ self.render_current_turn_prompt_with_flow_archetype(None)
++ }
++
++ pub(crate) fn render_current_turn_prompt_with_flow_archetype(
++ &self,
++ flow_archetype_text: Option<&str>,
++ ) -> Result<String> {
+ let prelude = self.create_turn_prelude(false);
+ Ok(prelude
- .build_system_prompt_tiered()?
++ .build_system_prompt_tiered_with_flow_archetype(flow_archetype_text)?
+ .system_messages()
+ .join(""))
+ }
+
pub(super) fn create_turn_prelude(
&self,
force_integration_refresh: bool,
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs
index fd1d329616,d3e7ba8e47..5b40b807a2
--- a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs
@@@ -2,9 -2,12 +2,12 @@@
use std::sync::Arc;
-use tinyagents_runtime::ToolSnapshot;
+use tinyagents_harness::tool::ToolSnapshot;
use tinytools::ToolSpec;
+ #[cfg(feature = "flows")]
+ #[path = "runtime_session_flow_prompt_tests.rs"]
+ mod flow_prompt_tests;
#[path = "runtime_session_terminal_tests.rs"]
mod terminal_tests;
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
index 704bce5111,383b663e96..c67da8e253
--- a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
@@@ -188,50 -148,10 +192,50 @@@ impl OpenHumanSessionHost
let outcome = match Box::pin(turn).await {
Ok(outcome) => outcome,
Err(error) => {
+ drop(descendant_lease);
+ drop(root_cancellation);
- return Err(anyhow::anyhow!(error.to_string()));
+ return Err(runtime_turn_error(error, &session_sidecar));
}
};
- Ok(outcome.output.unwrap_or_default())
+ let mut output = outcome.output.unwrap_or_default();
+ if let Some(lease) = descendant_lease {
+ let deadline = settlement_deadline.expect("headless turns always have a deadline");
+ let jobs = lease
+ .settle(deadline, &cancellation)
+ .await
+ .map_err(|error| anyhow::anyhow!("settle headless sub-agent results: {error}"))?;
+ for job in jobs {
+ match job.status {
+ tinyagents_orchestration::subagent::SubAgentJobStatus::Completed => {
+ if let Some(child_output) =
+ job.output.filter(|text| !text.trim().is_empty())
+ {
+ output.push_str("\n\n[Sub-agent result: ");
+ output.push_str(&job.agent);
+ output.push_str("]\n");
+ output.push_str(&child_output);
+ }
+ }
+ status => {
+ return Err(anyhow::anyhow!(
+ "headless sub-agent '{}' ended with {status:?}: {}",
+ job.agent,
+ job.error.unwrap_or_else(|| "no error details".to_string())
+ ));
+ }
+ }
+ }
+ }
+ drop(root_cancellation);
+ Ok(output)
+ }
+}
+
+struct RootRunCancellationGuard(tinyagents_harness::cancel::CancellationToken);
+
+impl Drop for RootRunCancellationGuard {
+ fn drop(&mut self) {
+ self.0.cancel();
}
}
diff --cc crates/openhuman-core/src/agent/subagent_host/lifecycle_storage_adoption_tests.rs
index 2a2782e68d,3171c5886a..52183262de
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle_storage_adoption_tests.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_storage_adoption_tests.rs
@@@ -230,12 -219,11 +230,12 @@@ async fn a_detached_driver_uses_its_car
done.send(result).unwrap();
})
});
- // No ambient CoreContext is installed here. The actor is carried only
- // by the explicit parent, through the generic tool's real tokio::spawn.
let (_, bundle) = super::super::invoke_driver_tool_with_request(
&parent,
- request,
+ super::super::driver_adapter::HostRequest {
- invocation: definition,
++ invocation: super::super::HostInvocation::Agent(definition),
+ options,
+ },
"finish".into(),
"background",
Some(completion),
diff --cc crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
index 7729771ae2,b5aa371405..99b86958cc
--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
@@@ -19,6 -19,6 +19,14 @@@ use tinytools_agent::dialect::Transcrip
use super::transcript::persist_subagent_transcript;
use crate::threads::worker_mirror::mirror_worker_thread;
++#[path = "dispatch_helpers.rs"]
++mod helpers;
++pub(crate) use helpers::inherited_thread_id;
++use helpers::{
++ build_subagent_context_mw, cap_tool_results, map_tinyagents_subagent_error,
++ spawn_subagent_trace_export,
++};
++
/// Cumulative usage stats gathered across a sub-agent graph run.
#[derive(Debug, Clone, Default)]
pub(in super::super) struct AggregatedUsage {
@@@ -577,214 -566,159 +585,57 @@@ pub(in super::super) async fn run_subag
))
}
-fn spawn_subagent_trace_export(
- config: Option<&crate::config::Config>,
- dispatch: &crate::core::runtime::DispatchCtx,
- journal_run_id: Option<&str>,
- thread_id: Option<&str>,
- agent_id: &str,
- task_id: &str,
-) {
- let (Some(config), Some(journal_run_id)) = (
- config.filter(|config| config.observability.share_usage_data),
- journal_run_id,
- ) else {
- return;
- };
- let config = config.clone();
- let dispatch = dispatch.clone();
- let journal_run_id = journal_run_id.to_owned();
- let thread_id = thread_id.map(str::to_owned);
- let agent_id = agent_id.to_owned();
- let task_id = task_id.to_owned();
- tokio::spawn(async move {
- crate::core::observability::progress_tracing::export_subagent_journal_trace(
- &dispatch,
- &config,
- &journal_run_id,
- thread_id.as_deref(),
- &agent_id,
- &task_id,
- )
- .await;
- });
-}
-
-/// A task-specific thread explicitly routes a worker; an absent task thread
-/// leaves the parent run's transcript affinity intact.
-pub(crate) fn inherited_thread_id(
- parent_thread_id: Option<String>,
- task_thread_id: Option<String>,
-) -> Option<String> {
- task_thread_id.or(parent_thread_id)
-}
+/// Rebuilds the inherited channel ceiling for the child's callable tool set.
+/// A parent's `HideFromPrompt` entries describe only that parent's projection;
+/// carrying them forward would hide tools explicitly granted by the child
+/// definition. Explicit denials and approval requirements still narrow the
+/// child when they refer to tools in its resolved allowlist.
+pub(super) fn child_tool_policy(
+ parent: Option<&crate::agent::tinyagents::ToolPolicyEnforcement>,
+ child_agent_id: &str,
+ child_allowed_names: &HashSet<String>,
+ child_tools: &[&dyn Tool],
+) -> Option<crate::agent::tinyagents::ToolPolicyEnforcement> {
+ let parent = parent?;
+ let profile = &parent.session.profile;
+ let channel_permissions = [(
+ profile.channel.clone(),
+ profile.allowed_permission.to_string(),
+ )]
+ .into_iter()
+ .collect();
+ let mut session = tinytools::agent_policy::ToolPolicyEngine::build_session_from_refs(
+ child_agent_id,
+ profile.channel.clone(),
+ profile.entrypoint.clone(),
+ &channel_permissions,
+ child_tools,
+ child_allowed_names,
+ );
-/// Build the sub-agent turn's [`TurnContextMiddleware`] from the live
-/// `[context]` config and the agent's TokenJuice profile (#4466), mirroring the
-/// chat path (`session/turn/core.rs`). Falls back to
-/// [`TurnContextMiddleware::defaults`] when the config can't be loaded so a
-/// config glitch degrades to the safe (byte-cap-only) behavior rather than
-/// erroring the run.
-fn build_subagent_context_mw(
- tokenjuice_compression: AgentTokenjuiceCompression,
- config: Option<&crate::config::Config>,
-) -> crate::agent::tinyagents::middleware::turn_context::TurnContextMiddleware {
- let mut mw =
- crate::agent::tinyagents::middleware::turn_context::TurnContextMiddleware::defaults();
- // Always thread the agent's compression profile — even on the config-default
- // path — so the definition's TokenJuice choice is honored.
- mw.tokenjuice_compression = tokenjuice_compression;
- match config {
- Some(config) => {
- mw.runtime_config = Some(Arc::new(config.clone()));
- let ctx = &config.context;
- // TokenJuice content-aware compaction gates on the same master
- // `[context].compaction_enabled` the chat path reads
- // (`ContextConfig::compaction_enabled`).
- mw.tokenjuice_compaction_enabled =
- ctx.compaction_enabled && crate::inference::tokenjuice::enabled(config);
- mw.tool_result_budget_bytes = ctx.tool_result_budget_bytes;
- // Microcompact keep-recent is `0` (disabled) unless microcompact is on.
- mw.microcompact_keep_recent = if ctx.microcompact_enabled {
- ctx.microcompact_keep_recent
- } else {
- 0
- };
- // Summarization step honors the `[context].enabled` + autocompact
- // opt-outs, same as `ContextConfig::enabled && autocompact_enabled`.
- mw.autocompact_enabled = ctx.enabled && ctx.autocompact_enabled;
- mw.compaction = ctx.compaction_settings();
- tracing::debug!(
- tokenjuice_compaction_enabled = mw.tokenjuice_compaction_enabled,
- compression = ?mw.tokenjuice_compression,
- tool_result_budget_bytes = mw.tool_result_budget_bytes,
- microcompact_keep_recent = mw.microcompact_keep_recent,
- autocompact_enabled = mw.autocompact_enabled,
- "[subagent_host:graph] built sub-agent context middleware from config (#4466)"
- );
- }
- None => {
- tracing::debug!(
- "[subagent_host:graph] no config available building sub-agent context mw; using defaults + compression profile"
- );
+ for name in child_allowed_names {
+ let Some(decision) = parent.session.decisions.get(name) else {
+ continue;
+ };
+ if !matches!(
+ decision.action,
+ tinytools::ToolPolicyAction::Deny | tinytools::ToolPolicyAction::RequireApproval
+ ) {
+ continue;
}
+ session.decisions.insert(name.clone(), decision.clone());
+ session.allowed_tool_names.remove(name);
+ session.blocked_tool_names.insert(name.clone());
}
- mw
-}
-fn map_tinyagents_subagent_error(err: anyhow::Error) -> SubagentRunError {
- match err.downcast::<SubagentRunError>() {
- Ok(run_err) => run_err,
- Err(err) => SubagentRunError::Provider(err),
- }
+ Some(crate::agent::tinyagents::ToolPolicyEnforcement {
+ policy: parent.policy.clone(),
+ session,
+ channel: parent.channel.clone(),
+ agent_definition_id: child_agent_id.to_string(),
+ })
}
-/// Build the `tool → outcome` digest the cap-hit summary call summarizes, in the
-/// legacy `- {name} [{ok|failed}]: {output}` format (engine `run_tool_digest`),
-/// pairing each tool result back to its call by id. Per-tool success is derived
-/// from the turn's captured [`ToolCallOutcome`]s (#4467, item 7) rather than
-/// reported optimistically as `ok`: a result whose call has no captured outcome
-/// — e.g. a hallucinated/unknown tool the crate recovered without running
-/// `after_tool` — is marked `failed`, so the summary no longer tells the model
-/// every call succeeded.
-fn cap_tool_results<'a>(
- conversation: &'a [TranscriptEntry],
- tool_outcomes: &[tinyagents_harness::turn_outcome::ToolCallOutcome],
-) -> Vec<tinyagents_harness::summarization::CapToolResult<'a>> {
- use std::collections::HashMap;
- use tinyagents_harness::summarization::CapToolResult;
-
- // call_id -> tool name, from this turn's assistant tool-call rounds.
- let mut names: HashMap<&str, &str> = HashMap::new();
- for msg in conversation {
- if let TranscriptEntry::AssistantToolCalls { tool_calls, .. } = msg {
- for call in tool_calls {
- names.insert(call.id.as_str(), call.name.as_str());
- }
- }
- }
-
- // call_id -> success, from the captured per-call outcomes.
- let success_by_id: HashMap<&str, bool> = tool_outcomes
- .iter()
- .map(|o| (o.call_id.as_str(), o.success))
- .collect();
-
- let results: Vec<_> = conversation
- .iter()
- .filter_map(|entry| match entry {
- TranscriptEntry::ToolResults(results) => Some(results),
- _ => None,
- })
- .flatten()
- .map(|result| CapToolResult {
- call_id: &result.tool_call_id,
- name: names
- .get(result.tool_call_id.as_str())
- .copied()
- .unwrap_or("tool"),
- output: &result.content,
- // Missing outcome means the tool was never run successfully.
- success: success_by_id
- .get(result.tool_call_id.as_str())
- .copied()
- .unwrap_or(false),
- })
- .collect();
- results
-}
+#[cfg(test)]
+#[path = "dispatch_policy_tests.rs"]
+mod policy_tests;
-
- fn spawn_subagent_trace_export(
- config: Option<&crate::config::Config>,
- dispatch: &crate::core::runtime::DispatchCtx,
- journal_run_id: Option<&str>,
- thread_id: Option<&str>,
- agent_id: &str,
- task_id: &str,
- ) {
- let (Some(config), Some(journal_run_id)) = (
- config.filter(|config| config.observability.share_usage_data),
- journal_run_id,
- ) else {
- return;
- };
- let config = config.clone();
- let dispatch = dispatch.clone();
- let journal_run_id = journal_run_id.to_owned();
- let thread_id = thread_id.map(str::to_owned);
- let agent_id = agent_id.to_owned();
- let task_id = task_id.to_owned();
- tokio::spawn(async move {
- crate::core::observability::progress_tracing::export_subagent_journal_trace(
- &dispatch,
- &config,
- &journal_run_id,
- thread_id.as_deref(),
- &agent_id,
- &task_id,
- )
- .await;
- });
- }
-
- /// A task-specific thread explicitly routes a worker; an absent task thread
- /// leaves the parent run's transcript affinity intact.
- pub(crate) fn inherited_thread_id(
- parent_thread_id: Option<String>,
- task_thread_id: Option<String>,
- ) -> Option<String> {
- task_thread_id.or(parent_thread_id)
- }
-
- /// Build the sub-agent turn's [`TurnContextMiddleware`] from the live
- /// `[context]` config and the agent's TokenJuice profile (#4466), mirroring the
- /// chat path (`session/turn/core.rs`). Falls back to
- /// [`TurnContextMiddleware::defaults`] when the config can't be loaded so a
- /// config glitch degrades to the safe (byte-cap-only) behavior rather than
- /// erroring the run.
- fn build_subagent_context_mw(
- tokenjuice_compression: AgentTokenjuiceCompression,
- config: Option<&crate::config::Config>,
- ) -> crate::agent::tinyagents::middleware::turn_context::TurnContextMiddleware {
- let mut mw =
- crate::agent::tinyagents::middleware::turn_context::TurnContextMiddleware::defaults();
- // Always thread the agent's compression profile — even on the config-default
- // path — so the definition's TokenJuice choice is honored.
- mw.tokenjuice_compression = tokenjuice_compression;
- match config {
- Some(config) => {
- mw.runtime_config = Some(Arc::new(config.clone()));
- let ctx = &config.context;
- // TokenJuice content-aware compaction gates on the same master
- // `[context].compaction_enabled` the chat path reads
- // (`ContextConfig::compaction_enabled`).
- mw.tokenjuice_compaction_enabled =
- ctx.compaction_enabled && crate::inference::tokenjuice::enabled(config);
- mw.tool_result_budget_bytes = ctx.tool_result_budget_bytes;
- // Microcompact keep-recent is `0` (disabled) unless microcompact is on.
- mw.microcompact_keep_recent = if ctx.microcompact_enabled {
- ctx.microcompact_keep_recent
- } else {
- 0
- };
- // Summarization step honors the `[context].enabled` + autocompact
- // opt-outs, same as `ContextConfig::enabled && autocompact_enabled`.
- mw.autocompact_enabled = ctx.enabled && ctx.autocompact_enabled;
- mw.compaction = ctx.compaction_settings();
- tracing::debug!(
- tokenjuice_compaction_enabled = mw.tokenjuice_compaction_enabled,
- compression = ?mw.tokenjuice_compression,
- tool_result_budget_bytes = mw.tool_result_budget_bytes,
- microcompact_keep_recent = mw.microcompact_keep_recent,
- autocompact_enabled = mw.autocompact_enabled,
- "[subagent_host:graph] built sub-agent context middleware from config (#4466)"
- );
- }
- None => {
- tracing::debug!(
- "[subagent_host:graph] no config available building sub-agent context mw; using defaults + compression profile"
- );
- }
- }
- mw
- }
-
- fn map_tinyagents_subagent_error(err: anyhow::Error) -> SubagentRunError {
- match err.downcast::<SubagentRunError>() {
- Ok(run_err) => run_err,
- Err(err) => SubagentRunError::Provider(err),
- }
- }
-
- /// Build the `tool → outcome` digest the cap-hit summary call summarizes, in the
- /// legacy `- {name} [{ok|failed}]: {output}` format (engine `run_tool_digest`),
- /// pairing each tool result back to its call by id. Per-tool success is derived
- /// from the turn's captured [`ToolCallOutcome`]s (#4467, item 7) rather than
- /// reported optimistically as `ok`: a result whose call has no captured outcome
- /// — e.g. a hallucinated/unknown tool the crate recovered without running
- /// `after_tool` — is marked `failed`, so the summary no longer tells the model
- /// every call succeeded.
- fn cap_tool_results<'a>(
- conversation: &'a [TranscriptEntry],
- tool_outcomes: &[tinyagents_harness::turn_outcome::ToolCallOutcome],
- ) -> Vec<tinyagents_harness::summarization::CapToolResult<'a>> {
- use std::collections::HashMap;
- use tinyagents_harness::summarization::CapToolResult;
-
- // call_id -> tool name, from this turn's assistant tool-call rounds.
- let mut names: HashMap<&str, &str> = HashMap::new();
- for msg in conversation {
- if let TranscriptEntry::AssistantToolCalls { tool_calls, .. } = msg {
- for call in tool_calls {
- names.insert(call.id.as_str(), call.name.as_str());
- }
- }
- }
-
- // call_id -> success, from the captured per-call outcomes.
- let success_by_id: HashMap<&str, bool> = tool_outcomes
- .iter()
- .map(|o| (o.call_id.as_str(), o.success))
- .collect();
-
- let results: Vec<_> = conversation
- .iter()
- .filter_map(|entry| match entry {
- TranscriptEntry::ToolResults(results) => Some(results),
- _ => None,
- })
- .flatten()
- .map(|result| CapToolResult {
- call_id: &result.tool_call_id,
- name: names
- .get(result.tool_call_id.as_str())
- .copied()
- .unwrap_or("tool"),
- output: &result.content,
- // Missing outcome means the tool was never run successfully.
- success: success_by_id
- .get(result.tool_call_id.as_str())
- .copied()
- .unwrap_or(false),
- })
- .collect();
- results
- }
diff --cc crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch_helpers.rs
index 0000000000,0000000000..712afbbab3
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch_helpers.rs
@@@ -1,0 -1,0 +1,158 @@@
++use super::*;
++
++pub(super) fn spawn_subagent_trace_export(
++ config: Option<&crate::config::Config>,
++ dispatch: &crate::core::runtime::DispatchCtx,
++ journal_run_id: Option<&str>,
++ thread_id: Option<&str>,
++ agent_id: &str,
++ task_id: &str,
++) {
++ let (Some(config), Some(journal_run_id)) = (
++ config.filter(|config| config.observability.share_usage_data),
++ journal_run_id,
++ ) else {
++ return;
++ };
++ let config = config.clone();
++ let dispatch = dispatch.clone();
++ let journal_run_id = journal_run_id.to_owned();
++ let thread_id = thread_id.map(str::to_owned);
++ let agent_id = agent_id.to_owned();
++ let task_id = task_id.to_owned();
++ tokio::spawn(async move {
++ crate::core::observability::progress_tracing::export_subagent_journal_trace(
++ &dispatch,
++ &config,
++ &journal_run_id,
++ thread_id.as_deref(),
++ &agent_id,
++ &task_id,
++ )
++ .await;
++ });
++}
++
++/// A task-specific thread explicitly routes a worker; an absent task thread
++/// leaves the parent run's transcript affinity intact.
++pub(crate) fn inherited_thread_id(
++ parent_thread_id: Option<String>,
++ task_thread_id: Option<String>,
++) -> Option<String> {
++ task_thread_id.or(parent_thread_id)
++}
++
++/// Build the sub-agent turn's [`TurnContextMiddleware`] from the live
++/// `[context]` config and the agent's TokenJuice profile (#4466), mirroring the
++/// chat path (`session/turn/core.rs`). Falls back to
++/// [`TurnContextMiddleware::defaults`] when the config can't be loaded so a
++/// config glitch degrades to the safe (byte-cap-only) behavior rather than
++/// erroring the run.
++pub(super) fn build_subagent_context_mw(
++ tokenjuice_compression: AgentTokenjuiceCompression,
++ config: Option<&crate::config::Config>,
++) -> crate::agent::tinyagents::middleware::turn_context::TurnContextMiddleware {
++ let mut mw =
++ crate::agent::tinyagents::middleware::turn_context::TurnContextMiddleware::defaults();
++ // Always thread the agent's compression profile — even on the config-default
++ // path — so the definition's TokenJuice choice is honored.
++ mw.tokenjuice_compression = tokenjuice_compression;
++ match config {
++ Some(config) => {
++ mw.runtime_config = Some(Arc::new(config.clone()));
++ let ctx = &config.context;
++ // TokenJuice content-aware compaction gates on the same master
++ // `[context].compaction_enabled` the chat path reads
++ // (`ContextConfig::compaction_enabled`).
++ mw.tokenjuice_compaction_enabled =
++ ctx.compaction_enabled && crate::inference::tokenjuice::enabled(config);
++ mw.tool_result_budget_bytes = ctx.tool_result_budget_bytes;
++ // Microcompact keep-recent is `0` (disabled) unless microcompact is on.
++ mw.microcompact_keep_recent = if ctx.microcompact_enabled {
++ ctx.microcompact_keep_recent
++ } else {
++ 0
++ };
++ // Summarization step honors the `[context].enabled` + autocompact
++ // opt-outs, same as `ContextConfig::enabled && autocompact_enabled`.
++ mw.autocompact_enabled = ctx.enabled && ctx.autocompact_enabled;
++ mw.compaction = ctx.compaction_settings();
++ tracing::debug!(
++ tokenjuice_compaction_enabled = mw.tokenjuice_compaction_enabled,
++ compression = ?mw.tokenjuice_compression,
++ tool_result_budget_bytes = mw.tool_result_budget_bytes,
++ microcompact_keep_recent = mw.microcompact_keep_recent,
++ autocompact_enabled = mw.autocompact_enabled,
++ "[subagent_host:graph] built sub-agent context middleware from config (#4466)"
++ );
++ }
++ None => {
++ tracing::debug!(
++ "[subagent_host:graph] no config available building sub-agent context mw; using defaults + compression profile"
++ );
++ }
++ }
++ mw
++}
++
++pub(super) fn map_tinyagents_subagent_error(err: anyhow::Error) -> SubagentRunError {
++ match err.downcast::<SubagentRunError>() {
++ Ok(run_err) => run_err,
++ Err(err) => SubagentRunError::Provider(err),
++ }
++}
++
++/// Build the `tool → outcome` digest the cap-hit summary call summarizes, in the
++/// legacy `- {name} [{ok|failed}]: {output}` format (engine `run_tool_digest`),
++/// pairing each tool result back to its call by id. Per-tool success is derived
++/// from the turn's captured [`ToolCallOutcome`]s (#4467, item 7) rather than
++/// reported optimistically as `ok`: a result whose call has no captured outcome
++/// — e.g. a hallucinated/unknown tool the crate recovered without running
++/// `after_tool` — is marked `failed`, so the summary no longer tells the model
++/// every call succeeded.
++pub(super) fn cap_tool_results<'a>(
++ conversation: &'a [TranscriptEntry],
++ tool_outcomes: &[tinyagents_harness::turn_outcome::ToolCallOutcome],
++) -> Vec<tinyagents_harness::summarization::CapToolResult<'a>> {
++ use std::collections::HashMap;
++ use tinyagents_harness::summarization::CapToolResult;
++
++ // call_id -> tool name, from this turn's assistant tool-call rounds.
++ let mut names: HashMap<&str, &str> = HashMap::new();
++ for msg in conversation {
++ if let TranscriptEntry::AssistantToolCalls { tool_calls, .. } = msg {
++ for call in tool_calls {
++ names.insert(call.id.as_str(), call.name.as_str());
++ }
++ }
++ }
++
++ // call_id -> success, from the captured per-call outcomes.
++ let success_by_id: HashMap<&str, bool> = tool_outcomes
++ .iter()
++ .map(|o| (o.call_id.as_str(), o.success))
++ .collect();
++
++ let results: Vec<_> = conversation
++ .iter()
++ .filter_map(|entry| match entry {
++ TranscriptEntry::ToolResults(results) => Some(results),
++ _ => None,
++ })
++ .flatten()
++ .map(|result| CapToolResult {
++ call_id: &result.tool_call_id,
++ name: names
++ .get(result.tool_call_id.as_str())
++ .copied()
++ .unwrap_or("tool"),
++ output: &result.content,
++ // Missing outcome means the tool was never run successfully.
++ success: success_by_id
++ .get(result.tool_call_id.as_str())
++ .copied()
++ .unwrap_or(false),
++ })
++ .collect();
++ results
++}
diff --cc crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 1da2dcbf7b,8c05862c23..627af60bb5
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@@ -647,8 -538,10 +547,11 @@@ impl OpenHumanRunContext
child.dispatch = None;
child.subagent_usage = Arc::new(Mutex::new(Vec::new()));
child.parent_subagent_usage = None;
+ // Detached work has its own terminal boundary; its typed refusal must
+ // never be mistaken for the interactive parent's failure.
+ child.session_sidecar = Arc::new(Mutex::new(SessionTurnSidecar::default()));
child.cancellation = tinyagents_harness::cancel::CancellationToken::new();
+ child.headless_descendant_settlement = false;
child
}
diff --cc crates/openhuman-core/src/agent/tinyagents/observability.rs
index 1dbda13b1e,1dbda13b1e..8c20304103
--- a/crates/openhuman-core/src/agent/tinyagents/observability.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability.rs
@@@ -9,6 -9,6 +9,8 @@@
//! tinyagents path — and feeds per-call usage into the global cost tracker.
mod bridge_types;
++#[path = "observability_cache_projection.rs"]
++mod cache_projection;
mod event_bridge;
mod event_projection;
mod tool_progress_projection;
@@@ -23,8 -23,8 +25,8 @@@ use tinyinference_llm::usage::Usage
use crate::progress::AgentProgress;
pub(crate) use bridge_types::{ProviderUsageCarry, SubagentScope, ToolFailureMap, ToolNameMap};
++pub(crate) use cache_projection::surface_cache_layout_events;
pub(crate) use event_bridge::OpenhumanEventBridge;
--pub(crate) use event_projection::surface_cache_layout_events;
#[cfg(test)]
#[path = "observability_tests.rs"]
diff --cc crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
index 25c6d9be3e,71eda602ca..8defb7c6e0
--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
@@@ -2,7 -2,9 +2,8 @@@
//! each `tinyagents` [`AgentEvent`] onto an [`AgentProgress`] update (or a
//! grep-friendly trace lines for events with no UI surface.
- use tinyagents_harness::cache::CacheLayoutEvent;
+ use std::sync::atomic::Ordering;
+
-use tinyagents_harness::cache::CacheLayoutEvent;
use tinyagents_harness::events::{AgentEvent, EventListener, EventRecord};
use crate::progress::AgentProgress;
@@@ -724,27 -736,27 +735,3 @@@ impl OpenhumanEventBridge
})
}
}
--
--/// Surface the crate `PromptCacheGuardMiddleware`'s recorded
--/// [`CacheLayoutEvent`]s as structured `[cache]` warnings (issue #4249, 03.2).
--///
--/// The guard records a layout event whenever the cacheable prompt prefix changes
--/// between turns (volatile content — a timestamp, uuid, injected memory, etc. —
--/// silently busting the provider KV-cache prefix). This is the crate-native
--/// replacement for the deleted `CacheAlignMiddleware` free-text warn-log:
--/// instead of a token-pattern heuristic it reports the exact before/after
--/// cacheable segment ids. Drained by the turn loop after the run and logged
--/// here. The warn-only `CacheAlignMiddleware` shadow was deleted in C3; this
--/// guard is now the sole owner of KV-cache-prefix drift detection.
--pub(crate) fn surface_cache_layout_events(model: &str, events: &[CacheLayoutEvent]) {
-- for event in events {
-- tracing::warn!(
-- model,
-- changed_prefix = event.changed_prefix,
-- volatile_only = event.volatile_only,
-- segments_before = ?event.segment_ids_before,
-- segments_after = ?event.segment_ids_after,
-- "[cache] prompt-cache prefix changed across turns — KV-cache prefix may not hit; keep dynamic content out of the system prompt / stable tool set"
-- );
-- }
--}
diff --cc crates/openhuman-core/src/agent/tinyagents/observability_cache_projection.rs
index 0000000000,0000000000..b9f4492a59
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/observability_cache_projection.rs
@@@ -1,0 -1,0 +1,25 @@@
++use tinyagents_harness::cache::CacheLayoutEvent;
++
++/// Surface the crate `PromptCacheGuardMiddleware`'s recorded
++/// [`CacheLayoutEvent`]s as structured `[cache]` warnings (issue #4249, 03.2).
++///
++/// The guard records a layout event whenever the cacheable prompt prefix changes
++/// between turns (volatile content — a timestamp, uuid, injected memory, etc. —
++/// silently busting the provider KV-cache prefix). This is the crate-native
++/// replacement for the deleted `CacheAlignMiddleware` free-text warn-log:
++/// instead of a token-pattern heuristic it reports the exact before/after
++/// cacheable segment ids. Drained by the turn loop after the run and logged
++/// here. The warn-only `CacheAlignMiddleware` shadow was deleted in C3; this
++/// guard is now the sole owner of KV-cache-prefix drift detection.
++pub(crate) fn surface_cache_layout_events(model: &str, events: &[CacheLayoutEvent]) {
++ for event in events {
++ tracing::warn!(
++ model,
++ changed_prefix = event.changed_prefix,
++ volatile_only = event.volatile_only,
++ segments_before = ?event.segment_ids_before,
++ segments_after = ?event.segment_ids_after,
++ "[cache] prompt-cache prefix changed across turns — KV-cache prefix may not hit; keep dynamic content out of the system prompt / stable tool set"
++ );
++ }
++}
diff --cc crates/openhuman-core/src/agent/tinyagents/observability_progress_tests.rs
index 0000000000,0000000000..b007e6c4eb
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/observability_progress_tests.rs
@@@ -1,0 -1,0 +1,38 @@@
++use super::*;
++
++/// A running tool's progress report reaches the web channel as
++/// `ToolCallProgress` for the same call; an update with no message does not.
++#[tokio::test]
++async fn bridge_forwards_tool_progress_with_a_message() {
++ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
++ let bridge = OpenhumanEventBridge::new(Some(tx), "mock-model", 10);
++ let sink = EventSink::new();
++ sink.subscribe(bridge.clone());
++
++ sink.emit(AgentEvent::ToolProgressDetail {
++ call_id: "c1".into(),
++ message: "running 4m 12s · 38.2 KB output".to_string(),
++ fraction: None,
++ partial: None,
++ });
++ sink.emit(AgentEvent::ToolProgressDetail {
++ call_id: "c1".into(),
++ message: String::new(),
++ fraction: Some(0.5),
++ partial: None,
++ });
++
++ let mut progress = Vec::new();
++ while let Ok(p) = rx.try_recv() {
++ if let AgentProgress::ToolCallProgress { call_id, message } = p {
++ progress.push((call_id, message));
++ }
++ }
++ assert_eq!(
++ progress,
++ vec![(
++ "c1".to_string(),
++ "running 4m 12s · 38.2 KB output".to_string()
++ )]
++ );
++}
diff --cc crates/openhuman-core/src/agent/tinyagents/observability_tests.rs
index e57481696c,d113168b98..6a15ac0004
--- a/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs
@@@ -640,39 -711,70 +711,36 @@@ async fn tool_call_events_use_the_tool_
);
}
--/// A running tool's progress report reaches the web channel as
--/// `ToolCallProgress` for the same call; an update with no message does not.
--#[tokio::test]
--async fn bridge_forwards_tool_progress_with_a_message() {
-- let (tx, mut rx) = tokio::sync::mpsc::channel(64);
-- let bridge = OpenhumanEventBridge::new(Some(tx), "mock-model", 10);
-- let sink = EventSink::new();
-- sink.subscribe(bridge.clone());
-
- sink.emit(AgentEvent::ToolProgressDetail {
- call_id: "c1".into(),
- message: "running 4m 12s · 38.2 KB output".to_string(),
- fraction: None,
- partial: None,
- });
- sink.emit(AgentEvent::ToolProgressDetail {
- call_id: "c1".into(),
- message: String::new(),
- fraction: Some(0.5),
- partial: None,
- });
-
- let mut progress = Vec::new();
- while let Ok(p) = rx.try_recv() {
- if let AgentProgress::ToolCallProgress { call_id, message } = p {
- progress.push((call_id, message));
- }
- }
- assert_eq!(
- progress,
- vec![(
- "c1".to_string(),
- "running 4m 12s · 38.2 KB output".to_string()
- )]
- );
-}
++#[path = "observability_progress_tests.rs"]
++mod progress_tests;
- sink.emit(AgentEvent::ToolProgressDetail {
- call_id: "c1".into(),
- message: "running 4m 12s · 38.2 KB output".to_string(),
- fraction: None,
- partial: None,
- });
- sink.emit(AgentEvent::ToolProgressDetail {
- call_id: "c1".into(),
- message: String::new(),
- fraction: Some(0.5),
- partial: None,
- });
-
- let mut progress = Vec::new();
- while let Ok(p) = rx.try_recv() {
- if let AgentProgress::ToolCallProgress { call_id, message } = p {
- progress.push((call_id, message));
- }
- }
- assert_eq!(
- progress,
- vec![(
- "c1".to_string(),
- "running 4m 12s · 38.2 KB output".to_string()
- )]
- );
+ #[tokio::test]
+ async fn only_a_top_level_turn_announces_its_compaction() {
+ let (tx, mut rx) = tokio::sync::mpsc::channel(8);
+ OpenhumanEventBridge::new(Some(tx), "mock-model", 10).announce_compaction();
+ assert!(matches!(
+ rx.try_recv(),
+ Ok(AgentProgress::ContextCompacting)
+ ));
+
+ let (tx, mut rx) = tokio::sync::mpsc::channel(8);
+ OpenhumanEventBridge::with_scope(
+ Some(tx),
+ "mock-model",
+ "custom",
+ 10,
+ Some(SubagentScope {
+ agent_id: "researcher".into(),
+ task_id: "t1".into(),
+ extended_policy: false,
+ }),
+ Arc::default(),
+ Arc::default(),
+ Arc::default(),
+ Arc::default(),
+ Vec::new(),
+ crate::core::runtime::DispatchCtx::unbound(),
+ )
+ .announce_compaction();
+ assert!(rx.try_recv().is_err());
}
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
index 9ef6b8cc06,fe1325d4ae..d045a5fb8a
--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
@@@ -8,13 -8,12 +8,12 @@@
//! finalize the run into a [`TinyagentsTurnOutcome`].
use std::collections::{BTreeSet, HashSet};
--use std::sync::{Arc, LazyLock};
++use std::sync::Arc;
use anyhow::Result;
--use tinyagents_harness::runtime::AgentHarness;
use tinyagents_harness::runtime::{AgentInvocation, AgentTurnRequest, InvocationRuntime};
use tinyagents_harness::store::{InMemoryStore as ToolResultArtifactIndexStore, StoreRegistry};
+use tinyagents_harness::tool::ToolSnapshot;
use tinyagents_harness::turn_policy::effective_max_iterations;
use tinyagents_runtime::turn_driver::{
SubagentScope as DriverSubagentScope, TurnControls, TurnDriver, TurnScope,
@@@ -45,18 -44,18 +44,8 @@@ use tinyagents_harness::turn_outcome::T
use tinyagents_session::transcript::TranscriptMessage;
use super::ToolPolicyEnforcement;
--
--/// The durable root entry point for hosted turns. It intentionally carries no
--/// product authority: models, tools, middleware, progress and host capabilities
--/// are attached through an [`InvocationRuntime`] and [`AgentInvocation`] for
--/// each root. That prevents concurrent sessions from replacing one another's
--/// security or workspace state on a shared harness.
--static ROOT_HOSTED_HARNESS: LazyLock<AgentHarness<(), OpenHumanRunContext>> =
-- LazyLock::new(AgentHarness::new);
--
--fn root_hosted_harness() -> &'static AgentHarness<(), OpenHumanRunContext> {
-- &ROOT_HOSTED_HARNESS
--}
++mod root_hosted_harness;
++use root_hosted_harness::root_hosted_harness;
#[cfg(test)]
#[path = "turn_exec_tests.rs"]
@@@ -179,31 -178,13 +168,34 @@@ async fn drive_turn
// otherwise the harness model-call cap would be zero and abort the run before
// the first provider call.
let max_iterations = effective_max_iterations(max_iterations);
- let hosted_security_gate = hosted_root.is_some();
+ let native_security_gate = if hosted_root.is_none() {
+ native_subagent.as_ref().and_then(|native| {
+ run_context.hosted_base.as_ref().map(|base| {
+ let mut gate = crate::agent::tinyagents::host::OpenHumanSecurityGate::new(
+ base.security_policy.clone(),
+ tool_sets.clone(),
+ )
+ .with_input_screening(!run_context.untrusted_input_turn)
+ .with_approval(run_context.approval.clone())
+ .with_dispatch(run_context.dispatch_ctx())
+ .with_headless_descendant_settlement(run_context.headless_descendant_settlement);
+ if let Some(policy) = tool_policy.as_ref() {
+ gate = gate.with_tool_policy(Arc::new(policy.session.clone()));
+ }
+ (Arc::new(gate), native.name.clone())
+ })
+ })
+ } else {
+ None
+ };
+ let is_hosted_root = hosted_root.is_some();
+ let hosted_security_gate = is_hosted_root || native_security_gate.is_some();
let is_local = turn_models.is_local();
// Wrap concrete routes before the invocation-local hosted resolver captures them.
- let turn_models = turn_models.with_budget(run_context.model_budget.as_ref());
+ let turn_models = turn_models.with_host_controls(
+ run_context.model_budget.as_ref(),
+ run_context.dispatch_admission.clone(),
+ );
let hosted_model_resolver = hosted_root.as_ref().map(|_| {
Arc::new(turn_models.resolver()) as Arc<dyn tinyagents_harness::host::ModelResolver<()>>
});
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_exec/root_hosted_harness.rs
index 0000000000,0000000000..3715afedbb
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec/root_hosted_harness.rs
@@@ -1,0 -1,0 +1,16 @@@
++//! Shared, stateless harness used for durable hosted root turns.
++
++use std::sync::LazyLock;
++use tinyagents_harness::runtime::AgentHarness;
++
++use crate::agent::tinyagents::host::OpenHumanRunContext;
++
++/// The durable root entry point carries no product authority. Models, tools,
++/// middleware, progress, and host capabilities are attached per invocation,
++/// preventing concurrent sessions from replacing one another's host state.
++static ROOT_HOSTED_HARNESS: LazyLock<AgentHarness<(), OpenHumanRunContext>> =
++ LazyLock::new(AgentHarness::new);
++
++pub(super) fn root_hosted_harness() -> &'static AgentHarness<(), OpenHumanRunContext> {
++ &ROOT_HOSTED_HARNESS
++}
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
index 7254c80841,5afdbad5cd..c2b0dc2821
--- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
@@@ -44,6 -40,6 +44,9 @@@ use crate::agent::tinyagents::verify_be
use crate::inference::provider::model::TurnChatModel;
use super::ToolPolicyEnforcement;
++#[path = "turn_native_security.rs"]
++mod native_security;
++use native_security::NativeSubagentSecurityMiddleware;
/// What the middleware stack needs to know about the turn.
pub(super) struct TurnMiddlewareInputs {
@@@ -523,13 -515,6 +526,12 @@@ pub(super) fn install_turn_middleware
// `ApprovalGate`, a denial short-circuits with a model-consumable result, and
// an approved call records a terminal audit row. Replaces the inline approval
// block that used to live in the legacy tool adapter.
+ let native_security_gate_installed = native_security_gate.is_some();
+ if let Some((gate, agent_id)) = native_security_gate {
- harness.push_tool_middleware(Arc::new(NativeSubagentSecurityMiddleware {
- gate,
- agent_id,
- }));
++ harness.push_tool_middleware(Arc::new(NativeSubagentSecurityMiddleware::new(
++ gate, agent_id,
++ )));
+ }
if !hosted_security_gate {
harness.push_tool_middleware(Arc::new(ApprovalGateMiddleware::new(
"approval_security",
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_native_security.rs
index 0000000000,0000000000..f70880fe23
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_native_security.rs
@@@ -1,0 -1,0 +1,112 @@@
++use super::*;
++
++pub(super) struct NativeSubagentSecurityMiddleware {
++ gate: Arc<OpenHumanSecurityGate>,
++ agent_id: String,
++}
++
++impl NativeSubagentSecurityMiddleware {
++ pub(super) fn new(gate: Arc<OpenHumanSecurityGate>, agent_id: String) -> Self {
++ Self { gate, agent_id }
++ }
++}
++
++#[async_trait]
++impl ToolMiddleware<(), OpenHumanRunContext> for NativeSubagentSecurityMiddleware {
++ fn name(&self) -> &str {
++ "openhuman_security_gate"
++ }
++
++ async fn wrap_tool(
++ &self,
++ ctx: &tinyagents_harness::context::RunContext<OpenHumanRunContext>,
++ state: &(),
++ call: tinyinference_llm::tool::ToolCall,
++ next: ToolHandler<'_, (), OpenHumanRunContext>,
++ ) -> tinyagents_harness::error::Result<MiddlewareToolOutcome> {
++ let call_id = call.id.to_string();
++ let request = ToolCallRequest::new(
++ call.name.clone(),
++ call.arguments.clone(),
++ self.agent_id.clone(),
++ )
++ .with_call_id(call_id.clone());
++ let decision = match self.gate.authorize_tool(&request).await {
++ Ok(decision) => decision,
++ Err(error) => {
++ tracing::error!(tool = %call.name, %error, "native child authorization failed closed");
++ return Ok(tinytools::ToolResult::error(
++ "Tool authorization failed because the security check could not complete.",
++ )
++ .into());
++ }
++ };
++ match decision {
++ GateDecision::Allow | GateDecision::Prompted { approved: true } => {}
++ GateDecision::Deny { reason } => {
++ return Ok(tinytools::ToolResult::error(reason).into());
++ }
++ GateDecision::Prompted { approved: false } => {
++ return Ok(tinytools::ToolResult::error("Approval was not granted.").into());
++ }
++ }
++
++ let mut audit = self
++ .gate
++ .take_audit_request_id(&call_id)
++ .map(NativeSecurityAudit::new);
++ let result = next.run(ctx, state, call).await;
++ if let Some(audit) = &mut audit {
++ match &result {
++ Ok(MiddlewareToolOutcome::Result(result)) if result.is_error => {
++ audit.record(
++ crate::security::approval::ExecutionOutcome::Failure,
++ Some(result.output()),
++ );
++ }
++ Ok(_) => audit.record(crate::security::approval::ExecutionOutcome::Success, None),
++ Err(error) => audit.record(
++ crate::security::approval::ExecutionOutcome::Failure,
++ Some(error.to_string()),
++ ),
++ }
++ }
++ result
++ }
++}
++
++struct NativeSecurityAudit {
++ request_id: String,
++ recorded: bool,
++}
++
++impl NativeSecurityAudit {
++ fn new(request_id: String) -> Self {
++ Self {
++ request_id,
++ recorded: false,
++ }
++ }
++
++ fn record(
++ &mut self,
++ execution: crate::security::approval::ExecutionOutcome,
++ error: Option<String>,
++ ) {
++ if let Some(gate) = crate::security::approval::ApprovalGate::try_global() {
++ gate.record_execution(&self.request_id, execution, error.as_deref());
++ }
++ self.recorded = true;
++ }
++}
++
++impl Drop for NativeSecurityAudit {
++ fn drop(&mut self) {
++ if !self.recorded {
++ self.record(
++ crate::security::approval::ExecutionOutcome::Failure,
++ Some("tool execution ended before reporting a result".to_string()),
++ );
++ }
++ }
++}
diff --cc crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rs
index 77893198e0,3596c2ddc3..a1698d66f0
--- a/crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rs
@@@ -115,13 -165,12 +164,12 @@@ fn on_belt(def: &AgentDefinition, tool
}
}
- /// Can this built-in definition call `tool` from its own (root) tool belt?
- /// Child-run spawn stripping is checked separately during child tool prep;
- /// here a parent definition such as the orchestrator may call its registered
- /// spawn and continuation tools.
+ /// Can `def` call `tool`? Its belt, less what it disallows and what the pack
+ /// table withholds from it — plus `use_skill`, which the harness advertises
+ /// whenever the pack table withheld something (`strip_packed_from_visible`).
fn can_call(def: &AgentDefinition, tool: &str, universe: &BTreeSet<String>) -> bool {
use crate::tools::toolpacks::ops::is_withheld_from;
- if tool == tinyagents_harness::tool::packs::USE_SKILL {
+ if tool == tinyagents_harness_tools::skills::USE_SKILL {
return universe
.iter()
.any(|n| on_belt(def, n) && is_withheld_from(&def.id, n));
diff --cc crates/openhuman-core/src/artifacts/ops.rs
index 0b9b829a41,e1ec9edc86..f81f3a0dc7
--- a/crates/openhuman-core/src/artifacts/ops.rs
+++ b/crates/openhuman-core/src/artifacts/ops.rs
@@@ -318,7 -290,6 +290,7 @@@ pub async fn ai_save_artifact_version
super::files::FileRoots::from_config(config),
artifact_id,
body,
- ctx,
++ &crate::core::runtime::DispatchCtx::ambient(),
)
.await?;
log::debug!(
@@@ -341,18 -312,16 +313,16 @@@ pub async fn ai_share_artifact
artifact_id: &str,
version: Option<u32>,
public: bool,
- ctx: &crate::core::runtime::DispatchCtx,
) -> Result<Outcome<Value>, String> {
- let publisher = super::artifact_publisher_in(config, ctx)
+ let publisher = super::artifact_publisher(config)
.ok_or_else(|| "sign in to share artifacts".to_string())?;
- let artifacts = super::tiny_store::artifacts_service(
+ let artifacts = super::tiny_store::artifacts_service_with_publisher(
&config.workspace_dir,
super::files::FileRoots::from_config(config),
None,
None,
- ctx,
- )
- .with_publisher(publisher);
+ Some(&publisher),
+ );
let options = tiny_artifacts::PublishOptions {
public,
..tiny_artifacts::PublishOptions::default()
diff --cc crates/openhuman-core/src/artifacts/preview.rs
index e82760d8b3,95b2dadc1c..cd79f27f7e
--- a/crates/openhuman-core/src/artifacts/preview.rs
+++ b/crates/openhuman-core/src/artifacts/preview.rs
@@@ -45,13 -46,11 +46,11 @@@ pub struct ArtifactBody
///
/// Returns an error when the artifact does not exist or its record cannot be
/// read.
- pub async fn read_body(
- config: &Config,
- id: &str,
- ctx: &crate::core::runtime::DispatchCtx,
- ) -> Result<ArtifactBody, String> {
+ pub async fn read_body(config: &Config, id: &str) -> Result<ArtifactBody, String> {
let files = super::files::FileRoots::from_config(config);
- let (artifacts, file_store) = super::tiny_store::artifacts_service_with_file_store(
+ let mut roots =
+ super::tiny_store::file_roots(&config.workspace_dir, &files, Some(&config.action_dir));
- let versioned = super::tiny_store::artifacts_service(
++ let versioned = super::tiny_store::artifacts_service_current(
&config.workspace_dir,
files.clone(),
Some(&config.action_dir),
@@@ -63,24 -63,29 +63,35 @@@
Some(record) => record,
// An artifact made before versioning has only its legacy record: show
// the file that record vouches for.
- None => legacy_record(&config.workspace_dir, &files, id, file_store.as_ref(), ctx).await?,
+ None => {
+ let record = legacy_record(&config.workspace_dir, &files, id).await?;
+ if let Some(folder) = record
+ .latest()
+ .and_then(|v| v.file.as_ref())
+ .and_then(|f| Path::new(&f.key).parent())
+ {
+ roots.push(folder.to_path_buf());
+ }
+ record
+ }
};
- // A version's file is kept under a storage key inside the version files
- // folder; show it by the path it has on disk. A legacy absolute key stays
- // as it is, since joining an absolute path replaces the base.
- let kept = super::tiny_store::version_files_dir(&config.workspace_dir);
+ if let Some(file) = record.versions.last_mut().and_then(|v| v.file.as_mut()) {
- file.key = kept.join(&file.key).display().to_string();
++ // Version bytes live in the acting tenant's blob store. The legacy
++ // card bridge materializes the current version into its guarded,
++ // user-visible file path; preview reads that same path.
++ if let Ok(path) = super::files::resolve_ready_file(&config.workspace_dir, &files, id).await
++ {
++ file.key = path.display().to_string();
++ } else {
++ file.key = super::tiny_store::stored_file_path(&config.workspace_dir, file)
++ .display()
++ .to_string();
++ }
+ }
let converter = DocumentConverter::for_config(config);
- let display_path = ctx
- .enter(async {
- match super::store::get_artifact(&config.workspace_dir, id).await {
- Ok(meta) => super::files::resolve_file(&config.workspace_dir, &meta, &files)
- .await
- .ok()
- .map(|path| path.to_string_lossy().into_owned()),
- Err(_) => None,
- }
- })
- .await;
Ok(body_of(
&record,
- file_store.as_ref(),
- display_path.as_deref(),
+ &super::tiny_store::guarded_roots(roots),
&converter,
)
.await)
diff --cc crates/openhuman-core/src/artifacts/production.rs
index 8eca4b4079,18e303a424..ae6d8ef8de
--- a/crates/openhuman-core/src/artifacts/production.rs
+++ b/crates/openhuman-core/src/artifacts/production.rs
@@@ -18,11 -18,11 +18,12 @@@
//! always has its versioned record.
use std::path::{Path, PathBuf};
++use std::sync::Arc;
use tiny_artifacts::{ArtifactKind, Artifacts, Author, Content};
use super::files::FileRoots;
- use super::tiny_store::legacy_kind_for_extension;
-use super::tiny_store::{artifacts_service, legacy_kind_for_extension};
++use super::tiny_store::{artifacts_service_current, legacy_kind_for_extension};
use super::types::ArtifactKind as LegacyArtifactKind;
use crate::security::approval::ApprovalChatContext;
@@@ -136,32 -80,21 +81,21 @@@ impl Production
legacy_kind_for_extension(&extension.to_ascii_lowercase())
};
let target = revise.filter(|id| !id.trim().is_empty());
- let (artifacts, file_store) = super::tiny_store::build_artifacts_service_with_scope(
+ let (meta, path) = super::store::create_artifact_regenerating(
workspace_dir,
files.clone(),
- None,
+ legacy_kind,
+ title,
+ extension,
+ tool_call_id,
+ target,
chat,
- ctx,
- scoped,
- None,
- );
- let file_store =
- file_store.ok_or_else(|| "artifact tenant storage is unavailable".to_string())?;
- let (meta, path) = ctx
- .enter(super::store::create_artifact_regenerating(
- workspace_dir,
- files.clone(),
- legacy_kind,
- title,
- extension,
- tool_call_id,
- target,
- chat,
- ))
- .await?;
+ )
+ .await?;
+
- let artifacts = artifacts_service(workspace_dir, files.clone(), None, chat);
++ let artifacts = artifacts_service_current(workspace_dir, files.clone(), None, chat);
let mut production = Self {
artifacts,
- ctx: ctx.clone(),
workspace_dir: workspace_dir.to_path_buf(),
files,
chat: chat.cloned(),
@@@ -304,13 -236,10 +237,23 @@@
Ok(Some(record)) if record.latest().is_some() => record,
_ => return self.fail_card(reason).await,
};
++ let ctx = crate::core::runtime::DispatchCtx::ambient();
++ let scoped = crate::storage::sessions::artifact_scoped_for_in(&self.workspace_dir, &ctx);
++ let file_store = scoped.as_ref().map(|scoped| {
++ Arc::new(tiny_artifacts::BlobFileStore::new(scoped))
++ as Arc<dyn tiny_artifacts::FileStore>
++ });
let bridge = super::tiny_store::LegacyUiBridge::new(
&self.workspace_dir,
self.files.clone(),
- super::tiny_store::guarded_roots(self.files.trusted().to_vec()),
- self.file_store.clone(),
++ super::tiny_store::guarded_roots(super::tiny_store::file_roots(
++ &self.workspace_dir,
++ &self.files,
++ None,
++ )),
++ file_store,
self.chat.as_ref(),
- &self.ctx,
++ &ctx,
);
if let Err(err) = bridge.show_newest(&record).await {
tracing::warn!(
diff --cc crates/openhuman-core/src/artifacts/production_tests.rs
index 41f39795ad,543fb58100..ae629eb913
--- a/crates/openhuman-core/src/artifacts/production_tests.rs
+++ b/crates/openhuman-core/src/artifacts/production_tests.rs
@@@ -1,6 -1,6 +1,6 @@@
use std::path::PathBuf;
--use tiny_artifacts::{ArtifactKind, ArtifactStatus as RecordStatus, ArtifactStore};
++use tiny_artifacts::{ArtifactKind, ArtifactStatus as RecordStatus, ArtifactStore, FileStore};
use super::*;
use crate::artifacts::store::get_artifact;
@@@ -148,18 -123,14 +123,14 @@@ async fn a_revision_reuses_the_id_and_f
b"deck-v2!"
);
// Each version still holds what it was.
- let ctx = crate::core::runtime::DispatchCtx::process_default();
- let (_, file_store) = super::super::tiny_store::artifacts_service_with_file_store(
- &workspace,
- FileRoots::new(&files),
- None,
- None,
- &ctx,
- );
- let file_store = file_store.unwrap();
- let key_of = |n: u32| record.version(n).unwrap().file.clone().unwrap().key;
- assert_eq!(file_store.read(&key_of(1)).await.unwrap(), b"deck-v1");
- assert_eq!(file_store.read(&key_of(2)).await.unwrap(), b"deck-v2!");
- let bytes_of = |n: u32| {
- let file = record.version(n).unwrap().file.clone().unwrap();
- std::fs::read(crate::artifacts::tiny_store::stored_file_path(
- &workspace, &file,
- ))
- };
- assert_eq!(bytes_of(1).unwrap(), b"deck-v1");
- assert_eq!(bytes_of(2).unwrap(), b"deck-v2!");
++ let context = crate::core::runtime::DispatchCtx::ambient();
++ let scoped = crate::storage::sessions::artifact_scoped_for_in(&workspace, &context)
++ .expect("production's artifact scope is available");
++ let blobs = tiny_artifacts::BlobFileStore::new(&scoped);
++ for (version, expected) in [(1, b"deck-v1".as_slice()), (2, b"deck-v2!".as_slice())] {
++ let file = record.version(version).unwrap().file.as_ref().unwrap();
++ assert_eq!(blobs.read(&file.key).await.unwrap(), expected);
++ }
}
#[tokio::test]
diff --cc crates/openhuman-core/src/artifacts/tiny_store.rs
index f1479d5989,860b8a2961..34a33961aa
--- a/crates/openhuman-core/src/artifacts/tiny_store.rs
+++ b/crates/openhuman-core/src/artifacts/tiny_store.rs
@@@ -30,8 -29,8 +29,8 @@@ use std::sync::Arc
use async_trait::async_trait;
use tiny_artifacts::{
- ArtifactEvent, ArtifactEventKind, ArtifactKind, ArtifactObserver, ArtifactRecord, Artifacts,
- Author, Content,
+ ArtifactEvent, ArtifactEventKind, ArtifactKind, ArtifactObserver, ArtifactRecord,
- ArtifactStore, Artifacts, Author, Content, FileRef, FileStore, FsFileStore,
++ ArtifactStore, Artifacts, Author, Content, FileRef, FileStore,
};
use super::files::FileRoots;
@@@ -92,97 -91,6 +91,87 @@@ pub fn versioned_store(workspace_dir: &
super::version_documents::DocumentArtifactStore::new(workspace_dir)
}
- /// Imports version records written by earlier OpenHuman builds, whose file
- /// references held host paths, through the owner's guarded legacy importer.
- struct LegacyFileImportStore {
- records: Arc<dyn ArtifactStore>,
- files: Arc<dyn FileStore>,
- roots: tiny_artifacts::FileRoots,
- }
-
- /// Refuses all versioned-record operations when a tenant storage binding
- /// could not be resolved, rather than substituting ambient workspace data.
+struct UnavailableArtifactStore;
+
+#[async_trait]
+impl ArtifactStore for UnavailableArtifactStore {
+ async fn list(&self) -> anyhow::Result<Vec<ArtifactRecord>> {
+ anyhow::bail!("artifact tenant storage is unavailable")
+ }
-
+ async fn get(&self, _id: &str) -> anyhow::Result<Option<ArtifactRecord>> {
+ anyhow::bail!("artifact tenant storage is unavailable")
+ }
-
+ async fn upsert(&self, _artifact: &ArtifactRecord) -> anyhow::Result<()> {
+ anyhow::bail!("artifact tenant storage is unavailable")
+ }
-
+ async fn delete(&self, _id: &str) -> anyhow::Result<bool> {
+ anyhow::bail!("artifact tenant storage is unavailable")
+ }
+}
+
++struct LegacyFileImportStore {
++ records: Arc<dyn ArtifactStore>,
++ files: Arc<dyn FileStore>,
++ roots: tiny_artifacts::FileRoots,
++}
++
+impl LegacyFileImportStore {
+ async fn import_record(&self, mut record: ArtifactRecord) -> anyhow::Result<ArtifactRecord> {
+ if !record.kind.holds_file() {
+ return Ok(record);
+ }
+ let mut changed = false;
+ for version in &mut record.versions {
+ let legacy = version.file.clone().unwrap_or_else(|| FileRef {
+ key: version.body.clone(),
+ size_bytes: 0,
+ media_type: None,
+ });
+ if legacy.key.starts_with("artifacts/files/") {
+ continue;
+ }
+ let ext = Path::new(&legacy.key)
+ .extension()
+ .and_then(|ext| ext.to_str())
+ .unwrap_or("bin");
+ let key = format!("artifacts/files/{}/v{}.{}", record.id, version.version, ext);
+ let imported =
+ tiny_artifacts::import_legacy_file(self.files.as_ref(), &self.roots, &legacy, &key)
+ .await?;
+ version.body = imported.key.clone();
+ version.file = Some(imported);
+ changed = true;
+ }
+ if changed {
+ self.records.upsert(&record).await?;
+ }
+ Ok(record)
+ }
+}
+
+#[async_trait]
+impl ArtifactStore for LegacyFileImportStore {
+ async fn list(&self) -> anyhow::Result<Vec<ArtifactRecord>> {
+ let mut imported = Vec::new();
+ for record in self.records.list().await? {
+ imported.push(self.import_record(record).await?);
+ }
+ Ok(imported)
+ }
-
+ async fn get(&self, id: &str) -> anyhow::Result<Option<ArtifactRecord>> {
+ match self.records.get(id).await? {
+ Some(record) => self.import_record(record).await.map(Some),
+ None => Ok(None),
+ }
+ }
-
+ async fn upsert(&self, record: &ArtifactRecord) -> anyhow::Result<()> {
+ self.records.upsert(record).await
+ }
-
+ async fn delete(&self, id: &str) -> anyhow::Result<bool> {
+ self.records.delete(id).await
+ }
+}
+
/// Where an earlier build kept versioned records, one `<id>.json` each.
pub fn legacy_versioned_dir(workspace_dir: &Path) -> PathBuf {
workspace_dir.join("artifacts").join(VERSIONED_SUBDIR)
@@@ -243,16 -138,14 +232,9 @@@ impl LegacyUiBridge
.map(str::to_ascii_lowercase)
== Some(ext.clone())
});
- if owned_has_extension {
- if let Some(owned) = owned {
- let source_buf = stored_file_path(&self.workspace_dir, file);
- let source = source_buf.as_path();
- let size = if same_file(owned, source) {
- tokio::fs::metadata(source).await?.len()
- } else {
- tokio::fs::copy(source, owned).await?
- };
++ if owned.is_some() {
+ let destination = self.resolve_visible_destination(&meta).await?;
- let file_store = self
- .file_store
- .as_ref()
- .ok_or_else(|| anyhow::anyhow!("artifact file storage is unavailable"))?;
- let bytes = file_store.read(&file.key).await?;
- let size = self
- .write_visible_file(&destination, &bytes, file.media_type.as_deref())
- .await?;
++ let size = self.write_file_version(file, &destination).await?;
super::store::finalize_artifact(
&self.workspace_dir,
&record.id,
@@@ -277,25 -170,15 +259,18 @@@
)
.await
.map_err(anyhow::Error::msg)?;
- let destination = self.resolve_visible_destination(&meta).await?;
let size = if record.holds_file() {
- let source = latest.file.as_ref().map_or_else(
- || PathBuf::from(&latest.body),
- |f| stored_file_path(&self.workspace_dir, f),
- );
- if same_file(&source, &dest) {
- tokio::fs::metadata(&dest).await?.len()
+ if let Some(file) = latest.file.as_ref() {
- let file_store = self
- .file_store
- .as_ref()
- .ok_or_else(|| anyhow::anyhow!("artifact file storage is unavailable"))?;
- let bytes = file_store.read(&file.key).await?;
- self.write_visible_file(&destination, &bytes, file.media_type.as_deref())
- .await?
++ self.write_file_version(file, &dest).await?
} else {
- tokio::fs::copy(&source, &dest).await?
+ let source = self.source_roots.resolve(&latest.body).await?;
- if same_file(&source.path, &destination) {
- tokio::fs::metadata(&destination).await?.len()
++ if same_file(&source.path, &dest) {
++ tokio::fs::metadata(&dest).await?.len()
+ } else {
+ let bytes = tokio::fs::read(&source.path).await?;
- self.write_visible_file(&destination, &bytes, source.media_type.as_deref())
++ self.write_visible_file(&dest, &bytes, source.media_type.as_deref())
+ .await?
+ }
}
} else {
tokio::fs::write(&dest, latest.body.as_bytes()).await?;
@@@ -306,73 -189,6 +281,53 @@@
.map_err(anyhow::Error::msg)?;
Ok(())
}
+
- async fn resolve_visible_destination(&self, meta: &ArtifactMeta) -> anyhow::Result<PathBuf> {
++ async fn write_file_version(&self, file: &FileRef, destination: &Path) -> anyhow::Result<u64> {
++ let store = self
++ .file_store
++ .as_ref()
++ .ok_or_else(|| anyhow::anyhow!("artifact tenant file storage is unavailable"))?;
++ let bytes = store.read(&file.key).await?;
++ self.write_visible_file(destination, &bytes, file.media_type.as_deref())
++ .await
++ }
++
++ async fn resolve_visible_destination(
++ &self,
++ meta: &super::types::ArtifactMeta,
++ ) -> anyhow::Result<PathBuf> {
+ let path = super::files::resolve_file(&self.workspace_dir, meta, &self.files)
+ .await
+ .map_err(anyhow::Error::msg)?;
+ let raw = path
+ .to_str()
+ .ok_or_else(|| anyhow::anyhow!("artifact presentation path is not valid UTF-8"))?;
- let resolved = super::tiny_store::guarded_roots(self.files.trusted().to_vec())
- .resolve(raw)
- .await?;
++ let resolved = self.files_guard().resolve(raw).await?;
+ Ok(resolved.path)
+ }
+
++ fn files_guard(&self) -> tiny_artifacts::FileRoots {
++ guarded_roots(self.files.trusted().to_vec())
++ }
++
+ async fn write_visible_file(
+ &self,
+ destination: &Path,
+ bytes: &[u8],
+ media_type: Option<&str>,
+ ) -> anyhow::Result<u64> {
+ let root = destination
+ .parent()
- .ok_or_else(|| anyhow::anyhow!("artifact presentation file has no parent"))?;
++ .ok_or_else(|| anyhow::anyhow!("artifact file has no parent"))?;
+ let name = destination
+ .file_name()
+ .and_then(|name| name.to_str())
- .ok_or_else(|| anyhow::anyhow!("artifact presentation file has no valid name"))?;
- let metadata = FsFileStore::new(root)
++ .ok_or_else(|| anyhow::anyhow!("artifact file has no valid name"))?;
++ Ok(tiny_artifacts::FsFileStore::new(root)
+ .overwrite_existing(name, bytes, media_type)
- .await?;
- Ok(metadata.size_bytes)
- }
-
- async fn on_event_in_scope(&self, event: &ArtifactEvent) -> anyhow::Result<()> {
- let id = &event.record.id;
- match event.kind {
- ArtifactEventKind::Ready => self.show_newest_in_scope(&event.record).await,
- ArtifactEventKind::Failed => {
- let reason = event.record.error.as_deref().unwrap_or("failed");
- // Only an artifact the UI already shows has a row to fail.
- if super::store::get_artifact(&self.workspace_dir, id)
- .await
- .is_ok()
- {
- super::store::fail_artifact(
- &self.workspace_dir,
- self.files.clone(),
- id,
- reason,
- self.chat.as_ref(),
- )
- .await
- .map_err(anyhow::Error::msg)?;
- }
- Ok(())
- }
- ArtifactEventKind::Deleted => {
- let _ = super::store::delete_artifact(&self.workspace_dir, self.files.clone(), id)
- .await;
- Ok(())
- }
- // The legacy pipeline's pending row needs the file's extension,
- // which a pending artifact does not have yet; its card appears
- // when the first version lands.
- ArtifactEventKind::Pending => Ok(()),
- }
++ .await?
++ .size_bytes)
+ }
}
fn same_file(a: &Path, b: &Path) -> bool {
@@@ -385,7 -201,38 +340,46 @@@
#[async_trait]
impl ArtifactObserver for LegacyUiBridge {
async fn on_event(&self, event: &ArtifactEvent) -> anyhow::Result<()> {
- self.ctx.enter(self.on_event_in_scope(event)).await
- let id = &event.record.id;
- match event.kind {
- ArtifactEventKind::Ready => self.show_newest(&event.record).await,
- ArtifactEventKind::Failed => {
- let reason = event.record.error.as_deref().unwrap_or("failed");
- // Only an artifact the UI already shows has a row to fail.
- if super::store::get_artifact(&self.workspace_dir, id)
- .await
- .is_ok()
- {
- super::store::fail_artifact(
- &self.workspace_dir,
- self.files.clone(),
- id,
- reason,
- self.chat.as_ref(),
- )
- .await
- .map_err(anyhow::Error::msg)?;
++ self.ctx
++ .enter(async {
++ let id = &event.record.id;
++ match event.kind {
++ ArtifactEventKind::Ready => self.show_newest(&event.record).await,
++ ArtifactEventKind::Failed => {
++ let reason = event.record.error.as_deref().unwrap_or("failed");
++ // Only an artifact the UI already shows has a row to fail.
++ if super::store::get_artifact(&self.workspace_dir, id)
++ .await
++ .is_ok()
++ {
++ super::store::fail_artifact(
++ &self.workspace_dir,
++ self.files.clone(),
++ id,
++ reason,
++ self.chat.as_ref(),
++ )
++ .await
++ .map_err(anyhow::Error::msg)?;
++ }
++ Ok(())
++ }
++ ArtifactEventKind::Deleted => {
++ let _ = super::store::delete_artifact(
++ &self.workspace_dir,
++ self.files.clone(),
++ id,
++ )
++ .await;
++ Ok(())
++ }
++ // The legacy pipeline's pending row needs the file's extension,
++ // which a pending artifact does not have yet; its card appears
++ // when the first version lands.
++ ArtifactEventKind::Pending => Ok(()),
+ }
- Ok(())
- }
- ArtifactEventKind::Deleted => {
- let _ = super::store::delete_artifact(&self.workspace_dir, self.files.clone(), id)
- .await;
- Ok(())
- }
- // The legacy pipeline's pending row needs the file's extension,
- // which a pending artifact does not have yet; its card appears
- // when the first version lands.
- ArtifactEventKind::Pending => Ok(()),
- }
++ })
++ .await
}
}
@@@ -453,102 -300,17 +447,112 @@@ pub fn artifacts_service
files: FileRoots,
action_dir: Option<&Path>,
chat: Option<&ApprovalChatContext>,
+ ctx: &crate::core::runtime::DispatchCtx,
) -> Artifacts {
- build_artifacts_service(workspace_dir, files, action_dir, chat, ctx, None).0
++ let scoped = crate::storage::sessions::artifact_scoped_for_in(workspace_dir, ctx);
++ build_artifacts_service_with_scope(workspace_dir, files, action_dir, chat, ctx, scoped, None).0
+}
+
- /// Build an artifact service and bind an optional publisher to the exact
- /// tenant-scoped file store used by that service.
- pub fn artifacts_service_with_publisher(
++/// Build the artifact service in the current dispatch context.
++pub fn artifacts_service_current(
+ workspace_dir: &Path,
+ files: FileRoots,
+ action_dir: Option<&Path>,
+ chat: Option<&ApprovalChatContext>,
- ctx: &crate::core::runtime::DispatchCtx,
- publisher: Option<&super::publisher_slot::ArtifactPublisherBinder>,
+) -> Artifacts {
- build_artifacts_service(workspace_dir, files, action_dir, chat, ctx, publisher).0
- }
-
- pub(crate) fn artifacts_service_with_file_store(
- workspace_dir: &Path,
- files: FileRoots,
- action_dir: Option<&Path>,
- chat: Option<&ApprovalChatContext>,
- ctx: &crate::core::runtime::DispatchCtx,
- ) -> (Artifacts, Option<Arc<dyn FileStore>>) {
- build_artifacts_service(workspace_dir, files, action_dir, chat, ctx, None)
++ artifacts_service(
++ workspace_dir,
++ files,
++ action_dir,
++ chat,
++ &crate::core::runtime::DispatchCtx::ambient(),
++ )
+}
+
- fn build_artifacts_service(
++/// Build a service and bind its publisher to the same tenant file store used
++/// by the artifact versions.
++pub fn artifacts_service_with_publisher(
+ workspace_dir: &Path,
+ files: FileRoots,
+ action_dir: Option<&Path>,
+ chat: Option<&ApprovalChatContext>,
- ctx: &crate::core::runtime::DispatchCtx,
- publisher: Option<&super::publisher_slot::ArtifactPublisherBinder>,
- ) -> (Artifacts, Option<Arc<dyn FileStore>>) {
- let scoped = crate::storage::sessions::artifact_scoped_for_in(workspace_dir, ctx);
++ publisher: Option<&super::ArtifactPublisherBinder>,
++) -> Artifacts {
++ let ctx = crate::core::runtime::DispatchCtx::ambient();
++ let scoped = crate::storage::sessions::artifact_scoped_for_in(workspace_dir, &ctx);
+ build_artifacts_service_with_scope(
+ workspace_dir,
+ files,
+ action_dir,
+ chat,
- ctx,
++ &ctx,
+ scoped,
+ publisher,
+ )
++ .0
+}
+
+pub(super) fn build_artifacts_service_with_scope(
+ workspace_dir: &Path,
+ files: FileRoots,
+ action_dir: Option<&Path>,
+ chat: Option<&ApprovalChatContext>,
+ ctx: &crate::core::runtime::DispatchCtx,
+ scoped: Option<crate::storage::ScopedStorage>,
- publisher: Option<&super::publisher_slot::ArtifactPublisherBinder>,
++ publisher: Option<&super::ArtifactPublisherBinder>,
+) -> (Artifacts, Option<Arc<dyn FileStore>>) {
let roots = file_roots(workspace_dir, &files, action_dir);
- Artifacts::new(Arc::new(versioned_store(workspace_dir)))
- .with_observer(Arc::new(LegacyUiBridge::new(workspace_dir, files, chat)))
+ let file_store = scoped
+ .as_ref()
+ .map(|scoped| Arc::new(tiny_artifacts::BlobFileStore::new(scoped)) as Arc<dyn FileStore>);
+ let mut records: Arc<dyn ArtifactStore> = match scoped.as_ref() {
+ Some(scoped) => Arc::new(super::version_documents::DocumentArtifactStore::over(
+ workspace_dir,
+ scoped,
+ )),
+ None => Arc::new(UnavailableArtifactStore),
+ };
+ if let Some(store) = file_store.as_ref() {
+ records = Arc::new(LegacyFileImportStore {
+ records,
+ files: store.clone(),
+ roots: guarded_roots(roots.clone()),
+ });
+ }
+ let mut artifacts = Artifacts::new(records)
+ .with_observer(Arc::new(LegacyUiBridge::new(
+ workspace_dir,
+ files,
+ guarded_roots(roots.clone()),
+ file_store.clone(),
+ chat,
+ ctx,
+ )))
- .with_file_roots(guarded_roots(roots));
+ .with_file_roots(guarded_roots(roots))
- .with_version_files(version_files_dir(workspace_dir))
++ .with_version_files(version_files_dir(workspace_dir));
+ if let Some(file_store) = file_store.as_ref() {
+ if let Some(publisher) = publisher {
+ artifacts = artifacts.with_publisher(publisher(file_store.clone()));
+ }
+ artifacts = artifacts.with_file_store(file_store.clone());
+ }
+ (artifacts, file_store)
+}
+
- /// Legacy workspace folder that earlier builds used for per-version file
- /// copies. New file bytes live in the acting tenant's scoped blob store.
++pub(crate) fn artifacts_service_with_file_store(
++ workspace_dir: &Path,
++ files: FileRoots,
++ action_dir: Option<&Path>,
++ chat: Option<&ApprovalChatContext>,
++ ctx: &crate::core::runtime::DispatchCtx,
++) -> (Artifacts, Option<Arc<dyn FileStore>>) {
++ let scoped = crate::storage::sessions::artifact_scoped_for_in(workspace_dir, ctx);
++ build_artifacts_service_with_scope(workspace_dir, files, action_dir, chat, ctx, scoped, None)
+ }
+
+ /// Where each file version keeps its own copy:
+ /// `<workspace>/artifacts/versioned/files/<id>/v<N>.<ext>`. The visible file
+ /// in the files folder shows the newest version.
pub fn version_files_dir(workspace_dir: &Path) -> PathBuf {
workspace_dir
.join("artifacts")
@@@ -566,29 -335,23 +577,24 @@@ pub fn stored_file_path(workspace_dir:
/// around a service whose UI bridge carries that call's chat routing
/// ([`PerCallTool`]); the card then reaches the chat the agent is answering.
pub fn registered_tools(
- config: crate::config::Config,
+ workspace_dir: &Path,
files: FileRoots,
action_dir: &Path,
- publisher_available: bool,
- publisher: Option<Arc<dyn tiny_artifacts::ArtifactPublisher>>,
++ publisher: Option<super::ArtifactPublisherBinder>,
) -> Vec<Box<dyn tinytools::Tool>> {
- let can_publish = publisher_available;
+ let can_publish = publisher.is_some();
let service = {
- let workspace_dir = config.workspace_dir.clone();
+ let workspace_dir = workspace_dir.to_path_buf();
let action_dir = action_dir.to_path_buf();
- let publisher_config = config.clone();
- Arc::new(
- move |chat: Option<&ApprovalChatContext>, ctx: &crate::core::runtime::DispatchCtx| {
- let publisher = super::artifact_publisher_in(&publisher_config, ctx);
- Arc::new(artifacts_service_with_publisher(
- &workspace_dir,
- files.clone(),
- Some(&action_dir),
- chat,
- ctx,
- publisher.as_ref(),
- ))
- },
- )
+ Arc::new(move |chat: Option<&ApprovalChatContext>| {
- let mut service =
- artifacts_service(&workspace_dir, files.clone(), Some(&action_dir), chat);
- if let Some(publisher) = &publisher {
- service = service.with_publisher(publisher.clone());
- }
- Arc::new(service)
++ Arc::new(artifacts_service_with_publisher(
++ &workspace_dir,
++ files.clone(),
++ Some(&action_dir),
++ chat,
++ publisher.as_ref(),
++ ))
+ })
};
let author = Author::agent(AGENT_AUTHOR_ID);
let mut tools: Vec<Box<dyn tinytools::Tool>> = Vec::new();
diff --cc crates/openhuman-core/src/artifacts/tiny_store_tests.rs
index 63bac644a7,d726beb6fc..1559bcbbbe
--- a/crates/openhuman-core/src/artifacts/tiny_store_tests.rs
+++ b/crates/openhuman-core/src/artifacts/tiny_store_tests.rs
@@@ -1,12 -1,11 +1,26 @@@
use std::path::PathBuf;
use tiny_artifacts::{
- ArtifactAuthor, ArtifactKind, ArtifactRecord, ArtifactStore, Author, Content,
+ ArtifactAuthor, ArtifactKind, ArtifactRecord, ArtifactStore, ArtifactVersion, Author, Content,
- FileRef, FileStore,
++ FileRef, FileStore, PublishOptions, PublishedLink,
};
use super::*;
++struct UnusedPublisher;
++
++#[async_trait::async_trait]
++impl tiny_artifacts::ArtifactPublisher for UnusedPublisher {
++ async fn publish(
++ &self,
++ _record: &ArtifactRecord,
++ _version: &ArtifactVersion,
++ _options: &PublishOptions,
++ ) -> anyhow::Result<PublishedLink> {
++ anyhow::bail!("publisher is not used by this test")
++ }
++}
++
fn temp_dirs() -> (PathBuf, PathBuf) {
let root = std::env::temp_dir().join(format!("tiny-store-{}", uuid::Uuid::new_v4()));
let (workspace, files) = (root.join("workspace"), root.join("Files"));
@@@ -441,22 -169,32 +455,24 @@@ async fn deleting_an_artifact_removes_i
#[test]
fn share_artifact_is_offered_only_with_a_publisher() {
let (workspace, files) = temp_dirs();
- let names = |publisher: Option<std::sync::Arc<dyn tiny_artifacts::ArtifactPublisher>>| {
- registered_tools(&workspace, FileRoots::new(&files), &workspace, publisher)
- .iter()
- .map(|t| t.name().to_string())
- .collect::<Vec<_>>()
+ let names = |publisher_available: bool| {
+ registered_tools(
- crate::config::Config {
- workspace_dir: workspace.clone(),
- action_dir: workspace.clone(),
- ..crate::config::Config::default()
- },
++ &workspace,
+ FileRoots::new(&files),
+ &workspace,
- publisher_available,
++ publisher_available.then(|| {
++ std::sync::Arc::new(
++ |_| -> std::sync::Arc<dyn tiny_artifacts::ArtifactPublisher> {
++ std::sync::Arc::new(UnusedPublisher)
++ },
++ ) as crate::artifacts::ArtifactPublisherBinder
++ }),
+ )
+ .iter()
+ .map(|t| t.name().to_string())
+ .collect::<Vec<_>>()
};
- let without = names(None);
+ let without = names(false);
assert!(
!without.contains(&"share_artifact".to_string()),
"{without:?}"
diff --cc crates/openhuman-core/src/channels/tests/runtime_debounce.rs
index 0000000000,6fc0794f88..b8eeb77d8e
mode 000000,100644..100644
--- a/crates/openhuman-core/src/channels/tests/runtime_debounce.rs
+++ b/crates/openhuman-core/src/channels/tests/runtime_debounce.rs
@@@ -1,0 -1,432 +1,430 @@@
+ use super::super::context::{ChannelRuntimeContext, CHANNEL_MESSAGE_TIMEOUT_SECS};
+ use super::super::runtime::{run_message_dispatch_loop, RuntimeChannelMessage};
+ use super::super::Channel;
+ use super::common::{RecordingChannel, SlowModel, TelegramRecordingChannel};
+ use crate::agent::bus::{mock_agent_run_turn, AgentTurnRequest, AgentTurnResponse};
+ use crate::config::InboundDebounceConfig;
+ use crate::core::bus_testing::MockBusGuard;
-use crate::inference::provider;
+ use std::collections::HashMap;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::{Arc, Mutex};
+ use std::time::Duration;
+ use tinychannels_bus as traits;
+ use tinychannels_bus::module_inbound::PreparedChannelInbound;
+ use tokio::sync::{mpsc, Notify};
+ use tokio::task::JoinHandle;
+
+ #[derive(Default)]
+ struct Turns {
+ histories: Mutex<Vec<Vec<(String, String)>>>,
+ active: AtomicUsize,
+ peak: AtomicUsize,
+ }
+
+ impl Turns {
+ fn count(&self) -> usize {
+ self.histories.lock().unwrap().len()
+ }
+
+ fn last_user(&self, turn: usize) -> String {
+ let histories = self.histories.lock().unwrap();
+ histories[turn]
+ .iter()
+ .rev()
+ .find(|(role, _)| role == "user")
+ .map(|(_, content)| content.clone())
+ .unwrap_or_default()
+ }
+
+ fn history(&self, turn: usize) -> Vec<(String, String)> {
+ self.histories.lock().unwrap()[turn].clone()
+ }
+ }
+
+ async fn install_handler(turns: Arc<Turns>, gate: Option<Arc<Notify>>) -> MockBusGuard {
+ mock_agent_run_turn(move |req: AgentTurnRequest| {
+ let turns = Arc::clone(&turns);
+ let gate = gate.clone();
+ async move {
+ let index = {
+ let mut histories = turns.histories.lock().unwrap();
+ histories.push(
+ req.history
+ .iter()
+ .map(|m| (m.role.clone(), m.content.clone()))
+ .collect(),
+ );
+ histories.len()
+ };
+ let active = turns.active.fetch_add(1, Ordering::SeqCst) + 1;
+ turns.peak.fetch_max(active, Ordering::SeqCst);
+ if index == 1 {
+ if let Some(gate) = gate {
+ gate.notified().await;
+ }
+ }
+ turns.active.fetch_sub(1, Ordering::SeqCst);
+ Ok(AgentTurnResponse::new(format!("reply {index}")))
+ }
+ })
+ .await
+ }
+
+ fn runtime() -> (Arc<RecordingChannel>, Arc<ChannelRuntimeContext>) {
+ let channel_impl = Arc::new(RecordingChannel::default());
+ let ctx = runtime_with(channel_impl.clone());
+ (channel_impl, ctx)
+ }
+
+ fn runtime_with(channel: Arc<dyn Channel>) -> Arc<ChannelRuntimeContext> {
+ let mut channels_by_name = HashMap::new();
+ channels_by_name.insert(channel.name().to_string(), channel);
+ Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
+ channels_by_name: Arc::new(channels_by_name),
+ turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
+ Arc::new(SlowModel {
+ delay: Duration::from_millis(1),
+ }),
+ )),
+ default_provider: Arc::new("test-provider".to_string()),
+ tools_registry: Arc::new(vec![]),
+ system_prompt: crate::channels::ChannelSystemPrompt::fixed("test-system-prompt"),
+ model: Arc::new("test-model".to_string()),
+ temperature: 0.0,
+ max_tool_iterations: 10,
+ conversation_histories: Arc::new(Mutex::new(HashMap::new())),
+ turn_model_source_cache: Arc::new(Mutex::new(HashMap::new())),
+ route_overrides: Arc::new(Mutex::new(HashMap::new())),
+ api_url: None,
+ inference_url: None,
+ reliability: Arc::new(crate::config::ReliabilityConfig::default()),
- provider_runtime_options: provider::ProviderRuntimeOptions::default(),
+ workspace_dir: Arc::new(std::env::temp_dir()),
+ message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,
+ multimodal: crate::config::MultimodalConfig::default(),
+ multimodal_files: crate::config::MultimodalFileConfig::default(),
+ config: None,
+ core: None,
+ })
+ }
+
+ struct Running {
+ tx: mpsc::Sender<RuntimeChannelMessage>,
+ task: JoinHandle<()>,
+ next_ts: u64,
+ channel: &'static str,
+ }
+
+ impl Running {
+ fn start(ctx: Arc<ChannelRuntimeContext>, config: InboundDebounceConfig) -> Self {
+ let (tx, rx) = mpsc::channel(32);
+ let task = crate::core::runtime::DispatchCtx::ambient()
+ .spawn(run_message_dispatch_loop(rx, ctx, 4, config));
+ Self {
+ tx,
+ task,
+ next_ts: 1,
+ channel: "test-channel",
+ }
+ }
+
+ fn message(&mut self, sender: &str, content: &str) -> traits::ChannelMessage {
+ let ts = self.next_ts;
+ self.next_ts += 1;
+ traits::ChannelMessage {
+ id: format!("m{ts}"),
+ sender: sender.to_string(),
+ reply_target: sender.to_string(),
+ content: content.to_string(),
+ channel: self.channel.to_string(),
+ timestamp: ts,
+ thread_ts: None,
+ sender_name: None,
+ }
+ }
+
+ async fn send(&mut self, sender: &str, content: &str) {
+ let message = self.prepared(sender, content);
+ self.tx.send(message).await.unwrap();
+ }
+
+ fn prepared(&mut self, sender: &str, content: &str) -> RuntimeChannelMessage {
+ let message = self.message(sender, content);
+ let history_key = format!("{}_{sender}_{sender}", self.channel);
+ let prepared = PreparedChannelInbound {
+ message: message.clone(),
+ envelope: Default::default(),
+ history_key: history_key.clone(),
+ thread_id: history_key.clone(),
+ client_id: self.channel.to_string(),
+ session_key: history_key,
+ };
+ RuntimeChannelMessage {
+ message,
+ inbound_envelope: None,
+ authenticated_relay: false,
+ prepared_inbound: Some(prepared),
+ }
+ }
+
+ async fn send_unprepared(&mut self, sender: &str, content: &str) {
+ let message = self.message(sender, content);
+ self.tx
+ .send(RuntimeChannelMessage::from(message))
+ .await
+ .unwrap();
+ }
+
+ async fn finish(self) {
+ drop(self.tx);
+ tokio::time::timeout(Duration::from_secs(600), self.task)
+ .await
+ .expect("dispatch loop drains")
+ .expect("dispatch loop does not panic");
+ }
+ }
+
+ async fn sleep_ms(ms: u64) {
+ tokio::time::sleep(Duration::from_millis(ms)).await;
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn two_quick_messages_from_one_sender_become_one_turn() {
+ let turns = Arc::new(Turns::default());
+ let _guard = install_handler(Arc::clone(&turns), None).await;
+ let (channel, ctx) = runtime();
+ let mut run = Running::start(ctx, InboundDebounceConfig::default());
+
+ run.send("alice", "first").await;
+ sleep_ms(500).await;
+ run.send("alice", "second").await;
+ sleep_ms(1000).await;
+ assert_eq!(turns.count(), 0, "still inside the quiet window");
+ sleep_ms(2000).await;
+
+ assert_eq!(turns.count(), 1);
+ assert!(turns.last_user(0).ends_with("first\nsecond"));
+ assert_eq!(channel.sent_messages.lock().await.len(), 1);
+ assert!(channel.start_typing_calls.load(Ordering::SeqCst) >= 1);
+ run.finish().await;
+ assert_eq!(turns.count(), 1);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn text_after_an_image_joins_it_through_the_media_window() {
+ let turns = Arc::new(Turns::default());
+ let _guard = install_handler(Arc::clone(&turns), None).await;
+ let (_channel, ctx) = runtime();
+ let mut run = Running::start(ctx, InboundDebounceConfig::default());
+
+ run.send("alice", "[IMAGE:https://example.com/a.png]\nlook")
+ .await;
+ sleep_ms(3000).await;
+ assert_eq!(turns.count(), 0);
+ run.send("alice", "what is this?").await;
+ sleep_ms(5000).await;
+
+ assert_eq!(turns.count(), 1);
+ let user = turns.last_user(0);
+ assert!(user.contains("look\nwhat is this?"), "{user}");
+ run.finish().await;
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn messages_during_a_running_turn_become_one_follow_up_that_sees_its_history() {
+ let turns = Arc::new(Turns::default());
+ let gate = Arc::new(Notify::new());
+ let _guard = install_handler(Arc::clone(&turns), Some(Arc::clone(&gate))).await;
+ let (channel, ctx) = runtime();
+ let mut run = Running::start(ctx, InboundDebounceConfig::default());
+
+ run.send("alice", "first").await;
+ sleep_ms(2000).await;
+ assert_eq!(turns.count(), 1, "first turn is running");
+ run.send("alice", "second").await;
+ sleep_ms(200).await;
+ run.send("alice", "third").await;
+ sleep_ms(5000).await;
+ assert_eq!(turns.count(), 1, "follow-up waits for the running turn");
+
+ gate.notify_one();
+ sleep_ms(100).await;
+ assert_eq!(turns.count(), 2, "quiet window already passed");
+ assert_eq!(turns.peak.load(Ordering::SeqCst), 1);
+ assert!(turns.last_user(1).ends_with("second\nthird"));
+ let history = turns.history(1);
+ assert!(history
+ .iter()
+ .any(|(role, content)| role == "assistant" && content == "reply 1"));
+ assert!(history
+ .iter()
+ .any(|(role, content)| role == "user" && content.ends_with("first")));
+ run.finish().await;
+ assert_eq!(channel.sent_messages.lock().await.len(), 2);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn follow_up_keeps_waiting_while_the_user_is_still_typing() {
+ let turns = Arc::new(Turns::default());
+ let gate = Arc::new(Notify::new());
+ let _guard = install_handler(Arc::clone(&turns), Some(Arc::clone(&gate))).await;
+ let (_channel, ctx) = runtime();
+ let mut run = Running::start(ctx, InboundDebounceConfig::default());
+
+ run.send("alice", "first").await;
+ sleep_ms(2000).await;
+ run.send("alice", "second").await;
+ sleep_ms(100).await;
+ gate.notify_one();
+ sleep_ms(100).await;
+ assert_eq!(turns.count(), 1, "second is still inside its quiet window");
+ run.send("alice", "third").await;
+ sleep_ms(2000).await;
+ assert_eq!(turns.count(), 2);
+ assert!(turns.last_user(1).ends_with("second\nthird"));
+ run.finish().await;
+ }
+
+ #[tokio::test]
+ async fn runtime_command_is_answered_without_waiting_for_the_buffer() {
+ let turns = Arc::new(Turns::default());
+ let _guard = install_handler(Arc::clone(&turns), None).await;
+ let channel = Arc::new(TelegramRecordingChannel::default());
+ let ctx = runtime_with(channel.clone());
+ let long_window = InboundDebounceConfig {
+ debounce_ms: 600_000,
+ media_debounce_ms: 600_000,
+ max_wait_ms: 600_000,
+ ..Default::default()
+ };
+ let mut run = Running::start(ctx, long_window);
+ run.channel = "telegram";
+
+ run.send("alice", "hello").await;
+ run.send_unprepared("alice", "/model").await;
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while channel.sent_messages.lock().await.is_empty() {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the command is answered while the buffer still holds hello");
+ assert_eq!(turns.count(), 0);
+
+ run.finish().await;
+ assert_eq!(turns.count(), 1);
+ assert!(turns.last_user(0).ends_with("hello"));
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_steady_stream_flushes_at_max_wait() {
+ let turns = Arc::new(Turns::default());
+ let _guard = install_handler(Arc::clone(&turns), None).await;
+ let (_channel, ctx) = runtime();
+ let mut run = Running::start(ctx, InboundDebounceConfig::default());
+
+ for index in 0..12 {
+ run.send("alice", &format!("part {index}")).await;
+ sleep_ms(900).await;
+ }
+
+ assert_eq!(
+ turns.count(),
+ 1,
+ "deadline at 10s, quiet window would be 11.4s"
+ );
+ let user = turns.last_user(0);
+ assert!(
+ user.contains("part 0\n") && user.ends_with("part 11"),
+ "{user}"
+ );
+ run.finish().await;
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn disabled_config_runs_one_turn_per_message_in_order() {
+ let turns = Arc::new(Turns::default());
+ let _guard = install_handler(Arc::clone(&turns), None).await;
+ let (_channel, ctx) = runtime();
+ let mut run = Running::start(ctx, InboundDebounceConfig::disabled());
+
+ run.send("alice", "one").await;
+ run.send("alice", "two").await;
+ sleep_ms(100).await;
+
+ assert_eq!(turns.count(), 2);
+ assert_eq!(turns.peak.load(Ordering::SeqCst), 1);
+ assert!(turns.last_user(0).ends_with("one"));
+ assert!(turns.last_user(1).ends_with("two"));
+ run.finish().await;
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn different_senders_are_never_merged() {
+ let turns = Arc::new(Turns::default());
+ let _guard = install_handler(Arc::clone(&turns), None).await;
+ let (channel, ctx) = runtime();
+ let mut run = Running::start(ctx, InboundDebounceConfig::default());
+
+ run.send("alice", "from alice").await;
+ run.send("bob", "from bob").await;
+ sleep_ms(2000).await;
+
+ assert_eq!(turns.count(), 2);
+ let mut users = [turns.last_user(0), turns.last_user(1)];
+ users.sort();
+ assert!(users[0].ends_with("from alice"));
+ assert!(users[1].ends_with("from bob"));
+ run.finish().await;
+ assert_eq!(channel.sent_messages.lock().await.len(), 2);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn closing_the_queue_flushes_buffered_messages() {
+ let turns = Arc::new(Turns::default());
+ let _guard = install_handler(Arc::clone(&turns), None).await;
+ let (_channel, ctx) = runtime();
+ let mut run = Running::start(ctx, InboundDebounceConfig::default());
+
+ run.send("alice", "a").await;
+ run.send("alice", "b").await;
+ run.finish().await;
+
+ assert_eq!(turns.count(), 1);
+ assert!(turns.last_user(0).ends_with("a\nb"));
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_full_intake_budget_stops_receiving_until_turns_drain() {
+ let turns = Arc::new(Turns::default());
+ let gate = Arc::new(Notify::new());
+ let _guard = install_handler(Arc::clone(&turns), Some(Arc::clone(&gate))).await;
+ let (_channel, ctx) = runtime();
+ let config = InboundDebounceConfig {
+ max_batch_messages: 1,
+ ..InboundDebounceConfig::default()
+ };
+ let mut run = Running::start(ctx, config);
+
+ run.send("alice", "first").await;
+ sleep_ms(2000).await;
+ assert_eq!(turns.count(), 1);
+
+ let mut accepted = 0;
+ for i in 0..200 {
+ let message = run.prepared("alice", &format!("queued {i}"));
+ if run.tx.try_send(message).is_err() {
+ break;
+ }
+ accepted += 1;
+ sleep_ms(1).await;
+ }
+ assert_eq!(accepted, 4 + 32, "4 held by the loop plus a full queue");
+
+ gate.notify_one();
+ run.finish().await;
+ assert_eq!(turns.count(), 1 + accepted);
+ for i in 0..accepted {
+ assert!(turns.last_user(i + 1).ends_with(&format!("queued {i}")));
+ }
+ }
diff --cc crates/openhuman-core/src/config/mod.rs
index ac9d9cb3c9,69a9cadaa0..ba16b99a83
--- a/crates/openhuman-core/src/config/mod.rs
+++ b/crates/openhuman-core/src/config/mod.rs
@@@ -49,25 -49,24 +49,24 @@@ pub use schema::
CapabilityProviderTrustState, ChannelsConfig, CompactionSettings, CompactionStrategy,
ComposioConfig, ComposioDirectBaseUrls, ComposioHostCredential, ComputerConfig, Config,
ContextConfig, CostConfig, CronConfig, CurlConfig, DashboardConfig, DecisionModel,
- DiagramViewerConfig, DictationActivationMode, DictationConfig, DiscordConfig,
- DockerRuntimeConfig, EmailConfig, EmbeddingRouteConfig, GitbooksConfig, HttpHeader,
- HttpRequestConfig, IMessageConfig, IntegrationToggle, IntegrationsConfig, LarkConfig,
- LegacySearchInputs, LinqConfig, LocalAiConfig, LocalJailConfig, MatrixConfig, McpAuthConfig,
- McpClientConfig, McpClientIdentityConfig, McpServerConfig, McpToolExposure, MemoryConfig,
- MemoryLayoutMode, ModelRouteConfig, MultimodalConfig, MultimodalFileConfig,
- ObservabilityConfig, OrchestratorModelConfig, PresentationMode, PrivacyConfig, PrivacyMode,
- ProviderRoute, ProxyConfig, ProxyScope, ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig,
- DelegateAgentConfig, DiagramViewerConfig, DiscordConfig, DockerRuntimeConfig, EmailConfig,
- EmbeddingRouteConfig, GitbooksConfig, HttpHeader, HttpRequestConfig, IMessageConfig,
- IntegrationToggle, IntegrationsConfig, LarkConfig, LegacySearchInputs, LinqConfig,
- LocalAiConfig, LocalJailConfig, MatrixConfig, McpAuthConfig, McpClientConfig,
- McpClientIdentityConfig, McpServerConfig, McpToolExposure, MemoryConfig, MemoryLayoutMode,
- ModelRouteConfig, MultimodalConfig, MultimodalFileConfig, ObservabilityConfig,
- OrchestratorModelConfig, PresentationMode, PrivacyConfig, PrivacyMode, ProviderRoute,
- ProxyConfig, ProxyScope, ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig,
-- SandboxBackend, SandboxConfig, SchedulerConfig, SchedulerGateConfig, SchedulerGateMode,
-- SearchConfig, SearchEngineCredentials, SearchHostCredential, SearchProviderSettings,
-- SearxngConfig, SecretsConfig, SecurityConfig, ShellConfig, SlackConfig, StreamMode, SttEngine,
-- TeamModelConfig, TelegramConfig, TokenjuiceConfig, UnknownKeyedSearchProvider, UpdateConfig,
- UpdateRestartStrategy, VoiceActivationMode, VoiceServerConfig, WebSearchConfig, WebhookConfig,
- YuanbaoConfig, DEFAULT_MODEL, LEGACY_TIER_MODELS, MANAGED_MULTIMODAL_MODELS,
- MANAGED_SEARCH_PROVIDERS, MODEL_IMAGE_GENERATION_AGENT, MODEL_MANAGED_DEFAULT,
- MODEL_MEDIA_UNDERSTANDING, MODEL_VIDEO_GENERATION_AGENT, SEARCH_ENGINE_BRAVE,
- SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA, SEARCH_ENGINE_MANAGED, SEARCH_ENGINE_PARALLEL,
- SEARCH_ENGINE_QUERIT, SEARCH_ENGINE_TAVILY, SEARCH_PROVIDERS, SEARCH_ROLES, SEARCH_ROLE_ANSWER,
- SEARCH_ROLE_CONTENTS, SEARCH_ROLE_SEARCH,
- UpdateRestartStrategy, VoiceServerConfig, WebSearchConfig, WebhookConfig, YuanbaoConfig,
- DEFAULT_MODEL, LEGACY_TIER_MODELS, MANAGED_MULTIMODAL_MODELS, MANAGED_SEARCH_PROVIDERS,
++ DiagramViewerConfig, DiscordConfig, DockerRuntimeConfig, EmailConfig, EmbeddingRouteConfig,
++ GitbooksConfig, HttpHeader, HttpRequestConfig, IMessageConfig, IntegrationToggle,
++ IntegrationsConfig, LarkConfig, LegacySearchInputs, LinqConfig, LocalAiConfig, LocalJailConfig,
++ MatrixConfig, McpAuthConfig, McpClientConfig, McpClientIdentityConfig, McpServerConfig,
++ McpToolExposure, MemoryConfig, MemoryLayoutMode, ModelRouteConfig, MultimodalConfig,
++ MultimodalFileConfig, ObservabilityConfig, OrchestratorModelConfig, PresentationMode,
++ PrivacyConfig, PrivacyMode, ProviderRoute, ProxyConfig, ProxyScope, ReliabilityConfig,
++ ResourceLimitsConfig, RuntimeConfig, SandboxBackend, SandboxConfig, SchedulerConfig,
++ SchedulerGateConfig, SchedulerGateMode, SearchConfig, SearchEngineCredentials,
++ SearchHostCredential, SearchProviderSettings, SearxngConfig, SecretsConfig, SecurityConfig,
++ ShellConfig, SlackConfig, StreamMode, SttEngine, TeamModelConfig, TelegramConfig,
++ TokenjuiceConfig, UnknownKeyedSearchProvider, UpdateConfig, UpdateRestartStrategy,
++ VoiceServerConfig, WebSearchConfig, WebhookConfig, YuanbaoConfig, DEFAULT_MODEL,
++ LEGACY_TIER_MODELS, MANAGED_MULTIMODAL_MODELS, MANAGED_SEARCH_PROVIDERS,
+ MODEL_IMAGE_GENERATION_AGENT, MODEL_MANAGED_DEFAULT, MODEL_MEDIA_UNDERSTANDING,
+ MODEL_VIDEO_GENERATION_AGENT, SEARCH_ENGINE_BRAVE, SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA,
+ SEARCH_ENGINE_MANAGED, SEARCH_ENGINE_PARALLEL, SEARCH_ENGINE_QUERIT, SEARCH_ENGINE_TAVILY,
+ SEARCH_PROVIDERS, SEARCH_ROLES, SEARCH_ROLE_ANSWER, SEARCH_ROLE_CONTENTS, SEARCH_ROLE_SEARCH,
};
// Kept as a separate re-export (issue #4117) so the large alphabetized group
// above stays byte-identical and rustfmt-stable.
diff --cc crates/openhuman-core/src/core/agent_cli/debug/mod.rs
index dddcf89a38,c7912f47a4..785b376b0c
--- a/crates/openhuman-core/src/core/agent_cli/debug/mod.rs
+++ b/crates/openhuman-core/src/core/agent_cli/debug/mod.rs
@@@ -186,8 -192,22 +192,22 @@@ async fn render_via_session
// snapshot matches what the runtime will send, without starting a model turn.
agent.refresh_prompt_surface().await;
+ #[cfg(feature = "flows")]
+ let flow_archetype_text = match agent.resolved_definition() {
+ Some(definition) => {
+ crate::agent::prompts::flow_archetype::load_for_definition(
+ Some(config),
+ definition.as_ref(),
+ )
+ .await?
+ }
+ None => None,
+ };
+ #[cfg(not(feature = "flows"))]
+ let flow_archetype_text: Option<String> = None;
+
let text = agent
- .render_current_turn_prompt()
- .build_system_prompt_with_flow_archetype(flow_archetype_text.as_deref())
++ .render_current_turn_prompt_with_flow_archetype(flow_archetype_text.as_deref())
.with_context(|| format!("rendering system prompt for `{agent_id}`"))?;
Ok(session_dump(&agent, agent_id, text))
diff --cc crates/openhuman-core/src/core/observability.rs
index 66bf9e7edb,7916812c79..f3c60da177
--- a/crates/openhuman-core/src/core/observability.rs
+++ b/crates/openhuman-core/src/core/observability.rs
@@@ -27,7 -27,7 +27,7 @@@ use std::fmt::Display
#[path = "observability_release_tag.rs"]
mod release_tag;
#[cfg(feature = "crash-reporting")]
--use release_tag::{parse_release_tag, parse_version};
++pub use release_tag::is_stale_release_event;
#[path = "observability_availability.rs"]
mod availability;
@@@ -3396,34 -3423,34 +3423,6 @@@ pub fn is_connectivity_event(event: &se
false
}
--/// Filter out events from **stale releases** — releases older than
--/// `MAX_AGE_MINOR_VERSIONS` minor versions behind the current build.
--///
--/// Ancient-client errors are not actionable against the current codebase.
--/// Target: ~4 issues from releases like v0.54.0 against current v0.58+.
--#[cfg(feature = "crash-reporting")]
--pub fn is_stale_release_event(event: &sentry::protocol::Event<'_>) -> bool {
-- // Maximum number of minor versions behind the current release to accept.
-- // Events from clients on releases older than this are dropped.
-- const MAX_AGE_MINOR_VERSIONS: u32 = 6;
--
-- let Some(release) = event.release.as_ref() else {
-- return false;
-- };
--
-- let current = env!("CARGO_PKG_VERSION");
-- parse_version(current).is_some_and(|(current_major, current_minor)| {
-- parse_release_tag(release).is_some_and(|(event_major, event_minor)| {
-- if event_major != current_major {
-- // Different major version = definitely stale (or from the future)
-- return event_major < current_major;
-- }
-- // Same major: check minor version gap
-- current_minor.saturating_sub(event_minor) > MAX_AGE_MINOR_VERSIONS
-- })
-- })
--}
--
#[cfg(test)]
#[path = "observability_tests.rs"]
mod tests;
diff --cc crates/openhuman-core/src/core/observability_error_classification_session_plan_tests.rs
index 0000000000,0000000000..f860bf9013
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/core/observability_error_classification_session_plan_tests.rs
@@@ -1,0 -1,0 +1,27 @@@
++use super::*;
++
++#[test]
++fn memory_plan_refusal_is_backend_user_state_not_session_expiry() {
++ // #8081: memory not in the account's plan is user state for Sentry, and
++ // must not read as an expired session (which signs the user out).
++ let plan =
++ "unauthorized: [MEMORY_PLAN_REQUIRED] memory API memory/scopes on api.tinyhumans.ai: \
++ the session expired or the API key was rejected (HTTP 403 Forbidden); \
++ re-authenticate — memory is not included in this account's plan";
++ assert!(is_plan_required_message(plan));
++ assert!(!is_session_expired_message(plan));
++ assert_eq!(
++ expected_error_kind(plan),
++ Some(ExpectedErrorKind::BackendUserError)
++ );
++ assert!(!is_plan_required_message(
++ "[USER_INSUFFICIENT_CREDITS] top up"
++ ));
++ // Only the delimited code in a hosted failure head counts, not a mention.
++ assert!(!is_plan_required_message(
++ "backend returned 500: unexpected [MEMORY_PLAN_REQUIRED] token"
++ ));
++ assert!(!is_plan_required_message(
++ "engine error: saw [not a code_PLAN_REQUIRED] memory API x"
++ ));
++}
diff --cc crates/openhuman-core/src/core/observability_error_classification_session_tests.rs
index 03786d30c0,51d31d231f..af417a01eb
--- a/crates/openhuman-core/src/core/observability_error_classification_session_tests.rs
+++ b/crates/openhuman-core/src/core/observability_error_classification_session_tests.rs
@@@ -742,3 -742,29 +742,6 @@@ fn classifies_offline_local_session_ref
));
assert!(!is_session_expired_message(msg));
}
+
-#[test]
-fn memory_plan_refusal_is_backend_user_state_not_session_expiry() {
- // #8081: memory not in the account's plan is user state for Sentry, and
- // must not read as an expired session (which signs the user out).
- let plan =
- "unauthorized: [MEMORY_PLAN_REQUIRED] memory API memory/scopes on api.tinyhumans.ai: \
- the session expired or the API key was rejected (HTTP 403 Forbidden); \
- re-authenticate — memory is not included in this account's plan";
- assert!(is_plan_required_message(plan));
- assert!(!is_session_expired_message(plan));
- assert_eq!(
- expected_error_kind(plan),
- Some(ExpectedErrorKind::BackendUserError)
- );
- assert!(!is_plan_required_message(
- "[USER_INSUFFICIENT_CREDITS] top up"
- ));
- // Only the delimited code in a hosted failure head counts, not a mention.
- assert!(!is_plan_required_message(
- "backend returned 500: unexpected [MEMORY_PLAN_REQUIRED] token"
- ));
- assert!(!is_plan_required_message(
- "engine error: saw [not a code_PLAN_REQUIRED] memory API x"
- ));
-}
++#[path = "observability_error_classification_session_plan_tests.rs"]
++mod plan_tests;
diff --cc crates/openhuman-core/src/core/observability_release_tag.rs
index 9fca678d41,9fca678d41..25e717e364
--- a/crates/openhuman-core/src/core/observability_release_tag.rs
+++ b/crates/openhuman-core/src/core/observability_release_tag.rs
@@@ -13,3 -13,3 +13,31 @@@ pub(super) fn parse_version(version: &s
let minor = parts.next()?.parse::<u32>().ok()?;
Some((major, minor))
}
++
++/// Filter out events from **stale releases** — releases older than
++/// `MAX_AGE_MINOR_VERSIONS` minor versions behind the current build.
++///
++/// Ancient-client errors are not actionable against the current codebase.
++/// Target: ~4 issues from releases like v0.54.0 against current v0.58+.
++#[cfg(feature = "crash-reporting")]
++pub fn is_stale_release_event(event: &sentry::protocol::Event<'_>) -> bool {
++ // Maximum number of minor versions behind the current release to accept.
++ // Events from clients on releases older than this are dropped.
++ const MAX_AGE_MINOR_VERSIONS: u32 = 6;
++
++ let Some(release) = event.release.as_ref() else {
++ return false;
++ };
++
++ let current = env!("CARGO_PKG_VERSION");
++ parse_version(current).is_some_and(|(current_major, current_minor)| {
++ parse_release_tag(release).is_some_and(|(event_major, event_minor)| {
++ if event_major != current_major {
++ // Different major version = definitely stale (or from the future)
++ return event_major < current_major;
++ }
++ // Same major: check minor version gap
++ current_minor.saturating_sub(event_minor) > MAX_AGE_MINOR_VERSIONS
++ })
++ })
++}
diff --cc crates/openhuman-core/src/core/runtime/mod.rs
index 3ae6ea3b9f,3b7acd4f84..6a50181b81
--- a/crates/openhuman-core/src/core/runtime/mod.rs
+++ b/crates/openhuman-core/src/core/runtime/mod.rs
@@@ -64,10 -64,8 +64,10 @@@ pub mod tenant
pub use agent_scope::{agent_scope_dir, slot_for, AgentContextRegistry, AgentScopedState};
pub use builder::{CoreBuilder, CoreRuntime, DomainSet, ServiceSet, TokenSource};
- pub use context::{ContextOverlay, CoreContext};
+ pub use context::{AutonomyTierSource, ContextOverlay, CoreContext};
pub use dispatch_ctx::DispatchCtx;
+#[cfg(test)]
+pub(crate) use mode::lock_mode;
pub use mode::{current_mode, is_saas, Mode};
pub use saas::SaasConfig;
pub use tenant::{
diff --cc crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs
index 560e4a185e,0000000000..b4f1733dc6
mode 100644,000000..100644
--- a/crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs
@@@ -1,454 -1,0 +1,453 @@@
+use super::*;
+use async_trait::async_trait;
+use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
+
+const CHILD_PROMPT: &str = "headless-cron-child-result-marker";
+
+struct ChildInvocationDrop(std::sync::Arc<std::sync::atomic::AtomicBool>);
+
+impl Drop for ChildInvocationDrop {
+ fn drop(&mut self) {
+ self.0.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+}
+
+struct CronChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize,
+ child_calls: std::sync::atomic::AtomicUsize,
+ child_invocation_dropped: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ accepted_followups: std::sync::atomic::AtomicUsize,
+ child_attempts_dangerous_tool: bool,
+ child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool,
+ child_started: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
+ child_release: tokio::sync::Notify,
+}
+
+fn scheduled_agent_fixture(
+ timeout_secs: u64,
+) -> (
+ TempDir,
+ Config,
+ std::sync::Arc<crate::core::runtime::CoreContext>,
+ crate::core::runtime::DispatchCtx,
+ tinyflows_bus::schedule::types::CronJob,
+) {
+ let temp = TempDir::new().expect("cron workspace");
+ let mut config = Config::default();
+ config.workspace_dir = temp.path().join("workspace");
+ config.action_dir = config.workspace_dir.clone();
+ config.default_model = Some("test-model".into());
+ config.chat_provider = Some("omlx:test-model".into());
+ config.agent.agent_timeout_secs = timeout_secs;
+ config.reliability.scheduler_retries = 0;
+ std::fs::create_dir_all(&config.workspace_dir).expect("workspace");
+
+ let definitions =
+ Arc::new(crate::agent_registry::host_definition::AgentDefinitionRegistry::builtins_only());
+ let core = crate::core::runtime::CoreContext::for_test_with_config(
+ crate::core::runtime::DomainSet::full(),
+ config.clone(),
+ )
+ .derive_with(
+ crate::core::runtime::ContextOverlay::new(
+ config.clone(),
+ crate::core::runtime::DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::none(),
+ )
+ .definitions(definitions),
+ );
+ let dispatch = crate::core::runtime::DispatchCtx::new(std::sync::Arc::clone(&core));
- let job = crate::cron::add_agent_job(
- &config,
- Some("headless child test".into()),
++ let mut spec = tinyflows_bus::schedule::AgentJobSpec::new(
+ tinyflows_bus::schedule::types::Schedule::Every {
+ every_ms: 3_600_000,
+ },
+ "Delegate this scheduled task to its worker.",
- SessionTarget::Isolated,
- Some("test-model".into()),
- None,
- false,
- )
- .expect("persist scheduled agent job");
++ );
++ spec.name = Some("headless child test".into());
++ spec.session_target = SessionTarget::Isolated;
++ spec.model = Some("test-model".into());
++ spec.enabled = true;
++ let job =
++ crate::cron::add_agent_job_from_spec(&config, spec).expect("persist scheduled agent job");
+ crate::cron::store::force_next_run_for_test(
+ &config,
+ &job.id,
+ chrono::Utc::now() - chrono::Duration::seconds(1),
+ )
+ .expect("make the job due");
+ (temp, config, core, dispatch, job)
+}
+
+async fn dispatch_scheduled_agent(
+ core: std::sync::Arc<crate::core::runtime::CoreContext>,
+ dispatch: crate::core::runtime::DispatchCtx,
+ config: Config,
+) {
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ let mut dispatcher = JobDispatcher::new(&dispatch, &config, &security);
+ crate::core::runtime::CoreContext::scope(
+ core,
+ Box::pin(async move {
+ let dispatched = dispatcher.tick(&config).await.expect("scheduler tick");
+ assert_eq!(dispatched, 1, "the persisted due job is dispatched");
+ dispatcher.drain().await;
+ }),
+ )
+ .await;
+}
+
+#[async_trait]
+impl ChatModel<()> for CronChildModel {
+ fn profile(&self) -> Option<&ModelProfile> {
+ static PROFILE: std::sync::OnceLock<ModelProfile> = std::sync::OnceLock::new();
+ Some(PROFILE.get_or_init(|| ModelProfile {
+ tool_calling: true,
+ parallel_tool_calls: true,
+ ..ModelProfile::default()
+ }))
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ if request
+ .messages
+ .iter()
+ .any(|message| message.text().contains(CHILD_PROMPT))
+ {
+ let call = self
+ .child_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if let Some(started) = self.child_started.lock().unwrap().take() {
+ let _ = started.send(());
+ }
+ if self.child_attempts_dangerous_tool {
+ if call > 0 {
+ return Ok(ModelResponse::assistant(
+ "headless-cron-child-returned-after-policy-denial",
+ ));
+ }
+ self.child_dangerous_tool_schema_seen.store(
+ request
+ .tools
+ .iter()
+ .any(|tool| tool.name == "delete_artifact"),
+ std::sync::atomic::Ordering::SeqCst,
+ );
+ let mut response = ModelResponse::assistant("");
+ response.message.tool_calls = vec![tinyinference_llm::tool::ToolCall::new(
+ "headless-cron-forbidden-write",
+ "delete_artifact",
+ serde_json::json!({"artifact_id": "missing-headless-cron-artifact"}),
+ )];
+ response.finish_reason = Some("tool_calls".into());
+ return Ok(response);
+ }
+ if let Some(started) = self.child_started.lock().unwrap().take() {
+ let _ = started.send(());
+ }
+ let _drop = ChildInvocationDrop(std::sync::Arc::clone(&self.child_invocation_dropped));
+ self.child_release.notified().await;
+ return Ok(ModelResponse::assistant("headless-cron-child-result"));
+ }
+
+ if request.messages.iter().any(|message| {
+ message
+ .text()
+ .contains("Accepted async sub-agent `task_manager_agent`")
+ }) {
+ self.accepted_followups
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ return Ok(ModelResponse::assistant("headless-cron-root-result"));
+ }
+
+ if self
+ .spawn_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ > 0
+ {
+ return Ok(ModelResponse::assistant("headless-cron-root-result"));
+ }
+ let mut response = ModelResponse::assistant("");
+ response.message.tool_calls = vec![tinyinference_llm::tool::ToolCall::new(
+ "headless-cron-spawn",
+ "spawn_subagent",
+ serde_json::json!({
+ "agent_id": "task_manager_agent",
+ "prompt": CHILD_PROMPT,
+ "task_key": "headless-cron-child-task",
+ "context": "headless cron regression",
+ "model": "test-model"
+ }),
+ )];
+ response.finish_reason = Some("tool_calls".into());
+ Ok(response)
+ }
+}
+
+#[tokio::test]
+async fn scheduled_agent_history_includes_its_spawned_child_result() {
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let model = std::sync::Arc::new(CronChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_invocation_dropped: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ accepted_followups: std::sync::atomic::AtomicUsize::new(0),
+ child_attempts_dangerous_tool: false,
+ child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool::new(false),
+ child_started: std::sync::Mutex::new(None),
+ child_release: tokio::sync::Notify::new(),
+ });
+ let _model =
+ crate::inference::provider::factory::test_provider_override::install_model(model.clone());
+ let (_temp, config, core, dispatch, job) = scheduled_agent_fixture(900);
+
+ let (child_started_tx, child_started_rx) = tokio::sync::oneshot::channel();
+ *model.child_started.lock().unwrap() = Some(child_started_tx);
+ let scheduler_config = config.clone();
+ let run =
+ tokio::spawn(
+ async move { dispatch_scheduled_agent(core, dispatch, scheduler_config).await },
+ );
+ match tokio::time::timeout(std::time::Duration::from_secs(5), child_started_rx).await {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) => panic!("child-start observation disconnected: {error}"),
+ Err(_) => {
+ model.child_release.notify_one();
+ let result = tokio::time::timeout(std::time::Duration::from_secs(5), run).await;
+ panic!(
+ "scheduled child never reached its model (spawn calls: {}, followups: {}); run result: {result:?}",
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ model.accepted_followups.load(std::sync::atomic::Ordering::SeqCst),
+ );
+ }
+ }
+ model.child_release.notify_one();
+
+ run.await.expect("cron scheduler task");
+ let runs = crate::cron::list_runs(&config, &job.id, 10).expect("read persisted run history");
+ assert_eq!(runs.len(), 1, "scheduler persisted one completed run");
+ assert_eq!(runs[0].status, "ok", "agent job completed successfully");
+ assert!(
+ runs[0]
+ .output
+ .as_deref()
+ .unwrap_or_default()
+ .contains("headless-cron-child-result"),
+ "the persisted cron result must include its spawned child output: {}",
+ runs[0].output.as_deref().unwrap_or_default()
+ );
+ assert_eq!(
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert_eq!(
+ model.child_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert_eq!(
+ model
+ .accepted_followups
+ .load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the parent accepted the real spawn result before the child completed"
+ );
+}
+
+#[tokio::test]
+async fn scheduled_agent_timeout_cancels_its_blocked_child_before_history_settles() {
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let model = std::sync::Arc::new(CronChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_invocation_dropped: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ accepted_followups: std::sync::atomic::AtomicUsize::new(0),
+ child_attempts_dangerous_tool: false,
+ child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool::new(false),
+ child_started: std::sync::Mutex::new(None),
+ child_release: tokio::sync::Notify::new(),
+ });
+ let _model =
+ crate::inference::provider::factory::test_provider_override::install_model(model.clone());
+ let (_temp, config, core, dispatch, job) = scheduled_agent_fixture(2);
+ let inspect_dispatch = dispatch.clone();
+ let (child_started_tx, child_started_rx) = tokio::sync::oneshot::channel();
+ *model.child_started.lock().unwrap() = Some(child_started_tx);
+ let scheduler_config = config.clone();
+ let run =
+ tokio::spawn(
+ async move { dispatch_scheduled_agent(core, dispatch, scheduler_config).await },
+ );
+
+ match tokio::time::timeout(std::time::Duration::from_secs(5), child_started_rx).await {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) => panic!("scheduled child exited before its model blocked: {error}"),
+ Err(_) => {
+ model.child_release.notify_one();
+ let _ = tokio::time::timeout(std::time::Duration::from_secs(5), run).await;
+ panic!(
+ "scheduled child never reached its blocking model (spawns: {}, accepted followups: {})",
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ model.accepted_followups.load(std::sync::atomic::Ordering::SeqCst),
+ );
+ }
+ }
+
+ tokio::time::timeout(std::time::Duration::from_secs(5), run)
+ .await
+ .expect("cron timeout should settle the blocked run")
+ .expect("cron scheduler task");
+ let runs = crate::cron::list_runs(&config, &job.id, 10).expect("read persisted run history");
+ assert_eq!(runs.len(), 1, "scheduler persisted one completed attempt");
+ assert_ne!(runs[0].status, "ok", "the configured deadline expired");
+ assert!(!runs[0]
+ .output
+ .as_deref()
+ .unwrap_or_default()
+ .contains("headless-cron-child-result"));
+ assert_eq!(
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert_eq!(
+ model
+ .accepted_followups
+ .load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the root accepted the child before waiting on it"
+ );
+ assert_eq!(
+ model.child_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert!(
+ model
+ .child_invocation_dropped
+ .load(std::sync::atomic::Ordering::SeqCst),
+ "the root deadline dropped the child model future"
+ );
+ let owner = crate::agent::tinyagents::tool_registration::subagent_owner_key(
+ &config.workspace_dir,
+ &format!("cron:{}", job.id),
+ None,
+ );
+ let registry = crate::core::runtime::slot_for::<
+ tinyagents_harness_tools::subagents::SubAgentJobRegistry,
+ >(&inspect_dispatch);
+ let jobs = registry
+ .try_list_owned(owner.as_str())
+ .expect("inspect this Cron run's native descendants");
+ assert_eq!(jobs.len(), 1, "one native child belongs to this Cron job");
+ let child = tokio::time::timeout(
+ std::time::Duration::from_secs(2),
+ registry.wait_owned(jobs[0].id.as_str(), owner),
+ )
+ .await
+ .expect("root timeout cancellation reaches its child")
+ .expect("the child remains available until its terminal state");
+ assert_eq!(
+ child.status,
+ tinyagents_orchestration::subagent::SubAgentJobStatus::Cancelled,
+ "the root deadline cancels the blocked native child"
+ );
+}
+
+#[tokio::test]
+async fn scheduled_cron_child_cannot_run_its_declared_destructive_tool() {
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let model = std::sync::Arc::new(CronChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_invocation_dropped: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ accepted_followups: std::sync::atomic::AtomicUsize::new(0),
+ child_attempts_dangerous_tool: true,
+ child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool::new(false),
+ child_started: std::sync::Mutex::new(None),
+ child_release: tokio::sync::Notify::new(),
+ });
+ let _model =
+ crate::inference::provider::factory::test_provider_override::install_model(model.clone());
+ let (_temp, config, core, dispatch, job) = scheduled_agent_fixture(900);
+ let inspect_dispatch = dispatch.clone();
+ let (child_started_tx, child_started_rx) = tokio::sync::oneshot::channel();
+ *model.child_started.lock().unwrap() = Some(child_started_tx);
+ let scheduler_config = config.clone();
+ let run =
+ tokio::spawn(
+ async move { dispatch_scheduled_agent(core, dispatch, scheduler_config).await },
+ );
+ match tokio::time::timeout(std::time::Duration::from_secs(5), child_started_rx).await {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) => panic!("scheduled child exited before its model call: {error}"),
+ Err(_) => {
+ let _ = tokio::time::timeout(std::time::Duration::from_secs(5), run).await;
+ panic!("scheduled child never reached its model");
+ }
+ }
+ tokio::time::timeout(std::time::Duration::from_secs(5), run)
+ .await
+ .expect("Cron should settle the denied child result")
+ .expect("Cron scheduler task");
+
+ assert_eq!(
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert_eq!(
+ model.child_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the child model requested the declared destructive tool"
+ );
+ assert!(
+ model
+ .child_dangerous_tool_schema_seen
+ .load(std::sync::atomic::Ordering::SeqCst),
+ "the real child model request exposed the declared destructive tool"
+ );
+ let owner = crate::agent::tinyagents::tool_registration::subagent_owner_key(
+ &config.workspace_dir,
+ &format!("cron:{}", job.id),
+ None,
+ );
+ let jobs = crate::core::runtime::slot_for::<
+ tinyagents_harness_tools::subagents::SubAgentJobRegistry,
+ >(&inspect_dispatch)
+ .try_list_owned(owner)
+ .expect("inspect the exact Cron session owner");
+ assert_eq!(jobs.len(), 1, "one native child belongs to this Cron job");
+ assert_eq!(
+ jobs[0].status,
+ tinyagents_orchestration::subagent::SubAgentJobStatus::Incomplete,
+ "the child records the policy-blocked action as an incomplete run"
+ );
+ let child_run_id = jobs[0]
+ .subagent_run_id
+ .as_deref()
+ .expect("native child records its own run id");
+ let child_events =
+ crate::agent::tinyagents::journal::read_run_events(&inspect_dispatch, child_run_id, 0)
+ .await
+ .expect("read the native child's durable tool events");
+ let denial = child_events
+ .iter()
+ .find_map(|observation| match &observation.event {
+ tinyagents_harness::events::AgentEvent::ToolCompleted {
+ tool_name,
+ error: Some(error),
+ ..
+ } if tool_name == "delete_artifact" => Some(error.as_str()),
+ _ => None,
+ })
+ .expect("the native child journal records the denied delete_artifact call");
+ assert!(denial.contains("Scheduled agent turns may use read-only tools only"));
+ assert!(!denial.contains("not found"));
+ let runs = crate::cron::list_runs(&config, &job.id, 10).expect("read persisted run history");
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0].status, "error");
+}
diff --cc crates/openhuman-core/src/flows/caps_host/agent_harness.rs
index 0000000000,999008de0e..8039428439
mode 000000,100644..100644
--- a/crates/openhuman-core/src/flows/caps_host/agent_harness.rs
+++ b/crates/openhuman-core/src/flows/caps_host/agent_harness.rs
@@@ -1,0 -1,219 +1,221 @@@
+ use super::tier::escalated_origin_for_nested_harness;
+ use super::*;
+ use std::borrow::Cow;
+
+ impl OpenHumanAgentRunner {
+ /// Full harness turn: build a real session agent for `agent_ref` and drive
+ /// one `run_single` under the node's model override + timeout. See
+ /// [`OpenHumanAgentRunner`] for the security/origin contract.
+ ///
+ /// `entry_model` is the custom `AgentRegistryEntry`'s own `model` pin (a
+ /// `hint:<role>` or raw BYOK model id), when `agent_ref` resolved to one —
+ /// `None` for a shipped/TOML harness definition, which has no such entry.
+ /// It is the fallback below the node's own `config.model` override (see
+ /// `resolve_node_model`), matching the precedence
+ /// `run_via_registry_fallback` already gave `entry.model` — without this,
+ /// a custom flow agent's model pin (e.g. `hint:reasoning`) silently
+ /// dropped to the default chat model once routed through the harness.
+ ///
- /// **Synchronous only (B40 / Gap 4).** A flow `agent` node runs here with
- /// no explicit chat thread on its run context. If the
- /// agent it runs is a delegating agent (e.g. the orchestrator) and
- /// calls `spawn_async_subagent` directly, the tool now refuses (see the
- /// `parent_thread_id.is_none()` guard in
- /// `agent_orchestration::tools::spawn_async_subagent`) rather than
- /// silently discarding the background result once it finishes —
- /// `background_delivery` has nowhere to deliver it without a thread id.
- /// This module does not bridge async subagent delivery into flow runs.
- /// For work that needs to happen in parallel, model it as parallel flow
- /// nodes (the tinyflows engine already fans those out) instead of
- /// reaching for a background sub-agent from inside a single node.
++ /// **Headless settlement.** A flow `agent` node has no chat thread, so it
++ /// opts its fresh session into bounded descendant settlement. Native
++ /// `spawn_subagent` calls remain asynchronous; the session waits for the
++ /// root-owned descendant tree and folds completed child output into the
++ /// node result before returning. The harness turn and descendant wait use
++ /// one absolute deadline derived from the node's effective timeout.
+ pub(super) async fn run_via_harness(
+ &self,
+ dispatch: &crate::core::runtime::DispatchCtx,
+ agent_ref: &str,
+ request: Value,
+ conn: Option<&str>,
+ entry_model: Option<&str>,
+ host: Option<crate::agent::host_agents::HostAgent>,
+ ) -> Result<Value> {
+ use crate::agent::OpenHumanSessionHost;
+
+ // Hold a slot for the whole turn: a fanned-out node can call this
+ // hundreds of times at once, and each call below builds a full agent
+ // session. Acquired before any work so waiters queue rather than pile
+ // up half-built agents. `_permit` is released on drop at end of scope,
+ // including on every early return below.
+ let _permit = HARNESS_AGENT_SLOTS.acquire().await.map_err(|_| {
+ EngineError::Capability(
+ "agent node: harness concurrency limiter closed unexpectedly".to_string(),
+ )
+ })?;
+
+ if let Some(c) = conn {
+ tracing::debug!(
+ target: "flows",
+ conn = %c,
+ "[flows] agent_runner: connection_ref present but not resolved to a BYOK account \
+ for the harness turn (matches OpenHumanLlm)"
+ );
+ }
+
+ // Model precedence for a harness node: node `config.model` > the
+ // custom registry entry's own `model` pin (if any) > the definition's
+ // own default.
+ let initial = self
+ .prepare_agent_run(request.clone(), entry_model, None, 0)
+ .await?;
+ let node_model = initial.model.clone();
+
+ // Apply the override the cron way (`run_agent_job`): a cloned `Config`
+ // with a new `default_model`, so we never mutate the shared config or
+ // invent a new Agent setter API. The tier is normalised to the
+ // `hint:<role>` form the session builder routes on.
+ // A host-registered agent starts from its own config (its provider
+ // model and route), not the flow runner's.
+ let base: &Config = host
+ .as_ref()
+ .map_or(self.config.as_ref(), |host| &host.config);
+ let effective: Cow<'_, Config> = match node_model.as_deref() {
+ Some(model) => {
+ let mut config = base.clone();
+ config.default_model = Some(harness_model_default_override(model));
+ Cow::Owned(config)
+ }
+ None => Cow::Borrowed(base),
+ };
+
+ let built = match &host {
+ Some(host) => host.session_host(effective.as_ref(), None),
+ None => {
+ OpenHumanSessionHost::from_config_for_agent(dispatch, effective.as_ref(), agent_ref)
+ }
+ };
+ let mut agent = built.map_err(|e| {
+ EngineError::Capability(format!(
+ "agent node: failed to build harness agent '{agent_ref}': {e:#}"
+ ))
+ })?;
+ agent.set_agent_definition_name(agent_ref.to_string());
+ agent.set_on_progress(self.progress.clone());
++ agent.enable_headless_descendant_settlement();
+
+ // Issue #4868 — the session builder now stamps `agent_ref`'s own
+ // `effective_max_iterations()` onto the agent (instead of the global
+ // default of 10), so `code_executor`/`tools_agent`/etc. can run up to
+ // 50 iterations here. Read the cap actually applied to `agent`
+ // (reflects the definition cap or the global fallback, whichever the
+ // builder resolved) and scale the DEFAULT timeout accordingly — see
+ // `scale_timeout_for_iteration_cap`.
+ //
+ // Post-merge Codex P2 finding: an EXPLICIT `timeout_secs` the node
+ // config supplied is a caller-chosen bound (e.g. a fast-fail/SLA of
+ // 120s) and must be honored as-is, never scaled up just because the
+ // agent's iteration cap is high — see `resolve_run_timeout_secs`.
+ let effective_iteration_cap = agent.agent_config().max_tool_iterations;
+ let prepared = self
+ .prepare_agent_run(
+ request.clone(),
+ entry_model,
+ None,
+ u32::try_from(effective_iteration_cap).unwrap_or(u32::MAX),
+ )
+ .await?;
+ let prompt = prepared.prompt;
+ let base_timeout_secs = prepared.base_timeout_secs;
+ let timeout_secs = prepared.timeout_secs;
++ let deadline = tinyagents_harness::turn_deadline::TurnDeadline::starting_now(
++ std::time::Duration::from_secs(timeout_secs),
++ );
++ let absolute_deadline =
++ tokio::time::Instant::from_std(deadline.started() + deadline.backstop());
++ let mut host_env = agent.host_env().clone();
++ host_env.turn_deadline = Some(deadline);
++ agent.set_host_env(host_env);
+
+ tracing::debug!(
+ target: "flows",
+ agent_ref,
+ node_model = node_model.as_deref().unwrap_or("<definition-default>"),
+ default_model = effective.default_model.as_deref().unwrap_or("<config-default>"),
+ effective_iteration_cap,
+ base_timeout_secs,
+ timeout_secs,
+ prompt_len = prompt.len(),
+ "[flows] agent_runner: dispatching full harness turn"
+ );
+
+ // Nested-harness HITL escalation (issue #4595): the engine future runs
+ // under the flow's Workflow origin, but the flow author only pre-
+ // declared `agent_ref` — not the concrete tools the harness LLM will
+ // pick from the definition's `ToolScope`. If we let the inner turn
+ // inherit a `Workflow { require_approval: false }` origin,
+ // `ApprovalGate::intercept_audited` treats it as a trust root and
+ // auto-`Allow`s external_effect tools (see
+ // `crates/openhuman-core/src/security/approval/gate.rs` `Workflow { require_approval: false }`
+ // branch), which would let a scheduled / app-event flow reach out to
+ // Slack / email / desktop control with no HITL. We force
+ // `require_approval: true` around `run_single` so external_effect tools
+ // park for a real decision the same way flow acting nodes escalated by
+ // [`gate_call_for_tier`] do. Read-only tools (no `external_effect`)
+ // aren't gated by `intercept_audited` at all, so this doesn't add noise
+ // for pure-read nested agents.
+ //
+ // Cancellation: the run_registry token aborts the engine future, and the
+ // inner turn drops with it (task-local scope unwinds cleanly).
+ use crate::security::turn_origin;
+ let escalated_origin = escalated_origin_for_nested_harness(self.ctx.turn_origin());
+ if let Some(ref escalated) = escalated_origin {
+ tracing::debug!(
+ target: "flows",
+ agent_ref,
+ origin = ?escalated,
+ "[flows] agent_runner: escalating nested harness turn to Workflow{{require_approval:true}} \
+ so external_effect tools park for HITL (issue #4595)"
+ );
+ }
+ let run: std::pin::Pin<
+ Box<dyn std::future::Future<Output = anyhow::Result<String>> + Send>,
+ > = if let Some(escalated) = escalated_origin {
+ Box::pin(turn_origin::with_origin(
+ escalated,
+ agent.run_single_with_approval(&prompt, None, self.approval.clone()),
+ ))
+ } else {
+ Box::pin(agent.run_single_with_approval(&prompt, None, self.approval.clone()))
+ };
+ // A host agent's turn reads its own context (config, domains, tool
+ // groups, session store); the origin task-local is untouched.
+ let run: std::pin::Pin<
+ Box<dyn std::future::Future<Output = anyhow::Result<String>> + Send>,
+ > = match host
+ .as_ref()
+ .map(|host| std::sync::Arc::clone(&host.context))
+ {
+ Some(context) => Box::pin(crate::core::runtime::CoreContext::scope(context, run)),
+ None => run,
+ };
- let final_text =
- match tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), run).await {
- Ok(Ok(text)) => text,
- Ok(Err(e)) => {
- tracing::warn!(
- target: "flows",
- agent_ref,
- error = %e,
- "[flows] agent_runner: harness turn failed"
- );
- return Err(EngineError::Capability(format!(
- "agent node '{agent_ref}' turn failed: {e:#}"
- )));
- }
- Err(_) => {
- tracing::warn!(
- target: "flows",
- agent_ref,
- timeout_secs,
- "[flows] agent_runner: harness turn timed out"
- );
- return Err(EngineError::Capability(format!(
- "agent node '{agent_ref}' timed out after {timeout_secs}s"
- )));
- }
- };
++ let final_text = match tokio::time::timeout_at(absolute_deadline, run).await {
++ Ok(Ok(text)) => text,
++ Ok(Err(e)) => {
++ tracing::warn!(
++ target: "flows",
++ agent_ref,
++ error = %e,
++ "[flows] agent_runner: harness turn failed"
++ );
++ return Err(EngineError::Capability(format!(
++ "agent node '{agent_ref}' turn failed: {e:#}"
++ )));
++ }
++ Err(_) => {
++ tracing::warn!(
++ target: "flows",
++ agent_ref,
++ timeout_secs,
++ "[flows] agent_runner: harness turn timed out"
++ );
++ return Err(EngineError::Capability(format!(
++ "agent node '{agent_ref}' timed out after {timeout_secs}s"
++ )));
++ }
++ };
+
+ self.format_agent_result(agent_ref, request, final_text)
+ .await
+ }
+ }
diff --cc crates/openhuman-core/src/flows/caps_host/agent_tests.rs
index f5b8b411f9,9c913b7f11..e266e6d1a6
--- a/crates/openhuman-core/src/flows/caps_host/agent_tests.rs
+++ b/crates/openhuman-core/src/flows/caps_host/agent_tests.rs
@@@ -29,259 -29,6 +29,259 @@@ async fn production_harness_ceiling_is_
assert!(!super::HARNESS_AGENT_SLOTS.is_closed());
}
+#[tokio::test]
+async fn headless_flow_agent_includes_nested_grandchild_result() {
+ use async_trait::async_trait;
+ use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
+
+ const CHILD_PROMPT: &str = "headless-flow-child-result-marker";
+ const GRANDCHILD_PROMPT: &str = "headless-flow-grandchild-result-marker";
+
+ struct FlowChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize,
+ child_calls: std::sync::atomic::AtomicUsize,
+ grandchild_calls: std::sync::atomic::AtomicUsize,
+ nested_spawn_calls: std::sync::atomic::AtomicUsize,
+ accepted_followups: std::sync::atomic::AtomicUsize,
+ child_started: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
+ child_release: tokio::sync::Notify,
+ root_followup: tokio::sync::Notify,
+ }
+
+ #[async_trait]
+ impl ChatModel<()> for FlowChildModel {
+ fn profile(&self) -> Option<&ModelProfile> {
+ static PROFILE: std::sync::OnceLock<ModelProfile> = std::sync::OnceLock::new();
+ Some(PROFILE.get_or_init(|| ModelProfile {
+ tool_calling: true,
+ parallel_tool_calls: true,
+ ..ModelProfile::default()
+ }))
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ if request
+ .messages
+ .iter()
+ .any(|message| message.text().contains(GRANDCHILD_PROMPT))
+ {
+ self.grandchild_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if let Some(started) = self.child_started.lock().unwrap().take() {
+ let _ = started.send(());
+ }
+ self.child_release.notified().await;
+ return Ok(ModelResponse::assistant("headless-flow-grandchild-result"));
+ }
+ if request
+ .messages
+ .iter()
+ .any(|message| message.text().contains(CHILD_PROMPT))
+ {
+ let call = self
+ .child_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if call > 0 {
+ return Ok(ModelResponse::assistant(
+ "headless-flow-worker-result-with-grandchild",
+ ));
+ }
+ self.nested_spawn_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ let mut response = ModelResponse::assistant("");
+ response.message.tool_calls = vec![tinyinference_llm::tool::ToolCall::new(
+ "headless-flow-grandchild-spawn",
+ "spawn_subagent",
+ serde_json::json!({
+ "agent_id": "task_manager_agent",
+ "prompt": GRANDCHILD_PROMPT,
+ "task_key": "headless-flow-grandchild-task",
+ "context": "headless flow grandchild regression",
+ "model": "test-model"
+ }),
+ )];
+ response.finish_reason = Some("tool_calls".into());
+ return Ok(response);
+ }
+
+ if request.messages.iter().any(|message| {
+ message
+ .text()
+ .contains("Accepted async sub-agent `flow_worker`")
+ }) {
+ self.accepted_followups
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ self.root_followup.notify_one();
+ return Ok(ModelResponse::assistant("headless-flow-root-result"));
+ }
+ if self
+ .spawn_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ > 0
+ {
+ return Ok(ModelResponse::assistant(
+ "headless-flow-root-finished-without-accepted-child",
+ ));
+ }
+ let mut response = ModelResponse::assistant("");
+ response.message.tool_calls = vec![tinyinference_llm::tool::ToolCall::new(
+ "headless-flow-spawn",
+ "spawn_subagent",
+ serde_json::json!({
+ "agent_id": "flow_worker",
+ "prompt": CHILD_PROMPT,
+ "task_key": "headless-flow-child-task",
+ "context": "headless flow regression",
+ "model": "test-model"
+ }),
+ )];
+ response.finish_reason = Some("tool_calls".into());
+ Ok(response)
+ }
+ }
+
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let model = std::sync::Arc::new(FlowChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_calls: std::sync::atomic::AtomicUsize::new(0),
+ grandchild_calls: std::sync::atomic::AtomicUsize::new(0),
+ nested_spawn_calls: std::sync::atomic::AtomicUsize::new(0),
+ accepted_followups: std::sync::atomic::AtomicUsize::new(0),
+ child_started: std::sync::Mutex::new(None),
+ child_release: tokio::sync::Notify::new(),
+ root_followup: tokio::sync::Notify::new(),
+ });
+ let _model =
+ crate::inference::provider::factory::test_provider_override::install_model(model.clone());
+ let workspace = tempfile::tempdir().expect("flow workspace");
+ let mut config = crate::config::Config::default();
+ config.workspace_dir = workspace.path().to_path_buf();
+ config.action_dir = workspace.path().to_path_buf();
+ config.default_model = Some("test-model".into());
+ config.chat_provider = Some("omlx:test-model".into());
+
+ let builtin_definitions =
+ crate::agent_registry::host_definition::AgentDefinitionRegistry::builtins_only();
+ let mut orchestrator = builtin_definitions
+ .get("orchestrator")
+ .expect("orchestrator definition")
+ .clone();
+ orchestrator.subagents = vec![tinyagents_definition::SubagentEntry::AgentId(
+ "flow_worker".to_string(),
+ )];
+ let mut worker = builtin_definitions
+ .get("task_manager_agent")
+ .expect("worker definition")
+ .clone();
+ worker.id = "flow_worker".to_string();
+ worker.agent_tier = tinyagents_definition::AgentTier::Reasoning;
+ worker.extra_tools.push("spawn_subagent".to_string());
+ worker.subagents = vec![tinyagents_definition::SubagentEntry::AgentId(
+ "task_manager_agent".to_string(),
+ )];
+ let definitions =
+ std::sync::Arc::new(builtin_definitions.with_definitions([orchestrator, worker]));
+ let core = crate::core::runtime::CoreContext::for_test_with_config(
+ crate::core::runtime::DomainSet::full(),
+ config.clone(),
+ )
+ .derive_with(
+ crate::core::runtime::ContextOverlay::new(
+ config.clone(),
+ crate::core::runtime::DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::none(),
+ )
+ .definitions(definitions),
+ );
+
+ let runner = super::OpenHumanAgentRunner {
+ config: std::sync::Arc::new(config),
+ ctx: crate::core::runtime::DispatchCtx::new(std::sync::Arc::clone(&core)),
+ approval: Default::default(),
++ progress: None,
+ };
+ let (child_started_tx, child_started_rx) = tokio::sync::oneshot::channel();
+ *model.child_started.lock().unwrap() = Some(child_started_tx);
+ let jobs_core = std::sync::Arc::clone(&core);
+ let run = tokio::spawn(async move {
+ crate::core::runtime::CoreContext::scope(
+ core,
- Box::pin(tinyflows::caps::AgentRunner::run_agent(
- &runner,
++ Box::pin(runner.run_agent(
+ "orchestrator",
+ serde_json::json!({"prompt": "Delegate this task to the child."}),
+ None,
+ )),
+ )
+ .await
+ });
+ tokio::time::timeout(std::time::Duration::from_secs(5), child_started_rx)
+ .await
+ .expect("the real native grandchild reaches its model")
+ .expect("grandchild-start observation remains connected");
+ tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ model.root_followup.notified(),
+ )
+ .await
+ .expect("the parent receives spawn acceptance and produces its final response");
+ tokio::task::yield_now().await;
+ let returned_before_child = run.is_finished();
+ model.child_release.notify_one();
+ let output = run.await.expect("flow runner task");
+ let output = output.expect("headless flow agent should settle its child");
+ let snapshots = crate::core::runtime::slot_for::<
+ tinyagents_harness_tools::subagents::SubAgentJobRegistry,
+ >(&crate::core::runtime::DispatchCtx::new(jobs_core))
+ .list();
+
+ assert_eq!(
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the parent model must issue the real spawn_subagent call"
+ );
+ assert_eq!(
+ model.child_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 2,
+ "the worker must run, spawn its grandchild, and complete through the real dispatch"
+ );
+ assert_eq!(
+ model
+ .nested_spawn_calls
+ .load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the worker must issue a real nested spawn"
+ );
+ assert_eq!(
+ model
+ .grandchild_calls
+ .load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the grandchild must run through the real model dispatch"
+ );
+ assert_eq!(
+ model
+ .accepted_followups
+ .load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the parent must receive the actual async spawn acceptance"
+ );
+ assert!(
+ !returned_before_child,
+ "the headless flow must remain pending after root turn until its child settles; jobs: {snapshots:?}"
+ );
+
+ assert!(
+ output
+ .to_string()
+ .contains("headless-flow-grandchild-result"),
+ "the headless flow result must include its grandchild output: {output}"
+ );
+}
+
// --- host-registered agents (agent::host_agents) ---
struct FlowsHost;
diff --cc crates/openhuman-core/src/inference/host_runtime/ops.rs
index 3d9c187267,3ccfcc0a4b..8717920dd3
--- a/crates/openhuman-core/src/inference/host_runtime/ops.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops.rs
@@@ -14,13 -13,14 +13,17 @@@ mod complete_once
mod runtime_ops;
mod turn_guards;
- pub(crate) use agent_chat::agent_chat_reply_for_with_headless;
pub use agent_chat::{
- agent_chat, agent_chat_for, agent_chat_reply_for, agent_chat_simple, AgentChatEnv,
- AgentChatReply, AgentChatTarget,
+ agent_chat, agent_chat_for, agent_chat_reply_for, agent_chat_reply_for_controlled,
+ agent_chat_simple, AgentChatEnv, AgentChatReply, AgentChatTarget,
+ };
++pub(crate) use agent_chat::{
++ agent_chat_for_with_turn_model_source, agent_chat_reply_for_with_headless,
++};
+ pub use complete_once::{
+ complete_once, complete_once_controlled, complete_once_observed,
+ validate_complete_once_request, CompletionEndpoint,
};
- pub(crate) use agent_chat_source::agent_chat_for_with_turn_model_source;
- pub use complete_once::{complete_once, CompletionEndpoint};
pub use runtime_ops::{
local_ai_prompt, local_ai_status, local_ai_summarize, local_ai_transcribe,
local_ai_transcribe_bytes, local_ai_tts, local_ai_vision_prompt,
diff --cc crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
index 7d3ea4bb52,9983223bfe..4d9626204d
--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
@@@ -5,6 -5,6 +5,12 @@@ use crate::config::Config
use crate::core::Outcome;
use crate::inference::provider as providers;
++mod simple;
++#[path = "agent_chat/types.rs"]
++mod types;
++pub use simple::agent_chat_simple;
++pub use types::{AgentChatEnv, AgentChatReply, AgentChatTarget};
++
use super::turn_guards::{
effective_agent_chat_origin, enforce_user_prompt_or_reject, grant_turn_cwd,
normalize_model_override, resolve_turn_cwd,
@@@ -72,185 -72,185 +78,6 @@@ pub async fn agent_chat
.await
}
--/// What an in-process caller hands one [`agent_chat_for`] turn besides its
--/// request: the live progress receiver and the host environment (shared model
--/// budget, delegation depth, cancellation, deadline, hooks, tool-belt
--/// authority). Both are explicit values that travel with the call -- never an
--/// ambient scope -- so they reach exactly this turn and its child runs.
--#[derive(Clone, Default)]
--pub struct AgentChatEnv {
-- /// Live progress for the turn; `None` attaches a drain-only sink so the
-- /// model calls still stream.
-- pub progress: Option<tokio::sync::mpsc::Sender<crate::progress::AgentProgress>>,
-- /// The host environment installed on the session
-- /// ([`OpenHumanSessionHost::set_host_env`]).
-- pub host: crate::agent::turn_env::HostTurnEnv,
-- /// Messages to steer the turn while it runs
-- /// ([`OpenHumanSessionHost::set_run_queue`]). Items pushed on its
-- /// [`QueueLane::Steer`](tinyagents_harness::run_queue::QueueLane::Steer)
-- /// lane before or during the turn are injected as user messages at the
-- /// loop's next safe checkpoint; a steer that arrives while the model is
-- /// writing its final answer earns one more model call. Steers the turn
-- /// did not apply are back on the lane once this call returns.
-- pub run_queue: Option<
-- std::sync::Arc<
-- tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>,
-- >,
-- >,
--}
--
--/// The log line every successful agent chat turn carries.
--const AGENT_CHAT_COMPLETED_LOG: &str = "agent chat completed";
--
--/// What one agent chat turn produced: its reply and whether it stopped at the
--/// tool-iteration cap rather than finishing.
--#[derive(Debug, Clone, PartialEq, Eq)]
--pub struct AgentChatReply {
-- /// The reply text. When `hit_cap` is set this is the turn's checkpoint.
-- pub text: String,
-- /// The turn paused at its iteration cap (see
-- /// [`OpenHumanSessionHost::last_turn_hit_cap`]).
-- pub hit_cap: bool,
--}
--
--impl AgentChatReply {
-- /// The historical `Outcome<String>` shape, for library callers.
-- pub fn into_outcome(self) -> Outcome<String> {
-- Outcome::single_log(self.text, AGENT_CHAT_COMPLETED_LOG)
-- }
--
-- /// The `inference.agent_chat` wire shape: the historical
-- /// `{"result": <text>, "logs": [...]}` envelope plus `hit_cap`, and, when
-- /// the turn was capped, `checkpoint` (the same text, named for what it is).
-- ///
-- /// Additive on purpose: existing clients keep reading the reply from
-- /// `result` (directly or through `unwrap_rpc`), and a headless caller can
-- /// now tell a capped turn from a finished one and continue it (#6958).
-- pub fn into_rpc_json(self) -> Result<serde_json::Value, String> {
-- let hit_cap = self.hit_cap;
-- let checkpoint = hit_cap.then(|| self.text.clone());
-- let mut value = self.into_outcome().into_cli_compatible_json()?;
-- let serde_json::Value::Object(map) = &mut value else {
-- return Err("agent chat envelope is not a JSON object".to_string());
-- };
-- map.insert("hit_cap".to_string(), serde_json::Value::Bool(hit_cap));
-- if let Some(checkpoint) = checkpoint {
-- map.insert(
-- "checkpoint".to_string(),
-- serde_json::Value::String(checkpoint),
-- );
-- }
-- Ok(value)
-- }
--}
--
--/// Which session [`agent_chat_for`] builds the turn on.
--#[derive(Clone, Copy)]
--pub enum AgentChatTarget<'a> {
-- /// The orchestrator — [`OpenHumanSessionHost::from_config`], today's `agent_chat`.
-- Orchestrator,
-- /// Resolve `id` the way every other id-keyed entry point does: the
-- /// process registry first, then `config.agent_registry.entries`.
-- AgentId(&'a str),
-- /// A definition the caller already holds; nothing is resolved by id. The
-- /// entry point for a library host running its own per-agent specs — see
-- /// [`OpenHumanSessionHost::from_config_with_definition`].
-- ///
-- /// `host` carries the caller's own `dyn Tool` objects. It rides the target
-- /// rather than `agent_chat_for`'s argument list because only this target
-- /// can honour it: the other two resolve a definition the caller does not
-- /// hold, so there is no agent for a host belt to belong to.
-- Definition {
-- definition: &'a crate::agent_registry::host_definition::AgentDefinition,
-- host: Option<&'a crate::agent::HostTools>,
-- /// History to seed this turn with, as `(role, content)` rows, instead
-- /// of whatever the session would otherwise resume.
-- ///
-- /// Rides the target for the same reason `host` does, and it is the
-- /// per-turn half of the same idea: a host whose history lives in its
-- /// own log -- a journal, a board, an episode -- is the only thing that
-- /// can say what this turn should have seen. Seeding is how that view
-- /// reaches the session with roles intact; passing it as prose in the
-- /// message would flatten the host's own prior turns into quoted text.
-- ///
-- /// `None` leaves resume untouched, which is every existing caller.
-- seed: Option<&'a [(String, String)]>,
-- /// Where to report what the turn spent.
-- ///
-- /// An out-parameter because this is the only target that can fill it:
-- /// the turn runs in-process here, so the session that counted the
-- /// tokens is still in hand when it ends. The other two answer over
-- /// `AGENT_CHAT`, whose reply is a string.
-- ///
-- /// Written whether the turn succeeded or failed -- a turn that ended
-- /// badly still spent what it spent, and a host that meters only
-- /// successes bills nothing for the ones that cost most.
-- usage: Option<&'a std::sync::Mutex<Option<crate::agent::tinyagents::host::LastTurnUsage>>>,
-- /// Build the session from `host` alone: no config-derived, delegation,
-- /// memory, skill or MCP tool, and a deny-by-default gate for any other
-- /// name. See [`OpenHumanSessionHost::from_config_host_only`].
-- host_only: bool,
-- /// Skip the prompt-injection guard: the message is untrusted data (a
-- /// PR diff) the agent reads, not an instruction. Refused unless
-- /// `host_only`, whose agent has nothing it could be talked into doing.
-- untrusted_input: bool,
-- /// A response format and output cap for every model call of the turn,
-- /// and the slot its final call is reported into.
-- shape: Option<&'a std::sync::Arc<tinyagents_harness::middleware::ResponseShapeScope>>,
-- /// The observer scoped around the caller, re-established around the
-- /// turn because the dispatch may run on a worker task that does not
-- /// inherit task locals.
-- observer: Option<
-- &'a std::sync::Arc<tinyagents_harness::observability::turn_observer::ObserverScope>,
-- >,
-- /// Files the host attaches to this turn as bytes, in order.
-- ///
-- /// Rides the target for the same reason `host` does: only an
-- /// in-process caller can hand over bytes, and `AGENT_CHAT` carries a
-- /// string. Each is staged into the acting workspace and reaches the
-- /// model as an image or document block ahead of the message, under
-- /// the configured multimodal count and size limits. No local path is
-- /// read, so they are accepted whatever the turn's origin.
-- ///
-- /// Empty for every caller that attaches nothing.
-- attachments: &'a [crate::agent::HostAttachment],
-- },
--}
--
--// Hand-written because a host belt is a closure, and a closure is not `Debug`.
--// Reporting whether one is present is what a log line here is ever for; the
--// belt it would return is not known until the turn builds it.
--impl std::fmt::Debug for AgentChatTarget<'_> {
-- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-- match self {
-- Self::Orchestrator => f.write_str("Orchestrator"),
-- Self::AgentId(id) => f.debug_tuple("AgentId").field(id).finish(),
-- Self::Definition {
-- definition,
-- host,
-- seed,
-- usage,
-- host_only,
-- untrusted_input,
-- shape,
-- observer,
-- attachments,
-- } => f
-- .debug_struct("Definition")
-- .field("definition", &definition.id)
-- .field("host_tools", &host.is_some())
-- .field("seed_rows", &seed.map_or(0, <[(String, String)]>::len))
-- .field("meters", &usage.is_some())
-- .field("host_only", host_only)
-- .field("untrusted_input", untrusted_input)
-- .field("attachments", &attachments.len())
-- .field("shaped", &shape.is_some())
-- .field("observed", &observer.is_some())
-- .finish(),
-- }
-- }
--}
--
// Definitions are reusable snapshots. A turn override belongs only to the
// definition passed to this call's factory, which otherwise wins over Config.
fn definition_for_turn(
@@@ -354,40 -337,7 +181,74 @@@ pub fn agent_chat_for<'a>
route: Option<crate::config::schema::EphemeralRoute>,
env: AgentChatEnv,
) -> futures::future::BoxFuture<'a, Result<Outcome<String>, String>> {
- Box::pin(agent_chat_for_inner(
+ Box::pin(async move {
+ agent_chat_reply_for_inner(
+ config,
+ target,
+ message,
+ model_override,
+ temperature,
+ thread_id,
+ cwd,
+ route,
+ env,
+ None,
+ false,
+ )
+ .await
+ .map(AgentChatReply::into_outcome)
++ .map_err(|error| error.to_string())
++ })
++}
++
++/// Runs a controlled direct agent turn with the caller's selected model source.
++#[allow(clippy::too_many_arguments)]
++pub(crate) fn agent_chat_for_with_turn_model_source<'a>(
++ config: &'a mut Config,
++ target: AgentChatTarget<'a>,
++ message: &'a str,
++ model_override: Option<String>,
++ temperature: Option<f64>,
++ thread_id: Option<String>,
++ cwd: Option<String>,
++ route: Option<crate::config::schema::EphemeralRoute>,
++ env: AgentChatEnv,
++ turn_model_source: (crate::agent::tinyagents::TurnModelSource, String),
++) -> futures::future::BoxFuture<'a, anyhow::Result<Outcome<String>>> {
++ Box::pin(async move {
++ agent_chat_reply_for_inner(
++ config,
++ target,
++ message,
++ model_override,
++ temperature,
++ thread_id,
++ cwd,
++ route,
++ env,
++ Some(turn_model_source),
++ false,
++ )
++ .await
++ .map(AgentChatReply::into_outcome)
+ })
+}
+
+/// [`agent_chat_for`], keeping whether the turn stopped at its iteration cap.
+/// The `inference.agent_chat` controller answers from this.
+#[allow(clippy::too_many_arguments)]
+pub async fn agent_chat_reply_for(
+ config: &mut Config,
+ target: AgentChatTarget<'_>,
+ message: &str,
+ model_override: Option<String>,
+ temperature: Option<f64>,
+ thread_id: Option<String>,
+ cwd: Option<String>,
+ route: Option<crate::config::schema::EphemeralRoute>,
+ env: AgentChatEnv,
+) -> Result<AgentChatReply, String> {
+ agent_chat_reply_for_with_headless(
config,
target,
message,
@@@ -425,14 -372,44 +286,45 @@@ pub(crate) async fn agent_chat_reply_fo
cwd,
route,
env,
+ None,
+ headless,
)
.await
- .map(AgentChatReply::into_outcome)
++ .map_err(|error| error.to_string())
+ }
+
-/// [`agent_chat_for`], keeping whether the turn stopped at its iteration cap.
-/// The `inference.agent_chat` controller answers from this.
++/// Retains typed host-policy errors for callers that need to distinguish
++/// dispatch refusal from provider failure.
+ #[allow(clippy::too_many_arguments)]
-pub async fn agent_chat_reply_for(
++pub async fn agent_chat_reply_for_controlled(
+ config: &mut Config,
+ target: AgentChatTarget<'_>,
+ message: &str,
+ model_override: Option<String>,
+ temperature: Option<f64>,
+ thread_id: Option<String>,
+ cwd: Option<String>,
+ route: Option<crate::config::schema::EphemeralRoute>,
+ env: AgentChatEnv,
-) -> Result<AgentChatReply, String> {
- agent_chat_reply_for_controlled(
++) -> anyhow::Result<AgentChatReply> {
++ agent_chat_reply_for_inner(
+ config,
+ target,
+ message,
+ model_override,
+ temperature,
+ thread_id,
+ cwd,
+ route,
+ env,
++ None,
++ false,
+ )
+ .await
- .map_err(|error| error.to_string())
}
-/// [`agent_chat_reply_for`] while retaining typed host-policy errors for
-/// callers that need to distinguish dispatch refusal from provider failure.
#[allow(clippy::too_many_arguments)]
-pub async fn agent_chat_reply_for_controlled(
+pub(super) async fn agent_chat_reply_for_inner(
config: &mut Config,
target: AgentChatTarget<'_>,
message: &str,
@@@ -442,9 -419,7 +334,9 @@@
cwd: Option<String>,
route: Option<crate::config::schema::EphemeralRoute>,
env: AgentChatEnv,
+ turn_model_source: Option<(crate::agent::tinyagents::TurnModelSource, String)>,
+ headless: bool,
- ) -> Result<AgentChatReply, String> {
+ ) -> anyhow::Result<AgentChatReply> {
match target {
AgentChatTarget::Definition {
untrusted_input: true,
@@@ -503,28 -481,17 +398,30 @@@
"[inference] agent_chat rooting turn tools at cwd={}",
root.display()
);
- let mut agent =
- build_turn_agent(&turn_ctx, &scoped, &target, turn_session_id, temperature)
- .map_err(anyhow::Error::msg)?;
+ let mut agent = build_turn_agent(
+ &turn_ctx,
+ &scoped,
+ &target,
+ turn_session_id,
+ temperature,
+ turn_model_source.clone(),
- )?;
++ )
++ .map_err(anyhow::Error::msg)?;
// Also thread it as the turn's workspace descriptor so acting tools
// that read `ToolExecutionContext::workspace` (shell) resolve their
// default cwd here, and so spawned sub-agents inherit the same root.
agent.set_workspace_descriptor(Some(tinytools::WorkspaceDescriptor::new(root.clone())));
agent
}
- None => build_turn_agent(&turn_ctx, config, &target, turn_session_id, temperature)
- .map_err(anyhow::Error::msg)?,
+ None => build_turn_agent(
+ &turn_ctx,
+ config,
+ &target,
+ turn_session_id,
+ temperature,
+ turn_model_source,
- )?,
++ )
++ .map_err(anyhow::Error::msg)?,
};
// Thread-correct resume. `OpenHumanSessionHost::turn` would otherwise auto-load the
// newest transcript for the agent *name*, which is another thread's
@@@ -706,74 -657,74 +600,6 @@@
Ok(AgentChatReply { text, hit_cap })
}
--/// A simplified chat interface that does not update the base configuration.
--pub async fn agent_chat_simple(
-- ctx: &crate::core::runtime::DispatchCtx,
-- config: &Config,
-- message: &str,
-- model_override: Option<String>,
-- temperature: Option<f64>,
-- thread_id: Option<String>,
--) -> Result<Outcome<String>, String> {
-- enforce_user_prompt_or_reject(message, "local_ai.ops.agent_chat_simple")?;
--
-- let mut effective = config.clone();
-- // TAURI-RUST-RS: see `normalize_model_override` for the rationale.
-- if let Some(model) = normalize_model_override(model_override) {
-- effective.default_model = Some(model);
-- }
-- if let Some(temp) = temperature {
-- effective.default_temperature = temp;
-- }
--
-- let default_model = effective
-- .default_model
-- .clone()
-- .unwrap_or_else(|| crate::config::DEFAULT_MODEL.to_string());
--
-- let (model, resolved_model): (
-- std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>,
-- String,
-- ) = if providers::factory::resolves_to_managed_backend("chat", &effective) {
-- let (backend, resolved_model) =
-- providers::factory::make_openhuman_backend_model_for_thread(
-- "chat",
-- &effective,
-- &default_model,
-- true,
-- thread_id.as_deref(),
-- &crate::security::egress::EgressLedger::none(),
-- )
-- .map_err(|e| e.to_string())?;
-- (backend, resolved_model)
-- } else {
-- providers::create_chat_model_with_model_id_in(
-- ctx,
-- "chat",
-- &effective,
-- effective.default_temperature,
-- )
-- .map_err(|e| e.to_string())?
-- };
-- tracing::debug!(
-- requested_model = %default_model,
-- resolved_model = %resolved_model,
-- temperature = effective.default_temperature,
-- "[inference] agent_chat_simple invoking crate-native chat model"
-- );
-- let run = model.invoke(
-- &(),
-- tinyinference_llm::model::ModelRequest::new(vec![
-- tinyinference_llm::message::Message::user(message.to_string()),
-- ])
-- .with_model(default_model.clone())
-- .with_temperature(effective.default_temperature),
-- );
-- let response = run.await.map_err(|e| e.to_string())?.text();
--
-- Ok(Outcome::single_log(response, "agent simple chat completed"))
--}
--
#[cfg(test)]
#[path = "agent_chat_tests.rs"]
mod tests;
diff --cc crates/openhuman-core/src/inference/host_runtime/ops/agent_chat/simple.rs
index 0000000000,0000000000..f317675c7a
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat/simple.rs
@@@ -1,0 -1,0 +1,69 @@@
++use super::*;
++
++/// A simplified chat interface that does not update the base configuration.
++pub async fn agent_chat_simple(
++ ctx: &crate::core::runtime::DispatchCtx,
++ config: &Config,
++ message: &str,
++ model_override: Option<String>,
++ temperature: Option<f64>,
++ thread_id: Option<String>,
++) -> Result<Outcome<String>, String> {
++ enforce_user_prompt_or_reject(message, "local_ai.ops.agent_chat_simple")?;
++
++ let mut effective = config.clone();
++ // TAURI-RUST-RS: see `normalize_model_override` for the rationale.
++ if let Some(model) = normalize_model_override(model_override) {
++ effective.default_model = Some(model);
++ }
++ if let Some(temp) = temperature {
++ effective.default_temperature = temp;
++ }
++
++ let default_model = effective
++ .default_model
++ .clone()
++ .unwrap_or_else(|| crate::config::DEFAULT_MODEL.to_string());
++
++ let (model, resolved_model): (
++ std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>,
++ String,
++ ) = if providers::factory::resolves_to_managed_backend("chat", &effective) {
++ let (backend, resolved_model) =
++ providers::factory::make_openhuman_backend_model_for_thread(
++ "chat",
++ &effective,
++ &default_model,
++ true,
++ thread_id.as_deref(),
++ &crate::security::egress::EgressLedger::none(),
++ )
++ .map_err(|e| e.to_string())?;
++ (backend, resolved_model)
++ } else {
++ providers::create_chat_model_with_model_id_in(
++ ctx,
++ "chat",
++ &effective,
++ effective.default_temperature,
++ )
++ .map_err(|e| e.to_string())?
++ };
++ tracing::debug!(
++ requested_model = %default_model,
++ resolved_model = %resolved_model,
++ temperature = effective.default_temperature,
++ "[inference] agent_chat_simple invoking crate-native chat model"
++ );
++ let run = model.invoke(
++ &(),
++ tinyinference_llm::model::ModelRequest::new(vec![
++ tinyinference_llm::message::Message::user(message.to_string()),
++ ])
++ .with_model(default_model.clone())
++ .with_temperature(effective.default_temperature),
++ );
++ let response = run.await.map_err(|e| e.to_string())?.text();
++
++ Ok(Outcome::single_log(response, "agent simple chat completed"))
++}
diff --cc crates/openhuman-core/src/inference/host_runtime/ops/agent_chat/types.rs
index 0000000000,0000000000..a013b3076f
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat/types.rs
@@@ -1,0 -1,0 +1,180 @@@
++use super::*;
++
++/// What an in-process caller hands one [`agent_chat_for`] turn besides its
++/// request: the live progress receiver and the host environment (shared model
++/// budget, delegation depth, cancellation, deadline, hooks, tool-belt
++/// authority). Both are explicit values that travel with the call -- never an
++/// ambient scope -- so they reach exactly this turn and its child runs.
++#[derive(Clone, Default)]
++pub struct AgentChatEnv {
++ /// Live progress for the turn; `None` attaches a drain-only sink so the
++ /// model calls still stream.
++ pub progress: Option<tokio::sync::mpsc::Sender<crate::progress::AgentProgress>>,
++ /// The host environment installed on the session
++ /// ([`OpenHumanSessionHost::set_host_env`]).
++ pub host: crate::agent::turn_env::HostTurnEnv,
++ /// Messages to steer the turn while it runs
++ /// ([`OpenHumanSessionHost::set_run_queue`]). Items pushed on its
++ /// [`QueueLane::Steer`](tinyagents_harness::run_queue::QueueLane::Steer)
++ /// lane before or during the turn are injected as user messages at the
++ /// loop's next safe checkpoint; a steer that arrives while the model is
++ /// writing its final answer earns one more model call. Steers the turn
++ /// did not apply are back on the lane once this call returns.
++ pub run_queue: Option<
++ std::sync::Arc<
++ tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>,
++ >,
++ >,
++}
++
++/// The log line every successful agent chat turn carries.
++pub const AGENT_CHAT_COMPLETED_LOG: &str = "agent chat completed";
++
++/// What one agent chat turn produced: its reply and whether it stopped at the
++/// tool-iteration cap rather than finishing.
++#[derive(Debug, Clone, PartialEq, Eq)]
++pub struct AgentChatReply {
++ /// The reply text. When `hit_cap` is set this is the turn's checkpoint.
++ pub text: String,
++ /// The turn paused at its iteration cap (see
++ /// [`OpenHumanSessionHost::last_turn_hit_cap`]).
++ pub hit_cap: bool,
++}
++
++impl AgentChatReply {
++ /// The historical `Outcome<String>` shape, for library callers.
++ pub fn into_outcome(self) -> Outcome<String> {
++ Outcome::single_log(self.text, AGENT_CHAT_COMPLETED_LOG)
++ }
++
++ /// The `inference.agent_chat` wire shape: the historical
++ /// `{"result": <text>, "logs": [...]}` envelope plus `hit_cap`, and, when
++ /// the turn was capped, `checkpoint` (the same text, named for what it is).
++ ///
++ /// Additive on purpose: existing clients keep reading the reply from
++ /// `result` (directly or through `unwrap_rpc`), and a headless caller can
++ /// now tell a capped turn from a finished one and continue it (#6958).
++ pub fn into_rpc_json(self) -> Result<serde_json::Value, String> {
++ let hit_cap = self.hit_cap;
++ let checkpoint = hit_cap.then(|| self.text.clone());
++ let mut value = self.into_outcome().into_cli_compatible_json()?;
++ let serde_json::Value::Object(map) = &mut value else {
++ return Err("agent chat envelope is not a JSON object".to_string());
++ };
++ map.insert("hit_cap".to_string(), serde_json::Value::Bool(hit_cap));
++ if let Some(checkpoint) = checkpoint {
++ map.insert(
++ "checkpoint".to_string(),
++ serde_json::Value::String(checkpoint),
++ );
++ }
++ Ok(value)
++ }
++}
++
++/// Which session [`agent_chat_for`] builds the turn on.
++#[derive(Clone, Copy)]
++pub enum AgentChatTarget<'a> {
++ /// The orchestrator — [`OpenHumanSessionHost::from_config`], today's `agent_chat`.
++ Orchestrator,
++ /// Resolve `id` the way every other id-keyed entry point does: the
++ /// process registry first, then `config.agent_registry.entries`.
++ AgentId(&'a str),
++ /// A definition the caller already holds; nothing is resolved by id. The
++ /// entry point for a library host running its own per-agent specs — see
++ /// [`OpenHumanSessionHost::from_config_with_definition`].
++ ///
++ /// `host` carries the caller's own `dyn Tool` objects. It rides the target
++ /// rather than `agent_chat_for`'s argument list because only this target
++ /// can honour it: the other two resolve a definition the caller does not
++ /// hold, so there is no agent for a host belt to belong to.
++ Definition {
++ definition: &'a crate::agent_registry::host_definition::AgentDefinition,
++ host: Option<&'a crate::agent::HostTools>,
++ /// History to seed this turn with, as `(role, content)` rows, instead
++ /// of whatever the session would otherwise resume.
++ ///
++ /// Rides the target for the same reason `host` does, and it is the
++ /// per-turn half of the same idea: a host whose history lives in its
++ /// own log -- a journal, a board, an episode -- is the only thing that
++ /// can say what this turn should have seen. Seeding is how that view
++ /// reaches the session with roles intact; passing it as prose in the
++ /// message would flatten the host's own prior turns into quoted text.
++ ///
++ /// `None` leaves resume untouched, which is every existing caller.
++ seed: Option<&'a [(String, String)]>,
++ /// Where to report what the turn spent.
++ ///
++ /// An out-parameter because this is the only target that can fill it:
++ /// the turn runs in-process here, so the session that counted the
++ /// tokens is still in hand when it ends. The other two answer over
++ /// `AGENT_CHAT`, whose reply is a string.
++ ///
++ /// Written whether the turn succeeded or failed -- a turn that ended
++ /// badly still spent what it spent, and a host that meters only
++ /// successes bills nothing for the ones that cost most.
++ usage: Option<&'a std::sync::Mutex<Option<crate::agent::tinyagents::host::LastTurnUsage>>>,
++ /// Build the session from `host` alone: no config-derived, delegation,
++ /// memory, skill or MCP tool, and a deny-by-default gate for any other
++ /// name. See [`OpenHumanSessionHost::from_config_host_only`].
++ host_only: bool,
++ /// Skip the prompt-injection guard: the message is untrusted data (a
++ /// PR diff) the agent reads, not an instruction. Refused unless
++ /// `host_only`, whose agent has nothing it could be talked into doing.
++ untrusted_input: bool,
++ /// A response format and output cap for every model call of the turn,
++ /// and the slot its final call is reported into.
++ shape: Option<&'a std::sync::Arc<tinyagents_harness::middleware::ResponseShapeScope>>,
++ /// The observer scoped around the caller, re-established around the
++ /// turn because the dispatch may run on a worker task that does not
++ /// inherit task locals.
++ observer: Option<
++ &'a std::sync::Arc<tinyagents_harness::observability::turn_observer::ObserverScope>,
++ >,
++ /// Files the host attaches to this turn as bytes, in order.
++ ///
++ /// Rides the target for the same reason `host` does: only an
++ /// in-process caller can hand over bytes, and `AGENT_CHAT` carries a
++ /// string. Each is staged into the acting workspace and reaches the
++ /// model as an image or document block ahead of the message, under
++ /// the configured multimodal count and size limits. No local path is
++ /// read, so they are accepted whatever the turn's origin.
++ ///
++ /// Empty for every caller that attaches nothing.
++ attachments: &'a [crate::agent::HostAttachment],
++ },
++}
++
++// Hand-written because a host belt is a closure, and a closure is not `Debug`.
++// Reporting whether one is present is what a log line here is ever for; the
++// belt it would return is not known until the turn builds it.
++impl std::fmt::Debug for AgentChatTarget<'_> {
++ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
++ match self {
++ Self::Orchestrator => f.write_str("Orchestrator"),
++ Self::AgentId(id) => f.debug_tuple("AgentId").field(id).finish(),
++ Self::Definition {
++ definition,
++ host,
++ seed,
++ usage,
++ host_only,
++ untrusted_input,
++ shape,
++ observer,
++ attachments,
++ } => f
++ .debug_struct("Definition")
++ .field("definition", &definition.id)
++ .field("host_tools", &host.is_some())
++ .field("seed_rows", &seed.map_or(0, <[(String, String)]>::len))
++ .field("meters", &usage.is_some())
++ .field("host_only", host_only)
++ .field("untrusted_input", untrusted_input)
++ .field("attachments", &attachments.len())
++ .field("shaped", &shape.is_some())
++ .field("observed", &observer.is_some())
++ .finish(),
++ }
++ }
++}
diff --cc crates/openhuman-core/src/inference/provider/factory_crate_native_fallback_tests.rs
index 0000000000,0000000000..e21707c954
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/factory_crate_native_fallback_tests.rs
@@@ -1,0 -1,0 +1,35 @@@
++use super::*;
++
++#[test]
++fn try_create_cloud_slug_flips_openai_but_declines_non_cloud() {
++ let _guard = crate::inference::inference_test_guard();
++ // `openai` (API-key Bearer, no codex OAuth) now flips crate-native on Chat
++ // Completions — the legacy `/v1/responses` fallback is not replicated.
++ let mut openai = Config::default();
++ openai.cloud_providers.push(openai_entry("p_oai", "openai"));
++ openai.chat_provider = Some("openai:gpt-4o-mini".to_string());
++ let (model, model_id) =
++ try_create_cloud_slug_chat_model("chat", &openai, &EgressLedger::none())
++ .expect("openai should flip crate-native")
++ .expect("build");
++ assert_eq!(model_id, "gpt-4o-mini");
++ assert_eq!(
++ model.profile().and_then(|p| p.provider.as_deref()),
++ Some("openai")
++ );
++
++ // Managed (default), local runtimes, and unconfigured slugs are not cloud
++ // slugs — they decline and fall through to their own paths.
++ assert!(
++ try_create_cloud_slug_chat_model("chat", &Config::default(), &EgressLedger::none())
++ .is_none()
++ );
++ let mut local = Config::default();
++ local.chat_provider = Some("ollama:qwen2.5".to_string());
++ assert!(try_create_cloud_slug_chat_model("chat", &local, &EgressLedger::none()).is_none());
++ let mut unconfigured = Config::default();
++ unconfigured.chat_provider = Some("deepseek:deepseek-chat".to_string());
++ assert!(
++ try_create_cloud_slug_chat_model("chat", &unconfigured, &EgressLedger::none()).is_none()
++ );
++}
diff --cc crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs
index ef9a0d87fc,29ab6af4fe..fc4ea49089
--- a/crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs
@@@ -688,36 -729,36 +729,5 @@@ fn openhuman_jwt_slug_without_model_pre
assert_eq!(model_id, crate::config::MODEL_MANAGED_DEFAULT);
}
--#[test]
--fn try_create_cloud_slug_flips_openai_but_declines_non_cloud() {
-- let _guard = crate::inference::inference_test_guard();
-- // `openai` (API-key Bearer, no codex OAuth) now flips crate-native on Chat
-- // Completions — the legacy `/v1/responses` fallback is not replicated.
-- let mut openai = Config::default();
-- openai.cloud_providers.push(openai_entry("p_oai", "openai"));
-- openai.chat_provider = Some("openai:gpt-4o-mini".to_string());
-- let (model, model_id) =
-- try_create_cloud_slug_chat_model("chat", &openai, &EgressLedger::none())
-- .expect("openai should flip crate-native")
-- .expect("build");
-- assert_eq!(model_id, "gpt-4o-mini");
-- assert_eq!(
-- model.profile().and_then(|p| p.provider.as_deref()),
-- Some("openai")
-- );
--
-- // Managed (default), local runtimes, and unconfigured slugs are not cloud
-- // slugs — they decline and fall through to their own paths.
-- assert!(
-- try_create_cloud_slug_chat_model("chat", &Config::default(), &EgressLedger::none())
-- .is_none()
-- );
-- let mut local = Config::default();
-- local.chat_provider = Some("ollama:qwen2.5".to_string());
-- assert!(try_create_cloud_slug_chat_model("chat", &local, &EgressLedger::none()).is_none());
-- let mut unconfigured = Config::default();
-- unconfigured.chat_provider = Some("deepseek:deepseek-chat".to_string());
-- assert!(
-- try_create_cloud_slug_chat_model("chat", &unconfigured, &EgressLedger::none()).is_none()
-- );
--}
++#[path = "factory_crate_native_fallback_tests.rs"]
++mod fallback_tests;
diff --cc crates/openhuman-core/src/media/generation/artifact_tool.rs
index 35032d63c4,a90c4706f8..2235e1d4d6
--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs
@@@ -237,7 -235,6 +237,7 @@@ impl<T: Tool> MediaArtifactTool<T>
total: usize,
call_id: Option<&str>,
chat: Option<&ApprovalChatContext>,
- ctx: &crate::core::runtime::DispatchCtx,
++ _ctx: &crate::core::runtime::DispatchCtx,
) -> Option<String> {
let ext = src
.extension()
diff --cc crates/openhuman-core/src/tools/ops_tests_catalog_fixture_tests.rs
index 91cdb421be,6978cf4ca3..68b6a00e33
--- a/crates/openhuman-core/src/tools/ops_tests_catalog_fixture_tests.rs
+++ b/crates/openhuman-core/src/tools/ops_tests_catalog_fixture_tests.rs
@@@ -115,16 -116,50 +116,49 @@@ fn full_tool_catalog_names() -> Vec<Str
let browser = cfg.browser.clone();
let http = cfg.http_request.clone();
- let tools = all_tools(
- Arc::new(cfg.clone()),
- &security,
- AuditLogger::disabled(),
- &browser,
- &http,
- tmp.path(),
- &cfg,
+ // Media generators belong to the host, so provide the same three tools
+ // through the generic source port the product host uses. Keep the source
+ // in this context's Extensions: a process-global test registration can
+ // leak into concurrently running catalog tests.
+ let extensions = crate::core::slots::Extensions::new();
+ #[cfg(feature = "media")]
+ crate::tools::sources::register_tool_source_in(&extensions, "catalog-test-media", |_| {
+ use std::sync::Arc;
+ use tinyagents_harness::tinyinference_image::MockImageGenerator;
+ use tinyagents_harness::tinyinference_video::{MockVideoGenerator, MockVideoScript};
+
+ crate::media::generation::media_tools_from(
+ crate::media::generation::MediaGenerators::new(
+ Arc::new(MockImageGenerator::new()),
+ Arc::new(MockVideoGenerator::new(MockVideoScript::delivers())),
+ ),
+ std::path::Path::new("."),
+ std::path::Path::new("./workspace"),
+ std::path::Path::new("./Files"),
+ tinyagents_harness::tinyinference_video::WaitPolicy::new(
+ std::time::Duration::from_millis(1),
+ std::time::Duration::from_secs(5),
+ ),
+ )
+ });
+ let context = crate::core::runtime::CoreContext::for_test_with_extensions(
+ crate::core::runtime::DomainSet::full(),
+ Some(tmp.path().to_path_buf()),
+ extensions,
);
+ let tools = crate::core::runtime::CoreContext::sync_scope(context, || {
+ all_tools(
+ Arc::new(cfg.clone()),
+ &security,
+ AuditLogger::disabled(),
+ &browser,
+ &http,
+ tmp.path(),
- &HashMap::new(),
+ &cfg,
+ )
+ });
+
let mut names: Vec<String> = tools.iter().map(|t| t.name().to_string()).collect();
names.push(tinyagents_harness::tool::discover::TOOL_SEARCH_NAME.to_string());
names.sort();
diff --cc crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher.rs
index 3454787871,1115f974c6..1f051a39c5
--- a/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher.rs
+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher.rs
@@@ -41,7 -39,9 +40,10 @@@ pub struct StorageArtifactPublisher
/// The turn the backend requests are reported to. A publisher is built
/// once per tool set, not per call, so it reports outside any chat.
approval: ApprovalTurnContext,
+ /// The folder a version's storage key is relative to. `None` reads keys
+ /// as the paths they are (records from before versions were kept).
+ version_files: Option<PathBuf>,
++ file_store: Option<Arc<dyn FileStore>>,
}
impl StorageArtifactPublisher {
@@@ -55,44 -51,59 +53,83 @@@
Self {
client,
security,
- files,
approval: ApprovalTurnContext::default(),
+ version_files: None,
++ file_store: None,
}
}
+
+ /// Resolve a version's file key against `dir`, the folder its copies are
+ /// kept in. An absolute key still names itself.
+ #[must_use]
+ pub fn with_version_files(mut self, dir: impl Into<PathBuf>) -> Self {
+ self.version_files = Some(dir.into());
+ self
+ }
++
++ /// Bind publishing to the same tenant store that owns the artifact bytes.
++ #[must_use]
++ pub fn with_file_store(mut self, file_store: Arc<dyn FileStore>) -> Self {
++ self.file_store = Some(file_store);
++ self
++ }
}
/// The publisher for `config`, or `None` when there is no integration client
/// (no backend URL configured, or not signed in) — the same condition under
/// which the `storage_*` tools are absent.
- pub fn artifact_publisher(config: &Config) -> Option<ArtifactPublisherBinder> {
-pub fn artifact_publisher(config: &Config) -> Option<Arc<dyn ArtifactPublisher>> {
++pub fn artifact_publisher(
++ config: &Config,
++) -> Option<openhuman_embed::__host::artifact_publisher::ArtifactPublisherBinder> {
let client = crate::integrations::build_client(config)?;
let security = Arc::new(SecurityPolicy::from_config(
&config.autonomy,
&config.workspace_dir,
&config.action_dir,
));
- Some(Arc::new(move |files| {
- Arc::new(StorageArtifactPublisher::new(
- client.clone(),
- security.clone(),
- files,
- ))
- Some(Arc::new(
- StorageArtifactPublisher::new(client, security).with_version_files(
- openhuman_embed::__host::artifact_publisher::version_files_dir(&config.workspace_dir),
- ),
- ))
++ Some(Arc::new(move |file_store| {
++ Arc::new(
++ StorageArtifactPublisher::new(client.clone(), Arc::clone(&security))
++ .with_file_store(file_store),
++ ) as Arc<dyn ArtifactPublisher>
+ }))
}
/// The bytes, file name and media type a version uploads as.
async fn upload_body(
- files: &dyn FileStore,
record: &ArtifactRecord,
version: &ArtifactVersion,
- ) -> anyhow::Result<(Vec<u8>, String, String)> {
+ version_files: Option<&Path>,
++ file_store: Option<&dyn FileStore>,
+ ) -> anyhow::Result<(Vec<u8>, String, &'static str)> {
if record.holds_file() {
- let file = version
++ if let (Some(file_store), Some(file)) = (file_store, version.file.as_ref()) {
++ let bytes = file_store.read(&file.key).await?;
++ let extension = Path::new(&file.key)
++ .extension()
++ .and_then(|ext| ext.to_str());
++ let filename = extension.map_or_else(
++ || record.title.clone(),
++ |extension| format!("{}.{}", record.title, extension),
++ );
++ let mime = mime_for_path(Path::new(&filename));
++ return Ok((bytes, filename, mime));
++ }
+ let path = version
.file
.as_ref()
- .ok_or_else(|| anyhow::anyhow!("file artifact version has no file reference"))?;
- let bytes = files
- .read(&file.key)
+ .map_or(version.body.as_str(), |f| f.key.as_str());
+ let joined = version_files.map(|dir| dir.join(path));
+ let path = joined.as_deref().unwrap_or_else(|| Path::new(path));
+ // The record was checked when written; check again on what the path
+ // resolves to now, so nothing protected leaves the machine.
+ let resolved = tokio::fs::canonicalize(path)
+ .await
+ .map_err(|e| anyhow::anyhow!("cannot read the artifact's file: {e}"))?;
+ if let Some(reason) = openhuman_embed::__host::artifact_publisher::refused_path(&resolved) {
+ anyhow::bail!("[policy-blocked] cannot share this artifact: {reason}");
+ }
+ let bytes = tokio::fs::read(&resolved)
.await
.map_err(|e| anyhow::anyhow!("cannot read the artifact's file: {e}"))?;
// Named after the artifact: the file read may be a kept version copy
@@@ -229,7 -235,8 +261,13 @@@ impl ArtifactPublisher for StorageArtif
if !self.security.can_act() {
anyhow::bail!("[policy-blocked] Action blocked: autonomy is read-only");
}
- let (bytes, filename, mime) = upload_body(self.files.as_ref(), record, version).await?;
- let (bytes, filename, mime) =
- upload_body(record, version, self.version_files.as_deref()).await?;
++ let (bytes, filename, mime) = upload_body(
++ record,
++ version,
++ self.version_files.as_deref(),
++ self.file_store.as_deref(),
++ )
++ .await?;
tracing::debug!(
artifact_id = %record.id,
version = version.version,
diff --cc scripts/ci/check-openhuman-rust-layout.mjs
index ee9c0b75ad,ef24590fe9..c21c46fd00
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@@ -31,18 -29,19 +29,18 @@@ const LEGACY_LIMIT_ENTRIES =
// provider, security, memory, tool and prompt policy. Generic session
// state moved to tinyagents-runtime; this remaining composition is split in
// a follow-up without reintroducing an old harness/session exception.
- ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 921],
- ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 754],
- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 927],
- ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1089],
+ ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 866],
- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 880],
- ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1060],
++ ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 885],
++ ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1074],
// These established external test modules grew with upstream coverage. Pin
// their current sizes while follow-up work separates their test concerns.
// `core/` was pruned from the line limit by name until these pins; its
// oversized files are pinned at the size they had when enforcement began.
- ["crates/openhuman-core/src/core/all.rs", 1215],
+ ["crates/openhuman-core/src/core/all.rs", 1114],
["crates/openhuman-core/src/core/all_tests.rs", 1465],
- ["crates/openhuman-core/src/core/events.rs", 1741],
- ["crates/openhuman-core/src/core/events_tests.rs", 997],
- ["crates/openhuman-core/src/core/observability.rs", 3429],
+ ["crates/openhuman-core/src/core/events.rs", 1697],
+ ["crates/openhuman-core/src/core/events_tests.rs", 988],
- ["crates/openhuman-core/src/core/observability.rs", 3429],
++ ["crates/openhuman-core/src/core/observability.rs", 3428],
];
const LEGACY_LIMITS = new Map(LEGACY_LIMIT_ENTRIES);
diff --cc vendor/tinyagents
index 73f348e76a,aa64b26a06..598137aefa
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@@ -1,1 -1,1 +1,1 @@@
- Subproject commit 73f348e76aaf42a8a2191005a6d0e6c0e0b0f1b7
-Subproject commit aa64b26a06377e17e1126f355c620318c347798a
++Subproject commit 598137aefa32ec4a7189171a22a74210d8722bd0