返回 CodeWhale
dsh_terminal.rs
根目录 / crates / engine / src / extension_host / dsh_terminal.rs
1 use std::path::Path;
2
3 use codewhale_agent_contract::worker_profile::ShellPolicy;
4 use codewhale_workflow_js::ToolCallResponse;
5 use serde::{Deserialize, Serialize};
6 use serde_json::{Value, json};
7
8 use super::dsh_broker::{
9 BrokerCall, BrokerEffect, BrokerFuture, BrokerMethods, BrokerRefusal, decode,
10 };
11 use super::protocol::DshService;
12 use crate::tools::execution_envelope::enforce_tool_denial;
13
14 const SUPPORTED: bool = cfg!(all(unix, not(target_env = "ohos")));
15 const DEFAULT_SESSION: &str = "term-1";
16 const MAX_SESSION_NAME: usize = 64;
17 const MAX_COMMAND_BYTES: usize = 16 * 1024;
18 const MAX_INPUT_BYTES: usize = 64 * 1024;
19 const MAX_TIMEOUT_SECS: u64 = 600;
20 const MAX_SETTLE_MS: u64 = 60_000;
21 pub(crate) const MAX_TERMINALS: usize = 8;
22 const LOG: &str = "codewhale::dsh_terminal";
23
24 static REGISTRY_GATE: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
25
26 #[derive(Deserialize)]
27 #[serde(tag = "method", content = "input", deny_unknown_fields)]
28 enum TerminalMethod {
29 #[serde(rename = "list")]
30 List(NoInput),
31 #[serde(rename = "run")]
32 Run(RunInput),
33 #[serde(rename = "send")]
34 Send(SendInput),
35 #[serde(rename = "wait")]
36 Wait(WaitInput),
37 #[serde(rename = "cancel")]
38 Cancel(SessionInput),
39 #[serde(rename = "reset")]
40 Reset(SessionInput),
41 }
42
43 impl BrokerMethods for TerminalMethod {
44 const NAMES: &'static [&'static str] = &["list", "run", "send", "wait", "cancel", "reset"];
45 }
46
47 #[derive(Deserialize)]
48 #[serde(deny_unknown_fields)]
49 struct NoInput {}
50
51 #[derive(Deserialize)]
52 #[serde(deny_unknown_fields)]
53 struct RunInput {
54 command: String,
55 #[serde(default)]
56 session: Option<String>,
57 #[serde(default)]
58 timeout_secs: Option<u64>,
59 }
60
61 #[derive(Deserialize)]
62 #[serde(deny_unknown_fields)]
63 struct SendInput {
64 session: String,
65 text: String,
66 #[serde(default)]
67 wait_ms: Option<u64>,
68 }
69
70 #[derive(Deserialize)]
71 #[serde(deny_unknown_fields)]
72 struct WaitInput {
73 session: String,
74 #[serde(default)]
75 timeout_secs: Option<u64>,
76 }
77
78 #[derive(Deserialize)]
79 #[serde(deny_unknown_fields)]
80 struct SessionInput {
81 session: String,
82 }
83
84 #[derive(Serialize)]
85 struct Terminal {
86 terminal_id: String,
87 session: String,
88 state: String,
89 running: bool,
90 exit_code: Option<u32>,
91 updated_at: String,
92 }
93
94 struct Live {
95 instance: String,
96 terminals: Vec<Terminal>,
97 }
98
99 impl Live {
100 fn holds(&self, session: &str) -> bool {
101 self.terminals
102 .iter()
103 .any(|terminal| terminal.session == session)
104 }
105
106 fn existing(&self, session: &str) -> Result<(), BrokerRefusal> {
107 if self.holds(session) {
108 Ok(())
109 } else {
110 Err(invalid(
111 "this plugin has no live terminal with that name in this session; `list` reports the live ones",
112 ))
113 }
114 }
115 }
116
117 pub(super) fn serve(call: BrokerCall) -> BrokerFuture {
118 Box::pin(async move {
119 let method = decode::<TerminalMethod>(&call)?;
120 if call.context.cancel().is_cancelled() {
121 return Err(refused("the terminal call was withdrawn"));
122 }
123 match method {
124 TerminalMethod::List(NoInput {}) => {
125 let live = live(&call, codewhale_tools::names::TERMINAL_WAIT_NAME).await?;
126 call.context.act("list", BrokerEffect::Read, None).await?;
127 tracing::info!(target: LOG, plugin = %call.owner.plugin_id, terminals = live.terminals.len(), "terminals listed");
128 Ok(json!({
129 "instance": live.instance,
130 "limit": MAX_TERMINALS,
131 "terminals": live.terminals,
132 }))
133 }
134 TerminalMethod::Run(RunInput {
135 command,
136 session,
137 timeout_secs,
138 }) => {
139 let session = session_name(session.as_deref().unwrap_or(DEFAULT_SESSION))?;
140 if command.trim().is_empty()
141 || command.len() > MAX_COMMAND_BYTES
142 || command.contains('\0')
143 {
144 return Err(invalid(format!(
145 "a command is 1 to {MAX_COMMAND_BYTES} bytes with no NUL"
146 )));
147 }
148 let timeout_secs = timeout(timeout_secs)?;
149 let live = live(&call, codewhale_tools::names::TERMINAL_RUN_NAME).await?;
150 if !live.holds(session) && live.terminals.len() >= MAX_TERMINALS {
151 tracing::info!(target: LOG, plugin = %call.owner.plugin_id, "terminal limit reached");
152 return Err(refused(
153 "this plugin already holds the most terminals it may open in this session",
154 ));
155 }
156 let mut input =
157 json!({ "command": command, "session": owned_name(&call, session) });
158 if let Some(timeout_secs) = timeout_secs {
159 input["timeout_secs"] = json!(timeout_secs);
160 }
161 nested(
162 &call,
163 codewhale_tools::names::TERMINAL_RUN_NAME,
164 session,
165 input,
166 )
167 .await
168 }
169 TerminalMethod::Send(SendInput {
170 session,
171 text,
172 wait_ms,
173 }) => {
174 let session = session_name(&session)?;
175 if text.is_empty() || text.len() > MAX_INPUT_BYTES {
176 return Err(invalid(format!(
177 "terminal input is 1 to {MAX_INPUT_BYTES} bytes"
178 )));
179 }
180 if wait_ms.is_some_and(|wait_ms| wait_ms > MAX_SETTLE_MS) {
181 return Err(invalid(format!("wait_ms is at most {MAX_SETTLE_MS}")));
182 }
183 live(&call, codewhale_tools::names::TERMINAL_SEND_NAME)
184 .await?
185 .existing(session)?;
186 let mut input = json!({ "session": owned_name(&call, session), "text": text });
187 if let Some(wait_ms) = wait_ms {
188 input["wait_ms"] = json!(wait_ms);
189 }
190 nested(
191 &call,
192 codewhale_tools::names::TERMINAL_SEND_NAME,
193 session,
194 input,
195 )
196 .await
197 }
198 TerminalMethod::Wait(WaitInput {
199 session,
200 timeout_secs,
201 }) => {
202 let session = session_name(&session)?;
203 let timeout_secs = timeout(timeout_secs)?;
204 live(&call, codewhale_tools::names::TERMINAL_WAIT_NAME)
205 .await?
206 .existing(session)?;
207 let mut input = json!({ "session": owned_name(&call, session) });
208 if let Some(timeout_secs) = timeout_secs {
209 input["timeout_secs"] = json!(timeout_secs);
210 }
211 nested(
212 &call,
213 codewhale_tools::names::TERMINAL_WAIT_NAME,
214 session,
215 input,
216 )
217 .await
218 }
219 TerminalMethod::Cancel(SessionInput { session }) => {
220 let session = session_name(&session)?;
221 live(&call, codewhale_tools::names::TERMINAL_CANCEL_NAME)
222 .await?
223 .existing(session)?;
224 let input = json!({ "session": owned_name(&call, session) });
225 nested(
226 &call,
227 codewhale_tools::names::TERMINAL_CANCEL_NAME,
228 session,
229 input,
230 )
231 .await
232 }
233 TerminalMethod::Reset(SessionInput { session }) => {
234 let session = session_name(&session)?;
235 live(&call, codewhale_tools::names::TERMINAL_RESET_NAME)
236 .await?
237 .existing(session)?;
238 let input = json!({ "session": owned_name(&call, session) });
239 nested(
240 &call,
241 codewhale_tools::names::TERMINAL_RESET_NAME,
242 session,
243 input,
244 )
245 .await
246 }
247 }
248 })
249 }
250
251 fn invalid(message: impl Into<String>) -> BrokerRefusal {
252 BrokerRefusal::InvalidInput {
253 service: DshService::Terminal,
254 message: message.into(),
255 }
256 }
257
258 fn refused(message: &str) -> BrokerRefusal {
259 BrokerRefusal::Refused {
260 service: DshService::Terminal,
261 message: message.to_string(),
262 }
263 }
264
265 pub(crate) fn is_valid_session_name(name: &str) -> bool {
266 !name.is_empty()
267 && name.len() <= MAX_SESSION_NAME
268 && name
269 .bytes()
270 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
271 }
272
273 fn session_name(name: &str) -> Result<&str, BrokerRefusal> {
274 if is_valid_session_name(name) {
275 Ok(name)
276 } else {
277 Err(invalid(format!(
278 "a terminal name is 1 to {MAX_SESSION_NAME} letters, digits, `_`, `-` or `.`"
279 )))
280 }
281 }
282
283 #[cfg(all(unix, not(target_env = "ohos")))]
284 pub(crate) fn session_parts(full_name: &str) -> Option<(&str, &str)> {
285 let rest = full_name.strip_prefix("dsh:")?;
286 let (plugin_id, session) = rest.rsplit_once(':')?;
287 (!plugin_id.is_empty() && is_valid_session_name(session)).then_some((plugin_id, session))
288 }
289
290 fn timeout(secs: Option<u64>) -> Result<Option<u64>, BrokerRefusal> {
291 match secs {
292 Some(secs) if !(1..=MAX_TIMEOUT_SECS).contains(&secs) => Err(invalid(format!(
293 "timeout_secs is between 1 and {MAX_TIMEOUT_SECS}"
294 ))),
295 other => Ok(other),
296 }
297 }
298
299 pub(crate) fn prefix(plugin: &str) -> String {
300 format!("dsh:{plugin}:")
301 }
302
303 #[cfg(all(unix, not(target_env = "ohos")))]
304 pub(super) fn kill_plugin_sessions(plugin_id: &str) {
305 let prefix = prefix(plugin_id);
306 if let Err(error) = crate::tools::terminal_session::kill_sessions_named(&prefix) {
307 tracing::warn!(target: LOG, plugin = %plugin_id, %error, "failed to end plugin terminal sessions");
308 }
309 }
310
311 #[cfg(not(all(unix, not(target_env = "ohos"))))]
312 pub(super) fn kill_plugin_sessions(_plugin_id: &str) {}
313
314 fn owned_name(call: &BrokerCall, session: &str) -> String {
315 format!("{}{session}", prefix(&call.owner.plugin_id))
316 }
317
318 async fn live(call: &BrokerCall, tool_name: &'static str) -> Result<Live, BrokerRefusal> {
319 if !SUPPORTED {
320 return Err(BrokerRefusal::NotAvailable(DshService::Terminal));
321 }
322 let mut tool = call.context.tool().clone();
323 let _ = tool.refresh_live_posture();
324 let needs_full = matches!(
325 tool_name,
326 codewhale_tools::names::TERMINAL_RUN_NAME
327 | codewhale_tools::names::TERMINAL_SEND_NAME
328 | codewhale_tools::names::TERMINAL_RESET_NAME
329 );
330 if !tool.shell_policy.allows_shell()
331 || (needs_full && tool.shell_policy != ShellPolicy::Full)
332 || enforce_tool_denial(&tool, tool_name, &json!({})).is_err()
333 {
334 tracing::info!(target: LOG, plugin = %call.owner.plugin_id, tool = tool_name, "terminal refused: the caller may not use this shell tool");
335 return Err(refused("terminals are not available to this caller"));
336 }
337 let workspace = tool.workspace.clone();
338 let owner = tool.state_namespace.clone();
339 let mine = prefix(&call.owner.plugin_id);
340 let read = async move {
341 let permit = REGISTRY_GATE.acquire().await.map_err(|_| ())?;
342 tokio::task::spawn_blocking(move || {
343 let _permit = permit;
344 owned(&workspace, &owner, &mine)
345 })
346 .await
347 .map_err(|_| ())?
348 .map_err(|error| {
349 tracing::warn!(target: LOG, %error, "terminal registry read failed");
350 })
351 };
352 tokio::select! {
353 biased;
354 () = call.context.cancel().cancelled() => Err(refused("the terminal call was withdrawn")),
355 live = read => live.map_err(|()| refused("the terminal registry could not be read")),
356 }
357 }
358
359 #[cfg(all(unix, not(target_env = "ohos")))]
360 fn owned(workspace: &Path, owner: &str, mine: &str) -> Result<Live, String> {
361 use crate::tools::terminal_session;
362
363 let terminals = terminal_session::owned_sessions(workspace, owner)?
364 .into_iter()
365 .filter_map(|info| {
366 let session = info.name.strip_prefix(mine)?;
367 session_name(session).ok()?;
368 Some(Terminal {
369 session: session.to_string(),
370 state: match info.exit_code {
371 Some(_) => "exited".to_string(),
372 None => serde_json::to_value(info.state)
373 .ok()
374 .and_then(|state| state.as_str().map(str::to_owned))
375 .unwrap_or_default(),
376 },
377 running: info.exit_code.is_none(),
378 exit_code: info.exit_code,
379 terminal_id: info.id,
380 updated_at: info.updated_at,
381 })
382 })
383 .collect();
384 Ok(Live {
385 instance: terminal_session::instance_id().to_string(),
386 terminals,
387 })
388 }
389
390 #[cfg(not(all(unix, not(target_env = "ohos"))))]
391 fn owned(_workspace: &Path, _owner: &str, _mine: &str) -> Result<Live, String> {
392 Err("terminal sessions are not supported on this platform".to_string())
393 }
394
395 async fn nested(
396 call: &BrokerCall,
397 tool: &'static str,
398 session: &str,
399 input: Value,
400 ) -> Result<Value, BrokerRefusal> {
401 let plugin = &call.owner.plugin_id;
402 match call.context.core_call(tool, input).await {
403 Ok(response) => {
404 tracing::info!(target: LOG, %plugin, tool, session, ok = response.ok, "terminal call ran through the gate");
405 Ok(outcome(session, response))
406 }
407 Err(refusal) => {
408 let code = refusal.code();
409 let detail = match &refusal {
410 BrokerRefusal::Denied { message, .. } | BrokerRefusal::Refused { message, .. } => {
411 message.as_str()
412 }
413 _ => "",
414 };
415 tracing::info!(target: LOG, %plugin, tool, session, code, detail, "terminal call not run");
416 Err(match refusal {
417 BrokerRefusal::Denied { .. } => BrokerRefusal::Denied {
418 service: DshService::Terminal,
419 message: "the terminal call was denied".to_string(),
420 },
421 _ => refused("the terminal call was refused"),
422 })
423 }
424 }
425 }
426
427 fn text(value: &Value) -> String {
428 match value {
429 Value::String(text) => text.clone(),
430 Value::Null => String::new(),
431 other => other.to_string(),
432 }
433 }
434
435 fn outcome(session: &str, response: ToolCallResponse) -> Value {
436 if !response.ok {
437 return json!({ "ok": false, "session": session, "output": text(&response.result) });
438 }
439 let metadata = &response.result["metadata"];
440 json!({
441 "ok": true,
442 "session": session,
443 "output": text(&response.result["content"]),
444 "truncated": !response.result["truncated"].is_null(),
445 "status": metadata["status"],
446 "exit_code": metadata["exit_code"],
447 "cwd": metadata["cwd"],
448 "terminal_id": metadata["terminal_session_id"],
449 "state": metadata["terminal_state"],
450 "previous_terminal_id": metadata["previous_session_id"],
451 })
452 }
453
454 #[cfg(test)]
455 mod tests {
456 use super::super::dsh_broker::BrokerContext;
457 use super::*;
458 use codewhale_config::OwnerRef;
459
460 fn call(owner: &OwnerRef, method: &str, input: Value) -> BrokerCall {
461 BrokerCall {
462 owner: owner.clone(),
463 session_id: "session".into(),
464 service: DshService::Terminal,
465 method: method.into(),
466 input,
467 context: BrokerContext::detached_for_test(owner, DshService::Terminal),
468 }
469 }
470
471 fn owner() -> OwnerRef {
472 OwnerRef {
473 plugin_id: "a".into(),
474 generation: 1,
475 owner_token: "t".into(),
476 }
477 }
478
479 #[tokio::test]
480 async fn terminal_methods_decode_strictly_and_bound_every_input_before_anything_runs() {
481 let owner = owner();
482 for method in ["spawn", "open", "kill", "resize", "read", "exec", "core"] {
483 let refusal = serve(call(&owner, method, json!({}))).await.unwrap_err();
484 assert_eq!(refusal.code(), "unknown_method", "{method}");
485 }
486 let long_name = "n".repeat(MAX_SESSION_NAME + 1);
487 let long_command = "c".repeat(MAX_COMMAND_BYTES + 1);
488 let long_text = "t".repeat(MAX_INPUT_BYTES + 1);
489 for (method, input) in [
490 ("list", json!({ "workspace": "/" })),
491 ("run", json!({})),
492 ("run", json!({ "command": "" })),
493 ("run", json!({ "command": " \n" })),
494 ("run", json!({ "command": "a\u{0}b" })),
495 ("run", json!({ "command": long_command })),
496 ("run", json!({ "command": "true", "session": "" })),
497 ("run", json!({ "command": "true", "session": "../term-1" })),
498 ("run", json!({ "command": "true", "session": "dsh:b:x" })),
499 ("run", json!({ "command": "true", "session": long_name })),
500 ("run", json!({ "command": "true", "timeout_secs": 0 })),
501 ("run", json!({ "command": "true", "timeout_secs": 601 })),
502 (
503 "run",
504 json!({ "command": "true", "sandbox_permissions": "danger" }),
505 ),
506 ("run", json!({ "command": "true", "name": "exec_shell" })),
507 ("send", json!({ "session": "x" })),
508 ("send", json!({ "session": "x", "text": "" })),
509 ("send", json!({ "session": "x", "text": long_text })),
510 (
511 "send",
512 json!({ "session": "x", "text": "y", "wait_ms": 60_001 }),
513 ),
514 ("wait", json!({ "session": "x", "timeout_secs": 601 })),
515 ("wait", json!({})),
516 ("cancel", json!({ "session": "a b" })),
517 ("reset", json!({ "session": "x", "force": true })),
518 ] {
519 let refusal = serve(call(&owner, method, input.clone()))
520 .await
521 .unwrap_err();
522 assert_eq!(refusal.code(), "invalid_input", "{method} {input}");
523 }
524 }
525
526 #[tokio::test]
527 async fn a_terminal_call_whose_cancel_has_fired_has_no_effect() {
528 let owner = owner();
529 let fired = call(&owner, "run", json!({ "command": "true" }));
530 fired.context.cancel().cancel();
531 let refusal = serve(fired).await.unwrap_err();
532 assert_eq!(refusal.code(), "refused");
533 }
534
535 #[test]
536 fn terminal_names_are_scoped_to_the_plugin_and_a_result_is_a_typed_projection() {
537 assert_eq!(prefix("a"), "dsh:a:");
538 assert!(
539 "dsh:a:b:x"
540 .strip_prefix(&prefix("a"))
541 .is_some_and(|rest| session_name(rest).is_err())
542 );
543 let ran = outcome(
544 "build",
545 ToolCallResponse {
546 ok: true,
547 result: json!({
548 "content": 42,
549 "truncated": null,
550 "metadata": {
551 "status": "completed",
552 "exit_code": 0,
553 "cwd": "/w",
554 "terminal_session_id": "id-1",
555 "terminal_state": "idle",
556 "state_path": "/private/state.json",
557 },
558 }),
559 },
560 );
561 assert_eq!(
562 ran,
563 json!({
564 "ok": true,
565 "session": "build",
566 "output": "42",
567 "truncated": false,
568 "status": "completed",
569 "exit_code": 0,
570 "cwd": "/w",
571 "terminal_id": "id-1",
572 "state": "idle",
573 "previous_terminal_id": null,
574 })
575 );
576 let failed = outcome(
577 "build",
578 ToolCallResponse {
579 ok: false,
580 result: json!("boom"),
581 },
582 );
583 assert_eq!(
584 failed,
585 json!({ "ok": false, "session": "build", "output": "boom" })
586 );
587 }
588 }
589
589 lines RUST