1use crate::config::constants::tools;
17use anyhow::{Context, Result};
18use serde::{Deserialize, Serialize};
19use serde_json::{Value, json};
20use std::io::Read;
21use std::path::{Path, PathBuf};
22use std::sync::Arc;
23use tokio::fs;
24use tokio::sync::RwLock;
25use tracing::{debug, info};
26use vtcode_commons::formatting::truncate_byte_budget;
27use vtcode_commons::serde_helpers::json_to_string_pretty;
28use vtcode_commons::utils::calculate_sha256;
29
30const TOOL_OUTPUT_DIR: &str = ".vtcode/context/tool_outputs";
31const SPOOL_CREATE_ATTEMPTS: u32 = 16;
32
33mod preview;
37pub(crate) use preview::command_preview_content;
38use preview::condense_content;
39#[cfg(test)]
40use preview::{CONDENSE_HEAD_BYTES, CONDENSE_TAIL_BYTES, inspection_preview_content, verification_preview_content};
41
42pub const DEFAULT_SPOOL_THRESHOLD_BYTES: usize = 8_192;
43
44#[derive(Debug, Clone, Copy, Eq, PartialEq)]
46enum SpoolCleanupScope {
47 AgeOnly,
49 AgeAndCount,
51}
52
53impl SpoolCleanupScope {
54 fn enforces_count_budget(self) -> bool {
55 matches!(self, SpoolCleanupScope::AgeAndCount)
56 }
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct SpoolerConfig {
62 #[serde(default = "default_enabled")]
64 pub enabled: bool,
65
66 #[serde(default = "default_threshold")]
68 pub threshold_bytes: usize,
69
70 #[serde(default = "default_max_files")]
72 pub max_files: usize,
73
74 #[serde(default = "default_max_age_secs")]
76 pub max_age_secs: u64,
77
78 #[serde(default = "default_include_reference")]
80 pub include_file_reference: bool,
81}
82
83fn default_enabled() -> bool {
84 true
85}
86
87fn default_threshold() -> usize {
88 DEFAULT_SPOOL_THRESHOLD_BYTES
89}
90
91fn default_max_files() -> usize {
92 100
93}
94
95fn default_max_age_secs() -> u64 {
96 3600
97}
98
99fn default_include_reference() -> bool {
100 true
101}
102
103impl Default for SpoolerConfig {
104 fn default() -> Self {
105 Self {
106 enabled: true,
107 threshold_bytes: DEFAULT_SPOOL_THRESHOLD_BYTES,
108 max_files: 100,
109 max_age_secs: default_max_age_secs(),
110 include_file_reference: true,
111 }
112 }
113}
114
115#[derive(Debug, Clone)]
117pub struct SpoolResult {
118 pub file_path: PathBuf,
120 pub original_bytes: usize,
122 pub byte_count: u64,
124 pub sha256: String,
126 pub state: SpoolState,
128 pub content: String,
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum SpoolState {
134 Pending,
135 Completed,
136 Unknown,
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub(crate) struct SpoolIntegrity {
141 pub byte_count: u64,
142 pub line_count: u64,
143 pub sha256: String,
144}
145
146#[derive(Default)]
148pub(crate) struct SpoolLineCounter {
149 newline_count: u64,
150 last_byte: Option<u8>,
151}
152
153impl SpoolLineCounter {
154 pub(crate) fn append(&mut self, bytes: &[u8]) {
155 self.newline_count = self
156 .newline_count
157 .saturating_add(bytes.iter().filter(|byte| **byte == b'\n').count() as u64);
158 if let Some(byte) = bytes.last() {
159 self.last_byte = Some(*byte);
160 }
161 }
162
163 pub(crate) fn line_count(&self) -> u64 {
164 self.newline_count
165 .saturating_add(u64::from(self.last_byte.is_some_and(|byte| byte != b'\n')))
166 }
167}
168
169pub(crate) fn encode_digest_hex(digest: impl AsRef<[u8]>) -> String {
170 use std::fmt::Write as _;
171
172 let bytes = digest.as_ref();
173 let mut encoded = String::with_capacity(bytes.len() * 2);
174 for byte in bytes {
175 let _ = write!(encoded, "{byte:02x}");
176 }
177 encoded
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub struct SpooledOutputReference<'a> {
186 pub spool_path: &'a str,
187 pub preview: Option<&'a str>,
188 pub original_bytes: Option<u64>,
189 pub sha256: Option<&'a str>,
190 pub state: SpoolState,
191}
192
193impl<'a> SpooledOutputReference<'a> {
194 #[must_use]
195 pub fn recognizes_path(path: &Path) -> bool {
196 is_workspace_tool_output_path(path, true)
197 }
198
199 #[must_use]
204 pub fn recognizes_file_path(path: &Path) -> bool {
205 is_workspace_tool_output_path(path, false)
206 }
207
208 #[must_use]
209 pub fn from_value(value: &'a Value) -> Option<Self> {
210 let spool_path = value
211 .get("spool_path")
212 .and_then(Value::as_str)
213 .map(str::trim)
214 .filter(|path| !path.is_empty())?;
215 let preview = value
216 .get("preview")
217 .and_then(Value::as_str)
218 .filter(|preview| !preview.trim().is_empty());
219 let original_bytes = value.get("spooled_bytes").and_then(Value::as_u64);
220 let sha256 = value.get("spool_sha256").and_then(Value::as_str);
221 let state = match value.get("spool_state").and_then(Value::as_str) {
222 Some("pending") => SpoolState::Pending,
223 Some("completed") => SpoolState::Completed,
224 _ if value.get("spool_pending").and_then(Value::as_bool) == Some(true) => SpoolState::Pending,
225 _ if value.get("spool_complete").and_then(Value::as_bool) == Some(true) => SpoolState::Completed,
226 _ => SpoolState::Unknown,
227 };
228 Some(Self { spool_path, preview, original_bytes, sha256, state })
229 }
230
231 pub fn read_verified_completed(&self, workspace_root: &Path) -> Result<String> {
234 anyhow::ensure!(self.state == SpoolState::Completed, "spool is not marked completed");
235 let expected_bytes = self.original_bytes.context("completed spool is missing byte count")?;
236 let expected_sha256 = self.sha256.context("completed spool is missing SHA-256 digest")?;
237 anyhow::ensure!(
238 is_workspace_tool_output_path(Path::new(self.spool_path), false),
239 "unrecognized tool output spool path"
240 );
241
242 let canonical_root = vtcode_commons::canonicalize(workspace_root)
243 .with_context(|| format!("canonicalize workspace root {}", workspace_root.display()))?;
244 let path = Path::new(self.spool_path);
245 let relative = if path.is_absolute() {
246 path.strip_prefix(&canonical_root)
247 .context("absolute spool path is outside workspace")?
248 } else {
249 path
250 };
251 anyhow::ensure!(
252 is_workspace_tool_output_path(relative, false),
253 "spool path is outside the tool output directory"
254 );
255
256 let mut file = vtcode_commons::fs::bound_file::open_file_beneath(&canonical_root, relative)
257 .with_context(|| format!("open completed spool {}", relative.display()))?;
258 let metadata = file.metadata().context("read completed spool metadata")?;
259 anyhow::ensure!(metadata.is_file(), "completed spool is not a regular file");
260 anyhow::ensure!(metadata.len() == expected_bytes, "completed spool length mismatch");
261 let capacity = usize::try_from(expected_bytes).context("completed spool is too large to read")?;
262 let mut bytes = Vec::with_capacity(capacity);
263 file.read_to_end(&mut bytes).context("read completed spool")?;
264 anyhow::ensure!(bytes.len() as u64 == expected_bytes, "completed spool changed while reading");
265 anyhow::ensure!(calculate_sha256(&bytes) == expected_sha256, "completed spool digest mismatch");
266 String::from_utf8(bytes).context("completed spool is not valid UTF-8")
267 }
268
269 pub fn read_pending_bounded(&self, workspace_root: &Path, max_bytes: usize) -> Result<String> {
272 anyhow::ensure!(self.state == SpoolState::Pending, "spool is not marked pending");
273 anyhow::ensure!(max_bytes > 0, "pending spool read limit must be positive");
274 anyhow::ensure!(
275 is_workspace_tool_output_path(Path::new(self.spool_path), false),
276 "unrecognized tool output spool path"
277 );
278 let canonical_root = vtcode_commons::canonicalize(workspace_root)
279 .with_context(|| format!("canonicalize workspace root {}", workspace_root.display()))?;
280 let path = Path::new(self.spool_path);
281 let relative = if path.is_absolute() {
282 path.strip_prefix(&canonical_root)
283 .context("absolute spool path is outside workspace")?
284 } else {
285 path
286 };
287 let file = vtcode_commons::fs::bound_file::open_file_beneath(&canonical_root, relative)
288 .with_context(|| format!("open pending spool {}", relative.display()))?;
289 let mut bytes = Vec::with_capacity(max_bytes.min(64 * 1024));
290 file.take(max_bytes as u64)
291 .read_to_end(&mut bytes)
292 .context("read bounded pending spool")?;
293 Ok(decode_pending_snapshot(bytes))
294 }
295}
296
297fn decode_pending_snapshot(bytes: Vec<u8>) -> String {
304 match String::from_utf8(bytes) {
305 Ok(text) => text,
306 Err(error) => {
307 let utf8_error = error.utf8_error();
308 let bytes = error.into_bytes();
309 if utf8_error.error_len().is_none() {
310 String::from_utf8_lossy(&bytes[..utf8_error.valid_up_to()]).into_owned()
311 } else {
312 String::from_utf8_lossy(&bytes).into_owned()
313 }
314 }
315 }
316}
317
318fn is_workspace_tool_output_path(path: &Path, allow_directory: bool) -> bool {
319 let normalized = path.to_string_lossy().replace('\\', "/");
322 let absolute = normalized.starts_with('/')
323 || (normalized.as_bytes().get(1) == Some(&b':') && normalized.as_bytes().get(2) == Some(&b'/'));
324 let mut components = Vec::new();
325 for component in normalized.split('/') {
326 if component.is_empty() || component == "." {
327 continue;
328 }
329 if component == ".." {
330 return false;
331 }
332 components.push(component);
333 }
334
335 let needle = [".vtcode", "context", "tool_outputs"];
336 if let Some(directory_start) = components.len().checked_sub(needle.len() + 1)
337 && (absolute || directory_start == 0)
338 && components[directory_start..directory_start + needle.len()] == needle
339 {
340 return true;
341 }
342 if !allow_directory {
343 return false;
344 }
345 let Some(directory_start) = components.len().checked_sub(needle.len()) else {
346 return false;
347 };
348 (absolute || directory_start == 0) && components[directory_start..] == needle
349}
350
351pub(crate) fn ensure_spooled_reference_metadata(value: &mut Value) {
358 let Some(object) = value.as_object_mut() else {
359 return;
360 };
361 let Some(spool_path) = object
362 .get("spool_path")
363 .and_then(Value::as_str)
364 .filter(|path| !path.is_empty())
365 .map(str::to_owned)
366 else {
367 return;
368 };
369
370 let preview_source = ["preview", "output", "raw_output", "stdout", "content"]
371 .into_iter()
372 .find_map(|field| {
373 object
374 .get(field)
375 .and_then(Value::as_str)
376 .filter(|text| !text.is_empty())
377 .map(str::to_owned)
378 });
379 if object
380 .get("preview")
381 .and_then(Value::as_str)
382 .is_none_or(|preview| preview.is_empty())
383 && let Some(preview) = preview_source.as_deref()
384 {
385 object.insert("preview".to_string(), Value::String(preview.to_string()));
386 }
387
388 let spooled_bytes = object
389 .get("spooled_bytes")
390 .and_then(Value::as_u64)
391 .or_else(|| object.get("total_output_bytes").and_then(Value::as_u64))
392 .or_else(|| preview_source.as_ref().map(|preview| preview.len() as u64));
393 if let Some(bytes) = spooled_bytes {
394 object.entry("spooled_bytes").or_insert_with(|| json!(bytes));
395 let extent = object
396 .get("spool_line_count")
397 .and_then(Value::as_u64)
398 .map(|lines| format!(", {lines} lines; EOF at line {lines}"))
399 .unwrap_or_default();
400 object.entry("spool_note").or_insert_with(|| {
401 json!(format!(
402 "Large output ({bytes} bytes{extent}) spooled to `{spool_path}`. Do not re-inline the full file. Use exec_command with sed or rg to inspect only missing sections; avoid overlapping reads."
403 ))
404 });
405 } else {
406 object.entry("spool_note").or_insert_with(|| {
407 json!(format!(
408 "Large output spooled to `{spool_path}`. Use exec_command with cat, sed, or rg to inspect only the sections you need."
409 ))
410 });
411 }
412}
413
414const CLEANUP_EVERY_N_SPOOLS: u64 = 50;
416
417pub struct ToolOutputSpooler {
419 workspace_root: PathBuf,
421 output_dir: PathBuf,
423 config: SpoolerConfig,
425 spooled_files: Arc<RwLock<Vec<PathBuf>>>,
427 pinned_files: Arc<RwLock<std::collections::HashSet<PathBuf>>>,
431 spool_count: std::sync::atomic::AtomicU64,
433}
434
435impl ToolOutputSpooler {
436 pub fn new(workspace_root: &Path) -> Self {
438 Self::with_config(workspace_root, SpoolerConfig::default())
439 }
440
441 pub fn with_config(workspace_root: &Path, config: SpoolerConfig) -> Self {
443 let output_dir = workspace_root.join(TOOL_OUTPUT_DIR);
444
445 let max_files = config.max_files;
446 Self {
447 workspace_root: workspace_root.to_path_buf(),
448 output_dir,
449 config,
450 spooled_files: Arc::new(RwLock::new(Vec::with_capacity(max_files))),
451 pinned_files: Arc::new(RwLock::new(std::collections::HashSet::new())),
452 spool_count: std::sync::atomic::AtomicU64::new(0),
453 }
454 }
455
456 pub fn should_spool(&self, value: &Value) -> bool {
458 if !self.config.enabled {
459 return false;
460 }
461 if value.get("no_spool").and_then(|v| v.as_bool()).unwrap_or(false) {
462 return false;
463 }
464 self.estimate_size(value) > self.config.threshold_bytes
465 }
466
467 fn estimate_size(&self, value: &Value) -> usize {
468 if let Some(s) = value.get("raw_output").and_then(|v| v.as_str()) {
469 return s.len();
470 }
471 if let Some(s) = value.get("content").and_then(|v| v.as_str()) {
472 return s.len();
473 }
474 if let Some(s) = value.get("output").and_then(|v| v.as_str()) {
475 return s.len();
476 }
477 if let Some(s) = value.as_str() {
478 return s.len();
479 }
480 value.to_string().len()
481 }
482
483 pub async fn spool_output(&self, tool_name: &str, value: &Value, is_mcp: bool) -> Result<SpoolResult> {
485 let timestamp = std::time::SystemTime::now()
488 .duration_since(std::time::UNIX_EPOCH)
489 .unwrap_or_default()
490 .as_micros();
491
492 let content = if (tool_name == tools::READ_FILE || tool_name == tools::UNIFIED_FILE) && !is_mcp {
495 if let Some(raw_content) = value.get("content").and_then(|v| v.as_str()) {
496 raw_content.to_string()
497 } else if let Some(json_str) = value.as_str() {
498 if let Ok(parsed) = serde_json::from_str::<Value>(json_str) {
500 if let Some(raw_content) = parsed.get("content").and_then(|v| v.as_str()) {
501 debug!(
502 tool = tool_name,
503 "read_file spool: recovered content from double-serialized JSON string"
504 );
505 raw_content.to_string()
506 } else {
507 json_str.to_string()
508 }
509 } else {
510 json_str.to_string()
511 }
512 } else {
513 debug!(
515 tool = tool_name,
516 has_content = value.get("content").is_some(),
517 "read_file spool: could not extract content as string; falling back to JSON"
518 );
519 json_to_string_pretty(value)
520 }
521 } else if crate::tools::tool_intent::is_command_session_tool(tool_name) && !is_mcp {
522 if let Some(output_content) = value.get("raw_output").and_then(|v| v.as_str()) {
530 output_content.to_string()
531 } else if let Some(output_content) = value.get("output").and_then(|v| v.as_str()) {
532 output_content.to_string()
533 } else if let Some(json_str) = value.as_str() {
534 if let Ok(parsed) = serde_json::from_str::<Value>(json_str) {
537 if let Some(output_content) = parsed.get("raw_output").and_then(|v| v.as_str()) {
538 debug!(tool = tool_name, "PTY spool: recovered raw_output from double-serialized JSON string");
539 output_content.to_string()
540 } else if let Some(output_content) = parsed.get("output").and_then(|v| v.as_str()) {
541 debug!(tool = tool_name, "PTY spool: recovered output from double-serialized JSON string");
542 output_content.to_string()
543 } else {
544 if let Some(stdout) = parsed.get("stdout").and_then(|v| v.as_str()) {
546 stdout.to_string()
547 } else {
548 json_str.to_string()
549 }
550 }
551 } else {
552 json_str.to_string()
554 }
555 } else {
556 debug!(
558 tool = tool_name,
559 has_output = value.get("output").is_some(),
560 output_type = ?value.get("output").map(|v| match v {
561 serde_json::Value::Null => "null",
562 serde_json::Value::Bool(_) => "bool",
563 serde_json::Value::Number(_) => "number",
564 serde_json::Value::String(_) => "string",
565 serde_json::Value::Array(_) => "array",
566 serde_json::Value::Object(_) => "object",
567 }),
568 "PTY spool: could not extract output as string; falling back to JSON"
569 );
570 json_to_string_pretty(value)
571 }
572 } else if let Some(s) = value.as_str() {
573 s.to_string()
574 } else {
575 json_to_string_pretty(value)
576 };
577
578 let sanitized_content = vtcode_commons::sanitizer::redact_secrets(content);
580 let original_bytes = sanitized_content.len();
581 let byte_count = original_bytes as u64;
582 let sha256 = calculate_sha256(sanitized_content.as_bytes());
583 let canonical_root = vtcode_commons::canonicalize(&self.workspace_root)
584 .with_context(|| format!("canonicalize spool workspace {}", self.workspace_root.display()))?;
585 let sanitized_name = sanitize_tool_name(tool_name);
586 let bytes = sanitized_content.as_bytes().to_vec();
587 let (file_path, relative_path) = tokio::task::spawn_blocking(move || -> Result<(PathBuf, PathBuf)> {
588 let output_dir = Path::new(TOOL_OUTPUT_DIR);
589 vtcode_commons::fs::bound_file::ensure_directory_beneath(&canonical_root, output_dir)
590 .context("create bound tool output directory")?;
591 for collision in 0..SPOOL_CREATE_ATTEMPTS {
592 let suffix = if collision == 0 {
593 String::new()
594 } else {
595 format!("_{collision}")
596 };
597 let filename = format!("{sanitized_name}_{timestamp}{suffix}.txt");
598 let relative = output_dir.join(filename);
599 match vtcode_commons::fs::bound_file::write_file_beneath(&canonical_root, &relative, &bytes) {
600 Ok(()) => return Ok((canonical_root.join(&relative), relative)),
601 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
602 Err(error) => return Err(error).context("write immutable tool output spool"),
603 }
604 }
605 anyhow::bail!("tool output spool filename collisions exceeded {SPOOL_CREATE_ATTEMPTS} attempts")
606 })
607 .await
608 .context("join tool output spool writer")??;
609
610 {
611 let mut files = self.spooled_files.write().await;
612 files.push(file_path.clone());
613
614 if files.len() > self.config.max_files {
615 let pinned = self.pinned_files.read().await;
616 if let Some(evict_idx) = files.iter().position(|candidate| !pinned.contains(candidate)) {
617 let old_file = files.remove(evict_idx);
618 drop(pinned);
619 let _ = fs::remove_file(&old_file).await;
620 }
621 }
622 }
623
624 info!(
625 tool = tool_name,
626 bytes = original_bytes,
627 path = %relative_path.display(),
628 is_mcp = is_mcp,
629 "Spooled large tool output to file"
630 );
631
632 Ok(SpoolResult {
633 file_path: relative_path,
634 original_bytes,
635 byte_count,
636 sha256,
637 state: SpoolState::Completed,
638 content: sanitized_content,
639 })
640 }
641
642 pub async fn process_output(&self, tool_name: &str, value: Value, is_mcp: bool) -> Result<Value> {
648 self.process_output_with_options(tool_name, value, is_mcp, false, None).await
649 }
650
651 pub async fn process_output_with_force(
656 &self,
657 tool_name: &str,
658 value: Value,
659 is_mcp: bool,
660 force_spool: bool,
661 ) -> Result<Value> {
662 self.process_output_with_options(tool_name, value, is_mcp, force_spool, None)
663 .await
664 }
665
666 pub(crate) async fn process_output_with_preview_limit(
667 &self,
668 tool_name: &str,
669 value: Value,
670 is_mcp: bool,
671 force_spool: bool,
672 max_preview_bytes: usize,
673 ) -> Result<Value> {
674 self.process_output_with_options(tool_name, value, is_mcp, force_spool, Some(max_preview_bytes))
675 .await
676 }
677
678 async fn process_output_with_options(
679 &self,
680 tool_name: &str,
681 value: Value,
682 is_mcp: bool,
683 force_spool: bool,
684 max_preview_bytes: Option<usize>,
685 ) -> Result<Value> {
686 let no_spool = value.get("no_spool").and_then(|v| v.as_bool()).unwrap_or(false);
687 if no_spool {
688 return Ok(value);
689 }
690 if !self.config.enabled {
691 return Ok(value);
692 }
693 if !force_spool && !self.should_spool(&value) {
694 return Ok(value);
695 }
696
697 let spool_result = self.spool_output(tool_name, &value, is_mcp).await?;
698
699 let count = self.spool_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
702 if count.is_multiple_of(CLEANUP_EVERY_N_SPOOLS) {
703 if let Err(e) = self.cleanup_old_files().await {
704 debug!(error = %e, "Periodic spool cleanup failed");
705 }
706 }
707 let condensed = if crate::tools::tool_intent::is_command_session_tool(tool_name) {
708 command_preview_content(tool_name, &value, &spool_result.content, max_preview_bytes)
709 } else {
710 let condensed = condense_content(&spool_result.content);
711 max_preview_bytes
712 .map(|limit| truncate_byte_budget(&condensed, limit, ""))
713 .unwrap_or(condensed)
714 };
715 let spool_path = spool_result.file_path.to_string_lossy().to_string();
716
717 let mut response = match value {
718 Value::Object(map) => Value::Object(map),
719 _ => json!({}),
720 };
721 let is_pty_tool = crate::tools::tool_intent::is_command_session_tool(tool_name);
722 let use_output_field =
723 is_pty_tool || response.get("output").and_then(|v| v.as_str()).is_some_and(|s| !s.is_empty());
724 let source_path = if tool_name == tools::READ_FILE || tool_name == tools::UNIFIED_FILE {
725 response.get("path").and_then(|v| v.as_str()).map(String::from)
726 } else {
727 None
728 };
729 let stderr_preview = response
730 .get("stderr")
731 .and_then(|v| v.as_str())
732 .map(|s| truncate_byte_budget(s, 500, "... (truncated)"));
733
734 if let Some(obj) = response.as_object_mut() {
735 obj.remove("stdout");
736 obj.remove("follow_up_prompt");
737 obj.remove("spooled_to_file");
738 obj.remove("raw_output");
739 obj.insert("preview".to_string(), json!(condensed.clone()));
740
741 if use_output_field {
743 obj.insert("output".to_string(), json!(condensed));
744 } else {
745 obj.insert("content".to_string(), json!(condensed));
746 }
747
748 obj.insert("spool_path".to_string(), json!(spool_path));
749 obj.insert("spooled_bytes".to_string(), json!(spool_result.original_bytes));
750 obj.insert("spool_sha256".to_string(), json!(spool_result.sha256));
751 obj.insert("spool_state".to_string(), json!("completed"));
752 obj.insert("spool_complete".to_string(), json!(true));
753 let mut line_counter = SpoolLineCounter::default();
754 line_counter.append(spool_result.content.as_bytes());
755 obj.insert("spool_line_count".to_string(), json!(line_counter.line_count()));
756
757 if let Some(src) = source_path {
758 obj.entry("source_path".to_string()).or_insert_with(|| json!(src));
759 }
760 if let Some(stderr) = stderr_preview {
761 obj.insert("stderr_preview".to_string(), json!(stderr));
762 }
763 }
764
765 ensure_spooled_reference_metadata(&mut response);
766 Ok(response)
767 }
768
769 pub async fn pin_spool_files(&self, paths: &[PathBuf]) {
773 if paths.is_empty() {
774 return;
775 }
776 let mut pinned = self.pinned_files.write().await;
777 pinned.extend(paths.iter().cloned());
778 }
779
780 pub async fn unpin_spool_files(&self, paths: &[PathBuf]) {
783 if paths.is_empty() {
784 return;
785 }
786 let mut pinned = self.pinned_files.write().await;
787 for path in paths {
788 pinned.remove(path);
789 }
790 }
791
792 pub fn spool_paths_from_value(value: &Value) -> Option<String> {
795 SpooledOutputReference::from_value(value).map(|reference| reference.spool_path.to_string())
796 }
797
798 pub async fn cleanup_old_files(&self) -> Result<usize> {
805 self.cleanup_files(SpoolCleanupScope::AgeAndCount).await
806 }
807
808 pub async fn cleanup_expired_files(&self) -> Result<usize> {
818 self.cleanup_files(SpoolCleanupScope::AgeOnly).await
819 }
820
821 async fn cleanup_files(&self, scope: SpoolCleanupScope) -> Result<usize> {
822 if !fs::try_exists(&self.output_dir).await.unwrap_or(false) {
823 return Ok(0);
824 }
825
826 let now = std::time::SystemTime::now();
827 let mut removed = 0;
828
829 let mut paths_to_remove = Vec::new();
831 let mut survivors: Vec<(PathBuf, std::time::SystemTime)> = Vec::new();
833
834 let pinned = self.pinned_files.read().await;
835 let mut entries = fs::read_dir(&self.output_dir).await?;
836 while let Some(entry) = entries.next_entry().await? {
837 let path = entry.path();
838 if pinned.contains(&path) {
839 continue;
840 }
841 if let Ok(metadata) = entry.metadata().await
842 && let Ok(modified) = metadata.modified()
843 {
844 let age = now.duration_since(modified).unwrap_or_default();
845 if age.as_secs() > self.config.max_age_secs {
846 paths_to_remove.push(path);
847 } else {
848 survivors.push((path, modified));
849 }
850 }
851 }
852 drop(pinned);
853
854 if scope.enforces_count_budget() && survivors.len() > self.config.max_files {
857 survivors.sort_by_key(|(_, modified)| *modified);
858 let overflow = survivors.len() - self.config.max_files;
859 for (path, _) in survivors.into_iter().take(overflow) {
860 paths_to_remove.push(path);
861 }
862 }
863
864 for path in &paths_to_remove {
866 if fs::remove_file(path).await.is_ok() {
867 removed += 1;
868 debug!(path = %path.display(), "Removed old spooled file");
869 }
870 }
871
872 if removed > 0 {
874 let mut files = self.spooled_files.write().await;
875 files.retain(|p| !paths_to_remove.contains(p));
876 }
877
878 if removed > 0 {
879 info!(count = removed, "Cleaned up old spooled tool output files");
880 }
881
882 Ok(removed)
883 }
884
885 pub fn output_dir(&self) -> &Path {
887 &self.output_dir
888 }
889
890 pub fn config(&self) -> &SpoolerConfig {
892 &self.config
893 }
894
895 pub fn set_config(&mut self, config: SpoolerConfig) {
897 self.config = config;
898 }
899
900 pub async fn list_spooled_files(&self) -> Vec<PathBuf> {
902 self.spooled_files.read().await.clone()
903 }
904}
905
906fn sanitize_tool_name(name: &str) -> String {
908 name.chars()
909 .map(|c| if c.is_alphanumeric() || c == '_' { c } else { '_' })
910 .collect()
911}
912
913pub trait SpoolableOutput {
915 fn should_spool(&self, threshold_bytes: usize) -> bool;
917
918 fn byte_size(&self) -> usize;
920}
921
922impl SpoolableOutput for Value {
923 fn should_spool(&self, threshold_bytes: usize) -> bool {
924 self.to_string().len() > threshold_bytes
925 }
926
927 fn byte_size(&self) -> usize {
928 self.to_string().len()
929 }
930}
931
932#[cfg(test)]
933mod tests;