---
name: ai
description: "Use when adding LLM features (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); the server function imports it directly.
  `@tanstack/charts` is a peer of wcz-layout, which npm installs with it; the chat loads it with
  the first chart the model draws, so an app never defines a chart tool of its own.
- 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.
- Import the adapter from `wcz-layout/ai`: `adapter: await chatAdapter("gpt-5.5")`, created
  per request inside the server function. It sends the app token and the subscription key itself.
  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.
- Call `chatAdapter` only in server functions (`src/server/...`): it reads server env and tokens.
- 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.
- 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,
  so the prompt never states it), and `read_page`, `click`, `fill` and `press_key` (the model
  uses the page the user is on as they would: it reads the text and numbered controls, clicks,
  types and presses keys, and never answers a `useDialogs` confirmation). Never define them
  again. The client sends its tools with every request, so the
  server function only merges them: `tools: mergeAgentTools(serverTools, tools)`. It must also
  forward `parentRunId` and `resume`, or tool results and approvals never continue the run.
- The chat sends the page the user is on as AG-UI context. Put it in the prompt: each
  `aguiContext` item becomes a `"<description>: <value>"` line in `systemPrompts` (see the example).
- Data and writes are server tools (`toolDefinition(...).server(...)`) in `serverTools` 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.
- Only tools that delete get `needsApproval: true`: the chat asks "Are you sure?" (Cancel /
  Confirm) before they run, so the prompt tells the model to say first what it will delete.
  Creating and changing run straight away, and the model says what it did.
- Give feature tools `lazy: true` and pass `lazyToolsConfig: { includeDescription:
  "first-sentence" }` to `chat()`: the model sees names and first sentences, and loads a feature's
  schemas only when a request needs them. Write each description's first sentence to stand alone.
  Pass `agentLoopStrategy: maxIterations(20)` too: the default 5 turns end a run without a reply
  once discovering, looking up and saving add up.
- 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.
- The chat renders markdown links to the app's own pages (`/...`) through the router; tell the
  model the page paths so it links the records it mentions.
- 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 {
  chat,
  chatParamsFromRequestBody,
  maxIterations,
  mergeAgentTools,
  toServerSentEventsResponse,
  toolDefinition,
} from "@tanstack/ai";
import type { RunAgentInput } from "@tanstack/ai/client";
import { createServerFn } from "@tanstack/react-start";
import { authMiddleware } from "wcz-layout/middleware";
import { chatAdapter } from "wcz-layout/ai";
import z from "zod";
import { deleteOrder } from "./order"; // the server function the screens call

const orderTools = () => [
  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(async ({ data }) => {
    const { messages, threadId, runId, parentRunId, resume, tools, aguiContext } =
      await chatParamsFromRequestBody(data);
    const abortController = new AbortController();
    const stream = chat({
      adapter: await chatAdapter("gpt-5.5"),
      threadId,
      runId,
      parentRunId,
      resume,
      systemPrompts: [
        SYSTEM_PROMPT,
        ...aguiContext.map(({ description, value }) => `${description}: ${value}`),
      ],
      messages,
      tools: mergeAgentTools(orderTools(), tools),
      lazyToolsConfig: { includeDescription: "first-sentence" },
      agentLoopStrategy: maxIterations(20),
      abortController,
    });
    return toServerSentEventsResponse(stream, { abortController });
  });
```

```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 /> }}>
```
