@docx-editor.dev/editor-api 2.31.0 → 2.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/OFFICE_JS_GUIDE.md +187 -12
- package/README.md +31 -3
- package/dist/agent.d.mts +243 -0
- package/dist/agent.d.ts +243 -0
- package/dist/agent.js +5 -0
- package/dist/agent.mjs +5 -0
- package/dist/browser.d.mts +7 -3
- package/dist/browser.d.ts +7 -3
- package/dist/browser.js +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{server-Dw4k9h0p.d.mts → server-CDfqcHfQ.d.mts} +786 -473
- package/dist/{server-Dw4k9h0p.d.ts → server-CDfqcHfQ.d.ts} +786 -473
- package/docs/accept-reject-without-scrolling.md +95 -0
- package/docs/comment-on-found-text.md +72 -0
- package/docs/custom-review-cards.md +178 -0
- package/docs/highlight-ranges.md +48 -0
- package/docs/index.md +36 -0
- package/docs/propose-rewrite.md +247 -0
- package/docs/tracked-replacement.md +68 -0
- package/package.json +11 -2
package/OFFICE_JS_GUIDE.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
The public document model follows a documented subset of Word's Office.js API. Host creation, authentication, collaboration transport, and job lifetime belong outside that model.
|
|
4
4
|
|
|
5
|
+
Use this API for headless, server, and agent pipelines. To build a review UI in a React or Vue host, use `useReview()` and `DocxEditorReview` from `@docx-editor.dev/pro/react` or `@docx-editor.dev/pro/vue` instead. For the task-by-task choice, see `docs/index.md` in this package.
|
|
6
|
+
|
|
5
7
|
## A complete server example
|
|
6
8
|
|
|
7
9
|
This function returns a DOCX containing one pending replacement. Supply the agent's author name. The `finally` block disposes the runtime after the job.
|
|
@@ -203,10 +205,10 @@ Use `isDocxEditorError(error)` and branch on `error.code`. `error.target` identi
|
|
|
203
205
|
| `InvalidObjectPath` | Sync before using a newly returned proxy, or acquire a fresh proxy in a new run. `debugInfo.innerError.code` `edit.stale-target` means the document no longer holds the object; read again. |
|
|
204
206
|
| `StaleDocument` | Search again, reconsider the model proposal, then write. |
|
|
205
207
|
| `ConflictingChanges` | Separate edits that claim the same paragraph and reconsider anchors between commits. |
|
|
206
|
-
| `NotSupported` |
|
|
207
|
-
| `NotImplemented` |
|
|
208
|
+
| `NotSupported` | The call is outside the supported subset for this host, mode, or content. Don't retry it. Read `debugInfo.innerError.code`, then check the host, tracking mode, author, and operation against the [tracking subset](#tracking-subset). |
|
|
209
|
+
| `NotImplemented` | The API does not implement the call for this target, such as a tracked edit beside your own pending change. Don't retry it. Read `debugInfo.innerError.code`, reconsider the target, and do not disable tracking. |
|
|
208
210
|
| `InvalidArgument` | Validate the argument and consult the member's JSDoc. |
|
|
209
|
-
| `GeneralException` | Act on `error.debugInfo.innerError.code` (see [Diagnostics](/docs/2.x/guides/diagnostics#edit-internal-invariant)). For `edit.internal-invariant`, or when `innerError` is absent, report the failure with the engine version and do not retry the write unchanged. |
|
|
211
|
+
| `GeneralException` | Act on `error.debugInfo.innerError.code` (see [Diagnostics](https://www.docx-editor.dev/docs/2.x/guides/diagnostics#edit-internal-invariant)). For `edit.internal-invariant`, or when `innerError` is absent, report the failure with the engine version and do not retry the write unchanged. |
|
|
210
212
|
|
|
211
213
|
### Read why the engine refused
|
|
212
214
|
|
|
@@ -225,7 +227,7 @@ try {
|
|
|
225
227
|
}
|
|
226
228
|
```
|
|
227
229
|
|
|
228
|
-
For all codes, see [Diagnostics](/docs/2.x/guides/diagnostics). To record anonymous refusal events, add a telemetry module to `createServer({ modules })`. For more information, see [Server agents](/docs/2.x/telemetry/agents).
|
|
230
|
+
For all codes, see [Diagnostics](https://www.docx-editor.dev/docs/2.x/guides/diagnostics). To record anonymous refusal events, add a telemetry module to `createServer({ modules })`. For more information, see [Server agents](https://www.docx-editor.dev/docs/2.x/telemetry/agents).
|
|
229
231
|
|
|
230
232
|
### Recover from a stale range
|
|
231
233
|
|
|
@@ -279,6 +281,9 @@ await runtime.run(async (context) => {
|
|
|
279
281
|
| Replace a range | `range.insertText(text, 'Replace')` |
|
|
280
282
|
| Delete range content | `range.delete()` or `range.clear()` |
|
|
281
283
|
| Propose removing a paragraph | `paragraph.delete()` |
|
|
284
|
+
| Propose a field | `range.insertField('After', 'Ref', '_Ref123456 \\h')` |
|
|
285
|
+
| Write a proposed field's result | Sync, then `field.result.insertText('Figure 3', 'Replace')` |
|
|
286
|
+
| Propose an equation | `range.insertOoxml(flatOpcWithOneEquation, 'After')` |
|
|
282
287
|
| Read the current mode | `document.load('changeTrackingMode')`, then sync and read the property |
|
|
283
288
|
| Make an intentional permanent edit | Explicitly set `changeTrackingMode = 'Off'` |
|
|
284
289
|
|
|
@@ -290,11 +295,36 @@ await runtime.run(async (context) => {
|
|
|
290
295
|
| Paragraph deletion | `paragraph.delete()` records the text and the paragraph mark as deletions; accept removes the paragraph |
|
|
291
296
|
| Font and paragraphs | Track font, paragraph-format, and paragraph-style edits as property revisions |
|
|
292
297
|
| Paragraph insertion | Track inserted text and paragraph marks |
|
|
298
|
+
| Paragraph split | `insertText()` with `\n` tracks the text and each new paragraph mark; reject joins the paragraphs again |
|
|
293
299
|
| Lists | Track creation, membership, and level changes; configure newly proposed definitions |
|
|
294
300
|
| Tables | Track complete insertion, cell values, row additions, and partial row deletions |
|
|
295
301
|
| Content controls | Wrap nonempty ordinary text in `PlainText`, `RichText`, or `DatePicker` controls outside collaboration |
|
|
302
|
+
| Fields | Insert an inert field as one complex field in one tracked insertion, and write the cached result of your own pending field into it; reject removes the whole field |
|
|
303
|
+
| Equations | `insertOoxml()` with one inline `m:oMath` in a Flat OPC package writes one tracked insertion; reject removes the whole equation |
|
|
304
|
+
|
|
305
|
+
Tracked range edits refuse table and wrapper boundaries. In collaboration, a tracked replacement must remain within one paragraph. One refusal refuses the whole sync.
|
|
306
|
+
|
|
307
|
+
A tracked paragraph deletion fails with `NotSupported` for these paragraphs:
|
|
308
|
+
|
|
309
|
+
- The last paragraph of a story, table cell, or content control.
|
|
310
|
+
- A paragraph directly before a table or a block content control.
|
|
311
|
+
- A paragraph whose mark ends a section.
|
|
312
|
+
- A paragraph with an inline content control.
|
|
313
|
+
- A paragraph that holds a complex field boundary whose matching boundary is in another paragraph.
|
|
314
|
+
- A paragraph that nests inline content more than 64 levels deep.
|
|
315
|
+
|
|
316
|
+
A tracked paragraph deletion fails with `NotImplemented` in these cases:
|
|
317
|
+
|
|
318
|
+
- The paragraph has your own pending change, or another author's pending paragraph mark, formatting, move, or structural change.
|
|
319
|
+
- The start of the next paragraph has a pending change.
|
|
320
|
+
- A later sync deletes beside your own pending deletion. Delete adjacent paragraphs in one sync instead.
|
|
321
|
+
- A tracked deletion or replacement starts a paragraph whose previous paragraph mark you already proposed deleting.
|
|
296
322
|
|
|
297
|
-
|
|
323
|
+
Text that another participant types into struck text joins the proposed deletion. Reject restores it, and accept removes it with no separate revision.
|
|
324
|
+
|
|
325
|
+
Tracked edits can go inside or beside another author's pending text insertion or deletion. A deletion of their inserted text is recorded inside their insertion. New text lands after any deleted text, and new text inside their insertion splits it into two halves. The returned range names the new text where it lands, and each author's change stays a separate decision. For more information, see [Edit another author's pending text](#edit-another-authors-pending-text). Continuation can extend the runtime author's text and paragraph proposals.
|
|
326
|
+
|
|
327
|
+
Simple fields with nested fields or other result containers refuse tracked deletion and replacement. Direct result runs remain supported. A tracked deletion or replacement that covers an equation strikes the whole equation: accepting removes it, and rejecting restores it.
|
|
298
328
|
|
|
299
329
|
An author can configure a complete proposed table while it has no foreign revisions. Existing table properties and columns require permanent edits. Tracked table and cell value replacement refuse in collaboration. Row deletion suggestions must leave a row without a pending deletion. Pending row or cell structure revisions refuse tracked row deletion with `NotImplemented`.
|
|
300
330
|
|
|
@@ -306,9 +336,31 @@ When a person adopts an agent's suggestions, attribute them to that person with
|
|
|
306
336
|
|
|
307
337
|
Standard `insertText('', 'Replace')` means deletion, and an empty insertion is a no-op. Agent tools should require nonempty insertion/replacement text and expose deletion as an explicit model decision. The shipped worker does this. The [compatibility manifest](https://github.com/eigenpal/docx-editor/blob/main/packages/editor-api/compat/manifest.json) records measured members and behavioral differences.
|
|
308
338
|
|
|
339
|
+
### Propose a paragraph split
|
|
340
|
+
|
|
341
|
+
`insertText()` on a body, paragraph, or range treats `\n`, `\r`, and `\r\n` as paragraph breaks. The text after a break starts a new paragraph with the properties of the paragraph that you wrote into. With `TrackMineOnly`, the inserted text and each new paragraph mark are tracked insertions.
|
|
342
|
+
|
|
343
|
+
To split between two sentences, replace only the gap between them with `'\n'`:
|
|
344
|
+
|
|
345
|
+
```ts
|
|
346
|
+
await runtime.run(async (context) => {
|
|
347
|
+
context.document.changeTrackingMode = 'TrackMineOnly';
|
|
348
|
+
const body = context.document.body;
|
|
349
|
+
const first = body.search('the goods.').getFirst();
|
|
350
|
+
const second = body.search('The buyer').getFirst();
|
|
351
|
+
const gap = first.getRange('End').expandTo(second.getRange('Start'));
|
|
352
|
+
gap.insertText('\n', 'Replace');
|
|
353
|
+
await context.sync();
|
|
354
|
+
});
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
The proposal strikes the one space and adds one paragraph mark. Accept gives two paragraphs with no trailing space. Reject joins the paragraphs again. Don't replace a sentence with the same words and a break: that proposes deleting and inserting those words.
|
|
358
|
+
|
|
359
|
+
The returned range runs from the first inserted character to the end of the last inserted segment. Text that lands inside an inline content control refuses with `NotSupported` and `edit.indivisible-content`. A write with a break can't share a sync with another edit in the same paragraph. For the batching rules and a refusal table, see [Propose several structural edits in one run](https://www.docx-editor.dev/docs/2.x/editor-api/revisions#propose-several-structural-edits-in-one-run).
|
|
360
|
+
|
|
309
361
|
### Edit another author's pending text
|
|
310
362
|
|
|
311
|
-
A counterparty's pending insertion is ordinary text to a tracked edit. Replace it, delete part of it, or write inside it. Your changes record under the runtime author, and each author's change stays a separate decision. New text inside their insertion splits it, so their insertion becomes two revisions, one on each side of your text. To accept or reject all of their insertion, decide both revisions, or pass both to `revisions.resolve(action, [first, second])`.
|
|
363
|
+
A counterparty's pending insertion is ordinary text to a tracked edit. Replace it, delete part of it, or write inside it. Your changes record under the runtime author, and each author's change stays a separate decision. New text inside their insertion splits it, so their insertion becomes two revisions, one on each side of your text. To accept or reject all of their insertion, decide both revisions, or pass both to `revisions.resolve(action, [first, second])`. The same edits work in a collaboration session; a participant's concurrent accept or reject of the counterparty's change applies to all of that change and to nothing else. In the following example, the agent replaces a counterparty's proposed term, then rejects only its own revisions:
|
|
312
364
|
|
|
313
365
|
```ts
|
|
314
366
|
// Create runtime with author: 'Avery Chen' before this example.
|
|
@@ -339,11 +391,100 @@ These tracked edits fail with `NotImplemented`. Read `error.debugInfo.innerError
|
|
|
339
391
|
| `innerError.code` | Edit |
|
|
340
392
|
| --- | --- |
|
|
341
393
|
| `edit.tracked-deleted-text-only` | A deletion or replacement that covers only deleted text and no paragraph mark |
|
|
342
|
-
| `edit.tracked-foreign-revision-unsupported` | An edit that touches another author's paragraph mark, formatting, move, or structural change
|
|
394
|
+
| `edit.tracked-foreign-revision-unsupported` | An edit that touches another author's paragraph mark, formatting, move, or structural change, or new text inside a link or content control within their insertion |
|
|
343
395
|
| `edit.tracked-own-pending-change` | An edit that covers or borders your own pending change |
|
|
344
396
|
|
|
345
397
|
The range that a tracked `insertText()` returns names your own pending insertion. With tracking on, replacing or deleting that range fails with `edit.tracked-own-pending-change`, because the edit would cover your own pending text. Write the final text in one call, or reject your revision and write again.
|
|
346
398
|
|
|
399
|
+
### Rewrite a paragraph word by word
|
|
400
|
+
|
|
401
|
+
To propose a model's rewrite of a paragraph, use `prepareRewrite` from `@docx-editor.dev/editor-api/agent`. It reads the paragraph into text for your model. `draft.apply()` then applies the steps in this section for you, keeps fields, equations, note references, and locked controls whole, and rejects only its own changes if a write fails. You own the prompt and the model call:
|
|
402
|
+
|
|
403
|
+
```ts
|
|
404
|
+
import { prepareRewrite } from '@docx-editor.dev/editor-api/agent';
|
|
405
|
+
|
|
406
|
+
await runtime.run(async (context) => {
|
|
407
|
+
const paragraph = context.document.body.paragraphs.getFirst();
|
|
408
|
+
const draft = await prepareRewrite(context, paragraph);
|
|
409
|
+
const prompt = ['Make this clause shorter.', draft.legend, draft.text].join('\n\n');
|
|
410
|
+
await draft.apply(await callModel(prompt));
|
|
411
|
+
});
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
`draft.text` holds the paragraph with numbered placeholders, and `draft.legend` states the placeholder rules. To check model text without writing, call `draft.check(modelText)`. For several paragraphs, prepare them all, call the model for every draft at once, and then apply the drafts one after another. For its guarantees and error codes, see [Propose an AI rewrite as tracked changes](https://www.docx-editor.dev/docs/2.x/recipes/propose-rewrite). The rest of this section shows the calls it makes.
|
|
415
|
+
|
|
416
|
+
Split a paragraph into word ranges with `paragraph.getTextRanges([' '])`. Each range keeps its trailing space, so a deleted word takes its space with it, and a replacement for a range ends with a space too. Address a run of words with `first.expandTo(last)`. After tracked edits, `paragraph.text` reads the deleted and the inserted words together. `getReviewedText('Current')` reads the text as if you accepted every change, and `'Original'` reads it as if you rejected every change.
|
|
417
|
+
|
|
418
|
+
Each word range is a snapshot. An edit before a range in its paragraph makes the range fail with `StaleDocument`, and an edit after it keeps it valid. Read the ranges once, before you edit. Pass the range texts to the model and plan the edits by range index, because a paragraph can repeat a word. Then apply the edits from the last index to the first, one sync per edit:
|
|
419
|
+
|
|
420
|
+
```ts
|
|
421
|
+
await runtime.run(async (context) => {
|
|
422
|
+
context.document.changeTrackingMode = 'TrackMineOnly';
|
|
423
|
+
const paragraph = context.document.body.paragraphs.getFirst();
|
|
424
|
+
const words = paragraph.getTextRanges([' ']);
|
|
425
|
+
words.load('items/text');
|
|
426
|
+
await context.sync();
|
|
427
|
+
|
|
428
|
+
// Pass plain text to the model; keep the ranges in this run.
|
|
429
|
+
// ['The ', 'fee ', 'is ', 'due ', 'per ', 'unit ', 'and ', 'the ', 'buyer ', ...]
|
|
430
|
+
const tokens = words.items.map((range) => range.text);
|
|
431
|
+
|
|
432
|
+
// Edits by index, applied from the last index to the first.
|
|
433
|
+
words.items[7]!.delete();
|
|
434
|
+
await context.sync();
|
|
435
|
+
words.items[4]!.insertText('net ', 'After');
|
|
436
|
+
await context.sync();
|
|
437
|
+
words.items[0]!.expandTo(words.items[1]!).insertText('Each charge ', 'Replace');
|
|
438
|
+
await context.sync();
|
|
439
|
+
|
|
440
|
+
const proposed = paragraph.getReviewedText('Current');
|
|
441
|
+
await context.sync();
|
|
442
|
+
console.log(tokens.length, proposed.value);
|
|
443
|
+
});
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
A field, an equation, a picture, or a note reference reads as one unit that never splits and joins the word it touches. A field reads as its result, which can contain spaces, such as `Section 4.2`. An equation, a picture, and a note reference read as U+FFFC. A tab ends a range only when you list `'\t'` as a mark. `trimSpacing` removes spaces, tabs, and column breaks from the edges of each range; use it to read words, not to plan deletions. `Range.getRange('Start')` and `'End'` answer an insertion point; `'After'` fails with `NotSupported`. Ranges in different stories make `expandTo()` fail with `InvalidArgument`.
|
|
447
|
+
|
|
448
|
+
A tracked deletion or replacement that covers an equation strikes the whole equation. Accept removes it, and reject restores it.
|
|
449
|
+
|
|
450
|
+
The words of an inline content control join the ranges around it. `paragraph.contentControls` and `range.contentControls` list the controls that the paragraph or range overlaps, including a control that holds the whole range. Before you plan edits, load them with `cannotEdit`, `tag`, and `text`, for each word range in one sync, and keep each locked control as one unit. A replacement or deletion of part of a content-locked control fails, and `error.debugInfo.innerError.code` is `edit.protected-content`. The outer code is `GeneralException` with `TrackMineOnly` and `InvalidArgument` without it, so branch on the inner code. With tracking on, a deletion or replacement that covers the whole control proposes removing the control as one deletion.
|
|
451
|
+
|
|
452
|
+
Map each difference between the old and the new words to one call. The last range of a paragraph has no space after it:
|
|
453
|
+
|
|
454
|
+
| Difference | Call |
|
|
455
|
+
| --- | --- |
|
|
456
|
+
| Replace one or more words | `first.expandTo(last).insertText(text, 'Replace')` |
|
|
457
|
+
| Delete one or more words | `first.expandTo(last).delete()` |
|
|
458
|
+
| Insert before the first word | `words[0].insertText(text, 'Before')` |
|
|
459
|
+
| Insert after a word | `word.insertText(text, 'After')` |
|
|
460
|
+
| Insert after the last word | `last.insertText(' ' + text, 'After')`, because the last word has no space after it |
|
|
461
|
+
|
|
462
|
+
Ranges follow the runtime's `revisionTextView`. Text that the view hides, such as a pending insertion in the `original` view, holds no ending mark, and a range starts and ends at characters that the view shows. Hidden text between two shown characters of one range stays inside the range, so an edit through that range also changes the hidden text.
|
|
463
|
+
|
|
464
|
+
Do not split the paragraph again after tracked edits to plan more edits. A range over pending revisions can join deleted and inserted text, such as `two2` after you replace `two` with `2`. An edit that touches your own pending change fails with `NotImplemented`, and `error.debugInfo.innerError.code` is `edit.tracked-own-pending-change`. Read the proposed text with `getReviewedText('Current')`, then edit a range outside your pending change. To change your proposal itself, reject it and propose again.
|
|
465
|
+
|
|
466
|
+
Catch a refused word-range edit and read its rule from `debugInfo`:
|
|
467
|
+
|
|
468
|
+
```ts
|
|
469
|
+
import { DocxEditor, isDocxEditorError } from '@docx-editor.dev/editor-api';
|
|
470
|
+
|
|
471
|
+
const runtime = await DocxEditor.createServer(bytes, { author: 'Review agent' });
|
|
472
|
+
await runtime.run(async (context) => {
|
|
473
|
+
context.document.changeTrackingMode = 'TrackMineOnly';
|
|
474
|
+
const words = context.document.body.paragraphs.getFirst().getTextRanges([' ']);
|
|
475
|
+
words.load('items');
|
|
476
|
+
await context.sync();
|
|
477
|
+
try {
|
|
478
|
+
words.items[0]!.insertText('Each ', 'Replace');
|
|
479
|
+
await context.sync();
|
|
480
|
+
} catch (error) {
|
|
481
|
+
if (!isDocxEditorError(error)) throw error;
|
|
482
|
+
// For example, 'edit.protected-content' inside a content-locked control.
|
|
483
|
+
console.log(error.code, error.debugInfo.innerError?.code);
|
|
484
|
+
}
|
|
485
|
+
});
|
|
486
|
+
```
|
|
487
|
+
|
|
347
488
|
## Review changes in a range
|
|
348
489
|
|
|
349
490
|
Use `range.revisions` to reach the tracked changes inside a search result, a comment range, or any other range. The collection lists the changes the range overlaps in its own story, including a nested change or another author's change beside it. A partly covered change is listed whole, and a replacement lists its deletion and insertion separately. Load the members and decide on each one:
|
|
@@ -372,7 +513,7 @@ await runtime.run(async (context) => {
|
|
|
372
513
|
});
|
|
373
514
|
```
|
|
374
515
|
|
|
375
|
-
`acceptAll()` and `rejectAll()` on a range collection resolve every change the range overlaps, whole, including
|
|
516
|
+
`acceptAll()` and `rejectAll()` on a range collection resolve every change the range overlaps, whole, including history that `items` omits. They fail with `NotImplemented` when one of those changes is read-only. When the range overlaps only part of a group of nested changes, only the overlapped changes resolve; the others stay pending. Two decisions in one sync that reach one change resolve it once; contrary decisions fail with `ConflictingChanges`. A change inside text that a decision in the same sync removes, such as a rejected insertion or an accepted deletion, goes with that text, so any decision on it in that sync is skipped. This also applies to `accept()` and `reject()` on single revisions. `resolve()` and `setAuthor()` refuse with `NotSupported` on a range collection. Use the story's `body.revisions` for them.
|
|
376
517
|
|
|
377
518
|
A browser review panel identifies cards by `key`. Pass the key to the DocxEditor function `getReviewItemRevisions(context, key)` to decide the card's own change, or the two halves of a paired replacement. `getReviewItemRange(context, key)` returns the range that a card covers; use `getReviewItemRangeOrNullObject(context, key)` when another reviewer can resolve the change first. Do not match cards to revisions by text.
|
|
378
519
|
|
|
@@ -416,21 +557,55 @@ await runtime.run(async (context) => {
|
|
|
416
557
|
|
|
417
558
|
`TableRow.insertRows('Before', count, values)` and `'After'` support ordinary source rows beside unrelated merged headers. Merged source rows and crossing vertical merges refuse. Keep each row insertion as the only write in its sync. Sync before editing returned rows. For more information, see [Tables and cells](https://docx-editor.dev/docs/2.x/editor-api/tables).
|
|
418
559
|
|
|
419
|
-
##
|
|
560
|
+
## Merge and split cells
|
|
561
|
+
|
|
562
|
+
`Table.mergeCells(topRow, firstCell, bottomRow, lastCell)` merges a rectangle and returns the merged cell. Edits to that cell can share the sync. `TableCell.split(rowCount, columnCount)` splits one cell. A ragged rectangle refuses with `InvalidArgument` and `innerError.code` `edit.table-merge-not-rectangle`. A split the cell cannot take refuses with `InvalidArgument` and `edit.table-split-unsupported`. Both refuse with `NotSupported` in a tracking mode. Do not turn tracking off to make them succeed.
|
|
563
|
+
|
|
564
|
+
```ts
|
|
565
|
+
import { DocxEditor, isDocxEditorError } from '@docx-editor.dev/editor-api';
|
|
566
|
+
|
|
567
|
+
const runtime = await DocxEditor.createServer(bytes);
|
|
568
|
+
await runtime.run(async (context) => {
|
|
569
|
+
const table = context.document.body.tables.getFirst();
|
|
570
|
+
const header = table.mergeCells(0, 0, 0, 2);
|
|
571
|
+
header.value = 'Quarterly results';
|
|
572
|
+
try {
|
|
573
|
+
await context.sync();
|
|
574
|
+
} catch (error) {
|
|
575
|
+
if (!isDocxEditorError(error)) throw error;
|
|
576
|
+
// A merged cell crosses the rectangle: read the table again and pick its real corners.
|
|
577
|
+
const reason = error.debugInfo.innerError;
|
|
578
|
+
if (reason?.code !== 'edit.table-merge-not-rectangle') throw error;
|
|
579
|
+
feedback.push(reason.message);
|
|
580
|
+
}
|
|
581
|
+
});
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
## Pictures and fields
|
|
420
585
|
|
|
421
|
-
Insert a manual line break with `range.insertBreak('Line', 'After')` or `\v` in inserted text. Call `await context.sync()` after queuing the write. Manual line breaks support `TrackMineOnly` and text edits in the same sync. Single-line content controls refuse manual line breaks. Reads report manual line breaks as `\v`, column breaks as U+000E, and paragraph separators as `\r`. Text writes refuse U+000E and paragraph separators. Do not flatten these characters before sending read text back to the document.
|
|
586
|
+
Insert a manual line break with `range.insertBreak('Line', 'After')` or `\v` in inserted text. Call `await context.sync()` after queuing the write. Manual line breaks support `TrackMineOnly` and text edits in the same sync. Single-line content controls refuse manual line breaks. Reads report manual line breaks as `\v`, column breaks as U+000E, and paragraph separators as `\r`. Text writes refuse U+000E. `insertText()` on a body, paragraph, or range writes `\n`, `\r`, and `\r\n` as paragraph breaks. Other paragraph separators refuse. Do not flatten these characters before sending read text back to the document.
|
|
422
587
|
|
|
423
588
|
Insert PNG or JPEG images with `range.insertInlinePictureFromBase64(data, 'After')`. Sync before setting properties on the returned picture. Width and height use points. New pictures lock the aspect ratio. Set `lockAspectRatio = false` before setting independent dimensions. Set `altTextDescription` to describe the image. Deletion preserves shared media relationships.
|
|
424
589
|
|
|
590
|
+
Insert an inert field with `range.insertField(location, type, text)`. The runtime inserts `Page`, `NumPages`, `Ref`, `PageRef`, `NoteRef`, `Seq`, `StyleRef`, `Date`, `Time`, and `TOC`. `text` holds the arguments, such as a bookmark name and switches: `range.insertField('After', 'Ref', '_Ref123456 \\h')`. With `Empty`, `text` holds the whole instruction. The runtime never evaluates an instruction, and a new field has an empty cached result.
|
|
591
|
+
|
|
592
|
+
Untracked `Page`, `NumPages`, and `TOC` fields are simple fields. Other fields, and every tracked field, are complex fields. Their runs take the formatting of the text before the insertion point. New `Ref`, `PageRef`, `NoteRef`, `Seq`, `StyleRef`, `Date`, and `Time` fields carry `w:dirty="true"`, so an application that evaluates fields recomputes them on open.
|
|
593
|
+
|
|
594
|
+
Write the cached result with `field.result.insertText(text, 'Replace')` after a sync, and read it with `field.load('result')`. The result range supports only `text` and that `insertText()` call. Its other members refuse with `NotImplemented` and `edit.field-result-unsupported`. With `TrackMineOnly`, the write works only on your own pending field and joins its insertion. If the write fails, `field.delete()` takes your own pending field back outright.
|
|
595
|
+
|
|
596
|
+
Field types that fetch, embed, link, run, or prompt, such as `DDE`, `IncludeText`, `IncludePicture`, `Link`, and `MacroButton`, fail with `InvalidArgument` and `edit.field-unsupported`. With `TrackMineOnly`, the field is one complex field inside one tracked insertion. Accept keeps it, and reject removes all of it. Tracked TOC creation refuses. For the refusal tables, see [Fields and pagination](https://www.docx-editor.dev/docs/2.x/editor-api/fields).
|
|
597
|
+
|
|
598
|
+
Insert one equation with `range.insertOoxml(ooxml, location)`. `ooxml` is a Flat OPC package (`pkg:package`) whose document part holds one paragraph with exactly one inline `m:oMath` and optional plain runs. The equation reads as U+FFFC. With `TrackMineOnly`, it is one tracked insertion, and reject removes it whole. Every other OOXML shape refuses and inserts nothing: other parts, relationships, images, fields, paragraph properties, display equations, and unknown elements fail with `NotSupported` and `edit.ooxml-unsupported`. Malformed XML, DTDs, and entities fail with `InvalidArgument` and `edit.invalid-argument`. For the accepted shape and every refusal, see [Insert an equation](https://www.docx-editor.dev/docs/2.x/editor-api/text-and-ranges#insert-an-equation).
|
|
599
|
+
|
|
425
600
|
Use `range.insertField('Before', 'TOC', '\\o "1-3" \\h')` to insert an inert TOC instruction. This call saves no calculated entries. TOC evaluation and code writes refuse.
|
|
426
601
|
|
|
427
602
|
Insert a page field with `range.insertField('After', 'Page')` or `'NumPages'`. Sync before using the returned field. `field.code = 'NUMPAGES'` changes its instruction; `field.updateResult()` computes and stores its result. These calls use separate syncs. Field updates can share a sync with other field updates. They cannot share a sync with layout-changing writes.
|
|
428
603
|
|
|
429
|
-
Headless field calculation requires an explicit `pagination.measurer` when creating the server runtime. Use measurements from the document's fonts. Browser runtimes use the editor's measured layout. Without pagination, `updateResult()` fails with `NotSupported`. Other field instructions remain inert. The authoring subset refuses unsupported field codes and
|
|
604
|
+
Headless field calculation requires an explicit `pagination.measurer` when creating the server runtime. Use measurements from the document's fonts. Browser runtimes use the editor's measured layout. Without pagination, `updateResult()` fails with `NotSupported`. Other field instructions remain inert. The authoring subset refuses unsupported field codes and page-field switches. A field inside a pending tracked insertion refuses `updateResult()` and code writes until a reviewer accepts it.
|
|
430
605
|
|
|
431
606
|
Character formatting also supports underline, strikethrough, exact Word-palette highlighting, subscript, and superscript. `font.underline = 'None'` removes an underline. Setting one script mode to `true` clears the other mode. The highlight setter keeps Office's pinned `string` type, although Microsoft documents runtime `null` for clearing. The runtime accepts this clearing value. The runtime rejects unsupported highlight colors.
|
|
432
607
|
|
|
433
|
-
The
|
|
608
|
+
The repository's tests run these workflows on both hosts and through save and reopen, including primary footer creation and a saved `NUMPAGES` result.
|
|
434
609
|
|
|
435
610
|
## Set document metadata
|
|
436
611
|
|
package/README.md
CHANGED
|
@@ -35,12 +35,16 @@ Start with [Runtime and setup](https://www.docx-editor.dev/docs/2.x/editor-api/r
|
|
|
35
35
|
| Task | Guide |
|
|
36
36
|
| --- | --- |
|
|
37
37
|
| Read, insert, replace, or remove text | [Text and ranges](https://www.docx-editor.dev/docs/2.x/editor-api/text-and-ranges) |
|
|
38
|
-
|
|
|
38
|
+
| Split a paragraph with `insertText()` and `\n`, also as a tracked change | [Split a paragraph](https://www.docx-editor.dev/docs/2.x/editor-api/text-and-ranges#split-a-paragraph) |
|
|
39
|
+
| Find matches or use bookmarks | [Search and navigation](https://www.docx-editor.dev/docs/2.x/editor-api/search-and-navigation) |
|
|
39
40
|
| Set fonts, paragraph properties, styles, or links | [Formatting and styles](https://www.docx-editor.dev/docs/2.x/editor-api/formatting) |
|
|
40
41
|
| Create and configure lists | [Lists and numbering](https://www.docx-editor.dev/docs/2.x/editor-api/lists) |
|
|
41
42
|
| Work with table values, rows, columns, and cells | [Tables and cells](https://www.docx-editor.dev/docs/2.x/editor-api/tables) |
|
|
42
43
|
| Insert and resize images | [Inline pictures](https://www.docx-editor.dev/docs/2.x/editor-api/pictures) |
|
|
43
|
-
|
|
|
44
|
+
| Insert fields, write their cached results, or calculate PAGE and NUMPAGES | [Fields and pagination](https://www.docx-editor.dev/docs/2.x/editor-api/fields) |
|
|
45
|
+
| Insert an equation from OOXML | [Insert an equation](https://www.docx-editor.dev/docs/2.x/editor-api/text-and-ranges#insert-an-equation) |
|
|
46
|
+
| Propose a split, a field, or an equation as a tracked change | [Tracked changes](https://www.docx-editor.dev/docs/2.x/editor-api/revisions#propose-several-structural-edits-in-one-run) |
|
|
47
|
+
| Propose a model's paragraph rewrite as the fewest tracked changes | [Propose an AI rewrite](https://www.docx-editor.dev/docs/2.x/recipes/propose-rewrite), with `prepareRewrite` from `@docx-editor.dev/editor-api/agent` |
|
|
44
48
|
| Set page geometry and edit headers, footers, or notes | [Page layout and stories](https://www.docx-editor.dev/docs/2.x/editor-api/page-layout-and-stories) |
|
|
45
49
|
| Fill template controls and edit their metadata | [Content controls](https://www.docx-editor.dev/docs/2.x/editor-api/content-controls) |
|
|
46
50
|
| Discuss content and manage threads | [Comments](https://www.docx-editor.dev/docs/2.x/editor-api/comments) |
|
|
@@ -100,7 +104,7 @@ await runtime.run(async (context) => {
|
|
|
100
104
|
|
|
101
105
|
Use `range.insertText(text, 'Before' | 'After')` for insertions, and `range.delete()` or `range.clear()` for deletions. `insertText()` returns the inserted range. Mode assignments and edits commit together at `sync()`; failed batches preserve the previous mode and document. Load `document.changeTrackingMode` before reading it. `Off` is the initial mode.
|
|
102
106
|
|
|
103
|
-
This is a supported Office.js subset. `TrackMineOnly` applies to this server host and persists across its `run()` calls. It does not change peers' tracking settings or save a document-wide tracking policy. `TrackAll` fails with `NotSupported`. Browser tracked writes require the Pro review module; the runtime setting does not change the editor UI mode. Tracked text edits support one paragraph, including table-cell text, and adjacent sibling paragraphs outside collaboration. Tracked `Paragraph.delete()` and `Range.delete()` over whole paragraphs record deleted text and deleted paragraph marks, also in collaboration. Font, paragraph-format, paragraph-style, and `readingOrder` changes record property revisions, and paragraph insertion records inserted text and paragraph marks. The runtime
|
|
107
|
+
This is a supported Office.js subset. `TrackMineOnly` applies to this server host and persists across its `run()` calls. It does not change peers' tracking settings or save a document-wide tracking policy. `TrackAll` fails with `NotSupported`. Browser tracked writes require the Pro review module; the runtime setting does not change the editor UI mode. Tracked text edits support one paragraph, including table-cell text, and adjacent sibling paragraphs outside collaboration. Tracked `Paragraph.delete()` and `Range.delete()` over whole paragraphs record deleted text and deleted paragraph marks, also in collaboration. Font, paragraph-format, paragraph-style, and `readingOrder` changes record property revisions, and paragraph insertion records inserted text and paragraph marks. Tracked edits can go inside or beside another author's pending text insertion or deletion, and each author's change stays a separate decision. The runtime refuses edits that touch your own pending change, another author's paragraph mark, formatting, move, or structural change, and text inside a row with a pending insertion or deletion. Tracked paragraph splits through `insertText()` with `\n`, fields through `insertField()` with results through `Field.result`, and one equation at a time through `insertOoxml()` produce native revisions. Other structural changes refuse while tracking. For the complete list, see [Revisions](https://docx-editor.dev/docs/2.x/editor-api/revisions). Comments and revision decisions remain available. Set `Off` explicitly when permanent edits are intended.
|
|
104
108
|
|
|
105
109
|
See the [server-agent review example](../../examples/server-agent-review/README.md) for Hocuspocus, stale-read handling, and the review lifecycle.
|
|
106
110
|
|
|
@@ -160,6 +164,30 @@ To upgrade from the former reviewer, bridge, MCP, or chat APIs, see [Migration](
|
|
|
160
164
|
| [`@docx-editor.dev/pro`](https://www.npmjs.com/package/@docx-editor.dev/pro) | Tracked changes, comments, and custom nodes. |
|
|
161
165
|
| [`@docx-editor.dev/editor-api`](https://www.npmjs.com/package/@docx-editor.dev/editor-api) | Supported Office.js subset for document editing on a server or in an open editor. |
|
|
162
166
|
|
|
167
|
+
## Which API for which job
|
|
168
|
+
|
|
169
|
+
| Job | Use |
|
|
170
|
+
| --- | --- |
|
|
171
|
+
| Build a review UI in the browser | The React or Vue adapter hooks, plus the review hooks and `DocxEditorReview` from `@docx-editor.dev/pro/react` or `@docx-editor.dev/pro/vue`. |
|
|
172
|
+
| Edit in a headless, server, or agent pipeline | The editing API in `@docx-editor.dev/editor-api`, which follows the Office.js object model. |
|
|
173
|
+
|
|
174
|
+
| Task | Browser host (React or Vue) | Headless, server, or agent |
|
|
175
|
+
| --- | --- | --- |
|
|
176
|
+
| [Comment on found text](https://www.docx-editor.dev/docs/2.x/recipes/comment-on-found-text) | `editor.findMatches`, `editor.selectMatch`, then `useReview().comment` | `body.search`, then `Range.insertComment` |
|
|
177
|
+
| Reply to a thread | `useReview().reply(item, text)` | `Comment.reply(text)` |
|
|
178
|
+
| [Record a tracked replacement](https://www.docx-editor.dev/docs/2.x/recipes/tracked-replacement) | Suggesting mode, then `editor.exec({ type: 'replaceMatch', match, text })` | `document.changeTrackingMode = 'TrackMineOnly'`, then `Range.insertText(text, 'Replace')` |
|
|
179
|
+
| [Propose an AI rewrite as tracked changes](https://www.docx-editor.dev/docs/2.x/recipes/propose-rewrite) | The same code through `DocxEditor.createBrowser` from `@docx-editor.dev/editor-api/browser` | `prepareRewrite` from `@docx-editor.dev/editor-api/agent` |
|
|
180
|
+
| [Accept or reject a change](https://www.docx-editor.dev/docs/2.x/recipes/accept-reject-without-scrolling) | `useReview().accept(item)` or `useReview().reject(item)` | `Revision.accept()` or `Revision.reject()` |
|
|
181
|
+
| [Open or reveal a change without scrolling](https://www.docx-editor.dev/docs/2.x/recipes/accept-reject-without-scrolling) | `useReview().setActive(key, { reveal: false })` | Not applicable: no viewport |
|
|
182
|
+
| [Highlight ranges](https://www.docx-editor.dev/docs/2.x/recipes/highlight-ranges) | `useHighlights(name, source, options)` | Not applicable |
|
|
183
|
+
| [Custom review rail cards](https://www.docx-editor.dev/docs/2.x/recipes/custom-review-cards) | `DocxEditorReview` with `preset` set to `false`, `useReview().items`, `useStackedReviewPositions`, and `useReviewRailMetrics` | Not applicable |
|
|
184
|
+
| Comment-on-selection button | `DocxEditorReview.AddComment` as a direct child of `DocxEditorReview`, or `useEditorCommand('review.addComment')` | Not applicable |
|
|
185
|
+
| Page setup and paragraph dialogs from a custom toolbar | `DocxEditor.PageSetupDialog` or `DocxEditor.ParagraphDialog` with `open` and a close handler (`onClose` in React, `@close` in Vue); enable the button from `usePageSetup().isEnabled` or `useParagraphFormat().isEnabled` | `Section.pageSetup`, and `Paragraph` properties such as `alignment` |
|
|
186
|
+
|
|
187
|
+
The review hooks need `reviewModule()` from `@docx-editor.dev/pro` in the editor's modules, and an editor `author` for comments and tracked changes. The editing API takes its author from the `author` option of `DocxEditor.createServer`, imported from `@docx-editor.dev/editor-api`, or of `DocxEditor.createBrowser`, imported from `@docx-editor.dev/editor-api/browser`.
|
|
188
|
+
|
|
189
|
+
This package ships the task recipes in [`docs/index.md`](./docs/index.md). They are also on the site: [Task recipes](https://www.docx-editor.dev/docs/2.x/recipes).
|
|
190
|
+
|
|
163
191
|
## License
|
|
164
192
|
|
|
165
193
|
This package uses the [EigenPal Pro License](https://github.com/eigenpal/docx-editor/blob/main/packages/editor-api/LICENSE.md). See [pricing](https://www.docx-editor.dev/pricing) for license and support options.
|
package/dist/agent.d.mts
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for AI agents that edit documents through the editing API.
|
|
3
|
+
*
|
|
4
|
+
* `prepareRewrite` reads a paragraph into text for a model, and `draft.apply()` proposes the
|
|
5
|
+
* model's new text as the fewest tracked changes. Fields, pictures, equations, note references,
|
|
6
|
+
* and locked content controls reach the model as numbered placeholders, so they change whole or
|
|
7
|
+
* not at all. Either every change lands and the paragraph reads as the model text, or the
|
|
8
|
+
* paragraph stays as it was and `apply()` throws a `RewriteError` with a stable `code`.
|
|
9
|
+
*
|
|
10
|
+
* You own the model call: the prompt, the instruction, retries, timeouts, and concurrency. The
|
|
11
|
+
* helpers own only the document side, which is deterministic.
|
|
12
|
+
*
|
|
13
|
+
* The helpers sit next to the object model, not on it, and are outside its Office.js
|
|
14
|
+
* compatibility scope. They use only the Office.js-shaped calls of
|
|
15
|
+
* `@docx-editor.dev/editor-api`, on the `context` and `paragraph` that you pass in.
|
|
16
|
+
*
|
|
17
|
+
* @example Rewrite the first paragraph on a server
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { DocxEditor } from '@docx-editor.dev/editor-api';
|
|
20
|
+
* import { prepareRewrite } from '@docx-editor.dev/editor-api/agent';
|
|
21
|
+
*
|
|
22
|
+
* const runtime = await DocxEditor.createServer(bytes, { author: 'Rewrite agent' });
|
|
23
|
+
* try {
|
|
24
|
+
* await runtime.run(async (context) => {
|
|
25
|
+
* const paragraph = context.document.body.paragraphs.getFirst();
|
|
26
|
+
* const draft = await prepareRewrite(context, paragraph);
|
|
27
|
+
* const prompt = `Make the paragraph shorter.\n\n${draft.legend}\n\n${draft.text}`;
|
|
28
|
+
* await draft.apply(await callModel(prompt));
|
|
29
|
+
* });
|
|
30
|
+
* const saved = await runtime.save();
|
|
31
|
+
* } finally {
|
|
32
|
+
* runtime.dispose();
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @packageDocumentation
|
|
37
|
+
* @public
|
|
38
|
+
*/
|
|
39
|
+
import { RequestContext, Paragraph } from '@docx-editor.dev/editor-api';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Why a rewrite was refused or failed.
|
|
43
|
+
*
|
|
44
|
+
* - The model text broke a rule, and nothing was written. `draft.check()` returns these too.
|
|
45
|
+
* Send `error.message` back to the model and ask again with the same draft:
|
|
46
|
+
* `invalid-output`, `placeholder-missing`, `placeholder-unknown`, `placeholder-moved`,
|
|
47
|
+
* `placeholder-repeated`, `placeholder-grouped`.
|
|
48
|
+
* - The request context is in use, and nothing was written: `busy` when another helper call
|
|
49
|
+
* runs on it, such as two `apply()` calls at once, and `context-used` when commands are
|
|
50
|
+
* queued on it that are not synced.
|
|
51
|
+
* - The paragraph cannot take a rewrite now, and nothing was written: `pending-changes`,
|
|
52
|
+
* `tracking-unavailable`, `draft-used`, `too-long`, `unsupported-text`, `read-failed`.
|
|
53
|
+
* - A write or the final check failed, and the helper rejected the changes it had written:
|
|
54
|
+
* `stale`, `locked`, `write-failed`, `verification-failed`. After `stale` or
|
|
55
|
+
* `verification-failed`, another edit moved the paragraph: prepare it again, and ask the model
|
|
56
|
+
* again with the new draft.
|
|
57
|
+
* - The rollback failed too, or could not find the paragraph after another edit joined or
|
|
58
|
+
* removed it, so the document can hold some of the proposal: `rollback-failed`. Do not retry
|
|
59
|
+
* automatically.
|
|
60
|
+
*
|
|
61
|
+
* @public
|
|
62
|
+
*/
|
|
63
|
+
type RewriteErrorCode = 'invalid-output' | 'placeholder-missing' | 'placeholder-unknown' | 'placeholder-moved' | 'placeholder-repeated' | 'placeholder-grouped' | 'context-used' | 'busy' | 'pending-changes' | 'tracking-unavailable' | 'draft-used' | 'too-long' | 'unsupported-text' | 'read-failed' | 'stale' | 'locked' | 'write-failed' | 'verification-failed' | 'rollback-failed';
|
|
64
|
+
/**
|
|
65
|
+
* A refused or failed rewrite. Every code except `rollback-failed` leaves the paragraph as it
|
|
66
|
+
* was before the rewrite.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* try {
|
|
71
|
+
* const draft = await prepareRewrite(context, paragraph);
|
|
72
|
+
* await draft.apply(await callModel(`${draft.legend}\n\n${draft.text}`));
|
|
73
|
+
* } catch (error) {
|
|
74
|
+
* if (error instanceof RewriteError && error.code === 'pending-changes') {
|
|
75
|
+
* // Decide the tracked changes in the paragraph first.
|
|
76
|
+
* } else throw error;
|
|
77
|
+
* }
|
|
78
|
+
* ```
|
|
79
|
+
*
|
|
80
|
+
* @public
|
|
81
|
+
*/
|
|
82
|
+
declare class RewriteError extends Error {
|
|
83
|
+
/** Always `'RewriteError'`. */
|
|
84
|
+
readonly name = "RewriteError";
|
|
85
|
+
/** What went wrong. See {@link RewriteErrorCode} for what to do next. */
|
|
86
|
+
readonly code: RewriteErrorCode;
|
|
87
|
+
/**
|
|
88
|
+
* Whether the model output broke a rule. The message then explains the rule in words that you
|
|
89
|
+
* can send back to the model.
|
|
90
|
+
*/
|
|
91
|
+
readonly isModelError: boolean;
|
|
92
|
+
/**
|
|
93
|
+
* A second error that happened while the helper cleaned up after this one, such as a failure
|
|
94
|
+
* to turn tracking off again. It never replaces this error.
|
|
95
|
+
*/
|
|
96
|
+
suppressed?: unknown;
|
|
97
|
+
constructor(code: RewriteErrorCode, message: string, options?: {
|
|
98
|
+
cause?: unknown;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* What a placeholder stands for.
|
|
104
|
+
*
|
|
105
|
+
* @public
|
|
106
|
+
*/
|
|
107
|
+
type RewritePlaceholderKind = 'field' | 'content-control' | 'picture' | 'equation' | 'note-reference' | 'line-break';
|
|
108
|
+
/**
|
|
109
|
+
* One placeholder in the draft text, and what it stands for.
|
|
110
|
+
*
|
|
111
|
+
* @public
|
|
112
|
+
*/
|
|
113
|
+
interface RewritePlaceholder {
|
|
114
|
+
/** The placeholder as the model sees it, such as `⟦1⟧`. */
|
|
115
|
+
readonly placeholder: string;
|
|
116
|
+
/** What the placeholder stands for. */
|
|
117
|
+
readonly kind: RewritePlaceholderKind;
|
|
118
|
+
/**
|
|
119
|
+
* The text the paragraph reads for it: a field result, a control's text, U+000B for a line
|
|
120
|
+
* break, or U+FFFC for an equation, a picture, or a note reference.
|
|
121
|
+
*/
|
|
122
|
+
readonly text: string;
|
|
123
|
+
/**
|
|
124
|
+
* A description for the model, such as `field REF _Ref1 \h, reads "Section 4.2"`,
|
|
125
|
+
* `equation`, or `locked content control "party", reads "Acme Corp"`.
|
|
126
|
+
*/
|
|
127
|
+
readonly description: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* How to read the paragraph and check the model text.
|
|
132
|
+
*
|
|
133
|
+
* @public
|
|
134
|
+
*/
|
|
135
|
+
interface PrepareRewriteOptions {
|
|
136
|
+
/**
|
|
137
|
+
* Refuse model text that leaves out a placeholder, with `placeholder-missing`. By default, a
|
|
138
|
+
* left-out placeholder deletes what it stands for as one tracked deletion. `draft.legend`
|
|
139
|
+
* states the rule that applies.
|
|
140
|
+
*/
|
|
141
|
+
readonly keepPlaceholders?: boolean;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* A paragraph read for a model: plain data, plus `check()` and `apply()` for the model text.
|
|
145
|
+
*
|
|
146
|
+
* Build the prompt from `text` and `legend` with your own instruction, and call your model.
|
|
147
|
+
* Then call `apply()` in the same `run()` as `prepareRewrite`.
|
|
148
|
+
*
|
|
149
|
+
* @public
|
|
150
|
+
*/
|
|
151
|
+
interface RewriteDraft {
|
|
152
|
+
/** The paragraph's `uniqueLocalId`. */
|
|
153
|
+
readonly paragraphId: string;
|
|
154
|
+
/** The paragraph text as it reads now. */
|
|
155
|
+
readonly original: string;
|
|
156
|
+
/**
|
|
157
|
+
* The paragraph text with each field, picture, equation, note reference, line break, and
|
|
158
|
+
* locked control as a placeholder, such as `Subject to ⟦1⟧, the fee applies`. A paragraph that
|
|
159
|
+
* already contains `⟦` or `⟧` gets another bracket pair, such as `⟪1⟫`; read the exact
|
|
160
|
+
* placeholders from `placeholders`.
|
|
161
|
+
*/
|
|
162
|
+
readonly text: string;
|
|
163
|
+
/** Each placeholder in `text`, in order, and what it stands for. */
|
|
164
|
+
readonly placeholders: readonly RewritePlaceholder[];
|
|
165
|
+
/**
|
|
166
|
+
* The placeholder contract as plain text for a prompt: what a placeholder is, the rules (copy
|
|
167
|
+
* each kept placeholder exactly, leave one out to delete it, keep the order, do not repeat
|
|
168
|
+
* one), and one line per placeholder, such as `⟦1⟧ = equation`. An empty string when `text`
|
|
169
|
+
* has no placeholder.
|
|
170
|
+
*
|
|
171
|
+
* It holds no instruction and no paragraph text. The descriptions come from the file, so treat
|
|
172
|
+
* the legend as document data in your prompt, as you treat `text`.
|
|
173
|
+
*/
|
|
174
|
+
readonly legend: string;
|
|
175
|
+
/**
|
|
176
|
+
* Check model text without writing. Returns the {@link RewriteError} that `apply()` would
|
|
177
|
+
* throw before it writes, or `null` when `apply()` may go ahead. Most often the error is a
|
|
178
|
+
* model error (`error.isModelError`), whose message you can send back to the model. It can
|
|
179
|
+
* also be `draft-used`; `too-long`, when the text makes too many edits to compare; or
|
|
180
|
+
* `verification-failed`, when the text differs only in spacing that the helper cannot write.
|
|
181
|
+
*
|
|
182
|
+
* A `null` result does not promise that the write succeeds: the document can change, and
|
|
183
|
+
* `apply()` also checks the request context.
|
|
184
|
+
*/
|
|
185
|
+
check(modelText: string): RewriteError | null;
|
|
186
|
+
/**
|
|
187
|
+
* Propose the model text as the fewest tracked changes. Either every change lands and the
|
|
188
|
+
* paragraph reads as the model text, or the paragraph stays as it was and this throws a
|
|
189
|
+
* {@link RewriteError}. After a model error, you can call it again with new model text. Call
|
|
190
|
+
* it once at a time on a request context: a helper call that overlaps another throws `busy`.
|
|
191
|
+
*/
|
|
192
|
+
apply(modelText: string): Promise<RewriteResult>;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* What a proposed rewrite changed. Plain data.
|
|
196
|
+
*
|
|
197
|
+
* @public
|
|
198
|
+
*/
|
|
199
|
+
interface RewriteResult {
|
|
200
|
+
/** The paragraph's `uniqueLocalId`. */
|
|
201
|
+
readonly paragraphId: string;
|
|
202
|
+
/** The text before the rewrite: what rejecting every proposed change gives. */
|
|
203
|
+
readonly original: string;
|
|
204
|
+
/**
|
|
205
|
+
* The text after the rewrite: what accepting every proposed change gives. As in
|
|
206
|
+
* `getReviewedText`, an equation, a picture, or a note reference reads as U+FFFC, and a line
|
|
207
|
+
* break as U+000B.
|
|
208
|
+
*/
|
|
209
|
+
readonly proposed: string;
|
|
210
|
+
/**
|
|
211
|
+
* How many word edits the helper wrote: each run of changed words counts once. A replacement
|
|
212
|
+
* counts once, though `revisions.items` lists it as a `Delete` and an `Insert`. `0` when the
|
|
213
|
+
* model changed nothing.
|
|
214
|
+
*/
|
|
215
|
+
readonly changes: number;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Read a paragraph for a model. The draft is plain data: build a prompt from `draft.text` and
|
|
220
|
+
* `draft.legend` with your own instruction, call your model, and pass its text to
|
|
221
|
+
* `draft.apply()` in the same `run()`. `draft.check()` tests model text without writing.
|
|
222
|
+
*
|
|
223
|
+
* The helper never calls a model and never retries. It reads the paragraph, checks model text,
|
|
224
|
+
* and writes the fewest tracked changes, all or nothing.
|
|
225
|
+
*
|
|
226
|
+
* Throws a {@link RewriteError}: `pending-changes` when the paragraph has tracked changes,
|
|
227
|
+
* `tracking-unavailable` when the runtime has no author, `too-long` or `unsupported-text` when
|
|
228
|
+
* the paragraph cannot be compared, `read-failed` when the document refuses a read, `busy` when
|
|
229
|
+
* another helper call runs on the context, and `context-used` when edits are queued on it.
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```ts
|
|
233
|
+
* const draft = await prepareRewrite(context, paragraph);
|
|
234
|
+
* const prompt = `Make this paragraph formal.\n\n${draft.legend}\n\n${draft.text}`;
|
|
235
|
+
* const result = await draft.apply(await callModel(prompt));
|
|
236
|
+
* ```
|
|
237
|
+
*
|
|
238
|
+
* @public
|
|
239
|
+
*/
|
|
240
|
+
declare function prepareRewrite(context: RequestContext, paragraph: Paragraph, options?: PrepareRewriteOptions): Promise<RewriteDraft>;
|
|
241
|
+
|
|
242
|
+
export { RewriteError, prepareRewrite };
|
|
243
|
+
export type { PrepareRewriteOptions, RewriteDraft, RewriteErrorCode, RewritePlaceholder, RewritePlaceholderKind, RewriteResult };
|