repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/llmiterate/parser.ts

Raw
File outline
import { BUILTIN_COMMENT_PREFIXES, DISABLE_MARKER, MARKER } from "./constants";

export interface MarkerPrompt {
  marker: typeof MARKER;
  file: string;
  startLine: number;
  endLine: number;
  prompt: string;
  key: string;
  promptHash: string;
}

const commentPrefixGroupCache = new Map<string, Map<string, string[]>>();

export function parseMarkerPrompts(file: string, text: string, commentPrefixes = BUILTIN_COMMENT_PREFIXES): MarkerPrompt[] {
  if (!text.includes("llmiterate")) return [];
  if (isLlmiterateDisabled(text, commentPrefixes)) return [];

  const prefixes = normalizeCommentPrefixes(commentPrefixes);
  const lines = normalizeLines(text);
  const prompts: MarkerPrompt[] = [];

  for (let i = 0; i < lines.length; i++) {
    const first = parsePromptLine(lines[i] ?? "", prefixes);
    if (!first) continue;

    const startLine = i + 1;
    const body = [first];
    let endLine = startLine;

    for (let j = i + 1; j < lines.length; j++) {
      const next = parsePromptLine(lines[j] ?? "", prefixes);
      if (!next) break;
      body.push(next);
      endLine = j + 1;
      i = j;
    }

    const prompt = body.join("\n").trim();
    if (prompt) prompts.push(makePrompt(file, startLine, endLine, prompt));
  }

  return prompts;
}

export function isLlmiterateDisabled(text: string, commentPrefixes = BUILTIN_COMMENT_PREFIXES): boolean {
  if (!text.includes(DISABLE_MARKER)) return false;
  const prefixes = normalizeCommentPrefixes(commentPrefixes);
  return normalizeLines(text).some((line) => {
    const stripped = stripCommentPrefix(line, prefixes);
    return stripped !== undefined && /^!llmiterate(?:\s|$)/.test(stripped);
  });
}

function parsePromptLine(line: string, prefixes: string[]): string | undefined {
  const stripped = stripCommentPrefix(line, prefixes);
  if (stripped === undefined || !stripped.startsWith(MARKER)) return undefined;
  const prompt = stripped.slice(MARKER.length).trim();
  return prompt || undefined;
}

function stripCommentPrefix(line: string, prefixes: string[]): string | undefined {
  const trimmed = line.trimStart();
  const candidates = commentPrefixGroups(prefixes).get(trimmed[0] ?? "");
  if (!candidates) return undefined;
  for (const prefix of candidates) {
    if (!startsWithCommentPrefix(trimmed, prefix)) continue;
    const suffix = commentSuffix(prefix);
    let body = trimmed.slice(prefix.length).trimStart();
    if (suffix && body.endsWith(suffix)) body = body.slice(0, -suffix.length).trimEnd();
    return body;
  }
  return undefined;
}

function startsWithCommentPrefix(line: string, prefix: string): boolean {
  if (!line.startsWith(prefix)) return false;
  if (/^[a-z]+$/i.test(prefix)) {
    const next = line[prefix.length];
    return next === undefined || /\s/.test(next);
  }
  return true;
}

function commentPrefixGroups(prefixes: string[]): Map<string, string[]> {
  const key = prefixes.join("\0");
  const cached = commentPrefixGroupCache.get(key);
  if (cached) return cached;
  const groups = new Map<string, string[]>();
  for (const prefix of prefixes) {
    const key = prefix[0] ?? "";
    const group = groups.get(key) ?? [];
    group.push(prefix);
    groups.set(key, group);
  }
  commentPrefixGroupCache.set(key, groups);
  return groups;
}

function commentSuffix(prefix: string): string | undefined {
  if (prefix === "<!--") return "-->";
  if (prefix === "/*" || prefix === "/**") return "*/";
  return undefined;
}

function normalizeLines(text: string): string[] {
  return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
}

function makePrompt(file: string, startLine: number, endLine: number, prompt: string): MarkerPrompt {
  const promptHash = hashString(prompt);
  return {
    marker: MARKER,
    file,
    startLine,
    endLine,
    prompt,
    promptHash,
    key: `${file}:${startLine}:${promptHash}`,
  };
}

function hashString(input: string): string {
  let hash = 0x811c9dc5;
  for (let i = 0; i < input.length; i++) {
    hash ^= input.charCodeAt(i);
    hash = Math.imul(hash, 0x01000193);
  }
  return (hash >>> 0).toString(16).padStart(8, "0");
}

function normalizeCommentPrefixes(prefixes: string[]): string[] {
  return [...new Set(prefixes.map((p) => p.trim()).filter(Boolean))].sort((a, b) => b.length - a.length);
}