Skip to content

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

Rust

restore opencode conversation routing (#3533)

ktc4c238ca025e
diff --git a/crates/pa-ai/src/providers/anthropic/mod.rs b/crates/pa-ai/src/providers/anthropic/mod.rs
index ba705bc88a..ffbfd03fdb 100644
--- a/crates/pa-ai/src/providers/anthropic/mod.rs
+++ b/crates/pa-ai/src/providers/anthropic/mod.rs
@@ -365,7 +365,7 @@ pub(crate) fn build_request_headers(
.collect()
});
- let mut default_headers = match model.provider.as_str() {
+ let default_headers = match model.provider.as_str() {
"cloudflare-ai-gateway" => {
let mut headers = Map::new();
headers.insert("accept".into(), json!("application/json"));
@@ -425,14 +425,8 @@ pub(crate) fn build_request_headers(
}
};
- // withOpenCodeHeaders: session header for opencode providers.
- if model.provider == "opencode" || model.provider == "opencode-go" {
- if let Some(session_id) = session_id {
- default_headers.insert("session_id".into(), json!(session_id));
- }
- }
-
let mut pairs = headers_to_pairs(&default_headers);
+ crate::providers::opencode_headers::apply(&mut pairs, &model.provider, session_id);
// The Anthropic SDK always sends the API version; mirror it.
pairs.insert(0, ("anthropic-version".into(), "2023-06-01".into()));
if model.provider == "cloudflare-ai-gateway" || model.provider == "github-copilot" || is_oauth {
diff --git a/crates/pa-ai/src/providers/google.rs b/crates/pa-ai/src/providers/google.rs
index 4f96fe3493..12098b8bce 100644
--- a/crates/pa-ai/src/providers/google.rs
+++ b/crates/pa-ai/src/providers/google.rs
@@ -269,11 +269,11 @@ async fn run_stream(
headers.push((name.clone(), value.clone()));
}
}
- if model.provider == "opencode" || model.provider == "opencode-go" {
- if let Some(session_id) = &options.base.session_id {
- headers.push(("session_id".into(), session_id.clone()));
- }
- }
+ crate::providers::opencode_headers::apply(
+ &mut headers,
+ &model.provider,
+ options.base.session_id.as_deref(),
+ );
headers.push(("x-goog-api-key".into(), api_key));
let mut response: HttpResponse = send(RequestOptions {
diff --git a/crates/pa-ai/src/providers/mod.rs b/crates/pa-ai/src/providers/mod.rs
index bf92f4f716..be878fa57b 100644
--- a/crates/pa-ai/src/providers/mod.rs
+++ b/crates/pa-ai/src/providers/mod.rs
@@ -15,5 +15,6 @@ pub mod openai_responses;
pub mod openai_responses_hooks;
pub mod openai_responses_shared;
pub mod openai_responses_stream;
+mod opencode_headers;
pub mod simple_options;
pub mod transform_messages;
diff --git a/crates/pa-ai/src/providers/openai_completions/params.rs b/crates/pa-ai/src/providers/openai_completions/params.rs
index 8ea4a7c178..c93b85c40c 100644
--- a/crates/pa-ai/src/providers/openai_completions/params.rs
+++ b/crates/pa-ai/src/providers/openai_completions/params.rs
@@ -351,7 +351,7 @@ pub(crate) fn build_headers(
}
}
- let _ = conversation_id;
+ crate::providers::opencode_headers::apply(&mut headers, &model.provider, conversation_id);
headers
}
diff --git a/crates/pa-ai/src/providers/openai_responses.rs b/crates/pa-ai/src/providers/openai_responses.rs
index 14a14e0c48..65809b8255 100644
--- a/crates/pa-ai/src/providers/openai_responses.rs
+++ b/crates/pa-ai/src/providers/openai_responses.rs
@@ -186,6 +186,11 @@ fn build_headers(
headers.push((name.clone(), value.clone()));
}
}
+ crate::providers::opencode_headers::apply(
+ &mut headers,
+ &model.provider,
+ options.base.session_id.as_deref(),
+ );
headers
}
diff --git a/crates/pa-ai/src/providers/opencode_headers.rs b/crates/pa-ai/src/providers/opencode_headers.rs
new file mode 100644
index 0000000000..a4a7001307
--- /dev/null
+++ b/crates/pa-ai/src/providers/opencode_headers.rs
@@ -0,0 +1,22 @@
+//! `OpenCode` routing identity is conversation-scoped, independently of prompt caching.
+
+pub(super) fn apply(headers: &mut Vec<(String, String)>, provider: &str, session_id: Option<&str>) {
+ if !matches!(provider, "opencode" | "opencode-go") {
+ return;
+ }
+ // TS `withOpenCodeHeaders`: a missing id is skipped; explicit caller headers win.
+ for (name, value) in [
+ ("User-Agent", Some("prime-agent")),
+ ("x-opencode-session", session_id),
+ ] {
+ let Some(value) = value else {
+ continue;
+ };
+ if !headers
+ .iter()
+ .any(|(existing, _)| existing.eq_ignore_ascii_case(name))
+ {
+ headers.push((name.to_string(), value.to_string()));
+ }
+ }
+}
diff --git a/crates/pa-ai/tests/opencode_session.rs b/crates/pa-ai/tests/opencode_session.rs
new file mode 100644
index 0000000000..99f70f38be
--- /dev/null
+++ b/crates/pa-ai/tests/opencode_session.rs
@@ -0,0 +1,123 @@
+use pa_ai::types::{CacheRetention, SimpleStreamOptions, StreamOptions};
+use pa_types::ai::{Context, Model};
+use serde_json::json;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+async fn capture(
+ api: &str,
+ provider: &str,
+ id: &str,
+ headers: Option<std::collections::HashMap<String, String>>,
+) -> Vec<(String, String)> {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut request = Vec::new();
+ let mut buf = [0; 4096];
+ while !request.windows(4).any(|b| b == b"\r\n\r\n") {
+ let count = socket.read(&mut buf).await.unwrap();
+ assert!(count > 0);
+ request.extend_from_slice(&buf[..count]);
+ }
+ socket
+ .write_all(
+ b"HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
+ )
+ .await
+ .unwrap();
+ String::from_utf8(request)
+ .unwrap()
+ .split("\r\n\r\n")
+ .next()
+ .unwrap()
+ .lines()
+ .skip(1)
+ .filter_map(|line| line.split_once(':'))
+ .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string()))
+ .collect::<Vec<_>>()
+ });
+ let model: Model = serde_json::from_value(json!({
+ "id":"test-model", "name":"Test", "provider":provider, "api":api,
+ "baseUrl":format!("http://{address}"), "reasoning":false, "input":["text"],
+ "contextWindow":10000, "maxTokens":100,
+ "cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0}
+ }))
+ .unwrap();
+ let options = SimpleStreamOptions::from_base(StreamOptions {
+ api_key: Some("synthetic-only".into()),
+ session_id: Some(id.into()),
+ cache_retention: Some(CacheRetention::None),
+ timeout_ms: Some(5_000),
+ headers,
+ ..Default::default()
+ });
+ let context = Context {
+ system_prompt: None,
+ messages: vec![],
+ tools: None,
+ };
+ let _ = pa_ai::complete_simple(&model, &context, Some(options))
+ .await
+ .unwrap();
+ tokio::time::timeout(std::time::Duration::from_secs(10), server)
+ .await
+ .unwrap()
+ .unwrap()
+}
+
+#[tokio::test]
+async fn opencode_session_identity_reaches_every_transport_without_cache_retention() {
+ for api in [
+ "openai-completions",
+ "openai-responses",
+ "anthropic-messages",
+ "google-generative-ai",
+ ] {
+ let headers = capture(api, "opencode-go", "conversation", None).await;
+ assert_eq!(
+ headers
+ .iter()
+ .filter(|(name, _)| name == "x-opencode-session")
+ .map(|(_, value)| value.as_str())
+ .collect::<Vec<_>>(),
+ vec!["conversation"],
+ "{api}"
+ );
+ assert!(
+ headers.contains(&("user-agent".into(), "prime-agent".into())),
+ "{api}: {headers:?}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn opencode_session_preserves_case_insensitive_explicit_overrides() {
+ for api in [
+ "openai-completions",
+ "openai-responses",
+ "anthropic-messages",
+ "google-generative-ai",
+ ] {
+ let explicit = std::collections::HashMap::from([
+ ("X-OpenCode-Session".into(), "explicit".into()),
+ ("User-Agent".into(), "custom-client".into()),
+ ]);
+ let headers = capture(api, "opencode-go", "conversation", Some(explicit)).await;
+ assert_eq!(
+ headers
+ .iter()
+ .filter(|(name, _)| name == "x-opencode-session")
+ .map(|(_, value)| value.as_str())
+ .collect::<Vec<_>>(),
+ vec!["explicit"]
+ );
+ assert!(headers.contains(&("user-agent".into(), "custom-client".into())));
+ }
+}
+
+#[tokio::test]
+async fn unrelated_gateway_does_not_receive_opencode_identity() {
+ let headers = capture("openai-completions", "custom-gateway", "conversation", None).await;
+ assert!(headers.iter().all(|(name, _)| name != "x-opencode-session"));
+}
diff --git a/crates/pa-core/src/session_engine/branch_summarization.rs b/crates/pa-core/src/session_engine/branch_summarization.rs
index 94c9d36b10..b0648064d8 100644
--- a/crates/pa-core/src/session_engine/branch_summarization.rs
+++ b/crates/pa-core/src/session_engine/branch_summarization.rs
@@ -300,6 +300,9 @@ pub struct GenerateBranchSummaryOptions<'a> {
/// When present, the summary call resolves its model through the
/// `auxiliaryModel` setting with a context-window fit check.
pub auxiliary: Option<&'a super::auxiliary_model::AuxiliaryModelContext>,
+ /// The owning conversation's id (TS `branch-summarization.ts` passes `sessionId`), so
+ /// providers that route by conversation (opencode's `x-opencode-session`) accept the call.
+ pub session_id: Option<&'a str>,
}
/// The default reserve budget.
@@ -357,6 +360,7 @@ pub async fn generate_branch_summary(
replace_instructions,
reserve_tokens,
auxiliary,
+ session_id,
} = options;
// The branch summary runs with its own prompt prefix, so on the session model it
// re-reads the whole branch — route it to the auxiliary model when its known window fits.
@@ -456,6 +460,10 @@ pub async fn generate_branch_summary(
pa_ai::types::SimpleStreamOptions::from_base(pa_ai::types::StreamOptions {
max_tokens: Some(BRANCH_SUMMARY_MAX_TOKENS),
api_key,
+ session_id: session_id.map(str::to_string),
+ // One-off prompts ride SSE: they keep the conversation id (cache key, opencode routing)
+ // but never take or replace the session's Codex WebSocket and its continuation.
+ transport: Some(pa_ai::types::Transport::Sse),
headers: summary_headers.map(|headers| headers.into_iter().collect()),
..Default::default()
});
@@ -698,6 +706,7 @@ mod tests {
replace_instructions: false,
reserve_tokens: DEFAULT_BRANCH_RESERVE_TOKENS,
auxiliary: None,
+ session_id: None,
},
)
.await;
@@ -730,6 +739,7 @@ mod tests {
replace_instructions: false,
reserve_tokens: DEFAULT_BRANCH_RESERVE_TOKENS,
auxiliary: None,
+ session_id: None,
},
)
.await;
@@ -766,16 +776,23 @@ mod tests {
cwd: tmp.path().to_path_buf(),
agent_dir: tmp.path().to_path_buf(),
};
- let seen_models: std::sync::Arc<std::sync::Mutex<Vec<String>>> =
- std::sync::Arc::default();
+ let seen_models =
+ std::sync::Arc::new(std::sync::Mutex::new(
+ Vec::<(String, Option<String>, bool)>::new(),
+ ));
let recorder = seen_models.clone();
registration.set_responses(vec![pa_ai::faux::FauxResponseStep::Factory(
std::sync::Arc::new(
move |_context: &pa_types::ai::Context,
- _options: Option<&pa_ai::types::StreamOptions>,
+ options: Option<&pa_ai::types::StreamOptions>,
_call: u64,
model: &pa_types::ai::Model| {
- recorder.lock().unwrap().push(model.id.clone());
+ recorder.lock().unwrap().push((
+ model.id.clone(),
+ options.and_then(|options| options.session_id.clone()),
+ options.and_then(|options| options.transport)
+ == Some(pa_ai::types::Transport::Sse),
+ ));
Ok(pa_ai::faux::faux_assistant_text_message(
"## Goal\nexplore the tree",
pa_ai::faux::FauxAssistantMessageOptions::default(),
@@ -793,12 +810,17 @@ mod tests {
replace_instructions: false,
reserve_tokens: DEFAULT_BRANCH_RESERVE_TOKENS,
auxiliary: Some(&aux),
+ session_id: Some("conversation"),
},
)
.await;
assert!(result.error.is_none(), "error: {:?}", result.error);
assert!(result.summary.is_some());
- assert_eq!(seen_models.lock().unwrap().as_slice(), ["faux-1"]);
+ // The routed call still carries the owning conversation's id.
+ assert_eq!(
+ seen_models.lock().unwrap().as_slice(),
+ [("faux-1".to_string(), Some("conversation".to_string()), true)]
+ );
registration.unregister();
}
}
diff --git a/crates/pa-core/src/session_engine/compact_session.rs b/crates/pa-core/src/session_engine/compact_session.rs
index 1c80607fff..0133767edb 100644
--- a/crates/pa-core/src/session_engine/compact_session.rs
+++ b/crates/pa-core/src/session_engine/compact_session.rs
@@ -126,6 +126,7 @@ pub enum CompactOutcome {
}
pub(crate) struct CompactionAttempt {
+ session_id: String,
/// The session leaf at prepare: the commit is valid while the active
/// branch still grows through it with no compaction between.
prefix_leaf: Option<String>,
@@ -210,6 +211,7 @@ pub(crate) fn prepare_attempt(
let details: CompactionDetails =
details_for(&file_op_messages, &entries, prev_compaction_index);
Ok(CompactionAttempt {
+ session_id: session.get_session_id().to_string(),
prefix_leaf,
cut,
previous_summary,
@@ -243,6 +245,7 @@ async fn summary_call_with_retry(
compaction: Option<&super::semantic_edges::SemanticCompaction>,
summary_headers: Option<std::collections::BTreeMap<String, String>>,
model: &pa_types::ai::Model,
+ session_id: &str,
api_key: Option<String>,
max_tokens: u64,
mut request: Vec<AgentMessage>,
@@ -253,6 +256,7 @@ async fn summary_call_with_retry(
super::semantic_edges::summary_slice_call(compaction, summary_headers.clone(), |headers| {
complete_summary_call(
model,
+ session_id,
api_key.clone(),
headers,
max_tokens,
@@ -278,7 +282,9 @@ async fn summary_call_with_retry(
}
}
let retry = super::semantic_edges::summary_slice_call(compaction, summary_headers, |headers| {
- complete_summary_call(model, api_key, headers, max_tokens, request, None, failure)
+ complete_summary_call(
+ model, session_id, api_key, headers, max_tokens, request, None, failure,
+ )
})
.await?;
// Both attempts are wire calls, so both bill: the slice's usage is their sum.
@@ -396,6 +402,7 @@ pub(crate) async fn summarize_attempt(
attempt.semantic_compaction.as_ref(),
summary_headers.clone(),
&model,
+ &attempt.session_id,
api_key.clone(),
history_max_tokens,
request,
@@ -419,6 +426,7 @@ pub(crate) async fn summarize_attempt(
attempt.semantic_compaction.as_ref(),
summary_headers.clone(),
&model,
+ &attempt.session_id,
api_key.clone(),
turn_prefix_max_tokens,
request,
diff --git a/crates/pa-core/src/session_engine/compact_session/tests/split_turn.rs b/crates/pa-core/src/session_engine/compact_session/tests/split_turn.rs
index f8d57a012e..f0326be528 100644
--- a/crates/pa-core/src/session_engine/compact_session/tests/split_turn.rs
+++ b/crates/pa-core/src/session_engine/compact_session/tests/split_turn.rs
@@ -75,13 +75,27 @@ async fn split_turn_compaction_runs_two_summarizer_calls_and_merges_the_turn_con
// Each factory call records its request, so both wire calls are
// captured regardless of issue order.
let seen: std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>> = std::sync::Arc::default();
+ let expected_session_id = session.get_session_id().to_string();
let make_step = |response: &'static str| {
let seen = seen.clone();
+ let expected_session_id = expected_session_id.clone();
pa_ai::faux::FauxResponseStep::Factory(std::sync::Arc::new(
move |context: &pa_types::ai::Context,
- _options: Option<&pa_ai::types::StreamOptions>,
+ options: Option<&pa_ai::types::StreamOptions>,
_call: u64,
_model: &pa_types::ai::Model| {
+ let actual = options.and_then(|o| o.session_id.as_deref());
+ let transport = options.and_then(|o| o.transport);
+ if transport != Some(pa_ai::types::Transport::Sse) {
+ return Err(format!(
+ "expected the SSE transport, received {transport:?}"
+ ));
+ }
+ if actual != Some(expected_session_id.as_str()) {
+ return Err(format!(
+ "expected conversation {expected_session_id}, received {actual:?}"
+ ));
+ }
let text = match &context.messages[0] {
pa_types::ai::Message::User(user) => user.content.text(),
_ => panic!("expected a user request"),
@@ -148,30 +162,55 @@ async fn split_turn_compaction_runs_two_summarizer_calls_and_merges_the_turn_con
);
assert_eq!(run.result.first_kept_entry_id, kept_id);
// The usage is the sum of the two wire calls (faux estimates each
- // call as ceil(chars/4) over the serialized prompt plus response).
+ // call as ceil(chars/4), with a shared conversation prompt cache).
let est = |text: &str| (text.chars().count() as f64 / 4.0).ceil() as u64;
- let usage_of = |request: &str, response: &str| {
- let prompt = format!(
- "system:{}\n\nuser:{request}",
- super::super::compaction_utils::SUMMARIZATION_SYSTEM_PROMPT
+ let expected_for_order = |first: (&str, &str), second: (&str, &str)| {
+ let mut previous_prompt = String::new();
+ let mut usage_of = |request: &str, response: &str| {
+ let prompt = format!(
+ "system:{}\n\nuser:{request}",
+ super::super::compaction_utils::SUMMARIZATION_SYSTEM_PROMPT
+ );
+ let shared_chars = previous_prompt
+ .chars()
+ .zip(prompt.chars())
+ .take_while(|(a, b)| a == b)
+ .count();
+ let cache_read = est(&prompt.chars().take(shared_chars).collect::<String>());
+ let cache_write = est(&prompt.chars().skip(shared_chars).collect::<String>());
+ let input = est(&prompt) - cache_read;
+ previous_prompt = prompt;
+ let output = est(response);
+ pa_types::ai::Usage {
+ input,
+ output,
+ cache_read,
+ cache_write,
+ total_tokens: input + output + cache_read + cache_write,
+ cost: pa_types::ai::UsageCost::default(),
+ }
+ };
+ let mut expected = usage_of(first.0, first.1);
+ super::super::compaction_exec::add_assistant_usage(
+ &mut expected,
+ &usage_of(second.0, second.1),
);
- let input = est(&prompt);
- let output = est(response);
- pa_types::ai::Usage {
- input,
- output,
- cache_read: 0,
- cache_write: 0,
- total_tokens: input + output,
- cost: pa_types::ai::UsageCost::default(),
- }
+ expected
};
- let mut expected = usage_of(history_request, history_response);
- super::super::compaction_exec::add_assistant_usage(
- &mut expected,
- &usage_of(prefix_request, prefix_response),
- );
- assert_eq!(run.result.usage, Some(expected));
+ // Both summary calls run concurrently, so either can populate the cache first.
+ let expected = [
+ expected_for_order(
+ (history_request, history_response),
+ (prefix_request, prefix_response),
+ ),
+ expected_for_order(
+ (prefix_request, prefix_response),
+ (history_request, history_response),
+ ),
+ ];
+ assert!(expected
+ .iter()
+ .any(|usage| run.result.usage.as_ref() == Some(usage)));
assert_eq!(run.entry.usage, run.result.usage);
assert_eq!(run.entry.summary, run.result.summary);
let persisted = session
@@ -475,8 +514,8 @@ async fn split_turn_without_history_makes_only_the_prefix_call() {
input,
output,
cache_read: 0,
- cache_write: 0,
- total_tokens: input + output,
+ cache_write: input,
+ total_tokens: input * 2 + output,
cost: pa_types::ai::UsageCost::default(),
})
);
diff --git a/crates/pa-core/src/session_engine/compaction_arms.rs b/crates/pa-core/src/session_engine/compaction_arms.rs
index b1bce19367..dfde1fb261 100644
--- a/crates/pa-core/src/session_engine/compaction_arms.rs
+++ b/crates/pa-core/src/session_engine/compaction_arms.rs
@@ -401,7 +401,7 @@ impl AgentSession {
options,
source,
model,
- refine::default_refiner_call(api_key),
+ refine::default_refiner_call(api_key, self.session_id().await),
global_harness_dir,
)
.await
diff --git a/crates/pa-core/src/session_engine/compaction_exec.rs b/crates/pa-core/src/session_engine/compaction_exec.rs
index fe89bd46a6..459b3c86ce 100644
--- a/crates/pa-core/src/session_engine/compaction_exec.rs
+++ b/crates/pa-core/src/session_engine/compaction_exec.rs
@@ -139,8 +139,10 @@ pub type SummaryDeltaSink = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
/// Returns an error when the summarizer wire call fails, when its reply
/// stops with an error, a tool call, or an abort, or when its joined text
/// is empty (all labeled with `failure`).
+#[allow(clippy::too_many_arguments)] // Each summary carries its owning conversation and request metadata.
pub async fn complete_summary_call(
model: &pa_types::ai::Model,
+ session_id: &str,
api_key: Option<String>,
headers: Option<std::collections::BTreeMap<String, String>>,
max_tokens: u64,
@@ -169,6 +171,10 @@ pub async fn complete_summary_call(
pa_ai::types::SimpleStreamOptions::from_base(pa_ai::types::StreamOptions {
signal: Some(cancel),
max_tokens: Some(max_tokens),
+ session_id: Some(session_id.to_string()),
+ // One-off prompts ride SSE: they keep the conversation id (cache key, opencode routing)
+ // but never take or replace the session's Codex WebSocket and its continuation.
+ transport: Some(pa_ai::types::Transport::Sse),
api_key,
headers: headers.map(|headers| headers.into_iter().collect()),
..Default::default()
diff --git a/crates/pa-core/src/session_engine/compaction_outcome_tests.rs b/crates/pa-core/src/session_engine/compaction_outcome_tests.rs
index 734c190af3..2c05434ade 100644
--- a/crates/pa-core/src/session_engine/compaction_outcome_tests.rs
+++ b/crates/pa-core/src/session_engine/compaction_outcome_tests.rs
@@ -604,3 +604,49 @@ async fn refine_keeps_the_retry_drop_instead_of_resurrecting_the_error_row() {
"the reference rebuild resurrects the dropped row; the push does not"
);
}
+
+#[tokio::test]
+async fn refinement_and_auto_review_preserve_conversation_identity() {
+ let (session, tmp) = refine_test_session().await;
+ let expected = session.session_id().await;
+ let registration =
+ pa_ai::faux::register_faux_provider(pa_ai::faux::RegisterFauxProviderOptions::default());
+ let observed = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let step = |text: &'static str| {
+ let observed = Arc::clone(&observed);
+ pa_ai::faux::FauxResponseStep::Factory(Arc::new(move |_, options, _, _| {
+ observed.lock().unwrap().push((
+ options.and_then(|o| o.session_id.clone()),
+ options.and_then(|o| o.transport),
+ ));
+ Ok(pa_ai::faux::faux_assistant_text_message(
+ text,
+ pa_ai::faux::FauxAssistantMessageOptions::default(),
+ ))
+ }))
+ };
+ registration.set_responses(vec![
+ step(EMPTY_PLAN),
+ step(r#"{"shouldRefine":false,"rationale":"fixture"}"#),
+ ]);
+ let model = registration.get_model();
+ let global = tmp.path().join("harness");
+ session
+ .refine(
+ &refine::RefineOptions::default(),
+ refine::RefinementSource::User,
+ &model,
+ None,
+ global.clone(),
+ )
+ .await
+ .unwrap();
+ session
+ .review_compact_auto_refine(&model, None, &global, 5, 0)
+ .await
+ .unwrap();
+ assert_eq!(
+ *observed.lock().unwrap(),
+ vec![(Some(expected), Some(pa_ai::types::Transport::Sse)); 2]
+ );
+}
diff --git a/crates/pa-core/src/session_engine/refine.rs b/crates/pa-core/src/session_engine/refine.rs
index 902bba6adf..e4795db6c5 100644
--- a/crates/pa-core/src/session_engine/refine.rs
+++ b/crates/pa-core/src/session_engine/refine.rs
@@ -536,7 +536,7 @@ impl AgentSession {
reason: AUTO_REFINE_COMPACT_REASON.to_string(),
turns_since_last_review,
},
- default_refiner_call(api_key.clone()),
+ default_refiner_call(api_key.clone(), self.session_id().await),
)
.await?;
if !review.should_refine {
@@ -612,7 +612,10 @@ impl AgentSession {
/// The default model seam over pa-ai completion.
#[must_use]
-pub fn default_refiner_call(api_key: Option<String>) -> crate::refinement::executor::RefinerFn {
+pub fn default_refiner_call(
+ api_key: Option<String>,
+ session_id: String,
+) -> crate::refinement::executor::RefinerFn {
Box::new(move |model, system_prompt, prompt| {
let api_key = api_key;
Box::pin(async move {
@@ -628,6 +631,11 @@ pub fn default_refiner_call(api_key: Option<String>) -> crate::refinement::execu
let mut stream_options =
pa_ai::types::SimpleStreamOptions::from_base(pa_ai::types::StreamOptions {
api_key,
+ session_id: Some(session_id),
+ // One-off prompts ride SSE: they keep the conversation id (cache key,
+ // opencode routing) but never take or replace the session's Codex
+ // WebSocket and its continuation.
+ transport: Some(pa_ai::types::Transport::Sse),
..Default::default()
});
stream_options.reasoning = pa_types::ai::minimum_reasoning(&model);
diff --git a/crates/pa-core/tests/compaction_transport.rs b/crates/pa-core/tests/compaction_transport.rs
index 9efa4aac07..9368af539e 100644
--- a/crates/pa-core/tests/compaction_transport.rs
+++ b/crates/pa-core/tests/compaction_transport.rs
@@ -97,6 +97,7 @@ async fn summary_respects_mandatory_thinking() {
let (model, request, server) = mock_summary(Reply::Complete).await;
let summary = complete_summary_call(
&model,
+ "synthetic-session",
Some("synthetic-key".into()),
None,
512,
@@ -124,6 +125,7 @@ async fn dropped_summary_closes_hung_transport() {
let task = tokio::spawn(async move {
complete_summary_call(
&model,
+ "synthetic-session",
Some("synthetic-key".into()),
None,
512,
@@ -167,6 +169,7 @@ async fn summary_preserves_unspecified_reasoning_when_off_is_supported() {
let model = serde_json::from_value(wire).unwrap();
complete_summary_call(
&model,
+ "synthetic-session",
Some("synthetic-key".into()),
None,
512,
@@ -206,6 +209,7 @@ async fn branch_summary_respects_mandatory_thinking() {
replace_instructions: false,
reserve_tokens: DEFAULT_BRANCH_RESERVE_TOKENS,
auxiliary: None,
+ session_id: None,
},
)
.await;
@@ -222,10 +226,13 @@ async fn branch_summary_respects_mandatory_thinking() {
#[tokio::test]
async fn refiner_call_respects_mandatory_thinking() {
let (model, request, server) = mock_summary(Reply::Complete).await;
- let reply =
- default_refiner_call(Some("synthetic-key".into()))(model, "system", "prompt".into())
- .await
- .unwrap();
+ let reply = default_refiner_call(Some("synthetic-key".into()), "synthetic-session".into())(
+ model,
+ "system",
+ "prompt".into(),
+ )
+ .await
+ .unwrap();
assert!(matches!(
reply.content.as_slice(),
[pa_types::ai::AssistantContentBlock::Text(text)] if text.text == "summary"
diff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs
index be01ca6db5..50e0a30b78 100644
--- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs
+++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs
@@ -731,6 +731,7 @@ impl SessionEngine for AgentSessionEngine {
let entries = request.entries;
let custom_instructions = request.custom_instructions;
let replace_instructions = request.replace_instructions;
+ let session_id = request.session_id;
// TS #2411: the branch summary resolves its model through the
// `auxiliaryModel` setting, keeping its one-off prompt off the
// prompt-cache prefix.
@@ -748,6 +749,7 @@ impl SessionEngine for AgentSessionEngine {
replace_instructions,
reserve_tokens,
auxiliary: Some(&auxiliary),
+ session_id: Some(&session_id),
},
)
.await
diff --git a/crates/pa-daemon/src/agent_engine/tests/compaction.rs b/crates/pa-daemon/src/agent_engine/tests/compaction.rs
index a4db41d9b0..c0361fe877 100644
--- a/crates/pa-daemon/src/agent_engine/tests/compaction.rs
+++ b/crates/pa-daemon/src/agent_engine/tests/compaction.rs
@@ -1226,11 +1226,15 @@ fn low_custom_percentage_compacts_real_history_once_and_then_makes_progress() {
}),
16_384,
);
+ // The faux provider's conversation-scoped prompt cache reports a rewritten
+ // prompt as both input and cache-write tokens, so the first turn after a
+ // compaction reads about twice the retained history. Keep that doubled
+ // reading below the 42_769 retention floor (10_000 + 2 * 16_384 + 1).
std::fs::write(
dir.path().join("agent/settings.json"),
serde_json::json!({"compaction": {
"enabled": true, "thresholdPercent": 5,
- "reserveTokens": 16_384, "keepRecentTokens": 20_000
+ "reserveTokens": 16_384, "keepRecentTokens": 10_000
}})
.to_string(),
)
@@ -1303,7 +1307,7 @@ fn low_custom_percentage_compacts_real_history_once_and_then_makes_progress() {
pa_core::session_engine::compaction::CompactionSettings {
threshold_percent: 75.0,
reserve_tokens: 16_384,
- keep_recent_tokens: 20_000,
+ keep_recent_tokens: 10_000,
..Default::default()
}
);
diff --git a/crates/pa-daemon/src/agent_engine/tests/session.rs b/crates/pa-daemon/src/agent_engine/tests/session.rs
index 4d451b7967..ed7112fcd7 100644
--- a/crates/pa-daemon/src/agent_engine/tests/session.rs
+++ b/crates/pa-daemon/src/agent_engine/tests/session.rs
@@ -546,3 +546,88 @@ fn a_bare_invocation_of_a_close_tagged_body_still_floors() {
);
assert_eq!(assistant_texts(&events), vec!["ok"]);
}
+
+/// The branch summary call carries the request's durable session id even
+/// when no core session is built (a `/tree` summary right after a resume
+/// races the create's background build). The faux registry is
+/// process-global, so the test holds `FAUX_TEST_LOCK`; the recorder
+/// registration replaces the script's provider for the summary call.
+#[test]
+fn an_unbuilt_engine_branch_summary_carries_the_request_session_id() {
+ use crate::engine::SessionEngine as _;
+ let _faux = FAUX_TEST_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let dir = tempfile::TempDir::new().unwrap();
+ let engine = AgentSessionEngine::new(AgentEngineConfig {
+ cwd: dir.path().to_path_buf(),
+ agent_dir: dir.path().join("agent"),
+ provider: None,
+ model: None,
+ api_key: None,
+ thinking: None,
+ session_dir: None,
+ session_file: None,
+ faux_script: Some(json!({ "engine": "faux", "responses": [{ "text": "ok" }] }).to_string()),
+ supervisor_link: None,
+ telemetry_disabled: Some(true),
+ cron_store: None,
+ queued_steering_probe: None,
+ })
+ .unwrap();
+ engine.resolve_model().expect("faux model");
+ assert!(engine.session.blocking_lock().is_none(), "no session built");
+ let recorder = pa_ai::faux::register_faux_provider(pa_ai::faux::RegisterFauxProviderOptions {
+ api: Some("faux".to_string()),
+ provider: Some("faux".to_string()),
+ ..Default::default()
+ });
+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let sink = std::sync::Arc::clone(&seen);
+ recorder.set_responses(vec![pa_ai::faux::FauxResponseStep::Factory(
+ std::sync::Arc::new(
+ move |_context: &pa_types::ai::Context,
+ options: Option<&pa_ai::types::StreamOptions>,
+ _call: u64,
+ _model: &pa_types::ai::Model| {
+ sink.lock()
+ .unwrap()
+ .push(options.and_then(|options| options.session_id.clone()));
+ Ok(pa_ai::faux::faux_assistant_text_message(
+ "## Goal\nexplore the tree",
+ pa_ai::faux::FauxAssistantMessageOptions::default(),
+ ))
+ },
+ ),
+ )]);
+ let outcome = engine.run_branch_summary(
+ crate::engine::BranchSummaryRequest {
+ entries: vec![pa_types::session::FileEntry::Message {
+ message: pa_types::session::AgentMessage::User(pa_types::ai::UserMessage {
+ content: pa_types::ai::UserContent::Text("explore the widget".to_string()),
+ timestamp: 0,
+ rest: Map::default(),
+ }),
+ base: pa_types::session::EntryBase {
+ id: Some("e0".to_string()),
+ parent_id: None,
+ timestamp: Some("2024-01-01T00:00:00.000Z".to_string()),
+ rest: Map::default(),
+ },
+ }],
+ custom_instructions: None,
+ replace_instructions: false,
+ session_id: "durable-session".to_string(),
+ },
+ &pa_agent::abort::AbortController::new().signal(),
+ );
+ recorder.unregister();
+ assert!(
+ matches!(
+ outcome,
+ crate::engine::BranchSummaryOutcome::Complete { .. }
+ ),
+ "{outcome:?}"
+ );
+ assert_eq!(*seen.lock().unwrap(), [Some("durable-session".to_string())]);
+}
diff --git a/crates/pa-daemon/src/branch_navigation.rs b/crates/pa-daemon/src/branch_navigation.rs
index 18e770aca1..fa2c87f545 100644
--- a/crates/pa-daemon/src/branch_navigation.rs
+++ b/crates/pa-daemon/src/branch_navigation.rs
@@ -147,7 +147,7 @@ impl TreeNavigation {
.map(str::to_string);
// Snapshot the tree state under one lock pass; the model call below runs without it.
- let (target, old_leaf, entries) = {
+ let (target, old_leaf, entries, session_id) = {
let core = self.core.lock().unwrap();
let Some(store) = core.store.as_ref() else {
return response_failure(
@@ -167,7 +167,7 @@ impl TreeNavigation {
};
let old_leaf = store.leaf_id().map(str::to_string);
let entries = store.entries().to_vec();
- (target, old_leaf, entries)
+ (target, old_leaf, entries, store.session_id().to_string())
};
// No-op when already at the target (TS checks before pausing work).
if Some(target_id) == old_leaf.as_deref() {
@@ -212,6 +212,7 @@ impl TreeNavigation {
entries: collected.entries,
custom_instructions,
replace_instructions,
+ session_id,
},
&signal,
)
diff --git a/crates/pa-daemon/src/engine/wire.rs b/crates/pa-daemon/src/engine/wire.rs
index fe3535c9f2..0a72edc625 100644
--- a/crates/pa-daemon/src/engine/wire.rs
+++ b/crates/pa-daemon/src/engine/wire.rs
@@ -351,6 +351,9 @@ pub struct BranchSummaryRequest {
pub custom_instructions: Option<String>,
/// Replace the default prompt instead of appending the custom focus.
pub replace_instructions: bool,
+ /// The session's durable id: the summary call carries it like the main requests
+ /// (opencode rejects a request without `x-opencode-session`).
+ pub session_id: String,
}
/// One completed branch summary: the final summary text, the summarizer