@stll/folio-agents 0.1.0 → 0.2.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,25 +18,26 @@ 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
- | `find_text` | Search block text for a string; returns block id, occurrence, and context per match |
25
- | `read_comments` | Read comment threads (author, text, resolved, anchored block, replies) |
26
- | `read_changes` | Read pending tracked changes (insertions/deletions) awaiting review |
27
- | `add_comment` | Attach a comment to a block, optionally quoting specific text |
28
- | `suggest_changes` | Propose `replaceInBlock` / `insertAfterBlock` / `insertBeforeBlock` / `replaceBlock` / `deleteBlock` edits as tracked changes |
29
- | `reply_comment` | Reply to a comment thread |
30
- | `resolve_comment` | Resolve or reopen a comment thread |
31
- | `read_page` | Read a page's plain text (live editor only) |
32
- | `read_selection` | Read the current text selection (live editor only) |
33
- | `scroll_to_block` | Scroll the live editor to a block (live editor only) |
21
+ | Tool | What it does |
22
+ | ----------------- | ----------------------------------------------------------------------------------- |
23
+ | `read_document` | Read the document body as `{ blockId, kind, text }` blocks |
24
+ | `find_text` | Search block text for a string; returns block id, occurrence, and context per match |
25
+ | `read_comments` | Read comment threads (author, text, resolved, anchored block, replies) |
26
+ | `read_changes` | Read pending tracked changes (insertions/deletions) awaiting review |
27
+ | `add_comment` | Attach a comment to a block, optionally quoting specific text |
28
+ | `suggest_changes` | Propose block or stable-range edits as tracked changes |
29
+ | `reply_comment` | Reply to a comment thread |
30
+ | `resolve_comment` | Resolve or reopen a comment thread |
31
+ | `read_page` | Read a page's plain text (live editor only) |
32
+ | `read_selection` | Read the current text selection (live editor only) |
33
+ | `scroll_to_block` | Scroll the live editor to a block (live editor only) |
34
34
 
35
35
  Block ids and comment ids always come from a prior tool call
36
36
  (`read_document`, `find_text`, `read_comments`) within the same conversation —
37
37
  never guess them. `suggest_changes` reports a plain-language reason when an
38
38
  operation is skipped (e.g. the block changed since it was last read), so the
39
- model can re-read and retry.
39
+ model can re-read and retry. Successful mutation results include `receipts`
40
+ that identify affected blocks, ranges, insertions, and created comments.
40
41
 
41
42
  ### Untrusted documents
42
43
 
@@ -115,7 +116,7 @@ if (!parsed.ok) {
115
116
  // executeFolioToolCall would.
116
117
  } else {
117
118
  // `parsed.operations` is FolioAIEditOperation[] — route it into your own
118
- // review queue instead of bridge.applyOperations(...).
119
+ // review queue instead of bridge.applyDocumentOperations(...).
119
120
  reviewQueue.enqueue(parsed.operations);
120
121
  }
