Skip to content
Back to search

OfficeCLI

OfficeCLI is the first and best Office suite purpose-built for AI agents to read, edit, and automate Word, Excel, and PowerPoint files. Free, open-source, single binary, no Office installation required.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/iOfficeAI/OfficeCLI with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/iOfficeAI/OfficeCLI'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/iofficeai--officecli/badge.svg)](/listings/iofficeai--officecli)

HTML

<a href="/listings/iofficeai--officecli"><img src="/api/listings/iofficeai--officecli/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

# Create a presentation and add content
officecli create deck.pptx
officecli add deck.pptx / --type slide --prop title="Q4 Report" --prop background=1A1A2E
officecli add deck.pptx '/slide[1]' --type shape \
  --prop text="Revenue grew 25%" --prop x=2cm --prop y=5cm \
  --prop font=Arial --prop size=24 --prop color=FFFFFF

# View as outline
officecli view deck.pptx outline
# → Slide 1: Q4 Report
# →   Shape 1 [TextBox]: Revenue grew 25%

# View as HTML — opens a rendered preview in your browser, no server needed
officecli view deck.pptx html

# Get structured JSON for any element
officecli get deck.pptx '/slide[1]/shape[1]' --json

# Save and close — flushes the resident session to disk
officecli close deck.pptx
{
  "tag": "shape",
  "path": "/slide[1]/shape[1]",
  "attributes": {
    "name": "TextBox 1",
    "text": "Revenue grew 25%",
    "x": "720000",
    "y": "1800000"
  }
}

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 417 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ---
  2. name: officecli
  3. description: Create, analyze, proofread, and modify Office documents (.docx, .xlsx, .pptx) using the officecli CLI tool. Use when the user wants to create, inspect, check formatting, find issues, add charts, or modify Office documents.
  4. ---
  5. # officecli
  6. AI-friendly CLI for .docx, .xlsx, .pptx. Single binary, no dependencies, no Office installation needed.
  7. ## Install
  8. If `officecli` is not installed:
  9. ```bash
  10. # macOS / Linux
  11. curl -fsSL https://d.officecli.ai/install.sh | bash
  12. # Windows (PowerShell)
  13. irm https://d.officecli.ai/install.ps1 | iex
  14. ```
  15. Verify with `officecli --version`. If still not found after install, open a new terminal.
  16. ---
  17. ## Strategy
  18. **L1 (read) → L2 (DOM edit) → L3 (raw XML)**. Always prefer higher layers. Add `--json` for structured output.
  19. **Before doc work, check Specialized Skills** (bottom of this file). Fundraising decks, academic papers, financial models, dashboards, and Morph animations need their own skill loaded first — `load_skill` once, then proceed.
  20. ---
  21. ## Help System (IMPORTANT)
  22. **When unsure about property names, value formats, or command syntax, ALWAYS run help instead of guessing.** One help query beats guess-fail-retry loops.
  23. `officecli help` ≡ `officecli --help`, and `officecli <cmd> --help` ≡ `officecli help <cmd>` — same content.
  24. ```bash
  25. officecli help # All commands + global options + schema entry points
  26. officecli help docx # List all docx elements
  27. officecli help docx paragraph # Full schema: properties, aliases, examples, readbacks
  28. officecli help docx set paragraph # Verb-filtered: only props usable with `set`
  29. officecli help docx paragraph --json # Structured schema (machine-readable)
  30. ```
  31. Format aliases: `word`→`docx`, `excel`→`xlsx`, `ppt`/`powerpoint`→`pptx`. Verbs: `add`, `set`, `get`, `query`, `remove`. MCP exposes the same schema via the single `command` string param: `{"command":"help docx paragraph"}` (not a structured `{"format":...,"type":...}` object — the MCP tool has exactly one param, `command`, and passes it through to the CLI verbatim).
  32. ---
  33. ## Performance: Resident Mode
  34. **Every command auto-starts a resident on first access** (60s idle timeout) — file-lock conflicts are automatically avoided. Explicit `open`/`close` is still recommended for longer sessions (12min idle):
  35. ```bash
  36. officecli open report.docx # explicitly keep in memory
  37. officecli set report.docx ... # no file I/O overhead
  38. officecli close report.docx # save and release
  39. ```
  40. Opt out of auto-start: `OFFICECLI_NO_AUTO_RESIDENT=1`.
  41. **Flush only at the non-officecli boundary.** officecli's own reads (`get`/`query`/`view`/`dump`) always see your latest edits, so you never need to save mid-workflow. Run `save` (keeps the resident) or `close` (flush + release) only **before a non-officecli program reads the file** — python-docx/openpyxl, Word, a renderer, delivery/upload. (Idle sessions auto-flush within seconds; `OFFICECLI_RESIDENT_FLUSH=each` makes every mutation flush before returning.)
  42. ---
  43. ## Quick Start
  44. **PPT:**
  45. ```bash
  46. officecli create slides.pptx
  47. officecli add slides.pptx / --type slide --prop title="Q4 Report" --prop background=1A1A2E
  48. officecli add slides.pptx '/slide[1]' --type shape --prop text="Revenue grew 25%" --prop x=2cm --prop y=5cm --prop font=Arial --prop size=24 --prop color=FFFFFF
  49. ```
  50. **Word:**
  51. ```bash
  52. officecli create report.docx
  53. officecli add report.docx /body --type paragraph --prop text="Executive Summary" --prop style=Heading1
  54. officecli add report.docx /body --type paragraph --prop text="Revenue increased by 25% year-over-year."
  55. ```
  56. **Excel:**
  57. ```bash
  58. officecli create data.xlsx
  59. officecli set data.xlsx /Sheet1/A1 --prop value="Name" --prop bold=true
  60. officecli set data.xlsx /Sheet1/A2 --prop value="Alice"
  61. ```
  62. ---
  63. ## L1: Create, Read & Inspect
  64. ```bash
  65. officecli create <file> # Create blank .docx/.xlsx/.pptx (type from extension)
  66. officecli view <file> <mode> # outline | stats | issues | text | annotated | html
  67. officecli get <file> <path> --depth N # Get a node and its children [--json]
  68. officecli query <file> <selector> # CSS-like query
  69. officecli validate <file> # Validate against OpenXML schema
  70. ```
  71. ### view modes
  72. | Mode | Description | Useful flags |
  73. |------|-------------|-------------|
  74. | `outline` | Document structure | |
  75. | `stats` | Statistics (pages, words, shapes) | |
  76. | `issues` | Formatting/content/structure problems | `--type format\|content\|structure`, `--limit N` |
  77. | `text` | Plain text extraction | `--start N --end N`, `--max-lines N` |
  78. | `annotated` | Text with formatting annotations | |
  79. | `html` | Static HTML snapshot — same renderer as `watch`, no server needed | `--browser`, `--page N` (docx), `--start N --end N` (pptx) |
  80. | `screenshot` / `svg` / `pdf` / `forms` | PNG via headless browser / SVG (pptx slide) / PDF via exporter plugin / form-fields JSON via format-handler plugin | `-o`, `--screenshot-width/-height`, pptx `--grid N` |
  81. Use `view html` for one-shot snapshots (CI artifacts, archival, diffing); use `watch` when you need live refresh or browser-side click-to-select.
  82. ### get
  83. Any XML path via element localName. Use `--depth N` to expand children. Add `--json` for structured output. Default text output is grep-friendly: `path (type) "text" key=val key=val ...`
  84. ```bash
  85. officecli get report.docx '/body/p[3]' --depth 2 --json
  86. officecli get slides.pptx '/slide[1]' --depth 1 # list all shapes on slide 1
  87. officecli get data.xlsx '/Sheet1/B2' --json
  88. ```
  89. ### Stable ID Addressing
  90. Elements with stable IDs return `@attr=value` paths instead of positional indices. Prefer these in multi-step workflows — positional indices shift on insert/delete, stable IDs do not.
  91. ```
  92. /slide[1]/shape[@id=550950021] # PPT shape
  93. /slide[1]/table[@id=1388430425]/tr[1]/tc[2] # PPT table
  94. /body/p[@paraId=1A2B3C4D] # Word paragraph
  95. /comments/comment[@commentId=1] # Word comment
  96. ```
  97. PPT also accepts `@name=` (e.g. `shape[@name=Title 1]`), with morph `!!` prefix awareness. Elements without stable IDs (slide, run, tr/tc, row) fall back to positional indices.
  98. ### query
  99. CSS-like selectors: `[attr=value]`, `[attr!=value]`, `[attr~=text]`, `[attr>=value]`, `[attr<=value]`, `:contains("text")`, `:empty`, `:has(formula)`, `:no-alt`. Boolean `and`/`or` supported across `query`/`set`/`remove`: `cell[value>5000 or value<100]`, `cell[(type=Number or type=Date) and value>0]`. Excel row-by-column-name: `Sheet1!row[Salary>5000]`. `set` accepts selectors and Excel-native paths (parity with `get`/`query`). Bare unscoped selectors rejected on `set`/`remove`.
  100. ```bash
  101. officecli query report.docx 'paragraph[style=Normal] > run[font!=Arial]'
  102. officecli query slides.pptx 'shape[fill=FF0000]'
  103. ```
  104. ---
  105. ## Watch & Interactive Selection
  106. Live HTML preview that auto-refreshes on every file change. Browsers can click / shift-click / box-drag to select shapes; the CLI can read the current browser selection and act on it.
  107. ```bash
  108. officecli watch <file> [--port N] # Start preview server (default port 26315)
  109. officecli unwatch <file> # Stop
  110. officecli goto <file> <path> # Scroll watching browser(s) to element (docx: p / table / tr / tc)
  111. ```
  112. Open the printed `http://localhost:N` URL. Click to select; shift/cmd/ctrl+click to multi-select; drag from empty space to box-select. PPT/Word use blue outline; Excel uses native-style green selection (double-click cell to edit inline; drag a chart to reposition).
  113. ### `get <file> selected` — read what the user clicked
  114. ```bash
  115. officecli get <file> selected [--json]
  116. ```
  117. Returns DocumentNodes for whatever is currently selected. Empty result if nothing selected. Exit code != 0 if no watch is running.
  118. ```bash
  119. # User clicks shapes in the browser, then asks "make these red"
  120. PATHS=$(officecli get deck.pptx selected --json | jq -r '.data.Results[].path')
  121. for p in $PATHS; do officecli set deck.pptx "$p" --prop fill=FF0000; done
  122. ```
  123. ### Key properties
  124. - **Selection survives file edits.** Paths use stable `@id=` form.
  125. - **All connected browsers share one selection.** Last-write-wins.
  126. - **Same-file single-watch.** A given file can have only one watch process at a time.
  127. - **Group shapes select as a whole.** Drilling into individual children of a group is not supported in v1.
  128. - **Coverage:** `.pptx` shapes/pictures/tables/charts/connectors/groups; `.docx` top-level paragraphs and tables. Inherited layout/master decorations and Word nested elements (table cells, run-level) are not addressable. **`.xlsx` does not emit `data-path`** — `mark`/`selection` on xlsx always resolve `stale=true` (v2 candidate).
  129. ### Marks — edit proposals waiting for review
  130. Use `mark` when changes need human review BEFORE they hit the file. Marks live in the watch process only; a separate `set` pipeline applies accepted ones. For one-shot changes use `set` directly; for permanent file annotations use `add --type comment` (Word native).
  131. ```bash
  132. officecli mark <file> <path> [--prop find=... color=... note=... tofix=... regex=true] [--json]
  133. officecli unmark <file> [--path <p> | --all] [--json]
  134. officecli get-marks <file> [--json]
  135. ```
  136. Props: `find` (literal or regex when `regex=true`; raw form `find='r"[abc]"'`), `color` (hex / `rgb(...)` / 22 named whitelist), `note`, `tofix` (drives apply pipeline). **Path** must be `data-path` format from watch HTML — see subskills for full pipeline.
  137. ---
  138. ## L2: DOM Operations
  139. ### set — modify properties
  140. ```bash
  141. officecli set <file> <path> --prop key=value [--prop ...]
  142. ```
  143. **Any XML attribute is settable** via element path (found via `get --depth N`) — even attributes not currently present. Without `find=`, `set` applies format to the entire element.
  144. **Value formats:**
  145. | Type | Format | Examples |
  146. |------|--------|---------|
  147. | Colors | Hex (with/without `#`), named, RGB, theme | `FF0000`, `#FF0000`, `red`, `rgb(255,0,0)`, `accent1`..`accent6` |
  148. | Spacing | Unit-qualified | `12pt`, `0.5cm`, `1.5x`, `150%` |
  149. | Dimensions | EMU or suffixed | `914400`, `2.54cm`, `1in`, `72pt`, `96px` |
  150. **Dotted-attr aliases** — `font.<attr>` forms accepted on shape/run/paragraph/table/row/cell/section/styles, e.g. `--prop font.color=red --prop font.bold=true --prop font.size=14pt`. Run `officecli help <fmt> <element>` for the full list.
  151. ### find — format or replace matched text
  152. Use top-level `--find` / `--replace` on `set` (and `--find` on `query`). Legacy `--prop find=X` still works but emits a hint.
  153. ```bash
  154. # Format matched text (auto-splits runs)
  155. officecli set doc.docx '/body/p[1]' --find weather --prop bold=true --prop color=red
  156. # Regex matching (regex= still a prop flag)
  157. officecli set doc.docx '/body/p[1]' --find '\d+%' --prop regex=true --prop color=red
  158. # Replace text (use `/` for whole-document scope)
  159. officecli set doc.docx / --find draft --replace final
  160. # docx: tracked Find&Replace
  161. officecli set doc.docx / --find draft --replace final --prop revision.author=Alice
  162. # PPT — same syntax, different paths
  163. officecli set slides.pptx / --find draft --replace final
  164. ```
  165. **Path controls search scope:** `/` = whole document, `/body/p[1]` or `/slide[N]/shape[M]` = specific element, `/header[1]` / `/footer[1]` = headers/footers.
  166. **Notes:**
  167. - Case-sensitive by default. Case-insensitive: `--prop 'find=(?i)error' --prop regex=true`
  168. - Matches work across run boundaries
  169. - No match = silent success. `--json` includes `"matched": N`
  170. - **Excel:** only `find` + `replace` supported (no find + format props)
  171. ### add — add elements or clone
  172. ```bash
  173. officecli add <file> <parent> --type <type> [--prop ...]
  174. officecli add <file> <parent> --type <type> --after <path> [--prop ...] # insert after anchor
  175. officecli add <file> <parent> --type <type> --before <path> [--prop ...] # insert before anchor
  176. officecli add <file> <parent> --type <type> --index N [--prop ...] # 0-based position (legacy)
  177. officecli add <file> <parent> --from <path> # clone existing element
  178. ```
  179. `--after`, `--before`, `--index` are mutually exclusive. No position flag = append to end.
  180. **Element types (with aliases):**
  181. | Format | Types |
  182. |--------|-------|
  183. | **pptx** | slide (incl. hidden), shape (font.latin/ea/cs, direction=rtl, underline.color, highlight=COLOR (Add/Set/Get/HTML preview), effective.X+effective.X.src; arrow alias for rightArrow; slideMaster/slideLayout typed add/set/remove), picture (SVG, brightness/contrast/glow/shadow, rotation, link, tooltip), chart (direction=rtl, pieOfPie, barOfPie, axisLine/gridline per-attr setters, animation+chartBuild=byCategory|bySeries, line dropLines/hiLowLines/upDownBars, anchor=x,y,w,h shorthand), table (cell direction=rtl, fill/background, built-in PowerPoint style catalogue, /col[C] get + swap/copyFrom, row/col Move/CopyFrom), row (tr), connector (from/to accept full-path `@name=`/`@id=` forms — bare `@name=Foo` is rejected, must be `/slide[N]/shape[@name=Foo]` — startshape/endshape SetByPath; edge-to-edge anchoring by default, fromSide/toSide to force an edge, fromIdx/toIdx for raw cxn index), group (link, tooltip, deep walk by get/query/add/remove, ungroup=true dissolves back to slide-absolute), align/distribute (targets= accepts shape[@id=N] paths, not just positional), video/audio (loop, autoStart alias), equation, notes (direction=rtl, lang), comment (legacy + modern p188 threaded round-trip), animation (15 emphasis + 16 exit presets, multi-effect chains, motion-path presets, repeat/restart/autoReverse, chart animations), transition (12 p15 presets + morph/p14), paragraph (para), run, zoom, ole (preview=, full dump round-trip via add-part+raw-set), placeholder (phType=...), model3d (rotation=ax,ay,az; full dump round-trip), smartart (dump round-trip via add-part), diagram (add-only mermaid → native shapes or rendered image, `--type diagram`/`flowchart`). |
  184. | **docx** | paragraph (direction/font.latin/ea/cs, bold.cs/italic.cs/size.cs, lang.latin/ea/cs, wordWrap, framePr.\*, tabs shorthand), run (lang slots, direction, underline.color, position half-pts, **revision.type=ins\|del\|format\|moveFrom\|moveTo + revision.action=accept\|reject** with .author/.date — bare `@author=`/`@type=` selector on `set /revision[...]` for filtered accept/reject, but `query 'revision[...]'` needs the dotted `revision.author=`/`revision.type=` form; move+revision is run-level paths only, not paragraph-level; **range=START:END** on a paragraph/shape path formats a char span by explicit 0-based half-open offset instead of addressing a run — the offset sibling of find=), table (direction=rtl, hMerge, cantSplit on row/nowrap on cell (both add+set), **virtual column ops**: add/remove/move/copyfrom on /body/tbl[N]/col), row (tr), cell (td), image, header/footer (direction), section (pageNumFmt full enum, direction=rtl, rtlGutter, pgBorders=box), bookmark, comment, footnote, endnote, formfield, sdt, chart, equation, field (28 types), hyperlink, style (direction, indents, pbdr, lineSpacing on Add/Set), toc, watermark, break, ole, **num/abstractNum/lvl**, **tab**, **textbox/shape** (add-mostly — Get returns raw XML preview only, no structured readback; Set is limited to width/height/geometry/fill/line.\*; position is `anchor.x`/`anchor.y` not bare x/y; **textbox-only** `textDirection`/rotation/gradient/shadow — docx shape itself has neither rotation nor gradient), embedded **OLE round-trip on dump→batch**, **diagram** (add-only mermaid → native shapes or rendered image, `--type diagram`/`flowchart`, no x/y at add-time — reposition via `set /body/group[N]`). docDefaults.rtl, autoHyphenation, `get /` exposes locale + /comments /footnotes /endnotes. `create --minimal` for raw OOXML scaffolding. |
  185. | **xlsx** | sheet (visible/hidden/veryHidden, print margins, printTitleRows/Cols, rightToLeft sheetView, cascade-aware rename), row (c{N}= cell-content shorthand; add accepts --from /Sheet/col[L]; formula-ref rewrite on insert), col (formula-ref rewrite, named-range follow on move), cell (type=richtext+runs, merge=range/sweep, direction=rtl, phonetic; **--shift left\|up on remove, shift=right\|down on add** — Excel UI dialog parity; formula auto-detect; OFFSET/INDIRECT in calc), chart (per-axis RTL/title, anchor=x,y,w,h, pareto), image (SVG), comment (direction=rtl), table (listobject), namedrange (definedname, volatile, `[@name=X]`; formula-body inlined at parse), pivottable (cache CoW + cross-pivot sharing, labelFilter=field:type:value add-time-only, topN=integer add-time-only, fillDownLabels is an alias of repeatLabels not a separate feature, calculatedField), sparkline, validation, autofilter, shape, textbox, CF (databar/colorscale/iconset/formulacf/cellIs/topN/aboveAverage), ole, csv. Query supports `merge`/`mergedrange`. Workbook: password. Shape selector enumerates leaves inside grpSp. |
  186. ### Pivot tables (xlsx)
  187. ```bash
  188. officecli add data.xlsx /Sheet1 --type pivottable \
  189. --prop source="Sheet1!A1:E100" --prop rows=Region,Category \
  190. --prop cols=Year --prop values="Sales:sum,Qty:count" \
  191. --prop grandTotals=rows --prop subtotals=off --prop sort=asc
  192. ```
  193. Key props: `rows`, `cols`, `values` (Field:func[:showDataAs]), `filters`, `source`, `position`, `layout` (compact/outline/tabular), `repeatLabels`, `blankRows`, `aggregate`, `showDataAs` (percent_of_total/row/col, running_total), `grandTotals`, `subtotals`, `sort`. Aggregators: sum, count, average, max, min, product, stdDev, stdDevp, var, varp, countNums. Date columns auto-group. Run `officecli help xlsx pivottable` for full schema.
  194. ### Document-level properties (all formats)
  195. ```bash
  196. officecli set doc.docx / --prop docDefaults.font=Arial --prop docDefaults.fontSize=11pt
  197. officecli set doc.docx / --prop protection=forms --prop evenAndOddHeaders=true
  198. officecli set data.xlsx / --prop calc.mode=manual --prop calc.refMode=r1c1
  199. officecli set slides.pptx / --prop defaultFont=Arial --prop show.loop=true --prop print.what=handouts
  200. ```
  201. Run `officecli help <format> /` for all document-level properties (docDefaults, docGrid, CJK spacing, calc, print, show, theme, extended).
  202. ### Sort (xlsx)
  203. ```bash
  204. officecli set data.xlsx /Sheet1 --prop sort="C desc" --prop sortHeader=true
  205. officecli set data.xlsx '/Sheet1/A1:D100' --prop sort="A asc" --prop sortHeader=true
  206. ```
  207. Format: `COL DIR[, COL DIR ...]`. Rejects ranges with merged cells or formulas. Sidecar metadata (hyperlinks, comments, conditional formatting, drawings) follows rows automatically.
  208. ### Text-anchored insert (`--after find:X` / `--before find:X`)
  209. Locate an insertion point by text match within a paragraph. Inline types (run, picture, hyperlink) insert within the paragraph; block types (table, paragraph) auto-split it. PPT only supports inline.
  210. ```bash
  211. # Word: inline run after matched text
  212. officecli add doc.docx '/body/p[1]' --type run --after find:weather --prop text=" (sunny)"
  213. # Word: block table after matched text (auto-splits paragraph)
  214. officecli add doc.docx '/body/p[1]' --type table --after "find:First sentence." --prop rows=2 --prop cols=2
  215. ```
  216. ### Clone
  217. `officecli add <file> / --from '/slide[1]'` — copies with all cross-part relationships.
  218. ### move, swap, remove
  219. ```bash
  220. officecli move <file> <path> [--to <parent>] [--index N] [--after <path>] [--before <path>]
  221. officecli swap <file> <path1> <path2>
  222. officecli remove <file> '/body/p[4]'
  223. ```
  224. When using `--after` or `--before`, `--to` can be omitted — the target container is inferred from the anchor.
  225. ### batch — multiple operations in one save cycle
  226. **Atomic by default (v1.0.137+):** every item still runs and is reported (so `N succeeded, M failed` stays meaningful and every failure surfaces), but if *any* item fails the whole batch rolls back — the file on disk is left byte-identical to before the batch ran (confirmed live in both standalone and resident mode). Use `--best-effort` to restore the old apply-what-succeeds behavior (useful for lossy `dump→batch` replays where losing the whole thing over one unsupported item is worse than a partial result). `--stop-on-error` only changes how early the run stops (remaining items are `skipped`), not whether what ran gets kept — combine it with `--best-effort` if you want "stop at first failure but keep what already succeeded." `--force` is unrelated — it's only the docx-protection bypass. Failed items carry a machine-readable `code` field (same list as `error.code`); a rolled-back batch's JSON summary carries `"atomicRolledBack": true`.
  227. `officecli dump <file> [<path>]` emits a replayable batch JSON for round-trip — `.docx` (full coverage), `.pptx` (text/tables/pictures/charts/notes/theme + OLE/3D/video/audio/SmartArt/morph/p15 transitions via raw-set passthrough), and `.xlsx` (cells/formulas/styles + tables, conditional formatting, validations, comments, charts, sparklines, pictures, shapes, pivot tables; slicers/chartEx/OLE via verbatim carrier). Path defaults to `/` (whole document); pass a subtree path (docx: `/body`, `/body/p[N]`, `/body/tbl[N]`, `/theme`, `/settings`, `/numbering`, `/styles`; xlsx: `/SheetName`, `/sheet[N]`) to scope the dump. `officecli refresh <file.docx>` recalculates TOC page numbers / PAGE / cross-references after replay (Word backend on Windows; headless-HTML fallback elsewhere). `officecli plugins list` extends support to `.doc`, `.hwpx`, `.pdf` export.
  228. ```bash
  229. echo '[
  230. {"command":"set","path":"/Sheet1/A1","props":{"value":"Name","bold":"true"}},
  231. {"command":"set","path":"/Sheet1/B1","props":{"value":"Score","bold":"true"}}
  232. ]' | officecli batch data.xlsx --json
  233. officecli batch data.xlsx --commands '[{"op":"set","path":"/Sheet1/A1","props":{"value":"Done"}}]' --json
  234. officecli batch data.xlsx --input updates.json --best-effort --json # keep whatever succeeds even if some items fail
  235. ```
  236. Supports: `add`, `set`, `get`, `query`, `remove`, `move`, `swap`, `view`, `raw`, `raw-set`, `validate`. Fields: `command` (or `op`), `path`, `parent`, `type`, `from`, `to`, `index`, `after`, `before`, `props`, `selector`, `mode`, `depth`, `part`, `xpath`, `action`, `xml`.
  237. ---
  238. ## L3: Raw XML
  239. Use when L2 cannot express what you need. No xmlns declarations needed — prefixes auto-registered.
  240. ```bash
  241. officecli raw <file> <part> # view raw XML
  242. officecli raw-set <file> <part> --xpath "..." --action replace --xml '<w:p>...</w:p>'
  243. officecli add-part <file> <parent> # create new document part (returns rId)
  244. ```
  245. `raw-set` actions: `append`, `prepend`, `insertbefore`, `insertafter`, `replace`, `remove`, `setattr`. Run `officecli help <format> raw` for available parts.
  246. ---
  247. ## Common Pitfalls
  248. | Pitfall | Correct Approach |
  249. |---------|-----------------|
  250. | `--name "foo"` | Use `--prop name="foo"` — all attributes go through `--prop` |
  251. | Unquoted `[N]` paths in zsh/bash | Always quote: `'/slide[1]'` or `"/slide[1]"` (shell glob-expands brackets) |
  252. | PPT `shape[1]` for content | `shape[1]` is typically the title placeholder. Use `shape[2]+` for content shapes |
  253. | `/shape[myname]` | Name indexing not supported. Use numeric index or `@name=` (PPT only) |
  254. | Guessing property names | Run `officecli help <format> <element>` to see exact names |
  255. | Modifying an open file | Close the file in PowerPoint/WPS first |
  256. | `\n` in shell strings | Use `\\n` for newlines in `--prop text="..."` |
  257. | `$` in shell text | `--prop text="$15M"` strips `$15`. Use single quotes: `--prop text='$15M'`, or heredoc batch |
  258. ---
  259. ## Specialized Skills
  260. `officecli load_skill <name>` — output is a SKILL.md, follow its rules.
  261. **Loading rule**:
  262. - Pick the most specific match in "When to use"; if none fits, load the format default (`word` / `pptx` / `excel`).
  263. - Scenes already contain the format default's rules — load **one** skill per artifact, never stack.
  264. - Loaded rules persist across turns; don't re-load each reply.
  265. - Two distinct artifacts → two separate loads.
  266. ### Word (.docx)
  267. | Name | When to use |
  268. |------|-------------|
  269. | `word` | Reports, letters, memos, proposals, generic documents |
  270. | `academic-paper` | Journal / conference / thesis: APA / Chicago / IEEE / MLA citations, equations, SEQ + PAGEREF cross-refs, multi-column journal layout, bibliography. NOT for business reports or letters (route those to `word`) |
  271. ### PowerPoint (.pptx)
  272. | Name | When to use |
  273. |------|-------------|
  274. | `pptx` | Generic decks: board reviews, sales decks, all-hands, product launches |
  275. | `pitch-deck` | **Fundraising only** — seed / Series A-C / SAFE / convertible / strategic raise. NOT for sales / product / board decks (route those to `pptx`) |
  276. | `morph-ppt` | Cinematic Morph-animated presentations. NOT for static decks (route those to `pptx`) |
  277. | `morph-ppt-3d` | 3D Morph: GLB models, camera moves, depth. NOT for 2D-only Morph (route those to `morph-ppt`) |
  278. ### Excel (.xlsx)
  279. | Name | When to use |
  280. |------|-------------|
  281. | `excel` | Generic workbooks, formulas, pivots, trackers |
  282. | `financial-model` | Financial models, scenarios, projections. NOT for general data analysis (route those to `excel`) |
  283. | `data-dashboard` | CSV/tabular data → KPI / analytics / executive dashboards with charts and sparklines. NOT for raw data tracking (route those to `excel`) |
  284. Example: a fundraising deck task → `officecli load_skill pitch-deck` → use the printed rules.
  285. ---
  286. ## Notes
  287. - Paths are **1-based** (XPath convention): `'/body/p[3]'` = third paragraph
  288. - `--index` is **0-based** (array convention): `--index 0` = first position
  289. - **Excel exception**: for `add --type row` and `add --type col`, `--index N` is **1-based** (matches OOXML RowIndex / column letter index). `--index 5` inserts at row 5 / column 5.
  290. - After modifications, verify with `validate` and/or `view issues`
  291. - **When unsure**, run `officecli help <format> <element>` instead of guessing
