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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions .github/workflows/patched-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,17 @@ jobs:
"agents::platform_extensions::summon::subagent_policy::tests::subagent_policy_strict_start_accepts_extensions_that_start" \
"agents::platform_extensions::summon::subagent_policy::tests::subagent_policy_strict_start_fails_on_an_extension_that_does_not_start" \
"agents::platform_extensions::summon::subagent_policy::tests::subagent_policy_delegate_fails_when_its_extension_does_not_start" \
"agents::platform_extensions::summon::subagent_policy::tests::subagent_policy_delegate_without_policy_runs_on_after_a_failed_extension"
"agents::platform_extensions::summon::subagent_policy::tests::subagent_policy_delegate_without_policy_runs_on_after_a_failed_extension" \
"acp::server::truncate_from_message::tests::message_id_from_meta_reads_goose_message_id" \
"acp::server::truncate_from_message::tests::message_id_from_meta_rejects_empty_or_non_string" \
"acp::server::truncate_from_message::tests::agent_capabilities_advertise_truncate_from_message" \
"session::session_manager::tests::test_truncate_conversation_from_message_keeps_same_second_previous_rows"

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"
"test_manual_compaction_refusal_fails_without_replacing_context" \
"test_prompt_message_id_and_truncate_from_message"

run_exact_tests --release -p goose --features "$F" --test acp_session_settings_test -- \
"test_session_settings_set_rejects_invalid_input" \
Expand Down
24 changes: 23 additions & 1 deletion crates/goose-sdk-types/src/custom_requests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Modified by Jonathan Mohrbacher, 2026: register the session_settings custom request module.
// Modified by Jonathan Mohrbacher, 2026: register the session_settings custom request module; TruncateSessionConversationFromMessageRequest.
use agent_client_protocol::schema::v1::{
AvailableCommand, ContentBlock, McpServer, Meta, SessionInfo,
};
Expand Down Expand Up @@ -857,6 +857,28 @@ pub struct TruncateSessionConversationRequest {
pub truncate_from: i64,
}

/// Truncate a session conversation from the message with the given id onward
/// (that message included). The boundary is the message's row, so messages
/// stored in the same second before it are kept. Refused while the session has
/// an active run.
#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema, JsonRpcRequest)]
#[request(
method = "_goose/unstable/session/conversation/truncate_from_message",
response = TruncateSessionConversationFromMessageResponse
)]
#[serde(rename_all = "camelCase")]
pub struct TruncateSessionConversationFromMessageRequest {
pub session_id: String,
pub message_id: String,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema, JsonRpcResponse)]
#[serde(rename_all = "camelCase")]
pub struct TruncateSessionConversationFromMessageResponse {
/// False when no message with that id exists in the session (nothing was removed).
pub found: bool,
}

