@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +34 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,828 @@
1
+ """
2
+ Google Docs to Markdown Converter
3
+
4
+ Converts Google Docs API JSON responses to clean Markdown, preserving:
5
+ - Headings (H1-H6, Title, Subtitle)
6
+ - Bold, italic, strikethrough, code, links
7
+ - Ordered and unordered lists with nesting
8
+ - Checklists with checked/unchecked state
9
+ - Tables with header row separators
10
+ - Smart chips: person (@mentions), rich links, dates, dropdowns, inline
11
+ images, footnotes, horizontal rules, auto-text (page numbers), equations
12
+ - Document tabs (multi-tab and nested child tabs)
13
+ - Explicit RGB text color as a trailing ``[color: #rrggbb]`` note (opt-in)
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import re
20
+ from datetime import datetime
21
+ from typing import Any
22
+ from urllib.parse import quote
23
+
24
+ from gdocs.docs_links import resolve_link_target
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ MONO_FONTS = {"Courier New", "Consolas", "Roboto Mono", "Source Code Pro"}
29
+
30
+ HEADING_MAP = {
31
+ "TITLE": "#",
32
+ "SUBTITLE": "##",
33
+ "HEADING_1": "#",
34
+ "HEADING_2": "##",
35
+ "HEADING_3": "###",
36
+ "HEADING_4": "####",
37
+ "HEADING_5": "#####",
38
+ "HEADING_6": "######",
39
+ }
40
+
41
+
42
+ SUGGESTION_INSERT_MARKERS = ("{++", "++}")
43
+ SUGGESTION_DELETE_MARKERS = ("{--", "--}")
44
+ SUGGESTION_LEGEND = (
45
+ "> Pending suggestions are shown inline: {++inserted text++}, "
46
+ "{--deleted text--}. Suggested text formatting is shown as if accepted.\n\n"
47
+ )
48
+ _SUGGESTION_KEYS = (
49
+ "suggestedInsertionIds",
50
+ "suggestedDeletionIds",
51
+ "suggestedTextStyleChanges",
52
+ )
53
+
54
+
55
+ def convert_doc_to_markdown(doc: dict[str, Any], include_colors: bool = False) -> str:
56
+ """Convert a Google Docs API document response to markdown.
57
+
58
+ Supports both legacy (top-level body) and tab-aware responses
59
+ (includeTabsContent=True). For multi-tab docs, each tab gets a
60
+ heading separator. Single-tab docs render without a tab heading.
61
+ Pending suggestions (SUGGESTIONS_INLINE view) are marked as
62
+ {++inserted++} and {--deleted--}, with a legend at the top.
63
+
64
+ Args:
65
+ doc: The document JSON from docs.documents.get()
66
+ include_colors: Mark text with an explicit RGB color as ``[color: #rrggbb]``
67
+
68
+ Returns:
69
+ Markdown string
70
+ """
71
+ tabs = doc.get("tabs", [])
72
+
73
+ if tabs:
74
+ markdown = _convert_tabs_to_markdown(tabs, include_colors=include_colors)
75
+ else:
76
+ # Legacy: no tabs, use top-level body/lists/footnotes/inlineObjects
77
+ markdown = _convert_body_to_markdown(doc, include_colors=include_colors)
78
+
79
+ rendered: list[tuple[str, dict[str, Any]]] = []
80
+ _collect_tabs(tabs, rendered)
81
+ if any(
82
+ _has_pending_suggestions([tab_doc.get("body"), tab_doc.get("footnotes")])
83
+ for _, tab_doc in rendered or [("", doc)]
84
+ ):
85
+ return SUGGESTION_LEGEND + markdown
86
+ return markdown
87
+
88
+
89
+ def _has_pending_suggestions(node: Any) -> bool:
90
+ """Whether any element under ``node`` carries a pending suggestion."""
91
+ if isinstance(node, dict):
92
+ if any(node.get(key) for key in _SUGGESTION_KEYS):
93
+ return True
94
+ return any(_has_pending_suggestions(value) for value in node.values())
95
+ if isinstance(node, list):
96
+ return any(_has_pending_suggestions(item) for item in node)
97
+ return False
98
+
99
+
100
+ def _convert_tabs_to_markdown(
101
+ tabs: list[dict[str, Any]], include_colors: bool = False
102
+ ) -> str:
103
+ """Convert a list of document tabs to markdown, recursing into child tabs."""
104
+ all_tab_docs: list[tuple[str, dict[str, Any]]] = []
105
+ _collect_tabs(tabs, all_tab_docs)
106
+
107
+ if len(all_tab_docs) == 1:
108
+ _, tab_doc = all_tab_docs[0]
109
+ return _convert_body_to_markdown(tab_doc, include_colors=include_colors)
110
+
111
+ sections: list[str] = []
112
+ for title, tab_doc in all_tab_docs:
113
+ tab_md = _convert_body_to_markdown(tab_doc, include_colors=include_colors)
114
+ sections.append(f"# {title}\n\n{tab_md}")
115
+
116
+ return "\n".join(sections).rstrip("\n") + "\n"
117
+
118
+
119
+ def _collect_tabs(
120
+ tabs: list[dict[str, Any]],
121
+ result: list[tuple[str, dict[str, Any]]],
122
+ ) -> None:
123
+ """Flatten tab hierarchy into (title, documentTab) pairs."""
124
+ for tab in tabs:
125
+ props = tab.get("tabProperties", {})
126
+ title = props.get("title", "Untitled Tab")
127
+ doc_tab = tab.get("documentTab", {})
128
+ if doc_tab:
129
+ result.append((title, doc_tab))
130
+ for child in tab.get("childTabs", []):
131
+ _collect_tabs([child], result)
132
+
133
+
134
+ def _convert_body_to_markdown(doc: dict[str, Any], include_colors: bool = False) -> str:
135
+ """Convert a single document body (or documentTab) to markdown."""
136
+ body = doc.get("body", {})
137
+ content = body.get("content", [])
138
+ lists_meta = doc.get("lists", {})
139
+ footnotes_meta = doc.get("footnotes", {})
140
+ inline_objects = doc.get("inlineObjects", {})
141
+
142
+ lines: list[str] = []
143
+ ordered_counters: dict[tuple[str, int], int] = {}
144
+ prev_was_list = False
145
+ footnote_defs: list[tuple[str, str]] = []
146
+
147
+ for position, element in enumerate(content):
148
+ if "paragraph" in element:
149
+ para = element["paragraph"]
150
+ text = _convert_paragraph_text(
151
+ para,
152
+ footnotes_meta=footnotes_meta,
153
+ inline_objects=inline_objects,
154
+ footnote_defs=footnote_defs,
155
+ include_colors=include_colors,
156
+ )
157
+
158
+ if not text.strip():
159
+ if prev_was_list:
160
+ prev_was_list = False
161
+ continue
162
+
163
+ bullet = para.get("bullet")
164
+ if bullet:
165
+ list_id = bullet["listId"]
166
+ nesting = bullet.get("nestingLevel", 0)
167
+
168
+ if _is_checklist(lists_meta, list_id, nesting):
169
+ checked = _is_checked(para)
170
+ checkbox = "[x]" if checked else "[ ]"
171
+ indent = " " * nesting
172
+ cb_text = (
173
+ _convert_paragraph_text(
174
+ para,
175
+ skip_strikethrough=True,
176
+ footnotes_meta=footnotes_meta,
177
+ inline_objects=inline_objects,
178
+ footnote_defs=footnote_defs,
179
+ include_colors=include_colors,
180
+ )
181
+ if checked
182
+ else text
183
+ )
184
+ lines.append(f"{indent}- {checkbox} {cb_text}")
185
+ elif _is_ordered_list(lists_meta, list_id, nesting):
186
+ key = (list_id, nesting)
187
+ ordered_counters[key] = ordered_counters.get(key, 0) + 1
188
+ counter = ordered_counters[key]
189
+ indent = " " * nesting
190
+ lines.append(f"{indent}{counter}. {text}")
191
+ else:
192
+ indent = " " * nesting
193
+ lines.append(f"{indent}- {text}")
194
+ prev_was_list = True
195
+ else:
196
+ if prev_was_list:
197
+ ordered_counters.clear()
198
+ lines.append("")
199
+ prev_was_list = False
200
+
201
+ style = para.get("paragraphStyle", {})
202
+ named_style = style.get("namedStyleType", "NORMAL_TEXT")
203
+ prefix = HEADING_MAP.get(named_style, "")
204
+
205
+ if prefix:
206
+ lines.append(f"{prefix} {text}")
207
+ lines.append("")
208
+ else:
209
+ lines.append(text)
210
+ lines.append("")
211
+
212
+ elif "table" in element:
213
+ if prev_was_list:
214
+ ordered_counters.clear()
215
+ lines.append("")
216
+ prev_was_list = False
217
+ table_md = _convert_table(
218
+ element["table"],
219
+ footnotes_meta=footnotes_meta,
220
+ inline_objects=inline_objects,
221
+ footnote_defs=footnote_defs,
222
+ include_colors=include_colors,
223
+ )
224
+ lines.append(table_md)
225
+ lines.append("")
226
+ # The Docs API opens every body with a section break; only later ones
227
+ # reflect a break the author inserted.
228
+ elif "sectionBreak" in element and position > 0:
229
+ lines.append("[Section Break]")
230
+ lines.append("")
231
+
232
+ if footnote_defs:
233
+ lines.append("")
234
+ for fn_id, fn_text in footnote_defs:
235
+ lines.append(f"[^{fn_id}]: {fn_text}")
236
+
237
+ result = "\n".join(lines).rstrip("\n") + "\n"
238
+ return result
239
+
240
+
241
+ def _convert_paragraph_text(
242
+ para: dict[str, Any],
243
+ skip_strikethrough: bool = False,
244
+ footnotes_meta: dict[str, Any] | None = None,
245
+ inline_objects: dict[str, Any] | None = None,
246
+ footnote_defs: list[tuple[str, str]] | None = None,
247
+ active_footnotes: set[str] | None = None,
248
+ include_colors: bool = False,
249
+ ) -> str:
250
+ """Convert paragraph elements to inline markdown text."""
251
+ parts: list[str] = []
252
+ elements = para.get("elements", [])
253
+ link_start = 0
254
+ color_visible = False
255
+ for position, elem in enumerate(elements):
256
+ if "textRun" in elem:
257
+ group = _link_group(elements, position)
258
+ link = group[0]
259
+ if _link_group(elements, position - 1) != group:
260
+ link_start = len(parts)
261
+ parts.append(_convert_text_run(elem["textRun"], skip_strikethrough))
262
+ color = _text_run_color(elements, position) if include_colors else None
263
+ if color:
264
+ if _text_run_color(elements, position - 1) != color:
265
+ color_visible = False
266
+ color_visible |= bool(elem["textRun"].get("content", "").strip())
267
+ color_ends = (
268
+ color is not None
269
+ and color_visible
270
+ and _text_run_color(elements, position + 1) != color
271
+ )
272
+ # Link a label split across styled runs once, after its final run,
273
+ # at a suggestion boundary or before a color note.
274
+ if link and (color_ends or _link_group(elements, position + 1) != group):
275
+ parts[link_start:] = [
276
+ _mark_suggested(
277
+ _apply_link("".join(parts[link_start:]), link), elem["textRun"]
278
+ )
279
+ ]
280
+ link_start = len(parts)
281
+ elif not link:
282
+ parts[-1] = _mark_suggested(parts[-1], elem["textRun"])
283
+ if color_ends:
284
+ label = parts[-1].rstrip()
285
+ parts[-1] = f"{label} [color: {color}]{parts[-1][len(label) :]}"
286
+ continue
287
+ if "person" in elem:
288
+ carrier = elem["person"]
289
+ part = _convert_person_chip(carrier)
290
+ elif "richLink" in elem:
291
+ carrier = elem["richLink"]
292
+ part = _convert_rich_link_chip(carrier)
293
+ elif "dateElement" in elem:
294
+ carrier = elem["dateElement"]
295
+ part = _convert_date_chip(carrier)
296
+ elif "dropdown" in elem:
297
+ carrier = elem["dropdown"]
298
+ part = carrier.get("dropdownProperties", {}).get("displayValue", "")
299
+ elif "inlineObjectElement" in elem:
300
+ carrier = elem["inlineObjectElement"]
301
+ part = _convert_inline_object(carrier, inline_objects)
302
+ elif "footnoteReference" in elem:
303
+ carrier = elem["footnoteReference"]
304
+ part = _convert_footnote_reference(
305
+ carrier,
306
+ footnotes_meta,
307
+ inline_objects,
308
+ footnote_defs,
309
+ active_footnotes,
310
+ include_colors=include_colors,
311
+ )
312
+ elif "horizontalRule" in elem:
313
+ carrier = elem["horizontalRule"]
314
+ part = "\n---\n"
315
+ elif "autoText" in elem:
316
+ carrier = elem["autoText"]
317
+ part = _convert_auto_text(carrier)
318
+ elif "pageBreak" in elem:
319
+ carrier = elem["pageBreak"]
320
+ part = "[Page Break]"
321
+ elif "columnBreak" in elem:
322
+ carrier = elem["columnBreak"]
323
+ part = "[Column Break]"
324
+ elif "equation" in elem:
325
+ carrier = elem["equation"]
326
+ part = _convert_equation(carrier)
327
+ else:
328
+ continue
329
+ parts.append(_mark_suggested(part, carrier))
330
+ return "".join(parts).strip()
331
+
332
+
333
+ def _mark_suggested(text: str, carrier: dict[str, Any]) -> str:
334
+ """Wrap rendered text in markers when its carrier is a pending suggestion."""
335
+ if not text:
336
+ return text
337
+ if carrier.get("suggestedDeletionIds"):
338
+ text = f"{SUGGESTION_DELETE_MARKERS[0]}{text}{SUGGESTION_DELETE_MARKERS[1]}"
339
+ if carrier.get("suggestedInsertionIds"):
340
+ text = f"{SUGGESTION_INSERT_MARKERS[0]}{text}{SUGGESTION_INSERT_MARKERS[1]}"
341
+ return text
342
+
343
+
344
+ def _link_group(
345
+ elements: list[dict[str, Any]], index: int
346
+ ) -> tuple[dict[str, Any] | None, tuple[str, ...], tuple[str, ...]] | None:
347
+ """Effective link and suggestion ids of the text run at ``index``.
348
+
349
+ Neighboring runs with an equal value render as one link.
350
+ """
351
+ if 0 <= index < len(elements) and "textRun" in elements[index]:
352
+ run = elements[index]["textRun"]
353
+ return (
354
+ _effective_text_style(run).get("link"),
355
+ tuple(run.get("suggestedInsertionIds", ())),
356
+ tuple(run.get("suggestedDeletionIds", ())),
357
+ )
358
+ return None
359
+
360
+
361
+ def _convert_text_run(
362
+ text_run: dict[str, Any], skip_strikethrough: bool = False
363
+ ) -> str:
364
+ """Convert a single text run to markdown, suggested style changes applied."""
365
+ content = text_run.get("content", "")
366
+ style = _effective_text_style(text_run)
367
+
368
+ text = content.rstrip("\n")
369
+ # Replace Google Docs Private Use Area chip placeholders (e.g. \ue907)
370
+ # that appear for unsupported chip types like vote, stopwatch, timer
371
+ text = text.replace("\ue907", "[Smart Chip]")
372
+ if not text:
373
+ return ""
374
+
375
+ return _apply_text_style(text, style, skip_strikethrough)
376
+
377
+
378
+ def _effective_text_style(text_run: dict[str, Any]) -> dict[str, Any]:
379
+ """The run's text style with pending style suggestions applied.
380
+
381
+ Only the fields a suggestion flags as ``<field>Suggested`` are taken from it.
382
+ """
383
+ style = dict(text_run.get("textStyle", {}))
384
+ for change in text_run.get("suggestedTextStyleChanges", {}).values():
385
+ suggested = change.get("textStyle", {})
386
+ for key, flagged in change.get("textStyleSuggestionState", {}).items():
387
+ if not flagged or not key.endswith("Suggested"):
388
+ continue
389
+ field = key[: -len("Suggested")]
390
+ if field in suggested:
391
+ style[field] = suggested[field]
392
+ else:
393
+ style.pop(field, None)
394
+ return style
395
+
396
+
397
+ def _convert_person_chip(person: dict[str, Any]) -> str:
398
+ """Convert a person smart chip to a mailto link."""
399
+ props = person.get("personProperties", {})
400
+ name = props.get("name", "")
401
+ email = props.get("email", "")
402
+ if email:
403
+ label = name or email
404
+ return f"[{label}](mailto:{email})"
405
+ return name or ""
406
+
407
+
408
+ def _convert_rich_link_chip(rich_link: dict[str, Any]) -> str:
409
+ """Convert a rich link smart chip to markdown.
410
+
411
+ Rich link chips contain a richLinkProperties dict with title and uri.
412
+ """
413
+ props = rich_link.get("richLinkProperties", {})
414
+ title = props.get("title", "")
415
+ uri = props.get("uri", "")
416
+ if title and uri:
417
+ return f"[{title}]({uri})"
418
+ if uri:
419
+ return uri
420
+ return title or ""
421
+
422
+
423
+ def _convert_date_chip(date_elem: dict[str, Any]) -> str:
424
+ """Convert a date smart chip (dateElement) to markdown.
425
+
426
+ Date elements contain dateElementProperties with displayText (the
427
+ locale-formatted string) and a timestamp.
428
+ """
429
+ props = date_elem.get("dateElementProperties", {})
430
+ display_text = props.get("displayText", "")
431
+ if display_text:
432
+ return display_text
433
+ # Fallback: parse the timestamp into a date string
434
+ timestamp = props.get("timestamp", "")
435
+ if timestamp:
436
+ try:
437
+ dt = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
438
+ return dt.strftime("%Y-%m-%d")
439
+ except (ValueError, TypeError):
440
+ return timestamp
441
+ return ""
442
+
443
+
444
+ def _convert_inline_object(
445
+ element: dict[str, Any],
446
+ inline_objects: dict[str, Any] | None,
447
+ ) -> str:
448
+ """Convert an inline object (image/drawing) to markdown."""
449
+ obj_id = element.get("inlineObjectId", "")
450
+ if not inline_objects or obj_id not in inline_objects:
451
+ return ""
452
+ obj = inline_objects[obj_id]
453
+ props = obj.get("inlineObjectProperties", {}).get("embeddedObject", {})
454
+ title = props.get("title", "") or props.get("description", "")
455
+ uri = props.get("imageProperties", {}).get("contentUri", "")
456
+ if uri:
457
+ return f"![{title}]({uri})"
458
+ return f"[Image: {title}]" if title else "[Image]"
459
+
460
+
461
+ def _convert_footnote_reference(
462
+ ref: dict[str, Any],
463
+ footnotes_meta: dict[str, Any] | None,
464
+ inline_objects: dict[str, Any] | None,
465
+ footnote_defs: list[tuple[str, str]] | None,
466
+ active_footnotes: set[str] | None = None,
467
+ include_colors: bool = False,
468
+ ) -> str:
469
+ """Convert a footnote reference to a markdown footnote marker.
470
+
471
+ Also collects the definition text with the reference's suggestion markers
472
+ for appending at the end.
473
+ """
474
+ fn_id = ref.get("footnoteId", "")
475
+ if not fn_id:
476
+ return ""
477
+ if footnotes_meta and footnote_defs is not None and fn_id in footnotes_meta:
478
+ # Avoid duplicates if the same footnote is referenced multiple times.
479
+ existing_ids = {fid for fid, _ in footnote_defs}
480
+ if fn_id not in existing_ids:
481
+ next_active = set(active_footnotes or ())
482
+ if fn_id not in next_active:
483
+ next_active.add(fn_id)
484
+ fn_content = footnotes_meta[fn_id].get("content", [])
485
+ fn_text = _convert_footnote_content(
486
+ fn_content,
487
+ footnotes_meta=footnotes_meta,
488
+ inline_objects=inline_objects,
489
+ footnote_defs=footnote_defs,
490
+ active_footnotes=next_active,
491
+ include_colors=include_colors,
492
+ )
493
+ footnote_defs.append((fn_id, _mark_suggested(fn_text, ref)))
494
+ return f"[^{fn_id}]"
495
+
496
+
497
+ def _convert_footnote_content(
498
+ content: list[dict[str, Any]],
499
+ *,
500
+ footnotes_meta: dict[str, Any] | None,
501
+ inline_objects: dict[str, Any] | None,
502
+ footnote_defs: list[tuple[str, str]] | None,
503
+ active_footnotes: set[str] | None = None,
504
+ include_colors: bool = False,
505
+ ) -> str:
506
+ """Convert footnote content with the same inline handling as body paragraphs."""
507
+ parts: list[str] = []
508
+ for element in content:
509
+ if "paragraph" in element:
510
+ text = _convert_paragraph_text(
511
+ element["paragraph"],
512
+ footnotes_meta=footnotes_meta,
513
+ inline_objects=inline_objects,
514
+ footnote_defs=footnote_defs,
515
+ active_footnotes=active_footnotes,
516
+ include_colors=include_colors,
517
+ )
518
+ if text.strip():
519
+ parts.append(text.strip())
520
+ elif "table" in element:
521
+ table_text = _convert_table(
522
+ element["table"],
523
+ footnotes_meta=footnotes_meta,
524
+ inline_objects=inline_objects,
525
+ footnote_defs=footnote_defs,
526
+ active_footnotes=active_footnotes,
527
+ include_colors=include_colors,
528
+ )
529
+ if table_text.strip():
530
+ parts.append(table_text.replace("\n", " "))
531
+ return " ".join(parts)
532
+
533
+
534
+ def _convert_auto_text(auto_text: dict[str, Any]) -> str:
535
+ """Convert an autoText element (e.g. page number) to a placeholder."""
536
+ text_type = auto_text.get("type", "")
537
+ if text_type == "PAGE_NUMBER":
538
+ return "[Page #]"
539
+ if text_type == "PAGE_COUNT":
540
+ return "[Page Count]"
541
+ return ""
542
+
543
+
544
+ def _convert_equation(equation: dict[str, Any]) -> str:
545
+ """Convert an equation element to markdown."""
546
+ # The Docs API does not expose equation content as text — only the
547
+ # suggestedInsertionIds / suggestedDeletionIds are available.
548
+ return "[Equation]"
549
+
550
+
551
+ def _apply_text_style(
552
+ text: str, style: dict[str, Any], skip_strikethrough: bool = False
553
+ ) -> str:
554
+ """Apply markdown formatting based on text style, excluding links."""
555
+ font_family = style.get("weightedFontFamily", {}).get("fontFamily", "")
556
+ if font_family in MONO_FONTS:
557
+ delimiter = "`" * (
558
+ max((len(run) for run in re.findall(r"`+", text)), default=0) + 1
559
+ )
560
+ # CommonMark removes one surrounding space pair except for all-space
561
+ # content. Padding also keeps edge backticks separate from delimiters.
562
+ if (
563
+ text.startswith("`")
564
+ or text.endswith("`")
565
+ or (text.startswith(" ") and text.endswith(" ") and text.strip(" "))
566
+ ):
567
+ text = f" {text} "
568
+ text = f"{delimiter}{text}{delimiter}"
569
+
570
+ bold = style.get("bold", False)
571
+ italic = style.get("italic", False)
572
+ strikethrough = style.get("strikethrough", False)
573
+
574
+ if bold and italic:
575
+ text = f"***{text}***"
576
+ elif bold:
577
+ text = f"**{text}**"
578
+ elif italic:
579
+ text = f"*{text}*"
580
+
581
+ if strikethrough and not skip_strikethrough:
582
+ text = f"~~{text}~~"
583
+
584
+ return text
585
+
586
+
587
+ def _text_run_color(elements: list[dict[str, Any]], index: int) -> str | None:
588
+ """Return the explicit RGB foreground color of the run at ``index`` as ``#rrggbb``.
589
+
590
+ Theme colors have no fixed hex value and return None.
591
+ """
592
+ if not 0 <= index < len(elements):
593
+ return None
594
+ style = _effective_text_style(elements[index].get("textRun", {}))
595
+ rgb = style.get("foregroundColor", {}).get("color", {}).get("rgbColor")
596
+ if rgb is None:
597
+ return None
598
+ channels = (rgb.get(key, 0.0) for key in ("red", "green", "blue"))
599
+ return "#" + "".join(f"{min(255, max(0, round(c * 255))):02x}" for c in channels)
600
+
601
+
602
+ def _apply_link(text: str, link: dict[str, Any]) -> str:
603
+ """Render a link around already-styled label text."""
604
+ link_target = resolve_link_target(link)
605
+ if not text or not link_target:
606
+ return text
607
+ if link_target.kind == "url":
608
+ destination = link_target.value
609
+ if re.search(r"[\s()<>\\]", destination):
610
+ # Angle brackets allow unbalanced parentheses. Encode whitespace
611
+ # and characters that could escape or close the destination.
612
+ destination = quote(destination, safe="/:?#[]@!$&'()*+,;=%")
613
+ destination = f"<{destination}>"
614
+ return f"[{text}]({destination})"
615
+ if link_target.kind in ("heading", "bookmark"):
616
+ tab_part = f", tab: {link_target.tab_id}" if link_target.tab_id else ""
617
+ return f"{text} [{link_target.kind}: {link_target.value}{tab_part}]"
618
+ if link_target.kind == "tab":
619
+ return f"{text} [tab: {link_target.value}]"
620
+ return text
621
+
622
+
623
+ def _is_ordered_list(lists_meta: dict[str, Any], list_id: str, nesting: int) -> bool:
624
+ """Check if a list at a given nesting level is ordered."""
625
+ list_info = lists_meta.get(list_id, {})
626
+ nesting_levels = list_info.get("listProperties", {}).get("nestingLevels", [])
627
+ if nesting < len(nesting_levels):
628
+ level = nesting_levels[nesting]
629
+ glyph = level.get("glyphType", "")
630
+ return glyph not in ("", "GLYPH_TYPE_UNSPECIFIED")
631
+ return False
632
+
633
+
634
+ def _is_checklist(lists_meta: dict[str, Any], list_id: str, nesting: int) -> bool:
635
+ """Check if a list at a given nesting level is a checklist.
636
+
637
+ Google Docs checklists are distinguished from regular bullet lists by having
638
+ GLYPH_TYPE_UNSPECIFIED with no glyphSymbol — the Docs UI renders interactive
639
+ checkboxes rather than a static glyph character.
640
+ """
641
+ list_info = lists_meta.get(list_id, {})
642
+ nesting_levels = list_info.get("listProperties", {}).get("nestingLevels", [])
643
+ if nesting < len(nesting_levels):
644
+ level = nesting_levels[nesting]
645
+ glyph_type = level.get("glyphType", "")
646
+ has_glyph_symbol = "glyphSymbol" in level
647
+ return glyph_type in ("", "GLYPH_TYPE_UNSPECIFIED") and not has_glyph_symbol
648
+ return False
649
+
650
+
651
+ def _is_checked(para: dict[str, Any]) -> bool:
652
+ """Check if a checklist item is checked.
653
+
654
+ Google Docs marks checked checklist items by applying strikethrough
655
+ formatting to the paragraph text.
656
+ """
657
+ for elem in para.get("elements", []):
658
+ if "textRun" in elem:
659
+ content = elem["textRun"].get("content", "").strip()
660
+ if content:
661
+ return elem["textRun"].get("textStyle", {}).get("strikethrough", False)
662
+ return False
663
+
664
+
665
+ def _convert_table(
666
+ table: dict[str, Any],
667
+ *,
668
+ footnotes_meta: dict[str, Any] | None = None,
669
+ inline_objects: dict[str, Any] | None = None,
670
+ footnote_defs: list[tuple[str, str]] | None = None,
671
+ active_footnotes: set[str] | None = None,
672
+ include_colors: bool = False,
673
+ ) -> str:
674
+ """Convert a table element to markdown."""
675
+ rows = table.get("tableRows", [])
676
+ if not rows:
677
+ return ""
678
+
679
+ md_rows: list[str] = []
680
+ for i, row in enumerate(rows):
681
+ cells: list[str] = []
682
+ for cell in row.get("tableCells", []):
683
+ cell_text = _extract_cell_text(
684
+ cell,
685
+ footnotes_meta=footnotes_meta,
686
+ inline_objects=inline_objects,
687
+ footnote_defs=footnote_defs,
688
+ active_footnotes=active_footnotes,
689
+ include_colors=include_colors,
690
+ )
691
+ cells.append(cell_text)
692
+ md_rows.append("| " + " | ".join(cells) + " |")
693
+
694
+ if i == 0:
695
+ sep = "| " + " | ".join("---" for _ in cells) + " |"
696
+ md_rows.append(sep)
697
+
698
+ return "\n".join(md_rows)
699
+
700
+
701
+ def _extract_cell_text(
702
+ cell: dict[str, Any],
703
+ *,
704
+ footnotes_meta: dict[str, Any] | None = None,
705
+ inline_objects: dict[str, Any] | None = None,
706
+ footnote_defs: list[tuple[str, str]] | None = None,
707
+ active_footnotes: set[str] | None = None,
708
+ include_colors: bool = False,
709
+ ) -> str:
710
+ """Extract text from a table cell."""
711
+ parts: list[str] = []
712
+ for content_elem in cell.get("content", []):
713
+ if "paragraph" in content_elem:
714
+ text = _convert_paragraph_text(
715
+ content_elem["paragraph"],
716
+ footnotes_meta=footnotes_meta,
717
+ inline_objects=inline_objects,
718
+ footnote_defs=footnote_defs,
719
+ active_footnotes=active_footnotes,
720
+ include_colors=include_colors,
721
+ )
722
+ if text.strip():
723
+ parts.append(text.strip())
724
+ cell_text = " ".join(parts)
725
+ return cell_text.replace("|", "\\|")
726
+
727
+
728
+ def format_comments_inline(markdown: str, comments: list[dict[str, Any]]) -> str:
729
+ """Insert footnote-style comment annotations inline in markdown.
730
+
731
+ For each comment, finds the anchor text in the markdown and inserts
732
+ a footnote reference. Unmatched comments go to an appendix at the bottom.
733
+ """
734
+ if not comments:
735
+ return markdown
736
+
737
+ legend = SUGGESTION_LEGEND if markdown.startswith(SUGGESTION_LEGEND) else ""
738
+ markdown = markdown[len(legend) :]
739
+ footnotes: list[str] = []
740
+ unmatched: list[dict[str, Any]] = []
741
+
742
+ for i, comment in enumerate(comments, 1):
743
+ ref = f"[^c{i}]"
744
+ anchor = comment.get("anchor_text", "")
745
+
746
+ if anchor and anchor in markdown:
747
+ markdown = markdown.replace(anchor, anchor + ref, 1)
748
+ footnotes.append(_format_footnote(i, comment))
749
+ else:
750
+ unmatched.append(comment)
751
+
752
+ if footnotes:
753
+ markdown = markdown.rstrip("\n") + "\n\n" + "\n".join(footnotes) + "\n"
754
+
755
+ if unmatched:
756
+ appendix = format_comments_appendix(unmatched)
757
+ if appendix.strip():
758
+ markdown = markdown.rstrip("\n") + "\n\n" + appendix
759
+
760
+ return legend + markdown
761
+
762
+
763
+ def _format_footnote(num: int, comment: dict[str, Any]) -> str:
764
+ """Format a single footnote."""
765
+ lines = [f"[^c{num}]: **{comment['author']}**: {comment['content']}"]
766
+ for reply in comment.get("replies", []):
767
+ lines.append(f" - **{reply['author']}**: {reply['content']}")
768
+ return "\n".join(lines)
769
+
770
+
771
+ def format_comments_appendix(
772
+ comments: list[dict[str, Any]], title: str = "Comments"
773
+ ) -> str:
774
+ """Format comments as an appendix section with blockquoted anchors."""
775
+ if not comments:
776
+ return ""
777
+
778
+ lines = [f"## {title}", ""]
779
+ for comment in comments:
780
+ resolved_tag = " *(Resolved)*" if comment.get("resolved") else ""
781
+ anchor = comment.get("anchor_text", "")
782
+ if anchor:
783
+ lines.append(f"> {anchor}")
784
+ lines.append("")
785
+ lines.append(f"- **{comment['author']}**: {comment['content']}{resolved_tag}")
786
+ for reply in comment.get("replies", []):
787
+ lines.append(f" - **{reply['author']}**: {reply['content']}")
788
+ lines.append("")
789
+
790
+ return "\n".join(lines)
791
+
792
+
793
+ def parse_drive_comments(
794
+ response: dict[str, Any], include_resolved: bool = False
795
+ ) -> list[dict[str, Any]]:
796
+ """Parse Drive API comments response into structured dicts.
797
+
798
+ Args:
799
+ response: Raw JSON from drive.comments.list()
800
+ include_resolved: Whether to include resolved comments
801
+
802
+ Returns:
803
+ List of comment dicts with keys: author, content, anchor_text,
804
+ replies, resolved
805
+ """
806
+ results = []
807
+ for comment in response.get("comments", []):
808
+ if not include_resolved and comment.get("resolved", False):
809
+ continue
810
+
811
+ anchor_text = comment.get("quotedFileContent", {}).get("value", "")
812
+ replies = [
813
+ {
814
+ "author": r.get("author", {}).get("displayName", "Unknown"),
815
+ "content": r.get("content", ""),
816
+ }
817
+ for r in comment.get("replies", [])
818
+ ]
819
+ results.append(
820
+ {
821
+ "author": comment.get("author", {}).get("displayName", "Unknown"),
822
+ "content": comment.get("content", ""),
823
+ "anchor_text": anchor_text,
824
+ "replies": replies,
825
+ "resolved": comment.get("resolved", False),
826
+ }
827
+ )
828
+ return results