Skip to content

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

Rust

acp daemon session runs one prompt turn at a time with a per-turn cancel (#3256)

Sebastian Müller576239506ac4
diff --git a/.changes/fix-acp-turn-ownership.md b/.changes/fix-acp-turn-ownership.md
new file mode 100644
index 0000000000..accfa4a2be
--- /dev/null
+++ b/.changes/fix-acp-turn-ownership.md
@@ -0,0 +1 @@
+- ACP sessions run one prompt turn at a time: a prompt sent while a turn runs, or while a cancel is stopping it, is refused instead of overlapping it; a cancel now stops only its own turn, and a failed turn no longer reports itself as finished.
diff --git a/crates/pa-cli/tests/acp_mode_e2e.rs b/crates/pa-cli/tests/acp_mode_e2e.rs
index 9cb427ceaf..188e999195 100644
--- a/crates/pa-cli/tests/acp_mode_e2e.rs
+++ b/crates/pa-cli/tests/acp_mode_e2e.rs
@@ -846,18 +846,13 @@ fn acp_daemon_attached_cancels_mid_turn() {
}
#[test]
-fn acp_daemon_attached_prompt_after_cancel_runs() {
- // A Stop -> resend flow: a mid-turn cancel leaves the worker's
- // queued-input admission suspended (TS `requestAbort`), and the next
- // ACP prompt resumes it through its streaming behavior (TS sends
- // `followUp` + `queueIfBusy: true` on every prompt, acp-mode.ts).
- // The first response streams at a fixed token rate, so the test
- // cancels only after its first chunk: the turn is observably running,
- // and the cancel cannot land before the worker admitted it.
+fn acp_daemon_attached_overlapping_prompt_is_refused() {
+ // A second prompt while the first runs is refused; the running turn
+ // is untouched and the next prompt after its settle runs.
let (mut client, _socket) = AcpChild::spawn_daemon_attached(
&["--mode", "acp", "--no-session"],
&json!({ "engine": "faux", "tokensPerSecond": 2, "responses": [
- { "text": "a paced answer that streams slowly enough to cancel mid-turn" },
+ { "text": "a paced answer that streams slowly enough to overlap a prompt" },
"SECOND-OK",
] }),
);
@@ -875,28 +870,198 @@ fn acp_daemon_attached_prompt_after_cancel_runs() {
);
// Readiness is the turn's own first streamed chunk, not a timer.
client.wait_update("agent_message_chunk", TIMEOUT);
+ let second = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "the overlap" }] }),
+ );
+ let (second_response, _) = client.wait_response(second, TIMEOUT);
+ assert_eq!(
+ second_response["error"]["code"], -32603,
+ "the overlapping prompt is refused: {second_response}"
+ );
+ assert!(
+ second_response["error"]["data"]["details"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("A prompt turn is already running for this ACP session"),
+ "the refusal names the running-turn rule: {second_response}"
+ );
+ let (first_response, _) = client.wait_response(first, TIMEOUT);
+ assert_eq!(
+ first_response["result"]["stopReason"], "end_turn",
+ "the refused overlap never touched the running turn: {first_response}"
+ );
+ let third = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "after the settle" }] }),
+ );
+ let (third_response, updates) = client.wait_response(third, TIMEOUT);
+ assert_eq!(
+ third_response["result"]["stopReason"], "end_turn",
+ "the turn slot frees at the settle: {third_response}"
+ );
+ let chunk = updates
+ .iter()
+ .find(|update| update["params"]["update"]["sessionUpdate"] == "agent_message_chunk")
+ .expect("the next turn streams its scripted answer");
+ assert_eq!(
+ chunk["params"]["update"]["content"],
+ json!({ "type": "text", "text": "SECOND-OK" })
+ );
+}
+
+#[test]
+fn acp_daemon_attached_close_mid_turn_answers_cancelled() {
+ let (mut client, _socket) = AcpChild::spawn_daemon_attached(
+ &["--mode", "acp", "--no-session"],
+ &json!({ "engine": "faux", "tokensPerSecond": 2, "responses": [
+ { "text": "a paced answer that streams slowly enough to close mid-turn" },
+ ] }),
+ );
+ 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": "a slow question" }] }),
+ );
+ client.wait_update("agent_message_chunk", TIMEOUT);
+ let close = client.request("session/close", &json!({ "sessionId": session_id }));
+ let (prompt_response, frames) = client.wait_response(prompt, TIMEOUT);
+ assert_eq!(
+ prompt_response["result"]["stopReason"], "cancelled",
+ "a prompt closed mid-turn answers cancelled: {prompt_response}"
+ );
+ let close_response = frames
+ .into_iter()
+ .find(|frame| frame["id"] == close)
+ .unwrap_or_else(|| client.wait_response(close, TIMEOUT).0);
+ assert_eq!(close_response["result"], json!({}));
+}
+
+#[test]
+fn acp_daemon_attached_prompt_during_cancel_is_refused() {
+ // A prompt behind a cancel is refused while the stop runs, and the
+ // cancelled response comes after the stop, so a resend right after it
+ // runs.
+ let (mut client, _socket) = AcpChild::spawn_daemon_attached(
+ &["--mode", "acp", "--no-session"],
+ &json!({ "engine": "faux", "tokensPerSecond": 2, "responses": [
+ { "text": "a paced answer that streams slowly enough to cancel mid-turn" },
+ "AFTER-STOP",
+ ] }),
+ );
+ 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 first = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "a slow question" }] }),
+ );
+ client.wait_update("agent_message_chunk", TIMEOUT);
client.notify("session/cancel", &json!({ "sessionId": session_id }));
+ let second = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "behind the stop" }] }),
+ );
+ let (second_response, _) = client.wait_response(second, TIMEOUT);
+ assert_eq!(
+ second_response["error"]["code"], -32603,
+ "the prompt behind the cancel is refused: {second_response}"
+ );
+ assert_eq!(
+ second_response["error"]["data"]["details"],
+ format!("ACP session is cancelling: {session_id}"),
+ "the refusal names the cancelling window: {second_response}"
+ );
let (first_response, _) = client.wait_response(first, TIMEOUT);
assert_eq!(
first_response["result"]["stopReason"], "cancelled",
- "the mid-turn cancel settles the first prompt: {first_response}"
+ "the cancel settles the running turn: {first_response}"
);
- let second = client.request(
+ // The resend also resumes the queued-input admission the cancel
+ // suspended (TS sends `followUp` + `queueIfBusy: true`).
+ let third = client.request(
"session/prompt",
&json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "the resend" }] }),
);
- let (second_response, updates) = client.wait_response(second, TIMEOUT);
+ let (third_response, updates) = client.wait_response(third, TIMEOUT);
assert_eq!(
- second_response["result"]["stopReason"], "end_turn",
- "the prompt after a cancel runs: {second_response}"
+ third_response["result"]["stopReason"], "end_turn",
+ "the stop cleared before the cancelled response: {third_response}"
);
let chunk = updates
.iter()
.find(|update| update["params"]["update"]["sessionUpdate"] == "agent_message_chunk")
- .expect("the resumed turn streams its scripted answer");
+ .expect("the resent turn streams its scripted answer");
assert_eq!(
chunk["params"]["update"]["content"],
- json!({ "type": "text", "text": "SECOND-OK" })
+ json!({ "type": "text", "text": "AFTER-STOP" })
+ );
+}
+
+#[test]
+fn acp_daemon_attached_failed_turn_publishes_only_the_error_boundary() {
+ // A failed turn (here: the empty-prompt rejection) publishes one
+ // error boundary and no terminal-quiescence update (TS settle catch).
+ let (mut client, _socket) = AcpChild::spawn_daemon_attached(
+ &["--mode", "acp", "--no-session"],
+ &json!({ "engine": "faux", "responses": [] }),
+ );
+ 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": [] }),
+ );
+ let (prompt_response, updates) = client.wait_response(prompt, TIMEOUT);
+ assert_eq!(
+ prompt_response["error"]["code"], -32603,
+ "the failed turn errors the request: {prompt_response}"
+ );
+ assert!(
+ prompt_response["error"]["data"]["details"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("Prompt cannot be empty"),
+ "the worker's failure is the error: {prompt_response}"
+ );
+ let mut boundaries = 0;
+ for update in &updates {
+ let body = &update["params"]["update"];
+ let meta = &body["_meta"]["ai.primeintellect.prime-agent"];
+ assert_ne!(
+ meta["phase"], "terminalQuiescence",
+ "a failed turn never publishes a terminal frame: {updates:?}"
+ );
+ if meta["phase"] == "responseBoundary" {
+ boundaries += 1;
+ assert_eq!(
+ meta["terminalQuiescenceExpected"], false,
+ "the one boundary declares no terminal expectation: {updates:?}"
+ );
+ assert_eq!(meta["outcome"], "error");
+ }
+ }
+ assert_eq!(
+ boundaries, 1,
+ "the failed turn published exactly one correlated error boundary: {updates:?}"
);
}
diff --git a/crates/pa-daemon/src/acp/daemon.rs b/crates/pa-daemon/src/acp/daemon.rs
index 6b57128018..d2af372201 100644
--- a/crates/pa-daemon/src/acp/daemon.rs
+++ b/crates/pa-daemon/src/acp/daemon.rs
@@ -243,7 +243,9 @@ pub(crate) struct HostedSession {
pub(crate) config: Arc<HostedConfig>,
mcp_owner_id: String,
mcp_server_names: Vec<String>,
- cancel_requested: bool,
+ /// The running prompt turn; one at a time. A cancelled turn keeps
+ /// the slot until its stop sequence finishes (TS `entry.cancelling`).
+ turn: Option<ActiveTurn>,
/// The newest assistant stop reason observed on the event stream.
assistant_stop_reason: Option<String>,
/// Resolved when the worker emits the turn's last `agent_end` event:
@@ -261,6 +263,16 @@ pub(crate) struct HostedSession {
agent_runs_ended: u64,
}
+struct ActiveTurn {
+ /// TS `admissionId`; the stop sequence cancels the admission by it.
+ admission_id: String,
+ /// TS the per-turn `AbortController`.
+ cancelled: bool,
+ /// Resolves when the stop sequence finished; the cancelled turn's
+ /// response waits for it, so the next prompt never sees "cancelling".
+ stop_done_rx: Option<oneshot::Receiver<()>>,
+}
+
/// The daemon-attached transport state: one hosted session at most, like
/// the in-process connection state.
#[derive(Default)]
@@ -431,25 +443,51 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::
// handling): a prompt turn may span minutes, and `session/cancel`
// must reach the daemon while it is in flight. The state machine
// (one hosted session, one in-flight close) keeps the concurrency
- // bounded.
- // Frame-order admission for `session/prompt` (TS ordering parity):
- // the spawned handlers race each other, but TS runs a request's
- // synchronous prefix before the next frame's handler. A
- // `session/cancel` that arrives after the prompt must win, so the
- // prompt's cancel-flag reset happens here, in read order, instead
- // of inside the spawned prompt task.
- if matches!(&incoming, Incoming::Request { method, .. } if method == "session/prompt") {
- if let Some(hosted) = state.lock().await.session.as_mut() {
- hosted.cancel_requested = false;
+ // bounded. Prompt admission and cancel marking run here, in frame
+ // order (TS runs a request's synchronous prefix before the next
+ // frame's handler).
+ match frame_order_prefix(&incoming, &state).await {
+ FrameOrder::Spawn => {
+ let link = Arc::clone(&link);
+ let state = Arc::clone(&state);
+ let options = options.clone();
+ let options_tx = tx.clone();
+ tokio::spawn(async move {
+ handle_incoming(incoming, &link, &state, &options, options_tx).await;
+ });
+ }
+ FrameOrder::AdmitPrompt {
+ id,
+ params,
+ admission_id,
+ } => {
+ let link = Arc::clone(&link);
+ let state = Arc::clone(&state);
+ let options_tx = tx.clone();
+ tokio::spawn(async move {
+ handle_session_prompt(id, params, admission_id, &link, &state, options_tx)
+ .await;
+ });
+ }
+ // A refused prompt answers from the prefix; the running turn
+ // is untouched.
+ FrameOrder::Refused { id, message } => {
+ let _ = tx.send(super::internal_error(&id, &message));
+ }
+ // A cancel arms the stop task; the request form answers `{}`
+ // immediately (the notification form has no response).
+ FrameOrder::Cancel { request_id, stop } => {
+ if let Some(stop) = stop {
+ let link = Arc::clone(&link);
+ tokio::spawn(async move {
+ run_cancel_stop(stop, &link).await;
+ });
+ }
+ if let Some(id) = request_id {
+ let _ = tx.send(jsonrpc::response(&id, &json!({})));
+ }
}
}
- let link = Arc::clone(&link);
- let state = Arc::clone(&state);
- let options = options.clone();
- let options_tx = tx.clone();
- tokio::spawn(async move {
- handle_incoming(incoming, &link, &state, &options, options_tx).await;
- });
}
// A client-owned session dies with the connection: stop the work,
@@ -460,6 +498,157 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::
Ok(0)
}
+enum FrameOrder {
+ Spawn,
+ AdmitPrompt {
+ id: Value,
+ params: Value,
+ admission_id: String,
+ },
+ Refused {
+ id: Value,
+ message: String,
+ },
+ /// `request_id` is set for the request form, which answers `{}` (TS
+ /// only registers the notification form).
+ Cancel {
+ request_id: Option<Value>,
+ stop: Option<CancelStop>,
+ },
+}
+
+struct CancelStop {
+ daemon_session_id: String,
+ admission_id: String,
+ stop_done_tx: oneshot::Sender<()>,
+}
+
+/// Prompt admission and cancel marking, in the client's frame order.
+async fn frame_order_prefix(incoming: &Incoming, state: &Arc<Mutex<DaemonAcpState>>) -> FrameOrder {
+ match incoming {
+ Incoming::Request { id, method, params } if method == "session/prompt" => {
+ match admit_prompt(params, state).await {
+ Ok(admission_id) => FrameOrder::AdmitPrompt {
+ id: id.clone(),
+ params: params.clone(),
+ admission_id,
+ },
+ Err(message) => FrameOrder::Refused {
+ id: id.clone(),
+ message,
+ },
+ }
+ }
+ Incoming::Request { id, method, params } if method == "session/cancel" => {
+ let stop = arm_cancel(params, state).await;
+ FrameOrder::Cancel {
+ request_id: Some(id.clone()),
+ stop,
+ }
+ }
+ Incoming::Notification { method, params } if method == "session/cancel" => {
+ let stop = arm_cancel(params, state).await;
+ FrameOrder::Cancel {
+ request_id: None,
+ stop,
+ }
+ }
+ _ => FrameOrder::Spawn,
+ }
+}
+
+/// Reserve the turn slot for one prompt. `Err` is the refusal message,
+/// checked in TS order: unknown session, cancelling, turn running.
+async fn admit_prompt(
+ params: &Value,
+ state: &Arc<Mutex<DaemonAcpState>>,
+) -> Result<String, String> {
+ let session_id = params
+ .get("sessionId")
+ .and_then(Value::as_str)
+ .unwrap_or_default();
+ let mut guard = state.lock().await;
+ let Some(hosted) = guard
+ .session
+ .as_mut()
+ .filter(|hosted| hosted.acp_session_id == session_id)
+ else {
+ return Err(format!("Unknown ACP session: {session_id}"));
+ };
+ match &hosted.turn {
+ Some(turn) if turn.cancelled => {
+ return Err(format!("ACP session is cancelling: {session_id}"));
+ }
+ Some(_) => {
+ return Err("A prompt turn is already running for this ACP session".to_string());
+ }
+ None => {}
+ }
+ let admission_id = format!("prompt-admission:{}", uuid::Uuid::new_v4());
+ hosted.turn = Some(ActiveTurn {
+ admission_id: admission_id.clone(),
+ cancelled: false,
+ stop_done_rx: None,
+ });
+ Ok(admission_id)
+}
+
+/// Mark the addressed turn cancelled and arm its stop sequence. `None`
+/// when there is no running turn or it is already cancelled.
+async fn arm_cancel(params: &Value, state: &Arc<Mutex<DaemonAcpState>>) -> Option<CancelStop> {
+ let session_id = params.get("sessionId").and_then(Value::as_str)?;
+ let mut guard = state.lock().await;
+ let hosted = guard
+ .session
+ .as_mut()
+ .filter(|hosted| hosted.acp_session_id == session_id)?;
+ let daemon_session_id = hosted.daemon_active_session_id.clone();
+ let turn = hosted.turn.as_mut()?;
+ if turn.cancelled {
+ return None;
+ }
+ turn.cancelled = true;
+ let (stop_done_tx, stop_done_rx) = oneshot::channel();
+ turn.stop_done_rx = Some(stop_done_rx);
+ Some(CancelStop {
+ daemon_session_id,
+ admission_id: turn.admission_id.clone(),
+ stop_done_tx,
+ })
+}
+
+/// TS `stopSessionWork`, without the RLM child cancellations. The owned
+/// admission cancel stops a prompt that was sent before the cancel but
+/// committed after the abort. Dropping `stop_done_tx` releases the
+/// cancelled turn's response.
+async fn run_cancel_stop(stop: CancelStop, link: &Arc<DaemonLink>) {
+ let _ = link
+ .request(DaemonCommand::AbortAndClearQueue {
+ id: None,
+ active_session_id: stop.daemon_session_id.clone(),
+ rest: Map::default(),
+ })
+ .await;
+ let _ = link
+ .request(DaemonCommand::CancelPromptAdmission {
+ id: None,
+ active_session_id: stop.daemon_session_id.clone(),
+ admission_id: stop.admission_id,
+ cancel_owned: Some(true),
+ rest: Map::default(),
+ })
+ .await;
+ let _ = link
+ .request(DaemonCommand::WaitForIdle {
+ id: None,
+ active_session_id: stop.daemon_session_id,
+ wait_for_rlm_quiescence: None,
+ rest: Map::default(),
+ })
+ .await;
+ drop(stop.stop_done_tx);
+}
+
/// One incoming ACP frame. Requests answer; notifications may drive state.
async fn handle_incoming(
incoming: Incoming,
@@ -472,13 +661,8 @@ async fn handle_incoming(
Incoming::Request { id, method, params } => {
handle_request(id, method, params, link, state, options, tx).await;
}
- Incoming::Notification { method, params } => {
- // `session/cancel` also arrives as a notification; treat it
- // like the request form without a response.
- if method == "session/cancel" {
- let _ = session_cancel(params, link, state).await;
- }
- }
+ // `session/cancel` is handled in the reader loop.
+ Incoming::Notification { .. } => {}
}
}
@@ -500,13 +684,6 @@ async fn handle_request(
"session/new" => {
handle_session_new(id, params, link, state, options, tx).await;
}
- "session/prompt" => {
- handle_session_prompt(id, params, link, state, tx).await;
- }
- "session/cancel" => {
- let _ = session_cancel(params, link, state).await;
- let _ = tx.send(jsonrpc::response(&id, &json!({})));
- }
"session/set_config_option" => {
handle_set_config_option(id, params, link, state, tx).await;
}
@@ -672,7 +849,7 @@ async fn handle_session_new(
config,
mcp_owner_id,
mcp_server_names: Vec::new(),
- cancel_requested: false,
+ turn: None,
assistant_stop_reason: None,
turn_emitted: None,
agent_runs_started: 0,
@@ -756,66 +933,111 @@ async fn replace_session_servers(
Ok(())
}
-/// Run one prompt turn: `prompt_and_wait` while the event stream fans out.
async fn handle_session_prompt(
id: Value,
params: Value,
+ admission_id: String,
link: &Arc<DaemonLink>,
state: &Arc<Mutex<DaemonAcpState>>,
tx: producer::FrameSink,
) {
+ let reply = prompt_turn(id, params, &admission_id, link, state).await;
+ release_turn_slot(state, &admission_id).await;
+ let _ = tx.send(reply);
+}
+
+/// Release this prompt's turn slot, after its stop sequence if it was
+/// cancelled. A slot holding another prompt's turn (close + new while
+/// this prompt ran) is left alone.
+async fn release_turn_slot(state: &Arc<Mutex<DaemonAcpState>>, admission_id: &str) {
+ let stop_done = {
+ let mut guard = state.lock().await;
+ let Some(hosted) = guard.session.as_mut() else {
+ return;
+ };
+ let stop_done = match hosted.turn.as_mut() {
+ Some(turn) if turn.admission_id != admission_id => return,
+ Some(turn) => turn.stop_done_rx.take(),
+ None => return,
+ };
+ let Some(stop_done) = stop_done else {
+ hosted.turn = None;
+ return;
+ };
+ stop_done
+ };
+ let _ = stop_done.await;
+ if let Some(hosted) = state.lock().await.session.as_mut() {
+ hosted
+ .turn
+ .take_if(|turn| turn.admission_id == admission_id);
+ }
+}
+
+/// Whether this prompt lost its turn: cancelled, or its session was closed
+/// (close, or close + new, takes the slot - like TS close aborting the turn).
+fn turn_cancelled(state: &DaemonAcpState, admission_id: &str) -> bool {
+ !state
+ .session
+ .as_ref()
+ .and_then(|hosted| hosted.turn.as_ref())
+ .is_some_and(|turn| turn.admission_id == admission_id && !turn.cancelled)
+}
+
+fn cancelled_response(id: &Value) -> Value {
+ jsonrpc::response(
+ id,
+ &serde_json::to_value(types::AcpStopReasonResponse {
+ stop_reason: types::AcpStopReason::Cancelled,
+ })
+ .expect("serializes"),
+ )
+}
+
+/// Run one admitted prompt turn and return its reply frame.
+async fn prompt_turn(
+ id: Value,
+ params: Value,
+ admission_id: &str,
+ link: &Arc<DaemonLink>,
+ state: &Arc<Mutex<DaemonAcpState>>,
+) -> Value {
let params = types::PromptParams::parse(&params);
let admitted = match super::session::AdmittedPrompt::parse(&params.prompt) {
Ok(admitted) => admitted,
- Err(error) => {
- let _ = tx.send(super::session::prompt_block_error(&id, &error));
- return;
- }
+ Err(error) => return super::session::prompt_block_error(&id, &error),
};
let (producer, hosted_daemon_session_id) = {
- let mut guard = state.lock().await;
- match guard.session.as_mut() {
- Some(hosted) if hosted.acp_session_id == params.session_id => {
- // TS `entry.cancelling`: a prompt admitted while a cancel
- // is in flight is dropped by the cancel and answers the
- // protocol stop reason instead of running a turn. Taking
- // the flag (not clearing it) settles the cancel so the
- // next prompt runs normally. The reader loop already reset
- // the flag in frame order when it admitted this prompt, so
- // this only fires for a cancel that arrived between the
- // prompt frame's admission and this task starting.
- if std::mem::take(&mut hosted.cancel_requested) {
- let _ = tx.send(jsonrpc::response(
- &id,
- &serde_json::to_value(types::AcpStopReasonResponse {
- stop_reason: types::AcpStopReason::Cancelled,
- })
- .expect("serializes"),
- ));
- return;
- }
- (
- Arc::clone(&hosted.producer),
- hosted.daemon_active_session_id.clone(),
- )
- }
- _ => {
- let _ = tx.send(super::internal_error(
- &id,
- &format!("Unknown ACP session: {}", params.session_id),
- ));
- return;
- }
+ let guard = state.lock().await;
+ match guard.session.as_ref() {
+ Some(hosted) if hosted.acp_session_id == params.session_id => (
+ Arc::clone(&hosted.producer),
+ hosted.daemon_active_session_id.clone(),
+ ),
+ // Admission checked the session id: a miss is a close since.
+ _ => return cancelled_response(&id),
}
};
let turn_id = producer.begin_prompt().await;
// The turn-end marker: the consumer loop resolves it on the worker's
// post-turn `agent_end` event (after the `prompt_and_wait` response).
let (emitted_tx, emitted_rx) = oneshot::channel::<()>();
- if let Some(hosted) = state.lock().await.session.as_mut() {
- hosted.turn_emitted = Some(emitted_tx);
- hosted.agent_runs_started = 0;
- hosted.agent_runs_ended = 0;
+ // TS `abort.signal.aborted` before `promptAndWait`.
+ let cancelled = {
+ let mut guard = state.lock().await;
+ let cancelled = turn_cancelled(&guard, admission_id);
+ if !cancelled {
+ if let Some(hosted) = guard.session.as_mut() {
+ hosted.turn_emitted = Some(emitted_tx);
+ hosted.agent_runs_started = 0;
+ hosted.agent_runs_ended = 0;
+ }
+ }
+ cancelled
+ };
+ if cancelled {
+ producer.finish_prompt(turn_id).await;
+ return cancelled_response(&id);
}
let prompt = DaemonCommand::PromptAndWait {
id: None,
@@ -845,7 +1067,7 @@ async fn handle_session_prompt(
custom_message: None,
queue_key: None,
prefix_messages: None,
- admission_id: None,
+ admission_id: Some(admission_id.to_string()),
rlm_notice_nonce: None,
},
rest: Map::default(),
@@ -853,9 +1075,9 @@ async fn handle_session_prompt(
let response = match link.request_until_close(prompt).await {
Ok(response) => response,
Err(error) => {
+ publish_error_boundary(&producer, turn_id).await;
producer.finish_prompt(turn_id).await;
- let _ = tx.send(super::internal_error(&id, &error.to_string()));
- return;
+ return super::internal_error(&id, &error.to_string());
}
};
// The worker answers the response before its post-turn marker; wait
@@ -866,9 +1088,9 @@ async fn handle_session_prompt(
// the settle must not pay the full marker window for a turn that
// never ran.
let marker_resolved = {
- let mut guard = state.lock().await;
+ let guard = state.lock().await;
matches!(
- guard.session.as_mut(),
+ guard.session.as_ref(),
Some(hosted) if hosted.agent_runs_started == 0
)
};
@@ -881,40 +1103,35 @@ async fn handle_session_prompt(
}
}
let _ = tokio::time::timeout(std::time::Duration::from_secs(30), emitted_rx).await;
- // Read-and-take the flag (TS clears `entry.cancelling` when the
- // cancel settles): this turn settles as cancelled, the next starts clean.
- let cancelled = state
- .lock()
- .await
- .session
- .as_mut()
- .is_none_or(|hosted| std::mem::take(&mut hosted.cancel_requested));
+ let cancelled = {
+ let guard = state.lock().await;
+ turn_cancelled(&guard, admission_id)
+ };
if cancelled {
producer.finish_prompt(turn_id).await;
- let _ = tx.send(jsonrpc::response(
- &id,
- &serde_json::to_value(types::AcpStopReasonResponse {
- stop_reason: types::AcpStopReason::Cancelled,
- })
- .expect("serializes"),
- ));
- return;
+ return cancelled_response(&id);
+ }
+ // TS settle catch: one error boundary, no terminal-quiescence update.
+ if !response.success {
+ let failure = response
+ .error
+ .unwrap_or_else(|| "unknown error".to_string());
+ publish_error_boundary(&producer, turn_id).await;
+ producer.finish_prompt(turn_id).await;
+ return super::internal_error(&id, &format!("prime-agent turn failed: {failure}"));
}
- let outcome = if response.success {
- PrimeAgentOutcome::Result
- } else {
- PrimeAgentOutcome::Error
- };
// The autonomous accounting for the completion envelope: the daemon's
// headless-completion status (TS `waitForHeadlessCompletion`), fetched
// after the turn marker settled the run. A failed fetch degrades to no
// autonomous meta (the envelope still settles, like an in-process
// session without a run).
- let autonomous_status = if response.success {
- fetch_autonomous_status(link, &hosted_daemon_session_id).await
- } else {
- None
- };
+ let autonomous_status = fetch_autonomous_status(link, &hosted_daemon_session_id).await;
+ // TS `abort.signal.aborted` after `waitForHeadlessCompletion`: queued
+ // continuations (goal, post-compaction autonomous) run inside that wait.
+ if turn_cancelled(&*state.lock().await, admission_id) {
+ producer.finish_prompt(turn_id).await;
+ return cancelled_response(&id);
+ }
let autonomous_meta = autonomous_status
.as_ref()
.filter(|status| status.enabled)
@@ -943,7 +1160,7 @@ async fn handle_session_prompt(
&boundary,
turn_id,
PrimeAgentEventPhase::ResponseBoundary,
- Some(outcome),
+ Some(PrimeAgentOutcome::Result),
)
.await;
// The completion envelope mirrors the in-process settlement: the
@@ -977,34 +1194,39 @@ async fn handle_session_prompt(
&terminal,
turn_id,
PrimeAgentEventPhase::TerminalQuiescence,
- Some(outcome),
+ Some(PrimeAgentOutcome::Result),
)
.await;
producer.finish_prompt(turn_id).await;
if !published || !completion_published || !terminal_published {
- let _ = tx.send(super::internal_error(
- &id,
- "Failed to publish ACP completion",
- ));
- return;
- }
- if !response.success {
- let failure = response
- .error
- .unwrap_or_else(|| "unknown error".to_string());
- let _ = tx.send(super::internal_error(
- &id,
- &format!("prime-agent turn failed: {failure}"),
- ));
- return;
+ return super::internal_error(&id, "Failed to publish ACP completion");
}
// The stop reason follows the TS mapping (acp-stop-reason.ts): a limit
// reached on the enabled run is the only non-end_turn outcome.
let stop_reason = meta::acp_stop_reason_for_status(false, autonomous_status.as_ref());
- let _ = tx.send(jsonrpc::response(
+ jsonrpc::response(
&id,
&serde_json::to_value(types::AcpStopReasonResponse { stop_reason }).expect("serializes"),
- ));
+ )
+}
+
+/// The error boundary a failed turn publishes (TS
+/// `terminalQuiescenceExpected: false`).
+async fn publish_error_boundary(producer: &Arc<UpdateProducer>, turn_id: u64) {
+ let boundary = types::AcpSessionUpdate::SessionInfoUpdate {
+ meta: meta::prime_agent_meta(&PrimeAgentSessionMeta {
+ terminal_quiescence_expected: Some(false),
+ ..Default::default()
+ }),
+ };
+ let _ = producer
+ .publish(
+ &boundary,
+ turn_id,
+ PrimeAgentEventPhase::ResponseBoundary,
+ Some(PrimeAgentOutcome::Error),
+ )
+ .await;
}
/// Fetch the session's autonomous-run status (`wait_for_headless_completion`
@@ -1029,36 +1251,6 @@ async fn fetch_autonomous_status(
serde_json::from_value(response.data.unwrap_or(Value::Null)).ok()
}
-/// Abort the hosted session's work (the request and notification forms).
-async fn session_cancel(
- params: Value,
- link: &Arc<DaemonLink>,
- state: &Arc<Mutex<DaemonAcpState>>,
-) -> anyhow::Result<()> {
- let session_id = params
- .get("sessionId")
- .and_then(Value::as_str)
- .unwrap_or_default()
- .to_string();
- let mut guard = state.lock().await;
- let Some(hosted) = guard
- .session
- .as_mut()
- .filter(|hosted| hosted.acp_session_id == session_id)
- else {
- return Ok(());
- };
- hosted.cancel_requested = true;
- let abort = DaemonCommand::Abort {
- id: None,
- active_session_id: hosted.daemon_active_session_id.clone(),
- rest: Map::default(),
- };
- drop(guard);
- let _ = link.request(abort).await;
- Ok(())
-}
-
/// Close: abort, release the servers, kill the client-owned worker, fence
/// the producer.
async fn handle_session_close(
diff --git a/crates/pa-daemon/src/acp/producer.rs b/crates/pa-daemon/src/acp/producer.rs
index 6315b7ef13..a95114d0a9 100644
--- a/crates/pa-daemon/src/acp/producer.rs
+++ b/crates/pa-daemon/src/acp/producer.rs
@@ -91,16 +91,15 @@ impl UpdateProducer {
}
/// Open admission: the `session/new` response has been queued on the
- /// sink, so held updates may now flow behind it.
+ /// sink, so held updates may now flow behind it. The flush holds the
+ /// lock so a concurrent publish cannot interleave.
pub async fn commit_session_new_response(&self) {
- let held = {
- let mut state = self.state.lock().await;
- if state.admission.mode != AdmissionMode::Buffering {
- return;
- }
- state.admission.mode = AdmissionMode::Open;
- std::mem::take(&mut state.admission.held)
- };
+ let mut state = self.state.lock().await;
+ if state.admission.mode != AdmissionMode::Buffering {
+ return;
+ }
+ state.admission.mode = AdmissionMode::Open;
+ let held = std::mem::take(&mut state.admission.held);
for frame in held {
self.send(frame);
}
@@ -124,8 +123,11 @@ impl UpdateProducer {
phase: PrimeAgentEventPhase,
outcome: Option<PrimeAgentOutcome>,
) -> bool {
- let frame = self.correlate(update, turn_id, phase, outcome).await;
+ // Stamp and send under one lock hold so `eventSequence` order is
+ // delivery order.
let mut state = self.state.lock().await;
+ state.event_sequence += 1;
+ let frame = self.correlate(update, turn_id, phase, outcome, state.event_sequence);
match state.admission.mode {
AdmissionMode::Buffering => {
state.admission.held.push(frame);
@@ -140,24 +142,21 @@ impl UpdateProducer {
}
/// Stamp the update with its `eventSequence` and namespace payload.
- async fn correlate(
+ fn correlate(
&self,
update: &AcpSessionUpdate,
turn_id: u64,
phase: PrimeAgentEventPhase,
outcome: Option<PrimeAgentOutcome>,
+ event_sequence: u64,
) -> Value {
let mut value = update.to_bare_value();
- let correlation = {
- let mut state = self.state.lock().await;
- state.event_sequence += 1;
- PrimeAgentSessionMeta {
- prompt_turn_id: Some(turn_id),
- event_sequence: Some(state.event_sequence),
- phase: Some(phase),
- outcome,
- ..Default::default()
- }
+ let correlation = PrimeAgentSessionMeta {
+ prompt_turn_id: Some(turn_id),
+ event_sequence: Some(event_sequence),
+ phase: Some(phase),
+ outcome,
+ ..Default::default()
};
// Merge with any namespace payload the update already carries
// (e.g. ipython rich output): correlation fields are stamped onto