diff --git a/design-system/packages/ui/src/flow-chat/tool-cards/AgentControlToolCard.module.css b/design-system/packages/ui/src/flow-chat/tool-cards/AgentControlToolCard.module.css
index 8bf01921fe..7ddaeee038 100644
--- a/design-system/packages/ui/src/flow-chat/tool-cards/AgentControlToolCard.module.css
+++ b/design-system/packages/ui/src/flow-chat/tool-cards/AgentControlToolCard.module.css
@@ -96,6 +96,7 @@
line-height: var(--openbitfun-type-label-sm-line-height);
}
.agentType { flex: 0 1 auto; min-inline-size: 0; max-inline-size: 45%; }
+ .agentType:only-child { flex: 1 1 0; max-inline-size: 100%; }
.model { flex: 1 1 0; min-inline-size: 0; }
.model:not([data-overflow='true']) { text-align: end; }
.status,
diff --git a/design-system/packages/ui/src/flow-chat/tool-cards/AgentControlToolCard.tsx b/design-system/packages/ui/src/flow-chat/tool-cards/AgentControlToolCard.tsx
index 64bd43ad44..f53b69b9b8 100644
--- a/design-system/packages/ui/src/flow-chat/tool-cards/AgentControlToolCard.tsx
+++ b/design-system/packages/ui/src/flow-chat/tool-cards/AgentControlToolCard.tsx
@@ -30,6 +30,7 @@ export interface AgentControlToolCardProps
};
requiresConfirmation?: boolean;
status: FlowChatToolStatus;
+ /** Pass null to hide both the label and the fallback status glyph. */
statusLabel?: ReactNode;
statusTone?: 'danger' | 'neutral' | 'success' | 'warning';
summary?: ReactNode;
@@ -82,8 +83,10 @@ export function AgentControlToolCard({
{preview.labels.description}
@@ -145,7 +148,7 @@ export function AgentControlToolCard({
{statusLabel}
- ) : !['completed', 'confirmed', 'cancelled', 'rejected'].includes(status) ? (
+ ) : statusLabel !== null && !['completed', 'confirmed', 'cancelled', 'rejected'].includes(status) ? (
) : null}
@@ -154,8 +157,10 @@ export function AgentControlToolCard({
{preview.agentType}
- {preview.model}
+ {preview.model && (
+ {preview.model}
+ )}
)}
diff --git a/docs/architecture/agent-runtime-services-design.md b/docs/architecture/agent-runtime-services-design.md
index f27549b55e..5bc250e47e 100644
--- a/docs/architecture/agent-runtime-services-design.md
+++ b/docs/architecture/agent-runtime-services-design.md
@@ -68,7 +68,7 @@ Agent Runtime API 的逻辑归属与物理部署分离:相同归属模块可
私有 SDK Host 或目标机器 Runtime 中。任何 Rust 部署都只管理自己进程树内的服务与 Node/Bun Plugin Host;不能因为多个
GUI/TUI/Remote Client 连接就复制 Runtime 状态模块,或按 Client/Workspace 创建 Plugin Host。
-Rust Runtime SDK 以 `AGENT_RUNTIME_SDK_API_VERSION` 标记兼容边界。当前接口版本为 v10 preview:
+Rust Runtime SDK 以 `AGENT_RUNTIME_SDK_API_VERSION` 标记兼容边界。当前接口版本为 v11 preview:
小版本更新允许增加可选 builder hook、有默认实现的端口方法或注册表查询能力,但不得向外部可用
Rust 结构体字面量(struct literal)构造的 DTO 直接增加字段,也不得改变既有端口语义、错误分类、session / turn 标识含义或
默认 feature 依赖。任何需要调用方改写现有嵌入代码的变更,必须提升接口版本并提供兼容迁移路径。
@@ -101,6 +101,12 @@ Product Assembly 选择并在 `agent-workflows` / 现有产品 owner 中执行
v10 让 Turn settlement 返回 Runtime 确认的终态、最终回答和结束原因。现有 Rust embedder 需要接收
`AgentTurnSettlementResult`;CLI 和 App Server adapter 可在不扩展各自 wire contract 的情况下丢弃返回值。
+v11 移除按模型名称和 Agent 类型选择的上下文策略,以及父子任务关系对策略的覆盖。
+Rust 调用方删除 `ModelCapabilityProfile`、`ContextProfile`、`ContextProfilePolicy` 和
+`context_profile` 模块的引用。普通子代理并发直接使用 `ai.subagent_max_concurrency`;
+重复失败检测直接使用现有执行配置;压缩和报告统一使用每类 8 条的结构化证据容量上限。
+持久化数据和 wire payload 无需迁移。
+
只要外部调用方仍必须导入 `openbitfun-core`、启用 `product-full`、持有具体服务管理器、读取产品命令
注册表、理解 ACP/内部端口或依赖全局可变状态,公开 SDK 发布边界就不成立。公开 SDK 的完整
术语、能力等价和版本要求以 [`agent-sdk-product-architecture.md`](agent-sdk-product-architecture.md) 为准。
@@ -444,7 +450,7 @@ impl AgentRuntime {
该 Rust 接口是内部产品入口复用的当前形态,不是公开 Python/TypeScript SDK 的目标 API。它必须只接收
已组装的类型化部件,不负责创建
文件系统、终端、MCP、AI 客户端、Remote 提供方或产品命令。
-当前 v10 preview 接口以 message / attachment / metadata、默认标准执行目标和活动 Turn 文本 steer 作为最小输入形态;若把
+当前 v11 preview 接口以 message / attachment / metadata、默认标准执行目标和活动 Turn 文本 steer 作为最小输入形态;若把
model-round cancellation token、结构化 AgentInput 或更复杂的事件游标纳入公开 SDK,
必须分别评审 Rust Runtime SDK、SDK Host protocol 和公开 SDK API 的版本,并保留旧路径兼容。
diff --git a/docs/architecture/deep-review.md b/docs/architecture/deep-review.md
index 21d36a3bce..7b88737cdf 100644
--- a/docs/architecture/deep-review.md
+++ b/docs/architecture/deep-review.md
@@ -128,7 +128,7 @@ The default strict-review contract is mirrored in Rust and TypeScript. New stric
- automatic file splitting, same-role fan-out, and reviewer retry are disabled;
- workers and the Judge share one three-call allowance and at most two run concurrently.
-The runtime enforces the shared allowance even if a weak model ignores the prompt. This is a resource ceiling, not a keyword or risk-score workflow rule. The model decides whether another check is useful from the actual evidence and task; the manifest and backend limit which read-only capability, target scope, and question it may use. The Review capacity setting may lower focused checks and managed large-target batches to one-at-a-time execution, but it cannot raise the two-way ceiling or create additional work.
+The runtime enforces the shared allowance even if a model ignores the prompt. This is a resource ceiling, not a keyword or risk-score workflow rule. The model decides whether another check is useful from the actual evidence and task; the manifest and backend limit which read-only capability, target scope, and question it may use. The Review capacity setting may lower focused checks and managed large-target batches to one-at-a-time execution, but it cannot raise the two-way ceiling or create additional work.
Historical configuration fields for reviewer timeouts, file-split thresholds, same-role instances, retries, concurrency, and queue behavior remain readable so stored sessions can recover honestly. New adaptive manifests override split, same-role, retry, concurrency, and call values to the bounded policy above. Configured review agents must be file-backed and read-only. `DeepReview` and `ReviewFixer` remain disallowed.
diff --git a/scripts/core-boundaries/rules/source/facade-rules.mjs b/scripts/core-boundaries/rules/source/facade-rules.mjs
index 440d3c9281..7f6e001dc9 100644
--- a/scripts/core-boundaries/rules/source/facade-rules.mjs
+++ b/scripts/core-boundaries/rules/source/facade-rules.mjs
@@ -1,11 +1,6 @@
// Boundary rules for source ownership, facades, and required owner content.
export const facadeOnlyFiles = [
- {
- path: 'src/crates/assembly/core/src/agentic/context_profile.rs',
- importPrefix: 'openbitfun_agent_runtime::context_profile',
- reason: 'core context profile path must only re-export the agent-runtime owner crate',
- },
{
path: 'src/crates/assembly/core/src/agentic/core/dialog_turn.rs',
importPrefix: 'openbitfun_agent_runtime::dialog_turn',
diff --git a/scripts/core-boundaries/rules/source/public-api-rules.mjs b/scripts/core-boundaries/rules/source/public-api-rules.mjs
index 6d70be3b8a..1d814c2937 100644
--- a/scripts/core-boundaries/rules/source/public-api-rules.mjs
+++ b/scripts/core-boundaries/rules/source/public-api-rules.mjs
@@ -26,7 +26,6 @@ export const agentRuntimeRootPublicModules = [
'agents',
'checkpoint',
'compression_prefetch',
- 'context_profile',
'custom_agent',
'custom_subagent',
'deep_review',
diff --git a/scripts/core-boundaries/rules/source/required-rules.mjs b/scripts/core-boundaries/rules/source/required-rules.mjs
index c575b66548..3b7753abef 100644
--- a/scripts/core-boundaries/rules/source/required-rules.mjs
+++ b/scripts/core-boundaries/rules/source/required-rules.mjs
@@ -731,33 +731,6 @@ export const requiredContentRules = [
},
],
},
- {
- path: 'src/crates/execution/agent-runtime/src/context_profile.rs',
- reason:
- 'agent-runtime must own provider-neutral context profile and model capability policy facts',
- patterns: [
- {
- regex: /\bpub enum ContextProfile\b/,
- message: 'missing context profile fact',
- },
- {
- regex: /\bpub enum ModelCapabilityProfile\b/,
- message: 'missing model capability profile fact',
- },
- {
- regex: /\bpub struct ContextProfilePolicy\b/,
- message: 'missing context profile policy fact',
- },
- {
- regex: /\bfor_subagent_context_and_models\b/,
- message: 'missing subagent context/model policy helper',
- },
- {
- regex: /\bmodel_capability_weak_for_mini\b/,
- message: 'missing weak-model regression',
- },
- ],
- },
{
path: 'src/crates/execution/agent-runtime/src/session_state.rs',
reason:
diff --git a/scripts/core-boundaries/self-test.mjs b/scripts/core-boundaries/self-test.mjs
index 93804e6636..e69829238f 100644
--- a/scripts/core-boundaries/self-test.mjs
+++ b/scripts/core-boundaries/self-test.mjs
@@ -2762,16 +2762,6 @@ export function runManifestParserSelfTest({
path: 'src/crates/execution/agent-runtime/Cargo.toml',
contracts: ['[features]', 'default = []'],
},
- {
- path: 'src/crates/execution/agent-runtime/src/context_profile.rs',
- contracts: [
- 'ContextProfile',
- 'ModelCapabilityProfile',
- 'ContextProfilePolicy',
- 'for_subagent_context_and_models',
- 'model_capability_weak_for_mini',
- ],
- },
{
path: 'src/crates/execution/agent-runtime/src/session_state.rs',
contracts: [
diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md
index 51b2b77331..04ee00d919 100644
--- a/src/crates/assembly/core/AGENTS.md
+++ b/src/crates/assembly/core/AGENTS.md
@@ -210,6 +210,12 @@ cargo test --locked -p openbitfun-core --no-default-features --features agent-ru
These fixtures cover prompt name mappings and simulated workspace policies;
they do not establish live SSH, relay, Peer, or Detached Dispatch behavior.
+For ordinary subagent shared concurrency, permit release, and cancelled/timed-out waits:
+
+```bash
+cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib subagent_concurrency_
+```
+
For smart routing, unchanged subagent model policy and resumed subagent choices:
```bash
diff --git a/src/crates/assembly/core/src/agentic/context_profile.rs b/src/crates/assembly/core/src/agentic/context_profile.rs
deleted file mode 100644
index 2c609e831e..0000000000
--- a/src/crates/assembly/core/src/agentic/context_profile.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-//! Compatibility facade for Agent Kernel context profile policy.
-
-pub use openbitfun_agent_runtime::context_profile::{
- ContextProfile, ContextProfilePolicy, ModelCapabilityProfile,
-};
diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs
index 5d0b43ee24..1095b252fd 100644
--- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs
+++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs
@@ -15,7 +15,6 @@ use super::{
use crate::agentic::agents::{
get_agent_registry, is_swarm_delegate_agent_type, ExternalSubagentModelBinding,
};
-use crate::agentic::context_profile::ContextProfilePolicy;
use crate::agentic::core::{
InternalReminderKind, Message, MessageContent, MessageSemanticKind, ProcessingPhase, Session,
SessionAgentRouteOwner, SessionConfig, SessionContinuationPolicy, SessionKind,
@@ -1443,7 +1442,6 @@ pub struct ConversationCoordinator {
event_router: Arc
,
subagent_concurrency_limiter: Arc>>,
swarm_concurrency_limiter: Arc>>,
- subagent_profile_concurrency_limiters: Arc>>,
/// Registry for dynamically adjusting subagent timeouts.
subagent_timeout_registry: Arc>>>,
/// Active subagent executions keyed by subagent session id.
@@ -2383,7 +2381,6 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
event_router,
subagent_concurrency_limiter: Arc::new(RwLock::new(None)),
swarm_concurrency_limiter: Arc::new(RwLock::new(None)),
- subagent_profile_concurrency_limiters: Arc::new(RwLock::new(HashMap::new())),
subagent_timeout_registry: Arc::new(RwLock::new(HashMap::new())),
active_subagent_executions: Arc::new(DashMap::new()),
background_subagent_tasks: Arc::new(DashMap::new()),
@@ -10613,32 +10610,6 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
limiter
}
- async fn get_subagent_profile_concurrency_limiter(
- &self,
- max_concurrency: usize,
- ) -> SubagentConcurrencyLimiter {
- let max_concurrency = normalize_subagent_max_concurrency(max_concurrency);
-
- {
- let limiter_guard = self.subagent_profile_concurrency_limiters.read().await;
- if let Some(limiter) = limiter_guard.get(&max_concurrency) {
- return limiter.clone();
- }
- }
-
- let mut limiter_guard = self.subagent_profile_concurrency_limiters.write().await;
- if let Some(limiter) = limiter_guard.get(&max_concurrency) {
- return limiter.clone();
- }
-
- let limiter = SubagentConcurrencyLimiter {
- semaphore: Arc::new(Semaphore::new(max_concurrency)),
- max_concurrency,
- };
- limiter_guard.insert(max_concurrency, limiter.clone());
- limiter
- }
-
async fn get_swarm_concurrency_limiter(&self) -> SubagentConcurrencyLimiter {
let configured = match GlobalConfigManager::get_service().await {
Ok(config_service) => match config_service
@@ -10755,7 +10726,6 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
async fn acquire_subagent_concurrency_permit(
&self,
agent_type: &str,
- profile_concurrency_cap: usize,
cancel_token: Option<&CancellationToken>,
deadline: Option,
) -> OpenBitFunResult<(
@@ -10778,19 +10748,6 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
));
}
- let profile_limiter = self
- .get_subagent_profile_concurrency_limiter(profile_concurrency_cap)
- .await;
- let profile_permit = self
- .acquire_permit_from_limiter(
- &profile_limiter,
- agent_type,
- cancel_token,
- deadline,
- "profile",
- )
- .await?;
-
let global_limiter = self.get_subagent_concurrency_limiter().await;
let global_permit = self
.acquire_permit_from_limiter(
@@ -10804,55 +10761,11 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
let wait_ms = started_waiting.elapsed().as_millis();
debug!(
- "Acquired subagent concurrency permits: agent_type={}, wait_ms={}, profile_max_concurrency={}, global_max_concurrency={}",
- agent_type, wait_ms, profile_limiter.max_concurrency, global_limiter.max_concurrency
+ "Acquired subagent concurrency permit: agent_type={}, wait_ms={}, max_concurrency={}",
+ agent_type, wait_ms, global_limiter.max_concurrency
);
- Ok((
- vec![
- (profile_permit, profile_limiter),
- (global_permit, global_limiter),
- ],
- wait_ms,
- ))
- }
-
- fn context_profile_policy_for_subagent(
- &self,
- agent_type: &str,
- session_config: &SessionConfig,
- subagent_parent_info: Option<&SubagentParentInfo>,
- ) -> ContextProfilePolicy {
- if let Some(parent_info) = subagent_parent_info {
- if let Some(parent_session) = self.session_manager.get_session(&parent_info.session_id)
- {
- let parent_is_review_subagent = get_agent_registry()
- .get_subagent_is_review(&parent_session.agent_type)
- .unwrap_or(false);
- let is_review_subagent = get_agent_registry()
- .get_subagent_is_review(agent_type)
- .unwrap_or(false);
- return ContextProfilePolicy::for_subagent_context_and_models(
- agent_type,
- is_review_subagent,
- session_config.model_id.as_deref(),
- Some(&parent_session.agent_type),
- parent_is_review_subagent,
- parent_session.config.model_id.as_deref(),
- );
- }
- }
-
- let is_review_subagent = get_agent_registry()
- .get_subagent_is_review(agent_type)
- .unwrap_or(false);
- let model_id = session_config.model_id.as_deref().unwrap_or_default();
- ContextProfilePolicy::for_agent_context_and_model(
- agent_type,
- is_review_subagent,
- model_id,
- model_id,
- )
+ Ok((vec![(global_permit, global_limiter)], wait_ms))
}
async fn execute_hidden_subagent_internal(
@@ -10952,18 +10865,6 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
.map(|info| info.tool_call_id.as_str())
.unwrap_or("-");
- let context_profile_policy = self.context_profile_policy_for_subagent(
- &agent_type,
- &session_config,
- subagent_parent_info.as_ref(),
- );
- debug!(
- "Subagent context profile policy selected: agent_type={}, profile={:?}, profile_concurrency_cap={}",
- agent_type,
- context_profile_policy.profile,
- context_profile_policy.subagent_concurrency_cap
- );
-
// Check cancel token (before creating session)
if let Some(token) = cancel_token {
if token.is_cancelled() {
@@ -10983,12 +10884,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
// target hidden session may have been created by the scheduler before
// this point so per-session queueing can use its real session_id.
let (permits, wait_ms) = match self
- .acquire_subagent_concurrency_permit(
- &agent_type,
- context_profile_policy.subagent_concurrency_cap,
- cancel_token,
- initial_deadline,
- )
+ .acquire_subagent_concurrency_permit(&agent_type, cancel_token, initial_deadline)
.await
{
Ok(value) => value,
@@ -18579,6 +18475,76 @@ pub(crate) mod tests {
);
}
+ #[tokio::test]
+ async fn subagent_concurrency_uses_global_capacity_for_all_ordinary_agent_types() {
+ use super::SubagentConcurrencyPermitGuard;
+ use tokio::time::Instant;
+
+ let (coordinator, _) = test_coordinator();
+ let limiter = coordinator.get_subagent_concurrency_limiter().await;
+ let capacity = limiter.max_concurrency;
+ let agent_types = [
+ "Explore",
+ "Cowork",
+ "ResearchSpecialist",
+ "ReviewSecurity",
+ "Standard",
+ ];
+ let mut guards = Vec::new();
+ for index in 0..capacity {
+ let agent_type = agent_types[index % agent_types.len()];
+ let (permits, _) = coordinator
+ .acquire_subagent_concurrency_permit(
+ agent_type,
+ None,
+ Some(Instant::now() + Duration::from_secs(5)),
+ )
+ .await
+ .expect("ordinary agents should share all configured global slots");
+ assert_eq!(permits.len(), 1);
+ assert!(Arc::ptr_eq(&permits[0].1.semaphore, &limiter.semaphore));
+ guards.push(SubagentConcurrencyPermitGuard::new(
+ permits,
+ agent_type.to_string(),
+ ));
+ }
+ assert_eq!(limiter.semaphore.available_permits(), 0);
+
+ let timed_out = coordinator
+ .acquire_subagent_concurrency_permit("Explore", None, Some(Instant::now()))
+ .await;
+ assert!(matches!(
+ timed_out,
+ Err(crate::util::errors::OpenBitFunError::Timeout(_))
+ ));
+
+ let cancelled = CancellationToken::new();
+ cancelled.cancel();
+ let cancelled_wait = coordinator
+ .acquire_subagent_concurrency_permit("ResearchSpecialist", Some(&cancelled), None)
+ .await;
+ assert!(matches!(
+ cancelled_wait,
+ Err(crate::util::errors::OpenBitFunError::Cancelled(_))
+ ));
+
+ guards.pop();
+ let (permits, _) = coordinator
+ .acquire_subagent_concurrency_permit(
+ "ResearchSpecialist",
+ None,
+ Some(Instant::now() + Duration::from_secs(5)),
+ )
+ .await
+ .expect("releasing a slot should admit a different ordinary agent type");
+ drop(SubagentConcurrencyPermitGuard::new(
+ permits,
+ "ResearchSpecialist".to_string(),
+ ));
+ drop(guards);
+ assert_eq!(limiter.semaphore.available_permits(), capacity);
+ }
+
#[tokio::test]
async fn background_subagent_start_honors_an_already_cancelled_tool() {
let (coordinator, _session_manager) = test_coordinator();
diff --git a/src/crates/assembly/core/src/agentic/deep_review/report.rs b/src/crates/assembly/core/src/agentic/deep_review/report.rs
index c98a43df18..145db03d82 100644
--- a/src/crates/assembly/core/src/agentic/deep_review/report.rs
+++ b/src/crates/assembly/core/src/agentic/deep_review/report.rs
@@ -4,14 +4,13 @@
//! updates are owned by `openbitfun-agent-runtime::deep_review::report`. This file
//! keeps core-only context lookup, diagnostics logging, and session metadata IO.
-use crate::agentic::agents::get_agent_registry;
-use crate::agentic::context_profile::ContextProfilePolicy;
use crate::agentic::coordination::get_global_coordinator;
use crate::agentic::core::CompressionContract;
use crate::agentic::deep_review_policy::{
deep_review_capacity_skip_count, deep_review_concurrency_cap_rejection_count,
deep_review_runtime_diagnostics_snapshot,
};
+use crate::agentic::session::DEFAULT_COMPRESSION_CONTRACT_LIMIT;
use crate::agentic::tools::framework::ToolUseContext;
use crate::util::errors::OpenBitFunResult;
use log::debug;
@@ -38,12 +37,9 @@ pub(crate) fn compression_contract_for_context(
let session_id = context.session_id.as_deref()?;
let coordinator = get_global_coordinator()?;
let session = coordinator.get_session_manager().get_session(session_id)?;
- let agent_type = Some(session.agent_type.as_str());
- let model_id = session.config.model_id.as_deref();
- let limit = reliability_contract_limit(agent_type, model_id);
let contract = coordinator
.get_session_manager()
- .compression_contract_for_session(session_id, limit)?;
+ .compression_contract_for_session(session_id, DEFAULT_COMPRESSION_CONTRACT_LIMIT)?;
should_report_compression_preserved(
session.compression_state.compression_count,
Some(&contract),
@@ -51,31 +47,6 @@ pub(crate) fn compression_contract_for_context(
.then_some(contract)
}
-pub(crate) fn reliability_contract_limit(
- agent_type: Option<&str>,
- model_id: Option<&str>,
-) -> usize {
- let agent_type = agent_type
- .map(str::trim)
- .filter(|agent_type| !agent_type.is_empty())
- .unwrap_or("DeepReview");
- let model_id = model_id
- .map(str::trim)
- .filter(|model_id| !model_id.is_empty())
- .unwrap_or_default();
- let is_review_subagent = get_agent_registry()
- .get_subagent_is_review(agent_type)
- .unwrap_or(false);
-
- ContextProfilePolicy::for_agent_context_and_model(
- agent_type,
- is_review_subagent,
- model_id,
- model_id,
- )
- .compression_contract_limit
-}
-
pub(crate) fn should_report_compression_preserved(
compression_count: usize,
compression_contract: Option<&CompressionContract>,
diff --git a/src/crates/assembly/core/src/agentic/execution/compression_lifecycle.rs b/src/crates/assembly/core/src/agentic/execution/compression_lifecycle.rs
index 0f946f65f8..c9a8fd9c9b 100644
--- a/src/crates/assembly/core/src/agentic/execution/compression_lifecycle.rs
+++ b/src/crates/assembly/core/src/agentic/execution/compression_lifecycle.rs
@@ -66,7 +66,6 @@ impl ExecutionEngine {
system_prompt_message: Message,
prepended_prompt_reminders: &PrependedPromptReminders,
primary_supports_image_understanding: bool,
- compression_contract_limit: usize,
workspace: Option<&WorkspaceBinding>,
workspace_services: Option<&crate::agentic::workspace::WorkspaceServices>,
prefetch: Option,
@@ -145,7 +144,7 @@ impl ExecutionEngine {
// Execute compression
let compression_contract = self
.session_manager
- .compression_contract_for_session(session_id, compression_contract_limit);
+ .compression_contract_for_session(session_id, DEFAULT_COMPRESSION_CONTRACT_LIMIT);
let model_exchange_trace_dir = self
.session_manager
.persistent_model_exchange_trace_dir(session_id)
diff --git a/src/crates/assembly/core/src/agentic/execution/compression_tests.rs b/src/crates/assembly/core/src/agentic/execution/compression_tests.rs
index 1d1a49ee8a..9701125fa4 100644
--- a/src/crates/assembly/core/src/agentic/execution/compression_tests.rs
+++ b/src/crates/assembly/core/src/agentic/execution/compression_tests.rs
@@ -143,7 +143,6 @@ async fn apply_prefetch(
messages[0].clone(),
&PrependedPromptReminders::default(),
false,
- 10_000,
None,
None,
prefetch,
@@ -598,7 +597,6 @@ async fn compression_failure_preserves_context_and_success_count() {
Message::system("system".into()),
&PrependedPromptReminders::default(),
false,
- 10_000,
None,
None,
None,
diff --git a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs
index 76db71057b..1f3821fe8a 100644
--- a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs
+++ b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs
@@ -17,7 +17,6 @@ use crate::agentic::agents::{
render_direct_tool_listing_body, PrependedPromptReminders, PromptBuilder, PromptBuilderContext,
RuntimeContextNeeds, ToolListingSections, UserContextPolicy, UserContextSection,
};
-use crate::agentic::context_profile::{ContextProfilePolicy, ModelCapabilityProfile};
use crate::agentic::coordination::scheduler::agent_dialog_turn_image_contexts;
use crate::agentic::core::{
render_system_reminder, InternalReminderKind, Message, MessageContent, MessageHelper,
@@ -38,7 +37,8 @@ use crate::agentic::image_analysis::{
use crate::agentic::round_preempt::RoundInjectionKind;
use crate::agentic::session::{
ContextCompressor, SessionManager, SystemPromptCacheIdentity, TokenAnchor, TokenAnchorInput,
- UserContextCacheIdentity, INTERRUPTED_TURN_MODEL_BINDING_FINGERPRINT_METADATA_KEY,
+ UserContextCacheIdentity, DEFAULT_COMPRESSION_CONTRACT_LIMIT,
+ INTERRUPTED_TURN_MODEL_BINDING_FINGERPRINT_METADATA_KEY,
INTERRUPTED_TURN_PERMISSION_MODE_METADATA_KEY,
INTERRUPTED_TURN_REASONING_FINGERPRINT_METADATA_KEY,
INTERRUPTED_TURN_REASONING_PRESET_METADATA_KEY,
@@ -370,7 +370,6 @@ struct CompressionRuntimeScaffold {
system_prompt_message: Message,
prepended_prompt_reminders: PrependedPromptReminders,
primary_supports_image_understanding: bool,
- compression_contract_limit: usize,
}
#[derive(Debug, Clone)]
@@ -429,38 +428,6 @@ impl ContextHealthSnapshot {
);
}
- fn log_policy_thresholds(
- &self,
- session_id: &str,
- turn_id: &str,
- round_index: usize,
- policy: &ContextProfilePolicy,
- ) {
- if policy.has_repeated_tool_loop(self.repeated_tool_signature_count) {
- debug!(
- "Context profile repeated-tool threshold reached: session_id={}, turn_id={}, round_index={}, profile={:?}, repeated_tool_signature_count={}, threshold={}",
- session_id,
- turn_id,
- round_index,
- policy.profile,
- self.repeated_tool_signature_count,
- policy.repeated_tool_signature_threshold
- );
- }
-
- if policy.has_consecutive_command_failure_loop(self.consecutive_failed_commands) {
- warn!(
- "Context profile command-failure threshold reached: session_id={}, turn_id={}, round_index={}, profile={:?}, consecutive_failed_commands={}, threshold={}",
- session_id,
- turn_id,
- round_index,
- policy.profile,
- self.consecutive_failed_commands,
- policy.consecutive_failed_command_threshold
- );
- }
- }
-
fn repeated_tool_signature_count(recent_tool_signatures: &[String]) -> usize {
let Some(last_signature) = recent_tool_signatures.last() else {
return 0;
@@ -2758,22 +2725,8 @@ impl ExecutionEngine {
"Config service unavailable, assuming compression model is text-only for image input gating",
)
.await;
- let resolved_primary_model_id = primary_model_facts.model_id.clone();
let primary_supports_image_understanding = primary_model_facts.supports_image_inputs;
- let model_capability_profile = ModelCapabilityProfile::from_resolved_model(
- &resolved_primary_model_id,
- &ai_client.config.model,
- );
- let is_review_subagent = agent_registry
- .get_subagent_is_review(&context.agent_type)
- .unwrap_or(false);
- let context_profile_policy = ContextProfilePolicy::for_agent_context(
- &context.agent_type,
- is_review_subagent,
- model_capability_profile,
- );
-
let tool_policy = agent_registry
.get_agent_tool_policy(
&context.agent_type,
@@ -2850,7 +2803,6 @@ impl ExecutionEngine {
system_prompt_message: turn_prompt_scaffold.system_prompt_message,
prepended_prompt_reminders: turn_prompt_scaffold.prepended_prompt_reminders,
primary_supports_image_understanding,
- compression_contract_limit: context_profile_policy.compression_contract_limit,
})
}
@@ -2968,7 +2920,7 @@ impl ExecutionEngine {
let compression_contract = self
.session_manager
- .compression_contract_for_session(&session_id, scaffold.compression_contract_limit);
+ .compression_contract_for_session(&session_id, DEFAULT_COMPRESSION_CONTRACT_LIMIT);
let model_exchange_trace_dir = self
.session_manager
.persistent_model_exchange_trace_dir(&session_id)
@@ -3622,7 +3574,6 @@ impl ExecutionEngine {
"Config service unavailable, assuming primary model is text-only for image input gating",
)
.await;
- let resolved_primary_model_id = primary_model_facts.model_id.clone();
let mut primary_supports_image_understanding = primary_model_facts.supports_image_inputs;
let model_context_window = ai_client.config.context_window as usize;
@@ -3639,30 +3590,6 @@ impl ExecutionEngine {
);
}
- let model_capability_profile = ModelCapabilityProfile::from_resolved_model(
- &resolved_primary_model_id,
- &ai_client.config.model,
- );
- let is_review_subagent = agent_registry
- .get_subagent_is_review(&agent_type)
- .unwrap_or(false);
- let mut context_profile_policy = ContextProfilePolicy::for_agent_context(
- &agent_type,
- is_review_subagent,
- model_capability_profile,
- );
- debug!(
- "Context profile policy selected: session_id={}, agent_type={}, profile={:?}, model_capability={:?}, compression_contract_limit={}, subagent_concurrency_cap={}, repeated_tool_signature_threshold={}, consecutive_failed_command_threshold={}",
- context.session_id,
- agent_type,
- context_profile_policy.profile,
- model_capability_profile,
- context_profile_policy.compression_contract_limit,
- context_profile_policy.subagent_concurrency_cap,
- context_profile_policy.repeated_tool_signature_threshold,
- context_profile_policy.consecutive_failed_command_threshold
- );
-
// 3. Get available tools list (read tool configuration for current mode from global config)
let tool_policy = agent_registry
.get_agent_tool_policy(
@@ -3999,7 +3926,6 @@ impl ExecutionEngine {
};
let baseline_primary_model_facts = primary_model_facts.clone();
let baseline_supports_image_understanding = primary_supports_image_understanding;
- let baseline_context_profile_policy = context_profile_policy.clone();
let mut scaffold_model_key = (
baseline_model_id.clone(),
baseline_ai_client.config.model.clone(),
@@ -4250,15 +4176,6 @@ impl ExecutionEngine {
context_window = (ai_client.config.context_window as usize).min(session_max_tokens);
compression_trigger_budget =
Self::compression_trigger_budget(context_window, ai_client.config.max_tokens);
- let model_capability_profile = ModelCapabilityProfile::from_resolved_model(
- &primary_model_facts.model_id,
- &ai_client.config.model,
- );
- context_profile_policy = ContextProfilePolicy::for_agent_context(
- &agent_type,
- is_review_subagent,
- model_capability_profile,
- );
let next_scaffold_model_key = (
model_id.clone(),
@@ -4372,14 +4289,6 @@ impl ExecutionEngine {
.await;
primary_supports_image_understanding =
primary_model_facts.supports_image_inputs;
- context_profile_policy = ContextProfilePolicy::for_agent_context(
- &agent_type,
- is_review_subagent,
- ModelCapabilityProfile::from_resolved_model(
- &model_id,
- &ai_client.config.model,
- ),
- );
let description_context = tool_context_runtime::build_tool_description_context(
&agent_type,
context.workspace.as_ref(),
@@ -4633,7 +4542,6 @@ impl ExecutionEngine {
turn_prompt_scaffold.system_prompt_message.clone(),
&turn_prompt_scaffold.prepended_prompt_reminders,
baseline_supports_image_understanding,
- baseline_context_profile_policy.compression_contract_limit,
context.workspace.as_ref(),
context.workspace_services.as_ref(),
compression_prefetch.take(),
@@ -4966,7 +4874,6 @@ impl ExecutionEngine {
turn_prompt_scaffold.system_prompt_message.clone(),
&turn_prompt_scaffold.prepended_prompt_reminders,
baseline_supports_image_understanding,
- baseline_context_profile_policy.compression_contract_limit,
context.workspace.as_ref(),
context.workspace_services.as_ref(),
compression_prefetch.take(),
@@ -5210,15 +5117,7 @@ impl ExecutionEngine {
round_index,
"after_round",
);
- after_round_health.log_policy_thresholds(
- &context.session_id,
- &context.dialog_turn_id,
- round_index,
- &context_profile_policy,
- );
-
- let max_consec = context_profile_policy
- .effective_loop_threshold(self.config.max_consecutive_same_tool);
+ let max_consec = self.config.max_consecutive_same_tool.max(1);
if recent_failed_tool_signatures.len() >= max_consec {
let tail = &recent_failed_tool_signatures
[recent_failed_tool_signatures.len() - max_consec..];
diff --git a/src/crates/assembly/core/src/agentic/mod.rs b/src/crates/assembly/core/src/agentic/mod.rs
index 4418e8e438..7364d40e24 100644
--- a/src/crates/assembly/core/src/agentic/mod.rs
+++ b/src/crates/assembly/core/src/agentic/mod.rs
@@ -19,7 +19,6 @@ pub mod execution;
pub mod tools;
// Coordination module
-pub mod context_profile;
pub mod coordination;
pub mod deep_review;
pub mod deep_review_policy;
@@ -57,7 +56,6 @@ mod util;
pub mod insights;
pub use agents::*;
-pub use context_profile::*;
pub use coordination::*;
pub use core::*;
pub use events::{queue, router, types as event_types};
diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/code_review_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/code_review_tool.rs
index 5d1e1844df..83cdf15e49 100644
--- a/src/crates/assembly/core/src/agentic/tools/implementations/code_review_tool.rs
+++ b/src/crates/assembly/core/src/agentic/tools/implementations/code_review_tool.rs
@@ -423,11 +423,6 @@ impl CodeReviewTool {
deep_review_report::compression_contract_for_context(context)
}
- #[cfg(test)]
- fn reliability_contract_limit(agent_type: Option<&str>, model_id: Option<&str>) -> usize {
- deep_review_report::reliability_contract_limit(agent_type, model_id)
- }
-
#[cfg(test)]
fn should_report_compression_preserved(
compression_count: usize,
@@ -1379,18 +1374,6 @@ mod tests {
);
}
- #[test]
- fn deep_review_reliability_contract_limit_uses_context_profile_policy() {
- assert_eq!(
- CodeReviewTool::reliability_contract_limit(Some("DeepReview"), Some("gpt-5")),
- 8
- );
- assert_eq!(
- CodeReviewTool::reliability_contract_limit(Some("DeepReview"), Some("gpt-5-mini")),
- 4
- );
- }
-
#[test]
fn deep_review_defaults_include_reduced_scope_reliability_signal() {
let manifest = json!({
diff --git a/src/crates/execution/agent-runtime/AGENTS.md b/src/crates/execution/agent-runtime/AGENTS.md
index 5463852d2c..de515b07e3 100644
--- a/src/crates/execution/agent-runtime/AGENTS.md
+++ b/src/crates/execution/agent-runtime/AGENTS.md
@@ -162,6 +162,12 @@ so `autotests = false` cannot silently omit a new contract.
## Verification
+For evidence summary bounds and compression contract projection:
+
+```bash
+cargo test --locked -p openbitfun-agent-runtime --no-default-features --features agent-runtime --lib evidence_ledger
+```
+
For next-input suggestion eligibility, surrounding whitespace trimming with
message content preservation, and cancellation:
diff --git a/src/crates/execution/agent-runtime/examples/sdk_minimal.rs b/src/crates/execution/agent-runtime/examples/sdk_minimal.rs
index ad244a2c4f..6876d743dc 100644
--- a/src/crates/execution/agent-runtime/examples/sdk_minimal.rs
+++ b/src/crates/execution/agent-runtime/examples/sdk_minimal.rs
@@ -49,7 +49,7 @@ impl AgentSubmissionPort for ExampleAgentProvider {
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box> {
let compatibility = AgentRuntimeSdkCompatibility::current();
- assert_eq!(compatibility.api_version, 10);
+ assert_eq!(compatibility.api_version, 11);
let provider = Arc::new(ExampleAgentProvider::default());
let events = AgentEventStream::new();
diff --git a/src/crates/execution/agent-runtime/src/context_profile.rs b/src/crates/execution/agent-runtime/src/context_profile.rs
deleted file mode 100644
index 60be16c3b1..0000000000
--- a/src/crates/execution/agent-runtime/src/context_profile.rs
+++ /dev/null
@@ -1,335 +0,0 @@
-//! Adaptive context profile policy.
-//!
-//! Profiles keep context behavior aligned with the shape of the agent workload
-//! without exposing more knobs to the UI.
-
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum ContextProfile {
- LongTask,
- Conversation,
-}
-
-impl ContextProfile {
- pub fn for_agent_type(agent_type: &str) -> Self {
- Self::for_agent_context(agent_type, false)
- }
-
- pub fn for_agent_context(agent_type: &str, is_review_subagent: bool) -> Self {
- if is_review_subagent || is_long_task_agent(agent_type) {
- Self::LongTask
- } else {
- Self::Conversation
- }
- }
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum ModelCapabilityProfile {
- Standard,
- Weak,
-}
-
-impl ModelCapabilityProfile {
- pub fn from_model_id(model_id: Option<&str>) -> Self {
- let Some(model_id) = model_id.map(str::trim).filter(|id| !id.is_empty()) else {
- return Self::Standard;
- };
- let normalized = model_id.to_ascii_lowercase();
- if matches!(normalized.as_str(), "fast" | "primary") {
- return Self::Standard;
- }
-
- // Weak model detection: match suffix-based markers (e.g., "gpt-4o-mini",
- // "gemini-1.5-flash") and exact markers (e.g., "haiku", "mini").
- // Avoid false positives from substring matches (e.g., "gemini-pro" should
- // NOT match "mini" inside "gemini").
- let weak_suffixes = ["-haiku", "-mini", "-small", "-lite", "-flash", "-nano"];
- let weak_exact = ["haiku", "mini", "small", "lite", "flash", "nano"];
- // Also match known weak model name patterns where the marker appears
- // mid-string but is a genuine weak model (e.g., "claude-3-haiku-20240307").
- let weak_mid_patterns = [
- "-haiku-", "-mini-", "-small-", "-lite-", "-flash-", "-nano-",
- ];
- if weak_suffixes.iter().any(|s| normalized.ends_with(s))
- || weak_exact.iter().any(|e| normalized == *e)
- || weak_mid_patterns.iter().any(|p| normalized.contains(p))
- {
- Self::Weak
- } else {
- Self::Standard
- }
- }
-
- pub fn from_resolved_model(resolved_model_id: &str, provider_model_name: &str) -> Self {
- let resolved = Self::from_model_id(Some(resolved_model_id));
- if resolved == Self::Weak {
- resolved
- } else {
- Self::from_model_id(Some(provider_model_name))
- }
- }
-}
-
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub struct ContextProfilePolicy {
- pub profile: ContextProfile,
- pub compression_contract_limit: usize,
- pub subagent_concurrency_cap: usize,
- pub repeated_tool_signature_threshold: usize,
- pub consecutive_failed_command_threshold: usize,
-}
-
-impl ContextProfilePolicy {
- pub fn for_agent_context(
- agent_type: &str,
- is_review_subagent: bool,
- model_capability: ModelCapabilityProfile,
- ) -> Self {
- let profile = ContextProfile::for_agent_context(agent_type, is_review_subagent);
- let mut policy = match profile {
- ContextProfile::LongTask => Self::long_task(),
- ContextProfile::Conversation => Self::conversation(),
- };
-
- if model_capability == ModelCapabilityProfile::Weak {
- policy.apply_weak_model_override();
- }
-
- policy
- }
-
- pub fn for_agent_context_and_model(
- agent_type: &str,
- is_review_subagent: bool,
- resolved_model_id: &str,
- provider_model_name: &str,
- ) -> Self {
- Self::for_agent_context(
- agent_type,
- is_review_subagent,
- ModelCapabilityProfile::from_resolved_model(resolved_model_id, provider_model_name),
- )
- }
-
- pub fn for_subagent_context_and_models(
- agent_type: &str,
- is_review_subagent: bool,
- subagent_model_id: Option<&str>,
- parent_agent_type: Option<&str>,
- parent_is_review_subagent: bool,
- parent_model_id: Option<&str>,
- ) -> Self {
- let child_profile = ContextProfile::for_agent_context(agent_type, is_review_subagent);
- let parent_profile = parent_agent_type
- .map(|agent_type| {
- ContextProfile::for_agent_context(agent_type, parent_is_review_subagent)
- })
- .unwrap_or(ContextProfile::Conversation);
- let profile = if child_profile == ContextProfile::LongTask
- || parent_profile == ContextProfile::LongTask
- {
- ContextProfile::LongTask
- } else {
- ContextProfile::Conversation
- };
- let model_capability = subagent_model_id
- .map(str::trim)
- .filter(|model_id| !model_id.is_empty())
- .map(|model_id| ModelCapabilityProfile::from_model_id(Some(model_id)))
- .or_else(|| {
- parent_model_id
- .map(str::trim)
- .filter(|model_id| !model_id.is_empty())
- .map(|model_id| ModelCapabilityProfile::from_model_id(Some(model_id)))
- })
- .unwrap_or(ModelCapabilityProfile::Standard);
-
- let mut policy = match profile {
- ContextProfile::LongTask => Self::long_task(),
- ContextProfile::Conversation => Self::conversation(),
- };
- if model_capability == ModelCapabilityProfile::Weak {
- policy.apply_weak_model_override();
- }
- policy
- }
-
- pub fn effective_subagent_max_concurrency(&self, configured: usize) -> usize {
- configured.clamp(1, self.subagent_concurrency_cap)
- }
-
- pub fn effective_loop_threshold(&self, configured: usize) -> usize {
- configured
- .max(1)
- .min(self.repeated_tool_signature_threshold.max(1))
- }
-
- pub fn has_repeated_tool_loop(&self, repeated_tool_signature_count: usize) -> bool {
- repeated_tool_signature_count >= self.repeated_tool_signature_threshold.max(1)
- }
-
- pub fn has_consecutive_command_failure_loop(&self, consecutive_failed_commands: usize) -> bool {
- consecutive_failed_commands >= self.consecutive_failed_command_threshold.max(1)
- }
-
- fn long_task() -> Self {
- Self {
- profile: ContextProfile::LongTask,
- compression_contract_limit: 8,
- subagent_concurrency_cap: 5,
- repeated_tool_signature_threshold: 3,
- consecutive_failed_command_threshold: 2,
- }
- }
-
- fn conversation() -> Self {
- Self {
- profile: ContextProfile::Conversation,
- compression_contract_limit: 4,
- subagent_concurrency_cap: 2,
- repeated_tool_signature_threshold: 4,
- consecutive_failed_command_threshold: 3,
- }
- }
-
- fn apply_weak_model_override(&mut self) {
- self.compression_contract_limit = self.compression_contract_limit.min(4);
- self.subagent_concurrency_cap = self.subagent_concurrency_cap.min(2);
- self.repeated_tool_signature_threshold = self.repeated_tool_signature_threshold.min(2);
- self.consecutive_failed_command_threshold =
- self.consecutive_failed_command_threshold.min(2);
- }
-}
-
-fn is_long_task_agent(agent_type: &str) -> bool {
- matches!(
- agent_type,
- "Standard"
- | "DeepReview"
- | "DeepResearch"
- | "ComputerUse"
- | "Ultimate"
- | "SwarmPlanner"
- | "SwarmWorker"
- | "SwarmReviewer"
- ) || agent_type.starts_with("Review")
-}
-
-#[cfg(test)]
-mod tests {
- use super::ModelCapabilityProfile;
-
- #[test]
- fn model_capability_standard_for_empty_or_none() {
- assert_eq!(
- ModelCapabilityProfile::from_model_id(None),
- ModelCapabilityProfile::Standard
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("")),
- ModelCapabilityProfile::Standard
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some(" ")),
- ModelCapabilityProfile::Standard
- );
- }
-
- #[test]
- fn model_capability_standard_for_strong_models() {
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("gpt-4o")),
- ModelCapabilityProfile::Standard
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("claude-sonnet-4")),
- ModelCapabilityProfile::Standard
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("gemini-pro")),
- ModelCapabilityProfile::Standard
- );
- }
-
- #[test]
- fn model_capability_weak_for_haiku() {
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("claude-3-haiku-20240307")),
- ModelCapabilityProfile::Weak
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("anthropic/claude-3-haiku")),
- ModelCapabilityProfile::Weak
- );
- }
-
- #[test]
- fn model_capability_weak_for_mini() {
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("gpt-4o-mini")),
- ModelCapabilityProfile::Weak
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("openai/gpt-4o-mini")),
- ModelCapabilityProfile::Weak
- );
- }
-
- #[test]
- fn model_capability_weak_for_flash() {
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("gemini-1.5-flash")),
- ModelCapabilityProfile::Weak
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("google/gemini-flash")),
- ModelCapabilityProfile::Weak
- );
- }
-
- #[test]
- fn model_capability_weak_for_lite() {
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("qwen-lite")),
- ModelCapabilityProfile::Weak
- );
- }
-
- #[test]
- fn model_capability_weak_for_small() {
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("llama-small")),
- ModelCapabilityProfile::Weak
- );
- }
-
- #[test]
- fn model_capability_weak_for_nano() {
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("gemini-nano")),
- ModelCapabilityProfile::Weak
- );
- }
-
- #[test]
- fn model_capability_from_resolved_model_prefers_resolved() {
- // resolved is weak → returns weak regardless of provider name
- assert_eq!(
- ModelCapabilityProfile::from_resolved_model("gpt-4o-mini", "gpt-4o"),
- ModelCapabilityProfile::Weak
- );
- // resolved is standard, provider is weak → returns weak
- assert_eq!(
- ModelCapabilityProfile::from_resolved_model("gpt-4o", "gpt-4o-mini"),
- ModelCapabilityProfile::Weak
- );
- // both standard → returns standard
- assert_eq!(
- ModelCapabilityProfile::from_resolved_model("gpt-4o", "claude-sonnet"),
- ModelCapabilityProfile::Standard
- );
- }
-}
diff --git a/src/crates/execution/agent-runtime/src/evidence_ledger.rs b/src/crates/execution/agent-runtime/src/evidence_ledger.rs
index 2f0d9fa72b..9c20f29119 100644
--- a/src/crates/execution/agent-runtime/src/evidence_ledger.rs
+++ b/src/crates/execution/agent-runtime/src/evidence_ledger.rs
@@ -8,6 +8,8 @@ use std::time::{SystemTime, UNIX_EPOCH};
const MAX_PARTIAL_OUTPUT_BYTES: usize = 8_000;
pub const EVIDENCE_LEDGER_SCHEMA_VERSION: u32 = 1;
+/// Per-category evidence bound shared by compression and reliability reporting.
+pub const DEFAULT_COMPRESSION_CONTRACT_LIMIT: usize = 8;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum EvidenceLedgerTargetKind {
@@ -934,6 +936,34 @@ mod tests {
assert!(partial_output.is_char_boundary(partial_output.len()));
}
+ #[test]
+ fn compression_contract_keeps_bounded_recent_evidence_without_pruning_the_ledger() {
+ let ledger = SessionEvidenceLedger::new();
+ for index in 0..12 {
+ ledger.append(
+ EvidenceLedgerEvent::new(
+ "session-a",
+ "turn-a",
+ "ExecCommand",
+ EvidenceLedgerTargetKind::Command,
+ format!("cargo test test_{index}"),
+ EvidenceLedgerEventStatus::Failed,
+ format!("Test {index} failed"),
+ )
+ .with_touched_files(vec![format!("src/file_{index}.rs")]),
+ );
+ }
+ let contract: CompressionContract = ledger
+ .summary_for_session("session-a", super::DEFAULT_COMPRESSION_CONTRACT_LIMIT)
+ .into();
+ assert_eq!(contract.touched_files.len(), 8);
+ assert_eq!(contract.blocking_failures.len(), 8);
+ assert_eq!(contract.verification_commands.len(), 8);
+ assert_eq!(contract.touched_files.first().unwrap(), "src/file_11.rs");
+ assert_eq!(contract.touched_files.last().unwrap(), "src/file_4.rs");
+ assert_eq!(ledger.events_for_session("session-a").len(), 12);
+ }
+
#[test]
fn summary_projects_into_compression_contract() {
let ledger = SessionEvidenceLedger::new();
diff --git a/src/crates/execution/agent-runtime/src/lib.rs b/src/crates/execution/agent-runtime/src/lib.rs
index 8610f23fa4..14d4c73d4f 100644
--- a/src/crates/execution/agent-runtime/src/lib.rs
+++ b/src/crates/execution/agent-runtime/src/lib.rs
@@ -13,8 +13,6 @@ pub mod channel_routing;
pub mod checkpoint;
#[cfg(feature = "agent-runtime")]
pub mod compression_prefetch;
-#[cfg(feature = "agent-runtime")]
-pub mod context_profile;
#[cfg(any(feature = "agent-runtime", feature = "definition-contracts"))]
pub mod custom_agent;
#[cfg(feature = "agent-runtime")]
diff --git a/src/crates/execution/agent-runtime/src/sdk.rs b/src/crates/execution/agent-runtime/src/sdk.rs
index 7a948a8e40..c610bd6952 100644
--- a/src/crates/execution/agent-runtime/src/sdk.rs
+++ b/src/crates/execution/agent-runtime/src/sdk.rs
@@ -8,7 +8,7 @@
use std::sync::Arc;
-pub const AGENT_RUNTIME_SDK_API_VERSION: u32 = 10;
+pub const AGENT_RUNTIME_SDK_API_VERSION: u32 = 11;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
@@ -34,7 +34,6 @@ impl AgentRuntimeSdkCompatibility {
}
}
-pub use crate::context_profile::{ContextProfile, ContextProfilePolicy, ModelCapabilityProfile};
pub use crate::dialog_turn::TurnTokenUsage;
pub use crate::event_source::{AgentEventReceiver, AgentEventSource, AgentSessionEventReceiver};
pub use crate::permission::{
diff --git a/src/crates/execution/agent-runtime/tests/agent_definition_contracts.rs b/src/crates/execution/agent-runtime/tests/agent_definition_contracts.rs
index 5d8fc901f2..5a0785fe1f 100644
--- a/src/crates/execution/agent-runtime/tests/agent_definition_contracts.rs
+++ b/src/crates/execution/agent-runtime/tests/agent_definition_contracts.rs
@@ -3,8 +3,6 @@
#[path = "agent_definition_contracts/agent_registry_contracts.rs"]
mod agent_registry_contracts;
-#[path = "agent_definition_contracts/context_profile.rs"]
-mod context_profile;
#[path = "agent_definition_contracts/custom_agent_mode_contracts.rs"]
mod custom_agent_mode_contracts;
#[path = "agent_definition_contracts/custom_subagent_contracts.rs"]
diff --git a/src/crates/execution/agent-runtime/tests/agent_definition_contracts/context_profile.rs b/src/crates/execution/agent-runtime/tests/agent_definition_contracts/context_profile.rs
deleted file mode 100644
index 71fb48f466..0000000000
--- a/src/crates/execution/agent-runtime/tests/agent_definition_contracts/context_profile.rs
+++ /dev/null
@@ -1,159 +0,0 @@
-use openbitfun_agent_runtime::context_profile::{
- ContextProfile, ContextProfilePolicy, ModelCapabilityProfile,
-};
-
-#[test]
-fn context_profile_maps_long_running_agents_to_long_task_profile() {
- for agent_type in [
- "Standard",
- "DeepReview",
- "DeepResearch",
- "ComputerUse",
- "ReviewFrontend",
- "ReviewSecurity",
- ] {
- assert_eq!(
- ContextProfile::for_agent_type(agent_type),
- ContextProfile::LongTask,
- "{agent_type} should use the long-task profile"
- );
- }
-}
-
-#[test]
-fn context_profile_maps_conversation_agents_to_conversation_profile() {
- for agent_type in ["Cowork", "Claw", "unknown-custom-agent"] {
- assert_eq!(
- ContextProfile::for_agent_type(agent_type),
- ContextProfile::Conversation,
- "{agent_type} should use the conversation profile"
- );
- }
-}
-
-#[test]
-fn context_profile_review_custom_subagents_can_be_promoted_to_long_task_profile() {
- assert_eq!(
- ContextProfile::for_agent_context("legal-domain-reviewer", true),
- ContextProfile::LongTask
- );
- assert_eq!(
- ContextProfile::for_agent_context("legal-domain-reviewer", false),
- ContextProfile::Conversation
- );
-}
-
-#[test]
-fn context_profile_long_task_policy_preserves_current_context_defaults() {
- let policy = ContextProfilePolicy::for_agent_context(
- "DeepReview",
- false,
- ModelCapabilityProfile::Standard,
- );
-
- assert_eq!(policy.profile, ContextProfile::LongTask);
- assert_eq!(policy.compression_contract_limit, 8);
- assert_eq!(policy.subagent_concurrency_cap, 5);
- assert_eq!(policy.repeated_tool_signature_threshold, 3);
- assert_eq!(policy.consecutive_failed_command_threshold, 2);
-}
-
-#[test]
-fn context_profile_conversation_policy_keeps_more_recent_chat_context() {
- let policy =
- ContextProfilePolicy::for_agent_context("Cowork", false, ModelCapabilityProfile::Standard);
-
- assert_eq!(policy.profile, ContextProfile::Conversation);
- assert_eq!(policy.compression_contract_limit, 4);
- assert_eq!(policy.subagent_concurrency_cap, 2);
- assert_eq!(policy.repeated_tool_signature_threshold, 4);
- assert_eq!(policy.consecutive_failed_command_threshold, 3);
-}
-
-#[test]
-fn context_profile_weak_model_override_shortens_contract_and_caps_fanout() {
- let standard = ContextProfilePolicy::for_agent_context(
- "DeepReview",
- false,
- ModelCapabilityProfile::Standard,
- );
- let weak =
- ContextProfilePolicy::for_agent_context("DeepReview", false, ModelCapabilityProfile::Weak);
-
- assert_eq!(weak.profile, ContextProfile::LongTask);
- assert!(weak.compression_contract_limit < standard.compression_contract_limit);
- assert!(weak.subagent_concurrency_cap < standard.subagent_concurrency_cap);
- assert!(weak.repeated_tool_signature_threshold < standard.repeated_tool_signature_threshold);
- assert_eq!(weak.compression_contract_limit, 4);
- assert_eq!(weak.subagent_concurrency_cap, 2);
- assert_eq!(weak.repeated_tool_signature_threshold, 2);
-}
-
-#[test]
-fn context_profile_model_capability_profile_only_marks_explicit_weak_models() {
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("claude-3-haiku")),
- ModelCapabilityProfile::Weak
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("gpt-5.4-mini")),
- ModelCapabilityProfile::Weak
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(Some("fast")),
- ModelCapabilityProfile::Standard,
- "configured model slots should not be treated as weak before resolving"
- );
- assert_eq!(
- ModelCapabilityProfile::from_model_id(None),
- ModelCapabilityProfile::Standard
- );
-}
-
-#[test]
-fn context_profile_configured_subagent_concurrency_is_capped_by_policy() {
- let long_task = ContextProfilePolicy::for_agent_context(
- "DeepReview",
- false,
- ModelCapabilityProfile::Standard,
- );
- let conversation =
- ContextProfilePolicy::for_agent_context("Cowork", false, ModelCapabilityProfile::Standard);
-
- assert_eq!(long_task.effective_subagent_max_concurrency(64), 5);
- assert_eq!(long_task.effective_subagent_max_concurrency(3), 3);
- assert_eq!(conversation.effective_subagent_max_concurrency(64), 2);
- assert_eq!(conversation.effective_subagent_max_concurrency(1), 1);
-}
-
-#[test]
-fn context_profile_subagent_policy_combines_parent_workload_and_child_model() {
- let policy = ContextProfilePolicy::for_subagent_context_and_models(
- "custom-security-reviewer",
- true,
- Some("claude-3-haiku"),
- Some("DeepReview"),
- false,
- Some("gpt-5"),
- );
-
- assert_eq!(policy.profile, ContextProfile::LongTask);
- assert_eq!(policy.compression_contract_limit, 4);
- assert_eq!(policy.subagent_concurrency_cap, 2);
- assert_eq!(policy.repeated_tool_signature_threshold, 2);
-}
-
-#[test]
-fn context_profile_subagent_policy_inherits_parent_long_task_when_child_is_plain() {
- let policy = ContextProfilePolicy::for_subagent_context_and_models(
- "Explore",
- false,
- None,
- Some("DeepReview"),
- false,
- Some("gpt-5"),
- );
-
- assert_eq!(policy.profile, ContextProfile::LongTask);
- assert_eq!(policy.subagent_concurrency_cap, 5);
-}
diff --git a/src/crates/execution/agent-runtime/tests/agent_session_contracts/sdk_smoke.rs b/src/crates/execution/agent-runtime/tests/agent_session_contracts/sdk_smoke.rs
index 6fc5fc1d7f..660596492f 100644
--- a/src/crates/execution/agent-runtime/tests/agent_session_contracts/sdk_smoke.rs
+++ b/src/crates/execution/agent-runtime/tests/agent_session_contracts/sdk_smoke.rs
@@ -87,7 +87,7 @@ impl AgentModeCatalogPort for FakeModeCatalog {
fn sdk_facade_exposes_versioned_preview_compatibility_contract() {
let compatibility = AgentRuntimeSdkCompatibility::current();
- assert_eq!(compatibility.api_version, 10);
+ assert_eq!(compatibility.api_version, 11);
assert_eq!(compatibility.crate_version, env!("CARGO_PKG_VERSION"));
assert_eq!(compatibility.stability, AgentRuntimeSdkStability::Preview);
}
diff --git a/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.test.tsx b/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.test.tsx
index 7d3d926cc6..bbde8f635f 100644
--- a/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.test.tsx
+++ b/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.test.tsx
@@ -15,6 +15,8 @@ const mocks = vi.hoisted(() => ({
openBtwSessionInAuxPane: vi.fn(),
listeners: new Set<() => void>(),
includeChildSession: true,
+ includeChildTurn: true,
+ childPersistedStatus: undefined as 'completed' | undefined,
locale: 'en-US',
modelName: 'Test model',
childTurnStatus: 'processing' as DialogTurn['status'],
@@ -30,6 +32,7 @@ vi.mock('@/infrastructure/i18n/hooks/useI18n', () => ({
return names[key.split('.').at(-1) as keyof typeof names];
}
if (key === 'flowChatHeader.agentTreeStatus.running') return 'Running';
+ if (key === 'toolCards.default.preparing') return 'Preparing';
if (key === 'flowChatHeader.agentTreeStatus.completed') return 'Completed';
if (key === 'toolCards.taskTool.defaultAgentKind') return 'Agent';
if (typeof options?.defaultValue === 'string') return options.defaultValue;
@@ -74,13 +77,14 @@ vi.mock('../store/FlowChatStore', () => ({
title: 'SwarmWorker: inspect parser',
createdAt: 1000,
status: 'active',
+ persistedStatus: mocks.childPersistedStatus,
needsUserAttention: mocks.needsUserAttention,
config: { agentType: 'SwarmWorker', modelName: mocks.modelName },
- dialogTurns: [{
+ dialogTurns: mocks.includeChildTurn ? [{
id: 'child-turn',
status: mocks.childTurnStatus,
modelRounds: [],
- }],
+ }] : [],
});
}
return { sessions };
@@ -175,6 +179,8 @@ describeWithJsdom('AgentControlToolCard', () => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
mocks.includeChildSession = true;
+ mocks.includeChildTurn = true;
+ mocks.childPersistedStatus = undefined;
mocks.locale = 'en-US';
mocks.modelName = 'Test model';
mocks.childTurnStatus = 'processing';
@@ -243,6 +249,76 @@ describeWithJsdom('AgentControlToolCard', () => {
},
);
+ it.each([
+ { status: 'preparing' },
+ { status: 'streaming' },
+ { status: 'receiving' },
+ { status: 'running', isParamsStreaming: true },
+ ] as const)('shows Preparing while spawn parameters stream: %j', async (streamingState) => {
+ mocks.includeChildSession = false;
+ const render = (overrides: Partial) => act(async () => root.render(
+ ,
+ ));
+
+ await render(streamingState);
+ expect(container.querySelector('[data-openbitfun-part="agentSummary"]')?.textContent).toBe(flowChatEn.subagentIdentity.names.cloudHopper);
+ expect(container.querySelector('[data-openbitfun-part="statusSlot"]')).toBeNull();
+ expect(container.querySelector('[data-openbitfun-part="agentStatus"]')?.textContent).toBe('Preparing');
+ expect(container.textContent).not.toContain('Running');
+ expect(container.querySelector('[data-agent-capsule-trigger]')?.getAttribute('aria-label')).not.toContain('Running');
+
+ mocks.includeChildSession = true;
+ await render({ status: 'running', isParamsStreaming: false });
+ expect(container.querySelector('[data-openbitfun-part="agentStatus"]')?.textContent).toBe('Running');
+ });
+
+ it.each([false, true])('keeps Running through the spawn receipt and child hydration (JSON result: %s)', async (serialized) => {
+ mocks.includeChildSession = false;
+ mocks.includeChildTurn = false;
+ const item = agentToolItem('AgentSpawn', {
+ status: 'running', subagentSessionId: undefined, subagentDialogTurnId: undefined,
+ });
+ const render = () => act(async () => root.render(
+ ,
+ ));
+ const publish = () => act(() => { mocks.listeners.forEach(listener => listener()); });
+ const expectRunning = () => {
+ expect(container.querySelector('[data-openbitfun-part="agentStatus"]')?.textContent).toBe('Running');
+ expect(container.querySelector('[data-openbitfun-tool-card="agent-control"]')?.getAttribute('data-openbitfun-status')).toBe('running');
+ };
+
+ await render();
+ expectRunning();
+ const receipt = { status: 'started', agent_id: 'worker', bg_task_id: 'worker_bg1' };
+ item.status = 'completed';
+ item.toolResult = { success: true, result: serialized ? JSON.stringify(receipt) : receipt };
+ await render();
+ expectRunning();
+ expect(container.querySelector('[data-openbitfun-part="agentSummary"]')?.textContent).toBe('toolCards.interaction.unknownAgent');
+
+ mocks.includeChildSession = true;
+ publish();
+ expectRunning();
+ expect(container.querySelector('[data-openbitfun-part="agentSummary"]')?.textContent).toBe(flowChatEn.subagentIdentity.names.cloudHopper);
+
+ mocks.includeChildTurn = true;
+ mocks.childTurnStatus = 'pending';
+ publish();
+ expectRunning();
+ mocks.childTurnStatus = 'processing';
+ publish();
+ expectRunning();
+ mocks.childTurnStatus = 'completed';
+ publish();
+ expect(container.querySelector('[data-openbitfun-part="agentStatus"]')).toBeNull();
+
+ mocks.includeChildTurn = false;
+ mocks.childPersistedStatus = 'completed';
+ publish();
+ expect(container.querySelector('[data-openbitfun-part="agentStatus"]')).toBeNull();
+ expect(container.querySelector('[data-openbitfun-tool-card="agent-control"]')?.getAttribute('data-openbitfun-status')).toBe('completed');
+ });
+
it('keeps a finishing child labelled Running and stops the highlight when waiting or complete', async () => {
await act(async () => root.render(
,
@@ -291,6 +367,10 @@ describeWithJsdom('AgentControlToolCard', () => {
const button = container.querySelector('[data-agent-capsule-trigger]')!;
expect(button.getAttribute('aria-disabled')).toBe('true');
expect(button.hasAttribute('aria-expanded')).toBe(false);
+ expect(container.querySelector('[data-openbitfun-part="agentSummary"]')?.textContent)
+ .toBe('toolCards.interaction.unknownAgent');
+ expect(container.querySelector('[data-openbitfun-part="statusSlot"]')).toBeNull();
+ expect(container.querySelector('[data-openbitfun-part="agentStatus"]')?.textContent).toBe('Preparing');
await act(async () => button.click());
expect(mocks.openBtwSessionInAuxPane).not.toHaveBeenCalled();
mocks.includeChildSession = true;
@@ -405,4 +485,18 @@ describeWithJsdom('AgentControlToolCard', () => {
expect(mocks.openBtwSessionInAuxPane).toHaveBeenCalledOnce();
expect(document.querySelector('[role="tooltip"]')).toBeNull();
});
+
+ it('hides model metadata when an AgentSpawn has no model information', async () => {
+ mocks.modelName = '';
+ const item = agentToolItem('AgentSpawn');
+ item.toolCall!.input = { agent_type: 'SwarmWorker', prompt: 'Inspect the parser.' };
+ await act(async () => root.render(
+ ,
+ ));
+
+ expect(container.querySelector('[data-openbitfun-part="agentModel"]')).toBeNull();
+ const popup = await revealPreview();
+ expect(popup.querySelector('[data-openbitfun-part="previewModel"]')).toBeNull();
+ expect(popup.textContent).not.toContain(flowChatEn.subagentIdentity.preview.model);
+ });
});
diff --git a/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.tsx b/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.tsx
index 318243d875..c717802105 100644
--- a/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.tsx
+++ b/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.tsx
@@ -19,7 +19,7 @@ import {
import { openBtwSessionInAuxPane } from '../services/btwSessionPane';
import { AgentControlToolCard as AgentControlToolCardView } from '@openbitfun/ui/flow-chat';
import { AgentInteractionToolCard } from './AgentInteractionToolCard';
-import { resolveInteractionAgentSessionId } from './toolInteractionModel';
+import { readToolRecord, resolveInteractionAgentSessionId } from './toolInteractionModel';
const PARAMETER_STREAMING_STATUSES = new Set([
'preparing',
@@ -141,9 +141,19 @@ const AgentSpawnCard: React.FC = ({
const linkedSession = linkedSubagentSessionId
? flowChatStore.getState().sessions.get(linkedSubagentSessionId)
: undefined;
- const lifecycle = linkedSession
+ const linkedLifecycle = linkedSession
? sessionLineageLifecycleForSession(linkedSession)
- : fallbackLifecycle(status);
+ : undefined;
+ // A successful spawn receipt completes the launch, not the background task.
+ // Keep the active display until the child's first turn supplies its lifecycle.
+ const launchStarted = (status === 'completed' || status === 'confirmed')
+ && toolItem.toolResult?.success !== false
+ && readToolRecord(toolItem.toolResult?.result).status === 'started';
+ const awaitingFirstTurn = !linkedSession?.dialogTurns.length
+ && (!linkedSession || linkedLifecycle === 'idle');
+ const lifecycle = awaitingFirstTurn && (status === 'running' || launchStarted)
+ ? 'running'
+ : linkedLifecycle ?? fallbackLifecycle(status);
const agentDisplayName = linkedSubagentSessionId
? t(resolveSubagentNameKey(linkedSubagentSessionId)) : t('toolCards.interaction.unknownAgent');
const stableAgentType = linkedSession?.mode?.trim()
@@ -154,7 +164,7 @@ const AgentSpawnCard: React.FC = ({
|| linkedSession?.config?.modelName?.trim()
|| toolItem.subagentModelId?.trim()
|| readString(params, 'model_id', 'modelId')
- || t('subagentIdentity.preview.unknownModel');
+ || '';
const isParameterStreaming = Boolean(toolItem.isParamsStreaming)
|| PARAMETER_STREAMING_STATUSES.has(status);
const displayStatus = isParameterStreaming
@@ -242,7 +252,7 @@ const AgentSpawnCard: React.FC = ({
description: t('subagentIdentity.preview.description'),
},
}}
- statusLabel={lifecycle === 'completed' ? undefined
+ statusLabel={isParameterStreaming ? t('toolCards.default.preparing') : lifecycle === 'completed' ? undefined
: t(`flowChatHeader.agentTreeStatus.${lifecycle === 'finishing' ? 'running' : lifecycle}`)}
statusTone={statusTone}
onOpenAgent={canOpenSession ? handleOpenSession : undefined}