# https://github.com/iOfficeAI/OfficeCLI Project Manual

Generated at: 2026-07-06 17:49:22 UTC

## Table of Contents

- [Overview & Architecture](#page-1)
- [Document Operations & Command Reference](#page-2)
- [Resident Mode, Batch Execution & Live Preview](#page-3)
- [AI Integration, Templates & Advanced Features](#page-4)

<a id='page-1'></a>

## Overview & Architecture

### Related Pages

Related topics: [Document Operations & Command Reference](#page-2), [Resident Mode, Batch Execution & Live Preview](#page-3), [AI Integration, Templates & Advanced Features](#page-4)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/iOfficeAI/OfficeCLI/blob/main/README.md)
- [src/officecli/Program.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Program.cs)
- [src/officecli/CommandBuilder.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.cs)
- [officecli.slnx](https://github.com/iOfficeAI/OfficeCLI/blob/main/officecli.slnx)
- [build.sh](https://github.com/iOfficeAI/OfficeCLI/blob/main/build.sh)
- [install.sh](https://github.com/iOfficeAI/OfficeCLI/blob/main/install.sh)
</details>

# Overview & Architecture

## Purpose & Scope

OfficeCLI is a command-line interface for programmatic creation and editing of Microsoft Office documents (`.docx`, `.xlsx`, `.pptx`) from a terminal, shell, or AI agent. It is designed so that LLM-based assistants and automation pipelines can read, mutate, and watch Office files without launching Word, Excel, or PowerPoint, while still producing structurally valid OOXML output.

The project is distributed as a single C#/.NET solution (`officecli.slnx`) with a primary executable named `officecli`. It is consumed through three primary surfaces:

- A **batch / one-shot CLI** that runs a single command against a file and exits.
- A **Resident Server** that holds a file open, locks it, and applies successive edits quickly without re-parsing the OOXML package on every call.
- A **Watcher** that streams Server-Sent Events (SSE) describing patches applied to the file, enabling live previews.

Source: [README.md:1-40]()

The tool is intentionally shell-friendly: every subcommand emits a JSON envelope (`{ "success": ..., "message": ... }`) so that AI agents can parse results reliably. Community issue #63 documents recurring failures where an agent reuses CLI commands while a Resident is still holding a file, leading to "main pipe busy or unresponsive" errors — a reminder that Resident lifecycle is a first-class architectural concern, not an internal detail.

Source: [src/officecli/Program.cs:1-120]()

## Solution & Build Layout

The repository is a single .NET solution. `officecli.slnx` aggregates the executable project under `src/officecli/`. The build is wrapped by `build.sh`, which compiles the C# entry points, while `install.sh` publishes the binary into the user's `PATH` so that AI skills (e.g., Codex, Hermes) and shell scripts can invoke `officecli` directly.

Source: [officecli.slnx:1-20]()
Source: [build.sh:1-30]()
Source: [install.sh:1-40]()

`Program.cs` is the composition root: it parses argv, dispatches to the command parser, and decides whether the invocation should run as a one-shot CLI, attach to an existing Resident Server, or spawn a new resident process for the given file. `CommandBuilder.cs` is responsible for translating verb–noun pairs (e.g., `xlsx add`, `word set`, `ppt batch`) into the strongly-typed internal request objects that the Office backends consume.

Source: [src/officecli/Program.cs:120-260]()
Source: [src/officecli/CommandBuilder.cs:1-80]()

## High-Level Architecture

```mermaid
flowchart LR
    A[CLI / AI Agent] -->|argv| B[Program.cs]
    B --> C{Resident alive?}
    C -- no --> D[Spawn ResidentServer]
    C -- yes --> E[IPC pipe]
    D --> F[Document Backend]
    E --> F
    F[docx/xlsx/pptx backend] --> G[(OOXML file on disk)]
    F --> H[Watch SSE stream]
    H --> I[Browser / Preview UI]
```

Three layers are visible:

1. **Front-end shell** — argv parsing, command construction, JSON formatting. Backed by `Program.cs` and `CommandBuilder.cs`.
2. **Resident Server** — long-lived process keyed per file. Owns the in-memory OOXML model and a write lock so concurrent invocations do not corrupt the package.
3. **Document backends** — format-specific modules that mutate the OOXML tree for `.docx`, `.xlsx`, and `.pptx`.

The Resident Server is what makes OfficeCLI usable for agents that issue many small edits in a row: instead of re-opening the file each time, commands are delivered over an internal pipe and the file is flushed at the end of each operation.

Source: [src/officecli/Program.cs:260-400]()
Source: [src/officecli/CommandBuilder.cs:80-160]()

## Resident Server, Locks & Live Watch

The Resident model is also the source of the most common user-reported pitfalls:

- **File-lock conflicts (issue #63).** Because a Resident keeps the file open, calling a non-resident command path while a Resident is alive can return `success: false` with `"main pipe busy or unresponsive"`. The recommended recovery is to either retry the same command — so it is routed through the Resident — or run `officecli close <file>` to release the lock.

  Source: [src/officecli/Program.cs:400-520]()

- **Watch SSE patches (issue #169).** The `watch <file>` command subscribes to patch notifications. Single operations (`add`, `set`, `move`, `remove`) emit `word-patch`, `replace`, or `excel-patch` SSE events so a preview pane can refresh in place. However, `batch` and `create --force` historically bypassed this notification path. v1.0.129 fixes this by routing `ResidentServer.ExecuteBatch` through the same `NotifyWatch*` hooks, so all edit paths now produce live SSE updates.

  Source: [src/officecli/Program.cs:520-640]()

- **Bind address (issue #167).** The watch endpoint currently binds to `localhost` only; exposing it on `0.0.0.0` is tracked as a feature request and would require an additional `--host` flag plumbed through `Program.cs` into the HTTP/SSE host.

  Source: [src/officecli/Program.cs:640-720]()

## Command Surface

OfficeCLI exposes a verb–noun command grammar rather than per-file subcommands. The shape, constructed in `CommandBuilder.cs`, looks roughly like:

| Verb    | Targets           | Purpose                                    |
|---------|-------------------|--------------------------------------------|
| `add`   | docx / xlsx / pptx| Append rows, paragraphs, or slides         |
| `set`   | docx / xlsx / pptx| Mutate an existing cell, run, or shape     |
| `move`  | xlsx              | Reorder rows or sheets                     |
| `remove`| docx / xlsx / pptx| Delete an element by id                    |
| `batch` | docx / xlsx / pptx| Apply many edits in one Resident call      |
| `create`| docx / xlsx / pptx| Generate a new file (`--force` to overwrite)|
| `close` | any               | Terminate the Resident for a file          |
| `watch` | any               | Start the SSE preview stream               |

Source: [src/officecli/CommandBuilder.cs:160-280]()
Source: [src/officecli/CommandBuilder.cs:280-360]()

This grammar is deliberately narrow: each verb maps to exactly one backend method, which keeps prompts sent to LLMs short and predictable. Template reuse — copying styles, headers, and numbering from an existing `.docx` into a freshly generated one, as asked in issue #168 — is therefore expressed as a `create` that references a template file plus a `batch` of style applications, rather than a dedicated `template` subcommand.

Source: [README.md:40-120]()
Source: [src/officecli/CommandBuilder.cs:360-440]()

Taken together, the architecture is a thin orchestration layer: a CLI front-end, a per-file Resident with a notification bus, and three format backends. The architectural invariants to keep in mind when extending the project are that every edit must flow through the Resident's `NotifyWatch*` path (so previews stay live) and that all responses must remain JSON envelopes (so AI agents can parse them).

---

<a id='page-2'></a>

## Document Operations & Command Reference

### Related Pages

Related topics: [Overview & Architecture](#page-1), [Resident Mode, Batch Execution & Live Preview](#page-3)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/officecli/CommandBuilder.Add.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Add.cs)
- [src/officecli/CommandBuilder.Set.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Set.cs)
- [src/officecli/CommandBuilder.GetQuery.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.GetQuery.cs)
- [src/officecli/CommandBuilder.View.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.View.cs)
- [src/officecli/CommandBuilder.Raw.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Raw.cs)
- [src/officecli/CommandBuilder.Help.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Help.cs)
</details>

# Document Operations & Command Reference

## Purpose and Scope

`officecli` is a CLI tool that exposes Office document operations (`xlsx`, `docx`, `pptx`) to AI agents and automation pipelines. The `CommandBuilder.*` partial-class files together form the **command surface** — they translate CLI verbs (`add`, `set`, `get`, `query`, `view`, `raw`, `help`) into typed operations against a resident document server. Each builder is responsible for argument parsing, validation, and dispatching the request to the appropriate handler for the active document type.

The scope of this page is the **document-operation command set**: how reads, writes, and previews are expressed on the CLI, and how those verbs map to the underlying builder classes. Background services such as the resident server, watch/SSE pipeline, and template engines are covered separately.

Source: [src/officecli/CommandBuilder.Help.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Help.cs)

## Command Verbs at a Glance

The CLI groups operations into six core verbs, each implemented by its own builder file. The table below summarizes what each verb does and which source file owns its definition.

| Verb | Source file | Primary role |
|------|-------------|--------------|
| `add` | `CommandBuilder.Add.cs` | Append cells, rows, paragraphs, or slides to an existing document |
| `set` | `CommandBuilder.Set.cs` | Overwrite a cell, range, paragraph, or property at a target index |
| `get` / `query` | `CommandBuilder.GetQuery.cs` | Read structured data and metadata from the document |
| `view` | `CommandBuilder.View.cs` | Render a preview (HTML / SSE) for human or agent inspection |
| `raw` | `CommandBuilder.Raw.cs` | Escape hatch: pass an unparsed payload for advanced operations |
| `help` | `CommandBuilder.Help.cs` | Emit usage text, examples, and the per-verb flag list |

Source: [src/officecli/CommandBuilder.Add.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Add.cs), [src/officecli/CommandBuilder.Set.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Set.cs), [src/officecli/CommandBuilder.GetQuery.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.GetQuery.cs), [src/officecli/CommandBuilder.View.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.View.cs), [src/officecli/CommandBuilder.Raw.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Raw.cs), [src/officecli/CommandBuilder.Help.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Help.cs)

## Write Operations: `add` and `set`

`add` and `set` are the two mutating verbs. They are dispatched through the resident server so that the file lock is held by a single process and concurrent edits do not corrupt the workbook.

- `add` appends a new element (a row, cell, paragraph, or slide) at the next available position. The builder validates required arguments — such as target sheet, target document, and content payload — and rejects malformed inputs before the request leaves the CLI.
- `set` targets an **existing** location specified by an index, address (e.g. `B3`), or range. It is the verb to use when an AI agent already knows where a value belongs.

A common failure mode in agent workflows is the "main pipe busy" error: the resident is running but the command cannot be delivered because the previous request has not drained. Community issue #63 documents this behavior in the context of AionUi + Codex; the recommended recovery is to retry, or to run `officecli close` and reopen the document before issuing a new mutation.

Source: [src/officecli/CommandBuilder.Add.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Add.cs), [src/officecli/CommandBuilder.Set.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Set.cs)

## Read and Preview Operations: `get`, `query`, `view`

Read-side verbs let an agent inspect the document before deciding what to write.

- `get` / `query` returns structured data: cell values, sheet names, paragraph text, slide titles, or document metadata. `CommandBuilder.GetQuery.cs` owns the flag set that controls pagination, range selection, and output format (JSON vs. plain text).
- `view` produces a renderable representation intended for both humans and downstream consumers. For Word and Excel, `view` emits the same patch primitives (`word-patch`, `replace`, `excel-patch`) that the watch SSE stream uses to live-update a preview when a single command is executed.

A note from the field: `view` is the entry point used by `officecli watch <file>`. Community issue #169 reported that `batch` and `create --force` did not trigger a content patch, so the preview would not refresh until the next single-command edit. This was fixed in v1.0.129 by routing resident batch edits through the watch notification path.

Source: [src/officecli/CommandBuilder.GetQuery.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.GetQuery.cs), [src/officecli/CommandBuilder.View.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.View.cs)

## Escape Hatches and Discoverability: `raw` and `help`

When the typed verbs are insufficient — for example, when an agent needs to apply a complex template format that maps cleanly onto the underlying Office API — `raw` forwards a payload directly to the document handler. This is the verb most relevant to issue #168, where users want to reuse an existing report's cover page, table of contents, header, and footer on a newly generated `docx`. Because template work frequently falls outside the curated verb set, `raw` is the documented fallback.

`help` is the discoverability surface. `CommandBuilder.Help.cs` produces per-verb usage text, flag lists, and worked examples. It is the recommended first call for any agent session: it enumerates which verbs are available for the active document type (`xlsx`, `docx`, `pptx`) and which flags each verb accepts.

Source: [src/officecli/CommandBuilder.Raw.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Raw.cs), [src/officecli/CommandBuilder.Help.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Help.cs)

## Worked Command Flow

The diagram below shows how a single mutating command travels from the CLI to the resident server and back to the agent.

```mermaid
sequenceDiagram
    participant Agent
    participant CLI as officecli (CommandBuilder)
    participant Resident as ResidentServer
    participant Watch as watch SSE
    Agent->>CLI: officecli set file.xlsx B3 "=SUM(A1:A2)"
    CLI->>Resident: dispatch typed SetRequest
    Resident->>Resident: apply mutation, hold file lock
    Resident-->>Watch: notify (single command)
    Watch-->>Agent: excel-patch SSE event
    Resident-->>CLI: success envelope
    CLI-->>Agent: JSON result
```

The notification step on the right is the same path that v1.0.129 extended to `batch` and `create --force`, so the preview now updates regardless of which mutating verb was used.

Source: [src/officecli/CommandBuilder.Set.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Set.cs), [src/officecli/CommandBuilder.Add.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Add.cs)

## Practical Guidance for Agents

- Always start a session with `officecli help` to enumerate verbs for the current document type. Source: [src/officecli/CommandBuilder.Help.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Help.cs)
- Prefer `get` / `query` over parsing the file directly; the builder returns a stable JSON shape. Source: [src/officecli/CommandBuilder.GetQuery.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.GetQuery.cs)
- For template-heavy output (issue #168), fall back to `raw` rather than composing many small `set` calls. Source: [src/officecli/CommandBuilder.Raw.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Raw.cs)
- If the resident returns a "pipe busy" error (issue #63), retry after a short back-off or `officecli close` and reopen. Source: [src/officecli/CommandBuilder.Set.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Set.cs)
- On v1.0.129 or later, `batch` and `create --force` now refresh the watch preview (issue #169). Source: [src/officecli/CommandBuilder.View.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.View.cs)

---

<a id='page-3'></a>

## Resident Mode, Batch Execution & Live Preview

### Related Pages

Related topics: [Document Operations & Command Reference](#page-2), [AI Integration, Templates & Advanced Features](#page-4)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/officecli/ResidentServer.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/ResidentServer.cs)
- [src/officecli/ResidentClient.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/ResidentClient.cs)
- [src/officecli/Core/BatchExecutor.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/BatchExecutor.cs)
- [src/officecli/CommandBuilder.Batch.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Batch.cs)
- [src/officecli/CommandBuilder.Watch.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Watch.cs)
- [src/officecli/Core/Watch/WatchServer.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchServer.cs)
- [src/officecli/Program.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Program.cs)
</details>

# Resident Mode, Batch Execution & Live Preview

OfficeCLI exposes a long-running, per-file **resident** process so that AI agents and human operators can edit `.docx`, `.xlsx`, and `.pptx` files repeatedly without paying the cost of re-opening the Office SDK on every call. On top of the resident, two complementary capabilities are layered:

- **Batch execution** — many commands applied against a single resident in one round-trip.
- **Live preview** — an SSE-based `watch` channel that pushes content patches to any open browser tab.

Together they form the editing backbone used by the CLI's `add`, `set`, `move`, `remove`, `batch`, and `watch` subcommands.

## Architecture Overview

A resident is launched by the CLI when the first command targeting a file needs persistent state. Subsequent invocations of `officecli` locate the existing resident via a named pipe (`ResidentServer`) and dispatch commands through a request/response protocol (`ResidentClient`). Batch and single-shot commands share the same pipe, but batches are routed to a dedicated executor inside the resident.

```mermaid
flowchart LR
    CLI[officecli CLI<br/>Program.cs] -->|named pipe| RS[ResidentServer]
    RS --> BE[BatchExecutor]
    RS --> SS[Single Command Handler]
    BE -->|NotifyWatch*| WS[WatchServer]
    SS -->|NotifyWatch*| WS
    WS -->|SSE /word-patch, /excel-patch, /replace| Browser[Browser Preview]
```

Source: [src/officecli/Program.cs:1-120](), [src/officecli/ResidentServer.cs:1-80](), [src/officecli/Core/Watch/WatchServer.cs:1-60]().

## Resident Mode

`ResidentServer` is the long-lived host. It owns the open Office document, the SDK session, and any in-memory caches needed for repeated edits. When the CLI is invoked with a target file, the program either:

1. **Spawns** a new resident if no pipe is registered for that file, or
2. **Attaches** to an existing resident through `ResidentClient`, which negotiates the pipe name and sends a serialized command frame.

The resident holds the file lock for its lifetime, which is exactly what makes the **"file lock conflict"** error in issue #63 possible: if a second resident tries to open the same workbook while the first is alive, the SDK refuses. The reported symptom — `"Resident for test_data_table.xlsx is running but the command could not be delivered (main pipe busy or unresponsive)"` — comes from `ResidentClient` timing out while writing to that single shared pipe. Users are advised to call `officecli close <file>` before retrying.

Source: [src/officecli/ResidentServer.cs:1-200](), [src/officecli/ResidentClient.cs:1-150]().

## Batch Execution

The `batch` subcommand is wired in `CommandBuilder.Batch.cs` and forwarded, once attached to a resident, to `Core/BatchExecutor.cs`. A batch carries an ordered list of operations that mutate the same resident document; the executor applies them sequentially, shares intermediate state, and returns a single aggregated result. This avoids:

- Repeated pipe round-trips per command.
- Re-loading the document between edits.
- Partial-application ambiguity on failure.

Because every batch operation runs inside the resident, the executor is the natural place to emit post-mutation notifications. Prior to v1.0.129, `BatchExecutor` did **not** call the `NotifyWatch*` hooks that single-shot handlers emit after `add` / `set` / `move` / `remove`. This is the root cause documented in issue #169: `ResidentServer.ExecuteBatch never calls NotifyWatch*`.

Source: [src/officecli/CommandBuilder.Batch.cs:1-120](), [src/officecli/Core/BatchExecutor.cs:1-180]().

## Live Preview via `watch`

`officecli watch <file>` boots `Core/Watch/WatchServer.cs`, an SSE endpoint that streams content patches to connected browsers. The server registers listeners with the resident; whenever a single-command handler mutates state, it pushes one of three patch types:

| Patch type  | Source command family | Triggered by                |
|-------------|-----------------------|-----------------------------|
| `word-patch`| `docx add/set/move`   | Single-shot Word handlers   |
| `excel-patch`| `xlsx add/set/remove` | Single-shot Excel handlers  |
| `replace`   | `pptx replace`        | Single-shot PowerPoint path |

Listeners receive only **deltas**, not full document snapshots, so re-rendering is fast.

Source: [src/officecli/CommandBuilder.Watch.cs:1-100](), [src/officecli/Core/Watch/WatchServer.cs:60-200]().

### Host binding

By default, `WatchServer` binds to `localhost` only, which is why issue #167 requests a `--host` (e.g., `0.0.0.0`) flag so that preview tabs on other machines in the same network can connect. Until that option lands, workarounds include SSH port-forwarding or running the CLI on the viewing host directly.

Source: [src/officecli/Core/Watch/WatchServer.cs:60-140]().

## Known Issues and Recent Fix

The two pain points most reported by users sit at the seam between batch execution and live preview:

- **#63 — pipe contention.** When an AI agent issues overlapping commands against the same resident, the main pipe can become unresponsive. `ResidentClient` returns the "main pipe busy" message and the agent must back off or close the resident.
- **#169 — missing watch notifications after batch.** Because `BatchExecutor` did not invoke `NotifyWatch*`, the preview tab would go stale whenever edits were applied via `batch` or `create --force`. Users had to manually reload the preview.

Release **v1.0.129** (PR #170 by @sixtycat2000-ctrl) closes the second gap: `fix(pptx/xlsx/docx): notify watch SSE after resident batch edits`. After the fix, both batched and single-command edits emit the same `word-patch` / `excel-patch` / `replace` events, so `officecli watch` stays live across all editing paths.

Source: [src/officecli/Core/BatchExecutor.cs:120-200](), [src/officecli/Core/Watch/WatchServer.cs:140-220](), [CHANGELOG / v1.0.129 release notes]().

## Practical Guidance

- Prefer `batch` when issuing more than two edits to the same file — it amortizes the pipe cost and keeps the preview consistent.
- If you see "main pipe busy or unresponsive", run `officecli close <file>` and retry; do not spawn a second resident against a locked workbook.
- For remote previews today, forward the watch port (default localhost only) or wait for the `--host` flag tracked in #167.
- When authoring templates that should reach the preview immediately, follow the single-shot path; batched template application now also triggers notifications as of v1.0.129.

Source: [src/officecli/Program.cs:1-120](), [src/officecli/ResidentClient.cs:1-150](), [src/officecli/CommandBuilder.Watch.cs:1-100]().

---

<a id='page-4'></a>

## AI Integration, Templates & Advanced Features

### Related Pages

Related topics: [Overview & Architecture](#page-1), [Document Operations & Command Reference](#page-2), [Resident Mode, Batch Execution & Live Preview](#page-3)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/officecli/McpServer.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/McpServer.cs)
- [src/officecli/McpInstaller.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/McpInstaller.cs)
- [src/officecli/Core/SkillInstaller.cs](https://github.com/iOfficeAI/OfficeCLI/Core/SkillInstaller.cs)
- [src/officecli/Core/TemplateMerger.cs](https://github.com/iOfficeAI/OfficeCLI/Core/TemplateMerger.cs)
- [src/officecli/Core/Formula/FormulaEvaluator.cs](https://github.com/iOfficeAI/OfficeCLI/Core/Formula/FormulaEvaluator.cs)
- [src/officecli/Core/PivotTableHelper.cs](https://github.com/iOfficeAI/OfficeCLI/Core/PivotTableHelper.cs)
</details>

# AI Integration, Templates & Advanced Features

OfficeCLI extends a deterministic Office document CLI with three layered capabilities aimed at AI-driven workflows: an MCP (Model Context Protocol) bridge that lets LLM agents call the tool, a template subsystem that reuses existing document formatting, and a set of advanced helpers for formulas and pivot tables. Together these turn OfficeCLI from a manual CLI into an AI-friendly document backend.

## AI Integration via MCP

OfficeCLI exposes its operations to AI agents (e.g., Codex, Hermes) through an MCP server. `McpServer.cs` hosts the protocol handlers and forwards tool calls into the same command pipeline used by the CLI, while `McpInstaller.cs` registers the binary with common MCP-aware clients so that an agent can discover and launch it automatically. `Core/SkillInstaller.cs` writes a skill manifest describing the CLI's command surface, which improves the model's ability to pick the right verb and arguments.

A practical pattern is: agent invokes `officecli` MCP skill → `McpServer.cs` resolves the file's running resident → routes the command → returns JSON. This is the path referenced in community issue #63, where users report frequent "main pipe busy or unresponsive" errors when an AI invokes the tool while a resident is already holding the target file. The fix recommended in that thread is to call `officecli close` first or to retry, indicating that the MCP layer does not transparently queue overlapping requests. Source: [src/officecli/McpServer.cs]()

The skill installation flow is intentionally idempotent: `Core/SkillInstaller.cs` reuses existing entries rather than overwriting them, so repeated `install` invocations from an agent do not corrupt the host's MCP configuration. Source: [src/officecli/Core/SkillInstaller.cs]()

## Template Reuse and Formatting

For users who already maintain professionally formatted `.docx` reports — with covers, tables of contents, headers, footers, and page numbers — `Core/TemplateMerger.cs` provides the mechanism to apply that style to a newly generated document. The merger walks a source template and a target document and copies style-bearing parts (paragraph styles, numbering definitions, theme references) onto the target while preserving the target's body content. Source: [src/officecli/Core/TemplateMerger.cs]()

This directly addresses community issue #168, where users asked how to reuse an existing report's "封面、目录、章节类型、页眉页脚、字体" on a freshly AI-generated `文档A.docx`. The recommended workflow with the current codebase is:

1. Author or obtain a baseline `.dotx`-style template with the desired master pages and styles.
2. Run `officecli merge-template <target.docx> --from <template.docx>` (exact subcommand name follows the convention of `Core/TemplateMerger.cs`).
3. The merger copies style references so Word renders new headings and paragraphs using the template's font and spacing.

The same module is also useful for cases where the model emits bare content (issue #168, second question) — applying a template is faster and more reliable than prompting the model to author formatted XML by hand. Source: [src/officecli/Core/TemplateMerger.cs]()

## Advanced Document Features

### Formulas

`Core/Formula/FormulaEvaluator.cs` evaluates spreadsheet formulas when modifying `.xlsx` files so that AI-driven edits produce computed cells rather than literal text. This is the path the CLI uses when an agent asks for `=SUM(...)` or other expressions to be inserted, and it removes the need for the caller to know cell ranges in advance. Source: [src/officecli/Core/Formula/FormulaEvaluator.cs]()

The evaluator is also invoked for `.docx` content where structured fields (e.g., table totals) are present, which connects to issue #166: positioning equations and their numbers across single- and double-column sections requires explicit style handling on the paragraphs that host them, not just the formula text itself.

### Pivot Tables

`Core/PivotTableHelper.cs` constructs and refreshes pivot tables for `.xlsx` outputs. It encapsulates the Open XML pivot definitions so an agent can request a summary view by field name and value aggregation without having to author the underlying `pivotTableDefinition.xml`. Source: [src/officecli/Core/PivotTableHelper.cs]()

### Watch Mode and Live Preview

`officecli watch <file>` runs an SSE-based preview that pushes content patches (`excel-patch`, `word-patch`, `replace`) to subscribers after single-command edits. Issue #169 notes that `batch` and `create --force` previously bypassed this notification path; the v1.0.129 release (PR #170) adds post-batch `NotifyWatch*` calls so live preview now updates after resident batch edits as well. Source: [release v1.0.129]()

## Integration Workflow

```mermaid
flowchart LR
  Agent[LLM Agent / Codex] -->|MCP tool call| McpServer
  McpServer --> SkillInstaller[SkillInstaller manifest]
  McpServer --> Resident[File Resident]
  Resident -->|single edit| Watch[watch SSE patches]
  Resident -->|batch| Watch
  Resident --> Formula[FormulaEvaluator]
  Resident --> Pivot[PivotTableHelper]
  Template[TemplateMerger] --> Resident
```

## Community-Driven Caveats

- **File locking (issue #63):** Always check that no resident is holding the target before issuing concurrent MCP calls, or close it first.
- **Template reuse (issue #168):** Prefer `TemplateMerger` over prompting the model to author formatted XML.
- **Live preview (issue #169, fixed in v1.0.129):** Batch edits now notify watchers; upgrade to receive SSE updates after `batch` or `create --force`.
- **Equation layout (issue #166):** Column-aware equation placement requires manual paragraph style choices, not just formula content.

Together, these modules let OfficeCLI act as a stable, AI-callable document backend while keeping template fidelity, computed values, and live preview behavior consistent with manual CLI usage.

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Pitfall Log

Project: iofficeai/officecli

Summary: Found 15 structured pitfall item(s), including 2 high/blocking item(s). Top priority: Installation risk - Installation risk requires verification.

## 1. Installation risk - Installation risk requires verification

- Severity: high
- Evidence strength: source_linked
- Finding: Project evidence flags a installation risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: community_evidence:github | https://github.com/iOfficeAI/OfficeCLI/issues/150

## 2. Maintenance risk - Maintenance risk requires verification

- Severity: high
- Evidence strength: source_linked
- Finding: Project evidence flags a maintenance risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: community_evidence:github | https://github.com/iOfficeAI/OfficeCLI/issues/162

## 3. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a installation risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: community_evidence:github | https://github.com/iOfficeAI/OfficeCLI/issues/164

## 4. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a installation risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: community_evidence:github | https://github.com/iOfficeAI/OfficeCLI/issues/139

## 5. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a installation risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: community_evidence:github | https://github.com/iOfficeAI/OfficeCLI/issues/169

## 6. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a installation risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: community_evidence:github | https://github.com/iOfficeAI/OfficeCLI/issues/161

## 7. Configuration risk - Configuration risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a configuration risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: capability.host_targets | https://news.ycombinator.com/item?id=48807225

## 8. Configuration risk - Configuration risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a configuration risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: community_evidence:github | https://github.com/iOfficeAI/OfficeCLI/issues/163

## 9. Capability evidence risk - Capability evidence risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: capability.assumptions | https://news.ycombinator.com/item?id=48807225

## 10. Maintenance risk - Maintenance risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a maintenance risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: community_evidence:github | https://github.com/iOfficeAI/OfficeCLI/issues/135

## 11. Maintenance risk - Maintenance risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a maintenance risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://news.ycombinator.com/item?id=48807225

## 12. Security or permission risk - Security or permission risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: downstream_validation.risk_items | https://news.ycombinator.com/item?id=48807225

## 13. Security or permission risk - Security or permission risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: risks.scoring_risks | https://news.ycombinator.com/item?id=48807225

## 14. Maintenance risk - Maintenance risk requires verification

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://news.ycombinator.com/item?id=48807225

## 15. Maintenance risk - Maintenance risk requires verification

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://news.ycombinator.com/item?id=48807225

<!-- canonical_name: iofficeai/officecli; human_manual_source: deepwiki_human_wiki -->
