> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reducto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent edits

An agent edits a document with the [Office.js facade](https://docs.reducto.ai/office/docx/js-api/concepts.md): `WordDocument`, `body.search`, `insertText` and so on. This page shows how its edit reaches the document that the user has open in the [editor](https://docs.reducto.ai/office/docx/ui/editor.md), or in Word.

## Choose a pattern

```mermaid theme={null}
flowchart TD
  start([An agent edits the open document]) --> approve{Must the user approve each edit first?}
  approve -->|Yes| where{Where does the user review?}
  where -->|In the editor| cards[Suggestion cards]
  where -->|In Word| word[Word add-in]
  approve -->|No| typing{Does the user type while the agent runs?}
  typing -->|Yes| rebase[Rebase]
  typing -->|No| history{One undo history?}
  history -->|Yes| session[Same session]
  history -->|No| reopen[Reopen the bytes]
```

| Pattern | Where the agent runs | The edit lands | The user types during the run | Undo |
| - | - | - | - | - |
| [Reopen the bytes](#reopen-the-bytes) | Page | At once | No | Starts a new history |
| [Same session](#same-session) | Editor worker | At once | No | One step in the user's history |
| [Rebase](#rebase) | Your server or sandbox | At once, as tracked changes | Yes | The user undoes only their own edits |
| [Suggestion cards](#suggestion-cards) | Your server or sandbox | When the user accepts a card | Yes | Each accept and reject is one step |
| [Word add-in](#word-add-in) | Your server or sandbox | When the user accepts a card in Word | Yes | Word's own undo |

## Reopen the bytes

Take the bytes out, edit them, and open them again with `keepView`:

```ts theme={null}
import { WordDocument } from "@reductoai/docx/officejs";

const doc = await WordDocument.fromBytes(await editor.model.toBytes());
doc.revisionAuthor = "Assistant";
doc.changeTrackingMode = "TrackAll";
doc.body.search("30 days").items.forEach((hit) => hit.insertText("15 business days", "Replace"));

await editor.model.open(await doc.toBytes(), editor.model.name, { keepView: true });
```

`keepView` keeps the old pages on screen until the new layout is ready, and keeps the scroll position and the caret. The undo history starts again.

## Same session

Run the facade in the editor's worker, on the session the editor has open. The edit is one step in the user's undo history. The worker serves the editor on a `MessagePort` and takes your own messages on `self`:

```ts theme={null}
// editor.worker.ts
import { WordDocument } from "@reductoai/docx/browser";
import {
  createDefaultHost,
  portableFonts,
  serveEditorHost,
  type EditorHostHandle,
} from "@reductoai/docx-editor/model";

const fonts = portableFonts("/fonts");
let editor: EditorHostHandle | undefined;

self.onmessage = async ({ data }) => {
  if (data.type === "attach") {
    editor = serveEditorHost(
      {
        fonts,
        createHost: (bytes, name, onProgress) => createDefaultHost(fonts, bytes, name, onProgress),
      },
      data.port,
    );
  }
  if (data.type === "redline" && editor) {
    await editor.recordExternal(async (host) => {
      const doc = WordDocument.from(host.session, { layout: host.pages });
      doc.revisionAuthor = "Assistant";
      doc.changeTrackingMode = "TrackAll";
      doc.body.search("30 days").items.forEach((hit) => hit.insertText("15 business days", "Replace"));
    });
    self.postMessage({ type: "done" });
  }
};
```

The page gives the editor a new port each time it opens a document, and asks the model to repaint after the edit:

```ts theme={null}
import { createDefaultHost, mountDocxEditor, portableFonts } from "@reductoai/docx-editor";

const worker = new Worker(new URL("./editor.worker.ts", import.meta.url), { type: "module" });
const fonts = portableFonts("/fonts");

const editor = mountDocxEditor(document.getElementById("app")!, {
  fontsUrl: "/fonts",
  transport: {
    fonts,
    createHost: (bytes, name, onProgress) => createDefaultHost(fonts, bytes, name, onProgress),
    spawnWorker: () => {
      const channel = new MessageChannel();
      worker.postMessage({ type: "attach", port: channel.port2 }, [channel.port2]);
      return channel.port1;
    },
  },
});

async function redline() {
  const done = new Promise((resolve) =>
    worker.addEventListener("message", ({ data }) => data.type === "done" && resolve(null)),
  );
  worker.postMessage({ type: "redline" });
  await done;
  await editor.model.refreshFromHost();
}
```

`recordExternal` makes the whole edit one undo step. It waits for the request the editor is busy with, and the next keystroke waits for it. In a [live session](https://docs.reducto.ai/office/document-server.md), the edit goes to the server as one change when the code ends. `refreshFromHost()` lays out again and keeps the caret where it can.

## Rebase

The agent edits on your server while the user keeps typing. The agent and each browser tab are writers of one shared session. The server puts their changes in one order, and each tab rebases the keystrokes it has not sent yet. No edit is lost, and the user does not wait.

```mermaid theme={null}
sequenceDiagram
  participant Tab as Browser tab
  participant Server
  participant Sandbox as Agent sandbox
  Server->>Sandbox: bytes at seq 7
  Tab->>Server: user's change, base 7
  Server->>Tab: ack, seq 8
  Sandbox->>Server: agent's change, base 7
  Note over Server: rebases it past seq 8
  Server->>Tab: agent's change, seq 9
  Note over Tab: rebases keystrokes it has not sent yet
```

### Server

> [!TIP]
>
> The [document server](https://docs.reducto.ai/office/document-server.md) does this for you: it orders and rebases the changes, stores each document and runs agent code on it. Run the code below only to keep this on your own server.

For each open document, the server keeps a sequencer (`CollabServer`) and a mirror (`SessionReplica`): a copy that every change is written into, so it can give the bytes at any `seq`.

```ts theme={null}
import { CollabServer, type CollabChange, type Outgoing } from "@reductoai/docx/collab";
import { collabChange, DocxSession, SessionReplica } from "@reductoai/docx/editor";

const log = new CollabServer();
const reopen = (next: Uint8Array) => DocxSession.fromBytes(next);
const replica = await SessionReplica.start(await reopen(bytes), log.seq, reopen);

let tail: Promise<unknown> = Promise.resolve();
function serial<T>(step: () => Promise<T>): Promise<T> {
  const run = tail.then(step);
  tail = run.catch(() => {});
  return run;
}

/** The bytes of the mirror and the seq they reflect: for a sandbox, a new tab or a reopen. */
const snapshot = () => serial(async () => ({ seq: replica.seq, bytes: await replica.session.toBytes() }));

type Tab = { send(message: string): void };
const tabs = new Set<Tab>();
function broadcast(s: { seq: number; change: CollabChange }, from?: Tab): void {
  for (const tab of tabs) tab.send(JSON.stringify({ ...s, own: tab === from }));
}

/** Give a change its place, send it to every tab, and write it into the mirror. */
function sequence(base: number, change: CollabChange, from?: Tab): void {
  const { seq, change: rebased } = log.receive(base, change);
  broadcast({ seq, change: rebased }, from);
  void serial(() => replica.remote(rebased, seq));
}

const fromTab = (tab: Tab, out: Outgoing) => sequence(out.base, out.change, tab);
```

A change to a part other than the body opens the mirror again, so always read it through `replica.session`. The new session keeps the `revisionAuthor` and `revisionDate` that you set on the old one.

### Agent turn

Give the sandbox the bytes, take back the bytes it wrote, and send the difference. `collabChange` diffs the body token by token, so the change holds only what the agent changed:

```ts theme={null}
async function agentTurn(runInSandbox: (docx: Uint8Array) => Promise<Uint8Array>): Promise<void> {
  const { seq, bytes } = await snapshot();
  const written = await runInSandbox(bytes); // the user keeps typing meanwhile
  sequence(seq, await collabChange(bytes, written));
}
```

The sandbox needs nothing from collab:

```ts theme={null}
const doc = await WordDocument.fromBytes(input);
doc.revisionAuthor = "Assistant";
doc.changeTrackingMode = "TrackAll";
doc.body.search("30 days").getFirst().insertText("15 business days", "Replace");
return doc.toBytes();
```

If the agent runs the facade in the server process, it can edit a `SessionReplica` of its own and send `await replica.commit()` instead of a diff.

### Browser tab

Open the bytes of a known `seq`, then join:

```ts theme={null}
await editor.model.open(bytes, name);
await editor.model.startCollab({
  seq,
  block, // this tab's id block, from the server: 1, 2, 3, ...
  send: (out) => socket.send(JSON.stringify(out)),
  onError: () => reopenFromServer(),
});

socket.onmessage = ({ data }) => {
  const { seq, change, own } = JSON.parse(data);
  if (own) editor.model.collabAck(seq);
  else editor.model.collabRemote(change, seq);
};
```

| Rule | Why |
| - | - |
| A tab sends one change at a time, and holds the next keystrokes until the ack | They go as one change against the newest `seq` |
| `onError` means that a remote change did not apply | Open `snapshot()` again. A new tab opens the same way |
| Each tab gets its own `block`, a number from 1 up | New links, pictures, comments and lists take ids inside it, so two writers never make the same id. The sandbox needs no block |
| The agent's edit is tracked | The user accepts or rejects it in the review margin |

Pass the same `block` to `CollabBinding.start` or `SessionReplica.start` when you drive one directly.

### What merges

| Part | Merge |
| - | - |
| Body | Token by token |
| Relationships, content types | By entry: each writer's links and pictures stay |
| Comments, footnotes, endnotes, lists (`numbering.xml`) | By entry, keyed by id |
| Styles (`styles.xml`) | By entry, keyed by `w:styleId`; doc defaults and latent styles are one entry each |
| Headers, footers, settings, everything else | Whole part: the last writer wins |

### Show where a writer is

A presence is a selection as body token indices after a given `seq`. A tab can show the agent's range, and the agent can read the user's selection:

```ts theme={null}
// Headless writer: a facade Range to a presence, and back.
const doc = WordDocument.from(replica.session);
const presence = replica.presence(doc.search("30 days").getFirst()); // { seq, anchor, focus }
socket.send(JSON.stringify({ presence }));

const range = replica.place(peerPresence); // a Range in replica.session, or undefined
range?.font.highlightColor; // read or edit it like any other range

// Editor tab: a selection to a presence, and back.
const mine = binding.presence(selection);
const theirs = binding.place(peerPresence); // { anchor, focus } in this tab's targets
```

* `place` moves an older presence forward. It gives `undefined` until this writer reaches the presence's `seq`, and when the presence is more than 256 changes old.
* `presence` and `place` give `undefined` while the writer holds an edit it did not send. On a `SessionReplica`, call `commit()` first.

Positions come in four kinds. Do not use a number from one where another is expected:

| Address | Counts | Where you get it |
| - | - | - |
| Paragraph index | `doc.body.paragraphs` includes paragraphs in table cells; `doc.paragraphs` does not | the facade collections |
| Body block index | Top-level body blocks: a table is one block | `getTarget(id)`, editor `target.bodyIndex` |
| Character offset | UTF-16 units in one paragraph (facade) or one target (editor) | `Range`, editor `Position.offset` |
| Token index | Body tokens in the shared stream, after one `seq` | `presence` / `place` only. Keep the `seq` with them |

### When the agent settles a revision

The agent can accept or reject a revision that another author made (`TrackedChange.accept()` in the sandbox). That edit is its own card:

* `kinds` is `["review"]`. The card has no `revisions`, and `settles` names the ids as the forked document numbers them.
* Each piece of its preview carries `review: { action, kind, author }`, and `previewText` reads it as `{accept +forty+}` or `{reject -thirty-}`.
* It has no `text` to rewrite.
* In a header, a footer or a note, the card names the ids of the revisions in that story.
* Accepting the card settles the revision as Word does: no new revision, one undo step. `revert` puts the revision back with its author and date.

An edit is not a review:

* An author who rewrites words inside her own pending insertion edits it. When one author has both the text the card takes out and the text it puts in at that place, the card is `text` with no `settles`, under every grouping.
* An untracked edit that takes letters out of a word and puts letters in replaces the whole word.

### Limits

* Two writers who change the same header, footer, settings part, comment, note, list or style at the same time: the later change wins, and nothing reports it.
* Presence is for the body only.
* A remote change to a part other than the body opens the writer's session again. Read it through `replica.session` or `binding.host`. `TrackMineOnly` reopens as `TrackAll`.
* An undo of a style the tab added keeps the style definition, because another writer may use it.
* `w14:paraId` and revision `w:id` values are not in a writer's id block. Two writers can make the same one.
* Two concurrent changes to the structure of one table can leave rows with different cell counts.
* The sequencer does not check a change. Accept changes only from writers you trust.

## Suggestion cards

The agent's edits do not reach the document until the user accepts them. The agent edits a copy with Track Changes on, and the page cuts what it wrote into cards. The user keeps typing while the agent works, and each card follows those edits.

```mermaid theme={null}
sequenceDiagram
  participant User
  participant Page as Page (AgentSuggestions)
  participant Sandbox as Agent sandbox
  User->>Page: asks the agent
  Page->>Page: fork(): bytes now, start to record edits
  Page->>Sandbox: run.bytes
  User->>Page: keeps typing
  Sandbox->>Page: redlined bytes
  Page->>Page: load(): cards, moved past the user's typing
  User->>Page: accepts a card
  Page->>Page: lands as the agent's tracked change, one undo step
```

```ts theme={null}
import { AgentSuggestions, type Suggestion } from "@reductoai/docx-editor/suggestions";

const model = editor.model;
const suggestions = new AgentSuggestions(model, () => void render());
await model.open(bytes, name);
await model.startCollab({ observe: suggestions.observe });

async function askAgent(prompt: string): Promise<void> {
  const run = await suggestions.fork();
  const redlined = await backend.runAgent({ run: run.id, docx: run.bytes, prompt });
  await suggestions.load(run.id, redlined);
}

async function render(): Promise<void> {
  const cards: Suggestion[] = await suggestions.list();
  // card.id, card.kinds ("text" | "format" | "structure" | "part" | "review"), card.state, card.stale
  // card.preview.paragraphs[].pieces[]: { text, change: "ins" | "del" | "format" | undefined, format, look, object, image }
  // card.preview.blocks[]: { kind: "paragraph", paragraph } | { kind: "table", table: { change, rows[]: { row, change, context, cells } } }
}

await suggestions.accept(card.id); // selects what landed
await suggestions.reject(card.id); // the document does not change
await suggestions.show(card.id); // selects the text a card changes and scrolls to it
```

`startCollab` without `send` makes a session of one, with no server. If the page is already in a shared session, pass `observe` to that `startCollab` call, and an accepted card goes to the other writers like typing.

The sandbox edits with tracking on and returns the whole file. A file that Word saved works too:

```ts theme={null}
const doc = await WordDocument.fromBytes(input);
doc.revisionAuthor = "Assistant";
doc.changeTrackingMode = "TrackAll";
doc.body.search("30 days").getFirst().insertText("15 business days", "Replace");
doc.body.search("Confidential Information").getFirst().font.bold = true;
return doc.toBytes();
```

### The fork

`fork()` takes the bytes and starts to record each edit the document takes. The cards move past those edits. So:

1. **Send `run.bytes`, nothing else.** A saved file or a stored copy does not have the user's unsaved edits, and the cards would undo them.
2. **Give `run.id` back with the result**: `load(run.id, bytes)`. Several runs can be open.
3. **Do not diff the result against the live document.** `load` diffs against the fork, then moves the cards forward.
4. **Keep the page open from `fork()` to `load()`.** A run that is not loaded is in the page only. After a loaded run, use [save and restore](#save-and-restore).
5. **One `load` per run.** To revise, start a new run. A new run does not see pending cards of earlier runs, so tell the agent which ones are open. When two runs suggest the same change, accepting one makes the other `stale`.

### How cards are cut

By default, edits in one paragraph are separate cards unless they touch or only spaces part them, so the user can take one and leave the other. Pass `group: "paragraph"` to make each changed paragraph one card:

```ts theme={null}
new AgentSuggestions(model, render, { group: "paragraph" });
await suggestions.load(run.id, redlined, { group: "paragraph" }); // or per run
```

New paragraphs inserted together are one card, apart from the paragraph after them, even when that paragraph is edited too.

Pass `group: "revision"` when the agent answers other authors' changes:

* Each change of theirs that the agent accepts or rejects is a card of its own. The two halves of a replacement are one change.
* The agent's own edits are cut as by default, apart from those answers.
* An answer and an edit join only when they share text or an insert point, for example when the agent types inside the insertion it rejects.

`save` keeps the choice, and `restore` cuts the run the same way. A row, a table or a list still makes one card, whatever the choice.

### What a card has

| Field | Meaning |
| - | - |
| `state` | `pending`, `accepted` or `rejected`. See [Card states](#card-states) |
| `preview` | The paragraphs the card touches, read against the document now. Also `comments`, `notes` and `parts` (headers, footers and others), and `stories`: each header, footer, note or comment the card changes, with its `paragraphs`, a display `label` and a fixed `storyType` (`Header`, `Footer`, `Footnote`, `Endnote`, `Comments`, as `TrackedChange.storyType`) |
| `kinds` | `text`, `format`, `structure`, `part`, `review` |
| `settles` | `{ accept, reject }`: ids of revisions the document already held (another author's) that the card accepts or rejects. See [When the agent settles a revision](#when-the-agent-settles-a-revision) |
| `stale` | The user, or another accepted card, edited inside the text the card changes. It still applies; read it again first. Only a pending card is stale |
| `targets` / `missing` | Items the card deletes or formats, and how many of them the user deleted since the fork. `missing === targets`: the text is gone |
| `blocked` | Why `accept` refuses the card, from your [refuse policy](#when-the-user-edited-the-same-text) |
| `text` | `{ before, after }` when the card only changes text in one paragraph of the body, a header, a footer or a note. See [Rewrite a card](#rewrite-a-card) |
| `keys` | Your names for the card's edits. See [Your own ids](#your-own-ids) |
| `overlaps` | A hint: the pending cards of later runs that edit the same text. See [Overlapping cards](#overlapping-cards) |
| `paragraphs` | `{ index, paraId? }[]`: the body paragraphs the card reaches. See [The paragraphs a card reaches](#the-paragraphs-a-card-reaches) |

### Overlapping cards

`overlaps` is a hint on a pending card that edits text. It lists the pending cards of runs forked later (`r3` after `r2`) that edit the same text too. The agent may have redlined the text again, or made a second edit that goes with the first: you decide what to show.

* Accepting both merges the later card as `stale`.
* Only cards with revisions of their own count. A card that only comments, or only settles another author's revisions, does not.
* Edits elsewhere in the same paragraph do not count. Compare `paragraphs` for that.
* Without the editor, `spansOverlap(a.spans, b.spans)` tests two `DeckCard`s that follow one document.

### The paragraphs a card reaches

`paragraphs` lists the body paragraphs the card reaches now. For an accepted card, that is where it landed.

* `index` counts in `doc.body.paragraphs` order (cells included).
* `paraId` is the paragraph's `w14:paraId` when the file has one.
* An edit in a text box names the paragraph that holds the box.
* The list is empty for a card only in a header, footer, note or other part.
* Each `list()` reads the paragraphs again, since an edit above moves the index.
* Without the editor, `redlineCards` gives the same field on each `RedlineCard`, counted in the base (`Redline.tokens`). `new ParagraphIndex(tokens).of(card.spans)` counts a `DeckCard` against the tokens its spans count in.

### Card states

```mermaid theme={null}
stateDiagram-v2
  [*] --> pending: load
  pending --> accepted: accept
  pending --> rejected: reject
  accepted --> pending: revert, or undo of the accept
  rejected --> pending: revert, or undo of the reject
  accepted --> rejected: rejected in the review margin
```

| Action | The document | Undo |
| - | - | - |
| `accept(id)` | Gets the card as the agent's tracked change | One step. Undo makes the card `pending`, redo accepts it again |
| `acceptMany(ids)`, `acceptAll()` | Gets each card the policy lets through, in order, across runs | One step for the whole batch. Returns the ids it accepted |
| `reject(id)`, `rejectAll()` | Does not change | One step; `rejectAll` is one step for all its cards. Not sent to other writers |
| `revert(id)` on an accepted card | The card's text and comments go, and the revisions it settled come back. See [Revert an accepted card](#revert-an-accepted-card) | One step |
| `revert(id)` on a rejected card | Does not change. The card followed the user's edits while rejected | One step |
| Accept or reject in the review margin | Settles the card's revisions | `list()` reads it from the document: the card reads `accepted` or `rejected` |

### Revert an accepted card

`revert(id)` applies the change that undoes the accept, moved past every edit since. It takes the card back out: its text, its comments and the revisions it settled.

* Revert in any order: accept A, B and C, then revert only A. What another accepted card shares with it stays.
* A comment the user put on only the card's inserted words goes with them, as in Word. A comment that also covers other words stays.
* It works after `restore` too: `save` keeps the change and the document it fits.

`revert` throws when:

* the review margin already settled the card's revisions
* another accepted card edits inside its text (revert that card first)
* nothing of the card is left

### When the user edited the same text

By default a card merges: if the user deleted the words it replaces, it inserts its words there; if the user typed new words there, both stay. A `refuse` policy stops that. It gets each pending card and returns a reason, or `undefined` to let it merge:

```ts theme={null}
import { AgentSuggestions, refuseMissing, refuseStale } from "@reductoai/docx-editor/suggestions";

new AgentSuggestions(model, render, { refuse: refuseStale }); // refuse any card the user edited inside
new AgentSuggestions(model, render, { refuse: refuseMissing }); // refuse only when text the card changes is gone
new AgentSuggestions(model, render, {
  refuse: (card) => (card.missing === card.targets && card.targets > 0 ? "The text is gone" : undefined),
});
```

`list()` gives the reason as `blocked`, `accept` throws it, and `acceptAll` skips the card. The policy runs again each time, so an undo can make a card clean again. A tracked deletion by the user is a format change, so it does not add to `missing`; `stale` catches it.

### Save and restore

`save(run.id)` gives a `SavedRun`: the fork, the sandbox's bytes, your keys and each card's state. Its `base`, `redlined` and `at` are whole .docx files as `Uint8Array`. Structured clone keeps them, so you can put a `SavedRun` in IndexedDB as it is:

```ts theme={null}
const saved = await suggestions.save(run.id);
await store.put(documentId, saved);

// Later, after model.open and startCollab:
for (const saved of await store.getAll(documentId)) await suggestions.restore(saved);
```

`JSON.stringify` does not keep the bytes. For a server, a database column or any other text store, use `savedRunToJSON`, which writes the files in base64, and `savedRunFromJSON` to read the text back:

```ts theme={null}
import { savedRunFromJSON, savedRunToJSON } from "@reductoai/docx-editor/suggestions";

await fetch(`/runs/${documentId}`, { method: "PUT", body: savedRunToJSON(saved) });
await suggestions.restore(savedRunFromJSON(await (await fetch(`/runs/${documentId}`)).text()));
```

`restore` also reads a run that went through plain `JSON.stringify`, or that holds its files as base64 text or number arrays. It throws a `TypeError` that names the field when a field is not a .docx.

Each card comes back in the state it was saved in, also when two cards hold pieces of one revision:

| Card | What `restore` does |
| - | - |
| Pending | Moves it past the edits made between the save and the restore |
| `waiting`: the user's edits took it out of reach | Keeps it as it stood |
| Accepted | Finds its revisions by `w:id`. `save` keeps the change that takes each one out, with the document as it was (`at`), so `restore` moves that change past the edits made since |
| No revisions of its own: it only settles other authors' revisions or adds a comment | Finds it by those revisions and comments (`SavedCard.marks`), not by its id alone |

You may change `SavedCard.state` in a stored run, for example when the user dismisses a card while the editor is closed:

| Change | Result after `restore` |
| - | - |
| `pending` → `rejected` | The card reads rejected. `revert(id)` brings it back |
| `rejected` → `pending` | The card waits again, and `accept` lands it |
| `accepted` → anything | Ignored: the card is in the document, so it reads accepted. Call `revert(id)` after `restore` to take it out |

A `SavedRun` holds up to three whole files (`base`, `redlined`, `at`) plus one change per accepted card (`SavedCard.inverse`). A run saved before 0.0.17 has no `inverse`: `revert` on its accepted cards rejects their revisions by id, and throws on a card without revisions.

### Rewrite a card

Show `card.text.after` in a text box, and accept what the user wrote:

```ts theme={null}
if (card.text) await suggestions.accept(card.id, { text: userText });
```

The card lands as a redline from the document's text to the user's, cut by words as Word's compare cuts them, and signed by the agent. A word deleted from another author's insertion is the agent's deletion inside it, as in Word. `accept` throws on a line break and on text equal to the document's.

The same works in a header, a footer, a footnote or an endnote: a card that changes text in one paragraph there has `text`, and the rewrite lands in that story. A card that edits two stories, or a story and the body, has no `text`.

### Reword or drop a card's comment

`card.preview.comments` holds the text of each comment the card adds. Pass `comment` to word it your way (one paragraph per line), or `null` to keep the edit without the comment:

```ts theme={null}
await suggestions.accept(card.id, { comment: "Sixty matches the master agreement." });
await suggestions.accept(card.id, { comment: null });
```

One text replaces every comment the card adds and keeps the first run's look. When a card adds more than one comment, pass an array with one entry per `preview.comments` entry, in that order. Each entry is the new text, or `null` to drop that comment alone:

```ts theme={null}
await suggestions.accept(card.id, { comment: ["Keep this one, reworded.", null] });
```

* A dropped comment takes its anchors and the comment parts it alone made.
* `save` keeps the wording, so a restored card shows it.
* `comment` and `text` can go together.

`accept` throws when:

* the card adds no comment
* the array has the wrong length
* every comment is dropped from a card that is only comments. Reject that card instead.

After the accept, the card's comments are ordinary comments: the user edits, answers or deletes them in the margin (`editComment`, `replyComment`, `deleteComment`). The card follows:

* `preview.comments` reads them as the document has them, and a restore does too.
* A revert takes them out as they are. The card then waits with the user's words, or without a deleted comment, and the next accept puts that back.
* Replies go out with the comment.

### Sign an accepted card as the reviewer

By default an accepted card stays the agent's tracked change. Pass `sign` to make it the reviewer's: its revisions and the comments it adds take the editor's author (`model.revisionAuthor`) and the time of the accept. Other authors' revisions in the card keep their names.

```ts theme={null}
await suggestions.accept(card.id, { sign: true });
await suggestions.acceptMany(ids, { sign: { author: "J. Chen", date: new Date() } });
new AgentSuggestions(model, render, { sign: true }); // every accept; `sign: false` on one accept keeps the agent's name
```

`accept` throws when `sign: true` and the editor has no author.

### Answer another author's change yourself

A `review` card accepts or rejects revisions of another author (`settles`). The user can answer them in place of the agent:

| `review` | Their insertion | Their deletion |
| - | - | - |
| `"accept"` | Stays, plain text | Goes |
| `"reject"` | Goes | Comes back, plain text |
| `"strike"` | Stays under the reviewer's tracked deletion | Refused |
| `{ revise: text }` | Rewritten to `text` as the reviewer's tracked edits inside it | Accepted, and `text` goes in as the reviewer's insertion |

```ts theme={null}
await suggestions.accept(card.id, { review: "strike" });
await suggestions.accept(card.id, { review: { revise: "45 days " } });
```

To answer only some of them, pass `{ choice, ids }` with ids from the card's `theirs`. Those take `choice`. The rest keep the agent's answer and its edits on them, or stay as they are when the agent did not answer them. `accept` throws on an id that is not in `theirs`, and on an empty list:

```ts theme={null}
const [fair] = card.theirs;
await suggestions.accept(card.id, { review: { choice: "accept", ids: [fair] } });
```

How the answer lands:

* Marks it adds are the reviewer's (`sign`, else `model.revisionAuthor`).
* It goes in the header, footer or note the card edits.
* A format change can only be accepted.
* Undo, `revert`, `save` and `restore` work as for any accept.

The agent's own edits in the card:

* They land as they are, except edits of words the answer takes out where the agent kept them: those go, with any words the agent typed beside them.
* Under `group: "revision"` such edits are another card, so `accept` throws while that card is accepted, and that card's `accept` throws while the answer is in.
* A card that settles nothing but edits on or beside another author's change (its `theirs`) takes `review` too: the answer replaces the agent's edits on that change, and its other edits land.

`accept` throws on a card that settles nothing and has no `theirs`, and when `review` comes with `text` or `comment`.

### Edit a card any way you like

For a change that `text`, `comment` and `review` do not cover, edit the card yourself. `draft(id)` gives the document with the card in, as a file. Edit it with any Word API, with Track Changes on as the reviewer, and give it back to `accept`:

```ts theme={null}
const doc = await WordDocument.fromBytes(await suggestions.draft(card.id));
doc.session.changeTrackingMode = "TrackAll";
doc.session.revisionAuthor = model.revisionAuthor;
doc.body.search("30 days").getFirst().insertText("45 days", "Replace");
await suggestions.accept(card.id, { draft: await doc.toBytes() });
```

The card lands as the edited file reads, as one undo step: the agent's change, then the host's edits, each mark with the author the file gives it. `revert` and undo take all of it back out. The user can keep typing while the host holds the draft: the edits are carried past what the document takes meanwhile. Settings a save writes (rsids, the Track Changes switch) stay out.

* Once reverted, the card waits as it landed, with the host's edits in it
* To reword text the card inserts, edit as the card's author (`revisionAuthor` set to the agent's name), with Track Changes on and `sign` at the accept. Text an author deletes from their own insertion goes with no deletion mark, as in Word, and `sign` makes every mark the reviewer's. As the reviewer, the replaced words stay as a deletion inside the new text
* With Track Changes off, every edit lands untracked: inside the card's insertion that reads the same, but an edit to text the card does not insert changes the document with no mark
* `save` keeps how the card read (`SavedCard.drafted`), so a restored card shows the host's version
* `accept` throws on a draft `draft()` did not give for that card, and when `draft` comes with `text`, `comment` or `review`
* `sign` signs every new mark the card lands, the host's too; other authors' revisions keep their names
* Each draft is a whole file: about 50 ms for an 800-paragraph form, about 2 s for a 4,600-paragraph contract

### Your own ids

To show why the agent made an edit, map its revision ids to your key in the sandbox, and pass the map to `load`:

```ts theme={null}
// Sandbox, after the agent's edit:
const keys: Record<number, string> = {};
for (const change of doc.body.getTrackedChanges().items)
  for (const id of change.revisionIds) keys[id] ??= "why-12";

// Page:
await suggestions.load(run.id, redlined, { keys });
// card.keys: ["why-12"]
```

The page can join your edits into one card, so a card can hold several keys. It does not cut one card finer, because each card must apply alone. `save` and `restore` keep the keys.

### Limits

* Pending cards are not in the document. Keep the `SavedRun` with the document to show them again.
* Word gives new `w:id` values to revisions when it saves the file. After that, a restored accepted card cannot find its revisions, and your keys do not match.
* A card rejected in the review margin and then edited can read `accepted`. A format card accepted in the margin and then formatted again can read `rejected`.
* When the agent deletes across another author's tracked deletion (a counterparty's), that deletion stays theirs. Formatting over another author's insertion is signed by the agent.
* The agent's edits and its settles are separate cards unless they touch. `revert` on a card that does both takes out its edits and puts the settled revisions back.
* A revision in the sandbox's file that marks nothing (an empty `w:ins` a tool left) makes no card.
* Keep tracking on in the sandbox. Untracked edits give coarse cards (a one-word change can replace its paragraph), and they land untracked.

## Word add-in

The same cards work when the user reviews in Word. `WordReview` from `@reductoai/docx/redline` follows Word's file. Word has no live change feed, so there is no `fork()`: the fork is the file you read before the agent starts, and `WordReview` diffs each file you give it against the last one.

```mermaid theme={null}
sequenceDiagram
  participant Word
  participant AddIn as Your add-in (WordReview)
  participant Sandbox as Agent sandbox
  AddIn->>Word: getFileAsync
  Word-->>AddIn: base
  AddIn->>Sandbox: base
  Sandbox-->>AddIn: redlined
  Note over Word: the user keeps typing
  AddIn->>Word: getFileAsync
  Word-->>AddIn: now
  Note over AddIn: open(base, redlined, now): cards
  loop each accept
    AddIn->>Word: getFileAsync
    Note over AddIn: read(file), then accept(id): edits
    AddIn->>Word: applyWordEdits (insertOoxml "Replace")
    AddIn->>Word: getFileAsync
    Note over AddIn: landed(id, file): other cards move past it
  end
```

```ts theme={null}
import { WordReview, applyWordEdits } from "@reductoai/docx/redline";

const base = await wordFile(); // wordFile: getFileAsync(Compressed), as bytes
const redlined = await runAgent(base); // tracking on in the sandbox
const review = await WordReview.open(base, redlined, await wordFile()); // the user typed meanwhile

async function accept(cardId: string) {
  await review.read(await wordFile()); // always first: the edits are made against the last file read
  const card = review.cards.find((each) => each.id === cardId)!;
  if (card.stale || card.missing) return "The document changed here. Look at the card again.";
  const { edits, unsupported } = await review.accept(cardId);
  if (unsupported.length) return `Word cannot take this card: ${unsupported.join(", ")}`;
  try {
    await Word.run((context) => applyWordEdits(context, edits));
  } catch (error) {
    review.unaccept(cardId);
    throw error;
  }
  await review.landed(cardId, await wordFile()); // the other cards move past it
}
```

Each edit replaces a run of paragraphs, a table or a cell's content with `insertOoxml` "Replace". The OOXML holds the agent's tracked markup and the styles, lists, pictures, links, comments and notes it uses, so `applyWordEdits` turns Word's tracking off while it replaces.

| Your add-in must | Because |
| - | - |
| Call `review.read` before each `accept` | The edits are made against the last file read. Without it they go to the wrong paragraphs |
| Check `card.stale` and `card.missing` | `WordReview` has no refuse policy. A stale card merges with the user's edit: the user's "post" and the agent's "email" give "postemail" |
| Keep rejects in your UI | A rejected card is not in the document. Or call `review.deck.reject(id)` |
| Not find revisions by their ids | Word numbers revisions by their position in the file, so a reject or undo of one changes the ids of all after it |

### Limits

* `WordReview` cannot tell when the user undid an accept (Ctrl+Z removes the card's revisions in one step) or settled it in the margin. The card stays `accepted`.
* It has no `revert`, no text rewrite, no refuse policy and no save.
* A card that changes a style, list or comment that Word already has is `unsupported`.
* An accept replaces whole paragraphs, so paragraph ids and Word's state inside them change.
