# Agents and automation

> Compose inspection, editing, and validation tools so existing agents can work with Office content.

- Human documentation: [https://docs.univer.ai/overview/features/shared/agents](https://docs.univer.ai/overview/features/shared/agents)

- Agent Markdown: [https://docs.univer.ai/overview/features/shared/agents.md](https://docs.univer.ai/overview/features/shared/agents.md)

- Requested language: `en-US`

- Content language: `en-US`

- Documentation version: `1.6.1`

- Source: [features/shared/agents.mdx](https://github.com/dream-num/documentation/blob/dev/content/docs/features/shared/agents.mdx)

---

AI SDK exposes Univer's content models, Facades, and collaboration as composable TypeScript capabilities. An existing Agent can read content, modify it, verify the result, and hand it over for review. The application chooses the model, the tool protocol, and the method of orchestration.

## Connect content capabilities to an Agent

The capability packages return structured results that the application can pass to its own tools, services, or CLI. The optional `-command` packages expose the same capabilities as native Commander commands. Both forms operate on the content model and command system shared with the Web editor.

| Capability | Responsibility |
| --- | --- |
| Inspection | Reads structure, ranges, paragraphs, and object details to narrow the task. |
| API Reference | Queries the bundled Facade declarations, overloads, types, and examples offline. |
| Content Execution | Binds `workbook`, `doc`, `presentation`, `base`, or `board` to a specific Unit and prepares the code for execution. |
| Collaboration Runtime | Loads content, captures mutations, reconciles remote changes, and commits changesets explicitly. |

## How a Runtime restores editable state

A Collaboration Runtime remains bound to a single Unit for its entire lifetime. During loading it opens the backend provided by the application, reads a UnitData or Snapshot checkpoint, and replays the changesets on top of that checkpoint. It then closes the continuous revision gap to the remote head and, when the formula module is installed, waits for the latest calculation results.

```mermaid
sequenceDiagram
participant A as Application tool
participant R as Runtime
participant U as Content engine
participant B as Collaboration backend
A->>R: load
R->>B: Load checkpoint and changes
R->>U: Restore Unit and revision
A->>R: pull: fetch remote changes
R->>B: fetchChangesets
B-->>R: changesets
R->>U: Reconcile with OT and apply
A->>R: execute: Facade changes
R->>U: Facade
U-->>R: Produce mutations
Note over R: Keep pending changes
A->>R: commit: submit changeset
R->>B: changeset
B-->>R: ACK: confirm identity and revision
```

`fetch()` retrieves changes and validates them. `pull()` reconciles remote changes with the local pending and awaiting state through OT, then applies the result. The Runtime exposes `baseRevision`, `knownHeadRevision`, `pendingMutationCount`, and `awaitingChangeset` so that the application can assess progress.

## Locate content before executing a Facade

Provide the model with an overview first, then query a stable ID or a precise selector instead of sending a complete Snapshot. Inspection covers Sheet ranges, Doc paragraphs, Slide pages, Relational Table schema overviews, and Canvases objects. A Relational Table overview includes the field configuration but not record values or View projections; read those through Facades when required.

`prepareContentExecutionProgram()` resolves the root Facade from the Unit ID, independently of the current browser selection, and it rejects a redeclaration of an injected binding. In read mode the Runtime blocks business actions that would persist before they run; in write mode it captures the mutations of the target Unit. Unit creation and disposal are separate lifecycle operations and lie outside this single-Unit execution entry.

When an API is unfamiliar, `find()` lists candidates and `show()` prints the exact declaration together with the related types. The reference is distributed with the SDK, so it requires neither a content engine nor the online documentation. See [content operations](https://docs.univer.ai/ai/content-operations.md) and the [package overview](https://docs.univer.ai/ai/packages.md).

## Execution and confirmed persistence

`execute({ mode: 'write' })` modifies the live Unit and accumulates pending mutations. **It does not mean that the server has saved the changes.** `commit()` creates a changeset with an attached identity; the ACK must match that identity, the payload, and the revision before the change counts as confirmed.

| Commit status | Application action |
| --- | --- |
| `confirmed` / `nothing-to-commit` | The changes are confirmed, or there was nothing to submit. |
| `pull-required` | The remote revision has advanced. Call `pull()` to reconcile, then call `commit()` again. |
| `retry` / `unknown` | Keep the awaiting state in the same Runtime and retry `commit()`. Do not rerun the editing program. |
| `conflict` | Stop further writes and let the application choose recovery or reload. |

When the outcome of a submission is uncertain, the Runtime retains `sid + reqId`, so the backend can confirm the same changeset idempotently instead of duplicating the edits. The backend must implement this idempotency contract. A program that throws can leave the mutations it has already made in place, so inspect the pending state and decide how to recover. `execute()` is not a transaction that rolls back automatically.

The example below accepts an already loaded Sheet Runtime and returns both the execution result and the commit result. The caller handles the statuses above and closes the Runtime when its ownership period ends.

```ts
import { prepareContentExecutionProgram } from '@univer-cli/content-execution'
import type { UniverCollaborationRuntime } from '@univer-cli/univer-collaboration-runtime'

async function updateSales(runtime: UniverCollaborationRuntime) {
  const pulled = await runtime.pull()
  if (pulled.status === 'conflict') return pulled

  const code = prepareContentExecutionProgram({
    unitId: runtime.unitId,
    unitType: 'sheet',
    code: `
      const sheet = workbook.getSheetByName('Data');
      if (!sheet) throw new Error('Worksheet Data not found');
      sheet.getRange('A2:B2').setValues([
        [{ v: 'East', t: 1 }, { v: 128000, t: 2 }]
      ]);
      return sheet.getRange('A2:B2').getRawValues();
    `,
  })
  const execution = await runtime.execute({ mode: 'write', code })
  const commit = await runtime.commit()
  return { execution, commit }
}
```

## Reuse Runtimes for frequent tasks

Frequent tasks can lease a Worker Runtime exclusively under a key owned by the application. Cold creation is single-flight per key, leases are queued in FIFO order, and different keys can use different Workers. `release()` returns the instance, TTL/LRU eviction reclaims idle resources, and `invalidate()` retires an instance that is no longer trustworthy.

A key should distinguish the backend, the Unit, and the Worktree. The pool does not verify whether two sets of initialization inputs are semantically compatible. A daemon can hold the pool across short CLI calls, but a reused Runtime still requires synchronization and commit confirmation. The application should balance startup cost against resident memory and Worker count; see [Runtime reuse and daemon](https://docs.univer.ai/ai/runtime-architecture.md).

## From automation to human review

The capabilities can be combined for reporting, data cleanup, template filling, or content generation. The flow locates the target, writes through Facades, waits for any calculation on which the result depends, and reads back values, text, and object properties. Add [visual inspection](https://docs.univer.ai/overview/features/shared/visual-inspection.md) when the task requires it.

For approval workflows, the Agent works in a [Worktree](https://docs.univer.ai/overview/features/shared/worktree.md). It edits and verifies in rounds, and a person then reviews the Ready content and decides whether to merge. Track execution and commit results per Unit, because several Runtimes together do not form a cross-document atomic transaction.

The application owns identity, authorization, model integration, and the task lifecycle. Read and write restrictions enforce the boundary around business operations, while process isolation and file or network permissions for untrusted JavaScript remain the responsibility of the application. See [getting started](https://docs.univer.ai/overview/get-started.md) and the [Univer CLI example](https://docs.univer.ai/overview/examples/cli.md).

## Generate and edit content with Skills

To let an existing Agent work directly on Office content, start from the application that matches the location of the files:

- [CLI Skills](https://docs.univer.ai/overview/examples/cli.md#skills): create, edit, and check local Office files, then open the Viewer for review.
- [Workspace Skills](https://docs.univer.ai/overview/examples/workspace.md#skills): work on files in a connected Space, generate Office content and Web Apps, and hand changes off for collaboration and review.

[Back to features](https://docs.univer.ai/overview/features.md)
