> ## 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.

| Handler | Runs | Use it for |
| - | - | - |
| `read` with a view (`txRead`) | In one view instance, on fresh data | Everything about one customer, now. |
| `read` without a view | Across all data, for analytics | Lists, search, and aggregates. |
| `action` (`txWrite`) | In one view instance, as one transaction | Changes, and calls to third parties. |
| `realtime` | Like a read, pushed again whenever its result changes | Live spaces. |

## 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 ontology/customer.ts theme={"system"}
import { transactionalView } from "@tilde/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 "@tilde/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/ontology/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"}
export const topCustomers = read("topCustomers", {
  description: "Customers in a tier.",
  kind: "read",
  input: z.object({ tier: z.enum(["bronze", "silver", "gold"]) }),
  output: z.array(z.object({ customerId: z.string(), name: z.string() })),
  reads: [Customer],
  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 "@tilde/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;
  },
});

export const addCustomerNote = action("addCustomerNote", {
  description: "Write a note about a customer. Repeating a requestId replays the first outcome.",
  view: CustomerView,
  kind: "txWrite",
  input: z.object({ requestId: z.string(), body: z.string() }),
  output: z.object({ noteId: z.string() }),
  edits: [CustomerNote],
  reads: [Customer],
  idempotency: (input) => input.requestId,
  handler: ({ input, view, ctx }) => ({
    noteId: ctx.create(CustomerNote, { customer: view.key, body: input.body, author: ctx.principal.sub }),
  }),
});
```

| Helper | Does |
| - | - |
| `ctx.update(Object, key, values)` | Changes ontology-owned properties. |
| `ctx.create(Object, values)` | Creates an ontology-owned object, and returns its key. |
| `ctx.delete(Object, key)` | Deletes an ontology-owned object. |
| `ctx.require(condition, message)` | Fails with `message` unless the condition holds. Nothing is written. |
| `ctx.fail(message)` | Fails with `message`. |
| `ctx.principal` | Who is asking: `sub`, the actors acting for them (`act`), and token attributes (`attrs`). |

`edits` is a hard limit, like `reads`. With `idempotency`, 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/ontology/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. It retries with backoff, in order per origin, with an `Idempotency-Key` header.

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

```ts theme={"system"}
export const escalateTicket = action("escalateTicket", {
  description: "Escalate an open ticket, and post it to Slack.",
  view: CustomerView,
  kind: "txWrite",
  input: z.object({ ticketId: z.string(), note: z.string() }),
  output: z.null(),
  edits: [Ticket.escalated],
  reads: [Ticket],
  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: slack });
    return null;
  },
});
```

`ctx.deferredFetch` is fetch-compatible, so you can pass it to an SDK as its `fetch`. Reads can make live calls with `ctx.fetch(url, init, { auth: slot })`.

Options of `ctx.deferredFetch`:

| Option | Does |
| - | - |
| `auth` | A connection slot, or an `auth()` resolver that derives headers from secrets when the request is sent. |
| `pending` | Expected new values of source-owned properties, shown until the source confirms them. |
| `then` | An action of the same view to run with the response, for example to store an id the third party assigned. List it in the action's `continuations`. |
| `idempotencyKey` | A key stable across retries. |

### Pending values

When an action changes a value the source owns, such as a tier in Stripe, declare the property in `pending`. Reads then show the expected value until the change comes back through the pipeline.

```ts theme={"system"}
export const updateCustomerTier = action("updateCustomerTier", {
  view: CustomerView,
  kind: "txWrite",
  input: z.object({ tier: z.enum(["bronze", "silver", "gold"]) }),
  output: z.null(),
  edits: [],
  reads: [Customer],
  pending: [Customer.tier],
  handler: async ({ input, view, ctx }) => {
    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 } } });
    return null;
  },
});
```

### Secrets and settings

Declare per-environment values in `env`, and read them from `ctx.secrets` and `ctx.settings`.

```ts theme={"system"}
import { secret, setting } from "@tilde/ontology";

export const env = {
  PARTNER_API_KEY: secret(),
  STRIPE_API: setting("https://api.stripe.com"),
  SLACK_API: setting("https://slack.com/api"),
};
```

Prefer connection slots for third-party accounts. Settings keep their defaults unless an environment overrides them, which lets a test environment point at a stand-in API. See [Secrets and settings](https://trytilde.ai/docs/ontology/deploying.md#secrets-and-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 "@tilde/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),
  }),
});

export const tierBoard = realtime("tierBoard", {
  watch: [Customer],
  input: z.object({ tier: z.string() }),
  output: z.array(z.object({ customerId: z.string() })),
  reads: [Customer],
  handler: ({ input, ctx }) => ctx.lake.query(`SELECT "customerId" FROM Customer WHERE tier = $1`, input.tier),
});
```

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

## 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 `topCustomers`, so they can find the instance to act on. To connect an agent, see [Give an agent the ontology](https://trytilde.ai/docs/ontology/deploying.md#give-an-agent-the-ontology).


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