문서 로드와 콘텐츠 작업

AI Agent의 최소 콘텐츠 작업 흐름을 익히고 Collaboration Runtime, Inspection, API Reference, Content Execution을 구성합니다.

AI Agent의 최소 콘텐츠 작업 흐름

모든 콘텐츠 명령을 위해, 비즈니스 CLI는 대상 Unit1를로드하고 최신 콘텐츠를 동기화합니다. 에이전트의 관점에서 전형적인 내용 작동은 다음과 같이 진행합니다.

100%

api find / api show 노드는 모드를 읽고 최종 검토는 유일한 조건 단계입니다. 에이전트는 다음 경계에 따라 기능을 선택합니다.

AI Agent 목표우선 기능
문서 구조와 주요 내용 분포 이해inspect 개요
Range, Paragraph, Slide 등 표준 콘텐츠 읽기inspect 선택자
조건부 서식, 차트 설정 등 미지원 부분 읽기execute --mode read
익숙하지 않은 Facade API 검색·확인api find / api show
문서 수정·커밋execute --mode write
결과 검토inspect / execute --mode read

예제: Sheet 범위 업데이트

book-1에서 [["East", 128000]]에 Data!A2:B2를 새롭게 하는 일을 고려하십시오. 사업 CLI를 조립하는 것은 이 페이지에 나중에 묘사된 것과 같이 조립되었습니다, 대리인은 다음과 같이 진행합니다.

  1. Workbook과 Target Range를 이해하는 검사를 사용하십시오:
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 참조를 시연하려면 에이전트가 setValues를 알지 못하며 서명을 확인해야 합니다.
Bash
my-cli api find setValues --unit sheetmy-cli api show FWorkbook.getSheetByName FWorksheet.getRange FRange.setValues
  1. 쓰기 모드에서 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. 작업의 위험에 근거를 둔 검토 여부를 결정합니다. 검사 범위 값을 다루고, 범위를 다시 읽으십시오:
Bash
my-cli inspect range A2:B2 --worksheet name:Data --unit "$UNIT_ID" --json

이 작업은 읽기 모드가 필요하지 않습니다. 검사가 쓰기 전에 범위를 읽을 수 있기 때문에. 읽기 모드는 검사가 조건 지정 및 차트 구성 예와 같은 커버하지 않는 내용에 대해 예약됩니다.

업무 CLI에 기능 구성

이 섹션은 @univer-cli/univer-collaboration-runtime에서 시작하여 검사, API 참조 및 Content Execution를 추가합니다. 스니펫은 각 기능의 핵심 인터페이스를 제공합니다. 서버 구성, 정체성, 오류 발표 및 명령 인수는 응용 프로그램의 책임에 남아 있습니다.

각 단계는 동일한 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에서 운영하는 대리인을 위한 2개의 목적을 봉사합니다: 그것은 단위를 실행하고, 협력 클라이언트로 행동합니다. 런타임은 그것의 전체 수명주기를 위한 단일 단위에 경계를 둡니다.

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);

애플리케이션은 @univer-cli/headless-univer 또는 사용자 정의 구성에서 표준 구현 중 하나 인 headlessUniverFactory를 주사합니다. 이 페이지는 초기화 세부 사항을 미칩니다. 이 응용 프로그램은 또한 어댑터에 필요한 프로토콜 주소로 서버 구성, 정체성 및 단위 대상을 매핑합니다. 스냅 샷을 실행하면 개정을 유지하고 날짜까지 설정 설정을 변경하고 Facade 실행 환경을 제공합니다.

핵심 런타임 APIs는:

API용도
pull()원격 변경 집합을 가져와 OT로 조정하고 Unit 갱신
execute({ mode, code })Facade 실행. read는 읽기, write는 mutation 생성
commit()현재 대기 mutation 수동 제출
exportUnitData()Runtime이 보유한 전체 UnitData 내보내기
getState()리비전·연결·대기·충돌 상태 읽기
close()백엔드 핸들과 headless Univer 해제

2. Inspection으로 내용 이해

일반적인 읽기 작업은 Facade 코드를 작성하는 에이전트가 필요하지 않습니다. @univer-cli/content-inspection는 구조화, 읽기 전용 결과를 반환합니다.

UnitInspection 개요어떤 에이전트가 빨리 배우는
Sheet워크북 개요워크시트 식별 정보, 사용 범위, Table·Rule·Drawing 요약
Doc문서 개요문서 모드, 문단 인덱스, 텍스트 미리보기, 기능 개수
Slide프레젠테이션 개요슬라이드 인덱스, 텍스트 미리보기, 요소 개수, 크기, Layout 개수

Collaboration Runtime는 이미 검사가 예상되는 읽기 전용 실행 인터페이스를 만족시킵니다.

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()는 읽기 전용 Facade 프로그램에 unitId를 컴파일하고 univerAPI.getWorkbook(unitId)을 통해 대상 Workbook을 찾습니다. unitType은 쿼리가 단위 유형에 일치한다는 것을 확인합니다.

단위의 구조와 주요 내용을 설치하기 위해 개요 쿼리를 시작 다음 검사 커버 표준 내용에 대한 워크 시트, 범위, 단락 및 슬라이드 선택기를 사용합니다. 필요한 구성 또는 세부 사항이 검사 결과에서 누락되면 완전한 조건 지정 규칙 또는 차트 구성과 같은 하나의 작은 대상 쿼리를 발급 execute({ mode: "read" }).

