Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): report the provenance of every outbound provider request

thinhlpg7d077a00fb03
diff --git a/protocol/rpc-schema.json b/protocol/rpc-schema.json
index 78a5abb0e..dc4c6b8d6 100644
--- a/protocol/rpc-schema.json
+++ b/protocol/rpc-schema.json
@@ -1104,6 +1104,77 @@
"id",
"details"
]
+ },
+ {
+ "description": "What the run is about to send a provider, emitted immediately before\neach request goes out -- the hook an experiment harness needs to hold two\nruns comparable (pi's `onPayload` is the shape Robot Studio already\nrecords).\n\nEvery outbound request gets one, including the side calls a turn makes\n(compaction, a session title) and every child run's own requests; the\nhashes describe the body Jan built for the adapter, so two runs can be\ncompared field by field. Nothing here is model input or output: it never\njoins the transcript, and a consumer may render it, store it or ignore\nit.",
+ "type": "object",
+ "properties": {
+ "run_id": {
+ "description": "Which run made the request: `None` for the main run, the child's\nrun id for a subagent.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "session_id": {
+ "description": "The session the request belongs to, as the run's handshake names it\n(the correlation id the request carries is derived from it).",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "provider": {
+ "description": "The configured provider the model resolved to.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "model": {
+ "description": "The model id the upstream receives, without a `<provider>/` prefix.",
+ "type": "string"
+ },
+ "api_type": {
+ "description": "The wire API the request is built for (`anthropic`, `google`,\n`openai-responses`), absent for chat/completions.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "request_sha256": {
+ "description": "SHA-256 of the request body as Jan built it, canonical JSON -- the\nvalue that makes two runs comparable even when a field this record\ndoes not itemize has changed.",
+ "type": "string"
+ },
+ "body_bytes": {
+ "type": "integer",
+ "format": "uint64",
+ "minimum": 0
+ },
+ "tools_sha256": {
+ "description": "SHA-256 of the `tools` array as sent, able to change while the model\nid does not.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "images": {
+ "description": "Every image in the body, in order, hashed over its decoded bytes so\nthe host can hash the same frame it captured.",
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/ProvenanceImage"
+ }
+ },
+ "type": {
+ "type": "string",
+ "const": "request_provenance"
+ }
+ },
+ "required": [
+ "type",
+ "model",
+ "request_sha256",
+ "body_bytes"
+ ]
}
],
"$defs": {
@@ -1320,6 +1391,37 @@
"minimum": 0
}
}
+ },
+ "ProvenanceImage": {
+ "description": "One image in an outbound request, as [`StreamEvent::RequestProvenance`]\nreports it: identity, not content.",
+ "type": "object",
+ "properties": {
+ "sha256": {
+ "description": "SHA-256 over the image's decoded bytes.",
+ "type": "string"
+ },
+ "mime_type": {
+ "type": "string"
+ },
+ "bytes": {
+ "description": "Decoded length in bytes.",
+ "type": "integer",
+ "format": "uint64",
+ "minimum": 0
+ },
+ "tool_call_id": {
+ "description": "The host tool call whose result carried it, when one did. `None` for an\nimage the user attached.",
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "sha256",
+ "mime_type",
+ "bytes"
+ ]
}
}
}
diff --git a/protocol/schema.json b/protocol/schema.json
index f5fb7dd6b..b9e29aca0 100644
--- a/protocol/schema.json
+++ b/protocol/schema.json
@@ -678,6 +678,77 @@
"id",
"details"
]
+ },
+ {
+ "description": "What the run is about to send a provider, emitted immediately before\neach request goes out -- the hook an experiment harness needs to hold two\nruns comparable (pi's `onPayload` is the shape Robot Studio already\nrecords).\n\nEvery outbound request gets one, including the side calls a turn makes\n(compaction, a session title) and every child run's own requests; the\nhashes describe the body Jan built for the adapter, so two runs can be\ncompared field by field. Nothing here is model input or output: it never\njoins the transcript, and a consumer may render it, store it or ignore\nit.",
+ "type": "object",
+ "properties": {
+ "run_id": {
+ "description": "Which run made the request: `None` for the main run, the child's\nrun id for a subagent.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "session_id": {
+ "description": "The session the request belongs to, as the run's handshake names it\n(the correlation id the request carries is derived from it).",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "provider": {
+ "description": "The configured provider the model resolved to.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "model": {
+ "description": "The model id the upstream receives, without a `<provider>/` prefix.",
+ "type": "string"
+ },
+ "api_type": {
+ "description": "The wire API the request is built for (`anthropic`, `google`,\n`openai-responses`), absent for chat/completions.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "request_sha256": {
+ "description": "SHA-256 of the request body as Jan built it, canonical JSON -- the\nvalue that makes two runs comparable even when a field this record\ndoes not itemize has changed.",
+ "type": "string"
+ },
+ "body_bytes": {
+ "type": "integer",
+ "format": "uint64",
+ "minimum": 0
+ },
+ "tools_sha256": {
+ "description": "SHA-256 of the `tools` array as sent, able to change while the model\nid does not.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "images": {
+ "description": "Every image in the body, in order, hashed over its decoded bytes so\nthe host can hash the same frame it captured.",
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/ProvenanceImage"
+ }
+ },
+ "type": {
+ "type": "string",
+ "const": "request_provenance"
+ }
+ },
+ "required": [
+ "type",
+ "model",
+ "request_sha256",
+ "body_bytes"
+ ]
}
]
},
@@ -895,6 +966,37 @@
}
}
},
+ "ProvenanceImage": {
+ "description": "One image in an outbound request, as [`StreamEvent::RequestProvenance`]\nreports it: identity, not content.",
+ "type": "object",
+ "properties": {
+ "sha256": {
+ "description": "SHA-256 over the image's decoded bytes.",
+ "type": "string"
+ },
+ "mime_type": {
+ "type": "string"
+ },
+ "bytes": {
+ "description": "Decoded length in bytes.",
+ "type": "integer",
+ "format": "uint64",
+ "minimum": 0
+ },
+ "tool_call_id": {
+ "description": "The host tool call whose result carried it, when one did. `None` for an\nimage the user attached.",
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "sha256",
+ "mime_type",
+ "bytes"
+ ]
+ },
"Init": {
"description": "The first record of a `--output-format stream-json` channel, and the only\none a client may require before any other.\n\nIt exists because the rest of the stream is unversioned and unaddressable: a\nconsumer sees events and nothing else, so it cannot tell which contract it\nis reading, whose run it is watching, or what it is allowed to send back.\nThose are the questions a handshake answers, and a consumer that has to\ninfer them from a side channel (a CLI flag it passed, a config file it read)\nis one refactor away from being wrong.\n\nField names are snake_case like the rest of this channel -- the event tags\nand the envelope's `session_id`/`stop_reason` set that convention, so the\nhandshake follows it rather than introducing a second one for two fields.\n\nThe compatibility rule for what a client may assume:\n\n- a v1 client may rely on `protocol_version`, `session_id` and `model`\n always being present;\n- fields may be added without a version bump, so a client ignores unknown\n ones and unknown tags rather than failing;\n- a tag is never renamed and never removed within v1;\n- behaviour beyond v1 is asserted against `protocol_version`, not assumed.",
"type": "object",
diff --git a/src-tauri/jan-cli/tests/stream_json_init.rs b/src-tauri/jan-cli/tests/stream_json_init.rs
index 6bd718a5d..582a8835e 100644
--- a/src-tauri/jan-cli/tests/stream_json_init.rs
+++ b/src-tauri/jan-cli/tests/stream_json_init.rs
@@ -36,12 +36,25 @@ const REFUSAL: &str =
/// Serve one canned reply per connection until the test process exits, and
/// return the OpenAI-compatible base URL for it.
fn stub_provider(status: &'static str, content_type: &'static str, body: &'static str) -> String {
+ stub_provider_recording(status, content_type, body).0
+}
+
+/// The same, keeping every request body it was sent: what the provider received
+/// is the only honest witness of what a run put on the wire.
+#[allow(clippy::type_complexity)]
+fn stub_provider_recording(
+ status: &'static str,
+ content_type: &'static str,
+ body: &'static str,
+) -> (String, std::sync::Arc<std::sync::Mutex<Vec<Vec<u8>>>>) {
+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let sink = std::sync::Arc::clone(&seen);
let listener = TcpListener::bind("127.0.0.1:0").expect("bind the stub provider");
let addr = listener.local_addr().expect("stub address");
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
- read_request(&mut stream);
+ sink.lock().unwrap().push(read_request(&mut stream));
let response = format!(
"HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
@@ -50,19 +63,19 @@ fn stub_provider(status: &'static str, content_type: &'static str, body: &'stati
let _ = stream.flush();
}
});
- format!("http://{addr}/v1")
+ (format!("http://{addr}/v1"), seen)
}
-/// Read a request off the wire, headers and body. Without this the client sees
-/// a reset instead of an answer, which would make a failure case pass for the
-/// wrong reason.
-fn read_request(stream: &mut TcpStream) {
+/// Read a request off the wire, headers and body, returning the body. Without
+/// this the client sees a reset instead of an answer, which would make a
+/// failure case pass for the wrong reason.
+fn read_request(stream: &mut TcpStream) -> Vec<u8> {
let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
let mut buf: Vec<u8> = Vec::new();
let mut chunk = [0u8; 4096];
loop {
match stream.read(&mut chunk) {
- Ok(0) | Err(_) => return,
+ Ok(0) | Err(_) => return Vec::new(),
Ok(n) => buf.extend_from_slice(&chunk[..n]),
}
let Some(head) = buf.windows(4).position(|w| w == b"\r\n\r\n") else {
@@ -75,7 +88,7 @@ fn read_request(stream: &mut TcpStream) {
.and_then(|v| v.trim().parse::<usize>().ok())
.unwrap_or(0);
if buf.len() >= head + 4 + want {
- return;
+ return buf[head + 4..head + 4 + want].to_vec();
}
}
}
@@ -132,6 +145,10 @@ impl Scratch {
/// closed. A `stream-json` reader that hits end of input is the ordinary
/// case: the run keeps going, it just has no client left to talk to.
fn run(&self) -> Output {
+ self.run_task("say hi")
+ }
+
+ fn run_task(&self, task: &str) -> Output {
let project = self.project();
self.command(&[
"cli",
@@ -147,7 +164,7 @@ impl Scratch {
"stream-json",
"--input-format",
"stream-json",
- "say hi",
+ task,
])
.stdin(Stdio::null())
.output()
@@ -339,3 +356,110 @@ fn a_setup_failure_reports_the_envelope_without_a_handshake() {
assert_eq!(records[0]["error"]["code"], "setup_error");
assert_eq!(records[0]["session_id"], serde_json::Value::Null);
}
+
+/// Every request a run sends is preceded by a `request_provenance` record, and
+/// the record's digest is a deterministic function of the request Jan built.
+/// That is the property a harness relies on to say two runs sent the same
+/// thing, so it is the property pinned here: two identical runs report one
+/// digest, and a different task does not.
+///
+/// The digest covers the body Jan built, before the provider adapter's own
+/// serialization -- the record is identity for comparing runs, not a byte
+/// audit of what a particular client put on the wire.
+#[test]
+fn a_run_reports_the_provenance_of_the_request_it_sends() {
+ let scratch = Scratch::new("provenance");
+ let (url, seen) = stub_provider_recording("200 OK", "text/event-stream", ANSWER);
+ scratch.configure(&url);
+
+ let first = scratch.run_task("say hi");
+ assert!(
+ first.status.success(),
+ "the run failed: {}",
+ String::from_utf8_lossy(&first.stderr)
+ );
+ let first_records = records(&first);
+ let record = one_provenance(&first_records);
+ assert_eq!(record["model"], "stub-model");
+ assert_eq!(record["provider"], "stub");
+ assert_eq!(
+ record["session_id"],
+ first_records[0]["session_id"],
+ "the record names the session the handshake announced, not a derivation of it"
+ );
+ assert!(
+ record.get("run_id").is_none() || record["run_id"].is_null(),
+ "the main run is not a child: {record}"
+ );
+ assert!(
+ record.get("api_type").is_none() || record["api_type"].is_null(),
+ "chat/completions has no wire API name to report: {record}"
+ );
+ assert!(
+ record["tools_sha256"].is_string(),
+ "a run sends a tool array, so its digest is reported: {record}"
+ );
+ assert!(
+ record.get("images").is_none(),
+ "no images went out, so none are reported: {record}"
+ );
+ assert!(
+ record["body_bytes"].as_u64().expect("a length") > 0,
+ "the body has a size: {record}"
+ );
+
+ // The record belongs to the request that went out: the provider received a
+ // body naming the model the record does.
+ let bodies = seen.lock().unwrap().clone();
+ let body: serde_json::Value = serde_json::from_slice(
+ bodies.first().expect("the provider received the request"),
+ )
+ .expect("the request body is JSON");
+ assert_eq!(body["model"], record["model"]);
+
+ // Emitted before the call, which is what lets a harness record a request
+ // whose reply it never gets.
+ let at = |records: &Vec<serde_json::Value>, want: &str| {
+ records
+ .iter()
+ .position(|r| r["type"] == want)
+ .unwrap_or_else(|| panic!("no {want} record: {records:#?}"))
+ };
+ assert!(
+ at(&first_records, "request_provenance") < at(&first_records, "token"),
+ "the record precedes the answer it belongs to"
+ );
+
+ // Same task, same request: the digest is reproducible across runs.
+ let again = scratch.run_task("say hi");
+ let repeat = records(&again);
+ assert_eq!(
+ one_provenance(&repeat)["request_sha256"],
+ record["request_sha256"],
+ "an identical request must report an identical digest"
+ );
+
+ // A different task is a different request, so the digest must move: a
+ // constant or mis-scoped hash would pass the check above.
+ let other = scratch.run_task("say bye");
+ let changed = records(&other);
+ assert_ne!(
+ one_provenance(&changed)["request_sha256"],
+ record["request_sha256"],
+ "a different request must report a different digest"
+ );
+}
+
+/// The one `request_provenance` record of a single-request run.
+fn one_provenance(records: &Vec<serde_json::Value>) -> &serde_json::Value {
+ let found: Vec<&serde_json::Value> = records
+ .iter()
+ .filter(|r| r["type"] == "request_provenance")
+ .collect();
+ assert_eq!(
+ found.len(),
+ 1,
+ "one record per request, and this run makes one: {records:#?}"
+ );
+ found[0]
+}
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index d16f5c009..f18b6c93f 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -270,6 +270,64 @@ pub enum StreamEvent {
id: String,
details: serde_json::Value,
},
+ /// What the run is about to send a provider, emitted immediately before
+ /// each request goes out -- the hook an experiment harness needs to hold two
+ /// runs comparable (pi's `onPayload` is the shape Robot Studio already
+ /// records).
+ ///
+ /// Every outbound request gets one, including the side calls a turn makes
+ /// (compaction, a session title) and every child run's own requests; the
+ /// hashes describe the body Jan built for the adapter, so two runs can be
+ /// compared field by field. Nothing here is model input or output: it never
+ /// joins the transcript, and a consumer may render it, store it or ignore
+ /// it.
+ RequestProvenance {
+ /// Which run made the request: `None` for the main run, the child's
+ /// run id for a subagent.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ run_id: Option<String>,
+ /// The session the request belongs to, as the run's handshake names it
+ /// (the correlation id the request carries is derived from it).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ session_id: Option<String>,
+ /// The configured provider the model resolved to.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ provider: Option<String>,
+ /// The model id the upstream receives, without a `<provider>/` prefix.
+ model: String,
+ /// The wire API the request is built for (`anthropic`, `google`,
+ /// `openai-responses`), absent for chat/completions.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ api_type: Option<String>,
+ /// SHA-256 of the request body as Jan built it, canonical JSON -- the
+ /// value that makes two runs comparable even when a field this record
+ /// does not itemize has changed.
+ request_sha256: String,
+ body_bytes: u64,
+ /// SHA-256 of the `tools` array as sent, able to change while the model
+ /// id does not.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ tools_sha256: Option<String>,
+ /// Every image in the body, in order, hashed over its decoded bytes so
+ /// the host can hash the same frame it captured.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ images: Vec<ProvenanceImage>,
+ },
+}
+
+/// One image in an outbound request, as [`StreamEvent::RequestProvenance`]
+/// reports it: identity, not content.
+#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
+pub struct ProvenanceImage {
+ /// SHA-256 over the image's decoded bytes.
+ pub sha256: String,
+ pub mime_type: String,
+ /// Decoded length in bytes.
+ pub bytes: u64,
+ /// The host tool call whose result carried it, when one did. `None` for an
+ /// image the user attached.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tool_call_id: Option<String>,
}
/// A subagent in a not-yet-started phase of a phased dispatch: its name (unique
@@ -574,6 +632,25 @@ pub(crate) mod tests {
execution_id: None,
},
),
+ (
+ "RequestProvenance",
+ StreamEvent::RequestProvenance {
+ run_id: Some("run-1".into()),
+ session_id: Some("session-9".into()),
+ provider: Some("anthropic".into()),
+ model: "claude-sonnet-5".into(),
+ api_type: Some("anthropic".into()),
+ request_sha256: "0".repeat(64),
+ body_bytes: 41,
+ tools_sha256: Some("1".repeat(64)),
+ images: vec![ProvenanceImage {
+ sha256: "2".repeat(64),
+ mime_type: "image/png".into(),
+ bytes: 3,
+ tool_call_id: Some("call_7".into()),
+ }],
+ },
+ ),
(
"Done",
StreamEvent::Done {
@@ -659,7 +736,8 @@ pub(crate) mod tests {
| StreamEvent::PermissionRequest { .. }
| StreamEvent::ToolRequest { .. }
| StreamEvent::ToolRequestCancelled { .. }
- | StreamEvent::ToolDetails { .. } => {}
+ | StreamEvent::ToolDetails { .. }
+ | StreamEvent::RequestProvenance { .. } => {}
}
}
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index d6b593dc0..6c2c73fd9 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -124,6 +124,11 @@ pub(crate) struct OrchestrationArgs {
/// code paths with no session (server proxy runs) keeps the default
/// throwaway per-command tmpfs.
pub session_id: Option<String>,
+ /// This run's own id when it is a child run: `None` for the main run, the
+ /// id the dispatch gave it (the same one that tags its events and its host
+ /// tool requests) for a subagent. Provenance records carry it so a harness
+ /// can attribute a request to the run that made it.
+ pub run_id: Option<String>,
/// Per-invocation override for `bash` confinement (the CLI's `--sandbox`).
/// `None` falls through to `[tools].sandbox`, then the user's global
/// `sandbox`, then the surface default -- see [`resolve_sandbox`]. Inherited
@@ -323,6 +328,72 @@ struct HttpModelInvoker {
/// [`crate::core::agent::correlation`]. `None` when the run has no session
/// to correlate.
client_request_id: Option<String>,
+ /// The session this invoker belongs to, as the handshake reports it. The
+ /// correlation id above is derived from it, so provenance names the id a
+ /// client already holds rather than the derivation it has never seen.
+ session_id: Option<String>,
+ /// Identity for the provenance record emitted before each request: the
+ /// provider the model resolved to, the wire API the body is built for, and
+ /// the child run's id when this invoker belongs to one.
+ provenance: RequestIdentityOwned,
+}
+
+/// [`crate::core::agent::provenance::RequestIdentity`] as the invoker stores it:
+/// the identity fields outlive the resolution that produced them.
+#[derive(Debug, Default, Clone)]
+struct RequestIdentityOwned {
+ run_id: Option<String>,
+ provider: Option<String>,
+ api_type: Option<String>,
+ /// Whether the provider's credential is an OAuth account token, which the
+ /// converter it is built from needs (Anthropic's beta header). Carried here
+ /// because one lookup answers both, and two lookups could disagree.
+ oauth: bool,
+}
+
+impl RequestIdentityOwned {
+ fn as_identity<'a>(
+ &'a self,
+ session_id: Option<&'a str>,
+ ) -> crate::core::agent::provenance::RequestIdentity<'a> {
+ crate::core::agent::provenance::RequestIdentity {
+ run_id: self.run_id.as_deref(),
+ session_id,
+ provider: self.provider.as_deref(),
+ api_type: self.api_type.as_deref(),
+ }
+ }
+}
+
+/// The identity a request is reported under: which provider the model maps to,
+/// which wire API the body is built for, and the run making it. Resolved once
+/// per invoker rather than per request, and shared by the invokers that make
+/// side calls (compaction, /goal evaluations) so their provenance records name
+/// the run the same way the turn's does.
+///
+/// This is the same model-to-provider lookup the request itself resolves
+/// through, and it needs neither a URL nor a credential: the record names the
+/// provider, it does not authenticate to it.
+async fn request_identity(
+ model_id: &str,
+ provider_configs: &Arc<Mutex<HashMap<String, ProviderConfig>>>,
+ run_id: Option<&str>,
+) -> RequestIdentityOwned {
+ let (api_type, oauth) =
+ match resolve_api_type_for_model(model_id, provider_configs.clone()).await {
+ Some((api_type, oauth)) => (Some(api_type), oauth),
+ None => (None, false),
+ };
+ let provider = {
+ let configs = provider_configs.lock().await;
+ crate::core::agent::upstream::pick_provider_for_model(model_id, &configs)
+ };
+ RequestIdentityOwned {
+ run_id: run_id.map(str::to_string),
+ provider,
+ api_type,
+ oauth,
+ }
}
fn converter_http_client() -> reqwest::Client {
@@ -349,6 +420,12 @@ impl ModelInvoker for HttpModelInvoker {
normalized["model"] = serde_json::json!(bare);
}
}
+ // Emitted before the request goes out, so a harness that records
+ // provenance sees the request even when the call then fails.
+ let _ = events.send(crate::core::agent::provenance::of_request(
+ &normalized,
+ self.provenance.as_identity(self.session_id.as_deref()),
+ ));
if let Some(converter) = &self.converter {
crate::core::agent::upstream::stream_converted_chat_completions(
&self.converter_client,
@@ -2234,6 +2311,8 @@ pub(crate) async fn run_server_side_openai_orchestration(
auto_approve: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
session_id: None,
+ // The top-level run is not a child: no dispatch gave it an id.
+ run_id: None,
sandbox: None,
monitors: None,
// Run-owned: the proxy has no conversation to deliver a later ping
@@ -2794,6 +2873,7 @@ async fn orchestrate_inner(
auto_approve,
run_mode,
session_id,
+ run_id,
monitors: session_monitors,
bg_shells: session_bg_shells,
subagent_bg: session_subagent_bg,
@@ -3051,18 +3131,24 @@ async fn orchestrate_inner(
let max_turns = body_turn_cap(json_body);
+ let provenance = request_identity(&model_id, provider_configs, run_id.as_deref()).await;
+ let converter = provenance
+ .api_type
+ .as_deref()
+ .and_then(|api_type| converter_for(Some(api_type), provenance.oauth));
+
let http_model = HttpModelInvoker {
client: client.clone(),
upstream_url,
api_keys: session_api_keys,
provider_configs: provider_configs.clone(),
- converter: resolve_api_type_for_model(&model_id, provider_configs.clone())
- .await
- .and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),
+ converter,
converter_client: converter_http_client(),
client_request_id: crate::core::agent::correlation::session_request_id(
args.session_id.as_deref(),
),
+ session_id: args.session_id.clone(),
+ provenance,
};
let mcp_tools = McpToolInvoker {
tool_to_server,
@@ -3473,14 +3559,18 @@ pub(crate) async fn compact_history(
args.mlx_sessions.clone(),
)
.await?;
+ let provenance =
+ request_identity(model_id, &args.provider_configs, args.run_id.as_deref()).await;
+ let converter = provenance
+ .api_type
+ .as_deref()
+ .and_then(|api_type| converter_for(Some(api_type), provenance.oauth));
let model = HttpModelInvoker {
client: args.client.clone(),
upstream_url,
api_keys,
provider_configs: args.provider_configs.clone(),
- converter: resolve_api_type_for_model(model_id, args.provider_configs.clone())
- .await
- .and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),
+ converter,
converter_client: converter_http_client(),
// A compaction call is billed to the same session as the turn that
// triggered it, so it carries the same correlation id: leaving it out
@@ -3488,6 +3578,8 @@ pub(crate) async fn compact_history(
client_request_id: crate::core::agent::correlation::session_request_id(
args.session_id.as_deref(),
),
+ session_id: args.session_id.clone(),
+ provenance,
};
crate::core::agent::compaction::compact_conversation(messages, model_id, &model, keep_recent)
.await
@@ -3513,19 +3605,29 @@ pub(crate) async fn evaluate_goal(
args.mlx_sessions.clone(),
)
.await?;
+ let provenance = request_identity(
+ smol_model_id,
+ &args.provider_configs,
+ args.run_id.as_deref(),
+ )
+ .await;
+ let converter = provenance
+ .api_type
+ .as_deref()
+ .and_then(|api_type| converter_for(Some(api_type), provenance.oauth));
let model = HttpModelInvoker {
client: args.client.clone(),
upstream_url,
api_keys,
provider_configs: args.provider_configs.clone(),
- converter: resolve_api_type_for_model(smol_model_id, args.provider_configs.clone())
- .await
- .and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),
+ converter,
converter_client: converter_http_client(),
// Same session, same bill (see `compact_history`).
client_request_id: crate::core::agent::correlation::session_request_id(
args.session_id.as_deref(),
),
+ session_id: args.session_id.clone(),
+ provenance,
};
crate::core::agent::goal::evaluate(smol_model_id, condition, messages, &model).await
}
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index 0c47d1cd0..3b36fd969 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -43,6 +43,7 @@ pub mod plugin_commands;
pub mod plugins;
pub mod project;
pub mod prompt;
+pub mod provenance;
pub mod reminder;
pub mod session;
pub mod skill_hub;
diff --git a/src-tauri/src/core/agent/provenance.rs b/src-tauri/src/core/agent/provenance.rs
new file mode 100644
index 000000000..8c793da67
--- /dev/null
+++ b/src-tauri/src/core/agent/provenance.rs
@@ -0,0 +1,244 @@
+//! Request provenance: what a run is about to send a provider, and nothing else.
+//!
+//! The record is identity, not content -- a hash of the body, a hash of the tool
+//! array, and one hash per image -- so an experiment harness can hold two runs
+//! comparable without copying prompts or frames around. It is emitted
+//! immediately before each request goes out, for the main run and for every
+//! child, which is the shape Robot Studio already records from pi's
+//! `onPayload`.
+//!
+//! The hashes describe the body Jan built for the adapter (canonical JSON of the
+//! request body, before an adapter's own serialization), so they are stable for
+//! a given run and comparable across runs of the same provider. Two runs on
+//! different wire APIs differ by construction: the tool array each provider
+//! receives is not the same shape.
+
+use base64::engine::general_purpose::STANDARD as BASE64;
+use base64::Engine as _;
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+
+use crate::core::agent::events::{ProvenanceImage, StreamEvent};
+
+/// Who is sending the request: the same identity the request's own correlation
+/// id and a child's `run_id` carry.
+#[derive(Debug, Default, Clone, Copy)]
+pub(crate) struct RequestIdentity<'a> {
+ /// `None` for the main run, the child's run id for a subagent.
+ pub run_id: Option<&'a str>,
+ /// The session the request belongs to, when the run has one.
+ pub session_id: Option<&'a str>,
+ /// The configured provider the model resolved to.
+ pub provider: Option<&'a str>,
+ /// The wire API the body is built for, absent for chat/completions.
+ pub api_type: Option<&'a str>,
+}
+
+/// The [`StreamEvent::RequestProvenance`] for one outbound request body.
+pub(crate) fn of_request(body: &Value, identity: RequestIdentity<'_>) -> StreamEvent {
+ let bytes = serde_json::to_vec(body).unwrap_or_default();
+ StreamEvent::RequestProvenance {
+ run_id: identity.run_id.map(str::to_string),
+ session_id: identity.session_id.map(str::to_string),
+ provider: identity.provider.map(str::to_string),
+ model: body
+ .get("model")
+ .and_then(|m| m.as_str())
+ .unwrap_or_default()
+ .to_string(),
+ api_type: identity.api_type.map(str::to_string),
+ request_sha256: sha256_hex(&bytes),
+ body_bytes: bytes.len() as u64,
+ tools_sha256: body
+ .get("tools")
+ .filter(|tools| tools.as_array().is_some_and(|t| !t.is_empty()))
+ .and_then(|tools| serde_json::to_vec(tools).ok())
+ .map(|tools| sha256_hex(&tools)),
+ images: images_of(body),
+ }
+}
+
+/// Every image the body carries, in message order.
+///
+/// A `data:` URL is hashed over its decoded bytes, so a host can hash the frame
+/// it captured and compare; a remote URL is hashed as text (there are no bytes
+/// here to hash, the provider fetches them), which is why it reports no MIME
+/// type and zero bytes.
+fn images_of(body: &Value) -> Vec<ProvenanceImage> {
+ let mut images = Vec::new();
+ let Some(messages) = body.get("messages").and_then(|m| m.as_array()) else {
+ return images;
+ };
+ for message in messages {
+ let tool_call_id = message
+ .get("tool_call_id")
+ .and_then(|id| id.as_str())
+ .map(str::to_string);
+ let Some(parts) = message.get("content").and_then(|c| c.as_array()) else {
+ continue;
+ };
+ for url in parts
+ .iter()
+ .filter(|part| part.get("type").and_then(|t| t.as_str()) == Some("image_url"))
+ .filter_map(|part| part.get("image_url")?.get("url")?.as_str())
+ {
+ if let Some((mime_type, payload)) = data_url_parts(url) {
+ if let Ok(decoded) = BASE64.decode(payload) {
+ images.push(ProvenanceImage {
+ sha256: sha256_hex(&decoded),
+ mime_type: mime_type.to_string(),
+ bytes: decoded.len() as u64,
+ tool_call_id: tool_call_id.clone(),
+ });
+ }
+ } else if url.starts_with("http://") || url.starts_with("https://") {
+ images.push(ProvenanceImage {
+ sha256: sha256_hex(url.as_bytes()),
+ mime_type: String::new(),
+ bytes: 0,
+ tool_call_id: tool_call_id.clone(),
+ });
+ }
+ }
+ }
+ images
+}
+
+/// `("image/png", "<base64>")` for a `data:image/png;base64,<payload>` URL.
+fn data_url_parts(url: &str) -> Option<(&str, &str)> {
+ let rest = url.strip_prefix("data:")?;
+ let (meta, payload) = rest.split_once(',')?;
+ let (mime, encoding) = meta.split_once(';')?;
+ if !encoding.eq_ignore_ascii_case("base64") || payload.is_empty() {
+ return None;
+ }
+ Some((mime, payload))
+}
+
+fn sha256_hex(bytes: &[u8]) -> String {
+ let mut hasher = Sha256::new();
+ hasher.update(bytes);
+ hex::encode(hasher.finalize())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn record(body: &Value) -> (String, u64, Option<String>, Vec<ProvenanceImage>) {
+ match of_request(body, RequestIdentity::default()) {
+ StreamEvent::RequestProvenance {
+ request_sha256,
+ body_bytes,
+ tools_sha256,
+ images,
+ ..
+ } => (request_sha256, body_bytes, tools_sha256, images),
+ other => panic!("expected a provenance record, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn the_body_hash_is_stable_for_the_same_request() {
+ let body = json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]});
+ let (first, bytes, tools, _) = record(&body);
+ let (second, ..) = record(&body);
+ assert_eq!(first, second);
+ assert_eq!(bytes as usize, serde_json::to_vec(&body).unwrap().len());
+ assert!(tools.is_none(), "no tools array means no tools hash");
+
+ let changed = json!({"model": "m", "messages": [{"role": "user", "content": "hello"}]});
+ assert_ne!(record(&changed).0, first, "a changed body changes the hash");
+ }
+
+ #[test]
+ fn images_are_hashed_over_their_decoded_bytes() {
+ // "QUJD" is "ABC": 3 bytes, so the hash is over those three bytes.
+ let body = json!({
+ "model": "m",
+ "messages": [
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"id": "call_7", "type": "function", "function": {"name": "camera", "arguments": "{}"}}
+ ]},
+ {"role": "tool", "tool_call_id": "call_7", "content": [
+ {"type": "text", "text": "front camera"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,QUJD"}}
+ ]},
+ {"role": "user", "content": [
+ {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,QQ=="}},
+ {"type": "image_url", "image_url": {"url": "https://example.test/shot.png"}}
+ ]}
+ ]
+ });
+ let images = record(&body).3;
+ assert_eq!(images.len(), 3);
+ assert_eq!(
+ images[0],
+ ProvenanceImage {
+ sha256: sha256_hex(b"ABC"),
+ mime_type: "image/png".into(),
+ bytes: 3,
+ tool_call_id: Some("call_7".into()),
+ }
+ );
+ assert_eq!(images[1].bytes, 1);
+ assert_eq!(images[1].mime_type, "image/jpeg");
+ assert_eq!(images[1].tool_call_id, None, "a user image names no call");
+ assert_eq!(images[2].bytes, 0, "a remote URL has no bytes here");
+ assert_eq!(images[2].mime_type, "");
+ assert_eq!(
+ images[2].sha256,
+ sha256_hex(b"https://example.test/shot.png")
+ );
+ }
+
+ #[test]
+ fn the_tools_hash_tracks_the_schemas_sent() {
+ let tools = json!([{"type": "function", "function": {"name": "read", "parameters": {"type": "object"}}}]);
+ let body = json!({"model": "m", "messages": [], "tools": tools});
+ let hash = record(&body).2.expect("tools hash");
+ assert_eq!(
+ hash,
+ sha256_hex(&serde_json::to_vec(&tools).unwrap()),
+ "the hash is over the array as sent"
+ );
+ assert_eq!(
+ record(&json!({"model": "m", "messages": [], "tools": []})).2,
+ None,
+ "an empty tools array is not a schema"
+ );
+ }
+
+ #[test]
+ fn identity_and_model_travel_into_the_record() {
+ let body = json!({"model": "claude-sonnet-5", "messages": []});
+ let event = of_request(
+ &body,
+ RequestIdentity {
+ run_id: Some("child-1"),
+ session_id: Some("session-9"),
+ provider: Some("anthropic"),
+ api_type: Some("anthropic"),
+ },
+ );
+ let value = serde_json::to_value(&event).unwrap();
+ assert_eq!(value["type"], "request_provenance");
+ assert_eq!(value["run_id"], "child-1");
+ assert_eq!(value["session_id"], "session-9");
+ assert_eq!(value["provider"], "anthropic");
+ assert_eq!(value["api_type"], "anthropic");
+ assert_eq!(value["model"], "claude-sonnet-5");
+ assert!(value.get("images").is_none(), "no images, no field");
+
+ // And a record with every optional field absent still reads back: a
+ // consumer validates what it receives against these shapes.
+ let minimal = of_request(&body, RequestIdentity::default());
+ let line = serde_json::to_string(&minimal).unwrap();
+ let back: StreamEvent = serde_json::from_str(&line).expect("reads back without optionals");
+ assert_eq!(
+ serde_json::to_value(&back).unwrap(),
+ serde_json::to_value(&minimal).unwrap()
+ );
+ }
+}
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index eb793a512..16e7c8d89 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -1307,6 +1307,9 @@ async fn run_subagent(
{
child_args.host_tool_route = Some((events.clone(), run_id.clone()));
}
+ // Every build gets the child's own id, not just the headless one: a
+ // provenance record has to name the run that made the request.
+ child_args.run_id = Some(run_id.clone());
let body = child_body(&resolved, &description, &parent);
@@ -3136,6 +3139,7 @@ mod tests {
use std::sync::Arc;
use tauri_plugin_agent_tools::permissions::ToolPermissions;
OrchestrationArgs {
+ run_id: None,
client: crate::core::agent::upstream::agent_http_client(),
provider_configs: Arc::new(tokio::sync::Mutex::new(
HashMap::<String, ProviderConfig>::new(),
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 107c60d53..cb63d6581 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -1171,6 +1171,8 @@ fn build_cli_orchestration_args(
// reuses `args` across turns and wipes it when the interactive session
// ends.
session_id: Some(uuid::Uuid::new_v4().to_string()),
+ // The top-level run is not a child: no dispatch gave it an id.
+ run_id: None,
// Run-owned here, so a headless run parks on its watchers: nobody is
// there to talk to meanwhile. The TUI installs its session set itself.
monitors: None,
@@ -2028,6 +2030,11 @@ async fn run_agent_loop(
.thread_id
.clone()
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
+ // The run's own id becomes the session id, so the one a client is handed,
+ // the one its requests are correlated under, and the one a provenance
+ // record names are the same id: three spellings of a session would only
+ // ever be a way to lose the thread between them.
+ args.session_id = Some(session_id.clone());
// The handshake, before anything else can reach stdout. Printed here rather
// than from the printer task for exactly that reason: nothing has been
@@ -2752,6 +2759,10 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry, duplex: boo
eprint!("\x1b[2m{delta}\x1b[0m");
let _ = std::io::stderr().flush();
}
+ // Provenance is machine-facing: it is an identity record for an
+ // experiment harness, not something to draw. The stream-json writer
+ // serializes the event itself, so nothing is lost by not printing it.
+ StreamEvent::RequestProvenance { .. } => {}
// Reasoning is progress, not answer: dimmed on stderr so piping stdout
// yields only the real completion.
StreamEvent::Reasoning { text } => {
diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rs
index a10043b22..e106609c4 100644
--- a/src-tauri/src/core/cli/run_report.rs
+++ b/src-tauri/src/core/cli/run_report.rs
@@ -16,7 +16,8 @@
//! `subagent_end`, `subagent_plan`, `subagent`, `notice`, `monitors`,
//! `parked`, `messages_updated`, `ask_request`, `ask_resolved`, `todo_update`,
//! `turn_usage`, `done`, `error`, `permission_request`, `tool_request`,
-//! `tool_request_cancelled`, `tool_details`. Four tags are minted by
+//! `tool_request_cancelled`, `tool_details`, `request_provenance`. Four tags are
+//! minted by
//! the CLI rather than by the loop: `init`, `permission_decision`, `result` and
//! `input_error`. `init` is the handshake a client reads before any other record
//! (see [`Init`]); `permission_decision` reports how this CLI answered a gated
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 3173a4e8b..8b250423b 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -5551,7 +5551,8 @@ impl App {
// cannot receive this.
StreamEvent::ToolRequest { .. }
| StreamEvent::ToolRequestCancelled { .. }
- | StreamEvent::ToolDetails { .. } => {}
+ | StreamEvent::ToolDetails { .. }
+ | StreamEvent::RequestProvenance { .. } => {}
// The loop auto-answered a timed-out ask; drop its now-dead prompt.
// A user answer clears the queue in `resolve_front_ask` instead, so
// this only fires for the timeout path.
@@ -25245,6 +25246,7 @@ mod tests {
provider_configs: std::collections::HashMap<String, crate::core::state::ProviderConfig>,
) -> std::sync::Arc<super::OrchestrationArgs> {
std::sync::Arc::new(super::OrchestrationArgs {
+ run_id: None,
client: crate::core::agent::upstream::agent_http_client(),
provider_configs: std::sync::Arc::new(tokio::sync::Mutex::new(provider_configs)),
mcp_servers: std::sync::Arc::new(tokio::sync::Mutex::new(