@memberjunction/ai-agents 6.3.0-edge.0 → 6.3.0-edge.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/README.md +8 -5
  2. package/dist/AgentDataPreloader.d.ts +9 -2
  3. package/dist/AgentDataPreloader.d.ts.map +1 -1
  4. package/dist/AgentDataPreloader.js +134 -15
  5. package/dist/AgentDataPreloader.js.map +1 -1
  6. package/dist/AgentDecisionService.d.ts +10 -1
  7. package/dist/AgentDecisionService.d.ts.map +1 -1
  8. package/dist/AgentDecisionService.js +28 -13
  9. package/dist/AgentDecisionService.js.map +1 -1
  10. package/dist/AgentRunner.d.ts +57 -15
  11. package/dist/AgentRunner.d.ts.map +1 -1
  12. package/dist/AgentRunner.js +692 -101
  13. package/dist/AgentRunner.js.map +1 -1
  14. package/dist/ArtifactToolManager.d.ts +134 -39
  15. package/dist/ArtifactToolManager.d.ts.map +1 -1
  16. package/dist/ArtifactToolManager.js +2761 -321
  17. package/dist/ArtifactToolManager.js.map +1 -1
  18. package/dist/GovernedArtifactService.d.ts +367 -0
  19. package/dist/GovernedArtifactService.d.ts.map +1 -0
  20. package/dist/GovernedArtifactService.js +2569 -0
  21. package/dist/GovernedArtifactService.js.map +1 -0
  22. package/dist/PayloadManager.d.ts +46 -0
  23. package/dist/PayloadManager.d.ts.map +1 -1
  24. package/dist/PayloadManager.js +284 -66
  25. package/dist/PayloadManager.js.map +1 -1
  26. package/dist/SkillMarkdownConverter.d.ts.map +1 -1
  27. package/dist/SkillMarkdownConverter.js +4 -2
  28. package/dist/SkillMarkdownConverter.js.map +1 -1
  29. package/dist/agent-context-injector.d.ts +2 -25
  30. package/dist/agent-context-injector.d.ts.map +1 -1
  31. package/dist/agent-context-injector.js +38 -153
  32. package/dist/agent-context-injector.js.map +1 -1
  33. package/dist/agent-instance.d.ts +28 -0
  34. package/dist/agent-instance.d.ts.map +1 -0
  35. package/dist/agent-instance.js +39 -0
  36. package/dist/agent-instance.js.map +1 -0
  37. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  38. package/dist/agent-memory-context-builder.js +46 -42
  39. package/dist/agent-memory-context-builder.js.map +1 -1
  40. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  41. package/dist/agent-pre-execution-rag.js +5 -0
  42. package/dist/agent-pre-execution-rag.js.map +1 -1
  43. package/dist/agent-run-watchdog.d.ts +38 -6
  44. package/dist/agent-run-watchdog.d.ts.map +1 -1
  45. package/dist/agent-run-watchdog.js +75 -13
  46. package/dist/agent-run-watchdog.js.map +1 -1
  47. package/dist/agent-types/flow-agent-type.d.ts +6 -1
  48. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  49. package/dist/agent-types/flow-agent-type.js +30 -7
  50. package/dist/agent-types/flow-agent-type.js.map +1 -1
  51. package/dist/agent-types/loop-agent-type.d.ts +4 -0
  52. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  53. package/dist/agent-types/loop-agent-type.js +29 -0
  54. package/dist/agent-types/loop-agent-type.js.map +1 -1
  55. package/dist/artifact-presence-locator.d.ts +132 -0
  56. package/dist/artifact-presence-locator.d.ts.map +1 -0
  57. package/dist/artifact-presence-locator.js +472 -0
  58. package/dist/artifact-presence-locator.js.map +1 -0
  59. package/dist/artifact-tools/CSVToolLibrary.d.ts +2 -2
  60. package/dist/artifact-tools/CSVToolLibrary.d.ts.map +1 -1
  61. package/dist/artifact-tools/CSVToolLibrary.js +41 -14
  62. package/dist/artifact-tools/CSVToolLibrary.js.map +1 -1
  63. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts +2 -2
  64. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts.map +1 -1
  65. package/dist/artifact-tools/DataSnapshotToolLibrary.js +53 -21
  66. package/dist/artifact-tools/DataSnapshotToolLibrary.js.map +1 -1
  67. package/dist/artifact-tools/DocumentToolLibrary.d.ts +101 -0
  68. package/dist/artifact-tools/DocumentToolLibrary.d.ts.map +1 -0
  69. package/dist/artifact-tools/DocumentToolLibrary.js +1846 -0
  70. package/dist/artifact-tools/DocumentToolLibrary.js.map +1 -0
  71. package/dist/artifact-tools/DocxToolLibrary.d.ts +2 -4
  72. package/dist/artifact-tools/DocxToolLibrary.d.ts.map +1 -1
  73. package/dist/artifact-tools/DocxToolLibrary.js +42 -30
  74. package/dist/artifact-tools/DocxToolLibrary.js.map +1 -1
  75. package/dist/artifact-tools/ExcelToolLibrary.d.ts +2 -3
  76. package/dist/artifact-tools/ExcelToolLibrary.d.ts.map +1 -1
  77. package/dist/artifact-tools/ExcelToolLibrary.js +105 -49
  78. package/dist/artifact-tools/ExcelToolLibrary.js.map +1 -1
  79. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts +2 -2
  80. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts.map +1 -1
  81. package/dist/artifact-tools/GenericBinaryToolLibrary.js +3 -2
  82. package/dist/artifact-tools/GenericBinaryToolLibrary.js.map +1 -1
  83. package/dist/artifact-tools/JSONToolLibrary.d.ts +4 -4
  84. package/dist/artifact-tools/JSONToolLibrary.d.ts.map +1 -1
  85. package/dist/artifact-tools/JSONToolLibrary.js +32 -11
  86. package/dist/artifact-tools/JSONToolLibrary.js.map +1 -1
  87. package/dist/artifact-tools/PDFToolLibrary.d.ts +27 -3
  88. package/dist/artifact-tools/PDFToolLibrary.d.ts.map +1 -1
  89. package/dist/artifact-tools/PDFToolLibrary.js +36 -21
  90. package/dist/artifact-tools/PDFToolLibrary.js.map +1 -1
  91. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts +2 -2
  92. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts.map +1 -1
  93. package/dist/artifact-tools/SearchResultSetToolLibrary.js +83 -24
  94. package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -1
  95. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts +50 -0
  96. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts.map +1 -0
  97. package/dist/artifact-tools/SlideDeckToolLibrary.js +1617 -0
  98. package/dist/artifact-tools/SlideDeckToolLibrary.js.map +1 -0
  99. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts +87 -0
  100. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts.map +1 -0
  101. package/dist/artifact-tools/SpreadsheetToolLibrary.js +3351 -0
  102. package/dist/artifact-tools/SpreadsheetToolLibrary.js.map +1 -0
  103. package/dist/artifact-tools/TextToolLibrary.d.ts +3 -3
  104. package/dist/artifact-tools/TextToolLibrary.d.ts.map +1 -1
  105. package/dist/artifact-tools/TextToolLibrary.js +34 -24
  106. package/dist/artifact-tools/TextToolLibrary.js.map +1 -1
  107. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts +69 -0
  108. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts.map +1 -0
  109. package/dist/artifact-tools/WhiteboardToolLibrary.js +555 -0
  110. package/dist/artifact-tools/WhiteboardToolLibrary.js.map +1 -0
  111. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts +98 -0
  112. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts.map +1 -0
  113. package/dist/artifact-tools/artifact-comment-suggestion-helper.js +851 -0
  114. package/dist/artifact-tools/artifact-comment-suggestion-helper.js.map +1 -0
  115. package/dist/artifact-tools/artifact-tool-helpers.d.ts +21 -0
  116. package/dist/artifact-tools/artifact-tool-helpers.d.ts.map +1 -0
  117. package/dist/artifact-tools/artifact-tool-helpers.js +74 -0
  118. package/dist/artifact-tools/artifact-tool-helpers.js.map +1 -0
  119. package/dist/artifact-tools/grepHelper.d.ts +27 -0
  120. package/dist/artifact-tools/grepHelper.d.ts.map +1 -0
  121. package/dist/artifact-tools/grepHelper.js +229 -0
  122. package/dist/artifact-tools/grepHelper.js.map +1 -0
  123. package/dist/artifact-tools/node-vm-safe-regex.d.ts +10 -0
  124. package/dist/artifact-tools/node-vm-safe-regex.d.ts.map +1 -0
  125. package/dist/artifact-tools/node-vm-safe-regex.js +148 -0
  126. package/dist/artifact-tools/node-vm-safe-regex.js.map +1 -0
  127. package/dist/base-agent.d.ts +119 -14
  128. package/dist/base-agent.d.ts.map +1 -1
  129. package/dist/base-agent.js +529 -112
  130. package/dist/base-agent.js.map +1 -1
  131. package/dist/decision-discovery.d.ts +42 -15
  132. package/dist/decision-discovery.d.ts.map +1 -1
  133. package/dist/decision-discovery.js +90 -20
  134. package/dist/decision-discovery.js.map +1 -1
  135. package/dist/index.d.ts +12 -1
  136. package/dist/index.d.ts.map +1 -1
  137. package/dist/index.js +12 -2
  138. package/dist/index.js.map +1 -1
  139. package/dist/memory-decision-uses.d.ts +206 -0
  140. package/dist/memory-decision-uses.d.ts.map +1 -0
  141. package/dist/memory-decision-uses.js +259 -0
  142. package/dist/memory-decision-uses.js.map +1 -0
  143. package/dist/memory-manager-agent.d.ts +66 -6
  144. package/dist/memory-manager-agent.d.ts.map +1 -1
  145. package/dist/memory-manager-agent.js +184 -31
  146. package/dist/memory-manager-agent.js.map +1 -1
  147. package/dist/memory-note-gate.d.ts +12 -9
  148. package/dist/memory-note-gate.d.ts.map +1 -1
  149. package/dist/memory-note-gate.js +16 -11
  150. package/dist/memory-note-gate.js.map +1 -1
  151. package/dist/native-tools/agent-tool-circuit-breaker.d.ts +44 -0
  152. package/dist/native-tools/agent-tool-circuit-breaker.d.ts.map +1 -0
  153. package/dist/native-tools/agent-tool-circuit-breaker.js +71 -0
  154. package/dist/native-tools/agent-tool-circuit-breaker.js.map +1 -0
  155. package/dist/native-tools/agent-tools.d.ts +7 -0
  156. package/dist/native-tools/agent-tools.d.ts.map +1 -1
  157. package/dist/native-tools/agent-tools.js.map +1 -1
  158. package/dist/native-tools/control-tools.d.ts +8 -1
  159. package/dist/native-tools/control-tools.d.ts.map +1 -1
  160. package/dist/native-tools/control-tools.js +38 -5
  161. package/dist/native-tools/control-tools.js.map +1 -1
  162. package/dist/native-tools/framework-tools.d.ts +3 -3
  163. package/dist/native-tools/framework-tools.d.ts.map +1 -1
  164. package/dist/native-tools/framework-tools.js +20 -8
  165. package/dist/native-tools/framework-tools.js.map +1 -1
  166. package/dist/payload-path-keys.d.ts +54 -0
  167. package/dist/payload-path-keys.d.ts.map +1 -0
  168. package/dist/payload-path-keys.js +126 -0
  169. package/dist/payload-path-keys.js.map +1 -0
  170. package/dist/pipeline/template.d.ts +9 -4
  171. package/dist/pipeline/template.d.ts.map +1 -1
  172. package/dist/pipeline/template.js +29 -30
  173. package/dist/pipeline/template.js.map +1 -1
  174. package/dist/realtime/artifact-workspace-channel-server.d.ts +27 -0
  175. package/dist/realtime/artifact-workspace-channel-server.d.ts.map +1 -0
  176. package/dist/realtime/artifact-workspace-channel-server.js +43 -0
  177. package/dist/realtime/artifact-workspace-channel-server.js.map +1 -0
  178. package/dist/realtime/bridge-realtime-session-factory.d.ts +2 -2
  179. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  180. package/dist/realtime/bridge-realtime-session-factory.js +7 -56
  181. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  182. package/dist/realtime/realtime-artifact-helpers.d.ts +37 -0
  183. package/dist/realtime/realtime-artifact-helpers.d.ts.map +1 -0
  184. package/dist/realtime/realtime-artifact-helpers.js +150 -0
  185. package/dist/realtime/realtime-artifact-helpers.js.map +1 -0
  186. package/dist/realtime/realtime-client-session-service.d.ts +87 -17
  187. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  188. package/dist/realtime/realtime-client-session-service.js +259 -39
  189. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  190. package/dist/realtime/realtime-coagent-config.d.ts +22 -7
  191. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  192. package/dist/realtime/realtime-coagent-config.js +20 -22
  193. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  194. package/dist/realtime/realtime-moderator-decision.d.ts +86 -0
  195. package/dist/realtime/realtime-moderator-decision.d.ts.map +1 -0
  196. package/dist/realtime/realtime-moderator-decision.js +131 -0
  197. package/dist/realtime/realtime-moderator-decision.js.map +1 -0
  198. package/dist/realtime/realtime-tool-broker.d.ts +6 -0
  199. package/dist/realtime/realtime-tool-broker.d.ts.map +1 -1
  200. package/dist/realtime/realtime-tool-broker.js +4 -2
  201. package/dist/realtime/realtime-tool-broker.js.map +1 -1
  202. package/dist/realtime/realtime-turn-moderator.d.ts +20 -0
  203. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  204. package/dist/realtime/realtime-turn-moderator.js +63 -8
  205. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  206. package/dist/repeated-failing-step.d.ts +50 -0
  207. package/dist/repeated-failing-step.d.ts.map +1 -0
  208. package/dist/repeated-failing-step.js +130 -0
  209. package/dist/repeated-failing-step.js.map +1 -0
  210. package/dist/tsconfig.tsbuildinfo +1 -0
  211. package/package.json +20 -20
