返回 CodeWhale
terminal_session.rs
根目录 / crates / engine / src / tools / terminal_session.rs
1 //! Stateful, PTY-backed terminal sessions.
2 //!
3 //! Live PTY processes remain deliberately process-local, while a non-secret
4 //! durable summary records identity, last-known cwd, lifecycle state, and
5 //! replacement history. A later process reports the shell as stale/lost and
6 //! starts a new identity; it never claims to reattach from a reused PID.
7 //!
8 //! A session belongs to one owner (the tool context's `state_namespace`: a
9 //! runtime thread's id, or the TUI session's) in one canonical workspace, so
10 //! two conversations that both say `term-1` get two shells. Each live shell
11 //! carries an identity (`session_id`) issued at creation and never reused;
12 //! reset and restart issue a new one.
13 //!
14 //! Known limitations: the dock lists every owner's shells in its workspace;
15 //! deleting a thread does not end its shells, which live until the process
16 //! exits; and a workspace directory replaced at the same path does not retire
17 //! shells already running there.
18
19 #[cfg(unix)]
20 use std::collections::{HashMap, VecDeque};
21 #[cfg(unix)]
22 use std::io::{self, Write};
23 #[cfg(unix)]
24 use std::path::{Path, PathBuf};
25 #[cfg(unix)]
26 use std::sync::{Arc, Mutex, OnceLock};
27 #[cfg(unix)]
28 use std::time::{Duration, Instant};
29
30 use async_trait::async_trait;
31 #[cfg(unix)]
32 use serde::{Deserialize, Serialize};
33 use serde_json::json;
34 #[cfg(unix)]
35 use sha2::{Digest, Sha256};
36 #[cfg(unix)]
37 use uuid::Uuid;
38
39 use super::spec::{
40 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
41 };
42 #[cfg(unix)]
43 use super::spec::{optional_u64, required_str};
44 use codewhale_tools::names::{
45 TERMINAL_CANCEL_NAME, TERMINAL_RESET_NAME, TERMINAL_RUN_NAME, TERMINAL_SEND_NAME,
46 TERMINAL_WAIT_NAME,
47 };
48
49 #[cfg(unix)]
50 const BUFFER_LIMIT: usize = 512 * 1024;
51 #[cfg(unix)]
52 const OUTPUT_LIMIT: usize = 12 * 1024;
53 /// Ceiling for one [`OutputBuffer::read_since`] response. The ring is already
54 /// bounded at [`BUFFER_LIMIT`]; this bounds a single frame so a client cannot
55 /// ask for the whole window at once.
56 #[cfg(unix)]
57 pub const READ_LIMIT: usize = 64 * 1024;
58 #[cfg(unix)]
59 const DEFAULT_TIMEOUT_SECS: u64 = 120;
60 #[cfg(unix)]
61 const MAX_TIMEOUT_SECS: u64 = 600;
62 #[cfg(unix)]
63 const CANCEL_CONFIRM_TIMEOUT: Duration = Duration::from_secs(2);
64 #[cfg(unix)]
65 const CANCEL_SENTINEL_RETRY_INTERVAL: Duration = Duration::from_millis(50);
66 #[cfg(unix)]
67 const CANCEL_INTERRUPT_RETRY_INTERVAL: Duration = Duration::from_millis(500);
68
69 #[cfg(unix)]
70 pub struct TerminalSession {
71 writer: Arc<Mutex<Box<dyn Write + Send>>>,
72 /// The pty master is retained after the reader and writer clones are taken
73 /// so [`TerminalSession::resize`] can reach the kernel's window size. The
74 /// clones keep the pty alive; nothing else clones the master.
75 master: Box<dyn portable_pty::MasterPty + Send>,
76 child: Box<dyn portable_pty::Child + Send>,
77 output: Arc<Mutex<OutputBuffer>>,
78 read_cursor: u64,
79 command: Option<CommandState>,
80 durable: DurableTerminalRecord,
81 durable_path: PathBuf,
82 /// True when the live PTY was started through a real sandbox backend.
83 /// A later narrowed posture must not reuse an unsandboxed shell.
84 sandbox_confined: bool,
85 /// A running process cannot adopt changed roots or network restrictions.
86 sandbox_policy: codewhale_sandbox::SandboxPolicy,
87 }
88
89 #[cfg(unix)]
90 #[derive(Clone, Debug, Serialize, Deserialize)]
91 struct DurableTerminalRecord {
92 schema_version: u32,
93 session_id: String,
94 runtime_nonce: String,
95 process_id: u32,
96 workspace: PathBuf,
97 name: String,
98 shell: String,
99 last_known_cwd: PathBuf,
100 environment_summary: EnvironmentSummary,
101 state: DurableTerminalState,
102 updated_at: String,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
104 previous: Option<Box<DurableTerminalRecord>>,
105 }
106
107 #[cfg(unix)]
108 #[derive(Clone, Debug, Serialize, Deserialize)]
109 struct EnvironmentSummary {
110 term: Option<String>,
111 virtual_env_active: bool,
112 conda_env_active: bool,
113 nix_shell_active: bool,
114 note: String,
115 }
116
117 #[cfg(unix)]
118 #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
119 #[serde(rename_all = "snake_case")]
120 pub enum DurableTerminalState {
121 Running,
122 Idle,
123 Canceled,
124 Failed,
125 StaleLost,
126 Reset,
127 }
128
129 #[cfg(unix)]
130 struct CommandState {
131 id: String,
132 marker: String,
133 start_marker: String,
134 }
135
136 #[cfg(unix)]
137 #[derive(Default)]
138 struct OutputBuffer {
139 bytes: VecDeque<u8>,
140 total: u64,
141 last_activity: Option<Instant>,
142 }
143
144 /// One absolute-offset slice of a session's output.
145 ///
146 /// Offsets are absolute for the life of the live PTY: they count every byte
147 /// the reader thread ever appended, not the bytes still retained. That is what
148 /// lets a client resume from a cursor it stored earlier, and what lets this
149 /// type tell it the truth when the retained window has moved past it.
150 ///
151 /// Field names match the `/v1/threads/{id}/terminals/{terminal_id}/output`
152 /// wire so the payload is a projection, not a translation (the same
153 /// vocabulary the jobs byte stream uses).
154 #[cfg(unix)]
155 #[derive(Clone, Debug, PartialEq, Eq)]
156 pub struct OutputChunk {
157 pub bytes: Vec<u8>,
158 /// Absolute offset of `bytes[0]` in the session's lifetime output.
159 pub offset: u64,
160 /// Offset to pass as the next `cursor`.
161 pub next_cursor: u64,
162 /// Every byte the session has produced, retained or not.
163 pub total: u64,
164 /// Leading bytes the ring has permanently discarded.
165 pub dropped: u64,
166 /// True when the requested cursor predates the retained window. The bytes
167 /// in between cannot be recovered from this process — report, not repair.
168 pub gap: bool,
169 }
170
171 #[cfg(unix)]
172 impl OutputBuffer {
173 fn append(&mut self, data: &[u8]) {
174 self.last_activity = Some(Instant::now());
175 self.total = self.total.saturating_add(data.len() as u64);
176 self.bytes.extend(data);
177 while self.bytes.len() > BUFFER_LIMIT {
178 let _ = self.bytes.pop_front();
179 }
180 }
181
182 fn text(&self) -> String {
183 String::from_utf8_lossy(&self.bytes.iter().copied().collect::<Vec<_>>()).into_owned()
184 }
185
186 /// Absolute offset of the oldest retained byte.
187 fn oldest(&self) -> u64 {
188 self.total.saturating_sub(self.bytes.len() as u64)
189 }
190
191 /// Read from an absolute cursor without consuming: the caller owns its own
192 /// position, so two readers can replay the same bytes and a repeated read
193 /// is idempotent. Does not advance `read_cursor` — the consuming
194 /// tool-result path is untouched. This is the cursor arithmetic only;
195 /// response-size policy belongs to the caller.
196 ///
197 /// A cursor past the head clamps to `total`: nothing is there yet, and
198 /// echoing the future cursor back as `next_cursor` would make every byte
199 /// produced before the stream reached it invisible to that client.
200 fn read_since(&self, cursor: u64, max_bytes: usize) -> OutputChunk {
201 let dropped = self.oldest();
202 let gap = cursor < dropped;
203 let start = cursor.max(dropped).min(self.total);
204 let skip = usize::try_from(start - dropped).unwrap_or(usize::MAX);
205 let take = max_bytes.min(self.bytes.len().saturating_sub(skip));
206 let bytes = self.bytes.iter().skip(skip).take(take).copied().collect();
207 OutputChunk {
208 bytes,
209 offset: start,
210 next_cursor: start + take as u64,
211 total: self.total,
212 dropped,
213 gap,
214 }
215 }
216 }
217
218 #[cfg(unix)]
219 pub type SharedSession = Arc<Mutex<TerminalSession>>;
220
221 #[cfg(unix)]
222 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
223 struct SessionKey {
224 workspace: PathBuf,
225 owner: String,
226 name: String,
227 }
228
229 #[cfg(unix)]
230 struct Registered {
231 id: String,
232 session: SharedSession,
233 }
234
235 #[cfg(unix)]
236 impl Registered {
237 fn new(session: &SharedSession) -> Result<Self, String> {
238 let id = session
239 .lock()
240 .map_err(|_| "terminal session lock poisoned".to_string())?
241 .durable
242 .session_id
243 .clone();
244 Ok(Self {
245 id,
246 session: Arc::clone(session),
247 })
248 }
249 }
250
251 #[cfg(unix)]
252 static SESSIONS: OnceLock<Mutex<HashMap<SessionKey, Registered>>> = OnceLock::new();
253
254 #[cfg(unix)]
255 static RUNTIME_NONCE: OnceLock<String> = OnceLock::new();
256
257 #[cfg(unix)]
258 fn runtime_nonce() -> &'static str {
259 RUNTIME_NONCE.get_or_init(|| Uuid::new_v4().to_string())
260 }
261
262 #[cfg(unix)]
263 pub fn instance_id() -> &'static str {
264 runtime_nonce()
265 }
266
267 #[cfg(unix)]
268 fn sessions() -> &'static Mutex<HashMap<SessionKey, Registered>> {
269 SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
270 }
271
272 #[cfg(unix)]
273 fn canonical(workspace: &Path) -> PathBuf {
274 workspace
275 .canonicalize()
276 .unwrap_or_else(|_| workspace.to_path_buf())
277 }
278
279 #[cfg(unix)]
280 fn session_key(owner: &str, name: &str, workspace: &Path) -> SessionKey {
281 SessionKey {
282 workspace: canonical(workspace),
283 owner: owner.to_string(),
284 name: name.to_string(),
285 }
286 }
287
288 #[cfg(unix)]
289 fn durable_path(owner: &str, name: &str, workspace: &Path) -> Result<PathBuf, String> {
290 let workspace = canonical(workspace);
291 let mut hasher = Sha256::new();
292 hasher.update(workspace.to_string_lossy().as_bytes());
293 hasher.update(b"\0");
294 hasher.update(owner.as_bytes());
295 hasher.update(b"\0");
296 hasher.update(name.as_bytes());
297 let digest = hasher
298 .finalize()
299 .iter()
300 .map(|byte| format!("{byte:02x}"))
301 .collect::<String>();
302 #[cfg(any(test, feature = "test-support"))]
303 let state_dir = workspace.join(".codewhale-test-terminal-sessions");
304 #[cfg(not(any(test, feature = "test-support")))]
305 let state_dir = codewhale_config::ensure_state_dir("terminal-sessions")
306 .map_err(|error| format!("failed to resolve terminal session state directory: {error}"))?;
307 std::fs::create_dir_all(&state_dir)
308 .map_err(|error| format!("failed to create terminal session state directory: {error}"))?;
309 Ok(state_dir.join(format!("{}.json", &digest[..32])))
310 }
311
312 #[cfg(unix)]
313 fn load_durable(path: &Path) -> Result<Option<DurableTerminalRecord>, String> {
314 let bytes = match std::fs::read(path) {
315 Ok(bytes) => bytes,
316 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
317 Err(error) => {
318 return Err(format!(
319 "failed to read terminal session state {}: {error}",
320 path.display()
321 ));
322 }
323 };
324 serde_json::from_slice(&bytes).map(Some).map_err(|error| {
325 format!(
326 "terminal session state {} is corrupt: {error}",
327 path.display()
328 )
329 })
330 }
331
332 #[cfg(unix)]
333 fn persist_durable(path: &Path, record: &DurableTerminalRecord) -> Result<(), String> {
334 let payload = serde_json::to_vec_pretty(record)
335 .map_err(|error| format!("failed to encode terminal session state: {error}"))?;
336 codewhale_util::utils::write_atomic(path, &payload)
337 .map_err(|error| format!("failed to persist terminal session state: {error}"))
338 }
339
340 #[cfg(unix)]
341 fn pty_lacks_required_sandbox(
342 policy: &codewhale_sandbox::SandboxPolicy,
343 applied: codewhale_sandbox::SandboxType,
344 ) -> bool {
345 policy.should_sandbox() && matches!(applied, codewhale_sandbox::SandboxType::None)
346 }
347
348 #[cfg(unix)]
349 fn pty_sandbox_policy(
350 context: &ToolContext,
351 ) -> Result<codewhale_sandbox::SandboxPolicy, ToolError> {
352 if context.sandbox_backend.is_some() {
353 return Err(ToolError::not_available(
354 "terminal PTY tools start a local shell, and this session runs commands in an external sandbox; run the command through the shell tool instead",
355 ));
356 }
357 Ok(context.elevated_sandbox_policy.clone().unwrap_or_default())
358 }
359
360 #[cfg(unix)]
361 fn prepare_pty_shell(
362 shell: &str,
363 workspace: &std::path::Path,
364 project: &std::path::Path,
365 policy: codewhale_sandbox::SandboxPolicy,
366 shell_manager: &crate::tools::shell::SharedShellManager,
367 ) -> Result<(codewhale_sandbox::ExecEnv, bool), String> {
368 let prepared = shell_manager
369 .lock()
370 .unwrap_or_else(std::sync::PoisonError::into_inner)
371 .prepare_runner(
372 shell,
373 vec!["-i".to_string()],
374 workspace,
375 project,
376 Duration::from_secs(24 * 60 * 60),
377 Some(policy.clone()),
378 );
379 if pty_lacks_required_sandbox(&policy, prepared.sandbox_type) {
380 return Err(
381 "terminal PTY tools cannot run unsandboxed under a narrowed filesystem posture; use Full Access / ExternalSandbox or enable seatbelt/bwrap"
382 .to_string(),
383 );
384 }
385 if prepared.command.is_empty() {
386 return Err("sandbox prepare returned an empty PTY command".to_string());
387 }
388 let confined = !matches!(prepared.sandbox_type, codewhale_sandbox::SandboxType::None);
389 Ok((prepared, confined))
390 }
391
392 #[cfg(unix)]
393 fn create_session(
394 owner: &str,
395 name: &str,
396 workspace: &std::path::Path,
397 policy: codewhale_sandbox::SandboxPolicy,
398 shell_manager: &crate::tools::shell::SharedShellManager,
399 ) -> Result<SharedSession, String> {
400 // Unit tests exercise the persistent-PTY contract, not a developer's
401 // interactive shell startup files. Keep their deadlines deterministic and
402 // avoid racing process-global HOME/SHELL overrides from parallel tests.
403 #[cfg(any(test, feature = "test-support"))]
404 let shell = "/bin/sh".to_string();
405 #[cfg(not(any(test, feature = "test-support")))]
406 let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
407 let project = workspace.to_path_buf();
408 let workspace = canonical(workspace);
409 let durable_path = durable_path(owner, name, &workspace)?;
410 let previous = load_durable(&durable_path)
411 .unwrap_or_else(|error| {
412 tracing::warn!(name, "{error}");
413 None
414 })
415 .map(|mut record| {
416 // A persisted shell is historical evidence only. A random per-process
417 // nonce makes PID reuse irrelevant and deliberately forbids reattach.
418 record.state = DurableTerminalState::StaleLost;
419 record.updated_at = chrono::Utc::now().to_rfc3339();
420 Box::new(record)
421 });
422 let pty = portable_pty::native_pty_system();
423 let pair = pty
424 .openpty(portable_pty::PtySize {
425 rows: 24,
426 cols: 120,
427 pixel_width: 0,
428 pixel_height: 0,
429 })
430 .map_err(|e| format!("failed to open PTY: {e}"))?;
431
432 let (prepared, sandbox_confined) =
433 prepare_pty_shell(&shell, &workspace, &project, policy.clone(), shell_manager)?;
434 let child = prepared
435 .spawn_pty(pair.slave, &prepared.cwd)
436 .map_err(|e| format!("failed to start shell {shell}: {e}"))?;
437
438 let reader = pair
439 .master
440 .try_clone_reader()
441 .map_err(|e| format!("failed to read PTY: {e}"))?;
442 let writer = pair
443 .master
444 .take_writer()
445 .map_err(|e| format!("failed to write PTY: {e}"))?;
446 let output = Arc::new(Mutex::new(OutputBuffer::default()));
447 let reader_output = Arc::clone(&output);
448 std::thread::spawn(move || {
449 let mut reader = reader;
450 let mut buf = [0u8; 8192];
451 loop {
452 match std::io::Read::read(&mut reader, &mut buf) {
453 Ok(0) | Err(_) => break,
454 Ok(n) => {
455 if let Ok(mut output) = reader_output.lock() {
456 output.append(&buf[..n]);
457 }
458 }
459 }
460 }
461 });
462
463 let durable = DurableTerminalRecord {
464 schema_version: 1,
465 session_id: Uuid::new_v4().to_string(),
466 runtime_nonce: runtime_nonce().to_string(),
467 process_id: std::process::id(),
468 workspace: workspace.clone(),
469 name: name.to_string(),
470 shell,
471 last_known_cwd: workspace,
472 environment_summary: EnvironmentSummary {
473 term: std::env::var("TERM").ok().filter(|value| !value.trim().is_empty()),
474 virtual_env_active: std::env::var_os("VIRTUAL_ENV").is_some(),
475 conda_env_active: std::env::var_os("CONDA_PREFIX").is_some(),
476 nix_shell_active: std::env::var_os("IN_NIX_SHELL").is_some(),
477 note: "Values and secrets are not persisted; in-shell environment changes are process-local."
478 .to_string(),
479 },
480 state: DurableTerminalState::Idle,
481 updated_at: chrono::Utc::now().to_rfc3339(),
482 previous,
483 };
484 persist_durable(&durable_path, &durable)?;
485
486 Ok(Arc::new(Mutex::new(TerminalSession {
487 writer: Arc::new(Mutex::new(writer)),
488 master: pair.master,
489 child,
490 output,
491 read_cursor: 0,
492 command: None,
493 durable,
494 durable_path,
495 sandbox_confined,
496 sandbox_policy: policy,
497 })))
498 }
499
500 #[cfg(unix)]
501 pub fn get_or_create(
502 owner: &str,
503 name: &str,
504 workspace: &std::path::Path,
505 policy: codewhale_sandbox::SandboxPolicy,
506 shell_manager: &crate::tools::shell::SharedShellManager,
507 ) -> Result<SharedSession, String> {
508 let key = session_key(owner, name, workspace);
509 let mut registry = sessions()
510 .lock()
511 .map_err(|_| "terminal session registry lock poisoned".to_string())?;
512 let existing = registry.get(&key).map(|entry| Arc::clone(&entry.session));
513 if let Some(session) = existing {
514 drop(registry);
515 let reusable = {
516 let guard = session
517 .lock()
518 .map_err(|_| "terminal session lock poisoned".to_string())?;
519 can_reuse_under_policy(&guard, &policy)
520 };
521 if !reusable {
522 return Err(
523 "existing PTY session does not enforce the current sandbox policy; start a new session name under the current posture or use Full Access"
524 .to_string(),
525 );
526 }
527 return Ok(session);
528 }
529 if let Some((plugin_id, _)) = crate::extension_host::dsh_terminal::session_parts(name) {
530 let held = registry
531 .keys()
532 .filter(|entry| {
533 entry.workspace == key.workspace
534 && entry.owner == key.owner
535 && crate::extension_host::dsh_terminal::session_parts(&entry.name)
536 .is_some_and(|(other, _)| other == plugin_id)
537 })
538 .count();
539 if held >= crate::extension_host::dsh_terminal::MAX_TERMINALS {
540 return Err(
541 "this plugin already holds the most terminals it may open in this session"
542 .to_string(),
543 );
544 }
545 }
546 let session = create_session(owner, name, workspace, policy, shell_manager)?;
547 registry.insert(key, Registered::new(&session)?);
548 Ok(session)
549 }
550
551 #[cfg(unix)]
552 fn replace_registered(key: SessionKey, session: &SharedSession) -> Result<String, String> {
553 let entry = Registered::new(session)?;
554 let id = entry.id.clone();
555 sessions()
556 .lock()
557 .map_err(|_| "terminal session registry lock poisoned".to_string())?
558 .insert(key, entry);
559 Ok(id)
560 }
561
562 /// Restricted reuse requires the policy that actually created the process.
563 /// Exact comparison is deliberately conservative: widening a restricted policy
564 /// may require a new name too, but never weakens a running process's boundary.
565 #[cfg(unix)]
566 fn can_reuse_under_policy(
567 session: &TerminalSession,
568 policy: &codewhale_sandbox::SandboxPolicy,
569 ) -> bool {
570 !policy.should_sandbox() || (session.sandbox_confined && session.sandbox_policy == *policy)
571 }
572
573 #[cfg(unix)]
574 fn find(owner: &str, name: &str, workspace: &Path) -> Result<SharedSession, String> {
575 let live = sessions()
576 .lock()
577 .map_err(|_| "terminal session registry lock poisoned".to_string())?
578 .get(&session_key(owner, name, workspace))
579 .map(|entry| Arc::clone(&entry.session));
580 if let Some(live) = live {
581 return Ok(live);
582 }
583 if let Ok(path) = durable_path(owner, name, workspace)
584 && let Some(mut record) = load_durable(&path)?
585 {
586 record.state = DurableTerminalState::StaleLost;
587 record.updated_at = chrono::Utc::now().to_rfc3339();
588 if let Err(error) = persist_durable(&path, &record) {
589 tracing::warn!(name, "{error}");
590 }
591 return Err(format!(
592 "terminal session '{name}' is stale/lost after restart (last cwd: {}); run {TERMINAL_RUN_NAME} with this name to start a replacement while preserving the historical summary",
593 record.last_known_cwd.display()
594 ));
595 }
596 Err(format!(
597 "terminal session '{name}' does not exist in workspace {}",
598 workspace.display()
599 ))
600 }
601
602 #[cfg(unix)]
603 fn write_bytes(session: &TerminalSession, bytes: &[u8]) -> io::Result<()> {
604 let mut writer = session
605 .writer
606 .lock()
607 .map_err(|_| io::Error::other("terminal PTY writer lock poisoned"))?;
608 writer.write_all(bytes)?;
609 writer.flush()
610 }
611
612 /// Raw input must not silently overflow the canonical line buffer. This
613 /// refuses the demonstrated oversized batch, not cumulative line editing
614 /// or a concurrent terminal-mode change. Internal shell source and completion
615 /// sentinels use the private writer instead.
616 #[cfg(unix)]
617 pub fn write_raw_input(session: &TerminalSession, bytes: &[u8]) -> io::Result<()> {
618 if bytes.len() >= 1024
619 && session
620 .master
621 .get_termios()
622 .is_none_or(|mode| mode.local_flags.bits() & libc::ICANON != 0)
623 {
624 return Err(io::Error::new(
625 io::ErrorKind::InvalidInput,
626 "terminal input batch is too large for canonical or unknown input mode; no input was sent. Send fewer than 1024 bytes, or use an application in raw mode.",
627 ));
628 }
629 write_bytes(session, bytes)
630 }
631
632 #[cfg(unix)]
633 fn output_snapshot(session: &TerminalSession) -> String {
634 session
635 .output
636 .lock()
637 .map(|output| output.text())
638 .unwrap_or_default()
639 }
640
641 #[cfg(unix)]
642 fn take_output(session: &mut TerminalSession) -> String {
643 let Ok(output) = session.output.lock() else {
644 return String::new();
645 };
646 let chunk = output.read_since(session.read_cursor, usize::MAX);
647 session.read_cursor = output.total;
648 String::from_utf8_lossy(&chunk.bytes).into_owned()
649 }
650
651 /// Resize the live pty's window. The kernel updates its `winsize` and signals
652 /// the child, which is what makes an interactive app redraw at the new size.
653 #[cfg(unix)]
654 pub fn resize_session(session: &TerminalSession, rows: u16, cols: u16) -> Result<(), String> {
655 session
656 .master
657 .resize(portable_pty::PtySize {
658 rows,
659 cols,
660 pixel_width: 0,
661 pixel_height: 0,
662 })
663 .map_err(|e| format!("PTY resize failed: {e}"))
664 }
665
666 /// Absolute-offset, non-consuming read. `max_bytes` is clamped to
667 /// [`READ_LIMIT`] so one caller cannot ask for the whole retained window.
668 ///
669 /// Known limitation: this reports a [`OutputChunk::gap`]; it does not repair
670 /// one. Bytes dropped by the ring are gone with the process, and nothing here
671 /// re-reads them from disk — the durable record is identity and lifecycle,
672 /// never output.
673 #[cfg(unix)]
674 pub fn read_session_since(
675 session: &TerminalSession,
676 cursor: u64,
677 max_bytes: usize,
678 ) -> Result<OutputChunk, String> {
679 let output = session
680 .output
681 .lock()
682 .map_err(|_| "terminal output lock poisoned".to_string())?;
683 Ok(output.read_since(cursor, max_bytes.min(READ_LIMIT)))
684 }
685
686 /// Poll the shell without blocking; `None` means it is still running.
687 #[cfg(unix)]
688 pub fn session_exit_status(
689 session: &mut TerminalSession,
690 ) -> Result<Option<portable_pty::ExitStatus>, String> {
691 session
692 .child
693 .try_wait()
694 .map_err(|e| format!("PTY wait failed: {e}"))
695 }
696
697 /// Terminate the shell. The caller still observes the exit through
698 /// [`session_exit_status`].
699 #[cfg(unix)]
700 pub fn kill_session(session: &mut TerminalSession) -> Result<(), String> {
701 session
702 .child
703 .kill()
704 .map_err(|e| format!("PTY kill failed: {e}"))
705 }
706
707 #[cfg(unix)]
708 fn kill_matching_sessions(mut matches: impl FnMut(&SessionKey) -> bool) -> Result<usize, String> {
709 let mut registry = sessions()
710 .lock()
711 .map_err(|_| "terminal session registry lock poisoned".to_string())?;
712 let keys = registry
713 .keys()
714 .filter(|key| matches(key))
715 .cloned()
716 .collect::<Vec<_>>();
717 let mut ended = 0;
718 for key in keys {
719 let Some(registered) = registry.remove(&key) else {
720 continue;
721 };
722 let mut session = registered
723 .session
724 .lock()
725 .map_err(|_| "terminal session lock poisoned".to_string())?;
726 let killed = kill_session(&mut session)
727 .inspect_err(|error| {
728 tracing::warn!(owner = %key.owner, name = %key.name, "terminal PTY kill failed during thread cleanup: {error}");
729 })
730 .is_ok();
731 session.durable.state = DurableTerminalState::Canceled;
732 session.durable.updated_at = chrono::Utc::now().to_rfc3339();
733 let persisted = persist_durable(&session.durable_path, &session.durable)
734 .inspect_err(|error| {
735 tracing::warn!(owner = %key.owner, name = %key.name, "{error}");
736 })
737 .is_ok();
738 if killed && persisted {
739 ended += 1;
740 }
741 }
742 Ok(ended)
743 }
744
745 #[cfg(unix)]
746 pub fn kill_owner_sessions(workspace: &Path, owner: &str) -> Result<usize, String> {
747 let workspace = canonical(workspace);
748 kill_matching_sessions(|key| key.workspace == workspace && key.owner == owner)
749 }
750
751 #[cfg(unix)]
752 pub fn kill_sessions_named(prefix: &str) -> Result<usize, String> {
753 let valid_prefix = prefix
754 .strip_prefix("dsh:")
755 .and_then(|rest| rest.strip_suffix(':'))
756 .is_some_and(|plugin_id| !plugin_id.is_empty());
757 if !valid_prefix {
758 return Ok(0);
759 }
760 kill_matching_sessions(|key| {
761 key.name
762 .strip_prefix(prefix)
763 .is_some_and(crate::extension_host::dsh_terminal::is_valid_session_name)
764 })
765 }
766
767 #[cfg(not(unix))]
768 pub fn kill_owner_sessions(_workspace: &std::path::Path, _owner: &str) -> Result<usize, String> {
769 Ok(0)
770 }
771
772 #[cfg(not(unix))]
773 pub fn kill_sessions_named(_prefix: &str) -> Result<usize, String> {
774 Ok(0)
775 }
776
777 /// Resolve a live session by the identity it was issued, never creating one.
778 ///
779 /// HTTP clients attach to shells the Engine already owns (the agent's
780 /// terminal tools create them): an identity with no live session is a miss,
781 /// never a new process. `owner` narrows the match to one thread's shells; the
782 /// dock passes `None` because it shows every shell in its workspace.
783 #[cfg(unix)]
784 pub fn lookup(workspace: &Path, owner: Option<&str>, id: &str) -> Option<SharedSession> {
785 registered(workspace, owner, None, id)
786 }
787
788 #[cfg(unix)]
789 fn registered(
790 workspace: &Path,
791 owner: Option<&str>,
792 name: Option<&str>,
793 id: &str,
794 ) -> Option<SharedSession> {
795 let workspace = canonical(workspace);
796 sessions()
797 .lock()
798 .ok()?
799 .iter()
800 .find(|(key, entry)| {
801 entry.id == id
802 && key.workspace == workspace
803 && owner.is_none_or(|owner| key.owner == owner)
804 && name.is_none_or(|name| key.name == name)
805 })
806 .map(|(_, entry)| Arc::clone(&entry.session))
807 }
808
809 /// A projection of the existing registry, never another session owner.
810 #[cfg(unix)]
811 #[derive(Clone, Debug, PartialEq, Eq)]
812 pub struct TerminalSessionInfo {
813 pub id: String,
814 pub name: String,
815 pub state: DurableTerminalState,
816 pub exit_code: Option<u32>,
817 pub updated_at: String,
818 pub last_activity: Option<Instant>,
819 }
820
821 #[cfg(unix)]
822 fn live_entries(
823 workspace: &Path,
824 owner: Option<&str>,
825 ) -> Result<Vec<(TerminalSessionInfo, SharedSession)>, String> {
826 let workspace = canonical(workspace);
827 let live = sessions()
828 .lock()
829 .map_err(|_| "terminal session registry lock poisoned".to_string())?
830 .iter()
831 .filter(|(key, _)| {
832 key.workspace == workspace && owner.is_none_or(|owner| key.owner == owner)
833 })
834 .map(|(_, entry)| Arc::clone(&entry.session))
835 .collect::<Vec<_>>();
836 let mut entries = Vec::with_capacity(live.len());
837 for handle in live {
838 let mut session = handle
839 .lock()
840 .map_err(|_| "terminal session lock poisoned".to_string())?;
841 let exit_code = session_exit_status(&mut session)?.map(|status| status.exit_code());
842 let state = match completion(&session) {
843 Some((0, _)) => DurableTerminalState::Idle,
844 Some((130, _)) => DurableTerminalState::Canceled,
845 Some(_) => DurableTerminalState::Failed,
846 None => session.durable.state,
847 };
848 entries.push((
849 TerminalSessionInfo {
850 id: session.durable.session_id.clone(),
851 name: session.durable.name.clone(),
852 state,
853 exit_code,
854 updated_at: session.durable.updated_at.clone(),
855 last_activity: session
856 .output
857 .lock()
858 .map_err(|_| "terminal output lock poisoned".to_string())?
859 .last_activity,
860 },
861 handle.clone(),
862 ));
863 }
864 entries.sort_by(|(a, _), (b, _)| {
865 b.last_activity
866 .cmp(&a.last_activity)
867 .then(b.updated_at.cmp(&a.updated_at))
868 .then(a.name.cmp(&b.name))
869 });
870 Ok(entries)
871 }
872
873 /// Called on the dock's blocking worker. Reads never consume tool output.
874 /// A selected identity that disappeared is not replaced by a reused name.
875 #[cfg(unix)]
876 pub fn inspect_workspace(
877 workspace: &Path,
878 selected: Option<&str>,
879 ) -> Result<(Vec<TerminalSessionInfo>, Option<OutputChunk>), String> {
880 inspect_workspace_since(workspace, selected, None)
881 }
882
883 #[cfg(unix)]
884 pub fn inspect_workspace_since(
885 workspace: &Path,
886 selected: Option<&str>,
887 cursor: Option<u64>,
888 ) -> Result<(Vec<TerminalSessionInfo>, Option<OutputChunk>), String> {
889 let entries = live_entries(workspace, None)?;
890 let selected = match selected {
891 Some(id) => entries.iter().find(|(info, _)| info.id == id),
892 None => entries.first(),
893 };
894 let output = selected
895 .map(|(_, handle)| -> Result<OutputChunk, String> {
896 let session = handle
897 .lock()
898 .map_err(|_| "terminal session lock poisoned".to_string())?;
899 let output = session
900 .output
901 .lock()
902 .map_err(|_| "terminal output lock poisoned".to_string())?;
903 let start = cursor.unwrap_or_else(|| output.total.saturating_sub(READ_LIMIT as u64));
904 Ok(output.read_since(start, READ_LIMIT))
905 })
906 .transpose()?;
907 Ok((entries.into_iter().map(|(info, _)| info).collect(), output))
908 }
909
910 #[cfg(unix)]
911 pub fn owned_sessions(workspace: &Path, owner: &str) -> Result<Vec<TerminalSessionInfo>, String> {
912 Ok(live_entries(workspace, Some(owner))?
913 .into_iter()
914 .map(|(info, _)| info)
915 .collect())
916 }
917
918 #[cfg(unix)]
919 #[derive(Debug)]
920 pub enum HumanInputError {
921 Gone,
922 Posture,
923 Exited,
924 Rejected(String),
925 Failed(String),
926 }
927
928 #[cfg(unix)]
929 impl std::fmt::Display for HumanInputError {
930 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
931 formatter.write_str(match self {
932 Self::Gone => {
933 "selected terminal is gone or was reset; select its replacement explicitly"
934 }
935 Self::Posture => {
936 "selected terminal does not enforce the current sandbox policy; start a fresh terminal"
937 }
938 Self::Exited => "selected terminal has exited; start a fresh terminal",
939 Self::Rejected(message) | Self::Failed(message) => message.as_str(),
940 })
941 }
942 }
943
944 /// Human input is bound to the displayed incarnation, including across reset.
945 /// It follows the same sandbox-reuse guard as the model's terminal_run path.
946 #[cfg(unix)]
947 pub fn write_human_input(
948 handle: &SharedSession,
949 bytes: &[u8],
950 policy: &codewhale_sandbox::SandboxPolicy,
951 ) -> Result<(), HumanInputError> {
952 let mut session = handle
953 .lock()
954 .map_err(|_| HumanInputError::Failed("terminal session lock poisoned".into()))?;
955 if !can_reuse_under_policy(&session, policy) {
956 return Err(HumanInputError::Posture);
957 }
958 if session_exit_status(&mut session)
959 .map_err(HumanInputError::Failed)?
960 .is_some()
961 {
962 return Err(HumanInputError::Exited);
963 }
964 if bytes == [3] && session.command.is_some() && completion(&session).is_none() {
965 // SIGINT can discard the grouped command's completion suffix. Reuse
966 // the confirmed interrupt path so model waiters and later runs see
967 // the persistent shell become ready again.
968 drop(session);
969 return cancel_shared_session(handle)
970 .map(|_| ())
971 .map_err(|error| HumanInputError::Failed(error.to_string()));
972 }
973 write_raw_input(&session, bytes).map_err(|error| {
974 if error.kind() == io::ErrorKind::InvalidInput {
975 HumanInputError::Rejected(error.to_string())
976 } else {
977 HumanInputError::Failed(error.to_string())
978 }
979 })
980 }
981
982 #[cfg(unix)]
983 pub fn write_dock_input(
984 workspace: &Path,
985 name: &str,
986 id: &str,
987 bytes: &[u8],
988 policy: &codewhale_sandbox::SandboxPolicy,
989 ) -> Result<(), String> {
990 let handle = registered(workspace, None, Some(name), id)
991 .ok_or_else(|| HumanInputError::Gone.to_string())?;
992 write_human_input(&handle, bytes, policy).map_err(|error| error.to_string())
993 }
994
995 #[cfg(unix)]
996 pub fn resize_dock_session(
997 workspace: &Path,
998 name: &str,
999 id: &str,
1000 rows: u16,
1001 cols: u16,
1002 ) -> Result<(), String> {
1003 let handle = registered(workspace, None, Some(name), id)
1004 .ok_or("selected terminal is gone or was reset")?;
1005 let session = handle
1006 .lock()
1007 .map_err(|_| "terminal session lock poisoned".to_string())?;
1008 resize_session(&session, rows, cols)
1009 }
1010
1011 #[cfg(unix)]
1012 fn prune_output(input: &str) -> String {
1013 if input.len() <= OUTPUT_LIMIT {
1014 return input.to_string();
1015 }
1016 let head = OUTPUT_LIMIT / 3;
1017 let tail = OUTPUT_LIMIT - head;
1018 let head_end = input
1019 .char_indices()
1020 .find(|(index, _)| *index >= head)
1021 .map_or(input.len(), |(index, _)| index);
1022 // The earliest boundary that still fits: the tail is where a build's
1023 // error and the command's completion marker are.
1024 let tail_start = input
1025 .char_indices()
1026 .map(|(index, _)| index)
1027 .find(|index| *index >= head_end && input.len() - *index <= tail)
1028 .unwrap_or(input.len());
1029 format!(
1030 "{}\n… [output truncated: {} bytes omitted] …\n{}",
1031 &input[..head_end],
1032 tail_start - head_end,
1033 &input[tail_start..]
1034 )
1035 }
1036
1037 #[cfg(unix)]
1038 fn strip_zsh_prompt_marks(raw: &str) -> String {
1039 if !raw.contains("\x1b[") {
1040 return raw.to_string();
1041 }
1042 const MARKS: &[&str] = &[
1043 "\x1b[1m\x1b[7m%\x1b[27m\x1b[1m\x1b[0m",
1044 "\x1b[1m\x1b[7m#\x1b[27m\x1b[1m\x1b[0m",
1045 "\x1b[7m%\x1b[27m",
1046 "\x1b[7m#\x1b[27m",
1047 ];
1048 let mut out = String::with_capacity(raw.len());
1049 let mut rest = raw;
1050 while !rest.is_empty() {
1051 let mut matched = None;
1052 for mark in MARKS {
1053 if let Some(after) = rest.strip_prefix(mark) {
1054 matched = Some(after);
1055 break;
1056 }
1057 }
1058 if let Some(mut after) = matched {
1059 let trimmed_spaces = after.trim_start_matches(' ');
1060 if let Some(post_cr) = trimmed_spaces
1061 .strip_prefix("\r \r")
1062 .or_else(|| trimmed_spaces.strip_prefix('\r'))
1063 {
1064 after = post_cr;
1065 } else if trimmed_spaces.starts_with('\n') {
1066 after = trimmed_spaces;
1067 }
1068 rest = after;
1069 continue;
1070 }
1071 let next_esc = rest
1072 .match_indices('\x1b')
1073 .find(|(offset, _)| *offset > 0)
1074 .map_or(rest.len(), |(offset, _)| offset);
1075 out.push_str(&rest[..next_esc]);
1076 rest = &rest[next_esc..];
1077 }
1078 out
1079 }
1080
1081 #[cfg(unix)]
1082 fn collapse_carriage_returns(line: &str) -> String {
1083 if !line.contains('\r') {
1084 return line.to_string();
1085 }
1086 let mut buf: Vec<char> = Vec::new();
1087 let mut col = 0usize;
1088 for ch in line.chars() {
1089 if ch == '\r' {
1090 col = 0;
1091 } else {
1092 if col < buf.len() {
1093 buf[col] = ch;
1094 } else {
1095 buf.push(ch);
1096 }
1097 col += 1;
1098 }
1099 }
1100 if buf.iter().all(|ch| *ch == ' ') {
1101 return String::new();
1102 }
1103 let collapsed: String = buf.into_iter().collect();
1104 collapsed.trim_end_matches(' ').to_string()
1105 }
1106
1107 #[cfg(unix)]
1108 fn normalize_pty_text(raw: &str) -> String {
1109 let without_zsh = strip_zsh_prompt_marks(raw);
1110 let mut stripped = String::with_capacity(without_zsh.len());
1111 codewhale_sanitize::sanitize::strip_ansi_into(&without_zsh, &mut stripped);
1112 let lf = stripped.replace("\r\n", "\n");
1113 let mut out = String::with_capacity(lf.len());
1114 for (idx, line) in lf.split('\n').enumerate() {
1115 if idx > 0 {
1116 out.push('\n');
1117 }
1118 let collapsed = collapse_carriage_returns(line);
1119 for ch in collapsed.chars() {
1120 if ch == '\t' || (!ch.is_control() && ch != '\x7f') {
1121 out.push(ch);
1122 }
1123 }
1124 }
1125 out
1126 }
1127
1128 #[cfg(unix)]
1129 fn parse_completion_marker(raw: &str, marker: &str) -> Option<(i32, String)> {
1130 let marker_colon = format!("{marker}:");
1131 if !raw.contains(&marker_colon) {
1132 return None;
1133 }
1134 let cleaned = normalize_pty_text(raw);
1135 let needle = format!("\n{marker}:");
1136 let tail = cleaned
1137 .rsplit_once(&needle)
1138 .map(|(_, tail)| tail)
1139 .or_else(|| cleaned.strip_prefix(&marker_colon))?;
1140 let (line, _) = tail.split_once('\n')?;
1141 let (status, cwd) = line.split_once(':')?;
1142 Some((status.trim().parse().ok()?, cwd.to_string()))
1143 }
1144
1145 #[cfg(unix)]
1146 fn is_internal_sentinel_line(line: &str) -> bool {
1147 let trimmed = line.trim();
1148 let Some(rest) = trimmed.strip_prefix("__CODEWHALE_TERM_") else {
1149 return false;
1150 };
1151 if let Some((prefix, tail)) = rest.split_once("__:") {
1152 !prefix.is_empty()
1153 && prefix.bytes().all(|b| b.is_ascii_alphanumeric())
1154 && tail
1155 .split_once(':')
1156 .is_some_and(|(code, _)| code.trim().parse::<i32>().is_ok())
1157 } else {
1158 rest.ends_with("__START") || rest.ends_with("SOURCE")
1159 }
1160 }
1161
1162 #[cfg(unix)]
1163 fn strip_internal_scaffolding(input: &str) -> String {
1164 if !input.contains("__CODEWHALE_TERM_") {
1165 return input.to_string();
1166 }
1167 let has_trailing_nl = input.ends_with('\n');
1168 let lines: Vec<&str> = if has_trailing_nl {
1169 input[..input.len() - 1].split('\n').collect()
1170 } else {
1171 input.split('\n').collect()
1172 };
1173 let mut start = 0usize;
1174 if let Some(wrapper_idx) = lines
1175 .iter()
1176 .position(|line| line.contains(". /dev/fd/9 9<<'__CODEWHALE_TERM_"))
1177 && let Some(rel_end) = lines[wrapper_idx + 1..].iter().position(|line| {
1178 line.contains("__CODEWHALE_TERM_") && line.trim_end().ends_with("SOURCE")
1179 })
1180 {
1181 start = wrapper_idx + 1 + rel_end + 1;
1182 }
1183 let mut end = lines.len();
1184 if let Some(rel_sentinel) = lines[start..].iter().rposition(|line| {
1185 let trimmed = line.trim();
1186 trimmed.starts_with("__CODEWHALE_TERM_")
1187 && trimmed.contains("__:")
1188 && is_internal_sentinel_line(trimmed)
1189 }) {
1190 end = start + rel_sentinel;
1191 }
1192 let kept: Vec<&str> = lines[start..end]
1193 .iter()
1194 .copied()
1195 .filter(|line| {
1196 !(line.contains(". /dev/fd/9 9<<'__CODEWHALE_TERM_")
1197 || (line.contains("__cw_status=") && line.contains("__CODEWHALE_TERM_"))
1198 || (line.contains("heredoc>") && line.contains("__CODEWHALE_TERM_"))
1199 || is_internal_sentinel_line(line))
1200 })
1201 .collect();
1202 let mut joined = kept.join("\n");
1203 if has_trailing_nl && end == lines.len() && !joined.is_empty() {
1204 joined.push('\n');
1205 }
1206 joined
1207 }
1208
1209 #[cfg(unix)]
1210 fn clean_pty_output(raw: &str, command: Option<&CommandState>) -> String {
1211 let normalized = normalize_pty_text(raw);
1212 let mut body: &str = &normalized;
1213 if let Some(state) = command {
1214 let start_with_nl = format!("\n{}\n", state.start_marker);
1215 let start_prefix = format!("{}\n", state.start_marker);
1216 let start_trailing = format!("\n{}", state.start_marker);
1217 if let Some(pos) = body.find(&start_with_nl) {
1218 body = &body[pos + start_with_nl.len()..];
1219 } else if let Some(rest) = body.strip_prefix(&start_prefix) {
1220 body = rest;
1221 } else if let Some(pos) = body.find(&start_trailing) {
1222 body = &body[pos + start_trailing.len()..];
1223 body = body.strip_prefix('\n').unwrap_or(body);
1224 }
1225 let end_nl = format!("\n{}:", state.marker);
1226 let end_prefix = format!("{}:", state.marker);
1227 if let Some((before, _)) = body.rsplit_once(&end_nl) {
1228 body = before;
1229 } else if body.starts_with(&end_prefix) {
1230 body = "";
1231 }
1232 }
1233 strip_internal_scaffolding(body)
1234 }
1235
1236 #[cfg(unix)]
1237 fn completion(session: &TerminalSession) -> Option<(i32, String)> {
1238 let state = session.command.as_ref()?;
1239 let output = output_snapshot(session);
1240 parse_completion_marker(&output, &state.marker)
1241 }
1242
1243 #[cfg(unix)]
1244 fn start_command(session: &mut TerminalSession, command: &str) -> Result<(), String> {
1245 if session.command.is_some() && completion(session).is_none() {
1246 return Err("terminal session already has a running foreground command".to_string());
1247 }
1248 let id = Uuid::new_v4().simple().to_string();
1249 let marker = format!("__CODEWHALE_TERM_{id}__");
1250 let start_marker = format!("{marker}START");
1251 let delimiter = format!("{marker}SOURCE");
1252 let wrapped = format!(
1253 "printf '\\n__CODEWHALE_TERM_%s__START\\n' '{id}'; . /dev/fd/9 9<<'{delimiter}'; __cw_status=$?; printf '\\n__CODEWHALE_TERM_%s__:%s:%s\\n' '{id}' \"$__cw_status\" \"$PWD\"\n{command}\n{delimiter}\n"
1254 );
1255 write_bytes(session, wrapped.as_bytes())
1256 .map_err(|error| format!("PTY write failed: {error}"))?;
1257 session.command = Some(CommandState {
1258 id,
1259 marker,
1260 start_marker,
1261 });
1262 session.durable.state = DurableTerminalState::Running;
1263 session.durable.updated_at = chrono::Utc::now().to_rfc3339();
1264 persist_durable(&session.durable_path, &session.durable)?;
1265 Ok(())
1266 }
1267
1268 #[cfg(unix)]
1269 fn write_completion_sentinel(
1270 session: &TerminalSession,
1271 id: &str,
1272 status: i32,
1273 ) -> Result<(), String> {
1274 let sentinel = format!(
1275 "__cw_status={status}; printf '\\n__CODEWHALE_TERM_%s__:%s:%s\\n' '{id}' \"$__cw_status\" \"$PWD\"\n"
1276 );
1277 write_bytes(session, sentinel.as_bytes()).map_err(|error| format!("PTY write failed: {error}"))
1278 }
1279
1280 #[cfg(unix)]
1281 #[cfg(test)]
1282 fn wait_session(session: &mut TerminalSession, timeout: Duration) -> (Option<(i32, String)>, bool) {
1283 let deadline = Instant::now() + timeout;
1284 loop {
1285 if let Some(done) = completion(session) {
1286 return (Some(done), false);
1287 }
1288 if Instant::now() >= deadline {
1289 return (None, true);
1290 }
1291 std::thread::sleep(Duration::from_millis(25));
1292 }
1293 }
1294
1295 /// Wait without monopolizing the per-session lock. `terminal_send` and
1296 /// `terminal_cancel` must be able to acquire the lock while a foreground
1297 /// command is active; otherwise interactive input and cancellation deadlock
1298 /// behind the waiter.
1299 #[cfg(unix)]
1300 fn wait_shared_session(
1301 session: &SharedSession,
1302 timeout: Duration,
1303 ) -> Result<(Option<(i32, String)>, bool), ToolError> {
1304 let deadline = Instant::now() + timeout;
1305 loop {
1306 let done = {
1307 let session = session
1308 .lock()
1309 .map_err(|_| ToolError::execution_failed("terminal session lock poisoned"))?;
1310 completion(&session)
1311 };
1312 if let Some(done) = done {
1313 return Ok((Some(done), false));
1314 }
1315 if Instant::now() >= deadline {
1316 return Ok((None, true));
1317 }
1318 std::thread::sleep(Duration::from_millis(25));
1319 }
1320 }
1321
1322 /// Interrupt a foreground command and wait until the persistent shell confirms
1323 /// that it is ready again.
1324 ///
1325 /// Canonical PTYs may flush queued input when they process ETX, and an ETX
1326 /// sent before the foreground child owns the terminal never interrupts it.
1327 /// Resubmit the completion sentinel until the shell acknowledges it, and
1328 /// resubmit the interrupt on a slower cadence only while the terminal's
1329 /// foreground group is not the shell's own, so a re-interrupt cannot flush or
1330 /// abort a sentinel the shell is about to run.
1331 #[cfg(unix)]
1332 fn cancel_shared_session(session: &SharedSession) -> Result<(i32, String), ToolError> {
1333 let command_id = {
1334 let session = session
1335 .lock()
1336 .map_err(|_| ToolError::execution_failed("terminal session lock poisoned"))?;
1337 if session.command.is_none() || completion(&session).is_some() {
1338 return Err(ToolError::execution_failed(
1339 "terminal session has no running foreground command",
1340 ));
1341 }
1342 write_bytes(&session, &[3])
1343 .map_err(|error| ToolError::execution_failed(format!("PTY write failed: {error}")))?;
1344 session
1345 .command
1346 .as_ref()
1347 .expect("running command checked above")
1348 .id
1349 .clone()
1350 };
1351 let deadline = Instant::now() + CANCEL_CONFIRM_TIMEOUT;
1352 let mut last_interrupt = Instant::now();
1353
1354 loop {
1355 std::thread::sleep(CANCEL_SENTINEL_RETRY_INTERVAL);
1356 let session = session
1357 .lock()
1358 .map_err(|_| ToolError::execution_failed("terminal session lock poisoned"))?;
1359 if let Some(done) = completion(&session) {
1360 return Ok(done);
1361 }
1362 if Instant::now() >= deadline {
1363 return Err(ToolError::execution_failed(
1364 "terminal interrupt was sent, but cancellation was not confirmed within 2 seconds",
1365 ));
1366 }
1367 if last_interrupt.elapsed() >= CANCEL_INTERRUPT_RETRY_INTERVAL {
1368 let shell_foreground = session
1369 .master
1370 .process_group_leader()
1371 .and_then(|leader| u32::try_from(leader).ok())
1372 .is_some_and(|foreground| Some(foreground) == session.child.process_id());
1373 if !shell_foreground {
1374 write_bytes(&session, &[3]).map_err(|error| {
1375 ToolError::execution_failed(format!("PTY write failed: {error}"))
1376 })?;
1377 last_interrupt = Instant::now();
1378 }
1379 }
1380 write_completion_sentinel(&session, &command_id, 130)
1381 .map_err(ToolError::execution_failed)?;
1382 }
1383 }
1384
1385 #[cfg(unix)]
1386 fn session_result(
1387 session: &mut TerminalSession,
1388 done: Option<(i32, String)>,
1389 timed_out: bool,
1390 ) -> ToolResult {
1391 session_result_with_status(session, done, timed_out, None)
1392 }
1393
1394 #[cfg(unix)]
1395 fn session_result_with_status(
1396 session: &mut TerminalSession,
1397 done: Option<(i32, String)>,
1398 timed_out: bool,
1399 status_override: Option<&str>,
1400 ) -> ToolResult {
1401 let raw = take_output(session);
1402 let cleaned = clean_pty_output(&raw, session.command.as_ref());
1403 let stdout = prune_output(&cleaned);
1404 let finished = done.is_some();
1405 let (exit_code, cwd) = done.map_or((None, String::new()), |(code, cwd)| (Some(code), cwd));
1406 let status = status_override.unwrap_or(if timed_out {
1407 "timed_out"
1408 } else if finished {
1409 "completed"
1410 } else {
1411 "running"
1412 });
1413 if !cwd.is_empty() {
1414 session.durable.last_known_cwd = PathBuf::from(&cwd);
1415 }
1416 let effective_cwd = if cwd.is_empty() {
1417 session.durable.last_known_cwd.display().to_string()
1418 } else {
1419 cwd.clone()
1420 };
1421 session.durable.state = if timed_out || !finished {
1422 DurableTerminalState::Running
1423 } else if exit_code == Some(0) {
1424 DurableTerminalState::Idle
1425 } else if exit_code == Some(130) {
1426 DurableTerminalState::Canceled
1427 } else {
1428 DurableTerminalState::Failed
1429 };
1430 session.durable.updated_at = chrono::Utc::now().to_rfc3339();
1431 let persistence_error = persist_durable(&session.durable_path, &session.durable).err();
1432 let previous = session.durable.previous.as_deref().map(|record| {
1433 json!({
1434 "session_id": record.session_id,
1435 "state": record.state,
1436 "last_known_cwd": record.last_known_cwd,
1437 "updated_at": record.updated_at,
1438 })
1439 });
1440 let content = json!({
1441 "stdout": stdout,
1442 "exit_code": exit_code,
1443 "cwd": effective_cwd,
1444 "status": status,
1445 "session": session.durable.name,
1446 "session_id": session.durable.session_id,
1447 })
1448 .to_string();
1449 ToolResult {
1450 content,
1451 // A successful send while the command is still running is itself a
1452 // successful tool operation. Completed commands still report their
1453 // real exit status, and timeouts remain unsuccessful.
1454 success: status == "canceled" || (!timed_out && (!finished || exit_code == Some(0))),
1455 metadata: Some(json!({
1456 "status": status,
1457 "exit_code": exit_code,
1458 "cwd": cwd,
1459 "session_persistent": true,
1460 "durability": "live shell is process-local; identity and last-known summary persist",
1461 "terminal_session_id": session.durable.session_id,
1462 "terminal_state": session.durable.state,
1463 "state_path": session.durable_path,
1464 "previous_session": previous,
1465 "persistence_error": persistence_error,
1466 })),
1467 }
1468 }
1469
1470 #[cfg(unix)]
1471 fn session_name(input: &serde_json::Value, required: bool) -> Result<&str, ToolError> {
1472 match input.get("session").and_then(serde_json::Value::as_str) {
1473 Some(name) if !name.is_empty() => Ok(name),
1474 Some(_) => Err(ToolError::execution_failed("session must not be empty")),
1475 None if required => Err(ToolError::missing_field("session")),
1476 None => Ok("term-1"),
1477 }
1478 }
1479
1480 #[cfg(unix)]
1481 fn timeout_secs(input: &serde_json::Value, key: &str) -> Result<Duration, ToolError> {
1482 Ok(Duration::from_secs(
1483 optional_u64(input, key, DEFAULT_TIMEOUT_SECS)?.clamp(1, MAX_TIMEOUT_SECS),
1484 ))
1485 }
1486
1487 fn shell_allowed(context: &ToolContext, name: &str) -> Result<(), ToolError> {
1488 crate::tools::execution_envelope::enforce_tool_denial(context, name, &json!({}))?;
1489 if matches!(
1490 name,
1491 TERMINAL_RUN_NAME | TERMINAL_SEND_NAME | TERMINAL_RESET_NAME
1492 ) && context.shell_policy != codewhale_agent_contract::worker_profile::ShellPolicy::Full
1493 {
1494 return Err(ToolError::permission_denied(
1495 "Persistent terminal execution and input require full shell permission.",
1496 ));
1497 }
1498 if context.shell_policy.allows_shell() {
1499 Ok(())
1500 } else {
1501 Err(ToolError::execution_failed(
1502 "Shell tools are disabled by the active permission profile.",
1503 ))
1504 }
1505 }
1506
1507 #[cfg(not(unix))]
1508 fn unsupported() -> ToolResult {
1509 ToolResult::error("Stateful terminal sessions are currently supported on Unix only.")
1510 }
1511
1512 macro_rules! terminal_tool_common {
1513 ($name:expr, $description:literal) => {
1514 fn name(&self) -> &'static str {
1515 $name
1516 }
1517 fn description(&self) -> &'static str {
1518 $description
1519 }
1520 fn capabilities(&self) -> Vec<ToolCapability> {
1521 vec![
1522 ToolCapability::ExecutesCode,
1523 ToolCapability::RequiresApproval,
1524 ]
1525 }
1526 fn approval_requirement(&self) -> ApprovalRequirement {
1527 ApprovalRequirement::Required
1528 }
1529 };
1530 }
1531
1532 pub struct TerminalRunTool;
1533 #[async_trait]
1534 impl ToolSpec for TerminalRunTool {
1535 terminal_tool_common!(
1536 TERMINAL_RUN_NAME,
1537 "Run a command in a persistent PTY shell session. cd, exports, shell functions, and activated environments persist across calls in this process. Identity and a non-secret last-known summary persist across restarts; prior shells are surfaced as stale/lost and are never reattached. On timeout the wait is abandoned but the command keeps running in the session (use terminal_wait or terminal_cancel). (Unix only)"
1538 );
1539 fn input_schema(&self) -> serde_json::Value {
1540 json!({"type":"object","properties":{"command":{"type":"string"},"session":{"type":"string","default":"term-1"},"timeout_secs":{"type":"integer","default":120}},"required":["command"]})
1541 }
1542 async fn execute(
1543 &self,
1544 input: serde_json::Value,
1545 context: &ToolContext,
1546 ) -> Result<ToolResult, ToolError> {
1547 shell_allowed(context, self.name())?;
1548 #[cfg(unix)]
1549 {
1550 let command = required_str(&input, "command")?.to_string();
1551 let name = session_name(&input, false)?.to_string();
1552 let session = get_or_create(
1553 &context.state_namespace,
1554 &name,
1555 &context.workspace,
1556 pty_sandbox_policy(context)?,
1557 &context.shell_manager,
1558 )
1559 .map_err(ToolError::execution_failed)?;
1560 let timeout = timeout_secs(&input, "timeout_secs")?;
1561 return tokio::task::spawn_blocking(move || {
1562 {
1563 let mut session = session.lock().map_err(|_| {
1564 ToolError::execution_failed("terminal session lock poisoned")
1565 })?;
1566 start_command(&mut session, &command).map_err(ToolError::execution_failed)?;
1567 }
1568 let (done, timed_out) = wait_shared_session(&session, timeout)?;
1569 let mut session = session
1570 .lock()
1571 .map_err(|_| ToolError::execution_failed("terminal session lock poisoned"))?;
1572 Ok(session_result(&mut session, done, timed_out))
1573 })
1574 .await
1575 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
1576 }
1577 #[cfg(not(unix))]
1578 {
1579 let _ = input;
1580 Ok(unsupported())
1581 }
1582 }
1583 }
1584
1585 pub struct TerminalSendTool;
1586 #[async_trait]
1587 impl ToolSpec for TerminalSendTool {
1588 terminal_tool_common!(
1589 TERMINAL_SEND_NAME,
1590 "Send raw input to a live persistent terminal session. Use a literal ETX control byte to interrupt an interactive process. A prior-process shell is reported as stale/lost rather than reattached. (Unix only)"
1591 );
1592 fn input_schema(&self) -> serde_json::Value {
1593 json!({"type":"object","properties":{"session":{"type":"string"},"text":{"type":"string"},"wait_ms":{"type":"integer","default":250}},"required":["session","text"]})
1594 }
1595 async fn execute(
1596 &self,
1597 input: serde_json::Value,
1598 context: &ToolContext,
1599 ) -> Result<ToolResult, ToolError> {
1600 shell_allowed(context, self.name())?;
1601 #[cfg(unix)]
1602 {
1603 let name = session_name(&input, true)?.to_string();
1604 let text = required_str(&input, "text")?.as_bytes().to_vec();
1605 let session = find(&context.state_namespace, &name, &context.workspace)
1606 .map_err(ToolError::execution_failed)?;
1607 let wait = Duration::from_millis(optional_u64(&input, "wait_ms", 250)?.min(60_000));
1608 return tokio::task::spawn_blocking(move || {
1609 {
1610 let session = session.lock().map_err(|_| {
1611 ToolError::execution_failed("terminal session lock poisoned")
1612 })?;
1613 write_raw_input(&session, &text)
1614 .map_err(|error| ToolError::execution_failed(error.to_string()))?;
1615 }
1616 std::thread::sleep(wait);
1617 let mut session = session
1618 .lock()
1619 .map_err(|_| ToolError::execution_failed("terminal session lock poisoned"))?;
1620 let done = completion(&session);
1621 Ok(session_result(&mut session, done, false))
1622 })
1623 .await
1624 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
1625 }
1626 #[cfg(not(unix))]
1627 {
1628 let _ = input;
1629 Ok(unsupported())
1630 }
1631 }
1632 }
1633
1634 pub struct TerminalWaitTool;
1635 #[async_trait]
1636 impl ToolSpec for TerminalWaitTool {
1637 terminal_tool_common!(
1638 TERMINAL_WAIT_NAME,
1639 "Wait for the current foreground command in a live persistent terminal session and return buffered output. A prior-process shell is reported as stale/lost rather than reattached. Output buffer holds at most 512KiB; older bytes are dropped silently. (Unix only)"
1640 );
1641 fn input_schema(&self) -> serde_json::Value {
1642 json!({"type":"object","properties":{"session":{"type":"string"},"timeout_secs":{"type":"integer","default":120}},"required":["session"]})
1643 }
1644 async fn execute(
1645 &self,
1646 input: serde_json::Value,
1647 context: &ToolContext,
1648 ) -> Result<ToolResult, ToolError> {
1649 shell_allowed(context, self.name())?;
1650 #[cfg(unix)]
1651 {
1652 let name = session_name(&input, true)?.to_string();
1653 let session = find(&context.state_namespace, &name, &context.workspace)
1654 .map_err(ToolError::execution_failed)?;
1655 let timeout = timeout_secs(&input, "timeout_secs")?;
1656 return tokio::task::spawn_blocking(move || {
1657 let (done, timed_out) = wait_shared_session(&session, timeout)?;
1658 let mut session = session
1659 .lock()
1660 .map_err(|_| ToolError::execution_failed("terminal session lock poisoned"))?;
1661 Ok(session_result(&mut session, done, timed_out))
1662 })
1663 .await
1664 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
1665 }
1666 #[cfg(not(unix))]
1667 {
1668 let _ = input;
1669 Ok(unsupported())
1670 }
1671 }
1672 }
1673
1674 pub struct TerminalCancelTool;
1675 #[async_trait]
1676 impl ToolSpec for TerminalCancelTool {
1677 terminal_tool_common!(
1678 TERMINAL_CANCEL_NAME,
1679 "Interrupt the running foreground command with ETX. The live terminal session survives and can be reused; its non-secret summary persists. (Unix only)"
1680 );
1681 fn input_schema(&self) -> serde_json::Value {
1682 json!({"type":"object","properties":{"session":{"type":"string"}},"required":["session"]})
1683 }
1684 async fn execute(
1685 &self,
1686 input: serde_json::Value,
1687 context: &ToolContext,
1688 ) -> Result<ToolResult, ToolError> {
1689 shell_allowed(context, self.name())?;
1690 #[cfg(unix)]
1691 {
1692 let name = session_name(&input, true)?.to_string();
1693 let session = find(&context.state_namespace, &name, &context.workspace)
1694 .map_err(ToolError::execution_failed)?;
1695 return tokio::task::spawn_blocking(move || {
1696 let done = cancel_shared_session(&session)?;
1697 let mut session = session
1698 .lock()
1699 .map_err(|_| ToolError::execution_failed("terminal session lock poisoned"))?;
1700 let mut result =
1701 session_result_with_status(&mut session, Some(done), false, Some("canceled"));
1702 if let Some(metadata) = result.metadata.as_mut() {
1703 metadata["canceled"] = json!(true);
1704 }
1705 Ok(result)
1706 })
1707 .await
1708 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
1709 }
1710 #[cfg(not(unix))]
1711 {
1712 let _ = input;
1713 Ok(unsupported())
1714 }
1715 }
1716 }
1717
1718 pub struct TerminalResetTool;
1719 #[async_trait]
1720 impl ToolSpec for TerminalResetTool {
1721 terminal_tool_common!(
1722 TERMINAL_RESET_NAME,
1723 "Kill and recreate a persistent terminal session with a fresh environment. This loses live cd, exports, functions, activated environments, and running work while retaining the prior historical summary. (Unix only)"
1724 );
1725 fn input_schema(&self) -> serde_json::Value {
1726 json!({"type":"object","properties":{"session":{"type":"string"}},"required":["session"]})
1727 }
1728 async fn execute(
1729 &self,
1730 input: serde_json::Value,
1731 context: &ToolContext,
1732 ) -> Result<ToolResult, ToolError> {
1733 shell_allowed(context, self.name())?;
1734 #[cfg(unix)]
1735 {
1736 let name = session_name(&input, true)?.to_string();
1737 let owner = context.state_namespace.clone();
1738 let old =
1739 find(&owner, &name, &context.workspace).map_err(ToolError::execution_failed)?;
1740 let workspace = context.workspace.clone();
1741 let policy = pty_sandbox_policy(context)?;
1742 let shell_manager = context.shell_manager.clone();
1743 return tokio::task::spawn_blocking(move || {
1744 let mut previous = None;
1745 if let Ok(mut old) = old.lock() {
1746 let _ = old.child.kill();
1747 old.durable.state = DurableTerminalState::Reset;
1748 old.durable.updated_at = chrono::Utc::now().to_rfc3339();
1749 let _ = persist_durable(&old.durable_path, &old.durable);
1750 previous = Some(old.durable.session_id.clone());
1751 }
1752 let fresh = create_session(&owner, &name, &workspace, policy, &shell_manager)
1753 .map_err(ToolError::execution_failed)?;
1754 let id = replace_registered(session_key(&owner, &name, &workspace), &fresh)
1755 .map_err(ToolError::execution_failed)?;
1756 Ok(ToolResult {
1757 content: format!(
1758 "Reset terminal session '{name}'. Lost shell state and any running command."
1759 ),
1760 success: true,
1761 metadata: Some(json!({
1762 "session": name,
1763 "reset": true,
1764 "terminal_session_id": id,
1765 "previous_session_id": previous,
1766 "lost_state": ["cwd", "environment", "functions", "activated environments", "running command"],
1767 })),
1768 })
1769 })
1770 .await
1771 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
1772 }
1773 #[cfg(not(unix))]
1774 {
1775 let _ = input;
1776 Ok(unsupported())
1777 }
1778 }
1779 }
1780
1781 #[cfg(all(test, unix))]
1782 mod tests {
1783 #[cfg(unix)]
1784 #[test]
1785 fn corrupt_durable_record_is_reported_not_treated_as_missing() {
1786 let dir = tempfile::tempdir().expect("tempdir");
1787 let path = dir.path().join("record.json");
1788 assert!(load_durable(&path).expect("missing is ok").is_none());
1789 std::fs::write(&path, b"{not json").expect("write");
1790 let error = load_durable(&path).expect_err("corrupt record must error");
1791 assert!(error.contains("corrupt"), "{error}");
1792 }
1793
1794 fn test_shell_manager() -> crate::tools::shell::SharedShellManager {
1795 crate::tools::shell::new_shared_shell_manager(std::path::PathBuf::from("/tmp"))
1796 }
1797
1798 use super::*;
1799
1800 const OWNER: &str = "workspace";
1801
1802 /// Dock tests own a workspace so parallel tests cannot share their registry
1803 /// entries or durable summaries. Kill and reap every owned shell on drop.
1804 struct DockWorkspace(tempfile::TempDir);
1805
1806 impl DockWorkspace {
1807 fn new() -> Self {
1808 Self(tempfile::tempdir().unwrap())
1809 }
1810
1811 fn path(&self) -> &Path {
1812 self.0.path()
1813 }
1814
1815 fn session(&self, name: &str) -> SharedSession {
1816 get_or_create(
1817 OWNER,
1818 name,
1819 self.path(),
1820 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
1821 &test_shell_manager(),
1822 )
1823 .unwrap()
1824 }
1825 }
1826
1827 impl Drop for DockWorkspace {
1828 fn drop(&mut self) {
1829 let workspace = canonical(self.path());
1830 let mut owned = Vec::new();
1831 if let Ok(mut registry) = sessions().lock() {
1832 registry.retain(|key, entry| {
1833 if key.workspace == workspace {
1834 owned.push(Arc::clone(&entry.session));
1835 false
1836 } else {
1837 true
1838 }
1839 });
1840 }
1841 for session in owned {
1842 if let Ok(mut session) = session.lock()
1843 && session.child.kill().is_ok()
1844 {
1845 let _ = session.child.wait();
1846 }
1847 }
1848 }
1849 }
1850
1851 fn open_when_pty_available(open: impl Fn() -> Result<SharedSession, String>) -> SharedSession {
1852 let deadline = Instant::now() + Duration::from_secs(30);
1853 loop {
1854 match open() {
1855 Err(error)
1856 if error.starts_with("failed to open PTY") && Instant::now() < deadline =>
1857 {
1858 std::thread::sleep(Duration::from_millis(100));
1859 }
1860 opened => return opened.unwrap(),
1861 }
1862 }
1863 }
1864
1865 fn fresh(name: &str) -> SharedSession {
1866 let session = open_when_pty_available(|| {
1867 get_or_create(
1868 OWNER,
1869 name,
1870 std::path::Path::new("/tmp"),
1871 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
1872 &test_shell_manager(),
1873 )
1874 });
1875 let mut session_guard = session.lock().unwrap();
1876 let _ = session_guard.child.kill();
1877 drop(session_guard);
1878 let replacement = open_when_pty_available(|| {
1879 create_session(
1880 OWNER,
1881 name,
1882 std::path::Path::new("/tmp"),
1883 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
1884 &test_shell_manager(),
1885 )
1886 });
1887 replace_registered(session_key(OWNER, name, Path::new("/tmp")), &replacement).unwrap();
1888 replacement
1889 }
1890
1891 fn run(session: &SharedSession, command: &str, timeout: Duration) -> ToolResult {
1892 let mut session = session.lock().unwrap();
1893 start_command(&mut session, command).unwrap();
1894 let (done, timed_out) = wait_session(&mut session, timeout);
1895 session_result(&mut session, done, timed_out)
1896 }
1897
1898 #[test]
1899 fn prune_output_keeps_the_tail_and_counts_what_it_dropped() {
1900 let input = format!(
1901 "first-line\n{}\nerror: the last line é\n",
1902 "x".repeat(OUTPUT_LIMIT * 2)
1903 );
1904 let pruned = prune_output(&input);
1905 let (head, rest) = pruned
1906 .split_once("\n… [output truncated: ")
1907 .expect("truncation marker");
1908 let (omitted, tail) = rest.split_once(" bytes omitted] …\n").expect("count");
1909 let omitted: usize = omitted.parse().expect("omitted count");
1910 assert!(head.starts_with("first-line"));
1911 assert!(tail.ends_with("error: the last line é\n"), "{tail:?}");
1912 assert!(tail.len() > OUTPUT_LIMIT / 2, "tail kept only {tail:?}");
1913 assert_eq!(head.len() + omitted + tail.len(), input.len());
1914 }
1915
1916 // The whole family is compiled and registered on Unix only, a run's
1917 // timeout abandons the wait without stopping the command, and the output
1918 // ring silently drops the oldest bytes past 512KiB — the descriptions
1919 // must say all three so the model can plan around them.
1920 #[test]
1921 fn terminal_descriptions_disclose_platform_and_wait_semantics() {
1922 let descriptions = [
1923 (TerminalRunTool.name(), TerminalRunTool.description()),
1924 (TerminalSendTool.name(), TerminalSendTool.description()),
1925 (TerminalWaitTool.name(), TerminalWaitTool.description()),
1926 (TerminalCancelTool.name(), TerminalCancelTool.description()),
1927 (TerminalResetTool.name(), TerminalResetTool.description()),
1928 ];
1929 for (name, description) in descriptions {
1930 assert!(
1931 description.contains("(Unix only)"),
1932 "{name} must disclose its platform restriction: {description}"
1933 );
1934 }
1935 assert!(
1936 TerminalRunTool
1937 .description()
1938 .contains("the command keeps running in the session"),
1939 "terminal_run must disclose that a timeout abandons the wait, not the command"
1940 );
1941 assert!(
1942 TerminalWaitTool.description().contains("512KiB"),
1943 "terminal_wait must disclose the retained-output bound"
1944 );
1945 }
1946
1947 #[test]
1948 #[cfg(unix)]
1949 fn cd_persists_between_runs() {
1950 let session = fresh("test-cd");
1951 let _ = run(
1952 &session,
1953 "mkdir -p /tmp/cw-term-cd-proof && cd /tmp/cw-term-cd-proof",
1954 Duration::from_secs(3),
1955 );
1956 // A separate run must still be inside the directory — this is the
1957 // whole point of the stateful session (EXEC-001).
1958 let result = run(&session, "pwd", Duration::from_secs(3));
1959 assert!(result.content.contains("cw-term-cd-proof"), "{}", {
1960 &result.content
1961 });
1962 }
1963
1964 #[test]
1965 #[cfg(unix)]
1966 fn export_persists_and_sessions_are_isolated() {
1967 let one = fresh("test-env-one");
1968 let two = fresh("test-env-two");
1969 let _ = run(&one, "export CW_TERM_TEST=present", Duration::from_secs(3));
1970 assert!(
1971 run(&one, "printf %s $CW_TERM_TEST", Duration::from_secs(3))
1972 .content
1973 .contains("present")
1974 );
1975 assert!(
1976 !run(
1977 &two,
1978 "printf %s ${CW_TERM_TEST-unset}",
1979 Duration::from_secs(3)
1980 )
1981 .content
1982 .contains("present")
1983 );
1984 }
1985
1986 #[test]
1987 #[cfg(unix)]
1988 fn reset_replaces_shell_environment() {
1989 let session = fresh("test-reset");
1990 let _ = run(
1991 &session,
1992 "export CW_TERM_RESET=present",
1993 Duration::from_secs(3),
1994 );
1995 assert!(
1996 run(&session, "printf %s $CW_TERM_RESET", Duration::from_secs(3))
1997 .content
1998 .contains("present")
1999 );
2000 let _ = session.lock().unwrap().child.kill();
2001 let replacement = create_session(
2002 OWNER,
2003 "test-reset",
2004 std::path::Path::new("/tmp"),
2005 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2006 &test_shell_manager(),
2007 )
2008 .unwrap();
2009 replace_registered(
2010 session_key(OWNER, "test-reset", Path::new("/tmp")),
2011 &replacement,
2012 )
2013 .unwrap();
2014 assert!(
2015 !run(
2016 &replacement,
2017 "printf %s ${CW_TERM_RESET-unset}",
2018 Duration::from_secs(3)
2019 )
2020 .content
2021 .contains("present")
2022 );
2023 }
2024
2025 #[test]
2026 #[cfg(unix)]
2027 fn timeout_leaves_session_alive() {
2028 let session = fresh("test-timeout");
2029 let result = run(
2030 &session,
2031 "printf before; sleep 2",
2032 Duration::from_millis(100),
2033 );
2034 assert_eq!(result.metadata.as_ref().unwrap()["status"], "timed_out");
2035 let result = {
2036 let mut session_guard = session.lock().unwrap();
2037 let (done, timed_out) = wait_session(&mut session_guard, Duration::from_secs(3));
2038 session_result(&mut session_guard, done, timed_out)
2039 };
2040 assert_eq!(result.metadata.as_ref().unwrap()["status"], "completed");
2041 let result = run(&session, "printf after", Duration::from_secs(3));
2042 assert!(result.content.contains("after"));
2043 }
2044
2045 #[test]
2046 #[cfg(unix)]
2047 fn cancel_interrupts_sleep_and_session_survives() {
2048 let session = fresh("test-cancel");
2049 // Prove the interactive shell is initialized before interrupting it.
2050 // A SIGINT delivered while `sh -i` is still starting can kill the
2051 // shell itself, which later surfaces as EIO on the next PTY write
2052 // (hosted macOS run 34716492759 under load).
2053 assert!(
2054 run(&session, "printf ready", Duration::from_secs(10))
2055 .content
2056 .contains("ready")
2057 );
2058 let worker = Arc::clone(&session);
2059 {
2060 let mut guard = worker.lock().unwrap();
2061 // The quoted split keeps the marker out of the echoed command
2062 // line, so seeing it proves the shell reached this command.
2063 start_command(&mut guard, "printf 'st''arted'; sleep 10").unwrap();
2064 }
2065 let deadline = Instant::now() + Duration::from_secs(10);
2066 loop {
2067 let started = output_snapshot(&session.lock().unwrap()).contains("started");
2068 if started {
2069 break;
2070 }
2071 assert!(
2072 Instant::now() < deadline,
2073 "shell never reached the sleep command"
2074 );
2075 std::thread::sleep(Duration::from_millis(25));
2076 }
2077 let handle = std::thread::spawn(move || {
2078 let (done, timed_out) = wait_shared_session(&worker, Duration::from_secs(30)).unwrap();
2079 let mut guard = worker.lock().unwrap();
2080 session_result(&mut guard, done, timed_out)
2081 });
2082 std::thread::sleep(Duration::from_millis(150));
2083 let done = cancel_shared_session(&session).unwrap();
2084 let result = handle.join().unwrap();
2085 assert_eq!(done.0, 130);
2086 assert_eq!(result.metadata.as_ref().unwrap()["exit_code"], 130);
2087 assert!(
2088 run(&session, "printf alive", Duration::from_secs(3))
2089 .content
2090 .contains("alive")
2091 );
2092 }
2093
2094 #[test]
2095 fn narrowed_posture_without_a_backend_fails_closed() {
2096 assert!(pty_lacks_required_sandbox(
2097 &codewhale_sandbox::SandboxPolicy::read_only(),
2098 codewhale_sandbox::SandboxType::None,
2099 ));
2100 assert!(!pty_lacks_required_sandbox(
2101 &codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2102 codewhale_sandbox::SandboxType::None,
2103 ));
2104 }
2105
2106 #[test]
2107 fn full_access_prepares_an_unsandboxed_pty() {
2108 let (prepared, confined) = prepare_pty_shell(
2109 "/bin/sh",
2110 Path::new("/tmp"),
2111 Path::new("/tmp"),
2112 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2113 &test_shell_manager(),
2114 )
2115 .expect("full access may start a PTY");
2116 assert!(!confined);
2117 assert_eq!(prepared.command[0], "/bin/sh");
2118 assert_eq!(prepared.command[1], "-i");
2119 }
2120
2121 #[test]
2122 #[cfg(unix)]
2123 fn session_names_are_scoped_to_owner_and_workspace() {
2124 let first_workspace = DockWorkspace::new();
2125 let second_workspace = DockWorkspace::new();
2126 let first = first_workspace.session("shared-name");
2127 let second = second_workspace.session("shared-name");
2128 let other_owner = get_or_create(
2129 "another-thread",
2130 "shared-name",
2131 first_workspace.path(),
2132 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2133 &test_shell_manager(),
2134 )
2135 .unwrap();
2136 assert!(!Arc::ptr_eq(&first, &second));
2137 assert!(!Arc::ptr_eq(&first, &other_owner));
2138 assert!(find(OWNER, "shared-name", first_workspace.path()).is_ok());
2139 assert!(find(OWNER, "shared-name", second_workspace.path()).is_ok());
2140 assert!(find(OWNER, "shared-name", Path::new("/tmp")).is_err());
2141 let other_id = other_owner.lock().unwrap().durable.session_id.clone();
2142 assert!(lookup(first_workspace.path(), Some("another-thread"), &other_id).is_some());
2143 assert!(lookup(first_workspace.path(), Some(OWNER), &other_id).is_none());
2144 assert!(lookup(second_workspace.path(), None, &other_id).is_none());
2145 }
2146
2147 #[test]
2148 fn dock_snapshot_scopes_identities_and_leaves_the_model_cursor_untouched() {
2149 let one = DockWorkspace::new();
2150 let two = DockWorkspace::new();
2151 let first = one.session("shared-name");
2152 let second = two.session("shared-name");
2153 let first_id = first.lock().unwrap().durable.session_id.clone();
2154 let second_id = second.lock().unwrap().durable.session_id.clone();
2155 // Stop the output producer before seeding a deterministic retained tail.
2156 // This verifies the dock projection independently of shell throughput.
2157 {
2158 let mut session = first.lock().unwrap();
2159 session.child.kill().unwrap();
2160 session.child.wait().unwrap();
2161 session.read_cursor = 23;
2162 // The detached PTY reader may still drain its final bytes; give
2163 // this projection fixture an independent buffer after reaping.
2164 session.output = Arc::new(Mutex::new(OutputBuffer::default()));
2165 let mut output = session.output.lock().unwrap();
2166 output.append(&vec![b'x'; BUFFER_LIMIT + 41]);
2167 output.append(b"dock-tail-proof");
2168 }
2169 let (entries, output) = inspect_workspace(one.path(), Some(&first_id)).unwrap();
2170 assert_eq!(entries.len(), 1);
2171 assert_eq!(entries[0].id, first_id);
2172 assert!(entries[0].last_activity.is_some());
2173 let output = output.unwrap();
2174 assert_eq!(output.bytes.len(), READ_LIMIT);
2175 assert_eq!(output.offset, output.total - READ_LIMIT as u64);
2176 assert!(output.bytes.ends_with(b"dock-tail-proof"));
2177 assert!(output.dropped > 0);
2178 assert_eq!(first.lock().unwrap().read_cursor, 23);
2179 // A foreign UUID never chooses a same-named local shell or falls back.
2180 let (entries, output) = inspect_workspace(one.path(), Some(&second_id)).unwrap();
2181 assert_eq!(entries.len(), 1);
2182 assert!(output.is_none());
2183 let error = write_dock_input(
2184 two.path(),
2185 "shared-name",
2186 &first_id,
2187 b"printf wrong-workspace\n",
2188 &codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2189 )
2190 .unwrap_err();
2191 assert!(error.contains("reset"), "{error}");
2192 }
2193
2194 #[test]
2195 fn dock_never_attaches_to_a_reset_name_without_selecting_its_new_identity() {
2196 let workspace = DockWorkspace::new();
2197 let old = workspace.session("replaceable");
2198 let old_id = old.lock().unwrap().durable.session_id.clone();
2199 {
2200 let mut old = old.lock().unwrap();
2201 old.child.kill().unwrap();
2202 old.child.wait().unwrap();
2203 }
2204 let replacement = create_session(
2205 OWNER,
2206 "replaceable",
2207 workspace.path(),
2208 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2209 &test_shell_manager(),
2210 )
2211 .unwrap();
2212 let new_id = replace_registered(
2213 session_key(OWNER, "replaceable", workspace.path()),
2214 &replacement,
2215 )
2216 .unwrap();
2217 let (entries, output) = inspect_workspace(workspace.path(), Some(&old_id)).unwrap();
2218 assert_eq!(entries[0].id, new_id);
2219 assert!(output.is_none());
2220 let error = write_dock_input(
2221 workspace.path(),
2222 "replaceable",
2223 &old_id,
2224 b"touch stale-input-must-not-run\n",
2225 &codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2226 )
2227 .unwrap_err();
2228 assert!(
2229 error.contains("select its replacement explicitly"),
2230 "{error}"
2231 );
2232 assert!(resize_dock_session(workspace.path(), "replaceable", &old_id, 40, 80).is_err());
2233 assert!(!workspace.path().join("stale-input-must-not-run").exists());
2234 // Refusal preserves the replacement and its environment instead of
2235 // silently resetting it to recover from the stale selection.
2236 assert_eq!(
2237 find(OWNER, "replaceable", workspace.path())
2238 .unwrap()
2239 .lock()
2240 .unwrap()
2241 .durable
2242 .session_id,
2243 new_id
2244 );
2245 }
2246
2247 #[test]
2248 fn dock_and_model_reuse_refuse_changed_restricted_policies() {
2249 use codewhale_sandbox::SandboxPolicy;
2250 let workspace = DockWorkspace::new();
2251 let shell = workspace.session("posture");
2252 let id = shell.lock().unwrap().durable.session_id.clone();
2253 let narrowed = SandboxPolicy::read_only();
2254 assert!(
2255 get_or_create(
2256 OWNER,
2257 "posture",
2258 workspace.path(),
2259 narrowed.clone(),
2260 &test_shell_manager()
2261 )
2262 .is_err()
2263 );
2264 assert!(write_dock_input(workspace.path(), "posture", &id, b"x", &narrowed).is_err());
2265
2266 // The process creation boundary is tested separately against real
2267 // sandbox backends. Seed its recorded policy here so this regression
2268 // stays portable even on hosts without seatbelt/bwrap.
2269 let original = SandboxPolicy::workspace_with_roots(
2270 vec![workspace.path().join("extra-write-root")],
2271 true,
2272 );
2273 {
2274 let mut shell = shell.lock().unwrap();
2275 shell.sandbox_confined = true;
2276 shell.sandbox_policy = original.clone();
2277 }
2278 let changed = [
2279 SandboxPolicy::read_only(),
2280 SandboxPolicy::workspace_with_roots(vec![], true),
2281 SandboxPolicy::workspace_with_roots(
2282 vec![workspace.path().join("extra-write-root")],
2283 false,
2284 ),
2285 ];
2286 for policy in changed {
2287 assert!(
2288 get_or_create(
2289 OWNER,
2290 "posture",
2291 workspace.path(),
2292 policy.clone(),
2293 &test_shell_manager()
2294 )
2295 .is_err()
2296 );
2297 assert!(write_dock_input(workspace.path(), "posture", &id, b"x", &policy).is_err());
2298 }
2299 assert!(Arc::ptr_eq(
2300 &get_or_create(
2301 OWNER,
2302 "posture",
2303 workspace.path(),
2304 original,
2305 &test_shell_manager()
2306 )
2307 .unwrap(),
2308 &shell
2309 ));
2310 assert_eq!(shell.lock().unwrap().durable.session_id, id);
2311 }
2312
2313 #[test]
2314 fn dock_input_refuses_an_exited_shell() {
2315 let workspace = DockWorkspace::new();
2316 let shell = workspace.session("exited");
2317 let id = {
2318 let mut shell = shell.lock().unwrap();
2319 let id = shell.durable.session_id.clone();
2320 shell.child.kill().unwrap();
2321 shell.child.wait().unwrap();
2322 id
2323 };
2324 let error = write_dock_input(
2325 workspace.path(),
2326 "exited",
2327 &id,
2328 b"must-not-run\n",
2329 &codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2330 )
2331 .unwrap_err();
2332 assert!(error.contains("has exited"), "{error}");
2333 }
2334
2335 #[test]
2336 fn raw_input_refuses_oversized_canonical_batches_without_touching_pending_read() {
2337 let workspace = DockWorkspace::new();
2338 let shell = workspace.session("paste-guard");
2339 let id = {
2340 let mut shell = shell.lock().unwrap();
2341 start_command(
2342 &mut shell,
2343 "stty icanon; printf 'paste-gu''ard-ready\\n'; IFS= read -r answer; printf 'answer=%s\\n' \"$answer\"",
2344 )
2345 .unwrap();
2346 shell.durable.session_id.clone()
2347 };
2348 let deadline = Instant::now() + Duration::from_secs(10);
2349 while !output_snapshot(&shell.lock().unwrap()).contains("paste-guard-ready") {
2350 assert!(Instant::now() < deadline, "shell did not reach its read");
2351 std::thread::sleep(Duration::from_millis(25));
2352 }
2353 let error = write_raw_input(&shell.lock().unwrap(), &vec![b'x'; 64 * 1024]).unwrap_err();
2354 assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
2355 assert!(error.to_string().contains("no input was sent"));
2356 // The dock must use the same boundary, including its exact lower edge.
2357 let error = write_dock_input(
2358 workspace.path(),
2359 "paste-guard",
2360 &id,
2361 &[b'x'; 1024],
2362 &codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2363 )
2364 .unwrap_err();
2365 assert!(error.contains("no input was sent"), "{error}");
2366 write_dock_input(
2367 workspace.path(),
2368 "paste-guard",
2369 &id,
2370 b"human-answer\n",
2371 &codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2372 )
2373 .unwrap();
2374 let (done, timed_out) = wait_shared_session(&shell, Duration::from_secs(10)).unwrap();
2375 assert!(!timed_out, "refused paste stranded the pending read");
2376 assert_eq!(done.unwrap().0, 0);
2377 let output = output_snapshot(&shell.lock().unwrap());
2378 assert!(output.contains("answer=human-answer"), "{output}");
2379 assert!(
2380 !output.contains("xxxxxxxx"),
2381 "refused input leaked into the PTY"
2382 );
2383 }
2384
2385 #[tokio::test(flavor = "current_thread")]
2386 async fn terminal_send_wait_releases_the_session_for_dock_snapshot_and_input() {
2387 let workspace = DockWorkspace::new();
2388 let shell = workspace.session("send-wait");
2389 let (id, output) = {
2390 let mut shell = shell.lock().unwrap();
2391 start_command(
2392 &mut shell,
2393 "stty icanon echo; printf 'send-wa''it-ready\\n'; IFS= read -r answer; printf 'answer=%s\\n' \"$answer\"",
2394 )
2395 .unwrap();
2396 (shell.durable.session_id.clone(), Arc::clone(&shell.output))
2397 };
2398 let deadline = Instant::now() + Duration::from_secs(10);
2399 while !output.lock().unwrap().text().contains("send-wait-ready") {
2400 assert!(Instant::now() < deadline, "shell did not reach its read");
2401 tokio::time::sleep(Duration::from_millis(25)).await;
2402 }
2403 let context = ToolContext::new(workspace.path());
2404 let send = tokio::spawn(async move {
2405 TerminalSendTool
2406 .execute(
2407 json!({"session":"send-wait", "text":"model-", "wait_ms":3000}),
2408 &context,
2409 )
2410 .await
2411 });
2412 // Observe the PTY reader directly: taking the session mutex here would
2413 // hide the old bug by waiting for terminal_send to finish first.
2414 let deadline = Instant::now() + Duration::from_secs(10);
2415 while !output.lock().unwrap().text().contains("model-") {
2416 assert!(Instant::now() < deadline, "terminal_send did not write");
2417 tokio::time::sleep(Duration::from_millis(25)).await;
2418 }
2419 assert!(
2420 !send.is_finished(),
2421 "terminal_send already finished its wait"
2422 );
2423 let path = workspace.path().to_path_buf();
2424 let mut dock = tokio::task::spawn_blocking(move || {
2425 let snapshot = inspect_workspace(&path, Some(&id))?;
2426 write_dock_input(
2427 &path,
2428 "send-wait",
2429 &id,
2430 b"human\n",
2431 &codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2432 )?;
2433 Ok::<_, String>(snapshot)
2434 });
2435 let quick_dock = tokio::time::timeout(Duration::from_secs(1), &mut dock).await;
2436 let responsive = quick_dock.is_ok() && !send.is_finished();
2437 // Join both workers even on the old lock-held path before asserting,
2438 // so a failed regression cannot leave work using the owned fixture.
2439 let (entries, snapshot) = match quick_dock {
2440 Ok(result) => result,
2441 Err(_) => dock.await,
2442 }
2443 .unwrap()
2444 .unwrap();
2445 let result = send.await.unwrap().unwrap();
2446 assert!(responsive, "terminal_send held the session during wait_ms");
2447 assert_eq!(entries[0].state, DurableTerminalState::Running);
2448 assert!(String::from_utf8_lossy(&snapshot.unwrap().bytes).contains("model-"));
2449 assert!(result.content.contains("answer=model-human"), "{result:?}");
2450 assert_eq!(result.metadata.unwrap()["exit_code"], 0);
2451 }
2452
2453 #[test]
2454 fn interactive_command_keeps_its_completion_marker_out_of_stdin() {
2455 let workspace = DockWorkspace::new();
2456 let shell = workspace.session("interactive");
2457 let id = {
2458 let mut shell = shell.lock().unwrap();
2459 start_command(
2460 &mut shell,
2461 "printf 'ready-for-human\\n'; IFS= read -r answer; printf 'answer=%s\\n' \"$answer\"\n# trailing comment",
2462 )
2463 .unwrap();
2464 shell.durable.session_id.clone()
2465 };
2466 let (done, timed_out) = wait_shared_session(&shell, Duration::from_millis(200)).unwrap();
2467 assert!(timed_out && done.is_none());
2468 write_dock_input(
2469 workspace.path(),
2470 "interactive",
2471 &id,
2472 b"human-answer\n",
2473 &codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2474 )
2475 .unwrap();
2476 let (done, timed_out) = wait_shared_session(&shell, Duration::from_secs(10)).unwrap();
2477 assert!(!timed_out, "interactive command lost its completion marker");
2478 assert_eq!(done.unwrap().0, 0);
2479 assert!(output_snapshot(&shell.lock().unwrap()).contains("answer=human-answer"));
2480 let result = run(
2481 &shell,
2482 "cat <<'CW_EOF'\nheredoc-proof\nCW_EOF\nfalse # preserve status",
2483 Duration::from_secs(10),
2484 );
2485 assert!(result.content.contains("heredoc-proof"));
2486 assert_eq!(result.metadata.unwrap()["exit_code"], 1);
2487 let alias = run(
2488 &shell,
2489 "alias cw_dock_alias='printf alias-proof'\ncw_dock_alias",
2490 Duration::from_secs(10),
2491 );
2492 assert!(alias.content.contains("alias-proof"));
2493 assert_eq!(alias.metadata.unwrap()["exit_code"], 0);
2494 }
2495
2496 #[test]
2497 fn dock_input_can_interrupt_a_command_while_the_model_waits() {
2498 let workspace = DockWorkspace::new();
2499 let shell = workspace.session("waiting");
2500 assert!(
2501 run(&shell, "printf ready", Duration::from_secs(10))
2502 .content
2503 .contains("ready")
2504 );
2505 let id = {
2506 let mut shell = shell.lock().unwrap();
2507 start_command(&mut shell, "printf 'dock-wa''it-ready'; sleep 30").unwrap();
2508 shell.durable.session_id.clone()
2509 };
2510 let deadline = Instant::now() + Duration::from_secs(10);
2511 while !output_snapshot(&shell.lock().unwrap()).contains("dock-wait-ready") {
2512 assert!(Instant::now() < deadline, "shell did not start its command");
2513 std::thread::sleep(Duration::from_millis(25));
2514 }
2515 let waiter_shell = Arc::clone(&shell);
2516 let waiter = std::thread::spawn(move || {
2517 wait_shared_session(&waiter_shell, Duration::from_secs(10)).unwrap()
2518 });
2519 write_dock_input(
2520 workspace.path(),
2521 "waiting",
2522 &id,
2523 &[3],
2524 &codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2525 )
2526 .unwrap();
2527 let (done, timed_out) = waiter.join().unwrap();
2528 assert!(!timed_out, "dock input was blocked behind the model waiter");
2529 assert_eq!(done.unwrap().0, 130);
2530 assert!(
2531 run(&shell, "printf 'still-alive'", Duration::from_secs(3))
2532 .content
2533 .contains("still-alive")
2534 );
2535 }
2536
2537 #[test]
2538 #[cfg(unix)]
2539 fn durable_summary_marks_prior_process_shell_stale_and_preserves_history() {
2540 let workspace = tempfile::tempdir().unwrap();
2541 let canonical_workspace = workspace.path().canonicalize().unwrap();
2542 let name = format!("restart-proof-{}", Uuid::new_v4());
2543 let first = create_session(
2544 OWNER,
2545 &name,
2546 workspace.path(),
2547 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2548 &test_shell_manager(),
2549 )
2550 .unwrap();
2551 let first_record = first.lock().unwrap().durable.clone();
2552 assert_eq!(first_record.state, DurableTerminalState::Idle);
2553 assert_eq!(first_record.last_known_cwd, canonical_workspace);
2554 assert!(!first_record.session_id.is_empty());
2555
2556 // Removing only the process-local registry entry models a restart.
2557 // The durable record remains, but cannot be used to reattach.
2558 sessions()
2559 .lock()
2560 .unwrap()
2561 .remove(&session_key(OWNER, &name, workspace.path()));
2562 let stale = match find(OWNER, &name, workspace.path()) {
2563 Ok(_) => panic!("persisted session must not be reattached"),
2564 Err(error) => error,
2565 };
2566 assert!(stale.contains("stale/lost"), "{stale}");
2567 assert!(stale.contains("start a replacement"), "{stale}");
2568
2569 let replacement = create_session(
2570 OWNER,
2571 &name,
2572 workspace.path(),
2573 codewhale_sandbox::SandboxPolicy::DangerFullAccess,
2574 &test_shell_manager(),
2575 )
2576 .unwrap();
2577 let replacement = replacement.lock().unwrap();
2578 assert_ne!(replacement.durable.session_id, first_record.session_id);
2579 let previous = replacement.durable.previous.as_deref().unwrap();
2580 assert_eq!(previous.session_id, first_record.session_id);
2581 assert_eq!(previous.state, DurableTerminalState::StaleLost);
2582 assert_eq!(previous.last_known_cwd, canonical_workspace);
2583 assert_ne!(replacement.durable.runtime_nonce, "");
2584 }
2585
2586 #[test]
2587 #[cfg(unix)]
2588 fn output_is_capped_with_notice() {
2589 let session = fresh("test-output-cap");
2590 let result = run(&session, "yes x | head -n 100000", Duration::from_secs(3));
2591 let parsed: serde_json::Value = serde_json::from_str(&result.content).unwrap();
2592 let stdout = parsed["stdout"].as_str().unwrap();
2593 assert!(stdout.len() <= OUTPUT_LIMIT + 100);
2594 assert!(stdout.contains("output truncated"));
2595 }
2596
2597 #[test]
2598 #[cfg(unix)]
2599 fn pty_run_strips_wrapper_heredoc_ansi_and_sentinel_into_clean_json() {
2600 let state = CommandState {
2601 id: "deadbeef1234".to_string(),
2602 marker: "__CODEWHALE_TERM_deadbeef1234__".to_string(),
2603 start_marker: "__CODEWHALE_TERM_deadbeef1234__START".to_string(),
2604 };
2605 let raw_zsh = concat!(
2606 "\x1b]2;zsh\x07\x1b[1m\x1b[7m%\x1b[27m\x1b[1m\x1b[0m \r \r",
2607 "user@host CW % \x1b[?2004hprintf '\\n__CODEWHALE_TERM_%s__START\\n' 'deadbeef1234'; ",
2608 ". /dev/fd/9 9<<'__CODEWHALE_TERM_deadbeef1234__SOURCE'; __cw_status=$?; ",
2609 "printf '\\n__CODEWHALE_TERM_%s__:%s:%s\\n' 'deadbeef1234' \"$__cw_status\" \"$PWD\"\x1b[?2004l\r\n",
2610 "heredoc> \x1b[?2004hpwd && echo ok\x1b[?2004l\r\n",
2611 "heredoc> \x1b[?2004h__CODEWHALE_TERM_deadbeef1234__SOURCE\x1b[?2004l\r\n",
2612 "\r\n__CODEWHALE_TERM_deadbeef1234__START\r\n",
2613 "\x1b]0;running\x07\x1b[32m/tmp/work\x1b[0m\r\n",
2614 "col1\t\x1b[1mok\x1b[0m\r\n",
2615 "\r\n__CODEWHALE_TERM_deadbeef1234__:0:/tmp/work\r\n",
2616 "\x1b[1m\x1b[7m%\x1b[27m\x1b[1m\x1b[0m \r \ruser@host CW % \x1b[?2004h"
2617 );
2618 assert_eq!(
2619 parse_completion_marker(raw_zsh, &state.marker),
2620 Some((0, "/tmp/work".to_string()))
2621 );
2622 assert_eq!(strip_zsh_prompt_marks("é\x1b[0m🐳"), "é\x1b[0m🐳");
2623 let cleaned = clean_pty_output(raw_zsh, Some(&state));
2624 assert_eq!(cleaned, "/tmp/work\ncol1\tok\n");
2625 assert!(!cleaned.contains("__CODEWHALE_TERM_"));
2626 assert!(!cleaned.contains("heredoc>"));
2627 assert!(!cleaned.contains("/dev/fd/9"));
2628 assert!(!cleaned.contains('\x1b'));
2629
2630 let legacy_without_start = concat!(
2631 "user@host % . /dev/fd/9 9<<'__CODEWHALE_TERM_abcd__SOURCE'; __cw_status=$?; printf '\\n__CODEWHALE_TERM_abcd__:%s:%s\\n' \"$__cw_status\" \"$PWD\"\r\n",
2632 "heredoc> pwd && echo ok\r\n",
2633 "heredoc> __CODEWHALE_TERM_abcd__SOURCE\r\n",
2634 "/tmp/work\r\nok\r\n",
2635 "\r\n__CODEWHALE_TERM_abcd__:0:/tmp/work\r\n",
2636 "\x1b[1m\x1b[7m%\x1b[27m\x1b[1m\x1b[0m \r \ruser@host % "
2637 );
2638 assert_eq!(
2639 clean_pty_output(legacy_without_start, None),
2640 "/tmp/work\nok\n"
2641 );
2642
2643 let session = fresh("test-clean-pty-json");
2644 let result = run(
2645 &session,
2646 "pwd && printf 'a\\tok\\n'",
2647 Duration::from_secs(5),
2648 );
2649 assert!(result.success, "{}", result.content);
2650 let parsed: serde_json::Value =
2651 serde_json::from_str(&result.content).expect("structured json content");
2652 assert_eq!(parsed["exit_code"], 0);
2653 assert_eq!(parsed["status"], "completed");
2654 assert_eq!(parsed["session"], "test-clean-pty-json");
2655 assert!(parsed["session_id"].as_str().is_some_and(|s| !s.is_empty()));
2656 let cwd = parsed["cwd"].as_str().expect("cwd");
2657 assert!(!cwd.is_empty());
2658 let stdout = parsed["stdout"].as_str().expect("stdout");
2659 assert!(stdout.contains("a\tok"), "{stdout:?}");
2660 assert!(stdout.contains(cwd), "{stdout:?} vs {cwd:?}");
2661 assert!(!stdout.contains("__CODEWHALE_TERM_"), "{stdout:?}");
2662 assert!(!stdout.contains("/dev/fd/9"), "{stdout:?}");
2663 assert!(!stdout.contains("heredoc>"), "{stdout:?}");
2664 assert!(!stdout.contains('\x1b'), "{stdout:?}");
2665 }
2666
2667 /// The cursor contract the Engine byte stream rides on: offsets are
2668 /// absolute for the life of the PTY, reads never consume, and a cursor the
2669 /// retained window has moved past is reported rather than silently
2670 /// answered from the middle of the stream.
2671 #[test]
2672 #[cfg(unix)]
2673 fn bounded_replay_is_absolute_non_consuming_and_reports_its_gap() {
2674 let mut buffer = OutputBuffer::default();
2675 buffer.append(b"hello");
2676 let first = buffer.read_since(0, 4);
2677 assert_eq!(first.bytes, b"hell");
2678 assert_eq!(first.offset, 0);
2679 assert_eq!(first.next_cursor, 4);
2680 assert_eq!(first.total, 5);
2681 assert_eq!(first.dropped, 0);
2682 assert!(!first.gap);
2683 // A second read at the same cursor returns the same bytes: the caller
2684 // owns the position, so replay is idempotent.
2685 assert_eq!(buffer.read_since(0, 4), first);
2686 let rest = buffer.read_since(first.next_cursor, 4);
2687 assert_eq!(rest.bytes, b"o");
2688 assert_eq!(rest.offset, 4);
2689 assert_eq!(rest.next_cursor, 5);
2690
2691 // Past the ring: the first 32 bytes are gone and the chunk says so.
2692 let mut wrapped = OutputBuffer::default();
2693 wrapped.append(&vec![b'x'; BUFFER_LIMIT + 32]);
2694 let lost = wrapped.read_since(0, 8);
2695 assert!(lost.gap, "a cursor below the retained window is a gap");
2696 assert_eq!(lost.dropped, 32);
2697 assert_eq!(
2698 lost.offset, 32,
2699 "the chunk starts at the oldest retained byte"
2700 );
2701 assert_eq!(lost.total, BUFFER_LIMIT as u64 + 32);
2702 assert_eq!(lost.bytes, vec![b'x'; 8]);
2703 assert_eq!(lost.next_cursor, 40);
2704
2705 // A cursor at the head is not a gap and returns nothing new.
2706 let current = wrapped.read_since(BUFFER_LIMIT as u64 + 32, 8);
2707 assert!(!current.gap);
2708 assert!(current.bytes.is_empty());
2709 assert_eq!(current.next_cursor, BUFFER_LIMIT as u64 + 32);
2710
2711 // A cursor past the head clamps to it instead of being echoed back:
2712 // a client that continues from `next_cursor` must not skip the bytes
2713 // the stream produces before it reaches the bogus position.
2714 let beyond = wrapped.read_since(BUFFER_LIMIT as u64 + 4096, 8);
2715 assert!(!beyond.gap);
2716 assert!(beyond.bytes.is_empty());
2717 assert_eq!(beyond.offset, BUFFER_LIMIT as u64 + 32);
2718 assert_eq!(beyond.next_cursor, BUFFER_LIMIT as u64 + 32);
2719 }
2720
2721 /// The session-level entry point an Engine byte stream will call: absolute
2722 /// cursor, non-consuming, clamped, and honest about a cursor ahead of the
2723 /// stream.
2724 #[test]
2725 #[cfg(unix)]
2726 fn session_read_since_is_non_consuming_and_clamped() {
2727 let session = fresh("test-read-since");
2728 let _ = run(
2729 &session,
2730 "printf 'cw-replay-proof\\n'",
2731 Duration::from_secs(3),
2732 );
2733 // The tool-result path already consumed this output through its own
2734 // cursor; an absolute cursor still reads it, which is the point.
2735 let printed = read_session_since(&session.lock().unwrap(), 0, usize::MAX).unwrap();
2736 assert!(
2737 String::from_utf8_lossy(&printed.bytes).contains("cw-replay-proof"),
2738 "{}",
2739 String::from_utf8_lossy(&printed.bytes)
2740 );
2741 let again = read_session_since(&session.lock().unwrap(), 0, usize::MAX).unwrap();
2742 assert_eq!(again.bytes, printed.bytes, "a replay read must not consume");
2743
2744 // A cursor ahead of the stream is not a gap: nothing was lost, there
2745 // is simply nothing there yet — and the answer clamps to the head so
2746 // continuing from it cannot skip what arrives next.
2747 let ahead =
2748 read_session_since(&session.lock().unwrap(), printed.next_cursor + 4096, 16).unwrap();
2749 assert!(!ahead.gap);
2750 assert!(ahead.bytes.is_empty());
2751 assert_eq!(ahead.next_cursor, ahead.total);
2752
2753 // More than one response's worth of output proves the clamp.
2754 let large = fresh("test-read-since-clamp");
2755 let _ = run(&large, "yes x | head -n 100000", Duration::from_secs(3));
2756 let chunk = read_session_since(&large.lock().unwrap(), 0, usize::MAX).unwrap();
2757 assert_eq!(chunk.bytes.len(), READ_LIMIT);
2758 assert!(!chunk.gap);
2759 assert_eq!(chunk.next_cursor, READ_LIMIT as u64);
2760 }
2761
2762 /// Resize has to reach the kernel, not just a field: `get_size` reads the
2763 /// window back from the pty, and the shell reports it through `stty`.
2764 #[test]
2765 #[cfg(unix)]
2766 fn resize_reaches_the_kernel_and_the_live_shell() {
2767 let session = fresh("test-resize");
2768 {
2769 let guard = session.lock().unwrap();
2770 assert_eq!(guard.master.get_size().unwrap().rows, 24);
2771 }
2772 resize_session(&session.lock().unwrap(), 40, 100).unwrap();
2773 let size = session.lock().unwrap().master.get_size().unwrap();
2774 assert_eq!((size.rows, size.cols), (40, 100));
2775 let result = run(&session, "stty size", Duration::from_secs(3));
2776 assert!(
2777 result.content.contains("40 100"),
2778 "the shell should see the new window: {}",
2779 result.content
2780 );
2781 }
2782
2783 /// Exit is observable: a killed shell reports a status instead of looking
2784 /// alive forever (the "pretending to reattach" failure the durable record
2785 /// is written to avoid).
2786 #[test]
2787 #[cfg(unix)]
2788 fn killed_shell_reports_an_exit_status() {
2789 let session = fresh("test-exit-status");
2790 {
2791 let mut guard = session.lock().unwrap();
2792 assert!(
2793 session_exit_status(&mut guard).unwrap().is_none(),
2794 "fresh shell is alive"
2795 );
2796 kill_session(&mut guard).unwrap();
2797 }
2798 let deadline = Instant::now() + Duration::from_secs(5);
2799 loop {
2800 let exited = session_exit_status(&mut session.lock().unwrap())
2801 .unwrap()
2802 .is_some();
2803 if exited {
2804 break;
2805 }
2806 assert!(
2807 Instant::now() < deadline,
2808 "a killed shell must report its exit"
2809 );
2810 std::thread::sleep(Duration::from_millis(20));
2811 }
2812 }
2813
2814 #[test]
2815 #[cfg(unix)]
2816 fn new_session_does_not_inherit_parent_secret_env() {
2817 use crate::test_support::{EnvVarGuard, lock_test_env};
2818 let _env_lock = lock_test_env();
2819 let _secret = EnvVarGuard::set("CODEWHALE_TEST_PTY_SECRET", "pty-secret-value");
2820 let session = fresh("test-env-scrub");
2821 let result = run(
2822 &session,
2823 "printf 'se''cret=%s ho''me=%s' \"${CODEWHALE_TEST_PTY_SECRET-unset}\" \"${HOME-none}\"",
2824 Duration::from_secs(10),
2825 );
2826 assert!(
2827 !result.content.contains("pty-secret-value"),
2828 "{}",
2829 result.content
2830 );
2831 assert!(
2832 result.content.contains("secret=unset"),
2833 "{}",
2834 result.content
2835 );
2836 let home = std::env::var("HOME").unwrap_or_default();
2837 if !home.is_empty() {
2838 assert!(
2839 result.content.contains(&format!("home={home}")),
2840 "allowlisted variables still reach the shell: {}",
2841 result.content
2842 );
2843 }
2844 }
2845
2846 #[test]
2847 #[cfg(unix)]
2848 fn kill_sessions_named_ends_only_matching_plugin_sessions_and_get_or_create_caps_per_plugin() {
2849 let workspace = DockWorkspace::new();
2850 let path = workspace.path();
2851 let manager = test_shell_manager();
2852 let policy = codewhale_sandbox::SandboxPolicy::DangerFullAccess;
2853 let thread = format!("thread-named-{}", Uuid::new_v4());
2854 let suffix = Uuid::new_v4().simple().to_string();
2855 let plugin_a = format!("plug-a-{suffix}");
2856 let plugin_ab = format!("{plugin_a}b");
2857 let plugin_b = format!("plug-b-{suffix}");
2858
2859 let term1 = get_or_create(&thread, "term-1", path, policy.clone(), &manager).unwrap();
2860 let colliding = get_or_create(
2861 &thread,
2862 &format!("dsh:{plugin_a}:b:x"),
2863 path,
2864 policy.clone(),
2865 &manager,
2866 )
2867 .unwrap();
2868 let other_prefix = get_or_create(
2869 &thread,
2870 &format!("dsh:{plugin_ab}:s0"),
2871 path,
2872 policy.clone(),
2873 &manager,
2874 )
2875 .unwrap();
2876 let other_plugin = get_or_create(
2877 &thread,
2878 &format!("dsh:{plugin_b}:s0"),
2879 path,
2880 policy.clone(),
2881 &manager,
2882 )
2883 .unwrap();
2884
2885 let mut plugin_sessions = Vec::new();
2886 for idx in 0..crate::extension_host::dsh_terminal::MAX_TERMINALS {
2887 let session = get_or_create(
2888 &thread,
2889 &format!("dsh:{plugin_a}:s{idx}"),
2890 path,
2891 policy.clone(),
2892 &manager,
2893 )
2894 .unwrap();
2895 plugin_sessions.push(session);
2896 }
2897 assert!(
2898 get_or_create(
2899 &thread,
2900 &format!("dsh:{plugin_a}:s0"),
2901 path,
2902 policy.clone(),
2903 &manager,
2904 )
2905 .is_ok()
2906 );
2907 assert!(
2908 get_or_create(
2909 &thread,
2910 &format!("dsh:{plugin_a}:overflow"),
2911 path,
2912 policy.clone(),
2913 &manager,
2914 )
2915 .is_err()
2916 );
2917 assert!(get_or_create(&thread, "term-2", path, policy, &manager).is_ok());
2918 {
2919 let mut first = plugin_sessions[0].lock().unwrap();
2920 start_command(&mut first, "sleep 30").unwrap();
2921 }
2922
2923 assert_eq!(kill_sessions_named("").unwrap(), 0);
2924 assert_eq!(kill_sessions_named("dsh::").unwrap(), 0);
2925 assert_eq!(kill_sessions_named("term-").unwrap(), 0);
2926 assert_eq!(
2927 kill_sessions_named(&format!("dsh:{plugin_a}:")).unwrap(),
2928 crate::extension_host::dsh_terminal::MAX_TERMINALS
2929 );
2930
2931 let deadline = Instant::now() + Duration::from_secs(5);
2932 for session in &plugin_sessions {
2933 while session_exit_status(&mut session.lock().unwrap())
2934 .unwrap()
2935 .is_none()
2936 {
2937 assert!(
2938 Instant::now() < deadline,
2939 "killed plugin shell did not exit"
2940 );
2941 std::thread::sleep(Duration::from_millis(20));
2942 }
2943 }
2944 for survivor in [&term1, &colliding, &other_prefix, &other_plugin] {
2945 assert!(
2946 session_exit_status(&mut survivor.lock().unwrap())
2947 .unwrap()
2948 .is_none()
2949 );
2950 }
2951 let remaining: Vec<String> = owned_sessions(path, &thread)
2952 .unwrap()
2953 .into_iter()
2954 .map(|info| info.name)
2955 .collect();
2956 assert!(remaining.contains(&"term-1".to_string()), "{remaining:?}");
2957 assert!(remaining.contains(&"term-2".to_string()), "{remaining:?}");
2958 assert!(
2959 remaining.contains(&format!("dsh:{plugin_a}:b:x")),
2960 "{remaining:?}"
2961 );
2962 assert!(
2963 remaining.contains(&format!("dsh:{plugin_ab}:s0")),
2964 "{remaining:?}"
2965 );
2966 assert!(
2967 remaining.contains(&format!("dsh:{plugin_b}:s0")),
2968 "{remaining:?}"
2969 );
2970 assert!(
2971 !remaining
2972 .iter()
2973 .any(|name| name.starts_with(&format!("dsh:{plugin_a}:s"))),
2974 "{remaining:?}"
2975 );
2976 }
2977 }
2978
2978 lines RUST