Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 5 additions & 9 deletions src/crates/assembly/core/src/agentic/coordination/coordinator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,7 @@ use crate::agentic::skill_agent_snapshot::{
use crate::agentic::tools::pipeline::{
PrimaryModelFacts, SubagentParentInfo, ToolExecutionContext, ToolExecutionOptions, ToolPipeline,
};
use crate::agentic::tools::{
miniapp_agent_run_tool_restrictions,
tool_restrictions_for_delegation_policy as runtime_tool_restrictions_for_delegation_policy,
ToolRuntimeRestrictions,
};
use crate::agentic::tools::{miniapp_agent_run_tool_restrictions, ToolRuntimeRestrictions};
use crate::agentic::workspace::WorkspaceServices;
use crate::agentic::WorkspaceBinding;
use crate::native_hooks::{self, NativeHookSessionFacts};
Expand Down Expand Up @@ -12843,10 +12839,9 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
context: request.context,
permission_runtime_ceiling: Some(request.permission_runtime_ceiling),
delegation_policy: request.delegation_policy,
// Launch tools enforce delegation policy without changing the catalog.
runtime_tool_restrictions: runtime_tool_restrictions_for_session_lifetime(
runtime_tool_restrictions_for_delegation_policy(
request.delegation_policy,
),
ToolRuntimeRestrictions::default(),
transient,
),
prompt_cache_source_session_id: None,
Expand Down Expand Up @@ -12944,8 +12939,9 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
context: request.context,
permission_runtime_ceiling: Some(request.permission_runtime_ceiling),
delegation_policy: request.delegation_policy,
// Match forks: keep launch tools visible and enforce delegation at invocation.
runtime_tool_restrictions: runtime_tool_restrictions_for_session_lifetime(
runtime_tool_restrictions_for_delegation_policy(request.delegation_policy),
ToolRuntimeRestrictions::default(),
parent_transient,
),
prompt_cache_source_session_id: None,
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ async fn fresh_subagent_inherits_matching_parent_worktree_binding() {
.await
.expect("fresh subagent request should resolve");

assert!(!resolved.delegation_policy.allow_subagent_spawn);
for tool_name in ["AgentSpawn", "AgentFork"] {
assert!(resolved
.runtime_tool_restrictions
.is_tool_allowed(tool_name));
}
assert_eq!(
resolved.session_config.workspace_path.as_deref(),
Some(workspace_path.as_str())
Expand Down Expand Up @@ -201,6 +207,12 @@ async fn fresh_subagent_inherits_transient_parent_persistence_boundary() {
.expect("fresh subagent request should resolve");

assert!(resolved.transient);
assert!(!resolved.delegation_policy.allow_subagent_spawn);
for tool_name in ["AgentSpawn", "AgentFork"] {
assert!(resolved
.runtime_tool_restrictions
.is_tool_allowed(tool_name));
}
assert!(!resolved
.runtime_tool_restrictions
.is_tool_allowed("SessionControl"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,17 @@ impl ExecutionEngine {
"The external agent does not expose its current model context".into(),
));
}
if session.kind != openbitfun_core_types::SessionKind::Standard {
// BTW inherits a normal conversation's catalog and carries host-assigned
// parent ownership, even before its first turn. Other ephemeral workers
// may have execution-only restrictions that inspection cannot reconstruct.
let has_conversation_parent = session
.created_by
.as_deref()
.and_then(|owner| owner.strip_prefix("session-"))
.is_some_and(|parent_id| !parent_id.is_empty());
if session.kind == openbitfun_core_types::SessionKind::EphemeralChild
&& !has_conversation_parent
{
return Err(OpenBitFunError::NotImplemented(
"Delegated session context requires its execution-scoped tool restrictions".into(),
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ impl SessionManager {
Some(session) => session,
None => persistence.load_session_header(storage, session_id).await?,
};
if !self.should_persist_session_id(session_id) {
return self.read_in_memory_context_estimate_inputs(session);
}
let boundary = persistence
.load_session_revert_state(storage, session_id)
.await?
Expand Down Expand Up @@ -113,4 +116,53 @@ impl SessionManager {
cache_ttl: self.config.prompt_cache_policy.cache_ttl,
})
}

fn read_in_memory_context_estimate_inputs(
&self,
session: Session,
) -> OpenBitFunResult<ContextEstimateInputs> {
let session_id = &session.session_id;
if !self.context_store.has_session(session_id) {
return Err(OpenBitFunError::service(
"Temporary session context is unavailable for context inspection",
));
}
let turn = self
.transient_turns
.get(session_id)
.and_then(|history| history.turns.last().cloned());
if turn.is_none() && !session.dialog_turn_ids.is_empty() {
return Err(OpenBitFunError::service(
"Temporary session history is unavailable for context inspection",
));
}
let messages = self.context_store.get_context_messages(session_id);
let prompt_cache = self
.prompt_cache_store
.get_cache(session_id)
.unwrap_or_default();
let listing_baseline = self
.skill_agent_baseline_override_snapshot_store
.get(session_id)
.map(|snapshot| snapshot.value().clone())
.or_else(|| {
self.turn_skill_agent_snapshot_store
.get_snapshot(session_id, 0)
});
Ok(ContextEstimateInputs {
session,
messages,
prompt_cache,
listing_baseline,
turn_id: turn
.as_ref()
.map(|turn| turn.turn_id.clone())
.unwrap_or_default(),
turn_metadata: turn
.as_ref()
.and_then(|turn| turn.user_message.metadata.clone()),
turn_index: turn.as_ref().map(|turn| turn.turn_index).unwrap_or(0),
cache_ttl: self.config.prompt_cache_policy.cache_ttl,
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,162 @@ use crate::service::session::{DialogTurnData, SessionContextUsage, SessionContex
use std::path::{Path, PathBuf};
use std::sync::Arc;

#[tokio::test]
async fn current_context_estimate_reads_temporary_turns_caches_and_compression_only_from_memory() {
use crate::agentic::core::{MessageSemanticKind, SessionKind};
use crate::agentic::session::{SystemPromptCacheIdentity, UserContextCacheIdentity};
use crate::agentic::skill_agent_snapshot::{SkillSnapshotEntry, TurnSkillAgentSnapshot};

let workspace = TestWorkspace::new();
let persistence = Arc::new(PersistenceManager::new(workspace.path_manager()).unwrap());
let manager = test_manager(persistence.clone());
let session = manager
.create_session_with_id_and_details(
None,
"BTW".into(),
"Standard".into(),
SessionConfig {
workspace_path: Some(workspace.path().to_string_lossy().into_owned()),
..Default::default()
},
Some("session-parent".into()),
SessionKind::EphemeralChild,
)
.await
.unwrap();
let id = &session.session_id;
let storage = manager.effective_session_storage_path(id).await.unwrap();
let inherited = Message::user("Inherited context".into());
manager
.replace_context_messages(id, vec![inherited.clone()])
.await;
let initial = manager
.read_context_estimate_inputs(&storage, id)
.await
.unwrap();
assert!(initial.turn_id.is_empty());
assert!(initial.prompt_cache.is_empty());
assert!(initial.listing_baseline.is_none());
assert_eq!(initial.messages[0].id, inherited.id);
let root = if persistence.is_resolved_sessions_dir(&storage) {
storage.clone()
} else {
persistence.path_manager().project_sessions_dir(&storage)
};
let child_dir = root.join(id);
assert!(!child_dir.exists());

manager
.remember_system_prompt(
id,
SystemPromptCacheIdentity::new("system"),
"Cached system".into(),
)
.await;
manager
.remember_user_context(
id,
UserContextCacheIdentity::new("rules"),
"Cached rules".into(),
)
.await;
let baseline = TurnSkillAgentSnapshot {
skills: vec![SkillSnapshotEntry {
name: "inherited-skill".into(),
description: "Inherited skill baseline".into(),
location: "/workspace/skill.md".into(),
}],
subagents: Vec::new(),
deferred_tools: None,
};
manager
.skill_agent_baseline_override_snapshot_store
.insert(id.clone(), baseline.clone());
for index in 0..2 {
let turn_id = manager
.start_dialog_turn(
id,
"Standard".into(),
format!("Question {index}"),
Some(format!("btw-turn-{index}")),
None,
Some(serde_json::json!({"kind": "btw", "questionIndex": index})),
)
.await
.unwrap();
if index == 0 {
manager
.complete_dialog_turn(
id,
&turn_id,
"Answer".into(),
&[],
Default::default(),
Some("stop".into()),
Some(true),
)
.await
.unwrap();
manager.reset_session_state_if_processing(id, &turn_id);
}
}
let mut summary = Message::user("Compressed temporary conversation".into());
summary.metadata.semantic_kind = Some(MessageSemanticKind::CompressionSummary);
manager
.replace_context_messages(id, vec![summary.clone()])
.await;
assert!(
!child_dir.exists(),
"temporary history and caches must not be persisted"
);

// Even an unrelated durable record at this ID cannot supply recovery facts.
std::fs::create_dir_all(&child_dir).unwrap();
let poison = child_dir.join("session-revert.json");
std::fs::write(&poison, b"not temporary session state").unwrap();
let inputs = manager
.read_context_estimate_inputs(&storage, id)
.await
.unwrap();
assert_eq!(inputs.turn_id, "btw-turn-1");
assert_eq!(inputs.turn_index, 1);
assert_eq!(inputs.turn_metadata.unwrap()["questionIndex"], 1);
assert_eq!(inputs.messages.len(), 1);
assert_eq!(inputs.messages[0].id, summary.id);
assert_eq!(
inputs.prompt_cache.system_prompt.unwrap().text.content,
"Cached system"
);
assert_eq!(
inputs.prompt_cache.user_context.unwrap().text.content,
"Cached rules"
);
assert_eq!(inputs.listing_baseline, Some(baseline));
assert_eq!(
std::fs::read(&poison).unwrap(),
b"not temporary session state"
);
assert_eq!(std::fs::read_dir(&child_dir).unwrap().count(), 1);

manager.context_store.delete_session(id);
assert!(manager
.read_context_estimate_inputs(&storage, id)
.await
.err()
.expect("missing context must fail")
.to_string()
.contains("Temporary session context is unavailable"));
manager.context_store.replace_context(id, vec![summary]);
manager.transient_turns.remove(id);
assert!(manager
.read_context_estimate_inputs(&storage, id)
.await
.err()
.expect("missing temporary history must fail")
.to_string()
.contains("Temporary session history is unavailable"));
}

#[tokio::test]
async fn current_context_estimate_reads_compression_forks_and_legacy_snapshots_without_writes() {
use openbitfun_services_core::session::{SessionBranchBoundary, SessionBranchRequest};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1013,7 +1013,7 @@ async fn validate_input_accepts_fork_context_with_caller_selected_agent_id() {
}

#[tokio::test]
async fn call_impl_rejects_nested_subagent_delegation() {
async fn visible_launch_tools_reject_nested_subagent_delegation() {
let policy = DelegationPolicy::top_level().spawn_child();
let context = ToolUseContext {
tool_call_id: Some("tool-call-1".to_string()),
Expand All @@ -1039,6 +1039,19 @@ async fn call_impl_rejects_nested_subagent_delegation() {
runtime_handles: openbitfun_runtime_ports::ToolRuntimeHandles::default(),
};

let manifest = crate::agentic::tools::resolve_tool_manifest(
&["AgentSpawn".into(), "AgentFork".into()],
&Default::default(),
&context,
)
.await;
for tool_name in ["AgentSpawn", "AgentFork"] {
assert!(manifest
.tool_definitions
.iter()
.any(|definition| definition.name == tool_name));
}

let error = AgentExecutionTool::new()
.call_impl(
&json!({
Expand All @@ -1055,6 +1068,20 @@ async fn call_impl_rejects_nested_subagent_delegation() {
assert!(error
.to_string()
.contains("Recursive subagent delegation is blocked. Use direct tools instead."));
let spawn_error = AgentSpawnTool::new()
.call_impl(
&json!({
"agent_id": "repo-inspector",
"prompt": "Inspect the repo",
"agent_type": "Explore"
}),
&context,
)
.await
.expect_err("visible launch tools must enforce nested delegation restrictions");
assert!(spawn_error
.to_string()
.contains("Recursive subagent delegation is blocked"));
let fork_error = AgentForkTool::new()
.call_impl(
&json!({"agent_id":"review-fork", "prompt":"Review the inherited findings"}),
Expand Down
Loading
Loading