Dev.to Security 🔐 Cybersecurity 👁 0 📖 6 min read

Feeding command output back to an LLM: truncation, cleanup and secret masking

An agent runs npm test. The command prints 40,000 lines: progress bars, colour codes, a deprecation warning repeated 900 times, and, at the very end, the one assertion failure that matters. If you pass all of that back a

An agent runs npm test. The command prints 40,000 lines: progress bars, colour codes, a deprecation warning repeated 900 times, and, at the very end, the one assertion failure that matters. If you pass all of that back as the tool result, you pay for every token, push earlier context out of the window, and make the model hunt for the needle. If you cut it to the first 2,000 characters, the failure is gone.

Tool output needs preparing before a model sees it. This post walks through a small TypeScript helper that does four things in order: normalize terminal noise, mask secrets, collapse repeated lines, and truncate head and tail with a visible marker. It is independent of any model provider or sandbox.

What goes wrong with raw output

  • Length. Build and test output is routinely far larger than anything you want in a prompt.
  • Terminal noise. ANSI colour codes and carriage-return progress bars are meaningful to a terminal and noise to a model. A progress bar that redraws itself 100 times becomes 100 lines.
  • Repetition. The same warning per file, the same retry message per attempt.
  • Secrets. Debugging commands such as env, verbose HTTP clients and stack traces with connection strings can put credentials in output. Once it is in the prompt, it can end up in logs, in the model provider's systems, or in the agent's next commit message.
  • Silent truncation. If you cut output without saying so, the model may conclude a command printed nothing after a point, and reason from a false picture.

The helper

const SECRET_PATTERNS: RegExp[] = [
  /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, // AWS access key IDs
  /\bgh[pousr]_[A-Za-z0-9]{36,}\b/g, // GitHub tokens
  /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
];

export function maskSecrets(text: string, knownValues: string[] = []): string {
  let out = text;
  for (const value of knownValues) {
    if (value.length >= 8) out = out.split(value).join('[redacted]');
  }
  for (const pattern of SECRET_PATTERNS) out = out.replace(pattern, '[redacted]');
  return out;
}