README.md · README · 698 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # OfficeCLI
  2. > **OfficeCLI is the world's first and the best Office suite designed for AI agents.**
  3. **Give any AI agent full control over Word, Excel, and PowerPoint — in one line of code.**
  4. Open-source. Single binary. No Office installation. No dependencies. Works everywhere.
  5. **OfficeCLI's built-in HTML rendering engine reproduces documents with high fidelity — and that's what gives AI eyes.** It renders `.docx` / `.xlsx` / `.pptx` to HTML or PNG, closing the *render → look → fix* loop.
  6. [![GitHub Release](https://img.shields.io/github/v/release/iOfficeAI/OfficeCLI)](https://github.com/iOfficeAI/OfficeCLI/releases)
  7. [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
  8. **English** | [中文](README_zh.md) | [日本語](README_ja.md) | [한국어](README_ko.md)
  9. <p align="center">
  10. <strong>🌐 Website:</strong> <a href="https://officecli.ai" target="_blank">officecli.ai</a> &nbsp;|&nbsp; <strong>💬 Community:</strong> <a href="https://discord.gg/2QAwJn7Egx" target="_blank">Discord</a>
  11. </p>
  12. <p align="center">
  13. <img src="assets/ppt-process.webp" alt="OfficeCLI creating a PowerPoint presentation on AionUi" width="100%">
  14. </p>
  15. <p align="center"><em>PPT creation process using OfficeCLI on <a href="https://github.com/iOfficeAI/AionUi">AionUi</a></em></p>
  16. <p align="center"><strong>PowerPoint Presentations</strong></p>
  17. <table>
  18. <tr>
  19. <td width="33%"><img src="assets/designwhatmovesyou.gif" alt="OfficeCLI design presentation (PowerPoint)"></td>
  20. <td width="33%"><img src="assets/horizon.gif" alt="OfficeCLI business presentation (PowerPoint)"></td>
  21. <td width="33%"><img src="assets/efforless.gif" alt="OfficeCLI tech presentation (PowerPoint)"></td>
  22. </tr>
  23. <tr>
  24. <td width="33%"><img src="assets/blackhole.gif" alt="OfficeCLI space presentation (PowerPoint)"></td>
  25. <td width="33%"><img src="assets/first-ppt-aionui.gif" alt="OfficeCLI gaming presentation (PowerPoint)"></td>
  26. <td width="33%"><img src="assets/shiba.gif" alt="OfficeCLI creative presentation (PowerPoint)"></td>
  27. </tr>
  28. </table>
  29. <p align="center">—</p>
  30. <p align="center"><strong>Word Documents</strong></p>
  31. <table>
  32. <tr>
  33. <td width="33%"><img src="assets/showcase/word1.gif" alt="OfficeCLI academic paper (Word)"></td>
  34. <td width="33%"><img src="assets/showcase/word2.gif" alt="OfficeCLI project proposal (Word)"></td>
  35. <td width="33%"><img src="assets/showcase/word3.gif" alt="OfficeCLI annual report (Word)"></td>
  36. </tr>
  37. </table>
  38. <p align="center">—</p>
  39. <p align="center"><strong>Excel Spreadsheets</strong></p>
  40. <table>
  41. <tr>
  42. <td width="33%"><img src="assets/showcase/excel1.gif" alt="OfficeCLI budget tracker (Excel)"></td>
  43. <td width="33%"><img src="assets/showcase/excel2.gif" alt="OfficeCLI gradebook (Excel)"></td>
  44. <td width="33%"><img src="assets/showcase/excel3.gif" alt="OfficeCLI sales dashboard (Excel)"></td>
  45. </tr>
  46. </table>
  47. <p align="center"><em>All documents above were created entirely by AI agents using OfficeCLI — no templates, no manual editing.</em></p>
  48. ## For AI Agents — Get Started in One Line
  49. Paste this into your AI agent's chat — it will read the skill file and install everything automatically:
  50. ```
  51. curl -fsSL https://officecli.ai/SKILL.md
  52. ```
  53. That's it. The skill file teaches the agent how to install the binary and use all commands.
  54. ## For Humans
  55. **Option A — GUI:** Install [**AionUi**](https://github.com/iOfficeAI/AionUi) — a desktop app that lets you create and edit Office documents through natural language, powered by OfficeCLI under the hood. Just describe what you want, and AionUi handles the rest.
  56. **Option B — CLI:** Download the binary for your platform from [GitHub Releases](https://github.com/iOfficeAI/OfficeCLI/releases), then run:
  57. ```bash
  58. officecli install
  59. ```
  60. This copies the binary to your PATH and installs the **officecli skill** into every AI coding agent it detects — Claude Code, Cursor, Windsurf, GitHub Copilot, and more. Your agent can immediately create, read, and edit Office documents on your behalf, no extra configuration needed.
  61. ## For Developers — See It Live in 30 Seconds
  62. ```bash
  63. # 1. Install (macOS / Linux) — or: brew install officecli / npm install -g @officecli/officecli
  64. curl -fsSL https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh | bash
  65. # Windows (PowerShell): irm https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1 | iex
  66. # 2. Create a blank PowerPoint
  67. officecli create deck.pptx
  68. # 3. Start live preview — opens http://localhost:26315 in your browser
  69. officecli watch deck.pptx
  70. # 4. Open another terminal, add a slide — watch the browser update instantly
  71. officecli add deck.pptx / --type slide --prop title="Hello, World!"
  72. ```
  73. That's it. Every `add`, `set`, or `remove` command you run will refresh the preview in real time. Keep experimenting — the browser is your live feedback loop.
  74. ## Quick Start
  75. ```bash
  76. # Create a presentation and add content
  77. officecli create deck.pptx
  78. officecli add deck.pptx / --type slide --prop title="Q4 Report" --prop background=1A1A2E
  79. officecli add deck.pptx '/slide[1]' --type shape \
  80. --prop text="Revenue grew 25%" --prop x=2cm --prop y=5cm \
  81. --prop font=Arial --prop size=24 --prop color=FFFFFF
  82. # View as outline
  83. officecli view deck.pptx outline
  84. # → Slide 1: Q4 Report
  85. # → Shape 1 [TextBox]: Revenue grew 25%
  86. # View as HTML — opens a rendered preview in your browser, no server needed
  87. officecli view deck.pptx html
  88. # Get structured JSON for any element
  89. officecli get deck.pptx '/slide[1]/shape[1]' --json
  90. # Save and close — flushes the resident session to disk
  91. officecli close deck.pptx
  92. ```
  93. ```json
  94. {
  95. "tag": "shape",
  96. "path": "/slide[1]/shape[1]",
  97. "attributes": {
  98. "name": "TextBox 1",
  99. "text": "Revenue grew 25%",
  100. "x": "720000",
  101. "y": "1800000"
  102. }
  103. }
  104. ```
  105. ## Why OfficeCLI?
  106. What used to take 50 lines of Python and 3 separate libraries:
  107. ```python
  108. from pptx import Presentation
  109. from pptx.util import Inches, Pt
  110. prs = Presentation()
  111. slide = prs.slides.add_slide(prs.slide_layouts[0])
  112. title = slide.shapes.title
  113. title.text = "Q4 Report"
  114. # ... 45 more lines ...
  115. prs.save('deck.pptx')
  116. ```
  117. Now takes one command:
  118. ```bash
  119. officecli add deck.pptx / --type slide --prop title="Q4 Report"
  120. ```
  121. **What OfficeCLI can do:**
  122. - **Create** documents from scratch -- blank or with content
  123. - **Read** text, structure, styles, formulas -- in plain text or structured JSON
  124. - **Analyze** formatting issues, style inconsistencies, and structural problems
  125. - **Modify** any element -- text, fonts, colors, layout, formulas, charts, images
  126. - **Reorganize** content -- add, remove, move, copy elements across documents
  127. | Format | Read | Modify | Create |
  128. |--------|------|--------|--------|
  129. | Word (.docx) | ✅ | ✅ | ✅ |
  130. | Excel (.xlsx) | ✅ | ✅ | ✅ |
  131. | PowerPoint (.pptx) | ✅ | ✅ | ✅ |
  132. **Word** — full [i18n & RTL support](https://github.com/iOfficeAI/OfficeCLI/wiki/i18n) (per-script font slots, per-script BCP-47 lang tags `lang.latin/ea/cs`, complex-script bold/italic/size, `direction=rtl` cascading through paragraph/run/section/table/style/header/footer/docDefaults, `rtlGutter` + `pgBorders` shorthand, locale-aware page numbering for Hindi/Arabic/Thai/CJK; `create --locale ar-SA` auto-enables RTL), [paragraphs](https://github.com/iOfficeAI/OfficeCLI/wiki/word-paragraph) (framePr, tabs shorthand, char-based indents), [runs](https://github.com/iOfficeAI/OfficeCLI/wiki/word-run) (underline.color, position half-pts), [tables](https://github.com/iOfficeAI/OfficeCLI/wiki/word-table) (virtual column ops add/remove/move/copyfrom, hMerge), [styles](https://github.com/iOfficeAI/OfficeCLI/wiki/word-style), [textbox](https://github.com/iOfficeAI/OfficeCLI/wiki/word-textbox) / [shape](https://github.com/iOfficeAI/OfficeCLI/wiki/word-shape) (textbox: rotation, `textDirection` `eaVert`/`vert270`, gradient, shadow, opacity), [headers/footers](https://github.com/iOfficeAI/OfficeCLI/wiki/word-header-footer), [images](https://github.com/iOfficeAI/OfficeCLI/wiki/word-picture) (PNG/JPG/GIF/SVG), [equations](https://github.com/iOfficeAI/OfficeCLI/wiki/word-equation) (LaTeX input), [diagrams](https://github.com/iOfficeAI/OfficeCLI/wiki/diagram) (mermaid → native editable shapes, or any mermaid type as a full-fidelity PNG), [comments](https://github.com/iOfficeAI/OfficeCLI/wiki/word-comment), [footnotes](https://github.com/iOfficeAI/OfficeCLI/wiki/word-footnote), [watermarks](https://github.com/iOfficeAI/OfficeCLI/wiki/word-watermark), [bookmarks](https://github.com/iOfficeAI/OfficeCLI/wiki/word-bookmark), [TOC](https://github.com/iOfficeAI/OfficeCLI/wiki/word-toc), [charts](https://github.com/iOfficeAI/OfficeCLI/wiki/word-chart), [hyperlinks](https://github.com/iOfficeAI/OfficeCLI/wiki/word-hyperlink), [sections](https://github.com/iOfficeAI/OfficeCLI/wiki/word-section), [form fields](https://github.com/iOfficeAI/OfficeCLI/wiki/word-formfield), [content controls (SDT)](https://github.com/iOfficeAI/OfficeCLI/wiki/word-sdt), [fields](https://github.com/iOfficeAI/OfficeCLI/wiki/word-field) (22 zero-param types + MERGEFIELD / REF / PAGEREF / SEQ / STYLEREF / DOCPROPERTY / IF), [OLE objects](https://github.com/iOfficeAI/OfficeCLI/wiki/word-ole), [revisions / tracked changes](https://github.com/iOfficeAI/OfficeCLI/wiki/word-revision) (`revision.type=ins\|del\|format\|moveFrom\|moveTo` + `revision.action=accept\|reject`, per-target `/revision[@author=Alice]` selector, tracked Find&Replace), page background color, [document properties](https://github.com/iOfficeAI/OfficeCLI/wiki/word-document)
  133. **Excel** — [cells](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-cell) (phonetic guide / furigana on add, Excel-UI `--shift left\|up` on remove / `shift=right\|down` on add), formulas (350+ built-in functions with auto-evaluation, spilling dynamic arrays with `_xlfn.` auto-prefix, financial / bond and statistical families, OFFSET/INDIRECT, defined-name formula bodies inlined at parse, formula-ref rewrite on row/col insert), [sheets](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-sheet) (visible/hidden/veryHidden, print margins, printTitleRows/Cols, RTL `sheetView`, cascade-aware sheet rename, empty-cell bloat filter on open), boolean `and`/`or` selectors (`row[Salary>5000 and Region=EMEA]`), [tables](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-table), [sort](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-sort) (sheet / range, multi-key, sidecar-aware), [conditional formatting](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-conditionalformatting), [charts](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-chart) (including box-whisker, [pareto](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-chart-add) with auto-sort + cumulative-%, log axis), [pivot tables](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-pivottable) (multi-field, date grouping, showDataAs, sort, grandTotals, subtotals, compact/outline/tabular layout, repeat item labels, blank rows, calculated fields, persistent `labelFilter` / `topN` filters, cache CoW + cross-pivot sharing), [slicers](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-slicer), [named ranges](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-namedrange), [data validation](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-validation), [images](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-picture) (PNG/JPG/GIF/SVG with dual-representation fallback), [sparklines](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-sparkline), [comments](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-comment) (RTL), [autofilter](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-autofilter), [shapes](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-shape), [OLE objects](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-ole), CSV/TSV import, `$Sheet:A1` cell addressing
  134. **PowerPoint** — [slides](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-slide) (header/footer/date/slidenum toggles, hidden), [shapes](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-shape) (pattern fill, blur effect, hyperlink tooltip + slide-jump links, **highlight color** on runs, `slideMaster`/`slideLayout` typed add/set/remove, arrow alias, effective.X + effective.X.src), [images](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-picture) (PNG/JPG/GIF/SVG, fill modes: stretch/contain/cover/tile, brightness/contrast/glow/shadow, rotation, link + tooltip), [tables](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-table) (built-in PowerPoint style catalogue, virtual `/col[C]` get + swap/copyFrom, row/col Move/CopyFrom, fill/background alias), [charts](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-chart) (pieOfPie, barOfPie, per-attr axisLine/gridline setters, series add/remove with theme palette, `anchor=x,y,w,h` shorthand), [animations](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-shape-set) (15 emphasis + 16 exit template-backed presets, multi-effect chains, motion-path presets, repeat/restart/autoReverse, chart animations + `chartBuild`), [transitions](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-morph-check) (morph + p14 + 12 p15 PowerPoint 2013+ presets), [3D models (.glb)](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-3dmodel) (combined `rotation=ax,ay,az`), [slide zoom](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-zoom), [equations](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-equation) (LaTeX input), [diagrams](https://github.com/iOfficeAI/OfficeCLI/wiki/diagram) (mermaid flowchart / sequence → native editable shapes, or any mermaid type as a full-fidelity PNG), [themes](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-theme), [connectors](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-connector) (`from`/`to` accept a full `/slide[N]/shape[@name=Foo]` path), [video/audio](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-video) (loop, autoStart), [groups](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-group) (link + tooltip; Get/Query/Add/Remove all descend into groups), [notes](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-notes) (RTL, lang), [comments](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-comment) (RTL, legacy + modern p188 threaded round-trip), SmartArt (round-trip via add-part + raw-set), [OLE objects](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-ole), [placeholders](https://github.com/iOfficeAI/OfficeCLI/wiki/ppt-placeholder) (add/set by phType)
  135. ## Use Cases
  136. **For Developers:**
  137. - Automate report generation from databases or APIs
  138. - Batch-process documents (bulk find/replace, style updates)
  139. - Build document pipelines in CI/CD environments (generate docs from test results)
  140. - Headless Office automation in Docker/containerized environments
  141. **For AI Agents:**
  142. - Generate presentations from user prompts (see examples above)
  143. - Extract structured data from documents to JSON
  144. - Validate and check document quality before delivery
  145. **For Teams:**
  146. - Clone document templates and populate with data
  147. - Automated document validation in CI/CD pipelines
  148. ## Installation
  149. Ships as a single self-contained binary. The .NET runtime is embedded -- nothing to install, no runtime to manage.
  150. **One-line install:**
  151. ```bash
  152. # macOS / Linux
  153. curl -fsSL https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh | bash
  154. # Windows (PowerShell)
  155. irm https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1 | iex
  156. ```
  157. **Or via a package manager:**
  158. ```bash
  159. # Homebrew (macOS / Linux)
  160. brew install officecli
  161. # Scoop (Windows)
  162. scoop install officecli
  163. # npm (all platforms — fetches the native binary for your platform)
  164. npm install -g @officecli/officecli
  165. ```
  166. **Or download manually** from [GitHub Releases](https://github.com/iOfficeAI/OfficeCLI/releases):
  167. | Platform | Binary |
  168. |----------|--------|
  169. | macOS Apple Silicon | `officecli-mac-arm64` |
  170. | macOS Intel | `officecli-mac-x64` |
  171. | Linux x64 | `officecli-linux-x64` |
  172. | Linux ARM64 | `officecli-linux-arm64` |
  173. | Windows x64 | `officecli-win-x64.exe` |
  174. | Windows ARM64 | `officecli-win-arm64.exe` |
  175. Verify installation: `officecli --version`
  176. **Or self-install from a downloaded binary (or run bare `officecli` to auto-install):**
  177. ```bash
  178. officecli install # explicit
  179. officecli # bare invocation also triggers install
  180. ```
  181. Updates are checked automatically in the background. Disable with `officecli config autoUpdate false` or skip per-invocation with `OFFICECLI_SKIP_UPDATE=1`. Configuration lives under `~/.officecli/config.json`.
  182. ## Key Features
  183. ### Built-in Engines & Generation Primitives
  184. OfficeCLI is self-contained. The capabilities below ship inside the binary — **no Office required**.
  185. #### Rendering engine — high-fidelity, built-in
  186. OfficeCLI's keystone: a from-scratch, high-fidelity HTML rendering engine that lets an AI agent *see* the rendered document instead of guessing from the DOM. It covers shapes, charts (trendlines, error bars, waterfall, candlestick, sparklines), equations (OMML → LaTeX, rendered with KaTeX), 3D `.glb` models via Three.js, morph transitions, slide zoom, and shape effects. Per-page PNG screenshots are produced by piping the rendered HTML through a headless browser. Three modes:
  187. - **`view html`** — standalone HTML file, assets inlined. Open in any browser.
  188. - **`view screenshot`** — per-page PNG, ready for multimodal agents to read.
  189. - **`watch`** — local HTTP server with auto-refreshing preview; every `add` / `set` / `remove` updates the browser instantly. Excel watch supports inline cell editing and drag-to-reposition charts.
  190. ```bash
  191. officecli view deck.pptx html -o /tmp/deck.html
  192. officecli view deck.pptx screenshot -o /tmp/deck.png # add --page 1-N for more slides
  193. officecli watch deck.pptx # http://localhost:26315
  194. ```
  195. > Without visualization, an agent generating slides is flying blind — it can read the DOM but can't tell if the title overflows or two shapes overlap. Because rendering is built into the binary, the *render → look → fix* loop works in CI, in Docker, on a server with no display — anywhere the binary runs.
  196. #### Formula & pivot engine
  197. 350+ built-in Excel functions evaluated automatically on write — write `=SUM(A1:A2)`, `get` the cell, the value is already there. No round-trip through Office to recalc. Covers spilling dynamic arrays (`FILTER` / `SORT` / `UNIQUE` / `SEQUENCE` / `LET` / `LAMBDA` / `MAP`), `VLOOKUP` / `XLOOKUP` / `INDEX` / `MATCH`, financial & bond math (`XIRR` / `PRICE` / `YIELD` / `DURATION` / `COUPNUM`), statistical distributions, tests & regression (`NORM.DIST` / `T.TEST` / `LINEST`), and date & text functions.
  198. Plus native OOXML pivot tables from a source range with one command — multi-field rows/cols/filters, 10 aggregations, `showDataAs` modes, date grouping, calculated fields, top-N, layouts. Pivot cache + definition are written to OOXML, so Excel opens the file with the aggregation already populated:
  199. ```bash
  200. officecli add sales.xlsx '/Sheet1' --type pivottable \
  201. --prop source='Data!A1:E10000' --prop rows='Region,Category' \
  202. --prop cols=Quarter --prop values='Revenue:sum,Units:avg' \
  203. --prop showDataAs=percentOfTotal
  204. ```
  205. #### Template merge — generate once, fill many
  206. `merge` replaces `{{key}}` placeholders in any `.docx` / `.xlsx` / `.pptx` with JSON data — across paragraphs, table cells, shapes, headers, footers, and chart titles. Agent designs the layout once (expensive); production code fills it N times (cheap, deterministic, zero token cost). Avoids the failure mode where an agent regenerates each report from scratch and produces N inconsistent layouts.
  207. ```bash
  208. officecli merge invoice-template.docx out-001.docx --data '{"client":"Acme","total":"$5,200"}'
  209. officecli merge q4-template.pptx q4-acme.pptx --data data.json
  210. ```
  211. #### Round-trip dump — learn from existing docs
  212. `dump` serializes any `.docx`, `.pptx`, or `.xlsx` — whole document **or any subtree** (a single paragraph, table, slide, worksheet, the styles part, numbering, theme, or settings) — into a replayable batch JSON; `batch` replays it. Given a sample the user wants to imitate, an agent reads the structured spec instead of raw OOXML XML, mutates, and replays. Bridges "I have an existing template" and "generate me 100 variations."
  213. ```bash
  214. officecli dump existing.docx -o blueprint.json # whole document
  215. officecli dump existing.docx /body/tbl[1] -o table.json # any subtree
  216. officecli dump existing.xlsx /Sheet1 -o sheet.json # a single worksheet
  217. officecli batch new.docx --input blueprint.json
  218. ```
  219. ### Resident Mode & Batch
  220. For multi-step workflows, resident mode keeps the document in memory. Batch mode applies multiple operations in a single pass.
  221. ```bash
  222. # Resident mode — near-zero latency via named pipes
  223. officecli open report.docx
  224. officecli set report.docx /body/p[1]/r[1] --prop bold=true
  225. officecli set report.docx /body/p[2]/r[1] --prop color=FF0000
  226. officecli close report.docx
  227. # Batch mode — multi-command execution (atomic by default: any failed item rolls back the whole batch)
  228. echo '[{"command":"set","path":"/slide[1]/shape[1]","props":{"text":"Hello"}},
  229. {"command":"set","path":"/slide[1]/shape[2]","props":{"fill":"FF0000"}}]' \
  230. | officecli batch deck.pptx --json
  231. # Inline batch with --commands (no stdin needed)
  232. officecli batch deck.pptx --commands '[{"op":"set","path":"/slide[1]/shape[1]","props":{"text":"Hi"}}]'
  233. # Keep whatever succeeds even if some items fail (pre-1.0.137 behavior)
  234. officecli batch deck.pptx --input updates.json --best-effort --json
  235. # Stop at the first failing command instead of running the rest (still rolls back everything unless combined with --best-effort)
  236. officecli batch deck.pptx --input updates.json --stop-on-error --json
  237. ```
  238. > **Reading the file with another tool? Flush to disk first.**
  239. > officecli's own reads (`get`/`query`/`view`) always see your latest edits, so within officecli you never need to save. But a live resident defers the disk write, so **before a non‑officecli program reads the file** — python‑docx/openpyxl, Microsoft Word, a renderer, delivery/upload — flush it:
  240. > ```bash
  241. > officecli set report.docx /body/p[1] --prop bold=true
  242. > officecli save report.docx # flush, keep the resident warm (or `close` to flush + release)
  243. > python my_reader.py report.docx # now sees the edit
  244. > ```
  245. > A live resident also auto‑flushes shortly after going idle (adaptive 2–10s, scaled to the document's measured save cost). For a pipeline where another program reads after every command, set `OFFICECLI_RESIDENT_FLUSH=each` — every mutation is on disk before the command returns, while the resident stays warm. Full flush model (`each`/`auto`/fixed/`off`, save / close, env tuning): [wiki → open / close](https://github.com/iOfficeAI/OfficeCLI/wiki/command-open#when-the-file-on-disk-is-refreshed).
  246. ### Three-Layer Architecture
  247. Start simple, go deep only when needed.
  248. | Layer | Purpose | Commands |
  249. |-------|---------|----------|
  250. | **L1: Read** | Semantic views of content | `view` (text, annotated, outline, stats, issues, html, svg, screenshot) |
  251. | **L2: DOM** | Structured element operations | `get`, `query`, `set`, `add`, `remove`, `move`, `swap` |
  252. | **L3: Raw XML** | Direct XPath access — universal fallback | `raw`, `raw-set`, `add-part`, `validate` |
  253. ```bash
  254. # L1 — high-level views
  255. officecli view report.docx annotated
  256. officecli view budget.xlsx text --cols A,B,C --max-lines 50
  257. # L2 — element-level operations
  258. officecli query report.docx "run:contains(TODO)"
  259. officecli add budget.xlsx / --type sheet --prop name="Q2 Report"
  260. officecli move report.docx /body/p[5] --to /body --index 1
  261. # L3 — raw XML when L2 isn't enough
  262. officecli raw deck.pptx '/slide[1]'
  263. officecli raw-set report.docx document \
  264. --xpath "//w:p[1]" --action append \
  265. --xml '<w:r><w:t>Injected text</w:t></w:r>'
  266. ```
  267. ## AI Integration
  268. ### MCP Server
  269. Built-in [MCP](https://modelcontextprotocol.io) server — register with one command:
  270. ```bash
  271. officecli mcp claude # Claude Code
  272. officecli mcp cursor # Cursor
  273. officecli mcp vscode # VS Code / Copilot
  274. officecli mcp lmstudio # LM Studio
  275. officecli mcp opencode # OpenCode
  276. officecli mcp list # Check registration status
  277. ```
  278. Exposes all document operations as tools over JSON-RPC — no shell access needed.
  279. ### Direct CLI Integration
  280. Get OfficeCLI working with your AI agent in two steps:
  281. 1. **Install the binary** -- one command (see [Installation](#installation))
  282. 2. **Done.** OfficeCLI automatically detects your AI tools (Claude Code, GitHub Copilot, Codex) by checking known config directories and installs its skill file. Your agent can immediately create, read, and modify any Office document.
  283. <details>
  284. <summary><strong>Manual setup (optional)</strong></summary>
  285. If auto-install doesn't cover your setup, you can install the skill file manually:
  286. **Feed SKILL.md to your agent directly:**
  287. ```bash
  288. curl -fsSL https://officecli.ai/SKILL.md
  289. ```
  290. **Install as a local skill for Claude Code:**
  291. ```bash
  292. curl -fsSL https://officecli.ai/SKILL.md -o ~/.claude/skills/officecli.md
  293. ```
  294. **Other agents:** Include the contents of `SKILL.md` in your agent's system prompt or tool description.
  295. </details>
  296. ### Why your agent will thrive on OfficeCLI
  297. - **Deterministic JSON output** — every command supports `--json` with consistent schemas. No regex parsing, no scraping stdout.
  298. - **Path-based addressing** — every element has a stable path (`/slide[1]/shape[2]`). Agents navigate documents without understanding XML namespaces. (OfficeCLI syntax: 1-based indexing, element local names — not XPath.)
  299. - **Progressive complexity (L1 → L2 → L3)** — agents start with read-only views, escalate to DOM ops, fall back to raw XML only when needed. Minimizes token usage.
  300. - **Self-healing workflow** — `validate`, `view issues`, and the structured error codes (`not_found`, `invalid_value`, `unsupported_property`) return suggestions and valid ranges. Agents self-correct without human intervention.
  301. - **Built-in agent-friendly rendering engine** — `view html` / `view screenshot` / `watch` emit HTML and PNG natively. No Office required. Agents can *see* their output and fix layout issues, even inside CI / Docker / headless environments.
  302. - **Built-in formula & pivot engine** — 350+ Excel functions auto-evaluated on write (incl. spilling dynamic arrays, financial / bond and statistical families); native OOXML pivot tables from a source range with one command. Agents read computed values and shipped aggregations immediately, without round-tripping through Office.
  303. - **Template merge** — agent designs the layout once, downstream code fills `{{key}}` placeholders N times. Avoids burning tokens regenerating every report from scratch.
  304. - **Round-trip dump** — `dump` turns any `.docx`, `.pptx`, or `.xlsx` into replayable batch JSON. Agents learn from human-authored samples by reading a structured spec, not raw OOXML XML.
  305. - **Built-in help** — when unsure about property names or value formats, the agent runs `officecli <format> set <element>` instead of guessing.
  306. - **Auto-install** — OfficeCLI detects your AI tooling (Claude Code, Cursor, VS Code, …) and configures itself. No manual skill-file setup.
  307. ### Built-in Help
  308. Don't guess property names — drill into the help:
  309. ```bash
  310. officecli help pptx set # All settable elements and properties
  311. officecli help pptx set shape # Detail for one element type
  312. officecli help docx query # Selector reference: attributes, :contains, :has(), etc.
  313. ```
  314. Run `officecli --help` for the full overview.
  315. ### JSON Output Schemas
  316. All commands support `--json`. The general response shapes:
  317. **Single element** (`get --json`):
  318. ```json
  319. {"tag": "shape", "path": "/slide[1]/shape[1]", "attributes": {"name": "TextBox 1", "text": "Hello"}}
  320. ```
  321. **List of elements** (`query --json`):
  322. ```json
  323. [
  324. {"tag": "paragraph", "path": "/body/p[1]", "attributes": {"style": "Heading1", "text": "Title"}},
  325. {"tag": "paragraph", "path": "/body/p[5]", "attributes": {"style": "Heading1", "text": "Summary"}}
  326. ]
  327. ```
  328. **Errors** return a non-zero exit code with a structured error object including error code, suggestion, and valid values when available:
  329. ```json
  330. {
  331. "success": false,
  332. "error": {
  333. "error": "Slide 50 not found (total: 8)",
  334. "code": "not_found",
  335. "suggestion": "Valid Slide index range: 1-8"
  336. }
  337. }
  338. ```
  339. Error codes: `not_found`, `invalid_value`, `unsupported_property`, `invalid_path`, `unsupported_type`, `missing_property`, `file_not_found`, `file_locked`, `invalid_selector`. Property names are auto-corrected -- misspelling a property returns a suggestion with the closest match.
  340. **Error Recovery** -- Agents self-correct by inspecting available elements:
  341. ```bash
  342. # Agent tries an invalid path
  343. officecli get report.docx /body/p[99] --json
  344. # Returns: {"success": false, "error": {"error": "...", "code": "not_found", "suggestion": "..."}}
  345. # Agent self-corrects by checking available elements
  346. officecli get report.docx /body --depth 1 --json
  347. # Returns the list of available children, agent picks the right path
  348. ```
  349. **Mutation confirmations** (`set`, `add`, `remove`, `move`, `create` with `--json`):
  350. ```json
  351. {"success": true, "path": "/slide[1]/shape[1]"}
  352. ```
  353. **Exit codes.** `0` — the operation landed. `1` — it did not (process or business failure; the envelope carries `error`). `2` — it ran with caveats: an `unsupported_property` was dropped, or a validator raised a warning. Exit 2 covers both "landed with a warning" (`success: true`) and "nothing applied" (`success: false`, e.g. every property refused), so scripts must read `success` in the envelope, not the exit code alone; `warnings[]` lists what was dropped. The MCP server derives `isError` from the envelope the same way.
  354. ## Comparison
  355. | | OfficeCLI | Microsoft Office | LibreOffice | python-docx / openpyxl |
  356. |---|---|---|---|---|
  357. | Open source & free | ✓ (Apache 2.0) | ✗ (paid license) | ✓ | ✓ |
  358. | AI-native CLI + JSON | ✓ | ✗ | ✗ | ✗ |
  359. | Zero install (single binary) | ✓ | ✗ | ✗ | ✗ (Python + pip) |
  360. | Call from any language | ✓ (CLI) | ✗ (COM/Add-in) | ✗ (UNO API) | Python only |
  361. | Path-based element access | ✓ | ✗ | ✗ | ✗ |
  362. | Raw XML fallback | ✓ | ✗ | ✗ | Partial |
  363. | Built-in agent-friendly rendering engine | ✓ | ✗ | ✗ | ✗ |
  364. | Headless HTML/PNG output | ✓ | ✗ | Partial | ✗ |
  365. | Template merge (`{{key}}`) across formats | ✓ | ✗ | ✗ | ✗ |
  366. | Round-trip dump → batch JSON | ✓ | ✗ | ✗ | ✗ |
  367. | Live preview (auto-refresh on edit) | ✓ | ✗ | ✗ | ✗ |
  368. | Headless / CI | ✓ | ✗ | Partial | ✓ |
  369. | Cross-platform | ✓ | Windows/Mac | ✓ | ✓ |
  370. | Word + Excel + PowerPoint | ✓ | ✓ | ✓ | Separate libs |
  371. ## Command Reference
  372. | Command | Description |
  373. |---------|-------------|
  374. | [`create`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-create) | Create a blank .docx, .xlsx, or .pptx (type from extension) |
  375. | [`view`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-view) | View content (modes: `outline`, `text`, `annotated`, `stats` (`--page-count`), `issues`, `html`, `svg`, `screenshot`, `pdf` (via exporter plugin), `forms` (via format-handler plugin)). docx supports `--render auto\|native\|html`. |
  376. | [`load_skill`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-skills) | Print embedded SKILL.md content for a specialized skill (no install) |
  377. | [`get`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-get) | Get element and children (`--depth N`, `--json`) |
  378. | [`query`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-query) | CSS-like query with boolean `and`/`or`, row-by-column-name (`row[Salary>5000]`), `--find` flag |
  379. | [`set`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-set) | Modify element properties; accepts selectors and Excel-native paths (parity with `get`/`query`), `--find`/`--replace` flags |
  380. | [`add`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-add) | Add element (or clone with `--from <path>`) |
  381. | [`remove`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-remove) | Remove an element |
  382. | [`move`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-move) | Move element (`--to <parent>`, `--index N`, `--after <path>`, `--before <path>`) |
  383. | [`swap`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-swap) | Swap two elements |
  384. | [`validate`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-validate) | Validate against OpenXML schema |
  385. | `view <file> issues` | Enumerate document issues (text overflow, missing alt text, formula errors, ...) |
  386. | [`batch`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-batch) | Multiple operations applied in a single pass (stdin, `--input`, or `--commands`; atomic by default — any failed item rolls back the whole batch — `--best-effort` to keep partial progress, `--stop-on-error` to abort early) |
  387. | [`dump`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-dump) | Serialize a `.docx`, `.pptx`, or `.xlsx` into a replayable batch JSON (round-trip via `batch`); accepts a subtree path |
  388. | [`refresh`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-refresh) | Recalculate TOC page numbers / `PAGE` / cross-references (`.docx`; Word backend on Windows, headless-HTML fallback) |
  389. | [`plugins`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-plugins) | List / inspect / lint installed plugins (extend to `.doc`, `.hwpx`, `.pdf` export via dump-reader / exporter / format-handler kinds) |
  390. | [`merge`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-merge) | Template merge — replace `{{key}}` placeholders with JSON data |
  391. | [`watch`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-watch) | Live HTML preview in browser with auto-refresh |
  392. | [`mcp`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-mcp) | Start MCP server for AI tool integration |
  393. | [`raw`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-raw) | View raw XML of a document part |
  394. | [`raw-set`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-raw) | Modify raw XML via XPath |
  395. | `add-part` | Add a new document part (header, chart, etc.) |
  396. | [`open`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-open) | Start resident mode (keep document in memory) |
  397. | `close` | Save and close resident mode |
  398. | [`install`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-install) | Install binary + skills + MCP (`all`, `claude`, `cursor`, etc.) |
  399. | `config` | Get or set configuration |
  400. | `help <format> <command>` | [Built-in help](https://github.com/iOfficeAI/OfficeCLI/wiki/command-reference) (e.g. `officecli help pptx set shape`) |
  401. ## End-to-End Workflow Example
  402. A typical self-healing agent workflow: create a presentation, populate it, verify, and fix issues -- all without human intervention.
  403. ```bash
  404. # 1. Create
  405. officecli create report.pptx
  406. # 2. Add content
  407. officecli add report.pptx / --type slide --prop title="Q4 Results"
  408. officecli add report.pptx '/slide[1]' --type shape \
  409. --prop text="Revenue: $4.2M" --prop x=2cm --prop y=5cm --prop size=28
  410. officecli add report.pptx / --type slide --prop title="Details"
  411. officecli add report.pptx '/slide[2]' --type shape \
  412. --prop text="Growth driven by new markets" --prop x=2cm --prop y=5cm
  413. # 3. Verify
  414. officecli view report.pptx outline
  415. officecli validate report.pptx
  416. # 4. Fix any issues found
  417. officecli view report.pptx issues --json
  418. # Address issues based on output, e.g.:
  419. officecli set report.pptx '/slide[1]/shape[1]' --prop font=Arial
  420. ```
  421. ### Units & Colors
  422. All dimension and color properties accept flexible input formats:
  423. | Type | Accepted formats | Examples |
  424. |------|-----------------|----------|
  425. | **Dimensions** | cm, in, pt, px, or raw EMU | `2cm`, `1in`, `72pt`, `96px`, `914400` |
  426. | **Colors** | Hex, named, RGB, theme | `#FF0000`, `FF0000`, `red`, `rgb(255,0,0)`, `accent1` |
  427. | **Font sizes** | Bare number or pt-suffixed | `14`, `14pt`, `10.5pt` |
  428. | **Spacing** | pt, cm, in, or multiplier | `12pt`, `0.5cm`, `1.5x`, `150%` |
  429. ## Common Patterns
  430. ```bash
  431. # Replace all Heading1 text in a Word doc
  432. officecli query report.docx "paragraph[style=Heading1]" --json | ...
  433. officecli set report.docx /body/p[1]/r[1] --prop text="New Title"
  434. # Export all slide content as JSON
  435. officecli get deck.pptx / --depth 2 --json
  436. # Bulk-update Excel cells
  437. officecli batch budget.xlsx --input updates.json --json
  438. # Import CSV data into an Excel sheet
  439. officecli add budget.xlsx / --type sheet --prop name="Q1 Data"
  440. officecli import budget.xlsx "/Q1 Data" sales.csv --header
  441. # Template merge for batch reports
  442. officecli merge invoice-template.docx invoice-001.docx --data '{"client":"Acme","total":"$5,200"}'
  443. # Check document quality before delivery
  444. officecli validate report.docx && officecli view report.docx issues --json
  445. ```
  446. **From Python or Node.js** — install one of the thin resident-pipe SDKs (no per-call process spawn):
  447. ```python
  448. # Python — `pip install officecli-sdk`
  449. import officecli
  450. with officecli.create("deck.pptx") as doc: # or officecli.open("deck.pptx")
  451. doc.send({"command": "add", "parent": "/", "type": "slide"})
  452. print(doc.send({"command": "get", "path": "/slide[1]"}))
  453. ```
  454. ```javascript
  455. // Node.js — `npm install @officecli/sdk`
  456. const oc = require("@officecli/sdk");
  457. const doc = await oc.create("deck.pptx"); // or oc.open("deck.pptx")
  458. await doc.send({ command: "add", parent: "/", type: "slide" });
  459. console.log(await doc.send({ command: "get", path: "/slide[1]" }));
  460. await doc.close();
  461. ```
  462. Both SDKs auto-provision the native CLI when missing (mirror-first, Windows-capable) and announce the install rather than doing it silently.
  463. Or wrap subprocess directly, one-shot:
  464. ```python
  465. import json, subprocess
  466. def cli(*args):
  467. return json.loads(subprocess.check_output(["officecli", *args, "--json"], text=True))
  468. cli("create", "deck.pptx")
  469. ```
  470. ## Documentation
  471. The [Wiki](https://github.com/iOfficeAI/OfficeCLI/wiki) has detailed guides for every command, element type, and property:
  472. - **By format:** [Word](https://github.com/iOfficeAI/OfficeCLI/wiki/word-reference) | [Excel](https://github.com/iOfficeAI/OfficeCLI/wiki/excel-reference) | [PowerPoint](https://github.com/iOfficeAI/OfficeCLI/wiki/powerpoint-reference)
  473. - **Workflows:** [End-to-end examples](https://github.com/iOfficeAI/OfficeCLI/wiki/workflows) -- Word reports, Excel dashboards, PowerPoint decks, batch modifications, resident mode
  474. - **Runnable examples:** [examples/](examples/) -- copy-paste scripts (.sh/.py) for Word, Excel, and PowerPoint, with output files included
  475. - **Troubleshooting:** [Common errors and solutions](https://github.com/iOfficeAI/OfficeCLI/wiki/troubleshooting)
  476. - **AI agent guide:** [Decision tree for navigating the wiki](https://github.com/iOfficeAI/OfficeCLI/wiki/agent-guide)
  477. ## Build from Source
  478. Requires [.NET 10 SDK](https://dotnet.microsoft.com/download) for compilation only. The output is a self-contained, native binary -- .NET is embedded in the binary and is not needed at runtime.
  479. ```bash
  480. ./build.sh
  481. ```
  482. ## License
  483. [Apache License 2.0](LICENSE)
  484. Bug reports and contributions are welcome on [GitHub Issues](https://github.com/iOfficeAI/OfficeCLI/issues).
  485. ---
  486. If you find OfficeCLI useful, please [give it a star on GitHub](https://github.com/iOfficeAI/OfficeCLI) — it helps others discover the project.
  487. [OfficeCLI.AI](https://OfficeCLI.AI) | [GitHub](https://github.com/iOfficeAI/OfficeCLI)
  488. <!--
  489. yaml-frontmatter:
  490. name: officecli
  491. version: see GitHub Releases
  492. description: The standard CLI for AI agents to create, read, and modify Office documents
  493. formats: [docx, xlsx, pptx]
  494. platforms: [macos, linux, windows]
  495. license: Apache-2.0
  496. keywords: [office, cli, ai-agent, automation, docx, xlsx, pptx, openxml, document-generation, mcp-server, word, excel, powerpoint]
  497. ai-agent-compatible: true
  498. mcp-server: true
  499. skill-file: SKILL.md
  500. install-command-unix: curl -fsSL https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh | bash
  501. install-command-windows: irm https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1 | iex
  502. -->
  503. <!-- LLM/agent discovery metadata
  504. tool: officecli
  505. type: cli
  506. canonical: the standard CLI for AI-driven Office document manipulation
  507. formats: docx, xlsx, pptx
  508. capabilities: create, read, modify, validate, batch, resident-mode, mcp-server, live-preview, auto-install
  509. output: json, text, annotated
  510. platforms: macos, linux, windows
  511. license: Apache-2.0
  512. keywords: office, cli, ai-agent, automation, docx, xlsx, pptx, openxml, document-generation, mcp-server, word, excel, powerpoint, ai-tools, command-line, structured-output
  513. ai-agent-compatible: true
  514. mcp-server: true
  515. skill-file: SKILL.md
  516. skill-file-lines: 403
  517. alternatives: python-docx, openpyxl, python-pptx, libreoffice --headless
  518. install-command-unix: curl -fsSL https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh | bash
  519. install-command-windows: irm https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1 | iex
  520. -->
sdk/node/index.js · Bundled script · 644 lines · 2 findings marked
  1. 'use strict';
  2. /*
  3. * officecli — a thin Node.js shell over officecli's resident pipe.
  4. *
  5. * Node port of sdk/python/officecli.py. Same one job: forward a command to the
  6. * running resident over its named pipe and hand back the response. There is NO
  7. * second vocabulary: a command is the same object you'd put in an officecli
  8. * `batch` list — e.g. {command:"set", path:"/Sheet1/A1", props:{text:"Hello"}}.
  9. * `send` forwards one; `batch` forwards many in a single round-trip.
  10. *
  11. * Two surfaces, by design:
  12. * - bootstrap (infrequent): create() / open() spawn ONE CLI process — a file
  13. * that isn't open yet has no resident to talk to.
  14. * - everything else (the hot path): send() / batch() are pure pipe
  15. * round-trips, no per-command process spawn.
  16. *
  17. * const oc = require('@officecli/sdk');
  18. * const doc = await oc.create('report.xlsx', ['--force']);
  19. * try {
  20. * await doc.send({ command: 'set', path: '/Sheet1/A1', props: { text: 'Hello' } });
  21. * console.log(await doc.send({ command: 'get', path: '/Sheet1/A1' }));
  22. * } finally {
  23. * await doc.close();
  24. * }
  25. * // or `await using doc = await oc.open('existing.xlsx')` on Node >= 24.
  26. *
  27. * Protocol (matches ResidentServer.cs / ResidentClient.cs):
  28. * - pipe name : officecli-<SHA256(fullpath)[:16] uppercase>;
  29. * fullpath upper-cased on macOS/Windows, left as-is on Linux.
  30. * - unix path : $TMPDIR/CoreFxPipe_<name> (+ "-ping"); $TMPDIR else /tmp
  31. * - win path : \\.\pipe\<name> (+ "-ping")
  32. * - framing : one request line + one response line, UTF-8, '\n' terminated;
  33. * one connection == one command. The reply may carry a UTF-8 BOM
  34. * (unix StreamWriter) and a trailing '\r' — both stripped here.
  35. * - request : PascalCase {"Command","Args","Props","Json"}
  36. * - response : {"ExitCode","Stdout","Stderr"}
  37. */
  38. const os = require('os');
  39. const net = require('net');
  40. const path = require('path');
  41. const fs = require('fs');
  42. const crypto = require('crypto');
  43. const { spawnSync } = require('child_process');
  44. const IS_WIN = process.platform === 'win32';
  45. const IS_MAC = process.platform === 'darwin';
  46. // Mirror officecli's TryResident busy-delivery policy (CommandBuilder.cs): a
  47. // generous connect timeout + a few retries with backoff, applied identically to
  48. // every command. The reply read itself blocks (no timeout) — like officecli's
  49. // PipeReadLine — trusting the resident to answer once our turn comes up in its
  50. // serialized queue. Retries only re-attempt the CONNECT (before the command
  51. // executes), so re-sending is safe even for mutations: there is no "read timed
  52. // out, resend" path that could double-apply.
  53. const BUSY_CONNECT_TIMEOUT_MS = 30000; // = ResidentBusyConnectTimeoutMs
  54. const BUSY_MAX_RETRIES = 3; // = ResidentBusyMaxRetries
  55. // = CommandBuilder's DefaultOpenIdleSeconds. open() upgrades a reused resident
  56. // (which create() may have auto-started with a short 60s timeout) to the 12min
  57. // interactive window, so a long session over an SDK handle isn't cut short.
  58. const OPEN_IDLE_SECONDS = 12 * 60;
  59. // Installer scripts: the d.officecli.ai mirror is primary; GitHub raw is only a
  60. // fallback (same order as install.sh / install-binary.js). The mirror is
  61. // Cloudflare-fronted and reachable where raw.githubusercontent.com may be
  62. // rate-limited or blocked.
  63. const INSTALL_SH_MIRROR = 'https://d.officecli.ai/install.sh';
  64. const INSTALL_SH_GITHUB = 'https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh';
  65. const INSTALL_PS1_MIRROR = 'https://d.officecli.ai/install.ps1';
  66. const INSTALL_PS1_GITHUB = 'https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1';
  67. const MISSING_CLI =
  68. "officecli CLI not found: {bin} is not on PATH nor in the default install " +
  69. 'location (~/.local/bin, or %LOCALAPPDATA%\\OfficeCLI on Windows). This SDK only ' +
  70. 'forwards commands to the officecli binary, which must be installed separately. Install it:\n' +
  71. ' node -e "require(\'@officecli/sdk\').install()" # runs the official installer\n' +
  72. ' # or: curl -fsSL ' + INSTALL_SH_MIRROR + ' | bash\n' +
  73. ' # (npm i @officecli/sdk already pulls @officecli/officecli, which bundles the binary)\n' +
  74. 'Already installed elsewhere? pass { binary: "/path/to/officecli" }.';
  75. /**
  76. * Raised on transport/process failure (could not reach the resident). Business
  77. * outcomes are NOT exceptions — they live in the returned envelope's `success`
  78. * field, same as the CLI's exit code.
  79. */
  80. class OfficeCliError extends Error {
  81. constructor(code, msg) {
  82. super(`[exit ${code}] ${msg}`);
  83. this.name = 'OfficeCliError';
  84. this.code = code;
  85. }
  86. }
  87. // ---------------------------------------------------------------- pipe address
  88. function dotnetTempDir() {
  89. // Mirror .NET Path.GetTempPath() on Unix exactly: $TMPDIR else /tmp.
  90. return process.env.TMPDIR || '/tmp';
  91. }
  92. // Match the path officecli's resident hashes into the pipe name. On Windows it
  93. // derives the name from GetFullPath, which expands 8.3 short components (e.g.
  94. // RUNNER~1, or any user name > 8 chars under %TEMP%) to their long form.
  95. // path.resolve does NOT expand 8.3, so a short path would hash to a different
  96. // pipe and every connect fails with ENOENT — hence realpath, which does expand
  97. // it. realpath needs the file to exist; fall back to the resolved path when it
  98. // doesn't (e.g. pre-create). realpath ALSO resolves symlinks/junctions, which
  99. // GetFullPath does not; harmless here because we hand this resolved path to the
  100. // resident, so the server's GetFullPath sees the already-resolved string and
  101. // both sides hash the same thing. Windows only — on Linux/macOS officecli uses
  102. // GetFullPath (no symlink resolution), so realpath would diverge there
  103. // (e.g. /tmp → /private/tmp on macOS).
  104. function canonicalPath(filePath) {
  105. const resolved = path.resolve(filePath);
  106. if (IS_WIN) {
  107. try { return fs.realpathSync.native(resolved); } catch (_) { /* not there yet */ }
  108. }
  109. return resolved;
  110. }
  111. /** [main, ping] pipe addresses for a document path. Exposed for debugging. */
  112. function pipePaths(filePath) {
  113. let full = canonicalPath(filePath);
  114. if (IS_MAC || IS_WIN) full = full.toUpperCase(); // Linux: case-sensitive, no upper
  115. const h = crypto.createHash('sha256').update(full, 'utf8').digest('hex').toUpperCase().slice(0, 16);
  116. const name = `officecli-${h}`;
  117. if (IS_WIN) return [`\\\\.\\pipe\\${name}`, `\\\\.\\pipe\\${name}-ping`];
  118. const base = path.join(dotnetTempDir(), `CoreFxPipe_${name}`);
  119. return [base, base + '-ping'];
  120. }
  121. // ---------------------------------------------------------------- transport
  122. function sleep(ms) {
  123. return new Promise((r) => setTimeout(r, ms));
  124. }
  125. // One attempt: bound the CONNECT, then block on the reply (no read timeout) —
  126. // exactly like officecli's TrySend (Connect(timeout) + blocking PipeReadLine).
  127. function sendOnce(sockPath, line, connectTimeoutMs) {
  128. return new Promise((resolve, reject) => {
  129. let settled = false;
  130. const chunks = [];
  131. const socket = net.createConnection(sockPath);
  132. const connTimer = setTimeout(() => {
  133. if (settled) return;
  134. settled = true;
  135. socket.destroy();
  136. reject(new Error(`connect timed out after ${connectTimeoutMs}ms`));
  137. }, connectTimeoutMs);
  138. const fail = (err) => {
  139. if (settled) return;
  140. settled = true;
  141. clearTimeout(connTimer);
  142. socket.destroy();
  143. reject(err);
  144. };
  145. socket.once('connect', () => {
  146. clearTimeout(connTimer); // connected: stop bounding; reply read blocks
  147. socket.write(line);
  148. });
  149. socket.on('data', (d) => {
  150. chunks.push(d);
  151. // Line protocol: the reply is one '\n'-terminated line.
  152. if (d.length && d[d.length - 1] === 0x0a) {
  153. if (settled) return;
  154. settled = true;
  155. clearTimeout(connTimer);
  156. socket.end();
  157. resolve(Buffer.concat(chunks));
  158. }
  159. });
  160. socket.once('end', () => {
  161. if (settled) return;
  162. settled = true;
  163. clearTimeout(connTimer);
  164. resolve(Buffer.concat(chunks));
  165. });
  166. socket.once('error', fail);
  167. });
  168. }
  169. function decodeLine(raw) {
  170. let text = raw.toString('utf8');
  171. if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); // strip UTF-8 BOM (unix StreamWriter)
  172. if (text.charCodeAt(text.length - 1) === 0x0a) text = text.slice(0, -1); // drop the '\n' terminator
  173. if (text.charCodeAt(text.length - 1) === 0x0d) text = text.slice(0, -1); // and a trailing '\r'
  174. return text;
  175. }
  176. /**
  177. * Forward one request, mirroring officecli's TrySend: bounded connect + a few
  178. * retries with backoff, then a blocking read. A retry only re-attempts the
  179. * connect (before the command runs), so it never double-applies a mutation. If
  180. * the command still can't be delivered, raise a busy/unresponsive error — never
  181. * fall back to touching the file directly (that would race the resident).
  182. *
  183. * `maxRetries` overrides the busy-retry count. Liveness probes (serves) pass 0
  184. * so a missing/stale pipe fails FAST instead of sleeping through the backoff.
  185. */
  186. async function rpc(sockPath, req, connectTimeoutMs = BUSY_CONNECT_TIMEOUT_MS, maxRetries = BUSY_MAX_RETRIES) {
  187. const line = Buffer.from(JSON.stringify(req) + '\n', 'utf8');
  188. let raw = null;
  189. for (let attempt = 0; ; attempt++) {
  190. try {
  191. raw = await sendOnce(sockPath, line, connectTimeoutMs);
  192. break;
  193. } catch (e) {
  194. // Connect/socket error only — the command never ran, so a retry is safe.
  195. if (attempt >= maxRetries) {
  196. throw new OfficeCliError(
  197. -1,
  198. 'resident is running but the command could not be delivered ' +
  199. `(pipe busy or unresponsive); retry, or close and reopen [${e.message}]`
  200. );
  201. }
  202. await sleep(50 * (attempt + 1)); // = TrySend's 50*(n+1)ms backoff
  203. }
  204. }
  205. const text = decodeLine(raw);
  206. if (!text.trim()) {
  207. // Empty/closed reply: the resident accepted the connection but closed
  208. // without a complete response (e.g. crashed mid-serve). We refuse to
  209. // re-send — the command may already have been APPLIED before the resident
  210. // died, so re-sending would double-apply a non-idempotent op — and raise
  211. // instead. _cmd's recovery then restarts a dead resident and retries once.
  212. throw new OfficeCliError(
  213. -1,
  214. 'resident closed the connection without a response ' +
  215. '(it may have crashed mid-command); retry, or close and reopen'
  216. );
  217. }
  218. return JSON.parse(text);
  219. }
  220. function parseEnvelope(resp) {
  221. // Return the useful payload: the parsed JSON envelope (object/array) if Stdout
  222. // is JSON, otherwise the raw Stdout text ("" when empty). Accept ONLY
  223. // object/array — a bare JSON scalar ("42", "true", "null", a quoted string)
  224. // stays text, or the caller can't tell literal text "42" from the number 42.
  225. const out = (resp && resp.Stdout) || '';
  226. let v;
  227. try {
  228. v = JSON.parse(out);
  229. } catch (_) {
  230. return out;
  231. }
  232. return v !== null && typeof v === 'object' ? v : out;
  233. }
  234. function strMap(o) {
  235. // Drop null/undefined values (omit), and stringify the rest — the resident's
  236. // Args/Props are Dictionary<string,string>. A value set to null means "don't
  237. // send it", not "send empty string"; pass "" for an explicit empty value.
  238. const r = {};
  239. for (const k of Object.keys(o)) {
  240. const v = o[k];
  241. if (v !== null && v !== undefined) r[k] = String(v);
  242. }
  243. return r;
  244. }
  245. async function serves(pingPath, fullPath, timeoutMs = 1000) {
  246. // Is a resident alive on `pingPath` AND serving `fullPath`? Probes the
  247. // always-responsive `-ping` pipe (officecli's TryConnect): it answers even
  248. // while the MAIN pipe is busy. Single-shot (maxRetries=0): a probe should fail
  249. // fast, not sit through the busy-retry backoff.
  250. let resp;
  251. try {
  252. resp = await rpc(pingPath, { Command: '__ping__' }, timeoutMs, 0);
  253. } catch (e) {
  254. if (e instanceof OfficeCliError) return false;
  255. throw e;
  256. }
  257. const served = ((resp && resp.Stdout) || '').trim(); // ping echoes the served path
  258. if (!served) return false;
  259. const a = path.resolve(served);
  260. return a === fullPath || ((IS_MAC || IS_WIN) && a.toLowerCase() === fullPath.toLowerCase());
  261. }
  262. // ---------------------------------------------------------------- binary resolution
  263. function installDirCandidate(name) {
  264. // Where install.sh / install.ps1 drop the binary: ~/.local/bin on macOS/Linux,
  265. // %LOCALAPPDATA%\OfficeCLI on Windows. PATH-miss fallback only.
  266. if (IS_WIN) {
  267. const base = process.env.LOCALAPPDATA;
  268. if (!base) return null;
  269. const exe = name.toLowerCase().endsWith('.exe') ? name : name + '.exe';
  270. return path.join(base, 'OfficeCLI', exe);
  271. }
  272. return path.join(os.homedir(), '.local', 'bin', name);
  273. }
  274. function whichOnPath(name) {
  275. const dirs = (process.env.PATH || '').split(path.delimiter);
  276. const cands = IS_WIN ? [name, name + '.exe', name + '.cmd'] : [name];
  277. for (const dir of dirs) {
  278. if (!dir) continue;
  279. for (const c of cands) {
  280. const p = path.join(dir, c);
  281. try {
  282. fs.accessSync(p, fs.constants.X_OK);
  283. return p;
  284. } catch (_) {
  285. /* keep looking */
  286. }
  287. }
  288. }
  289. return null;
  290. }
  291. function bundledBinary() {
  292. // If the @officecli/officecli installer package is installed (it is a
  293. // dependency), prefer its vendored, auto-updating binary. Returns the path if
  294. // it is present on disk, else null. require is wrapped so the SDK still works
  295. // as a pure thin client when the dependency was omitted.
  296. try {
  297. const cli = require('@officecli/officecli');
  298. const p = cli.binaryPath();
  299. return fs.existsSync(p) ? p : null;
  300. } catch (_) {
  301. return null;
  302. }
  303. }
  304. function resolveBinary(binary) {
  305. // Order: explicit path (has a separator) is trusted as-is; then the bundled
  306. // installer-package binary; then PATH; then the official installer's known
  307. // location. Idempotent — an already-resolved absolute path passes through.
  308. if (binary.includes(path.sep) || binary.includes('/')) return binary;
  309. if (binary === 'officecli') {
  310. const bundled = bundledBinary();
  311. if (bundled) return bundled;
  312. }
  313. const found = whichOnPath(binary);
  314. if (found) return found;
  315. const cand = installDirCandidate(binary);
  316. if (cand) {
  317. try {
  318. fs.accessSync(cand, fs.constants.X_OK);
  319. return cand;
  320. } catch (_) {
  321. /* fall through */
  322. }
  323. }
  324. return binary; // give up; runCli raises the helpful error
  325. }
  326. async function ensureCliBinary(binary, autoInstall) {
  327. // Async binary resolution for the entry points (open/create), able to ACTIVELY
  328. // provision a missing CLI. Order: explicit path is trusted as-is; then the
  329. // bundled installer package (download its binary if not yet present — this is
  330. // the package's own signed download, not a surprise); then PATH; then the
  331. // installer's known location; finally, if autoInstall, run the official
  332. // install.sh. Returns the resolved path (or the bare name, so runCli raises
  333. // the helpful MISSING_CLI error if everything failed).
  334. if (binary.includes(path.sep) || binary.includes('/')) return binary; // explicit: trust caller
  335. // Accept the first candidate that actually RUNS (`--version` exit 0), in
  336. // priority order: the bundled (auto-updating) binary, then PATH, then the
  337. // installer's known location. Probing — not mere file existence — means a
  338. // present-but-broken binary is skipped, and a working officecli is never
  339. // shadowed by a needless install.
  340. const candidates = [];
  341. if (binary === 'officecli') {
  342. try {
  343. const p = require('@officecli/officecli').binaryPath();
  344. if (fs.existsSync(p)) candidates.push(p);
  345. } catch (_) { /* dependency absent */ }
  346. }
  347. const onPath = whichOnPath(binary);
  348. if (onPath) candidates.push(onPath);
  349. const cand = installDirCandidate(binary);
  350. if (cand) candidates.push(cand);
  351. for (const c of candidates) {
  352. if (probeVersion(c)) return c;
  353. }
  354. // Nothing usable found anywhere — provision it (only for the default name).
  355. if (autoInstall && binary === 'officecli') {
  356. process.stderr.write('[officecli] CLI not found — installing from d.officecli.ai …\n');
  357. try {
  358. const cli = require('@officecli/officecli');
  359. await cli.ensureBinary(); // bundled package's own signed download
  360. const p = cli.binaryPath();
  361. if (probeVersion(p)) return p;
  362. } catch (_) { /* fall through to the official installer */ }
  363. install(); // install.sh (unix) / install.ps1 (Windows)
  364. const after = installDirCandidate('officecli');
  365. if (after && probeVersion(after)) return after;
  366. }
  367. return binary; // give up → runCli raises the helpful MISSING_CLI
  368. }
  369. // Quote one token for a cmd.exe command line: ALWAYS wrap in double quotes,
  370. // doubling any embedded quote. Unconditional quoting (rather than "only when it
  371. // looks dangerous") is deliberate — it removes any reliance on enumerating every
  372. // cmd metacharacter. A double-quoted token cannot be re-tokenized by cmd.exe, so
  373. // & | < > ^ ( ) " are inert, and a %VAR% expansion stays *inside* the quotes and
  374. // thus can never inject a command separator (at worst the argument is mangled —
  375. // there is no command-line escape for %, a documented cmd.exe limitation). This
  376. // matters because the binary path / args may be untrusted when the SDK is driven
  377. // by a server. cmd /s strips the outer wrapper, leaving these per-token quotes.
  378. function quoteForCmd(s) {
  379. return `"${String(s).replace(/"/g, '""')}"`;
  380. }
  381. function spawnCli(binary, argv, extraOpts) {
  382. let cmd = binary;
  383. let args = argv;
  384. const opts = { encoding: 'utf8', ...extraOpts };
  385. if (IS_WIN && /\.(cmd|bat)$/i.test(binary)) {
  386. // Node refuses to spawn a .cmd/.bat directly without a shell since
  387. // CVE-2024-27980 (raises EINVAL). Run it through cmd.exe ourselves,
  388. // quoting each token so paths with spaces survive — shell:true would
  389. // join the args unquoted and break on the first space. Mirrors Node's
  390. // own shell idiom (cmd /d /s /c "<line>" + windowsVerbatimArguments)
  391. // but with the per-token quoting shell:true omits.
  392. const line = [binary, ...argv].map(quoteForCmd).join(' ');
  393. cmd = process.env.ComSpec || 'cmd.exe';
  394. args = ['/d', '/s', '/c', `"${line}"`];
  395. opts.windowsVerbatimArguments = true;
  396. }
  397. return spawnSync(cmd, args, opts);
  398. }
  399. function runCli(binary, argv) {
  400. const r = spawnCli(binary, argv);
  401. if (r.error && r.error.code === 'ENOENT') {
  402. throw new OfficeCliError(127, MISSING_CLI.replace('{bin}', JSON.stringify(binary)));
  403. }
  404. if (r.error) throw new OfficeCliError(-1, r.error.message);
  405. return r;
  406. }
  407. // Probe a resolved binary by running `<binary> --version`: true iff it actually
  408. // runs and exits 0. We accept only a WORKING officecli — a present-but-broken
  409. // file (wrong arch, stale/again-renamed shim, corrupt download) must not be
  410. // used, and conversely a working officecli on PATH must not be shadowed by a
  411. // needless auto-install. Output is discarded.
  412. function probeVersion(binPath) {
  413. const r = spawnCli(binPath, ['--version'], { stdio: ['ignore', 'ignore', 'ignore'] });
  414. return !r.error && r.status === 0;
  415. }
  416. // ---------------------------------------------------------------- the shell
  417. class Document {
  418. constructor(filePath, binary = 'officecli', timeoutMs = 30000) {
  419. // Canonical (Windows 8.3-expanded) so the pipe name AND the serves() path
  420. // comparison both match what the resident reports.
  421. this.path = canonicalPath(filePath);
  422. this.bin = resolveBinary(binary);
  423. this.timeout = timeoutMs; // connect timeout (ms); the reply read blocks
  424. const [main, ping] = pipePaths(this.path);
  425. this._main = main;
  426. this._ping = ping;
  427. this._restarting = null; // in-flight dead-resident restart (serializes callers)
  428. }
  429. async _start() {
  430. // Reuse a resident already serving this file (no spawn). serves() is a real
  431. // liveness probe (ping + path match), so a stale/dead socket falls through
  432. // to `officecli open`, which replaces it via TryConnect.
  433. if (await serves(this._ping, this.path)) return;
  434. const r = runCli(this.bin, ['open', this.path]);
  435. if (r.status !== 0) throw new OfficeCliError(r.status == null ? -1 : r.status, r.stderr || r.stdout);
  436. }
  437. async _cmd(command, args, props, asJson = true, timeoutMs) {
  438. const req = { Command: command, Json: asJson };
  439. if (args) req.Args = strMap(args);
  440. if (props !== null && props !== undefined) req.Props = strMap(props);
  441. const t = timeoutMs == null ? this.timeout : timeoutMs;
  442. try {
  443. return await rpc(this._main, req, t, BUSY_MAX_RETRIES);
  444. } catch (e) {
  445. if (!(e instanceof OfficeCliError)) throw e;
  446. // Delivery failed. Use the -ping pipe to tell DEAD from BUSY:
  447. // • ALIVE but main pipe unresponsive → do NOT bypass it (a second writer
  448. // racing the live resident loses data on its save). Re-raise.
  449. // • DEAD (crashed / stale socket) → restart with one `officecli open`
  450. // and retry ONCE. Safe across reads and mutations.
  451. if (await this.alive()) throw e;
  452. // Serialize the restart across concurrent callers sharing this Document so
  453. // only one spawns `officecli open` (else N-1 orphaned residents race saves).
  454. if (!this._restarting) {
  455. this._restarting = (async () => {
  456. if (!(await this.alive())) await this._start();
  457. })().finally(() => {
  458. this._restarting = null;
  459. });
  460. }
  461. await this._restarting;
  462. return await rpc(this._main, req, t, BUSY_MAX_RETRIES);
  463. }
  464. }
  465. /**
  466. * Forward ONE command in officecli's batch-item shape and return its parsed
  467. * result (the JSON envelope, or raw text for content commands). `item` is
  468. * exactly an object you'd put in a `batch` list:
  469. * { command: 'set', path: '/Sheet1/A1', props: { text: 'hi' } }
  470. * `command` (or `op`) picks the command, `props` becomes the property map, and
  471. * every other key is forwarded verbatim as a command argument. asJson=false
  472. * requests plain-text output (view/raw/dump), mirroring the CLI's --json.
  473. */
  474. async send(item, asJson = true, timeoutMs) {
  475. const command = item.command || item.op;
  476. if (!command) throw new OfficeCliError(-1, "send(item): item needs a 'command' (or 'op') key");
  477. const args = {};
  478. for (const k of Object.keys(item)) {
  479. if (k !== 'command' && k !== 'op' && k !== 'props') args[k] = item[k];
  480. }
  481. return parseEnvelope(await this._cmd(command, args, item.props, asJson, timeoutMs));
  482. }
  483. /**
  484. * Forward officecli's `batch`: apply a LIST of the same item objects as send()
  485. * in ONE round-trip — the fast path for many writes.
  486. */
  487. async batch(items, { force = true, stopOnError = false, timeoutMs } = {}) {
  488. const args = { batchJson: JSON.stringify(items), force, stopOnError };
  489. return parseEnvelope(await this._cmd('batch', args, undefined, true, timeoutMs));
  490. }
  491. // Best-effort idle-timeout upgrade over the always-responsive ping pipe.
  492. // Mirrors ResidentClient.SendSetIdleTimeout: a failure is non-fatal — the
  493. // resident keeps its original idle schedule. Single-shot (maxRetries=0).
  494. async _setIdleTimeout(seconds) {
  495. try {
  496. await rpc(this._ping, { Command: '__set-idle-timeout__', Args: { seconds: String(seconds) } }, this.timeout, 0);
  497. } catch (e) {
  498. if (!(e instanceof OfficeCliError)) throw e;
  499. }
  500. }
  501. /** True iff a resident is alive AND serving this file (probes the -ping pipe). */
  502. async alive(timeoutMs = 1000) {
  503. return serves(this._ping, this.path, timeoutMs);
  504. }
  505. /**
  506. * = `officecli close`: stop the resident. It flushes the in-memory doc to disk
  507. * as it shuts down, so no separate save is needed. The resident acks AFTER
  508. * shutting down, so a missing/empty ack still means "closed"; a real shutdown
  509. * error is a non-empty response and surfaces through the return value.
  510. */
  511. async close() {
  512. try {
  513. return parseEnvelope(await rpc(this._ping, { Command: '__close__' }, this.timeout));
  514. } catch (e) {
  515. if (!(e instanceof OfficeCliError)) throw e;
  516. // Only swallow if the resident is actually gone. If it's still alive (ping
  517. // momentarily unreachable), the close did NOT take effect — re-raise, or
  518. // the caller wrongly believes the file is released.
  519. if (await this.alive()) throw e;
  520. return ''; // resident gone / ack lost — end state is "closed"
  521. }
  522. }
  523. async [Symbol.asyncDispose]() {
  524. await this.close();
  525. }
  526. }
  527. /**
  528. * Create a blank Office document and return a live Document handle. Extra CLI
  529. * flags pass through verbatim:
  530. * await create('report.xlsx', ['--force']);
  531. * await create('doc', ['--type', 'docx']);
  532. * One CLI spawn (`officecli create`), which auto-starts a resident; the handle
  533. * binds to THAT resident (no second spawn). Inherits officecli's semantics —
  534. * file_locked (close it first) / file_exists (pass '--force').
  535. */
  536. async function create(filePath, args = [], { binary = 'officecli', timeoutMs = 30000, autoInstall = true } = {}) {
  537. const full = path.resolve(filePath);
  538. const bin = await ensureCliBinary(binary, autoInstall);
  539. const r = runCli(bin, ['create', full, ...args]);
  540. if (r.status !== 0) throw new OfficeCliError(r.status == null ? -1 : r.status, r.stderr || r.stdout);
  541. const doc = new Document(full, bin, timeoutMs);
  542. await doc._start(); // create auto-started a resident; this finds it alive (no extra spawn)
  543. return doc;
  544. }
  545. /**
  546. * Open an EXISTING document and return a live Document handle. `officecli open`
  547. * is idempotent: reuse a resident already serving this file or start one.
  548. *
  549. * Owner — `const d = await open(f); try { ... } finally { await d.close(); }`
  550. * Borrow — `const d = await open(f); await d.send(...)` // leave it running
  551. *
  552. * Failure model (per send/batch): a DEAD resident is transparently restarted and
  553. * the command retried once; an ALIVE-but-busy pipe raises OfficeCliError (retry,
  554. * or close() and reopen).
  555. */
  556. async function open(filePath, { binary = 'officecli', timeoutMs = 30000, autoInstall = true } = {}) {
  557. const bin = await ensureCliBinary(binary, autoInstall);
  558. const doc = new Document(filePath, bin, timeoutMs);
  559. await doc._start();
  560. // Mirror CLI `open`: when reusing a resident create() auto-started with a
  561. // short 60s timeout, upgrade it to the 12min interactive window. (If _start
  562. // spawned `officecli open` instead, that path already set 12min; re-sending
  563. // is idempotent.)
  564. await doc._setIdleTimeout(OPEN_IDLE_SECONDS);
  565. return doc;
  566. }
  567. /**
  568. * Install the officecli CLI binary via its OFFICIAL installer — explicit by
  569. * design (this SDK never auto-downloads behind your back). Runs install.ps1 via
  570. * PowerShell on Windows and install.sh via bash elsewhere. Note: when installed
  571. * via npm, @officecli/officecli already bundles an auto-updating binary, so this
  572. * is only needed for a standalone (~/.local/bin or %LOCALAPPDATA%\OfficeCLI)
  573. * install.
  574. */
  575. function install() {
  576. if (IS_WIN) {
  577. process.stderr.write(`Installing officecli via ${INSTALL_PS1_MIRROR} (github fallback) ...\n`);
  578. // Fetch the script mirror-first, github fallback, then run it. The whole
  579. // try/catch is assigned so a mirror failure transparently falls back.
  580. const ps = `$s = try { irm '${INSTALL_PS1_MIRROR}' } catch { irm '${INSTALL_PS1_GITHUB}' }; $s | iex`;
  581. const r = spawnSync('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ps], {
  582. stdio: 'inherit',
  583. });
  584. if (r.status !== 0) {
  585. throw new OfficeCliError(
  586. r.status == null ? -1 : r.status,
  587. `officecli install failed. Run manually:\n irm ${INSTALL_PS1_MIRROR} | iex`
  588. );
  589. }
  590. return;
  591. }
  592. process.stderr.write(`Installing officecli via ${INSTALL_SH_MIRROR} (github fallback) ...\n`);
  593. // (curl mirror || curl github) | bash — the subshell emits whichever script
  594. // fetch succeeds; the group keeps the pipe bound to the whole fallback.
  595. const sh = `(curl -fsSL ${INSTALL_SH_MIRROR} 2>/dev/null || curl -fsSL ${INSTALL_SH_GITHUB}) | bash`;
  596. const r = spawnSync('bash', ['-c', sh], { stdio: 'inherit' });
  597. if (r.status !== 0) {
  598. throw new OfficeCliError(
  599. r.status == null ? -1 : r.status,
  600. `officecli install failed. Run manually:\n curl -fsSL ${INSTALL_SH_MIRROR} | bash`
  601. );
  602. }
  603. }
  604. module.exports = { open, create, install, Document, OfficeCliError, pipePaths };
sdk/python/officecli.py · Bundled script · 626 lines · 2 findings marked
  1. r"""
  2. officecli — a thin Python shell over officecli's resident pipe.
  3. It does ONE thing: forward a command to the running resident over its named
  4. pipe and hand back the response. There is NO second vocabulary to learn: a
  5. command is the same dict you'd put in an officecli `batch` list — e.g.
  6. {"command":"set","path":"/Sheet1/A1","props":{"text":"Hello"}}. `send` forwards
  7. one; `batch` forwards many in a single round-trip.
  8. Two surfaces, by design:
  9. - bootstrap (infrequent): `create` / `open` spawn ONE CLI process — a file that
  10. isn't open yet (or doesn't exist yet) has no resident to talk to.
  11. - everything else (the hot path): `send` / `batch` are pure pipe round-trips,
  12. no per-command process spawn.
  13. import officecli
  14. with officecli.create("report.xlsx", "--force") as doc: # make file + get handle
  15. doc.send({"command": "set", "path": "/Sheet1/A1",
  16. "props": {"text": "Hello"}})
  17. print(doc.send({"command": "get", "path": "/Sheet1/A1"}))
  18. doc.send({"command": "save"})
  19. # ...or officecli.open("existing.xlsx") for a file that already exists.
  20. The item keys are officecli's batch fields (command/op, path, parent, type,
  21. index, after, before, to, selector, text, mode, depth, part, xpath, action,
  22. xml) plus a nested `props` dict. Everything except command/op/props is
  23. forwarded verbatim as a command argument; the resident dispatches it exactly
  24. like the matching CLI command. See `officecli help` / the batch docs for the
  25. field-and-prop reference — this shell adds none of its own.
  26. Protocol (matches ResidentServer.cs / ResidentClient.cs):
  27. - pipe name : officecli-<SHA256(fullpath)[:16] uppercase>;
  28. fullpath upper-cased on macOS/Windows, left as-is on Linux.
  29. - unix path : $TMPDIR/CoreFxPipe_<name> (+ "-ping"); $TMPDIR else /tmp
  30. - win path : \\.\pipe\<name> (+ "-ping")
  31. - framing : one request line + one response line, UTF-8, '\n' terminated;
  32. one connection == one command.
  33. - request : PascalCase {"Command","Args","Props","Json"}
  34. - response : {"ExitCode","Stdout","Stderr"}
  35. """
  36. import os
  37. import sys
  38. import json
  39. import time
  40. import socket
  41. import hashlib
  42. import shutil
  43. import threading
  44. import subprocess
  45. # Mirror officecli's TryResident busy-delivery policy (CommandBuilder.cs): a
  46. # generous connect timeout + a few retries with backoff, applied identically to
  47. # every command. The reply read itself blocks (no timeout) — like officecli's
  48. # PipeReadLine — trusting the resident to answer once our turn comes up in its
  49. # serialized queue. Because retries only re-attempt the CONNECT (before the
  50. # command executes), re-sending is safe even for mutations; there is no
  51. # "read timed out, resend" path that could double-apply.
  52. _BUSY_CONNECT_TIMEOUT = 30.0 # = ResidentBusyConnectTimeoutMs (30000)
  53. _BUSY_MAX_RETRIES = 3 # = ResidentBusyMaxRetries
  54. # = CommandBuilder's DefaultOpenIdleSeconds. `open` upgrades a reused resident
  55. # (which `create` may have auto-started with a short 60s timeout) to the 12min
  56. # interactive window, so a long editing session over an SDK handle isn't cut
  57. # short by the create-time timeout.
  58. _OPEN_IDLE_SECONDS = 12 * 60
  59. _IS_WIN = sys.platform.startswith("win")
  60. _IS_MAC = sys.platform == "darwin"
  61. _builtin_open = open # preserved; this module defines its own open() below
  62. # officecli's official installer (README one-liner). install() shells out to it;
  63. # the missing-CLI error points users at it / at install().
  64. # Installer scripts: the d.officecli.ai mirror is primary; GitHub raw is only a
  65. # fallback (same order as install.sh / install.ps1 themselves). The mirror is
  66. # Cloudflare-fronted and reachable where raw.githubusercontent.com may be
  67. # rate-limited or blocked.
  68. _INSTALL_SH_MIRROR = "https://d.officecli.ai/install.sh"
  69. _INSTALL_SH_GITHUB = "https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh"
  70. _INSTALL_PS1_MIRROR = "https://d.officecli.ai/install.ps1"
  71. _INSTALL_PS1_GITHUB = "https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1"
  72. _MISSING_CLI = (
  73. "officecli CLI not found: {bin!r} is not on PATH nor in the default install "
  74. "location (~/.local/bin, or %LOCALAPPDATA%\\OfficeCLI on Windows). This SDK only forwards "
  75. "commands to the officecli binary, which must be installed separately. Install it:\n"
  76. " python -m officecli install # runs the official installer\n"
  77. " # or: curl -fsSL " + _INSTALL_SH_MIRROR + " | bash\n"
  78. "Already installed elsewhere? pass binary=\"/path/to/officecli\"."
  79. )
  80. class OfficeCliError(Exception):
  81. """Raised on transport/process failure (could not reach the resident).
  82. Business outcomes are NOT exceptions — they live in the returned envelope's
  83. 'success' field, same as the CLI's exit code."""
  84. def __init__(self, code, msg):
  85. super().__init__(f"[exit {code}] {msg}")
  86. self.code = code
  87. # ---------------------------------------------------------------- pipe address
  88. def _dotnet_tempdir():
  89. # Mirror .NET Path.GetTempPath() on Unix exactly: $TMPDIR else /tmp.
  90. return os.environ.get("TMPDIR") or "/tmp"
  91. def _canonical_path(file_path):
  92. """Match the path officecli's resident hashes into the pipe name. On Windows
  93. it derives the name from GetFullPath, which expands 8.3 short components
  94. (RUNNER~1, or any user name > 8 chars under %TEMP%) to their long form.
  95. os.path.abspath does NOT expand 8.3, so a short path hashes to a different
  96. pipe and every connect fails with ENOENT — hence realpath, which does expand
  97. it. realpath needs the file to exist; fall back to the abspath when it
  98. doesn't. realpath ALSO resolves symlinks/junctions, which GetFullPath does
  99. not; harmless here because we hand this resolved path to the resident, so the
  100. server's GetFullPath sees the already-resolved string and both sides hash the
  101. same thing. Windows only — on unix officecli uses GetFullPath (no symlink
  102. resolution), so realpath would diverge there (e.g. /tmp -> /private/tmp on
  103. macOS)."""
  104. resolved = os.path.abspath(file_path)
  105. if _IS_WIN:
  106. try:
  107. return os.path.realpath(resolved)
  108. except OSError:
  109. pass
  110. return resolved
  111. def pipe_paths(file_path):
  112. """(main, ping) pipe addresses for a document path. Exposed for debugging."""
  113. full = _canonical_path(file_path)
  114. if _IS_MAC or _IS_WIN:
  115. full = full.upper() # Linux: case-sensitive, no upper
  116. h = hashlib.sha256(full.encode("utf-8")).hexdigest().upper()[:16]
  117. name = f"officecli-{h}"
  118. if _IS_WIN:
  119. return rf"\\.\pipe\{name}", rf"\\.\pipe\{name}-ping"
  120. base = os.path.join(_dotnet_tempdir(), f"CoreFxPipe_{name}")
  121. return base, base + "-ping"
  122. # ---------------------------------------------------------------- transport
  123. # One attempt: bound the CONNECT, then block on the reply (no read timeout) —
  124. # exactly like officecli's TrySend (Connect(timeout) + blocking PipeReadLine).
  125. def _send_unix(sock_path, line, connect_timeout):
  126. s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  127. try:
  128. s.settimeout(connect_timeout)
  129. s.connect(sock_path)
  130. s.settimeout(None) # block on the reply; resident answers in turn
  131. s.sendall(line)
  132. buf = b""
  133. while not buf.endswith(b"\n"):
  134. chunk = s.recv(65536)
  135. if not chunk:
  136. break
  137. buf += chunk
  138. return buf
  139. finally:
  140. s.close()
  141. def _send_win(pipe_path, line, connect_timeout):
  142. deadline = time.time() + connect_timeout
  143. while True: # bound the "open" (connect) phase
  144. try:
  145. f = _builtin_open(pipe_path, "r+b", buffering=0) # not the module open()
  146. break
  147. except FileNotFoundError:
  148. # No pipe == no resident. Fail FAST, like _send_unix's connect()
  149. # raising ENOENT immediately — do NOT spin to the deadline. This is
  150. # what makes a max_retries=0 probe (_serves/alive) fail fast instead
  151. # of sitting through the whole connect_timeout when nothing is there.
  152. raise
  153. except OSError:
  154. # The pipe exists but the open lost the race (e.g. ERROR_PIPE_BUSY:
  155. # every server instance is mid-handoff). The resident IS alive, so
  156. # retry until the connect deadline.
  157. if time.time() > deadline:
  158. raise
  159. time.sleep(0.02)
  160. try:
  161. # FileIO.write (raw, buffering=0) issues a single WriteFile and may
  162. # return a short count, so loop until the whole request is out — a
  163. # truncated request leaves the resident blocking for a newline that
  164. # never comes, deadlocking the (untimed) reply read. Mirrors _send_unix's
  165. # sendall() and the C# client's Stream.Write.
  166. view = memoryview(line)
  167. sent = 0
  168. while sent < len(view):
  169. n = f.write(view[sent:])
  170. if n is None: # non-blocking handle not ready (shouldn't happen)
  171. continue
  172. sent += n
  173. buf = b""
  174. while not buf.endswith(b"\n"): # blocking read, like PipeReadLine
  175. chunk = f.read(65536)
  176. if not chunk:
  177. break
  178. buf += chunk
  179. return buf
  180. finally:
  181. f.close()
  182. def _rpc(sock_path, req, connect_timeout=_BUSY_CONNECT_TIMEOUT, max_retries=_BUSY_MAX_RETRIES):
  183. """Forward one request, mirroring officecli's TrySend: bounded connect + a few
  184. retries with backoff, then a blocking read. A retry only re-attempts the
  185. connect (before the command runs), so it never double-applies a mutation. If
  186. the command still can't be delivered, raise a busy/unresponsive error — never
  187. fall back to touching the file directly (that would race the resident).
  188. `max_retries` overrides the busy-retry count. Liveness probes (_serves) pass 0
  189. so a missing/stale pipe fails FAST instead of sleeping through ~0.3s of backoff
  190. — retrying a probe the resident isn't answering can't make it answer; the
  191. busy-retry policy is for delivering a real command to a slow-but-live pipe."""
  192. line = (json.dumps(req, ensure_ascii=False) + "\n").encode("utf-8")
  193. send = _send_win if _IS_WIN else _send_unix
  194. for attempt in range(max_retries + 1):
  195. try:
  196. raw = send(sock_path, line, connect_timeout)
  197. break
  198. except OSError as e:
  199. if attempt >= max_retries:
  200. raise OfficeCliError(-1,
  201. f"resident is running but the command could not be delivered "
  202. f"(pipe busy or unresponsive); retry, or close and reopen [{e}]")
  203. time.sleep(0.05 * (attempt + 1)) # = TrySend's 50*(n+1)ms backoff
  204. # utf-8-sig: the resident's StreamWriter (Encoding.UTF8) prepends a BOM the
  205. # C# StreamReader strips; we must too, or json.loads chokes on the leading .
  206. text = raw.decode("utf-8-sig")
  207. if not text.strip():
  208. # Empty/closed reply: the resident accepted the connection but closed
  209. # without a complete response (e.g. crashed mid-serve). We refuse to
  210. # re-send — the command may already have been APPLIED before the resident
  211. # died, so re-sending would double-apply a non-idempotent op — and raise
  212. # instead. officecli's TrySend now matches: its retry covers only the
  213. # connect phase (before the command is written); on an empty reply after a
  214. # successful write it returns null without re-sending, the C# equivalent of
  215. # this raise. _cmd's recovery then restarts a dead resident and retries once
  216. # (a fresh connect, before re-send), and _serves()/alive() (which swallow
  217. # OfficeCliError) read an empty reply as "not alive".
  218. raise OfficeCliError(-1,
  219. "resident closed the connection without a response "
  220. "(it may have crashed mid-command); retry, or close and reopen")
  221. return json.loads(text)
  222. def _parse(resp):
  223. """Return the useful payload: the parsed JSON envelope (dict/list) if Stdout is
  224. a JSON object/array, otherwise the raw Stdout text ("" when empty). We accept
  225. ONLY dict/list from json.loads — a text-mode reply that happens to BE a bare
  226. JSON scalar ("42", "true", "null", a quoted string) must stay text, or the
  227. caller can't tell literal text "42" from the number 42 (and None from a missing
  228. key). Faithful to the response — no synthesizing a dict for view/raw text."""
  229. out = resp.get("Stdout", "")
  230. try:
  231. v = json.loads(out)
  232. except ValueError:
  233. return out
  234. return v if isinstance(v, (dict, list)) else out
  235. def _strv(d):
  236. # Drop None-valued props (omit), matching how _cmd() drops None args — a prop
  237. # set to None means "don't send it", not "send empty string". Pass "" for
  238. # an explicit empty value.
  239. return {k: str(v) for k, v in d.items() if v is not None}
  240. def _serves(ping_path, full_path, timeout=1.0):
  241. """Is a resident alive on `ping_path` AND serving `full_path`? Probes the
  242. always-responsive `-ping` pipe (officecli's TryConnect equivalent): it answers
  243. even while the MAIN pipe is busy. The path-match guards against a stale socket
  244. serving a different/renamed file. `full_path` must already be absolute.
  245. Single-shot (max_retries=0): a probe should fail fast, not sit through the
  246. busy-retry backoff that a real command delivery uses."""
  247. try:
  248. resp = _rpc(ping_path, {"Command": "__ping__"}, timeout, max_retries=0)
  249. except OfficeCliError:
  250. return False
  251. served = resp.get("Stdout", "").strip() # ping echoes the served file path
  252. if not served:
  253. return False
  254. a = os.path.abspath(served)
  255. return a == full_path or ((_IS_MAC or _IS_WIN) and a.lower() == full_path.lower())
  256. def _install_dir_candidate(name):
  257. """Where the official installer (install.sh / install.ps1) drops the binary:
  258. ~/.local/bin on macOS/Linux, %LOCALAPPDATA%\\OfficeCLI on Windows. Used only
  259. as a PATH-miss fallback (see _resolve_binary)."""
  260. if _IS_WIN:
  261. base = os.environ.get("LOCALAPPDATA")
  262. if not base:
  263. return None
  264. exe = name if name.lower().endswith(".exe") else name + ".exe"
  265. return os.path.join(base, "OfficeCLI", exe)
  266. return os.path.join(os.path.expanduser("~"), ".local", "bin", name)
  267. def _resolve_binary(binary):
  268. """Resolve the officecli binary to invoke. Order: explicit path (a value with
  269. a path separator) is trusted as-is; otherwise a bare name is looked up on
  270. PATH; if PATH misses, fall back to the official installer's known location.
  271. Why the fallback: the installer adds its dir to PATH via the shell rc file, so
  272. a bare 'officecli' resolves in an interactive terminal — but NOT in processes
  273. that never sourced that rc (IDE-spawned Python, cron, systemd, CI). The binary
  274. is still sitting at the known install path; find it there instead of failing.
  275. Idempotent: an already-resolved absolute path passes straight through, so it's
  276. safe to call at every entry point (create + Document)."""
  277. if os.sep in binary or (os.altsep and os.altsep in binary):
  278. return binary # explicit path: trust the caller
  279. found = shutil.which(binary)
  280. if found:
  281. return found # on PATH: normal case
  282. cand = _install_dir_candidate(binary) # PATH miss: try the known install dir
  283. if cand and os.path.isfile(cand) and os.access(cand, os.X_OK):
  284. return cand
  285. return binary # give up; _run_cli raises the helpful error
  286. def _runs_ok(binary):
  287. """True iff `<binary> --version` actually runs and exits 0. Accept only a
  288. WORKING officecli — skip a present-but-broken file, and don't trigger a
  289. needless install when a usable officecli is already there."""
  290. try:
  291. return subprocess.run([binary, "--version"], capture_output=True).returncode == 0
  292. except OSError:
  293. return False
  294. def _ensure_binary(binary, auto_install=True):
  295. """Resolve to a WORKING officecli, provisioning one if none is found and
  296. auto_install is set. An explicit path (with a separator) is trusted as-is;
  297. otherwise each candidate (PATH, then the installer's known location) is
  298. accepted only when `officecli --version` actually runs — so a present-but-
  299. broken binary is skipped and a usable one never triggers a needless install.
  300. install() picks install.sh (unix) or install.ps1 (Windows), so auto-install
  301. works on both."""
  302. if os.sep in binary or (os.altsep and os.altsep in binary):
  303. return binary # explicit path: trust the caller
  304. for cand in filter(None, (shutil.which(binary), _install_dir_candidate(binary))):
  305. if _runs_ok(cand):
  306. return cand # a working officecli is already here
  307. if auto_install:
  308. print("officecli CLI not found — installing from d.officecli.ai ...", file=sys.stderr)
  309. install() # CLI absent/unusable → official installer
  310. for cand in filter(None, (shutil.which(binary), _install_dir_candidate(binary))):
  311. if _runs_ok(cand):
  312. return cand
  313. return binary # give up; _run_cli raises the helpful error
  314. def _run_cli(binary, argv):
  315. """Run `binary <argv...>` (capturing output). A missing binary surfaces as a
  316. clear OfficeCliError with install guidance, not a raw FileNotFoundError."""
  317. try:
  318. # text=True alone decodes with locale.getencoding() — the ANSI code page
  319. # on Windows (cp936/cp1252). The CLI always writes UTF-8, so a message
  320. # carrying a non-ASCII path raised UnicodeDecodeError (or mojibake) out
  321. # of subprocess instead of a clean OfficeCliError. The resident-pipe
  322. # route below already decodes utf-8; keep the two agreeing.
  323. return subprocess.run([binary, *argv], capture_output=True,
  324. text=True, encoding="utf-8", errors="replace")
  325. except FileNotFoundError:
  326. raise OfficeCliError(127, _MISSING_CLI.format(bin=binary)) from None
  327. # ---------------------------------------------------------------- the shell
  328. class Document:
  329. def __init__(self, path, binary="officecli", timeout=30.0):
  330. # Canonical (Windows 8.3-expanded) so the pipe name AND the _serves()
  331. # path comparison both match what the resident reports.
  332. self.path = _canonical_path(path)
  333. self.bin = _resolve_binary(binary)
  334. self.timeout = timeout # connect timeout (s); the reply read blocks
  335. self._main, self._ping = pipe_paths(self.path)
  336. self._restart_lock = threading.Lock() # serialize dead-resident restarts
  337. self._start()
  338. def _start(self):
  339. # If a resident is ALREADY serving this file, reuse it — no process spawn.
  340. # Mirrors officecli, where a command after `create` reuses the resident
  341. # `create` auto-started instead of re-running `open`. _serves() is a real
  342. # liveness probe (ping the -ping pipe + verify the served path), not a
  343. # socket-file-exists check, so a stale/dead socket fails the probe and
  344. # falls through to `officecli open`, which replaces it via TryConnect.
  345. # (A plain os.path.exists() here would wrongly skip on a stale socket.)
  346. if _serves(self._ping, self.path):
  347. return
  348. # Otherwise spawn `officecli open` (one process). It's idempotent and uses
  349. # the same TryConnect to start a fresh resident or replace a stale socket.
  350. r = _run_cli(self.bin, ["open", self.path])
  351. if r.returncode != 0:
  352. raise OfficeCliError(r.returncode, r.stderr or r.stdout)
  353. # -- transport primitive: build {Command,Args,Props,Json}, forward, parse --
  354. def _cmd(self, command, args=None, props=None, as_json=True, timeout=None):
  355. # `as_json`, not `json`, so we don't shadow the imported json module.
  356. # timeout=None uses this Document's default (self.timeout). It bounds the
  357. # CONNECT/delivery (with retries); the reply read blocks, so a legitimately
  358. # slow command isn't cut off — it waits for the resident, like officecli.
  359. req = {"Command": command, "Json": as_json}
  360. if args:
  361. req["Args"] = {k: str(v) for k, v in args.items() if v is not None}
  362. if props is not None:
  363. req["Props"] = _strv(props)
  364. t = self.timeout if timeout is None else timeout
  365. try:
  366. return _rpc(self._main, req, t)
  367. except OfficeCliError:
  368. # Delivery failed after _rpc's own connect retries. Use the -ping pipe
  369. # to tell DEAD from BUSY — officecli's own distinction (alive()):
  370. # • ALIVE but main pipe unresponsive → do NOT bypass it. officecli
  371. # deliberately dropped the direct-file fallback: a second writer
  372. # racing the live resident loses data on its eventual save. Re-raise
  373. # the busy error so the caller can retry or close+reopen.
  374. # • DEAD (crashed / stale socket) → restart with one `officecli open`
  375. # and retry ONCE. Safe across reads and mutations: mutations live in
  376. # memory until save/close, so a crash loses them and disk holds the
  377. # last save — replaying against the restarted (disk-state) resident
  378. # reproduces the lost op once, with nothing live to double-apply.
  379. if self.alive():
  380. raise
  381. # Serialize the restart across threads sharing this Document. Without
  382. # the lock, N concurrent callers each see alive()==False and each spawn
  383. # `officecli open`, leaving N-1 orphaned residents on the same file
  384. # (which can then race each other's save). Re-check alive() inside the
  385. # lock so only the first thread restarts; the rest find it back up.
  386. with self._restart_lock:
  387. if not self.alive():
  388. self._start()
  389. return _rpc(self._main, req, t)
  390. # -- the surface: send ONE batch-shaped command, or a LIST of them ---------
  391. def send(self, item, as_json=True, timeout=None):
  392. """Forward ONE command in officecli's batch-item shape and return its
  393. parsed result (the JSON envelope, or raw text for content commands).
  394. `item` is exactly a dict you'd put in a `batch` list, e.g.
  395. {"command": "set", "path": "/Sheet1/A1", "props": {"text": "hi"}}
  396. {"command": "get", "path": "/Sheet1/A1"}
  397. Keys are officecli's batch fields; `command` (or `op`) picks the command,
  398. `props` becomes the property map, and every other key is forwarded
  399. verbatim as a command argument — no field list maintained here, so new
  400. officecli fields work without touching this shell.
  401. `as_json=False` requests plain-text output (view/raw/dump), mirroring the
  402. CLI's --json toggle."""
  403. command = item.get("command") or item.get("op")
  404. if not command:
  405. raise OfficeCliError(-1, "send(item): item needs a 'command' (or 'op') key")
  406. args = {k: v for k, v in item.items() if k not in ("command", "op", "props")}
  407. return _parse(self._cmd(command, args, item.get("props"),
  408. as_json=as_json, timeout=timeout))
  409. def batch(self, items, force=True, stop_on_error=False, timeout=None):
  410. """Forward officecli's `batch` command: apply a LIST of the same item
  411. dicts as `send` in ONE round-trip — the fast path for many writes. Same
  412. contract as `send`, just plural."""
  413. args = {"batchJson": json.dumps(items, ensure_ascii=False),
  414. "force": force, "stopOnError": stop_on_error}
  415. return _parse(self._cmd("batch", args, timeout=timeout))
  416. def _set_idle_timeout(self, seconds):
  417. # Best-effort idle-timeout upgrade, served on the always-responsive ping
  418. # pipe (bypasses _commandLock, answers even while the main pipe is busy).
  419. # Mirrors ResidentClient.SendSetIdleTimeout: a failure is non-fatal — the
  420. # resident is still usable, it just keeps its original idle schedule.
  421. # Single-shot (max_retries=0): don't sit through the busy backoff for a
  422. # best-effort nicety.
  423. try:
  424. _rpc(self._ping, {"Command": "__set-idle-timeout__",
  425. "Args": {"seconds": str(seconds)}},
  426. self.timeout, max_retries=0)
  427. except OfficeCliError:
  428. pass
  429. def alive(self, timeout=1.0):
  430. """Return True iff a resident is alive AND serving this file. Probes the
  431. always-responsive `-ping` pipe (officecli's TryConnect), which answers even
  432. while the MAIN pipe is busy — so it distinguishes "alive but busy" from
  433. "gone". This is the discriminator `_cmd` uses on a delivery failure (busy →
  434. raise, gone → restart+retry); send/batch already auto-recover from a gone
  435. resident, so call this only when you want to check liveness yourself."""
  436. return _serves(self._ping, self.path, timeout)
  437. # -- lifecycle ------------------------------------------------------------
  438. def close(self):
  439. # = `officecli close`: stop the resident. It flushes the in-memory doc to
  440. # disk as it shuts down (handler.Dispose), so no separate save is needed —
  441. # verified: a set followed by __close__ alone lands on disk.
  442. #
  443. # The resident acks AFTER shutting down, so a missing/empty ack (lost to a
  444. # crash or the 5s write-timeout) still means "closed". A real shutdown
  445. # data-loss is a NON-empty error response, so it surfaces through _parse.
  446. try:
  447. return _parse(_rpc(self._ping, {"Command": "__close__"}, self.timeout))
  448. except OfficeCliError:
  449. # Only swallow if the resident is actually gone. If it's still alive
  450. # (ping pipe was momentarily unreachable/busy), the close did NOT take
  451. # effect — re-raise, or the caller wrongly believes the file is released
  452. # and may race a re-open/overwrite.
  453. if self.alive():
  454. raise
  455. return "" # resident gone / ack lost — end state is "closed"
  456. def __enter__(self):
  457. return self
  458. def __exit__(self, *a):
  459. # `with` means "I manage this session" → close on exit. To only borrow a
  460. # resident another program owns, DON'T use `with` and DON'T call close():
  461. # d = officecli.open(f); d.send(...) # left running
  462. self.close()
  463. def create(path, *args, binary="officecli", timeout=30.0, auto_install=True):
  464. """Create a blank Office document and return a live `Document` handle for it.
  465. Parallel to `open`: both return the session handle you actually work with —
  466. they differ only in the file's expected state. `open` requires an existing
  467. file; `create` makes a new one (like file mode "x" vs "r"). Extra CLI flags
  468. pass through verbatim, so there's no option list maintained here:
  469. with officecli.create("report.xlsx", "--force") as doc:
  470. doc.send({"command": "set", "path": "/Sheet1/A1", "props": {"text": "hi"}})
  471. officecli.create("doc", "--type", "docx")
  472. One CLI spawn (`officecli create`), which also auto-starts a resident for the
  473. new file; the returned Document binds to THAT resident (no second spawn).
  474. Raises OfficeCliError on failure, inheriting officecli's exact semantics:
  475. • file held by a LIVE resident → file_locked (close it first). We do NOT
  476. silently close+overwrite it — in a shared workspace that resident may be
  477. another owner's active session.
  478. • file exists without --force → file_exists (pass "--force" to overwrite)."""
  479. full = os.path.abspath(path)
  480. binary = _ensure_binary(binary, auto_install)
  481. r = _run_cli(binary, ["create", full, *args])
  482. if r.returncode != 0:
  483. raise OfficeCliError(r.returncode, r.stderr or r.stdout)
  484. # create auto-started a resident for the new file; bind a handle to it
  485. # (Document.__init__ -> _start -> _serves finds it alive, so no extra spawn).
  486. return Document(full, binary=binary, timeout=timeout)
  487. def open(path, binary="officecli", timeout=30.0, auto_install=True):
  488. """Open an EXISTING document and return a live `Document` handle (parallel to
  489. `create`, which makes a new file). `officecli open` is idempotent: it reuses a
  490. resident already serving this file or starts one — and if a live resident is
  491. already up, no process is spawned at all.
  492. Lifecycle:
  493. Owner — `with officecli.open(f) as d: ...` (exit closes the resident)
  494. Borrow — `d = officecli.open(f); d.send(...)` (no `with`/close → left running)
  495. Failure model (applies to every send/batch on the handle):
  496. • resident DEAD/gone (crash, idle-timeout, missing pipe) → transparently
  497. restarted and the command retried once; the caller sees no error.
  498. • resident ALIVE but the pipe is unresponsive (busy) → raises OfficeCliError
  499. — never a deadlock, and never bypassing the live resident (that would race
  500. its save and lose data). Retry, or close() and reopen.
  501. `timeout` bounds command DELIVERY (connect + retries) in seconds, mirroring
  502. officecli's TrySend; the reply read itself blocks (a busy resident answers in
  503. turn). Override per call via send(..., timeout=...) / batch(..., timeout=...);
  504. use alive() to probe liveness."""
  505. doc = Document(path, binary=_ensure_binary(binary, auto_install), timeout=timeout)
  506. # Mirror CLI `open`: when reusing a resident `create` auto-started with a
  507. # short 60s timeout, upgrade it to the 12min interactive window. (If _start
  508. # spawned `officecli open` instead, that path already set 12min; re-sending
  509. # is idempotent.)
  510. doc._set_idle_timeout(_OPEN_IDLE_SECONDS)
  511. return doc
  512. def install():
  513. """Install the officecli CLI binary via its OFFICIAL installer — install.sh on
  514. unix, install.ps1 on Windows. Reuses officecli's own installers (platform
  515. detection + checksum + ~/.local/bin or %LOCALAPPDATA%\\OfficeCLI), rather than
  516. reimplementing download logic that would drift from upstream.
  517. Called automatically by open()/create() when the CLI is missing (pass
  518. auto_install=False to disable), and exposed directly as `python -m officecli
  519. install`. Returns None on success; raises OfficeCliError on failure. Output is
  520. NOT captured, so the installer's progress and checksum lines stream to the
  521. user."""
  522. if _IS_WIN:
  523. print(f"Installing officecli via {_INSTALL_PS1_MIRROR} (github fallback) ...", file=sys.stderr)
  524. # Windows PowerShell (powershell.exe) ships with the OS; -ExecutionPolicy
  525. # Bypass lets the remote script run without changing machine policy. Fetch
  526. # the script mirror-first, github fallback, then run it.
  527. ps = (f"$s = try {{ irm '{_INSTALL_PS1_MIRROR}' }} "
  528. f"catch {{ irm '{_INSTALL_PS1_GITHUB}' }}; $s | iex")
  529. r = subprocess.run(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps])
  530. if r.returncode != 0:
  531. raise OfficeCliError(r.returncode,
  532. f"officecli install failed (exit {r.returncode}). Run manually:\n"
  533. f" irm {_INSTALL_PS1_MIRROR} | iex")
  534. return None
  535. print(f"Installing officecli via {_INSTALL_SH_MIRROR} (github fallback) ...", file=sys.stderr)
  536. # (curl mirror || curl github) | bash — the subshell emits whichever fetch
  537. # succeeds; the group keeps the pipe bound to the whole fallback. Output is
  538. # NOT captured, so progress and checksum lines stream to the user.
  539. sh = f"(curl -fsSL {_INSTALL_SH_MIRROR} 2>/dev/null || curl -fsSL {_INSTALL_SH_GITHUB}) | bash"
  540. r = subprocess.run(["bash", "-c", sh])
  541. if r.returncode != 0:
  542. raise OfficeCliError(r.returncode,
  543. f"officecli install failed (exit {r.returncode}). Run manually:\n"
  544. f" curl -fsSL {_INSTALL_SH_MIRROR} | bash")
  545. return None
  546. # Advertised surface = the command shell + its error. pipe_paths stays importable
  547. # (officecli.pipe_paths) as a debug helper but isn't part of the command API.
  548. __all__ = ["open", "create", "install", "Document", "OfficeCliError"]
  549. if __name__ == "__main__":
  550. # `python -m officecli install` — bootstrap the CLI binary.
  551. if len(sys.argv) >= 2 and sys.argv[1] == "install":
  552. install()
  553. else:
  554. print("usage: python -m officecli install", file=sys.stderr)
  555. sys.exit(2)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.