返回 CodeWhale
shell.rs
根目录 / crates / engine / src / tools / shell.rs
1 //! Advanced shell execution with background process support and sandboxing.
2 //!
3 //! Provides:
4 //! - Synchronous command execution with timeout
5 //! - Background process execution
6 //! - Process output retrieval
7 //! - Process termination
8 //! - Sandbox support (macOS Seatbelt and opt-in Linux bubblewrap)
9 //! - Streaming output (future)
10
11 use anyhow::{Context, Result, anyhow};
12 use base64::Engine as _;
13 #[cfg(unix)]
14 use codewhale_runtime::process_tree::wait_leader_exit_until;
15 use serde::{Deserialize, Serialize};
16 use std::collections::{HashMap, HashSet};
17 use std::fs::File;
18 use std::io;
19 use std::io::{Read, Write};
20 use std::path::{Path, PathBuf};
21 use std::process::{Child, ChildStdin, Command, Stdio};
22 use std::sync::atomic::{AtomicBool, Ordering};
23 use std::sync::{Arc, Mutex, Weak};
24 use std::time::{Duration, Instant};
25 use uuid::Uuid;
26 use wait_timeout::ChildExt;
27
28 #[cfg(unix)]
29 use std::os::fd::FromRawFd;
30 #[cfg(unix)]
31 use std::os::unix::process::CommandExt;
32 #[cfg(windows)]
33 use std::os::windows::io::AsRawHandle;
34 #[cfg(windows)]
35 use std::os::windows::io::FromRawHandle;
36 #[cfg(windows)]
37 use windows::Win32::Foundation::{CloseHandle, HANDLE};
38 #[cfg(windows)]
39 use windows::Win32::System::JobObjects::{
40 AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
41 JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
42 SetInformationJobObject, TerminateJobObject,
43 };
44 #[cfg(windows)]
45 use windows::core::PCWSTR;
46
47 #[cfg(not(target_env = "ohos"))]
48 use portable_pty::{PtySize, native_pty_system};
49
50 mod guidance;
51 mod output;
52
53 use super::shell_output::{
54 kill_outcome_note, output_phase_hint, summarize_output, truncate_with_meta,
55 };
56 use crate::tools::resource_admission::{
57 CommandExpense, HeavyCommandPermit, MemoryPressure, acquire_heavy_command_permit,
58 infer_command_expense,
59 };
60 use crate::work_graph::{
61 EvidenceKind, EvidenceRef, OperationIntent, OperationOwnerSnapshot, OwnerState,
62 SharedWorkRuntime,
63 };
64 use codewhale_agent_contract::worker_profile::ShellPolicy;
65 use codewhale_runtime::child_env;
66 use codewhale_sandbox::{
67 CommandSpec, ExecEnv, SandboxManager, SandboxPolicy as ExecutionSandboxPolicy, SandboxType,
68 };
69 #[cfg(any(test, feature = "test-support"))]
70 use output::new_shared_raw_output;
71 use output::{
72 BoundedOutputAccumulator, BoundedOutputSnapshot, PersistedShellArtifact, RAW_STREAM_MAX_BYTES,
73 RAW_STREAM_SETTLED_TAIL_BYTES, RawOutputBuffer, SessionArtifactSpec, SharedRawOutput,
74 persist_shell_output_artifact, tail_from_buffer, tail_text, take_delta_from_buffer,
75 };
76
77 const READONLY_ENV_MARKER: &str = "CODEWHALE_INTERNAL_READONLY_ARGV";
78 const GIT_HARDENING_ENV_MARKER: &str = "CODEWHALE_INTERNAL_GIT_HARDENING";
79
80 #[derive(Clone, Copy)]
81 pub(super) enum ReadonlyCommandHardening<'a> {
82 None,
83 StrictReadOnly(&'a std::path::Path),
84 GitReadOnlyIfAdmitted {
85 workspace: &'a std::path::Path,
86 require_native_sandbox: bool,
87 },
88 }
89 pub const AGENT_PROJECT_ENV: &str = "CODEWHALE_AGENT_PROJECT";
90 pub const AGENT_POSTURE_ENV: &str = "CODEWHALE_AGENT_POSTURE";
91 pub const AGENT_THREAD_ID_ENV: &str = "CODEWHALE_AGENT_THREAD_ID";
92 pub const AGENT_TURN_ID_ENV: &str = "CODEWHALE_AGENT_TURN_ID";
93 pub const AGENT_TOOL_CALL_ID_ENV: &str = "CODEWHALE_AGENT_TOOL_CALL_ID";
94
95 pub fn insert_agent_mark_env(
96 env: &mut std::collections::HashMap<String, String>,
97 context: &ToolContext,
98 ) {
99 env.insert(
100 AGENT_PROJECT_ENV.to_string(),
101 context.workspace.to_string_lossy().into_owned(),
102 );
103 if context.approval_mode == codewhale_execpolicy::ApprovalMode::Auto {
104 env.insert(AGENT_POSTURE_ENV.to_string(), "auto_review".to_string());
105 let thread_id = context.state_namespace.trim();
106 if !thread_id.is_empty() {
107 env.insert(AGENT_THREAD_ID_ENV.to_string(), thread_id.to_string());
108 }
109 if let Some(turn_id) = context
110 .origin_turn_id
111 .as_deref()
112 .map(str::trim)
113 .filter(|id| !id.is_empty())
114 {
115 env.insert(AGENT_TURN_ID_ENV.to_string(), turn_id.to_string());
116 }
117 if let Some(tool_call_id) = context
118 .origin_tool_call_id
119 .as_deref()
120 .map(str::trim)
121 .filter(|id| !id.is_empty())
122 {
123 env.insert(AGENT_TOOL_CALL_ID_ENV.to_string(), tool_call_id.to_string());
124 }
125 }
126 }
127
128 #[cfg(unix)]
129 static PENDING_PERSISTENT_PROCESS_GROUPS: std::sync::OnceLock<
130 Mutex<std::collections::HashSet<u32>>,
131 > = std::sync::OnceLock::new();
132
133 #[cfg(unix)]
134 fn pending_persistent_process_groups() -> &'static Mutex<std::collections::HashSet<u32>> {
135 PENDING_PERSISTENT_PROCESS_GROUPS.get_or_init(|| Mutex::new(std::collections::HashSet::new()))
136 }
137
138 #[cfg(unix)]
139 fn register_pending_persistent_process_group(process_group_id: u32) {
140 let mut groups = pending_persistent_process_groups()
141 .lock()
142 .unwrap_or_else(std::sync::PoisonError::into_inner);
143 groups.insert(process_group_id);
144 }
145
146 #[cfg(unix)]
147 fn unregister_pending_persistent_process_group(process_group_id: u32) {
148 let mut groups = pending_persistent_process_groups()
149 .lock()
150 .unwrap_or_else(std::sync::PoisonError::into_inner);
151 groups.remove(&process_group_id);
152 }
153
154 /// Kill services that were staged for ownership transfer but have not yet
155 /// been released. The process-wide signal path calls this immediately before
156 /// `process::exit`, where Rust destructors cannot run.
157 #[cfg(unix)]
158 pub fn abort_pending_persistent_process_groups_for_exit() {
159 let groups = {
160 let mut groups = pending_persistent_process_groups()
161 .lock()
162 .unwrap_or_else(std::sync::PoisonError::into_inner);
163 groups.drain().collect::<Vec<_>>()
164 };
165 for process_group_id in groups {
166 if let Ok(process_group_id) = i32::try_from(process_group_id) {
167 // SAFETY: the id was captured from a child spawned with
168 // `process_group(0)`. A negative pid targets that child's process
169 // group, never Codewhale's own group.
170 unsafe {
171 libc::kill(-process_group_id, libc::SIGKILL);
172 }
173 }
174 }
175 }
176
177 fn validate_shell_working_dir(path: &Path, inherited_session_workspace: bool) -> Result<()> {
178 let metadata = std::fs::metadata(path).with_context(|| {
179 let source = if inherited_session_workspace {
180 "saved session workspace"
181 } else {
182 "requested working directory"
183 };
184 format!(
185 "{source} is unavailable: {}. Restore or remap that directory, resume/fork the session from an existing workspace, or pass an explicit `cwd` to `bash`",
186 path.display()
187 )
188 })?;
189 if !metadata.is_dir() {
190 let source = if inherited_session_workspace {
191 "saved session workspace"
192 } else {
193 "requested working directory"
194 };
195 return Err(anyhow!(
196 "{source} is not a directory: {}. Resume/fork from an existing workspace or pass an explicit `cwd` to `bash`",
197 path.display()
198 ));
199 }
200 Ok(())
201 }
202
203 #[derive(Debug, thiserror::Error)]
204 #[error("shell launch did not start")]
205 pub struct ShellLaunchNotStarted;
206
207 /// Status of a shell process.
208 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
209 pub enum ShellStatus {
210 Running,
211 Completed,
212 Failed,
213 Killed,
214 TimedOut,
215 }
216
217 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
218 #[serde(rename_all = "snake_case")]
219 pub enum ShellTerminationCause {
220 Producer,
221 Killed,
222 TimedOut,
223 Unknown,
224 }
225
226 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
227 #[serde(rename_all = "snake_case")]
228 pub enum ShellJobStopReason {
229 OwnerLost,
230 Deadline,
231 }
232
233 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
234 pub struct ShellJobHold {
235 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub owner_keepalive_seconds: Option<u64>,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
238 pub keepalive_expires_at: Option<chrono::DateTime<chrono::Utc>>,
239 #[serde(default, skip_serializing_if = "Option::is_none")]
240 pub deadline_at: Option<chrono::DateTime<chrono::Utc>>,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub stop_reason: Option<ShellJobStopReason>,
243 }
244
245 #[derive(Debug, thiserror::Error, PartialEq, Eq)]
246 pub enum ShellHoldError {
247 #[error("job not found")]
248 NotFound,
249 #[error("job is not running")]
250 NotRunning,
251 #[error("job has no owner keepalive")]
252 NotHeld,
253 #[error("job owner keepalive expired")]
254 Expired,
255 }
256
257 #[derive(Debug, Clone)]
258 struct JobHoldState {
259 keepalive: Option<Duration>,
260 keepalive_until: Option<Instant>,
261 deadline_at: Option<chrono::DateTime<chrono::Utc>>,
262 stop_reason: Option<ShellJobStopReason>,
263 }
264
265 impl JobHoldState {
266 fn expired(
267 &self,
268 now: Instant,
269 now_utc: chrono::DateTime<chrono::Utc>,
270 ) -> Option<ShellJobStopReason> {
271 if self.deadline_at.is_some_and(|deadline| now_utc >= deadline) {
272 Some(ShellJobStopReason::Deadline)
273 } else if self.keepalive_until.is_some_and(|until| now >= until) {
274 Some(ShellJobStopReason::OwnerLost)
275 } else {
276 None
277 }
278 }
279
280 fn view(&self) -> ShellJobHold {
281 let now = Instant::now();
282 ShellJobHold {
283 owner_keepalive_seconds: self.keepalive.map(|keepalive| keepalive.as_secs()),
284 keepalive_expires_at: self.keepalive_until.and_then(|until| {
285 chrono::Duration::from_std(until.saturating_duration_since(now))
286 .ok()
287 .map(|left| chrono::Utc::now() + left)
288 }),
289 deadline_at: self.deadline_at,
290 stop_reason: self.stop_reason,
291 }
292 }
293 }
294
295 #[derive(Debug, Clone)]
296 pub struct ShellRunningJob {
297 pub job_id: String,
298 pub background: bool,
299 pub last_progress_at: chrono::DateTime<chrono::Utc>,
300 pub hold: Option<ShellJobHold>,
301 }
302
303 /// Result from a shell command execution.
304 #[derive(Debug, Clone, Serialize, Deserialize)]
305 pub struct ShellResult {
306 pub task_id: Option<String>,
307 pub status: ShellStatus,
308 /// Lossless process exit status. Windows exception/NTSTATUS values use
309 /// the full unsigned 32-bit range, so an i32 would corrupt them.
310 pub exit_code: Option<i64>,
311 pub stdout: String,
312 pub stderr: String,
313 pub duration_ms: u64,
314 /// Original stdout length in bytes.
315 #[serde(default)]
316 pub stdout_len: usize,
317 /// Original stderr length in bytes.
318 #[serde(default)]
319 pub stderr_len: usize,
320 /// Bytes omitted from stdout due to truncation.
321 #[serde(default)]
322 pub stdout_omitted: usize,
323 /// Bytes omitted from stderr due to truncation.
324 #[serde(default)]
325 pub stderr_omitted: usize,
326 /// Whether stdout was truncated.
327 #[serde(default)]
328 pub stdout_truncated: bool,
329 /// Whether stderr was truncated.
330 #[serde(default)]
331 pub stderr_truncated: bool,
332 /// Whether the command was executed in a sandbox.
333 #[serde(default)]
334 pub sandboxed: bool,
335 /// Type of sandbox used (if any).
336 #[serde(skip_serializing_if = "Option::is_none")]
337 pub sandbox_type: Option<String>,
338 /// Whether the command was blocked by sandbox restrictions.
339 #[serde(default)]
340 pub sandbox_denied: bool,
341 }
342
343 /// Compact, UI-oriented view of a tracked background shell job.
344 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
345 pub struct ShellJobSnapshot {
346 pub id: String,
347 pub job_id: String,
348 pub command: String,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
350 pub description: Option<String>,
351 pub cwd: PathBuf,
352 pub status: ShellStatus,
353 /// Explicitly backgrounded or detached from the foreground waiter.
354 #[serde(default)]
355 pub background: bool,
356 #[serde(default, skip_serializing_if = "Option::is_none")]
357 pub started_at: Option<chrono::DateTime<chrono::Utc>>,
358 /// First observed terminal time; legacy snapshots cannot trigger notices.
359 #[serde(default, skip_serializing_if = "Option::is_none")]
360 pub finished_at: Option<chrono::DateTime<chrono::Utc>>,
361 #[serde(default, skip_serializing_if = "Option::is_none")]
362 pub cause: Option<ShellTerminationCause>,
363 #[serde(default)]
364 pub producer_reported: bool,
365 pub exit_code: Option<i64>,
366 pub elapsed_ms: u64,
367 pub stdout_tail: String,
368 pub stderr_tail: String,
369 pub stdout_len: usize,
370 pub stderr_len: usize,
371 pub stdin_available: bool,
372 pub stale: bool,
373 #[serde(default, skip_serializing_if = "Option::is_none")]
374 pub elapsed_since_output_ms: Option<u64>,
375 pub linked_task_id: Option<String>,
376 #[serde(default, skip_serializing_if = "Option::is_none")]
377 pub owner_agent_id: Option<String>,
378 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pub owner_agent_name: Option<String>,
380 #[serde(default, skip_serializing_if = "Option::is_none")]
381 pub origin_tool_call_id: Option<String>,
382 #[serde(default, skip_serializing_if = "Option::is_none")]
383 pub origin_turn_id: Option<String>,
384 /// Immutable root session that launched the job. Empty legacy records are
385 /// intentionally hidden from session-scoped completion drains.
386 #[serde(default, skip_serializing_if = "String::is_empty")]
387 pub owner_session_id: String,
388 }
389
390 #[derive(Debug, Clone)]
391 pub struct ShellReceiptWitness {
392 pub cwd: PathBuf,
393 pub status: ShellStatus,
394 pub exit_code: Option<i64>,
395 pub owner_session_id: String,
396 pub wait_failed: bool,
397 pub terminal_confirmed: bool,
398 pub stop_reason: Option<ShellJobStopReason>,
399 }
400
401 impl ShellReceiptWitness {
402 fn from_shell(shell: &mut BackgroundShell) -> Self {
403 let terminal_confirmed = shell.status != ShellStatus::Running
404 && !shell.wait_failed
405 && shell.terminal_exit_confirmed;
406 Self {
407 cwd: shell.working_dir.clone(),
408 status: shell.status.clone(),
409 exit_code: shell.exit_code,
410 owner_session_id: shell.owner_session_id.clone(),
411 wait_failed: shell.wait_failed,
412 terminal_confirmed,
413 stop_reason: shell.hold.as_ref().and_then(|hold| hold.stop_reason),
414 }
415 }
416 }
417
418 /// Once-only completion event for a tracked background shell job.
419 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
420 pub struct ShellCompletionEvent {
421 pub task_id: String,
422 pub command: String,
423 pub status: ShellStatus,
424 #[serde(default, skip_serializing_if = "Option::is_none")]
425 pub started_at: Option<chrono::DateTime<chrono::Utc>>,
426 #[serde(default, skip_serializing_if = "Option::is_none")]
427 pub cause: Option<ShellTerminationCause>,
428 #[serde(default)]
429 pub producer_reported: bool,
430 pub exit_code: Option<i64>,
431 pub duration_ms: u64,
432 pub stdout_tail: String,
433 pub stderr_tail: String,
434 #[serde(default)]
435 pub stdout_len: usize,
436 #[serde(default)]
437 pub stderr_len: usize,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
439 pub evidence_ref: Option<String>,
440 pub linked_task_id: Option<String>,
441 #[serde(default, skip_serializing_if = "Option::is_none")]
442 pub owner_agent_id: Option<String>,
443 #[serde(default, skip_serializing_if = "Option::is_none")]
444 pub owner_agent_name: Option<String>,
445 #[serde(default, skip_serializing_if = "Option::is_none")]
446 pub origin_tool_call_id: Option<String>,
447 #[serde(default, skip_serializing_if = "Option::is_none")]
448 pub origin_turn_id: Option<String>,
449 #[serde(default, skip_serializing_if = "String::is_empty")]
450 pub owner_session_id: String,
451 }
452
453 /// Byte evidence captured alongside a bounded completion event. Exact unless
454 /// the stream exceeded the in-memory retention ceiling, in which case the
455 /// omission is declared per stream rather than presented as complete.
456 #[derive(Debug, Clone)]
457 pub struct ShellCompletionEvidence {
458 pub event: ShellCompletionEvent,
459 stdout: Vec<u8>,
460 stderr: Vec<u8>,
461 stdout_omitted: usize,
462 stderr_omitted: usize,
463 persisted_artifact: Option<PersistedShellArtifact>,
464 }
465
466 impl ShellCompletionEvidence {
467 /// Encode each stream losslessly. UTF-8 remains readable; arbitrary bytes
468 /// use base64 so `retrieve_tool_result` can still recover exact output.
469 pub fn artifact_bytes(&self) -> Vec<u8> {
470 fn stream(bytes: &[u8], omitted: usize) -> serde_json::Value {
471 let mut value = match std::str::from_utf8(bytes) {
472 Ok(content) => serde_json::json!({
473 "encoding": "utf-8",
474 "byte_length": bytes.len(),
475 "content": content,
476 }),
477 Err(_) => serde_json::json!({
478 "encoding": "base64",
479 "byte_length": bytes.len(),
480 "content": base64::engine::general_purpose::STANDARD.encode(bytes),
481 }),
482 };
483 // Additive and only present when something was actually dropped, so
484 // the common case stays byte-identical to the v1 artifact readers
485 // already parse.
486 if omitted > 0
487 && let Some(object) = value.as_object_mut()
488 {
489 object.insert("leading_bytes_omitted".into(), omitted.into());
490 object.insert(
491 "total_byte_length".into(),
492 bytes.len().saturating_add(omitted).into(),
493 );
494 }
495 value
496 }
497
498 let mut payload = serde_json::json!({
499 "schema": "codewhale.shell_completion.evidence.v1",
500 "task_id": self.event.task_id,
501 "command": self.event.command,
502 "status": format!("{:?}", self.event.status),
503 "exit_code": self.event.exit_code,
504 "duration_ms": self.event.duration_ms,
505 "origin_tool_call_id": self.event.origin_tool_call_id,
506 "origin_turn_id": self.event.origin_turn_id,
507 "stdout": stream(&self.stdout, self.stdout_omitted),
508 "stderr": stream(&self.stderr, self.stderr_omitted),
509 });
510 if let Some(artifact) = self.persisted_artifact.as_ref() {
511 stamp_persisted_shell_artifact_metadata(
512 &mut payload["stdout"],
513 artifact,
514 &self.event.stdout_tail,
515 );
516 }
517 payload.to_string().into_bytes()
518 }
519
520 pub fn needs_evidence_artifact(&self) -> bool {
521 self.stdout_omitted > 0
522 || self.stderr_omitted > 0
523 || self.event.stdout_len > SHELL_COMPLETION_TAIL_BYTES
524 || self.event.stderr_len > SHELL_COMPLETION_TAIL_BYTES
525 || self.event.stdout_tail.as_bytes() != self.stdout.as_slice()
526 || self.event.stderr_tail.as_bytes() != self.stderr.as_slice()
527 }
528 }
529
530 // Keep the two inline streams at a 2 KiB combined hard ceiling. The durable
531 // artifact carries the exact bytes beyond these diagnostic tails.
532 const SHELL_COMPLETION_TAIL_BYTES: usize = 1_024;
533
534 /// How long a finished shell record stays listed in `/jobs`.
535 const FINISHED_SHELL_MAX_AGE: Duration = Duration::from_secs(3600);
536 /// Ceiling on finished records kept for the jobs panel. A long automation run
537 /// makes hundreds of `Bash` calls per hour; the panel is only useful for the
538 /// recent ones (#5472).
539 const MAX_FINISHED_SHELL_RECORDS: usize = 128;
540 /// Ceiling on bytes still held across all finished records. Each settled record
541 /// releases down to a 64 KiB tail, so this only binds when many large outputs
542 /// finish inside the same window.
543 const MAX_FINISHED_SHELL_BYTES: usize = 8 * 1024 * 1024;
544
545 fn bounded_completion_tail(buffer: &SharedRawOutput, max_bytes: usize) -> (usize, String) {
546 let (total, candidate) = tail_from_buffer(buffer, max_bytes);
547 if candidate.len() <= max_bytes {
548 return (total, candidate);
549 }
550 let content_budget = max_bytes.saturating_sub(3);
551 let mut start = candidate.len().saturating_sub(content_budget);
552 while start < candidate.len() && !candidate.is_char_boundary(start) {
553 start += 1;
554 }
555 (total, format!("...{}", &candidate[start..]))
556 }
557
558 /// Optional owner attribution for background shell work.
559 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
560 pub struct ShellJobOwner {
561 pub agent_id: String,
562 pub agent_name: String,
563 }
564
565 /// Full output view used by `/jobs show <id>`.
566 #[derive(Debug, Clone, Serialize, Deserialize)]
567 pub struct ShellJobDetail {
568 pub snapshot: ShellJobSnapshot,
569 pub stdout: String,
570 pub stderr: String,
571 }
572
573 pub struct ShellDeltaResult {
574 pub command: String,
575 pub result: ShellResult,
576 pub stdout_total_len: usize,
577 pub stderr_total_len: usize,
578 }
579
580 struct RawShellDelta {
581 command: String,
582 task_id: String,
583 status: ShellStatus,
584 exit_code: Option<i64>,
585 duration_ms: u64,
586 stdout: String,
587 stderr: String,
588 stdout_delta_len: usize,
589 stderr_delta_len: usize,
590 stdout_total_len: usize,
591 stderr_total_len: usize,
592 sandboxed: bool,
593 sandbox_type: Option<String>,
594 sandbox_denied: bool,
595 persisted_artifact: Option<PersistedShellArtifact>,
596 }
597
598 /// Which of a job's raw output streams to read. Stderr is a separate stream
599 /// only for piped jobs; PTY and merged modes fold it into stdout.
600 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
601 pub enum ShellOutputStream {
602 Stdout,
603 Stderr,
604 }
605
606 /// A non-consuming window of a job's raw output stream at absolute byte
607 /// offsets. Unlike delta polling, reading a chunk never
608 /// advances anyone else's cursor, so several HTTP clients can follow the same
609 /// job without splitting the stream.
610 pub struct ShellOutputChunk {
611 /// Absolute offset of `bytes[0]`. Exceeds the requested cursor when the
612 /// bounded buffer already discarded that prefix — the gap is reported via
613 /// `dropped`, never silently re-sent.
614 pub offset: usize,
615 /// Raw stream bytes. Output is arbitrary bytes, not guaranteed UTF-8.
616 pub bytes: Vec<u8>,
617 /// Absolute offset just past the last returned byte; the next cursor.
618 pub next_offset: usize,
619 /// Total bytes this stream has produced, including discarded bytes.
620 pub total: usize,
621 /// Leading bytes permanently discarded by the in-flight bound.
622 pub dropped: usize,
623 pub status: ShellStatus,
624 pub exit_code: Option<i64>,
625 }
626
627 enum ShellChild {
628 Process(Child),
629 #[cfg(not(target_env = "ohos"))]
630 Pty(Box<dyn portable_pty::Child + Send>),
631 }
632 #[cfg(unix)]
633 impl ShellChild {
634 fn process_id(&self) -> Option<u32> {
635 match self {
636 Self::Process(child) => Some(child.id()),
637 #[cfg(not(target_env = "ohos"))]
638 Self::Pty(_) => None,
639 }
640 }
641 }
642
643 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
644 enum ShellOwnership {
645 Managed,
646 PersistPending,
647 Released,
648 }
649
650 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
651 pub struct PersistentServiceReceipt {
652 pub task_id: String,
653 pub pid: u32,
654 pub process_group_id: u32,
655 pub ownership: String,
656 }
657
658 #[cfg(unix)]
659 fn signal_child_process_group(child: &Child, signal: libc::c_int) -> std::io::Result<()> {
660 let pgid = child.id() as libc::pid_t;
661 if pgid <= 0 {
662 return Ok(());
663 }
664
665 // SAFETY: kill(2) dereferences no pointers.
666 let result = unsafe { libc::kill(-pgid, signal) };
667 if result == 0 {
668 Ok(())
669 } else {
670 let err = std::io::Error::last_os_error();
671 if err.raw_os_error() == Some(libc::ESRCH) {
672 // The group is already gone (or never formed); nothing to signal.
673 Ok(())
674 } else {
675 Err(err)
676 }
677 }
678 }
679
680 #[cfg(unix)]
681 fn kill_child_process_group(child: &mut Child) -> std::io::Result<()> {
682 let pgid = child.id() as libc::pid_t;
683 if pgid <= 0 {
684 return child.kill();
685 }
686
687 signal_child_process_group(child, libc::SIGKILL).or_else(|_| child.kill())
688 }
689
690 /// Bounded wait for the direct child to exit. Returns true once the child was
691 /// reaped (or the wait errored), false when the grace elapsed first. Unlike
692 /// `Child::wait`, this can never wedge the caller behind a child stuck in
693 /// uninterruptible sleep.
694 #[cfg(unix)]
695 fn wait_child_bounded(child: &mut Child, grace: Duration) -> bool {
696 let deadline = Instant::now() + grace;
697 loop {
698 match child.try_wait() {
699 Ok(Some(_)) | Err(_) => return true,
700 Ok(None) => {}
701 }
702 if Instant::now() >= deadline {
703 return false;
704 }
705 std::thread::sleep(Duration::from_millis(10));
706 }
707 }
708
709 /// Terminate a shell's whole process group with a bounded SIGTERM → SIGKILL
710 /// escalation (#52). The previous kill path SIGKILLed only the direct child
711 /// and then joined output-reader threads with no timeout, so the tool
712 /// returned whenever the command's descendants felt like exiting — observed
713 /// as a 120s foreground timeout returning after 300s. Every step here is
714 /// bounded: the tool returns at ~timeout + grace.
715 #[cfg(unix)]
716 fn terminate_child_process_group(child: &mut Child) -> std::io::Result<()> {
717 // Cooperative stop first so shells and their children can run traps and
718 // clean up; bounded so a SIGTERM-ignoring command cannot stall the caller.
719 let _ = signal_child_process_group(child, libc::SIGTERM);
720 if wait_leader_exit_until(child, Instant::now() + KILL_TERM_GRACE)? {
721 // The leader exited on SIGTERM; descendants may linger, so SIGKILL
722 // the rest of the group (ESRCH when it is already empty) while the
723 // unreaped leader still pins the group id, then reap it.
724 let killed = kill_child_process_group(child);
725 let _ = child.try_wait();
726 return killed;
727 }
728 kill_child_process_group(child)?;
729 let _ = wait_child_bounded(child, KILL_REAP_GRACE);
730 Ok(())
731 }
732
733 /// Configure parent-death signaling so shell-spawned children are reaped when
734 /// the TUI dies abnormally (#421). On Linux this installs
735 /// `PR_SET_PDEATHSIG(SIGTERM)` via `pre_exec` — the kernel then sends SIGTERM
736 /// to the child the moment the parent process exits, even on SIGKILL of the
737 /// TUI. The cancellation path already SIGKILLs the whole process group, so
738 /// this only fires when the parent dies without running its drop / cleanup
739 /// code (panic during shutdown, OOM, hardware crash, etc.).
740 ///
741 /// On macOS / Windows there's no kernel equivalent. The existing graceful
742 /// path (`kill_child_process_group` from the cancellation token) still
743 /// handles normal shutdown; abnormal exit can leak children — tracked as a
744 /// follow-up watchdog item per the original issue's acceptance criteria.
745 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
746 fn install_parent_death_signal(cmd: &mut Command) {
747 use std::os::unix::process::CommandExt;
748 // Captured before the fork so the child can tell whether the TUI already
749 // died in the fork→prctl window, where the signal would never arrive.
750 let parent_pid = std::process::id() as libc::pid_t;
751 // SAFETY: `pre_exec` runs in the child between fork and exec. The closure
752 // only calls `libc::prctl` / `libc::getppid` with stack-allocated
753 // arguments and does not touch heap memory or the parent's locks. Both
754 // requirements (async-signal-safe + no allocation in the post-fork
755 // window) are met.
756 unsafe {
757 cmd.pre_exec(move || {
758 let result = libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM, 0, 0, 0);
759 if result == -1 {
760 // Surface the errno but do not abort the spawn — the child
761 // will simply lose the parent-death cleanup safety net.
762 return Err(std::io::Error::last_os_error());
763 }
764 if libc::getppid() != parent_pid {
765 // The TUI exited before the signal was armed: do not exec an
766 // orphan nobody will ever reap.
767 return Err(std::io::Error::from_raw_os_error(libc::ESRCH));
768 }
769 Ok(())
770 });
771 }
772 }
773
774 /// Watcher script for [`watch_process_group_for_parent_death`]. `$1` is the
775 /// process group id. The outer `sh` only forks the watcher and exits, so the
776 /// watcher is reparented away from the TUI and never needs reaping. The
777 /// watcher blocks reading the pipe the TUI holds the other end of: the read
778 /// ends at EOF when every write end closes, which happens however the TUI
779 /// dies. It then SIGTERMs the group, waits briefly and SIGKILLs it. It sits in
780 /// the job's own process group, so the group id cannot be reused while it
781 /// waits, and the TUI's normal group kills take it down with the job.
782 #[cfg(unix)]
783 const PROCESS_GROUP_WATCHER_SCRIPT: &str = r#"exec 3<&0
784 (
785 trap '' TERM
786 read -r _ <&3 || {
787 kill -TERM -"$1" 2>/dev/null
788 sleep 2
789 kill -KILL -"$1" 2>/dev/null
790 }
791 ) >/dev/null 2>&1 &"#;
792
793 /// Kill a `Managed` background shell's whole process group when the TUI dies
794 /// (#6654).
795 ///
796 /// `PR_SET_PDEATHSIG` is not enough here: it signals only the direct child
797 /// (the `sh -c` wrapper), a fork clears it in grandchildren, so a command that
798 /// does not `exec` its last step (`cd app && npm run dev; echo done`,
799 /// `a | b`) keeps its real workload alive; it also fires when the forking
800 /// *thread* exits, and background spawns run on threads that retire. So a
801 /// small watcher joins the job's process group and blocks on a pipe whose
802 /// write end only the TUI holds (it is close-on-exec, so no child inherits
803 /// it). The returned write end lives in the `BackgroundShell`; closing it —
804 /// by dropping the shell or by the TUI dying in any way, SIGKILL included —
805 /// makes the watcher terminate the group. This works on Linux and macOS alike.
806 ///
807 /// Best effort: if the watcher cannot start, the job still runs, just
808 /// without this cleanup. A TUI that dies between the job spawn and the
809 /// watcher spawn also leaves the job running.
810 #[cfg(unix)]
811 fn watch_process_group_for_parent_death(
812 process_group_id: u32,
813 ) -> std::io::Result<std::io::PipeWriter> {
814 let (reader, writer) = std::io::pipe()?;
815 let pgid = i32::try_from(process_group_id)
816 .map_err(|_| std::io::Error::from_raw_os_error(libc::EINVAL))?;
817 let mut cmd = Command::new("/bin/sh");
818 cmd.args([
819 "-c",
820 PROCESS_GROUP_WATCHER_SCRIPT,
821 "codewhale-bg-watch",
822 &process_group_id.to_string(),
823 ])
824 .stdin(Stdio::from(reader))
825 .stdout(Stdio::null())
826 .stderr(Stdio::null())
827 .process_group(pgid);
828 // The outer `sh` exits as soon as it has forked the watcher.
829 let status = cmd.spawn()?.wait()?;
830 if status.success() {
831 Ok(writer)
832 } else {
833 Err(std::io::Error::other(format!(
834 "process-group watcher exited with {status}"
835 )))
836 }
837 }
838
839 /// Attach `args` to a `std::process::Command`, honoring shell-quoting on
840 /// Windows.
841 ///
842 /// Issue #1691: on Windows the shell command is invoked as
843 /// `cmd /C "chcp 65001 >NUL & <command>"`. Rust's `Command::arg` applies
844 /// MSVCRT (`CommandLineToArgvW`) escaping, turning the embedded `"` in a
845 /// quoted argument (e.g. `git commit -m "feat: complete sub-pages"`) into
846 /// `\"`. `cmd.exe` does NOT use MSVCRT parsing — it treats `\` literally and
847 /// `"` as a bare quote toggle — so the escaped payload is mis-tokenized and
848 /// `git` receives `feat:`, `complete`, `sub-pages"` as separate pathspecs
849 /// (the reported `pathspec 'sub-pages"' did not match` symptom). Passing the
850 /// `cmd /C` payload through `CommandExt::raw_arg` suppresses std's escaping so
851 /// the string reaches `cmd.exe` verbatim, exactly as a terminal would.
852 #[cfg(windows)]
853 fn push_shell_args(cmd: &mut Command, program: &str, args: &[String]) {
854 use std::os::windows::process::CommandExt;
855 // The `cmd /C <payload>` shape is the only place std's per-arg escaping
856 // corrupts a quoted command. Pass `/C` and the payload raw so the quotes
857 // survive; any other program keeps normal (correct) escaping. Match `cmd`
858 // by file stem so a full path (`C:\Windows\System32\cmd.exe`) or `.exe`
859 // suffix still triggers the raw-arg path.
860 let is_cmd = std::path::Path::new(program)
861 .file_stem()
862 .and_then(|s| s.to_str())
863 .map(|s| s.eq_ignore_ascii_case("cmd"))
864 .unwrap_or(false);
865 if is_cmd && args.len() == 2 && args[0].eq_ignore_ascii_case("/C") {
866 cmd.raw_arg(&args[0]);
867 cmd.raw_arg(&args[1]);
868 } else {
869 cmd.args(args);
870 }
871 }
872
873 #[cfg(not(windows))]
874 fn push_shell_args(cmd: &mut Command, _program: &str, args: &[String]) {
875 // Unix delegates tokenization entirely to `sh -c <command>`; the command
876 // string is passed as a single argv entry and never split by us.
877 cmd.args(args);
878 }
879
880 #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))]
881 fn install_parent_death_signal(_cmd: &mut Command) {
882 // No kernel-level equivalent on macOS / Windows. The cooperative
883 // cancellation + process_group SIGKILL path covers normal shutdown;
884 // abnormal exit (panic without unwind, SIGKILL of the TUI) can still
885 // leak children on those platforms — tracked as a follow-up. Pipe-backed
886 // background shells are covered on every platform: Unix by the
887 // process-group watcher (`watch_process_group_for_parent_death`), Windows
888 // by their KILL_ON_JOB_CLOSE job object.
889 //
890 // Known limitations on every platform (#6654): `tty: true` background
891 // shells spawn through `portable_pty`, which never goes through
892 // `std::process::Command`, so they get no watcher (or job object); and
893 // staged persistent services (`persist_pending`) stay deliberately
894 // unwatched because the user can take ownership of the service.
895 }
896
897 #[cfg(windows)]
898 #[derive(Debug)]
899 struct WindowsJob {
900 handle: HANDLE,
901 }
902
903 #[cfg(windows)]
904 // SAFETY: Windows job handles are process-wide kernel handles. Moving the
905 // wrapper between threads does not invalidate the handle, and access is
906 // externally synchronized by ShellManager's mutex.
907 unsafe impl Send for WindowsJob {}
908 #[cfg(windows)]
909 // SAFETY: The wrapper exposes only terminate/drop operations around a kernel
910 // handle; concurrent use is guarded by ShellManager.
911 unsafe impl Sync for WindowsJob {}
912
913 #[cfg(windows)]
914 impl WindowsJob {
915 fn attach_to_child(child: &Child) -> std::io::Result<Self> {
916 // SAFETY: returned handle is owned by the new wrapper.
917 let handle = unsafe { CreateJobObjectW(None, PCWSTR::null()).map_err(windows_io_error)? };
918 let job = Self { handle };
919
920 let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
921 limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
922
923 // SAFETY: `limits` is live with matching size; both handles are live.
924 unsafe {
925 SetInformationJobObject(
926 job.handle,
927 JobObjectExtendedLimitInformation,
928 &limits as *const _ as *const core::ffi::c_void,
929 std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
930 )
931 .map_err(windows_io_error)?;
932
933 let process_handle = HANDLE(child.as_raw_handle());
934 AssignProcessToJobObject(job.handle, process_handle).map_err(windows_io_error)?;
935 }
936
937 Ok(job)
938 }
939
940 fn terminate(&self) -> std::io::Result<()> {
941 // SAFETY: `self.handle` is a live owned job handle.
942 unsafe { TerminateJobObject(self.handle, 1).map_err(windows_io_error) }
943 }
944 }
945
946 #[cfg(windows)]
947 impl Drop for WindowsJob {
948 fn drop(&mut self) {
949 // SAFETY: `self.handle` is owned here; Drop runs once.
950 unsafe {
951 let _ = CloseHandle(self.handle);
952 }
953 }
954 }
955
956 #[cfg(windows)]
957 fn windows_io_error(error: windows::core::Error) -> std::io::Error {
958 std::io::Error::other(error)
959 }
960
961 #[cfg(windows)]
962 fn terminate_windows_job(job: Option<&WindowsJob>, child: &mut Child) -> std::io::Result<()> {
963 if let Some(job) = job {
964 match job.terminate() {
965 Ok(()) => return Ok(()),
966 Err(error) => {
967 tracing::warn!(
968 ?error,
969 "failed to terminate Windows job object; falling back to immediate child kill"
970 );
971 }
972 }
973 }
974 child.kill()
975 }
976
977 #[cfg(windows)]
978 fn terminate_and_close_windows_job(windows_job: Option<WindowsJob>) {
979 if let Some(job) = windows_job.as_ref()
980 && let Err(err) = job.terminate()
981 {
982 tracing::warn!(
983 ?err,
984 "failed to terminate Windows shell job before closing job handle"
985 );
986 }
987 drop(windows_job);
988 }
989
990 #[cfg(windows)]
991 fn terminate_child_and_close_windows_job(
992 windows_job: Option<WindowsJob>,
993 child: &mut Child,
994 ) -> std::io::Result<()> {
995 let result = terminate_windows_job(windows_job.as_ref(), child);
996 drop(windows_job);
997 result
998 }
999
1000 #[cfg(windows)]
1001 fn attach_windows_job(child: &Child, command: &str) -> Option<WindowsJob> {
1002 match WindowsJob::attach_to_child(child) {
1003 Ok(job) => Some(job),
1004 Err(error) => {
1005 tracing::warn!(
1006 ?error,
1007 command,
1008 "failed to attach Windows shell process to job object; descendant cleanup degraded"
1009 );
1010 None
1011 }
1012 }
1013 }
1014
1015 #[cfg(windows)]
1016 fn terminate_unregistered_process(child: &mut Child, job: Option<&WindowsJob>) {
1017 let _ = terminate_windows_job(job, child);
1018 let _ = child.wait();
1019 }
1020
1021 #[cfg(not(windows))]
1022 fn terminate_unregistered_process(child: &mut Child) {
1023 #[cfg(unix)]
1024 {
1025 let _ = kill_child_process_group(child);
1026 let _ = wait_child_bounded(child, KILL_REAP_GRACE);
1027 }
1028 #[cfg(not(unix))]
1029 {
1030 let _ = child.kill();
1031 let _ = child.wait();
1032 }
1033 }
1034
1035 #[derive(Clone, Copy, Debug)]
1036 struct ShellExitStatus {
1037 code: Option<i64>,
1038 success: bool,
1039 }
1040
1041 impl ShellExitStatus {
1042 fn from_std(status: std::process::ExitStatus) -> Self {
1043 Self {
1044 code: status.code().map(std_exit_code_i64),
1045 success: status.success(),
1046 }
1047 }
1048
1049 #[cfg(not(target_env = "ohos"))]
1050 fn from_pty(status: portable_pty::ExitStatus) -> Self {
1051 Self {
1052 code: Some(i64::from(status.exit_code())),
1053 success: status.success(),
1054 }
1055 }
1056 }
1057
1058 #[cfg(windows)]
1059 fn std_exit_code_i64(code: i32) -> i64 {
1060 // std exposes Windows DWORD process statuses through i32. Reinterpret
1061 // negative values as their original unsigned bit pattern so codes such
1062 // as 0xC0000005 survive JSON, persistence, and diagnostics unchanged.
1063 i64::from(code as u32)
1064 }
1065
1066 #[cfg(not(windows))]
1067 fn std_exit_code_i64(code: i32) -> i64 {
1068 i64::from(code)
1069 }
1070
1071 impl ShellChild {
1072 fn try_wait(&mut self) -> std::io::Result<Option<ShellExitStatus>> {
1073 match self {
1074 ShellChild::Process(child) => child
1075 .try_wait()
1076 .map(|status| status.map(ShellExitStatus::from_std)),
1077 #[cfg(not(target_env = "ohos"))]
1078 ShellChild::Pty(child) => child
1079 .try_wait()
1080 .map(|status| status.map(ShellExitStatus::from_pty)),
1081 }
1082 }
1083
1084 fn poll_owned_exit(&mut self) -> std::io::Result<Option<ShellExitStatus>> {
1085 #[cfg(unix)]
1086 match self {
1087 Self::Process(child) => {
1088 match codewhale_runtime::process_tree::leader_exited_unreaped(child.id()) {
1089 Ok(false) => return Ok(None),
1090 Ok(true) => {
1091 let _ = kill_child_process_group(child);
1092 }
1093 Err(_) => {}
1094 }
1095 }
1096 #[cfg(not(target_env = "ohos"))]
1097 Self::Pty(_) => {}
1098 }
1099 self.try_wait()
1100 }
1101
1102 #[cfg(not(windows))]
1103 fn kill(&mut self) -> std::io::Result<()> {
1104 match self {
1105 #[cfg(unix)]
1106 ShellChild::Process(child) => kill_child_process_group(child),
1107 #[cfg(not(unix))]
1108 ShellChild::Process(child) => child.kill(),
1109 #[cfg(not(target_env = "ohos"))]
1110 ShellChild::Pty(child) => child.kill(),
1111 }
1112 }
1113 }
1114
1115 enum StdinWriter {
1116 Pipe(ChildStdin),
1117 #[cfg(not(target_env = "ohos"))]
1118 Pty(Box<dyn Write + Send>),
1119 }
1120
1121 impl StdinWriter {
1122 fn write_all(&mut self, data: &[u8]) -> std::io::Result<()> {
1123 match self {
1124 StdinWriter::Pipe(stdin) => stdin.write_all(data),
1125 #[cfg(not(target_env = "ohos"))]
1126 StdinWriter::Pty(writer) => writer.write_all(data),
1127 }
1128 }
1129
1130 fn flush(&mut self) -> std::io::Result<()> {
1131 match self {
1132 StdinWriter::Pipe(stdin) => stdin.flush(),
1133 #[cfg(not(target_env = "ohos"))]
1134 StdinWriter::Pty(writer) => writer.flush(),
1135 }
1136 }
1137 }
1138
1139 fn spawn_reader_thread<R: Read + Send + 'static>(
1140 mut reader: R,
1141 buffer: SharedRawOutput,
1142 ) -> std::thread::JoinHandle<()> {
1143 std::thread::spawn(move || {
1144 let mut chunk = [0u8; 4096];
1145 loop {
1146 match reader.read(&mut chunk) {
1147 Ok(0) => break,
1148 Ok(n) => {
1149 // `RawOutputBuffer::append` enforces the in-flight ceiling
1150 // here, at the only writer, so a chatty command cannot grow
1151 // the process without bound while it runs (#5472). It
1152 // returns false once the stream has been abandoned, which
1153 // is this thread's only exit when a descendant holds the
1154 // pipe open and EOF never arrives.
1155 let keep_reading = buffer
1156 .lock()
1157 .unwrap_or_else(|e| e.into_inner())
1158 .append(&chunk[..n]);
1159 if !keep_reading {
1160 break;
1161 }
1162 }
1163 Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
1164 Err(_) => {
1165 buffer
1166 .lock()
1167 .unwrap_or_else(|e| e.into_inner())
1168 .mark_read_error();
1169 break;
1170 }
1171 }
1172 }
1173 })
1174 }
1175
1176 fn spawn_bounded_reader_thread<R: Read + Send + 'static>(
1177 mut reader: R,
1178 output: Arc<Mutex<BoundedOutputAccumulator>>,
1179 raw: SharedRawOutput,
1180 ) -> std::thread::JoinHandle<()> {
1181 std::thread::spawn(move || {
1182 let mut chunk = [0u8; 4096];
1183 loop {
1184 match reader.read(&mut chunk) {
1185 Ok(0) => break,
1186 Ok(n) => {
1187 if !raw
1188 .lock()
1189 .unwrap_or_else(|e| e.into_inner())
1190 .append(&chunk[..n])
1191 {
1192 return;
1193 }
1194 let mut guard = output.lock().unwrap_or_else(|error| error.into_inner());
1195 if let Err(error) = guard.append(&chunk[..n]) {
1196 guard.record_error(&error);
1197 return;
1198 }
1199 }
1200 Err(error) => {
1201 output
1202 .lock()
1203 .unwrap_or_else(|poison| poison.into_inner())
1204 .record_error(&error);
1205 return;
1206 }
1207 }
1208 }
1209 let mut guard = output.lock().unwrap_or_else(|error| error.into_inner());
1210 if let Err(error) = guard.finish() {
1211 guard.record_error(&error);
1212 }
1213 })
1214 }
1215
1216 #[cfg(unix)]
1217 fn shared_output_pipe() -> io::Result<(File, File, File)> {
1218 let mut descriptors = [0; 2];
1219 // SAFETY: `pipe` initializes both descriptors on success. Each descriptor
1220 // is immediately transferred into exactly one owned `File`.
1221 if unsafe { libc::pipe(descriptors.as_mut_ptr()) } != 0 {
1222 return Err(io::Error::last_os_error());
1223 }
1224 // SAFETY: successful `pipe` returned two live, uniquely owned descriptors.
1225 let reader = unsafe { File::from_raw_fd(descriptors[0]) };
1226 let writer = unsafe { File::from_raw_fd(descriptors[1]) };
1227 let stderr_writer = writer.try_clone()?;
1228 Ok((reader, writer, stderr_writer))
1229 }
1230
1231 #[cfg(windows)]
1232 fn shared_output_pipe() -> io::Result<(File, File, File)> {
1233 let mut read_handle = std::ptr::null_mut();
1234 let mut write_handle = std::ptr::null_mut();
1235 // SAFETY: CreatePipe initializes both handles on success; ownership is
1236 // transferred to `File` immediately below.
1237 if unsafe {
1238 windows_sys::Win32::System::Pipes::CreatePipe(
1239 &mut read_handle,
1240 &mut write_handle,
1241 std::ptr::null(),
1242 0,
1243 )
1244 } == 0
1245 {
1246 return Err(io::Error::last_os_error());
1247 }
1248 // SAFETY: successful CreatePipe returned two live, uniquely owned handles.
1249 let reader = unsafe { File::from_raw_handle(read_handle.cast()) };
1250 let writer = unsafe { File::from_raw_handle(write_handle.cast()) };
1251 let stderr_writer = writer.try_clone()?;
1252 Ok((reader, writer, stderr_writer))
1253 }
1254
1255 const SYNC_READER_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
1256 pub const QUIET_NO_OUTPUT_AFTER: Duration = Duration::from_secs(60);
1257
1258 /// Grace between SIGTERM and SIGKILL on the shell kill path (timeout,
1259 /// cancel, drop). Bounded so a SIGTERM-ignoring command is force-killed
1260 /// instead of stalling the tool (#52).
1261 #[cfg(unix)]
1262 const KILL_TERM_GRACE: Duration = Duration::from_millis(500);
1263 /// Bounded reap wait after SIGKILL; a child stuck in uninterruptible sleep
1264 /// must not wedge the caller behind an unbounded `wait`.
1265 #[cfg(unix)]
1266 const KILL_REAP_GRACE: Duration = Duration::from_millis(1_000);
1267 /// Bounded join for output-reader threads after the process group is killed.
1268 /// A descendant that escaped the group (its own session/process group) keeps
1269 /// its inherited pipe write-end open, so the reader cannot see EOF until that
1270 /// descendant exits on its own — an unbounded join held the shell-manager
1271 /// lock for minutes and overshot the tool timeout (#52).
1272 const READER_JOIN_GRACE: Duration = Duration::from_millis(2_000);
1273
1274 fn spawn_sync_reader_thread<R: Read + Send + 'static>(
1275 mut reader: R,
1276 ) -> std::sync::mpsc::Receiver<Vec<u8>> {
1277 let (tx, rx) = std::sync::mpsc::channel();
1278 std::thread::spawn(move || {
1279 // Bounded, unlike the `read_to_end` this replaces (#5472 finding 2).
1280 // `recv_sync_reader_output` gives up after 5 s, but the thread lives as
1281 // long as the pipe does — an interactive command that keeps printing
1282 // grew this Vec without limit, for a result nobody was still waiting
1283 // for. The tail is what the caller renders, so keep the tail.
1284 let mut buf = RawOutputBuffer::new();
1285 let mut chunk = [0u8; 4096];
1286 loop {
1287 match reader.read(&mut chunk) {
1288 Ok(0) => break,
1289 Ok(n) => {
1290 if !buf.append(&chunk[..n]) {
1291 break;
1292 }
1293 }
1294 Err(_) => break,
1295 }
1296 }
1297 tx.send(buf.retained().to_vec()).ok();
1298 });
1299 rx
1300 }
1301
1302 fn recv_sync_reader_output(rx: &std::sync::mpsc::Receiver<Vec<u8>>) -> Vec<u8> {
1303 rx.recv_timeout(SYNC_READER_DRAIN_TIMEOUT)
1304 .unwrap_or_default()
1305 }
1306
1307 #[cfg(unix)]
1308 fn set_foreground_stdin_nonblocking(stdin: &ChildStdin) -> std::io::Result<()> {
1309 use std::os::fd::AsRawFd;
1310 let fd = stdin.as_raw_fd();
1311 let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1312 if flags == -1 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 {
1313 return Err(std::io::Error::last_os_error());
1314 }
1315 Ok(())
1316 }
1317
1318 #[cfg(windows)]
1319 fn set_foreground_stdin_nonblocking(stdin: &ChildStdin) -> std::io::Result<()> {
1320 use windows_sys::Win32::System::Pipes::{PIPE_NOWAIT, SetNamedPipeHandleState};
1321 let ok = unsafe {
1322 SetNamedPipeHandleState(
1323 stdin.as_raw_handle(),
1324 &PIPE_NOWAIT,
1325 std::ptr::null(),
1326 std::ptr::null(),
1327 )
1328 };
1329 if ok == 0 {
1330 return Err(std::io::Error::last_os_error());
1331 }
1332 Ok(())
1333 }
1334
1335 #[cfg(not(any(unix, windows)))]
1336 fn set_foreground_stdin_nonblocking(_: &ChildStdin) -> std::io::Result<()> {
1337 Err(std::io::ErrorKind::Unsupported.into())
1338 }
1339
1340 fn write_foreground_input(
1341 writer: &mut impl Write,
1342 mut input: &[u8],
1343 remaining: impl Fn() -> Duration,
1344 ) -> std::io::Result<bool> {
1345 while !input.is_empty() {
1346 let budget = remaining();
1347 if budget.is_zero() {
1348 return Ok(false);
1349 }
1350 match writer.write(input) {
1351 #[cfg(windows)]
1352 Ok(0) => {}
1353 #[cfg(not(windows))]
1354 Ok(0) => return Err(std::io::ErrorKind::WriteZero.into()),
1355 Ok(count) => {
1356 input = &input[count..];
1357 continue;
1358 }
1359 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
1360 Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {}
1361 Err(error) => return Err(error),
1362 }
1363 std::thread::sleep(remaining().min(Duration::from_millis(5)));
1364 }
1365 Ok(true)
1366 }
1367
1368 /// Cell dimensions accepted by the existing PTY owner. Pixel sizes remain
1369 /// unspecified; callers must not allocate an unbounded terminal grid.
1370 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1371 #[serde(deny_unknown_fields)]
1372 pub struct PtyDimensions {
1373 pub rows: u16,
1374 pub cols: u16,
1375 }
1376
1377 impl Default for PtyDimensions {
1378 fn default() -> Self {
1379 Self { rows: 24, cols: 80 }
1380 }
1381 }
1382
1383 impl PtyDimensions {
1384 pub fn validate(self) -> Result<Self> {
1385 anyhow::ensure!(
1386 (1..=1000).contains(&self.rows) && (1..=1000).contains(&self.cols),
1387 "PTY rows and columns must each be between 1 and 1000"
1388 );
1389 Ok(self)
1390 }
1391 }
1392
1393 /// A background shell process being tracked
1394 pub struct BackgroundShell {
1395 pub id: String,
1396 pub command: String,
1397 pub description: Option<String>,
1398 pub working_dir: PathBuf,
1399 pub status: ShellStatus,
1400 background: bool,
1401 pub exit_code: Option<i64>,
1402 pub started_at: Instant,
1403 started_at_utc: chrono::DateTime<chrono::Utc>,
1404 /// When the job reached a terminal status. A finished job reports the
1405 /// duration it finished with; without this, `started_at.elapsed()` kept
1406 /// growing and `/jobs` showed "2m 07s" for a 12-second command (#5478).
1407 finished_at: Option<Instant>,
1408 finished_at_utc: Option<chrono::DateTime<chrono::Utc>>,
1409 cause: Option<ShellTerminationCause>,
1410 last_output_at: Instant,
1411 last_observed_output_len: usize,
1412 pub sandbox_type: SandboxType,
1413 pub linked_task_id: Option<String>,
1414 pub owner_agent: Option<ShellJobOwner>,
1415 owner_session_id: String,
1416 origin_tool_call_id: Option<String>,
1417 origin_turn_id: Option<String>,
1418 ownership: ShellOwnership,
1419 stdout_buffer: SharedRawOutput,
1420 stderr_buffer: Option<SharedRawOutput>,
1421 /// Lowercase `bash` streams one combined process pipe through a bounded
1422 /// small-contract-compatible accumulator while persisting the complete output.
1423 bounded_output: Option<Arc<Mutex<BoundedOutputAccumulator>>>,
1424 heavy_permit: Option<HeavyCommandPermit>,
1425 scratch: Option<codewhale_sandbox::ScratchDir>,
1426 stdout_cursor: usize,
1427 stderr_cursor: usize,
1428 completion_reported: bool,
1429 stdin: Option<StdinWriter>,
1430 /// Retain the existing PTY owner for resize; never create another session.
1431 #[cfg(not(target_env = "ohos"))]
1432 pty_master: Option<Box<dyn portable_pty::MasterPty + Send>>,
1433 terminal_size: Option<PtyDimensions>,
1434 child: Option<ShellChild>,
1435 #[cfg(windows)]
1436 windows_job: Option<WindowsJob>,
1437 /// Write end of the process-group watcher's pipe for `Managed` shells;
1438 /// closing it (drop, or the TUI dying) kills the job's group (#6654).
1439 #[cfg(unix)]
1440 parent_death_watch: Option<std::io::PipeWriter>,
1441 stdout_thread: Option<std::thread::JoinHandle<()>>,
1442 stderr_thread: Option<std::thread::JoinHandle<()>>,
1443 work_lifecycle: Option<ShellWorkLifecycle>,
1444 lifecycle_seq: u64,
1445 last_lifecycle_status: Option<ShellStatus>,
1446 last_lifecycle_bytes: usize,
1447 /// The terminal status came from a failed `try_wait`, not an observed
1448 /// exit or signal. Such a run gets no execution receipt (#6689).
1449 wait_failed: bool,
1450 terminal_exit_confirmed: bool,
1451 hold: Option<JobHoldState>,
1452 }
1453
1454 #[derive(Clone)]
1455 pub(super) struct ShellWorkLifecycle {
1456 work: SharedWorkRuntime,
1457 session_id: String,
1458 }
1459
1460 impl ShellWorkLifecycle {
1461 fn register(&self, id: &str, command: &str) -> Result<()> {
1462 self.work
1463 .register_operation(
1464 &self.session_id,
1465 OperationIntent::new(
1466 format!("shell:{id}"),
1467 format!("Shell · {command}"),
1468 false,
1469 "exec_shell",
1470 id,
1471 ),
1472 )
1473 .map(|_| ())
1474 .map_err(anyhow::Error::msg)
1475 }
1476
1477 fn observe(&self, id: &str, status: &ShellStatus, seq: u64, raw_bytes: usize) -> Result<()> {
1478 let owner_state = match status {
1479 ShellStatus::Running => OwnerState::Running,
1480 ShellStatus::Completed => OwnerState::Completed,
1481 ShellStatus::Failed | ShellStatus::TimedOut => OwnerState::Failed,
1482 ShellStatus::Killed => OwnerState::Cancelled,
1483 };
1484 let raw_bytes = u64::try_from(raw_bytes).unwrap_or(u64::MAX);
1485 let output = EvidenceRef::new(
1486 EvidenceKind::Receipt {
1487 owner: "shell".to_string(),
1488 },
1489 format!("shell:{id}:output"),
1490 Some(raw_bytes),
1491 false,
1492 )
1493 .map_err(|err| anyhow!(err.to_string()))?;
1494 self.work
1495 .reconcile_operation(
1496 &self.session_id,
1497 OperationOwnerSnapshot::new(
1498 format!("shell:{id}"),
1499 owner_state,
1500 seq,
1501 lifecycle_now_ms(),
1502 )
1503 .with_output(output),
1504 )
1505 .map(|_| ())
1506 .map_err(anyhow::Error::msg)
1507 }
1508 }
1509
1510 struct ShellSpawnIntentGuard {
1511 lifecycle: Option<ShellWorkLifecycle>,
1512 id: String,
1513 armed: bool,
1514 }
1515
1516 struct ShellSpawnContext {
1517 owner_agent: Option<ShellJobOwner>,
1518 owner_session_id: String,
1519 origin_tool_call_id: Option<String>,
1520 origin_turn_id: Option<String>,
1521 work_lifecycle: Option<ShellWorkLifecycle>,
1522 }
1523
1524 impl ShellSpawnIntentGuard {
1525 /// Register the spawn intent with the Work graph.
1526 ///
1527 /// Registration is observability bookkeeping — the same subsystem already
1528 /// treats the `observe` half as best-effort (a graph-write failure must
1529 /// not relabel a completed command) — so a transiently busy To-do/Plan
1530 /// state must not veto the command itself. Live sessions hit this: a
1531 /// shell call issued right after another tool call failed outright with
1532 /// "To-do state is busy; operation was not registered" because
1533 /// `register_operation` gives the lock only a short try-lock spin.
1534 ///
1535 /// On failure the guard goes inert: the shell still runs, and no later
1536 /// `observe` pretends the operation was bound.
1537 fn new(lifecycle: Option<ShellWorkLifecycle>, id: &str, command: &str) -> Self {
1538 let lifecycle = lifecycle.and_then(|lifecycle| match lifecycle.register(id, command) {
1539 Ok(()) => Some(lifecycle),
1540 Err(err) => {
1541 tracing::warn!(
1542 shell_id = %id,
1543 error = %err,
1544 "shell work-graph registration skipped; running without a bound operation"
1545 );
1546 None
1547 }
1548 });
1549 Self {
1550 lifecycle,
1551 id: id.to_string(),
1552 armed: true,
1553 }
1554 }
1555
1556 fn disarm(&mut self) {
1557 self.armed = false;
1558 }
1559 }
1560
1561 impl Drop for ShellSpawnIntentGuard {
1562 fn drop(&mut self) {
1563 if self.armed
1564 && let Some(lifecycle) = self.lifecycle.as_ref()
1565 && let Err(err) = lifecycle.observe(&self.id, &ShellStatus::Failed, 1, 0)
1566 {
1567 tracing::warn!(shell_id = %self.id, error = %err, "failed to record shell spawn failure");
1568 }
1569 }
1570 }
1571
1572 impl BackgroundShell {
1573 fn has_unsettled_child(&self) -> bool {
1574 self.ownership != ShellOwnership::Released
1575 && self.child.is_some()
1576 && !self.terminal_exit_confirmed
1577 }
1578
1579 /// Wall time to report: elapsed while running, frozen once finished.
1580 fn wall_duration(&self) -> Duration {
1581 self.finished_at
1582 .unwrap_or_else(Instant::now)
1583 .saturating_duration_since(self.started_at)
1584 }
1585
1586 fn wall_millis(&self) -> u64 {
1587 u64::try_from(self.wall_duration().as_millis()).unwrap_or(u64::MAX)
1588 }
1589
1590 /// Stamp the finish instant the first time a terminal status is observed.
1591 /// Idempotent: a later poll must not restate when the job ended.
1592 fn mark_finished(&mut self) {
1593 if self.finished_at.is_none() && self.status != ShellStatus::Running {
1594 self.finished_at = Some(Instant::now());
1595 self.finished_at_utc = Some(chrono::Utc::now());
1596 self.cause = Some(match &self.status {
1597 ShellStatus::Killed => ShellTerminationCause::Killed,
1598 ShellStatus::TimedOut => ShellTerminationCause::TimedOut,
1599 ShellStatus::Completed | ShellStatus::Failed => ShellTerminationCause::Producer,
1600 ShellStatus::Running => ShellTerminationCause::Unknown,
1601 });
1602 }
1603 }
1604
1605 /// Check if the process has completed and update status
1606 fn poll(&mut self) -> bool {
1607 self.refresh_output_activity();
1608 if self.status != ShellStatus::Running {
1609 if self.has_unsettled_child()
1610 && let Some(child) = self.child.as_mut()
1611 && child.try_wait().is_ok_and(|status| status.is_some())
1612 {
1613 self.terminal_exit_confirmed = true;
1614 self.child = None;
1615 }
1616 self.mark_finished();
1617 self.publish_lifecycle_best_effort();
1618 return true;
1619 }
1620
1621 #[cfg(unix)]
1622 let pending_process_group = (self.ownership == ShellOwnership::PersistPending)
1623 .then(|| self.child.as_ref().and_then(ShellChild::process_id))
1624 .flatten();
1625 let completed = if let Some(ref mut child) = self.child {
1626 match child.poll_owned_exit() {
1627 Ok(Some(status)) => {
1628 self.terminal_exit_confirmed = true;
1629 self.exit_code = status.code;
1630 self.status = if status.success {
1631 ShellStatus::Completed
1632 } else {
1633 ShellStatus::Failed
1634 };
1635 self.heavy_permit.take();
1636 self.finish_child();
1637 self.scratch.take();
1638 true
1639 }
1640 Ok(None) => false, // Still running
1641 Err(_) => {
1642 self.status = ShellStatus::Failed;
1643 self.wait_failed = true;
1644 self.heavy_permit.take();
1645 self.finish_child();
1646 self.scratch.take();
1647 true
1648 }
1649 }
1650 } else {
1651 true
1652 };
1653 #[cfg(unix)]
1654 if completed && let Some(process_group_id) = pending_process_group {
1655 unregister_pending_persistent_process_group(process_group_id);
1656 }
1657 self.mark_finished();
1658 self.publish_lifecycle_best_effort();
1659 completed
1660 }
1661
1662 fn publish_lifecycle(&mut self) -> Result<()> {
1663 let bytes = self.observed_output_len();
1664 if self.last_lifecycle_status.as_ref() == Some(&self.status)
1665 && self.last_lifecycle_bytes == bytes
1666 {
1667 return Ok(());
1668 }
1669 let next_seq = self.lifecycle_seq.saturating_add(1);
1670 if let Some(lifecycle) = self.work_lifecycle.as_ref() {
1671 lifecycle.observe(&self.id, &self.status, next_seq, bytes)?;
1672 }
1673 self.lifecycle_seq = next_seq;
1674 self.last_lifecycle_status = Some(self.status.clone());
1675 self.last_lifecycle_bytes = bytes;
1676 Ok(())
1677 }
1678
1679 fn publish_lifecycle_best_effort(&mut self) {
1680 if let Err(err) = self.publish_lifecycle() {
1681 tracing::warn!(shell_id = %self.id, error = %err, "failed to reconcile shell lifecycle");
1682 }
1683 }
1684
1685 fn refresh_output_activity(&mut self) {
1686 let observed_len = self.observed_output_len();
1687 if observed_len != self.last_observed_output_len {
1688 self.last_observed_output_len = observed_len;
1689 self.last_output_at = Instant::now();
1690 }
1691 }
1692
1693 fn observed_output_len(&self) -> usize {
1694 if let Some(output) = self.bounded_output.as_ref() {
1695 return output
1696 .lock()
1697 .map(|output| output.total_bytes())
1698 .unwrap_or(0);
1699 }
1700 let stdout_len = self
1701 .stdout_buffer
1702 .lock()
1703 .map(|data| data.total_len())
1704 .unwrap_or(0);
1705 let stderr_len = self
1706 .stderr_buffer
1707 .as_ref()
1708 .and_then(|buffer| buffer.lock().ok().map(|data| data.total_len()))
1709 .unwrap_or(0);
1710 stdout_len.saturating_add(stderr_len)
1711 }
1712
1713 /// Drop everything but a bounded tail of both raw streams.
1714 ///
1715 /// Called only once a job is terminal **and** its bytes have already been
1716 /// delivered — either returned as the foreground tool result, or written to
1717 /// its durable completion artifact. Before that the full bytes are a
1718 /// contract; after it they are pure residency for the up-to-1 h the
1719 /// finished record stays listed, which is what took the owner's host to
1720 /// 11 GB of swap (#5472 finding 1).
1721 fn release_delivered_output(&mut self) {
1722 if self.status == ShellStatus::Running {
1723 return;
1724 }
1725 if let Some(output) = self.bounded_output.as_ref() {
1726 output
1727 .lock()
1728 .unwrap_or_else(|poison| poison.into_inner())
1729 .release_temp();
1730 }
1731 for buffer in [Some(&self.stdout_buffer), self.stderr_buffer.as_ref()]
1732 .into_iter()
1733 .flatten()
1734 {
1735 buffer
1736 .lock()
1737 .unwrap_or_else(|poison| poison.into_inner())
1738 .release_to_tail(RAW_STREAM_SETTLED_TAIL_BYTES);
1739 }
1740 }
1741
1742 /// Bytes still held in memory for this job, for the eviction accounting in
1743 /// [`ShellManager::cleanup`] and for tests that assert the bound.
1744 fn retained_output_bytes(&self) -> usize {
1745 let stdout = self
1746 .stdout_buffer
1747 .lock()
1748 .map(|data| data.retained().len())
1749 .unwrap_or(0);
1750 let stderr = self
1751 .stderr_buffer
1752 .as_ref()
1753 .and_then(|buffer| buffer.lock().ok().map(|data| data.retained().len()))
1754 .unwrap_or(0);
1755 stdout.saturating_add(stderr)
1756 }
1757
1758 fn finish_child(&mut self) {
1759 #[cfg(unix)]
1760 drop(self.parent_death_watch.take());
1761 #[cfg(windows)]
1762 terminate_and_close_windows_job(self.windows_job.take());
1763 if let Some(handle) = self.stdout_thread.take() {
1764 finish_background_reader(handle, &self.status, Some(&self.stdout_buffer));
1765 }
1766 if let Some(handle) = self.stderr_thread.take() {
1767 finish_background_reader(handle, &self.status, self.stderr_buffer.as_ref());
1768 }
1769 self.stdin = None;
1770 #[cfg(not(target_env = "ohos"))]
1771 {
1772 self.pty_master = None;
1773 }
1774 if self.terminal_exit_confirmed {
1775 self.child = None;
1776 }
1777 }
1778
1779 fn write_stdin(&mut self, input: &str, close: bool) -> Result<()> {
1780 self.write_stdin_bytes(input.as_bytes(), close)
1781 }
1782
1783 fn write_stdin_bytes(&mut self, input: &[u8], close: bool) -> Result<()> {
1784 if let Some(stdin) = self.stdin.as_mut() {
1785 if !input.is_empty() {
1786 stdin.write_all(input).context("Failed to write to stdin")?;
1787 stdin.flush().context("Failed to flush stdin")?;
1788 }
1789 if close {
1790 self.stdin = None;
1791 }
1792 return Ok(());
1793 }
1794
1795 if input.is_empty() && close {
1796 return Ok(());
1797 }
1798
1799 Err(anyhow!("stdin is not available for task {}", self.id))
1800 }
1801
1802 fn full_output(&self) -> (String, String, usize, usize) {
1803 if let Some(snapshot) = self.bounded_output_snapshot(false).ok().flatten() {
1804 return (snapshot.content, String::new(), snapshot.total_bytes, 0);
1805 }
1806 let (stdout_bytes, stderr_bytes, stdout_omitted, stderr_omitted) =
1807 self.retained_output_bytes_with_omissions();
1808 // Report what the stream produced, not what is still held.
1809 let stdout_len = stdout_bytes.len().saturating_add(stdout_omitted);
1810 let stderr_len = stderr_bytes.len().saturating_add(stderr_omitted);
1811
1812 (
1813 String::from_utf8_lossy(&stdout_bytes).to_string(),
1814 String::from_utf8_lossy(&stderr_bytes).to_string(),
1815 stdout_len,
1816 stderr_len,
1817 )
1818 }
1819
1820 /// Retained bytes for both streams plus how many leading bytes the memory
1821 /// bound discarded. Callers that publish these bytes as evidence must
1822 /// declare the omission rather than presenting a clipped stream as exact.
1823 fn retained_output_bytes_with_omissions(&self) -> (Vec<u8>, Vec<u8>, usize, usize) {
1824 if let Some(output) = self.bounded_output.as_ref()
1825 && let Some((bytes, omitted)) = output
1826 .lock()
1827 .unwrap_or_else(|error| error.into_inner())
1828 .retained_raw_bytes()
1829 {
1830 return (bytes, Vec::new(), omitted, 0);
1831 }
1832 if let Some(snapshot) = self.bounded_output_snapshot(false).ok().flatten() {
1833 let omitted = snapshot.total_bytes.saturating_sub(snapshot.retained_bytes);
1834 return (snapshot.content.into_bytes(), Vec::new(), omitted, 0);
1835 }
1836 let (stdout_bytes, stdout_omitted) = self
1837 .stdout_buffer
1838 .lock()
1839 .map(|data| (data.retained().to_vec(), data.dropped()))
1840 .unwrap_or_default();
1841 let (stderr_bytes, stderr_omitted) = self
1842 .stderr_buffer
1843 .as_ref()
1844 .and_then(|buffer| {
1845 buffer
1846 .lock()
1847 .ok()
1848 .map(|data| (data.retained().to_vec(), data.dropped()))
1849 })
1850 .unwrap_or_default();
1851 (stdout_bytes, stderr_bytes, stdout_omitted, stderr_omitted)
1852 }
1853
1854 fn take_delta(
1855 &mut self,
1856 ) -> (
1857 String,
1858 String,
1859 usize,
1860 usize,
1861 usize,
1862 usize,
1863 Option<PersistedShellArtifact>,
1864 ) {
1865 let bounded_delta = self.bounded_output.as_ref().and_then(|output| {
1866 let output = output.lock().unwrap_or_else(|error| error.into_inner());
1867 let total = output.total_bytes();
1868 output
1869 .delta_since(self.stdout_cursor)
1870 .ok()
1871 .map(|delta| (delta, total))
1872 });
1873 if let Some(((mut delta, omitted), total_bytes)) = bounded_delta {
1874 let delta_len = total_bytes.saturating_sub(self.stdout_cursor);
1875 self.stdout_cursor = total_bytes;
1876 if delta_len == 0 {
1877 return (String::new(), String::new(), 0, 0, total_bytes, 0, None);
1878 }
1879 self.last_output_at = Instant::now();
1880 self.last_observed_output_len = total_bytes;
1881 let mut persisted_artifact = None;
1882 if omitted > 0
1883 && let Some(output) = self.bounded_output.as_ref()
1884 {
1885 let mut guard = output.lock().unwrap_or_else(|error| error.into_inner());
1886 let notice = guard.omitted_notice(omitted);
1887 persisted_artifact = guard.persisted_artifact();
1888 delta.insert_str(0, &notice);
1889 }
1890 return (
1891 delta,
1892 String::new(),
1893 delta_len,
1894 0,
1895 total_bytes,
1896 0,
1897 persisted_artifact,
1898 );
1899 }
1900 let previous_stdout = self.stdout_cursor;
1901 let previous_stderr = self.stderr_cursor;
1902 let (stdout_delta, stdout_total) =
1903 take_delta_from_buffer(&self.stdout_buffer, &mut self.stdout_cursor);
1904 let (stderr_delta, stderr_total) = if let Some(buffer) = self.stderr_buffer.as_ref() {
1905 take_delta_from_buffer(buffer, &mut self.stderr_cursor)
1906 } else {
1907 (Vec::new(), 0)
1908 };
1909
1910 let stdout_delta_len = self.stdout_cursor.saturating_sub(previous_stdout);
1911 let stderr_delta_len = self.stderr_cursor.saturating_sub(previous_stderr);
1912
1913 if stdout_delta_len > 0 || stderr_delta_len > 0 {
1914 self.last_output_at = Instant::now();
1915 self.last_observed_output_len = stdout_total.saturating_add(stderr_total);
1916 }
1917
1918 (
1919 String::from_utf8_lossy(&stdout_delta).to_string(),
1920 String::from_utf8_lossy(&stderr_delta).to_string(),
1921 stdout_delta_len,
1922 stderr_delta_len,
1923 stdout_total,
1924 stderr_total,
1925 None,
1926 )
1927 }
1928
1929 fn sandbox_denied(&self) -> bool {
1930 if matches!(self.status, ShellStatus::Running) {
1931 return false;
1932 }
1933 let (_, stderr_full, _, _) = self.full_output();
1934 SandboxManager::was_denied(
1935 self.sandbox_type,
1936 self.exit_code
1937 .and_then(|code| i32::try_from(code).ok())
1938 .unwrap_or(-1),
1939 &stderr_full,
1940 )
1941 }
1942
1943 /// Kill the process
1944 fn kill(&mut self) -> Result<()> {
1945 if self.poll() && self.status != ShellStatus::Running {
1946 return Ok(());
1947 }
1948 #[cfg(unix)]
1949 if self.ownership == ShellOwnership::PersistPending
1950 && let Some(process_group_id) = self.child.as_ref().and_then(ShellChild::process_id)
1951 {
1952 unregister_pending_persistent_process_group(process_group_id);
1953 }
1954 if let Some(ref mut child) = self.child {
1955 match &mut *child {
1956 ShellChild::Process(proc) => {
1957 #[cfg(windows)]
1958 {
1959 terminate_windows_job(self.windows_job.as_ref(), proc)
1960 .context("Failed to kill process tree")?;
1961 let _ = proc.wait();
1962 }
1963 #[cfg(all(not(windows), unix))]
1964 {
1965 // Bounded SIGTERM → SIGKILL escalation against the
1966 // whole process group; returns within ~grace even if
1967 // the command ignores SIGTERM (#52).
1968 terminate_child_process_group(proc).context("Failed to kill process")?;
1969 }
1970 #[cfg(all(not(windows), not(unix)))]
1971 {
1972 proc.kill().context("Failed to kill process")?;
1973 let _ = proc.wait();
1974 }
1975 }
1976 #[cfg(not(target_env = "ohos"))]
1977 ShellChild::Pty(child) => {
1978 child.kill().context("Failed to kill process")?;
1979 let _ = child.wait();
1980 }
1981 }
1982 if child.try_wait().is_ok_and(|status| status.is_some()) {
1983 self.terminal_exit_confirmed = true;
1984 }
1985 }
1986 self.status = ShellStatus::Killed;
1987 self.mark_finished();
1988 self.heavy_permit.take();
1989 self.finish_child();
1990 self.scratch.take();
1991 self.publish_lifecycle_best_effort();
1992 Ok(())
1993 }
1994
1995 pub fn snapshot(&self) -> Result<ShellResult> {
1996 self.snapshot_with_artifact(self.status != ShellStatus::Running)
1997 .map(|(result, _)| result)
1998 }
1999
2000 fn snapshot_with_artifact(
2001 &self,
2002 finalize: bool,
2003 ) -> Result<(ShellResult, Option<PersistedShellArtifact>)> {
2004 let sandboxed = !matches!(self.sandbox_type, SandboxType::None);
2005 if let Some(snapshot) = self.bounded_output_snapshot(finalize)? {
2006 return Ok((
2007 ShellResult {
2008 task_id: Some(self.id.clone()),
2009 status: self.status.clone(),
2010 exit_code: self.exit_code,
2011 stdout: snapshot.content,
2012 stderr: String::new(),
2013 duration_ms: self.wall_millis(),
2014 stdout_len: snapshot.total_bytes,
2015 stderr_len: 0,
2016 stdout_omitted: snapshot.total_bytes.saturating_sub(snapshot.retained_bytes),
2017 stderr_omitted: 0,
2018 stdout_truncated: snapshot.truncated,
2019 stderr_truncated: false,
2020 sandboxed,
2021 sandbox_type: sandboxed.then(|| self.sandbox_type.to_string()),
2022 sandbox_denied: false,
2023 },
2024 snapshot.persisted_artifact,
2025 ));
2026 }
2027 let (stdout_full, stderr_full, stdout_total, stderr_total) = self.full_output();
2028 let (stdout, stdout_meta) = truncate_with_meta(&stdout_full);
2029 let (stderr, stderr_meta) = truncate_with_meta(&stderr_full);
2030 let stdout_dropped = stdout_total.saturating_sub(stdout_meta.original_len);
2031 let stderr_dropped = stderr_total.saturating_sub(stderr_meta.original_len);
2032 let stdout_truncated = stdout_meta.truncated || stdout_dropped > 0;
2033 let stderr_truncated = stderr_meta.truncated || stderr_dropped > 0;
2034 let persisted_artifact = if finalize && (stdout_truncated || stderr_truncated) {
2035 self.publish_raw_output()?
2036 } else {
2037 None
2038 };
2039 Ok((
2040 ShellResult {
2041 task_id: Some(self.id.clone()),
2042 status: self.status.clone(),
2043 exit_code: self.exit_code,
2044 stdout,
2045 stderr,
2046 duration_ms: self.wall_millis(),
2047 stdout_len: stdout_total,
2048 stderr_len: stderr_total,
2049 stdout_omitted: stdout_meta.omitted.saturating_add(stdout_dropped),
2050 stderr_omitted: stderr_meta.omitted.saturating_add(stderr_dropped),
2051 stdout_truncated,
2052 stderr_truncated,
2053 sandboxed,
2054 sandbox_type: if sandboxed {
2055 Some(self.sandbox_type.to_string())
2056 } else {
2057 None
2058 },
2059 sandbox_denied: self.sandbox_denied(),
2060 },
2061 persisted_artifact,
2062 ))
2063 }
2064
2065 fn publish_raw_output(&self) -> Result<Option<PersistedShellArtifact>> {
2066 if !codewhale_runtime::artifacts::is_valid_session_id(&self.owner_session_id) {
2067 return Ok(None);
2068 }
2069 let mut stdout = self.stdout_buffer.lock().unwrap_or_else(|e| e.into_inner());
2070 let stderr = self
2071 .stderr_buffer
2072 .as_ref()
2073 .map(|buffer| buffer.lock().unwrap_or_else(|e| e.into_inner()));
2074 if let Some(artifact) = stdout.artifact() {
2075 return Ok(Some(artifact));
2076 }
2077 if !stdout.capture_complete() || stderr.as_ref().is_some_and(|s| !s.capture_complete()) {
2078 return Ok(None);
2079 }
2080 let key = self.origin_tool_call_id.as_deref().unwrap_or(&self.id);
2081 let publish = stdout.publish_complete(stderr.as_deref(), &self.owner_session_id, key);
2082 let publish = match publish {
2083 Err(error) if error.kind() == io::ErrorKind::AlreadyExists && key != self.id => {
2084 stdout.publish_complete(stderr.as_deref(), &self.owner_session_id, &self.id)
2085 }
2086 other => other,
2087 };
2088 Ok(Some(publish?))
2089 }
2090
2091 fn finalize_output_artifact(&self) -> Result<Option<PersistedShellArtifact>> {
2092 if let Some(snapshot) = self.bounded_output_snapshot(true)? {
2093 return Ok(snapshot.persisted_artifact);
2094 }
2095 let large = [&self.stdout_buffer]
2096 .into_iter()
2097 .chain(self.stderr_buffer.iter())
2098 .any(|buffer| {
2099 let guard = buffer.lock().unwrap_or_else(|e| e.into_inner());
2100 guard.total_len() > RAW_STREAM_MAX_BYTES
2101 });
2102 if large {
2103 self.publish_raw_output()
2104 } else {
2105 Ok(None)
2106 }
2107 }
2108
2109 fn bounded_output_snapshot(&self, finalize: bool) -> Result<Option<BoundedOutputSnapshot>> {
2110 self.bounded_output
2111 .as_ref()
2112 .map(|output| {
2113 output
2114 .lock()
2115 .unwrap_or_else(|error| error.into_inner())
2116 .snapshot(finalize)
2117 .map_err(anyhow::Error::from)
2118 })
2119 .transpose()
2120 }
2121
2122 fn last_progress_at(&self) -> chrono::DateTime<chrono::Utc> {
2123 chrono::Duration::from_std(self.last_output_at.elapsed())
2124 .ok()
2125 .and_then(|age| chrono::Utc::now().checked_sub_signed(age))
2126 .unwrap_or(self.started_at_utc)
2127 .max(self.started_at_utc)
2128 }
2129
2130 fn job_snapshot(&self) -> ShellJobSnapshot {
2131 // Use tail_from_buffer instead of full_output so we never clone the
2132 // entire accumulated stdout/stderr for display purposes. full_output
2133 // is O(total_bytes_written), which caused the ShellManager mutex to be
2134 // held for an arbitrarily long time during list_jobs() calls from the
2135 // TUI event loop — freezing input handling on long automation runs.
2136 let (stdout_len, stdout_tail) =
2137 if let Some(snapshot) = self.bounded_output_snapshot(false).ok().flatten() {
2138 (snapshot.total_bytes, tail_text(&snapshot.content, 1_200))
2139 } else {
2140 tail_from_buffer(&self.stdout_buffer, 1200)
2141 };
2142 let (stderr_len, stderr_tail) = self
2143 .stderr_buffer
2144 .as_ref()
2145 .map(|buf| tail_from_buffer(buf, 1200))
2146 .unwrap_or((0, String::new()));
2147 let elapsed_since_output_ms = (self.status == ShellStatus::Running)
2148 .then(|| u64::try_from(self.last_output_at.elapsed().as_millis()).unwrap_or(u64::MAX));
2149 let producer_reported =
2150 self.cause == Some(ShellTerminationCause::Producer) && !self.wait_failed;
2151 ShellJobSnapshot {
2152 id: self.id.clone(),
2153 job_id: self.id.clone(),
2154 command: self.command.clone(),
2155 description: self.description.clone(),
2156 cwd: self.working_dir.clone(),
2157 status: self.status.clone(),
2158 background: self.background,
2159 started_at: Some(self.started_at_utc),
2160 finished_at: self.finished_at_utc,
2161 cause: self.cause,
2162 producer_reported,
2163 exit_code: self.exit_code,
2164 elapsed_ms: self.wall_millis(),
2165 stdout_tail,
2166 stderr_tail,
2167 stdout_len,
2168 stderr_len,
2169 stdin_available: self.stdin.is_some() && self.status == ShellStatus::Running,
2170 stale: false,
2171 elapsed_since_output_ms,
2172 linked_task_id: self.linked_task_id.clone(),
2173 owner_agent_id: self
2174 .owner_agent
2175 .as_ref()
2176 .map(|owner| owner.agent_id.clone()),
2177 owner_agent_name: self
2178 .owner_agent
2179 .as_ref()
2180 .map(|owner| owner.agent_name.clone()),
2181 origin_tool_call_id: self.origin_tool_call_id.clone(),
2182 origin_turn_id: self.origin_turn_id.clone(),
2183 owner_session_id: self.owner_session_id.clone(),
2184 }
2185 }
2186
2187 fn completion_event(&self) -> ShellCompletionEvent {
2188 let snapshot = self.job_snapshot();
2189 let (stdout_len, stdout_tail) =
2190 if let Some(output) = self.bounded_output_snapshot(false).ok().flatten() {
2191 (
2192 output.total_bytes,
2193 tail_text(&output.content, SHELL_COMPLETION_TAIL_BYTES),
2194 )
2195 } else {
2196 bounded_completion_tail(&self.stdout_buffer, SHELL_COMPLETION_TAIL_BYTES)
2197 };
2198 let (stderr_len, stderr_tail) = self
2199 .stderr_buffer
2200 .as_ref()
2201 .map(|buffer| bounded_completion_tail(buffer, SHELL_COMPLETION_TAIL_BYTES))
2202 .unwrap_or((0, String::new()));
2203 ShellCompletionEvent {
2204 task_id: snapshot.id,
2205 command: snapshot.command,
2206 status: snapshot.status,
2207 started_at: snapshot.started_at,
2208 cause: snapshot.cause,
2209 producer_reported: snapshot.producer_reported,
2210 exit_code: snapshot.exit_code,
2211 duration_ms: snapshot.elapsed_ms,
2212 stdout_tail,
2213 stderr_tail,
2214 stdout_len,
2215 stderr_len,
2216 evidence_ref: None,
2217 linked_task_id: snapshot.linked_task_id,
2218 owner_agent_id: snapshot.owner_agent_id,
2219 owner_agent_name: snapshot.owner_agent_name,
2220 origin_tool_call_id: snapshot.origin_tool_call_id,
2221 origin_turn_id: snapshot.origin_turn_id,
2222 owner_session_id: snapshot.owner_session_id,
2223 }
2224 }
2225
2226 fn completion_evidence(&self) -> ShellCompletionEvidence {
2227 let mut event = self.completion_event();
2228 let persisted_artifact = self.bounded_output.as_ref().and_then(|output| {
2229 output
2230 .lock()
2231 .unwrap_or_else(|error| error.into_inner())
2232 .persisted_artifact()
2233 });
2234 let persisted_artifact = persisted_artifact.or_else(|| {
2235 self.stdout_buffer
2236 .lock()
2237 .unwrap_or_else(|e| e.into_inner())
2238 .artifact()
2239 });
2240 if let Some(artifact) = persisted_artifact.as_ref() {
2241 event.evidence_ref = Some(artifact.artifact_id.clone());
2242 }
2243 let (stdout, stderr, stdout_omitted, stderr_omitted) =
2244 self.retained_output_bytes_with_omissions();
2245 ShellCompletionEvidence {
2246 event,
2247 stdout,
2248 stderr,
2249 stdout_omitted,
2250 stderr_omitted,
2251 persisted_artifact,
2252 }
2253 }
2254
2255 fn job_detail(&self) -> ShellJobDetail {
2256 let (stdout, stderr, _, _) = self.full_output();
2257 ShellJobDetail {
2258 snapshot: self.job_snapshot(),
2259 stdout,
2260 stderr,
2261 }
2262 }
2263 }
2264
2265 fn finish_background_reader(
2266 handle: std::thread::JoinHandle<()>,
2267 status: &ShellStatus,
2268 buffer: Option<&SharedRawOutput>,
2269 ) {
2270 // A killed Windows process can leave a pipe reader blocked even after its
2271 // Job Object has been closed. Cancellation must return promptly instead of
2272 // waiting for that reader to observe EOF. Other terminal states still join
2273 // so their final output is collected before the shell is discarded.
2274 #[cfg(windows)]
2275 if *status == ShellStatus::Killed {
2276 drop(handle);
2277 return;
2278 }
2279
2280 #[cfg(not(windows))]
2281 let _ = status;
2282
2283 // Bounded join (#52): after the process group is killed the reader
2284 // normally sees EOF immediately, but a descendant that escaped the group
2285 // (its own session/process group) keeps its inherited pipe write-end
2286 // open, so the reader stays blocked until that descendant exits on its
2287 // own. Joining unboundedly froze the foreground shell — and, through the
2288 // shell-manager lock, every other shell — for minutes. On timeout the
2289 // join is handed to a helper thread and we return; the reader thread
2290 // still finishes on its own once the pipe finally closes.
2291 let (done_tx, done_rx) = std::sync::mpsc::channel();
2292 std::thread::spawn(move || {
2293 let _ = handle.join();
2294 let _ = done_tx.send(());
2295 });
2296 if done_rx.recv_timeout(READER_JOIN_GRACE).is_ok() {
2297 return;
2298 }
2299 // The reader is still blocked in `read()` on a pipe a descendant refuses to
2300 // close. Previously both it and the helper thread above stayed alive for the
2301 // life of the process, the reader still appending into a buffer nobody would
2302 // ever read (#5472 finding 2). Abandoning the stream releases what it holds
2303 // and gives the reader an exit on its next wakeup, which also lets the
2304 // helper's `join` return.
2305 if let Some(buffer) = buffer {
2306 buffer
2307 .lock()
2308 .unwrap_or_else(|poison| poison.into_inner())
2309 .abandon();
2310 }
2311 }
2312
2313 impl Drop for BackgroundShell {
2314 fn drop(&mut self) {
2315 #[cfg(unix)]
2316 if self.ownership == ShellOwnership::PersistPending
2317 && let Some(process_group_id) = self.child.as_ref().and_then(ShellChild::process_id)
2318 {
2319 unregister_pending_persistent_process_group(process_group_id);
2320 }
2321 if self.ownership != ShellOwnership::Released
2322 && self.status == ShellStatus::Running
2323 && let Some(ref mut child) = self.child
2324 {
2325 #[cfg(windows)]
2326 match child {
2327 ShellChild::Process(proc) => {
2328 let _ = terminate_windows_job(self.windows_job.as_ref(), proc);
2329 }
2330 #[cfg(not(target_env = "ohos"))]
2331 ShellChild::Pty(child) => {
2332 let _ = child.kill();
2333 }
2334 }
2335 #[cfg(all(not(windows), unix))]
2336 {
2337 let _ = child.kill();
2338 match child {
2339 ShellChild::Process(proc) => {
2340 let _ = wait_child_bounded(proc, KILL_REAP_GRACE);
2341 }
2342 #[cfg(not(target_env = "ohos"))]
2343 ShellChild::Pty(child) => {
2344 let _ = child.wait();
2345 }
2346 }
2347 }
2348 #[cfg(all(not(windows), not(unix)))]
2349 {
2350 let _ = child.kill();
2351 let _ = child.wait();
2352 }
2353 }
2354 }
2355 }
2356
2357 #[cfg(all(unix, not(target_env = "ohos")))]
2358 pub fn inherited_interactive_terminal_refusal() -> Option<&'static str> {
2359 Some(
2360 "Inherited interactive terminal takeover is unavailable on Unix because foreground TTY \
2361 ownership cannot be transferred safely. Use `terminal_run` and `terminal_send` for \
2362 interactive PTY sessions, or launch the command in a new terminal. For non-interactive \
2363 work, omit `interactive: true`.",
2364 )
2365 }
2366
2367 #[cfg(all(unix, target_env = "ohos"))]
2368 pub fn inherited_interactive_terminal_refusal() -> Option<&'static str> {
2369 Some(
2370 "Inherited interactive terminal takeover is unavailable on Unix because foreground TTY \
2371 ownership cannot be transferred safely. Launch the command in a new terminal, or omit \
2372 `interactive: true` for non-interactive work.",
2373 )
2374 }
2375
2376 #[cfg(not(unix))]
2377 pub fn inherited_interactive_terminal_refusal() -> Option<&'static str> {
2378 None
2379 }
2380
2381 /// Manages background shell processes with optional sandboxing.
2382 pub struct ShellManager {
2383 processes: HashMap<String, BackgroundShell>,
2384 stale_jobs: HashMap<String, ShellJobSnapshot>,
2385 receipt_pins: HashSet<String>,
2386 receipt_witnesses: HashMap<String, ShellReceiptWitness>,
2387 default_workspace: PathBuf,
2388 sandbox_manager: SandboxManager,
2389 sandbox_policy: ExecutionSandboxPolicy,
2390 /// Only live wait futures hold strong references. A request cannot survive
2391 /// completion/cancellation and release a later wait or another session.
2392 active_waits: Vec<(String, Weak<AtomicBool>)>,
2393 /// Directory for lowercase-`bash` complete-output spill files
2394 /// (`None` = process temp dir). Overridable so tests can fault-inject a
2395 /// missing/unwritable spill location.
2396 output_spill_dir: Option<PathBuf>,
2397 }
2398
2399 impl std::fmt::Debug for ShellManager {
2400 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2401 f.debug_struct("ShellManager")
2402 .field("processes", &self.processes.len())
2403 .field("stale_jobs", &self.stale_jobs.len())
2404 .field("default_workspace", &self.default_workspace)
2405 .field("sandbox_policy", &self.sandbox_policy)
2406 .field(
2407 "active_waits",
2408 &self
2409 .active_waits
2410 .iter()
2411 .filter(|(_, wait)| wait.strong_count() > 0)
2412 .count(),
2413 )
2414 .finish()
2415 }
2416 }
2417
2418 impl ShellManager {
2419 pub fn pin_job_receipt(&mut self, task_id: &str) -> Result<()> {
2420 anyhow::ensure!(self.processes.contains_key(task_id), "job not tracked");
2421 self.receipt_pins.insert(task_id.to_string());
2422 Ok(())
2423 }
2424
2425 pub fn job_receipt_witness(&mut self, task_id: &str) -> Option<ShellReceiptWitness> {
2426 if !self.receipt_pins.contains(task_id) {
2427 return None;
2428 }
2429 if let Some(shell) = self.processes.get_mut(task_id) {
2430 shell.poll();
2431 return Some(ShellReceiptWitness::from_shell(shell));
2432 }
2433 self.receipt_witnesses.get(task_id).cloned()
2434 }
2435
2436 pub fn release_job_receipt(&mut self, task_id: &str) {
2437 self.receipt_pins.remove(task_id);
2438 self.receipt_witnesses.remove(task_id);
2439 }
2440
2441 fn require_session_owner(&self, task_id: &str, active_session_id: &str) -> Result<()> {
2442 let owned = self.processes.get(task_id).is_some_and(|shell| {
2443 !active_session_id.is_empty() && shell.owner_session_id == active_session_id
2444 }) || self.stale_jobs.get(task_id).is_some_and(|job| {
2445 !active_session_id.is_empty() && job.owner_session_id == active_session_id
2446 });
2447 if owned {
2448 Ok(())
2449 } else {
2450 // Do not disclose whether the id exists in another session.
2451 Err(anyhow!("Job {task_id} not found"))
2452 }
2453 }
2454
2455 /// Create a new `ShellManager` with default (no sandbox) policy.
2456 pub fn new(workspace: PathBuf) -> Self {
2457 Self {
2458 processes: HashMap::new(),
2459 stale_jobs: HashMap::new(),
2460 receipt_pins: HashSet::new(),
2461 receipt_witnesses: HashMap::new(),
2462 default_workspace: workspace,
2463 sandbox_manager: SandboxManager::new(),
2464 sandbox_policy: ExecutionSandboxPolicy::default(),
2465 active_waits: Vec::new(),
2466 output_spill_dir: None,
2467 }
2468 }
2469
2470 /// Point lowercase-`bash` complete-output spill files at `dir` instead of
2471 /// the process temp dir. Tests use a nonexistent dir to simulate a full or
2472 /// broken temp volume. (unix-only: the regression test that uses it drives
2473 /// a POSIX shell loop.)
2474 #[cfg(all(test, unix))]
2475 pub fn set_output_spill_dir_for_test(&mut self, dir: Option<PathBuf>) {
2476 self.output_spill_dir = dir;
2477 }
2478
2479 /// Insert a finished job without spawning. Count-bound tests would
2480 /// otherwise pay for 100+ live shells.
2481 #[cfg(any(test, feature = "test-support"))]
2482 pub fn seed_finished_record_for_test(&mut self, id: impl Into<String>, age: Duration) {
2483 let now = Instant::now();
2484 let started_at = now.checked_sub(age).unwrap_or(now);
2485 let finished_at_utc = chrono::Utc::now();
2486 let started_at_utc = chrono::Duration::from_std(age)
2487 .ok()
2488 .and_then(|age| finished_at_utc.checked_sub_signed(age))
2489 .unwrap_or(finished_at_utc);
2490 let id = id.into();
2491 self.processes.insert(
2492 id.clone(),
2493 BackgroundShell {
2494 id,
2495 command: String::new(),
2496 description: None,
2497 working_dir: self.default_workspace.clone(),
2498 status: ShellStatus::Completed,
2499 background: true,
2500 exit_code: Some(0),
2501 started_at,
2502 started_at_utc,
2503 finished_at: Some(now),
2504 finished_at_utc: Some(finished_at_utc),
2505 cause: Some(ShellTerminationCause::Producer),
2506 last_output_at: now,
2507 last_observed_output_len: 0,
2508 sandbox_type: SandboxType::None,
2509 linked_task_id: None,
2510 owner_agent: None,
2511 owner_session_id: String::new(),
2512 origin_tool_call_id: None,
2513 origin_turn_id: None,
2514 ownership: ShellOwnership::Managed,
2515 stdout_buffer: new_shared_raw_output(),
2516 stderr_buffer: Some(new_shared_raw_output()),
2517 bounded_output: None,
2518 heavy_permit: None,
2519 scratch: None,
2520 stdout_cursor: 0,
2521 stderr_cursor: 0,
2522 completion_reported: false,
2523 stdin: None,
2524 #[cfg(not(target_env = "ohos"))]
2525 pty_master: None,
2526 terminal_size: None,
2527 child: None,
2528 #[cfg(windows)]
2529 windows_job: None,
2530 #[cfg(unix)]
2531 parent_death_watch: None,
2532 stdout_thread: None,
2533 stderr_thread: None,
2534 work_lifecycle: None,
2535 lifecycle_seq: 0,
2536 last_lifecycle_status: None,
2537 last_lifecycle_bytes: 0,
2538 wait_failed: false,
2539 terminal_exit_confirmed: false,
2540 hold: None,
2541 },
2542 );
2543 }
2544
2545 /// Test-only observation of the workspace selected by runtime rebuilds.
2546 #[cfg(any(test, feature = "test-support"))]
2547 pub fn default_workspace(&self) -> &Path {
2548 &self.default_workspace
2549 }
2550
2551 /// Enable or disable bubblewrap passthrough (#2184).
2552 ///
2553 /// When enabled and `/usr/bin/bwrap` is executable on Linux, exec_shell
2554 /// commands are routed through bubblewrap for filesystem isolation.
2555 pub fn set_prefer_bwrap(&mut self, prefer: bool) {
2556 self.sandbox_manager.set_prefer_bwrap(prefer);
2557 }
2558
2559 pub fn set_tool_launcher(&mut self, launcher: Option<Vec<String>>) {
2560 self.sandbox_manager.set_tool_launcher(launcher);
2561 }
2562
2563 pub fn tool_launcher_active(&self) -> bool {
2564 self.sandbox_manager.tool_launcher_active()
2565 }
2566
2567 /// Move the fallback working directory. Callers that pass an explicit
2568 /// `working_dir` are unaffected; this only keeps `None` honest when a
2569 /// thread's workspace changes while its jobs are still tracked here.
2570 pub fn set_default_workspace(&mut self, workspace: PathBuf) {
2571 self.default_workspace = workspace;
2572 }
2573
2574 /// Set user-configured bwrap mount extensions (#5410): extra read-only
2575 /// roots and writable device nodes such as `/dev/null`.
2576 pub fn set_bwrap_extensions(&mut self, extensions: codewhale_sandbox::BwrapMountExtensions) {
2577 self.sandbox_manager.set_bwrap_extensions(extensions);
2578 }
2579
2580 /// Forward the opt-in sandbox read deny-list (S1, #5568) to the sandbox
2581 /// manager; `~` prefixes expand there.
2582 pub fn set_denied_read_subpaths(&mut self, paths: Vec<std::path::PathBuf>) {
2583 self.sandbox_manager.set_denied_read_subpaths(paths);
2584 }
2585
2586 /// Return the OS sandbox wrapper this shell manager is configured and able
2587 /// to apply to commands.
2588 pub fn configured_sandbox_type(&self) -> Option<SandboxType> {
2589 self.sandbox_manager.configured_sandbox()
2590 }
2591
2592 /// Prepare a program for a tool that runs workspace code outside
2593 /// `exec_shell`, under the policy and sandbox configuration a shell
2594 /// command would get in this session.
2595 pub fn prepare_runner(
2596 &self,
2597 program: &str,
2598 args: Vec<String>,
2599 cwd: &Path,
2600 project: &Path,
2601 timeout: Duration,
2602 policy_override: Option<ExecutionSandboxPolicy>,
2603 ) -> ExecEnv {
2604 let policy = policy_override.unwrap_or_else(|| self.sandbox_policy.clone());
2605 let spec =
2606 CommandSpec::program(program, args, cwd.to_path_buf(), timeout).with_policy(policy);
2607 let mut exec_env = self.sandbox_manager.prepare(&spec);
2608 exec_env.env.insert(
2609 AGENT_PROJECT_ENV.to_string(),
2610 project.to_string_lossy().into_owned(),
2611 );
2612 exec_env
2613 }
2614
2615 pub fn validate_background_job(
2616 &self,
2617 command: &str,
2618 cwd: &Path,
2619 timeout_ms: u64,
2620 policy: &ExecutionSandboxPolicy,
2621 env: &HashMap<String, String>,
2622 ) -> Result<()> {
2623 validate_shell_working_dir(cwd, false)?;
2624 let spec = CommandSpec::shell(
2625 command,
2626 cwd.to_path_buf(),
2627 Duration::from_millis(timeout_ms.clamp(1_000, 600_000)),
2628 )
2629 .with_policy(policy.clone())
2630 .with_env(env.clone());
2631 let prepared = self
2632 .sandbox_manager
2633 .try_prepare(&spec)
2634 .map_err(anyhow::Error::msg)?;
2635 if matches!(spec.sandbox_policy, ExecutionSandboxPolicy::ReadOnly { .. }) {
2636 require_native_readonly_execution(&prepared)?;
2637 }
2638 Ok(())
2639 }
2640
2641 fn register_shell_wait(&mut self, session_id: &str) -> Arc<AtomicBool> {
2642 self.active_waits
2643 .retain(|(_, wait)| wait.strong_count() > 0);
2644 let detach = Arc::new(AtomicBool::new(false));
2645 self.active_waits
2646 .push((session_id.to_string(), Arc::downgrade(&detach)));
2647 detach
2648 }
2649
2650 /// Release the owning session's currently active shell waits without
2651 /// stopping their processes. This never queues a request for future work.
2652 pub fn request_shell_wait_detach(&mut self, session_id: &str) -> bool {
2653 let mut requested = false;
2654 self.active_waits.retain(|(owner, wait)| {
2655 let Some(wait) = wait.upgrade() else {
2656 return false;
2657 };
2658 if !session_id.is_empty() && owner == session_id {
2659 wait.store(true, Ordering::Release);
2660 requested = true;
2661 }
2662 true
2663 });
2664 requested
2665 }
2666
2667 #[cfg(any(test, feature = "test-support"))]
2668 pub fn shell_wait_active_for_test(&self, session_id: &str) -> bool {
2669 self.active_waits
2670 .iter()
2671 .any(|(owner, wait)| owner == session_id && wait.strong_count() > 0)
2672 }
2673
2674 #[cfg(any(test, feature = "test-support"))]
2675 pub fn register_shell_wait_for_test(&mut self, session_id: &str) -> Arc<AtomicBool> {
2676 self.register_shell_wait(session_id)
2677 }
2678
2679 /// Execute a shell command with stdin/TTY options plus an extra env-var map
2680 /// that is merged into the spawned process environment. Used by the
2681 /// `shell_env` hook injection path (#456).
2682 #[allow(clippy::too_many_arguments)]
2683 #[cfg(any(test, feature = "test-support"))]
2684 pub fn execute_with_options_env(
2685 &mut self,
2686 command: &str,
2687 working_dir: Option<&str>,
2688 timeout_ms: u64,
2689 background: bool,
2690 stdin_data: Option<&str>,
2691 tty: bool,
2692 policy_override: Option<ExecutionSandboxPolicy>,
2693 extra_env: HashMap<String, String>,
2694 ) -> Result<ShellResult> {
2695 self.execute_with_options_env_for_owner(
2696 command,
2697 working_dir,
2698 timeout_ms,
2699 background,
2700 stdin_data,
2701 tty,
2702 policy_override,
2703 extra_env,
2704 None,
2705 )
2706 }
2707
2708 /// Launch a parent-owned job stamped to the immutable root session.
2709 #[allow(clippy::too_many_arguments)]
2710 pub fn execute_with_options_env_for_session(
2711 &mut self,
2712 command: &str,
2713 working_dir: Option<&str>,
2714 timeout_ms: u64,
2715 background: bool,
2716 stdin_data: Option<&str>,
2717 tty: bool,
2718 policy_override: Option<ExecutionSandboxPolicy>,
2719 extra_env: HashMap<String, String>,
2720 owner_session_id: &str,
2721 ) -> Result<ShellResult> {
2722 self.execute_with_options_env_for_owner_and_work(
2723 command,
2724 None,
2725 working_dir,
2726 timeout_ms,
2727 background,
2728 stdin_data,
2729 tty,
2730 policy_override,
2731 extra_env,
2732 None,
2733 owner_session_id.to_string(),
2734 None,
2735 None,
2736 None,
2737 None,
2738 false,
2739 (1_000, 600_000),
2740 )
2741 }
2742
2743 /// Same as `execute_with_options_env`, with optional background-job owner
2744 /// attribution for sub-agent launched jobs.
2745 #[allow(clippy::too_many_arguments)]
2746 #[cfg(any(test, feature = "test-support"))]
2747 pub fn execute_with_options_env_for_owner(
2748 &mut self,
2749 command: &str,
2750 working_dir: Option<&str>,
2751 timeout_ms: u64,
2752 background: bool,
2753 stdin_data: Option<&str>,
2754 tty: bool,
2755 policy_override: Option<ExecutionSandboxPolicy>,
2756 extra_env: HashMap<String, String>,
2757 owner_agent: Option<ShellJobOwner>,
2758 ) -> Result<ShellResult> {
2759 self.execute_with_options_env_for_owner_and_work(
2760 command,
2761 None,
2762 working_dir,
2763 timeout_ms,
2764 background,
2765 stdin_data,
2766 tty,
2767 policy_override,
2768 extra_env,
2769 owner_agent,
2770 String::new(),
2771 None,
2772 None,
2773 None,
2774 None,
2775 false,
2776 (1_000, 600_000),
2777 )
2778 }
2779
2780 /// Test-only owner-aware launch with an explicit immutable session owner.
2781 #[allow(clippy::too_many_arguments)]
2782 #[cfg(any(test, feature = "test-support"))]
2783 pub fn execute_with_options_env_for_owner_and_session(
2784 &mut self,
2785 command: &str,
2786 working_dir: Option<&str>,
2787 timeout_ms: u64,
2788 background: bool,
2789 stdin_data: Option<&str>,
2790 tty: bool,
2791 policy_override: Option<ExecutionSandboxPolicy>,
2792 extra_env: HashMap<String, String>,
2793 owner_agent: Option<ShellJobOwner>,
2794 owner_session_id: &str,
2795 ) -> Result<ShellResult> {
2796 self.execute_with_options_env_for_owner_and_work(
2797 command,
2798 None,
2799 working_dir,
2800 timeout_ms,
2801 background,
2802 stdin_data,
2803 tty,
2804 policy_override,
2805 extra_env,
2806 owner_agent,
2807 owner_session_id.to_string(),
2808 None,
2809 None,
2810 None,
2811 None,
2812 false,
2813 (1_000, 600_000),
2814 )
2815 }
2816
2817 /// Owner-aware execution with an optional Work Graph lifecycle sink.
2818 #[allow(clippy::too_many_arguments)]
2819 pub(super) fn execute_with_options_env_for_owner_and_work(
2820 &mut self,
2821 command: &str,
2822 program_args: Option<(&str, &[String])>,
2823 working_dir: Option<&str>,
2824 timeout_ms: u64,
2825 background: bool,
2826 stdin_data: Option<&str>,
2827 tty: bool,
2828 policy_override: Option<ExecutionSandboxPolicy>,
2829 extra_env: HashMap<String, String>,
2830 owner_agent: Option<ShellJobOwner>,
2831 owner_session_id: String,
2832 origin_tool_call_id: Option<String>,
2833 origin_turn_id: Option<String>,
2834 work_lifecycle: Option<ShellWorkLifecycle>,
2835 readonly_workspace: Option<&std::path::Path>,
2836 persist_pending: bool,
2837 timeout_bounds_ms: (u64, u64),
2838 ) -> Result<ShellResult> {
2839 self.execute_with_options_env_for_owner_and_work_hardened(
2840 command,
2841 program_args,
2842 working_dir,
2843 timeout_ms,
2844 background,
2845 stdin_data,
2846 tty,
2847 policy_override,
2848 extra_env,
2849 owner_agent,
2850 owner_session_id,
2851 origin_tool_call_id,
2852 origin_turn_id,
2853 work_lifecycle,
2854 readonly_workspace.map_or(
2855 ReadonlyCommandHardening::None,
2856 ReadonlyCommandHardening::StrictReadOnly,
2857 ),
2858 persist_pending,
2859 timeout_bounds_ms,
2860 )
2861 }
2862
2863 #[allow(clippy::too_many_arguments)]
2864 fn execute_with_options_env_for_owner_and_work_hardened(
2865 &mut self,
2866 command: &str,
2867 program_args: Option<(&str, &[String])>,
2868 working_dir: Option<&str>,
2869 timeout_ms: u64,
2870 background: bool,
2871 stdin_data: Option<&str>,
2872 tty: bool,
2873 policy_override: Option<ExecutionSandboxPolicy>,
2874 extra_env: HashMap<String, String>,
2875 owner_agent: Option<ShellJobOwner>,
2876 owner_session_id: String,
2877 origin_tool_call_id: Option<String>,
2878 origin_turn_id: Option<String>,
2879 work_lifecycle: Option<ShellWorkLifecycle>,
2880 readonly_hardening: ReadonlyCommandHardening<'_>,
2881 persist_pending: bool,
2882 timeout_bounds_ms: (u64, u64),
2883 ) -> Result<ShellResult> {
2884 // Log execution via ShellDispatcher when SHELL_DISPATCHER_LOG is set.
2885 codewhale_sandbox::shell_dispatcher::ShellDispatcher::log_exec(command);
2886
2887 let work_dir = working_dir.map_or_else(|| self.default_workspace.clone(), PathBuf::from);
2888 validate_shell_working_dir(&work_dir, working_dir.is_none()).map_err(|error| {
2889 let message = error.to_string();
2890 error.context(ShellLaunchNotStarted).context(message)
2891 })?;
2892
2893 let timeout_ms = timeout_ms.clamp(timeout_bounds_ms.0, timeout_bounds_ms.1);
2894
2895 // Use override policy if provided, otherwise use the manager's policy
2896 let policy = policy_override.unwrap_or_else(|| self.sandbox_policy.clone());
2897
2898 // Create command spec and prepare sandboxed environment
2899 let spec = if let Some((program, args)) = program_args {
2900 anyhow::ensure!(
2901 matches!(readonly_hardening, ReadonlyCommandHardening::None),
2902 "explicit argv cannot use shell read-only validation"
2903 );
2904 CommandSpec::program(
2905 program,
2906 args.to_vec(),
2907 work_dir.clone(),
2908 Duration::from_millis(timeout_ms),
2909 )
2910 } else {
2911 match readonly_hardening {
2912 ReadonlyCommandHardening::StrictReadOnly(workspace) => {
2913 if readonly_command_needs_shell(command) {
2914 let script = hardened_readonly_script(command, workspace)?;
2915 CommandSpec::shell(
2916 &script,
2917 work_dir.clone(),
2918 Duration::from_millis(timeout_ms),
2919 )
2920 } else {
2921 let (program, args) = hardened_readonly_argv(command)?;
2922 let program = resolve_readonly_program(&program, workspace)?;
2923 CommandSpec::program(
2924 program.to_str().ok_or_else(|| {
2925 anyhow!("read-only executable path is not valid UTF-8")
2926 })?,
2927 args,
2928 work_dir.clone(),
2929 Duration::from_millis(timeout_ms),
2930 )
2931 }
2932 }
2933 ReadonlyCommandHardening::GitReadOnlyIfAdmitted { workspace, .. }
2934 if command_is_admitted_readonly_git(command) =>
2935 {
2936 if readonly_command_needs_shell(command) {
2937 let script = hardened_readonly_script(command, workspace)?;
2938 CommandSpec::shell(
2939 &script,
2940 work_dir.clone(),
2941 Duration::from_millis(timeout_ms),
2942 )
2943 } else {
2944 let (program, args) = hardened_readonly_argv(command)?;
2945 let program = resolve_readonly_program(&program, workspace)?;
2946 CommandSpec::program(
2947 program.to_str().ok_or_else(|| {
2948 anyhow!("read-only executable path is not valid UTF-8")
2949 })?,
2950 args,
2951 work_dir.clone(),
2952 Duration::from_millis(timeout_ms),
2953 )
2954 }
2955 }
2956 ReadonlyCommandHardening::GitReadOnlyIfAdmitted { .. }
2957 | ReadonlyCommandHardening::None => {
2958 CommandSpec::shell(command, work_dir.clone(), Duration::from_millis(timeout_ms))
2959 }
2960 }
2961 };
2962 let spec = spec.with_policy(policy).with_env(extra_env);
2963 let spec = if matches!(spec.sandbox_policy, ExecutionSandboxPolicy::ReadOnly { .. }) {
2964 spec.with_private_tmp()
2965 } else {
2966 spec
2967 };
2968 let mut exec_env = self.sandbox_manager.try_prepare(&spec).map_err(|message| {
2969 anyhow::Error::msg(message.clone())
2970 .context(ShellLaunchNotStarted)
2971 .context(message)
2972 })?;
2973 let needs_native_readonly = match readonly_hardening {
2974 ReadonlyCommandHardening::StrictReadOnly(_) => false,
2975 ReadonlyCommandHardening::None => true,
2976 ReadonlyCommandHardening::GitReadOnlyIfAdmitted {
2977 require_native_sandbox,
2978 ..
2979 } => require_native_sandbox,
2980 };
2981 if matches!(spec.sandbox_policy, ExecutionSandboxPolicy::ReadOnly { .. })
2982 && needs_native_readonly
2983 {
2984 // Arbitrary code with a read-only policy needs kernel enforcement;
2985 // only the separately hardened argv subset may run without it.
2986 require_native_readonly_execution(&exec_env).map_err(|error| {
2987 let message = error.to_string();
2988 error.context(ShellLaunchNotStarted).context(message)
2989 })?;
2990 }
2991
2992 if background {
2993 let bounded_output = !tty
2994 && !persist_pending
2995 && (program_args.is_some() || timeout_bounds_ms == (1, BASH_MAX_TIMEOUT_MS));
2996 self.spawn_background_sandboxed(
2997 command,
2998 &work_dir,
2999 &mut exec_env,
3000 None,
3001 stdin_data,
3002 tty,
3003 ShellSpawnContext {
3004 owner_agent,
3005 owner_session_id,
3006 origin_tool_call_id,
3007 origin_turn_id,
3008 work_lifecycle,
3009 },
3010 persist_pending,
3011 bounded_output,
3012 )
3013 } else {
3014 if tty {
3015 return Err(anyhow!(
3016 "TTY mode requires background execution (set background: true)."
3017 ));
3018 }
3019 Self::execute_sync_sandboxed(command, &work_dir, timeout_ms, stdin_data, &exec_env)
3020 }
3021 }
3022
3023 /// Interactive variant that accepts extra env vars (#456 shell_env hook).
3024 pub fn execute_interactive_with_policy_env(
3025 &mut self,
3026 command: &str,
3027 working_dir: Option<&str>,
3028 timeout_ms: u64,
3029 policy_override: Option<ExecutionSandboxPolicy>,
3030 extra_env: HashMap<String, String>,
3031 ) -> Result<ShellResult> {
3032 codewhale_sandbox::shell_dispatcher::ShellDispatcher::log_exec(command);
3033
3034 // A new Unix process group that inherits the terminal is not its
3035 // foreground owner. Letting it read stdin triggers SIGTTIN; sharing
3036 // Codewhale's group instead would make cooked-mode Ctrl+C terminate
3037 // both parent and child. Until this path owns a complete POSIX job-
3038 // control lease, fail closed before spawning. Persistent PTY tools
3039 // already provide a safe interactive lane without taking over the
3040 // operator's live terminal.
3041 if let Some(message) = inherited_interactive_terminal_refusal() {
3042 return Err(anyhow!(message));
3043 }
3044
3045 let work_dir = working_dir.map_or_else(|| self.default_workspace.clone(), PathBuf::from);
3046 validate_shell_working_dir(&work_dir, working_dir.is_none())?;
3047
3048 let timeout_ms = timeout_ms.clamp(1000, 600_000);
3049 let policy = policy_override.unwrap_or_else(|| self.sandbox_policy.clone());
3050
3051 let spec = CommandSpec::shell(command, work_dir.clone(), Duration::from_millis(timeout_ms))
3052 .with_policy(policy)
3053 .with_env(extra_env);
3054 let exec_env = self
3055 .sandbox_manager
3056 .try_prepare(&spec)
3057 .map_err(anyhow::Error::msg)?;
3058 if matches!(spec.sandbox_policy, ExecutionSandboxPolicy::ReadOnly { .. }) {
3059 require_native_readonly_execution(&exec_env)?;
3060 }
3061
3062 Self::execute_interactive_sandboxed(command, &work_dir, timeout_ms, &exec_env)
3063 }
3064
3065 /// Execute command synchronously with timeout (sandboxed).
3066 fn execute_sync_sandboxed(
3067 original_command: &str,
3068 working_dir: &std::path::Path,
3069 timeout_ms: u64,
3070 stdin_data: Option<&str>,
3071 exec_env: &ExecEnv,
3072 ) -> Result<ShellResult> {
3073 let started = Instant::now();
3074 let deadline = started + Duration::from_millis(timeout_ms);
3075 let sandbox_type = exec_env.sandbox_type;
3076 let sandboxed = exec_env.is_sandboxed();
3077
3078 // Build the command from ExecEnv
3079 let program = exec_env.program();
3080 let args = exec_env.args();
3081
3082 let mut cmd = Command::new(program);
3083 codewhale_util::utils::suppress_console_window(&mut cmd);
3084 push_shell_args(&mut cmd, program, args);
3085 cmd.current_dir(working_dir)
3086 .stdout(Stdio::piped())
3087 .stderr(Stdio::piped());
3088 install_parent_death_signal(&mut cmd);
3089
3090 // Without input, stdin is closed rather than inherited: an unexpected
3091 // read (`cat`, a prompt) gets EOF instead of blocking on, or reading,
3092 // the operator's terminal until the timeout.
3093 cmd.stdin(if stdin_data.is_some() {
3094 Stdio::piped()
3095 } else {
3096 Stdio::null()
3097 });
3098
3099 child_env::apply_to_command(&mut cmd, child_env::string_map_env(&exec_env.env));
3100 remove_readonly_redirect_env(&mut cmd, &exec_env.env);
3101
3102 // Leave raw mode before spawn; the guard restores it only if raw mode
3103 // was active on entry (issue #1690).
3104 let _raw_mode = codewhale_runtime::host_terminal::suspend_raw_mode();
3105
3106 let (mut child, tree) = codewhale_runtime::process_tree::spawn_contained_std(&mut cmd)
3107 .with_context(|| format!("Failed to execute: {original_command}"))?;
3108
3109 let run = (|| -> Result<_> {
3110 let stdout = child.stdout.take().context("Failed to capture stdout")?;
3111 let stderr = child.stderr.take().context("Failed to capture stderr")?;
3112 let stdout_rx = spawn_sync_reader_thread(stdout);
3113 let stderr_rx = spawn_sync_reader_thread(stderr);
3114 if let Some(input) = stdin_data
3115 && let Some(mut stdin) = child.stdin.take()
3116 {
3117 set_foreground_stdin_nonblocking(&stdin).context("Failed to prepare stdin")?;
3118 if !write_foreground_input(&mut stdin, input.as_bytes(), || {
3119 deadline.saturating_duration_since(Instant::now())
3120 })
3121 .context("Failed to write to stdin")?
3122 {
3123 return Ok((stdout_rx, stderr_rx, false));
3124 }
3125 }
3126
3127 #[cfg(unix)]
3128 let completed = wait_leader_exit_until(&child, deadline).unwrap_or(true)
3129 && tree.kill_if_leader_exited();
3130 #[cfg(not(unix))]
3131 let completed = child
3132 .wait_timeout(deadline.saturating_duration_since(Instant::now()))?
3133 .is_some();
3134 Ok((stdout_rx, stderr_rx, completed))
3135 })();
3136
3137 let _ = tree.kill().or_else(|_| child.kill());
3138 tree.disarm();
3139 drop(tree);
3140 let status = child.wait();
3141 let (stdout_rx, stderr_rx, completed) = run?;
3142 let status = if completed {
3143 Some(ShellExitStatus::from_std(status?))
3144 } else {
3145 status.ok().map(ShellExitStatus::from_std)
3146 };
3147 let exit_code = status.and_then(|status| status.code);
3148 let stdout = recv_sync_reader_output(&stdout_rx);
3149 let stderr = recv_sync_reader_output(&stderr_rx);
3150 let (stdout, stdout_meta) = truncate_with_meta(&String::from_utf8_lossy(&stdout));
3151 let stderr = String::from_utf8_lossy(&stderr);
3152 let sandbox_denied = completed
3153 && SandboxManager::was_denied(
3154 sandbox_type,
3155 exit_code
3156 .and_then(|code| i32::try_from(code).ok())
3157 .unwrap_or(-1),
3158 &stderr,
3159 );
3160 let (stderr, stderr_meta) = truncate_with_meta(&stderr);
3161
3162 Ok(ShellResult {
3163 task_id: None,
3164 status: if !completed {
3165 ShellStatus::TimedOut
3166 } else if status.is_some_and(|status| status.success) {
3167 ShellStatus::Completed
3168 } else {
3169 ShellStatus::Failed
3170 },
3171 exit_code,
3172 stdout,
3173 stderr,
3174 duration_ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
3175 stdout_len: stdout_meta.original_len,
3176 stderr_len: stderr_meta.original_len,
3177 stdout_omitted: stdout_meta.omitted,
3178 stderr_omitted: stderr_meta.omitted,
3179 stdout_truncated: stdout_meta.truncated,
3180 stderr_truncated: stderr_meta.truncated,
3181 sandboxed,
3182 sandbox_type: sandboxed.then(|| sandbox_type.to_string()),
3183 sandbox_denied,
3184 })
3185 }
3186
3187 /// Execute command interactively with timeout (sandboxed).
3188 fn execute_interactive_sandboxed(
3189 original_command: &str,
3190 working_dir: &std::path::Path,
3191 timeout_ms: u64,
3192 exec_env: &ExecEnv,
3193 ) -> Result<ShellResult> {
3194 let started = Instant::now();
3195 let timeout = Duration::from_millis(timeout_ms);
3196 let sandbox_type = exec_env.sandbox_type;
3197 let sandboxed = exec_env.is_sandboxed();
3198
3199 let program = exec_env.program();
3200 let args = exec_env.args();
3201
3202 let mut cmd = Command::new(program);
3203 codewhale_util::utils::suppress_console_window(&mut cmd);
3204 push_shell_args(&mut cmd, program, args);
3205 cmd.current_dir(working_dir)
3206 .stdin(Stdio::inherit())
3207 .stdout(Stdio::inherit())
3208 .stderr(Stdio::inherit());
3209 #[cfg(unix)]
3210 {
3211 cmd.process_group(0);
3212 }
3213 install_parent_death_signal(&mut cmd);
3214
3215 // Leave raw mode before spawn; the guard restores it only if raw mode
3216 // was active on entry (issue #1690).
3217 let _raw_mode = codewhale_runtime::host_terminal::suspend_raw_mode();
3218
3219 child_env::apply_to_command(&mut cmd, child_env::string_map_env(&exec_env.env));
3220
3221 let mut child = cmd
3222 .spawn()
3223 .with_context(|| format!("Failed to execute: {original_command}"))?;
3224 #[cfg(windows)]
3225 let windows_job = attach_windows_job(&child, original_command);
3226
3227 if let Some(status) = child.wait_timeout(timeout)? {
3228 let status = ShellExitStatus::from_std(status);
3229 #[cfg(windows)]
3230 terminate_and_close_windows_job(windows_job);
3231 Ok(ShellResult {
3232 task_id: None,
3233 status: if status.success {
3234 ShellStatus::Completed
3235 } else {
3236 ShellStatus::Failed
3237 },
3238 exit_code: status.code,
3239 stdout: String::new(),
3240 stderr: String::new(),
3241 duration_ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
3242 stdout_len: 0,
3243 stderr_len: 0,
3244 stdout_omitted: 0,
3245 stderr_omitted: 0,
3246 stdout_truncated: false,
3247 stderr_truncated: false,
3248 sandboxed,
3249 sandbox_type: if sandboxed {
3250 Some(sandbox_type.to_string())
3251 } else {
3252 None
3253 },
3254 sandbox_denied: false,
3255 })
3256 } else {
3257 #[cfg(unix)]
3258 let _ = kill_child_process_group(&mut child);
3259 #[cfg(windows)]
3260 let _ = terminate_child_and_close_windows_job(windows_job, &mut child);
3261 #[cfg(all(not(unix), not(windows)))]
3262 let _ = child.kill();
3263 let status = child.wait().ok();
3264
3265 Ok(ShellResult {
3266 task_id: None,
3267 status: ShellStatus::TimedOut,
3268 exit_code: status
3269 .map(ShellExitStatus::from_std)
3270 .and_then(|status| status.code),
3271 stdout: String::new(),
3272 stderr: String::new(),
3273 duration_ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
3274 stdout_len: 0,
3275 stderr_len: 0,
3276 stdout_omitted: 0,
3277 stderr_omitted: 0,
3278 stdout_truncated: false,
3279 stderr_truncated: false,
3280 sandboxed,
3281 sandbox_type: if sandboxed {
3282 Some(sandbox_type.to_string())
3283 } else {
3284 None
3285 },
3286 sandbox_denied: false,
3287 })
3288 }
3289 }
3290
3291 /// Spawn a background process (sandboxed).
3292 #[allow(clippy::too_many_arguments)]
3293 fn spawn_background_sandboxed(
3294 &mut self,
3295 original_command: &str,
3296 working_dir: &std::path::Path,
3297 exec_env: &mut ExecEnv,
3298 heavy_permit: Option<HeavyCommandPermit>,
3299 stdin_data: Option<&str>,
3300 tty: bool,
3301 spawn_context: ShellSpawnContext,
3302 persist_pending: bool,
3303 small_contract_mode: bool,
3304 ) -> Result<ShellResult> {
3305 let ShellSpawnContext {
3306 owner_agent,
3307 owner_session_id,
3308 origin_tool_call_id,
3309 origin_turn_id,
3310 work_lifecycle,
3311 } = spawn_context;
3312 let task_id = format!("shell_{}", Uuid::new_v4().simple());
3313 let mut spawn_guard =
3314 ShellSpawnIntentGuard::new(work_lifecycle, &task_id, original_command);
3315 // The guard owns the registration outcome: when bookkeeping could not
3316 // bind this operation, nothing below may publish to it (#6435).
3317 let work_lifecycle = spawn_guard.lifecycle.clone();
3318 let started = Instant::now();
3319 let started_at_utc = chrono::Utc::now();
3320 let sandbox_type = exec_env.sandbox_type;
3321 let sandboxed = exec_env.is_sandboxed();
3322
3323 // Build the command from ExecEnv
3324 let program = exec_env.program();
3325 let args = exec_env.args();
3326
3327 #[cfg(target_env = "ohos")]
3328 if tty {
3329 return Err(anyhow!(
3330 "TTY shell mode is not supported on HarmonyOS/OpenHarmony yet."
3331 ));
3332 }
3333
3334 let spool = !small_contract_mode
3335 && !persist_pending
3336 && codewhale_runtime::artifacts::is_valid_session_id(&owner_session_id);
3337 let stdout_buffer = RawOutputBuffer::for_job(
3338 if small_contract_mode {
3339 RAW_STREAM_SETTLED_TAIL_BYTES
3340 } else {
3341 RAW_STREAM_MAX_BYTES
3342 },
3343 spool,
3344 );
3345 let stderr_buffer = if tty || persist_pending || small_contract_mode {
3346 None
3347 } else {
3348 Some(RawOutputBuffer::for_job(RAW_STREAM_MAX_BYTES, spool))
3349 };
3350 let bounded_output =
3351 small_contract_mode.then(|| {
3352 let session_artifact = codewhale_runtime::artifacts::is_valid_session_id(
3353 &owner_session_id,
3354 )
3355 .then(|| SessionArtifactSpec {
3356 session_id: owner_session_id.clone(),
3357 artifact_id: codewhale_runtime::artifacts::artifact_id_for_tool_call(&task_id),
3358 });
3359 Arc::new(Mutex::new(BoundedOutputAccumulator::new_in(
3360 self.output_spill_dir.as_deref(),
3361 session_artifact,
3362 )))
3363 });
3364
3365 #[cfg(windows)]
3366 let mut windows_job = None;
3367 #[cfg(unix)]
3368 let mut parent_death_watch = None;
3369
3370 #[cfg(not(target_env = "ohos"))]
3371 let mut pty_master = None;
3372 let (child, stdin, stdout_thread, stderr_thread) = if tty {
3373 #[cfg(target_env = "ohos")]
3374 unreachable!("OHOS TTY mode returns before PTY setup");
3375
3376 #[cfg(not(target_env = "ohos"))]
3377 {
3378 let pty_system = native_pty_system();
3379 let pair = pty_system
3380 .openpty(PtySize {
3381 rows: 24,
3382 cols: 80,
3383 pixel_width: 0,
3384 pixel_height: 0,
3385 })
3386 .context(ShellLaunchNotStarted)
3387 .context("Failed to open PTY")?;
3388
3389 let mut child = exec_env
3390 .spawn_pty(pair.slave, working_dir)
3391 .with_context(|| format!("Failed to spawn PTY command: {original_command}"))?;
3392
3393 let reader = match pair.master.try_clone_reader() {
3394 Ok(reader) => reader,
3395 Err(err) => {
3396 let _ = child.kill();
3397 let _ = child.wait();
3398 return Err(err).context("Failed to clone PTY reader");
3399 }
3400 };
3401 let writer = match pair.master.take_writer() {
3402 Ok(writer) => writer,
3403 Err(err) => {
3404 let _ = child.kill();
3405 let _ = child.wait();
3406 return Err(err).context("Failed to take PTY writer");
3407 }
3408 };
3409 let stdout_thread = Some(spawn_reader_thread(reader, Arc::clone(&stdout_buffer)));
3410 pty_master = Some(pair.master);
3411
3412 (
3413 ShellChild::Pty(child),
3414 Some(StdinWriter::Pty(writer)),
3415 stdout_thread,
3416 None,
3417 )
3418 }
3419 } else if persist_pending {
3420 let mut cmd = Command::new(program);
3421 codewhale_util::utils::suppress_console_window(&mut cmd);
3422 push_shell_args(&mut cmd, program, args);
3423 cmd.current_dir(working_dir)
3424 .stdin(Stdio::null())
3425 .stdout(Stdio::null())
3426 .stderr(Stdio::null());
3427 #[cfg(unix)]
3428 {
3429 cmd.process_group(0);
3430 }
3431 // Deliberately no parent-death cleanup: a staged service can be
3432 // handed to the user (`ShellOwnership::Released`) and must then
3433 // outlive the TUI (#6654).
3434
3435 child_env::apply_to_command(&mut cmd, child_env::string_map_env(&exec_env.env));
3436 remove_readonly_redirect_env(&mut cmd, &exec_env.env);
3437
3438 let child = exec_env.spawn_background(cmd).with_context(|| {
3439 format!("Failed to spawn persistent service: {original_command}")
3440 })?;
3441 (ShellChild::Process(child), None, None, None)
3442 } else {
3443 let mut cmd = Command::new(program);
3444 codewhale_util::utils::suppress_console_window(&mut cmd);
3445 push_shell_args(&mut cmd, program, args);
3446 cmd.current_dir(working_dir).stdin(Stdio::piped());
3447 let combined_reader = if small_contract_mode {
3448 let (reader, stdout, stderr) =
3449 shared_output_pipe().context("Failed to create combined shell output pipe")?;
3450 cmd.stdout(Stdio::from(stdout)).stderr(Stdio::from(stderr));
3451 Some(reader)
3452 } else {
3453 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
3454 None
3455 };
3456 #[cfg(unix)]
3457 {
3458 cmd.process_group(0);
3459 }
3460
3461 child_env::apply_to_command(&mut cmd, child_env::string_map_env(&exec_env.env));
3462 remove_readonly_redirect_env(&mut cmd, &exec_env.env);
3463
3464 let mut child = exec_env
3465 .spawn_background(cmd)
3466 .with_context(|| format!("Failed to spawn background: {original_command}"))?;
3467 // Managed children die with the TUI (#6654); unlike the
3468 // persistent branch above, nobody can take ownership of them.
3469 #[cfg(unix)]
3470 {
3471 parent_death_watch = watch_process_group_for_parent_death(child.id())
3472 .inspect_err(|err| {
3473 tracing::warn!(
3474 "background shell {task_id} has no parent-death cleanup: {err}"
3475 );
3476 })
3477 .ok();
3478 }
3479 #[cfg(windows)]
3480 {
3481 windows_job = attach_windows_job(&child, original_command);
3482 }
3483
3484 let stdin_handle = child.stdin.take().map(StdinWriter::Pipe);
3485
3486 let (stdout_thread, stderr_thread) =
3487 if let (Some(reader), Some(output)) = (combined_reader, bounded_output.as_ref()) {
3488 (
3489 Some(spawn_bounded_reader_thread(
3490 reader,
3491 Arc::clone(output),
3492 Arc::clone(&stdout_buffer),
3493 )),
3494 None,
3495 )
3496 } else {
3497 let stdout_handle = child.stdout.take().ok_or_else(|| {
3498 #[cfg(windows)]
3499 terminate_unregistered_process(&mut child, windows_job.as_ref());
3500 #[cfg(not(windows))]
3501 terminate_unregistered_process(&mut child);
3502 anyhow!("Failed to capture stdout")
3503 })?;
3504 let stderr_handle = child.stderr.take().ok_or_else(|| {
3505 #[cfg(windows)]
3506 terminate_unregistered_process(&mut child, windows_job.as_ref());
3507 #[cfg(not(windows))]
3508 terminate_unregistered_process(&mut child);
3509 anyhow!("Failed to capture stderr")
3510 })?;
3511 (
3512 Some(spawn_reader_thread(
3513 stdout_handle,
3514 Arc::clone(&stdout_buffer),
3515 )),
3516 stderr_buffer
3517 .as_ref()
3518 .map(|buffer| spawn_reader_thread(stderr_handle, Arc::clone(buffer))),
3519 )
3520 };
3521
3522 (
3523 ShellChild::Process(child),
3524 stdin_handle,
3525 stdout_thread,
3526 stderr_thread,
3527 )
3528 };
3529
3530 let mut bg_shell = BackgroundShell {
3531 id: task_id.clone(),
3532 command: original_command.to_string(),
3533 description: None,
3534 working_dir: working_dir.to_path_buf(),
3535 status: ShellStatus::Running,
3536 background: true,
3537 exit_code: None,
3538 started_at: started,
3539 started_at_utc,
3540 finished_at: None,
3541 finished_at_utc: None,
3542 cause: None,
3543 last_output_at: started,
3544 last_observed_output_len: 0,
3545 sandbox_type,
3546 linked_task_id: None,
3547 owner_agent,
3548 owner_session_id,
3549 origin_tool_call_id,
3550 origin_turn_id,
3551 ownership: if persist_pending {
3552 ShellOwnership::PersistPending
3553 } else {
3554 ShellOwnership::Managed
3555 },
3556 stdout_buffer,
3557 stderr_buffer,
3558 bounded_output,
3559 heavy_permit,
3560 scratch: exec_env.scratch.take(),
3561 stdout_cursor: 0,
3562 stderr_cursor: 0,
3563 completion_reported: false,
3564 stdin,
3565 #[cfg(not(target_env = "ohos"))]
3566 pty_master,
3567 terminal_size: tty.then(PtyDimensions::default),
3568 child: Some(child),
3569 #[cfg(windows)]
3570 windows_job,
3571 #[cfg(unix)]
3572 parent_death_watch,
3573 stdout_thread,
3574 stderr_thread,
3575 work_lifecycle,
3576 lifecycle_seq: 0,
3577 last_lifecycle_status: None,
3578 last_lifecycle_bytes: 0,
3579 wait_failed: false,
3580 terminal_exit_confirmed: false,
3581 hold: None,
3582 };
3583
3584 #[cfg(unix)]
3585 if persist_pending {
3586 let process_group_id = bg_shell
3587 .child
3588 .as_ref()
3589 .and_then(ShellChild::process_id)
3590 .ok_or_else(|| anyhow!("Persistent service has no process group id"))?;
3591 register_pending_persistent_process_group(process_group_id);
3592 }
3593
3594 if let Some(input) = stdin_data
3595 && let Err(err) = bg_shell.write_stdin(input, false)
3596 {
3597 let _ = bg_shell.kill();
3598 return Err(err);
3599 }
3600
3601 // Work-graph publication is bookkeeping: a graph write that fails
3602 // now must not kill a command that already started (#6435).
3603 bg_shell.publish_lifecycle_best_effort();
3604
3605 self.processes.insert(task_id.clone(), bg_shell);
3606 spawn_guard.disarm();
3607 // Evict here, not only from `list_jobs()`: retention must not depend on
3608 // the user opening the jobs panel, and every spawn is exactly the moment
3609 // the previous calls' records became one call staler (#5472).
3610 self.cleanup(FINISHED_SHELL_MAX_AGE);
3611
3612 Ok(ShellResult {
3613 task_id: Some(task_id),
3614 status: ShellStatus::Running,
3615 exit_code: None,
3616 stdout: String::new(),
3617 stderr: String::new(),
3618 duration_ms: 0,
3619 stdout_len: 0,
3620 stderr_len: 0,
3621 stdout_omitted: 0,
3622 stderr_omitted: 0,
3623 stdout_truncated: false,
3624 stderr_truncated: false,
3625 sandboxed,
3626 sandbox_type: if sandboxed {
3627 Some(sandbox_type.to_string())
3628 } else {
3629 None
3630 },
3631 sandbox_denied: false,
3632 })
3633 }
3634
3635 pub fn get_output(
3636 &mut self,
3637 task_id: &str,
3638 block: bool,
3639 timeout_ms: u64,
3640 ) -> Result<ShellResult> {
3641 self.get_output_with_artifact(task_id, block, timeout_ms)
3642 .map(|(result, _)| result)
3643 }
3644
3645 fn get_output_with_artifact(
3646 &mut self,
3647 task_id: &str,
3648 block: bool,
3649 timeout_ms: u64,
3650 ) -> Result<(ShellResult, Option<PersistedShellArtifact>)> {
3651 let shell = self
3652 .processes
3653 .get_mut(task_id)
3654 .ok_or_else(|| anyhow!("Task {task_id} not found"))?;
3655
3656 if block && shell.status == ShellStatus::Running {
3657 let timeout = Duration::from_millis(timeout_ms.clamp(1000, 600_000));
3658 let deadline = Instant::now() + timeout;
3659
3660 while shell.status == ShellStatus::Running && Instant::now() < deadline {
3661 if shell.poll() {
3662 break;
3663 }
3664 std::thread::sleep(Duration::from_millis(100));
3665 }
3666
3667 if shell.status == ShellStatus::Running {
3668 return shell.snapshot_with_artifact(false);
3669 }
3670 } else {
3671 shell.poll();
3672 }
3673
3674 shell.snapshot_with_artifact(shell.status != ShellStatus::Running)
3675 }
3676
3677 pub(super) fn test_output(
3678 &mut self,
3679 task_id: &str,
3680 session_id: &str,
3681 ) -> Result<(ShellResult, serde_json::Value)> {
3682 self.require_session_owner(task_id, session_id)?;
3683 let (snapshot, artifact) = self.get_output_with_artifact(task_id, false, 0)?;
3684 let mut metadata = json!({});
3685 if let Some(artifact) = artifact {
3686 stamp_persisted_shell_artifact_metadata(&mut metadata, &artifact, &snapshot.stdout);
3687 }
3688 Ok((snapshot, metadata))
3689 }
3690
3691 /// Poll a job and return only its status.
3692 ///
3693 /// The foreground wait loop ticks every 100 ms and discards the snapshot
3694 /// unless the job is terminal, but `get_output` → `snapshot` clones both
3695 /// raw buffers to build it. On a command printing 50 MB that was ~1.5 GB of
3696 /// allocate-and-drop churn per wait, all of it thrown away (#5472 finding 1,
3697 /// the transient term). Status is what the loop actually needs.
3698 pub(super) fn poll_status(&mut self, task_id: &str) -> Result<ShellStatus> {
3699 let shell = self
3700 .processes
3701 .get_mut(task_id)
3702 .ok_or_else(|| anyhow!("Task {task_id} not found"))?;
3703 shell.poll();
3704 Ok(shell.status.clone())
3705 }
3706
3707 /// Write data to stdin of a background process.
3708 pub fn write_stdin(&mut self, task_id: &str, input: &str, close: bool) -> Result<()> {
3709 self.write_stdin_bytes(task_id, input.as_bytes(), close)
3710 }
3711
3712 /// Exact input bytes from an authenticated client; never round-trip through UTF-8.
3713 pub fn write_stdin_bytes(&mut self, task_id: &str, input: &[u8], close: bool) -> Result<()> {
3714 let shell = self
3715 .processes
3716 .get_mut(task_id)
3717 .ok_or_else(|| anyhow!("Task {task_id} not found"))?;
3718 shell.write_stdin_bytes(input, close)?;
3719 Ok(())
3720 }
3721
3722 /// Historical evicted records have no terminal-size evidence.
3723 pub fn job_terminal_size(&self, task_id: &str) -> Option<PtyDimensions> {
3724 self.processes
3725 .get(task_id)
3726 .and_then(|shell| shell.terminal_size)
3727 }
3728
3729 pub fn resize_pty(&mut self, task_id: &str, size: PtyDimensions) -> Result<()> {
3730 let size = size.validate()?;
3731 let shell = self
3732 .processes
3733 .get_mut(task_id)
3734 .ok_or_else(|| anyhow!("Job {task_id} not found"))?;
3735 shell.poll();
3736 anyhow::ensure!(
3737 shell.status == ShellStatus::Running,
3738 "PTY job is no longer running"
3739 );
3740 #[cfg(not(target_env = "ohos"))]
3741 {
3742 let master = shell.pty_master.as_ref().context("Job is not a PTY")?;
3743 master
3744 .resize(PtySize {
3745 rows: size.rows,
3746 cols: size.cols,
3747 pixel_width: 0,
3748 pixel_height: 0,
3749 })
3750 .context("Failed to resize PTY")?;
3751 shell.terminal_size = Some(size);
3752 Ok(())
3753 }
3754 #[cfg(target_env = "ohos")]
3755 {
3756 let _ = size;
3757 Err(anyhow!("PTY resize is unavailable on this platform"))
3758 }
3759 }
3760
3761 pub fn write_stdin_for_session(
3762 &mut self,
3763 active_session_id: &str,
3764 task_id: &str,
3765 input: &str,
3766 close: bool,
3767 ) -> Result<()> {
3768 self.require_session_owner(task_id, active_session_id)?;
3769 self.write_stdin(task_id, input, close)
3770 }
3771
3772 fn get_raw_output_delta(
3773 &mut self,
3774 task_id: &str,
3775 wait: bool,
3776 timeout_ms: u64,
3777 ) -> Result<RawShellDelta> {
3778 let shell = self
3779 .processes
3780 .get_mut(task_id)
3781 .ok_or_else(|| anyhow!("Task {task_id} not found"))?;
3782 wait_while_running(shell, wait, timeout_ms);
3783 let finalized_artifact = if shell.status != ShellStatus::Running {
3784 shell.finalize_output_artifact()?
3785 } else {
3786 None
3787 };
3788 let (
3789 stdout,
3790 stderr,
3791 stdout_delta_len,
3792 stderr_delta_len,
3793 stdout_total_len,
3794 stderr_total_len,
3795 persisted_artifact,
3796 ) = shell.take_delta();
3797 let persisted_artifact = finalized_artifact.or(persisted_artifact);
3798 let sandboxed = !matches!(shell.sandbox_type, SandboxType::None);
3799 let sandbox_denied = shell.sandbox_denied();
3800 let status = shell.status.clone();
3801 if status != ShellStatus::Running {
3802 shell.completion_reported = true;
3803 shell.release_delivered_output();
3804 }
3805
3806 Ok(RawShellDelta {
3807 command: shell.command.clone(),
3808 task_id: shell.id.clone(),
3809 status,
3810 exit_code: shell.exit_code,
3811 duration_ms: u64::try_from(shell.started_at.elapsed().as_millis()).unwrap_or(u64::MAX),
3812 stdout,
3813 stderr,
3814 stdout_delta_len,
3815 stderr_delta_len,
3816 stdout_total_len,
3817 stderr_total_len,
3818 sandboxed,
3819 sandbox_type: sandboxed.then(|| shell.sandbox_type.to_string()),
3820 sandbox_denied,
3821 persisted_artifact,
3822 })
3823 }
3824
3825 #[cfg(any(test, feature = "test-support"))]
3826 fn get_output_delta(
3827 &mut self,
3828 task_id: &str,
3829 wait: bool,
3830 timeout_ms: u64,
3831 ) -> Result<ShellDeltaResult> {
3832 let raw = self.get_raw_output_delta(task_id, wait, timeout_ms)?;
3833 let (stdout, stdout_meta) = truncate_with_meta(&raw.stdout);
3834 let (stderr, stderr_meta) = truncate_with_meta(&raw.stderr);
3835 let result = ShellResult {
3836 task_id: Some(raw.task_id),
3837 status: raw.status,
3838 exit_code: raw.exit_code,
3839 stdout,
3840 stderr,
3841 duration_ms: raw.duration_ms,
3842 stdout_len: stdout_meta.original_len.max(raw.stdout_delta_len),
3843 stderr_len: stderr_meta.original_len.max(raw.stderr_delta_len),
3844 stdout_omitted: stdout_meta.omitted,
3845 stderr_omitted: stderr_meta.omitted,
3846 stdout_truncated: stdout_meta.truncated,
3847 stderr_truncated: stderr_meta.truncated,
3848 sandboxed: raw.sandboxed,
3849 sandbox_type: raw.sandbox_type,
3850 sandbox_denied: raw.sandbox_denied,
3851 };
3852
3853 Ok(ShellDeltaResult {
3854 command: raw.command,
3855 result,
3856 stdout_total_len: raw.stdout_total_len,
3857 stderr_total_len: raw.stderr_total_len,
3858 })
3859 }
3860
3861 fn attach_heavy_permit(&mut self, task_id: &str, permit: HeavyCommandPermit) -> Result<()> {
3862 let shell = self
3863 .processes
3864 .get_mut(task_id)
3865 .ok_or_else(|| anyhow!("Task {task_id} not found"))?;
3866 shell.heavy_permit = Some(permit);
3867 Ok(())
3868 }
3869
3870 pub fn hold_job(
3871 &mut self,
3872 task_id: &str,
3873 keepalive: Option<Duration>,
3874 deadline_at: Option<chrono::DateTime<chrono::Utc>>,
3875 ) -> Result<(), ShellHoldError> {
3876 let shell = self
3877 .processes
3878 .get_mut(task_id)
3879 .ok_or(ShellHoldError::NotFound)?;
3880 shell.hold = Some(JobHoldState {
3881 keepalive,
3882 keepalive_until: keepalive.map(|keepalive| Instant::now() + keepalive),
3883 deadline_at,
3884 stop_reason: None,
3885 });
3886 Ok(())
3887 }
3888
3889 pub fn keep_job_alive(&mut self, task_id: &str) -> Result<ShellJobHold, ShellHoldError> {
3890 let shell = self
3891 .processes
3892 .get_mut(task_id)
3893 .ok_or(ShellHoldError::NotFound)?;
3894 shell.poll();
3895 let hold = shell
3896 .hold
3897 .as_mut()
3898 .filter(|hold| hold.keepalive.is_some())
3899 .ok_or(ShellHoldError::NotHeld)?;
3900 if hold.stop_reason.is_some() {
3901 return Err(ShellHoldError::Expired);
3902 }
3903 if shell.status != ShellStatus::Running {
3904 return Err(ShellHoldError::NotRunning);
3905 }
3906 if hold.expired(Instant::now(), chrono::Utc::now()).is_some() {
3907 return Err(ShellHoldError::Expired);
3908 }
3909 hold.keepalive_until = hold.keepalive.map(|keepalive| Instant::now() + keepalive);
3910 Ok(hold.view())
3911 }
3912
3913 pub fn job_hold(&self, task_id: &str) -> Option<ShellJobHold> {
3914 self.processes
3915 .get(task_id)?
3916 .hold
3917 .as_ref()
3918 .map(JobHoldState::view)
3919 }
3920
3921 pub fn job_last_progress_at(&self, task_id: &str) -> Option<chrono::DateTime<chrono::Utc>> {
3922 self.processes
3923 .get(task_id)
3924 .filter(|shell| shell.status == ShellStatus::Running)
3925 .map(BackgroundShell::last_progress_at)
3926 }
3927
3928 pub fn enforce_job_hold(&mut self, task_id: &str) -> bool {
3929 let Some(shell) = self.processes.get_mut(task_id) else {
3930 return false;
3931 };
3932 shell.poll();
3933 if shell.status != ShellStatus::Running {
3934 return false;
3935 }
3936 let Some(reason) = shell
3937 .hold
3938 .as_ref()
3939 .and_then(|hold| hold.expired(Instant::now(), chrono::Utc::now()))
3940 else {
3941 return shell.hold.is_some();
3942 };
3943 if let Some(hold) = shell.hold.as_mut() {
3944 hold.stop_reason = Some(reason);
3945 }
3946 if let Err(error) = shell.kill() {
3947 tracing::warn!(shell_id = %task_id, ?reason, error = %error, "failed to stop held job");
3948 return true;
3949 }
3950 shell.status == ShellStatus::Running
3951 }
3952
3953 pub(crate) fn unsettled_owned_job_count(&mut self) -> usize {
3954 let mut unsettled = 0;
3955 for shell in self
3956 .processes
3957 .values_mut()
3958 .filter(|shell| shell.has_unsettled_child())
3959 {
3960 shell.poll();
3961 if shell.has_unsettled_child() {
3962 unsettled += 1;
3963 }
3964 }
3965 unsettled
3966 }
3967
3968 pub fn running_jobs(&mut self) -> Vec<ShellRunningJob> {
3969 self.processes
3970 .values_mut()
3971 .filter_map(|shell| {
3972 shell.poll();
3973 (shell.status == ShellStatus::Running).then(|| ShellRunningJob {
3974 job_id: shell.id.clone(),
3975 background: shell.background,
3976 last_progress_at: shell.last_progress_at(),
3977 hold: shell.hold.as_ref().map(JobHoldState::view),
3978 })
3979 })
3980 .collect()
3981 }
3982
3983 pub fn last_output_age_ms(&self, task_id: &str) -> Option<u64> {
3984 let shell = self.processes.get(task_id)?;
3985 Some(u64::try_from(shell.last_output_at.elapsed().as_millis()).unwrap_or(u64::MAX))
3986 }
3987
3988 pub fn running_progress(&mut self, task_id: &str) -> Option<String> {
3989 let shell = self.processes.get_mut(task_id)?;
3990 shell.poll();
3991 if shell.status != ShellStatus::Running {
3992 return None;
3993 }
3994 let job = shell.job_snapshot();
3995 let quiet_secs = shell.last_output_at.elapsed().as_secs();
3996 Some(format!(
3997 "Progress: last output {quiet_secs}s ago; {}.",
3998 output_phase_hint(&format!("{}\n{}", job.stdout_tail, job.stderr_tail))
3999 ))
4000 }
4001
4002 pub fn kill(&mut self, task_id: &str) -> Result<ShellResult> {
4003 self.kill_with_artifact(task_id).map(|(result, _)| result)
4004 }
4005
4006 fn kill_with_artifact(
4007 &mut self,
4008 task_id: &str,
4009 ) -> Result<(ShellResult, Option<PersistedShellArtifact>)> {
4010 let shell = self
4011 .processes
4012 .get_mut(task_id)
4013 .ok_or_else(|| anyhow!("Task {task_id} not found"))?;
4014
4015 shell.kill()?;
4016 shell.snapshot_with_artifact(true)
4017 }
4018
4019 pub fn mark_cancel_reported(&mut self, result: &ShellResult) {
4020 if result.status != ShellStatus::Running
4021 && let Some(shell) = result
4022 .task_id
4023 .as_deref()
4024 .and_then(|id| self.processes.get_mut(id))
4025 {
4026 shell.completion_reported = true;
4027 shell.release_delivered_output();
4028 }
4029 }
4030
4031 pub fn kill_for_session(
4032 &mut self,
4033 active_session_id: &str,
4034 task_id: &str,
4035 ) -> Result<ShellResult> {
4036 self.require_session_owner(task_id, active_session_id)?;
4037 self.kill(task_id)
4038 }
4039
4040 /// Kill every currently running background shell process.
4041 #[cfg(any(test, feature = "test-support"))]
4042 pub fn kill_running(&mut self) -> Result<Vec<ShellResult>> {
4043 let ids = self
4044 .processes
4045 .iter()
4046 .filter(|(_, shell)| shell.status == ShellStatus::Running)
4047 .map(|(id, _)| id.clone())
4048 .collect::<Vec<_>>();
4049
4050 let mut results = Vec::with_capacity(ids.len());
4051 for id in ids {
4052 results.push(self.kill(&id)?);
4053 }
4054 Ok(results)
4055 }
4056
4057 /// End every background job this manager still owns that is running.
4058 ///
4059 /// Released shells belong to the user and are left alone; already-finished
4060 /// shells are not counted. Used when the owning conversation is deleted so
4061 /// its jobs do not outlive the thread record.
4062 pub fn kill_all_owned_running(&mut self) -> usize {
4063 let ids = self
4064 .processes
4065 .iter()
4066 .filter(|(_, shell)| {
4067 shell.status == ShellStatus::Running && shell.ownership != ShellOwnership::Released
4068 })
4069 .map(|(id, _)| id.clone())
4070 .collect::<Vec<_>>();
4071 let mut ended = 0;
4072 for id in ids {
4073 match self.kill(&id) {
4074 Ok(result) if result.status == ShellStatus::Killed => ended += 1,
4075 Ok(_) => {}
4076 Err(error) => {
4077 tracing::warn!(shell_id = %id, %error, "failed to end background job");
4078 }
4079 }
4080 }
4081 ended
4082 }
4083
4084 pub fn kill_running_for_session(
4085 &mut self,
4086 active_session_id: &str,
4087 ) -> Result<Vec<ShellResult>> {
4088 let ids = self
4089 .processes
4090 .iter_mut()
4091 .filter(|(_, shell)| {
4092 !active_session_id.is_empty() && shell.owner_session_id == active_session_id
4093 })
4094 .filter_map(|(id, shell)| {
4095 shell.poll();
4096 (shell.status == ShellStatus::Running).then(|| id.clone())
4097 })
4098 .collect::<Vec<_>>();
4099 let mut results = Vec::with_capacity(ids.len());
4100 for id in ids {
4101 results.push(self.kill(&id)?);
4102 }
4103 results.retain(|result| result.status == ShellStatus::Killed);
4104 Ok(results)
4105 }
4106
4107 /// Transfer every still-running `persist:true` process out of Codewhale's
4108 /// ownership. This is called only by the real headless exec host after the
4109 /// enclosing turn has completed successfully.
4110 #[cfg(unix)]
4111 pub fn commit_persistent_services(&mut self) -> Result<Vec<PersistentServiceReceipt>> {
4112 let mut ids = self
4113 .processes
4114 .iter()
4115 .filter(|(_, shell)| shell.ownership == ShellOwnership::PersistPending)
4116 .map(|(id, _)| id.clone())
4117 .collect::<Vec<_>>();
4118 ids.sort();
4119
4120 for id in &ids {
4121 let shell = self
4122 .processes
4123 .get_mut(id)
4124 .ok_or_else(|| anyhow!("Persistent service {id} disappeared before commit"))?;
4125 shell.poll();
4126 if shell.status != ShellStatus::Running {
4127 return Err(anyhow!(
4128 "Persistent service {id} exited before ownership transfer (status {:?}, exit code {:?})",
4129 shell.status,
4130 shell.exit_code
4131 ));
4132 }
4133 if shell
4134 .child
4135 .as_ref()
4136 .and_then(ShellChild::process_id)
4137 .is_none()
4138 {
4139 return Err(anyhow!(
4140 "Persistent service {id} has no releasable process id"
4141 ));
4142 }
4143 }
4144
4145 let mut receipts = Vec::with_capacity(ids.len());
4146 for id in ids {
4147 let mut shell = self
4148 .processes
4149 .remove(&id)
4150 .ok_or_else(|| anyhow!("Persistent service {id} disappeared during commit"))?;
4151 let pid = shell
4152 .child
4153 .as_ref()
4154 .and_then(ShellChild::process_id)
4155 .ok_or_else(|| anyhow!("Persistent service {id} lost its process id"))?;
4156 unregister_pending_persistent_process_group(pid);
4157 shell.ownership = ShellOwnership::Released;
4158 shell.stdin = None;
4159 shell.heavy_permit.take();
4160 shell.work_lifecycle = None;
4161 receipts.push(PersistentServiceReceipt {
4162 task_id: id,
4163 pid,
4164 process_group_id: pid,
4165 ownership: "external".to_string(),
4166 });
4167 }
4168 Ok(receipts)
4169 }
4170
4171 /// Kill only services waiting for a successful exec ownership transfer.
4172 /// Ordinary background jobs retain their existing manager lifetime.
4173 pub fn abort_persistent_services(&mut self) {
4174 let ids = self
4175 .processes
4176 .iter()
4177 .filter(|(_, shell)| shell.ownership == ShellOwnership::PersistPending)
4178 .map(|(id, _)| id.clone())
4179 .collect::<Vec<_>>();
4180 for id in ids {
4181 if let Err(error) = self.kill(&id) {
4182 tracing::warn!(shell_id = %id, %error, "failed to abort pending persistent service");
4183 }
4184 }
4185 }
4186
4187 /// Poll a background process and return incremental output.
4188 #[cfg(any(test, feature = "test-support"))]
4189 pub fn poll_delta(
4190 &mut self,
4191 task_id: &str,
4192 wait: bool,
4193 timeout_ms: u64,
4194 ) -> Result<ShellDeltaResult> {
4195 self.get_output_delta(task_id, wait, timeout_ms)
4196 }
4197
4198 fn get_raw_output_delta_for_session(
4199 &mut self,
4200 active_session_id: &str,
4201 task_id: &str,
4202 wait: bool,
4203 timeout_ms: u64,
4204 ) -> Result<RawShellDelta> {
4205 self.require_session_owner(task_id, active_session_id)?;
4206 self.get_raw_output_delta(task_id, wait, timeout_ms)
4207 }
4208
4209 /// Read a job's raw stream at an absolute byte offset without consuming
4210 /// anything. This is the `/v1/jobs` byte-stream contract: HTTP clients hold
4211 /// the cursor, so reads must not disturb the engine's own delta consumer.
4212 ///
4213 /// `cursor` is a byte offset into the stream's lifetime output (matching
4214 /// `total`). When the bounded buffer has already discarded `[0, dropped)`,
4215 /// the window starts at `dropped` instead and the caller sees the gap in
4216 /// the response rather than a replayed tail. With `wait_ms > 0` on a
4217 /// running job, polls up to that bound for new bytes past `cursor` before
4218 /// answering — long-poll instead of a hot loop.
4219 pub fn read_output_chunk(
4220 &mut self,
4221 task_id: &str,
4222 stream: ShellOutputStream,
4223 cursor: usize,
4224 max_bytes: usize,
4225 wait_ms: u64,
4226 ) -> Result<ShellOutputChunk> {
4227 let Some(shell) = self.processes.get_mut(task_id) else {
4228 // Evicted jobs retain only their snapshot tails. Serve that tail as
4229 // the final retained window so a late reader still gets the ending
4230 // of the stream instead of a bare not-found.
4231 let snapshot = self
4232 .stale_jobs
4233 .get(task_id)
4234 .ok_or_else(|| anyhow!("Job {task_id} not found"))?;
4235 let (tail, total) = match stream {
4236 ShellOutputStream::Stdout => (&snapshot.stdout_tail, snapshot.stdout_len),
4237 ShellOutputStream::Stderr => (&snapshot.stderr_tail, snapshot.stderr_len),
4238 };
4239 let tail_start = total.saturating_sub(tail.len());
4240 let offset = cursor.max(tail_start).min(total);
4241 let next_offset = offset.saturating_add(max_bytes).min(total);
4242 return Ok(ShellOutputChunk {
4243 offset,
4244 bytes: tail.as_bytes()[offset - tail_start..next_offset - tail_start].to_vec(),
4245 next_offset,
4246 total,
4247 dropped: tail_start,
4248 status: snapshot.status.clone(),
4249 exit_code: snapshot.exit_code,
4250 });
4251 };
4252 let buffer = match stream {
4253 ShellOutputStream::Stdout => shell.stdout_buffer.clone(),
4254 ShellOutputStream::Stderr => shell
4255 .stderr_buffer
4256 .clone()
4257 .ok_or_else(|| anyhow!("Job {task_id} merges stderr into stdout"))?,
4258 };
4259
4260 let wait_deadline = (wait_ms > 0 && shell.status == ShellStatus::Running)
4261 .then(|| Instant::now() + Duration::from_millis(wait_ms.clamp(50, 30_000)));
4262 loop {
4263 shell.poll();
4264 let total = buffer.lock().map(|guard| guard.total_len()).unwrap_or(0);
4265 let done_waiting = total > cursor
4266 || shell.status != ShellStatus::Running
4267 || wait_deadline.is_none_or(|deadline| Instant::now() >= deadline);
4268 if done_waiting {
4269 break;
4270 }
4271 std::thread::sleep(Duration::from_millis(50));
4272 }
4273
4274 let (bytes, offset, next_offset, total, dropped) = {
4275 let guard = buffer.lock().unwrap_or_else(|e| e.into_inner());
4276 let total = guard.total_len();
4277 let dropped = guard.dropped();
4278 let offset = cursor.max(dropped).min(total);
4279 let next_offset = offset.saturating_add(max_bytes).min(total);
4280 let retained = guard.retained();
4281 let bytes = retained[offset - dropped..next_offset - dropped].to_vec();
4282 (bytes, offset, next_offset, total, dropped)
4283 };
4284 Ok(ShellOutputChunk {
4285 offset,
4286 bytes,
4287 next_offset,
4288 total,
4289 dropped,
4290 status: shell.status.clone(),
4291 exit_code: shell.exit_code,
4292 })
4293 }
4294
4295 /// Attach durable task context to a live shell job.
4296 pub fn tag_linked_task(&mut self, task_id: &str, linked_task_id: Option<String>) -> Result<()> {
4297 let shell = self
4298 .processes
4299 .get_mut(task_id)
4300 .ok_or_else(|| anyhow!("Task {task_id} not found"))?;
4301 shell.linked_task_id = linked_task_id;
4302 Ok(())
4303 }
4304
4305 pub fn tag_description(&mut self, task_id: &str, description: Option<String>) -> Result<()> {
4306 let shell = self
4307 .processes
4308 .get_mut(task_id)
4309 .ok_or_else(|| anyhow!("Task {task_id} not found"))?;
4310 shell.description = description;
4311 Ok(())
4312 }
4313
4314 /// Inspect full output for a live or stale job.
4315 pub fn inspect_job(&mut self, task_id: &str) -> Result<ShellJobDetail> {
4316 if let Some(shell) = self.processes.get_mut(task_id) {
4317 shell.poll();
4318 return Ok(shell.job_detail());
4319 }
4320 if let Some(snapshot) = self.stale_jobs.get(task_id) {
4321 return Ok(ShellJobDetail {
4322 snapshot: snapshot.clone(),
4323 stdout: snapshot.stdout_tail.clone(),
4324 stderr: snapshot.stderr_tail.clone(),
4325 });
4326 }
4327 Err(anyhow!("Job {task_id} not found"))
4328 }
4329
4330 pub fn inspect_job_for_session(
4331 &mut self,
4332 active_session_id: &str,
4333 task_id: &str,
4334 ) -> Result<ShellJobDetail> {
4335 self.require_session_owner(task_id, active_session_id)?;
4336 self.inspect_job(task_id)
4337 }
4338
4339 /// List all live and known-stale background shell jobs for the TUI.
4340 pub fn list_jobs(&mut self) -> Vec<ShellJobSnapshot> {
4341 for shell in self.processes.values_mut() {
4342 shell.poll();
4343 }
4344 // Evict completed processes older than 1 hour to bound memory growth.
4345 self.cleanup(FINISHED_SHELL_MAX_AGE);
4346
4347 let mut jobs = self
4348 .processes
4349 .values()
4350 .map(BackgroundShell::job_snapshot)
4351 .collect::<Vec<_>>();
4352 jobs.extend(self.stale_jobs.values().cloned());
4353 jobs.sort_by(|a, b| {
4354 job_status_rank(&a.status, a.stale)
4355 .cmp(&job_status_rank(&b.status, b.stale))
4356 .then_with(|| a.id.cmp(&b.id))
4357 });
4358 jobs
4359 }
4360
4361 pub fn list_jobs_for_session(&mut self, active_session_id: &str) -> Vec<ShellJobSnapshot> {
4362 if active_session_id.is_empty() {
4363 return Vec::new();
4364 }
4365 self.list_jobs()
4366 .into_iter()
4367 .filter(|job| job.owner_session_id == active_session_id)
4368 .collect()
4369 }
4370
4371 /// Whether a finished parent-owned job's completion is waiting to be
4372 /// claimed. Unlike
4373 /// [`Self::may_have_undelivered_completion`] this polls, so it reports
4374 /// readiness the moment the process exits; the engine's idle shell wake
4375 /// uses it to fire exactly when evidence exists.
4376 #[cfg(any(test, feature = "test-support"))]
4377 pub fn has_finished_unreported_jobs(&mut self) -> bool {
4378 self.processes.values_mut().any(|shell| {
4379 shell.poll();
4380 shell.owner_agent.is_none()
4381 && shell.status != ShellStatus::Running
4382 && !shell.completion_reported
4383 })
4384 }
4385
4386 pub fn has_finished_unreported_jobs_for_session(&mut self, active_session_id: &str) -> bool {
4387 !active_session_id.is_empty()
4388 && self.processes.values_mut().any(|shell| {
4389 shell.poll();
4390 shell.owner_session_id == active_session_id
4391 && shell.owner_agent.is_none()
4392 && shell.status != ShellStatus::Running
4393 && !shell.completion_reported
4394 })
4395 }
4396
4397 /// Drain once-only completion events together with lossless stream bytes.
4398 /// The engine publishes the bytes outside this manager's mutex and puts
4399 /// only the bounded event plus resulting handle into model context.
4400 #[cfg(any(test, feature = "test-support"))]
4401 pub fn drain_finished_jobs_with_evidence(&mut self) -> Vec<ShellCompletionEvidence> {
4402 self.drain_finished_jobs_with_evidence_inner(None)
4403 }
4404
4405 pub fn drain_finished_jobs_with_evidence_for_session(
4406 &mut self,
4407 active_session_id: &str,
4408 ) -> Vec<ShellCompletionEvidence> {
4409 self.drain_finished_jobs_with_evidence_inner(Some(active_session_id))
4410 }
4411
4412 fn drain_finished_jobs_with_evidence_inner(
4413 &mut self,
4414 active_session_id: Option<&str>,
4415 ) -> Vec<ShellCompletionEvidence> {
4416 let mut completions = Vec::new();
4417 for shell in self.processes.values_mut() {
4418 shell.poll();
4419 let owned = active_session_id.is_none_or(|session_id| {
4420 !session_id.is_empty() && shell.owner_session_id == session_id
4421 });
4422 if owned
4423 && shell.owner_agent.is_none()
4424 && shell.status != ShellStatus::Running
4425 && !shell.completion_reported
4426 {
4427 if let Err(error) = shell.finalize_output_artifact() {
4428 tracing::warn!(task_id = %shell.id, %error, "shell completion artifact publication failed; retaining output for retry");
4429 continue;
4430 }
4431 shell.completion_reported = true;
4432 completions.push(shell.completion_evidence());
4433 // The bytes are now in the caller's hands (they become a durable
4434 // session artifact). Holding a second copy here for the rest of
4435 // the retention hour is what #5472 measured.
4436 shell.release_delivered_output();
4437 }
4438 }
4439 completions.sort_by(|a, b| a.event.task_id.cmp(&b.event.task_id));
4440 completions
4441 }
4442
4443 /// A terminal foreground result is already returned as the tool result;
4444 /// do not emit it again through the background-completion channel.
4445 pub(super) fn acknowledge_foreground_completion(&mut self, task_id: &str) {
4446 if let Some(shell) = self.processes.get_mut(task_id) {
4447 shell.completion_reported = true;
4448 // The caller already holds this job's `ShellResult`; the record only
4449 // stays listed so `/jobs` can show it. A 1,200-char tail is all any
4450 // remaining consumer reads, so the rest is released now instead of
4451 // at the 1 h `cleanup` (#5472 finding 1 — the dominant term: every
4452 // uppercase `Bash` call, foreground included, went through here).
4453 shell.release_delivered_output();
4454 }
4455 }
4456
4457 /// Whether the next production turn may inject a parent-owned shell
4458 /// completion event.
4459 ///
4460 /// This deliberately does not poll processes or flip
4461 /// `completion_reported`: preview is read-only. A running job counts as
4462 /// pending because it can finish before production drains completions; in
4463 /// that race an exact request body cannot be proved without mutation.
4464 #[cfg(any(test, feature = "test-support"))]
4465 pub fn may_have_undelivered_completion(&self) -> bool {
4466 self.processes
4467 .values()
4468 .any(|shell| shell.owner_agent.is_none() && !shell.completion_reported)
4469 }
4470
4471 pub fn may_have_undelivered_completion_for_session(&self, active_session_id: &str) -> bool {
4472 !active_session_id.is_empty()
4473 && self.processes.values().any(|shell| {
4474 shell.owner_session_id == active_session_id
4475 && shell.owner_agent.is_none()
4476 && !shell.completion_reported
4477 })
4478 }
4479
4480 /// Return agent owners whose tracked shell work is still running. The
4481 /// engine uses this to keep a worker's heartbeat alive while its only
4482 /// pending work is an explicitly tracked background shell task.
4483 #[cfg(any(test, feature = "test-support"))]
4484 pub fn running_owner_agent_ids(&mut self) -> Vec<String> {
4485 self.running_owner_agent_ids_inner(None)
4486 }
4487
4488 pub fn running_owner_agent_ids_for_session(&mut self, active_session_id: &str) -> Vec<String> {
4489 self.running_owner_agent_ids_inner(Some(active_session_id))
4490 }
4491
4492 fn running_owner_agent_ids_inner(&mut self, active_session_id: Option<&str>) -> Vec<String> {
4493 let mut owners = self
4494 .processes
4495 .values_mut()
4496 .filter_map(|shell| {
4497 shell.poll();
4498 (shell.status == ShellStatus::Running
4499 && active_session_id.is_none_or(|session_id| {
4500 !session_id.is_empty() && shell.owner_session_id == session_id
4501 }))
4502 .then(|| {
4503 shell
4504 .owner_agent
4505 .as_ref()
4506 .map(|owner| owner.agent_id.clone())
4507 })
4508 .flatten()
4509 })
4510 .collect::<Vec<_>>();
4511 owners.sort();
4512 owners.dedup();
4513 owners
4514 }
4515
4516 /// Remember a restart-stale job so the UI can show it instead of hiding it.
4517 #[cfg(any(test, feature = "test-support"))]
4518 pub fn remember_stale_job(
4519 &mut self,
4520 id: impl Into<String>,
4521 command: impl Into<String>,
4522 cwd: PathBuf,
4523 linked_task_id: Option<String>,
4524 ) {
4525 let id = id.into();
4526 self.stale_jobs.insert(
4527 id.clone(),
4528 ShellJobSnapshot {
4529 id: id.clone(),
4530 job_id: id,
4531 command: command.into(),
4532 description: None,
4533 cwd,
4534 status: ShellStatus::Killed,
4535 background: true,
4536 started_at: None,
4537 finished_at: None,
4538 cause: Some(ShellTerminationCause::Unknown),
4539 producer_reported: false,
4540 exit_code: None,
4541 elapsed_ms: 0,
4542 stdout_tail: String::new(),
4543 stderr_tail: "Process is no longer attached to this TUI session.".to_string(),
4544 stdout_len: 0,
4545 stderr_len: 0,
4546 stdin_available: false,
4547 stale: true,
4548 elapsed_since_output_ms: None,
4549 linked_task_id,
4550 owner_agent_id: None,
4551 owner_agent_name: None,
4552 origin_tool_call_id: None,
4553 origin_turn_id: None,
4554 owner_session_id: String::new(),
4555 },
4556 );
4557 }
4558
4559 /// Clean up completed processes older than the given duration, then enforce
4560 /// the count and byte ceilings on what is left.
4561 ///
4562 /// Age alone is not a bound: it only fired from `list_jobs()`, so a session
4563 /// that never opened the jobs panel evicted nothing, and 500 finished
4564 /// records inside one hour were all retained regardless of size (#5472).
4565 ///
4566 /// Age counts from when a job finished, not when it started: a job that
4567 /// ran longer than `max_age` would otherwise be dropped the moment it
4568 /// exited, before its completion was delivered. Undelivered completions
4569 /// age out too: jobs launched over the Runtime API, or owned by a session
4570 /// that is no longer active, are never drained.
4571 pub fn cleanup(&mut self, max_age: Duration) {
4572 let pins = &self.receipt_pins;
4573 let witnesses = &mut self.receipt_witnesses;
4574 self.processes.retain(|id, shell| {
4575 if shell.status == ShellStatus::Running || shell.has_unsettled_child() {
4576 return true;
4577 }
4578 shell.mark_finished();
4579 let retain = shell
4580 .finished_at
4581 .is_none_or(|finished| finished.elapsed() < max_age);
4582 if !retain && pins.contains(id) {
4583 witnesses.insert(id.clone(), ShellReceiptWitness::from_shell(shell));
4584 }
4585 retain
4586 });
4587 self.enforce_finished_job_bounds();
4588 }
4589
4590 /// Bytes still held across every tracked job. The retention bound in #5472
4591 /// is stated in these terms, so the tests assert on them directly.
4592 #[cfg(all(test, unix))]
4593 pub fn retained_output_bytes_total(&self) -> usize {
4594 self.processes
4595 .values()
4596 .map(BackgroundShell::retained_output_bytes)
4597 .fold(0, usize::saturating_add)
4598 }
4599
4600 #[cfg(any(test, feature = "test-support"))]
4601 pub fn tracked_job_count(&self) -> usize {
4602 self.processes.len()
4603 }
4604
4605 /// Drop the oldest finished records once they exceed either ceiling.
4606 /// Running jobs are never evicted — killing the handle would orphan a live
4607 /// process — and a job whose completion has not been delivered yet is
4608 /// evicted last, since dropping it loses the only copy of its result.
4609 fn enforce_finished_job_bounds(&mut self) {
4610 let mut finished = self
4611 .processes
4612 .iter()
4613 .filter(|(_, shell)| {
4614 shell.status != ShellStatus::Running && !shell.has_unsettled_child()
4615 })
4616 .map(|(id, shell)| {
4617 (
4618 id.clone(),
4619 shell.completion_reported || shell.owner_agent.is_some(),
4620 // Oldest by finish, like the age rule in `cleanup`.
4621 shell.finished_at.unwrap_or(shell.started_at),
4622 shell.retained_output_bytes(),
4623 )
4624 })
4625 .collect::<Vec<_>>();
4626 let total_bytes: usize = finished
4627 .iter()
4628 .map(|(_, _, _, bytes)| *bytes)
4629 .fold(0, usize::saturating_add);
4630 if finished.len() <= MAX_FINISHED_SHELL_RECORDS && total_bytes <= MAX_FINISHED_SHELL_BYTES {
4631 return;
4632 }
4633 // Undelivered parent completions last, then oldest first. Child-owned
4634 // results never reach the parent model, so they rank with delivered.
4635 finished.sort_by(|a, b| a.1.cmp(&b.1).reverse().then_with(|| a.2.cmp(&b.2)));
4636 let mut remaining_count = finished.len();
4637 let mut remaining_bytes = total_bytes;
4638 for (id, _, _, bytes) in finished {
4639 if remaining_count <= MAX_FINISHED_SHELL_RECORDS
4640 && remaining_bytes <= MAX_FINISHED_SHELL_BYTES
4641 {
4642 break;
4643 }
4644 if let Some(mut shell) = self.processes.remove(&id)
4645 && self.receipt_pins.contains(&id)
4646 {
4647 self.receipt_witnesses
4648 .insert(id, ShellReceiptWitness::from_shell(&mut shell));
4649 }
4650 remaining_count -= 1;
4651 remaining_bytes = remaining_bytes.saturating_sub(bytes);
4652 }
4653 }
4654 }
4655
4656 fn wait_while_running(shell: &mut BackgroundShell, wait: bool, timeout_ms: u64) {
4657 if wait && shell.status == ShellStatus::Running {
4658 let timeout = Duration::from_millis(timeout_ms.clamp(1000, 600_000));
4659 let deadline = Instant::now() + timeout;
4660
4661 while shell.status == ShellStatus::Running && Instant::now() < deadline {
4662 if shell.poll() {
4663 break;
4664 }
4665 std::thread::sleep(Duration::from_millis(100));
4666 }
4667 } else {
4668 shell.poll();
4669 }
4670 }
4671
4672 fn job_status_rank(status: &ShellStatus, stale: bool) -> u8 {
4673 if stale {
4674 return 4;
4675 }
4676 match status {
4677 ShellStatus::Running => 0,
4678 ShellStatus::Failed | ShellStatus::TimedOut => 1,
4679 ShellStatus::Killed => 2,
4680 ShellStatus::Completed => 3,
4681 }
4682 }
4683
4684 /// Thread-safe wrapper for `ShellManager`
4685 pub type SharedShellManager = Arc<Mutex<ShellManager>>;
4686
4687 /// Create a new shared shell manager with default sandbox policy.
4688 pub fn new_shared_shell_manager(workspace: PathBuf) -> SharedShellManager {
4689 Arc::new(Mutex::new(ShellManager::new(workspace)))
4690 }
4691
4692 // === ToolSpec Implementations ===
4693
4694 use crate::tools::cargo_failure_summary::summarize_cargo_failure;
4695 use crate::tools::spec::{
4696 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
4697 optional_bool, optional_str, optional_u64, required_str, type_mismatch,
4698 };
4699 use async_trait::async_trait;
4700 use codewhale_execpolicy::command_safety::{
4701 NetworkRead, ReadonlyRejection, SafetyAnalysis, SafetyLevel, agent_readonly_verdict,
4702 analyze_command, extract_primary_command, is_parallel_readonly_command,
4703 normalize_windows_command_paths, readonly_network_reads, split_leading_cd,
4704 };
4705 use codewhale_execpolicy::toml_rules::{ExecPolicyConfig, RuleDecision};
4706 use codewhale_runtime::features::Feature;
4707 use serde_json::json;
4708
4709 /// The TOML execpolicy file lives in the user config home; the rule engine
4710 /// itself is `codewhale_execpolicy::toml_rules`.
4711 fn default_execpolicy_path() -> Option<std::path::PathBuf> {
4712 codewhale_paths::user_home().map(|home| home.join(".deepseek").join("execpolicy.toml"))
4713 }
4714
4715 fn load_default_policy() -> anyhow::Result<Option<ExecPolicyConfig>> {
4716 /// A parsed rules file, tagged with the identity it was parsed from.
4717 type PolicyKey = (std::path::PathBuf, u64, Option<std::time::SystemTime>);
4718
4719 let Some(path) = default_execpolicy_path() else {
4720 return Ok(None);
4721 };
4722 // An unreadable or missing file (including a permissions error, which
4723 // `exists()` also swallows) means "no file rules" — the same answer as
4724 // before, just reached with one `stat` instead of an existence check plus a
4725 // full read.
4726 let Ok(metadata) = std::fs::metadata(&path) else {
4727 return Ok(None);
4728 };
4729 let key: PolicyKey = (path.clone(), metadata.len(), metadata.modified().ok());
4730
4731 // #6208: this runs on every shell execution, so the read and TOML parse
4732 // happen only when the file's identity changes. Length joins the timestamp
4733 // because a coarse-mtime filesystem can hand back the same instant for two
4734 // different revisions.
4735 static CACHE: std::sync::OnceLock<std::sync::Mutex<Option<(PolicyKey, ExecPolicyConfig)>>> =
4736 std::sync::OnceLock::new();
4737 let cache = CACHE.get_or_init(|| std::sync::Mutex::new(None));
4738 let mut cache = cache
4739 .lock()
4740 .unwrap_or_else(|poisoned| poisoned.into_inner());
4741 if let Some((cached_key, config)) = cache.as_ref()
4742 && *cached_key == key
4743 {
4744 return Ok(Some(config.clone()));
4745 }
4746
4747 let config = ExecPolicyConfig::from_path(&path)?;
4748 *cache = Some((key, config.clone()));
4749 Ok(Some(config))
4750 }
4751
4752 /// The last `n` lines of `text`, marking how many were left out.
4753 fn tail_lines(text: &str, n: usize) -> String {
4754 let lines: Vec<&str> = text.lines().collect();
4755 if lines.len() <= n {
4756 return text.to_string();
4757 }
4758 format!(
4759 "[{} earlier lines]\n{}",
4760 lines.len() - n,
4761 lines[lines.len() - n..].join("\n")
4762 )
4763 }
4764
4765 const MACOS_PROVENANCE_HINT: &str = "Docker buildx failed to update its activity file due to a macOS \
4766 com.apple.provenance restriction. Files created by Docker Desktop's signed process carry a \
4767 kernel-enforced provenance tag that blocks writes from child processes (including the TUI \
4768 shell sandbox). Workarounds: (1) run the Docker build from a regular terminal outside the \
4769 TUI, or (2) disable BuildKit with DOCKER_BUILDKIT=0 (only works if your Dockerfiles do not \
4770 use RUN --mount directives).";
4771
4772 /// Human-readable exit status for a shell result: the numeric code when the
4773 /// process returned one, or "terminated by signal" when it did not (rather
4774 /// than leaking `Some(127)` / `None` Debug output to the user).
4775 fn exit_code_label(code: Option<i64>) -> String {
4776 match (code, exit_code_hex(code)) {
4777 (Some(code), Some(hex)) => format!("exit code {code} ({hex})"),
4778 (Some(code), None) => format!("exit code {code}"),
4779 (None, _) => "terminated by signal".to_string(),
4780 }
4781 }
4782
4783 fn exit_code_hex(code: Option<i64>) -> Option<String> {
4784 code.filter(|code| *code > i64::from(i32::MAX) && *code <= i64::from(u32::MAX))
4785 .map(|code| format!("0x{code:08X}"))
4786 }
4787 const PYTHON_BUILD_DEPENDENCY_HINT: &str = "Python build dependency missing: setuptools is not \
4788 available in the active environment. Install the declared build requirements first, for example \
4789 `python -m pip install -U pip setuptools wheel build`, then rerun the build command.";
4790
4791 fn attach_cargo_failure_summary(
4792 metadata: &mut serde_json::Value,
4793 command: &str,
4794 result: &ShellResult,
4795 ) {
4796 if let Some(summary) = summarize_cargo_failure(
4797 command,
4798 &result.stdout,
4799 &result.stderr,
4800 result.exit_code.and_then(|code| i32::try_from(code).ok()),
4801 ) {
4802 metadata["cargo_failure_summary"] = summary.to_metadata_value();
4803 }
4804 }
4805
4806 fn attach_python_build_dependency_hint(
4807 metadata: &mut serde_json::Value,
4808 hint: Option<&'static str>,
4809 ) {
4810 if let Some(hint) = hint {
4811 metadata["python_build_dependency_hint"] = json!({
4812 "kind": "missing_setuptools",
4813 "hint": hint,
4814 "recommended_first_step": "python -m pip install -U pip setuptools wheel build",
4815 });
4816 }
4817 }
4818
4819 pub fn looks_like_macos_provenance_failure(result: &ShellResult) -> bool {
4820 if matches!(result.status, ShellStatus::Completed) && result.exit_code == Some(0) {
4821 return false;
4822 }
4823 let combined = format!("{}\n{}", result.stdout, result.stderr).to_ascii_lowercase();
4824 combined.contains("com.apple.provenance")
4825 || combined.contains("update builder last activity")
4826 || (combined.contains("buildx/activity") && combined.contains("operation not permitted"))
4827 }
4828
4829 fn macos_provenance_hint(result: &ShellResult) -> Option<&'static str> {
4830 if looks_like_macos_provenance_failure(result) {
4831 Some(MACOS_PROVENANCE_HINT)
4832 } else {
4833 None
4834 }
4835 }
4836
4837 fn python_build_dependency_hint(command: &str, result: &ShellResult) -> Option<&'static str> {
4838 if matches!(result.status, ShellStatus::Completed) && result.exit_code == Some(0) {
4839 return None;
4840 }
4841
4842 let command = command.to_ascii_lowercase();
4843 let combined = format!("{}\n{}", result.stdout, result.stderr).to_ascii_lowercase();
4844 let mentions_missing_setuptools = [
4845 "no module named 'setuptools'",
4846 "no module named \"setuptools\"",
4847 "setuptools is not available",
4848 "cannot import 'setuptools",
4849 "cannot import \"setuptools",
4850 "missing dependencies",
4851 ]
4852 .iter()
4853 .any(|needle| combined.contains(needle))
4854 && combined.contains("setuptools");
4855 if !mentions_missing_setuptools {
4856 return None;
4857 }
4858
4859 let pythonish_command = [
4860 "python",
4861 "pip",
4862 "pytest",
4863 "tox",
4864 "nox",
4865 "cython",
4866 "setup.py",
4867 "build_ext",
4868 ]
4869 .iter()
4870 .any(|needle| command.contains(needle));
4871 let pythonish_output = [
4872 "setup.py",
4873 "pyproject.toml",
4874 "build_meta",
4875 "build_ext",
4876 "pep 517",
4877 "cython",
4878 ]
4879 .iter()
4880 .any(|needle| combined.contains(needle));
4881
4882 if pythonish_command || pythonish_output {
4883 Some(PYTHON_BUILD_DEPENDENCY_HINT)
4884 } else {
4885 None
4886 }
4887 }
4888
4889 fn command_likely_needs_network(command: &str) -> bool {
4890 let normalized = command.to_ascii_lowercase();
4891 let Some(primary) = extract_primary_command(&normalized) else {
4892 return false;
4893 };
4894 let primary = primary.rsplit(['/', '\\']).next().unwrap_or(primary);
4895
4896 match primary {
4897 "curl" | "wget" | "fetch" | "nc" | "netcat" | "ncat" | "ssh" | "scp" | "sftp" | "rsync"
4898 | "ftp" | "ping" | "traceroute" | "nslookup" | "dig" | "host" | "nmap" | "gh" | "hub" => {
4899 true
4900 }
4901 "git" => [
4902 " fetch",
4903 " pull",
4904 " clone",
4905 " ls-remote",
4906 " submodule",
4907 " push",
4908 ]
4909 .iter()
4910 .any(|needle| normalized.contains(needle)),
4911 "cargo" => [" install", " fetch", " update", " publish", " search"]
4912 .iter()
4913 .any(|needle| normalized.contains(needle)),
4914 "npm" | "pnpm" | "yarn" => [" install", " i", " add", " update", " publish"]
4915 .iter()
4916 .any(|needle| normalized.contains(needle)),
4917 "pip" | "pip3" | "uv" | "poetry" => [" install", " add", " sync", " update"]
4918 .iter()
4919 .any(|needle| normalized.contains(needle)),
4920 "brew" | "apt" | "apt-get" | "yum" | "dnf" | "pacman" => true,
4921 "go" => [" get", " install", " mod download"]
4922 .iter()
4923 .any(|needle| normalized.contains(needle)),
4924 _ => false,
4925 }
4926 }
4927
4928 fn looks_like_network_blocked_failure(result: &ShellResult) -> bool {
4929 if matches!(result.status, ShellStatus::Completed | ShellStatus::Running)
4930 || result.exit_code == Some(0)
4931 {
4932 return false;
4933 }
4934
4935 if result.stdout.trim() == "000" {
4936 return true;
4937 }
4938 if result.sandboxed && result.stdout.is_empty() && result.stderr.is_empty() {
4939 return true;
4940 }
4941
4942 let output = format!("{}\n{}", result.stdout, result.stderr).to_ascii_lowercase();
4943 [
4944 "operation not permitted",
4945 "network is unreachable",
4946 "could not resolve host",
4947 "couldn't resolve host",
4948 "failed to resolve",
4949 "temporary failure in name resolution",
4950 "name or service not known",
4951 "nodename nor servname provided",
4952 "no address associated",
4953 "failed to connect",
4954 "couldn't connect",
4955 "connection timed out",
4956 "connection reset",
4957 "error connecting to",
4958 "token in keyring is invalid",
4959 ]
4960 .iter()
4961 .any(|pattern| output.contains(pattern))
4962 }
4963
4964 const READONLY_OFFLINE_NETWORK_HINT: &str = "This read_only run has no network and cannot write files outside its private TMPDIR. Read-only commands reach the network only in Full Access, with a session sandbox that allows network, a [network] policy that does not deny by default, and this agent's network grant. Use a web tool if this session has one; otherwise report the source as unreachable.";
4965
4966 const READONLY_WRITE_DENIED_HINT: &str = "read_only=true can write only to its private TMPDIR, which is deleted when the command ends; the workspace, home, Git metadata and every other path stay read-only. A command that must write (git fetch writes .git/FETCH_HEAD; git ls-remote reads remote refs without writing) has to run without read_only.";
4967
4968 const READONLY_AGENT_WRITE_DENIED_HINT: &str = "read_only=true can write only to its private TMPDIR, which is deleted when the command ends; the workspace, home, Git metadata and every other path stay read-only. This read-only agent cannot run mutating commands; return your findings and the blocked command to the parent.";
4969
4970 const READONLY_SESSION_WRITE_DENIED_HINT: &str = "read_only=true can write only to its private TMPDIR, which is deleted when the command ends; the workspace, home, Git metadata and every other path stay read-only. This read-only session cannot run mutating commands; the user can change modes with /mode.";
4971
4972 const READONLY_MACOS_MKTEMP_HINT: &str = "macOS mktemp ignores TMPDIR unless told otherwise and writes to the per-user temporary directory, which read_only cannot write. Use `mktemp -p \"$TMPDIR\"` or `mktemp \"$TMPDIR/name.XXXXXX\"`.";
4973
4974 const READONLY_MACOS_HEREDOC_HINT: &str = "macOS /bin/sh and /bin/bash ignore TMPDIR for here-documents (<<EOF) and write to /var/tmp, which read_only cannot write. Run the heredoc with `/bin/zsh -c '...'` (which uses the private TMPDIR), pipe with `printf ... |`, or pass input via a file under `\"$TMPDIR\"`.";
4975
4976 const READONLY_SETUID_DENIED_HINT: &str = "macOS Seatbelt never starts a setuid program such as ps or top inside a sandbox. List processes with `pgrep -lf <pattern>` or `lsof -nP -iTCP -sTCP:LISTEN` instead.";
4977
4978 fn split_shell_separators(token: &str) -> Vec<&str> {
4979 let mut out = Vec::new();
4980 let mut start = 0;
4981 let bytes = token.as_bytes();
4982 let mut i = 0;
4983 while i < bytes.len() {
4984 let sep_len = if bytes[i..].starts_with(b"||") || bytes[i..].starts_with(b"&&") {
4985 2
4986 } else if matches!(
4987 bytes[i],
4988 b';' | b'|' | b'&' | b'(' | b')' | b'\n' | b'<' | b'>'
4989 ) {
4990 1
4991 } else {
4992 0
4993 };
4994 if sep_len > 0 {
4995 if start < i {
4996 out.push(&token[start..i]);
4997 }
4998 out.push(&token[i..i + sep_len]);
4999 i += sep_len;
5000 start = i;
5001 } else {
5002 i += 1;
5003 }
5004 }
5005 if start < bytes.len() {
5006 out.push(&token[start..]);
5007 }
5008 out
5009 }
5010
5011 fn command_invokes_program(command: &str, target: &str) -> bool {
5012 let mut expect_command = true;
5013 let mut in_shell_invocation = false;
5014 let mut after_shell_c = false;
5015 let tokens = shell_words::split(command).unwrap_or_else(|_| {
5016 command
5017 .split_whitespace()
5018 .map(|token| token.trim_matches(['\'', '"']).to_string())
5019 .collect()
5020 });
5021 for token in tokens {
5022 for piece in split_shell_separators(&token) {
5023 if piece.is_empty() {
5024 continue;
5025 }
5026 if matches!(piece, ";" | "|" | "||" | "&" | "&&" | "(" | ")" | "\n") {
5027 expect_command = true;
5028 in_shell_invocation = false;
5029 after_shell_c = false;
5030 continue;
5031 }
5032 if after_shell_c {
5033 after_shell_c = false;
5034 if command_invokes_program(piece, target) {
5035 return true;
5036 }
5037 expect_command = false;
5038 continue;
5039 }
5040 if expect_command {
5041 if piece.contains('=') && !piece.starts_with('=') {
5042 continue;
5043 }
5044 if matches!(
5045 piece,
5046 "command" | "exec" | "env" | "nohup" | "time" | "nice"
5047 ) {
5048 continue;
5049 }
5050 let base = piece.rsplit('/').next().unwrap_or(piece);
5051 let matches_target = base == target
5052 && (piece == target
5053 || match target {
5054 "ps" => piece == "/bin/ps",
5055 "top" => piece == "/usr/bin/top",
5056 _ => true,
5057 });
5058 if matches_target {
5059 return true;
5060 }
5061 in_shell_invocation = matches!(base, "sh" | "bash" | "zsh" | "dash" | "ksh");
5062 expect_command = false;
5063 } else if in_shell_invocation && piece.starts_with('-') && piece.contains('c') {
5064 after_shell_c = true;
5065 in_shell_invocation = false;
5066 } else if !piece.starts_with('-') {
5067 in_shell_invocation = false;
5068 }
5069 }
5070 }
5071 false
5072 }
5073
5074 fn mentions_denied_program(output: &str, name: &str, abs_path: &str) -> bool {
5075 output.contains(&format!("{abs_path}: operation not permitted"))
5076 || output.contains(&format!("operation not permitted: {abs_path}"))
5077 || output.contains(&format!("operation not permitted: '{abs_path}'"))
5078 || output.contains(&format!("operation not permitted: {name}"))
5079 || output.contains(&format!("{name}: operation not permitted"))
5080 }
5081
5082 fn readonly_write_denied_hint(context: &ToolContext) -> &'static str {
5083 if matches!(context.shell_policy, ShellPolicy::ReadOnly) {
5084 if context.owner_agent_id.is_some() || context.tool_authority.is_some() {
5085 READONLY_AGENT_WRITE_DENIED_HINT
5086 } else {
5087 READONLY_SESSION_WRITE_DENIED_HINT
5088 }
5089 } else {
5090 READONLY_WRITE_DENIED_HINT
5091 }
5092 }
5093
5094 fn readonly_denied_hint(
5095 context: &ToolContext,
5096 command: &str,
5097 result: &ShellResult,
5098 ) -> Option<&'static str> {
5099 readonly_denied_hint_for_os(context, command, result, cfg!(target_os = "macos"))
5100 }
5101
5102 fn readonly_denied_hint_for_os(
5103 context: &ToolContext,
5104 command: &str,
5105 result: &ShellResult,
5106 is_macos: bool,
5107 ) -> Option<&'static str> {
5108 if matches!(result.status, ShellStatus::Completed | ShellStatus::Running)
5109 || result.exit_code == Some(0)
5110 {
5111 return None;
5112 }
5113 if result.sandbox_denied && codewhale_sandbox::bwrap_setup_failure(&result.stderr).is_some() {
5114 return None;
5115 }
5116 let output = format!("{}\n{}", result.stdout, result.stderr).to_ascii_lowercase();
5117 if !output.contains("operation not permitted") && !output.contains("read-only file system") {
5118 return None;
5119 }
5120 if is_macos {
5121 if output.contains("cannot create temp file for here document") {
5122 return Some(READONLY_MACOS_HEREDOC_HINT);
5123 }
5124 if (command_invokes_program(command, "ps")
5125 && mentions_denied_program(&output, "ps", "/bin/ps"))
5126 || (command_invokes_program(command, "top")
5127 && mentions_denied_program(&output, "top", "/usr/bin/top"))
5128 {
5129 return Some(READONLY_SETUID_DENIED_HINT);
5130 }
5131 if command_invokes_program(command, "mktemp")
5132 && (output.contains("mkstemp failed") || output.contains("mkdtemp failed"))
5133 {
5134 return Some(READONLY_MACOS_MKTEMP_HINT);
5135 }
5136 }
5137 Some(readonly_write_denied_hint(context))
5138 }
5139
5140 fn readonly_offline_network_hint(command: &str, result: &ShellResult) -> Option<&'static str> {
5141 if result.sandbox_denied && codewhale_sandbox::bwrap_setup_failure(&result.stderr).is_some() {
5142 return None;
5143 }
5144 let output = format!("{}\n{}", result.stdout, result.stderr).to_ascii_lowercase();
5145 if output.contains("read-only file system") || output.contains("fetch_head") {
5146 return None;
5147 }
5148 let rest = split_leading_cd(command).map(|(_, rest)| rest);
5149 let command = rest.as_deref().unwrap_or(command);
5150 (command_likely_needs_network(command)
5151 && (result.sandbox_denied || looks_like_network_blocked_failure(result)))
5152 .then_some(READONLY_OFFLINE_NETWORK_HINT)
5153 }
5154
5155 fn shell_network_restricted_hint<'a>(
5156 context: &'a ToolContext,
5157 command: &str,
5158 result: &ShellResult,
5159 ) -> Option<&'a str> {
5160 if result.sandbox_denied && codewhale_sandbox::bwrap_setup_failure(&result.stderr).is_some() {
5161 return None;
5162 }
5163 let hint = context.shell_network_denied_hint.as_deref()?;
5164 let policy_blocks_network = context
5165 .elevated_sandbox_policy
5166 .as_ref()
5167 .is_some_and(|policy| !policy.has_network_access());
5168 if !policy_blocks_network || !command_likely_needs_network(command) {
5169 return None;
5170 }
5171 if result.sandbox_denied || looks_like_network_blocked_failure(result) {
5172 Some(hint)
5173 } else {
5174 None
5175 }
5176 }
5177
5178 /// Coaching line when the execution sandbox denied a command and the
5179 /// Plan-mode network hint did not already explain it. Most often a write under
5180 /// a read-only posture: name the effective posture and the Ask-only retry shape
5181 /// so other postures do not mistake it for autonomous authority.
5182 fn shell_sandbox_denied_hint(context: &ToolContext, result: &ShellResult) -> Option<String> {
5183 if !result.sandbox_denied {
5184 return None;
5185 }
5186 if let Some(error) = codewhale_sandbox::bwrap_setup_failure(&result.stderr) {
5187 return Some(format!(
5188 "The Linux sandbox (bubblewrap) could not be set up, so this command did not run and nothing ran outside the sandbox: {error}. Every sandboxed command fails the same way until the cause it names is fixed or removed, or `prefer_bwrap = false` is set to run without the OS sandbox. [sandbox: Ask-only escalation — to run only this command without the sandbox, retry it once with sandbox_permissions \"danger-full-access\" + justification; the approval prompt asks the user]"
5189 ));
5190 }
5191 let policy = context.elevated_sandbox_policy.as_ref()?;
5192 Some(format!(
5193 "The execution sandbox blocked this command. Effective sandbox posture: {}. [sandbox: Ask-only escalation — retry this exact command once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]",
5194 policy.posture_label()
5195 ))
5196 }
5197
5198 pub(super) fn shell_job_owner_from_context(context: &ToolContext) -> Option<ShellJobOwner> {
5199 let agent_id = context
5200 .owner_agent_id
5201 .as_deref()
5202 .map(str::trim)
5203 .filter(|value| !value.is_empty())?;
5204 let agent_name = context
5205 .owner_agent_name
5206 .as_deref()
5207 .map(str::trim)
5208 .filter(|value| !value.is_empty())
5209 .unwrap_or(agent_id);
5210 Some(ShellJobOwner {
5211 agent_id: agent_id.to_string(),
5212 agent_name: agent_name.to_string(),
5213 })
5214 }
5215
5216 pub(super) fn shell_work_lifecycle_from_context(
5217 context: &ToolContext,
5218 ) -> Option<ShellWorkLifecycle> {
5219 context
5220 .runtime
5221 .work
5222 .as_ref()
5223 .map(|work| ShellWorkLifecycle {
5224 work: work.clone(),
5225 session_id: context.state_namespace.clone(),
5226 })
5227 }
5228
5229 fn lifecycle_now_ms() -> i64 {
5230 std::time::SystemTime::now()
5231 .duration_since(std::time::UNIX_EPOCH)
5232 .unwrap_or_default()
5233 .as_millis()
5234 .try_into()
5235 .unwrap_or(i64::MAX)
5236 }
5237
5238 fn attach_shell_owner_metadata(metadata: &mut serde_json::Value, context: &ToolContext) {
5239 let Some(owner) = shell_job_owner_from_context(context) else {
5240 return;
5241 };
5242 metadata["owner_agent_id"] = json!(owner.agent_id);
5243 metadata["owner_agent_name"] = json!(owner.agent_name);
5244 }
5245
5246 /// NUL bytes cannot cross the `exec` boundary: `Command` panics on them.
5247 /// Refuse with the byte offset before anything spawns (#5529).
5248 fn require_no_nul<'a>(value: &'a str, field: &str) -> Result<&'a str, ToolError> {
5249 if let Some(offset) = value.find('\0') {
5250 return Err(ToolError::invalid_input(format!(
5251 "Shell {field} contains a NUL byte at byte offset {offset}; it cannot cross the exec boundary. Remove it (usually a truncated heredoc or binary paste) and re-send."
5252 )));
5253 }
5254 Ok(value)
5255 }
5256
5257 /// Apply the network policy to every network read inside a read-only
5258 /// command, segment by segment, so a pipeline or chain cannot hide one.
5259 /// A full shell keeps its historical scope here: only a lone `gh` read is
5260 /// judged, because its other network use is governed elsewhere.
5261 fn enforce_readonly_network_reads(command: &str, context: &ToolContext) -> Result<(), ToolError> {
5262 let Some(decider) = context.network_policy.as_ref() else {
5263 return Ok(());
5264 };
5265 let mut reads = readonly_network_reads(command);
5266 if context.shell_policy != ShellPolicy::ReadOnly {
5267 let lone = agent_readonly_verdict(command).is_ok_and(|segments| segments.len() == 1);
5268 reads.retain(|read| lone && *read == NetworkRead::GitHub);
5269 }
5270 use codewhale_net::network_policy::Decision;
5271 for read in reads {
5272 let host = read.host();
5273 match decider.evaluate(host, "Bash") {
5274 Decision::Allow => {}
5275 Decision::Deny => {
5276 return Err(ToolError::permission_denied(format!(
5277 "Read-only network access to '{host}' is blocked by the active network policy."
5278 )));
5279 }
5280 Decision::Prompt => {
5281 return Err(ToolError::permission_denied(format!(
5282 "Read-only network access to '{host}' requires network approval; allow that host in the parent session or network policy first."
5283 )));
5284 }
5285 }
5286 }
5287 Ok(())
5288 }
5289
5290 /// This is a request for mandatory filesystem isolation, not a claim
5291 /// about what the command does. The executor refuses it without a native
5292 /// enforcing sandbox and checks the prepared environment again before spawn.
5293 fn enforced_readonly_input(input: &serde_json::Value) -> bool {
5294 let Some(fields) = input.as_object() else {
5295 return false;
5296 };
5297 fields.get("read_only").and_then(serde_json::Value::as_bool) == Some(true)
5298 && fields.keys().all(|key| {
5299 matches!(
5300 key.as_str(),
5301 "action"
5302 | "command"
5303 | "cwd"
5304 | "timeout_ms"
5305 | "read_only"
5306 | "description"
5307 | "background"
5308 )
5309 })
5310 && fields
5311 .get("description")
5312 .is_none_or(|value| value.is_null() || value.is_string())
5313 && fields
5314 .get("background")
5315 .is_none_or(|value| value == &serde_json::Value::Bool(false))
5316 && fields
5317 .get("action")
5318 .is_none_or(|action| action.as_str() == Some("run"))
5319 && fields
5320 .get("command")
5321 .and_then(serde_json::Value::as_str)
5322 .is_some_and(|command| !command.trim().is_empty())
5323 }
5324
5325 fn is_native_readonly_sandbox(sandbox_type: SandboxType) -> bool {
5326 match sandbox_type {
5327 #[cfg(target_os = "macos")]
5328 SandboxType::MacosSeatbelt => true,
5329 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
5330 SandboxType::LinuxBubblewrap => true,
5331 _ => false,
5332 }
5333 }
5334
5335 /// Build the child for a tool that runs workspace code outside `exec_shell`
5336 /// (gate commands, the cargo test runner). It gets exactly the confinement a
5337 /// shell command gets in this session: the same policy, the same OS sandbox
5338 /// wrapper, and the sanitized child environment. Callers keep their own
5339 /// process-tree containment, timeout and cancellation.
5340 ///
5341 /// Known limitations: where the platform has no enforcing sandbox configured
5342 /// (Linux without bubblewrap, Windows) a workspace-write policy runs
5343 /// unsandboxed, as it does for `exec_shell`; a read-only policy refuses there.
5344 /// A session whose commands run in an external sandbox backend cannot run
5345 /// these local children at all.
5346 pub fn sandboxed_runner_command(
5347 context: &crate::tools::spec::ToolContext,
5348 program: &str,
5349 args: Vec<String>,
5350 cwd: &Path,
5351 timeout: Duration,
5352 ) -> std::result::Result<tokio::process::Command, crate::tools::spec::ToolError> {
5353 use crate::tools::spec::ToolError;
5354 if context.sandbox_backend.is_some() {
5355 return Err(ToolError::not_available(
5356 "this tool starts a local process, and this session runs commands in an external sandbox; run the command through the shell tool instead",
5357 ));
5358 }
5359 let exec_env = context
5360 .shell_manager
5361 .lock()
5362 .unwrap_or_else(std::sync::PoisonError::into_inner)
5363 .prepare_runner(
5364 program,
5365 args,
5366 cwd,
5367 &context.workspace,
5368 timeout,
5369 context.elevated_sandbox_policy.clone(),
5370 );
5371 if matches!(exec_env.policy, ExecutionSandboxPolicy::ReadOnly { .. }) {
5372 require_native_readonly_execution(&exec_env)
5373 .map_err(|error| ToolError::permission_denied(error.to_string()))?;
5374 }
5375 let mut cmd = tokio::process::Command::new(exec_env.program());
5376 codewhale_util::utils::suppress_tokio_console_window(&mut cmd);
5377 cmd.args(exec_env.args())
5378 .current_dir(&exec_env.cwd)
5379 .stdout(std::process::Stdio::piped())
5380 .stderr(std::process::Stdio::piped());
5381 // Workspace code never inherits parent credentials.
5382 codewhale_runtime::child_env::apply_to_tokio_command(
5383 &mut cmd,
5384 codewhale_runtime::child_env::string_map_env(&exec_env.env),
5385 );
5386 Ok(cmd)
5387 }
5388
5389 fn require_native_readonly_execution(exec_env: &ExecEnv) -> Result<()> {
5390 if matches!(exec_env.policy, ExecutionSandboxPolicy::ReadOnly { .. })
5391 && is_native_readonly_sandbox(exec_env.sandbox_type)
5392 {
5393 Ok(())
5394 } else {
5395 Err(anyhow!(
5396 "read_only execution requires an enforcing native read-only sandbox; nothing was run"
5397 ))
5398 }
5399 }
5400
5401 /// `exec_shell_input_is_parallel_readonly` with the agent-posture classifier:
5402 /// same input-shape restrictions (run action only, no background/tty/stdin),
5403 /// but commands are judged by
5404 /// [`codewhale_execpolicy::command_safety::agent_readonly_verdict`] so
5405 /// `ShellPolicy::ReadOnly` agents keep a usable inspection surface
5406 /// (pipelines and chains of reads, globs, `git -C`, `find`, `sed -n`,
5407 /// `npm view`). Callers pass input already through [`normalize_readonly_cd`].
5408 fn exec_shell_input_agent_readonly_verdict(
5409 input: &serde_json::Value,
5410 ) -> Result<(), ReadonlyRejection> {
5411 if enforced_readonly_input(input) {
5412 return Ok(());
5413 }
5414 if !exec_shell_input_is_parallel_readonly_shape(input) {
5415 return Err(ReadonlyRejection::new(
5416 "shape",
5417 "read-only shell accepts only a foreground `command` with optional `cwd` and timeout; background, stdin, interactive and TTY modes are not admitted",
5418 ));
5419 }
5420 let command = input
5421 .get("command")
5422 .and_then(serde_json::Value::as_str)
5423 .expect("shape check established a command string");
5424 agent_readonly_verdict(command).map(|_| ())
5425 }
5426
5427 /// Move a leading `cd <dir> &&` into the `cwd` field, resolved against any
5428 /// `cwd` already present, so no gate has to interpret `cd`: the ordinary
5429 /// working-directory workspace check then judges the directory, and every
5430 /// gate and the executor see the same rewritten input. Only the shape
5431 /// [`split_leading_cd`] accepts is rewritten; `read_only: true` input runs
5432 /// its command unchanged under the enforced lane.
5433 pub fn normalize_readonly_cd(input: &serde_json::Value) -> serde_json::Value {
5434 let mut input = input.clone();
5435 if enforced_readonly_input(&input) {
5436 return input;
5437 }
5438 // Bounded: each pass removes one leading `cd`.
5439 for _ in 0..4 {
5440 let Some((dir, rest)) = input
5441 .get("command")
5442 .and_then(serde_json::Value::as_str)
5443 .and_then(split_leading_cd)
5444 else {
5445 break;
5446 };
5447 let cwd = match input.get("cwd") {
5448 None | Some(serde_json::Value::Null) => dir,
5449 Some(serde_json::Value::String(existing)) => std::path::Path::new(existing)
5450 .join(&dir)
5451 .to_string_lossy()
5452 .into_owned(),
5453 // A wrong type is reported by the executor's own type check.
5454 Some(_) => break,
5455 };
5456 input["command"] = json!(rest);
5457 input["cwd"] = json!(cwd);
5458 }
5459 input
5460 }
5461
5462 /// The refusal a read-only agent sees, shared by every gate that judges the
5463 /// agent grammar (subagent posture, durable authority, and the executor), so
5464 /// the rule text is byte-identical wherever a command is refused. The next
5465 /// steps name only tools such an agent has.
5466 pub fn readonly_refusal(rejection: &ReadonlyRejection, enforced_lane: bool) -> String {
5467 let lane = if enforced_lane {
5468 ", rerun it with `read_only: true` to run it in an enforced read-only sandbox"
5469 } else {
5470 ""
5471 };
5472 format!(
5473 "{rejection}. Next: use admitted reads only (the shell tool description lists the grammar), read or search files with the File tool{lane}, or, if the probe is essential, return your findings and the blocked probe to the parent."
5474 )
5475 }
5476
5477 /// Whether `read_only: true` can run here: a native enforcing sandbox and
5478 /// no external backend.
5479 pub fn readonly_enforced_lane_available(context: &ToolContext) -> bool {
5480 context.sandbox_backend.is_none()
5481 && context.shell_manager.lock().is_ok_and(|manager| {
5482 manager
5483 .configured_sandbox_type()
5484 .is_some_and(is_native_readonly_sandbox)
5485 })
5486 }
5487
5488 pub fn readonly_lane_network_access(context: &ToolContext) -> bool {
5489 (context.auto_approve || context.approval_mode == codewhale_execpolicy::ApprovalMode::Bypass)
5490 && context
5491 .elevated_sandbox_policy
5492 .as_ref()
5493 .is_some_and(ExecutionSandboxPolicy::has_network_access)
5494 && context
5495 .network_policy
5496 .as_ref()
5497 .is_none_or(|decider| !decider.denies_by_default())
5498 && crate::tools::web::fetch::network_authorized(context)
5499 }
5500
5501 /// `exec_shell_input_agent_readonly_verdict` is also the gate-side predicate for the
5502 /// subagent posture check (#5426): the catalog carve-out that admits
5503 /// canonical `bash` to Scout/Reviewer/Planner must judge the same call the
5504 /// `BashTool::execute` `ShellPolicy::ReadOnly` branch will judge, so the
5505 /// posture gate can admit a proven-readonly call without ever widening past
5506 /// the execute-time refusal.
5507 pub fn agent_readonly_bash_input(input: &serde_json::Value) -> bool {
5508 agent_readonly_bash_verdict(input).is_ok()
5509 }
5510
5511 /// [`agent_readonly_bash_input`] with the rule that refused the call.
5512 pub fn agent_readonly_bash_verdict(input: &serde_json::Value) -> Result<(), ReadonlyRejection> {
5513 // Canonical lowercase `bash` advertises `timeout` in seconds, while the
5514 // internal executor contract uses `timeout_ms`. Normalize through the same
5515 // translator the concrete tool uses so posture, session approval, envelope,
5516 // and execute judge one input (#5595). Legacy/internal shapes fall back to
5517 // their existing direct classification. A leading `cd` is then moved into
5518 // `cwd` exactly as `BashTool::execute` does.
5519 let translated = contract_bash_legacy_input(input).unwrap_or_else(|_| input.clone());
5520 exec_shell_input_agent_readonly_verdict(&normalize_readonly_cd(&translated))
5521 }
5522
5523 fn exec_shell_input_is_parallel_readonly(input: &serde_json::Value) -> bool {
5524 if enforced_readonly_input(input) {
5525 return true;
5526 }
5527 if !exec_shell_input_is_parallel_readonly_shape(input) {
5528 return false;
5529 }
5530 let command = input
5531 .get("command")
5532 .and_then(serde_json::Value::as_str)
5533 .expect("shape check established a command string");
5534 is_parallel_readonly_command(command)
5535 }
5536
5537 fn exec_shell_input_is_parallel_readonly_shape(input: &serde_json::Value) -> bool {
5538 let Some(fields) = input.as_object() else {
5539 return false;
5540 };
5541 if fields.keys().any(|key| {
5542 !matches!(
5543 key.as_str(),
5544 "action" | "command" | "cwd" | "timeout_ms" | "description" | "background"
5545 )
5546 }) {
5547 return false;
5548 }
5549 if fields
5550 .get("description")
5551 .is_some_and(|value| !value.is_null() && !value.is_string())
5552 {
5553 return false;
5554 }
5555 match input.get("action") {
5556 None | Some(serde_json::Value::Null) => {}
5557 Some(serde_json::Value::String(action)) if action == "run" => {}
5558 Some(_) => return false,
5559 }
5560 if ["background", "interactive", "tty", "combined_output"]
5561 .iter()
5562 .any(|key| {
5563 !matches!(
5564 input.get(*key),
5565 None | Some(serde_json::Value::Null | serde_json::Value::Bool(false))
5566 )
5567 })
5568 {
5569 return false;
5570 }
5571 if ["stdin", "input", "data"]
5572 .iter()
5573 .any(|key| input.get(*key).is_some())
5574 {
5575 return false;
5576 }
5577 if ["task_id", "id", "wait", "block", "close_stdin", "all"]
5578 .iter()
5579 .any(|key| input.get(*key).is_some())
5580 {
5581 return false;
5582 }
5583
5584 input
5585 .get("command")
5586 .and_then(serde_json::Value::as_str)
5587 .is_some()
5588 }
5589
5590 /// Whether a classifier-approved read needs a shell to join its segments or
5591 /// apply an admitted redirect; a lone plain command runs as direct argv.
5592 fn readonly_command_needs_shell(command: &str) -> bool {
5593 agent_readonly_verdict(command).map_or(true, |segments| {
5594 segments.len() > 1 || segments.iter().any(|segment| !segment.redirects.is_empty())
5595 })
5596 }
5597
5598 fn hardened_readonly_script(command: &str, workspace: &std::path::Path) -> Result<String> {
5599 use codewhale_sandbox::shell_dispatcher::ShellKind;
5600 // POSIX quoting must never be passed to a different command interpreter.
5601 let supported = match codewhale_sandbox::shell_dispatcher::global_dispatcher().kind() {
5602 ShellKind::Bash => true,
5603 ShellKind::Custom { binary, .. } => matches!(
5604 std::path::Path::new(binary)
5605 .file_name()
5606 .and_then(|name| name.to_str()),
5607 Some("bash" | "zsh")
5608 ),
5609 _ => false,
5610 };
5611 if !supported {
5612 return Err(anyhow!(
5613 "read-only pipelines and chains require bash or zsh; run each read separately"
5614 ));
5615 }
5616 let segments = agent_readonly_verdict(command)
5617 .map_err(|rejection| anyhow!("command is outside the read-only policy: {rejection}"))?;
5618 let mut script = String::from("set -o pipefail;");
5619 for segment in &segments {
5620 let (program, args) = hardened_readonly_argv(&segment.command)?;
5621 let program = resolve_readonly_program(&program, workspace)?;
5622 let program = program
5623 .to_str()
5624 .ok_or_else(|| anyhow!("read-only executable path is not valid UTF-8"))?;
5625 for word in std::iter::once(program).chain(args.iter().map(String::as_str)) {
5626 script.push(' ');
5627 script.push_str(&shell_words::quote(word));
5628 }
5629 for redirect in &segment.redirects {
5630 script.push(' ');
5631 script.push_str(redirect);
5632 }
5633 if let Some(join) = segment.join {
5634 script.push(' ');
5635 script.push_str(join.as_str());
5636 }
5637 }
5638 // The only shell syntax is the admitted operators and redirect words.
5639 // Filenames cannot expand into options or unvalidated symlinks; every Git
5640 // stage retains helper guards.
5641 Ok(script)
5642 }
5643
5644 fn hardened_readonly_argv(command: &str) -> Result<(String, Vec<String>)> {
5645 let mut argv = shell_words::split(&normalize_windows_command_paths(command))
5646 .map_err(|error| anyhow!("could not parse classifier-approved read command: {error}"))?;
5647 if argv.is_empty() {
5648 return Err(anyhow!("classifier-approved read command was empty"));
5649 }
5650
5651 // Even when repository/user configuration names a diff or signature
5652 // helper, these flags make Git keep the read inside its own process.
5653 if argv.first().is_some_and(|program| program == "git") {
5654 // The agent read-only classifier admits `git -C <dir>` and
5655 // `git --no-pager` before the subcommand; keep the preamble but
5656 // locate the subcommand after it so the hardening flags splice in
5657 // the right place. `-C` targets were already workspace-checked by
5658 // `enforce_readonly_workspace_operands`.
5659 let mut subcommand_index = 1;
5660 while let Some(flag) = argv.get(subcommand_index) {
5661 match flag.as_str() {
5662 "--no-pager" => subcommand_index += 1,
5663 "-C" => subcommand_index += 2,
5664 _ => break,
5665 }
5666 }
5667 let subcommand = argv
5668 .get(subcommand_index)
5669 .map(String::as_str)
5670 .ok_or_else(|| {
5671 anyhow!("classifier-approved Git read was missing its literal subcommand")
5672 })?;
5673 match subcommand {
5674 "diff" => {
5675 let at = subcommand_index + 1;
5676 argv.splice(
5677 at..at,
5678 codewhale_dependencies::Git::REVIEW_DIFF_ARGS.map(String::from),
5679 );
5680 }
5681 "log" | "show" => {
5682 let at = subcommand_index + 1;
5683 argv.splice(
5684 at..at,
5685 codewhale_dependencies::Git::REVIEW_DIFF_ARGS
5686 .into_iter()
5687 .chain(["--no-show-signature"])
5688 .map(String::from),
5689 );
5690 }
5691 "blame" => {
5692 let at = subcommand_index + 1;
5693 argv.insert(at, "--no-textconv".to_string());
5694 }
5695 "status" | "ls-files" | "grep" => {}
5696 _ => {
5697 return Err(anyhow!(
5698 "classifier-approved Git read did not keep its subcommand in argv[1]"
5699 ));
5700 }
5701 }
5702 }
5703
5704 let program = argv.remove(0);
5705 Ok((program, argv))
5706 }
5707
5708 fn command_first_program(command: &str) -> Option<String> {
5709 shell_words::split(&normalize_windows_command_paths(command))
5710 .ok()
5711 .and_then(|argv| argv.into_iter().next())
5712 }
5713
5714 fn command_is_admitted_readonly_git(command: &str) -> bool {
5715 agent_readonly_verdict(command).is_ok_and(|segments| {
5716 segments.iter().any(|segment| {
5717 command_first_program(&segment.command).is_some_and(|program| program == "git")
5718 })
5719 })
5720 }
5721
5722 fn has_git_dir_ancestor(start: &std::path::Path) -> bool {
5723 start.ancestors().any(|dir| dir.join(".git").exists())
5724 }
5725
5726 /// The directory each `git` segment of a read-only command runs in: `cwd`
5727 /// followed through any leading `-C` hops, as git itself resolves them.
5728 #[cfg(test)]
5729 fn readonly_git_dirs(command: &str, cwd: &std::path::Path) -> Vec<std::path::PathBuf> {
5730 readonly_git_dirs_with_cwd_repo(command, cwd, false)
5731 }
5732
5733 fn readonly_git_dirs_with_cwd_repo(
5734 command: &str,
5735 cwd: &std::path::Path,
5736 include_cwd_if_repo: bool,
5737 ) -> Vec<std::path::PathBuf> {
5738 let mut base_cwd = cwd.to_path_buf();
5739 let mut remaining = command.to_string();
5740 for _ in 0..4 {
5741 let Some((dir, rest)) = split_leading_cd(&remaining) else {
5742 break;
5743 };
5744 base_cwd = base_cwd.join(dir);
5745 remaining = rest;
5746 }
5747 // Split with the same lexer the classifier and executor use (#6637), so a
5748 // `git` segment after `&&`, `||` or `;` gets its filter hardening too.
5749 let segments = agent_readonly_verdict(&remaining).map_or_else(
5750 |_| remaining.split('|').map(str::to_string).collect::<Vec<_>>(),
5751 |segments| {
5752 segments
5753 .into_iter()
5754 .map(|segment| segment.command)
5755 .collect()
5756 },
5757 );
5758 let mut dirs: Vec<std::path::PathBuf> = Vec::new();
5759 let mut push_unique = |dir: std::path::PathBuf| {
5760 if !dirs.contains(&dir) {
5761 dirs.push(dir);
5762 }
5763 };
5764 for argv in segments
5765 .iter()
5766 .filter_map(|segment| shell_words::split(&normalize_windows_command_paths(segment)).ok())
5767 .filter(|argv| argv.first().is_some_and(|program| program == "git"))
5768 {
5769 let mut dir = base_cwd.clone();
5770 let mut args = argv.iter().skip(1);
5771 while let Some(flag) = args.next() {
5772 match flag.as_str() {
5773 "--no-pager" => {}
5774 "-C" => match args.next() {
5775 Some(target) => dir = dir.join(target),
5776 None => break,
5777 },
5778 _ => break,
5779 }
5780 }
5781 push_unique(dir);
5782 }
5783 if include_cwd_if_repo {
5784 if has_git_dir_ancestor(cwd) {
5785 push_unique(cwd.to_path_buf());
5786 }
5787 if base_cwd != cwd && has_git_dir_ancestor(&base_cwd) {
5788 push_unique(base_cwd);
5789 }
5790 }
5791 dirs
5792 }
5793
5794 fn enforce_readonly_workspace_operands(
5795 command: &str,
5796 workspace: &std::path::Path,
5797 effective_cwd: &std::path::Path,
5798 ) -> Result<(), ToolError> {
5799 // Judge each segment of a pipeline or chain on its own, so the `gh`
5800 // exemption below covers only the `gh` segment itself.
5801 let segments = agent_readonly_verdict(command).map_or_else(
5802 |_| vec![command.to_string()],
5803 |segments| {
5804 segments
5805 .into_iter()
5806 .map(|segment| segment.command)
5807 .collect()
5808 },
5809 );
5810 for segment in &segments {
5811 enforce_readonly_segment_operands(segment, workspace, effective_cwd)?;
5812 }
5813 Ok(())
5814 }
5815
5816 fn enforce_readonly_segment_operands(
5817 command: &str,
5818 workspace: &std::path::Path,
5819 effective_cwd: &std::path::Path,
5820 ) -> Result<(), ToolError> {
5821 let argv = shell_words::split(&normalize_windows_command_paths(command)).map_err(|error| {
5822 ToolError::invalid_input(format!(
5823 "Could not parse read-only command arguments: {error}"
5824 ))
5825 })?;
5826 if argv.first().is_some_and(|program| program == "gh") {
5827 // High-level gh reads do not consume local path operands. Their host
5828 // is pinned and evaluated separately by the network-policy guard.
5829 return Ok(());
5830 }
5831 let workspace = workspace.canonicalize().map_err(|error| {
5832 ToolError::execution_failed(format!(
5833 "Could not resolve the Scout workspace before shell dispatch: {error}"
5834 ))
5835 })?;
5836 let effective_cwd = effective_cwd.canonicalize().map_err(|error| {
5837 ToolError::permission_denied(format!(
5838 "Could not prove the read-only shell working directory stays in the workspace: {error}"
5839 ))
5840 })?;
5841 if !effective_cwd.starts_with(&workspace) {
5842 return Err(ToolError::permission_denied(
5843 "[shell.readonly.cwd.outside_workspace] Read-only Scout shell working directory resolves outside the workspace.",
5844 ));
5845 }
5846
5847 for token in argv.iter().skip(1) {
5848 if token.starts_with('-') && (token.contains('/') || token.contains('\\')) {
5849 return Err(ToolError::permission_denied(format!(
5850 "[shell.readonly.option.attached_path] Read-only Scout shell options may not carry attached paths; refused {token:?}. Use the bounded File read/search actions for project evidence."
5851 )));
5852 }
5853 let value = token
5854 .split_once('=')
5855 .map_or(token.as_str(), |(_, value)| value)
5856 .trim();
5857 // Windows `Path::canonicalize` returns verbatim device paths
5858 // (`\\?\C:\...`), which `Path::is_absolute` does not recognize; without
5859 // stripping the prefix the operand falls into the shape refusal and
5860 // every canonical absolute read is denied on Windows. The stripped
5861 // form resolves to the same location, so location-based judgement is
5862 // unchanged. On unix hosts such spellings stay fail-closed below.
5863 let value = value
5864 .strip_prefix(r"\\?\")
5865 .or_else(|| value.strip_prefix(r"\\.\"))
5866 .unwrap_or(value);
5867 if value.is_empty() || value == "-" {
5868 continue;
5869 }
5870 let candidate = std::path::Path::new(value);
5871 let bytes = value.as_bytes();
5872 let windows_prefixed =
5873 (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
5874 || value.starts_with("\\\\")
5875 || candidate
5876 .components()
5877 .any(|component| matches!(component, std::path::Component::Prefix(_)));
5878
5879 // #5595: an absolute operand is safe by resolved location, not by
5880 // spelling. This is the canonical `git -C /absolute/workspace log`
5881 // case. Requiring canonicalization also keeps nonexistent output-like
5882 // targets fail-closed, while symlinks are judged by their destination.
5883 if candidate.is_absolute() {
5884 let resolved = candidate.canonicalize().map_err(|error| {
5885 ToolError::permission_denied(format!(
5886 "[shell.readonly.operand.unresolved] Could not prove absolute read-only operand {value:?} stays inside the workspace because it could not be resolved: {error}"
5887 ))
5888 })?;
5889 if !resolved.starts_with(&workspace) {
5890 return Err(ToolError::permission_denied(format!(
5891 "[shell.readonly.operand.outside_workspace] Read-only Scout shell operand {value:?} resolves outside the workspace. Use the bounded File read/search actions for project evidence."
5892 )));
5893 }
5894 continue;
5895 }
5896
5897 if value.starts_with('~')
5898 || value.contains('\\')
5899 || windows_prefixed
5900 || candidate.has_root()
5901 || candidate
5902 .components()
5903 .any(|component| matches!(component, std::path::Component::ParentDir))
5904 {
5905 return Err(ToolError::permission_denied(format!(
5906 "[shell.readonly.operand.shape] Read-only Scout shell operands must stay inside the workspace; refused {value:?}. Use the bounded File read/search actions for project evidence."
5907 )));
5908 }
5909
5910 let joined = effective_cwd.join(candidate);
5911 if joined.exists() {
5912 let resolved = joined.canonicalize().map_err(|error| {
5913 ToolError::permission_denied(format!(
5914 "[shell.readonly.operand.unresolved] Could not prove read-only operand {value:?} stays in the workspace: {error}"
5915 ))
5916 })?;
5917 if !resolved.starts_with(&workspace) {
5918 return Err(ToolError::permission_denied(format!(
5919 "[shell.readonly.operand.outside_workspace] Read-only Scout shell operand {value:?} resolves outside the workspace. Use the bounded File read/search actions for project evidence."
5920 )));
5921 }
5922 }
5923 }
5924 Ok(())
5925 }
5926
5927 fn readonly_sanitized_path_from(
5928 workspace: &std::path::Path,
5929 path: &std::ffi::OsStr,
5930 ) -> Option<std::ffi::OsString> {
5931 let workspace = workspace.canonicalize().ok()?;
5932 let safe = std::env::split_paths(path).filter_map(|entry| {
5933 if !entry.is_absolute() {
5934 return None;
5935 }
5936 let resolved = entry.canonicalize().ok()?;
5937 (!resolved.starts_with(&workspace)).then_some(resolved)
5938 });
5939 std::env::join_paths(safe).ok()
5940 }
5941
5942 fn readonly_sanitized_path(workspace: &std::path::Path) -> Option<String> {
5943 let path = std::env::var_os("PATH")?;
5944 readonly_sanitized_path_from(workspace, &path).map(|value| value.to_string_lossy().into_owned())
5945 }
5946
5947 fn resolve_readonly_program(program: &str, workspace: &std::path::Path) -> Result<PathBuf> {
5948 let path = std::env::var_os("PATH")
5949 .ok_or_else(|| anyhow!("no executable search path is configured"))?;
5950 resolve_readonly_program_from_path(program, workspace, &path)
5951 }
5952
5953 fn resolve_readonly_program_from_path(
5954 program: &str,
5955 workspace: &std::path::Path,
5956 path: &std::ffi::OsStr,
5957 ) -> Result<PathBuf> {
5958 let workspace = workspace.canonicalize()?;
5959 if std::path::Path::new(program).components().count() != 1 {
5960 return Err(anyhow!(
5961 "read-only command must name a bare allowlisted executable"
5962 ));
5963 }
5964 let safe_path = readonly_sanitized_path_from(&workspace, path).ok_or_else(|| {
5965 anyhow!("no trusted executable search path remains outside the workspace")
5966 })?;
5967 let names = if cfg!(windows) {
5968 vec![format!("{program}.exe"), format!("{program}.com")]
5969 } else {
5970 vec![program.to_string()]
5971 };
5972 for directory in std::env::split_paths(&safe_path) {
5973 for name in &names {
5974 let candidate = directory.join(name);
5975 if !candidate.is_file() {
5976 continue;
5977 }
5978 #[cfg(unix)]
5979 {
5980 use std::os::unix::fs::PermissionsExt as _;
5981 if candidate.metadata()?.permissions().mode() & 0o111 == 0 {
5982 continue;
5983 }
5984 }
5985 let resolved = candidate.canonicalize()?;
5986 if resolved.is_absolute() && !resolved.starts_with(&workspace) {
5987 return Ok(resolved);
5988 }
5989 }
5990 }
5991 Err(anyhow!(
5992 "allowlisted read-only executable {program:?} was not found at a canonical path outside the workspace"
5993 ))
5994 }
5995
5996 fn remove_readonly_redirect_env(cmd: &mut Command, env: &HashMap<String, String>) {
5997 let readonly_mode = env.get(READONLY_ENV_MARKER).map(String::as_str) == Some("1");
5998 let git_hardening_mode =
5999 readonly_mode || env.get(GIT_HARDENING_ENV_MARKER).map(String::as_str) == Some("1");
6000 if !git_hardening_mode {
6001 return;
6002 }
6003 cmd.env_remove(READONLY_ENV_MARKER);
6004 cmd.env_remove(GIT_HARDENING_ENV_MARKER);
6005 let removals = cmd
6006 .get_envs()
6007 .filter_map(|(key, _)| {
6008 let upper = key.to_string_lossy().to_ascii_uppercase();
6009 let guarded = upper.starts_with("GIT_")
6010 || (readonly_mode && (upper.starts_with("GH_") || upper.starts_with("GITHUB_")));
6011 let safe = matches!(
6012 upper.as_str(),
6013 "GIT_OPTIONAL_LOCKS"
6014 | "GIT_NO_LAZY_FETCH"
6015 | "GIT_NO_REPLACE_OBJECTS"
6016 | "GIT_PAGER"
6017 | "GIT_CONFIG_NOSYSTEM"
6018 | "GIT_CONFIG_GLOBAL"
6019 | "GIT_CONFIG_PARAMETERS"
6020 | "GIT_EXTERNAL_DIFF"
6021 | "GIT_ATTR_NOSYSTEM"
6022 | "GIT_CONFIG_COUNT"
6023 | "GH_PAGER"
6024 | "GH_PROMPT_DISABLED"
6025 | "GH_NO_UPDATE_NOTIFIER"
6026 | "GH_HOST"
6027 | "GH_REPO"
6028 ) || (matches!(
6029 upper.as_str(),
6030 "GIT_SSH_COMMAND" | "GIT_EDITOR" | "GIT_ASKPASS"
6031 ) && env.contains_key(upper.as_str()))
6032 || upper.starts_with("GIT_CONFIG_KEY_")
6033 || upper.starts_with("GIT_CONFIG_VALUE_");
6034 (guarded && !safe).then(|| key.to_os_string())
6035 })
6036 .collect::<Vec<_>>();
6037 for key in removals {
6038 cmd.env_remove(key);
6039 }
6040 }
6041
6042 fn exec_shell_input_starts_detached(input: &serde_json::Value) -> bool {
6043 input
6044 .get("command")
6045 .and_then(serde_json::Value::as_str)
6046 .is_some()
6047 && input
6048 .get("interactive")
6049 .and_then(serde_json::Value::as_bool)
6050 != Some(true)
6051 && (input.get("background").and_then(serde_json::Value::as_bool) == Some(true)
6052 || input.get("tty").and_then(serde_json::Value::as_bool) == Some(true))
6053 }
6054
6055 fn persistent_services_enabled_for(context: &ToolContext) -> bool {
6056 #[cfg(unix)]
6057 {
6058 context.persist_services_enabled
6059 && context.owner_agent_id.is_none()
6060 && context.tool_authority.is_none()
6061 && context.sandbox_backend.is_none()
6062 && matches!(context.shell_policy, ShellPolicy::Full)
6063 && matches!(
6064 context.elevated_sandbox_policy,
6065 Some(ExecutionSandboxPolicy::DangerFullAccess)
6066 )
6067 }
6068 #[cfg(not(unix))]
6069 {
6070 let _ = context;
6071 false
6072 }
6073 }
6074
6075 #[allow(clippy::too_many_arguments)]
6076 async fn execute_foreground_via_background(
6077 context: &ToolContext,
6078 command: &str,
6079 description: Option<String>,
6080 heavy_permit: Option<HeavyCommandPermit>,
6081 working_dir: Option<String>,
6082 timeout_ms: Option<u64>,
6083 stdin_data: Option<&str>,
6084 tty: bool,
6085 policy_override: Option<ExecutionSandboxPolicy>,
6086 extra_env: HashMap<String, String>,
6087 readonly_hardening: ReadonlyCommandHardening<'_>,
6088 timeout_bounds_ms: (u64, u64),
6089 wants_receipt: bool,
6090 receipt_identity: &mut Option<ShellExecutionIdentity>,
6091 ) -> Result<(ShellResult, Option<PersistedShellArtifact>)> {
6092 let timeout_ms =
6093 timeout_ms.map(|timeout| timeout.clamp(timeout_bounds_ms.0, timeout_bounds_ms.1));
6094 let spawn_timeout_ms = timeout_ms.unwrap_or(timeout_bounds_ms.1);
6095 // Freeze the receipt's directory before execution and hand that same
6096 // resolved spelling to the OS. Looking up the original symlink after
6097 // the command runs can name a different directory than the one it used.
6098 // Resolution is asynchronous; failure leaves the ordinary execution
6099 // path intact but cannot produce an exact receipt.
6100 let receipt_cwd = if wants_receipt {
6101 match working_dir.as_deref() {
6102 Some(cwd) => tokio::fs::canonicalize(cwd)
6103 .await
6104 .ok()
6105 .and_then(|path| path.into_os_string().into_string().ok()),
6106 None => None,
6107 }
6108 } else {
6109 None
6110 };
6111 let working_dir = receipt_cwd.clone().or(working_dir);
6112 let rewritten_argv = matches!(
6113 readonly_hardening,
6114 ReadonlyCommandHardening::StrictReadOnly(_)
6115 ) || (matches!(
6116 readonly_hardening,
6117 ReadonlyCommandHardening::GitReadOnlyIfAdmitted { .. }
6118 ) && command_is_admitted_readonly_git(command));
6119 let (task_id, detach) = {
6120 let mut manager = context
6121 .shell_manager
6122 .lock()
6123 .map_err(|_| anyhow!("shell manager lock poisoned"))?;
6124 let owner = shell_job_owner_from_context(context);
6125 let lifecycle = shell_work_lifecycle_from_context(context);
6126 let spawned = manager.execute_with_options_env_for_owner_and_work_hardened(
6127 command,
6128 None,
6129 working_dir.as_deref(),
6130 spawn_timeout_ms,
6131 true,
6132 stdin_data,
6133 tty,
6134 policy_override,
6135 extra_env,
6136 owner,
6137 context.state_namespace.clone(),
6138 context.origin_tool_call_id.clone(),
6139 context.origin_turn_id.clone(),
6140 lifecycle,
6141 readonly_hardening,
6142 false,
6143 timeout_bounds_ms,
6144 )?;
6145 let task_id = spawned
6146 .task_id
6147 .ok_or_else(|| anyhow!("foreground shell did not return a process id"))?;
6148 // Classify before releasing the manager lock: even an immediately
6149 // completed foreground command must never look like background work.
6150 let process = manager
6151 .processes
6152 .get_mut(&task_id)
6153 .ok_or_else(|| anyhow!("foreground shell {task_id} is not tracked"))?;
6154 process.background = false;
6155 process.description = description;
6156 // #6689: the receipt identity is what the manager recorded for this
6157 // spawn — the admitted command and the directory handed to the OS —
6158 // never the before-hook request. Only pipe-backed, unsandboxed local
6159 // runs through a POSIX-style `<shell> <flag> <source>` dispatcher
6160 // qualify: a PTY, the hardened read-only argv rewrite, an OS sandbox
6161 // wrapper, Windows shell prefixes, and a PowerShell dispatcher (even
6162 // `$SHELL=pwsh` on Unix, which wraps the source or runs it from a temp
6163 // `-File`) all change what the process executes relative to this string.
6164 if receipt_cwd.is_some()
6165 && !cfg!(windows)
6166 && !tty
6167 && !rewritten_argv
6168 && !spawned.sandboxed
6169 && !spawned.sandbox_denied
6170 && !codewhale_sandbox::shell_dispatcher::global_dispatcher()
6171 .kind()
6172 .is_powershell()
6173 {
6174 *receipt_identity = Some(ShellExecutionIdentity {
6175 command: process.command.clone(),
6176 cwd: process.working_dir.clone(),
6177 });
6178 }
6179 let detach = manager.register_shell_wait(&context.state_namespace);
6180 (task_id, detach)
6181 };
6182 let mut foreground = ForegroundShellGuard {
6183 manager: context.shell_manager.clone(),
6184 task_id: task_id.clone(),
6185 armed: true,
6186 };
6187 if let Some(permit) = heavy_permit {
6188 let mut manager = context
6189 .shell_manager
6190 .lock()
6191 .map_err(|_| anyhow!("shell manager lock poisoned"))?;
6192 manager.attach_heavy_permit(&task_id, permit)?;
6193 }
6194
6195 // A foreground pipe command gets EOF on stdin: an unexpected read (`cat`,
6196 // `read x`, a confirmation prompt) then fails at once instead of blocking
6197 // until the timeout kills it. A TTY keeps its terminal input. A command
6198 // later moved to /jobs keeps the closed stdin; interactive input needs
6199 // `background: true` from the start.
6200 if stdin_data.is_some() || !tty {
6201 let mut manager = context
6202 .shell_manager
6203 .lock()
6204 .map_err(|_| anyhow!("shell manager lock poisoned"))?;
6205 manager.write_stdin(&task_id, "", true)?;
6206 }
6207
6208 let deadline = timeout_ms.map(|timeout| Instant::now() + Duration::from_millis(timeout));
6209 // Adaptive poll cadence: fast commands (the common case — grep, wc, echo)
6210 // finish in single-digit milliseconds, and a fixed 100ms tick made every
6211 // foreground call pay that full quantum before completion was noticed.
6212 // Start fine-grained and back off to the 100ms cap for long-running work.
6213 let mut poll_tick_ms: u64 = FOREGROUND_POLL_INITIAL_MS;
6214 loop {
6215 if context
6216 .cancel_token
6217 .as_ref()
6218 .is_some_and(|token| token.is_cancelled())
6219 {
6220 let mut manager = context
6221 .shell_manager
6222 .lock()
6223 .map_err(|_| anyhow!("shell manager lock poisoned"))?;
6224 let result = manager.kill_with_artifact(&task_id);
6225 if result.is_ok() {
6226 manager.acknowledge_foreground_completion(&task_id);
6227 foreground.armed = false;
6228 }
6229 return result;
6230 }
6231
6232 let finished = {
6233 let mut manager = context
6234 .shell_manager
6235 .lock()
6236 .map_err(|_| anyhow!("shell manager lock poisoned"))?;
6237 if detach.load(Ordering::Acquire) {
6238 if let Some(shell) = manager.processes.get_mut(&task_id) {
6239 shell.background = true;
6240 }
6241 let snapshot = manager.get_output(&task_id, false, 0)?;
6242 foreground.armed = false;
6243 return Ok((snapshot, None));
6244 }
6245 if manager.poll_status(&task_id)? == ShellStatus::Running {
6246 None
6247 } else {
6248 if manager
6249 .processes
6250 .get(&task_id)
6251 .is_none_or(|shell| shell.wait_failed)
6252 {
6253 *receipt_identity = None;
6254 }
6255 let snapshot = manager.get_output_with_artifact(&task_id, false, 0)?;
6256 manager.acknowledge_foreground_completion(&task_id);
6257 Some(snapshot)
6258 }
6259 };
6260
6261 if let Some(snapshot) = finished {
6262 foreground.armed = false;
6263 return Ok(snapshot);
6264 }
6265
6266 if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
6267 let mut manager = context
6268 .shell_manager
6269 .lock()
6270 .map_err(|_| anyhow!("shell manager lock poisoned"))?;
6271 if let Some(process) = manager.processes.get_mut(&task_id) {
6272 process.background = true;
6273 }
6274 let snapshot = manager.get_output(&task_id, false, 0)?;
6275 foreground.armed = false;
6276 return Ok((snapshot, None));
6277 }
6278
6279 tokio::time::sleep(Duration::from_millis(poll_tick_ms)).await;
6280 poll_tick_ms = (poll_tick_ms * 2).min(FOREGROUND_POLL_MAX_MS);
6281 }
6282 }
6283
6284 /// A foreground wait owns its process even if its caller drops the future
6285 /// before cooperative cancellation can be polled. Only an explicit transfer
6286 /// to /jobs releases that ownership while the process is still running.
6287 struct ForegroundShellGuard {
6288 manager: SharedShellManager,
6289 task_id: String,
6290 armed: bool,
6291 }
6292
6293 impl Drop for ForegroundShellGuard {
6294 fn drop(&mut self) {
6295 if !self.armed {
6296 return;
6297 }
6298 let mut manager = self
6299 .manager
6300 .lock()
6301 .unwrap_or_else(std::sync::PoisonError::into_inner);
6302 let result = manager.poll_status(&self.task_id).and_then(|status| {
6303 if status == ShellStatus::Running {
6304 manager.kill(&self.task_id).map(|_| ())
6305 } else {
6306 Ok(())
6307 }
6308 });
6309 if let Err(error) = result {
6310 tracing::warn!(shell_id = %self.task_id, %error, "foreground shell cleanup failed");
6311 }
6312 if let Some(shell) = manager.processes.get_mut(&self.task_id) {
6313 // No result received these bytes. Retain them for /jobs inspection,
6314 // but do not let an abandoned foreground wait wake a new model turn.
6315 shell.completion_reported = true;
6316 }
6317 }
6318 }
6319
6320 /// The admitted command and working directory a foreground spawn recorded,
6321 /// for the `tool_call_after` execution receipt (#6689).
6322 struct ShellExecutionIdentity {
6323 command: String,
6324 cwd: PathBuf,
6325 }
6326
6327 /// Largest command or working directory a receipt carries. Identities are
6328 /// exact or absent, never truncated.
6329 const EXECUTION_RECEIPT_IDENTITY_MAX_BYTES: usize = 8 * 1024;
6330
6331 /// Starting per-stream output preview in an execution receipt. Halved until
6332 /// the serialized receipt fits `HOOK_EXECUTION_RECEIPT_MAX_BYTES`.
6333 const EXECUTION_RECEIPT_PREVIEW_MAX_BYTES: usize = 8 * 1024;
6334
6335 /// Keep both ends of an output stream — the first lines and the final
6336 /// diagnostic — cut on UTF-8 boundaries with a visible marker.
6337 fn execution_receipt_preview(text: &str, budget: usize) -> (String, bool) {
6338 if text.len() <= budget {
6339 return (text.to_owned(), false);
6340 }
6341 let mut head = budget / 2;
6342 while !text.is_char_boundary(head) {
6343 head -= 1;
6344 }
6345 let mut tail = text.len() - budget / 2;
6346 while !text.is_char_boundary(tail) {
6347 tail += 1;
6348 }
6349 (
6350 format!(
6351 "{}\n[receipt preview truncated]\n{}",
6352 &text[..head],
6353 &text[tail..]
6354 ),
6355 true,
6356 )
6357 }
6358
6359 /// Build the schema-1 execution receipt for a settled foreground shell run
6360 /// (#6689), exported to `tool_call_after` hooks as
6361 /// `DEEPSEEK_TOOL_EXECUTION_RECEIPT`.
6362 ///
6363 /// Returns `None` — absence, which implies neither success nor failure — for
6364 /// a run still in flight, a sandboxed run, or an identity that is not exact:
6365 /// empty, over the identity bound, containing NUL, or a relative or non-UTF-8
6366 /// directory. `output_kind` is `"combined"` when stdout and stderr shared one
6367 /// pipe, so `stdout` holds the combined preview.
6368 fn shell_execution_receipt(
6369 identity: &ShellExecutionIdentity,
6370 result: &ShellResult,
6371 output_kind: &'static str,
6372 ) -> Option<serde_json::Value> {
6373 let command = identity.command.as_str();
6374 let cwd = identity.cwd.to_str()?;
6375 if command.is_empty()
6376 || command.len() > EXECUTION_RECEIPT_IDENTITY_MAX_BYTES
6377 || command.contains('\0')
6378 || cwd.len() > EXECUTION_RECEIPT_IDENTITY_MAX_BYTES
6379 || cwd.contains('\0')
6380 || !identity.cwd.is_absolute()
6381 || result.sandboxed
6382 || result.sandbox_denied
6383 {
6384 return None;
6385 }
6386 // A nonzero exit is still a completed run; `interrupted` is a signal,
6387 // kill, cancel, or timeout. The exit code is only ever the observed one.
6388 let state = match result.status {
6389 ShellStatus::Completed => "completed",
6390 ShellStatus::Failed if result.exit_code.is_some() => "completed",
6391 ShellStatus::Failed | ShellStatus::Killed | ShellStatus::TimedOut => "interrupted",
6392 ShellStatus::Running => return None,
6393 };
6394 let mut budget = EXECUTION_RECEIPT_PREVIEW_MAX_BYTES;
6395 loop {
6396 let (stdout, stdout_clipped) = execution_receipt_preview(&result.stdout, budget);
6397 let (stderr, stderr_clipped) = execution_receipt_preview(&result.stderr, budget);
6398 let receipt = json!({
6399 "schema_version": 1,
6400 "command": command,
6401 "cwd": cwd,
6402 "state": state,
6403 "scope": "local",
6404 "exit_code": result.exit_code,
6405 "stdout": stdout,
6406 "stderr": stderr,
6407 "stdout_truncated": result.stdout_truncated || stdout_clipped,
6408 "stderr_truncated": result.stderr_truncated || stderr_clipped,
6409 "output_kind": output_kind,
6410 });
6411 // The bound is on the serialized form, so JSON escaping counts.
6412 if serde_json::to_vec(&receipt).ok()?.len()
6413 <= crate::hooks::HOOK_EXECUTION_RECEIPT_MAX_BYTES
6414 {
6415 return Some(receipt);
6416 }
6417 if budget == 0 {
6418 return None;
6419 }
6420 budget /= 2;
6421 }
6422 }
6423
6424 const BASH_MAX_TIMEOUT_MS: u64 = i32::MAX as u64;
6425
6426 /// Initial cadence for foreground-via-background completion polling. Fast
6427 /// commands dominate real agent traffic; detection latency on `true`-class
6428 /// commands drops from ~100ms to ~10ms, while long commands reach the
6429 /// 100ms cap within one doubling step.
6430 const FOREGROUND_POLL_INITIAL_MS: u64 = 10;
6431 /// Poll-cadence ceiling; matches the previous fixed tick so long-running
6432 /// command overhead is unchanged.
6433 const FOREGROUND_POLL_MAX_MS: u64 = 100;
6434
6435 /// Default foreground lifetime for a contract-`bash` `action=run` that names
6436 /// no `timeout_ms`. Matches the value the tool's own input schema advertises;
6437 /// before this existed the omitted case fell through to
6438 /// `BASH_MAX_TIMEOUT_MS`.
6439 const CONTRACT_BASH_FOREGROUND_DEFAULT_TIMEOUT_MS: u64 = 30_000;
6440
6441 /// Resolve the lifetime for one `bash` run.
6442 ///
6443 /// A foreground contract-`bash` run that names no timeout used to inherit
6444 /// `BASH_MAX_TIMEOUT_MS` (~24.8 days), so a command that blocked on an
6445 /// interactive prompt or a hung network call pinned the turn indefinitely —
6446 /// the tool row just counted seconds while the model waited. The tool's own
6447 /// schema already promises `action=run 30000`, so an omitted timeout takes
6448 /// that default as the foreground wait. Past it the command moves to the
6449 /// background (it is never killed for running long) and the model gets its
6450 /// output so far and task id.
6451 ///
6452 /// An explicit `timeout_ms` is still honored up to the full contract ceiling,
6453 /// and background and interactive runs keep their own lifetimes: their
6454 /// processes are meant to outlive the call, so bounding them here would kill
6455 /// long-lived jobs the model deliberately detached.
6456 fn contract_bash_timeout_ms(
6457 optional_timeout: bool,
6458 requested_ms: Option<u64>,
6459 background: bool,
6460 interactive: bool,
6461 ) -> Option<u64> {
6462 if optional_timeout && requested_ms.is_none() && !background && !interactive {
6463 return Some(CONTRACT_BASH_FOREGROUND_DEFAULT_TIMEOUT_MS);
6464 }
6465 requested_ms
6466 }
6467
6468 fn promotion_notice(
6469 context: &ToolContext,
6470 task_id: &str,
6471 elapsed_seconds: u64,
6472 output: &str,
6473 ) -> String {
6474 let last_output = context
6475 .shell_manager
6476 .lock()
6477 .unwrap_or_else(|error| error.into_inner())
6478 .last_output_age_ms(task_id)
6479 .map_or_else(
6480 || "last output age unknown".to_string(),
6481 |ms| format!("last output {}s ago", ms / 1_000),
6482 );
6483 format!(
6484 "Still running after {elapsed_seconds}s ({last_output}; {}); moved to the background as {task_id} (not killed).",
6485 output_phase_hint(output)
6486 )
6487 }
6488
6489 fn contract_bash_error_status(result: &ShellResult, timeout_ms: Option<u64>) -> String {
6490 match result.status {
6491 ShellStatus::TimedOut => {
6492 let millis = timeout_ms.unwrap_or(BASH_MAX_TIMEOUT_MS);
6493 let seconds = if millis.is_multiple_of(1_000) {
6494 (millis / 1_000).to_string()
6495 } else {
6496 format!("{}", millis as f64 / 1_000.0)
6497 };
6498 format!("Command timed out after {seconds} seconds")
6499 }
6500 ShellStatus::Killed => format!(
6501 "Command aborted. {}",
6502 kill_outcome_note(&format!("{}{}", result.stdout, result.stderr))
6503 ),
6504 ShellStatus::Failed | ShellStatus::Completed | ShellStatus::Running => format!(
6505 "Command exited with code {}",
6506 result.exit_code.unwrap_or(-1)
6507 ),
6508 }
6509 }
6510
6511 fn combine_full_shell_streams(stdout: &str, stderr: &str) -> String {
6512 if stderr.is_empty() {
6513 stdout.to_string()
6514 } else if stdout.is_empty() {
6515 format!("STDERR:\n{stderr}")
6516 } else {
6517 format!("{stdout}\n\nSTDERR:\n{stderr}")
6518 }
6519 }
6520
6521 pub(crate) fn completed_bash_artifact_handle<'a>(
6522 metadata: &'a serde_json::Value,
6523 tool_name: &str,
6524 tool_id: &str,
6525 session_id: &str,
6526 ) -> Option<&'a str> {
6527 let job = metadata["task_id"].as_str()?;
6528 let handle = metadata["artifact_id"].as_str()?;
6529 (tool_name == "bash"
6530 && job
6531 .strip_prefix("shell_")
6532 .is_some_and(|id| Uuid::parse_str(id).is_ok())
6533 && handle.strip_prefix("art_") == Some(job)
6534 && metadata["artifact_relative_path"]
6535 .as_str()
6536 .is_some_and(|path| {
6537 Path::new(path)
6538 == codewhale_runtime::artifacts::session_artifact_relative_path(handle)
6539 })
6540 && metadata["artifact_origin_tool_call_id"].as_str() == Some(tool_id)
6541 && metadata["artifact_session_id"].as_str() == Some(session_id)
6542 && metadata["artifact_complete"].as_bool() == Some(true))
6543 .then_some(handle)
6544 }
6545
6546 fn format_persisted_shell_artifact_footer(artifact: &PersistedShellArtifact) -> String {
6547 let label = if artifact.complete {
6548 "Full output"
6549 } else {
6550 "Output excerpt"
6551 };
6552 format!(
6553 "[{label} saved as artifact {}; {}]",
6554 artifact.artifact_id,
6555 crate::tools::truncate::spillover_recovery_instruction(Some(&artifact.artifact_id)),
6556 )
6557 }
6558
6559 fn stamp_persisted_shell_artifact_metadata(
6560 metadata: &mut serde_json::Value,
6561 artifact: &PersistedShellArtifact,
6562 preview_source: &str,
6563 ) {
6564 let Some(obj) = metadata.as_object_mut() else {
6565 return;
6566 };
6567 let absolute = serde_json::Value::String(artifact.absolute_path.display().to_string());
6568 let relative =
6569 codewhale_runtime::artifacts::format_artifact_relative_path(&artifact.relative_path);
6570 let mut preview: String = preview_source.chars().take(200).collect();
6571 if preview_source.chars().count() > 200 {
6572 preview.push_str("...");
6573 }
6574 obj.insert("spillover_path".into(), absolute.clone());
6575 obj.insert("artifact_path".into(), absolute);
6576 obj.insert("artifact_id".into(), artifact.artifact_id.clone().into());
6577 obj.insert(
6578 "artifact_session_id".into(),
6579 artifact.session_id.clone().into(),
6580 );
6581 obj.insert("artifact_relative_path".into(), relative.into());
6582 obj.insert("artifact_byte_size".into(), artifact.byte_size.into());
6583 obj.insert("artifact_digest".into(), artifact.digest.clone().into());
6584 obj.insert(
6585 "content_digest".into(),
6586 format!("sha256:{}", artifact.digest).into(),
6587 );
6588 obj.insert("artifact_preview".into(), preview.into());
6589 obj.insert("truncated".into(), true.into());
6590 obj.insert("artifact_complete".into(), artifact.complete.into());
6591 if artifact.complete {
6592 obj.insert("original_byte_count".into(), artifact.byte_size.into());
6593 }
6594 }
6595
6596 fn attach_shell_artifact_to_tool_result(
6597 result: &mut ToolResult,
6598 artifact: &PersistedShellArtifact,
6599 ) {
6600 if !result.content.contains(&artifact.artifact_id) {
6601 result.content.push_str("\n\n");
6602 result
6603 .content
6604 .push_str(&format_persisted_shell_artifact_footer(artifact));
6605 }
6606 let metadata = result.metadata.get_or_insert_with(|| json!({}));
6607 stamp_persisted_shell_artifact_metadata(metadata, artifact, &result.content);
6608 }
6609
6610 #[allow(clippy::too_many_arguments)]
6611 fn finish_contract_bash_result(
6612 result: ShellResult,
6613 timeout_ms: Option<u64>,
6614 context: &ToolContext,
6615 execution_receipt: Option<serde_json::Value>,
6616 readonly_network: bool,
6617 network_restricted_hint: Option<&str>,
6618 readonly_denied_hint: Option<&str>,
6619 explicit_background: bool,
6620 description: Option<&str>,
6621 persisted_artifact: Option<PersistedShellArtifact>,
6622 ) -> Result<ToolResult, ToolError> {
6623 let sandbox_denied_hint = if network_restricted_hint.is_none() {
6624 readonly_denied_hint
6625 .map(str::to_string)
6626 .or_else(|| shell_sandbox_denied_hint(context, &result))
6627 } else {
6628 None
6629 };
6630 let mut output = result.stdout.clone();
6631 output.push_str(&result.stderr);
6632 if let Some(hint) = network_restricted_hint {
6633 output = if output.is_empty() {
6634 hint.to_string()
6635 } else {
6636 format!("{hint}\n\n{output}")
6637 };
6638 }
6639 if let Some(hint) = sandbox_denied_hint.as_deref() {
6640 output = if output.is_empty() {
6641 hint.to_string()
6642 } else {
6643 format!("{hint}\n\n{output}")
6644 };
6645 }
6646 let mut metadata = json!({
6647 "evidence_routing": "inline", "exit_code": result.exit_code,
6648 "status": format!("{:?}", result.status), "duration_ms": result.duration_ms,
6649 "sandboxed": result.sandboxed, "sandbox_type": result.sandbox_type,
6650 "task_id": result.task_id, "backgrounded": result.status == ShellStatus::Running,
6651 });
6652 if let Some(description) = description {
6653 metadata["description"] = json!(description);
6654 }
6655 if let Some(receipt) = execution_receipt {
6656 metadata["execution_receipt"] = receipt;
6657 }
6658 if readonly_network {
6659 metadata["sandbox_network"] = json!(true);
6660 }
6661 if let Some(hint) = network_restricted_hint {
6662 metadata["sandbox_network_restricted"] = json!(true);
6663 metadata["sandbox_network_denied_hint"] = json!(hint);
6664 }
6665 if let Some(hint) = sandbox_denied_hint {
6666 metadata["sandbox_denied_hint"] = json!(hint);
6667 }
6668 if let Some(artifact) = persisted_artifact.as_ref() {
6669 if !output.contains(&artifact.artifact_id) {
6670 if !output.is_empty() {
6671 output.push_str("\n\n");
6672 }
6673 output.push_str(&format_persisted_shell_artifact_footer(artifact));
6674 }
6675 stamp_persisted_shell_artifact_metadata(&mut metadata, artifact, &output);
6676 if let Some(call_id) = &context.origin_tool_call_id {
6677 metadata["artifact_origin_tool_call_id"] = json!(call_id);
6678 }
6679 }
6680 if result.status == ShellStatus::Running {
6681 let task_id = result.task_id.as_deref().unwrap_or("unknown");
6682 let lead = if explicit_background {
6683 format!("Background task started: {task_id}.")
6684 } else {
6685 let so_far = if output.trim().is_empty() {
6686 "(no output yet)".to_string()
6687 } else {
6688 tail_lines(output.trim(), 20)
6689 };
6690 let notice = promotion_notice(context, task_id, result.duration_ms / 1_000, &output);
6691 format!("{notice}\n\nOutput so far:\n{so_far}")
6692 };
6693 let completion = if context.owner_agent_id.is_some() {
6694 "Its completion stays in task/status and is not injected into the parent model."
6695 } else {
6696 "Its completion reaches you as a runtime event before your next step; if you end the turn first, a headless run stops it unseen."
6697 };
6698 return Ok(ToolResult::success(format!(
6699 "{lead}\n\n{completion} To see more output or block until it finishes, call `task_shell_wait` directly with task_id=\"{task_id}\"; do not sleep-poll with bash. To stop it, send the same call with cancel=true. It also stops when the session ends."
6700 ))
6701 .with_metadata(metadata));
6702 }
6703 if result.status != ShellStatus::Completed {
6704 // A nonzero exit, timeout, or kill stays a failed tool call, but it
6705 // keeps the same metadata a success carries: hooks read `exit_code`
6706 // and `status` from it, and an error with no metadata left them blind
6707 // to exactly the commands that failed.
6708 let status = contract_bash_error_status(&result, timeout_ms);
6709 return Err(ToolError::execution_failed_with_metadata(
6710 if output.is_empty() {
6711 status
6712 } else {
6713 format!("{output}\n\n{status}")
6714 },
6715 metadata,
6716 ));
6717 }
6718
6719 Ok(ToolResult::success(if output.is_empty() {
6720 "(no output)".to_string()
6721 } else {
6722 output
6723 })
6724 .with_metadata(metadata))
6725 }
6726
6727 /// Small foreground-only shell surface shown to new model turns.
6728 pub struct LowercaseBashTool;
6729
6730 #[async_trait]
6731 impl ToolSpec for LowercaseBashTool {
6732 fn name(&self) -> &'static str {
6733 "bash"
6734 }
6735
6736 fn description(&self) -> &'static str {
6737 guidance::foreground_description()
6738 }
6739
6740 fn input_schema(&self) -> serde_json::Value {
6741 json!({
6742 "type": "object",
6743 "properties": {
6744 "command": { "type": "string", "description": guidance::runtime_command_guidance() },
6745 "description": { "type": "string", "description": "Optional few-word summary shown to the user beside the command." },
6746 "cwd": { "type": "string", "description": "Optional workspace-relative working directory." },
6747 "timeout": { "type": "number", "description": "Optional seconds to wait in the foreground (default 30 seconds). A command still running then is not killed: it moves to the background by itself and you get its output so far, how long ago it last printed, its build phase, and a task_id. Call task_shell_wait directly with that task_id to read more or wait for it; do not sleep-poll with bash." },
6748 "background": { "type": "boolean", "description": "Run immediately in the background and return a task_id (good for >5s or parallel jobs; incompatible with read_only=true). Call task_shell_wait to wait or cancel." },
6749 "read_only": { "type": "boolean", "description": "Set true to run analysis code (including Python/SQLite) or a network fetch (curl) with mandatory native filesystem read-only isolation. Outbound network is on only in Full Access when the session sandbox, the network policy and your network grant allow it. Available during peer writes. Refused when native enforcement is unavailable; no background, stdin, external backend, or sandbox escalation." },
6750 "sandbox_permissions": {
6751 "type": "string",
6752 "enum": ["workspace-write", "danger-full-access"],
6753 "description": "The wider sandbox mode this exact command needs. Use only as a one-shot retry after a sandbox denial; requires justification and user approval in Ask."
6754 },
6755 "justification": {
6756 "type": "string",
6757 "description": "Required with sandbox_permissions: one sentence explaining why this exact command needs wider access."
6758 }
6759 },
6760 "required": ["command"],
6761 "additionalProperties": false
6762 })
6763 }
6764
6765 fn capabilities(&self) -> Vec<ToolCapability> {
6766 BashTool::contract_delegate().capabilities()
6767 }
6768
6769 fn approval_requirement(&self) -> ApprovalRequirement {
6770 ApprovalRequirement::Required
6771 }
6772
6773 fn approval_requirement_for(&self, input: &serde_json::Value) -> ApprovalRequirement {
6774 contract_bash_legacy_input(input).map_or(ApprovalRequirement::Required, |translated| {
6775 BashTool::contract_delegate().approval_requirement_for(&translated)
6776 })
6777 }
6778
6779 fn is_read_only_for(&self, input: &serde_json::Value) -> bool {
6780 contract_bash_legacy_input(input)
6781 .is_ok_and(|translated| BashTool::contract_delegate().is_read_only_for(&translated))
6782 }
6783
6784 fn supports_parallel_for(&self, input: &serde_json::Value) -> bool {
6785 contract_bash_legacy_input(input).is_ok_and(|translated| {
6786 BashTool::contract_delegate().is_read_only_for(&translated)
6787 || translated
6788 .get("background")
6789 .and_then(serde_json::Value::as_bool)
6790 == Some(true)
6791 })
6792 }
6793
6794 fn starts_detached_for(&self, input: &serde_json::Value) -> bool {
6795 contract_bash_legacy_input(input)
6796 .is_ok_and(|translated| BashTool::contract_delegate().starts_detached_for(&translated))
6797 }
6798
6799 fn refusal_before_approval(
6800 &self,
6801 input: &serde_json::Value,
6802 context: &ToolContext,
6803 ) -> Option<ToolResult> {
6804 let translated = contract_bash_legacy_input(input).unwrap_or_else(|_| input.clone());
6805 BashTool::contract_delegate().refusal_before_approval(&translated, context)
6806 }
6807
6808 async fn execute(
6809 &self,
6810 input: serde_json::Value,
6811 context: &ToolContext,
6812 ) -> Result<ToolResult, ToolError> {
6813 let translated = contract_bash_legacy_input(&input)?;
6814 BashTool::contract_delegate()
6815 .execute(translated, context)
6816 .await
6817 }
6818 }
6819
6820 pub fn strip_readonly_bash_schema_properties(schema: &mut serde_json::Value) {
6821 if let Some(properties) = schema
6822 .get_mut("properties")
6823 .and_then(serde_json::Value::as_object_mut)
6824 {
6825 properties.remove("background");
6826 }
6827 }
6828
6829 fn dangerous_command_block(safety: &SafetyAnalysis) -> Option<ToolResult> {
6830 if safety.level != SafetyLevel::Dangerous {
6831 return None;
6832 }
6833 let reasons = safety.reasons.join("; ");
6834 let suggestions = if safety.suggestions.is_empty() {
6835 String::new()
6836 } else {
6837 format!("\nSuggestions: {}", safety.suggestions.join("; "))
6838 };
6839 Some(ToolResult {
6840 content: format!(
6841 "BLOCKED: This command was blocked for safety reasons.\n\nReasons: {reasons}{suggestions}\n\nNote: allow_shell=true exposes shell tools, but it does not disable built-in shell safety validation."
6842 ),
6843 success: false,
6844 metadata: Some(json!({
6845 "safety_level": "dangerous",
6846 "blocked": true,
6847 "reasons": safety.reasons,
6848 "suggestions": safety.suggestions,
6849 })),
6850 })
6851 }
6852
6853 fn contract_bash_legacy_input(input: &serde_json::Value) -> Result<serde_json::Value, ToolError> {
6854 let object = input
6855 .as_object()
6856 .ok_or_else(|| ToolError::invalid_input("bash input must be an object"))?;
6857 let unexpected = object
6858 .keys()
6859 .filter(|key| {
6860 !matches!(
6861 key.as_str(),
6862 "command"
6863 | "description"
6864 | "cwd"
6865 | "timeout"
6866 | "background"
6867 | "read_only"
6868 | "sandbox_permissions"
6869 | "justification"
6870 )
6871 })
6872 .cloned()
6873 .collect::<Vec<_>>();
6874 if !unexpected.is_empty() {
6875 return Err(ToolError::invalid_input(format!(
6876 "unexpected bash parameter(s): {}",
6877 unexpected.join(", ")
6878 )));
6879 }
6880 let command = required_str(input, "command")?;
6881 let mut translated = json!({"command": command});
6882 if let Some(description) = optional_str(input, "description")?
6883 .map(str::trim)
6884 .filter(|value| !value.is_empty())
6885 {
6886 translated["description"] = json!(description);
6887 }
6888 if let Some(cwd) = optional_str(input, "cwd")? {
6889 translated["cwd"] = json!(cwd);
6890 }
6891 if let Some(timeout) = input.get("timeout") {
6892 let seconds = timeout.as_f64().ok_or_else(|| {
6893 ToolError::invalid_input("Invalid timeout: expected a finite number of seconds")
6894 })?;
6895 if !seconds.is_finite() || seconds <= 0.0 {
6896 return Err(ToolError::invalid_input(
6897 "Invalid timeout: expected a positive finite number of seconds",
6898 ));
6899 }
6900 let millis = seconds * 1000.0;
6901 if millis > BASH_MAX_TIMEOUT_MS as f64 {
6902 return Err(ToolError::invalid_input(format!(
6903 "Invalid timeout: maximum is {} seconds",
6904 BASH_MAX_TIMEOUT_MS as f64 / 1000.0
6905 )));
6906 }
6907 translated["timeout_ms"] = json!((millis as u64).max(1));
6908 }
6909 let mut read_only = false;
6910 if let Some(value) = input.get("read_only") {
6911 let Some(enabled) = value.as_bool() else {
6912 return Err(type_mismatch("read_only", value, "a boolean"));
6913 };
6914 read_only = enabled;
6915 translated["read_only"] = value.clone();
6916 }
6917 if let Some(value) = input.get("background") {
6918 let enabled = value
6919 .as_bool()
6920 .ok_or_else(|| type_mismatch("background", value, "a boolean"))?;
6921 if read_only && enabled {
6922 return Err(ToolError::invalid_input(
6923 "read_only=true accepts only foreground run with command, cwd and timeout_ms; background, input, interactive modes and sandbox escalation are incompatible",
6924 ));
6925 }
6926 translated["background"] = json!(enabled);
6927 }
6928 for field in ["sandbox_permissions", "justification"] {
6929 if let Some(value) = input.get(field) {
6930 translated[field] = value.clone();
6931 }
6932 }
6933 Ok(translated)
6934 }
6935
6936 /// Compatibility shell tool retained for saved v0.9.x transcripts and the
6937 /// background/session control surface. It is hidden from new model catalogs.
6938 pub struct BashTool {
6939 name: &'static str,
6940 forced_action: Option<&'static str>,
6941 read_only: bool,
6942 optional_timeout: bool,
6943 }
6944
6945 pub fn readonly_bash_input_schema() -> serde_json::Value {
6946 json!({
6947 "type": "object",
6948 "properties": {
6949 "action": { "type": "string", "enum": ["run"] },
6950 "command": { "type": "string", "description": "A classifier-approved read command, or analysis code with read_only=true" },
6951 "read_only": { "type": "boolean", "description": "Require native filesystem read-only enforcement for analysis code or a network fetch (curl); outbound network is on only in Full Access when the session sandbox, the network policy and your network grant allow it. Unavailable sandboxes fail closed." },
6952 "cwd": { "type": "string", "description": "Workspace-relative working directory" },
6953 "timeout_ms": { "type": "integer", "description": "Foreground wait in milliseconds (1000-600000). A command still running then moves to the background; it is not killed." }
6954 },
6955 "required": ["command"],
6956 "additionalProperties": false
6957 })
6958 }
6959
6960 impl BashTool {
6961 pub const fn new(name: &'static str) -> Self {
6962 Self {
6963 name,
6964 forced_action: None,
6965 read_only: false,
6966 optional_timeout: false,
6967 }
6968 }
6969
6970 pub const fn read_only(name: &'static str) -> Self {
6971 Self {
6972 name,
6973 forced_action: None,
6974 read_only: true,
6975 optional_timeout: false,
6976 }
6977 }
6978
6979 pub const fn alias(name: &'static str, action: &'static str) -> Self {
6980 Self {
6981 name,
6982 forced_action: Some(action),
6983 read_only: false,
6984 optional_timeout: false,
6985 }
6986 }
6987
6988 const fn contract_delegate() -> Self {
6989 Self {
6990 name: "bash",
6991 forced_action: Some("run"),
6992 read_only: false,
6993 optional_timeout: true,
6994 }
6995 }
6996 }
6997
6998 #[async_trait]
6999 impl ToolSpec for BashTool {
7000 fn name(&self) -> &'static str {
7001 self.name
7002 }
7003
7004 fn model_visible(&self) -> bool {
7005 false
7006 }
7007
7008 fn description(&self) -> &'static str {
7009 if self.read_only {
7010 "Inspect with classifier-bounded commands run directly as argv, never through a shell. For analysis code or a network fetch (curl), read_only=true instead requires a native filesystem read-only sandbox, with outbound network only in Full Access when the session sandbox, the network policy and your network grant allow it. Only foreground action=run with command, cwd, timeout_ms, and read_only is accepted."
7011 } else {
7012 guidance::description()
7013 }
7014 }
7015
7016 fn input_schema(&self) -> serde_json::Value {
7017 if self.read_only {
7018 return readonly_bash_input_schema();
7019 }
7020 json!({
7021 "type": "object",
7022 "properties": {
7023 "action": {
7024 "type": "string",
7025 "enum": ["run", "wait", "interact", "cancel"],
7026 "description": "Action to perform (default: run)"
7027 },
7028 "command": {
7029 "type": "string",
7030 "description": guidance::runtime_command_guidance()
7031 },
7032 "description": {
7033 "type": "string",
7034 "description": "Optional few-word summary shown to the user beside the command."
7035 },
7036 "read_only": { "type": "boolean", "description": "Set true to require native filesystem read-only execution, with outbound network only in Full Access when the session sandbox, the network policy and your network grant allow it. Only foreground run with command, cwd and timeout_ms; unavailable enforcement fails closed." },
7037 "timeout_ms": {
7038 "type": "integer",
7039 "description": "How long to wait, in milliseconds. action=run: how long the turn waits in the foreground (default 30000, max 600000); a command still running then is NOT killed — it moves to the background by itself and you get its output so far, how long ago it last printed, its build phase, and task_id. action=wait 30000, action=interact 1000. For action=wait, `timeout_secs` (seconds) and `timeout` (milliseconds) are accepted aliases."
7040 },
7041 "background": {
7042 "type": "boolean",
7043 "description": "Temporary background; killed at session exit. Surviving headless services need background:true,persist:true. It is not killed at timeout_ms; plan to poll it with action=wait or stop it with action=cancel."
7044 },
7045 "interactive": {
7046 "type": "boolean",
7047 "description": "Run interactively with terminal IO (default: false)"
7048 },
7049 "stdin": {
7050 "type": "string",
7051 "description": "Stdin data to send (action=run: before waiting; action=interact: to the background task). Also accepted as `input` or `data` — send only one."
7052 },
7053 "input": {
7054 "type": "string",
7055 "description": "Alias for `stdin`."
7056 },
7057 "data": {
7058 "type": "string",
7059 "description": "Alias for `stdin`."
7060 },
7061 "cwd": {
7062 "type": "string",
7063 "description": "Optional working directory for the command"
7064 },
7065 "tty": {
7066 "type": "boolean",
7067 "description": "Allocate a pseudo-terminal for interactive programs (implies background)"
7068 },
7069 "combined_output": {
7070 "type": "boolean",
7071 "description": "Capture stdout and stderr as one chronological PTY stream (default false)"
7072 },
7073 "task_id": {
7074 "type": "string",
7075 "description": "Task ID for action=wait/interact/cancel. Also accepted as `id`."
7076 },
7077 "task_ids": {
7078 "type": "array",
7079 "items": { "type": "string" },
7080 "description": "For action=wait: wait on several background task ids at once (alternative to `task_id`)."
7081 },
7082 "until": {
7083 "type": "string",
7084 "enum": ["any", "all"],
7085 "description": "For action=wait with `task_ids`: return as soon as any task is terminal (`any`) or when every task is terminal (`all`, default)."
7086 },
7087 "id": {
7088 "type": "string",
7089 "description": "Alias for `task_id`."
7090 },
7091 "wait": {
7092 "type": "boolean",
7093 "description": "For action=wait, block until the task completes or timeout elapses (default: true). Pass false for a nonblocking snapshot; `block` is an accepted alias."
7094 },
7095 "close_stdin": {
7096 "type": "boolean",
7097 "description": "Close stdin after sending (action=interact)"
7098 },
7099 "all": {
7100 "type": "boolean",
7101 "description": "Cancel all running background tasks (action=cancel)"
7102 },
7103 "persist": {
7104 "type": "boolean",
7105 "description": "Keep this background service running after a successful headless exec (default: false). Requires background:true and explicit danger-full-access. Run the service itself in the foreground; do not use nohup or a trailing `&`."
7106 },
7107 "sandbox_permissions": {
7108 "type": "string",
7109 "enum": ["workspace-write", "danger-full-access"],
7110 "description": "The wider sandbox mode this exact command needs. Use only as a one-shot retry after a sandbox denial; requires justification and user approval in Ask."
7111 },
7112 "justification": {
7113 "type": "string",
7114 "description": "Required with sandbox_permissions: one sentence explaining why this exact command needs wider access."
7115 }
7116 },
7117 // The schema used to declare nothing required at all, so
7118 // `Bash{}` was schema-valid for the tool that runs shell
7119 // commands. What is required is per-action and cannot be spelled
7120 // as a flat `required` list: `run` needs `command`,
7121 // `wait`/`interact`/`cancel` need `task_id` (or its `id` alias),
7122 // and `cancel` needs `all` instead when cancelling everything.
7123 // A root `anyOf` of `required` groups is how this repo already
7124 // spells that (`apply_patch`), and `schema_sanitize`
7125 // knows the shape: providers that reject root composition get the
7126 // groups merged and the constraint restated as a description note
7127 // (`root_composition_constraint_note`). The cost is that
7128 // `strict_schema_supported` rejects a root `anyOf`, so `Bash`
7129 // opts out of DeepSeek strict mode.
7130 "anyOf": [
7131 { "required": ["command"] },
7132 { "required": ["task_id"] },
7133 { "required": ["id"] },
7134 { "required": ["all"] }
7135 ]
7136 })
7137 }
7138
7139 fn capabilities(&self) -> Vec<ToolCapability> {
7140 vec![
7141 ToolCapability::ExecutesCode,
7142 ToolCapability::Sandboxable,
7143 ToolCapability::RequiresApproval,
7144 ]
7145 }
7146
7147 fn approval_requirement(&self) -> ApprovalRequirement {
7148 ApprovalRequirement::Required
7149 }
7150
7151 fn approval_requirement_for(&self, input: &serde_json::Value) -> ApprovalRequirement {
7152 if exec_shell_input_is_parallel_readonly(input) {
7153 ApprovalRequirement::Auto
7154 } else {
7155 self.approval_requirement()
7156 }
7157 }
7158
7159 fn is_read_only_for(&self, input: &serde_json::Value) -> bool {
7160 exec_shell_input_is_parallel_readonly(input)
7161 }
7162
7163 fn supports_parallel_for(&self, input: &serde_json::Value) -> bool {
7164 exec_shell_input_is_parallel_readonly(input)
7165 }
7166
7167 fn starts_detached_for(&self, input: &serde_json::Value) -> bool {
7168 exec_shell_input_starts_detached(input)
7169 }
7170
7171 fn refusal_before_approval(
7172 &self,
7173 input: &serde_json::Value,
7174 context: &ToolContext,
7175 ) -> Option<ToolResult> {
7176 if input
7177 .get("sandbox_permissions")
7178 .and_then(serde_json::Value::as_str)
7179 == Some("danger-full-access")
7180 && context
7181 .shell_manager
7182 .lock()
7183 .unwrap_or_else(std::sync::PoisonError::into_inner)
7184 .tool_launcher_active()
7185 {
7186 return Some(ToolResult {
7187 content: "BLOCKED: this host runs tool commands as another user, and only inside the sandbox, so a danger-full-access escalation cannot run. Retry without sandbox_permissions.".to_string(),
7188 success: false,
7189 metadata: Some(json!({
7190 "blocked": true,
7191 "reason": "tool_launcher_requires_sandbox",
7192 })),
7193 });
7194 }
7195 if context.auto_approve {
7196 return None;
7197 }
7198 let input = if context.shell_policy == ShellPolicy::ReadOnly {
7199 normalize_readonly_cd(input)
7200 } else {
7201 input.clone()
7202 };
7203 let action = match self.forced_action {
7204 Some(forced) => forced,
7205 None => optional_str(&input, "action").ok()?.unwrap_or("run"),
7206 };
7207 if action != "run" {
7208 return None;
7209 }
7210 let command = input.get("command")?.as_str()?;
7211 dangerous_command_block(&analyze_command(command))
7212 }
7213
7214 async fn execute(
7215 &self,
7216 input: serde_json::Value,
7217 context: &ToolContext,
7218 ) -> Result<ToolResult, ToolError> {
7219 // A leading `cd <dir> &&` becomes the working directory before any
7220 // check, exactly as the read-only gates judged it.
7221 let input = if context.shell_policy == ShellPolicy::ReadOnly {
7222 normalize_readonly_cd(&input)
7223 } else {
7224 input
7225 };
7226 // `and_then(as_str).unwrap_or("run")` treated *any* non-string
7227 // `action` as absent and fell through to the branch that runs
7228 // arbitrary code: `Bash{action: 3, command: "…"}` executed the
7229 // command. Every sibling family refuses a non-string action
7230 // (`codewhale_tools::required_action`), and `Bash` cannot be the
7231 // lenient one. `optional_str` is the type-strictness lane's extractor:
7232 // absent or `null` takes the documented `run` default, anything else
7233 // is a `type_mismatch` naming the field and the type it needed.
7234 let action = match self.forced_action {
7235 Some(forced) => forced,
7236 None => optional_str(&input, "action")?.unwrap_or("run"),
7237 };
7238 let enforced_readonly = match input.get("read_only") {
7239 None => false,
7240 Some(serde_json::Value::Bool(enabled)) => *enabled,
7241 Some(value) => return Err(type_mismatch("read_only", value, "a boolean")),
7242 };
7243 if enforced_readonly && (!enforced_readonly_input(&input) || action != "run") {
7244 return Err(ToolError::invalid_input(
7245 "read_only=true accepts only foreground run with command, cwd and timeout_ms; background, input, interactive modes and sandbox escalation are incompatible",
7246 ));
7247 }
7248 if enforced_readonly {
7249 if context.sandbox_backend.is_some() {
7250 return Err(ToolError::permission_denied(
7251 "read_only execution requires a native enforcing sandbox; external backends cannot attest this policy",
7252 ));
7253 }
7254 let manager = context
7255 .shell_manager
7256 .lock()
7257 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
7258 if !manager
7259 .configured_sandbox_type()
7260 .is_some_and(is_native_readonly_sandbox)
7261 {
7262 return Err(ToolError::not_available(
7263 "read_only execution requires native read-only enforcement (macOS Seatbelt or configured Linux bubblewrap); nothing was run",
7264 ));
7265 }
7266 }
7267 let mut policy_input = input.clone();
7268 if let Some(object) = policy_input.as_object_mut() {
7269 object.insert("action".into(), json!(action));
7270 }
7271 crate::tools::execution_envelope::enforce_tool_denial(context, self.name(), &policy_input)?;
7272 if action == "interact" && context.shell_policy != ShellPolicy::Full {
7273 return Err(ToolError::permission_denied(
7274 "Sending shell input requires full shell permission.",
7275 ));
7276 }
7277 match action {
7278 "wait" => return self.execute_wait(&input, context).await,
7279 "interact" => return self.execute_interact(&input, context).await,
7280 "cancel" => return self.execute_cancel(&input, context).await,
7281 "run" => {}
7282 // Bash was the only action wrapper whose catch-all fell through to
7283 // its most dangerous branch: `{"action":"kill", "command":…}` ran
7284 // the command instead of cancelling, and a mis-cased "Cancel" did
7285 // the same. Every sibling (`File`, `Git`, `Web`, `Run`) already
7286 // refuses an unknown action; the tool that executes arbitrary code
7287 // should not be the lenient one.
7288 other => {
7289 return Err(ToolError::invalid_input(format!(
7290 "Unknown Bash action \"{other}\"; nothing was run. Pass one of: run, wait, interact, cancel."
7291 )));
7292 }
7293 }
7294 let command = require_no_nul(required_str(&input, "command")?, "command")?;
7295 let description = optional_str(&input, "description")?
7296 .map(str::trim)
7297 .filter(|value| !value.is_empty())
7298 .map(str::to_string);
7299 match context.shell_policy {
7300 ShellPolicy::None => {
7301 return Ok(ToolResult::error(
7302 "Shell tools are disabled by the active permission profile.",
7303 ));
7304 }
7305 ShellPolicy::ReadOnly => {
7306 if let Err(rejection) = exec_shell_input_agent_readonly_verdict(&input) {
7307 // A typed denial, so a Fleet worker's no-progress guard
7308 // counts it. #6298: an agent has no mode to switch to,
7309 // so it gets the same next steps as the other read-only
7310 // gates; only a parent session is told the user can
7311 // change modes.
7312 let message = if context.owner_agent_id.is_some()
7313 || context.tool_authority.is_some()
7314 {
7315 readonly_refusal(&rejection, readonly_enforced_lane_available(context))
7316 } else {
7317 format!(
7318 "{rejection}. This shell admits read-only inspection commands only. The user can change modes with /mode."
7319 )
7320 };
7321 return Err(ToolError::permission_denied(message));
7322 }
7323 }
7324 ShellPolicy::Full => {}
7325 }
7326 enforce_readonly_network_reads(command, context)?;
7327 let requested_timeout_ms = if self.optional_timeout {
7328 input
7329 .get("timeout_ms")
7330 .map(|value| {
7331 value
7332 .as_u64()
7333 .ok_or_else(|| type_mismatch("timeout_ms", value, "a positive integer"))
7334 })
7335 .transpose()?
7336 } else {
7337 let detached = optional_bool(&input, "background", false)?
7338 || optional_bool(&input, "interactive", false)?;
7339 let default_ms = if detached {
7340 120_000
7341 } else {
7342 CONTRACT_BASH_FOREGROUND_DEFAULT_TIMEOUT_MS
7343 };
7344 Some(optional_u64(&input, "timeout_ms", default_ms)?.min(600_000))
7345 };
7346 let background = optional_bool(&input, "background", false)?;
7347 let interactive = optional_bool(&input, "interactive", false)?;
7348 let combined_output = optional_bool(&input, "combined_output", false)?;
7349 let tty = optional_bool(&input, "tty", false)? || (combined_output && background);
7350 let timeout_ms = contract_bash_timeout_ms(
7351 self.optional_timeout,
7352 requested_timeout_ms,
7353 background,
7354 interactive,
7355 );
7356 let timeout_value_ms = timeout_ms.unwrap_or(BASH_MAX_TIMEOUT_MS);
7357 // Strict types (2026-08-04 review): a non-string here used to be
7358 // silently dropped — the command then ran with NO stdin and reported
7359 // success, the exact silent-drop failure the alias hardening closed
7360 // for misspelled names. A wrong type is an error, never a no-op.
7361 let stdin_data = match first_present_field(&input, &["stdin", "input", "data"]) {
7362 None => None,
7363 Some((name, value)) => Some(
7364 value
7365 .as_str()
7366 .ok_or_else(|| type_mismatch(name, value, "a string"))?
7367 .to_string(),
7368 ),
7369 };
7370
7371 if interactive && background {
7372 return Ok(ToolResult::error(
7373 "Interactive commands cannot run in background mode.",
7374 ));
7375 }
7376 if interactive && (tty || combined_output) {
7377 return Ok(ToolResult::error(
7378 "Interactive mode cannot be combined with TTY or combined_output sessions.",
7379 ));
7380 }
7381 if interactive && stdin_data.is_some() {
7382 return Ok(ToolResult::error(
7383 "Interactive mode cannot be combined with stdin data.",
7384 ));
7385 }
7386
7387 let persist = optional_bool(&input, "persist", false)?;
7388 if persist {
7389 if !background {
7390 return Err(ToolError::invalid_input(
7391 "persist:true requires background:true; a persisted service must be started as a background task.",
7392 ));
7393 }
7394 if interactive || tty {
7395 return Err(ToolError::invalid_input(
7396 "persist:true cannot be combined with interactive or TTY modes.",
7397 ));
7398 }
7399 if stdin_data.is_some() {
7400 return Err(ToolError::invalid_input(
7401 "persist:true spawns the service with null stdio; stdin data is not accepted.",
7402 ));
7403 }
7404 if !persistent_services_enabled_for(context) {
7405 return Err(ToolError::not_available(
7406 "persistent background services (persist:true) require Unix, a Full Access shell authority and a host that keeps services alive. They are rejected in restricted sandboxes, Fleet/sub-agents, and TTY/interactive/stdin modes.",
7407 ));
7408 }
7409 }
7410
7411 let background = background || tty;
7412
7413 let mut execpolicy_decision: Option<RuleDecision> = None;
7414 if context.features.enabled(Feature::ExecPolicy)
7415 && let Some(policy) = tokio::task::spawn_blocking(load_default_policy)
7416 .await
7417 .map_err(|e| {
7418 ToolError::execution_failed(format!("execpolicy load task failed: {e}"))
7419 })?
7420 .map_err(|e| ToolError::execution_failed(format!("execpolicy load failed: {e}")))?
7421 {
7422 let decision = policy.evaluate(command);
7423 execpolicy_decision = Some(decision.clone());
7424 if let RuleDecision::Deny(reason) = decision {
7425 return Ok(ToolResult {
7426 content: format!("BLOCKED: {reason}"),
7427 success: false,
7428 metadata: Some(json!({
7429 "execpolicy": {
7430 "decision": "deny",
7431 "reason": reason,
7432 }
7433 })),
7434 });
7435 }
7436 }
7437
7438 // Safety analysis (always run for metadata, but only block when not in YOLO mode)
7439 let safety = analyze_command(command);
7440 if !context.auto_approve
7441 && let Some(blocked) = dangerous_command_block(&safety)
7442 {
7443 return Ok(blocked);
7444 }
7445
7446 // This explicit mode only narrows the caller's posture. No approval or
7447 // inherited full-access override can disable the required sandbox.
7448 let readonly_network = enforced_readonly && readonly_lane_network_access(context);
7449 let policy_override = if enforced_readonly {
7450 Some(ExecutionSandboxPolicy::ReadOnly {
7451 network_access: readonly_network,
7452 })
7453 } else {
7454 context.elevated_sandbox_policy.clone()
7455 };
7456 // Strict types: a non-string cwd used to silently run the command in
7457 // the workspace default instead of erroring (2026-08-04 review).
7458 let working_dir = match first_present_field(&input, &["cwd", "working_dir"])
7459 .map(|(name, value)| {
7460 value
7461 .as_str()
7462 .ok_or_else(|| type_mismatch(name, value, "a string"))
7463 .and_then(|dir| require_no_nul(dir, name))
7464 })
7465 .transpose()?
7466 {
7467 Some(dir) => {
7468 // Validate cwd against workspace boundary (same as file tools)
7469 let resolved = context.resolve_path(dir)?;
7470 Some(resolved.to_string_lossy().to_string())
7471 }
7472 // Default to the tool context's workspace (which reflects the
7473 // child agent's worktree when `worktree: true` was used), not the
7474 // shared ShellManager's parent-workspace default_workspace.
7475 None => Some(context.workspace.display().to_string()),
7476 };
7477 if matches!(context.shell_policy, ShellPolicy::ReadOnly) && !enforced_readonly {
7478 let effective_cwd = working_dir
7479 .as_deref()
7480 .map(std::path::Path::new)
7481 .unwrap_or(&context.workspace);
7482 enforce_readonly_workspace_operands(command, &context.workspace, effective_cwd)?;
7483 }
7484
7485 // #456 — collect env from any configured `shell_env` hooks. Runs
7486 // synchronously, captures stdout, parses `KEY=VAL` lines, audit-logs
7487 // the keys (never the values). Empty / no-op when no hook is
7488 // configured.
7489 let policy_readonly = matches!(context.shell_policy, ShellPolicy::ReadOnly);
7490 let read_only_shell = policy_readonly || enforced_readonly;
7491 let auto_approved_readonly =
7492 !read_only_shell && exec_shell_input_is_parallel_readonly(&input);
7493 let auto_approved_readonly_git = auto_approved_readonly
7494 && command_first_program(command)
7495 .is_some_and(|program| matches!(program.as_str(), "git" | "gh"));
7496 let harden_git_env = read_only_shell || auto_approved_readonly_git;
7497 let mut extra_env = if read_only_shell {
7498 // shell_env hooks are arbitrary operator-configured processes.
7499 // They cannot run inside the evidence-only execution boundary.
7500 HashMap::new()
7501 } else if context.acp_host.is_none()
7502 && let Some(hook_executor) = &context.runtime.hook_executor
7503 {
7504 let hook_ctx = crate::hooks::HookContext::new()
7505 .with_tool_context(context)
7506 .with_tool_name("exec_shell")
7507 .with_tool_args(&input);
7508 let executor = Arc::clone(hook_executor);
7509 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
7510 #[cfg(any(test, feature = "test-support"))]
7511 let env_scope = crate::test_support::env_scope_ticket();
7512 tokio::task::spawn_blocking(move || {
7513 let _policy = codewhale_plugins::activation::PolicyScope::propagate(policy);
7514 #[cfg(any(test, feature = "test-support"))]
7515 let _env_scope = crate::test_support::join_env_scope(env_scope);
7516 executor.collect_shell_env(&hook_ctx)
7517 })
7518 .await
7519 .unwrap_or_default()
7520 } else {
7521 std::collections::HashMap::new()
7522 };
7523 if read_only_shell {
7524 extra_env.insert("GH_PAGER".to_string(), String::new());
7525 extra_env.insert("GH_PROMPT_DISABLED".to_string(), "1".to_string());
7526 extra_env.insert("GH_NO_UPDATE_NOTIFIER".to_string(), "1".to_string());
7527 // The classifier rejects explicit GHES repo/URL targets. Pin the
7528 // implicit environment side too, so inherited GH_HOST/GH_REPO
7529 // cannot redirect the call after api.github.com was approved.
7530 extra_env.insert("GH_HOST".to_string(), "github.com".to_string());
7531 extra_env.insert("GH_REPO".to_string(), String::new());
7532 extra_env.insert("ENV".to_string(), String::new());
7533 extra_env.insert("BASH_ENV".to_string(), String::new());
7534 extra_env.insert("CDPATH".to_string(), String::new());
7535 extra_env.insert("RIPGREP_CONFIG_PATH".to_string(), String::new());
7536 if let Some(path) = readonly_sanitized_path(&context.workspace) {
7537 extra_env.insert("PATH".to_string(), path);
7538 }
7539 extra_env.insert(READONLY_ENV_MARKER.to_string(), "1".to_string());
7540 }
7541 if harden_git_env {
7542 let null_device = if cfg!(windows) { "NUL" } else { "/dev/null" };
7543 let inert_git_helper = codewhale_dependencies::Git::INERT_HELPER;
7544 extra_env.retain(|key, _| {
7545 let upper = key.to_ascii_uppercase();
7546 !upper.starts_with("GIT_CONFIG_KEY_") && !upper.starts_with("GIT_CONFIG_VALUE_")
7547 });
7548 extra_env.insert("GIT_OPTIONAL_LOCKS".to_string(), "0".to_string());
7549 extra_env.insert("GIT_NO_LAZY_FETCH".to_string(), "1".to_string());
7550 extra_env.insert("GIT_NO_REPLACE_OBJECTS".to_string(), "1".to_string());
7551 extra_env.insert("GIT_PAGER".to_string(), String::new());
7552 extra_env.insert("PAGER".to_string(), String::new());
7553 // Ignore user/system Git configuration and replace any repository
7554 // external diff/gpg/ssh/editor/askpass helper with a fixed inert
7555 // executable. Repository config and attributes are attacker-controlled
7556 // evidence inputs; a nominal `git diff/log/show/status/blame` must not
7557 // turn them into programs.
7558 extra_env.insert("GIT_CONFIG_NOSYSTEM".to_string(), "1".to_string());
7559 extra_env.insert("GIT_CONFIG_GLOBAL".to_string(), null_device.to_string());
7560 extra_env.insert("GIT_CONFIG_PARAMETERS".to_string(), String::new());
7561 extra_env.insert(
7562 "GIT_EXTERNAL_DIFF".to_string(),
7563 inert_git_helper.to_string(),
7564 );
7565 extra_env.insert("GIT_ATTR_NOSYSTEM".to_string(), "1".to_string());
7566 extra_env.insert("GIT_SSH_COMMAND".to_string(), inert_git_helper.to_string());
7567 extra_env.insert("GIT_EDITOR".to_string(), inert_git_helper.to_string());
7568 extra_env.insert("GIT_ASKPASS".to_string(), inert_git_helper.to_string());
7569 let static_git_config = [
7570 ("core.fsmonitor", "false"),
7571 ("core.hooksPath", null_device),
7572 ("core.pager", ""),
7573 ("core.sshCommand", inert_git_helper),
7574 ("core.editor", inert_git_helper),
7575 ("core.askPass", inert_git_helper),
7576 ("core.alternateRefsCommand", ""),
7577 ("credential.helper", ""),
7578 ("log.showSignature", "false"),
7579 ("diff.submodule", "short"),
7580 ("diff.ignoreSubmodules", "dirty"),
7581 ("protocol.ext.allow", "never"),
7582 ("gpg.program", inert_git_helper),
7583 ("gpg.openpgp.program", inert_git_helper),
7584 ("gpg.x509.program", inert_git_helper),
7585 ("gpg.ssh.program", inert_git_helper),
7586 ];
7587 let mut count = 0usize;
7588 for (key, value) in static_git_config {
7589 extra_env.insert(format!("GIT_CONFIG_KEY_{count}"), key.to_string());
7590 extra_env.insert(format!("GIT_CONFIG_VALUE_{count}"), value.to_string());
7591 count += 1;
7592 }
7593 // A working-tree read (diff, status, blame) runs the repository's
7594 // clean filters and diff drivers; discover and neutralize every
7595 // dynamic repository driver key.
7596 let git_dirs = readonly_git_dirs_with_cwd_repo(
7597 command,
7598 working_dir
7599 .as_deref()
7600 .map_or(context.workspace.as_path(), std::path::Path::new),
7601 enforced_readonly || auto_approved_readonly_git,
7602 );
7603 let overrides = tokio::task::spawn_blocking(move || {
7604 let mut overrides = std::collections::BTreeMap::new();
7605 for dir in git_dirs {
7606 for (key, value) in
7607 codewhale_dependencies::Git::review_shell_config_overrides(&dir)?
7608 {
7609 overrides.insert(key, value);
7610 }
7611 }
7612 anyhow::Ok(overrides)
7613 })
7614 .await
7615 .map_err(|e| ToolError::execution_failed(format!("git task panicked: {e}")))?
7616 .map_err(|e| {
7617 ToolError::permission_denied(format!(
7618 "Read-only shell could not inspect the repository's Git configuration: {e:#}"
7619 ))
7620 })?;
7621 for (key, value) in overrides {
7622 extra_env.insert(format!("GIT_CONFIG_KEY_{count}"), key);
7623 extra_env.insert(format!("GIT_CONFIG_VALUE_{count}"), value.to_string());
7624 count += 1;
7625 }
7626 extra_env.insert("GIT_CONFIG_COUNT".to_string(), count.to_string());
7627 extra_env.insert(GIT_HARDENING_ENV_MARKER.to_string(), "1".to_string());
7628 }
7629 insert_agent_mark_env(&mut extra_env, context);
7630
7631 let command_expense = infer_command_expense(command);
7632 let heavy_permit = acquire_heavy_command_permit(command, context.cancel_token.as_ref())
7633 .await
7634 .map_err(|error| ToolError::execution_failed(error.to_string()))?;
7635 let admission_wait_ms = heavy_permit
7636 .as_ref()
7637 .map(|permit| u64::try_from(permit.queued_for().as_millis()).unwrap_or(u64::MAX));
7638 let admission_limit = heavy_permit.as_ref().map(HeavyCommandPermit::limit);
7639 let admission_memory = heavy_permit
7640 .as_ref()
7641 .map(HeavyCommandPermit::memory_pressure);
7642
7643 // Route through external sandbox backend when configured.
7644 if let Some(backend) = &context.sandbox_backend {
7645 if self.optional_timeout {
7646 return Err(ToolError::not_available(
7647 "bash is unavailable with this external sandbox backend because it cannot preserve combined streaming output and timeout semantics. Use the native sandbox or search for the backend-specific shell tool.",
7648 ));
7649 }
7650 if matches!(context.shell_policy, ShellPolicy::ReadOnly) {
7651 return Err(ToolError::permission_denied(
7652 "Read-only Scout shell cannot use an external sandbox backend because that interface accepts a raw command string rather than the classifier-approved argv. Use File read/search, or run this Scout without the external backend.",
7653 ));
7654 }
7655 if interactive {
7656 return Ok(ToolResult::error(
7657 "Interactive mode is not supported with external sandbox backends.",
7658 ));
7659 }
7660 if background {
7661 return Ok(ToolResult::error(
7662 "Background mode is not supported with external sandbox backends.",
7663 ));
7664 }
7665 if tty {
7666 return Ok(ToolResult::error(
7667 "TTY mode is not supported with external sandbox backends.",
7668 ));
7669 }
7670
7671 let started = std::time::Instant::now();
7672 let backend_command =
7673 if auto_approved_readonly_git && command_is_admitted_readonly_git(command) {
7674 let (program, args) = hardened_readonly_argv(command)
7675 .map_err(|e| ToolError::permission_denied(e.to_string()))?;
7676 std::iter::once(program)
7677 .chain(args)
7678 .map(|word| shell_words::quote(&word).into_owned())
7679 .collect::<Vec<_>>()
7680 .join(" ")
7681 } else {
7682 command.to_string()
7683 };
7684 let backend_result = backend.exec(&backend_command, &extra_env).await;
7685
7686 let (result, persisted_artifact) = match backend_result {
7687 Ok(output) => {
7688 let (stdout, stdout_meta) = truncate_with_meta(&output.stdout);
7689 let (stderr, stderr_meta) = truncate_with_meta(&output.stderr);
7690 let persisted_artifact = if stdout_meta.truncated || stderr_meta.truncated {
7691 let session_id = context.state_namespace.clone();
7692 let origin_tool_call_id = context.origin_tool_call_id.clone();
7693 tokio::task::spawn_blocking(move || {
7694 let full_combined =
7695 combine_full_shell_streams(&output.stdout, &output.stderr);
7696 persist_shell_output_artifact(
7697 &session_id,
7698 origin_tool_call_id.as_deref(),
7699 &format!("bash-sandbox-{}", Uuid::new_v4().simple()),
7700 full_combined.as_bytes(),
7701 )
7702 .ok()
7703 })
7704 .await
7705 .map_err(|err| ToolError::execution_failed(err.to_string()))?
7706 } else {
7707 None
7708 };
7709 (
7710 ShellResult {
7711 task_id: None,
7712 status: if output.exit_code == 0 {
7713 ShellStatus::Completed
7714 } else {
7715 ShellStatus::Failed
7716 },
7717 exit_code: Some(i64::from(output.exit_code)),
7718 stdout,
7719 stderr,
7720 duration_ms: u64::try_from(started.elapsed().as_millis())
7721 .unwrap_or(u64::MAX),
7722 stdout_len: stdout_meta.original_len,
7723 stderr_len: stderr_meta.original_len,
7724 stdout_omitted: stdout_meta.omitted,
7725 stderr_omitted: stderr_meta.omitted,
7726 stdout_truncated: stdout_meta.truncated,
7727 stderr_truncated: stderr_meta.truncated,
7728 sandboxed: true,
7729 sandbox_type: Some("opensandbox".to_string()),
7730 sandbox_denied: false,
7731 },
7732 persisted_artifact,
7733 )
7734 }
7735 Err(e) => {
7736 return Ok(ToolResult::error(format!("Sandbox backend error: {e}")));
7737 }
7738 };
7739
7740 let stdout_summary = summarize_output(&result.stdout);
7741 let stderr_summary = summarize_output(&result.stderr);
7742 let summary = if !stderr_summary.is_empty() {
7743 stderr_summary.clone()
7744 } else {
7745 stdout_summary.clone()
7746 };
7747 let python_dependency_hint = python_build_dependency_hint(command, &result);
7748 let mut output = if result.stdout.is_empty() && result.stderr.is_empty() {
7749 "(no output)".to_string()
7750 } else if result.stderr.is_empty() {
7751 result.stdout.clone()
7752 } else {
7753 format!("{}\n\nSTDERR:\n{}", result.stdout, result.stderr)
7754 };
7755 if let Some(hint) = python_dependency_hint {
7756 output = format!("{hint}\n\n{output}");
7757 }
7758
7759 let mut metadata = json!({
7760 "exit_code": result.exit_code,
7761 "exit_code_hex": exit_code_hex(result.exit_code),
7762 "status": format!("{:?}", result.status),
7763 "duration_ms": result.duration_ms,
7764 "sandboxed": true,
7765 "sandbox_type": "opensandbox",
7766 "sandbox_denied": false,
7767 "task_id": result.task_id,
7768 "stdout_len": result.stdout_len,
7769 "stderr_len": result.stderr_len,
7770 "stdout_truncated": result.stdout_truncated,
7771 "stderr_truncated": result.stderr_truncated,
7772 "stdout_omitted": result.stdout_omitted,
7773 "stderr_omitted": result.stderr_omitted,
7774 "summary": summary,
7775 "stdout_summary": stdout_summary,
7776 "stderr_summary": stderr_summary,
7777 "safety_level": format!("{:?}", safety.level),
7778 "interactive": false,
7779 "canceled": false,
7780 "sandbox_backend": backend.kind().as_str(),
7781 "expense_class": match command_expense {
7782 CommandExpense::Heavy => "heavy",
7783 CommandExpense::Normal => "normal",
7784 },
7785 "resource_admission_wait_ms": admission_wait_ms,
7786 "resource_admission_limit": admission_limit,
7787 });
7788 if let Some(description) = description.as_deref() {
7789 metadata["description"] = json!(description);
7790 }
7791 attach_shell_owner_metadata(&mut metadata, context);
7792 attach_cargo_failure_summary(&mut metadata, command, &result);
7793 attach_python_build_dependency_hint(&mut metadata, python_dependency_hint);
7794 if let Some(artifact) = persisted_artifact.as_ref() {
7795 output.push_str("\n\n");
7796 output.push_str(&format_persisted_shell_artifact_footer(artifact));
7797 stamp_persisted_shell_artifact_metadata(&mut metadata, artifact, &output);
7798 }
7799
7800 return Ok(ToolResult {
7801 content: output,
7802 success: result.status == ShellStatus::Completed,
7803 metadata: Some(metadata),
7804 });
7805 }
7806
7807 let mut lifecycle_warning = None;
7808 let timeout_bounds_ms = if self.optional_timeout {
7809 (1, BASH_MAX_TIMEOUT_MS)
7810 } else {
7811 (1_000, 600_000)
7812 };
7813 let mut receipt_identity = None;
7814 // #6689: the receipt exists for completion hooks to read. Without one
7815 // registered it would only ride along in tool metadata, which the
7816 // Runtime API persists and emits for every call.
7817 let wants_receipt = context.runtime.hook_executor.as_ref().is_some_and(|hooks| {
7818 hooks.has_hooks_for_event(codewhale_config::hooks::HookEvent::ToolCallAfter)
7819 || hooks.has_hooks_for_event(codewhale_config::hooks::HookEvent::OnError)
7820 });
7821 let result = if interactive {
7822 let mut manager = context
7823 .shell_manager
7824 .lock()
7825 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
7826 let work_lifecycle = shell_work_lifecycle_from_context(context);
7827 let task_id = format!("shell_{}", Uuid::new_v4().simple());
7828 let mut spawn_guard = ShellSpawnIntentGuard::new(work_lifecycle, &task_id, command);
7829 // Only a registered operation is observed (#6435).
7830 let work_lifecycle = spawn_guard.lifecycle.clone();
7831 let result = manager.execute_interactive_with_policy_env(
7832 command,
7833 working_dir.as_deref(),
7834 timeout_value_ms,
7835 policy_override,
7836 extra_env,
7837 );
7838 match result {
7839 Ok(result) => {
7840 // The process result is authoritative once execution has
7841 // completed. Disarm before observing it so a graph-write
7842 // failure cannot relabel a successful command as Failed.
7843 spawn_guard.disarm();
7844 if let Some(lifecycle) = work_lifecycle.as_ref() {
7845 let raw_bytes = result.stdout_len.saturating_add(result.stderr_len);
7846 if let Err(err) = lifecycle.observe(&task_id, &result.status, 1, raw_bytes)
7847 {
7848 tracing::warn!(shell_id = %task_id, error = %err, "interactive shell completed but Work lifecycle reconciliation failed");
7849 lifecycle_warning = Some(err.to_string());
7850 }
7851 }
7852 Ok((result, None))
7853 }
7854 Err(err) => Err(err),
7855 }
7856 } else if background {
7857 let mut manager = context
7858 .shell_manager
7859 .lock()
7860 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
7861 let result = manager.execute_with_options_env_for_owner_and_work(
7862 command,
7863 None,
7864 working_dir.as_deref(),
7865 timeout_value_ms,
7866 true,
7867 stdin_data.as_deref(),
7868 tty,
7869 policy_override,
7870 extra_env,
7871 shell_job_owner_from_context(context),
7872 context.state_namespace.clone(),
7873 context.origin_tool_call_id.clone(),
7874 context.origin_turn_id.clone(),
7875 shell_work_lifecycle_from_context(context),
7876 None,
7877 persist,
7878 timeout_bounds_ms,
7879 );
7880 if let (Ok(result), Some(permit)) = (&result, heavy_permit)
7881 && let Some(task_id) = result.task_id.as_deref()
7882 {
7883 manager
7884 .attach_heavy_permit(task_id, permit)
7885 .map_err(|error| ToolError::execution_failed(error.to_string()))?;
7886 }
7887 if let (Ok(result), Some(description)) = (&result, description.clone())
7888 && let Some(task_id) = result.task_id.as_deref()
7889 {
7890 let _ = manager.tag_description(task_id, Some(description));
7891 }
7892 result.map(|result| (result, None))
7893 } else {
7894 let readonly_hardening = if policy_readonly && !enforced_readonly {
7895 ReadonlyCommandHardening::StrictReadOnly(context.workspace.as_path())
7896 } else if enforced_readonly {
7897 ReadonlyCommandHardening::GitReadOnlyIfAdmitted {
7898 workspace: context.workspace.as_path(),
7899 require_native_sandbox: true,
7900 }
7901 } else if auto_approved_readonly_git {
7902 ReadonlyCommandHardening::GitReadOnlyIfAdmitted {
7903 workspace: context.workspace.as_path(),
7904 require_native_sandbox: false,
7905 }
7906 } else {
7907 ReadonlyCommandHardening::None
7908 };
7909 execute_foreground_via_background(
7910 context,
7911 command,
7912 description.clone(),
7913 heavy_permit,
7914 working_dir,
7915 timeout_ms,
7916 stdin_data.as_deref(),
7917 combined_output,
7918 policy_override,
7919 extra_env,
7920 readonly_hardening,
7921 timeout_bounds_ms,
7922 wants_receipt,
7923 &mut receipt_identity,
7924 )
7925 .await
7926 };
7927
7928 match result {
7929 Ok((result, persisted_artifact)) => {
7930 let backgrounded_foreground =
7931 !background && !interactive && result.status == ShellStatus::Running;
7932 if (background || backgrounded_foreground)
7933 && let (Some(shell_id), Some(task_id)) = (
7934 result.task_id.as_deref(),
7935 context.runtime.active_task_id.clone(),
7936 )
7937 && let Ok(mut manager) = context.shell_manager.lock()
7938 {
7939 let _ = manager.tag_linked_task(shell_id, Some(task_id));
7940 }
7941
7942 let was_cancelled = context
7943 .cancel_token
7944 .as_ref()
7945 .is_some_and(|token| token.is_cancelled());
7946 let execution_receipt = receipt_identity.as_ref().and_then(|identity| {
7947 shell_execution_receipt(
7948 identity,
7949 &result,
7950 if self.optional_timeout {
7951 "combined"
7952 } else {
7953 "separate"
7954 },
7955 )
7956 });
7957 let readonly_offline_hint = (enforced_readonly && !readonly_network)
7958 .then(|| readonly_offline_network_hint(command, &result))
7959 .flatten();
7960 let readonly_sandbox_hint = enforced_readonly
7961 .then(|| readonly_denied_hint(context, command, &result))
7962 .flatten();
7963 if self.optional_timeout {
7964 let network_restricted_hint = readonly_offline_hint
7965 .or_else(|| shell_network_restricted_hint(context, command, &result));
7966 return finish_contract_bash_result(
7967 result,
7968 timeout_ms,
7969 context,
7970 execution_receipt,
7971 readonly_network,
7972 network_restricted_hint,
7973 readonly_sandbox_hint,
7974 background,
7975 description.as_deref(),
7976 persisted_artifact,
7977 );
7978 }
7979 let task_id_str = result.task_id.clone().unwrap_or_default();
7980 let stdout_summary = summarize_output(&result.stdout);
7981 let stderr_summary = summarize_output(&result.stderr);
7982 let summary = if !stderr_summary.is_empty() {
7983 stderr_summary.clone()
7984 } else {
7985 stdout_summary.clone()
7986 };
7987 let network_restricted_hint = readonly_offline_hint
7988 .or_else(|| shell_network_restricted_hint(context, command, &result))
7989 .map(str::to_string);
7990 let sandbox_denied_hint = if network_restricted_hint.is_none() {
7991 readonly_sandbox_hint
7992 .map(str::to_string)
7993 .or_else(|| shell_sandbox_denied_hint(context, &result))
7994 } else {
7995 None
7996 };
7997 let provenance_hint = macos_provenance_hint(&result);
7998 let python_dependency_hint = python_build_dependency_hint(command, &result);
7999 let mut output = if interactive {
8000 format!(
8001 "Interactive command completed (exit code: {:?})",
8002 result.exit_code
8003 )
8004 } else if result.status == ShellStatus::Completed {
8005 if result.stdout.is_empty() && result.stderr.is_empty() {
8006 "(no output)".to_string()
8007 } else if result.stderr.is_empty() {
8008 result.stdout.clone()
8009 } else {
8010 format!("{}\n\nSTDERR:\n{}", result.stdout, result.stderr)
8011 }
8012 } else if persist && result.status == ShellStatus::Running {
8013 format!(
8014 "Persistent service staged: {task_id_str}. Probe readiness with a separate command. Codewhale will transfer ownership only if this exec finishes successfully."
8015 )
8016 } else if result.status == ShellStatus::Running {
8017 let completion_contract = if context.owner_agent_id.is_some() {
8018 "completion stays in task/status and is not injected into the parent model."
8019 } else {
8020 "completion is delivered to the model as an internal runtime event before its next step and shown in task/status state; if the turn ends first, a headless run stops the task unseen."
8021 };
8022 if backgrounded_foreground {
8023 let seconds = result.duration_ms / 1_000;
8024 let so_far = match (result.stdout.trim(), result.stderr.trim()) {
8025 ("", "") => "(no output yet)".to_string(),
8026 (out, "") => tail_lines(out, 20),
8027 ("", err) => format!("STDERR:\n{}", tail_lines(err, 20)),
8028 (out, err) => format!(
8029 "{}\n\nSTDERR:\n{}",
8030 tail_lines(out, 20),
8031 tail_lines(err, 20)
8032 ),
8033 };
8034 let notice = promotion_notice(
8035 context,
8036 &task_id_str,
8037 seconds,
8038 &format!("{}{}", result.stdout, result.stderr),
8039 );
8040 format!(
8041 "{notice}\n\nOutput so far:\n{so_far}\n\n{completion_contract} Keep working if you can. To decide: call `task_shell_wait` directly with task_id=\"{task_id_str}\" for more output or completion, or with cancel=true to stop it. It also stops when the session ends; do not sleep-poll with bash."
8042 )
8043 } else {
8044 format!(
8045 "Background task started: {task_id_str}\n\nReturns immediately; {completion_contract} Codewhale terminates this task when the session exits. If a service must survive a successful headless exec, start it with background=true and persist=true. Keep working; call `task_shell_wait` directly with task_id=\"{task_id_str}\" at a true dependency to block until completion or timeout. Do not sleep-poll with bash."
8046 )
8047 }
8048 } else if result.status == ShellStatus::Killed && was_cancelled {
8049 format!(
8050 "Command canceled; process killed. {}\n\nSTDOUT:\n{}\n\nSTDERR:\n{}",
8051 kill_outcome_note(&format!("{}{}", result.stdout, result.stderr)),
8052 result.stdout,
8053 result.stderr
8054 )
8055 } else if result.status == ShellStatus::TimedOut {
8056 format!(
8057 "Command timed out after {timeout_value_ms}ms; process killed.\n\nSTDOUT:\n{}\n\nSTDERR:\n{}",
8058 result.stdout, result.stderr
8059 )
8060 } else {
8061 format!(
8062 "Command failed ({})\n\nSTDOUT:\n{}\n\nSTDERR:\n{}",
8063 exit_code_label(result.exit_code),
8064 result.stdout,
8065 result.stderr
8066 )
8067 };
8068 if let Some(hint) = network_restricted_hint.as_deref() {
8069 output = format!("{hint}\n\n{output}");
8070 }
8071 if let Some(hint) = sandbox_denied_hint.as_deref() {
8072 output = format!("{hint}\n\n{output}");
8073 }
8074 if let Some(hint) = provenance_hint {
8075 output = format!("{hint}\n\n{output}");
8076 }
8077 if let Some(hint) = python_dependency_hint {
8078 output = format!("{hint}\n\n{output}");
8079 }
8080
8081 let mut metadata = json!({
8082 "exit_code": result.exit_code,
8083 "exit_code_hex": exit_code_hex(result.exit_code),
8084 "status": format!("{:?}", result.status),
8085 "duration_ms": result.duration_ms,
8086 "sandboxed": result.sandboxed,
8087 "sandbox_type": result.sandbox_type,
8088 "sandbox_denied": result.sandbox_denied,
8089 "task_id": result.task_id,
8090 "stdout_len": result.stdout_len,
8091 "stderr_len": result.stderr_len,
8092 "stdout_truncated": result.stdout_truncated,
8093 "stderr_truncated": result.stderr_truncated,
8094 "stdout_omitted": result.stdout_omitted,
8095 "stderr_omitted": result.stderr_omitted,
8096 "lifecycle_warning": lifecycle_warning,
8097 "expense_class": match command_expense {
8098 CommandExpense::Heavy => "heavy",
8099 CommandExpense::Normal => "normal",
8100 },
8101 "resource_admission_wait_ms": admission_wait_ms,
8102 "resource_admission_limit": admission_limit,
8103 "resource_admission_memory": match admission_memory {
8104 Some(MemoryPressure::Critical) => "critical",
8105 Some(MemoryPressure::Constrained) => "constrained",
8106 Some(MemoryPressure::Nominal) | None => "nominal",
8107 Some(MemoryPressure::Unknown) => "unknown",
8108 },
8109 "summary": summary,
8110 "stdout_summary": stdout_summary,
8111 "stderr_summary": stderr_summary,
8112 "safety_level": format!("{:?}", safety.level),
8113 "interactive": interactive,
8114 "combined_output": combined_output,
8115 "canceled": was_cancelled,
8116 "execpolicy": execpolicy_decision.as_ref().map(|decision| match decision {
8117 RuleDecision::Allow => json!({
8118 "decision": "allow",
8119 }),
8120 RuleDecision::Deny(reason) => json!({
8121 "decision": "deny",
8122 "reason": reason,
8123 }),
8124 RuleDecision::AskUser(reason) => json!({
8125 "decision": "ask_user",
8126 "reason": reason,
8127 }),
8128 }),
8129 });
8130 if let Some(description) = description.as_deref() {
8131 metadata["description"] = json!(description);
8132 }
8133 if let Some(receipt) = execution_receipt {
8134 metadata["execution_receipt"] = receipt;
8135 }
8136 metadata["backgrounded"] = json!(background || backgrounded_foreground);
8137 if persist {
8138 metadata["persist_requested"] = json!(true);
8139 metadata["ownership"] = json!("managed_pending_exec_success");
8140 metadata["background_policy"] = json!("pending_ownership_transfer");
8141 metadata["auto_resume_on_completion"] = json!(false);
8142 metadata["completion_surface"] = json!("headless_exec_release_receipt");
8143 } else if background || backgrounded_foreground {
8144 let child_owned = context.owner_agent_id.is_some();
8145 metadata["auto_resume_on_completion"] = json!(!child_owned);
8146 metadata["completion_surface"] = if child_owned {
8147 json!("task_status_and_explicit_wait")
8148 } else {
8149 json!("runtime_event_and_task_status")
8150 };
8151 metadata["background_policy"] = json!("nonblocking");
8152 }
8153 if let Some(hint) = network_restricted_hint {
8154 metadata["sandbox_network_restricted"] = json!(true);
8155 metadata["sandbox_network_denied_hint"] = json!(hint);
8156 }
8157 if readonly_network {
8158 metadata["sandbox_network"] = json!(true);
8159 }
8160 if let Some(hint) = sandbox_denied_hint {
8161 metadata["sandbox_denied_hint"] = json!(hint);
8162 }
8163 if provenance_hint.is_some() {
8164 metadata["macos_provenance_restricted"] = json!(true);
8165 }
8166 attach_shell_owner_metadata(&mut metadata, context);
8167 attach_cargo_failure_summary(&mut metadata, command, &result);
8168 attach_python_build_dependency_hint(&mut metadata, python_dependency_hint);
8169 if let Some(artifact) = persisted_artifact.as_ref() {
8170 output.push_str("\n\n");
8171 output.push_str(&format_persisted_shell_artifact_footer(artifact));
8172 stamp_persisted_shell_artifact_metadata(&mut metadata, artifact, &output);
8173 }
8174
8175 Ok(ToolResult {
8176 content: output,
8177 success: result.status == ShellStatus::Completed
8178 || result.status == ShellStatus::Running,
8179 metadata: Some(metadata),
8180 })
8181 }
8182 Err(e) => Ok(ToolResult::error(shell_execution_failed_message(&e))),
8183 }
8184 }
8185 }
8186
8187 /// Render a spawn/stream failure for the model and the user: the full cause
8188 /// chain (an anyhow context alone hides the `ENOSPC`/`EMFILE` underneath) plus,
8189 /// when the innermost error looks like host resource exhaustion, what to do
8190 /// about it. The shell tool keeps no state from a failed spawn, so retrying is
8191 /// always safe.
8192 fn shell_execution_failed_message(error: &anyhow::Error) -> String {
8193 let hint = error
8194 .chain()
8195 .filter_map(|cause| cause.downcast_ref::<io::Error>())
8196 .find_map(output::resource_exhaustion_hint);
8197 match hint {
8198 Some(hint) => format!(
8199 "Shell execution failed: {error:#}. Likely host resource exhaustion — {hint}. The shell tool itself is still usable; the next call starts fresh."
8200 ),
8201 None => format!("Shell execution failed: {error:#}"),
8202 }
8203 }
8204
8205 /// Maximum deliberate dependency-barrier wait accepted by `exec_shell_wait`.
8206 pub const EXEC_SHELL_WAIT_MAX_TIMEOUT_MS: u64 = 600_000;
8207
8208 impl BashTool {
8209 async fn execute_wait(
8210 &self,
8211 input: &serde_json::Value,
8212 context: &ToolContext,
8213 ) -> Result<ToolResult, ToolError> {
8214 // Multi-task wait (#5549): task_ids + until=any|all. The validated
8215 // single-task path stays unchanged below when task_ids is absent.
8216 if let Some(task_ids) = input.get("task_ids") {
8217 let ids = task_ids
8218 .as_array()
8219 .ok_or_else(|| type_mismatch("task_ids", task_ids, "an array of strings"))?;
8220 let ids = ids
8221 .iter()
8222 .map(|value| {
8223 value
8224 .as_str()
8225 .ok_or_else(|| type_mismatch("task_ids", value, "strings"))
8226 .map(str::to_string)
8227 })
8228 .collect::<Result<Vec<_>, _>>()?;
8229 return self.execute_wait_many(input, context, &ids).await;
8230 }
8231 let task_id = required_task_id(input)?;
8232 let wait = match first_present_field(input, &["wait", "block"]) {
8233 None => true,
8234 Some((name, value)) => value
8235 .as_bool()
8236 .ok_or_else(|| type_mismatch(name, value, "a boolean"))?,
8237 };
8238 let timeout_ms = wait_timeout_ms(input)?;
8239
8240 let ((delta, persisted_artifact), interruption) = if wait {
8241 wait_for_shell_delta_cancellable(context, task_id, timeout_ms).await?
8242 } else {
8243 let raw = {
8244 let mut manager = context
8245 .shell_manager
8246 .lock()
8247 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8248 manager
8249 .get_raw_output_delta_for_session(
8250 &context.state_namespace,
8251 task_id,
8252 false,
8253 timeout_ms,
8254 )
8255 .map_err(|err| ToolError::execution_failed(err.to_string()))?
8256 };
8257 (finalize_raw_shell_delta(raw, context), None)
8258 };
8259
8260 let status = delta.result.status.clone();
8261 let mut result = build_shell_delta_tool_result(delta, context);
8262 if let Some(artifact) = persisted_artifact.as_ref() {
8263 attach_shell_artifact_to_tool_result(&mut result, artifact);
8264 }
8265 if let Some(metadata) = result.metadata.as_mut()
8266 && let Some(object) = metadata.as_object_mut()
8267 {
8268 object.insert("wait_timeout_ms".to_string(), json!(timeout_ms));
8269 }
8270 if matches!(status, ShellStatus::Running)
8271 && let Some(progress) = context
8272 .shell_manager
8273 .lock()
8274 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?
8275 .running_progress(task_id)
8276 {
8277 result.content = format!("{progress}\n{}", result.content);
8278 }
8279 if let Some(interruption) = interruption {
8280 let (action, key) = match interruption {
8281 ShellWaitInterruption::Canceled => ("canceled", "wait_canceled"),
8282 ShellWaitInterruption::Detached => ("detached", "wait_detached"),
8283 };
8284 if matches!(status, ShellStatus::Running) {
8285 result.content = format!(
8286 "Wait {action}; background shell task {task_id} is still running.\n\n{}",
8287 result.content
8288 );
8289 }
8290 if let Some(metadata) = result.metadata.as_mut()
8291 && let Some(object) = metadata.as_object_mut()
8292 {
8293 object.insert(key.to_string(), json!(true));
8294 }
8295 }
8296
8297 Ok(result)
8298 }
8299
8300 /// Wait on several background tasks at once (#5549).
8301 ///
8302 /// `until` selects the completion condition: `any` returns as soon as one
8303 /// task is terminal, `all` waits for every one. Unknown task ids fail the
8304 /// call (same contract as the single-task path); a timeout reports the
8305 /// still-running ids so the caller can cancel or wait again.
8306 async fn execute_wait_many(
8307 &self,
8308 input: &serde_json::Value,
8309 context: &ToolContext,
8310 task_ids: &[String],
8311 ) -> Result<ToolResult, ToolError> {
8312 let until = match input.get("until").and_then(serde_json::Value::as_str) {
8313 None | Some("all") => "all",
8314 Some("any") => "any",
8315 Some(other) => {
8316 return Err(ToolError::invalid_input(format!(
8317 "until must be \"any\" or \"all\", got {other}"
8318 )));
8319 }
8320 };
8321 let wait = match first_present_field(input, &["wait", "block"]) {
8322 None => true,
8323 Some((name, value)) => value
8324 .as_bool()
8325 .ok_or_else(|| type_mismatch(name, value, "a boolean"))?,
8326 };
8327 let timeout_ms = wait_timeout_ms(input)?;
8328 let deadline = std::time::Instant::now() + Duration::from_millis(timeout_ms);
8329 let mut timed_out = false;
8330 let mut wait_canceled = false;
8331 let mut wait_detached = false;
8332
8333 let snapshot =
8334 |manager: &mut ShellManager| -> Result<Vec<(String, ShellStatus)>, ToolError> {
8335 task_ids
8336 .iter()
8337 .map(|id| {
8338 let detail = manager
8339 .inspect_job_for_session(&context.state_namespace, id)
8340 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
8341 Ok((id.clone(), detail.snapshot.status))
8342 })
8343 .collect()
8344 };
8345
8346 let detach = if wait {
8347 let mut manager = context
8348 .shell_manager
8349 .lock()
8350 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8351 // Validate every owner before registering or consuming any output.
8352 snapshot(&mut manager)?;
8353 Some(manager.register_shell_wait(&context.state_namespace))
8354 } else {
8355 None
8356 };
8357 let mut poll_tick_ms: u64 = FOREGROUND_POLL_INITIAL_MS;
8358 let statuses = loop {
8359 let current = {
8360 let mut manager = context
8361 .shell_manager
8362 .lock()
8363 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8364 snapshot(&mut manager)?
8365 };
8366 if context
8367 .cancel_token
8368 .as_ref()
8369 .is_some_and(|token| token.is_cancelled())
8370 {
8371 wait_canceled = true;
8372 break current;
8373 }
8374 let running = current
8375 .iter()
8376 .filter(|(_, status)| *status == ShellStatus::Running)
8377 .count();
8378 let terminal = current.len().saturating_sub(running);
8379 let satisfied = if until == "any" {
8380 terminal >= 1
8381 } else {
8382 running == 0
8383 };
8384 if !wait || satisfied {
8385 break current;
8386 }
8387 if detach
8388 .as_ref()
8389 .is_some_and(|detach| detach.load(Ordering::Acquire))
8390 {
8391 wait_detached = true;
8392 break current;
8393 }
8394 if std::time::Instant::now() >= deadline {
8395 timed_out = true;
8396 break current;
8397 }
8398 tokio::time::sleep(Duration::from_millis(poll_tick_ms)).await;
8399 poll_tick_ms = (poll_tick_ms * 2).min(FOREGROUND_POLL_MAX_MS);
8400 };
8401
8402 let running_after = statuses
8403 .iter()
8404 .filter(|(_, status)| *status == ShellStatus::Running)
8405 .count();
8406 let settled = statuses.len().saturating_sub(running_after);
8407 let lines: Vec<String> = {
8408 let mut manager = context
8409 .shell_manager
8410 .lock()
8411 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8412 statuses
8413 .iter()
8414 .map(|(id, status)| {
8415 let progress = (*status == ShellStatus::Running)
8416 .then(|| manager.running_progress(id))
8417 .flatten();
8418 match progress {
8419 Some(progress) => format!("{id}: {status:?} ({progress})"),
8420 None => format!("{id}: {status:?}"),
8421 }
8422 })
8423 .collect()
8424 };
8425 let still_running: Vec<&str> = statuses
8426 .iter()
8427 .filter(|(_, status)| *status == ShellStatus::Running)
8428 .map(|(id, _)| id.as_str())
8429 .collect();
8430 let summary = if timed_out {
8431 format!(
8432 "wait timed out after {}ms; still running: {}",
8433 timeout_ms,
8434 if still_running.is_empty() {
8435 "none".to_string()
8436 } else {
8437 still_running.join(", ")
8438 }
8439 )
8440 } else if wait_canceled || wait_detached {
8441 let action = if wait_canceled {
8442 "canceled"
8443 } else {
8444 "detached"
8445 };
8446 format!(
8447 "wait {action}; still running: {}",
8448 if still_running.is_empty() {
8449 "none".to_string()
8450 } else {
8451 still_running.join(", ")
8452 }
8453 )
8454 } else {
8455 format!(
8456 "{settled} of {} background command{} settled; remaining running: {}",
8457 statuses.len(),
8458 if statuses.len() == 1 { "" } else { "s" },
8459 if still_running.is_empty() {
8460 "none".to_string()
8461 } else {
8462 still_running.join(", ")
8463 }
8464 )
8465 };
8466 let content = format!("{summary}\n{}\n", lines.join("\n"));
8467 let mut metadata = serde_json::Map::new();
8468 metadata.insert(
8469 "statuses".to_string(),
8470 serde_json::Value::Object(
8471 statuses
8472 .iter()
8473 .map(|(id, status)| (id.clone(), serde_json::json!(format!("{status:?}"))))
8474 .collect::<serde_json::Map<_, _>>(),
8475 ),
8476 );
8477 metadata.insert("wait_timeout_ms".to_string(), json!(timeout_ms));
8478 metadata.insert("until".to_string(), json!(until));
8479 metadata.insert("timed_out".to_string(), json!(timed_out));
8480 if wait_canceled {
8481 metadata.insert("wait_canceled".to_string(), json!(true));
8482 }
8483 if wait_detached {
8484 metadata.insert("wait_detached".to_string(), json!(true));
8485 }
8486 Ok(ToolResult {
8487 content: content.trim().to_string(),
8488 success: true,
8489 metadata: Some(serde_json::Value::Object(metadata)),
8490 })
8491 }
8492
8493 async fn execute_interact(
8494 &self,
8495 input: &serde_json::Value,
8496 context: &ToolContext,
8497 ) -> Result<ToolResult, ToolError> {
8498 let task_id = required_task_id(input)?;
8499 let close_stdin = optional_bool(input, "close_stdin", false)?;
8500 let timeout_ms = optional_u64(input, "timeout_ms", 1_000)?;
8501 // Same strict-type contract as `run` (2026-08-04): a non-string here
8502 // was silently dropped, so an `interact` call reported success while
8503 // writing nothing to the child's stdin. Alias order also matches
8504 // `run` now — `stdin` first — so the same payload reaches the same
8505 // place whichever spelling the model uses.
8506 let interaction_input = match first_present_field(input, &["stdin", "input", "data"]) {
8507 None => "",
8508 Some((name, value)) => value
8509 .as_str()
8510 .ok_or_else(|| type_mismatch(name, value, "a string"))?,
8511 };
8512
8513 {
8514 let mut manager = context
8515 .shell_manager
8516 .lock()
8517 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8518 if !interaction_input.is_empty() || close_stdin {
8519 manager
8520 .write_stdin_for_session(
8521 &context.state_namespace,
8522 task_id,
8523 interaction_input,
8524 close_stdin,
8525 )
8526 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
8527 }
8528 }
8529
8530 let mut elapsed = 0u64;
8531 loop {
8532 if context
8533 .cancel_token
8534 .as_ref()
8535 .is_some_and(|token| token.is_cancelled())
8536 {
8537 let raw = {
8538 let mut manager = context
8539 .shell_manager
8540 .lock()
8541 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8542 manager
8543 .get_raw_output_delta_for_session(
8544 &context.state_namespace,
8545 task_id,
8546 false,
8547 0,
8548 )
8549 .map_err(|err| ToolError::execution_failed(err.to_string()))?
8550 };
8551 let (delta, persisted_artifact) = finalize_raw_shell_delta(raw, context);
8552 let mut result = build_shell_delta_tool_result(delta, context);
8553 if let Some(artifact) = persisted_artifact.as_ref() {
8554 attach_shell_artifact_to_tool_result(&mut result, artifact);
8555 }
8556 if let Some(metadata) = result.metadata.as_mut()
8557 && let Some(object) = metadata.as_object_mut()
8558 {
8559 object.insert("wait_canceled".to_string(), json!(true));
8560 }
8561 return Ok(result);
8562 }
8563
8564 let raw = {
8565 let mut manager = context
8566 .shell_manager
8567 .lock()
8568 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8569 manager
8570 .get_raw_output_delta_for_session(&context.state_namespace, task_id, false, 0)
8571 .map_err(|err| ToolError::execution_failed(err.to_string()))?
8572 };
8573
8574 if !raw.stdout.is_empty()
8575 || !raw.stderr.is_empty()
8576 || raw.status != ShellStatus::Running
8577 || elapsed >= timeout_ms
8578 {
8579 let (delta, persisted_artifact) = finalize_raw_shell_delta(raw, context);
8580 let mut result = build_shell_delta_tool_result(delta, context);
8581 if let Some(artifact) = persisted_artifact.as_ref() {
8582 attach_shell_artifact_to_tool_result(&mut result, artifact);
8583 }
8584 return Ok(result);
8585 }
8586
8587 tokio::time::sleep(Duration::from_millis(50)).await;
8588 elapsed = elapsed.saturating_add(50);
8589 }
8590 }
8591
8592 async fn execute_cancel(
8593 &self,
8594 input: &serde_json::Value,
8595 context: &ToolContext,
8596 ) -> Result<ToolResult, ToolError> {
8597 let cancel_all = optional_bool(input, "all", false)?;
8598 let mut manager = context
8599 .shell_manager
8600 .lock()
8601 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8602
8603 if cancel_all {
8604 let results = manager
8605 .kill_running_for_session(&context.state_namespace)
8606 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
8607 for result in &results {
8608 manager.mark_cancel_reported(result);
8609 }
8610 if results.is_empty() {
8611 return Ok(ToolResult {
8612 content: "No running background commands.".to_string(),
8613 success: true,
8614 metadata: Some(json!({
8615 "status": "Noop",
8616 "canceled": 0,
8617 "task_ids": [],
8618 })),
8619 });
8620 }
8621
8622 let task_ids = results
8623 .iter()
8624 .filter_map(|result| result.task_id.clone())
8625 .collect::<Vec<_>>();
8626 return Ok(ToolResult {
8627 content: format!(
8628 "Canceled {} background command{}: {}",
8629 task_ids.len(),
8630 if task_ids.len() == 1 { "" } else { "s" },
8631 task_ids.join(", ")
8632 ),
8633 success: true,
8634 metadata: Some(json!({
8635 "status": "Killed",
8636 "canceled": task_ids.len(),
8637 "task_ids": task_ids,
8638 })),
8639 });
8640 }
8641
8642 let task_id = required_task_id(input)?;
8643 let result = manager
8644 .kill_for_session(&context.state_namespace, task_id)
8645 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
8646 manager.mark_cancel_reported(&result);
8647 let task_id = result
8648 .task_id
8649 .clone()
8650 .unwrap_or_else(|| task_id.to_string());
8651 Ok(ToolResult {
8652 content: if result.status == ShellStatus::Killed {
8653 format!(
8654 "Canceled background command: {task_id}. {}",
8655 kill_outcome_note(&format!("{}{}", result.stdout, result.stderr))
8656 )
8657 } else {
8658 format!("{} Nothing was killed.", wait_timing_line(&result))
8659 },
8660 success: true,
8661 metadata: Some(json!({
8662 "status": format!("{:?}", result.status),
8663 "task_id": task_id,
8664 "exit_code": result.exit_code,
8665 "duration_ms": result.duration_ms,
8666 })),
8667 })
8668 }
8669 }
8670
8671 fn required_task_id(input: &serde_json::Value) -> Result<&str, ToolError> {
8672 // A present-but-non-string task_id is a type error, not a missing field:
8673 // "missing required field" sends the model's retry in the wrong
8674 // direction when it already supplied `task_id: 42` (2026-08-04 review).
8675 match first_present_field(input, &["task_id", "id"]) {
8676 None => Err(ToolError::missing_field("task_id")),
8677 Some((name, value)) => value
8678 .as_str()
8679 .ok_or_else(|| type_mismatch(name, value, "a string")),
8680 }
8681 }
8682
8683 /// First PRESENT value among aliased spellings of one field. `null` counts
8684 /// as absent, matching the `is_absent` rule the shared typed helpers use.
8685 fn first_present_field<'a>(
8686 input: &'a serde_json::Value,
8687 names: &[&'static str],
8688 ) -> Option<(&'static str, &'a serde_json::Value)> {
8689 names.iter().find_map(|name| match input.get(*name) {
8690 None | Some(serde_json::Value::Null) => None,
8691 Some(value) => Some((*name, value)),
8692 })
8693 }
8694
8695 /// Effective `action=wait` timeout in milliseconds. `timeout_ms` is
8696 /// canonical; `timeout_secs` (seconds) and bare `timeout` (milliseconds) are
8697 /// honored so a habit formed on other wait tools gets the duration it asked
8698 /// for instead of silently falling back to the 30 s default.
8699 fn wait_timeout_ms(input: &serde_json::Value) -> Result<u64, ToolError> {
8700 match first_present_field(input, &["timeout_ms", "timeout_secs", "timeout"]) {
8701 None => Ok(30_000),
8702 Some(("timeout_secs", value)) => {
8703 let secs = value
8704 .as_u64()
8705 .ok_or_else(|| type_mismatch("timeout_secs", value, "an integer"))?;
8706 Ok(secs.saturating_mul(1_000))
8707 }
8708 Some((name, value)) => value
8709 .as_u64()
8710 .ok_or_else(|| type_mismatch(name, value, "an integer")),
8711 }
8712 }
8713
8714 fn build_shell_delta_tool_result(delta: ShellDeltaResult, context: &ToolContext) -> ToolResult {
8715 let result = delta.result;
8716 let network_restricted_hint =
8717 shell_network_restricted_hint(context, &delta.command, &result).map(str::to_string);
8718 let sandbox_denied_hint = if network_restricted_hint.is_none() {
8719 shell_sandbox_denied_hint(context, &result)
8720 } else {
8721 None
8722 };
8723 let provenance_hint = macos_provenance_hint(&result);
8724 let python_dependency_hint = python_build_dependency_hint(&delta.command, &result);
8725 let stdout_summary = summarize_output(&result.stdout);
8726 let stderr_summary = summarize_output(&result.stderr);
8727 let summary = if !stderr_summary.is_empty() {
8728 stderr_summary.clone()
8729 } else {
8730 stdout_summary.clone()
8731 };
8732
8733 let mut output = if result.stdout.is_empty() && result.stderr.is_empty() {
8734 match result.status {
8735 ShellStatus::Running => "Background task running (no new output).".to_string(),
8736 ShellStatus::Completed => "(no new output)".to_string(),
8737 ShellStatus::Failed => {
8738 format!("Command failed ({})", exit_code_label(result.exit_code))
8739 }
8740 ShellStatus::TimedOut => "Command timed out (no new output).".to_string(),
8741 ShellStatus::Killed => "Command killed (no new output).".to_string(),
8742 }
8743 } else if result.stderr.is_empty() {
8744 result.stdout.clone()
8745 } else {
8746 format!("{}\n\nSTDERR:\n{}", result.stdout, result.stderr)
8747 };
8748 // The model cannot see metadata, so surface the real elapsed time in the
8749 // visible content. Without it every wait result looks identical whether
8750 // the task just started or has been running for minutes, which biases the
8751 // model into busy-polling short waits and misjudging long ones.
8752 output = format!("{}\n\n{output}", wait_timing_line(&result));
8753
8754 if let Some(hint) = network_restricted_hint.as_deref() {
8755 output = format!("{hint}\n\n{output}");
8756 }
8757 if let Some(hint) = sandbox_denied_hint.as_deref() {
8758 output = format!("{hint}\n\n{output}");
8759 }
8760 if let Some(hint) = provenance_hint {
8761 output = format!("{hint}\n\n{output}");
8762 }
8763 if let Some(hint) = python_dependency_hint {
8764 output = format!("{hint}\n\n{output}");
8765 }
8766
8767 let mut metadata = json!({
8768 "exit_code": result.exit_code,
8769 "exit_code_hex": exit_code_hex(result.exit_code),
8770 "status": format!("{:?}", result.status),
8771 "duration_ms": result.duration_ms,
8772 "sandboxed": result.sandboxed,
8773 "sandbox_type": result.sandbox_type,
8774 "sandbox_denied": result.sandbox_denied,
8775 "task_id": result.task_id,
8776 "stdout_len": result.stdout_len,
8777 "stderr_len": result.stderr_len,
8778 "stdout_truncated": result.stdout_truncated,
8779 "stderr_truncated": result.stderr_truncated,
8780 "stdout_omitted": result.stdout_omitted,
8781 "stderr_omitted": result.stderr_omitted,
8782 "stdout_total_len": delta.stdout_total_len,
8783 "stderr_total_len": delta.stderr_total_len,
8784 "summary": summary,
8785 "stdout_summary": stdout_summary,
8786 "stderr_summary": stderr_summary,
8787 "command": delta.command,
8788 "stream_delta": true,
8789 });
8790 attach_shell_owner_metadata(&mut metadata, context);
8791 attach_cargo_failure_summary(&mut metadata, &delta.command, &result);
8792 attach_python_build_dependency_hint(&mut metadata, python_dependency_hint);
8793
8794 let mut tool_result = ToolResult {
8795 content: output,
8796 success: matches!(result.status, ShellStatus::Completed | ShellStatus::Running),
8797 metadata: Some(metadata),
8798 };
8799 if let Some(hint) = network_restricted_hint
8800 && let Some(metadata) = tool_result.metadata.as_mut()
8801 && let Some(object) = metadata.as_object_mut()
8802 {
8803 object.insert("sandbox_network_restricted".to_string(), json!(true));
8804 object.insert("sandbox_network_denied_hint".to_string(), json!(hint));
8805 }
8806 if let Some(hint) = sandbox_denied_hint
8807 && let Some(metadata) = tool_result.metadata.as_mut()
8808 && let Some(object) = metadata.as_object_mut()
8809 {
8810 object.insert("sandbox_denied_hint".to_string(), json!(hint));
8811 }
8812 if provenance_hint.is_some()
8813 && let Some(metadata) = tool_result.metadata.as_mut()
8814 && let Some(object) = metadata.as_object_mut()
8815 {
8816 object.insert("macos_provenance_restricted".to_string(), json!(true));
8817 }
8818 tool_result
8819 }
8820
8821 /// Human-readable elapsed time for a shell task ("450 ms", "12.3 s", "2m5s").
8822 fn format_elapsed_ms(ms: u64) -> String {
8823 if ms < 1_000 {
8824 format!("{ms} ms")
8825 } else if ms < 60_000 {
8826 let secs = ms as f64 / 1_000.0;
8827 format!("{secs} s")
8828 } else {
8829 let total_secs = ms / 1_000;
8830 format!("{}m{}s", total_secs / 60, total_secs % 60)
8831 }
8832 }
8833
8834 /// One-line status + elapsed summary for wait/delta results, placed at the top
8835 /// of the visible content so the model can judge how long it actually waited.
8836 fn wait_timing_line(result: &ShellResult) -> String {
8837 let status_phrase = match result.status {
8838 ShellStatus::Running => "still running",
8839 ShellStatus::Completed => "completed",
8840 ShellStatus::Failed => "failed",
8841 ShellStatus::Killed => "killed",
8842 ShellStatus::TimedOut => "timed out",
8843 };
8844 let elapsed = format_elapsed_ms(result.duration_ms);
8845 match result.task_id.as_deref() {
8846 Some(task_id) => format!("Task {task_id} {status_phrase} after {elapsed}."),
8847 None => format!("Task {status_phrase} after {elapsed}."),
8848 }
8849 }
8850
8851 enum ShellWaitInterruption {
8852 Canceled,
8853 Detached,
8854 }
8855
8856 async fn wait_for_shell_delta_cancellable(
8857 context: &ToolContext,
8858 task_id: &str,
8859 timeout_ms: u64,
8860 ) -> Result<
8861 (
8862 (ShellDeltaResult, Option<PersistedShellArtifact>),
8863 Option<ShellWaitInterruption>,
8864 ),
8865 ToolError,
8866 > {
8867 let detach = {
8868 let mut manager = context
8869 .shell_manager
8870 .lock()
8871 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8872 manager
8873 .require_session_owner(task_id, &context.state_namespace)
8874 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
8875 manager.register_shell_wait(&context.state_namespace)
8876 };
8877 let timeout_ms = timeout_ms.clamp(1000, EXEC_SHELL_WAIT_MAX_TIMEOUT_MS);
8878 let deadline = Instant::now() + Duration::from_millis(timeout_ms);
8879 let mut stdout_accum = String::new();
8880 let mut stderr_accum = String::new();
8881 let mut stdout_delta_total = 0usize;
8882 let mut stderr_delta_total = 0usize;
8883 let mut persisted_artifact: Option<PersistedShellArtifact> = None;
8884
8885 let mut poll_tick_ms: u64 = FOREGROUND_POLL_INITIAL_MS;
8886 let mut last_raw = loop {
8887 let canceled = context
8888 .cancel_token
8889 .as_ref()
8890 .is_some_and(|token| token.is_cancelled());
8891 if canceled || detach.load(Ordering::Acquire) {
8892 let mut raw = {
8893 let mut manager = context
8894 .shell_manager
8895 .lock()
8896 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8897 manager
8898 .get_raw_output_delta_for_session(&context.state_namespace, task_id, false, 0)
8899 .map_err(|err| ToolError::execution_failed(err.to_string()))?
8900 };
8901 append_raw_shell_delta(
8902 &mut stdout_accum,
8903 &mut stderr_accum,
8904 &mut stdout_delta_total,
8905 &mut stderr_delta_total,
8906 &mut persisted_artifact,
8907 &mut raw,
8908 );
8909 raw.stdout = stdout_accum;
8910 raw.stderr = stderr_accum;
8911 raw.stdout_delta_len = stdout_delta_total;
8912 raw.stderr_delta_len = stderr_delta_total;
8913 raw.persisted_artifact = persisted_artifact;
8914 return Ok((
8915 finalize_raw_shell_delta(raw, context),
8916 Some(if canceled {
8917 ShellWaitInterruption::Canceled
8918 } else {
8919 ShellWaitInterruption::Detached
8920 }),
8921 ));
8922 }
8923
8924 let mut raw = {
8925 let mut manager = context
8926 .shell_manager
8927 .lock()
8928 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
8929 manager
8930 .get_raw_output_delta_for_session(&context.state_namespace, task_id, false, 0)
8931 .map_err(|err| ToolError::execution_failed(err.to_string()))?
8932 };
8933 append_raw_shell_delta(
8934 &mut stdout_accum,
8935 &mut stderr_accum,
8936 &mut stdout_delta_total,
8937 &mut stderr_delta_total,
8938 &mut persisted_artifact,
8939 &mut raw,
8940 );
8941
8942 if raw.status != ShellStatus::Running || Instant::now() >= deadline {
8943 break raw;
8944 }
8945
8946 tokio::time::sleep(Duration::from_millis(poll_tick_ms)).await;
8947 poll_tick_ms = (poll_tick_ms * 2).min(FOREGROUND_POLL_MAX_MS);
8948 };
8949
8950 last_raw.stdout = stdout_accum;
8951 last_raw.stderr = stderr_accum;
8952 last_raw.stdout_delta_len = stdout_delta_total;
8953 last_raw.stderr_delta_len = stderr_delta_total;
8954 last_raw.persisted_artifact = persisted_artifact;
8955 Ok((finalize_raw_shell_delta(last_raw, context), None))
8956 }
8957
8958 fn append_bounded_accum(accum: &mut String, chunk: &str) {
8959 if chunk.is_empty() {
8960 return;
8961 }
8962 accum.push_str(chunk);
8963 if accum.len() > RAW_STREAM_MAX_BYTES {
8964 let mut start = accum.len().saturating_sub(RAW_STREAM_MAX_BYTES);
8965 while start < accum.len() && !accum.is_char_boundary(start) {
8966 start += 1;
8967 }
8968 accum.drain(..start);
8969 }
8970 }
8971
8972 fn append_raw_shell_delta(
8973 stdout_accum: &mut String,
8974 stderr_accum: &mut String,
8975 stdout_delta_total: &mut usize,
8976 stderr_delta_total: &mut usize,
8977 persisted_artifact: &mut Option<PersistedShellArtifact>,
8978 raw: &mut RawShellDelta,
8979 ) {
8980 append_bounded_accum(stdout_accum, &raw.stdout);
8981 append_bounded_accum(stderr_accum, &raw.stderr);
8982 *stdout_delta_total = stdout_delta_total.saturating_add(raw.stdout_delta_len);
8983 *stderr_delta_total = stderr_delta_total.saturating_add(raw.stderr_delta_len);
8984 if let Some(artifact) = raw.persisted_artifact.take() {
8985 *persisted_artifact = Some(artifact);
8986 }
8987 }
8988
8989 fn finalize_raw_shell_delta(
8990 raw: RawShellDelta,
8991 context: &ToolContext,
8992 ) -> (ShellDeltaResult, Option<PersistedShellArtifact>) {
8993 let (stdout, stdout_meta) = truncate_with_meta(&raw.stdout);
8994 let (stderr, stderr_meta) = truncate_with_meta(&raw.stderr);
8995 let persisted_artifact = raw.persisted_artifact.or_else(|| {
8996 if stdout_meta.truncated || stderr_meta.truncated {
8997 let full_combined = combine_full_shell_streams(&raw.stdout, &raw.stderr);
8998 persist_shell_output_artifact(
8999 &context.state_namespace,
9000 None,
9001 &format!("shell-wait-{}-{}", raw.task_id, Uuid::new_v4().simple()),
9002 full_combined.as_bytes(),
9003 )
9004 .ok()
9005 .map(|mut artifact| {
9006 artifact.complete = false;
9007 artifact
9008 })
9009 } else {
9010 None
9011 }
9012 });
9013 let result = ShellResult {
9014 task_id: Some(raw.task_id),
9015 status: raw.status,
9016 exit_code: raw.exit_code,
9017 stdout,
9018 stderr,
9019 duration_ms: raw.duration_ms,
9020 stdout_len: stdout_meta.original_len.max(raw.stdout_delta_len),
9021 stderr_len: stderr_meta.original_len.max(raw.stderr_delta_len),
9022 stdout_omitted: stdout_meta
9023 .omitted
9024 .saturating_add(raw.stdout_delta_len.saturating_sub(raw.stdout.len())),
9025 stderr_omitted: stderr_meta
9026 .omitted
9027 .saturating_add(raw.stderr_delta_len.saturating_sub(raw.stderr.len())),
9028 stdout_truncated: stdout_meta.truncated || raw.stdout_delta_len > raw.stdout.len(),
9029 stderr_truncated: stderr_meta.truncated || raw.stderr_delta_len > raw.stderr.len(),
9030 sandboxed: raw.sandboxed,
9031 sandbox_type: raw.sandbox_type,
9032 sandbox_denied: raw.sandbox_denied,
9033 };
9034
9035 (
9036 ShellDeltaResult {
9037 command: raw.command,
9038 result,
9039 stdout_total_len: raw.stdout_total_len,
9040 stderr_total_len: raw.stderr_total_len,
9041 },
9042 persisted_artifact,
9043 )
9044 }
9045
9046 #[cfg(test)]
9047 #[path = "shell/tests/enforced_readonly.rs"]
9048 mod enforced_readonly_tests;
9049 #[cfg(test)]
9050 #[path = "shell/tests/git_config_hardening.rs"]
9051 mod git_config_hardening_tests;
9052 #[cfg(test)]
9053 mod tests;
9054
9055 pub fn foreground_command_requests_detach(command: &str) -> bool {
9056 let mut single_quoted = false;
9057 let mut double_quoted = false;
9058 let mut escaped = false;
9059 let chars = command.chars().collect::<Vec<_>>();
9060 for (index, ch) in chars.iter().copied().enumerate() {
9061 if escaped {
9062 escaped = false;
9063 continue;
9064 }
9065 if ch == '\\' && !single_quoted {
9066 escaped = true;
9067 continue;
9068 }
9069 if ch == '\'' && !double_quoted {
9070 single_quoted = !single_quoted;
9071 continue;
9072 }
9073 if ch == '"' && !single_quoted {
9074 double_quoted = !double_quoted;
9075 continue;
9076 }
9077 if ch != '&' || single_quoted || double_quoted {
9078 continue;
9079 }
9080 let previous = index.checked_sub(1).and_then(|i| chars.get(i)).copied();
9081 let next = chars.get(index + 1).copied();
9082 // `&&`, `&>`/`&>>`, and `>&` are chaining/redirection rather than a
9083 // detached child. Any other unquoted ampersand is a background
9084 // control operator and is unavailable in ACP.
9085 if previous != Some('&') && next != Some('&') && next != Some('>') && previous != Some('>')
9086 {
9087 return true;
9088 }
9089 }
9090
9091 shell_words::split(command).is_ok_and(|words| {
9092 words.iter().any(|word| {
9093 matches!(
9094 word.to_ascii_lowercase().as_str(),
9095 "nohup" | "disown" | "setsid" | "daemonize"
9096 )
9097 })
9098 })
9099 }
9100
9101 #[cfg(test)]
9102 mod working_dir_error_tests {
9103 use super::validate_shell_working_dir;
9104 use tempfile::tempdir;
9105
9106 #[test]
9107 fn working_dir_errors_name_bash_instead_of_exec_shell() {
9108 let tmp = tempdir().expect("tempdir");
9109 let missing = tmp.path().join("does-not-exist");
9110 let missing_err = validate_shell_working_dir(&missing, true)
9111 .expect_err("missing dir must fail")
9112 .to_string();
9113 assert!(missing_err.contains("`bash`"), "{missing_err}");
9114 assert!(missing_err.contains("`cwd`"), "{missing_err}");
9115 assert!(!missing_err.contains("exec_shell"), "{missing_err}");
9116
9117 let file = tmp.path().join("plain.txt");
9118 std::fs::write(&file, "x").expect("write");
9119 let not_dir_err = validate_shell_working_dir(&file, false)
9120 .expect_err("file path must fail")
9121 .to_string();
9122 assert!(not_dir_err.contains("`bash`"), "{not_dir_err}");
9123 assert!(not_dir_err.contains("`cwd`"), "{not_dir_err}");
9124 assert!(!not_dir_err.contains("exec_shell"), "{not_dir_err}");
9125 }
9126 }
9127
9127 lines RUST