Skip to content

Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.

fix(gateway): recognize native Claude Code, Pi, DSH and OpenCode sessions (#97)

澄潭f29585cbb5da
diff --git a/crates/gateway/README.md b/crates/gateway/README.md
index 7b62f883..505a794f 100644
--- a/crates/gateway/README.md
+++ b/crates/gateway/README.md
@@ -24,6 +24,50 @@ renderers omit foreign reasoning without inventing signatures. The
[production protocol matrix](../../tools/e2e-harness/tests/p0_gateway_protocol/production_matrix.rs)
covers the listener boundary, including tool continuation.
+## Native session correlation
+
+[context_hold/identity.rs](src/context_hold/identity.rs) resolves one identity for
+ContextHold, decision history and observation before request content is externalized.
+Verified Worker tasks take precedence. Ordinary clients supply these native fields:
+
+| Client | Accepted native identity |
+| --- | --- |
+| Claude Code | `X-Claude-Code-Session-Id`; Messages also retains the JSON session inside `metadata.user_id` |
+| Codex | `thread-id` / `session-id`, with matching Responses `client_metadata` dimensions |
+| Qoder | `session-id`, retaining its existing generic session namespace |
+| Pi | pi-ai session headers scoped by `pi (...)` User-Agent |
+| DeepSeek Harness | `x-deepseek-harness-session-id`; pi-ai session headers scoped by `deepseek-harness/<version>` User-Agent |
+| OpenCode | `x-opencode-session-id`, including custom providers and all three supported ingress protocols |
+
+OpenCode's [released request producer](https://github.com/anomalyco/opencode/blob/733b2c627e5aec39cb33cc22373bdce33053ef2c/packages/opencode/src/session/llm/request.ts)
+sends the actual session in `x-opencode-session-id`. Its
+[current cache affinity](https://github.com/anomalyco/opencode/blob/d21b0790a6c146815f28fea604e41e922f009590/packages/core/src/session/affinity.ts)
+can share a parent or fork source, so `x-opencode-session`, `x-session-affinity`
+and `X-Session-Id` are not OpenCode identity aliases and need not match that ID.
+Parent, project and request headers also do not identify the current session.
+This input support does not add OpenCode managed configuration or Worker launch.
+
+For pi-ai, Responses sends its native `sessionId` as `x-client-request-id` and
+optionally `session_id`; OpenRouter compatibility uses `x-session-id`. Messages
+can send `x-session-affinity` or `x-session-id` when native affinity is enabled.
+See the pinned [Responses transport](https://github.com/earendil-works/pi/blob/e6b9a6af5d45fd191f8e90b56176a0c41aab3199/packages/ai/src/api/openai-responses.ts)
+and [DSH adapter](https://github.com/deepseek-ai/deepseek-harness/blob/d743267388641bc76f17c45ce8b4c231aed1d32c/packages/llm/llm-pi-ai/src/adapter.ts).
+Branding limits interpretation of these fields; it is not authentication.
+Generic request IDs, prompt cache keys and other clients' affinity headers cannot
+establish a native session. A client that sends no native identity, including
+DSH's current standard pi-ai Messages configuration or disabled pi-ai caching,
+retains the existing conservative first-user inference or request scope.
+
+Recognized IDs must be nonempty, at most 128 bytes, and free of control characters.
+Duplicates, invalid values, conflicting dimensions or competing vendor families
+stay request-scoped. Coherent generic Codex dimensions retain their historical
+namespace, including Pi's Codex transport. Claude header and metadata share the
+existing Claude namespace. Session storage uses the producer's scoped HMAC;
+raw IDs are not persisted and existing observations are not rewritten.
+[p0_gateway_native_sessions.rs](../../tools/e2e-harness/tests/p0_gateway_native_sessions.rs)
+covers the real listener and observation boundary across Responses and Messages,
+plus OpenCode's native identity across Chat Completions and shared cache affinity.
+
## Decision operation
[core_runtime/classification.rs](src/core_runtime/classification.rs) owns the
diff --git a/crates/gateway/src/context_hold/identity.rs b/crates/gateway/src/context_hold/identity.rs
index 47fe0251..6cfc52ce 100644
--- a/crates/gateway/src/context_hold/identity.rs
+++ b/crates/gateway/src/context_hold/identity.rs
@@ -94,20 +94,11 @@ pub(crate) fn identity_facts(
return verified_worker_identity(run);
}
- match codex_identity(ingress, headers, request) {
+ match native_identity(ingress, headers, document, request) {
Field::Value((kind, parts)) => return reliable(kind, parts, false),
Field::Invalid => return ContextIdentityFacts::request_scoped(),
Field::Absent => {}
}
- if ingress == IngressProtocol::Messages {
- match claude_identity(document) {
- Field::Value(session_id) => {
- return reliable("claude_metadata_session", vec![session_id], false);
- }
- Field::Invalid => return ContextIdentityFacts::request_scoped(),
- Field::Absent => {}
- }
- }
let Some(first_user) = first_user_digest(request, hold_key) else {
return ContextIdentityFacts::request_scoped();
@@ -157,6 +148,120 @@ enum Field<T> {
Invalid,
}
+type NativeIdentity = (&'static str, Vec<String>);
+
+fn native_identity(
+ ingress: IngressProtocol,
+ headers: &HeaderMap,
+ document: &Value,
+ request: &ModelRequestIRV1,
+) -> Field<NativeIdentity> {
+ let claude_metadata = if ingress == IngressProtocol::Messages {
+ claude_metadata_identity(document)
+ } else {
+ Field::Absent
+ };
+ // Keep the metadata namespace so adding the native header does not split an
+ // existing Claude conversation. Conflicting/invalid claims never infer from text.
+ let claude = session_identity(
+ "claude_metadata_session",
+ merge_dimension(
+ header_value(headers, "x-claude-code-session-id"),
+ claude_metadata,
+ ),
+ );
+ let dsh = session_identity(
+ "deepseek_harness_session",
+ header_value(headers, "x-deepseek-harness-session-id"),
+ );
+ let vendor = merge_vendor_identity(claude, dsh);
+ // OpenCode emits the actual session ID even for custom providers. Its
+ // cache-affinity headers may instead identify a shared parent/fork source.
+ let vendor = merge_vendor_identity(
+ vendor,
+ session_identity(
+ "opencode_session",
+ header_value(headers, "x-opencode-session-id"),
+ ),
+ );
+ let vendor = merge_vendor_identity(vendor, pi_ai_identity(ingress, headers));
+ let generic = codex_identity(ingress, headers, request);
+ match (generic, vendor) {
+ (Field::Invalid, _) | (_, Field::Invalid) => Field::Invalid,
+ (Field::Absent, value) | (value, Field::Absent) => value,
+ (Field::Value((kind, parts)), Field::Value((_, session)))
+ if matches!(kind, "codex_session" | "codex_thread_session")
+ && parts.last() == session.first() =>
+ {
+ // Pi's Codex transport also sends session-id. Preserve all already
+ // accepted generic dimensions and their historical HMAC namespace.
+ Field::Value((kind, parts))
+ }
+ (Field::Value(_), Field::Value(_)) => Field::Invalid,
+ }
+}
+
+fn session_identity(kind: &'static str, session: Field<String>) -> Field<NativeIdentity> {
+ match session {
+ Field::Absent => Field::Absent,
+ Field::Invalid => Field::Invalid,
+ Field::Value(session) => Field::Value((kind, vec![session])),
+ }
+}
+
+fn merge_vendor_identity(
+ left: Field<NativeIdentity>,
+ right: Field<NativeIdentity>,
+) -> Field<NativeIdentity> {
+ match (left, right) {
+ (Field::Invalid, _) | (_, Field::Invalid) => Field::Invalid,
+ (Field::Absent, value) | (value, Field::Absent) => value,
+ (Field::Value(left), Field::Value(right)) if left == right => Field::Value(left),
+ (Field::Value(_), Field::Value(_)) => Field::Invalid,
+ }
+}
+
+fn pi_ai_identity(ingress: IngressProtocol, headers: &HeaderMap) -> Field<NativeIdentity> {
+ // pi-ai copies options.sessionId into these transport headers. Their names
+ // alone do not imply session semantics for arbitrary API clients. Branding
+ // is still only an Agent claim; authorization comes from the existing grant.
+ let kind = match single_header(headers, "user-agent", 1_024) {
+ Field::Value(agent) if agent.starts_with("pi (") && agent.ends_with(')') => "pi_session",
+ Field::Value(agent)
+ if agent
+ .strip_prefix("deepseek-harness/")
+ .is_some_and(|tail| !tail.is_empty() && !tail.starts_with(char::is_whitespace)) =>
+ {
+ "deepseek_harness_session"
+ }
+ Field::Invalid
+ if [
+ "x-client-request-id",
+ "session_id",
+ "x-session-id",
+ "x-session-affinity",
+ ]
+ .iter()
+ .any(|name| headers.contains_key(*name)) =>
+ {
+ return Field::Invalid;
+ }
+ Field::Absent | Field::Invalid | Field::Value(_) => return Field::Absent,
+ };
+ let session = match ingress {
+ IngressProtocol::Responses => merge_dimension(
+ header_value(headers, "x-client-request-id"),
+ header_value(headers, "session_id"),
+ ),
+ IngressProtocol::Messages => header_value(headers, "x-session-affinity"),
+ IngressProtocol::ChatCompletions => return Field::Absent,
+ };
+ session_identity(
+ kind,
+ merge_dimension(session, header_value(headers, "x-session-id")),
+ )
+}
+
fn codex_identity(
ingress: IngressProtocol,
headers: &HeaderMap,
@@ -187,6 +292,10 @@ fn codex_identity(
}
fn header_value(headers: &HeaderMap, name: &'static str) -> Field<String> {
+ single_header(headers, name, 128)
+}
+
+fn single_header(headers: &HeaderMap, name: &'static str, max_bytes: usize) -> Field<String> {
let mut values = headers.get_all(name).iter();
let Some(value) = values.next() else {
return Field::Absent;
@@ -197,7 +306,10 @@ fn header_value(headers: &HeaderMap, name: &'static str) -> Field<String> {
value
.to_str()
.ok()
- .and_then(valid_identity)
+ .filter(|value| {
+ !value.is_empty() && value.len() <= max_bytes && !value.chars().any(char::is_control)
+ })
+ .map(str::to_owned)
.map_or(Field::Invalid, Field::Value)
}
@@ -223,7 +335,7 @@ fn merge_dimension(header: Field<String>, body: Field<String>) -> Field<String>
}
}
-fn claude_identity(document: &Value) -> Field<String> {
+fn claude_metadata_identity(document: &Value) -> Field<String> {
let Some(metadata) = document.get("metadata") else {
return Field::Absent;
};
@@ -314,157 +426,5 @@ fn hex(value: &[u8; 32]) -> String {
}
#[cfg(test)]
-mod tests {
- use super::*;
- use crate::server::core_runtime::model_ir::{
- CanonicalMessage, MODEL_REQUEST_IR_SCHEMA, RequestedReasoningControl,
- ResponsesRequestOptionsV1, ToolChoice,
- };
-
- #[test]
- fn worker_continue_keeps_conversation_identity_without_joining_other_tasks() {
- let context = |task: &str, run: &str, native: Option<&str>| {
- crate::server::request_plan::VerifiedRunObservationContext {
- task_id: task.into(),
- run_id: run.into(),
- plan_id: "plan/one".into(),
- plan_revision: 1,
- publication_ref: "publication/one".into(),
- harness_id: "pi".into(),
- native_session_id: native.map(str::to_owned),
- parent_context_ref: None,
- continued_from_run_id: None,
- }
- };
- let initial = verified_worker_identity(&context("task/one", "run/initial", None));
- let continued =
- verified_worker_identity(&context("task/one", "run/continue", Some("native-one")));
- assert_eq!(initial.hold_identity(), continued.hold_identity());
- assert_eq!(
- initial.observation_identity(),
- continued.observation_identity()
- );
- assert_eq!(continued.correlation_provenance(), "protocol_state");
- assert_eq!(continued.session_scope(), "conversation");
- let other = verified_worker_identity(&context("task/two", "run/other", Some("native-one")));
- assert_ne!(initial.hold_identity(), other.hold_identity());
- assert_ne!(initial.observation_identity(), other.observation_identity());
- let invalid = verified_worker_identity(&context("", "run/valid", None));
- assert_eq!(invalid.session_scope(), "request_scoped");
- }
-
- fn request(text: &str) -> ModelRequestIRV1 {
- ModelRequestIRV1 {
- native_body: None,
- native_only: false,
- schema_version: MODEL_REQUEST_IR_SCHEMA.into(),
- ingress_protocol: IngressProtocol::Responses,
- served_model_id: "agent/test".into(),
- stream: false,
- instructions: Vec::new(),
- messages: vec![CanonicalMessage {
- role: MessageRole::User,
- content: vec![ContentPart::Text { text: text.into() }],
- name: None,
- }],
- tools: Vec::new(),
- tool_namespaces: Vec::new(),
- responses_tool_order: Vec::new(),
- web_search: None,
- responses_search_history: Default::default(),
- responses_annotations: Default::default(),
- responses_message_phases: Default::default(),
- responses_internal_chat_message_metadata: Default::default(),
- responses_reasoning_history: Default::default(),
- tool_choice: ToolChoice::None,
- parallel_tool_calls: false,
- requested_reasoning: RequestedReasoningControl::absent(),
- requested_max_output_tokens: None,
- provider_state: Vec::new(),
- responses_options: None,
- responses_item_ids: Default::default(),
- responses_item_statuses: Default::default(),
- }
- }
-
- #[test]
- fn codex_requires_consistent_dimensions_and_keeps_thread_with_session() {
- let mut headers = HeaderMap::new();
- headers.insert("thread-id", "thread".parse().unwrap());
- headers.insert("session-id", "session".parse().unwrap());
- let mut request = request("hello");
- request.responses_options = Some(ResponsesRequestOptionsV1 {
- store: None,
- include: None,
- prompt_cache_key: None,
- client_metadata: Some(
- [
- ("thread_id".into(), "thread".into()),
- ("session_id".into(), "session".into()),
- ]
- .into_iter()
- .collect(),
- ),
- reasoning_summary: None,
- reasoning_context: None,
- });
- match codex_identity(IngressProtocol::Responses, &headers, &request) {
- Field::Value((kind, parts)) => {
- assert_eq!(kind, "codex_thread_session");
- assert_eq!(parts, ["thread", "session"]);
- }
- Field::Absent | Field::Invalid => panic!("consistent identity was not accepted"),
- }
- request
- .responses_options
- .as_mut()
- .unwrap()
- .client_metadata
- .as_mut()
- .unwrap()
- .insert("session_id".into(), "other".into());
- assert!(matches!(
- codex_identity(IngressProtocol::Responses, &headers, &request),
- Field::Invalid
- ));
- headers.append("thread-id", "duplicate".parse().unwrap());
- assert!(matches!(
- codex_identity(IngressProtocol::Responses, &headers, &request),
- Field::Invalid
- ));
- }
-
- #[test]
- fn inferred_anchor_uses_complete_user_and_rejects_public_wrappers() {
- let key = [3; 32];
- let common = "x".repeat(4_096);
- assert_ne!(
- first_user_digest(&request(&(common.clone() + "a")), &key),
- first_user_digest(&request(&(common + "b")), &key)
- );
- for public in [
- "# AGENTS.md instructions for /tmp",
- "<environment_context>cwd</environment_context>",
- "<system-reminder>rules</system-reminder>",
- "<recommended_plugins>plugins</recommended_plugins>\n# AGENTS.md instructions for /tmp",
- "<send_user_message_question_reply>prior answer</send_user_message_question_reply>",
- " ",
- ] {
- assert!(first_user_digest(&request(public), &key).is_none());
- }
- }
-
- #[test]
- fn claude_metadata_extracts_only_bounded_json_session() {
- assert!(matches!(
- claude_identity(&serde_json::json!({
- "metadata":{"user_id":"{\"session_id\":\"claude-session\",\"device_id\":\"ignored\"}"}
- })),
- Field::Value(value) if value == "claude-session"
- ));
- assert!(matches!(
- claude_identity(&serde_json::json!({"metadata":{"user_id":"not-json"}})),
- Field::Invalid
- ));
- }
-}
+#[path = "identity_tests.rs"]
+mod tests;
diff --git a/crates/gateway/src/context_hold/identity_tests.rs b/crates/gateway/src/context_hold/identity_tests.rs
new file mode 100644
index 00000000..cb73b34d
--- /dev/null
+++ b/crates/gateway/src/context_hold/identity_tests.rs
@@ -0,0 +1,479 @@
+use super::*;
+use crate::server::core_runtime::model_ir::{
+ CanonicalMessage, MODEL_REQUEST_IR_SCHEMA, RequestedReasoningControl,
+ ResponsesRequestOptionsV1, ToolChoice,
+};
+
+#[test]
+fn worker_continue_keeps_conversation_identity_without_joining_other_tasks() {
+ let context = |task: &str, run: &str, native: Option<&str>| {
+ crate::server::request_plan::VerifiedRunObservationContext {
+ task_id: task.into(),
+ run_id: run.into(),
+ plan_id: "plan/one".into(),
+ plan_revision: 1,
+ publication_ref: "publication/one".into(),
+ harness_id: "pi".into(),
+ native_session_id: native.map(str::to_owned),
+ parent_context_ref: None,
+ continued_from_run_id: None,
+ }
+ };
+ let initial = verified_worker_identity(&context("task/one", "run/initial", None));
+ let continued =
+ verified_worker_identity(&context("task/one", "run/continue", Some("native-one")));
+ assert_eq!(initial.hold_identity(), continued.hold_identity());
+ assert_eq!(
+ initial.observation_identity(),
+ continued.observation_identity()
+ );
+ assert_eq!(continued.correlation_provenance(), "protocol_state");
+ assert_eq!(continued.session_scope(), "conversation");
+ let other = verified_worker_identity(&context("task/two", "run/other", Some("native-one")));
+ assert_ne!(initial.hold_identity(), other.hold_identity());
+ assert_ne!(initial.observation_identity(), other.observation_identity());
+ let invalid = verified_worker_identity(&context("", "run/valid", None));
+ assert_eq!(invalid.session_scope(), "request_scoped");
+}
+
+fn request(text: &str) -> ModelRequestIRV1 {
+ ModelRequestIRV1 {
+ native_body: None,
+ native_only: false,
+ schema_version: MODEL_REQUEST_IR_SCHEMA.into(),
+ ingress_protocol: IngressProtocol::Responses,
+ served_model_id: "agent/test".into(),
+ stream: false,
+ instructions: Vec::new(),
+ messages: vec![CanonicalMessage {
+ role: MessageRole::User,
+ content: vec![ContentPart::Text { text: text.into() }],
+ name: None,
+ }],
+ tools: Vec::new(),
+ tool_namespaces: Vec::new(),
+ responses_tool_order: Vec::new(),
+ web_search: None,
+ responses_search_history: Default::default(),
+ responses_annotations: Default::default(),
+ responses_message_phases: Default::default(),
+ responses_internal_chat_message_metadata: Default::default(),
+ responses_reasoning_history: Default::default(),
+ tool_choice: ToolChoice::None,
+ parallel_tool_calls: false,
+ requested_reasoning: RequestedReasoningControl::absent(),
+ requested_max_output_tokens: None,
+ provider_state: Vec::new(),
+ responses_options: None,
+ responses_item_ids: Default::default(),
+ responses_item_statuses: Default::default(),
+ }
+}
+
+#[test]
+fn codex_requires_consistent_dimensions_and_keeps_thread_with_session() {
+ let mut headers = HeaderMap::new();
+ headers.insert("thread-id", "thread".parse().unwrap());
+ headers.insert("session-id", "session".parse().unwrap());
+ let mut request = request("hello");
+ request.responses_options = Some(ResponsesRequestOptionsV1 {
+ store: None,
+ include: None,
+ prompt_cache_key: None,
+ client_metadata: Some(
+ [
+ ("thread_id".into(), "thread".into()),
+ ("session_id".into(), "session".into()),
+ ]
+ .into_iter()
+ .collect(),
+ ),
+ reasoning_summary: None,
+ reasoning_context: None,
+ });
+ match codex_identity(IngressProtocol::Responses, &headers, &request) {
+ Field::Value((kind, parts)) => {
+ assert_eq!(kind, "codex_thread_session");
+ assert_eq!(parts, ["thread", "session"]);
+ }
+ Field::Absent | Field::Invalid => panic!("consistent identity was not accepted"),
+ }
+ request
+ .responses_options
+ .as_mut()
+ .unwrap()
+ .client_metadata
+ .as_mut()
+ .unwrap()
+ .insert("session_id".into(), "other".into());
+ assert!(matches!(
+ codex_identity(IngressProtocol::Responses, &headers, &request),
+ Field::Invalid
+ ));
+ headers.append("thread-id", "duplicate".parse().unwrap());
+ assert!(matches!(
+ codex_identity(IngressProtocol::Responses, &headers, &request),
+ Field::Invalid
+ ));
+}
+
+#[test]
+fn inferred_anchor_uses_complete_user_and_rejects_public_wrappers() {
+ let key = [3; 32];
+ let common = "x".repeat(4_096);
+ assert_ne!(
+ first_user_digest(&request(&(common.clone() + "a")), &key),
+ first_user_digest(&request(&(common + "b")), &key)
+ );
+ for public in [
+ "# AGENTS.md instructions for /tmp",
+ "<environment_context>cwd</environment_context>",
+ "<system-reminder>rules</system-reminder>",
+ "<recommended_plugins>plugins</recommended_plugins>\n# AGENTS.md instructions for /tmp",
+ "<send_user_message_question_reply>prior answer</send_user_message_question_reply>",
+ " ",
+ ] {
+ assert!(first_user_digest(&request(public), &key).is_none());
+ }
+}
+
+#[test]
+fn claude_metadata_extracts_only_bounded_json_session() {
+ assert!(matches!(
+ claude_metadata_identity(&serde_json::json!({
+ "metadata":{"user_id":"{\"session_id\":\"claude-session\",\"device_id\":\"ignored\"}"}
+ })),
+ Field::Value(value) if value == "claude-session"
+ ));
+ assert!(matches!(
+ claude_metadata_identity(&serde_json::json!({"metadata":{"user_id":"not-json"}})),
+ Field::Invalid
+ ));
+}
+
+fn native(
+ headers: &[(&'static str, &str)],
+ ingress: IngressProtocol,
+ document: Value,
+) -> Field<NativeIdentity> {
+ let mut map = HeaderMap::new();
+ for (name, value) in headers {
+ map.append(
+ http::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
+ value.parse().unwrap(),
+ );
+ }
+ native_identity(
+ ingress,
+ &map,
+ &document,
+ &request("# AGENTS.md instructions"),
+ )
+}
+
+fn assert_native(field: Field<NativeIdentity>, kind: &str, expected: &[&str]) {
+ match field {
+ Field::Value((actual, parts)) => {
+ assert_eq!(actual, kind);
+ assert_eq!(parts, expected);
+ }
+ Field::Absent | Field::Invalid => panic!("native identity was not accepted"),
+ }
+}
+
+#[test]
+fn claude_header_and_metadata_share_the_released_namespace_and_require_agreement() {
+ let metadata = serde_json::json!({"metadata":{"user_id":"{\"session_id\":\"native\"}"}});
+ for document in [serde_json::json!({}), metadata.clone()] {
+ assert_native(
+ native(
+ &[("X-Claude-Code-Session-Id", "native")],
+ IngressProtocol::Messages,
+ document,
+ ),
+ "claude_metadata_session",
+ &["native"],
+ );
+ }
+ assert!(matches!(
+ native(
+ &[("x-claude-code-session-id", "other")],
+ IngressProtocol::Messages,
+ metadata
+ ),
+ Field::Invalid
+ ));
+ assert!(matches!(
+ native(
+ &[("x-claude-code-session-id", "native")],
+ IngressProtocol::Messages,
+ serde_json::json!({"metadata":{"user_id":"not-json"}})
+ ),
+ Field::Invalid
+ ));
+}
+
+#[test]
+fn native_header_validation_rejects_duplicates_empty_oversized_and_nontext_values() {
+ for name in [
+ "x-claude-code-session-id",
+ "x-deepseek-harness-session-id",
+ "x-opencode-session-id",
+ "session-id",
+ ] {
+ for value in ["".to_owned(), "x".repeat(129)] {
+ assert!(matches!(
+ native(&[(name, &value)], IngressProtocol::Messages, Value::Null),
+ Field::Invalid
+ ));
+ }
+ assert!(matches!(
+ native(
+ &[(name, "same"), (name, "same")],
+ IngressProtocol::Messages,
+ Value::Null
+ ),
+ Field::Invalid
+ ));
+ let mut headers = HeaderMap::new();
+ headers.insert(name, http::HeaderValue::from_bytes(&[0xff]).unwrap());
+ assert!(matches!(
+ native_identity(
+ IngressProtocol::Messages,
+ &headers,
+ &Value::Null,
+ &request("same")
+ ),
+ Field::Invalid
+ ));
+ assert!(valid_identity(&"x".repeat(128)).is_some());
+ assert!(valid_identity("native\tbad").is_none());
+ assert!(valid_identity(&"界".repeat(43)).is_none());
+ }
+}
+
+#[test]
+fn opencode_uses_actual_session_without_merging_parent_or_cache_affinity() {
+ for ingress in [
+ IngressProtocol::Responses,
+ IngressProtocol::ChatCompletions,
+ IngressProtocol::Messages,
+ ] {
+ assert_native(
+ native(&[("X-OpenCode-Session-Id", "native")], ingress, Value::Null),
+ "opencode_session",
+ &["native"],
+ );
+ let hints = [
+ ("user-agent", "opencode/1.19.0"),
+ ("x-opencode-session", "shared-cache"),
+ ("x-session-affinity", "shared-cache"),
+ ("x-session-id", "shared-cache"),
+ ("x-opencode-parent-session-id", "parent"),
+ ("x-parent-session-id", "parent"),
+ ("x-opencode-project", "project"),
+ ("x-opencode-request", "request"),
+ ];
+ assert!(matches!(
+ native(&hints, ingress, Value::Null),
+ Field::Absent
+ ));
+ let mut headers = hints.to_vec();
+ headers.push(("x-opencode-session-id", "child"));
+ assert_native(
+ native(&headers, ingress, Value::Null),
+ "opencode_session",
+ &["child"],
+ );
+ }
+ // Pi's OpenCode provider also sends the routing header; it is not another
+ // vendor's identity claim and must preserve Pi's accepted session namespace.
+ assert_native(
+ native(
+ &[
+ ("user-agent", "pi (linux; x64)"),
+ ("x-client-request-id", "pi-session"),
+ ("x-opencode-session", "pi-session"),
+ ],
+ IngressProtocol::Responses,
+ Value::Null,
+ ),
+ "pi_session",
+ &["pi-session"],
+ );
+}
+
+#[test]
+fn pi_ai_session_headers_are_scoped_to_client_and_protocol() {
+ for (agent, kind) in [
+ ("pi (darwin 25; arm64)", "pi_session"),
+ (
+ "deepseek-harness/0.2.0-rc.2 (+https://github.com/deepseek-ai/deepseek-harness)",
+ "deepseek_harness_session",
+ ),
+ ] {
+ for name in ["x-client-request-id", "session_id", "x-session-id"] {
+ assert_native(
+ native(
+ &[("user-agent", agent), (name, "native")],
+ IngressProtocol::Responses,
+ Value::Null,
+ ),
+ kind,
+ &["native"],
+ );
+ }
+ for name in ["x-session-affinity", "x-session-id"] {
+ assert_native(
+ native(
+ &[("user-agent", agent), (name, "native")],
+ IngressProtocol::Messages,
+ Value::Null,
+ ),
+ kind,
+ &["native"],
+ );
+ }
+ assert!(matches!(
+ native(
+ &[
+ ("user-agent", agent),
+ ("x-client-request-id", "per-request")
+ ],
+ IngressProtocol::Messages,
+ Value::Null
+ ),
+ Field::Absent
+ ));
+ assert!(matches!(
+ native(
+ &[("user-agent", agent), ("x-session-affinity", "affinity")],
+ IngressProtocol::Responses,
+ Value::Null
+ ),
+ Field::Absent
+ ));
+ assert!(matches!(
+ native(
+ &[
+ ("user-agent", agent),
+ ("x-client-request-id", "a"),
+ ("session_id", "b")
+ ],
+ IngressProtocol::Responses,
+ Value::Null
+ ),
+ Field::Invalid
+ ));
+ assert!(matches!(
+ native(
+ &[
+ ("user-agent", agent),
+ ("x-session-id", "a"),
+ ("x-session-id", "a")
+ ],
+ IngressProtocol::Responses,
+ Value::Null
+ ),
+ Field::Invalid
+ ));
+ }
+ for agent in ["other-client/1", "pi-other/1", "deepseek-harness/"] {
+ assert!(matches!(
+ native(
+ &[
+ ("user-agent", agent),
+ ("x-client-request-id", "a"),
+ ("x-session-id", "a"),
+ ("session_id", "a")
+ ],
+ IngressProtocol::Responses,
+ Value::Null
+ ),
+ Field::Absent
+ ));
+ }
+ assert!(matches!(
+ native(
+ &[("x-client-request-id", "a"), ("x-session-affinity", "a")],
+ IngressProtocol::Responses,
+ Value::Null
+ ),
+ Field::Absent
+ ));
+}
+
+#[test]
+fn native_families_cannot_override_conflicts_or_discard_codex_dimensions() {
+ assert_native(
+ native(
+ &[
+ ("x-opencode-session-id", "native"),
+ ("session-id", "native"),
+ ("thread-id", "thread"),
+ ],
+ IngressProtocol::Responses,
+ Value::Null,
+ ),
+ "codex_thread_session",
+ &["thread", "native"],
+ );
+ assert_native(
+ native(
+ &[
+ ("user-agent", "pi (linux; x64)"),
+ ("session-id", "native"),
+ ("thread-id", "thread"),
+ ("x-client-request-id", "native"),
+ ],
+ IngressProtocol::Responses,
+ Value::Null,
+ ),
+ "codex_thread_session",
+ &["thread", "native"],
+ );
+ assert_native(
+ native(
+ &[
+ ("x-deepseek-harness-session-id", "native"),
+ ("user-agent", "deepseek-harness/0.2"),
+ ("x-client-request-id", "native"),
+ ],
+ IngressProtocol::Responses,
+ Value::Null,
+ ),
+ "deepseek_harness_session",
+ &["native"],
+ );
+ for headers in [
+ vec![("session-id", "a"), ("x-claude-code-session-id", "b")],
+ vec![("session-id", "a"), ("x-opencode-session-id", "b")],
+ vec![
+ ("x-claude-code-session-id", "a"),
+ ("x-opencode-session-id", "a"),
+ ],
+ vec![
+ ("x-deepseek-harness-session-id", "a"),
+ ("x-opencode-session-id", "a"),
+ ],
+ vec![
+ ("x-opencode-session-id", "a"),
+ ("user-agent", "pi (browser)"),
+ ("x-client-request-id", "a"),
+ ],
+ vec![
+ ("x-claude-code-session-id", "a"),
+ ("x-deepseek-harness-session-id", "a"),
+ ],
+ vec![
+ ("x-deepseek-harness-session-id", "a"),
+ ("user-agent", "pi (browser)"),
+ ("x-client-request-id", "a"),
+ ],
+ ] {
+ assert!(matches!(
+ native(&headers, IngressProtocol::Responses, Value::Null),
+ Field::Invalid
+ ));
+ }
+}
diff --git a/crates/gateway/src/observation.rs b/crates/gateway/src/observation.rs
index 1d1c27ad..2d9f74b0 100644
--- a/crates/gateway/src/observation.rs
+++ b/crates/gateway/src/observation.rs
@@ -96,6 +96,7 @@ pub struct GatewayObservation {
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum NativeAgentObservationIdentityV1 {
+ /// Claude Code header or the supported JSON metadata session, with one stable namespace.
ClaudeMetadataSession {
session_id: String,
},
@@ -109,6 +110,18 @@ pub enum NativeAgentObservationIdentityV1 {
QoderSession {
session_id: String,
},
+ /// Native Pi session carried by its pi-ai transport (without Codex dimensions).
+ PiSession {
+ session_id: String,
+ },
+ /// Native DSH header or its scoped pi-ai transport session.
+ DeepseekHarnessSession {
+ session_id: String,
+ },
+ /// Actual OpenCode session from `x-opencode-session-id`, not cache affinity.
+ OpenCodeSession {
+ session_id: String,
+ },
CodexThreadSession {
thread_id: String,
session_id: String,
@@ -169,6 +182,22 @@ pub fn derive_native_agent_observation_session_id(
NativeAgentObservationIdentityV1::CodexSession { session_id } => {
("codex_session", vec![session_id.as_str()])
}
+ NativeAgentObservationIdentityV1::PiSession { session_id } => {
+ if !matches!(
+ trust.ingress_protocol,
+ hiroute_domain::IngressProtocolV1::Responses
+ | hiroute_domain::IngressProtocolV1::Messages
+ ) {
+ return Err(NativeAgentObservationSessionError::UnsupportedIngress);
+ }
+ ("pi_session", vec![session_id.as_str()])
+ }
+ NativeAgentObservationIdentityV1::DeepseekHarnessSession { session_id } => {
+ ("deepseek_harness_session", vec![session_id.as_str()])
+ }
+ NativeAgentObservationIdentityV1::OpenCodeSession { session_id } => {
+ ("opencode_session", vec![session_id.as_str()])
+ }
NativeAgentObservationIdentityV1::QoderSession { session_id } => {
if !matches!(
trust.ingress_protocol,
diff --git a/crates/gateway/src/observation/tests.rs b/crates/gateway/src/observation/tests.rs
index 8eb1e7ac..0ce7f71b 100644
--- a/crates/gateway/src/observation/tests.rs
+++ b/crates/gateway/src/observation/tests.rs
@@ -123,12 +123,91 @@ fn native_agent_session_derivation_reuses_the_producer_identity_formula() {
)
.unwrap()
);
+ for (identity, kind) in [
+ (
+ NativeAgentObservationIdentityV1::PiSession {
+ session_id: "pi-native".into(),
+ },
+ "pi_session",
+ ),
+ (
+ NativeAgentObservationIdentityV1::DeepseekHarnessSession {
+ session_id: "dsh-native".into(),
+ },
+ "deepseek_harness_session",
+ ),
+ (
+ NativeAgentObservationIdentityV1::OpenCodeSession {
+ session_id: "opencode-native".into(),
+ },
+ "opencode_session",
+ ),
+ ] {
+ let raw = match &identity {
+ NativeAgentObservationIdentityV1::PiSession { session_id }
+ | NativeAgentObservationIdentityV1::DeepseekHarnessSession { session_id }
+ | NativeAgentObservationIdentityV1::OpenCodeSession { session_id } => session_id,
+ _ => unreachable!(),
+ };
+ let expected = SessionId::parse(reliable_observation_session_id(
+ &key,
+ workspace.as_str(),
+ &trust.authority_id,
+ &trust.grant_id,
+ trust.agent_plan_id.as_ref().unwrap().as_str(),
+ &trust.served_model_id,
+ "responses",
+ kind,
+ &[raw],
+ ))
+ .unwrap();
+ assert_eq!(
+ derive_native_agent_observation_session_id(&workspace, &key, &trust, &identity)
+ .unwrap(),
+ expected
+ );
+ assert_ne!(
+ derive_native_agent_observation_session_id(
+ &workspace,
+ &key,
+ &messages_trust,
+ &identity
+ )
+ .unwrap(),
+ expected
+ );
+ }
let mut wrong_protocol = trust;
wrong_protocol.ingress_protocol = hiroute_domain::IngressProtocolV1::ChatCompletions;
assert!(
derive_native_agent_observation_session_id(&workspace, &key, &wrong_protocol, &qoder)
.is_err()
);
+ let opencode = NativeAgentObservationIdentityV1::OpenCodeSession {
+ session_id: "opencode-native".into(),
+ };
+ let expected_chat = SessionId::parse(reliable_observation_session_id(
+ &key,
+ workspace.as_str(),
+ &wrong_protocol.authority_id,
+ &wrong_protocol.grant_id,
+ wrong_protocol.agent_plan_id.as_ref().unwrap().as_str(),
+ &wrong_protocol.served_model_id,
+ "chat_completions",
+ "opencode_session",
+ &["opencode-native"],
+ ))
+ .unwrap();
+ assert_eq!(
+ derive_native_agent_observation_session_id(&workspace, &key, &wrong_protocol, &opencode)
+ .unwrap(),
+ expected_chat
+ );
+ wrong_protocol.ingress_protocol = hiroute_domain::IngressProtocolV1::Unknown;
+ assert_eq!(
+ derive_native_agent_observation_session_id(&workspace, &key, &wrong_protocol, &opencode),
+ Err(NativeAgentObservationSessionError::InvalidTrust)
+ );
}
fn request(policy: OtelContentPolicy) -> RequestObservation {
diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.md
index ab18d457..75907400 100644
--- a/docs/code-map/architecture.md
+++ b/docs/code-map/architecture.md
@@ -75,6 +75,7 @@ Scan → Prepare → Save → restart → native use, including stale-source rej
| Concern | Owner | What callers must preserve |
| --- | --- | --- |
+| Native Agent session correlation | [Gateway identity resolver](../../crates/gateway/src/context_hold/identity.rs), [native input guide](../../crates/gateway/README.md#native-session-correlation) | One identity feeds ContextHold, decision history and observation; native IDs precede content inference, malformed or conflicting claims remain request-scoped |
| Capture completeness | [Content completeness](../../crates/observation/src/content/completeness.rs), [session query](../../crates/observation/src/query_v2/sessions.rs) | Aggregate every required request/direction; a finished stream or readable preview does not prove the session is complete |
| Streaming memory | [Capture](../../crates/gateway/src/observation/provider/capture.rs), [pending delivery](../../crates/gateway/src/observation/provider/capture/tracker.rs) | Decoder, projector and delivery tracker share the stream budget; queue capacity is not capture evidence |
| Upstream fault attribution | [Wire projection](../../crates/gateway/src/observation/provider/wire_diagnostic.rs), [attempt association](../../crates/gateway/src/observation/request/diagnostic.rs), [decision calls](../../crates/gateway/src/core_runtime/classification/diagnostic.rs) | Actual bounded model/control fields, negotiated HTTP protocol, closed error codes, hashed request IDs and separate client headers/body commit facts must preserve the real outcome without prompts or provider error text |
diff --git a/scripts/ci-shards.py b/scripts/ci-shards.py
index de27be93..033f3cfa 100755
--- a/scripts/ci-shards.py
+++ b/scripts/ci-shards.py
@@ -67,6 +67,7 @@ INTEGRATION_SHARDS = {
("hiroute-e2e", "p0_gateway_commit_boundary"),
("hiroute-e2e", "p0_gateway_context_hold"),
("hiroute-e2e", "p0_gateway_matrix_coverage"),
+ ("hiroute-e2e", "p0_gateway_native_sessions"),
("hiroute-e2e", "p0_gateway_observation"),
("hiroute-e2e", "p0_gateway_oracle"),
("hiroute-e2e", "p0_gateway_planner"),
diff --git a/scripts/test-plan.py b/scripts/test-plan.py
index 45405287..85acad4f 100644
--- a/scripts/test-plan.py
+++ b/scripts/test-plan.py
@@ -252,6 +252,9 @@ def e2e_consumers(path):
return [("hiroute-product-e2e", "pi_delegation")]
if path.startswith("crates/daemon/tests/support/qoder_"):
return [("hiroute-product-e2e", "qoder_delegation")]
+ if path == "tools/e2e-harness/tests/p0_gateway_native_sessions.rs":
+ return [("hiroute-e2e", "p0_gateway_native_sessions"), ("hiroute-e2e", "p0_gateway_protocol"),
+ ("hiroute-e2e", "p0_gateway_matrix_coverage")]
if path == "tools/e2e-harness/tests/p0_gateway_runtime.rs" or path.startswith("tools/e2e-harness/tests/p0_gateway_runtime/"):
return [("hiroute-e2e", "p0_gateway_runtime"), ("hiroute-e2e", "p0_gateway_protocol"),
("hiroute-e2e", "p0_gateway_matrix_coverage")]
@@ -271,7 +274,7 @@ def e2e_consumers(path):
return []
-PROCESS_TARGETS = {"p0_gateway_runtime", "p0_gateway_protocol", "smoke_cli"}
+PROCESS_TARGETS = {"p0_gateway_native_sessions", "p0_gateway_runtime", "p0_gateway_protocol", "smoke_cli"}
def worker_product_checks(paths):
@@ -410,7 +413,8 @@ def select(paths, full=False):
not (t == "smoke_cli" and groups & PRODUCT_GROUPS)}
# #94: ACP enables preserve_order in the full backend graph. Keep this
# known fixture-sensitive combination in focused runtime checks too.
- runtime_context = ("hiroute-e2e", "p0_gateway_runtime") in pending
+ runtime_context = bool(pending & {("hiroute-e2e", "p0_gateway_runtime"),
+ ("hiroute-e2e", "p0_gateway_native_sessions")})
feature_flags = ["--features", "serde_json/preserve_order"]
if runtime_context:
reasons.append("Gateway runtime: check serde_json/preserve_order from the full backend context (#94)")
@@ -424,7 +428,7 @@ def select(paths, full=False):
continue
flags = ["--lib"] if target == "lib" else ["--test", target]
commands.append(["cargo", "test", "--locked", "-p", package, "--all-features", *flags] +
- (feature_flags if target == "p0_gateway_runtime" else []) +
+ (feature_flags if target in {"p0_gateway_runtime", "p0_gateway_native_sessions"} else []) +
(["--", "--test-threads=1"] if target in PROCESS_TARGETS else []))
rust = bool(commands)
if full or any(path.startswith(("assets/agent-profiles/", "assets/release-facts/",
@@ -486,7 +490,8 @@ def integration_preflight(plan, collect_failures=False, context_plan=None):
reasons = []
for path in plan["paths"]:
consumers = {t for p, t in e2e_consumers(path) if p == "hiroute-e2e"}
- selected = consumers & {"p0_gateway_matrix_coverage", "p0_gateway_protocol", "p0_gateway_runtime"}
+ selected = consumers & {"p0_gateway_matrix_coverage", "p0_gateway_protocol", "p0_gateway_runtime",
+ "p0_gateway_native_sessions"}
# These production adapters and the shared model IR feed the protocol matrix.
# This only adds early checks; their conservative final package scope stays intact.
if path.startswith(("crates/gateway/src/adapters/", "crates/gateway/src/model_ir/")):
@@ -510,7 +515,7 @@ def integration_preflight(plan, collect_failures=False, context_plan=None):
context = broad[:] if broad else ["cargo", "test", "--locked", "-p", "hiroute-e2e", "--all-features"]
if "--workspace" not in context and "hiroute-e2e" not in context:
context.extend(["-p", "hiroute-e2e"])
- if "--workspace" not in context and "p0_gateway_runtime" in targets:
+ if "--workspace" not in context and targets & {"p0_gateway_runtime", "p0_gateway_native_sessions"}:
context.extend(["--features", "serde_json/preserve_order"])
# First expose stale generated receipts, before even short protocol/runtime tests.
if "p0_gateway_matrix_coverage" in targets:
diff --git a/scripts/test-test-plan.py b/scripts/test-test-plan.py
index b7c59370..4d1d6f84 100644
--- a/scripts/test-test-plan.py
+++ b/scripts/test-test-plan.py
@@ -534,6 +534,22 @@ class SelectionTests(unittest.TestCase):
'tools/product-e2e/src/smoke/process.rs', 'e2e/schema/current-wire.json']:
self.assertEqual(plan.select([path])['mode'], 'full')
+ def test_native_session_listener_keeps_protocol_consumers_and_serial_feature_context(self):
+ path = 'tools/e2e-harness/tests/p0_gateway_native_sessions.rs'
+ result = plan.select([path])
+ self.assertEqual(result['mode'], 'affected')
+ self.assertFalse(result['frontend'])
+ tests = [c for c in result['commands'] if c[:2] == ['cargo', 'test']]
+ self.assertEqual({c[c.index('--test') + 1] for c in tests},
+ {'p0_gateway_native_sessions', 'p0_gateway_protocol', 'p0_gateway_matrix_coverage'})
+ native = next(c for c in tests if 'p0_gateway_native_sessions' in c)
+ self.assertIn('serde_json/preserve_order', native)
+ self.assertEqual(native[-2:], ['--', '--test-threads=1'])
+ preflight = plan.integration_preflight(result)
+ behavior = next(c for c in preflight['commands'] if 'p0_gateway_native_sessions' in c)
+ self.assertIn('serde_json/preserve_order', behavior)
+ self.assertIn('--test-threads=1', behavior)
+
def test_responses_helper_includes_indirect_smoke_consumer(self):
result = plan.select(['tools/e2e-harness/src/p0/client.rs'])
commands = result['commands']
diff --git a/tools/e2e-harness/tests/p0_gateway_native_sessions.rs b/tools/e2e-harness/tests/p0_gateway_native_sessions.rs
new file mode 100644
index 00000000..00051f39
--- /dev/null
+++ b/tools/e2e-harness/tests/p0_gateway_native_sessions.rs
@@ -0,0 +1,455 @@
+//! Native session claims through the production listener and observation producer.
+mod runtime_support;
+
+use std::fs;
+use std::path::Path;
+use std::thread;
+use std::time::{Duration, Instant};
+
+use runtime_support::{NativeProvider, ObservationFaults, ProviderReply, RuntimeFixture, request};
+use serde_json::{Value, json};
+
+const RESPONSE: &[u8] = br#"{"id":"accepted","model":"runtime-native","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}"#;
+const DECISION: &[u8] =
+ br#"{"decision":{"kind":"ordinal","probabilities":{"simple":0.9,"complex":0.1}}}"#;
+
+fn provider(body: &'static [u8]) -> NativeProvider {
+ NativeProvider::start(vec![
+ ProviderReply::Complete {
+ status: 200,
+ error_kind: None,
+ body,
+ };
+ 128
+ ])
+}
+
+fn body(messages: bool, text: &str, metadata: Option<&str>) -> Value {
+ let mut body = if messages {
+ json!({"model":"runtime-model","max_tokens":64,"messages":[{"role":"user","content":text}]})
+ } else {
+ json!({"model":"runtime-model","input":text,"stream":false})
+ };
+ if let Some(metadata) = metadata {
+ body["metadata"] = json!({"user_id":metadata});
+ }
+ body
+}
+
+fn send(
+ fixture: &RuntimeFixture,
+ messages: bool,
+ headers: &[(&str, &str)],
+ body: &Value,
+ ordinal: usize,
+) -> Value {
+ send_at(
+ fixture,
+ if messages {
+ "/v1/messages"
+ } else {
+ "/v1/responses"
+ },
+ if messages {
+ runtime_support::MESSAGES_TOKEN
+ } else {
+ runtime_support::TOKEN
+ },
+ headers,
+ body,
+ ordinal,
+ )
+}
+
+fn send_at(
+ fixture: &RuntimeFixture,
+ path: &str,
+ token: &str,
+ headers: &[(&str, &str)],
+ body: &Value,
+ ordinal: usize,
+) -> Value {
+ let mut headers = headers.to_vec();
+ let bearer = format!("Bearer {token}");
+ headers.push(if path == "/v1/chat/completions" {
+ ("Authorization", bearer.as_str())
+ } else {
+ ("X-HiRoute-Token", token)
+ });
+ let response = request(
+ fixture.address,
+ "POST",
+ path,
+ &headers,
+ &serde_json::to_vec(body).unwrap(),
+ );
+ assert_eq!(
+ response.status,
+ 200,
+ "{path}: {}",
+ String::from_utf8_lossy(&response.body)
+ );
+ let finished = finished(fixture.observation_root.as_deref().unwrap(), ordinal);
+ finished.last().unwrap()["correlation"].clone()
+}
+
+fn finished(root: &Path, count: usize) -> Vec<Value> {
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ let records: Vec<Value> = fs::read_to_string(root.join("execution-fact.jsonl"))
+ .unwrap_or_default()
+ .lines()
+ .filter_map(|line| serde_json::from_str(line).ok())
+ .collect();
+ let finished: Vec<_> = records
+ .into_iter()
+ .filter(|record| {
+ record["fact"]["kind"] == "request_finished"
+ && record["fact"]["outcome"] == "accepted"
+ })
+ .collect();
+ if finished.len() >= count {
+ assert_eq!(
+ finished.len(),
+ count,
+ "each request must finish exactly once"
+ );
+ return finished;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "missing executed request {count}"
+ );
+ thread::sleep(Duration::from_millis(10));
+ }
+}
+
+#[test]
+fn real_listener_native_sessions_prioritize_ids_and_isolate_identical_content() {
+ let simple = provider(RESPONSE);
+ let complex = provider(RESPONSE);
+ let classifier = provider(DECISION);
+ let fixture = RuntimeFixture::launch_rest_classified_with_observation(
+ &[&simple, &complex, &classifier],
+ 1,
+ ObservationFaults::healthy(),
+ );
+ let mut ordinal = 0;
+ for messages in [false, true] {
+ let mut cases = vec![
+ ("x-claude-code-session-id", None),
+ ("session-id", None), // Qoder and Codex keep their existing namespace.
+ ("x-deepseek-harness-session-id", None),
+ ("x-session-id", Some("pi (linux; x64)")),
+ ];
+ if messages {
+ cases.push(("x-session-affinity", Some("pi (linux; x64)")));
+ cases.push(("x-session-affinity", Some("deepseek-harness/0.2.0")));
+ } else {
+ cases.push(("x-client-request-id", Some("pi (linux; x64)")));
+ cases.push(("session_id", Some("pi (linux; x64)")));
+ cases.push(("x-client-request-id", Some("deepseek-harness/0.2.0")));
+ }
+ for (index, (name, agent)) in cases.into_iter().enumerate() {
+ let native = format!("native-{messages}-{index}");
+ let other = format!("other-{messages}-{index}");
+ let mut correlations = Vec::new();
+ for (id, text) in [
+ (&native, "identical first user"),
+ (&native, "# AGENTS.md instructions\nrebuilt native context"),
+ (&other, "identical first user"),
+ ] {
+ let mut headers = vec![(name, id.as_str())];
+ if let Some(agent) = agent {
+ headers.push(("User-Agent", agent));
+ }
+ ordinal += 1;
+ let correlation = send(
+ &fixture,
+ messages,
+ &headers,
+ &body(messages, text, None),
+ ordinal,
+ );
+ assert_eq!(correlation["session_scope"], "conversation", "{name}");
+ assert_eq!(
+ correlation["correlation_provenance"], "agent_supplied",
+ "{name}"
+ );
+ assert!(
+ !correlation["conversation_id"]
+ .as_str()
+ .unwrap()
+ .contains(id)
+ );
+ correlations.push(correlation);
+ }
+ assert_eq!(
+ correlations[0]["conversation_id"], correlations[1]["conversation_id"],
+ "{name}: rewritten content must keep native session"
+ );
+ assert_ne!(
+ correlations[0]["conversation_id"], correlations[2]["conversation_id"],
+ "{name}: identical content must not join different native sessions"
+ );
+ }
+ }
+ assert_eq!(simple.calls() + complex.calls(), ordinal);
+}
+
+#[test]
+fn real_listener_opencode_sessions_keep_children_separate_from_cache_affinity() {
+ let simple = provider(RESPONSE);
+ let complex = provider(RESPONSE);
+ let classifier = provider(DECISION);
+ let fixture = RuntimeFixture::launch_rest_classified_with_observation(
+ &[&simple, &complex, &classifier],
+ 1,
+ ObservationFaults::healthy(),
+ );
+ let mut ordinal = 0;
+ for (path, token) in [
+ ("/v1/responses", runtime_support::TOKEN),
+ ("/v1/chat/completions", runtime_support::CHAT_TOKEN),
+ ("/v1/messages", runtime_support::MESSAGES_TOKEN),
+ ] {
+ let ordinary = "identical ordinary first user";
+ let document = |text| body(path != "/v1/responses", text, None);
+ let mut correlations = Vec::new();
+ // OpenCode's current cache routing may share a parent/fork affinity.
+ // Only the dedicated session-id identifies the actual child session.
+ for (id, text, affinity, request_id) in [
+ ("ses_child_a", ordinary, "ses_parent", "msg_initial"),
+ (
+ "ses_child_a",
+ "# AGENTS.md instructions\nrebuilt native context",
+ "ses_other_cache_root",
+ "msg_followup",
+ ),
+ ("ses_child_b", ordinary, "ses_parent", "msg_initial"),
+ ] {
+ ordinal += 1;
+ let correlation = send_at(
+ &fixture,
+ path,
+ token,
+ &[
+ ("User-Agent", "opencode/1.19.0"),
+ ("X-OpenCode-Session-Id", id),
+ ("x-opencode-parent-session-id", "ses_parent"),
+ ("x-parent-session-id", "ses_parent"),
+ ("x-opencode-session", affinity),
+ ("x-session-affinity", affinity),
+ ("X-Session-Id", affinity),
+ ("x-opencode-request", request_id),
+ ("x-opencode-project", "project_shared"),
+ ],
+ &document(text),
+ ordinal,
+ );
+ assert_eq!(correlation["session_scope"], "conversation", "{path}");
+ assert_eq!(
+ correlation["correlation_provenance"], "agent_supplied",
+ "{path}"
+ );
+ assert!(
+ !correlation["conversation_id"]
+ .as_str()
+ .unwrap()
+ .contains(id)
+ );
+ correlations.push(correlation);
+ }
+ assert_eq!(
+ correlations[0]["conversation_id"], correlations[1]["conversation_id"],
+ "{path}: cache and request changes must retain the native session"
+ );
+ assert_ne!(
+ correlations[0]["conversation_id"], correlations[2]["conversation_id"],
+ "{path}: siblings sharing cache affinity must remain separate"
+ );
+
+ let mut inferred = Vec::new();
+ for _ in 0..2 {
+ ordinal += 1;
+ let correlation = send_at(&fixture, path, token, &[], &document(ordinary), ordinal);
+ assert_eq!(correlation["session_scope"], "conversation");
+ assert_eq!(correlation["correlation_provenance"], "gateway_generated");
+ inferred.push(correlation);
+ }
+ assert_eq!(
+ inferred[0]["conversation_id"],
+ inferred[1]["conversation_id"]
+ );
+ let mut invalid_sessions = std::collections::BTreeSet::new();
+ for headers in [
+ vec![("x-opencode-session-id", "")],
+ vec![
+ ("x-opencode-session-id", "same"),
+ ("x-opencode-session-id", "same"),
+ ],
+ vec![
+ ("x-opencode-session-id", "session"),
+ ("session-id", "other"),
+ ],
+ ] {
+ for _ in 0..2 {
+ ordinal += 1;
+ let correlation = send_at(
+ &fixture,
+ path,
+ token,
+ &headers,
+ &document(ordinary),
+ ordinal,
+ );
+ assert_eq!(correlation["session_scope"], "request_scoped", "{path}");
+ assert_eq!(correlation["correlation_provenance"], "unproven", "{path}");
+ assert!(
+ invalid_sessions
+ .insert(correlation["conversation_id"].as_str().unwrap().to_owned())
+ );
+ }
+ }
+ let hints = [
+ ("User-Agent", "opencode/1.19.0"),
+ ("x-opencode-session", "ses_parent"),
+ ("x-session-affinity", "ses_parent"),
+ ("X-Session-Id", "ses_parent"),
+ ("x-opencode-parent-session-id", "ses_parent"),
+ ("x-parent-session-id", "ses_parent"),
+ ("x-opencode-request", "msg_request"),
+ ("x-opencode-project", "project_shared"),
+ ];
+ for _ in 0..2 {
+ ordinal += 1;
+ let correlation = send_at(&fixture, path, token, &hints, &document(ordinary), ordinal);
+ assert_eq!(correlation["correlation_provenance"], "gateway_generated");
+ assert_eq!(
+ correlation["conversation_id"],
+ inferred[0]["conversation_id"]
+ );
+ }
+ ordinal += 1;
+ let correlation = send_at(
+ &fixture,
+ path,
+ token,
+ &hints,
+ &document("# AGENTS.md instructions"),
+ ordinal,
+ );
+ assert_eq!(correlation["session_scope"], "request_scoped");
+ assert_eq!(correlation["correlation_provenance"], "unproven");
+ }
+ assert_eq!(ordinal, 42, "every required OpenCode scenario must execute");
+ assert_eq!(simple.calls() + complex.calls(), ordinal);
+}
+
+#[test]
+fn real_listener_invalid_native_claims_and_unscoped_hints_remain_request_scoped() {
+ let simple = provider(RESPONSE);
+ let complex = provider(RESPONSE);
+ let classifier = provider(DECISION);
+ let fixture = RuntimeFixture::launch_rest_classified_with_observation(
+ &[&simple, &complex, &classifier],
+ 1,
+ ObservationFaults::healthy(),
+ );
+ let mut ordinal = 0;
+ let ordinary = "identical ordinary first user";
+ // Prove this content is inferable: invalid native claims must suppress the
+ // same fallback that otherwise joins these two ordinary requests.
+ let mut inferred = Vec::new();
+ for _ in 0..2 {
+ ordinal += 1;
+ let correlation = send(&fixture, false, &[], &body(false, ordinary, None), ordinal);
+ assert_eq!(correlation["session_scope"], "conversation");
+ assert_eq!(correlation["correlation_provenance"], "gateway_generated");
+ inferred.push(correlation);
+ }
+ assert_eq!(
+ inferred[0]["conversation_id"],
+ inferred[1]["conversation_id"]
+ );
+ let cases = [
+ (
+ false,
+ vec![
+ ("x-claude-code-session-id", "same"),
+ ("x-claude-code-session-id", "same"),
+ ],
+ None,
+ ),
+ (
+ true,
+ vec![("x-claude-code-session-id", "header")],
+ Some("{\"session_id\":\"body\"}"),
+ ),
+ (true, vec![("x-deepseek-harness-session-id", "")], None),
+ (
+ false,
+ vec![
+ ("User-Agent", "pi (browser)"),
+ ("x-client-request-id", "a"),
+ ("session_id", "b"),
+ ],
+ None,
+ ),
+ (
+ false,
+ vec![
+ ("User-Agent", "ordinary-client/1"),
+ ("x-client-request-id", "per-request"),
+ ("session_id", "unknown"),
+ ],
+ None,
+ ),
+ (
+ true,
+ vec![
+ ("x-session-affinity", "cache-root"),
+ ("User-Agent", "ordinary-client/1"),
+ ],
+ None,
+ ),
+ ];
+ let mut sessions = std::collections::BTreeSet::new();
+ for (index, (messages, headers, metadata)) in cases.into_iter().enumerate() {
+ let text = if index < 4 {
+ ordinary
+ } else {
+ "# AGENTS.md instructions\nshared wrapper"
+ };
+ for _ in 0..2 {
+ ordinal += 1;
+ let correlation = send(
+ &fixture,
+ messages,
+ &headers,
+ &body(messages, text, metadata),
+ ordinal,
+ );
+ assert_eq!(correlation["session_scope"], "request_scoped");
+ assert_eq!(correlation["correlation_provenance"], "unproven");
+ assert!(
+ sessions.insert(correlation["conversation_id"].as_str().unwrap().to_owned()),
+ "request-scoped claims must never join"
+ );
+ }
+ }
+ // A cache key is not a native session, even for a client carrying Pi branding.
+ ordinal += 1;
+ let mut cache_only = body(false, "# AGENTS.md instructions", None);
+ cache_only["prompt_cache_key"] = json!("cache-root");
+ let correlation = send(
+ &fixture,
+ false,
+ &[("User-Agent", "pi (browser)")],
+ &cache_only,
+ ordinal,
+ );
+ assert_eq!(correlation["session_scope"], "request_scoped");
+ assert_eq!(correlation["correlation_provenance"], "unproven");
+ assert_eq!(simple.calls() + complex.calls(), ordinal);
+}