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
//! App-server-backed workspace command execution for TUI-owned background lookups.
//!
//! This module is the TUI boundary for non-interactive commands that need to run wherever
//! the active workspace lives. Callers describe a command in terms of argv, cwd, environment
//! overrides, timeout, and output cap; the runner translates that request to app-server
//! `command/exec`. Keeping this as a TUI-local abstraction lets status surfaces avoid knowing
//! whether the current app-server is embedded or remote.
//!
//! Commands sent through this path should not prompt for stdin. Most callers should keep output
//! bounded so metadata refreshes cannot grow into unbounded background processes; callers that own a
//! full user-visible payload, such as `/diff`, can explicitly opt out of output capping.
use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use lemurclaw_server::app_server_client::AppServerRequestHandle;
use lemurclaw_core::app_server_protocol::ClientRequest;
use lemurclaw_core::app_server_protocol::CommandExecParams;
use lemurclaw_core::app_server_protocol::CommandExecResponse;
use lemurclaw_core::app_server_protocol::RequestId;
use uuid::Uuid;
/// Shared handle for running workspace commands from TUI components.
pub(crate) type WorkspaceCommandRunner = Arc<dyn WorkspaceCommandExecutor>;
/// Describes a bounded non-interactive command to execute in the active workspace.
///
/// The command is intentionally argv-based rather than shell-based so callers do not need to quote
/// user or repository data. `cwd` is interpreted by app-server relative to the workspace rules for
/// the active session, which is what makes the same request shape work for embedded and remote
/// app-server instances.
#[derive(Clone, Debug)]
pub(crate) struct WorkspaceCommand {
/// Program and arguments to execute without shell interpolation.
pub(crate) argv: Vec<String>,
/// Working directory for the command, if different from app-server's session cwd.
pub(crate) cwd: Option<PathBuf>,
/// Environment overrides where `None` removes a variable.
pub(crate) env: HashMap<String, Option<String>>,
/// Maximum wall-clock duration before app-server cancels the command.
pub(crate) timeout: Duration,
/// Maximum captured stdout/stderr bytes returned by app-server.
pub(crate) output_bytes_cap: usize,
/// Whether app-server should return uncapped stdout/stderr.
pub(crate) disable_output_cap: bool,
}
impl WorkspaceCommand {
/// Creates a workspace command with conservative defaults for metadata probes.
pub(crate) fn new(argv: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
argv: argv.into_iter().map(Into::into).collect(),
cwd: None,
env: HashMap::new(),
timeout: Duration::from_secs(/*secs*/ 5),
output_bytes_cap: 64 * 1024,
disable_output_cap: false,
}
}
/// Sets the command working directory.
pub(crate) fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
self.cwd = Some(cwd.into());
self
}
/// Adds or replaces one environment variable override.
pub(crate) fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.env.insert(key.into(), Some(value.into()));
self
}
/// Sets the maximum wall-clock duration before app-server cancels the command.
pub(crate) fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
/// Requests uncapped stdout/stderr capture from app-server.
pub(crate) fn disable_output_cap(mut self) -> Self {
self.disable_output_cap = true;
self
}
}
/// Captured result from a completed workspace command.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct WorkspaceCommandOutput {
/// Process exit status code reported by app-server.
pub(crate) exit_code: i32,
/// Captured stdout after app-server output capping.
pub(crate) stdout: String,
/// Captured stderr after app-server output capping.
pub(crate) stderr: String,
}
impl WorkspaceCommandOutput {
/// Returns whether the process exited successfully.
pub(crate) fn success(&self) -> bool {
self.exit_code == 0
}
}
/// Transport or protocol failure before a command result was available.
///
/// Non-zero process exits are represented as `WorkspaceCommandOutput` so callers can distinguish
/// a normal probe miss from an app-server request failure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct WorkspaceCommandError {
message: String,
}
impl WorkspaceCommandError {
fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl std::fmt::Display for WorkspaceCommandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for WorkspaceCommandError {}
/// Executes non-interactive workspace commands through the active TUI app-server session.
///
/// Implementations decide where the workspace lives. Callers provide argv/cwd/env and should not
/// branch on local versus remote execution.
pub(crate) trait WorkspaceCommandExecutor: Send + Sync {
/// Runs a workspace command and returns captured output or an app-server request error.
///
/// Callers should treat errors as infrastructure failures and should treat successful output
/// with a non-zero exit code as ordinary command failure. Returning a boxed future keeps the
/// trait object-safe.
fn run(
&self,
command: WorkspaceCommand,
) -> Pin<
Box<dyn Future<Output = Result<WorkspaceCommandOutput, WorkspaceCommandError>> + Send + '_>,
>;
}
/// Workspace command runner that forwards every request to the active app-server.
#[derive(Clone)]
pub(crate) struct AppServerWorkspaceCommandRunner {
request_handle: AppServerRequestHandle,
}
impl AppServerWorkspaceCommandRunner {
/// Creates a runner from an app-server request handle owned by the current TUI session.
pub(crate) fn new(request_handle: AppServerRequestHandle) -> Self {
Self { request_handle }
}
}
impl WorkspaceCommandExecutor for AppServerWorkspaceCommandRunner {
/// Sends the command as a one-off app-server `command/exec` request.
///
/// The request is non-tty, does not stream stdin/stdout/stderr, and uses the caller's timeout
/// and output cap. It leaves sandbox and permission profile selection to app-server so the same
/// runner follows the active session's embedded or remote execution policy.
fn run(
&self,
command: WorkspaceCommand,
) -> Pin<
Box<dyn Future<Output = Result<WorkspaceCommandOutput, WorkspaceCommandError>> + Send + '_>,
> {
Box::pin(async move {
let timeout_ms = i64::try_from(command.timeout.as_millis()).unwrap_or(i64::MAX);
let env = if command.env.is_empty() {
None
} else {
Some(command.env)
};
let response: CommandExecResponse = self
.request_handle
.request_typed(ClientRequest::OneOffCommandExec {
request_id: RequestId::String(format!("workspace-command-{}", Uuid::new_v4())),
params: CommandExecParams {
command: command.argv,
process_id: None,
tty: false,
stream_stdin: false,
stream_stdout_stderr: false,
output_bytes_cap: (!command.disable_output_cap)
.then_some(command.output_bytes_cap),
disable_output_cap: command.disable_output_cap,
disable_timeout: false,
timeout_ms: Some(timeout_ms),
cwd: command.cwd,
env,
size: None,
sandbox_policy: None,
permission_profile: None,
},
})
.await
.map_err(|err| WorkspaceCommandError::new(err.to_string()))?;
Ok(WorkspaceCommandOutput {
exit_code: response.exit_code,
stdout: response.stdout,
stderr: response.stderr,
})
})
}
}