---
name: ai
description: "Use when adding LLM features (the assistant, chat, streamed text, structured output, tools, media generation)"
metadata:
  type: convention
  library: wcz-layout
---

> Mechanics are covered by TanStack's own `@tanstack/ai` skills.
> This skill adds the wcz-layout conventions on top of that.

## Rules

- Install `@tanstack/ai` and `@tanstack/ai-openai` in the app (if missing). An app with the
  assistant also installs `@tanstack/ai-code-mode`, `@tanstack/ai-isolate-quickjs` and
  `@tanstack/ai-compaction`: `layoutChat` loads them on its first call. Code mode's optional
  peers ask for an older vitest than vite-plus brings, so npm refuses to install it until the
  app's `package.json` has `"overrides": { "@tanstack/ai-persistence": { "vitest": "<version>" } }`,
  with the version `npm ls vitest` shows. `@tanstack/charts` is a peer of wcz-layout, which npm
  installs with it; the chat loads it with the first chart the model draws.
- Code mode runs the model's programs in QuickJS, whose WebAssembly a production bundle leaves
  behind: give the app's `nitro()` plugin `traceDeps: ["quickjs-emscripten"]` in `vite.config.ts`.
- Require the gateway env in the app's `src/env.ts` `server` block, so a missing value fails at
  startup: `AI_BASE_URL: z.url()` and `AI_SUBSCRIPTION_KEY: z.string()`. The gateway token also
  uses the Entra app registration: `ENTRA_TENANT_ID`, `ENTRA_CLIENT_ID`, `ENTRA_CLIENT_SECRET`.
  Values come from `.env.local` or Vault.
