@stll/folio-agents 0.7.0 → 0.8.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/dist/execute.js CHANGED
@@ -1,6 +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, getFolioDocumentOutline, readFolioDocumentSection } from "@stll/folio-core/server";
3
+ import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, createFolioAITextRangeHandle, getFolioDocumentOutline, hashFolioAIBlockText, normalizeFolioAIBlockText, readFolioDocumentSection } from "@stll/folio-core/server";
4
4
  //#region src/execute.ts
5
5
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
6
  const isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
@@ -13,6 +13,15 @@ const fail = (error) => ({
13
13
  error
14
14
  });
15
15
  const VALID_TOOL_NAMES = Object.values(FOLIO_AGENT_TOOL_NAMES);
16
+ /**
17
+ * The same normalized-text hash the core snapshot/apply machinery uses for
18
+ * `precondition.blockTextHash` (see `hashFolioAIBlockText` /
19
+ * `normalizeFolioAIBlockText`). Computed straight from a block's `text`
20
+ * rather than looked up from `snapshot.anchors` so every read path (main
21
+ * document, a section, a find_text match) can attach it without threading
22
+ * the anchors map around — it is defined to produce the exact same value.
23
+ */
24
+ const blockTextHashOf = (text) => hashFolioAIBlockText(normalizeFolioAIBlockText(text));
16
25
  /** `find_text` requires a short `query` and caps how much of a large match set it returns in one call. */
17
26
  const MAX_QUERY_LENGTH = 1e3;
18
27
  const MAX_FIND_MATCHES = 200;
@@ -60,7 +69,8 @@ const readDocument = (bridge) => {
60
69
  return ok(blocks.map((block) => ({
61
70
  blockId: block.id,
62
71
  kind: block.kind,
63
- text: block.text
72
+ text: block.text,
73
+ blockTextHash: blockTextHashOf(block.text)
64
74
  })));
65
75
  };
