Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

acp: map a truncated final response to the max_tokens stop reason (#3363) (#3367)

Sebastian Müller9981e925012f
diff --git a/.changes/acp-max-tokens-stop-reason.md b/.changes/acp-max-tokens-stop-reason.md
new file mode 100644
index 0000000000..0822378ff0
--- /dev/null
+++ b/.changes/acp-max-tokens-stop-reason.md
@@ -0,0 +1 @@
+- ACP mode now resolves a prompt turn whose final model response stopped at the provider's output-token limit with `stopReason: "max_tokens"` instead of `end_turn`, so a truncated answer is no longer indistinguishable from a finished one; autonomous-run limits keep their existing stop reasons (the TypeScript version does not map the truncation case).
diff --git a/crates/pa-cli/tests/acp_mode_e2e.rs b/crates/pa-cli/tests/acp_mode_e2e.rs
index 57d9fefe66..41ffaddc05 100644
--- a/crates/pa-cli/tests/acp_mode_e2e.rs
+++ b/crates/pa-cli/tests/acp_mode_e2e.rs
@@ -1728,6 +1728,48 @@ fn acp_autonomous_disabled_reports_end_turn_without_accounting() {
);
}
+#[test]
+fn acp_truncated_final_response_maps_to_max_tokens_stop_reason() {
+ // Issue #3363: a turn whose final assistant message stopped at the
+ // provider's output-token cap resolves with max_tokens, not end_turn;
+ // and the stop reason is per-turn — the following /compact prompt runs
+ // no model call (the faux session is short, so it skips), so it must
+ // not inherit the truncated turn's length.
+ let script = json!({
+ "engine": "faux",
+ "responses": [{ "text": "half an answer", "stopReason": "length" }],
+ });
+ let mut client = AcpChild::spawn(&["--mode", "acp", "--no-session"], &script);
+ let init = client.request("initialize", &initialize_params());
+ let _ = client.wait_response(init, TIMEOUT);
+ let new = client.request("session/new", &json!({ "mcpServers": [] }));
+ let (new_response, _) = client.wait_response(new, TIMEOUT);
+ let session_id = new_response["result"]["sessionId"]
+ .as_str()
+ .unwrap()
+ .to_string();
+
+ let prompt = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "write a long essay" }] }),
+ );
+ let (prompt_response, _) = client.wait_response(prompt, TIMEOUT);
+ assert_eq!(
+ prompt_response["result"],
+ json!({ "stopReason": "max_tokens" })
+ );
+
+ let slash = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "/compact" }] }),
+ );
+ let (slash_response, _) = client.wait_response(slash, TIMEOUT);
+ assert_eq!(
+ slash_response["result"],
+ json!({ "stopReason": "end_turn" })
+ );
+}
+
#[test]
fn acp_daemon_attached_reports_autonomous_accounting_and_limit_stop_reason() {
// An autonomous run with --max-turns 1: the completion envelope carries
diff --git a/crates/pa-daemon/src/acp/daemon.rs b/crates/pa-daemon/src/acp/daemon.rs
index afa391fa8d..f64bc450bd 100644
--- a/crates/pa-daemon/src/acp/daemon.rs
+++ b/crates/pa-daemon/src/acp/daemon.rs
@@ -272,8 +272,11 @@ pub(crate) struct HostedSession {
/// The running prompt turn; one at a time. A cancelled turn keeps
/// the slot until its cancel stop finishes.
turn: Option<ActiveTurn>,
- /// The newest assistant stop reason observed on the event stream.
- assistant_stop_reason: Option<String>,
+ /// The newest assistant stop reason observed on the event stream,
+ /// cleared when a prompt turn is admitted so a turn never reads a
+ /// previous turn's stop reason (read after the settlement for the
+ /// stop-reason response).
+ assistant_stop_reason: Option<pa_types::ai::StopReason>,
/// The event mapping state lives and dies with the session, like TS.
mapping: WireMappingState,
observed_children: std::collections::HashSet<String>,
@@ -734,6 +737,9 @@ async fn admit_prompt(
return Err("A prompt turn is already running for this ACP session".to_string());
}
let admission_id = format!("prompt-admission:{}", uuid::Uuid::new_v4());
+ // The stop reason is per-turn: a turn that runs no model call (a
+ // slash command) must not inherit the previous turn's stop reason.
+ hosted.assistant_stop_reason = None;
hosted.turn = Some(ActiveTurn {
admission_id: admission_id.clone(),
cancelled: false,
@@ -1626,13 +1632,26 @@ async fn prompt_turn(
}
break status;
};
- // The stop reason follows the TS mapping (acp-stop-reason.ts): the
- // abort flag read after the settlement, and the settlement's status
- // (`pending.status`), not the first observation's.
- let stop_reason = meta::acp_stop_reason_for_status(
- turn_cancelled(&*state.lock().await, admission_id),
- Some(&settled_status),
- );
+ // The stop reason follows the TS mapping (acp-stop-reason.ts) plus the
+ // turn's final assistant stop reason (#3363): the abort flag read after
+ // the settlement, the settlement's status (`pending.status`), not the
+ // first observation's, and the newest assistant stop reason — the link's
+ // one frame consumer applies every message_end (the autonomous
+ // continuations' included, since they run inside the waits above) before
+ // the response that ended each wait resolved, so this read after the
+ // settlement sees the run's final one.
+ let (cancelled, assistant_stop_reason) = {
+ let guard = state.lock().await;
+ (
+ turn_cancelled(&guard, admission_id),
+ guard
+ .session
+ .as_ref()
+ .and_then(|hosted| hosted.assistant_stop_reason),
+ )
+ };
+ let stop_reason =
+ meta::acp_stop_reason_for_status(cancelled, Some(&settled_status), assistant_stop_reason);
jsonrpc::response(
&id,
&serde_json::to_value(types::AcpStopReasonResponse { stop_reason }).expect("serializes"),
diff --git a/crates/pa-daemon/src/acp/meta.rs b/crates/pa-daemon/src/acp/meta.rs
index 72353e343f..1231c05840 100644
--- a/crates/pa-daemon/src/acp/meta.rs
+++ b/crates/pa-daemon/src/acp/meta.rs
@@ -202,31 +202,43 @@ pub fn autonomous_meta(
}
}
-/// Map a finished turn onto an ACP stop reason: autonomous quality gates
-/// deliberately never surface as a stop reason; token exhaustion is the one
-/// natively-expressed limit.
+/// Map a finished turn onto an ACP stop reason. Precedence: an explicit
+/// cancel, then the TS `acpStopReason` mapping for an enabled autonomous
+/// run, then the turn's final assistant stop reason (#3363): a per-call
+/// output-token truncation (`StopReason::Length`) is an honest
+/// `max_tokens`, so `end_turn` stays reserved for a finished answer;
+/// every other final reason (and none) keeps TS's `end_turn`.
pub fn acp_stop_reason_for_status(
cancelled: bool,
status: Option<&pa_core::autonomous::AgentAutonomousStatus>,
+ assistant_stop_reason: Option<pa_types::ai::StopReason>,
) -> super::types::AcpStopReason {
use pa_core::autonomous::{autonomous_limit_reason_of_status, AutonomousLimitReason};
+ use pa_types::ai::StopReason;
if cancelled {
return super::types::AcpStopReason::Cancelled;
}
- let Some(status) = status else {
- return super::types::AcpStopReason::EndTurn;
- };
- if !status.enabled {
- return super::types::AcpStopReason::EndTurn;
- }
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_millis() as u64)
.unwrap_or_default();
- match autonomous_limit_reason_of_status(status, now) {
+ match status
+ .filter(|status| status.enabled)
+ .and_then(|status| autonomous_limit_reason_of_status(status, now))
+ {
Some(AutonomousLimitReason::MaxTokens) => super::types::AcpStopReason::MaxTokens,
- Some(_) => super::types::AcpStopReason::MaxTurnRequests,
- None => super::types::AcpStopReason::EndTurn,
+ Some(
+ AutonomousLimitReason::MaxContinuations
+ | AutonomousLimitReason::MaxTurns
+ | AutonomousLimitReason::TimeoutMs,
+ ) => super::types::AcpStopReason::MaxTurnRequests,
+ None => match assistant_stop_reason {
+ Some(StopReason::Length) => super::types::AcpStopReason::MaxTokens,
+ Some(
+ StopReason::Stop | StopReason::ToolUse | StopReason::Error | StopReason::Aborted,
+ )
+ | None => super::types::AcpStopReason::EndTurn,
+ },
}
}
@@ -259,6 +271,66 @@ mod tests {
);
}
+ #[test]
+ fn acp_stop_reason_keeps_cancel_and_run_limits_first() {
+ // The precedence the e2e cannot build against a truncated final
+ // message: the explicit cancel and the enabled run's own limits
+ // stay ahead of the final assistant stop reason (the e2e covers
+ // the disabled-status and below-mapping cases).
+ use super::super::types::AcpStopReason;
+ use pa_core::autonomous::{AgentAutonomousStatus, AutonomousLimits, NormalizedGateConfig};
+ use pa_types::ai::StopReason;
+ let status = |enabled: bool, turns_used: u64| AgentAutonomousStatus {
+ enabled,
+ continuations_used: 0,
+ turns_used,
+ tokens_used: 1_000,
+ started_at: None,
+ limits: AutonomousLimits {
+ max_continuations: 3,
+ max_turns: 12,
+ max_tokens: 80_000,
+ timeout_ms: 1_800_000,
+ },
+ gates: NormalizedGateConfig {
+ commands: Vec::new(),
+ max_retries: 0,
+ timeout_ms: 0,
+ },
+ gate_attempts: std::collections::HashMap::new(),
+ last_gate_failure: None,
+ subagent_keep_alive_ms: None,
+ };
+ // An explicit cancel wins over the turn's own truncated stop reason.
+ assert_eq!(
+ acp_stop_reason_for_status(
+ /*cancelled*/ true,
+ Some(&status(false, 1)),
+ Some(StopReason::Length)
+ ),
+ AcpStopReason::Cancelled
+ );
+ // An enabled run below its limits maps the final length (#3363).
+ assert_eq!(
+ acp_stop_reason_for_status(
+ /*cancelled*/ false,
+ Some(&status(true, 1)),
+ Some(StopReason::Length)
+ ),
+ AcpStopReason::MaxTokens
+ );
+ // The turn-request limit stays the run's stop reason even when the
+ // final message also truncated.
+ assert_eq!(
+ acp_stop_reason_for_status(
+ /*cancelled*/ false,
+ Some(&status(true, 12)),
+ Some(StopReason::Length)
+ ),
+ AcpStopReason::MaxTurnRequests
+ );
+ }
+
#[test]
fn quiescence_serializes_camel_case() {
let wrapped = prime_agent_meta(&PrimeAgentSessionMeta {
diff --git a/crates/pa-daemon/src/acp/wire_events.rs b/crates/pa-daemon/src/acp/wire_events.rs
index af53ec50f7..b246b94686 100644
--- a/crates/pa-daemon/src/acp/wire_events.rs
+++ b/crates/pa-daemon/src/acp/wire_events.rs
@@ -7,6 +7,7 @@
//! `agent_begin/end`, `session_action_update`) map to nothing, exactly like
//! the TS switch's default arm.
+use serde::Deserialize as _;
use serde_json::{json, Value};
use super::meta::{prime_agent_meta, PrimeAgentCompactionMeta, PrimeAgentSessionMeta};
@@ -43,14 +44,15 @@ impl WireMappingState {
}
}
-/// The newest assistant stop reason carried by a `message_end` event (the
-/// transport reads it after the turn for the stop-reason response).
+/// The assistant stop reason carried by one `message_end` event: the
+/// transport keeps the newest one and reads it after the turn for the
+/// stop-reason response.
pub struct AssistantStop {
- pub stop_reason: Option<String>,
+ pub stop_reason: Option<pa_types::ai::StopReason>,
}
-/// Extract the assistant stop/error fields from one wire event, when the
-/// event settles an assistant message.
+/// Extract the assistant stop reason from one wire event, when the event
+/// settles an assistant message.
pub fn assistant_stop(event: &Value) -> Option<AssistantStop> {
if event.get("type").and_then(Value::as_str) != Some("message_end") {
return None;
@@ -62,8 +64,7 @@ pub fn assistant_stop(event: &Value) -> Option<AssistantStop> {
Some(AssistantStop {
stop_reason: message
.get("stopReason")
- .and_then(Value::as_str)
- .map(str::to_string),
+ .and_then(|value| pa_types::ai::StopReason::deserialize(value).ok()),
})
}
@@ -645,10 +646,10 @@ mod tests {
fn assistant_stop_reason_is_captured_from_message_end() {
let stop = assistant_stop(&json!({
"type": "message_end",
- "message": { "role": "assistant", "stopReason": "end_turn" },
+ "message": { "role": "assistant", "stopReason": "length" },
}))
.expect("assistant message_end");
- assert_eq!(stop.stop_reason.as_deref(), Some("end_turn"));
+ assert_eq!(stop.stop_reason, Some(pa_types::ai::StopReason::Length));
assert!(assistant_stop(&json!({
"type": "message_end",
"message": { "role": "user" },