Skip to content

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

fix(mirror): remove unused state and lifecycle modules

Steven Enamakel35397f961b7c
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror/caps.rs b/crates/openhuman-core/src/threads/turn_state/mirror/caps.rs
deleted file mode 100644
index 042c713ebc..0000000000
--- a/crates/openhuman-core/src/threads/turn_state/mirror/caps.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-//! Size caps applied to snapshot-persisted tool output, tool arguments, and
-//! transcript prose so a runaway stream or oversized payload can't make the
-//! full-file snapshot rewrite (at every tool boundary) unbounded.
-
-/// Upper bound on the tool result text persisted per timeline row. The
-/// snapshot file is rewritten in full at every tool boundary, so this is
-/// deliberately tighter than the 256 KiB live-socket cap — it bounds the
-/// per-flush rewrite while still giving the rehydrated "View processing"
-/// panel a meaningful result preview.
-const MAX_PERSISTED_TOOL_OUTPUT: usize = 64 * 1024;
-
-/// Bytes reserved within the cap for the truncation marker so the final
-/// persisted payload (content + marker) never exceeds
-/// [`MAX_PERSISTED_TOOL_OUTPUT`].
-const TRUNCATION_MARKER_BUDGET: usize = 80;
-
-/// Upper bound on a single persisted transcript prose item (one coalesced
-/// narration or reasoning block, parent or sub-agent). A runaway reasoning
-/// stream would otherwise grow one item without bound and bloat every
-/// full-file snapshot rewrite. Tighter than [`MAX_PERSISTED_TOOL_OUTPUT`]
-/// because a turn can accumulate many prose items.
-pub(crate) const MAX_PERSISTED_TRANSCRIPT_ITEM: usize = 16 * 1024;
-
-/// Marker appended once when a transcript prose item is truncated at its cap.
-pub(super) const TRANSCRIPT_TRUNCATION_MARKER: &str = "\n…[truncated]";
-
-/// Upper bound on the child tool arguments persisted per sub-agent call.
-/// Sized like [`MAX_PERSISTED_TRANSCRIPT_ITEM`] rather than the looser
-/// [`MAX_PERSISTED_TOOL_OUTPUT`]: a sub-agent turn accumulates many child
-/// calls and the snapshot file is rewritten in full at every tool boundary,
-/// so one `write_file`-shaped payload must not dominate every rewrite.
-const MAX_PERSISTED_TOOL_ARGS: usize = 16 * 1024;
-
-/// Append `delta` to a coalescing transcript prose buffer, enforcing
-/// [`MAX_PERSISTED_TRANSCRIPT_ITEM`] on a char boundary and stamping a one-time
-/// truncation marker the first time the cap is hit. Once at the cap, further
-/// deltas are dropped (the marker is already present). Used by both the parent
-/// and sub-agent transcript coalescers so a single streamed block stays bounded.
-pub(super) fn append_capped_transcript_text(text: &mut String, delta: &str) {
- if delta.is_empty() {
- return;
- }
- if text.len() >= MAX_PERSISTED_TRANSCRIPT_ITEM {
- // Already at the cap but more content is arriving — ensure the marker is
- // present exactly once so the truncation is visible even when deltas
- // land exactly on the boundary (never straddling it).
- if !text.ends_with(TRANSCRIPT_TRUNCATION_MARKER) {
- text.push_str(TRANSCRIPT_TRUNCATION_MARKER);
- }
- return;
- }
- let remaining = MAX_PERSISTED_TRANSCRIPT_ITEM - text.len();
- if delta.len() <= remaining {
- text.push_str(delta);
- return;
- }
- let mut end = remaining;
- while end > 0 && !delta.is_char_boundary(end) {
- end -= 1;
- }
- text.push_str(&delta[..end]);
- text.push_str(TRANSCRIPT_TRUNCATION_MARKER);
-}
-
-/// Cap `output` for snapshot persistence, slicing on a char boundary and
-/// appending a truncation marker when content was dropped. Returns `None`
-/// for empty output (payload capture off) so the field serializes away.
-pub(super) fn cap_persisted_output(output: &str) -> Option<String> {
- if output.is_empty() {
- return None;
- }
- if output.len() <= MAX_PERSISTED_TOOL_OUTPUT {
- return Some(output.to_string());
- }
- let mut end = MAX_PERSISTED_TOOL_OUTPUT.saturating_sub(TRUNCATION_MARKER_BUDGET);
- while end > 0 && !output.is_char_boundary(end) {
- end -= 1;
- }
- let omitted = output.len() - end;
- Some(format!(
- "{}\n…[truncated {omitted} bytes of tool output]",
- &output[..end]
- ))
-}
-
-/// Cap `arguments` for snapshot persistence. Returns `None` for a null
-/// payload, which would otherwise persist as a meaningless "Input: null" row.
-///
-/// A null is not the same as "this call had no input": on the tinyagents path
-/// the *started* event always carries `Value::Null` and the captured arguments
-/// only arrive with `SubagentToolCallCompleted`, so the completion arm
-/// backfills what this returns `None` for at start.
-///
-/// A payload that serialises within [`MAX_PERSISTED_TOOL_ARGS`] is kept
-/// verbatim, so the rehydrated row renders the same structured input the live
-/// row did. An oversized one degrades to a truncated *string* carrying the
-/// same marker shape [`cap_persisted_output`] uses: the prefix is what the
-/// reader actually wants ("what did it search for?"), and a string is honest
-/// about no longer being parseable JSON.
-pub(super) fn cap_persisted_args(arguments: &serde_json::Value) -> Option<serde_json::Value> {
- if arguments.is_null() {
- return None;
- }
- let rendered = arguments.to_string();
- if rendered.len() <= MAX_PERSISTED_TOOL_ARGS {
- return Some(arguments.clone());
- }
- let mut end = MAX_PERSISTED_TOOL_ARGS.saturating_sub(TRUNCATION_MARKER_BUDGET);
- while end > 0 && !rendered.is_char_boundary(end) {
- end -= 1;
- }
- let omitted = rendered.len() - end;
- Some(serde_json::Value::String(format!(
- "{}\n…[truncated {omitted} bytes of tool arguments]",
- &rendered[..end]
- )))
-}
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs b/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs
deleted file mode 100644
index 05481cf58d..0000000000
--- a/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs
+++ /dev/null
@@ -1,118 +0,0 @@
-//! Snapshot flush, interrupted-turn finalization, and the partial-answer
-//! carry-over into the session transcript.
-
-use super::state::TurnStateMirror;
-use tinyagents_session::turn_state::types::TurnLifecycle;
-
-pub(super) const MIRROR_LOG_PREFIX: &str = "[threads:turn_state:mirror]";
-
-impl TurnStateMirror {
- /// Mark the turn as `Interrupted` on the in-memory snapshot and
- /// flush. Called when the bridge exits without a `TurnCompleted`
- /// event (i.e. the agent loop errored out).
- pub fn finish(mut self) {
- if self.turn_completed {
- return;
- }
- // The turn driver settles this snapshot the moment the turn ends
- // (`TurnStateStore::settle_turn`), because this bridge can outlive its
- // turn by minutes — it only exits when its progress sender drops, and
- // for a cached per-thread session that waits for the *next* turn. If the
- // driver already recorded a terminal outcome, keep it: a late blind
- // `Interrupted` here would raise a retry banner on a turn that actually
- // succeeded and whose reply was delivered.
- let already_completed = matches!(
- self.store
- .get_turn(&self.state.thread_id, &self.state.request_id)
- .ok()
- .flatten()
- .map(|snapshot| snapshot.lifecycle),
- Some(TurnLifecycle::Completed)
- );
- self.state.lifecycle = if already_completed {
- self.state.phase = None;
- TurnLifecycle::Completed
- } else {
- TurnLifecycle::Interrupted
- };
- self.state.active_tool = None;
- self.state.active_subagent = None;
- self.state.updated_at = chrono::Utc::now().to_rfc3339();
- self.flush();
- // Only a genuinely interrupted turn has a partial answer to carry over;
- // a settled turn's reply was already delivered and persisted, and
- // appending it again would duplicate it in the session transcript.
- if !already_completed {
- self.persist_interrupted_partial();
- }
- }
-
- /// Append the partial streamed answer of an interrupted turn to the session
- /// transcript so the derived display view (Phase B) can surface it even
- /// after the live turn_state snapshot is gone. Display-only: the
- /// model-context reader skips `interrupted:true` lines.
- ///
- /// Guard: the root transcript file must already exist. An interrupted
- /// **first** turn has no session file yet (the harness has not persisted a
- /// turn), so there is nothing to append to — that case stays recoverable
- /// from the turn_state snapshot alone, as today. We log and skip it.
- fn persist_interrupted_partial(&self) {
- let partial = self.state.streaming_text.trim();
- if partial.is_empty() {
- return;
- }
- let thread_id = self.state.thread_id.trim();
- if thread_id.is_empty() {
- return;
- }
- let workspace_dir = self.store.workspace_dir();
- let Some(path) = tinyagents_session::transcript::find_root_transcript_for_thread(
- workspace_dir,
- thread_id,
- ) else {
- log::debug!(
- "{MIRROR_LOG_PREFIX} no root transcript for thread={thread_id} yet — leaving interrupted partial ({} chars) in turn_state snapshot only",
- partial.len()
- );
- return;
- };
- let request_id = if self.state.request_id.is_empty() {
- None
- } else {
- Some(self.state.request_id.as_str())
- };
- let thinking = self.state.thinking.trim();
- let reasoning = if thinking.is_empty() {
- None
- } else {
- Some(thinking)
- };
- match tinyagents_session::transcript::append_interrupted_partial(
- &path,
- partial,
- request_id,
- Some(self.state.iteration),
- reasoning,
- ) {
- Ok(()) => log::debug!(
- "{MIRROR_LOG_PREFIX} appended interrupted partial ({} chars, thinking={} chars) for thread={thread_id} request_id={} to {}",
- partial.len(),
- thinking.len(),
- self.state.request_id,
- path.display()
- ),
- Err(err) => log::warn!(
- "{MIRROR_LOG_PREFIX} failed to append interrupted partial for thread={thread_id}: {err}"
- ),
- }
- }
-
- pub(super) fn flush(&mut self) {
- if let Err(err) = self.store.put(&self.state) {
- log::warn!(
- "{MIRROR_LOG_PREFIX} failed to persist snapshot for thread={}: {err}",
- self.state.thread_id
- );
- }
- }
-}
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror/observe.rs b/crates/openhuman-core/src/threads/turn_state/mirror/observe.rs
index 24eee6eb26..7e1c2164ef 100644
--- a/crates/openhuman-core/src/threads/turn_state/mirror/observe.rs
+++ b/crates/openhuman-core/src/threads/turn_state/mirror/observe.rs
@@ -455,161 +455,4 @@ impl TurnStateMirror {
}
}
}
-
- /// Append a visible-narration delta to the transcript, coalescing into
- /// the trailing [`TranscriptItem::Narration`] when it's the most recent
- /// item and from the same round — so a streamed paragraph stays one item
- /// instead of one-per-token. A new round (or any intervening thinking /
- /// tool item) starts a fresh narration block.
- fn push_transcript_narration(&mut self, round: u32, delta: &str) {
- if let Some(TranscriptItem::Narration { round: r, text, .. }) =
- self.state.transcript.last_mut()
- {
- if *r == round {
- append_capped_transcript_text(text, delta);
- return;
- }
- }
- let seq = self.next_seq();
- let mut text = String::new();
- append_capped_transcript_text(&mut text, delta);
- self.state
- .transcript
- .push(TranscriptItem::Narration { round, seq, text });
- }
-
- /// Append a hidden-reasoning delta to the transcript, with the same
- /// coalescing rule as [`Self::push_transcript_narration`].
- ///
- /// Stamps the block's first delta as `started_at` and every appended delta
- /// as `ended_at` (epoch ms), which is what the "Thought for Ns" label reads.
- fn push_transcript_thinking(&mut self, round: u32, delta: &str) {
- let now = now_epoch_ms();
- if let Some(TranscriptItem::Thinking {
- round: r,
- text,
- ended_at,
- ..
- }) = self.state.transcript.last_mut()
- {
- if *r == round {
- append_capped_transcript_text(text, delta);
- *ended_at = Some(now);
- return;
- }
- }
- let seq = self.next_seq();
- let mut text = String::new();
- append_capped_transcript_text(&mut text, delta);
- log::trace!("[turn_state] thinking block opened round={round} seq={seq}");
- self.state.transcript.push(TranscriptItem::Thinking {
- round,
- seq,
- text,
- started_at: Some(now),
- ended_at: Some(now),
- });
- }
-
- /// Record a tool call in the transcript at the point it occurred, as a
- /// pointer into [`TurnState::tool_timeline`] (the row's status/label live
- /// there). Skips a duplicate if the same `call_id` was already recorded
- /// (e.g. a start event after an args-delta placeholder).
- fn push_transcript_tool(&mut self, round: u32, call_id: &str) {
- let already = self.state.transcript.iter().any(
- |item| matches!(item, TranscriptItem::ToolCall { call_id: c, .. } if c == call_id),
- );
- if already {
- return;
- }
- let seq = self.next_seq();
- self.state.transcript.push(TranscriptItem::ToolCall {
- round,
- seq,
- call_id: call_id.to_string(),
- });
- }
-
- /// Return the next monotonic transcript ordering key and advance it.
- fn next_seq(&mut self) -> u32 {
- let seq = self.next_seq;
- self.next_seq = self.next_seq.saturating_add(1);
- seq
- }
-
- /// Return the next monotonic tool-timeline ordering key and advance it.
- fn next_tool_seq(&mut self) -> u64 {
- let seq = self.next_tool_seq;
- self.next_tool_seq = self.next_tool_seq.saturating_add(1);
- seq
- }
-
- fn find_subagent_entry_mut(&mut self, task_id: &str) -> Option<&mut ToolTimelineEntry> {
- let needle = format!("subagent:{task_id}");
- self.state
- .tool_timeline
- .iter_mut()
- .rev()
- .find(|entry| entry.id == needle)
- }
-
- /// Append a sub-agent prose delta (narration when `is_thinking == false`,
- /// reasoning otherwise) to that sub-agent's transcript, coalescing into the
- /// trailing same-kind, same-iteration item so a streamed paragraph stays
- /// one entry (mirrors the frontend `appendSubagentStreamDelta`). Mutate-
- /// only (no flush) — high-frequency like the parent's `TextDelta`; the
- /// accumulated prose is persisted at the next sub-agent tool boundary.
- fn push_subagent_prose(
- &mut self,
- task_id: &str,
- iteration: u32,
- delta: &str,
- is_thinking: bool,
- ) {
- let Some(entry) = self.find_subagent_entry_mut(task_id) else {
- return;
- };
- let Some(activity) = entry.subagent.as_mut() else {
- return;
- };
- match activity.transcript.last_mut() {
- Some(SubagentTranscriptItem::Thinking {
- iteration: it,
- text,
- }) if is_thinking && *it == Some(iteration) => {
- append_capped_transcript_text(text, delta);
- return;
- }
- Some(SubagentTranscriptItem::Text {
- iteration: it,
- text,
- }) if !is_thinking && *it == Some(iteration) => {
- append_capped_transcript_text(text, delta);
- return;
- }
- _ => {}
- }
- let mut text = String::new();
- append_capped_transcript_text(&mut text, delta);
- activity.transcript.push(if is_thinking {
- SubagentTranscriptItem::Thinking {
- iteration: Some(iteration),
- text,
- }
- } else {
- SubagentTranscriptItem::Text {
- iteration: Some(iteration),
- text,
- }
- });
- }
-}
-
-/// Wall-clock epoch milliseconds for transcript timing (0 if the clock is
-/// before the epoch, which only a broken system clock produces).
-fn now_epoch_ms() -> u64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
- .unwrap_or(0)
}
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror/state.rs b/crates/openhuman-core/src/threads/turn_state/mirror/state.rs
deleted file mode 100644
index 595d851085..0000000000
--- a/crates/openhuman-core/src/threads/turn_state/mirror/state.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-use tinyagents_session::turn_state::store::TurnStateStore;
-use tinyagents_session::turn_state::types::TurnState;
-
-/// In-process cursor that keeps the authoritative [`TurnState`] in sync
-/// with the agent loop and writes it through to a [`TurnStateStore`].
-pub struct TurnStateMirror {
- pub(super) store: TurnStateStore,
- pub(super) state: TurnState,
- /// Set to `true` once we observe `TurnCompleted` so `finish` knows
- /// to delete the snapshot rather than mark it interrupted.
- pub(super) turn_completed: bool,
- /// Monotonic ordering key for [`TranscriptItem`]s. Round alone can't
- /// order narration vs thinking vs tool calls *within* one iteration, so
- /// every transcript push stamps and increments this.
- pub(super) next_seq: u32,
- /// Separate monotonic ordering key for [`ToolTimelineEntry::seq`] — the flat
- /// timeline is an independent projection from the interleaved transcript, so
- /// it gets its own space (sharing `next_seq` would leave gaps in the
- /// transcript's contiguous ordering).
- pub(super) next_tool_seq: u64,
-}
-
-impl TurnStateMirror {
- /// Build a mirror primed with a `Started` snapshot and immediately
- /// flush so a crash before the first agent event still leaves a
- /// recoverable record.
- pub fn new(
- store: TurnStateStore,
- thread_id: impl Into<String>,
- request_id: impl Into<String>,
- ) -> Self {
- let now = chrono::Utc::now().to_rfc3339();
- let state = TurnState::started(thread_id, request_id, 0, now);
- let mut mirror = Self {
- store,
- state,
- turn_completed: false,
- next_seq: 0,
- next_tool_seq: 0,
- };
- mirror.flush();
- mirror
- }
-
- #[cfg(test)]
- pub(crate) fn snapshot(&self) -> &TurnState {
- &self.state
- }
-}
diff --git a/vendor/tinyagents b/vendor/tinyagents
index fd2e81d4f8..264564e28e 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit fd2e81d4f8dce45b7e2084f5fc7c5eea35c7e14e
+Subproject commit 264564e28e104f778c561ae58917f2b8d57c1298