@stll/folio-agents 0.9.7 → 0.10.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/parse.js CHANGED
@@ -1,6 +1,19 @@
1
- import { decodeMainStoryTextRangeHandle } from "./codecs.js";
2
- import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, parseFolioDocumentOperationBatch } from "@stll/folio-core/server";
1
+ import { resolveSuggestChangesOptions } from "./suggest-changes-options.js";
2
+ import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, FOLIO_DOCUMENT_OPERATION_KEYS_BY_TYPE, InvalidFolioDocumentOperationBatchError, parseFolioDocumentOperationBatch } from "@stll/folio-core/server";
3
3
  //#region src/parse.ts
4
+ /**
5
+ * Validation-only parsers for `suggest_changes` / `add_comment` tool-call
6
+ * arguments — the canonical rules `execute.ts` runs before handing operations
7
+ * to a {@link FolioAgentBridge}, factored out so a host can validate a
8
+ * model's tool-call arguments with the exact same rules (a host review queue
9
+ * should prefer a queue bridge, see the README, but the parsers stay pure).
10
+ *
11
+ * `parseSuggestChangesInput` is a front door over the contract parser in
12
+ * `@stll/folio-core`, not a second parser: it decodes leniently (reporting
13
+ * every normalisation), enforces the agent-layer caps and the host's
14
+ * {@link FolioSuggestChangesOptions}, mints ids, wraps `comment` strings, and
15
+ * then delegates every per-operation rule to `parseFolioDocumentOperationBatch`.
16
+ */
4
17
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
18
  const isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
6
19
  /**
@@ -10,21 +23,22 @@ const isNonEmptyString = (value) => typeof value === "string" && value.length >
10
23
  * the tracked-changes engine, in one shot. `execute.ts` reuses
11
24
  * {@link MAX_OPERATION_TEXT_LENGTH} for `reply_comment`'s text cap too, so
12
25
  * the limit stays a single number shared across every text-bearing tool.
26
+ * The per-call operation count is a host option
27
+ * (`FolioSuggestChangesOptions.maxOperations`), defaulting to
28
+ * {@link DEFAULT_MAX_OPERATIONS_PER_CALL}.
13
29
  */
14
- const MAX_OPERATIONS_PER_CALL = 50;
15
30
  const MAX_OPERATION_TEXT_LENGTH = 1e5;
16
31
  const MAX_TABLE_INSERTION_CELL_TEXTS = 256;
17
32
  /**
18
33
  * Aggregate cap on the SUM of every text-bearing field's length across one
19
34
  * `suggest_changes` call. Each field alone is bounded by
20
- * {@link MAX_OPERATION_TEXT_LENGTH} and each call by
21
- * {@link MAX_OPERATIONS_PER_CALL} operations, but an operation can carry
22
- * several capped fields (e.g. `comment` plus `text`), and a table-insertion
23
- * operation can carry up to {@link MAX_TABLE_INSERTION_CELL_TEXTS} capped
24
- * cell texts — so a maximally-shaped batch could still push roughly
25
- * 50 * 256 * 100,000 ~= 1.28B characters into the tracked-changes engine in
26
- * one call even though every per-field cap was respected. This budget bounds
27
- * the running total instead.
35
+ * {@link MAX_OPERATION_TEXT_LENGTH} and each call by the operation cap, but
36
+ * an operation can carry several capped fields (e.g. `comment` plus `text`),
37
+ * and a table-insertion operation can carry up to
38
+ * {@link MAX_TABLE_INSERTION_CELL_TEXTS} capped cell texts — so a
39
+ * maximally-shaped batch could still push an unbounded total into the
40
+ * tracked-changes engine in one call even though every per-field cap was
41
+ * respected. This budget bounds the running total instead.
28
42
  */
29
43
  const MAX_TOTAL_OPERATION_TEXT_LENGTH = 2e6;
30
44
  /** Plain-language error for a string argument over {@link MAX_OPERATION_TEXT_LENGTH}. */