// eslint-disable-next-line no-control-regex
const ANSI = /\x1b\[[0-9;?]*[ -\/]*[@-~]/g;

export function normalize(text: string): string {
  return text
    .replace(ANSI, '')
    .replace(/\r\n/g, '\n')
    .split('\n')
    .map((line) => line.replace(/^[^\n]*\r/, '')) // keep what a terminal would show after carriage returns
    .join('\n');
}

export function collapseRepeats(text: string): string {
  const lines = text.split('\n');
  const out: string[] = [];
  let i = 0;
  while (i < lines.length) {
    let j = i + 1;
    while (j < lines.length && lines[j] === lines[i]) j++;
    out.push(lines[i]);
    if (j - i > 2) out.push(`[previous line repeated ${j - i - 1} more times]`);
    else if (j - i === 2) out.push(lines[i]);
    i = j;
  }
  return out.join('\n');
}

export function headTail(text: string, maxChars: number, headShare = 0.3): string {
  if (text.length <= maxChars) return text;
  const head = Math.floor(maxChars * headShare);
  const tail = maxChars - head;
  const cut = text.length - head - tail;
  // Snap both cuts to line boundaries so no line is half shown.
  const headEnd = text.lastIndexOf('\n', head) > 0 ? text.lastIndexOf('\n', head) : head;
  const tailStartRaw = text.length - tail;
  const nl = text.indexOf('\n', tailStartRaw);
  const tailStart = nl >= 0 && nl < text.length - 1 ? nl + 1 : tailStartRaw;
  return `${text.slice(0, headEnd)}\n[... ${cut} characters omitted ...]\n${text.slice(tailStart)}`;
}

export interface ToolResultForModel {
  exitCode: number;
  timedOut: boolean;
  stdout: string;
  stderr: string;
  truncated: boolean;
}

export function prepareForModel(
  run: { exitCode: number; timedOut: boolean; stdout: string; stderr: string },
  opts: { maxStdout?: number; maxStderr?: number; secrets?: string[] } = {},
): ToolResultForModel {
  const maxStdout = opts.maxStdout ?? 8000;
  const maxStderr = opts.maxStderr ?? 4000;
  const clean = (s: string) => collapseRepeats(maskSecrets(normalize(s), opts.secrets));
  const stdout = clean(run.stdout);
  const stderr = clean(run.stderr);
  // Errors usually sit at the end, so stderr keeps more tail than head.
  const outCut = headTail(stdout, maxStdout);
  const errCut = headTail(stderr, maxStderr, 0.2);
  return {
    exitCode: run.exitCode,
    timedOut: run.timedOut,
    stdout: outCut,
    stderr: errCut,
    truncated: outCut !== stdout || errCut !== stderr,
  };
}

The order matters

Normalize first. Stripping ANSI escape codes before anything else means the later steps see plain text. A colour code in the middle of a token would otherwise break both secret matching and repeat detection. Carriage returns are resolved the way a terminal would show them, so a progress bar that went from 10% to 100% leaves only the final state.

Mask second. Secret masking runs on the full, clean output before anything is cut. Truncation can split a secret across the omitted section; masking first makes that irrelevant. Two kinds of masking are combined:

  • Known values. Pass the actual secret values the run had access to, such as the values you put in its environment, and every exact occurrence is replaced. This is the reliable part. Values shorter than eight characters are skipped to avoid replacing common substrings.
  • Patterns. A few well-known formats are matched by regular expression. Patterns catch credentials you did not know were there, but no pattern list is complete, so treat it as a backstop, not a guarantee.

Collapse third. Runs of identical lines become one line plus a count. This alone often shrinks noisy logs dramatically while keeping the information that a warning repeated.

Truncate last, from both ends. Command output has two interesting regions: the start, which shows what ran and how it was configured, and the end, which usually holds the result or the error. headTail keeps 30% of the budget from the start and 70% from the end, snaps both cuts to line boundaries, and inserts a marker saying how many characters were omitted. For stderr, the split shifts further toward the tail, because tracebacks and compiler errors end with the line that matters.

Telling the model what happened

The result includes a truncated flag alongside the exit code and the timeout flag. Put it in the tool result and mention it in your system prompt: if output was truncated and the model needs the middle, it should run a narrower command, such as grep for the failing test name or tail -n 200 on a log file, rather than assume.

That one instruction changes agent behavior noticeably. Instead of rerunning the whole suite, a well-prompted model narrows down.

Choosing budgets

The defaults here are 8,000 characters of stdout and 4,000 of stderr. They are a starting point, not a recommendation for every model. Consider:

  • Your context window and the rest of the prompt. A long-running agent accumulates tool results; each one should be small enough that ten of them still fit.
  • The command. A cat of a source file the model asked to read deserves a bigger budget than a test run. Let the tool call specify a budget within a hard cap.
  • Cost. Every character you pass is billed by the model provider on every turn it stays in context.

Other things worth doing

  • Write the full output somewhere. Keep the untruncated output as a file the agent can read in pieces, for example in the sandbox's workspace, so truncation never loses information permanently.
  • Treat output as untrusted input. Command output can contain text written by anyone: a dependency's README, a web page, a test fixture. That text can carry prompt injection. Masking and truncation do not change that; see from prompt injection to code execution.
  • Do not rely on the model to ignore secrets. Masking has to happen in your code, before the prompt is built.

Where Sandscale fits

When you run commands in a Sandscale sandbox, run returns exitCode, stdout, stderr, timedOut and oomKilled, which map directly onto the helper's input. Separately, on every plan, DLP scans prompts and MCP tool calls for credentials and stops a call that contains one. That is a second line of defence for the masking step, not a replacement for it: it does not scan files or output inside the sandbox, and catching a secret in your own code first means the agent keeps working instead of being blocked.

Originally published on the Sandscale blog.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.