66
76
  const parseSectionHandle = (value) => {
@@ -122,7 +132,8 @@ const readSection = (args, bridge) => {
122
132
  blocks: selected.map(({ id, kind, text }) => ({
123
133
  blockId: id,
124
134
  kind,
125
- text
135
+ text,
136
+ blockTextHash: blockTextHashOf(text)
126
137
  })),
127
138
  totalBlocks: resolved.section.blocks.length,
128
139
  truncated: hasMore,
@@ -162,6 +173,16 @@ const readStory = (args, bridge) => {
162
173
  const CONTEXT_RADIUS = 40;
163
174
  const WORD_CHARACTER_AT_END = /[\p{L}\p{M}\p{N}_]$/u;
164
175
  const WORD_CHARACTER_AT_START = /^[\p{L}\p{M}\p{N}_]/u;
176
+ /**
177
+ * Window (UTF-16 code units) sliced on each side of a match for the
178
+ * whole-word boundary check. The regexes above only ever test the single
179
+ * grapheme adjacent to the match, but a surrogate pair or a base character
180
+ * with stacked combining marks can span a few code units — this window is
181
+ * generous enough to cover that while staying a constant, not
182
+ * `block.text.length`. Without a bound, `.slice(0, at)` / `.slice(at + len)`
183
+ * on every match makes a whole-word search O(n^2) in the block's length.
184
+ */
185
+ const WORD_BOUNDARY_WINDOW = 8;
165
186
  const findTextMatches = (blocks, query, matchCase, wholeWord, getTargetPage, pageFilter) => {
166
187
  const matches = [];
167
188
  let totalMatches = 0;
@@ -169,10 +190,11 @@ const findTextMatches = (blocks, query, matchCase, wholeWord, getTargetPage, pag
169
190
  const expression = new RegExp(escapedQuery, matchCase ? "gu" : "giu");
170
191
  for (const block of blocks) {
171
192
  let occurrence = 0;
193
+ let blockTextHash;
172
194
  for (const match of block.text.matchAll(expression)) {
173
195
  const at = match.index;
174
196
  const matchedText = match[0];
175
- if (wholeWord && (WORD_CHARACTER_AT_END.test(block.text.slice(0, at)) || WORD_CHARACTER_AT_START.test(block.text.slice(at + matchedText.length)))) continue;
197
+ 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;
176
198
  const range = createFolioAITextRangeHandle({
177
199
  blockId: block.id,
178
200
  text: block.text,
@@ -186,10 +208,12 @@ const findTextMatches = (blocks, query, matchCase, wholeWord, getTargetPage, pag
186
208
  if (matches.length < MAX_FIND_MATCHES) {
187
209
  const contextStart = Math.max(0, at - CONTEXT_RADIUS);
188
210
  const contextEnd = Math.min(block.text.length, at + matchedText.length + CONTEXT_RADIUS);
211
+ blockTextHash ??= blockTextHashOf(block.text);
189
212
  matches.push({
190
213
  type: "main",
191
214
  story: { type: "main" },
192
215
  blockId: block.id,
216
+ blockTextHash,
193
217
  range,
194
218
  occurrenceInBlock: occurrence,
195
219
  context: block.text.slice(contextStart, contextEnd),
@@ -212,7 +236,7 @@ const findStoryTextMatches = (text, story, query, matchCase, wholeWord) => {
212
236
  for (const match of text.matchAll(expression)) {
213
237
  const at = match.index;
214
238
  const matchedText = match[0];
215
- if (wholeWord && (WORD_CHARACTER_AT_END.test(text.slice(0, at)) || WORD_CHARACTER_AT_START.test(text.slice(at + matchedText.length)))) continue;
239
+ if (wholeWord && (WORD_CHARACTER_AT_END.test(text.slice(Math.max(0, at - WORD_BOUNDARY_WINDOW), at)) || WORD_CHARACTER_AT_START.test(text.slice(at + matchedText.length, at + matchedText.length + WORD_BOUNDARY_WINDOW)))) continue;
216
240
  if (matches.length < MAX_FIND_MATCHES) matches.push({
217
241
  type: "story",
218
242
  story,
@@ -318,10 +342,31 @@ const summarizeApplyResult = (result) => ({
318
342
  issues: result.issues ?? [],
319
343
  receipts: result.receipts ?? []
320
344
  });
345
+ /**
346
+ * Attach a `precondition.blockTextHash` guard to every operation before
347
+ * handing the batch to the bridge.
348
+ *
349
+ * When the caller (the model) already echoed a `precondition` on the
350
+ * operation — sourced from a `blockTextHash` returned by an earlier
351
+ * `read_document` / `read_section` / `find_text` call — that is honored
352
+ * as-is: it is the only signal that can catch a document edit made
353
+ * BETWEEN that read and this apply call.
354
+ *
355
+ * When no precondition was supplied, fall back to stamping one from this
356
+ * call's own fresh `bridge.snapshot()`, matching the previous behavior.
357
+ * This fallback cannot detect cross-call staleness — the snapshot it reads
358
+ * from is taken right before applying, so it always matches the current
359
+ * live document — but it still guards a later operation in the SAME batch
360
+ * against an earlier operation in that batch touching the same block.
361
+ */
321
362
  const applyOperations = (bridge, operations) => {
322
363
  const snapshot = bridge.snapshot();
323
364
  const guardedOperations = [];
324
365
  for (const operation of operations) {
366
+ if (operation.precondition !== void 0) {
367
+ guardedOperations.push(operation);
368
+ continue;
369
+ }
325
370
  const blockId = operation.type === "replaceRange" || operation.type === "commentOnRange" || operation.type === "formatRange" ? operation.range.blockId : operation.blockId;
326
371
  const blockTextHash = snapshot.anchors[blockId]?.textHash;
327
372
  guardedOperations.push({
@@ -43,6 +43,26 @@ declare const FOLIO_TEXT_RANGE_JSON_SCHEMA: {
43
43
  readonly required: readonly ["type", "story", "blockId", "startOffset", "endOffset", "selectedTextHash"];
44
44
  readonly additionalProperties: false;
45
45
  };
46
+ /**
47
+ * JSON Schema for the contract's optional `precondition` guard: `{
48
+ * blockTextHash }`, echoed from a `blockTextHash` returned by a document
49
+ * read (`read_document`, `read_section`, `find_text`). Exported so
50
+ * `tools.ts` can attach the same shape to `suggest_changes` and
51
+ * `add_comment` without redeclaring it.
52
+ */
53
+ declare const FOLIO_PRECONDITION_JSON_SCHEMA: {
54
+ readonly type: "object";
55
+ readonly description: string;
56
+ readonly properties: {
57
+ readonly blockTextHash: {
58
+ readonly type: "string";
59
+ readonly pattern: "^h[0-9a-z]+$";
60
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
61
+ };
62
+ };
63
+ readonly required: readonly ["blockTextHash"];
64
+ readonly additionalProperties: false;
65
+ };
46
66
  /**
47
67
  * JSON Schema (draft-07 compatible) for ONE document operation: the full
48
68
  * thirteen-variant union accepted by `parseFolioDocumentOperationBatch` in
@@ -106,7 +126,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
106
126
  readonly blockTextHash: {
107
127
  readonly type: "string";
108
128
  readonly pattern: "^h[0-9a-z]+$";
109
- readonly description: "Normalized hash of the target block's text.";
129
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
110
130
  };
111
131
  };
112
132
  readonly required: readonly ["blockTextHash"];
@@ -193,7 +213,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
193
213
  readonly blockTextHash: {
194
214
  readonly type: "string";
195
215
  readonly pattern: "^h[0-9a-z]+$";
196
- readonly description: "Normalized hash of the target block's text.";
216
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
197
217
  };
198
218
  };
199
219
  readonly required: readonly ["blockTextHash"];
@@ -276,7 +296,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
276
296
  readonly blockTextHash: {
277
297
  readonly type: "string";
278
298
  readonly pattern: "^h[0-9a-z]+$";
279
- readonly description: "Normalized hash of the target block's text.";
299
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
280
300
  };
281
301
  };
282
302
  readonly required: readonly ["blockTextHash"];
@@ -364,7 +384,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
364
384
  readonly blockTextHash: {
365
385
  readonly type: "string";
366
386
  readonly pattern: "^h[0-9a-z]+$";
367
- readonly description: "Normalized hash of the target block's text.";
387
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
368
388
  };
369
389
  };
370
390
  readonly required: readonly ["blockTextHash"];
@@ -433,7 +453,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
433
453
  readonly blockTextHash: {
434
454
  readonly type: "string";
435
455
  readonly pattern: "^h[0-9a-z]+$";
436
- readonly description: "Normalized hash of the target block's text.";
456
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
437
457
  };
438
458
  };
439
459
  readonly required: readonly ["blockTextHash"];
@@ -502,7 +522,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
502
522
  readonly blockTextHash: {
503
523
  readonly type: "string";
504
524
  readonly pattern: "^h[0-9a-z]+$";
505
- readonly description: "Normalized hash of the target block's text.";
525
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
506
526
  };
507
527
  };
508
528
  readonly required: readonly ["blockTextHash"];
@@ -567,7 +587,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
567
587
  readonly blockTextHash: {
568
588
  readonly type: "string";
569
589
  readonly pattern: "^h[0-9a-z]+$";
570
- readonly description: "Normalized hash of the target block's text.";
590
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
571
591
  };
572
592
  };
573
593
  readonly required: readonly ["blockTextHash"];
@@ -620,7 +640,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
620
640
  readonly blockTextHash: {
621
641
  readonly type: "string";
622
642
  readonly pattern: "^h[0-9a-z]+$";
623
- readonly description: "Normalized hash of the target block's text.";
643
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
624
644
  };
625
645
  };
626
646
  readonly required: readonly ["blockTextHash"];
@@ -677,7 +697,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
677
697
  readonly blockTextHash: {
678
698
  readonly type: "string";
679
699
  readonly pattern: "^h[0-9a-z]+$";
680
- readonly description: "Normalized hash of the target block's text.";
700
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
681
701
  };
682
702
  };
683
703
  readonly required: readonly ["blockTextHash"];
@@ -758,7 +778,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
758
778
  readonly blockTextHash: {
759
779
  readonly type: "string";
760
780
  readonly pattern: "^h[0-9a-z]+$";
761
- readonly description: "Normalized hash of the target block's text.";
781
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
762
782
  };
763
783
  };
764
784
  readonly required: readonly ["blockTextHash"];
@@ -811,7 +831,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
811
831
  readonly blockTextHash: {
812
832
  readonly type: "string";
813
833
  readonly pattern: "^h[0-9a-z]+$";
814
- readonly description: "Normalized hash of the target block's text.";
834
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
815
835
  };
816
836
  };
817
837
  readonly required: readonly ["blockTextHash"];
@@ -852,7 +872,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
852
872
  readonly blockTextHash: {
853
873
  readonly type: "string";
854
874
  readonly pattern: "^h[0-9a-z]+$";
855
- readonly description: "Normalized hash of the target block's text.";
875
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
856
876
  };
857
877
  };
858
878
  readonly required: readonly ["blockTextHash"];
@@ -905,7 +925,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
905
925
  readonly blockTextHash: {
906
926
  readonly type: "string";
907
927
  readonly pattern: "^h[0-9a-z]+$";
908
- readonly description: "Normalized hash of the target block's text.";
928
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
909
929
  };
910
930
  };
911
931
  readonly required: readonly ["blockTextHash"];
@@ -946,7 +966,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
946
966
  readonly blockTextHash: {
947
967
  readonly type: "string";
948
968
  readonly pattern: "^h[0-9a-z]+$";
949
- readonly description: "Normalized hash of the target block's text.";
969
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
950
970
  };
951
971
  };
952
972
  readonly required: readonly ["blockTextHash"];
@@ -997,7 +1017,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
997
1017
  readonly blockTextHash: {
998
1018
  readonly type: "string";
999
1019
  readonly pattern: "^h[0-9a-z]+$";
1000
- readonly description: "Normalized hash of the target block's text.";
1020
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1001
1021
  };
1002
1022
  };
1003
1023
  readonly required: readonly ["blockTextHash"];
@@ -1043,7 +1063,7 @@ declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: {
1043
1063
  readonly blockTextHash: {
1044
1064
  readonly type: "string";
1045
1065
  readonly pattern: "^h[0-9a-z]+$";
1046
- readonly description: "Normalized hash of the target block's text.";
1066
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1047
1067
  };
1048
1068
  };
1049
1069
  readonly required: readonly ["blockTextHash"];
@@ -1128,7 +1148,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1128
1148
  readonly blockTextHash: {
1129
1149
  readonly type: "string";
1130
1150
  readonly pattern: "^h[0-9a-z]+$";
1131
- readonly description: "Normalized hash of the target block's text.";
1151
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1132
1152
  };
1133
1153
  };
1134
1154
  readonly required: readonly ["blockTextHash"];
@@ -1215,7 +1235,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1215
1235
  readonly blockTextHash: {
1216
1236
  readonly type: "string";
1217
1237
  readonly pattern: "^h[0-9a-z]+$";
1218
- readonly description: "Normalized hash of the target block's text.";
1238
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1219
1239
  };
1220
1240
  };
1221
1241
  readonly required: readonly ["blockTextHash"];
@@ -1298,7 +1318,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1298
1318
  readonly blockTextHash: {
1299
1319
  readonly type: "string";
1300
1320
  readonly pattern: "^h[0-9a-z]+$";
1301
- readonly description: "Normalized hash of the target block's text.";
1321
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1302
1322
  };
1303
1323
  };
1304
1324
  readonly required: readonly ["blockTextHash"];
@@ -1386,7 +1406,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1386
1406
  readonly blockTextHash: {
1387
1407
  readonly type: "string";
1388
1408
  readonly pattern: "^h[0-9a-z]+$";
1389
- readonly description: "Normalized hash of the target block's text.";
1409
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1390
1410
  };
1391
1411
  };
1392
1412
  readonly required: readonly ["blockTextHash"];
@@ -1455,7 +1475,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1455
1475
  readonly blockTextHash: {
1456
1476
  readonly type: "string";
1457
1477
  readonly pattern: "^h[0-9a-z]+$";
1458
- readonly description: "Normalized hash of the target block's text.";
1478
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1459
1479
  };
1460
1480
  };
1461
1481
  readonly required: readonly ["blockTextHash"];
@@ -1524,7 +1544,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1524
1544
  readonly blockTextHash: {
1525
1545
  readonly type: "string";
1526
1546
  readonly pattern: "^h[0-9a-z]+$";
1527
- readonly description: "Normalized hash of the target block's text.";
1547
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1528
1548
  };
1529
1549
  };
1530
1550
  readonly required: readonly ["blockTextHash"];
@@ -1589,7 +1609,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1589
1609
  readonly blockTextHash: {
1590
1610
  readonly type: "string";
1591
1611
  readonly pattern: "^h[0-9a-z]+$";
1592
- readonly description: "Normalized hash of the target block's text.";
1612
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1593
1613
  };
1594
1614
  };
1595
1615
  readonly required: readonly ["blockTextHash"];
@@ -1642,7 +1662,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1642
1662
  readonly blockTextHash: {
1643
1663
  readonly type: "string";
1644
1664
  readonly pattern: "^h[0-9a-z]+$";
1645
- readonly description: "Normalized hash of the target block's text.";
1665
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1646
1666
  };
1647
1667
  };
1648
1668
  readonly required: readonly ["blockTextHash"];
@@ -1699,7 +1719,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1699
1719
  readonly blockTextHash: {
1700
1720
  readonly type: "string";
1701
1721
  readonly pattern: "^h[0-9a-z]+$";
1702
- readonly description: "Normalized hash of the target block's text.";
1722
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1703
1723
  };
1704
1724
  };
1705
1725
  readonly required: readonly ["blockTextHash"];
@@ -1780,7 +1800,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1780
1800
  readonly blockTextHash: {
1781
1801
  readonly type: "string";
1782
1802
  readonly pattern: "^h[0-9a-z]+$";
1783
- readonly description: "Normalized hash of the target block's text.";
1803
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1784
1804
  };
1785
1805
  };
1786
1806
  readonly required: readonly ["blockTextHash"];
@@ -1833,7 +1853,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1833
1853
  readonly blockTextHash: {
1834
1854
  readonly type: "string";
1835
1855
  readonly pattern: "^h[0-9a-z]+$";
1836
- readonly description: "Normalized hash of the target block's text.";
1856
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1837
1857
  };
1838
1858
  };
1839
1859
  readonly required: readonly ["blockTextHash"];
@@ -1874,7 +1894,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1874
1894
  readonly blockTextHash: {
1875
1895
  readonly type: "string";
1876
1896
  readonly pattern: "^h[0-9a-z]+$";
1877
- readonly description: "Normalized hash of the target block's text.";
1897
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1878
1898
  };
1879
1899
  };
1880
1900
  readonly required: readonly ["blockTextHash"];
@@ -1927,7 +1947,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1927
1947
  readonly blockTextHash: {
1928
1948
  readonly type: "string";
1929
1949
  readonly pattern: "^h[0-9a-z]+$";
1930
- readonly description: "Normalized hash of the target block's text.";
1950
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1931
1951
  };
1932
1952
  };
1933
1953
  readonly required: readonly ["blockTextHash"];
@@ -1968,7 +1988,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
1968
1988
  readonly blockTextHash: {
1969
1989
  readonly type: "string";
1970
1990
  readonly pattern: "^h[0-9a-z]+$";
1971
- readonly description: "Normalized hash of the target block's text.";
1991
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
1972
1992
  };
1973
1993
  };
1974
1994
  readonly required: readonly ["blockTextHash"];
@@ -2019,7 +2039,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
2019
2039
  readonly blockTextHash: {
2020
2040
  readonly type: "string";
2021
2041
  readonly pattern: "^h[0-9a-z]+$";
2022
- readonly description: "Normalized hash of the target block's text.";
2042
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
2023
2043
  };
2024
2044
  };
2025
2045
  readonly required: readonly ["blockTextHash"];
@@ -2065,7 +2085,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
2065
2085
  readonly blockTextHash: {
2066
2086
  readonly type: "string";
2067
2087
  readonly pattern: "^h[0-9a-z]+$";
2068
- readonly description: "Normalized hash of the target block's text.";
2088
+ readonly description: "Normalized hash of the target block's text, from a prior document read.";
2069
2089
  };
2070
2090
  };
2071
2091
  readonly required: readonly ["blockTextHash"];
@@ -2079,7 +2099,7 @@ declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: {
2079
2099
  };
2080
2100
  readonly mode: {
2081
2101
  readonly type: "string";
2082
- readonly enum: readonly ["direct", "tracked-changes"];
2102
+ readonly enum: readonly ["direct", "tracked-changes", "suggested"];
2083
2103
  readonly description: string;
2084
2104
  };
2085
2105
  readonly atomic: {
@@ -2143,4 +2163,4 @@ type FolioDocumentOperationBatchSchema = StandardSchemaV1<unknown, FolioDocument
2143
2163
  */
2144
2164
  declare const folioDocumentOperationBatchSchema: FolioDocumentOperationBatchSchema;
2145
2165
  //#endregion
2146
- export { FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, folioDocumentOperationBatchSchema };
2166
+ export { FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, folioDocumentOperationBatchSchema };
@@ -69,13 +69,20 @@ const FOLIO_TEXT_RANGE_JSON_SCHEMA = {
69
69
  ],
70
70
  additionalProperties: false
71
71
  };
72
- const preconditionJsonSchema = {
72
+ /**
73
+ * JSON Schema for the contract's optional `precondition` guard: `{
74
+ * blockTextHash }`, echoed from a `blockTextHash` returned by a document
75
+ * read (`read_document`, `read_section`, `find_text`). Exported so
76
+ * `tools.ts` can attach the same shape to `suggest_changes` and
77
+ * `add_comment` without redeclaring it.
78
+ */
79
+ const FOLIO_PRECONDITION_JSON_SCHEMA = {
73
80
  type: "object",
74
- description: "Optional guard: the operation is skipped (reason `preconditionFailed`) unless the target block's normalized text hash still matches.",
81
+ description: "Optional guard against editing a block that changed since you read it: echo the `blockTextHash` returned by read_document / read_section / find_text for this block. The operation is skipped (reason `preconditionFailed`) unless the target block's current normalized text hash still matches.",
75
82
  properties: { blockTextHash: {
76
83
  type: "string",
77
84
  pattern: NORMALIZED_TEXT_HASH_PATTERN,
78
- description: "Normalized hash of the target block's text."
85
+ description: "Normalized hash of the target block's text, from a prior document read."
79
86
  } },
80
87
  required: ["blockTextHash"],
81
88
  additionalProperties: false
@@ -112,7 +119,7 @@ const operationMetaProperties = {
112
119
  type: "string",
113
120
  description: "Optional review area label (e.g. \"Penalty\") for structured-review workflows."
114
121
  },
115
- precondition: preconditionJsonSchema
122
+ precondition: FOLIO_PRECONDITION_JSON_SCHEMA
116
123
  };
117
124
  const blockIdProperty = {
118
125
  type: "string",
@@ -661,4 +668,4 @@ const folioDocumentOperationBatchSchema = {
661
668
  jsonSchema: FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA
662
669
  };
663
670
  //#endregion
664
- export { FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, folioDocumentOperationBatchSchema };
671
+ export { FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, folioDocumentOperationBatchSchema };
package/dist/parse.d.ts CHANGED
@@ -11,6 +11,19 @@ import { FolioAIEditOperation } from "@stll/folio-core/server";
11
11
  */
12
12
  declare const MAX_OPERATIONS_PER_CALL = 50;
13
13
  declare const MAX_OPERATION_TEXT_LENGTH = 100000;
14
+ /**
15
+ * Aggregate cap on the SUM of every text-bearing field's length across one
16
+ * `suggest_changes` call. Each field alone is bounded by
17
+ * {@link MAX_OPERATION_TEXT_LENGTH} and each call by
18
+ * {@link MAX_OPERATIONS_PER_CALL} operations, but an operation can carry
19
+ * several capped fields (e.g. `comment` plus `text`), and a table-insertion
20
+ * operation can carry up to {@link MAX_TABLE_INSERTION_CELL_TEXTS} capped
21
+ * cell texts — so a maximally-shaped batch could still push roughly
22
+ * 50 * 256 * 100,000 ~= 1.28B characters into the tracked-changes engine in
23
+ * one call even though every per-field cap was respected. This budget bounds
24
+ * the running total instead.
25
+ */
26
+ declare const MAX_TOTAL_OPERATION_TEXT_LENGTH = 2000000;
14
27
  /** Plain-language error for a string argument over {@link MAX_OPERATION_TEXT_LENGTH}. */
15
28
  declare const explainTextTooLong: (label: string, length: number) => string;
16
29
  /** Result of {@link parseAddCommentInput}. */
@@ -42,4 +55,4 @@ type ParseSuggestChangesResult = {
42
55
  */
43
56
  declare const parseSuggestChangesInput: (args: unknown) => ParseSuggestChangesResult;
44
57
  //#endregion
45
- export { MAX_OPERATIONS_PER_CALL, MAX_OPERATION_TEXT_LENGTH, ParseAddCommentResult, ParseSuggestChangesResult, explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput };
58
+ export { MAX_OPERATIONS_PER_CALL, MAX_OPERATION_TEXT_LENGTH, MAX_TOTAL_OPERATION_TEXT_LENGTH, ParseAddCommentResult, ParseSuggestChangesResult, explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput };
package/dist/parse.js CHANGED
@@ -12,8 +12,49 @@ const isNonEmptyString = (value) => typeof value === "string" && value.length >
12
12
  const MAX_OPERATIONS_PER_CALL = 50;
13
13
  const MAX_OPERATION_TEXT_LENGTH = 1e5;
14
14
  const MAX_TABLE_INSERTION_CELL_TEXTS = 256;
15
+ /**
16
+ * Aggregate cap on the SUM of every text-bearing field's length across one
17
+ * `suggest_changes` call. Each field alone is bounded by
18
+ * {@link MAX_OPERATION_TEXT_LENGTH} and each call by
19
+ * {@link MAX_OPERATIONS_PER_CALL} operations, but an operation can carry
20
+ * several capped fields (e.g. `comment` plus `text`), and a table-insertion
21
+ * operation can carry up to {@link MAX_TABLE_INSERTION_CELL_TEXTS} capped
22
+ * cell texts — so a maximally-shaped batch could still push roughly
23
+ * 50 * 256 * 100,000 ~= 1.28B characters into the tracked-changes engine in
24
+ * one call even though every per-field cap was respected. This budget bounds
25
+ * the running total instead.
26
+ */
27
+ const MAX_TOTAL_OPERATION_TEXT_LENGTH = 2e6;
15
28
  /** Plain-language error for a string argument over {@link MAX_OPERATION_TEXT_LENGTH}. */
16
29
  const explainTextTooLong = (label, length) => `${label} is ${length.toLocaleString()} characters, over the ${MAX_OPERATION_TEXT_LENGTH.toLocaleString()}-character limit; shorten it or split it into multiple operations.`;
30
+ /** Plain-language error when the running total across all operations exceeds {@link MAX_TOTAL_OPERATION_TEXT_LENGTH}. */
31
+ const explainAggregateTextTooLong = (index) => `operations[${index}] pushes suggest_changes' combined text over the ${MAX_TOTAL_OPERATION_TEXT_LENGTH.toLocaleString()}-character aggregate limit across all operations; split the edit across multiple suggest_changes calls.`;
32
+ /** Normalized text hashes (`hashFolioAIBlockText`) look like `h` followed by base-36 digits. */
33
+ const NORMALIZED_TEXT_HASH_PATTERN = /^h[0-9a-z]+$/;
34
+ /**
35
+ * Parse an optional `precondition: { blockTextHash }` field, present on
36
+ * `add_comment` / `suggest_changes` operation arguments when the caller
37
+ * echoes a `blockTextHash` returned by an earlier `read_document` /
38
+ * `read_section` / `find_text` call. Guards the eventual apply against a
39
+ * document edit made between that read and this call — `execute.ts`
40
+ * otherwise has no way to distinguish "the model never read this block" from
41
+ * "the model read it and it has since changed".
42
+ *
43
+ * Returns `undefined` when omitted, the parsed precondition when valid, or a
44
+ * plain-language error string otherwise.
45
+ */
46
+ const readOperationPrecondition = (value) => {
47
+ if (value === void 0) return;
48
+ if (!isPlainObject(value)) return "`precondition` must be an object when provided.";
49
+ const blockTextHash = value["blockTextHash"];
50
+ if (!isNonEmptyString(blockTextHash) || !NORMALIZED_TEXT_HASH_PATTERN.test(blockTextHash)) return "`precondition.blockTextHash` must be a normalized block text hash, echoed from read_document / read_section / find_text.";
51
+ return { blockTextHash };
52
+ };
53
+ /** Decrement the shared budget by `length`; returns true once the aggregate cap is exceeded. */
54
+ const consumeTextBudget = (budget, length) => {
55
+ budget.remaining -= length;
56
+ return budget.remaining < 0;
57
+ };
17
58
  /**
18
59
  * Validate `add_comment`'s raw tool-call arguments and build the
19
60
  * `commentOnBlock` {@link FolioAIEditOperation} it applies. Pure: does not
@@ -47,6 +88,11 @@ const parseAddCommentInput = (args) => {
47
88
  ok: false,
48
89
  error: explainTextTooLong("add_comment's `quote`", quote.length)
49
90
  };
91
+ const precondition = readOperationPrecondition(args["precondition"]);
92
+ if (typeof precondition === "string") return {
93
+ ok: false,
94
+ error: `add_comment's ${precondition}`
95
+ };
50
96
  return {
51
97
  ok: true,
52
98
  operation: {
@@ -54,7 +100,8 @@ const parseAddCommentInput = (args) => {
54
100
  type: "commentOnBlock",
55
101
  blockId,
56
102
  comment: { text },
57
- ...quote !== void 0 ? { quote } : {}
103
+ ...quote !== void 0 ? { quote } : {},
104
+ ...precondition !== void 0 ? { precondition } : {}
58
105
  }
59
106
  };
60
107
  };
@@ -73,7 +120,7 @@ const readTextRange = (value, index) => {
73
120
  if (!isNonEmptyString(blockId)) return `${path}.blockId must be a non-empty string.`;
74
121
  if (typeof startOffset !== "number" || !Number.isInteger(startOffset) || startOffset < 0) return `${path}.startOffset must be a non-negative integer.`;
75
122
  if (typeof endOffset !== "number" || !Number.isInteger(endOffset) || endOffset <= startOffset) return `${path}.endOffset must be an integer greater than startOffset.`;
76
- if (!isNonEmptyString(selectedTextHash) || !/^h[0-9a-z]+$/.test(selectedTextHash)) return `${path}.selectedTextHash must be a normalized text hash.`;
123
+ if (!isNonEmptyString(selectedTextHash) || !NORMALIZED_TEXT_HASH_PATTERN.test(selectedTextHash)) return `${path}.selectedTextHash must be a normalized text hash.`;
77
124
  return {
78
125
  type,
79
126
  story,
@@ -83,9 +130,26 @@ const readTextRange = (value, index) => {
83
130
  selectedTextHash
84
131
  };
85
132
  };
86
- /** Validate + map one `suggest_changes` operation, or return a plain-language error string. */
87
- const buildSuggestedOperation = (raw, index) => {
133
+ /**
134
+ * Validate + map one `suggest_changes` operation, or return a plain-language
135
+ * error string. Parses the shared `precondition` field itself (every
136
+ * operation variant accepts it, so it does not belong to any one type's
137
+ * branch below) and merges it onto whatever {@link buildSuggestedOperationCore}
138
+ * builds.
139
+ */
140
+ const buildSuggestedOperation = (raw, index, budget) => {
88
141
  if (!isPlainObject(raw)) return `operations[${index}] must be an object.`;
142
+ const precondition = readOperationPrecondition(raw["precondition"]);
143
+ if (typeof precondition === "string") return `operations[${index}] ${precondition}`;
144
+ const built = buildSuggestedOperationCore(raw, index, budget);
145
+ if (typeof built === "string") return built;
146
+ return precondition === void 0 ? built : {
147
+ ...built,
148
+ precondition
149
+ };
150
+ };
151
+ /** Type-and-shape-specific half of {@link buildSuggestedOperation}. */
152
+ const buildSuggestedOperationCore = (raw, index, budget) => {
89
153
  const type = raw["type"];
90
154
  const blockId = raw["blockId"];
91
155
  const id = raw["id"];
@@ -93,7 +157,10 @@ const buildSuggestedOperation = (raw, index) => {
93
157
  if (!isOperationType(type)) return `operations[${index}].type must be one of ${OPERATION_TYPES}.`;
94
158
  if (id !== void 0 && !isNonEmptyString(id)) return `operations[${index}].id must be a non-empty string when provided.`;
95
159
  if (comment !== void 0 && typeof comment !== "string") return `operations[${index}].comment must be a string when provided.`;
96
- if (typeof comment === "string" && comment.length > 1e5) return explainTextTooLong(`operations[${index}].comment`, comment.length);
160
+ if (typeof comment === "string") {
161
+ if (comment.length > 1e5) return explainTextTooLong(`operations[${index}].comment`, comment.length);
162
+ if (consumeTextBudget(budget, comment.length)) return explainAggregateTextTooLong(index);
163
+ }
97
164
  const opId = isNonEmptyString(id) ? id : `op-${index + 1}`;
98
165
  const commentField = typeof comment === "string" ? { comment: { text: comment } } : {};
99
166
  if (type === "replaceRange" || type === "commentOnRange" || type === "formatRange") {
@@ -133,6 +200,7 @@ const buildSuggestedOperation = (raw, index) => {
133
200
  const replace = raw["replace"];
134
201
  if (typeof replace !== "string") return `operations[${index}] (replaceRange) requires a string \`replace\`.`;
135
202
  if (replace.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceRange) \`replace\``, replace.length);
203
+ if (consumeTextBudget(budget, replace.length)) return explainAggregateTextTooLong(index);
136
204
  return {
137
205
  id: opId,
138
206
  type,
@@ -152,6 +220,7 @@ const buildSuggestedOperation = (raw, index) => {
152
220
  for (const [cellIndex, cellText] of (rawCellTexts ?? []).entries()) {
153
221
  if (typeof cellText !== "string") return `operations[${index}] (${type}) \`cellTexts[${cellIndex}]\` must be a string.`;
154
222
  if (cellText.length > 1e5) return explainTextTooLong(`operations[${index}] (${type}) \`cellTexts[${cellIndex}]\``, cellText.length);
223
+ if (consumeTextBudget(budget, cellText.length)) return explainAggregateTextTooLong(index);
155
224
  cellTexts.push(cellText);
156
225
  }
157
226
  return {
@@ -189,8 +258,10 @@ const buildSuggestedOperation = (raw, index) => {
189
258
  const replace = raw["replace"];
190
259
  if (!isNonEmptyString(find)) return `operations[${index}] (replaceInBlock) requires a non-empty string \`find\`.`;
191
260
  if (find.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceInBlock) \`find\``, find.length);
261
+ if (consumeTextBudget(budget, find.length)) return explainAggregateTextTooLong(index);
192
262
  if (typeof replace !== "string") return `operations[${index}] (replaceInBlock) requires a string \`replace\`.`;
193
263
  if (replace.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceInBlock) \`replace\``, replace.length);
264
+ if (consumeTextBudget(budget, replace.length)) return explainAggregateTextTooLong(index);
194
265
  return {
195
266
  id: opId,
196
267
  type,
@@ -204,6 +275,7 @@ const buildSuggestedOperation = (raw, index) => {
204
275
  const text = raw["text"];
205
276
  if (!isNonEmptyString(text)) return `operations[${index}] (${type}) requires a non-empty string \`text\`.`;
206
277
  if (text.length > 1e5) return explainTextTooLong(`operations[${index}] (${type}) \`text\``, text.length);
278
+ if (consumeTextBudget(budget, text.length)) return explainAggregateTextTooLong(index);
207
279
  return {
208
280
  id: opId,
209
281
  type,
@@ -216,6 +288,7 @@ const buildSuggestedOperation = (raw, index) => {
216
288
  const text = raw["text"];
217
289
  if (!isNonEmptyString(text)) return "operations[" + index + "] (replaceBlock) requires a non-empty string `text`.";
218
290
  if (text.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceBlock) \`text\``, text.length);
291
+ if (consumeTextBudget(budget, text.length)) return explainAggregateTextTooLong(index);
219
292
  return {
220
293
  id: opId,
221
294
  type,
@@ -251,8 +324,9 @@ const parseSuggestChangesInput = (args) => {
251
324
  error: `suggest_changes' \`operations\` array has ${rawOperations.length.toLocaleString()} entries, over the 50-operation limit; batch it across multiple suggest_changes calls.`
252
325
  };
253
326
  const operations = [];
327
+ const budget = { remaining: MAX_TOTAL_OPERATION_TEXT_LENGTH };
254
328
  for (const [index, raw] of rawOperations.entries()) {
255
- const built = buildSuggestedOperation(raw, index);
329
+ const built = buildSuggestedOperation(raw, index, budget);
256
330
  if (typeof built === "string") return {
257
331
  ok: false,
258
332
  error: built
@@ -265,4 +339,4 @@ const parseSuggestChangesInput = (args) => {
265
339
  };
266
340
  };
267
341
  //#endregion
268
- export { MAX_OPERATIONS_PER_CALL, MAX_OPERATION_TEXT_LENGTH, explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput };
342
+ export { MAX_OPERATIONS_PER_CALL, MAX_OPERATION_TEXT_LENGTH, MAX_TOTAL_OPERATION_TEXT_LENGTH, explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput };
package/dist/tools.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { FOLIO_AGENT_TOOL_NAMES } from "./types.js";
2
- import { FOLIO_TEXT_RANGE_JSON_SCHEMA } from "./operation-schema.js";
2
+ import { FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA } from "./operation-schema.js";
3
3
  import { FOLIO_DOCUMENT_OPERATION_TYPES } from "@stll/folio-core/server";
4
4
  //#region src/tools.ts
5
5
  const storyHandleSchema = {
@@ -89,10 +89,12 @@ const scopedHandleSchema = {
89
89
  * where the contract requires it;
90
90
  * - `comment` is a plain string here; `parse.ts` wraps it into the contract's
91
91
  * `{ text }` object;
92
- * - the review metadata (`severity`, `area`), `precondition` guard, and the
93
- * insert/replace formatting knobs (`inheritFormatting`, `pageBreakBefore`,
94
- * `preserveFormatting`, `styleId`, `parties`, `quote`,
95
- * except `formatting`) are not exposed to the model.
92
+ * - the review metadata (`severity`, `area`) and the insert/replace
93
+ * formatting knobs (`inheritFormatting`, `pageBreakBefore`,
94
+ * `preserveFormatting`, `styleId`, `parties`, `quote`, except `formatting`)
95
+ * are not exposed to the model. `precondition` IS exposed (see
96
+ * `FOLIO_PRECONDITION_JSON_SCHEMA`) so the model can guard an edit against
97
+ * staleness introduced between an earlier read and this call.
96
98
  */
97
99
  const SUGGEST_CHANGES_EXCLUDED_OPERATION_TYPES = /* @__PURE__ */ new Set(["commentOnBlock", "insertSignatureTable"]);
98
100
  /**
@@ -170,7 +172,8 @@ const suggestChangesOperationSchema = {
170
172
  comment: {
171
173
  type: "string",
172
174
  description: "Optional comment explaining this edit, attached to the affected text, up to 100,000 characters."
173
- }
175
+ },
176
+ precondition: FOLIO_PRECONDITION_JSON_SCHEMA
174
177
  },
175
178
  required: ["type"],
176
179
  additionalProperties: false
@@ -186,7 +189,7 @@ const suggestChangesOperationSchema = {
186
189
  const FOLIO_AGENT_TOOLS = [
187
190
  {
188
191
  name: FOLIO_AGENT_TOOL_NAMES.readDocument,
189
- 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.",
192
+ 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.",
190
193
  inputSchema: {
191
194
  type: "object",
192
195
  properties: {},
@@ -211,7 +214,7 @@ const FOLIO_AGENT_TOOLS = [
211
214
  },
212
215
  {
213
216
  name: FOLIO_AGENT_TOOL_NAMES.readSection,
214
- 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.",
217
+ 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.",
215
218
  inputSchema: {
216
219
  type: "object",
217
220
  properties: {
@@ -253,7 +256,7 @@ const FOLIO_AGENT_TOOLS = [
253
256
  },
254
257
  {
255
258
  name: FOLIO_AGENT_TOOL_NAMES.findText,
256
- description: "Search a document, section, rendered page, or story and return `{ matches, truncated, totalMatches }`. Main-story matches include a stable block and exact range; other stories return story-relative offsets. Every match includes surrounding context. `matches` is capped at 200 entries; `truncated` is true and `totalMatches` reports the real count when there were more — narrow the query or scope instead of assuming you saw every hit.",
259
+ description: "Search a document, section, rendered page, or story and return `{ matches, truncated, totalMatches }`. Main-story matches include a stable block, exact range, and `blockTextHash` (echo it as `precondition.blockTextHash` on a later suggest_changes / add_comment operation); other stories return story-relative offsets. Every match includes surrounding context. `matches` is capped at 200 entries; `truncated` is true and `totalMatches` reports the real count when there were more — narrow the query or scope instead of assuming you saw every hit.",
257
260
  inputSchema: {
258
261
  type: "object",
259
262
  properties: {
@@ -341,7 +344,8 @@ const FOLIO_AGENT_TOOLS = [
341
344
  text: {
342
345
  type: "string",
343
346
  description: "The comment body, up to 100,000 characters."
344
- }
347
+ },
348
+ precondition: FOLIO_PRECONDITION_JSON_SCHEMA
345
349
  },
346
350
  required: ["blockId", "text"],
347
351
  additionalProperties: false
@@ -349,7 +353,7 @@ const FOLIO_AGENT_TOOLS = [
349
353
  },
350
354
  {
351
355
  name: FOLIO_AGENT_TOOL_NAMES.suggestChanges,
352
- description: "Propose one or more edits as tracked changes for a human to accept or reject — nothing is applied directly to the visible text. Each operation needs a blockId from `read_document` or `find_text`; if the document changed since that read, re-read it and retry with fresh ids (a skip reason will say so). At most 50 operations per call — batch larger edits across multiple calls. Each `find` / `replace` / `text` / `comment` string is capped at 100,000 characters.",
356
+ description: "Propose one or more edits as tracked changes for a human to accept or reject — nothing is applied directly to the visible text. Each operation needs a blockId from `read_document` or `find_text`; if the document changed since that read, re-read it and retry with fresh ids (a skip reason will say so). Pass the `blockTextHash` from that read as `precondition.blockTextHash` to guard against the document changing between the read and this call. At most 50 operations per call — batch larger edits across multiple calls. Each `find` / `replace` / `text` / `comment` string is capped at 100,000 characters.",
353
357
  inputSchema: {
354
358
  type: "object",
355
359
  properties: { operations: {
package/dist/types.d.ts CHANGED
@@ -58,6 +58,15 @@ type FolioAgentBlock = {
58
58
  blockId: string;
59
59
  kind: string;
60
60
  text: string;
61
+ /**
62
+ * Normalized-text hash of this block at read time. Echo it back as
63
+ * `precondition.blockTextHash` on a `suggest_changes` / `add_comment`
64
+ * operation targeting this block so the apply call is guarded against
65
+ * edits made to the document between this read and that apply — without
66
+ * it, only same-call staleness within one `suggest_changes` batch is
67
+ * caught.
68
+ */
69
+ blockTextHash: string;
61
70
  };
62
71
  /** One main-story `find_text` match. Existing consumers can keep using its block and range directly. */
63
72
  type FolioAgentTextMatch = {
@@ -65,7 +74,8 @@ type FolioAgentTextMatch = {
65
74
  story?: {
66
75
  type: "main";
67
76
  };
68
- blockId: string; /** Stable handle that can be passed directly to `show_in_document` or a range operation. */
77
+ blockId: string; /** Normalized-text hash of the whole containing block; see {@link FolioAgentBlock.blockTextHash}. */
78
+ blockTextHash: string; /** Stable handle that can be passed directly to `show_in_document` or a range operation. */
69
79
  range: FolioAITextRangeHandle; /** 0-based index of this occurrence within its block. */
70
80
  occurrenceInBlock: number; /** Real rendered page when a live paginated surface supplies it. */
71
81
  page?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/folio-agents",
3
- "version": "0.7.0",
3
+ "version": "0.8.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.6.0"
57
+ "@stll/folio-core": "^0.12.0"
58
58
  },
59
59
  "main": "./dist/index.js",
60
60
  "types": "./dist/index.d.ts"