@mindstone/mcp-server-google-workspace 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +43 -5
  2. package/dist/modules/docs/service.d.ts +76 -6
  3. package/dist/modules/docs/service.js +791 -103
  4. package/dist/modules/docs/tabCopy.d.ts +266 -0
  5. package/dist/modules/docs/tabCopy.js +794 -0
  6. package/dist/modules/docs/tabs.d.ts +161 -0
  7. package/dist/modules/docs/tabs.js +416 -0
  8. package/dist/modules/docs/types.d.ts +141 -1
  9. package/dist/modules/drive/service.d.ts +15 -0
  10. package/dist/modules/drive/service.js +77 -2
  11. package/dist/modules/drive/types.d.ts +1 -1
  12. package/dist/modules/sheets/a1Utils.d.ts +13 -0
  13. package/dist/modules/sheets/a1Utils.js +33 -7
  14. package/dist/modules/sheets/formatters.d.ts +33 -2
  15. package/dist/modules/sheets/formatters.js +84 -5
  16. package/dist/modules/sheets/service.d.ts +26 -1
  17. package/dist/modules/sheets/service.js +264 -8
  18. package/dist/modules/sheets/types.d.ts +71 -0
  19. package/dist/modules/sheets/types.js +12 -1
  20. package/dist/modules/sheets/writeGuards.js +2 -2
  21. package/dist/tools/definitions/destructive-overrides.json +8 -0
  22. package/dist/tools/definitions/docs.js +395 -9
  23. package/dist/tools/definitions/drive.js +9 -4
  24. package/dist/tools/definitions/open-world-overrides.json +8 -0
  25. package/dist/tools/definitions/sheets.js +177 -1
  26. package/dist/tools/docs-handlers.d.ts +125 -0
  27. package/dist/tools/docs-handlers.js +397 -15
  28. package/dist/tools/param-normalizer.js +16 -0
  29. package/dist/tools/server.js +35 -3
  30. package/dist/tools/sheets-handlers.d.ts +54 -1
  31. package/dist/tools/sheets-handlers.js +107 -13
  32. package/dist/tools/type-guards.d.ts +89 -0
  33. package/dist/tools/type-guards.js +190 -6
  34. package/dist/tools/types.d.ts +1 -1
  35. package/dist/utils/apiError.d.ts +6 -0
  36. package/dist/utils/apiError.js +12 -0
  37. package/dist/utils/tabPosition.d.ts +20 -0
  38. package/dist/utils/tabPosition.js +19 -0
  39. package/package.json +1 -1
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Pure helpers for Google Docs tabs (no network).
3
+ *
4
+ * A Docs document is a tree of tabs: `doc.tabs[]`, each with `tabProperties`,
5
+ * `documentTab` (the content) and `childTabs[]`. The API only returns that tree
6
+ * when `documents.get` is called with `includeTabsContent: true`; without it the
7
+ * legacy top-level `body` holds the first tab's content only.
8
+ */
9
+ import { docs_v1 } from 'googleapis';
10
+ import { McpError } from '@modelcontextprotocol/sdk/types.js';
11
+ export declare const TRUNCATION_MARKER = "\n\n[TRUNCATED - document exceeds character limit]";
12
+ /**
13
+ * Input error raised by the tab helpers (unknown tab id, refused `default`,
14
+ * oversized JSON, …). Service catches rethrow it so the caller sees
15
+ * InvalidParams instead of a generic API failure.
16
+ */
17
+ export declare class DocsInputError extends McpError {
18
+ constructor(message: string);
19
+ }
20
+ export type FlatTab = {
21
+ tabId: string;
22
+ title: string;
23
+ parentTabId: string | null;
24
+ /** 0-based position among its siblings. */
25
+ index: number;
26
+ /** 0 = top-level tab. */
27
+ nestingLevel: number;
28
+ /** Titles from the top-level tab down, joined with " > ". */
29
+ path: string;
30
+ childCount: number;
31
+ tab: docs_v1.Schema$Tab;
32
+ };
33
+ /**
34
+ * Pre-order walk of the tab tree (parent before its children, siblings in order).
35
+ */
36
+ export declare function flattenTabs(tabs: docs_v1.Schema$Tab[] | undefined): FlatTab[];
37
+ /**
38
+ * `fields` mask for a tree-only read: tab properties down `depth` levels of
39
+ * `childTabs`, no content. Docs nests far fewer levels than the default 6.
40
+ */
41
+ export declare function buildTabTreeFields(depth?: number): string;
42
+ export declare const TAB_TREE_FIELDS: string;
43
+ export declare const DEFAULT_TAB_REFUSED_MESSAGE = "Pass a real tab id from list_workspace_document_tabs; \"default\" is not accepted by tools that delete, move, rename or overwrite a tab.";
44
+ /**
45
+ * Find a tab by id. `"default"` means the first top-level tab where
46
+ * `allowDefault` is true and is refused otherwise. The error message never
47
+ * echoes tab titles (they are untrusted document content).
48
+ */
49
+ export declare function resolveTab(flat: FlatTab[], requested: string, opts: {
50
+ allowDefault: boolean;
51
+ }): FlatTab;
52
+ /**
53
+ * Plain text of a body (paragraphs and one level of table cells; a newline after
54
+ * every table row). With no options the output matches the connector's original
55
+ * first-tab extraction exactly. `renderInline` also emits smart chips in place:
56
+ * rich-link title (or URI), person name and email, date display text.
57
+ * `markStructure` prefixes list items and headings with a read-only marker
58
+ * (see structureMarker).
59
+ */
60
+ export declare function extractBodyText(body: docs_v1.Schema$Body | undefined, opts?: {
61
+ renderInline?: boolean;
62
+ markStructure?: boolean;
63
+ }): string;
64
+ /** Text options of `tab_id` / `all_tabs` reads (the no-tab read passes none). */
65
+ export declare const TAB_READ_TEXT_OPTIONS: {
66
+ readonly renderInline: true;
67
+ readonly markStructure: true;
68
+ };
69
+ /**
70
+ * The text exactly as Docs will store it, so offsets computed from its length
71
+ * (the style-clear range, the reported count) cover only the inserted text.
72
+ * "\r\n" and a lone "\r" become "\n"; characters Docs would strip are removed
73
+ * and counted.
74
+ */
75
+ export declare function normalizeInsertText(text: string): {
76
+ text: string;
77
+ removedChars: number;
78
+ };
79
+ export declare function countWords(text: string): number;
80
+ /**
81
+ * Index to insert at the end of a body (before its final newline).
82
+ */
83
+ export declare function bodyEndIndex(body: docs_v1.Schema$Body | undefined): number;
84
+ /**
85
+ * The tab tree of an `includeTabsContent` read. Fails loudly instead of falling
86
+ * back to the legacy single-body view.
87
+ */
88
+ export declare function requireTabs(doc: docs_v1.Schema$Document): docs_v1.Schema$Tab[];
89
+ /**
90
+ * Refuse a tab title that another tab already uses. Docs requires tab titles
91
+ * to be unique across the whole document, sub-tabs included. Comparison is
92
+ * exact after trimming both sides. Echoing the caller's own title is fine; no
93
+ * document title is echoed.
94
+ */
95
+ export declare function assertUniqueTitle(flat: FlatTab[], title: string, exceptTabId?: string): void;
96
+ /**
97
+ * Every tab below `tabId` (children, grandchildren, …) in tree order.
98
+ */
99
+ export declare function descendantsOf(flat: FlatTab[], tabId: string): FlatTab[];
100
+ /**
101
+ * The tabs directly under `parentTabId` (`null` = top level), in position order.
102
+ */
103
+ export declare function siblingsOf(flat: FlatTab[], parentTabId: string | null): FlatTab[];
104
+ /** Every character-style field, for clearing a range's text style with `updateTextStyle`. */
105
+ export declare const ALL_TEXT_KEYS = "bold,italic,underline,strikethrough,smallCaps,fontSize,foregroundColor,backgroundColor,weightedFontFamily,baselineOffset,link";
106
+ /** Where a paragraph lives: the tab body, or one table cell (table = n-th table in the body). */
107
+ export type ParagraphContainer = 'body' | {
108
+ table: number;
109
+ row: number;
110
+ col: number;
111
+ };
112
+ export type FlatParagraph = {
113
+ paragraph: docs_v1.Schema$Paragraph;
114
+ container: ParagraphContainer;
115
+ startIndex: number;
116
+ endIndex: number;
117
+ /** Position of the paragraph's structural element in `body.content` (body paragraphs only). */
118
+ bodyElementIndex?: number;
119
+ };
120
+ /**
121
+ * Body paragraphs and table-cell paragraphs, in document order (one level of
122
+ * tables, like the text extraction).
123
+ */
124
+ export declare function flatParagraphs(body: docs_v1.Schema$Body | undefined): FlatParagraph[];
125
+ /**
126
+ * Searchable text of a paragraph whose string offsets equal document-index
127
+ * offsets: text runs as they are (JS strings count UTF-16 units, like the Docs
128
+ * API), every other element (smart chip, person, date, image, …) as one
129
+ * placeholder character per index it occupies, so it can never match an anchor.
130
+ */
131
+ export declare function paragraphSearchText(paragraph: docs_v1.Schema$Paragraph): string;
132
+ export type AnchorMatch = {
133
+ paragraphIdx: number;
134
+ offset: number;
135
+ };
136
+ /**
137
+ * Every place `anchor` occurs inside a single paragraph. Anchors never span
138
+ * paragraphs; an anchor containing a newline is refused.
139
+ */
140
+ export declare function findAnchor(paragraphs: FlatParagraph[], anchor: string, matchCase: boolean): AnchorMatch[];
141
+ /**
142
+ * Index of the start of the paragraph after `paragraphs[paragraphIdx]` in the
143
+ * same container: in the body, the next body element must be a paragraph; in a
144
+ * table cell, the next paragraph of the same cell.
145
+ */
146
+ export declare function nextParagraphInContainer(body: docs_v1.Schema$Body | undefined, paragraphs: FlatParagraph[], paragraphIdx: number): FlatParagraph;
147
+ /** Marker for the one tab an `all_tabs` read cuts at the shared budget. */
148
+ export declare const TAB_TRUNCATION_MARKER = "\n\n[TRUNCATED - this tab continues past the max_chars budget]";
149
+ /**
150
+ * Text of every tab, in tree order, under `## Tab:` headings. `maxChars` is one
151
+ * budget for tab text shared across all tabs; headings and the final
152
+ * "not shown in full" list sit outside it. The tab that crosses the budget is
153
+ * cut with the tab truncation marker; it heads the final list (marked
154
+ * "cut short"), followed by every later tab by path and id.
155
+ */
156
+ export declare function buildAllTabsText(flat: FlatTab[], maxChars: number): {
157
+ content: string;
158
+ truncated: boolean;
159
+ shownCount: number;
160
+ };
161
+ //# sourceMappingURL=tabs.d.ts.map
@@ -0,0 +1,416 @@
1
+ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
2
+ export const TRUNCATION_MARKER = '\n\n[TRUNCATED - document exceeds character limit]';
3
+ /**
4
+ * Input error raised by the tab helpers (unknown tab id, refused `default`,
5
+ * oversized JSON, …). Service catches rethrow it so the caller sees
6
+ * InvalidParams instead of a generic API failure.
7
+ */
8
+ export class DocsInputError extends McpError {
9
+ constructor(message) {
10
+ super(ErrorCode.InvalidParams, message);
11
+ this.name = 'DocsInputError';
12
+ }
13
+ }
14
+ /**
15
+ * Pre-order walk of the tab tree (parent before its children, siblings in order).
16
+ */
17
+ export function flattenTabs(tabs) {
18
+ const out = [];
19
+ const walk = (list, depth, parent) => {
20
+ (list ?? []).forEach((tab, position) => {
21
+ const props = tab.tabProperties ?? {};
22
+ const title = props.title ?? '';
23
+ const flat = {
24
+ tabId: props.tabId ?? '',
25
+ title,
26
+ parentTabId: parent ? parent.tabId : null,
27
+ index: props.index ?? position,
28
+ nestingLevel: depth,
29
+ path: parent ? `${parent.path} > ${title}` : title,
30
+ childCount: tab.childTabs?.length ?? 0,
31
+ tab,
32
+ };
33
+ out.push(flat);
34
+ walk(tab.childTabs, depth + 1, flat);
35
+ });
36
+ };
37
+ walk(tabs, 0, null);
38
+ return out;
39
+ }
40
+ /**
41
+ * `fields` mask for a tree-only read: tab properties down `depth` levels of
42
+ * `childTabs`, no content. Docs nests far fewer levels than the default 6.
43
+ */
44
+ export function buildTabTreeFields(depth = 6) {
45
+ const level = (remaining) => remaining <= 0 ? 'tabProperties' : `tabProperties,childTabs(${level(remaining - 1)})`;
46
+ return `tabs(${level(depth)})`;
47
+ }
48
+ export const TAB_TREE_FIELDS = 'documentId,title,revisionId,' + buildTabTreeFields();
49
+ export const DEFAULT_TAB_REFUSED_MESSAGE = 'Pass a real tab id from list_workspace_document_tabs; "default" is not accepted by tools that delete, move, rename or overwrite a tab.';
50
+ /**
51
+ * Find a tab by id. `"default"` means the first top-level tab where
52
+ * `allowDefault` is true and is refused otherwise. The error message never
53
+ * echoes tab titles (they are untrusted document content).
54
+ */
55
+ export function resolveTab(flat, requested, opts) {
56
+ if (requested === 'default') {
57
+ if (!opts.allowDefault) {
58
+ throw new DocsInputError(DEFAULT_TAB_REFUSED_MESSAGE);
59
+ }
60
+ const first = flat.find((tab) => tab.nestingLevel === 0);
61
+ if (first)
62
+ return first;
63
+ }
64
+ else {
65
+ const match = flat.find((tab) => tab.tabId === requested);
66
+ if (match)
67
+ return match;
68
+ }
69
+ throw new DocsInputError(`Tab "${requested}" not found in this document. Call list_workspace_document_tabs to see tab ids.`);
70
+ }
71
+ function inlineElementText(element, renderInline) {
72
+ if (element.textRun?.content) {
73
+ return element.textRun.content;
74
+ }
75
+ if (!renderInline) {
76
+ return undefined;
77
+ }
78
+ const richLink = element.richLink?.richLinkProperties;
79
+ if (richLink) {
80
+ return richLink.title || richLink.uri || undefined;
81
+ }
82
+ const person = element.person?.personProperties;
83
+ if (person) {
84
+ if (person.name && person.email)
85
+ return `${person.name} <${person.email}>`;
86
+ return person.name || person.email || undefined;
87
+ }
88
+ const date = element.dateElement?.dateElementProperties;
89
+ if (date?.displayText) {
90
+ return date.displayText;
91
+ }
92
+ return undefined;
93
+ }
94
+ const HEADING_MARKERS = {
95
+ TITLE: '[Title] ',
96
+ SUBTITLE: '[Subtitle] ',
97
+ HEADING_1: '[H1] ',
98
+ HEADING_2: '[H2] ',
99
+ HEADING_3: '[H3] ',
100
+ HEADING_4: '[H4] ',
101
+ HEADING_5: '[H5] ',
102
+ HEADING_6: '[H6] ',
103
+ };
104
+ /**
105
+ * Read-only marker in front of a paragraph: a list item gets "• " (two spaces
106
+ * of indent per nesting level), a heading gets "[H1] "…"[H6] ", "[Title] " or
107
+ * "[Subtitle] ". Not `#`, so a heading can't be mistaken for an all_tabs
108
+ * "## Tab:" line. The markers are not document text.
109
+ */
110
+ function structureMarker(paragraph) {
111
+ const heading = HEADING_MARKERS[paragraph.paragraphStyle?.namedStyleType ?? ''] ?? '';
112
+ if (!paragraph.bullet) {
113
+ return heading;
114
+ }
115
+ return `${' '.repeat(paragraph.bullet.nestingLevel ?? 0)}• ${heading}`;
116
+ }
117
+ /**
118
+ * Plain text of a body (paragraphs and one level of table cells; a newline after
119
+ * every table row). With no options the output matches the connector's original
120
+ * first-tab extraction exactly. `renderInline` also emits smart chips in place:
121
+ * rich-link title (or URI), person name and email, date display text.
122
+ * `markStructure` prefixes list items and headings with a read-only marker
123
+ * (see structureMarker).
124
+ */
125
+ export function extractBodyText(body, opts = {}) {
126
+ if (!body?.content) {
127
+ return '';
128
+ }
129
+ const renderInline = opts.renderInline === true;
130
+ const markStructure = opts.markStructure === true;
131
+ const textParts = [];
132
+ const pushParagraph = (paragraph) => {
133
+ if (markStructure && paragraph?.elements?.length) {
134
+ const marker = structureMarker(paragraph);
135
+ if (marker)
136
+ textParts.push(marker);
137
+ }
138
+ for (const paragraphElement of paragraph?.elements ?? []) {
139
+ const text = inlineElementText(paragraphElement, renderInline);
140
+ if (text) {
141
+ textParts.push(text);
142
+ }
143
+ }
144
+ };
145
+ for (const element of body.content) {
146
+ if (element.paragraph?.elements) {
147
+ pushParagraph(element.paragraph);
148
+ }
149
+ else if (element.table) {
150
+ // Extract text from table cells
151
+ for (const row of element.table.tableRows || []) {
152
+ for (const cell of row.tableCells || []) {
153
+ for (const cellElement of cell.content ?? []) {
154
+ if (cellElement.paragraph?.elements) {
155
+ pushParagraph(cellElement.paragraph);
156
+ }
157
+ }
158
+ }
159
+ textParts.push('\n'); // Row separator
160
+ }
161
+ }
162
+ }
163
+ return textParts.join('');
164
+ }
165
+ /** Text options of `tab_id` / `all_tabs` reads (the no-tab read passes none). */
166
+ export const TAB_READ_TEXT_OPTIONS = { renderInline: true, markStructure: true };
167
+ /**
168
+ * Characters the Docs API strips from `insertText`: control characters
169
+ * U+0000–U+0008 and U+000C–U+001F, and the BMP private-use area U+E000–U+F8FF.
170
+ * Tab (U+0009), newline (U+000A) and U+000B (a line break inside a paragraph)
171
+ * are kept. Carriage returns are handled before this, as line endings.
172
+ */
173
+ const DOCS_STRIPPED_CHARS = /[\u0000-\u0008\u000C-\u001F-]/g;
174
+ /**
175
+ * The text exactly as Docs will store it, so offsets computed from its length
176
+ * (the style-clear range, the reported count) cover only the inserted text.
177
+ * "\r\n" and a lone "\r" become "\n"; characters Docs would strip are removed
178
+ * and counted.
179
+ */
180
+ export function normalizeInsertText(text) {
181
+ const lineEndings = text.replace(/\r\n?/g, '\n');
182
+ const normalized = lineEndings.replace(DOCS_STRIPPED_CHARS, '');
183
+ return { text: normalized, removedChars: lineEndings.length - normalized.length };
184
+ }
185
+ export function countWords(text) {
186
+ return text.split(/\s+/).filter((word) => word.length > 0).length;
187
+ }
188
+ /**
189
+ * Index to insert at the end of a body (before its final newline).
190
+ */
191
+ export function bodyEndIndex(body) {
192
+ if (!body?.content || body.content.length === 0) {
193
+ return 1;
194
+ }
195
+ // Find the last structural element and get its end index
196
+ const lastElement = body.content[body.content.length - 1];
197
+ return (lastElement.endIndex ?? 1) - 1; // -1 to insert before final newline
198
+ }
199
+ /**
200
+ * The tab tree of an `includeTabsContent` read. Fails loudly instead of falling
201
+ * back to the legacy single-body view.
202
+ */
203
+ export function requireTabs(doc) {
204
+ if (!doc.tabs) {
205
+ throw new Error('Docs API returned no tabs for an includeTabsContent read');
206
+ }
207
+ return doc.tabs;
208
+ }
209
+ /**
210
+ * Refuse a tab title that another tab already uses. Docs requires tab titles
211
+ * to be unique across the whole document, sub-tabs included. Comparison is
212
+ * exact after trimming both sides. Echoing the caller's own title is fine; no
213
+ * document title is echoed.
214
+ */
215
+ export function assertUniqueTitle(flat, title, exceptTabId) {
216
+ const wanted = title.trim();
217
+ const clash = flat.find((tab) => tab.tabId !== exceptTabId && tab.title.trim() === wanted);
218
+ if (clash) {
219
+ throw new DocsInputError(`A tab titled "${wanted}" already exists. Tab titles must be unique across the whole document, including sub-tabs.`);
220
+ }
221
+ }
222
+ /**
223
+ * Every tab below `tabId` (children, grandchildren, …) in tree order.
224
+ */
225
+ export function descendantsOf(flat, tabId) {
226
+ const start = flat.findIndex((tab) => tab.tabId === tabId);
227
+ if (start < 0)
228
+ return [];
229
+ const depth = flat[start].nestingLevel;
230
+ const out = [];
231
+ // Pre-order: descendants follow the tab until the walk climbs back to its depth.
232
+ for (let i = start + 1; i < flat.length && flat[i].nestingLevel > depth; i++) {
233
+ out.push(flat[i]);
234
+ }
235
+ return out;
236
+ }
237
+ /**
238
+ * The tabs directly under `parentTabId` (`null` = top level), in position order.
239
+ */
240
+ export function siblingsOf(flat, parentTabId) {
241
+ return flat
242
+ .filter((tab) => tab.parentTabId === parentTabId)
243
+ .sort((a, b) => a.index - b.index);
244
+ }
245
+ /** Every character-style field, for clearing a range's text style with `updateTextStyle`. */
246
+ export const ALL_TEXT_KEYS = 'bold,italic,underline,strikethrough,smallCaps,fontSize,foregroundColor,backgroundColor,weightedFontFamily,baselineOffset,link';
247
+ /**
248
+ * Body paragraphs and table-cell paragraphs, in document order (one level of
249
+ * tables, like the text extraction).
250
+ */
251
+ export function flatParagraphs(body) {
252
+ const out = [];
253
+ let tableNumber = 0;
254
+ (body?.content ?? []).forEach((element, bodyElementIndex) => {
255
+ if (element.paragraph) {
256
+ out.push({
257
+ paragraph: element.paragraph,
258
+ container: 'body',
259
+ startIndex: element.startIndex ?? 0,
260
+ endIndex: element.endIndex ?? 0,
261
+ bodyElementIndex,
262
+ });
263
+ }
264
+ else if (element.table) {
265
+ (element.table.tableRows ?? []).forEach((row, rowIndex) => {
266
+ (row.tableCells ?? []).forEach((cell, colIndex) => {
267
+ for (const cellElement of cell.content ?? []) {
268
+ if (cellElement.paragraph) {
269
+ out.push({
270
+ paragraph: cellElement.paragraph,
271
+ container: { table: tableNumber, row: rowIndex, col: colIndex },
272
+ startIndex: cellElement.startIndex ?? 0,
273
+ endIndex: cellElement.endIndex ?? 0,
274
+ });
275
+ }
276
+ }
277
+ });
278
+ });
279
+ tableNumber++;
280
+ }
281
+ });
282
+ return out;
283
+ }
284
+ /** Object-replacement character standing in for one index of a non-text element. */
285
+ const NON_TEXT_PLACEHOLDER = '';
286
+ /**
287
+ * Searchable text of a paragraph whose string offsets equal document-index
288
+ * offsets: text runs as they are (JS strings count UTF-16 units, like the Docs
289
+ * API), every other element (smart chip, person, date, image, …) as one
290
+ * placeholder character per index it occupies, so it can never match an anchor.
291
+ */
292
+ export function paragraphSearchText(paragraph) {
293
+ return (paragraph.elements ?? [])
294
+ .map((element) => {
295
+ if (element.textRun) {
296
+ return element.textRun.content ?? '';
297
+ }
298
+ const span = element.startIndex != null && element.endIndex != null
299
+ ? element.endIndex - element.startIndex
300
+ : 1;
301
+ return NON_TEXT_PLACEHOLDER.repeat(Math.max(0, span));
302
+ })
303
+ .join('');
304
+ }
305
+ /**
306
+ * Case-insensitive comparison one UTF-16 unit at a time, so case folding that
307
+ * changes a string's length (e.g. "İ" lower-cases to two units) can never shift
308
+ * the match offset.
309
+ */
310
+ function sameCharIgnoringCase(a, b) {
311
+ return a === b || a.toLowerCase() === b.toLowerCase() || a.toUpperCase() === b.toUpperCase();
312
+ }
313
+ /**
314
+ * Every place `anchor` occurs inside a single paragraph. Anchors never span
315
+ * paragraphs; an anchor containing a newline is refused.
316
+ */
317
+ export function findAnchor(paragraphs, anchor, matchCase) {
318
+ if (anchor.length === 0) {
319
+ throw new DocsInputError('anchor_text must not be empty.');
320
+ }
321
+ if (anchor.includes('\n') || anchor.includes('\r')) {
322
+ throw new DocsInputError('anchor_text must be on one line.');
323
+ }
324
+ const matches = [];
325
+ paragraphs.forEach((entry, paragraphIdx) => {
326
+ const text = paragraphSearchText(entry.paragraph);
327
+ for (let offset = 0; offset + anchor.length <= text.length; offset++) {
328
+ let hit = true;
329
+ for (let i = 0; i < anchor.length; i++) {
330
+ const a = text[offset + i];
331
+ const b = anchor[i];
332
+ if (matchCase ? a !== b : !sameCharIgnoringCase(a, b)) {
333
+ hit = false;
334
+ break;
335
+ }
336
+ }
337
+ if (hit) {
338
+ matches.push({ paragraphIdx, offset });
339
+ }
340
+ }
341
+ });
342
+ return matches;
343
+ }
344
+ const NEXT_PARAGRAPH_MISSING_MESSAGE = 'The anchor paragraph is followed by a table (or nothing); use position "after" instead.';
345
+ /**
346
+ * Index of the start of the paragraph after `paragraphs[paragraphIdx]` in the
347
+ * same container: in the body, the next body element must be a paragraph; in a
348
+ * table cell, the next paragraph of the same cell.
349
+ */
350
+ export function nextParagraphInContainer(body, paragraphs, paragraphIdx) {
351
+ const current = paragraphs[paragraphIdx];
352
+ if (current.container === 'body') {
353
+ const nextElementIndex = (current.bodyElementIndex ?? -1) + 1;
354
+ const nextElement = body?.content?.[nextElementIndex];
355
+ const next = nextElement?.paragraph
356
+ ? paragraphs.find((entry) => entry.bodyElementIndex === nextElementIndex)
357
+ : undefined;
358
+ if (!next) {
359
+ throw new DocsInputError(NEXT_PARAGRAPH_MISSING_MESSAGE);
360
+ }
361
+ return next;
362
+ }
363
+ const cell = current.container;
364
+ const next = paragraphs[paragraphIdx + 1];
365
+ if (!next ||
366
+ next.container === 'body' ||
367
+ next.container.table !== cell.table ||
368
+ next.container.row !== cell.row ||
369
+ next.container.col !== cell.col) {
370
+ throw new DocsInputError(NEXT_PARAGRAPH_MISSING_MESSAGE);
371
+ }
372
+ return next;
373
+ }
374
+ /** Marker for the one tab an `all_tabs` read cuts at the shared budget. */
375
+ export const TAB_TRUNCATION_MARKER = '\n\n[TRUNCATED - this tab continues past the max_chars budget]';
376
+ /**
377
+ * Text of every tab, in tree order, under `## Tab:` headings. `maxChars` is one
378
+ * budget for tab text shared across all tabs; headings and the final
379
+ * "not shown in full" list sit outside it. The tab that crosses the budget is
380
+ * cut with the tab truncation marker; it heads the final list (marked
381
+ * "cut short"), followed by every later tab by path and id.
382
+ */
383
+ export function buildAllTabsText(flat, maxChars) {
384
+ const blocks = [];
385
+ let used = 0;
386
+ let cut;
387
+ let next = 0;
388
+ for (; next < flat.length; next++) {
389
+ const remaining = maxChars - used;
390
+ if (remaining <= 0) {
391
+ break;
392
+ }
393
+ const tab = flat[next];
394
+ const heading = `## Tab: ${tab.path} [tabId: ${tab.tabId}]`;
395
+ const text = extractBodyText(tab.tab.documentTab?.body, TAB_READ_TEXT_OPTIONS);
396
+ if (text.length > remaining) {
397
+ blocks.push(`${heading}\n${text.substring(0, remaining)}${TAB_TRUNCATION_MARKER}\n`);
398
+ cut = tab;
399
+ next++;
400
+ break;
401
+ }
402
+ blocks.push(`${heading}\n${text}\n`);
403
+ used += text.length;
404
+ }
405
+ const listed = [
406
+ ...(cut ? [`- ${cut.path} [tabId: ${cut.tabId}] (cut short)`] : []),
407
+ ...flat.slice(next).map((tab) => `- ${tab.path} [tabId: ${tab.tabId}]`),
408
+ ];
409
+ // Tab blocks end with their own newline; the final list is newline-joined.
410
+ let content = blocks.join('');
411
+ if (listed.length > 0) {
412
+ content += ['\n[Not shown in full — over the max_chars budget; read them with tab_id]:', ...listed].join('\n');
413
+ }
414
+ return { content, truncated: listed.length > 0, shownCount: next };
415
+ }
416
+ //# sourceMappingURL=tabs.js.map