@@ -0,0 +1,3351 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { RegisterClass, UUIDsEqual } from '@memberjunction/global';
10
+ import { BaseArtifactToolLibrary, ResolveEmbeddedArtifactId, ResolveEmbeddedVersionId } from '@memberjunction/ai-core-plus';
11
+ import { ColumnIndexToLetter, CompileSafeUserRegex, FormatCellAddress, IsSafeUserRegex, ParseCellAddress, ParseRangeAddress, SafeRegexSearchDetailed, SpreadsheetEngine } from '@memberjunction/core-entities';
12
+ import { EnsureNodeVmSafeRegexExecutorRegistered, ExecuteSafeRegexBatchWithRecovery } from './node-vm-safe-regex.js';
13
+ import { ComputeNumericExtremum } from './artifact-tool-helpers.js';
14
+ import { ExecuteArtifactCommentTool, ExecuteListSuggestionsTool, ExecuteProposeSuggestionTool, ExecuteReviewSuggestionTool, GetSharedCommentAndSuggestionToolDefinitions, ParseSuggestionAnchor, ValidateEmbeddedArtifactAccess } from './artifact-comment-suggestion-helper.js';
15
+ const MAX_SHEET_ROW_COUNT = 10_000;
16
+ const MAX_SHEET_COLUMN_COUNT = 256;
17
+ const MAX_INSERT_COUNT = 1_000;
18
+ const MAX_READ_RANGE_CELLS = 10_000;
19
+ const SEARCH_MATCH_LIMIT = 100;
20
+ const TOOL_REGEX_BUDGET_MS = 150;
21
+ const BATCH_REGEX_MAX_MS = 40;
22
+ const MAX_BATCH_ITEMS = 512;
23
+ const MAX_BATCH_CHARS = 262_144;
24
+ const MAX_REGEX_INPUT_BYTES = 65_536;
25
+ const MAX_SAFE_UTF16_UNITS_FOR_64KB = 21_845;
26
+ const MAX_REPORTED_UNSEARCHABLE_CELLS = 25;
27
+ function exceedsSheetRegexInputBytes(text) {
28
+ if (text.length <= MAX_SAFE_UTF16_UNITS_FOR_64KB) {
29
+ return false;
30
+ }
31
+ return Buffer.byteLength(text, 'utf8') > MAX_REGEX_INPUT_BYTES;
32
+ }
33
+ EnsureNodeVmSafeRegexExecutorRegistered();
34
+ function computeFastCellSortKey(addr) {
35
+ let i = 0;
36
+ const len = addr.length;
37
+ if (i < len && addr.charCodeAt(i) === 36)
38
+ i++;
39
+ let col = 0;
40
+ while (i < len) {
41
+ let ch = addr.charCodeAt(i);
42
+ if (ch >= 97 && ch <= 122)
43
+ ch -= 32;
44
+ if (ch >= 65 && ch <= 90) {
45
+ col = col * 26 + (ch - 64);
46
+ i++;
47
+ }
48
+ else {
49
+ break;
50
+ }
51
+ }
52
+ if (i < len && addr.charCodeAt(i) === 36)
53
+ i++;
54
+ let row = 0;
55
+ while (i < len) {
56
+ const ch = addr.charCodeAt(i);
57
+ if (ch >= 48 && ch <= 57) {
58
+ row = row * 10 + (ch - 48);
59
+ i++;
60
+ }
61
+ else {
62
+ break;
63
+ }
64
+ }
65
+ return row * 65_536 + col;
66
+ }
67
+ const VALID_AGGREGATE_OPS = new Set(['sum', 'avg', 'count', 'min', 'max']);
68
+ const VALID_HORIZONTAL_ALIGNS = new Set(['left', 'center', 'right']);
69
+ const VALID_FORMAT_TYPES = new Set([
70
+ 'general',
71
+ 'number',
72
+ 'currency',
73
+ 'percent',
74
+ 'integer',
75
+ 'date',
76
+ 'datetime',
77
+ 'text'
78
+ ]);
79
+ function buildStylePatch(rec, existingStyle) {
80
+ const patch = {};
81
+ let hasKeys = false;
82
+ const rawFmt = typeof rec.formatType === 'string' ? rec.formatType.trim().toLowerCase() : undefined;
83
+ if (rawFmt && VALID_FORMAT_TYPES.has(rawFmt)) {
84
+ const formatType = rawFmt;
85
+ patch.FormatType = formatType;
86
+ hasKeys = true;
87
+ if (typeof rec.numberFormatPattern !== 'string' &&
88
+ (!existingStyle?.NumberFormatPattern || existingStyle.FormatType !== formatType)) {
89
+ const defPattern = SpreadsheetEngine.Instance.DefaultPatternForFormatType(formatType);
90
+ if (defPattern !== undefined) {
91
+ patch.NumberFormatPattern = defPattern;
92
+ }
93
+ }
94
+ }
95
+ if (typeof rec.numberFormatPattern === 'string') {
96
+ patch.NumberFormatPattern = rec.numberFormatPattern;
97
+ hasKeys = true;
98
+ }
99
+ if (typeof rec.bold === 'boolean') {
100
+ patch.Bold = rec.bold;
101
+ hasKeys = true;
102
+ }
103
+ if (typeof rec.italic === 'boolean') {
104
+ patch.Italic = rec.italic;
105
+ hasKeys = true;
106
+ }
107
+ if (typeof rec.horizontalAlign === 'string') {
108
+ const align = rec.horizontalAlign.trim().toLowerCase();
109
+ if (VALID_HORIZONTAL_ALIGNS.has(align)) {
110
+ patch.HorizontalAlign = align;
111
+ hasKeys = true;
112
+ }
113
+ }
114
+ if (typeof rec.textColor === 'string') {
115
+ patch.TextColor = rec.textColor;
116
+ hasKeys = true;
117
+ }
118
+ if (typeof rec.backgroundColor === 'string') {
119
+ patch.BackgroundColor = rec.backgroundColor;
120
+ hasKeys = true;
121
+ }
122
+ return hasKeys ? patch : undefined;
123
+ }
124
+ function isActorAllowedForProtectedRule(rule, editCtx) {
125
+ if (editCtx?.BypassProtection) {
126
+ return true;
127
+ }
128
+ const actor = (editCtx?.UserID ?? '').trim();
129
+ if (actor && editCtx?.OwnerUserID && UUIDsEqual(actor, editCtx.OwnerUserID)) {
130
+ return true;
131
+ }
132
+ if (actor && rule.LockedByUserID && UUIDsEqual(actor, rule.LockedByUserID)) {
133
+ return true;
134
+ }
135
+ if (rule.AllowEditors && editCtx?.IsEditor) {
136
+ return true;
137
+ }
138
+ return false;
139
+ }
140
+ function checkBoundsProtection(sheet, bounds, editCtx, actionLabel) {
141
+ if (editCtx.BypassProtection || (sheet.ProtectedRanges?.length ?? 0) === 0) {
142
+ return null;
143
+ }
144
+ for (const rule of sheet.ProtectedRanges ?? []) {
145
+ const ruleBounds = ParseRangeAddress(rule.Range, MAX_SHEET_ROW_COUNT, MAX_SHEET_COLUMN_COUNT);
146
+ if (!ruleBounds)
147
+ continue;
148
+ const overlaps = bounds.startRow <= ruleBounds.endRow &&
149
+ bounds.endRow >= ruleBounds.startRow &&
150
+ bounds.startCol <= ruleBounds.endCol &&
151
+ bounds.endCol >= ruleBounds.startCol;
152
+ if (overlaps && !isActorAllowedForProtectedRule(rule, editCtx)) {
153
+ return `Cannot ${actionLabel}: intersects protected range '${rule.Range}' (locked by ${rule.LockedByUserID}).`;
154
+ }
155
+ }
156
+ return null;
157
+ }
158
+ function resolveColumnNumber(colArg) {
159
+ if (typeof colArg === 'number' && Number.isFinite(colArg)) {
160
+ const n = Math.trunc(colArg);
161
+ return n >= 1 && n <= MAX_SHEET_COLUMN_COUNT ? n : null;
162
+ }
163
+ if (typeof colArg === 'string' && colArg.trim()) {
164
+ const trimmed = colArg.trim();
165
+ if (/^\d+$/.test(trimmed)) {
166
+ const n = parseInt(trimmed, 10);
167
+ return n >= 1 && n <= MAX_SHEET_COLUMN_COUNT ? n : null;
168
+ }
169
+ const parsed = ParseCellAddress(`${trimmed.toUpperCase()}1`);
170
+ return parsed && parsed.col >= 1 && parsed.col <= MAX_SHEET_COLUMN_COUNT ? parsed.col : null;
171
+ }
172
+ return null;
173
+ }
174
+ /**
175
+ * Server-side and agent tool library for `Excel Spreadsheet` artifacts (`MJ Sheets`, § 3.6 & § 6).
176
+ *
177
+ * Registered under `'SpreadsheetToolLibrary'` via `@RegisterClass(BaseArtifactToolLibrary, 'SpreadsheetToolLibrary')`
178
+ * to match `metadata/artifact-types/.artifact-types.json` (`O1`).
179
+ *
180
+ * All mutations and reads run headlessly on the server through {@link SpreadsheetEngine} (`§ 6.1`, `O7`),
181
+ * so when an agent writes a formula into a cell and reads it back with no browser open, the computed
182
+ * value is immediately accurate (`Accept #3`).
183
+ */
184
+ let SpreadsheetToolLibrary = class SpreadsheetToolLibrary extends BaseArtifactToolLibrary {
185
+ constructor() {
186
+ super(...arguments);
187
+ /**
188
+ * Wall-clock budget, in milliseconds, for one regex `search_cells` call. Cells not reached in time
189
+ * are reported as unsearchable and the result is marked `partial`. Defaults to
190
+ * {@link TOOL_REGEX_BUDGET_MS}; tests that assert a complete search raise it so a slow CI runner
191
+ * does not turn a timing margin into a failure.
192
+ */
193
+ this.RegexBudgetMs = TOOL_REGEX_BUDGET_MS;
194
+ this.activeOriginalXlsxStorage = new AsyncLocalStorage();
195
+ }
196
+ getSubclassToolList() {
197
+ return [
198
+ {
199
+ name: 'get_workbook_outline',
200
+ description: 'Returns the workbook title, revisionHash, active sheet ID, named ranges, and each worksheet summary (sheetId, name, rowCount, columnCount, cellCount, formulaCount, liveTables, charts, embeddedArtifacts).',
201
+ inputSchema: {
202
+ type: 'object',
203
+ properties: {}
204
+ }
205
+ },
206
+ {
207
+ name: 'read_workbook',
208
+ description: 'Alias for get_workbook_outline: returns full workbook structure and worksheet summaries.',
209
+ inputSchema: {
210
+ type: 'object',
211
+ properties: {}
212
+ }
213
+ },
214
+ {
215
+ name: 'read_range',
216
+ description: 'Reads a cell or rectangular A1 range (e.g. "B4" or "A1:D10") from a worksheet after headless formula evaluation, returning each cell address, stable RowID/ColumnID, rawValue, formula, computedValue, and displayValue.',
217
+ inputSchema: {
218
+ type: 'object',
219
+ properties: {
220
+ sheet: {
221
+ type: 'string',
222
+ description: 'Worksheet SheetID or Name (defaults to the active sheet).'
223
+ },
224
+ range: {
225
+ type: 'string',
226
+ description: 'A1 cell or range to read (e.g. "B4" or "A1:D10").'
227
+ }
228
+ },
229
+ required: ['range']
230
+ }
231
+ },
232
+ {
233
+ name: 'write_cells',
234
+ description: 'Writes values, formulas (including =SUM, =VLOOKUP, =MJ.QUERY, =MJ.VIEW, =MJ.IMPORTRANGE), and styles into one or more cells on a worksheet while preserving unspecified style attributes, recalculates all dependent formulas headlessly on the server, and returns the updated cells with their computed values.',
235
+ inputSchema: {
236
+ type: 'object',
237
+ properties: {
238
+ sheet: {
239
+ type: 'string',
240
+ description: 'Target worksheet SheetID or Name (defaults to active sheet).'
241
+ },
242
+ cells: {
243
+ type: 'array',
244
+ description: 'Array of cell updates: [{ address: "B4", value?: 100, formula?: "=SUM(B2:B3)", formatType?: "currency" | "percent" | "number" | "integer" | "date" | "datetime" | "text" | "general", numberFormatPattern?: "$#,##0.00", bold?: true, italic?: false, horizontalAlign?: "left" | "center" | "right", textColor?: "#111827", backgroundColor?: "#EEF2FF", note?: "..." }]. Also accepts address aliases (cell, ref, coord) or 0-based { r, c, v?, f? }.'
245
+ },
246
+ expectedRevisionHash: {
247
+ type: 'string',
248
+ description: 'Optional optimistic concurrency revision hash from a prior read.'
249
+ }
250
+ },
251
+ required: ['cells']
252
+ }
253
+ },
254
+ {
255
+ name: 'format_range',
256
+ description: 'Applies style attributes (bold, italic, horizontalAlign, textColor, backgroundColor, formatType, numberFormatPattern) across an A1 cell range while preserving existing cell values, formulas, and unspecified style properties.',
257
+ inputSchema: {
258
+ type: 'object',
259
+ properties: {
260
+ sheet: {
261
+ type: 'string',
262
+ description: 'Target worksheet SheetID or Name (defaults to active sheet).'
263
+ },
264
+ range: {
265
+ type: 'string',
266
+ description: 'A1 cell or rectangular range to format (e.g. "A1:D1" or "B2:B10").'
267
+ },
268
+ bold: { type: 'boolean', description: 'Bold font weight.' },
269
+ italic: { type: 'boolean', description: 'Italic font style.' },
270
+ horizontalAlign: {
271
+ type: 'string',
272
+ enum: ['left', 'center', 'right'],
273
+ description: 'Horizontal text alignment.'
274
+ },
275
+ textColor: { type: 'string', description: 'CSS/hex color or token for cell text.' },
276
+ backgroundColor: { type: 'string', description: 'CSS/hex color or token for cell background fill.' },
277
+ formatType: {
278
+ type: 'string',
279
+ enum: ['general', 'number', 'currency', 'percent', 'integer', 'date', 'datetime', 'text'],
280
+ description: 'Number display format category.'
281
+ },
282
+ numberFormatPattern: {
283
+ type: 'string',
284
+ description: 'Excel-compatible number format pattern (e.g. "$#,##0.00", "0.0%").'
285
+ },
286
+ expectedRevisionHash: {
287
+ type: 'string',
288
+ description: 'Optional optimistic concurrency revision hash from a prior read.'
289
+ }
290
+ },
291
+ required: ['range']
292
+ }
293
+ },
294
+ {
295
+ name: 'clear_range',
296
+ description: 'Clears values, styles, notes, or everything inside an A1 cell or rectangular range (including any owned dynamic-array or legacy CSE spill children) and recalculates dependents.',
297
+ inputSchema: {
298
+ type: 'object',
299
+ properties: {
300
+ sheet: {
301
+ type: 'string',
302
+ description: 'Target worksheet SheetID or Name (defaults to active sheet).'
303
+ },
304
+ range: {
305
+ type: 'string',
306
+ description: 'A1 cell or range to clear (e.g. "I6" or "A2:D10").'
307
+ },
308
+ mode: {
309
+ type: 'string',
310
+ enum: ['all', 'values', 'formats', 'notes'],
311
+ description: 'What to clear: "all" (default, removes cells completely), "values" (clears values/formulas while keeping styles/notes), "formats" (clears styles), or "notes" (clears notes).'
312
+ },
313
+ expectedRevisionHash: {
314
+ type: 'string',
315
+ description: 'Optional optimistic concurrency revision hash from a prior read.'
316
+ }
317
+ },
318
+ required: ['range']
319
+ }
320
+ },
321
+ {
322
+ name: 'insert_rows',
323
+ description: 'Inserts one or more rows at 1-based atRowNumber with stable RowIDs, automatically shifting cells and updating all A1 formulas.',
324
+ inputSchema: {
325
+ type: 'object',
326
+ properties: {
327
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
328
+ atRowNumber: { type: 'number', description: '1-based row number where new rows are inserted.' },
329
+ count: { type: 'number', description: 'Number of rows to insert (default 1).' },
330
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
331
+ },
332
+ required: ['atRowNumber']
333
+ }
334
+ },
335
+ {
336
+ name: 'delete_rows',
337
+ description: 'Deletes one or more rows starting at 1-based atRowNumber, enforcing ProtectedRanges locks and updating formulas.',
338
+ inputSchema: {
339
+ type: 'object',
340
+ properties: {
341
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
342
+ atRowNumber: { type: 'number', description: '1-based starting row number to delete.' },
343
+ count: { type: 'number', description: 'Number of rows to delete (default 1).' },
344
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
345
+ },
346
+ required: ['atRowNumber']
347
+ }
348
+ },
349
+ {
350
+ name: 'insert_columns',
351
+ description: 'Inserts one or more columns at 1-based atColumnNumber with stable ColumnIDs, automatically shifting cells and updating all A1 formulas.',
352
+ inputSchema: {
353
+ type: 'object',
354
+ properties: {
355
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
356
+ atColumnNumber: {
357
+ type: 'number',
358
+ description: '1-based column number where new columns are inserted.'
359
+ },
360
+ count: { type: 'number', description: 'Number of columns to insert (default 1).' },
361
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
362
+ },
363
+ required: ['atColumnNumber']
364
+ }
365
+ },
366
+ {
367
+ name: 'delete_columns',
368
+ description: 'Deletes one or more columns starting at 1-based atColumnNumber, enforcing ProtectedRanges locks and updating formulas.',
369
+ inputSchema: {
370
+ type: 'object',
371
+ properties: {
372
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
373
+ atColumnNumber: { type: 'number', description: '1-based starting column number to delete.' },
374
+ count: { type: 'number', description: 'Number of columns to delete (default 1).' },
375
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
376
+ },
377
+ required: ['atColumnNumber']
378
+ }
379
+ },
380
+ {
381
+ name: 'add_sheet',
382
+ description: 'Adds a new worksheet tab to the workbook.',
383
+ inputSchema: {
384
+ type: 'object',
385
+ properties: {
386
+ name: { type: 'string', description: 'Display name for the new worksheet tab.' },
387
+ rowCount: { type: 'number', description: 'Initial row count (default 25).' },
388
+ columnCount: { type: 'number', description: 'Initial column count (default 12).' },
389
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
390
+ },
391
+ required: ['name']
392
+ }
393
+ },
394
+ {
395
+ name: 'rename_sheet',
396
+ description: 'Renames an existing worksheet tab.',
397
+ inputSchema: {
398
+ type: 'object',
399
+ properties: {
400
+ sheet: { type: 'string', description: 'Worksheet SheetID or current Name.' },
401
+ newName: { type: 'string', description: 'New display name (up to 31 characters).' },
402
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
403
+ },
404
+ required: ['sheet', 'newName']
405
+ }
406
+ },
407
+ {
408
+ name: 'duplicate_sheet',
409
+ description: 'Duplicates an existing worksheet tab (cells, styles, formulas, charts, live tables, embedded artifacts) with fresh internal IDs and inserts it after the source sheet.',
410
+ inputSchema: {
411
+ type: 'object',
412
+ properties: {
413
+ sheet: { type: 'string', description: 'Source worksheet SheetID or Name to duplicate.' },
414
+ newName: { type: 'string', description: 'Optional display name for the duplicated sheet (up to 31 characters).' },
415
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
416
+ },
417
+ required: ['sheet']
418
+ }
419
+ },
420
+ {
421
+ name: 'reorder_sheets',
422
+ description: 'Reorders worksheet tabs in the workbook according to sheetIds (SheetIDs or Names).',
423
+ inputSchema: {
424
+ type: 'object',
425
+ properties: {
426
+ sheetIds: {
427
+ type: 'array',
428
+ items: { type: 'string' },
429
+ description: 'Ordered array of worksheet SheetIDs or Names.'
430
+ },
431
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
432
+ },
433
+ required: ['sheetIds']
434
+ }
435
+ },
436
+ {
437
+ name: 'delete_sheet',
438
+ description: 'Deletes a worksheet tab from the workbook (requires at least 2 tabs in the workbook).',
439
+ inputSchema: {
440
+ type: 'object',
441
+ properties: {
442
+ sheet: { type: 'string', description: 'Worksheet SheetID or Name to delete.' },
443
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
444
+ },
445
+ required: ['sheet']
446
+ }
447
+ },
448
+ {
449
+ name: 'set_sheet_layout',
450
+ description: 'Updates worksheet layout properties such as frozenRows, frozenColumns, rowHeights/hidden state, and columnWidths/hidden state.',
451
+ inputSchema: {
452
+ type: 'object',
453
+ properties: {
454
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name (defaults to active sheet).' },
455
+ frozenRows: { type: 'number', description: 'Number of frozen top rows (0 or greater).' },
456
+ frozenColumns: { type: 'number', description: 'Number of frozen left columns (0 or greater).' },
457
+ rowHeights: {
458
+ type: 'array',
459
+ description: 'Array of row layout overrides: [{ rowNumber: 1, height?: 32, hidden?: false }].'
460
+ },
461
+ columnWidths: {
462
+ type: 'array',
463
+ description: 'Array of column layout overrides: [{ column: "A" | 1, width?: 160, hidden?: false }].'
464
+ },
465
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
466
+ }
467
+ }
468
+ },
469
+ {
470
+ name: 'upsert_live_table',
471
+ description: 'Binds or updates an MJ EntityView or SavedQuery range table on a worksheet (with optional extraFilter, fields, parameters, maxRows, and calculated formula columns), materializes live rows under the user permissions, and returns the resolved headers, rowCount, and boundingRange.',
472
+ inputSchema: {
473
+ type: 'object',
474
+ properties: {
475
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
476
+ tableId: { type: 'string', description: 'Optional stable TableID.' },
477
+ title: { type: 'string', description: 'Display title for the bound table.' },
478
+ sourceType: {
479
+ type: 'string',
480
+ description: '"EntityView" (or "view"/"entity") or "SavedQuery" (or "query").'
481
+ },
482
+ entityName: { type: 'string', description: 'Target EntityName when sourceType="EntityView".' },
483
+ viewId: { type: 'string', description: 'Optional saved User View ID.' },
484
+ viewName: { type: 'string', description: 'Optional saved User View Name.' },
485
+ extraFilter: { type: 'string', description: 'Optional SQL filter clause for EntityView sources.' },
486
+ fields: {
487
+ type: 'array',
488
+ description: 'Optional subset of field names to include.'
489
+ },
490
+ queryId: { type: 'string', description: 'Target Saved Query ID when sourceType="SavedQuery".' },
491
+ queryName: {
492
+ type: 'string',
493
+ description: 'Target Saved Query Name when sourceType="SavedQuery".'
494
+ },
495
+ parameters: {
496
+ type: 'object',
497
+ description: 'Optional parameter map passed to the SavedQuery.'
498
+ },
499
+ maxRows: {
500
+ type: 'number',
501
+ description: 'Maximum rows to materialize (default 100).'
502
+ },
503
+ anchorCell: { type: 'string', description: 'Top-left A1 cell (default "A1").' },
504
+ calculatedColumns: {
505
+ type: 'array',
506
+ description: 'Optional calculated formula columns: [{ header: "Total", formulaTemplate: "=B{ROW}*C{ROW}", formatType?: "currency" }].'
507
+ },
508
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
509
+ },
510
+ required: ['sourceType']
511
+ }
512
+ },
513
+ {
514
+ name: 'refresh_live_tables',
515
+ description: 'Re-executes bound LiveTables and =MJ.* custom functions across the workbook under the current user permissions, updates worksheet cells and dependent formulas, and returns updated bounds and headers.',
516
+ inputSchema: {
517
+ type: 'object',
518
+ properties: {
519
+ tableId: {
520
+ type: 'string',
521
+ description: 'Optional TableID to refresh only one bound live table (defaults to all).'
522
+ },
523
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
524
+ },
525
+ required: []
526
+ }
527
+ },
528
+ {
529
+ name: 'upsert_chart',
530
+ description: 'Adds or updates a range chart on a worksheet and returns its evaluated chart series dataset.',
531
+ inputSchema: {
532
+ type: 'object',
533
+ properties: {
534
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
535
+ chartId: { type: 'string', description: 'Optional stable ChartID.' },
536
+ title: { type: 'string', description: 'Chart title.' },
537
+ chartType: {
538
+ type: 'string',
539
+ description: '"bar", "line", "pie", or "area".'
540
+ },
541
+ sourceRange: {
542
+ type: 'string',
543
+ description: 'A1 source range on the worksheet, or comma-separated non-contiguous ranges (e.g. "A1:C6" or "A1:A6,D1:D6").'
544
+ },
545
+ positionCell: {
546
+ type: 'string',
547
+ description: 'Anchor cell for the chart card (default "E2").'
548
+ },
549
+ placement: {
550
+ type: 'string',
551
+ enum: ['dock', 'sheet'],
552
+ description: 'Where to render the chart: "dock" in bottom strip (default) or "sheet" floating over grid cells.'
553
+ },
554
+ widthPx: { type: 'number', description: 'Optional chart width in pixels.' },
555
+ heightPx: { type: 'number', description: 'Optional chart height in pixels.' },
556
+ showLegend: { type: 'boolean', description: 'Whether to display the legend (defaults to true).' },
557
+ hasHeaderRow: {
558
+ description: 'Header handling: "auto" (default), true, or false.'
559
+ },
560
+ seriesOrientation: {
561
+ type: 'string',
562
+ enum: ['columns', 'rows'],
563
+ description: 'Whether series come from "columns" (default) or "rows".'
564
+ },
565
+ categoryColumnIndex: {
566
+ type: 'number',
567
+ description: 'Zero-based column (or row) index within sourceRange for category labels.'
568
+ },
569
+ includedSeriesIndices: {
570
+ type: 'array',
571
+ items: { type: 'number' },
572
+ description: 'Zero-based series indices within sourceRange to include.'
573
+ },
574
+ showDataLabels: {
575
+ type: 'boolean',
576
+ description: 'Whether to show numeric value labels on plotted chart elements.'
577
+ },
578
+ offsetX: { type: 'number', description: 'Optional horizontal pixel offset when placement is "sheet".' },
579
+ offsetY: { type: 'number', description: 'Optional vertical pixel offset when placement is "sheet".' },
580
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
581
+ },
582
+ required: ['sourceRange']
583
+ }
584
+ },
585
+ {
586
+ name: 'delete_chart',
587
+ description: 'Removes a range chart from a worksheet by chartId.',
588
+ inputSchema: {
589
+ type: 'object',
590
+ properties: {
591
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
592
+ chartId: { type: 'string', description: 'ChartID to delete.' },
593
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
594
+ },
595
+ required: ['chartId']
596
+ }
597
+ },
598
+ {
599
+ name: 'delete_live_table',
600
+ description: 'Removes a bound LiveTable definition from a worksheet by tableId (optionally clearing its cells).',
601
+ inputSchema: {
602
+ type: 'object',
603
+ properties: {
604
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
605
+ tableId: { type: 'string', description: 'LiveTable TableID to delete.' },
606
+ clearCells: {
607
+ type: 'boolean',
608
+ description: 'When true, also clears materialized cells belonging to this table.'
609
+ },
610
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
611
+ },
612
+ required: ['tableId']
613
+ }
614
+ },
615
+ {
616
+ name: 'embed_artifact',
617
+ description: 'Embeds an inline OLE Artifact (such as an interactive Whiteboard) anchored to a worksheet cell.',
618
+ inputSchema: {
619
+ type: 'object',
620
+ properties: {
621
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
622
+ embedId: { type: 'string', description: 'Optional stable EmbedID.' },
623
+ title: { type: 'string', description: 'Display title.' },
624
+ artifactId: {
625
+ type: 'string',
626
+ description: 'Target MJ: Artifacts UUID (or session short-ID like "B", "D", which is resolved automatically).'
627
+ },
628
+ versionId: {
629
+ type: 'string',
630
+ description: 'Optional pinned MJ: Artifact Versions UUID (or session short ID such as "E"; omit to track latest).'
631
+ },
632
+ artifactTypeName: {
633
+ type: 'string',
634
+ description: 'Artifact type name (e.g. "Whiteboard").'
635
+ },
636
+ anchorCell: { type: 'string', description: 'Anchor A1 cell (default "F2").' },
637
+ widthPx: { type: 'number', description: 'Width in pixels (default 520).' },
638
+ heightPx: { type: 'number', description: 'Height in pixels (default 320).' },
639
+ allowInlineEdit: { type: 'boolean', description: 'Whether inline editing is allowed (defaults to true).' },
640
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
641
+ },
642
+ required: ['artifactId']
643
+ }
644
+ },
645
+ {
646
+ name: 'delete_embedded_artifact',
647
+ description: 'Removes an embedded OLE Artifact from a worksheet by embedId.',
648
+ inputSchema: {
649
+ type: 'object',
650
+ properties: {
651
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
652
+ embedId: { type: 'string', description: 'Embedded artifact EmbedID to delete.' },
653
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
654
+ },
655
+ required: ['embedId']
656
+ }
657
+ },
658
+ {
659
+ name: 'sort_and_filter',
660
+ description: 'Sorts a worksheet by a column and/or applies column filters.',
661
+ inputSchema: {
662
+ type: 'object',
663
+ properties: {
664
+ sheet: { type: 'string', description: 'Target worksheet SheetID or Name.' },
665
+ sortColumn: { type: 'string', description: 'Optional column letter to sort by (e.g. "B").' },
666
+ sortDirection: { type: 'string', description: '"asc" or "desc" (default "asc").' },
667
+ filters: {
668
+ type: 'array',
669
+ description: 'Optional filter specs: [{ columnLetter: "A", operator: "equals" | "contains" | "gt" | "lt" | "notEmpty", value: "..." }].'
670
+ },
671
+ expectedRevisionHash: { type: 'string', description: 'Optional concurrency revision hash.' }
672
+ }
673
+ }
674
+ },
675
+ {
676
+ name: 'get_sheets',
677
+ description: 'Returns sheet names, row counts, and column counts for every sheet in the workbook.',
678
+ inputSchema: { type: 'object', properties: {}, required: [] }
679
+ },
680
+ {
681
+ name: 'get_sheet_data',
682
+ description: 'Returns rows from a sheet as key-value objects using the header row as keys. Defaults to first 50 data rows (capped at 10,000).',
683
+ inputSchema: {
684
+ type: 'object',
685
+ properties: {
686
+ sheet: { type: 'string', description: 'Sheet name or SheetID' },
687
+ startRow: { type: 'number', description: '1-based data row to start from (after header). Default: 1' },
688
+ rowCount: { type: 'number', description: 'Number of data rows to return (max 10,000). Default: 50' }
689
+ },
690
+ required: ['sheet']
691
+ }
692
+ },
693
+ {
694
+ name: 'search_cells',
695
+ description: 'Case-insensitive literal substring search (default false for use_regex) or regular expression search (when use_regex is true) across all cells. Optionally scope to a single sheet. Returns up to 100 matches.',
696
+ inputSchema: {
697
+ type: 'object',
698
+ properties: {
699
+ query: {
700
+ type: 'string',
701
+ description: 'Plain-text literal substring (default) or case-insensitive regex pattern (when use_regex is true) to search for'
702
+ },
703
+ sheet: { type: 'string', description: 'Optional sheet name or SheetID to limit search scope' },
704
+ use_regex: {
705
+ type: 'boolean',
706
+ description: 'Optional (default false): set true to evaluate query as a regular expression; defaults to false for literal plain-text search with no 64 KB cap.'
707
+ },
708
+ useRegex: {
709
+ type: 'boolean',
710
+ description: 'Alias for use_regex (default false).'
711
+ }
712
+ },
713
+ required: ['query']
714
+ }
715
+ },
716
+ {
717
+ name: 'aggregate_column',
718
+ description: 'Computes an aggregate (sum, avg, count, min, max) on a column identified by its header name.',
719
+ inputSchema: {
720
+ type: 'object',
721
+ properties: {
722
+ sheet: { type: 'string', description: 'Sheet name or SheetID' },
723
+ column: { type: 'string', description: 'Column header name' },
724
+ operation: { type: 'string', description: 'Aggregate operation: sum, avg, count, min, max' }
725
+ },
726
+ required: ['sheet', 'column', 'operation']
727
+ }
728
+ },
729
+ {
730
+ name: 'get_formulas',
731
+ description: 'Returns all cells containing formulas in a given sheet.',
732
+ inputSchema: {
733
+ type: 'object',
734
+ properties: {
735
+ sheet: { type: 'string', description: 'Sheet name or SheetID' }
736
+ },
737
+ required: ['sheet']
738
+ }
739
+ },
740
+ {
741
+ name: 'merge_cells',
742
+ description: 'Merges a rectangular A1 range (>= 2 cells) on a worksheet.',
743
+ inputSchema: {
744
+ type: 'object',
745
+ properties: {
746
+ sheet: { type: 'string', description: 'Sheet name or SheetID.' },
747
+ range: { type: 'string', description: 'Canonical rectangular A1 range (e.g. "A1:C1").' },
748
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
749
+ },
750
+ required: ['range']
751
+ }
752
+ },
753
+ {
754
+ name: 'unmerge_cells',
755
+ description: 'Unmerges any merged ranges matching or overlapping the supplied A1 range.',
756
+ inputSchema: {
757
+ type: 'object',
758
+ properties: {
759
+ sheet: { type: 'string', description: 'Sheet name or SheetID.' },
760
+ range: { type: 'string', description: 'A1 cell or range to unmerge.' },
761
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
762
+ },
763
+ required: ['range']
764
+ }
765
+ },
766
+ {
767
+ name: 'upsert_conditional_format',
768
+ description: 'Creates or updates a conditional formatting rule on a worksheet range.',
769
+ inputSchema: {
770
+ type: 'object',
771
+ properties: {
772
+ sheet: { type: 'string', description: 'Sheet name or SheetID.' },
773
+ ruleId: { type: 'string', description: 'Optional rule ID to update in place.' },
774
+ range: { type: 'string', description: 'Target A1 range (e.g. "D2:D50").' },
775
+ operator: {
776
+ type: 'string',
777
+ enum: ['gt', 'lt', 'eq', 'between', 'contains'],
778
+ description: 'Comparison operator.'
779
+ },
780
+ value1: { type: 'string', description: 'Primary threshold value (string or number).' },
781
+ value2: { type: 'number', description: 'Upper bound numeric threshold when operator is "between".' },
782
+ highlightTone: {
783
+ type: 'string',
784
+ enum: ['success', 'warning', 'danger', 'info'],
785
+ description: 'Semantic highlight tone.'
786
+ },
787
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
788
+ },
789
+ required: ['range', 'operator', 'value1', 'highlightTone']
790
+ }
791
+ },
792
+ {
793
+ name: 'delete_conditional_format',
794
+ description: 'Removes a conditional formatting rule by ruleId.',
795
+ inputSchema: {
796
+ type: 'object',
797
+ properties: {
798
+ sheet: { type: 'string', description: 'Sheet name or SheetID.' },
799
+ ruleId: { type: 'string', description: 'Conditional formatting RuleID to remove.' },
800
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
801
+ },
802
+ required: ['ruleId']
803
+ }
804
+ },
805
+ {
806
+ name: 'upsert_validation_rule',
807
+ description: 'Creates or updates a data validation rule on a worksheet range.',
808
+ inputSchema: {
809
+ type: 'object',
810
+ properties: {
811
+ sheet: { type: 'string', description: 'Sheet name or SheetID.' },
812
+ ruleId: { type: 'string', description: 'Optional rule ID to update in place.' },
813
+ range: { type: 'string', description: 'Target A1 range (e.g. "C2:C50").' },
814
+ ruleType: {
815
+ type: 'string',
816
+ enum: ['list', 'numberRange', 'notEmpty'],
817
+ description: 'Validation rule type.'
818
+ },
819
+ allowedValues: {
820
+ type: 'array',
821
+ items: { type: 'string' },
822
+ description: 'Allowed string values when ruleType is "list".'
823
+ },
824
+ minValue: { type: 'number', description: 'Minimum number when ruleType is "numberRange".' },
825
+ maxValue: { type: 'number', description: 'Maximum number when ruleType is "numberRange".' },
826
+ errorMessage: { type: 'string', description: 'Optional validation failure message.' },
827
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
828
+ },
829
+ required: ['range', 'ruleType']
830
+ }
831
+ },
832
+ {
833
+ name: 'delete_validation_rule',
834
+ description: 'Removes a data validation rule by ruleId.',
835
+ inputSchema: {
836
+ type: 'object',
837
+ properties: {
838
+ sheet: { type: 'string', description: 'Sheet name or SheetID.' },
839
+ ruleId: { type: 'string', description: 'Validation RuleID to remove.' },
840
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
841
+ },
842
+ required: ['ruleId']
843
+ }
844
+ },
845
+ {
846
+ name: 'upsert_named_range',
847
+ description: 'Creates or updates a workbook-level named range and recalculates dependent formulas.',
848
+ inputSchema: {
849
+ type: 'object',
850
+ properties: {
851
+ name: { type: 'string', description: 'Formula identifier (e.g. "TaxRate").' },
852
+ sheet: { type: 'string', description: 'Sheet name or SheetID owning the range.' },
853
+ range: { type: 'string', description: 'A1 cell or rectangular range (e.g. "B2:B10").' },
854
+ description: { type: 'string', description: 'Optional description.' },
855
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
856
+ },
857
+ required: ['name', 'range']
858
+ }
859
+ },
860
+ {
861
+ name: 'delete_named_range',
862
+ description: 'Removes a workbook-level named range by name.',
863
+ inputSchema: {
864
+ type: 'object',
865
+ properties: {
866
+ name: { type: 'string', description: 'Named range identifier to remove.' },
867
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
868
+ },
869
+ required: ['name']
870
+ }
871
+ },
872
+ {
873
+ name: 'set_lock',
874
+ description: 'Adds or updates a protected range lock on a worksheet.',
875
+ inputSchema: {
876
+ type: 'object',
877
+ properties: {
878
+ sheet: { type: 'string', description: 'Sheet name or SheetID.' },
879
+ range: { type: 'string', description: 'A1 cell or range to lock.' },
880
+ rangeId: { type: 'string', description: 'Optional stable RangeID.' },
881
+ description: { type: 'string', description: 'Optional lock rationale/description.' },
882
+ allowEditors: { type: 'boolean', description: 'Whether artifact editors may modify cells inside the protected range (default false = owner only).' },
883
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
884
+ },
885
+ required: ['range']
886
+ }
887
+ },
888
+ {
889
+ name: 'release_lock',
890
+ description: 'Removes an existing protected range lock on a worksheet if the actor is authorized.',
891
+ inputSchema: {
892
+ type: 'object',
893
+ properties: {
894
+ sheet: { type: 'string', description: 'Sheet name or SheetID.' },
895
+ rangeId: { type: 'string', description: 'Protected range RuleID / RangeID to unlock.' },
896
+ range: { type: 'string', description: 'Optional A1 range to match if rangeId is omitted.' },
897
+ expectedRevisionHash: { type: 'string', description: 'Optional revision hash for concurrency control.' }
898
+ }
899
+ }
900
+ },
901
+ ...GetSharedCommentAndSuggestionToolDefinitions('spreadsheet')
902
+ ];
903
+ }
904
+ async invokeSubclassTool(toolName, input, artifactContent, context) {
905
+ const originalXlsxBytes = Buffer.isBuffer(artifactContent) &&
906
+ artifactContent.length > 4 &&
907
+ artifactContent[0] === 0x50 &&
908
+ artifactContent[1] === 0x4b
909
+ ? new Uint8Array(artifactContent)
910
+ : null;
911
+ return this.activeOriginalXlsxStorage.run(originalXlsxBytes, async () => {
912
+ if (toolName === 'list_comments' ||
913
+ toolName === 'add_comment' ||
914
+ toolName === 'reply_comment' ||
915
+ toolName === 'resolve_comment') {
916
+ return ExecuteArtifactCommentTool({
917
+ toolName,
918
+ input,
919
+ context,
920
+ domain: 'spreadsheet'
921
+ });
922
+ }
923
+ const engine = SpreadsheetEngine.Instance;
924
+ let workbook;
925
+ try {
926
+ workbook = await this.loadWorkbookFromContentIsolated(artifactContent);
927
+ }
928
+ catch (err) {
929
+ return this.errorResult(`Failed to parse spreadsheet content: ${err instanceof Error ? err.message : String(err)}`);
930
+ }
931
+ let cachedCurrentHash = null;
932
+ const getCurrentHash = () => {
933
+ if (cachedCurrentHash === null) {
934
+ cachedCurrentHash = engine.ComputeRevisionHash(workbook);
935
+ }
936
+ return cachedCurrentHash;
937
+ };
938
+ const expectedHash = typeof input.expectedRevisionHash === 'string' ? input.expectedRevisionHash.trim() : '';
939
+ if (expectedHash && expectedHash !== getCurrentHash()) {
940
+ return this.errorResult(`Revision conflict: expectedRevisionHash '${expectedHash}' does not match current workbook revision '${getCurrentHash()}'. Re-read the workbook before retrying.`);
941
+ }
942
+ switch (toolName) {
943
+ case 'get_workbook_outline':
944
+ case 'read_workbook':
945
+ return this.handleGetWorkbookOutline(workbook, getCurrentHash());
946
+ case 'get_sheets':
947
+ return this.handleGetSheets(workbook);
948
+ case 'get_sheet_data':
949
+ return this.handleGetSheetData(workbook, input);
950
+ case 'search_cells':
951
+ return this.handleSearchCells(workbook, input);
952
+ case 'aggregate_column':
953
+ return this.handleAggregateColumn(workbook, input);
954
+ case 'get_formulas':
955
+ return this.handleGetFormulas(workbook, input);
956
+ case 'read_range':
957
+ return this.handleReadRange(workbook, input, getCurrentHash());
958
+ case 'write_cells':
959
+ return this.handleWriteCells(workbook, input, context);
960
+ case 'format_range':
961
+ return this.handleFormatRange(workbook, input, context);
962
+ case 'clear_range':
963
+ return this.handleClearRange(workbook, input, context);
964
+ case 'insert_rows':
965
+ return this.handleInsertRows(workbook, input, context);
966
+ case 'delete_rows':
967
+ return this.handleDeleteRows(workbook, input, context);
968
+ case 'insert_columns':
969
+ return this.handleInsertColumns(workbook, input, context);
970
+ case 'delete_columns':
971
+ return this.handleDeleteColumns(workbook, input, context);
972
+ case 'add_sheet':
973
+ return this.handleAddSheet(workbook, input);
974
+ case 'rename_sheet':
975
+ return this.handleRenameSheet(workbook, input);
976
+ case 'duplicate_sheet':
977
+ return this.handleDuplicateSheet(workbook, input);
978
+ case 'reorder_sheets':
979
+ return this.handleReorderSheets(workbook, input);
980
+ case 'delete_sheet':
981
+ return this.handleDeleteSheet(workbook, input, context);
982
+ case 'set_sheet_layout':
983
+ return this.handleSetSheetLayout(workbook, input, context);
984
+ case 'upsert_live_table':
985
+ return this.handleUpsertLiveTable(workbook, input, context);
986
+ case 'refresh_live_tables':
987
+ return this.handleRefreshLiveTables(workbook, input, context);
988
+ case 'delete_live_table':
989
+ return this.handleDeleteLiveTable(workbook, input, context);
990
+ case 'upsert_chart':
991
+ return this.handleUpsertChart(workbook, input);
992
+ case 'delete_chart':
993
+ return this.handleDeleteChart(workbook, input);
994
+ case 'embed_artifact':
995
+ return this.handleEmbedArtifact(workbook, input, context);
996
+ case 'delete_embedded_artifact':
997
+ return this.handleDeleteEmbeddedArtifact(workbook, input);
998
+ case 'sort_and_filter':
999
+ return this.handleSortAndFilter(workbook, input, context);
1000
+ case 'merge_cells':
1001
+ return this.handleMergeCells(workbook, input, context);
1002
+ case 'unmerge_cells':
1003
+ return this.handleUnmergeCells(workbook, input, context);
1004
+ case 'upsert_conditional_format':
1005
+ return this.handleUpsertConditionalFormat(workbook, input, context);
1006
+ case 'delete_conditional_format':
1007
+ return this.handleDeleteConditionalFormat(workbook, input, context);
1008
+ case 'upsert_validation_rule':
1009
+ return this.handleUpsertValidationRule(workbook, input, context);
1010
+ case 'delete_validation_rule':
1011
+ return this.handleDeleteValidationRule(workbook, input, context);
1012
+ case 'upsert_named_range':
1013
+ return this.handleUpsertNamedRange(workbook, input, context);
1014
+ case 'delete_named_range':
1015
+ return this.handleDeleteNamedRange(workbook, input, context);
1016
+ case 'set_lock':
1017
+ return this.handleSetLock(workbook, input, context);
1018
+ case 'release_lock':
1019
+ return this.handleReleaseLock(workbook, input, context);
1020
+ case 'list_suggestions':
1021
+ return ExecuteListSuggestionsTool({
1022
+ domain: 'spreadsheet',
1023
+ artifactContent,
1024
+ input,
1025
+ context
1026
+ });
1027
+ case 'propose_suggestion':
1028
+ return this.handleProposeSuggestion(workbook, artifactContent, input, context);
1029
+ case 'review_suggestion':
1030
+ return this.handleReviewSuggestion(workbook, artifactContent, input, context);
1031
+ default:
1032
+ return this.errorResult(`Unknown SpreadsheetToolLibrary tool '${toolName}'.`);
1033
+ }
1034
+ });
1035
+ }
1036
+ async loadWorkbookFromContentIsolated(artifactContent) {
1037
+ const engine = SpreadsheetEngine.Instance;
1038
+ if (Buffer.isBuffer(artifactContent)) {
1039
+ if (artifactContent.length > 4 &&
1040
+ artifactContent[0] === 0x50 &&
1041
+ artifactContent[1] === 0x4b) {
1042
+ return await engine.ImportFromXlsxBytesIsolated(new Uint8Array(artifactContent));
1043
+ }
1044
+ return await engine.ParseWorkbookIsolated(artifactContent.toString('utf-8'));
1045
+ }
1046
+ return await engine.ParseWorkbookIsolated(artifactContent);
1047
+ }
1048
+ /**
1049
+ * Evaluates a workbook and computes its revision hash (`R9-9`).
1050
+ */
1051
+ ComputeRevisionHash(content) {
1052
+ const engine = SpreadsheetEngine.Instance;
1053
+ const workbook = Buffer.isBuffer(content)
1054
+ ? content.length > 4 && content[0] === 0x50 && content[1] === 0x4b
1055
+ ? engine.ImportFromXlsxBytes(new Uint8Array(content), undefined, { SkipEvaluate: true })
1056
+ : engine.ParseWorkbook(content.toString('utf-8'), undefined, { SkipEvaluate: true })
1057
+ : engine.ParseWorkbook(content, undefined, { SkipEvaluate: true });
1058
+ return engine.ComputeRevisionHash(workbook);
1059
+ }
1060
+ resolveSheet(workbook, sheetArg) {
1061
+ const engine = SpreadsheetEngine.Instance;
1062
+ if (typeof sheetArg === 'string' && sheetArg.trim().length > 0) {
1063
+ return engine.GetWorksheet(workbook, sheetArg.trim()) ?? null;
1064
+ }
1065
+ return (engine.GetWorksheet(workbook, workbook.ActiveSheetID) ??
1066
+ workbook.Worksheets[0] ??
1067
+ null);
1068
+ }
1069
+ async buildMutationSuccess(workbook, extra, options) {
1070
+ const engine = SpreadsheetEngine.Instance;
1071
+ if (!options?.skipEvaluate) {
1072
+ await engine.EvaluateWorkbookIsolated(workbook);
1073
+ }
1074
+ const serializedJson = engine.SerializeWorkbook(workbook);
1075
+ const originalXlsxBytes = this.activeOriginalXlsxStorage.getStore() ?? null;
1076
+ const xlsxBytes = originalXlsxBytes
1077
+ ? await engine.PatchXlsxBytesIsolated(originalXlsxBytes, workbook)
1078
+ : engine.ExportToXlsxBytes(workbook, true, { SkipEvaluate: true });
1079
+ const xlsxBase64 = Buffer.from(xlsxBytes).toString('base64');
1080
+ const revisionHash = engine.ComputeRevisionHash(workbook);
1081
+ return this.successResult({
1082
+ ...extra,
1083
+ revisionHash,
1084
+ updatedContent: serializedJson,
1085
+ xlsxBase64
1086
+ });
1087
+ }
1088
+ handleGetWorkbookOutline(workbook, revisionHash) {
1089
+ return this.successResult({
1090
+ workbookId: workbook.WorkbookID,
1091
+ title: workbook.Title,
1092
+ activeSheetId: workbook.ActiveSheetID,
1093
+ revisionHash,
1094
+ namedRanges: workbook.NamedRanges,
1095
+ sheets: workbook.Worksheets.map((ws) => {
1096
+ const cells = Object.values(ws.Cells);
1097
+ const formulaCount = cells.filter((c) => Boolean(c.Formula)).length;
1098
+ return {
1099
+ sheetId: ws.SheetID,
1100
+ name: ws.Name,
1101
+ rowCount: ws.Rows.length,
1102
+ columnCount: ws.Columns.length,
1103
+ populatedCellCount: cells.length,
1104
+ formulaCount,
1105
+ frozenRows: ws.FrozenRows,
1106
+ frozenColumns: ws.FrozenColumns,
1107
+ protectedRanges: ws.ProtectedRanges ?? [],
1108
+ liveTables: ws.LiveTables,
1109
+ charts: ws.Charts,
1110
+ embeddedArtifacts: ws.EmbeddedArtifacts
1111
+ };
1112
+ })
1113
+ });
1114
+ }
1115
+ handleReadRange(workbook, input, revisionHash) {
1116
+ const engine = SpreadsheetEngine.Instance;
1117
+ const sheet = this.resolveSheet(workbook, input.sheet ?? input.sheetName);
1118
+ if (!sheet) {
1119
+ return this.errorResult(`Worksheet '${String(input.sheet ?? input.sheetName ?? '')}' not found.`);
1120
+ }
1121
+ const range = typeof input.range === 'string' ? input.range.trim() : '';
1122
+ if (!range) {
1123
+ return this.errorResult('Parameter "range" is required (e.g. "B4" or "A1:D10").');
1124
+ }
1125
+ const bounds = ParseRangeAddress(range);
1126
+ if (!bounds) {
1127
+ return this.errorResult(`Invalid A1 range '${range}'.`);
1128
+ }
1129
+ const requestedCellCount = (bounds.endRow - bounds.startRow + 1) * (bounds.endCol - bounds.startCol + 1);
1130
+ if (requestedCellCount > MAX_READ_RANGE_CELLS) {
1131
+ return this.errorResult(`Requested range '${range}' spans ${requestedCellCount} cells, exceeding the maximum read_range limit of ${MAX_READ_RANGE_CELLS} cells.`);
1132
+ }
1133
+ if (bounds.endRow > MAX_SHEET_ROW_COUNT || bounds.endCol > MAX_SHEET_COLUMN_COUNT) {
1134
+ return this.errorResult(`Requested range '${range}' exceeds worksheet bounds (max ${MAX_SHEET_ROW_COUNT} rows x ${MAX_SHEET_COLUMN_COUNT} columns).`);
1135
+ }
1136
+ try {
1137
+ const grid = engine.ReadRange(workbook, sheet.SheetID, range);
1138
+ const flatCells = grid.flat().map((c) => ({
1139
+ address: c.Address,
1140
+ rowId: c.RowID,
1141
+ columnId: c.ColumnID,
1142
+ rawValue: c.RawValue,
1143
+ formula: c.Formula ?? null,
1144
+ formulaStable: c.FormulaStable ?? null,
1145
+ computedValue: c.ComputedValue ?? c.RawValue ?? null,
1146
+ displayValue: c.DisplayValue ??
1147
+ engine.FormatCellValue(c.ComputedValue ?? c.RawValue ?? null, c.Style),
1148
+ style: c.Style ?? null
1149
+ }));
1150
+ return this.successResult({
1151
+ sheetId: sheet.SheetID,
1152
+ sheetName: sheet.Name,
1153
+ range,
1154
+ revisionHash,
1155
+ cell: flatCells.length === 1 ? flatCells[0] : undefined,
1156
+ cells: flatCells,
1157
+ matrix: grid.map((row) => row.map((c) => c.ComputedValue ?? c.RawValue ?? null))
1158
+ });
1159
+ }
1160
+ catch (err) {
1161
+ return this.errorResult(err instanceof Error ? err.message : String(err));
1162
+ }
1163
+ }
1164
+ resolveWriteCellEntry(rec, index) {
1165
+ const rawAddr = typeof rec.address === 'string'
1166
+ ? rec.address.trim()
1167
+ : typeof rec.cell === 'string'
1168
+ ? rec.cell.trim()
1169
+ : typeof rec.ref === 'string'
1170
+ ? rec.ref.trim()
1171
+ : typeof rec.coord === 'string'
1172
+ ? rec.coord.trim()
1173
+ : '';
1174
+ if (rawAddr) {
1175
+ const parsedAddr = ParseCellAddress(rawAddr);
1176
+ if (!parsedAddr) {
1177
+ return {
1178
+ ok: false,
1179
+ errorMessage: `Invalid cell address '${rawAddr}' at cells[${index}]. Expected A1 notation or 0-based coordinates, e.g. { "address": "A1", "value": "Region" } or { "r": 0, "c": 0, "v": "Region" }.`
1180
+ };
1181
+ }
1182
+ if (parsedAddr.row > MAX_SHEET_ROW_COUNT || parsedAddr.col > MAX_SHEET_COLUMN_COUNT) {
1183
+ return {
1184
+ ok: false,
1185
+ errorMessage: `Cell address '${rawAddr}' exceeds maximum worksheet bounds (${MAX_SHEET_ROW_COUNT} rows x ${MAX_SHEET_COLUMN_COUNT} columns).`
1186
+ };
1187
+ }
1188
+ return {
1189
+ ok: true,
1190
+ canonicalAddr: FormatCellAddress(parsedAddr.row, parsedAddr.col),
1191
+ row: parsedAddr.row,
1192
+ col: parsedAddr.col
1193
+ };
1194
+ }
1195
+ if (rec.r !== undefined || rec.c !== undefined) {
1196
+ if (typeof rec.r !== 'number' ||
1197
+ typeof rec.c !== 'number' ||
1198
+ !Number.isInteger(rec.r) ||
1199
+ !Number.isInteger(rec.c) ||
1200
+ rec.r < 0 ||
1201
+ rec.c < 0) {
1202
+ return {
1203
+ ok: false,
1204
+ errorMessage: `Invalid cell coordinates at cells[${index}] (r=${String(rec.r)}, c=${String(rec.c)}): 0-based numeric indices r and c must be non-negative integers, e.g. { "r": 0, "c": 0, "v": "Region" } or { "address": "A1", "value": "Region" }.`
1205
+ };
1206
+ }
1207
+ const row = rec.r + 1;
1208
+ const col = rec.c + 1;
1209
+ if (row > MAX_SHEET_ROW_COUNT || col > MAX_SHEET_COLUMN_COUNT) {
1210
+ return {
1211
+ ok: false,
1212
+ errorMessage: `Cell coordinates (r=${rec.r}, c=${rec.c}) exceed maximum worksheet bounds (${MAX_SHEET_ROW_COUNT} rows x ${MAX_SHEET_COLUMN_COUNT} columns).`
1213
+ };
1214
+ }
1215
+ return {
1216
+ ok: true,
1217
+ canonicalAddr: FormatCellAddress(row, col),
1218
+ row,
1219
+ col
1220
+ };
1221
+ }
1222
+ return {
1223
+ ok: false,
1224
+ errorMessage: `Invalid cell address '' at cells[${index}]. Provide A1 notation or 0-based coordinates, e.g. { "address": "A1", "value": "Region" } or { "r": 0, "c": 0, "v": "Region" }.`
1225
+ };
1226
+ }
1227
+ async handleWriteCells(workbook, input, context) {
1228
+ const engine = SpreadsheetEngine.Instance;
1229
+ const sheet = this.resolveSheet(workbook, input.sheet);
1230
+ if (!sheet) {
1231
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1232
+ }
1233
+ const rawCells = Array.isArray(input.cells) ? input.cells : [];
1234
+ if (rawCells.length === 0) {
1235
+ return this.errorResult('Parameter "cells" must be a non-empty array of cell updates.');
1236
+ }
1237
+ if (rawCells.length > 10_000) {
1238
+ return this.errorResult(`Parameter "cells" exceeds maximum per-call batch limit of 10000 updates (got ${rawCells.length}).`);
1239
+ }
1240
+ const editCtx = this.extractCellEditContext(context);
1241
+ const normalizedCells = [];
1242
+ // Pre-validate cell addresses and protected ranges atomically before mutating any cell in the batch
1243
+ for (let idx = 0; idx < rawCells.length; idx++) {
1244
+ const item = rawCells[idx];
1245
+ if (!item || typeof item !== 'object' || Array.isArray(item))
1246
+ continue;
1247
+ const rec = item;
1248
+ const resolved = this.resolveWriteCellEntry(rec, idx);
1249
+ if (resolved.ok === false) {
1250
+ return this.errorResult(resolved.errorMessage);
1251
+ }
1252
+ const perm = engine.CheckCellWritePermission(sheet, resolved.canonicalAddr, editCtx);
1253
+ if (!perm.Allowed) {
1254
+ return this.errorResult(perm.Reason || `Cell '${resolved.canonicalAddr}' is inside a protected range.`);
1255
+ }
1256
+ normalizedCells.push({ rec, canonicalAddr: resolved.canonicalAddr });
1257
+ }
1258
+ const updatedAddresses = [];
1259
+ const mjFormulaCells = [];
1260
+ for (const { rec, canonicalAddr } of normalizedCells) {
1261
+ const existingCell = sheet.Cells[canonicalAddr];
1262
+ const rawValue = rec.value !== undefined ? rec.value : rec.v !== undefined ? rec.v : rec.val;
1263
+ const val = rawValue === null ||
1264
+ typeof rawValue === 'string' ||
1265
+ typeof rawValue === 'number' ||
1266
+ typeof rawValue === 'boolean'
1267
+ ? rawValue
1268
+ : undefined;
1269
+ const rawFormula = rec.formula !== undefined ? rec.formula : rec.f;
1270
+ const formula = typeof rawFormula === 'string' ? rawFormula : undefined;
1271
+ const stylePatch = buildStylePatch(rec, existingCell?.Style);
1272
+ const note = typeof rec.note === 'string' ? rec.note : undefined;
1273
+ engine.SetCell(workbook, sheet.SheetID, canonicalAddr, {
1274
+ Value: val,
1275
+ Formula: formula,
1276
+ Style: stylePatch,
1277
+ Note: note
1278
+ }, false, editCtx);
1279
+ updatedAddresses.push(canonicalAddr);
1280
+ if (formula && engine.ParseMjCustomFunctionFormula(formula) !== null) {
1281
+ mjFormulaCells.push(canonicalAddr);
1282
+ }
1283
+ }
1284
+ const preEvalSnapshot = mjFormulaCells.length > 0
1285
+ ? {
1286
+ cells: { ...sheet.Cells },
1287
+ rows: [...sheet.Rows],
1288
+ columns: [...sheet.Columns]
1289
+ }
1290
+ : null;
1291
+ const spilledRanges = [];
1292
+ if (mjFormulaCells.length > 0 && context?.contextUser && context?.provider) {
1293
+ await engine.EvaluateMjCustomFunctions(workbook, context.contextUser, context.provider, {
1294
+ HostArtifactID: context.artifactId,
1295
+ BypassCache: true
1296
+ });
1297
+ for (const formulaCell of mjFormulaCells) {
1298
+ const summary = this.summarizeSpilledFormulaFootprint(sheet, formulaCell);
1299
+ if (summary) {
1300
+ const spillBounds = ParseRangeAddress(summary.boundingRange);
1301
+ if (spillBounds) {
1302
+ const spillProtErr = checkBoundsProtection(sheet, spillBounds, editCtx, `spill formula '${formulaCell}' across '${summary.boundingRange}'`);
1303
+ if (spillProtErr && preEvalSnapshot) {
1304
+ sheet.Cells = preEvalSnapshot.cells;
1305
+ sheet.Rows = preEvalSnapshot.rows;
1306
+ sheet.Columns = preEvalSnapshot.columns;
1307
+ return this.errorResult(spillProtErr);
1308
+ }
1309
+ }
1310
+ spilledRanges.push(summary);
1311
+ }
1312
+ }
1313
+ }
1314
+ await engine.EvaluateWorkbookIsolated(workbook);
1315
+ const refreshedSheet = engine.GetWorksheet(workbook, sheet.SheetID) ?? sheet;
1316
+ const updatedCells = updatedAddresses
1317
+ .map((a) => refreshedSheet.Cells[a])
1318
+ .filter((c) => Boolean(c));
1319
+ return this.buildMutationSuccess(workbook, {
1320
+ sheetId: refreshedSheet.SheetID,
1321
+ sheetName: refreshedSheet.Name,
1322
+ updatedCells: updatedCells.map((c) => ({
1323
+ address: c.Address,
1324
+ rowId: c.RowID,
1325
+ columnId: c.ColumnID,
1326
+ rawValue: c.RawValue,
1327
+ formula: c.Formula ?? null,
1328
+ formulaStable: c.FormulaStable ?? null,
1329
+ computedValue: c.ComputedValue ?? null,
1330
+ displayValue: c.DisplayValue ?? ''
1331
+ })),
1332
+ ...(spilledRanges.length > 0 ? { spilledRanges } : {})
1333
+ }, { skipEvaluate: true });
1334
+ }
1335
+ async handleFormatRange(workbook, input, context) {
1336
+ const engine = SpreadsheetEngine.Instance;
1337
+ const sheet = this.resolveSheet(workbook, input.sheet);
1338
+ if (!sheet) {
1339
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1340
+ }
1341
+ const range = typeof input.range === 'string' ? input.range.trim() : '';
1342
+ if (!range) {
1343
+ return this.errorResult('Parameter "range" is required.');
1344
+ }
1345
+ const bounds = ParseRangeAddress(range);
1346
+ if (!bounds) {
1347
+ return this.errorResult(`Invalid A1 range '${range}'.`);
1348
+ }
1349
+ const cellCount = (bounds.endRow - bounds.startRow + 1) * (bounds.endCol - bounds.startCol + 1);
1350
+ if (cellCount > MAX_READ_RANGE_CELLS) {
1351
+ return this.errorResult(`Requested range '${range}' spans ${cellCount} cells, exceeding the limit of ${MAX_READ_RANGE_CELLS}.`);
1352
+ }
1353
+ if (bounds.endRow > MAX_SHEET_ROW_COUNT || bounds.endCol > MAX_SHEET_COLUMN_COUNT) {
1354
+ return this.errorResult(`Requested range '${range}' exceeds worksheet bounds.`);
1355
+ }
1356
+ const stylePreview = buildStylePatch(input);
1357
+ if (!stylePreview) {
1358
+ return this.errorResult('format_range requires at least one style property (bold, italic, horizontalAlign, textColor, backgroundColor, formatType, numberFormatPattern).');
1359
+ }
1360
+ const editCtx = this.extractCellEditContext(context);
1361
+ const protErr = checkBoundsProtection(sheet, bounds, editCtx, `format range '${range}'`);
1362
+ if (protErr) {
1363
+ return this.errorResult(protErr);
1364
+ }
1365
+ let formattedCellCount = 0;
1366
+ for (let r = bounds.startRow; r <= bounds.endRow; r++) {
1367
+ for (let c = bounds.startCol; c <= bounds.endCol; c++) {
1368
+ const addr = FormatCellAddress(r, c);
1369
+ const cellPatch = buildStylePatch(input, sheet.Cells[addr]?.Style);
1370
+ if (cellPatch) {
1371
+ engine.SetCell(workbook, sheet.SheetID, addr, { Style: cellPatch }, false, editCtx);
1372
+ formattedCellCount++;
1373
+ }
1374
+ }
1375
+ }
1376
+ return this.buildMutationSuccess(workbook, {
1377
+ sheetId: sheet.SheetID,
1378
+ sheetName: sheet.Name,
1379
+ range,
1380
+ formattedCellCount,
1381
+ styleApplied: stylePreview
1382
+ });
1383
+ }
1384
+ async handleClearRange(workbook, input, context) {
1385
+ const engine = SpreadsheetEngine.Instance;
1386
+ const sheet = this.resolveSheet(workbook, input.sheet);
1387
+ if (!sheet) {
1388
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1389
+ }
1390
+ const range = typeof input.range === 'string' ? input.range.trim() : '';
1391
+ if (!range) {
1392
+ return this.errorResult('Parameter "range" is required.');
1393
+ }
1394
+ const bounds = ParseRangeAddress(range);
1395
+ if (!bounds) {
1396
+ return this.errorResult(`Invalid A1 range '${range}'.`);
1397
+ }
1398
+ const modeRaw = typeof input.mode === 'string' ? input.mode.trim().toLowerCase() : 'all';
1399
+ if (modeRaw !== 'all' && modeRaw !== 'values' && modeRaw !== 'formats' && modeRaw !== 'notes') {
1400
+ return this.errorResult(`Unsupported clear_range mode '${modeRaw}'. Valid modes: all, values, formats, notes.`);
1401
+ }
1402
+ const editCtx = this.extractCellEditContext(context);
1403
+ if (modeRaw === 'all') {
1404
+ let clearedAddresses;
1405
+ try {
1406
+ clearedAddresses = engine.ClearRange(workbook, sheet.SheetID, range, false, editCtx);
1407
+ }
1408
+ catch (err) {
1409
+ return this.errorResult(err instanceof Error ? err.message : String(err));
1410
+ }
1411
+ return this.buildMutationSuccess(workbook, {
1412
+ sheetId: sheet.SheetID,
1413
+ clearedRange: range,
1414
+ mode: 'all',
1415
+ clearedAddresses
1416
+ });
1417
+ }
1418
+ const protErr = checkBoundsProtection(sheet, bounds, editCtx, `clear range '${range}'`);
1419
+ if (protErr) {
1420
+ return this.errorResult(protErr);
1421
+ }
1422
+ const targetCells = [];
1423
+ for (const [addr, cell] of Object.entries(sheet.Cells)) {
1424
+ const pos = ParseCellAddress(addr);
1425
+ if (pos &&
1426
+ pos.row >= bounds.startRow &&
1427
+ pos.row <= bounds.endRow &&
1428
+ pos.col >= bounds.startCol &&
1429
+ pos.col <= bounds.endCol) {
1430
+ targetCells.push(cell);
1431
+ }
1432
+ }
1433
+ const clearedAddresses = [];
1434
+ for (const cell of targetCells) {
1435
+ const addr = cell.Address;
1436
+ const perm = engine.CheckCellWritePermission(sheet, addr, editCtx);
1437
+ if (!perm.Allowed) {
1438
+ return this.errorResult(perm.Reason || `Cell '${addr}' is inside a protected range.`);
1439
+ }
1440
+ if (modeRaw === 'values') {
1441
+ engine.SetCell(workbook, sheet.SheetID, addr, { Value: null }, false, editCtx);
1442
+ clearedAddresses.push(addr);
1443
+ }
1444
+ else if (modeRaw === 'formats') {
1445
+ if (cell.Style) {
1446
+ delete cell.Style;
1447
+ clearedAddresses.push(addr);
1448
+ }
1449
+ }
1450
+ else if (modeRaw === 'notes') {
1451
+ if (cell.Note !== undefined && cell.Note !== null) {
1452
+ cell.Note = null;
1453
+ clearedAddresses.push(addr);
1454
+ }
1455
+ }
1456
+ }
1457
+ return this.buildMutationSuccess(workbook, {
1458
+ sheetId: sheet.SheetID,
1459
+ clearedRange: range,
1460
+ mode: modeRaw,
1461
+ clearedAddresses
1462
+ });
1463
+ }
1464
+ extractCellEditContext(context) {
1465
+ return {
1466
+ UserID: context?.actorUserId ?? context?.contextUser?.ID ?? null,
1467
+ OwnerUserID: context?.ownerUserId ?? null,
1468
+ IsEditor: Boolean(context?.isEditor)
1469
+ };
1470
+ }
1471
+ async handleInsertRows(workbook, input, context) {
1472
+ const sheet = this.resolveSheet(workbook, input.sheet);
1473
+ if (!sheet) {
1474
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1475
+ }
1476
+ const atRow = Math.max(1, Math.trunc(Number(input.atRowNumber) || 1));
1477
+ const rawCount = input.count !== undefined ? Math.trunc(Number(input.count)) : 1;
1478
+ if (Number.isNaN(rawCount) || rawCount < 1 || rawCount > MAX_INSERT_COUNT) {
1479
+ return this.errorResult(`Insert row count must be between 1 and ${MAX_INSERT_COUNT}.`);
1480
+ }
1481
+ if (sheet.Rows.length + rawCount > MAX_SHEET_ROW_COUNT) {
1482
+ return this.errorResult(`Cannot exceed maximum worksheet row count (${MAX_SHEET_ROW_COUNT}).`);
1483
+ }
1484
+ const editCtx = this.extractCellEditContext(context);
1485
+ const protErr = checkBoundsProtection(sheet, { startRow: atRow, endRow: MAX_SHEET_ROW_COUNT, startCol: 1, endCol: MAX_SHEET_COLUMN_COUNT }, editCtx, `insert ${rawCount} row(s) at row ${atRow}`);
1486
+ if (protErr) {
1487
+ return this.errorResult(protErr);
1488
+ }
1489
+ const inserted = SpreadsheetEngine.Instance.InsertRows(workbook, sheet.SheetID, atRow, rawCount, undefined, false);
1490
+ return this.buildMutationSuccess(workbook, {
1491
+ sheetId: sheet.SheetID,
1492
+ insertedRowIds: inserted.map((r) => r.RowID),
1493
+ rowCount: sheet.Rows.length
1494
+ });
1495
+ }
1496
+ async handleDeleteRows(workbook, input, context) {
1497
+ const sheet = this.resolveSheet(workbook, input.sheet);
1498
+ if (!sheet) {
1499
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1500
+ }
1501
+ const rawAtRow = Number(input.atRowNumber);
1502
+ if (!Number.isFinite(rawAtRow) || rawAtRow < 1) {
1503
+ return this.errorResult('Parameter "atRowNumber" must be a positive 1-based row number.');
1504
+ }
1505
+ const atRow = Math.trunc(rawAtRow);
1506
+ const rawCount = input.count !== undefined ? Math.trunc(Number(input.count)) : 1;
1507
+ if (Number.isNaN(rawCount) || rawCount < 1 || rawCount > MAX_INSERT_COUNT) {
1508
+ return this.errorResult(`Delete row count must be between 1 and ${MAX_INSERT_COUNT}.`);
1509
+ }
1510
+ if (atRow > MAX_SHEET_ROW_COUNT) {
1511
+ return this.errorResult(`Row number ${atRow} exceeds maximum worksheet rows (${MAX_SHEET_ROW_COUNT}).`);
1512
+ }
1513
+ const endRow = Math.min(MAX_SHEET_ROW_COUNT, atRow + rawCount - 1);
1514
+ const editCtx = this.extractCellEditContext(context);
1515
+ const protErr = checkBoundsProtection(sheet, { startRow: atRow, endRow, startCol: 1, endCol: MAX_SHEET_COLUMN_COUNT }, editCtx, `delete row(s) ${atRow}..${endRow}`);
1516
+ if (protErr) {
1517
+ return this.errorResult(protErr);
1518
+ }
1519
+ SpreadsheetEngine.Instance.DeleteRows(workbook, sheet.SheetID, atRow, rawCount, undefined, false);
1520
+ return this.buildMutationSuccess(workbook, {
1521
+ sheetId: sheet.SheetID,
1522
+ deletedAtRow: atRow,
1523
+ deletedCount: rawCount,
1524
+ rowCount: sheet.Rows.length
1525
+ });
1526
+ }
1527
+ async handleInsertColumns(workbook, input, context) {
1528
+ const sheet = this.resolveSheet(workbook, input.sheet);
1529
+ if (!sheet) {
1530
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1531
+ }
1532
+ const atCol = Math.max(1, Math.trunc(Number(input.atColumnNumber) || 1));
1533
+ const rawCount = input.count !== undefined ? Math.trunc(Number(input.count)) : 1;
1534
+ if (Number.isNaN(rawCount) || rawCount < 1 || rawCount > MAX_INSERT_COUNT) {
1535
+ return this.errorResult(`Insert column count must be between 1 and ${MAX_INSERT_COUNT}.`);
1536
+ }
1537
+ if (sheet.Columns.length + rawCount > MAX_SHEET_COLUMN_COUNT) {
1538
+ return this.errorResult(`Cannot exceed maximum worksheet column count (${MAX_SHEET_COLUMN_COUNT}).`);
1539
+ }
1540
+ const editCtx = this.extractCellEditContext(context);
1541
+ const protErr = checkBoundsProtection(sheet, { startRow: 1, endRow: MAX_SHEET_ROW_COUNT, startCol: atCol, endCol: MAX_SHEET_COLUMN_COUNT }, editCtx, `insert ${rawCount} column(s) at column ${atCol}`);
1542
+ if (protErr) {
1543
+ return this.errorResult(protErr);
1544
+ }
1545
+ const inserted = SpreadsheetEngine.Instance.InsertColumns(workbook, sheet.SheetID, atCol, rawCount, undefined, false);
1546
+ return this.buildMutationSuccess(workbook, {
1547
+ sheetId: sheet.SheetID,
1548
+ insertedColumnIds: inserted.map((c) => c.ColumnID),
1549
+ columnCount: sheet.Columns.length
1550
+ });
1551
+ }
1552
+ async handleDeleteColumns(workbook, input, context) {
1553
+ const sheet = this.resolveSheet(workbook, input.sheet);
1554
+ if (!sheet) {
1555
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1556
+ }
1557
+ const rawAtCol = Number(input.atColumnNumber);
1558
+ if (!Number.isFinite(rawAtCol) || rawAtCol < 1) {
1559
+ return this.errorResult('Parameter "atColumnNumber" must be a positive 1-based column number.');
1560
+ }
1561
+ const atCol = Math.trunc(rawAtCol);
1562
+ const rawCount = input.count !== undefined ? Math.trunc(Number(input.count)) : 1;
1563
+ if (Number.isNaN(rawCount) || rawCount < 1 || rawCount > MAX_INSERT_COUNT) {
1564
+ return this.errorResult(`Delete column count must be between 1 and ${MAX_INSERT_COUNT}.`);
1565
+ }
1566
+ if (atCol > MAX_SHEET_COLUMN_COUNT) {
1567
+ return this.errorResult(`Column number ${atCol} exceeds maximum worksheet columns (${MAX_SHEET_COLUMN_COUNT}).`);
1568
+ }
1569
+ const endCol = Math.min(MAX_SHEET_COLUMN_COUNT, atCol + rawCount - 1);
1570
+ const editCtx = this.extractCellEditContext(context);
1571
+ const protErr = checkBoundsProtection(sheet, { startRow: 1, endRow: MAX_SHEET_ROW_COUNT, startCol: atCol, endCol }, editCtx, `delete column(s) ${atCol}..${endCol}`);
1572
+ if (protErr) {
1573
+ return this.errorResult(protErr);
1574
+ }
1575
+ SpreadsheetEngine.Instance.DeleteColumns(workbook, sheet.SheetID, atCol, rawCount, undefined, false);
1576
+ return this.buildMutationSuccess(workbook, {
1577
+ sheetId: sheet.SheetID,
1578
+ deletedAtColumn: atCol,
1579
+ deletedCount: rawCount,
1580
+ columnCount: sheet.Columns.length
1581
+ });
1582
+ }
1583
+ async handleAddSheet(workbook, input) {
1584
+ const name = typeof input.name === 'string' ? input.name.trim() : '';
1585
+ if (!name) {
1586
+ return this.errorResult('Parameter "name" is required.');
1587
+ }
1588
+ const rawRows = input.rowCount !== undefined ? Math.trunc(Number(input.rowCount)) : 25;
1589
+ const rawCols = input.columnCount !== undefined ? Math.trunc(Number(input.columnCount)) : 12;
1590
+ if (Number.isNaN(rawRows) || rawRows < 1 || rawRows > MAX_SHEET_ROW_COUNT) {
1591
+ return this.errorResult(`Parameter "rowCount" must be between 1 and ${MAX_SHEET_ROW_COUNT}.`);
1592
+ }
1593
+ if (Number.isNaN(rawCols) || rawCols < 1 || rawCols > MAX_SHEET_COLUMN_COUNT) {
1594
+ return this.errorResult(`Parameter "columnCount" must be between 1 and ${MAX_SHEET_COLUMN_COUNT}.`);
1595
+ }
1596
+ const ws = SpreadsheetEngine.Instance.AddWorksheet(workbook, name, rawRows, rawCols);
1597
+ return this.buildMutationSuccess(workbook, {
1598
+ sheetId: ws.SheetID,
1599
+ name: ws.Name
1600
+ });
1601
+ }
1602
+ async handleRenameSheet(workbook, input) {
1603
+ const sheet = this.resolveSheet(workbook, input.sheet);
1604
+ if (!sheet) {
1605
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1606
+ }
1607
+ const newName = typeof input.newName === 'string' ? input.newName.replace(/[\[\]:*?/\\]/g, ' ').trim().slice(0, 31) : '';
1608
+ if (!newName) {
1609
+ return this.errorResult('Parameter "newName" is required.');
1610
+ }
1611
+ if (workbook.Worksheets.some((w) => w.SheetID !== sheet.SheetID && w.Name.toLowerCase() === newName.toLowerCase())) {
1612
+ return this.errorResult(`A worksheet named '${newName}' already exists.`);
1613
+ }
1614
+ if (!SpreadsheetEngine.Instance.RenameWorksheet(workbook, sheet.SheetID, newName, false)) {
1615
+ return this.errorResult(`Failed to rename worksheet '${sheet.Name}' to '${newName}'.`);
1616
+ }
1617
+ return this.buildMutationSuccess(workbook, {
1618
+ sheetId: sheet.SheetID,
1619
+ name: sheet.Name
1620
+ });
1621
+ }
1622
+ async handleDuplicateSheet(workbook, input) {
1623
+ const engine = SpreadsheetEngine.Instance;
1624
+ const sourceSheet = this.resolveSheet(workbook, input.sheet);
1625
+ if (!sourceSheet) {
1626
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1627
+ }
1628
+ const existingNames = new Set(workbook.Worksheets.map((w) => w.Name.toLowerCase()));
1629
+ let targetName;
1630
+ if (typeof input.newName === 'string' && input.newName.trim()) {
1631
+ targetName = input.newName.replace(/[\[\]:*?/\\]/g, ' ').trim().slice(0, 31);
1632
+ if (!targetName) {
1633
+ return this.errorResult('Parameter "newName" must contain valid worksheet name characters.');
1634
+ }
1635
+ if (existingNames.has(targetName.toLowerCase())) {
1636
+ return this.errorResult(`A worksheet named '${targetName}' already exists.`);
1637
+ }
1638
+ }
1639
+ else {
1640
+ const base = sourceSheet.Name.slice(0, 24);
1641
+ let candidate = `${base} (Copy)`.slice(0, 31);
1642
+ let suffix = 2;
1643
+ while (existingNames.has(candidate.toLowerCase())) {
1644
+ const tag = ` (${suffix++})`;
1645
+ candidate = `${base.slice(0, 31 - tag.length)}${tag}`;
1646
+ }
1647
+ targetName = candidate;
1648
+ }
1649
+ const existingSheetIds = new Set(workbook.Worksheets.map((w) => w.SheetID));
1650
+ let newSheetId = `sheet-${randomUUID().slice(0, 8)}`;
1651
+ while (existingSheetIds.has(newSheetId)) {
1652
+ newSheetId = `sheet-${randomUUID().slice(0, 8)}`;
1653
+ }
1654
+ const rowIdMap = new Map();
1655
+ const clonedRows = sourceSheet.Rows.map((row) => {
1656
+ const nextRowId = `${newSheetId}-row-${randomUUID().slice(0, 8)}`;
1657
+ rowIdMap.set(row.RowID, nextRowId);
1658
+ return { ...row, RowID: nextRowId };
1659
+ });
1660
+ const colIdMap = new Map();
1661
+ const clonedCols = sourceSheet.Columns.map((col) => {
1662
+ const nextColId = `${newSheetId}-col-${randomUUID().slice(0, 8)}`;
1663
+ colIdMap.set(col.ColumnID, nextColId);
1664
+ return { ...col, ColumnID: nextColId };
1665
+ });
1666
+ const tableIdMap = new Map();
1667
+ const clonedLiveTables = sourceSheet.LiveTables.map((tbl) => {
1668
+ const nextTableId = `tbl-${randomUUID().slice(0, 8)}`;
1669
+ tableIdMap.set(tbl.TableID, nextTableId);
1670
+ return {
1671
+ ...tbl,
1672
+ TableID: nextTableId,
1673
+ Fields: tbl.Fields ? [...tbl.Fields] : undefined,
1674
+ QueryParameters: tbl.QueryParameters ? { ...tbl.QueryParameters } : undefined,
1675
+ CalculatedColumns: tbl.CalculatedColumns ? tbl.CalculatedColumns.map((cc) => ({ ...cc })) : undefined
1676
+ };
1677
+ });
1678
+ const clonedCharts = sourceSheet.Charts.map((ch) => ({
1679
+ ...ch,
1680
+ ChartID: `chart-${randomUUID().slice(0, 8)}`,
1681
+ SheetID: newSheetId,
1682
+ IncludedSeriesIndices: ch.IncludedSeriesIndices ? [...ch.IncludedSeriesIndices] : undefined
1683
+ }));
1684
+ const clonedEmbeds = sourceSheet.EmbeddedArtifacts.map((emb) => ({
1685
+ ...emb,
1686
+ EmbedID: `embed-${randomUUID().slice(0, 8)}`
1687
+ }));
1688
+ const clonedProtected = sourceSheet.ProtectedRanges
1689
+ ? sourceSheet.ProtectedRanges.map((pr) => ({
1690
+ ...pr,
1691
+ RangeID: `prot-${randomUUID().slice(0, 8)}`
1692
+ }))
1693
+ : undefined;
1694
+ const clonedCells = {};
1695
+ const vrowPrefix = `${sourceSheet.SheetID}-vrow-`;
1696
+ const vcolPrefix = `${sourceSheet.SheetID}-vcol-`;
1697
+ for (const [addr, cell] of Object.entries(sourceSheet.Cells)) {
1698
+ let nextRowId = rowIdMap.get(cell.RowID);
1699
+ if (!nextRowId) {
1700
+ nextRowId = cell.RowID.startsWith(vrowPrefix)
1701
+ ? `${newSheetId}-vrow-${cell.RowID.slice(vrowPrefix.length)}`
1702
+ : `${newSheetId}-row-${randomUUID().slice(0, 8)}`;
1703
+ rowIdMap.set(cell.RowID, nextRowId);
1704
+ }
1705
+ let nextColId = colIdMap.get(cell.ColumnID);
1706
+ if (!nextColId) {
1707
+ nextColId = cell.ColumnID.startsWith(vcolPrefix)
1708
+ ? `${newSheetId}-vcol-${cell.ColumnID.slice(vcolPrefix.length)}`
1709
+ : `${newSheetId}-col-${randomUUID().slice(0, 8)}`;
1710
+ colIdMap.set(cell.ColumnID, nextColId);
1711
+ }
1712
+ clonedCells[addr] = {
1713
+ ...cell,
1714
+ RowID: nextRowId,
1715
+ ColumnID: nextColId,
1716
+ Style: cell.Style ? { ...cell.Style } : undefined,
1717
+ LiveTableID: cell.LiveTableID ? (tableIdMap.get(cell.LiveTableID) ?? cell.LiveTableID) : cell.LiveTableID
1718
+ };
1719
+ }
1720
+ const clonedSheet = {
1721
+ SheetID: newSheetId,
1722
+ Name: targetName,
1723
+ Rows: clonedRows,
1724
+ Columns: clonedCols,
1725
+ Cells: clonedCells,
1726
+ FrozenRows: sourceSheet.FrozenRows,
1727
+ FrozenColumns: sourceSheet.FrozenColumns,
1728
+ SortSpec: sourceSheet.SortSpec ? { ...sourceSheet.SortSpec } : sourceSheet.SortSpec,
1729
+ FilterSpecs: sourceSheet.FilterSpecs.map((f) => ({ ...f })),
1730
+ ValidationRules: sourceSheet.ValidationRules.map((v) => ({
1731
+ ...v,
1732
+ AllowedValues: v.AllowedValues ? [...v.AllowedValues] : undefined
1733
+ })),
1734
+ ConditionalFormats: sourceSheet.ConditionalFormats.map((cf) => ({
1735
+ ...cf,
1736
+ RuleID: `cf-${randomUUID().slice(0, 8)}`
1737
+ })),
1738
+ LiveTables: clonedLiveTables,
1739
+ Charts: clonedCharts,
1740
+ EmbeddedArtifacts: clonedEmbeds,
1741
+ ProtectedRanges: clonedProtected
1742
+ };
1743
+ const srcIdx = workbook.Worksheets.findIndex((w) => w.SheetID === sourceSheet.SheetID);
1744
+ workbook.Worksheets.splice(srcIdx + 1, 0, clonedSheet);
1745
+ for (const cell of Object.values(clonedSheet.Cells)) {
1746
+ if (cell.Formula && cell.Formula.trim().startsWith('=')) {
1747
+ cell.FormulaStable = engine.CompileFormulaToStableIds(clonedSheet, cell.Formula, workbook);
1748
+ }
1749
+ }
1750
+ return this.buildMutationSuccess(workbook, {
1751
+ sourceSheetId: sourceSheet.SheetID,
1752
+ sheetId: clonedSheet.SheetID,
1753
+ name: clonedSheet.Name,
1754
+ sheetCount: workbook.Worksheets.length
1755
+ });
1756
+ }
1757
+ async handleReorderSheets(workbook, input) {
1758
+ const rawIds = Array.isArray(input.sheetIds) ? input.sheetIds : [];
1759
+ const requestedIds = rawIds.filter((s) => typeof s === 'string' && s.trim().length > 0).map((s) => s.trim());
1760
+ if (requestedIds.length === 0) {
1761
+ return this.errorResult('Parameter "sheetIds" must be a non-empty array of sheet IDs or names.');
1762
+ }
1763
+ const reordered = [];
1764
+ const seenIds = new Set();
1765
+ for (const ref of requestedIds) {
1766
+ const match = this.resolveSheet(workbook, ref);
1767
+ if (!match) {
1768
+ return this.errorResult(`Worksheet '${ref}' not found.`);
1769
+ }
1770
+ if (!seenIds.has(match.SheetID)) {
1771
+ seenIds.add(match.SheetID);
1772
+ reordered.push(match);
1773
+ }
1774
+ }
1775
+ for (const ws of workbook.Worksheets) {
1776
+ if (!seenIds.has(ws.SheetID)) {
1777
+ reordered.push(ws);
1778
+ }
1779
+ }
1780
+ workbook.Worksheets = reordered;
1781
+ return this.buildMutationSuccess(workbook, {
1782
+ orderedSheets: reordered.map((w) => ({ sheetId: w.SheetID, name: w.Name }))
1783
+ });
1784
+ }
1785
+ async handleDeleteSheet(workbook, input, context) {
1786
+ if (workbook.Worksheets.length <= 1) {
1787
+ return this.errorResult('Cannot delete the only worksheet in the workbook.');
1788
+ }
1789
+ const sheet = this.resolveSheet(workbook, input.sheet);
1790
+ if (!sheet) {
1791
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1792
+ }
1793
+ const editCtx = this.extractCellEditContext(context);
1794
+ if (!editCtx.BypassProtection && (sheet.ProtectedRanges?.length ?? 0) > 0) {
1795
+ const blockingRule = sheet.ProtectedRanges.find((rule) => !isActorAllowedForProtectedRule(rule, editCtx));
1796
+ if (blockingRule) {
1797
+ return this.errorResult(`Cannot delete worksheet '${sheet.Name}': contains protected range '${blockingRule.Range}' (locked by ${blockingRule.LockedByUserID}).`);
1798
+ }
1799
+ }
1800
+ workbook.Worksheets = workbook.Worksheets.filter((w) => w.SheetID !== sheet.SheetID);
1801
+ if (workbook.ActiveSheetID === sheet.SheetID) {
1802
+ workbook.ActiveSheetID = workbook.Worksheets[0].SheetID;
1803
+ }
1804
+ return this.buildMutationSuccess(workbook, {
1805
+ deletedSheetId: sheet.SheetID,
1806
+ remainingSheetIds: workbook.Worksheets.map((w) => w.SheetID)
1807
+ });
1808
+ }
1809
+ async handleSetSheetLayout(workbook, input, context) {
1810
+ const sheet = this.resolveSheet(workbook, input.sheet);
1811
+ if (!sheet) {
1812
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1813
+ }
1814
+ const editCtx = this.extractCellEditContext(context);
1815
+ if (Array.isArray(input.rowHeights)) {
1816
+ for (const entry of input.rowHeights) {
1817
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
1818
+ continue;
1819
+ const rec = entry;
1820
+ const rowNumber = typeof rec.rowNumber === 'number' ? Math.trunc(rec.rowNumber) : NaN;
1821
+ if (!Number.isFinite(rowNumber) || rowNumber < 1 || rowNumber > MAX_SHEET_ROW_COUNT) {
1822
+ return this.errorResult(`Invalid rowNumber '${String(rec.rowNumber ?? '')}' in rowHeights.`);
1823
+ }
1824
+ if (rec.hidden === true || (typeof rec.height === 'number' && rec.height === 0)) {
1825
+ const protErr = checkBoundsProtection(sheet, { startRow: rowNumber, endRow: rowNumber, startCol: 1, endCol: MAX_SHEET_COLUMN_COUNT }, editCtx, `hide row ${rowNumber}`);
1826
+ if (protErr) {
1827
+ return this.errorResult(protErr);
1828
+ }
1829
+ }
1830
+ }
1831
+ }
1832
+ if (Array.isArray(input.columnWidths)) {
1833
+ for (const entry of input.columnWidths) {
1834
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
1835
+ continue;
1836
+ const rec = entry;
1837
+ const colNum = resolveColumnNumber(rec.column);
1838
+ if (!colNum) {
1839
+ return this.errorResult(`Invalid column '${String(rec.column ?? '')}' in columnWidths.`);
1840
+ }
1841
+ if (rec.hidden === true || (typeof rec.width === 'number' && rec.width === 0)) {
1842
+ const protErr = checkBoundsProtection(sheet, { startRow: 1, endRow: MAX_SHEET_ROW_COUNT, startCol: colNum, endCol: colNum }, editCtx, `hide column ${colNum}`);
1843
+ if (protErr) {
1844
+ return this.errorResult(protErr);
1845
+ }
1846
+ }
1847
+ }
1848
+ }
1849
+ if (typeof input.frozenRows === 'number' && Number.isFinite(input.frozenRows)) {
1850
+ const frozenRows = Math.trunc(input.frozenRows);
1851
+ if (frozenRows < 0 || frozenRows > MAX_SHEET_ROW_COUNT) {
1852
+ return this.errorResult(`frozenRows must be between 0 and ${MAX_SHEET_ROW_COUNT}.`);
1853
+ }
1854
+ sheet.FrozenRows = frozenRows;
1855
+ }
1856
+ if (typeof input.frozenColumns === 'number' && Number.isFinite(input.frozenColumns)) {
1857
+ const frozenCols = Math.trunc(input.frozenColumns);
1858
+ if (frozenCols < 0 || frozenCols > MAX_SHEET_COLUMN_COUNT) {
1859
+ return this.errorResult(`frozenColumns must be between 0 and ${MAX_SHEET_COLUMN_COUNT}.`);
1860
+ }
1861
+ sheet.FrozenColumns = frozenCols;
1862
+ }
1863
+ if (Array.isArray(input.rowHeights)) {
1864
+ for (const entry of input.rowHeights) {
1865
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
1866
+ continue;
1867
+ const rec = entry;
1868
+ const rowNumber = typeof rec.rowNumber === 'number' ? Math.trunc(rec.rowNumber) : NaN;
1869
+ if (!Number.isFinite(rowNumber) || rowNumber < 1 || rowNumber > MAX_SHEET_ROW_COUNT) {
1870
+ return this.errorResult(`Invalid rowNumber '${String(rec.rowNumber ?? '')}' in rowHeights.`);
1871
+ }
1872
+ while (sheet.Rows.length < rowNumber) {
1873
+ sheet.Rows.push({
1874
+ RowID: `${sheet.SheetID}-row-${randomUUID().slice(0, 8)}`,
1875
+ Index: sheet.Rows.length + 1,
1876
+ Height: 24,
1877
+ Hidden: false
1878
+ });
1879
+ }
1880
+ const targetRow = sheet.Rows[rowNumber - 1];
1881
+ if (typeof rec.height === 'number' && Number.isFinite(rec.height) && rec.height >= 0) {
1882
+ targetRow.Height = Math.round(rec.height);
1883
+ }
1884
+ if (typeof rec.hidden === 'boolean') {
1885
+ targetRow.Hidden = rec.hidden;
1886
+ }
1887
+ }
1888
+ }
1889
+ if (Array.isArray(input.columnWidths)) {
1890
+ for (const entry of input.columnWidths) {
1891
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
1892
+ continue;
1893
+ const rec = entry;
1894
+ const colNum = resolveColumnNumber(rec.column);
1895
+ if (!colNum) {
1896
+ return this.errorResult(`Invalid column '${String(rec.column ?? '')}' in columnWidths.`);
1897
+ }
1898
+ while (sheet.Columns.length < colNum) {
1899
+ const nextIdx = sheet.Columns.length + 1;
1900
+ sheet.Columns.push({
1901
+ ColumnID: `${sheet.SheetID}-col-${randomUUID().slice(0, 8)}`,
1902
+ Index: nextIdx,
1903
+ Letter: ColumnIndexToLetter(nextIdx),
1904
+ Width: 110,
1905
+ Hidden: false
1906
+ });
1907
+ }
1908
+ const targetCol = sheet.Columns[colNum - 1];
1909
+ if (typeof rec.width === 'number' && Number.isFinite(rec.width) && rec.width >= 0) {
1910
+ targetCol.Width = Math.round(rec.width);
1911
+ }
1912
+ if (typeof rec.hidden === 'boolean') {
1913
+ targetCol.Hidden = rec.hidden;
1914
+ }
1915
+ }
1916
+ }
1917
+ return this.buildMutationSuccess(workbook, {
1918
+ sheetId: sheet.SheetID,
1919
+ frozenRows: sheet.FrozenRows,
1920
+ frozenColumns: sheet.FrozenColumns,
1921
+ rowCount: sheet.Rows.length,
1922
+ columnCount: sheet.Columns.length
1923
+ });
1924
+ }
1925
+ async handleUpsertLiveTable(workbook, input, context) {
1926
+ const sheet = this.resolveSheet(workbook, input.sheet);
1927
+ if (!sheet) {
1928
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
1929
+ }
1930
+ const rawSourceType = typeof input.sourceType === 'string' ? input.sourceType.trim().toLowerCase() : '';
1931
+ const sourceType = rawSourceType === 'savedquery' || rawSourceType === 'query'
1932
+ ? 'SavedQuery'
1933
+ : 'EntityView';
1934
+ const tableId = typeof input.tableId === 'string' && input.tableId.trim()
1935
+ ? input.tableId.trim()
1936
+ : `tbl-${Date.now().toString(36)}`;
1937
+ const rawCalcCols = Array.isArray(input.calculatedColumns) ? input.calculatedColumns : [];
1938
+ const calcCols = rawCalcCols
1939
+ .filter((c) => Boolean(c && typeof c === 'object' && !Array.isArray(c)))
1940
+ .map((c) => ({
1941
+ Header: String(c.header ?? c.Header ?? 'Calculated'),
1942
+ FormulaTemplate: String(c.formulaTemplate ?? c.FormulaTemplate ?? '=0'),
1943
+ FormatType: typeof c.formatType === 'string'
1944
+ ? c.formatType
1945
+ : undefined
1946
+ }));
1947
+ const rawParamsObj = input.parameters && typeof input.parameters === 'object' && !Array.isArray(input.parameters)
1948
+ ? input.parameters
1949
+ : input.queryParameters && typeof input.queryParameters === 'object' && !Array.isArray(input.queryParameters)
1950
+ ? input.queryParameters
1951
+ : undefined;
1952
+ let queryParameters;
1953
+ if (rawParamsObj) {
1954
+ queryParameters = {};
1955
+ for (const [k, v] of Object.entries(rawParamsObj)) {
1956
+ if (v === null) {
1957
+ queryParameters[k] = null;
1958
+ }
1959
+ else if (typeof v === 'string') {
1960
+ queryParameters[k] = v;
1961
+ }
1962
+ else if (typeof v === 'number') {
1963
+ queryParameters[k] = v;
1964
+ }
1965
+ else if (typeof v === 'boolean') {
1966
+ queryParameters[k] = v;
1967
+ }
1968
+ else if (v !== undefined) {
1969
+ queryParameters[k] = JSON.stringify(v);
1970
+ }
1971
+ }
1972
+ }
1973
+ const anchorCell = typeof input.anchorCell === 'string' && input.anchorCell.trim() ? input.anchorCell.trim().toUpperCase() : 'A1';
1974
+ const anchorPos = ParseCellAddress(anchorCell);
1975
+ if (!anchorPos || anchorPos.row > MAX_SHEET_ROW_COUNT || anchorPos.col > MAX_SHEET_COLUMN_COUNT) {
1976
+ return this.errorResult(`Invalid anchorCell '${anchorCell}'.`);
1977
+ }
1978
+ const spec = {
1979
+ TableID: tableId,
1980
+ Title: String(input.title ?? input.entityName ?? input.queryName ?? 'Live Data Table'),
1981
+ SourceType: sourceType,
1982
+ EntityName: typeof input.entityName === 'string' ? input.entityName : undefined,
1983
+ ViewID: typeof input.viewId === 'string' ? input.viewId : undefined,
1984
+ ViewName: typeof input.viewName === 'string' ? input.viewName : undefined,
1985
+ ExtraFilter: typeof input.extraFilter === 'string' ? input.extraFilter : undefined,
1986
+ Fields: Array.isArray(input.fields) ? input.fields.map(String) : undefined,
1987
+ QueryID: typeof input.queryId === 'string' ? input.queryId : undefined,
1988
+ QueryName: typeof input.queryName === 'string' ? input.queryName : undefined,
1989
+ QueryParameters: queryParameters,
1990
+ MaxRows: typeof input.maxRows === 'number' && input.maxRows > 0 ? Math.trunc(input.maxRows) : undefined,
1991
+ AnchorCell: anchorCell,
1992
+ IncludeHeaders: true,
1993
+ Mode: 'Live',
1994
+ CalculatedColumns: calcCols
1995
+ };
1996
+ const editCtx = this.extractCellEditContext(context);
1997
+ const existingBounds = this.getLiveTableCellBounds(sheet, tableId);
1998
+ if (existingBounds) {
1999
+ const existingProtErr = checkBoundsProtection(sheet, existingBounds, editCtx, `update live table '${tableId}'`);
2000
+ if (existingProtErr) {
2001
+ return this.errorResult(existingProtErr);
2002
+ }
2003
+ }
2004
+ const anchorBounds = this.computeLiveTableResultBounds(spec);
2005
+ if (anchorBounds) {
2006
+ const anchorProtErr = checkBoundsProtection(sheet, anchorBounds, editCtx, `upsert live table '${tableId}' at '${spec.AnchorCell}'`);
2007
+ if (anchorProtErr) {
2008
+ return this.errorResult(anchorProtErr);
2009
+ }
2010
+ }
2011
+ const prevLiveTables = [...sheet.LiveTables];
2012
+ const prevCells = { ...sheet.Cells };
2013
+ const prevRows = [...sheet.Rows];
2014
+ const prevColumns = [...sheet.Columns];
2015
+ const existingIdx = sheet.LiveTables.findIndex((t) => t.TableID === tableId);
2016
+ if (existingIdx >= 0) {
2017
+ sheet.LiveTables[existingIdx] = spec;
2018
+ }
2019
+ else {
2020
+ sheet.LiveTables.push(spec);
2021
+ }
2022
+ let materializedSummary = this.buildUnmaterializedTableSummary(sheet, spec);
2023
+ if (context?.contextUser && context?.provider) {
2024
+ const engine = SpreadsheetEngine.Instance;
2025
+ const refreshResults = await engine.RefreshLiveTables(workbook, context.contextUser, context.provider, {
2026
+ TableID: spec.TableID
2027
+ });
2028
+ const tblRes = refreshResults[spec.TableID];
2029
+ if (tblRes && (tblRes.AccessDenied || !tblRes.Success)) {
2030
+ sheet.LiveTables = prevLiveTables;
2031
+ sheet.Cells = prevCells;
2032
+ sheet.Rows = prevRows;
2033
+ sheet.Columns = prevColumns;
2034
+ return this.errorResult(tblRes.ErrorMessage || `Access denied or failed to materialize live table '${spec.TableID}'.`);
2035
+ }
2036
+ const materializedBounds = this.getLiveTableCellBounds(sheet, spec.TableID) ??
2037
+ this.computeLiveTableResultBounds(spec, tblRes);
2038
+ if (materializedBounds) {
2039
+ const matProtErr = checkBoundsProtection(sheet, materializedBounds, editCtx, `materialize live table '${tableId}'`);
2040
+ if (matProtErr) {
2041
+ sheet.LiveTables = prevLiveTables;
2042
+ sheet.Cells = prevCells;
2043
+ sheet.Rows = prevRows;
2044
+ sheet.Columns = prevColumns;
2045
+ return this.errorResult(matProtErr);
2046
+ }
2047
+ }
2048
+ await engine.EvaluateMjCustomFunctions(workbook, context.contextUser, context.provider, {
2049
+ HostArtifactID: context.artifactId,
2050
+ BypassCache: true
2051
+ });
2052
+ await engine.EvaluateWorkbookIsolated(workbook);
2053
+ const refreshedSheet = engine.GetWorksheet(workbook, sheet.SheetID) ?? sheet;
2054
+ materializedSummary = this.summarizeMaterializedLiveTable(refreshedSheet, spec, refreshResults[spec.TableID]);
2055
+ }
2056
+ return this.buildMutationSuccess(workbook, {
2057
+ sheetId: sheet.SheetID,
2058
+ sheetName: sheet.Name,
2059
+ tableId: spec.TableID,
2060
+ anchorCell: spec.AnchorCell,
2061
+ liveTable: spec,
2062
+ ...materializedSummary
2063
+ });
2064
+ }
2065
+ async handleRefreshLiveTables(workbook, input, context) {
2066
+ if (!context?.contextUser || !context?.provider) {
2067
+ return this.errorResult('refresh_live_tables requires an authenticated user and metadata provider context.');
2068
+ }
2069
+ const engine = SpreadsheetEngine.Instance;
2070
+ const targetTableId = typeof input.tableId === 'string' && input.tableId.trim() ? input.tableId.trim() : undefined;
2071
+ const editCtx = this.extractCellEditContext(context);
2072
+ for (const ws of workbook.Worksheets) {
2073
+ for (const tbl of ws.LiveTables) {
2074
+ if (targetTableId && tbl.TableID !== targetTableId)
2075
+ continue;
2076
+ const existingBounds = this.getLiveTableCellBounds(ws, tbl.TableID);
2077
+ if (existingBounds) {
2078
+ const protErr = checkBoundsProtection(ws, existingBounds, editCtx, `refresh live table '${tbl.TableID}'`);
2079
+ if (protErr) {
2080
+ return this.errorResult(protErr);
2081
+ }
2082
+ }
2083
+ const anchorBounds = this.computeLiveTableResultBounds(tbl);
2084
+ if (anchorBounds) {
2085
+ const anchorErr = checkBoundsProtection(ws, anchorBounds, editCtx, `refresh live table '${tbl.TableID}'`);
2086
+ if (anchorErr) {
2087
+ return this.errorResult(anchorErr);
2088
+ }
2089
+ }
2090
+ }
2091
+ }
2092
+ const sheetSnapshots = workbook.Worksheets.map((ws) => ({
2093
+ ws,
2094
+ cells: { ...ws.Cells },
2095
+ rows: [...ws.Rows],
2096
+ columns: [...ws.Columns],
2097
+ liveTables: ws.LiveTables.map((t) => ({ ...t }))
2098
+ }));
2099
+ const refreshResults = await engine.RefreshLiveTables(workbook, context.contextUser, context.provider, {
2100
+ TableID: targetTableId
2101
+ });
2102
+ for (const ws of workbook.Worksheets) {
2103
+ for (const tbl of ws.LiveTables) {
2104
+ if (targetTableId && tbl.TableID !== targetTableId)
2105
+ continue;
2106
+ const tblRes = refreshResults[tbl.TableID];
2107
+ if (tblRes && (tblRes.AccessDenied || !tblRes.Success)) {
2108
+ for (const snap of sheetSnapshots) {
2109
+ snap.ws.Cells = snap.cells;
2110
+ snap.ws.Rows = snap.rows;
2111
+ snap.ws.Columns = snap.columns;
2112
+ snap.ws.LiveTables = snap.liveTables;
2113
+ }
2114
+ return this.errorResult(tblRes.ErrorMessage || `Access denied or failed to refresh live table '${tbl.TableID}'.`);
2115
+ }
2116
+ const cellBounds = this.getLiveTableCellBounds(ws, tbl.TableID);
2117
+ const resultBounds = this.computeLiveTableResultBounds(tbl, refreshResults[tbl.TableID]);
2118
+ const boundsToCheck = cellBounds ?? resultBounds;
2119
+ if (boundsToCheck) {
2120
+ const matProtErr = checkBoundsProtection(ws, boundsToCheck, editCtx, `refresh live table '${tbl.TableID}'`);
2121
+ if (matProtErr) {
2122
+ for (const snap of sheetSnapshots) {
2123
+ snap.ws.Cells = snap.cells;
2124
+ snap.ws.Rows = snap.rows;
2125
+ snap.ws.Columns = snap.columns;
2126
+ snap.ws.LiveTables = snap.liveTables;
2127
+ }
2128
+ return this.errorResult(matProtErr);
2129
+ }
2130
+ }
2131
+ }
2132
+ }
2133
+ await engine.EvaluateMjCustomFunctions(workbook, context.contextUser, context.provider, {
2134
+ HostArtifactID: context.artifactId,
2135
+ BypassCache: true
2136
+ });
2137
+ await engine.EvaluateWorkbookIsolated(workbook);
2138
+ const tables = [];
2139
+ for (const ws of workbook.Worksheets) {
2140
+ for (const tbl of ws.LiveTables) {
2141
+ if (targetTableId && tbl.TableID !== targetTableId)
2142
+ continue;
2143
+ tables.push({
2144
+ tableId: tbl.TableID,
2145
+ sheetId: ws.SheetID,
2146
+ sheetName: ws.Name,
2147
+ anchorCell: tbl.AnchorCell,
2148
+ ...this.summarizeMaterializedLiveTable(ws, tbl, refreshResults[tbl.TableID])
2149
+ });
2150
+ }
2151
+ }
2152
+ return this.buildMutationSuccess(workbook, {
2153
+ refreshedCount: tables.length,
2154
+ tables
2155
+ }, { skipEvaluate: true });
2156
+ }
2157
+ async handleDeleteLiveTable(workbook, input, context) {
2158
+ const sheet = this.resolveSheet(workbook, input.sheet);
2159
+ if (!sheet) {
2160
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
2161
+ }
2162
+ const tableId = typeof input.tableId === 'string' ? input.tableId.trim() : '';
2163
+ if (!tableId) {
2164
+ return this.errorResult('Parameter "tableId" is required.');
2165
+ }
2166
+ const idx = sheet.LiveTables.findIndex((t) => t.TableID === tableId);
2167
+ if (idx < 0) {
2168
+ return this.errorResult(`LiveTable '${tableId}' was not found on worksheet '${sheet.Name}'.`);
2169
+ }
2170
+ if (input.clearCells === true) {
2171
+ const editCtx = this.extractCellEditContext(context);
2172
+ const tableCells = Object.values(sheet.Cells).filter((c) => c.LiveTableID === tableId);
2173
+ for (const cell of tableCells) {
2174
+ const perm = SpreadsheetEngine.Instance.CheckCellWritePermission(sheet, cell.Address, editCtx);
2175
+ if (!perm.Allowed) {
2176
+ return this.errorResult(perm.Reason || `Cell '${cell.Address}' is inside a protected range.`);
2177
+ }
2178
+ }
2179
+ for (const cell of tableCells) {
2180
+ SpreadsheetEngine.Instance.ClearRange(workbook, sheet.SheetID, cell.Address, false, editCtx);
2181
+ }
2182
+ }
2183
+ sheet.LiveTables.splice(idx, 1);
2184
+ return this.buildMutationSuccess(workbook, {
2185
+ sheetId: sheet.SheetID,
2186
+ deletedTableId: tableId,
2187
+ remainingLiveTables: sheet.LiveTables
2188
+ });
2189
+ }
2190
+ buildUnmaterializedTableSummary(sheet, spec) {
2191
+ return {
2192
+ materialized: false,
2193
+ headers: [],
2194
+ rowCount: 0,
2195
+ boundingRange: spec.AnchorCell || 'A1',
2196
+ dataRange: null,
2197
+ sampleRows: [],
2198
+ };
2199
+ }
2200
+ summarizeMaterializedLiveTable(sheet, spec, execRes) {
2201
+ if (!execRes || !execRes.Success || execRes.AccessDenied) {
2202
+ return {
2203
+ materialized: false,
2204
+ headers: [],
2205
+ rowCount: 0,
2206
+ boundingRange: spec.AnchorCell || 'A1',
2207
+ dataRange: null,
2208
+ sampleRows: [],
2209
+ refreshError: execRes?.ErrorMessage || spec.LastError || 'Failed to materialize live table.'
2210
+ };
2211
+ }
2212
+ const anchor = ParseCellAddress(spec.AnchorCell || 'A1') ?? { row: 1, col: 1 };
2213
+ const baseColumns = execRes.Columns && execRes.Columns.length > 0
2214
+ ? execRes.Columns.map((c) => c.DisplayName || c.Name)
2215
+ : execRes.Rows[0]
2216
+ ? Object.keys(execRes.Rows[0])
2217
+ : [];
2218
+ const calcHeaders = (spec.CalculatedColumns ?? []).map((cc) => cc.Header);
2219
+ const headers = [...baseColumns, ...calcHeaders];
2220
+ const totalCols = Math.max(1, headers.length);
2221
+ const rowCount = execRes.Rows.length;
2222
+ const headerOffset = spec.IncludeHeaders !== false ? 1 : 0;
2223
+ const startAddr = FormatCellAddress(anchor.row, anchor.col);
2224
+ const lastRow = anchor.row + headerOffset + Math.max(0, rowCount - (headerOffset === 0 ? 1 : 0)) - (rowCount === 0 && headerOffset > 0 ? 0 : 0);
2225
+ const boundedLastRow = Math.max(anchor.row, anchor.row + headerOffset + rowCount - 1);
2226
+ const endColAddr = FormatCellAddress(boundedLastRow, anchor.col + totalCols - 1);
2227
+ const boundingRange = startAddr === endColAddr ? startAddr : `${startAddr}:${endColAddr}`;
2228
+ let dataRange = null;
2229
+ if (rowCount > 0) {
2230
+ const firstDataRow = anchor.row + headerOffset;
2231
+ const lastDataRow = firstDataRow + rowCount - 1;
2232
+ dataRange = `${FormatCellAddress(firstDataRow, anchor.col)}:${FormatCellAddress(lastDataRow, anchor.col + totalCols - 1)}`;
2233
+ }
2234
+ const sampleRows = execRes.Rows.slice(0, 5).map((row) => {
2235
+ const out = {};
2236
+ for (const [k, v] of Object.entries(row)) {
2237
+ if (v === null || v === undefined) {
2238
+ out[k] = null;
2239
+ }
2240
+ else if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
2241
+ out[k] = v;
2242
+ }
2243
+ else {
2244
+ out[k] = String(v);
2245
+ }
2246
+ }
2247
+ return out;
2248
+ });
2249
+ // Reconcile unused-param lint while keeping helper cohesive with future sheet-cell checks
2250
+ void lastRow;
2251
+ void sheet;
2252
+ return {
2253
+ materialized: true,
2254
+ headers,
2255
+ rowCount,
2256
+ boundingRange,
2257
+ dataRange,
2258
+ sampleRows
2259
+ };
2260
+ }
2261
+ summarizeSpilledFormulaFootprint(sheet, formulaCell) {
2262
+ const origin = ParseCellAddress(formulaCell);
2263
+ if (!origin)
2264
+ return null;
2265
+ let maxRow = origin.row;
2266
+ let maxCol = origin.col;
2267
+ for (const cell of Object.values(sheet.Cells)) {
2268
+ if (cell.Address === formulaCell || cell.SpilledFrom === formulaCell) {
2269
+ const pos = ParseCellAddress(cell.Address);
2270
+ if (pos) {
2271
+ if (pos.row > maxRow)
2272
+ maxRow = pos.row;
2273
+ if (pos.col > maxCol)
2274
+ maxCol = pos.col;
2275
+ }
2276
+ }
2277
+ }
2278
+ const headers = [];
2279
+ for (let c = origin.col; c <= maxCol; c++) {
2280
+ const hdrCell = sheet.Cells[FormatCellAddress(origin.row, c)];
2281
+ if (hdrCell) {
2282
+ headers.push(hdrCell.DisplayValue || String(hdrCell.ComputedValue ?? hdrCell.RawValue ?? ''));
2283
+ }
2284
+ }
2285
+ const startAddr = FormatCellAddress(origin.row, origin.col);
2286
+ const endAddr = FormatCellAddress(maxRow, maxCol);
2287
+ return {
2288
+ formulaCell,
2289
+ boundingRange: startAddr === endAddr ? startAddr : `${startAddr}:${endAddr}`,
2290
+ headers,
2291
+ rowCount: Math.max(0, maxRow - origin.row)
2292
+ };
2293
+ }
2294
+ async handleUpsertChart(workbook, input) {
2295
+ const sheet = this.resolveSheet(workbook, input.sheet);
2296
+ if (!sheet) {
2297
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
2298
+ }
2299
+ const rawSourceRange = input.sourceRange ?? input.dataRange ?? input.range;
2300
+ const sourceRange = typeof rawSourceRange === 'string' ? rawSourceRange.trim() : '';
2301
+ if (!sourceRange) {
2302
+ return this.errorResult('Parameter "sourceRange" is required.');
2303
+ }
2304
+ const chartId = typeof input.chartId === 'string' && input.chartId.trim()
2305
+ ? input.chartId.trim()
2306
+ : `chart-${sheet.Charts.length + 1}`;
2307
+ const existingIdx = sheet.Charts.findIndex((c) => c.ChartID === chartId);
2308
+ const existing = existingIdx >= 0 ? sheet.Charts[existingIdx] : undefined;
2309
+ const chartTypeRaw = typeof input.chartType === 'string' ? input.chartType.toLowerCase() : existing?.ChartType ?? 'bar';
2310
+ const chartType = chartTypeRaw === 'line' || chartTypeRaw === 'pie' || chartTypeRaw === 'area'
2311
+ ? chartTypeRaw
2312
+ : 'bar';
2313
+ const placement = input.placement === 'sheet' || input.placement === 'dock' ? input.placement : existing?.Placement;
2314
+ const hasHeaderRow = input.hasHeaderRow === true || input.hasHeaderRow === false || input.hasHeaderRow === 'auto'
2315
+ ? input.hasHeaderRow
2316
+ : existing?.HasHeaderRow;
2317
+ const seriesOrientation = input.seriesOrientation === 'rows' || input.seriesOrientation === 'columns'
2318
+ ? input.seriesOrientation
2319
+ : existing?.SeriesOrientation;
2320
+ const categoryColumnIndex = typeof input.categoryColumnIndex === 'number' && Number.isInteger(input.categoryColumnIndex) && input.categoryColumnIndex >= 0
2321
+ ? input.categoryColumnIndex
2322
+ : existing?.CategoryColumnIndex;
2323
+ const includedSeriesIndices = Array.isArray(input.includedSeriesIndices)
2324
+ ? input.includedSeriesIndices.filter((n) => typeof n === 'number' && Number.isInteger(n) && n >= 0)
2325
+ : existing?.IncludedSeriesIndices;
2326
+ const chartSpec = {
2327
+ ...(existing ?? {}),
2328
+ ChartID: chartId,
2329
+ Title: typeof input.title === 'string' ? input.title : existing?.Title ?? `Chart (${sourceRange})`,
2330
+ ChartType: chartType,
2331
+ SheetID: sheet.SheetID,
2332
+ SourceRange: sourceRange,
2333
+ PositionCell: typeof input.positionCell === 'string' ? input.positionCell : existing?.PositionCell ?? 'E2',
2334
+ Placement: placement,
2335
+ OffsetX: typeof input.offsetX === 'number' && Number.isFinite(input.offsetX) ? Math.round(input.offsetX) : existing?.OffsetX,
2336
+ OffsetY: typeof input.offsetY === 'number' && Number.isFinite(input.offsetY) ? Math.round(input.offsetY) : existing?.OffsetY,
2337
+ WidthPx: typeof input.widthPx === 'number' && Number.isFinite(input.widthPx) ? Math.round(input.widthPx) : existing?.WidthPx,
2338
+ HeightPx: typeof input.heightPx === 'number' && Number.isFinite(input.heightPx) ? Math.round(input.heightPx) : existing?.HeightPx,
2339
+ ShowLegend: typeof input.showLegend === 'boolean' ? input.showLegend : existing?.ShowLegend ?? true,
2340
+ HasHeaderRow: hasHeaderRow,
2341
+ SeriesOrientation: seriesOrientation,
2342
+ CategoryColumnIndex: categoryColumnIndex,
2343
+ IncludedSeriesIndices: includedSeriesIndices,
2344
+ ShowDataLabels: typeof input.showDataLabels === 'boolean' ? input.showDataLabels : existing?.ShowDataLabels
2345
+ };
2346
+ if (existingIdx >= 0) {
2347
+ sheet.Charts[existingIdx] = chartSpec;
2348
+ }
2349
+ else {
2350
+ sheet.Charts.push(chartSpec);
2351
+ }
2352
+ await SpreadsheetEngine.Instance.EvaluateWorkbookIsolated(workbook);
2353
+ const dataset = SpreadsheetEngine.Instance.ExtractChartDataset(workbook, sheet.SheetID, chartId, undefined, { SkipEvaluate: true });
2354
+ return this.buildMutationSuccess(workbook, {
2355
+ sheetId: sheet.SheetID,
2356
+ chart: chartSpec,
2357
+ dataset
2358
+ }, { skipEvaluate: true });
2359
+ }
2360
+ async handleDeleteChart(workbook, input) {
2361
+ const sheet = this.resolveSheet(workbook, input.sheet);
2362
+ if (!sheet) {
2363
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
2364
+ }
2365
+ const chartId = typeof input.chartId === 'string' ? input.chartId.trim() : '';
2366
+ if (!chartId) {
2367
+ return this.errorResult('Parameter "chartId" is required.');
2368
+ }
2369
+ const idx = sheet.Charts.findIndex((c) => c.ChartID === chartId);
2370
+ if (idx < 0) {
2371
+ return this.errorResult(`Chart '${chartId}' was not found on worksheet '${sheet.Name}'.`);
2372
+ }
2373
+ sheet.Charts.splice(idx, 1);
2374
+ return this.buildMutationSuccess(workbook, {
2375
+ sheetId: sheet.SheetID,
2376
+ deletedChartId: chartId,
2377
+ remainingCharts: sheet.Charts
2378
+ });
2379
+ }
2380
+ async handleEmbedArtifact(workbook, input, context) {
2381
+ const sheet = this.resolveSheet(workbook, input.sheet);
2382
+ if (!sheet) {
2383
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
2384
+ }
2385
+ const rawArtifactId = typeof input.artifactId === 'string' ? input.artifactId.trim() : '';
2386
+ if (!rawArtifactId) {
2387
+ return this.errorResult('Parameter "artifactId" is required.');
2388
+ }
2389
+ const resolved = ResolveEmbeddedArtifactId(rawArtifactId, context);
2390
+ if (!resolved.ok) {
2391
+ return this.errorResult(resolved.errorMessage);
2392
+ }
2393
+ const artifactId = resolved.artifactId;
2394
+ let resolvedVersionId;
2395
+ if (typeof input.versionId === 'string' && input.versionId.trim()) {
2396
+ const verResult = ResolveEmbeddedVersionId(input.versionId, context);
2397
+ if (!verResult.ok) {
2398
+ return this.errorResult(verResult.errorMessage);
2399
+ }
2400
+ resolvedVersionId = verResult.versionId;
2401
+ }
2402
+ else if (input.versionId === null) {
2403
+ resolvedVersionId = null;
2404
+ }
2405
+ const access = await ValidateEmbeddedArtifactAccess({
2406
+ targetArtifactId: artifactId,
2407
+ targetVersionId: resolvedVersionId,
2408
+ context
2409
+ });
2410
+ if (!access.Ok) {
2411
+ return this.errorResult(access.ErrorMessage || `Cannot embed artifact '${artifactId}'.`);
2412
+ }
2413
+ const embedId = typeof input.embedId === 'string' && input.embedId.trim()
2414
+ ? input.embedId.trim()
2415
+ : `embed-${sheet.EmbeddedArtifacts.length + 1}`;
2416
+ const existing = sheet.EmbeddedArtifacts.find((e) => e.EmbedID === embedId);
2417
+ const typeName = typeof input.artifactTypeName === 'string'
2418
+ ? input.artifactTypeName
2419
+ : existing?.ArtifactTypeName ?? access.ArtifactTypeName ?? 'Whiteboard';
2420
+ const spec = {
2421
+ EmbedID: embedId,
2422
+ Title: typeof input.title === 'string' ? input.title : existing?.Title ?? `${typeName} Canvas`,
2423
+ ArtifactID: artifactId,
2424
+ ArtifactVersionID: resolvedVersionId !== undefined
2425
+ ? resolvedVersionId
2426
+ : existing?.ArtifactVersionID ?? null,
2427
+ ArtifactTypeName: typeName,
2428
+ DriverClass: access.DriverClass ??
2429
+ (typeName === 'Whiteboard' ? 'WhiteboardArtifactViewerPlugin' : existing?.DriverClass),
2430
+ AnchorCell: typeof input.anchorCell === 'string' ? input.anchorCell : existing?.AnchorCell ?? 'F2',
2431
+ WidthPx: typeof input.widthPx === 'number' && Number.isFinite(input.widthPx) && input.widthPx > 0
2432
+ ? Math.round(input.widthPx)
2433
+ : existing?.WidthPx ?? 520,
2434
+ HeightPx: typeof input.heightPx === 'number' && Number.isFinite(input.heightPx) && input.heightPx > 0
2435
+ ? Math.round(input.heightPx)
2436
+ : existing?.HeightPx ?? 320,
2437
+ AllowInlineEdit: typeof input.allowInlineEdit === 'boolean'
2438
+ ? input.allowInlineEdit
2439
+ : existing?.AllowInlineEdit ?? true
2440
+ };
2441
+ const idx = sheet.EmbeddedArtifacts.findIndex((e) => e.EmbedID === embedId);
2442
+ if (idx >= 0) {
2443
+ sheet.EmbeddedArtifacts[idx] = spec;
2444
+ }
2445
+ else {
2446
+ sheet.EmbeddedArtifacts.push(spec);
2447
+ }
2448
+ return this.buildMutationSuccess(workbook, {
2449
+ sheetId: sheet.SheetID,
2450
+ embeddedArtifact: spec
2451
+ });
2452
+ }
2453
+ async handleDeleteEmbeddedArtifact(workbook, input) {
2454
+ const sheet = this.resolveSheet(workbook, input.sheet);
2455
+ if (!sheet) {
2456
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
2457
+ }
2458
+ const embedId = typeof input.embedId === 'string' ? input.embedId.trim() : '';
2459
+ if (!embedId) {
2460
+ return this.errorResult('Parameter "embedId" is required.');
2461
+ }
2462
+ const idx = sheet.EmbeddedArtifacts.findIndex((e) => e.EmbedID === embedId);
2463
+ if (idx < 0) {
2464
+ return this.errorResult(`Embedded artifact '${embedId}' was not found on worksheet '${sheet.Name}'.`);
2465
+ }
2466
+ sheet.EmbeddedArtifacts.splice(idx, 1);
2467
+ return this.buildMutationSuccess(workbook, {
2468
+ sheetId: sheet.SheetID,
2469
+ deletedEmbedId: embedId,
2470
+ remainingEmbeddedArtifacts: sheet.EmbeddedArtifacts
2471
+ });
2472
+ }
2473
+ getLiveTableCellBounds(sheet, tableId) {
2474
+ let minRow = Infinity;
2475
+ let maxRow = 0;
2476
+ let minCol = Infinity;
2477
+ let maxCol = 0;
2478
+ for (const cell of Object.values(sheet.Cells)) {
2479
+ if (cell?.LiveTableID !== tableId)
2480
+ continue;
2481
+ const pos = ParseCellAddress(cell.Address);
2482
+ if (!pos)
2483
+ continue;
2484
+ if (pos.row < minRow)
2485
+ minRow = pos.row;
2486
+ if (pos.row > maxRow)
2487
+ maxRow = pos.row;
2488
+ if (pos.col < minCol)
2489
+ minCol = pos.col;
2490
+ if (pos.col > maxCol)
2491
+ maxCol = pos.col;
2492
+ }
2493
+ if (maxRow === 0 || maxCol === 0) {
2494
+ return null;
2495
+ }
2496
+ return { startRow: minRow, endRow: maxRow, startCol: minCol, endCol: maxCol };
2497
+ }
2498
+ computeLiveTableResultBounds(table, result) {
2499
+ const anchor = ParseCellAddress(table.AnchorCell || 'A1');
2500
+ if (!anchor) {
2501
+ return null;
2502
+ }
2503
+ const dataCols = result
2504
+ ? result.Columns && result.Columns.length > 0
2505
+ ? result.Columns.length
2506
+ : result.Rows[0]
2507
+ ? Object.keys(result.Rows[0]).length
2508
+ : 0
2509
+ : (table.Fields?.length ?? 0);
2510
+ const totalCols = Math.max(1, dataCols + (table.CalculatedColumns?.length ?? 0));
2511
+ const headerRows = table.IncludeHeaders !== false ? 1 : 0;
2512
+ const dataRows = result ? result.Rows.length : 0;
2513
+ const totalRows = Math.max(1, headerRows + dataRows);
2514
+ return {
2515
+ startRow: anchor.row,
2516
+ endRow: Math.min(MAX_SHEET_ROW_COUNT, anchor.row + totalRows - 1),
2517
+ startCol: anchor.col,
2518
+ endCol: Math.min(MAX_SHEET_COLUMN_COUNT, anchor.col + totalCols - 1)
2519
+ };
2520
+ }
2521
+ async handleSortAndFilter(workbook, input, context) {
2522
+ const engine = SpreadsheetEngine.Instance;
2523
+ const sheet = this.resolveSheet(workbook, input.sheet);
2524
+ if (!sheet) {
2525
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
2526
+ }
2527
+ const hasSort = typeof input.sortColumn === 'string' && input.sortColumn.trim().length > 0;
2528
+ const hasFilters = Array.isArray(input.filters);
2529
+ if (hasSort || hasFilters) {
2530
+ const editCtx = this.extractCellEditContext(context);
2531
+ const populated = this.getPopulatedBounds(sheet);
2532
+ const startRow = 2; // HeaderRows: 1 keeps row 1 fixed
2533
+ const endRow = hasFilters
2534
+ ? Math.max(startRow, sheet.Rows.length, populated.maxRow)
2535
+ : Math.max(startRow, populated.maxRow);
2536
+ const protErr = checkBoundsProtection(sheet, { startRow, endRow, startCol: 1, endCol: MAX_SHEET_COLUMN_COUNT }, editCtx, hasSort && hasFilters ? 'sort and filter worksheet' : hasSort ? 'sort worksheet' : 'filter worksheet');
2537
+ if (protErr) {
2538
+ return this.errorResult(protErr);
2539
+ }
2540
+ }
2541
+ if (hasSort) {
2542
+ engine.SortWorksheet(workbook, sheet.SheetID, {
2543
+ ColumnLetter: String(input.sortColumn).trim().toUpperCase(),
2544
+ Direction: input.sortDirection === 'desc' ? 'desc' : 'asc',
2545
+ HeaderRows: 1
2546
+ }, undefined, false);
2547
+ }
2548
+ if (hasFilters) {
2549
+ sheet.FilterSpecs = input.filters
2550
+ .filter((f) => Boolean(f && typeof f === 'object' && !Array.isArray(f)))
2551
+ .map((f) => ({
2552
+ ColumnLetter: String(f.columnLetter ?? 'A').toUpperCase(),
2553
+ Operator: f.operator ?? 'contains',
2554
+ Value: String(f.value ?? '')
2555
+ }));
2556
+ engine.ApplyWorksheetFilters(workbook, sheet.SheetID);
2557
+ }
2558
+ return this.buildMutationSuccess(workbook, {
2559
+ sheetId: sheet.SheetID,
2560
+ sortSpec: sheet.SortSpec,
2561
+ filterSpecs: sheet.FilterSpecs,
2562
+ visibleRowCount: sheet.Rows.filter((r) => !r.Hidden).length
2563
+ });
2564
+ }
2565
+ // -----------------------------------------------------------------------
2566
+ // ExcelToolLibrary Parity Inspection Tools (E6)
2567
+ // -----------------------------------------------------------------------
2568
+ handleGetSheets(workbook) {
2569
+ const sheets = workbook.Worksheets.map((ws) => {
2570
+ const bounds = this.getPopulatedBounds(ws);
2571
+ return {
2572
+ sheetId: ws.SheetID,
2573
+ name: ws.Name,
2574
+ rowCount: bounds.maxRow > 0 ? bounds.maxRow : ws.Rows.length,
2575
+ columnCount: bounds.maxCol > 0 ? bounds.maxCol : ws.Columns.length
2576
+ };
2577
+ });
2578
+ return this.successResult({ sheets });
2579
+ }
2580
+ handleGetSheetData(workbook, input) {
2581
+ const sheetArg = input.sheet ?? input.sheetName;
2582
+ const ws = this.resolveSheet(workbook, sheetArg);
2583
+ if (!ws) {
2584
+ return this.errorResult(`Sheet "${String(sheetArg ?? '')}" not found.`);
2585
+ }
2586
+ const startRow = Math.max(1, Math.trunc(Number(input.startRow ?? 1) || 1));
2587
+ const requestedRowCount = Math.trunc(Number(input.rowCount ?? 50) || 50);
2588
+ if (requestedRowCount < 1) {
2589
+ return this.errorResult('Parameter "rowCount" must be >= 1.');
2590
+ }
2591
+ const rowCount = Math.min(MAX_SHEET_ROW_COUNT, requestedRowCount);
2592
+ const headerMap = this.buildWorksheetHeaderMap(ws);
2593
+ if (headerMap.size === 0) {
2594
+ return this.successResult({ rows: [] });
2595
+ }
2596
+ const bounds = this.getPopulatedBounds(ws);
2597
+ const firstDataRow = 1 + startRow;
2598
+ const lastDataRow = Math.min(1 + startRow + rowCount - 1, bounds.maxRow);
2599
+ const rows = [];
2600
+ for (let r = firstDataRow; r <= lastDataRow; r++) {
2601
+ let hasAnyCellInRow = false;
2602
+ const record = {};
2603
+ for (const [colIdx, colName] of headerMap.entries()) {
2604
+ const addr = FormatCellAddress(r, colIdx);
2605
+ const cell = ws.Cells[addr];
2606
+ const val = cell ? (cell.ComputedValue ?? cell.RawValue ?? null) : null;
2607
+ if (val !== null && val !== undefined && val !== '') {
2608
+ hasAnyCellInRow = true;
2609
+ }
2610
+ record[colName] = val;
2611
+ }
2612
+ if (hasAnyCellInRow) {
2613
+ rows.push(record);
2614
+ }
2615
+ }
2616
+ return this.successResult({ rows });
2617
+ }
2618
+ handleSearchCells(workbook, input) {
2619
+ EnsureNodeVmSafeRegexExecutorRegistered();
2620
+ const engine = SpreadsheetEngine.Instance;
2621
+ const query = typeof input.query === 'string' ? input.query : '';
2622
+ if (!query) {
2623
+ return this.errorResult('Parameter "query" is required.');
2624
+ }
2625
+ const explicitRegex = input.use_regex === true || input.useRegex === true;
2626
+ let regex = null;
2627
+ if (explicitRegex) {
2628
+ if (query.length > 256) {
2629
+ return this.errorResult('Unsafe or overly complex regular expression rejected');
2630
+ }
2631
+ try {
2632
+ new RegExp(query, 'i');
2633
+ }
2634
+ catch {
2635
+ return this.errorResult(`Invalid regex pattern: "${query}".`);
2636
+ }
2637
+ regex = CompileSafeUserRegex(query, 'i');
2638
+ if (!regex || !IsSafeUserRegex(query, 'i')) {
2639
+ return this.errorResult('Unsafe or overly complex regular expression rejected');
2640
+ }
2641
+ }
2642
+ const literalNeedle = regex ? '' : query.toLowerCase();
2643
+ const sheetScope = input.sheet ?? input.sheetName;
2644
+ let targetSheets;
2645
+ if (typeof sheetScope === 'string' && sheetScope.trim().length > 0) {
2646
+ const found = engine.GetWorksheet(workbook, sheetScope.trim());
2647
+ if (!found) {
2648
+ return this.errorResult(`Sheet "${sheetScope}" not found.`);
2649
+ }
2650
+ targetSheets = [found];
2651
+ }
2652
+ else {
2653
+ targetSheets = workbook.Worksheets;
2654
+ }
2655
+ const matches = [];
2656
+ const unsearchableCells = [];
2657
+ let tooLongCount = 0;
2658
+ let timeoutCount = 0;
2659
+ let budgetExpired = false;
2660
+ const regexDeadline = regex ? performance.now() + this.RegexBudgetMs : 0;
2661
+ const recordUnsearchableCell = (sheetName, cellAddr, reason) => {
2662
+ if (reason === 'exceeds_64kb_regex_limit') {
2663
+ tooLongCount++;
2664
+ }
2665
+ else {
2666
+ timeoutCount++;
2667
+ }
2668
+ if (unsearchableCells.length < MAX_REPORTED_UNSEARCHABLE_CELLS) {
2669
+ unsearchableCells.push({
2670
+ sheet: sheetName,
2671
+ cell: cellAddr,
2672
+ reason
2673
+ });
2674
+ }
2675
+ };
2676
+ let pendingBatch = [];
2677
+ let pendingTexts = [];
2678
+ let pendingChars = 0;
2679
+ const flushCellBatch = () => {
2680
+ if (pendingBatch.length === 0 || !regex)
2681
+ return;
2682
+ if (matches.length >= SEARCH_MATCH_LIMIT) {
2683
+ pendingBatch = [];
2684
+ pendingTexts = [];
2685
+ pendingChars = 0;
2686
+ return;
2687
+ }
2688
+ if (budgetExpired) {
2689
+ for (const item of pendingBatch) {
2690
+ recordUnsearchableCell(item.sheetName, item.cellAddr, 'regex_timeout');
2691
+ }
2692
+ pendingBatch = [];
2693
+ pendingTexts = [];
2694
+ pendingChars = 0;
2695
+ return;
2696
+ }
2697
+ const recRes = ExecuteSafeRegexBatchWithRecovery(regex, pendingTexts, regexDeadline, BATCH_REGEX_MAX_MS, MAX_REGEX_INPUT_BYTES);
2698
+ if (recRes.BudgetExpired) {
2699
+ budgetExpired = true;
2700
+ }
2701
+ for (let k = 0; k < pendingBatch.length; k++) {
2702
+ const item = pendingBatch[k];
2703
+ if (matches.length >= SEARCH_MATCH_LIMIT) {
2704
+ break;
2705
+ }
2706
+ if (recRes.Matches[k]) {
2707
+ matches.push({
2708
+ sheet: item.sheetName,
2709
+ cell: item.cellAddr,
2710
+ value: item.text
2711
+ });
2712
+ continue;
2713
+ }
2714
+ if (recRes.TimedOut[k] || recRes.BudgetSkipped[k]) {
2715
+ recordUnsearchableCell(item.sheetName, item.cellAddr, 'regex_timeout');
2716
+ continue;
2717
+ }
2718
+ if (recRes.InputTooLong[k]) {
2719
+ recordUnsearchableCell(item.sheetName, item.cellAddr, 'exceeds_64kb_regex_limit');
2720
+ continue;
2721
+ }
2722
+ if (item.altRawStr !== null) {
2723
+ if (budgetExpired) {
2724
+ recordUnsearchableCell(item.sheetName, item.cellAddr, 'regex_timeout');
2725
+ continue;
2726
+ }
2727
+ const remAlt = regexDeadline - performance.now();
2728
+ if (remAlt <= 0) {
2729
+ budgetExpired = true;
2730
+ recordUnsearchableCell(item.sheetName, item.cellAddr, 'regex_timeout');
2731
+ continue;
2732
+ }
2733
+ const altRes = SafeRegexSearchDetailed(regex, item.altRawStr, Math.min(BATCH_REGEX_MAX_MS, remAlt), MAX_REGEX_INPUT_BYTES);
2734
+ if (altRes.Matched) {
2735
+ matches.push({
2736
+ sheet: item.sheetName,
2737
+ cell: item.cellAddr,
2738
+ value: item.text
2739
+ });
2740
+ }
2741
+ else if (altRes.InputTooLong) {
2742
+ recordUnsearchableCell(item.sheetName, item.cellAddr, 'exceeds_64kb_regex_limit');
2743
+ }
2744
+ else if (altRes.TimedOut) {
2745
+ budgetExpired = true;
2746
+ recordUnsearchableCell(item.sheetName, item.cellAddr, 'regex_timeout');
2747
+ }
2748
+ }
2749
+ else if (item.altTooLong) {
2750
+ recordUnsearchableCell(item.sheetName, item.cellAddr, 'exceeds_64kb_regex_limit');
2751
+ }
2752
+ }
2753
+ pendingBatch = [];
2754
+ pendingTexts = [];
2755
+ pendingChars = 0;
2756
+ };
2757
+ for (const ws of targetSheets) {
2758
+ if (matches.length >= SEARCH_MATCH_LIMIT)
2759
+ break;
2760
+ const rawCellList = Object.values(ws.Cells);
2761
+ const keyedCells = new Array(rawCellList.length);
2762
+ for (let i = 0; i < rawCellList.length; i++) {
2763
+ const c = rawCellList[i];
2764
+ keyedCells[i] = { sortKey: computeFastCellSortKey(c.Address), cell: c };
2765
+ }
2766
+ keyedCells.sort((a, b) => a.sortKey - b.sortKey);
2767
+ for (let i = 0; i < keyedCells.length; i++) {
2768
+ if (matches.length >= SEARCH_MATCH_LIMIT)
2769
+ break;
2770
+ const cell = keyedCells[i].cell;
2771
+ const val = cell.ComputedValue ?? cell.RawValue;
2772
+ if (val === null || val === undefined || val === '')
2773
+ continue;
2774
+ const rawStr = String(val);
2775
+ const text = cell.DisplayValue || rawStr;
2776
+ if (!regex) {
2777
+ const matched = text.toLowerCase().includes(literalNeedle) ||
2778
+ (rawStr !== text && rawStr.toLowerCase().includes(literalNeedle));
2779
+ if (matched) {
2780
+ matches.push({
2781
+ sheet: ws.Name,
2782
+ cell: cell.Address,
2783
+ value: text
2784
+ });
2785
+ }
2786
+ continue;
2787
+ }
2788
+ if (exceedsSheetRegexInputBytes(text)) {
2789
+ flushCellBatch();
2790
+ recordUnsearchableCell(ws.Name, cell.Address, 'exceeds_64kb_regex_limit');
2791
+ continue;
2792
+ }
2793
+ if (budgetExpired) {
2794
+ recordUnsearchableCell(ws.Name, cell.Address, 'regex_timeout');
2795
+ continue;
2796
+ }
2797
+ const hasAlt = rawStr !== text;
2798
+ const altTooLong = hasAlt && exceedsSheetRegexInputBytes(rawStr);
2799
+ pendingBatch.push({
2800
+ sheetName: ws.Name,
2801
+ cellAddr: cell.Address,
2802
+ text,
2803
+ altRawStr: hasAlt && !altTooLong ? rawStr : null,
2804
+ altTooLong
2805
+ });
2806
+ pendingTexts.push(text);
2807
+ pendingChars += text.length;
2808
+ if (pendingBatch.length >= MAX_BATCH_ITEMS || pendingChars >= MAX_BATCH_CHARS) {
2809
+ flushCellBatch();
2810
+ }
2811
+ }
2812
+ flushCellBatch();
2813
+ }
2814
+ const unsearchableCount = tooLongCount + timeoutCount;
2815
+ const warnings = [];
2816
+ if (tooLongCount > 0) {
2817
+ warnings.push(`${tooLongCount} cell(s) exceeded the 64 KB regex limit and were not searched. Retry with use_regex: false for plain-text search across arbitrarily large cells.`);
2818
+ }
2819
+ if (timeoutCount > 0) {
2820
+ warnings.push(`${timeoutCount} cell(s) were skipped because regex evaluation reached the ${this.RegexBudgetMs}ms tool time budget. Simplify the pattern or retry with use_regex: false for plain-text search.`);
2821
+ }
2822
+ if (unsearchableCount > unsearchableCells.length) {
2823
+ warnings.push(`Showing first ${unsearchableCells.length} of ${unsearchableCount} unsearchable cell(s) in unsearchableCells.`);
2824
+ }
2825
+ return this.successResult({
2826
+ matches,
2827
+ partial: unsearchableCount > 0,
2828
+ timedOut: timeoutCount > 0,
2829
+ unsearchableCount,
2830
+ unsearchableCells,
2831
+ warnings
2832
+ });
2833
+ }
2834
+ handleAggregateColumn(workbook, input) {
2835
+ const sheetArg = input.sheet ?? input.sheetName;
2836
+ const columnName = typeof input.column === 'string' ? input.column.trim() : '';
2837
+ const operation = typeof input.operation === 'string' ? input.operation.trim().toLowerCase() : '';
2838
+ const ws = this.resolveSheet(workbook, sheetArg);
2839
+ if (!ws) {
2840
+ return this.errorResult(`Sheet "${String(sheetArg ?? '')}" not found.`);
2841
+ }
2842
+ if (!VALID_AGGREGATE_OPS.has(operation)) {
2843
+ return this.errorResult(`Unsupported aggregate operation: "${operation}". Valid operations: ${[...VALID_AGGREGATE_OPS].join(', ')}.`);
2844
+ }
2845
+ const headerMap = this.buildWorksheetHeaderMap(ws);
2846
+ let targetCol = -1;
2847
+ for (const [colIdx, name] of headerMap.entries()) {
2848
+ if (name === columnName || name.toLowerCase() === columnName.toLowerCase()) {
2849
+ targetCol = colIdx;
2850
+ break;
2851
+ }
2852
+ }
2853
+ if (targetCol === -1) {
2854
+ return this.errorResult(`Column "${columnName}" not found in sheet "${ws.Name}". Available columns: ${[...headerMap.values()].join(', ')}.`);
2855
+ }
2856
+ const bounds = this.getPopulatedBounds(ws);
2857
+ const numericValues = [];
2858
+ for (let r = 2; r <= bounds.maxRow; r++) {
2859
+ const addr = FormatCellAddress(r, targetCol);
2860
+ const cell = ws.Cells[addr];
2861
+ const raw = cell ? (cell.ComputedValue ?? cell.RawValue) : null;
2862
+ if (raw === null || raw === undefined || raw === '')
2863
+ continue;
2864
+ const num = typeof raw === 'number' ? raw : Number(raw);
2865
+ if (!Number.isNaN(num)) {
2866
+ numericValues.push(num);
2867
+ }
2868
+ }
2869
+ if (operation === 'count') {
2870
+ return this.successResult({ operation, column: columnName, value: numericValues.length });
2871
+ }
2872
+ if (numericValues.length === 0) {
2873
+ return this.errorResult(`No numeric values found in column "${columnName}".`);
2874
+ }
2875
+ let value;
2876
+ switch (operation) {
2877
+ case 'sum':
2878
+ value = numericValues.reduce((acc, v) => acc + v, 0);
2879
+ break;
2880
+ case 'avg':
2881
+ value = numericValues.reduce((acc, v) => acc + v, 0) / numericValues.length;
2882
+ break;
2883
+ case 'min':
2884
+ value = ComputeNumericExtremum(numericValues, 'min') ?? 0;
2885
+ break;
2886
+ case 'max':
2887
+ value = ComputeNumericExtremum(numericValues, 'max') ?? 0;
2888
+ break;
2889
+ default:
2890
+ value = numericValues.length;
2891
+ }
2892
+ return this.successResult({ operation, column: columnName, value: Number(value.toPrecision(15)) });
2893
+ }
2894
+ handleGetFormulas(workbook, input) {
2895
+ const sheetArg = input.sheet ?? input.sheetName;
2896
+ const ws = this.resolveSheet(workbook, sheetArg);
2897
+ if (!ws) {
2898
+ return this.errorResult(`Sheet "${String(sheetArg ?? '')}" not found.`);
2899
+ }
2900
+ const formulas = Object.values(ws.Cells)
2901
+ .filter((c) => Boolean(c.Formula))
2902
+ .sort((a, b) => {
2903
+ const pa = ParseCellAddress(a.Address);
2904
+ const pb = ParseCellAddress(b.Address);
2905
+ if (!pa || !pb)
2906
+ return 0;
2907
+ return pa.row !== pb.row ? pa.row - pb.row : pa.col - pb.col;
2908
+ })
2909
+ .map((c) => ({
2910
+ cell: c.Address,
2911
+ formula: c.Formula,
2912
+ computedValue: c.ComputedValue ?? null
2913
+ }));
2914
+ return this.successResult({ formulas });
2915
+ }
2916
+ buildWorksheetHeaderMap(ws) {
2917
+ const headerMap = new Map();
2918
+ const bounds = this.getPopulatedBounds(ws);
2919
+ for (let c = 1; c <= bounds.maxCol; c++) {
2920
+ const addr = FormatCellAddress(1, c);
2921
+ const cell = ws.Cells[addr];
2922
+ const val = cell ? (cell.ComputedValue ?? cell.RawValue) : null;
2923
+ if (val !== null && val !== undefined && String(val).trim() !== '') {
2924
+ headerMap.set(c, String(val).trim());
2925
+ }
2926
+ }
2927
+ return headerMap;
2928
+ }
2929
+ getPopulatedBounds(ws) {
2930
+ let maxRow = 0;
2931
+ let maxCol = 0;
2932
+ for (const cell of Object.values(ws.Cells)) {
2933
+ const pos = ParseCellAddress(cell.Address);
2934
+ if (!pos)
2935
+ continue;
2936
+ const val = cell.ComputedValue ?? cell.RawValue ?? cell.Formula;
2937
+ if (val !== null && val !== undefined && val !== '') {
2938
+ if (pos.row > maxRow)
2939
+ maxRow = pos.row;
2940
+ if (pos.col > maxCol)
2941
+ maxCol = pos.col;
2942
+ }
2943
+ }
2944
+ return { maxRow, maxCol };
2945
+ }
2946
+ async handleMergeCells(workbook, input, context) {
2947
+ const sheet = this.resolveSheet(workbook, input.sheet);
2948
+ if (!sheet) {
2949
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
2950
+ }
2951
+ const range = typeof input.range === 'string' ? input.range.trim().toUpperCase() : '';
2952
+ const parsed = range ? ParseRangeAddress(range) : null;
2953
+ if (!parsed) {
2954
+ return this.errorResult(`Invalid range '${String(input.range ?? '')}'. Expected A1 notation (e.g. "A1:C1").`);
2955
+ }
2956
+ const editCtx = this.extractCellEditContext(context);
2957
+ const protErr = checkBoundsProtection(sheet, parsed, editCtx, `merge cells '${range}'`);
2958
+ if (protErr) {
2959
+ return this.errorResult(protErr);
2960
+ }
2961
+ try {
2962
+ const mergedRange = SpreadsheetEngine.Instance.MergeCells(workbook, sheet.SheetID, range, editCtx);
2963
+ return this.buildMutationSuccess(workbook, {
2964
+ sheetId: sheet.SheetID,
2965
+ mergedRange,
2966
+ mergeRanges: sheet.MergeRanges ?? []
2967
+ });
2968
+ }
2969
+ catch (err) {
2970
+ return this.errorResult(err instanceof Error ? err.message : String(err));
2971
+ }
2972
+ }
2973
+ async handleUnmergeCells(workbook, input, context) {
2974
+ const sheet = this.resolveSheet(workbook, input.sheet);
2975
+ if (!sheet) {
2976
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
2977
+ }
2978
+ const range = typeof input.range === 'string' ? input.range.trim().toUpperCase() : '';
2979
+ const parsed = range ? ParseRangeAddress(range) : null;
2980
+ if (!parsed) {
2981
+ return this.errorResult(`Invalid range '${String(input.range ?? '')}'.`);
2982
+ }
2983
+ const editCtx = this.extractCellEditContext(context);
2984
+ const protErr = checkBoundsProtection(sheet, parsed, editCtx, `unmerge cells '${range}'`);
2985
+ if (protErr) {
2986
+ return this.errorResult(protErr);
2987
+ }
2988
+ try {
2989
+ const unmergedCount = SpreadsheetEngine.Instance.UnmergeCells(workbook, sheet.SheetID, range, editCtx);
2990
+ return this.buildMutationSuccess(workbook, {
2991
+ sheetId: sheet.SheetID,
2992
+ unmergedCount,
2993
+ mergeRanges: sheet.MergeRanges ?? []
2994
+ });
2995
+ }
2996
+ catch (err) {
2997
+ return this.errorResult(err instanceof Error ? err.message : String(err));
2998
+ }
2999
+ }
3000
+ async handleUpsertConditionalFormat(workbook, input, context) {
3001
+ const sheet = this.resolveSheet(workbook, input.sheet);
3002
+ if (!sheet) {
3003
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
3004
+ }
3005
+ const range = typeof input.range === 'string' ? input.range.trim().toUpperCase() : '';
3006
+ const parsed = range ? ParseRangeAddress(range) : null;
3007
+ if (!parsed) {
3008
+ return this.errorResult(`Invalid range '${String(input.range ?? '')}'.`);
3009
+ }
3010
+ const editCtx = this.extractCellEditContext(context);
3011
+ const protErr = checkBoundsProtection(sheet, parsed, editCtx, `upsert conditional format on '${range}'`);
3012
+ if (protErr) {
3013
+ return this.errorResult(protErr);
3014
+ }
3015
+ const operator = String(input.operator ?? '');
3016
+ if (operator !== 'gt' &&
3017
+ operator !== 'lt' &&
3018
+ operator !== 'eq' &&
3019
+ operator !== 'between' &&
3020
+ operator !== 'contains') {
3021
+ return this.errorResult(`Invalid operator '${operator}'.`);
3022
+ }
3023
+ const highlightTone = String(input.highlightTone ?? '');
3024
+ if (highlightTone !== 'success' &&
3025
+ highlightTone !== 'warning' &&
3026
+ highlightTone !== 'danger' &&
3027
+ highlightTone !== 'info') {
3028
+ return this.errorResult(`Invalid highlightTone '${highlightTone}'.`);
3029
+ }
3030
+ const rawVal1 = input.value1;
3031
+ if (typeof rawVal1 !== 'string' && typeof rawVal1 !== 'number') {
3032
+ return this.errorResult('Parameter "value1" must be a string or number.');
3033
+ }
3034
+ const rule = {
3035
+ RuleID: typeof input.ruleId === 'string' && input.ruleId.trim()
3036
+ ? input.ruleId.trim()
3037
+ : `cf-${randomUUID().slice(0, 8)}`,
3038
+ Range: range,
3039
+ Operator: operator,
3040
+ Value1: rawVal1,
3041
+ Value2: typeof input.value2 === 'number' && Number.isFinite(input.value2) ? input.value2 : undefined,
3042
+ HighlightTone: highlightTone
3043
+ };
3044
+ const saved = SpreadsheetEngine.Instance.AddConditionalFormat(workbook, sheet.SheetID, rule);
3045
+ return this.buildMutationSuccess(workbook, {
3046
+ sheetId: sheet.SheetID,
3047
+ rule: saved,
3048
+ conditionalFormatCount: sheet.ConditionalFormats.length
3049
+ });
3050
+ }
3051
+ async handleDeleteConditionalFormat(workbook, input, context) {
3052
+ const sheet = this.resolveSheet(workbook, input.sheet);
3053
+ if (!sheet) {
3054
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
3055
+ }
3056
+ const ruleId = typeof input.ruleId === 'string' ? input.ruleId.trim() : '';
3057
+ if (!ruleId) {
3058
+ return this.errorResult('Parameter "ruleId" is required.');
3059
+ }
3060
+ const existing = sheet.ConditionalFormats.find((r) => r.RuleID === ruleId);
3061
+ if (!existing) {
3062
+ return this.errorResult(`Conditional format rule '${ruleId}' was not found on sheet '${sheet.Name}'.`);
3063
+ }
3064
+ const parsed = ParseRangeAddress(existing.Range);
3065
+ if (parsed) {
3066
+ const protErr = checkBoundsProtection(sheet, parsed, this.extractCellEditContext(context), `delete conditional format '${ruleId}'`);
3067
+ if (protErr) {
3068
+ return this.errorResult(protErr);
3069
+ }
3070
+ }
3071
+ SpreadsheetEngine.Instance.RemoveConditionalFormat(workbook, sheet.SheetID, ruleId);
3072
+ return this.buildMutationSuccess(workbook, {
3073
+ sheetId: sheet.SheetID,
3074
+ deletedRuleId: ruleId,
3075
+ conditionalFormatCount: sheet.ConditionalFormats.length
3076
+ });
3077
+ }
3078
+ async handleUpsertValidationRule(workbook, input, context) {
3079
+ const sheet = this.resolveSheet(workbook, input.sheet);
3080
+ if (!sheet) {
3081
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
3082
+ }
3083
+ const range = typeof input.range === 'string' ? input.range.trim().toUpperCase() : '';
3084
+ const parsed = range ? ParseRangeAddress(range) : null;
3085
+ if (!parsed) {
3086
+ return this.errorResult(`Invalid range '${String(input.range ?? '')}'.`);
3087
+ }
3088
+ const editCtx = this.extractCellEditContext(context);
3089
+ const protErr = checkBoundsProtection(sheet, parsed, editCtx, `upsert validation rule on '${range}'`);
3090
+ if (protErr) {
3091
+ return this.errorResult(protErr);
3092
+ }
3093
+ const ruleType = String(input.ruleType ?? '');
3094
+ if (ruleType !== 'list' && ruleType !== 'numberRange' && ruleType !== 'notEmpty') {
3095
+ return this.errorResult(`Invalid ruleType '${ruleType}'.`);
3096
+ }
3097
+ const rule = {
3098
+ RuleID: typeof input.ruleId === 'string' && input.ruleId.trim()
3099
+ ? input.ruleId.trim()
3100
+ : `val-${randomUUID().slice(0, 8)}`,
3101
+ Range: range,
3102
+ RuleType: ruleType,
3103
+ AllowedValues: Array.isArray(input.allowedValues)
3104
+ ? input.allowedValues.filter((v) => typeof v === 'string')
3105
+ : undefined,
3106
+ MinValue: typeof input.minValue === 'number' && Number.isFinite(input.minValue) ? input.minValue : undefined,
3107
+ MaxValue: typeof input.maxValue === 'number' && Number.isFinite(input.maxValue) ? input.maxValue : undefined,
3108
+ ErrorMessage: typeof input.errorMessage === 'string' ? input.errorMessage : undefined
3109
+ };
3110
+ const saved = SpreadsheetEngine.Instance.AddValidationRule(workbook, sheet.SheetID, rule);
3111
+ return this.buildMutationSuccess(workbook, {
3112
+ sheetId: sheet.SheetID,
3113
+ rule: saved,
3114
+ validationRuleCount: sheet.ValidationRules.length
3115
+ });
3116
+ }
3117
+ async handleDeleteValidationRule(workbook, input, context) {
3118
+ const sheet = this.resolveSheet(workbook, input.sheet);
3119
+ if (!sheet) {
3120
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
3121
+ }
3122
+ const ruleId = typeof input.ruleId === 'string' ? input.ruleId.trim() : '';
3123
+ if (!ruleId) {
3124
+ return this.errorResult('Parameter "ruleId" is required.');
3125
+ }
3126
+ const existing = sheet.ValidationRules.find((r) => r.RuleID === ruleId);
3127
+ if (!existing) {
3128
+ return this.errorResult(`Validation rule '${ruleId}' was not found on sheet '${sheet.Name}'.`);
3129
+ }
3130
+ const parsed = ParseRangeAddress(existing.Range);
3131
+ if (parsed) {
3132
+ const protErr = checkBoundsProtection(sheet, parsed, this.extractCellEditContext(context), `delete validation rule '${ruleId}'`);
3133
+ if (protErr) {
3134
+ return this.errorResult(protErr);
3135
+ }
3136
+ }
3137
+ SpreadsheetEngine.Instance.RemoveValidationRule(workbook, sheet.SheetID, ruleId);
3138
+ return this.buildMutationSuccess(workbook, {
3139
+ sheetId: sheet.SheetID,
3140
+ deletedRuleId: ruleId,
3141
+ validationRuleCount: sheet.ValidationRules.length
3142
+ });
3143
+ }
3144
+ async handleUpsertNamedRange(workbook, input, context) {
3145
+ const sheet = this.resolveSheet(workbook, input.sheet);
3146
+ if (!sheet) {
3147
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
3148
+ }
3149
+ const name = typeof input.name === 'string' ? input.name.trim() : '';
3150
+ if (!name || !/^[A-Za-z_][A-Za-z0-9_.]*$/.test(name)) {
3151
+ return this.errorResult(`Invalid named range identifier '${name}'.`);
3152
+ }
3153
+ const range = typeof input.range === 'string' ? input.range.trim().toUpperCase() : '';
3154
+ const parsed = range ? ParseRangeAddress(range) : null;
3155
+ if (!parsed) {
3156
+ return this.errorResult(`Invalid range '${String(input.range ?? '')}'.`);
3157
+ }
3158
+ const protErr = checkBoundsProtection(sheet, parsed, this.extractCellEditContext(context), `upsert named range '${name}' at '${range}'`);
3159
+ if (protErr) {
3160
+ return this.errorResult(protErr);
3161
+ }
3162
+ const spec = {
3163
+ Name: name,
3164
+ SheetID: sheet.SheetID,
3165
+ Range: range,
3166
+ Description: typeof input.description === 'string' ? input.description : undefined
3167
+ };
3168
+ const saved = SpreadsheetEngine.Instance.SetNamedRange(workbook, spec, false);
3169
+ return this.buildMutationSuccess(workbook, {
3170
+ namedRange: saved,
3171
+ namedRangeCount: workbook.NamedRanges.length
3172
+ });
3173
+ }
3174
+ async handleDeleteNamedRange(workbook, input, context) {
3175
+ const name = typeof input.name === 'string' ? input.name.trim() : '';
3176
+ if (!name) {
3177
+ return this.errorResult('Parameter "name" is required.');
3178
+ }
3179
+ const existing = workbook.NamedRanges.find((n) => n.Name.toLowerCase() === name.toLowerCase());
3180
+ if (!existing) {
3181
+ return this.errorResult(`Named range '${name}' was not found.`);
3182
+ }
3183
+ const targetSheet = workbook.Worksheets.find((w) => w.SheetID === existing.SheetID);
3184
+ const parsed = ParseRangeAddress(existing.Range);
3185
+ if (targetSheet && parsed) {
3186
+ const protErr = checkBoundsProtection(targetSheet, parsed, this.extractCellEditContext(context), `delete named range '${name}'`);
3187
+ if (protErr) {
3188
+ return this.errorResult(protErr);
3189
+ }
3190
+ }
3191
+ SpreadsheetEngine.Instance.RemoveNamedRange(workbook, existing.Name, false);
3192
+ return this.buildMutationSuccess(workbook, {
3193
+ deletedName: existing.Name,
3194
+ namedRangeCount: workbook.NamedRanges.length
3195
+ });
3196
+ }
3197
+ async handleSetLock(workbook, input, context) {
3198
+ const sheet = this.resolveSheet(workbook, input.sheet);
3199
+ if (!sheet) {
3200
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
3201
+ }
3202
+ const range = typeof input.range === 'string' ? input.range.trim().toUpperCase() : '';
3203
+ if (!range || !ParseRangeAddress(range)) {
3204
+ return this.errorResult(`Invalid range '${String(input.range ?? '')}' for set_lock.`);
3205
+ }
3206
+ const editCtx = this.extractCellEditContext(context);
3207
+ const actorUserId = editCtx.UserID ?? editCtx.OwnerUserID ?? 'system';
3208
+ const rangeId = typeof input.rangeId === 'string' && input.rangeId.trim()
3209
+ ? input.rangeId.trim()
3210
+ : `prot-${randomUUID().slice(0, 8)}`;
3211
+ try {
3212
+ const protectedRange = SpreadsheetEngine.Instance.AddProtectedRange(workbook, sheet.SheetID, {
3213
+ RangeID: rangeId,
3214
+ Range: range,
3215
+ LockedByUserID: actorUserId,
3216
+ Description: typeof input.description === 'string' ? input.description : undefined,
3217
+ AllowEditors: input.allowEditors === true
3218
+ }, editCtx);
3219
+ return this.buildMutationSuccess(workbook, {
3220
+ sheetId: sheet.SheetID,
3221
+ protectedRange,
3222
+ protectedRangeCount: sheet.ProtectedRanges?.length ?? 0
3223
+ });
3224
+ }
3225
+ catch (err) {
3226
+ return this.errorResult(err instanceof Error ? err.message : String(err));
3227
+ }
3228
+ }
3229
+ async handleReleaseLock(workbook, input, context) {
3230
+ const sheet = this.resolveSheet(workbook, input.sheet);
3231
+ if (!sheet) {
3232
+ return this.errorResult(`Worksheet '${String(input.sheet ?? '')}' not found.`);
3233
+ }
3234
+ const explicitId = typeof input.rangeId === 'string' ? input.rangeId.trim() : '';
3235
+ const rangeMatch = typeof input.range === 'string' ? input.range.trim().toUpperCase() : '';
3236
+ let targetRule = explicitId
3237
+ ? (sheet.ProtectedRanges ?? []).find((r) => r.RangeID === explicitId)
3238
+ : undefined;
3239
+ if (!targetRule && rangeMatch) {
3240
+ targetRule = (sheet.ProtectedRanges ?? []).find((r) => r.Range.toUpperCase() === rangeMatch);
3241
+ }
3242
+ if (!targetRule) {
3243
+ return this.errorResult(`Protected range lock '${explicitId || rangeMatch}' was not found on sheet '${sheet.Name}'.`);
3244
+ }
3245
+ const editCtx = this.extractCellEditContext(context);
3246
+ try {
3247
+ const removed = SpreadsheetEngine.Instance.RemoveProtectedRange(workbook, sheet.SheetID, targetRule.RangeID, editCtx);
3248
+ if (!removed) {
3249
+ return this.errorResult(`Protected range lock '${targetRule.RangeID}' was not removed.`);
3250
+ }
3251
+ return this.buildMutationSuccess(workbook, {
3252
+ sheetId: sheet.SheetID,
3253
+ unlockedRangeId: targetRule.RangeID,
3254
+ protectedRangeCount: sheet.ProtectedRanges?.length ?? 0
3255
+ });
3256
+ }
3257
+ catch (err) {
3258
+ return this.errorResult(err instanceof Error ? err.message : String(err));
3259
+ }
3260
+ }
3261
+ async handleProposeSuggestion(workbook, artifactContent, input, context) {
3262
+ return ExecuteProposeSuggestionTool({
3263
+ domain: 'spreadsheet',
3264
+ artifactContent,
3265
+ input,
3266
+ context,
3267
+ validateTarget: (anchor) => {
3268
+ const sheet = this.resolveSheet(workbook, anchor.SheetId ?? anchor.Sheet);
3269
+ if (!sheet) {
3270
+ return { ok: false, errorMessage: `Target sheet '${String(anchor.Sheet ?? anchor.SheetId ?? '')}' not found.` };
3271
+ }
3272
+ const targetRange = (anchor.Range ?? anchor.CellAddress ?? '').trim().toUpperCase();
3273
+ if (!targetRange || !ParseRangeAddress(targetRange)) {
3274
+ return {
3275
+ ok: false,
3276
+ errorMessage: 'propose_suggestion for spreadsheets requires anchor.range (or anchor.cellAddress) in A1 notation.'
3277
+ };
3278
+ }
3279
+ return { ok: true };
3280
+ }
3281
+ });
3282
+ }
3283
+ async handleReviewSuggestion(workbook, artifactContent, input, context) {
3284
+ return ExecuteReviewSuggestionTool({
3285
+ domain: 'spreadsheet',
3286
+ artifactContent,
3287
+ input,
3288
+ context,
3289
+ applyAcceptedSuggestion: async (suggestion) => {
3290
+ const engine = SpreadsheetEngine.Instance;
3291
+ const targetAnchor = ParseSuggestionAnchor(suggestion.Anchor, 'spreadsheet');
3292
+ const sheet = this.resolveSheet(workbook, targetAnchor.SheetId ?? targetAnchor.Sheet);
3293
+ if (!sheet) {
3294
+ return { ok: false, errorMessage: 'Suggestion target sheet was not found.' };
3295
+ }
3296
+ const targetRange = (targetAnchor.Range ?? targetAnchor.CellAddress ?? '').trim().toUpperCase();
3297
+ const bounds = targetRange ? ParseRangeAddress(targetRange) : null;
3298
+ if (!bounds) {
3299
+ return { ok: false, errorMessage: `Invalid suggestion anchor range '${targetRange}'.` };
3300
+ }
3301
+ const editCtx = this.extractCellEditContext(context);
3302
+ const protErr = checkBoundsProtection(sheet, bounds, editCtx, `accept suggestion at '${targetRange}'`);
3303
+ if (protErr) {
3304
+ return { ok: false, errorMessage: protErr };
3305
+ }
3306
+ const anchorAddr = FormatCellAddress(bounds.startRow, bounds.startCol);
3307
+ const trimmedReplacement = suggestion.ProposedReplacement.trim();
3308
+ const isFormula = trimmedReplacement.startsWith('=');
3309
+ let scalarValue = suggestion.ProposedReplacement;
3310
+ if (!isFormula) {
3311
+ if (trimmedReplacement === 'true') {
3312
+ scalarValue = true;
3313
+ }
3314
+ else if (trimmedReplacement === 'false') {
3315
+ scalarValue = false;
3316
+ }
3317
+ else if (trimmedReplacement !== '' && Number.isFinite(Number(trimmedReplacement))) {
3318
+ scalarValue = Number(trimmedReplacement);
3319
+ }
3320
+ }
3321
+ engine.SetCell(workbook, sheet.SheetID, anchorAddr, isFormula ? { Formula: trimmedReplacement } : { Value: scalarValue }, false, editCtx);
3322
+ const mutation = await this.buildMutationSuccess(workbook, {
3323
+ sheetId: sheet.SheetID,
3324
+ appliedCell: anchorAddr
3325
+ });
3326
+ const payload = mutation.data;
3327
+ return {
3328
+ ok: true,
3329
+ updatedContent: payload.updatedContent ?? '',
3330
+ revisionHash: payload.revisionHash ?? '',
3331
+ xlsxBase64: payload.xlsxBase64,
3332
+ extra: {
3333
+ sheetId: sheet.SheetID,
3334
+ appliedRange: targetRange
3335
+ }
3336
+ };
3337
+ }
3338
+ });
3339
+ }
3340
+ successResult(data) {
3341
+ return { success: true, data };
3342
+ }
3343
+ errorResult(errorMessage) {
3344
+ return { success: false, data: null, errorMessage };
3345
+ }
3346
+ };
3347
+ SpreadsheetToolLibrary = __decorate([
3348
+ RegisterClass(BaseArtifactToolLibrary, 'SpreadsheetToolLibrary')
3349
+ ], SpreadsheetToolLibrary);
3350
+ export { SpreadsheetToolLibrary };
3351
+ //# sourceMappingURL=SpreadsheetToolLibrary.js.map