"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
fix(libreoffice): import existing office files
yuhao77c4ae620250
diff --git a/libreoffice/agent-harness/LIBREOFFICE.md b/libreoffice/agent-harness/LIBREOFFICE.mdindex 5bf66171d..48828c55e 100644--- a/libreoffice/agent-harness/LIBREOFFICE.md+++ b/libreoffice/agent-harness/LIBREOFFICE.md@@ -5,7 +5,8 @@The LibreOffice CLI harness provides command-line document editing forWriter (word processor), Calc (spreadsheet), and Impress (presentations).It produces real ODF files (ZIP archives with XML) that can be opened by-LibreOffice and other ODF-compatible applications.+LibreOffice and other ODF-compatible applications. It can also import+existing ODF and Office files into the harness JSON project model for editing.## Architecture@@ -17,6 +18,7 @@ cli/core/__init__.pydocument.py # create/open/save/info/profiles+ importer.py # import existing ODF/Office files into project JSONwriter.py # paragraphs, headings, lists, tables, page breakscalc.py # sheets, cells, formulasimpress.py # slides, elements@@ -67,6 +69,14 @@ python3 -m cli.libreoffice_cli --project report.json writer add-paragraph -t "Bopython3 -m cli.libreoffice_cli --project report.json export render report.odt -p odt --overwrite```+### Import an existing document, edit it, and export it++```bash+python3 -m cli.libreoffice_cli document import existing.docx -o existing.json+python3 -m cli.libreoffice_cli --project existing.json writer add-paragraph -t "Added by CLI"+python3 -m cli.libreoffice_cli --project existing.json export render existing-updated.docx -p docx --overwrite+```+### Create a spreadsheet```bashpython3 -m cli.libreoffice_cli document new --type calc -o budget.jsondiff --git a/libreoffice/agent-harness/cli_anything/libreoffice/README.md b/libreoffice/agent-harness/cli_anything/libreoffice/README.mdindex d89d0b302..c858befed 100644--- a/libreoffice/agent-harness/cli_anything/libreoffice/README.md+++ b/libreoffice/agent-harness/cli_anything/libreoffice/README.md@@ -3,15 +3,17 @@A stateful command-line interface for document editing, producing real ODFfiles (ZIP archives with XML). Designed for AI agents and power users whoneed to create and manipulate Writer, Calc, and Impress documents without-a GUI or LibreOffice installation.+a GUI.## Prerequisites- Python 3.10+- `click` (CLI framework)+- LibreOffice/soffice for importing DOCX/XLSX/PPTX and exporting PDF or+ Microsoft Office formats-No other dependencies required -- uses Python stdlib (`zipfile`,-`xml.etree.ElementTree`, `json`) for ODF generation.+ODF import/export uses Python stdlib (`zipfile`, `xml.etree.ElementTree`,+`json`). Microsoft Office conversion uses LibreOffice headless.## Install Dependencies@@ -32,6 +34,10 @@ python3 -m cli.libreoffice_cli --help# Create a new Writer documentpython3 -m cli.libreoffice_cli document new --type writer --name "Report" -o report.json+# Import an existing Office/ODF document into editable project JSON+python3 -m cli.libreoffice_cli document import existing.docx -o imported.json+python3 -m cli.libreoffice_cli document open existing.odt -o imported.json+# Create with a page profilepython3 -m cli.libreoffice_cli document new --profile a4_portrait -o project.json@@ -57,7 +63,9 @@ Inside the REPL, type `help` for all available commands.```bashdocument new [--type writer|calc|impress] [--name N] [--profile P] [-o path]-document open <path>+document open <project.json|office-file> [-o project.json] [--name N]+document import <office-file> -o project.json [--name N]+document import-formatsdocument save [path]document infodocument profiles@@ -119,7 +127,7 @@ Style properties: `font_size`, `font_name`, `bold`, `italic`, `underline`,```bashexport presetsexport preset-info <name>-export render <output> [--preset odt|ods|odp|html|text] [--overwrite]+export render <output> [--preset odt|ods|odp|html|text|pdf|docx|xlsx|pptx|csv] [--overwrite]```### Session@@ -181,3 +189,16 @@ Exported ODF files are valid ZIP archives containing:These files can be opened by LibreOffice, Apache OpenOffice, and otherODF-compatible applications.++## Existing Files++`document open` opens CLI project JSON directly. When the input is an Office or+ODF file, it imports the file into the harness project model. Use `-o` for+one-shot workflows so the imported project is saved as JSON before subsequent+edit commands:++```bash+python3 -m cli.libreoffice_cli document open proposal.docx -o proposal.json+python3 -m cli.libreoffice_cli --project proposal.json writer add-paragraph -t "Appendix"+python3 -m cli.libreoffice_cli --project proposal.json export render proposal-updated.docx -p docx --overwrite+```diff --git a/libreoffice/agent-harness/cli_anything/libreoffice/core/document.py b/libreoffice/agent-harness/cli_anything/libreoffice/core/document.pyindex 63a7a8f0f..5688fe9b5 100644--- a/libreoffice/agent-harness/cli_anything/libreoffice/core/document.py+++ b/libreoffice/agent-harness/cli_anything/libreoffice/core/document.py@@ -4,6 +4,7 @@ import jsonimport osimport copyfrom datetime import datetime+from json import JSONDecodeErrorfrom typing import Optional, Dict, Any, List@@ -119,8 +120,15 @@ def open_document(path: str) -> Dict[str, Any]:"""Open a .lo-cli.json project file."""if not os.path.exists(path):raise FileNotFoundError(f"Document file not found: {path}")- with open(path, "r") as f:- project = json.load(f)+ try:+ with open(path, "r", encoding="utf-8") as f:+ project = json.load(f)+ except (JSONDecodeError, UnicodeDecodeError) as e:+ raise ValueError(+ f"Invalid project file: {path}. "+ "Use 'document import <office-file> -o project.json' to import "+ "ODF, DOCX, XLSX, PPTX, or other Office files."+ ) from eif "version" not in project or "type" not in project:raise ValueError(f"Invalid project file: {path}")if project["type"] not in VALID_DOC_TYPES:diff --git a/libreoffice/agent-harness/cli_anything/libreoffice/core/importer.py b/libreoffice/agent-harness/cli_anything/libreoffice/core/importer.pynew file mode 100644index 000000000..a9317cfa5--- /dev/null+++ b/libreoffice/agent-harness/cli_anything/libreoffice/core/importer.py@@ -0,0 +1,403 @@+"""Import existing Office/ODF files into the LibreOffice CLI project model."""++import os+import tempfile+import zipfile+import xml.etree.ElementTree as ET+from datetime import datetime+from typing import Any, Dict, List, Optional, Tuple++from cli_anything.libreoffice.core.document import create_document+from cli_anything.libreoffice.utils.lo_backend import convert+from cli_anything.libreoffice.utils.odf_utils import ODF_MIMETYPES, ODF_NS, parse_odf+++ODF_EXTENSION_TYPES = {+ ".odt": "writer",+ ".ott": "writer",+ ".ods": "calc",+ ".ots": "calc",+ ".odp": "impress",+ ".otp": "impress",+}++OFFICE_EXTENSION_CONVERSIONS = {+ ".doc": ("writer", "odt"),+ ".docx": ("writer", "odt"),+ ".docm": ("writer", "odt"),+ ".rtf": ("writer", "odt"),+ ".txt": ("writer", "odt"),+ ".html": ("writer", "odt"),+ ".htm": ("writer", "odt"),+ ".xls": ("calc", "ods"),+ ".xlsx": ("calc", "ods"),+ ".xlsm": ("calc", "ods"),+ ".csv": ("calc", "ods"),+ ".ppt": ("impress", "odp"),+ ".pptx": ("impress", "odp"),+ ".pptm": ("impress", "odp"),+}++SUPPORTED_IMPORT_EXTENSIONS = tuple(+ sorted(set(ODF_EXTENSION_TYPES) | set(OFFICE_EXTENSION_CONVERSIONS))+)+++def can_import(path: str) -> bool:+ """Return True if the path extension is supported by the import pipeline."""+ return os.path.splitext(path)[1].lower() in SUPPORTED_IMPORT_EXTENSIONS+++def list_import_formats() -> List[Dict[str, str]]:+ """List importable document extensions."""+ formats = []+ for ext, doc_type in sorted(ODF_EXTENSION_TYPES.items()):+ formats.append({+ "extension": ext,+ "type": doc_type,+ "method": "native-odf",+ })+ for ext, (doc_type, odf_format) in sorted(OFFICE_EXTENSION_CONVERSIONS.items()):+ formats.append({+ "extension": ext,+ "type": doc_type,+ "method": "libreoffice-headless",+ "intermediate": odf_format,+ })+ return formats+++def import_document(path: str, name: Optional[str] = None) -> Dict[str, Any]:+ """Import an existing Office/ODF file into a CLI project dict.++ ODF files are parsed directly. Microsoft Office, legacy Office, CSV, RTF,+ HTML, and text inputs are first converted to ODF with LibreOffice headless,+ then parsed into the harness state model.+ """+ if not os.path.exists(path):+ raise FileNotFoundError(f"Document file not found: {path}")++ ext = os.path.splitext(path)[1].lower()+ if ext in ODF_EXTENSION_TYPES:+ doc_type = ODF_EXTENSION_TYPES[ext]+ project = import_odf(path, doc_type=doc_type, name=name)+ project["metadata"]["import_method"] = "native-odf"+ return project++ if ext not in OFFICE_EXTENSION_CONVERSIONS:+ raise ValueError(+ f"Unsupported import format: {ext or '(none)'}. "+ f"Supported: {', '.join(SUPPORTED_IMPORT_EXTENSIONS)}"+ )++ doc_type, odf_format = OFFICE_EXTENSION_CONVERSIONS[ext]+ with tempfile.TemporaryDirectory() as tmpdir:+ odf_path = convert(path, odf_format, output_dir=tmpdir)+ project = import_odf(odf_path, doc_type=doc_type, name=name)++ project["metadata"]["import_method"] = "libreoffice-headless"+ project["metadata"]["original_format"] = ext.lstrip(".")+ project["metadata"]["source_path"] = os.path.abspath(path)+ return project+++def import_odf(+ path: str,+ doc_type: Optional[str] = None,+ name: Optional[str] = None,+) -> Dict[str, Any]:+ """Import an ODF file into a CLI project dict."""+ try:+ parsed = parse_odf(path)+ except zipfile.BadZipFile as e:+ raise ValueError(f"Invalid ODF file: {path}") from e++ inferred_type = doc_type or _doc_type_from_mimetype(parsed.get("mimetype", ""))+ if inferred_type not in ("writer", "calc", "impress"):+ raise ValueError(f"Unsupported ODF document type: {inferred_type}")++ project_name = name or os.path.splitext(os.path.basename(path))[0]+ project = create_document(doc_type=inferred_type, name=project_name)+ _apply_metadata(project, parsed.get("meta_xml", ""), path)++ content_xml = parsed.get("content_xml")+ if not content_xml:+ return project++ try:+ root = ET.fromstring(content_xml)+ except ET.ParseError as e:+ raise ValueError(f"Invalid ODF content.xml in: {path}") from e+ if inferred_type == "writer":+ project["content"] = _parse_writer_content(root)+ elif inferred_type == "calc":+ project["sheets"] = _parse_calc_content(root)+ if not project["sheets"]:+ project["sheets"] = [{"name": "Sheet1", "cells": {}}]+ elif inferred_type == "impress":+ project["slides"] = _parse_impress_content(root)++ return project+++def _doc_type_from_mimetype(mimetype: str) -> str:+ for doc_type, expected in ODF_MIMETYPES.items():+ if mimetype == expected:+ return doc_type+ raise ValueError(f"Unsupported or missing ODF mimetype: {mimetype}")+++def _apply_metadata(project: Dict[str, Any], meta_xml: str, source_path: str) -> None:+ metadata = project.setdefault("metadata", {})+ metadata.update({+ "source_path": os.path.abspath(source_path),+ "imported_at": datetime.now().isoformat(),+ })+ if not meta_xml:+ return++ root = ET.fromstring(meta_xml)+ mappings = {+ "title": ("dc", "title"),+ "author": ("dc", "creator"),+ "description": ("dc", "description"),+ "subject": ("dc", "subject"),+ "created": ("meta", "creation-date"),+ "modified": ("dc", "date"),+ }+ for key, (prefix, local) in mappings.items():+ elem = root.find(f".//{_q(prefix, local)}")+ if elem is not None and elem.text:+ metadata[key] = elem.text+++def _parse_writer_content(root: ET.Element) -> List[Dict[str, Any]]:+ body = root.find(_q("office", "body"))+ text_root = body.find(_q("office", "text")) if body is not None else None+ if text_root is None:+ return []++ content = []+ for child in list(text_root):+ local = _local_name(child.tag)+ if local == "h":+ text = _text_content(child)+ if text:+ level = _int_attr(child, "text", "outline-level", default=1)+ content.append({+ "type": "heading",+ "level": max(1, min(level, 6)),+ "text": text,+ "style": {},+ })+ elif local == "p":+ text = _text_content(child)+ if text:+ content.append({"type": "paragraph", "text": text, "style": {}})+ elif local == "list":+ items = _parse_list_items(child)+ if items:+ content.append({+ "type": "list",+ "list_style": "bullet",+ "items": items,+ })+ elif local == "table":+ table = _parse_writer_table(child)+ if table is not None:+ content.append(table)++ return content+++def _parse_list_items(list_elem: ET.Element) -> List[str]:+ items = []+ for item_elem in _children_by_local(list_elem, "list-item"):+ text = _text_content(item_elem)+ if text:+ items.append(text)+ return items+++def _parse_writer_table(table_elem: ET.Element) -> Optional[Dict[str, Any]]:+ rows = []+ max_cols = 0+ for row_elem in _children_by_local(table_elem, "table-row"):+ row_values = _parse_table_row_values(row_elem)+ if any(value != "" for value in row_values):+ rows.append(row_values)+ max_cols = max(max_cols, len(row_values))++ if not rows:+ return None++ for row in rows:+ row.extend([""] * (max_cols - len(row)))++ return {+ "type": "table",+ "rows": len(rows),+ "cols": max_cols,+ "data": rows,+ }+++def _parse_calc_content(root: ET.Element) -> List[Dict[str, Any]]:+ body = root.find(_q("office", "body"))+ spreadsheet = body.find(_q("office", "spreadsheet")) if body is not None else None+ if spreadsheet is None:+ return []++ sheets = []+ for i, table_elem in enumerate(_children_by_local(spreadsheet, "table")):+ name = _attr(table_elem, "table", "name") or f"Sheet{i + 1}"+ cells = _parse_calc_cells(table_elem)+ sheets.append({"name": name, "cells": cells})+ return sheets+++def _parse_calc_cells(table_elem: ET.Element) -> Dict[str, Dict[str, Any]]:+ cells: Dict[str, Dict[str, Any]] = {}+ row_index = 1++ for row_elem in _children_by_local(table_elem, "table-row"):+ row_repeat = max(1, _int_attr(row_elem, "table", "number-rows-repeated", 1))+ row_cells = _parse_calc_row(row_elem, row_index)+ if row_cells:+ for repeat_offset in range(min(row_repeat, 1000)):+ for ref, cell in row_cells.items():+ col, row = _split_ref(ref)+ repeated_ref = f"{col}{int(row) + repeat_offset}"+ cells[repeated_ref] = dict(cell)+ row_index += row_repeat++ return cells+++def _parse_calc_row(row_elem: ET.Element, row_index: int) -> Dict[str, Dict[str, Any]]:+ row_cells: Dict[str, Dict[str, Any]] = {}+ col_index = 1++ for cell_elem in list(row_elem):+ if _local_name(cell_elem.tag) not in ("table-cell", "covered-table-cell"):+ continue++ col_repeat = max(1, _int_attr(cell_elem, "table", "number-columns-repeated", 1))+ cell_data = _cell_data(cell_elem)+ if cell_data is not None:+ for repeat_offset in range(min(col_repeat, 1000)):+ ref = f"{_num_to_col(col_index + repeat_offset)}{row_index}"+ row_cells[ref] = dict(cell_data)+ col_index += col_repeat++ return row_cells+++def _cell_data(cell_elem: ET.Element) -> Optional[Dict[str, Any]]:+ value_type = _attr(cell_elem, "office", "value-type") or "string"+ formula = _attr(cell_elem, "table", "formula")+ text = _text_content(cell_elem)+ numeric_value = _attr(cell_elem, "office", "value")++ if not formula and not numeric_value and not text:+ return None++ if value_type in ("float", "currency", "percentage") and numeric_value is not None:+ try:+ value: Any = float(numeric_value)+ cell_type = "float"+ except ValueError:+ value = numeric_value+ cell_type = "string"+ elif value_type == "boolean":+ value = (_attr(cell_elem, "office", "boolean-value") or text).lower() == "true"+ cell_type = "boolean"+ else:+ value = text if text != "" else (numeric_value or "")+ cell_type = "string"++ data = {"value": value, "type": cell_type}+ if formula:+ data["formula"] = formula+ return data+++def _parse_impress_content(root: ET.Element) -> List[Dict[str, Any]]:+ body = root.find(_q("office", "body"))+ presentation = body.find(_q("office", "presentation")) if body is not None else None+ if presentation is None:+ return []++ slides = []+ for page in _children_by_local(presentation, "page"):+ texts = [_text_content(elem) for elem in page.iter() if _local_name(elem.tag) in ("h", "p")]+ texts = [text for text in texts if text]+ title = texts[0] if texts else (_attr(page, "draw", "name") or "")+ content = "\n".join(texts[1:]) if len(texts) > 1 else ""+ slides.append({+ "title": title,+ "content": content,+ "elements": [],+ })+ return slides+++def _parse_table_row_values(row_elem: ET.Element) -> List[str]:+ values = []+ for cell_elem in list(row_elem):+ if _local_name(cell_elem.tag) not in ("table-cell", "covered-table-cell"):+ continue+ repeat = max(1, _int_attr(cell_elem, "table", "number-columns-repeated", 1))+ text = _text_content(cell_elem)+ for _ in range(min(repeat, 1000)):+ values.append(text)+ return values+++def _children_by_local(elem: ET.Element, local_name: str) -> List[ET.Element]:+ return [child for child in list(elem) if _local_name(child.tag) == local_name]+++def _text_content(elem: ET.Element) -> str:+ return "".join(elem.itertext()).strip()+++def _q(prefix: str, local: str) -> str:+ return f"{{{ODF_NS[prefix]}}}{local}"+++def _attr(elem: ET.Element, prefix: str, local: str) -> Optional[str]:+ return elem.get(_q(prefix, local))+++def _int_attr(elem: ET.Element, prefix: str, local: str, default: int = 1) -> int:+ value = _attr(elem, prefix, local)+ if value is None:+ return default+ try:+ return int(value)+ except ValueError:+ return default+++def _local_name(tag: str) -> str:+ return tag.rsplit("}", 1)[-1] if "}" in tag else tag+++def _num_to_col(num: int) -> str:+ result = ""+ while num > 0:+ num, rem = divmod(num - 1, 26)+ result = chr(ord("A") + rem) + result+ return result+++def _split_ref(ref: str) -> Tuple[str, str]:+ col = ""+ row = ""+ for ch in ref:+ if ch.isalpha():+ col += ch+ else:+ row += ch+ return col, rowdiff --git a/libreoffice/agent-harness/cli_anything/libreoffice/libreoffice_cli.py b/libreoffice/agent-harness/cli_anything/libreoffice/libreoffice_cli.pyindex 41d762677..4fff4380f 100644--- a/libreoffice/agent-harness/cli_anything/libreoffice/libreoffice_cli.py+++ b/libreoffice/agent-harness/cli_anything/libreoffice/libreoffice_cli.py@@ -31,6 +31,7 @@ from cli_anything.libreoffice.core import calc as calc_modfrom cli_anything.libreoffice.core import impress as impress_modfrom cli_anything.libreoffice.core import styles as styles_modfrom cli_anything.libreoffice.core import export as export_mod+from cli_anything.libreoffice.core import importer as import_mod# Global session state_session: Optional[Session] = None@@ -181,9 +182,25 @@ def document_new(doc_type, name, profile, output_path):@document.command("open")@click.argument("path")-@handle_error-def document_open(path):- """Open an existing project file."""[email protected]("--output", "-o", "output_path", type=str, default=None,+ help="Save imported Office/ODF files to this project JSON path")[email protected]("--name", "-n", type=str, default=None,+ help="Override imported project name")+@handle_error+def document_open(path, output_path, name):+ """Open a project JSON file, or import an existing Office/ODF file."""+ if import_mod.can_import(path):+ proj = import_mod.import_document(path, name=name)+ sess = get_session()+ sess.set_project(proj, output_path)+ if output_path:+ doc_mod.save_document(proj, output_path)+ info = doc_mod.get_document_info(proj)+ info["source_path"] = proj.get("metadata", {}).get("source_path")+ info["project_path"] = output_path+ output(info, f"Imported: {path}")+ return+proj = doc_mod.open_document(path)sess = get_session()sess.set_project(proj, path)@@ -191,6 +208,33 @@ def document_open(path):output(info, f"Opened: {path}")[email protected]("import")[email protected]("path")[email protected]("--output", "-o", "output_path", required=True,+ help="Project JSON path to create")[email protected]("--name", "-n", type=str, default=None,+ help="Override imported project name")+@handle_error+def document_import(path, output_path, name):+ """Import an existing Office/ODF file into a project JSON file."""+ proj = import_mod.import_document(path, name=name)+ doc_mod.save_document(proj, output_path)+ sess = get_session()+ sess.set_project(proj, output_path)+ info = doc_mod.get_document_info(proj)+ info["source_path"] = proj.get("metadata", {}).get("source_path")+ info["project_path"] = output_path+ output(info, f"Imported: {path}")++[email protected]("import-formats")+@handle_error+def document_import_formats():+ """List supported import formats."""+ formats = import_mod.list_import_formats()+ output(formats, "Supported import formats:")++@document.command("save")@click.argument("path", required=False)@handle_error@@ -743,7 +787,7 @@ def repl(project_path):def _repl_help(skin=None):commands = {- "document new|open|save|info|profiles|json": "Document management",+ "document new|open|import|import-formats|save|info|profiles|json": "Document management","writer add-paragraph|add-heading|add-list|add-table|add-page-break|remove|list|set-text": "Writer editing","calc add-sheet|remove-sheet|rename-sheet|set-cell|get-cell|list-sheets": "Spreadsheet editing","impress add-slide|remove-slide|set-content|list-slides|add-element": "Presentation editing",diff --git a/libreoffice/agent-harness/cli_anything/libreoffice/skills/SKILL.md b/libreoffice/agent-harness/cli_anything/libreoffice/skills/SKILL.mdindex b31e3e345..25bfafdcc 100644--- a/libreoffice/agent-harness/cli_anything/libreoffice/skills/SKILL.md+++ b/libreoffice/agent-harness/cli_anything/libreoffice/skills/SKILL.md@@ -60,7 +60,9 @@ Document management commands.| Command | Description ||---------|-------------|| `new` | Create a new document |-| `open` | Open an existing project file |+| `open` | Open project JSON, or import an existing Office/ODF file |+| `import` | Import an existing Office/ODF file to project JSON |+| `import-formats` | List supported import formats || `save` | Save the current document || `info` | Show document information || `profiles` | List available page profiles |@@ -189,6 +191,7 @@ The CLI maintains session state with:- **Undo/Redo**: Up to 50 levels of history- **Project persistence**: Save/load project state as JSON+- **Existing file import**: Convert ODF/DOCX/XLSX/PPTX and related formats into editable project JSON- **Session tracking**: Track modifications and changes## Output Formats@@ -214,7 +217,8 @@ When using this CLI programmatically:2. **Check return codes** - 0 for success, non-zero for errors3. **Parse stderr** for error messages on failure4. **Use absolute paths** for all file operations-5. **Verify outputs exist** after export operations+5. **Import existing Office files to JSON first** with `document import input.docx -o work.json`+6. **Verify outputs exist** after export operations## More Information@@ -224,4 +228,4 @@ When using this CLI programmatically:## Version-1.0.0\ No newline at end of file+1.0.0diff --git a/libreoffice/agent-harness/cli_anything/libreoffice/tests/TEST.md b/libreoffice/agent-harness/cli_anything/libreoffice/tests/TEST.mdindex 501c95b51..2b0e10005 100644--- a/libreoffice/agent-harness/cli_anything/libreoffice/tests/TEST.md+++ b/libreoffice/agent-harness/cli_anything/libreoffice/tests/TEST.md@@ -4,24 +4,34 @@| File | Test Classes | Test Count | Focus ||------|-------------|------------|-------|-| `test_core.py` | 6 | 96 | Unit tests for document, Writer, Calc, Impress, styles, session |-| `test_full_e2e.py` | 9 | 47 | E2E workflows: ODF ZIP structure, XML validity, export formats, CLI subprocess |-| **Total** | **15** | **143** | |+| `test_core.py` | 7 | 97 | Unit tests for document, import, Writer, Calc, Impress, styles, session |+| `test_full_e2e.py` | 17 | 73 | E2E workflows: ODF ZIP structure, XML validity, import, export formats, CLI subprocess |+| **Total** | **24** | **170** | |## Unit Tests (`test_core.py`)All unit tests use synthetic/in-memory data only. No LibreOffice installation required.-### TestDocument (15 tests)+### TestDocument (16 tests)- Create Writer, Calc, and Impress documents- Create with custom name and named profile (A4, Letter)- Reject invalid document type and invalid profile- Save and open roundtrip- Open nonexistent file raises error; open invalid file raises error+- Opening ODF as project JSON raises a helpful import hint- Get document info for Writer and Calc- List available profiles- Metadata populated on creation (title, created date)+### TestImport (7 tests)+- List supported import formats, including ODF and Microsoft Office extensions+- Import generated ODT into Writer project content+- Import generated ODS into Calc sheets and cells+- Import generated ODP into Impress slides+- Route DOCX import through LibreOffice conversion without requiring LibreOffice in unit tests+- Reject unsupported import formats+- Reject invalid ODF files with a clean error+### TestWriter (18 tests)- Add paragraph with default and custom style- Add heading; headings support levels 1-6; reject invalid level@@ -106,6 +116,11 @@ E2E tests produce real ODF files (ODT/ODS/ODP) and validate ZIP structure, XML c- Presentation with elements (textboxes, images) in ODP- Export to HTML produces slide content+### TestOfficeImportE2E (3 tests)+- Import existing DOCX through LibreOffice conversion into Writer project content+- Import existing XLSX through LibreOffice conversion into Calc sheets and cells+- Import existing PPTX through LibreOffice conversion into Impress slides+### TestExportEdgeCases (10 tests)- Overwrite protection prevents clobbering existing files- Overwrite allowed when force flag is set@@ -133,12 +148,13 @@ E2E tests produce real ODF files (ODT/ODS/ODP) and validate ZIP structure, XML c- Undo reverses slide addition- Undo reverses style creation-### TestCLISubprocess (8 tests)+### TestCLISubprocess (9 tests)- `--help` prints usage- `document new` creates document- `document new --json` outputs valid JSON- `document profiles` lists profiles- `export presets` lists presets+- `document open existing.odt -o imported.json` imports, edits, and re-exports- Full Writer workflow via JSON CLI- Calc workflow via JSON CLI- Impress workflow via JSON CLI@@ -155,14 +171,6 @@ E2E tests produce real ODF files (ODT/ODS/ODP) and validate ZIP structure, XML c## Test Results```-============================= test session starts ==============================-platform linux -- Python 3.13.11, pytest-9.0.2, pluggy-1.5.0-rootdir: /root/cli-anything-plugins: langsmith-0.5.1, anyio-4.12.0-collected 143 items--test_core.py 96 passed-test_full_e2e.py 47 passed--============================= 143 passed in 2.25s ==============================+test_core.py: 97 passed in 0.15s+test_full_e2e.py: 73 passed in 58.33s```diff --git a/libreoffice/agent-harness/cli_anything/libreoffice/tests/test_core.py b/libreoffice/agent-harness/cli_anything/libreoffice/tests/test_core.pyindex 361ad1456..0c359f295 100644--- a/libreoffice/agent-harness/cli_anything/libreoffice/tests/test_core.py+++ b/libreoffice/agent-harness/cli_anything/libreoffice/tests/test_core.py@@ -7,6 +7,7 @@ import jsonimport osimport sysimport tempfile+import shutilimport pytestsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))@@ -32,6 +33,8 @@ from cli_anything.libreoffice.core.styles import (get_style, apply_style,)from cli_anything.libreoffice.core.session import Session+from cli_anything.libreoffice.core.export import to_odt, to_ods, to_odp+from cli_anything.libreoffice.core import importer as importer_mod# ── Document Tests ───────────────────────────────────────────────@@ -102,6 +105,15 @@ class TestDocument:finally:os.unlink(path)+ def test_open_odt_as_project_gives_import_hint(self):+ proj = create_document(doc_type="writer")+ add_paragraph(proj, text="Existing file")+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "existing.odt")+ to_odt(proj, path)+ with pytest.raises(ValueError, match="document import"):+ open_document(path)+def test_get_document_info_writer(self):proj = create_document(name="info_test", doc_type="writer")info = get_document_info(proj)@@ -128,6 +140,113 @@ class TestDocument:assert proj["metadata"]["software"] == "libreoffice-cli 1.0"+class TestImport:+ def test_list_import_formats_includes_office_and_odf(self):+ formats = importer_mod.list_import_formats()+ extensions = {item["extension"] for item in formats}+ assert ".odt" in extensions+ assert ".docx" in extensions+ assert ".xlsx" in extensions+ assert ".pptx" in extensions++ def test_import_writer_odt(self):+ proj = create_document(doc_type="writer", name="import_writer")+ add_heading(proj, text="Imported Heading", level=2)+ add_paragraph(proj, text="Imported paragraph")+ add_list(proj, items=["One", "Two"])+ add_table(proj, rows=2, cols=2, data=[["A", "B"], ["C", "D"]])++ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "writer.odt")+ to_odt(proj, path)+ imported = importer_mod.import_document(path)++ assert imported["type"] == "writer"+ assert imported["metadata"]["import_method"] == "native-odf"+ assert [item["type"] for item in imported["content"]] == [+ "heading", "paragraph", "list", "table",+ ]+ assert imported["content"][0]["text"] == "Imported Heading"+ assert imported["content"][0]["level"] == 2+ assert imported["content"][3]["data"][1][1] == "D"++ def test_import_calc_ods(self):+ proj = create_document(doc_type="calc", name="import_calc")+ set_cell(proj, "A1", "Name")+ set_cell(proj, "B1", "42", cell_type="float")++ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "sheet.ods")+ to_ods(proj, path)+ imported = importer_mod.import_document(path)++ assert imported["type"] == "calc"+ assert imported["sheets"][0]["name"] == "Sheet1"+ assert imported["sheets"][0]["cells"]["A1"]["value"] == "Name"+ assert imported["sheets"][0]["cells"]["B1"]["value"] == 42.0+ assert imported["sheets"][0]["cells"]["B1"]["type"] == "float"++ def test_import_impress_odp(self):+ proj = create_document(doc_type="impress", name="import_impress")+ add_slide(proj, title="Intro", content="Welcome")+ add_slide(proj, title="End", content="Questions")++ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "deck.odp")+ to_odp(proj, path)+ imported = importer_mod.import_document(path)++ assert imported["type"] == "impress"+ assert len(imported["slides"]) == 2+ assert imported["slides"][0]["title"] == "Intro"+ assert imported["slides"][0]["content"] == "Welcome"++ def test_import_docx_uses_libreoffice_conversion(self, monkeypatch):+ source_proj = create_document(doc_type="writer")+ add_paragraph(source_proj, text="Converted content")++ with tempfile.TemporaryDirectory() as tmp:+ odt_path = os.path.join(tmp, "converted.odt")+ to_odt(source_proj, odt_path)+ docx_path = os.path.join(tmp, "input.docx")+ with open(docx_path, "wb") as f:+ f.write(b"fake docx; conversion is monkeypatched")++ def fake_convert(input_path, output_format, output_dir=None, timeout=120):+ assert input_path == docx_path+ assert output_format == "odt"+ out = os.path.join(output_dir, "input.odt")+ shutil.copyfile(odt_path, out)+ return out++ monkeypatch.setattr(importer_mod, "convert", fake_convert)+ imported = importer_mod.import_document(docx_path)++ assert imported["type"] == "writer"+ assert imported["metadata"]["import_method"] == "libreoffice-headless"+ assert imported["metadata"]["original_format"] == "docx"+ assert imported["content"][0]["text"] == "Converted content"++ def test_reject_unsupported_import_format(self):+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as f:+ path = f.name+ try:+ with pytest.raises(ValueError, match="Unsupported import format"):+ importer_mod.import_document(path)+ finally:+ os.unlink(path)++ def test_reject_invalid_odf_file(self):+ with tempfile.NamedTemporaryFile(suffix=".odt", delete=False) as f:+ f.write(b"not a zip")+ path = f.name+ try:+ with pytest.raises(ValueError, match="Invalid ODF file"):+ importer_mod.import_document(path)+ finally:+ os.unlink(path)++# ── Writer Tests ─────────────────────────────────────────────────class TestWriter:diff --git a/libreoffice/agent-harness/cli_anything/libreoffice/tests/test_full_e2e.py b/libreoffice/agent-harness/cli_anything/libreoffice/tests/test_full_e2e.pyindex f13cc9c83..18ac2e844 100644--- a/libreoffice/agent-harness/cli_anything/libreoffice/tests/test_full_e2e.py+++ b/libreoffice/agent-harness/cli_anything/libreoffice/tests/test_full_e2e.py@@ -34,6 +34,7 @@ from cli_anything.libreoffice.core.styles import create_style, apply_style, listfrom cli_anything.libreoffice.core.export import (export, to_odt, to_ods, to_odp, to_html, to_text, list_presets,)+from cli_anything.libreoffice.core import importer as importer_modfrom cli_anything.libreoffice.core.session import Sessionfrom cli_anything.libreoffice.utils.odf_utils import validate_odf, parse_odf, ODF_MIMETYPESfrom cli_anything.libreoffice.utils.lo_backend import find_libreoffice, get_version, convert_odf_to@@ -580,6 +581,37 @@ class TestCLISubprocess:assert result.returncode == 0assert "odt" in result.stdout+ def test_open_existing_odt_to_project_and_edit(self, tmp_dir):+ source_proj = create_document(doc_type="writer", name="Existing")+ add_heading(source_proj, text="Existing Heading", level=1)+ add_paragraph(source_proj, text="Original paragraph")+ source_odt = os.path.join(tmp_dir, "existing.odt")+ imported_json = os.path.join(tmp_dir, "imported.json")+ edited_odt = os.path.join(tmp_dir, "edited.odt")+ to_odt(source_proj, source_odt)++ result = self._run([+ "--json", "document", "open", source_odt,+ "-o", imported_json,+ ])+ data = json.loads(result.stdout)+ assert data["type"] == "writer"+ assert data["content_count"] == 2+ assert os.path.exists(imported_json)++ self._run([+ "--project", imported_json,+ "writer", "add-paragraph", "-t", "Added after import",+ ])+ self._run([+ "--project", imported_json,+ "export", "render", edited_odt, "-p", "odt", "--overwrite",+ ])++ parsed = parse_odf(edited_odt)+ assert "Existing Heading" in parsed["content_xml"]+ assert "Added after import" in parsed["content_xml"]+def test_full_workflow(self, tmp_dir):proj_path = os.path.join(tmp_dir, "workflow.json")odt_path = os.path.join(tmp_dir, "output.odt")@@ -915,6 +947,66 @@ class TestImpressToPPTX:print(f"\n Impress PDF: {result['output']} ({result['file_size']:,} bytes)")+class TestOfficeImportE2E:+ """True E2E: existing Office files -> ODF -> project JSON model."""++ def test_import_existing_docx(self, tmp_dir):+ proj = create_document(doc_type="writer", name="Import DOCX")+ add_heading(proj, text="DOCX Source", level=1)+ add_paragraph(proj, text="Paragraph imported from an existing DOCX.")+ docx_path = os.path.join(tmp_dir, "source.docx")+ export(proj, docx_path, preset="docx", overwrite=True)++ imported = importer_mod.import_document(docx_path)++ assert imported["type"] == "writer"+ text = "\n".join(+ [item.get("text", "") for item in imported["content"]] ++ [+ list_item+ for item in imported["content"]+ for list_item in item.get("items", [])+ ]+ )+ assert "DOCX Source" in text+ assert "Paragraph imported from an existing DOCX." in text+ assert imported["metadata"]["import_method"] == "libreoffice-headless"++ def test_import_existing_xlsx(self, tmp_dir):+ proj = create_document(doc_type="calc", name="Import XLSX")+ set_cell(proj, "A1", "Name")+ set_cell(proj, "B1", "Score")+ set_cell(proj, "A2", "Alice")+ set_cell(proj, "B2", "95", cell_type="float")+ xlsx_path = os.path.join(tmp_dir, "source.xlsx")+ export(proj, xlsx_path, preset="xlsx", overwrite=True)++ imported = importer_mod.import_document(xlsx_path)++ assert imported["type"] == "calc"+ cells = imported["sheets"][0]["cells"]+ assert cells["A1"]["value"] == "Name"+ assert cells["A2"]["value"] == "Alice"+ assert cells["B2"]["value"] == 95.0++ def test_import_existing_pptx(self, tmp_dir):+ proj = create_document(doc_type="impress", name="Import PPTX")+ add_slide(proj, title="Opening", content="Imported from PPTX")+ add_slide(proj, title="Closing", content="Done")+ pptx_path = os.path.join(tmp_dir, "source.pptx")+ export(proj, pptx_path, preset="pptx", overwrite=True)++ imported = importer_mod.import_document(pptx_path)++ assert imported["type"] == "impress"+ slide_text = "\n".join(+ f"{slide.get('title', '')}\n{slide.get('content', '')}"+ for slide in imported["slides"]+ )+ assert "Opening" in slide_text+ assert "Imported from PPTX" in slide_text++class TestCLISubprocessE2E:"""True E2E via subprocess: invoke the installed CLI to produce real files."""diff --git a/libreoffice/agent-harness/cli_anything/libreoffice/utils/lo_backend.py b/libreoffice/agent-harness/cli_anything/libreoffice/utils/lo_backend.pyindex e611e6f8e..0ec44f77b 100644--- a/libreoffice/agent-harness/cli_anything/libreoffice/utils/lo_backend.py+++ b/libreoffice/agent-harness/cli_anything/libreoffice/utils/lo_backend.py@@ -108,19 +108,35 @@ def convert(output_dir = os.path.dirname(input_path)os.makedirs(output_dir, exist_ok=True)- cmd = [- lo,- "--headless",- "--convert-to", output_format,- "--outdir", output_dir,- input_path,- ]-- result = subprocess.run(- cmd,- capture_output=True, text=True,- timeout=timeout,- )+ with tempfile.TemporaryDirectory(prefix="lo-profile-") as profile_dir, \+ tempfile.TemporaryDirectory(prefix="lo-runtime-") as runtime_dir, \+ tempfile.TemporaryDirectory(prefix="lo-config-") as config_dir, \+ tempfile.TemporaryDirectory(prefix="lo-cache-") as cache_dir:+ os.chmod(runtime_dir, 0o700)+ env = os.environ.copy()+ env.update({+ "XDG_RUNTIME_DIR": runtime_dir,+ "XDG_CONFIG_HOME": config_dir,+ "XDG_CACHE_HOME": cache_dir,+ })++ cmd = [+ lo,+ "--headless",+ "--nologo",+ "--nofirststartwizard",+ f"-env:UserInstallation=file://{profile_dir}",+ "--convert-to", output_format,+ "--outdir", output_dir,+ input_path,+ ]++ result = subprocess.run(+ cmd,+ capture_output=True, text=True,+ timeout=timeout,+ env=env,+ )if result.returncode != 0:raise RuntimeError(diff --git a/libreoffice/agent-harness/setup.py b/libreoffice/agent-harness/setup.pyindex e5a85600f..1f629c582 100644--- a/libreoffice/agent-harness/setup.py+++ b/libreoffice/agent-harness/setup.py@@ -16,7 +16,7 @@ setup(version="1.0.0",author="cli-anything contributors",author_email="",- description="CLI harness for LibreOffice - Create and manipulate ODF documents, export to PDF/DOCX/XLSX/PPTX via LibreOffice headless",+ description="CLI harness for LibreOffice - import, create, edit, and export ODF/Office documents via LibreOffice headless",long_description=long_description,long_description_content_type="text/markdown",url="https://github.com/HKUDS/CLI-Anything",