121
122
  ```
package/dist/bridge.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { FolioAgentChange, FolioAgentComment } from "./types.js";
2
- import { FolioAIEditApplyResult, FolioAIEditOperation, FolioAIEditSnapshot } from "@stll/folio-core/server";
2
+ import { FolioAIEditSnapshot, FolioDocumentOperationBatch, FolioDocumentOperationResult, FolioDocumentStory, FolioDocumentStoryHandle } from "@stll/folio-core/server";
3
3
 
4
4
  //#region src/bridge.d.ts
5
5
  /**
@@ -18,13 +18,14 @@ import { FolioAIEditApplyResult, FolioAIEditOperation, FolioAIEditSnapshot } fro
18
18
  type FolioAgentBridge = {
19
19
  /** Snapshot the current document into AI-facing blocks + anchors. */snapshot(): FolioAIEditSnapshot;
20
20
  /**
21
- * Apply operations against the current document. The bridge decides mode
22
- * (tracked-changes by default) and author internally — callers only supply
23
- * the operations.
21
+ * Apply a versioned operation batch against the current document. The
22
+ * bridge decides mode (tracked-changes by default) and author internally.
24
23
  */
25
- applyOperations(operations: FolioAIEditOperation[]): FolioAIEditApplyResult; /** The comment threads present in the document. */
24
+ applyDocumentOperations(batch: FolioDocumentOperationBatch): FolioDocumentOperationResult; /** The comment threads present in the document. */
26
25
  getComments(): FolioAgentComment[]; /** The pending tracked changes (insertions/deletions) present in the document. */
27
- getChanges(): FolioAgentChange[]; /** Reply to a comment thread. Returns `false` when the target comment does not exist. */
26
+ getChanges(): FolioAgentChange[]; /** Discover typed document stories when the surface exposes package parts. */
27
+ listStories?(): FolioDocumentStory[]; /** Read one previously discovered story. */
28
+ readStory?(handle: FolioDocumentStoryHandle): FolioDocumentStory | null; /** Reply to a comment thread. Returns `false` when the target comment does not exist. */
28
29
  replyToComment(commentId: string, text: string): boolean; /** Mark a comment thread resolved or reopen it. Returns `false` when the target comment does not exist. */
29
30
  resolveComment(commentId: string, resolved: boolean): boolean; /** Scroll the live editor to the given block and select it. */
30
31
  scrollToBlock?(blockId: string): boolean; /** The user's current text selection in the live editor, as plain text. */
@@ -1,9 +1,14 @@
1
1
  import { FolioAgentBridge } from "../bridge.js";
2
- import { FolioAIEditApplyMode, FolioAIEditApplyResult, FolioAIEditOperation, FolioAIEditSnapshot } from "@stll/folio-core/server";
2
+ import { FolioAIEditApplyMode, FolioAIEditApplyResult, FolioAIEditOperation, FolioAIEditSnapshot, FolioDocumentOperationBatch, FolioDocumentOperationResult } from "@stll/folio-core/server";
3
3
  import { FolioCommentAnchor, FolioReviewChange as FolioReviewChange$1 } from "@stll/folio-core/ai-edits";
4
4
  import { Comment } from "@stll/folio-core/types/content";
5
5
 
6
6
  //#region src/bridges/editor-ref.d.ts
7
+ type FolioAgentEditorApplyDocumentOperationsOptions = {
8
+ snapshot: FolioAIEditSnapshot;
9
+ batch: FolioDocumentOperationBatch;
10
+ author?: string;
11
+ };
7
12
  /**
8
13
  * Minimal structural slice of `DocxEditorRef` (`packages/react`) this bridge
9
14
  * drives — declared locally per AGENTS.md's react-free-core rule (agents
@@ -24,7 +29,8 @@ type FolioAgentEditorRefLike = {
24
29
  operations: FolioAIEditOperation[];
25
30
  mode?: FolioAIEditApplyMode;
26
31
  author?: string;
27
- }): FolioAIEditApplyResult; /** `DocxEditorRef.scrollToBlock`. */
32
+ }): FolioAIEditApplyResult; /** `DocxEditorRef.applyDocumentOperations`, when available on newer refs. */
33
+ applyDocumentOperations?(options: FolioAgentEditorApplyDocumentOperationsOptions): FolioDocumentOperationResult; /** `DocxEditorRef.scrollToBlock`. */
28
34
  scrollToBlock(blockId: string, snapshot?: FolioAIEditSnapshot): boolean; /** `DocxEditorRef.getTotalPages`. */
29
35
  getTotalPages(): number;
30
36
  /**
@@ -87,4 +93,4 @@ type CreateEditorRefBridgeOptions = {
87
93
  */
88
94
  declare const createEditorRefBridge: (options: CreateEditorRefBridgeOptions) => FolioAgentBridge;
89
95
  //#endregion
90
- export { CreateEditorRefBridgeOptions, FolioAgentEditorRefLike, createEditorRefBridge };
96
+ export { CreateEditorRefBridgeOptions, FolioAgentEditorApplyDocumentOperationsOptions, FolioAgentEditorRefLike, createEditorRefBridge };
@@ -1,4 +1,5 @@
1
1
  import { toAgentChange } from "./shared.js";
2
+ import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, assertSupportedFolioDocumentOperationVersion, getFolioDocumentOperationIssues, getFolioDocumentOperationReceipts } from "@stll/folio-core/server";
2
3
  import { createReply } from "@stll/folio-core/docx/replyToComment";
3
4
  //#region src/bridges/editor-ref.ts
4
5
  const toAgentCommentReply = (reply) => ({
@@ -58,12 +59,67 @@ const createEditorRefBridge = (options) => {
58
59
  };
59
60
  const bridge = {
60
61
  snapshot: requireSnapshot,
61
- applyOperations: (operations) => ref.applyAIEditOperations({
62
- snapshot: requireSnapshot(),
63
- operations,
64
- mode,
65
- author
66
- }),
62
+ applyDocumentOperations: (batch) => {
63
+ assertSupportedFolioDocumentOperationVersion(batch.version);
64
+ const snapshot = requireSnapshot();
65
+ const versionedBatch = {
66
+ ...batch,
67
+ mode
68
+ };
69
+ if (ref.applyDocumentOperations) {
70
+ const result = ref.applyDocumentOperations({
71
+ snapshot,
72
+ batch: versionedBatch,
73
+ author
74
+ });
75
+ return {
76
+ ...result,
77
+ issues: result.issues ?? getFolioDocumentOperationIssues(versionedBatch.operations, result.skipped),
78
+ receipts: result.receipts ?? getFolioDocumentOperationReceipts(versionedBatch.operations, result.applied)
79
+ };
80
+ }
81
+ if (versionedBatch.dryRun === true) {
82
+ const skipped = versionedBatch.operations.map(({ id }) => ({
83
+ id,
84
+ reason: "unsupportedMode"
85
+ }));
86
+ return {
87
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
88
+ status: "previewed",
89
+ applied: [],
90
+ skipped,
91
+ issues: getFolioDocumentOperationIssues(versionedBatch.operations, skipped),
92
+ receipts: []
93
+ };
94
+ }
95
+ if (versionedBatch.atomic === true) {
96
+ const skipped = versionedBatch.operations.map(({ id }) => ({
97
+ id,
98
+ reason: "unsupportedMode"
99
+ }));
100
+ return {
101
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
102
+ status: "rejected",
103
+ applied: [],
104
+ skipped,
105
+ issues: getFolioDocumentOperationIssues(versionedBatch.operations, skipped),
106
+ receipts: []
107
+ };
108
+ }
109
+ const result = ref.applyAIEditOperations({
110
+ snapshot,
111
+ operations: versionedBatch.operations,
112
+ mode: versionedBatch.mode,
113
+ author
114
+ });
115
+ return {
116
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
117
+ status: "committed",
118
+ ...result,
119
+ issues: getFolioDocumentOperationIssues(versionedBatch.operations, result.skipped),
120
+ receipts: getFolioDocumentOperationReceipts(versionedBatch.operations, result.applied)
121
+ };
122
+ },
67
123
  getComments: () => {
68
124
  const comments = getComments();
69
125
  const anchors = ref.getCommentAnchors?.();
@@ -117,10 +173,7 @@ const createEditorRefBridge = (options) => {
117
173
  const next = comments.map((comment) => {
118
174
  if (comment.id !== targetId) return comment;
119
175
  found = true;
120
- return {
121
- ...comment,
122
- done: resolved
123
- };
176
+ return Object.assign({}, comment, { done: resolved });
124
177
  });
125
178
  if (!found) return false;
126
179
  setComments(next);
@@ -33,9 +33,14 @@ const createReviewerBridge = (reviewer, options = {}) => {
33
33
  const mode = options.mode ?? "tracked-changes";
34
34
  return {
35
35
  snapshot: () => reviewer.snapshot(),
36
- applyOperations: (operations) => reviewer.applyOperations(operations, { mode }),
36
+ applyDocumentOperations: (batch) => reviewer.applyDocumentOperations({
37
+ ...batch,
38
+ mode
39
+ }),
37
40
  getComments: () => reviewer.getComments().map(toAgentComment),
38
41
  getChanges: () => reviewer.getChanges().map(toAgentChange),
42
+ listStories: () => reviewer.listStories(),
43
+ readStory: (handle) => reviewer.readStory(handle),
39
44
  replyToComment: (commentId, text) => {
40
45
  const parentId = parseCommentId(commentId);
41
46
  if (parentId === null) return false;
package/dist/compare.d.ts CHANGED
@@ -1,53 +1,15 @@
1
- import { WordDiffSegment } from "@stll/folio-core/ai-edits";
1
+ import { FolioBlockDiff, FolioVersionDiff, FolioVersionDiffSegment } from "@stll/folio-core/server";
2
2
 
3
3
  //#region src/compare.d.ts
4
- /** One word-level diff segment within a `modified` block. Mirrors {@link WordDiffSegment}. */
5
- type FolioAgentVersionDiffSegment = WordDiffSegment;
6
- /** One block-level change between two document versions, in revised-side document order. */
7
- type FolioAgentBlockDiff = {
8
- type: "added";
9
- blockId: string;
10
- kind: string;
11
- text: string;
12
- } | {
13
- type: "deleted";
14
- blockId: string;
15
- kind: string;
16
- text: string;
17
- } | {
18
- type: "modified";
19
- blockId: string;
20
- kind: string;
21
- segments: FolioAgentVersionDiffSegment[];
22
- };
23
- /** Result of {@link compareDocxVersions}. */
24
- type FolioAgentVersionDiff = {
25
- /** Every added, deleted, or modified block, in revised-side document order (deletions slotted where they sat). */changes: FolioAgentBlockDiff[]; /** Counts across every paired/unpaired block, including the unchanged blocks `changes` omits. */
26
- summaryCounts: {
27
- added: number;
28
- deleted: number;
29
- modified: number;
30
- unchanged: number;
31
- };
32
- };
33
- /** True when an `unpairedBaseCount * unpairedRevisedCount` LCS table would exceed {@link MAX_LCS_CELLS}. */
34
- declare const exceedsLcsBudget: (unpairedBaseCount: number, unpairedRevisedCount: number) => boolean;
35
- /**
36
- * Compare two `.docx` buffers and return a structured, block-level diff.
37
- * See the module doc comment for the as-accepted comparison semantics and
38
- * the three-pass alignment algorithm.
39
- */
4
+ /** Backward-compatible name for a core word-level version-diff segment. */
5
+ type FolioAgentVersionDiffSegment = FolioVersionDiffSegment;
6
+ /** Backward-compatible name for a core block-level version diff. */
7
+ type FolioAgentBlockDiff = FolioBlockDiff;
8
+ /** Backward-compatible name for a structured core version diff. */
9
+ type FolioAgentVersionDiff = FolioVersionDiff;
10
+ /** Compare two `.docx` buffers using folio-core's version comparison semantics. */
40
11
  declare const compareDocxVersions: (base: ArrayBuffer, revised: ArrayBuffer) => Promise<FolioAgentVersionDiff>;
41
- /**
42
- * Render a {@link FolioAgentVersionDiff} as compact, deterministic text for a
43
- * model prompt: a header line with the summary counts, then one line per
44
- * change — `~ [blockId] modified: …`, `+ [blockId] added: …`,
45
- * `- [blockId] deleted: …`. A modified block's segments render inline using
46
- * `git diff --word-diff` porcelain conventions (`[-removed-]`, `{+added+}`,
47
- * plain text for unchanged runs, truncated to ~30 characters on each side
48
- * when long). The format is stable across calls — do not change it without
49
- * checking `compare.test.ts`.
50
- */
12
+ /** Render a structured version diff as compact, deterministic model input. */
51
13
  declare const formatVersionDiffForLLM: (diff: FolioAgentVersionDiff) => string;
52
14
  //#endregion
53
- export { FolioAgentBlockDiff, FolioAgentVersionDiff, FolioAgentVersionDiffSegment, compareDocxVersions, exceedsLcsBudget, formatVersionDiffForLLM };
15
+ export { FolioAgentBlockDiff, FolioAgentVersionDiff, FolioAgentVersionDiffSegment, compareDocxVersions, formatVersionDiffForLLM };
package/dist/compare.js CHANGED
@@ -1,169 +1,13 @@
1
- import { diffWordSegments } from "@stll/folio-core/ai-edits";
2
- import { FolioDocxReviewer, getFolioParaIdFromBlockId } from "@stll/folio-core/server";
1
+ import { compareDocxVersions as compareDocxVersions$1 } from "@stll/folio-core/server";
3
2
  //#region src/compare.ts
4
- /**
5
- * Document version-diff engine: compare two `.docx` buffers block by block
6
- * and produce a structured, LLM-summarizable diff.
7
- *
8
- * Both buffers are parsed through {@link FolioDocxReviewer} — the same
9
- * headless parsing + clean-text path `read_document` / `read_changes` use —
10
- * so the comparison runs over each document's AS-ACCEPTED view: any pending
11
- * tracked changes already present in EITHER buffer count as applied before
12
- * the two are compared. Two documents that agree once their own pending
13
- * redlines are accepted report as unchanged, even if the underlying
14
- * tracked-change history differs.
15
- *
16
- * ## Alignment
17
- *
18
- * Blocks are paired across the two snapshots in three passes, each only
19
- * considering blocks the previous pass left unpaired:
20
- *
21
- * 1. **Stable-id pairing.** Blocks whose ids are equal AND not a `seq-NNNN`
22
- * positional fallback ({@link getFolioParaIdFromBlockId} returns non-null)
23
- * are paired directly. This covers both id shapes a snapshot can carry:
24
- * - A real Word `w14:paraId`: stable identity, independent of text — an
25
- * equal-id pair with different text is a genuine edit (`modified`).
26
- * - `FolioDocxReviewer`'s deterministic fallback id (assigned when the
27
- * source paragraph has no `w14:paraId`), which hashes the paragraph's
28
- * TEXT plus its document ordinal. It is structurally indistinguishable
29
- * from a real paraId ({@link getFolioParaIdFromBlockId} can't tell them
30
- * apart), but pairing on equality is still safe: two equal deterministic
31
- * ids necessarily came from identical text at an identical ordinal, so
32
- * the pair is always text-equal (`unchanged`) — never a false
33
- * `modified`. What it can't do is FIND a paragraph whose ordinal shifted
34
- * (an insertion/deletion earlier in the document) even though its text
35
- * is unchanged: that pair has two different fallback ids and falls
36
- * through to pass 2.
37
- * 2. **Exact-text pairing.** An order-preserving LCS over remaining blocks,
38
- * matched by exact text equality. This is what recovers same-text blocks
39
- * that pass 1 missed because a fallback id shifted with the ordinal. Its
40
- * O(m·n) table is skipped ({@link exceedsLcsBudget}) once the unpaired
41
- * counts on both sides would exceed a fixed cell budget, so a document
42
- * with few/no stable ids can't force a quadratic-sized allocation; those
43
- * blocks fall through to pass 3 instead.
44
- * 3. **Positional fallback.** Whatever a monotonicity filter leaves
45
- * unpaired is split into the gaps between anchored pairs (pass 1 + 2,
46
- * time-ordered); within each gap the shorter side is zipped positionally
47
- * against the longer one (`modified`), and any excess on either side is
48
- * reported as `added` / `deleted`.
49
- *
50
- * The combined anchor set from passes 1 and 2 is re-filtered to the longest
51
- * increasing subsequence by revised-side index before pass 3 runs, so a
52
- * pathological crossing match (content reordered across versions) can't
53
- * produce an out-of-order gap — the alignment always walks both documents
54
- * forward.
55
- */
56
- const isStableBlockId = (id) => getFolioParaIdFromBlockId(id) !== null;
57
- const index = (blocks) => blocks.map((block, blockIndex) => ({
58
- block,
59
- index: blockIndex
60
- }));
61
- /**
62
- * Longest increasing subsequence by `revisedIndex`, assuming `pairs` is
63
- * already sorted by `baseIndex` ascending. Drops any pair that would make
64
- * the alignment walk backward in the revised document — the guard against
65
- * both id collisions (pass 1) and any crossing match (pass 1 + 2 combined).
66
- */
67
- const longestIncreasingByRevisedIndex = (pairs) => {
68
- if (pairs.length === 0) return [];
69
- const lengths = Array.from({ length: pairs.length }).fill(1);
70
- const predecessors = Array.from({ length: pairs.length }).fill(-1);
71
- let bestEnd = 0;
72
- for (let i = 0; i < pairs.length; i++) {
73
- for (let j = 0; j < i; j++) {
74
- const current = pairs[j];
75
- const candidate = pairs[i];
76
- if (!current || !candidate) continue;
77
- if (current.revisedIndex < candidate.revisedIndex && (lengths[j] ?? 0) + 1 > (lengths[i] ?? 0)) {
78
- lengths[i] = (lengths[j] ?? 0) + 1;
79
- predecessors[i] = j;
80
- }
81
- }
82
- if ((lengths[i] ?? 0) > (lengths[bestEnd] ?? 0)) bestEnd = i;
83
- }
84
- const ordered = [];
85
- for (let cursor = bestEnd; cursor !== -1; cursor = predecessors[cursor] ?? -1) {
86
- const pair = pairs[cursor];
87
- if (pair) ordered.push(pair);
88
- }
89
- return ordered.toReversed();
90
- };
91
- /** Pass 1: pair blocks with equal, non-`seq-NNNN` ids. See the module doc comment. */
92
- const pairByStableId = (base, revised) => {
93
- const revisedIndexById = /* @__PURE__ */ new Map();
94
- revised.forEach((block, revisedIndex) => {
95
- if (isStableBlockId(block.id)) revisedIndexById.set(block.id, revisedIndex);
96
- });
97
- const candidates = [];
98
- base.forEach((block, baseIndex) => {
99
- if (!isStableBlockId(block.id)) return;
100
- const revisedIndex = revisedIndexById.get(block.id);
101
- if (revisedIndex !== void 0) candidates.push({
102
- baseIndex,
103
- revisedIndex
104
- });
105
- });
106
- return longestIncreasingByRevisedIndex(candidates);
107
- };
108
- /**
109
- * Cell budget for pass 2's O(m·n) exact-text LCS table (`dp` below allocates
110
- * `(m + 1) * (n + 1)` numbers). A document with no `w14:paraId`s — or an
111
- * adversarial one crafted to defeat pass 1 — can leave thousands of blocks
112
- * unpaired on both sides; without a cap, `pairByExactText` would allocate a
113
- * quadratic-sized table for it. Past this budget, {@link exceedsLcsBudget}
114
- * makes pass 2 back off entirely so alignment falls through to pass 3's
115
- * linear positional zip instead — pairing is less precise for these
116
- * degenerate inputs, but memory use stays bounded.
117
- */
118
- const MAX_LCS_CELLS = 4e6;
119
- /** True when an `unpairedBaseCount * unpairedRevisedCount` LCS table would exceed {@link MAX_LCS_CELLS}. */
120
- const exceedsLcsBudget = (unpairedBaseCount, unpairedRevisedCount) => unpairedBaseCount * unpairedRevisedCount > MAX_LCS_CELLS;
121
- /** Pass 2: order-preserving LCS by exact text equality over the blocks pass 1 left unpaired. */
122
- const pairByExactText = (base, revised) => {
123
- const m = base.length;
124
- const n = revised.length;
125
- if (m === 0 || n === 0) return [];
126
- if (exceedsLcsBudget(m, n)) return [];
127
- const stride = n + 1;
128
- const dp = new Int32Array((m + 1) * stride);
129
- for (let i = m - 1; i >= 0; i--) {
130
- const rowOffset = i * stride;
131
- const nextRowOffset = (i + 1) * stride;
132
- for (let j = n - 1; j >= 0; j--) {
133
- const baseText = base[i]?.block.text;
134
- const revisedText = revised[j]?.block.text;
135
- dp[rowOffset + j] = baseText === revisedText ? (dp[nextRowOffset + j + 1] ?? 0) + 1 : Math.max(dp[nextRowOffset + j] ?? 0, dp[rowOffset + j + 1] ?? 0);
136
- }
137
- }
138
- const pairs = [];
139
- let i = 0;
140
- let j = 0;
141
- while (i < m && j < n) {
142
- const baseEntry = base[i];
143
- const revisedEntry = revised[j];
144
- if (!baseEntry || !revisedEntry) break;
145
- if (baseEntry.block.text === revisedEntry.block.text) {
146
- pairs.push({
147
- baseIndex: baseEntry.index,
148
- revisedIndex: revisedEntry.index
149
- });
150
- i++;
151
- j++;
152
- continue;
153
- }
154
- if ((dp[(i + 1) * stride + j] ?? 0) >= (dp[i * stride + j + 1] ?? 0)) i++;
155
- else j++;
156
- }
157
- return pairs;
158
- };
3
+ /** Compare two `.docx` buffers using folio-core's version comparison semantics. */
4
+ const compareDocxVersions = (base, revised) => compareDocxVersions$1(base, revised);
159
5
  const ELLIPSIS = "…";
160
6
  const UNCHANGED_EDGE_CHARS = 30;
161
- /** Collapse a long `equal`-type run to ~30 chars on each side with an ellipsis in between. */
162
7
  const truncateUnchangedRun = (text) => {
163
8
  if (text.length <= 61) return text;
164
9
  return `${text.slice(0, UNCHANGED_EDGE_CHARS)}${ELLIPSIS}${text.slice(-30)}`;
165
10
  };
166
- /** Render one word-diff segment: plain for `equal` (truncated if long), bracketed for `del` / `ins`. */
167
11
  const renderSegment = (segment) => {
168
12
  switch (segment.type) {
169
13
  case "equal": return truncateUnchangedRun(segment.text);
@@ -173,113 +17,20 @@ const renderSegment = (segment) => {
173
17
  }
174
18
  };
175
19
  const formatChangeLine = (change) => {
176
- if (change.type === "added") return `+ [${change.blockId}] added: ${change.text}`;
177
- if (change.type === "deleted") return `- [${change.blockId}] deleted: ${change.text}`;
178
- return `~ [${change.blockId}] modified: ${change.segments.map(renderSegment).join("")}`;
179
- };
180
- /**
181
- * Compare two `.docx` buffers and return a structured, block-level diff.
182
- * See the module doc comment for the as-accepted comparison semantics and
183
- * the three-pass alignment algorithm.
184
- */
185
- const compareDocxVersions = async (base, revised) => {
186
- const [baseReviewer, revisedReviewer] = await Promise.all([FolioDocxReviewer.fromBuffer(base), FolioDocxReviewer.fromBuffer(revised)]);
187
- const baseBlocks = baseReviewer.snapshot().blocks;
188
- const revisedBlocks = revisedReviewer.snapshot().blocks;
189
- const stableIdAnchors = pairByStableId(baseBlocks, revisedBlocks);
190
- const usedBaseIndexes = new Set(stableIdAnchors.map((anchor) => anchor.baseIndex));
191
- const usedRevisedIndexes = new Set(stableIdAnchors.map((anchor) => anchor.revisedIndex));
192
- const exactTextAnchors = pairByExactText(index(baseBlocks).filter(({ index: i }) => !usedBaseIndexes.has(i)), index(revisedBlocks).filter(({ index: i }) => !usedRevisedIndexes.has(i)));
193
- const anchors = longestIncreasingByRevisedIndex([...stableIdAnchors, ...exactTextAnchors].toSorted((a, b) => a.baseIndex - b.baseIndex));
194
- const changes = [];
195
- const counts = {
196
- added: 0,
197
- deleted: 0,
198
- modified: 0,
199
- unchanged: 0
200
- };
201
- /** Pass 3: positionally zip the leftover blocks in one gap between anchors. */
202
- const emitGap = (baseFrom, baseTo, revisedFrom, revisedTo) => {
203
- const baseSlice = baseBlocks.slice(baseFrom, baseTo);
204
- const revisedSlice = revisedBlocks.slice(revisedFrom, revisedTo);
205
- const pairedCount = Math.min(baseSlice.length, revisedSlice.length);
206
- for (let k = 0; k < pairedCount; k++) {
207
- const baseBlock = baseSlice[k];
208
- const revisedBlock = revisedSlice[k];
209
- if (!baseBlock || !revisedBlock) continue;
210
- if (baseBlock.text === revisedBlock.text) {
211
- counts.unchanged++;
212
- continue;
213
- }
214
- counts.modified++;
215
- changes.push({
216
- type: "modified",
217
- blockId: revisedBlock.id,
218
- kind: revisedBlock.kind,
219
- segments: diffWordSegments(baseBlock.text, revisedBlock.text)
220
- });
221
- }
222
- for (let k = pairedCount; k < baseSlice.length; k++) {
223
- const baseBlock = baseSlice[k];
224
- if (!baseBlock) continue;
225
- counts.deleted++;
226
- changes.push({
227
- type: "deleted",
228
- blockId: baseBlock.id,
229
- kind: baseBlock.kind,
230
- text: baseBlock.text
231
- });
232
- }
233
- for (let k = pairedCount; k < revisedSlice.length; k++) {
234
- const revisedBlock = revisedSlice[k];
235
- if (!revisedBlock) continue;
236
- counts.added++;
237
- changes.push({
238
- type: "added",
239
- blockId: revisedBlock.id,
240
- kind: revisedBlock.kind,
241
- text: revisedBlock.text
242
- });
243
- }
244
- };
245
- let baseCursor = 0;
246
- let revisedCursor = 0;
247
- for (const anchor of anchors) {
248
- emitGap(baseCursor, anchor.baseIndex, revisedCursor, anchor.revisedIndex);
249
- const baseBlock = baseBlocks[anchor.baseIndex];
250
- const revisedBlock = revisedBlocks[anchor.revisedIndex];
251
- if (baseBlock && revisedBlock) if (baseBlock.text === revisedBlock.text) counts.unchanged++;
252
- else {
253
- counts.modified++;
254
- changes.push({
255
- type: "modified",
256
- blockId: revisedBlock.id,
257
- kind: revisedBlock.kind,
258
- segments: diffWordSegments(baseBlock.text, revisedBlock.text)
259
- });
260
- }
261
- baseCursor = anchor.baseIndex + 1;
262
- revisedCursor = anchor.revisedIndex + 1;
20
+ switch (change.type) {
21
+ case "added": return `+ [${change.blockId}] added: ${change.text}`;
22
+ case "deleted": return `- [${change.blockId}] deleted: ${change.text}`;
23
+ case "modified": return `~ [${change.blockId}] modified: ${change.segments.map(renderSegment).join("")}`;
24
+ case "formatChanged": return `~ [${change.blockId}] format changed (${change.changedProperties.join(", ")}): ${truncateUnchangedRun(change.text)}`;
25
+ case "movedFrom": return `< [${change.blockId}] moved away (move ${change.moveGroupId}): ${truncateUnchangedRun(change.text)}`;
26
+ case "movedTo": return `> [${change.blockId}] moved here (move ${change.moveGroupId}): ${truncateUnchangedRun(change.text)}`;
27
+ default: return "";
263
28
  }
264
- emitGap(baseCursor, baseBlocks.length, revisedCursor, revisedBlocks.length);
265
- return {
266
- changes,
267
- summaryCounts: counts
268
- };
269
29
  };
270
- /**
271
- * Render a {@link FolioAgentVersionDiff} as compact, deterministic text for a
272
- * model prompt: a header line with the summary counts, then one line per
273
- * change — `~ [blockId] modified: …`, `+ [blockId] added: …`,
274
- * `- [blockId] deleted: …`. A modified block's segments render inline using
275
- * `git diff --word-diff` porcelain conventions (`[-removed-]`, `{+added+}`,
276
- * plain text for unchanged runs, truncated to ~30 characters on each side
277
- * when long). The format is stable across calls — do not change it without
278
- * checking `compare.test.ts`.
279
- */
30
+ /** Render a structured version diff as compact, deterministic model input. */
280
31
  const formatVersionDiffForLLM = (diff) => {
281
- const { added, deleted, modified, unchanged } = diff.summaryCounts;
282
- return [`Version diff: ${added} added, ${deleted} deleted, ${modified} modified, ${unchanged} unchanged`, ...diff.changes.map(formatChangeLine)].join("\n");
32
+ const { added, deleted, modified, formatChanged, moved, unchanged } = diff.summaryCounts;
33
+ return [`Version diff: ${added} added, ${deleted} deleted, ${modified} modified, ${formatChanged} format-changed, ${moved} moved, ${unchanged} unchanged`, ...diff.changes.map(formatChangeLine)].join("\n");
283
34
  };
284
35
  //#endregion
285
- export { compareDocxVersions, exceedsLcsBudget, formatVersionDiffForLLM };
36
+ export { compareDocxVersions, formatVersionDiffForLLM };
package/dist/execute.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput } from "./parse.js";
2
2
  import { FOLIO_AGENT_TOOL_NAMES } from "./types.js";
3
+ import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, createFolioAITextRangeHandle } from "@stll/folio-core/server";
3
4
  //#region src/execute.ts
4
5
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
6
  const isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
@@ -37,6 +38,8 @@ const executeFolioToolCall = (name, args, bridge) => {
37
38
  };
38
39
  const dispatch = (name, args, bridge) => {
39
40
  if (name === FOLIO_AGENT_TOOL_NAMES.readDocument) return readDocument(bridge);
41
+ if (name === FOLIO_AGENT_TOOL_NAMES.listStories) return bridge.listStories ? ok(bridge.listStories()) : fail("This editor surface does not support story discovery.");
42
+ if (name === FOLIO_AGENT_TOOL_NAMES.readStory) return readStory(args, bridge);
40
43
  if (name === FOLIO_AGENT_TOOL_NAMES.findText) return findText(args, bridge);
41
44
  if (name === FOLIO_AGENT_TOOL_NAMES.readComments) return readComments(args, bridge);
42
45
  if (name === FOLIO_AGENT_TOOL_NAMES.readChanges) return ok(bridge.getChanges());
@@ -57,6 +60,31 @@ const readDocument = (bridge) => {
57
60
  text: block.text
58
61
  })));
59
62
  };
63
+ const readStory = (args, bridge) => {
64
+ if (!bridge.readStory) return fail("This editor surface does not support story reads.");
65
+ if (!isPlainObject(args) || !isPlainObject(args["handle"])) return fail("read_story requires a typed `handle` from list_stories.");
66
+ const handle = args["handle"];
67
+ const type = handle["type"];
68
+ let parsed;
69
+ if (type === "main") parsed = { type };
70
+ else if (type === "header" || type === "footer") {
71
+ const relationshipId = handle["relationshipId"];
72
+ if (!isNonEmptyString(relationshipId)) return fail("read_story requires the handle's `relationshipId`.");
73
+ parsed = {
74
+ type,
75
+ relationshipId
76
+ };
77
+ } else if (type === "footnote" || type === "endnote") {
78
+ const noteId = handle["noteId"];
79
+ if (typeof noteId !== "number" || !Number.isInteger(noteId)) return fail("read_story requires the handle's integer `noteId`.");
80
+ parsed = {
81
+ type,
82
+ noteId
83
+ };
84
+ } else return fail("read_story received an unsupported story handle type.");
85
+ const story = bridge.readStory(parsed);
86
+ return story ? ok(story) : fail("The requested story was not found; run list_stories again.");
87
+ };
60
88
  const CONTEXT_RADIUS = 40;
61
89
  const findTextMatches = (blocks, query, matchCase) => {
62
90
  const matches = [];
@@ -73,8 +101,16 @@ const findTextMatches = (blocks, query, matchCase) => {
73
101
  if (matches.length < MAX_FIND_MATCHES) {
74
102
  const contextStart = Math.max(0, at - CONTEXT_RADIUS);
75
103
  const contextEnd = Math.min(block.text.length, at + query.length + CONTEXT_RADIUS);
104
+ const range = createFolioAITextRangeHandle({
105
+ blockId: block.id,
106
+ text: block.text,
107
+ startOffset: at,
108
+ endOffset: at + query.length
109
+ });
110
+ if (range === null) break;
76
111
  matches.push({
77
112
  blockId: block.id,
113
+ range,
78
114
  occurrenceInBlock: occurrence,
79
115
  context: block.text.slice(contextStart, contextEnd)
80
116
  });
@@ -97,11 +133,12 @@ const findText = (args, bridge) => {
97
133
  if (matchCase !== void 0 && typeof matchCase !== "boolean") return fail("find_text's `matchCase` must be a boolean when provided.");
98
134
  const { blocks } = bridge.snapshot();
99
135
  const { matches, totalMatches } = findTextMatches(blocks, query, matchCase === true);
100
- return ok({
136
+ const result = {
101
137
  matches,
102
138
  truncated: totalMatches > matches.length,
103
139
  totalMatches
104
- });
140
+ };
141
+ return ok(result);
105
142
  };
106
143
  const isCommentFilter = (value) => value === "all" || value === "open" || value === "resolved";
107
144
  const readComments = (args, bridge) => {
@@ -122,26 +159,49 @@ const explainSkipReason = (reason) => {
122
159
  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.";
123
160
  if (reason === "missingFind") return "`find` was not found in this block; re-read the block's current text and retry.";
124
161
  if (reason === "unsupportedBlock") return "this block kind does not support this operation.";
162
+ if (reason === "unsupportedMode") return "this operation does not support the requested mutation mode; inspect document operation capabilities and retry with a supported mode.";
163
+ if (reason === "atomicBatchRejected") return "another operation in this atomic batch could not be applied; no operations were committed.";
164
+ if (reason === "preconditionFailed") return "the target block changed after the operation was prepared; re-read the document and retry with a fresh operation.";
165
+ if (reason === "staleRange") return "the selected range changed or shifted; run find_text again and retry with the fresh range.";
125
166
  if (reason === "emptyOperation") return "this operation has no effect; nothing to apply.";
126
167
  if (reason === "noopOperation") return "this operation would not change the document (the text already matches what you asked for).";
127
168
  return reason;
128
169
  };
129
170
  const summarizeApplyResult = (result) => ({
171
+ version: result.version,
130
172
  applied: result.applied.map((entry) => ({ id: entry.id })),
131
173
  skipped: result.skipped.map((entry) => ({
132
174
  id: entry.id,
133
175
  reason: explainSkipReason(entry.reason)
134
- }))
176
+ })),
177
+ issues: result.issues ?? [],
178
+ receipts: result.receipts ?? []
135
179
  });
180
+ const applyOperations = (bridge, operations) => {
181
+ const snapshot = bridge.snapshot();
182
+ const guardedOperations = [];
183
+ for (const operation of operations) {
184
+ const blockId = operation.type === "replaceRange" || operation.type === "commentOnRange" || operation.type === "formatRange" ? operation.range.blockId : operation.blockId;
185
+ const blockTextHash = snapshot.anchors[blockId]?.textHash;
186
+ guardedOperations.push({
187
+ ...operation,
188
+ ...blockTextHash !== void 0 && { precondition: { blockTextHash } }
189
+ });
190
+ }
191
+ return summarizeApplyResult(bridge.applyDocumentOperations({
192
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
193
+ operations: guardedOperations
194
+ }));
195
+ };
136
196
  const addComment = (args, bridge) => {
137
197
  const parsed = parseAddCommentInput(args);
138
198
  if (!parsed.ok) return fail(parsed.error);
139
- return ok(summarizeApplyResult(bridge.applyOperations([parsed.operation])));
199
+ return ok(applyOperations(bridge, [parsed.operation]));
140
200
  };
141
201
  const suggestChanges = (args, bridge) => {
142
202
  const parsed = parseSuggestChangesInput(args);
143
203
  if (!parsed.ok) return fail(parsed.error);
144
- return ok(summarizeApplyResult(bridge.applyOperations(parsed.operations)));
204
+ return ok(applyOperations(bridge, parsed.operations));
145
205
  };
146
206
  const replyComment = (args, bridge) => {
147
207
  if (!isPlainObject(args)) return fail("reply_comment expects an object with `commentId` and `text` strings.");
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { FOLIO_AGENT_TOOL_NAMES, FolioAgentApplyOperationsSummary, FolioAgentBlock, FolioAgentChange, FolioAgentComment, FolioAgentCommentFilter, FolioAgentCommentReply, FolioAgentTextMatch, FolioAgentToolDefinition, FolioAgentToolName, FolioToolCallResult } from "./types.js";
2
2
  import { FolioAgentBridge } from "./bridge.js";
3
- import { CreateEditorRefBridgeOptions, FolioAgentEditorRefLike, createEditorRefBridge } from "./bridges/editor-ref.js";
3
+ import { CreateEditorRefBridgeOptions, FolioAgentEditorApplyDocumentOperationsOptions, FolioAgentEditorRefLike, createEditorRefBridge } from "./bridges/editor-ref.js";
4
4
  import { CreateReviewerBridgeOptions, createReviewerBridge } from "./bridges/reviewer.js";
5
5
  import { FolioAgentBlockDiff, FolioAgentVersionDiff, FolioAgentVersionDiffSegment, compareDocxVersions, formatVersionDiffForLLM } from "./compare.js";
6
6
  import { executeFolioToolCall } from "./execute.js";
7
7
  import { ParseAddCommentResult, ParseSuggestChangesResult, parseAddCommentInput, parseSuggestChangesInput } from "./parse.js";
8
8
  import { AnthropicToolDefinition, OpenAIToolDefinition, toAnthropicTools, toOpenAITools } from "./providers.js";
9
9
  import { FOLIO_AGENT_TOOLS, getFolioToolDefinitions } from "./tools.js";
10
- export { type AnthropicToolDefinition, type CreateEditorRefBridgeOptions, type CreateReviewerBridgeOptions, FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_NAMES, type FolioAgentApplyOperationsSummary, type FolioAgentBlock, type FolioAgentBlockDiff, type FolioAgentBridge, type FolioAgentChange, type FolioAgentComment, type FolioAgentCommentFilter, type FolioAgentCommentReply, type FolioAgentEditorRefLike, type FolioAgentTextMatch, type FolioAgentToolDefinition, type FolioAgentToolName, type FolioAgentVersionDiff, type FolioAgentVersionDiffSegment, type FolioToolCallResult, type OpenAIToolDefinition, type ParseAddCommentResult, type ParseSuggestChangesResult, compareDocxVersions, createEditorRefBridge, createReviewerBridge, executeFolioToolCall, formatVersionDiffForLLM, getFolioToolDefinitions, parseAddCommentInput, parseSuggestChangesInput, toAnthropicTools, toOpenAITools };
10
+ export { type AnthropicToolDefinition, type CreateEditorRefBridgeOptions, type CreateReviewerBridgeOptions, FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_NAMES, type FolioAgentApplyOperationsSummary, type FolioAgentBlock, type FolioAgentBlockDiff, type FolioAgentBridge, type FolioAgentChange, type FolioAgentComment, type FolioAgentCommentFilter, type FolioAgentCommentReply, type FolioAgentEditorApplyDocumentOperationsOptions, type FolioAgentEditorRefLike, type FolioAgentTextMatch, type FolioAgentToolDefinition, type FolioAgentToolName, type FolioAgentVersionDiff, type FolioAgentVersionDiffSegment, type FolioToolCallResult, type OpenAIToolDefinition, type ParseAddCommentResult, type ParseSuggestChangesResult, compareDocxVersions, createEditorRefBridge, createReviewerBridge, executeFolioToolCall, formatVersionDiffForLLM, getFolioToolDefinitions, parseAddCommentInput, parseSuggestChangesInput, toAnthropicTools, toOpenAITools };
package/dist/parse.js CHANGED
@@ -57,8 +57,31 @@ const parseAddCommentInput = (args) => {
57
57
  }
58
58
  };
59
59
  };
60
- const OPERATION_TYPES = "replaceInBlock, insertAfterBlock, insertBeforeBlock, replaceBlock, deleteBlock";
61
- const isOperationType = (value) => value === "replaceInBlock" || value === "insertAfterBlock" || value === "insertBeforeBlock" || value === "replaceBlock" || value === "deleteBlock";
60
+ const OPERATION_TYPES = "replaceInBlock, replaceRange, commentOnRange, insertAfterBlock, insertBeforeBlock, replaceBlock, deleteBlock";
61
+ const isOperationType = (value) => value === "replaceInBlock" || value === "replaceRange" || value === "commentOnRange" || value === "insertAfterBlock" || value === "insertBeforeBlock" || value === "replaceBlock" || value === "deleteBlock";
62
+ const readTextRange = (value, index) => {
63
+ const path = `operations[${index}].range`;
64
+ if (!isPlainObject(value)) return `${path} must be an object copied from find_text.`;
65
+ const type = value["type"];
66
+ const story = value["story"];
67
+ const blockId = value["blockId"];
68
+ const startOffset = value["startOffset"];
69
+ const endOffset = value["endOffset"];
70
+ const selectedTextHash = value["selectedTextHash"];
71
+ if (type !== "textRange" || story !== "main") return `${path} must be a main-story textRange copied from find_text.`;
72
+ if (!isNonEmptyString(blockId)) return `${path}.blockId must be a non-empty string.`;
73
+ if (typeof startOffset !== "number" || !Number.isInteger(startOffset) || startOffset < 0) return `${path}.startOffset must be a non-negative integer.`;
74
+ if (typeof endOffset !== "number" || !Number.isInteger(endOffset) || endOffset <= startOffset) return `${path}.endOffset must be an integer greater than startOffset.`;
75
+ if (!isNonEmptyString(selectedTextHash) || !/^h[0-9a-z]+$/.test(selectedTextHash)) return `${path}.selectedTextHash must be a normalized text hash.`;
76
+ return {
77
+ type,
78
+ story,
79
+ blockId,
80
+ startOffset,
81
+ endOffset,
82
+ selectedTextHash
83
+ };
84
+ };
62
85
  /** Validate + map one `suggest_changes` operation, or return a plain-language error string. */
63
86
  const buildSuggestedOperation = (raw, index) => {
64
87
  if (!isPlainObject(raw)) return `operations[${index}] must be an object.`;
@@ -67,12 +90,35 @@ const buildSuggestedOperation = (raw, index) => {
67
90
  const id = raw["id"];
68
91
  const comment = raw["comment"];
69
92
  if (!isOperationType(type)) return `operations[${index}].type must be one of ${OPERATION_TYPES}.`;
70
- if (!isNonEmptyString(blockId)) return `operations[${index}].blockId must be a non-empty string.`;
71
93
  if (id !== void 0 && !isNonEmptyString(id)) return `operations[${index}].id must be a non-empty string when provided.`;
72
94
  if (comment !== void 0 && typeof comment !== "string") return `operations[${index}].comment must be a string when provided.`;
73
95
  if (typeof comment === "string" && comment.length > 1e5) return explainTextTooLong(`operations[${index}].comment`, comment.length);
74
96
  const opId = isNonEmptyString(id) ? id : `op-${index + 1}`;
75
97
  const commentField = typeof comment === "string" ? { comment: { text: comment } } : {};
98
+ if (type === "replaceRange" || type === "commentOnRange") {
99
+ const range = readTextRange(raw["range"], index);
100
+ if (typeof range === "string") return range;
101
+ if (type === "commentOnRange") {
102
+ if (!isNonEmptyString(comment)) return `operations[${index}] (commentOnRange) requires a non-empty string \`comment\`.`;
103
+ return {
104
+ id: opId,
105
+ type,
106
+ range,
107
+ comment: { text: comment }
108
+ };
109
+ }
110
+ const replace = raw["replace"];
111
+ if (typeof replace !== "string") return `operations[${index}] (replaceRange) requires a string \`replace\`.`;
112
+ if (replace.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceRange) \`replace\``, replace.length);
113
+ return {
114
+ id: opId,
115
+ type,
116
+ range,
117
+ replace,
118
+ ...commentField
119
+ };
120
+ }
121
+ if (!isNonEmptyString(blockId)) return `operations[${index}].blockId must be a non-empty string.`;
76
122
  if (type === "replaceInBlock") {
77
123
  const find = raw["find"];
78
124
  const replace = raw["replace"];
package/dist/tools.js CHANGED
@@ -18,6 +18,44 @@ const FOLIO_AGENT_TOOLS = [
18
18
  additionalProperties: false
19
19
  }
20
20
  },
