Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

8.5 KB
Raw Blame
import { existsSync, statSync } from 'fs';
import { homedir } from 'os';
import path from 'path';
import { parse, quote, type ParsedToken } from 'shell-quote';

const MAX_FILE_PATHS = 10;
const READ_COMMANDS = new Set(['cat', 'head', 'tail', 'less', 'more', 'bat', 'view', 'nl', 'tac']);
const FLAGS_WITH_VALUES_BY_COMMAND: Record<string, Set<string>> = {
  head: new Set(['-n', '-c', '--lines', '--bytes']),
  tail: new Set(['-n', '-c', '--lines', '--bytes']),
};
const NO_FLAGS_WITH_VALUES = new Set<string>();

function isOperatorToken(token: ParsedToken): token is { op: string } {
  return typeof token === 'object' && token !== null && 'op' in token;
}

function splitSegments(tokens: ParsedToken[]): string[][] {
  const segments: string[][] = [];
  let current: string[] = [];
  let outputTarget = false;

  for (const token of tokens) {
    if (outputTarget) {
      // shell-quote emits >| as two operator tokens.
      if (isOperatorToken(token) && token.op === '|') continue;
      outputTarget = false;
      if (typeof token === 'string') continue;
    }
    if (isOperatorToken(token)) {
      // Output redirections remove an output target from argv; they do not
      // end the command. Read operands can occur on either side of them.
      if (['>', '>>', '>&', '>|'].includes(token.op)) {
        outputTarget = true;
        continue;
      }
      if (current.length > 0) segments.push(current);
      current = [];
      continue;
    }
    if (typeof token === 'string') {
      current.push(token);
    }
  }

  if (current.length > 0) segments.push(current);
  return segments;
}

// Codex runs PowerShell on Windows, where a quoted '~/x' path still resolves
// to the home directory, so only POSIX shells keep a quoted or escaped tilde literal.
const QUOTED_TILDE_IS_LITERAL = process.platform !== 'win32';

// Expand before shell-quote removes quote/escape information. A quoted or
// escaped tilde, and every literal argv element, names cwd/~/... instead.
function expandShellHome(command: string, homeDirectory: string): string {
  let result = '';
  let quoting: "'" | '"' | undefined;
  let wordStart = true;
  for (let index = 0; index < command.length; index++) {
    const char = command[index];
    if (char === '\\' && quoting !== "'") {
      if (command[index + 1] === '\n') { index++; continue; }
      result += char + (command[++index] ?? '');
      wordStart = false;
      continue;
    }
    if (char === "'" || char === '"') {
      if (quoting === char) quoting = undefined;
      else if (quoting === undefined) quoting = char;
      result += char;
      wordStart = false;
      continue;
    }
    if (!quoting && wordStart && char === '~') {
      // Line continuations disappear before the shell identifies a tilde
      // prefix. Look at the next logical character without altering quoted text.
      let next = index + 1;
      while (command[next] === '\\' && command[next + 1] === '\n') next += 2;
      if (next === command.length || /[\s/|&;()<>]/.test(command[next])) {
        result += quote([homeDirectory]);
        wordStart = false;
        continue;
      }
    }
    result += char;
    wordStart = !quoting && /[\s|&;()<>]/.test(char);
  }
  return result;
}

function normalizeCommand(command: unknown, homeDirectory: string): string | null {
  if (typeof command === 'string') return QUOTED_TILDE_IS_LITERAL ? expandShellHome(command, homeDirectory) : command;
  if (Array.isArray(command)) {
    const parts = command.filter((part): part is string => typeof part === 'string');
    return parts.length > 0 ? quote(parts) : null;
  }
  return null;
}

function isFlagLike(value: string): boolean {
  return value.startsWith('-') || value.startsWith('+');
}

function flagsWithValues(command: string): Set<string> {
  return FLAGS_WITH_VALUES_BY_COMMAND[command] ?? NO_FLAGS_WITH_VALUES;
}

function dropFlagValue(flag: string, command: string): boolean {
  const valueFlags = flagsWithValues(command);
  if (valueFlags.has(flag)) return true;
  const eqIndex = flag.indexOf('=');
  return eqIndex > 0 && valueFlags.has(flag.slice(0, eqIndex));
}

