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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! The session a run on an external agent runtime (Claude Code,
//! Antigravity) is recorded under: the wire events of what the run records
//! ([`AttachmentEvent`]), so clients observe it as they observe a Rho
//! child's session, live or replayed from the run's attach journal, and the
//! options that session shows.
//!
//! The run keeps its runtime's own conversation; the session's file holds
//! only its prompt and reply (see [`crate::session::SessionEngine::Acp`]).
//! How the run ended comes from its status, as a Rho child's does.
use rho_protocol::{
display::{Presentation, ToolCard, ToolCardStatus},
ContentBlock, ModelChoice, ModelOptions, ModelRef, PermissionModeOptions,
SessionEvent as WireEvent, SessionOptions, ToolCallId, ToolCallUpdate, ToolStatus,
};
use super::{
card, header_title,
message_ids::{fresh_message_id, ChunkKind, MessageStream},
status_update, CallIds,
};
use crate::{
cli_runtime::agent_event::render::MAX_ACTIVE_TOOLS,
display_transcript::{DisplayRow, NotificationRow},
presentation::checklist::{plan_card, EXTERNAL_PLAN_KEY},
run_artifacts::AttachmentEvent,
};
/// The model an external run shows when its agent pins none: the runtime
/// chooses, and reports which only as the run goes.
const RUNTIME_DEFAULT_MODEL: &str = "default";
/// The model an external run whose agent pins `model`, if any, runs on, as
/// its session shows it.
pub(crate) fn runtime_model(model: Option<&str>) -> &str {
model.unwrap_or(RUNTIME_DEFAULT_MODEL)
}
/// Maps one external run's recorded events, in order, to its session's.
#[derive(Default)]
pub(crate) struct ExternalEvents {
messages: MessageStream,
/// Ids for calls recorded without a key.
calls: CallIds,
/// The calls started and not finished, in the order they started, with
/// the card each last showed: the run's end closes them, as an agent's
/// plan, which it never finishes.
open: Vec<(ToolCallId, ToolCard)>,
}
impl ExternalEvents {
/// The wire events of `event`; none for what clients are told another
/// way, or not at all.
pub(crate) fn map(&mut self, event: &AttachmentEvent) -> Vec<WireEvent> {
let events = self.wire_events(event);
if events.iter().any(|event| {
!matches!(
event,
WireEvent::AgentMessageChunk { .. } | WireEvent::ThoughtChunk { .. }
)
}) {
// Text after anything else starts a message.
self.messages.interrupt();
}
events
}
fn wire_events(&mut self, event: &AttachmentEvent) -> Vec<WireEvent> {
match event {
AttachmentEvent::Prompt(text) => vec![WireEvent::UserMessage {
message: fresh_message_id(),
content: vec![ContentBlock::Text { text: text.clone() }],
steer: None,
}],
AttachmentEvent::PromptContent(content) => vec![WireEvent::UserMessage {
message: fresh_message_id(),
content: content.clone(),
steer: None,
}],
AttachmentEvent::Steered { steer, content } => vec![WireEvent::UserMessage {
message: fresh_message_id(),
content: content.clone(),
steer: Some(steer.clone()),
}],
AttachmentEvent::Message(message) => {
let row = DisplayRow::Notification(Box::new(NotificationRow {
card: (**message).clone(),
info: None,
}));
vec![card(&row).event]
}
AttachmentEvent::AssistantTextDelta(text) => vec![WireEvent::AgentMessageChunk {
message: self.messages.chunk(ChunkKind::Agent),
text: text.clone(),
}],
AttachmentEvent::ReasoningDelta(text) => vec![WireEvent::ThoughtChunk {
message: self.messages.chunk(ChunkKind::Thought),
text: text.clone(),
}],
AttachmentEvent::ToolStarted { key, card } => {
let id = self.call_id(key.as_deref());
self.shown(&id, card);
vec![WireEvent::tool_call(ToolCallUpdate {
title: header_title(card.header.clone()),
display: Some(Presentation::Card(card.clone())),
..status_update(id, tool_status(card.status))
})]
}
AttachmentEvent::ToolUpdated { key, card } => {
let id = self.call_id(key.as_deref());
self.shown(&id, card);
vec![WireEvent::tool_call(ToolCallUpdate {
display: Some(Presentation::Card(card.clone())),
..status_update(id, tool_status(card.status))
})]
}
AttachmentEvent::ToolFinished { key, presentation } => {
let status = match presentation {
Presentation::Card(card) | Presentation::SummaryCard(card) => {
tool_status(card.status)
}
Presentation::Notification(_) => Some(ToolStatus::Completed),
};
let id = self.call_id(key.as_deref());
self.open.retain(|(open, _)| *open != id);
vec![WireEvent::tool_call(ToolCallUpdate {
display: Some(presentation.clone()),
..status_update(id, status)
})]
}
// Absent fields are unchanged: the call keeps its card and
// status, and shows `content` until a later update replaces it.
AttachmentEvent::ToolContent { key, content } => {
vec![WireEvent::tool_call(ToolCallUpdate {
content: Some(content.clone()),
..status_update(ToolCallId::new(key), /*status*/ None)
})]
}
AttachmentEvent::Notice(text) => vec![WireEvent::Notice { text: text.clone() }],
// The session's plan, and the card that shows it among the
// run's calls, as a Rho session's todo shows both.
AttachmentEvent::Plan(entries) => {
let card = AttachmentEvent::ToolStarted {
key: Some(EXTERNAL_PLAN_KEY.to_owned()),
card: plan_card(entries),
};
let mut events = vec![WireEvent::Plan {
entries: entries.clone(),
}];
events.extend(self.wire_events(&card));
events
}
AttachmentEvent::ContextUsage(usage) => usage
.tokens
.map(|used_tokens| WireEvent::Usage {
used_tokens,
window_tokens: usage.context_window,
cost_usd_micros: None,
})
.into_iter()
.collect(),
// The run's end closes its open calls as it ended; how it ended
// comes from its status, which the run's follower reports.
AttachmentEvent::Completed => self.close_open(ToolCardStatus::Ok),
AttachmentEvent::Cancelled => self.close_open(ToolCardStatus::Interrupted),
AttachmentEvent::Failed(_) => self.close_open(ToolCardStatus::Error),
// Argument previews are a Rho child's alone; a model call's
// usage and a step's start show in the run's status.
AttachmentEvent::ToolPreview { .. }
| AttachmentEvent::Usage(_)
| AttachmentEvent::ModelCallCompleted { .. }
| AttachmentEvent::StepStarted
| AttachmentEvent::ProviderStreamReset => Vec::new(),
}
}
/// Closes the calls still open as interrupted, for a run whose journal
/// ends without its end, as when the daemon running it died: none once
/// the run's end closed them.
pub(crate) fn cut_short(&mut self) -> Vec<WireEvent> {
self.close_open(ToolCardStatus::Interrupted)
}
/// Keeps call `id` open with `card`, while the card shows it running.
/// Past as many open calls as the run's renderer keeps in flight, which
/// announces its own overflow, a call is shown but not kept open: the
/// first, as the plan, are the ones the run's end must close.
fn shown(&mut self, id: &ToolCallId, card: &ToolCard) {
self.open.retain(|(open, _)| open != id);
if card.status == ToolCardStatus::Running && self.open.len() < MAX_ACTIVE_TOOLS {
self.open.push((id.clone(), card.clone()));
}
}
/// Closes the calls still open, their last cards showing `status`: a
/// completed run's as completed, since what an agent leaves open when
/// it ends, as its plan, ended with it.
fn close_open(&mut self, status: ToolCardStatus) -> Vec<WireEvent> {
std::mem::take(&mut self.open)
.into_iter()
.map(|(id, mut card)| {
card.status = status;
WireEvent::tool_call(ToolCallUpdate {
display: Some(Presentation::Card(card)),
..status_update(id, tool_status(status))
})
})
.collect()
}
/// Call `key`'s id; for a call recorded without a key, which no later
/// event names, a numbered one.
fn call_id(&mut self, key: Option<&str>) -> ToolCallId {
match key {
Some(key) => ToolCallId::new(key),
None => self.calls.open(""),
}
}
}
/// The options the session of an external run shows: the `provider`,
/// `model` (if its agent pins one) and `mode` it was bound with, which
/// nobody changes while it runs.
pub(crate) fn external_options(
provider: &str,
model: Option<&str>,
mode: rho_protocol::PermissionMode,
) -> SessionOptions {
let model = runtime_model(model).to_owned();
let current = ModelRef {
provider: provider.to_owned(),
model: model.clone(),
};
SessionOptions {
model: ModelOptions {
available: vec![ModelChoice {
model: current.clone(),
label: model,
}],
current,
// The runtime signs in itself; its sign-in is its provider's.
auth: provider.to_owned(),
},
reasoning: None,
fast_mode: None,
permission_mode: PermissionModeOptions {
current: mode,
available: vec![mode],
},
commands: Vec::new(),
added_dirs: Vec::new(),
}
}
fn tool_status(status: ToolCardStatus) -> Option<ToolStatus> {
match status {
ToolCardStatus::Running => Some(ToolStatus::InProgress),
ToolCardStatus::Ok => Some(ToolStatus::Completed),
ToolCardStatus::Error => Some(ToolStatus::Failed),
ToolCardStatus::Interrupted => Some(ToolStatus::Cancelled),
// `Unknown`, or a status a newer protocol adds.
_ => None,
}
}
#[cfg(test)]
#[path = "external_tests.rs"]
mod tests;