Skip to main content

Transcript

Struct Transcript 

Source
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

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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. Test: transcript::tests::push_response_appends_assistant.

Source

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.

Source

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.

Source

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.

Source

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

Source§

fn clone(&self) -> Transcript

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Transcript

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Transcript

Source§

fn default() -> Transcript

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more