Skip to content

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

chore: remove agent_prepare_context tool and its context_scout subagent

Steven Enamakel3df083ef8882
diff --git a/app/src/utils/toolTimelineFormatting.agentPrepareContext.test.ts b/app/src/utils/toolTimelineFormatting.agentPrepareContext.test.ts
deleted file mode 100644
index a892b230e4..0000000000
--- a/app/src/utils/toolTimelineFormatting.agentPrepareContext.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { ToolTimelineEntry } from '../store/chatRuntimeSlice';
-import { formatTimelineEntry, formatToolName } from './toolTimelineFormatting';
-
-function entry(partial: Partial<ToolTimelineEntry> & { name: string }): ToolTimelineEntry {
- return { id: 'e1', round: 0, seq: 0, status: 'running', ...partial };
-}
-
-describe('toolTimelineFormatting — agent_prepare_context / context_scout', () => {
- it('labels the agent_prepare_context tool name', () => {
- expect(formatToolName('agent_prepare_context')).toBe('Preparing context');
- });
-
- it('formats the agent_prepare_context tool entry with the question as detail', () => {
- const result = formatTimelineEntry(
- entry({
- name: 'agent_prepare_context',
- argsBuffer: JSON.stringify({ question: 'what should I focus on?' }),
- })
- );
- expect(result.title).toBe('Preparing context');
- expect(result.detail).toBe('what should I focus on?');
- });
-
- it('formats the context_scout subagent rows', () => {
- expect(formatTimelineEntry(entry({ name: 'subagent:context_scout', detail: 'd' })).title).toBe(
- 'Scouting context'
- );
- expect(formatTimelineEntry(entry({ name: 'context_scout' })).title).toBe('Scouting context');
- });
-});
diff --git a/crates/openhuman-core/src/agent/orchestration/tools.rs b/crates/openhuman-core/src/agent/orchestration/tools.rs
index b3b7942796..4c166cd460 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools.rs
@@ -8,7 +8,7 @@
//! - **Control**: `steer_subagent`, `continue_subagent`, `close_subagent`,
//! `wait_subagent`, `wait` / `wait_loop`, `list_subagents`.
//! - **Delegation**: `DelegateGraphTool`, `ArchetypeDelegationTool`,
-//! `CollapsedDelegationTool` (`delegate_to`), and `agent_prepare_context`.
+//! and `CollapsedDelegationTool` (`delegate_to`).
//!
//! `dispatch.rs`, `awaiting_user.rs`, and `worker_thread.rs` are `pub(crate)`
//! helpers shared by the tools above (the common spawn path, the awaiting-user
@@ -20,8 +20,6 @@
//! `agent::subagent_host::run_subagent`; this module only owns the tool-call
//! surface (schema, argument parsing, response formatting).
-#[path = "tools/agent_prepare_context.rs"]
-mod agent_prepare_context;
#[path = "tools/archetype_delegation.rs"]
mod archetype_delegation;
#[path = "tools/awaiting_user.rs"]
@@ -79,10 +77,6 @@ pub(crate) fn ambient_parent_run_context(
})
}
-pub(crate) use agent_prepare_context::AgentPrepareContextDispatch;
-pub use agent_prepare_context::{
- run_context_scout, run_context_scout_with_catalog, AgentPrepareContextTool,
-};
pub use archetype_delegation::{ArchetypeDelegationTool, DelegationTarget};
pub(crate) use close_subagent::CloseSubagentDispatch;
pub use close_subagent::CloseSubagentTool;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context.rs
deleted file mode 100644
index 683d281dfd..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-//! Tool: `agent_prepare_context` — "plan mode as a subagent".
-//!
-//! When a parent agent explicitly needs an ad hoc context pass, it can call
-//! `agent_prepare_context`. This runs the read-only `context_scout` sub-agent
-//! inline (blocking), which gathers context from memory, the user's
-//! goals/profile, connected integrations, and the web, then returns a tight
-//! `[context_bundle]` envelope: whether there's enough context to act, a
-//! compact context summary, and an ordered set of recommended next tool calls
-//! drawn from the *parent's own* tool catalogue.
-//!
-//! The scout's output is bounded by `context_scout`'s `max_result_chars`
-//! (≈1000 tokens) so the parent's context only grows by a bounded amount.
-//!
-//! - [`scout_run`] — the engine: running `context_scout` inline, extracting
-//! its envelope, and classifying/logging failures.
-//! - [`tool`] — the `Tool` wrapper: schema and parent-catalogue rendering.
-
-#[path = "agent_prepare_context/scout_run.rs"]
-mod scout_run;
-#[path = "agent_prepare_context/tool.rs"]
-mod tool;
-
-#[cfg(test)]
-#[path = "agent_prepare_context_tests.rs"]
-mod tests;
-
-pub use scout_run::{run_context_scout, run_context_scout_with_catalog};
-pub(crate) use tool::AgentPrepareContextDispatch;
-pub use tool::AgentPrepareContextTool;
-
-#[cfg(test)]
-use scout_run::{extract_context_bundle, is_expected_billing_failure, scout_failure_signal};
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs
deleted file mode 100644
index db8bc3ebf9..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs
+++ /dev/null
@@ -1,638 +0,0 @@
-//! The `context_scout` engine: running the sub-agent inline (blocking),
-//! extracting its `[context_bundle]` envelope, classifying/logging failures,
-//! and bootstrapping a thread goal from the scout's proposal.
-
-use crate::agent::harness::definition::AgentDefinitionRegistry;
-use crate::agent::harness::fork_context::AgentContextPreparedSource;
-use crate::agent::progress::AgentProgress;
-use crate::agent::subagent_host::{
- run_subagent_with_parent, SubagentRunError, SubagentRunOptions, SubagentRunStatus,
-};
-use crate::core::bus::BUS;
-use crate::core::events::DomainEvent;
-use tinytools::ToolResult;
-use tinytools::WorkspaceDescriptor;
-
-use super::tool::AgentPrepareContextTool;
-
-/// The sub-agent archetype this tool drives.
-const SCOUT_AGENT_ID: &str = "context_scout";
-
-/// Extract exactly one `[context_bundle] … [/context_bundle]` envelope from
-/// `output`, tolerating surrounding prose, and return only the envelope
-/// substring (tags included). Returns `None` when no usable envelope is
-/// present.
-///
-/// The `context_scout` contract is "emit the single envelope and nothing
-/// outside it", but the fast model may wrap the envelope in a preamble (`Sure,
-/// here's what I found:\n[context_bundle]…`) or a closing line
-/// (`…[/context_bundle]\nHope that helps!`). Requiring the *whole* trimmed
-/// output to be the envelope would discard an otherwise-good bundle.
-///
-/// Pulling the envelope substring out of the surrounding text keeps the safety
-/// property intact: callers receive only the bracketed envelope, never the
-/// model's free-form prose. We still reject genuinely unusable output —
-/// absent, unterminated/reversed, or duplicated (where we can't tell which
-/// envelope is authoritative) — by returning `None`.
-pub(super) fn extract_context_bundle(output: &str) -> Option<String> {
- const OPEN: &str = "[context_bundle]";
- const CLOSE: &str = "[/context_bundle]";
- // Exactly one open + one close tag. Duplicates are a contract violation we
- // reject rather than guess which envelope is authoritative.
- if output.matches(OPEN).count() != 1 || output.matches(CLOSE).count() != 1 {
- return None;
- }
- let open_idx = output.find(OPEN)?;
- let close_idx = output.find(CLOSE)?;
- // Tags must appear in order (open before close) and not overlap.
- if close_idx < open_idx + OPEN.len() {
- return None;
- }
- let end = close_idx + CLOSE.len();
- Some(output[open_idx..end].trim().to_string())
-}
-
-pub(super) fn already_prepared_context_bundle(sources: &[AgentContextPreparedSource]) -> String {
- let source_names = if sources.is_empty() {
- "the OpenHuman harness".to_string()
- } else {
- sources
- .iter()
- .map(|source| source.source.as_str())
- .collect::<Vec<_>>()
- .join(", ")
- };
- let has_enough_context = if sources
- .iter()
- .any(|source| source.has_enough_context == Some(false))
- {
- false
- } else {
- sources
- .iter()
- .any(|source| source.has_enough_context == Some(true))
- };
- let sufficiency_note = if has_enough_context {
- "The earlier prepared context reported enough context."
- } else {
- "This no-op result does not assert that enough context is available; \
- inspect the earlier prepared-context blocks for sufficiency and recommended follow-up tools."
- };
- format!(
- "[context_bundle]\nhas_enough_context: {has_enough_context}\nproposed_goal: none\n\
- summary: Agent context has already been prepared once for this turn by {source_names}. \
- {sufficiency_note} Use the existing prepared-context blocks in the current user message; do not run \
- another context_scout pass.\nrecommended_tool_calls:\n[/context_bundle]"
- )
-}
-
-/// Run the `context_scout` sub-agent inline (blocking) for `question` and
-/// return its bounded `[context_bundle]` envelope as a [`ToolResult`].
-///
-/// This is the engine behind [`AgentPrepareContextTool`], invoked autonomously
-/// by the LLM when it decides to scout context mid-turn.
-///
-/// Must be called from within an active agent turn (i.e. with the
-/// [`crate::agent::harness::fork_context::PARENT_CONTEXT`]
-/// task-local installed) — it reads the parent's visible tool catalogue
-/// and runs the scout against the parent's provider. Outside a turn the
-/// `run_subagent` call surfaces a no-parent error as a [`ToolResult::error`].
-pub async fn run_context_scout(question: &str, focus: Option<&str>) -> anyhow::Result<ToolResult> {
- let tool_catalog = AgentPrepareContextTool::render_parent_tool_catalog(None);
- run_context_scout_with_catalog(question, focus, &tool_catalog).await
-}
-
-/// Same as [`run_context_scout`] but with an **explicitly-supplied** tool
-/// catalogue — for callers *outside* an agent turn that can't receive the
-/// parent's visible tool set explicitly (e.g. the subconscious
-/// engine's structured tick).
-///
-/// The caller passes the catalogue of tools the eventual decision agent can
-/// actually call (one `- name: description` per line), so the bundle's
-/// `recommended_tool_calls` stay grounded in callable tools.
-///
-/// **A parent execution context is still required.** Like [`run_context_scout`]
-/// this spawns `context_scout` via `run_subagent`, which resolves its provider /
-/// tools / model from the `PARENT_CONTEXT` task-local and returns
-/// `NoParentContext` when it is unset. A background surface with no enclosing
-/// turn MUST establish a root parent first — call this *inside*
-/// [`with_root_parent`](crate::agent::orchestration::parent_context::with_root_parent).
-/// Skipping that is exactly the TAURI-RUST-HMW failure (#4337): every spawn
-/// died with `NoParentContext` and the tick ran un-grounded. Only the
-/// progress / subagent-lifecycle telemetry degrades gracefully without a
-/// parent — `parent_session` falls back to `standalone` and the absent progress
-/// sink no-ops — but the spawn itself does not.
-pub async fn run_context_scout_with_catalog(
- question: &str,
- focus: Option<&str>,
- tool_catalog: &str,
-) -> anyhow::Result<ToolResult> {
- run_context_scout_with_catalog_and_workspace(
- question,
- focus,
- tool_catalog,
- None,
- None,
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
- None,
- None,
- )
- .await
-}
-
-/// The text [`log_scout_failure`] classifies: a failed run flattened into one
-/// string, `source` chain included.
-///
-/// The billing classifiers key on the **provider wire body**
-/// (`… "errorCode":"USER_INSUFFICIENT_CREDITS"`), which arrives inside
-/// [`SubagentRunError::Provider`]'s `anyhow` error — often as a *cause* under a
-/// context layer, so `to_string()` alone renders only `"provider call failed:
-/// <top-level context>"` and would miss the very failure this exists to demote.
-/// Walk `anyhow`'s chain for that variant; every other variant is a flat
-/// `thiserror` message already. Used for classification only — the
-/// user-visible `message` stays `err.to_string()`, unchanged.
-pub(super) fn scout_failure_signal(err: &SubagentRunError) -> String {
- let SubagentRunError::Provider(inner) = err else {
- return err.to_string();
- };
- let mut chain = inner.to_string();
- for cause in inner.chain().skip(1) {
- chain.push_str(": ");
- chain.push_str(&cause.to_string());
- }
- chain
-}
-
-/// Is a failed `context_scout` run just the user being out of credits?
-///
-/// Two billing shapes reach here, both **user-state, not defects**:
-/// * the managed OpenHuman backend's budget-exhausted 400
-/// (`{"error":"Insufficient budget","errorCode":"USER_INSUFFICIENT_CREDITS"}`),
-/// matched by [`crate::backend::classify::is_budget_exhausted_message`];
-/// * a BYO provider's insufficient-credits 402, matched by
-/// [`crate::core::observability::is_insufficient_credits_message`].
-///
-/// Both delegate to the crate's single-source classifiers so the phrase sets
-/// can't drift from the cron halt / `before_send` nets that share them.
-pub(super) fn is_expected_billing_failure(message: &str) -> bool {
- crate::backend::classify::is_budget_exhausted_message(message)
- || crate::core::observability::is_insufficient_credits_message(message)
-}
-
-/// Log a failed `context_scout` run at the severity its cause deserves.
-///
-/// The scout is a **background/best-effort** pass: every caller already
-/// degrades to the un-augmented message on failure. When the cause is the user
-/// being out of credits (`USER_INSUFFICIENT_CREDITS`) that is a preventable
-/// billing state OpenHuman has no lever over, yet `tracing::error!` maps to
-/// `EventFilter::Event` in `core::logging::sentry_tracing_layer` — so every
-/// tick of every out-of-credits user paged Sentry (TAURI-RUST-HMW: 8314 events
-/// / 13 users, #5308). The existing `is_budget_event` `before_send` net cannot
-/// catch it: that filter is tag-gated (`failure=non_2xx` + `status=400`) and
-/// keys on the event *message*, but this event's message is the static
-/// `"context_scout run failed"` with the wire body only in a breadcrumb.
-///
-/// So demote at the emit site: `warn!` maps to `EventFilter::Breadcrumb`, which
-/// keeps the local log line (and the Sentry breadcrumb trail for any *real*
-/// error that follows) without raising an issue. Every other cause still
-/// `error!`s and keeps paging.
-pub(super) fn log_scout_failure(error_kind: &str, message: &str) {
- if is_expected_billing_failure(message) {
- // Metadata-only — never log the raw provider body (see CLAUDE.md).
- tracing::warn!(
- target: "agent_prepare_context",
- error_kind = %error_kind,
- "[agent_prepare_context] context_scout run skipped — account is out of credits (expected user-state, not reported)"
- );
- return;
- }
- tracing::error!(
- target: "agent_prepare_context",
- error_kind = %error_kind,
- "[agent_prepare_context] context_scout run failed"
- );
-}
-
-pub(super) async fn run_context_scout_with_catalog_and_workspace(
- question: &str,
- focus: Option<&str>,
- tool_catalog: &str,
- parent_workspace_descriptor: Option<WorkspaceDescriptor>,
- thread_id: Option<String>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- live_parent: Option<
- &tinyagents_harness::context::RunContext<
- crate::agent::tinyagents::host::OpenHumanRunContext,
- >,
- >,
- parent_call_id: Option<String>,
-) -> anyhow::Result<ToolResult> {
- let question = question.trim().to_string();
- let focus = focus.map(|s| s.to_string());
-
- tracing::info!(
- target: "agent_prepare_context",
- question_chars = question.chars().count(),
- has_focus = focus.as_deref().map(|f| !f.trim().is_empty()).unwrap_or(false),
- "[agent_prepare_context] invoked"
- );
-
- if question.is_empty() {
- return Ok(ToolResult::error(
- "agent_prepare_context: `question` is required",
- ));
- }
-
- let Some(live_parent) = live_parent else {
- return Ok(ToolResult::error(
- "agent_prepare_context requires a live harness run context.",
- ));
- };
- let parent = run_context.parent.clone();
-
- let registry = match AgentDefinitionRegistry::global() {
- Some(reg) => reg,
- None => {
- return Ok(ToolResult::error(
- "agent_prepare_context: AgentDefinitionRegistry has not been initialised.",
- ));
- }
- };
- let definition = match registry.get(SCOUT_AGENT_ID) {
- Some(def) => def,
- None => {
- return Ok(ToolResult::error(format!(
- "agent_prepare_context: built-in agent `{SCOUT_AGENT_ID}` is not registered.",
- )));
- }
- };
-
- let catalog_tool_count = tool_catalog.lines().filter(|l| !l.is_empty()).count();
- let scout_prompt =
- AgentPrepareContextTool::build_scout_prompt(&question, focus.as_deref(), tool_catalog);
-
- tracing::debug!(
- target: "agent_prepare_context",
- catalog_tool_count,
- scout_prompt_chars = scout_prompt.chars().count(),
- "[agent_prepare_context] spawning context_scout (blocking)"
- );
-
- let task_id = format!("ctx-{}", uuid::Uuid::new_v4());
- let parent_session = parent
- .as_ref()
- .map(|p| p.session_id.clone())
- .unwrap_or_else(|| "standalone".into());
- let progress_sink = run_context.progress.clone();
-
- // Surface the scout as a live subagent row in the parent thread. The
- // child's own iterations/tool-calls already stream to this sink from
- // inside run_subagent; we bookend them with spawned/completed so the
- // UI opens and closes the card. Best-effort — a closed sink is fine.
- crate::agent::orchestration::subagent_events::publish_subagent_spawned(
- parent_session.clone(),
- definition.id.clone(),
- "typed".to_string(),
- task_id.clone(),
- scout_prompt.chars().count(),
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentSpawned {
- agent_id: definition.id.clone(),
- task_id: task_id.clone(),
- mode: "typed".to_string(),
- dedicated_thread: false,
- prompt_chars: scout_prompt.chars().count(),
- prompt: scout_prompt.clone(),
- worker_thread_id: None,
- display_name: Some(definition.display_name().to_string()),
- parent_call_id: parent_call_id.clone(),
- })
- .await;
- }
-
- let worktree_action_dir = parent_workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone());
- if let Some(descriptor) = parent_workspace_descriptor.as_ref() {
- tracing::debug!(
- target: "agent_prepare_context",
- task_id = %task_id,
- workspace_root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[agent_prepare_context] using ToolExecutionContext workspace root"
- );
- }
- let options = SubagentRunOptions {
- task_id: Some(task_id.clone()),
- thread_id: thread_id.clone(),
- run_context,
- worktree_action_dir,
- workspace_descriptor: parent_workspace_descriptor,
- ..Default::default()
- };
-
- let run = run_subagent_with_parent(
- live_parent,
- definition.clone(),
- scout_prompt.clone(),
- options,
- )
- .await;
- match run {
- Ok(outcome) => {
- let emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();
- match &outcome.status {
- SubagentRunStatus::Completed => {
- // Guard the contract: the scout MUST return exactly one
- // `[context_bundle] … [/context_bundle]` envelope. We tolerate
- // surrounding prose by extracting just the envelope (the harness
- // prepends any non-error result to turn 1 as "Prepared context",
- // so we still inject only the bracketed envelope, never the
- // model's free-form text). Genuinely unusable output — absent,
- // unterminated, or duplicated — is rejected so the caller falls
- // back to the un-augmented message.
- let Some(bundle) = extract_context_bundle(&outcome.output) else {
- tracing::warn!(
- target: "agent_prepare_context",
- task_id = %outcome.task_id,
- output_chars = outcome.output.chars().count(),
- "[agent_prepare_context] scout returned a malformed/absent context_bundle — rejecting"
- );
- if emit_lifecycle_effects {
- crate::agent::orchestration::subagent_events::publish_subagent_completed(
- parent_session.clone(),
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- outcome.elapsed.as_millis() as u64,
- 0,
- outcome.iterations,
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentCompleted {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- iterations: outcome.iterations as u32,
- output_chars: 0,
- output: String::new(),
- // Not audited for whether this child's spend reached the
- // parent turn's ledger, so it stays silent: omission adds
- // nothing, which is the status quo. See the field's docs.
- usage: None,
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- })
- .await;
- }
- }
- return Ok(ToolResult::error(
- "agent_prepare_context: context_scout did not return a well-formed \
- [context_bundle] envelope",
- ));
- };
- // From here on use the extracted `bundle`, not the raw
- // `outcome.output`, so any prose the scout wrapped around the
- // envelope never reaches the parent's context.
- tracing::info!(
- target: "agent_prepare_context",
- task_id = %outcome.task_id,
- elapsed_ms = outcome.elapsed.as_millis() as u64,
- iterations = outcome.iterations,
- output_chars = bundle.chars().count(),
- raw_output_chars = outcome.output.chars().count(),
- "[agent_prepare_context] context bundle ready"
- );
- if emit_lifecycle_effects {
- crate::agent::orchestration::subagent_events::publish_subagent_completed(
- parent_session.clone(),
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- outcome.elapsed.as_millis() as u64,
- bundle.chars().count(),
- outcome.iterations,
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentCompleted {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- iterations: outcome.iterations as u32,
- output_chars: bundle.chars().count(),
- output: bundle.clone(),
- // Not audited for whether this child's spend reached the
- // parent turn's ledger, so it stays silent: omission adds
- // nothing, which is the status quo. See the field's docs.
- usage: None,
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- })
- .await;
- }
- }
-
- // Bootstrap this thread's goal from the scout's proposal — but
- // ONLY when the thread has none yet. The orchestrator stays
- // authoritative (it sets/replaces via `goal_set`); the
- // context-gathering path just seeds a goal on the first scout of
- // a fresh chat so the harness has something to steer toward.
- // Best-effort — never fails the call.
- if let (Some(parent), Some(thread_id)) = (parent.as_ref(), thread_id) {
- if let Some(objective) =
- AgentPrepareContextTool::parse_proposed_goal(&bundle)
- {
- match crate::agent::goals::store::set_if_absent(
- &parent.workspace_dir,
- &thread_id,
- &objective,
- None,
- )
- .await
- {
- Ok(Some(goal)) => {
- tracing::info!(
- target: "agent_prepare_context",
- thread_id = %thread_id,
- goal_id = %goal.goal_id,
- "[agent_prepare_context] bootstrapped thread goal from scout proposal"
- );
- BUS.publish(DomainEvent::ThreadGoalUpdated {
- thread_id: goal.thread_id.clone(),
- goal_id: goal.goal_id.clone(),
- status: goal.status.as_str().to_string(),
- goal: Some(crate::agent::goals::goal_to_value(&goal)),
- });
- }
- Ok(None) => {
- tracing::debug!(
- target: "agent_prepare_context",
- thread_id = %thread_id,
- "[agent_prepare_context] thread already has a goal — scout proposal not applied"
- );
- }
- Err(e) => {
- tracing::debug!(
- target: "agent_prepare_context",
- error = %e,
- "[agent_prepare_context] failed to persist scout-proposed goal"
- );
- }
- }
- }
- }
-
- Ok(ToolResult::success(bundle))
- }
- // The scout normally has no `ask_user_clarification` tool, but
- // a dynamically admitted tool must still preserve the durable
- // pause contract rather than pretending this lifecycle ended.
- SubagentRunStatus::AwaitingUser {
- question,
- checkpoint,
- ..
- } => {
- tracing::warn!(
- target: "agent_prepare_context",
- task_id = %outcome.task_id,
- "[agent_prepare_context] scout unexpectedly awaited user input"
- );
- if emit_lifecycle_effects {
- crate::agent::orchestration::subagent_events::publish_subagent_awaiting_user(
- parent_session.clone(),
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- question.clone(),
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentAwaitingUser {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- question: question.clone(),
- worker_thread_id: None,
- checkpoint_path: checkpoint
- .as_ref()
- .map(|path| path.to_string_lossy().to_string()),
- })
- .await;
- }
- }
- Ok(ToolResult::success(
- crate::agent::orchestration::tools::awaiting_user::awaiting_user_envelope(
- &outcome.task_id,
- &outcome.agent_id,
- None,
- question,
- checkpoint.is_some(),
- ),
- ))
- }
- SubagentRunStatus::Incomplete { reason } => {
- // The scout stopped short (stuck halt / iteration cap) without a
- // well-formed bundle. Don't inject partial context — return a
- // has_enough_context:false bundle and close the lifecycle.
- tracing::warn!(
- target: "agent_prepare_context",
- task_id = %outcome.task_id,
- reason = %reason,
- "[agent_prepare_context] scout stopped incomplete — returning empty bundle"
- );
- if emit_lifecycle_effects {
- crate::agent::orchestration::subagent_events::publish_subagent_completed(
- parent_session.clone(),
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- outcome.elapsed.as_millis() as u64,
- 0,
- outcome.iterations,
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentCompleted {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- iterations: outcome.iterations as u32,
- output_chars: 0,
- output: String::new(),
- // Not audited for whether this child's spend reached the
- // parent turn's ledger, so it stays silent: omission adds
- // nothing, which is the status quo. See the field's docs.
- usage: None,
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- })
- .await;
- }
- }
- Ok(ToolResult::success(format!(
- "[context_bundle]\nhas_enough_context: false\n\
- summary: The context scout stopped before finishing ({reason}).\n\
- recommended_tool_calls:\n[/context_bundle]"
- )))
- }
- SubagentRunStatus::Cancelled => {
- tracing::info!(
- target: "agent_prepare_context",
- task_id = %outcome.task_id,
- "[agent_prepare_context] scout cancelled"
- );
- if emit_lifecycle_effects {
- let message = "context scout was cancelled".to_string();
- crate::agent::orchestration::subagent_events::publish_subagent_failed(
- parent_session.clone(),
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- message.clone(),
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentFailed {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- error: message,
- })
- .await;
- }
- }
- Ok(ToolResult::error(
- "agent_prepare_context: context scout was cancelled",
- ))
- }
- }
- }
- Err(err) => {
- let message = err.to_string();
- let error_kind = message
- .split(':')
- .next()
- .map(str::trim)
- .unwrap_or("unknown");
- log_scout_failure(error_kind, &scout_failure_signal(&err));
- crate::agent::orchestration::subagent_events::publish_subagent_failed(
- parent_session.clone(),
- task_id.clone(),
- definition.id.clone(),
- message.clone(),
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentFailed {
- agent_id: definition.id.clone(),
- task_id: task_id.clone(),
- error: message.clone(),
- })
- .await;
- }
- Ok(ToolResult::error(format!(
- "agent_prepare_context failed: {message}"
- )))
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs
deleted file mode 100644
index 5f12633034..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs
+++ /dev/null
@@ -1,312 +0,0 @@
-//! The `agent_prepare_context` [`Tool`] wrapper: schema, permission level,
-//! and the parent tool-catalogue / scout-prompt / proposed-goal rendering
-//! the scout engine (see [`super::scout_run`]) is built from.
-
-use std::fmt::Write as _;
-use std::sync::Arc;
-
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use async_trait::async_trait;
-use serde_json::json;
-use tinyagents_harness::context::RunContext;
-use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
-use tinytools::ToolRunContext;
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
-
-use super::scout_run::{
- already_prepared_context_bundle, run_context_scout_with_catalog_and_workspace,
-};
-
-/// Spawns the `context_scout` sub-agent to collect context and propose a plan.
-pub struct AgentPrepareContextTool;
-
-pub(crate) struct AgentPrepareContextDispatch {
- tool: Arc<dyn Tool>,
-}
-impl AgentPrepareContextDispatch {
- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
- Self { tool }
- }
-}
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for AgentPrepareContextDispatch
-{
- fn tool(&self) -> Arc<dyn Tool> {
- self.tool.clone()
- }
- async fn execute(
- &self,
- _state: &(),
- _call_id: tinyagents_harness::CallId,
- arguments: serde_json::Value,
- _options: ToolCallOptions,
- parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let context = ToolExecutionContext::from_run_context(parent, _call_id.clone());
- AgentPrepareContextTool::new()
- .execute_with_live_parent_context(
- arguments,
- Some(&context),
- parent.data.child(),
- Some(parent),
- )
- .await
- }
-}
-
-impl Default for AgentPrepareContextTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl AgentPrepareContextTool {
- pub fn new() -> Self {
- Self
- }
-
- /// Render the parent agent's tool catalogue into a compact
- /// `- name: description` list the scout can recommend *back* to the
- /// parent. Excludes this tool itself (recommending another scout pass
- /// would be circular). Returns an empty string when there's no parent
- /// context (e.g. a direct CLI/RPC tool call outside an agent turn) — the
- /// subsequent `run_subagent` call surfaces the no-parent error.
- ///
- /// Restricted to the parent's **visible** tool set (what it actually
- /// advertises and will execute this turn), not the full registry —
- /// otherwise the scout could recommend hidden direct-exec/spawn tools
- /// the parent can't call, which the runtime would reject or which would
- /// bypass specialist routing. Read from `visible_tool_specs`, the parent's
- /// own advertised list, because `all_tool_specs` describes what a *child*
- /// may inherit and deliberately carries none of the parent's synthesised
- /// `delegate_*` tools — the very tools the scout most often recommends.
- /// Falls back to that registry, name-filtered, when a context does not
- /// carry the visible list, to preserve behaviour for builders that don't
- /// populate it.
- pub(super) fn render_parent_tool_catalog(parent: Option<&ParentExecutionContext>) -> String {
- let Some(parent) = parent else {
- return String::new();
- };
- let visible = &parent.visible_tool_names;
- let specs: &[std::sync::Arc<tinytools::ToolSpec>] = if parent.visible_tool_specs.is_empty()
- {
- &parent.all_tool_specs
- } else {
- &parent.visible_tool_specs
- };
- let mut out = String::with_capacity(2048);
- for spec in specs.iter() {
- if spec.name == "agent_prepare_context" {
- continue;
- }
- if !visible.is_empty() && !visible.contains(&spec.name) {
- continue;
- }
- // One line per tool; trim the description to keep the catalogue
- // from dwarfing the scout's own prompt.
- let desc: String = spec
- .description
- .split_whitespace()
- .collect::<Vec<_>>()
- .join(" ");
- let desc = if desc.chars().count() > 160 {
- let cut = desc
- .char_indices()
- .nth(160)
- .map(|(i, _)| i)
- .unwrap_or(desc.len());
- format!("{}…", &desc[..cut])
- } else {
- desc
- };
- let _ = writeln!(out, "- {}: {}", spec.name, desc);
- }
- out
- }
-
- /// Build the scout's task prompt: the request, optional focus, and the
- /// parent tool catalogue the scout draws its recommendations from.
- pub(super) fn build_scout_prompt(
- question: &str,
- focus: Option<&str>,
- tool_catalog: &str,
- ) -> String {
- let mut prompt = String::with_capacity(question.len() + tool_catalog.len() + 512);
- let _ = writeln!(prompt, "[Request]\n{question}\n");
- if let Some(focus) = focus.filter(|f| !f.trim().is_empty()) {
- let _ = writeln!(prompt, "[Focus]\n{}\n", focus.trim());
- }
- if tool_catalog.trim().is_empty() {
- prompt.push_str(
- "[Orchestrator tools]\n(none available — return an empty \
- recommended_tool_calls list)\n",
- );
- } else {
- let _ = writeln!(
- prompt,
- "[Orchestrator tools]\nThese are the tools the orchestrator can call next. \
- Every `recommended_tool_calls[].tool` MUST be one of these exact names:\n{tool_catalog}"
- );
- }
- prompt.push_str(
- "\nGather what you need, then emit the single [context_bundle] … \
- [/context_bundle] block as specified. Do not answer the request yourself.",
- );
- prompt
- }
-
- /// Extract the scout's `proposed_goal:` line from a `[context_bundle]`, if
- /// present and meaningful. Returns `None` for a missing line or an explicit
- /// `none`. The prefix is matched case-insensitively; its byte length is
- /// fixed (no multibyte), so slicing past it is safe.
- pub(super) fn parse_proposed_goal(bundle: &str) -> Option<String> {
- const PREFIX: &str = "proposed_goal:";
- // Boundary-safe prefix match: `get(..len)` returns None rather than
- // panicking when the line begins with a multibyte char before byte 14.
- let line = bundle.lines().map(str::trim).find(|l| {
- l.get(..PREFIX.len())
- .is_some_and(|p| p.eq_ignore_ascii_case(PREFIX))
- })?;
- let value = line[PREFIX.len()..].trim();
- if value.is_empty() || value.eq_ignore_ascii_case("none") {
- return None;
- }
- Some(value.to_string())
- }
-}
-
-#[async_trait]
-impl Tool for AgentPrepareContextTool {
- fn name(&self) -> &str {
- "agent_prepare_context"
- }
-
- fn description(&self) -> &str {
- "Before answering or delegating, scout existing context. Runs a fast \
- read-only context-collector that checks memory, past conversations \
- (transcripts), your goals/profile, installed/registry skills, connected \
- integrations, and the web, then returns whether there's enough context \
- to answer, a compact context summary, an ordered list of recommended \
- next tool calls (parent tools, by exact name, with args), and any \
- skills worth running. Use only when a caller explicitly needs an \
- ad hoc scout pass. If the current prompt says agent context has \
- already been prepared, use the prepared context and do not call this \
- tool again."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "required": ["question"],
- "properties": {
- "question": {
- "type": "string",
- "description": "The user's request or goal to gather context for. Be specific — the scout has no memory of your conversation."
- },
- "focus": {
- "type": "string",
- "description": "Optional hint that narrows what to scout (e.g. a platform, time window, or sub-question)."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // ReadOnly, not Execute: this tool only ever runs the read-only
- // `context_scout` (read_only sandbox, no write/exec tools). Marking it
- // Execute would make `ToolPolicyEngine` strip it from any
- // provider-visible set on a `ReadOnly`-capped channel, which would hide
- // the scout from callers that still expose it explicitly.
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_context(args, ToolCallOptions::default(), None)
- .await
- }
-
- async fn execute_with_context(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- tool_context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- if let Some(live_parent) = super::super::ambient_parent_run_context("direct-context-scout")
- {
- let run_context = live_parent.data.child();
- return self
- .execute_with_live_parent_context(
- args,
- tool_context,
- run_context,
- Some(&live_parent),
- )
- .await;
- }
- self.execute_with_parent_context(
- args,
- tool_context,
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
- )
- .await
- }
-}
-
-impl AgentPrepareContextTool {
- pub(crate) async fn execute_with_parent_context(
- &self,
- args: serde_json::Value,
- tool_context: Option<&dyn ToolRunContext>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- ) -> anyhow::Result<ToolResult> {
- self.execute_with_live_parent_context(args, tool_context, run_context, None)
- .await
- }
-
- /// Typed-harness entrypoint that retains the actual parent run for the
- /// blocking scout child.
- pub(crate) async fn execute_with_live_parent_context(
- &self,
- args: serde_json::Value,
- tool_context: Option<&dyn ToolRunContext>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- live_parent: Option<&RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>>,
- ) -> anyhow::Result<ToolResult> {
- let ambient_prepared_sources =
- crate::agent::harness::current_agent_context_prepared_sources();
- let prepared_sources = if run_context.prepared_context_sources.is_empty() {
- ambient_prepared_sources.as_slice()
- } else {
- run_context.prepared_context_sources.as_ref()
- };
- if !prepared_sources.is_empty() {
- tracing::info!(
- target: "agent_prepare_context",
- sources = ?prepared_sources,
- "[agent_prepare_context] skipped because agent context is already prepared for this turn"
- );
- return Ok(ToolResult::success(already_prepared_context_bundle(
- prepared_sources,
- )));
- }
-
- let question = args.get("question").and_then(|v| v.as_str()).unwrap_or("");
- let focus = args.get("focus").and_then(|v| v.as_str());
- let tool_catalog =
- AgentPrepareContextTool::render_parent_tool_catalog(run_context.parent.as_ref());
- run_context_scout_with_catalog_and_workspace(
- question,
- focus,
- &tool_catalog,
- tool_context.and_then(|ctx| ctx.workspace().cloned()),
- tool_context
- .and_then(ToolRunContext::thread_id)
- .map(str::to_owned),
- run_context,
- live_parent,
- crate::tools::host_extensions::tool_call_id(tool_context),
- )
- .await
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context_tests.rs
deleted file mode 100644
index e3b77490f0..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context_tests.rs
+++ /dev/null
@@ -1,432 +0,0 @@
-use super::*;
-
-use crate::agent::harness::AgentContextPreparedSource;
-use crate::agent::subagent_host::SubagentRunError;
-use serde_json::json;
-use tinytools::Tool;
-#[test]
-fn schema_requires_question_and_makes_focus_optional() {
- let tool = AgentPrepareContextTool::new();
- let schema = tool.parameters_schema();
- let required = schema
- .get("required")
- .and_then(|v| v.as_array())
- .expect("schema has required array");
- assert!(required.iter().any(|v| v.as_str() == Some("question")));
- assert!(
- required.iter().all(|v| v.as_str() != Some("focus")),
- "focus must be optional"
- );
- let props = schema.get("properties").expect("schema has properties");
- assert!(props.get("question").is_some());
- assert!(props.get("focus").is_some());
-}
-
-#[test]
-fn description_skips_when_context_is_already_prepared() {
- let tool = AgentPrepareContextTool::new();
- let description = tool.description();
-
- assert!(description.contains("agent context has already been prepared"));
- assert!(description.contains("do not call this tool again"));
-}
-
-#[test]
-fn build_scout_prompt_includes_request_focus_and_catalog() {
- let prompt = AgentPrepareContextTool::build_scout_prompt(
- "summarise my unread gmail",
- Some("last 24h"),
- "- research: web and docs crawler\n",
- );
- assert!(prompt.contains("[Request]"));
- assert!(prompt.contains("summarise my unread gmail"));
- assert!(prompt.contains("[Focus]"));
- assert!(prompt.contains("last 24h"));
- assert!(prompt.contains("[Orchestrator tools]"));
- assert!(prompt.contains("research"));
- assert!(prompt.contains("[context_bundle]"));
-}
-
-#[test]
-fn build_scout_prompt_handles_empty_catalog() {
- let prompt = AgentPrepareContextTool::build_scout_prompt("do a thing", None, "");
- assert!(prompt.contains("(none available"));
- assert!(!prompt.contains("[Focus]"));
-}
-
-#[test]
-fn parse_proposed_goal_extracts_objective_or_none() {
- let bundle = "[context_bundle]\nhas_enough_context: true\n\
- proposed_goal: Ship the desktop release to all platforms\n\
- summary: ...\n[/context_bundle]";
- assert_eq!(
- AgentPrepareContextTool::parse_proposed_goal(bundle).as_deref(),
- Some("Ship the desktop release to all platforms")
- );
-
- // Explicit `none` → no goal.
- let none_bundle = "[context_bundle]\nproposed_goal: none\nsummary: x\n[/context_bundle]";
- assert!(AgentPrepareContextTool::parse_proposed_goal(none_bundle).is_none());
-
- // Missing line → no goal.
- let no_line = "[context_bundle]\nhas_enough_context: true\n[/context_bundle]";
- assert!(AgentPrepareContextTool::parse_proposed_goal(no_line).is_none());
-
- // Case-insensitive prefix.
- let cased = "Proposed_Goal: Land the migration ";
- assert_eq!(
- AgentPrepareContextTool::parse_proposed_goal(cased).as_deref(),
- Some("Land the migration")
- );
-
- // Lines starting with a multibyte char must not panic the byte-prefix
- // match (regression for the `l[..14]` non-boundary slice).
- let multibyte = "[context_bundle]\n日本語の要約 summary line\nproposed_goal: 目標を達成する\n[/context_bundle]";
- assert_eq!(
- AgentPrepareContextTool::parse_proposed_goal(multibyte).as_deref(),
- Some("目標を達成する")
- );
-}
-
-#[tokio::test]
-async fn missing_question_returns_error() {
- let tool = AgentPrepareContextTool::new();
- let result = tool.execute(json!({})).await.unwrap();
- assert!(result.is_error);
- assert!(result.output().contains("question"));
-}
-
-#[tokio::test]
-async fn execute_short_circuits_when_context_already_prepared() {
- let tool = AgentPrepareContextTool::new();
- let result = crate::agent::harness::with_agent_context_prepared_sources(
- vec![AgentContextPreparedSource {
- source: "memory agent context retrieval".to_string(),
- has_enough_context: Some(false),
- }],
- tool.execute(json!({"question": "prepare context again"})),
- )
- .await
- .unwrap();
-
- assert!(!result.is_error, "{}", result.output());
- assert!(result.output().contains("[context_bundle]"));
- assert!(result.output().contains("has_enough_context: false"));
- assert!(result.output().contains("already been prepared once"));
- assert!(result.output().contains("memory agent context retrieval"));
- assert!(result
- .output()
- .contains("does not assert that enough context is available"));
- assert!(result.output().contains("[/context_bundle]"));
-}
-
-#[tokio::test]
-async fn execute_preserves_prior_prepared_context_sufficiency_when_true() {
- let tool = AgentPrepareContextTool::new();
- let result = crate::agent::harness::with_agent_context_prepared_sources(
- vec![AgentContextPreparedSource {
- source: "memory agent context retrieval".to_string(),
- has_enough_context: Some(true),
- }],
- tool.execute(json!({"question": "prepare context again"})),
- )
- .await
- .unwrap();
-
- assert!(!result.is_error, "{}", result.output());
- assert!(result.output().contains("has_enough_context: true"));
- assert!(result.output().contains("reported enough context"));
-}
-
-#[test]
-fn extracts_a_single_well_formed_bundle() {
- let out = "[context_bundle]\nhas_enough_context: true\nsummary: ok\n[/context_bundle]";
- assert_eq!(extract_context_bundle(out).as_deref(), Some(out));
-}
-
-#[test]
-fn rejects_free_form_prose_without_a_bundle() {
- assert_eq!(
- extract_context_bundle("Sure! Here's what I found about your request..."),
- None
- );
-}
-
-#[test]
-fn rejects_unterminated_or_reversed_envelope() {
- // Open tag with no close.
- assert_eq!(
- extract_context_bundle("[context_bundle]\nsummary: ..."),
- None
- );
- // Close before open — out of order.
- assert_eq!(
- extract_context_bundle("[/context_bundle] stray [context_bundle]"),
- None
- );
-}
-
-#[test]
-fn rejects_duplicated_envelope() {
- // Two envelopes — we can't tell which is authoritative, so reject.
- assert_eq!(
- extract_context_bundle(
- "[context_bundle]a[/context_bundle][context_bundle]b[/context_bundle]"
- ),
- None
- );
-}
-
-#[test]
-fn extracts_envelope_from_surrounding_prose() {
- // Regression for the "scout runs, bundle missing" bug: a fast chat-tier
- // scout wraps the envelope in a preamble and/or a closing line. We must
- // extract just the envelope, not drop it and not inject the prose.
- let leading = "Sure, here's what I found:\n[context_bundle]\nsummary: x\n[/context_bundle]";
- assert_eq!(
- extract_context_bundle(leading).as_deref(),
- Some("[context_bundle]\nsummary: x\n[/context_bundle]")
- );
- let trailing = "[context_bundle]\nsummary: x\n[/context_bundle]\nHope that helps!";
- assert_eq!(
- extract_context_bundle(trailing).as_deref(),
- Some("[context_bundle]\nsummary: x\n[/context_bundle]")
- );
- let both = "Here you go:\n[context_bundle]\nsummary: x\n[/context_bundle]\n\nLet me know!";
- assert_eq!(
- extract_context_bundle(both).as_deref(),
- Some("[context_bundle]\nsummary: x\n[/context_bundle]")
- );
-}
-
-#[test]
-fn extracts_envelope_with_surrounding_whitespace() {
- // Leading/trailing whitespace is trimmed, not treated as prose.
- assert_eq!(
- extract_context_bundle("\n [context_bundle]\nsummary: x\n[/context_bundle]\n ")
- .as_deref(),
- Some("[context_bundle]\nsummary: x\n[/context_bundle]")
- );
-}
-
-// ── Credits-exhausted scout failures stay off Sentry (#5308) ────────
-
-/// Verbatim wire body from Sentry TAURI-RUST-HMW's breadcrumb — the
-/// managed backend's budget-exhausted 400. Pinning the exact string makes a
-/// backend phrasing drift fail CI rather than silently re-flood Sentry.
-const CREDITS_400_BODY: &str = "OpenHuman returned HTTP 400: \
- {\"success\":false,\"error\":\"Insufficient budget\",\
- \"errorCode\":\"USER_INSUFFICIENT_CREDITS\"}";
-
-#[test]
-fn classifies_managed_credits_400_and_byo_402_as_expected_billing() {
- assert!(
- is_expected_billing_failure(CREDITS_400_BODY),
- "the managed USER_INSUFFICIENT_CREDITS 400 is user-state, not a defect"
- );
- // The BYO sibling: a provider 402 whose body names the credit shortfall.
- assert!(is_expected_billing_failure(
- "openrouter API error (402 Payment Required): {\"error\":\"Insufficient credits\"}"
- ));
-}
-
-#[test]
-fn real_scout_failures_are_not_classified_as_billing() {
- for message in [
- "provider call failed: connection reset by peer",
- "agent definition 'context_scout' not found in registry",
- "sub-agent exceeded maximum iterations (8)",
- "OpenHuman returned HTTP 400: {\"error\":\"model not found\"}",
- // A healthy-balance readout must not be swallowed.
- "You have 100 remaining credits this month",
- "",
- ] {
- assert!(
- !is_expected_billing_failure(message),
- "{message:?} must keep paging Sentry"
- );
- }
-}
-
-#[test]
-fn scout_failure_signal_flattens_the_provider_cause_chain() {
- // The wire body arrives as a *cause* under the runner's own context, so
- // `to_string()` alone loses it — the classifier would then miss the very
- // failure the demotion exists for.
- let inner = anyhow::Error::msg(CREDITS_400_BODY).context("chat completion failed");
- let err = SubagentRunError::Provider(inner);
-
- assert!(
- !err.to_string().contains("USER_INSUFFICIENT_CREDITS"),
- "precondition: the flat Display drops the cause carrying the wire body"
- );
- let signal = scout_failure_signal(&err);
- assert!(signal.contains("USER_INSUFFICIENT_CREDITS"));
- assert!(is_expected_billing_failure(&signal));
-
- // Non-`Provider` variants are already flat thiserror messages.
- assert_eq!(
- scout_failure_signal(&SubagentRunError::MaxIterationsExceeded(8)),
- "sub-agent exceeded maximum iterations (8)"
- );
-}
-
-/// The regression this issue is about: a background `context_scout` run that
-/// fails on exhausted credits must NOT become a Sentry error event, while
-/// every other failure still does.
-///
-/// Asserted end-to-end through the real `sentry-tracing` bridge (mirroring
-/// `core::logging::sentry_tracing_layer`'s level mapping) rather than by
-/// inspecting the log level, because the level→event mapping *is* the
-/// mechanism: `ERROR` → `EventFilter::Event`, `WARN` → `Breadcrumb`.
-#[cfg(feature = "crash-reporting")]
-#[test]
-fn credits_exhausted_scout_failure_does_not_reach_sentry() {
- use sentry::test::TestTransport;
- use std::sync::Arc;
- use tracing::Level;
- use tracing_subscriber::layer::SubscriberExt;
-
- let transport = TestTransport::new();
- let options = sentry::ClientOptions {
- dsn: Some("https://[email protected]/1".parse().unwrap()),
- transport: Some(Arc::new(transport.clone())),
- ..Default::default()
- };
- let hub = Arc::new(sentry::Hub::new(
- Some(Arc::new(options.into())),
- Arc::new(Default::default()),
- ));
- let _hub_guard = sentry::HubSwitchGuard::new(hub);
-
- let subscriber = tracing_subscriber::registry().with(
- sentry::integrations::tracing::layer().event_filter(|metadata| match *metadata.level() {
- Level::ERROR => sentry::integrations::tracing::EventFilter::Event,
- Level::WARN | Level::INFO => sentry::integrations::tracing::EventFilter::Breadcrumb,
- _ => sentry::integrations::tracing::EventFilter::Ignore,
- }),
- );
- let _subscriber_guard = tracing::subscriber::set_default(subscriber);
-
- super::scout_run::log_scout_failure("provider call failed", CREDITS_400_BODY);
- assert!(
- transport.fetch_and_clear_events().is_empty(),
- "an out-of-credits background scout must not page Sentry (TAURI-RUST-HMW)"
- );
-
- super::scout_run::log_scout_failure("provider call failed", "connection reset by peer");
- let events = transport.fetch_and_clear_events();
- assert_eq!(
- events.len(),
- 1,
- "a genuine scout failure must still reach Sentry"
- );
- assert_eq!(events[0].level, sentry::Level::Error);
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// Parent tool catalogue: rendered from the parent's own advertised surface
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// A spec with the given name and description; the schema is irrelevant here.
-fn catalog_spec(name: &str, description: &str) -> std::sync::Arc<tinytools::ToolSpec> {
- std::sync::Arc::new(tinytools::ToolSpec {
- name: name.to_string(),
- description: description.to_string(),
- parameters: serde_json::json!({"type": "object"}),
- })
-}
-
-/// A parent context whose inheritable registry (`all_tool_specs`) and own
-/// advertised surface (`visible_tool_specs`) are chosen by the caller.
-/// `visible_tool_names` is derived from the visible specs, as the turn
-/// builder derives it.
-fn parent_context_with_specs(
- all_tool_specs: Vec<std::sync::Arc<tinytools::ToolSpec>>,
- visible_tool_specs: Vec<std::sync::Arc<tinytools::ToolSpec>>,
-) -> crate::agent::harness::fork_context::ParentExecutionContext {
- use std::sync::Arc;
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_dir = workspace.path().to_path_buf();
- std::mem::forget(workspace);
- // The context needs *a* memory to be constructed with and never reads one
- // back, which is exactly what `noop_memory` is for.
- let memory: Arc<dyn crate::memory::Memory> = crate::memory::test_support::noop_memory();
- let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
- Arc::new(tinyagents_harness::testkit::ScriptedModel::new(Vec::new()));
- crate::agent::harness::fork_context::ParentExecutionContext {
- workspace_descriptor: None,
- agent_definition_id: "orchestrator".into(),
- allowed_subagent_ids: std::collections::HashSet::new(),
- turn_model_source: crate::agent::tinyagents::TurnModelSource::from_model(model),
- all_tools: Arc::new(Vec::new()),
- all_tool_specs: Arc::new(all_tool_specs),
- visible_tool_names: visible_tool_specs
- .iter()
- .map(|spec| spec.name.clone())
- .collect(),
- visible_tool_specs: Arc::new(visible_tool_specs),
- subagent_tool_ceiling_names: std::collections::HashSet::new(),
- model_name: "test-model".into(),
- temperature: 0.0,
- workspace_dir,
- memory,
- agent_config: crate::config::AgentConfig::default(),
- workflows: Arc::new(Vec::new()),
- memory_context: Arc::new(None),
- session_id: "parent-session".into(),
- channel: "test".into(),
- connected_integrations: Vec::new(),
- tool_call_format: crate::agent::prompts::ToolCallFormat::Native,
- session_key: "parent-key".into(),
- session_parent_prefix: None,
- on_progress: None,
- run_queue: None,
- }
-}
-
-/// The catalogue describes the parent's own advertised surface, which includes
-/// its synthesised `delegate_*` tools — not `all_tool_specs`, which is what a
-/// child may inherit and deliberately carries no delegate (#4452). The scout
-/// exists to recommend exactly those delegates back to the parent.
-#[tokio::test]
-async fn catalog_lists_the_parents_synthesised_delegates_from_its_visible_specs() {
- let ctx = parent_context_with_specs(
- vec![
- catalog_spec("echo", "durable"),
- catalog_spec("agent_prepare_context", "this tool"),
- ],
- vec![
- catalog_spec("echo", "durable"),
- catalog_spec("research", "web and docs crawler"),
- catalog_spec("agent_prepare_context", "this tool"),
- ],
- );
- let catalog = AgentPrepareContextTool::render_parent_tool_catalog(Some(&ctx));
- assert!(
- catalog.contains("- research: web and docs crawler\n"),
- "the parent's delegate must be recommendable: {catalog:?}"
- );
- assert!(catalog.contains("- echo: durable\n"));
- assert!(
- !catalog.contains("agent_prepare_context"),
- "the scout must not recommend another scout pass"
- );
-}
-
-/// A context without a visible spec list (background builders, older
-/// callers) keeps the previous behaviour: the inheritable registry, filtered
-/// by the visible names.
-#[tokio::test]
-async fn catalog_falls_back_to_all_tool_specs_when_visible_specs_are_absent() {
- let mut ctx = parent_context_with_specs(
- vec![
- catalog_spec("echo", "durable"),
- catalog_spec("hidden", "not advertised"),
- ],
- Vec::new(),
- );
- ctx.visible_tool_names = std::iter::once("echo".to_string()).collect();
- let catalog = AgentPrepareContextTool::render_parent_tool_catalog(Some(&ctx));
- assert_eq!(catalog, "- echo: durable\n");
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
index 997e955ebf..b95968c885 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
@@ -13,7 +13,7 @@ use tinyagents_registry::{
};
use crate::agent::orchestration::tools::{
- AgentPrepareContextDispatch, CloseSubagentDispatch, ContinueSubagentDispatch,
+ CloseSubagentDispatch, ContinueSubagentDispatch,
DelegateGraphDispatch, DelegationDispatch, ListSubagentsDispatch, SpawnAsyncSubagentDispatch,
SpawnParallelAgentsDispatch, SpawnSubagentDispatch, SpawnWorkerThreadDispatch,
SteerSubagentDispatch, WaitSubagentDispatch,
@@ -54,7 +54,6 @@ pub(crate) fn typed_dispatch_for(
"steer_subagent" => Arc::new(SteerSubagentDispatch::new(adapter)),
"close_subagent" => Arc::new(CloseSubagentDispatch::new(adapter)),
"list_subagents" => Arc::new(ListSubagentsDispatch::new(adapter)),
- "agent_prepare_context" => Arc::new(AgentPrepareContextDispatch::new(adapter)),
"delegate_graph" => Arc::new(DelegateGraphDispatch::new(adapter)),
"delegate" => Arc::new(DelegateToolDispatch::new(adapter)),
"todo" => Arc::new(TodoToolDispatch::new(adapter)),
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs b/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs
index 762a9ae22f..176145f44e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs
@@ -301,6 +301,5 @@ pub(crate) fn effective_max_iterations(max_iterations: usize) -> usize {
pub(crate) fn is_subagent_spawn_or_delegate_tool(name: &str) -> bool {
name == "spawn_subagent"
|| name.starts_with("delegate_")
- || name == "agent_prepare_context"
|| name == "spawn_worker_thread"
}
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index 65dd2c56c9..2e075eac99 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -190,11 +190,6 @@ pub fn all_tools_with_runtime(
// tree) rooted at the agent action dir. Named by the orchestrator and
// planner scopes.
Box::new(WorkspaceStateTool::new(action_dir.to_path_buf())),
- // "Plan mode as a subagent": runs the read-only `context_scout`
- // inline and returns a bounded context bundle + recommended next
- // tool calls. Visible only to agents that allowlist it
- // (orchestrator / planner).
- Box::new(AgentPrepareContextTool::new()),
// Steer/list/close reusable async sub-agents and collect results by
// durable `subagent_session_id` (preferred) or transient `task_id`.
Box::new(ListSubagentsTool::new()),
@@ -1232,7 +1227,6 @@ fn tool_group(name: &str) -> crate::core::all::DomainGroup {
|| matches!(
name,
"ask_user_clarification"
- | "agent_prepare_context"
| "delegate"
| "delegate_graph"
| "delegate_to_personality"
diff --git a/scripts/debug/agent-prepare-context-audit.mjs b/scripts/debug/agent-prepare-context-audit.mjs
deleted file mode 100644
index c8ee0ecb44..0000000000
--- a/scripts/debug/agent-prepare-context-audit.mjs
+++ /dev/null
@@ -1,992 +0,0 @@
-#!/usr/bin/env node
-// Live audit for harness-driven prepared context + the `context_scout` subagent.
-//
-// Drives real first-turn orchestrator sessions through JSON-RPC against an
-// authenticated core, then reads the resulting session transcripts to surface —
-// per query — the harness-collected [context_bundle]
-// (including the new `recommended_skills` block), the scout's step-by-step turns
-// ("thoughts"), which curated gathering tools it exercised, and tokens/cost.
-//
-// To prove the enrichment end-to-end on a live session, it also seeds a PRIOR
-// chat thread with a distinctive canary fact and adds a "transcript/recall"
-// case: the scout must call `transcript_search`, find that earlier message, and
-// echo the canary into its bundle. Pass --no-seed-transcript to skip seeding.
-//
-// Unlike harness-cache-audit.mjs (which deliberately hides bodies), this script
-// PRINTS bundle + thought content so you can iterate on the context_scout
-// prompt. Run it against a core built from this branch (so the tools exist) and
-// signed into your account (so the LLM calls bill to you).
-import { spawn } from "node:child_process";
-import { randomBytes } from "node:crypto";
-import { once } from "node:events";
-import { statSync } from "node:fs";
-import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
-import { createServer } from "node:net";
-import { homedir } from "node:os";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-const DEFAULT_RPC_URL = "http://127.0.0.1:7788/rpc";
-const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
-const SCOUT_AGENT = "context_scout";
-
-// Default audit queries, each aimed at a different context source.
-const DEFAULT_CASES = [
- {
- name: "memory/projects",
- query:
- "What do you know about my current projects and what should I work on next?",
- },
- {
- name: "goals/profile",
- query: "Based on my stated goals, what should I prioritise this week?",
- },
- {
- name: "web/fresh-fact",
- query:
- "What is the latest stable Rust release and one notable change in it?",
- },
- {
- name: "integrations/email",
- query: "Summarise my most important unread emails from the last day.",
- },
- {
- name: "mixed/plan",
- query:
- "Plan my day: combine my goals, recent activity, and anything time-sensitive.",
- },
-];
-
-function usage() {
- return `Usage: node scripts/debug/agent-prepare-context-audit.mjs [options]
-
-Audits harness-driven prepared context live: starts a fresh thread per query, then prints the
-returned context bundle, the scout's turns, and tokens/cache/cost.
-
-Options:
- --core-url <url> JSON-RPC endpoint (default: OPENHUMAN_CORE_RPC_URL or ${DEFAULT_RPC_URL})
- --token <token> RPC bearer (default: OPENHUMAN_CORE_TOKEN or <workspace>/core.token)
- --workspace <path> Workspace whose session_raw transcripts are read
- --model <model> Optional model_override passed to openhuman.inference_agent_chat
- --query <text> Add a custom query (repeatable). Replaces the defaults.
- --raw Deprecated no-op; queries are always sent directly so
- the harness scout sees the real case request.
- --scout-prompt-file <f> Override the context_scout system prompt with this file
- (writes a temporary workspace agent override; restored
- after the run unless --keep-workspace). Test your prompt.
- --thread-prefix <s> Thread id prefix to isolate transcripts (default: random)
- --no-seed-transcript Skip seeding a prior-chat thread (default: seed one with
- a canary fact so the scout has past chat to search)
- --max-print-chars <n> Truncate printed bundle/thought blocks (default: 4000)
- --rpc-timeout-ms <n> Per-RPC timeout (default: 600000)
- --spawn-core Start \`cargo run --bin openhuman-core\` for the audit
- --keep-workspace Keep any temp override files written for --scout-prompt-file
- --json Print a machine-readable JSON summary at the end
- --verbose Stream spawned core logs
- -h, --help Show this help
-
-Examples:
- node scripts/debug/agent-prepare-context-audit.mjs --spawn-core
- node scripts/debug/agent-prepare-context-audit.mjs --query "what are my goals?" --model claude-sonnet-4-6
- node scripts/debug/agent-prepare-context-audit.mjs --scout-prompt-file /tmp/my-scout.md
-`;
-}
-
-function parseArgs(argv) {
- const opts = {
- coreUrl: process.env.OPENHUMAN_CORE_RPC_URL || DEFAULT_RPC_URL,
- token: process.env.OPENHUMAN_CORE_TOKEN || "",
- workspace: process.env.OPENHUMAN_WORKSPACE || "",
- model: "",
- queries: [],
- raw: false,
- scoutPromptFile: "",
- threadPrefix: `apc-audit-${randomBytes(3).toString("hex")}`,
- seedTranscript: true,
- maxPrintChars: 4000,
- rpcTimeoutMs: 600_000,
- spawnCore: false,
- keepWorkspace: false,
- json: false,
- verbose: false,
- coreUrlExplicit: Boolean(process.env.OPENHUMAN_CORE_RPC_URL),
- workspaceExplicit: Boolean(process.env.OPENHUMAN_WORKSPACE),
- };
- for (let i = 0; i < argv.length; i += 1) {
- const arg = argv[i];
- const next = () => {
- const value = argv[++i];
- if (value === undefined) throw new Error(`missing value for ${arg}`);
- return value;
- };
- switch (arg) {
- case "--core-url":
- opts.coreUrl = next();
- opts.coreUrlExplicit = true;
- break;
- case "--token":
- opts.token = next();
- break;
- case "--workspace":
- opts.workspace = next();
- opts.workspaceExplicit = true;
- break;
- case "--model":
- opts.model = next();
- break;
- case "--query":
- opts.queries.push(next());
- break;
- case "--raw":
- opts.raw = true;
- break;
- case "--scout-prompt-file":
- opts.scoutPromptFile = next();
- break;
- case "--thread-prefix":
- opts.threadPrefix = next();
- break;
- case "--seed-transcript":
- opts.seedTranscript = true;
- break;
- case "--no-seed-transcript":
- opts.seedTranscript = false;
- break;
- case "--max-print-chars":
- opts.maxPrintChars = parsePositiveInt(next(), "--max-print-chars");
- break;
- case "--rpc-timeout-ms":
- opts.rpcTimeoutMs = parsePositiveInt(next(), "--rpc-timeout-ms");
- break;
- case "--spawn-core":
- opts.spawnCore = true;
- break;
- case "--keep-workspace":
- opts.keepWorkspace = true;
- break;
- case "--json":
- opts.json = true;
- break;
- case "--verbose":
- opts.verbose = true;
- break;
- case "-h":
- case "--help":
- console.log(usage());
- process.exit(0);
- default:
- throw new Error(`unknown option: ${arg}`);
- }
- }
- return opts;
-}
-
-function parsePositiveInt(raw, label) {
- const value = Number(raw);
- if (!Number.isInteger(value) || value < 1)
- throw new Error(`${label} must be a positive integer`);
- return value;
-}
-
-function defaultOpenhumanDir() {
- if (process.env.OPENHUMAN_APP_ENV === "staging") {
- return path.join(homedir(), ".openhuman-staging");
- }
- if (process.env.OPENHUMAN_APP_ENV) {
- return path.join(homedir(), ".openhuman");
- }
- // APP_ENV unset: the core (launched from a shell that may export
- // OPENHUMAN_APP_ENV=staging) and this script can disagree. Auto-pick the
- // dir whose active_user.toml was touched most recently so transcript reads
- // land in the same env the core actually uses. Falls back to prod.
- const prod = path.join(homedir(), ".openhuman");
- const staging = path.join(homedir(), ".openhuman-staging");
- const mtime = (p) => {
- try {
- return statSync(path.join(p, "active_user.toml")).mtimeMs;
- } catch {
- return -1;
- }
- };
- return mtime(staging) > mtime(prod) ? staging : prod;
-}
-
-async function defaultWorkspace() {
- if (process.env.OPENHUMAN_WORKSPACE) return process.env.OPENHUMAN_WORKSPACE;
- const openhumanDir = defaultOpenhumanDir();
- try {
- const active = await readFile(
- path.join(openhumanDir, "active_user.toml"),
- "utf8",
- );
- const match = active.match(/^\s*user_id\s*=\s*"([^"]+)"\s*$/m);
- if (match?.[1])
- return path.join(openhumanDir, "users", match[1], "workspace");
- } catch {
- // fall through to legacy root
- }
- return openhumanDir;
-}
-
-async function readToken(opts) {
- if (opts.token.trim()) return opts.token.trim();
- const tokenPath = path.join(
- opts.workspace || (await defaultWorkspace()),
- "core.token",
- );
- try {
- return (await readFile(tokenPath, "utf8")).trim();
- } catch {
- throw new Error(
- `RPC token not provided and ${tokenPath} could not be read. Pass --token or set OPENHUMAN_CORE_TOKEN.`,
- );
- }
-}
-
-async function rpc(coreUrl, token, method, params, timeoutMs = 600_000) {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
- let res;
- try {
- res = await fetch(coreUrl, {
- method: "POST",
- signal: controller.signal,
- headers: {
- "content-type": "application/json",
- authorization: `Bearer ${token}`,
- },
- body: JSON.stringify({
- jsonrpc: "2.0",
- id: `apc-${Date.now()}-${Math.random().toString(16).slice(2)}`,
- method,
- params,
- }),
- });
- } catch (err) {
- if (err?.name === "AbortError")
- throw new Error(`RPC ${method} timed out after ${timeoutMs}ms`);
- throw err;
- } finally {
- clearTimeout(timeout);
- }
- const bodyText = await res.text();
- let body;
- try {
- body = JSON.parse(bodyText);
- } catch {
- throw new Error(
- `RPC ${method} returned non-JSON HTTP ${res.status}: ${bodyText.slice(0, 200)}`,
- );
- }
- if (!res.ok) throw new Error(`RPC ${method} HTTP ${res.status}`);
- if (body.error)
- throw new Error(
- `RPC ${method} error: ${JSON.stringify(body.error).slice(0, 300)}`,
- );
- return body.result;
-}
-
-// ── Transcript reading ──────────────────────────────────────────────────────
-
-async function walkJsonl(dir) {
- const out = [];
- async function walk(current) {
- let entries;
- try {
- entries = await readdir(current, { withFileTypes: true });
- } catch {
- return;
- }
- await Promise.all(
- entries.map(async (entry) => {
- const full = path.join(current, entry.name);
- if (entry.isDirectory()) return walk(full);
- if (entry.isFile() && entry.name.endsWith(".jsonl")) out.push(full);
- }),
- );
- }
- await walk(dir);
- return out;
-}
-
-function num(value) {
- return Number.isFinite(Number(value)) ? Number(value) : 0;
-}
-
-async function readTranscript(file) {
- const data = await readFile(file, "utf8");
- const lines = data.split(/\r?\n/).filter((l) => l.trim());
- if (lines.length === 0) throw new Error("empty transcript");
- const meta = JSON.parse(lines[0])._meta || {};
- const messages = [];
- for (const line of lines.slice(1)) {
- try {
- const m = JSON.parse(line);
- if (typeof m.role === "string") messages.push(m);
- } catch {
- // skip malformed line
- }
- }
- return {
- file,
- agent: String(meta.agent || "(unknown)"),
- threadId: meta.thread_id || null,
- isSubagent: path.basename(file).includes("__"),
- input: num(meta.input_tokens),
- output: num(meta.output_tokens),
- cached: num(meta.cached_input_tokens),
- charged: num(meta.charged_amount_usd),
- messages,
- };
-}
-
-async function snapshot(workspace) {
- const files = await walkJsonl(path.join(workspace, "session_raw"));
- const map = new Map();
- await Promise.all(
- files.map(async (file) => {
- try {
- map.set(file, await readTranscript(file));
- } catch {
- // ignore partial writes
- }
- }),
- );
- return map;
-}
-
-// Transcripts created or grown since `before`, scoped to a thread id.
-function changedForThread(before, after, threadId) {
- const rows = [];
- for (const [file, cur] of after.entries()) {
- if (threadId && cur.threadId && cur.threadId !== threadId) continue;
- const prior = before.get(file);
- const grew =
- !prior ||
- cur.input !== prior.input ||
- cur.output !== prior.output ||
- cur.messages.length !== prior.messages.length;
- if (grew) rows.push(cur);
- }
- return rows;
-}
-
-// ── Bundle parsing ──────────────────────────────────────────────────────────
-
-function extractBundle(text) {
- if (typeof text !== "string") return null;
- const open = text.indexOf("[context_bundle]");
- if (open === -1) return null;
- const close = text.indexOf("[/context_bundle]", open);
- const inner = text
- .slice(open + "[context_bundle]".length, close === -1 ? undefined : close)
- .trim();
- const hasEnough =
- /has_enough_context\s*:\s*(true|false)/i.exec(inner)?.[1] ??
- "(unspecified)";
- // summary: everything between `summary:` and `recommended_tool_calls:`
- const sumMatch =
- /summary\s*:\s*([\s\S]*?)(?:\n\s*recommended_tool_calls\s*:|$)/i.exec(
- inner,
- );
- const summary = (sumMatch?.[1] || "").trim();
- // recommended_tool_calls: between its header and recommended_skills (or end).
- const recIdx = inner.search(/recommended_tool_calls\s*:/i);
- const skillsIdx = inner.search(/recommended_skills\s*:/i);
- const toolsEnd =
- skillsIdx > recIdx && skillsIdx !== -1 ? skillsIdx : undefined;
- const recBlock =
- recIdx === -1
- ? ""
- : inner.slice(recIdx, toolsEnd).replace(/^[^\n]*\n?/, "");
- const tools = [];
- for (const m of recBlock.matchAll(/(?:^|\n)\s*-?\s*tool\s*:\s*([^\n]+)/gi)) {
- tools.push(m[1].trim());
- }
- // recommended_skills: the new block — collect `skill:` names.
- const skillBlock =
- skillsIdx === -1 ? "" : inner.slice(skillsIdx).replace(/^[^\n]*\n?/, "");
- const skills = [];
- for (const m of skillBlock.matchAll(
- /(?:^|\n)\s*-?\s*skill\s*:\s*([^\n]+)/gi,
- )) {
- skills.push(m[1].trim());
- }
- return {
- raw: text.slice(
- open,
- close === -1 ? undefined : close + "[/context_bundle]".length,
- ),
- hasEnough,
- summary,
- tools,
- skills,
- full: inner,
- };
-}
-
-function clip(text, max) {
- if (typeof text !== "string") return "";
- if (text.length <= max) return text;
- return `${text.slice(0, max)}\n…[truncated ${text.length - max} chars]`;
-}
-
-// The scout's curated read-only gathering surface. We detect which of these it
-// actually exercised by scanning its turn contents (tool calls render the tool
-// name into the assistant turn; results carry recognizable output). This is the
-// signal that the enrichment "went through chat messages / skills", not just
-// memory + web.
-const GATHERING_TOOLS = [
- "memory_recall",
- "transcript_search",
- "thread_list",
- "thread_read",
- "list_workflows",
- "skill_registry_browse",
- "skill_registry_search",
- "web_search_tool",
- "web_fetch",
-];
-
-function gatheringToolsUsed(scout) {
- if (!scout) return [];
- const blob = scout.messages
- .filter((m) => m.role === "assistant" || m.role === "tool")
- .map((m) => (typeof m.content === "string" ? m.content : ""))
- .join("\n");
- return GATHERING_TOOLS.filter((t) => blob.includes(t));
-}
-
-// ── Transcript seeding ───────────────────────────────────────────────────────
-
-// Seed a *prior* conversation the scout can find via `transcript_search`. Plants
-// a distinctive canary fact so a transcript-recall case can prove the scout read
-// past chat (the summary should echo the canary). Returns { threadId, canary,
-// query } or null on failure (seeding is best-effort — the audit still runs).
-async function seedTranscript(opts) {
- const canary = `deploy-canary-${randomBytes(4).toString("hex")}`;
- const nowIso = new Date().toISOString();
- try {
- // create_new auto-generates the thread id; pull it from the envelope.
- const created = await rpc(
- opts.coreUrl,
- opts.token,
- "openhuman.threads_create_new",
- { labels: ["apc-audit-seed"] },
- opts.rpcTimeoutMs,
- );
- const threadId = created?.data?.id || created?.id;
- if (!threadId)
- throw new Error(
- `no thread id in create_new envelope: ${JSON.stringify(created).slice(0, 200)}`,
- );
- const message = {
- id: `seed-${randomBytes(4).toString("hex")}`,
- content: `Earlier I told you the staging deploy passphrase is "${canary}". Please remember it for later.`,
- type: "text",
- extraMetadata: {},
- sender: "user",
- createdAt: nowIso,
- };
- await rpc(
- opts.coreUrl,
- opts.token,
- "openhuman.threads_message_append",
- { thread_id: threadId, message },
- opts.rpcTimeoutMs,
- );
- return {
- threadId,
- canary,
- query: `In an earlier chat I told you the staging deploy passphrase. What was it?`,
- };
- } catch (err) {
- console.log(
- `[apc-audit] WARN: transcript seeding failed (${err.message}); transcript-recall case skipped.`,
- );
- return null;
- }
-}
-
-// ── Scout prompt override (optional) ─────────────────────────────────────────
-
-function scoutOverrideToml(inlinePrompt) {
- // A full context_scout definition mirroring the builtin, with the system
- // prompt swapped for the user's file. Workspace overrides replace the builtin
- // on id collision, so every field the runtime relies on must be present.
- const esc = inlinePrompt.replace(/\\/g, "\\\\").replace(/"""/g, '\\"\\"\\"');
- return `id = "context_scout"
-display_name = "Context Scout (override)"
-when_to_use = "Pre-flight context collector (prompt override)."
-temperature = 0.3
-max_iterations = 8
-iteration_policy = "extended"
-max_result_chars = 5000
-sandbox_mode = "read_only"
-agent_tier = "worker"
-omit_identity = true
-omit_memory_context = true
-omit_safety_preamble = true
-omit_profile = false
-omit_memory_md = false
-
-[model]
-hint = "agentic"
-
-[system_prompt]
-inline = """
-${esc}
-"""
-
-[tools]
-# Curated read-only surface, mirroring the builtin context_scout so a prompt
-# override under audit does not silently drop the scout's gathering reach.
-# memory_tree and the write-capable thread/skill tools are intentionally
-# excluded — the scout auto-runs on prompt-injectable input.
-named = [
- "memory_recall",
- "transcript_search",
- "thread_list",
- "thread_read",
- "list_workflows",
- "skill_registry_browse",
- "skill_registry_search",
- "web_search_tool",
- "web_fetch",
-]
-`;
-}
-
-// ── Core spawn helpers (mirrors harness-cache-audit.mjs) ─────────────────────
-
-async function pickFreePort() {
- return await new Promise((resolve, reject) => {
- const server = createServer();
- server.unref();
- server.on("error", reject);
- server.listen(0, "127.0.0.1", () => {
- const address = server.address();
- const port = typeof address === "object" && address ? address.port : 0;
- server.close(() => resolve(port));
- });
- });
-}
-
-async function startCore(opts) {
- const token = opts.token || `apc-${randomBytes(24).toString("hex")}`;
- const env = { ...process.env, OPENHUMAN_CORE_TOKEN: token };
- // Only pin OPENHUMAN_WORKSPACE when the user explicitly asked for one.
- // Setting it to the auto-resolved active-user workspace makes the core
- // create a *nested* `.openhuman/` config dir without the signed-in
- // session (→ SESSION_EXPIRED). Leaving it unset lets the core resolve the
- // active user from ~/.openhuman/active_user.toml and load its live session;
- // transcripts then land in that same workspace the script reads.
- if (opts.workspaceExplicit && opts.workspace)
- env.OPENHUMAN_WORKSPACE = opts.workspace;
- const port = new URL(opts.coreUrl).port || "7788";
- env.OPENHUMAN_CORE_PORT = port;
- env.OPENHUMAN_CORE_RPC_URL = opts.coreUrl;
- const args = ["run", "--host", "127.0.0.1", "--port", port, "--jsonrpc-only"];
- const child = spawn(
- "cargo",
- ["run", "--quiet", "--bin", "openhuman-core", "--", ...args],
- {
- cwd: path.resolve(SCRIPT_DIR, "../.."),
- env,
- stdio: opts.verbose
- ? ["ignore", "inherit", "inherit"]
- : ["ignore", "ignore", "pipe"],
- },
- );
- let stderr = "";
- if (child.stderr) {
- child.stderr.on("data", (chunk) => {
- stderr += chunk.toString();
- if (stderr.length > 8000) stderr = stderr.slice(-8000);
- });
- }
- await waitForCore(opts.coreUrl, token, child, () => stderr);
- return { child, token };
-}
-
-async function waitForCore(coreUrl, token, child, stderrFn) {
- const deadline = Date.now() + 180_000;
- while (Date.now() < deadline) {
- if (child.exitCode !== null)
- throw new Error(
- `spawned core exited with ${child.exitCode}\n${stderrFn()}`,
- );
- try {
- await rpc(coreUrl, token, "core.ping", {}, 10_000);
- return;
- } catch {
- await new Promise((r) => setTimeout(r, 750));
- }
- }
- throw new Error(
- `timed out waiting for spawned core at ${coreUrl}\n${stderrFn()}`,
- );
-}
-
-async function stopChild(child) {
- if (child.exitCode !== null || child.signalCode !== null) return;
- child.kill("SIGTERM");
- const exited = await Promise.race([
- once(child, "exit").then(() => true),
- new Promise((r) => setTimeout(() => r(false), 5_000)),
- ]);
- if (exited || child.exitCode !== null || child.signalCode !== null) return;
- child.kill("SIGKILL");
- await Promise.race([
- once(child, "exit"),
- new Promise((r) => setTimeout(r, 2_000)),
- ]);
-}
-
-// ── Reporting ────────────────────────────────────────────────────────────────
-
-function printCase(opts, caseInfo, scout, root, ms) {
- console.log(`\n${"═".repeat(78)}`);
- console.log(`▶ case: ${caseInfo.name} (${ms}ms)`);
- console.log(` query: ${caseInfo.query}`);
-
- if (!scout) {
- console.log(
- " ⚠ no context_scout transcript found — prepared context did not run.",
- );
- console.log(
- " (Is the core built from this branch?)",
- );
- return;
- }
-
- // Which curated gathering tools the scout actually exercised this turn.
- const used = gatheringToolsUsed(scout);
- console.log(
- ` gathering tools used (${used.length}): ${used.join(", ") || "(none detected)"}`,
- );
- if (caseInfo.canary) {
- const hitCanary = scout.messages.some(
- (m) =>
- typeof m.content === "string" && m.content.includes(caseInfo.canary),
- );
- console.log(
- ` transcript canary recalled: ${hitCanary ? `YES (${caseInfo.canary})` : "NO"}`,
- );
- }
-
- // Scout turns ("thoughts" — the model's step-by-step text + tool results).
- const assistantTurns = scout.messages.filter((m) => m.role === "assistant");
- const toolTurns = scout.messages.filter((m) => m.role === "tool");
- console.log(
- `\n ── scout thoughts (${assistantTurns.length} assistant turn(s), ${toolTurns.length} tool result(s)) ──`,
- );
- scout.messages
- .filter((m) => m.role === "assistant" || m.role === "tool")
- .forEach((m, i) => {
- const label = m.role === "assistant" ? "think" : "tool ←";
- console.log(
- ` [${i}] ${label}: ${clip(m.content, opts.maxPrintChars).replace(/\n/g, "\n ")}`,
- );
- });
-
- // Parsed bundle from the scout's final assistant message.
- const finalText = assistantTurns.at(-1)?.content || "";
- const bundle =
- extractBundle(finalText) ||
- extractBundle(scout.messages.at(-1)?.content || "");
- console.log("\n ── parsed context bundle ──");
- if (bundle) {
- console.log(` has_enough_context: ${bundle.hasEnough}`);
- console.log(
- ` summary: ${clip(bundle.summary, opts.maxPrintChars).replace(/\n/g, "\n ")}`,
- );
- console.log(
- ` recommended_tool_calls (${bundle.tools.length}): ${bundle.tools.join(", ") || "(none)"}`,
- );
- console.log(
- ` recommended_skills (${bundle.skills?.length || 0}): ${(bundle.skills || []).join(", ") || "(none)"}`,
- );
- } else {
- console.log(
- " ⚠ scout output did not contain a [context_bundle] envelope. Raw final text:",
- );
- console.log(
- ` ${clip(finalText, opts.maxPrintChars).replace(/\n/g, "\n ")}`,
- );
- }
-
- // Token / cost breakdown.
- const rows = [];
- rows.push(usageRow("context_scout", scout));
- if (root) rows.push(usageRow("orchestrator", root));
- rows.push({
- session: "TOTAL",
- in: scout.input + (root?.input || 0),
- out: scout.output + (root?.output || 0),
- cached: scout.cached + (root?.cached || 0),
- "cache%": cachePct(
- scout.input + (root?.input || 0),
- scout.cached + (root?.cached || 0),
- ),
- cost_usd: round6(scout.charged + (root?.charged || 0)),
- });
- console.log("\n ── tokens & cost ──");
- console.table(rows);
-}
-
-function usageRow(label, t) {
- return {
- session: label,
- in: t.input,
- out: t.output,
- cached: t.cached,
- "cache%": cachePct(t.input, t.cached),
- cost_usd: round6(t.charged),
- };
-}
-
-function cachePct(input, cached) {
- return input > 0 ? `${((cached / input) * 100).toFixed(1)}%` : "0.0%";
-}
-
-function round6(n) {
- return Number(n.toFixed(6));
-}
-
-// ── Main ──────────────────────────────────────────────────────────────────────
-
-async function main() {
- const opts = parseArgs(process.argv.slice(2));
- if (!opts.workspace) opts.workspace = await defaultWorkspace();
-
- const cases =
- opts.queries.length > 0
- ? opts.queries.map((q, i) => ({ name: `custom-${i + 1}`, query: q }))
- : [...DEFAULT_CASES];
-
- // Write the optional context_scout prompt override BEFORE the core starts,
- // so a spawned core loads it (the override is read at boot). For attached
- // mode the caller must have already started the core after writing it — but
- // writing first here still beats writing after, and we warn below.
- let overridePath = "";
- if (opts.scoutPromptFile) {
- const promptBody = await readFile(opts.scoutPromptFile, "utf8");
- const agentsDir = path.join(opts.workspace, "agents");
- await mkdir(agentsDir, { recursive: true });
- overridePath = path.join(agentsDir, "context_scout.toml");
- await writeFile(overridePath, scoutOverrideToml(promptBody.trim()));
- console.log(`[apc-audit] wrote scout prompt override → ${overridePath}`);
- if (!opts.spawnCore) {
- console.log(
- "[apc-audit] NOTE: attached mode — restart your core now so it loads the override before audits run.",
- );
- }
- }
-
- let spawned;
- if (opts.spawnCore) {
- if (!opts.coreUrlExplicit) {
- const port = await pickFreePort();
- opts.coreUrl = `http://127.0.0.1:${port}/rpc`;
- }
- spawned = await startCore(opts);
- opts.token = spawned.token;
- } else {
- opts.token = await readToken(opts);
- }
-
- // Seed a prior-chat thread (with a canary fact) and append a transcript-recall
- // case so the audit exercises the scout's new transcript_search reach. Only
- // when running the default cases — custom --query runs are left untouched.
- let seed = null;
- if (opts.seedTranscript && opts.queries.length === 0) {
- seed = await seedTranscript(opts);
- if (seed) {
- console.log(
- `[apc-audit] seeded prior-chat thread ${seed.threadId} with canary ${seed.canary}`,
- );
- cases.push({
- name: "transcript/recall",
- query: seed.query,
- canary: seed.canary,
- });
- }
- }
-
- console.log("[apc-audit] starting live prepared-context audit");
- console.log(` rpc: ${opts.coreUrl}`);
- console.log(` workspace: ${opts.workspace}`);
- console.log(
- ` mode: ${opts.spawnCore ? "spawned-core (this branch)" : "attached-core"}`,
- );
- console.log(` model: ${opts.model || "(account default)"}`);
- console.log(` cases: ${cases.length} (direct query)`);
-
- const caseResults = [];
- try {
- for (let i = 0; i < cases.length; i += 1) {
- const c = cases[i];
- const threadId = `${opts.threadPrefix}-${i}`;
- const before = await snapshot(opts.workspace);
- const params = {
- message: c.query,
- thread_id: threadId,
- };
- if (opts.model) params.model_override = opts.model;
- const started = Date.now();
- let rpcError = "";
- try {
- await rpc(
- opts.coreUrl,
- opts.token,
- "openhuman.inference_agent_chat",
- params,
- opts.rpcTimeoutMs,
- );
- } catch (err) {
- rpcError = err.message;
- }
- const ms = Date.now() - started;
- const after = await snapshot(opts.workspace);
- const changed = changedForThread(before, after, threadId);
- const scout =
- changed.find((t) => t.isSubagent && t.agent === SCOUT_AGENT) ||
- changed.find((t) => t.agent === SCOUT_AGENT);
- const root = changed.find((t) => !t.isSubagent);
-
- if (rpcError) console.log(`\n▶ case: ${c.name} — RPC error: ${rpcError}`);
- printCase(opts, c, scout, root, ms);
-
- const finalText =
- scout?.messages.filter((m) => m.role === "assistant").at(-1)?.content ||
- "";
- const bundle = scout ? extractBundle(finalText) : null;
- const used = gatheringToolsUsed(scout);
- const canaryRecalled = c.canary
- ? Boolean(
- scout?.messages.some(
- (m) =>
- typeof m.content === "string" && m.content.includes(c.canary),
- ),
- )
- : null;
- caseResults.push({
- name: c.name,
- query: c.query,
- ms,
- invoked: Boolean(scout),
- hasEnough: bundle?.hasEnough ?? null,
- recommended: bundle?.tools ?? [],
- skills: bundle?.skills ?? [],
- gatheringUsed: used,
- canaryRecalled,
- scout: scout ? pick(scout) : null,
- orchestrator: root ? pick(root) : null,
- rpcError: rpcError || null,
- });
- }
- } finally {
- // Delete the seeded prior-chat thread BEFORE tearing down the core (RPC must
- // still be reachable), so the audit leaves no fake "deploy passphrase" data
- // in the user's live conversation index/memory surface. Best-effort — a
- // failure here is logged, not fatal. --keep-workspace preserves it.
- if (seed?.threadId && !opts.keepWorkspace) {
- try {
- await rpc(
- opts.coreUrl,
- opts.token,
- "openhuman.threads_delete",
- { thread_id: seed.threadId, deleted_at: new Date().toISOString() },
- opts.rpcTimeoutMs,
- );
- console.log(`\n[apc-audit] cleaned up seeded thread ${seed.threadId}`);
- } catch (err) {
- console.log(
- `\n[apc-audit] WARN: failed to delete seeded thread ${seed.threadId} (${err.message}); remove it manually.`,
- );
- }
- }
- if (spawned?.child) await stopChild(spawned.child);
- if (overridePath && !opts.keepWorkspace) {
- await rm(overridePath, { force: true });
- console.log(
- `\n[apc-audit] removed scout prompt override ${overridePath}`,
- );
- }
- }
-
- // Aggregate.
- const agg = caseResults.reduce(
- (a, r) => {
- a.invoked += r.invoked ? 1 : 0;
- a.in += (r.scout?.input || 0) + (r.orchestrator?.input || 0);
- a.out += (r.scout?.output || 0) + (r.orchestrator?.output || 0);
- a.cached += (r.scout?.cached || 0) + (r.orchestrator?.cached || 0);
- a.cost += (r.scout?.charged || 0) + (r.orchestrator?.charged || 0);
- return a;
- },
- { invoked: 0, in: 0, out: 0, cached: 0, cost: 0 },
- );
-
- console.log(`\n${"═".repeat(78)}`);
- console.log("[apc-audit] summary");
- console.table(
- caseResults.map((r) => ({
- case: r.name,
- prepared: r.invoked ? "yes" : "NO",
- enough: r.hasEnough ?? "-",
- rec_tools: r.recommended.length,
- rec_skills: r.skills.length,
- gather: r.gatheringUsed.length,
- canary: r.canaryRecalled === null ? "-" : r.canaryRecalled ? "YES" : "NO",
- ms: r.ms,
- cost_usd: round6(
- (r.scout?.charged || 0) + (r.orchestrator?.charged || 0),
- ),
- })),
- );
- console.log(` prepared-context runs: ${agg.invoked}/${caseResults.length}`);
- // Surface whether the transcript-recall case actually proved the new reach.
- const recallCase = caseResults.find((r) => r.canaryRecalled !== null);
- if (recallCase) {
- console.log(
- ` transcript recall: ${recallCase.canaryRecalled ? "PASS — scout recalled the seeded canary" : "MISS — scout did not surface the seeded canary"}` +
- ` (gathering tools: ${recallCase.gatheringUsed.join(", ") || "none"})`,
- );
- }
- console.log(
- ` total tokens: ${agg.in} in / ${agg.out} out / ${agg.cached} cached (${cachePct(agg.in, agg.cached)} hit)`,
- );
- console.log(` total cost: $${round6(agg.cost)}`);
-
- if (opts.json) {
- console.log(
- `\n[apc-audit] json\n${JSON.stringify({ cases: caseResults, totals: { ...agg, cost: round6(agg.cost) } }, null, 2)}`,
- );
- }
-
- const everInvoked = agg.invoked > 0;
- if (!everInvoked) {
- console.error(
- "\n[apc-audit] FAIL: prepared context was never invoked (no context_scout transcript).",
- );
- process.exit(1);
- }
- console.log("\n[apc-audit] done");
-}
-
-function pick(t) {
- return {
- input: t.input,
- output: t.output,
- cached: t.cached,
- charged: t.charged,
- file: t.file,
- };
-}
-
-main().catch((err) => {
- console.error(`[apc-audit] ERROR: ${err.message}`);
- process.exit(1);
-});