21
+ {
22
+ name: FOLIO_AGENT_TOOL_NAMES.listStories,
23
+ description: "List readable document stories and their typed handles.",
24
+ inputSchema: {
25
+ type: "object",
26
+ properties: {},
27
+ required: [],
28
+ additionalProperties: false
29
+ }
30
+ },
31
+ {
32
+ name: FOLIO_AGENT_TOOL_NAMES.readStory,
33
+ description: "Read one document story using a handle returned by `list_stories`.",
34
+ inputSchema: {
35
+ type: "object",
36
+ properties: { handle: {
37
+ type: "object",
38
+ properties: {
39
+ type: {
40
+ type: "string",
41
+ enum: [
42
+ "main",
43
+ "header",
44
+ "footer",
45
+ "footnote",
46
+ "endnote"
47
+ ]
48
+ },
49
+ relationshipId: { type: "string" },
50
+ noteId: { type: "integer" }
51
+ },
52
+ required: ["type"],
53
+ additionalProperties: false
54
+ } },
55
+ required: ["handle"],
56
+ additionalProperties: false
57
+ }
58
+ },
21
59
  {
22
60
  name: FOLIO_AGENT_TOOL_NAMES.findText,
23
61
  description: "Search the document body for a text string and return `{ matches, truncated, totalMatches }`, where each match has its block id, which occurrence within that block it is, and surrounding context. `matches` is capped at 200 entries; `truncated` is true and `totalMatches` reports the real count when there were more — narrow the query instead of assuming you saw every hit. Use this to locate the blockId for a known phrase instead of reading the whole document.",
@@ -107,6 +145,8 @@ const FOLIO_AGENT_TOOLS = [
107
145
  type: "string",
108
146
  enum: [
109
147
  "replaceInBlock",
148
+ "replaceRange",
149
+ "commentOnRange",
110
150
  "insertAfterBlock",
111
151
  "insertBeforeBlock",
112
152
  "replaceBlock",
@@ -118,13 +158,46 @@ const FOLIO_AGENT_TOOLS = [
118
158
  type: "string",
119
159
  description: "The block to edit, from `read_document` or `find_text`."
120
160
  },
161
+ range: {
162
+ type: "object",
163
+ description: "Required for `replaceRange`: copy the range object returned by `find_text`.",
164
+ properties: {
165
+ type: {
166
+ type: "string",
167
+ enum: ["textRange"]
168
+ },
169
+ story: {
170
+ type: "string",
171
+ enum: ["main"]
172
+ },
173
+ blockId: { type: "string" },
174
+ startOffset: {
175
+ type: "integer",
176
+ minimum: 0
177
+ },
178
+ endOffset: {
179
+ type: "integer",
180
+ minimum: 1
181
+ },
182
+ selectedTextHash: { type: "string" }
183
+ },
184
+ required: [
185
+ "type",
186
+ "story",
187
+ "blockId",
188
+ "startOffset",
189
+ "endOffset",
190
+ "selectedTextHash"
191
+ ],
192
+ additionalProperties: false
193
+ },
121
194
  find: {
122
195
  type: "string",
123
196
  description: "Required for `replaceInBlock`: the exact text to find within the block, up to 100,000 characters."
124
197
  },
125
198
  replace: {
126
199
  type: "string",
127
- description: "Required for `replaceInBlock`: the text to replace `find` with, up to 100,000 characters."
200
+ description: "Required for `replaceInBlock` and `replaceRange`: replacement text, up to 100,000 characters."
128
201
  },
129
202
  text: {
130
203
  type: "string",
@@ -135,7 +208,7 @@ const FOLIO_AGENT_TOOLS = [
135
208
  description: "Optional comment explaining this edit, attached to the affected text, up to 100,000 characters."
136
209
  }
137
210
  },
138
- required: ["type", "blockId"],
211
+ required: ["type"],
139
212
  additionalProperties: false
140
213
  }
141
214
  } },
