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.
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
Markdown
[](/listings/iofficeai--officecli)HTML
<a href="/listings/iofficeai--officecli"><img src="/api/listings/iofficeai--officecli/badge.svg" alt="findsafeskills safety rating" /></a>Install
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.
- ---
- name: officecli
- 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.
- ---
- # officecli
- AI-friendly CLI for .docx, .xlsx, .pptx. Single binary, no dependencies, no Office installation needed.
- ## Install
- If `officecli` is not installed:
- ```bash
- # macOS / Linux
- curl -fsSL https://d.officecli.ai/install.sh | bash
- # Windows (PowerShell)
- irm https://d.officecli.ai/install.ps1 | iex
- ```
- Verify with `officecli --version`. If still not found after install, open a new terminal.
- ---
- ## Strategy
- **L1 (read) → L2 (DOM edit) → L3 (raw XML)**. Always prefer higher layers. Add `--json` for structured output.
- **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.
- ---
- ## Help System (IMPORTANT)
- **When unsure about property names, value formats, or command syntax, ALWAYS run help instead of guessing.** One help query beats guess-fail-retry loops.
- `officecli help` ≡ `officecli --help`, and `officecli <cmd> --help` ≡ `officecli help <cmd>` — same content.
- ```bash
- officecli help # All commands + global options + schema entry points
- officecli help docx # List all docx elements
- officecli help docx paragraph # Full schema: properties, aliases, examples, readbacks
- officecli help docx set paragraph # Verb-filtered: only props usable with `set`
- officecli help docx paragraph --json # Structured schema (machine-readable)
- ```
- 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).
- ---
- ## Performance: Resident Mode
- **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):
- ```bash
- officecli open report.docx # explicitly keep in memory
- officecli set report.docx ... # no file I/O overhead
- officecli close report.docx # save and release
- ```
- Opt out of auto-start: `OFFICECLI_NO_AUTO_RESIDENT=1`.
- **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.)
- ---
- ## Quick Start
- **PPT:**
- ```bash
- officecli create slides.pptx
- officecli add slides.pptx / --type slide --prop title="Q4 Report" --prop background=1A1A2E
- 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
- ```
- **Word:**
- ```bash
- officecli create report.docx
- officecli add report.docx /body --type paragraph --prop text="Executive Summary" --prop style=Heading1
- officecli add report.docx /body --type paragraph --prop text="Revenue increased by 25% year-over-year."
- ```
- **Excel:**
- ```bash
- officecli create data.xlsx
- officecli set data.xlsx /Sheet1/A1 --prop value="Name" --prop bold=true
- officecli set data.xlsx /Sheet1/A2 --prop value="Alice"
- ```
- ---
- ## L1: Create, Read & Inspect
- ```bash
- officecli create <file> # Create blank .docx/.xlsx/.pptx (type from extension)
- officecli view <file> <mode> # outline | stats | issues | text | annotated | html
- officecli get <file> <path> --depth N # Get a node and its children [--json]
- officecli query <file> <selector> # CSS-like query
- officecli validate <file> # Validate against OpenXML schema
- ```
- ### view modes
- | Mode | Description | Useful flags |
- |------|-------------|-------------|
- | `outline` | Document structure | |
- | `stats` | Statistics (pages, words, shapes) | |
- | `issues` | Formatting/content/structure problems | `--type format\|content\|structure`, `--limit N` |
- | `text` | Plain text extraction | `--start N --end N`, `--max-lines N` |
- | `annotated` | Text with formatting annotations | |
- | `html` | Static HTML snapshot — same renderer as `watch`, no server needed | `--browser`, `--page N` (docx), `--start N --end N` (pptx) |
- | `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` |
- Use `view html` for one-shot snapshots (CI artifacts, archival, diffing); use `watch` when you need live refresh or browser-side click-to-select.
- ### get
- 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 ...`
- ```bash
- officecli get report.docx '/body/p[3]' --depth 2 --json
- officecli get slides.pptx '/slide[1]' --depth 1 # list all shapes on slide 1
- officecli get data.xlsx '/Sheet1/B2' --json
- ```
- ### Stable ID Addressing
- 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.
- ```
- /slide[1]/shape[@id=550950021] # PPT shape
- /slide[1]/table[@id=1388430425]/tr[1]/tc[2] # PPT table
- /body/p[@paraId=1A2B3C4D] # Word paragraph
- /comments/comment[@commentId=1] # Word comment
- ```
- 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.
- ### query
- 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`.
- ```bash
- officecli query report.docx 'paragraph[style=Normal] > run[font!=Arial]'
- officecli query slides.pptx 'shape[fill=FF0000]'
- ```
- ---
- ## Watch & Interactive Selection
- 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.
- ```bash
- officecli watch <file> [--port N] # Start preview server (default port 26315)
- officecli unwatch <file> # Stop
- officecli goto <file> <path> # Scroll watching browser(s) to element (docx: p / table / tr / tc)
- ```
- 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).
- ### `get <file> selected` — read what the user clicked
- ```bash
- officecli get <file> selected [--json]
- ```
- Returns DocumentNodes for whatever is currently selected. Empty result if nothing selected. Exit code != 0 if no watch is running.
- ```bash
- # User clicks shapes in the browser, then asks "make these red"
- PATHS=$(officecli get deck.pptx selected --json | jq -r '.data.Results[].path')
- for p in $PATHS; do officecli set deck.pptx "$p" --prop fill=FF0000; done
- ```
- ### Key properties
- - **Selection survives file edits.** Paths use stable `@id=` form.
- - **All connected browsers share one selection.** Last-write-wins.
- - **Same-file single-watch.** A given file can have only one watch process at a time.
- - **Group shapes select as a whole.** Drilling into individual children of a group is not supported in v1.
- - **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).
- ### Marks — edit proposals waiting for review
- 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).
- ```bash
- officecli mark <file> <path> [--prop find=... color=... note=... tofix=... regex=true] [--json]
- officecli unmark <file> [--path <p> | --all] [--json]
- officecli get-marks <file> [--json]
- ```
- 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.
- ---
- ## L2: DOM Operations
- ### set — modify properties
- ```bash
- officecli set <file> <path> --prop key=value [--prop ...]
- ```
- **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.
- **Value formats:**
- | Type | Format | Examples |
- |------|--------|---------|
- | Colors | Hex (with/without `#`), named, RGB, theme | `FF0000`, `#FF0000`, `red`, `rgb(255,0,0)`, `accent1`..`accent6` |
- | Spacing | Unit-qualified | `12pt`, `0.5cm`, `1.5x`, `150%` |
- | Dimensions | EMU or suffixed | `914400`, `2.54cm`, `1in`, `72pt`, `96px` |
- **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.
- ### find — format or replace matched text
- Use top-level `--find` / `--replace` on `set` (and `--find` on `query`). Legacy `--prop find=X` still works but emits a hint.
- ```bash
- # Format matched text (auto-splits runs)
- officecli set doc.docx '/body/p[1]' --find weather --prop bold=true --prop color=red
- # Regex matching (regex= still a prop flag)
- officecli set doc.docx '/body/p[1]' --find '\d+%' --prop regex=true --prop color=red
- # Replace text (use `/` for whole-document scope)
- officecli set doc.docx / --find draft --replace final
- # docx: tracked Find&Replace
- officecli set doc.docx / --find draft --replace final --prop revision.author=Alice
- # PPT — same syntax, different paths
- officecli set slides.pptx / --find draft --replace final
- ```
- **Path controls search scope:** `/` = whole document, `/body/p[1]` or `/slide[N]/shape[M]` = specific element, `/header[1]` / `/footer[1]` = headers/footers.
- **Notes:**
- - Case-sensitive by default. Case-insensitive: `--prop 'find=(?i)error' --prop regex=true`
- - Matches work across run boundaries
- - No match = silent success. `--json` includes `"matched": N`
- - **Excel:** only `find` + `replace` supported (no find + format props)
- ### add — add elements or clone
- ```bash
- officecli add <file> <parent> --type <type> [--prop ...]
- officecli add <file> <parent> --type <type> --after <path> [--prop ...] # insert after anchor
- officecli add <file> <parent> --type <type> --before <path> [--prop ...] # insert before anchor
- officecli add <file> <parent> --type <type> --index N [--prop ...] # 0-based position (legacy)
- officecli add <file> <parent> --from <path> # clone existing element
- ```
- `--after`, `--before`, `--index` are mutually exclusive. No position flag = append to end.
- **Element types (with aliases):**
- | Format | Types |
- |--------|-------|
- | **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`). |
- | **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. |
- | **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. |
- ### Pivot tables (xlsx)
- ```bash
- officecli add data.xlsx /Sheet1 --type pivottable \
- --prop source="Sheet1!A1:E100" --prop rows=Region,Category \
- --prop cols=Year --prop values="Sales:sum,Qty:count" \
- --prop grandTotals=rows --prop subtotals=off --prop sort=asc
- ```
- 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.
- ### Document-level properties (all formats)
- ```bash
- officecli set doc.docx / --prop docDefaults.font=Arial --prop docDefaults.fontSize=11pt
- officecli set doc.docx / --prop protection=forms --prop evenAndOddHeaders=true
- officecli set data.xlsx / --prop calc.mode=manual --prop calc.refMode=r1c1
- officecli set slides.pptx / --prop defaultFont=Arial --prop show.loop=true --prop print.what=handouts
- ```
- Run `officecli help <format> /` for all document-level properties (docDefaults, docGrid, CJK spacing, calc, print, show, theme, extended).
- ### Sort (xlsx)
- ```bash
- officecli set data.xlsx /Sheet1 --prop sort="C desc" --prop sortHeader=true
- officecli set data.xlsx '/Sheet1/A1:D100' --prop sort="A asc" --prop sortHeader=true
- ```
- Format: `COL DIR[, COL DIR ...]`. Rejects ranges with merged cells or formulas. Sidecar metadata (hyperlinks, comments, conditional formatting, drawings) follows rows automatically.
- ### Text-anchored insert (`--after find:X` / `--before find:X`)
- 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.
- ```bash
- # Word: inline run after matched text
- officecli add doc.docx '/body/p[1]' --type run --after find:weather --prop text=" (sunny)"
- # Word: block table after matched text (auto-splits paragraph)
- officecli add doc.docx '/body/p[1]' --type table --after "find:First sentence." --prop rows=2 --prop cols=2
- ```
- ### Clone
- `officecli add <file> / --from '/slide[1]'` — copies with all cross-part relationships.
- ### move, swap, remove
- ```bash
- officecli move <file> <path> [--to <parent>] [--index N] [--after <path>] [--before <path>]
- officecli swap <file> <path1> <path2>
- officecli remove <file> '/body/p[4]'
- ```
- When using `--after` or `--before`, `--to` can be omitted — the target container is inferred from the anchor.
- ### batch — multiple operations in one save cycle
- **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`.
- `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.
- ```bash
- echo '[
- {"command":"set","path":"/Sheet1/A1","props":{"value":"Name","bold":"true"}},
- {"command":"set","path":"/Sheet1/B1","props":{"value":"Score","bold":"true"}}
- ]' | officecli batch data.xlsx --json
- officecli batch data.xlsx --commands '[{"op":"set","path":"/Sheet1/A1","props":{"value":"Done"}}]' --json
- officecli batch data.xlsx --input updates.json --best-effort --json # keep whatever succeeds even if some items fail
- ```
- 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`.
- ---
- ## L3: Raw XML
- Use when L2 cannot express what you need. No xmlns declarations needed — prefixes auto-registered.
- ```bash
- officecli raw <file> <part> # view raw XML
- officecli raw-set <file> <part> --xpath "..." --action replace --xml '<w:p>...</w:p>'
- officecli add-part <file> <parent> # create new document part (returns rId)
- ```
- `raw-set` actions: `append`, `prepend`, `insertbefore`, `insertafter`, `replace`, `remove`, `setattr`. Run `officecli help <format> raw` for available parts.
- ---
- ## Common Pitfalls
- | Pitfall | Correct Approach |
- |---------|-----------------|
- | `--name "foo"` | Use `--prop name="foo"` — all attributes go through `--prop` |
- | Unquoted `[N]` paths in zsh/bash | Always quote: `'/slide[1]'` or `"/slide[1]"` (shell glob-expands brackets) |
- | PPT `shape[1]` for content | `shape[1]` is typically the title placeholder. Use `shape[2]+` for content shapes |
- | `/shape[myname]` | Name indexing not supported. Use numeric index or `@name=` (PPT only) |
- | Guessing property names | Run `officecli help <format> <element>` to see exact names |
- | Modifying an open file | Close the file in PowerPoint/WPS first |
- | `\n` in shell strings | Use `\\n` for newlines in `--prop text="..."` |
- | `$` in shell text | `--prop text="$15M"` strips `$15`. Use single quotes: `--prop text='$15M'`, or heredoc batch |
- ---
- ## Specialized Skills
- `officecli load_skill <name>` — output is a SKILL.md, follow its rules.
- **Loading rule**:
- - Pick the most specific match in "When to use"; if none fits, load the format default (`word` / `pptx` / `excel`).
- - Scenes already contain the format default's rules — load **one** skill per artifact, never stack.
- - Loaded rules persist across turns; don't re-load each reply.
- - Two distinct artifacts → two separate loads.
- ### Word (.docx)
- | Name | When to use |
- |------|-------------|
- | `word` | Reports, letters, memos, proposals, generic documents |
- | `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`) |
- ### PowerPoint (.pptx)
- | Name | When to use |
- |------|-------------|
- | `pptx` | Generic decks: board reviews, sales decks, all-hands, product launches |
- | `pitch-deck` | **Fundraising only** — seed / Series A-C / SAFE / convertible / strategic raise. NOT for sales / product / board decks (route those to `pptx`) |
- | `morph-ppt` | Cinematic Morph-animated presentations. NOT for static decks (route those to `pptx`) |
- | `morph-ppt-3d` | 3D Morph: GLB models, camera moves, depth. NOT for 2D-only Morph (route those to `morph-ppt`) |
- ### Excel (.xlsx)
- | Name | When to use |
- |------|-------------|
- | `excel` | Generic workbooks, formulas, pivots, trackers |
- | `financial-model` | Financial models, scenarios, projections. NOT for general data analysis (route those to `excel`) |
- | `data-dashboard` | CSV/tabular data → KPI / analytics / executive dashboards with charts and sparklines. NOT for raw data tracking (route those to `excel`) |
- Example: a fundraising deck task → `officecli load_skill pitch-deck` → use the printed rules.
- ---
- ## Notes
- - Paths are **1-based** (XPath convention): `'/body/p[3]'` = third paragraph
- - `--index` is **0-based** (array convention): `--index 0` = first position
- - **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.
- - After modifications, verify with `validate` and/or `view issues`
- - **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.
- # OfficeCLI
- > **OfficeCLI is the world's first and the best Office suite designed for AI agents.**
- **Give any AI agent full control over Word, Excel, and PowerPoint — in one line of code.**
- Open-source. Single binary. No Office installation. No dependencies. Works everywhere.
- **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.
- [](https://github.com/iOfficeAI/OfficeCLI/releases)
- [](LICENSE)
- **English** | [中文](README_zh.md) | [日本語](README_ja.md) | [한국어](README_ko.md)
- <p align="center">
- <strong>🌐 Website:</strong> <a href="https://officecli.ai" target="_blank">officecli.ai</a> | <strong>💬 Community:</strong> <a href="https://discord.gg/2QAwJn7Egx" target="_blank">Discord</a>
- </p>
- <p align="center">
- <img src="assets/ppt-process.webp" alt="OfficeCLI creating a PowerPoint presentation on AionUi" width="100%">
- </p>
- <p align="center"><em>PPT creation process using OfficeCLI on <a href="https://github.com/iOfficeAI/AionUi">AionUi</a></em></p>
- <p align="center"><strong>PowerPoint Presentations</strong></p>
- <table>
- <tr>
- <td width="33%"><img src="assets/designwhatmovesyou.gif" alt="OfficeCLI design presentation (PowerPoint)"></td>
- <td width="33%"><img src="assets/horizon.gif" alt="OfficeCLI business presentation (PowerPoint)"></td>
- <td width="33%"><img src="assets/efforless.gif" alt="OfficeCLI tech presentation (PowerPoint)"></td>
- </tr>
- <tr>
- <td width="33%"><img src="assets/blackhole.gif" alt="OfficeCLI space presentation (PowerPoint)"></td>
- <td width="33%"><img src="assets/first-ppt-aionui.gif" alt="OfficeCLI gaming presentation (PowerPoint)"></td>
- <td width="33%"><img src="assets/shiba.gif" alt="OfficeCLI creative presentation (PowerPoint)"></td>
- </tr>
- </table>
- <p align="center">—</p>
- <p align="center"><strong>Word Documents</strong></p>
- <table>
- <tr>
- <td width="33%"><img src="assets/showcase/word1.gif" alt="OfficeCLI academic paper (Word)"></td>
- <td width="33%"><img src="assets/showcase/word2.gif" alt="OfficeCLI project proposal (Word)"></td>
- <td width="33%"><img src="assets/showcase/word3.gif" alt="OfficeCLI annual report (Word)"></td>
- </tr>
- </table>
- <p align="center">—</p>
- <p align="center"><strong>Excel Spreadsheets</strong></p>
- <table>
- <tr>
- <td width="33%"><img src="assets/showcase/excel1.gif" alt="OfficeCLI budget tracker (Excel)"></td>
- <td width="33%"><img src="assets/showcase/excel2.gif" alt="OfficeCLI gradebook (Excel)"></td>
- <td width="33%"><img src="assets/showcase/excel3.gif" alt="OfficeCLI sales dashboard (Excel)"></td>
- </tr>
- </table>
- <p align="center"><em>All documents above were created entirely by AI agents using OfficeCLI — no templates, no manual editing.</em></p>
- ## For AI Agents — Get Started in One Line
- Paste this into your AI agent's chat — it will read the skill file and install everything automatically:
- ```
- curl -fsSL https://officecli.ai/SKILL.md
- ```
- That's it. The skill file teaches the agent how to install the binary and use all commands.
- ## For Humans
- **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.
- **Option B — CLI:** Download the binary for your platform from [GitHub Releases](https://github.com/iOfficeAI/OfficeCLI/releases), then run:
- ```bash
- officecli install
- ```
- 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.
- ## For Developers — See It Live in 30 Seconds
- ```bash
- # 1. Install (macOS / Linux) — or: brew install officecli / npm install -g @officecli/officecli
- curl -fsSL https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh | bash
- # Windows (PowerShell): irm https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1 | iex
- # 2. Create a blank PowerPoint
- officecli create deck.pptx
- # 3. Start live preview — opens http://localhost:26315 in your browser
- officecli watch deck.pptx
- # 4. Open another terminal, add a slide — watch the browser update instantly
- officecli add deck.pptx / --type slide --prop title="Hello, World!"
- ```
- 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.
- ## Quick Start
- ```bash
- # 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
- ```
- ```json
- {
- "tag": "shape",
- "path": "/slide[1]/shape[1]",
- "attributes": {
- "name": "TextBox 1",
- "text": "Revenue grew 25%",
- "x": "720000",
- "y": "1800000"
- }
- }
- ```
- ## Why OfficeCLI?
- What used to take 50 lines of Python and 3 separate libraries:
- ```python
- from pptx import Presentation
- from pptx.util import Inches, Pt
- prs = Presentation()
- slide = prs.slides.add_slide(prs.slide_layouts[0])
- title = slide.shapes.title
- title.text = "Q4 Report"
- # ... 45 more lines ...
- prs.save('deck.pptx')
- ```
- Now takes one command:
- ```bash
- officecli add deck.pptx / --type slide --prop title="Q4 Report"
- ```
- **What OfficeCLI can do:**
- - **Create** documents from scratch -- blank or with content
- - **Read** text, structure, styles, formulas -- in plain text or structured JSON
- - **Analyze** formatting issues, style inconsistencies, and structural problems
- - **Modify** any element -- text, fonts, colors, layout, formulas, charts, images
- - **Reorganize** content -- add, remove, move, copy elements across documents
- | Format | Read | Modify | Create |
- |--------|------|--------|--------|
- | Word (.docx) | ✅ | ✅ | ✅ |
- | Excel (.xlsx) | ✅ | ✅ | ✅ |
- | PowerPoint (.pptx) | ✅ | ✅ | ✅ |
- **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)
- **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
- **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)
- ## Use Cases
- **For Developers:**
- - Automate report generation from databases or APIs
- - Batch-process documents (bulk find/replace, style updates)
- - Build document pipelines in CI/CD environments (generate docs from test results)
- - Headless Office automation in Docker/containerized environments
- **For AI Agents:**
- - Generate presentations from user prompts (see examples above)
- - Extract structured data from documents to JSON
- - Validate and check document quality before delivery
- **For Teams:**
- - Clone document templates and populate with data
- - Automated document validation in CI/CD pipelines
- ## Installation
- Ships as a single self-contained binary. The .NET runtime is embedded -- nothing to install, no runtime to manage.
- **One-line install:**
- ```bash
- # macOS / Linux
- curl -fsSL https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh | bash
- # Windows (PowerShell)
- irm https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1 | iex
- ```
- **Or via a package manager:**
- ```bash
- # Homebrew (macOS / Linux)
- brew install officecli
- # Scoop (Windows)
- scoop install officecli
- # npm (all platforms — fetches the native binary for your platform)
- npm install -g @officecli/officecli
- ```
- **Or download manually** from [GitHub Releases](https://github.com/iOfficeAI/OfficeCLI/releases):
- | Platform | Binary |
- |----------|--------|
- | macOS Apple Silicon | `officecli-mac-arm64` |
- | macOS Intel | `officecli-mac-x64` |
- | Linux x64 | `officecli-linux-x64` |
- | Linux ARM64 | `officecli-linux-arm64` |
- | Windows x64 | `officecli-win-x64.exe` |
- | Windows ARM64 | `officecli-win-arm64.exe` |
- Verify installation: `officecli --version`
- **Or self-install from a downloaded binary (or run bare `officecli` to auto-install):**
- ```bash
- officecli install # explicit
- officecli # bare invocation also triggers install
- ```
- 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`.
- ## Key Features
- ### Built-in Engines & Generation Primitives
- OfficeCLI is self-contained. The capabilities below ship inside the binary — **no Office required**.
- #### Rendering engine — high-fidelity, built-in
- 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:
- - **`view html`** — standalone HTML file, assets inlined. Open in any browser.
- - **`view screenshot`** — per-page PNG, ready for multimodal agents to read.
- - **`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.
- ```bash
- officecli view deck.pptx html -o /tmp/deck.html
- officecli view deck.pptx screenshot -o /tmp/deck.png # add --page 1-N for more slides
- officecli watch deck.pptx # http://localhost:26315
- ```
- > 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.
- #### Formula & pivot engine
- 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.
- 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:
- ```bash
- officecli add sales.xlsx '/Sheet1' --type pivottable \
- --prop source='Data!A1:E10000' --prop rows='Region,Category' \
- --prop cols=Quarter --prop values='Revenue:sum,Units:avg' \
- --prop showDataAs=percentOfTotal
- ```
- #### Template merge — generate once, fill many
- `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.
- ```bash
- officecli merge invoice-template.docx out-001.docx --data '{"client":"Acme","total":"$5,200"}'
- officecli merge q4-template.pptx q4-acme.pptx --data data.json
- ```
- #### Round-trip dump — learn from existing docs
- `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."
- ```bash
- officecli dump existing.docx -o blueprint.json # whole document
- officecli dump existing.docx /body/tbl[1] -o table.json # any subtree
- officecli dump existing.xlsx /Sheet1 -o sheet.json # a single worksheet
- officecli batch new.docx --input blueprint.json
- ```
- ### Resident Mode & Batch
- For multi-step workflows, resident mode keeps the document in memory. Batch mode applies multiple operations in a single pass.
- ```bash
- # Resident mode — near-zero latency via named pipes
- officecli open report.docx
- officecli set report.docx /body/p[1]/r[1] --prop bold=true
- officecli set report.docx /body/p[2]/r[1] --prop color=FF0000
- officecli close report.docx
- # Batch mode — multi-command execution (atomic by default: any failed item rolls back the whole batch)
- echo '[{"command":"set","path":"/slide[1]/shape[1]","props":{"text":"Hello"}},
- {"command":"set","path":"/slide[1]/shape[2]","props":{"fill":"FF0000"}}]' \
- | officecli batch deck.pptx --json
- # Inline batch with --commands (no stdin needed)
- officecli batch deck.pptx --commands '[{"op":"set","path":"/slide[1]/shape[1]","props":{"text":"Hi"}}]'
- # Keep whatever succeeds even if some items fail (pre-1.0.137 behavior)
- officecli batch deck.pptx --input updates.json --best-effort --json
- # Stop at the first failing command instead of running the rest (still rolls back everything unless combined with --best-effort)
- officecli batch deck.pptx --input updates.json --stop-on-error --json
- ```
- > **Reading the file with another tool? Flush to disk first.**
- > 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:
- > ```bash
- > officecli set report.docx /body/p[1] --prop bold=true
- > officecli save report.docx # flush, keep the resident warm (or `close` to flush + release)
- > python my_reader.py report.docx # now sees the edit
- > ```
- > 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).
- ### Three-Layer Architecture
- Start simple, go deep only when needed.
- | Layer | Purpose | Commands |
- |-------|---------|----------|
- | **L1: Read** | Semantic views of content | `view` (text, annotated, outline, stats, issues, html, svg, screenshot) |
- | **L2: DOM** | Structured element operations | `get`, `query`, `set`, `add`, `remove`, `move`, `swap` |
- | **L3: Raw XML** | Direct XPath access — universal fallback | `raw`, `raw-set`, `add-part`, `validate` |
- ```bash
- # L1 — high-level views
- officecli view report.docx annotated
- officecli view budget.xlsx text --cols A,B,C --max-lines 50
- # L2 — element-level operations
- officecli query report.docx "run:contains(TODO)"
- officecli add budget.xlsx / --type sheet --prop name="Q2 Report"
- officecli move report.docx /body/p[5] --to /body --index 1
- # L3 — raw XML when L2 isn't enough
- officecli raw deck.pptx '/slide[1]'
- officecli raw-set report.docx document \
- --xpath "//w:p[1]" --action append \
- --xml '<w:r><w:t>Injected text</w:t></w:r>'
- ```
- ## AI Integration
- ### MCP Server
- Built-in [MCP](https://modelcontextprotocol.io) server — register with one command:
- ```bash
- officecli mcp claude # Claude Code
- officecli mcp cursor # Cursor
- officecli mcp vscode # VS Code / Copilot
- officecli mcp lmstudio # LM Studio
- officecli mcp opencode # OpenCode
- officecli mcp list # Check registration status
- ```
- Exposes all document operations as tools over JSON-RPC — no shell access needed.
- ### Direct CLI Integration
- Get OfficeCLI working with your AI agent in two steps:
- 1. **Install the binary** -- one command (see [Installation](#installation))
- 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.
- <details>
- <summary><strong>Manual setup (optional)</strong></summary>
- If auto-install doesn't cover your setup, you can install the skill file manually:
- **Feed SKILL.md to your agent directly:**
- ```bash
- curl -fsSL https://officecli.ai/SKILL.md
- ```
- **Install as a local skill for Claude Code:**
- ```bash
- curl -fsSL https://officecli.ai/SKILL.md -o ~/.claude/skills/officecli.md
- ```
- **Other agents:** Include the contents of `SKILL.md` in your agent's system prompt or tool description.
- </details>
- ### Why your agent will thrive on OfficeCLI
- - **Deterministic JSON output** — every command supports `--json` with consistent schemas. No regex parsing, no scraping stdout.
- - **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.)
- - **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.
- - **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.
- - **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.
- - **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.
- - **Template merge** — agent designs the layout once, downstream code fills `{{key}}` placeholders N times. Avoids burning tokens regenerating every report from scratch.
- - **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.
- - **Built-in help** — when unsure about property names or value formats, the agent runs `officecli <format> set <element>` instead of guessing.
- - **Auto-install** — OfficeCLI detects your AI tooling (Claude Code, Cursor, VS Code, …) and configures itself. No manual skill-file setup.
- ### Built-in Help
- Don't guess property names — drill into the help:
- ```bash
- officecli help pptx set # All settable elements and properties
- officecli help pptx set shape # Detail for one element type
- officecli help docx query # Selector reference: attributes, :contains, :has(), etc.
- ```
- Run `officecli --help` for the full overview.
- ### JSON Output Schemas
- All commands support `--json`. The general response shapes:
- **Single element** (`get --json`):
- ```json
- {"tag": "shape", "path": "/slide[1]/shape[1]", "attributes": {"name": "TextBox 1", "text": "Hello"}}
- ```
- **List of elements** (`query --json`):
- ```json
- [
- {"tag": "paragraph", "path": "/body/p[1]", "attributes": {"style": "Heading1", "text": "Title"}},
- {"tag": "paragraph", "path": "/body/p[5]", "attributes": {"style": "Heading1", "text": "Summary"}}
- ]
- ```
- **Errors** return a non-zero exit code with a structured error object including error code, suggestion, and valid values when available:
- ```json
- {
- "success": false,
- "error": {
- "error": "Slide 50 not found (total: 8)",
- "code": "not_found",
- "suggestion": "Valid Slide index range: 1-8"
- }
- }
- ```
- 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.
- **Error Recovery** -- Agents self-correct by inspecting available elements:
- ```bash
- # Agent tries an invalid path
- officecli get report.docx /body/p[99] --json
- # Returns: {"success": false, "error": {"error": "...", "code": "not_found", "suggestion": "..."}}
- # Agent self-corrects by checking available elements
- officecli get report.docx /body --depth 1 --json
- # Returns the list of available children, agent picks the right path
- ```
- **Mutation confirmations** (`set`, `add`, `remove`, `move`, `create` with `--json`):
- ```json
- {"success": true, "path": "/slide[1]/shape[1]"}
- ```
- **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.
- ## Comparison
- | | OfficeCLI | Microsoft Office | LibreOffice | python-docx / openpyxl |
- |---|---|---|---|---|
- | Open source & free | ✓ (Apache 2.0) | ✗ (paid license) | ✓ | ✓ |
- | AI-native CLI + JSON | ✓ | ✗ | ✗ | ✗ |
- | Zero install (single binary) | ✓ | ✗ | ✗ | ✗ (Python + pip) |
- | Call from any language | ✓ (CLI) | ✗ (COM/Add-in) | ✗ (UNO API) | Python only |
- | Path-based element access | ✓ | ✗ | ✗ | ✗ |
- | Raw XML fallback | ✓ | ✗ | ✗ | Partial |
- | Built-in agent-friendly rendering engine | ✓ | ✗ | ✗ | ✗ |
- | Headless HTML/PNG output | ✓ | ✗ | Partial | ✗ |
- | Template merge (`{{key}}`) across formats | ✓ | ✗ | ✗ | ✗ |
- | Round-trip dump → batch JSON | ✓ | ✗ | ✗ | ✗ |
- | Live preview (auto-refresh on edit) | ✓ | ✗ | ✗ | ✗ |
- | Headless / CI | ✓ | ✗ | Partial | ✓ |
- | Cross-platform | ✓ | Windows/Mac | ✓ | ✓ |
- | Word + Excel + PowerPoint | ✓ | ✓ | ✓ | Separate libs |
- ## Command Reference
- | Command | Description |
- |---------|-------------|
- | [`create`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-create) | Create a blank .docx, .xlsx, or .pptx (type from extension) |
- | [`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`. |
- | [`load_skill`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-skills) | Print embedded SKILL.md content for a specialized skill (no install) |
- | [`get`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-get) | Get element and children (`--depth N`, `--json`) |
- | [`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 |
- | [`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 |
- | [`add`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-add) | Add element (or clone with `--from <path>`) |
- | [`remove`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-remove) | Remove an element |
- | [`move`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-move) | Move element (`--to <parent>`, `--index N`, `--after <path>`, `--before <path>`) |
- | [`swap`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-swap) | Swap two elements |
- | [`validate`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-validate) | Validate against OpenXML schema |
- | `view <file> issues` | Enumerate document issues (text overflow, missing alt text, formula errors, ...) |
- | [`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) |
- | [`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 |
- | [`refresh`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-refresh) | Recalculate TOC page numbers / `PAGE` / cross-references (`.docx`; Word backend on Windows, headless-HTML fallback) |
- | [`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) |
- | [`merge`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-merge) | Template merge — replace `{{key}}` placeholders with JSON data |
- | [`watch`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-watch) | Live HTML preview in browser with auto-refresh |
- | [`mcp`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-mcp) | Start MCP server for AI tool integration |
- | [`raw`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-raw) | View raw XML of a document part |
- | [`raw-set`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-raw) | Modify raw XML via XPath |
- | `add-part` | Add a new document part (header, chart, etc.) |
- | [`open`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-open) | Start resident mode (keep document in memory) |
- | `close` | Save and close resident mode |
- | [`install`](https://github.com/iOfficeAI/OfficeCLI/wiki/command-install) | Install binary + skills + MCP (`all`, `claude`, `cursor`, etc.) |
- | `config` | Get or set configuration |
- | `help <format> <command>` | [Built-in help](https://github.com/iOfficeAI/OfficeCLI/wiki/command-reference) (e.g. `officecli help pptx set shape`) |
- ## End-to-End Workflow Example
- A typical self-healing agent workflow: create a presentation, populate it, verify, and fix issues -- all without human intervention.
- ```bash
- # 1. Create
- officecli create report.pptx
- # 2. Add content
- officecli add report.pptx / --type slide --prop title="Q4 Results"
- officecli add report.pptx '/slide[1]' --type shape \
- --prop text="Revenue: $4.2M" --prop x=2cm --prop y=5cm --prop size=28
- officecli add report.pptx / --type slide --prop title="Details"
- officecli add report.pptx '/slide[2]' --type shape \
- --prop text="Growth driven by new markets" --prop x=2cm --prop y=5cm
- # 3. Verify
- officecli view report.pptx outline
- officecli validate report.pptx
- # 4. Fix any issues found
- officecli view report.pptx issues --json
- # Address issues based on output, e.g.:
- officecli set report.pptx '/slide[1]/shape[1]' --prop font=Arial
- ```
- ### Units & Colors
- All dimension and color properties accept flexible input formats:
- | Type | Accepted formats | Examples |
- |------|-----------------|----------|
- | **Dimensions** | cm, in, pt, px, or raw EMU | `2cm`, `1in`, `72pt`, `96px`, `914400` |
- | **Colors** | Hex, named, RGB, theme | `#FF0000`, `FF0000`, `red`, `rgb(255,0,0)`, `accent1` |
- | **Font sizes** | Bare number or pt-suffixed | `14`, `14pt`, `10.5pt` |
- | **Spacing** | pt, cm, in, or multiplier | `12pt`, `0.5cm`, `1.5x`, `150%` |
- ## Common Patterns
- ```bash
- # Replace all Heading1 text in a Word doc
- officecli query report.docx "paragraph[style=Heading1]" --json | ...
- officecli set report.docx /body/p[1]/r[1] --prop text="New Title"
- # Export all slide content as JSON
- officecli get deck.pptx / --depth 2 --json
- # Bulk-update Excel cells
- officecli batch budget.xlsx --input updates.json --json
- # Import CSV data into an Excel sheet
- officecli add budget.xlsx / --type sheet --prop name="Q1 Data"
- officecli import budget.xlsx "/Q1 Data" sales.csv --header
- # Template merge for batch reports
- officecli merge invoice-template.docx invoice-001.docx --data '{"client":"Acme","total":"$5,200"}'
- # Check document quality before delivery
- officecli validate report.docx && officecli view report.docx issues --json
- ```
- **From Python or Node.js** — install one of the thin resident-pipe SDKs (no per-call process spawn):
- ```python
- # Python — `pip install officecli-sdk`
- import officecli
- with officecli.create("deck.pptx") as doc: # or officecli.open("deck.pptx")
- doc.send({"command": "add", "parent": "/", "type": "slide"})
- print(doc.send({"command": "get", "path": "/slide[1]"}))
- ```
- ```javascript
- // Node.js — `npm install @officecli/sdk`
- const oc = require("@officecli/sdk");
- const doc = await oc.create("deck.pptx"); // or oc.open("deck.pptx")
- await doc.send({ command: "add", parent: "/", type: "slide" });
- console.log(await doc.send({ command: "get", path: "/slide[1]" }));
- await doc.close();
- ```
- Both SDKs auto-provision the native CLI when missing (mirror-first, Windows-capable) and announce the install rather than doing it silently.
- Or wrap subprocess directly, one-shot:
- ```python
- import json, subprocess
- def cli(*args):
- return json.loads(subprocess.check_output(["officecli", *args, "--json"], text=True))
- cli("create", "deck.pptx")
- ```
- ## Documentation
- The [Wiki](https://github.com/iOfficeAI/OfficeCLI/wiki) has detailed guides for every command, element type, and property:
- - **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)
- - **Workflows:** [End-to-end examples](https://github.com/iOfficeAI/OfficeCLI/wiki/workflows) -- Word reports, Excel dashboards, PowerPoint decks, batch modifications, resident mode
- - **Runnable examples:** [examples/](examples/) -- copy-paste scripts (.sh/.py) for Word, Excel, and PowerPoint, with output files included
- - **Troubleshooting:** [Common errors and solutions](https://github.com/iOfficeAI/OfficeCLI/wiki/troubleshooting)
- - **AI agent guide:** [Decision tree for navigating the wiki](https://github.com/iOfficeAI/OfficeCLI/wiki/agent-guide)
- ## Build from Source
- 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.
- ```bash
- ./build.sh
- ```
- ## License
- [Apache License 2.0](LICENSE)
- Bug reports and contributions are welcome on [GitHub Issues](https://github.com/iOfficeAI/OfficeCLI/issues).
- ---
- If you find OfficeCLI useful, please [give it a star on GitHub](https://github.com/iOfficeAI/OfficeCLI) — it helps others discover the project.
- [OfficeCLI.AI](https://OfficeCLI.AI) | [GitHub](https://github.com/iOfficeAI/OfficeCLI)
- <!--
- yaml-frontmatter:
- name: officecli
- version: see GitHub Releases
- description: The standard CLI for AI agents to create, read, and modify Office documents
- formats: [docx, xlsx, pptx]
- platforms: [macos, linux, windows]
- license: Apache-2.0
- keywords: [office, cli, ai-agent, automation, docx, xlsx, pptx, openxml, document-generation, mcp-server, word, excel, powerpoint]
- ai-agent-compatible: true
- mcp-server: true
- skill-file: SKILL.md
- install-command-unix: curl -fsSL https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh | bash
- install-command-windows: irm https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1 | iex
- -->
- <!-- LLM/agent discovery metadata
- tool: officecli
- type: cli
- canonical: the standard CLI for AI-driven Office document manipulation
- formats: docx, xlsx, pptx
- capabilities: create, read, modify, validate, batch, resident-mode, mcp-server, live-preview, auto-install
- output: json, text, annotated
- platforms: macos, linux, windows
- license: Apache-2.0
- keywords: office, cli, ai-agent, automation, docx, xlsx, pptx, openxml, document-generation, mcp-server, word, excel, powerpoint, ai-tools, command-line, structured-output
- ai-agent-compatible: true
- mcp-server: true
- skill-file: SKILL.md
- skill-file-lines: 403
- alternatives: python-docx, openpyxl, python-pptx, libreoffice --headless
- install-command-unix: curl -fsSL https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh | bash
- install-command-windows: irm https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1 | iex
- -->
sdk/node/index.js · Bundled script · 644 lines · 2 findings marked
- 'use strict';
- /*
- * officecli — a thin Node.js shell over officecli's resident pipe.
- *
- * Node port of sdk/python/officecli.py. Same one job: forward a command to the
- * running resident over its named pipe and hand back the response. There is NO
- * second vocabulary: a command is the same object you'd put in an officecli
- * `batch` list — e.g. {command:"set", path:"/Sheet1/A1", props:{text:"Hello"}}.
- * `send` forwards one; `batch` forwards many in a single round-trip.
- *
- * Two surfaces, by design:
- * - bootstrap (infrequent): create() / open() spawn ONE CLI process — a file
- * that isn't open yet has no resident to talk to.
- * - everything else (the hot path): send() / batch() are pure pipe
- * round-trips, no per-command process spawn.
- *
- * const oc = require('@officecli/sdk');
- * const doc = await oc.create('report.xlsx', ['--force']);
- * try {
- * await doc.send({ command: 'set', path: '/Sheet1/A1', props: { text: 'Hello' } });
- * console.log(await doc.send({ command: 'get', path: '/Sheet1/A1' }));
- * } finally {
- * await doc.close();
- * }
- * // or `await using doc = await oc.open('existing.xlsx')` on Node >= 24.
- *
- * Protocol (matches ResidentServer.cs / ResidentClient.cs):
- * - pipe name : officecli-<SHA256(fullpath)[:16] uppercase>;
- * fullpath upper-cased on macOS/Windows, left as-is on Linux.
- * - unix path : $TMPDIR/CoreFxPipe_<name> (+ "-ping"); $TMPDIR else /tmp
- * - win path : \\.\pipe\<name> (+ "-ping")
- * - framing : one request line + one response line, UTF-8, '\n' terminated;
- * one connection == one command. The reply may carry a UTF-8 BOM
- * (unix StreamWriter) and a trailing '\r' — both stripped here.
- * - request : PascalCase {"Command","Args","Props","Json"}
- * - response : {"ExitCode","Stdout","Stderr"}
- */
- const os = require('os');
- const net = require('net');
- const path = require('path');
- const fs = require('fs');
- const crypto = require('crypto');
- const { spawnSync } = require('child_process');
- const IS_WIN = process.platform === 'win32';
- const IS_MAC = process.platform === 'darwin';
- // Mirror officecli's TryResident busy-delivery policy (CommandBuilder.cs): a
- // generous connect timeout + a few retries with backoff, applied identically to
- // every command. The reply read itself blocks (no timeout) — like officecli's
- // PipeReadLine — trusting the resident to answer once our turn comes up in its
- // serialized queue. Retries only re-attempt the CONNECT (before the command
- // executes), so re-sending is safe even for mutations: there is no "read timed
- // out, resend" path that could double-apply.
- const BUSY_CONNECT_TIMEOUT_MS = 30000; // = ResidentBusyConnectTimeoutMs
- const BUSY_MAX_RETRIES = 3; // = ResidentBusyMaxRetries
- // = CommandBuilder's DefaultOpenIdleSeconds. open() upgrades a reused resident
- // (which create() may have auto-started with a short 60s timeout) to the 12min
- // interactive window, so a long session over an SDK handle isn't cut short.
- const OPEN_IDLE_SECONDS = 12 * 60;
- // Installer scripts: the d.officecli.ai mirror is primary; GitHub raw is only a
- // fallback (same order as install.sh / install-binary.js). The mirror is
- // Cloudflare-fronted and reachable where raw.githubusercontent.com may be
- // rate-limited or blocked.
- const INSTALL_SH_MIRROR = 'https://d.officecli.ai/install.sh';
- const INSTALL_SH_GITHUB = 'https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh';
- const INSTALL_PS1_MIRROR = 'https://d.officecli.ai/install.ps1';
- const INSTALL_PS1_GITHUB = 'https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1';
- const MISSING_CLI =
- "officecli CLI not found: {bin} is not on PATH nor in the default install " +
- 'location (~/.local/bin, or %LOCALAPPDATA%\\OfficeCLI on Windows). This SDK only ' +
- 'forwards commands to the officecli binary, which must be installed separately. Install it:\n' +
- ' node -e "require(\'@officecli/sdk\').install()" # runs the official installer\n' +
- ' # or: curl -fsSL ' + INSTALL_SH_MIRROR + ' | bash\n' +
- ' # (npm i @officecli/sdk already pulls @officecli/officecli, which bundles the binary)\n' +
- 'Already installed elsewhere? pass { binary: "/path/to/officecli" }.';
- /**
- * Raised on transport/process failure (could not reach the resident). Business
- * outcomes are NOT exceptions — they live in the returned envelope's `success`
- * field, same as the CLI's exit code.
- */
- class OfficeCliError extends Error {
- constructor(code, msg) {
- super(`[exit ${code}] ${msg}`);
- this.name = 'OfficeCliError';
- this.code = code;
- }
- }
- // ---------------------------------------------------------------- pipe address
- function dotnetTempDir() {
- // Mirror .NET Path.GetTempPath() on Unix exactly: $TMPDIR else /tmp.
- return process.env.TMPDIR || '/tmp';
- }
- // Match the path officecli's resident hashes into the pipe name. On Windows it
- // derives the name from GetFullPath, which expands 8.3 short components (e.g.
- // RUNNER~1, or any user name > 8 chars under %TEMP%) to their long form.
- // path.resolve does NOT expand 8.3, so a short path would hash to a different
- // pipe and every connect fails with ENOENT — hence realpath, which does expand
- // it. realpath needs the file to exist; fall back to the resolved path when it
- // doesn't (e.g. pre-create). realpath ALSO resolves symlinks/junctions, which
- // GetFullPath does not; harmless here because we hand this resolved path to the
- // resident, so the server's GetFullPath sees the already-resolved string and
- // both sides hash the same thing. Windows only — on Linux/macOS officecli uses
- // GetFullPath (no symlink resolution), so realpath would diverge there
- // (e.g. /tmp → /private/tmp on macOS).
- function canonicalPath(filePath) {
- const resolved = path.resolve(filePath);
- if (IS_WIN) {
- try { return fs.realpathSync.native(resolved); } catch (_) { /* not there yet */ }
- }
- return resolved;
- }
- /** [main, ping] pipe addresses for a document path. Exposed for debugging. */
- function pipePaths(filePath) {
- let full = canonicalPath(filePath);
- if (IS_MAC || IS_WIN) full = full.toUpperCase(); // Linux: case-sensitive, no upper
- const h = crypto.createHash('sha256').update(full, 'utf8').digest('hex').toUpperCase().slice(0, 16);
- const name = `officecli-${h}`;
- if (IS_WIN) return [`\\\\.\\pipe\\${name}`, `\\\\.\\pipe\\${name}-ping`];
- const base = path.join(dotnetTempDir(), `CoreFxPipe_${name}`);
- return [base, base + '-ping'];
- }
- // ---------------------------------------------------------------- transport
- function sleep(ms) {
- return new Promise((r) => setTimeout(r, ms));
- }
- // One attempt: bound the CONNECT, then block on the reply (no read timeout) —
- // exactly like officecli's TrySend (Connect(timeout) + blocking PipeReadLine).
- function sendOnce(sockPath, line, connectTimeoutMs) {
- return new Promise((resolve, reject) => {
- let settled = false;
- const chunks = [];
- const socket = net.createConnection(sockPath);
- const connTimer = setTimeout(() => {
- if (settled) return;
- settled = true;
- socket.destroy();
- reject(new Error(`connect timed out after ${connectTimeoutMs}ms`));
- }, connectTimeoutMs);
- const fail = (err) => {
- if (settled) return;
- settled = true;
- clearTimeout(connTimer);
- socket.destroy();
- reject(err);
- };
- socket.once('connect', () => {
- clearTimeout(connTimer); // connected: stop bounding; reply read blocks
- socket.write(line);
- });
- socket.on('data', (d) => {
- chunks.push(d);
- // Line protocol: the reply is one '\n'-terminated line.
- if (d.length && d[d.length - 1] === 0x0a) {
- if (settled) return;
- settled = true;
- clearTimeout(connTimer);
- socket.end();
- resolve(Buffer.concat(chunks));
- }
- });
- socket.once('end', () => {
- if (settled) return;
- settled = true;
- clearTimeout(connTimer);
- resolve(Buffer.concat(chunks));
- });
- socket.once('error', fail);
- });
- }
- function decodeLine(raw) {
- let text = raw.toString('utf8');
- if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); // strip UTF-8 BOM (unix StreamWriter)
- if (text.charCodeAt(text.length - 1) === 0x0a) text = text.slice(0, -1); // drop the '\n' terminator
- if (text.charCodeAt(text.length - 1) === 0x0d) text = text.slice(0, -1); // and a trailing '\r'
- return text;
- }
- /**
- * Forward one request, mirroring officecli's TrySend: bounded connect + a few
- * retries with backoff, then a blocking read. A retry only re-attempts the
- * connect (before the command runs), so it never double-applies a mutation. If
- * the command still can't be delivered, raise a busy/unresponsive error — never
- * fall back to touching the file directly (that would race the resident).
- *
- * `maxRetries` overrides the busy-retry count. Liveness probes (serves) pass 0
- * so a missing/stale pipe fails FAST instead of sleeping through the backoff.
- */
- async function rpc(sockPath, req, connectTimeoutMs = BUSY_CONNECT_TIMEOUT_MS, maxRetries = BUSY_MAX_RETRIES) {
- const line = Buffer.from(JSON.stringify(req) + '\n', 'utf8');
- let raw = null;
- for (let attempt = 0; ; attempt++) {
- try {
- raw = await sendOnce(sockPath, line, connectTimeoutMs);
- break;
- } catch (e) {
- // Connect/socket error only — the command never ran, so a retry is safe.
- if (attempt >= maxRetries) {
- throw new OfficeCliError(
- -1,
- 'resident is running but the command could not be delivered ' +
- `(pipe busy or unresponsive); retry, or close and reopen [${e.message}]`
- );
- }
- await sleep(50 * (attempt + 1)); // = TrySend's 50*(n+1)ms backoff
- }
- }
- const text = decodeLine(raw);
- if (!text.trim()) {
- // Empty/closed reply: the resident accepted the connection but closed
- // without a complete response (e.g. crashed mid-serve). We refuse to
- // re-send — the command may already have been APPLIED before the resident
- // died, so re-sending would double-apply a non-idempotent op — and raise
- // instead. _cmd's recovery then restarts a dead resident and retries once.
- throw new OfficeCliError(
- -1,
- 'resident closed the connection without a response ' +
- '(it may have crashed mid-command); retry, or close and reopen'
- );
- }
- return JSON.parse(text);
- }
- function parseEnvelope(resp) {
- // Return the useful payload: the parsed JSON envelope (object/array) if Stdout
- // is JSON, otherwise the raw Stdout text ("" when empty). Accept ONLY
- // object/array — a bare JSON scalar ("42", "true", "null", a quoted string)
- // stays text, or the caller can't tell literal text "42" from the number 42.
- const out = (resp && resp.Stdout) || '';
- let v;
- try {
- v = JSON.parse(out);
- } catch (_) {
- return out;
- }
- return v !== null && typeof v === 'object' ? v : out;
- }
- function strMap(o) {
- // Drop null/undefined values (omit), and stringify the rest — the resident's
- // Args/Props are Dictionary<string,string>. A value set to null means "don't
- // send it", not "send empty string"; pass "" for an explicit empty value.
- const r = {};
- for (const k of Object.keys(o)) {
- const v = o[k];
- if (v !== null && v !== undefined) r[k] = String(v);
- }
- return r;
- }
- async function serves(pingPath, fullPath, timeoutMs = 1000) {
- // Is a resident alive on `pingPath` AND serving `fullPath`? Probes the
- // always-responsive `-ping` pipe (officecli's TryConnect): it answers even
- // while the MAIN pipe is busy. Single-shot (maxRetries=0): a probe should fail
- // fast, not sit through the busy-retry backoff.
- let resp;
- try {
- resp = await rpc(pingPath, { Command: '__ping__' }, timeoutMs, 0);
- } catch (e) {
- if (e instanceof OfficeCliError) return false;
- throw e;
- }
- const served = ((resp && resp.Stdout) || '').trim(); // ping echoes the served path
- if (!served) return false;
- const a = path.resolve(served);
- return a === fullPath || ((IS_MAC || IS_WIN) && a.toLowerCase() === fullPath.toLowerCase());
- }
- // ---------------------------------------------------------------- binary resolution
- function installDirCandidate(name) {
- // Where install.sh / install.ps1 drop the binary: ~/.local/bin on macOS/Linux,
- // %LOCALAPPDATA%\OfficeCLI on Windows. PATH-miss fallback only.
- if (IS_WIN) {
- const base = process.env.LOCALAPPDATA;
- if (!base) return null;
- const exe = name.toLowerCase().endsWith('.exe') ? name : name + '.exe';
- return path.join(base, 'OfficeCLI', exe);
- }
- return path.join(os.homedir(), '.local', 'bin', name);
- }
- function whichOnPath(name) {
- const dirs = (process.env.PATH || '').split(path.delimiter);
- const cands = IS_WIN ? [name, name + '.exe', name + '.cmd'] : [name];
- for (const dir of dirs) {
- if (!dir) continue;
- for (const c of cands) {
- const p = path.join(dir, c);
- try {
- fs.accessSync(p, fs.constants.X_OK);
- return p;
- } catch (_) {
- /* keep looking */
- }
- }
- }
- return null;
- }
- function bundledBinary() {
- // If the @officecli/officecli installer package is installed (it is a
- // dependency), prefer its vendored, auto-updating binary. Returns the path if
- // it is present on disk, else null. require is wrapped so the SDK still works
- // as a pure thin client when the dependency was omitted.
- try {
- const cli = require('@officecli/officecli');
- const p = cli.binaryPath();
- return fs.existsSync(p) ? p : null;
- } catch (_) {
- return null;
- }
- }
- function resolveBinary(binary) {
- // Order: explicit path (has a separator) is trusted as-is; then the bundled
- // installer-package binary; then PATH; then the official installer's known
- // location. Idempotent — an already-resolved absolute path passes through.
- if (binary.includes(path.sep) || binary.includes('/')) return binary;
- if (binary === 'officecli') {
- const bundled = bundledBinary();
- if (bundled) return bundled;
- }
- const found = whichOnPath(binary);
- if (found) return found;
- const cand = installDirCandidate(binary);
- if (cand) {
- try {
- fs.accessSync(cand, fs.constants.X_OK);
- return cand;
- } catch (_) {
- /* fall through */
- }
- }
- return binary; // give up; runCli raises the helpful error
- }
- async function ensureCliBinary(binary, autoInstall) {
- // Async binary resolution for the entry points (open/create), able to ACTIVELY
- // provision a missing CLI. Order: explicit path is trusted as-is; then the
- // bundled installer package (download its binary if not yet present — this is
- // the package's own signed download, not a surprise); then PATH; then the
- // installer's known location; finally, if autoInstall, run the official
- // install.sh. Returns the resolved path (or the bare name, so runCli raises
- // the helpful MISSING_CLI error if everything failed).
- if (binary.includes(path.sep) || binary.includes('/')) return binary; // explicit: trust caller
- // Accept the first candidate that actually RUNS (`--version` exit 0), in
- // priority order: the bundled (auto-updating) binary, then PATH, then the
- // installer's known location. Probing — not mere file existence — means a
- // present-but-broken binary is skipped, and a working officecli is never
- // shadowed by a needless install.
- const candidates = [];
- if (binary === 'officecli') {
- try {
- const p = require('@officecli/officecli').binaryPath();
- if (fs.existsSync(p)) candidates.push(p);
- } catch (_) { /* dependency absent */ }
- }
- const onPath = whichOnPath(binary);
- if (onPath) candidates.push(onPath);
- const cand = installDirCandidate(binary);
- if (cand) candidates.push(cand);
- for (const c of candidates) {
- if (probeVersion(c)) return c;
- }
- // Nothing usable found anywhere — provision it (only for the default name).
- if (autoInstall && binary === 'officecli') {
- process.stderr.write('[officecli] CLI not found — installing from d.officecli.ai …\n');
- try {
- const cli = require('@officecli/officecli');
- await cli.ensureBinary(); // bundled package's own signed download
- const p = cli.binaryPath();
- if (probeVersion(p)) return p;
- } catch (_) { /* fall through to the official installer */ }
- install(); // install.sh (unix) / install.ps1 (Windows)
- const after = installDirCandidate('officecli');
- if (after && probeVersion(after)) return after;
- }
- return binary; // give up → runCli raises the helpful MISSING_CLI
- }
- // Quote one token for a cmd.exe command line: ALWAYS wrap in double quotes,
- // doubling any embedded quote. Unconditional quoting (rather than "only when it
- // looks dangerous") is deliberate — it removes any reliance on enumerating every
- // cmd metacharacter. A double-quoted token cannot be re-tokenized by cmd.exe, so
- // & | < > ^ ( ) " are inert, and a %VAR% expansion stays *inside* the quotes and
- // thus can never inject a command separator (at worst the argument is mangled —
- // there is no command-line escape for %, a documented cmd.exe limitation). This
- // matters because the binary path / args may be untrusted when the SDK is driven
- // by a server. cmd /s strips the outer wrapper, leaving these per-token quotes.
- function quoteForCmd(s) {
- return `"${String(s).replace(/"/g, '""')}"`;
- }
- function spawnCli(binary, argv, extraOpts) {
- let cmd = binary;
- let args = argv;
- const opts = { encoding: 'utf8', ...extraOpts };
- if (IS_WIN && /\.(cmd|bat)$/i.test(binary)) {
- // Node refuses to spawn a .cmd/.bat directly without a shell since
- // CVE-2024-27980 (raises EINVAL). Run it through cmd.exe ourselves,
- // quoting each token so paths with spaces survive — shell:true would
- // join the args unquoted and break on the first space. Mirrors Node's
- // own shell idiom (cmd /d /s /c "<line>" + windowsVerbatimArguments)
- // but with the per-token quoting shell:true omits.
- const line = [binary, ...argv].map(quoteForCmd).join(' ');
- cmd = process.env.ComSpec || 'cmd.exe';
- args = ['/d', '/s', '/c', `"${line}"`];
- opts.windowsVerbatimArguments = true;
- }
- return spawnSync(cmd, args, opts);
- }
- function runCli(binary, argv) {
- const r = spawnCli(binary, argv);
- if (r.error && r.error.code === 'ENOENT') {
- throw new OfficeCliError(127, MISSING_CLI.replace('{bin}', JSON.stringify(binary)));
- }
- if (r.error) throw new OfficeCliError(-1, r.error.message);
- return r;
- }
- // Probe a resolved binary by running `<binary> --version`: true iff it actually
- // runs and exits 0. We accept only a WORKING officecli — a present-but-broken
- // file (wrong arch, stale/again-renamed shim, corrupt download) must not be
- // used, and conversely a working officecli on PATH must not be shadowed by a
- // needless auto-install. Output is discarded.
- function probeVersion(binPath) {
- const r = spawnCli(binPath, ['--version'], { stdio: ['ignore', 'ignore', 'ignore'] });
- return !r.error && r.status === 0;
- }
- // ---------------------------------------------------------------- the shell
- class Document {
- constructor(filePath, binary = 'officecli', timeoutMs = 30000) {
- // Canonical (Windows 8.3-expanded) so the pipe name AND the serves() path
- // comparison both match what the resident reports.
- this.path = canonicalPath(filePath);
- this.bin = resolveBinary(binary);
- this.timeout = timeoutMs; // connect timeout (ms); the reply read blocks
- const [main, ping] = pipePaths(this.path);
- this._main = main;
- this._ping = ping;
- this._restarting = null; // in-flight dead-resident restart (serializes callers)
- }
- async _start() {
- // Reuse a resident already serving this file (no spawn). serves() is a real
- // liveness probe (ping + path match), so a stale/dead socket falls through
- // to `officecli open`, which replaces it via TryConnect.
- if (await serves(this._ping, this.path)) return;
- const r = runCli(this.bin, ['open', this.path]);
- if (r.status !== 0) throw new OfficeCliError(r.status == null ? -1 : r.status, r.stderr || r.stdout);
- }
- async _cmd(command, args, props, asJson = true, timeoutMs) {
- const req = { Command: command, Json: asJson };
- if (args) req.Args = strMap(args);
- if (props !== null && props !== undefined) req.Props = strMap(props);
- const t = timeoutMs == null ? this.timeout : timeoutMs;
- try {
- return await rpc(this._main, req, t, BUSY_MAX_RETRIES);
- } catch (e) {
- if (!(e instanceof OfficeCliError)) throw e;
- // Delivery failed. Use the -ping pipe to tell DEAD from BUSY:
- // • ALIVE but main pipe unresponsive → do NOT bypass it (a second writer
- // racing the live resident loses data on its save). Re-raise.
- // • DEAD (crashed / stale socket) → restart with one `officecli open`
- // and retry ONCE. Safe across reads and mutations.
- if (await this.alive()) throw e;
- // Serialize the restart across concurrent callers sharing this Document so
- // only one spawns `officecli open` (else N-1 orphaned residents race saves).
- if (!this._restarting) {
- this._restarting = (async () => {
- if (!(await this.alive())) await this._start();
- })().finally(() => {
- this._restarting = null;
- });
- }
- await this._restarting;
- return await rpc(this._main, req, t, BUSY_MAX_RETRIES);
- }
- }
- /**
- * Forward ONE command in officecli's batch-item shape and return its parsed
- * result (the JSON envelope, or raw text for content commands). `item` is
- * exactly an object you'd put in a `batch` list:
- * { command: 'set', path: '/Sheet1/A1', props: { text: 'hi' } }
- * `command` (or `op`) picks the command, `props` becomes the property map, and
- * every other key is forwarded verbatim as a command argument. asJson=false
- * requests plain-text output (view/raw/dump), mirroring the CLI's --json.
- */
- async send(item, asJson = true, timeoutMs) {
- const command = item.command || item.op;
- if (!command) throw new OfficeCliError(-1, "send(item): item needs a 'command' (or 'op') key");
- const args = {};
- for (const k of Object.keys(item)) {
- if (k !== 'command' && k !== 'op' && k !== 'props') args[k] = item[k];
- }
- return parseEnvelope(await this._cmd(command, args, item.props, asJson, timeoutMs));
- }
- /**
- * Forward officecli's `batch`: apply a LIST of the same item objects as send()
- * in ONE round-trip — the fast path for many writes.
- */
- async batch(items, { force = true, stopOnError = false, timeoutMs } = {}) {
- const args = { batchJson: JSON.stringify(items), force, stopOnError };
- return parseEnvelope(await this._cmd('batch', args, undefined, true, timeoutMs));
- }
- // Best-effort idle-timeout upgrade over the always-responsive ping pipe.
- // Mirrors ResidentClient.SendSetIdleTimeout: a failure is non-fatal — the
- // resident keeps its original idle schedule. Single-shot (maxRetries=0).
- async _setIdleTimeout(seconds) {
- try {
- await rpc(this._ping, { Command: '__set-idle-timeout__', Args: { seconds: String(seconds) } }, this.timeout, 0);
- } catch (e) {
- if (!(e instanceof OfficeCliError)) throw e;
- }
- }
- /** True iff a resident is alive AND serving this file (probes the -ping pipe). */
- async alive(timeoutMs = 1000) {
- return serves(this._ping, this.path, timeoutMs);
- }
- /**
- * = `officecli close`: stop the resident. It flushes the in-memory doc to disk
- * as it shuts down, so no separate save is needed. The resident acks AFTER
- * shutting down, so a missing/empty ack still means "closed"; a real shutdown
- * error is a non-empty response and surfaces through the return value.
- */
- async close() {
- try {
- return parseEnvelope(await rpc(this._ping, { Command: '__close__' }, this.timeout));
- } catch (e) {
- if (!(e instanceof OfficeCliError)) throw e;
- // Only swallow if the resident is actually gone. If it's still alive (ping
- // momentarily unreachable), the close did NOT take effect — re-raise, or
- // the caller wrongly believes the file is released.
- if (await this.alive()) throw e;
- return ''; // resident gone / ack lost — end state is "closed"
- }
- }
- async [Symbol.asyncDispose]() {
- await this.close();
- }
- }
- /**
- * Create a blank Office document and return a live Document handle. Extra CLI
- * flags pass through verbatim:
- * await create('report.xlsx', ['--force']);
- * await create('doc', ['--type', 'docx']);
- * One CLI spawn (`officecli create`), which auto-starts a resident; the handle
- * binds to THAT resident (no second spawn). Inherits officecli's semantics —
- * file_locked (close it first) / file_exists (pass '--force').
- */
- async function create(filePath, args = [], { binary = 'officecli', timeoutMs = 30000, autoInstall = true } = {}) {
- const full = path.resolve(filePath);
- const bin = await ensureCliBinary(binary, autoInstall);
- const r = runCli(bin, ['create', full, ...args]);
- if (r.status !== 0) throw new OfficeCliError(r.status == null ? -1 : r.status, r.stderr || r.stdout);
- const doc = new Document(full, bin, timeoutMs);
- await doc._start(); // create auto-started a resident; this finds it alive (no extra spawn)
- return doc;
- }
- /**
- * Open an EXISTING document and return a live Document handle. `officecli open`
- * is idempotent: reuse a resident already serving this file or start one.
- *
- * Owner — `const d = await open(f); try { ... } finally { await d.close(); }`
- * Borrow — `const d = await open(f); await d.send(...)` // leave it running
- *
- * Failure model (per send/batch): a DEAD resident is transparently restarted and
- * the command retried once; an ALIVE-but-busy pipe raises OfficeCliError (retry,
- * or close() and reopen).
- */
- async function open(filePath, { binary = 'officecli', timeoutMs = 30000, autoInstall = true } = {}) {
- const bin = await ensureCliBinary(binary, autoInstall);
- const doc = new Document(filePath, bin, timeoutMs);
- await doc._start();
- // Mirror CLI `open`: when reusing a resident create() auto-started with a
- // short 60s timeout, upgrade it to the 12min interactive window. (If _start
- // spawned `officecli open` instead, that path already set 12min; re-sending
- // is idempotent.)
- await doc._setIdleTimeout(OPEN_IDLE_SECONDS);
- return doc;
- }
- /**
- * Install the officecli CLI binary via its OFFICIAL installer — explicit by
- * design (this SDK never auto-downloads behind your back). Runs install.ps1 via
- * PowerShell on Windows and install.sh via bash elsewhere. Note: when installed
- * via npm, @officecli/officecli already bundles an auto-updating binary, so this
- * is only needed for a standalone (~/.local/bin or %LOCALAPPDATA%\OfficeCLI)
- * install.
- */
- function install() {
- if (IS_WIN) {
- process.stderr.write(`Installing officecli via ${INSTALL_PS1_MIRROR} (github fallback) ...\n`);
- // Fetch the script mirror-first, github fallback, then run it. The whole
- // try/catch is assigned so a mirror failure transparently falls back.
- const ps = `$s = try { irm '${INSTALL_PS1_MIRROR}' } catch { irm '${INSTALL_PS1_GITHUB}' }; $s | iex`;
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 619 on GitHub
- const r = spawnSync('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ps], {
- stdio: 'inherit',
- });
- if (r.status !== 0) {
- throw new OfficeCliError(
- r.status == null ? -1 : r.status,
- `officecli install failed. Run manually:\n irm ${INSTALL_PS1_MIRROR} | iex`
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 626 on GitHub
- );
- }
- return;
- }
- process.stderr.write(`Installing officecli via ${INSTALL_SH_MIRROR} (github fallback) ...\n`);
- // (curl mirror || curl github) | bash — the subshell emits whichever script
- // fetch succeeds; the group keeps the pipe bound to the whole fallback.
- const sh = `(curl -fsSL ${INSTALL_SH_MIRROR} 2>/dev/null || curl -fsSL ${INSTALL_SH_GITHUB}) | bash`;
- const r = spawnSync('bash', ['-c', sh], { stdio: 'inherit' });
- if (r.status !== 0) {
- throw new OfficeCliError(
- r.status == null ? -1 : r.status,
- `officecli install failed. Run manually:\n curl -fsSL ${INSTALL_SH_MIRROR} | bash`
- );
- }
- }
- module.exports = { open, create, install, Document, OfficeCliError, pipePaths };
sdk/python/officecli.py · Bundled script · 626 lines · 2 findings marked
- r"""
- officecli — a thin Python shell over officecli's resident pipe.
- It does ONE thing: forward a command to the running resident over its named
- pipe and hand back the response. There is NO second vocabulary to learn: a
- command is the same dict you'd put in an officecli `batch` list — e.g.
- {"command":"set","path":"/Sheet1/A1","props":{"text":"Hello"}}. `send` forwards
- one; `batch` forwards many in a single round-trip.
- Two surfaces, by design:
- - bootstrap (infrequent): `create` / `open` spawn ONE CLI process — a file that
- isn't open yet (or doesn't exist yet) has no resident to talk to.
- - everything else (the hot path): `send` / `batch` are pure pipe round-trips,
- no per-command process spawn.
- import officecli
- with officecli.create("report.xlsx", "--force") as doc: # make file + get handle
- doc.send({"command": "set", "path": "/Sheet1/A1",
- "props": {"text": "Hello"}})
- print(doc.send({"command": "get", "path": "/Sheet1/A1"}))
- doc.send({"command": "save"})
- # ...or officecli.open("existing.xlsx") for a file that already exists.
- The item keys are officecli's batch fields (command/op, path, parent, type,
- index, after, before, to, selector, text, mode, depth, part, xpath, action,
- xml) plus a nested `props` dict. Everything except command/op/props is
- forwarded verbatim as a command argument; the resident dispatches it exactly
- like the matching CLI command. See `officecli help` / the batch docs for the
- field-and-prop reference — this shell adds none of its own.
- Protocol (matches ResidentServer.cs / ResidentClient.cs):
- - pipe name : officecli-<SHA256(fullpath)[:16] uppercase>;
- fullpath upper-cased on macOS/Windows, left as-is on Linux.
- - unix path : $TMPDIR/CoreFxPipe_<name> (+ "-ping"); $TMPDIR else /tmp
- - win path : \\.\pipe\<name> (+ "-ping")
- - framing : one request line + one response line, UTF-8, '\n' terminated;
- one connection == one command.
- - request : PascalCase {"Command","Args","Props","Json"}
- - response : {"ExitCode","Stdout","Stderr"}
- """
- import os
- import sys
- import json
- import time
- import socket
- import hashlib
- import shutil
- import threading
- import subprocess
- # Mirror officecli's TryResident busy-delivery policy (CommandBuilder.cs): a
- # generous connect timeout + a few retries with backoff, applied identically to
- # every command. The reply read itself blocks (no timeout) — like officecli's
- # PipeReadLine — trusting the resident to answer once our turn comes up in its
- # serialized queue. Because retries only re-attempt the CONNECT (before the
- # command executes), re-sending is safe even for mutations; there is no
- # "read timed out, resend" path that could double-apply.
- _BUSY_CONNECT_TIMEOUT = 30.0 # = ResidentBusyConnectTimeoutMs (30000)
- _BUSY_MAX_RETRIES = 3 # = ResidentBusyMaxRetries
- # = CommandBuilder's DefaultOpenIdleSeconds. `open` upgrades a reused resident
- # (which `create` may have auto-started with a short 60s timeout) to the 12min
- # interactive window, so a long editing session over an SDK handle isn't cut
- # short by the create-time timeout.
- _OPEN_IDLE_SECONDS = 12 * 60
- _IS_WIN = sys.platform.startswith("win")
- _IS_MAC = sys.platform == "darwin"
- _builtin_open = open # preserved; this module defines its own open() below
- # officecli's official installer (README one-liner). install() shells out to it;
- # the missing-CLI error points users at it / at install().
- # Installer scripts: the d.officecli.ai mirror is primary; GitHub raw is only a
- # fallback (same order as install.sh / install.ps1 themselves). The mirror is
- # Cloudflare-fronted and reachable where raw.githubusercontent.com may be
- # rate-limited or blocked.
- _INSTALL_SH_MIRROR = "https://d.officecli.ai/install.sh"
- _INSTALL_SH_GITHUB = "https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh"
- _INSTALL_PS1_MIRROR = "https://d.officecli.ai/install.ps1"
- _INSTALL_PS1_GITHUB = "https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1"
- _MISSING_CLI = (
- "officecli CLI not found: {bin!r} is not on PATH nor in the default install "
- "location (~/.local/bin, or %LOCALAPPDATA%\\OfficeCLI on Windows). This SDK only forwards "
- "commands to the officecli binary, which must be installed separately. Install it:\n"
- " python -m officecli install # runs the official installer\n"
- " # or: curl -fsSL " + _INSTALL_SH_MIRROR + " | bash\n"
- "Already installed elsewhere? pass binary=\"/path/to/officecli\"."
- )
- class OfficeCliError(Exception):
- """Raised on transport/process failure (could not reach the resident).
- Business outcomes are NOT exceptions — they live in the returned envelope's
- 'success' field, same as the CLI's exit code."""
- def __init__(self, code, msg):
- super().__init__(f"[exit {code}] {msg}")
- self.code = code
- # ---------------------------------------------------------------- pipe address
- def _dotnet_tempdir():
- # Mirror .NET Path.GetTempPath() on Unix exactly: $TMPDIR else /tmp.
- return os.environ.get("TMPDIR") or "/tmp"
- def _canonical_path(file_path):
- """Match the path officecli's resident hashes into the pipe name. On Windows
- it derives the name from GetFullPath, which expands 8.3 short components
- (RUNNER~1, or any user name > 8 chars under %TEMP%) to their long form.
- os.path.abspath does NOT expand 8.3, so a short path hashes to a different
- pipe and every connect fails with ENOENT — hence realpath, which does expand
- it. realpath needs the file to exist; fall back to the abspath when it
- doesn't. realpath ALSO resolves symlinks/junctions, which GetFullPath does
- not; harmless here because we hand this resolved path to the resident, so the
- server's GetFullPath sees the already-resolved string and both sides hash the
- same thing. Windows only — on unix officecli uses GetFullPath (no symlink
- resolution), so realpath would diverge there (e.g. /tmp -> /private/tmp on
- macOS)."""
- resolved = os.path.abspath(file_path)
- if _IS_WIN:
- try:
- return os.path.realpath(resolved)
- except OSError:
- pass
- return resolved
- def pipe_paths(file_path):
- """(main, ping) pipe addresses for a document path. Exposed for debugging."""
- full = _canonical_path(file_path)
- if _IS_MAC or _IS_WIN:
- full = full.upper() # Linux: case-sensitive, no upper
- h = hashlib.sha256(full.encode("utf-8")).hexdigest().upper()[:16]
- name = f"officecli-{h}"
- if _IS_WIN:
- return rf"\\.\pipe\{name}", rf"\\.\pipe\{name}-ping"
- base = os.path.join(_dotnet_tempdir(), f"CoreFxPipe_{name}")
- return base, base + "-ping"
- # ---------------------------------------------------------------- transport
- # One attempt: bound the CONNECT, then block on the reply (no read timeout) —
- # exactly like officecli's TrySend (Connect(timeout) + blocking PipeReadLine).
- def _send_unix(sock_path, line, connect_timeout):
- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- try:
- s.settimeout(connect_timeout)
- s.connect(sock_path)
- s.settimeout(None) # block on the reply; resident answers in turn
- s.sendall(line)
- buf = b""
- while not buf.endswith(b"\n"):
- chunk = s.recv(65536)
- if not chunk:
- break
- buf += chunk
- return buf
- finally:
- s.close()
- def _send_win(pipe_path, line, connect_timeout):
- deadline = time.time() + connect_timeout
- while True: # bound the "open" (connect) phase
- try:
- f = _builtin_open(pipe_path, "r+b", buffering=0) # not the module open()
- break
- except FileNotFoundError:
- # No pipe == no resident. Fail FAST, like _send_unix's connect()
- # raising ENOENT immediately — do NOT spin to the deadline. This is
- # what makes a max_retries=0 probe (_serves/alive) fail fast instead
- # of sitting through the whole connect_timeout when nothing is there.
- raise
- except OSError:
- # The pipe exists but the open lost the race (e.g. ERROR_PIPE_BUSY:
- # every server instance is mid-handoff). The resident IS alive, so
- # retry until the connect deadline.
- if time.time() > deadline:
- raise
- time.sleep(0.02)
- try:
- # FileIO.write (raw, buffering=0) issues a single WriteFile and may
- # return a short count, so loop until the whole request is out — a
- # truncated request leaves the resident blocking for a newline that
- # never comes, deadlocking the (untimed) reply read. Mirrors _send_unix's
- # sendall() and the C# client's Stream.Write.
- view = memoryview(line)
- sent = 0
- while sent < len(view):
- n = f.write(view[sent:])
- if n is None: # non-blocking handle not ready (shouldn't happen)
- continue
- sent += n
- buf = b""
- while not buf.endswith(b"\n"): # blocking read, like PipeReadLine
- chunk = f.read(65536)
- if not chunk:
- break
- buf += chunk
- return buf
- finally:
- f.close()
- def _rpc(sock_path, req, connect_timeout=_BUSY_CONNECT_TIMEOUT, max_retries=_BUSY_MAX_RETRIES):
- """Forward one request, mirroring officecli's TrySend: bounded connect + a few
- retries with backoff, then a blocking read. A retry only re-attempts the
- connect (before the command runs), so it never double-applies a mutation. If
- the command still can't be delivered, raise a busy/unresponsive error — never
- fall back to touching the file directly (that would race the resident).
- `max_retries` overrides the busy-retry count. Liveness probes (_serves) pass 0
- so a missing/stale pipe fails FAST instead of sleeping through ~0.3s of backoff
- — retrying a probe the resident isn't answering can't make it answer; the
- busy-retry policy is for delivering a real command to a slow-but-live pipe."""
- line = (json.dumps(req, ensure_ascii=False) + "\n").encode("utf-8")
- send = _send_win if _IS_WIN else _send_unix
- for attempt in range(max_retries + 1):
- try:
- raw = send(sock_path, line, connect_timeout)
- break
- except OSError as e:
- if attempt >= max_retries:
- raise OfficeCliError(-1,
- f"resident is running but the command could not be delivered "
- f"(pipe busy or unresponsive); retry, or close and reopen [{e}]")
- time.sleep(0.05 * (attempt + 1)) # = TrySend's 50*(n+1)ms backoff
- # utf-8-sig: the resident's StreamWriter (Encoding.UTF8) prepends a BOM the
- # C# StreamReader strips; we must too, or json.loads chokes on the leading .
- text = raw.decode("utf-8-sig")
- if not text.strip():
- # Empty/closed reply: the resident accepted the connection but closed
- # without a complete response (e.g. crashed mid-serve). We refuse to
- # re-send — the command may already have been APPLIED before the resident
- # died, so re-sending would double-apply a non-idempotent op — and raise
- # instead. officecli's TrySend now matches: its retry covers only the
- # connect phase (before the command is written); on an empty reply after a
- # successful write it returns null without re-sending, the C# equivalent of
- # this raise. _cmd's recovery then restarts a dead resident and retries once
- # (a fresh connect, before re-send), and _serves()/alive() (which swallow
- # OfficeCliError) read an empty reply as "not alive".
- raise OfficeCliError(-1,
- "resident closed the connection without a response "
- "(it may have crashed mid-command); retry, or close and reopen")
- return json.loads(text)
- def _parse(resp):
- """Return the useful payload: the parsed JSON envelope (dict/list) if Stdout is
- a JSON object/array, otherwise the raw Stdout text ("" when empty). We accept
- ONLY dict/list from json.loads — a text-mode reply that happens to BE a bare
- JSON scalar ("42", "true", "null", a quoted string) must stay text, or the
- caller can't tell literal text "42" from the number 42 (and None from a missing
- key). Faithful to the response — no synthesizing a dict for view/raw text."""
- out = resp.get("Stdout", "")
- try:
- v = json.loads(out)
- except ValueError:
- return out
- return v if isinstance(v, (dict, list)) else out
- def _strv(d):
- # Drop None-valued props (omit), matching how _cmd() drops None args — a prop
- # set to None means "don't send it", not "send empty string". Pass "" for
- # an explicit empty value.
- return {k: str(v) for k, v in d.items() if v is not None}
- def _serves(ping_path, full_path, timeout=1.0):
- """Is a resident alive on `ping_path` AND serving `full_path`? Probes the
- always-responsive `-ping` pipe (officecli's TryConnect equivalent): it answers
- even while the MAIN pipe is busy. The path-match guards against a stale socket
- serving a different/renamed file. `full_path` must already be absolute.
- Single-shot (max_retries=0): a probe should fail fast, not sit through the
- busy-retry backoff that a real command delivery uses."""
- try:
- resp = _rpc(ping_path, {"Command": "__ping__"}, timeout, max_retries=0)
- except OfficeCliError:
- return False
- served = resp.get("Stdout", "").strip() # ping echoes the served file path
- if not served:
- return False
- a = os.path.abspath(served)
- return a == full_path or ((_IS_MAC or _IS_WIN) and a.lower() == full_path.lower())
- def _install_dir_candidate(name):
- """Where the official installer (install.sh / install.ps1) drops the binary:
- ~/.local/bin on macOS/Linux, %LOCALAPPDATA%\\OfficeCLI on Windows. Used only
- as a PATH-miss fallback (see _resolve_binary)."""
- if _IS_WIN:
- base = os.environ.get("LOCALAPPDATA")
- if not base:
- return None
- exe = name if name.lower().endswith(".exe") else name + ".exe"
- return os.path.join(base, "OfficeCLI", exe)
- return os.path.join(os.path.expanduser("~"), ".local", "bin", name)
- def _resolve_binary(binary):
- """Resolve the officecli binary to invoke. Order: explicit path (a value with
- a path separator) is trusted as-is; otherwise a bare name is looked up on
- PATH; if PATH misses, fall back to the official installer's known location.
- Why the fallback: the installer adds its dir to PATH via the shell rc file, so
- a bare 'officecli' resolves in an interactive terminal — but NOT in processes
- that never sourced that rc (IDE-spawned Python, cron, systemd, CI). The binary
- is still sitting at the known install path; find it there instead of failing.
- Idempotent: an already-resolved absolute path passes straight through, so it's
- safe to call at every entry point (create + Document)."""
- if os.sep in binary or (os.altsep and os.altsep in binary):
- return binary # explicit path: trust the caller
- found = shutil.which(binary)
- if found:
- return found # on PATH: normal case
- cand = _install_dir_candidate(binary) # PATH miss: try the known install dir
- if cand and os.path.isfile(cand) and os.access(cand, os.X_OK):
- return cand
- return binary # give up; _run_cli raises the helpful error
- def _runs_ok(binary):
- """True iff `<binary> --version` actually runs and exits 0. Accept only a
- WORKING officecli — skip a present-but-broken file, and don't trigger a
- needless install when a usable officecli is already there."""
- try:
- return subprocess.run([binary, "--version"], capture_output=True).returncode == 0
- except OSError:
- return False
- def _ensure_binary(binary, auto_install=True):
- """Resolve to a WORKING officecli, provisioning one if none is found and
- auto_install is set. An explicit path (with a separator) is trusted as-is;
- otherwise each candidate (PATH, then the installer's known location) is
- accepted only when `officecli --version` actually runs — so a present-but-
- broken binary is skipped and a usable one never triggers a needless install.
- install() picks install.sh (unix) or install.ps1 (Windows), so auto-install
- works on both."""
- if os.sep in binary or (os.altsep and os.altsep in binary):
- return binary # explicit path: trust the caller
- for cand in filter(None, (shutil.which(binary), _install_dir_candidate(binary))):
- if _runs_ok(cand):
- return cand # a working officecli is already here
- if auto_install:
- print("officecli CLI not found — installing from d.officecli.ai ...", file=sys.stderr)
- install() # CLI absent/unusable → official installer
- for cand in filter(None, (shutil.which(binary), _install_dir_candidate(binary))):
- if _runs_ok(cand):
- return cand
- return binary # give up; _run_cli raises the helpful error
- def _run_cli(binary, argv):
- """Run `binary <argv...>` (capturing output). A missing binary surfaces as a
- clear OfficeCliError with install guidance, not a raw FileNotFoundError."""
- try:
- # text=True alone decodes with locale.getencoding() — the ANSI code page
- # on Windows (cp936/cp1252). The CLI always writes UTF-8, so a message
- # carrying a non-ASCII path raised UnicodeDecodeError (or mojibake) out
- # of subprocess instead of a clean OfficeCliError. The resident-pipe
- # route below already decodes utf-8; keep the two agreeing.
- return subprocess.run([binary, *argv], capture_output=True,
- text=True, encoding="utf-8", errors="replace")
- except FileNotFoundError:
- raise OfficeCliError(127, _MISSING_CLI.format(bin=binary)) from None
- # ---------------------------------------------------------------- the shell
- class Document:
- def __init__(self, path, binary="officecli", timeout=30.0):
- # Canonical (Windows 8.3-expanded) so the pipe name AND the _serves()
- # path comparison both match what the resident reports.
- self.path = _canonical_path(path)
- self.bin = _resolve_binary(binary)
- self.timeout = timeout # connect timeout (s); the reply read blocks
- self._main, self._ping = pipe_paths(self.path)
- self._restart_lock = threading.Lock() # serialize dead-resident restarts
- self._start()
- def _start(self):
- # If a resident is ALREADY serving this file, reuse it — no process spawn.
- # Mirrors officecli, where a command after `create` reuses the resident
- # `create` auto-started instead of re-running `open`. _serves() is a real
- # liveness probe (ping the -ping pipe + verify the served path), not a
- # socket-file-exists check, so a stale/dead socket fails the probe and
- # falls through to `officecli open`, which replaces it via TryConnect.
- # (A plain os.path.exists() here would wrongly skip on a stale socket.)
- if _serves(self._ping, self.path):
- return
- # Otherwise spawn `officecli open` (one process). It's idempotent and uses
- # the same TryConnect to start a fresh resident or replace a stale socket.
- r = _run_cli(self.bin, ["open", self.path])
- if r.returncode != 0:
- raise OfficeCliError(r.returncode, r.stderr or r.stdout)
- # -- transport primitive: build {Command,Args,Props,Json}, forward, parse --
- def _cmd(self, command, args=None, props=None, as_json=True, timeout=None):
- # `as_json`, not `json`, so we don't shadow the imported json module.
- # timeout=None uses this Document's default (self.timeout). It bounds the
- # CONNECT/delivery (with retries); the reply read blocks, so a legitimately
- # slow command isn't cut off — it waits for the resident, like officecli.
- req = {"Command": command, "Json": as_json}
- if args:
- req["Args"] = {k: str(v) for k, v in args.items() if v is not None}
- if props is not None:
- req["Props"] = _strv(props)
- t = self.timeout if timeout is None else timeout
- try:
- return _rpc(self._main, req, t)
- except OfficeCliError:
- # Delivery failed after _rpc's own connect retries. Use the -ping pipe
- # to tell DEAD from BUSY — officecli's own distinction (alive()):
- # • ALIVE but main pipe unresponsive → do NOT bypass it. officecli
- # deliberately dropped the direct-file fallback: a second writer
- # racing the live resident loses data on its eventual save. Re-raise
- # the busy error so the caller can retry or close+reopen.
- # • DEAD (crashed / stale socket) → restart with one `officecli open`
- # and retry ONCE. Safe across reads and mutations: mutations live in
- # memory until save/close, so a crash loses them and disk holds the
- # last save — replaying against the restarted (disk-state) resident
- # reproduces the lost op once, with nothing live to double-apply.
- if self.alive():
- raise
- # Serialize the restart across threads sharing this Document. Without
- # the lock, N concurrent callers each see alive()==False and each spawn
- # `officecli open`, leaving N-1 orphaned residents on the same file
- # (which can then race each other's save). Re-check alive() inside the
- # lock so only the first thread restarts; the rest find it back up.
- with self._restart_lock:
- if not self.alive():
- self._start()
- return _rpc(self._main, req, t)
- # -- the surface: send ONE batch-shaped command, or a LIST of them ---------
- def send(self, item, as_json=True, timeout=None):
- """Forward ONE command in officecli's batch-item shape and return its
- parsed result (the JSON envelope, or raw text for content commands).
- `item` is exactly a dict you'd put in a `batch` list, e.g.
- {"command": "set", "path": "/Sheet1/A1", "props": {"text": "hi"}}
- {"command": "get", "path": "/Sheet1/A1"}
- Keys are officecli's batch fields; `command` (or `op`) picks the command,
- `props` becomes the property map, and every other key is forwarded
- verbatim as a command argument — no field list maintained here, so new
- officecli fields work without touching this shell.
- `as_json=False` requests plain-text output (view/raw/dump), mirroring the
- CLI's --json toggle."""
- command = item.get("command") or item.get("op")
- if not command:
- raise OfficeCliError(-1, "send(item): item needs a 'command' (or 'op') key")
- args = {k: v for k, v in item.items() if k not in ("command", "op", "props")}
- return _parse(self._cmd(command, args, item.get("props"),
- as_json=as_json, timeout=timeout))
- def batch(self, items, force=True, stop_on_error=False, timeout=None):
- """Forward officecli's `batch` command: apply a LIST of the same item
- dicts as `send` in ONE round-trip — the fast path for many writes. Same
- contract as `send`, just plural."""
- args = {"batchJson": json.dumps(items, ensure_ascii=False),
- "force": force, "stopOnError": stop_on_error}
- return _parse(self._cmd("batch", args, timeout=timeout))
- def _set_idle_timeout(self, seconds):
- # Best-effort idle-timeout upgrade, served on the always-responsive ping
- # pipe (bypasses _commandLock, answers even while the main pipe is busy).
- # Mirrors ResidentClient.SendSetIdleTimeout: a failure is non-fatal — the
- # resident is still usable, it just keeps its original idle schedule.
- # Single-shot (max_retries=0): don't sit through the busy backoff for a
- # best-effort nicety.
- try:
- _rpc(self._ping, {"Command": "__set-idle-timeout__",
- "Args": {"seconds": str(seconds)}},
- self.timeout, max_retries=0)
- except OfficeCliError:
- pass
- def alive(self, timeout=1.0):
- """Return True iff a resident is alive AND serving this file. Probes the
- always-responsive `-ping` pipe (officecli's TryConnect), which answers even
- while the MAIN pipe is busy — so it distinguishes "alive but busy" from
- "gone". This is the discriminator `_cmd` uses on a delivery failure (busy →
- raise, gone → restart+retry); send/batch already auto-recover from a gone
- resident, so call this only when you want to check liveness yourself."""
- return _serves(self._ping, self.path, timeout)
- # -- lifecycle ------------------------------------------------------------
- def close(self):
- # = `officecli close`: stop the resident. It flushes the in-memory doc to
- # disk as it shuts down (handler.Dispose), so no separate save is needed —
- # verified: a set followed by __close__ alone lands on disk.
- #
- # The resident acks AFTER shutting down, so a missing/empty ack (lost to a
- # crash or the 5s write-timeout) still means "closed". A real shutdown
- # data-loss is a NON-empty error response, so it surfaces through _parse.
- try:
- return _parse(_rpc(self._ping, {"Command": "__close__"}, self.timeout))
- except OfficeCliError:
- # Only swallow if the resident is actually gone. If it's still alive
- # (ping pipe was momentarily unreachable/busy), the close did NOT take
- # effect — re-raise, or the caller wrongly believes the file is released
- # and may race a re-open/overwrite.
- if self.alive():
- raise
- return "" # resident gone / ack lost — end state is "closed"
- def __enter__(self):
- return self
- def __exit__(self, *a):
- # `with` means "I manage this session" → close on exit. To only borrow a
- # resident another program owns, DON'T use `with` and DON'T call close():
- # d = officecli.open(f); d.send(...) # left running
- self.close()
- def create(path, *args, binary="officecli", timeout=30.0, auto_install=True):
- """Create a blank Office document and return a live `Document` handle for it.
- Parallel to `open`: both return the session handle you actually work with —
- they differ only in the file's expected state. `open` requires an existing
- file; `create` makes a new one (like file mode "x" vs "r"). Extra CLI flags
- pass through verbatim, so there's no option list maintained here:
- with officecli.create("report.xlsx", "--force") as doc:
- doc.send({"command": "set", "path": "/Sheet1/A1", "props": {"text": "hi"}})
- officecli.create("doc", "--type", "docx")
- One CLI spawn (`officecli create`), which also auto-starts a resident for the
- new file; the returned Document binds to THAT resident (no second spawn).
- Raises OfficeCliError on failure, inheriting officecli's exact semantics:
- • file held by a LIVE resident → file_locked (close it first). We do NOT
- silently close+overwrite it — in a shared workspace that resident may be
- another owner's active session.
- • file exists without --force → file_exists (pass "--force" to overwrite)."""
- full = os.path.abspath(path)
- binary = _ensure_binary(binary, auto_install)
- r = _run_cli(binary, ["create", full, *args])
- if r.returncode != 0:
- raise OfficeCliError(r.returncode, r.stderr or r.stdout)
- # create auto-started a resident for the new file; bind a handle to it
- # (Document.__init__ -> _start -> _serves finds it alive, so no extra spawn).
- return Document(full, binary=binary, timeout=timeout)
- def open(path, binary="officecli", timeout=30.0, auto_install=True):
- """Open an EXISTING document and return a live `Document` handle (parallel to
- `create`, which makes a new file). `officecli open` is idempotent: it reuses a
- resident already serving this file or starts one — and if a live resident is
- already up, no process is spawned at all.
- Lifecycle:
- Owner — `with officecli.open(f) as d: ...` (exit closes the resident)
- Borrow — `d = officecli.open(f); d.send(...)` (no `with`/close → left running)
- Failure model (applies to every send/batch on the handle):
- • resident DEAD/gone (crash, idle-timeout, missing pipe) → transparently
- restarted and the command retried once; the caller sees no error.
- • resident ALIVE but the pipe is unresponsive (busy) → raises OfficeCliError
- — never a deadlock, and never bypassing the live resident (that would race
- its save and lose data). Retry, or close() and reopen.
- `timeout` bounds command DELIVERY (connect + retries) in seconds, mirroring
- officecli's TrySend; the reply read itself blocks (a busy resident answers in
- turn). Override per call via send(..., timeout=...) / batch(..., timeout=...);
- use alive() to probe liveness."""
- doc = Document(path, binary=_ensure_binary(binary, auto_install), timeout=timeout)
- # Mirror CLI `open`: when reusing a resident `create` auto-started with a
- # short 60s timeout, upgrade it to the 12min interactive window. (If _start
- # spawned `officecli open` instead, that path already set 12min; re-sending
- # is idempotent.)
- doc._set_idle_timeout(_OPEN_IDLE_SECONDS)
- return doc
- def install():
- """Install the officecli CLI binary via its OFFICIAL installer — install.sh on
- unix, install.ps1 on Windows. Reuses officecli's own installers (platform
- detection + checksum + ~/.local/bin or %LOCALAPPDATA%\\OfficeCLI), rather than
- reimplementing download logic that would drift from upstream.
- Called automatically by open()/create() when the CLI is missing (pass
- auto_install=False to disable), and exposed directly as `python -m officecli
- install`. Returns None on success; raises OfficeCliError on failure. Output is
- NOT captured, so the installer's progress and checksum lines stream to the
- user."""
- if _IS_WIN:
- print(f"Installing officecli via {_INSTALL_PS1_MIRROR} (github fallback) ...", file=sys.stderr)
- # Windows PowerShell (powershell.exe) ships with the OS; -ExecutionPolicy
- # Bypass lets the remote script run without changing machine policy. Fetch
- # the script mirror-first, github fallback, then run it.
- ps = (f"$s = try {{ irm '{_INSTALL_PS1_MIRROR}' }} "
- f"catch {{ irm '{_INSTALL_PS1_GITHUB}' }}; $s | iex")
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 595 on GitHub
- r = subprocess.run(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps])
- if r.returncode != 0:
- raise OfficeCliError(r.returncode,
- f"officecli install failed (exit {r.returncode}). Run manually:\n"
- f" irm {_INSTALL_PS1_MIRROR} | iex")
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 600 on GitHub
- return None
- print(f"Installing officecli via {_INSTALL_SH_MIRROR} (github fallback) ...", file=sys.stderr)
- # (curl mirror || curl github) | bash — the subshell emits whichever fetch
- # succeeds; the group keeps the pipe bound to the whole fallback. Output is
- # NOT captured, so progress and checksum lines stream to the user.
- sh = f"(curl -fsSL {_INSTALL_SH_MIRROR} 2>/dev/null || curl -fsSL {_INSTALL_SH_GITHUB}) | bash"
- r = subprocess.run(["bash", "-c", sh])
- if r.returncode != 0:
- raise OfficeCliError(r.returncode,
- f"officecli install failed (exit {r.returncode}). Run manually:\n"
- f" curl -fsSL {_INSTALL_SH_MIRROR} | bash")
- return None
- # Advertised surface = the command shell + its error. pipe_paths stays importable
- # (officecli.pipe_paths) as a debug helper but isn't part of the command API.
- __all__ = ["open", "create", "install", "Document", "OfficeCliError"]
- if __name__ == "__main__":
- # `python -m officecli install` — bootstrap the CLI binary.
- if len(sys.argv) >= 2 and sys.argv[1] == "install":
- install()
- else:
- print("usage: python -m officecli install", file=sys.stderr)
- sys.exit(2)
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.