# Sygnal: AI (`sygnal/ai`): chat, one-off requests, agent tools, decisions, composed UI, chat cards

> A topic file of Sygnal's agent context. It assumes the core (`llms.txt`, or the sygnal-dev skill's `SKILL.md`: mental model, component anatomy, canonical forms, wiring rules, testing): read that first. Canonical forms only.

## In short
- **AI** (`sygnal/ai`): a chat conversation is the `chat` behavior, never hand-rolled: `uses = { chat: chat({ agent: false, form: '.ask', prompt: '.prompt', stop: '.stop', regenerate: '.retry' }) }` → `state.chat` (`messages`, `prompt`, `draft`, `status`, `error`; Stop keeps the partial reply, Retry doesn't repeat the question); a one-off request (summary, structured `output`) is an `LLM` sink request `{ messages: [{ role: 'user', content: text }], delta: 'DELTA', ok: 'DONE', error: 'FAILED' }`; both need `makeChatDriver({ transport })` (tests: `t.stream('LLM', ['Hi'])`); what agents may run is the `agent` static `{ name, description, read, actions, queries }` (only declared actions; `read` is all they see; `queries: { find: { description, input, run: (state, input) => result } }` are read-only lookups, pure and synchronous; an action that starts a fetch answers once it lands with `until: 'resourceName'`; tests: `t.callTool(name, args)`); typed answers: `decide()` + `choice` / `noul` / `score` as a resource. No provider API key in the browser: `uiMessageStream('/api/chat')` to your server.

## Details
- **A chat conversation** (send, streaming draft, Stop keeping the partial reply, Retry) is the `chat` behavior with no tools; don't hand-roll it: `Chat.uses = { chat: chat({ agent: false, form: '.ask', prompt: '.prompt', stop: '.stop', regenerate: '.retry' }) }` → `state.chat` (`messages`, `prompt` (bind `<input className="prompt" value={state.chat.prompt} />`), `draft`, `status`: `'ready' | 'submitted' | 'streaming' | 'error'`, `error`), the markup in the host's own view (SYG104), `next('chat.SEND', text)` to send from code, a host entry `'chat.DONE'` after a reply; options and slice: agent.md "Options and state". **One-off requests** (a summary, structured `output`, or your own state shape) are a driver request, like HTTP: `SEND: { STATE: (s) => ({ ...s, messages: [...s.messages, { role: 'user', content: s.prompt }], prompt: '' }), LLM: (s) => ({ messages: s.messages, key: 'reply', delta: 'DELTA', ok: 'DONE', error: 'FAILED' }) }` (STATE runs first: the LLM sink sends the list it stored), `DELTA: (s, { text }) => ({ ...s, draft: text })` (all the text so far), `DONE: (s, { message }) => ({ ...s, messages: [...s.messages, message], draft: '' })` (also `text`, `toolCalls`, and `value` for `output: schema`), `FAILED` gets `{ error }`; `{ abort: 'reply' }` stops it (nothing more arrives; `latest` is on: a new request with the same key aborts the old); render with `messageText(m)`. On the root, a local Ollama: `App.drivers = { LLM: makeChatDriver({ transport: openResponses({ baseURL: 'http://localhost:11434/v1', model: 'llama3.2' }) }) }`; production: `transport: uiMessageStream('/api/chat')` (an AI SDK route on your server; the JSON it POSTs: ai-chat.md, "What uiMessageStream sends"). Tests need no driver: `await t.stream('LLM', ['Hel', 'lo'])` (then `ok`), `t.respond('LLM', text)`, `t.fail('LLM', 429)`, `t.requests('LLM')`.
- **`agent` static**: what an LLM may do in the app: `TodoApp.agent = { name: 'todos', description: 'The todo list', read: (state) => ({ todos: state.todos.map(({ id, text, done }) => ({ id, text, done })) }), actions: { ADD: { description: 'Add a todo', input: z.string().min(1) }, CLEAR_DONE: { description: 'Delete the done todos', consequential: true } } }` → tools `todos_add`, `todos_clear_done`, `todos_read`. **Only declared actions are tools, and `read` is all agents see** (a projection: keep ids, leave out secrets; `untrusted: true` when it holds text users typed). Per action: `input` (a Standard Schema with JSON Schema: zod 4.2+, or `jsonSchema({ type: 'string' })`; the reducer's data is the parsed input, so `z.object({ packed: z.boolean() })` gives `(state, { packed })`, never `(state, packed)`), `consequential` (the user confirms), `when: (state) => bool`, `idempotent`, `until: 'search'` (the call answers once that resource has loaded, with the `read`, not `loading`; or `until: (state) => bool` for a reply action; `timeout` → `{ ok: true, pending: true }`); an entry counts as a trigger (SYG102); a Collection item's `agent` (+ `label: (s) => s.text`) gives one tool per action with an `id` parameter. Data too large for `read` (a long list, one record): `queries: { find: { description, input, run: (state, input) => state.todos.filter(…) } }` → read-only tool `todos_find`, `{ ok: true, result }`, nothing dispatched; `run` is pure and synchronous (async is SYG246: load data with an action + `until`). A reducer refuses with `abort('reason')` (from `'sygnal'`). Tests: `t.tools()`, `await t.callTool('todos_add', { value: 'milk' })` → `{ ok: true, state }` (a consequential tool needs `{ confirm: true }`), `t.agentContext()`. `read` / `when` / `until` / `queries.run` get the instance's bag last (props, context: `(state, bag)`, `(state, input, bag)`).
- **Decisions** (typed answers from a decision model; a fetch-driver request, `HTTP: makeFetchDriver()`): `const questions = { topic: choice('What is this ticket about?', { billing: 'Payments, invoices', bug: 'Something is broken' }), urgent: noul('Does it need handling today?'), mood: score('How upset is the customer?', ['calm', 'annoyed', 'angry']) }`, as a resource: `Ticket.resources = { triage: (state) => state.text && decide({ model: 'jev-latest', state: state.text, questions }) }` → `state.triage.data.answers.topic.choice` (`.confidence`: below ~0.6, ask a chat model), `answers.urgent.noul` (0–1), `answers.mood.score`; a click-triggered one is an `HTTP` sink `decide({ …, ok, error })`. Tests: `await t.respond('HTTP', answers(questions, { topic: 'bug', urgent: true }), 'triage')`.
- **A page a model composes from your parts** (a dashboard the user describes in words; the model only picks parts, params and places, never markup): `const catalog = defineCatalog({ parts: { revenue: { component: Kpi, props: { metric: 'revenue' }, description: 'Revenue (KPI card: the total this month)' }, orders: { component: OrdersTable, description: 'Orders (table of recent orders)', params: { status: { default: 'any', options: { any: 'orders of every status', pending: 'pending orders (not paid yet)' } } } }, tasks: { component: Checklist, state: 'tasks', description: "Tasks (the user's checklist)" } } })` (`description` is all a model sees: "Noun (what it shows)", no overlap between parts; params arrive as props; `state` is a key, a lens, or for a record param (`{ from: (state) => records }`) `(node) => byId('customers', node.params.id)` with `byId` from `'sygnal'`; `containers: { tabs: { slots, render: ({ slots, control }) => … } }` are view functions, never components (SYG161)), `Dashboard.uses = { page: compose(catalog, { backend: compose.decisions({ model: 'jev-latest' }), form: '.ask', prompt: '.prompt' }) }` (or `compose.llm()` on the `LLM` sink: same app, same tests) → `state.page` (`status`: `'composing' | 'preview' | 'done' | 'unavailable' | 'error'`, `layout`, `decisions`, `error`), rendered in the host's view as `{catalog.render(state.page, state)}` or `<Composed catalog={catalog} from="page" />`: the parts are the host's children (lenses, `CHILD.select`) keyed by identity, so a follow-up `next('page.COMPOSE', 'Move the orders to the top')` edits the page and keeps the untouched parts' instances (`{ prompt, fresh: true }` starts over; `persist` the slice to keep the page); for an agent: `actions: { ...compose.action('page') }`, `read: (s) => ({ page: compose.summary(s.page) })`. Tests (either backend): `t.simulateAction('page.COMPOSE', 'Pending orders')`, then `await composeWith(t, catalog, [{ part: 'orders', params: { status: 'pending' } }])`.
- **Cards in a chat** (the assistant asks with your parts; the user clicks the answer): `uses = { assistant: chat({ form: '.ask', prompt: '.prompt', ask: { catalog } }) }` gives the model the tool `ask_user({ need })`; the card composes from the catalog (`compose.llm()` on the chat's sink by default, or `ask: { catalog, backend: compose.decisions({ model: 'jev-latest' }) }`) and lives on the tool part as `part.ui` (`status`: `'composing' | 'open' | 'answered' | 'failed' | 'cancelled'`; persisted with the chat): render it where the view renders a `tool-ask_user` message part, `askCard(catalog, state, part) ?? <p>Composing…</p>`. A part with `result: true` answers it: `PICK: { PARENT: (state, id, next, props) => compose.answer(props, id) }` → the call's output is `{ part, answer }` and the chat goes on (no result part in the catalog: SYG686). Tools the app answers itself: `clientTools: { confirm: { description, inputSchema } }`, listed by `openToolCalls(state.assistant)`, answered with `next('assistant.TOOL_OUTPUT', { toolCallId, output })`. `chat({ model: (state) => state.chatModel })` picks the model per request. Tests: `await t.stream('LLM', [{ toolCall: { id: 'c1', name: 'ask_user', input: { need: 'Pick a plan' } } }])`, then `await composeWith(t, catalog, [{ part: 'plans' }])`.
- **Never put a provider API key in browser code**: the browser calls your server (`uiMessageStream('/api/chat')`, the default `/api/decide` of `decide()` and `compose.decisions()`), which adds the key, fixes the model and instructions, and rate-limits; an auth header to another origin is refused (SYG670). Strict provider schemas: `openResponses({ baseURL, model, strict: strictSchemas })` (an import; `strict: true` is SYG672). Every request sends the whole conversation (models are stateless); never `fetch` a provider from a component.
- Guides: `node_modules/sygnal/dist/guide/ai-chat.md` (transports, structured `output`, tools, shipping), `ai-decisions.md` (escalation, `decide.openai()`), `ai-compose.md` (catalogs, containers, edits, `byId`), `ai-cards.md` (`chat({ ask })`, client tools), `agent.md` (the in-app assistant `uses = { assistant: chat({ form: '.ask', prompt: '.prompt', instructions }) }`, `commandBar`, security), `webmcp.md` (`experimentalExposeWebMcp(app)`, `form(schema, { tool: formTool({ name, description }) })`: experimental, outside semver), `mcp-apps.md` (`makeMcpAppDriver()`: the app inside Claude or ChatGPT); online https://sygnal.js.org/guide/ai-chat/ (and `/guide/ai-decisions/`, `/guide/ai-compose/`, `/guide/ai-cards/`, `/guide/agent/`, `/guide/webmcp/`, `/guide/mcp-apps/`)

## A composed page, end to end
A model builds a page (or a card in a chat) from parts the app prepared: it only picks parts, params and places, never markup. Guides: `ai-compose.md`, `ai-cards.md`.
```jsx
import { defineCatalog, compose, Composed } from 'sygnal/ai'
import { OrdersTable, Checklist } from './parts.jsx'

export const catalog = defineCatalog({
  parts: {
    orders: {
      component: OrdersTable,
      description: 'Orders (table of recent orders)',   // all a model sees: "Noun (what it shows)"
      params: { status: { default: 'any', options: { any: 'orders of every status', pending: 'pending orders (not paid yet)' } } },
    },
    tasks: { component: Checklist, state: 'tasks', description: "Tasks (the user's checklist)" },   // a lens into app state
  },
})

export function Dashboard({ state }) {
  return (
    <main>
      <form className="ask">
        <input className="prompt" aria-label="The page you want" value={state.page.prompt} />
        <button type="submit">Compose</button>
      </form>
      <Composed catalog={catalog} from="page" />
    </main>
  )
}
Dashboard.initialState = { tasks: [] }
Dashboard.uses = { page: compose(catalog, { backend: compose.decisions({ model: 'jev-latest' }), form: '.ask', prompt: '.prompt' }) }
```
```js
import { it, expect } from 'vitest'
import { renderComponent } from 'sygnal'
import { composeWith } from 'sygnal/ai'
import { catalog, Dashboard } from './Dashboard.jsx'

it('composes the pending orders', async () => {
  const t = renderComponent(Dashboard)
  t.simulateAction('page.COMPOSE', 'Pending orders')
  await composeWith(t, catalog, [{ part: 'orders', params: { status: 'pending' } }])   // answers either backend
  await t.waitForState((s) => s.page.status === 'done')
  expect(t.state.page.layout.nodes.orders.params).toEqual({ status: 'pending' })
  t.dispose()
})
```
- `backend: compose.llm()` (the `LLM` sink, a streamed preview) takes the same catalog, view and tests. `compose.decisions()` posts to your `/api/decide` route, which holds the API key. `state.page`: `status` (`'composing' | 'preview' | 'done' | 'unavailable' | 'error'`), `layout` (plain JSON), `decisions`, `error`.
- Parts are the host's children, keyed by their node key: params arrive as props, `CHILD.select(Part)` hears their `PARENT`, a `state` lens edits app state. A follow-up `next('page.COMPOSE', 'Move the orders to the top')` edits the page and keeps the untouched parts' instances (with `compose.llm()` an edit can also group parts in a new container, `wrap`, or `unwrap` one; a runaway reply is stopped, SYG687; a step past `timeoutMs`, 300 s, is `status: 'error'`); `{ prompt, fresh: true }` starts over (while it streams, the page's other parts stay in place: `compose(catalog, { preview: 'merge' })`, the default; `'replace'`, `'keep'`). A page that recomposes itself (`STATE.watch(signature)` → `page.COMPOSE`) faster than the model answers takes `compose(catalog, { busy: 'queue' })`: one composition in flight, the newest `page.COMPOSE` waits in `state.page.queued` and starts when it lands (the default `'abort'` aborts the one in flight, so none may finish); adjust a landed layout in a `'page.DONE'` entry's STATE (`page.SET_LAYOUT` ends both); bursts: `.compose(debounce(500))` on the watch. One part per record: a param `{ from: (state) => records }` + `state: (node) => byId('customers', node.params.id)` (`byId` from `'sygnal'`). Containers (`containers: { tabs: { slots, render: (view) => … } }`) are view functions, never components (SYG161); a container repeats freely unless it sets `maxUses`. A `render` part (a view function instead of `component`) renders in the host's DOM scope, keyed by its node key. `{catalog.render(state.page, state)}` is the view-call form of `<Composed>`. An agent composes with `actions: { ...compose.action('page') }` and reads `compose.summary(state.page)`.
- **Chat cards**: `chat({ form: '.ask', prompt: '.prompt', ask: { catalog } })` under `assistant` gives the model `ask_user({ need })`; render each `tool-ask_user` message part with `askCard(catalog, state, part)` (null while composing; the card is `part.ui`, `status` `'composing' | 'open' | 'answered' | 'failed' | 'cancelled'`). A part with `result: true` answers it: `PICK: { PARENT: (state, id, next, props) => compose.answer(props, id) }` → the call's output `{ part, answer }` (no result part: SYG686). Tools the app answers itself: `clientTools: { confirm: { description, inputSchema } }`, `openToolCalls(state.assistant)`, `next('assistant.TOOL_OUTPUT', { toolCallId, output })`. Tests: `await t.stream('LLM', [{ toolCall: { id: 'c1', name: 'ask_user', input: { need: 'Pick a plan' } } }])`, then `await composeWith(t, catalog, [{ part: 'plans' }])`.
- **A form from `render` parts**: one host `form()`: `form((state) => schemaOf(state.page.layout), { values: {}, dynamic: (state) => fieldsOf(state.page.layout), submit: 'SEND' })`, where `fieldsOf` maps each placed node key to its part's start value (`{ amount: '', currency: 'USD' }`) and `schemaOf` (memoized per layout: SYG239) to its rules, so only placed fields are required; a part names its fields after its `node` prop (`name={`${node}.amount`}`), so a part can repeat (`amount`, `amount~2`).
