@stll/folio-agents 0.16.12 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bridge.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { FolioAgentCommentId } from "./codecs.js";
1
+ import { FolioAgentCommentId, FolioAgentSuggestionStory } from "./codecs.js";
2
2
  import { FolioAgentChange, FolioAgentComment } from "./types.js";
3
3
  import { FolioAIEditSnapshot, FolioDocumentNavigationTarget, FolioDocumentOperationBatch, FolioDocumentOperationMode, FolioDocumentOperationResult, FolioDocumentOperationUndoHandle, FolioDocumentOperationUndoResult, FolioDocumentStory, FolioDocumentStoryHandle } from "@stll/folio-core/server";
4
4
  /**
@@ -47,6 +47,8 @@ export type FolioAgentBridge = {
47
47
  listStories?(): FolioDocumentStory[];
48
48
  /** Read one previously discovered story. */
49
49
  readStory?(handle: FolioDocumentStoryHandle): FolioDocumentStory | null;
50
+ /** Scope block snapshots and operations to an existing header or footer. */
51
+ forStory?(handle: FolioAgentSuggestionStory): FolioAgentBridge | null;
50
52
  /** Reply to a comment thread. Returns `false` when the target comment does not exist. */
51
53
  replyToComment(commentId: string, text: string): boolean;
52
54
  /** Mark a comment thread resolved or reopen it. Returns `false` when the target comment does not exist. */
@@ -3,6 +3,7 @@ import { decodeCommentId } from "../codecs.js";
3
3
  import { toAgentChange } from "./shared.js";
4
4
  import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, assertSupportedFolioDocumentOperationVersion, getFolioDocumentOperationIssues, getFolioDocumentOperationReceipts } from "@stll/folio-core/server";
5
5
  import { createReply } from "@stll/folio-core/docx/replyToComment";
6
+ import { createCommentIdAllocator } from "@stll/folio-core/prosemirror/commentIdAllocator";
6
7
  // src/bridges/editor-ref.ts
