@adeu/mcp-server
Version:
[](https://github.com/dealfluence/adeu) [](https://modelcontextprotocol.io/) [ and comment (Com:) ids \u2014 ids shift between document states.";
function split_projection(text) {
const [body, appendix] = split_structural_appendix(text);
return [appendix ? body.replace(/\n\n---$/, "") : body, appendix];
}
function handleServerCliArgs(argv, packageVersion2) {
if (argv.includes("--version") || argv.includes("-v")) {
return `adeu-mcp-server ${packageVersion2}`;
}
if (argv.includes("--help") || argv.includes("-h")) {
return [
"Usage: adeu-mcp-server [options]",
"",
"Adeu MCP server (stdio transport, zero-dependency Node engine).",
"Started by MCP hosts such as Claude Desktop; it reads JSON-RPC on stdin.",
"",
"Options:",
" -h, --help Show this help and exit",
" -v, --version Print the server version and exit",
"",
"Docs: https://github.com/dealfluence/adeu"
].join("\n");
}
return null;
}
// src/ledger.ts
import { resolve, basename } from "path";
import { statSync } from "fs";
import {
offset_to_page,
paginate,
parse_page_arg,
collectFields,
readDocumentProtection,
renderLedger,
bannerForDocument
} from "@adeu/core";
var BUBBLE_RE = /\{>>([\s\S]*?)<<\}/g;
var WRAPPER_RE = /(\{\+\+|\{--|\{==)([\s\S]*?)(?:\+\+\}|--\}|==\})/g;
var TAG_RE = /\[(Chg|Com):([\p{L}\p{N}_]+)(?:\s+(insert|delete|format))?\]/gu;
var PAIR_RE = /\(pairs\s+(?:with\s+)?((?:Chg:[\p{L}\p{N}_]+(?:,\s*)?)+)\)/u;
var CHG_ID_RE = /Chg:([\p{L}\p{N}_]+)/gu;
var REPLY_RE = /\(reply\s+to\s+(Com:[\p{L}\p{N}_]+|[\p{L}\p{N}_]+)\)/u;
var AUTHOR_NOISE_RE = /\s*\((?:pairs(?:\s+with)?|reply\s+to)\s+.*?\)/g;
var COM_HEADER_DATED_RE = /^\s*([\s\S]*?)\s*@\s*(\p{Nd}{4}\S*):(?=\s|$)\s*([\s\S]*)$/u;
var COM_HEADER_PLAIN_RE = /^\s*(?:([\s\S]*?):(?=\s|$)\s*|:\s*)([\s\S]*)$/;
var SNIPPET_TAGS = {
del: ["{--", "--}"],
ins: ["{++", "++}"],
fmt: ["{==", "==}"]
};
var LEDGER_PAGE_SIZE = 300;
var SNIPPET_LOOKBACK = 1e5;
var collapse = (s) => s.replace(/\s+/g, " ").trim();
var isDigits = (s) => /^\p{Nd}+$/u.test(s);
var stripPrefix = (s, prefix) => s.startsWith(prefix) ? s.slice(prefix.length) : s;
var ND_RE = /\p{Nd}/u;
function ascii_digits(s) {
return s.replace(/\p{Nd}/gu, (d) => {
const cp = d.codePointAt(0);
let zero = cp;
while (zero > 0 && ND_RE.test(String.fromCodePoint(zero - 1))) zero--;
return String((cp - zero) % 10);
});
}
function _parse_com_header(slice_text) {
const m1 = COM_HEADER_DATED_RE.exec(slice_text);
if (m1) {
const body = m1[3];
return [m1[1].trim(), body, slice_text.length - body.length];
}
const m2 = COM_HEADER_PLAIN_RE.exec(slice_text);
if (m2) {
const raw_author = m2[1];
const body = m2[2];
return [raw_author ? raw_author.trim() : "", body, slice_text.length - body.length];
}
return ["", slice_text.trim(), -1];
}
function addPair(pair_map, from, to) {
const partners = pair_map.get(from);
if (!partners) {
pair_map.set(from, [to]);
} else if (!partners.includes(to)) {
partners.push(to);
}
}
var BANNER_MEMO = /* @__PURE__ */ new Map();
var BANNER_MEMO_MAX = 32;
async function banner_for_path(path, hint, load) {
let key;
try {
const st = statSync(path);
key = `${resolve(path)}|${st.mtimeMs}|${st.size}`;
} catch {
return null;
}
if (BANNER_MEMO.has(key)) {
const cached = BANNER_MEMO.get(key);
return cached && hint ? `${cached}${hint}` : cached;
}
let banner = null;
try {
banner = bannerForDocument(await load(path));
} catch {
banner = null;
}
BANNER_MEMO.set(key, banner);
if (BANNER_MEMO.size > BANNER_MEMO_MAX) {
BANNER_MEMO.delete(BANNER_MEMO.keys().next().value);
}
return banner && hint ? `${banner}${hint}` : banner;
}
function fields_discovery_hint() {
return ' \xB7 read mode="fields" for the field ledger';
}
function build_fields_response(doc, text, file_path, opts = {}) {
const { offset = 0, bundle = void 0, no_chrome = false } = opts;
const body = bundle ? bundle.body : split_projection(text)[0];
const pag_res = bundle ? bundle.pagination : paginate(body, "");
const entries = collectFields(doc, body, pag_res.body_page_offsets);
const protection = readDocumentProtection(doc);
const ledger = renderLedger(
basename(file_path) || file_path,
entries,
protection,
offset
);
const llm_content = no_chrome ? ledger : `> **File Path:** \`${file_path}\`
${ledger}`;
return {
content: [{ type: "text", text: llm_content }],
structuredContent: {
markdown: ledger,
file_path: resolve(file_path),
title: basename(file_path)
}
};
}
function build_changes_response(text, file_path, opts = {}) {
const {
comments_data = null,
author_filter = null,
page = null,
bundle,
existing_change_ids = null,
no_chrome = false
} = opts;
let offset = opts.offset ?? 0;
if (offset < 0) offset = 0;
const comment_data_for = (key) => comments_data && Object.hasOwn(comments_data, key) ? comments_data[key] : null;
const body = bundle ? bundle.body : split_projection(text)[0];
const pag_res = bundle ? bundle.pagination : paginate(body, "");
const page_offsets = pag_res.body_page_offsets;
const total_pages = pag_res.total_pages;
const existing_ids = existing_change_ids == null ? null : new Set(existing_change_ids);
const isLiveId = (cid) => existing_ids !== null && (existing_ids.has(cid) || existing_ids.has(`Chg:${cid}`));
const chg_entries = /* @__PURE__ */ new Map();
const com_entries = /* @__PURE__ */ new Map();
const pair_map = /* @__PURE__ */ new Map();
for (const m of body.matchAll(BUBBLE_RE)) {
const b_start = m.index;
const p_num = offset_to_page(b_start, page_offsets);
const bubble_raw = m[1].trim();
const pre = body.slice(Math.max(0, b_start - SNIPPET_LOOKBACK), b_start);
const wrappers = [...pre.matchAll(WRAPPER_RE)];
const all_ins_snips = wrappers.filter((w) => w[1] === "{++").map((w) => w[2]);
const all_del_snips = wrappers.filter((w) => w[1] === "{--").map((w) => w[2]);
const all_fmt_snips = wrappers.filter((w) => w[1] === "{==").map((w) => w[2]);
const tag_matches = [...bubble_raw.matchAll(TAG_RE)];
if (tag_matches.length === 0) continue;
let first_com_delim_pos = Number.POSITIVE_INFINITY;
for (const tm of tag_matches) {
if (tm[1] === "Com") {
const tm_end = tm.index + tm[0].length;
const [, , d_off] = _parse_com_header(bubble_raw.slice(tm_end));
if (d_off !== -1) {
first_com_delim_pos = tm_end + d_off;
break;
}
}
}
const header_tokens = [];
for (const tm of tag_matches) {
if (tm[1] === "Com") {
header_tokens.push(tm);
} else if (tm[1] === "Chg") {
if (tm.index <= first_com_delim_pos) {
header_tokens.push(tm);
} else {
const line_start = tm.index === 0 ? 0 : bubble_raw.lastIndexOf("\n", tm.index - 1) + 1;
if (!bubble_raw.slice(line_start, tm.index).trim()) {
header_tokens.push(tm);
}
}
}
}
if (header_tokens.length === 0) continue;
const parsed_chg_items = [];
const parsed_com_items = [];
for (let i = 0; i < header_tokens.length; i++) {
const tm = header_tokens[i];
const kind = tm[1];
const cid = tm[2];
const next_start = i + 1 < header_tokens.length ? header_tokens[i + 1].index : bubble_raw.length;
const token_slice = bubble_raw.slice(tm.index + tm[0].length, next_start);
if (kind === "Chg") {
parsed_chg_items.push({ cid, raw_type: tm[3], rest: token_slice.trim(), change_type: "" });
} else if (kind === "Com") {
const [c_author, c_body] = _parse_com_header(token_slice);
parsed_com_items.push({ cid, parsed_author: c_author, body_text: c_body.trim() });
}
}
let shared_chg_rest = "";
for (let i = parsed_chg_items.length - 1; i >= 0; i--) {
if (parsed_chg_items[i].rest) {
shared_chg_rest = parsed_chg_items[i].rest;
break;
}
}
for (const item of parsed_chg_items) {
if (!item.rest) item.rest = shared_chg_rest;
if (item.raw_type === "delete") item.change_type = "del";
else if (item.raw_type === "insert") item.change_type = "ins";
else if (item.raw_type === "format") item.change_type = "fmt";
else item.change_type = all_del_snips.length ? "del" : all_fmt_snips.length ? "fmt" : "ins";
}
const N_del = parsed_chg_items.filter((it) => it.change_type === "del").length;
const N_ins = parsed_chg_items.filter((it) => it.change_type === "ins").length;
const N_fmt = parsed_chg_items.filter((it) => it.change_type === "fmt").length;
const bubble_del_snips = N_del > 0 && all_del_snips.length >= N_del ? all_del_snips.slice(-N_del) : all_del_snips;
const bubble_ins_snips = N_ins > 0 && all_ins_snips.length >= N_ins ? all_ins_snips.slice(-N_ins) : all_ins_snips;
const bubble_fmt_snips = N_fmt > 0 && all_fmt_snips.length >= N_fmt ? all_fmt_snips.slice(-N_fmt) : all_fmt_snips;
let del_idx = 0;
let ins_idx = 0;
let fmt_idx = 0;
for (const item of parsed_chg_items) {
const cid = item.cid;
const change_type = item.change_type;
const rest = item.rest;
const pick = (snips, idx) => idx < snips.length ? snips[idx] : snips.length ? snips[snips.length - 1] : "";
let raw_snip = "";
if (change_type === "del") raw_snip = pick(bubble_del_snips, del_idx++);
else if (change_type === "ins") raw_snip = pick(bubble_ins_snips, ins_idx++);
else if (change_type === "fmt") raw_snip = pick(bubble_fmt_snips, fmt_idx++);
if (!raw_snip) {
const [open_tag, close_tag] = SNIPPET_TAGS[change_type] ?? SNIPPET_TAGS.del;
const tag_open = body.lastIndexOf(open_tag, b_start - open_tag.length);
if (tag_open !== -1) {
let tag_close = body.indexOf(close_tag, tag_open);
if (tag_close !== -1 && tag_close + close_tag.length > b_start) tag_close = -1;
raw_snip = tag_close !== -1 ? body.slice(tag_open + open_tag.length, tag_close) : body.slice(tag_open + open_tag.length, b_start);
}
}
let clean_snip = collapse(raw_snip);
if (clean_snip.length > 48) clean_snip = `${clean_snip.slice(0, 45)}...`;
const pair_match = PAIR_RE.exec(rest);
if (pair_match) {
const partner_cids = [...pair_match[1].matchAll(CHG_ID_RE)].map((pm) => pm[1]);
const bubble_cids = parsed_chg_items.map((it) => it.cid);
let src_cid = cid;
if (partner_cids.includes(cid)) {
const non_partner_cids = bubble_cids.filter((c) => !partner_cids.includes(c));
src_cid = non_partner_cids.length ? non_partner_cids[0] : cid;
}
for (const pid of partner_cids) {
if (pid !== src_cid) {
addPair(pair_map, src_cid, pid);
addPair(pair_map, pid, src_cid);
}
}
}
const author = rest.replace(AUTHOR_NOISE_RE, "").trim() || "Unknown";
if (existing_ids !== null && !isLiveId(cid)) continue;
if (!chg_entries.has(cid)) {
chg_entries.set(cid, {
kind: "chg",
cid,
change_type,
author,
page: p_num,
snippet: clean_snip,
pair_ids: [],
reply_to_id: null,
position: b_start
});
}
}
for (const item of parsed_com_items) {
const cid = item.cid;
const cdata = comment_data_for(cid) || comment_data_for(`Com:${cid}`) || null;
let author;
let raw_comm;
let parent_id;
if (cdata !== null) {
author = cdata.author || "Unknown";
raw_comm = cdata.text ?? "";
parent_id = cdata.parent_id;
} else {
const parsed_author = item.parsed_author;
raw_comm = item.body_text;
const reply_match = REPLY_RE.exec(parsed_author);
parent_id = reply_match ? reply_match[1] : null;
author = parsed_author;
}
author = author.replace(AUTHOR_NOISE_RE, "").trim() || "Unknown";
let clean_comm = collapse(raw_comm);
if (clean_comm.length > 120) clean_comm = `${clean_comm.slice(0, 117)}...`;
const reply_to = parent_id ? String(parent_id).startsWith("Com:") ? String(parent_id) : `Com:${parent_id}` : null;
if (!com_entries.has(cid)) {
com_entries.set(cid, {
kind: "com",
cid,
change_type: "",
author,
page: p_num,
snippet: clean_comm,
pair_ids: [],
reply_to_id: reply_to,
position: b_start
});
}
}
}
if (comments_data) {
for (const [cid, cdata] of Object.entries(comments_data)) {
const str_cid = stripPrefix(String(cid), "Com:");
if (com_entries.has(str_cid)) continue;
const author = (cdata.author || "Unknown").replace(AUTHOR_NOISE_RE, "").trim() || "Unknown";
let clean_comm = collapse(cdata.text ?? "");
if (clean_comm.length > 120) clean_comm = `${clean_comm.slice(0, 117)}...`;
const parent_id = cdata.parent_id;
const reply_to = parent_id ? String(parent_id).startsWith("Com:") ? String(parent_id) : `Com:${parent_id}` : null;
com_entries.set(str_cid, {
kind: "com",
cid: str_cid,
change_type: "",
author,
page: 1,
snippet: clean_comm,
pair_ids: [],
reply_to_id: reply_to,
position: 999999
});
}
}
if (existing_ids !== null) {
for (const raw_id of existing_ids) {
const clean_cid = stripPrefix(String(raw_id), "Chg:");
if (chg_entries.has(clean_cid)) continue;
chg_entries.set(clean_cid, {
kind: "chg",
cid: clean_cid,
change_type: "del",
author: "Unknown",
page: 1,
snippet: "",
pair_ids: [],
reply_to_id: null,
position: 999999
});
}
}
for (const [cid, e] of chg_entries) {
const partners = pair_map.get(cid);
if (partners) e.pair_ids = partners;
if (existing_ids !== null) e.pair_ids = e.pair_ids.filter((pid) => isLiveId(pid));
}
const num_id = (cid) => isDigits(cid) ? parseInt(ascii_digits(cid), 10) : 0;
const all_entries = [...chg_entries.values(), ...com_entries.values()].sort(
(a, b) => a.position - b.position || (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0) || num_id(a.cid) - num_id(b.cid)
);
let filtered = all_entries;
if (author_filter) {
const af = author_filter.trim().toLowerCase();
filtered = filtered.filter((e) => e.author.toLowerCase().includes(af));
}
if (page != null && String(page).toLowerCase() !== "all") {
const [kind, p_val] = parse_page_arg(page);
if (kind === "range") {
const [start_p, end_p] = p_val;
if (start_p < 1 || end_p < 1 || start_p > total_pages) {
throw new Error(`Page ${start_p} out of range (doc has ${total_pages} pages).`);
}
filtered = filtered.filter((e) => start_p <= e.page && e.page <= end_p);
} else if (kind === "single") {
const p_single = p_val;
if (p_single < 1 || p_single > total_pages) {
throw new Error(`Page ${p_single} out of range (doc has ${total_pages} pages).`);
}
filtered = filtered.filter((e) => e.page === p_single);
}
}
const total_changes = filtered.filter((e) => e.kind === "chg").length;
const total_comments = filtered.filter((e) => e.kind === "com").length;
const dist = /* @__PURE__ */ new Map();
for (const e of filtered) dist.set(e.page, (dist.get(e.page) ?? 0) + 1);
const dist_str = dist.size ? [...dist.keys()].sort((a, b) => a - b).map((p) => `p${p}: ${dist.get(p)}`).join(", ") : "none";
const authors = [...new Set(filtered.filter((e) => e.author).map((e) => e.author))].sort();
const authors_str = authors.length ? authors.join(", ") : "None";
const header = `> **Changes ledger** \u2014 ${total_changes} change(s), ${total_comments} comment(s) across ${total_pages} page(s).
> Distribution \u2014 ${dist_str}
> Authors \u2014 ${authors_str}
`;
const total_entries = filtered.length;
const slice_entries = filtered.slice(offset, offset + LEDGER_PAGE_SIZE);
const lines = [];
for (const e of slice_entries) {
if (e.kind === "chg") {
let pair_suffix = "";
if (e.pair_ids.length) {
const sorted_pids = [...e.pair_ids].sort((a, b) => num_id(a) - num_id(b) || (a < b ? -1 : a > b ? 1 : 0));
pair_suffix = ` (pairs ${sorted_pids.map((pid) => `Chg:${pid}`).join(", ")})`;
}
lines.push(`Chg:${e.cid} ${e.change_type} ${e.author} p${e.page} "${e.snippet}"${pair_suffix}`);
} else {
const reply_suffix = e.reply_to_id ? ` (reply to ${e.reply_to_id})` : "";
lines.push(`Com:${e.cid} ${e.author} p${e.page} "${e.snippet}"${reply_suffix}`);
}
}
let continuation = "";
if (offset + LEDGER_PAGE_SIZE < total_entries) {
const next_offset = offset + LEDGER_PAGE_SIZE;
const mcp_args = [];
if (file_path) mcp_args.push(`file_path="${file_path}"`);
mcp_args.push('mode="changes"');
if (author_filter) mcp_args.push(`changes_author="${author_filter}"`);
if (page != null) {
mcp_args.push(typeof page === "string" ? `page="${page}"` : `page=${page}`);
}
mcp_args.push(`changes_offset=${next_offset}`);
continuation = `
> **Showing entries ${offset + 1}-${offset + slice_entries.length} of ${total_entries}.** Continue with \`read_docx(${mcp_args.join(", ")})\`.`;
}
let ui_markdown;
let llm_content;
if (no_chrome) {
ui_markdown = lines.join("\n") || `${total_changes} change(s), ${total_comments} comment(s)`;
llm_content = ui_markdown;
} else {
ui_markdown = header + lines.join("\n") + continuation;
llm_content = `> **File Path:** \`${resolve(file_path)}\`
${ui_markdown}`;
}
return {
content: [{ type: "text", text: llm_content }],
structuredContent: {
markdown: ui_markdown,
file_path: resolve(file_path),
title: basename(file_path)
}
};
}
// src/response-builders.ts
function makeBuilderResult(llmContent, structuredContent) {
const res = {
content: [{ type: "text", text: llmContent }]
};
if (structuredContent !== void 0) {
res.structuredContent = structuredContent;
}
return res;
}
var STYLE_MARKER_RE = /\*\*|(?<![\w])_(?=\S)|(?<=\S)_(?![\w])/g;
var PROTECTED_TOKEN_RE = /\{#[^}]+\}|_{3,}/g;
var ANCHOR_TOKEN_SRC = "\\{#[^}\\n]*\\}";
function emphasizedSnippetSpans(region, spans) {
const keep = new Array(region.length).fill(true);
const protected_idx = new Array(region.length).fill(false);
for (const m of region.matchAll(PROTECTED_TOKEN_RE)) {
for (let i = m.index; i < m.index + m[0].length; i++)
protected_idx[i] = true;
}
for (const m of region.matchAll(STYLE_MARKER_RE)) {
let overlaps_protected = false;
for (let i = m.index; i < m.index + m[0].length; i++) {
if (protected_idx[i]) {
overlaps_protected = true;
break;
}
}
if (overlaps_protected) continue;
for (let i = m.index; i < m.index + m[0].length; i++) keep[i] = false;
}
const stripped = (a, b) => {
let out = "";
for (let i = a; i < b; i++) if (keep[i]) out += region[i];
return out;
};
const sorted = [...spans].sort((x, y) => x[0] - y[0]);
const parts = [];
let cursor = 0;
for (const [s, e] of sorted) {
parts.push(stripped(cursor, s));
parts.push(`**${stripped(s, e)}**`);
cursor = e;
}
parts.push(stripped(cursor, region.length));
return parts.join("");
}
var SEARCH_TOKENS_PER_MATCH = 60;
var CHARS_PER_TOKEN = 4;
var SNIPPET_RADIUS_LADDER = [120, 60, 30, 16];
var SEARCH_FIXED_CHROME_TOKENS = 120;
var SEARCH_ENTRY_CHROME_TOKENS = 22;
var SEARCH_MIN_SNIPPET_TOKENS = 13;
function search_budget_tokens(max_matches, rendered_count) {
if (max_matches < 1) return SEARCH_FIXED_CHROME_TOKENS;
const rendered = rendered_count === void 0 ? max_matches : Math.min(max_matches, Math.max(rendered_count, 0));
return Math.max(
max_matches * SEARCH_TOKENS_PER_MATCH,
SEARCH_FIXED_CHROME_TOKENS + rendered * (SEARCH_ENTRY_CHROME_TOKENS + SEARCH_MIN_SNIPPET_TOKENS)
);
}
var SNIPPET_MARKUP_PAIRS = [
["{>>", "<<}"],
["{--", "--}"],
["{++", "++}"],
["{==", "==}"]
];
var SNIPPET_CLOSER_OF = Object.fromEntries(SNIPPET_MARKUP_PAIRS);
var SNIPPET_OPENER_OF = Object.fromEntries(
SNIPPET_MARKUP_PAIRS.map(([opener, closer]) => [closer, opener])
);
var SNIPPET_MARKUP_TOKEN_SRC = [
...Object.keys(SNIPPET_CLOSER_OF),
...Object.keys(SNIPPET_OPENER_OF)
].map((t) => escapeRegExp(t)).join("|");
function escapeRegExp(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function balanceSnippetWindow(body, start, end) {
for (; ; ) {
const depth = {};
for (const opener of Object.keys(SNIPPET_CLOSER_OF)) depth[opener] = 0;
let widened = false;
const anchor_re = new RegExp(ANCHOR_TOKEN_SRC, "g");
let a;
while ((a = anchor_re.exec(body)) !== null) {
const a_start = a.index;
const a_end = a.index + a[0].length;
if (a_start < start && start < a_end) {
start = a_start;
widened = true;
}
if (a_start < end && end < a_end) {
end = a_end;
widened = true;
}
if (a_start >= end) break;
}
if (widened) continue;
const token_re = new RegExp(SNIPPET_MARKUP_TOKEN_SRC, "g");
token_re.lastIndex = start;
let tok;
while ((tok = token_re.exec(body)) !== null) {
if (tok.index + tok[0].length > end) break;
const token = tok[0];
if (token in SNIPPET_CLOSER_OF) {
depth[token] += 1;
continue;
}
const opener = SNIPPET_OPENER_OF[token];
if (depth[opener]) {
depth[opener] -= 1;
continue;
}
const search_from = start - opener.length;
const prev_opener = search_from < 0 ? -1 : body.lastIndexOf(opener, search_from);
if (prev_opener !== -1) {
start = prev_opener;
widened = true;
break;
}
}
if (widened) continue;
for (const opener of Object.keys(depth)) {
if (!depth[opener]) continue;
const closer = SNIPPET_CLOSER_OF[opener];
const next_closer = body.indexOf(closer, end);
if (next_closer !== -1) {
end = next_closer + closer.length;
widened = true;
break;
}
}
if (!widened) return [start, end];
}
}
var TRAILING_BUBBLE_RE = /\{>>\s*(\[[^\]\n]{0,80}\])([\s\S]*?)<<\}/y;
function trailingBubbleHeader(body, at) {
TRAILING_BUBBLE_RE.lastIndex = at;
const m = TRAILING_BUBBLE_RE.exec(body);
if (!m) return "";
return "{>>" + m[1] + (m[2].trim() ? " ..." : "") + "<<}";
}
function enclosingSnippetMarkup(body, start, end) {
const open_spans = [];
for (const [opener, closer] of SNIPPET_MARKUP_PAIRS) {
const pair_re = new RegExp(
`${escapeRegExp(opener)}|${escapeRegExp(closer)}`,
"g"
);
const stack = [];
let tok;
while ((tok = pair_re.exec(body)) !== null) {
if (tok.index + tok[0].length > start) break;
if (tok[0] === opener) stack.push(tok.index);
else if (stack.length) stack.pop();
}
if (!stack.length) continue;
const closer_at = body.indexOf(closer, end);
if (closer_at === -1) continue;
const open_at = stack[stack.length - 1];
let prefix = opener;
let suffix = closer;
if (opener === "{>>") {
const header = /^\[[^\]\n]{0,80}\]/.exec(
body.slice(open_at + opener.length, start)
);
if (header) prefix += header[0];
} else {
suffix += trailingBubbleHeader(body, closer_at + closer.length);
}
open_spans.push([open_at, prefix, suffix]);
}
open_spans.sort((a, b) => a[0] - b[0]);
return [
open_spans.map(([, prefix]) => prefix).join(""),
open_spans.slice().reverse().map(([, , suffix]) => suffix).join("")
];
}
function mergeSpans(spans) {
const merged = [];
for (const [span_start, span_end] of [...spans].sort(
(a, b) => a[0] - b[0] || a[1] - b[1]
)) {
const last = merged[merged.length - 1];
if (last && span_start <= last[1]) last[1] = Math.max(last[1], span_end);
else merged.push([span_start, span_end]);
}
return merged;
}
function snapCodePointBoundary(text, start, end) {
if (start > 0 && start < text.length) {
const code = text.charCodeAt(start);
if (code >= 56320 && code <= 57343) start -= 1;
}
if (end > 0 && end < text.length) {
const code = text.charCodeAt(end - 1);
if (code >= 55296 && code <= 56319) end += 1;
}
return [start, end];
}
function with_path_header(file_path, fields_banner, ui_markdown) {
let header = `> **File Path:** \`${resolve2(file_path)}\``;
if (fields_banner) header += `
${fields_banner}`;
return `${header}
${ui_markdown}`;
}
function parseBundleAndOptions(arg3, arg4) {
let bundle;
let no_chrome = false;
let fields_banner;
if (typeof arg3 === "boolean") {
no_chrome = arg3;
} else if (arg3 && "body" in arg3) {
bundle = arg3;
} else if (arg3 && typeof arg3 === "object") {
if ("no_chrome" in arg3 && arg3.no_chrome !== void 0) {
no_chrome = Boolean(arg3.no_chrome);
}
if ("fields_banner" in arg3) fields_banner = arg3.fields_banner;
}
if (typeof arg4 === "boolean") {
no_chrome = arg4;
} else if (arg4 && typeof arg4 === "object") {
if ("no_chrome" in arg4 && arg4.no_chrome !== void 0) {
no_chrome = Boolean(arg4.no_chrome);
}
if ("fields_banner" in arg4) fields_banner = arg4.fields_banner;
}
return { bundle, no_chrome, fields_banner };
}
function _build_appendix_pointer(has_appendix) {
if (!has_appendix) return "";
return `
---
> **Appendix available.** This document has structural metadata (defined terms, cross-references, bookmarks, diagnostics) that may be relevant when editing. Call \`read_docx\` with \`mode='appendix'\` to load it before submitting edits.`;
}
function _build_page_banner(page, total) {
if (total <= 1) return "";
return `> **Page ${page} of ${total}** (synthetic page \u2014 a length-based chunk, not a printed Word page) \u2014 call \`read_docx\` with \`mode='outline'\` for a heading map of the full document.
---
`;
}
function _build_page_footer(page, total, has_next) {
if (total <= 1 || !has_next) return "";
return `
---
> **Continues on page ${page + 1} of ${total}.**`;
}
function render_outline_tree(nodes, max_level = 2, verbose = false, no_chrome = false) {
if (!nodes || nodes.length === 0) {
return "# (No headings detected)\n\nThis document has no detectable headings.";
}
const visible = nodes.filter((n) => n.level <= max_level);
if (visible.length === 0) {
if (no_chrome) {
return `# (No headings at level <= ${max_level})
Document has ${nodes.length} headings, all at deeper levels.`;
}
return `# (No headings at level <= ${max_level})
Document has ${nodes.length} headings, all at deeper levels. Call read_docx with mode='outline' and outline_max_level=N (up to 6) to see them.`;
}
const lines = [];
for (const node of visible) {
const prefix = "#".repeat(node.level);
if (verbose) {
const meta_parts = [`p${node.page}`, node.style];
if (node.has_table) meta_parts.push("has table");
if (node.footnote_ids && node.footnote_ids.length > 0)
meta_parts.push("fn:" + node.footnote_ids.join(","));
lines.push(`${prefix} ${node.text} (${meta_parts.join(", ")})`);
} else {
const page_str = node.end_page && node.end_page > node.page ? `p${node.page}-p${node.end_page}` : `p${node.page}`;
lines.push(`${prefix} ${node.text} (${page_str})`);
}
}
return lines.join("\n");
}
function build_full_document_response(text, file_path, bundleOrOpts, no_chrome_param) {
const { bundle, no_chrome, fields_banner } = parseBundleAndOptions(
bundleOrOpts,
no_chrome_param
);
const body = bundle ? bundle.body : split_projection(text)[0];
const ui_markdown = body;
const llm_content = no_chrome ? ui_markdown : with_path_header(file_path, fields_banner, ui_markdown);
return makeBuilderResult(llm_content, {
markdown: ui_markdown,
file_path: resolve2(file_path),
title: basename2(file_path)
});
}
function build_bounded_full_response(projected_text, file_path, nodes, bundle) {
const limit = response_budget_limit();
const total_chars = projected_text.length;
const total_pages = bundle.pagination.total_pages;
const list = nodes ?? [];
const entries = list.some((n) => n.level === 1) ? render_outline_tree(list, 1, false).split("\n").filter((l) => l.trim()) : [];
const tail = (shown2, page_content) => {
let cont = "";
if (shown2 < total_pages && !page_content.includes("Continues on page")) {
cont = `Continue with \`page="${shown2 + 1}-${Math.min(shown2 + PAGE_RANGE_MAX_PAGES, total_pages)}"\` \xB7 `;
}
const head = [
"---",
"",
`> **Document exceeds the response budget** (${total_chars.toLocaleString("en-US")} chars, ~${Math.floor(total_chars / 4).toLocaleString("en-US")} tokens; limit ${limit.toLocaleString("en-US")}): showing pages 1-${shown2} of ${total_pages}.`,
`> ${cont}find a passage with \`search_query\` \xB7 heading map with \`mode='outline'\` \xB7 whole body with \`force=true\`.`
];
const kept = [...entries];
for (; ; ) {
const lines = [...head];
if (kept.length) {
lines.push("", "Outline (L1 Headings):", ...kept);
if (kept.length < entries.length) {
lines.push(` (${entries.length - kept.length} more headings: mode='outline')`);
}
}
const text = lines.join("\n");
if (!kept.length || text.length <= GUARD_EMITTED_MAX_CHARS) return text;
kept.pop();
}
};
let shown = Math.min(PAGE_RANGE_MAX_PAGES, total_pages);
let res;
let note;
for (; ; ) {
res = build_page_range_response(projected_text, 1, shown, file_path, bundle);
note = tail(shown, res.content[0].text);
if (shown === 1 || res.content[0].text.length + 2 + note.length <= limit) break;
shown--;
}
res.content[0].text = `${res.content[0].text}
${note}`;
const sc = res.structuredContent;
if (sc && typeof sc.markdown === "string") sc.markdown = `${sc.markdown}
${note}`;
return res;
}
function build_paginated_response(text, page, file_path, bundleOrOpts, no_chrome_param) {
const { bundle, no_chrome, fields_banner } = parseBundleAndOptions(
bundleOrOpts,
no_chrome_param
);
const [body, appendix] = bundle ? [bundle.body, bundle.appendix] : split_projection(text);
const has_appendix = Boolean(appendix.trim());
const result = bundle ? bundle.pagination : paginate2(body, "");
if (page < 1 || page > result.total_pages) {
throw new Error(
`Page ${page} out of range (doc has ${result.total_pages} pages).`
);
}
const selected = result.pages[page - 1];
let ui_markdown;
let llm_content;
if (no_chrome) {
const page_marker = selected.total_pages > 1 ? `[p${selected.page}/${selected.total_pages}]
` : "";
ui_markdown = `${page_marker}${selected.page_content}`;
llm_content = ui_markdown;
} else {
const banner = _build_page_banner(selected.page, selected.total_pages);
const footer = _build_page_footer(
selected.page,
selected.total_pages,
selected.has_next
);
const appendix_pointer = _build_appendix_pointer(has_appendix);
ui_markdown = banner + selected.page_content + footer + appendix_pointer;
llm_content = with_path_header(file_path, fields_banner, ui_markdown);
}
return makeBuilderResult(llm_content, {
markdown: ui_markdown,
file_path: resolve2(file_path),
title: basename2(file_path)
});
}
function build_page_range_response(text, start, end, file_path, bundleOrOpts, no_chrome_param) {
const { bundle, no_chrome } = parseBundleAndOptions(
bundleOrOpts,
no_chrome_param
);
if (start < 1)
throw new Error(`Invalid page number ${start}: page numbers must be positive integers.`);
if (start > end)
throw new Error(`end page (${end}) cannot be less than start page (${start})`);
const [body, appendix] = bundle ? [bundle.body, bundle.appendix] : split_projection(text);
const has_appendix = Boolean(appendix.trim());
const result = bundle ? bundle.pagination : paginate2(body, "");
const total_pages = result.total_pages;
if (start > total_pages)
throw new Error(`Page ${start} out of range (doc has ${total_pages} pages).`);
const last = Math.min(end, start + PAGE_RANGE_MAX_PAGES - 1, total_pages);
const page_blocks = [];
for (let p = start; p <= last; p++) {
const selected = result.pages[p - 1];
const banner = no_chrome ? selected.total_pages > 1 ? `[p${selected.page}/${selected.total_pages}]
` : "" : _build_page_banner(selected.page, selected.total_pages);
page_blocks.push(`${banner}${selected.page_content}`);
}
const ui_parts = [page_blocks.join("\n\n")];
if (!no_chrome) {
if (last < end && last < total_pages) {
ui_parts.push(
`> **Range capped at ${PAGE_RANGE_MAX_PAGES} pages.** Continue with \`page="${last + 1}-${end}"\`.`
);
} else if (last === end && last < total_pages && end - start + 1 >= PAGE_RANGE_MAX_PAGES) {
const next_start = last + 1;
const next_end = Math.min(last + PAGE_RANGE_MAX_PAGES, total_pages);
ui_parts.push(
`> **Continues on page ${next_start} of ${total_pages}.** Pass \`page="${next_start}-${next_end}"\` to read the next pages.`
);
} else if (end > total_pages) {
ui_parts.push(
`> **[range stopped at page ${total_pages}: the document has ${total_pages} page(s)]**`
);
}
const pointer = _build_appendix_pointer(has_appendix);
if (pointer) ui_parts.push(pointer.trim());
}
const ui_markdown = ui_parts.join("\n\n");
const llm_content = no_chrome ? ui_markdown : `> **File Path:** \`${resolve2(file_path)}\`
${ui_markdown}`;
return makeBuilderResult(llm_content, {
markdown: ui_markdown,
file_path: resolve2(file_path),
title: basename2(file_path)
});
}
function build_outline_response(doc, projected_text, file_path, outline_max_level = 2, outline_verbose = false, paragraph_offsets = null, no_chromeOrOpts = false) {
const [body] = split_projection(projected_text);
const pagination_result = paginate2(body, "");
const nodes = extract_outline(
doc,
body,
pagination_result.body_pages,
pagination_result.body_page_offsets,
paragraph_offsets
);
return render_outline_response(
nodes,
pagination_result.total_pages,
file_path,
outline_max_level,
outline_verbose,
no_chromeOrOpts
);
}
function render_outline_response(nodes, total_pages, file_path, outline_max_level = 2, outline_verbose = false, no_chromeOrOpts = false) {
const no_chrome = typeof no_chromeOrOpts === "boolean" ? no_chromeOrOpts : Boolean(no_chromeOrOpts?.no_chrome);
outline_max_level = Math.max(1, Math.min(outline_max_level, 6));
const rendered = render_outline_tree(
nodes,
outline_max_level,
outline_verbose,
no_chrome
);
const visible_count = nodes.filter(
(n) => n.level <= outline_max_level
).length;
const deeper_count = nodes.length - visible_count;
const deeper_hint = deeper_count > 0 ? ` (${deeper_count} more at deeper levels, raise outline_max_level to see)` : "";
let ui_markdown;
let llm_content;
if (no_chrome) {
ui_markdown = rendered;
llm_content = ui_markdown;
} else {
const header = `> **Outline view** \u2014 showing ${visible_count} of ${nodes.length} headings (L1-L${outline_max_level}${deeper_hint}) across ${total_pages} page(s). Call \`read_docx\` with \`mode='full'\` and \`page=N\` to read a section.
---
`;
ui_markdown = header + rendered;
llm_content = `> **File Path:** \`${resolve2(file_path)}\`
${ui_markdown}`;
}
return makeBuilderResult(llm_content, {
markdown: ui_markdown,
file_path: resolve2(file_path),
title: `Outline: ${basename2(file_path)}`
});
}
function build_appendix_response(text, page, file_path, bundleOrOpts, no_chrome_param) {
const { bundle, no_chrome } = parseBundleAndOptions(
bundleOrOpts,
no_chrome_param
);
const appendix = bundle ? bundle.appendix : split_projection(text)[1];
if (!appendix.trim()) {
const ui_markdown2 = "# Appendix\n\nThis document has no structural appendix (no defined terms, named anchors, or diagnostics detected).";
const llm_content2 = no_chrome ? ui_markdown2 : `> **File Path:** \`${resolve2(file_path)}\`
${ui_markdown2}`;
return makeBuilderResult(llm_content2, {
markdown: ui_markdown2,
file_path: resolve2(file_path),
title: `Appendix: ${basename2(file_path)}`
});
}
const result = paginate2(appendix, "");
if (page < 1 || page > result.total_pages) {
throw new Error(
`Appendix page ${page} out of range (appendix has ${result.total_pages} pages).`
);
}
const selected = result.pages[page - 1];
let ui_markdown;
let llm_content;
if (no_chrome) {
const page_marker = selected.total_pages > 1 ? `[p${selected.page}/${selected.total_pages}]
` : "";
ui_markdown = `${page_marker}${selected.page_content}`;
llm_content = ui_markdown;
} else {
let banner = "";
let footer = "";
if (selected.total_pages > 1) {
banner = `> **Appendix page ${selected.page} of ${selected.total_pages}** \u2014 structural metadata for this document.
---
`;
footer = selected.has_next ? `
---
> **Continues on appendix page ${selected.page + 1} of ${selected.total_pages}.**` : "";
} else {
banner = "> **Appendix** \u2014 structural metadata for this document.\n\n---\n\n";
}
ui_markdown = banner + selected.page_content + footer;
llm_content = `> **File Path:** \`${resolve2(file_path)}\`
${ui_markdown}`;
}
return makeBuilderResult(llm_content, {
markdown: ui_markdown,
file_path: resolve2(file_path),
title: `Appendix: ${basename2(file_path)}`
});
}
function build_search_response(text, search_query, search_regex, search_case_sensitive, page, file_path, bundle, opts) {
const max_matches = opts?.max_matches ?? 20;
const full_paragraph = opts?.full_paragraph ?? false;
const no_chrome = opts?.no_chrome ?? false;
let match_offset = opts?.match_offset ?? 0;
if (match_offset < 0) match_offset = 0;
const body = bundle ? bundle.body : split_projection(text)[0];
const flags = search_case_sensitive ? "g" : "gi";
const literalMatches = () => Array.from(
body.matchAll(new RegExp(escapeRegExp(search_query), flags)),
(m) => ({ start: m.index, end: m.index + m[0].length })
);
let regexDowngradedNote = "";
let rawMatches;
let isUserRegex = false;
if (search_regex) {
try {
compileRegexWithInlineFlags(search_query, flags);
isUserRegex = true;
} catch (e) {
regexDowngradedNote = `> **Note:** \`${search_query}\` is not a valid regular expression (${e.message}), so it was searched as literal text instead. If you meant a regex, fix the pattern; if you meant literal text, set \`search_regex\` to false.`;
}
}
if (isUserRegex) {
try {
rawMatches = userFindAllMatches(search_query, body, flags);
} catch (e) {
if (!(e instanceof RegexTimeoutError)) throw e;
regexDowngradedNote = `> **Note:** \`${search_query}\` was searched as literal text instead of as a regular expression: ${e.message}`;
rawMatches = literalMatches();
}
} else {
rawMatches = literalMatches();
}
const pag_res = bundle ? bundle.pagination : paginate2(body, "");
const page_offsets = pag_res.body_page_offsets;
const total_doc_pages = pag_res.total_pages;
const pageOfOffset = (offset) => {
let p = 1;
for (let j = 0; j < page_offsets.length; j++) {
if (offset >= page_offsets[j]) p = j + 1;
else break;
}
return p;
};
const shownPage = typeof page === "string" ? `'${page}'` : String(page);
const badPage = (omitted_hint) => new Error(
`Invalid page value: ${shownPage}. In search mode, \`page\` must be ${omitted_hint}, \`'all'\`, or a positive integer document page number.`
);
let page_filter = null;
let page_range_filter = null;
if (page !== void 0 && page !== null) {
if (Array.isArray(page) && page.length === 2) {
const startP = Number(page[0]);
const endP = Number(page[1]);
if (!Number.isInteger(startP) || !Number.isInteger(endP) || startP < 1 || endP < startP) {
throw badPage("omitted");
}
if (startP > total_doc_pages) {
throw new Error(
`Document page ${startP} is out of range \u2014 the document has ${total_doc_pages} page(s). In search mode, \`page\` filters matches by document page; omit \`page\` (or pass \`page='all'\`) to search across the whole document.`
);
}
page_range_filter = [startP, Math.min(endP, total_doc_pages)];
} else if (typeof page === "string") {
const s_clean = page.trim().replace(/^['"]+|['"]+$/g, "").trim();
if (s_clean.toLowerCase() !== "all") {
if (!/^[+-]?\d+$/.test(s_clean)) throw badPage("omitted (search all pages)");
page_filter = parseInt(s_clean, 10);
if (page_filter < 1) throw badPage("omitted");
}
} else if (typeof page === "number" && Number.isInteger(page)) {
if (page < 1) throw badPage("omitted");
page_filter = page;
} else {
throw badPage("omitted");
}
}
if (page_filter !== null && page_filter > total_doc_pages) {
throw new Error(
`Document page ${page_filter} is out of range \u2014 the document has ${total_doc_pages} page(s). In search mode, \`page\` filters matches by document page; omit \`page\` (or pass \`page='all'\`) to search across the whole document.`
);
}
const title = `Search: ${basename2(file_path)}`;
const wrap = (ui_markdown2) => ({
content: [
{
type: "text",
text: no_chrome ? ui_markdown2 : `> **File Path:** \`${resolve2(file_path)}\`
${ui_markdown2}`
}
],
structuredContent: {
markdown: ui_markdown2,
title,
file_path: resolve2(file_path)
}
});
if (rawMatches.length === 0) {
let ui_markdown2 = no_chrome ? `No matches found for query \`${search_query}\`.` : `> **Search Results** \u2014 No matches found for query \`${search_query}\` in \`${basename2(file_path)}\`.
Verify your search spelling, or try setting \`search_case_sensitive\` to false or enabling \`search_regex\` if you used pattern wildcards.`;
if (regexDowngradedNote)
ui_markdown2 = `${regexDowngradedNote}
${ui_markdown2}`;
return wrap(ui_markdown2);
}
const all_hits = rawMatches.map((m, i) => ({
text: body.slice(m.start, m.end),
start: m.start,
end: m.end,
page: pageOfOffset(m.start),
index: i + 1
}));
const total_matches = all_hits.length;
const occurrences_map = /* @__PURE__ */ Object.create(null);
const page_distribution = /* @__PURE__ */ new Map();
for (const hit of all_hits) {
occurrences_map[hit.text] = (occurrences_map[hit.text] || 0) + 1;
page_distribution.set(hit.page, (page_distribution.get(hit.page) || 0) + 1);
}
const pages_with_hits = Array.from(page_distribution.keys()).sort(
(a, b) => a - b
);
const active_page_label = page_range_filter ? `pages ${page_range_filter[0]}-${page_range_filter[1]}` : page_filter !== null ? `page ${page_filter}` : "";
const filtered = page_range_filter ? all_hits.filter(
(hit) => hit.page >= page_range_filter[0] && hit.page <= page_range_filter[1]
) : page_filter === null ? all_hits : all_hits.filter((hit) => hit.page === page_filter);
if (active_page_label && filtered.length === 0) {
const other_pages_str = pages_with_hits.join(", ");
const ui_markdown2 = no_chrome ? `No matches on document ${active_page_label} for query \`${search_query}\`. Query appears on page(s) ${other_pages_str}.` : `> **Search Results** \u2014 No matches on document ${active_page_label} for query \`${search_query}\` in \`${basename2(file_path)}\`.
The query DOES appear elsewhere (${total_matches} match${total_matches !== 1 ? "es" : ""} on page${pages_with_hits.length !== 1 ? "s" : ""} ${other_pages_str}). Omit \`page\` or pass \`page='all'\` to see them.`;
return wrap(ui_markdown2);
}
const total_filtered = filtered.length;
const window_note_response = (note) => {
const ui_parts = [];
if (!no_chrome) {
ui_parts.push(
!active_page_label ? `> **Search Results** \u2014 Found ${total_matches} match${total_matches !== 1 ? "es" : ""} for query \`${search_query}\` in \`${basename2(file_path)}\`.` : `> **Search Results** \u2014 Found ${total_filtered} match${total_filtered !== 1 ? "es" : ""} on document ${active_page_label} for query \`${search_query}\` in \`${basename2(file_path)}\` (${total_matches} total in document).`
);
}
ui_parts.push(note);
if (regexDowngradedNote) ui_parts.unshift(regexDowngradedNote);
return wrap(ui_parts.filter((part) => part).join("\n\n"));
};
if (max_matches < 1) {
return window_note_response(
no_chrome ? `No matches shown (max_matches=${max_matches}, total matches=${total_filtered}).` : `> **Note:** No matches shown (max_matches=${max_matches}, total matches=${total_filtered}). Pass \`max_matches=N\` with N >= 1 to see match snippets.`
);
}
if (match_offset >= total_filtered) {
return window_note_response(
no_chrome ? `No matches in this window (match_offset=${match_offset}, total matches=${total_filtered}).` : `> **Note:** No matches in this window (match_offset=${match_offset}, total matches=${total_filtered}).`
);
}
const selected_matches = filtered.slice(
match_offset,
match_offset + max_matches
);
function build_header(num_rendered) {
const head = [];
const next_offset = match_offset + num_rendered;
const has_more = next_offset < total_filtered;
if (!active_page_label) {
const found = `> **Search Results** \u2014 Found ${total_matches} match${total_matches !== 1 ? "es" : ""} for query \`${search_query}\` in \`${basename2(file_path)}\``;
head.push(
total_filtered > num_rendered || match_offset > 0 ? `${found} (${total_matches} total, ${num_rendered} shown).` : `${found}.`
);
if (pages_with_hits.length > 1) {
const dist_str = pages_with_hits.map((p) => `p${p}: ${page_distribution.get(p)}`).join(", ");
head.push(
`> Distribution across ${pages_with_hits.length} document pages \u2014 ${dist_str}`
);
}
} else {
const found = `> **Search Results** \u2014 Found ${total_filtered} match${total_filtered !== 1 ? "es" : ""} on document ${active_page_label} for query \`${search_query}\` in \`${basename2(file_path)}\` (${total_matches} total in document`;
head.push(
total_filtered > num_rendered || match_offset > 0 ? `${found}, ${num_rendered} shown).` : `${found}).`
);
const other_pages = page_range_filter ? pages_with_hits.filter(
(p) => p < page_range_filter[0] || p > page_range_filter[1]
) : pages_with_hits.filter((p) => p !== page_filter);
if (other_pages.length) {
head.push(
`> Additional matches exist on page${other_pages.length !== 1 ? "s" : ""} ${other_pages.join(", ")} \u2014 omit \`page\` or pass \`page='all'\` to see them.`
);
}
}
if (has_more) {
head.push(
`> **Note:** Only ${num_rendered} matches shown (max_matches=${max_matches}). Continue with \`match_offset=${next_offset}\`.`
);
}
return head;
}
const get_heading = heading_path_at;
function group_by_line(hits) {
const groups = [];
const by_line = /* @__PURE__ */ new Map();
for (const hit of hits) {
const last_nl = hit.start <= 0 ? -1 : body.lastIndexOf("\n", hit.start - 1);
const line_start = last_nl === -1 ? 0 : last_nl + 1;
let group = by_line.get(line_start);
if (!group) {
group = [];
by_line.set(line_start, group);
groups.push([line_start, group]);
}
group.push(hit);
}
return groups;
}
function render_entry(line_start, group, radius) {
const first = group[0];
const last_hit_end = Math.max(...group.map((hit) => hit.end));
const next_nl = body.indexOf("\n", last_hit_end);
const line_end = next_nl === -1 ? body.length : next_nl;
let intervals;
if (radius === null) {
intervals = [[line_start, line_end]];
} else {
const windows2 = group.map((hit) => [
Math.max(line_start, hit.start - radius),
Math.min(line_end, hit.end + radius)
]);
intervals = mergeSpans(
mergeSpans(windows2).map(([s, e]) => balanceSnippetWindow(body, s, e))
).map(([s, e]) => snapCodePointBoundary(body, s, e));
}
const segments = [];
for (const [s_pos, e_pos] of intervals) {
const spans = group.filter((hit) => s_pos <= hit.start && hit.end <= e_pos).map((hit) => [hit.start - s_pos, hit.end - s_pos]);
const [open_tags, close_tags] = enclosingSnippetMarkup(body, s_pos, e_pos);
segments.push(
open_tags + emphasizedSnippetSpans(body.slice(s_pos, e_pos), spans) + close_tags
);
}
let snippet = segments.join(" ... ");
const window_start = intervals[0][0];
const window_end = intervals[intervals.length - 1][1];
const nl_before = window_start <= 0 ? -1 : body.lastIndexOf("\n", window_start - 1);
const first_line_start = nl_before + 1;
const nl_after = body.indexOf("\n", window_end);
const last_line_end = nl_after === -1 ? body.length : nl_after;
if (window_start > first_line_start) snippet = "..." + snippet;
if (window_end < last_line_end) snippet = snippet + "...";
const snippet_lines = snippet.split("\n").filter((line) => line.trim().length > 0).map((line) => `> ${line}`).join("\n");
const match_lines = ["---", `### Match ${first.index} (p${first.page})`];
const h_path = get_heading(first.start, body);
if (h_path) match_lines.push(`**Path:** \`${h_path}\``);
const distinct_strs = [];
for (const hit of group)
if (!distinct_strs.includes(hit.text)) distinct_strs.push(hit.text);
let occurrence_line;
if (distinct_strs.length === 1) {
const n = occurrences_map[distinct_strs[0]];
occurrence_line = `*Occurrences:* This exact phrasing appears ${n} time${n !== 1 ? "s" : ""} in the document.`;
} else {
occurrence_line = "*Occurrences:* " + distinct_strs.map((s) => {
const n = occurrences_map[s];
return `\`${s}\` appears ${n} time${n !== 1 ? "s" : ""}`;
}).join("; ") + " in the document.";
}
match_lines.push(snippet_lines, occurrence_line);
return match_lines.join("\n\n");
}
const content_prefix = no_chrome ? "" : `> **File Path:** \`${resolve2(file_path)}\`
`;
function compose(hits, radius, budget_note) {
const parts = no_chrome ? [] : build_header(hits.length);
for (const [line_start, group] of group_by_line(hits))
parts.push(render_entry(line_start, group, radius));
if (budget_note && !no_chrome) parts.push(budget_note);
if (regexDowngradedNote) parts.unshift(regexDowngradedNote);
return parts.filter((part) => part).join("\n\n");
}
const prefix_chrome = content_prefix ? content_prefix.length - resolve2(file_path).length : 0;
const fits = (markdown, rendered_count) => prefix_chrome + markdown.length <= search_budget_tokens(max_matches, rendered_count) * CHARS_PER_TOKEN;
let ui_markdown;
if (full_paragraph) {
ui_markdown = compose(selected_matches, null, "");
} else {
let radius = SNIPPET_RADIUS_LADDER[0];
ui_markdown = compose(selected_matches, radius, "");
for (const rung of SNIPPET_RADIUS_LADDER.slice(1)) {
radius = rung;
if (fits(ui_markdown, selected_matches.length)) break;
ui_markdown = compose(
selected_matches,
radius,
`> **Note:** Snippets trimmed to \xB1${radius} chars to fit the response size budget.`
);
}
const kept = [...selected_matches];
while (kept.length && !fits(ui_markdown, kept.length)) {
kept.pop();
if (!kept.length) {
return window_note_response(
no_chrome ? `No matches shown in this window: not even one \xB1${radius}-char snippet fits the response size budget (max_matches=${max_matches}, total matches=${total_filtered}).` : `> **Note:** No matches shown in this window: not even one \xB1${radius}-char snippet fits the response size budget (max_matches=${max_matches}, total matches=${total_filtered}). Raise \`max_matches\`, or pass \`full_paragraph=true\` to read the matching paragraph in full.`
);
}
ui_markdown = compose(
kept,
radius,
`> **Note:** Snippets trimmed to \xB1${radius} chars and trailing matches dropped to fit the response size budget \u2014 continue from the \`match_offset\` above.`
);
}
}
return wrap(ui_markdown);
}
// src/doc-cache.ts
import { statSync as statSync2 } from "fs";
import { resolve as resolve3 } from "path";
import { getHeapStatistics } from "v8";
import {
_extractTextFromDoc,
extract_outline as extract_outline2,
paginate as paginate3
} from "@adeu/core";
function makeBundle(text) {
const [body, appendix] = split_projection(text);
return { body, appendix, pagination: paginate3(body, "") };
}
var delay = (ms) => new Promise((r) => setTimeout(r, ms));
var DocCache = class {
constructor(maxEntries = 3, hotTtlMs = 3 * 6e4) {
this.maxEntries = maxEntries;
this.hotTtlMs = hotTtlMs;
}
maxEntries;
hotTtlMs;
entries = /* @__PURE__ */ new Map();
inflight = /* @__PURE__ */ new Map();
/** Observability for tests: how many full ingests ran. */
ingest_count = 0;
/** Timestamp of the most recent cache request — the clean fill's
* quietness signal (the extraction is one synchronous block, so it must
* not start while requests are actively arriving). */
lastTouch = 0;
/**
* Hot-DOM slot (docs/PERFORMANCE.md §5 "stop re-parsing"): the parsed
* DocumentObject of the most recently ingested/edited document version,
* kept so the NEXT operation on the same version (typically a
* process_document_batch right after a read, or a chained edit on a batch
* output) skips the multi-second disk parse entirely.
*
* Single slot, consume-on-take (an edit mutates the DOM, so it can never
* be shared), TTL-evicted, and guarded by a heap-headroom check so a
* multi-GB DOM is only pinned when there is room for it.
*/
hot = null;
hotTimer = null;
/** Test observability: how many edits reused a hot DOM. */
hot_hits = 0;
/** Priming jobs by key: a read arriving mid-prime joins instead of
* re-ingesting from disk. */
priming = /* @__PURE__ */ new Map();
/**
* Heap headroom check for the pin-release VALVE. Pinning a DOM never
* grows the heap (it only delays release of memory the ingest already
* allocated), so storing is always safe; the hazard is holding a pinned
* multi-GB tree WHILE a new ingest allocates another one. Before any
* ingest, the pin is dropped when headroom is low.
*/
heapHasRoom() {
try {
const limit = getHeapStatistics().heap_size_limit;
return process.memoryUsage().heapUsed < limit * 0.55;
} catch {
return false;
}
}
/** Drop the pinned DOM if a new multi-GB allocation needs the room. */
releaseHotIfPressured() {
if (this.hot && !this.heapHasRoom()) {
this.hot = null;
if (this.hotTimer) {
clearTimeout(this.hotTimer);
this.hotTimer = null;
}
}
}
storeHotDoc(key, doc) {
if (this.hotTimer) clearTimeout(this.hotTimer);
this.hot = { key, doc, jobs: [] };
this.hotTimer = setTimeout(() => {
this.hot = null;
this.hotTimer = null;
}, this.hotTtlMs);
this.hotTimer.unref?.();
}
/** Attach a background job to the hot slot iff it still holds `doc`. */
registerHotJob(doc, force, promise) {
if (this.hot && this.hot.doc === doc) {
this.hot.jobs.push({ force, promise });
}
}
/**
* Hand the parsed DOM of the CURRENT version of `file_path` to a mutating
* consumer (the edit path), or null when the slot holds a different
* version/file. Consume-on-take: the slot is cleared; all background jobs
* reading the DOM are forced to completion first.
*/
async takeHotDoc(file_path) {
this.lastTouch = Date.now();
if (!this.hot) return null;
let key;
try {
key = this.keyFor(resolve3(file_path));
} catch {
return null;
}
if (this.hot.key !== key) return null;
const slot = this.hot;
this.hot = null;
if (this.hotTimer) {
clearTimeout(this.hotTimer);
this.hotTimer = null;
}
for (const job of slot.jobs) {
try {
job.force();
} catch {
}
}
await Promise.all(slot.jobs.map((j) => j.promise.catch(() => {
})));
this.hot_hits++;
return slot.doc;
}
/**
* Put a DOM back in the slot after an operation that provably left it
* equal to the on-disk file (a rolled-back failed batch — restored via
* the engine's transactional snapshot).
*
* "Provably" is the caller's obligation, and it is not satisfied by the
* operation merely having thrown: the engine reports whether its rollback
* verified (RedlineEngine.rollback_verified), and only that answer makes a
* post-failure DOM safe to re-pin. Pinning an unverified one publishes a
* half-applied document under the UNCHANGED file's cache key, where the
* next call picks it up as if it had come from disk.
*/
restoreHotDoc(file_path, doc) {
try {
const key = this.keyFor(resolve3(file_path));
this.storeHotDoc(key, doc);
} catch {
}
}
/** Stat-derived identity of the CURRENT file version. */
keyFor(resolvedPath) {
const st = statSync2(resolvedPath);
return `${resolvedPath}|${st.mtimeMs}|${st.size}`;
}
/**
* Drop every cached product for `resolvedPath`, whatever version it was
* keyed under.
*
* `store()` already keeps one live version per path, but only when a NEW
* version is stored. That is exactly what a colliding key defeats: when a
* rewrite preserves both mtime and size — a size-neutral edit inside one
* filesystem timestamp tick — no new entry is ever built, so `get()` keeps
* returning the pre-write entry (its `entries` hit-check runs before the
* `priming` join). Writers must therefore evict explicitly.
*
* Entries carry the resolved path, so they are matched exactly, as in
* `store()`. The hot/priming/inflight maps are keyed by string only, and
* keyFor always emits `${resolvedPath}|…`, so a whole-prefix compare is
* exact there — a '|' inside a POSIX filename can neither miss nor
* over-match.
*/
purgePath(resolvedPath, opts) {
const prefix = `${resolvedPath}|`;
for (const [key, entry] of [...this.entries]) {
if (entry.file_path === resolvedPath) this.entries.delete(key);
}
for (const key of [...this.priming.keys()]) {
if (key.startsWith(prefix)) this.priming.delete(key);
}
for (const key of [...this.inflight.keys()]) {
if (key.startsWith(prefix)) this.inflight.delete(key);
}
if (!opts?.keepHot && this.hot && this.hot.key.startsWith(prefix)) {
this.hot = null;
if (this.hotTimer) {
clearTimeout(this.hotTimer);
this.hotTimer = null;
}
}
}
/**
* Forget everything cached for `file_path`. Callers that write a document
* without handing the post-write DOM to primeFromDoc MUST call this, or a
* later read can be served the pre-write projection.
*/
invalidate(file_path) {
this.purgePath(resolve3(file_path));
}
/**
* Returns the products for the current version of `file_path`, ingesting
* at most once per version (single-flight). `readBytes` is called only on
* a miss and owns the file-not-found error shape; `onProgress` is invoked
* only during a cold ingest.
*/
async get(file_path, readBytes, loadDoc, onProgress) {
this.lastTouch = Date.now();
const resolvedPath = resolve3(file_path);
let key;
try {
key = this.keyFor(resolvedPath);
} catch {
readBytes();
throw new Error(`Cannot stat file: ${resolvedPath}`);
}
const hit = this.entries.get(key);
if (hit) {
this.entries.delete(key);
this.entries.set(key, hit);
return hit;
}
const prime = this.priming.get(key);
if (prime) {
prime.force();
const primed = await prime.promise.catch(() => null);
if (primed) {
this.entries.delete(primed.key);
this.entries.set(primed.key, primed);
return primed;
}
}
const pending = this.inflight.get(key);
if (pending) return pending;
const job = this.ingest(
key,
resolvedPath,
readBytes,
loadDoc,
onProgress
).finally(() => this.inflight.delete(key));
this.inflight.set(key, job);
return job;
}
async ingest(key, resolvedPath, readBytes, loadDoc, onProgress) {
this.ingest_count++;
this.releaseHotIfPressured();
const notify = async (m, p) => {
if (onProgress) {
try {
await onProgress(m, p, 100);
} catch {
}
}
};
await notify("reading file", 2);
const buf = readBytes();
const doc = await loadDoc(buf, {
onPart: onProgress ? async (done, total) => {
const pct = 5 + Math.floor(done / Math.max(1, total) * 65);
await notify(`parsing part ${done}/${total}`, pct);
} : void 0
});
const entry = await this.buildEntry(key, resolvedPath, doc, notify);
this.storeHotDoc(key, doc);
this.scheduleCleanFill(entry, doc);
return entry;
}
/**
* Products of one loaded document: shared by the disk-ingest path and by
* primeFromDoc (which starts from the in-memory post-edit document).
*
* Deliberately does NOT pin the DOM or schedule the clean fill — the caller
* decides. When primeFromDoc's deferred job runs, it may be running because
* takeHotDoc forced it, and takeHotDoc has already cleared the hot slot and
* is about to hand this DOM to a mutating consumer. Pinning here would
* re-publish a DOM that is about to be edited, and scheduleCleanFill's
* registerHotJob would silently no-op (the slot is null), leaving an
* unguarded fill that later extracts the half-edited document and stores it
* as the clean projection of the PRE-edit version.
*/
async buildEntry(key, resolvedPath, doc, notify) {
const n = notify ?? (async () => {
});
await n("projecting text", 75);
const extract_res = _extractTextFromDoc(doc, false, true, true);
await n("paginating", 88);
const raw_bundle = makeBundle(extract_res.text);
await n("building outline", 93);
const outline_nodes = extract_outline2(
doc,
raw_bundle.body,
raw_bundle.pagination.body_pages,
raw_bundle.pagination.body_page_offsets,
extract_res.paragraph_offsets
);
const entry = {
key,
file_path: resolvedPath,
raw_text: extract_res.text,
raw_bundle,
outline_nodes,
clean_text: null,
clean_bundle: null,
clean_outline_nodes: null,
clean_fill: null
};
this.store(entry);
await n("done", 100);
return entry;
}
/**
* Background warm-up of the clean view AFTER the caller's response is
* flushed. The clean extraction is ONE synchronous block (seconds on a
* huge document), so it must not start while requests are still
* arriving — the VVBIG bench caught an innocent warm page-turn stalling
* 2.1 s behind it. Wait for a quiet period (no cache request for
* QUIET_MS), bounded by MAX_WAIT_MS; ensureCleanText sets _fill_forced
* to skip the wait — the clean_view requester pays for clean view,
* nobody else does. Failures leave clean_text null — the on-demand path
* in ensureCleanText rebuilds from bytes instead.
*/
scheduleCleanFill(entry, doc) {
const QUIET_MS = 400;
const MAX_WAIT_MS = 3e4;
let docRef = doc;
entry.clean_fill = (async () => {
try {
const eligibleAt = Date.now();
const started = eligibleAt;
while (!entry._fill_forced && Date.now() - Math.max(this.lastTouch, eligibleAt) < QUIET_MS && Date.now() - started < MAX_WAIT_MS) {
await delay(100);
}
entry.clean_text = _extractTextFromDoc(docRef, true, true);
} catch {
entry.clean_text = null;
} finally {
docRef = null;
entry.clean_fill = null;
}
})();
this.registerHotJob(
doc,
() => {
entry._fill_forced = true;
},
entry.clean_fill
);
}
/**
* After a successful batch write: adopt the in-memory post-edit document
* as the cache state of the OUTPUT file. The DOM is pinned for chained
* edits immediately; the text products are built after a quiet period
* (forced early if a read arrives and joins via the priming map). The
* agent's read-after-edit therefore never re-parses what the server just
* had in memory.
*
* SAFETY GATE: primed products must byte-equal what a fresh parse of the
* written file would produce — guaranteed by the deterministic
* serialize→parse round-trip and enforced by the prime-equivalence tests.
*/
primeFromDoc(file_path, doc) {
this.lastTouch = Date.now();
const resolvedPath = resolve3(file_path);
let key;
try {
key = this.keyFor(resolvedPath);
} catch {
return;
}
this.purgePath(resolvedPath, { keepHot: true });
this.storeHotDoc(key, doc);
let forced = false;
const QUIET_MS = 400;
const MAX_WAIT_MS = 3e4;
const job = (async () => {
const eligibleAt = Date.now();
const started = eligibleAt;
while (!forced && Date.now() - Math.max(this.lastTouch, eligibleAt) < QUIET_MS && Date.now() - started < MAX_WAIT_MS) {
await delay(100);
}
return await this.buildEntry(key, resolvedPath, doc);
})();
const rec = {
promise: job,
force: () => {
forced = true;
}
};
this.priming.set(key, rec);
job.catch(() => {
}).finally(() => {
if (this.priming.get(key) === rec) this.priming.delete(key);
});
this.registerHotJob(doc, rec.force, job);
}
/**
* Clean-view text for an entry: already warm, else await the in-flight
* background fill, else (fill failed / entry from a crashed fill) rebuild
* from bytes without caching a DOM.
*/
async ensureCleanText(entry, readBytes, loadDoc) {
this.lastTouch = Date.now();
if (entry.clean_text !== null) return entry.clean_text;
if (entry.clean_fill) {
entry._fill_forced = true;
await entry.clean_fill;
}
if (entry.clean_text !== null) return entry.clean_text;
const doc = await loadDoc(readBytes());
entry.clean_text = _extractTextFromDoc(doc, true, true);
return entry.clean_text;
}
/** Clean-view bundle, derived once from the clean text. */
async ensureCleanBundle(entry, readBytes, loadDoc) {
if (!entry.clean_bundle) {
entry.clean_bundle = makeBundle(
await this.ensureCleanText(entry, readBytes, loadDoc)
);
}
return entry.clean_bundle;
}
/**
* Clean-view heading map. The raw outline cannot stand in for it: its page
* numbers and CriticMarkup-bearing heading text describe a different
* projection. Python fills outline nodes per VIEW (doc_cache.py:155-188), so
* both engines' clean-view readers get a real heading map.
*
* Costs a parse: the paragraph-offset map the extractor needs references
* live elements from ITS OWN parse, so it can never be derived from the
* cached clean string. Cached on the entry, so at most once per version.
*/
async ensureCleanOutline(entry, readBytes, loadDoc) {
this.lastTouch = Date.now();
if (entry.clean_outline_nodes) return entry.clean_outline_nodes;
const doc = await loadDoc(readBytes());
const extract_res = _extractTextFromDoc(doc, true, true, true);
if (entry.clean_text === null) entry.clean_text = extract_res.text;
if (!entry.clean_bundle) entry.clean_bundle = makeBundle(extract_res.text);
const bundle = entry.clean_bundle;
entry.clean_outline_nodes = extract_outline2(
doc,
bundle.body,
bundle.pagination.body_pages,
bundle.pagination.body_page_offsets,
extract_res.paragraph_offsets
);
return entry.clean_outline_nodes;
}
store(entry) {
for (const [k, e] of this.entries) {
if (e.file_path === entry.file_path && k !== entry.key) {
this.entries.delete(k);
}
}
this.entries.set(entry.key, entry);
while (this.entries.size > this.maxEntries) {
const oldest = this.entries.keys().next().value;
this.entries.delete(oldest);
}
}
clear() {
this.entries.clear();
this.inflight.clear();
this.priming.clear();
this.hot = null;
if (this.hotTimer) {
clearTimeout(this.hotTimer);
this.hotTimer = null;
}
}
};
var docCache = new DocCache(3);
// src/protocol-adapter.ts
var SUPPORTED_PROTOCOL_VERSIONS = [
"2026-07-28",
"2025-11-25",
"2024-11-05"
];
var MODERN_PROTOCOL_VERSION = "2026-07-28";
var META_PROTOCOL_VERSION = "io.modelcontextprotocol/protocolVersion";
var META_CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
var META_LOG_LEVEL = "io.modelcontextprotocol/logLevel";
var META_SERVER_INFO = "io.modelcontextprotocol/serverInfo";
var MCP_ERROR_CODES = {
INVALID_PARAMS: -32602,
HEADER_MISMATCH: -32020,
MISSING_REQUIRED_CLIENT_CAPABILITY: -32021,
UNSUPPORTED_PROTOCOL_VERSION: -32022,
LEGACY_RESOURCE_NOT_FOUND: -32002
};
var LOG_LEVELS = [
"debug",
"info",
"notice",
"warning",
"error",
"critical",
"alert",
"emergency"
];
var DEFAULT_TTL_MS = 36e5;
var CACHE_POLICY = {
// Static lists identical for every caller -> "public" (spec §Choosing a Cache Scope)
"server/discover": { ttlMs: DEFAULT_TTL_MS, cacheScope: "public" },
"tools/list": { ttlMs: DEFAULT_TTL_MS, cacheScope: "public" },
"prompts/list": { ttlMs: DEFAULT_TTL_MS, cacheScope: "public" },
"resources/list": { ttlMs: DEFAULT_TTL_MS, cacheScope: "public" },
"resources/templates/list": { ttlMs: DEFAULT_TTL_MS, cacheScope: "public" },
// Reads may become document-derived; stay conservative
"resources/read": { ttlMs: 6e4, cacheScope: "private" }
};
var UI_EXTENSION_CAPABILITY = {
"io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] }
};
function readServerCapabilities(server2) {
let caps = null;
try {
const rawCaps = server2?.server?.getCapabilities?.();
if (rawCaps && typeof rawCaps === "object" && !Array.isArray(rawCaps)) {
caps = rawCaps;
}
} catch {
caps = null;
}
if (!caps) {
caps = {
tools: { listChanged: true },
resources: { listChanged: true }
};
}
const existingExt = caps.extensions && typeof caps.extensions === "object" && !Array.isArray(caps.extensions) ? caps.extensions : {};
return structuredClone({
...caps,
extensions: {
...existingExt,
...UI_EXTENSION_CAPABILITY
}
});
}
function sortToolsDeterministically(tools) {
return [...tools].sort((a, b) => {
const x = typeof a?.name === "string" ? a.name : "";
const y = typeof b?.name === "string" ? b.name : "";
return x < y ? -1 : x > y ? 1 : 0;
});
}
var SCHEMA_VALUED_KEYWORDS = /* @__PURE__ */ new Set([
"additionalItems",
"additionalProperties",
"contains",
"contentSchema",
"else",
"if",
"items",
"not",
"propertyNames",
"then",
"unevaluatedItems",
"unevaluatedProperties"
]);
var SCHEMA_ARRAY_KEYWORDS = /* @__PURE__ */ new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
"$defs",
"definitions",
"dependentSchemas",
"patternProperties",
"properties"
]);
function stripJsonSchemaDialect(schema) {
if (Array.isArray(schema)) {
return schema.map((item) => stripJsonSchemaDialect(item));
}
if (!schema || typeof schema !== "object") return schema;
const out = {};
for (const [key, value] of Object.entries(schema)) {
if (key === "$schema") continue;
if (SCHEMA_VALUED_KEYWORDS.has(key) || SCHEMA_ARRAY_KEYWORDS.has(key)) {
out[key] = stripJsonSchemaDialect(value);
} else if (SCHEMA_MAP_KEYWORDS.has(key)) {
if (value && typeof value === "object" && !Array.isArray(value)) {
const mapped = {};
for (const [name, sub] of Object.entries(value)) {
mapped[name] = stripJsonSchemaDialect(sub);
}
out[key] = mapped;
} else {
out[key] = value;
}
} else {
out[key] = value;
}
}
return out;
}
function stripToolSchemaDialects(tools) {
return tools.map((tool) => {
if (!tool || typeof tool !== "object" || Array.isArray(tool)) return tool;
const t = tool;
let next;
for (const field of ["inputSchema", "outputSchema"]) {
const schema = t[field];
if (!schema || typeof schema !== "object" || Array.isArray(schema)) continue;
next ??= { ...t };
next[field] = stripJsonSchemaDialect(schema);
}
return next ?? tool;
});
}
function inferCachePolicy(result) {
if (Array.isArray(result.tools)) return CACHE_POLICY["tools/list"];
if (Array.isArray(result.resourceTemplates))
return CACHE_POLICY["resources/templates/list"];
if (Array.isArray(result.resources)) return CACHE_POLICY["resources/list"];
if (Array.isArray(result.prompts)) return CACHE_POLICY["prompts/list"];
if (Array.isArray(result.contents)) return CACHE_POLICY["resources/read"];
return void 0;
}
var ProtocolAdapter = class {
serverName;
serverVersion;
options;
pendingMethods = /* @__PURE__ */ new Map();
constructor(serverName, serverVersion, options = {}) {
this.serverName = serverName;
this.serverVersion = serverVersion;
this.options = options;
}
get pendingRequestCount() {
return this.pendingMethods.size;
}
errorResponse(id, code, message, data) {
return {
action: "respond",
message: {
jsonrpc: "2.0",
id,
error: {
code,
message,
...data !== void 0 ? { data } : {}
}
}
};
}
/**
* Transforms an outgoing JSON-RPC result or error response to ensure 2026-07-28 spec compliance.
*/
transformOutgoingMessage(msg) {
if (!msg || typeof msg !== "object") return msg;
if (msg.error && typeof msg.error === "object") {
if (msg.id !== void 0 && msg.id !== null) {
this.pendingMethods.delete(msg.id);
}
if (msg.error.code === MCP_ERROR_CODES.LEGACY_RESOURCE_NOT_FOUND) {
return {
...msg,
error: {
...msg.error,
code: MCP_ERROR_CODES.INVALID_PARAMS
}
};
}
return msg;
}
if (!msg.result || typeof msg.result !== "object" || Array.isArray(msg.result)) {
return msg;
}
const method = msg.id !== void 0 && msg.id !== null ? this.pendingMethods.get(msg.id) : void 0;
if (msg.id !== void 0 && msg.id !== null) {
this.pendingMethods.delete(msg.id);
}
const result = { ...msg.result };
if (!("resultType" in result)) {
result.resultType = "complete";
}
const meta = result._meta && typeof result._meta === "object" && !Array.isArray(result._meta) ? { ...result._meta } : {};
if (!meta[META_SERVER_INFO]) {
meta[META_SERVER_INFO] = {
name: this.serverName,
version: this.serverVersion
};
}
result._meta = meta;
if (Array.isArray(result.tools)) {
result.tools = stripToolSchemaDialects(sortToolsDeterministically(result.tools));
}
if (result.resultType === "complete") {
const policy = method ? CACHE_POLICY[method] : inferCachePolicy(result);
if (policy) {
if (!("ttlMs" in result)) result.ttlMs = policy.ttlMs;
if (!("cacheScope" in result)) result.cacheScope = policy.cacheScope;
}
}
return {
...msg,
result
};
}
/**
* Validates an incoming JSON-RPC request message according to 2026-07-28 spec rules.
* Returns AdapterDecision indicating whether to pass or respond.
*/
validateIncomingRequest(msg) {
if (!msg || typeof msg !== "object" || Array.isArray(msg) || msg.jsonrpc !== "2.0" || typeof msg.method !== "string") {
return { action: "pass" };
}
const isRequest = msg.id !== void 0 && msg.id !== null;
if (!isRequest) {
return { action: "pass" };
}
const id = msg.id;
const method = msg.method;
const params = msg.params;
const meta = params?._meta && typeof params._meta === "object" && !Array.isArray(params._meta) ? params._meta : void 0;
if (meta && META_PROTOCOL_VERSION in meta) {
const version = meta[META_PROTOCOL_VERSION];
if (typeof version !== "string" || !SUPPORTED_PROTOCOL_VERSIONS.includes(version)) {
return this.errorResponse(
id,
MCP_ERROR_CODES.UNSUPPORTED_PROTOCOL_VERSION,
`Unsupported protocol version: ${version}. Supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")}`,
{
requested: version,
supported: [...SUPPORTED_PROTOCOL_VERSIONS]
}
);
}
if (version === MODERN_PROTOCOL_VERSION) {
const clientCaps = meta[META_CLIENT_CAPABILITIES];
if (!(META_CLIENT_CAPABILITIES in meta) || !clientCaps || typeof clientCaps !== "object" || Array.isArray(clientCaps)) {
return this.errorResponse(
id,
MCP_ERROR_CODES.INVALID_PARAMS,
"Missing required _meta parameter: io.modelcontextprotocol/clientCapabilities"
);
}
}
if (META_LOG_LEVEL in meta) {
const logLevel = meta[META_LOG_LEVEL];
if (typeof logLevel !== "string" || !LOG_LEVELS.includes(logLevel)) {
return this.errorResponse(
id,
MCP_ERROR_CODES.INVALID_PARAMS,
`Invalid log level: ${logLevel}. Supported: ${LOG_LEVELS.join(", ")}`
);
}
}
}
if (method === "server/discover") {
return {
action: "respond",
message: this.buildDiscoverResponse(id)
};
}
this.pendingMethods.set(id, method);
while (this.pendingMethods.size > 512) {
const firstKey = this.pendingMethods.keys().next().value;
if (firstKey !== void 0) {
this.pendingMethods.delete(firstKey);
}
}
return { action: "pass" };
}
buildDiscoverResponse(id) {
const caps = this.options.getCapabilities?.() ?? readServerCapabilities(null);
return {
jsonrpc: "2.0",
id,
result: {
resultType: "complete",
supportedVersions: [...SUPPORTED_PROTOCOL_VERSIONS],
protocolVersions: [...SUPPORTED_PROTOCOL_VERSIONS],
capabilities: caps,
serverInfo: {
name: this.serverName,
version: this.serverVersion
},
_meta: {
"io.modelcontextprotocol/serverInfo": {
name: this.serverName,
version: this.serverVersion
}
},
ttlMs: DEFAULT_TTL_MS,
cacheScope: "public"
}
};
}
};
function attachProtocolAdapter(server2, transport, serverName, serverVersion) {
const downstream = transport.onmessage;
if (typeof downstream !== "function") {
throw new Error(
"attachProtocolAdapter must be called AFTER server.connect(transport): the MCP SDK chains onmessage handlers, so a pre-connect wrapper cannot suppress SDK handling and every intercepted request would be answered twice."
);
}
const adapter = new ProtocolAdapter(serverName, serverVersion, {
getCapabilities: () => readServerCapabilities(server2)
});
const originalSend = transport.send.bind(transport);
transport.send = async (message, options) => {
const transformed = adapter.transformOutgoingMessage(message);
return originalSend(transformed, options);
};
transport.onmessage = (message, extra) => {
const decision = adapter.validateIncomingRequest(message);
if (decision.action === "respond") {
transport.send(decision.message).catch((err) => {
transport.onerror?.(
err instanceof Error ? err : new Error(String(err))
);
});
return;
}
downstream(message, extra);
};
return adapter;
}
// src/path-policy.ts
import fs from "fs";
import { randomUUID } from "crypto";
import {
basename as basename3,
delimiter,
dirname,
extname,
isAbsolute,
join,
parse,
resolve as resolve4
} from "path";
import { fromFdPromise } from "yauzl";
var openEndings = [".docx", ".docm", ".dotx", ".dotm"];
var wordEndings = [...openEndings, ".doc", ".dot"];
var restrictedEndings = [".docm", ".dotm", ".dotx", ".dot"];
var windows = process.platform === "win32";
var PathRefusal = class extends Error {
};
function refuse(path, reason, advice) {
throw new PathRefusal(`Refused '${path}': ${reason}. ${advice}.`);
}
function ordinaryPath(path) {
if (!path || path.includes("\0"))
refuse(path, "invalid file path", "Supply a filename");
if (!windows) return path;
const name = path.replaceAll("/", "\\").replace(/^\\\\\?\\UNC\\/i, "\\\\").replace(/^\\\\\?\\(?=[a-z]:\\)/i, "");
const reserved = /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|(?:COM|LPT)[1-9\u00b9\u00b2\u00b3]) *(?:\.|$)/i;
const components = name.replace(/^[a-z]:/i, "").split("\\");
if (/^(?:\\\\[?.]\\|\\\?\?\\)/.test(name) || /^\\\\[^\\]+\\(?:PIPE|MAILSLOT)(?:\\|$)/i.test(name) || name.replace(/^[a-z]:/i, "").includes(":") || components.some(
(part) => part !== "." && part !== ".." && (/[. ]$/.test(part) || reserved.test(part))
)) {
refuse(
path,
"Windows treats this as a device or ambiguous filename",
"Use an ordinary filename without extra colons or trailing dots or spaces"
);
}
return name;
}
function sameFolder(first, second) {
const a = dirname(first);
const b = dirname(second);
if (a === b) return true;
if (!windows) return false;
const left = fs.statSync(a, { bigint: true, throwIfNoEntry: false });
const right = fs.statSync(b, { bigint: true, throwIfNoEntry: false });
return !!left && !!right && left.ino !== 0n && left.ino === right.ino && left.dev === right.dev;
}
function canonicalPath(path, strict = false, base = process.cwd(), links = 0) {
path = ordinaryPath(path);
if (links > 40) refuse(path, "too many symbolic links", "Use a direct path");
const root = parse(path).root;
let current = root ? resolve4(base, root) : base;
for (const part of path.slice(root.length).split(windows ? /[\\/]/ : "/")) {
if (!part || part === ".") continue;
const parent = fs.lstatSync(current, { throwIfNoEntry: strict });
if (parent && !parent.isDirectory()) {
if (strict)
throw Object.assign(new Error("Invalid parent folder"), {
code: "ENOTDIR"
});
refuse(path, "invalid parent folder", "Choose an accessible folder");
}
if (part === "..") {
current = dirname(current);
continue;
}
const child = join(current, part);
const stat = fs.lstatSync(child, { throwIfNoEntry: strict });
if (stat?.isSymbolicLink()) {
current = canonicalPath(
fs.readlinkSync(child),
strict,
current,
links + 1
);
} else {
current = stat?.isFile() || stat?.isDirectory() ? fs.realpathSync.native(child) : child;
}
}
return ordinaryPath(current);
}
function readAllowedFolders(value) {
const entries = value.split(delimiter).filter((entry) => entry.trim());
if (!entries.length)
throw new Error("ADEU_ALLOWED_DIRS is set but contains no folders.");
const roots = entries.map((entry) => {
const prefix = `ADEU_ALLOWED_DIRS entry '${entry}'`;
if (!isAbsolute(entry) || windows && parse(entry).root.length === 1)
throw new Error(`${prefix} is relative. Use an absolute folder path.`);
let path;
let stat;
try {
path = canonicalPath(entry, true);
stat = fs.statSync(path, { bigint: true });
} catch (error) {
const code = error.code;
if (code === "ENOENT") throw new Error(`${prefix} does not exist.`);
if (code === "ENOTDIR") throw new Error(`${prefix} is not a folder.`);
throw new Error(`${prefix} cannot be resolved.`);
}
if (!stat.isDirectory()) throw new Error(`${prefix} is not a folder.`);
return { path, ino: stat.ino, dev: stat.dev };
});
const listing = roots.map((root) => root.path).join(delimiter);
return {
listing,
resolve(path) {
try {
const target = canonicalPath(path);
for (let dir = target; ; dir = dirname(dir)) {
const stat = fs.statSync(dir, {
bigint: true,
throwIfNoEntry: false
});
if (stat?.isDirectory() && roots.some(
(root) => root.ino ? root.ino === stat.ino && root.dev === stat.dev : stat.ino === 0n && root.path === dir
))
return target;
if (dirname(dir) === dir) break;
}
} catch {
}
throw new PathRefusal(`File access refused. Allowed folders: ${listing}`);
}
};
}
var allowedFolders = (() => {
const value = process.env.ADEU_ALLOWED_DIRS;
if (value === void 0) return void 0;
try {
const folders = readAllowedFolders(value);
console.error(`ADEU_ALLOWED_DIRS allowed folders: ${folders.listing}`);
return folders;
} catch (error) {
console.error(error.message);
process.exit(1);
}
})();
function listDocumentSiblings(dir) {
const folder = allowedFolders ? allowedFolders.resolve(dir) : dir;
const names = fs.readdirSync(folder).filter((name) => name.toLowerCase().endsWith(".docx"));
if (!allowedFolders) return names;
return names.filter((name) => {
try {
allowedFolders.resolve(join(folder, name));
return true;
} catch {
return false;
}
});
}
async function packageKind(path) {
const { O_RDONLY, O_NONBLOCK, O_NOFOLLOW } = fs.constants;
const fd = fs.openSync(
path,
O_RDONLY | (O_NONBLOCK ?? 0) | (O_NOFOLLOW ?? 0)
);
try {
if (!fs.fstatSync(fd).isFile())
refuse(path, "not a regular file", "Use a regular Word document");
const archive = await fromFdPromise(fd, {
autoClose: false,
decodeStrings: false,
validateEntrySizes: false
});
let types = false;
let main2 = false;
for await (const entry of archive.eachEntry()) {
const name = entry.fileNameRaw.toString("latin1");
if (name === "[Content_Types].xml") types = true;
if (name === "word/document.xml") main2 = true;
}
return types && main2 ? "word" : "other";
} catch (err) {
if (err instanceof PathRefusal || err.code)
throw err;
return "invalid";
} finally {
fs.closeSync(fd);
}
}
async function checkToolPath(path, use, inputs = []) {
try {
const target = allowedFolders ? allowedFolders.resolve(path) : canonicalPath(path);
const stat = fs.lstatSync(target, { throwIfNoEntry: false });
if (use === "source") {
return stat || allowedFolders ? target : path;
}
const ext = extname(target).toLowerCase();
if (stat && !stat.isFile())
refuse(
path,
"not a regular file",
"Use a regular Word document or a new output filename"
);
if (use === "open") {
if (!stat || !openEndings.includes(ext) || await packageKind(target) !== "word") {
refuse(
path,
"opening requires an existing Word package",
"Choose a regular .docx, .docm, .dotx or .dotm Word document"
);
}
return target;
}
const sources = inputs.map(
(input) => allowedFolders ? allowedFolders.resolve(input) : canonicalPath(input)
);
const matching = sources.filter(
(source) => extname(source).toLowerCase() === ext
);
if (use === "pdf" ? ext !== ".pdf" : !ext || ext === ".pdf" || ext !== ".docx" && !matching.length) {
refuse(
path,
"the output ending is not permitted",
use === "pdf" ? "Use .pdf for the PDF output" : "Use .docx or the input document's ending"
);
}
if (restrictedEndings.includes(ext) && !matching.some((source) => sameFolder(source, target))) {
refuse(
path,
"this ending is restricted to the input document's folder",
"Use .docx here or save beside the input with that ending"
);
}
if (!stat || !stat.size) return target;
const kind = await packageKind(target);
if (kind === "word" || kind === "invalid" && wordEndings.includes(ext) && sources.some((source) => sameFolder(source, target)))
return target;
refuse(
path,
"the existing file is not a Word package",
"Choose a new filename or an empty regular file"
);
} catch (err) {
if (err instanceof PathRefusal) throw err;
refuse(
path,
`the path could not be checked (${err.code ?? "filesystem error"})`,
"Use an accessible regular file or a new output filename"
);
}
}
function defaultOutputPath(source, suffix) {
if (suffix === "redlined") {
const name = basename3(source);
const dot = name.lastIndexOf(".");
const stem2 = dot === -1 ? name : name.slice(0, dot);
return stem2.endsWith("_redlined") || stem2.endsWith("_processed") ? source : join(dirname(source), `${stem2}_redlined.docx`);
}
const ext = extname(source);
const stem = basename3(source, ext);
if (suffix === "processed" && /(?:_|-|\.)(processed|redlined|redline|markup|marked)$/i.test(stem))
return resolve4(dirname(source), `${stem}${ext}`);
return resolve4(dirname(source), `${stem}_${suffix}${ext}`);
}
function diagnosticPath(output) {
return join(
dirname(output),
`${basename3(output, extname(output))}.unverified.docx`
);
}
var toolPaths = {
read_docx: { inputs: ["file_path"] },
process_document_batch: {
inputs: ["original_docx_path"],
output: "output_path",
defaultOutput: "processed"
},
accept_all_changes: {
inputs: ["docx_path"],
output: "output_path",
defaultOutput: "clean"
},
diff_docx_files: {
inputs: ["original_path", "modified_path"],
output: "output_path"
},
finalize_document: {
inputs: ["file_path"],
output: "output_path",
defaultOutput: "final"
},
apply_text_revision: {
inputs: ["file_path"],
output: "output_path",
defaultOutput: "redlined"
}
};
async function checkToolArguments(tool, args) {
const policy = toolPaths[tool];
if (!policy) return args;
const checked = { ...args };
const sources = [];
for (const key of policy.inputs) {
const source = await checkToolPath(args[key], "source");
checked[key] = source;
sources.push(source);
}
if (policy.output) {
let output = args[policy.output];
if (allowedFolders) {
if (output === void 0 && policy.defaultOutput)
output = defaultOutputPath(sources[0], policy.defaultOutput);
if (output !== void 0) {
output = allowedFolders.resolve(output);
if (policy.defaultOutput === "redlined")
allowedFolders.resolve(diagnosticPath(output));
}
}
if (output !== void 0)
checked[policy.output] = await checkToolPath(output, "write", sources);
}
return checked;
}
async function writeToolDocument(path, data, inputs) {
const target = await checkToolPath(path, "write", inputs);
const existing = fs.lstatSync(target, { throwIfNoEntry: false });
const parent = dirname(target);
fs.mkdirSync(parent, { recursive: true });
if (!existing) {
fs.writeFileSync(target, data, { flag: "wx" });
} else {
const temporary = join(parent, `.adeu-${randomUUID()}.docx`);
const fd = fs.openSync(temporary, "wx", existing.mode & 511);
try {
try {
fs.writeFileSync(fd, data);
} finally {
fs.closeSync(fd);
}
fs.renameSync(temporary, target);
} finally {
fs.rmSync(temporary, { force: true });
}
}
return { path: target, existedBefore: !!existing };
}
// src/index.ts
var MATCH_MODE_SYNONYMS = {
strict: "strict",
first: "first",
all: "all",
first_only: "first",
firstonly: "first",
"first-only": "first",
all_occurrences: "all",
alloccurrences: "all",
"all-occurrences": "all",
every: "all"
};
function coerceChangeItemInPlace(item) {
if (item === null || typeof item !== "object" || Array.isArray(item)) return;
if (!("type" in item) || item.type === void 0 || item.type === null) {
if ("cells" in item) item.type = "insert_row";
else if ("text" in item && "target_id" in item) item.type = "reply";
else if ("target_text" in item && "new_text" in item) item.type = "modify";
else if ("field" in item && "value" in item) item.type = "set_field";
}
if ("match_mode" in item) {
const raw = item.match_mode;
if (typeof raw !== "string") {
delete item.match_mode;
} else {
const key = raw.trim().toLowerCase();
const mapped = Object.hasOwn(MATCH_MODE_SYNONYMS, key) ? MATCH_MODE_SYNONYMS[key] : void 0;
if (mapped === void 0) delete item.match_mode;
else item.match_mode = mapped;
}
}
if (item.type === "modify" && (item.new_text === void 0 || item.new_text === null)) {
const target = item.target_text;
const comment = item.comment;
const has_comment = typeof comment === "string" && comment.trim() || Array.isArray(comment) && comment.some(
(c) => c && typeof c.text === "string" && c.text.trim()
);
if (typeof target === "string" && target && has_comment) {
item.new_text = target;
}
}
if (Array.isArray(item.comment)) {
item[COMMENT_LIST_KEY] = item.comment;
delete item.comment;
}
}
var COMMENT_LIST_KEY = "__adeu_comment_list";
function restoreCommentListInPlace(item) {
if (item !== null && typeof item === "object" && COMMENT_LIST_KEY in item) {
item.comment = item[COMMENT_LIST_KEY];
delete item[COMMENT_LIST_KEY];
}
}
var NOT_FOUND_SUGGESTION_CAP = 10;
function closestFilenames(requested, candidates) {
const req = requested.toLowerCase();
const score = (name) => {
const cand = name.toLowerCase();
let prefix = 0;
while (prefix < req.length && prefix < cand.length && req[prefix] === cand[prefix]) {
prefix++;
}
const stem = req.replace(/\.docx$/, "");
return prefix * 100 + (stem && cand.includes(stem) ? 50 : 0);
};
return [...candidates].sort((a, b) => score(b) - score(a) || a.localeCompare(b)).slice(0, NOT_FOUND_SUGGESTION_CAP);
}
function readFileBytesOrThrow(filePath) {
try {
return readFileSync(filePath);
} catch (err) {
if (err.code === "ENOENT") {
let available = "";
try {
const dir = dirname2(filePath);
const docs = listDocumentSiblings(dir);
if (docs.length) {
const shown = closestFilenames(basename4(filePath), docs);
available = ` available files: [${shown.join(", ")}]`;
if (docs.length > shown.length) {
available += ` (+${docs.length - shown.length} more in ${dir})`;
}
} else {
available = ` (no .docx files found in ${dir})`;
}
} catch {
}
const hint = isAbsolute2(filePath) ? "" : " Provide an absolute path \u2014 the server cannot resolve relative paths.";
throw new Error(`file not found: ${filePath};${available}${hint}`);
}
throw err;
}
}
function overwriteNote(outPath, inputPath, existedBefore) {
if (!existedBefore) return "";
if (resolve5(outPath) === resolve5(inputPath)) {
return `
Note: the source document at ${outPath} was overwritten in place.`;
}
return `
Note: replaced existing file ${outPath}.`;
}
function isSameFile(a, b) {
try {
if (existsSync(a) && existsSync(b)) {
const sa = fs2.statSync(a, { bigint: true });
const sb = fs2.statSync(b, { bigint: true });
if (sa.dev === sb.dev && sa.ino === sb.ino) return true;
}
} catch {
}
return resolve5(a) === resolve5(b);
}
async function loadDocxOrThrow(buf, filePath, opts) {
try {
return await DocumentObject3.load(buf, opts);
} catch (err) {
throw new Error(
`'${filePath}' is not a valid .docx (Word) document: ${err?.message ?? err}`
);
}
}
var DIST_DIR = import.meta.dirname;
function getAssetContent(folder, filename, fallbackMessage) {
const filePath = join2(DIST_DIR, folder, filename);
if (existsSync(filePath)) {
return readFileSync(filePath, "utf-8");
}
return fallbackMessage;
}
var READ_DOCX_COMMON_DESC = "Reads a DOCX file. Returns text with inline CriticMarkup for Tracked Changes and Comments: {++inserted++}, {--deleted--}, {==highlighted==}{>>comment<<}. Set clean_view=True for the finalized 'Accepted' text without markup.\n\n";
async function mcpFieldsBanner(file_path) {
return banner_for_path(
file_path,
fields_discovery_hint(),
async (p) => loadDocxOrThrow(readFileSync(p), p)
);
}
var READ_DOCX_TAIL = "Modes:\n- 'full' (default): paginated body content. Use page=N to navigate.\n- 'outline': heading map only \u2014 start here for large docs to plan targeted reads. Defaults to L1-L2 headings; pass outline_max_level=3-6 to see deeper structure.\n- 'appendix': defined terms, anchors, and cross-reference targets. Consult before editing legal/technical docs to avoid breaking references.\n- 'changes' (mode='changes'): a ledger of every tracked change and comment (id, type, author, page, snippet) \u2014 start here for review work instead of reading pages. Filter with changes_author, page, and changes_offset.\n- 'fields' (mode='fields'): a ledger of every content control (ordinal, class, alias/tag, location, lock/binding state, current value) \u2014 start here to discover fillable fields. Paginate with fields_offset; `page` and `search_query` do not apply.\n\n`page`: a positive integer (1-indexed, default 1), a page RANGE like '2-6' (returns up to 8 pages in one call, then names the next range), or 'all'. Pages are synthetic length-based chunks sized for LLM consumption, NOT printed Word pages. In mode='full', page='all' returns the whole body with no page chrome; when over the response budget, it serves the first pages that fit plus an L1 outline and continuation hint unless force=true. With `search_query`, `page` instead restricts matches to that page or 'N-M' page range (default: search all pages).";
var PROCESS_BATCH_COMMON_DESC = "Applies a batch of edits and review actions to a DOCX.\n\nBatches apply SEQUENTIALLY: each change validates against state from prior changes. Valid changes apply when others fail (salvage default): response LEADS with `PARTIAL: applied K of N` listing unapplied changes. Pass partial=false for all-or-nothing.\n\n";
var PROCESS_BATCH_OPERATIONS_DESC = "Each item in `changes` needs a `type`:\n1. 'modify': search-and-replace. `target_text` must match uniquely (`match_mode`:'strict', default) \u2014 add context or set `match_mode`:'first'/'all' or `regex`:true ($1, $2\u2026 in `new_text`). `new_text` supports '#'\u2013'######' headings, '**bold**', '_italic_', '\\n\\n' splits, and pipe tables (`| H1 | H2 |\\n|---|---|\\n| A | B |`). Omit `new_text` (with `comment`) to annotate; empty string deletes. Never write CriticMarkup \u2014 use `comment` (string or `[{text, author?}]`).\n \u2022 EMPTY CELLS: blank cells carry `{#cell:<id>}` anchors \u2014 set `target_text` to the anchor and value in `new_text`.\n2. 'accept'/'reject': finalize or revert by `target_id` ('Chg:12'); add `part` ('word/header1.xml') when the id exists in several parts.\n3. 'reply': reply to `target_id` ('Com:5') with `text`.\n4. 'set_field': fill a form field \u2014 `field` is 'CC:<N>', tag or alias, `value` the text (list via `read_docx` `mode`:'fields'; checkboxes true/false, dates YYYY-MM-DD, dropdowns a listed option). Updates bound stores; locked/protected controls refuse and name the override.\n5. 'insert_row': add table row (`target_text` anchor, `cells` array left-to-right, `position` 'above'/'below'). 'delete_row': remove row matching `target_text`. Disk mode only.\n\nID VOLATILITY: 'Chg:N'/'Com:N' shift between states \u2014 call `read_docx` before accept/reject/reply.\n\n`markup_mode`:'manual' writes strikethrough/underline + comments instead of Track Changes. `commented_change_granularity`:'word' word-splits commented edits under one spanning comment.\n`author_name` sets attribution; default 'Adeu AI (TS)'.";
var DIFF_DOCX_DESC = "Compares two DOCX files and returns a compact `@@ Word Patch @@` diff \u2014 Adeu's token-level, sub-word patch format \u2014 of their text content. Useful for analyzing differences between versions before editing.\n\nPass `output_path` (and optional `author_name`) to also write the comparison as a tracked-changes .docx of original_path in one step \u2014 the recommended way to make a redline between two versions; never hand-build compare batches. All or nothing: if any change cannot be tracked, nothing is written. output_path may not be either input.";
var gitSha = "989ccb3";
var packageVersion = "4.2.0";
var buildTag = ` [Adeu v${packageVersion}+${gitSha}]`;
var server = new McpServer({
name: "adeu-redlining-service",
version: packageVersion
});
var originalRegisterTool = server.registerTool.bind(server);
server.registerTool = (name, schema, handler) => {
if (schema && typeof schema === "object") {
if (schema.description && !schema.description.includes(buildTag.trim())) {
schema.description = schema.description.trim() + buildTag;
}
}
return originalRegisterTool(name, schema, async (args, extra) => {
try {
return await handler(await checkToolArguments(name, args), extra);
} catch (error) {
return { isError: true, content: [{ type: "text", text: error.message }] };
}
});
};
var registerAppTool = (mcpServer, name, schema, handler) => {
if (schema && typeof schema === "object") {
if (schema.description) {
schema.description = schema.description.trim() + buildTag;
}
}
return origRegisterAppTool(mcpServer, name, schema, handler);
};
var UI_CSP = {
connectDomains: ["https://fonts.googleapis.com", "https://fonts.gstatic.com"],
resourceDomains: [
"https://fonts.googleapis.com",
"https://fonts.gstatic.com"
]
};
registerAppResource(
server,
MARKDOWN_UI_URI,
MARKDOWN_UI_URI,
{ mimeType: RESOURCE_MIME_TYPE, description: "Adeu Markdown Viewer UI" },
async () => {
let html = getAssetContent(
"templates",
"markdown_ui.html",
"<html><body>UI Template Not Found</body></html>"
);
const markedJs = getAssetContent(
"assets",
"marked.min.js",
"window.__MARKED_ERROR = 'marked.min.js not found';"
);
const svg = getAssetContent("assets", "adeu.svg", "");
html = html.replace("[[marked_js_code | safe]]", markedJs).replace("[[ adeu_svg_code ]]", svg);
return {
contents: [
{
uri: MARKDOWN_UI_URI,
mimeType: RESOURCE_MIME_TYPE,
text: html,
_meta: { ui: { csp: UI_CSP } }
}
]
};
}
);
var READ_DOCX_OUTPUT_SCHEMA = z.object({
markdown: z.string().describe("Document content as Markdown, for display."),
title: z.string().optional().describe("Display title (the file name, or 'Search: <file name>')."),
file_path: z.string().optional().describe("Absolute path of the document that was read.")
}).loose();
registerAppTool(
server,
"read_docx",
{
title: "Read DOCX",
description: READ_DOCX_COMMON_DESC + READ_DOCX_TAIL,
inputSchema: z.object({
reasoning: z.string().optional().describe(
"Why do I need to read this docx document? State this reason before any other parameter."
),
file_path: z.string().describe("Absolute path to the DOCX file."),
clean_view: z.boolean().default(false).describe(
"If False (default), returns the 'Raw' text with inline CriticMarkup. If True, returns 'Accepted' text."
),
mode: z.enum(["full", "outline", "appendix", "changes", "fields"]).default("full").describe(
"'full' returns body content. 'outline' returns a structural heading map. 'appendix' returns defined terms. 'changes' returns tracked changes and comments ledger. 'fields' returns the content-control ledger."
),
// ONE published JSON type (string) — real MCP clients strip
// property-level anyOf/oneOf to {}, losing the type and docs entirely
// (QA 2026-07-23 client-compat test 2). Numbers still arrive at
// runtime and are coerced to their string form before validation; the
// operative guidance lives in the tool description because clients
// also drop optional-parameter descriptions.
page: z.preprocess(
(v) => typeof v === "number" && Number.isFinite(v) ? String(v) : v,
z.string().describe(
"Positive integer (1-indexed, defaults to 1) or 'all'. See the tool description for the full behavior per mode."
)
).optional(),
force: z.boolean().default(false).describe(
"For mode='full' with page='all': read the whole document even when it exceeds the response budget."
),
outline_max_level: z.coerce.number().default(2).describe("For mode='outline' only: cap on heading depth."),
outline_verbose: z.boolean().default(false).describe("For mode='outline' only: includes metadata."),
changes_author: z.string().optional().describe(
"For mode='changes' only: filter tracked changes ledger by author name."
),
changes_offset: z.coerce.number().int().default(0).describe(
"For mode='changes' only: entry offset for paginating tracked changes ledger."
),
fields_offset: z.coerce.number().int().default(0).describe(
"For mode='fields' only: entry offset for paginating the content-control ledger."
),
search_query: z.string().optional().describe(
"The substring or regex pattern to search for. When provided, filters results to matching paragraphs."
),
search_regex: z.boolean().default(false).describe(
"Set to true to interpret search_query as a regular expression."
),
search_case_sensitive: z.boolean().default(true).describe("Set to false to perform case-insensitive matching."),
max_matches: z.coerce.number().int().default(20).describe(
"For search queries: maximum number of search matches to return (default 20)."
),
match_offset: z.coerce.number().int().default(0).describe(
"For search queries: 0-based match offset to start search results from for pagination (default 0)."
),
full_paragraph: z.boolean().default(false).describe(
"For search queries: return full paragraph for search matches instead of clamping snippets to \xB1120 chars."
)
}),
outputSchema: READ_DOCX_OUTPUT_SCHEMA,
_meta: { ui: { resourceUri: MARKDOWN_UI_URI } }
},
async ({
reasoning,
file_path,
clean_view,
mode,
page,
force,
outline_max_level,
outline_verbose,
search_query,
search_regex,
search_case_sensitive,
max_matches,
match_offset,
full_paragraph,
changes_author,
changes_offset,
fields_offset
}, extra) => {
try {
void reasoning;
const readBytes = () => readFileBytesOrThrow(file_path);
const progressToken = extra?._meta?.progressToken;
const onProgress = progressToken !== void 0 && extra?.sendNotification ? async (message, progress, total) => {
try {
await extra.sendNotification({
method: "notifications/progress",
params: { progressToken, progress, total, message }
});
} catch {
}
} : void 0;
const loadDoc = (buf, opts) => loadDocxOrThrow(buf, file_path, opts);
const getEntry = () => docCache.get(file_path, readBytes, loadDoc, onProgress);
if (mode === "outline") {
if (!clean_view) {
const entry2 = await getEntry();
const res3 = render_outline_response(
entry2.outline_nodes,
entry2.raw_bundle.pagination.total_pages,
file_path,
outline_max_level,
outline_verbose
);
return res3;
}
const buf = readBytes();
const doc = await loadDocxOrThrow(buf, file_path);
const extract_res = _extractTextFromDoc2(
doc,
clean_view,
true,
true
);
const res2 = build_outline_response(
doc,
extract_res.text,
file_path,
outline_max_level,
outline_verbose,
extract_res.paragraph_offsets
);
return res2;
}
const entry = await getEntry();
const text = clean_view ? await docCache.ensureCleanText(entry, readBytes, loadDoc) : entry.raw_text;
const bundle = clean_view ? await docCache.ensureCleanBundle(entry, readBytes, loadDoc) : entry.raw_bundle;
if (search_query !== void 0 && search_query !== null) {
let searchPage = page;
if (typeof page === "string") {
const sClean = page.trim().replace(/^['"]+|['"]+$/g, "").trim();
if (sClean.includes("-")) {
try {
const [pKind, pVal] = parse_page_arg2(sClean);
if (pKind === "range") {
searchPage = pVal;
}
} catch {
}
}
}
const res2 = build_search_response(
text,
search_query,
search_regex,
search_case_sensitive,
searchPage,
file_path,
bundle,
{ max_matches, match_offset, full_paragraph }
);
return res2;
}
if (mode === "changes") {
if (clean_view) {
return {
isError: true,
content: [
{
type: "text",
text: "Error executing tool read_docx: --clean-view cannot be used with mode='changes'."
}
]
};
}
const entry2 = await getEntry();
let comments_data = null;
let existing_change_ids = null;
try {
const buf = readBytes();
const doc = await loadDocxOrThrow(buf, file_path);
comments_data = extract_comments_data(doc.pkg);
existing_change_ids = new RedlineEngine(doc, "Adeu AI (TS)", {
id_discovery_hint: MCP_ID_DISCOVERY_HINT
}).existing_change_ids();
} catch {
}
const res2 = build_changes_response(entry2.raw_text, file_path, {
comments_data,
author_filter: changes_author ?? null,
page: page ?? null,
offset: changes_offset,
bundle: entry2.raw_bundle,
existing_change_ids
});
return res2;
}
if (mode === "fields") {
const entryF = await getEntry();
const docF = await loadDocxOrThrow(readBytes(), file_path);
const res2 = build_fields_response(docF, entryF.raw_text, file_path, {
offset: fields_offset,
bundle: entryF.raw_bundle
});
return res2;
}
let pageKind = "single";
let pageVal = 1;
try {
[pageKind, pageVal] = parse_page_arg2(page);
} catch (e) {
return {
isError: true,
content: [
{
type: "text",
text: e.message
}
]
};
}
if (mode === "appendix") {
if (pageKind === "range") {
return {
isError: true,
content: [
{
type: "text",
text: "Page range pagination is only supported in 'full' mode, not 'appendix' mode."
}
]
};
}
if (pageKind === "all") {
return {
isError: true,
content: [
{
type: "text",
text: `Invalid page parameter: '${page}'. Provide a positive integer.`
}
]
};
}
const resolvedPage2 = pageVal;
const res2 = build_appendix_response(
text,
resolvedPage2,
file_path,
bundle
);
return res2;
}
if (mode === "full") {
if (pageKind === "all") {
if (!force && bundle.body.length > response_budget_limit2()) {
const nodes = clean_view ? await docCache.ensureCleanOutline(entry, readBytes, loadDoc) : entry.outline_nodes;
return build_bounded_full_response(bundle.body, file_path, nodes, bundle);
}
const res2 = build_full_document_response(text, file_path, bundle, {
fields_banner: await mcpFieldsBanner(file_path)
});
return res2;
}
if (pageKind === "range") {
const [startP, endP] = pageVal;
const res2 = build_page_range_response(
text,
startP,
endP,
file_path,
bundle
);
return res2;
}
}
const resolvedPage = pageVal;
const res = build_paginated_response(
text,
resolvedPage,
file_path,
bundle,
{ fields_banner: await mcpFieldsBanner(file_path) }
);
return res;
} catch (e) {
return {
isError: true,
content: [
{
type: "text",
text: `Error executing tool read_docx: ${e.message}`
}
]
};
}
}
);
var CHANGE_ITEM_SCHEMA = z.object({
type: z.string().optional().describe(
"Change kind: 'modify' (search-and-replace), 'accept'/'reject' (resolve a tracked change by id), 'reply' (reply to a comment by id), 'set_field' (fill a content control), 'insert_row'/'delete_row' (table edits; disk mode only). If omitted it is inferred when unambiguous from the other fields."
),
target_text: z.string().optional().describe(
"modify / insert_row / delete_row: the existing text to locate (interpreted as a regex when regex=true)."
),
new_text: z.string().optional().describe(
"modify: replacement text. Supports Markdown (headings, **bold**, _italic_, '\\n\\n' paragraph splits, and pipe tables `| H1 | H2 |\\n|---|---|\\n| A | B |`); empty string deletes. Regex capture groups are available as $1, $2\u2026 Omit it (with a comment) to annotate without changing the text; an explicit empty string deletes."
),
// Primitive strings, deliberately: real MCP clients strip property-level
// anyOf/oneOf to {} (QA 2026-07-23), so a union here would erase both the
// type and this guidance client-side.
field: z.string().optional().describe(
"set_field only: which control to fill - the 'CC:<N>' id, its tag, or its alias. Run read_docx with mode='fields' to list them."
),
value: z.string().optional().describe(
"set_field only: the value to write. Checkboxes take true/false; dates take YYYY-MM-DD; dropdowns must match a listed option. Empty string clears the field."
),
target_id: z.string().optional().describe(
"accept / reject / reply: the 'Chg:N' or 'Com:N' id taken from a fresh read_docx."
),
part: z.string().optional().describe(
"accept / reject: the package part holding the change, e.g. 'word/header1.xml'. Revision ids are numbered per part, so the same Chg:N can name unrelated changes in different parts; a bare ambiguous id is refused with an error listing the parts, and this field picks one. Omit whenever the id is unique (the usual case)."
),
text: z.string().optional().describe("reply: the reply body."),
// Published as a string only: real MCP clients strip property-level
// anyOf/oneOf to {} (QA 2026-07-23). The list form is runtime tolerance:
// coerceChangeItemInPlace parks it under COMMENT_LIST_KEY past this
// schema, the handler restores it, and the engine validates the entries.
comment: z.string().optional().describe(
"modify: attach a margin comment to the edited text \u2014 a string, or a list of comments [{text, author?}] on the same change, each under its own author (the engine author when omitted). accept / reject: record the rationale (a string) as a margin comment anchored where the change was resolved (reported as Com:N)."
),
match_mode: z.enum(["strict", "first", "all"]).optional().describe(
"modify only: 'strict' (default \u2014 target must match uniquely), 'first' (first occurrence), or 'all' (every occurrence)."
),
regex: z.boolean().optional().describe(
"modify only: treat target_text as a regular expression (default false)."
),
position: z.enum(["above", "below"]).optional().describe(
"insert_row: place the new row above or below the matched row."
),
cells: z.array(z.string()).optional().describe("insert_row: the cell values for the new row, left to right.")
}).passthrough();
var RAW_STRING_ITEM_KEY = "__adeu_unparseable_item";
var CHANGE_ITEM_WITH_REPAIR = z.preprocess((item) => {
let obj = item;
if (typeof item === "string") {
try {
const parsed = JSON.parse(item);
obj = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : { [RAW_STRING_ITEM_KEY]: item };
} catch {
obj = { [RAW_STRING_ITEM_KEY]: item };
}
}
if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) {
coerceChangeItemInPlace(obj);
}
return obj;
}, CHANGE_ITEM_SCHEMA);
server.registerTool(
"process_document_batch",
{
description: PROCESS_BATCH_COMMON_DESC + PROCESS_BATCH_OPERATIONS_DESC,
inputSchema: {
reasoning: z.string().optional().describe(
"Why do I need to apply these changes to the document? State this reason before any other parameter."
),
original_docx_path: z.string().describe("Absolute path to the source file."),
// Defaulted, not required: real MCP clients drop primitive-typed
// entries from required[] anyway, so schema-following models
// legitimately omit author_name — the call must succeed cleanly
// instead of dumping raw Zod issues (QA 2026-07-23 F3/client-compat).
// The default matches the engine's own.
author_name: z.string().default("Adeu AI (TS)").describe(
"Name to appear in Track Changes (e.g., 'Reviewer AI'). Defaults to 'Adeu AI (TS)' when omitted."
),
// Deliberately a plain REQUIRED array of typed items. Wrapping the
// ARRAY in z.preprocess (to also accept the whole array as one JSON
// string) drops it out of the schema's `required` list, and a z.union
// publishes an anyOf that real clients strip to {} — so per-item
// tolerance lives inside CHANGE_ITEM_WITH_REPAIR's item-level
// preprocess instead. A wholly stringified payload gets a clear
// "expected array, received string" it can retry from.
changes: z.array(CHANGE_ITEM_WITH_REPAIR).describe(
"Ordered list of changes to apply. Each item is an object carrying a `type` discriminator plus that type's fields (see the per-field docs and the tool description). Items apply SEQUENTIALLY: each one evaluates against the document state produced by the items before it, so later items may target text an earlier item introduced."
),
output_path: z.string().optional().describe("Optional output path."),
// Salvage is the default (B5, parity with tools/document.py:1511-1514):
// losing the changes that were right because one was wrong costs the
// agent a whole round trip. The response leads with what did not land.
partial: z.boolean().default(true).describe(
"Whether to apply valid edits when some fail (salvage mode). Defaults to true."
),
// CC-4 write-gate overrides (spec-gates.md §1). All default FALSE:
// §1 requires it because a truthy default survives client stripping,
// and a gate that defaults to off is a gate that does not exist.
// .default() rather than required, per the author_name note above:
// real clients drop primitive entries from required[].
ignore_control_locks: z.boolean().default(false).describe(
"Apply edits even inside content-locked or grouped content controls. Defaults to false. Word refuses such edits, so overriding means the document owner has accepted the lock is wrong."
),
ignore_document_protection: z.boolean().default(false).describe(
"Apply changes even when the document carries enforced editing protection (read-only, fill-in-forms, comments-only, tracked-changes-only). Defaults to false."
),
allow_untracked_writes: z.boolean().default(false).describe(
"Permit writes that Word records WITHOUT tracked changes. Defaults to false. Applies only to fill-in-forms-protected documents, where Word does not record revisions at all; every such write is flagged in the report. Separate from ignore_document_protection because it concedes Adeu's own always-tracked guarantee rather than bypassing the author's restriction."
),
markup_mode: z.enum(["track_changes", "manual"]).default("track_changes").describe(
"Markup mode: 'track_changes' (default, native Word w:ins/w:del) or 'manual' (inline strikethrough deletions and bold underlined red #C00000 insertions with native Word comments)."
),
commented_change_granularity: z.enum(["atomic", "word"]).default("atomic").describe(
"How a modify edit carrying a comment is tracked: 'atomic' (default, one single w:del/w:ins replacement wrapping the whole edit) or 'word' (minimal word-level w:del/w:ins fragments wrapped by one spanning Word comment)."
)
}
},
async ({
reasoning,
original_docx_path,
author_name,
changes,
output_path,
partial,
ignore_control_locks,
ignore_document_protection,
allow_untracked_writes,
markup_mode,
commented_change_granularity
}) => {
try {
void reasoning;
if (!author_name || !author_name.trim())
return {
content: [
{ type: "text", text: "Error: author_name cannot be empty." }
]
};
const author_ctrl = describe_illegal_control_chars(author_name);
if (author_ctrl)
return {
content: [
{
type: "text",
text: `Error: author_name contains control character(s) (${author_ctrl}) that cannot be stored in a DOCX. Remove them and retry.`
}
]
};
if (!changes || changes.length === 0)
return {
content: [{ type: "text", text: "Error: No changes provided." }]
};
const sanitizedChanges = changes.map((item) => {
let obj = item;
if (obj !== null && typeof obj === "object" && !Array.isArray(obj) && RAW_STRING_ITEM_KEY in obj) {
return obj[RAW_STRING_ITEM_KEY];
}
if (typeof item === "string") {
try {
const parsed = JSON.parse(item);
obj = parsed !== null && typeof parsed === "object" ? parsed : item;
} catch {
obj = item;
}
}
if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) {
coerceChangeItemInPlace(obj);
restoreCommentListInPlace(obj);
}
return obj;
});
const VALID_TYPES = /* @__PURE__ */ new Set([
"modify",
"accept",
"reject",
"reply",
"set_field",
"insert_row",
"delete_row"
]);
const typeErrors = [];
const typeFailed = [];
sanitizedChanges.forEach((c, i) => {
if (c !== null && typeof c === "object" && !Array.isArray(c) && (!c.type || !VALID_TYPES.has(c.type))) {
const fused = has_fused_json_marker(c.type) ? ` ${FUSED_JSON_HINT}` : "";
const reason = `missing or unrecognized "type". Use one of: modify (needs target_text + new_text), accept/reject (needs target_id like "Chg:12"), reply (needs target_id like "Com:5" + text), set_field (needs field + value), insert_row (needs target_text + cells), delete_row (needs target_text). Received keys: [${Object.keys(c).join(", ")}].${fused}`;
typeErrors.push(`- Change ${i + 1}: ${reason}`);
typeFailed.push([i, reason]);
}
});
if (typeErrors.length > 0) {
const env = failure_envelope(
"invalid_changes_file",
typeFailed,
"Batch rejected. Some changes are malformed.",
typeErrors
);
return {
isError: true,
content: [
{
type: "text",
text: `Batch rejected. Some changes are malformed:
${typeErrors.join("\n")}
\`\`\`json
${JSON.stringify(env)}
\`\`\``
}
]
};
}
let outPath = output_path || defaultOutputPath(original_docx_path, "processed");
let doc = await docCache.takeHotDoc(original_docx_path);
if (!doc) {
const buf = readFileBytesOrThrow(original_docx_path);
doc = await loadDocxOrThrow(buf, original_docx_path);
}
const engine = new RedlineEngine(doc, author_name, {
id_discovery_hint: MCP_ID_DISCOVERY_HINT,
ignore_control_locks,
ignore_document_protection,
allow_untracked_writes,
markup_mode,
commented_change_granularity
});
let stats;
try {
stats = engine.process_batch(sanitizedChanges, void 0, partial);
} catch (e) {
if (e instanceof BatchValidationError) {
if (engine.rollback_verified) {
docCache.restoreHotDoc(original_docx_path, doc);
}
const env = failure_envelope(
"batch_validation_failed",
e.failed,
"Batch rejected. Some edits failed validation.",
e.errors
);
return {
isError: true,
content: [
{
type: "text",
text: `Batch rejected. Some edits failed validation:
${e.errors.join("\n\n")}
\`\`\`json
${JSON.stringify(env)}
\`\`\``
}
]
};
}
throw e;
}
const applied_count = (stats.edits_applied || 0) + (stats.actions_applied || 0);
const engine_failed = stats.failed || [];
if (applied_count === 0 && engine_failed.length > 0) {
const env = failure_envelope(
"batch_validation_failed",
engine_failed.map((f) => [f.index, f.reason]),
"Batch rejected. Some edits failed validation.",
engine_failed.map((f) => f.reason)
);
return {
isError: true,
content: [
{
type: "text",
text: `Batch rejected. Some edits failed validation:
${engine_failed.map((f) => f.reason).join("\n\n")}
\`\`\`json
${JSON.stringify(env)}
\`\`\``
}
]
};
}
let overwrite_note = "";
const outBuf = await doc.save();
try {
const written = await writeToolDocument(outPath, outBuf, [original_docx_path]);
outPath = written.path;
overwrite_note = overwriteNote(outPath, original_docx_path, written.existedBefore);
} catch (e) {
return {
isError: true,
content: [
{
type: "text",
text: `Could not write output file '${outPath}': ${e.message}`
}
]
};
}
docCache.primeFromDoc(outPath, doc);
let partial_header = "";
if (partial && engine_failed.length > 0 && applied_count > 0) {
const fails = [...engine_failed].sort((a, b) => a.index - b.index);
const max_idx = fails.reduce((m, f) => Math.max(m, f.index), 0);
const total_n = Math.max(max_idx + 1, sanitizedChanges.length);
partial_header = `PARTIAL: applied ${applied_count} of ${total_n} changes. ${fails.length} failed validation:
`;
for (const f of fails) {
partial_header += `- Change #${f.index + 1} Failed: ${f.reason}
`;
}
partial_header += "\n";
}
let res = partial_header + formatBatchResult(stats, outPath) + overwrite_note;
if (sanitizedChanges.length === 0) {
res = `\u26A0\uFE0F 0 changes provided \u2014 nothing to do. The output is an unmodified copy of the original.
` + res;
}
return { content: [{ type: "text", text: res }] };
} catch (e) {
return {
isError: true,
content: [{ type: "text", text: `Error: ${e.message}` }]
};
}
}
);
server.registerTool(
"accept_all_changes",
{
description: "Accepts every tracked change in the document, producing a finalized clean document.\n\nremove_comments (boolean, DEFAULT TRUE): also delete every comment. The default is TRUE because this tool's purpose is a distributable clean document, and comments are internal review notes that must not travel to a counterparty. Pass remove_comments=false to accept the tracked changes while KEEPING the comments \u2014 use that when the review conversation is still live. Either way the response reports how many comments were deleted and names each one with its author, and comments whose anchored text an accepted deletion consumes are removed regardless, exactly as Word does.",
inputSchema: {
reasoning: z.string().optional().describe(
"Why do I need to accept all changes in this document? State this reason before any other parameter."
),
docx_path: z.string().describe("Absolute path to the DOCX file."),
output_path: z.string().optional().describe("Optional output path."),
remove_comments: z.boolean().default(true).describe(
"Also delete every comment in the document. Defaults to true (finalized clean document); pass false to keep comments while accepting the tracked changes."
)
}
},
async ({ reasoning, docx_path, output_path, remove_comments }) => {
try {
void reasoning;
let outPath = output_path || defaultOutputPath(docx_path, "clean");
const buf = readFileBytesOrThrow(docx_path);
const doc = await loadDocxOrThrow(buf, docx_path);
const engine = new RedlineEngine(doc, "Adeu AI (TS)", {
id_discovery_hint: MCP_ID_DISCOVERY_HINT
});
const counts = engine.accept_all_revisions(remove_comments !== false);
const removedCommentNotes = [...engine.removed_comment_notes];
const total = counts.accepted_insertions + counts.accepted_deletions + counts.accepted_formatting + counts.removed_comments;
const outBuf = await doc.save();
const written = await writeToolDocument(outPath, outBuf, [docx_path]);
outPath = written.path;
docCache.invalidate(outPath);
let text;
if (total === 0) {
text = `No tracked changes or comments to accept \u2014 the document is already clean. Saved to: ${outPath}`;
} else {
text = `Accepted all changes. Saved to: ${outPath}
Accepted: ${counts.accepted_insertions} insertion(s), ${counts.accepted_deletions} deletion(s), ${counts.accepted_formatting} formatting change(s).`;
if (counts.removed_comments > 0) {
text += `
Comments removed: ${counts.removed_comments}.`;
if (removedCommentNotes.length > 0) {
text += `
Comments deleted: ${removedCommentNotes.join(", ")}`;
if (remove_comments === false) {
text += `
Note: these comments were anchored to text an accepted deletion consumed, so Word removes them too. Nothing else was deleted.`;
}
}
} else if (remove_comments === false) {
text += `
Comments kept (remove_comments=false).`;
}
}
text += overwriteNote(outPath, docx_path, written.existedBefore);
return {
content: [{ type: "text", text }]
};
} catch (e) {
return {
isError: true,
content: [{ type: "text", text: `Error: ${e.message}` }]
};
}
}
);
server.registerTool(
"diff_docx_files",
{
description: DIFF_DOCX_DESC,
inputSchema: {
reasoning: z.string().optional().describe(
"Why do I need to diff these two documents? State this reason before any other parameter."
),
original_path: z.string().describe("Absolute path to the baseline DOCX file."),
modified_path: z.string().describe("Absolute path to the modified DOCX file."),
compare_clean: z.boolean().default(true).describe(
"If True, compares 'Accepted' state. If False, compares raw text."
),
output_path: z.string().optional().describe(
"Optional path to save a redlined DOCX showing all changes from original_path to modified_path as native Word tracked changes."
),
author_name: z.string().optional().describe(
"Author name for tracked changes when output_path is provided (default: 'Comparison')."
)
}
},
async ({
reasoning,
original_path,
modified_path,
compare_clean,
output_path,
author_name
}) => {
try {
void reasoning;
const origBuf = readFileBytesOrThrow(original_path);
const modBuf = readFileBytesOrThrow(modified_path);
const origDoc = await loadDocxOrThrow(origBuf, original_path);
const modDoc = await loadDocxOrThrow(modBuf, modified_path);
let saved_header = "";
if (output_path) {
for (const [input, role] of [
[original_path, "original"],
[modified_path, "modified"]
]) {
if (isSameFile(output_path, input)) {
throw new Error(
`output_path '${output_path}' is the same file as the ${role} document; writing the redline there would destroy it. Choose a different output path.`
);
}
}
const effAuthor = (author_name || "").trim() || "Comparison";
let comparison;
try {
comparison = await build_redline_comparison(origBuf, modBuf, effAuthor, compare_clean);
} catch (e) {
if (e instanceof ComparisonError) {
throw new Error([e.message, ...e.details].join("\n"));
}
throw e;
}
const written = await writeToolDocument(output_path, comparison.data, [original_path, modified_path]);
const media = new Set(
collect_media_difference_warnings(new Uint8Array(origBuf), new Uint8Array(modBuf))
);
const warnings = comparison.warnings.filter((w) => !media.has(w)).map((w) => `\u26A0\uFE0F ${w}
`).join("");
saved_header = `Redline saved to: ${written.path} (${comparison.applied} tracked change(s) applied, Author: ${effAuthor}).${overwriteNote(written.path, original_path, written.existedBefore)}
${warnings}
`;
}
const origText = _extractTextFromDoc2(origDoc, compare_clean, false, false, false, false);
const modText = _extractTextFromDoc2(modDoc, compare_clean, false, false, false, false);
let diff = create_word_patch_diff(
origText,
modText,
basename4(original_path),
basename4(modified_path)
);
if (!diff.includes("@@ Word Patch @@")) {
diff = `--- ${basename4(original_path)}
+++ ${basename4(modified_path)}
No textual differences found between the documents.`;
}
const media_warnings = collect_media_difference_warnings(
new Uint8Array(origBuf),
new Uint8Array(modBuf)
);
const warning_text = media_warnings.length ? media_warnings.map((w) => `\u26A0\uFE0F ${w}`).join("\n") + "\n\n" : "";
return {
content: [
{
type: "text",
text: saved_header + warning_text + diff
}
]
};
} catch (e) {
return {
isError: true,
content: [{ type: "text", text: `Error: ${e.message}` }]
};
}
}
);
server.registerTool(
"finalize_document",
{
description: "Prepares a document for external distribution or e-signature. Note: in this zero-dependency environment, protection_mode='encrypt' is unsupported and falls back to a native read-only lock; export_pdf and password are ignored.",
inputSchema: {
reasoning: z.string().optional().describe(
"Why do I need to finalize this document? State this reason before any other parameter."
),
file_path: z.string().describe("Absolute path to the DOCX file."),
output_path: z.string().optional().describe("Optional output path."),
sanitize_mode: z.enum(["full", "keep-markup"]).optional().describe("full removes all markup, keep-markup redacts metadata."),
accept_all: z.boolean().optional().describe(
"If true, auto-accepts all unresolved track changes before finalizing."
),
protection_mode: z.enum(["read_only", "encrypt"]).optional().describe(
"Native OOXML document locking. Note: 'encrypt' is unsupported in this zero-dependency build and falls back to 'read_only'."
),
password: z.string().optional().describe("Ignored in this environment."),
author: z.string().optional().describe("Replace all remaining markup authorship with this name."),
export_pdf: z.boolean().optional().describe("Ignored in this environment.")
}
},
async ({
reasoning,
file_path,
output_path,
sanitize_mode,
accept_all,
protection_mode,
author,
export_pdf
}) => {
try {
void reasoning;
let outPath = output_path || defaultOutputPath(file_path, "final");
const buf = readFileBytesOrThrow(file_path);
const doc = await loadDocxOrThrow(buf, file_path);
const result = await finalize_document(doc, {
filename: basename4(file_path),
sanitize_mode: sanitize_mode || "full",
accept_all,
protection_mode,
author,
export_pdf
});
if (result.outBuffer) {
const written = await writeToolDocument(outPath, result.outBuffer, [file_path]);
outPath = written.path;
docCache.invalidate(outPath);
const note = overwriteNote(outPath, file_path, written.existedBefore);
return {
content: [
{
type: "text",
text: `Saved to: ${outPath}${note}
${result.reportText}`
}
]
};
} else {
return {
content: [
{
type: "text",
text: result.reportText
}
]
};
}
} catch (e) {
return {
isError: true,
content: [{ type: "text", text: `Error: ${e.message}` }]
};
}
}
);
server.registerTool(
"apply_text_revision",
{
description: "Applies whole-text revised text to a DOCX document by computing a diff and generating tracked changes. Includes a clean-text verification gate to ensure the applied document matches the supplied text.\n\n`revised_text` must be the complete CLEAN view of the document: read it with `read_docx` (`clean_view=true`, `page='all'`), edit that text, and send ALL of it back. Never CriticMarkup ({++, {--, {>>) \u2014 this tool diffs against the clean view, so markup tokens would land in the document as literal prose. Never one page of a paginated extract \u2014 everything absent from the text is applied as a tracked deletion.\n\nINTERLOCK: a revision that drops >50% of the characters (>75% for documents under 2000 characters) is refused unless you pass allow_major_deletions=true.\n\nIf the applied document's clean text does not then match `revised_text`, NOTHING is written to output_path: a diagnostic copy is kept at <name>.unverified.docx and the call fails. output_path defaults to <name>_redlined.docx; an existing _redlined/_processed artifact is revised in place.",
inputSchema: {
reasoning: z.string().optional().describe(
"Why do I need to apply this text revision? State this reason before any other parameter."
),
file_path: z.string().describe("Absolute path to the source DOCX file."),
revised_text: z.string().describe("The complete revised clean text of the document."),
output_path: z.string().optional().describe("Optional output path for the modified DOCX."),
author: z.string().optional().describe("Author name for Track Changes."),
allow_major_deletions: z.boolean().default(false).describe(
"Allow deleting >50% of characters (>75% for documents under 2000 characters)."
)
}
},
async ({
reasoning,
file_path,
revised_text,
output_path,
author,
allow_major_deletions
}) => {
try {
void reasoning;
output_path = await checkToolPath(
output_path ?? defaultOutputPath(file_path, "redlined"),
"write",
[file_path]
);
const diagnostic = await checkToolPath(
diagnosticPath(output_path),
"write",
[file_path]
);
if (isSameFile(output_path, diagnostic) || isSameFile(file_path, diagnostic)) {
throw new Error(`Refused '${diagnostic}': the diagnostic would replace the source or requested output. Choose a different output filename.`);
}
const buf = readFileBytesOrThrow(file_path);
const doc = await loadDocxOrThrow(buf, file_path);
let result;
try {
result = await apply_text_revision_core({
doc,
input_path: file_path,
revised_text,
output_path,
author,
allow_major_deletions
});
} catch (error) {
if (!(error instanceof TextRevisionVerificationError)) throw error;
const written = await writeToolDocument(diagnostic, error.unverified_bytes, [file_path]);
return {
isError: true,
content: [{ type: "text", text: error.message.replace(error.unverified_path, () => written.path) }]
};
}
const { path: outPath, existedBefore } = await writeToolDocument(
result.output_path,
result.out_bytes,
[file_path]
);
docCache.invalidate(outPath);
return {
content: [
{
type: "text",
text: formatBatchResult(result.stats, outPath) + overwriteNote(outPath, file_path, existedBefore)
}
]
};
} catch (e) {
return {
isError: true,
content: [
{
type: "text",
text: e instanceof TextRevisionError ? e.message : `Error: ${e.message}`
}
]
};
}
}
);
function formatBatchResult(stats, outPath) {
let res = `Batch complete. Saved to: ${outPath}
`;
if (stats.overrides_note) {
res += `
*${stats.overrides_note}*
`;
}
if (stats.author_impersonation_warning) {
res += `
*Warning:* ${stats.author_impersonation_warning}
`;
}
const total_occurrences = stats.edits ? stats.edits.reduce(
(acc, e) => acc + (e.status === "applied" ? e.occurrences_modified || 1 : 0),
0
) : 0;
const occ_text = total_occurrences > stats.edits_applied ? ` (${total_occurrences} occurrences)` : "";
const already = stats.actions_already_resolved || 0;
const already_text = already ? `, ${already} already resolved (no effect)` : "";
res += `Actions: ${stats.actions_applied} applied, ${stats.actions_skipped} skipped${already_text}.
`;
res += `Edits: ${stats.edits_applied} applied${occ_text}, ${stats.edits_skipped} skipped.
`;
if (stats.document_state) {
res += `Document State: ${stats.document_state.tracked_changes ?? 0} tracked change(s), ${stats.document_state.comments ?? 0} comment(s) remaining.
`;
}
if (stats.actions && stats.actions.length > 0) {
res += "\nApplied Actions:\n";
for (const actRep of stats.actions) {
const rIds = (actRep.resolved_ids || []).map((rid) => `\`${rid}\``).join(", ");
res += `- **${actRep.type}** on ${rIds} \u2705 [${actRep.status || "applied"}]
`;
}
}
if (stats.edits && stats.edits.length > 0) {
res += "\nDetailed Edit Reports:\n";
for (let i = 0; i < stats.edits.length; i++) {
const report = stats.edits[i];
const status_indicator = report.status === "applied" ? "\u2705 [applied]" : "\u274C [failed]";
const pagesStr = report.pages && report.pages.length > 0 ? ` (p${report.pages.join(", p")})` : "";
res += `### Edit ${i + 1} ${status_indicator}${pagesStr}
`;
if (report.heading_path) {
res += `**Path:** \`${report.heading_path}\`
`;
}
if (report.part) {
res += `**Part:** ${report.part}
`;
}
if (report.field) {
res += `field: ${report.field}
`;
}
const occ = report.occurrences_modified ?? 0;
res += `**Mode:** \`${report.match_mode || "strict"}\` (${occ} occurrence${occ !== 1 ? "s" : ""} modified)
`;
const allMintedIds = [
...report.change_ids || [],
...report.comment_ids || []
];
if (allMintedIds.length > 0) {
res += `**IDs:** ${allMintedIds.map((id) => `\`${id}\``).join(", ")}
`;
}
if (Array.isArray(report.comment)) {
for (const c of report.comment) {
res += `**Comment${c.author ? ` (${c.author})` : ""}:** "${c.text}"
`;
}
} else if (report.comment) {
res += `**Comment:** "${report.comment}"
`;
}
if (report.error) {
res += `*Error:* ${report.error}
`;
}
if (report.warning) {
res += `*Warning:* ${report.warning}
`;
}
if (report.critic_markup) {
res += `*Preview (CriticMarkup):*
> ${report.critic_markup.split("\\n").join("\\n> ")}
`;
}
res += "\n";
}
}
if (stats.skipped_details && stats.skipped_details.length > 0) {
const allNotes = stats.skipped_details.every(
(d) => d.trimStart().startsWith("- Note:")
);
const header = allNotes ? "Notes:" : "Skipped Details:";
res += `
${header}
${stats.skipped_details.join("\n")}`;
}
return res.trim();
}
async function main() {
const cliOutput = handleServerCliArgs(process.argv.slice(2), packageVersion);
if (cliOutput !== null) {
process.stdout.write(cliOutput + "\n");
return;
}
const transport = new StdioServerTransport();
await server.connect(transport);
attachProtocolAdapter(server, transport, "adeu-redlining-service", packageVersion);
const gitSha2 = "989ccb3";
const buildTs = "2026-11-21T18:53:13.787Z";
console.error(
`Adeu MCP Server (Node.js Engine: ${identifyEngine()}) running on stdio build=${gitSha2}@${buildTs}`
);
}
main().catch(console.error);
export {
CHANGE_ITEM_SCHEMA,
coerceChangeItemInPlace,
formatBatchResult,
restoreCommentListInPlace
};
//# sourceMappingURL=index.js.map