@stll/folio-agents 0.6.1 → 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.
@@ -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",
@@ -120,7 +127,7 @@ const blockIdProperty = {
120
127
  };
121
128
  /**
122
129
  * JSON Schema (draft-07 compatible) for ONE document operation: the full
123
- * ten-variant union accepted by `parseFolioDocumentOperationBatch` in
130
+ * thirteen-variant union accepted by `parseFolioDocumentOperationBatch` in
124
131
  * `@stll/folio-core`, one `oneOf` variant per entry in
125
132
  * `FOLIO_DOCUMENT_OPERATION_TYPES`. Intended for LLM tool definitions and
126
133
  * other consumers that need the contract's wire shape without re-declaring
@@ -205,7 +212,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
205
212
  },
206
213
  {
207
214
  type: "object",
208
- description: "Apply inline formatting to the text covered by a range handle. Direct mode only (formatting is not representable as a tracked change).",
215
+ description: "Apply inline formatting to the text covered by a range handle in direct or tracked mode.",
209
216
  properties: {
210
217
  ...operationMetaProperties,
211
218
  type: {
@@ -427,6 +434,145 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
427
434
  "parties"
428
435
  ],
429
436
  additionalProperties: false
437
+ },
438
+ {
439
+ type: "object",
440
+ description: "Insert a row next to the row containing the anchor block.",
441
+ properties: {
442
+ ...operationMetaProperties,
443
+ type: {
444
+ type: "string",
445
+ enum: ["insertTableRow"]
446
+ },
447
+ blockId: blockIdProperty,
448
+ position: {
449
+ type: "string",
450
+ enum: ["after", "before"],
451
+ description: "Insert after the anchor row (default) or before it. Defaults to \"after\"."
452
+ },
453
+ cellTexts: {
454
+ type: "array",
455
+ description: "Initial text for physical cells in source order; omitted cells stay empty.",
456
+ items: { type: "string" }
457
+ }
458
+ },
459
+ required: [
460
+ "id",
461
+ "type",
462
+ "blockId"
463
+ ],
464
+ additionalProperties: false
465
+ },
466
+ {
467
+ type: "object",
468
+ description: "Delete the row containing the anchor block.",
469
+ properties: {
470
+ ...operationMetaProperties,
471
+ type: {
472
+ type: "string",
473
+ enum: ["deleteTableRow"]
474
+ },
475
+ blockId: blockIdProperty
476
+ },
477
+ required: [
478
+ "id",
479
+ "type",
480
+ "blockId"
481
+ ],
482
+ additionalProperties: false
483
+ },
484
+ {
485
+ type: "object",
486
+ description: "Insert a column next to the column containing the anchor block.",
487
+ properties: {
488
+ ...operationMetaProperties,
489
+ type: {
490
+ type: "string",
491
+ enum: ["insertTableColumn"]
492
+ },
493
+ blockId: blockIdProperty,
494
+ position: {
495
+ type: "string",
496
+ enum: ["after", "before"],
497
+ description: "Insert after the anchor column (default) or before it. Defaults to \"after\"."
498
+ },
499
+ cellTexts: {
500
+ type: "array",
501
+ description: "Initial text for newly created physical cells in row order.",
502
+ items: { type: "string" }
503
+ }
504
+ },
505
+ required: [
506
+ "id",
507
+ "type",
508
+ "blockId"
509
+ ],
510
+ additionalProperties: false
511
+ },
512
+ {
513
+ type: "object",
514
+ description: "Delete the column containing the anchor block.",
515
+ properties: {
516
+ ...operationMetaProperties,
517
+ type: {
518
+ type: "string",
519
+ enum: ["deleteTableColumn"]
520
+ },
521
+ blockId: blockIdProperty
522
+ },
523
+ required: [
524
+ "id",
525
+ "type",
526
+ "blockId"
527
+ ],
528
+ additionalProperties: false
529
+ },
530
+ {
531
+ type: "object",
532
+ description: "Merge a region targeted by an opposite-cell anchor or a downward row count. Tracked mode supports vertical-only regions with empty continuation cells.",
533
+ properties: {
534
+ ...operationMetaProperties,
535
+ type: {
536
+ type: "string",
537
+ enum: ["mergeTableCells"]
538
+ },
539
+ blockId: blockIdProperty,
540
+ endBlockId: {
541
+ type: "string",
542
+ minLength: 1,
543
+ description: "Stable paragraph anchor inside the opposite corner cell."
544
+ },
545
+ rowCount: {
546
+ type: "integer",
547
+ minimum: 2,
548
+ description: "Number of grid rows to merge downward from the anchored cell."
549
+ }
550
+ },
551
+ required: [
552
+ "id",
553
+ "type",
554
+ "blockId"
555
+ ],
556
+ oneOf: [{ required: ["endBlockId"] }, { required: ["rowCount"] }],
557
+ additionalProperties: false
558
+ },
559
+ {
560
+ type: "object",
561
+ description: "Split one spanned table cell into individual cells. Tracked mode supports vertical-only spans.",
562
+ properties: {
563
+ ...operationMetaProperties,
564
+ type: {
565
+ type: "string",
566
+ enum: ["splitTableCell"]
567
+ },
568
+ blockId: blockIdProperty
569
+ },
570
+ required: [
571
+ "id",
572
+ "type",
573
+ "blockId"
574
+ ],
575
+ additionalProperties: false
430
576
  }
431
577
  ]
432
578
  };
@@ -455,7 +601,7 @@ const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA = {
455
601
  mode: {
456
602
  type: "string",
457
603
  enum: FOLIO_DOCUMENT_OPERATION_MODES,
458
- description: "How edits land: \"tracked-changes\" (default) proposes revisions for human review, \"direct\" applies immediately. `formatRange` and `insertSignatureTable` support \"direct\" only."
604
+ description: "How edits land: \"tracked-changes\" (default) proposes revisions for human review, \"direct\" applies immediately. `insertSignatureTable` supports \"direct\" only. Tracked cell merge and split operations support unambiguous vertical-only topology."
459
605
  },
460
606
  atomic: {
461
607
  type: "boolean",
@@ -522,4 +668,4 @@ const folioDocumentOperationBatchSchema = {
522
668
  jsonSchema: FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA
523
669
  };
524
670
  //#endregion
525
- 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
@@ -11,8 +11,50 @@ const isNonEmptyString = (value) => typeof value === "string" && value.length >
11
11
  */
