@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.
@@ -55,6 +55,8 @@ type FolioAgentToolInputByName = {
55
55
  };
56
56
  [FOLIO_AGENT_TOOL_NAMES.suggestChanges]: {
57
57
  operations: unknown[];
58
+ /** Present when the tool was defined with a `documentVersion` option. */
59
+ documentVersion?: string;
58
60
  };
59
61
  [FOLIO_AGENT_TOOL_NAMES.replyComment]: {
60
62
  commentId: string;
package/dist/tools.d.ts CHANGED
@@ -1,15 +1,29 @@
1
1
  import { FolioAgentApplyOperationsSummary, FolioAgentBlock, FolioAgentChange, FolioAgentComment, FolioAgentCommentFilter, FolioAgentDocumentOutline, FolioAgentScopedFindTextResult, FolioAgentSectionRead, FolioAgentToolDefinition, FolioAgentTypedToolDefinition } from "./types.js";
2
+ import { FolioAgentToolOptions, FolioSuggestChangesOptions } from "./suggest-changes-options.js";
2
3
  import { FolioAgentFindTextScope, FolioAgentShowInDocumentArgs } from "./tool-contract.js";
3
- import { FolioDocumentOperationType } from "@stll/folio-core/server";
4
4
  //#region src/tools.d.ts
5
5
  /**
6
- * The contract operation types `suggest_changes` exposes to the model,
7
- * derived from the shared contract constant minus the exclusions above.
8
- * Exported (module-level only, not from the package index) so
9
- * `parse.test.ts` can assert this enum stays in lockstep with what
10
- * `parseSuggestChangesInput` actually accepts.
6
+ * `suggest_changes` is a host-configurable projection of the document-operation
7
+ * contract (see `FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA` in `operation-schema.ts`):
8
+ * the allowed operation types, the review-metadata policy, the per-call cap,
9
+ * and an optional document-version pin all come from
10
+ * {@link FolioSuggestChangesOptions}. The schema is derived from the resolved
11
+ * options and from core's per-type key map, so the properties it advertises
12
+ * are exactly the ones the contract parser accepts for the allowed types.
13
+ * Two model-facing conveniences differ from the contract on the wire:
14
+ * `id` is optional (the parser mints unique ids) and `comment` may be a plain
15
+ * string (the parser wraps it into `{ text }`). `suggestionId` is host-side
16
+ * grouping state and is never exposed to the model.
11
17
  */
12
- declare const SUGGEST_CHANGES_OPERATION_TYPES: readonly FolioDocumentOperationType[];
18
+ declare const SUGGEST_CHANGES_OPERATION_TYPES: readonly ("replaceInBlock" | "replaceRange" | "commentOnRange" | "formatRange" | "insertAfterBlock" | "insertBeforeBlock" | "replaceBlock" | "deleteBlock" | "commentOnBlock" | "insertSignatureTable" | "insertTableRow" | "deleteTableRow" | "insertTableColumn" | "deleteTableColumn" | "mergeTableCells" | "splitTableCell")[];
19
+ /**
20
+ * Plain-language capability statement for a configured `suggest_changes`
21
+ * surface: the allowed operations, the structural knobs they unlock, the
22
+ * limits, and the review-metadata and document-version requirements. Used
23
+ * inside the tool description and exported so a host can paste the same
24
+ * text into its system prompt instead of hand-maintaining a copy that drifts.
25
+ */
26
+ declare const describeSuggestChangesCapabilities: (options?: FolioSuggestChangesOptions) => string;
13
27
  /**
14
28
  * The tools this package exposes, described for an LLM. Every tool that reads
15
29
  * or mutates the document expects `blockId` values that came from
@@ -52,6 +66,7 @@ declare const FOLIO_AGENT_TOOL_REGISTRY: {
52
66
  }, FolioAgentApplyOperationsSummary>;
53
67
  readonly suggest_changes: FolioAgentTypedToolDefinition<"suggest_changes", {
54
68
  operations: unknown[];
69
+ documentVersion?: string;
55
70
  }, FolioAgentApplyOperationsSummary>;
56
71
  readonly reply_comment: FolioAgentTypedToolDefinition<"reply_comment", {
57
72
  commentId: string;
@@ -85,7 +100,13 @@ declare const FOLIO_AGENT_TOOL_REGISTRY: {
85
100
  }>;
86
101
  };
87
102
  declare const FOLIO_AGENT_TOOLS: FolioAgentToolDefinition[];
88
- /** The tool definitions this package exposes. Same array as {@link FOLIO_AGENT_TOOLS}, as a function for symmetry with the other providers. */
89
- declare const getFolioToolDefinitions: () => FolioAgentToolDefinition[];
103
+ /**
104
+ * The tool definitions this package exposes. Without options this is
105
+ * {@link FOLIO_AGENT_TOOLS}; with `suggestChanges` options the
106
+ * `suggest_changes` definition is rebuilt for that surface. Pass the same
107
+ * options to `executeFolioToolCall` so the parser enforces what the schema
108
+ * advertises.
109
+ */
110
+ declare const getFolioToolDefinitions: (options?: FolioAgentToolOptions) => FolioAgentToolDefinition[];
90
111
  //#endregion
91
- export { FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_REGISTRY, SUGGEST_CHANGES_OPERATION_TYPES, getFolioToolDefinitions };
112
+ export { FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_REGISTRY, SUGGEST_CHANGES_OPERATION_TYPES, describeSuggestChangesCapabilities, getFolioToolDefinitions };
package/dist/tools.js CHANGED
@@ -1,107 +1,243 @@
1
1
  import { FOLIO_COMMENT_ID_JSON_SCHEMA, FOLIO_SCOPED_HANDLE_JSON_SCHEMA, FOLIO_SECTION_HANDLE_JSON_SCHEMA, FOLIO_STORY_HANDLE_JSON_SCHEMA } from "./codecs.js";
2
2
  import { FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA } from "./operation-schema.js";
3
+ import { DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, resolveSuggestChangesOptions } from "./suggest-changes-options.js";
3
4
  import { defineFolioAgentToolDefinition } from "./tool-contract.js";
4
5
  import { FOLIO_AGENT_TOOL_NAMES } from "./types.js";
5
- import { FOLIO_DOCUMENT_OPERATION_TYPES } from "@stll/folio-core/server";
6
+ import { FOLIO_DOCUMENT_OPERATION_KEYS_BY_TYPE } from "@stll/folio-core/server";
6
7
  //#region src/tools.ts
7
8
  /**
8
- * `suggest_changes` deliberately narrows the full document-operation contract
9
- * (see `FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA` in `operation-schema.ts`):
10
- * - excluded types: `insertSignatureTable` (direct-only) and `commentOnBlock`
11
- * (covered by the dedicated `add_comment` tool);
12
- * - `id` is optional here (auto-generated `op-1`, `op-2`, … by `parse.ts`)
13
- * where the contract requires it;
14
- * - `comment` is a plain string here; `parse.ts` wraps it into the contract's
15
- * `{ text }` object;
16
- * - the review metadata (`severity`, `area`) and the insert/replace
17
- * formatting knobs (`inheritFormatting`, `pageBreakBefore`,
18
- * `preserveFormatting`, `styleId`, `parties`, `quote`, except `formatting`)
19
- * are not exposed to the model. `precondition` IS exposed (see
20
- * `FOLIO_PRECONDITION_JSON_SCHEMA`) so the model can guard an edit against
21
- * staleness introduced between an earlier read and this call.
9
+ * `suggest_changes` is a host-configurable projection of the document-operation
10
+ * contract (see `FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA` in `operation-schema.ts`):
11
+ * the allowed operation types, the review-metadata policy, the per-call cap,
12
+ * and an optional document-version pin all come from
13
+ * {@link FolioSuggestChangesOptions}. The schema is derived from the resolved
14
+ * options and from core's per-type key map, so the properties it advertises
15
+ * are exactly the ones the contract parser accepts for the allowed types.
16
+ * Two model-facing conveniences differ from the contract on the wire:
17
+ * `id` is optional (the parser mints unique ids) and `comment` may be a plain
18
+ * string (the parser wraps it into `{ text }`). `suggestionId` is host-side
19
+ * grouping state and is never exposed to the model.
22
20
  */
23
- const SUGGEST_CHANGES_EXCLUDED_OPERATION_TYPES = /* @__PURE__ */ new Set(["commentOnBlock", "insertSignatureTable"]);
21
+ const SUGGEST_CHANGES_OPERATION_TYPES = DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES;
22
+ /** One-line meaning of each contract operation type, for schemas and prompts. */
23
+ const OPERATION_TYPE_SUMMARIES = {
24
+ replaceInBlock: "replace an exact text match inside one block (`find` -> `replace`)",
25
+ replaceRange: "replace the text covered by a `range` copied from find_text",
26
+ commentOnRange: "attach a comment to a `range` copied from find_text",
27
+ formatRange: "toggle bold, italic, or underline on a `range` copied from find_text",
28
+ insertAfterBlock: "insert a new paragraph after a block",
29
+ insertBeforeBlock: "insert a new paragraph before a block",
30
+ replaceBlock: "replace one block's entire text",
31
+ deleteBlock: "delete one block",
32
+ commentOnBlock: "attach a comment to one block, optionally quoting text within it",
33
+ insertSignatureTable: "insert a side-by-side signature table for the given `parties`",
34
+ insertTableRow: "insert a table row next to the row containing a cell block",
35
+ deleteTableRow: "delete the table row containing a cell block",
36
+ insertTableColumn: "insert a table column next to the column containing a cell block",
37
+ deleteTableColumn: "delete the table column containing a cell block",
38
+ mergeTableCells: "merge table cells from a cell block to `endBlockId`, or `rowCount` rows downward",
39
+ splitTableCell: "split a previously merged table cell"
40
+ };
24
41
  /**
25
- * The contract operation types `suggest_changes` exposes to the model,
26
- * derived from the shared contract constant minus the exclusions above.
27
- * Exported (module-level only, not from the package index) so
28
- * `parse.test.ts` can assert this enum stays in lockstep with what
29
- * `parseSuggestChangesInput` actually accepts.
42
+ * Model-facing schema for every operation property the contract knows,
43
+ * keyed by wire name. A `suggest_changes` schema includes a property only
44
+ * when at least one allowed operation type accepts it (per
45
+ * `FOLIO_DOCUMENT_OPERATION_KEYS_BY_TYPE`), so a three-type host surface
46
+ * advertises three types' worth of fields.
30
47
  */
31
- const SUGGEST_CHANGES_OPERATION_TYPES = FOLIO_DOCUMENT_OPERATION_TYPES.filter((type) => !SUGGEST_CHANGES_EXCLUDED_OPERATION_TYPES.has(type));
32
- const suggestChangesOperationSchema = {
33
- type: "object",
34
- properties: {
35
- id: {
36
- type: "string",
37
- description: "Optional caller-supplied operation id, echoed back in `applied`/`skipped`. Auto-generated (op-1, op-2, …) when omitted."
38
- },
39
- type: {
40
- type: "string",
41
- enum: SUGGEST_CHANGES_OPERATION_TYPES,
42
- description: "The kind of edit to make."
43
- },
44
- blockId: {
45
- type: "string",
46
- description: "The block to edit, from `read_document` or `find_text`."
47
- },
48
- endBlockId: {
49
- type: "string",
50
- minLength: 1,
51
- description: "For cell merging, a block in the opposite corner cell."
52
- },
53
- rowCount: {
54
- type: "integer",
55
- minimum: 2,
56
- description: "For vertical cell merging, the number of grid rows to merge downward."
57
- },
58
- range: {
59
- ...FOLIO_TEXT_RANGE_JSON_SCHEMA,
60
- description: "Required for `replaceRange`, `commentOnRange`, and `formatRange`: copy the range object returned by `find_text`."
61
- },
62
- find: {
63
- type: "string",
64
- description: "Required for `replaceInBlock`: the exact text to find within the block, up to 100,000 characters."
65
- },
66
- replace: {
67
- type: "string",
68
- description: "Required for `replaceInBlock` and `replaceRange`: replacement text, up to 100,000 characters."
69
- },
70
- text: {
71
- type: "string",
72
- description: "Required for `insertAfterBlock` / `insertBeforeBlock` / `replaceBlock`: the text to insert or replace the block with, up to 100,000 characters."
73
- },
74
- position: {
75
- type: "string",
76
- enum: ["after", "before"],
77
- description: "For row or column insertion, place the new structure after the anchor or before it."
78
- },
79
- cellTexts: {
80
- type: "array",
81
- description: "For row or column insertion, initial text for new physical cells in source order, up to 100,000 characters per cell.",
82
- maxItems: 256,
83
- items: { type: "string" }
84
- },
85
- formatting: {
48
+ const OPERATION_PROPERTY_SCHEMAS = {
49
+ id: {
50
+ type: "string",
51
+ description: "Optional caller-supplied operation id, echoed back in `applied` / `queued` / `skipped`. Generated when omitted."
52
+ },
53
+ blockId: {
54
+ type: "string",
55
+ description: "The block to edit, from `read_document` or `find_text`."
56
+ },
57
+ severity: {
58
+ type: "string",
59
+ enum: [
60
+ "low",
61
+ "medium",
62
+ "high"
63
+ ],
64
+ description: "Review severity of this edit, used to sort a review queue."
65
+ },
66
+ area: {
67
+ type: "string",
68
+ description: "Short review area label (e.g. \"Payment terms\"), used to group a review queue."
69
+ },
70
+ precondition: FOLIO_PRECONDITION_JSON_SCHEMA,
71
+ endBlockId: {
72
+ type: "string",
73
+ minLength: 1,
74
+ description: "For cell merging, a block in the opposite corner cell."
75
+ },
76
+ rowCount: {
77
+ type: "integer",
78
+ minimum: 2,
79
+ description: "For vertical cell merging, the number of grid rows to merge downward."
80
+ },
81
+ range: {
82
+ ...FOLIO_TEXT_RANGE_JSON_SCHEMA,
83
+ description: "Required for `replaceRange`, `commentOnRange`, and `formatRange`: copy the range object returned by `find_text`."
84
+ },
85
+ find: {
86
+ type: "string",
87
+ description: "Required for `replaceInBlock`: the exact text to find within the block, up to 100,000 characters."
88
+ },
89
+ replace: {
90
+ type: "string",
91
+ description: "Required for `replaceInBlock` and `replaceRange`: replacement text, up to 100,000 characters."
92
+ },
93
+ text: {
94
+ type: "string",
95
+ description: "Required for `insertAfterBlock` / `insertBeforeBlock` / `replaceBlock`: the text to insert or replace the block with, up to 100,000 characters."
96
+ },
97
+ quote: {
98
+ type: "string",
99
+ description: "For `commentOnBlock`: optional exact text within the block the comment is about, up to 100,000 characters."
100
+ },
101
+ styleId: {
102
+ type: "string",
103
+ description: "For inserts and `replaceBlock`: paragraph style id to apply (e.g. a clause-heading style from the document)."
104
+ },
105
+ pageBreakBefore: {
106
+ type: "boolean",
107
+ description: "For inserts: start the inserted paragraph on a new page."
108
+ },
109
+ inheritFormatting: {
110
+ type: "boolean",
111
+ description: "For inserts: inherit the anchor block's formatting for the inserted paragraph."
112
+ },
113
+ preserveFormatting: {
114
+ type: "boolean",
115
+ description: "For `replaceBlock`: keep the block's existing formatting for the replacement text."
116
+ },
117
+ position: {
118
+ type: "string",
119
+ enum: ["after", "before"],
120
+ description: "For row, column, or signature-table insertion, place the new structure after the anchor (default) or before it."
121
+ },
122
+ parties: {
123
+ type: "array",
124
+ description: "For `insertSignatureTable`: the signing parties, one table cell per party.",
125
+ items: {
86
126
  type: "object",
87
- description: "Required for `formatRange`: set one or more inline properties to enable or disable.",
88
127
  properties: {
89
- bold: { type: "boolean" },
90
- italic: { type: "boolean" },
91
- underline: { type: "boolean" }
128
+ name: {
129
+ type: "string",
130
+ description: "Party name (rendered bold)."
131
+ },
132
+ signatory: {
133
+ type: "string",
134
+ description: "Name of the person signing."
135
+ },
136
+ title: {
137
+ type: "string",
138
+ description: "Signatory title (rendered in italics)."
139
+ }
92
140
  },
93
- minProperties: 1,
141
+ required: ["name"],
94
142
  additionalProperties: false
143
+ }
144
+ },
145
+ cellTexts: {
146
+ type: "array",
147
+ description: "For row or column insertion, initial text for new physical cells in source order, up to 100,000 characters per cell.",
148
+ maxItems: 256,
149
+ items: { type: "string" }
150
+ },
151
+ formatting: {
152
+ type: "object",
153
+ description: "Required for `formatRange`: set one or more inline properties to enable or disable.",
154
+ properties: {
155
+ bold: { type: "boolean" },
156
+ italic: { type: "boolean" },
157
+ underline: { type: "boolean" }
95
158
  },
96
- comment: {
97
- type: "string",
98
- description: "Optional comment explaining this edit, attached to the affected text, up to 100,000 characters."
99
- },
100
- precondition: FOLIO_PRECONDITION_JSON_SCHEMA
159
+ minProperties: 1,
160
+ additionalProperties: false
101
161
  },
102
- required: ["type"],
103
- additionalProperties: false
162
+ comment: {
163
+ type: "string",
164
+ description: "Optional comment explaining this edit, attached to the affected text, up to 100,000 characters. Required for comment operations."
165
+ }
166
+ };
167
+ /** Wire keys the model never sees (`type` is emitted separately with its enum). */
168
+ const HIDDEN_OPERATION_KEYS = /* @__PURE__ */ new Set(["suggestionId", "type"]);
169
+ const operationPropertyKeys = (types) => {
170
+ const keys = /* @__PURE__ */ new Set();
171
+ for (const type of types) for (const key of FOLIO_DOCUMENT_OPERATION_KEYS_BY_TYPE[type]) if (!HIDDEN_OPERATION_KEYS.has(key)) keys.add(key);
172
+ return keys;
173
+ };
174
+ const summarizeOperationTypes = (types) => types.map((type) => `${type} (${OPERATION_TYPE_SUMMARIES[type]})`).join("; ");
175
+ const buildSuggestChangesOperationSchema = (resolved) => {
176
+ const keys = operationPropertyKeys(resolved.operationTypes);
177
+ const properties = { type: {
178
+ type: "string",
179
+ enum: resolved.operationTypes,
180
+ description: `The kind of edit: ${summarizeOperationTypes(resolved.operationTypes)}.`
181
+ } };
182
+ for (const [key, schema] of Object.entries(OPERATION_PROPERTY_SCHEMAS)) if (keys.has(key)) properties[key] = schema;
183
+ return {
184
+ type: "object",
185
+ properties,
186
+ required: resolved.reviewMeta === "required" ? [
187
+ "type",
188
+ "severity",
189
+ "area"
190
+ ] : ["type"],
191
+ additionalProperties: false
192
+ };
193
+ };
194
+ const hasAnyType = (resolved, types) => types.some((type) => resolved.operationTypes.includes(type));
195
+ /**
196
+ * Plain-language capability statement for a configured `suggest_changes`
197
+ * surface: the allowed operations, the structural knobs they unlock, the
198
+ * limits, and the review-metadata and document-version requirements. Used
199
+ * inside the tool description and exported so a host can paste the same
200
+ * text into its system prompt instead of hand-maintaining a copy that drifts.
201
+ */
202
+ const describeSuggestChangesCapabilities = (options) => describeResolvedCapabilities(resolveSuggestChangesOptions(options));
203
+ const describeResolvedCapabilities = (resolved) => {
204
+ const lines = [`Supported operations: ${summarizeOperationTypes(resolved.operationTypes)}.`];
205
+ const styleIdTargets = [...hasAnyType(resolved, ["insertAfterBlock", "insertBeforeBlock"]) ? ["an insert"] : [], ...hasAnyType(resolved, ["replaceBlock"]) ? ["replaceBlock"] : []];
206
+ if (styleIdTargets.length > 0) {
207
+ const pageBreak = hasAnyType(resolved, ["insertAfterBlock", "insertBeforeBlock"]) ? "set `pageBreakBefore: true` on an insert to start it on a new page; " : "";
208
+ lines.push(`Structural edits: ${pageBreak}set \`styleId\` on ${styleIdTargets.join(" or ")} to apply a paragraph style such as a clause heading. Never emit directive markers or markdown syntax as paragraph text.`);
209
+ }
210
+ if (hasAnyType(resolved, ["insertSignatureTable"])) lines.push("Signature blocks: use insertSignatureTable with `parties`; never draw one out of paragraphs.");
211
+ if (!hasAnyType(resolved, ["formatRange"])) lines.push("This surface cannot change run formatting (fonts, bold/italic/underline, size, colour, alignment, spacing, list style); do not promise formatting changes.");
212
+ lines.push(`Limits: at most ${resolved.maxOperations} operations per call (batch larger edits across calls); each text field at most 100,000 characters.`);
213
+ lines.push(resolved.reviewMeta === "required" ? "Every operation must set `severity` (low, medium, or high) and a short `area` label; the review queue sorts and groups by them." : "Set `severity` and `area` on operations when the edit is part of a structured review.");
214
+ if (resolved.documentVersion !== null) lines.push("Pass `documentVersion` exactly as given in this tool's schema; the batch is skipped as a whole when the document has moved on since.");
215
+ return lines.join("\n");
104
216
  };
217
+ const SUGGEST_CHANGES_BASE_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.";
218
+ const buildSuggestChangesToolDefinition = (resolved) => defineFolioAgentToolDefinition({
219
+ name: FOLIO_AGENT_TOOL_NAMES.suggestChanges,
220
+ description: `${SUGGEST_CHANGES_BASE_DESCRIPTION}\n${describeResolvedCapabilities(resolved)}`,
221
+ inputSchema: {
222
+ type: "object",
223
+ properties: {
224
+ ...resolved.documentVersion !== null && { documentVersion: {
225
+ type: "string",
226
+ enum: [resolved.documentVersion.current],
227
+ description: "The current document version shown here. Copy it exactly; the batch is skipped if the document changes before it applies."
228
+ } },
229
+ operations: {
230
+ type: "array",
231
+ description: `The edits to propose, applied in order. At most ${resolved.maxOperations} per call.`,
232
+ minItems: 1,
233
+ maxItems: resolved.maxOperations,
234
+ items: buildSuggestChangesOperationSchema(resolved)
235
+ }
236
+ },
237
+ required: resolved.documentVersion !== null ? ["documentVersion", "operations"] : ["operations"],
238
+ additionalProperties: false
239
+ }
240
+ });
105
241
  const definitionsFromRegistry = (registry) => Object.values(registry);
106
242
  /**
107
243
  * The tools this package exposes, described for an LLM. Every tool that reads
@@ -276,20 +412,7 @@ const FOLIO_AGENT_TOOL_REGISTRY = {
276
412
  additionalProperties: false
277
413
  }
278
414
  }),
279
- [FOLIO_AGENT_TOOL_NAMES.suggestChanges]: defineFolioAgentToolDefinition({
280
- name: FOLIO_AGENT_TOOL_NAMES.suggestChanges,
281
- 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.",
282
- inputSchema: {
283
- type: "object",
284
- properties: { operations: {
285
- type: "array",
286
- description: "The edits to propose, applied in order. At most 50 per call.",
287
- items: suggestChangesOperationSchema
288
- } },
289
- required: ["operations"],
290
- additionalProperties: false
291
- }
292
- }),
415
+ [FOLIO_AGENT_TOOL_NAMES.suggestChanges]: buildSuggestChangesToolDefinition(resolveSuggestChangesOptions()),
293
416
  [FOLIO_AGENT_TOOL_NAMES.replyComment]: defineFolioAgentToolDefinition({
294
417
  name: FOLIO_AGENT_TOOL_NAMES.replyComment,
295
418
  description: "Reply to an existing comment thread, referenced by the id from `read_comments`. `text` is capped at 100,000 characters.",
@@ -376,7 +499,17 @@ const FOLIO_AGENT_TOOL_REGISTRY = {
376
499
  })
377
500
  };
378
501
  const FOLIO_AGENT_TOOLS = definitionsFromRegistry(FOLIO_AGENT_TOOL_REGISTRY);
379
- /** The tool definitions this package exposes. Same array as {@link FOLIO_AGENT_TOOLS}, as a function for symmetry with the other providers. */
380
- const getFolioToolDefinitions = () => FOLIO_AGENT_TOOLS;
502
+ /**
503
+ * The tool definitions this package exposes. Without options this is
504
+ * {@link FOLIO_AGENT_TOOLS}; with `suggestChanges` options the
505
+ * `suggest_changes` definition is rebuilt for that surface. Pass the same
506
+ * options to `executeFolioToolCall` so the parser enforces what the schema
507
+ * advertises.
508
+ */
509
+ const getFolioToolDefinitions = (options = {}) => {
510
+ if (options.suggestChanges === void 0) return FOLIO_AGENT_TOOLS;
511
+ const suggestChanges = buildSuggestChangesToolDefinition(resolveSuggestChangesOptions(options.suggestChanges));
512
+ return FOLIO_AGENT_TOOLS.map((definition) => definition.name === FOLIO_AGENT_TOOL_NAMES.suggestChanges ? suggestChanges : definition);
513
+ };
381
514
  //#endregion
382
- export { FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_REGISTRY, SUGGEST_CHANGES_OPERATION_TYPES, getFolioToolDefinitions };
515
+ export { FOLIO_AGENT_TOOLS, FOLIO_AGENT_TOOL_REGISTRY, SUGGEST_CHANGES_OPERATION_TYPES, describeSuggestChangesCapabilities, getFolioToolDefinitions };
package/dist/types.d.ts CHANGED
@@ -176,18 +176,34 @@ type FolioAgentChange = {
176
176
  };
177
177
  /** Filter for {@link FOLIO_AGENT_TOOL_NAMES.readComments}. */
178
178
  type FolioAgentCommentFilter = "all" | "open" | "resolved";
179
+ /**
180
+ * One lenient-decoding step the parser took on a tool call's arguments
181
+ * (a `kind` key read as `type`, an operation supplied as a JSON string, a
182
+ * stray property dropped). Reported back to the model so sloppy calls
183
+ * still succeed without the normalisation going unnoticed.
184
+ */
185
+ type FolioAgentInputNormalization = {
186
+ /** Where in the arguments, e.g. `operations[2].kind`. */
187
+ path: string;
188
+ message: string;
189
+ };
179
190
  /** Result of {@link FOLIO_AGENT_TOOL_NAMES.addComment} / `suggest_changes`. */
180
191
  type FolioAgentApplyOperationsSummary = {
181
192
  version: typeof FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION;
182
193
  applied: {
183
194
  id: string;
184
195
  }[];
196
+ /** Operations a host review-queue bridge accepted for later human review instead of applying. */
197
+ queued: {
198
+ id: string;
199
+ }[];
185
200
  skipped: {
186
201
  id: string;
187
202
  reason: string;
188
203
  }[];
189
204
  issues: FolioDocumentOperationIssue[];
190
205
  receipts: FolioDocumentOperationReceipt[];
206
+ normalizations: FolioAgentInputNormalization[];
191
207
  };
192
208
  //#endregion
193
- export { FOLIO_AGENT_TOOL_NAMES, FolioAgentApplyOperationsSummary, FolioAgentBlock, FolioAgentChange, FolioAgentComment, FolioAgentCommentFilter, FolioAgentCommentReply, FolioAgentDocumentOutline, FolioAgentFindTextResult, FolioAgentJsonObjectSchema, FolioAgentOutlineEntry, FolioAgentScopedFindTextResult, FolioAgentSectionRead, FolioAgentStoryFindTextResult, FolioAgentStoryTextMatch, FolioAgentTextMatch, FolioAgentToolDefinition, FolioAgentToolName, FolioAgentTypedToolDefinition, FolioToolCallResult };
209
+ export { FOLIO_AGENT_TOOL_NAMES, FolioAgentApplyOperationsSummary, FolioAgentBlock, FolioAgentChange, FolioAgentComment, FolioAgentCommentFilter, FolioAgentCommentReply, FolioAgentDocumentOutline, FolioAgentFindTextResult, FolioAgentInputNormalization, FolioAgentJsonObjectSchema, FolioAgentOutlineEntry, FolioAgentScopedFindTextResult, FolioAgentSectionRead, FolioAgentStoryFindTextResult, FolioAgentStoryTextMatch, FolioAgentTextMatch, FolioAgentToolDefinition, FolioAgentToolName, FolioAgentTypedToolDefinition, FolioToolCallResult };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/folio-agents",
3
- "version": "0.9.8",
3
+ "version": "0.10.1",
4
4
  "description": "Framework-neutral LLM tool layer over folio's ai-edits engine: function-calling tools so an agent can read and mutate .docx documents through @stll/folio-core.",
5
5
  "keywords": [
6
6
  "agent",
@@ -54,7 +54,8 @@
54
54
  "test": "bun test src"
55
55
  },
56
56
  "dependencies": {
57
- "@stll/folio-core": "^0.31.0"
57
+ "@stll/folio-core": "^0.32.2",
58
+ "better-result": "3.0.1"
58
59
  },
59
60
  "main": "./dist/index.js",
60
61
  "types": "./dist/index.d.ts"
@@ -24,17 +24,20 @@ comment pending human review — nothing is silently finalized.
24
24
 
25
25
  ## Integration recipe
26
26
 
27
- 1. `getFolioToolDefinitions()` returns `FolioAgentToolDefinition[]` — plain
28
- `{ name, description, inputSchema }` objects with a conservative JSON
27
+ 1. `getFolioToolDefinitions(options?)` returns `FolioAgentToolDefinition[]` —
28
+ plain `{ name, description, inputSchema }` objects with a conservative JSON
29
29
  Schema subset (`type: "object"`, `properties`, `required`, `enum`,
30
30
  `additionalProperties: false`, plain arrays — safe for providers that
31
- reject uncommon keywords, e.g. Gemini's OpenAPI-3.0 subset).
31
+ reject uncommon keywords, e.g. Gemini's OpenAPI-3.0 subset). Pass
32
+ `{ suggestChanges }` options to shape `suggest_changes` for the surface
33
+ (see below) and pass the same object to `executeFolioToolCall`.
32
34
  2. Register them with your framework:
33
35
  - TanStack AI: pass `inputSchema` directly as `toolDefinition({ inputSchema })` — no wrapper needed.
34
36
  - Raw Anthropic/OpenAI SDKs: `toAnthropicTools(defs)` / `toOpenAITools(defs)`.
35
37
  - Vercel AI SDK: wrap each `inputSchema` in `jsonSchema()` from `ai`.
36
38
  3. In your tool-use loop, for every `tool_use` / `tool_call` the model emits:
37
- call `executeFolioToolCallUntyped(name, args, bridge)` → returns
39
+ call `executeFolioToolCallUntyped(name, args, bridge, { suggestChanges })`
40
+ with the same options object as step 1 → returns
38
41
  `{ ok: true, result } | { ok: false, error }`.
39
42
  4. Feed that result straight back to the model as the tool result message —
40
43
  both branches are meant to reach the model, not just the `ok: true` one:
@@ -73,20 +76,48 @@ unsupported rather than throwing — this is how the headless reviewer bridge
73
76
  signals `read_page` / `read_selection` / `scroll_to_block` as unsupported too,
74
77
  since a headless document has no live page/selection/scroll surface at all.
75
78
 
79
+ ## Configuring `suggest_changes`
80
+
81
+ `suggest_changes` is configured per host surface, never re-derived. Pass one
82
+ `FolioSuggestChangesOptions` object to both `getFolioToolDefinitions({
83
+ suggestChanges })` and `executeFolioToolCall(name, args, bridge, {
84
+ suggestChanges })`:
85
+
86
+ - `operationTypes`: any subset of the contract's operation types (default:
87
+ everything except `commentOnBlock`, covered by `add_comment`, and
88
+ `insertSignatureTable`, which is direct-only). The schema advertises only
89
+ the properties those types accept.
90
+ - `reviewMeta: "required"`: every operation must carry `severity` and `area`
91
+ (a review queue that sorts and groups needs them). Default `"optional"`.
92
+ - `maxOperations`: 1 to 200 per call, default 50.
93
+ - `documentVersion: { current }`: the model must echo the token; the executor
94
+ compares it to `bridge.getDocumentVersion()` and skips the whole batch with
95
+ `documentVersionMismatch` when the document moved on.
96
+
97
+ `describeSuggestChangesCapabilities(options)` returns the capability text the
98
+ tool description carries; paste it into a system prompt instead of
99
+ hand-writing a "what this tool can do" paragraph that drifts.
100
+
101
+ The parser decodes leniently (a `kind` key, an operation given as a JSON
102
+ string, a property that does not apply to the type) and reports each step in
103
+ the result's `normalizations`; it then enforces the caps, mints ids unique
104
+ across calls, and delegates every per-operation rule to
105
+ `parseFolioDocumentOperationBatch` in `@stll/folio-core`.
106
+
76
107
  ## Host-managed review queue
77
108
 
78
109
  A host that already has its own review-queue UX — its own place to store a
79
110
  model's proposed edits pending approval, separate from folio's
80
- tracked-changes redlines — can skip `executeFolioToolCall` for
81
- `suggest_changes` / `add_comment` and instead validate the model's tool-call
82
- arguments directly with `parseSuggestChangesInput` / `parseAddCommentInput`.
83
- These are the exact same validation rules `executeFolioToolCall` runs
84
- (argument shape, the 50-operation cap, the 100,000-character text caps),
85
- factored out so both the host's path and folio's own executor agree on what a
86
- valid `suggest_changes` / `add_comment` call looks like. On success they
87
- return the parsed `FolioAIEditOperation`(s) to route into the host's own
88
- queue; on failure they return the same plain-language `error` string meant to
89
- go straight back to the model.
111
+ tracked-changes redlines — writes a `FolioAgentBridge` whose
112
+ `applyDocumentOperations` enqueues the batch and returns `status: "queued"`
113
+ with the operations listed in `queued` (build `receipts` with
114
+ `getFolioDocumentOperationReceipts` from `@stll/folio-core/server`). The
115
+ executor then produces the standard envelope for the model (`queued`,
116
+ `skipped` with plain-language reasons, `receipts`, `normalizations`) and keeps
117
+ the automatic `precondition` stamping and the document-version check. A
118
+ surface with nothing editable reports every operation as skipped with
119
+ `documentNotEditable`. `parseSuggestChangesInput` / `parseAddCommentInput`
120
+ stay exported for validation-only paths.
90
121
 
91
122
  ## Ground rules for the model
92
123
 
@@ -105,14 +136,18 @@ go straight back to the model.
105
136
  - `suggest_changes` defaults to tracked-changes mode on both shipped bridges
106
137
  — it proposes redlines for a human to accept or reject, never edits the
107
138
  visible text directly.
108
- - The tool surface here is fixed: seven edit operation kinds
109
- (`replaceInBlock`, `replaceRange`, `commentOnRange`, `insertAfterBlock`,
110
- `insertBeforeBlock`, `replaceBlock`, `deleteBlock`) plus
111
- comment/reply/resolve. There is no
112
- `insertSignatureTable`-style structural op, and none should be invented —
113
- compose the seven primitives, or extend `@stll/folio-core`'s ai-edits engine
114
- itself if a document needs a structural operation this package doesn't
115
- expose.
139
+ - The operation kinds a surface accepts are exactly the ones in its
140
+ `suggest_changes` schema's `type` enum (by default `replaceInBlock`,
141
+ `replaceRange`, `commentOnRange`, `formatRange`, `insertAfterBlock`,
142
+ `insertBeforeBlock`, `replaceBlock`, `deleteBlock`, `insertTableRow`,
143
+ `deleteTableRow`, `insertTableColumn`, `deleteTableColumn`,
144
+ `mergeTableCells`, `splitTableCell`) plus comment/reply/resolve. Do not
145
+ invent an operation kind or a directive marker; if a document needs a
146
+ structural operation the contract lacks, extend `@stll/folio-core`'s
147
+ ai-edits engine and the contract, then the schema follows.
148
+ - A `queued` list in a `suggest_changes` result means the host parked those
149
+ operations in its own review queue; treat it like `applied` for the purpose
150
+ of "the edit has been proposed", never as a failure.
116
151
  - **Untrusted documents:** `read_document`, `read_comments`, `read_changes`,
117
152
  and `find_text` return document content verbatim, so a `.docx` from an
118
153
  untrusted party can inject prompt instructions straight into the model's