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
//! Generic adoption helpers for the client command channel.
//!
//! A client protocol opts into injected commands (the dashboard's \[send\]
//! button, and any future programmatic control) with a ~10-line diff to its
//! connection loop:
//!
//! ```ignore
//! let mut command_rx = command_support::register_command_channel(&app_state, client_id).await;
//! // ... inside the read loop:
//! tokio::select! {
//! read = read_half.read(&mut buffer) => { /* existing arms unchanged */ }
//! Some(cmd) = command_rx.recv() => {
//! if command_support::handle_stream_client_command(
//! &MyClientProtocol, &write_half_arc, cmd, client_id, &app_state, &status_tx,
//! ).await { break; }
//! }
//! }
//! ```
//!
//! `handle_stream_client_command` is fully generic for split-stream clients:
//! it executes the action through the protocol's own `execute_action` (the
//! same machinery LLM-produced actions use), writes `SendData` results to the
//! write half, and replies with a [`ClientSendOutcome`]. A protocol whose
//! vocabulary produces `Custom` results (IRC's send_privmsg, for instance)
//! writes its own arm body and uses [`reply`] directly.
//!
//! Concurrency note: the command arm runs in the same single task as the read
//! loop, so a command never races the loop's own writes. A command arriving
//! while the loop is mid-LLM-call simply waits its turn in the bounded
//! channel; user injection is deliberately independent of the protocol's
//! Idle/Processing state machine.
//!
//! Cancellation-safety note for adopters: `AsyncReadExt::read` is
//! cancellation-safe, so wrapping it in `tokio::select!` with the command arm
//! does not lose data.
use std::sync::Arc;
use tokio::io::{AsyncWrite, AsyncWriteExt};
use tokio::sync::{mpsc, Mutex};
use tracing::{error, info};
use crate::llm::actions::client_trait::{Client, ClientActionResult};
use crate::state::client_handles::{
ClientCommand, ClientHandle, ClientSendOutcome, CLIENT_COMMAND_CAPACITY,
};
use crate::state::{AccessLogOwner, AppState, ClientId};
/// Create and register the command channel for a running client. Call once the
/// connection is established; move the returned receiver into the loop task.
pub async fn register_command_channel(
state: &AppState,
client_id: ClientId,
) -> mpsc::Receiver<ClientCommand> {
let (command_tx, command_rx) = mpsc::channel(CLIENT_COMMAND_CAPACITY);
state
.register_client_handle(client_id, ClientHandle { command_tx })
.await;
command_rx
}
/// Reply on a command's oneshot, tolerating a caller that stopped listening.
pub fn reply(command: ClientCommand, outcome: anyhow::Result<ClientSendOutcome>) {
let _ = command.reply_tx.send(outcome);
}
/// Generic command-arm body for split-stream clients. Executes the action,
/// maps the result to wire writes, records a client access-log entry, and
/// replies on the command's oneshot.
///
/// Returns `true` when the action requested disconnect and the loop should
/// break (the reply is sent before returning).
pub async fn handle_stream_client_command<W, P>(
protocol: &P,
write_half: &Arc<Mutex<W>>,
command: ClientCommand,
client_id: ClientId,
state: &AppState,
status_tx: &mpsc::UnboundedSender<String>,
) -> bool
where
W: AsyncWrite + Unpin,
P: Client + ?Sized,
{
let action = command.action.clone();
let (outcome, should_break) = execute_command_action(protocol, write_half, &action).await;
// Record the injected action in the access log so it shows up in the
// client's request pane exactly like LLM-produced traffic.
let outcome_json = match &outcome {
Ok(outcome) => serde_json::to_value(outcome).unwrap_or(serde_json::Value::Null),
Err(e) => serde_json::json!({"error": e.to_string()}),
};
state
.record_access_log(
AccessLogOwner::Client(client_id.as_u32()),
protocol.protocol_name(),
None,
"injected_action",
action,
vec![outcome_json],
)
.await;
match &outcome {
Ok(ClientSendOutcome::Sent { bytes_sent }) => {
info!(
"Client {} executed injected action ({} bytes sent)",
client_id, bytes_sent
);
}
Ok(ClientSendOutcome::Disconnected) => {
info!("Client {} disconnecting on injected action", client_id);
}
Ok(_) => {}
Err(e) => {
error!("Client {} injected action failed: {}", client_id, e);
let _ = status_tx.send(format!(
"[WARN] Client {} injected action failed: {}",
client_id, e
));
}
}
let _ = status_tx.send("__UPDATE_UI__".to_string());
reply(command, outcome);
should_break
}
/// Execute one action and fold its (possibly `Multiple`) results into a single
/// outcome. Separated from the reply/logging so it can recurse.
async fn execute_command_action<W, P>(
protocol: &P,
write_half: &Arc<Mutex<W>>,
action: &serde_json::Value,
) -> (anyhow::Result<ClientSendOutcome>, bool)
where
W: AsyncWrite + Unpin,
P: Client + ?Sized,
{
let result = match protocol.execute_action(action.clone()) {
Ok(result) => result,
Err(e) => {
return (
Ok(ClientSendOutcome::Rejected {
error: e.to_string(),
}),
false,
)
}
};
let mut bytes_sent = 0usize;
let mut disconnect = false;
let mut details: Vec<String> = Vec::new();
// Flatten Multiple one level deep — that is the only nesting the enum's
// own producers use.
let results = match result {
ClientActionResult::Multiple(results) => results,
single => vec![single],
};
for result in results {
match result {
ClientActionResult::SendData(bytes) => {
let mut guard = write_half.lock().await;
if let Err(e) = guard.write_all(&bytes).await {
return (Err(anyhow::anyhow!("write failed: {e}")), false);
}
if let Err(e) = guard.flush().await {
return (Err(anyhow::anyhow!("flush failed: {e}")), false);
}
bytes_sent += bytes.len();
}
ClientActionResult::Disconnect => disconnect = true,
ClientActionResult::WaitForMore => details.push("wait_for_more".to_string()),
ClientActionResult::NoAction => details.push("no_action".to_string()),
ClientActionResult::Custom { name, .. } => {
// The generic arm cannot run protocol-specific machinery;
// protocols with Custom vocabularies need a bespoke arm body.
details.push(format!(
"custom result '{name}' not executed by generic arm"
));
}
ClientActionResult::Multiple(_) => {
details.push("nested multiple ignored".to_string());
}
}
}
let outcome = if disconnect {
ClientSendOutcome::Disconnected
} else if bytes_sent > 0 {
ClientSendOutcome::Sent { bytes_sent }
} else {
ClientSendOutcome::Executed {
detail: if details.is_empty() {
"executed".to_string()
} else {
details.join(", ")
},
}
};
(Ok(outcome), disconnect)
}