1mod execution;
7mod interaction;
8mod output;
9mod tui;
10
11use std::sync::Arc;
12
13use tokio::sync::Mutex;
14use tracing::{error, info};
15
16pub use super::background_shell::{BackgroundShellManager, ExitedShellInfo};
17use crate::errors::{Result, WinxError};
18use crate::runtime::{lock_session_store, EmbeddedShellRuntime, ShellRuntime, ShellTarget};
19use crate::state::bash_state::BashState;
20use crate::state::live_terminal::ScreenUpdate;
21use crate::state::pty::PtyShell;
22use crate::types::{normalize_thread_id, BashCommand, BashCommandAction};
23
24use execution::execute_command;
25use interaction::{execute_send_ascii, execute_send_specials, execute_send_text};
26use output::{execute_status_check, finalize_tombstone};
27use tui::{execute_screen, execute_wait_for_turn};
28
29type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;
30
31#[derive(Debug, Default)]
34pub(crate) struct ShellDeliveryCursor {
35 generation: Option<u64>,
36 delivered_output: String,
37 last_returned_hash: Option<u64>,
38 screen_snapshot: Option<Vec<String>>,
39}
40
41impl ShellDeliveryCursor {
42 fn sync_generation(&mut self, generation: u64) {
43 if self.generation != Some(generation) {
44 self.generation = Some(generation);
45 self.delivered_output.clear();
46 self.last_returned_hash = None;
47 self.screen_snapshot = None;
48 }
49 }
50
51 fn screen_update(&mut self, current: Vec<String>, threshold: usize) -> ScreenUpdate {
52 let update = match self.screen_snapshot.as_ref() {
53 Some(previous) => {
54 let rows = previous.len().max(current.len());
55 let changed = (0..rows)
56 .filter_map(|index| {
57 let before = previous.get(index).map_or("", String::as_str);
58 let after = current.get(index).map_or("", String::as_str);
59 (before != after).then(|| (index + 1, after.to_string()))
60 })
61 .collect::<Vec<_>>();
62 if changed.is_empty() {
63 ScreenUpdate::Unchanged
64 } else if changed.len() <= threshold {
65 ScreenUpdate::Diff(changed)
66 } else {
67 ScreenUpdate::Full(current.clone())
68 }
69 }
70 None => ScreenUpdate::Full(current.clone()),
71 };
72 self.screen_snapshot = Some(current);
73 update
74 }
75}
76
77fn main_shell(bash_state: &BashState) -> SharedPtyShell {
78 let mut store = lock_session_store();
79 store.bind_main(&bash_state.current_thread_id, &bash_state.pty_shell);
80 store
81 .resolve(&bash_state.current_thread_id, &ShellTarget::Main)
82 .unwrap_or_else(|| bash_state.pty_shell.clone())
83}
84
85const DEFAULT_TIMEOUT: f64 = 5.0;
86
87fn effective_wait_for_seconds(wait_for_seconds: Option<f32>) -> f64 {
88 wait_for_seconds.map_or(DEFAULT_TIMEOUT, |seconds| f64::from(seconds).max(0.0))
89}
90
91fn send_utf8_in_byte_chunks(shell: &mut PtyShell, text: &str, chunk_size: usize) -> Result<()> {
92 let mut start = 0;
93 while start < text.len() {
94 let mut end = (start + chunk_size).min(text.len());
95 while !text.is_char_boundary(end) {
96 end -= 1;
97 }
98 if end == start {
99 end =
100 text[start..].char_indices().nth(1).map_or(text.len(), |(index, _)| start + index);
101 }
102 shell.send_text(&text[start..end]).map_err(|error| {
103 WinxError::CommandExecutionError(format!("Failed to write PTY input: {error}"))
104 })?;
105 start = end;
106 }
107 Ok(())
108}
109
110pub async fn handle_tool_call(
112 bash_state: &Arc<Mutex<Option<BashState>>>,
113 command: BashCommand,
114) -> Result<String> {
115 handle_tool_call_with_runtime(&EmbeddedShellRuntime, bash_state, command).await
116}
117
118pub async fn handle_tool_call_with_runtime(
120 runtime: &dyn ShellRuntime,
121 bash_state: &Arc<Mutex<Option<BashState>>>,
122 command: BashCommand,
123) -> Result<String> {
124 runtime.run_action(bash_state, command).await
125}
126
127pub(crate) async fn handle_embedded_tool_call(
128 bash_state: &Arc<Mutex<Option<BashState>>>,
129 command: BashCommand,
130) -> Result<String> {
131 handle_embedded_tool_call_inner(bash_state, command, None).await
132}
133
134pub(crate) async fn handle_embedded_tool_call_with_cursor(
135 bash_state: &Arc<Mutex<Option<BashState>>>,
136 command: BashCommand,
137 delivery_cursor: &Arc<Mutex<ShellDeliveryCursor>>,
138) -> Result<String> {
139 let mut delivery_cursor = delivery_cursor.lock().await;
140 handle_embedded_tool_call_inner(bash_state, command, Some(&mut delivery_cursor)).await
141}
142
143#[tracing::instrument(level = "info", skip(bash_state, command, delivery_cursor))]
144async fn handle_embedded_tool_call_inner(
145 bash_state: &Arc<Mutex<Option<BashState>>>,
146 command: BashCommand,
147 delivery_cursor: Option<&mut ShellDeliveryCursor>,
148) -> Result<String> {
149 let action_kind = match &command.action_json {
150 BashCommandAction::Command { .. } => "command",
151 BashCommandAction::StatusCheck { .. } => "status_check",
152 BashCommandAction::SendText { .. } => "send_text",
153 BashCommandAction::SendSpecials { .. } => "send_specials",
154 BashCommandAction::SendAscii { .. } => "send_ascii",
155 BashCommandAction::Screen { .. } => "screen",
156 BashCommandAction::WaitForTurn { .. } => "wait_for_turn",
157 };
158 info!(thread_id = %command.thread_id, action = action_kind, "BashCommand tool called");
159
160 let thread_id = normalize_thread_id(&command.thread_id);
161 if thread_id.is_empty() {
162 error!("Empty thread_id provided in BashCommand");
163 return Err(WinxError::ThreadIdMismatch(
164 "Error: No saved bash state found for thread ID \"\". Please initialize first with this ID."
165 .to_string(),
166 ));
167 }
168
169 let mut local_state = {
170 let guard = bash_state.lock().await;
171 let Some(state) = &*guard else {
172 error!("BashState not initialized");
173 return Err(WinxError::BashStateNotInitialized);
174 };
175 state.clone()
176 };
177
178 if thread_id != local_state.current_thread_id {
179 let loaded = local_state.load_state_from_disk(&thread_id).map_err(|error| {
180 WinxError::CommandExecutionError(format!(
181 "Failed to load saved bash state for thread_id `{thread_id}`: {error}"
182 ))
183 })?;
184 if !loaded {
185 return Err(WinxError::ThreadIdMismatch(format!(
186 "Error: No saved bash state found for thread_id `{thread_id}`. Please initialize first with this ID."
187 )));
188 }
189 if let Some(state) = bash_state.lock().await.as_mut() {
190 *state = local_state.clone();
191 }
192 }
193
194 lock_session_store().bind_main(&local_state.current_thread_id, &local_state.pty_shell);
195 let timeout_secs = effective_wait_for_seconds(command.wait_for_seconds);
196 let result =
197 execute_bash_action(&mut local_state, &command.action_json, timeout_secs, delivery_cursor)
198 .await;
199
200 if let Some(state) = bash_state.lock().await.as_mut() {
201 state.cwd.clone_from(&local_state.cwd);
202 }
203
204 match result {
205 Ok(mut output) => {
206 if let BashCommandAction::Command { ref command, .. } = command.action_json {
207 let command = command.trim();
208 if output.starts_with(command) {
209 output = output[command.len()..].to_string();
210 }
211 }
212 Ok(output)
213 }
214 Err(error) => Err(error),
215 }
216}
217
218#[allow(clippy::too_many_lines)]
219async fn execute_bash_action(
220 bash_state: &mut BashState,
221 action: &BashCommandAction,
222 timeout_secs: f64,
223 delivery_cursor: Option<&mut ShellDeliveryCursor>,
224) -> Result<String> {
225 let mut is_background = false;
226 let mut background_id: Option<String> = None;
227
228 let background_shell = match action {
229 BashCommandAction::Command { .. } => None,
230 BashCommandAction::StatusCheck { bg_command_id, .. }
231 | BashCommandAction::SendText { bg_command_id, .. }
232 | BashCommandAction::SendSpecials { bg_command_id, .. }
233 | BashCommandAction::SendAscii { bg_command_id, .. }
234 | BashCommandAction::Screen { bg_command_id, .. }
235 | BashCommandAction::WaitForTurn { bg_command_id, .. } => {
236 if let Some(id) = bg_command_id {
237 let mut manager = lock_session_store();
238 manager.prune_finished_shells();
239 if let Some(shell) = manager.get_shell(&bash_state.current_thread_id, id) {
240 is_background = true;
241 background_id = Some(id.clone());
242 Some(shell)
243 } else if let Some(tombstone) =
244 manager.peek_tombstone(&bash_state.current_thread_id, id)
245 {
246 drop(manager);
247 return finalize_tombstone(id, tombstone, action);
248 } else {
249 let error = format!(
250 "No shell found running with command id {}.\n{}",
251 id,
252 manager.get_running_info(&bash_state.current_thread_id)
253 );
254 return Err(WinxError::InvalidInput(error));
255 }
256 } else {
257 None
258 }
259 }
260 };
261
262 match action {
263 BashCommandAction::Command { command, is_background, allow_multi } => {
264 execute_command(
265 bash_state,
266 command,
267 *is_background,
268 *allow_multi,
269 timeout_secs,
270 delivery_cursor,
271 )
272 .await
273 }
274 BashCommandAction::StatusCheck { scrollback_lines, verbose, .. } => {
275 execute_status_check(
276 bash_state,
277 background_shell,
278 is_background,
279 background_id.as_deref(),
280 timeout_secs,
281 *scrollback_lines,
282 *verbose,
283 delivery_cursor,
284 )
285 .await
286 }
287 BashCommandAction::SendText { send_text, submit, .. } => {
288 execute_send_text(
289 bash_state,
290 send_text,
291 *submit,
292 background_shell,
293 is_background,
294 background_id.as_deref(),
295 timeout_secs,
296 delivery_cursor,
297 )
298 .await
299 }
300 BashCommandAction::SendSpecials { send_specials, submit, .. } => {
301 execute_send_specials(
302 bash_state,
303 send_specials,
304 *submit,
305 background_shell,
306 is_background,
307 background_id.as_deref(),
308 timeout_secs,
309 delivery_cursor,
310 )
311 .await
312 }
313 BashCommandAction::SendAscii { send_ascii, submit, .. } => {
314 execute_send_ascii(
315 bash_state,
316 send_ascii,
317 *submit,
318 background_shell,
319 is_background,
320 background_id.as_deref(),
321 timeout_secs,
322 delivery_cursor,
323 )
324 .await
325 }
326 BashCommandAction::Screen { lines, diff, .. } => {
327 execute_screen(
328 bash_state,
329 background_shell,
330 is_background,
331 background_id.as_deref(),
332 *lines,
333 *diff,
334 delivery_cursor,
335 )
336 .await
337 }
338 BashCommandAction::WaitForTurn {
339 recognizer,
340 quiet_ms,
341 timeout_seconds,
342 lines,
343 wait_through_busy,
344 ..
345 } => {
346 execute_wait_for_turn(
347 bash_state,
348 background_shell,
349 is_background,
350 background_id.as_deref(),
351 recognizer.as_deref(),
352 *quiet_ms,
353 *timeout_seconds,
354 *lines,
355 *wait_through_busy,
356 )
357 .await
358 }
359 }
360}
361
362#[cfg(test)]
363mod tests {
364 use super::effective_wait_for_seconds;
365
366 #[test]
367 fn requested_wait_is_not_silently_capped() {
368 assert!((effective_wait_for_seconds(Some(120.0)) - 120.0).abs() < f64::EPSILON);
369 assert!((effective_wait_for_seconds(Some(150.0)) - 150.0).abs() < f64::EPSILON);
370 }
371}