@@ -34,15 +48,10 @@ const explainAggregateTextTooLong = (index) => `operations[${index}] pushes sugg
34
48
  /** Normalized text hashes (`hashFolioAIBlockText`) look like `h` followed by base-36 digits. */
35
49
  const NORMALIZED_TEXT_HASH_PATTERN = /^h[0-9a-z]+$/;
36
50
  /**
37
- * Parse an optional `precondition: { blockTextHash }` field, present on
38
- * `add_comment` / `suggest_changes` operation arguments when the caller
39
- * echoes a `blockTextHash` returned by an earlier `read_document` /
40
- * `read_section` / `find_text` call. Guards the eventual apply against a
41
- * document edit made between that read and this call — `execute.ts`
42
- * otherwise has no way to distinguish "the model never read this block" from
43
- * "the model read it and it has since changed".
44
- *
45
- * Returns `undefined` when omitted, the parsed precondition when valid, or a
51
+ * Parse an optional `precondition: { blockTextHash }` field on `add_comment`
52
+ * arguments, present when the caller echoes a `blockTextHash` returned by an
53
+ * earlier `read_document` / `read_section` / `find_text` call. Returns
54
+ * `undefined` when omitted, the parsed precondition when valid, or a
46
55
  * plain-language error string otherwise.
47
56
  */
48
57
  const readOperationPrecondition = (value) => {
@@ -63,12 +72,13 @@ const consumeTextBudget = (budget, length) => {
63
72
  * batch is safe to hand straight to `applyDocumentOperations`; core marks
64
73
  * parsed batches internally so the downstream apply path can skip reparsing.
65
74
  */
66
- const prepareFolioAgentDocumentOperationBatch = ({ operations, mode, atomic, dryRun }) => parseFolioDocumentOperationBatch({
75
+ const prepareFolioAgentDocumentOperationBatch = ({ operations, mode, atomic, dryRun, precondition }) => parseFolioDocumentOperationBatch({
67
76
  version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
68
77
  operations,
69
78
  ...mode !== void 0 && { mode },
70
79
  ...atomic !== void 0 && { atomic },
71
- ...dryRun !== void 0 && { dryRun }
80
+ ...dryRun !== void 0 && { dryRun },
81
+ ...precondition !== void 0 && { precondition }
72
82
  });
73
83
  /**
74
84
  * Validate `add_comment`'s raw tool-call arguments and build the
@@ -120,227 +130,230 @@ const parseAddCommentInput = (args) => {
120
130
  }
121
131
  };
122
132
  };
123
- const OPERATION_TYPES = "replaceInBlock, replaceRange, commentOnRange, formatRange, insertAfterBlock, insertBeforeBlock, replaceBlock, deleteBlock, insertTableRow, deleteTableRow, insertTableColumn, deleteTableColumn, mergeTableCells, splitTableCell";
124
- 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";
125
- const readTextRange = (value, index) => {
126
- const path = `operations[${index}].range`;
127
- if (!isPlainObject(value)) return `${path} must be an object copied from find_text.`;
128
- const range = decodeMainStoryTextRangeHandle(value);
129
- if (range !== null) return range;
130
- if (value["type"] !== "textRange" || value["story"] !== "main") return `${path} must be a main-story textRange copied from find_text.`;
131
- if (!isNonEmptyString(value["blockId"])) return `${path}.blockId must be a non-empty string.`;
132
- if (typeof value["startOffset"] !== "number" || !Number.isInteger(value["startOffset"]) || value["startOffset"] < 0) return `${path}.startOffset must be a non-negative integer.`;
133
- if (typeof value["endOffset"] !== "number" || !Number.isInteger(value["endOffset"]) || value["endOffset"] <= value["startOffset"]) return `${path}.endOffset must be an integer greater than startOffset.`;
134
- if (!isNonEmptyString(value["selectedTextHash"]) || !NORMALIZED_TEXT_HASH_PATTERN.test(value["selectedTextHash"])) return `${path}.selectedTextHash must be a normalized text hash.`;
135
- return `${path} must be copied from find_text.`;
136
- };
133
+ const SUGGEST_CHANGES_ARGUMENT_KEYS = ["operations", "documentVersion"];
134
+ /** String-valued operation fields that count against the text caps. */
135
+ const TEXT_FIELDS = [
136
+ "find",
137
+ "replace",
138
+ "text",
139
+ "quote",
140
+ "styleId",
141
+ "area"
142
+ ];
137
143
  /**
138
- * Validate + map one `suggest_changes` operation, or return a plain-language
139
- * error string. Parses the shared `precondition` field itself (every
140
- * operation variant accepts it, so it does not belong to any one type's
141
- * branch below) and merges it onto whatever {@link buildSuggestedOperationCore}
142
- * builds.
144
+ * Try to read a value the model serialised as a JSON string where an object
145
+ * or array was expected. Returns `undefined` when it is not such a string.
143
146
  */
144
- const buildSuggestedOperation = (raw, index, budget) => {
145
- if (!isPlainObject(raw)) return `operations[${index}] must be an object.`;
146
- const precondition = readOperationPrecondition(raw["precondition"]);
147
- if (typeof precondition === "string") return `operations[${index}] ${precondition}`;
148
- const built = buildSuggestedOperationCore(raw, index, budget);
149
- if (typeof built === "string") return built;
150
- return precondition === void 0 ? built : {
151
- ...built,
152
- precondition
153
- };
147
+ const parseEmbeddedJson = (value) => {
148
+ if (typeof value !== "string") return;
149
+ const trimmed = value.trim();
150
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return;
151
+ try {
152
+ return JSON.parse(trimmed);
153
+ } catch {
154
+ return;
155
+ }
154
156
  };
155
- /** Type-and-shape-specific half of {@link buildSuggestedOperation}. */
156
- const buildSuggestedOperationCore = (raw, index, budget) => {
157
- const type = raw["type"];
158
- const blockId = raw["blockId"];
159
- const id = raw["id"];
160
- const comment = raw["comment"];
161
- if (!isOperationType(type)) return `operations[${index}].type must be one of ${OPERATION_TYPES}.`;
162
- if (id !== void 0 && !isNonEmptyString(id)) return `operations[${index}].id must be a non-empty string when provided.`;
163
- if (comment !== void 0 && typeof comment !== "string") return `operations[${index}].comment must be a string when provided.`;
164
- if (typeof comment === "string") {
165
- if (comment.length > 1e5) return explainTextTooLong(`operations[${index}].comment`, comment.length);
166
- if (consumeTextBudget(budget, comment.length)) return explainAggregateTextTooLong(index);
157
+ /**
158
+ * Lenient decode of the raw arguments: JSON-string envelopes and operations,
159
+ * `kind` for `type`, stray keys. Every normalisation is recorded so the host
160
+ * and the model can see what was tolerated. Shape errors that cannot be
161
+ * normalised come back as a plain-language string.
162
+ */
163
+ const decodeSuggestChangesInput = (rawArgs, options) => {
164
+ const normalizations = [];
165
+ let args = rawArgs;
166
+ const embeddedArgs = parseEmbeddedJson(args);
167
+ if (isPlainObject(embeddedArgs)) {
168
+ normalizations.push({
169
+ path: "$",
170
+ message: "arguments were supplied as a JSON string"
171
+ });
172
+ args = embeddedArgs;
167
173
  }
168
- const opId = isNonEmptyString(id) ? id : `op-${index + 1}`;
169
- const commentField = typeof comment === "string" ? { comment: { text: comment } } : {};
170
- if (type === "replaceRange" || type === "commentOnRange" || type === "formatRange") {
171
- const range = readTextRange(raw["range"], index);
172
- if (typeof range === "string") return range;
173
- if (type === "commentOnRange") {
174
- if (!isNonEmptyString(comment)) return `operations[${index}] (commentOnRange) requires a non-empty string \`comment\`.`;
175
- return {
176
- id: opId,
177
- type,
178
- range,
179
- comment: { text: comment }
180
- };
174
+ if (!isPlainObject(args)) return "suggest_changes requires an `operations` array.";
175
+ for (const key of Object.keys(args)) if (!SUGGEST_CHANGES_ARGUMENT_KEYS.includes(key)) normalizations.push({
176
+ path: key,
177
+ message: `unknown argument \`${key}\` was ignored`
178
+ });
179
+ let rawOperations = args["operations"];
180
+ const embeddedOperations = parseEmbeddedJson(rawOperations);
181
+ if (Array.isArray(embeddedOperations)) {
182
+ normalizations.push({
183
+ path: "operations",
184
+ message: "`operations` was supplied as a JSON string"
185
+ });
186
+ rawOperations = embeddedOperations;
187
+ }
188
+ if (!Array.isArray(rawOperations)) return "suggest_changes requires an `operations` array.";
189
+ if (rawOperations.length === 0) return "suggest_changes' `operations` array must not be empty.";
190
+ if (rawOperations.length > options.maxOperations) return `suggest_changes' \`operations\` array has ${rawOperations.length.toLocaleString()} entries, over the ${options.maxOperations}-operation limit; batch it across multiple suggest_changes calls.`;
191
+ const operations = [];
192
+ for (const [index, rawOperation] of rawOperations.entries()) {
193
+ const path = `operations[${index}]`;
194
+ let operation = rawOperation;
195
+ const embeddedOperation = parseEmbeddedJson(operation);
196
+ if (isPlainObject(embeddedOperation)) {
197
+ normalizations.push({
198
+ path,
199
+ message: "operation was supplied as a JSON string"
200
+ });
201
+ operation = embeddedOperation;
181
202
  }
182
- if (type === "formatRange") {
183
- const rawFormatting = raw["formatting"];
184
- if (!isPlainObject(rawFormatting)) return `operations[${index}] (formatRange) requires a \`formatting\` object.`;
185
- const formatting = {};
186
- for (const key of [
187
- "bold",
188
- "italic",
189
- "underline"
190
- ]) {
191
- const value = rawFormatting[key];
192
- if (value === void 0) continue;
193
- if (typeof value !== "boolean") return `operations[${index}].formatting.${key} must be a boolean when provided.`;
194
- formatting[key] = value;
195
- }
196
- if (Object.keys(formatting).length === 0) return `operations[${index}] (formatRange) requires at least one formatting property.`;
197
- return {
198
- id: opId,
199
- type,
200
- range,
201
- formatting
202
- };
203
+ if (!isPlainObject(operation)) return `${path} must be an object.`;
204
+ let type = operation["type"];
205
+ let typeKey = "type";
206
+ if (type === void 0 && typeof operation["kind"] === "string") {
207
+ normalizations.push({
208
+ path: `${path}.kind`,
209
+ message: "`kind` was read as `type`"
210
+ });
211
+ type = operation["kind"];
212
+ typeKey = "kind";
203
213
  }
204
- const replace = raw["replace"];
205
- if (typeof replace !== "string") return `operations[${index}] (replaceRange) requires a string \`replace\`.`;
206
- if (replace.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceRange) \`replace\``, replace.length);
207
- if (consumeTextBudget(budget, replace.length)) return explainAggregateTextTooLong(index);
208
- return {
209
- id: opId,
210
- type,
211
- range,
212
- replace,
213
- ...commentField
214
- };
215
- }
216
- if (!isNonEmptyString(blockId)) return `operations[${index}].blockId must be a non-empty string.`;
217
- if (type === "insertTableRow" || type === "insertTableColumn") {
218
- const position = raw["position"];
219
- if (position !== void 0 && position !== "after" && position !== "before") return `operations[${index}] (${type}) \`position\` must be "after" or "before" when provided.`;
220
- const rawCellTexts = raw["cellTexts"];
221
- if (rawCellTexts !== void 0 && !Array.isArray(rawCellTexts)) return `operations[${index}] (${type}) \`cellTexts\` must be an array of strings when provided.`;
222
- 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.`;
223
- const cellTexts = [];
224
- for (const [cellIndex, cellText] of (rawCellTexts ?? []).entries()) {
225
- if (typeof cellText !== "string") return `operations[${index}] (${type}) \`cellTexts[${cellIndex}]\` must be a string.`;
226
- if (cellText.length > 1e5) return explainTextTooLong(`operations[${index}] (${type}) \`cellTexts[${cellIndex}]\``, cellText.length);
227
- if (consumeTextBudget(budget, cellText.length)) return explainAggregateTextTooLong(index);
228
- cellTexts.push(cellText);
214
+ if (!isAllowedOperationType(type, options)) return `${path}.type must be one of ${options.operationTypes.join(", ")}.`;
215
+ const allowedKeys = FOLIO_DOCUMENT_OPERATION_KEYS_BY_TYPE[type];
216
+ const decoded = { type };
217
+ for (const [key, value] of Object.entries(operation)) {
218
+ if (key === typeKey) continue;
219
+ if (allowedKeys.includes(key)) {
220
+ decoded[key] = value;
221
+ continue;
222
+ }
223
+ normalizations.push({
224
+ path: `${path}.${key}`,
225
+ message: `\`${key}\` does not apply to ${type} and was ignored`
226
+ });
229
227
  }
230
- return {
231
- id: opId,
232
- type,
233
- blockId,
234
- ...position !== void 0 && { position },
235
- ...rawCellTexts !== void 0 && { cellTexts }
236
- };
228
+ operations.push(decoded);
237
229
  }