- The assistant is one server function that returns `layoutChat({ data, user, systemPrompts,
  tools, guides })` from `wcz-layout/ai`, and nothing else. `layoutChat` brings what every app's
  assistant shares: the model, code mode, the guides, the shared rules (how to read and change
  data, deletes, charts, attached files, the page, the reply's language), who the user is, a
  conversation bounded at 100k tokens and a `[chat]` line in the server log with the tokens of
  each model call. Never call `chat()` for the assistant yourself, and never repeat those rules
  in the app's prompt.
- `systemPrompts` say only what the app is: what its records are called and mean, what the
  assistant cannot do there, and the paths of its pages (`[name](/orders/<id>)`), so the model
  links the records it mentions. Keep it the same for every user and every request: no user,
  date or page in it, or the provider's prompt cache misses. `layoutChat` adds the user; the
  model reads the time with `get_time` and the page with `read_page` when a request needs them.
- `tools` are server tools (`toolDefinition(...).server(...)`) that call the app's own server
  functions, `deleteOrder({ data: id })`: called on the server they run in the same request, with
  the screens' middleware, validation and permission checks. Never reimplement a server function
  for a tool. After a write, `context?.emitCustomEvent("invalidate", { queryKey })` makes the
  chat invalidate that query, so open screens refetch.
- A tool without `needsApproval` becomes a function of the programs the model runs
  (`execute_typescript`): it reads, filters, joins and counts on the server, and creates or
  changes many records in one program, e.g. a device per row of an attached spreadsheet. Only
  the program's answer enters the conversation. So a reading tool takes no filters: it returns
  every record the user may see, with an `outputSchema` that gives the model the rows' shape.
- Only tools that delete get `needsApproval: true`. They stay tool calls of their own, and the
  chat asks "Are you sure?" (Cancel / Confirm) before one runs.
- Give feature tools `lazy: true`: the model sees names and first sentences, and loads a
  feature's types only when a request needs them. Write each description's first sentence to
  stand alone.
- `guides` is how the app works, as markdown by topic, each starting with a `# Title` line:
  `import orders from "./guides/orders.md?raw"`. Only the titles ride on every request; the
  model reads a guide when a question touches it. Write them from the user's view: the rules,
  who may do what, what happens next. This is what lets a new user ask anything about the app.
- Build every chat with `createLayoutChatHook(chatFn)` from `wcz-layout/hooks`. Its labels are
  `Layout.Chat.*` keys: copy the `Layout.Chat` object from wcz-layout's `src/lib/locales/*.json`
  into each of the app's locale files, or the chat shows raw keys.
- An app-wide assistant is one chat on every page: a component rendering
  `<LayoutChat chat={useLayoutChat({ threadId })} />`, passed as `LayoutProvider`'s
  `options.chat`. It shows for a signed-in user, opens from the app bar and mounts on the first
  open. From `lg` up it docks beside the page and remembers its width and whether it is open;
  below `lg` it covers the page right of the navigation rail, opens only from the button and
  closes when a page opens, so a link, `navigate` or the rail shows the page. A chat page of its
  own sits in a parent with a height (e.g. `Fullscreen`). `LayoutChat` takes `sx` for its root,
  e.g. a background; it has none of its own.
- The chat brings these without any app code. Never build them again:
  - Files: the user drops them anywhere on the chat, pastes them or picks them. They travel in
    the message, never to the file service, and the model reads them as they are: images, PDF,
    Word, Excel, PowerPoint, CSV and text, up to 10 MB each. Nothing is parsed in the app. Of a
    spreadsheet the model sees the first 1000 rows of each sheet.
  - A message sent while a reply streams waits in a queue above the input, where it can be
    cancelled.
  - The conversation survives a reload and ends with the tab (`sessionStorage`, per user).
  - Each tool shows as one line with its name, and a program with the functions it calls.
- Every chat has these client tools built in: `show_ui` (the model renders MUI components, and
  charts: a `Chart` node with TanStack Charts marks as children, their official options as
  props), `ask_user` (asks with an MUI form), `get_user` (the signed-in user), `set_app_theme`
  (light, dark or system), `navigate` (opens one of the app's pages, listed from its route tree,
  and leaves a page whose record was just deleted), `get_time` (the user's current time and
  zone), and `read_page`, `click`, `fill` and `press_key` (the model uses the page the user is on
  as they would: it reads the address, the text, the numbered controls and the one the user was
  last in, clicks, types and presses keys, and never answers a `useDialogs` confirmation). Never
  define them again.
- The page tools read what a screen reader would, so a page the model can use has a name on
  every control: a `Tooltip` title or `aria-label` on each icon button, a label on each field,
  and a button, link or `CardActionArea` for anything clickable. Deletes confirm through
  `useDialogs`, which the model never clicks.
- Other browser actions are client tools:
  `useLayoutChat({ threadId, tools: [def.client(run)] })`, with `run` using the screen's hooks.
- One-off calls (a translation, a typed answer, reading a document) are `chat()` with
  `adapter: await chatAdapter("gpt-5.5")` from `wcz-layout/ai`, created per request in a server
  function (`src/server/...`): it reads server env and tokens, and sends the app token and the
  subscription key itself. It is the one adapter for everything, files included: a `document`
  part with `source: { type: "data", value: base64, mimeType }` and `metadata: { filename }`
  reaches the model as the file itself (PDF, Word, Excel, PowerPoint, CSV, text). Never build
  an OpenAI adapter in the app: `createOpenaiChat` (Responses API) fails on follow-ups with
  `400 invalid_encrypted_content`, because the gateway load-balances Azure deployments, and
  TanStack's own Chat Completions adapter refuses documents.
- Structured output (one typed object, e.g. a generated document) stays raw `useChat` with
  `outputSchema` and `partial`, not the chat. Render streamed text outside the chat with
  `@tanstack/markdown` (install if missing): `<Markdown>` from `@tanstack/markdown/react`.

## Example

```ts
// src/env.ts (server block)
AI_BASE_URL: z.url(),
AI_SUBSCRIPTION_KEY: z.string(),

// src/server/actions/assistant.ts
import { toolDefinition } from "@tanstack/ai";
import type { RunAgentInput } from "@tanstack/ai/client";
import { createServerFn } from "@tanstack/react-start";
import { layoutChat } from "wcz-layout/ai";
import { authMiddleware } from "wcz-layout/middleware";
import z from "zod";
import { OrderSchema } from "~/lib/schemas/order";
import orders from "../guides/orders.md?raw";
import { deleteOrder, insertOrder, selectOrders } from "./order"; // the screens' server functions

const SYSTEM_PROMPT =
  "You are the assistant in Orders, the application in which departments order material. " +
  "Link an order to its page with a markdown link: [number](/orders/<id>).";

const orderTools = [
  toolDefinition({
    name: "list_orders",
    description: "Every order the user can see, with its lines and state.",
    inputSchema: z.object({}),
    outputSchema: OrderSchema.array(),
    lazy: true,
  }).server(() => selectOrders()),
  toolDefinition({
    name: "create_order",
    description: "Create an order. It needs a supplier and at least one line.",
    inputSchema: OrderSchema.omit({ id: true }),
    lazy: true,
  }).server(async (order, context) => {
    const id = crypto.randomUUID();
    await insertOrder({ data: { ...order, id } });
    context?.emitCustomEvent("invalidate", { queryKey: ["orders"] });
    return { id, page: `/orders/${id}` };
  }),
  toolDefinition({
    name: "delete_order",
    description: "Delete one of the user's orders.",
    inputSchema: z.object({ id: z.uuid() }),
    needsApproval: true,
    lazy: true,
  }).server(async ({ id }, context) => {
    await deleteOrder({ data: id });
    context?.emitCustomEvent("invalidate", { queryKey: ["orders"] });
    return { deleted: id };
  }),
];

export const assistant = createServerFn({ method: "POST" })
  .validator(z.custom<RunAgentInput>())
  .middleware([authMiddleware()])
  .handler(({ data, context: { user } }) =>
    layoutChat({
      data,
      user,
      systemPrompts: [SYSTEM_PROMPT],
      tools: orderTools,
      guides: { orders },
    }),
  );
```

```tsx
// src/components/Assistant.tsx
import { createLayoutChatHook } from "wcz-layout/hooks";
import { assistant } from "~/server/actions/assistant";

const { useLayoutChat, LayoutChat } = createLayoutChatHook(assistant);

export function Assistant() {
  const chat = useLayoutChat({ threadId: "assistant" });

  return <LayoutChat chat={chat} />;
}

// src/routes/__root.tsx
<LayoutProvider navigation={navigation} theme={theme} options={{ chat: <Assistant /> }}>
```
