Guide

Contract redlining API: tracked changes in an embedded DOCX editor

Build a custom contract redlining agent. Connect AI SDK tools to a DOCX editing API and a review UI that users can control.

Updated 5 min read

Build a contract review agent that creates tracked changes in DOCX files. Your application controls the model, tools, permissions, and review workflow.

Propose a payment deadline, validate it, and review the tracked replacement. For a complete scripted review, open the contract redlining demo.

Configure the review UI

Install the browser packages in your application:

npm install @docx-editor.dev/react @docx-editor.dev/core \
  @docx-editor.dev/pro @docx-editor.dev/editor-api

Keep these packages on matching versions with one resolved copy of core. The Pro and editing API packages require a commercial license for production. See pricing for evaluation terms.

The review UI uses these settings:

  • reviewModule() to enable tracked changes
  • an author for revision attribution
  • mode="suggesting" to record interactive edits as proposals

API writes require TrackMineOnly separately, as shown in the execution example. The UI mode does not enable tracking for the API runtime.

import { DocxEditor } from "@docx-editor.dev/react";
import { DocxEditorReview, reviewModule } from "@docx-editor.dev/pro/react";
import "@docx-editor.dev/core/styles/editor.css";
 
const MODULES = [reviewModule()];
 
export function RedlineEditor({ bytes }: { bytes: Uint8Array }) {
  return (
    <DocxEditor.Root
      document={bytes}
      modules={MODULES}
      author="Contract agent"
      mode="suggesting"
    >
      <DocxEditor.Toolbar />
      <DocxEditor.Viewport>
        <DocxEditor.Content />
        <DocxEditorReview />
      </DocxEditor.Viewport>
    </DocxEditor.Root>
  );
}

The review rail shows each proposed insertion, deletion, or replacement. Reviewers can accept or reject proposals before saving the contract.

Define tools for your redlining agent

Use @docx-editor.dev/editor-api with your preferred model or agent framework. Expose only the tools your workflow needs.

The proposal validation tutorial defines proposalSchema and the matching executor in redlining-proposal.ts. The model supplies replacement and reason. Your application keeps the selected clause and policy outside that response.

Vercel AI SDK tools can use that shared schema:

import { tool } from "ai";
import { proposalSchema } from "./redlining-proposal";
 
export const redliningTools = {
  propose_replacement: tool({
    description: "Propose a payment deadline for the selected clause.",
    inputSchema: proposalSchema,
  }),
};

Pass the catalog to an AI SDK model loop. In this route excerpt, your application supplies model and messages:

import { streamText } from "ai";
 
const result = streamText({
  model,
  system: "Review the contract against the approved clause playbook.",
  messages,
  tools: redliningTools,
});
 
return result.toUIMessageStreamResponse();

The example tool has no server execute function. AI SDK forwards the tool call to your client. Your browser executor validates the request and runs it against the open document.

You can also use a ToolLoopAgent or another tool-calling framework. Your server owns the system prompt and model selection. It can combine document tools with playbook, matter, approval, or clause-library tools.

The tool catalog is an allowlist. A search agent needs only search tools. A redlining agent can also receive proposal tools. A model cannot call a document operation that you do not expose.

Execute a proposal through the document API

The browser handles a propose_replacement call against the document the user has open. Use the validator and scoped editor operation from the proposal tutorial. This excerpt assumes editor is your attached editor instance and toolInput is the model's untrusted tool input. The application captures task before requesting the proposal:

import { DocxEditor } from "@docx-editor.dev/editor-api/browser";
import { applyPaymentProposal } from "./redlining-proposal";
 
const task = {
  clause: "The customer pays the invoice within 7 days.",
  source: "within 7 days",
  minDays: 15,
  maxDays: 45,
};
const runtime = DocxEditor.createBrowser(editor, {
  author: "Contract agent",
  revisionTextView: "allMarkup",
});
try {
  await applyPaymentProposal(runtime, toolInput, task);
} finally {
  runtime.dispose();
}