238
- if (type === "deleteTableRow" || type === "deleteTableColumn" || type === "splitTableCell") return {
239
- id: opId,
240
- type,
241
- blockId
230
+ return {
231
+ operations,
232
+ documentVersion: args["documentVersion"],
233
+ normalizations
242
234
  };
243
- if (type === "mergeTableCells") {
244
- const endBlockId = raw["endBlockId"];
245
- const rowCount = raw["rowCount"];
246
- if (isNonEmptyString(endBlockId) && rowCount === void 0) return {
247
- id: opId,
248
- type,
249
- blockId,
250
- endBlockId
251
- };
252
- if (endBlockId === void 0 && typeof rowCount === "number" && Number.isInteger(rowCount) && rowCount >= 2) return {
253
- id: opId,
254
- type,
255
- blockId,
256
- rowCount
257
- };
258
- return `operations[${index}] (mergeTableCells) requires exactly one non-empty \`endBlockId\` or integer \`rowCount\` of at least 2.`;
259
- }
260
- if (type === "replaceInBlock") {
261
- const find = raw["find"];
262
- const replace = raw["replace"];
263
- if (!isNonEmptyString(find)) return `operations[${index}] (replaceInBlock) requires a non-empty string \`find\`.`;
264
- if (find.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceInBlock) \`find\``, find.length);
265
- if (consumeTextBudget(budget, find.length)) return explainAggregateTextTooLong(index);
266
- if (typeof replace !== "string") return `operations[${index}] (replaceInBlock) requires a string \`replace\`.`;
267
- if (replace.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceInBlock) \`replace\``, replace.length);
268
- if (consumeTextBudget(budget, replace.length)) return explainAggregateTextTooLong(index);
269
- return {
270
- id: opId,
271
- type,
272
- blockId,
273
- find,
274
- replace,
275
- ...commentField
276
- };
235
+ };
236
+ const isAllowedOperationType = (value, options) => typeof value === "string" && options.operationTypes.includes(value) && Object.hasOwn(FOLIO_DOCUMENT_OPERATION_KEYS_BY_TYPE, value);
237
+ /** Enforce the per-field and aggregate text caps on one decoded operation, or explain the breach. */
238
+ const checkTextCaps = (operation, index, budget) => {
239
+ const label = (field) => `operations[${index}].${field}`;
240
+ const charge = (field, value) => {
241
+ if (typeof value !== "string") return;
242
+ if (value.length > 1e5) return explainTextTooLong(label(field), value.length);
243
+ return consumeTextBudget(budget, value.length) ? explainAggregateTextTooLong(index) : void 0;
244
+ };
245
+ for (const field of TEXT_FIELDS) {
246
+ const breach = charge(field, operation[field]);
247
+ if (breach !== void 0) return breach;
277
248
  }
278
- if (type === "insertAfterBlock" || type === "insertBeforeBlock") {
279
- const text = raw["text"];
280
- if (!isNonEmptyString(text)) return `operations[${index}] (${type}) requires a non-empty string \`text\`.`;
281
- if (text.length > 1e5) return explainTextTooLong(`operations[${index}] (${type}) \`text\``, text.length);
282
- if (consumeTextBudget(budget, text.length)) return explainAggregateTextTooLong(index);
283
- return {
284
- id: opId,
285
- type,
286
- blockId,
287
- text,
288
- ...commentField
289
- };
249
+ const comment = operation["comment"];
250
+ const commentBreach = charge("comment", isPlainObject(comment) ? comment["text"] : comment);
251
+ if (commentBreach !== void 0) return commentBreach;
252
+ const cellTexts = operation["cellTexts"];
253
+ if (Array.isArray(cellTexts)) {
254
+ if (cellTexts.length > MAX_TABLE_INSERTION_CELL_TEXTS) return `${label("cellTexts")} has ${cellTexts.length.toLocaleString()} entries, over the ${MAX_TABLE_INSERTION_CELL_TEXTS.toLocaleString()}-cell limit.`;
255
+ for (const [cellIndex, cellText] of cellTexts.entries()) {
256
+ const breach = charge(`cellTexts[${cellIndex}]`, cellText);
257
+ if (breach !== void 0) return breach;
258
+ }
290
259
  }
291
- if (type === "replaceBlock") {
292
- const text = raw["text"];
293
- if (!isNonEmptyString(text)) return "operations[" + index + "] (replaceBlock) requires a non-empty string `text`.";
294
- if (text.length > 1e5) return explainTextTooLong(`operations[${index}] (replaceBlock) \`text\``, text.length);
295
- if (consumeTextBudget(budget, text.length)) return explainAggregateTextTooLong(index);
296
- return {
297
- id: opId,
298
- type,
299
- blockId,
300
- text,
301
- ...commentField
302
- };
260
+ const parties = operation["parties"];
261
+ if (Array.isArray(parties)) for (const [partyIndex, party] of parties.entries()) {
262
+ if (!isPlainObject(party)) continue;
263
+ for (const field of [
264
+ "name",
265
+ "signatory",
266
+ "title"
267
+ ]) {
268
+ const breach = charge(`parties[${partyIndex}].${field}`, party[field]);
269
+ if (breach !== void 0) return breach;
270
+ }
303
271
  }
304
- return {
305
- id: opId,
306
- type,
307
- blockId,
308
- ...commentField
309
- };
272
+ };
273
+ /**
274
+ * Ids minted for operations the model left unnamed. The per-call UUID keeps
275
+ * them unique across calls so a host queue can key on them without
276
+ * rewriting; the index keeps them readable in the model's own output.
277
+ */
278
+ const mintOperationIdPrefix = () => `op-${crypto.randomUUID()}`;
279
+ /** Turn a contract-parser failure into the model-facing message shape (`operations[0].find: expected a string.`). */
280
+ const explainContractError = (error) => {
281
+ if (error instanceof InvalidFolioDocumentOperationBatchError) return `${error.path.replace(/^\$\.?/, "")}: ${error.reason}.`;
282
+ return error instanceof Error ? error.message : String(error);
310
283
  };
311
284
  /**
312
285
  * Validate `suggest_changes`' raw tool-call arguments and build the
313
286
  * {@link FolioAIEditOperation}s it applies. Pure: does not touch a bridge or
314
- * document.
287
+ * document. `options` must match the {@link FolioSuggestChangesOptions} the
288
+ * tool definition was built with.
315
289
  */
316
- const parseSuggestChangesInput = (args) => {
317
- if (!isPlainObject(args) || !Array.isArray(args["operations"])) return {
318
- ok: false,
319
- error: "suggest_changes requires an `operations` array."
320
- };
321
- const rawOperations = args["operations"];
322
- if (rawOperations.length === 0) return {
323
- ok: false,
324
- error: "suggest_changes' `operations` array must not be empty."
325
- };
326
- if (rawOperations.length > 50) return {
290
+ const parseSuggestChangesInput = (args, options) => {
291
+ const resolved = resolveSuggestChangesOptions(options);
292
+ const decoded = decodeSuggestChangesInput(args, resolved);
293
+ if (typeof decoded === "string") return {
327
294
  ok: false,
328
- error: `suggest_changes' \`operations\` array has ${rawOperations.length.toLocaleString()} entries, over the 50-operation limit; batch it across multiple suggest_changes calls.`
295
+ error: decoded
329
296
  };
330
- const operations = [];
297
+ let precondition;
298
+ if (resolved.documentVersion !== null) {
299
+ if (!isNonEmptyString(decoded.documentVersion)) return {
300
+ ok: false,
301
+ error: "suggest_changes requires `documentVersion`: copy the current document version from the tool schema."
302
+ };
303
+ precondition = { documentVersion: decoded.documentVersion };
304
+ } else if (decoded.documentVersion !== void 0) decoded.normalizations.push({
305
+ path: "documentVersion",
306
+ message: "`documentVersion` is not pinned on this surface and was ignored"
307
+ });
331
308
  const budget = { remaining: MAX_TOTAL_OPERATION_TEXT_LENGTH };
332
- for (const [index, raw] of rawOperations.entries()) {
333
- const built = buildSuggestedOperation(raw, index, budget);
334
- if (typeof built === "string") return {
309
+ const idPrefix = mintOperationIdPrefix();
310
+ const prepared = [];
311
+ for (const [index, operation] of decoded.operations.entries()) {
312
+ const breach = checkTextCaps(operation, index, budget);
313
+ if (breach !== void 0) return {
314
+ ok: false,
315
+ error: breach
316
+ };
317
+ if (resolved.reviewMeta === "required") {
318
+ if (operation["severity"] === void 0) return {
319
+ ok: false,
320
+ error: `operations[${index}].severity is required on this surface ("low", "medium", or "high").`
321
+ };
322
+ if (!isNonEmptyString(operation["area"])) return {
323
+ ok: false,
324
+ error: `operations[${index}].area is required on this surface: a short review area label.`
325
+ };
326
+ }
327
+ const id = operation["id"];
328
+ if (id !== void 0 && !isNonEmptyString(id)) return {
335
329
  ok: false,
336
- error: built
330
+ error: `operations[${index}].id must be a non-empty string when provided.`
331
+ };
332
+ const comment = operation["comment"];
333
+ prepared.push({
334
+ ...operation,
335
+ id: id ?? `${idPrefix}-${index + 1}`,
336
+ ...typeof comment === "string" && { comment: { text: comment } }
337
+ });
338
+ }
339
+ try {
340
+ const batch = parseFolioDocumentOperationBatch({
341
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
342
+ operations: prepared,
343
+ ...precondition !== void 0 && { precondition }
344
+ });
345
+ return {
346
+ ok: true,
347
+ operations: [...batch.operations],
348
+ ...batch.precondition !== void 0 && { precondition: batch.precondition },
349
+ normalizations: decoded.normalizations
350
+ };
351
+ } catch (error) {
352
+ return {
353
+ ok: false,
354
+ error: explainContractError(error)
337
355
  };
338
- operations.push(built);
339
356
  }
340
- return {
341
- ok: true,
342
- operations
343
- };
344
357
  };
345
358
  //#endregion
346
- export { MAX_OPERATIONS_PER_CALL, MAX_OPERATION_TEXT_LENGTH, MAX_TOTAL_OPERATION_TEXT_LENGTH, explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput, prepareFolioAgentDocumentOperationBatch };
359
+ export { MAX_OPERATION_TEXT_LENGTH, MAX_TOTAL_OPERATION_TEXT_LENGTH, explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput, prepareFolioAgentDocumentOperationBatch };
@@ -0,0 +1,60 @@
1
+ import { FolioDocumentOperationType } from "@stll/folio-core/server";
2
+ //#region src/suggest-changes-options.d.ts
3
+ /** Whether every operation must carry `severity` and `area`. */
4
+ type FolioSuggestChangesReviewMetaPolicy = "optional" | "required";
5
+ /**
6
+ * Pin the batch to a host document version. The model must echo `current`
7
+ * as the tool's top-level `documentVersion` argument; it lands on the batch
8
+ * as `precondition.documentVersion`, and the executor skips the whole batch
9
+ * with `documentVersionMismatch` when the bridge reports a different version
10
+ * at apply time (an approval that ran after the document moved on).
11
+ */
12
+ type FolioSuggestChangesDocumentVersionOption = {
13
+ current: string;
14
+ };
15
+ /**
16
+ * Per-surface shape of the `suggest_changes` tool. Pass the same object to
17
+ * `getFolioToolDefinitions` and `executeFolioToolCall` so the schema the
18
+ * model sees and the parser that checks its calls agree.
19
+ */
20
+ type FolioSuggestChangesOptions = {
21
+ /**
22
+ * Operation types the model may emit, in any order. Defaults to every
23
+ * contract type except `commentOnBlock` (covered by `add_comment`) and
24
+ * `insertSignatureTable` (direct-only, so not a tracked change).
25
+ */
26
+ operationTypes?: readonly FolioDocumentOperationType[];
27
+ /** Defaults to `"optional"`. */
28
+ reviewMeta?: FolioSuggestChangesReviewMetaPolicy;
29
+ /** Operations accepted per call, 1 to 200. Defaults to 50. */
30
+ maxOperations?: number;
31
+ documentVersion?: FolioSuggestChangesDocumentVersionOption;
32
+ };
33
+ /**
34
+ * Per-surface configuration shared by `getFolioToolDefinitions` and
35
+ * `executeFolioToolCall`; every tool but `suggest_changes` is fixed.
36
+ */
37
+ type FolioAgentToolOptions = {
38
+ suggestChanges?: FolioSuggestChangesOptions;
39
+ };
40
+ type ResolvedFolioSuggestChangesOptions = {
41
+ /** Allowed types in contract order, deduplicated. */
42
+ readonly operationTypes: readonly FolioDocumentOperationType[];
43
+ readonly reviewMeta: FolioSuggestChangesReviewMetaPolicy;
44
+ readonly maxOperations: number;
45
+ readonly documentVersion: FolioSuggestChangesDocumentVersionOption | null;
46
+ };
47
+ /** The operation types `suggest_changes` exposes when a host passes no `operationTypes`. */
48
+ declare const DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES: readonly FolioDocumentOperationType[];
49
+ declare const DEFAULT_MAX_OPERATIONS_PER_CALL = 50;
50
+ declare const MAX_OPERATIONS_PER_CALL_LIMIT = 200;
51
+ declare const InvalidFolioSuggestChangesOptionsError_base: import("better-result").TaggedErrorClass<"InvalidFolioSuggestChangesOptionsError">;
52
+ /** Programmer misuse of {@link FolioSuggestChangesOptions}; never reaches the model. */
53
+ declare class InvalidFolioSuggestChangesOptionsError extends InvalidFolioSuggestChangesOptionsError_base<{
54
+ message: string;
55
+ option: keyof FolioSuggestChangesOptions;
56
+ }> {}
57
+ /** Validate and default a host's options; throws {@link InvalidFolioSuggestChangesOptionsError} on misuse. */
58
+ declare const resolveSuggestChangesOptions: (options?: FolioSuggestChangesOptions) => ResolvedFolioSuggestChangesOptions;
59
+ //#endregion
60
+ export { DEFAULT_MAX_OPERATIONS_PER_CALL, DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, FolioAgentToolOptions, FolioSuggestChangesDocumentVersionOption, FolioSuggestChangesOptions, FolioSuggestChangesReviewMetaPolicy, InvalidFolioSuggestChangesOptionsError, MAX_OPERATIONS_PER_CALL_LIMIT, ResolvedFolioSuggestChangesOptions, resolveSuggestChangesOptions };
@@ -0,0 +1,52 @@
1
+ import { FOLIO_DOCUMENT_OPERATION_TYPES } from "@stll/folio-core/server";
2
+ import { TaggedError } from "better-result";
3
+ //#region src/suggest-changes-options.ts
4
+ /**
5
+ * Host-facing configuration of the `suggest_changes` tool. One resolved
6
+ * options object drives the tool's JSON Schema (`tools.ts`), its parser
7
+ * (`parse.ts`), and its capability description, so a host that needs a
8
+ * narrower or stricter surface configures instead of re-deriving the
9
+ * contract.
10
+ */
11
+ const DEFAULT_EXCLUDED_OPERATION_TYPES = /* @__PURE__ */ new Set(["commentOnBlock", "insertSignatureTable"]);
12
+ /** The operation types `suggest_changes` exposes when a host passes no `operationTypes`. */
13
+ const DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES = FOLIO_DOCUMENT_OPERATION_TYPES.filter((type) => !DEFAULT_EXCLUDED_OPERATION_TYPES.has(type));
14
+ const DEFAULT_MAX_OPERATIONS_PER_CALL = 50;
15
+ const MAX_OPERATIONS_PER_CALL_LIMIT = 200;
16
+ /** Programmer misuse of {@link FolioSuggestChangesOptions}; never reaches the model. */
17
+ var InvalidFolioSuggestChangesOptionsError = class extends TaggedError("InvalidFolioSuggestChangesOptionsError") {};
18
+ const invalidOption = (option, message) => {
19
+ throw new InvalidFolioSuggestChangesOptionsError({
20
+ message: `Invalid suggest_changes option \`${option}\`: ${message}.`,
21
+ option
22
+ });
23
+ };
24
+ const isContractOperationType = (value) => typeof value === "string" && FOLIO_DOCUMENT_OPERATION_TYPES.includes(value);
25
+ const resolveOperationTypes = (requested) => {
26
+ if (requested === void 0) return DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES;
27
+ if (!Array.isArray(requested)) return invalidOption("operationTypes", "expected an array of operation types");
28
+ if (requested.length === 0) return invalidOption("operationTypes", "expected at least one operation type");
29
+ const unknown = requested.find((type) => !isContractOperationType(type));
30
+ if (unknown !== void 0) return invalidOption("operationTypes", `"${String(unknown)}" is not a contract operation type`);
31
+ const wanted = new Set(requested);
32
+ return FOLIO_DOCUMENT_OPERATION_TYPES.filter((type) => wanted.has(type));
33
+ };
34
+ const resolveMaxOperations = (requested) => {
35
+ if (requested === void 0) return 50;
36
+ if (!Number.isInteger(requested) || requested < 1 || requested > 200) return invalidOption("maxOperations", `expected an integer from 1 to 200`);
37
+ return requested;
38
+ };
39
+ const resolveDocumentVersion = (requested) => {
40
+ if (requested === void 0) return null;
41
+ if (typeof requested !== "object" || requested === null || typeof requested.current !== "string" || requested.current.length === 0) return invalidOption("documentVersion", "expected a non-empty `current` version token");
42
+ return { current: requested.current };
43
+ };
44
+ /** Validate and default a host's options; throws {@link InvalidFolioSuggestChangesOptionsError} on misuse. */
45
+ const resolveSuggestChangesOptions = (options = {}) => ({
46
+ operationTypes: resolveOperationTypes(options.operationTypes),
47
+ reviewMeta: options.reviewMeta ?? "optional",
48
+ maxOperations: resolveMaxOperations(options.maxOperations),
49
+ documentVersion: resolveDocumentVersion(options.documentVersion)
50
+ });
51
+ //#endregion
52
+ export { DEFAULT_MAX_OPERATIONS_PER_CALL, DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, InvalidFolioSuggestChangesOptionsError, MAX_OPERATIONS_PER_CALL_LIMIT, resolveSuggestChangesOptions };