Route every extension operation through a lease (#12723)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Douwe Osinga
2026-10-06 20:25:48 +00:00
committed by GitHub
parent 540df77c30
commit d26a422c24
30 changed files with 520 additions and 1494 deletions
+13 -16
View File
@@ -1448,7 +1448,8 @@ enum McpProbeElicitation {
}
async fn handle_mcp_probe(extension_command: String, script_path: Option<String>) -> Result<()> {
use goose::agents::{Agent, AgentConfig, ToolCallContext};
use goose::agents::extension_manager::CallRequest;
use goose::agents::{Agent, AgentConfig};
use goose::config::ExtensionConfig;
use rmcp::model::{ElicitRequestParams, ElicitResult, ElicitationAction};
use tokio_util::sync::CancellationToken;
@@ -1562,46 +1563,42 @@ async fn handle_mcp_probe(extension_command: String, script_path: Option<String>
let session_id = session.id.as_str();
agent.add_extension(extension, session_id).await?;
let working_dir = std::env::current_dir()?;
let mut results = Vec::new();
for step in script.steps {
let lease = agent
.extension_manager
.current_lease(session_id, Some(&working_dir))
.await;
let result = match step {
McpProbeStep::ListTools => serde_json::json!({
"action": "listTools",
"result": agent.extension_manager.list_tools_from_extension(
session_id,
"result": lease.list_tools_from_extension(
"probe",
CancellationToken::new(),
).await?,
}),
McpProbeStep::ListPrompts => serde_json::json!({
"action": "listPrompts",
"result": agent.extension_manager.list_prompts_from_extension(
session_id,
"result": lease.list_prompts_from_extension(
"probe",
CancellationToken::new(),
).await?,
}),
McpProbeStep::ListResources => serde_json::json!({
"action": "listResources",
"result": agent.extension_manager.list_resources_result_from_extension(
session_id,
"result": lease.list_resources_result_from_extension(
"probe",
CancellationToken::new(),
).await?,
}),
McpProbeStep::CallTool { name, arguments } => {
let scoped_name = format!("probe__{name}");
let ctx = ToolCallContext::new(
session_id.to_string(),
Some(std::env::current_dir()?),
Some("mcp-probe-tool-call".to_string()),
);
let result = agent
.extension_manager
.dispatch_tool_call(
&ctx,
let result = lease
.call(
rmcp::model::CallToolRequestParams::new(scoped_name)
.with_arguments(arguments),
CallRequest::new("mcp-probe-tool-call"),
CancellationToken::new(),
)
.await?
@@ -232,7 +232,6 @@ where
bundled: None,
available_tools: vec![],
},
Some(session.working_dir.clone()),
Arc::new(mock_client),
None,
)
+3 -6
View File
@@ -1140,13 +1140,10 @@ impl GooseAcpAgent {
.find(|extension| extension.name() == "developer")
.unwrap_or_else(|| builtin_to_extension_config("developer"));
if let Err(error) = agent
agent
.extension_manager
.add_session_client(developer_config, &session.id, client, info)
.await
{
warn!(%error, "Failed to install ACP developer client");
}
.add_client(developer_config, client, info)
.await;
}
async fn prepare_acp_session_agent(
+5 -6
View File
@@ -23,12 +23,11 @@ impl GooseAcpAgent {
};
let agent = self.get_session_agent(&session_id).await?;
let mut apps = fetch_mcp_apps(&agent.extension_manager, &session_id)
.await
.map_err(|error| {
agent_client_protocol::Error::internal_error()
.data(format!("Failed to list apps: {}", error.message))
})?;
let lease = agent
.extension_manager
.current_lease(&session_id, None)
.await;
let mut apps = fetch_mcp_apps(&lease).await;
McpAppCache::restore_bundled_default_apps(&mut apps);
+3 -1
View File
@@ -10,7 +10,9 @@ impl GooseAcpAgent {
let cancel_token = CancellationToken::new();
let result = agent
.extension_manager
.read_resource(session_id, &req.uri, &req.extension_name, cancel_token)
.current_lease(session_id, None)
.await
.read_resource(&req.uri, &req.extension_name, cancel_token)
.await
.internal_err()?;
let result_json = serde_json::to_value(&result).internal_err()?;
+7 -9
View File
@@ -109,18 +109,16 @@ impl GooseAcpAgent {
.data(format!("Session not found: {}", session_id))
})?;
let ctx = crate::agents::ToolCallContext::new(
session_id.clone(),
Some(session.working_dir),
None,
)
.with_container(agent.container().await);
let container = agent.container().await;
let tool_result = agent
.extension_manager
.dispatch_app_tool_call(
&ctx,
.current_lease(session_id, Some(&session.working_dir))
.await
.call_for_app(
tool_call,
&req.extension_name,
crate::agents::extension_manager::CallRequest::default()
.with_container(container.clone()),
CancellationToken::new(),
)
.await
@@ -128,7 +126,7 @@ impl GooseAcpAgent {
let result = agent
.extension_manager
.applying_mutation(tool_result, ctx.container().cloned(), session_id)
.applying_mutation(tool_result, container, session_id)
.result
.await
.map_err(|e| agent_client_protocol::Error::internal_error().data(e.to_string()))?;
+14 -162
View File
@@ -1499,18 +1499,18 @@ impl Agent {
) -> Arc<ExtensionLease> {
Arc::new(
self.extension_manager
.current_session_lease(session_id, working_dir)
.current_lease(session_id, Some(working_dir))
.await,
)
}
pub async fn list_tools(&self, session_id: &str, extension_name: Option<String>) -> Vec<Tool> {
let include_final_output = extension_name.is_none();
let mut prefixed_tools = self
.extension_manager
.get_prefixed_tools(session_id, extension_name)
.await
.unwrap_or_default();
let lease = self.extension_manager.current_lease(session_id, None).await;
let mut prefixed_tools = match extension_name {
Some(name) => lease.tools_for(&name).await,
None => lease.tools().await,
};
if include_final_output {
if let Some(final_output_tool) = self.final_output_tool.lock().await.as_ref() {
@@ -4023,9 +4023,10 @@ impl Agent {
pub async fn list_extension_prompts(&self, session_id: &str) -> HashMap<String, Vec<Prompt>> {
self.extension_manager
.list_prompts(session_id, CancellationToken::default())
.current_lease(session_id, None)
.await
.list_prompts(CancellationToken::default())
.await
.expect("Failed to list prompts")
}
pub async fn get_prompt(
@@ -4034,29 +4035,17 @@ impl Agent {
name: &str,
arguments: Value,
) -> Result<GetPromptResult> {
// First find which extension has this prompt
let prompts = self
.extension_manager
.list_prompts(session_id, CancellationToken::default())
.await
.map_err(|e| anyhow!("Failed to list prompts: {}", e))?;
let lease = self.extension_manager.current_lease(session_id, None).await;
let prompts = lease.list_prompts(CancellationToken::default()).await;
if let Some(extension) = prompts
.iter()
.find(|(_, prompt_list)| prompt_list.iter().any(|p| p.name == name))
.map(|(extension, _)| extension)
{
return self
.extension_manager
.get_prompt(
session_id,
extension,
name,
arguments,
CancellationToken::default(),
)
.await
.map_err(|e| anyhow!("Failed to get prompt: {}", e));
return lease
.get_prompt(extension, name, arguments, CancellationToken::default())
.await;
}
Err(anyhow!("Prompt '{}' not found", name))
@@ -4146,87 +4135,6 @@ mod tests {
call_count: AtomicUsize,
}
struct MovingDirectoryProvider {
manager: std::sync::Mutex<Option<Arc<ExtensionManager>>>,
session_id: std::sync::Mutex<Option<String>>,
new_working_dir: PathBuf,
tool_lists: std::sync::Mutex<Vec<Vec<String>>>,
call_count: AtomicUsize,
}
impl MovingDirectoryProvider {
fn new(new_working_dir: PathBuf) -> Self {
Self {
manager: std::sync::Mutex::new(None),
session_id: std::sync::Mutex::new(None),
new_working_dir,
tool_lists: std::sync::Mutex::new(Vec::new()),
call_count: AtomicUsize::new(0),
}
}
}
#[async_trait::async_trait]
impl crate::providers::base::Provider for MovingDirectoryProvider {
async fn stream(
&self,
_model_config: &goose_providers::model::ModelConfig,
_system_prompt: &str,
_messages: &[Message],
tools: &[Tool],
) -> Result<MessageStream, ProviderError> {
self.tool_lists
.lock()
.unwrap()
.push(tools.iter().map(|tool| tool.name.to_string()).collect());
let call = self.call_count.fetch_add(1, Ordering::SeqCst);
let message = if call == 0 {
let manager = self
.manager
.lock()
.unwrap()
.clone()
.expect("extension manager unavailable");
let session_id = self
.session_id
.lock()
.unwrap()
.clone()
.expect("session unavailable");
manager
.get_context()
.session_manager
.update(&session_id)
.working_dir(self.new_working_dir.clone())
.apply()
.await
.unwrap();
manager
.update_working_dir(&self.new_working_dir, None, &session_id)
.await
.unwrap();
Message::assistant().with_tool_request(
"move-directory",
Ok(CallToolRequestParams::new("changing__value")),
)
} else {
Message::assistant().with_text("done")
};
Ok(stream_from_single_message(
message,
ProviderUsage::new("mock-model".to_string(), Usage::default()),
))
}
fn get_name(&self) -> &str {
"moving-directory"
}
async fn get_context_limit(&self, _model: &str, _override_limit: Option<usize>) -> usize {
100_000
}
}
impl RefreshingLeaseProvider {
fn new() -> Self {
Self {
@@ -4264,7 +4172,6 @@ mod tests {
manager
.add_client(
platform_extension("changing"),
Some(PathBuf::default()),
Arc::new(LeaseValueClient("second")),
None,
)
@@ -4298,7 +4205,6 @@ mod tests {
.extension_manager
.add_client(
persisted_builtin("changing"),
Some(session.working_dir.clone()),
Arc::new(LeaseValueClient("first")),
None,
)
@@ -4309,7 +4215,6 @@ mod tests {
.extension_manager
.add_client(
persisted_builtin("changing"),
Some(session.working_dir.clone()),
Arc::new(LeaseValueClient("second")),
None,
)
@@ -4374,58 +4279,6 @@ mod tests {
Ok(())
}
#[tokio::test]
async fn legacy_inference_refreshes_the_session_directory() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let new_working_dir = temp_dir.path().join("moved");
std::fs::create_dir(&new_working_dir)?;
let provider = Arc::new(MovingDirectoryProvider::new(new_working_dir));
let (agent, session_id) = create_test_agent(
temp_dir.path().join("data"),
crate::hooks::HookManager::from_plugins_for_test(vec![]),
provider.clone(),
)
.await?;
let session = agent
.config
.session_manager
.get_session(&session_id, false)
.await?;
agent
.extension_manager
.add_client(
persisted_builtin("changing"),
Some(session.working_dir),
Arc::new(LeaseValueClient("value")),
None,
)
.await;
*provider.manager.lock().unwrap() = Some(Arc::clone(&agent.extension_manager));
*provider.session_id.lock().unwrap() = Some(session_id.clone());
let mut stream = agent
.reply(
Message::user().with_text("move the directory"),
SessionConfig {
id: session_id,
schedule_id: None,
max_turns: Some(100),
retry_config: None,
},
false,
None,
)
.await?;
while let Some(event) = stream.next().await {
event?;
}
let tool_lists = provider.tool_lists.lock().unwrap();
assert_eq!(tool_lists.len(), 2);
assert!(tool_lists[1].iter().any(|tool| tool == "changing__value"));
Ok(())
}
#[tokio::test]
async fn inference_context_uses_the_lease_session_snapshot() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
@@ -4450,7 +4303,6 @@ mod tests {
.extension_manager
.add_client(
persisted_builtin("changing"),
Some(stale_session.working_dir.clone()),
Arc::new(LeaseValueClient("value")),
None,
)
@@ -16,8 +16,9 @@ use std::sync::Arc;
use futures::stream;
use futures::{FutureExt, Stream};
use rmcp::model::{
CallToolRequestParams, CallToolResult, ContentBlock, ErrorCode, ErrorData, ListResourcesResult,
ReadResourceResult, ResourceContents, ServerNotification, Tool,
CallToolRequestParams, CallToolResult, ContentBlock, ErrorCode, ErrorData, GetPromptResult,
ListResourcesResult, ListToolsResult, Prompt, ReadResourceResult, Resource, ResourceContents,
ServerNotification, Tool,
};
use rmcp::service::ServiceError;
use serde_json::Value;
@@ -341,26 +342,123 @@ impl ExtensionLease {
})
}
pub async fn list_resources_result_from_extension(
&self,
extension_name: &str,
cancellation_token: CancellationToken,
) -> Result<ListResourcesResult, ErrorData> {
fn client(&self, extension_name: &str) -> Result<&Arc<dyn McpClientTrait>, ErrorData> {
let key = name_to_key(extension_name);
let client = self
.extensions
self.extensions
.iter()
.find(|extension| extension.key == key)
.map(|extension| Arc::clone(&extension.client))
.map(|extension| &extension.client)
.ok_or_else(|| {
ErrorData::new(
ErrorCode::INVALID_PARAMS,
format!("Extension {extension_name} is not valid"),
None,
)
})?;
})
}
client
pub async fn list_tools_from_extension(
&self,
extension_name: &str,
cancellation_token: CancellationToken,
) -> Result<ListToolsResult, ErrorData> {
self.client(extension_name)?
.list_tools(&self.scope_id, None, cancellation_token)
.await
.map_err(|error| {
ErrorData::new(
ErrorCode::INTERNAL_ERROR,
format!("Unable to list tools for {extension_name}, {error:?}"),
None,
)
})
}
pub async fn list_prompts_from_extension(
&self,
extension_name: &str,
cancellation_token: CancellationToken,
) -> Result<Vec<Prompt>, ErrorData> {
self.client(extension_name)?
.list_prompts(&self.scope_id, None, cancellation_token)
.await
.map(|result| result.prompts)
.map_err(|error| {
ErrorData::new(
ErrorCode::INTERNAL_ERROR,
format!("Unable to list prompts for {extension_name}, {error:?}"),
None,
)
})
}
pub async fn list_prompts(
&self,
cancellation_token: CancellationToken,
) -> HashMap<String, Vec<Prompt>> {
let results = futures::future::join_all(self.extensions.iter().map(|extension| {
let token = cancellation_token.clone();
async move {
(
extension.key.clone(),
self.list_prompts_from_extension(&extension.key, token)
.await,
)
}
}))
.await;
let mut prompts = HashMap::new();
for (key, result) in results {
match result {
Ok(listed) => {
prompts.insert(key, listed);
}
Err(error) => tracing::debug!(?error, "failed to list prompts"),
}
}
prompts
}
pub async fn get_prompt(
&self,
extension_name: &str,
name: &str,
arguments: Value,
cancellation_token: CancellationToken,
) -> anyhow::Result<GetPromptResult> {
self.client(extension_name)?
.get_prompt(&self.scope_id, name, arguments, cancellation_token)
.await
.map_err(|e| anyhow::anyhow!("Failed to get prompt: {}", e))
}
pub async fn ui_resources(&self) -> Vec<(String, Resource)> {
let mut ui_resources = Vec::new();
for extension in &self.extensions {
match extension
.client
.list_resources(&self.scope_id, None, CancellationToken::default())
.await
{
Ok(listed) => ui_resources.extend(
listed
.resources
.into_iter()
.filter(|resource| resource.uri.starts_with("ui://"))
.map(|resource| (extension.key.clone(), resource)),
),
Err(error) => warn!(extension = %extension.key, ?error, "failed to list resources"),
}
}
ui_resources
}
pub async fn list_resources_result_from_extension(
&self,
extension_name: &str,
cancellation_token: CancellationToken,
) -> Result<ListResourcesResult, ErrorData> {
self.client(extension_name)?
.list_resources(&self.scope_id, None, cancellation_token)
.await
.map_err(|error| {
@@ -425,23 +523,26 @@ impl ExtensionLease {
Ok(resources)
}
pub fn instructions(&self) -> Vec<ExtensionInfo> {
pub async fn instructions(&self) -> Vec<ExtensionInfo> {
let working_dir = self
.working_dir
.as_deref()
.unwrap_or(std::path::Path::new("."))
.to_string_lossy();
self.extensions
.iter()
.map(|extension| {
let instructions = extension.client.get_instructions().unwrap_or_default();
ExtensionInfo::new(
&extension.key,
&instructions.replace("{{WORKING_DIR}}", &working_dir),
extension.supports_resources(),
)
})
.collect()
.clone()
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
let placeholder = working_dir.to_string_lossy();
let mut infos = Vec::new();
for extension in &self.extensions {
let instructions = extension
.client
.get_instructions(&self.scope_id, &working_dir)
.await
.unwrap_or_default();
infos.push(ExtensionInfo::new(
&extension.key,
&instructions.replace("{{WORKING_DIR}}", &placeholder),
extension.supports_resources(),
));
}
infos
}
pub async fn moim(&self) -> Vec<String> {
File diff suppressed because it is too large Load Diff
+2 -12
View File
@@ -27,7 +27,7 @@ use rmcp::{
use serde_json::Value;
use std::{
collections::HashMap,
path::PathBuf,
path::{Path, PathBuf},
sync::{
atomic::{AtomicU64, Ordering},
Arc, Mutex as StdMutex,
@@ -91,20 +91,10 @@ pub trait McpClientTrait: Send + Sync {
fn get_info(&self) -> Option<&InitializeResult>;
/// Return the extension's current instructions. The default reads from
/// `get_info()`, but platform extensions can override this to provide
/// dynamically computed instructions (e.g. freshly discovered skills).
fn get_instructions(&self) -> Option<String> {
async fn get_instructions(&self, _session_id: &str, _working_dir: &Path) -> Option<String> {
self.get_info().and_then(|info| info.instructions.clone())
}
fn rebind_session(
&self,
_session: Arc<crate::session::Session>,
) -> Option<Arc<dyn McpClientTrait>> {
None
}
async fn list_resources(
&self,
_session_id: &str,
+6 -15
View File
@@ -221,6 +221,7 @@ fn turn_budget_part(turns_taken: u32, max_turns: u32) -> Option<String> {
#[cfg(test)]
mod tests {
use super::*;
use crate::agents::extension_manager::ExtensionSet;
use crate::agents::mcp_client::McpClientTrait;
use crate::agents::tool_execution::ToolCallContext;
use crate::config::ExtensionConfig;
@@ -334,21 +335,11 @@ mod tests {
#[tokio::test]
async fn turn_context_uses_the_inference_lease() {
let (session_id, em, _tmp) = session_and_manager().await;
em.add_client(
moim_extension(),
None,
Arc::new(MoimClient("old context")),
None,
)
.await;
em.add_client(moim_extension(), Arc::new(MoimClient("old context")), None)
.await;
let lease = em.current_lease(&session_id, None).await;
em.add_client(
moim_extension(),
None,
Arc::new(MoimClient("new context")),
None,
)
.await;
em.add_client(moim_extension(), Arc::new(MoimClient("new context")), None)
.await;
let message =
turn_context_message(&session_id, &em, &lease, 0, 100, chrono::Local::now(), None)
@@ -365,7 +356,7 @@ mod tests {
let (session_id, em, _tmp) = session_and_manager().await;
let leased_working_dir = PathBuf::from("/leased/dir");
let lease = em
.current_lease(&session_id, Some(&leased_working_dir))
.resolve(&ExtensionSet::new(&session_id, Some(leased_working_dir), vec![]).unwrap())
.await;
let message =
@@ -281,7 +281,6 @@ mod tests {
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager: Arc::new(SessionManager::new(std::env::temp_dir())),
scheduler: None,
session: None,
use_login_shell_path: false,
}
}
@@ -831,7 +831,6 @@ mod tests {
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager: Arc::new(SessionManager::new(apps_dir.join("sessions"))),
scheduler: None,
session: None,
use_login_shell_path: false,
},
apps_dir,
@@ -111,9 +111,14 @@ impl ChatRecallClient {
Ok(Self { info, context })
}
fn search_session_types(&self) -> Vec<SessionType> {
match self.context.session.as_ref().map(|s| s.session_type) {
Some(SessionType::Acp) => vec![SessionType::Acp],
async fn search_session_types(&self, current_session_id: &str) -> Vec<SessionType> {
let current = self
.context
.session_manager
.get_session(current_session_id, false)
.await;
match current.map(|s| s.session_type) {
Ok(SessionType::Acp) => vec![SessionType::Acp],
_ => vec![SessionType::User, SessionType::Scheduled],
}
}
@@ -205,7 +210,7 @@ impl ChatRecallClient {
after_date,
before_date,
exclude_session_id,
self.search_session_types(),
self.search_session_types(current_session_id).await,
)
.await
{
@@ -444,7 +449,6 @@ mod tests {
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager,
scheduler: None,
session: Some(Arc::new(current_session.clone())),
use_login_shell_path: false,
})
.unwrap();
@@ -77,26 +77,6 @@ impl CodeExecutionClient {
})
}
async fn load_callback_configs(
&self,
session_id: &str,
lease: Option<&ExtensionLease>,
) -> Option<Vec<CallbackConfig>> {
let tools = match lease {
Some(lease) => lease.tools_excluding(EXTENSION_NAME).await,
None => self
.context
.extension_manager
.as_ref()
.and_then(|manager| manager.upgrade())?
.get_prefixed_tools_excluding(session_id, EXTENSION_NAME)
.await
.ok()?,
};
Some(Self::callback_configs(tools))
}
fn callback_configs(tools: Vec<McpTool>) -> Vec<CallbackConfig> {
let mut cfgs = vec![];
for tool in tools {
@@ -124,15 +104,8 @@ impl CodeExecutionClient {
}
/// Get the cached CodeMode, rebuilding if callback configs have changed
async fn get_code_mode(
&self,
session_id: &str,
lease: Option<&ExtensionLease>,
) -> Result<CodeMode, String> {
let cfgs = self
.load_callback_configs(session_id, lease)
.await
.ok_or("Failed to load callback configs")?;
async fn get_code_mode(&self, lease: &ExtensionLease) -> Result<CodeMode, String> {
let cfgs = Self::callback_configs(lease.tools_excluding(EXTENSION_NAME).await);
self.get_code_mode_for_configs(cfgs).await
}
@@ -211,10 +184,9 @@ impl CodeExecutionClient {
/// Handle the list_functions tool call
async fn handle_list_functions(
&self,
session_id: &str,
lease: Option<&ExtensionLease>,
lease: &ExtensionLease,
) -> Result<Vec<ContentBlock>, String> {
let code_mode = self.get_code_mode(session_id, lease).await?;
let code_mode = self.get_code_mode(lease).await?;
let output = code_mode.list_functions();
Ok(vec![ContentBlock::text(output.code)])
@@ -223,8 +195,7 @@ impl CodeExecutionClient {
/// Handle the get_function_details tool call
async fn handle_get_function_details(
&self,
session_id: &str,
lease: Option<&ExtensionLease>,
lease: &ExtensionLease,
arguments: Option<JsonObject>,
) -> Result<Vec<ContentBlock>, String> {
let input: GetFunctionDetailsInput = arguments
@@ -233,7 +204,7 @@ impl CodeExecutionClient {
.map_err(|e| format!("Failed to parse arguments: {e}"))?
.ok_or("Missing arguments for get_function_details")?;
let code_mode = self.get_code_mode(session_id, lease).await?;
let code_mode = self.get_code_mode(lease).await?;
let output = code_mode.get_function_details(input);
Ok(vec![ContentBlock::text(output.code)])
@@ -242,8 +213,7 @@ impl CodeExecutionClient {
/// Handle the execute bash tool call
async fn handle_execute_bash(
&self,
session_id: &str,
lease: Option<&ExtensionLease>,
lease: &ExtensionLease,
arguments: Option<JsonObject>,
cancellation_token: CancellationToken,
) -> Result<Vec<ContentBlock>, String> {
@@ -253,7 +223,7 @@ impl CodeExecutionClient {
.map_err(|e| format!("Failed to parse arguments: {e}"))?
.ok_or("Missing arguments for execute_bash")?;
let command = input.command;
let code_mode = self.get_code_mode(session_id, lease).await?;
let code_mode = self.get_code_mode(lease).await?;
let dispatch_token = cancellation_token.child_token();
let output = run_in_deno_runtime(
@@ -288,10 +258,7 @@ impl CodeExecutionClient {
.map_err(|e| format!("Failed to parse arguments: {e}"))?
.ok_or("Missing arguments for execute_typescript")?;
let session_id = &ctx.session_id;
let code_mode = self
.get_code_mode(session_id, ctx.extension_lease().map(AsRef::as_ref))
.await?;
let code_mode = self.get_code_mode(dispatching_lease(ctx)).await?;
let dispatch_token = cancellation_token.child_token();
let rt = tokio::runtime::Handle::current();
let registry = self.build_callback_registry(ctx, &code_mode, dispatch_token.clone(), rt)?;
@@ -386,6 +353,11 @@ where
.map_err(|e| format!("Execution task failed: {e}"))?
}
fn dispatching_lease(ctx: &ToolCallContext) -> &ExtensionLease {
ctx.extension_lease()
.expect("platform tool calls are dispatched through a lease")
}
fn create_tool_callback(
ctx: ToolCallContext,
full_name: String,
@@ -409,18 +381,9 @@ fn create_tool_callback(
};
let handle = rt.spawn(async move {
let dispatch_result = match ctx.extension_lease().cloned() {
Some(lease) => {
lease
.call(tool_call, CallRequest::from(&ctx), cancellation_token)
.await
}
None => {
manager
.dispatch_tool_call(&ctx, tool_call, cancellation_token)
.await
}
};
let dispatch_result = dispatching_lease(&ctx)
.call(tool_call, CallRequest::from(&ctx), cancellation_token)
.await;
match dispatch_result {
Ok(dispatch_result) => match manager
.applying_mutation(
@@ -598,16 +561,12 @@ impl McpClientTrait for CodeExecutionClient {
arguments: Option<JsonObject>,
cancellation_token: CancellationToken,
) -> Result<CallToolResult, Error> {
let session_id = &ctx.session_id;
let lease = ctx.extension_lease().map(AsRef::as_ref);
let lease = dispatching_lease(ctx);
let result = match name {
"list_functions" => self.handle_list_functions(session_id, lease).await,
"get_function_details" => {
self.handle_get_function_details(session_id, lease, arguments)
.await
}
"list_functions" => self.handle_list_functions(lease).await,
"get_function_details" => self.handle_get_function_details(lease, arguments).await,
"execute_bash" => {
self.handle_execute_bash(session_id, lease, arguments, cancellation_token)
self.handle_execute_bash(lease, arguments, cancellation_token)
.await
}
"execute_typescript" => {
@@ -848,19 +807,14 @@ mod tests {
bundled: None,
available_tools: vec![],
},
None,
Arc::new(VisibilityClient),
None,
)
.await;
let mut context = manager.get_context().clone();
context.extension_manager = Some(Arc::downgrade(&manager));
let client = CodeExecutionClient::new(context, ToolDisclosure::Catalog).unwrap();
let configs = client
.load_callback_configs("test-session", None)
.await
.unwrap();
let lease = manager.current_lease("test-session", None).await;
let configs =
CodeExecutionClient::callback_configs(lease.tools_excluding(EXTENSION_NAME).await);
let names = configs
.iter()
.map(|config| config.name.as_str())
@@ -1197,7 +1151,6 @@ mod tests {
temp.path().join("sessions"),
)),
scheduler: None,
session: None,
use_login_shell_path: false,
},
ToolDisclosure::Filesystem,
@@ -297,7 +297,6 @@ mod tests {
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager: Arc::new(SessionManager::new(data_dir)),
scheduler: None,
session: None,
use_login_shell_path: false,
}
}
@@ -28,9 +28,6 @@ pub enum ExtensionManagerToolError {
#[error("Unknown tool: {tool_name}")]
UnknownTool { tool_name: String },
#[error("Extension manager not available")]
ManagerUnavailable,
#[error("Missing required parameter: {param_name}")]
MissingParameter { param_name: String },
@@ -105,23 +102,15 @@ impl ExtensionManagerClient {
Ok(Self { info, context })
}
async fn handle_search_available_extensions(
&self,
) -> Result<Vec<ContentBlock>, ExtensionManagerToolError> {
let extension_manager = self
.context
.extension_manager
.as_ref()
.and_then(|weak| weak.upgrade())
.ok_or(ExtensionManagerToolError::ManagerUnavailable)?;
let enabled = extension_manager.list_extensions().await.map_err(|e| {
ExtensionManagerToolError::OperationFailed {
message: format!("Failed to search available extensions: {}", e),
}
})?;
Ok(vec![ContentBlock::text(search_available_extensions(
&enabled,
))])
fn handle_search_available_extensions(ctx: &ToolCallContext) -> Vec<ContentBlock> {
let enabled: Vec<String> = ctx
.extension_lease()
.expect("platform tool calls are dispatched through a lease")
.configs()
.iter()
.map(ExtensionConfig::key)
.collect();
vec![ContentBlock::text(search_available_extensions(&enabled))]
}
async fn handle_manage_extensions(
@@ -221,21 +210,11 @@ impl ExtensionManagerClient {
arguments: Option<JsonObject>,
) -> Result<Vec<ContentBlock>, ExtensionManagerToolError> {
let params = arguments.map(serde_json::Value::Object).unwrap_or_default();
let result = if let Some(lease) = ctx.extension_lease() {
lease
.list_resources(params, CancellationToken::default())
.await
} else {
let manager = self
.context
.extension_manager
.as_ref()
.and_then(|manager| manager.upgrade())
.ok_or(ExtensionManagerToolError::ManagerUnavailable)?;
manager
.list_resources(&ctx.session_id, params, CancellationToken::default())
.await
};
let result = ctx
.extension_lease()
.expect("platform tool calls are dispatched through a lease")
.list_resources(params, CancellationToken::default())
.await;
result.map_err(|error| ExtensionManagerToolError::OperationFailed {
message: format!("Failed to list resources: {}", error.message),
})
@@ -247,21 +226,11 @@ impl ExtensionManagerClient {
arguments: Option<JsonObject>,
) -> Result<Vec<ContentBlock>, ExtensionManagerToolError> {
let params = arguments.map(serde_json::Value::Object).unwrap_or_default();
let result = if let Some(lease) = ctx.extension_lease() {
lease
.read_resource_tool(params, CancellationToken::default())
.await
} else {
let manager = self
.context
.extension_manager
.as_ref()
.and_then(|manager| manager.upgrade())
.ok_or(ExtensionManagerToolError::ManagerUnavailable)?;
manager
.read_resource_tool(&ctx.session_id, params, CancellationToken::default())
.await
};
let result = ctx
.extension_lease()
.expect("platform tool calls are dispatched through a lease")
.read_resource_tool(params, CancellationToken::default())
.await;
result.map_err(|error| ExtensionManagerToolError::OperationFailed {
message: format!("Failed to read resource: {}", error.message),
})
@@ -432,7 +401,7 @@ impl McpClientTrait for ExtensionManagerClient {
let session_id = &ctx.session_id;
let result = match name {
SEARCH_AVAILABLE_EXTENSIONS_TOOL_NAME => {
self.handle_search_available_extensions().await
Ok(Self::handle_search_available_extensions(ctx))
}
MANAGE_EXTENSIONS_TOOL_NAME => {
return Ok(self
@@ -542,11 +511,10 @@ mod tests {
fn client_for(manager: &Arc<ExtensionManager>) -> ExtensionManagerClient {
ExtensionManagerClient::new(PlatformExtensionContext {
extension_manager: Some(Arc::downgrade(manager)),
extension_manager: None,
provider: manager.get_provider().clone(),
session_manager: manager.get_context().session_manager.clone(),
scheduler: None,
session: None,
use_login_shell_path: false,
})
.unwrap()
@@ -19,7 +19,6 @@ pub mod tom;
use std::collections::HashMap;
use crate::agents::mcp_client::McpClientTrait;
use crate::session::Session;
use once_cell::sync::Lazy;
pub use ext_manager::MANAGE_EXTENSIONS_TOOL_NAME_COMPLETE;
@@ -224,9 +223,7 @@ pub static PLATFORM_EXTENSIONS: Lazy<HashMap<&'static str, PlatformExtensionDef>
default_enabled: true,
unprefixed_tools: true,
hidden: false,
client_factory: |ctx| {
Some(Box::new(crate::skills::SkillsClient::new(ctx).unwrap()))
},
client_factory: |_| Some(Box::new(crate::skills::SkillsClient::default())),
},
);
@@ -244,7 +241,6 @@ pub struct PlatformExtensionContext {
pub provider: crate::agents::types::SharedProvider,
pub session_manager: std::sync::Arc<crate::session::SessionManager>,
pub scheduler: Option<std::sync::Arc<dyn crate::scheduler_trait::SchedulerTrait>>,
pub session: Option<std::sync::Arc<Session>>,
pub use_login_shell_path: bool,
}
@@ -2,7 +2,7 @@ use crate::agents::extension::PlatformExtensionContext;
use crate::agents::mcp_client::{Error, McpClientTrait};
use crate::agents::tool_execution::ToolCallContext;
use crate::agents::{AgentEvent, SessionConfig};
use crate::config::{Config, ExtensionConfig, GooseMode};
use crate::config::{Config, GooseMode};
use crate::context_mgmt::format_message_for_compacting;
use crate::conversation::message::Message;
use crate::conversation::Conversation;
@@ -137,26 +137,6 @@ impl OrchestratorClient {
.ok_or_else(|| "Provider not available".to_string())
}
async fn parent_model_config(
&self,
provider_name: &str,
) -> Result<goose_providers::model::ModelConfig, String> {
if let Some(session) = self.context.session.as_ref() {
return self.context.model_config_for_session(&session.id).await;
}
let model_name = Config::global()
.get_goose_model()
.map_err(|_| "Could not resolve model config: missing model".to_string())?;
crate::model_config::model_config_from_user_config(provider_name, &model_name)
.map_err(|e| format!("Could not resolve model config: {e}"))
}
fn parent_extensions(&self) -> Vec<ExtensionConfig> {
let extension_data = self.context.session.as_ref().map(|s| &s.extension_data);
EnabledExtensionsState::extensions_or_default(extension_data, Config::global())
}
async fn handle_list_sessions(
&self,
arguments: Option<JsonObject>,
@@ -349,7 +329,7 @@ impl OrchestratorClient {
conversation_text
));
let model_config = self.parent_model_config(provider.get_name()).await?;
let model_config = self.context.model_config_for_session(session_id).await?;
let (response, _usage) = crate::model_config::complete_one_shot(
provider.as_ref(),
&model_config,
@@ -381,6 +361,7 @@ impl OrchestratorClient {
arguments: Option<JsonObject>,
) -> Result<CallToolResult, String> {
self.authorize_start_agent(session_id).await?;
let caller = self.caller_session(session_id).await?;
let args = arguments.ok_or("Missing arguments")?;
let working_dir = extract_string(&args, "working_dir")?;
@@ -394,13 +375,7 @@ impl OrchestratorClient {
let path = if raw_path.is_absolute() {
raw_path
} else {
let base = self
.context
.session
.as_ref()
.map(|s| s.working_dir.clone())
.unwrap_or_else(|| PathBuf::from("."));
base.join(&raw_path)
caller.working_dir.join(&raw_path)
};
let path = path
@@ -427,8 +402,11 @@ impl OrchestratorClient {
.map_err(|e| format!("Failed to create agent: {}", e))?;
let parent_provider = self.get_provider().await?;
let extensions = self.parent_extensions();
let model_config = self.parent_model_config(parent_provider.get_name()).await?;
let extensions = EnabledExtensionsState::extensions_or_default(
Some(&caller.extension_data),
Config::global(),
);
let model_config = self.context.model_config_for_session(session_id).await?;
let provider = providers::create(parent_provider.get_name(), extensions)
.await
.map_err(|e| format!("Failed to create provider for new agent: {}", e))?;
@@ -516,8 +494,15 @@ impl OrchestratorClient {
if agent.provider().await.is_err() {
if let Ok(parent_provider) = self.get_provider().await {
let extensions = self.parent_extensions();
let model_config = self.parent_model_config(parent_provider.get_name()).await?;
let caller = self.caller_session(parent_session_id).await?;
let extensions = EnabledExtensionsState::extensions_or_default(
Some(&caller.extension_data),
Config::global(),
);
let model_config = self
.context
.model_config_for_session(parent_session_id)
.await?;
if let Ok(provider) =
providers::create(parent_provider.get_name(), extensions).await
{
@@ -753,16 +738,12 @@ mod tests {
use crate::session::SessionManager;
use rmcp::model::{Annotations, Role, TextContent};
fn client_for(
session_manager: Arc<SessionManager>,
session: Option<crate::session::Session>,
) -> OrchestratorClient {
fn client_for(session_manager: Arc<SessionManager>) -> OrchestratorClient {
OrchestratorClient::new(PlatformExtensionContext {
extension_manager: None,
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager,
scheduler: None,
session: session.map(Arc::new),
use_login_shell_path: false,
})
.unwrap()
@@ -864,7 +845,7 @@ mod tests {
let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf()));
let subagent =
create_session(&session_manager, temp_dir.path(), SessionType::SubAgent).await;
let client = client_for(Arc::clone(&session_manager), Some(subagent.clone()));
let client = client_for(Arc::clone(&session_manager));
let result = start_agent(&client, &subagent.id, temp_dir.path()).await;
@@ -883,7 +864,7 @@ mod tests {
let user = create_session(&session_manager, temp_dir.path(), SessionType::User).await;
let subagent =
create_session(&session_manager, temp_dir.path(), SessionType::SubAgent).await;
let client = client_for(Arc::clone(&session_manager), Some(user.clone()));
let client = client_for(Arc::clone(&session_manager));
assert!(client.authorize_start_agent(&user.id).await.is_ok());
let user_tools = client
@@ -914,7 +895,7 @@ mod tests {
async fn unknown_caller_cannot_persist_user_session() {
let temp_dir = tempfile::tempdir().unwrap();
let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf()));
let client = client_for(Arc::clone(&session_manager), None);
let client = client_for(Arc::clone(&session_manager));
let result = start_agent(&client, "missing-session", temp_dir.path()).await;
@@ -932,7 +913,7 @@ mod tests {
let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf()));
let user = create_session(&session_manager, temp_dir.path(), SessionType::User).await;
let subagent = create_subagent_session(&session_manager, temp_dir.path(), &user.id).await;
let client = client_for(Arc::clone(&session_manager), Some(subagent.clone()));
let client = client_for(Arc::clone(&session_manager));
let error = client
.handle_send_message(
@@ -964,7 +945,7 @@ mod tests {
let parent = create_session(&session_manager, temp_dir.path(), SessionType::User).await;
let caller = create_subagent_session(&session_manager, temp_dir.path(), &parent.id).await;
let target = create_subagent_session(&session_manager, temp_dir.path(), &parent.id).await;
let client = client_for(Arc::clone(&session_manager), Some(caller.clone()));
let client = client_for(Arc::clone(&session_manager));
assert!(client
.authorize_send_message(&caller.id, &target.id)
@@ -984,7 +965,7 @@ mod tests {
create_subagent_session(&session_manager, temp_dir.path(), &caller_parent.id).await;
let target =
create_subagent_session(&session_manager, temp_dir.path(), &target_parent.id).await;
let client = client_for(Arc::clone(&session_manager), Some(caller.clone()));
let client = client_for(Arc::clone(&session_manager));
let error = client
.handle_send_message(
@@ -1017,7 +998,7 @@ mod tests {
let caller = create_subagent_session(&session_manager, temp_dir.path(), &parent.id).await;
let descendant =
create_subagent_session(&session_manager, temp_dir.path(), &caller.id).await;
let client = client_for(Arc::clone(&session_manager), Some(caller.clone()));
let client = client_for(Arc::clone(&session_manager));
let error = client
.authorize_send_message(&caller.id, &descendant.id)
@@ -1036,7 +1017,7 @@ mod tests {
let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf()));
let caller = create_session(&session_manager, temp_dir.path(), SessionType::SubAgent).await;
let target = create_session(&session_manager, temp_dir.path(), SessionType::SubAgent).await;
let client = client_for(Arc::clone(&session_manager), Some(caller.clone()));
let client = client_for(Arc::clone(&session_manager));
let error = client
.authorize_send_message(&caller.id, &target.id)
@@ -1055,7 +1036,7 @@ mod tests {
let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf()));
let caller = create_session(&session_manager, temp_dir.path(), SessionType::User).await;
let target = create_session(&session_manager, temp_dir.path(), SessionType::User).await;
let client = client_for(Arc::clone(&session_manager), Some(caller.clone()));
let client = client_for(Arc::clone(&session_manager));
assert!(client
.authorize_send_message(&caller.id, &target.id)
@@ -1068,7 +1049,7 @@ mod tests {
let temp_dir = tempfile::tempdir().unwrap();
let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf()));
let target = create_session(&session_manager, temp_dir.path(), SessionType::User).await;
let client = client_for(Arc::clone(&session_manager), None);
let client = client_for(Arc::clone(&session_manager));
let error = client
.authorize_send_message("missing-session", &target.id)
@@ -448,55 +448,12 @@ fn build_instructions_with_context(context: &str, instructions: &str) -> String
result
}
fn build_subagent_instructions(session: Option<&crate::session::Session>) -> String {
let Some(session) = session else {
return String::new();
};
// filter the sources down to what we want even though currently that is what we get
let mut sources: Vec<SourceEntry> = discover_filesystem_sources(&session.working_dir)
.into_iter()
.filter(|s| {
matches!(
s.source_type,
SourceType::Agent | SourceType::Recipe | SourceType::Subrecipe
)
})
.collect();
// If the session is started from a recipe, also use the subrecipes for
// that recipe as delegate targets
if let Some(recipe) = session.recipe.as_ref() {
if let Some(subs) = recipe.sub_recipes.as_ref() {
let mut seen: std::collections::HashSet<String> =
sources.iter().map(|s| s.name.clone()).collect();
for sr in subs {
if !seen.insert(sr.name.clone()) {
continue;
}
sources.push(SourceEntry {
source_type: SourceType::Subrecipe,
name: sr.name.clone(),
description: sr.description.clone().unwrap_or_default(),
content: String::new(),
path: sr.path.clone(),
global: false,
writable: false,
supporting_files: Vec::new(),
properties: std::collections::HashMap::new(),
});
}
}
}
fn build_subagent_instructions(sources: &[SourceEntry]) -> String {
if sources.is_empty() {
return String::new();
}
sources.sort_by(|a, b| (&a.source_type, &a.name).cmp(&(&b.source_type, &b.name)));
let subagents: Vec<&SourceEntry> = sources.iter().collect();
let names = subagents
let names = sources
.iter()
.map(|s| s.name.as_str())
.collect::<Vec<_>>()
@@ -510,7 +467,7 @@ fn build_subagent_instructions(session: Option<&crate::session::Session>) -> Str
);
let mut current_kind: Option<SourceType> = None;
for s in &subagents {
for s in sources {
if current_kind != Some(s.source_type) {
out.push_str(&format!("\n{}:", kind_plural(s.source_type)));
current_kind = Some(s.source_type);
@@ -579,9 +536,9 @@ fn is_session_id(s: &str) -> bool {
pub struct SummonClient {
info: InitializeResult,
context: PlatformExtensionContext,
source_cache: Arc<Mutex<Option<CachedSources>>>,
background_tasks: Arc<BackgroundTasks>,
completed_tasks: Arc<Mutex<HashMap<String, CompletedTask>>>,
source_cache: Mutex<Option<CachedSources>>,
background_tasks: BackgroundTasks,
completed_tasks: Mutex<HashMap<String, CompletedTask>>,
}
type CachedSources = (Instant, PathBuf, Vec<SourceEntry>);
@@ -614,24 +571,12 @@ impl SummonClient {
Ok(Self {
info,
context,
source_cache: Arc::new(Mutex::new(None)),
background_tasks: Arc::new(BackgroundTasks(Mutex::new(HashMap::new()))),
completed_tasks: Arc::new(Mutex::new(HashMap::new())),
source_cache: Mutex::new(None),
background_tasks: BackgroundTasks(Mutex::new(HashMap::new())),
completed_tasks: Mutex::new(HashMap::new()),
})
}
fn rebound(&self, session: Arc<crate::session::Session>) -> Self {
let mut context = self.context.clone();
context.session = Some(session);
Self {
info: self.info.clone(),
context,
source_cache: Arc::clone(&self.source_cache),
background_tasks: Arc::clone(&self.background_tasks),
completed_tasks: Arc::clone(&self.completed_tasks),
}
}
async fn create_subagent_session(
&self,
task_config: &TaskConfig,
@@ -823,12 +768,6 @@ impl SummonClient {
fn working_dir(&self, ctx: &ToolCallContext) -> PathBuf {
ctx.working_dir
.clone()
.or_else(|| {
self.context
.session
.as_ref()
.map(|session| session.working_dir.clone())
})
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default())
}
@@ -1387,20 +1326,12 @@ impl SummonClient {
self.validate_delegate_params(&params)?;
let mut session = match self
let mut session = self
.context
.session
.as_deref()
.filter(|session| session.id == session_id)
{
Some(session) => session.clone(),
None => self
.context
.session_manager
.get_session(session_id, false)
.await
.map_err(|e| format!("Failed to get session: {}", e))?,
};
.session_manager
.get_session(session_id, false)
.await
.map_err(|e| format!("Failed to get session: {}", e))?;
session.working_dir = working_dir.to_path_buf();
if session.session_type == SessionType::SubAgent {
@@ -2352,20 +2283,10 @@ impl McpClientTrait for SummonClient {
Some(&self.info)
}
fn get_instructions(&self) -> Option<String> {
let instructions = build_subagent_instructions(self.context.session.as_deref());
if instructions.is_empty() {
None
} else {
Some(instructions)
}
}
fn rebind_session(
&self,
session: Arc<crate::session::Session>,
) -> Option<Arc<dyn McpClientTrait>> {
Some(Arc::new(self.rebound(session)))
async fn get_instructions(&self, session_id: &str, working_dir: &Path) -> Option<String> {
let sources = self.get_sources(session_id, working_dir).await;
let instructions = build_subagent_instructions(&sources);
(!instructions.is_empty()).then_some(instructions)
}
async fn get_moim(&self, _session_id: &str, _tools: &[Tool]) -> Option<String> {
@@ -2491,7 +2412,6 @@ mod tests {
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager,
scheduler: None,
session: None,
use_login_shell_path: false,
}
}
@@ -2642,8 +2562,7 @@ mod tests {
}
#[tokio::test]
async fn rebound_client_refreshes_instructions_and_preserves_task_state() {
let data_dir = TempDir::new().unwrap();
async fn instructions_follow_the_calling_working_dir() {
let old_working_dir = TempDir::new().unwrap();
let new_working_dir = TempDir::new().unwrap();
for (working_dir, name) in [
@@ -2658,43 +2577,19 @@ mod tests {
)
.unwrap();
}
let session_manager = Arc::new(crate::session::SessionManager::new(
data_dir.path().to_path_buf(),
));
let old_session = session_manager
.create_session(
old_working_dir.path().to_path_buf(),
"old".to_string(),
SessionType::Hidden,
GooseMode::Auto,
)
let client = SummonClient::new(create_test_context()).unwrap();
let old = client
.get_instructions("session", old_working_dir.path())
.await
.unwrap();
let new_session = session_manager
.create_session(
new_working_dir.path().to_path_buf(),
"new".to_string(),
SessionType::Hidden,
GooseMode::Auto,
)
let new = client
.get_instructions("session", new_working_dir.path())
.await
.unwrap();
let mut context = create_test_context_with_session_manager(session_manager);
context.session = Some(Arc::new(old_session));
let client = SummonClient::new(context).unwrap();
let rebound = client.rebound(Arc::new(new_session));
assert!(client.get_instructions().unwrap().contains("old-agent"));
assert!(rebound.get_instructions().unwrap().contains("new-agent"));
assert!(Arc::ptr_eq(
&client.background_tasks,
&rebound.background_tasks
));
assert!(Arc::ptr_eq(
&client.completed_tasks,
&rebound.completed_tasks
));
assert!(old.contains("old-agent") && !old.contains("new-agent"));
assert!(new.contains("new-agent") && !new.contains("old-agent"));
}
#[tokio::test]
@@ -2726,9 +2621,10 @@ mod tests {
)
.await
.unwrap();
let mut context = create_test_context_with_session_manager(Arc::clone(&session_manager));
context.session = Some(Arc::new(session.clone()));
let client = SummonClient::new(context).unwrap();
let client = SummonClient::new(create_test_context_with_session_manager(Arc::clone(
&session_manager,
)))
.unwrap();
session_manager
.update(&session.id)
.working_dir(new_working_dir.path().to_path_buf())
@@ -2759,23 +2655,8 @@ mod tests {
}
#[tokio::test]
async fn shared_background_tasks_are_cancelled_after_all_clients_drop() {
let data_dir = TempDir::new().unwrap();
let session_manager = Arc::new(crate::session::SessionManager::new(
data_dir.path().to_path_buf(),
));
let session = session_manager
.create_session(
data_dir.path().to_path_buf(),
"rebound".to_string(),
SessionType::Hidden,
GooseMode::Auto,
)
.await
.unwrap();
let client =
SummonClient::new(create_test_context_with_session_manager(session_manager)).unwrap();
let rebound = client.rebound(Arc::new(session));
async fn background_tasks_are_cancelled_when_the_client_drops() {
let client = SummonClient::new(create_test_context()).unwrap();
let cancellation_token = CancellationToken::new();
let task_token = cancellation_token.clone();
let handle = tokio::spawn(async move {
@@ -2797,12 +2678,7 @@ mod tests {
},
);
let (first, second) = tokio::join!(
tokio::spawn(async move { drop(client) }),
tokio::spawn(async move { drop(rebound) })
);
first.unwrap();
second.unwrap();
drop(client);
assert!(cancellation_token.is_cancelled());
}
+15 -13
View File
@@ -542,22 +542,24 @@ mod tests {
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager,
scheduler: Some(scheduler),
session: Some(Arc::new(session)),
use_login_shell_path: false,
};
let mut extensions: Vec<ExtensionInfo> = PLATFORM_EXTENSIONS
.values()
.filter_map(|def| {
let client = (def.client_factory)(context.clone())?;
let instructions = client.get_instructions().unwrap_or_default();
let has_resources = client
.get_info()
.and_then(|i| i.capabilities.resources.as_ref())
.is_some();
Some(ExtensionInfo::new(def.name, &instructions, has_resources))
})
.collect();
let mut extensions = Vec::new();
for def in PLATFORM_EXTENSIONS.values() {
let Some(client) = (def.client_factory)(context.clone()) else {
continue;
};
let instructions = client
.get_instructions(&session.id, &session.working_dir)
.await
.unwrap_or_default();
let has_resources = client
.get_info()
.and_then(|i| i.capabilities.resources.as_ref())
.is_some();
extensions.push(ExtensionInfo::new(def.name, &instructions, has_resources));
}
extensions.sort_by(|a, b| a.name.cmp(&b.name));
+1 -1
View File
@@ -225,7 +225,7 @@ impl Agent {
let tools = prepare_inference_tools(tools, code_execution_active);
let extensions_info = lease.instructions();
let extensions_info = lease.instructions().await;
let model_config = self.effective_model_config_for_session(&session.id).await?;
let goose_mode = *self.current_goose_mode.lock().await;
@@ -1,6 +1,7 @@
//! Goose-specific inference request preparation.
use crate::agents::extension_manager::{ExtensionLease, ExtensionManager};
use crate::agents::state_machine::awaits_tool_responses;
use crate::agents::PromptManager;
use crate::config::GooseMode;
use crate::session::Session;
@@ -30,10 +31,18 @@ impl InferenceRequestPreparer<Session> for GooseInferenceRequestPreparer<'_> {
.extension_manager
.current_session_snapshot(session)
.await;
*self
.extension_lease
.lock()
.expect("extension lease unavailable") = Some(Arc::new(lease));
// Tool requests run under the lease of the inference that made them, so an
// approval answered after that lease is gone expires instead of picking up a new one.
let awaiting = match &session.conversation {
Some(conversation) => awaits_tool_responses(messages_since_kickoff(conversation)?),
None => false,
};
if !awaiting {
*self
.extension_lease
.lock()
.expect("extension lease unavailable") = Some(Arc::new(lease));
}
Ok(Some(session))
}
@@ -357,7 +357,7 @@ impl<'a> ToolExecutionOperation<'a> {
async fn resolve_lease(&self, session: &Session) -> Arc<ExtensionLease> {
let lease = Arc::new(
self.extension_manager
.current_session_lease(&session.id, &session.working_dir)
.current_lease(&session.id, Some(&session.working_dir))
.await,
);
*self.lease.lock().expect("extension lease unavailable") = Some(Arc::clone(&lease));
@@ -478,21 +478,11 @@ impl<'a> ToolExecutionOperation<'a> {
conversation: &Conversation,
emit: &Emitter,
) -> Result<OperationResult<GooseEffect>> {
let prompts = match self
.extension_manager
.list_prompts(&session.id, emit.cancel_token().clone())
let prompts = self
.lease(session)
.await
{
Ok(prompts) => prompts,
Err(error) => {
return Self::command_response(
conversation,
format!("Failed to list prompts: {}", error.message),
emit,
)
.await;
}
};
.list_prompts(emit.cancel_token().clone())
.await;
let extension_filter = command.params_str.split_whitespace().next();
if let Some(filter) = extension_filter {
if !prompts.contains_key(filter) {
@@ -541,21 +531,11 @@ impl<'a> ToolExecutionOperation<'a> {
)
.await;
};
let prompts = match self
.extension_manager
.list_prompts(&session.id, emit.cancel_token().clone())
let prompts = self
.lease(session)
.await
{
Ok(prompts) => prompts,
Err(error) => {
return Self::command_response(
conversation,
format!("Failed to list prompts: {}", error.message),
emit,
)
.await;
}
};
.list_prompts(emit.cancel_token().clone())
.await;
let found = prompts.iter().find_map(|(extension, prompts)| {
prompts
.iter()
@@ -597,9 +577,9 @@ impl<'a> ToolExecutionOperation<'a> {
.map(|(key, value)| (key.to_string(), value.trim_matches('"').to_string()))
.collect();
let result = match self
.extension_manager
.lease(session)
.await
.get_prompt(
&session.id,
&extension,
prompt_name,
serde_json::to_value(arguments)?,
@@ -857,7 +837,7 @@ impl Operation<Session, GooseEffect> for ToolExecutionOperation<'_> {
return Ok(prompt_parts);
}
let mut extensions = lease.instructions();
let mut extensions = lease.instructions().await;
extensions.retain(|extension| extension.name != crate::skills::EXTENSION_NAME);
if extensions.is_empty() {
return Ok(prompt_parts);
@@ -91,7 +91,6 @@ async fn agent_with_calculator() -> Result<(
.extension_manager
.add_client(
calculator_config(),
Some(temp_dir.path().to_path_buf()),
calculator.clone(),
calculator.get_info().cloned(),
)
@@ -249,7 +248,6 @@ async fn state_machine_confirmation_through_agent_resumes_tool_call() -> Result<
.extension_manager
.add_client(
calculator_config(),
Some(new_working_dir.path().to_path_buf()),
replacement.clone(),
replacement.get_info().cloned(),
)
@@ -871,7 +871,6 @@ async fn build_test_pipeline(
extension_manager
.add_client(
extension,
Some(session.working_dir.clone()),
calculator.clone(),
calculator.get_info().cloned(),
)
+6 -17
View File
@@ -1,5 +1,4 @@
use crate::agents::ExtensionManager;
use rmcp::model::ErrorData;
use crate::agents::extension_manager::ExtensionLease;
use serde::{Deserialize, Serialize};
use tokio_util::sync::CancellationToken;
use tracing::warn;
@@ -209,22 +208,12 @@ impl GooseApp {
}
}
pub async fn fetch_mcp_apps(
extension_manager: &ExtensionManager,
session_id: &str,
) -> Result<Vec<GooseApp>, ErrorData> {
pub async fn fetch_mcp_apps(lease: &ExtensionLease) -> Vec<GooseApp> {
let mut apps = Vec::new();
let ui_resources = extension_manager.get_ui_resources(session_id).await?;
for (extension_name, resource) in ui_resources {
match extension_manager
.read_resource(
session_id,
&resource.uri,
&extension_name,
CancellationToken::default(),
)
for (extension_name, resource) in lease.ui_resources().await {
match lease
.read_resource(&resource.uri, &extension_name, CancellationToken::default())
.await
{
Ok(read_result) => {
@@ -309,5 +298,5 @@ pub async fn fetch_mcp_apps(
}
}
Ok(apps)
apps
}
+39 -65
View File
@@ -1,6 +1,5 @@
use super::discover_skills_with_config;
use super::loaded_skill_context_with_args;
use crate::agents::extension::PlatformExtensionContext;
use crate::agents::mcp_client::{Error, McpClientTrait};
use crate::agents::ToolCallContext;
use crate::config::Config;
@@ -18,30 +17,24 @@ pub static EXTENSION_NAME: &str = "skills";
pub struct SkillsClient {
info: InitializeResult,
working_dir: PathBuf,
exclude_builtin_skills: bool,
config: &'static Config,
}
impl SkillsClient {
pub fn new(context: PlatformExtensionContext) -> anyhow::Result<Self> {
let working_dir = context
.session
.as_ref()
.map(|s| s.working_dir.clone())
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
impl Default for SkillsClient {
fn default() -> Self {
let info = InitializeResult::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(Implementation::new(EXTENSION_NAME, "1.0.0").with_title("Skills"));
Ok(Self {
Self {
info,
working_dir,
exclude_builtin_skills: false,
config: Config::global(),
})
}
}
}
impl SkillsClient {
/// Controls whether Goose's bundled skills are exposed by this client.
/// Bundled skills are enabled by default.
pub fn with_builtin_skills(mut self, enabled: bool) -> Self {
@@ -55,8 +48,8 @@ impl SkillsClient {
self
}
fn discover_skills(&self) -> Vec<SourceEntry> {
discover_skills_with_config(Some(&self.working_dir), self.config)
fn discover_skills(&self, working_dir: &Path) -> Vec<SourceEntry> {
discover_skills_with_config(Some(working_dir), self.config)
.into_iter()
.filter(|skill| {
!self.exclude_builtin_skills || skill.source_type != SourceType::BuiltinSkill
@@ -111,7 +104,7 @@ impl McpClientTrait for SkillsClient {
async fn call_tool(
&self,
_ctx: &ToolCallContext,
ctx: &ToolCallContext,
name: &str,
arguments: Option<JsonObject>,
_cancellation_token: CancellationToken,
@@ -139,7 +132,11 @@ impl McpClientTrait for SkillsClient {
.and_then(|args| args.get("args"))
.and_then(|v| v.as_str());
let skills = self.discover_skills();
let working_dir = ctx
.working_dir
.clone()
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
let skills = self.discover_skills(&working_dir);
if let Some(skill) = skills.iter().find(|s| s.name == skill_name) {
return match loaded_skill_context_with_args(skill, args) {
@@ -243,8 +240,8 @@ impl McpClientTrait for SkillsClient {
Some(&self.info)
}
fn get_instructions(&self) -> Option<String> {
let sources = self.discover_skills();
async fn get_instructions(&self, _session_id: &str, working_dir: &Path) -> Option<String> {
let sources = self.discover_skills(working_dir);
let mut skills: Vec<&SourceEntry> = sources
.iter()
.filter(|s| {
@@ -278,7 +275,6 @@ mod tests {
use crate::config::Config;
use std::collections::HashMap;
use std::fs;
use std::sync::Arc;
use tempfile::TempDir;
fn write_plugin_skill(
@@ -326,21 +322,9 @@ mod tests {
)]),
)
.unwrap();
let session = Arc::new(crate::session::Session {
working_dir: project.to_path_buf(),
..crate::session::Session::default()
});
SkillsClient::new(PlatformExtensionContext {
extension_manager: None,
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager: Arc::new(crate::session::SessionManager::instance()),
scheduler: None,
session: Some(session),
use_login_shell_path: false,
})
.unwrap()
.with_builtin_skills(false)
.with_config(config)
SkillsClient::default()
.with_builtin_skills(false)
.with_config(config)
}
fn result_text(result: &CallToolResult) -> &str {
@@ -364,10 +348,12 @@ mod tests {
let client = test_client(project.path(), "disabled-plugin", false);
assert!(client
.get_instructions()
.get_instructions("test", project.path())
.await
.is_none_or(|instructions| !instructions.contains("disabled-plugin-skill")));
let ctx = ToolCallContext::new("test".to_string(), None, None);
let ctx =
ToolCallContext::new("test".to_string(), Some(project.path().to_path_buf()), None);
let args = serde_json::from_value(serde_json::json!({
"name": "disabled-plugin-skill"
}))
@@ -404,13 +390,17 @@ mod tests {
write_open_plugin_manifest(project.path(), "enabled-plugin");
let client = test_client(project.path(), "enabled-plugin", true);
let instructions = client.get_instructions().unwrap();
let instructions = client
.get_instructions("test", project.path())
.await
.unwrap();
assert!(instructions.contains("enabled-plugin-skill"));
assert!(instructions.contains("Enabled plugin metadata"));
assert!(instructions.contains("custom-plugin-skill"));
assert!(instructions.contains("Custom plugin metadata"));
let ctx = ToolCallContext::new("test".to_string(), None, None);
let ctx =
ToolCallContext::new("test".to_string(), Some(project.path().to_path_buf()), None);
let args = serde_json::from_value(serde_json::json!({
"name": "custom-plugin-skill"
}))
@@ -447,7 +437,8 @@ mod tests {
std::os::unix::fs::symlink(&external_plugin, &plugin_link).unwrap();
let client = test_client(project.path(), "symlinked-plugin", true);
let ctx = ToolCallContext::new("test".to_string(), None, None);
let ctx =
ToolCallContext::new("test".to_string(), Some(project.path().to_path_buf()), None);
let args = serde_json::from_value(serde_json::json!({
"name": "symlinked-skill/guide.md"
}))
@@ -474,27 +465,18 @@ mod tests {
fs::create_dir(skill_dir.join("nested")).unwrap();
fs::write(skill_dir.join("nested/guide.md"), "Nested guidance.").unwrap();
let session = std::sync::Arc::new(crate::session::Session {
working_dir: temp_dir.path().to_path_buf(),
..crate::session::Session::default()
});
let client = SkillsClient::new(PlatformExtensionContext {
extension_manager: None,
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager: Arc::new(crate::session::SessionManager::instance()),
scheduler: None,
session: Some(session),
use_login_shell_path: false,
})
.unwrap()
.with_builtin_skills(false);
let client = SkillsClient::default().with_builtin_skills(false);
assert!(client
.discover_skills()
.discover_skills(temp_dir.path())
.iter()
.all(|skill| skill.source_type != SourceType::BuiltinSkill));
let ctx = ToolCallContext::new("test".to_string(), None, None);
let ctx = ToolCallContext::new(
"test".to_string(),
Some(temp_dir.path().to_path_buf()),
None,
);
let args: JsonObject =
serde_json::from_value(serde_json::json!({"name": "my-skill"})).unwrap();
let result = client
@@ -528,15 +510,7 @@ mod tests {
#[tokio::test]
async fn test_load_skill_not_found_returns_error() {
let client = SkillsClient::new(PlatformExtensionContext {
extension_manager: None,
provider: Arc::new(tokio::sync::Mutex::new(None)),
session_manager: Arc::new(crate::session::SessionManager::instance()),
scheduler: None,
session: None,
use_login_shell_path: false,
})
.unwrap();
let client = SkillsClient::default();
let ctx = ToolCallContext::new("test".to_string(), None, None);
let args: JsonObject =
+15 -1
View File
@@ -557,6 +557,14 @@ async fn extension_lifecycle_across_real_transports(stdio_version: ProtocolVersi
assert!(load_leased_skill(&after_move)
.await
.contains("new workspace"));
// `session` still names the old directory; the add follows the stored one.
fx.add(&session, &stdio).await;
let re_added = fx
.resolve(&moved_session, std::slice::from_ref(&stdio))
.await;
let re_added_stdio = inspect_context(&re_added, "fixture_stdio__inspect_context").await;
assert_eq!(re_added_stdio.roots, after_stdio.roots);
let retained_http = inspect_context(&before_move, "fixture_http__inspect_context").await;
let retained_stdio = inspect_context(&before_move, "fixture_stdio__inspect_context").await;
let old_root = url::Url::from_file_path(&session.working_dir)
@@ -928,7 +936,13 @@ async fn test_replayed_session(
Some("test-id".to_string()),
);
let result = extension_manager
.dispatch_tool_call(&ctx, tool_call, CancellationToken::default())
.current_lease(&ctx.session_id, ctx.working_dir.as_deref())
.await
.call(
tool_call,
CallRequest::from(&ctx),
CancellationToken::default(),
)
.await;
let tool_result = result?;
+8 -10
View File
@@ -2,6 +2,7 @@ use anyhow::Result;
use dotenvy::dotenv;
use futures::StreamExt;
use goose::acp::ACP_CURRENT_MODEL;
use goose::agents::extension_manager::CallRequest;
use goose::agents::{Agent, AgentConfig, AgentEvent, GoosePlatform, PromptManager, SessionConfig};
use goose::config::{ExtensionConfig, GooseMode, PermissionManager};
use goose::conversation::message::{ActionRequiredData, Message, MessageContent};
@@ -306,18 +307,13 @@ impl ProviderFixture {
prompt: &str,
model_config: Option<goose_providers::model::ModelConfig>,
) -> Result<Message> {
let tools = self
let lease = self
.agent
.extension_manager
.get_prefixed_tools(&self.session_id, None)
.await
.unwrap();
let info = self
.agent
.extension_manager
.get_extensions_info(std::path::Path::new("."))
.current_lease(&self.session_id, None)
.await;
let tools = lease.tools().await;
let info = lease.instructions().await;
let system = PromptManager::new()
.builder()
.with_extensions(info.into_iter())
@@ -363,7 +359,9 @@ impl ProviderFixture {
let result = self
.agent
.extension_manager
.dispatch_tool_call(&ctx, params, CancellationToken::new())
.current_lease(&ctx.session_id, ctx.working_dir.as_deref())
.await
.call(params, CallRequest::from(&ctx), CancellationToken::new())
.await
.unwrap()
.result