Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(agent): conclude a capped turn inside the loop, not after it

sanil-23fd0f4cc0cc9b
diff --git a/src/openhuman/agent/harness/session/mod.rs b/src/openhuman/agent/harness/session/mod.rs
index 3e32e90ea3..3784652b98 100644
--- a/src/openhuman/agent/harness/session/mod.rs
+++ b/src/openhuman/agent/harness/session/mod.rs
@@ -41,7 +41,12 @@ mod tool_progress;
pub(crate) mod transcript;
pub(crate) mod transcript_history;
mod turn;
-mod turn_checkpoint;
+// `pub(crate)` since issue #6014: the tool-call-cap instruction is now appended
+// inside the loop by `tinyagents::middleware::FinalCallWrapUpMiddleware`, so the
+// harness-assembly site has to name it. It stays the one definition — the whole
+// point is that the in-loop conclusion and the out-of-band fallback ask for the
+// same thing.
+pub(crate) mod turn_checkpoint;
mod types;
pub use migration::{migrate_session_layout_if_needed, MigrationOutcome};
diff --git a/src/openhuman/agent/harness/session/turn/core.rs b/src/openhuman/agent/harness/session/turn/core.rs
index 61491b06df..2724d2a720 100644
--- a/src/openhuman/agent/harness/session/turn/core.rs
+++ b/src/openhuman/agent/harness/session/turn/core.rs
@@ -61,6 +61,49 @@ fn tool_records_from_conversation(
records
}
+/// The cap checkpoint's view of this turn's tool calls: name, status, and a
+/// truncated slice of the **actual output** (issue #6014).
+///
+/// The sibling of [`tool_records_from_conversation`] above, and separate from
+/// it on purpose. That one builds `hooks::ToolCallRecord`s, whose
+/// `output_summary` is deliberately sanitized to carry no raw output — right
+/// for the learning pipeline it feeds, useless for a checkpoint the user reads
+/// in place of the answer the turn ran out of room to write. Reading
+/// `ToolCallOutcome::content` directly here keeps the raw payload on the one
+/// path that needs it instead of widening the sanitized type for everyone.
+fn checkpoint_results_from_conversation(
+ conversation: &[ConversationMessage],
+ tool_outcomes: &[crate::openhuman::agent::tinyagents::ToolCallOutcome],
+) -> Vec<super::super::turn_checkpoint::CheckpointToolResult> {
+ let mut results = Vec::new();
+ for msg in conversation {
+ if let ConversationMessage::AssistantToolCalls { tool_calls, .. } = msg {
+ for call in tool_calls {
+ let outcome = tool_outcomes.iter().find(|o| o.call_id == call.id);
+ // Same missing-outcome rule as `tool_records_from_conversation`:
+ // a call the crate recovered without running `after_tool` never
+ // reached the capture sink, so it is reported as failed rather
+ // than silently as a success.
+ let success = outcome.map(|o| o.success).unwrap_or(false);
+ let content = outcome
+ .map(|o| {
+ super::super::turn_checkpoint::truncate_chars(
+ &o.content,
+ super::super::turn_checkpoint::CHECKPOINT_RESULT_CHARS,
+ )
+ })
+ .unwrap_or_default();
+ results.push(super::super::turn_checkpoint::CheckpointToolResult {
+ name: call.name.clone(),
+ success,
+ content,
+ });
+ }
+ }
+ }
+ results
+}
+
/// Stamp each **failed** tool-result [`ChatMessage`] with its failure outcome
/// before persistence, so the derived transcript view can render an error tool
/// row instead of a false success.
diff --git a/src/openhuman/agent/harness/session/turn/core_session.rs b/src/openhuman/agent/harness/session/turn/core_session.rs
index 2a09c1d2ef..3a3564cba1 100644
--- a/src/openhuman/agent/harness/session/turn/core_session.rs
+++ b/src/openhuman/agent/harness/session/turn/core_session.rs
@@ -221,11 +221,37 @@ impl Agent {
let mut cached_input_tokens = outcome.cached_input_tokens;
let mut charged_amount_usd = outcome.charged_amount_usd;
- let reply = if outcome.hit_cap {
+ let reply = if outcome.hit_cap && outcome.wrap_up_injected && !outcome.text.trim().is_empty()
+ {
+ // The conclusion was produced INSIDE the loop (issue #6014):
+ // `FinalCallWrapUpMiddleware` withdrew the tools on the last
+ // permitted model call and appended the wrap-up instruction, so this
+ // turn's own final response already is the capped turn's answer.
+ // There is nothing left to ask for, and asking anyway would spend a
+ // second call to re-summarise text the model has just written.
+ //
+ // No `history.push` either: unlike the out-of-band path below, this
+ // response came from the loop, so it was already folded into
+ // `self.history` by the `extend(outcome.conversation)` above. Pushing
+ // it again would duplicate the assistant turn in the transcript and
+ // in the next request's prefix.
+ log::info!(
+ "[agent_loop] turn capped at {} model call(s); the loop's final call produced the \
+ conclusion ({} chars) — no out-of-band wrap-up needed",
+ outcome.model_calls,
+ outcome.text.chars().count()
+ );
+ outcome.text.clone()
+ } else if outcome.hit_cap {
// The loop paused at the tool-call cap. Ask the model for a resumable
// checkpoint (tools disabled), falling back to a deterministic
// done/next summary so the thread never ends on a dangling tool
// cycle. Fold the extra call's usage into the turn accounting.
+ //
+ // Reached when the in-loop conclusion above did not happen or came
+ // back empty: a run with the middleware uninstalled, a budget of one
+ // model call, or a concluding call that answered with nothing. Kept
+ // intact so no path loses the behaviour it had before #6014.
let base = self.tool_dispatcher.to_provider_messages(&self.history);
let (summary, summary_usage) = self
.summarize_turn_wrapup(
@@ -243,7 +269,10 @@ impl Agent {
}
let checkpoint = if summary.trim().is_empty() {
super::super::turn_checkpoint::build_deterministic_checkpoint(
- &tool_records_from_conversation(&outcome.conversation, &outcome.tool_outcomes),
+ &checkpoint_results_from_conversation(
+ &outcome.conversation,
+ &outcome.tool_outcomes,
+ ),
max_iterations,
)
} else {
diff --git a/src/openhuman/agent/harness/session/turn_checkpoint.rs b/src/openhuman/agent/harness/session/turn_checkpoint.rs
index daa2161df1..58f5114126 100644
--- a/src/openhuman/agent/harness/session/turn_checkpoint.rs
+++ b/src/openhuman/agent/harness/session/turn_checkpoint.rs
@@ -42,31 +42,174 @@ pub(crate) fn assistant_message_has_tool_calls(msg: &ChatMessage) -> bool {
/// to wrap up with a resumable checkpoint instead of letting the turn die.
/// Native tools are disabled for this call so the model produces prose,
/// not yet another tool call. See bug-report-2026-05-26 A1.
-pub(super) const MAX_ITER_CHECKPOINT_INSTRUCTION: &str = "\
+///
+/// # Conclude the work, do not narrate the process (issue #6014)
+///
+/// This asked for "**Done so far** — what you have accomplished" + "**Next
+/// steps** — what you plan to do next", and closed with "Be concise". Every
+/// clause steers at the *process*: "accomplished" and "plan" are both about
+/// the steps taken, and terseness is asked for on the one call whose whole job
+/// is to say something substantive. A turn that spent its whole budget
+/// fetching data answered with a status line about having fetched it, while
+/// that data sat unread in the very request this instruction rides on.
+///
+/// The replacement asks for **substance** rather than for findings, and the
+/// generality is deliberate rather than hedging. A capped turn is not always a
+/// retrieval that got cut off: it may just as well have been editing files,
+/// running commands, or checking something. Wording that asked for "the items
+/// and quotes you retrieved" would fit the gathering case and misdescribe the
+/// others, leaving a turn that spent its budget applying patches with nothing
+/// truthful to report under the heading it was given. Naming the three shapes
+/// (found / changed / established) keeps the concreteness that fixes the
+/// original — vagueness is what let "accomplished" read as process — without
+/// pinning one kind of work.
+///
+/// Two facts make the omission expensive rather than cosmetic:
+///
+/// * **The final round's tool results were never seen by the model.** The
+/// model-call cap is checked at the top of the loop, before the request is
+/// built (`agent_loop::run_loop`), so the last batch of results is appended
+/// to the transcript and the loop exits. This wrap-up is the *only* call
+/// that ever reads them.
+/// * **Resuming is not guaranteed.** Deferring the answer to a "continue"
+/// turn assumes the transcript survives, and embedders routinely rebuild the
+/// session between turns (OpenCompany's `HarnessPool::ensure` mints a fresh
+/// agent whenever any roster fingerprint moves). The unread results are then
+/// gone, and the plan is all that is left of them.
+///
+/// So the priority is inverted here: answer first, from the results in
+/// context, and demote the remaining work to a closing line. The sibling
+/// [`FINAL_ANSWER_INSTRUCTION`] already words its path this way ("what you
+/// found or accomplished, grounded in the tool results above") — this was the
+/// path that did not, and it is the one where the model never got its turn to
+/// answer at all.
+pub(crate) const MAX_ITER_CHECKPOINT_INSTRUCTION: &str = "\
You have reached the maximum number of tool calls allowed for this single turn, so you cannot call any more tools right now. \
-Do not attempt another tool call. Instead, write a short progress checkpoint for the user with two clearly labelled parts:\n\
-1. **Done so far** — what you have accomplished in this turn, grounded in the tool results above.\n\
-2. **Next steps** — exactly what you plan to do next.\n\
-Write it so you can pick up seamlessly where you left off when the user replies. Be concise.";
+Do not attempt another tool call.\n\
+\n\
+First, report the substance of what this turn produced, grounded in the tool results above: what you found, what you changed, \
+or what you established — whichever this task was. Be concrete about it. If you were gathering information, give the \
+information itself rather than saying that you gathered it; if you were changing something, say what is now different. \
+Include your most recent tool calls: they completed, and this is your only opportunity to use them.\n\
+\n\
+Then close with a brief **Still to do** line naming what remains, so the user can ask you to carry on.\n\
+\n\
+Let the length follow the substance — neither a one-line status nor a raw dump of tool output. If the results support no \
+conclusion yet, say that plainly and name what is missing.";
+
+/// One completed tool call, carrying enough of its **actual output** to stand
+/// in for an answer (issue #6014).
+///
+/// Deliberately not [`ToolCallRecord`], and the difference is a contract rather
+/// than a convenience: that type's `output_summary` is produced by
+/// [`sanitize_tool_output`](crate::openhuman::agent::hooks::sanitize_tool_output),
+/// which by design "never contains raw tool output or PII" and renders a
+/// success as `"{tool}: ok (N chars)"`. It feeds the learning pipeline, where
+/// stripping payloads is the point. A checkpoint the user reads has the
+/// opposite requirement — it is a substitute for the answer the turn ran out
+/// of room to give — so it needs the content that type exists to remove.
+/// Widening `ToolCallRecord` would have carried raw payloads into every
+/// learning record as a side effect.
+pub(super) struct CheckpointToolResult {
+ /// The tool that ran.
+ pub name: String,
+ /// Whether it reported success.
+ pub success: bool,
+ /// Its raw output, truncated at the call site to [`CHECKPOINT_RESULT_CHARS`].
+ pub content: String,
+}
+
+/// How much of one tool result the deterministic checkpoint reproduces.
+///
+/// A floor, not a summary: enough that a fetched list, count or error message
+/// survives, small enough that a dozen results stay readable in a chat bubble.
+/// The model-written checkpoint is what should normally answer — this is the
+/// safety net for when that call fails, and a truncated payload the user can
+/// read beats a tool name they cannot act on.
+pub(super) const CHECKPOINT_RESULT_CHARS: usize = 800;
+
+/// Ceiling on the reproduced output across **all** results in one checkpoint.
+///
+/// The per-result cap alone does not bound the message: a turn reaches this
+/// fallback by exhausting its iteration budget, so it arrives with as many
+/// results as the cap allowed — at 25 iterations and 800 chars each that is a
+/// 20,000-character wall in a chat bubble, which is not a checkpoint anybody
+/// reads. The budget is spent from the **newest** result backwards, because
+/// recency and value coincide precisely here: the last round's results are the
+/// ones the loop exited before the model could read (the cap is checked before
+/// the request is built), so they are both the freshest and the only ones
+/// guaranteed to have reached no other reader.
+pub(super) const CHECKPOINT_TOTAL_CHARS: usize = 4_000;
+
+/// Truncate `text` to `max` **characters**, on a char boundary, appending an
+/// ellipsis marker when anything was cut. Chars rather than bytes so a
+/// multi-byte payload cannot panic the fallback that exists to stop a turn
+/// wedging.
+pub(super) fn truncate_chars(text: &str, max: usize) -> String {
+ let trimmed = text.trim();
+ if trimmed.chars().count() <= max {
+ return trimmed.to_string();
+ }
+ let cut: String = trimmed.chars().take(max).collect();
+ format!("{cut}… [truncated]")
+}
/// Build a deterministic checkpoint summary from this turn's tool-call
-/// records. Used only as a safety net when the model-written checkpoint
+/// results. Used only as a safety net when the model-written checkpoint
/// call fails or returns empty, so a capped turn can never be left without
/// a well-formed assistant message — which is what silently wedged the
/// thread before (bug-report-2026-05-26 A1).
+///
+/// Reproduces each result's own output (issue #6014). It used to list
+/// `` `tool_name` — ok `` and nothing else, which told a user who had just
+/// waited out a full iteration budget only which tools had run, never what any
+/// of them returned — and this fallback fires precisely when the model-written
+/// checkpoint could not be produced, so it was the *only* thing standing
+/// between the turn's work and the user. The output is quoted as data, under a
+/// heading that says so, because none of it has been through a model on this
+/// path: it is raw tool output being surfaced verbatim, not an answer.
pub(super) fn build_deterministic_checkpoint(
- records: &[ToolCallRecord],
+ results: &[CheckpointToolResult],
max_iterations: usize,
) -> String {
let mut out = format!(
- "I reached the tool-call limit for this turn ({max_iterations} steps), so I paused here.\n\n**Done so far:**\n"
+ "I reached the tool-call limit for this turn ({max_iterations} steps), so I paused here \
+ before I could write up what I found.\n\n**Raw results from this turn**\n"
);
- if records.is_empty() {
- out.push_str("- (no tools completed yet)\n");
+ if results.is_empty() {
+ out.push_str("\n- (no tools completed yet)\n");
} else {
- for r in records {
+ // Choose how far back the budget reaches by walking from the newest
+ // result, then render in the original order — a checkpoint read
+ // backwards is harder to follow than one that simply starts later.
+ let mut budget = CHECKPOINT_TOTAL_CHARS;
+ let mut first_shown = results.len();
+ for (idx, r) in results.iter().enumerate().rev() {
+ let cost = r.content.chars().count();
+ if cost > budget && idx + 1 < results.len() {
+ // The newest result is always shown, however long, so a single
+ // oversized payload cannot empty the checkpoint entirely; every
+ // earlier one has to fit what is left.
+ break;
+ }
+ budget = budget.saturating_sub(cost);
+ first_shown = idx;
+ }
+ if first_shown > 0 {
+ out.push_str(&format!(
+ "\n_({first_shown} earlier tool result(s) omitted for length — the most recent are shown.)_\n"
+ ));
+ }
+ for r in &results[first_shown..] {
let status = if r.success { "ok" } else { "failed" };
- out.push_str(&format!("- `{}` — {}\n", r.name, status));
+ out.push_str(&format!("\n- `{}` — {}\n", r.name, status));
+ if !r.content.is_empty() {
+ for line in r.content.lines() {
+ out.push_str(" > ");
+ out.push_str(line);
+ out.push('\n');
+ }
+ }
}
}
out.push_str(
diff --git a/src/openhuman/agent/harness/session/turn_tests_part_03_tests.rs b/src/openhuman/agent/harness/session/turn_tests_part_03_tests.rs
index 88e38e5ca5..498c0a1c03 100644
--- a/src/openhuman/agent/harness/session/turn_tests_part_03_tests.rs
+++ b/src/openhuman/agent/harness/session/turn_tests_part_03_tests.rs
@@ -607,3 +607,110 @@ async fn fetch_learned_context_returns_empty_when_both_flags_off() {
assert!(learned.patterns.is_empty());
assert!(learned.reflections.is_empty());
}
+
+/// Issue #6014: a capped turn concludes from **inside** the loop.
+///
+/// The turn used to exit on the cap and then make a second, out-of-band call
+/// asking for a checkpoint. That call ran with none of the loop's context
+/// management and failed silently into a digest of tool names — on the very
+/// turns that had gathered the most. The last permitted model call now does the
+/// concluding itself: tools withdrawn, wrap-up instruction appended, answer
+/// produced by an ordinary loop iteration.
+///
+/// Pinned here: the tool schemas really are withdrawn on that call (not merely
+/// discouraged in prose), the loop's own text becomes the reply, the turn still
+/// reports as capped, and — the whole point — no extra provider call is made.
+#[tokio::test]
+async fn a_capped_turn_concludes_inside_the_loop_without_a_second_call() {
+ let recorded = Arc::new(SequenceProvider {
+ responses: AsyncMutex::new(vec![
+ // Call 1 spends the turn's only tool round.
+ Ok(ChatResponse {
+ text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
+ tool_calls: vec![],
+ usage: None,
+ reasoning_content: None,
+ }),
+ // Call 2 is the last permitted one, so the middleware turns it into
+ // the conclusion. A third response is deliberately NOT scripted: if
+ // anything still made an out-of-band wrap-up call, the provider
+ // would run dry and the turn would fail.
+ Ok(ChatResponse {
+ text: Some("The echo tool returned `hello`, which answers the question.".into()),
+ tool_calls: vec![],
+ usage: None,
+ reasoning_content: None,
+ }),
+ ]),
+ requests: AsyncMutex::new(Vec::new()),
+ tool_counts: AsyncMutex::new(Vec::new()),
+ });
+ let provider: Arc<dyn ChatModel<()>> = recorded.clone();
+
+ let mut agent = make_agent_with_builder(
+ provider,
+ vec![Box::new(EchoTool)],
+ vec![],
+ crate::openhuman::config::AgentConfig {
+ // Two, not one: a single-call budget would make the FIRST call the
+ // concluding one, so the turn could never run a tool at all — which
+ // the middleware treats as a misconfiguration and declines to touch.
+ max_tool_iterations: 2,
+ ..crate::openhuman::config::AgentConfig::default()
+ },
+ crate::openhuman::config::ContextConfig::default(),
+ );
+
+ let reply = agent
+ .turn("what does echo say?")
+ .await
+ .expect("a capped turn should conclude, not error");
+
+ // The loop's own final text is the reply — it reports the RESULT, which is
+ // what the old process-shaped checkpoint could not do.
+ assert!(
+ reply.contains("returned `hello`"),
+ "the in-loop conclusion should be the reply, got: {reply}"
+ );
+
+ let tool_counts = recorded.tool_counts.lock().await.clone();
+ assert_eq!(
+ tool_counts.len(),
+ 2,
+ "exactly two provider calls: the tool round and the conclusion — an out-of-band wrap-up \
+ would make a third, {tool_counts:?}"
+ );
+ assert!(
+ tool_counts[0] > 0,
+ "the first call must be offered the tool belt, got {tool_counts:?}"
+ );
+ assert_eq!(
+ tool_counts[1], 0,
+ "the concluding call must be offered NO tools — the instruction alone is a request the \
+ model may ignore, {tool_counts:?}"
+ );
+
+ // Still reported as a pause, so callers that render a "continue" affordance
+ // (and the workflow runner, which must not settle a capped node as
+ // finished) keep the signal they read today.
+ assert!(
+ agent.last_turn_hit_cap(),
+ "a turn that concluded at its cap is still a capped turn"
+ );
+
+ // The transcript ends on that conclusion exactly once: it came from the
+ // loop, so it is already folded in via the run's conversation, and the cap
+ // branch must not append a second copy.
+ let conclusions = agent
+ .history
+ .iter()
+ .filter(|message| {
+ matches!(message, ConversationMessage::Chat(msg)
+ if msg.role == "assistant" && msg.content.contains("returned `hello`"))
+ })
+ .count();
+ assert_eq!(
+ conclusions, 1,
+ "the conclusion should appear once in history, not be re-pushed by the cap branch"
+ );
+}
diff --git a/src/openhuman/agent/tinyagents/middleware_part_05.rs b/src/openhuman/agent/tinyagents/middleware_part_05.rs
index f1cce50cae..ef4145bda3 100644
--- a/src/openhuman/agent/tinyagents/middleware_part_05.rs
+++ b/src/openhuman/agent/tinyagents/middleware_part_05.rs
@@ -497,3 +497,116 @@ impl Middleware<()> for ImageAwareMessageTrimMiddleware {
Ok(())
}
}
+
+// ── FinalCallWrapUpMiddleware (issue #6014) ──────────────────────────────────
+
+/// Turns the **last permitted model call of a capped turn** into the turn's
+/// conclusion, in the loop, instead of leaving the answer to an extra call
+/// made after the loop has already exited.
+///
+/// # Why the loop and not afterwards
+///
+/// A capped turn used to end like this: the loop exits on the model-call cap,
+/// and `Agent::summarize_turn_wrapup` then dispatches a second, out-of-band
+/// request straight at the `ChatModel` asking for a checkpoint. Being outside
+/// the harness, that request ran with **none** of the loop's context
+/// management — no microcompact, no compression, no trim — while being built
+/// from the largest transcript the turn would ever hold (every tool result a
+/// full iteration budget produced). It was therefore the likeliest call of the
+/// whole turn to overflow the window, and each of its failure paths returns
+/// `("", None)` silently, so the answer degraded to a deterministic digest of
+/// tool names exactly when the turn had the most to report. It also bypassed
+/// usage accounting (folded back by hand at the call site) and the progress
+/// bridge (re-implemented there as buffer-then-validate-then-forward).
+///
+/// Doing it here removes all of that rather than compensating for it: the
+/// concluding call is an ordinary loop iteration, so it inherits the entire
+/// middleware stack, its usage rides `UsageCarryMiddleware` like any other
+/// call, and its text streams through the normal event bridge. It is also one
+/// provider call cheaper — the wrap-up was an extra call *past* the cap the
+/// operator configured.
+///
+/// # What "last permitted call" means, exactly
+///
+/// The loop records the model call **before** it builds the request
+/// (`agent_loop::run_loop`), so by the time `before_model` runs for the Nth
+/// call of an N-call budget, `remaining_model_calls()` is already `0`. That is
+/// the trigger, and it needs no new plumbing or counter of its own.
+///
+/// The trade this makes is explicit: a 25-call budget becomes 24 tool rounds
+/// plus a conclusion, rather than 25 tool rounds plus a 26th call nobody
+/// budgeted for.
+///
+/// # Why the tools are cleared rather than merely discouraged
+///
+/// The instruction alone is a request the model may ignore — the out-of-band
+/// wrap-up had to re-parse its own response through the dispatcher to catch a
+/// model that emitted a tool call anyway. Removing the schemas from the
+/// request makes it structural instead: there is nothing to call. `tool_choice`
+/// is reset alongside them because a `Required` choice with an empty tool array
+/// is a provider 400.
+pub(crate) struct FinalCallWrapUpMiddleware {
+ /// The synthetic user turn appended on the final call.
+ instruction: &'static str,
+ /// Set when the injection fires, so the caller can report the turn as
+ /// capped. Necessary because this turn now ends *naturally* — the model
+ /// returns text and requests no tools, which is the loop's ordinary
+ /// terminal condition — so the old `final_response.is_none()` tell no
+ /// longer distinguishes a capped turn from a finished one.
+ fired: Arc<std::sync::atomic::AtomicBool>,
+}
+
+impl FinalCallWrapUpMiddleware {
+ pub(crate) fn new(instruction: &'static str) -> Self {
+ Self {
+ instruction,
+ fired: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ }
+ }
+
+ /// The shared flag, for the run loop to read after the drive future returns.
+ pub(crate) fn fired(&self) -> Arc<std::sync::atomic::AtomicBool> {
+ self.fired.clone()
+ }
+}
+
+#[async_trait]
+impl Middleware<()> for FinalCallWrapUpMiddleware {
+ fn name(&self) -> &str {
+ "final_call_wrap_up"
+ }
+
+ async fn before_model(
+ &self,
+ ctx: &mut RunContext<()>,
+ _state: &(),
+ request: &mut ModelRequest,
+ ) -> TaResult<()> {
+ if ctx.limits.remaining_model_calls() > 0 {
+ return Ok(());
+ }
+ // A budget of one call would make the very first call the concluding
+ // one, so the turn could never run a tool at all. That is a
+ // misconfiguration rather than a cap being reached, and silently
+ // answering it with a "you have run out of tool calls" instruction
+ // would misreport it — leave such a run alone.
+ if ctx.limits.limits().max_model_calls <= 1 {
+ return Ok(());
+ }
+ tracing::info!(
+ model_calls = ctx.limits.model_calls(),
+ max_model_calls = ctx.limits.limits().max_model_calls,
+ tools_withdrawn = request.tools.len(),
+ "[tinyagents::mw] final permitted model call — withdrawing tools and asking for the \
+ turn's conclusion"
+ );
+ request.tools.clear();
+ request.tool_choice = tinyinference::model::ToolChoice::None;
+ request
+ .messages
+ .push(TaMessage::user(self.instruction.to_string()));
+ self.fired
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ Ok(())
+ }
+}
diff --git a/src/openhuman/agent/tinyagents/mod_part_01.rs b/src/openhuman/agent/tinyagents/mod_part_01.rs
index eb3ad863cf..eea9879246 100644
--- a/src/openhuman/agent/tinyagents/mod_part_01.rs
+++ b/src/openhuman/agent/tinyagents/mod_part_01.rs
@@ -326,6 +326,19 @@ pub(crate) struct TinyagentsTurnOutcome {
/// should summarize a resumable checkpoint rather than treat `text` as a
/// final answer — the tinyagents analogue of the legacy cap checkpoint seam.
pub hit_cap: bool,
+ /// `true` when [`FinalCallWrapUpMiddleware`] turned this turn's last
+ /// permitted model call into its conclusion (issue #6014) — the tools were
+ /// withdrawn and the wrap-up instruction appended in the loop, so `text`
+ /// already **is** the capped turn's answer.
+ ///
+ /// Read alongside [`hit_cap`](Self::hit_cap) rather than folded into it,
+ /// because the caller's action differs: with this set there is nothing left
+ /// to ask the model for, while a cap reached without it (a run with the
+ /// middleware uninstalled, or one whose final call still came back empty)
+ /// keeps the out-of-band `summarize_turn_wrapup` path it always had. That
+ /// makes the in-loop conclusion strictly additive — no path loses the
+ /// behaviour it has today.
+ pub wrap_up_injected: bool,
/// Set (with the root-cause halt summary) when the repeated-tool-failure /
/// repeat-progress circuit breaker halted the run before a natural finish.
/// The sub-agent runner surfaces this as `SubagentRunStatus::Incomplete`
@@ -477,6 +490,9 @@ pub(crate) async fn run_turn_via_tinyagents(
),
early_exit_tool: None,
hit_cap: false,
+ // The thin (test-only) variant installs no middleware, so nothing could
+ // have injected a conclusion.
+ wrap_up_injected: false,
// This thin (test-only) variant does not install the breaker middleware.
breaker_halt: None,
// This thin variant carries no per-call outcome capture middleware.
diff --git a/src/openhuman/agent/tinyagents/mod_part_02.rs b/src/openhuman/agent/tinyagents/mod_part_02.rs
index 2c2a7ca005..6be65b4b1a 100644
--- a/src/openhuman/agent/tinyagents/mod_part_02.rs
+++ b/src/openhuman/agent/tinyagents/mod_part_02.rs
@@ -48,6 +48,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
tool_outcome_sink,
handle,
early_exit_hook,
+ wrap_up_fired,
tool_count,
registry_snapshot: _,
registry_diagnostics,
@@ -68,6 +69,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
tool_policy,
routes::turn_required_capabilities(model),
deterministic_cacheable,
+ pause_at_cap,
);
// Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).
@@ -613,11 +615,23 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
// breaker halt is *not* a cap hit: it already carries a root-cause summary, so
// treating it as a cap would let the caller (sub-agent runner) overwrite that
// summary with a generic checkpoint digest.
+ // Issue #6014: the in-loop conclusion is the primary tell now. When
+ // `FinalCallWrapUpMiddleware` fired, the turn reached its cap *and* answered
+ // from inside the loop — which means it ended the way a finished turn does
+ // (text, no tool request), so `final_response` is `Some` and the original
+ // predicate below can no longer see it. The old predicate is kept as the
+ // second arm rather than replaced: it still covers every run with the
+ // middleware uninstalled, and the case where the concluding call itself came
+ // back requesting a tool (a text-protocol model ignoring an empty schema
+ // list) and the loop ran out with nothing final.
+ let wrap_up_injected = wrap_up_fired
+ .as_ref()
+ .is_some_and(|fired| fired.load(std::sync::atomic::Ordering::SeqCst));
let hit_cap = pause_at_cap
&& early_exit.is_none()
&& breaker_halt.is_none()
- && run.model_calls >= max_iterations
- && run.final_response.is_none();
+ && (wrap_up_injected
+ || (run.model_calls >= max_iterations && run.final_response.is_none()));
let (early_exit_tool, mut text) = match early_exit {
Some(exit) => (Some(exit.tool), exit.question),
@@ -669,6 +683,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
charged_amount_usd,
early_exit_tool,
hit_cap,
+ wrap_up_injected,
breaker_halt,
tool_outcomes,
})
diff --git a/src/openhuman/agent/tinyagents/mod_part_03.rs b/src/openhuman/agent/tinyagents/mod_part_03.rs
index bc107ab7f9..cd8c64e9e2 100644
--- a/src/openhuman/agent/tinyagents/mod_part_03.rs
+++ b/src/openhuman/agent/tinyagents/mod_part_03.rs
@@ -500,6 +500,14 @@ struct AssembledTurnHarness {
handle: Option<SteeringHandle>,
/// Records the first early-exit tool round, when early-exit tools exist.
early_exit_hook: Option<EarlyExitHook>,
+ /// Set by [`FinalCallWrapUpMiddleware`] when it turned the last permitted
+ /// model call into the turn's conclusion (issue #6014). `None` when the
+ /// middleware is not installed (a run that does not pause at its cap).
+ ///
+ /// A flag rather than an inference off the run, because this turn now ends
+ /// the way a finished one does — the model returns text and requests no
+ /// tools — so `final_response.is_none()` no longer tells the two apart.
+ wrap_up_fired: Option<Arc<std::sync::atomic::AtomicBool>>,
/// Number of callable tools registered.
tool_count: usize,
/// TinyAgents named-capability projection for this turn. The live run still
diff --git a/src/openhuman/agent/tinyagents/mod_part_04.rs b/src/openhuman/agent/tinyagents/mod_part_04.rs
index 875b21b01f..a64e90f0e2 100644
--- a/src/openhuman/agent/tinyagents/mod_part_04.rs
+++ b/src/openhuman/agent/tinyagents/mod_part_04.rs
@@ -19,6 +19,12 @@ fn assemble_turn_harness(
tool_policy: Option<ToolPolicyEnforcement>,
required_capabilities: Option<CapabilitySet>,
deterministic_cacheable: bool,
+ // Whether this run pauses gracefully at its model-call cap (issue #6014).
+ // Only such a run gets the in-loop conclusion: a run that errors at its cap
+ // instead (the channel/CLI path, which maps the stop to
+ // `MaxIterationsExceeded`) must keep doing that, and handing it a wrap-up
+ // would silently convert a documented error into an answer.
+ pause_at_cap: bool,
) -> AssembledTurnHarness {
let mut harness: AgentHarness<()> = AgentHarness::new();
// Cross-route fallback ownership (issue #4249, Workstream 02.2): populate the
@@ -201,6 +207,36 @@ fn assemble_turn_harness(
)));
}
}
+ // Issue #6014: make the last permitted model call the turn's conclusion,
+ // rather than leaving the answer to an extra out-of-band call after the loop
+ // has exited. Registered late so its `before_model` runs after the context
+ // middlewares have shaped the transcript — the instruction it appends is the
+ // final turn of the request and must not be what a trim evicts.
+ //
+ // **Top-level turns only**, the same cut `CapPauser`'s dispatch guard takes
+ // and for a related reason: a sub-agent reaching its own model-call cap is a
+ // routine outcome rather than a user-visible dead end. It summarises and
+ // hands the result back to its parent as a tool result, the parent keeps
+ // going, and `subagent_runner` already owns that checkpoint (including its
+ // own deterministic fallback). The problem this fixes — a person left with a
+ // status line where an answer should be — is a property of the turn that
+ // answers a human.
+ //
+ // Withholding it also leaves the child's budget arithmetic alone. The
+ // conclusion costs one model call, so installing this would silently convert
+ // a delegated run's N tool rounds into N-1; that is a fine trade to make
+ // once, deliberately, at the top level, and not one to impose on every child
+ // as a side effect.
+ let wrap_up_mw = (pause_at_cap && subagent_scope.is_none()).then(|| {
+ Arc::new(middleware::FinalCallWrapUpMiddleware::new(
+ crate::openhuman::agent::harness::session::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
+ ))
+ });
+ let wrap_up_fired = wrap_up_mw.as_ref().map(|mw| mw.fired());
+ if let Some(mw) = wrap_up_mw {
+ harness.push_middleware(mw);
+ }
+
let early_exit_set: HashSet<&str> = early_exit_tools.iter().copied().collect();
// One hook per run, shared by every early-exit adapter (records the first
// early-exit and pauses). Requires the steering handle.
@@ -636,6 +672,7 @@ fn assemble_turn_harness(
tool_outcome_sink,
handle,
early_exit_hook,
+ wrap_up_fired,
tool_count,
registry_snapshot,
registry_diagnostics,