@stll/folio-agents 0.14.2 → 0.15.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/README.md CHANGED
@@ -18,32 +18,54 @@ bun add @stll/folio-agents
18
18
 
19
19
  ## Tools
20
20
 
21
- | Tool | What it does |
22
- | ---------------------- | ---------------------------------------------------------------------- |
23
- | `read_document` | Read the document body as `{ blockId, kind, text }` blocks |
24
- | `get_document_outline` | Read heading hierarchy and stable section handles |
25
- | `read_section` | Read a bounded logical section, with block cursor pagination |
26
- | `list_stories` | List main, header, footer, footnote, and endnote story handles |
27
- | `read_story` | Read one story by its typed handle |
28
- | `find_text` | Search by document, section, real page, or story scope |
29
- | `read_comments` | Read comment threads (author, text, resolved, anchored block, replies) |
30
- | `read_changes` | Read pending tracked changes (insertions/deletions) awaiting review |
31
- | `add_comment` | Attach a comment to a block, optionally quoting specific text |
32
- | `suggest_changes` | Propose block or stable-range edits as tracked changes |
33
- | `reply_comment` | Reply to a comment thread |
34
- | `resolve_comment` | Resolve or reopen a comment thread |
35
- | `read_page` | Read a page's plain text (live editor only) |
36
- | `read_selection` | Read the current text selection (live editor only) |
37
- | `scroll_to_block` | Scroll the live editor to a block (live editor only) |
38
- | `show_in_document` | Reveal a stable block or exact text range (live editor only) |
21
+ | Tool | What it does |
22
+ | ---------------------- | ------------------------------------------------------------------------- |
23
+ | `read_document` | Read the document body as `{ blockId, kind, text, displayLabel? }` blocks |
24
+ | `get_document_outline` | Read heading hierarchy and stable section handles |
25
+ | `read_section` | Read a bounded logical section, with block cursor pagination |
26
+ | `list_stories` | List main, header, footer, footnote, and endnote story handles |
27
+ | `read_story` | Read one story by its typed handle |
28
+ | `find_text` | Search by document, section, real page, or story scope |
29
+ | `read_comments` | Read comment threads (author, text, resolved, anchored block, replies) |
30
+ | `read_changes` | Read pending tracked changes (insertions/deletions) awaiting review |
31
+ | `add_comment` | Attach a comment to a block, optionally quoting specific text |
32
+ | `suggest_changes` | Propose block or stable-range edits as tracked changes |
33
+ | `reply_comment` | Reply to a comment thread |
34
+ | `resolve_comment` | Resolve or reopen a comment thread |
35
+ | `read_page` | Read a page's plain text (live editor only) |
36
+ | `read_selection` | Read the current text selection (live editor only) |
37
+ | `scroll_to_block` | Scroll the live editor to a block (live editor only) |
38
+ | `show_in_document` | Reveal a stable block or exact text range (live editor only) |
39
+
40
+ A `read_document` / `read_section` block also carries, when present, the
41
+ number or bullet the document shows beside it (`displayLabel`: `2.1.`, `a)`,
42
+ `•`; an unnumbered heading's style id), its `headingLevel` (one-based) and
43
+ its `listLevel` (zero-based). A numbered heading is `kind: "heading"` with its
44
+ number in `displayLabel`; absent fields are omitted.
39
45
 
40
46
  Block ids and comment ids always come from a prior tool call
41
47
  (`read_document`, `find_text`, `read_comments`) within the same conversation —
42
48
  never guess them. `suggest_changes` reports a plain-language reason when an
43
- operation is skipped (e.g. the block changed since it was last read), so the
44
- model can re-read and retry. Successful mutation results include `receipts`
49
+ operation is skipped (e.g. the block changed since it was last read, an
50
+ earlier operation of the same call already deletes, rewrites, splits or merges
51
+ its target, an offset falls inside a character, its `styleId` names no
52
+ paragraph style the document defines, or its `numbering.numId` names an
53
+ instance the document does not define), so the model can re-read and retry.
54
+ An operation whose result would leave a document that cannot be saved is
55
+ skipped with `invalidResult` and nothing from it is applied. Successful
56
+ mutation results include `receipts`
45
57
  that identify affected blocks, ranges, insertions, and created comments.
46
58
 
59
+ An operation id names one operation for the whole document session: the
60
+ reviewer a bridge wraps, or the bridge itself for a live editor (build one per
61
+ loaded document). Resending a `suggest_changes` operation that already applied
62
+ or queued, with the same id and content, is a retry: nothing runs again, and
63
+ the result lists it under `replayed` with its original receipt. Reusing an id
64
+ for a different operation fails the call. A skipped operation is not recorded,
65
+ so resending it tries again. Ids the executor generates are unique, so a caller
66
+ that omits them never collides; `add_comment` takes no id and is not
67
+ deduplicated.
68
+
47
69
  For document questions, start with `get_document_outline`, then call
48
70
  `read_section` or scoped `find_text`. This keeps unrelated contract text out
49
71
  of model context. Section handles use Folio block identities, heading depth,
package/dist/bridge.d.ts CHANGED
@@ -71,5 +71,7 @@ type DecodedCommentHandlers = {
71
71
  };
72
72
  declare const registerDecodedCommentHandlers: (bridge: FolioAgentBridge, handlers: DecodedCommentHandlers) => FolioAgentBridge;
73
73
  declare const getDecodedCommentHandlers: (bridge: FolioAgentBridge) => DecodedCommentHandlers | undefined;
74
+ declare const registerOperationSession: (bridge: FolioAgentBridge, session: object) => FolioAgentBridge;
75
+ declare const getOperationSession: (bridge: FolioAgentBridge) => object;
74
76
  //#endregion
75
- export { FolioAgentBridge, getDecodedCommentHandlers, registerDecodedCommentHandlers };
77
+ export { FolioAgentBridge, getDecodedCommentHandlers, getOperationSession, registerDecodedCommentHandlers, registerOperationSession };
package/dist/bridge.js CHANGED
@@ -5,5 +5,18 @@ const registerDecodedCommentHandlers = (bridge, handlers) => {
5
5
  return bridge;
6
6
  };
7
7
  const getDecodedCommentHandlers = (bridge) => decodedCommentHandlers.get(bridge);
8
+ /**
9
+ * The document session an operation id is unique within. The reviewer bridge
10
+ * registers its reviewer, which holds one document for its lifetime, so a
11
+ * host that builds a new bridge per call keeps one session. Any other bridge
12
+ * is its own session: a live editor can load another document under the same
13
+ * ref, so a host builds one bridge per loaded document.
14
+ */
15
+ const operationSessions = /* @__PURE__ */ new WeakMap();
16
+ const registerOperationSession = (bridge, session) => {
17
+ operationSessions.set(bridge, session);
18
+ return bridge;
19
+ };
20
+ const getOperationSession = (bridge) => operationSessions.get(bridge) ?? bridge;
8
21
  //#endregion
9
- export { getDecodedCommentHandlers, registerDecodedCommentHandlers };
22
+ export { getDecodedCommentHandlers, getOperationSession, registerDecodedCommentHandlers, registerOperationSession };
@@ -1,4 +1,4 @@
1
- import { registerDecodedCommentHandlers } from "../bridge.js";
1
+ import { registerDecodedCommentHandlers, registerOperationSession } from "../bridge.js";
2
2
  import { decodeCommentId } from "../codecs.js";
3
3
  import { toAgentChange } from "./shared.js";
4
4
  //#region src/bridges/reviewer.ts
@@ -29,7 +29,7 @@ const createReviewerBridge = (reviewer, options = {}) => {
29
29
  const { revisionStamp } = options;
30
30
  const applyOptions = revisionStamp === void 0 ? {} : { revisionStamp };
31
31
  const replyDate = revisionStamp === void 0 ? {} : { date: revisionStamp.date };
32
- return registerDecodedCommentHandlers({
32
+ const bridge = {
33
33
  snapshot: () => reviewer.snapshot(),
34
34
  documentOperationMode: mode,
35
35
  applyDocumentOperations: (batch) => reviewer.applyDocumentOperations(batch.mode === void 0 ? {
@@ -52,7 +52,9 @@ const createReviewerBridge = (reviewer, options = {}) => {
52
52
  const decoded = decodeCommentId(commentId);
53
53
  return decoded !== null && reviewer.resolveComment(decoded.raw, { resolved });
54
54
  }
55
- }, {
55
+ };
56
+ registerOperationSession(bridge, reviewer);
57
+ return registerDecodedCommentHandlers(bridge, {
56
58
  replyToComment: ({ numeric }, text) => reviewer.replyTo(numeric, {
57
59
  text,
58
60
  ...replyDate
package/dist/execute.js CHANGED
@@ -1,8 +1,9 @@
1
- import { getDecodedCommentHandlers } from "./bridge.js";
1
+ import { getDecodedCommentHandlers, getOperationSession } from "./bridge.js";
2
2
  import { decodeCommentId, decodeMainStoryTextRangeHandle, decodeSectionHandle, decodeStoryHandle } from "./codecs.js";
3
3
  import { explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput, prepareFolioAgentDocumentOperationBatch } from "./parse.js";
4
4
  import { FOLIO_AGENT_TOOL_NAMES } from "./types.js";
5
5
  import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, createFolioAITextRangeHandle, getFolioDocumentOperationIssues, getFolioDocumentOutline, hashFolioAIBlockText, isFolioAIContentBlock, normalizeFolioAIBlockText, readFolioDocumentSection } from "@stll/folio-core/server";
6
+ import { panic } from "better-result";
6
7
  //#region src/execute.ts
7
8
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8
9
  const isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
@@ -24,6 +25,24 @@ const VALID_TOOL_NAMES = Object.values(FOLIO_AGENT_TOOL_NAMES);
24
25
  * the anchors map around — it is defined to produce the exact same value.
25
26
  */
26
27
  const blockTextHashOf = (text) => hashFolioAIBlockText(normalizeFolioAIBlockText(text));
28
+ /**
29
+ * A snapshot block as a `read_document` / `read_section` row: the number or
30
+ * label a reader sees beside it and its heading and list levels ride along,
31
+ * so the model is given the numbers the document shows. Absent fields stay
32
+ * absent to keep the rows compact.
33
+ */
34
+ const toAgentBlock = (block) => {
35
+ const row = {
36
+ blockId: block.id,
37
+ kind: block.kind,
38
+ text: block.text,
39
+ blockTextHash: blockTextHashOf(block.text)
40
+ };
41
+ if (block.displayLabel !== void 0) row.displayLabel = block.displayLabel;
42
+ if (block.headingLevel !== void 0) row.headingLevel = block.headingLevel;
43
+ if (block.listLevel !== void 0) row.listLevel = block.listLevel;
44
+ return row;
45
+ };
27
46
  /** `find_text` requires a short `query` and caps how much of a large match set it returns in one call. */
28
47
  const MAX_QUERY_LENGTH = 1e3;
29
48
  const MAX_FIND_MATCHES = 200;
@@ -56,12 +75,7 @@ const dispatch = (name, args, bridge, options) => {
56
75
  };
57
76
  const readDocument = (bridge) => {
58
77
  const blocks = bridge.snapshot().blocks.filter(isFolioAIContentBlock);
59
- return ok(blocks.map((block) => ({
60
- blockId: block.id,
61
- kind: block.kind,
62
- text: block.text,
63
- blockTextHash: blockTextHashOf(block.text)
64
- })));
78
+ return ok(blocks.map(toAgentBlock));
65
79
  };
66
80
  const getDocumentOutline = (args, bridge) => {
67
81
  const maxDepth = isPlainObject(args) ? args["maxDepth"] : void 0;
@@ -105,12 +119,7 @@ const readSection = (args, bridge) => {
105
119
  return ok({
106
120
  handle,
107
121
  heading: resolved.section.heading,
108
- blocks: selected.map(({ id, kind, text }) => ({
109
- blockId: id,
110
- kind,
111
- text,
112
- blockTextHash: blockTextHashOf(text)
113
- })),
122
+ blocks: selected.map(toAgentBlock),
114
123
  totalBlocks: resolved.section.blocks.length,
115
124
  truncated: hasMore,
116
125
  ...hasMore && lastBlockId !== void 0 && { nextAfterBlockId: lastBlockId }
@@ -125,6 +134,8 @@ const readStory = (args, bridge) => {
125
134
  };
126
135
  const CONTEXT_RADIUS = 40;
127
136
  const WORD_CHARACTER_AT_END = /[\p{L}\p{M}\p{N}_]$/u;
137
+ /** Whether `[start, end)` of a block's text starts or ends inside a note reference's marker. */
138
+ const cutsIntoNoteReference = (block, start, end) => (block.structuralBoundaries ?? []).some((boundary) => boundary.type === "noteReference" && [start, end].some((offset) => offset > boundary.offset && offset < boundary.offset + boundary.length));
128
139
  const WORD_CHARACTER_AT_START = /^[\p{L}\p{M}\p{N}_]/u;
129
140
  /**
130
141
  * Window (UTF-16 code units) sliced on each side of a match for the
@@ -148,6 +159,7 @@ const findTextMatches = (blocks, query, matchCase, wholeWord, getTargetPage, pag
148
159
  const at = match.index;
149
160
  const matchedText = match[0];
150
161
  if (wholeWord && (WORD_CHARACTER_AT_END.test(block.text.slice(Math.max(0, at - WORD_BOUNDARY_WINDOW), at)) || WORD_CHARACTER_AT_START.test(block.text.slice(at + matchedText.length, at + matchedText.length + WORD_BOUNDARY_WINDOW)))) continue;
162
+ if (cutsIntoNoteReference(block, at, at + matchedText.length)) continue;
151
163
  const range = createFolioAITextRangeHandle({
152
164
  blockId: block.id,
153
165
  text: block.text,
@@ -276,7 +288,7 @@ const explainSkipReason = (reason) => {
276
288
  if (reason === "changedBlock") return "the block changed since your snapshot; re-read the document and retry with fresh ids.";
277
289
  if (reason === "ambiguousFind") return "`find` matches more than once in this block; narrow it so it matches exactly once, or use a replaceBlock operation instead.";
278
290
  if (reason === "missingFind") return "`find` was not found in this block; re-read the block's current text and retry.";
279
- if (reason === "unsupportedBlock") return "this block kind does not support this operation.";
291
+ if (reason === "unsupportedBlock") return "this block does not support that operation; use read_document to inspect its kind and embedded content, then choose an operation for its text or containing structure. If none fits, tell the user this edit cannot be applied.";
280
292
  if (reason === "unsupportedMode") return "this operation does not support the requested mutation mode; inspect document operation capabilities and retry with a supported mode.";
281
293
  if (reason === "atomicBatchRejected") return "another operation in this atomic batch could not be applied; no operations were committed.";
282
294
  if (reason === "preconditionFailed") return "the target block changed after the operation was prepared; re-read the document and retry with a fresh operation.";
@@ -285,9 +297,18 @@ const explainSkipReason = (reason) => {
285
297
  if (reason === "pendingParagraphPropertyChange") return "this paragraph already has an unresolved tracked formatting change; accept or reject that change before retrying.";
286
298
  if (reason === "noopOperation") return "this operation would not change the document (the text already matches what you asked for).";
287
299
  if (reason === "documentVersionMismatch") return "the document changed after these edits were proposed; re-read it and regenerate the edits against the current version.";
300
+ if (reason === "protectedReference") return "the edit would change or remove a footnote/endnote reference (a `[^1]` / `[^e1]` marker), or write a marker as text; a reference is not text. Keep every marker your `find` covers in the replacement, in order, or match only the words beside it.";
288
301
  if (reason === "documentNotEditable") return "the document is not open for editing right now; nothing was applied or queued. Ask the user to open it for editing, then retry.";
302
+ if (reason === "payloadDoesNotFit") return "the operation supplies more values than its target has cells for; nothing was applied. Supply fewer cellTexts, or anchor the row or column where no merged cell takes a slot.";
303
+ if (reason === "splitsCharacter") return "an offset falls inside a single character (between the two halves of an emoji or other surrogate pair, or, for a text change or split, between a letter and its combining marks or inside an emoji sequence); nothing was applied. Move the offset to the boundary before or after that character and retry.";
304
+ if (reason === "overlappingOperation") return "an earlier operation in this batch already deletes, rewrites, splits or merges this block, or edits an overlapping stretch of its text; nothing of this operation was applied. Re-read the document after this batch and send it again on its own.";
305
+ if (reason === "missingStyle") return "`styleId` names no paragraph style this document defines (it is undefined, or a table or character style); nothing was applied. Use a paragraph style the document defines (the ones it offers are named after this reason), or `null` to clear the style.";
306
+ if (reason === "pendingDeletion") return "this block is pending deletion (a tracked change deletes it; it reads as a blank block); nothing was applied, since text written there would join the next paragraph once the deletion is accepted. Reject that deletion first, or insert a new block next to it (insertAfterBlock / insertBeforeBlock).";
307
+ if (reason === "missingNumbering") return "`numbering.numId` names a numbering instance this document does not define; nothing was applied. Re-read the document and use a `numId` it defines (the one a neighbouring list item carries), or omit `numbering`.";
308
+ if (reason === "invalidResult") return "applying this operation would have left a document that cannot be saved, so nothing from it was applied. Do not retry it as written; re-read the document and express the change differently.";
289
309
  return reason;
290
310
  };
311
+ const explainSkippedOperation = ({ reason, message }) => message === void 0 ? explainSkipReason(reason) : `${explainSkipReason(reason)} (${message})`;
291
312
  /**
292
313
  * Turn one apply-time `FolioAIEditNormalization` (an automatic adjustment the
293
314
  * applier made to an operation's input, e.g. splitting a multi-line
@@ -300,6 +321,10 @@ const explainApplyNormalization = (normalization) => {
300
321
  path: `operations[id=${normalization.id}].text`,
301
322
  message: `\`text\` contained line breaks; split into ${normalization.paragraphCount} consecutive paragraphs (one per non-blank line) instead of one paragraph with embedded newlines.`
302
323
  };
324
+ if (normalization.code === "uniformReplacementFormatting") return {
325
+ path: `operations[id=${normalization.id}]`,
326
+ message: "the replaced text carried more than one formatting, link or comment; the new text takes the formatting of the first character it replaces and every link and comment over the replaced text. Check the result if part of it should be formatted differently."
327
+ };
303
328
  return {
304
329
  path: `operations[id=${normalization.id}].moveId`,
305
330
  message: `\`moveId\` "${normalization.moveId}" did not name exactly one deletion and one insertion in this batch, so the operation applied as an ordinary insertion or deletion rather than half of a move.`
@@ -309,9 +334,10 @@ const summarizeApplyResult = (result, normalizations) => ({
309
334
  version: result.version,
310
335
  applied: result.applied.map((entry) => ({ id: entry.id })),
311
336
  queued: (result.queued ?? []).map((entry) => ({ id: entry.id })),
337
+ replayed: [],
312
338
  skipped: result.skipped.map((entry) => ({
313
339
  id: entry.id,
314
- reason: explainSkipReason(entry.reason)
340
+ reason: explainSkippedOperation(entry)
315
341
  })),
316
342
  issues: result.issues ?? [],
317
343
  receipts: result.receipts ?? [],
@@ -357,6 +383,89 @@ const addComment = (args, bridge) => {
357
383
  if (!parsed.ok) return fail(parsed.error);
358
384
  return ok(applyOperations(bridge, { operations: [parsed.operation] }));
359
385
  };
386
+ const operationLedgers = /* @__PURE__ */ new WeakMap();
387
+ const ledgerOf = (bridge) => {
388
+ const session = getOperationSession(bridge);
389
+ const existing = operationLedgers.get(session);
390
+ if (existing !== void 0) return existing;
391
+ const created = /* @__PURE__ */ new Map();
392
+ operationLedgers.set(session, created);
393
+ return created;
394
+ };
395
+ const canonicalJson = (value) => {
396
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
397
+ if (isPlainObject(value)) return `{${Object.keys(value).toSorted().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
398
+ return JSON.stringify(value) ?? "null";
399
+ };
400
+ /**
401
+ * Split a call into operations to apply and operations the session already
402
+ * applied or queued under the same id. An id resent with a different
403
+ * operation is the caller's mistake, not a retry, and refuses the call.
404
+ */
405
+ const partitionReplays = (operations, ledger) => {
406
+ const fresh = [];
407
+ const replays = [];
408
+ for (const [index, operation] of operations.entries()) {
409
+ const recorded = ledger.get(operation.id);
410
+ if (recorded === void 0) {
411
+ fresh.push(operation);
412
+ continue;
413
+ }
414
+ if (recorded.fingerprint !== canonicalJson(operation)) return `operations[${String(index)}].id "${operation.id}" already names a different operation this document applied. Give a new operation a new id, or omit ids to have them generated.`;
415
+ replays.push({
416
+ index,
417
+ id: operation.id,
418
+ receipt: recorded.receipt
419
+ });
420
+ }
421
+ return {
422
+ fresh,
423
+ replays
424
+ };
425
+ };
426
+ /** Remember what landed. A skipped operation is not recorded, so resending it tries again. */
427
+ const recordSettled = ({ ledger, operations, summary }) => {
428
+ const settled = new Set([...summary.applied, ...summary.queued].map(({ id }) => id));
429
+ for (const operation of operations) {
430
+ if (!settled.has(operation.id)) continue;
431
+ ledger.set(operation.id, {
432
+ fingerprint: canonicalJson(operation),
433
+ receipt: summary.receipts.find(({ operationId }) => operationId === operation.id)
434
+ });
435
+ }
436
+ };
437
+ /**
438
+ * The summary of the operations that ran, with the replayed ones added back:
439
+ * listed under `replayed`, their original receipts restored, and every index
440
+ * restated against the call as sent rather than the subset that ran.
441
+ */
442
+ const withReplays = ({ summary, operations, replays }) => {
443
+ if (replays.length === 0) return summary;
444
+ const inputIndex = new Map(operations.map(({ id }, index) => [id, index]));
445
+ const indexOf = (id) => inputIndex.get(id) ?? panic("A result names an operation the call did not send", { id });
446
+ const receipts = [];
447
+ for (const receipt of summary.receipts) receipts.push({
448
+ ...receipt,
449
+ operationIndex: indexOf(receipt.operationId)
450
+ });
451
+ for (const { index, receipt } of replays) if (receipt !== void 0) receipts.push({
452
+ ...receipt,
453
+ operationIndex: index
454
+ });
455
+ return {
456
+ ...summary,
457
+ replayed: replays.map(({ id }) => ({ id })),
458
+ receipts: receipts.toSorted((left, right) => left.operationIndex - right.operationIndex),
459
+ issues: summary.issues.map((issue) => {
460
+ const index = indexOf(issue.operationId);
461
+ return {
462
+ ...issue,
463
+ operationIndex: index,
464
+ path: `$.operations[${index}]`
465
+ };
466
+ })
467
+ };
468
+ };
360
469
  /**
361
470
  * A version-pinned batch is compared against the bridge's document version
362
471
  * BEFORE any operation is applied or queued: an approval that runs after
@@ -367,14 +476,36 @@ const addComment = (args, bridge) => {
367
476
  const suggestChanges = (args, bridge, options) => {
368
477
  const parsed = parseSuggestChangesInput(args, options.suggestChanges);
369
478
  if (!parsed.ok) return fail(parsed.error);
370
- if (parsed.precondition !== void 0) {
371
- if (!bridge.getDocumentVersion) return fail("This editor surface cannot verify `documentVersion`; it has no document version to compare against.");
372
- if (bridge.getDocumentVersion() !== parsed.precondition.documentVersion) return ok(rejectBatch(parsed.operations, "documentVersionMismatch", parsed.normalizations));
373
- }
374
- return ok(applyOperations(bridge, {
479
+ if (parsed.precondition !== void 0 && !bridge.getDocumentVersion) return fail("This editor surface cannot verify `documentVersion`; it has no document version to compare against.");
480
+ const ledger = ledgerOf(bridge);
481
+ const partitioned = partitionReplays(parsed.operations, ledger);
482
+ if (typeof partitioned === "string") return fail(partitioned);
483
+ const { fresh, replays } = partitioned;
484
+ const applyFresh = () => {
485
+ if (fresh.length === 0) return summarizeApplyResult({
486
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
487
+ applied: [],
488
+ skipped: [],
489
+ issues: [],
490
+ receipts: []
491
+ }, parsed.normalizations);
492
+ if (parsed.precondition !== void 0 && bridge.getDocumentVersion?.() !== parsed.precondition.documentVersion) return rejectBatch(fresh, "documentVersionMismatch", parsed.normalizations);
493
+ return applyOperations(bridge, {
494
+ operations: fresh,
495
+ ...parsed.precondition !== void 0 && { precondition: parsed.precondition },
496
+ normalizations: parsed.normalizations
497
+ });
498
+ };
499
+ const summary = applyFresh();
500
+ recordSettled({
501
+ ledger,
502
+ operations: fresh,
503
+ summary
504
+ });
505
+ return ok(withReplays({
506
+ summary,
375
507
  operations: parsed.operations,
376
- ...parsed.precondition !== void 0 && { precondition: parsed.precondition },
377
- normalizations: parsed.normalizations
508
+ replays
378
509
  }));
379
510
  };
380
511
  const replyComment = (args, bridge) => {
@@ -40,7 +40,7 @@ declare const FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA: {
40
40
  }, {
41
41
  readonly type: "null";
42
42
  }];
43
- readonly description: "Paragraph style id; null clears the direct style.";
43
+ readonly description: string;
44
44
  };
45
45
  declare const FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA: {
46
46
  readonly oneOf: readonly [{
@@ -52,6 +52,8 @@ declare const FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA: {
52
52
  }];
53
53
  readonly description: "`w:numPr/w:ilvl`, zero-based; a number retains the paragraph or anchor's numbering instance (`numId`), while null removes paragraph numbering unless a concrete numbering instance is supplied, in which case it omits the direct level.";
54
54
  };
55
+ /** Direct `w:outlineLvl`, or null to restore style inheritance. */
56
+ declare const FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA: FolioJsonSchema;
55
57
  /** Complete direct `w:ind` attributes, or null to restore style inheritance. */
56
58
  declare const FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA: {
57
59
  readonly oneOf: readonly [{
@@ -105,10 +107,29 @@ declare const FOLIO_CLEARABLE_NUMBERING_JSON_SCHEMA: {
105
107
  };
106
108
  readonly required: readonly ["numId", "level"];
107
109
  readonly additionalProperties: false;
110
+ }, {
111
+ readonly type: "object";
112
+ readonly properties: {
113
+ readonly start: {
114
+ readonly type: "string";
115
+ readonly enum: readonly ["new"];
116
+ };
117
+ readonly kind: {
118
+ readonly type: "string";
119
+ readonly enum: readonly ["numbered", "bullet"];
120
+ };
121
+ readonly level: {
122
+ readonly type: "integer";
123
+ readonly minimum: 0;
124
+ readonly maximum: 8;
125
+ };
126
+ };
127
+ readonly required: readonly ["start", "kind"];
128
+ readonly additionalProperties: false;
108
129
  }, {
109
130
  readonly type: "null";
110
131
  }];
111
- readonly description: "Concrete numbering instance and level; null removes paragraph numbering.";
132
+ readonly description: string;
112
133
  };
113
134
  declare const FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA: {
114
135
  readonly type: "object";
@@ -177,8 +198,9 @@ declare const FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA: {
177
198
  }, {
178
199
  readonly type: "null";
179
200
  }];
180
- readonly description: "Paragraph style id; null clears the direct style.";
201
+ readonly description: string;
181
202
  };
203
+ readonly outlineLevel: FolioJsonSchema;
182
204
  readonly listLevel: {
183
205
  readonly oneOf: readonly [{
184
206
  readonly type: "integer";
@@ -206,10 +228,29 @@ declare const FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA: {
206
228
  };
207
229
  readonly required: readonly ["numId", "level"];
208
230
  readonly additionalProperties: false;
231
+ }, {
232
+ readonly type: "object";
233
+ readonly properties: {
234
+ readonly start: {
235
+ readonly type: "string";
236
+ readonly enum: readonly ["new"];
237
+ };
238
+ readonly kind: {
239
+ readonly type: "string";
240
+ readonly enum: readonly ["numbered", "bullet"];
241
+ };
242
+ readonly level: {
243
+ readonly type: "integer";
244
+ readonly minimum: 0;
245
+ readonly maximum: 8;
246
+ };
247
+ };
248
+ readonly required: readonly ["start", "kind"];
249
+ readonly additionalProperties: false;
209
250
  }, {
210
251
  readonly type: "null";
211
252
  }];
212
- readonly description: "Concrete numbering instance and level; null removes paragraph numbering.";
253
+ readonly description: string;
213
254
  };
214
255
  readonly indentation: {
215
256
  readonly oneOf: readonly [{
@@ -365,4 +406,4 @@ type FolioDocumentOperationBatchSchema = StandardSchemaV1<unknown, FolioDocument
365
406
  */
366
407
  declare const folioDocumentOperationBatchSchema: FolioDocumentOperationBatchSchema;
367
408
  //#endregion
368
- export { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_NUMBERING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, FolioJsonSchema, folioDocumentOperationBatchSchema };
409
+ export { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_NUMBERING_JSON_SCHEMA, FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, FolioJsonSchema, folioDocumentOperationBatchSchema };
@@ -135,7 +135,7 @@ const blockIdProperty = {
135
135
  };
136
136
  const FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA = {
137
137
  oneOf: [{ type: "string" }, { type: "null" }],
138
- description: "Paragraph style id; null clears the direct style."
138
+ description: "Paragraph style id; it must name a paragraph style the document defines, or the operation skips with `missingStyle`. null clears the direct style."
139
139
  };
140
140
  const FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA = {
141
141
  oneOf: [{
@@ -145,6 +145,38 @@ const FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA = {
145
145
  }, { type: "null" }],
146
146
  description: "`w:numPr/w:ilvl`, zero-based; a number retains the paragraph or anchor's numbering instance (`numId`), while null removes paragraph numbering unless a concrete numbering instance is supplied, in which case it omits the direct level."
147
147
  };
148
+ /** Direct `w:outlineLvl`, or null to restore style inheritance. */
149
+ const FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA = {
150
+ oneOf: [
151
+ {
152
+ type: "object",
153
+ properties: {
154
+ kind: {
155
+ type: "string",
156
+ enum: ["heading"]
157
+ },
158
+ level: {
159
+ type: "integer",
160
+ minimum: 0,
161
+ maximum: 8
162
+ }
163
+ },
164
+ required: ["kind", "level"],
165
+ additionalProperties: false
166
+ },
167
+ {
168
+ type: "object",
169
+ properties: { kind: {
170
+ type: "string",
171
+ enum: ["bodyText"]
172
+ } },
173
+ required: ["kind"],
174
+ additionalProperties: false
175
+ },
176
+ { type: "null" }
177
+ ],
178
+ description: "Direct outline level (`w:outlineLvl`): a heading level from 0 (top) to 8, or body text. null removes it and lets the paragraph style decide."
179
+ };
148
180
  /** Complete direct `w:ind` attributes, or null to restore style inheritance. */
149
181
  const FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA = {
150
182
  oneOf: [{
@@ -178,24 +210,47 @@ const FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA = {
178
210
  description: "Which paragraphs split from `text` receive the operation's paragraph formatting: `firstParagraph` (default) formats only the first, for a heading followed by its body; `allParagraphs` formats every paragraph alike, for several list items in one operation."
179
211
  };
180
212
  const FOLIO_CLEARABLE_NUMBERING_JSON_SCHEMA = {
181
- oneOf: [{
182
- type: "object",
183
- properties: {
184
- numId: {
185
- type: "integer",
186
- minimum: 1,
187
- maximum: Number.MAX_SAFE_INTEGER
213
+ oneOf: [
214
+ {
215
+ type: "object",
216
+ properties: {
217
+ numId: {
218
+ type: "integer",
219
+ minimum: 1,
220
+ maximum: Number.MAX_SAFE_INTEGER
221
+ },
222
+ level: {
223
+ type: "integer",
224
+ minimum: 0,
225
+ maximum: Number.MAX_SAFE_INTEGER
226
+ }
188
227
  },
189
- level: {
190
- type: "integer",
191
- minimum: 0,
192
- maximum: Number.MAX_SAFE_INTEGER
193
- }
228
+ required: ["numId", "level"],
229
+ additionalProperties: false
194
230
  },
195
- required: ["numId", "level"],
196
- additionalProperties: false
197
- }, { type: "null" }],
198
- description: "Concrete numbering instance and level; null removes paragraph numbering."
231
+ {
232
+ type: "object",
233
+ properties: {
234
+ start: {
235
+ type: "string",
236
+ enum: ["new"]
237
+ },
238
+ kind: {
239
+ type: "string",
240
+ enum: ["numbered", "bullet"]
241
+ },
242
+ level: {
243
+ type: "integer",
244
+ minimum: 0,
245
+ maximum: 8
246
+ }
247
+ },
248
+ required: ["start", "kind"],
249
+ additionalProperties: false
250
+ },
251
+ { type: "null" }
252
+ ],
253
+ description: "An existing numbering instance and level (`numId` from a prior read; it must name an instance the document defines, one a list block read from it carries, or the operation skips with `missingNumbering`); or `{ start: \"new\", kind: \"numbered\" | \"bullet\", level? }` to start a new list, numbered from the first item, with every paragraph this operation numbers in it (separate operations start separate lists; works in a document with no lists); null removes paragraph numbering."
199
254
  };
200
255
  const FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA = {
201
256
  type: "object",
@@ -263,6 +318,7 @@ const FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA = {
263
318
  description: "The paragraph properties to set; at least one.",
264
319
  properties: {
265
320
  styleId: FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA,
321
+ outlineLevel: FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA,
266
322
  listLevel: FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA,
267
323
  numbering: FOLIO_CLEARABLE_NUMBERING_JSON_SCHEMA,
268
324
  indentation: FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA,
@@ -421,6 +477,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
421
477
  description: "Start the inserted paragraph on a new page (`pageBreakBefore`)."
422
478
  },
423
479
  styleId: FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA,
480
+ outlineLevel: FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA,
424
481
  listLevel: FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA,
425
482
  alignment: {
426
483
  oneOf: [{
@@ -477,6 +534,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
477
534
  description: "Start the inserted paragraph on a new page (`pageBreakBefore`)."
478
535
  },
479
536
  styleId: FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA,
537
+ outlineLevel: FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA,
480
538
  listLevel: FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA,
481
539
  alignment: {
482
540
  oneOf: [{
@@ -1025,4 +1083,4 @@ const folioDocumentOperationBatchSchema = {
1025
1083
  jsonSchema: FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA
1026
1084
  };
1027
1085
  //#endregion
1028
- export { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_NUMBERING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, folioDocumentOperationBatchSchema };
1086
+ export { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_NUMBERING_JSON_SCHEMA, FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, folioDocumentOperationBatchSchema };
package/dist/tools.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { FOLIO_COMMENT_ID_JSON_SCHEMA, FOLIO_SCOPED_HANDLE_JSON_SCHEMA, FOLIO_SECTION_HANDLE_JSON_SCHEMA, FOLIO_STORY_HANDLE_JSON_SCHEMA } from "./codecs.js";
2
- import { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_NUMBERING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA } from "./operation-schema.js";
2
+ import { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_LIST_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_NUMBERING_JSON_SCHEMA, FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA } from "./operation-schema.js";
3
3
  import { DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, resolveSuggestChangesOptions } from "./suggest-changes-options.js";
4
4
  import { defineFolioAgentToolDefinition } from "./tool-contract.js";
5
5
  import { FOLIO_AGENT_TOOL_NAMES } from "./types.js";
@@ -53,7 +53,7 @@ const OPERATION_TYPE_SUMMARIES = {
53
53
  const OPERATION_PROPERTY_SCHEMAS = {
54
54
  id: {
55
55
  type: "string",
56
- description: "Optional caller-supplied operation id, echoed back in `applied` / `queued` / `skipped`. Generated when omitted."
56
+ description: "Optional caller-supplied operation id, echoed back in `applied` / `queued` / `skipped`. Generated when omitted. An id names one operation for the whole document: resending an operation that already landed (a retry) changes nothing and lists it under `replayed`; reusing an id for a different operation fails the call."
57
57
  },
58
58
  blockId: {
59
59
  type: "string",
@@ -105,6 +105,7 @@ const OPERATION_PROPERTY_SCHEMAS = {
105
105
  description: "For `commentOnBlock`: optional exact text within the block the comment is about, up to 100,000 characters."
106
106
  },
107
107
  styleId: FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA,
108
+ outlineLevel: FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA,
108
109
  pageBreakBefore: {
109
110
  type: "boolean",
110
111
  description: "For inserts: start the inserted paragraph on a new page."
@@ -315,7 +316,7 @@ const definitionsFromRegistry = (registry) => Object.values(registry);
315
316
  const FOLIO_AGENT_TOOL_REGISTRY = {
316
317
  [FOLIO_AGENT_TOOL_NAMES.readDocument]: defineFolioAgentToolDefinition({
317
318
  name: FOLIO_AGENT_TOOL_NAMES.readDocument,
318
- description: "Read the full document body as a list of blocks (paragraphs, headings, list items). Call this first, or whenever you need fresh block ids after a mutation — block ids from a stale read may no longer resolve. Each block includes a `blockTextHash`; echo it as `precondition.blockTextHash` on a suggest_changes / add_comment operation to guard against the block changing before that call runs.",
319
+ description: "Read the full document body as a list of blocks (paragraphs, headings, list items). Call this first, or whenever you need fresh block ids after a mutation — block ids from a stale read may no longer resolve. A block shows its number or bullet (`2.1.`, `a)`, `•`) as `displayLabel`, a numbered heading included; a heading also has `headingLevel` and a numbered block `listLevel`. Each block includes a `blockTextHash`; echo it as `precondition.blockTextHash` on a suggest_changes / add_comment operation to guard against the block changing before that call runs.",
319
320
  inputSchema: {
320
321
  type: "object",
321
322
  properties: {},
@@ -340,7 +341,7 @@ const FOLIO_AGENT_TOOL_REGISTRY = {
340
341
  }),
341
342
  [FOLIO_AGENT_TOOL_NAMES.readSection]: defineFolioAgentToolDefinition({
342
343
  name: FOLIO_AGENT_TOOL_NAMES.readSection,
343
- description: "Read one logical heading section using a handle from get_document_outline. Content is block-bounded and paginated with an afterBlockId cursor, avoiding a full-document read. Each block includes a `blockTextHash`; echo it as `precondition.blockTextHash` on a suggest_changes / add_comment operation.",
344
+ description: "Read one logical heading section using a handle from get_document_outline. Content is block-bounded and paginated with an afterBlockId cursor, avoiding a full-document read. Blocks have the same fields as read_document's, `displayLabel`, `headingLevel` and `listLevel` included. Each block includes a `blockTextHash`; echo it as `precondition.blockTextHash` on a suggest_changes / add_comment operation.",
344
345
  inputSchema: {
345
346
  type: "object",
346
347
  properties: {
package/dist/types.d.ts CHANGED
@@ -67,11 +67,27 @@ type FolioToolCallResult<TResult = unknown> = {
67
67
  ok: false;
68
68
  error: string;
69
69
  };
70
- /** One document block as exposed to a model: id, kind, and its plain text. */
70
+ /**
71
+ * One document block as exposed to a model: id, kind, its plain text, and the
72
+ * number or level a reader sees beside it. Absent fields are omitted.
73
+ */
71
74
  type FolioAgentBlock = {
72
75
  blockId: string;
76
+ /**
77
+ * `heading`, `listItem` or `paragraph`. A numbered heading (`1. Scope`) is a
78
+ * `heading` with its number in `displayLabel`.
79
+ */
73
80
  kind: string;
74
81
  text: string;
82
+ /**
83
+ * What the document shows beside the text: the list or heading number
84
+ * (`2.1.`, `a)`, `•`), or an unnumbered heading's style id (`Heading1`).
85
+ */
86
+ displayLabel?: string;
87
+ /** One-based heading level, on headings. */
88
+ headingLevel?: number;
89
+ /** Zero-based numbering level, on numbered paragraphs and headings. */
90
+ listLevel?: number;
75
91
  /**
76
92
  * Normalized-text hash of this block at read time. Echo it back as
77
93
  * `precondition.blockTextHash` on a `suggest_changes` / `add_comment`
@@ -197,6 +213,14 @@ type FolioAgentApplyOperationsSummary = {
197
213
  queued: {
198
214
  id: string;
199
215
  }[];
216
+ /**
217
+ * Operations this document already applied or queued under the same id and
218
+ * the same content, resent (a retry after a lost response, say). Nothing
219
+ * runs again; their original receipts are in `receipts`.
220
+ */
221
+ replayed: {
222
+ id: string;
223
+ }[];
200
224
  skipped: {
201
225
  id: string;
202
226
  reason: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/folio-agents",
3
- "version": "0.14.2",
3
+ "version": "0.15.0",
4
4
  "description": "Framework-neutral LLM tool layer over folio's ai-edits engine: function-calling tools so an agent can read and mutate .docx documents through @stll/folio-core.",
5
5
  "keywords": [
6
6
  "agent",
@@ -54,7 +54,7 @@
54
54
  "test": "bun test src"
55
55
  },
56
56
  "dependencies": {
57
- "@stll/folio-core": "^0.52.0",
57
+ "@stll/folio-core": "^0.53.0",
58
58
  "better-result": "3.0.1"
59
59
  },
60
60
  "main": "./dist/index.js",
@@ -125,12 +125,42 @@ stay exported for validation-only paths.
125
125
  prior tool call in the same conversation — `read_document`, `find_text`, or
126
126
  `read_comments`. Never invent or reuse one from outside the conversation;
127
127
  ids are opaque values a caller reads, never ones it constructs, and they
128
- change whenever the document's structure changes.
128
+ change whenever the document's structure changes. The same holds for a
129
+ numbering instance (`numbering.numId`): use one a list block of this
130
+ document carries; an instance the document does not define skips the
131
+ operation (`missingNumbering`) before anything is applied.
132
+ - A clause number ("clause 2.1") is found through a block's `displayLabel`,
133
+ the number the document shows beside it; a numbered heading is
134
+ `kind: "heading"` with its `headingLevel` and its number in `displayLabel`.
129
135
  - `suggest_changes` operations that get skipped (`skipped: [{ id, reason }]`)
130
136
  return a plain-language reason, not a machine code (e.g. "the block changed
131
137
  since your snapshot; re-read the document and retry with fresh ids"). Treat
132
138
  a skip as a retry signal: re-read (`read_document` or `find_text`) and
133
- reissue with fresh ids, not a dead end.
139
+ reissue with fresh ids, not a dead end. The one exception is
140
+ `invalidResult`: the operation would have left a document that cannot be
141
+ saved, so nothing from it was applied; rephrase it rather than resend it.
142
+ - An operation `id` names one operation for the whole document. If a
143
+ `suggest_changes` response is lost, resend the same call: operations that
144
+ already landed come back under `replayed` and are not applied twice. Never
145
+ reuse an id for a different operation (that fails the call); omit ids to
146
+ have fresh ones generated.
147
+ - Every operation of one `suggest_changes` call addresses the document as it
148
+ was read. Give each block or stretch of text at most one operation that
149
+ deletes, rewrites, splits or merges it: a later operation on a target an
150
+ earlier one of the same call already claims is skipped
151
+ (`overlappingOperation`). Send it again, on its own, after re-reading.
152
+ - Offsets and ranges count UTF-16 code units and must fall between two
153
+ characters: not inside an emoji, and for a text change or split not between
154
+ a letter and its combining marks either (`splitsCharacter`, with the
155
+ offsets on either side).
156
+ - A `styleId` must name a paragraph style the document defines; an undefined
157
+ id, or a table or character style, skips the operation (`missingStyle`, with
158
+ the paragraph styles the document offers) before anything is applied.
159
+ `null` clears the style.
160
+ - A block pending deletion (a tracked change deletes its text and paragraph
161
+ mark, or its table row) reads as a blank block; `replaceBlock` on it skips
162
+ (`pendingDeletion`), since accepting would join the new text to the next
163
+ paragraph. Reject that deletion first, or insert a new block next to it.
134
164
  - Successful mutations return input-ordered `receipts`. Use their typed
135
165
  `affected` targets to identify updated blocks, stable ranges, insertions,
136
166
  and created comments without inferring effects from document text.
@@ -153,8 +183,12 @@ stay exported for validation-only paths.
153
183
  `insertBeforeBlock` with `text: ""` insert a blank line; `deleteBlock` on a
154
184
  blank removes it rather than doing nothing. Only an operation that would
155
185
  change nothing at all is refused.
156
- - `insertTableRow` builds the new row to the table's own column count, so
157
- `cellTexts` fills the columns that exist and any it does not name stay empty.
186
+ - `insertTableRow` builds one cell per column the new row has, so `cellTexts`
187
+ fills those cells in order and any it does not name stay empty. A vertical
188
+ merge crossing the insertion point grows through the new row and keeps its
189
+ column, so the row has fewer cells there; more `cellTexts` than cells is
190
+ refused as `payloadDoesNotFit` (the issue's `message` names the texts), never
191
+ truncated. The same holds for `insertTableColumn` across a horizontal merge.
158
192
  - A `queued` list in a `suggest_changes` result means the host parked those
159
193
  operations in its own review queue; treat it like `applied` for the purpose
160
194
  of "the edit has been proposed", never as a failure.