@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/README.md +86 -17
- package/dist/bridge.d.ts +9 -0
- package/dist/execute.d.ts +3 -2
- package/dist/execute.js +50 -33
- package/dist/index.d.ts +4 -3
- package/dist/index.js +3 -2
- package/dist/operation-schema.d.ts +1 -1
- package/dist/operation-schema.js +33 -1
- package/dist/parse.d.ts +22 -14
- package/dist/parse.js +234 -221
- package/dist/suggest-changes-options.d.ts +60 -0
- package/dist/suggest-changes-options.js +52 -0
- package/dist/tool-contract.d.ts +2 -0
- package/dist/tools.d.ts +31 -10
- package/dist/tools.js +238 -105
- package/dist/types.d.ts +17 -1
- package/package.json +3 -2
- package/skills/folio-agents/SKILL.md +57 -22
package/dist/parse.js
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
|
-
import {
|
|
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
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* `
|
|
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
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
-
*
|
|
139
|
-
*
|
|
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
|
|
145
|
-
if (
|
|
146
|
-
const
|
|
147
|
-
if (
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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
|
-
/**
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
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
|
-
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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 (
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
"
|
|
189
|
-
|
|
190
|
-
]
|
|
191
|
-
|
|
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
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
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
|
-
|
|
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
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
230
|
+
return {
|
|
231
|
+
operations,
|
|
232
|
+
documentVersion: args["documentVersion"],
|
|
233
|
+
normalizations
|
|
242
234
|
};
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
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
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
return {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
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
|
-
|
|
292
|
-
|
|
293
|
-
if (!
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
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
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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:
|
|
295
|
+
error: decoded
|
|
329
296
|
};
|
|
330
|
-
|
|
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
|
-
|
|
333
|
-
|
|
334
|
-
|
|
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:
|
|
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 {
|
|
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 };
|