12
12
  const MAX_OPERATIONS_PER_CALL = 50;
13
13
  const MAX_OPERATION_TEXT_LENGTH = 1e5;
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;
14
28
  /** Plain-language error for a string argument over {@link MAX_OPERATION_TEXT_LENGTH}. */
15
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
+ };
16
58
  /**
17
59
  * Validate `add_comment`'s raw tool-call arguments and build the
18
60
  * `commentOnBlock` {@link FolioAIEditOperation} it applies. Pure: does not
@@ -46,6 +88,11 @@ const parseAddCommentInput = (args) => {
46
88
  ok: false,
47
89
  error: explainTextTooLong("add_comment's `quote`", quote.length)
48
90
  };
91
+ const precondition = readOperationPrecondition(args["precondition"]);
92
+ if (typeof precondition === "string") return {
93
+ ok: false,
94
+ error: `add_comment's ${precondition}`
95
+ };
49
96
  return {
50
97
  ok: true,
51
98
  operation: {
@@ -53,12 +100,13 @@ const parseAddCommentInput = (args) => {
53
100
  type: "commentOnBlock",
54
101
  blockId,
55
102
  comment: { text },
56
- ...quote !== void 0 ? { quote } : {}
103
+ ...quote !== void 0 ? { quote } : {},
104
+ ...precondition !== void 0 ? { precondition } : {}
57
105
  }
58
106
  };
59
107
  };
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";
108
+ const OPERATION_TYPES = "replaceInBlock, replaceRange, commentOnRange, formatRange, insertAfterBlock, insertBeforeBlock, replaceBlock, deleteBlock, insertTableRow, deleteTableRow, insertTableColumn, deleteTableColumn, mergeTableCells, splitTableCell";
109
+ const isOperationType = (value) => value === "replaceInBlock" || value === "replaceRange" || value === "commentOnRange" || value === "formatRange" || value === "insertAfterBlock" || value === "insertBeforeBlock" || value === "replaceBlock" || value === "deleteBlock" || value === "insertTableRow" || value === "deleteTableRow" || value === "insertTableColumn" || value === "deleteTableColumn" || value === "mergeTableCells" || value === "splitTableCell";
62
110
  const readTextRange = (value, index) => {
63
111
  const path = `operations[${index}].range`;
64
112
  if (!isPlainObject(value)) return `${path} must be an object copied from find_text.`;
@@ -72,7 +120,7 @@ const readTextRange = (value, index) => {
72
120
  if (!isNonEmptyString(blockId)) return `${path}.blockId must be a non-empty string.`;
73
121
  if (typeof startOffset !== "number" || !Number.isInteger(startOffset) || startOffset < 0) return `${path}.startOffset must be a non-negative integer.`;
74
122
  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.`;
123
+ if (!isNonEmptyString(selectedTextHash) || !NORMALIZED_TEXT_HASH_PATTERN.test(selectedTextHash)) return `${path}.selectedTextHash must be a normalized text hash.`;
76
124
  return {
77
125
  type,
78
126
  story,
@@ -82,9 +130,26 @@ const readTextRange = (value, index) => {
82
130
  selectedTextHash
83
131
  };
84
132
  };
85
- /** Validate + map one `suggest_changes` operation, or return a plain-language error string. */
86
- 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) => {
87
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) => {
88
153
  const type = raw["type"];
89
154
  const blockId = raw["blockId"];
90
155
  const id = raw["id"];
@@ -92,10 +157,13 @@ const buildSuggestedOperation = (raw, index) => {
92
157
  if (!isOperationType(type)) return `operations[${index}].type must be one of ${OPERATION_TYPES}.`;
93
158
  if (id !== void 0 && !isNonEmptyString(id)) return `operations[${index}].id must be a non-empty string when provided.`;
94
159
  if (comment !== void 0 && typeof comment !== "string") return `operations[${index}].comment must be a string when provided.`;
95
- 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
+ }
96
164
  const opId = isNonEmptyString(id) ? id : `op-${index + 1}`;
97
165
  const commentField = typeof comment === "string" ? { comment: { text: comment } } : {};
98
- if (type === "replaceRange" || type === "commentOnRange") {
166
+ if (type === "replaceRange" || type === "commentOnRange" || type === "formatRange") {
99
167
  const range = readTextRange(raw["range"], index);
100
168
  if (typeof range === "string") return range;
101
169
  if (type === "commentOnRange") {
@@ -107,9 +175,32 @@ const buildSuggestedOperation = (raw, index) => {
107
175
  comment: { text: comment }
108
176
  };
109
177
  }
178
+ if (type === "formatRange") {
179
+ const rawFormatting = raw["formatting"];
180
+ if (!isPlainObject(rawFormatting)) return `operations[${index}] (formatRange) requires a \`formatting\` object.`;
181
+ const formatting = {};
182
+ for (const key of [
183
+ "bold",
184
+ "italic",
185
+ "underline"
186
+ ]) {
187
+ const value = rawFormatting[key];
188
+ if (value === void 0) continue;
189
+ if (typeof value !== "boolean") return `operations[${index}].formatting.${key} must be a boolean when provided.`;
190
+ formatting[key] = value;
191
+ }
192
+ if (Object.keys(formatting).length === 0) return `operations[${index}] (formatRange) requires at least one formatting property.`;
193
+ return {
194
+ id: opId,
195
+ type,
196
+ range,
197
+ formatting
198
+ };
199
+ }
110
200
  const replace = raw["replace"];
111
201
  if (typeof replace !== "string") return `operations[${index}] (replaceRange) requires a string \`replace\`.`;
112
202
  if (replace.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceRange) \`replace\``, replace.length);
203
+ if (consumeTextBudget(budget, replace.length)) return explainAggregateTextTooLong(index);
113
204
  return {
114
205
  id: opId,
115
206
  type,
@@ -119,13 +210,58 @@ const buildSuggestedOperation = (raw, index) => {
119
210
  };
120
211
  }
121
212
  if (!isNonEmptyString(blockId)) return `operations[${index}].blockId must be a non-empty string.`;
213
+ if (type === "insertTableRow" || type === "insertTableColumn") {
214
+ const position = raw["position"];
215
+ if (position !== void 0 && position !== "after" && position !== "before") return `operations[${index}] (${type}) \`position\` must be "after" or "before" when provided.`;
216
+ const rawCellTexts = raw["cellTexts"];
217
+ if (rawCellTexts !== void 0 && !Array.isArray(rawCellTexts)) return `operations[${index}] (${type}) \`cellTexts\` must be an array of strings when provided.`;
218
+ if (rawCellTexts !== void 0 && rawCellTexts.length > MAX_TABLE_INSERTION_CELL_TEXTS) return `operations[${index}] (${type}) \`cellTexts\` has ${rawCellTexts.length.toLocaleString()} entries, over the ${MAX_TABLE_INSERTION_CELL_TEXTS.toLocaleString()}-cell limit.`;
219
+ const cellTexts = [];
220
+ for (const [cellIndex, cellText] of (rawCellTexts ?? []).entries()) {
221
+ if (typeof cellText !== "string") return `operations[${index}] (${type}) \`cellTexts[${cellIndex}]\` must be a string.`;
222
+ if (cellText.length > 1e5) return explainTextTooLong(`operations[${index}] (${type}) \`cellTexts[${cellIndex}]\``, cellText.length);
223
+ if (consumeTextBudget(budget, cellText.length)) return explainAggregateTextTooLong(index);
224
+ cellTexts.push(cellText);
225
+ }
226
+ return {
227
+ id: opId,
228
+ type,
229
+ blockId,
230
+ ...position !== void 0 && { position },
231
+ ...rawCellTexts !== void 0 && { cellTexts }
232
+ };
233
+ }
234
+ if (type === "deleteTableRow" || type === "deleteTableColumn" || type === "splitTableCell") return {
235
+ id: opId,
236
+ type,
237
+ blockId
238
+ };
239
+ if (type === "mergeTableCells") {
240
+ const endBlockId = raw["endBlockId"];
241
+ const rowCount = raw["rowCount"];
242
+ if (isNonEmptyString(endBlockId) && rowCount === void 0) return {
243
+ id: opId,
244
+ type,
245
+ blockId,
246
+ endBlockId
247
+ };
248
+ if (endBlockId === void 0 && typeof rowCount === "number" && Number.isInteger(rowCount) && rowCount >= 2) return {
249
+ id: opId,
250
+ type,
251
+ blockId,
252
+ rowCount
253
+ };
254
+ return `operations[${index}] (mergeTableCells) requires exactly one non-empty \`endBlockId\` or integer \`rowCount\` of at least 2.`;
255
+ }
122
256
  if (type === "replaceInBlock") {
123
257
  const find = raw["find"];
124
258
  const replace = raw["replace"];
125
259
  if (!isNonEmptyString(find)) return `operations[${index}] (replaceInBlock) requires a non-empty string \`find\`.`;
126
260
  if (find.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceInBlock) \`find\``, find.length);
261
+ if (consumeTextBudget(budget, find.length)) return explainAggregateTextTooLong(index);
127
262
  if (typeof replace !== "string") return `operations[${index}] (replaceInBlock) requires a string \`replace\`.`;
128
263
  if (replace.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceInBlock) \`replace\``, replace.length);
264
+ if (consumeTextBudget(budget, replace.length)) return explainAggregateTextTooLong(index);
129
265
  return {
130
266
  id: opId,
131
267
  type,
@@ -139,6 +275,7 @@ const buildSuggestedOperation = (raw, index) => {
139
275
  const text = raw["text"];
140
276
  if (!isNonEmptyString(text)) return `operations[${index}] (${type}) requires a non-empty string \`text\`.`;
141
277
  if (text.length > 1e5) return explainTextTooLong(`operations[${index}] (${type}) \`text\``, text.length);
278
+ if (consumeTextBudget(budget, text.length)) return explainAggregateTextTooLong(index);
142
279
  return {
143
280
  id: opId,
144
281
  type,
@@ -151,6 +288,7 @@ const buildSuggestedOperation = (raw, index) => {
151
288
  const text = raw["text"];
152
289
  if (!isNonEmptyString(text)) return "operations[" + index + "] (replaceBlock) requires a non-empty string `text`.";
153
290
  if (text.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceBlock) \`text\``, text.length);
291
+ if (consumeTextBudget(budget, text.length)) return explainAggregateTextTooLong(index);
154
292
  return {
155
293
  id: opId,
156
294
  type,
@@ -186,8 +324,9 @@ const parseSuggestChangesInput = (args) => {
186
324
  error: `suggest_changes' \`operations\` array has ${rawOperations.length.toLocaleString()} entries, over the 50-operation limit; batch it across multiple suggest_changes calls.`
187
325
  };
188
326
  const operations = [];
327
+ const budget = { remaining: MAX_TOTAL_OPERATION_TEXT_LENGTH };
189
328
  for (const [index, raw] of rawOperations.entries()) {
190
- const built = buildSuggestedOperation(raw, index);
329
+ const built = buildSuggestedOperation(raw, index, budget);
191
330
  if (typeof built === "string") return {
192
331
  ok: false,
193
332
  error: built
@@ -200,4 +339,4 @@ const parseSuggestChangesInput = (args) => {
200
339
  };
201
340
  };
202
341
  //#endregion
203
- 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 = {
@@ -83,23 +83,20 @@ const scopedHandleSchema = {
83
83
  /**
84
84
  * `suggest_changes` deliberately narrows the full document-operation contract
85
85
  * (see `FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA` in `operation-schema.ts`):
86
- * - excluded types: `formatRange` and `insertSignatureTable` (direct-only,
87
- * not representable as tracked changes for human review) and
88
- * `commentOnBlock` (covered by the dedicated `add_comment` tool);
86
+ * - excluded types: `insertSignatureTable` (direct-only) and `commentOnBlock`
87
+ * (covered by the dedicated `add_comment` tool);
89
88
  * - `id` is optional here (auto-generated `op-1`, `op-2`, … by `parse.ts`)
90
89
  * where the contract requires it;
91
90
  * - `comment` is a plain string here; `parse.ts` wraps it into the contract's
92
91
  * `{ text }` object;
93
- * - the review metadata (`severity`, `area`), `precondition` guard, and the
94
- * insert/replace formatting knobs (`inheritFormatting`, `pageBreakBefore`,
95
- * `preserveFormatting`, `styleId`, `position`, `parties`, `quote`,
96
- * `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.
97
98
  */
98
- const SUGGEST_CHANGES_EXCLUDED_OPERATION_TYPES = /* @__PURE__ */ new Set([
99
- "formatRange",
100
- "commentOnBlock",
101
- "insertSignatureTable"
102
- ]);
99
+ const SUGGEST_CHANGES_EXCLUDED_OPERATION_TYPES = /* @__PURE__ */ new Set(["commentOnBlock", "insertSignatureTable"]);
103
100
  /**
104
101
  * The contract operation types `suggest_changes` exposes to the model,
105
102
  * derived from the shared contract constant minus the exclusions above.
@@ -124,9 +121,19 @@ const suggestChangesOperationSchema = {
124
121
  type: "string",
125
122
  description: "The block to edit, from `read_document` or `find_text`."
126
123
  },
124
+ endBlockId: {
125
+ type: "string",
126
+ minLength: 1,
127
+ description: "For cell merging, a block in the opposite corner cell."
128
+ },
129
+ rowCount: {
130
+ type: "integer",
131
+ minimum: 2,
132
+ description: "For vertical cell merging, the number of grid rows to merge downward."
133
+ },
127
134
  range: {
128
135
  ...FOLIO_TEXT_RANGE_JSON_SCHEMA,
129
- description: "Required for `replaceRange` and `commentOnRange`: copy the range object returned by `find_text`."
136
+ description: "Required for `replaceRange`, `commentOnRange`, and `formatRange`: copy the range object returned by `find_text`."
130
137
  },
131
138
  find: {
132
139
  type: "string",
@@ -140,10 +147,33 @@ const suggestChangesOperationSchema = {
140
147
  type: "string",
141
148
  description: "Required for `insertAfterBlock` / `insertBeforeBlock` / `replaceBlock`: the text to insert or replace the block with, up to 100,000 characters."
142
149
  },
150
+ position: {
151
+ type: "string",
152
+ enum: ["after", "before"],
153
+ description: "For row or column insertion, place the new structure after the anchor or before it."
154
+ },
155
+ cellTexts: {
156
+ type: "array",
157
+ description: "For row or column insertion, initial text for new physical cells in source order, up to 100,000 characters per cell.",
158
+ maxItems: 256,
159
+ items: { type: "string" }
160
+ },
161
+ formatting: {
162
+ type: "object",
163
+ description: "Required for `formatRange`: set one or more inline properties to enable or disable.",
164
+ properties: {
165
+ bold: { type: "boolean" },
166
+ italic: { type: "boolean" },
167
+ underline: { type: "boolean" }
168
+ },
169
+ minProperties: 1,
170
+ additionalProperties: false
171
+ },
143
172
  comment: {
144
173
  type: "string",
145
174
  description: "Optional comment explaining this edit, attached to the affected text, up to 100,000 characters."
146
- }
175
+ },
176
+ precondition: FOLIO_PRECONDITION_JSON_SCHEMA
147
177
  },
148
178
  required: ["type"],
149
179
  additionalProperties: false
@@ -159,7 +189,7 @@ const suggestChangesOperationSchema = {
159
189
  const FOLIO_AGENT_TOOLS = [
160
190
  {
161
191
  name: FOLIO_AGENT_TOOL_NAMES.readDocument,
162
- 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.",
163
193
  inputSchema: {
164
194
  type: "object",
165
195
  properties: {},
@@ -184,7 +214,7 @@ const FOLIO_AGENT_TOOLS = [
184
214
  },
185
215
  {
186
216
  name: FOLIO_AGENT_TOOL_NAMES.readSection,
187
- 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.",
188
218
  inputSchema: {
189
219
  type: "object",
190
220
  properties: {
@@ -226,7 +256,7 @@ const FOLIO_AGENT_TOOLS = [
226
256
  },
227
257
  {
228
258
  name: FOLIO_AGENT_TOOL_NAMES.findText,
229
- 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.",
230
260
  inputSchema: {
231
261
  type: "object",
232
262
  properties: {
@@ -289,7 +319,7 @@ const FOLIO_AGENT_TOOLS = [
289
319
  },
290
320
  {
291
321
  name: FOLIO_AGENT_TOOL_NAMES.readChanges,
292
- description: "Read pending tracked changes (insertions and deletions) awaiting human review. Use this to see the effect of edits already suggested via `suggest_changes` before proposing more.",
322
+ description: "Read pending tracked changes awaiting human review. Use this to see the effect of edits already suggested via `suggest_changes` before proposing more.",
293
323
  inputSchema: {
294
324
  type: "object",
295
325
  properties: {},
@@ -314,7 +344,8 @@ const FOLIO_AGENT_TOOLS = [
314
344
  text: {
315
345
  type: "string",
316
346
  description: "The comment body, up to 100,000 characters."
317
- }
347
+ },
348
+ precondition: FOLIO_PRECONDITION_JSON_SCHEMA
318
349
  },
319
350
  required: ["blockId", "text"],
320
351
  additionalProperties: false
@@ -322,7 +353,7 @@ const FOLIO_AGENT_TOOLS = [
322
353
  },
323
354
  {
324
355
  name: FOLIO_AGENT_TOOL_NAMES.suggestChanges,
325
- 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.",
326
357
  inputSchema: {
327
358
  type: "object",
328
359
  properties: { operations: {