-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathagentic-tools-head.js
More file actions
3312 lines (2856 loc) · 144 KB
/
agentic-tools-head.js
File metadata and controls
3312 lines (2856 loc) · 144 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global Word */
import { applyRedlineToOxml, applyReconciliationToParagraphBatch, ReconciliationPipeline, wrapInDocumentFragment, parseTable, getAuthorForTracking } from '../reconciliation/index.js';
import { applyHighlightToOoxml } from '../../ooxml-formatting-removal.js';
import {
detectDocumentFont,
markdownToWordHtml,
markdownToWordHtmlInline,
hasBlockElements,
hasInlineMarkdownFormatting,
preprocessMarkdownForParagraph,
applyFormatHintsToRanges,
applyFormatRemovalToRanges,
parseMarkdownList,
normalizeContentEscapes
} from '../utils/markdown-utils.js';
let loadApiKey;
let loadModel;
let loadSystemMessage;
let loadRedlineSetting;
let loadRedlineAuthor;
let setChangeTrackingForAi;
let restoreChangeTracking;
let SEARCH_LIMITS;
let SAFETY_SETTINGS_BLOCK_NONE;
let API_LIMITS;
function initAgenticTools(deps) {
({
loadApiKey,
loadModel,
loadSystemMessage,
loadRedlineSetting,
loadRedlineAuthor,
setChangeTrackingForAi,
restoreChangeTracking,
SEARCH_LIMITS,
SAFETY_SETTINGS_BLOCK_NONE,
API_LIMITS
} = deps);
}
/**
* Agentic Tool: Applies redlines based on an instruction using Structural Anchoring.
*/
async function executeRedline(instruction, fullDocumentText) {
// Check for API key
const geminiApiKey = loadApiKey();
if (!geminiApiKey) {
return "Error: Please set your Gemini API key in the Settings.";
}
try {
// Detect document font for consistent HTML insertion
await detectDocumentFont();
// 1. Build the prompt for the diff generator
const fullPrompt = `You are an expert legal editor. Review the document content (provided with [P#] anchors) based on the user's instruction.
Generate a JSON array of precise changes to be made, referencing the paragraph numbers.
CRITICAL: Return ONLY valid JSON. Do NOT include explanatory text, notes, or duplicate entries.
Each change must be an object with the following structure:
- "paragraphIndex": The integer number of the paragraph to modify (e.g., 1 for [P1]). For "replace_range", this is the START paragraph.
- "endParagraphIndex": (Only for "replace_range") The integer number of the END paragraph (inclusive).
- "operation": "edit_paragraph", "replace_paragraph", "modify_text", or "replace_range".
- "newContent": (For "edit_paragraph" ONLY) The complete rewritten paragraph content. The system will automatically compute precise word-level changes.
- "content": (For "replace_paragraph" and "replace_range" ONLY) The new content to insert.
- "originalText": (For "modify_text" ONLY) The specific text snippet within the paragraph to find and replace. **MAX 80 characters**.
- "replacementText": (For "modify_text" ONLY) The new text to replace "originalText" with.
**MARKDOWN FORMATTING (VERY IMPORTANT)**:
All content and replacementText values support Markdown formatting. Use these when the user requests formatting:
- **Bold**: Use **text** (double asterisks)
- *Italic*: Use *text* (single asterisks)
- **Underline**: Use ++text++ (double pluses)
- ~~Strikethrough~~: Use ~~text~~ (double tildes)
- ***Bold Italic***: Use ***text*** (triple asterisks)
- **Unordered/Bullet lists**: Use "- item" or "* item" on separate lines. These render as bullet points (•).
- **Ordered/Numbered lists**: Use "1. item", "2. item" on separate lines. These render as 1, 2, 3...
- **Alphabetical lists (A, B, C)**: Use "A. item", "B. item" on separate lines. Use lowercase "a. item" for a, b, c. Use "I.", "II." for roman numerals.
- Line breaks: Use actual newlines (\\n) in the text
- Tables: Use GitHub-style markdown tables:
| Header 1 | Header 2 |
|----------|----------|
| Cell 1 | Cell 2 |
- Headings: Use # for H1, ## for H2, ### for H3
**CRITICAL LIST FORMATTING RULES**:
- **PRESERVE HIERARCHY**: If the document uses nested numbering (1.1, 1.1.1, etc.), ALWAYS use that same hierarchical format in your changes. **Do NOT flatten nested lists** into simple numbered lists (1., 2., 3.) unless specifically asked to restructure the hierarchy.
- **INCLUDE MARKERS**: Always include the correct list marker (e.g., "1.1.1 ") at the start of your \`newContent\` or \`content\` for list items. The system will use these to correctly set the indentation level in Word, and then it will automatically strip them from the final text.
- **NO MIXING**: NEVER mix bullet markers with manual numbering like "• (a)" or "- 1." - this creates malformed output
- **MARKDOWN SYNTAX**:
- For bullets: use "- " or "* "
- For simple numbers: use "1. ", "2. "
- For hierarchical numbers: use "1.1. ", "1.1.1. "
- **STRIPPING**: When converting existing lists, REMOVE the original markers from your response and use ONLY the markdown syntax described above.
When the user asks for formatted content (bullets, tables, bold, etc.), ALWAYS use the appropriate Markdown syntax.
Rules:
- **PRIORITIZE \`edit_paragraph\`**: This is the NEW preferred method. For ANY text edit (small or large), use \`edit_paragraph\` with the complete rewritten paragraph. The system will automatically compute precise word-level changes using diff-match-patch. This is more reliable than \`modify_text\`.
- Use "edit_paragraph" for ALL text edits: spelling changes, word replacements, sentence rewrites, or even 60% paragraph rewrites. Just provide the full new paragraph content.
- Use "replace_paragraph" only when you need to replace with complex formatted content (lists, tables, headings) that requires HTML insertion.
- Use "modify_text" ONLY as a fallback for very specific surgical edits where you need to target exact substrings.
- **CRITICAL LENGTH LIMIT**: For "modify_text", "originalText" MUST be **80 characters or fewer**. This is a hard limit.
- Use "replace_range" when you need to replace multiple consecutive paragraphs (like converting a bulleted list to a single paragraph).
- For "replace_range", provide ONLY "paragraphIndex", "endParagraphIndex", "operation", and "content". Do NOT include "originalText" or "replacementText".
- For "edit_paragraph", provide ONLY "paragraphIndex", "operation", and "newContent".
- For "modify_text", "originalText" must match EXACTLY text found within that specific paragraph.
- Do NOT include the [P#] marker in any content fields.
- Return ONLY ONE change per unique text location. Do NOT create duplicate entries.
IMPORTANT: This document may contain existing tracked changes. The text shown represents the "accepted" state (as if all changes were accepted). Your changes will be applied as additional tracked changes on top of existing ones.
USER INSTRUCTION:
"${instruction}"
DOCUMENT CONTENT:
"""${fullDocumentText}"""
Return ONLY the JSON array, nothing else:`;
// 2. Call Gemini to get the JSON array of changes
const aiChanges = await callGeminiForDiffs(fullPrompt);
console.log("AI Suggested Changes (raw):", aiChanges);
if (!aiChanges || !Array.isArray(aiChanges)) {
return {
message: "AI did not return a valid list of changes. Please check the console logs for details.",
showToUser: false // Silent error - let the model handle it
};
}
if (aiChanges.length === 0) {
return {
message: "AI had no changes to suggest based on the instruction.",
showToUser: false // Silent - let the model try again or respond
};
}
let changesApplied = 0;
const redlineEnabled = loadRedlineSetting();
// 3. Apply changes in Word
await Word.run(async (context) => {
const trackingState = await setChangeTrackingForAi(context, redlineEnabled, "executeRedline");
try {
// Load paragraphs with all properties needed by routeChangeOperation to avoid syncs in the loop
const paragraphs = context.document.body.paragraphs;
paragraphs.load("items/text, items/style, items/parentTableCellOrNullObject, items/parentTableOrNullObject, items/font/name, items/font/size, items/parentTableOrNullObject/id");
paragraphs.load("items/text, items/style, items/parentTableCellOrNullObject, items/parentTableOrNullObject, items/font/name, items/font/size, items/parentTableOrNullObject/id");
context.document.load("changeTrackingMode");
await context.sync();
const baseTrackingMode = context.document.changeTrackingMode;
// Track the current paragraph count (may change as we add/remove paragraphs)
let currentParagraphCount = paragraphs.items.length;
const batchedEditResultsByChangeIndex = new Map();
// Batch simple edit_paragraph operations to reduce context.sync round-trips.
// Keep complex/table/empty-paragraph edits on the existing per-change path.
const batchCandidates = [];
const seenBatchParagraphs = new Set();
for (let changeIndex = 0; changeIndex < aiChanges.length; changeIndex++) {
const change = aiChanges[changeIndex];
if (!change || change.operation !== "edit_paragraph" || !change.newContent) {
continue;
}
const pIndex = change.paragraphIndex - 1;
if (pIndex < 0 || pIndex >= currentParagraphCount) {
continue;
}
if (seenBatchParagraphs.has(pIndex)) {
continue;
}
const targetParagraph = paragraphs.items[pIndex];
if (!targetParagraph) {
continue;
}
if (!targetParagraph.text || targetParagraph.text.trim().length === 0) {
continue;
}
const inTableCell = targetParagraph.parentTableCellOrNullObject && !targetParagraph.parentTableCellOrNullObject.isNullObject;
const inTable = targetParagraph.parentTableOrNullObject && !targetParagraph.parentTableOrNullObject.isNullObject;
if (inTableCell || inTable) {
continue;
}
const normalizedNewContent = normalizeContentEscapes(change.newContent || "");
const parsedBatchListData = parseMarkdownList(normalizedNewContent);
const hasStructuredList = normalizedNewContent.includes('\n') && parsedBatchListData && parsedBatchListData.type !== 'text';
if (hasBlockElements(normalizedNewContent) || hasStructuredList) {
continue;
}
batchCandidates.push({
changeIndex,
paragraph: targetParagraph,
newText: normalizedNewContent
});
seenBatchParagraphs.add(pIndex);
}
if (batchCandidates.length > 1) {
try {
const redlineAuthor = loadRedlineAuthor();
const batchResult = await applyReconciliationToParagraphBatch(
batchCandidates.map(candidate => ({
paragraph: candidate.paragraph,
newText: candidate.newText
})),
context,
{
generateRedlines: redlineEnabled,
author: redlineAuthor,
disableNativeTracking: redlineEnabled,
nativeTrackingMode: baseTrackingMode
}
);
batchResult.results.forEach((result, resultIndex) => {
const candidate = batchCandidates[resultIndex];
if (!candidate || !result || !result.success) {
if (candidate) {
console.warn(`[executeRedline] Batched edit failed for change ${candidate.changeIndex}: ${result?.message || 'unknown error'}`);
}
return;
}
batchedEditResultsByChangeIndex.set(candidate.changeIndex, result);
if (result.changed) {
changesApplied++;
}
});
console.log(`[executeRedline] Batched edit_paragraph processed: ${batchResult.message}`);
} catch (batchError) {
console.warn("[executeRedline] Batched edit_paragraph path failed, falling back to per-change path:", batchError);
}
}
let aiChangeIndex = -1;
for (const change of aiChanges) {
aiChangeIndex++;
try {
console.log("Processing change:", JSON.stringify(change));
const batchedResult = batchedEditResultsByChangeIndex.get(aiChangeIndex);
if (batchedResult) {
console.log(`[executeRedline] Applied batched edit for change ${aiChangeIndex}: ${batchedResult.message}`);
continue;
}
const pIndex = change.paragraphIndex - 1; // 0-based index
// Check if this is an insertion at the end (index equals or exceeds paragraph count)
// We're lenient here - any index beyond current count is treated as an append
const isInsertAtEnd = pIndex >= currentParagraphCount;
// Only reject negative indices - positive ones that exceed count are handled as appends
if (pIndex < 0) {
console.warn(`Invalid paragraph index (negative): ${change.paragraphIndex}`);
continue;
}
// For out-of-bounds indices, reload paragraphs and check again
if (pIndex >= paragraphs.items.length) {
// Reload paragraphs collection to get any newly added ones
// Reload paragraphs collection with all properties to maintain performance
paragraphs.load("items/text, items/style, items/parentTableCellOrNullObject, items/parentTableOrNullObject, items/font/name, items/font/size, items/parentTableOrNullObject/id");
await context.sync();
currentParagraphCount = paragraphs.items.length;
// If still out of bounds after reload, treat as append to last paragraph
if (pIndex >= paragraphs.items.length) {
console.log(`Paragraph index ${change.paragraphIndex} exceeds count (${paragraphs.items.length}), treating as append`);
}
}
// For insertions at the end, use the last paragraph as reference
const targetParagraph = (pIndex >= paragraphs.items.length)
? paragraphs.items[paragraphs.items.length - 1]
: paragraphs.items[pIndex];
if (change.operation === "edit_paragraph") {
console.log(`Editing Paragraph ${change.paragraphIndex} with DMP`);
if (!change.newContent) {
console.warn("No newContent provided for edit_paragraph. Skipping.");
continue;
}
try {
// If inserting at end, insert new paragraph instead of editing
if (isInsertAtEnd) {
console.log(`Inserting new paragraph after paragraph ${paragraphs.items.length}`);
targetParagraph.insertParagraph(change.newContent, "After");
await context.sync(); // Sync immediately to ensure tracked changes captures the insertion
changesApplied++;
} else {
// Route through our smart operation router with preloaded properties
await routeChangeOperation(change, targetParagraph, context, true);
changesApplied++;
}
} catch (error) {
console.error(`Error editing paragraph ${change.paragraphIndex}:`, error);
// Fallback to old modify_text approach if DMP fails
}
} else if (change.operation === "replace_paragraph") {
console.log(`Replacing Paragraph ${change.paragraphIndex}`);
if (change.content === null || change.content === undefined) {
console.warn("Content is null/undefined for replace_paragraph. Skipping.");
continue;
}
// Normalize content: Convert literal escape sequences to actual characters
// This handles cases where the AI returns "\\n" as a two-character string instead of actual newlines
let normalizedContent = normalizeContentEscapes(change.content || "");
// --- NEW: Detect if target paragraph is already a list item ---
// If so, we need to preserve its numId/ilvl when replacing content
let targetIsListItem = false;
let targetListContext = null;
if (!isInsertAtEnd) {
try {
const targetOoxmlResult = targetParagraph.getOoxml();
await context.sync();
// Check for w:numPr in the paragraph's OOXML
// Check for w:numPr in the paragraph's OOXML - use robust regex for different XML serializations
const numPrMatch = targetOoxmlResult.value.match(/<(?:w:)?numPr>[\s\S]*?<(?:w:)?ilvl\s+(?:w:)?val="(\d+)"[\s\S]*?<(?:w:)?numId\s+(?:w:)?val="(\d+)"[\s\S]*?<\/(?:w:)?numPr>/i);
if (numPrMatch) {
targetIsListItem = true;
targetListContext = {
ooxml: targetOoxmlResult.value,
ilvl: numPrMatch[1],
numId: numPrMatch[2]
};
console.log(`[replace_paragraph] Target P${change.paragraphIndex} is list item: numId=${targetListContext.numId}, ilvl=${targetListContext.ilvl}`);
}
} catch (ooxmlError) {
console.warn("[replace_paragraph] Could not check list context:", ooxmlError);
}
}
const hasHeadingMarkdown = /^\s*#{1,9}\s+/m.test(normalizedContent);
const hasMarkdownTable = /^\s*\|.*\|/m.test(normalizedContent) && normalizedContent.includes('\n');
const hasMixedTable = hasMarkdownTable && normalizedContent.replace(/^\s*\|.*$/gm, '').trim().length > 0;
// If target is a list item and content is plain text (no list markers),
// use OOXML reconciliation to preserve list formatting
const contentHasListMarkers = /^(\s*)([-*•]|\d+\.|[a-zA-Z]\.|[ivxlcIVXLC]+\.|\d+\.\d+\.?)\s+/m.test(normalizedContent);
const contentHasStructuralMarkers = contentHasListMarkers || hasHeadingMarkdown || hasMarkdownTable;
console.log(`[replace_paragraph] contentHasListMarkers: ${contentHasListMarkers}`);
if (targetIsListItem && !contentHasStructuralMarkers) {
console.log(`[replace_paragraph] Preserving list context for plain text edit`);
try {
const redlineEnabled = loadRedlineSetting();
const redlineAuthor = loadRedlineAuthor();
// Get original text for diffing
const originalText = targetParagraph.text;
await context.sync();
// Use OOXML reconciliation to preserve numPr
const result = await applyRedlineToOxml(
targetListContext.ooxml,
originalText,
normalizedContent,
{
author: redlineEnabled ? redlineAuthor : undefined,
generateRedlines: redlineEnabled
}
);
if (result.oxml && result.hasChanges) {
const doc = context.document;
// changeTrackingMode is pre-loaded as baseTrackingMode
if (redlineEnabled && baseTrackingMode !== Word.ChangeTrackingMode.off) {
doc.changeTrackingMode = Word.ChangeTrackingMode.off;
await context.sync();
}
try {
targetParagraph.insertOoxml(result.oxml, "Replace");
await context.sync();
console.log("✅ OOXML list-preserving edit successful");
changesApplied++;
} finally {
if (redlineEnabled && baseTrackingMode !== Word.ChangeTrackingMode.off) {
doc.changeTrackingMode = baseTrackingMode;
await context.sync();
}
}
continue; // Skip other handlers
}
} catch (listPreserveError) {
console.warn("[replace_paragraph] List preservation failed, falling back:", listPreserveError);
// Fall through to standard handlers
}
}
// --- END NEW ---
// Check if this is a list or block content with headings/tables - use OOXML pipeline for proper redlines
const listData = parseMarkdownList(normalizedContent);
console.log(`[replace_paragraph] listData result: type=${listData?.type}, items=${listData?.items?.length}`);
const shouldUseBlockPipeline = (listData && listData.type !== 'text') || hasMixedTable;
if (shouldUseBlockPipeline) {
const listLabel = listData && listData.type !== 'text' ? listData.type : 'block';
console.log(`Detected ${listLabel} content in replace_paragraph, using OOXML pipeline`);
try {
// Get original paragraph info for proper diff/redlines and font inheritance
// Only get original text if we're REPLACING (not appending)
let originalTextForDeletion = '';
let paragraphFont = null;
if (!isInsertAtEnd) {
// pre-loaded in initial batch
originalTextForDeletion = targetParagraph.text;
// Get font info for inheritance
if (targetParagraph.font) {
// pre-loaded in initial batch
paragraphFont = targetParagraph.font.name;
console.log(`[ListGen] Inheriting font from original paragraph: ${paragraphFont} ${targetParagraph.font.size}pt`);
}
}
// Create reconciliation pipeline with redline settings
const redlineEnabled = loadRedlineSetting();
const redlineAuthor = loadRedlineAuthor();
const pipeline = new ReconciliationPipeline({
generateRedlines: redlineEnabled,
author: redlineAuthor,
font: paragraphFont || 'Calibri' // Inherit font from original paragraph
});
// Execute block generation (list/table/headings) - this creates OOXML with w:ins/w:del track changes
const result = await pipeline.executeListGeneration(
normalizedContent,
null, // numberingContext - let pipeline determine
null, // originalRunModel - not available here
originalTextForDeletion // Only pass original text if replacing, not appending
);
const listOoxml = result?.ooxml || result?.oxml || "";
const listIsValid = result?.isValid !== false;
console.log(`[ListGen] Generated ${listOoxml.length} bytes of OOXML, isInsertAtEnd=${isInsertAtEnd}`);
if (listOoxml && listIsValid) {
// Wrap in document fragment for insertOoxml
const wrappedOoxml = wrapInDocumentFragment(listOoxml, {
includeNumbering: true,
numberingXml: result.numberingXml // Crucial for A, B, C styles
});
// Temporarily disable Word's track changes to avoid double-tracking
// Our w:ins/w:del ARE the track changes
const doc = context.document;
// changeTrackingMode is pre-loaded as baseTrackingMode
if (redlineEnabled && baseTrackingMode !== Word.ChangeTrackingMode.off) {
doc.changeTrackingMode = Word.ChangeTrackingMode.off;
await context.sync();
}
try {
// Use 'After' if appending at end, 'Replace' if replacing existing paragraph
const insertMode = isInsertAtEnd ? 'After' : 'Replace';
console.log(`[ListGen] Using insert mode: ${insertMode}`);
await insertOoxmlWithRangeFallback(targetParagraph, wrappedOoxml, insertMode, context, "replace_paragraph/ListGen");
console.log(`✅ OOXML list generation successful`);
// TEMP: Spacing workaround disabled - causes GeneralException
// Will investigate OOXML structure instead
/*
// WORKAROUND: Insert a dummy spacing paragraph after the list, then remove it
// This forces Word to properly re-evaluate and link the list structure
try {
// Get all paragraphs to find the newly inserted list items
const paragraphs = context.document.body.paragraphs;
paragraphs.load("items/text");
targetParagraph.load("index");
await context.sync();
// Find the paragraph at the target index (after replacement/insertion)
const targetIdx = targetParagraph.index;
// Calculate how many list items were inserted
const listItemCount = listData.items.length;
// Insert dummy paragraph after the last list item
if (targetIdx + listItemCount - 1 < paragraphs.items.length) {
const lastListItem = paragraphs.items[targetIdx + listItemCount - 1];
const dummyPara = lastListItem.insertParagraph("", "After");
await context.sync();
console.log(`[ListGen] Inserted dummy spacing paragraph after ${listItemCount} list items`);
// Force Word to re-evaluate
await context.sync();
// TEMP: Leave dummy paragraph to test if it fixes formatting
// dummyPara.delete();
// await context.sync();
console.log(`[ListGen] Left dummy spacing paragraph for testing`);
}
} catch (spacingError) {
console.warn(`[ListGen] Spacing workaround failed (non-critical):`, spacingError.message);
}
*/
changesApplied++;
} finally {
// Restore track changes mode
if (redlineEnabled && baseTrackingMode !== Word.ChangeTrackingMode.off) {
doc.changeTrackingMode = baseTrackingMode;
await context.sync();
}
}
} else {
const warnings = Array.isArray(result?.warnings) ? result.warnings.join("; ") : "none";
throw new Error(`[ListGen] OOXML pipeline returned invalid list result (isValid=${result?.isValid}, hasOoxml=${!!listOoxml}, warnings=${warnings})`);
}
} catch (listError) {
console.error(`Error in OOXML list generation:`, listError);
throw listError;
}
// Skip the rest of replace_paragraph handling
continue;
}
// Check if this is a table - use OOXML pipeline
const matchedTable = normalizedContent.includes('|');
if (matchedTable) {
const tableData = parseTable(normalizedContent);
if (tableData.rows.length > 0 || tableData.headers.length > 0) {
console.log(`Detected table in replace_paragraph, using OOXML pipeline`);
try {
// Create reconciliation pipeline with redline settings
const redlineEnabled = loadRedlineSetting();
const redlineAuthor = loadRedlineAuthor();
const pipeline = new ReconciliationPipeline({
generateRedlines: redlineEnabled,
author: redlineAuthor
});
// Execute table generation - this creates OOXML with w:tbl and optional w:ins
const result = pipeline.executeTableGeneration(normalizedContent);
if (result.ooxml && result.isValid) {
// Wrap in document fragment
const wrappedOoxml = wrapInDocumentFragment(result.ooxml, {
includeNumbering: false
});
// Disable track changes temporarily
const doc = context.document;
// changeTrackingMode is pre-loaded
if (redlineEnabled && baseTrackingMode !== Word.ChangeTrackingMode.off) {
doc.changeTrackingMode = Word.ChangeTrackingMode.off;
await context.sync();
}
try {
const insertMode = isInsertAtEnd ? 'After' : 'Replace';
console.log(`[TableGen] Using insert mode: ${insertMode}`);
targetParagraph.insertOoxml(wrappedOoxml, insertMode);
await context.sync();
console.log(`✅ OOXML table generation successful`);
changesApplied++;
} finally {
if (redlineEnabled && baseTrackingMode !== Word.ChangeTrackingMode.off) {
doc.changeTrackingMode = baseTrackingMode;
await context.sync();
}
}
} else {
console.warn('[TableGen] Pipeline failed, falling back to HTML');
const htmlContent = markdownToWordHtml(normalizedContent);
targetParagraph.insertHtml(htmlContent, isInsertAtEnd ? "After" : "Replace");
changesApplied++;
}
} catch (tableError) {
console.error(`Error in OOXML table generation:`, tableError);
const htmlContent = markdownToWordHtml(normalizedContent);
targetParagraph.insertHtml(htmlContent, isInsertAtEnd ? "After" : "Replace");
changesApplied++;
}
// Skip the rest of replace_paragraph handling
continue;
}
}
// Convert Markdown to Word-compatible HTML for regular content
let htmlContent = "";
try {
htmlContent = markdownToWordHtml(normalizedContent);
} catch (markedError) {
console.error("Error parsing markdown:", markedError);
htmlContent = normalizedContent; // Fallback to raw text
}
// Strip wrapping <p> if present to avoid double paragraphs if Word handles it
// But only if it's a single simple paragraph (no block elements inside)
const trimmed = htmlContent.trim();
const hasSingleParagraph = trimmed.startsWith('<p>') && trimmed.endsWith('</p>') &&
trimmed.indexOf('</p>', 3) === trimmed.length - 4 &&
!trimmed.includes('<ul>') && !trimmed.includes('<ol>') &&
!trimmed.includes('<table') && !trimmed.includes('<h');
if (hasSingleParagraph) {
htmlContent = trimmed.substring(3, trimmed.length - 4);
}
try {
// If inserting at end, use insertParagraph to add new content after
if (isInsertAtEnd) {
console.log(`Inserting new paragraph after paragraph ${paragraphs.items.length}`);
// Use insertParagraph to add new paragraph after the last one
const newPara = targetParagraph.insertParagraph(normalizedContent, "After");
await context.sync(); // Sync immediately to ensure tracked changes captures the insertion
changesApplied++;
} else {
targetParagraph.insertHtml(htmlContent, "Replace");
changesApplied++;
}
} catch (wordError) {
console.error(`Error replacing paragraph ${change.paragraphIndex}:`, wordError);
}
} else if (change.operation === "replace_range") {
const endIndex = change.endParagraphIndex - 1;
if (endIndex < 0 || endIndex >= paragraphs.items.length || endIndex < pIndex) {
console.warn(`Invalid end paragraph index: ${change.endParagraphIndex}`);
continue;
}
console.log(`Replacing Range from P${change.paragraphIndex} to P${change.endParagraphIndex}`);
try {
const startPara = paragraphs.items[pIndex];
const endPara = paragraphs.items[endIndex];
// Check if we are inside a table - wrap in try/catch for safety
let startHasTable = false;
let endHasTable = false;
try {
// Properties pre-loaded: items/parentTableOrNullObject/id
startHasTable = !startPara.parentTableOrNullObject.isNullObject;
endHasTable = !endPara.parentTableOrNullObject.isNullObject;
} catch (tableCheckError) {
console.warn("Could not check for table context:", tableCheckError);
// Continue without table detection
}
let targetRange = null;
let isTableReplacement = false;
let tableToDelete = null;
// If both start and end are in the same table
if (startHasTable && endHasTable) {
try {
const startTable = startPara.parentTableOrNullObject;
const endTable = endPara.parentTableOrNullObject;
if (startTable.id === endTable.id) {
console.log("Detected same table context. Will replace entire table.");
// Strategy: Insert AFTER the table, then delete the table.
// This avoids GeneralException when replacing complex structures directly.
targetRange = startTable.getRange();
isTableReplacement = true;
tableToDelete = startTable;
} else {
console.warn("Start and End paragraphs are in DIFFERENT tables. Falling back to standard range expansion.");
targetRange = startPara.getRange().expandTo(endPara.getRange());
}
} catch (tableError) {
console.warn("Error handling table replacement, falling back to range:", tableError);
targetRange = startPara.getRange().expandTo(endPara.getRange());
}
} else {
// Create a range covering both
targetRange = startPara.getRange().expandTo(endPara.getRange());
}
// Use 'content' field for replace_range (not replacementText)
const contentToParse = change.content || change.replacementText || "";
if (!contentToParse || contentToParse.trim().length === 0) {
console.warn("Empty content for replace_range. Skipping.");
continue;
}
// --- NEW: Detect list structures and use OOXML engine for proper numPr ---
const hasListMarkers = /^(\s*)([-*•]|\d+\.|[a-zA-Z]\.|[ivxlcIVXLC]+\.|\d+\.\d+\.?)\s+/m.test(contentToParse);
if (hasListMarkers && !isTableReplacement) {
console.log("[replace_range] Detected list markers, using OOXML reconciliation");
try {
// Get the original text from the range for diffing
targetRange.load("text");
const originalOoxmlResult = startPara.getOoxml(); // Get OOXML from first paragraph
await context.sync();
const originalText = targetRange.text || "";
const redlineEnabled = loadRedlineSetting();
const redlineAuthor = loadRedlineAuthor();
// Use the OOXML engine for proper list generation
const result = await applyRedlineToOxml(
originalOoxmlResult.value,
originalText,
contentToParse,
{
author: redlineEnabled ? redlineAuthor : undefined,
generateRedlines: redlineEnabled
}
);
if (result.oxml && result.hasChanges) {
// Temporarily disable track changes to avoid double-tracking
const doc = context.document;
// changeTrackingMode is pre-loaded
if (redlineEnabled && baseTrackingMode !== Word.ChangeTrackingMode.off) {
doc.changeTrackingMode = Word.ChangeTrackingMode.off;
await context.sync();
}
try {
targetRange.insertOoxml(result.oxml, "Replace");
await context.sync();
changesApplied++;
console.log("✅ OOXML list reconciliation successful for replace_range");
} finally {
if (redlineEnabled && baseTrackingMode !== Word.ChangeTrackingMode.off) {
doc.changeTrackingMode = baseTrackingMode;
await context.sync();
}
}
continue; // Skip HTML fallback
}
} catch (ooxmlError) {
console.warn("[replace_range] OOXML reconciliation failed, falling back to HTML:", ooxmlError);
// Fall through to HTML path
}
}
// --- END NEW ---
// Convert Markdown to Word-compatible HTML (fallback for non-list or table content)
let htmlContent = "";
try {
htmlContent = markdownToWordHtml(contentToParse);
} catch (markedError) {
console.error("Error parsing markdown for range:", markedError);
htmlContent = contentToParse;
}
if (isTableReplacement && tableToDelete) {
// Insert AFTER the table
if (htmlContent && htmlContent.trim().length > 0) {
targetRange.insertHtml(htmlContent, "After");
}
// Delete the old table
tableToDelete.delete();
changesApplied++;
} else if (targetRange) {
// Standard replacement
try {
targetRange.insertHtml(htmlContent, "Replace");
changesApplied++;
} catch (replaceError) {
console.warn("Standard insertHtml failed. Trying fallback (Clear + InsertStart).", replaceError);
// Fallback: Clear and insert at start
try {
targetRange.clear(); // Clears content but keeps range
targetRange.insertHtml(htmlContent, "Start");
changesApplied++;
} catch (fallbackError) {
console.warn("Fallback (Clear+InsertStart) failed. Trying Nuclear Option (InsertText+InsertHtml).", fallbackError);
// Fallback 2: Nuke with text first to reset formatting
try {
// Replace with a placeholder to reset structure
const tempRange = targetRange.insertText(" ", "Replace");
tempRange.insertHtml(htmlContent, "Replace");
changesApplied++;
} catch (nuclearError) {
console.error("Replacement failed:", nuclearError);
}
}
}
}
} catch (rangeError) {
console.error(`Error replacing range P${change.paragraphIndex}-P${change.endParagraphIndex}:`, rangeError);
}
} else if (change.operation === "modify_text") {
console.log(`Modifying text in Paragraph ${change.paragraphIndex}: "${change.originalText}" -> "${change.replacementText}"`);
// Safety check for search string length - Word API has strict limits
const fullOriginalText = change.originalText;
if (!fullOriginalText || fullOriginalText.length === 0) {
console.warn(`Empty search text for modify_text in Paragraph ${change.paragraphIndex}. Skipping.`);
continue;
}
// Word's search API has a practical limit of around 80 characters
const MAX_SEARCH_LENGTH = 80;
const needsRangeExpansion = fullOriginalText.length > MAX_SEARCH_LENGTH;
const searchText = needsRangeExpansion
? fullOriginalText.substring(0, MAX_SEARCH_LENGTH)
: fullOriginalText;
if (needsRangeExpansion) {
console.warn(`Search text too long (${fullOriginalText.length} chars), using range expansion strategy.`);
}
try {
// Search ONLY within this paragraph
const searchResults = targetParagraph.search(searchText, { matchCase: true });
searchResults.load("items/text");
await context.sync();
if (searchResults.items.length > 0) {
// Apply to first match only when using range expansion (to avoid ambiguity)
const matchesToProcess = needsRangeExpansion ? [searchResults.items[0]] : searchResults.items;
for (const item of matchesToProcess) {
const replacementText = change.replacementText || "";
let htmlReplacement = "";
try {
// Use inline parsing for modify_text to avoid wrapping in <p> tags
// unless the content has block elements
htmlReplacement = markdownToWordHtmlInline(replacementText);
} catch (markedError) {
console.error("Error parsing markdown for modify_text:", markedError);
htmlReplacement = replacementText;
}
// Strip wrapping <p> for simple inline content
const trimmed = htmlReplacement.trim();
const hasSingleParagraph = trimmed.startsWith('<p>') && trimmed.endsWith('</p>') &&
trimmed.indexOf('</p>', 3) === trimmed.length - 4 &&
!trimmed.includes('<ul>') && !trimmed.includes('<ol>') &&
!trimmed.includes('<table') && !trimmed.includes('<h');
if (hasSingleParagraph) {
htmlReplacement = trimmed.substring(3, trimmed.length - 4);
}
try {
if (needsRangeExpansion) {
// Expand the range to cover the full original text length
// Strategy: Find a short suffix from the END of the original text,
// then expand the range from prefix start to suffix end
const foundRange = item.getRange();
try {
// Take the LAST 60 chars of the original text as our suffix search
// This must be short enough for Word's search API
const SUFFIX_LENGTH = 60;
const suffixStart = Math.max(0, fullOriginalText.length - SUFFIX_LENGTH);
const suffixText = fullOriginalText.substring(suffixStart);
console.log(`Range expansion: searching for suffix "${suffixText.substring(0, 30)}..." (${suffixText.length} chars)`);
if (suffixText.length >= 5 && suffixText.length <= 80) {
const suffixResults = targetParagraph.search(suffixText, { matchCase: true });
suffixResults.load("items/text");
await context.sync();
if (suffixResults.items.length > 0) {
// Find the suffix match that comes after our prefix match
// by expanding from the found prefix to each suffix candidate
let expandedSuccessfully = false;
for (const suffixMatch of suffixResults.items) {
try {
// Expand from found prefix start to suffix end
const expandedRange = foundRange.expandTo(suffixMatch.getRange("End"));
expandedRange.load("text");
await context.sync();
// Verify the expanded range roughly matches the original length
// Allow some tolerance for whitespace differences
const expandedLength = expandedRange.text.length;
const originalLength = fullOriginalText.length;
const tolerance = Math.max(10, originalLength * 0.1);
if (Math.abs(expandedLength - originalLength) <= tolerance) {
console.log(`Expanded range matches: ${expandedLength} chars (original: ${originalLength})`);
// Use insertHtml with "Replace" for atomic replacement (avoids stale range bug)
expandedRange.insertHtml(htmlReplacement || "", "Replace");
changesApplied++;
expandedSuccessfully = true;
break;
} else {
console.log(`Expanded range length mismatch: ${expandedLength} vs ${originalLength}, trying next suffix match`);
}
} catch (expandError) {
console.warn("Could not expand to this suffix match:", expandError.message);
}
}
if (!expandedSuccessfully) {
// None of the suffix matches worked, fall back to prefix only
console.warn("No valid suffix match found, falling back to prefix-only replacement");
// Use insertHtml with "Replace" for atomic replacement
item.insertHtml(htmlReplacement || "", "Replace");
changesApplied++;
}
} else {
// Suffix not found, fall back to just the found range
console.warn("Could not find suffix for range expansion, applying to found range only");
// Use insertHtml with "Replace" for atomic replacement
item.insertHtml(htmlReplacement || "", "Replace");
changesApplied++;
}
} else {
// Suffix invalid length, fall back to just the found range
console.warn(`Suffix length invalid (${suffixText.length}), applying to found range only`);
// Use insertHtml with "Replace" for atomic replacement
item.insertHtml(htmlReplacement || "", "Replace");
changesApplied++;
}
} catch (expandError) {
console.warn("Range expansion failed, applying to found range only:", expandError.message);
// Use insertHtml with "Replace" for atomic replacement
item.insertHtml(htmlReplacement || "", "Replace");
changesApplied++;
}
} else {
// Standard case: exact match, delete then insert for clean redline
// Use insertHtml with "Replace" for atomic replacement
item.insertHtml(htmlReplacement || "", "Replace");
changesApplied++;
}
} catch (modifyError) {
console.error("Error applying modify_text:", modifyError);
}
}
} else {
console.warn(`Could not find text "${searchText}" in Paragraph ${change.paragraphIndex}`);
}
} catch (searchError) {
console.warn(`Search failed for modify_text "${searchText}" in Paragraph ${change.paragraphIndex}:`, searchError.message);
// Fallback: Try with a shorter search string
if (searchText.length > 30) {
const shorterText = searchText.substring(0, 30);
console.log(`Retrying modify_text with shorter search: "${shorterText}"`);
try {
const retryResults = targetParagraph.search(shorterText, { matchCase: true });
retryResults.load("items/text");
await context.sync();
if (retryResults.items.length > 0) {
const replacementText = change.replacementText || "";
let htmlReplacement = markdownToWordHtmlInline(replacementText);
const trimmed = htmlReplacement.trim();
const hasSingleParagraph = trimmed.startsWith('<p>') && trimmed.endsWith('</p>') &&
trimmed.indexOf('</p>', 3) === trimmed.length - 4 &&
!trimmed.includes('<ul>') && !trimmed.includes('<ol>') &&
!trimmed.includes('<table') && !trimmed.includes('<h');
if (hasSingleParagraph) {
htmlReplacement = trimmed.substring(3, trimmed.length - 4);
}
// Use insertHtml with "Replace" for atomic replacement
retryResults.items[0].insertHtml(htmlReplacement || "", "Replace");
changesApplied++;
}
} catch (retryError) {
console.warn(`Retry search also failed for modify_text:`, retryError.message);
}
}
}
}
// Ensure any queued operations for this change are executed here,
// so errors are caught per-change instead of bubbling as one big GeneralException.
await context.sync();
} catch (changeError) {