文件載入與內容操作

瞭解 AI Agent 的最小內容操作流程,組合 Collaboration Runtime、Inspection、API Reference 與 Content Execution。

AI Agent 的最小內容操作流程

業務 CLI 在處理每條內容命令時,都會先載入目標 Unit1,再同步最新內容。從 Agent 的角度看,一次典型的內容操作流程如下:

100%

圖中的 api find / api show、read 模式和最後的審查都是條件步驟,Agent 按下面的邊界選擇能力:

AI Agent 目標優先使用的能力
瞭解文件結構與主要內容分布inspect 概覽
讀取 Range、Paragraph、Slide 等標準內容inspect 選擇器
讀取條件格式、圖表設定或其他未涵蓋內容execute --mode read
尋找或確認不熟悉的 Facade APIapi find / api show
修改並提交文件execute --mode write
複查結果inspect / execute --mode read

範例:更新 Sheet 範圍

例如,任務是“把 book-1 的 Data!A2:B2 更新為 [["华东", 128000]]”。假設業務 CLI 已按本文後面的說明完成裝配,Agent 可按以下步驟執行。

  1. 用 Inspection 瞭解工作簿與目標範圍:
Bash
UNIT_ID="book-1"my-cli inspect workbook --unit "$UNIT_ID" --jsonmy-cli inspect range A1:B2 --worksheet name:Data --unit "$UNIT_ID" --json
  1. 為演示 API Reference,這裡假設 Agent 不熟悉 setValues,需要先確認其簽名:
Bash
my-cli api find setValues --unit sheetmy-cli api show FWorkbook.getSheetByName FWorksheet.getRange FRange.setValues
  1. 在 write 模式下執行 Facade 程式碼。提交由業務應用的 execute 命令處理:
Bash
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]]);'
  1. 根據任務風險決定是否審查。Range 的值已由 Inspection 覆蓋,重新讀取該 Range 即可:
Bash
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 根程式:

TypeScript
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. 載入協同 Unit

Collaboration Runtime2 在 Node.js 中承擔兩項職責:執行 Unit,以及充當協同客戶端。一個 Runtime 在整個生命週期內只繫結一個 Unit。

TypeScript
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()取得遠端變更集,透過 OT 協調並更新 Unit
execute({ mode, code })執行 Facade 程式碼;read 讀取內容,write 產生 mutation
commit()手動提交目前待處理 mutation
exportUnitData()匯出 Runtime 目前持有的完整 UnitData
getState()檢視 revision、連線狀態、pending state 和衝突狀態
close()釋放後端 handle 與 headless Univer

2. 透過 Inspection 瞭解內容

常見的讀取任務不需要 Agent 自己編寫 Facade 程式碼。@univer-cli/content-inspection 返回穩定、結構化的只讀結果:

UnitInspection 概覽Agent 能快速掌握什麼
Sheet工作簿概覽工作表身分、已用範圍,以及 Table、Rule、Drawing 摘要
Doc文件概覽文件模式、段落索引、文字預覽與功能數量
Slide簡報概覽投影片索引、文字預覽、元素數量、尺寸與 Layout 數量

Collaboration Runtime 已滿足 Inspection 所需的只讀執行介面:

TypeScript
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:

TypeScript
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,也不訪問線上文件服務。

TypeScript
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() 傳回類別、成員、類型或列舉的精確細節。
  • @univer-cli/api-reference-command 提供可選的 api find 和 api show 預設。

如需將同一個 reference 接入 Commander:

TypeScript
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:

TypeScript
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 將其封裝為應用級命令:

TypeScript
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 的顯式對映。

只對 Inspection 未涵蓋的內容使用讀取模式

Inspection 會告知 Agent 一個 Worksheet 上有多少條條件格式規則,但不會給出每條規則的完整配置。需要該配置時,Agent 先確認 API,再用 read 模式執行一段最小的 Facade 程式碼:

Bash
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

  1. Unit 指一個文件實例,例如一個活頁簿或一篇文件。工作表是活頁簿的一部分,不是獨立的 Unit。 ↩

  2. 此處的 Runtime 指已載入文件的 Univer 實例及其操作 Unit 所需的執行資源,不是 Node.js 執行檔,也不是儲存至磁碟的文件快照。 ↩

你覺得這篇文檔如何?

© 2026 DreamNum Co., Ltd.