1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//! Reading the tool output a client's events left out
//! (`rho/session/tool_output`), by the refs they carried.
//!
//! A ref is the hash of its item (`session_events::deferred`), so the
//! daemon finds it wherever the session still shows the item: a loaded
//! session's buffered live events, then its saved transcript, newest turn
//! first; a run's stream for a session a subagent run under way writes;
//! else the session's file, read as history reads it, without loading it.
//! A ref the session no longer holds renders every turn before the call
//! fails: on a session whose whole replay is 11.9 MB, measured end to end
//! on the daemon's socket, about 18 ms loaded and 75 ms unloaded, against
//! 20 ms and 80 to 97 ms for one it holds.
use rho_protocol::{
self as wire, ErrorCode, RpcError, SessionToolOutputParams, SessionToolOutputResponse,
ToolOutputItem,
};
use super::{locate::Located, reopen::parse_session, unloaded::Unloaded, Sessions, ANSWER_LIMIT};
use crate::app::session_events::{encoded_len, NewestTurns, Wanted};
impl Sessions {
/// The items `params.items` names, as the events that deferred them
/// would have carried them, in the order asked and as many as fit in
/// one message.
pub(in crate::app::daemon_host) async fn tool_output(
&self,
params: SessionToolOutputParams,
) -> Result<SessionToolOutputResponse, RpcError> {
self.refuse_when_stopping()?;
if params.items.is_empty() {
return Err(RpcError::new(
ErrorCode::InvalidParams,
"name at least one item to read",
));
}
let id = parse_session(¶ms.session)?;
let mut wanted = Wanted::new(params.items);
let turns = match self.locate(&id).await {
Located::Loaded(session) => session.feed.find_tool_output(&mut wanted),
Located::Unloaded { run, reopening } => {
// A subagent run under way writes it: its stream's buffered
// events hold what the run showed lately. What they no
// longer hold, the session's file may, which a run still
// writing it refuses to have read, as `SessionBusy`: a
// client asks again once it ends.
if let Some(run) = run {
run.find_tool_output(&mut wanted);
}
if wanted.complete() {
None
} else {
match self.read_unloaded(&reopening).await? {
// An agent runtime's session defers nothing.
Unloaded::Engine { .. } => None,
Unloaded::Saved { feed, .. } => feed.find_tool_output(&mut wanted),
}
}
}
};
let wanted = tokio::task::spawn_blocking(move || {
search(turns, &mut wanted);
wanted
})
.await
.map_err(|error| {
RpcError::new(
ErrorCode::InternalError,
format!("could not search the session for tool output: {error}"),
)
})?;
answer(&wanted)
}
}
/// Takes the items `wanted` still misses from `turns`, rendering them
/// newest first only until none is missing.
fn search(turns: Option<NewestTurns>, wanted: &mut Wanted) {
for event in turns.into_iter().flat_map(NewestTurns::events) {
if wanted.complete() {
return;
}
wanted.find_in(&event.event);
}
}
/// The answer to a call that found `wanted`: `ToolOutputGone` naming each
/// ref not found, else the items in the order asked that fit in one
/// message, at least one.
fn answer(wanted: &Wanted) -> Result<SessionToolOutputResponse, RpcError> {
let gone = wanted.gone();
if !gone.is_empty() {
// The refs go in the data alone: a call may name many.
let message = format!(
"the session no longer holds {} of the tool output items asked",
gone.len()
);
let data = serde_json::to_value(wire::ToolOutputGone::new(gone)).expect("refs are JSON");
return Err(RpcError::new(ErrorCode::ToolOutputGone, message).with_data(data));
}
let mut items = Vec::new();
let mut taken = 0_usize;
for (item, content) in wanted.answers() {
// Every ref asked was found.
let Some(content) = content else { continue };
let item = ToolOutputItem::new(item.clone(), content.clone());
// With a comma between two.
let bytes = encoded_len(&item).unwrap_or(usize::MAX).saturating_add(1);
if taken.saturating_add(bytes) > ANSWER_LIMIT {
if items.is_empty() {
return Err(RpcError::new(
ErrorCode::InternalError,
format!(
"tool output {} takes {bytes} bytes, past what one answer holds \
({ANSWER_LIMIT} bytes, ANSWER_LIMIT); ask for the others",
item.item
),
));
}
break;
}
taken += bytes;
items.push(item);
}
Ok(SessionToolOutputResponse::new(items))
}
#[cfg(test)]
#[path = "tool_output_tests.rs"]
mod tests;