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

# Sources and models

> Feed an ontology with pipelines declared in TypeScript, its connections, custom streams, and Tilde's own chat events, then shape the raw records into tables with SQL models.

Data reaches an ontology in two steps. **Sources** bring raw records in, one table per stream. **Models** are SQL that turns those records into the tables your objects read.

Pick the source that matches where the data is:

| Your data is in | Use |
| - | - |
| A third-party API, such as Linear or Stripe, or your own database | A [pipeline](#declare-pipelines) |
| Your own code, which sends records | A [custom stream](#custom-streams) |
| The project itself, such as a lookup table | [Reference data](#reference-data) |
| Tilde's own chat threads and messages | [Tilde chat events](#tilde-chat-events) |

## Declare pipelines

A pipeline feeds a source's raw streams. Declare it in TypeScript next to the source, with `source(name, { pipeline })`, and list it in `ontology({ pipelines })`. It compiles into the version, and Tilde runs it in each environment the version deploys to.

```ts ontologies/crm/pipelines.ts theme={"system"}
import { defineSecrets, github as githubPipelines, linear as linearPipelines, postgres, secret, source } from "@trytilde/ontology";
import { connections } from "./connections.ts";

export const secrets = defineSecrets({ APP_DB_PASSWORD: secret() });

// Poll Linear through the environment's `linear` connection.
export const linear = source("linear", {
  pipeline: linearPipelines.poll({ connection: connections.linear, streams: ["issues", "comments", "projects"], interval: "60s" }),
});

// Your own PostgreSQL database, by logical replication. The password is the environment's secret.
export const app = source("app", {
  pipeline: postgres.cdc({
    host: "db.example.com",
    user: "repl",
    password: secrets.APP_DB_PASSWORD,
    database: "app",
    sslmode: "require",
    tables: ["public.users", "public.orders"],
  }),
});
```

Read a stream with `linear.stream("issues")`. Stream names are typed by the pipeline, so a misspelt stream does not compile. List the connections, secrets, and pipelines in `ontology({ connections, secrets, pipelines: [linear, app, github] })`, with `github` from [GitHub](#github) below.

Pipeline helpers cover polled APIs (`linear`, `sentry`, and `cloudwatch`, and `polled()` for Plaid, QuickBooks, Xero, Google mail, calendars, and contacts, and Slack), GitHub (`github.sync`), provider webhooks (`github.webhook`, `linear.webhook`, `sentry.webhook`), your own `webhook()`, PostgreSQL row changes (`postgres.cdc`), Kafka topics (`kafka.consume`), and Tilde's own events (`tilde.events`).

* A pipeline with a `connection` gets the account's current credentials from Tilde, including refreshed OAuth tokens. A webhook pipeline with a connection receives that provider's verified webhooks.
* Any other credential is a secret from `defineSecrets`. Each environment binds it to one of your team's secrets. See [Bind connections and secrets](https://trytilde.ai/docs/foundry/deploying.md#bind-connections-and-secrets).
* Polled pipelines take `backfill: { start: "90d" }`: where the first run starts, as a date, an RFC 3339 time, or a duration before now.
* Once an ontology has one pipeline, every source it reads needs one, and every pipeline must be read.

### GitHub

`github.sync` keeps one stream per GitHub entity for the repositories you list: pull requests, their reviews, check runs, and releases. On its first run it backfills each repository's recent history from GitHub's API (30 days unless `backfill.start` says otherwise). After that, the connection's webhooks keep it current. Rows are the webhook bodies, whether backfilled or delivered, and each row's `_key` is the entity: `{repository, number}` for a pull request, `{id}` otherwise.

```ts ontologies/crm/pipelines.ts theme={"system"}
export const github = source("github", {
  pipeline: githubPipelines.sync({
    connection: connections.github,
    repositories: ["acme/api", "acme/web"],
    streams: ["pull_requests", "pull_request_reviews", "check_runs", "releases"],
  }),
});
```

* Only the listed repositories are written. Deliveries from any other repository the GitHub App is installed on are dropped, so list every repository you read.
* Each repository is backfilled once, by its own job: a repository added later gets its backfill on the next run, and the others are not fetched again.
* It never polls again after the backfill: GitHub's webhooks are complete.
* `github.webhook` (without `backfill`) still gives the raw deliveries, routed by event type into streams of your choosing.

## Connections

An ontology's connections are the third-party accounts it needs. Declare them as plain data, and bind each to one of your [connections](https://trytilde.ai/docs/connections.md) in each environment's entry in `tilde.config.ts`.

```ts ontologies/crm/connections.ts theme={"system"}
import type { Connections } from "@trytilde/ontology";

export const connections = {
  linear: { provider: "linear" },
  github: { provider: "github" },
  slack: { provider: "slack", type: "user_oauth" },
} satisfies Connections;
```

Pipelines and handlers name them as `connections.linear`, never as strings, and a pipeline helper takes only a connection of its provider. List them in `ontology({ connections })`. Handlers use the same connections to call the provider. See [Call third parties](https://trytilde.ai/docs/foundry/views-and-actions.md#call-third-parties).

## Custom streams

A custom stream takes records from your own code. Each record is validated against a zod schema and keyed, so a newer record with the same key replaces the older one.

```ts ontologies/crm/sources.ts theme={"system"}
import { stream } from "@trytilde/ontology";
import { z } from "zod";

export const feedback = stream("feedback", {
  schema: z.object({ id: z.string(), customerId: z.string(), score: z.number().int().min(1).max(5) }),
  key: "id",
});
```

List streams in `ontology({ streams: [feedback] })`. Write records through the management API, with a [management API key](https://trytilde.ai/docs/operator-access.md#management-api-keys) that has `write_streams` on the project.

### Reference data

A stream can also ship static records with the project, such as lookup tables. Add them as `reference: [ ... ]` on the stream, as in [the project guide](https://trytilde.ai/docs/project/ontology.md). Tilde validates them at build time and loads them on every deploy.

> [!NOTE]
>
> Removing a record from `reference` does not delete it. A redeploy only adds and replaces records.

## Tilde chat events

An ontology can read your organisation's own Tilde data, such as chat threads, messages, participants, and channel identities. Agents' conversations then become data you can join with everything else, for example to link a WhatsApp thread to a customer.

1. Declare a source named `tilde` with the streams you want. Message bodies reach the ontology only if you list `public_chat_messages`.

   ```ts ontologies/crm/pipelines.ts theme={"system"}
   import { source, tilde as tildeEvents } from "@trytilde/ontology";

   export const tilde = source("tilde", {
     pipeline: tildeEvents.events({
       streams: ["public_chat_threads", "public_chat_messages", "public_chat_participants", "public_chat_channel_identities"],
     }),
   });
   ```

2. Turn on **Registry events** in the environment's settings. Tilde delivers existing rows first, then every change, for the streams the version declares.

## Models

A model is SQL over sources or other models, in dbt's vocabulary. Read sources with `source(pipeline, stream)`, or use a custom stream directly.

```ts ontologies/crm/models.ts theme={"system"}
import { cdcCurrent, model, source, sql, t, tests } from "@trytilde/ontology";

// The latest row per key of a stream, with deletes applied.
export const stripeCustomers = model({ name: "stripe_customers", schema: "current", ...cdcCurrent(source("stripe", "customers")) });

export const customers = model({
  name: "customers",
  schema: "staging",
  materialized: "incremental",
  uniqueKey: "customer_id",
  tests: [tests.notNull("customer_id"), tests.unique("customer_id")],
  sql: ({ ref, changes, isIncremental }) => sql`
    SELECT payload->>'id' AS customer_id,
           payload->>'name' AS name,
           coalesce(payload->>'$.metadata.tier', 'bronze') AS tier
    FROM ${isIncremental ? changes(stripeCustomers) : ref(stripeCustomers)}`,
});
```

* `materialized` is `view`, `table`, `incremental`, or `cell`. A `cell` model is a table of a [transactional view](https://trytilde.ai/docs/foundry/views-and-actions.md#transactional-views).
* `sql` runs once for the full build and once for incremental runs. Use `ref()` for models and objects, `src()` for sources, and `changes()` for rows that changed since the last run. The build rejects SQL that names a raw table directly.
* You can keep SQL in a file with `sql: sqlFile("./customers.sql")`.
* Models and handler SQL use DuckDB's SQL dialect. Read JSON with `->>`, such as `payload->>'$.address.country'`.

### When a deploy rebuilds a model

Some changes make a deployed model rebuild from scratch, such as new inputs to `changes()`, a new schema, or a new dependency. Tilde refuses a deploy that would rebuild a model, and names each model. Deploy again with `tilde deploy --accept-rebuild <model>` when the rebuild is what you want. See [Deploy](https://trytilde.ai/docs/foundry/deploying.md#deploy).


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