Skip to content

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

feat(plan_review): move plan-review gate into tinyagents harness

Steven Enamakelf4a33c87525f
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 9f10a6bcb2..31e71472bc 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -102,7 +102,7 @@ tinyflows-import = { path = "../../vendor/tinyflows/crates/tinyflows-import", de
# below as its own path dependency for the same "one checkout, one type
# identity" reason `tinytools` is.
tinyagents-hooks = { workspace = true, features = ["goals"] }
-tinyagents-harness-tools = { workspace = true, features = ["goals", "todos", "skills", "subagents"] }
+tinyagents-harness-tools = { workspace = true, features = ["goals", "todos", "skills", "subagents", "plan-review"] }
tinyagents-harness = { path = "../../vendor/tinyagents/crates/tinyagents-harness", features = [
"sqlite",
"multimodal",
diff --git a/crates/openhuman-core/src/agent/registration.rs b/crates/openhuman-core/src/agent/registration.rs
index ea9aede210..1964923e51 100644
--- a/crates/openhuman-core/src/agent/registration.rs
+++ b/crates/openhuman-core/src/agent/registration.rs
@@ -1,7 +1,7 @@
//! Registration of agent dialogue and delegation tools.
use super::orchestration::tools::SpawnSubagentTool;
-use super::tools::{PlanExitTool, TodoTool};
+use super::tools::TodoTool;
use crate::config::Config;
#[cfg(feature = "skills")]
use crate::skills::run_workflow::{AwaitWorkflowTool, RunWorkflowTool};
@@ -35,8 +35,8 @@ pub(crate) fn dialogue_tools(action_dir: &Path, root_config: &Config) -> Vec<Box
Box::new(TodoTool::new(root_config.workspace_dir.clone())),
// Interactive plan-review gate: parks the live turn on a thread-scoped
// plan the user must approve before execution (Codex/Claude plan mode).
- Box::new(crate::plan_review::RequestPlanReviewTool::new()),
- Box::new(PlanExitTool::new()),
+ Box::new(crate::plan_review::host::request_plan_review_tool()),
+ Box::new(super::tools::plan_exit::plan_exit_tool()),
// Workflow composition: `run_workflow` runs another workflow as a
// subagent and (by default) waits on its result like a function call;
// `await_workflow` re-attaches to a run that outlived its inline wait.
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
index c2b0dc2821..87fa33a1ed 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
@@ -17,14 +17,14 @@ use async_trait::async_trait;
use tinyagents_harness::cache::InMemoryResponseCache;
use tinyagents_harness::host::security_gate::{GateDecision, SecurityGate, ToolCallRequest};
use tinyagents_harness::middleware::{
- install_unmet_deliverable, is_repeat_call_exempt, tool_sets_lookup, ResearchBudgetMiddleware,
- ShellTurnBudget, TurnClockMiddleware, DIRECT_WEB_READ_LIMIT,
+ ApprovalGateMiddleware, ArgRecoveryMiddleware, BudgetLimits, BudgetMiddleware,
+ ContextCompressionMiddleware, MiddlewareToolOutcome, PromptCacheGuardMiddleware,
+ RepeatProgressMiddleware, RunModeHandle, ToolHandler, ToolMiddleware,
+ ToolPolicyMiddleware as TaToolPolicyMiddleware, plan_mode_middleware,
};
use tinyagents_harness::middleware::{
- plan_mode_middleware, ApprovalGateMiddleware, ArgRecoveryMiddleware, BudgetLimits,
- BudgetMiddleware, ContextCompressionMiddleware, MiddlewareToolOutcome,
- PromptCacheGuardMiddleware, RepeatProgressMiddleware, RunModeHandle, ToolHandler,
- ToolMiddleware, ToolPolicyMiddleware as TaToolPolicyMiddleware,
+ DIRECT_WEB_READ_LIMIT, ResearchBudgetMiddleware, ShellTurnBudget, TurnClockMiddleware,
+ install_unmet_deliverable, is_repeat_call_exempt, tool_sets_lookup,
};
use tinyagents_harness::runtime::AgentHarness;
use tinyagents_harness::steering::SteeringHandle;
@@ -425,14 +425,11 @@ pub(super) fn install_turn_middleware(
// session `todo` list, and the per-thread `goal_*` tools.
if let Some(mode) = run_mode {
harness.push_middleware(Arc::new(
- plan_mode_middleware(mode, harness.tools().policies()).allow([
- "plan_exit",
- "request_plan_review",
- "todo",
- "goal_set",
- "goal_get",
- "goal_complete",
- ]),
+ plan_mode_middleware(mode, harness.tools().policies()).allow(
+ tinyagents_harness::middleware::library::plan_mode_allowlist()
+ .iter()
+ .copied(),
+ ),
));
}
diff --git a/crates/openhuman-core/src/agent/tools.rs b/crates/openhuman-core/src/agent/tools.rs
index 90ed428a87..b251ffe507 100644
--- a/crates/openhuman-core/src/agent/tools.rs
+++ b/crates/openhuman-core/src/agent/tools.rs
@@ -7,8 +7,8 @@
//! - `AskClarificationTool` (`ask_user_clarification`, from `tinyagents_harness_tools`) — returns the
//! question as its output; the turn actually pauses only because callers
//! list this name in the harness seam's `early_exit_tools`.
-//! - [`PlanExitTool`] — ends a plan-mode pass by returning the plan plus
-//! [`PLAN_EXIT_MARKER`], which TinyAgents consumes to switch to build mode.
+//! - `plan_exit_tool` — configures TinyAgents' plan-exit tool with OpenHuman's
+//! tenant-scoped mode and parked-review stores.
//! - `RunWorkflowTool` / `AwaitWorkflowTool` — spawn a
//! `crate::skills::runtime` workflow run and wait on its outcome. Compiled
//! in only with the `skills` feature, so builds without it omit both tools
@@ -21,7 +21,6 @@ pub(crate) mod plan_exit;
mod todo;
mod wait;
-pub use plan_exit::PlanExitTool;
pub const PLAN_EXIT_MARKER: &str = tinyagents_harness_tools::PLAN_EXIT_MARKER;
pub use todo::TodoTool;
pub(crate) use todo::TodoToolDispatch;
diff --git a/crates/openhuman-core/src/agent/tools/README.md b/crates/openhuman-core/src/agent/tools/README.md
index 2073e0ca4d..41d2ac4ae1 100644
--- a/crates/openhuman-core/src/agent/tools/README.md
+++ b/crates/openhuman-core/src/agent/tools/README.md
@@ -11,7 +11,7 @@ crate should construct them directly.
| Tool | File | Wire name (if different) |
| --- | --- | --- |
| `AskClarificationTool` | `tinyagents_harness_tools` | `ask_user_clarification` |
-| `PlanExitTool` | [`plan_exit.rs`](./plan_exit.rs) | `plan_exit` |
+| `plan_exit_tool` | [`plan_exit.rs`](./plan_exit.rs) | `plan_exit` |
| `RememberPreferenceTool` | `remember_preference.rs` | `remember_preference` |
| `SavePreferenceTool` | `save_preference.rs` | `save_preference` |
| `RunWorkflowTool`, `AwaitWorkflowTool` | [`run_workflow.rs`](./run_workflow.rs) | `run_workflow`, `await_workflow` |
@@ -31,9 +31,9 @@ instead of registering them as disabled.
Any caller that exposes this tool without that listing gets a tool that
answers its own question, since the model reads a normal success and keeps
going.
-- `PlanExitTool` ends a plan-mode pass by returning the plan text plus
- `PLAN_EXIT_MARKER`. The mode switch itself lives outside this tool; nothing
- in this crate currently consumes the marker.
+- `plan_exit_tool` configures TinyAgents' plan-exit tool with OpenHuman's
+ thread mode and pending-review stores. TinyAgents owns the tool behavior and
+ `PLAN_EXIT_MARKER`.
- `RememberPreferenceTool` pins an explicit `(class, key, value)` preference
into the `user_profile` memory namespace. `SavePreferenceTool` stores a
free-form preference into either the `general` or `situational` lane.
diff --git a/crates/openhuman-core/src/agent/tools/plan_exit.rs b/crates/openhuman-core/src/agent/tools/plan_exit.rs
index 81df1197bc..37ff79b32e 100644
--- a/crates/openhuman-core/src/agent/tools/plan_exit.rs
+++ b/crates/openhuman-core/src/agent/tools/plan_exit.rs
@@ -3,12 +3,9 @@
use std::hash::{Hash, Hasher};
use std::sync::Arc;
-use async_trait::async_trait;
-use serde_json::Value;
-use tinyagents_harness::middleware::RunModeHandle;
use tinyagents_harness_tools::run_mode::RunModeStore;
use tinyagents_harness_tools::{ParkedPlanReviewLookup, PlanExitHost};
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};
+use tinytools::Tool;
#[derive(Clone)]
struct PlanExitScope {
@@ -85,14 +82,11 @@ struct OpenHumanParkedReviews;
impl ParkedPlanReviewLookup<PlanExitScope> for OpenHumanParkedReviews {
fn has_parked_review(&self, scope: &PlanExitScope, thread_id: &str) -> bool {
- scope.valid
- && crate::plan_review::gate::global()
- .parked_review_for_thread(&scope.tenant, thread_id)
- .is_some()
+ scope.valid && crate::plan_review::host::has_parked_review(&scope.tenant, thread_id)
}
}
-fn owner_tool() -> tinyagents_harness_tools::PlanExitTool<PlanExitScope> {
+pub(crate) fn plan_exit_tool() -> impl Tool {
tinyagents_harness_tools::PlanExitTool::new(
Arc::new(OpenHumanPlanExitHost),
Arc::new(OpenHumanRunModes),
@@ -100,55 +94,6 @@ fn owner_tool() -> tinyagents_harness_tools::PlanExitTool<PlanExitScope> {
)
}
-/// Public unit-shaped compatibility adapter around TinyAgents' tool engine.
-pub struct PlanExitTool;
-
-impl PlanExitTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for PlanExitTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for PlanExitTool {
- fn name(&self) -> &str {
- tinyagents_harness_tools::PlanExitTool::<PlanExitScope>::NAME
- }
-
- fn description(&self) -> &str {
- tinyagents_harness_tools::PlanExitTool::<PlanExitScope>::DESCRIPTION
- }
-
- fn parameters_schema(&self) -> Value {
- owner_tool().parameters_schema()
- }
-
- fn permission_level(&self) -> PermissionLevel {
- owner_tool().permission_level()
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- owner_tool().execute(args).await
- }
-
- async fn execute_with_context(
- &self,
- args: Value,
- options: ToolCallOptions,
- context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- owner_tool()
- .execute_with_context(args, options, context)
- .await
- }
-}
-
#[cfg(test)]
#[path = "plan_exit_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/agent/tools/plan_exit_tests.rs b/crates/openhuman-core/src/agent/tools/plan_exit_tests.rs
index 5189240780..7a8abb4e20 100644
--- a/crates/openhuman-core/src/agent/tools/plan_exit_tests.rs
+++ b/crates/openhuman-core/src/agent/tools/plan_exit_tests.rs
@@ -1,6 +1,6 @@
-use crate::agent::tools::{PlanExitTool, PLAN_EXIT_MARKER};
-use crate::plan_review::PlanReviewResolution;
+use crate::agent::tools::{PLAN_EXIT_MARKER, plan_exit::plan_exit_tool};
use serde_json::json;
+use tinyagents_harness_tools::plan_review::{PlanReviewRequest, PlanReviewResolution};
use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolRunContext};
struct RunModeEventCollector(tokio::sync::mpsc::UnboundedSender<(String, String)>);
@@ -38,25 +38,29 @@ async fn plan_exit_does_not_flip_while_a_review_is_parked() {
thread_id,
tinyagents_harness::middleware::RunMode::Plan,
);
- let gate = crate::plan_review::gate::global();
+ let store = crate::plan_review::host::global();
let tenant = crate::core::runtime::DispatchCtx::ambient()
.tenant()
- .unwrap();
+ .unwrap()
+ .profile_only();
let parked = tokio::spawn(async move {
- gate.request_review(
- tenant,
- Some(thread_id.to_string()),
- None,
- "Plan".into(),
- vec!["step".into()],
- None,
- )
- .await
+ store
+ .request_review(
+ tenant,
+ thread_id.to_string(),
+ None,
+ PlanReviewRequest {
+ summary: "Plan".into(),
+ steps: vec!["step".into()],
+ tool_call_id: None,
+ },
+ )
+ .await
});
// Let the review register as parked before racing plan_exit against it.
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
- let tool = PlanExitTool::new();
+ let tool = plan_exit_tool();
let ctx = ThreadContext(thread_id);
let result = tool
.execute_with_context(
@@ -78,13 +82,16 @@ async fn plan_exit_does_not_flip_while_a_review_is_parked() {
// Resolve the parked review so the spawned task and the gate's
// bookkeeping don't leak past this test.
- assert!(crate::plan_review::gate::global().decide_by_thread(
- &crate::core::runtime::DispatchCtx::ambient()
- .tenant()
- .unwrap(),
- thread_id,
- PlanReviewResolution::Approve,
- ));
+ assert!(
+ crate::plan_review::host::global().decide_by_thread(
+ &crate::core::runtime::DispatchCtx::ambient()
+ .tenant()
+ .unwrap()
+ .profile_only(),
+ thread_id,
+ PlanReviewResolution::Approve,
+ )
+ );
let resolution = parked.await.unwrap();
assert_eq!(resolution, PlanReviewResolution::Approve);
@@ -109,7 +116,7 @@ async fn plan_exit_does_not_flip_while_a_review_is_parked() {
#[tokio::test]
async fn plan_exit_emits_marker() {
- let tool = PlanExitTool::new();
+ let tool = plan_exit_tool();
let result = tool
.execute(json!({ "plan": "1. Read X\n2. Edit Y" }))
.await
@@ -133,7 +140,7 @@ async fn plan_exit_publishes_build_run_mode_change() {
thread_id,
tinyagents_harness::middleware::RunMode::Plan,
);
- let tool = PlanExitTool::new();
+ let tool = plan_exit_tool();
let result = tool
.execute_with_context(
json!({ "plan": "1. Do the thing" }),
@@ -164,14 +171,14 @@ async fn plan_exit_publishes_build_run_mode_change() {
#[tokio::test]
async fn plan_exit_rejects_empty() {
- let tool = PlanExitTool::new();
+ let tool = plan_exit_tool();
let result = tool.execute(json!({ "plan": " " })).await.unwrap();
assert!(result.is_error);
}
#[test]
fn plan_exit_metadata() {
- let tool = PlanExitTool;
+ let tool = plan_exit_tool();
assert_eq!(tool.name(), "plan_exit");
assert_eq!(tool.permission_level(), PermissionLevel::None);
}
diff --git a/crates/openhuman-core/src/core/events.rs b/crates/openhuman-core/src/core/events.rs
index 398080e0b4..da74155e96 100644
--- a/crates/openhuman-core/src/core/events.rs
+++ b/crates/openhuman-core/src/core/events.rs
@@ -648,9 +648,9 @@ pub enum DomainEvent {
// ── Plan review (interactive plan-mode gate) ────────────────────────
/// An interactive turn parked on a thread-scoped plan the user must
- /// review before execution. Published by
- /// [`crate::plan_review::gate::PlanReviewGate::request_review`]
- /// and bridged to the web channel as a `plan_review_request` socket event.
+ /// review before execution. Published by the OpenHuman notifier for
+ /// TinyAgents' plan-review store and bridged to the web channel as a
+ /// `plan_review_request` socket event.
PlanReviewRequested {
/// Unique id correlating the decision back to the parked turn.
request_id: String,
diff --git a/crates/openhuman-core/src/plan_review/gate.rs b/crates/openhuman-core/src/plan_review/gate.rs
deleted file mode 100644
index c422290231..0000000000
--- a/crates/openhuman-core/src/plan_review/gate.rs
+++ /dev/null
@@ -1,342 +0,0 @@
-//! `PlanReviewGate` — parks a live interactive turn on a plan the user must
-//! review before execution.
-//!
-//! Flow (mirrors [`crate::security::approval::ApprovalGate`], in-memory):
-//! 1. The orchestrator calls the `request_plan_review` tool after laying out a
-//! thread-scoped plan. The tool calls [`PlanReviewGate::request_review`].
-//! 2. The gate registers a `oneshot::Sender` keyed by `request_id`, publishes
-//! [`DomainEvent::PlanReviewRequested`] (bridged to the `plan_review_request`
-//! socket event), and parks the turn on the receiver.
-//! 3. The UI's `PlanReviewCard` calls `plan_review_decide` (RPC) →
-//! [`PlanReviewGate::decide`] → sends the resolution on the oneshot.
-//! 4. The parked turn wakes with [`PlanReviewResolution`] and the tool returns
-//! a result that tells the agent to proceed / stop / revise.
-//!
-//! On TTL or a dropped sender the gate resolves to `Reject` — fail-closed, so a
-//! plan never executes without an explicit approval.
-
-use std::collections::HashMap;
-use std::sync::OnceLock;
-use std::time::Duration;
-
-use parking_lot::Mutex;
-use tokio::sync::oneshot;
-use uuid::Uuid;
-
-use crate::core::bus::BUS;
-use crate::core::events::DomainEvent;
-use crate::core::runtime::Tenant;
-
-use super::types::PlanReviewResolution;
-
-/// How long the gate parks a turn before timing out → `Reject`. Matches the
-/// default approval TTL (10 min) — long enough for a human to read the plan.
-const DEFAULT_PLAN_REVIEW_TTL: Duration = Duration::from_secs(60 * 10);
-
-/// Snapshot of a parked plan review, captured at park time. Used to replay
-/// the `plan_review_request` event to a socket that (re)joins the thread
-/// room after the live emit — mirrors
-/// [`crate::security::approval::PendingApproval`], but in-memory only (a
-/// plan review parks a live turn; it has nothing to recover across a
-/// restart).
-#[derive(Debug, Clone)]
-pub struct ParkedReview {
- pub request_id: String,
- pub thread_id: Option<String>,
- pub client_id: Option<String>,
- pub summary: String,
- pub steps: Vec<String>,
- /// The gated tool call's provider-assigned call id, when known.
- pub tool_call_id: Option<String>,
- /// RFC3339 expiry of this parked review.
- pub expires_at: Option<String>,
-}
-
-/// In-memory registry of parked plan reviews. Process-global singleton (see
-/// [`global`]); no persistence — a parked interactive turn cannot resume
-/// across a restart, so an orphaned review has nothing to recover.
-pub struct PlanReviewGate {
- ttl: Duration,
- waiters: Mutex<HashMap<(Tenant, String), oneshot::Sender<PlanReviewResolution>>>,
- /// Newest parked `request_id` per thread, so a typed reply or a UI action
- /// that only knows the thread can resolve the latest review.
- thread_to_request: Mutex<HashMap<(Tenant, String), String>>,
- /// request_id → [`ParkedReview`] for every currently-parked review —
- /// consulted by `parked_review_for_thread` so a socket that (re)joins a
- /// thread room can be handed whatever is parked on it, the same
- /// reconciliation `ApprovalGate::parked_request_for_thread` performs.
- parked: Mutex<HashMap<(Tenant, String), ParkedReview>>,
-}
-
-/// A tenant captured from trusted server context for a live socket. Its
-/// private field prevents transport payloads from manufacturing replay scope.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct SocketReviewScope(Tenant);
-
-impl PlanReviewGate {
- fn new(ttl: Duration) -> Self {
- Self {
- ttl,
- waiters: Mutex::new(HashMap::new()),
- thread_to_request: Mutex::new(HashMap::new()),
- parked: Mutex::new(HashMap::new()),
- }
- }
-
- /// Park the current turn on a plan review and block until the user decides
- /// or the TTL elapses. `summary` is a one-line description; `steps` are the
- /// ordered plan items shown in the review card. `thread_id` / `client_id`
- /// route the surface to the originating chat (absent → no routable surface,
- /// so the park TTL-rejects). `tool_call_id` is the gated `request_plan_review`
- /// call's provider-assigned id, when known, so the UI can correlate the
- /// review card back to the exact timeline row.
- pub async fn request_review(
- &self,
- tenant: Tenant,
- thread_id: Option<String>,
- client_id: Option<String>,
- summary: String,
- steps: Vec<String>,
- tool_call_id: Option<String>,
- ) -> PlanReviewResolution {
- let request_id = format!("plan-{}", Uuid::new_v4());
- let (tx, rx) = oneshot::channel();
- // Requests run under a derived agent context, while the profile's UI
- // decides and replays them from its profile-level context. Share the
- // profile's gate entries across its agents, but isolate other profiles.
- let scope = tenant.profile_only();
- let request_key = (scope.clone(), request_id.clone());
- self.waiters.lock().insert(request_key.clone(), tx);
- if let Some(tid) = thread_id.clone() {
- self.thread_to_request
- .lock()
- .insert((scope.clone(), tid), request_id.clone());
- }
- let expires_at = (chrono::Utc::now()
- + chrono::Duration::from_std(self.ttl).unwrap_or_default())
- .to_rfc3339();
- self.parked.lock().insert(
- request_key,
- ParkedReview {
- request_id: request_id.clone(),
- thread_id: thread_id.clone(),
- client_id: client_id.clone(),
- summary: summary.clone(),
- steps: steps.clone(),
- tool_call_id: tool_call_id.clone(),
- expires_at: Some(expires_at.clone()),
- },
- );
-
- // RAII cleanup: remove the waiter + thread + parked mappings on ANY
- // exit path, including when the parked future is cancelled/dropped
- // before `rx.await` completes (turn cancel, supervisor shutdown).
- // Without this, a cancelled review would leak entries that could be
- // re-decided against a dead turn or replayed as still-pending.
- let mut guard = ParkGuard {
- gate: self,
- tenant: scope,
- request_id: request_id.clone(),
- thread_id: thread_id.clone(),
- client_id: client_id.clone(),
- tool_call_id: tool_call_id.clone(),
- completed: false,
- };
-
- tracing::info!(
- request_id = %request_id,
- thread_id = ?thread_id,
- steps = steps.len(),
- "[plan_review::gate] parking turn for plan review"
- );
-
- BUS.publish(DomainEvent::PlanReviewRequested {
- request_id: request_id.clone(),
- thread_id: thread_id.clone(),
- client_id: client_id.clone(),
- summary,
- steps,
- tool_call_id: tool_call_id.clone(),
- expires_at: Some(expires_at),
- });
-
- let (resolution, terminal_reason) = match tokio::time::timeout(self.ttl, rx).await {
- Ok(Ok(resolution)) => (resolution, None),
- Ok(Err(_)) => {
- tracing::warn!(
- request_id = %request_id,
- "[plan_review::gate] review sender dropped → reject"
- );
- (PlanReviewResolution::Reject, Some("cancelled"))
- }
- Err(_) => {
- tracing::warn!(
- request_id = %request_id,
- "[plan_review::gate] review timed out → reject"
- );
- (PlanReviewResolution::Reject, Some("expired"))
- }
- };
-
- guard.publish_decided(&resolution, terminal_reason);
- tracing::info!(
- request_id = %request_id,
- decision = resolution.as_str(),
- "[plan_review::gate] review resolved"
- );
- resolution
- }
-
- /// The parked review on `thread_id`, if any — lets a socket (re)joining a
- /// thread room be handed whatever review is still parked on it.
- pub fn parked_review_for_thread(
- &self,
- tenant: &Tenant,
- thread_id: &str,
- ) -> Option<ParkedReview> {
- let scope = tenant.profile_only();
- let key = (scope.clone(), thread_id.to_string());
- let request_id = self.thread_to_request.lock().get(&key)?.clone();
- self.parked.lock().get(&(scope, request_id)).cloned()
- }
-
- /// The parked review a socket connected under its server-bound tenant
- /// should replay. The caller must capture this tenant from trusted server
- /// context when the socket connects; client event payloads are not identity.
- pub fn parked_review_for_socket(
- &self,
- socket_tenant: &SocketReviewScope,
- thread_id: &str,
- ) -> Option<ParkedReview> {
- self.parked_review_for_thread(&socket_tenant.0, thread_id)
- }
-
- /// Capture this socket's replay scope from the request's server-bound
- /// dispatch context. Socket transports may run connection handlers in a
- /// new task, so the request context must be passed explicitly rather than
- /// read from ambient task-local state. SaaS requests without a scoped
- /// tenant fail closed; local hosts retain their active profile/default.
- pub fn socket_scope_for_dispatch(
- &self,
- dispatch: &crate::core::runtime::DispatchCtx,
- ) -> Option<SocketReviewScope> {
- socket_scope_from_context(dispatch.tenant(), crate::core::runtime::is_saas())
- }
-
- /// Resolve a parked review by `request_id`. Returns `true` when a waiter was
- /// woken; `false` when the id is unknown (already decided / expired).
- pub fn decide(
- &self,
- tenant: &Tenant,
- request_id: &str,
- resolution: PlanReviewResolution,
- ) -> bool {
- let sender = self
- .waiters
- .lock()
- .remove(&(tenant.profile_only(), request_id.to_string()));
- match sender {
- Some(tx) => tx.send(resolution).is_ok(),
- None => {
- tracing::debug!(
- request_id = %request_id,
- "[plan_review::gate] decide for unknown/expired request"
- );
- false
- }
- }
- }
-
- /// Resolve the newest parked review on `thread_id` (typed-reply / thread-
- /// scoped path). Returns `true` when a waiter was woken.
- pub fn decide_by_thread(
- &self,
- tenant: &Tenant,
- thread_id: &str,
- resolution: PlanReviewResolution,
- ) -> bool {
- let scope = tenant.profile_only();
- let request_id = self
- .thread_to_request
- .lock()
- .get(&(scope, thread_id.to_string()))
- .cloned();
- match request_id {
- Some(id) => self.decide(tenant, &id, resolution),
- None => false,
- }
- }
-}
-
-fn socket_scope_from_context(
- tenant: Result<Tenant, crate::core::runtime::tenant::NoTenant>,
- saas: bool,
-) -> Option<SocketReviewScope> {
- match tenant {
- Ok(tenant) => Some(SocketReviewScope(tenant)),
- Err(_) if saas => None,
- Err(_) => Some(SocketReviewScope(Tenant::default())),
- }
-}
-
-/// Removes a parked review's registry entries on drop — covers both the normal
-/// return and cancellation of the parked future.
-struct ParkGuard<'a> {
- gate: &'a PlanReviewGate,
- tenant: Tenant,
- request_id: String,
- thread_id: Option<String>,
- client_id: Option<String>,
- tool_call_id: Option<String>,
- completed: bool,
-}
-
-impl ParkGuard<'_> {
- fn publish_decided(&mut self, decision: &PlanReviewResolution, resolution: Option<&str>) {
- if self.completed {
- return;
- }
- BUS.publish(DomainEvent::PlanReviewDecided {
- request_id: self.request_id.clone(),
- decision: decision.as_str().to_string(),
- thread_id: self.thread_id.clone(),
- client_id: self.client_id.clone(),
- tool_call_id: self.tool_call_id.clone(),
- resolution: resolution.map(str::to_string),
- });
- self.completed = true;
- }
-}
-
-impl Drop for ParkGuard<'_> {
- fn drop(&mut self) {
- // Dropping the parked future is a terminal cancellation too. Publish
- // before removing routing metadata so the frontend can clear its card.
- self.publish_decided(&PlanReviewResolution::Reject, Some("cancelled"));
- self.gate
- .waiters
- .lock()
- .remove(&(self.tenant.clone(), self.request_id.clone()));
- self.gate
- .parked
- .lock()
- .remove(&(self.tenant.clone(), self.request_id.clone()));
- if let Some(tid) = &self.thread_id {
- let mut map = self.gate.thread_to_request.lock();
- let key = (self.tenant.clone(), tid.clone());
- if map.get(&key) == Some(&self.request_id) {
- map.remove(&key);
- }
- }
- }
-}
-
-/// Process-global plan-review gate.
-pub fn global() -> &'static PlanReviewGate {
- static GATE: OnceLock<PlanReviewGate> = OnceLock::new();
- GATE.get_or_init(|| PlanReviewGate::new(DEFAULT_PLAN_REVIEW_TTL))
-}
-
-#[cfg(test)]
-#[path = "gate_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/plan_review/gate_tests.rs b/crates/openhuman-core/src/plan_review/gate_tests.rs
deleted file mode 100644
index aafa4156e5..0000000000
--- a/crates/openhuman-core/src/plan_review/gate_tests.rs
+++ /dev/null
@@ -1,317 +0,0 @@
-use super::*;
-
-struct DecisionCollector {
- thread_id: &'static str,
- sender: tokio::sync::mpsc::UnboundedSender<(String, Option<String>)>,
-}
-
-#[async_trait::async_trait]
-impl tinybus::EventHandler<crate::core::events::DomainEvent> for DecisionCollector {
- fn name(&self) -> &str {
- "plan-review-gate-test"
- }
-
- async fn handle(&self, event: &crate::core::events::DomainEvent) {
- if let crate::core::events::DomainEvent::PlanReviewDecided {
- decision,
- resolution,
- thread_id: Some(thread_id),
- ..
- } = event
- {
- if thread_id == self.thread_id {
- let _ = self.sender.send((decision.clone(), resolution.clone()));
- }
- }
- }
-}
-
-async fn decision_events(
- thread_id: &'static str,
-) -> (
- impl Drop,
- tokio::sync::mpsc::UnboundedReceiver<(String, Option<String>)>,
-) {
- crate::core::bus::init().await.expect("bus init");
- let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
- let handle = crate::core::bus::BUS
- .subscribe(std::sync::Arc::new(DecisionCollector {
- thread_id,
- sender: tx,
- }))
- .expect("subscribe to core events");
- (handle, rx)
-}
-
-fn tenant() -> crate::core::runtime::Tenant {
- crate::core::runtime::Tenant::default()
-}
-
-#[tokio::test]
-async fn approve_resolves_parked_turn() {
- let gate = PlanReviewGate::new(Duration::from_secs(5));
- let gate = std::sync::Arc::new(gate);
- let g2 = gate.clone();
- let parked = tokio::spawn(async move {
- g2.request_review(
- tenant(),
- Some("t1".into()),
- Some("c1".into()),
- "Ship it".into(),
- vec!["step one".into()],
- Some("call-1".into()),
- )
- .await
- });
- // Let the park register the waiter.
- tokio::time::sleep(Duration::from_millis(20)).await;
- assert!(gate.decide_by_thread(&tenant(), "t1", PlanReviewResolution::Approve));
- assert_eq!(parked.await.unwrap(), PlanReviewResolution::Approve);
-}
-
-#[tokio::test]
-async fn revise_carries_feedback_back() {
- let gate = std::sync::Arc::new(PlanReviewGate::new(Duration::from_secs(5)));
- let g2 = gate.clone();
- let parked = tokio::spawn(async move {
- g2.request_review(
- tenant(),
- Some("t2".into()),
- None,
- "Plan".into(),
- vec![],
- None,
- )
- .await
- });
- tokio::time::sleep(Duration::from_millis(20)).await;
- assert!(gate.decide_by_thread(
- &tenant(),
- "t2",
- PlanReviewResolution::Revise {
- feedback: "add a test step".into(),
- },
- ));
- assert_eq!(
- parked.await.unwrap(),
- PlanReviewResolution::Revise {
- feedback: "add a test step".into(),
- }
- );
-}
-
-#[tokio::test]
-async fn timeout_fails_closed_to_reject() {
- let (_subscription, mut decisions) = decision_events("t3").await;
- let gate = PlanReviewGate::new(Duration::from_millis(40));
- let resolution = gate
- .request_review(
- tenant(),
- Some("t3".into()),
- None,
- "Plan".into(),
- vec![],
- None,
- )
- .await;
- assert_eq!(resolution, PlanReviewResolution::Reject);
- assert_eq!(
- decisions.recv().await,
- Some(("reject".into(), Some("expired".into())))
- );
- // The waiter is cleaned up after timeout.
- assert!(!gate.decide_by_thread(&tenant(), "t3", PlanReviewResolution::Approve));
-}
-
-#[tokio::test]
-async fn cancelled_park_publishes_cancelled_decision() {
- let (_subscription, mut decisions) = decision_events("t-cancel-event").await;
- let gate = std::sync::Arc::new(PlanReviewGate::new(Duration::from_secs(30)));
- let g2 = gate.clone();
- let handle = tokio::spawn(async move {
- g2.request_review(
- tenant(),
- Some("t-cancel-event".into()),
- Some("client-cancel".into()),
- "Plan".into(),
- vec![],
- None,
- )
- .await
- });
- tokio::time::sleep(Duration::from_millis(20)).await;
- handle.abort();
- let _ = handle.await;
-
- assert_eq!(
- tokio::time::timeout(Duration::from_secs(1), decisions.recv())
- .await
- .unwrap(),
- Some(("reject".into(), Some("cancelled".into()))),
- "cancelling a parked review must tell the frontend to clear its card"
- );
-}
-
-#[tokio::test]
-async fn decide_unknown_request_is_false() {
- let gate = PlanReviewGate::new(Duration::from_secs(5));
- assert!(!gate.decide(&tenant(), "nope", PlanReviewResolution::Approve));
-}
-
-#[tokio::test]
-async fn cancelled_park_cleans_up_waiter() {
- // A parked review whose future is dropped (turn cancel) before it
- // resolves must not leak its waiter / thread mapping.
- let gate = std::sync::Arc::new(PlanReviewGate::new(Duration::from_secs(30)));
- let g2 = gate.clone();
- let handle = tokio::spawn(async move {
- g2.request_review(
- tenant(),
- Some("t-drop".into()),
- None,
- "Plan".into(),
- vec![],
- None,
- )
- .await
- });
- tokio::time::sleep(Duration::from_millis(20)).await;
- handle.abort();
- let _ = handle.await;
- // The drop guard removed the entry, so there is nothing left to decide.
- assert!(!gate.decide_by_thread(&tenant(), "t-drop", PlanReviewResolution::Approve));
-}
-
-#[tokio::test]
-async fn parked_review_for_thread_carries_tool_call_id_and_expiry() {
- let gate = std::sync::Arc::new(PlanReviewGate::new(Duration::from_secs(5)));
- let g2 = gate.clone();
- let parked = tokio::spawn(async move {
- g2.request_review(
- tenant(),
- Some("t-replay".into()),
- Some("c-replay".into()),
- "Ship it".into(),
- vec!["step one".into()],
- Some("call-replay".into()),
- )
- .await
- });
- tokio::time::sleep(Duration::from_millis(20)).await;
-
- let row = gate
- .parked_review_for_thread(&tenant(), "t-replay")
- .expect("review should be parked");
- assert_eq!(row.thread_id, Some("t-replay".to_string()));
- assert_eq!(row.client_id, Some("c-replay".to_string()));
- assert_eq!(row.tool_call_id, Some("call-replay".to_string()));
- assert!(row.expires_at.is_some());
- assert_eq!(row.steps, vec!["step one".to_string()]);
-
- assert!(gate.decide_by_thread(&tenant(), "t-replay", PlanReviewResolution::Approve));
- parked.await.unwrap();
-
- // Decided reviews are no longer parked.
- assert!(gate
- .parked_review_for_thread(&tenant(), "t-replay")
- .is_none());
-}
-
-#[tokio::test]
-async fn parked_review_for_thread_is_none_when_nothing_is_parked() {
- let gate = PlanReviewGate::new(Duration::from_secs(5));
- assert!(gate
- .parked_review_for_thread(&tenant(), "no-such-thread")
- .is_none());
-}
-
-#[tokio::test]
-async fn parked_reviews_are_isolated_by_tenant() {
- let gate = std::sync::Arc::new(PlanReviewGate::new(Duration::from_secs(5)));
- let alice = crate::core::runtime::Tenant {
- profile: Some("review-alice".into()),
- agent: Some("trigger_reactor".into()),
- };
- let alice_ui = crate::core::runtime::Tenant {
- profile: Some("review-alice".into()),
- agent: None,
- };
- let bob = crate::core::runtime::Tenant {
- profile: Some("review-bob".into()),
- agent: None,
- };
- let parked = gate.request_review(
- alice.clone(),
- Some("same-thread".into()),
- Some("alice-client".into()),
- "Alice's plan".into(),
- vec!["private step".into()],
- None,
- );
- let mut parked = Box::pin(parked);
- assert!(futures::poll!(parked.as_mut()).is_pending());
-
- let alice_review = gate
- .parked_review_for_thread(&alice_ui, "same-thread")
- .expect("Alice's profile UI can replay its agent's review");
- assert!(gate.parked_review_for_thread(&bob, "same-thread").is_none());
- assert!(!gate.decide(
- &bob,
- &alice_review.request_id,
- PlanReviewResolution::Approve
- ));
- assert!(gate.decide(
- &alice_ui,
- &alice_review.request_id,
- PlanReviewResolution::Approve
- ));
- assert_eq!(parked.await, PlanReviewResolution::Approve);
-}
-
-#[test]
-fn socket_review_scope_comes_from_server_context_and_fails_closed_in_saas() {
- let active_profile = Tenant {
- profile: Some("active-profile".into()),
- agent: Some("agent-a".into()),
- };
- let scope = socket_scope_from_context(Ok(active_profile.clone()), true)
- .expect("authenticated server context binds socket scope");
- assert_eq!(scope.0, active_profile);
- assert!(socket_scope_from_context(Err(crate::core::runtime::tenant::NoTenant), true).is_none());
-}
-
-#[tokio::test]
-async fn socket_scope_uses_explicit_dispatch_context_after_task_handoff() {
- use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};
-
- let root = CoreContext::for_test(DomainSet::full(), None);
- let active = root.derive_with(
- ContextOverlay::new(
- crate::config::Config::default(),
- DomainSet::full(),
- crate::tools::toolpacks::ToolGroups::none(),
- )
- .profile("active-profile"),
- );
- let dispatch = DispatchCtx::new(active);
- let gate = PlanReviewGate::new(Duration::from_secs(1));
-
- // Socket.IO spawns its async connect callback. The task-local context is
- // absent there; the request's explicit DispatchCtx remains the authority.
- let scope = tokio::spawn(async move { gate.socket_scope_for_dispatch(&dispatch) })
- .await
- .expect("spawned callback completes")
- .expect("request context binds socket scope");
- assert_eq!(scope.0.profile.as_deref(), Some("active-profile"));
-}
-
-#[test]
-fn local_socket_review_scope_preserves_the_active_profile() {
- let active_profile = Tenant {
- profile: Some("local-profile".into()),
- agent: None,
- };
- let scope = socket_scope_from_context(Ok(active_profile.clone()), false)
- .expect("local socket keeps its active profile");
- assert_eq!(scope.0, active_profile);
-}
diff --git a/crates/openhuman-core/src/plan_review/host.rs b/crates/openhuman-core/src/plan_review/host.rs
new file mode 100644
index 0000000000..b6effcd7cb
--- /dev/null
+++ b/crates/openhuman-core/src/plan_review/host.rs
@@ -0,0 +1,165 @@
+//! OpenHuman policy and event adapters for TinyAgents' plan-review store.
+
+use std::sync::{Arc, OnceLock};
+
+use async_trait::async_trait;
+use tinyagents_harness::middleware::RunMode;
+use tinyagents_harness_tools::plan_review::{
+ InteractiveReviewSurface, ParkedReview, PlanReviewHost, PlanReviewNotifier, PlanReviewReason,
+ PlanReviewRequest, PlanReviewResolution, PlanReviewStore,
+};
+use tinytools::ToolRunContext;
+
+use crate::core::bus::BUS;
+use crate::core::events::DomainEvent;
+use crate::core::runtime::{DispatchCtx, Tenant};
+use crate::security::turn_origin::AgentTurnOrigin;
+
+struct DomainEventNotifier;
+
+impl PlanReviewNotifier<Tenant> for DomainEventNotifier {
+ fn requested(&self, review: &ParkedReview<Tenant>) {
+ BUS.publish(DomainEvent::PlanReviewRequested {
+ request_id: review.request_id.clone(),
+ thread_id: Some(review.thread_id.clone()),
+ client_id: review.client_id.clone(),
+ summary: review.summary.clone(),
+ steps: review.steps.clone(),
+ tool_call_id: review.tool_call_id.clone(),
+ expires_at: Some(review.expires_at.clone()),
+ });
+ }
+
+ fn decided(
+ &self,
+ review: &ParkedReview<Tenant>,
+ resolution: &PlanReviewResolution,
+ reason: PlanReviewReason,
+ ) {
+ let terminal_reason = match reason {
+ PlanReviewReason::Expired => Some("expired"),
+ PlanReviewReason::Cancelled => Some("cancelled"),
+ PlanReviewReason::Approved | PlanReviewReason::Rejected | PlanReviewReason::Revised => {
+ None
+ }
+ };
+ BUS.publish(DomainEvent::PlanReviewDecided {
+ request_id: review.request_id.clone(),
+ decision: resolution.as_str().to_owned(),
+ thread_id: Some(review.thread_id.clone()),
+ client_id: review.client_id.clone(),
+ tool_call_id: review.tool_call_id.clone(),
+ resolution: terminal_reason.map(str::to_owned),
+ });
+ }
+}
+
+/// Process-wide review store. Its keys are normalized to a profile so that
+/// the profile UI can decide or replay a request created by any of its agents.
+#[doc(hidden)]
+pub fn global() -> &'static PlanReviewStore<Tenant> {
+ static STORE: OnceLock<PlanReviewStore<Tenant>> = OnceLock::new();
+ STORE.get_or_init(|| PlanReviewStore::new(Arc::new(DomainEventNotifier)))
+}
+
+struct OpenHumanPlanReviewHost;
+
+#[async_trait]
+impl PlanReviewHost for OpenHumanPlanReviewHost {
+ fn interactive_surface(
+ &self,
+ context: Option<&dyn ToolRunContext>,
+ ) -> Option<InteractiveReviewSurface> {
+ let origin = crate::agent::tinyagents::host::run_context::turn_origin_for_tool(context)?;
+ matches!(origin, AgentTurnOrigin::WebChat { .. }).then_some(InteractiveReviewSurface)
+ }
+
+ fn thread_id(&self, context: Option<&dyn ToolRunContext>) -> Option<String> {
+ crate::agent::tinyagents::host::run_context::approval_for_tool(context)
+ .chat
+ .map(|chat| chat.thread_id)
+ }
+
+ fn run_mode(&self, context: Option<&dyn ToolRunContext>, thread_id: Option<&str>) -> RunMode {
+ thread_id.map_or(RunMode::Build, |thread_id| {
+ crate::threads::run_mode::get_mode(
+ &crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(context),
+ thread_id,
+ )
+ })
+ }
+
+ fn tool_call_id(&self, context: Option<&dyn ToolRunContext>) -> Option<String> {
+ crate::tools::host_extensions::tool_call_id(context)
+ }
+
+ async fn request_review(
+ &self,
+ request: PlanReviewRequest,
+ context: Option<&dyn ToolRunContext>,
+ ) -> Result<PlanReviewResolution, String> {
+ let chat = crate::agent::tinyagents::host::run_context::approval_for_tool(context)
+ .chat
+ .ok_or_else(|| "plan review has no originating chat".to_owned())?;
+ let dispatch = crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(context);
+ let tenant = dispatch
+ .tenant()
+ .map_err(|error| error.to_string())?
+ .profile_only();
+ Ok(global()
+ .request_review(tenant, chat.thread_id, Some(chat.client_id), request)
+ .await)
+ }
+}
+
+/// The harness-owned tool configured with OpenHuman's turn, tenant and event policy.
+type RequestPlanReviewTool = tinyagents_harness_tools::plan_review::RequestPlanReviewTool;
+
+pub(crate) fn request_plan_review_tool() -> RequestPlanReviewTool {
+ tinyagents_harness_tools::plan_review::RequestPlanReviewTool::new(Some(Arc::new(
+ OpenHumanPlanReviewHost,
+ )))
+}
+
+/// Server-captured tenant for replay to a socket that joins a thread room.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SocketReviewScope(Tenant);
+
+/// Captures replay scope from trusted request state, never from socket payloads.
+pub fn socket_scope_for_dispatch(dispatch: &DispatchCtx) -> Option<SocketReviewScope> {
+ match dispatch.tenant() {
+ Ok(tenant) => Some(SocketReviewScope(tenant)),
+ Err(_) if crate::core::runtime::is_saas() => None,
+ Err(_) => Some(SocketReviewScope(Tenant::default())),
+ }
+}
+
+/// Returns the current review for a socket's captured profile scope.
+pub fn parked_review_for_socket(
+ scope: &SocketReviewScope,
+ thread_id: &str,
+) -> Option<ParkedReview<Tenant>> {
+ global().parked_review_for_thread(&scope.0.profile_only(), thread_id)
+}
+
+/// Resolves a request in the profile belonging to the dispatch context.
+pub(crate) fn decide(
+ dispatch: &DispatchCtx,
+ request_id: &str,
+ resolution: PlanReviewResolution,
+) -> Result<bool, String> {
+ let tenant = dispatch
+ .tenant()
+ .map_err(|error| error.to_string())?
+ .profile_only();
+ Ok(global().decide(&tenant, request_id, resolution))
+}
+
+/// Checks whether this profile has a pending review for the thread.
+pub(crate) fn has_parked_review(tenant: &Tenant, thread_id: &str) -> bool {
+ global().has_parked_review(&tenant.profile_only(), thread_id)
+}
+
+#[cfg(test)]
+#[path = "host_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/plan_review/host_tests.rs b/crates/openhuman-core/src/plan_review/host_tests.rs
new file mode 100644
index 0000000000..9058cb1e94
--- /dev/null
+++ b/crates/openhuman-core/src/plan_review/host_tests.rs
@@ -0,0 +1,115 @@
+use super::*;
+
+struct EventCollector(tokio::sync::mpsc::UnboundedSender<DomainEvent>);
+
+#[async_trait::async_trait]
+impl tinybus::EventHandler<DomainEvent> for EventCollector {
+ fn name(&self) -> &str {
+ "plan-review-host-test"
+ }
+
+ async fn handle(&self, event: &DomainEvent) {
+ let _ = self.0.send(event.clone());
+ }
+}
+
+async fn next_for_request(
+ events: &mut tokio::sync::mpsc::UnboundedReceiver<DomainEvent>,
+ request_id: &str,
+ requested: bool,
+) -> DomainEvent {
+ tokio::time::timeout(std::time::Duration::from_secs(1), async {
+ loop {
+ let event = events.recv().await.expect("event stream remains open");
+ let matches = match &event {
+ DomainEvent::PlanReviewRequested { request_id: id, .. } => {
+ requested && id == request_id
+ }
+ DomainEvent::PlanReviewDecided { request_id: id, .. } => {
+ !requested && id == request_id
+ }
+ _ => false,
+ };
+ if matches {
+ return event;
+ }
+ }
+ })
+ .await
+ .expect("plan-review event arrives")
+}
+
+#[tokio::test]
+async fn request_event_replay_and_rpc_decision_share_the_harness_store() {
+ crate::core::bus::init().await.expect("bus init");
+ let (tx, mut events) = tokio::sync::mpsc::unbounded_channel();
+ let _subscription = BUS
+ .subscribe(Arc::new(EventCollector(tx)))
+ .expect("subscribe to core events");
+
+ let dispatch = DispatchCtx::ambient();
+ let tenant = dispatch.tenant().expect("ambient tenant").profile_only();
+ let thread_id = format!("plan-review-host-{}", uuid::Uuid::new_v4());
+ let scope = socket_scope_for_dispatch(&dispatch).expect("trusted socket scope");
+ let store = global();
+ let request_thread = thread_id.clone();
+ let parked = tokio::spawn(async move {
+ store
+ .request_review(
+ tenant,
+ request_thread,
+ Some("test-client".into()),
+ PlanReviewRequest {
+ summary: "Review the change".into(),
+ steps: vec!["Inspect".into(), "Apply".into()],
+ tool_call_id: Some("call-123".into()),
+ },
+ )
+ .await
+ });
+
+ let replay = tokio::time::timeout(std::time::Duration::from_secs(1), async {
+ loop {
+ if let Some(review) = parked_review_for_socket(&scope, &thread_id) {
+ break review;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("pending review is available for replay");
+ let requested = next_for_request(&mut events, &replay.request_id, true).await;
+ let DomainEvent::PlanReviewRequested { request_id, .. } = requested else {
+ unreachable!("filtered to PlanReviewRequested")
+ };
+ assert_eq!(replay.request_id, request_id);
+ assert_eq!(replay.thread_id, thread_id);
+ assert_eq!(replay.summary, "Review the change");
+ assert_eq!(replay.steps, vec!["Inspect".to_owned(), "Apply".to_owned()]);
+ assert_eq!(replay.client_id.as_deref(), Some("test-client"));
+ assert_eq!(replay.tool_call_id.as_deref(), Some("call-123"));
+ assert!(!replay.expires_at.is_empty());
+
+ assert!(
+ decide(&dispatch, &request_id, PlanReviewResolution::Approve).expect("RPC tenant resolves")
+ );
+ assert_eq!(
+ parked.await.expect("park task completes"),
+ PlanReviewResolution::Approve
+ );
+ let decided = next_for_request(&mut events, &request_id, false).await;
+ assert!(matches!(
+ decided,
+ DomainEvent::PlanReviewDecided {
+ decision,
+ thread_id: Some(id),
+ client_id: Some(client),
+ tool_call_id: Some(call_id),
+ resolution: None,
+ ..
+ } if decision == "approve"
+ && id == thread_id
+ && client == "test-client"
+ && call_id == "call-123"
+ ));
+}
diff --git a/crates/openhuman-core/src/plan_review/mod.rs b/crates/openhuman-core/src/plan_review/mod.rs
index 59f771b01b..c931ac0502 100644
--- a/crates/openhuman-core/src/plan_review/mod.rs
+++ b/crates/openhuman-core/src/plan_review/mod.rs
@@ -1,22 +1,7 @@
-//! Interactive plan-review gate (Codex/Claude plan-mode contract).
-//!
-//! When an interactive (`WebChat`) turn proposes a thread-scoped plan, the
-//! orchestrator calls the [`tool::RequestPlanReviewTool`] (`request_plan_review`)
-//! which parks the live turn on [`gate::PlanReviewGate`] until the user decides.
-//! The UI's plan-review card resolves it via the `openhuman.plan_review_decide`
-//! RPC (see [`schemas`]). Approve resumes-and-executes, Reject resumes-and-stops,
-//! Revise resumes-with-feedback so the agent re-plans and re-parks.
-//!
-//! A chat plan is gated on the turn itself: there is no durable board status
-//! to park it on, so the gate holds the live turn. Modelled on
-//! [`crate::security::approval`] but in-memory only.
+//! OpenHuman's RPC, tenant and event adapters for TinyAgents plan review.
-pub mod gate;
+pub mod host;
pub mod schemas;
-pub mod tool;
-pub mod types;
pub use schemas::all_controller_schemas as all_plan_review_controller_schemas;
pub use schemas::all_registered_controllers as all_plan_review_registered_controllers;
-pub use tool::RequestPlanReviewTool;
-pub use types::PlanReviewResolution;
diff --git a/crates/openhuman-core/src/plan_review/schemas.rs b/crates/openhuman-core/src/plan_review/schemas.rs
index c5906c5b5b..bf57d22457 100644
--- a/crates/openhuman-core/src/plan_review/schemas.rs
+++ b/crates/openhuman-core/src/plan_review/schemas.rs
@@ -2,15 +2,14 @@
//! resolves a parked interactive turn (approve / reject / revise-with-feedback).
use crate::core::runtime::DispatchCtx;
-use serde::de::DeserializeOwned;
use serde::Deserialize;
+use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-use super::gate;
-use super::types::PlanReviewResolution;
+use tinyagents_harness_tools::plan_review::PlanReviewResolution;
pub fn all_controller_schemas() -> Vec<ControllerSchema> {
vec![schemas("decide")]
@@ -54,8 +53,7 @@ pub fn schemas(function: &str) -> ControllerSchema {
outputs: vec![FieldSchema {
name: "resolved",
ty: TypeSchema::Bool,
- comment:
- "true if a parked turn was woken; false if the request was unknown/expired.",
+ comment: "true if a parked turn was woken; false if the request was unknown/expired.",
required: true,
}],
},
@@ -84,7 +82,6 @@ struct DecideParams {
fn handle_decide(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let tenant = ctx.tenant().map_err(|error| error.to_string())?;
let p = parse::<DecideParams>(params)?;
let resolution = match p.decision.trim().to_ascii_lowercase().as_str() {
"approve" => PlanReviewResolution::Approve,
@@ -107,7 +104,7 @@ fn handle_decide(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu
decision = resolution.as_str(),
"[rpc][plan_review] decide entry"
);
- let resolved = gate::global().decide(&tenant, &p.request_id, resolution);
+ let resolved = super::host::decide(&ctx, &p.request_id, resolution)?;
Ok(serde_json::json!({ "resolved": resolved }))
})
}
diff --git a/crates/openhuman-core/src/plan_review/tool.rs b/crates/openhuman-core/src/plan_review/tool.rs
deleted file mode 100644
index 6bc4b86a17..0000000000
--- a/crates/openhuman-core/src/plan_review/tool.rs
+++ /dev/null
@@ -1,207 +0,0 @@
-//! `request_plan_review` — the agent tool that parks the current interactive
-//! turn on a plan the user must review before execution.
-//!
-//! The orchestrator calls this AFTER laying out a thread-scoped plan and BEFORE
-//! executing it. On an interactive (`WebChat`) turn the call blocks on
-//! [`PlanReviewGate`] until the user decides; the tool result then tells the
-//! agent to proceed / stop / revise. On any non-interactive origin (cron,
-//! background jobs, CLI, channels) there is no human to ask, so the tool
-//! auto-approves immediately — background automation is never blocked.
-
-use async_trait::async_trait;
-use serde_json::json;
-
-use crate::security::turn_origin::AgentTurnOrigin;
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext, ToolTimeout};
-
-use super::gate;
-use super::types::PlanReviewResolution;
-
-pub struct RequestPlanReviewTool;
-
-impl RequestPlanReviewTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for RequestPlanReviewTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for RequestPlanReviewTool {
- fn name(&self) -> &str {
- "request_plan_review"
- }
-
- fn description(&self) -> &str {
- "Pause the turn so the user can approve a thread-scoped plan before you execute it. Blocks until they decide, then returns `approved`, `rejected`, or `revise` with their feedback. Non-interactive turns (cron / CLI) auto-approve."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "summary": {
- "type": "string",
- "description": "One-line description of the plan being reviewed."
- },
- "steps": {
- "type": "array",
- "description": "Ordered plan steps shown to the user for review.",
- "items": { "type": "string" }
- }
- },
- "required": ["summary"]
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // The gate IS the user consent surface — don't double-gate it through
- // the ApprovalGate as well.
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- fn timeout_policy(&self, _args: &serde_json::Value) -> ToolTimeout {
- // This tool BLOCKS while the user reviews the plan — the global tool
- // timeout (default ~120s) would otherwise drop the parked future before
- // the gate's own 10-minute TTL, so approving the visible card could not
- // resume the turn. The gate is the real deadline (fail-closed reject on
- // TTL), so the harness must not impose its own.
- ToolTimeout::Unbounded
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_in_context(args, None).await
- }
-
- async fn execute_with_context(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- self.execute_in_context(args, context).await
- }
-}
-
-impl RequestPlanReviewTool {
- async fn execute_in_context(
- &self,
- args: serde_json::Value,
- context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let tool_call_id = crate::tools::host_extensions::tool_call_id(context);
- let summary = args
- .get("summary")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- let steps: Vec<String> = args
- .get("steps")
- .and_then(|v| v.as_array())
- .map(|arr| {
- arr.iter()
- .filter_map(|s| s.as_str())
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty())
- .collect()
- })
- .unwrap_or_default();
-
- // Only interactive (WebChat) turns have a human to review the plan.
- // Anything else auto-approves so background automation isn't wedged.
- let origin = crate::agent::tinyagents::host::run_context::turn_origin_for_tool(context)
- .unwrap_or(AgentTurnOrigin::Unknown);
- if !matches!(origin, AgentTurnOrigin::WebChat { .. }) {
- tracing::debug!(
- origin = ?origin,
- "[tool][request_plan_review] non-interactive turn — auto-approving"
- );
- return Ok(ToolResult::success(
- "approved: non-interactive turn (no review surface) — proceed with the plan."
- .to_string(),
- ));
- }
-
- // Route the surface back to the originating chat thread/client (set by
- // the web channel for the turn, the same context the ApprovalGate uses).
- let chat_ctx = crate::agent::tinyagents::host::run_context::approval_for_tool(context).chat;
- let thread_id = chat_ctx.as_ref().map(|c| c.thread_id.clone());
- let client_id = chat_ctx.as_ref().map(|c| c.client_id.clone());
-
- // Inert outside Plan mode (issue: plan-mode approvals). The chat
- // orchestrator carries this tool on its belt at all times so it is
- // reachable the instant a thread enters Plan mode (`agent.toml`), but
- // a research/lookup turn in ordinary Build mode must never park
- // behind a review card — that is the whole reason the tool was kept
- // off the orchestrator's belt before Plan mode existed. Deny the
- // model's own attempt to call it outside Plan mode with a plain
- // instruction rather than parking, so a mis-fire degrades to a no-op
- // instead of freezing the turn on an approval nobody asked for.
- let mode = thread_id
- .as_deref()
- .map(|thread_id| {
- crate::threads::run_mode::get_mode(
- &crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(context),
- thread_id,
- )
- })
- .unwrap_or_default();
- if mode != tinyagents_harness::middleware::RunMode::Plan {
- tracing::debug!(
- thread_id = ?thread_id,
- "[tool][request_plan_review] thread is not in plan mode — not parking"
- );
- return Ok(ToolResult::success(
- "not applicable: this thread is not in plan mode, so there is no plan to \
- review. Do not call `request_plan_review` again this turn."
- .to_string(),
- ));
- }
-
- tracing::info!(
- thread_id = ?thread_id,
- steps = steps.len(),
- "[tool][request_plan_review] parking interactive turn for plan review"
- );
-
- let dispatch_ctx =
- crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(context);
- let tenant = dispatch_ctx
- .tenant()
- .map_err(|error| anyhow::anyhow!(error.to_string()))?;
- let resolution = gate::global()
- .request_review(tenant, thread_id, client_id, summary, steps, tool_call_id)
- .await;
-
- let result = match resolution {
- PlanReviewResolution::Approve => ToolResult::success(
- "approved: the user approved the plan — proceed and execute it now.".to_string(),
- ),
- PlanReviewResolution::Reject => ToolResult::success(
- "rejected: the user rejected the plan — do NOT execute it. Briefly ask what \
- they would like to do instead."
- .to_string(),
- ),
- PlanReviewResolution::Revise { feedback } => ToolResult::success(format!(
- "revise: the user requested changes before executing. Their feedback:\n{feedback}\n\
- Revise the plan accordingly, then call `request_plan_review` again before \
- executing."
- )),
- };
- Ok(result)
- }
-}
-
-#[cfg(test)]
-#[path = "tool_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/plan_review/tool_tests.rs b/crates/openhuman-core/src/plan_review/tool_tests.rs
deleted file mode 100644
index f35ffc2810..0000000000
--- a/crates/openhuman-core/src/plan_review/tool_tests.rs
+++ /dev/null
@@ -1,82 +0,0 @@
-use super::*;
-use crate::security::approval::ApprovalChatContext;
-use crate::security::turn_origin::with_origin;
-
-/// The execution context the harness hands a tool dispatched inside a turn
-/// whose chat is `chat`.
-fn chat_tool_context(
- chat: crate::security::approval::ApprovalChatContext,
-) -> tinyagents_harness::tool::ToolExecutionContext {
- crate::agent::tinyagents::host::run_context::tool_context_with_approval(
- crate::security::approval::ApprovalTurnContext::chat(chat),
- )
-}
-
-#[tokio::test]
-async fn non_interactive_origin_auto_approves() {
- let tool = RequestPlanReviewTool::new();
- let out = with_origin(
- AgentTurnOrigin::Cli,
- tool.execute(json!({ "summary": "do x", "steps": ["a", "b"] })),
- )
- .await
- .unwrap();
- assert!(!out.is_error);
- assert!(out.output().starts_with("approved"));
-}
-
-#[tokio::test]
-async fn interactive_turn_parks_until_resolved() {
- // The tool is inert (no-ops rather than parks) outside Plan mode — see
- // `plan_mode_is_inert_outside_plan_mode` below — so this thread must be
- // in Plan mode for the park to actually happen.
- crate::threads::run_mode::set_mode(
- &crate::core::runtime::DispatchCtx::ambient(),
- "t-int",
- tinyagents_harness::middleware::RunMode::Plan,
- );
- let tool = RequestPlanReviewTool::new();
- let context = chat_tool_context(ApprovalChatContext {
- thread_id: "t-int".into(),
- client_id: "c-int".into(),
- request_id: Some("req-int".into()),
- });
- let fut = with_origin(
- AgentTurnOrigin::WebChat {
- thread_id: "t-int".into(),
- client_id: "c-int".into(),
- request_id: Some("req-int".into()),
- },
- tool.execute_with_context(
- json!({ "summary": "plan", "steps": ["one"] }),
- tinytools::ToolCallOptions::default(),
- Some(&context),
- ),
- );
- // The web channel supplies the origin and the chat context. One poll reaches the gate
- // and must remain pending; no wall-clock timeout is needed to prove park.
- tokio::pin!(fut);
- assert!(
- matches!(futures::poll!(fut.as_mut()), std::task::Poll::Pending),
- "interactive turn should park, not resolve immediately"
- );
-}
-
-#[tokio::test]
-async fn plan_mode_is_inert_outside_plan_mode() {
- // A thread that has never toggled plan mode defaults to Build — the
- // tool must no-op (return immediately) rather than park.
- let tool = RequestPlanReviewTool::new();
- let out = with_origin(
- AgentTurnOrigin::WebChat {
- thread_id: "t-build-inert".into(),
- client_id: "c-build-inert".into(),
- request_id: Some("req-build-inert".into()),
- },
- tool.execute(json!({ "summary": "plan", "steps": ["one"] })),
- )
- .await
- .unwrap();
- assert!(!out.is_error);
- assert!(out.output().starts_with("not applicable"));
-}
diff --git a/crates/openhuman-core/src/plan_review/types.rs b/crates/openhuman-core/src/plan_review/types.rs
deleted file mode 100644
index 67f6c9cbc9..0000000000
--- a/crates/openhuman-core/src/plan_review/types.rs
+++ /dev/null
@@ -1,36 +0,0 @@
-//! Types for the interactive plan-review gate.
-//!
-//! A plan review parks a live (interactive) agent turn after the orchestrator
-//! has laid out a thread-scoped plan, surfaces the plan to the user, and
-//! resumes the SAME turn with the user's decision. The gate is a
-//! parked-future on the live turn — modelled on
-//! [`crate::security::approval::ApprovalGate`] but
-//! in-memory only: an interactive turn that can't resume across a restart has
-//! nothing to persist.
-
-use serde::{Deserialize, Serialize};
-
-/// The user's decision on a parked plan, sent back to the parked turn.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(tag = "decision", rename_all = "snake_case")]
-pub enum PlanReviewResolution {
- /// Run the plan as proposed — the parked turn resumes and executes.
- Approve,
- /// Drop the plan — the parked turn resumes and stops without executing.
- Reject,
- /// Revise the plan per `feedback` — the parked turn resumes, re-plans, and
- /// re-parks for another review.
- Revise { feedback: String },
-}
-
-impl PlanReviewResolution {
- /// Stable label for events/logs (the `Revise` payload is omitted here —
- /// feedback is user content and must not land in redacted event fields).
- pub fn as_str(&self) -> &'static str {
- match self {
- Self::Approve => "approve",
- Self::Reject => "reject",
- Self::Revise { .. } => "revise",
- }
- }
-}
diff --git a/crates/openhuman-core/src/threads/run_mode.rs b/crates/openhuman-core/src/threads/run_mode.rs
index 63a6609fd4..358efa6637 100644
--- a/crates/openhuman-core/src/threads/run_mode.rs
+++ b/crates/openhuman-core/src/threads/run_mode.rs
@@ -1,34 +1,34 @@
-//! Per-thread [`RunMode`] registry (Plan vs Build).
-//!
-//! `tinyagents_harness::middleware::{RunMode, RunModeHandle, plan_mode_middleware}`
-//! (vendor tinyagents#211) gate side-effecting tools per-run via a live
-//! [`RunModeHandle`] the host can flip without restarting the run. OpenHuman's
-//! unit of "a run" for this purpose is a chat *thread*: the same thread is
-//! driven through many independent turns (one `install_turn_middleware` call
-//! each), so the mode has to live somewhere that outlives any one turn's
-//! [`crate::agent::tinyagents::host::OpenHumanRunContext`] — this process-wide,
-//! thread_id-keyed registry is that home.
-//!
-//! `plan_exit` (the tool) and the `agent.set_run_mode` / `agent.get_run_mode`
-//! RPCs both read/write through here; `turn_exec` looks the handle up by
-//! `OpenHumanRunContext::thread_id` right before assembling each turn's
-//! harness and pushes `plan_mode_middleware(handle, ..)` when a handle exists
-//! for the thread.
+//! OpenHuman's RPC and event adapter for TinyAgents' per-thread run-mode store.
use crate::core::runtime::DispatchCtx;
-use std::collections::HashMap;
use std::sync::Arc;
-
-use parking_lot::Mutex;
use tinyagents_harness::middleware::{RunMode, RunModeHandle};
+use tinyagents_harness_tools::run_mode::{InMemoryRunModeStore, ModeChangeNotifier, RunModeStore};
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
-type RunModeRegistry = Mutex<HashMap<String, RunModeHandle>>;
+struct ThreadRunModes(InMemoryRunModeStore<()>);
+
+struct DomainEventNotifier;
+
+impl ModeChangeNotifier<()> for DomainEventNotifier {
+ fn changed(&self, _scope: &(), thread_id: &str, mode: RunMode) {
+ BUS.publish(DomainEvent::ThreadRunModeChanged {
+ thread_id: thread_id.to_owned(),
+ mode: mode_label(mode).to_owned(),
+ });
+ }
+}
+
+impl Default for ThreadRunModes {
+ fn default() -> Self {
+ Self(InMemoryRunModeStore::new(Arc::new(DomainEventNotifier)))
+ }
+}
-fn registry(ctx: &DispatchCtx) -> Arc<RunModeRegistry> {
- crate::core::runtime::slot_for::<RunModeRegistry>(ctx)
+fn registry(ctx: &DispatchCtx) -> Arc<ThreadRunModes> {
+ crate::core::runtime::slot_for::<ThreadRunModes>(ctx)
}
/// Returns the [`RunModeHandle`] for `thread_id`, creating one (starting in
@@ -36,21 +36,13 @@ fn registry(ctx: &DispatchCtx) -> Arc<RunModeRegistry> {
/// the same underlying atomic, so every clone (a live turn's middleware, this
/// registry's own copy, a later RPC call) observes the same live value.
pub fn handle_for_thread(ctx: &DispatchCtx, thread_id: &str) -> RunModeHandle {
- let registry = registry(ctx);
- let mut map = registry.lock();
- map.entry(thread_id.to_string())
- .or_insert_with(|| RunModeHandle::new(RunMode::Build))
- .clone()
+ registry(ctx).0.handle_for_thread(&(), thread_id)
}
/// Returns the current mode for `thread_id` without creating a handle —
/// `Build` (the default) when the thread has never toggled plan mode.
pub fn get_mode(ctx: &DispatchCtx, thread_id: &str) -> RunMode {
- registry(ctx)
- .lock()
- .get(thread_id)
- .map(|h| h.get())
- .unwrap_or_default()
+ registry(ctx).0.get_mode(&(), thread_id)
}
/// Sets the mode for `thread_id` (creating a handle if needed) and publishes
@@ -58,38 +50,18 @@ pub fn get_mode(ctx: &DispatchCtx, thread_id: &str) -> RunMode {
/// `run_mode_changed` socket event. A no-op publish-wise when the mode is
/// already what was requested — still safe to call unconditionally.
pub fn set_mode(ctx: &DispatchCtx, thread_id: &str, mode: RunMode) {
- let handle = handle_for_thread(ctx, thread_id);
- let changed = handle.get() != mode;
- handle.set(mode);
- if changed {
- tracing::info!(
- thread_id = %thread_id,
- mode = mode_label(mode),
- "[agent::run_mode] thread run mode changed"
- );
- BUS.publish(DomainEvent::ThreadRunModeChanged {
- thread_id: thread_id.to_string(),
- mode: mode_label(mode).to_string(),
- });
- }
+ registry(ctx).0.set_mode(&(), thread_id, mode);
}
/// Stable wire label for a [`RunMode`] — `"plan"` / `"build"`.
pub fn mode_label(mode: RunMode) -> &'static str {
- match mode {
- RunMode::Plan => "plan",
- RunMode::Build => "build",
- }
+ tinyagents_harness_tools::run_mode::mode_label(mode)
}
/// Parses a wire label back into a [`RunMode`]. Unrecognized input maps to
/// `None` so callers can reject it rather than silently defaulting.
pub fn parse_mode_label(label: &str) -> Option<RunMode> {
- match label {
- "plan" => Some(RunMode::Plan),
- "build" => Some(RunMode::Build),
- _ => None,
- }
+ tinyagents_harness_tools::run_mode::parse_mode_label(label)
}
// ── JSON-RPC surface ────────────────────────────────────────────────────────
@@ -100,8 +72,8 @@ pub fn parse_mode_label(label: &str) -> Option<RunMode> {
// `schemas.rs` because this module IS the domain's entire surface (registry
// + RPC), not a multi-file domain directory.
-use serde::de::DeserializeOwned;
use serde::Deserialize;
+use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
diff --git a/crates/openhuman-core/src/web_chat/event_bus.rs b/crates/openhuman-core/src/web_chat/event_bus.rs
index 86e0da7726..2743afe8a1 100644
--- a/crates/openhuman-core/src/web_chat/event_bus.rs
+++ b/crates/openhuman-core/src/web_chat/event_bus.rs
@@ -729,3 +729,7 @@ impl EventHandler<DomainEvent> for ApprovalSurfaceSubscriber {
#[cfg(test)]
#[path = "event_bus_tests.rs"]
mod tests;
+
+#[cfg(test)]
+#[path = "plan_review_event_tests.rs"]
+mod plan_review_event_tests;
diff --git a/crates/openhuman-core/src/web_chat/plan_review_event_tests.rs b/crates/openhuman-core/src/web_chat/plan_review_event_tests.rs
new file mode 100644
index 0000000000..1939340043
--- /dev/null
+++ b/crates/openhuman-core/src/web_chat/plan_review_event_tests.rs
@@ -0,0 +1,54 @@
+use super::*;
+use tokio::sync::broadcast;
+
+#[tokio::test]
+async fn parked_plan_review_is_projected_as_the_socket_request_event() {
+ crate::core::bus::init().await.expect("bus init");
+ let _subscription = crate::core::bus::BUS
+ .subscribe(Arc::new(ApprovalSurfaceSubscriber))
+ .expect("subscribe to plan review events");
+ let mut web_rx = subscribe_web_channel_events();
+
+ crate::core::bus::BUS.publish(DomainEvent::PlanReviewRequested {
+ request_id: "plan-socket-projection".into(),
+ thread_id: Some("thread-socket-projection".into()),
+ client_id: Some("client-socket-projection".into()),
+ summary: "Review this plan".into(),
+ steps: vec!["Inspect".into(), "Apply".into()],
+ tool_call_id: Some("call-socket-projection".into()),
+ expires_at: Some("2030-01-01T00:00:00Z".into()),
+ });
+
+ let event = tokio::time::timeout(std::time::Duration::from_secs(1), async {
+ loop {
+ match web_rx.recv().await {
+ Ok(event)
+ if event.event == "plan_review_request"
+ && event.request_id == "plan-socket-projection" =>
+ {
+ return event;
+ }
+ Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => continue,
+ Err(broadcast::error::RecvError::Closed) => {
+ panic!("web-channel event stream closed")
+ }
+ }
+ }
+ })
+ .await
+ .expect("plan_review_request event arrives");
+
+ assert_eq!(event.thread_id, "thread-socket-projection");
+ assert_eq!(event.client_id, "client-socket-projection");
+ assert_eq!(event.tool_name.as_deref(), Some("request_plan_review"));
+ assert_eq!(
+ event.tool_call_id.as_deref(),
+ Some("call-socket-projection")
+ );
+ assert_eq!(event.message.as_deref(), Some("Review this plan"));
+ assert_eq!(event.expires_at.as_deref(), Some("2030-01-01T00:00:00Z"));
+ assert_eq!(
+ event.args.as_ref().and_then(|args| args.get("steps")),
+ Some(&serde_json::json!(["Inspect", "Apply"]))
+ );
+}
diff --git a/crates/openhuman-embed/src/host_internals.rs b/crates/openhuman-embed/src/host_internals.rs
index a340e8e627..454f62896a 100644
--- a/crates/openhuman-embed/src/host_internals.rs
+++ b/crates/openhuman-embed/src/host_internals.rs
@@ -181,9 +181,9 @@ pub mod agent {
pub use openhuman_core::agent::orchestration::release_background_completion_stores;
}
pub mod plan_review {
- pub mod gate {
- pub use openhuman_core::plan_review::gate::{global, SocketReviewScope};
- }
+ pub use openhuman_core::plan_review::host::{
+ parked_review_for_socket, socket_scope_for_dispatch, SocketReviewScope,
+ };
}
pub mod session_store {
pub use openhuman_core::storage::sessions::{
diff --git a/crates/openhuman-rpc/src/server/socketio.rs b/crates/openhuman-rpc/src/server/socketio.rs
index 5535d4261c..05d2cf3035 100644
--- a/crates/openhuman-rpc/src/server/socketio.rs
+++ b/crates/openhuman-rpc/src/server/socketio.rs
@@ -69,7 +69,7 @@ struct AuthedConnection;
/// The per-process bearer authenticates the connection but does not encode a
/// SaaS profile, so never accept tenant selection from a later event payload.
#[derive(Clone, Debug)]
-struct SocketTenant(crate::core_host::agent::plan_review::gate::SocketReviewScope);
+struct SocketTenant(crate::core_host::agent::plan_review::SocketReviewScope);
/// Bind replay tenancy from the HTTP request extensions retained by
/// Socket.IO. Its async connect callback is spawned independently of the
@@ -78,8 +78,7 @@ fn socket_tenant_from_request_extensions(
extensions: &axum::http::Extensions,
) -> Option<SocketTenant> {
let dispatch = extensions.get::<crate::core_host::core::runtime::DispatchCtx>()?;
- let scope =
- crate::core_host::agent::plan_review::gate::global().socket_scope_for_dispatch(dispatch)?;
+ let scope = crate::core_host::agent::plan_review::socket_scope_for_dispatch(dispatch)?;
Some(SocketTenant(scope))
}
@@ -1215,8 +1214,10 @@ fn replay_parked_plan_review(socket: &SocketRef, thread_id: &str) {
let Some(tenant) = socket.extensions.get::<SocketTenant>() else {
return;
};
- let Some(row) = crate::core_host::agent::plan_review::gate::global()
- .parked_review_for_socket(&tenant.0, thread_id)
+ let Some(row) = crate::core_host::agent::plan_review::parked_review_for_socket(
+ &tenant.0,
+ thread_id,
+ )
else {
return;
};
@@ -1228,7 +1229,7 @@ fn replay_parked_plan_review(socket: &SocketRef, thread_id: &str) {
thread_id,
&client_id,
row.tool_call_id.as_deref(),
- row.expires_at.as_deref(),
+ Some(row.expires_at.as_str()),
);
event.ts = Some(crate::core_host::web_chat::unix_epoch_ms());
let Ok(payload) = serde_json::to_value(&event) else {
diff --git a/crates/openhuman-rpc/src/server/socketio_tests.rs b/crates/openhuman-rpc/src/server/socketio_tests.rs
index 905e3ebd0a..d48d1a7e8c 100644
--- a/crates/openhuman-rpc/src/server/socketio_tests.rs
+++ b/crates/openhuman-rpc/src/server/socketio_tests.rs
@@ -8,7 +8,7 @@ use super::{
async fn socket_connect_reads_dispatch_context_from_request_extensions_after_spawn() {
let dispatch = crate::core_host::core::runtime::DispatchCtx::process_default();
let expected =
- crate::core_host::agent::plan_review::gate::global().socket_scope_for_dispatch(&dispatch);
+ crate::core_host::agent::plan_review::socket_scope_for_dispatch(&dispatch);
let mut extensions = axum::http::Extensions::new();
extensions.insert(dispatch);
diff --git a/tests/json_rpc_e2e.rs b/tests/json_rpc_e2e.rs
index 8713668450..40c1a120dd 100644
--- a/tests/json_rpc_e2e.rs
+++ b/tests/json_rpc_e2e.rs
@@ -3771,6 +3771,80 @@ async fn json_rpc_plan_review_decide_unknown_and_invalid() {
rpc_join.abort();
}
+#[tokio::test]
+async fn json_rpc_plan_review_decide_wakes_a_parked_review() {
+ let _env_lock = json_rpc_e2e_env_lock_async().await;
+ let tmp = tempdir().expect("tempdir");
+ let home = tmp.path();
+ let openhuman_home = home.join(".openhuman");
+
+ let _home_guard = EnvVarGuard::set_to_path("HOME", home);
+ let _workspace_guard = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
+ let _backend_url_guard = EnvVarGuard::unset("BACKEND_URL");
+ let _vite_backend_url_guard = EnvVarGuard::unset("VITE_BACKEND_URL");
+ let _api_url_guard = EnvVarGuard::unset("OPENHUMAN_API_URL");
+
+ let (api_addr, api_join) = serve_on_ephemeral(mock_upstream_router()).await;
+ write_min_config(openhuman_home.as_path(), &format!("http://{api_addr}"));
+ let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;
+ let rpc_base = format!("http://{rpc_addr}");
+
+ let dispatch = openhuman_core::core::runtime::DispatchCtx::ambient();
+ let tenant = dispatch.tenant().expect("ambient tenant").profile_only();
+ let thread_id = format!("plan-review-rpc-{}", uuid::Uuid::new_v4());
+ let scope = openhuman_core::plan_review::host::socket_scope_for_dispatch(&dispatch)
+ .expect("trusted socket scope");
+ let store = openhuman_core::plan_review::host::global();
+ let request_thread = thread_id.clone();
+ let parked = tokio::spawn(async move {
+ store
+ .request_review(
+ tenant,
+ request_thread,
+ Some("rpc-e2e-client".into()),
+ tinyagents_harness_tools::plan_review::PlanReviewRequest {
+ summary: "Resolve through the live RPC controller".into(),
+ steps: vec!["Wait for the user".into()],
+ tool_call_id: Some("call-rpc-e2e".into()),
+ },
+ )
+ .await
+ });
+
+ let replay = tokio::time::timeout(Duration::from_secs(1), async {
+ loop {
+ if let Some(review) =
+ openhuman_core::plan_review::host::parked_review_for_socket(&scope, &thread_id)
+ {
+ break review;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("parked review becomes available for socket replay");
+ assert_eq!(replay.thread_id, thread_id);
+ assert_eq!(replay.summary, "Resolve through the live RPC controller");
+ assert_eq!(replay.tool_call_id.as_deref(), Some("call-rpc-e2e"));
+
+ let decided = post_json_rpc(
+ &rpc_base,
+ 9304,
+ "openhuman.plan_review_decide",
+ json!({ "request_id": replay.request_id, "decision": "approve" }),
+ )
+ .await;
+ let result = assert_no_jsonrpc_error(&decided, "plan_review_decide parked request");
+ assert_eq!(result.get("resolved").and_then(Value::as_bool), Some(true));
+ assert_eq!(
+ parked.await.expect("parked turn completes"),
+ tinyagents_harness_tools::plan_review::PlanReviewResolution::Approve
+ );
+
+ api_join.abort();
+ rpc_join.abort();
+}
+
#[tokio::test]
async fn json_rpc_thread_title_create_and_update() {
let _env_lock = json_rpc_e2e_env_lock_async().await;
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 356ec10cab..d78160599d 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 356ec10cabe78a50bb7f634198bfe10eebce5e18
+Subproject commit d78160599dd15b8917518a07720a9d59ae878b00