trusty_code/run_task/recorder.rs
1//! Transcript-recording `LlmClientTrait` decorator (#1034).
2//!
3//! Why: `AgentLoop::run` returns only the final `AgentOutput` (content + usage);
4//! it does not expose the per-turn conversation. The `run-task` command must
5//! emit a structured transcript of every PM and engineer turn (model + assistant
6//! text + tool calls). Rather than change the loop's signature, we wrap the
7//! shared `LlmClientTrait` in a recorder that observes each request/response
8//! pair and appends a `TurnRecord`. The wrapper is transparent — it forwards to
9//! the inner client unchanged — so the real OpenRouter client and the offline
10//! mock both work behind it.
11//! What: `RecordingLlmClient` holds an inner `Arc<dyn LlmClientTrait>`, a role
12//! label (`"pm"` / `"python-engineer"`), and a shared `Arc<Mutex<Vec<TurnRecord>>>`.
13//! Each `chat` call records the resolved model and the resulting assistant text
14//! plus tool-call names, then returns the inner response verbatim.
15//! Test: `run_task::tests` assert the recorded transcript carries both roles, and
16//! the per-run engineer model slug.
17
18use std::sync::{Arc, Mutex};
19
20use async_trait::async_trait;
21use serde::{Deserialize, Serialize};
22
23use crate::llm::{ChatRequest, ChatResponse, LlmClientTrait, LlmError};
24use crate::perf::TokenUsage;
25
26/// One recorded assistant turn for the run transcript.
27///
28/// Why: The transcript output needs a machine- and human-renderable shape that
29/// captures who spoke (role), with which model, what text, and which tools it
30/// invoked — enough to reconstruct the PM→engineer interaction without leaking
31/// the full raw message history.
32/// What: `role` is the agent label; `model` is the resolved slug for that turn;
33/// `text` is the assistant prose (empty for tool-only turns); `tool_calls` lists
34/// the invoked tool names in order; `usage` is the token usage the provider
35/// reported for this turn (the per-turn unit the run aggregates over both PM and
36/// engineer turns, since the engineer's usage is otherwise lost when its output
37/// flows back to the PM as a tool-result string). `Deserialize` (#2060) lets
38/// `tcode`'s CLI thin client parse a `session.get_transcript` JSON-RPC result
39/// straight back into `Vec<TurnRecord>`.
40/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`.
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
42pub struct TurnRecord {
43 /// Agent label that produced this turn (e.g. `"pm"`, `"python-engineer"`).
44 pub role: String,
45 /// Resolved model slug used for this turn.
46 pub model: String,
47 /// Assistant prose for the turn (empty string for tool-only turns).
48 pub text: String,
49 /// Names of tools the assistant called this turn, in order.
50 pub tool_calls: Vec<String>,
51 /// Token usage the provider reported for this turn.
52 pub usage: TokenUsage,
53}
54
55/// Shared, thread-safe transcript accumulator.
56///
57/// Why: The PM and engineer recorders run on the same tokio runtime and both
58/// append to one ordered transcript; an `Arc<Mutex<…>>` is the minimal shared
59/// sink that keeps turn order without global state.
60/// What: A type alias for the shared vector of `TurnRecord`s.
61/// Test: Exercised by every `run_task` end-to-end test.
62pub type SharedTranscript = Arc<Mutex<Vec<TurnRecord>>>;
63
64/// A transparent `LlmClientTrait` that records each turn into a shared transcript.
65///
66/// Why: Captures the conversation for the run report without modifying the agent
67/// loop. Wrapping the shared client means PM and engineer turns land in one
68/// ordered transcript while usage still accrues on the inner client.
69/// What: Forwards `chat` to the inner client, then appends a `TurnRecord` tagged
70/// with this wrapper's `role` and the request's model. A poisoned transcript
71/// lock is treated as a no-op record (the run must not panic mid-flight).
72/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`.
73pub struct RecordingLlmClient {
74 inner: Arc<dyn LlmClientTrait>,
75 role: String,
76 transcript: SharedTranscript,
77}
78
79impl RecordingLlmClient {
80 /// Wrap `inner`, tagging recorded turns with `role`.
81 ///
82 /// Why: Each agent (PM, engineer) needs its own labelled recorder sharing the
83 /// same transcript sink so the report can distinguish their turns.
84 /// What: Stores the inner client, the role label, and the shared transcript.
85 /// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`.
86 pub fn new(
87 inner: Arc<dyn LlmClientTrait>,
88 role: impl Into<String>,
89 transcript: SharedTranscript,
90 ) -> Self {
91 Self {
92 inner,
93 role: role.into(),
94 transcript,
95 }
96 }
97}
98
99#[async_trait]
100impl LlmClientTrait for RecordingLlmClient {
101 /// Forward the chat call and record the resulting turn.
102 ///
103 /// Why: The transcript must reflect exactly what the model returned; recording
104 /// after the call (on success) keeps the report faithful and never fabricates
105 /// turns for failed requests.
106 /// What: Calls the inner client; on `Ok`, appends a `TurnRecord` with the
107 /// RESOLVED model slug (#1475 bug 2 — `resp.resolved_model(&req.model)`,
108 /// which prefers the provider-reported model and falls back to the
109 /// requested slug when the response omits one), the response's first
110 /// text, and its tool-call names; returns the response unchanged. Errors
111 /// propagate untouched (and are not recorded).
112 /// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`,
113 /// `run_task::tests::transcript_records_resolved_model_not_requested_slug`.
114 async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
115 let resp = self.inner.chat(req).await?;
116
117 let tool_calls = resp
118 .first_tool_calls()
119 .iter()
120 .map(|c| c.function.name.clone())
121 .collect();
122 let record = TurnRecord {
123 role: self.role.clone(),
124 model: resp.resolved_model(&req.model).to_string(),
125 text: resp.first_text().unwrap_or_default(),
126 tool_calls,
127 usage: resp.clone().token_usage(),
128 };
129
130 // A poisoned lock must not abort the run; drop the record rather than panic.
131 if let Ok(mut guard) = self.transcript.lock() {
132 guard.push(record);
133 }
134
135 Ok(resp)
136 }
137}