@stll/folio-agents 0.9.8 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -114,30 +114,99 @@ returns `[]`, comment entries fall back to `blockId: null` / `quote: ""`, and
114
114
  `read_page` / `read_selection` report an unsupported-capability error — see
115
115
  `src/bridges/editor-ref.ts` for the exact fallback per method.
116
116
 
117
+ ### Configuring `suggest_changes`
118
+
119
+ `suggest_changes` is a projection of the document-operation contract that a
120
+ host configures per surface instead of re-deriving. Pass the same options to
121
+ `getFolioToolDefinitions` (they shape the JSON Schema the model sees) and to
122
+ `executeFolioToolCall` (they drive the parser), so the two cannot drift:
123
+
124
+ ```ts
125
+ import {
126
+ describeSuggestChangesCapabilities,
127
+ executeFolioToolCall,
128
+ getFolioToolDefinitions,
129
+ type FolioSuggestChangesOptions,
130
+ } from "@stll/folio-agents";
131
+
132
+ const suggestChanges: FolioSuggestChangesOptions = {
133
+ // Any subset of the contract types, e.g. a text-only surface:
134
+ operationTypes: ["replaceInBlock", "replaceBlock", "deleteBlock"],
135
+ // Force `severity` and `area` on every operation for a review queue:
136
+ reviewMeta: "required",
137
+ // Per-call cap, 1 to 200 (default 50):
138
+ maxOperations: 200,
139
+ // Pin the batch to a host document version the model must echo back:
140
+ documentVersion: { current: entityVersionId },
141
+ };
142
+
143
+ const tools = getFolioToolDefinitions({ suggestChanges });
144
+ const result = executeFolioToolCall("suggest_changes", args, bridge, { suggestChanges });
145
+ // `describeSuggestChangesCapabilities({ ...suggestChanges })` returns the same
146
+ // capability text the tool description carries, for reuse in a system prompt.
147
+ ```
148
+
149
+ Defaults: every contract type except `commentOnBlock` (use `add_comment`) and
150
+ `insertSignatureTable` (direct-only, so never a tracked change); review
151
+ metadata optional; 50 operations per call; no version pin. The schema
152
+ advertises only the properties the allowed types accept, derived from
153
+ `FOLIO_DOCUMENT_OPERATION_KEYS_BY_TYPE` in `@stll/folio-core`.
154
+
155
+ The parser is a front door over the contract parser, not a second parser. It
156
+ decodes leniently first (a `kind` key read as `type`, an operation supplied as
157
+ a JSON string, a property that does not apply to the operation type) and
158
+ reports every such step in the result's `normalizations`, then enforces the
159
+ caps and the options above, mints ids that stay unique across calls
160
+ (`op-<nonce>-<n>`), wraps plain-string `comment`s, and hands the batch to
161
+ `parseFolioDocumentOperationBatch`.
162
+
163
+ With `documentVersion` set, the batch carries `precondition.documentVersion`
164
+ and the executor compares it to the bridge's `getDocumentVersion()` before
165
+ anything is applied: a mismatch skips every operation with
166
+ `documentVersionMismatch`, and a bridge without `getDocumentVersion` refuses
167
+ version-pinned batches instead of guessing.
168
+
117
169
  ### Host-managed review queue
118
170
 
