|
| 1 | +using System.Diagnostics; |
| 2 | + |
| 3 | +namespace PowerShell.MCP; |
| 4 | + |
| 5 | +/// <summary> |
| 6 | +/// Truncates large command output to preserve AI context window budget. |
| 7 | +/// Saves the full output to a temp file so the AI can retrieve it via Read tool if needed. |
| 8 | +/// </summary> |
| 9 | +public static class OutputTruncationHelper |
| 10 | +{ |
| 11 | + internal const int TruncationThreshold = 15_000; |
| 12 | + internal const int PreviewHeadSize = 1000; |
| 13 | + internal const int PreviewTailSize = 1000; |
| 14 | + |
| 15 | + // The threshold must exceed the combined preview sizes; otherwise the head |
| 16 | + // and tail slices overlap, producing duplicated content in the preview. |
| 17 | + private static readonly bool _ = Validate(); |
| 18 | + private static bool Validate() |
| 19 | + { |
| 20 | + Debug.Assert( |
| 21 | + TruncationThreshold > PreviewHeadSize + PreviewTailSize, |
| 22 | + $"TruncationThreshold ({TruncationThreshold}) must be greater than " + |
| 23 | + $"PreviewHeadSize + PreviewTailSize ({PreviewHeadSize + PreviewTailSize}) " + |
| 24 | + "to avoid overlapping head/tail previews."); |
| 25 | + return true; |
| 26 | + } |
| 27 | + internal const string OutputDirectoryName = "PowerShell.MCP.Output"; |
| 28 | + internal const int MaxFileAgeMinutes = 120; |
| 29 | + internal const int NewlineScanLimit = 200; |
| 30 | + |
| 31 | + /// <summary> |
| 32 | + /// Returns the output unchanged if within threshold, otherwise saves the full content |
| 33 | + /// to a temp file and returns a head+tail preview with the file path. |
| 34 | + /// </summary> |
| 35 | + public static string TruncateIfNeeded(string output, string? outputDirectory = null) |
| 36 | + { |
| 37 | + if (output.Length <= TruncationThreshold) |
| 38 | + return output; |
| 39 | + |
| 40 | + // Compute newline-aligned head boundary |
| 41 | + var headEnd = FindHeadBoundary(output, PreviewHeadSize); |
| 42 | + var head = output[..headEnd]; |
| 43 | + |
| 44 | + // Compute newline-aligned tail boundary |
| 45 | + var tailStart = FindTailBoundary(output, PreviewTailSize); |
| 46 | + var tail = output[tailStart..]; |
| 47 | + |
| 48 | + var omitted = output.Length - head.Length - tail.Length; |
| 49 | + |
| 50 | + var filePath = SaveOutputToFile(output, outputDirectory); |
| 51 | + |
| 52 | + var sb = new System.Text.StringBuilder(); |
| 53 | + |
| 54 | + if (filePath != null) |
| 55 | + { |
| 56 | + sb.AppendLine($"Output too large ({output.Length} characters). Full output saved to: {filePath}"); |
| 57 | + sb.AppendLine($"Use invoke_expression('Show-TextFiles \"{filePath}\" -Contains \"search term\"') or -Pattern \"regex\" to search the output."); |
| 58 | + } |
| 59 | + else |
| 60 | + { |
| 61 | + // Disk save failed — still provide the preview without a file path |
| 62 | + sb.AppendLine($"Output too large ({output.Length} characters). Could not save full output to file."); |
| 63 | + } |
| 64 | + |
| 65 | + sb.AppendLine(); |
| 66 | + sb.AppendLine("--- Preview (first ~1000 chars) ---"); |
| 67 | + sb.AppendLine(head); |
| 68 | + sb.AppendLine($"--- truncated ({omitted} chars omitted) ---"); |
| 69 | + sb.AppendLine("--- Preview (last ~1000 chars) ---"); |
| 70 | + sb.Append(tail); |
| 71 | + |
| 72 | + return sb.ToString(); |
| 73 | + } |
| 74 | + |
| 75 | + /// <summary> |
| 76 | + /// Saves the full output to a timestamped temp file and triggers opportunistic cleanup. |
| 77 | + /// Returns the file path on success, null on failure. |
| 78 | + /// </summary> |
| 79 | + internal static string? SaveOutputToFile(string output, string? outputDirectory = null) |
| 80 | + { |
| 81 | + try |
| 82 | + { |
| 83 | + var directory = outputDirectory |
| 84 | + ?? Path.Combine(Path.GetTempPath(), OutputDirectoryName); |
| 85 | + |
| 86 | + Directory.CreateDirectory(directory); |
| 87 | + |
| 88 | + var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"); |
| 89 | + var random = Path.GetRandomFileName(); |
| 90 | + var fileName = $"pwsh_output_{timestamp}_{random}.txt"; |
| 91 | + var filePath = Path.Combine(directory, fileName); |
| 92 | + |
| 93 | + File.WriteAllText(filePath, output); |
| 94 | + |
| 95 | + // Opportunistic cleanup — never let it block or fail the save |
| 96 | + CleanupOldOutputFiles(directory); |
| 97 | + |
| 98 | + return filePath; |
| 99 | + } |
| 100 | + catch |
| 101 | + { |
| 102 | + return null; |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + /// <summary> |
| 107 | + /// Deletes pwsh_output_*.txt files older than <see cref="MaxFileAgeMinutes"/> minutes. |
| 108 | + /// Each deletion is individually guarded so a locked file does not prevent other cleanups. |
| 109 | + /// </summary> |
| 110 | + internal static void CleanupOldOutputFiles(string? directory = null) |
| 111 | + { |
| 112 | + try |
| 113 | + { |
| 114 | + var dir = directory |
| 115 | + ?? Path.Combine(Path.GetTempPath(), OutputDirectoryName); |
| 116 | + |
| 117 | + if (!Directory.Exists(dir)) |
| 118 | + return; |
| 119 | + |
| 120 | + var cutoff = DateTime.Now.AddMinutes(-MaxFileAgeMinutes); |
| 121 | + |
| 122 | + foreach (var file in Directory.EnumerateFiles(dir, "pwsh_output_*.txt")) |
| 123 | + { |
| 124 | + try |
| 125 | + { |
| 126 | + if (File.GetLastWriteTime(file) < cutoff) |
| 127 | + File.Delete(file); |
| 128 | + } |
| 129 | + catch (IOException) |
| 130 | + { |
| 131 | + // Another thread may be writing — safe to ignore |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + catch |
| 136 | + { |
| 137 | + // Directory enumeration itself failed — nothing to clean up |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + /// <summary> |
| 142 | + /// Finds a head cut position aligned to the nearest preceding newline within scan limit. |
| 143 | + /// </summary> |
| 144 | + private static int FindHeadBoundary(string output, int nominalSize) |
| 145 | + { |
| 146 | + if (nominalSize >= output.Length) |
| 147 | + return output.Length; |
| 148 | + |
| 149 | + // Search backward from nominalSize for a newline, up to NewlineScanLimit chars |
| 150 | + var searchStart = Math.Max(0, nominalSize - NewlineScanLimit); |
| 151 | + var lastNewline = output.LastIndexOf('\n', nominalSize - 1, nominalSize - searchStart); |
| 152 | + |
| 153 | + // Cut after the newline to keep complete lines in the head |
| 154 | + return lastNewline >= 0 ? lastNewline + 1 : nominalSize; |
| 155 | + } |
| 156 | + |
| 157 | + /// <summary> |
| 158 | + /// Finds a tail start position aligned to the nearest following newline within scan limit. |
| 159 | + /// </summary> |
| 160 | + private static int FindTailBoundary(string output, int nominalSize) |
| 161 | + { |
| 162 | + var nominalStart = output.Length - nominalSize; |
| 163 | + if (nominalStart <= 0) |
| 164 | + return 0; |
| 165 | + |
| 166 | + // Search forward from nominalStart for a newline, up to NewlineScanLimit chars |
| 167 | + var searchEnd = Math.Min(output.Length, nominalStart + NewlineScanLimit); |
| 168 | + var nextNewline = output.IndexOf('\n', nominalStart, searchEnd - nominalStart); |
| 169 | + |
| 170 | + // Start at the character after the newline to begin on a fresh line |
| 171 | + return nextNewline >= 0 ? nextNewline + 1 : nominalStart; |
| 172 | + } |
| 173 | +} |
0 commit comments