@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +353 -2
- package/README.npm.md +28 -0
- package/auth/__init__.py +1 -0
- package/auth/auth_info_middleware.py +419 -0
- package/auth/client_secrets.py +76 -0
- package/auth/credential_store.py +598 -0
- package/auth/external_oauth_provider.py +369 -0
- package/auth/gateway_identity.py +164 -0
- package/auth/google_auth.py +1550 -0
- package/auth/google_oauth_provider.py +20 -0
- package/auth/mcp_session_middleware.py +95 -0
- package/auth/oauth21_session_store.py +1332 -0
- package/auth/oauth_callback_server.py +466 -0
- package/auth/oauth_config.py +693 -0
- package/auth/oauth_proxy_config.py +122 -0
- package/auth/oauth_responses.py +230 -0
- package/auth/oauth_types.py +92 -0
- package/auth/permissions.py +330 -0
- package/auth/port_resolver.py +153 -0
- package/auth/request_identity.py +89 -0
- package/auth/scopes.py +369 -0
- package/auth/service_decorator.py +1109 -0
- package/bin/google-workspace-mcp.cjs +123 -0
- package/core/__init__.py +1 -0
- package/core/api_enablement.py +108 -0
- package/core/attachment_storage.py +496 -0
- package/core/camel_case_middleware.py +98 -0
- package/core/cli.py +161 -0
- package/core/comments.py +609 -0
- package/core/config.py +57 -0
- package/core/context.py +43 -0
- package/core/file_limits.py +632 -0
- package/core/gcs_attachment_storage.py +253 -0
- package/core/http_utils.py +339 -0
- package/core/log_formatter.py +270 -0
- package/core/portable_schema_middleware.py +67 -0
- package/core/server.py +1192 -0
- package/core/startup_ui.py +239 -0
- package/core/storage.py +23 -0
- package/core/telemetry.py +194 -0
- package/core/tool_descriptions.py +19 -0
- package/core/tool_registry.py +311 -0
- package/core/tool_tier_loader.py +197 -0
- package/core/tool_tiers.yaml +179 -0
- package/core/toolset_header_middleware.py +67 -0
- package/core/utils.py +1537 -0
- package/core/valkey_storage.py +271 -0
- package/core/warning_filters.py +19 -0
- package/fastmcp_server.py +198 -0
- package/gappsscript/README.md +512 -0
- package/gappsscript/TESTING.md +254 -0
- package/gappsscript/__init__.py +0 -0
- package/gappsscript/apps_script_tools.py +1940 -0
- package/gcalendar/__init__.py +1 -0
- package/gcalendar/calendar_helpers.py +1323 -0
- package/gcalendar/calendar_tools.py +2252 -0
- package/gchat/__init__.py +7 -0
- package/gchat/chat_helpers.py +410 -0
- package/gchat/chat_tools.py +798 -0
- package/gcontacts/__init__.py +1 -0
- package/gcontacts/contacts_helpers.py +765 -0
- package/gcontacts/contacts_tools.py +1685 -0
- package/gdocs/__init__.py +0 -0
- package/gdocs/docs_anchors.py +163 -0
- package/gdocs/docs_comments.py +89 -0
- package/gdocs/docs_helpers.py +2201 -0
- package/gdocs/docs_links.py +87 -0
- package/gdocs/docs_markdown.py +828 -0
- package/gdocs/docs_markdown_writer.py +592 -0
- package/gdocs/docs_plain_text.py +463 -0
- package/gdocs/docs_structure.py +621 -0
- package/gdocs/docs_tables.py +425 -0
- package/gdocs/docs_tools.py +3300 -0
- package/gdocs/managers/__init__.py +18 -0
- package/gdocs/managers/batch_operation_manager.py +1694 -0
- package/gdocs/managers/header_footer_manager.py +526 -0
- package/gdocs/managers/table_operation_manager.py +488 -0
- package/gdocs/managers/validation_manager.py +1504 -0
- package/gdocs/operation_schemas.py +594 -0
- package/gdrive/__init__.py +0 -0
- package/gdrive/drive_helpers.py +1738 -0
- package/gdrive/drive_tools.py +3085 -0
- package/gforms/__init__.py +3 -0
- package/gforms/forms_tools.py +575 -0
- package/gmail/__init__.py +1 -0
- package/gmail/gmail_helpers.py +2107 -0
- package/gmail/gmail_tools.py +4895 -0
- package/gmail/gmail_web_mime.py +441 -0
- package/gsearch/__init__.py +0 -0
- package/gsearch/search_tools.py +253 -0
- package/gsheets/__init__.py +31 -0
- package/gsheets/sheets_helpers.py +2236 -0
- package/gsheets/sheets_tools.py +3280 -0
- package/gslides/__init__.py +0 -0
- package/gslides/slides_digest.py +390 -0
- package/gslides/slides_helpers.py +392 -0
- package/gslides/slides_markup.py +770 -0
- package/gslides/slides_tools.py +376 -0
- package/gtasks/__init__.py +5 -0
- package/gtasks/tasks_tools.py +936 -0
- package/main.py +1170 -0
- package/package.json +43 -4
- package/pyproject.toml +173 -0
- package/uv.lock +2504 -0
|
@@ -0,0 +1,1694 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Batch Operation Manager
|
|
3
|
+
|
|
4
|
+
This module provides high-level batch operation management for Google Docs,
|
|
5
|
+
extracting complex validation and request building logic.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import asyncio
|
|
10
|
+
from typing import Any, Union, Dict, List, Tuple
|
|
11
|
+
|
|
12
|
+
from gdocs.docs_anchors import (
|
|
13
|
+
AnchorResolutionError,
|
|
14
|
+
resolve_operation_anchor,
|
|
15
|
+
)
|
|
16
|
+
from gdocs.docs_helpers import (
|
|
17
|
+
utf16_length,
|
|
18
|
+
build_batch_update_body,
|
|
19
|
+
suggestion_save_error,
|
|
20
|
+
create_insert_text_request,
|
|
21
|
+
create_delete_range_request,
|
|
22
|
+
create_format_text_request,
|
|
23
|
+
create_update_paragraph_style_request,
|
|
24
|
+
create_update_table_cell_style_request,
|
|
25
|
+
create_find_replace_request,
|
|
26
|
+
create_insert_table_request,
|
|
27
|
+
create_insert_page_break_request,
|
|
28
|
+
create_insert_section_break_request,
|
|
29
|
+
create_insert_image_request,
|
|
30
|
+
create_insert_person_request,
|
|
31
|
+
create_insert_date_request,
|
|
32
|
+
create_dropdown_definition_request,
|
|
33
|
+
create_insert_dropdown_request,
|
|
34
|
+
create_bullet_list_request,
|
|
35
|
+
create_delete_bullet_list_request,
|
|
36
|
+
create_named_range_request,
|
|
37
|
+
create_delete_named_range_request,
|
|
38
|
+
create_replace_named_range_content_request,
|
|
39
|
+
create_update_document_style_request,
|
|
40
|
+
create_update_section_style_request,
|
|
41
|
+
create_create_header_footer_request,
|
|
42
|
+
create_insert_doc_tab_request,
|
|
43
|
+
create_delete_doc_tab_request,
|
|
44
|
+
create_update_doc_tab_request,
|
|
45
|
+
create_insert_table_row_request,
|
|
46
|
+
create_delete_table_row_request,
|
|
47
|
+
create_insert_table_column_request,
|
|
48
|
+
create_delete_table_column_request,
|
|
49
|
+
create_merge_table_cells_request,
|
|
50
|
+
create_unmerge_table_cells_request,
|
|
51
|
+
create_update_table_column_properties_request,
|
|
52
|
+
create_update_table_row_style_request,
|
|
53
|
+
create_pin_table_header_rows_request,
|
|
54
|
+
validate_operation,
|
|
55
|
+
)
|
|
56
|
+
from gdocs.managers.validation_manager import ValidationManager
|
|
57
|
+
|
|
58
|
+
logger = logging.getLogger(__name__)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _first_document_tab(tabs: list) -> dict | None:
|
|
62
|
+
"""First documentTab anywhere in the tab tree."""
|
|
63
|
+
for tab in tabs:
|
|
64
|
+
if "documentTab" in tab:
|
|
65
|
+
return tab["documentTab"]
|
|
66
|
+
found = _first_document_tab(tab.get("childTabs", []))
|
|
67
|
+
if found:
|
|
68
|
+
return found
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _find_document_tab(tabs: list, target_tab_id: str) -> dict | None:
|
|
73
|
+
"""documentTab for a given tab ID, anywhere in the tab tree."""
|
|
74
|
+
for tab in tabs:
|
|
75
|
+
if tab.get("tabProperties", {}).get("tabId") == target_tab_id:
|
|
76
|
+
return tab.get("documentTab")
|
|
77
|
+
found = _find_document_tab(tab.get("childTabs", []), target_tab_id)
|
|
78
|
+
if found:
|
|
79
|
+
return found
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class BatchOperationManager:
|
|
84
|
+
"""
|
|
85
|
+
High-level manager for Google Docs batch operations.
|
|
86
|
+
|
|
87
|
+
Handles complex multi-operation requests including:
|
|
88
|
+
- Operation validation and request building
|
|
89
|
+
- Batch execution with proper error handling
|
|
90
|
+
- Operation result processing and reporting
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(self, service):
|
|
94
|
+
"""
|
|
95
|
+
Initialize the batch operation manager.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
service: Google Docs API service instance
|
|
99
|
+
"""
|
|
100
|
+
self.service = service
|
|
101
|
+
self.validation_manager = ValidationManager()
|
|
102
|
+
|
|
103
|
+
async def execute_batch_operations(
|
|
104
|
+
self,
|
|
105
|
+
document_id: str,
|
|
106
|
+
operations: list[dict[str, Any]],
|
|
107
|
+
write_mode: str = "EDIT",
|
|
108
|
+
) -> tuple[bool, str, dict[str, Any]]:
|
|
109
|
+
"""
|
|
110
|
+
Execute multiple document operations in a single atomic batch.
|
|
111
|
+
|
|
112
|
+
This method extracts the complex logic from batch_update_doc tool function.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
document_id: ID of the document to update
|
|
116
|
+
operations: List of operation dictionaries
|
|
117
|
+
write_mode: "EDIT" applies the changes; "SUGGEST" records them as
|
|
118
|
+
suggested edits
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
Tuple of (success, message, metadata)
|
|
122
|
+
"""
|
|
123
|
+
logger.info(f"Executing batch operations on document {document_id}")
|
|
124
|
+
logger.info(f"Operations count: {len(operations)}")
|
|
125
|
+
|
|
126
|
+
if not operations:
|
|
127
|
+
return (
|
|
128
|
+
False,
|
|
129
|
+
"No operations provided. Please provide at least one operation.",
|
|
130
|
+
{},
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
# Anchor resolution rewrites locations and order; leave caller data intact.
|
|
135
|
+
operations = [dict(op) for op in operations]
|
|
136
|
+
anchor_error = await self._resolve_semantic_anchors(document_id, operations)
|
|
137
|
+
if anchor_error:
|
|
138
|
+
return False, anchor_error, {}
|
|
139
|
+
|
|
140
|
+
preflight_error = await self._preflight_create_header_footer_operations(
|
|
141
|
+
document_id, operations
|
|
142
|
+
)
|
|
143
|
+
if preflight_error:
|
|
144
|
+
return False, preflight_error, {}
|
|
145
|
+
|
|
146
|
+
# Validate and build requests
|
|
147
|
+
requests, operation_descriptions = await self._validate_and_build_requests(
|
|
148
|
+
operations
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
if not requests:
|
|
152
|
+
return False, "No valid requests could be built from operations", {}
|
|
153
|
+
|
|
154
|
+
revision_before = await self._get_revision_id(document_id)
|
|
155
|
+
|
|
156
|
+
# Execute the batch
|
|
157
|
+
result = await self._execute_batch_requests(
|
|
158
|
+
document_id, requests, write_mode
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
save_error = suggestion_save_error(result, write_mode)
|
|
162
|
+
if save_error:
|
|
163
|
+
return False, save_error, {}
|
|
164
|
+
|
|
165
|
+
# Process results
|
|
166
|
+
metadata = {
|
|
167
|
+
"operations_count": len(operations),
|
|
168
|
+
"requests_count": len(requests),
|
|
169
|
+
"replies_count": len(result.get("replies", [])),
|
|
170
|
+
"operation_summary": operation_descriptions[:5], # First 5 operations
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
metadata["revision_before"] = revision_before
|
|
174
|
+
|
|
175
|
+
# One post-batch read serves both the document length (for chaining)
|
|
176
|
+
# and the affected-range snapshot (so the caller can see what the
|
|
177
|
+
# write actually produced without a second verification call).
|
|
178
|
+
try:
|
|
179
|
+
doc = await asyncio.to_thread(
|
|
180
|
+
self.service.documents()
|
|
181
|
+
.get(
|
|
182
|
+
documentId=document_id,
|
|
183
|
+
includeTabsContent=True,
|
|
184
|
+
fields="revisionId,tabs",
|
|
185
|
+
)
|
|
186
|
+
.execute
|
|
187
|
+
)
|
|
188
|
+
metadata["revision_after"] = doc.get("revisionId")
|
|
189
|
+
targets = {}
|
|
190
|
+
for op in operations:
|
|
191
|
+
key = (op.get("tab_id"), op.get("segment_id"))
|
|
192
|
+
targets.setdefault(key, []).append(op)
|
|
193
|
+
target_ranges = []
|
|
194
|
+
for (tab_id, segment_id), target_ops in targets.items():
|
|
195
|
+
segment = self._target_segment(doc, tab_id, segment_id)
|
|
196
|
+
content = segment.get("content", []) if segment is not None else []
|
|
197
|
+
target = {
|
|
198
|
+
"tab_id": tab_id,
|
|
199
|
+
"segment_id": segment_id,
|
|
200
|
+
"document_length": (
|
|
201
|
+
(content[-1].get("endIndex", 0) if content else 1)
|
|
202
|
+
if segment is not None
|
|
203
|
+
else None
|
|
204
|
+
),
|
|
205
|
+
}
|
|
206
|
+
affected = self._affected_range(target_ops)
|
|
207
|
+
if affected and segment is not None:
|
|
208
|
+
target["affected_range"] = self._snapshot_range(
|
|
209
|
+
content, *affected
|
|
210
|
+
)
|
|
211
|
+
target_ranges.append(target)
|
|
212
|
+
metadata["target_ranges"] = target_ranges
|
|
213
|
+
# Preserve the existing fields only when there is one coordinate space.
|
|
214
|
+
if len(target_ranges) == 1:
|
|
215
|
+
metadata.update(target_ranges[0])
|
|
216
|
+
except Exception:
|
|
217
|
+
metadata["document_length"] = None
|
|
218
|
+
|
|
219
|
+
# Extract new tab IDs from insert_doc_tab replies
|
|
220
|
+
created_tabs = self._extract_created_tabs(result)
|
|
221
|
+
if created_tabs:
|
|
222
|
+
metadata["created_tabs"] = created_tabs
|
|
223
|
+
|
|
224
|
+
dropdown_results = self._extract_dropdown_results(requests, result)
|
|
225
|
+
if dropdown_results:
|
|
226
|
+
metadata["dropdown_results"] = dropdown_results
|
|
227
|
+
|
|
228
|
+
summary = self._build_operation_summary(operation_descriptions)
|
|
229
|
+
msg = f"Successfully executed {len(operations)} operations ({summary})"
|
|
230
|
+
if write_mode == "SUGGEST":
|
|
231
|
+
msg += " as suggested edits"
|
|
232
|
+
if created_tabs:
|
|
233
|
+
tab_info = ", ".join(
|
|
234
|
+
f"'{t['title']}' (tab_id: {t['tab_id']})" for t in created_tabs
|
|
235
|
+
)
|
|
236
|
+
msg += f". Created tabs: {tab_info}"
|
|
237
|
+
|
|
238
|
+
replace_verb = (
|
|
239
|
+
"Suggested replacing" if write_mode == "SUGGEST" else "Replaced"
|
|
240
|
+
)
|
|
241
|
+
for request, reply in zip(requests, result.get("replies", [])):
|
|
242
|
+
if "replaceAllText" in request:
|
|
243
|
+
count = reply.get("replaceAllText", {}).get("occurrencesChanged", 0)
|
|
244
|
+
find_text = request["replaceAllText"]["containsText"]["text"]
|
|
245
|
+
msg += f". {replace_verb} {count} occurrence(s) of '{find_text}'"
|
|
246
|
+
|
|
247
|
+
return True, msg, metadata
|
|
248
|
+
|
|
249
|
+
except Exception as e:
|
|
250
|
+
error_msg = self._rewrite_execution_error(str(e), operations)
|
|
251
|
+
logger.error(f"Failed to execute batch operations: {error_msg}")
|
|
252
|
+
return False, error_msg, {}
|
|
253
|
+
|
|
254
|
+
ANCHOR_FIELDS = ("after_heading", "before_heading", "anchor_text")
|
|
255
|
+
|
|
256
|
+
async def _resolve_semantic_anchors(
|
|
257
|
+
self, document_id: str, operations: list[dict[str, Any]]
|
|
258
|
+
) -> str | None:
|
|
259
|
+
"""
|
|
260
|
+
Rewrite semantic anchors into concrete indices before requests are built.
|
|
261
|
+
|
|
262
|
+
Resolving here rather than in the caller means the index is computed from
|
|
263
|
+
the document as it is at execution time, which is what makes an anchor
|
|
264
|
+
safer than an index the caller computed earlier.
|
|
265
|
+
"""
|
|
266
|
+
anchored = [
|
|
267
|
+
op
|
|
268
|
+
for op in operations
|
|
269
|
+
if any(op.get(field) is not None for field in self.ANCHOR_FIELDS)
|
|
270
|
+
]
|
|
271
|
+
if not anchored:
|
|
272
|
+
return None
|
|
273
|
+
|
|
274
|
+
for op in anchored:
|
|
275
|
+
if op.get("type") not in {
|
|
276
|
+
"insert_text",
|
|
277
|
+
"insert_table",
|
|
278
|
+
"insert_page_break",
|
|
279
|
+
"insert_section_break",
|
|
280
|
+
"insert_image",
|
|
281
|
+
"insert_person",
|
|
282
|
+
"insert_date",
|
|
283
|
+
"insert_dropdown",
|
|
284
|
+
}:
|
|
285
|
+
return "Semantic anchors are supported only for insertion operations."
|
|
286
|
+
valid, error = validate_operation(op)
|
|
287
|
+
if not valid:
|
|
288
|
+
return error
|
|
289
|
+
if len(anchored) != len(operations):
|
|
290
|
+
return (
|
|
291
|
+
"Semantic anchors cannot be mixed with other operations in one batch. "
|
|
292
|
+
"Submit anchored insertions separately so earlier mutations cannot "
|
|
293
|
+
"invalidate their indices."
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
doc = await asyncio.to_thread(
|
|
297
|
+
self.service.documents()
|
|
298
|
+
.get(documentId=document_id, includeTabsContent=True)
|
|
299
|
+
.execute
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
for op in anchored:
|
|
303
|
+
body = self._target_segment(doc, op.get("tab_id"), op.get("segment_id"))
|
|
304
|
+
if body is None:
|
|
305
|
+
return (
|
|
306
|
+
f"Tab '{op.get('tab_id')}' or segment '{op.get('segment_id')}' "
|
|
307
|
+
f"not found in document {document_id}."
|
|
308
|
+
)
|
|
309
|
+
try:
|
|
310
|
+
op["index"] = resolve_operation_anchor(
|
|
311
|
+
body,
|
|
312
|
+
after_heading=op.get("after_heading"),
|
|
313
|
+
before_heading=op.get("before_heading"),
|
|
314
|
+
anchor_text=op.get("anchor_text"),
|
|
315
|
+
anchor_position=op.get("anchor_position", "after"),
|
|
316
|
+
)
|
|
317
|
+
except AnchorResolutionError as e:
|
|
318
|
+
return str(e)
|
|
319
|
+
op["end_of_segment"] = False
|
|
320
|
+
for field in self.ANCHOR_FIELDS:
|
|
321
|
+
op.pop(field, None)
|
|
322
|
+
op.pop("anchor_position", None)
|
|
323
|
+
|
|
324
|
+
# Every operation is an anchored insertion into the pre-batch document.
|
|
325
|
+
# Higher indices first avoid shifting later targets; reverse ties preserve
|
|
326
|
+
# the caller's text order for multiple insertions at the same location.
|
|
327
|
+
operations[:] = [
|
|
328
|
+
op
|
|
329
|
+
for _, op in sorted(
|
|
330
|
+
enumerate(operations),
|
|
331
|
+
key=lambda item: (item[1]["index"], item[0]),
|
|
332
|
+
reverse=True,
|
|
333
|
+
)
|
|
334
|
+
]
|
|
335
|
+
return None
|
|
336
|
+
|
|
337
|
+
@staticmethod
|
|
338
|
+
def _target_segment(
|
|
339
|
+
doc: dict[str, Any], tab_id: str | None, segment_id: str | None = None
|
|
340
|
+
) -> dict[str, Any] | None:
|
|
341
|
+
"""Select one tab and its body, header, footer or footnote coordinate space."""
|
|
342
|
+
tabs = doc.get("tabs", [])
|
|
343
|
+
if tab_id:
|
|
344
|
+
tab = _find_document_tab(tabs, tab_id)
|
|
345
|
+
elif tabs:
|
|
346
|
+
tab = _first_document_tab(tabs)
|
|
347
|
+
else:
|
|
348
|
+
tab = doc
|
|
349
|
+
if tab is None:
|
|
350
|
+
return None
|
|
351
|
+
if not segment_id:
|
|
352
|
+
return tab.get("body", {})
|
|
353
|
+
for kind in ("headers", "footers", "footnotes"):
|
|
354
|
+
if segment_id in tab.get(kind, {}):
|
|
355
|
+
return tab[kind][segment_id]
|
|
356
|
+
return None
|
|
357
|
+
|
|
358
|
+
async def _get_revision_id(self, document_id: str) -> str | None:
|
|
359
|
+
"""Document revision before the batch, for correlating with version history."""
|
|
360
|
+
try:
|
|
361
|
+
doc = await asyncio.to_thread(
|
|
362
|
+
self.service.documents()
|
|
363
|
+
.get(documentId=document_id, fields="revisionId")
|
|
364
|
+
.execute
|
|
365
|
+
)
|
|
366
|
+
return doc.get("revisionId")
|
|
367
|
+
except Exception:
|
|
368
|
+
return None
|
|
369
|
+
|
|
370
|
+
@staticmethod
|
|
371
|
+
def _affected_range(
|
|
372
|
+
operations: list[dict[str, Any]],
|
|
373
|
+
) -> tuple[int, int] | None:
|
|
374
|
+
"""
|
|
375
|
+
Widest index range the operations targeted, or None when none is known.
|
|
376
|
+
|
|
377
|
+
Indices come from the request as submitted, so this brackets where the
|
|
378
|
+
edit was aimed; the snapshot then reports what is actually there now.
|
|
379
|
+
"""
|
|
380
|
+
starts: list[int] = []
|
|
381
|
+
ends: list[int] = []
|
|
382
|
+
for op in operations:
|
|
383
|
+
start = op.get("start_index")
|
|
384
|
+
if start is None:
|
|
385
|
+
start = op.get("index")
|
|
386
|
+
if start is None:
|
|
387
|
+
continue
|
|
388
|
+
end = op.get("end_index")
|
|
389
|
+
if end is None:
|
|
390
|
+
end = start + utf16_length(op.get("text") or "")
|
|
391
|
+
starts.append(start)
|
|
392
|
+
ends.append(end)
|
|
393
|
+
if not starts:
|
|
394
|
+
return None
|
|
395
|
+
return min(starts), max(ends)
|
|
396
|
+
|
|
397
|
+
@staticmethod
|
|
398
|
+
def _snapshot_range(
|
|
399
|
+
body_content: list[dict[str, Any]], start: int, end: int
|
|
400
|
+
) -> list[dict[str, Any]]:
|
|
401
|
+
"""Per-paragraph style and list membership for paragraphs overlapping a range."""
|
|
402
|
+
snapshot = []
|
|
403
|
+
for element in body_content:
|
|
404
|
+
paragraph = element.get("paragraph")
|
|
405
|
+
if paragraph is None:
|
|
406
|
+
continue
|
|
407
|
+
elem_start = element.get("startIndex", 0)
|
|
408
|
+
elem_end = element.get("endIndex", 0)
|
|
409
|
+
if elem_end <= start or elem_start >= end:
|
|
410
|
+
continue
|
|
411
|
+
text = "".join(
|
|
412
|
+
pe.get("textRun", {}).get("content", "")
|
|
413
|
+
for pe in paragraph.get("elements", [])
|
|
414
|
+
)
|
|
415
|
+
snapshot.append(
|
|
416
|
+
{
|
|
417
|
+
"start_index": elem_start,
|
|
418
|
+
"end_index": elem_end,
|
|
419
|
+
"named_style": paragraph.get("paragraphStyle", {}).get(
|
|
420
|
+
"namedStyleType"
|
|
421
|
+
),
|
|
422
|
+
"in_list": "bullet" in paragraph,
|
|
423
|
+
"text_preview": text[:80],
|
|
424
|
+
}
|
|
425
|
+
)
|
|
426
|
+
if len(snapshot) >= 20:
|
|
427
|
+
break
|
|
428
|
+
return snapshot
|
|
429
|
+
|
|
430
|
+
async def _preflight_create_header_footer_operations(
|
|
431
|
+
self, document_id: str, operations: list[dict[str, Any]]
|
|
432
|
+
) -> str | None:
|
|
433
|
+
"""
|
|
434
|
+
Validate create_header_footer operations against the live document before
|
|
435
|
+
sending low-level Docs API requests that often fail opaquely.
|
|
436
|
+
"""
|
|
437
|
+
create_ops = [
|
|
438
|
+
op for op in operations if op.get("type") == "create_header_footer"
|
|
439
|
+
]
|
|
440
|
+
if not create_ops:
|
|
441
|
+
return None
|
|
442
|
+
|
|
443
|
+
doc = await asyncio.to_thread(
|
|
444
|
+
self.service.documents().get(documentId=document_id).execute
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
style_field_map = {
|
|
448
|
+
"header": {
|
|
449
|
+
"DEFAULT": "defaultHeaderId",
|
|
450
|
+
"FIRST_PAGE_ONLY": "firstPageHeaderId",
|
|
451
|
+
"EVEN_PAGE": "evenPageHeaderId",
|
|
452
|
+
},
|
|
453
|
+
"footer": {
|
|
454
|
+
"DEFAULT": "defaultFooterId",
|
|
455
|
+
"FIRST_PAGE_ONLY": "firstPageFooterId",
|
|
456
|
+
"EVEN_PAGE": "evenPageFooterId",
|
|
457
|
+
},
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
section_breaks: dict[int, dict[str, Any]] = {}
|
|
461
|
+
for element in doc.get("body", {}).get("content", []):
|
|
462
|
+
if "sectionBreak" in element:
|
|
463
|
+
section_breaks[element.get("startIndex", 0)] = element["sectionBreak"]
|
|
464
|
+
|
|
465
|
+
for op in create_ops:
|
|
466
|
+
section_type = op["section_type"]
|
|
467
|
+
header_footer_type = op.get("header_footer_type", "DEFAULT")
|
|
468
|
+
style_field = style_field_map[section_type][header_footer_type]
|
|
469
|
+
section_break_index = op.get("section_break_index")
|
|
470
|
+
|
|
471
|
+
if section_break_index is None:
|
|
472
|
+
if doc.get("documentStyle", {}).get(style_field):
|
|
473
|
+
return (
|
|
474
|
+
"Batch operation failed: the requested header/footer already exists. "
|
|
475
|
+
"For normal header or footer text, use update_doc_headers_footers "
|
|
476
|
+
"instead of batch_update_doc with create_header_footer. "
|
|
477
|
+
"Reserve create_header_footer for advanced section-break layouts."
|
|
478
|
+
)
|
|
479
|
+
continue
|
|
480
|
+
|
|
481
|
+
if section_break_index not in section_breaks:
|
|
482
|
+
available = sorted(section_breaks.keys())
|
|
483
|
+
return (
|
|
484
|
+
"Batch operation failed: section_break_index must match an existing "
|
|
485
|
+
"section break start index from inspect_doc_structure.section_breaks[]. "
|
|
486
|
+
f"Got {section_break_index}. Available section break indices: {available or 'none'}. "
|
|
487
|
+
"For normal header/footer text, use update_doc_headers_footers instead."
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
if (
|
|
491
|
+
section_breaks[section_break_index]
|
|
492
|
+
.get("sectionStyle", {})
|
|
493
|
+
.get(style_field)
|
|
494
|
+
):
|
|
495
|
+
return (
|
|
496
|
+
"Batch operation failed: the requested section-scoped header/footer "
|
|
497
|
+
"already exists at that section break. Use inspect_doc_structure to "
|
|
498
|
+
"find real section breaks, or use update_doc_headers_footers for "
|
|
499
|
+
"ordinary header/footer text."
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
return None
|
|
503
|
+
|
|
504
|
+
async def _validate_and_build_requests(
|
|
505
|
+
self, operations: list[dict[str, Any]]
|
|
506
|
+
) -> tuple[list[dict[str, Any]], list[str]]:
|
|
507
|
+
"""
|
|
508
|
+
Validate operations and build API requests.
|
|
509
|
+
|
|
510
|
+
Args:
|
|
511
|
+
operations: List of operation dictionaries
|
|
512
|
+
|
|
513
|
+
Returns:
|
|
514
|
+
Tuple of (requests, operation_descriptions)
|
|
515
|
+
"""
|
|
516
|
+
requests = []
|
|
517
|
+
operation_descriptions = []
|
|
518
|
+
|
|
519
|
+
for i, op in enumerate(operations):
|
|
520
|
+
# Validate operation structure
|
|
521
|
+
is_valid, error_msg = validate_operation(op)
|
|
522
|
+
if not is_valid:
|
|
523
|
+
raise ValueError(f"Operation {i + 1}: {error_msg}")
|
|
524
|
+
|
|
525
|
+
op_type = op.get("type")
|
|
526
|
+
|
|
527
|
+
try:
|
|
528
|
+
# Build request based on operation type
|
|
529
|
+
result = self._build_operation_request(op, op_type)
|
|
530
|
+
|
|
531
|
+
# Handle both single request and list of requests
|
|
532
|
+
if isinstance(result[0], list):
|
|
533
|
+
# Multiple requests (e.g., replace_text)
|
|
534
|
+
for req in result[0]:
|
|
535
|
+
requests.append(req)
|
|
536
|
+
operation_descriptions.append(result[1])
|
|
537
|
+
elif result[0]:
|
|
538
|
+
# Single request
|
|
539
|
+
requests.append(result[0])
|
|
540
|
+
operation_descriptions.append(result[1])
|
|
541
|
+
|
|
542
|
+
except KeyError as e:
|
|
543
|
+
raise ValueError(
|
|
544
|
+
f"Operation {i + 1} ({op_type}) missing required field: {e}"
|
|
545
|
+
)
|
|
546
|
+
except Exception as e:
|
|
547
|
+
raise ValueError(
|
|
548
|
+
f"Operation {i + 1} ({op_type}) failed validation: {str(e)}"
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
return requests, operation_descriptions
|
|
552
|
+
|
|
553
|
+
def _build_operation_request(
|
|
554
|
+
self, op: dict[str, Any], op_type: str
|
|
555
|
+
) -> Tuple[Union[Dict[str, Any], List[Dict[str, Any]]], str]:
|
|
556
|
+
"""
|
|
557
|
+
Build a single operation request.
|
|
558
|
+
|
|
559
|
+
Args:
|
|
560
|
+
op: Operation dictionary
|
|
561
|
+
op_type: Operation type
|
|
562
|
+
|
|
563
|
+
Returns:
|
|
564
|
+
Tuple of (request, description)
|
|
565
|
+
"""
|
|
566
|
+
tab_id = op.get("tab_id")
|
|
567
|
+
segment_id = op.get("segment_id")
|
|
568
|
+
end_of_segment = op.get("end_of_segment", False)
|
|
569
|
+
|
|
570
|
+
if op_type == "insert_text":
|
|
571
|
+
request = create_insert_text_request(
|
|
572
|
+
op.get("index"),
|
|
573
|
+
op["text"],
|
|
574
|
+
tab_id,
|
|
575
|
+
segment_id=segment_id,
|
|
576
|
+
end_of_segment=end_of_segment,
|
|
577
|
+
)
|
|
578
|
+
description = (
|
|
579
|
+
f"insert text at end of segment '{segment_id or 'body'}'"
|
|
580
|
+
if end_of_segment
|
|
581
|
+
else f"insert text at {op['index']}"
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
elif op_type == "delete_text":
|
|
585
|
+
request = create_delete_range_request(
|
|
586
|
+
op["start_index"],
|
|
587
|
+
op["end_index"],
|
|
588
|
+
tab_id,
|
|
589
|
+
segment_id=segment_id,
|
|
590
|
+
)
|
|
591
|
+
description = f"delete text {op['start_index']}-{op['end_index']}"
|
|
592
|
+
|
|
593
|
+
elif op_type == "replace_text":
|
|
594
|
+
delete_request = create_delete_range_request(
|
|
595
|
+
op["start_index"],
|
|
596
|
+
op["end_index"],
|
|
597
|
+
tab_id,
|
|
598
|
+
segment_id=segment_id,
|
|
599
|
+
)
|
|
600
|
+
insert_request = create_insert_text_request(
|
|
601
|
+
op["start_index"],
|
|
602
|
+
op["text"],
|
|
603
|
+
tab_id,
|
|
604
|
+
segment_id=segment_id,
|
|
605
|
+
)
|
|
606
|
+
request = [delete_request, insert_request]
|
|
607
|
+
description = f"replace text {op['start_index']}-{op['end_index']} with '{op['text'][:20]}{'...' if len(op['text']) > 20 else ''}'"
|
|
608
|
+
|
|
609
|
+
elif op_type == "format_text":
|
|
610
|
+
request = create_format_text_request(
|
|
611
|
+
op["start_index"],
|
|
612
|
+
op["end_index"],
|
|
613
|
+
op.get("bold"),
|
|
614
|
+
op.get("italic"),
|
|
615
|
+
op.get("underline"),
|
|
616
|
+
op.get("strikethrough"),
|
|
617
|
+
op.get("font_size"),
|
|
618
|
+
op.get("font_family"),
|
|
619
|
+
op.get("font_weight"),
|
|
620
|
+
op.get("text_color"),
|
|
621
|
+
op.get("background_color"),
|
|
622
|
+
op.get("link_url"),
|
|
623
|
+
op.get("clear_link"),
|
|
624
|
+
op.get("baseline_offset"),
|
|
625
|
+
op.get("small_caps"),
|
|
626
|
+
tab_id,
|
|
627
|
+
segment_id,
|
|
628
|
+
)
|
|
629
|
+
|
|
630
|
+
if not request:
|
|
631
|
+
raise ValueError("No formatting options provided")
|
|
632
|
+
|
|
633
|
+
format_changes = []
|
|
634
|
+
for param, name in [
|
|
635
|
+
("bold", "bold"),
|
|
636
|
+
("italic", "italic"),
|
|
637
|
+
("underline", "underline"),
|
|
638
|
+
("strikethrough", "strikethrough"),
|
|
639
|
+
("font_size", "font size"),
|
|
640
|
+
("font_family", "font family"),
|
|
641
|
+
("font_weight", "font weight"),
|
|
642
|
+
("text_color", "text color"),
|
|
643
|
+
("background_color", "background color"),
|
|
644
|
+
("link_url", "link"),
|
|
645
|
+
("clear_link", "clear link"),
|
|
646
|
+
("baseline_offset", "baseline offset"),
|
|
647
|
+
("small_caps", "small caps"),
|
|
648
|
+
]:
|
|
649
|
+
if op.get(param) is not None:
|
|
650
|
+
if param == "font_size":
|
|
651
|
+
value = f"{op[param]}pt"
|
|
652
|
+
elif param == "font_weight":
|
|
653
|
+
value = f"{op[param]}w"
|
|
654
|
+
else:
|
|
655
|
+
value = op[param]
|
|
656
|
+
format_changes.append(f"{name}: {value}")
|
|
657
|
+
|
|
658
|
+
description = f"format text {op['start_index']}-{op['end_index']} ({', '.join(format_changes)})"
|
|
659
|
+
|
|
660
|
+
elif op_type == "update_paragraph_style":
|
|
661
|
+
request = create_update_paragraph_style_request(
|
|
662
|
+
op["start_index"],
|
|
663
|
+
op["end_index"],
|
|
664
|
+
op.get("heading_level"),
|
|
665
|
+
op.get("alignment"),
|
|
666
|
+
op.get("line_spacing"),
|
|
667
|
+
op.get("indent_first_line"),
|
|
668
|
+
op.get("indent_start"),
|
|
669
|
+
op.get("indent_end"),
|
|
670
|
+
op.get("space_above"),
|
|
671
|
+
op.get("space_below"),
|
|
672
|
+
tab_id,
|
|
673
|
+
op.get("named_style_type"),
|
|
674
|
+
segment_id,
|
|
675
|
+
op.get("direction"),
|
|
676
|
+
op.get("keep_lines_together"),
|
|
677
|
+
op.get("keep_with_next"),
|
|
678
|
+
op.get("avoid_widow_and_orphan"),
|
|
679
|
+
op.get("page_break_before"),
|
|
680
|
+
op.get("spacing_mode"),
|
|
681
|
+
op.get("shading_color"),
|
|
682
|
+
op.get("border_edges"),
|
|
683
|
+
op.get("border_color"),
|
|
684
|
+
op.get("border_width"),
|
|
685
|
+
op.get("border_padding"),
|
|
686
|
+
op.get("border_dash"),
|
|
687
|
+
)
|
|
688
|
+
|
|
689
|
+
if not request:
|
|
690
|
+
raise ValueError("No paragraph style options provided")
|
|
691
|
+
|
|
692
|
+
_PT_PARAMS = {
|
|
693
|
+
"indent_first_line",
|
|
694
|
+
"indent_start",
|
|
695
|
+
"indent_end",
|
|
696
|
+
"space_above",
|
|
697
|
+
"space_below",
|
|
698
|
+
"border_width",
|
|
699
|
+
"border_padding",
|
|
700
|
+
}
|
|
701
|
+
_SUFFIX = {
|
|
702
|
+
"heading_level": lambda v: f"H{v}",
|
|
703
|
+
"line_spacing": lambda v: f"{v}x",
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
style_changes = []
|
|
707
|
+
for param, name in [
|
|
708
|
+
("heading_level", "heading"),
|
|
709
|
+
("alignment", "alignment"),
|
|
710
|
+
("line_spacing", "line spacing"),
|
|
711
|
+
("indent_first_line", "first line indent"),
|
|
712
|
+
("indent_start", "start indent"),
|
|
713
|
+
("indent_end", "end indent"),
|
|
714
|
+
("space_above", "space above"),
|
|
715
|
+
("space_below", "space below"),
|
|
716
|
+
("named_style_type", "named style"),
|
|
717
|
+
("direction", "direction"),
|
|
718
|
+
("keep_lines_together", "keep lines together"),
|
|
719
|
+
("keep_with_next", "keep with next"),
|
|
720
|
+
("avoid_widow_and_orphan", "avoid widow/orphan"),
|
|
721
|
+
("page_break_before", "page break before"),
|
|
722
|
+
("spacing_mode", "spacing mode"),
|
|
723
|
+
("shading_color", "shading"),
|
|
724
|
+
("border_edges", "border edges"),
|
|
725
|
+
("border_color", "border color"),
|
|
726
|
+
("border_width", "border width"),
|
|
727
|
+
("border_padding", "border padding"),
|
|
728
|
+
("border_dash", "border dash"),
|
|
729
|
+
]:
|
|
730
|
+
if op.get(param) is not None:
|
|
731
|
+
raw = op[param]
|
|
732
|
+
fmt = _SUFFIX.get(param)
|
|
733
|
+
if fmt:
|
|
734
|
+
value = fmt(raw)
|
|
735
|
+
elif param in _PT_PARAMS:
|
|
736
|
+
value = f"{raw}pt"
|
|
737
|
+
else:
|
|
738
|
+
value = raw
|
|
739
|
+
style_changes.append(f"{name}: {value}")
|
|
740
|
+
|
|
741
|
+
description = f"paragraph style {op['start_index']}-{op['end_index']} ({', '.join(style_changes)})"
|
|
742
|
+
|
|
743
|
+
elif op_type == "update_table_cell_style":
|
|
744
|
+
is_valid, error_msg = (
|
|
745
|
+
self.validation_manager.validate_table_cell_style_params(
|
|
746
|
+
background_color=op.get("background_color"),
|
|
747
|
+
border_color=op.get("border_color"),
|
|
748
|
+
border_width=op.get("border_width"),
|
|
749
|
+
padding_top=op.get("padding_top"),
|
|
750
|
+
padding_bottom=op.get("padding_bottom"),
|
|
751
|
+
padding_left=op.get("padding_left"),
|
|
752
|
+
padding_right=op.get("padding_right"),
|
|
753
|
+
content_alignment=op.get("content_alignment"),
|
|
754
|
+
row_index=op.get("row_index"),
|
|
755
|
+
column_index=op.get("column_index"),
|
|
756
|
+
row_span=op.get("row_span"),
|
|
757
|
+
column_span=op.get("column_span"),
|
|
758
|
+
border_edges=op.get("border_edges"),
|
|
759
|
+
)
|
|
760
|
+
)
|
|
761
|
+
if not is_valid:
|
|
762
|
+
raise ValueError(error_msg)
|
|
763
|
+
|
|
764
|
+
request = create_update_table_cell_style_request(
|
|
765
|
+
table_start_index=op["table_start_index"],
|
|
766
|
+
background_color=op.get("background_color"),
|
|
767
|
+
border_color=op.get("border_color"),
|
|
768
|
+
border_width=op.get("border_width"),
|
|
769
|
+
padding_top=op.get("padding_top"),
|
|
770
|
+
padding_bottom=op.get("padding_bottom"),
|
|
771
|
+
padding_left=op.get("padding_left"),
|
|
772
|
+
padding_right=op.get("padding_right"),
|
|
773
|
+
content_alignment=op.get("content_alignment"),
|
|
774
|
+
row_index=op.get("row_index"),
|
|
775
|
+
column_index=op.get("column_index"),
|
|
776
|
+
row_span=op.get("row_span"),
|
|
777
|
+
column_span=op.get("column_span"),
|
|
778
|
+
tab_id=tab_id,
|
|
779
|
+
border_edges=op.get("border_edges"),
|
|
780
|
+
)
|
|
781
|
+
|
|
782
|
+
if not request:
|
|
783
|
+
raise ValueError("No table cell style options provided")
|
|
784
|
+
|
|
785
|
+
style_changes = []
|
|
786
|
+
for param, name in [
|
|
787
|
+
("background_color", "background"),
|
|
788
|
+
("border_color", "border color"),
|
|
789
|
+
("border_width", "border width"),
|
|
790
|
+
("padding_top", "padding top"),
|
|
791
|
+
("padding_bottom", "padding bottom"),
|
|
792
|
+
("padding_left", "padding left"),
|
|
793
|
+
("padding_right", "padding right"),
|
|
794
|
+
("content_alignment", "content alignment"),
|
|
795
|
+
("border_edges", "border edges"),
|
|
796
|
+
]:
|
|
797
|
+
if op.get(param) is not None:
|
|
798
|
+
value = (
|
|
799
|
+
f"{op[param]}pt"
|
|
800
|
+
if param
|
|
801
|
+
in (
|
|
802
|
+
"border_width",
|
|
803
|
+
"padding_top",
|
|
804
|
+
"padding_bottom",
|
|
805
|
+
"padding_left",
|
|
806
|
+
"padding_right",
|
|
807
|
+
)
|
|
808
|
+
else op[param]
|
|
809
|
+
)
|
|
810
|
+
style_changes.append(f"{name}: {value}")
|
|
811
|
+
|
|
812
|
+
if op.get("row_index") is not None:
|
|
813
|
+
row_span = op.get("row_span", 1)
|
|
814
|
+
column_span = op.get("column_span", 1)
|
|
815
|
+
target = (
|
|
816
|
+
f"row {op['row_index']}, column {op['column_index']}, "
|
|
817
|
+
f"span {row_span}x{column_span}"
|
|
818
|
+
)
|
|
819
|
+
else:
|
|
820
|
+
target = "entire table"
|
|
821
|
+
|
|
822
|
+
description = (
|
|
823
|
+
f"table cell style at {op['table_start_index']} "
|
|
824
|
+
f"({target}; {', '.join(style_changes)})"
|
|
825
|
+
)
|
|
826
|
+
|
|
827
|
+
elif op_type == "insert_table":
|
|
828
|
+
request = create_insert_table_request(
|
|
829
|
+
op.get("index"),
|
|
830
|
+
op["rows"],
|
|
831
|
+
op["columns"],
|
|
832
|
+
tab_id,
|
|
833
|
+
segment_id=segment_id,
|
|
834
|
+
end_of_segment=end_of_segment,
|
|
835
|
+
)
|
|
836
|
+
description = (
|
|
837
|
+
f"insert {op['rows']}x{op['columns']} table at end of segment '{segment_id or 'body'}'"
|
|
838
|
+
if end_of_segment
|
|
839
|
+
else f"insert {op['rows']}x{op['columns']} table at {op['index']}"
|
|
840
|
+
)
|
|
841
|
+
|
|
842
|
+
elif op_type == "insert_page_break":
|
|
843
|
+
request = create_insert_page_break_request(
|
|
844
|
+
op.get("index"), tab_id, end_of_segment=end_of_segment
|
|
845
|
+
)
|
|
846
|
+
description = (
|
|
847
|
+
"insert page break at end of body"
|
|
848
|
+
if end_of_segment
|
|
849
|
+
else f"insert page break at {op['index']}"
|
|
850
|
+
)
|
|
851
|
+
|
|
852
|
+
elif op_type == "insert_section_break":
|
|
853
|
+
request = create_insert_section_break_request(
|
|
854
|
+
op.get("index"),
|
|
855
|
+
op.get("section_type", "NEXT_PAGE"),
|
|
856
|
+
end_of_segment=end_of_segment,
|
|
857
|
+
tab_id=tab_id,
|
|
858
|
+
)
|
|
859
|
+
description = (
|
|
860
|
+
f"insert {op.get('section_type', 'NEXT_PAGE')} section break at end of body"
|
|
861
|
+
if end_of_segment
|
|
862
|
+
else f"insert {op.get('section_type', 'NEXT_PAGE')} section break at {op.get('index')}"
|
|
863
|
+
)
|
|
864
|
+
|
|
865
|
+
elif op_type == "find_replace":
|
|
866
|
+
request = create_find_replace_request(
|
|
867
|
+
op["find_text"], op["replace_text"], op.get("match_case", False), tab_id
|
|
868
|
+
)
|
|
869
|
+
description = f"find/replace '{op['find_text']}' → '{op['replace_text']}'"
|
|
870
|
+
|
|
871
|
+
elif op_type == "create_bullet_list":
|
|
872
|
+
list_type = op.get("list_type", "UNORDERED")
|
|
873
|
+
if list_type not in ("UNORDERED", "ORDERED", "CHECKBOX", "NONE"):
|
|
874
|
+
raise ValueError(
|
|
875
|
+
f"Invalid list_type '{list_type}'. Must be 'UNORDERED', 'ORDERED', 'CHECKBOX', or 'NONE'"
|
|
876
|
+
)
|
|
877
|
+
if list_type == "NONE":
|
|
878
|
+
request = create_delete_bullet_list_request(
|
|
879
|
+
op["start_index"], op["end_index"], tab_id, segment_id=segment_id
|
|
880
|
+
)
|
|
881
|
+
description = f"remove bullets {op['start_index']}-{op['end_index']}"
|
|
882
|
+
else:
|
|
883
|
+
request = create_bullet_list_request(
|
|
884
|
+
op["start_index"],
|
|
885
|
+
op["end_index"],
|
|
886
|
+
list_type,
|
|
887
|
+
op.get("nesting_level"),
|
|
888
|
+
op.get("paragraph_start_indices"),
|
|
889
|
+
tab_id,
|
|
890
|
+
op.get("bullet_preset"),
|
|
891
|
+
segment_id=segment_id,
|
|
892
|
+
)
|
|
893
|
+
if list_type == "UNORDERED":
|
|
894
|
+
style = "bulleted"
|
|
895
|
+
elif list_type == "CHECKBOX":
|
|
896
|
+
style = "checkbox"
|
|
897
|
+
else:
|
|
898
|
+
style = "numbered"
|
|
899
|
+
description = (
|
|
900
|
+
f"create {style} list {op['start_index']}-{op['end_index']}"
|
|
901
|
+
)
|
|
902
|
+
if op.get("nesting_level"):
|
|
903
|
+
description += f" (nesting level {op['nesting_level']})"
|
|
904
|
+
if op.get("bullet_preset"):
|
|
905
|
+
description += f" using {op['bullet_preset']}"
|
|
906
|
+
|
|
907
|
+
elif op_type == "create_named_range":
|
|
908
|
+
request = create_named_range_request(
|
|
909
|
+
op["name"],
|
|
910
|
+
op["start_index"],
|
|
911
|
+
op["end_index"],
|
|
912
|
+
tab_id=tab_id,
|
|
913
|
+
segment_id=segment_id,
|
|
914
|
+
)
|
|
915
|
+
description = (
|
|
916
|
+
f"create named range '{op['name']}' "
|
|
917
|
+
f"{op['start_index']}-{op['end_index']}"
|
|
918
|
+
)
|
|
919
|
+
|
|
920
|
+
elif op_type == "replace_named_range_content":
|
|
921
|
+
request = create_replace_named_range_content_request(
|
|
922
|
+
op["text"],
|
|
923
|
+
named_range_id=op.get("named_range_id"),
|
|
924
|
+
named_range_name=op.get("named_range_name"),
|
|
925
|
+
tab_id=tab_id,
|
|
926
|
+
)
|
|
927
|
+
target = op.get("named_range_id") or op.get("named_range_name")
|
|
928
|
+
description = f"replace named range content for '{target}'"
|
|
929
|
+
|
|
930
|
+
elif op_type == "delete_named_range":
|
|
931
|
+
request = create_delete_named_range_request(
|
|
932
|
+
named_range_id=op.get("named_range_id"),
|
|
933
|
+
named_range_name=op.get("named_range_name"),
|
|
934
|
+
tab_id=tab_id,
|
|
935
|
+
)
|
|
936
|
+
target = op.get("named_range_id") or op.get("named_range_name")
|
|
937
|
+
description = f"delete named range '{target}'"
|
|
938
|
+
|
|
939
|
+
elif op_type == "update_document_style":
|
|
940
|
+
request = create_update_document_style_request(
|
|
941
|
+
tab_id=tab_id,
|
|
942
|
+
background_color=op.get("background_color"),
|
|
943
|
+
margin_top=op.get("margin_top"),
|
|
944
|
+
margin_bottom=op.get("margin_bottom"),
|
|
945
|
+
margin_left=op.get("margin_left"),
|
|
946
|
+
margin_right=op.get("margin_right"),
|
|
947
|
+
margin_header=op.get("margin_header"),
|
|
948
|
+
margin_footer=op.get("margin_footer"),
|
|
949
|
+
page_width=op.get("page_width"),
|
|
950
|
+
page_height=op.get("page_height"),
|
|
951
|
+
page_number_start=op.get("page_number_start"),
|
|
952
|
+
use_even_page_header_footer=op.get("use_even_page_header_footer"),
|
|
953
|
+
use_first_page_header_footer=op.get("use_first_page_header_footer"),
|
|
954
|
+
flip_page_orientation=op.get("flip_page_orientation"),
|
|
955
|
+
document_mode=op.get("document_mode"),
|
|
956
|
+
)
|
|
957
|
+
if not request:
|
|
958
|
+
raise ValueError("No document style options provided")
|
|
959
|
+
description = "update document style"
|
|
960
|
+
|
|
961
|
+
elif op_type == "update_section_style":
|
|
962
|
+
request = create_update_section_style_request(
|
|
963
|
+
op["start_index"],
|
|
964
|
+
op["end_index"],
|
|
965
|
+
margin_top=op.get("margin_top"),
|
|
966
|
+
margin_bottom=op.get("margin_bottom"),
|
|
967
|
+
margin_left=op.get("margin_left"),
|
|
968
|
+
margin_right=op.get("margin_right"),
|
|
969
|
+
margin_header=op.get("margin_header"),
|
|
970
|
+
margin_footer=op.get("margin_footer"),
|
|
971
|
+
page_number_start=op.get("page_number_start"),
|
|
972
|
+
use_first_page_header_footer=op.get("use_first_page_header_footer"),
|
|
973
|
+
flip_page_orientation=op.get("flip_page_orientation"),
|
|
974
|
+
content_direction=op.get("content_direction"),
|
|
975
|
+
column_count=op.get("column_count"),
|
|
976
|
+
column_spacing=op.get("column_spacing"),
|
|
977
|
+
column_separator_style=op.get("column_separator_style"),
|
|
978
|
+
)
|
|
979
|
+
if not request:
|
|
980
|
+
raise ValueError("No section style options provided")
|
|
981
|
+
description = f"update section style {op['start_index']}-{op['end_index']}"
|
|
982
|
+
|
|
983
|
+
elif op_type == "create_header_footer":
|
|
984
|
+
request = create_create_header_footer_request(
|
|
985
|
+
op["section_type"],
|
|
986
|
+
op.get("header_footer_type", "DEFAULT"),
|
|
987
|
+
op.get("section_break_index"),
|
|
988
|
+
)
|
|
989
|
+
description = f"create {op['section_type']} ({op.get('header_footer_type', 'DEFAULT')})"
|
|
990
|
+
|
|
991
|
+
elif op_type == "insert_image":
|
|
992
|
+
request = create_insert_image_request(
|
|
993
|
+
op.get("index"),
|
|
994
|
+
op["image_uri"],
|
|
995
|
+
op.get("width"),
|
|
996
|
+
op.get("height"),
|
|
997
|
+
tab_id,
|
|
998
|
+
segment_id=segment_id,
|
|
999
|
+
end_of_segment=end_of_segment,
|
|
1000
|
+
)
|
|
1001
|
+
description = (
|
|
1002
|
+
f"insert image at end of segment '{segment_id or 'body'}'"
|
|
1003
|
+
if end_of_segment
|
|
1004
|
+
else f"insert image at {op.get('index')}"
|
|
1005
|
+
)
|
|
1006
|
+
|
|
1007
|
+
elif op_type == "insert_person":
|
|
1008
|
+
request = create_insert_person_request(
|
|
1009
|
+
op.get("index"),
|
|
1010
|
+
op["email"],
|
|
1011
|
+
tab_id,
|
|
1012
|
+
segment_id=segment_id,
|
|
1013
|
+
end_of_segment=end_of_segment,
|
|
1014
|
+
)
|
|
1015
|
+
description = (
|
|
1016
|
+
f"mention {op['email']} at end of segment '{segment_id or 'body'}'"
|
|
1017
|
+
if end_of_segment
|
|
1018
|
+
else f"mention {op['email']} at {op.get('index')}"
|
|
1019
|
+
)
|
|
1020
|
+
|
|
1021
|
+
elif op_type == "create_dropdown_definition":
|
|
1022
|
+
request = create_dropdown_definition_request(
|
|
1023
|
+
op["title"], op["options"], op.get("dropdown_definition_id"), tab_id
|
|
1024
|
+
)
|
|
1025
|
+
description = f"create dropdown definition '{op['title']}'"
|
|
1026
|
+
|
|
1027
|
+
elif op_type == "insert_dropdown":
|
|
1028
|
+
request = create_insert_dropdown_request(
|
|
1029
|
+
op.get("index"),
|
|
1030
|
+
op["dropdown_definition_id"],
|
|
1031
|
+
op.get("selected_option_id"),
|
|
1032
|
+
tab_id,
|
|
1033
|
+
segment_id=segment_id,
|
|
1034
|
+
end_of_segment=end_of_segment,
|
|
1035
|
+
)
|
|
1036
|
+
description = f"insert dropdown '{op['dropdown_definition_id']}'"
|
|
1037
|
+
|
|
1038
|
+
elif op_type == "insert_date":
|
|
1039
|
+
request = create_insert_date_request(
|
|
1040
|
+
op.get("index"),
|
|
1041
|
+
op["date"],
|
|
1042
|
+
op.get("date_format"),
|
|
1043
|
+
op.get("time_format"),
|
|
1044
|
+
op.get("timezone"),
|
|
1045
|
+
tab_id,
|
|
1046
|
+
segment_id=segment_id,
|
|
1047
|
+
end_of_segment=end_of_segment,
|
|
1048
|
+
)
|
|
1049
|
+
description = (
|
|
1050
|
+
f"date chip {op['date']} at end of segment '{segment_id or 'body'}'"
|
|
1051
|
+
if end_of_segment
|
|
1052
|
+
else f"date chip {op['date']} at {op.get('index')}"
|
|
1053
|
+
)
|
|
1054
|
+
|
|
1055
|
+
elif op_type == "insert_doc_tab":
|
|
1056
|
+
request = create_insert_doc_tab_request(
|
|
1057
|
+
op["title"], op["index"], op.get("parent_tab_id")
|
|
1058
|
+
)
|
|
1059
|
+
description = f"insert tab '{op['title']}' at {op['index']}"
|
|
1060
|
+
if op.get("parent_tab_id"):
|
|
1061
|
+
description += f" under parent tab {op['parent_tab_id']}"
|
|
1062
|
+
|
|
1063
|
+
elif op_type == "delete_doc_tab":
|
|
1064
|
+
request = create_delete_doc_tab_request(op["tab_id"])
|
|
1065
|
+
description = f"delete tab '{op['tab_id']}'"
|
|
1066
|
+
|
|
1067
|
+
elif op_type == "update_doc_tab":
|
|
1068
|
+
request = create_update_doc_tab_request(op["tab_id"], op["title"])
|
|
1069
|
+
description = f"rename tab '{op['tab_id']}' to '{op['title']}'"
|
|
1070
|
+
|
|
1071
|
+
elif op_type == "insert_table_row":
|
|
1072
|
+
request = create_insert_table_row_request(
|
|
1073
|
+
table_start_index=op["table_start_index"],
|
|
1074
|
+
row_index=op["row_index"],
|
|
1075
|
+
insert_below=op.get("insert_below", True),
|
|
1076
|
+
tab_id=tab_id,
|
|
1077
|
+
)
|
|
1078
|
+
direction = "below" if op.get("insert_below", True) else "above"
|
|
1079
|
+
description = f"insert row {direction} row {op['row_index']} in table at {op['table_start_index']}"
|
|
1080
|
+
|
|
1081
|
+
elif op_type == "delete_table_row":
|
|
1082
|
+
request = create_delete_table_row_request(
|
|
1083
|
+
table_start_index=op["table_start_index"],
|
|
1084
|
+
row_index=op["row_index"],
|
|
1085
|
+
tab_id=tab_id,
|
|
1086
|
+
)
|
|
1087
|
+
description = (
|
|
1088
|
+
f"delete row {op['row_index']} from table at {op['table_start_index']}"
|
|
1089
|
+
)
|
|
1090
|
+
|
|
1091
|
+
elif op_type == "insert_table_column":
|
|
1092
|
+
request = create_insert_table_column_request(
|
|
1093
|
+
table_start_index=op["table_start_index"],
|
|
1094
|
+
column_index=op["column_index"],
|
|
1095
|
+
insert_right=op.get("insert_right", True),
|
|
1096
|
+
tab_id=tab_id,
|
|
1097
|
+
)
|
|
1098
|
+
direction = "right of" if op.get("insert_right", True) else "left of"
|
|
1099
|
+
description = f"insert column {direction} column {op['column_index']} in table at {op['table_start_index']}"
|
|
1100
|
+
|
|
1101
|
+
elif op_type == "delete_table_column":
|
|
1102
|
+
request = create_delete_table_column_request(
|
|
1103
|
+
table_start_index=op["table_start_index"],
|
|
1104
|
+
column_index=op["column_index"],
|
|
1105
|
+
tab_id=tab_id,
|
|
1106
|
+
)
|
|
1107
|
+
description = f"delete column {op['column_index']} from table at {op['table_start_index']}"
|
|
1108
|
+
|
|
1109
|
+
elif op_type == "merge_table_cells":
|
|
1110
|
+
request = create_merge_table_cells_request(
|
|
1111
|
+
table_start_index=op["table_start_index"],
|
|
1112
|
+
row_index=op["row_index"],
|
|
1113
|
+
column_index=op["column_index"],
|
|
1114
|
+
row_span=op["row_span"],
|
|
1115
|
+
column_span=op["column_span"],
|
|
1116
|
+
tab_id=tab_id,
|
|
1117
|
+
)
|
|
1118
|
+
description = (
|
|
1119
|
+
f"merge cells at ({op['row_index']},{op['column_index']}) "
|
|
1120
|
+
f"span {op['row_span']}x{op['column_span']} in table at {op['table_start_index']}"
|
|
1121
|
+
)
|
|
1122
|
+
|
|
1123
|
+
elif op_type == "unmerge_table_cells":
|
|
1124
|
+
request = create_unmerge_table_cells_request(
|
|
1125
|
+
table_start_index=op["table_start_index"],
|
|
1126
|
+
row_index=op["row_index"],
|
|
1127
|
+
column_index=op["column_index"],
|
|
1128
|
+
row_span=op["row_span"],
|
|
1129
|
+
column_span=op["column_span"],
|
|
1130
|
+
tab_id=tab_id,
|
|
1131
|
+
)
|
|
1132
|
+
description = (
|
|
1133
|
+
f"unmerge cells at ({op['row_index']},{op['column_index']}) "
|
|
1134
|
+
f"span {op['row_span']}x{op['column_span']} in table at {op['table_start_index']}"
|
|
1135
|
+
)
|
|
1136
|
+
|
|
1137
|
+
elif op_type == "update_table_column_properties":
|
|
1138
|
+
request = create_update_table_column_properties_request(
|
|
1139
|
+
table_start_index=op["table_start_index"],
|
|
1140
|
+
column_indices=op["column_indices"],
|
|
1141
|
+
width=op.get("width"),
|
|
1142
|
+
width_type=op.get("width_type"),
|
|
1143
|
+
tab_id=tab_id,
|
|
1144
|
+
)
|
|
1145
|
+
|
|
1146
|
+
if not request:
|
|
1147
|
+
raise ValueError(
|
|
1148
|
+
"update_table_column_properties requires at least one of: width, width_type"
|
|
1149
|
+
)
|
|
1150
|
+
|
|
1151
|
+
description = (
|
|
1152
|
+
f"update column properties for columns {op['column_indices']} "
|
|
1153
|
+
f"in table at {op['table_start_index']}"
|
|
1154
|
+
)
|
|
1155
|
+
|
|
1156
|
+
elif op_type == "update_table_row_style":
|
|
1157
|
+
request = create_update_table_row_style_request(
|
|
1158
|
+
table_start_index=op["table_start_index"],
|
|
1159
|
+
row_indices=op["row_indices"],
|
|
1160
|
+
min_row_height=op.get("min_row_height"),
|
|
1161
|
+
tab_id=tab_id,
|
|
1162
|
+
)
|
|
1163
|
+
|
|
1164
|
+
if not request:
|
|
1165
|
+
raise ValueError(
|
|
1166
|
+
"update_table_row_style requires at least one of: min_row_height"
|
|
1167
|
+
)
|
|
1168
|
+
|
|
1169
|
+
description = (
|
|
1170
|
+
f"update row style for rows {op['row_indices']} "
|
|
1171
|
+
f"in table at {op['table_start_index']}"
|
|
1172
|
+
)
|
|
1173
|
+
|
|
1174
|
+
elif op_type == "pin_table_header_rows":
|
|
1175
|
+
request = create_pin_table_header_rows_request(
|
|
1176
|
+
table_start_index=op["table_start_index"],
|
|
1177
|
+
pinned_header_rows_count=op["pinned_header_rows_count"],
|
|
1178
|
+
tab_id=tab_id,
|
|
1179
|
+
)
|
|
1180
|
+
|
|
1181
|
+
description = (
|
|
1182
|
+
f"pin {op['pinned_header_rows_count']} header row(s) "
|
|
1183
|
+
f"for table at {op['table_start_index']}"
|
|
1184
|
+
)
|
|
1185
|
+
|
|
1186
|
+
else:
|
|
1187
|
+
supported_types = [
|
|
1188
|
+
"create_dropdown_definition",
|
|
1189
|
+
"insert_text",
|
|
1190
|
+
"delete_text",
|
|
1191
|
+
"replace_text",
|
|
1192
|
+
"format_text",
|
|
1193
|
+
"update_paragraph_style",
|
|
1194
|
+
"update_table_cell_style",
|
|
1195
|
+
"insert_table",
|
|
1196
|
+
"insert_page_break",
|
|
1197
|
+
"insert_section_break",
|
|
1198
|
+
"find_replace",
|
|
1199
|
+
"create_bullet_list",
|
|
1200
|
+
"create_named_range",
|
|
1201
|
+
"replace_named_range_content",
|
|
1202
|
+
"delete_named_range",
|
|
1203
|
+
"update_document_style",
|
|
1204
|
+
"update_section_style",
|
|
1205
|
+
"create_header_footer",
|
|
1206
|
+
"insert_image",
|
|
1207
|
+
"insert_person",
|
|
1208
|
+
"insert_date",
|
|
1209
|
+
"insert_dropdown",
|
|
1210
|
+
"insert_doc_tab",
|
|
1211
|
+
"delete_doc_tab",
|
|
1212
|
+
"update_doc_tab",
|
|
1213
|
+
"insert_table_row",
|
|
1214
|
+
"delete_table_row",
|
|
1215
|
+
"insert_table_column",
|
|
1216
|
+
"delete_table_column",
|
|
1217
|
+
"merge_table_cells",
|
|
1218
|
+
"unmerge_table_cells",
|
|
1219
|
+
"update_table_column_properties",
|
|
1220
|
+
"update_table_row_style",
|
|
1221
|
+
"pin_table_header_rows",
|
|
1222
|
+
]
|
|
1223
|
+
raise ValueError(
|
|
1224
|
+
f"Unsupported operation type '{op_type}'. Supported: {', '.join(supported_types)}"
|
|
1225
|
+
)
|
|
1226
|
+
|
|
1227
|
+
return request, description
|
|
1228
|
+
|
|
1229
|
+
async def _execute_batch_requests(
|
|
1230
|
+
self,
|
|
1231
|
+
document_id: str,
|
|
1232
|
+
requests: list[dict[str, Any]],
|
|
1233
|
+
write_mode: str = "EDIT",
|
|
1234
|
+
) -> dict[str, Any]:
|
|
1235
|
+
"""
|
|
1236
|
+
Execute the batch requests against the Google Docs API.
|
|
1237
|
+
|
|
1238
|
+
Args:
|
|
1239
|
+
document_id: Document ID
|
|
1240
|
+
requests: List of API requests
|
|
1241
|
+
write_mode: "EDIT" or "SUGGEST"
|
|
1242
|
+
|
|
1243
|
+
Returns:
|
|
1244
|
+
API response
|
|
1245
|
+
"""
|
|
1246
|
+
return await asyncio.to_thread(
|
|
1247
|
+
self.service.documents()
|
|
1248
|
+
.batchUpdate(
|
|
1249
|
+
documentId=document_id,
|
|
1250
|
+
body=build_batch_update_body(requests, write_mode),
|
|
1251
|
+
)
|
|
1252
|
+
.execute
|
|
1253
|
+
)
|
|
1254
|
+
|
|
1255
|
+
def _extract_created_tabs(self, result: dict[str, Any]) -> list[dict[str, str]]:
|
|
1256
|
+
"""
|
|
1257
|
+
Extract tab IDs from insert_doc_tab replies in the batchUpdate response.
|
|
1258
|
+
|
|
1259
|
+
Args:
|
|
1260
|
+
result: The batchUpdate API response
|
|
1261
|
+
|
|
1262
|
+
Returns:
|
|
1263
|
+
List of dicts with tab_id and title for each created tab
|
|
1264
|
+
"""
|
|
1265
|
+
created_tabs = []
|
|
1266
|
+
for reply in result.get("replies", []):
|
|
1267
|
+
# Google's Docs API returns the result under "addDocumentTab"
|
|
1268
|
+
# matching the request field name. Accept "createDocumentTab" too
|
|
1269
|
+
# in case the API surfaces that key in some legacy or future branch.
|
|
1270
|
+
for key in ("addDocumentTab", "createDocumentTab"):
|
|
1271
|
+
if key in reply:
|
|
1272
|
+
props = reply[key].get("tabProperties", {})
|
|
1273
|
+
tab_id = props.get("tabId")
|
|
1274
|
+
title = props.get("title", "")
|
|
1275
|
+
if tab_id:
|
|
1276
|
+
created_tabs.append({"tab_id": tab_id, "title": title})
|
|
1277
|
+
break
|
|
1278
|
+
return created_tabs
|
|
1279
|
+
|
|
1280
|
+
@staticmethod
|
|
1281
|
+
def _extract_dropdown_results(
|
|
1282
|
+
requests: list[dict[str, Any]], result: dict[str, Any]
|
|
1283
|
+
) -> list[dict[str, Any]]:
|
|
1284
|
+
"""IDs of each created dropdown definition and inserted chip, in request order."""
|
|
1285
|
+
results = []
|
|
1286
|
+
for request, reply in zip(requests, result.get("replies", [])):
|
|
1287
|
+
if "createDropdownDefinition" in reply:
|
|
1288
|
+
definition = reply["createDropdownDefinition"].get(
|
|
1289
|
+
"dropdownDefinition", {}
|
|
1290
|
+
)
|
|
1291
|
+
options = definition.get("dropdownDefinitionProperties", {}).get(
|
|
1292
|
+
"options", []
|
|
1293
|
+
)
|
|
1294
|
+
results.append(
|
|
1295
|
+
{
|
|
1296
|
+
"title": request["createDropdownDefinition"][
|
|
1297
|
+
"dropdownDefinition"
|
|
1298
|
+
]["dropdownDefinitionProperties"]["title"],
|
|
1299
|
+
"dropdown_definition_id": definition.get(
|
|
1300
|
+
"dropdownDefinitionId"
|
|
1301
|
+
),
|
|
1302
|
+
"tab_id": request["createDropdownDefinition"].get("tabId"),
|
|
1303
|
+
"options": [
|
|
1304
|
+
{
|
|
1305
|
+
"option_id": option.get("optionId"),
|
|
1306
|
+
"display_value": option.get("displayValue"),
|
|
1307
|
+
}
|
|
1308
|
+
for option in options
|
|
1309
|
+
],
|
|
1310
|
+
}
|
|
1311
|
+
)
|
|
1312
|
+
elif "insertDropdown" in reply:
|
|
1313
|
+
payload = request["insertDropdown"]
|
|
1314
|
+
location = payload.get(
|
|
1315
|
+
"location", payload.get("endOfSegmentLocation", {})
|
|
1316
|
+
)
|
|
1317
|
+
chip = reply["insertDropdown"].get("dropdown", {})
|
|
1318
|
+
results.append(
|
|
1319
|
+
{
|
|
1320
|
+
"dropdown_id": chip.get("dropdownId"),
|
|
1321
|
+
"dropdown_definition_id": payload["dropdownDefinitionId"],
|
|
1322
|
+
"selected_option_id": chip.get("dropdownProperties", {}).get(
|
|
1323
|
+
"selectedOptionId"
|
|
1324
|
+
),
|
|
1325
|
+
"tab_id": location.get("tabId"),
|
|
1326
|
+
}
|
|
1327
|
+
)
|
|
1328
|
+
return results
|
|
1329
|
+
|
|
1330
|
+
def _build_operation_summary(self, operation_descriptions: list[str]) -> str:
|
|
1331
|
+
"""
|
|
1332
|
+
Build a concise summary of operations performed.
|
|
1333
|
+
|
|
1334
|
+
Args:
|
|
1335
|
+
operation_descriptions: List of operation descriptions
|
|
1336
|
+
|
|
1337
|
+
Returns:
|
|
1338
|
+
Summary string
|
|
1339
|
+
"""
|
|
1340
|
+
if not operation_descriptions:
|
|
1341
|
+
return "no operations"
|
|
1342
|
+
|
|
1343
|
+
summary_items = operation_descriptions[:3] # Show first 3 operations
|
|
1344
|
+
summary = ", ".join(summary_items)
|
|
1345
|
+
|
|
1346
|
+
if len(operation_descriptions) > 3:
|
|
1347
|
+
remaining = len(operation_descriptions) - 3
|
|
1348
|
+
summary += f" and {remaining} more operation{'s' if remaining > 1 else ''}"
|
|
1349
|
+
|
|
1350
|
+
return summary
|
|
1351
|
+
|
|
1352
|
+
def _rewrite_execution_error(
|
|
1353
|
+
self, error_msg: str, operations: list[dict[str, Any]]
|
|
1354
|
+
) -> str:
|
|
1355
|
+
"""
|
|
1356
|
+
Rewrite common API failures into actionable guidance for tool callers.
|
|
1357
|
+
"""
|
|
1358
|
+
lowered = error_msg.lower()
|
|
1359
|
+
requested_header_footer_creation = any(
|
|
1360
|
+
op.get("type") == "create_header_footer" for op in operations
|
|
1361
|
+
)
|
|
1362
|
+
|
|
1363
|
+
if (
|
|
1364
|
+
requested_header_footer_creation
|
|
1365
|
+
and "already exists" in lowered
|
|
1366
|
+
and ("createheader" in lowered or "createfooter" in lowered)
|
|
1367
|
+
):
|
|
1368
|
+
return (
|
|
1369
|
+
"Batch operation failed: the requested header/footer already exists. "
|
|
1370
|
+
"For normal header or footer text, use update_doc_headers_footers "
|
|
1371
|
+
"instead of batch_update_doc with create_header_footer. "
|
|
1372
|
+
"Reserve create_header_footer for advanced section-break layouts."
|
|
1373
|
+
)
|
|
1374
|
+
|
|
1375
|
+
return f"Batch operation failed: {error_msg}"
|
|
1376
|
+
|
|
1377
|
+
def get_supported_operations(self) -> dict[str, Any]:
|
|
1378
|
+
"""
|
|
1379
|
+
Get information about supported batch operations.
|
|
1380
|
+
|
|
1381
|
+
Returns:
|
|
1382
|
+
Dictionary with supported operation types and their required parameters
|
|
1383
|
+
"""
|
|
1384
|
+
return {
|
|
1385
|
+
"supported_operations": {
|
|
1386
|
+
"insert_text": {
|
|
1387
|
+
"required": ["index", "text"],
|
|
1388
|
+
"description": "Insert text at specified index",
|
|
1389
|
+
},
|
|
1390
|
+
"delete_text": {
|
|
1391
|
+
"required": ["start_index", "end_index"],
|
|
1392
|
+
"description": "Delete text in specified range",
|
|
1393
|
+
},
|
|
1394
|
+
"replace_text": {
|
|
1395
|
+
"required": ["start_index", "end_index", "text"],
|
|
1396
|
+
"description": "Replace text in range with new text",
|
|
1397
|
+
},
|
|
1398
|
+
"format_text": {
|
|
1399
|
+
"required": ["start_index", "end_index"],
|
|
1400
|
+
"optional": [
|
|
1401
|
+
"bold",
|
|
1402
|
+
"italic",
|
|
1403
|
+
"underline",
|
|
1404
|
+
"strikethrough",
|
|
1405
|
+
"font_size",
|
|
1406
|
+
"font_family",
|
|
1407
|
+
"font_weight",
|
|
1408
|
+
"text_color",
|
|
1409
|
+
"background_color",
|
|
1410
|
+
"link_url",
|
|
1411
|
+
"clear_link",
|
|
1412
|
+
"baseline_offset",
|
|
1413
|
+
"small_caps",
|
|
1414
|
+
"segment_id",
|
|
1415
|
+
"tab_id",
|
|
1416
|
+
],
|
|
1417
|
+
"description": "Apply formatting to text range",
|
|
1418
|
+
},
|
|
1419
|
+
"update_paragraph_style": {
|
|
1420
|
+
"required": ["start_index", "end_index"],
|
|
1421
|
+
"optional": [
|
|
1422
|
+
"heading_level",
|
|
1423
|
+
"alignment",
|
|
1424
|
+
"line_spacing",
|
|
1425
|
+
"indent_first_line",
|
|
1426
|
+
"indent_start",
|
|
1427
|
+
"indent_end",
|
|
1428
|
+
"space_above",
|
|
1429
|
+
"space_below",
|
|
1430
|
+
"named_style_type",
|
|
1431
|
+
"direction",
|
|
1432
|
+
"keep_lines_together",
|
|
1433
|
+
"keep_with_next",
|
|
1434
|
+
"avoid_widow_and_orphan",
|
|
1435
|
+
"page_break_before",
|
|
1436
|
+
"spacing_mode",
|
|
1437
|
+
"shading_color",
|
|
1438
|
+
"border_edges",
|
|
1439
|
+
"border_color",
|
|
1440
|
+
"border_width",
|
|
1441
|
+
"border_padding",
|
|
1442
|
+
"border_dash",
|
|
1443
|
+
"segment_id",
|
|
1444
|
+
"tab_id",
|
|
1445
|
+
],
|
|
1446
|
+
"description": "Apply paragraph-level styling (headings, named styles like TITLE/SUBTITLE, alignment, spacing, indentation)",
|
|
1447
|
+
},
|
|
1448
|
+
"update_table_cell_style": {
|
|
1449
|
+
"required": ["table_start_index"],
|
|
1450
|
+
"optional": [
|
|
1451
|
+
"background_color",
|
|
1452
|
+
"border_color",
|
|
1453
|
+
"border_width",
|
|
1454
|
+
"padding_top",
|
|
1455
|
+
"padding_bottom",
|
|
1456
|
+
"padding_left",
|
|
1457
|
+
"padding_right",
|
|
1458
|
+
"content_alignment",
|
|
1459
|
+
"row_index",
|
|
1460
|
+
"column_index",
|
|
1461
|
+
"row_span",
|
|
1462
|
+
"column_span",
|
|
1463
|
+
"border_edges",
|
|
1464
|
+
],
|
|
1465
|
+
"description": "Apply table cell styling to an entire table or a targeted cell range",
|
|
1466
|
+
},
|
|
1467
|
+
"insert_table": {
|
|
1468
|
+
"required": ["rows", "columns"],
|
|
1469
|
+
"optional": ["index", "end_of_segment", "segment_id", "tab_id"],
|
|
1470
|
+
"description": "Insert table at specified index or end of a segment",
|
|
1471
|
+
},
|
|
1472
|
+
"insert_page_break": {
|
|
1473
|
+
"required": [],
|
|
1474
|
+
"optional": ["index", "end_of_segment", "tab_id"],
|
|
1475
|
+
"description": "Insert page break at specified index or end of body",
|
|
1476
|
+
},
|
|
1477
|
+
"insert_section_break": {
|
|
1478
|
+
"required": [],
|
|
1479
|
+
"optional": ["index", "end_of_segment", "section_type"],
|
|
1480
|
+
"description": "Insert a CONTINUOUS or NEXT_PAGE section break",
|
|
1481
|
+
},
|
|
1482
|
+
"find_replace": {
|
|
1483
|
+
"required": ["find_text", "replace_text"],
|
|
1484
|
+
"optional": ["match_case"],
|
|
1485
|
+
"description": "Find and replace text throughout document",
|
|
1486
|
+
},
|
|
1487
|
+
"create_bullet_list": {
|
|
1488
|
+
"required": ["start_index", "end_index"],
|
|
1489
|
+
"optional": [
|
|
1490
|
+
"list_type",
|
|
1491
|
+
"nesting_level",
|
|
1492
|
+
"paragraph_start_indices",
|
|
1493
|
+
"bullet_preset",
|
|
1494
|
+
],
|
|
1495
|
+
"description": "Apply or remove native bullet/numbered/checklist formatting (list_type: UNORDERED, ORDERED, CHECKBOX, or NONE to remove; nesting_level: 0-8)",
|
|
1496
|
+
},
|
|
1497
|
+
"create_named_range": {
|
|
1498
|
+
"required": ["name", "start_index", "end_index"],
|
|
1499
|
+
"optional": ["tab_id", "segment_id"],
|
|
1500
|
+
"description": "Create a named range anchor over a range",
|
|
1501
|
+
},
|
|
1502
|
+
"replace_named_range_content": {
|
|
1503
|
+
"required": ["text"],
|
|
1504
|
+
"optional": ["named_range_id", "named_range_name", "tab_id"],
|
|
1505
|
+
"description": "Replace the content of one or more named ranges",
|
|
1506
|
+
},
|
|
1507
|
+
"delete_named_range": {
|
|
1508
|
+
"required": [],
|
|
1509
|
+
"optional": ["named_range_id", "named_range_name", "tab_id"],
|
|
1510
|
+
"description": "Delete a named range by ID or name",
|
|
1511
|
+
},
|
|
1512
|
+
"update_document_style": {
|
|
1513
|
+
"required": [],
|
|
1514
|
+
"optional": [
|
|
1515
|
+
"background_color",
|
|
1516
|
+
"margin_top",
|
|
1517
|
+
"margin_bottom",
|
|
1518
|
+
"margin_left",
|
|
1519
|
+
"margin_right",
|
|
1520
|
+
"margin_header",
|
|
1521
|
+
"margin_footer",
|
|
1522
|
+
"page_width",
|
|
1523
|
+
"page_height",
|
|
1524
|
+
"page_number_start",
|
|
1525
|
+
"use_even_page_header_footer",
|
|
1526
|
+
"use_first_page_header_footer",
|
|
1527
|
+
"flip_page_orientation",
|
|
1528
|
+
"document_mode",
|
|
1529
|
+
"tab_id",
|
|
1530
|
+
],
|
|
1531
|
+
"description": "Update document-level layout settings such as margins, page size, headers/footers, and background",
|
|
1532
|
+
},
|
|
1533
|
+
"update_section_style": {
|
|
1534
|
+
"required": ["start_index", "end_index"],
|
|
1535
|
+
"optional": [
|
|
1536
|
+
"margin_top",
|
|
1537
|
+
"margin_bottom",
|
|
1538
|
+
"margin_left",
|
|
1539
|
+
"margin_right",
|
|
1540
|
+
"margin_header",
|
|
1541
|
+
"margin_footer",
|
|
1542
|
+
"page_number_start",
|
|
1543
|
+
"use_first_page_header_footer",
|
|
1544
|
+
"flip_page_orientation",
|
|
1545
|
+
"content_direction",
|
|
1546
|
+
"column_count",
|
|
1547
|
+
"column_spacing",
|
|
1548
|
+
"column_separator_style",
|
|
1549
|
+
],
|
|
1550
|
+
"description": "Update section-specific layout such as margins, pagination, orientation, and columns",
|
|
1551
|
+
},
|
|
1552
|
+
"create_header_footer": {
|
|
1553
|
+
"required": ["section_type"],
|
|
1554
|
+
"optional": ["header_footer_type", "section_break_index"],
|
|
1555
|
+
"description": "Create a header or footer, optionally tied to a section break",
|
|
1556
|
+
},
|
|
1557
|
+
"insert_image": {
|
|
1558
|
+
"required": ["image_uri"],
|
|
1559
|
+
"optional": [
|
|
1560
|
+
"index",
|
|
1561
|
+
"end_of_segment",
|
|
1562
|
+
"segment_id",
|
|
1563
|
+
"tab_id",
|
|
1564
|
+
"width",
|
|
1565
|
+
"height",
|
|
1566
|
+
],
|
|
1567
|
+
"description": "Insert an inline image at a location or at the end of a segment",
|
|
1568
|
+
},
|
|
1569
|
+
"insert_person": {
|
|
1570
|
+
"required": ["email"],
|
|
1571
|
+
"optional": ["index", "end_of_segment", "segment_id", "tab_id"],
|
|
1572
|
+
"description": "Insert a person @mention smart chip",
|
|
1573
|
+
},
|
|
1574
|
+
"create_dropdown_definition": {
|
|
1575
|
+
"required": ["title", "options"],
|
|
1576
|
+
"optional": ["dropdown_definition_id", "tab_id"],
|
|
1577
|
+
"description": "Create a reusable native dropdown definition in a tab",
|
|
1578
|
+
},
|
|
1579
|
+
"insert_dropdown": {
|
|
1580
|
+
"required": ["dropdown_definition_id"],
|
|
1581
|
+
"optional": [
|
|
1582
|
+
"selected_option_id",
|
|
1583
|
+
"index",
|
|
1584
|
+
"end_of_segment",
|
|
1585
|
+
"segment_id",
|
|
1586
|
+
"tab_id",
|
|
1587
|
+
"after_heading",
|
|
1588
|
+
"before_heading",
|
|
1589
|
+
"anchor_text",
|
|
1590
|
+
"anchor_position",
|
|
1591
|
+
],
|
|
1592
|
+
"description": "Insert a native dropdown chip using an existing definition",
|
|
1593
|
+
},
|
|
1594
|
+
"insert_date": {
|
|
1595
|
+
"required": ["date"],
|
|
1596
|
+
"optional": [
|
|
1597
|
+
"index",
|
|
1598
|
+
"end_of_segment",
|
|
1599
|
+
"segment_id",
|
|
1600
|
+
"tab_id",
|
|
1601
|
+
"date_format",
|
|
1602
|
+
"time_format",
|
|
1603
|
+
"timezone",
|
|
1604
|
+
],
|
|
1605
|
+
"description": "Insert a date smart chip",
|
|
1606
|
+
},
|
|
1607
|
+
"insert_doc_tab": {
|
|
1608
|
+
"required": ["title", "index"],
|
|
1609
|
+
"description": "Insert a new document tab with given title at specified index",
|
|
1610
|
+
},
|
|
1611
|
+
"delete_doc_tab": {
|
|
1612
|
+
"required": ["tab_id"],
|
|
1613
|
+
"description": "Delete a document tab by its ID",
|
|
1614
|
+
},
|
|
1615
|
+
"update_doc_tab": {
|
|
1616
|
+
"required": ["tab_id", "title"],
|
|
1617
|
+
"description": "Rename a document tab",
|
|
1618
|
+
},
|
|
1619
|
+
"insert_table_row": {
|
|
1620
|
+
"required": ["table_start_index", "row_index"],
|
|
1621
|
+
"optional": ["insert_below", "tab_id"],
|
|
1622
|
+
"description": "Insert a row above or below a reference row in a table",
|
|
1623
|
+
},
|
|
1624
|
+
"delete_table_row": {
|
|
1625
|
+
"required": ["table_start_index", "row_index"],
|
|
1626
|
+
"optional": ["tab_id"],
|
|
1627
|
+
"description": "Delete a row from a table",
|
|
1628
|
+
},
|
|
1629
|
+
"insert_table_column": {
|
|
1630
|
+
"required": ["table_start_index", "column_index"],
|
|
1631
|
+
"optional": ["insert_right", "tab_id"],
|
|
1632
|
+
"description": "Insert a column to the left or right of a reference column in a table",
|
|
1633
|
+
},
|
|
1634
|
+
"delete_table_column": {
|
|
1635
|
+
"required": ["table_start_index", "column_index"],
|
|
1636
|
+
"optional": ["tab_id"],
|
|
1637
|
+
"description": "Delete a column from a table",
|
|
1638
|
+
},
|
|
1639
|
+
"merge_table_cells": {
|
|
1640
|
+
"required": [
|
|
1641
|
+
"table_start_index",
|
|
1642
|
+
"row_index",
|
|
1643
|
+
"column_index",
|
|
1644
|
+
"row_span",
|
|
1645
|
+
"column_span",
|
|
1646
|
+
],
|
|
1647
|
+
"optional": ["tab_id"],
|
|
1648
|
+
"description": "Merge a rectangular range of cells in a table",
|
|
1649
|
+
},
|
|
1650
|
+
"unmerge_table_cells": {
|
|
1651
|
+
"required": [
|
|
1652
|
+
"table_start_index",
|
|
1653
|
+
"row_index",
|
|
1654
|
+
"column_index",
|
|
1655
|
+
"row_span",
|
|
1656
|
+
"column_span",
|
|
1657
|
+
],
|
|
1658
|
+
"optional": ["tab_id"],
|
|
1659
|
+
"description": "Unmerge cells in a table that were previously merged",
|
|
1660
|
+
},
|
|
1661
|
+
"update_table_column_properties": {
|
|
1662
|
+
"required": ["table_start_index", "column_indices"],
|
|
1663
|
+
"optional": ["width", "width_type", "tab_id"],
|
|
1664
|
+
"description": "Update column width and width type for specified columns in a table",
|
|
1665
|
+
},
|
|
1666
|
+
"update_table_row_style": {
|
|
1667
|
+
"required": ["table_start_index", "row_indices"],
|
|
1668
|
+
"optional": ["min_row_height", "tab_id"],
|
|
1669
|
+
"description": "Update row style for specified rows in a table (minimum row height)",
|
|
1670
|
+
},
|
|
1671
|
+
"pin_table_header_rows": {
|
|
1672
|
+
"required": ["table_start_index", "pinned_header_rows_count"],
|
|
1673
|
+
"optional": ["tab_id"],
|
|
1674
|
+
"description": "Pin (repeat) the leading N rows of a table as a header on every page",
|
|
1675
|
+
},
|
|
1676
|
+
},
|
|
1677
|
+
"example_operations": [
|
|
1678
|
+
{"type": "insert_text", "index": 1, "text": "Hello World"},
|
|
1679
|
+
{
|
|
1680
|
+
"type": "format_text",
|
|
1681
|
+
"start_index": 1,
|
|
1682
|
+
"end_index": 12,
|
|
1683
|
+
"bold": True,
|
|
1684
|
+
},
|
|
1685
|
+
{"type": "insert_table", "index": 20, "rows": 2, "columns": 3},
|
|
1686
|
+
{
|
|
1687
|
+
"type": "update_paragraph_style",
|
|
1688
|
+
"start_index": 1,
|
|
1689
|
+
"end_index": 20,
|
|
1690
|
+
"heading_level": 1,
|
|
1691
|
+
"alignment": "CENTER",
|
|
1692
|
+
},
|
|
1693
|
+
],
|
|
1694
|
+
}
|