Document loading and content operations
Learn the minimum agent content-operation flow and assemble Collaboration Runtime, Inspection, API Reference, and Content Execution.
Minimum content-operation flow for an agent
For every content command, the business CLI loads the target Unit1 and synchronizes it with the latest content. From the agent's perspective, a typical content operation proceeds as follows:
The api find / api show node, read mode, and the final review are the only conditional steps. The agent selects capabilities according to the following boundary:
| Agent goal | Preferred capability |
|---|---|
| Understand document structure and main-content distribution | inspect overview |
| Read standard content such as a Range, Paragraph, or Slide | inspect selector |
| Read conditional formatting, Chart configuration, or other gaps | execute --mode read |
| Find or confirm an unfamiliar Facade API | api find / api show |
| Modify and commit the document | execute --mode write |
| Review the result | inspect / execute --mode read |
Example: update a Sheet Range
Consider a task that updates Data!A2:B2 in book-1 to [["East", 128000]]. Assuming the business CLI has been assembled as described later on this page, the agent proceeds as follows.
- Use Inspection to understand the Workbook and the target Range:
UNIT_ID="book-1"my-cli inspect workbook --unit "$UNIT_ID" --jsonmy-cli inspect range A1:B2 --worksheet name:Data --unit "$UNIT_ID" --json- To demonstrate API Reference, assume the agent does not know
setValuesand needs to confirm its signature:
my-cli api find setValues --unit sheetmy-cli api show FWorkbook.getSheetByName FWorksheet.getRange FRange.setValues- Run the Facade code in write mode. The application's
executecommand handles the commit:
my-cli execute --unit "$UNIT_ID" --mode write \ --code 'const sheet = workbook.getSheetByName("Data");if (!sheet) throw new Error("Worksheet Data not found");sheet.getRange("A2:B2").setValues([["East", 128000]]);'- Decide whether to review based on the risk of the task. Inspection covers Range values, so read the Range again:
my-cli inspect range A2:B2 --worksheet name:Data --unit "$UNIT_ID" --jsonThis task does not require read mode, because Inspection can read the Range both before and after the write. Read mode is reserved for content that Inspection does not cover, such as the conditional-formatting and Chart configuration examples below.
Assemble these capabilities in a business CLI
This section starts from @univer-cli/univer-collaboration-runtime and adds Inspection, API Reference, and Content Execution. The snippets present the core interface of each capability. Server configuration, identity, error presentation, and command arguments remain the responsibility of the application.
Each step is registered on the same Commander root program:
import { Command } from "commander";const program = new Command("my-cli");// Register the inspect, execute, and api commands introduced below here.// Parse CLI arguments only after every command has been registered.await program.parseAsync();1. Load a collaborative Unit
Collaboration Runtime2 serves two purposes for an agent running in Node.js: it executes the Unit, and it acts as the collaboration client. A Runtime stays bound to a single Unit for its entire lifecycle.
import { createCollaborationServerAdapter, createUniverCollaborationRuntimeFactory,} from "@univer-cli/univer-collaboration-runtime";import { UniverInstanceType } from "@univerjs/core";const factory = createUniverCollaborationRuntimeFactory({ backend: createCollaborationServerAdapter({ snapshotServerUrl, collabSubmitChangesetUrl, collabWebSocketUrl, wsSessionTicketUrl, }), createUniver: headlessUniverFactory,});const unitId = "book-1";const runtime = await factory.load(unitId, UniverInstanceType.UNIVER_SHEET);The application injects headlessUniverFactory, which is either the standard implementation from @univer-cli/headless-univer or a custom composition; this page omits the initialization details. The application also maps its Server configuration, identity, and Unit target onto the protocol addresses required by the adapter. Runtime loads the Snapshot, keeps revisions and changesets up to date, and provides the Facade execution environment.
The core Runtime APIs are:
| API | Purpose |
|---|---|
pull() | Fetch remote changesets, reconcile them through OT, and update the Unit |
execute({ mode, code }) | Run Facade code; read reads content and write produces mutations |
commit() | Manually submit the current pending mutations |
exportUnitData() | Export the complete UnitData currently held by the Runtime |
getState() | Read revision, connection, pending state, and conflict state |
close() | Release the backend handle and headless Univer |
2. Understand content through Inspection
Common read tasks do not require the agent to write Facade code. @univer-cli/content-inspection returns structured, read-only results:
| Unit | Inspection overview | What the agent learns quickly |
|---|---|---|
| Sheet | Workbook overview | Worksheet identities, used ranges, and Table, Rule, and Drawing summaries |
| Doc | Document overview | Document mode, paragraph index, text previews, and feature counts |
| Slide | Presentation overview | Slide index, text previews, element counts, size, and Layout count |
Collaboration Runtime already satisfies the read-only execution interface that Inspection expects:
import { inspectContent } from "@univer-cli/content-inspection";const workbook = await inspectContent( { unitId: runtime.unitId, unitType: "sheet", execute: async (input) => { const result = await runtime.execute(input); return { value: result.value }; }, }, { kind: "workbook" },);inspectContent() compiles unitId into a read-only Facade program and locates the target Workbook through univerAPI.getWorkbook(unitId). unitType verifies that the query matches the Unit type.
Start with an overview query to establish the Unit's structure and main content, then use the worksheet, range, paragraph, and slide selectors for standard content that Inspection covers. When the required configuration or detail is missing from the Inspection results, such as a complete conditional-formatting rule or a Chart configuration, issue one small targeted query through execute({ mode: "read" }).
For the default Commander experience, add the inspect preset. The application only has to provide a Runtime lease:
import type { ContentInspectionLease } from "@univer-cli/content-inspection-command";import { createContentInspectionCommand } from "@univer-cli/content-inspection-command";program.addCommand( createContentInspectionCommand({ async acquireRuntime({ unitId }) { const runtime = await factory.load(unitId, UniverInstanceType.UNIVER_SHEET); await runtime.pull(); const lease: ContentInspectionLease = { unitId, unitType: "sheet", execute: async (input) => { const result = await runtime.execute(input); return { value: result.value }; }, invalidate: () => runtime.close(), release: () => runtime.close(), }; return lease; }, }),);acquireRuntime is the preset's public dependency field, and its return value must conform to ContentInspectionLease. This example has no pool, so invalidate() and release() both close the exclusive Runtime immediately. The preset handles selector parsing, text or JSON output, and lease release. Target mapping, Runtime initialization, authentication, and remote loading remain with the application. For a custom agent protocol, call inspectContent() directly.
3. Find and understand Facade APIs
When the agent knows the task but not the corresponding Facade API, use @univer-cli/api-reference. It ships with the current SDK, loads no Unit, and does not contact an online documentation service.
import { createStandardApiReference } from "@univer-cli/api-reference";const reference = createStandardApiReference();const matches = reference.find({ terms: ["setValues", "conditional formatting"], unit: "sheet", limit: 20,});const details = reference.show(["FRange", "FRange.setValues", "ICellData.v"]);find()turns task-oriented terms into candidate symbols.show()returns precise details for a class, member, type, or enum.@univer-cli/api-reference-commandadds the optionalapi findandapi showpresets.
To register the same reference with Commander:
import { createApiCommand } from "@univer-cli/api-reference-command";program.addCommand(createApiCommand({ reference }));API Reference comes before execution: the agent inspects the current content, finds or shows the required API, then writes and runs the Facade code.
4. Execute Facade reads and writes
For arbitrary reads and modifications, use Collaboration Runtime's execute(). @univer-cli/content-execution binds Facade JavaScript to a specific Unit and injects stable bindings for that Unit type:
import { prepareContentExecutionProgram } from "@univer-cli/content-execution";const executionProgram = prepareContentExecutionProgram({ unitId, unitType: "sheet", code: 'workbook.getActiveSheet().getRange("A1").setValue("done");',});const execution = await runtime.execute({ mode: "write", code: executionProgram,});mode: "read"allows arbitrary read-only queries and blocks mutations.mode: "write"captures Facade mutations and adds them to the Runtime's local pending state.- A successful run means the code ran. It does not mean a changeset reached the Server.
content-execution only produces an execution program. It never acquires a Runtime, submits changesets, or ships a public execute command preset package. The business CLI therefore wraps it in an application Commander command:
const executeCommand = new Command("execute") .requiredOption("--unit <id>") .requiredOption("--code <javascript>") .option("--mode <read|write>", "execute without or with mutations", "write") .action(async ({ unit, code, mode }) => { if (mode !== "read" && mode !== "write") { throw new Error("--mode must be read or write"); } const runtime = await factory.load(unit, UniverInstanceType.UNIVER_SHEET); try { await runtime.pull(); const executionProgram = prepareContentExecutionProgram({ unitId: unit, unitType: "sheet", code, }); const execution = await runtime.execute({ mode, code: executionProgram }); if (mode === "read") { process.stdout.write(`${JSON.stringify(execution.value, null, 2)}\n`); return; } let committed = await runtime.commit(); if (committed.status === "pull-required") { await runtime.pull(); committed = await runtime.commit(); } if (committed.status !== "confirmed") { throw new Error(`Commit failed: ${committed.status}`); } process.stdout.write( `${JSON.stringify( { commit: committed.status, mutations: execution.mutations.length, revision: committed.state.baseRevision, value: execution.value, }, null, 2, )}\n`, ); } finally { await runtime.close(); } });program.addCommand(executeCommand);This command defaults to write mode. Read mode prints the return value of the Facade code and nothing else: no mutations and no commit(). Write mode prints the mutation count, revision, and return value only after the commit is confirmed, so the agent can determine the exact outcome of the submission. Commander owns the arguments and the command lifecycle. The application owns Runtime acquisition, commit retries, error presentation, and authorization policy. This minimal fragment is fixed to Sheet; when the application supports Doc, Slide, Base, or Board, add an explicit mapping from CLI Unit types to UniverInstanceType.
Use read mode only for content not covered by Inspection
Inspection reports how many conditional-formatting rules a Worksheet contains, but not the full configuration of each rule. When the agent needs that detail, it confirms the API and runs a minimal Facade snippet in read mode:
my-cli api find getConditionalFormattingRules --unit sheetmy-cli api show FWorksheet.getConditionalFormattingRulesmy-cli execute --unit "$UNIT_ID" --mode read \ --code 'const sheet = workbook.getSheetByName("Data");if (!sheet) throw new Error("Worksheet Data not found");return sheet.getConditionalFormattingRules();'Inspection likewise reports how many Charts a Worksheet contains. When the task requires a full Chart configuration, a focused query can return sheet.getCharts().map((chart) => chart.getInfo()). Read mode never produces mutations; its role is to fill the gaps that Inspection leaves, not to replace Inspection.
Summary
A single Commander program now combines Collaboration Runtime, Inspection, API Reference, and Content Execution. Runtime loads and synchronizes the Unit, executes Facade code, and commits on request. Inspection provides structured reads. API Reference helps the agent locate the right Facade API. Commander exposes all of it through one CLI entry point.
A typical operation starts with inspect to establish the structure, the main content, and the standard details that Inspection already covers. When an API is unclear, use api find / api show. Use read mode only for configuration or detail that Inspection does not cover, then edit and commit in write mode. Review follows the same Inspection boundary.
Next step
Next, add Office file import and export. It converts Office files into UnitData for the same content-operation flow, and exports the latest UnitData as an Office file.
Footnotes
How is this guide?