7
8
  const toAgentCommentReply = (reply) => ({
8
9
  id: String(reply.id),
@@ -51,9 +52,14 @@ const createEditorRefBridge = (options) => {
51
52
  const mode = options.mode ?? "tracked-changes";
52
53
  const replyToDecodedComment = (commentId, text) => {
53
54
  const comments = getComments();
54
- const reply = createReply(comments, commentId, {
55
- author,
56
- text
55
+ const reply = createReply({
56
+ comments,
57
+ parentCommentId: commentId,
58
+ input: {
59
+ author,
60
+ text
61
+ },
62
+ commentIds: createCommentIdAllocator()
57
63
  });
58
64
  if (!reply) return false;
59
65
  setComments([...comments, reply]);
@@ -14,9 +14,8 @@ export type CreateReviewerBridgeOptions = {
14
14
  };
15
15
  /**
16
16
  * Build a {@link FolioAgentBridge} over a headless {@link FolioDocxReviewer}
17
- * (`@stll/folio-core/server`). No optional capability members are
18
- * implemented: a headless document has no live page/selection/scroll
19
- * surface, so `read_page`, `read_selection`, and `scroll_to_block` report an
17
+ * (`@stll/folio-core/server`). A headless document has no live page, selection,
18
+ * or scroll surface, so `read_page`, `read_selection`, and `scroll_to_block` report an
20
19
  * unsupported-capability error via {@link executeFolioToolCall} on this
21
20
  * bridge.
22
21
  */
@@ -18,9 +18,8 @@ const toAgentComment = (comment) => ({
18
18
  });
19
19
  /**
20
20
  * Build a {@link FolioAgentBridge} over a headless {@link FolioDocxReviewer}
21
- * (`@stll/folio-core/server`). No optional capability members are
22
- * implemented: a headless document has no live page/selection/scroll
23
- * surface, so `read_page`, `read_selection`, and `scroll_to_block` report an
21
+ * (`@stll/folio-core/server`). A headless document has no live page, selection,
22
+ * or scroll surface, so `read_page`, `read_selection`, and `scroll_to_block` report an
24
23
  * unsupported-capability error via {@link executeFolioToolCall} on this
25
24
  * bridge.
26
25
  */
@@ -29,21 +28,47 @@ const createReviewerBridge = (reviewer, options = {}) => {
29
28
  const { revisionStamp } = options;
30
29
  const applyOptions = revisionStamp === void 0 ? {} : { revisionStamp };
31
30
  const replyDate = revisionStamp === void 0 ? {} : { date: revisionStamp.date };
31
+ const withMode = (batch) => batch.mode === void 0 ? {
32
+ ...batch,
33
+ mode
34
+ } : batch;
35
+ const operationOptions = {
36
+ ...applyOptions,
37
+ undefinedReferences: "refuse"
38
+ };
39
+ const registerBridge = (bridge) => {
40
+ registerOperationSession(bridge, reviewer);
41
+ return registerDecodedCommentHandlers(bridge, {
42
+ replyToComment: ({ numeric }, text) => reviewer.replyTo(numeric, {
43
+ text,
44
+ ...replyDate
45
+ }) !== null,
46
+ resolveComment: ({ raw }, resolved) => reviewer.resolveComment(raw, { resolved })
47
+ });
48
+ };
32
49
  const bridge = {
33
50
  snapshot: () => reviewer.snapshot(),
34
51
  documentOperationMode: mode,
35
- applyDocumentOperations: (batch) => reviewer.applyDocumentOperations(batch.mode === void 0 ? {
36
- ...batch,
37
- mode
38
- } : batch, {
39
- ...applyOptions,
40
- undefinedReferences: "refuse"
41
- }),
52
+ applyDocumentOperations: (batch) => reviewer.applyDocumentOperations(withMode(batch), operationOptions),
42
53
  undoDocumentOperations: (undoHandle) => reviewer.undoDocumentOperations(undoHandle),
43
54
  getComments: () => reviewer.getComments().map(toAgentComment),
44
55
  getChanges: () => reviewer.getChanges().map(toAgentChange),
45
56
  listStories: () => reviewer.listStories(),
46
57
  readStory: (handle) => reviewer.readStory(handle),
58
+ forStory: (story) => {
59
+ const snapshot = reviewer.snapshotStory(story);
60
+ if (snapshot === null) return null;
61
+ return registerBridge({
62
+ ...bridge,
63
+ snapshot: () => snapshot,
64
+ applyDocumentOperations: (batch) => reviewer.applyDocumentOperationsToStory({
65
+ ...operationOptions,
66
+ story,
67
+ batch: withMode(batch),
68
+ snapshot
69
+ })
70
+ });
71
+ },
47
72
  replyToComment: (commentId, text) => {
48
73
  const decoded = decodeCommentId(commentId);
49
74
  return decoded !== null && reviewer.replyTo(decoded.numeric, {
@@ -56,13 +81,6 @@ const createReviewerBridge = (reviewer, options = {}) => {
56
81
  return decoded !== null && reviewer.resolveComment(decoded.raw, { resolved });
57
82
  }
58
83
  };
59
- registerOperationSession(bridge, reviewer);
60
- return registerDecodedCommentHandlers(bridge, {
61
- replyToComment: ({ numeric }, text) => reviewer.replyTo(numeric, {
62
- text,
63
- ...replyDate
64
- }) !== null,
65
- resolveComment: ({ raw }, resolved) => reviewer.resolveComment(raw, { resolved })
66
- });
84
+ return registerBridge(bridge);
67
85
  };
68
86
  export { createReviewerBridge };
package/dist/codecs.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  import { FOLIO_TEXT_RANGE_JSON_SCHEMA } from "./operation-schema.js";
2
+ import { FolioAgentJsonObjectSchema } from "./types.js";
2
3
  import { FolioAITextRangeHandle, FolioDocumentSectionHandle, FolioDocumentStoryHandle } from "@stll/folio-core/server";
4
+ export type FolioAgentSuggestionStory = Extract<FolioDocumentStoryHandle, {
5
+ type: "header" | "footer";
6
+ }>;
7
+ export declare const FOLIO_SUGGESTION_STORY_JSON_SCHEMA: FolioAgentJsonObjectSchema;
3
8
  export declare const FOLIO_STORY_HANDLE_JSON_SCHEMA: {
4
9
  readonly type: "object";
5
10
  readonly properties: {
@@ -85,6 +90,8 @@ export type FolioAgentCommentId = {
85
90
  };
86
91
  export declare const decodeSectionHandle: (value: unknown) => FolioDocumentSectionHandle | null;
87
92
  export declare const decodeStoryHandle: (value: unknown) => FolioDocumentStoryHandle | null;
93
+ /** Decode the editable header/footer subset of a story handle. */
94
+ export declare const decodeSuggestionStory: (value: unknown) => FolioAgentSuggestionStory | null;
88
95
  export declare const decodeMainStoryTextRangeHandle: (value: unknown) => FolioAITextRangeHandle | null;
89
96
  export declare const decodeCommentId: (value: unknown) => FolioAgentCommentId | null;
90
97
  export { FOLIO_TEXT_RANGE_JSON_SCHEMA };
package/dist/codecs.js CHANGED
@@ -1,5 +1,21 @@
1
1
  import { FOLIO_TEXT_RANGE_JSON_SCHEMA } from "./operation-schema.js";
2
2
  // src/codecs.ts
3
+ const FOLIO_SUGGESTION_STORY_JSON_SCHEMA = {
4
+ type: "object",
5
+ properties: {
6
+ type: {
7
+ type: "string",
8
+ enum: ["header", "footer"]
9
+ },
10
+ relationshipId: {
11
+ type: "string",
12
+ minLength: 1
13
+ }
14
+ },
15
+ required: ["type", "relationshipId"],
16
+ additionalProperties: false,
17
+ description: "Header or footer handle from list_stories. Omit to edit the body."
18
+ };
3
19
  const NORMALIZED_TEXT_HASH_PATTERN = /^h[0-9a-z]+$/;
4
20
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
21
  const isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
@@ -121,6 +137,12 @@ const decodeStoryHandle = (value) => {
121
137
  }
122
138
  return null;
123
139
  };
140
+ /** Decode the editable header/footer subset of a story handle. */
141
+ const decodeSuggestionStory = (value) => {
142
+ if (!isPlainObject(value) || Object.keys(value).some((key) => key !== "type" && key !== "relationshipId")) return null;
143
+ const story = decodeStoryHandle(value);
144
+ return story?.type === "header" || story?.type === "footer" ? story : null;
145
+ };
124
146
  const decodeMainStoryTextRangeHandle = (value) => {
125
147
  if (!isPlainObject(value)) return null;
126
148
  const blockId = value["blockId"];
@@ -146,4 +168,4 @@ const decodeCommentId = (value) => {
146
168
  numeric
147
169
  };
148
170
  };
149
- export { FOLIO_COMMENT_ID_JSON_SCHEMA, FOLIO_SCOPED_HANDLE_JSON_SCHEMA, FOLIO_SECTION_HANDLE_JSON_SCHEMA, FOLIO_STORY_HANDLE_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, decodeCommentId, decodeMainStoryTextRangeHandle, decodeSectionHandle, decodeStoryHandle };
171
+ export { FOLIO_COMMENT_ID_JSON_SCHEMA, FOLIO_SCOPED_HANDLE_JSON_SCHEMA, FOLIO_SECTION_HANDLE_JSON_SCHEMA, FOLIO_STORY_HANDLE_JSON_SCHEMA, FOLIO_SUGGESTION_STORY_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, decodeCommentId, decodeMainStoryTextRangeHandle, decodeSectionHandle, decodeStoryHandle, decodeSuggestionStory };
package/dist/execute.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { FolioAgentToolName, FolioToolCallResult } from "./types.js";
2
1
  import { FolioAgentBridge } from "./bridge.js";
3
2
  import { FolioAgentToolOptions } from "./suggest-changes-options.js";
4
3
  import { FolioAgentToolInputByName, FolioToolCallResultFor } from "./tool-contract.js";
4
+ import { FolioAgentToolName, FolioToolCallResult } from "./types.js";
5
5
  /**
6
6
  * Execute one tool call against a {@link FolioAgentBridge}. Every EXPECTED
7
7
  * failure — bad arguments, an unknown tool name, a capability the bridge does
package/dist/execute.js CHANGED
@@ -144,7 +144,12 @@ const readStory = (args, bridge) => {
144
144
  const parsed = isPlainObject(args) ? decodeStoryHandle(args["handle"]) : null;
145
145
  if (parsed === null) return fail("read_story requires a valid typed `handle` from list_stories.");
146
146
  const story = bridge.readStory(parsed);
147
- return story ? ok(story) : fail("The requested story was not found; run list_stories again.");
147
+ if (story === null) return fail("The requested story was not found; run list_stories again.");
148
+ const scoped = parsed.type === "header" || parsed.type === "footer" ? bridge.forStory?.(parsed) : void 0;
149
+ return ok(scoped ? {
150
+ ...story,
151
+ blocks: scoped.snapshot().blocks.map(toAgentBlock)
152
+ } : story);
148
153
  };
149
154
  const CONTEXT_RADIUS = 40;
150
155
  const WORD_CHARACTER_AT_END = /[\p{L}\p{M}\p{N}_]$/u;
@@ -338,6 +343,10 @@ const explainSkipReason = (reason) => {
338
343
  if (reason === "missingStyle") return "`styleId` names no paragraph style this document defines (it is undefined, or a table or character style); nothing was applied. Use a paragraph style the document defines (the ones it offers are named after this reason), or `null` to clear the style.";
339
344
  if (reason === "pendingDeletion") return "this block is pending deletion (a tracked change deletes it; it reads as a blank block); nothing was applied, since text written there would join the next paragraph once the deletion is accepted. Reject that deletion first, or insert a new block next to it (insertAfterBlock / insertBeforeBlock).";
340
345
  if (reason === "pendingParagraphMarkDeletion") return "a paragraph mark this operation depends on is pending tracked deletion; nothing was applied. Resolve that change first.";
346
+ if (reason === "pendingParagraphMarkInsertion") return "a paragraph mark this operation would record over is pending tracked insertion; nothing was applied. Resolve that change first.";
347
+ if (reason === "pendingTableInsertion") return "the merge would run the paragraph, through one whose mark is pending deletion, into a table that is pending insertion; nothing was applied. Resolve the table's insertion or that deletion first.";
348
+ if (reason === "pendingTableChange") return "the table, row, cell or grid this operation changes already carries a pending tracked change (a row pending insertion or deletion, a property or grid change); nothing was applied. Resolve that change first.";
349
+ if (reason === "existingRevisionConflict") return "the edit touches another author's pending revision. Resolve that revision first or use existingRevisions: allow.";
341
350
  if (reason === "missingNumbering") return "`numbering` names a numbering instance this document does not define; nothing was applied. Re-read the document and use a `{ kind: \"reference\", numId, ilvl? }` the document defines (the one a neighbouring list item carries), or choose another numbering state.";
342
351
  if (reason === "invalidResult") return "applying this operation would have left a document that cannot be saved, so nothing from it was applied. Do not retry it as written; re-read the document and express the change differently.";
343
352
  return reason;
@@ -391,7 +400,7 @@ const rejectBatch = (operations, reason, normalizations) => {
391
400
  receipts: []
392
401
  }, normalizations);
393
402
  };
394
- const applyOperations = (bridge, { operations, precondition, normalizations = [] }) => {
403
+ const applyOperations = (bridge, { operations, precondition, existingRevisions, normalizations = [] }) => {
395
404
  const snapshot = bridge.snapshot();
396
405
  const guardedOperations = [];
397
406
  for (const operation of operations) {
@@ -409,7 +418,8 @@ const applyOperations = (bridge, { operations, precondition, normalizations = []
409
418
  return summarizeApplyResult(bridge.applyDocumentOperations(prepareFolioAgentDocumentOperationBatch({
410
419
  operations: guardedOperations,
411
420
  ...bridge.documentOperationMode !== void 0 && { mode: bridge.documentOperationMode },
412
- ...precondition !== void 0 && { precondition }
421
+ ...precondition !== void 0 && { precondition },
422
+ ...existingRevisions !== void 0 && { existingRevisions }
413
423
  })), normalizations);
414
424
  };
415
425
  const addComment = (args, bridge) => {
@@ -431,12 +441,7 @@ const canonicalJson = (value) => {
431
441
  if (isPlainObject(value)) return `{${Object.keys(value).toSorted().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
432
442
  return JSON.stringify(value) ?? "null";
433
443
  };
434
- /**
435
- * Split a call into operations to apply and operations the session already
436
- * applied or queued under the same id. An id resent with a different
437
- * operation is the caller's mistake, not a retry, and refuses the call.
438
- */
439
- const partitionReplays = (operations, ledger) => {
444
+ const partitionReplays = ({ operations, ledger, fingerprintOf }) => {
440
445
  const fresh = [];
441
446
  const replays = [];
442
447
  for (const [index, operation] of operations.entries()) {
@@ -445,7 +450,7 @@ const partitionReplays = (operations, ledger) => {
445
450
  fresh.push(operation);
446
451
  continue;
447
452
  }
448
- if (recorded.fingerprint !== canonicalJson(operation)) return `operations[${String(index)}].id "${operation.id}" already names a different operation this document applied. Give a new operation a new id, or omit ids to have them generated.`;
453
+ if (recorded.fingerprint !== fingerprintOf(operation)) return `operations[${String(index)}].id "${operation.id}" already names a different operation this document applied. Give a new operation a new id, or omit ids to have them generated.`;
449
454
  replays.push({
450
455
  index,
451
456
  id: operation.id,
@@ -458,12 +463,12 @@ const partitionReplays = (operations, ledger) => {
458
463
  };
459
464
  };
460
465
  /** Remember what landed. A skipped operation is not recorded, so resending it tries again. */
461
- const recordSettled = ({ ledger, operations, summary }) => {
466
+ const recordSettled = ({ ledger, operations, summary, fingerprintOf }) => {
462
467
  const settled = new Set([...summary.applied, ...summary.queued].map(({ id }) => id));
463
468
  for (const operation of operations) {
464
469
  if (!settled.has(operation.id)) continue;
465
470
  ledger.set(operation.id, {
466
- fingerprint: canonicalJson(operation),
471
+ fingerprint: fingerprintOf(operation),
467
472
  receipt: summary.receipts.find(({ operationId }) => operationId === operation.id)
468
473
  });
469
474
  }
@@ -511,8 +516,19 @@ const suggestChanges = (args, bridge, options) => {
511
516
  const parsed = parseSuggestChangesInput(args, options.suggestChanges);
512
517
  if (!parsed.ok) return fail(parsed.error);
513
518
  if (parsed.precondition !== void 0 && !bridge.getDocumentVersion) return fail("This editor surface cannot verify `documentVersion`; it has no document version to compare against.");
519
+ const scoped = parsed.story === void 0 ? bridge : bridge.forStory?.(parsed.story);
520
+ if (scoped === void 0) return fail("This editor surface cannot edit a header or footer story.");
521
+ if (scoped === null) return fail("The requested story was not found; run list_stories again.");
522
+ const fingerprintOf = (operation) => canonicalJson({
523
+ story: parsed.story,
524
+ operation
525
+ });
514
526
  const ledger = ledgerOf(bridge);
515
- const partitioned = partitionReplays(parsed.operations, ledger);
527
+ const partitioned = partitionReplays({
528
+ operations: parsed.operations,
529
+ ledger,
530
+ fingerprintOf
531
+ });
516
532
  if (typeof partitioned === "string") return fail(partitioned);
517
533
  const { fresh, replays } = partitioned;
518
534
  const applyFresh = () => {
@@ -524,8 +540,9 @@ const suggestChanges = (args, bridge, options) => {
524
540
  receipts: []
525
541
  }, parsed.normalizations);
526
542
  if (parsed.precondition !== void 0 && bridge.getDocumentVersion?.() !== parsed.precondition.documentVersion) return rejectBatch(fresh, "documentVersionMismatch", parsed.normalizations);
527
- return applyOperations(bridge, {
543
+ return applyOperations(scoped, {
528
544
  operations: fresh,
545
+ ...parsed.existingRevisions !== void 0 && { existingRevisions: parsed.existingRevisions },
529
546
  ...parsed.precondition !== void 0 && { precondition: parsed.precondition },
530
547
  normalizations: parsed.normalizations
531
548
  });
@@ -534,7 +551,8 @@ const suggestChanges = (args, bridge, options) => {
534
551
  recordSettled({
535
552
  ledger,
536
553
  operations: fresh,
537
- summary
554
+ summary,
555
+ fingerprintOf
538
556
  });
539
557
  return ok(withReplays({
540
558
  summary,
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
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, FolioAgentInputNormalization, FolioAgentOutlineEntry, FolioAgentScopedFindTextResult, FolioAgentSectionRead, FolioAgentStoryFindTextResult, FolioAgentStoryTextMatch, FolioAgentTextMatch, FolioAgentToolDefinition, FolioAgentToolName, FolioToolCallResult } from "./types.js";
3
1
  import { FolioAgentBridge } from "./bridge.js";
4
2
  import { CreateEditorRefBridgeOptions, FolioAgentEditorApplyDocumentOperationsOptions, FolioAgentEditorRefLike, createEditorRefBridge } from "./bridges/editor-ref.js";
5
3
  import { CreateReviewerBridgeOptions, createReviewerBridge } from "./bridges/reviewer.js";
6
4
  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";
8
5
  import { executeFolioToolCall, executeFolioToolCallUntyped } from "./execute.js";
6
+ import { FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, folioDocumentOperationBatchSchema } from "./operation-schema.js";
9
7
  import { ParseAddCommentResult, ParseSuggestChangesResult, parseAddCommentInput, parseSuggestChangesInput } from "./parse.js";
10
8
  import { AnthropicToolDefinition, OpenAIToolDefinition, toAnthropicTools, toOpenAITools } from "./providers.js";
9
+ import { DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, FolioAgentToolOptions, FolioSuggestChangesOptions, InvalidFolioSuggestChangesOptionsError } from "./suggest-changes-options.js";
11
10
  import { FOLIO_AGENT_TOOLS, describeSuggestChangesCapabilities, getFolioToolDefinitions } from "./tools.js";
11
+ 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";
12
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 };
@@ -1,4 +1,18 @@
1
- import { FolioDocumentOperationBatch } from "@stll/folio-core/server";
1
+ /**
2
+ * Reusable projections of folio's versioned document-operation contract for
3
+ * tool builders: a JSON Schema for one operation, a JSON Schema for the
4
+ * versioned batch envelope, and a Standard Schema V1 wrapper around
5
+ * `parseFolioDocumentOperationBatch` so downstream tool definitions (e.g.
6
+ * TanStack AI tools) can consume the contract directly instead of
7
+ * hand-mirroring it in valibot/zod.
8
+ *
9
+ * The strict throwing parser in `@stll/folio-core` stays the single source of
10
+ * truth for semantics; everything here is a projection of it. Constraints
11
+ * JSON Schema cannot express (`endOffset > startOffset`, unique operation
12
+ * ids within a batch, per-type mode support) are noted in `description`s and
13
+ * enforced by the parser.
14
+ */
15
+ import { FOLIO_LIST_NUMBER_FORMAT_VALUES, FolioDocumentOperationBatch } from "@stll/folio-core/server";
2
16
  import { LineSpacingRule, ParagraphAlignment } from "@stll/folio-core/types/document";
3
17
  /** Compact public shape for the runtime JSON Schema projections. */
4
18
  export type FolioJsonSchema = {
@@ -152,6 +166,18 @@ export declare const FOLIO_PARAGRAPH_NUMBERING_JSON_SCHEMA: {
152
166
  readonly minimum: 0;
153
167
  readonly maximum: 8;
154
168
  };
169
+ readonly numFmt: {
170
+ readonly type: "string";
171
+ readonly enum: typeof FOLIO_LIST_NUMBER_FORMAT_VALUES;
172
+ };
173
+ readonly lvlText: {
174
+ readonly type: "string";
175
+ };
176
+ readonly start: {
177
+ readonly type: "integer";
178
+ readonly minimum: 0;
179
+ readonly maximum: number;
180
+ };
155
181
  };
156
182
  readonly required: readonly ["kind", "format"];
157
183
  readonly additionalProperties: false;
@@ -300,6 +326,18 @@ export declare const FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA: {
300
326
  readonly minimum: 0;
301
327
  readonly maximum: 8;
302
328
  };
329
+ readonly numFmt: {
330
+ readonly type: "string";
331
+ readonly enum: typeof FOLIO_LIST_NUMBER_FORMAT_VALUES;
332
+ };
333
+ readonly lvlText: {
334
+ readonly type: "string";
335
+ };
336
+ readonly start: {
337
+ readonly type: "integer";
338
+ readonly minimum: 0;
339
+ readonly maximum: number;
340
+ };
303
341
  };
304
342
  readonly required: readonly ["kind", "format"];
305
343
  readonly additionalProperties: false;
@@ -392,6 +430,8 @@ export declare const FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA: {
392
430
  readonly minProperties: 1;
393
431
  readonly additionalProperties: false;
394
432
  };
433
+ export declare const INLINE_FORMATTING_JSON_SCHEMA: FolioJsonSchema;
434
+ export declare const MARKDOWN_INSERTION_TEXT_FORMAT_JSON_SCHEMA: FolioJsonSchema;
395
435
  /**
396
436
  * JSON Schema (draft-07 compatible) for ONE document operation: the full
397
437
  * union accepted by `parseFolioDocumentOperationBatch` in
@@ -402,14 +442,8 @@ export declare const FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA: {
402
442
  * narrows this union (see the comment there).
403
443
  */
404
444
  export declare const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA: FolioJsonSchema;
405
- /**
406
- * JSON Schema (draft-07 compatible) for the versioned batch envelope accepted
407
- * by `parseFolioDocumentOperationBatch`: `version` (always
408
- * `FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION`), `operations`, and the
409
- * optional `mode` / `atomic` / `dryRun` flags — the exact wire shape of
410
- * `FolioDocumentOperationBatch`. Hand this to an LLM tool definition (or any
411
- * JSON Schema consumer) instead of re-declaring the contract.
412
- */
445
+ export declare const FOLIO_EXISTING_REVISIONS_JSON_SCHEMA: FolioJsonSchema;
446
+ /** JSON Schema (draft-07 compatible) for a versioned document operation batch. */
413
447
  export declare const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA: FolioJsonSchema;
414
448
  /**
415
449
  * Minimal structural subset of the Standard Schema V1 interface
@@ -1,4 +1,4 @@
1
- import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, FOLIO_DOCUMENT_OPERATION_MODES, FOLIO_LINE_SPACING_RULE_VALUES, FOLIO_PAGE_BREAK_CLEAR_VALUES, FOLIO_PARAGRAPH_ALIGNMENT_VALUES, InvalidFolioDocumentOperationBatchError, UnsupportedFolioDocumentOperationVersionError, parseFolioDocumentOperationBatch } from "@stll/folio-core/server";
1
+ import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, FOLIO_DOCUMENT_OPERATION_MODES, FOLIO_EXISTING_REVISION_POLICIES, FOLIO_HIGHLIGHT_COLOR_VALUES, FOLIO_LINE_SPACING_RULE_VALUES, FOLIO_LIST_NUMBER_FORMAT_VALUES, FOLIO_PAGE_BREAK_CLEAR_VALUES, FOLIO_PARAGRAPH_ALIGNMENT_VALUES, InvalidFolioDocumentOperationBatchError, UnsupportedFolioDocumentOperationVersionError, parseFolioDocumentOperationBatch } from "@stll/folio-core/server";
2
2
  // src/operation-schema.ts
3
3
  /**
4
4
  * Reusable projections of folio's versioned document-operation contract for
@@ -273,13 +273,23 @@ const FOLIO_PARAGRAPH_NUMBERING_JSON_SCHEMA = {
273
273
  type: "integer",
274
274
  minimum: 0,
275
275
  maximum: 8
276
+ },
277
+ numFmt: {
278
+ type: "string",
279
+ enum: FOLIO_LIST_NUMBER_FORMAT_VALUES
280
+ },
281
+ lvlText: { type: "string" },
282
+ start: {
283
+ type: "integer",
284
+ minimum: 0,
285
+ maximum: Number.MAX_SAFE_INTEGER
276
286
  }
277
287
  },
278
288
  required: ["kind", "format"],
279
289
  additionalProperties: false
280
290
  }
281
291
  ],
282
- description: "A paragraph numbering request: `none` cancels numbering, `inherit` removes the direct numbering reference, `levelOnly` sets only `w:ilvl`, `reference` selects a defined numbering instance with an optional level override, and `newList` starts a list with the requested format."
292
+ description: "A paragraph numbering request: `none` cancels numbering, `inherit` removes the direct numbering reference, `levelOnly` sets only `w:ilvl`, `reference` selects a defined numbering instance with an optional level override, and `newList` starts a list with the requested template and optional numbering format, label text, and start value at the selected level."
283
293
  };
284
294
  const FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA = {
285
295
  type: "object",
@@ -362,6 +372,29 @@ const FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA = {
362
372
  minProperties: 1,
363
373
  additionalProperties: false
364
374
  };
375
+ const INLINE_FORMATTING_JSON_SCHEMA = {
376
+ type: "object",
377
+ description: "Inline formatting to apply. Set at least one property.",
378
+ properties: {
379
+ bold: { type: "boolean" },
380
+ italic: { type: "boolean" },
381
+ underline: { type: "boolean" },
382
+ highlight: {
383
+ description: "Named OOXML highlight color. Use \"none\" to disable highlighting or null to remove the direct value.",
384
+ oneOf: [{
385
+ type: "string",
386
+ enum: FOLIO_HIGHLIGHT_COLOR_VALUES
387
+ }, { type: "null" }]
388
+ }
389
+ },
390
+ minProperties: 1,
391
+ additionalProperties: false
392
+ };
393
+ const MARKDOWN_INSERTION_TEXT_FORMAT_JSON_SCHEMA = {
394
+ type: "string",
395
+ enum: ["markdown"],
396
+ description: "Parse text as Markdown paragraphs, headings, or a standalone flat list. For insertTable, supply one plain Markdown table without rows. Use without insertion formatting fields, moveId, or a comment."
397
+ };
365
398
  /**
366
399
  * JSON Schema (draft-07 compatible) for ONE document operation: the full
367
400
  * union accepted by `parseFolioDocumentOperationBatch` in
@@ -460,17 +493,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
460
493
  enum: ["formatRange"]
461
494
  },
462
495
  range: FOLIO_TEXT_RANGE_JSON_SCHEMA,
463
- formatting: {
464
- type: "object",
465
- description: "Inline formatting to apply; at least one property is required.",
466
- properties: {
467
- bold: { type: "boolean" },
468
- italic: { type: "boolean" },
469
- underline: { type: "boolean" }
470
- },
471
- minProperties: 1,
472
- additionalProperties: false
473
- }
496
+ formatting: INLINE_FORMATTING_JSON_SCHEMA
474
497
  },
475
498
  required: [
476
499
  "id",
@@ -496,6 +519,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
496
519
  type: "string",
497
520
  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. By default only the first paragraph gets `styleId` / `numbering` / `alignment` / `spacing` / `inheritFormatting` and later ones use body formatting; set `formattingScope: \"allParagraphs\"` to format every paragraph alike, for example several list items. Prefer one paragraph per operation otherwise."
498
521
  },
522
+ textFormat: MARKDOWN_INSERTION_TEXT_FORMAT_JSON_SCHEMA,
499
523
  inheritFormatting: {
500
524
  type: "boolean",
501
525
  description: "Inherit the anchor block's formatting for the inserted paragraph."
@@ -552,6 +576,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
552
576
  type: "string",
553
577
  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. By default only the first paragraph gets `styleId` / `numbering` / `alignment` / `spacing` / `inheritFormatting` and later ones use body formatting; set `formattingScope: \"allParagraphs\"` to format every paragraph alike, for example several list items. Prefer one paragraph per operation otherwise."
554
578
  },
579
+ textFormat: MARKDOWN_INSERTION_TEXT_FORMAT_JSON_SCHEMA,
555
580
  inheritFormatting: {
556
581
  type: "boolean",
557
582
  description: "Inherit the anchor block's formatting for the inserted paragraph."
@@ -748,6 +773,15 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
748
773
  enum: ["after", "before"],
749
774
  description: "Place the table after the anchor (default) or before it."
750
775
  },
776
+ textFormat: {
777
+ type: "string",
778
+ enum: ["markdown"],
779
+ description: "Insert a standalone Markdown table with plain, unaligned cells."
780
+ },
781
+ text: {
782
+ type: "string",
783
+ description: "The complete Markdown table."
784
+ },
751
785
  rows: {
752
786
  type: "array",
753
787
  description: "Cell texts row by row; every row must hold the same number of cells.",
@@ -760,9 +794,18 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
760
794
  required: [
761
795
  "id",
762
796
  "type",
763
- "blockId",
764
- "rows"
797
+ "blockId"
765
798
  ],
799
+ oneOf: [{
800
+ required: ["rows"],
801
+ properties: {
802
+ text: { not: {} },
803
+ textFormat: { not: {} }
804
+ }
805
+ }, {
806
+ required: ["text", "textFormat"],
807
+ properties: { rows: { not: {} } }
808
+ }],
766
809
  additionalProperties: false
767
810
  },
768
811
  {
@@ -908,7 +951,7 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
908
951
  },
909
952
  {
910
953
  type: "object",
911
- description: "Insert a column next to the column containing the anchor block.",
954
+ description: "Insert one or more adjacent columns next to the column containing the anchor block.",
912
955
  properties: {
913
956
  ...operationMetaProperties,
914
957
  ...suggestionIdProperty,
@@ -922,9 +965,15 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
922
965
  enum: ["after", "before"],
923
966
  description: "Insert after the anchor column (default) or before it. Defaults to \"after\"."
924
967
  },
968
+ columnCount: {
969
+ type: "integer",
970
+ minimum: 1,
971
+ maximum: 63,
972
+ description: "How many adjacent columns to insert (default 1). Tracked, they are one change: accepting or rejecting it resolves every one of them."
973
+ },
925
974
  cellTexts: {
926
975
  type: "array",
927
- description: "Initial text for newly created physical cells in row order.",
976
+ description: "Initial text for newly created physical cells in reading order: row by row, left to right within a row.",
928
977
  items: { type: "string" }
929
978
  }
930
979
  },
@@ -1006,14 +1055,12 @@ const FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA = {
1006
1055
  }
1007
1056
  ]
1008
1057
  };
1009
- /**
1010
- * JSON Schema (draft-07 compatible) for the versioned batch envelope accepted
1011
- * by `parseFolioDocumentOperationBatch`: `version` (always
1012
- * `FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION`), `operations`, and the
1013
- * optional `mode` / `atomic` / `dryRun` flags — the exact wire shape of
1014
- * `FolioDocumentOperationBatch`. Hand this to an LLM tool definition (or any
1015
- * JSON Schema consumer) instead of re-declaring the contract.
1016
- */
1058
+ const FOLIO_EXISTING_REVISIONS_JSON_SCHEMA = {
1059
+ type: "string",
1060
+ enum: FOLIO_EXISTING_REVISION_POLICIES,
1061
+ description: "Whether to refuse tracked edits inside another author's pending revision. Defaults to allow."
1062
+ };
1063
+ /** JSON Schema (draft-07 compatible) for a versioned document operation batch. */
1017
1064
  const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA = {
1018
1065
  type: "object",
1019
1066
  description: "A versioned batch of document operations. Operation ids must be unique within the batch (enforced by the parser, not expressible in JSON Schema).",
@@ -1037,6 +1084,7 @@ const FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA = {
1037
1084
  type: "boolean",
1038
1085
  description: "Reject the whole batch when any operation would be skipped."
1039
1086
  },
1087
+ existingRevisions: FOLIO_EXISTING_REVISIONS_JSON_SCHEMA,
1040
1088
  dryRun: {
1041
1089
  type: "boolean",
1042
1090
  description: "Preview the batch without mutating the document."
@@ -1108,4 +1156,4 @@ const folioDocumentOperationBatchSchema = {
1108
1156
  },
1109
1157
  jsonSchema: FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA
1110
1158
  };
1111
- export { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PARAGRAPH_NUMBERING_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, folioDocumentOperationBatchSchema };
1159
+ export { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_BATCH_JSON_SCHEMA, FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA, FOLIO_EXISTING_REVISIONS_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PARAGRAPH_NUMBERING_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, INLINE_FORMATTING_JSON_SCHEMA, MARKDOWN_INSERTION_TEXT_FORMAT_JSON_SCHEMA, folioDocumentOperationBatchSchema };
package/dist/parse.d.ts CHANGED
@@ -1,5 +1,19 @@
1
- import { FolioAgentInputNormalization } from "./types.js";
1
+ /**
2
+ * Validation-only parsers for `suggest_changes` / `add_comment` tool-call
3
+ * arguments — the canonical rules `execute.ts` runs before handing operations
4
+ * to a {@link FolioAgentBridge}, factored out so a host can validate a
5
+ * model's tool-call arguments with the exact same rules (a host review queue
6
+ * should prefer a queue bridge, see the README, but the parsers stay pure).
7
+ *
8
+ * `parseSuggestChangesInput` is a front door over the contract parser in
9
+ * `@stll/folio-core`, not a second parser: it decodes leniently (reporting
10
+ * every normalisation), enforces the agent-layer caps and the host's
11
+ * {@link FolioSuggestChangesOptions}, mints ids, wraps `comment` strings, and
12
+ * then delegates every per-operation rule to `parseFolioDocumentOperationBatch`.
13
+ */
14
+ import { FolioAgentSuggestionStory } from "./codecs.js";
2
15
  import { FolioSuggestChangesOptions } from "./suggest-changes-options.js";
16
+ import { FolioAgentInputNormalization } from "./types.js";
3
17
  import { FolioAIEditOperation, FolioDocumentOperationBatch, FolioDocumentOperationBatchPrecondition, FolioDocumentOperationMode } from "@stll/folio-core/server";
4
18
  /**
5
19
  * Hard caps on `suggest_changes` / `add_comment` / `reply_comment` input
@@ -33,6 +47,7 @@ export type PrepareFolioAgentDocumentOperationBatchOptions = {
33
47
  atomic?: boolean;
34
48
  dryRun?: boolean;
35
49
  precondition?: FolioDocumentOperationBatchPrecondition;
50
+ existingRevisions?: FolioDocumentOperationBatch["existingRevisions"];
36
51
  };
37
52
  /**
38
53
  * Wrap agent-preprocessed operations in the versioned batch envelope and
@@ -40,7 +55,7 @@ export type PrepareFolioAgentDocumentOperationBatchOptions = {
40
55
  * batch is safe to hand straight to `applyDocumentOperations`; core marks
41
56
  * parsed batches internally so the downstream apply path can skip reparsing.
42
57
  */
43
- export declare const prepareFolioAgentDocumentOperationBatch: ({ operations, mode, atomic, dryRun, precondition }: PrepareFolioAgentDocumentOperationBatchOptions) => FolioDocumentOperationBatch;
58
+ export declare const prepareFolioAgentDocumentOperationBatch: ({ operations, mode, atomic, dryRun, precondition, existingRevisions }: PrepareFolioAgentDocumentOperationBatchOptions) => FolioDocumentOperationBatch;
44
59
  /** Result of {@link parseAddCommentInput}. */
45
60
  export type ParseAddCommentResult = {
46
61
  ok: true;
@@ -59,8 +74,10 @@ export declare const parseAddCommentInput: (args: unknown) => ParseAddCommentRes
59
74
  export type ParseSuggestChangesResult = {
60
75
  ok: true;
61
76
  operations: FolioAIEditOperation[];
77
+ story?: FolioAgentSuggestionStory;
62
78
  /** Present when the call pinned a host document version. */
63
79
  precondition?: FolioDocumentOperationBatchPrecondition;
80
+ existingRevisions?: FolioDocumentOperationBatch["existingRevisions"];
64
81
  normalizations: FolioAgentInputNormalization[];
65
82
  } | {
66
83
  ok: false;
package/dist/parse.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { decodeSuggestionStory } from "./codecs.js";
1
2
  import { resolveSuggestChangesOptions } from "./suggest-changes-options.js";
2
3
  import { FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION, FOLIO_DOCUMENT_OPERATION_KEYS_BY_TYPE, InvalidFolioDocumentOperationBatchError, parseFolioDocumentOperationBatch } from "@stll/folio-core/server";
3
4
  // src/parse.ts
@@ -72,13 +73,14 @@ const consumeTextBudget = (budget, length) => {
72
73
  * batch is safe to hand straight to `applyDocumentOperations`; core marks
73
74
  * parsed batches internally so the downstream apply path can skip reparsing.
74
75
  */
75
- const prepareFolioAgentDocumentOperationBatch = ({ operations, mode, atomic, dryRun, precondition }) => parseFolioDocumentOperationBatch({
76
+ const prepareFolioAgentDocumentOperationBatch = ({ operations, mode, atomic, dryRun, precondition, existingRevisions }) => parseFolioDocumentOperationBatch({
76
77
  version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
77
78
  operations,
78
79
  ...mode !== void 0 && { mode },
79
80
  ...atomic !== void 0 && { atomic },
80
81
  ...dryRun !== void 0 && { dryRun },
81
- ...precondition !== void 0 && { precondition }
82
+ ...precondition !== void 0 && { precondition },
83
+ ...existingRevisions !== void 0 && { existingRevisions }
82
84
  });
83
85
  /**
84
86
  * Validate `add_comment`'s raw tool-call arguments and build the
@@ -130,7 +132,12 @@ const parseAddCommentInput = (args) => {
130
132
  }
131
133
  };
132
134
  };
133
- const SUGGEST_CHANGES_ARGUMENT_KEYS = ["operations", "documentVersion"];
135
+ const SUGGEST_CHANGES_ARGUMENT_KEYS = [
136
+ "operations",
137
+ "documentVersion",
138
+ "story",
139
+ "existingRevisions"
140
+ ];
134
141
  /** String-valued operation fields that count against the text caps. */
135
142
  const TEXT_FIELDS = [
136
143
  "find",
@@ -216,7 +223,8 @@ const decodeSuggestChangesInput = (rawArgs, options) => {
216
223
  const decoded = { type };
217
224
  for (const [key, value] of Object.entries(operation)) {
218
225
  if (key === typeKey) continue;
219
- if (allowedKeys.includes(key)) {
226
+ const unusedTableText = type === "insertTable" && key === "text" && operation["textFormat"] === void 0;
227
+ if (allowedKeys.includes(key) && !unusedTableText) {
220
228
  decoded[key] = value;
221
229
  continue;
222
230
  }
@@ -230,6 +238,8 @@ const decodeSuggestChangesInput = (rawArgs, options) => {
230
238
  return {
231
239
  operations,
232
240
  documentVersion: args["documentVersion"],
241
+ story: args["story"],
242
+ existingRevisions: args["existingRevisions"],
233
243
  normalizations
234
244
  };
235
245
  };
@@ -294,6 +304,11 @@ const parseSuggestChangesInput = (args, options) => {
294
304
  ok: false,
295
305
  error: decoded
296
306
  };
307
+ const story = decoded.story === void 0 ? void 0 : decodeSuggestionStory(decoded.story);
308
+ if (story === null) return {
309
+ ok: false,
310
+ error: "suggest_changes requires a header or footer story handle from list_stories."
311
+ };
297
312
  let precondition;
298
313
  if (resolved.documentVersion !== null) {
299
314
  if (!isNonEmptyString(decoded.documentVersion)) return {
@@ -340,11 +355,14 @@ const parseSuggestChangesInput = (args, options) => {
340
355
  const batch = parseFolioDocumentOperationBatch({
341
356
  version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
342
357
  operations: prepared,
358
+ existingRevisions: decoded.existingRevisions,
343
359
  ...precondition !== void 0 && { precondition }
344
360
  });
345
361
  return {
346
362
  ok: true,
347
363
  operations: [...batch.operations],
364
+ ...story !== void 0 && { story },
365
+ ...batch.existingRevisions !== void 0 && { existingRevisions: batch.existingRevisions },
348
366
  ...batch.precondition !== void 0 && { precondition: batch.precondition },
349
367
  normalizations: decoded.normalizations
350
368
  };
package/dist/tools.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { FolioAgentApplyOperationsSummary, FolioAgentBlock, FolioAgentChange, FolioAgentComment, FolioAgentCommentFilter, FolioAgentDocumentOutline, FolioAgentScopedFindTextResult, FolioAgentSectionRead, FolioAgentToolDefinition, FolioAgentTypedToolDefinition } from "./types.js";
1
+ import { FolioAgentSuggestionStory } from "./codecs.js";
2
2
  import { FolioAgentToolOptions, FolioSuggestChangesOptions } from "./suggest-changes-options.js";
3
3
  import { FolioAgentFindTextScope, FolioAgentShowInDocumentArgs } from "./tool-contract.js";
4
- import { FolioDocumentOperationType, FolioDocumentSectionHandle, FolioDocumentStory, FolioDocumentStoryHandle } from "@stll/folio-core/server";
4
+ import { FolioAgentApplyOperationsSummary, FolioAgentBlock, FolioAgentChange, FolioAgentComment, FolioAgentCommentFilter, FolioAgentDocumentOutline, FolioAgentScopedFindTextResult, FolioAgentSectionRead, FolioAgentToolDefinition, FolioAgentTypedToolDefinition } from "./types.js";
5
+ import { FolioDocumentOperationBatch, FolioDocumentOperationType, FolioDocumentSectionHandle, FolioDocumentStory, FolioDocumentStoryHandle } from "@stll/folio-core/server";
5
6
  /**
6
7
  * `suggest_changes` is a host-configurable projection of the document-operation
7
8
  * contract (see `FOLIO_DOCUMENT_OPERATION_JSON_SCHEMA` in `operation-schema.ts`):
@@ -45,7 +46,9 @@ export declare const FOLIO_AGENT_TOOL_REGISTRY: {
45
46
  readonly list_stories: FolioAgentTypedToolDefinition<"list_stories", Readonly<Record<string, never>>, FolioDocumentStory[]>;
46
47
  readonly read_story: FolioAgentTypedToolDefinition<"read_story", {
47
48
  handle: FolioDocumentStoryHandle;
48
- }, FolioDocumentStory>;
49
+ }, FolioDocumentStory & {
50
+ blocks?: FolioAgentBlock[];
51
+ }>;
49
52
  readonly find_text: FolioAgentTypedToolDefinition<"find_text", {
50
53
  query: string;
51
54
  matchCase?: boolean;
@@ -67,6 +70,8 @@ export declare const FOLIO_AGENT_TOOL_REGISTRY: {
67
70
  readonly suggest_changes: FolioAgentTypedToolDefinition<"suggest_changes", {
68
71
  operations: unknown[];
69
72
  documentVersion?: string;
73
+ story?: FolioAgentSuggestionStory;
74
+ existingRevisions?: FolioDocumentOperationBatch["existingRevisions"];
70
75
  }, FolioAgentApplyOperationsSummary>;
71
76
  readonly reply_comment: FolioAgentTypedToolDefinition<"reply_comment", {
72
77
  commentId: string;
package/dist/tools.js CHANGED
@@ -1,5 +1,5 @@
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
- import { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PARAGRAPH_NUMBERING_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA } from "./operation-schema.js";
1
+ import { FOLIO_COMMENT_ID_JSON_SCHEMA, FOLIO_SCOPED_HANDLE_JSON_SCHEMA, FOLIO_SECTION_HANDLE_JSON_SCHEMA, FOLIO_STORY_HANDLE_JSON_SCHEMA, FOLIO_SUGGESTION_STORY_JSON_SCHEMA } from "./codecs.js";
2
+ import { FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA, FOLIO_CLEARABLE_OUTLINE_LEVEL_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA, FOLIO_CLEARABLE_PARAGRAPH_STYLE_ID_JSON_SCHEMA, FOLIO_EXISTING_REVISIONS_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_JSON_SCHEMA, FOLIO_HARD_PAGE_BREAK_OPERATION_CONSTRAINT, FOLIO_INSERT_FORMATTING_SCOPE_JSON_SCHEMA, FOLIO_PARAGRAPH_NUMBERING_JSON_SCHEMA, FOLIO_PRECONDITION_JSON_SCHEMA, FOLIO_TEXT_RANGE_JSON_SCHEMA, INLINE_FORMATTING_JSON_SCHEMA, MARKDOWN_INSERTION_TEXT_FORMAT_JSON_SCHEMA } from "./operation-schema.js";
3
3
  import { DEFAULT_SUGGEST_CHANGES_OPERATION_TYPES, resolveSuggestChangesOptions } from "./suggest-changes-options.js";
4
4
  import { defineFolioAgentToolDefinition } from "./tool-contract.js";
5
5
  import { FOLIO_AGENT_TOOL_NAMES } from "./types.js";
@@ -38,7 +38,7 @@ const OPERATION_TYPE_SUMMARIES = {
38
38
  insertSignatureTable: "insert a side-by-side signature table for the given `parties`",
39
39
  insertTableRow: "insert a table row next to the row containing a cell block",
40
40
  deleteTableRow: "delete the table row containing a cell block",
41
- insertTableColumn: "insert a table column next to the column containing a cell block",
41
+ insertTableColumn: "insert one or `columnCount` adjacent table columns next to the column containing a cell block",
42
42
  deleteTableColumn: "delete the table column containing a cell block",
43
43
  mergeTableCells: "merge table cells from a cell block to `endBlockId`, or `rowCount` rows downward",
44
44
  splitTableCell: "split a previously merged table cell"
@@ -78,6 +78,12 @@ const OPERATION_PROPERTY_SCHEMAS = {
78
78
  minLength: 1,
79
79
  description: "For cell merging, a block in the opposite corner cell."
80
80
  },
81
+ columnCount: {
82
+ type: "integer",
83
+ minimum: 1,
84
+ maximum: 63,
85
+ description: "For column insertion, how many adjacent columns to insert (default 1); they are one change, accepted or rejected together."
86
+ },
81
87
  rowCount: {
82
88
  type: "integer",
83
89
  minimum: 2,
@@ -123,6 +129,7 @@ const OPERATION_PROPERTY_SCHEMAS = {
123
129
  },
124
130
  spacing: FOLIO_CLEARABLE_PARAGRAPH_SPACING_JSON_SCHEMA,
125
131
  indentation: FOLIO_CLEARABLE_PARAGRAPH_INDENTATION_JSON_SCHEMA,
132
+ textFormat: MARKDOWN_INSERTION_TEXT_FORMAT_JSON_SCHEMA,
126
133
  lineBreakMode: {
127
134
  type: "string",
128
135
  enum: ["paragraph", "inline"],
@@ -168,7 +175,7 @@ const OPERATION_PROPERTY_SCHEMAS = {
168
175
  },
169
176
  rows: {
170
177
  type: "array",
171
- description: "Required for `insertTable`: cell texts row by row. Every row must hold the same number of cells.",
178
+ description: "For `insertTable`, provide equally sized rows of cell texts or one plain Markdown table in text.",
172
179
  items: {
173
180
  type: "array",
174
181
  items: { type: "string" }
@@ -176,20 +183,13 @@ const OPERATION_PROPERTY_SCHEMAS = {
176
183
  },
177
184
  cellTexts: {
178
185
  type: "array",
179
- description: "For row or column insertion, initial text for new physical cells in source order, up to 100,000 characters per cell.",
186
+ description: "For row or column insertion, initial text for new physical cells in reading order (row by row, left to right), up to 100,000 characters per cell.",
180
187
  maxItems: 256,
181
188
  items: { type: "string" }
182
189
  },
183
190
  formatting: {
184
- type: "object",
185
- description: "Required for `formatRange`: set one or more inline properties to enable or disable.",
186
- properties: {
187
- bold: { type: "boolean" },
188
- italic: { type: "boolean" },
189
- underline: { type: "boolean" }
190
- },
191
- minProperties: 1,
192
- additionalProperties: false
191
+ ...INLINE_FORMATTING_JSON_SCHEMA,
192
+ description: "Required for `formatRange`. Set one or more inline properties."
193
193
  },
194
194
  properties: {
195
195
  ...FOLIO_BLOCK_PARAGRAPH_PROPERTIES_JSON_SCHEMA,
@@ -279,13 +279,15 @@ const describeResolvedCapabilities = (resolved) => {
279
279
  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.");
280
280
  return lines.join("\n");
281
281
  };
282
- 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.";
282
+ 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. To edit a header or footer, pass its `story` handle from `list_stories` and use block ids and hashes from `read_story`.";
283
283
  const buildSuggestChangesToolDefinition = (resolved) => defineFolioAgentToolDefinition({
284
284
  name: FOLIO_AGENT_TOOL_NAMES.suggestChanges,
285
285
  description: `${SUGGEST_CHANGES_BASE_DESCRIPTION}\n${describeResolvedCapabilities(resolved)}`,
286
286
  inputSchema: {
287
287
  type: "object",
288
288
  properties: {
289
+ story: FOLIO_SUGGESTION_STORY_JSON_SCHEMA,
290
+ existingRevisions: FOLIO_EXISTING_REVISIONS_JSON_SCHEMA,
289
291
  ...resolved.documentVersion !== null && { documentVersion: {
290
292
  type: "string",
291
293
  enum: [resolved.documentVersion.current],
@@ -372,7 +374,7 @@ const FOLIO_AGENT_TOOL_REGISTRY = {
372
374
  }),
373
375
  [FOLIO_AGENT_TOOL_NAMES.readStory]: defineFolioAgentToolDefinition({
374
376
  name: FOLIO_AGENT_TOOL_NAMES.readStory,
375
- description: "Read one document story using a handle returned by `list_stories`.",
377
+ description: "Read a story using a handle from `list_stories`. Editable headers and footers include blocks and hashes for `suggest_changes`.",
376
378
  inputSchema: {
377
379
  type: "object",
378
380
  properties: { handle: FOLIO_STORY_HANDLE_JSON_SCHEMA },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/folio-agents",
3
- "version": "0.16.12",
3
+ "version": "0.17.0",
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",
@@ -58,12 +58,12 @@
58
58
  "test": "bun test src"
59
59
  },
60
60
  "dependencies": {
61
- "@stll/folio-core": "^0.69.0",
61
+ "@stll/folio-core": "^0.70.0",
62
62
  "@stll/utf8-boundaries": "0.2.0",
63
63
  "better-result": "3.0.1"
64
64
  },
65
65
  "devDependencies": {
66
- "@stll/docx-core": "0.43.1"
66
+ "@stll/docx-core": "0.44.0"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "prosemirror-commands": "^1.7.1",
@@ -166,6 +166,14 @@ stay exported for validation-only paths.
166
166
  mark, or its table row) reads as a blank block; `replaceBlock` on it skips
167
167
  (`pendingDeletion`), since accepting would join the new text to the next
168
168
  paragraph. Reject that deletion first, or insert a new block next to it.
169
+ - A paragraph whose mark alone is pending deletion (a tracked change joins it
170
+ to the next paragraph) keeps its properties until that change is resolved:
171
+ `setBlockParagraphProperties` skips (`pendingParagraphMarkDeletion`), since
172
+ accepting the join gives the joined paragraph the next paragraph's
173
+ properties. Resolve that change first, or state the joined paragraph's
174
+ properties with `mergedParagraphProperties` on the `mergeBlockWithNext`
175
+ that joins them. A `replaceBlock` there skips (`pendingDeletion`) only when
176
+ the paragraph's words are all pending deletion.
169
177
  - Successful mutations return input-ordered `receipts`. Use their typed
170
178
  `affected` targets to identify updated blocks, stable ranges, insertions,
171
179
  and created comments without inferring effects from document text.
@@ -194,6 +202,10 @@ stay exported for validation-only paths.
194
202
  column, so the row has fewer cells there; more `cellTexts` than cells is
195
203
  refused as `payloadDoesNotFit` (the issue's `message` names the texts), never
196
204
  truncated. The same holds for `insertTableColumn` across a horizontal merge.
205
+ - `insertTableColumn` with `columnCount` inserts that many adjacent columns as
206
+ one change; its `cellTexts` fill the new cells row by row, left to right.
207
+ Insert every column of one change in one operation: a second tracked column
208
+ insertion in a table whose columns already have a pending change is refused.
197
209
  - A `queued` list in a `suggest_changes` result means the host parked those
198
210
  operations in its own review queue; treat it like `applied` for the purpose
199
211
  of "the edit has been proposed", never as a failure.