# JavaScript

Embed rungent in a JavaScript API and put the dock in your web app. What createRungent takes, how to mount it on Hono, Express and Cloudflare Workers, which store to use, and the few dock props that matter.

An embedded rungent is one Web-standard `fetch` handler inside your app. Whatever the framework, the
integration is this:

```ts
import { createRungent } from 'rungent';

const rungent = createRungent({ url, host, signingKey, secret, store, models });

// Route these paths to rungent.fetch(request):
// /rungent/v0/*  /mcp  /skill.md  /llms.txt  /.well-known/rungent-keys.json
```

`createRungent` returns `{ fetch(request, ctx?), migrate(), close() }`. It does no I/O until the
first request, which creates rungent's tables; `migrate()` does it ahead of time, and `close()` waits
for runs in progress. rungent ships no framework adapter: the lines below are all of it. The
[Quickstart](quickstart.md) walks through a whole Hono host.

## What createRungent takes

| Option | What it is |
|---|---|
| `url` | **Required.** The public URL rungent is served at, `https://console.example.com`. Signed into every assertion as `iss`. |
| `host.origin` | **Required.** Your product's public origin: the assertion's `aud`, and the start of its `htu`. |
| `host.openapi` | **Required.** Path or URL of your OpenAPI 3.1 document, fetched with each user's credential. |
| `host.fetch` | Your app's own `fetch` (Hono's `app.fetch`), so rungent calls your API in the process. Default: the global `fetch`. |
| `host.baseUrl` | Where rungent reaches your API over the network (`http://127.0.0.1:3000`). Default: `host.origin`. |
| `signingKey` | **Required.** rungent's Ed25519 key, from `importSigningKey`. See [Keys and rotation](acting-as-the-user.md#keys-and-rotation). |
| `secret` | **Required.** 32 bytes or more; seals the model API keys admins save. A list rotates it: the first seals, every one unseals. |
| `store` | **Required.** Where conversations, approvals and settings live. See [Choose a store](#choose-a-store). |
| `models` | **Required.** `{ chain }`, the default model chain. See [Choose models](deploy.md#choose-models). |
| `name` | The assistant's name. Default `Assistant`. |
| `instructions` | Product facts added to the system prompt: a string, or a function of the user's identity. |
| `product` | `{ name, summary? }` for `/skill.md` and `/llms.txt` when a signed-out caller cannot read your OpenAPI. |
| `basePath` | Serve every route below a prefix. See [Serve rungent under a prefix](#serve-rungent-under-a-prefix). |
| `sources` | More search sources, such as your docs. See [Search and knowledge](search.md#index-docs-from-code). |
| `hostKeys` | Public keys your API signs `Rungent-Host-Assertion` with. See [HTTP API](http-api.md#host-assertions). |
| `skill` | `{ name?, guide?, cli? }` for `/skill.md`. See [Surfaces](surfaces.md#skill-md-and-llms-txt). |
| `limits` | `{ maxSteps, contextTokens, runTimeoutSeconds }`. Defaults 16, 128 000 and 600. |
| `mcp` | `{ authorizationServers?, instructions? }`. See [Surfaces](surfaces.md#sign-in-with-oauth). |

## Mount it on Hono

Give rungent your app's `fetch` and mount the paths. Its calls never leave the process; each arrives
at your routes as a request to `host.origin`.

```ts
const rungent = createRungent({
  url: 'https://console.example.com',
  host: { origin: 'https://console.example.com', openapi: '/api/openapi.json', fetch: app.fetch },
  // signingKey, secret, store, models …
});

for (const path of ['/rungent/v0/*', '/mcp', '/skill.md', '/llms.txt', '/.well-known/rungent-keys.json']) {
  app.all(path, (c) => rungent.fetch(c.req.raw));
}
```

rungent refuses a mutating request the browser marks `Sec-Fetch-Site: cross-site`, and under
`/rungent/v0` a body that is not `application/json`, so a cookie session cannot be driven from
another site.

## Mount it on Express

`nodeHandler(rungent)` from `rungent/node` adapts rungent to Node's `(req, res)`. Register it
before any body parser: rungent reads the raw body itself.

```ts
import express from 'express';
import { createRungent } from 'rungent';
import { nodeHandler } from 'rungent/node';

const app = express();
const rungent = createRungent({
  url: 'https://console.example.com',
  host: { origin: 'https://console.example.com', baseUrl: 'http://127.0.0.1:3000', openapi: '/api/openapi.json' },
  // signingKey, secret, store, models …
});

app.all(['/rungent/v0/*splat', '/mcp', '/skill.md', '/llms.txt', '/.well-known/rungent-keys.json'], nodeHandler(rungent));
app.use(express.json({ verify: (req, _res, buf) => { (req as { rawBody?: Buffer }).rawBody = buf; } }));
// … your routes
app.listen(3000);
```

The patterns are Express 5 syntax. Express has no in-process `fetch`, so rungent calls your API over
loopback at `host.baseUrl`. When you verify the assertion, rebuild its URL from the public origin
(`https://console.example.com${req.originalUrl}`) and hash `rawBody`, the exact bytes received.
On shutdown, `await rungent.close()` lets runs in progress finish.

## Mount it on Cloudflare Workers

Bindings arrive with each request, so build rungent once per isolate on the first one, and pass the
execution context: a run then keeps going with `waitUntil` after its response closes.

```ts
import { createRungent, SqlStore, type Rungent } from 'rungent';
import { importSigningKey } from 'rungent/delegation';
import { d1Driver } from 'rungent/sql/d1';

let rungent: Promise<Rungent> | undefined;

const rungentFor = (env: Env) =>
  (rungent ??= importSigningKey(JSON.parse(env.RUNGENT_SIGNING_KEY)).then((signingKey) =>
    createRungent({
      url: 'https://console.example.com',
      host: { origin: 'https://console.example.com', openapi: '/api/openapi.json', fetch: (request) => app.fetch(request, env) },
      signingKey,
      secret: env.RUNGENT_SECRET,
      store: new SqlStore(d1Driver(env.DB)),
      models: { chain: [{ id: 'main', provider: 'openai', model: 'gpt-4.1-mini', apiKey: env.OPENAI_API_KEY }] },
    }),
  ));

for (const path of ['/rungent/v0/*', '/mcp', '/skill.md', '/llms.txt', '/.well-known/rungent-keys.json']) {
  app.all(path, async (c) => (await rungentFor(c.env)).fetch(c.req.raw, c.executionCtx));
}
```

Keep `RUNGENT_SIGNING_KEY` and `RUNGENT_SECRET` as Worker secrets (`wrangler secret put`). `waitUntil`
still ends with the request's time limits, and every isolate has its own MCP sessions. In
production, route each user to a Durable Object that builds the rungent instance the same way and
calls `rungent.fetch(request, this.ctx)`: the object keeps running while a run streams, and one
user's requests meet in one place.

## Choose a store

| Store | Use it for |
|---|---|
| `new SqlStore(postgresDriver(url))`, driver from `rungent/sql/postgres` | Production, and several processes sharing one database. Needs the `postgres` package. |
| `new SqlStore(sqliteDriver('rungent.sqlite'))`, from `rungent/sql/sqlite` | One process on Node, with the built-in `node:sqlite`. |
| `new SqlStore(d1Driver(env.DB))`, from `rungent/sql/d1` | Cloudflare Workers. Run `migrate()` from one place, such as a deploy step. |
| `new MemoryStore()` | Development and tests: it forgets everything on restart. |

`SqlStore` and `MemoryStore` come from `rungent`. rungent keeps its own `rungent_*` tables and
creates or upgrades them on the first request; give it its own database or schema.
`postgresDriver` also takes an existing `postgres` client.

For development, `generateKeyPair('dev')` from `rungent/delegation` makes a key in memory
(`signingKey: (await generateKeyPair('dev')).signing`). In production, load the generated private
JWK with `importSigningKey(JSON.parse(process.env.RUNGENT_SIGNING_KEY!))`.

## Serve rungent under a prefix

To serve rungent at `/assistant`, set `basePath: '/assistant'` and
`url: 'https://console.example.com/assistant'`. Every route moves below the prefix, so one
`app.all('/assistant/*', …)` mounts it, and the web client takes the prefix:
`createClient({ baseUrl: '/assistant' })`.

## Add the dock

Mount the dock once, in the web app's root layout, around the area your pages render in. It then
stays put, with its conversation, while the user moves between pages.

```tsx
// web/RootLayout.tsx
import { createClient } from 'rungent/client';
import { RungentDock, RungentProvider, SearchPalette } from 'rungent/react';
import 'rungent/react/styles.css';

const client = createClient();

export function RootLayout({ children }: { children: React.ReactNode }) {
  const navigate = useNavigate();
  return (
    <RungentProvider
      client={client}
      locale={i18n.language}
      onOpen={navigate}
      forms={{ create_vm: CreateVm }}
      suggestions={() => ['Which servers are running?', 'Create a server']}
      context={() => [{ description: 'The page the user is on', value: location.pathname }]}
    >
      <Header />
      <RungentDock>{children}</RungentDock>
      <SearchPalette />
    </RungentProvider>
  );
}
```

The components need React 19. `createClient()` talks to the page's own origin, and the browser's
cookies sign the user in. An app that keeps an access token passes it on every request with
``createClient({ headers: async () => ({ Authorization: `Bearer ${await getToken()}` }) })``;
`baseUrl` points at another origin or a prefix.

### Props that matter

| `RungentProvider` prop | What it is |
|---|---|
| `client` | The client above. |
| `forms` | Your page's own form components, by operation name. See [Forms and approvals](forms-and-approvals.md#show-your-page-s-own-form). |
| `onOpen` | `(path) => void`: your router, for pages the assistant opens and links in answers. Same-origin paths only; without it, rungent sets `window.location`. |
| `locale` | rungent's own text: `zh-CN` has its own strings, any other tag speaks English. Pick it from your app's language setting. `strings` overrides any string by key (`{ assistant: 'Copilot' }`). |
| `theme` | `'light'`, `'dark'` or `'system'` (the default). |
| `context` | `() => {description, value}[]`, called as each run starts: what the user is looking at, so "stop this one" means the server on screen. |
| `suggestions` | `() => string[]`: questions an empty conversation offers, for example per page. |
| `upload` | `(file) => Promise<{url, mimeType, name}>`: stores a file the user attaches. Without it, the composer offers no attachments. |

`RungentDock` takes `open`/`onOpenChange` to control it, `onLayoutChange` (told `'closed'`,
`'panel'` or `'expanded'`, for example to fold your navigation), and `launcher={false}` when
your product has its own button. `useDock().ask(text)` opens it on a new conversation that starts
with that message. Under a fixed header, set `--rungent-dock-top` to the header's height. On a page
whose layout you do not own, render `<RungentDock />` without children: the panel is then fixed at
the window's edge.

### ⌘K and styles

`SearchPalette` opens on ⌘K; `useSearchPalette().open()` opens it from a search button, since
phones have no ⌘K. Every color and size is a CSS variable on `.rungent-root`:

```css
.rungent-root {
  --rungent-accent: #0f766e;
  --rungent-accent-fg: #ffffff;
  --rungent-radius: 6px;
  --rungent-font: Inter, system-ui, sans-serif;
}
.rungent-root[data-rungent-theme='dark'] { --rungent-accent: #2dd4bf; }
```

The components' styles set what they rely on, so a CSS reset such as Tailwind's preflight does
not change them. For a conversation UI of your own, `useThread`, `useThreads`, `useSearch`,
`useCatalog`, `RungentThread`, `ApprovalCard` and `RungentForm` are exported too; the events behind
them are in [HTTP API](http-api.md#events).

## Where to go next

- [Deploy](deploy.md#choose-models): the model chain, and the admin page that changes it.
- [Testing](testing.md): check every surface against your deployment.
