> ## Documentation Index
> Fetch the complete documentation index at: https://trytilde.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Views and actions

> Group the objects that change together into transactional views, and expose typed reads, actions, and realtime views that agents call as tools and spaces render.

Handlers are the ontology's API. Every handler has a name, a zod input and output, and declares what it reads and edits. Tilde turns each read and action into an agent tool, and a typed RPC for spaces and apps.

| You want to | Write |
| - | - |
| Show one thing, such as a customer, on fresh data | A [read in a view](#reads) (`txRead`) |
| List, search, or aggregate across all data | A [read without a view](#reads) (`read`) |
| Change one thing, and optionally call a third party | An [action](#actions) (`txWrite`) |
| Push updates to a live page | A [realtime view](#realtime-views) |

## Transactional views

A transactional view groups the objects that change together under one key. `Customer` with key `acme` holds that customer, its invoices, tickets, and notes. Reads and actions on a view instance see a consistent, up-to-date state, and an action's edits commit together.

```ts ontologies/crm/customer.ts theme={"system"}
import { transactionalView } from "@trytilde/ontology";

export const CustomerView = transactionalView("Customer", {
  key: "customer_id",
  tables: { customers: crmCustomers, invoices: crmInvoices },
  dependsOn: { objects: [Customer, Invoice, CustomerNote], links: [CustomerInvoices] },
});
```

Each table is a model with `materialized: "cell"` and a column named after the view key. The root table is keyed by it. An object lives in at most one view. Ontology-owned objects, like `CustomerNote`, belong to the view that lists them in `dependsOn`.

## Reads

A read in a view gets the view instance as `view`, keyed by `view.key`.

```ts theme={"system"}
import { prop, read } from "@trytilde/ontology";
import { z } from "zod";

export const customerOverview = read("customerOverview", {
  description: "The customer with open invoices and notes.",
  view: CustomerView,
  kind: "txRead",
  input: z.object({}),
  output: z.object({
    name: z.string(),
    tier: z.string(),
    internalNotes: prop(Customer.internalNotes),
    openInvoices: z.array(z.object({ invoiceId: z.string(), amount: z.number() })),
  }),
  reads: [Customer, Invoice],
  handler: ({ view }) => {
    const c = view.get(Customer, view.key)!;
    return {
      name: c.name,
      tier: c.tier,
      internalNotes: c.internalNotes,
      openInvoices: view.all(Invoice).filter((i) => i.status === "open").map((i) => ({ invoiceId: i.invoiceId, amount: Number(i.amount) })),
    };
  },
});
```

* `reads` is a hard limit. A handler sees only the objects and properties it declares.
* `prop(Customer.internalNotes)` tags an output field with its property. Callers who may not read that property get it unset. See [Field masking](https://trytilde.ai/docs/foundry/policies.md#field-masking).
* `ctx.sql` runs read-only SQL over the view instance, with objects as tables: `ctx.sql('SELECT sum(amount) AS total FROM Invoice WHERE status = ?', "open")`.

A read without a view queries across all data with `ctx.lake.query`. It is eventually consistent, seconds behind actions. It must scope its own rows, from `ctx.principal`, when that matters.

```ts theme={"system"}
handler: ({ input, ctx }) =>
  ctx.lake.query(`SELECT "customerId", name FROM Customer WHERE tier = $1 ORDER BY name`, input.tier),
```

Objects are tables named after the object, with a column per property. N:M links are tables too, such as `AccountTeam(from_key, to_key)`.

## Actions

An action changes one view instance in a transaction.

```ts theme={"system"}
import { action } from "@trytilde/ontology";

export const disputeInvoice = action("disputeInvoice", {
  description: "Flag an open invoice of this customer as disputed.",
  view: CustomerView,
  kind: "txWrite",
  input: z.object({ invoiceId: z.string() }),
  output: z.null(),
  edits: [Invoice.disputed],
  reads: [Invoice],
  handler: ({ input, view, ctx }) => {
    const inv = view.get(Invoice, input.invoiceId);
    if (!inv) return ctx.fail(`invoice ${input.invoiceId} does not belong to this customer`);
    ctx.require(inv.status === "open" && !inv.disputed, "only open, undisputed invoices can be disputed");
    ctx.update(Invoice, input.invoiceId, { disputed: true });
    return null;
  },
});
```

* `ctx.update`, `ctx.create`, and `ctx.delete` change ontology-owned objects and properties.
* `ctx.require(condition, message)` and `ctx.fail(message)` fail the action. Nothing is written.
* `ctx.principal` says who is asking, and which actors act for them.
* `edits` is a hard limit, like `reads`.
* Set `idempotency: (input) => input.requestId` so a repeat with the same key, by the same caller, replays the first outcome.

An action ends as **succeeded**, **failed**, **denied**, or **pending approval**. See [Approvals](https://trytilde.ai/docs/foundry/policies.md#approvals).

## Call third parties

Actions never call third parties during the transaction. `ctx.deferredFetch` records the request, and Tilde sends it after the action commits, with retries.

Name one of the ontology's [connections](https://trytilde.ai/docs/foundry/sources-and-models.md#connections) as `auth`. Tilde adds the account's current credentials when it sends the request. Handlers never see them.

```ts theme={"system"}
// In an action that edits Ticket.escalated:
handler: async ({ input, ctx }) => {
  ctx.update(Ticket, input.ticketId, { escalated: true });
  await ctx.deferredFetch(`${ctx.settings.SLACK_API}/chat.postMessage`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ channel: "#escalations", text: input.note }),
  }, { auth: connections.slack });
  return null;
},
```

`ctx.deferredFetch` is fetch-compatible, so you can pass it to an SDK as its `fetch`. Its `then` option runs another action of the same view with the response, for example to store an id the third party assigned. Reads can make live calls with `ctx.fetch(url, init, { auth: connections.github })`.

### Pending values

An action can't edit a property the source owns, such as a tier in Stripe. Instead, it asks the source to change it, and marks the expected value as pending: list the property in the action's `pending`, and pass the value to `ctx.deferredFetch`. Reads show it until the change comes back through the pipeline.

```ts theme={"system"}
// In an action with `pending: [Customer.tier]`:
await ctx.deferredFetch(`${ctx.settings.STRIPE_API}/v1/customers/${view.key}`, {
  method: "POST",
  body: `metadata[tier]=${input.tier}`,
}, { auth: stripe, pending: { object: Customer, key: view.key, values: { tier: input.tier } } });
```

### Secrets and settings

Declare per-environment values in `env`, with `secret()` and `setting(default)`, and read them from `ctx.secrets` and `ctx.settings`. Prefer connections for third-party accounts. See [Settings](https://trytilde.ai/docs/foundry/deploying.md#settings).

## Realtime views

A realtime view is a read whose result is pushed to subscribers whenever it changes. A view-scoped one re-runs after every commit in its view instance. One with `watch` runs across all data, and re-runs when a watched object changes.

```ts theme={"system"}
import { realtime } from "@trytilde/ontology";

export const customerActivity = realtime("customerActivity", {
  view: CustomerView,
  input: z.object({}),
  output: z.object({ name: z.string(), notes: z.array(z.string()) }),
  reads: [Customer, CustomerNote],
  handler: ({ view }) => ({
    name: view.get(Customer, view.key)!.name,
    notes: view.all(CustomerNote).map((n) => n.body),
  }),
});
```

List them in `ontology({ realtime })`. Spaces subscribe with `useRealtime`. See [Spaces](https://trytilde.ai/docs/foundry/spaces.md).

### List views

A list view keeps a window of rows from the top of an ordered list, such as a grid, and pushes only what changed. Give it `row`, `key`, `order`, and `rows` instead of `output` and `handler`:

```ts theme={"system"}
export const watchTickets = realtime("watchTickets", {
  watch: [ticketGrid],
  input: z.object({ status: z.string().optional() }),
  row: z.object({ ticketId: z.string(), title: z.string(), openedAt: z.string() }),
  key: "ticketId",
  // Sort the way `rows` does, and end with the key so no two rows tie.
  order: () => ({ by: (r) => [r.openedAt, r.ticketId], desc: true }),
  reads: [ticketGrid],
  // `select` is either `{ keys }` (re-read these rows) or `{ after, limit }` (the page below a row).
  rows: ({ input, ctx, select }) => ctx.lake.query(/* SQL filtered by input and select */),
  summary: { output: z.object({ total: z.number() }), handler: ({ ctx }) => ({ total: 0 }) },
});
```

* A subscriber sends `{ query, limit, resume }`, with `limit` up to 1,000.
* The first update holds the window (`reset`). Later updates hold only the rows that entered or changed, each with its index (`upserts`), the keys that left (`removes`), whether more rows follow (`more`), and `summary` when it changed.
* On Postgres storage, a commit to a watched model re-reads only the keys it changed, as the subscriber, so Cedar and masking still apply. Anything else re-reads the window.
* A window that loses a row is topped up from below.
* Widening is a new subscription with the larger `limit` and the last update's `resume`: only the new rows arrive.
* Every watched model's key is the row's `key`.

## Handlers as agent tools

Every read and action becomes an agent tool with the handler's name, `description`, and input schema. A tool for a handler in a view takes `{ "key": "<view key>", "input": { ... } }`. Other tools take `{ "input": { ... } }`.

Write each `description` for the agent that calls it. Give agents a view-less read that lists keys, such as `listCustomers` in [the project guide](https://trytilde.ai/docs/project/ontology.md), so they can find the instance to act on. To connect an agent, see [Give an agent the ontology](https://trytilde.ai/docs/foundry/deploying.md#give-an-agent-the-ontology).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.