Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Document Assistant v0.3.0 · generic

Archive SHA-256 084f2065dfcd8f2b9402eace1c9e0d03e5eee1dd7d78a54f1dbe7ca5bd99adb2 · 39.1 KB · built Dec 2, 2026

src/index.js

// Document Assistant — AgentRove native agent (MIT). Offline analysis of markdown / plain text you supply.
import { defineAgent, AgentError, runCli, runMcpStdio, handleMcpMessage, validateManifest } from "../sdk/index.js";
import { readFileSync } from "node:fs";
import { normalize, headings, outlineStrings, wordCount, titleOf, summarize, parseQuery, escapeRe, diffLines, wordChanges } from "./text.js";
import { buildReport } from "./report.js";

const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));
const MAX_LINE_OUT = 500;

function clip(s, n = MAX_LINE_OUT) {
  return s.length > n ? `${s.slice(0, n - 1)}…` : s;
}

function detectFormat(text, requested) {
  if (requested && requested !== "auto") return requested;
  // Numbered lines are deliberately not evidence of markdown: plain-text reports number their sections.
  return headings(text, "markdown").length || /(^|\n) {0,3}([-*+] \S|> |```|~~~)|\[[^\]]+\]\([^)]+\)|\*\*[^*\n]+\*\*/.test(text) ? "markdown" : "text";
}

function sectionLookup(hs) {
  return (line) => {
    let cur = null;
    for (const h of hs) { if (h.line <= line) cur = h; else break; }
    return cur ? cur.text : null;
  };
}

const handlers = {
  async outline(input) {
    const text = normalize(input.text);
    const format = detectFormat(text, input.format);
    const hs = headings(text, input.format ?? "auto");
    const notes = [];
    if (!text.trim()) notes.push("Document is empty");
    else if (!hs.length) notes.push(format === "markdown" ? "No markdown headings found" : "No heading-like lines found (plain-text headings are numbered or ALL-CAPS lines between blank lines)");
    return { title: titleOf(text, hs), format, outline: outlineStrings(hs), headings: hs, word_count: wordCount(text), notes };
  },

  async summarize(input) {
    const text = normalize(input.text);
    const hs = headings(text, input.format ?? "auto");
    const max = input.max_sentences ?? 5;
    const { sentences, count } = summarize(text, max);
    const notes = [];
    if (!text.trim()) notes.push("Document is empty");
    else if (!count) notes.push("No prose sentences found (only headings, code, tables or front matter)");
    else if (count <= max) notes.push(`Document has only ${count} sentence(s); all were kept`);
    return {
      title: titleOf(text, hs),
      outline: outlineStrings(hs),
      key_sentences: sentences.map((s) => s.text),
      word_count: wordCount(text),
      sentence_count: count,
      sentences,
      method: "extractive: TF-IDF-weighted sentence scores (IDF over paragraphs, heading terms x1.5, lead sentence x1.15), greedy selection with a redundancy penalty (terms already covered count x0.3, each sentence already taken from the same section x0.8), chosen sentences kept in original order",
      notes,
    };
  },

  async find(input) {
    const text = normalize(input.text);
    const terms = parseQuery(input.query);
    if (!terms.length) throw new AgentError("invalid_input", "query must contain at least one search term");
    if (terms.length > 20) throw new AgentError("invalid_input", "query may contain at most 20 terms");
    const caseSensitive = input.case_sensitive === true;
    const wholeWord = input.whole_word !== false;
    const mode = input.mode ?? "any";
    const ctxChars = input.context_chars ?? 60;
    const max = input.max_results ?? 50;
    const flags = `gu${caseSensitive ? "" : "i"}`;
    const res = terms.map((t) => new RegExp(wholeWord ? `(?<![\\p{L}\\p{N}_])${escapeRe(t)}(?![\\p{L}\\p{N}_])` : escapeRe(t), flags));
    const lines = text.split("\n");
    const section = sectionLookup(headings(text, "auto"));
    const matches = [];
    const perTerm = Object.fromEntries(terms.map((t) => [t, 0]));
    let total = 0;
    let linesMatched = 0;
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      const hits = [];
      res.forEach((re, ti) => { for (const m of line.matchAll(re)) hits.push({ term: terms[ti], index: m.index, match: m[0] }); });
      if (!hits.length) continue;
      if (mode === "all" && !terms.every((t) => hits.some((h) => h.term === t))) continue;
      linesMatched++;
      hits.sort((a, b) => a.index - b.index || a.term.localeCompare(b.term));
      for (const h of hits) {
        total++;
        perTerm[h.term]++;
        if (matches.length >= max) continue;
        let s = Math.max(0, h.index - ctxChars);
        let e = Math.min(line.length, h.index + h.match.length + ctxChars);
        // Snap the context window to whole words so snippets do not start or end mid-word.
        if (s > 0 && /\S/.test(line[s - 1])) { const ws = line.slice(s, h.index).search(/\s/); if (ws >= 0) s += ws + 1; }
        if (e < line.length && /\S/.test(line[e])) { const tail = line.slice(h.index + h.match.length, e); const ws = tail.search(/\s\S*$/); if (ws >= 0) e = h.index + h.match.length + ws; }
        const snippet = `${s > 0 ? "…" : ""}${line.slice(s, e).trim()}${e < line.length ? "…" : ""}`;
        const sec = section(i + 1);
        matches.push({ line: i + 1, column: h.index + 1, term: h.term, match: h.match, snippet, ...(sec !== null ? { section: sec } : {}) });
      }
    }
    return { query: input.query, terms, mode, total_matches: total, lines_matched: linesMatched, per_term: perTerm, truncated: total > matches.length, matches };
  },

  async compare(input) {
    const before = normalize(input.before);
    const after = normalize(input.after);
    const bl = before === "" ? [] : before.replace(/\n$/, "").split("\n");
    const al = after === "" ? [] : after.replace(/\n$/, "").split("\n");
    if (bl.length > 100000 || al.length > 100000) throw new AgentError("invalid_input", "each version may have at most 100000 lines");
    const ctx = input.context_lines ?? 1;
    const maxHunks = input.max_hunks ?? 200;
    const { ops, approximate } = diffLines(bl, al, { ignoreWhitespace: input.ignore_whitespace === true });
    const hunks = [];
    let added = 0;
    let removed = 0;
    let unchanged = 0;
    let cur = null;
    let ai = 0;
    let bj = 0;
    const close = () => {
      if (!cur) return;
      const bc = cur.removed.length;
      const ac = cur.added.length;
      // For edited lines (a removed line paired with the added line at the same position in the hunk),
      // list the words that changed, so a long paragraph edit shows "90-day" -> "60-day" directly.
      const word_changes = [];
      for (let k = 0; k < Math.min(bc, ac); k++) {
        const changes = wordChanges(cur.removed[k], cur.added[k]);
        if (changes?.length) word_changes.push({ before_line: cur.a + 1 + k, after_line: cur.b + 1 + k, changes: changes.map((c) => ({ removed: clip(c.removed, 200), added: clip(c.added, 200) })) });
      }
      hunks.push({
        kind: bc && ac ? "changed" : ac ? "added" : "removed",
        before_start: bc ? cur.a + 1 : cur.a,
        before_count: bc,
        after_start: ac ? cur.b + 1 : cur.b,
        after_count: ac,
        removed: cur.removed.map((l) => clip(l)),
        added: cur.added.map((l) => clip(l)),
        context_before: bl.slice(Math.max(0, cur.a - ctx), cur.a).map((l) => clip(l)),
        context_after: bl.slice(cur.a + bc, cur.a + bc + ctx).map((l) => clip(l)),
        ...(word_changes.length ? { word_changes } : {}),
      });
      cur = null;
    };
    for (const [t, i, j] of ops) {
      if (t === "eq") { close(); unchanged++; ai = i + 1; bj = j + 1; continue; }
      cur ??= { a: ai, b: bj, removed: [], added: [] };
      if (t === "del") { cur.removed.push(bl[i]); removed++; ai = i + 1; }
      else { cur.added.push(al[j]); added++; bj = j + 1; }
    }
    close();
    const key = (h) => `${h.level}|${h.text}`;
    const hb = headings(before, "auto").map(key);
    const ha = headings(after, "auto").map(key);
    const minus = (x, y) => { const pool = [...y]; return x.filter((k) => { const idx = pool.indexOf(k); if (idx >= 0) { pool.splice(idx, 1); return false; } return true; }); };
    const fmt = (k) => { const [lvl, ...rest] = k.split("|"); return `${"#".repeat(Number(lvl))} ${rest.join("|")}`; };
    const similarity = bl.length + al.length === 0 ? 1 : Math.round(((2 * unchanged) / (bl.length + al.length)) * 10000) / 10000;
    const wb = wordCount(before);
    const wa = wordCount(after);
    const identical = added === 0 && removed === 0;
    return {
      identical,
      summary: {
        lines_before: bl.length,
        lines_after: al.length,
        added,
        removed,
        unchanged,
        hunks: hunks.length,
        similarity,
        word_count_before: wb,
        word_count_after: wa,
        word_count_delta: wa - wb,
      },
      summary_text: identical
        ? `No line differences${input.ignore_whitespace ? " (whitespace ignored)" : ""}.`
        : `${hunks.length} changed region(s): ${added} line(s) added, ${removed} removed, ${unchanged} unchanged (similarity ${similarity}).`,
      headings_added: minus(ha, hb).map(fmt),
      headings_removed: minus(hb, ha).map(fmt),
      approximate,
      truncated: hunks.length > maxHunks,
      hunks: hunks.slice(0, maxHunks),
    };
  },

  // A cited Markdown report from other agents' output (0.3.0): see src/report.js.
  build_report(input, ctx) {
    return buildReport(input, ctx.now());
  },
};

const agent = defineAgent(manifest, handlers);
export default agent;
export { manifest, runCli, runMcpStdio, handleMcpMessage, validateManifest };

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).