pub struct Transcript { /* private fields */ }Expand description
Running conversation history for one agent-loop run.
Why: Centralises message accumulation so the loop body stays focused on
control flow rather than ChatMessage plumbing, and (#2070) centralises
the compaction state machine so the loop only has to call
maybe_compact at its turn boundary.
What: A thin wrapper over Vec<TranscriptEntry> with append helpers, a
raw-history accessor, a compacted model-facing view, and an
assistant-text accessor. last_compaction_len records the entry count at
the moment compaction most recently fired (None if it has never fired
in this run) — to_messages compares it against the CURRENT entry count
to append the last-user-message replay (§5.4 item 3) only on the turn
compaction actually fired on, not on every subsequent call. (#2347) goals
holds the session’s 5 fixed privileged goal slots behind an Arc<Mutex<_>>
(rather than a bare GoalSlots) so tools::goals::{SetGoalTool, ClearGoalTool} — constructed and registered into the PM’s tool registry
BEFORE this Transcript value is handed to AgentLoop::run_with_transcript
— can mutate the SAME live state to_messages reads on every call via
Self::goals_handle’s cloned Arc. Deliberately NOT a real
TranscriptEntry: it is rendered fresh into the model-facing view on every
to_messages call rather than stored/compacted, so it can never be folded
into a compaction summary and never drifts from the live tool-mutated state.
Test: transcript::tests::*.
Implementations§
Source§impl Transcript
impl Transcript
Sourcepub fn seed(system: &str, task: &str) -> Self
pub fn seed(system: &str, task: &str) -> Self
Seed a transcript with a system prompt and the user task.
Why: Every run starts from exactly these two turns; bundling the seed in
a constructor prevents the loop from forgetting either.
What: Pushes a system message then a user message, both starting
uncompacted. maybe_compact (#2070) never marks system or user
role entries — see its docs — so these two seed turns are preserved
forever regardless of how long the run continues.
Test: transcript::tests::seed_has_two_messages.
Sourcepub fn push_assistant(&mut self, text: Option<String>, tool_calls: &[ToolCall])
pub fn push_assistant(&mut self, text: Option<String>, tool_calls: &[ToolCall])
Append the assistant turn from a model response.
Why: The model’s turn (text and any tool calls) must be added to history
before the tool results, so the next request reflects the real ordering
the API expects.
What: Reconstructs a ChatMessage with role = "assistant", carrying the
optional text content and the emitted tool calls; records the text (if
any) for the final answer.
Test: transcript::tests::push_assistant_records_text.
Sourcepub fn push_tool_result(
&mut self,
tool_call_id: &str,
name: &str,
content: &str,
)
pub fn push_tool_result( &mut self, tool_call_id: &str, name: &str, content: &str, )
Append a tool role result message answering a specific tool call.
Why: The API requires each tool call to be answered by a tool message
referencing its tool_call_id, or the next assistant turn errors.
(#2070) A use_skill result is the loaded body of a skill the model
deliberately chose to invoke — §5.4 item 5 requires it survive
compaction forever, the same guarantee system/user turns get.
What: Pushes a ChatMessage::tool_result with the call id, function
name, and textual result — as a permanently pinned entry when
name == USE_SKILL_TOOL_NAME, otherwise as an ordinary compaction-
eligible entry.
Test: transcript::tests::push_tool_result_sets_call_id,
transcript::tests::maybe_compact_never_compacts_pinned_skill_output,
transcript::tests::maybe_compact_still_compacts_non_skill_tool_results.
Sourcepub fn messages(&self) -> Vec<ChatMessage>
pub fn messages(&self) -> Vec<ChatMessage>
Return the complete, uncompacted raw message history.
Why: (#2070) Non-destructive compaction is only meaningful if the full
history stays retrievable for audit even after to_messages starts
collapsing older turns; this is that escape hatch.
What: Clones every entry’s original ChatMessage, in order, regardless
of its compacted flag.
Test: transcript::tests::messages_reflects_appends,
transcript::tests::compacted_entries_remain_in_raw_history.
Sourcepub fn to_messages(&self) -> Vec<ChatMessage>
pub fn to_messages(&self) -> Vec<ChatMessage>
Render the model-facing view: compacted spans collapsed to a summary,
the live goal slots injected at position [1], plus a replayed last
user message once compaction has occurred.
Why: This is what ChatRequest.messages actually sends — it must
shrink once compaction fires (the whole point of §5.4) while staying
a valid, coherently-ordered conversation. (#2347) The goals injection
happens HERE, fresh on every call, rather than being a stored
TranscriptEntry — that is what makes it immune to compaction (it
never exists as an entry maybe_compact could mark) and immune to
drift (it always reflects whatever tools::goals::{SetGoalTool, ClearGoalTool} most recently wrote via the same Arc<Mutex<_>>).
What: Walks entries in order; a run of one-or-more contiguous
compacted entries is replaced by ONE synthetic system-role message
(super::compaction::summarize_span’s one-line text, plus (#2346) a
“full detail in session memory (turns N-M)” pointer appended when any
entry in the span carries a cadence_turn_range — see
[flush_span]’s docs) in its place; uncompacted entries pass through
unchanged. (#2347) If self.goals.render() returns Some, a
synthetic system-role message carrying that text is inserted at
index 1 (immediately after the real system message, which
Transcript::seed always places at index 0 and maybe_compact
never touches) — or appended if out is empty, a defensive case that
never occurs via seed. A poisoned goals lock degrades to “no goals
block” rather than panicking (mirrors run_task::recorder’s
poisoned-lock convention). After that insertion, if
last_compaction_len equals the CURRENT entry count (i.e. this call
is happening on the very turn maybe_compact last fired on — the
loop calls maybe_compact then to_messages back-to-back before any
further entries are appended), the LAST user-role entry’s message is
cloned and appended again at the very end — §5.4 item 3’s “re-anchor
the model” replay. On every later call the entry count has grown past
last_compaction_len, so the replay does not repeat until compaction
fires again. A transcript with no user entry (never happens via
seed, but guarded rather than assumed) simply skips the replay.
Test: transcript::tests::to_messages_collapses_compacted_span,
transcript::tests::to_messages_replays_last_user_message_after_compaction,
transcript::tests::to_messages_does_not_replay_on_every_subsequent_turn,
transcript::tests::to_messages_is_passthrough_before_compaction,
transcript::tests::to_messages_injects_goals_at_position_one,
transcript::tests::to_messages_omits_goals_message_when_all_empty,
transcript::tests::to_messages_goals_survive_aggressive_compaction.
Sourcepub fn maybe_compact(&mut self, cfg: &CompactionConfig) -> bool
pub fn maybe_compact(&mut self, cfg: &CompactionConfig) -> bool
Apply the compaction policy: mark eligible older entries compacted.
Why: (#2070) This is the turn-boundary hook the agent loop calls —
gated by the caller on HarnessMode::DailyDriver (Parity must never
compact, per §5.9’s D2 reconciliation) — so growth is bounded without
the loop body needing to know compaction’s internals. (#2278) A raw
entry-COUNT cutoff has no tool-call awareness: when it lands between
an assistant entry carrying tool_calls and one of its answering
tool-role entries, the assistant gets folded into the compacted
summary while the answering entry survives verbatim in the kept
zone — an orphaned tool result with no tool use, which providers
with a strict pairing invariant (Bedrock’s Converse API) reject
outright.
What: No-ops (returns false) unless the CURRENT model-facing view
(to_messages(), not the ever-growing raw history — raw size would
re-trigger every turn even after compaction shrank what’s actually
sent) exceeds cfg.token_threshold. Otherwise computes the naive
count-based cutoff keep_from = len - cfg.keep_last_messages, then
(#2278) [turn_group_start]/[turn_group_end] check whether that
cutoff falls INSIDE a turn group — an assistant entry carrying
tool_calls plus the maximal contiguous run of tool-role entries
immediately following it (naturally covering multi-tool-call turns:
N tool_calls followed by up to N tool entries). If so, the whole
group is pulled FORWARD into the kept zone by moving keep_from back
to the group’s start — cfg.keep_last_messages becomes a soft floor
that may slightly enlarge the active zone rather than ever splitting
a group. Marks every entry before the (possibly adjusted) keep_from
as compacted = true, EXCEPT entries already compacted (a one-way
transform), pinned entries (§5.4 item 5’s skill-output half — see
push_tool_result), and system/user role entries (§5.4 item 5’s
“preserve… user requests forever” half). Records last_compaction_len = Some(self.entries.len()) and returns true only if at least one
entry was newly marked (an already-fully-compacted or
entirely-preserved prefix is a no-op, not a spurious trigger) — this
marker is what lets to_messages replay the last user message
exactly once, on this turn, rather than on every subsequent call.
Test: transcript::tests::maybe_compact_is_noop_below_threshold,
transcript::tests::maybe_compact_never_touches_system_or_user,
transcript::tests::maybe_compact_never_compacts_pinned_skill_output,
transcript::tests::maybe_compact_still_compacts_non_skill_tool_results,
transcript::tests::maybe_compact_pulls_whole_multi_tool_call_group_forward.
Sourcepub fn cadence_turn_count(&self) -> usize
pub fn cadence_turn_count(&self) -> usize
Cumulative count of agent-loop turn boundaries observed (#2346).
Why: Lives on Transcript (not AgentLoop, which is reconstructed
fresh on every task.run call — see task::executor::run_and_record)
so cadence counts turns CUMULATIVELY across a session’s whole
lifetime, matching the epic’s “500+ turn interactive session” framing
rather than resetting every call.
What: The current cadence_turn_count.
Test: cadence::tests::fires_every_n_turns.
Sourcepub fn cadence_fire_count(&self) -> usize
pub fn cadence_fire_count(&self) -> usize
Number of times the cadence compressor has fired (#2346).
Why: The turn-count test (“cadence fires exactly every N turns”) and
the “compaction_events == 0” acceptance test both need an
observability counter distinct from compacted_count (entries, not
events).
What: The current cadence_fire_count.
Test: cadence::tests::fires_every_n_turns.
Sourcepub fn compaction_events(&self) -> u32
pub fn compaction_events(&self) -> u32
Cumulative count of #2308 threshold-compactor fires (#2349).
Why: The epic #2343 success metric is a “500+ turn session with
compaction_events == 0” — this is the field that metric reads,
exposed onto session::TranscriptRecord.compaction_events via
SessionRegistry::get_transcript.
What: The current threshold_compaction_events.
Test: agent_loop::tests::forced_degradation_increments_counter_and_logs_error,
cadence_tests::stays_under_budget_every_turn_and_threshold_never_fires.
Sourcepub fn compacted_count(&self) -> usize
pub fn compacted_count(&self) -> usize
Number of entries currently marked compacted.
Why: Test/observability accessor proving compaction happened without
exposing the private TranscriptEntry type.
What: Counts entries with compacted == true.
Test: transcript::tests::maybe_compact_marks_middle_span_only.
Sourcepub fn assistant_text(&self) -> String
pub fn assistant_text(&self) -> String
Join all recorded assistant text turns into the final answer string.
Why: The AgentOutput.content should be the model’s prose across the
run, not the raw JSON transcript; joining the text turns yields that.
What: Joins the recorded non-empty assistant texts with blank lines.
Test: transcript::tests::assistant_text_joins_turns.
Sourcepub fn push_response(&mut self, resp: &ChatResponse)
pub fn push_response(&mut self, resp: &ChatResponse)
Convenience accessor: push the assistant turn straight from a response.
Why: Callers usually have a ChatResponse in hand; this saves them
destructuring first_text/first_tool_calls at the call site.
What: Extracts the first choice’s text and tool calls and delegates to
push_assistant — EXCEPT for a turn that carries neither, which is
dropped (#8238).
A response with no text and no tool calls has nothing to re-send, and
recording it makes the next request invalid on providers that build the
wire message from content blocks: Bedrock Converse drops the empty text
(trusty_common::inference::bedrock) and then emits NO message for
that turn, so the surrounding tool result and the following user turn
merge into two consecutive user messages and Converse rejects the
request. That is reachable from #8238’s nudge, which appends a user
turn straight after exactly this shape. The direct-Anthropic request
builder already skips a wholly-empty assistant turn for the same
reason; dropping it here fixes every provider at once.
Test: transcript_tests::push_response_appends_a_turn_that_says_something,
transcript_tests::push_response_drops_a_turn_with_no_text_and_no_calls,
agent_loop::tests::sink_events::the_nudge_request_carries_no_empty_assistant_turn.
Sourcepub fn push_user(&mut self, task: &str)
pub fn push_user(&mut self, task: &str)
Append a plain user-role turn WITHOUT re-seeding a system message
(#2344).
Why: session::SessionRegistry::begin_pm_transcript uses this to
hand a SUBSEQUENT task.run on the same session its new request as a
fresh user turn on top of the growing, already-seeded conversation —
Transcript::seed is only ever called ONCE per session, on its
first run.
What: Pushes an uncompacted, unpinned user-role ChatMessage.
Test: transcript_tests::push_user_appends_without_reseeding_system.
Sourcepub fn assistant_text_mark(&self) -> usize
pub fn assistant_text_mark(&self) -> usize
Number of assistant text turns recorded so far (#2344).
Why: AgentLoop::run_with_transcript needs a marker of “how much
assistant text existed before this run” so it can later scope the
run’s OWN reported output to just its new turns via
Self::assistant_text_since, even though the underlying
conversation is persistent and keeps growing across runs.
What: The current length of the internal assistant_texts
accumulator.
Test: transcript_tests::assistant_text_since_scopes_to_new_turns_only.
Sourcepub fn assistant_text_since(&self, mark: usize) -> String
pub fn assistant_text_since(&self, mark: usize) -> String
Join assistant text turns recorded SINCE mark (#2344).
Why: Pairs with Self::assistant_text_mark — see its docs.
What: Joins self.assistant_texts[mark..] the same way
Self::assistant_text joins the whole vec. An out-of-range mark
(should never happen — only ever produced by assistant_text_mark on
the same instance) degrades to an empty string rather than panicking.
Test: transcript_tests::assistant_text_since_scopes_to_new_turns_only,
transcript_tests::assistant_text_since_out_of_range_mark_is_empty_not_panicking.
Sourcepub fn goals_handle(&self) -> Arc<Mutex<GoalSlots>> ⓘ
pub fn goals_handle(&self) -> Arc<Mutex<GoalSlots>> ⓘ
A cloned handle to this transcript’s live goal slots (#2347).
Why: tools::goals::{SetGoalTool, ClearGoalTool} need mutable access
to the EXACT SAME GoalSlots this Transcript renders in
to_messages — cloning the Arc (rather than copying the data)
means a tool’s set/clear call is visible to to_messages on the
very next turn, with no separate sync step. Callers register the
goal tools with this handle BEFORE handing the Transcript to
AgentLoop::run_with_transcript (see task::executor::run_and_record).
What: Arc::clone of the internal goals field.
Test: transcript_tests::goals_handle_mutation_visible_in_to_messages.
Trait Implementations§
Source§impl Clone for Transcript
impl Clone for Transcript
Source§impl Debug for Transcript
impl Debug for Transcript
Auto Trait Implementations§
impl Freeze for Transcript
impl RefUnwindSafe for Transcript
impl Send for Transcript
impl Sync for Transcript
impl Unpin for Transcript
impl UnsafeUnpin for Transcript
impl UnwindSafe for Transcript
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more