119
171
  A host with its own review-queue UX (its own place to store proposed edits
120
- pending approval, distinct from folio's tracked-changes redlines) can validate
121
- a model's `suggest_changes` / `add_comment` tool-call arguments with the same
122
- canonical rules `executeFolioToolCall` uses, without applying them through a
123
- bridge at all:
172
+ pending approval, distinct from folio's tracked-changes redlines) implements
173
+ `FolioAgentBridge` with an `applyDocumentOperations` that enqueues instead of
174
+ applying and reports the operations as `queued`. The executor then returns
175
+ the same envelope the model gets everywhere else, receipts and skip prose
176
+ included, and the host keeps the automatic `precondition` stamping and the
177
+ document-version check:
124
178
 
125
179
  ```ts
126
- import { parseSuggestChangesInput } from "@stll/folio-agents";
127
-
128
- const parsed = parseSuggestChangesInput(toolInput);
129
- if (!parsed.ok) {
130
- // Feed `parsed.error` back to the model as the tool result, same as
131
- // executeFolioToolCall would.
132
- } else {
133
- // `parsed.operations` is FolioAIEditOperation[] — route it into your own
134
- // review queue instead of bridge.applyDocumentOperations(...).
135
- reviewQueue.enqueue(parsed.operations);
136
- }
180
+ import { getFolioDocumentOperationReceipts } from "@stll/folio-core/server";
181
+ import type { FolioAgentBridge } from "@stll/folio-agents";
182
+
183
+ const queueBridge: FolioAgentBridge = {
184
+ snapshot: () => lastSnapshotShownToTheModel,
185
+ getDocumentVersion: () => currentEntityVersionId,
186
+ applyDocumentOperations: (batch) => {
187
+ const queued = batch.operations.map(({ id }) => ({ id }));
188
+ reviewQueue.enqueue(batch.operations);
189
+ return {
190
+ version: batch.version,
191
+ status: "queued",
192
+ applied: [],
193
+ queued,
194
+ skipped: [],
195
+ issues: [],
196
+ receipts: getFolioDocumentOperationReceipts(batch.operations, queued),
197
+ undoHandle: null,
198
+ };
199
+ },
200
+ getComments: () => [],
201
+ getChanges: () => [],
202
+ replyToComment: () => false,
203
+ resolveComment: () => false,
204
+ };
137
205
  ```
138
206
 
139
- `parseAddCommentInput` is the equivalent for `add_comment`, returning
140
- `{ ok: true; operation }` on success.
207
+ A surface with no editable document at the moment reports every operation as
208
+ skipped with `documentNotEditable` instead. `parseSuggestChangesInput` and
209
+ `parseAddCommentInput` remain exported for a host that only needs validation.
141
210
 
142
211
  ## Summarizing changes
143
212
 
package/dist/bridge.d.ts CHANGED
@@ -31,6 +31,15 @@ type FolioAgentBridge = {
31
31
  applyDocumentOperations(batch: FolioDocumentOperationBatch): FolioDocumentOperationResult;
32
32
  /** Undo the latest unchanged batch when the execution surface supports it. */
33
33
  undoDocumentOperations?(undoHandle: FolioDocumentOperationUndoHandle): FolioDocumentOperationUndoResult;
34
+ /**
35
+ * The host's opaque version token for the document this bridge holds (an
36
+ * entity version id, a collaboration checkpoint). When a `suggest_changes`
37
+ * batch carries `precondition.documentVersion`, the executor compares it
38
+ * to this value before applying and skips the whole batch with
39
+ * `documentVersionMismatch` on a difference. Omit on a surface without a
40
+ * version notion; such a surface then refuses version-pinned batches.
41
+ */
42
+ getDocumentVersion?(): string;
34
43
  /** The comment threads present in the document. */
35
44
  getComments(): FolioAgentComment[];
36
45
  /** The pending tracked changes (insertions/deletions) present in the document. */
package/dist/execute.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { FolioAgentToolName, FolioToolCallResult } from "./types.js";
2
2
  import { FolioAgentBridge } from "./bridge.js";
3
+ import { FolioAgentToolOptions } from "./suggest-changes-options.js";
3
4
  import { FolioAgentToolInputByName, FolioToolCallResultFor } from "./tool-contract.js";
4
5
  //#region src/execute.d.ts
5
6
  /**
@@ -14,7 +15,7 @@ import { FolioAgentToolInputByName, FolioToolCallResultFor } from "./tool-contra
14
15
  * Every bridge member used here ({@link FolioDocxReviewer} and the live-editor
15
16
  * ref) is synchronous, so this stays synchronous too.
16
17
  */
17
- declare const executeFolioToolCallUntyped: (name: string, args: unknown, bridge: FolioAgentBridge) => FolioToolCallResult;
18
- declare function executeFolioToolCall<TName extends FolioAgentToolName>(name: TName, args: FolioAgentToolInputByName[TName], bridge: FolioAgentBridge): FolioToolCallResultFor<TName>;
18
+ declare const executeFolioToolCallUntyped: (name: string, args: unknown, bridge: FolioAgentBridge, options?: FolioAgentToolOptions) => FolioToolCallResult;
19
+ declare function executeFolioToolCall<TName extends FolioAgentToolName>(name: TName, args: FolioAgentToolInputByName[TName], bridge: FolioAgentBridge, options?: FolioAgentToolOptions): FolioToolCallResultFor<TName>;
19
20
  //#endregion
20
21
  export { executeFolioToolCall, executeFolioToolCallUntyped };
package/dist/execute.js CHANGED
@@ -2,7 +2,7 @@ import { getDecodedCommentHandlers } from "./bridge.js";
2
2
  import { decodeCommentId, decodeMainStoryTextRangeHandle, decodeSectionHandle, decodeStoryHandle } from "./codecs.js";
3
3
  import { explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput, prepareFolioAgentDocumentOperationBatch } from "./parse.js";
4
4
  import { FOLIO_AGENT_TOOL_NAMES } from "./types.js";
5
- import { createFolioAITextRangeHandle, getFolioDocumentOutline, hashFolioAIBlockText, normalizeFolioAIBlockText, readFolioDocumentSection } from "@stll/folio-core/server";
5
+ import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, createFolioAITextRangeHandle, getFolioDocumentOperationIssues, getFolioDocumentOutline, hashFolioAIBlockText, normalizeFolioAIBlockText, readFolioDocumentSection } from "@stll/folio-core/server";
6
6
  //#region src/execute.ts
7
7
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8
8
  const isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
@@ -39,20 +39,20 @@ const MAX_FIND_MATCHES = 200;
39
39
  * Every bridge member used here ({@link FolioDocxReviewer} and the live-editor
40
40
  * ref) is synchronous, so this stays synchronous too.
41
41
  */
42
- const executeFolioToolCallUntyped = (name, args, bridge) => {
42
+ const executeFolioToolCallUntyped = (name, args, bridge, options = {}) => {
43
43
  if (!VALID_TOOL_NAMES.includes(name)) return fail(`Unknown tool "${name}". Valid tools: ${VALID_TOOL_NAMES.join(", ")}.`);
44
44
  try {
45
- return dispatch(name, args, bridge);
45
+ return dispatch(name, args, bridge, options);
46
46
  } catch (error) {
47
47
  return fail(error instanceof Error ? error.message : String(error));
48
48
  }
49
49
  };
50
- function executeFolioToolCall(name, args, bridge) {
51
- return executeFolioToolCallUntyped(name, args, bridge);
50
+ function executeFolioToolCall(name, args, bridge, options = {}) {
51
+ return executeFolioToolCallUntyped(name, args, bridge, options);
52
52
  }
53
- const dispatch = (name, args, bridge) => {
53
+ const dispatch = (name, args, bridge, options) => {
54
54
  if (!isFolioAgentToolName(name)) return fail(`Unknown tool "${name}".`);
55
- return TOOL_HANDLERS[name](args, bridge);
55
+ return TOOL_HANDLERS[name](args, bridge, options);
56
56
  };
57
57
  const readDocument = (bridge) => {
58
58
  const { blocks } = bridge.snapshot();
@@ -283,36 +283,54 @@ const explainSkipReason = (reason) => {
283
283
  if (reason === "staleRange") return "the selected range changed or shifted; run find_text again and retry with the fresh range.";
284
284
  if (reason === "emptyOperation") return "this operation has no effect; nothing to apply.";
285
285
  if (reason === "noopOperation") return "this operation would not change the document (the text already matches what you asked for).";
286
+ if (reason === "documentVersionMismatch") return "the document changed after these edits were proposed; re-read it and regenerate the edits against the current version.";
287
+ if (reason === "documentNotEditable") return "the document is not open for editing right now; nothing was applied or queued. Ask the user to open it for editing, then retry.";
286
288
  return reason;
287
289
  };
288
- const summarizeApplyResult = (result) => ({
290
+ /**
291
+ * Turn one apply-time `FolioAIEditNormalization` (an automatic adjustment the
292
+ * applier made to an operation's input, e.g. splitting a multi-line
293
+ * `insertAfterBlock` / `insertBeforeBlock` `text` into several paragraphs)
294
+ * into the same `{ path, message }` shape lenient decoding reports, so the
295
+ * model sees every normalization in one list regardless of where it happened.
296
+ */
297
+ const explainApplyNormalization = (normalization) => {
298
+ if (normalization.code === "splitMultilineText") return {
299
+ path: `operations[id=${normalization.id}].text`,
300
+ message: `\`text\` contained line breaks; split into ${normalization.paragraphCount} consecutive paragraphs (one per non-blank line) instead of one paragraph with embedded newlines.`
301
+ };
302
+ return {
303
+ path: `operations[id=${normalization.id}]`,
304
+ message: `input was normalized (${normalization.code}).`
305
+ };
306
+ };
307
+ const summarizeApplyResult = (result, normalizations) => ({
289
308
  version: result.version,
290
309
  applied: result.applied.map((entry) => ({ id: entry.id })),
310
+ queued: (result.queued ?? []).map((entry) => ({ id: entry.id })),
291
311
  skipped: result.skipped.map((entry) => ({
292
312
  id: entry.id,
293
313
  reason: explainSkipReason(entry.reason)
294
314
  })),
295
315
  issues: result.issues ?? [],
296
- receipts: result.receipts ?? []
316
+ receipts: result.receipts ?? [],
317
+ normalizations: [...normalizations, ...(result.normalizations ?? []).map(explainApplyNormalization)]
297
318
  });
298
- /**
299
- * Attach a `precondition.blockTextHash` guard to every operation before
300
- * handing the batch to the bridge.
301
- *
302
- * When the caller (the model) already echoed a `precondition` on the
303
- * operation — sourced from a `blockTextHash` returned by an earlier
304
- * `read_document` / `read_section` / `find_text` call — that is honored
305
- * as-is: it is the only signal that can catch a document edit made
306
- * BETWEEN that read and this apply call.
307
- *
308
- * When no precondition was supplied, fall back to stamping one from this
309
- * call's own fresh `bridge.snapshot()`, matching the previous behavior.
310
- * This fallback cannot detect cross-call staleness — the snapshot it reads
311
- * from is taken right before applying, so it always matches the current
312
- * live document — but it still guards a later operation in the SAME batch
313
- * against an earlier operation in that batch touching the same block.
314
- */
315
- const applyOperations = (bridge, operations) => {
319
+ /** Every operation skipped for one batch-wide reason, before anything reached the bridge. */
320
+ const rejectBatch = (operations, reason, normalizations) => {
321
+ const skipped = operations.map(({ id }) => ({
322
+ id,
323
+ reason
324
+ }));
325
+ return summarizeApplyResult({
326
+ version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
327
+ applied: [],
328
+ skipped,
329
+ issues: getFolioDocumentOperationIssues(operations, skipped),
330
+ receipts: []
331
+ }, normalizations);
332
+ };
333
+ const applyOperations = (bridge, { operations, precondition, normalizations = [] }) => {
316
334
  const snapshot = bridge.snapshot();
317
335
  const guardedOperations = [];
318
336
  for (const operation of operations) {
@@ -329,18 +347,34 @@ const applyOperations = (bridge, operations) => {
329
347
  }
330
348
  return summarizeApplyResult(bridge.applyDocumentOperations(prepareFolioAgentDocumentOperationBatch({
331
349
  operations: guardedOperations,
332
- ...bridge.documentOperationMode !== void 0 && { mode: bridge.documentOperationMode }
333
- })));
350
+ ...bridge.documentOperationMode !== void 0 && { mode: bridge.documentOperationMode },
351
+ ...precondition !== void 0 && { precondition }
352
+ })), normalizations);
334
353
  };
335
354
  const addComment = (args, bridge) => {
336
355
  const parsed = parseAddCommentInput(args);
337
356
  if (!parsed.ok) return fail(parsed.error);
338
- return ok(applyOperations(bridge, [parsed.operation]));
357
+ return ok(applyOperations(bridge, { operations: [parsed.operation] }));
339
358
  };
340
- const suggestChanges = (args, bridge) => {
341
- const parsed = parseSuggestChangesInput(args);
359
+ /**
360
+ * A version-pinned batch is compared against the bridge's document version
361
+ * BEFORE any operation is applied or queued: an approval that runs after
362
+ * the document moved on skips as a whole instead of landing half of its
363
+ * edits on a document the model never saw. A surface without a version
364
+ * notion cannot honour the pin and refuses rather than guessing.
365
+ */
366
+ const suggestChanges = (args, bridge, options) => {
367
+ const parsed = parseSuggestChangesInput(args, options.suggestChanges);
342
368
  if (!parsed.ok) return fail(parsed.error);
343
- return ok(applyOperations(bridge, parsed.operations));
369
+ if (parsed.precondition !== void 0) {
370
+ if (!bridge.getDocumentVersion) return fail("This editor surface cannot verify `documentVersion`; it has no document version to compare against.");
371
+ if (bridge.getDocumentVersion() !== parsed.precondition.documentVersion) return ok(rejectBatch(parsed.operations, "documentVersionMismatch", parsed.normalizations));
372
+ }
373
+ return ok(applyOperations(bridge, {
374
+ operations: parsed.operations,
375
+ ...parsed.precondition !== void 0 && { precondition: parsed.precondition },
376
+ normalizations: parsed.normalizations
377
+ }));
344
378
  };
345
379
  const replyComment = (args, bridge) => {
346
380
  if (!isPlainObject(args)) return fail("reply_comment expects an object with `commentId` and `text` strings.");
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, folioDocumentOperationBatchSchema } from "./operation-schema.js";
2
- import { FOLIO_AGENT_TOOL_NAMES, FolioAgentApplyOperationsSummary, FolioAgentBlock, FolioAgentChange, FolioAgentComment, FolioAgentCommentFilter, FolioAgentCommentReply, FolioAgentDocumentOutline, FolioAgentOutlineEntry, FolioAgentScopedFindTextResult, FolioAgentSectionRead, FolioAgentStoryFindTextResult, FolioAgentStoryTextMatch, FolioAgentTextMatch, FolioAgentToolDefinition, FolioAgentToolName, FolioToolCallResult } from "./types.js";
2
+ import { FOLIO_AGENT_TOOL_NAMES, FolioAgentApplyOperationsSummary, FolioAgentBlock, FolioAgentChange, FolioAgentComment, FolioAgentCommentFilter, FolioAgentCommentReply, FolioAgentDocumentOutline, FolioAgentInputNormalization, FolioAgentOutlineEntry, FolioAgentScopedFindTextResult, FolioAgentSectionRead, FolioAgentStoryFindTextResult, FolioAgentStoryTextMatch, FolioAgentTextMatch, FolioAgentToolDefinition, FolioAgentToolName, FolioToolCallResult } from "./types.js";
3
3
  import { FolioAgentBridge } from "./bridge.js";
4
4
  import { CreateEditorRefBridgeOptions, FolioAgentEditorApplyDocumentOperationsOptions, FolioAgentEditorRefLike, createEditorRefBridge } from "./bridges/editor-ref.js";
5
5
  import { CreateReviewerBridgeOptions, createReviewerBridge } from "./bridges/reviewer.js";
6
6
  import { FolioAgentBlockDiff, FolioAgentCompareDocxVersionsOptions, FolioAgentGenerateRedlineDocxOptions, FolioAgentGenerateRedlineDocxResult, FolioAgentVersionDiff, FolioAgentVersionDiffSegment, compareDocxVersions, formatVersionDiffForLLM, generateRedlineDocx } from "./compare.js";
7
+ import { DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, FolioAgentToolOptions, FolioSuggestChangesOptions, InvalidFolioSuggestChangesOptionsError } from "./suggest-changes-options.js";
7
8
  import { executeFolioToolCall, executeFolioToolCallUntyped } from "./execute.js";
8
9
  import { ParseAddCommentResult, ParseSuggestChangesResult, parseAddCommentInput, parseSuggestChangesInput } from "./parse.js";
9
10
  import { AnthropicToolDefinition, OpenAIToolDefinition, toAnthropicTools, toOpenAITools } from "./providers.js";
10
- import { FOLIO_AGENT_TOOLS, getFolioToolDefinitions } from "./tools.js";
11
- export { type AnthropicToolDefinition, type CreateEditorRefBridgeOptions, type CreateReviewerBridgeOptions, FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_NAMES, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, type FolioAgentApplyOperationsSummary, type FolioAgentBlock, type FolioAgentBlockDiff, type FolioAgentBridge, type FolioAgentChange, type FolioAgentComment, type FolioAgentCommentFilter, type FolioAgentCommentReply, type FolioAgentCompareDocxVersionsOptions, type FolioAgentDocumentOutline, type FolioAgentEditorApplyDocumentOperationsOptions, type FolioAgentEditorRefLike, type FolioAgentGenerateRedlineDocxOptions, type FolioAgentGenerateRedlineDocxResult, type FolioAgentOutlineEntry, type FolioAgentScopedFindTextResult, type FolioAgentSectionRead, type FolioAgentStoryFindTextResult, type FolioAgentStoryTextMatch, type FolioAgentTextMatch, type FolioAgentToolDefinition, type FolioAgentToolName, type FolioAgentVersionDiff, type FolioAgentVersionDiffSegment, type FolioToolCallResult, type OpenAIToolDefinition, type ParseAddCommentResult, type ParseSuggestChangesResult, compareDocxVersions, createEditorRefBridge, createReviewerBridge, executeFolioToolCall, executeFolioToolCallUntyped, folioDocumentOperationBatchSchema, formatVersionDiffForLLM, generateRedlineDocx, getFolioToolDefinitions, parseAddCommentInput, parseSuggestChangesInput, toAnthropicTools, toOpenAITools };
11
+ import { FOLIO_AGENT_TOOLS, describeSuggestChangesCapabilities, getFolioToolDefinitions } from "./tools.js";
12
+ export { type AnthropicToolDefinition, type CreateEditorRefBridgeOptions, type CreateReviewerBridgeOptions, DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_NAMES, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, type FolioAgentApplyOperationsSummary, type FolioAgentBlock, type FolioAgentBlockDiff, type FolioAgentBridge, type FolioAgentChange, type FolioAgentComment, type FolioAgentCommentFilter, type FolioAgentCommentReply, type FolioAgentCompareDocxVersionsOptions, type FolioAgentDocumentOutline, type FolioAgentEditorApplyDocumentOperationsOptions, type FolioAgentEditorRefLike, type FolioAgentGenerateRedlineDocxOptions, type FolioAgentGenerateRedlineDocxResult, type FolioAgentInputNormalization, type FolioAgentOutlineEntry, type FolioAgentScopedFindTextResult, type FolioAgentSectionRead, type FolioAgentStoryFindTextResult, type FolioAgentStoryTextMatch, type FolioAgentTextMatch, type FolioAgentToolDefinition, type FolioAgentToolName, type FolioAgentToolOptions, type FolioAgentVersionDiff, type FolioAgentVersionDiffSegment, type FolioSuggestChangesOptions, type FolioToolCallResult, InvalidFolioSuggestChangesOptionsError, type OpenAIToolDefinition, type ParseAddCommentResult, type ParseSuggestChangesResult, compareDocxVersions, createEditorRefBridge, createReviewerBridge, describeSuggestChangesCapabilities, executeFolioToolCall, executeFolioToolCallUntyped, folioDocumentOperationBatchSchema, formatVersionDiffForLLM, generateRedlineDocx, getFolioToolDefinitions, parseAddCommentInput, parseSuggestChangesInput, toAnthropicTools, toOpenAITools };
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { executeFolioToolCall, executeFolioToolCallUntyped } from "./execute.js"
5
5
  import { FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, folioDocumentOperationBatchSchema } from "./operation-schema.js";
6
6
  import { parseAddCommentInput, parseSuggestChangesInput } from "./parse.js";
7
7
  import { toAnthropicTools, toOpenAITools } from "./providers.js";
8
- import { FOLIO_AGENT_TOOLS, getFolioToolDefinitions } from "./tools.js";
8
+ import { DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, InvalidFolioSuggestChangesOptionsError } from "./suggest-changes-options.js";
9
+ import { FOLIO_AGENT_TOOLS, describeSuggestChangesCapabilities, getFolioToolDefinitions } from "./tools.js";
9
10
  import { FOLIO_AGENT_TOOL_NAMES } from "./types.js";
10
- export { FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_NAMES, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, compareDocxVersions, createEditorRefBridge, createReviewerBridge, executeFolioToolCall, executeFolioToolCallUntyped, folioDocumentOperationBatchSchema, formatVersionDiffForLLM, generateRedlineDocx, getFolioToolDefinitions, parseAddCommentInput, parseSuggestChangesInput, toAnthropicTools, toOpenAITools };
11
+ export { DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_NAMES, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, InvalidFolioSuggestChangesOptionsError, compareDocxVersions, createEditorRefBridge, createReviewerBridge, describeSuggestChangesCapabilities, executeFolioToolCall, executeFolioToolCallUntyped, folioDocumentOperationBatchSchema, formatVersionDiffForLLM, generateRedlineDocx, getFolioToolDefinitions, parseAddCommentInput, parseSuggestChangesInput, toAnthropicTools, toOpenAITools };
@@ -34,7 +34,7 @@ declare const FOLIO_TEXT_RANGE_JSON_SCHEMA: FolioJsonSchema;
34
34
  declare const FOLIO_PRECONDITION_JSON_SCHEMA: FolioJsonSchema;
35
35
  /**
36
36
  * JSON Schema (draft-07 compatible) for ONE document operation: the full
37
- * thirteen-variant union accepted by `parseFolioDocumentOperationBatch` in
37
+ * union accepted by `parseFolioDocumentOperationBatch` in
38
38
  * `@stll/folio-core`, one `oneOf` variant per entry in
39
39
  * `FOLIO_DOCUMENT_OPERATION_TYPES`. Intended for LLM tool definitions and
40
40
  * other consumers that need the contract's wire shape without re-declaring
@@ -100,6 +100,8 @@ const commentJsonSchema = {
100
100
  /**
101
101
  * Properties every operation variant accepts: the required `id` plus the
102
102
  * optional review metadata (`severity`, `area`) and `precondition` guard.
103
+ * `suggestionId` joins them on every variant except `commentOnRange`
104
+ * (comments are not tracked changes, so there is nothing to group).
103
105
  */
104
106
  const operationMetaProperties = {
105
107
  id: {
@@ -121,13 +123,17 @@ const operationMetaProperties = {
121
123
  },
122
124
  precondition: FOLIO_PRECONDITION_JSON_SCHEMA
123
125
  };
126
+ const suggestionIdProperty = { suggestionId: {
127
+ type: "string",
128
+ description: "Optional host-side grouping key: in \"suggested\" mode every mark this operation produces carries it so the whole suggestion is accepted or rejected as one unit."
129
+ } };
124
130
  const blockIdProperty = {
125
131
  type: "string",
126
132
  description: "Id of the target block, from a prior document read."
127
133
  };
128
134
  /**
129
135
  * JSON Schema (draft-07 compatible) for ONE document operation: the full
130
- * thirteen-variant union accepted by `parseFolioDocumentOperationBatch` in
136
+ * union accepted by `parseFolioDocumentOperationBatch` in
131
137
  * `@stll/folio-core`, one `oneOf` variant per entry in
132
138
  * `FOLIO_DOCUMENT_OPERATION_TYPES`. Intended for LLM tool definitions and
133
139
  * other consumers that need the contract's wire shape without re-declaring
@@ -142,6 +148,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
142
148
  description: "Replace an exact text match inside one block.",
143
149
  properties: {
144
150
  ...operationMetaProperties,
151
+ ...suggestionIdProperty,
145
152
  type: {
146
153
  type: "string",
147
154
  enum: ["replaceInBlock"]
@@ -171,6 +178,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
171
178
  description: "Replace the text covered by a range handle.",
172
179
  properties: {
173
180
  ...operationMetaProperties,
181
+ ...suggestionIdProperty,
174
182
  type: {
175
183
  type: "string",
176
184
  enum: ["replaceRange"]
@@ -215,6 +223,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
215
223
  description: "Apply inline formatting to the text covered by a range handle in direct or tracked mode.",
216
224
  properties: {
217
225
  ...operationMetaProperties,
226
+ ...suggestionIdProperty,
218
227
  type: {
219
228
  type: "string",
220
229
  enum: ["formatRange"]
@@ -245,6 +254,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
245
254
  description: "Insert a new paragraph after the anchor block.",
246
255
  properties: {
247
256
  ...operationMetaProperties,
257
+ ...suggestionIdProperty,
248
258
  type: {
249
259
  type: "string",
250
260
  enum: ["insertAfterBlock"]
@@ -252,7 +262,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
252
262
  blockId: blockIdProperty,
253
263
  text: {
254
264
  type: "string",
255
- description: "The paragraph text to insert."
265
+ description: "The paragraph text to insert. A line break splits this into consecutive paragraphs at the same anchor instead of one paragraph with embedded newlines — only the first paragraph gets `styleId` / `inheritFormatting`, later ones use body formatting. Prefer one paragraph per operation; only rely on the split for a heading immediately followed by its body text."
256
266
  },
257
267
  inheritFormatting: {
258
268
  type: "boolean",
@@ -281,6 +291,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
281
291
  description: "Insert a new paragraph before the anchor block.",
282
292
  properties: {
283
293
  ...operationMetaProperties,
294
+ ...suggestionIdProperty,
284
295
  type: {
285
296
  type: "string",
286
297
  enum: ["insertBeforeBlock"]
@@ -288,7 +299,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
288
299
  blockId: blockIdProperty,
289
300
  text: {
290
301
  type: "string",
291
- description: "The paragraph text to insert."
302
+ description: "The paragraph text to insert. A line break splits this into consecutive paragraphs at the same anchor instead of one paragraph with embedded newlines — only the first paragraph gets `styleId` / `inheritFormatting`, later ones use body formatting. Prefer one paragraph per operation; only rely on the split for a heading immediately followed by its body text."
292
303
  },
293
304
  inheritFormatting: {
294
305
  type: "boolean",
@@ -317,6 +328,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
317
328
  description: "Replace one block's entire text.",
318
329
  properties: {
319
330
  ...operationMetaProperties,
331
+ ...suggestionIdProperty,
320
332
  type: {
321
333
  type: "string",
322
334
  enum: ["replaceBlock"]
@@ -349,6 +361,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
349
361
  description: "Delete one block.",
350
362
  properties: {
351
363
  ...operationMetaProperties,
364
+ ...suggestionIdProperty,
352
365
  type: {
353
366
  type: "string",
354
367
  enum: ["deleteBlock"]
@@ -368,6 +381,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
368
381
  description: "Attach a comment to one block, optionally quoting text within it.",
369
382
  properties: {
370
383
  ...operationMetaProperties,
384
+ ...suggestionIdProperty,
371
385
  type: {
372
386
  type: "string",
373
387
  enum: ["commentOnBlock"]
@@ -392,6 +406,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
392
406
  description: "Insert a signature table next to the anchor block. Direct mode only (table insertion is not representable as a tracked change).",
393
407
  properties: {
394
408
  ...operationMetaProperties,
409
+ ...suggestionIdProperty,
395
410
  type: {
396
411
  type: "string",
397
412
  enum: ["insertSignatureTable"]
@@ -440,6 +455,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
440
455
  description: "Insert a row next to the row containing the anchor block.",
441
456
  properties: {
442
457
  ...operationMetaProperties,
458
+ ...suggestionIdProperty,
443
459
  type: {
444
460
  type: "string",
445
461
  enum: ["insertTableRow"]
@@ -468,6 +484,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
468
484
  description: "Delete the row containing the anchor block.",
469
485
  properties: {
470
486
  ...operationMetaProperties,
487
+ ...suggestionIdProperty,
471
488
  type: {
472
489
  type: "string",
473
490
  enum: ["deleteTableRow"]
@@ -486,6 +503,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
486
503
  description: "Insert a column next to the column containing the anchor block.",
487
504
  properties: {
488
505
  ...operationMetaProperties,
506
+ ...suggestionIdProperty,
489
507
  type: {
490
508
  type: "string",
491
509
  enum: ["insertTableColumn"]
@@ -514,6 +532,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
514
532
  description: "Delete the column containing the anchor block.",
515
533
  properties: {
516
534
  ...operationMetaProperties,
535
+ ...suggestionIdProperty,
517
536
  type: {
518
537
  type: "string",
519
538
  enum: ["deleteTableColumn"]
@@ -532,6 +551,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
532
551
  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
552
  properties: {
534
553
  ...operationMetaProperties,
554
+ ...suggestionIdProperty,
535
555
  type: {
536
556
  type: "string",
537
557
  enum: ["mergeTableCells"]
@@ -561,6 +581,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
561
581
  description: "Split one spanned table cell into individual cells. Tracked mode supports vertical-only spans.",
562
582
  properties: {
563
583
  ...operationMetaProperties,
584
+ ...suggestionIdProperty,
564
585
  type: {
565
586
  type: "string",
566
587
  enum: ["splitTableCell"]
@@ -610,6 +631,17 @@ const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA = {
610
631
  dryRun: {
611
632
  type: "boolean",
612
633
  description: "Preview the batch without mutating the document."
634
+ },
635
+ precondition: {
636
+ type: "object",
637
+ description: "Batch-level guard: the host document version this batch was authored against. A surface that knows its document version skips the whole batch (reason `documentVersionMismatch`) when the token differs.",
638
+ properties: { documentVersion: {
639
+ type: "string",
640
+ minLength: 1,
641
+ description: "Opaque host version token (an entity version id, a checkpoint)."
642
+ } },
643
+ required: ["documentVersion"],
644
+ additionalProperties: false
613
645
  }
614
646
  },
615
647
  required: ["version", "operations"],
package/dist/parse.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- import { FolioAIEditOperation, FolioDocumentOperationBatch, FolioDocumentOperationMode } from "@stll/folio-core/server";
1
+ import { FolioAgentInputNormalization } from "./types.js";
2
+ import { FolioSuggestChangesOptions } from "./suggest-changes-options.js";
3
+ import { FolioAIEditOperation, FolioDocumentOperationBatch, FolioDocumentOperationBatchPrecondition, FolioDocumentOperationMode } from "@stll/folio-core/server";
2
4
  //#region src/parse.d.ts
3
5
  /**
4
6
  * Hard caps on `suggest_changes` / `add_comment` / `reply_comment` input
@@ -7,20 +9,21 @@ import { FolioAIEditOperation, FolioDocumentOperationBatch, FolioDocumentOperati
7
9
  * the tracked-changes engine, in one shot. `execute.ts` reuses
8
10
  * {@link MAX_OPERATION_TEXT_LENGTH} for `reply_comment`'s text cap too, so
9
11
  * the limit stays a single number shared across every text-bearing tool.
12
+ * The per-call operation count is a host option
13
+ * (`FolioSuggestChangesOptions.maxOperations`), defaulting to
14
+ * {@link DEFAULT_MAX_OPERATIONS_PER_CALL}.
10
15
  */
11
- declare const MAX_OPERATIONS_PER_CALL = 50;
12
16
  declare const MAX_OPERATION_TEXT_LENGTH = 100000;
13
17
  /**
14
18
  * Aggregate cap on the SUM of every text-bearing field's length across one
15
19
  * `suggest_changes` call. Each field alone is bounded by
16
- * {@link MAX_OPERATION_TEXT_LENGTH} and each call by
17
- * {@link MAX_OPERATIONS_PER_CALL} operations, but an operation can carry
18
- * several capped fields (e.g. `comment` plus `text`), and a table-insertion
19
- * operation can carry up to {@link MAX_TABLE_INSERTION_CELL_TEXTS} capped
20
- * cell texts — so a maximally-shaped batch could still push roughly
21
- * 50 * 256 * 100,000 ~= 1.28B characters into the tracked-changes engine in
22
- * one call even though every per-field cap was respected. This budget bounds
23
- * the running total instead.
20
+ * {@link MAX_OPERATION_TEXT_LENGTH} and each call by the operation cap, but
21
+ * an operation can carry several capped fields (e.g. `comment` plus `text`),
22
+ * and a table-insertion operation can carry up to
23
+ * {@link MAX_TABLE_INSERTION_CELL_TEXTS} capped cell texts — so a
24
+ * maximally-shaped batch could still push an unbounded total into the
25
+ * tracked-changes engine in one call even though every per-field cap was
26
+ * respected. This budget bounds the running total instead.
24
27
  */
25
28
  declare const MAX_TOTAL_OPERATION_TEXT_LENGTH = 2000000;
26
29
  /** Plain-language error for a string argument over {@link MAX_OPERATION_TEXT_LENGTH}. */
@@ -30,6 +33,7 @@ type PrepareFolioAgentDocumentOperationBatchOptions = {
30
33
  mode?: FolioDocumentOperationMode;
31
34
  atomic?: boolean;
32
35
  dryRun?: boolean;
36
+ precondition?: FolioDocumentOperationBatchPrecondition;
33
37
  };
34
38
  /**
35
39
  * Wrap agent-preprocessed operations in the versioned batch envelope and
@@ -37,7 +41,7 @@ type PrepareFolioAgentDocumentOperationBatchOptions = {
37
41
  * batch is safe to hand straight to `applyDocumentOperations`; core marks
38
42
  * parsed batches internally so the downstream apply path can skip reparsing.
39
43
  */
40
- declare const prepareFolioAgentDocumentOperationBatch: ({ operations, mode, atomic, dryRun }: PrepareFolioAgentDocumentOperationBatchOptions) => FolioDocumentOperationBatch;
44
+ declare const prepareFolioAgentDocumentOperationBatch: ({ operations, mode, atomic, dryRun, precondition }: PrepareFolioAgentDocumentOperationBatchOptions) => FolioDocumentOperationBatch;
41
45
  /** Result of {@link parseAddCommentInput}. */
42
46
  type ParseAddCommentResult = {
43
47
  ok: true;
@@ -56,6 +60,9 @@ declare const parseAddCommentInput: (args: unknown) => ParseAddCommentResult;
56
60
  type ParseSuggestChangesResult = {
57
61
  ok: true;
58
62
  operations: FolioAIEditOperation[];
63
+ /** Present when the call pinned a host document version. */
64
+ precondition?: FolioDocumentOperationBatchPrecondition;
65
+ normalizations: FolioAgentInputNormalization[];
59
66
  } | {
60
67
  ok: false;
61
68
  error: string;
@@ -63,8 +70,9 @@ type ParseSuggestChangesResult = {
63
70
  /**
64
71
  * Validate `suggest_changes`' raw tool-call arguments and build the
65
72
  * {@link FolioAIEditOperation}s it applies. Pure: does not touch a bridge or
66
- * document.
73
+ * document. `options` must match the {@link FolioSuggestChangesOptions} the
74
+ * tool definition was built with.
67
75
  */
68
- declare const parseSuggestChangesInput: (args: unknown) => ParseSuggestChangesResult;
76
+ declare const parseSuggestChangesInput: (args: unknown, options?: FolioSuggestChangesOptions) => ParseSuggestChangesResult;
69
77
  //#endregion
70
- export { MAX_OPERATIONS_PER_CALL, MAX_OPERATION_TEXT_LENGTH, MAX_TOTAL_OPERATION_TEXT_LENGTH, ParseAddCommentResult, ParseSuggestChangesResult, PrepareFolioAgentDocumentOperationBatchOptions, explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput, prepareFolioAgentDocumentOperationBatch };
78
+ export { MAX_OPERATION_TEXT_LENGTH, MAX_TOTAL_OPERATION_TEXT_LENGTH, ParseAddCommentResult, ParseSuggestChangesResult, PrepareFolioAgentDocumentOperationBatchOptions, explainTextTooLong, parseAddCommentInput, parseSuggestChangesInput, prepareFolioAgentDocumentOperationBatch };