chore: remove ACP client-delegated developer tools (#13144)

This commit is contained in:
Jack Amadeo
2026-10-26 16:31:39 +00:00
committed by GitHub
parent bdb3e64867
commit 0a2f306815
16 changed files with 54 additions and 1412 deletions
-475
View File
@@ -1,475 +0,0 @@
use crate::acp::tool_call_notifier::ToolCallNotifier;
use crate::acp::tools::AcpAwareToolMeta;
use crate::agents::mcp_client::{Error as McpError, McpClientTrait};
use crate::agents::platform_extensions::developer::edit::{
resolve_path, string_replace, FileEditParams, FileReadParams, FileWriteParams,
};
use crate::agents::platform_extensions::developer::shell::{ShellParams, OUTPUT_LIMIT_BYTES};
use crate::agents::platform_extensions::developer::DeveloperClient;
use agent_client_protocol::schema::v1::{
CreateTerminalRequest, Diff, EnvVariable, KillTerminalRequest, ReadTextFileRequest,
ReleaseTerminalRequest, SessionId, Terminal, TerminalOutputRequest, ToolCallContent,
ToolCallId, ToolCallLocation, ToolCallUpdate, ToolCallUpdateFields, ToolKind,
WaitForTerminalExitRequest, WriteTextFileRequest,
};
use agent_client_protocol::{Client, ConnectionTo};
use agent_client_protocol_schema::v1::TerminalId;
use async_trait::async_trait;
use fs_err as fs;
use rmcp::model::{
Annotations, CallToolResult, ContentBlock as RmcpContent, TextContent, Tool, ToolAnnotations,
};
use schemars::schema_for;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
async fn acp_read_text_file(
cx: &ConnectionTo<Client>,
session_id: &SessionId,
path: &Path,
line: Option<u32>,
limit: Option<u32>,
) -> Result<String, String> {
let mut request = ReadTextFileRequest::new(session_id.clone(), path.to_path_buf());
if let Some(l) = line {
request = request.line(l);
}
if let Some(l) = limit {
request = request.limit(l);
}
let response = cx
.send_request(request)
.block_task()
.await
.map_err(|e| format!("{e:?}"))?;
Ok(response.content)
}
async fn acp_write_text_file(
cx: &ConnectionTo<Client>,
session_id: &SessionId,
path: &Path,
content: &str,
) -> Result<(), String> {
let request =
WriteTextFileRequest::new(session_id.clone(), path.to_path_buf(), content.to_string());
cx.send_request(request)
.block_task()
.await
.map_err(|e| format!("{e:?}"))?;
Ok(())
}
pub(crate) struct AcpTools {
pub(crate) inner: Arc<dyn McpClientTrait>,
pub(crate) cx: ConnectionTo<Client>,
pub(crate) session_id: SessionId,
pub(crate) tool_call_notifier: ToolCallNotifier,
pub(crate) fs_read: bool,
pub(crate) fs_write: bool,
pub(crate) terminal: bool,
}
fn create_terminal_request(
session_id: &SessionId,
params: &ShellParams,
ctx: &crate::agents::ToolCallContext,
) -> CreateTerminalRequest {
CreateTerminalRequest::new(session_id.clone(), &params.command)
.env(vec![EnvVariable::new("AGENT_SESSION_ID", &ctx.session_id)])
.cwd(ctx.working_dir.clone())
.output_byte_limit(OUTPUT_LIMIT_BYTES as u64)
}
fn visible_text(text: impl Into<String>) -> RmcpContent {
RmcpContent::Text(
TextContent::new(text).with_annotations(Annotations::default().with_priority(0.0)),
)
}
fn error_result(msg: impl std::fmt::Display) -> CallToolResult {
CallToolResult::error(vec![visible_text(msg.to_string())])
}
fn fail(action: &str, path: &str, err: impl std::fmt::Display) -> CallToolResult {
error_result(format!("Failed to {action} {path}: {err}"))
}
fn read_tool() -> Tool {
let schema = serde_json::to_value(schema_for!(FileReadParams))
.expect("schema serialization should succeed")
.as_object()
.expect("schema should serialize to an object")
.clone();
Tool::new("read", "Read a text file from disk.", schema).annotate(
ToolAnnotations::with_title("Read")
.read_only(true)
.destructive(false)
.idempotent(false)
.open_world(false),
)
}
impl AcpTools {
fn update_tool_call(&self, ctx: &crate::agents::ToolCallContext, fields: ToolCallUpdateFields) {
if let Some(ref req_id) = ctx.tool_call_request_id {
let _ = self
.tool_call_notifier
.send_update(ToolCallUpdate::new(ToolCallId::new(req_id.clone()), fields))
.inspect_err(|e| tracing::error!("error updating tool call with client: {}", e));
}
}
fn parse_args<T: serde::de::DeserializeOwned>(
arguments: Option<rmcp::model::JsonObject>,
) -> Result<T, String> {
DeveloperClient::parse_args(arguments).map_err(|e| format!("Error: {e}"))
}
async fn read_content(&self, path: &Path) -> Result<String, String> {
if self.fs_read {
acp_read_text_file(&self.cx, &self.session_id, path, None, None).await
} else {
fs::read_to_string(path).map_err(|e| e.to_string())
}
}
async fn acp_read(
&self,
arguments: Option<rmcp::model::JsonObject>,
ctx: &crate::agents::ToolCallContext,
) -> Result<CallToolResult, McpError> {
let params: FileReadParams = match Self::parse_args(arguments) {
Ok(p) => p,
Err(e) => return Ok(error_result(e)),
};
let path = resolve_path(&params.path, ctx.working_dir.as_deref());
self.update_tool_call(
ctx,
ToolCallUpdateFields::new()
.kind(ToolKind::Read)
.locations(vec![ToolCallLocation::new(&path).line(params.line)]),
);
match acp_read_text_file(&self.cx, &self.session_id, &path, params.line, params.limit).await
{
Ok(content) => Ok(CallToolResult::success(vec![visible_text(content)])),
Err(e) => Ok(fail("read", &params.path, e)),
}
}
async fn acp_write(
&self,
arguments: Option<rmcp::model::JsonObject>,
ctx: &crate::agents::ToolCallContext,
) -> Result<CallToolResult, McpError> {
let params: FileWriteParams = match Self::parse_args(arguments) {
Ok(p) => p,
Err(e) => return Ok(error_result(e)),
};
let path = resolve_path(&params.path, ctx.working_dir.as_deref());
self.update_tool_call(
ctx,
ToolCallUpdateFields::new()
.kind(ToolKind::Edit)
.locations(vec![ToolCallLocation::new(&path)]),
);
match acp_write_text_file(&self.cx, &self.session_id, &path, &params.content).await {
Ok(()) => {
self.update_tool_call(
ctx,
ToolCallUpdateFields::new().content(vec![ToolCallContent::Diff(Diff::new(
&path,
&params.content,
))]),
);
let line_count = params.content.lines().count();
let action = if path.exists() { "Wrote" } else { "Created" };
Ok(CallToolResult::success(vec![visible_text(format!(
"{action} {} ({line_count} lines)",
params.path
))]))
}
Err(e) => Ok(fail("write", &params.path, e)),
}
}
async fn acp_edit(
&self,
arguments: Option<rmcp::model::JsonObject>,
ctx: &crate::agents::ToolCallContext,
) -> Result<CallToolResult, McpError> {
let params: FileEditParams = match Self::parse_args(arguments) {
Ok(p) => p,
Err(e) => return Ok(error_result(e)),
};
let path = resolve_path(&params.path, ctx.working_dir.as_deref());
self.update_tool_call(
ctx,
ToolCallUpdateFields::new()
.kind(ToolKind::Edit)
.locations(vec![ToolCallLocation::new(&path)]),
);
let content = match self.read_content(&path).await {
Ok(c) => c,
Err(e) => return Ok(fail("read", &params.path, e)),
};
let new_content = match string_replace(&content, &params.before, &params.after) {
Ok(c) => c,
Err(msg) => return Ok(error_result(msg)),
};
let write_result = if self.fs_write {
acp_write_text_file(&self.cx, &self.session_id, &path, &new_content).await
} else {
fs::write(&path, &new_content).map_err(|e| e.to_string())
};
match write_result {
Ok(()) => {
self.update_tool_call(
ctx,
ToolCallUpdateFields::new().content(vec![ToolCallContent::Diff(
Diff::new(&path, &new_content).old_text(&content),
)]),
);
let old_lines = params.before.lines().count();
let new_lines = params.after.lines().count();
Ok(CallToolResult::success(vec![visible_text(format!(
"Edited {} ({old_lines} lines -> {new_lines} lines)",
params.path
))]))
}
Err(e) => Ok(fail("write", &params.path, e)),
}
}
async fn acp_shell(
&self,
arguments: Option<rmcp::model::JsonObject>,
ctx: &crate::agents::ToolCallContext,
) -> Result<CallToolResult, McpError> {
let params: ShellParams = match Self::parse_args(arguments) {
Ok(p) => p,
Err(e) => return Ok(error_result(e)),
};
self.update_tool_call(ctx, ToolCallUpdateFields::new().kind(ToolKind::Execute));
let create_res = self
.cx
.send_request(create_terminal_request(&self.session_id, &params, ctx))
.block_task()
.await
.map_err(|e| {
McpError::McpError(rmcp::model::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
format!("failed to create terminal: {e:?}"),
None,
))
})?;
let terminal_id = create_res.terminal_id;
self.update_tool_call(
ctx,
ToolCallUpdateFields::new().content(vec![ToolCallContent::Terminal(Terminal::new(
terminal_id.clone(),
))]),
);
let result = self
.run_terminal_to_completion(&terminal_id, params.timeout_secs)
.await;
// Always release the terminal, even if we hit errors above.
let _ = self
.cx
.send_request(ReleaseTerminalRequest::new(
self.session_id.clone(),
terminal_id.clone(),
))
.block_task()
.await
.inspect_err(|e| tracing::error!("failed to release terminal: {e:?}"));
let output_res = result?;
let exit_code = output_res
.exit_status
.and_then(|s| s.exit_code)
.unwrap_or_default();
let content = vec![
visible_text(format!("exit code: {exit_code}")),
visible_text(output_res.output),
];
if exit_code != 0 {
Ok(CallToolResult::error(content))
} else {
Ok(CallToolResult::success(content))
}
}
async fn run_terminal_to_completion(
&self,
terminal_id: &TerminalId,
timeout_secs: Option<u64>,
) -> Result<agent_client_protocol::schema::v1::TerminalOutputResponse, McpError> {
let wait_fut = self
.cx
.send_request(WaitForTerminalExitRequest::new(
self.session_id.clone(),
terminal_id.clone(),
))
.block_task();
let timed_out = match timeout_secs {
Some(secs) if secs > 0 => match timeout(Duration::from_secs(secs), wait_fut).await {
Ok(res) => {
res.map_err(|e| {
McpError::McpError(rmcp::model::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
format!("failed to wait for terminal exit: {e:?}"),
None,
))
})?;
false
}
Err(_) => {
let _ = self
.cx
.send_request(KillTerminalRequest::new(
self.session_id.clone(),
terminal_id.clone(),
))
.block_task()
.await
.inspect_err(|e| tracing::error!("failed to kill terminal: {e:?}"));
true
}
},
_ => {
wait_fut.await.map_err(|e| {
McpError::McpError(rmcp::model::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
format!("failed to wait for terminal exit: {e:?}"),
None,
))
})?;
false
}
};
let mut output_res = self
.cx
.send_request(TerminalOutputRequest::new(
self.session_id.clone(),
terminal_id.clone(),
))
.block_task()
.await
.map_err(|e| {
McpError::McpError(rmcp::model::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
format!("failed to get terminal output: {e:?}"),
None,
))
})?;
if timed_out {
output_res.output.push_str(&format!(
"\n\nCommand timed out after {} seconds",
timeout_secs.unwrap_or(0)
));
}
Ok(output_res)
}
}
#[async_trait]
impl McpClientTrait for AcpTools {
async fn list_tools(
&self,
session_id: &str,
next_cursor: Option<String>,
cancellation_token: CancellationToken,
) -> Result<rmcp::model::ListToolsResult, McpError> {
let mut result = self
.inner
.list_tools(session_id, next_cursor, cancellation_token)
.await?;
if self.fs_read {
result.tools.insert(0, read_tool());
}
Ok(result)
}
async fn call_tool(
&self,
ctx: &crate::agents::ToolCallContext,
name: &str,
arguments: Option<rmcp::model::JsonObject>,
cancellation_token: CancellationToken,
) -> Result<CallToolResult, McpError> {
match name {
"read" if self.fs_read => self
.acp_read(arguments, ctx)
.await
.map(|r| r.with_acp_aware_meta()),
"write" if self.fs_write => self
.acp_write(arguments, ctx)
.await
.map(|r| r.with_acp_aware_meta()),
"edit" if self.fs_read && self.fs_write => self
.acp_edit(arguments, ctx)
.await
.map(|r| r.with_acp_aware_meta()),
"shell" if self.terminal => self
.acp_shell(arguments, ctx)
.await
.map(|r| r.with_acp_aware_meta()),
_ => {
self.inner
.call_tool(ctx, name, arguments, cancellation_token)
.await
}
}
}
fn get_info(&self) -> Option<&rmcp::model::InitializeResult> {
self.inner.get_info()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::agents::ToolCallContext;
#[test]
fn terminal_request_includes_agent_session_id() {
let session_id = SessionId::new("acp-session");
let params = ShellParams {
command: "echo test".to_string(),
timeout_secs: None,
};
let ctx = ToolCallContext::new(
"agent-session".to_string(),
Some(std::path::PathBuf::from("/tmp/worktree")),
None,
);
let request = create_terminal_request(&session_id, &params, &ctx);
assert_eq!(
request.env,
vec![EnvVariable::new("AGENT_SESSION_ID", "agent-session")]
);
assert_eq!(request.cwd, Some(std::path::PathBuf::from("/tmp/worktree")));
}
}
-2
View File
@@ -1,5 +1,4 @@
mod common;
pub(crate) mod fs;
mod handoff;
#[cfg(feature = "acp-http")]
mod mcp_app_proxy;
@@ -8,7 +7,6 @@ mod response_builder;
pub mod server;
pub mod server_factory;
pub(crate) mod tool_call_notifier;
pub(crate) mod tools;
#[cfg(feature = "acp-http")]
pub mod transport;
+12 -89
View File
@@ -1,6 +1,5 @@
use crate::acp::custom_notifications::*;
use crate::acp::custom_requests::*;
use crate::acp::fs::AcpTools;
pub(super) use crate::acp::response_builder::{
agent_thinking_effort_support, build_config_options, build_mode_state, build_model_state,
build_provider_options, build_session_info, build_session_setup_config,
@@ -10,8 +9,7 @@ pub(super) use crate::acp::response_builder::{
use crate::acp::tool_call_notifier::ToolCallNotifier;
use crate::acp::{PermissionDecision, ACP_CURRENT_MODEL};
use crate::agents::extension::{Envs, PLATFORM_EXTENSIONS};
use crate::agents::mcp_client::{GooseMcpHostInfo, McpClientTrait};
use crate::agents::platform_extensions::developer::DeveloperClient;
use crate::agents::mcp_client::GooseMcpHostInfo;
use crate::agents::state_machine::{
has_unapplied_tool_confirmation_response, pending_tool_confirmations, turn_failure,
};
@@ -47,17 +45,16 @@ use agent_client_protocol::schema::v1::{
AgentCapabilities, Annotations, AuthMethod, AuthMethodAgent, AuthenticateRequest,
AuthenticateResponse, CancelNotification, CloseSessionRequest, CloseSessionResponse,
ConfigOptionUpdate, ContentBlock, Cost, CurrentModeUpdate, DeleteSessionRequest,
DeleteSessionResponse, EmbeddedResourceResource, FileSystemCapabilities, ForkSessionRequest,
ForkSessionResponse, ImageContent, Implementation, InitializeRequest, InitializeResponse,
ListSessionsRequest, ListSessionsResponse, LoadSessionRequest, LoadSessionResponse,
McpCapabilities, McpServer, Meta, NewSessionRequest, NewSessionResponse, PermissionOption,
PermissionOptionKind, PromptCapabilities, PromptRequest, PromptResponse,
RequestPermissionOutcome, RequestPermissionRequest, ResourceLink, SessionCapabilities,
SessionCloseCapabilities, SessionConfigOption, SessionDeleteCapabilities, SessionId,
SessionInfoUpdate, SessionListCapabilities, SessionNotification, SessionUpdate,
SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, SetSessionModeRequest,
SetSessionModeResponse, StopReason, TextContent, ToolCallId, ToolCallUpdate, Usage,
UsageUpdate,
DeleteSessionResponse, EmbeddedResourceResource, ForkSessionRequest, ForkSessionResponse,
ImageContent, Implementation, InitializeRequest, InitializeResponse, ListSessionsRequest,
ListSessionsResponse, LoadSessionRequest, LoadSessionResponse, McpCapabilities, McpServer,
Meta, NewSessionRequest, NewSessionResponse, PermissionOption, PermissionOptionKind,
PromptCapabilities, PromptRequest, PromptResponse, RequestPermissionOutcome,
RequestPermissionRequest, ResourceLink, SessionCapabilities, SessionCloseCapabilities,
SessionConfigOption, SessionDeleteCapabilities, SessionId, SessionInfoUpdate,
SessionListCapabilities, SessionNotification, SessionUpdate, SetSessionConfigOptionRequest,
SetSessionConfigOptionResponse, SetSessionModeRequest, SetSessionModeResponse, StopReason,
TextContent, ToolCallId, ToolCallUpdate, Usage, UsageUpdate,
};
use agent_client_protocol::schema::ProtocolVersion;
use agent_client_protocol::util::MatchDispatchFrom;
@@ -318,8 +315,6 @@ pub struct GooseAcpAgent {
agent_manager: Arc<AgentManager>,
provider_factory: AcpProviderFactory,
builtin_selection: AcpBuiltinSelection,
client_fs_capabilities: OnceCell<FileSystemCapabilities>,
client_terminal: OnceCell<bool>,
client_mcp_host_info: OnceCell<GooseMcpHostInfo>,
client_supports_acp_elicitation: OnceCell<bool>,
client_supports_goose_custom_notifications: OnceCell<bool>,
@@ -945,8 +940,6 @@ impl GooseAcpAgent {
agent_manager,
provider_factory: options.provider_factory,
builtin_selection: options.builtin_selection,
client_fs_capabilities: OnceCell::new(),
client_terminal: OnceCell::new(),
client_mcp_host_info: OnceCell::new(),
client_supports_acp_elicitation: OnceCell::new(),
client_supports_goose_custom_notifications: OnceCell::new(),
@@ -1034,70 +1027,6 @@ impl GooseAcpAgent {
.map_err(|error| agent_creation_error(error, "Failed to create agent"))
}
async fn apply_acp_extension_overrides(
&self,
cx: &ConnectionTo<Client>,
agent: &Arc<Agent>,
session: &Session,
) -> Result<(), agent_client_protocol::Error> {
let client_fs_capabilities = self
.client_fs_capabilities
.get()
.cloned()
.unwrap_or_default();
let client_terminal = self.client_terminal.get().copied().unwrap_or(false);
if !client_fs_capabilities.read_text_file
&& !client_fs_capabilities.write_text_file
&& !client_terminal
{
return Ok(());
}
if !agent
.extension_manager
.is_extension_enabled(&session.id, "developer")
.await
.internal_err()?
{
return Ok(());
}
let dev_client = match DeveloperClient::new() {
Ok(dev_client) => dev_client,
Err(error) => {
warn!(error = %error, "Failed to create ACP developer client");
return Ok(());
}
};
let session_id = SessionId::new(session.id.clone());
let client: Arc<dyn McpClientTrait> = Arc::new(AcpTools {
inner: Arc::new(dev_client),
cx: cx.clone(),
session_id: session_id.clone(),
tool_call_notifier: ToolCallNotifier::new(cx, &session_id),
fs_read: client_fs_capabilities.read_text_file,
fs_write: client_fs_capabilities.write_text_file,
terminal: client_terminal,
});
let info = client.get_info().cloned();
let developer_config = agent
.extension_manager
.get_extension_configs(&session.id)
.await
.internal_err()?
.into_iter()
.find(|extension| extension.name() == "developer")
.unwrap_or_else(|| builtin_to_extension_config("developer"));
agent
.extension_manager
.add_client(&session.id, developer_config, client, info)
.await;
Ok(())
}
async fn prepare_acp_session_agent(
&self,
cx: &ConnectionTo<Client>,
@@ -1106,8 +1035,6 @@ impl GooseAcpAgent {
let agent = self
.get_or_create_session_agent(cx, session.id.clone())
.await?;
self.apply_acp_extension_overrides(cx, &agent, session)
.await?;
// Leases start extensions on first use anyway; starting them here is
// what lets the session response report extensions that fail.
let extension_results = agent
@@ -1518,7 +1445,7 @@ impl GooseAcpAgent {
session_id: &SessionId,
cx: &ConnectionTo<Client>,
) -> Result<(), agent_client_protocol::Error> {
let fields = tool_call_update_fields_from_response(tool_response, tool_request, false);
let fields = tool_call_update_fields_from_response(tool_response, tool_request);
let update = ToolCallUpdate::new(ToolCallId::new(tool_response.id.clone()), fields)
.meta(tool_response_meta(tool_response));
@@ -1767,10 +1694,6 @@ impl GooseAcpAgent {
) -> Result<InitializeResponse, agent_client_protocol::Error> {
debug!(?args, "initialize request");
let _ = self
.client_fs_capabilities
.set(args.client_capabilities.fs.clone());
let _ = self.client_terminal.set(args.client_capabilities.terminal);
let goose_client_capabilities =
extract_client_capabilities_meta(&args).and_then(|meta| meta.goose);
let _ = self.client_mcp_host_info.set(extract_client_mcp_host_info(
+2 -2
View File
@@ -25,8 +25,8 @@ impl HandleDispatchFrom<Client> for GooseAcpHandler {
agent.start_thinking_effort_update_forwarder(&cx).await;
// InitializeRequest runs inline: it sets connection-scoped state
// (client fs/terminal capabilities) that later handlers read with
// defaults, so a pipelined NewSessionRequest must not race ahead of it.
// that later handlers read with defaults, so a pipelined
// NewSessionRequest must not race ahead of it.
MatchDispatchFrom::new(message, &cx)
.if_request(
|req: InitializeRequest, responder: Responder<InitializeResponse>| async {
@@ -170,7 +170,6 @@ fn replay_conversation_to_client(
let fields = tool_call_update_fields_from_response(
tool_response,
replay_tool_requests.get(&tool_response.id),
true,
);
let meta = tool_response_meta(tool_response).unwrap_or_default();
@@ -1,4 +1,3 @@
use crate::acp::tools::AcpAwareToolMeta;
use crate::agents::extension_manager::TRUSTED_TOOL_UPDATE_META_KEY;
use crate::conversation::message::{Message, ToolNameParts, ToolRequest, ToolResponse};
use crate::mcp_utils::ToolResult;
@@ -297,7 +296,6 @@ fn extract_tool_raw_output(tool_result: &ToolResult<CallToolResult>) -> Option<s
pub(crate) fn tool_call_update_fields_from_response(
tool_response: &ToolResponse,
tool_request: Option<&ToolRequest>,
include_content_for_acp_aware_tools: bool,
) -> ToolCallUpdateFields {
let is_failed = match &tool_response.tool_result {
Ok(result) => result.is_error == Some(true),
@@ -313,26 +311,15 @@ pub(crate) fn tool_call_update_fields_from_response(
if let Some(raw_output) = extract_tool_raw_output(&tool_response.tool_result) {
fields = fields.raw_output(raw_output);
}
let is_acp_aware = tool_response
.tool_result
.as_ref()
.is_ok_and(|result| result.is_acp_aware());
let include_content = include_content_for_acp_aware_tools || is_failed || !is_acp_aware;
let include_locations = !is_acp_aware;
fields = fields.content(build_tool_call_content(&tool_response.tool_result));
if include_content {
fields = fields.content(build_tool_call_content(&tool_response.tool_result));
}
if include_locations {
let locations = extract_tool_locations_from_response(tool_response).unwrap_or_else(|| {
tool_request
.map(extract_tool_locations_from_request)
.unwrap_or_default()
});
if !locations.is_empty() {
fields = fields.locations(locations);
}
let locations = extract_tool_locations_from_response(tool_response).unwrap_or_else(|| {
tool_request
.map(extract_tool_locations_from_request)
.unwrap_or_default()
});
if !locations.is_empty() {
fields = fields.locations(locations);
}
fields
@@ -842,7 +829,7 @@ mod tests {
let response = response_from_tool_result(Ok(result));
let request = write_request("/tmp/request.txt");
let fields = tool_call_update_fields_from_response(&response, Some(&request), false);
let fields = tool_call_update_fields_from_response(&response, Some(&request));
assert_eq!(fields.status, Some(ToolCallStatus::Completed));
assert_eq!(fields.raw_output, Some(raw_output));
@@ -860,41 +847,13 @@ mod tests {
"write failed",
)])));
let fields = tool_call_update_fields_from_response(&response, None, false);
let fields = tool_call_update_fields_from_response(&response, None);
assert_eq!(fields.status, Some(ToolCallStatus::Failed));
assert_eq!(first_tool_call_text(&fields), Some("write failed"));
assert!(fields.locations.is_none());
}
#[test]
fn suppresses_acp_aware_success_details() {
let raw_output = serde_json::json!({ "changed": true });
let mut result = CallToolResult::success(vec![RmcpContent::text("write completed")]);
result.structured_content = Some(raw_output.clone());
let response = response_from_tool_result(Ok(result.with_acp_aware_meta()));
let request = write_request("/tmp/request.txt");
let fields = tool_call_update_fields_from_response(&response, Some(&request), false);
assert_eq!(fields.status, Some(ToolCallStatus::Completed));
assert_eq!(fields.raw_output, Some(raw_output));
assert!(fields.content.is_none());
assert!(fields.locations.is_none());
}
#[test]
fn includes_acp_aware_success_content_when_requested() {
let result = CallToolResult::success(vec![RmcpContent::text("write completed")])
.with_acp_aware_meta();
let response = response_from_tool_result(Ok(result));
let fields = tool_call_update_fields_from_response(&response, None, true);
assert_eq!(fields.status, Some(ToolCallStatus::Completed));
assert_eq!(first_tool_call_text(&fields), Some("write completed"));
}
#[test]
fn prefers_explicit_location() {
let response = response_with_meta(Some(serde_json::json!({
@@ -902,7 +861,7 @@ mod tests {
})));
let request = write_request("/tmp/request.txt");
let fields = tool_call_update_fields_from_response(&response, Some(&request), false);
let fields = tool_call_update_fields_from_response(&response, Some(&request));
let locations = fields.locations.as_deref().expect("expected location");
assert_eq!(locations.len(), 1);
@@ -910,20 +869,6 @@ mod tests {
assert_eq!(locations[0].line, Some(7));
}
#[test]
fn includes_acp_aware_error_content() {
let result = CallToolResult::error(vec![RmcpContent::text("write failed")])
.with_acp_aware_meta();
let response = response_from_tool_result(Ok(result));
let request = write_request("/tmp/request.txt");
let fields = tool_call_update_fields_from_response(&response, Some(&request), false);
assert_eq!(fields.status, Some(ToolCallStatus::Failed));
assert_eq!(first_tool_call_text(&fields), Some("write failed"));
assert!(fields.locations.is_none());
}
#[test]
fn includes_transport_error_content() {
let response = response_from_tool_result(Err(rmcp::model::ErrorData::new(
@@ -932,7 +877,7 @@ mod tests {
None,
)));
let fields = tool_call_update_fields_from_response(&response, None, false);
let fields = tool_call_update_fields_from_response(&response, None);
assert_eq!(fields.status, Some(ToolCallStatus::Failed));
assert_eq!(first_tool_call_text(&fields), Some("transport failed"));
-25
View File
@@ -1,25 +0,0 @@
use rmcp::{
model::{CallToolResult, MetaObject},
object,
};
const ACP_AWARE_META_KEY: &str = "_goose/acp-aware";
pub trait AcpAwareToolMeta {
fn with_acp_aware_meta(self) -> Self;
fn is_acp_aware(&self) -> bool;
}
impl AcpAwareToolMeta for CallToolResult {
fn with_acp_aware_meta(self) -> Self {
self.with_meta(Some(MetaObject(object!({ACP_AWARE_META_KEY: true}))))
}
fn is_acp_aware(&self) -> bool {
self.meta
.as_ref()
.and_then(|meta| meta.get(ACP_AWARE_META_KEY))
.and_then(|v| v.as_bool())
.unwrap_or(false)
}
}
@@ -7,17 +7,6 @@ use serde::Deserialize;
const NO_MATCH_PREVIEW_LINES: usize = 20;
#[derive(Debug, Deserialize, JsonSchema)]
pub struct FileReadParams {
/// Absolute path to the file to read.
pub path: String,
/// Line number to start reading from (1-based).
#[schemars(range(min = 1))]
pub line: Option<u32>,
/// Maximum number of lines to read.
pub limit: Option<u32>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct FileWriteParams {
pub path: String,
@@ -44,25 +33,6 @@ impl EditTools {
Self
}
pub fn file_read_with_cwd(
&self,
params: FileReadParams,
working_dir: Option<&Path>,
) -> CallToolResult {
let path = resolve_path(&params.path, working_dir);
match fs::read_to_string(&path) {
Ok(content) => {
let content = apply_line_limit(&content, params.line, params.limit);
CallToolResult::success(vec![visible_text(content)])
}
Err(error) => CallToolResult::error(vec![visible_text(format!(
"Failed to read {}: {}",
params.path, error
))]),
}
}
pub fn file_write(&self, params: FileWriteParams) -> CallToolResult {
self.file_write_with_cwd(params, None)
}
@@ -195,22 +165,6 @@ pub fn string_replace(content: &str, before: &str, after: &str) -> Result<String
}
}
fn apply_line_limit(content: &str, line: Option<u32>, limit: Option<u32>) -> String {
if line.is_none() && limit.is_none() {
return content.to_string();
}
let lines: Vec<&str> = content.split_inclusive('\n').collect();
let start = line
.map(|l| (l as usize).saturating_sub(1))
.unwrap_or(0)
.min(lines.len());
let end = limit
.map(|l| start + l as usize)
.unwrap_or(lines.len())
.min(lines.len());
lines[start..end].concat()
}
pub fn resolve_path(path: &str, working_dir: Option<&Path>) -> PathBuf {
let path = PathBuf::from(path);
if path.is_absolute() {
@@ -283,7 +237,6 @@ mod tests {
use rmcp::model::ContentBlock;
use std::fs;
use tempfile::TempDir;
use test_case::test_case;
fn setup() -> TempDir {
tempfile::tempdir().unwrap()
@@ -296,58 +249,6 @@ mod tests {
}
}
#[test_case(None, None, "line1\nline2\nline3" ; "full content")]
#[test_case(Some(2), None, "line2\nline3" ; "from line 2")]
#[test_case(None, Some(2), "line1\nline2\n" ; "limit 2")]
#[test_case(Some(2), Some(1), "line2\n" ; "line 2 limit 1")]
#[test_case(Some(99), None, "" ; "beyond eof")]
fn test_apply_line_limit(line: Option<u32>, limit: Option<u32>, expected: &str) {
assert_eq!(
apply_line_limit("line1\nline2\nline3", line, limit),
expected
);
}
#[test]
fn test_file_read() {
let dir = setup();
let path = dir.path().join("read.txt");
fs::write(&path, "line1\nline2\nline3").unwrap();
let tools = EditTools::new();
let result = tools.file_read_with_cwd(
FileReadParams {
path: path.to_string_lossy().to_string(),
line: None,
limit: None,
},
None,
);
assert!(!result.is_error.unwrap_or(false));
assert_eq!(extract_text(&result), "line1\nline2\nline3");
}
#[test]
fn test_file_read_partial() {
let dir = setup();
let path = dir.path().join("read.txt");
fs::write(&path, "line1\nline2\nline3").unwrap();
let tools = EditTools::new();
let result = tools.file_read_with_cwd(
FileReadParams {
path: path.to_string_lossy().to_string(),
line: Some(2),
limit: Some(1),
},
None,
);
assert!(!result.is_error.unwrap_or(false));
assert_eq!(extract_text(&result), "line2\n");
}
#[test]
fn test_file_write_new() {
let dir = setup();
+5 -177
View File
@@ -6,11 +6,11 @@
pub mod fixtures;
use agent_client_protocol::schema::v1::{
ContentBlock, ListSessionsResponse, McpServer, McpServerHttp, SessionInfo, SessionModeId,
SessionUpdate, ToolCallStatus, ToolKind,
SessionUpdate, ToolCallStatus,
};
use fixtures::{
assert_notifications, Connection, FsFixture, Notification, OpenAiFixture, PermissionDecision,
Session, SessionData, TerminalCall, TerminalFixture, TestConnectionConfig,
assert_notifications, Connection, Notification, OpenAiFixture, PermissionDecision, Session,
SessionData, TestConnectionConfig,
};
use fs_err as fs;
use goose::acp::server::AcpProviderFactory;
@@ -279,60 +279,7 @@ pub async fn run_config_mcp<C: Connection>() {
expected_session_id.assert_matches(&session.session_id().0);
}
// Also proves developer loaded from config.yaml (not CLI args) gets ACP fs delegation.
pub async fn run_fs_read_text_file_true<C: Connection>() {
let temp_dir = tempfile::tempdir().unwrap();
let config_yaml = format!(
"GOOSE_MODEL: {TEST_MODEL}\nGOOSE_PROVIDER: openai\nextensions:\n developer:\n enabled: true\n type: platform\n name: developer\n description: Developer\n display_name: Developer\n bundled: true\n available_tools: []\n"
);
fs::write(temp_dir.path().join(CONFIG_YAML_NAME), config_yaml).unwrap();
let expected_session_id = C::expected_session_id();
let prompt = "Use the read tool to read /tmp/test_acp_read.txt and output only its contents.";
let openai = OpenAiFixture::new(
vec![
(
prompt.to_string(),
include_str!("../acp_test_data/openai_fs_read_tool_call.txt"),
),
(
r#""content":"test-read-content-12345""#.into(),
include_str!("../acp_test_data/openai_fs_read_tool_result.txt"),
),
],
expected_session_id.clone(),
)
.await;
let fs = FsFixture::new();
let config = TestConnectionConfig {
read_text_file: Some(fs.read_handler("/tmp/test_acp_read.txt", "test-read-content-12345")),
data_root: temp_dir.path().to_path_buf(),
..Default::default()
};
let mut conn = C::new(config, openai).await;
let SessionData { mut session, .. } = conn.new_session().await.unwrap();
expected_session_id.set(&session.session_id().0);
let output = session
.prompt(prompt, PermissionDecision::Cancel)
.await
.unwrap();
assert_eq!(output.text, "test-read-content-12345");
assert_notifications(
&session.notifications(),
&[
Notification::ToolCall,
Notification::ToolCallKind(ToolKind::Read),
Notification::ToolCallStatus(ToolCallStatus::Completed),
Notification::AgentMessage,
],
);
fs.assert_called();
expected_session_id.assert_matches(&session.session_id().0);
}
pub async fn run_fs_write_text_file_false<C: Connection>() {
pub async fn run_write_file<C: Connection>() {
let _ = fs::remove_file("/tmp/test_acp_write.txt");
let expected_session_id = C::expected_session_id();
@@ -382,70 +329,6 @@ pub async fn run_fs_write_text_file_false<C: Connection>() {
expected_session_id.assert_matches(&session.session_id().0);
}
pub async fn run_fs_write_text_file_true<C: Connection>() {
let expected_session_id = C::expected_session_id();
let prompt =
"Use the write tool to write 'test-write-content-67890' to /tmp/test_acp_write.txt";
let openai = OpenAiFixture::new(
vec![
(
prompt.to_string(),
include_str!("../acp_test_data/openai_fs_write_tool_call.txt"),
),
(
r#" /tmp/test_acp_write.txt (1 lines)"#.into(),
include_str!("../acp_test_data/openai_fs_write_tool_result.txt"),
),
],
expected_session_id.clone(),
)
.await;
let fs = FsFixture::new();
let config = TestConnectionConfig {
builtins: vec!["developer".to_string()],
write_text_file: Some(
fs.write_handler("/tmp/test_acp_write.txt", "test-write-content-67890"),
),
..Default::default()
};
let mut conn = C::new(config, openai).await;
let SessionData { mut session, .. } = conn.new_session().await.unwrap();
expected_session_id.set(&session.session_id().0);
let output = session
.prompt(prompt, PermissionDecision::AllowOnce)
.await
.unwrap();
assert!(!output.text.is_empty());
let updates = session.session_updates();
let initial_tool_call_id = updates
.iter()
.find_map(|update| match update {
SessionUpdate::ToolCall(tool_call) => Some(&tool_call.tool_call_id),
_ => None,
})
.expect("expected an initial tool call");
for update in &updates {
if let SessionUpdate::ToolCallUpdate(update) = update {
assert_eq!(&update.tool_call_id, initial_tool_call_id);
}
}
assert_notifications(
&fixtures::to_notifications(&updates),
&[
Notification::ToolCall,
Notification::ToolCallKind(ToolKind::Edit),
Notification::ToolCallContent("diff".into()),
Notification::ToolCallStatus(ToolCallStatus::Completed),
Notification::AgentMessage,
],
);
fs.assert_called();
expected_session_id.assert_matches(&session.session_id().0);
}
pub async fn run_initialize_doesnt_hit_provider<C: Connection>() {
let provider_factory: AcpProviderFactory =
Arc::new(|_| Box::pin(async { Err(anyhow::anyhow!("no provider configured")) }));
@@ -1495,7 +1378,7 @@ pub async fn run_prompt_skill<C: Connection>() {
expected_session_id.assert_matches(&session.session_id().0);
}
pub async fn run_shell_terminal_false<C: Connection>() {
pub async fn run_shell<C: Connection>() {
let expected_session_id = C::expected_session_id();
let prompt = format!("Run the command echo {SHELL_TEST_CONTENT} and output only its result.");
let openai = OpenAiFixture::new(
@@ -1544,58 +1427,3 @@ pub async fn run_shell_terminal_false<C: Connection>() {
);
expected_session_id.assert_matches(&session.session_id().0);
}
pub async fn run_shell_terminal_true<C: Connection>() {
let expected_session_id = C::expected_session_id();
let prompt = format!("Run the command echo {SHELL_TEST_CONTENT} and output only its result.");
let openai = OpenAiFixture::new(
vec![
(
prompt.clone(),
include_str!("../acp_test_data/openai_shell_tool_call.txt"),
),
(
SHELL_TEST_CONTENT.into(),
include_str!("../acp_test_data/openai_shell_tool_result.txt"),
),
],
expected_session_id.clone(),
)
.await;
let command = format!("echo {SHELL_TEST_CONTENT}");
let output_text = format!("{SHELL_TEST_CONTENT}\n");
let tid = String::from("term-1");
let terminal = TerminalFixture::new(vec![
TerminalCall::Create(command.clone(), tid.clone()),
TerminalCall::WaitForExit(tid.clone(), 0),
TerminalCall::Output(tid.clone(), output_text.clone(), 0),
TerminalCall::Release(tid),
]);
let config = TestConnectionConfig {
builtins: vec!["developer".to_string()],
terminal: Some(terminal.clone()),
..Default::default()
};
let mut conn = C::new(config, openai).await;
let SessionData { mut session, .. } = conn.new_session().await.unwrap();
expected_session_id.set(&session.session_id().0);
let output = session
.prompt(&prompt, PermissionDecision::AllowOnce)
.await
.unwrap();
assert_eq!(output.tool_status, Some(ToolCallStatus::Completed));
assert_notifications(
&session.notifications(),
&[
Notification::ToolCall,
Notification::ToolCallKind(ToolKind::Execute),
Notification::ToolCallContent("terminal".into()),
Notification::ToolCallStatus(ToolCallStatus::Completed),
Notification::AgentMessage,
],
);
terminal.assert_called();
expected_session_id.assert_matches(&session.session_id().0);
}
+2 -65
View File
@@ -8,8 +8,7 @@ use agent_client_protocol::schema::v1::{
};
use common_tests::fixtures::server::AcpServerConnection;
use common_tests::fixtures::{
run_test, send_custom, Connection, PermissionDecision, Session, SessionData,
TestConnectionConfig,
run_test, send_custom, Connection, Session, SessionData, TestConnectionConfig,
};
use goose::acp::server::AcpProviderFactory;
use goose::providers::base::{MessageStream, Provider};
@@ -18,7 +17,7 @@ use goose_providers::model::ModelConfig;
use goose_test_support::{EnforceSessionId, IgnoreSessionId, McpFixture, FAKE_CODE};
use serial_test::serial;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock, Mutex};
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use common_tests::fixtures::OpenAiFixture;
@@ -1049,68 +1048,6 @@ fn test_custom_unknown_method() {
});
}
#[test]
#[serial]
fn test_developer_fs_requests_use_acp_session_id() {
run_test(async {
let seen_session_id = Arc::new(Mutex::new(None::<String>));
let seen_session_id_clone = Arc::clone(&seen_session_id);
let openai = OpenAiFixture::new(
vec![
(
"Use the read tool to read /tmp/test_acp_read.txt and output only its contents."
.to_string(),
include_str!("acp_test_data/openai_fs_read_tool_call.txt"),
),
(
r#""content":"test-read-content-12345""#.into(),
include_str!("acp_test_data/openai_fs_read_tool_result.txt"),
),
],
Arc::new(IgnoreSessionId),
)
.await;
let config_dir = write_acp_global_config(&format!(
"GOOSE_MODEL: gpt-4.1\nGOOSE_PROVIDER: openai\nOPENAI_HOST: {}\n",
openai.uri()
));
let config = TestConnectionConfig {
// gpt-5-nano routes to the Responses API; use a Chat Completions
// model so the canned SSE fixtures are parsed correctly.
data_root: config_dir,
current_model: "gpt-4.1".to_string(),
read_text_file: Some(Arc::new(move |req| {
*seen_session_id_clone.lock().unwrap() = Some(req.session_id.0.to_string());
Ok(
agent_client_protocol::schema::v1::ReadTextFileResponse::new(
"test-read-content-12345",
),
)
})),
..Default::default()
};
let mut conn = AcpServerConnection::new(config, openai).await;
let SessionData { mut session, .. } = conn.new_session().await.unwrap();
let acp_session_id = session.session_id().0.to_string();
let output = session
.prompt(
"Use the read tool to read /tmp/test_acp_read.txt and output only its contents.",
PermissionDecision::Cancel,
)
.await
.expect("prompt should succeed");
assert_eq!(output.text, "test-read-content-12345");
assert_eq!(
seen_session_id.lock().unwrap().as_deref(),
Some(acp_session_id.as_str()),
"ACP read request should use the ACP session/thread ID",
);
});
}
#[test]
#[serial]
fn test_custom_provider_supported_models_lists_raw_provider_models() {
+2 -195
View File
@@ -2,11 +2,8 @@
#![allow(unused_attributes)]
use agent_client_protocol::schema::v1::{
CreateTerminalResponse, KillTerminalResponse, ListSessionsResponse, McpServer,
ReadTextFileRequest, ReadTextFileResponse, ReleaseTerminalResponse, SessionModeState,
SessionUpdate, TerminalExitStatus, TerminalId, TerminalOutputResponse, ToolCallContent,
ToolCallStatus, ToolKind, WaitForTerminalExitResponse, WriteTextFileRequest,
WriteTextFileResponse,
ListSessionsResponse, McpServer, SessionModeState, SessionUpdate, ToolCallContent,
ToolCallStatus, ToolKind,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
@@ -535,190 +532,6 @@ pub fn assert_notifications(actual: &[Notification], expected: &[Notification])
assert_eq!(actual, expected);
}
type ReadTextFileHandler =
Arc<dyn Fn(&ReadTextFileRequest) -> Result<ReadTextFileResponse, String> + Send + Sync>;
type WriteTextFileHandler =
Arc<dyn Fn(&WriteTextFileRequest) -> Result<WriteTextFileResponse, String> + Send + Sync>;
#[derive(Clone)]
pub struct FsFixture {
calls: Arc<Mutex<Vec<Result<(), String>>>>,
}
impl FsFixture {
pub fn new() -> Self {
Self {
calls: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn read_handler(&self, expected_path: &str, content: &str) -> ReadTextFileHandler {
let calls = self.calls.clone();
let expected_path = expected_path.to_string();
let content = content.to_string();
Arc::new(move |req: &ReadTextFileRequest| {
let path = req.path.to_str().unwrap_or("");
if path != expected_path {
let err = format!("expected path {expected_path}, got {path}");
calls.lock().unwrap().push(Err(err.clone()));
return Err(err);
}
calls.lock().unwrap().push(Ok(()));
Ok(ReadTextFileResponse::new(&content))
})
}
pub fn write_handler(
&self,
expected_path: &str,
expected_content: &str,
) -> WriteTextFileHandler {
let calls = self.calls.clone();
let expected_path = expected_path.to_string();
let expected_content = expected_content.to_string();
Arc::new(move |req: &WriteTextFileRequest| {
let path = req.path.to_str().unwrap_or("");
if path != expected_path {
let err = format!("expected path {expected_path}, got {path}");
calls.lock().unwrap().push(Err(err.clone()));
return Err(err);
}
if req.content != expected_content {
let err = format!("expected content {expected_content}, got {}", req.content);
calls.lock().unwrap().push(Err(err.clone()));
return Err(err);
}
calls.lock().unwrap().push(Ok(()));
Ok(WriteTextFileResponse::new())
})
}
pub fn assert_called(&self) {
let calls = self.calls.lock().unwrap();
assert!(!calls.is_empty(), "fs handler was never called");
let errors: Vec<_> = calls.iter().filter_map(|c| c.as_ref().err()).collect();
assert!(errors.is_empty(), "fs handler errors: {errors:?}");
}
}
/// Expected terminal calls. Each variant carries (expected_input, return_value) data,
/// like OpenAiFixture's (pattern, response) pairs.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum TerminalCall {
Create(String, String), // (command, terminal_id)
WaitForExit(String, u32), // (terminal_id, exit_code)
Output(String, String, u32), // (terminal_id, text, exit_code)
Release(String), // terminal_id
Kill(String), // terminal_id
}
impl TerminalCall {
fn name(&self) -> &'static str {
match self {
Self::Create(..) => "create",
Self::WaitForExit(..) => "wait_for_exit",
Self::Output(..) => "output",
Self::Release(_) => "release",
Self::Kill(_) => "kill",
}
}
}
pub struct TerminalFixture {
queue: Arc<Mutex<VecDeque<TerminalCall>>>,
errors: Arc<Mutex<Vec<String>>>,
}
impl TerminalFixture {
pub fn new(calls: Vec<TerminalCall>) -> Arc<Self> {
Arc::new(Self {
queue: Arc::new(Mutex::new(VecDeque::from(calls))),
errors: Arc::new(Mutex::new(Vec::new())),
})
}
fn pop(&self, expected: &str) -> Option<TerminalCall> {
let Some(call) = self.queue.lock().unwrap().pop_front() else {
self.record_error(format!("unexpected {expected}: queue empty"));
return None;
};
if call.name() != expected {
self.record_error(format!("expected {expected}, got {}", call.name()));
return None;
}
Some(call)
}
fn record_error(&self, msg: String) {
self.errors.lock().unwrap().push(msg);
}
fn validate_terminal_id(&self, method: &str, expected: &str, actual: &TerminalId) {
if expected != actual.0.as_ref() {
self.record_error(format!(
"{method}: expected terminal_id {expected}, got {actual}"
));
}
}
pub fn on_create(&self, command: &str) -> CreateTerminalResponse {
if let Some(TerminalCall::Create(expect_command, terminal_id)) = self.pop("create") {
if command != expect_command {
self.record_error(format!(
"create: expected command {expect_command}, got {command}"
));
}
CreateTerminalResponse::new(TerminalId::new(terminal_id))
} else {
CreateTerminalResponse::new(TerminalId::new("error"))
}
}
pub fn on_wait_for_exit(&self, terminal_id: &TerminalId) -> WaitForTerminalExitResponse {
if let Some(TerminalCall::WaitForExit(expected_id, exit_code)) = self.pop("wait_for_exit") {
self.validate_terminal_id("wait_for_exit", &expected_id, terminal_id);
WaitForTerminalExitResponse::new(TerminalExitStatus::new().exit_code(exit_code))
} else {
WaitForTerminalExitResponse::new(TerminalExitStatus::new().exit_code(1))
}
}
pub fn on_output(&self, terminal_id: &TerminalId) -> TerminalOutputResponse {
if let Some(TerminalCall::Output(expected_id, text, exit_code)) = self.pop("output") {
self.validate_terminal_id("output", &expected_id, terminal_id);
TerminalOutputResponse::new(text, false)
.exit_status(TerminalExitStatus::new().exit_code(exit_code))
} else {
TerminalOutputResponse::new("", false)
}
}
pub fn on_release(&self, terminal_id: &TerminalId) -> ReleaseTerminalResponse {
if let Some(TerminalCall::Release(expected_id)) = self.pop("release") {
self.validate_terminal_id("release", &expected_id, terminal_id);
}
ReleaseTerminalResponse::new()
}
pub fn on_kill(&self, terminal_id: &TerminalId) -> KillTerminalResponse {
if let Some(TerminalCall::Kill(expected_id)) = self.pop("kill") {
self.validate_terminal_id("kill", &expected_id, terminal_id);
}
KillTerminalResponse::new()
}
pub fn assert_called(&self) {
let errors = self.errors.lock().unwrap();
assert!(errors.is_empty(), "terminal fixture errors: {errors:?}");
let queue = self.queue.lock().unwrap();
assert!(
queue.is_empty(),
"terminal fixture has unconsumed calls: {queue:?}"
);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelStateFixture {
pub current_model_id: String,
@@ -739,9 +552,6 @@ pub struct TestConnectionConfig {
pub cwd: Option<tempfile::TempDir>,
pub data_root: PathBuf,
pub provider_factory: Option<AcpProviderFactory>,
pub read_text_file: Option<ReadTextFileHandler>,
pub write_text_file: Option<WriteTextFileHandler>,
pub terminal: Option<Arc<TerminalFixture>>,
// The model the server-side provider starts with. Defaults to TEST_MODEL.
pub current_model: String,
pub disable_session_naming: bool,
@@ -756,9 +566,6 @@ impl Default for TestConnectionConfig {
cwd: None,
data_root: PathBuf::new(),
provider_factory: None,
read_text_file: None,
write_text_file: None,
terminal: None,
current_model: TEST_MODEL.to_string(),
disable_session_naming: true,
}
+5 -112
View File
@@ -3,14 +3,11 @@ use super::{
PermissionDecision, Session, SessionData, TestConnectionConfig, TestOutput,
};
use agent_client_protocol::schema::v1::{
ClientCapabilities, CloseSessionRequest, ContentBlock, CreateTerminalRequest,
DeleteSessionRequest, FileSystemCapabilities, ImageContent, InitializeRequest,
KillTerminalRequest, ListSessionsRequest, ListSessionsResponse, LoadSessionRequest, McpServer,
NewSessionRequest, PromptRequest, ReadTextFileRequest, ReleaseTerminalRequest,
RequestPermissionRequest, SessionConfigKind, SessionConfigOptionCategory,
CloseSessionRequest, ContentBlock, DeleteSessionRequest, ImageContent, InitializeRequest,
ListSessionsRequest, ListSessionsResponse, LoadSessionRequest, McpServer, NewSessionRequest,
PromptRequest, RequestPermissionRequest, SessionConfigKind, SessionConfigOptionCategory,
SessionConfigOptionValue, SessionId, SessionModeId, SessionNotification, SessionUpdate,
SetSessionConfigOptionRequest, SetSessionModeRequest, StopReason, TerminalOutputRequest,
TextContent, ToolCallStatus, WaitForTerminalExitRequest, WriteTextFileRequest,
SetSessionConfigOptionRequest, SetSessionModeRequest, StopReason, TextContent, ToolCallStatus,
};
use agent_client_protocol::schema::ProtocolVersion;
use agent_client_protocol::{Agent, Client, ConnectionTo};
@@ -209,21 +206,10 @@ impl Connection for AcpServerConnection {
let notify = Arc::new(Notify::new());
let permission = Arc::new(Mutex::new(PermissionDecision::Cancel));
let mut fs_cap = FileSystemCapabilities::default();
if config.read_text_file.is_some() {
fs_cap = fs_cap.read_text_file(true);
}
if config.write_text_file.is_some() {
fs_cap = fs_cap.write_text_file(true);
}
let cx = {
let updates_clone = updates.clone();
let notify_clone = notify.clone();
let permission_clone = permission.clone();
let read_handler = config.read_text_file;
let write_handler = config.write_text_file;
let terminal = config.terminal;
let cx_holder: Arc<Mutex<Option<ConnectionTo<Agent>>>> = Arc::new(Mutex::new(None));
let cx_holder_clone = cx_holder.clone();
@@ -255,104 +241,11 @@ impl Connection for AcpServerConnection {
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
async move |req: ReadTextFileRequest, responder, _cx| match read_handler {
Some(ref rh) => match rh(&req) {
Ok(resp) => responder.respond(resp),
Err(msg) => responder.respond_with_internal_error(msg),
},
None => responder.respond_with_error(
agent_client_protocol::Error::method_not_found(),
),
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
async move |req: WriteTextFileRequest, responder, _cx| match write_handler {
Some(ref wh) => match wh(&req) {
Ok(resp) => responder.respond(resp),
Err(msg) => responder.respond_with_internal_error(msg),
},
None => responder.respond_with_error(
agent_client_protocol::Error::method_not_found(),
),
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
{
let t = terminal.clone();
async move |req: CreateTerminalRequest, responder, _cx| match t {
Some(ref f) => responder.respond(f.on_create(&req.command)),
None => responder.respond_with_error(
agent_client_protocol::Error::method_not_found(),
),
}
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
{
let t = terminal.clone();
async move |req: WaitForTerminalExitRequest, responder, _cx| match t {
Some(ref f) => {
responder.respond(f.on_wait_for_exit(&req.terminal_id))
}
None => responder.respond_with_error(
agent_client_protocol::Error::method_not_found(),
),
}
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
{
let t = terminal.clone();
async move |req: TerminalOutputRequest, responder, _cx| match t {
Some(ref f) => responder.respond(f.on_output(&req.terminal_id)),
None => responder.respond_with_error(
agent_client_protocol::Error::method_not_found(),
),
}
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
{
let t = terminal.clone();
async move |req: ReleaseTerminalRequest, responder, _cx| match t {
Some(ref f) => responder.respond(f.on_release(&req.terminal_id)),
None => responder.respond_with_error(
agent_client_protocol::Error::method_not_found(),
),
}
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
{
let t = terminal.clone();
async move |req: KillTerminalRequest, responder, _cx| match t {
Some(ref f) => responder.respond(f.on_kill(&req.terminal_id)),
None => responder.respond_with_error(
agent_client_protocol::Error::method_not_found(),
),
}
},
agent_client_protocol::on_receive_request!(),
)
.connect_with(transport.into_byte_streams(), {
let cx_holder = cx_holder_clone;
async move |cx: ConnectionTo<Agent>| {
let resp = cx
.send_request(
InitializeRequest::new(ProtocolVersion::V1)
.client_capabilities(
ClientCapabilities::new()
.fs(fs_cap)
.terminal(terminal.is_some()),
),
)
.send_request(InitializeRequest::new(ProtocolVersion::V1))
.block_task()
.await
.unwrap();
+6 -26
View File
@@ -8,12 +8,10 @@ use common_tests::fixtures::run_test;
#[cfg(feature = "code-mode")]
use common_tests::run_prompt_codemode;
use common_tests::{
run_close_session, run_config_mcp, run_delete_session, run_fs_read_text_file_true,
run_fs_write_text_file_false, run_fs_write_text_file_true, run_load_mode, run_load_model,
run_close_session, run_config_mcp, run_delete_session, run_load_mode, run_load_model,
run_load_session_error, run_load_session_mcp, run_model_list, run_permission_persistence,
run_prompt_basic, run_prompt_error, run_prompt_image, run_prompt_image_attachment,
run_prompt_mcp, run_prompt_model_mismatch, run_prompt_skill, run_shell_terminal_false,
run_shell_terminal_true,
run_prompt_mcp, run_prompt_model_mismatch, run_prompt_skill, run_shell, run_write_file,
};
#[test]
@@ -33,20 +31,8 @@ fn test_delete_session() {
}
#[test]
#[ignore = "provider is a plug-in to the goose CLI, UI and terminal clients, none of which handle buffered changes to files"]
fn test_fs_read_text_file_true() {
run_test(async { run_fs_read_text_file_true::<AcpProviderConnection>().await });
}
#[test]
fn test_fs_write_text_file_false() {
run_test(async { run_fs_write_text_file_false::<AcpProviderConnection>().await });
}
#[test]
#[ignore = "provider is a plug-in to the goose CLI, UI and terminal clients, none of which handle buffered changes to files"]
fn test_fs_write_text_file_true() {
run_test(async { run_fs_write_text_file_true::<AcpProviderConnection>().await });
fn test_write_file() {
run_test(async { run_write_file::<AcpProviderConnection>().await });
}
#[test]
@@ -126,12 +112,6 @@ fn test_prompt_skill() {
}
#[test]
fn test_shell_terminal_false() {
run_test(async { run_shell_terminal_false::<AcpProviderConnection>().await });
}
#[test]
#[ignore = "provider does not handle terminal delegation requests"]
fn test_shell_terminal_true() {
run_test(async { run_shell_terminal_true::<AcpProviderConnection>().await });
fn test_shell() {
run_test(async { run_shell::<AcpProviderConnection>().await });
}
+8 -25
View File
@@ -20,16 +20,14 @@ use common_tests::fixtures::{
use common_tests::run_prompt_codemode;
use common_tests::{
run_close_session, run_config_mcp, run_config_option_mode_set, run_config_option_model_set,
run_delete_session, run_fs_read_text_file_true, run_fs_write_text_file_false,
run_fs_write_text_file_true, run_initialize_doesnt_hit_provider, run_list_sessions,
run_load_mode, run_load_model, run_load_session_error, run_load_session_mcp,
run_delete_session, run_initialize_doesnt_hit_provider, run_list_sessions, run_load_mode,
run_load_model, run_load_session_error, run_load_session_mcp,
run_load_session_replays_image_attachment, run_mode_set, run_model_list, run_model_set,
run_model_set_error_session_not_found, run_new_session_returns_initial_config,
run_new_session_uses_current_config_mode, run_permission_persistence, run_prompt_basic,
run_prompt_error, run_prompt_image, run_prompt_image_attachment, run_prompt_mcp,
run_prompt_model_mismatch, run_prompt_skill, run_session_name_update_notification,
run_shell_terminal_false, run_shell_terminal_true, GENERATED_SESSION_TITLE,
OPENAI_SESSION_NAME_RESPONSE, TURN_CONTEXT_OPEN,
run_prompt_model_mismatch, run_prompt_skill, run_session_name_update_notification, run_shell,
run_write_file, GENERATED_SESSION_TITLE, OPENAI_SESSION_NAME_RESPONSE, TURN_CONTEXT_OPEN,
};
use goose::config::GooseMode;
use goose::conversation::message::{Message, MessageMetadata};
@@ -792,18 +790,8 @@ fn test_delete_session() {
}
#[test]
fn test_fs_read_text_file_true() {
run_test(async { run_fs_read_text_file_true::<AcpServerConnection>().await });
}
#[test]
fn test_fs_write_text_file_false() {
run_test(async { run_fs_write_text_file_false::<AcpServerConnection>().await });
}
#[test]
fn test_fs_write_text_file_true() {
run_test(async { run_fs_write_text_file_true::<AcpServerConnection>().await });
fn test_write_file() {
run_test(async { run_write_file::<AcpServerConnection>().await });
}
#[test]
@@ -1360,13 +1348,8 @@ fn test_prompt_skill() {
}
#[test]
fn test_shell_terminal_false() {
run_test(async { run_shell_terminal_false::<AcpServerConnection>().await });
}
#[test]
fn test_shell_terminal_true() {
run_test(async { run_shell_terminal_true::<AcpServerConnection>().await });
fn test_shell() {
run_test(async { run_shell::<AcpServerConnection>().await });
}
const CONTEXT_OVERFLOW: &str = r#"status:400 {"error":{"message":"too long","type":"invalid_request_error","code":"context_length_exceeded"}}"#;
@@ -1,31 +0,0 @@
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_ihWQp56Fq7txY7HHZJiNwzdy","type":"function","function":{"name":"read","arguments":""}}],"refusal":null},"finish_reason":null}],"usage":null,"obfuscation":"arnej9G"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"finish_reason":null}],"usage":null,"obfuscation":"M6pPn6sMuZ"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"path"}}]},"finish_reason":null}],"usage":null,"obfuscation":"7mHQMw0OR"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":"}}]},"finish_reason":null}],"usage":null,"obfuscation":"UktUfC37dd"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"/"}}]},"finish_reason":null}],"usage":null,"obfuscation":"kkR18xflju"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"tmp"}}]},"finish_reason":null}],"usage":null,"obfuscation":"WRyfb1apwr"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"/test"}}]},"finish_reason":null}],"usage":null,"obfuscation":"8Q5olmtW"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"_ac"}}]},"finish_reason":null}],"usage":null,"obfuscation":"3eLyGhC3LQ"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"p"}}]},"finish_reason":null}],"usage":null,"obfuscation":"NXUnZPCSiGnn"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"_read"}}]},"finish_reason":null}],"usage":null,"obfuscation":"mCuJG2UV"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":".txt"}}]},"finish_reason":null}],"usage":null,"obfuscation":"KjZS3z8R5"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"finish_reason":null}],"usage":null,"obfuscation":"Pe4UZ56QwD"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":null,"obfuscation":"5hgvg2ilskM"}
data: {"id":"chatcmpl-DFS7Z5WU3Km0oi1oFGiFSCLRPlriu","object":"chat.completion.chunk","created":1772575389,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[],"usage":{"prompt_tokens":7010,"completion_tokens":156,"total_tokens":7166,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":128,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}},"obfuscation":"bxKDPI1dGxmTdwd"}
data: [DONE]
@@ -1,21 +0,0 @@
data: {"id":"chatcmpl-DFS7cNHbE2luDLKMezfuTconLbkjx","object":"chat.completion.chunk","created":1772575392,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"finish_reason":null}],"usage":null,"obfuscation":"5Gvpc"}
data: {"id":"chatcmpl-DFS7cNHbE2luDLKMezfuTconLbkjx","object":"chat.completion.chunk","created":1772575392,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":"test"},"finish_reason":null}],"usage":null,"obfuscation":"8x6"}
data: {"id":"chatcmpl-DFS7cNHbE2luDLKMezfuTconLbkjx","object":"chat.completion.chunk","created":1772575392,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":"-read"},"finish_reason":null}],"usage":null,"obfuscation":"PM"}
data: {"id":"chatcmpl-DFS7cNHbE2luDLKMezfuTconLbkjx","object":"chat.completion.chunk","created":1772575392,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":"-content"},"finish_reason":null}],"usage":null,"obfuscation":"UxQl2cnPsJJsU4e"}
data: {"id":"chatcmpl-DFS7cNHbE2luDLKMezfuTconLbkjx","object":"chat.completion.chunk","created":1772575392,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":"-"},"finish_reason":null}],"usage":null,"obfuscation":"OIwMhu"}
data: {"id":"chatcmpl-DFS7cNHbE2luDLKMezfuTconLbkjx","object":"chat.completion.chunk","created":1772575392,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":"123"},"finish_reason":null}],"usage":null,"obfuscation":"wsSJ"}
data: {"id":"chatcmpl-DFS7cNHbE2luDLKMezfuTconLbkjx","object":"chat.completion.chunk","created":1772575392,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":"45"},"finish_reason":null}],"usage":null,"obfuscation":"2A6Mf"}
data: {"id":"chatcmpl-DFS7cNHbE2luDLKMezfuTconLbkjx","object":"chat.completion.chunk","created":1772575392,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":null,"obfuscation":"R"}
data: {"id":"chatcmpl-DFS7cNHbE2luDLKMezfuTconLbkjx","object":"chat.completion.chunk","created":1772575392,"model":"gpt-5-nano-2025-08-07","service_tier":"default","system_fingerprint":null,"choices":[],"usage":{"prompt_tokens":7061,"completion_tokens":143,"total_tokens":7204,"prompt_tokens_details":{"cached_tokens":6784,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":128,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}},"obfuscation":"GPZ33iiMhEfX"}
data: [DONE]