diff --git a/.github/workflows/patched-test.yml b/.github/workflows/patched-test.yml index c0c2fe63077a..9a9f3cda6b25 100644 --- a/.github/workflows/patched-test.yml +++ b/.github/workflows/patched-test.yml @@ -97,13 +97,25 @@ jobs: "acp::turn_error::tests::turn_error_message_under_the_cap_is_kept_whole" \ "acp::turn_error::tests::turn_error_message_over_the_cap_is_cut_on_a_char_boundary" \ "acp::server::tests::test_authentication_message_maps_to_auth_required" \ - "acp::server::tests::test_other_error_messages_map_to_internal_error" + "acp::server::tests::test_other_error_messages_map_to_internal_error" \ + "acp::server::session_settings::tests::max_turns_from_meta_absent_or_null_is_default" \ + "acp::server::session_settings::tests::max_turns_from_meta_accepts_positive_integer" \ + "acp::server::session_settings::tests::max_turns_from_meta_rejects_invalid_values" \ + "acp::server::session_settings::tests::cache_ttl_is_normalized_and_validated" run_exact_tests --release -p goose --features "$F" --test acp_server_test -- \ "test_prompt_reports_context_error_when_compaction_limit_is_exhausted" \ "test_prompt_fails_and_streams_the_error" \ "test_manual_compaction_refusal_fails_without_replacing_context" + run_exact_tests --release -p goose --features "$F" --test acp_session_settings_test -- \ + "test_session_settings_set_rejects_invalid_input" \ + "test_session_settings_set_persists_and_survives_reload" \ + "test_session_settings_set_activates_cold_session" \ + "test_prompt_max_turns_bounds_run" \ + "test_session_settings_idempotent_prompts_byte_identical" \ + "test_session_settings_templated_recipe_renders_consistently" + run_exact_tests --release -p goose-provider-types --lib -- \ "formats::anthropic::tests::native_claude_thinking_carries_display_and_block_binding" \ "formats::anthropic::tests::summarized_thinking_round_trips_with_its_signature" \ diff --git a/crates/goose-sdk-types/src/custom_requests.rs b/crates/goose-sdk-types/src/custom_requests.rs index aa2e5befd3cf..5c05c808956a 100644 --- a/crates/goose-sdk-types/src/custom_requests.rs +++ b/crates/goose-sdk-types/src/custom_requests.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: register the session_settings custom request module. use agent_client_protocol::schema::v1::{ AvailableCommand, ContentBlock, McpServer, Meta, SessionInfo, }; @@ -10,6 +11,8 @@ mod recipe; pub use recipe::*; mod schedule; pub use schedule::*; +mod session_settings; +pub use session_settings::*; /// Schema descriptor for a single custom method, produced by the /// `#[custom_methods]` macro's generated `custom_method_schemas()` function. diff --git a/crates/goose-sdk-types/src/custom_requests/recipe.rs b/crates/goose-sdk-types/src/custom_requests/recipe.rs index 5aac583134af..486268402648 100644 --- a/crates/goose-sdk-types/src/custom_requests/recipe.rs +++ b/crates/goose-sdk-types/src/custom_requests/recipe.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: accept jsonSchema alias in RecipeResponseDto. use std::collections::HashMap; use agent_client_protocol::{JsonRpcRequest, JsonRpcResponse}; @@ -82,7 +83,7 @@ pub struct RecipeSettingsDto { #[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)] pub struct RecipeResponseDto { - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(default, alias = "jsonSchema", skip_serializing_if = "Option::is_none")] pub json_schema: Option, } diff --git a/crates/goose-sdk-types/src/custom_requests/session_settings.rs b/crates/goose-sdk-types/src/custom_requests/session_settings.rs new file mode 100644 index 000000000000..5879ee59817c --- /dev/null +++ b/crates/goose-sdk-types/src/custom_requests/session_settings.rs @@ -0,0 +1,26 @@ +// Modified by Jonathan Mohrbacher, 2026: SetSessionSettingsRequest pins a session's cache TTL and recipe. +use agent_client_protocol::JsonRpcRequest; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::{EmptyResponse, RecipeDto}; + +/// Pin a session's prompt-cache TTL and recipe, persisted on the session row. +/// +/// The recipe is stored on the session and read every turn: its `title`, +/// `instructions` and `response` take effect. Its `settings`, `extensions`, +/// `prompt` and `parameters` are ignored, `retry` and `sub_recipes` are +/// dropped, and the session keeps its model. +#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema, JsonRpcRequest)] +#[request( + method = "_goose/unstable/session/settings/set", + response = EmptyResponse +)] +#[serde(rename_all = "camelCase")] +pub struct SetSessionSettingsRequest { + pub session_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_ttl: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub recipe: Option, +} diff --git a/crates/goose/acp-meta.json b/crates/goose/acp-meta.json index bed414d720d0..2c9ee62443f1 100644 --- a/crates/goose/acp-meta.json +++ b/crates/goose/acp-meta.json @@ -60,6 +60,11 @@ "requestType": "SetSessionSystemPromptRequest_unstable", "responseType": "EmptyResponse" }, + { + "method": "_goose/unstable/session/settings/set", + "requestType": "SetSessionSettingsRequest_unstable", + "responseType": "EmptyResponse" + }, { "method": "_goose/unstable/session/steer", "requestType": "SteerSessionRequest_unstable", diff --git a/crates/goose/acp-schema.json b/crates/goose/acp-schema.json index 43a5bf505f76..9dc433cad052 100644 --- a/crates/goose/acp-schema.json +++ b/crates/goose/acp-schema.json @@ -811,6 +811,36 @@ ], "description": "How a session system prompt update should be applied." }, + "SetSessionSettingsRequest_unstable": { + "type": "object", + "properties": { + "sessionId": { + "type": "string" + }, + "cacheTtl": { + "type": [ + "string", + "null" + ] + }, + "recipe": { + "anyOf": [ + { + "$ref": "#/$defs/RecipeDto" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "sessionId" + ], + "description": "Pin a session's prompt-cache TTL and recipe, persisted on the session row.\n\nThe recipe is stored on the session and read every turn: its `title`,\n`instructions` and `response` take effect. Its `settings`, `extensions`,\n`prompt` and `parameters` are ignored, `retry` and `sub_recipes` are\ndropped, and the session keeps its model.", + "x-side": "agent", + "x-method": "_goose/unstable/session/settings/set" + }, "SteerSessionRequest_unstable": { "type": "object", "properties": { @@ -7340,6 +7370,15 @@ "description": "Params for _goose/unstable/session/system-prompt/set", "title": "SetSessionSystemPromptRequest_unstable" }, + { + "allOf": [ + { + "$ref": "#/$defs/SetSessionSettingsRequest_unstable" + } + ], + "description": "Params for _goose/unstable/session/settings/set", + "title": "SetSessionSettingsRequest_unstable" + }, { "allOf": [ { diff --git a/crates/goose/src/acp/server.rs b/crates/goose/src/acp/server.rs index fc549abdba97..bca77f680e26 100644 --- a/crates/goose/src/acp/server.rs +++ b/crates/goose/src/acp/server.rs @@ -1,4 +1,4 @@ -// Modified by Jonathan Mohrbacher, 2026: session/prompt turn_failed errors carry data.kind and data.message. +// Modified by Jonathan Mohrbacher, 2026: session/prompt turn_failed errors carry data.kind and data.message; register session_settings (settings/set) and honour session/prompt _meta.goose.maxTurns. use crate::acp::custom_notifications::*; use crate::acp::custom_requests::*; pub(super) use crate::acp::response_builder::{ @@ -123,6 +123,7 @@ mod providers; mod recipe; mod resources; mod schedule; +mod session_settings; mod slash_commands; mod sources; mod tool_calls; @@ -2242,6 +2243,7 @@ impl AcpConnection { cx: &ConnectionTo, args: PromptRequest, ) -> Result { + let max_turns = session_settings::max_turns_from_meta(args.meta.as_ref())?; // The ACP session_id IS the thread ID. let session_id = args.session_id.0.to_string(); @@ -2290,7 +2292,7 @@ impl AcpConnection { let session_config = SessionConfig { id: session_id.clone(), schedule_id: None, - max_turns: None, + max_turns, }; let reply = self diff --git a/crates/goose/src/acp/server/custom_dispatch.rs b/crates/goose/src/acp/server/custom_dispatch.rs index 4a91752912d2..93787aad7287 100644 --- a/crates/goose/src/acp/server/custom_dispatch.rs +++ b/crates/goose/src/acp/server/custom_dispatch.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: dispatch _goose/unstable/session/settings/set. use super::*; use goose_acp_macros::custom_methods; @@ -126,6 +127,14 @@ impl AcpConnection { self.on_set_session_system_prompt(req).await } + #[custom_method(SetSessionSettingsRequest)] + async fn dispatch_set_session_settings( + &self, + req: SetSessionSettingsRequest, + ) -> Result { + self.on_set_session_settings(req).await + } + #[custom_method(SteerSessionRequest)] async fn dispatch_steer_session( &self, diff --git a/crates/goose/src/acp/server/session_settings.rs b/crates/goose/src/acp/server/session_settings.rs new file mode 100644 index 000000000000..5fa04ab2a938 --- /dev/null +++ b/crates/goose/src/acp/server/session_settings.rs @@ -0,0 +1,233 @@ +// Modified by Jonathan Mohrbacher, 2026: _goose/unstable/session/settings/set pins a session's cache TTL and recipe; session/prompt _meta.goose.maxTurns bounds the run. +use agent_client_protocol::schema::v1::Meta; + +use super::{AcpConnection, ResultExt}; +use crate::acp::custom_requests::{EmptyResponse, SetSessionSettingsRequest}; +use crate::agents::final_output_tool::FinalOutputTool; +use crate::recipe::build_recipe::{build_recipe_from_template, RecipeError}; +use crate::recipe::local_recipes::get_recipe_library_dir; +use crate::recipe::validate_recipe::validate_recipe_template_from_content; +use crate::recipe::Recipe; +use crate::session::{Session, SessionType}; + +const CACHE_TTLS: [&str; 2] = ["5m", "1h"]; + +fn invalid_recipe(detail: impl std::fmt::Display) -> agent_client_protocol::Error { + let detail = detail.to_string(); + let detail = detail.strip_prefix("recipe: ").unwrap_or(&detail); + agent_client_protocol::Error::invalid_params().data(format!("invalid recipe: {detail}")) +} + +fn normalized_cache_ttl(ttl: &str) -> Result { + let ttl = ttl.trim().to_lowercase(); + if CACHE_TTLS.contains(&ttl.as_str()) { + Ok(ttl) + } else { + Err(agent_client_protocol::Error::invalid_params() + .data("invalid cacheTtl: must be '5m' or '1h'")) + } +} + +/// The recipe as the session row stores it: rendered with the session's +/// parameter values, except for scheduled sessions, which keep the template. +/// `retry` and `sub_recipes` are dropped: the state machine reads the stored +/// recipe every turn, and a retry block would let a failed check truncate a +/// long-lived session back to its kickoff message. +fn recipe_to_store( + mut raw: Recipe, + session: &Session, +) -> Result { + raw.retry = None; + raw.sub_recipes = None; + if raw.check_for_security_warnings() { + return Err(invalid_recipe( + "contains hidden characters that could be malicious", + )); + } + let yaml = raw.to_yaml().map_err(invalid_recipe)?; + validate_recipe_template_from_content(&yaml, None).map_err(invalid_recipe)?; + + let recipe = if session.session_type == SessionType::Scheduled { + raw + } else { + let values: Vec<(String, String)> = session + .user_recipe_values + .clone() + .unwrap_or_default() + .into_iter() + .collect(); + match build_recipe_from_template( + yaml, + &get_recipe_library_dir(true), + values, + None:: Result>, + ) { + Ok(rendered) => rendered, + Err(RecipeError::MissingParams { .. }) => { + return Err(invalid_recipe("missing required parameters")) + } + Err(e) => return Err(invalid_recipe(e)), + } + }; + + if let Some(response) = recipe.response.clone() { + FinalOutputTool::try_new(response).map_err(invalid_recipe)?; + } + Ok(recipe) +} + +/// `_meta.goose.maxTurns`: absent or null means the configured default; any +/// value other than a positive 32-bit integer is rejected. +pub(super) fn max_turns_from_meta( + meta: Option<&Meta>, +) -> Result, agent_client_protocol::Error> { + let Some(value) = meta + .and_then(|meta| meta.get("goose")) + .and_then(|goose| goose.get("maxTurns")) + .filter(|value| !value.is_null()) + else { + return Ok(None); + }; + value + .as_u64() + .filter(|n| *n > 0) + .and_then(|n| u32::try_from(n).ok()) + .map(Some) + .ok_or_else(|| { + agent_client_protocol::Error::invalid_params() + .data("_meta.goose.maxTurns must be a positive integer") + }) +} + +impl AcpConnection { + pub(super) async fn on_set_session_settings( + &self, + req: SetSessionSettingsRequest, + ) -> Result { + let session_id = req.session_id.trim(); + if session_id.is_empty() { + return Err( + agent_client_protocol::Error::invalid_params().data("sessionId cannot be empty") + ); + } + let cache_ttl = req + .cache_ttl + .as_deref() + .map(normalized_cache_ttl) + .transpose()?; + + let mut session = self + .services + .session_manager + .get_session(session_id, false) + .await + .map_err(|_| { + agent_client_protocol::Error::resource_not_found(Some(session_id.to_string())) + .data(format!("Session not found: {}", session_id)) + })?; + + let recipe = req + .recipe + .map(|dto| { + let raw = Recipe::try_from(dto).map_err(invalid_recipe)?; + recipe_to_store(raw, &session) + }) + .transpose()?; + + self.open_session(session_id).await?; + + if let Some(ttl) = cache_ttl { + let model_config = self + .services + .model_config_for_session(session_id) + .await + .internal_err_ctx("Failed to resolve model config")?; + if model_config.cache_ttl().as_deref() != Some(ttl.as_str()) { + let provider_name = self + .services + .provider(session_id) + .await + .internal_err_ctx("Failed to get provider")? + .get_name() + .to_string(); + self.services + .switch_provider( + session_id, + &provider_name, + model_config.with_cache_ttl(&ttl), + ) + .await + .internal_err_ctx("Failed to pin cache TTL")?; + } + } + + let Some(recipe) = recipe else { + self.render_stored_recipe_template(&mut session).await?; + return Ok(EmptyResponse {}); + }; + self.services + .session_manager + .update(session_id) + .recipe(Some(recipe)) + .apply() + .await + .internal_err_ctx("Failed to persist recipe to session")?; + + Ok(EmptyResponse {}) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use agent_client_protocol::ErrorCode; + + fn meta(value: serde_json::Value) -> Meta { + serde_json::from_value(value).unwrap() + } + + #[test] + fn max_turns_from_meta_absent_or_null_is_default() { + assert_eq!(max_turns_from_meta(None).unwrap(), None); + for value in [ + serde_json::json!({}), + serde_json::json!({ "goose": {} }), + serde_json::json!({ "goose": { "maxTurns": null } }), + ] { + assert_eq!(max_turns_from_meta(Some(&meta(value))).unwrap(), None); + } + } + + #[test] + fn max_turns_from_meta_accepts_positive_integer() { + let value = meta(serde_json::json!({ "goose": { "maxTurns": 4 } })); + assert_eq!(max_turns_from_meta(Some(&value)).unwrap(), Some(4)); + } + + #[test] + fn max_turns_from_meta_rejects_invalid_values() { + for bad in [ + serde_json::json!(0), + serde_json::json!(-1), + serde_json::json!(2.5), + serde_json::json!("two"), + serde_json::json!(u64::from(u32::MAX) + 1), + ] { + let value = meta(serde_json::json!({ "goose": { "maxTurns": bad } })); + assert_eq!( + max_turns_from_meta(Some(&value)).unwrap_err().code, + ErrorCode::InvalidParams, + "maxTurns {bad}" + ); + } + } + + #[test] + fn cache_ttl_is_normalized_and_validated() { + assert_eq!(normalized_cache_ttl(" 1H ").unwrap(), "1h"); + assert_eq!(normalized_cache_ttl("5m").unwrap(), "5m"); + let err = normalized_cache_ttl("2h").unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidParams); + assert!(err.data.unwrap().to_string().contains("invalid cacheTtl: ")); + } +} diff --git a/crates/goose/tests/acp_fixtures/mod.rs b/crates/goose/tests/acp_fixtures/mod.rs index 49beb0e14035..986a45a11f20 100644 --- a/crates/goose/tests/acp_fixtures/mod.rs +++ b/crates/goose/tests/acp_fixtures/mod.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: OpenAiFixture captures request bodies for prompt caching assertions. #![recursion_limit = "256"] #![allow(unused_attributes)] @@ -216,6 +217,7 @@ pub struct OpenAiFixture { base_url: String, exchanges: Vec<(String, &'static str)>, queue: Arc>>, + captured: Arc>>, } impl OpenAiFixture { @@ -235,6 +237,7 @@ impl OpenAiFixture { ) -> Self { let mock_server = MockServer::start().await; let queue = Arc::new(Mutex::new(VecDeque::from(exchanges.clone()))); + let captured = Arc::new(Mutex::new(Vec::new())); // Always return the models when asked, as there is no POST data to validate Mock::given(method("GET")) @@ -252,8 +255,10 @@ impl OpenAiFixture { .respond_with({ let queue = queue.clone(); let expected_session_id = expected_session_id.clone(); + let captured = captured.clone(); move |req: &wiremock::Request| { let body = std::str::from_utf8(&req.body).unwrap_or(""); + captured.lock().unwrap().push(body.to_string()); // Validate session ID header let actual = req @@ -307,9 +312,14 @@ impl OpenAiFixture { base_url, exchanges, queue, + captured, } } + pub fn captured_requests_handle(&self) -> Arc>> { + Arc::clone(&self.captured) + } + pub fn uri(&self) -> &str { &self.base_url } diff --git a/crates/goose/tests/acp_session_settings_test.rs b/crates/goose/tests/acp_session_settings_test.rs new file mode 100644 index 000000000000..8726a58b9957 --- /dev/null +++ b/crates/goose/tests/acp_session_settings_test.rs @@ -0,0 +1,598 @@ +// Modified by Jonathan Mohrbacher, 2026: test _goose/unstable/session/settings/set and session/prompt _meta.goose.maxTurns. +#![recursion_limit = "256"] +#[allow(dead_code)] +#[path = "acp_common_tests/mod.rs"] +mod common_tests; + +use agent_client_protocol::schema::v1::{ContentBlock, SessionUpdate}; +use agent_client_protocol::ErrorCode; +use common_tests::fixtures::server::AcpServerConnection; +use common_tests::fixtures::{ + run_test, send_custom, Connection, OpenAiFixture, PermissionDecision, Session, SessionData, + TestConnectionConfig, +}; +use goose::session::SessionManager; +use goose_test_support::IgnoreSessionId; +use serial_test::serial; +use std::sync::Arc; + +const SETTINGS_SET: &str = "_goose/unstable/session/settings/set"; + +const FINAL_OUTPUT_SUMMARY_RESPONSE: &str = "data: {\"id\":\"chatcmpl-test\",\"object\":\"chat.completion.chunk\",\"created\":1766229303,\"model\":\"gpt-5-nano\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":null,\"tool_calls\":[{\"index\":0,\"id\":\"call_final\",\"type\":\"function\",\"function\":{\"name\":\"recipe__final_output\",\"arguments\":\"{\\\"summary\\\":\\\"done\\\"}\"}}]},\"finish_reason\":null}]}\n\ndata: {\"id\":\"chatcmpl-test\",\"object\":\"chat.completion.chunk\",\"created\":1766229303,\"model\":\"gpt-5-nano\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\ndata: [DONE]\n\n"; + +const FINAL_OUTPUT_VALUE_RESPONSE: &str = "data: {\"id\":\"chatcmpl-test\",\"object\":\"chat.completion.chunk\",\"created\":1766229303,\"model\":\"gpt-5-nano\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":null,\"tool_calls\":[{\"index\":0,\"id\":\"call_final\",\"type\":\"function\",\"function\":{\"name\":\"recipe__final_output\",\"arguments\":\"{\\\"value\\\":\\\"done\\\"}\"}}]},\"finish_reason\":null}]}\n\ndata: {\"id\":\"chatcmpl-test\",\"object\":\"chat.completion.chunk\",\"created\":1766229303,\"model\":\"gpt-5-nano\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\ndata: [DONE]\n\n"; + +const TEXT_TURN_1: &str = "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1766229303,\"model\":\"gpt-5-nano\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"Turn 1 working\"},\"finish_reason\":null}]}\n\ndata: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1766229303,\"model\":\"gpt-5-nano\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"; + +const TEXT_TURN_2: &str = "data: {\"id\":\"chatcmpl-2\",\"object\":\"chat.completion.chunk\",\"created\":1766229304,\"model\":\"gpt-5-nano\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"Turn 2 working\"},\"finish_reason\":null}]}\n\ndata: {\"id\":\"chatcmpl-2\",\"object\":\"chat.completion.chunk\",\"created\":1766229304,\"model\":\"gpt-5-nano\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"; + +async fn connect(data_root: &std::path::Path, openai: OpenAiFixture) -> AcpServerConnection { + AcpServerConnection::new( + TestConnectionConfig { + data_root: data_root.to_path_buf(), + ..Default::default() + }, + openai, + ) + .await +} + +fn offers_final_output(request_body: &str) -> bool { + let request: serde_json::Value = serde_json::from_str(request_body).unwrap(); + request["tools"] + .as_array() + .into_iter() + .flatten() + .any(|tool| tool["function"]["name"] == "recipe__final_output") +} + +fn data_text(err: &agent_client_protocol::Error) -> String { + err.data.as_ref().map(|d| d.to_string()).unwrap_or_default() +} + +fn agent_text(updates: &[SessionUpdate]) -> String { + updates + .iter() + .filter_map(|u| match u { + SessionUpdate::AgentMessageChunk(chunk) => match &chunk.content { + ContentBlock::Text(t) => Some(t.text.as_str()), + _ => None, + }, + _ => None, + }) + .collect::>() + .join("") +} + +fn summary_recipe() -> serde_json::Value { + serde_json::json!({ + "title": "Settings Test Recipe", + "description": "Test recipe description", + "instructions": "Special test recipe instructions", + "response": { + "json_schema": { + "type": "object", + "properties": { "summary": { "type": "string" } }, + "required": ["summary"] + } + } + }) +} + +#[test] +#[serial] +fn test_session_settings_set_rejects_invalid_input() { + run_test(async move { + let temp_data = tempfile::tempdir().unwrap(); + let openai = OpenAiFixture::new(vec![], Arc::new(IgnoreSessionId)).await; + let mut conn = connect(temp_data.path(), openai).await; + let SessionData { session, .. } = conn.new_session().await.unwrap(); + let session_id = session.session_id().0.to_string(); + + let err = send_custom( + conn.cx(), + SETTINGS_SET, + serde_json::json!({ "sessionId": session_id, "cacheTtl": "2h" }), + ) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidParams); + assert!(data_text(&err).contains("invalid cacheTtl: "), "{err:?}"); + + let err = send_custom( + conn.cx(), + SETTINGS_SET, + serde_json::json!({ + "sessionId": "unknown-nonexistent-session", + "recipe": { "title": "Some Recipe", "description": "Description" } + }), + ) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::ResourceNotFound); + + send_custom( + conn.cx(), + SETTINGS_SET, + serde_json::json!({ "sessionId": session_id, "recipe": summary_recipe() }), + ) + .await + .unwrap(); + + let rejected = [ + serde_json::json!({ + "title": "Bad Schema Recipe", + "description": "Empty schema", + "response": { "json_schema": {} } + }), + serde_json::json!({ + "title": "Bad Template Recipe", + "description": "Unclosed jinja", + "instructions": "Unclosed {% bad tag" + }), + ]; + for recipe in rejected { + let err = send_custom( + conn.cx(), + SETTINGS_SET, + serde_json::json!({ "sessionId": session_id, "recipe": recipe }), + ) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidParams); + assert!(data_text(&err).contains("invalid recipe: "), "{err:?}"); + } + + let stored = SessionManager::new(temp_data.path().to_path_buf()) + .get_session(&session_id, false) + .await + .unwrap(); + assert_eq!( + stored.recipe.and_then(|r| r.instructions).as_deref(), + Some("Special test recipe instructions"), + "a rejected recipe must not replace the stored one" + ); + }); +} + +#[test] +#[serial] +fn test_session_settings_set_persists_and_survives_reload() { + run_test(async move { + let temp_data = tempfile::tempdir().unwrap(); + let openai = OpenAiFixture::new( + vec![( + "Special test recipe instructions".to_string(), + FINAL_OUTPUT_SUMMARY_RESPONSE, + )], + Arc::new(IgnoreSessionId), + ) + .await; + let captured = openai.captured_requests_handle(); + let mut conn = connect(temp_data.path(), openai).await; + let SessionData { mut session, .. } = conn.new_session().await.unwrap(); + let session_id = session.session_id().0.to_string(); + let session_manager = SessionManager::new(temp_data.path().to_path_buf()); + + let mut recipe = summary_recipe(); + recipe["retry"] = serde_json::json!({ + "max_retries": 1, + "checks": [{ "type": "shell", "command": "false" }] + }); + recipe["sub_recipes"] = serde_json::json!([{ "name": "child", "path": "child.yaml" }]); + for _ in 0..2 { + let res = send_custom( + conn.cx(), + SETTINGS_SET, + serde_json::json!({ + "sessionId": session_id, + "cacheTtl": "1h", + "recipe": recipe, + }), + ) + .await + .unwrap(); + assert_eq!(res, serde_json::json!({})); + } + + let stored = session_manager + .get_session(&session_id, false) + .await + .unwrap(); + assert_eq!( + stored.model_config.as_ref().and_then(|mc| mc.cache_ttl()), + Some("1h".to_string()) + ); + let stored_recipe = stored.recipe.expect("recipe stored"); + assert!(stored_recipe.retry.is_none(), "retry must not be stored"); + assert!( + stored_recipe.sub_recipes.is_none(), + "sub_recipes must not be stored" + ); + let out = session + .prompt("Hello with recipe", PermissionDecision::AllowOnce) + .await + .unwrap(); + assert!(out.tool_status.is_some()); + let first = captured.lock().unwrap().clone(); + assert_eq!(first.len(), 1); + assert!(offers_final_output(&first[0])); + + let openai2 = OpenAiFixture::new( + vec![( + "Special test recipe instructions".to_string(), + FINAL_OUTPUT_SUMMARY_RESPONSE, + )], + Arc::new(IgnoreSessionId), + ) + .await; + let captured2 = openai2.captured_requests_handle(); + let mut conn2 = connect(temp_data.path(), openai2).await; + let SessionData { + session: mut loaded, + .. + } = conn2.load_session(&session_id, vec![]).await.unwrap(); + let out = loaded + .prompt("Hello after reload", PermissionDecision::AllowOnce) + .await + .unwrap(); + assert!(out.tool_status.is_some()); + let second = captured2.lock().unwrap().clone(); + assert_eq!(second.len(), 1); + assert!(offers_final_output(&second[0])); + let stored = session_manager + .get_session(&session_id, false) + .await + .unwrap(); + assert_eq!( + stored.model_config.as_ref().and_then(|mc| mc.cache_ttl()), + Some("1h".to_string()), + "session/load must keep the pinned cache TTL" + ); + }); +} + +#[test] +#[serial] +fn test_session_settings_set_activates_cold_session() { + run_test(async move { + let temp_data = tempfile::tempdir().unwrap(); + let openai = OpenAiFixture::new(vec![], Arc::new(IgnoreSessionId)).await; + let mut conn = connect(temp_data.path(), openai).await; + let SessionData { session, .. } = conn.new_session().await.unwrap(); + let session_id = session.session_id().0.to_string(); + send_custom( + conn.cx(), + SETTINGS_SET, + serde_json::json!({ "sessionId": session_id, "recipe": summary_recipe() }), + ) + .await + .unwrap(); + drop(session); + drop(conn); + + let openai = OpenAiFixture::new( + vec![ + ( + "Special test recipe instructions".to_string(), + FINAL_OUTPUT_SUMMARY_RESPONSE, + ), + ( + "Simple instructions without final output".to_string(), + TEXT_TURN_1, + ), + ], + Arc::new(IgnoreSessionId), + ) + .await; + let captured = openai.captured_requests_handle(); + let cold = connect(temp_data.path(), openai).await; + let res = send_custom( + cold.cx(), + SETTINGS_SET, + serde_json::json!({ "sessionId": session_id, "cacheTtl": "1h" }), + ) + .await + .unwrap(); + assert_eq!(res, serde_json::json!({})); + let stored = SessionManager::new(temp_data.path().to_path_buf()) + .get_session(&session_id, false) + .await + .unwrap(); + assert_eq!( + stored.model_config.as_ref().and_then(|mc| mc.cache_ttl()), + Some("1h".to_string()) + ); + + let res = send_custom( + cold.cx(), + "session/prompt", + serde_json::json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "Testing cold prompt" }], + }), + ) + .await + .unwrap(); + assert_eq!( + res.get("stopReason").and_then(|s| s.as_str()), + Some("end_turn"), + "the stored recipe's instructions must reach the provider: {res}" + ); + + send_custom( + cold.cx(), + SETTINGS_SET, + serde_json::json!({ + "sessionId": session_id, + "recipe": { + "title": "Recipe Without Response", + "description": "Recipe with no output schema", + "instructions": "Simple instructions without final output", + }, + }), + ) + .await + .unwrap(); + let res = send_custom( + cold.cx(), + "session/prompt", + serde_json::json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "Testing replaced recipe" }], + }), + ) + .await + .unwrap(); + assert_eq!( + res.get("stopReason").and_then(|s| s.as_str()), + Some("end_turn") + ); + let reqs = captured.lock().unwrap().clone(); + assert_eq!(reqs.len(), 2); + assert!(offers_final_output(&reqs[0])); + assert!( + !offers_final_output(&reqs[1]), + "a recipe without response removes the final_output tool" + ); + assert!(!reqs[1].contains("Special test recipe instructions")); + }); +} + +#[test] +#[serial] +fn test_prompt_max_turns_bounds_run() { + run_test(async move { + let openai = OpenAiFixture::new( + vec![ + ("what is 1+1".to_string(), TEXT_TURN_1), + ("final_output".to_string(), TEXT_TURN_2), + ], + Arc::new(IgnoreSessionId), + ) + .await; + let captured = openai.captured_requests_handle(); + let mut conn = AcpServerConnection::new(TestConnectionConfig::default(), openai).await; + let SessionData { session, .. } = conn.new_session().await.unwrap(); + let session_id = session.session_id().0.to_string(); + + send_custom( + conn.cx(), + SETTINGS_SET, + serde_json::json!({ + "sessionId": session_id, + "recipe": { + "title": "Recipe With Output", + "description": "Recipe requiring final output", + "instructions": "Always produce structured final output", + "response": { + "json_schema": { + "type": "object", + "properties": { "ans": { "type": "string" } }, + "required": ["ans"] + } + } + }, + }), + ) + .await + .unwrap(); + + for bad in [ + serde_json::json!(0), + serde_json::json!(-1), + serde_json::json!(2.5), + serde_json::json!("two"), + ] { + let err = send_custom( + conn.cx(), + "session/prompt", + serde_json::json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "what is 1+1" }], + "_meta": { "goose": { "maxTurns": bad } } + }), + ) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidParams, "maxTurns {bad}"); + } + assert!(captured.lock().unwrap().is_empty()); + + let result = send_custom( + conn.cx(), + "session/prompt", + serde_json::json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": "what is 1+1" }], + "_meta": { "goose": { "maxTurns": 1 } } + }), + ) + .await; + + assert_eq!( + captured.lock().unwrap().len(), + 1, + "maxTurns 1 must stop the run before the final_output continuation: {result:?}" + ); + let text = agent_text(&session.session_updates()); + let reported = match &result { + Ok(_) => text.contains("maximum number of actions"), + Err(err) => { + format!("{err:?}").contains("maximum number of actions") + || text.contains("maximum number of actions") + } + }; + assert!( + reported, + "expected the max turns message: {result:?} / {text}" + ); + }); +} + +#[test] +#[serial] +fn test_session_settings_idempotent_prompts_byte_identical() { + run_test(async move { + let temp_data = tempfile::tempdir().unwrap(); + let openai = OpenAiFixture::new( + vec![ + ("what is 1+1".to_string(), FINAL_OUTPUT_VALUE_RESPONSE), + ("what is 2+2".to_string(), FINAL_OUTPUT_VALUE_RESPONSE), + ], + Arc::new(IgnoreSessionId), + ) + .await; + let captured = openai.captured_requests_handle(); + let mut conn = connect(temp_data.path(), openai).await; + let SessionData { mut session, .. } = conn.new_session().await.unwrap(); + let session_id = session.session_id().0.to_string(); + let settings = serde_json::json!({ + "sessionId": session_id, + "cacheTtl": "1h", + "recipe": { + "title": "Cost Critical Recipe", + "description": "Recipe testing byte-identical prompts", + "instructions": "Deterministic prompt caching instructions", + "response": { + "json_schema": { + "type": "object", + "properties": { "value": { "type": "string" } }, + "required": ["value"] + } + } + }, + }); + + send_custom(conn.cx(), SETTINGS_SET, settings.clone()) + .await + .unwrap(); + let out1 = session + .prompt("what is 1+1", PermissionDecision::AllowOnce) + .await + .unwrap(); + assert!(out1.tool_status.is_some()); + send_custom(conn.cx(), SETTINGS_SET, settings) + .await + .unwrap(); + let out2 = session + .prompt("what is 2+2", PermissionDecision::AllowOnce) + .await + .unwrap(); + assert!(out2.tool_status.is_some()); + + let reqs = captured.lock().unwrap().clone(); + assert_eq!(reqs.len(), 2); + let req1: serde_json::Value = serde_json::from_str(&reqs[0]).unwrap(); + let req2: serde_json::Value = serde_json::from_str(&reqs[1]).unwrap(); + assert_eq!( + req1["messages"][0]["content"].to_string(), + req2["messages"][0]["content"].to_string(), + "system prompt must be byte-identical across identical settings/set" + ); + assert_eq!( + req1["tools"].to_string(), + req2["tools"].to_string(), + "tools must be byte-identical across identical settings/set" + ); + }); +} + +#[test] +#[serial] +fn test_session_settings_templated_recipe_renders_consistently() { + run_test(async move { + let temp_data = tempfile::tempdir().unwrap(); + let openai = OpenAiFixture::new( + vec![ + ("what is 1+1".to_string(), FINAL_OUTPUT_SUMMARY_RESPONSE), + ("what is 2+2".to_string(), FINAL_OUTPUT_SUMMARY_RESPONSE), + ], + Arc::new(IgnoreSessionId), + ) + .await; + let captured = openai.captured_requests_handle(); + let mut conn = connect(temp_data.path(), openai).await; + let SessionData { mut session, .. } = conn.new_session().await.unwrap(); + let session_id = session.session_id().0.to_string(); + + send_custom( + conn.cx(), + SETTINGS_SET, + serde_json::json!({ + "sessionId": session_id, + "cacheTtl": "1h", + "recipe": { + "title": "Templated Recipe", + "description": "Recipe with template variables", + "parameters": [{ + "key": "env", + "description": "Environment", + "input_type": "string", + "requirement": "optional", + "default": "production" + }], + "instructions": "Target env: {{ env }}. Recipe dir: {{ recipe_dir }}", + "response": { + "json_schema": { + "type": "object", + "properties": { "summary": { "type": "string" } }, + "required": ["summary"] + } + } + }, + }), + ) + .await + .unwrap(); + let out1 = session + .prompt("what is 1+1", PermissionDecision::AllowOnce) + .await + .unwrap(); + assert!(out1.tool_status.is_some()); + + send_custom( + conn.cx(), + SETTINGS_SET, + serde_json::json!({ "sessionId": session_id, "cacheTtl": "1h" }), + ) + .await + .unwrap(); + let out2 = session + .prompt("what is 2+2", PermissionDecision::AllowOnce) + .await + .unwrap(); + assert!(out2.tool_status.is_some()); + + let reqs = captured.lock().unwrap().clone(); + assert_eq!(reqs.len(), 2); + let req1: serde_json::Value = serde_json::from_str(&reqs[0]).unwrap(); + let req2: serde_json::Value = serde_json::from_str(&reqs[1]).unwrap(); + let sys1 = req1["messages"][0]["content"].as_str().unwrap(); + let sys2 = req2["messages"][0]["content"].as_str().unwrap(); + assert!(!sys1.contains("{{ env }}")); + assert!(!sys1.contains("{{ recipe_dir }}")); + assert!(sys1.contains("Target env: production")); + assert_eq!(sys1, sys2); + }); +}