package/dist/types.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, FolioAITextRangeHandle, FolioDocumentOperationIssue, FolioDocumentOperationReceipt } from "@stll/folio-core/server";
2
+
1
3
  //#region src/types.d.ts
2
4
  /**
3
5
  * Provider-neutral tool-layer types. `FolioAgentToolDefinition` describes a
@@ -8,6 +10,8 @@
8
10
  /** Every tool name this package exposes, as a stable string union (no enums). */
9
11
  declare const FOLIO_AGENT_TOOL_NAMES: {
10
12
  readonly readDocument: "read_document";
13
+ readonly listStories: "list_stories";
14
+ readonly readStory: "read_story";
11
15
  readonly findText: "find_text";
12
16
  readonly readComments: "read_comments";
13
17
  readonly readChanges: "read_changes";
@@ -54,7 +58,8 @@ type FolioAgentBlock = {
54
58
  };
55
59
  /** One `find_text` match: which block, which occurrence within it, and a text window around the match. */
56
60
  type FolioAgentTextMatch = {
57
- blockId: string; /** 0-based index of this occurrence within its block (multiple matches in one block increment this). */
61
+ blockId: string; /** Stable handle that can be passed directly to a `replaceRange` operation. */
62
+ range: FolioAITextRangeHandle; /** 0-based index of this occurrence within its block (multiple matches in one block increment this). */
58
63
  occurrenceInBlock: number; /** The match plus ~40 characters of surrounding context on each side. */
59
64
  context: string;
60
65
  };
@@ -103,6 +108,7 @@ type FolioAgentChange = {
103
108
  type FolioAgentCommentFilter = "all" | "open" | "resolved";
104
109
  /** Result of {@link FOLIO_AGENT_TOOL_NAMES.addComment} / `suggest_changes`. */
105
110
  type FolioAgentApplyOperationsSummary = {
111
+ version: typeof FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION;
106
112
  applied: {
107
113
  id: string;
108
114
  }[];
@@ -110,6 +116,8 @@ type FolioAgentApplyOperationsSummary = {
110
116
  id: string;
111
117
  reason: string;
112
118
  }[];
119
+ issues: FolioDocumentOperationIssue[];
120
+ receipts: FolioDocumentOperationReceipt[];
113
121
  };
114
122
  //#endregion
115
123
  export { FOLIO_AGENT_TOOL_NAMES, FolioAgentApplyOperationsSummary, FolioAgentBlock, FolioAgentChange, FolioAgentComment, FolioAgentCommentFilter, FolioAgentCommentReply, FolioAgentFindTextResult, FolioAgentTextMatch, FolioAgentToolDefinition, FolioAgentToolName, FolioToolCallResult };
package/dist/types.js CHANGED
@@ -8,6 +8,8 @@
8
8
  /** Every tool name this package exposes, as a stable string union (no enums). */
9
9
  const FOLIO_AGENT_TOOL_NAMES = {
10
10
  readDocument: "read_document",
11
+ listStories: "list_stories",
12
+ readStory: "read_story",
11
13
  findText: "find_text",
12
14
  readComments: "read_comments",
13
15
  readChanges: "read_changes",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/folio-agents",
3
- "version": "0.1.0",
3
+ "version": "0.2.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",
@@ -50,11 +50,11 @@
50
50
  "build": "rm -rf dist && tsdown",
51
51
  "prepack": "bun run build",
52
52
  "pack:dry-run": "bun pm pack --dry-run",
53
- "typecheck": "tsgo --noEmit -p tsconfig.build.json",
53
+ "typecheck": "bun ../../scripts/tsc-native.ts --noEmit -p tsconfig.build.json",
54
54
  "test": "bun test src"
55
55
  },
56
56
  "dependencies": {
57
- "@stll/folio-core": "^0.2.0"
57
+ "@stll/folio-core": "^0.4.0"
58
58
  },
59
59
  "main": "./dist/index.js",
60
60
  "types": "./dist/index.d.ts"
@@ -99,14 +99,18 @@ go straight back to the model.
99
99
  since your snapshot; re-read the document and retry with fresh ids"). Treat
100
100
  a skip as a retry signal: re-read (`read_document` or `find_text`) and
101
101
  reissue with fresh ids, not a dead end.
102
+ - Successful mutations return input-ordered `receipts`. Use their typed
103
+ `affected` targets to identify updated blocks, stable ranges, insertions,
104
+ and created comments without inferring effects from document text.
102
105
  - `suggest_changes` defaults to tracked-changes mode on both shipped bridges
103
106
  — it proposes redlines for a human to accept or reject, never edits the
104
107
  visible text directly.
105
- - The tool surface here is fixed: five edit operation kinds
106
- (`replaceInBlock`, `insertAfterBlock`, `insertBeforeBlock`, `replaceBlock`,
107
- `deleteBlock`) plus comment/reply/resolve. There is no
108
+ - The tool surface here is fixed: seven edit operation kinds
109
+ (`replaceInBlock`, `replaceRange`, `commentOnRange`, `insertAfterBlock`,
110
+ `insertBeforeBlock`, `replaceBlock`, `deleteBlock`) plus
111
+ comment/reply/resolve. There is no
108
112
  `insertSignatureTable`-style structural op, and none should be invented —
109
- compose the five primitives, or extend `@stll/folio-core`'s ai-edits engine
113
+ compose the seven primitives, or extend `@stll/folio-core`'s ai-edits engine
110
114
  itself if a document needs a structural operation this package doesn't
111
115
  expose.
112
116
  - **Untrusted documents:** `read_document`, `read_comments`, `read_changes`,
@@ -123,8 +127,8 @@ go straight back to the model.
123
127
  Two different questions, two different tools:
124
128
 
125
129
  - **Pending redlines in one document** — what a reviewer would see as tracked
126
- changes right now: use the `read_changes` tool (headless bridge only; see
127
- the capability gap above) or call `reviewer.getChanges()` directly.
130
+ changes right now: use the `read_changes` tool on a capable bridge or call
131
+ `reviewer.getChanges()` directly.
128
132
  - **Between two saved `.docx` versions** — `compareDocxVersions(previousBuffer,
129
133
  currentBuffer)` + `formatVersionDiffForLLM(diff)`. Both are plain async
130
134
  functions, not tool definitions: a model can't attach two buffers to one