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.

refactor(agent): keep a canonical transcript apart from the projection (#8988)

Thinh Led4438703041d
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rs
index b554b9f4e..9f90c94c1 100644
--- a/src-tauri/src/core/agent/compaction.rs
+++ b/src-tauri/src/core/agent/compaction.rs
@@ -218,7 +218,7 @@ fn role(msg: &Value) -> &str {
///
/// `None` when the tail would leave nothing worth dropping: the summary is
/// itself a message, so a prefix of one shrinks nothing.
-fn tail_start(rest: &[Value], target: usize) -> Option<usize> {
+pub(crate) fn tail_start(rest: &[Value], target: usize) -> Option<usize> {
let mut cut = target;
while cut < rest.len() && role(&rest[cut]) == "tool" {
cut += 1;
@@ -274,6 +274,16 @@ pub(crate) async fn fire_pre_compact(
}
}
+/// The `system` message a compaction summary travels in, marker included. One
+/// place, because [`is_compaction_summary`] recognizes a summary by that marker
+/// and the transcript records this node verbatim.
+pub(crate) fn summary_message(summary: &str) -> Value {
+ json!({
+ "role": "system",
+ "content": format!("{SUMMARY_MARKER}\n\n{summary}")
+ })
+}
+
/// Compact `messages` so the result is meaningfully smaller than the input.
/// Returns the input unchanged when there is nothing safe to compact (so the
/// caller can detect a no-op and stop retrying).
@@ -284,6 +294,11 @@ pub(crate) async fn fire_pre_compact(
/// model, the compacted request could still overflow). The `Err` is propagated
/// so the caller can preserve history and block the request instead. Every
/// other summarizer failure stays recoverable and yields a [`FALLBACK_NOTE`].
+///
+/// Only the TUI's `/compact` still calls this: the agent loop compacts through
+/// the transcript's own boundary ([`summarize_span`]), so outside the cli build
+/// there is nothing left to call it.
+#[cfg_attr(not(feature = "cli"), allow(dead_code))]
pub(crate) async fn compact_conversation(
messages: &[Value],
model_id: &str,
@@ -306,14 +321,25 @@ pub(crate) async fn compact_conversation(
let mut out = Vec::with_capacity(system_msgs.len() + 1 + kept.len());
out.extend_from_slice(system_msgs);
- out.push(json!({
- "role": "system",
- "content": format!("{SUMMARY_MARKER}\n\n{summary}")
- }));
+ out.push(summary_message(&summary));
out.extend_from_slice(kept);
Ok(out)
}
+/// Summarize a span for a caller that records the replacement itself: the
+/// transcript's compaction path, where the summary becomes an event rather than
+/// a rewritten list. The node carries [`SUMMARY_MARKER`], so a later turn reads
+/// it as condensed history instead of mistaking it for a prompt.
+pub(crate) async fn summarize_span(
+ span: &[Value],
+ model_id: &str,
+ model: &dyn ModelInvoker,
+) -> Result<Value, String> {
+ summarize(span, model_id, model)
+ .await
+ .map(|text| summary_message(&text))
+}
+
/// Flatten a span of wire messages into a plain-text transcript. Rendering
/// rather than replaying keeps the request small and sidesteps tool pairing:
/// the dropped span is a slice, so its trailing assistant `tool_calls` may have
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index c76a92a3f..011f17abb 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -17,12 +17,13 @@ use tokio::sync::{mpsc, Mutex};
use crate::core::agent::events::{StreamEvent, Usage};
use crate::core::agent::session::SessionBudget;
+use crate::core::agent::transcript::{Projection, Transcript};
use crate::core::agent::upstream::{
- arguments_are_executable, collect_mcp_openai_tools, copy_optional_chat_params,
- drop_malformed_tool_calls, execute_mcp_tool_calls, extract_choice_message, extract_tool_calls,
- load_assistant_config, parse_openai_messages, repair_dangling_tool_calls,
- insert_volatile_system, resolve_api_type_for_model, resolve_upstream_for_model,
- set_system_prompt, stream_openai_chat_completions,
+ collect_mcp_openai_tools, content_says_nothing, copy_optional_chat_params,
+ execute_mcp_tool_calls, extract_choice_message, extract_tool_calls, load_assistant_config,
+ pairable_tool_call_id, parse_openai_messages, prune_unusable_tool_calls,
+ resolve_api_type_for_model, resolve_upstream_for_model, stream_openai_chat_completions,
+ tool_call_is_usable,
};
use crate::core::server::converters::{converter_for, UpstreamConverter};
#[cfg(not(feature = "cli"))]
@@ -2262,27 +2263,7 @@ async fn orchestrate_inner(
let messages_value = json_body
.get("messages")
.ok_or("Missing required field 'messages'")?;
- let mut conversation_messages = parse_openai_messages(messages_value)?;
- // Drop tool calls a truncated stream left with unparsable arguments before
- // anything else looks at the history. Such a call is persisted by the run
- // that produced it and resent on every later turn, and an OpenAI-compatible
- // upstream 422s the whole request over it -- so without this the session is
- // wedged on its own history and cannot heal. Runs first so the dangling
- // repair below sees the post-removal shape.
- let poisoned = drop_malformed_tool_calls(&mut conversation_messages);
- if poisoned > 0 {
- log::warn!("agent: dropped {poisoned} tool call(s) with unparsable arguments from history");
- }
- // Self-heal a conversation an earlier interrupted run may have left with a
- // tool_calls turn missing one of its results (e.g. the process was killed
- // while an `ask`/permission prompt was still pending). Providers like
- // Anthropic reject the entire request on a dangling tool_use, so repair
- // it here -- the one place every incoming message array passes through --
- // before it ever reaches a provider.
- let repaired = repair_dangling_tool_calls(&mut conversation_messages);
- if repaired > 0 {
- log::warn!("agent: repaired {repaired} dangling tool call(s) with no prior result");
- }
+ let conversation_messages = parse_openai_messages(messages_value)?;
let assistant_id = json_body
.get("assistant_id")
@@ -2357,14 +2338,32 @@ async fn orchestrate_inner(
volatile_parts.push(addendum.to_string());
}
- if let Some(sys) = stable_system {
- set_system_prompt(&mut conversation_messages, &sys);
- insert_volatile_system(&mut conversation_messages, &volatile_parts.join("\n\n"));
- } else {
+ // The history becomes a canonical record and the prompt becomes an event
+ // the projection places: at the head while it is unchanged, appended behind
+ // the history when it changes, so a turn cannot invalidate the bytes an
+ // earlier request already sent. The per-turn block stays projection input:
+ // recording yesterday's date as history is how a resumed session ends up
+ // carrying yesterday's date forever.
+ let volatile_system = volatile_parts.join("\n\n");
+ // The prompt the user just submitted, read while the incoming list is still
+ // a list: the record is not one, and `UserPromptSubmit` reports this turn's
+ // text rather than the history's.
+ let submitted_prompt = latest_user_text(&conversation_messages);
+ let mut transcript =
+ crate::core::agent::transcript::Transcript::from_history(conversation_messages);
+ let volatile_projection = match &stable_system {
+ Some(sys) => {
+ transcript.record_prompt(sys);
+ Some(volatile_system)
+ }
// No stable prompt (an isolated child run with no override): the
// volatile block is all there is, so it stands in as message 0.
- set_system_prompt(&mut conversation_messages, &volatile_parts.join("\n\n"));
- }
+ None => {
+ transcript.record_prompt(&volatile_system);
+ None
+ }
+ };
+ let send_reasoning = body_send_reasoning(json_body);
// Paired with the addendum above: force the model's very first tool call
// to actually be `todo` rather than leaving compliance up to a prompt it
// could silently ignore.
@@ -2578,12 +2577,17 @@ async fn orchestrate_inner(
// last, so a hook brackets exactly the work the run did. A context
// answer from SessionStart is queued here and drained into the first
// turn's reminders, which is why it fires before `run_turn_cycle`.
+ // What both payloads report is the request this run is about, and the
+ // record's projection is what it is: projected once, since the two
+ // hooks fire back to back on the same state.
+ let request_message_count =
+ projected_message_count(&transcript, volatile_projection.as_deref(), send_reasoning);
tools
.fire_hooks(
tauri_plugin_agent_tools::tools::hooks::HookEvent::SessionStart,
tauri_plugin_agent_tools::tools::hooks::HookPayload {
session_id: session_id.clone(),
- message_count: Some(conversation_messages.len()),
+ message_count: Some(request_message_count),
..Default::default()
},
)
@@ -2594,14 +2598,14 @@ async fn orchestrate_inner(
// sites would inevitably grow a fourth it was never added to. `deny` is
// not honored -- there is no tool call to stop -- but `context` is,
// which is what a prompt hook is for.
- if let Some(prompt) = latest_user_text(&conversation_messages) {
+ if let Some(prompt) = submitted_prompt {
tools
.fire_hooks(
tauri_plugin_agent_tools::tools::hooks::HookEvent::UserPromptSubmit,
tauri_plugin_agent_tools::tools::hooks::HookPayload {
prompt: Some(prompt),
session_id: session_id.clone(),
- message_count: Some(conversation_messages.len()),
+ message_count: Some(request_message_count),
..Default::default()
},
)
@@ -2612,7 +2616,9 @@ async fn orchestrate_inner(
json_body,
&model_id,
&openai_tools,
- conversation_messages,
+ transcript,
+ volatile_projection,
+ send_reasoning,
max_turns,
&mut budget,
&http_model,
@@ -2663,7 +2669,9 @@ async fn orchestrate_inner(
json_body,
&model_id,
&openai_tools,
- conversation_messages,
+ transcript,
+ volatile_projection,
+ send_reasoning,
max_turns,
&mut budget,
&http_model,
@@ -2688,7 +2696,7 @@ const MAX_COMPACTION_ATTEMPTS: usize = 4;
/// `stripAssistantReasoningInBody`; kept in one place so every surface (TUI,
/// headless, subagents) strips consistently. Only assistant messages carry the
/// field, but the filter is defensive and targets just that role.
-fn strip_assistant_reasoning(messages: &[serde_json::Value]) -> Vec<serde_json::Value> {
+pub(crate) fn strip_assistant_reasoning(messages: &[serde_json::Value]) -> Vec<serde_json::Value> {
messages
.iter()
.map(|m| {
@@ -2937,27 +2945,98 @@ fn body_session_budget(json_body: &serde_json::Value) -> Option<u64> {
async fn receive_steering(
steering: Option<&mpsc::UnboundedSender<SteeringRequest>>,
- messages: &mut Vec<serde_json::Value>,
+ messages: Vec<serde_json::Value>,
run_mode: crate::core::agent::plan::RunMode,
-) -> bool {
+) -> Vec<serde_json::Value> {
let Some(steering) = steering else {
- return false;
+ return Vec::new();
};
let (reply, response) = tokio::sync::oneshot::channel();
if steering
.send(SteeringRequest {
- messages: messages.clone(),
+ messages,
reply,
run_mode,
})
.is_err()
{
- return false;
+ return Vec::new();
}
- let incoming = response.await.unwrap_or_default();
- let received = !incoming.is_empty();
- messages.extend(incoming);
- received
+ response.await.unwrap_or_default()
+}
+
+/// The request the run's record projects to right now.
+fn project(
+ transcript: &Transcript,
+ volatile_system: Option<&str>,
+ send_reasoning: bool,
+) -> Vec<serde_json::Value> {
+ transcript.project(&Projection {
+ volatile_system,
+ send_reasoning,
+ })
+}
+
+/// How many messages the request this run is about carries: the `message_count`
+/// a hook payload reports. The projection is the only thing that knows now that
+/// there is no live list to measure, so the count is projected rather than kept
+/// alongside the record, where it could drift from what the request carries.
+fn projected_message_count(
+ transcript: &Transcript,
+ volatile_system: Option<&str>,
+ send_reasoning: bool,
+) -> usize {
+ project(transcript, volatile_system, send_reasoning).len()
+}
+
+/// Record the assistant turn, minus the tool calls that may not be resent, and
+/// report the ids of the calls that were dropped.
+///
+/// The refusal rule itself is [`crate::core::agent::upstream::prune_unusable_tool_calls`],
+/// the same one [`crate::core::agent::upstream::drop_malformed_tool_calls`]
+/// applies to an incoming history: it used to clean these out of the live list
+/// on the next turn. The record is never rewritten, so an unusable call is
+/// refused entry instead: one whose arguments do not decode to a plain JSON
+/// object, or which has no non-empty id for its result to carry, is a turn a
+/// strict upstream rejects the whole request over -- and the run that emitted
+/// it cannot resend its own history until it is gone. The caller uses the
+/// returned ids to skip the results that answered those calls, which is the
+/// other half of the same repair: an orphaned `tool` message is invalid on its
+/// own.
+fn record_assistant_turn(transcript: &mut Transcript, message: &serde_json::Value) -> Vec<String> {
+ let mut message = message.clone();
+ let dropped = prune_unusable_tool_calls(&mut message);
+ // An assistant turn left with neither text nor calls is not a valid message
+ // to resend, and recording it would only make the next request invalid.
+ if message.get("tool_calls").is_none() && content_says_nothing(&message) {
+ return dropped;
+ }
+ transcript.record_message(message);
+ dropped
+}
+
+/// Compact the run's record in place: summarize the span the plan names, and
+/// record the point that stands in for it. `Some(messages summarized)` when a
+/// compaction happened; `None` when there is nothing safe to drop, which is how
+/// the caller tells a no-op from a shrink instead of comparing lengths.
+///
+/// The original span stays in the record - only the projection omits it - so a
+/// later turn, a different provider, or a changed `keep_recent` can still
+/// rebuild from it.
+async fn compact(
+ transcript: &mut Transcript,
+ keep_recent: usize,
+ model_id: &str,
+ model: &dyn ModelInvoker,
+) -> Result<Option<usize>, String> {
+ let Some(plan) = transcript.compaction_plan(keep_recent) else {
+ return Ok(None);
+ };
+ let summarized = plan.summarize.len();
+ let summary =
+ crate::core::agent::compaction::summarize_span(&plan.summarize, model_id, model).await?;
+ transcript.record_compaction(summary, plan.covers);
+ Ok(Some(summarized))
}
#[allow(clippy::too_many_arguments)]
@@ -2966,7 +3045,9 @@ async fn run_turn_cycle(
json_body: &serde_json::Value,
model_id: &str,
openai_tools: &[serde_json::Value],
- mut conversation_messages: Vec<serde_json::Value>,
+ mut transcript: Transcript,
+ volatile_system: Option<String>,
+ mut send_reasoning: bool,
max_turns: usize,
budget: &mut SessionBudget,
model: &dyn ModelInvoker,
@@ -3008,22 +3089,26 @@ async fn run_turn_cycle(
let mut shown_monitors = Vec::new();
while unlimited || turn < max_turns {
- receive_steering(steering, &mut conversation_messages, run_mode).await;
+ for message in receive_steering(
+ steering,
+ project(&transcript, volatile_system.as_deref(), send_reasoning),
+ run_mode,
+ )
+ .await
+ {
+ transcript.record_message(message);
+ }
let _ = events.send(StreamEvent::Step {
index: (turn as u32) + 1,
max: max_turns as u32,
});
- // A turn this run just produced can carry poison of its own: a
- // length-truncated tool call, or an argument string that decodes to a
- // scalar. A strict upstream rejects the whole request over it, so
- // sanitize per turn -- the next attempt lands on clean history instead
- // of wedging the session. The entry-time pass above cannot see what
- // this run created mid-flight.
- let poisoned = drop_malformed_tool_calls(&mut conversation_messages);
- if poisoned > 0 {
- log::warn!("agent: dropped {poisoned} malformed tool call(s) from the live context");
- }
+ // Nothing is sanitized here any more: a malformed tool call never
+ // enters the record (it is refused where the turn is recorded), and a
+ // history that arrived already carrying one was repaired at the entry -
+ // the one place a caller's array passes through. Sanitizing the live
+ // list used to *rewrite* it, which is what made the record unusable as
+ // a source of truth.
// Background work that finished since the last request reaches the model
// here, as a `<SYSTEM>` reminder rather than an invented tool result:
@@ -3032,7 +3117,7 @@ async fn run_turn_cycle(
let notices = tools.background_notices();
if !notices.is_empty() {
for notice in &notices {
- crate::core::agent::reminder::attach(&mut conversation_messages, &notice.text);
+ transcript.record_reminder(&notice.text);
// The headline is shown at delivery, not when the ping was
// queued, so the transcript reads in the order the model saw
// things (matching Cowork's inbox drain).
@@ -3043,7 +3128,7 @@ async fn run_turn_cycle(
}
}
let _ = events.send(StreamEvent::MessagesUpdated {
- messages: conversation_messages.clone(),
+ messages: project(&transcript, volatile_system.as_deref(), send_reasoning),
});
// A drained ping is how a match or a timeout reaches the display.
publish_monitors(tools, events, &mut shown_monitors);
@@ -3064,45 +3149,44 @@ async fn run_turn_cycle(
loop {
let request_value = build_completion_request(
model_id,
- &conversation_messages,
+ &project(&transcript, volatile_system.as_deref(), send_reasoning),
openai_tools,
json_body,
(turn == 0).then_some(force_first_tool).flatten(),
);
// Once per turn, on the request about to be sent. A prompt still
- // over the trigger after compacting is sent anyway:
- // `compact_conversation` returns its input unchanged when there
- // is nothing safe to drop, and retrying here would spin.
+ // over the trigger after compacting is sent anyway: there is
+ // nothing safe left to drop, and retrying here would spin.
if !preflighted {
preflighted = true;
if let Some(budget) = compaction {
let estimate =
crate::core::agent::compaction::estimate_request_tokens(&request_value);
if estimate > budget.trigger_tokens() {
- let compacted = crate::core::agent::compaction::compact_conversation(
- &conversation_messages,
+ if let Some(dropped) = compact(
+ &mut transcript,
+ crate::core::agent::compaction::DEFAULT_KEEP_RECENT,
model_id,
model,
- crate::core::agent::compaction::DEFAULT_KEEP_RECENT,
)
- .await?;
- if compacted.len() < conversation_messages.len() {
- let dropped = conversation_messages.len() - compacted.len();
+ .await?
+ {
log::info!(
"agent: prompt estimated at {estimate} tokens against a {} \
- token trigger on a {} token window, compacted {} -> {} \
- messages before dispatch",
+ token trigger on a {} token window, compacted {dropped} \
+ messages into a summary before dispatch",
budget.trigger_tokens(),
- budget.context_window,
- conversation_messages.len(),
- compacted.len()
+ budget.context_window
);
- conversation_messages = compacted;
// Published for the same reason the overflow
// path below publishes: a client holding the
// oversized history would send it again next turn.
let _ = events.send(StreamEvent::MessagesUpdated {
- messages: conversation_messages.clone(),
+ messages: project(
+ &transcript,
+ volatile_system.as_deref(),
+ send_reasoning,
+ ),
});
// The one legitimate cache break in a session,
// and the only way the user can tell it apart
@@ -3125,30 +3209,33 @@ async fn run_turn_cycle(
if crate::core::agent::upstream::is_context_overflow_error(&e)
&& attempts < MAX_COMPACTION_ATTEMPTS =>
{
- tools.pre_compact(conversation_messages.len()).await;
- let compacted = crate::core::agent::compaction::compact_conversation(
- &conversation_messages,
- model_id,
- model,
- keep_recent,
- )
- .await?;
- if compacted.len() >= conversation_messages.len() {
- return Err(e);
- }
+ tools
+ .pre_compact(projected_message_count(
+ &transcript,
+ volatile_system.as_deref(),
+ send_reasoning,
+ ))
+ .await;
+ // Nothing safe left to drop: the request is smaller than the
+ // window only in the provider's own maths.
+ let dropped = compact(&mut transcript, keep_recent, model_id, model)
+ .await?
+ .ok_or(e)?;
log::info!(
- "agent: context overflow, compacted {} -> {} messages (attempt {})",
- conversation_messages.len(),
- compacted.len(),
+ "agent: context overflow, compacted {dropped} messages into a \
+ summary (attempt {})",
attempts + 1
);
- conversation_messages = compacted;
// Publish now, not at the end of the run: a retry that
// never recovers returns Err, and an unpublished
// compaction leaves the client holding the oversized
// history that every later turn would re-overflow on.
let _ = events.send(StreamEvent::MessagesUpdated {
- messages: conversation_messages.clone(),
+ messages: project(
+ &transcript,
+ volatile_system.as_deref(),
+ send_reasoning,
+ ),
});
keep_recent = (keep_recent / 2).max(2);
attempts += 1;
@@ -3156,22 +3243,31 @@ async fn run_turn_cycle(
// This provider rejects `reasoning_content` outright rather
// than ignoring it, so the opt-out `[agent].send_reasoning`
// exists for is discovered here instead of having to be
- // configured by hand. Dropping it from the conversation is
- // enough on its own: a provider that rejects the field never
- // streams one either, so no later turn re-adds it. Published
- // so the client's persisted history loses it too, the way the
- // compacted history above is published.
+ // configured by hand. The retry drops the field from the
+ // *request*, not from the record: a route that accepts
+ // reasoning is entitled to what an earlier turn produced,
+ // and which route is asking is a projection option. The
+ // record keeps the reasoning, so nothing is destroyed for
+ // the route that would have accepted it.
Err(e)
if crate::core::agent::upstream::is_reasoning_field_error(&e)
- && body_send_reasoning(json_body)
- && carries_assistant_reasoning(&conversation_messages) =>
+ && send_reasoning
+ && carries_assistant_reasoning(&project(
+ &transcript,
+ volatile_system.as_deref(),
+ send_reasoning,
+ )) =>
{
log::info!(
"agent: upstream rejected reasoning_content, retrying without it"
);
- conversation_messages = strip_assistant_reasoning(&conversation_messages);
+ send_reasoning = false;
let _ = events.send(StreamEvent::MessagesUpdated {
- messages: conversation_messages.clone(),
+ messages: project(
+ &transcript,
+ volatile_system.as_deref(),
+ send_reasoning,
+ ),
});
}
Err(e) => return Err(e),
@@ -3206,14 +3302,22 @@ async fn run_turn_cycle(
// The terminal-boundary handshake also catches input submitted during
// the final model request without starting a separate run.
if steering.is_some() && (unlimited || turn + 1 < max_turns) {
- let mut continued = conversation_messages.clone();
let mut assistant = extract_choice_message(&completion)
.cloned()
.unwrap_or_else(|| serde_json::json!({ "content": final_text }));
assistant["role"] = serde_json::json!("assistant");
- continued.push(assistant);
- if receive_steering(steering, &mut continued, run_mode).await {
- conversation_messages = continued;
+ // The channel is shown the conversation it would be resuming,
+ // turn included, so it can decide to park the run. Nothing is
+ // recorded unless input actually arrives: the record is the
+ // history the model saw, and this turn was never resent.
+ let mut probe = project(&transcript, volatile_system.as_deref(), send_reasoning);
+ probe.push(assistant.clone());
+ let incoming = receive_steering(steering, probe, run_mode).await;
+ if !incoming.is_empty() {
+ transcript.record_message(assistant);
+ for message in incoming {
+ transcript.record_message(message);
+ }
turn += 1;
continue;
}
@@ -3225,18 +3329,15 @@ async fn run_turn_cycle(
{
if let Some(summary) = open_todo_summary(todo_registry).await {
closeout_nudged = true;
- conversation_messages.push(serde_json::json!({
+ transcript.record_message(serde_json::json!({
"role": "assistant",
"content": final_text,
}));
- crate::core::agent::reminder::attach(
- &mut conversation_messages,
- &format!(
- "Before you stop: these todos are still open:\n{summary}\n\nFor each \
- one you actually completed, call `todo` with `done` now (or `drop` if \
- you skipped it). If work genuinely remains, continue it instead."
- ),
- );
+ transcript.record_reminder(&format!(
+ "Before you stop: these todos are still open:\n{summary}\n\nFor each \
+ one you actually completed, call `todo` with `done` now (or `drop` if \
+ you skipped it). If work genuinely remains, continue it instead."
+ ));
turn += 1;
continue;
}
@@ -3261,7 +3362,7 @@ async fn run_turn_cycle(
// queued pings), and resuming on that would spend a turn asking
// the model to react to nothing.
if tools.background_pending() {
- conversation_messages.push(serde_json::json!({
+ transcript.record_message(serde_json::json!({
"role": "assistant",
"content": final_text,
}));
@@ -3277,35 +3378,39 @@ async fn run_turn_cycle(
// The reactive path above cannot help with that -- it only fires
// once an upstream has already rejected a request.
//
- // Only when it actually shrinks: `compact_conversation` returns the
- // input untouched when there is too little to drop, and publishing
- // an unchanged history would spend a summarizer call for nothing.
+ // Only when there is something to drop: a plan that
+ // covers nothing would spend a summarizer call to publish an
+ // unchanged history.
if budget.exhausted() {
- tools.pre_compact(conversation_messages.len()).await;
- match crate::core::agent::compaction::compact_conversation(
- &conversation_messages,
+ tools
+ .pre_compact(projected_message_count(
+ &transcript,
+ volatile_system.as_deref(),
+ send_reasoning,
+ ))
+ .await;
+ match compact(
+ &mut transcript,
+ crate::core::agent::compaction::DEFAULT_KEEP_RECENT,
model_id,
model,
- crate::core::agent::compaction::DEFAULT_KEEP_RECENT,
)
.await
{
- Ok(compacted) if compacted.len() < conversation_messages.len() => {
+ Ok(Some(dropped)) => {
log::info!(
- "agent: budget exhausted at end of run, compacted {} -> {} messages",
- conversation_messages.len(),
- compacted.len()
+ "agent: budget exhausted at end of run, compacted {dropped} messages \
+ into a summary"
);
- conversation_messages = compacted;
}
- Ok(_) => {}
+ Ok(None) => {}
Err(error) => {
log::warn!("agent: budget exhausted but compaction failed: {error}");
}
}
}
let _ = events.send(StreamEvent::MessagesUpdated {
- messages: conversation_messages.clone(),
+ messages: project(&transcript, volatile_system.as_deref(), send_reasoning),
});
return Ok(completion);
}
@@ -3322,7 +3427,7 @@ async fn run_turn_cycle(
// is the shape a model will imitate unprompted on later turns.
if budget.exhausted() && !budget_notice_recorded {
budget_notice_recorded = true;
- conversation_messages.push(serde_json::json!({
+ transcript.record_message(serde_json::json!({
"role": "system",
"content": format!(
"[session token budget exhausted ({} tokens)] The configured \
@@ -3331,7 +3436,7 @@ async fn run_turn_cycle(
),
}));
let _ = events.send(StreamEvent::MessagesUpdated {
- messages: conversation_messages.clone(),
+ messages: project(&transcript, volatile_system.as_deref(), send_reasoning),
});
}
@@ -3368,7 +3473,7 @@ async fn run_turn_cycle(
// for the specific model that needs it (scoped, content preserved), so
// the agent can speak standard OpenAI tool protocol on the wire again.
// See janhq/jan-internal#238.
- if let Some(choice_message) = extract_choice_message(&completion) {
+ let assistant_turn = if let Some(choice_message) = extract_choice_message(&completion) {
let assistant_content = choice_message
.get("content")
.cloned()
@@ -3388,14 +3493,18 @@ async fn run_turn_cycle(
{
msg["reasoning_content"] = serde_json::json!(r);
}
- conversation_messages.push(msg);
+ msg
} else {
- conversation_messages.push(serde_json::json!({
+ serde_json::json!({
"role": "assistant",
"content": serde_json::Value::Null,
"tool_calls": tool_calls.clone()
- }));
- }
+ })
+ };
+ // Recording is the gate that keeps poison out of the record: a call the
+ // model emitted with unparsable arguments is never resent, and the ids
+ // it answered are what the results below are matched against.
+ let dropped_tool_ids = record_assistant_turn(&mut transcript, &assistant_turn);
// A `length` finish means the model was cut off mid-emission, so the
// streamed tool-call arguments may be silently truncated. Executing them
@@ -3418,7 +3527,13 @@ async fn run_turn_cycle(
is_error: true,
diff: None,
});
- conversation_messages.push(serde_json::json!({
+ // A truncated call whose arguments no longer parse never made it
+ // into the record, so neither does its result: an orphaned tool
+ // message is invalid on its own.
+ if dropped_tool_ids.iter().any(|dropped| dropped == &id) {
+ continue;
+ }
+ transcript.record_message(serde_json::json!({
"role": "tool",
"tool_call_id": id,
"content": content
@@ -3428,29 +3543,31 @@ async fn run_turn_cycle(
continue;
}
- // Invariant: a tool call whose arguments do not decode to a plain
- // JSON object is never executed. A truncated stream or a confused
- // model would otherwise run a tool with invented or empty arguments.
- // The call fails visibly instead, and the per-request sanitizer keeps
- // the malformed call out of the history the next request carries.
+ // Invariant: a tool call the record cannot hold is never executed. A
+ // call whose arguments do not decode to a plain JSON object is one a
+ // truncated stream or a confused model would run with invented or empty
+ // arguments; a call with no non-empty id is one whose result would be a
+ // `role: "tool"` message paired with nothing. Both fail visibly instead
+ // of running, and the per-request sanitizer keeps them out of the
+ // history the next request carries.
let executable: Vec<serde_json::Value> = tool_calls
.iter()
- .filter(|tc| arguments_are_executable(tc))
+ .filter(|tc| tool_call_is_usable(tc))
.cloned()
.collect();
let mut error_outcomes: Vec<ToolOutcome> = tool_calls
.iter()
- .filter(|tc| !arguments_are_executable(tc))
+ .filter(|tc| !tool_call_is_usable(tc))
.map(|tc| {
- ToolOutcome::plain(
- tc.get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string(),
+ let id = pairable_tool_call_id(tc).unwrap_or_default();
+ let reason = if id.is_empty() {
+ "ERROR: tool call had no id; the call was not executed and its result would \
+ have nothing to pair with. Re-emit it as a tool call carrying an id."
+ } else {
"ERROR: tool-call arguments are not a plain JSON object; the call was not \
executed. Re-emit it with the arguments as a JSON object."
- .to_string(),
- )
+ };
+ ToolOutcome::plain(id.to_string(), reason.to_string())
})
.collect();
let mut tool_results: Vec<ToolOutcome> = if executable.is_empty() {
@@ -3527,11 +3644,16 @@ async fn run_turn_cycle(
}
serde_json::Value::Array(parts)
};
- conversation_messages.push(serde_json::json!({
- "role": "tool",
- "tool_call_id": id,
- "content": wire_content
- }));
+ // A result whose call was refused entry to the record would be an
+ // orphaned tool message on the next request: the call it answers is
+ // not there any more.
+ if !dropped_tool_ids.iter().any(|dropped| dropped == &id) {
+ transcript.record_message(serde_json::json!({
+ "role": "tool",
+ "tool_call_id": id,
+ "content": wire_content
+ }));
+ }
}
if todo_touched_this_batch {
mutations_since_todo_touch = 0;
@@ -3560,14 +3682,11 @@ async fn run_turn_cycle(
mutations_since_todo_touch = 0;
mid_run_nudge_count += 1;
let plural = if open_count == 1 { "" } else { "s" };
- crate::core::agent::reminder::attach(
- &mut conversation_messages,
- &format!(
- "Reminder: {open_count} todo item{plural} still open. If you finished a \
- task since the last todo update, mark it done now so progress stays \
- visible; otherwise just keep working."
- ),
- );
+ transcript.record_reminder(&format!(
+ "Reminder: {open_count} todo item{plural} still open. If you finished a \
+ task since the last todo update, mark it done now so progress stays \
+ visible; otherwise just keep working."
+ ));
}
}
@@ -3604,23 +3723,35 @@ mod tests {
})];
let body = json!({});
- let mut turn1 = vec![json!({"role": "user", "content": "first"})];
- set_system_prompt(&mut turn1, "STABLE PREFIX");
- insert_volatile_system(&mut turn1, "Today's date is 2026-09-16.");
- let req1 = build_completion_request("m", &turn1, &tools, &body, None);
+ // Two turns of the same session: the conversation grew and the volatile
+ // block differs. Both go through the projection, which is where the
+ // request is built from now on.
+ let volatile1 = "Today's date is 2026-09-16.";
+ let volatile2 = "Today's date is 2026-09-17.\n\n# Recalled memory\n- a note";
- // A later turn: the conversation has grown and the volatile block differs.
- let mut turn2 = vec![
+ let mut first = Transcript::from_history(vec![json!({"role": "user", "content": "first"})]);
+ first.record_prompt("STABLE PREFIX");
+ let req1 = build_completion_request(
+ "m",
+ &project(&first, Some(volatile1), true),
+ &tools,
+ &body,
+ None,
+ );
+
+ let mut second = Transcript::from_history(vec![
json!({"role": "user", "content": "first"}),
json!({"role": "assistant", "content": "reply"}),
json!({"role": "user", "content": "second"}),
- ];
- set_system_prompt(&mut turn2, "STABLE PREFIX");
- insert_volatile_system(
- &mut turn2,
- "Today's date is 2026-09-17.\n\n# Recalled memory\n- a note",
+ ]);
+ second.record_prompt("STABLE PREFIX");
+ let req2 = build_completion_request(
+ "m",
+ &project(&second, Some(volatile2), true),
+ &tools,
+ &body,
+ None,
);
- let req2 = build_completion_request("m", &turn2, &tools, &body, None);
let node0 = |r: &serde_json::Value| serde_json::to_string(&r["messages"][0]).unwrap();
let tools_of = |r: &serde_json::Value| serde_json::to_string(&r["tools"]).unwrap();
@@ -3632,6 +3763,40 @@ mod tests {
);
}
+ /// The record gate names every call it refuses, empty id included: the
+ /// caller skips results by that list, and a result left behind is the
+ /// orphan a strict upstream rejects the whole request over.
+ #[test]
+ fn a_tool_call_without_an_id_is_refused_entry_and_named_for_its_result() {
+ let mut transcript = Transcript::default();
+ let turn = json!({
+ "role": "assistant",
+ "content": "on it",
+ "tool_calls": [
+ { "type": "function", "function": { "name": "bash", "arguments": "{\"command\":\"ls\"}" } },
+ { "id": "call_ok", "type": "function", "function": { "name": "read", "arguments": "{}" } },
+ ]
+ });
+
+ let dropped = record_assistant_turn(&mut transcript, &turn);
+ assert_eq!(
+ dropped,
+ vec![String::new()],
+ "the empty id is what the refused call's result will carry"
+ );
+
+ let crate::core::agent::transcript::Event::Message(recorded) = &transcript.events()[0]
+ else {
+ panic!("the assistant turn is recorded");
+ };
+ let calls = recorded["tool_calls"]
+ .as_array()
+ .expect("the usable call stays");
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0]["id"], "call_ok");
+ assert_eq!(recorded["content"], "on it");
+ }
+
struct MockModel {
responses: StdMutex<VecDeque<serde_json::Value>>,
// Every request this mock was invoked with, in order -- lets a test
@@ -3851,7 +4016,9 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({"role": "user", "content": "start"})],
+ Transcript::from_history(vec![json!({"role": "user", "content": "start"})]),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -3904,7 +4071,9 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({"role": "user", "content": "start"})],
+ Transcript::from_history(vec![json!({"role": "user", "content": "start"})]),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -3935,16 +4104,17 @@ mod tests {
async fn steering_disconnected_surface_does_not_block_the_loop() {
let (steering, receiver) = mpsc::unbounded_channel();
drop(receiver);
- let mut messages = vec![json!({"role": "user", "content": "start"})];
+ let messages = vec![json!({"role": "user", "content": "start"})];
assert!(
- !receive_steering(
+ receive_steering(
Some(&steering),
- &mut messages,
+ messages,
crate::core::agent::plan::RunMode::Normal
)
.await
+ .is_empty(),
+ "a disconnected steering surface contributes nothing"
);
- assert_eq!(messages.len(), 1);
}
#[tokio::test]
@@ -3963,7 +4133,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -4069,7 +4241,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -4144,7 +4318,9 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({ "role": "user", "content": "hi" })],
+ Transcript::from_history(vec![json!({ "role": "user", "content": "hi" })]),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -4217,7 +4393,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -4277,7 +4455,9 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({ "role": "user", "content": "edit the file" })],
+ Transcript::from_history(vec![json!({ "role": "user", "content": "edit the file" })]),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -4398,7 +4578,9 @@ mod tests {
&json!({}),
"m",
&[],
- poisoned,
+ Transcript::from_history(poisoned),
+ None,
+ true,
8,
&mut SessionBudget::new(None),
&healed,
@@ -4435,7 +4617,9 @@ mod tests {
&json!({}),
"m",
&[crate::core::agent::todo::todo_tool_schema()],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -4589,8 +4773,8 @@ mod tests {
/// How many mid-run nudges are present in this request's history. Counting
/// messages (not requests) is what the per-cycle cap actually bounds: an
- /// injected nudge stays in `conversation_messages`, so every later request
- /// carries it and counting requests would grow with the turn count.
+ /// injected nudge stays in the transcript, so every later request carries
+ /// it and counting requests would grow with the turn count.
fn nudge_message_count(request: &serde_json::Value) -> usize {
request["messages"]
.as_array()
@@ -4631,7 +4815,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
0,
&mut budget,
&model,
@@ -4709,7 +4895,9 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({ "role": "user", "content": "go" })],
+ Transcript::from_history(vec![json!({ "role": "user", "content": "go" })]),
+ None,
+ true,
0,
&mut budget,
&model,
@@ -4755,7 +4943,9 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({ "role": "user", "content": "go" })],
+ Transcript::from_history(vec![json!({ "role": "user", "content": "go" })]),
+ None,
+ true,
0,
&mut budget,
&model,
@@ -4792,7 +4982,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
0,
&mut budget,
&model,
@@ -4845,7 +5037,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
0,
&mut budget,
&model,
@@ -4934,7 +5128,9 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({ "role": "user", "content": "look into it" })],
+ Transcript::from_history(vec![json!({ "role": "user", "content": "look into it" })]),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -4988,7 +5184,9 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({ "role": "user", "content": "go" })],
+ Transcript::from_history(vec![json!({ "role": "user", "content": "go" })]),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5087,7 +5285,11 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({ "role": "user", "content": "watch the build" })],
+ Transcript::from_history(vec![
+ json!({ "role": "user", "content": "watch the build" }),
+ ]),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5136,7 +5338,11 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({ "role": "user", "content": "watch the build" })],
+ Transcript::from_history(vec![
+ json!({ "role": "user", "content": "watch the build" }),
+ ]),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5230,7 +5436,9 @@ mod tests {
&json!({}),
"m",
&[],
- vec![json!({ "role": "user", "content": "hi" })],
+ Transcript::from_history(vec![json!({ "role": "user", "content": "hi" })]),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5287,7 +5495,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5392,7 +5602,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5460,7 +5672,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5540,7 +5754,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5559,11 +5775,12 @@ mod tests {
}
/// A strict endpoint rejects the DeepSeek `reasoning_content` extension
- /// instead of ignoring it. The turn must recover by dropping the field and
- /// retrying, and hand the stripped conversation to the client so its
- /// persisted history stops carrying it.
+ /// instead of ignoring it. The turn must recover by projecting the request
+ /// without the field and retrying, and hand the client the projection the
+ /// retry used; the record keeps the reasoning, so a route that accepts it
+ /// still gets what the earlier turn produced.
#[tokio::test]
- async fn turn_cycle_strips_reasoning_and_retries_when_the_upstream_rejects_it() {
+ async fn turn_cycle_retries_without_reasoning_when_the_upstream_rejects_it() {
let (tx, mut rx) = mpsc::unbounded_channel();
let model = ResultQueueModel {
results: StdMutex::new(
@@ -5589,7 +5806,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5620,9 +5839,10 @@ mod tests {
);
}
- /// The retry is one-shot by construction: once stripped, nothing carries the
- /// field, so a provider that keeps rejecting fails the turn instead of
- /// resending the same request forever.
+ /// The retry is one-shot by construction: nothing is destroyed when the field
+ /// is dropped from the failed request, so the retry sends the same bytes
+ /// minus that field, and a provider that keeps rejecting fails the turn
+ /// instead of resending the same request forever.
#[tokio::test]
async fn a_persistent_reasoning_rejection_fails_the_turn() {
let (tx, _rx) = mpsc::unbounded_channel();
@@ -5643,7 +5863,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5660,7 +5882,7 @@ mod tests {
assert_eq!(
model.results.lock().unwrap().len(),
1,
- "exactly one retry after the strip"
+ "exactly one retry without the field"
);
}
@@ -5708,7 +5930,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5766,7 +5990,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5818,7 +6044,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
8,
&mut budget,
&model,
@@ -5857,7 +6085,9 @@ mod tests {
&json!({}),
"m",
&[],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
0,
&mut budget,
&model,
@@ -7102,7 +7332,9 @@ mod tests {
&json!({}),
"m",
&[crate::core::agent::interaction::ask_tool_schema()],
- convo,
+ Transcript::from_history(convo),
+ None,
+ true,
0,
&mut budget,
model.as_ref(),
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index 8bf3314f9..d0b6c9438 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -37,6 +37,7 @@ pub mod skill_hub;
pub mod skills;
pub mod subagent;
pub mod todo;
+pub mod transcript;
pub mod upstream;
/// Render a path for embedding in a hook/plugin-tool shell command in tests.
diff --git a/src-tauri/src/core/agent/transcript.rs b/src-tauri/src/core/agent/transcript.rs
new file mode 100644
index 000000000..fd42002b2
--- /dev/null
+++ b/src-tauri/src/core/agent/transcript.rs
@@ -0,0 +1,707 @@
+//! The canonical transcript: what happened, and the request it projects to.
+//!
+//! Jan used to keep one message list and give it three jobs at once - it was
+//! the wire request, the stored transcript, and the thing compaction rewrote.
+//! Compaction therefore *replaced* history: the span it summarized was gone
+//! from every one of them, so a user asking "what exactly did that command
+//! print two hours ago" got the summary's paraphrase, and no later turn could
+//! re-derive the prefix that a different provider, a resumed session, or a
+//! changed `keep_recent` would need.
+//!
+//! This module splits the three jobs:
+//!
+//! ```text
+//! Transcript (append-only) the record: events, never rewritten
+//! |
+//! | project(&Projection) pure: same record + same options = same bytes
+//! v
+//! Vec<Value> (the wire request) placed prompt + history + summarized spans
+//! ```
+//!
+//! Three rules hold it together:
+//!
+//! - **The record is append-only.** Every mutator pushes; nothing removes or
+//! edits an event. A compaction point is a *boundary*, not a deletion: the
+//! events it stands in for stay in the record, and `project` is what omits
+//! them.
+//! - **The wire shape is projection-owned.** Where the stable prompt sits, how
+//! a changed prompt lands behind the history instead of rewriting the head
+//! (see [`crate::core::agent::upstream::set_system_prompt`]), how per-turn
+//! context occupies its slot, and whether a prior turn's reasoning is resent
+//! are all parameters of [`Projection`], not edits to the record.
+//! - **`project` is pure.** Two calls over an unchanged record with the same
+//! options produce byte-identical output, which is the property the
+//! prefix-stability suite asserts against.
+
+use serde_json::Value;
+
+use crate::core::agent::compaction::is_compaction_summary;
+use crate::core::agent::r#loop::strip_assistant_reasoning;
+use crate::core::agent::reminder;
+use crate::core::agent::upstream::{
+ drop_malformed_tool_calls, drop_orphaned_tool_results, insert_volatile_system, is_system_node,
+ repair_dangling_tool_calls, set_system_prompt,
+};
+
+/// One thing that happened, in the order it happened.
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) enum Event {
+ /// A wire message as it entered the conversation.
+ Message(Value),
+ /// A stable system prompt, in the order it was applied. The first one is
+ /// the request's head; a later one is appended behind the history so the
+ /// bytes an earlier request already sent are left alone.
+ Prompt(String),
+ /// Per-turn context that has no turn of its own: a background notice, a
+ /// todo nudge. Folded into the trailing message at projection time (see
+ /// [`crate::core::agent::reminder::attach`]) rather than recorded as one,
+ /// so the record keeps what actually arrived.
+ Reminder(String),
+ /// A summary standing in for every event recorded before it. `covers` is
+ /// the record index the kept tail begins at - a projection boundary, not a
+ /// deletion: the events before it are still in the record.
+ Compaction { summary: Value, covers: usize },
+}
+
+/// The record of a session.
+#[derive(Debug, Clone, Default)]
+pub(crate) struct Transcript {
+ events: Vec<Event>,
+}
+
+/// What the wire needs that is not in the record.
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct Projection<'a> {
+ /// The per-turn context block (today's date, query-specific memory recall,
+ /// plan/todo state). Per-turn by nature: it is placed in its slot and
+ /// replaced when it changes, unlike the stable prompt behind which the
+ /// cached prefix sits.
+ pub volatile_system: Option<&'a str>,
+ /// Resend a prior assistant turn's `reasoning_content`. `false` is a
+ /// provider capability answer ("this route rejects the field"), so it
+ /// belongs here rather than in the record: the turn that discovered it
+ /// must not destroy the reasoning the next route might accept.
+ pub send_reasoning: bool,
+}
+
+/// A compaction waiting to be recorded: what to summarize, and how much of the
+/// record the summary will stand in for.
+#[derive(Debug, Clone)]
+pub(crate) struct CompactionPlan {
+ /// The wire messages to hand the summarizer, in order.
+ pub summarize: Vec<Value>,
+ /// Record index the kept tail begins at, i.e. the number of events the
+ /// summary covers.
+ pub covers: usize,
+}
+
+impl Transcript {
+ /// Adopt a history that came from outside (a client's stored thread, a
+ /// caller's request body).
+ ///
+ /// This is the one boundary every incoming message array passes through,
+ /// so it is where the record heals: a tool call a truncated stream left
+ /// with unparsable arguments is refused entry, the result it orphaned goes
+ /// with it, a result whose call is not in the history at all is dropped,
+ /// and a surviving call that lost its result gets the synthetic error
+ /// reply. Every one of those shapes wedges a session - providers 422 the
+ /// whole request - and healing here means the record only ever holds turns
+ /// a strict upstream accepts.
+ ///
+ /// Two kinds of node are then read rather than recorded verbatim:
+ ///
+ /// - a stable prompt node becomes a [`Event::Prompt`], so the projection
+ /// places it the way the live list did (head, or appended behind the
+ /// history when it changed);
+ /// - the per-turn block in its slot is dropped: it is projection input,
+ /// regenerated from the current turn, and recording it would accumulate
+ /// yesterday's date in the history.
+ ///
+ /// A compaction summary is neither: it is history under the `system` role,
+ /// and it stays.
+ pub(crate) fn from_history(mut messages: Vec<Value>) -> Self {
+ let poisoned = drop_malformed_tool_calls(&mut messages);
+ if poisoned > 0 {
+ log::warn!("agent: dropped {poisoned} unusable tool call(s) from history");
+ }
+ let orphaned = drop_orphaned_tool_results(&mut messages);
+ if orphaned > 0 {
+ log::warn!("agent: dropped {orphaned} tool result(s) whose call is not in the history");
+ }
+ let repaired = repair_dangling_tool_calls(&mut messages);
+ if repaired > 0 {
+ log::warn!("agent: repaired {repaired} dangling tool call(s) with no prior result");
+ }
+
+ let volatile = volatile_index(&messages);
+ let mut events = Vec::with_capacity(messages.len());
+ for (index, message) in messages.into_iter().enumerate() {
+ if Some(index) == volatile {
+ continue;
+ }
+ events.push(
+ if is_system_node(&message) && !is_compaction_summary(&message) {
+ match message.get("content").and_then(|c| c.as_str()) {
+ Some(text) => Event::Prompt(text.to_string()),
+ None => Event::Message(message),
+ }
+ } else {
+ Event::Message(message)
+ },
+ );
+ }
+ Self { events }
+ }
+
+ /// Append a wire message (a user turn, an assistant turn, a tool result).
+ pub(crate) fn record_message(&mut self, message: Value) {
+ self.events.push(Event::Message(message));
+ }
+
+ /// Append a stable system prompt. Recording the same text twice is
+ /// harmless: the projection deduplicates it the way the live list did.
+ pub(crate) fn record_prompt(&mut self, text: &str) {
+ self.events.push(Event::Prompt(text.to_string()));
+ }
+
+ /// Append per-turn context to be folded into the trailing message.
+ pub(crate) fn record_reminder(&mut self, text: &str) {
+ self.events.push(Event::Reminder(text.to_string()));
+ }
+
+ /// Record a compaction point: `summary` stands in for the first `covers`
+ /// events, which stay in the record.
+ pub(crate) fn record_compaction(&mut self, summary: Value, covers: usize) {
+ debug_assert!(covers <= self.events.len(), "covers must be a record index");
+ self.events.push(Event::Compaction {
+ summary,
+ covers: covers.min(self.events.len()),
+ });
+ }
+
+ /// The record, in order. Read by the tests that assert nothing recorded is
+ /// ever lost, and by callers that need the pre-compaction span.
+ #[cfg(test)]
+ pub(crate) fn events(&self) -> &[Event] {
+ &self.events
+ }
+
+ /// How many events the summary of the latest compaction point stands in
+ /// for, i.e. where its projection begins.
+ fn boundary(&self) -> usize {
+ self.events
+ .iter()
+ .rev()
+ .find_map(|event| match event {
+ Event::Compaction { covers, .. } => Some(*covers),
+ _ => None,
+ })
+ .unwrap_or(0)
+ }
+
+ /// The record's contribution to the request, before the prompt is placed:
+ /// every event the boundary does not cover, in order, with the record index
+ /// each message came from.
+ ///
+ /// The index is what lets a compaction boundary computed over *messages*
+ /// (which is where the tool-pairing rule lives) be written back as a
+ /// *record* index.
+ fn conversation(&self) -> (Vec<Value>, Vec<usize>) {
+ let boundary = self.boundary();
+ let mut messages = Vec::with_capacity(self.events.len());
+ let mut sources = Vec::with_capacity(self.events.len());
+ // The summary stands at the head of the range it covers. A compaction
+ // point is recorded *after* the tail it kept - the tail was already in
+ // the record - so its position in the record is not its position in the
+ // projection.
+ if let Some(summary) = self.latest_summary() {
+ messages.push(summary.clone());
+ sources.push(boundary);
+ }
+ for (index, event) in self.events.iter().enumerate().skip(boundary) {
+ match event {
+ Event::Message(message) => {
+ messages.push(message.clone());
+ sources.push(index);
+ }
+ Event::Reminder(text) => {
+ // `attach` may append to the message already there or push
+ // one of its own; either way everything it wrote came from
+ // this event, so the boundary can land on it.
+ reminder::attach(&mut messages, text);
+ sources.resize(messages.len(), index);
+ }
+ Event::Prompt(_) | Event::Compaction { .. } => {}
+ }
+ }
+ (messages, sources)
+ }
+
+ /// The summary of the most recent compaction point. Earlier ones are inside
+ /// the range it covers, and it was summarized from a projection that
+ /// already carried them.
+ fn latest_summary(&self) -> Option<&Value> {
+ self.events.iter().rev().find_map(|event| match event {
+ Event::Compaction { summary, .. } => Some(summary),
+ _ => None,
+ })
+ }
+
+ /// Prompts remain active even when compaction covers the conversation
+ /// around them. The initial prompt is recorded after the incoming history,
+ /// and later updates can occur anywhere, so retain all covered prompts in
+ /// their original order rather than only a leading run of prompt events.
+ fn prompts_before(&self, boundary: usize) -> impl Iterator<Item = &str> {
+ self.events
+ .iter()
+ .take(boundary)
+ .filter_map(|event| match event {
+ Event::Prompt(text) => Some(text.as_str()),
+ _ => None,
+ })
+ }
+
+ /// The request this record projects to. Pure: same record, same options,
+ /// same bytes.
+ pub(crate) fn project(&self, projection: &Projection<'_>) -> Vec<Value> {
+ let boundary = self.boundary();
+ let mut out = Vec::with_capacity(self.events.len() + 1);
+ let mut volatile_placed = false;
+
+ for text in self.prompts_before(boundary) {
+ set_system_prompt(&mut out, text);
+ if !volatile_placed {
+ volatile_placed = self.place_volatile(&mut out, projection);
+ }
+ }
+
+ if let Some(summary) = self.latest_summary() {
+ out.push(summary.clone());
+ }
+
+ for event in self.events.iter().skip(boundary) {
+ match event {
+ Event::Message(message) => out.push(message.clone()),
+ Event::Reminder(text) => reminder::attach(&mut out, text),
+ Event::Prompt(text) => {
+ set_system_prompt(&mut out, text);
+ if !volatile_placed {
+ volatile_placed = self.place_volatile(&mut out, projection);
+ }
+ }
+ // Already emitted ahead of the range it covers.
+ Event::Compaction { .. } => {}
+ }
+ }
+ if !volatile_placed {
+ self.place_volatile(&mut out, projection);
+ }
+
+ if !projection.send_reasoning {
+ out = strip_assistant_reasoning(&out);
+ }
+ out
+ }
+
+ /// Put this turn's context block where it belongs and report whether it
+ /// went somewhere. A run with no stable prompt has no head to sit behind,
+ /// so the block stands in as node zero - the same arrangement the live list
+ /// used.
+ fn place_volatile(&self, out: &mut Vec<Value>, projection: &Projection<'_>) -> bool {
+ let Some(text) = projection.volatile_system.filter(|text| !text.is_empty()) else {
+ return false;
+ };
+ if out.iter().any(is_system_node) {
+ insert_volatile_system(out, text);
+ } else {
+ set_system_prompt(out, text);
+ }
+ true
+ }
+
+ /// What a compaction would summarize, and how far into the record its
+ /// summary would reach. `None` when there is nothing safe to drop, which is
+ /// how the caller detects a no-op instead of retrying.
+ ///
+ /// The boundary itself is computed by
+ /// [`crate::core::agent::compaction::tail_start`] over the messages, where
+ /// the tool-pairing rule lives.
+ pub(crate) fn compaction_plan(&self, keep_recent: usize) -> Option<CompactionPlan> {
+ let (messages, sources) = self.conversation();
+ if messages.len() <= keep_recent {
+ return None;
+ }
+ let cut =
+ crate::core::agent::compaction::tail_start(&messages, messages.len() - keep_recent)?;
+ Some(CompactionPlan {
+ // Only the conversation is summarized: the prompt is not history,
+ // it is placed around it.
+ summarize: messages[..cut].to_vec(),
+ covers: sources[cut],
+ })
+ }
+}
+
+/// Index of the per-turn block in a history that came from outside, if it has
+/// one: the slot the prompt writer owns, i.e. index 1 once a system node holds
+/// index 0. A summary that happens to occupy the slot is history, not a block.
+fn volatile_index(messages: &[Value]) -> Option<usize> {
+ let slot = usize::from(messages.first().is_some_and(is_system_node));
+ messages
+ .get(slot)
+ .filter(|message| is_system_node(message) && !is_compaction_summary(message))
+ .map(|_| slot)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn convo(turns: usize) -> Vec<Value> {
+ (0..turns)
+ .map(|i| {
+ json!({
+ "role": if i % 2 == 0 { "user" } else { "assistant" },
+ "content": format!("message {i}"),
+ })
+ })
+ .collect()
+ }
+
+ fn nothing() -> Projection<'static> {
+ Projection {
+ volatile_system: None,
+ send_reasoning: true,
+ }
+ }
+
+ /// The property the prefix-stability suite leans on: projecting the same
+ /// record twice produces the same bytes, so a request that changed nothing
+ /// cannot invalidate its own prefix.
+ #[test]
+ fn projecting_twice_yields_byte_identical_output() {
+ let mut transcript = Transcript::from_history(convo(6));
+ transcript.record_prompt("you are a careful agent");
+ transcript.record_message(json!({"role": "user", "content": "and now?"}));
+ transcript.record_reminder("Reminder: 2 todos are still open.");
+ let projection = Projection {
+ volatile_system: Some("Today's date is 2026-09-18."),
+ send_reasoning: true,
+ };
+ let first = transcript.project(&projection);
+ let second = transcript.project(&projection);
+ assert_eq!(
+ serde_json::to_string(&first).unwrap(),
+ serde_json::to_string(&second).unwrap()
+ );
+ }
+
+ /// A compaction point omits the span it stands in for without deleting it:
+ /// the projection carries the summary and the kept tail, and the record
+ /// still holds every message the summary replaced.
+ #[test]
+ fn a_compaction_point_keeps_the_span_it_replaced() {
+ let mut transcript = Transcript::from_history(convo(20));
+ let plan = transcript
+ .compaction_plan(4)
+ .expect("20 messages are worth compacting");
+ assert_eq!(plan.summarize.len(), 16);
+ transcript.record_compaction(
+ json!({"role": "system", "content": "[Summary] they talked about 0..15"}),
+ plan.covers,
+ );
+
+ let projected = transcript.project(&nothing());
+ assert_eq!(
+ projected[0]["content"], "[Summary] they talked about 0..15",
+ "the summary stands at the head of the history: {projected:?}"
+ );
+ assert_eq!(
+ projected.len(),
+ 1 + (20 - plan.summarize.len()),
+ "the kept tail follows the summary: {projected:?}"
+ );
+ assert_eq!(
+ projected[1]["content"],
+ format!("message {}", plan.summarize.len()),
+ "the tail begins where the summary stops: {projected:?}"
+ );
+
+ // ...and nothing the summary covers left the record.
+ let recorded: Vec<&Value> = transcript
+ .events()
+ .iter()
+ .filter_map(|event| match event {
+ Event::Message(message) => Some(message),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(recorded.len(), 20);
+ for (index, message) in recorded.iter().take(16).enumerate() {
+ assert_eq!(message["content"], format!("message {index}"));
+ }
+ }
+
+ /// The adoption boundary heals the shape no other pass can see: a
+ /// `role: "tool"` result whose call is not in the history at all. A strict
+ /// upstream rejects the whole request over that one orphan, so the record
+ /// must never take it in.
+ #[test]
+ fn from_history_drops_a_tool_result_whose_call_is_not_there() {
+ let transcript = Transcript::from_history(vec![
+ json!({ "role": "user", "content": "carry on" }),
+ json!({ "role": "tool", "tool_call_id": "call_gone", "content": "left behind" }),
+ json!({ "role": "assistant", "content": "as you asked" }),
+ ]);
+
+ let projected = transcript.project(&nothing());
+ assert_eq!(
+ projected.len(),
+ 2,
+ "the orphaned result never reaches the wire: {projected:?}"
+ );
+ assert_eq!(projected[0]["content"], "carry on");
+ assert_eq!(projected[1]["content"], "as you asked");
+ }
+
+ /// The reasoning retry is a projection option: a route that rejects the
+ /// field changes what goes on the wire, not what was recorded.
+ #[test]
+ fn dropping_reasoning_is_a_projection_option_not_a_record_edit() {
+ let mut transcript = Transcript::default();
+ transcript.record_message(json!({
+ "role": "assistant",
+ "content": "the answer",
+ "reasoning_content": "the thinking",
+ }));
+
+ let sent = transcript.project(&nothing());
+ assert_eq!(sent[0]["reasoning_content"], "the thinking");
+
+ let stripped = transcript.project(&Projection {
+ volatile_system: None,
+ send_reasoning: false,
+ });
+ assert!(stripped[0].get("reasoning_content").is_none());
+ assert_eq!(stripped[0]["content"], "the answer");
+
+ // A later route that accepts the field gets it back: the record kept it.
+ let again = transcript.project(&nothing());
+ assert_eq!(again[0]["reasoning_content"], "the thinking");
+ }
+
+ /// A reminder takes no turn of its own on the wire, but it is still an
+ /// event: the record keeps it, the projection folds it into the message it
+ /// belongs to.
+ #[test]
+ fn reminders_are_recorded_and_folded_at_projection_time() {
+ let mut transcript = Transcript::default();
+ transcript.record_message(json!({"role": "user", "content": "hello"}));
+ transcript.record_reminder("Reminder: 1 todo is still open.");
+
+ let projected = transcript.project(&nothing());
+ assert_eq!(projected.len(), 1, "no extra turn: {projected:?}");
+ let content = projected[0]["content"].as_str().unwrap();
+ assert!(content.starts_with("hello"), "{content}");
+ assert!(
+ content.contains("Reminder: 1 todo is still open."),
+ "{content}"
+ );
+
+ assert_eq!(
+ transcript.events().len(),
+ 2,
+ "both events are in the record"
+ );
+ }
+
+ /// A history from outside carries the previous turn's blocks: the stable
+ /// prompt is read back as a `Prompt` event (so it is placed the same way),
+ /// the per-turn block is not recorded at all (it is regenerated), and a
+ /// compaction summary stays as history.
+ #[test]
+ fn from_history_splits_the_previous_turns_wire_shape() {
+ let summary = format!("{} stuff", crate::core::agent::compaction::SUMMARY_MARKER);
+ let history = vec![
+ json!({"role": "system", "content": "stable prompt"}),
+ json!({"role": "system", "content": "Today's date is 2026-09-17."}),
+ json!({"role": "system", "content": summary}),
+ json!({"role": "user", "content": "carry on"}),
+ ];
+ let transcript = Transcript::from_history(history);
+ assert_eq!(
+ transcript.events()[0],
+ Event::Prompt("stable prompt".to_string())
+ );
+ assert_eq!(
+ transcript.events().len(),
+ 3,
+ "the per-turn block is not history"
+ );
+ assert_eq!(
+ transcript.events()[1],
+ Event::Message(json!({
+ "role": "system",
+ "content": summary,
+ }))
+ );
+
+ let projected = transcript.project(&Projection {
+ volatile_system: Some("Today's date is 2026-09-18."),
+ send_reasoning: true,
+ });
+ assert_eq!(projected[0]["content"], "stable prompt");
+ assert_eq!(
+ projected[1]["content"], "Today's date is 2026-09-18.",
+ "the current block, not yesterday's: {projected:?}"
+ );
+ assert_eq!(projected.len(), 4, "{projected:?}");
+ }
+
+ /// Equivalence with the live-list placement this replaced: a history and a
+ /// changed prompt produce the same bytes the old `set_system_prompt` +
+ /// `insert_volatile_system` pair did.
+ #[test]
+ fn the_projection_places_the_prompt_like_the_live_list_did() {
+ let history = vec![
+ json!({"role": "system", "content": "old prompt"}),
+ json!({"role": "system", "content": "Today's date is 2026-09-17."}),
+ json!({"role": "user", "content": "hi"}),
+ json!({"role": "assistant", "content": "hello"}),
+ ];
+
+ let mut live = history.clone();
+ set_system_prompt(&mut live, "new prompt");
+ insert_volatile_system(&mut live, "Today's date is 2026-09-18.");
+
+ let mut transcript = Transcript::from_history(history);
+ transcript.record_prompt("new prompt");
+ let projected = transcript.project(&Projection {
+ volatile_system: Some("Today's date is 2026-09-18."),
+ send_reasoning: true,
+ });
+
+ assert_eq!(
+ serde_json::to_string(&projected).unwrap(),
+ serde_json::to_string(&live).unwrap()
+ );
+ }
+
+ /// The record only ever grows: recording does not reorder or rewrite what
+ /// is already there.
+ #[test]
+ fn the_record_is_append_only() {
+ let mut transcript = Transcript::from_history(convo(4));
+ let before = transcript.events().to_vec();
+ transcript.record_prompt("prompt");
+ transcript.record_message(json!({"role": "user", "content": "more"}));
+ transcript.record_reminder("Reminder: look");
+ transcript.record_compaction(json!({"role": "system", "content": "summary"}), 2);
+
+ let after = transcript.events();
+ assert_eq!(&after[..before.len()], before.as_slice());
+ assert_eq!(after.len(), before.len() + 4);
+ }
+
+ #[test]
+ fn compaction_preserves_a_prompt_recorded_after_the_first_user_turn() {
+ let mut transcript =
+ Transcript::from_history(vec![json!({"role": "user", "content": "start"})]);
+ transcript.record_prompt("Follow the project instructions.");
+ for message in convo(12) {
+ transcript.record_message(message);
+ }
+ let projection = Projection {
+ volatile_system: Some("Today's date is 2026-09-21."),
+ send_reasoning: true,
+ };
+ let before = transcript.project(&projection);
+ let plan = transcript.compaction_plan(4).unwrap();
+ transcript.record_compaction(
+ crate::core::agent::compaction::summary_message("earlier work"),
+ plan.covers,
+ );
+
+ let after = transcript.project(&projection);
+ assert_eq!(
+ &after[..2],
+ &before[..2],
+ "compaction must retain the prompt"
+ );
+ assert!(is_compaction_summary(&after[2]));
+ assert_eq!(&after[3..], &before[before.len() - 4..]);
+ }
+
+ #[test]
+ fn compaction_preserves_prompt_updates_across_successive_boundaries() {
+ let mut transcript = Transcript::from_history(vec![
+ json!({"role": "system", "content": "Original instructions."}),
+ json!({"role": "user", "content": "start"}),
+ ]);
+ transcript.record_prompt("Updated instructions take precedence.");
+ for message in convo(12) {
+ transcript.record_message(message);
+ }
+ let projection = Projection {
+ volatile_system: Some("Today's date is 2026-09-21."),
+ send_reasoning: true,
+ };
+ let before = transcript.project(&projection);
+ let expected: Vec<&Value> = before.iter().filter(|m| is_system_node(m)).collect();
+
+ for keep_recent in [8, 4] {
+ let plan = transcript.compaction_plan(keep_recent).unwrap();
+ transcript.record_compaction(
+ crate::core::agent::compaction::summary_message("earlier work"),
+ plan.covers,
+ );
+ let after = transcript.project(&projection);
+ let prompts: Vec<&Value> = after
+ .iter()
+ .filter(|m| is_system_node(m) && !is_compaction_summary(m))
+ .collect();
+ assert_eq!(
+ prompts, expected,
+ "prompt precedence must survive compaction"
+ );
+ }
+ }
+
+ /// Nothing safe to drop means no compaction: a short history reports no
+ /// plan rather than a summary of itself.
+ #[test]
+ fn a_short_history_has_no_compaction_plan() {
+ let transcript = Transcript::from_history(convo(4));
+ assert!(transcript.compaction_plan(8).is_none());
+ }
+
+ /// A second compaction covers more of the record than the first, and the
+ /// first summary is still in the record behind it.
+ #[test]
+ fn a_second_compaction_extends_the_boundary() {
+ let mut transcript = Transcript::from_history(convo(30));
+ let first = transcript.compaction_plan(8).unwrap();
+ transcript.record_compaction(json!({"role": "system", "content": "first"}), first.covers);
+ let second = transcript.compaction_plan(4).unwrap();
+ assert!(
+ second.covers > first.covers,
+ "the boundary moves forward: {} then {}",
+ first.covers,
+ second.covers
+ );
+ transcript.record_compaction(
+ json!({"role": "system", "content": "second"}),
+ second.covers,
+ );
+
+ let projected = transcript.project(&nothing());
+ assert_eq!(projected[0]["content"], "second");
+ let summaries = transcript
+ .events()
+ .iter()
+ .filter(|event| matches!(event, Event::Compaction { .. }))
+ .count();
+ assert_eq!(summaries, 2, "both points are in the record");
+ }
+}
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index e0ebd763d..d14b7b9a0 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -196,25 +196,64 @@ pub(crate) fn repair_dangling_tool_calls(messages: &mut Vec<serde_json::Value>)
repaired
}
-/// Drops "poisoned" tool calls: an assistant `tool_calls` entry whose
-/// `function.arguments` is not parsable JSON. A model (observed with
-/// DeepSeek/vLLM) can end a stream mid-argument while still reporting
-/// `finish_reason: "tool_calls"`, so the truncated call is persisted into the
-/// thread. Every later turn resends it, and an OpenAI-compatible upstream
-/// rejects the whole request with 422 -- the session is wedged, because the
-/// poison is in the history the agent keeps replaying.
+/// Drops `role: "tool"` messages whose `tool_call_id` matches no tool call in
+/// the same array.
///
-/// Removal, not reconstruction: a truncated argument cannot be recovered, and
-/// inventing one would run a tool the model never actually asked for. The call
-/// is dropped along with any `role: "tool"` reply carrying its `tool_call_id`,
-/// so no orphaned result is left behind. Valid sibling calls in the same turn
-/// survive; an assistant turn whose calls are ALL dropped keeps its text and
-/// loses only the `tool_calls` key (and is removed entirely if that leaves it
-/// empty, which would otherwise be a contentless assistant turn some providers
-/// reject). Returns the number of calls dropped.
+/// [`drop_malformed_tool_calls`] removes the results of the calls it refuses,
+/// but nothing else in this module looks at a result whose call was never
+/// there: a caller's stored thread can carry a tool reply left behind by a
+/// dropped call, or one whose call lost its id, and a strict upstream rejects
+/// the entire request over that single orphan (Anthropic is the loudest, but
+/// OpenAI-compatible routes reject it too). This is the mirror of
+/// [`repair_dangling_tool_calls`] -- that pass fills a call that lost its
+/// result, this one removes a result that lost its call -- and the two together
+/// are what make the adoption boundary's history wire-shaped. Returns the
+/// number of results dropped.
+pub(crate) fn drop_orphaned_tool_results(messages: &mut Vec<serde_json::Value>) -> usize {
+ let mut called: std::collections::HashSet<String> = std::collections::HashSet::new();
+ for message in messages.iter() {
+ let Some(calls) = message.get("tool_calls").and_then(|v| v.as_array()) else {
+ continue;
+ };
+ for call in calls {
+ if let Some(id) = pairable_tool_call_id(call) {
+ called.insert(id.to_string());
+ }
+ }
+ }
+ let before = messages.len();
+ messages.retain(|message| {
+ if message.get("role").and_then(|v| v.as_str()) != Some("tool") {
+ return true;
+ }
+ message
+ .get("tool_call_id")
+ .and_then(|v| v.as_str())
+ .is_some_and(|id| !id.is_empty() && called.contains(id))
+ });
+ before - messages.len()
+}
+
+/// The id a tool call's result has to answer with, or `None` when the call
+/// cannot be paired at all.
///
-/// Runs before [`repair_dangling_tool_calls`], so a surviving call that lost
-/// its result still gets the synthetic error reply from that pass.
+/// The result of a call is a `role: "tool"` message carrying the call's id, and
+/// a strict upstream rejects a request where the two do not line up. A call
+/// whose `id` is missing, not a string, or empty has nothing for its result to
+/// carry, so it is neither executed nor recorded -- see
+/// [`drop_malformed_tool_calls`] for the history side of the same rule.
+pub(crate) fn pairable_tool_call_id(call: &serde_json::Value) -> Option<&str> {
+ call.get("id")
+ .and_then(|id| id.as_str())
+ .filter(|id| !id.is_empty())
+}
+
+/// A call the record may hold: its result can be paired with it, and its
+/// arguments are a plain JSON object.
+pub(crate) fn tool_call_is_usable(call: &serde_json::Value) -> bool {
+ pairable_tool_call_id(call).is_some() && arguments_are_executable(call)
+}
+
/// Whether a tool call's arguments are safe to execute and to keep in
/// provider-visible history.
///
@@ -245,42 +284,39 @@ pub(crate) fn arguments_are_executable(tc: &serde_json::Value) -> bool {
)
}
+/// Drops "poisoned" tool calls: an assistant `tool_calls` entry whose
+/// `function.arguments` is not parsable JSON, or which has no non-empty id for
+/// its result to carry. A model (observed with DeepSeek/vLLM) can end a stream
+/// mid-argument while still reporting `finish_reason: "tool_calls"`, so the
+/// truncated call is persisted into the thread. Every later turn resends it,
+/// and an OpenAI-compatible upstream rejects the whole request with 422 -- the
+/// session is wedged, because the poison is in the history the agent keeps
+/// replaying.
+///
+/// Removal, not reconstruction: a truncated argument cannot be recovered, and
+/// inventing one would run a tool the model never actually asked for. The call
+/// is dropped along with any `role: "tool"` reply carrying its `tool_call_id` -
+/// including the empty id an unpaired result carries - so no orphaned result is
+/// left behind. Valid sibling calls in the same turn survive; an assistant turn
+/// whose calls are ALL dropped keeps its text and loses only the `tool_calls`
+/// key (and is removed entirely if that leaves it empty, which would otherwise
+/// be a contentless assistant turn some providers reject). Returns the number
+/// of calls dropped.
+///
+/// Runs before [`drop_orphaned_tool_results`] and
+/// [`repair_dangling_tool_calls`], so a surviving call that lost its result
+/// still gets the synthetic error reply from that pass.
pub(crate) fn drop_malformed_tool_calls(messages: &mut Vec<serde_json::Value>) -> usize {
- // A call is poison when its arguments are not a plain JSON object. An
- // absent or empty `arguments` is the well-formed "no arguments" spelling
- // several providers use, and is left alone.
- let is_malformed = |call: &serde_json::Value| !arguments_are_executable(call);
-
+ // A call is refused when the record could not hold it: an unparsable
+ // `arguments` is the truncated-stream shape, and an absent or empty `id` is
+ // one nothing can pair a result with. An absent or empty `arguments` is the
+ // well-formed "no arguments" spelling several providers use, and is left
+ // alone.
let mut dropped_ids: Vec<String> = Vec::new();
- let mut dropped = 0;
for msg in messages.iter_mut() {
- let Some(calls) = msg.get("tool_calls").and_then(|v| v.as_array()) else {
- continue;
- };
- if !calls.iter().any(is_malformed) {
- continue;
- }
- let mut kept: Vec<serde_json::Value> = Vec::with_capacity(calls.len());
- for call in calls {
- if is_malformed(call) {
- if let Some(id) = call.get("id").and_then(|v| v.as_str()) {
- dropped_ids.push(id.to_string());
- }
- dropped += 1;
- } else {
- kept.push(call.clone());
- }
- }
- let Some(obj) = msg.as_object_mut() else {
- continue;
- };
- if kept.is_empty() {
- obj.remove("tool_calls");
- } else {
- obj.insert("tool_calls".to_string(), serde_json::Value::Array(kept));
- }
+ dropped_ids.extend(prune_unusable_tool_calls(msg));
}
- if dropped == 0 {
+ if dropped_ids.is_empty() {
return 0;
}
// Drop the results that answered a dropped call, then any assistant turn
@@ -300,20 +336,65 @@ pub(crate) fn drop_malformed_tool_calls(messages: &mut Vec<serde_json::Value>) -
}
// Keep a turn that still says something; a content-null/empty one is
// now an empty shell left by the dropped call.
- match m.get("content") {
- Some(serde_json::Value::String(s)) => !s.trim().is_empty(),
- Some(serde_json::Value::Array(a)) => !a.is_empty(),
- _ => false,
- }
+ !content_says_nothing(m)
});
- dropped
+ dropped_ids.len()
+}
+
+/// Refuse the tool calls in `message` the wire cannot carry, naming each.
+///
+/// This is the per-message half of [`drop_malformed_tool_calls`], and the same
+/// rule the live record applies as it accepts an assistant turn (see
+/// `loop::record_assistant_turn`): a call is refused when its result could not
+/// be paired with it, which is why a refused call with no id is still named
+/// here - its result carries the empty id, and skipping it would leave the
+/// orphan this pass exists to prevent. The `tool_calls` key is removed when
+/// every call went, and left untouched when none did, so a message with
+/// nothing to refuse is not rewritten. Returns the refused ids, empty id
+/// included, or an empty list when the message has no calls to refuse.
+pub(crate) fn prune_unusable_tool_calls(message: &mut serde_json::Value) -> Vec<String> {
+ let Some(calls) = message.get("tool_calls").and_then(|v| v.as_array()) else {
+ return Vec::new();
+ };
+ if calls.iter().all(tool_call_is_usable) {
+ return Vec::new();
+ }
+ let mut kept: Vec<serde_json::Value> = Vec::with_capacity(calls.len());
+ let mut refused: Vec<String> = Vec::new();
+ for call in calls {
+ if tool_call_is_usable(call) {
+ kept.push(call.clone());
+ } else {
+ refused.push(pairable_tool_call_id(call).unwrap_or_default().to_string());
+ }
+ }
+ if let Some(obj) = message.as_object_mut() {
+ if kept.is_empty() {
+ obj.remove("tool_calls");
+ } else {
+ obj.insert("tool_calls".to_string(), serde_json::Value::Array(kept));
+ }
+ }
+ refused
+}
+
+/// Whether a message's content carries nothing: no text, or text that is only
+/// whitespace, or an empty parts array. An absent or null content says nothing,
+/// which is what makes an assistant turn that lost its calls an empty shell
+/// rather than a message worth resending.
+pub(crate) fn content_says_nothing(message: &serde_json::Value) -> bool {
+ match message.get("content") {
+ Some(serde_json::Value::String(text)) => text.trim().is_empty(),
+ Some(serde_json::Value::Array(parts)) => parts.is_empty(),
+ _ => true,
+ }
}
fn system_node(content: &str) -> serde_json::Value {
serde_json::json!({ "role": "system", "content": content })
}
-fn is_system_node(message: &serde_json::Value) -> bool {
+pub(crate) fn is_system_node(message: &serde_json::Value) -> bool {
message.get("role").and_then(|r| r.as_str()) == Some("system")
}
@@ -2887,6 +2968,54 @@ mod tests {
assert_eq!(messages[1]["tool_call_id"], "ok");
}
+ #[test]
+ fn sanitize_drops_a_call_without_an_id_and_the_result_that_cannot_carry_one() {
+ // A call nothing can pair: its result goes out with an empty
+ // `tool_call_id`, which is an orphan on every later turn.
+ let mut messages = vec![
+ json!({ "role": "user", "content": "run it" }),
+ json!({
+ "role": "assistant",
+ "content": null,
+ "tool_calls": [{
+ "type": "function",
+ "function": { "name": "bash", "arguments": "{\"command\":\"ls\"}" }
+ }]
+ }),
+ json!({ "role": "tool", "tool_call_id": "", "content": "output" }),
+ ];
+ assert_eq!(drop_malformed_tool_calls(&mut messages), 1);
+ // The unpaired call, the empty shell it left, and its result are gone.
+ assert_eq!(messages.len(), 1);
+ assert_eq!(messages[0]["content"], "run it");
+ }
+
+ #[test]
+ fn orphan_tool_result_with_no_call_in_the_history_is_dropped() {
+ // What the sanitizer cannot see: a result whose call was never in the
+ // array at all (a caller's stored thread, a half-written replay). The
+ // pass is the mirror of `repair_dangling_tool_calls`, which fills the
+ // opposite gap.
+ let mut messages = vec![
+ json!({ "role": "user", "content": "carry on" }),
+ json!({ "role": "tool", "tool_call_id": "", "content": "left behind" }),
+ json!({ "role": "tool", "tool_call_id": "call_gone", "content": "also left behind" }),
+ json!({
+ "role": "assistant",
+ "content": null,
+ "tool_calls": [{
+ "id": "call_1",
+ "type": "function",
+ "function": { "name": "read", "arguments": "{}" }
+ }]
+ }),
+ json!({ "role": "tool", "tool_call_id": "call_1", "content": "contents" }),
+ ];
+ assert_eq!(drop_orphaned_tool_results(&mut messages), 2);
+ assert_eq!(messages.len(), 3);
+ assert_eq!(messages[2]["tool_call_id"], "call_1");
+ }
+
/// The full fixture matrix behind the plain-object invariant: what the
/// provider sees as `arguments` must decode to a JSON object. A parse-only
/// check is not enough -- the poisoned shapes here all parse cleanly and
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index 2b1bdac5c..58143ac05 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -29,9 +29,9 @@ use crate::core::{
pub(crate) use crate::core::agent::r#loop::run_server_side_openai_orchestration;
pub(crate) use crate::core::agent::upstream::{
call_openai_chat_completions, collect_mcp_openai_tools, copy_optional_chat_params,
- execute_mcp_tool_calls, extract_choice_message, extract_tool_calls, load_assistant_config,
- parse_openai_messages, repair_dangling_tool_calls, replace_system_prompt,
- resolve_upstream_for_model,
+ drop_orphaned_tool_results, execute_mcp_tool_calls, extract_choice_message, extract_tool_calls,
+ load_assistant_config, parse_openai_messages, repair_dangling_tool_calls,
+ replace_system_prompt, resolve_upstream_for_model,
};
use crate::core::openai_schema::{
http_status_indicates_api_key_retry, normalize_openai_tools_in_chat_body,
@@ -1212,9 +1212,17 @@ async fn proxy_request(
return Ok(error_response.body(full(e)).unwrap());
}
};
- // Self-heal a client-supplied conversation that has a tool_calls
- // turn missing one of its results -- some providers (notably
- // Anthropic) reject the entire request on a dangling tool_use.
+ // Self-heal a client-supplied conversation: a `role: "tool"`
+ // result whose call is not in the request, or a `tool_calls` turn
+ // missing one of its results, is rejected outright by some
+ // providers (notably Anthropic), so both shapes are fixed before
+ // the request goes on.
+ let orphaned = drop_orphaned_tool_results(&mut conversation_messages);
+ if orphaned > 0 {
+ log::warn!(
+ "proxy: dropped {orphaned} tool result(s) whose call is not in the request"
+ );
+ }
let repaired = repair_dangling_tool_calls(&mut conversation_messages);
if repaired > 0 {
log::warn!("proxy: repaired {repaired} dangling tool call(s) with no prior result");