/// Update the project association for a session.
#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema, JsonRpcRequest)]
#[request(method = "_goose/unstable/session/project/update", response = EmptyResponse)]
Expand Down
5 changes: 5 additions & 0 deletions crates/goose/acp-meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,11 @@
"requestType": "TruncateSessionConversationRequest_unstable",
"responseType": "EmptyResponse"
},
{
"method": "_goose/unstable/session/conversation/truncate_from_message",
"requestType": "TruncateSessionConversationFromMessageRequest_unstable",
"responseType": "TruncateSessionConversationFromMessageResponse_unstable"
},
{
"method": "_goose/unstable/session/project/update",
"requestType": "UpdateSessionProjectRequest_unstable",
Expand Down
49 changes: 49 additions & 0 deletions crates/goose/acp-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -5127,6 +5127,38 @@
"x-side": "agent",
"x-method": "_goose/unstable/session/conversation/truncate"
},
"TruncateSessionConversationFromMessageRequest_unstable": {
"type": "object",
"properties": {
"sessionId": {
"type": "string"
},
"messageId": {
"type": "string"
}
},
"required": [
"sessionId",
"messageId"
],
"description": "Truncate a session conversation from the message with the given id onward\n(that message included). The boundary is the message's row, so messages\nstored in the same second before it are kept. Refused while the session has\nan active run.",
"x-side": "agent",
"x-method": "_goose/unstable/session/conversation/truncate_from_message"
},
"TruncateSessionConversationFromMessageResponse_unstable": {
"type": "object",
"properties": {
"found": {
"type": "boolean",
"description": "False when no message with that id exists in the session (nothing was removed)."
}
},
"required": [
"found"
],
"x-side": "agent",
"x-method": "_goose/unstable/session/conversation/truncate_from_message"
},
"UpdateSessionProjectRequest_unstable": {
"type": "object",
"properties": {
Expand Down Expand Up @@ -8000,6 +8032,15 @@
"description": "Params for _goose/unstable/session/conversation/truncate",
"title": "TruncateSessionConversationRequest_unstable"
},
{
"allOf": [
{
"$ref": "#/$defs/TruncateSessionConversationFromMessageRequest_unstable"
}
],
"description": "Params for _goose/unstable/session/conversation/truncate_from_message",
"title": "TruncateSessionConversationFromMessageRequest_unstable"
},
{
"allOf": [
{
Expand Down Expand Up @@ -8764,6 +8805,14 @@
],
"title": "GetSessionInfoResponse_unstable"
},
{
"allOf": [
{
"$ref": "#/$defs/TruncateSessionConversationFromMessageResponse_unstable"
}
],
"title": "TruncateSessionConversationFromMessageResponse_unstable"
},
{
"allOf": [
{
Expand Down
13 changes: 11 additions & 2 deletions crates/goose/src/acp/server.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// 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.
// 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; session/prompt _meta.goose.messageId sets the stored user message id; advertise truncateFromMessage.
use crate::acp::custom_notifications::*;
use crate::acp::custom_requests::*;
pub(super) use crate::acp::response_builder::{
Expand Down Expand Up @@ -129,6 +129,7 @@ mod sources;
mod tool_calls;
mod tool_notifications;
mod tools;
mod truncate_from_message;

pub type AcpProviderFactory =
Arc<dyn Fn(String) -> BoxFuture<'static, Result<Arc<dyn Provider>>> + Send + Sync>;
Expand Down Expand Up @@ -409,6 +410,10 @@ fn meta_tags(meta: Option<&Meta>) -> Result<Vec<(String, String)>, agent_client_
fn agent_capabilities_meta() -> Option<Meta> {
let mut goose = serde_json::Map::new();
goose.insert("recipeParameterScopes".to_string(), serde_json::json!({}));
goose.insert(
truncate_from_message::TRUNCATE_FROM_MESSAGE_CAPABILITY.to_string(),
serde_json::json!(true),
);
if cfg!(feature = "local-inference") {
goose.insert("localInference".to_string(), serde_json::json!({}));
}
Expand Down Expand Up @@ -2244,6 +2249,7 @@ impl AcpConnection {
args: PromptRequest,
) -> Result<PromptResponse, agent_client_protocol::Error> {
let max_turns = session_settings::max_turns_from_meta(args.meta.as_ref())?;
let message_id = truncate_from_message::message_id_from_meta(args.meta.as_ref())?;
// The ACP session_id IS the thread ID.
let session_id = args.session_id.0.to_string();

Expand Down Expand Up @@ -2284,7 +2290,10 @@ impl AcpConnection {
return Err(error);
}

let user_message = Self::convert_acp_prompt_to_message(&args.prompt);
let mut user_message = Self::convert_acp_prompt_to_message(&args.prompt);
if let Some(message_id) = message_id {
user_message = user_message.with_id(message_id);
}
// The client's trace context must stay attached while the turn's spans and tool calls are polled.
#[cfg(feature = "otel")]
let trace_cx = crate::otel::trace_context::extract_from_meta(args.meta.as_ref())
Expand Down
11 changes: 10 additions & 1 deletion crates/goose/src/acp/server/custom_dispatch.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Modified by Jonathan Mohrbacher, 2026: dispatch _goose/unstable/session/settings/set.
// Modified by Jonathan Mohrbacher, 2026: dispatch _goose/unstable/session/settings/set; dispatch truncate_from_message.
use super::*;
use goose_acp_macros::custom_methods;

Expand Down Expand Up @@ -687,6 +687,15 @@ impl AcpConnection {
self.on_truncate_session_conversation(req).await
}

#[custom_method(TruncateSessionConversationFromMessageRequest)]
async fn dispatch_truncate_session_conversation_from_message(
&self,
req: TruncateSessionConversationFromMessageRequest,
) -> Result<TruncateSessionConversationFromMessageResponse, agent_client_protocol::Error> {
self.on_truncate_session_conversation_from_message(req)
.await
}

#[custom_method(UpdateSessionProjectRequest)]
async fn dispatch_update_session_project(
&self,
Expand Down
132 changes: 132 additions & 0 deletions crates/goose/src/acp/server/truncate_from_message.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// Modified by Jonathan Mohrbacher, 2026: client-chosen prompt message ids and truncate_from_message (honk /undo).
//! A client can choose the id goose stores a prompt's user message under
//! (`_meta.goose.messageId` on `session/prompt`) and later delete history from that
//! message onward with `_goose/unstable/session/conversation/truncate_from_message`.
//! Upstream's truncate cuts by timestamp, which also deletes a message stored in the
//! same second before the boundary.

use super::*;

pub(super) const TRUNCATE_FROM_MESSAGE_CAPABILITY: &str = "truncateFromMessage";

/// The caller owns uniqueness; truncation cuts from the first row with the id.
pub(super) fn message_id_from_meta(
meta: Option<&Meta>,
) -> Result<Option<String>, agent_client_protocol::Error> {
let Some(value) = meta
.and_then(|meta| meta.get("goose"))
.and_then(|goose| goose.get("messageId"))
else {
return Ok(None);
};
if value.is_null() {
return Ok(None);
}
match value.as_str().map(str::trim) {
Some(id) if !id.is_empty() => Ok(Some(id.to_string())),
_ => Err(agent_client_protocol::Error::invalid_params()
.data("_meta.goose.messageId must be a non-empty string")),
}
}

impl AcpConnection {
pub(super) async fn on_truncate_session_conversation_from_message(
&self,
req: TruncateSessionConversationFromMessageRequest,
) -> Result<TruncateSessionConversationFromMessageResponse, agent_client_protocol::Error> {
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 message_id = req.message_id.trim();
if message_id.is_empty() {
return Err(
agent_client_protocol::Error::invalid_params().data("messageId cannot be empty")
);
}
// A running turn (or a live voice interaction, which writes messages) would write
// its tail after the cut. Gateway and scheduler turns hold only the turn lock, so
// runs alone would miss them. The check is not atomic with a prompt arriving next;
// callers that need that (honkd) serialize prompts and truncation themselves.
if self.services.runtime.is_busy(session_id) {
return Err(agent_client_protocol::Error::invalid_request().data(format!(
"session {session_id} has an active run or live voice interaction; truncate after it ends"
)));
}

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 found = self
.services
.session_manager
.truncate_conversation_from_message(session_id, message_id)
.await
.internal_err()?;
Ok(TruncateSessionConversationFromMessageResponse { found })
}
}

#[cfg(test)]
mod tests {
use super::*;

fn meta(value: serde_json::Value) -> Meta {
serde_json::from_value(value).unwrap()
}

#[test]
fn message_id_from_meta_reads_goose_message_id() {
assert_eq!(message_id_from_meta(None).unwrap(), None);
for absent in [
serde_json::json!({ "other": 1 }),
serde_json::json!({ "goose": {} }),
serde_json::json!({ "goose": { "messageId": null } }),
] {
assert_eq!(message_id_from_meta(Some(&meta(absent))).unwrap(), None);
}
assert_eq!(
message_id_from_meta(Some(&meta(
serde_json::json!({ "goose": { "messageId": " msg_honk_1 " } })
)))
.unwrap()
.as_deref(),
Some("msg_honk_1")
);
}

#[test]
fn message_id_from_meta_rejects_empty_or_non_string() {
for bad in [
serde_json::json!(""),
serde_json::json!(" "),
serde_json::json!(7),
] {
let error = message_id_from_meta(Some(&meta(
serde_json::json!({ "goose": { "messageId": bad } }),
)))
.unwrap_err();
assert_eq!(
error.code,
agent_client_protocol::schema::v1::ErrorCode::InvalidParams
);
}
}

#[test]
fn agent_capabilities_advertise_truncate_from_message() {
assert_eq!(
agent_capabilities_meta()
.and_then(|meta| meta.get("goose").cloned())
.and_then(|goose| goose.get(TRUNCATE_FROM_MESSAGE_CAPABILITY).cloned()),
Some(serde_json::json!(true))
);
}
}
3 changes: 2 additions & 1 deletion crates/goose/src/agents/session_runtime.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Modified by Jonathan Mohrbacher, 2026: is_busy visible to truncate_from_message.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

Expand Down Expand Up @@ -189,7 +190,7 @@ impl SessionRuntime {

/// A Live conversation runs without a turn, and a prompt registers its run before
/// its turn starts.
fn is_busy(&self, session_id: &str) -> bool {
pub(crate) fn is_busy(&self, session_id: &str) -> bool {
self.confirmations.has_active_turn(session_id) || self.runs.is_active(session_id)
}

Expand Down
Loading
Loading