文档内容加载与读写
了解 Agent 的最小内容操作流程,并装配 Collaboration Runtime、Inspection、API Reference 与 Content Execution。
Agent 的最小内容操作流程
业务 CLI 在处理每条内容命令时,都会先加载目标 Unit1,再同步最新内容。从 Agent 的角度看,一次典型的内容操作流程如下:
图中的 api find / api show、read 模式和最后的审查都是条件步骤,Agent 按下面的边界选择能力:
| Agent 的目标 | 优先能力 |
|---|---|
| 了解文档结构和主体内容分布 | inspect overview |
| 读取 Range、Paragraph、Slide 等标准内容 | inspect selector |
| 读取 Inspection 未覆盖的条件格式、图表配置等细节 | execute --mode read |
| 查找或确认不熟悉的 Facade API | api find / api show |
| 修改并提交文档 | execute --mode write |
| 审查结果 | inspect / execute --mode read |
示例:更新一个 Sheet Range
例如,任务是“把 book-1 的 Data!A2:B2 更新为 [["华东", 128000]]”。假设业务 CLI 已按本文后面的说明完成装配,Agent 可按以下步骤执行。
- 先用 Inspection 了解 Workbook 和目标 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- 为演示 API Reference,这里假设 Agent 不熟悉
setValues,需要先确认其签名:
my-cli api find setValues --unit sheetmy-cli api show FWorkbook.getSheetByName FWorksheet.getRange FRange.setValues- 在 write 模式下执行 Facade 代码。提交由业务应用的
execute命令处理:
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([["华东", 128000]]);'- 根据任务风险决定是否审查。Range 的值已由 Inspection 覆盖,重新读取该 Range 即可:
my-cli inspect range A2:B2 --worksheet name:Data --unit "$UNIT_ID" --json该任务不需要 read 模式,因为 Inspection 在写入前后都能读取这个 Range。read 模式仅用于 Inspection 未覆盖的内容,例如下文的条件格式和图表配置示例。
在业务 CLI 中装配这些能力
本节从 @univer-cli/univer-collaboration-runtime 开始,依次加入 Inspection、API Reference 与 Content Execution。代码片段给出各能力的核心接口;Server 配置、身份、错误展示和命令参数由业务应用自行实现。
每一步都注册到同一个 Commander 根程序:
import { Command } from "commander";const program = new Command("my-cli");// 在这里注册后续章节介绍的 inspect、execute 和 api 命令。// 所有命令注册完成后,再解析 CLI 参数。await program.parseAsync();1. 加载一个协同 Unit
Collaboration Runtime2 在 Node.js 中承担两项职责:执行 Unit,以及充当协同客户端。一个 Runtime 在整个生命周期内只绑定一个 Unit。
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);headlessUniverFactory 由应用注入,可以是 @univer-cli/headless-univer 的标准实现,也可以是自定义的 composition;本文不展开初始化配置。应用还需要把 Server 配置、身份和 Unit target 映射为 adapter 所需的协议地址。Runtime 负责加载 Snapshot、维护 revision 和 changeset,并提供 Facade 执行环境。
Runtime 的核心 API 如下:
| API | 用途 |
|---|---|
pull() | 拉取远端 changeset,通过 OT 协调并更新当前 Unit |
execute({ mode, code }) | 执行 Facade 代码;read 用于读取,write 用于产生 mutation |
commit() | 手动提交当前 pending mutations |
exportUnitData() | 导出当前 Runtime 中完整的 UnitData |
getState() | 查看 revision、连接状态、pending state 和冲突状态 |
close() | 释放 backend handle 和 headless Univer |
2. 使用 Inspection 理解内容
常见的读取任务不需要 Agent 自己编写 Facade 代码。@univer-cli/content-inspection 返回稳定、结构化的只读结果:
| Unit | Inspection 概览 | Agent 能快速掌握什么 |
|---|---|---|
| Sheet | Workbook 概览 | Worksheet 身份、有效区域以及 Table、Rule、Drawing 摘要 |
| Doc | Document 概览 | 文档模式、段落索引、正文预览和 Feature 数量 |
| Slide | Presentation 概览 | 页面索引、文字预览、元素数量以及 Presentation 尺寸和 Layout 数 |
Collaboration Runtime 已满足 Inspection 所需的只读执行接口:
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() 用 unitId 生成只读 Facade 程序,并通过 univerAPI.getWorkbook(unitId) 定位目标 Workbook;unitType 用于校验查询与 Unit 类型是否一致。
建议先用 overview 查询了解 Unit 的结构和主体内容,再用 worksheet、range、paragraph 和 slide selector 读取 Inspection 已覆盖的标准内容。当所需的配置或细节不在 Inspection 结果中时,例如完整的条件格式规则或图表配置,再用 execute({ mode: "read" }) 执行一条最小的定向查询。
如需 Commander 的默认交互,可加入 inspect 预设。业务应用只需提供一个 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 是该预设对外公开的依赖字段,其返回值需符合 ContentInspectionLease。此示例未使用 pool,因此 invalidate() 和 release() 都会立即关闭这个独占的 Runtime。selector 解析、文本或 JSON 输出以及 lease 释放由预设负责;target 映射、Runtime 初始化、认证和远端加载仍由业务应用负责。如需接入自定义 Agent 协议,可直接调用 inspectContent()。
3. 查找和理解 Facade API
当 Agent 明确任务但不清楚应调用哪个 Facade API 时,使用 @univer-cli/api-reference。它随当前 SDK 发布,不加载 Unit,也不访问在线文档服务。
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()根据任务关键词找出候选 symbol;show()返回 class、member、type 或 enum 的精确详情;@univer-cli/api-reference-command提供可选的api find和api show预设。
如需将同一个 reference 接入 Commander:
import { createApiCommand } from "@univer-cli/api-reference-command";program.addCommand(createApiCommand({ reference }));API Reference 位于执行之前:Agent 先 Inspect 当前内容,再通过 Find/Show 确认所需 API,最后编写并执行 Facade 代码。
4. 执行 Facade 读写
需要自由读取或修改内容时,使用 Collaboration Runtime 的 execute()。@univer-cli/content-execution 先把 Facade JavaScript 绑定到指定的 Unit,再为对应的 Unit 类型注入稳定的 binding:
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"允许自由的只读查询,不允许产生 mutation;mode: "write"捕获 Facade 产生的 mutation,并加入 Runtime 本地的 pending state;- 执行成功只表示代码已执行完毕,不代表 changeset 已提交到 Server。
content-execution 只负责生成 execution program,不获取 Runtime、不提交 changeset,也不提供公开的 execute 预设命令包。因此业务 CLI 需要用 Commander 将其封装为应用级命令:
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);该命令默认使用 write 模式。read 模式只输出 Facade 代码的返回值,不产生 mutation,也不调用 commit()。write 模式仅在 commit 确认后输出 mutation 数量、revision 和返回值,Agent 因此能明确知道提交结果。参数和命令生命周期由 Commander 负责;Runtime 获取、提交重试、错误输出和权限策略由应用负责。为保持片段最小,这里固定使用 Sheet;如需支持 Doc、Slide、Base 或 Board,再补充 CLI Unit 类型到 UniverInstanceType 的显式映射。
只用 read 模式补充 Inspection 未覆盖的内容
Inspection 会告知 Agent 一个 Worksheet 上有多少条条件格式规则,但不会给出每条规则的完整配置。需要该配置时,Agent 先确认 API,再用 read 模式执行一段最小的 Facade 代码:
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 同样会告知 Agent 一个 Worksheet 中包含多少个 Chart。任务需要完整图表配置时,可定向返回 sheet.getCharts().map((chart) => chart.getInfo())。read 模式不产生 mutation,其作用是补充 Inspection 未覆盖的内容,而不是取代 Inspection。
总结
至此,同一个 Commander 程序已经把 Collaboration Runtime、Inspection、API Reference 和 Content Execution 组合在一起。Runtime 负责加载、同步、执行和手动提交;Inspection 提供结构化读取;API Reference 帮助 Agent 定位 Facade API;Commander 将它们统一到同一个 CLI 入口。
一次典型操作从 inspect 开始,先了解结构、主体内容和 Inspection 已覆盖的标准细节;API 不明确时使用 api find / api show。仅在 Inspection 未覆盖某项配置或细节时使用 read 模式,随后用 write 模式编辑并提交。审查阶段遵循同一条 Inspection 边界。
下一步
下一步是Office 文件导入导出:它把 Office 文件转换为 UnitData,接入同一条内容操作流程,也能把最新的 UnitData 导出为 Office 文件。
Footnotes
你觉得这篇文档如何?