기본 Commander 경험의 경우 inspect 사전 설정 추가. 응용 프로그램은 런타임 임대를 제공해야 합니다:

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는 preset의 공중 의존성 분야이고, 그것의 반환 가치는 ContentInspectionLease에 따르야 합니다. 이 예에는 수영장이 없습니다, 그래서 invalidate()와 release()는 둘 다 독점적인 런타임을 즉시 닫습니다. 미리 설치 손잡이 선택적인 파싱, 원본 또는 JSON 산출 및 임대 방출을 취급합니다. 표적 매핑, 런타임 초기화, 입증 및 먼 선적은 신청으로 남아 있습니다. 주문 대리인 의정서를 위해, 직접 전화 inspectContent().

3. Facade API 검색과 이해

에이전트가 작업을 알고 있지만 해당 Facade API가 아닌 경우 @univer-cli/api-reference를 사용하십시오. 현재 SDK로 배송되며 단위를로드하지 않으며 온라인 문서 서비스에 문의하십시오.

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()는 후보 기호로 작업 중심 용어를 전환합니다.
  • show()는 클래스·멤버·타입·열거형의 정확한 정보를 반환합니다.
  • @univer-cli/api-reference-command는 선택적인 api find 및 api show 미리 설치를 추가합니다.

Commander와 같은 참조를 등록하려면:

TypeScript
import { createApiCommand } from "@univer-cli/api-reference-command";program.addCommand(createApiCommand({ reference }));

API 참고는 실행하기 전에 온다 : 에이전트는 현재 내용을 검사, 찾기 또는 필요한 API를 보여줍니다, 다음 Facade 코드를 작성하고 실행합니다.

4. Facade 읽기·쓰기 실행

임의 읽기 및 수정을 위해 Collaboration Runtime의 execute()를 사용하십시오. @univer-cli/content-execution는 특정 단위에 Facade JavaScript을 묶고 그 단위 유형을 위한 안정되어 있는 바인딩을 주사합니다:

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"는 arbitrary 읽기 전용 쿼리 및 블록 mutations를 허용합니다.
  • mode: "write"는 Facade mutations를 캡처하고 Runtime의 로컬 종료 상태에 추가합니다.
  • 성공적인 실행은 코드 랜을 의미한다. 그것은 변경자가 서버에 도달하지 않습니다.

content-execution는 실행 프로그램을 제작합니다. Runtime을 취득하지 않거나, changesets를 제출하거나, public 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);

이 명령 기본값은 모드를 작성합니다. 모드를 읽으면 Facade 코드의 반환 값과 다른 것들이 없습니다. mutations 및 no commit(). 쓰기 모드는 mutation 카운트, 개정, 그리고 순서가 확인된 후에 반환값을 인쇄합니다, 그래서 대리인은 제출의 정확한 결과를 결정할 수 있습니다. Commander 인수 및 명령 수명주기를 소유합니다. 이 응용 프로그램은 런타임 취득을 소유하고, retries, 오류 발표 및 승인 정책. 이 최소 파편은 시트로 고정됩니다. 애플리케이션이 Doc, Slide, Base 또는 Board를 지원할 때 CLI Unit 유형에서 명시된 매핑을 추가합니다. UniverInstanceType.

Inspection이 다루지 않는 내용에만 읽기 모드 사용

검사 보고서 얼마나 많은 조건 지정 규칙은 작업 시트 포함, 하지만 각 규칙의 전체 구성이 아닙니다. 에이전트가 세부 사항을 필요로 할 때, API를 확인하고 읽기 모드에서 최소 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();'

같은 검사는 많은 차트가 포함되어 있는지보고합니다. 작업이 전체 차트 구성을 필요로 할 때, 집중 쿼리는 sheet.getCharts().map((chart) => chart.getInfo())를 반환 할 수 있습니다. 읽기 모드는 mutations를 결코 생산하지 않습니다; 그것의 역할은 검사를 대체하지 않는 간격을 채우기위한 것입니다.

정리

단일 Commander 프로그램은 이제 Collaboration Runtime, 검사, API 참조 및 Content Execution를 결합합니다. 런타임로드 및 동기화 장치는 Facade 코드를 실행하고 요청에 따라 커밋합니다. 검사는 구조화 된 읽기를 제공합니다. API 참조는 에이전트가 올바른 Facade API을 찾습니다. Commander는 하나의 CLI 입력 지점을 통해 모든 것을 노출시킵니다.

일반적인 작업은 inspect로 시작하여 구조, 주요 콘텐츠 및 검사가 이미 커버하는 표준 세부 사항을 설정합니다. API가 부패 할 때 api find / api show를 사용하십시오. 검사가 커버되지 않는 구성이나 세부 사항에 대해서만 읽는 모드를 사용하여 수정 모드를 작성하십시오. 검토는 동일한 검사 경계를 따릅니다.

다음 단계

다음 Office 파일 가져 오기 및 내보내기를 추가합니다. 그것은 같은 콘텐츠 운영 흐름에 대한 UnitData로 사무실 파일을 변환하고 사무실 파일로 최신 UnitData을 수출합니다.

Footnotes

  1. Unit은 통합 문서나 텍스트 문서 같은 문서 인스턴스입니다. 워크시트는 통합 문서의 일부이며 별도의 Unit이 아닙니다. ↩

  2. 여기서 Runtime은 문서를 로드한 Univer 인스턴스와 Unit 조작에 필요한 리소스를 뜻합니다. Node.js 실행 파일이나 저장된 문서 스냅샷을 뜻하지 않습니다. ↩

이 가이드는 어떠셨나요?

© 2026 DreamNum Co., Ltd.