The helper validates the deadline and finds the selected clause before writing. It enables TrackMineOnly for the API edit. The editor's UI mode does not enable API tracking. If the deadline is invalid or the clause has changed, show the error and request another review.

Return the tool result to the model

A browser-executed tool must report an outcome with addToolOutput. Otherwise, the conversation has a tool call with no result. Return failures too, so the model can revise an invalid deadline or explain why the edit stopped.

This hook assumes your chat endpoint uses the tool catalog above. Pass it the attached runtime and the task captured before the model request. Keep both stable while that request runs:

"use client";
 
import { useChat } from "@ai-sdk/react";
import { lastAssistantMessageIsCompleteWithToolCalls } from "ai";
import type { DocxEditorRuntime } from "@docx-editor.dev/editor-api/browser";
import { applyPaymentProposal, type PaymentTask } from "./redlining-proposal";
 
export function usePaymentAgent(runtime: DocxEditorRuntime, task: PaymentTask) {
  const chat = useChat({
    sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
    onToolCall: async ({ toolCall }): Promise<void> => {
      if (toolCall.dynamic || toolCall.toolName !== "propose_replacement") return;
      let output: { ok: boolean; message: string };
      try {
        await applyPaymentProposal(runtime, toolCall.input, task);
        output = { ok: true, message: "Tracked change created for review." };
      } catch (error) {
        output = {
          ok: false,
          message: error instanceof Error ? error.message : "The edit could not be applied.",
        };
      }
      void chat.addToolOutput({
        tool: "propose_replacement",
        toolCallId: toolCall.toolCallId,
        output,
      });
    },
  });
  return chat;
}

sendAutomaticallyWhen continues the model turn once the client tool results are available. The callback reports that a redline was created; it does not tell the model that the reviewer accepted it.

The same tool can use the server runtime for a background review. The server runtime takes DOCX bytes and returns DOCX bytes. The browser runtime instead updates the open editor, uses its undo history, and shows the result at once.

The editing API overview explains server and browser runtimes. The Office.js compatibility guide lists the supported object model and its deliberate differences.

Save and reopen the redlined document

Save through the attached editor after the proposal finishes. The browser runtime does not provide save(). This excerpt uses the same editor instance as the preceding example:

const output = await editor.save();
const blob = new Blob([output], {
  type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
const url = URL.createObjectURL(blob);
const download = document.createElement("a");
download.href = url;
download.download = "contract.redlined.docx";
document.body.append(download);
download.click();
download.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);

Keep the original file. Reopen the downloaded file in a fresh editor instance with the review module enabled. Confirm the proposal and its author remain visible. Use the Node.js inspection script to inspect the saved revision metadata separately.

For accept and reject checks, follow verify the review workflow.

Customize the agent and user interaction

Configure the document API and review UI separately.

Your application can customize:

  • The agent prompt, model, tool descriptions, and tool allowlist.
  • Clause retrieval, playbook rules, validation, and approval limits.
  • The editor toolbar, document layout, review rail, and agent panel.
  • Tool progress, citations, explanations, suggestion chips, and error states.
  • The point where a user accepts, rejects, changes, or comments on a proposal.

The React components expose the editor surface and review controls. Your application owns the chat or task interface around them. A user can review an agent proposal in the document, edit it manually, undo it, or reject it.

Use React composition for custom panels and controls. Use custom styles for the document style system. Use tracked changes and comments for the review interaction.

Manage the application workflow

@docx-editor.dev/editor-api is an embedded software library. Your application owns users, permissions, storage, negotiation state, and audit records.

It is not a hosted redlining service. It does not issue participant links, send webhooks, or manage negotiation turns. Use it when your product already owns that workflow and needs DOCX editing inside it.

Next steps

.docx in. .docx out.

Open a real document in the editor, then wire it into your app. It all runs client-side.