// A shell expands `~/` before `cat` sees it, so a command that reads
// `~/notes/x.md` reads a file under the home directory. Resolving the literal
// token against cwd would point at `<cwd>/~/notes/x.md`, which never exists.
export function expandHomeDirectory(candidate: string, homeDirectory: string = homedir()): string {
  if (candidate === '~') return homeDirectory;
  if (candidate.startsWith('~/')) return path.join(homeDirectory, candidate.slice(2));
  return candidate;
}

function isExistingFile(candidate: string, cwd: string): boolean {
  const absolutePath = path.isAbsolute(candidate) ? candidate : path.resolve(cwd, candidate);
  try {
    if (!existsSync(absolutePath)) return false;
    return statSync(absolutePath).isFile();
  } catch {
    // [ANTI-PATTERN IGNORED]: this probes arbitrary tokens parsed from shell commands against the
    // filesystem, so stat failures (delete race after existsSync, EACCES, junk tokens) are expected
    // per-token noise; recovery is treating the candidate as not a file, same as existsSync failing.
    return false;
  }
}

function dedupeAndCap(paths: string[]): string[] {
  const seen = new Set<string>();
  const deduped: string[] = [];

  for (const filePath of paths) {
    if (seen.has(filePath)) continue;
    seen.add(filePath);
    deduped.push(filePath);
    if (deduped.length >= MAX_FILE_PATHS) break;
  }

  return deduped;
}

function extractFromBash(toolInput: unknown, cwd: string, homeDirectory: string): string[] {
  const command = normalizeCommand((toolInput as { command?: unknown } | undefined)?.command, homeDirectory);
  if (!command) return [];

  // `parse` throws on substitutions it cannot resolve — `${}` raises
  // "Bad substitution" on every shell-quote 1.x, including 1.10.x. This is a
  // best-effort enrichment that only adds `filePaths` for read commands, so an
  // unparseable command must yield no paths rather than propagate: the throw
  // escaped to the generic hook handler, which answers BLOCKING_ERROR and
  // discards the tool call entirely (#3688). Failing to enrich is invisible;
  // blocking the user's command is not.
  let tokens: ParsedToken[];
  try {
    tokens = parse(command, process.env);
  } catch {
    return [];
  }
  const paths: string[] = [];

  for (const segment of splitSegments(tokens)) {
    const argv0Index = segment.findIndex(token => token && !isFlagLike(token));
    if (argv0Index === -1) continue;

    const argv0 = path.basename(segment[argv0Index]);
    if (!READ_COMMANDS.has(argv0)) continue;

    let skipNext = false;
    let optionsEnded = false;
    for (const token of segment.slice(argv0Index + 1)) {
      if (skipNext) {
        skipNext = false;
        continue;
      }
      if (!optionsEnded && token === '--') {
        optionsEnded = true;
        continue;
      }
      // cat accepts +name as a filename; other readers can use + for positioning.
      if (!optionsEnded && (token.startsWith('-') || (argv0 !== 'cat' && token.startsWith('+')))) {
        skipNext = dropFlagValue(token, argv0) && !token.includes('=');
        continue;
      }
      // The POSIX scanner splices the home directory in as text, so normalize
      // it to the shape path.join gives (no doubled separator from HOME=/).
      const candidate = QUOTED_TILDE_IS_LITERAL
        ? (token.startsWith(homeDirectory) ? path.normalize(token) : token)
        : expandHomeDirectory(token, homeDirectory);
      if (isExistingFile(candidate, cwd)) {
        paths.push(candidate);
      }
    }
  }

  return dedupeAndCap(paths);
}

function extractFromMcp(toolName: string, toolInput: unknown, cwd: string, homeDirectory: string): string[] {
  if (!/^mcp__.+__(read|view|cat)(?:_file|_files)?$/.test(toolName)) return [];

  const input = (toolInput ?? {}) as { path?: unknown; paths?: unknown };
  const candidates: string[] = [];

  if (typeof input.path === 'string') candidates.push(input.path);
  if (Array.isArray(input.paths)) {
    for (const item of input.paths) {
      if (typeof item === 'string') candidates.push(item);
    }
  }

  return dedupeAndCap(candidates.map(candidate => expandHomeDirectory(candidate, homeDirectory)).filter(candidate => isExistingFile(candidate, cwd)));
}

export function extractFilePaths(toolName: string, toolInput: unknown, cwd: string, homeDirectory: string = homedir()): string[] {
  if (toolName === 'Bash') return extractFromBash(toolInput, cwd, homeDirectory);
  if (toolName.startsWith('mcp__')) return extractFromMcp(toolName, toolInput, cwd, homeDirectory);
  return [];
}